LLVM 24.0.0git
MachineLateInstrsCleanup.cpp
Go to the documentation of this file.
1//==--- MachineLateInstrsCleanup.cpp - Late Instructions Cleanup Pass -----===//
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// This simple pass removes any identical and redundant immediate or address
10// loads to the same register. The immediate loads removed can originally be
11// the result of rematerialization, while the addresses are redundant frame
12// addressing anchor points created during Frame Indices elimination.
13//
14//===----------------------------------------------------------------------===//
15
17#include "llvm/ADT/BitVector.h"
19#include "llvm/ADT/Statistic.h"
28#include "llvm/Pass.h"
29#include "llvm/Support/Debug.h"
30
31using namespace llvm;
32
33#define DEBUG_TYPE "machine-latecleanup"
34
35STATISTIC(NumRemoved, "Number of redundant instructions removed.");
36
37namespace {
38
39class MachineLateInstrsCleanup {
40 const TargetRegisterInfo *TRI = nullptr;
41
42 // Data structures to map regs to their definitions and kills per MBB.
43 struct Reg2MIMap : public SmallDenseMap<Register, MachineInstr *> {
44 bool hasIdentical(Register Reg, MachineInstr *ArgMI) {
46 return MI && MI->isIdenticalTo(*ArgMI);
47 }
48 };
49 typedef SmallDenseMap<Register, TinyPtrVector<MachineInstr *>> Reg2MIVecMap;
50 std::vector<Reg2MIMap> RegDefs;
51 std::vector<Reg2MIVecMap> RegKills;
52
53 // Walk through the instructions in MBB and remove any redundant
54 // instructions.
55 bool processBlock(MachineBasicBlock *MBB);
56
57 void removeRedundantDef(MachineInstr *MI);
58 void clearKillsForDef(Register Reg, MachineBasicBlock *MBB,
59 BitVector &VisitedPreds, MachineInstr *ToRemoveMI);
60
61public:
62 bool run(MachineFunction &MF);
63};
64
65class MachineLateInstrsCleanupLegacy : public MachineFunctionPass {
66public:
67 static char ID; // Pass identification, replacement for typeid
68
69 MachineLateInstrsCleanupLegacy() : MachineFunctionPass(ID) {}
70
71 void getAnalysisUsage(AnalysisUsage &AU) const override {
72 AU.setPreservesCFG();
74 }
75
76 bool runOnMachineFunction(MachineFunction &MF) override;
77
78 MachineFunctionProperties getRequiredProperties() const override {
79 return MachineFunctionProperties().setNoVRegs();
80 }
81};
82
83} // end anonymous namespace
84
85char MachineLateInstrsCleanupLegacy::ID = 0;
86
87char &llvm::MachineLateInstrsCleanupID = MachineLateInstrsCleanupLegacy::ID;
88
89INITIALIZE_PASS(MachineLateInstrsCleanupLegacy, DEBUG_TYPE,
90 "Machine Late Instructions Cleanup Pass", false, false)
91
92bool MachineLateInstrsCleanupLegacy::runOnMachineFunction(MachineFunction &MF) {
93 if (skipFunction(MF.getFunction()))
94 return false;
95
96 return MachineLateInstrsCleanup().run(MF);
97}
98
102 MFPropsModifier _(*this, MF);
103 if (!MachineLateInstrsCleanup().run(MF))
104 return PreservedAnalyses::all();
106 PA.preserveSet<CFGAnalyses>();
107 return PA;
108}
109
110bool MachineLateInstrsCleanup::run(MachineFunction &MF) {
112
113 RegDefs.clear();
114 RegDefs.resize(MF.getNumBlockIDs());
115 RegKills.clear();
116 RegKills.resize(MF.getNumBlockIDs());
117
118 // Visit all MBBs in an order that maximises the reuse from predecessors.
119 bool Changed = false;
121 for (MachineBasicBlock *MBB : RPOT)
123
124 return Changed;
125}
126
127// Clear any preceding kill flag on Reg after removing a redundant
128// definition.
129void MachineLateInstrsCleanup::clearKillsForDef(Register Reg,
131 BitVector &VisitedPreds,
132 MachineInstr *ToRemoveMI) {
133 VisitedPreds.set(MBB->getNumber());
134
135 // Clear kill flag(s) in MBB, that have been seen after the preceding
136 // definition. If Reg or one of its subregs was killed, it would actually
137 // be ok to stop after removing that (and any other) kill-flag, but it
138 // doesn't seem noticeably faster while it would be a bit more complicated.
139 Reg2MIVecMap &MBBKills = RegKills[MBB->getNumber()];
140 if (auto Kills = MBBKills.find(Reg); Kills != MBBKills.end())
141 for (auto *KillMI : Kills->second)
142 KillMI->clearRegisterKills(Reg, TRI);
143
144 // Definition in current MBB: done.
145 Reg2MIMap &MBBDefs = RegDefs[MBB->getNumber()];
146 MachineInstr *DefMI = MBBDefs[Reg];
147 assert(DefMI->isIdenticalTo(*ToRemoveMI) && "Previous def not identical?");
148 if (DefMI->getParent() == MBB)
149 return;
150
151 // If an earlier def is not in MBB, continue in predecessors.
152 if (!MBB->isLiveIn(Reg))
153 MBB->addLiveIn(Reg);
154 assert(!MBB->pred_empty() && "Predecessor def not found!");
155 for (MachineBasicBlock *Pred : MBB->predecessors())
156 if (!VisitedPreds.test(Pred->getNumber()))
157 clearKillsForDef(Reg, Pred, VisitedPreds, ToRemoveMI);
158}
159
160void MachineLateInstrsCleanup::removeRedundantDef(MachineInstr *MI) {
161 Register Reg = MI->getOperand(0).getReg();
162 BitVector VisitedPreds(MI->getMF()->getNumBlockIDs());
163 clearKillsForDef(Reg, MI->getParent(), VisitedPreds, MI);
164 MI->eraseFromParent();
165 ++NumRemoved;
166}
167
168// Return true if MI is a potential candidate for reuse/removal and if so
169// also the register it defines in DefedReg. A candidate is a simple
170// instruction that does not touch memory, has only one register definition
171// and the only reg it may use is FrameReg. Typically this is an immediate
172// load or a load-address instruction.
173static bool isCandidate(const MachineInstr *MI, Register &DefedReg,
174 Register FrameReg) {
175 DefedReg = MCRegister::NoRegister;
176 bool SawStore = true;
177 if (!MI->isSafeToMove(SawStore) || MI->isImplicitDef() || MI->isInlineAsm())
178 return false;
179 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
180 const MachineOperand &MO = MI->getOperand(i);
181 if (MO.isReg()) {
182 if (MO.isDef()) {
183 if (i == 0 && !MO.isImplicit() && !MO.isDead())
184 DefedReg = MO.getReg();
185 else
186 return false;
187 } else if (MO.getReg() && MO.getReg() != FrameReg)
188 return false;
189 } else if (!(MO.isImm() || MO.isCImm() || MO.isFPImm() || MO.isCPI() ||
190 MO.isGlobal() || MO.isSymbol()))
191 return false;
192 }
193 return DefedReg.isValid();
194}
195
196bool MachineLateInstrsCleanup::processBlock(MachineBasicBlock *MBB) {
197 bool Changed = false;
198 Reg2MIMap &MBBDefs = RegDefs[MBB->getNumber()];
199 Reg2MIVecMap &MBBKills = RegKills[MBB->getNumber()];
200
201 // Find reusable definitions in the predecessor(s).
202 if (!MBB->pred_empty() && !MBB->isEHPad() &&
204 MachineBasicBlock *FirstPred = *MBB->pred_begin();
205 for (auto [Reg, DefMI] : RegDefs[FirstPred->getNumber()])
206 if (llvm::all_of(
208 [&, &Reg = Reg, &DefMI = DefMI](const MachineBasicBlock *Pred) {
209 return RegDefs[Pred->getNumber()].hasIdentical(Reg, DefMI);
210 })) {
211 MBBDefs[Reg] = DefMI;
212 LLVM_DEBUG(dbgs() << "Reusable instruction from pred(s): in "
213 << printMBBReference(*MBB) << ": " << *DefMI);
214 }
215 }
216
217 // Process MBB.
220 Register FrameReg = TRI->getFrameRegister(*MF);
222 // If FrameReg is modified, no previous load-address instructions (using
223 // it) are valid.
224 if (MI.modifiesRegister(FrameReg, TRI)) {
225 MBBDefs.clear();
226 MBBKills.clear();
227 continue;
228 }
229
230 Register DefedReg;
231 bool IsCandidate = isCandidate(&MI, DefedReg, FrameReg);
232
233 // Check for an earlier identical and reusable instruction.
234 if (IsCandidate && MBBDefs.hasIdentical(DefedReg, &MI)) {
235 LLVM_DEBUG(dbgs() << "Removing redundant instruction in "
236 << printMBBReference(*MBB) << ": " << MI);
237 removeRedundantDef(&MI);
238 Changed = true;
239 continue;
240 }
241
242 // Clear any entries in map that MI clobbers.
243 MBBDefs.remove_if([&](const auto &Entry) {
244 Register Reg = Entry.first;
245 if (MI.modifiesRegister(Reg, TRI)) {
246 MBBKills.erase(Reg);
247 return true;
248 }
249 if (MI.findRegisterUseOperandIdx(Reg, TRI, true /*isKill*/) != -1)
250 // Keep track of all instructions that fully or partially kills Reg.
251 MBBKills[Reg].push_back(&MI);
252 return false;
253 });
254
255 // Record this MI for potential later reuse.
256 if (IsCandidate) {
257 LLVM_DEBUG(dbgs() << "Found interesting instruction in "
258 << printMBBReference(*MBB) << ": " << MI);
259 MBBDefs[DefedReg] = &MI;
260 assert(!MBBKills.count(DefedReg) && "Should already have been removed.");
261 }
262 }
263
264 return Changed;
265}
MachineInstrBuilder MachineInstrBuilder & DefMI
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
This file implements the BitVector class.
#define DEBUG_TYPE
#define _
IRTranslator LLVM IR MI
static bool lookup(const GsymReader &GR, GsymDataExtractor &Data, uint64_t &Offset, uint64_t BaseAddr, uint64_t Addr, SourceLocations &SrcLocs, llvm::Error &Err)
A Lookup helper functions.
static bool isCandidate(const MachineInstr *MI, Register &DefedReg, Register FrameReg)
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
static bool processBlock(MachineBasicBlock &MBB, const SystemZInstrInfo *TII, const TargetRegisterInfo *TRI)
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:280
bool test(unsigned Idx) const
Returns true if bit Idx is set.
Definition BitVector.h:483
BitVector & set()
Set all bits in the bitvector.
Definition BitVector.h:367
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
static constexpr unsigned NoRegister
Definition MCRegister.h:60
An RAII based helper class to modify MachineFunctionProperties when running pass.
bool isInlineAsmBrIndirectTarget() const
Returns true if this is the indirect dest of an INLINEASM_BR.
bool isEHPad() const
Returns true if the block is a landing pad.
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
iterator_range< pred_iterator > predecessors()
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
unsigned getNumBlockIDs() const
getNumBlockIDs - Return the number of MBB ID's allocated.
Representation of each machine instruction.
LLVM_ABI PreservedAnalyses run(MachineFunction &MachineFunction, MachineFunctionAnalysisManager &MachineFunctionAM)
MachineOperand class - Representation of each machine instruction operand.
bool isCImm() const
isCImm - Test if this is a MO_CImmediate operand.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
bool isCPI() const
isCPI - Tests if this is a MO_ConstantPoolIndex operand.
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
bool isSymbol() const
isSymbol - Tests if this is a MO_ExternalSymbol operand.
bool isGlobal() const
isGlobal - Tests if this is a MO_GlobalAddress operand.
Register getReg() const
getReg - Returns the register number.
bool isFPImm() const
isFPImm - Tests if this is a MO_FPImmediate operand.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isValid() const
Definition Register.h:112
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
@ Entry
Definition COFF.h:862
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
LLVM_ABI char & MachineLateInstrsCleanupID
MachineLateInstrsCleanup - This pass removes redundant identical instructions after register allocati...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.