blob: 6467d41cc0bf7cfde59e6a09c3b5486e330ddf8d [file] [log] [blame]
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001//===- MemorySSAUpdater.h - Memory SSA Updater-------------------*- C++ -*-===//
2//
Andrew Walbran16937d02019-10-22 13:54:20 +01003// 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
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01006//
7//===----------------------------------------------------------------------===//
8//
9// \file
Andrew Scullcdfcccc2018-10-05 20:58:37 +010010// An automatic updater for MemorySSA that handles arbitrary insertion,
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010011// 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/SmallPtrSet.h"
Andrew Scullcdfcccc2018-10-05 20:58:37 +010035#include "llvm/ADT/SmallSet.h"
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010036#include "llvm/ADT/SmallVector.h"
Andrew Walbran16937d02019-10-22 13:54:20 +010037#include "llvm/Analysis/LoopInfo.h"
Andrew Scull0372a572018-11-16 15:47:06 +000038#include "llvm/Analysis/LoopIterator.h"
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010039#include "llvm/Analysis/MemorySSA.h"
40#include "llvm/IR/BasicBlock.h"
Andrew Scull0372a572018-11-16 15:47:06 +000041#include "llvm/IR/CFGDiff.h"
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010042#include "llvm/IR/Dominators.h"
43#include "llvm/IR/Module.h"
44#include "llvm/IR/OperandTraits.h"
45#include "llvm/IR/Type.h"
46#include "llvm/IR/Use.h"
47#include "llvm/IR/User.h"
48#include "llvm/IR/Value.h"
49#include "llvm/IR/ValueHandle.h"
Andrew Scull0372a572018-11-16 15:47:06 +000050#include "llvm/IR/ValueMap.h"
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010051#include "llvm/Pass.h"
52#include "llvm/Support/Casting.h"
53#include "llvm/Support/ErrorHandling.h"
54
55namespace llvm {
56
57class Function;
58class Instruction;
59class MemoryAccess;
60class LLVMContext;
61class raw_ostream;
62
Andrew Scull0372a572018-11-16 15:47:06 +000063using ValueToValueMapTy = ValueMap<const Value *, WeakTrackingVH>;
64using PhiToDefMap = SmallDenseMap<MemoryPhi *, MemoryAccess *>;
65using CFGUpdate = cfg::Update<BasicBlock *>;
66using GraphDiffInvBBPair =
67 std::pair<const GraphDiff<BasicBlock *> *, Inverse<BasicBlock *>>;
68
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010069class MemorySSAUpdater {
70private:
71 MemorySSA *MSSA;
Andrew Scullcdfcccc2018-10-05 20:58:37 +010072
73 /// We use WeakVH rather than a costly deletion to deal with dangling pointers.
74 /// MemoryPhis are created eagerly and sometimes get zapped shortly afterwards.
75 SmallVector<WeakVH, 16> InsertedPHIs;
76
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010077 SmallPtrSet<BasicBlock *, 8> VisitedBlocks;
Andrew Scullcdfcccc2018-10-05 20:58:37 +010078 SmallSet<AssertingVH<MemoryPhi>, 8> NonOptPhis;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010079
80public:
81 MemorySSAUpdater(MemorySSA *MSSA) : MSSA(MSSA) {}
Andrew Scull0372a572018-11-16 15:47:06 +000082
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010083 /// Insert a definition into the MemorySSA IR. RenameUses will rename any use
84 /// below the new def block (and any inserted phis). RenameUses should be set
85 /// to true if the definition may cause new aliases for loads below it. This
86 /// is not the case for hoisting or sinking or other forms of code *movement*.
87 /// It *is* the case for straight code insertion.
88 /// For example:
89 /// store a
90 /// if (foo) { }
91 /// load a
92 ///
93 /// Moving the store into the if block, and calling insertDef, does not
94 /// require RenameUses.
95 /// However, changing it to:
96 /// store a
97 /// if (foo) { store b }
98 /// load a
99 /// Where a mayalias b, *does* require RenameUses be set to true.
100 void insertDef(MemoryDef *Def, bool RenameUses = false);
101 void insertUse(MemoryUse *Use);
Andrew Scull0372a572018-11-16 15:47:06 +0000102 /// Update the MemoryPhi in `To` following an edge deletion between `From` and
103 /// `To`. If `To` becomes unreachable, a call to removeBlocks should be made.
104 void removeEdge(BasicBlock *From, BasicBlock *To);
105 /// Update the MemoryPhi in `To` to have a single incoming edge from `From`,
106 /// following a CFG change that replaced multiple edges (switch) with a direct
107 /// branch.
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100108 void removeDuplicatePhiEdgesBetween(const BasicBlock *From,
109 const BasicBlock *To);
110 /// Update MemorySSA when inserting a unique backedge block for a loop.
111 void updatePhisWhenInsertingUniqueBackedgeBlock(BasicBlock *LoopHeader,
112 BasicBlock *LoopPreheader,
113 BasicBlock *BackedgeBlock);
Andrew Scull0372a572018-11-16 15:47:06 +0000114 /// Update MemorySSA after a loop was cloned, given the blocks in RPO order,
115 /// the exit blocks and a 1:1 mapping of all blocks and instructions
116 /// cloned. This involves duplicating all defs and uses in the cloned blocks
117 /// Updating phi nodes in exit block successors is done separately.
118 void updateForClonedLoop(const LoopBlocksRPO &LoopBlocks,
119 ArrayRef<BasicBlock *> ExitBlocks,
120 const ValueToValueMapTy &VM,
121 bool IgnoreIncomingWithNoClones = false);
122 // Block BB was fully or partially cloned into its predecessor P1. Map
123 // contains the 1:1 mapping of instructions cloned and VM[BB]=P1.
124 void updateForClonedBlockIntoPred(BasicBlock *BB, BasicBlock *P1,
125 const ValueToValueMapTy &VM);
126 /// Update phi nodes in exit block successors following cloning. Exit blocks
127 /// that were not cloned don't have additional predecessors added.
128 void updateExitBlocksForClonedLoop(ArrayRef<BasicBlock *> ExitBlocks,
129 const ValueToValueMapTy &VMap,
130 DominatorTree &DT);
131 void updateExitBlocksForClonedLoop(
132 ArrayRef<BasicBlock *> ExitBlocks,
133 ArrayRef<std::unique_ptr<ValueToValueMapTy>> VMaps, DominatorTree &DT);
134
135 /// Apply CFG updates, analogous with the DT edge updates.
136 void applyUpdates(ArrayRef<CFGUpdate> Updates, DominatorTree &DT);
137 /// Apply CFG insert updates, analogous with the DT edge updates.
138 void applyInsertUpdates(ArrayRef<CFGUpdate> Updates, DominatorTree &DT);
139
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100140 void moveBefore(MemoryUseOrDef *What, MemoryUseOrDef *Where);
141 void moveAfter(MemoryUseOrDef *What, MemoryUseOrDef *Where);
142 void moveToPlace(MemoryUseOrDef *What, BasicBlock *BB,
143 MemorySSA::InsertionPlace Where);
Andrew Scull0372a572018-11-16 15:47:06 +0000144 /// `From` block was spliced into `From` and `To`. There is a CFG edge from
145 /// `From` to `To`. Move all accesses from `From` to `To` starting at
146 /// instruction `Start`. `To` is newly created BB, so empty of
147 /// MemorySSA::MemoryAccesses. Edges are already updated, so successors of
148 /// `To` with MPhi nodes need to update incoming block.
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100149 /// |------| |------|
150 /// | From | | From |
151 /// | | |------|
152 /// | | ||
153 /// | | => \/
154 /// | | |------| <- Start
155 /// | | | To |
156 /// |------| |------|
157 void moveAllAfterSpliceBlocks(BasicBlock *From, BasicBlock *To,
158 Instruction *Start);
Andrew Scull0372a572018-11-16 15:47:06 +0000159 /// `From` block was merged into `To`. There is a CFG edge from `To` to
160 /// `From`.`To` still branches to `From`, but all instructions were moved and
161 /// `From` is now an empty block; `From` is about to be deleted. Move all
162 /// accesses from `From` to `To` starting at instruction `Start`. `To` may
163 /// have multiple successors, `From` has a single predecessor. `From` may have
164 /// successors with MPhi nodes, replace their incoming block with `To`.
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100165 /// |------| |------|
166 /// | To | | To |
167 /// |------| | |
168 /// || => | |
169 /// \/ | |
170 /// |------| | | <- Start
171 /// | From | | |
172 /// |------| |------|
173 void moveAllAfterMergeBlocks(BasicBlock *From, BasicBlock *To,
174 Instruction *Start);
Andrew Scull0372a572018-11-16 15:47:06 +0000175 /// A new empty BasicBlock (New) now branches directly to Old. Some of
176 /// Old's predecessors (Preds) are now branching to New instead of Old.
177 /// If New is the only predecessor, move Old's Phi, if present, to New.
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100178 /// Otherwise, add a new Phi in New with appropriate incoming values, and
179 /// update the incoming values in Old's Phi node too, if present.
Andrew Scull0372a572018-11-16 15:47:06 +0000180 void wireOldPredecessorsToNewImmediatePredecessor(
181 BasicBlock *Old, BasicBlock *New, ArrayRef<BasicBlock *> Preds,
182 bool IdenticalEdgesWereMerged = true);
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100183 // The below are utility functions. Other than creation of accesses to pass
184 // to insertDef, and removeAccess to remove accesses, you should generally
185 // not attempt to update memoryssa yourself. It is very non-trivial to get
186 // the edge cases right, and the above calls already operate in near-optimal
187 // time bounds.
188
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100189 /// Create a MemoryAccess in MemorySSA at a specified point in a block,
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100190 /// with a specified clobbering definition.
191 ///
192 /// Returns the new MemoryAccess.
193 /// This should be called when a memory instruction is created that is being
194 /// used to replace an existing memory instruction. It will *not* create PHI
195 /// nodes, or verify the clobbering definition. The insertion place is used
196 /// solely to determine where in the memoryssa access lists the instruction
197 /// will be placed. The caller is expected to keep ordering the same as
198 /// instructions.
199 /// It will return the new MemoryAccess.
200 /// Note: If a MemoryAccess already exists for I, this function will make it
201 /// inaccessible and it *must* have removeMemoryAccess called on it.
202 MemoryAccess *createMemoryAccessInBB(Instruction *I, MemoryAccess *Definition,
203 const BasicBlock *BB,
204 MemorySSA::InsertionPlace Point);
205
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100206 /// Create a MemoryAccess in MemorySSA before or after an existing
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100207 /// MemoryAccess.
208 ///
209 /// Returns the new MemoryAccess.
210 /// This should be called when a memory instruction is created that is being
211 /// used to replace an existing memory instruction. It will *not* create PHI
212 /// nodes, or verify the clobbering definition.
213 ///
214 /// Note: If a MemoryAccess already exists for I, this function will make it
215 /// inaccessible and it *must* have removeMemoryAccess called on it.
216 MemoryUseOrDef *createMemoryAccessBefore(Instruction *I,
217 MemoryAccess *Definition,
218 MemoryUseOrDef *InsertPt);
219 MemoryUseOrDef *createMemoryAccessAfter(Instruction *I,
220 MemoryAccess *Definition,
221 MemoryAccess *InsertPt);
222
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100223 /// Remove a MemoryAccess from MemorySSA, including updating all
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100224 /// definitions and uses.
225 /// This should be called when a memory instruction that has a MemoryAccess
226 /// associated with it is erased from the program. For example, if a store or
227 /// load is simply erased (not replaced), removeMemoryAccess should be called
228 /// on the MemoryAccess for that store/load.
Andrew Walbran16937d02019-10-22 13:54:20 +0100229 void removeMemoryAccess(MemoryAccess *, bool OptimizePhis = false);
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100230
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100231 /// Remove MemoryAccess for a given instruction, if a MemoryAccess exists.
232 /// This should be called when an instruction (load/store) is deleted from
233 /// the program.
Andrew Walbran16937d02019-10-22 13:54:20 +0100234 void removeMemoryAccess(const Instruction *I, bool OptimizePhis = false) {
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100235 if (MemoryAccess *MA = MSSA->getMemoryAccess(I))
Andrew Walbran16937d02019-10-22 13:54:20 +0100236 removeMemoryAccess(MA, OptimizePhis);
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100237 }
238
239 /// Remove all MemoryAcceses in a set of BasicBlocks about to be deleted.
240 /// Assumption we make here: all uses of deleted defs and phi must either
241 /// occur in blocks about to be deleted (thus will be deleted as well), or
242 /// they occur in phis that will simply lose an incoming value.
243 /// Deleted blocks still have successor info, but their predecessor edges and
244 /// Phi nodes may already be updated. Instructions in DeadBlocks should be
245 /// deleted after this call.
246 void removeBlocks(const SmallPtrSetImpl<BasicBlock *> &DeadBlocks);
247
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100248 /// Instruction I will be changed to an unreachable. Remove all accesses in
249 /// I's block that follow I (inclusive), and update the Phis in the blocks'
250 /// successors.
251 void changeToUnreachable(const Instruction *I);
252
253 /// Conditional branch BI is changed or replaced with an unconditional branch
254 /// to `To`. Update Phis in BI's successors to remove BI's BB.
255 void changeCondBranchToUnconditionalTo(const BranchInst *BI,
256 const BasicBlock *To);
257
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100258 /// Get handle on MemorySSA.
259 MemorySSA* getMemorySSA() const { return MSSA; }
260
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100261private:
262 // Move What before Where in the MemorySSA IR.
263 template <class WhereType>
264 void moveTo(MemoryUseOrDef *What, BasicBlock *BB, WhereType Where);
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100265 // Move all memory accesses from `From` to `To` starting at `Start`.
266 // Restrictions apply, see public wrappers of this method.
267 void moveAllAccesses(BasicBlock *From, BasicBlock *To, Instruction *Start);
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100268 MemoryAccess *getPreviousDef(MemoryAccess *);
269 MemoryAccess *getPreviousDefInBlock(MemoryAccess *);
270 MemoryAccess *
271 getPreviousDefFromEnd(BasicBlock *,
272 DenseMap<BasicBlock *, TrackingVH<MemoryAccess>> &);
273 MemoryAccess *
274 getPreviousDefRecursive(BasicBlock *,
275 DenseMap<BasicBlock *, TrackingVH<MemoryAccess>> &);
276 MemoryAccess *recursePhi(MemoryAccess *Phi);
277 template <class RangeType>
278 MemoryAccess *tryRemoveTrivialPhi(MemoryPhi *Phi, RangeType &Operands);
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100279 void tryRemoveTrivialPhis(ArrayRef<WeakVH> UpdatedPHIs);
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100280 void fixupDefs(const SmallVectorImpl<WeakVH> &);
Andrew Scull0372a572018-11-16 15:47:06 +0000281 // Clone all uses and defs from BB to NewBB given a 1:1 map of all
282 // instructions and blocks cloned, and a map of MemoryPhi : Definition
283 // (MemoryAccess Phi or Def). VMap maps old instructions to cloned
284 // instructions and old blocks to cloned blocks. MPhiMap, is created in the
285 // caller of this private method, and maps existing MemoryPhis to new
286 // definitions that new MemoryAccesses must point to. These definitions may
287 // not necessarily be MemoryPhis themselves, they may be MemoryDefs. As such,
288 // the map is between MemoryPhis and MemoryAccesses, where the MemoryAccesses
289 // may be MemoryPhis or MemoryDefs and not MemoryUses.
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100290 // If CloneWasSimplified = true, the clone was exact. Otherwise, assume that
291 // the clone involved simplifications that may have: (1) turned a MemoryUse
292 // into an instruction that MemorySSA has no representation for, or (2) turned
293 // a MemoryDef into a MemoryUse or an instruction that MemorySSA has no
294 // representation for. No other cases are supported.
Andrew Scull0372a572018-11-16 15:47:06 +0000295 void cloneUsesAndDefs(BasicBlock *BB, BasicBlock *NewBB,
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100296 const ValueToValueMapTy &VMap, PhiToDefMap &MPhiMap,
297 bool CloneWasSimplified = false);
Andrew Scull0372a572018-11-16 15:47:06 +0000298 template <typename Iter>
299 void privateUpdateExitBlocksForClonedLoop(ArrayRef<BasicBlock *> ExitBlocks,
300 Iter ValuesBegin, Iter ValuesEnd,
301 DominatorTree &DT);
302 void applyInsertUpdates(ArrayRef<CFGUpdate>, DominatorTree &DT,
303 const GraphDiff<BasicBlock *> *GD);
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100304};
305} // end namespace llvm
306
307#endif // LLVM_ANALYSIS_MEMORYSSAUPDATER_H