LLVM 24.0.0git
MipsOptimizePICCall.cpp
Go to the documentation of this file.
1//===- MipsOptimizePICCall.cpp - Optimize PIC Calls -----------------------===//
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 pass eliminates unnecessary instructions that set up $gp and replace
10// instructions that load target function addresses with copy instructions.
11//
12//===----------------------------------------------------------------------===//
13
15#include "Mips.h"
16#include "MipsRegisterInfo.h"
17#include "MipsSubtarget.h"
37#include <cassert>
38#include <utility>
39
40using namespace llvm;
41
42#define DEBUG_TYPE "optimize-mips-pic-call"
43
44namespace {
45
47using CntRegP = std::pair<unsigned, unsigned>;
48using AllocatorTy = RecyclingAllocator<BumpPtrAllocator,
50using ScopedHTType = ScopedHashTable<ValueType, CntRegP,
51 DenseMapInfo<ValueType>, AllocatorTy>;
52
53class MBBInfo {
54public:
55 MBBInfo(MachineDomTreeNode *N);
56
57 const MachineDomTreeNode *getNode() const;
58 bool isVisited() const;
59 void preVisit(ScopedHTType &ScopedHT);
60 void postVisit();
61
62private:
64 ScopedHTType::ScopeTy *HTScope;
65};
66
67class OptimizePICCall : public MachineFunctionPass {
68public:
69 OptimizePICCall() : MachineFunctionPass(ID) {}
70
71 StringRef getPassName() const override { return "Mips OptimizePICCall"; }
72
73 bool runOnMachineFunction(MachineFunction &F) override;
74
75 void getAnalysisUsage(AnalysisUsage &AU) const override {
78 }
79
80private:
81 /// Visit MBB.
82 bool visitNode(MBBInfo &MBBI);
83
84 /// Test if MI jumps to a function via a register.
85 ///
86 /// Also, return the virtual register containing the target function's address
87 /// and the underlying object in Reg and Val respectively, if the function's
88 /// address can be resolved lazily.
89 bool isCallViaRegister(MachineInstr &MI, unsigned &Reg,
90 ValueType &Val) const;
91
92 /// Return the number of instructions that dominate the current
93 /// instruction and load the function address from object Entry.
94 unsigned getCount(ValueType Entry);
95
96 /// Return the destination virtual register of the last instruction
97 /// that loads from object Entry.
98 unsigned getReg(ValueType Entry);
99
100 /// Update ScopedHT.
101 void incCntAndSetReg(ValueType Entry, unsigned Reg);
102
103 ScopedHTType ScopedHT;
104
105 static char ID;
106};
107
108} // end of anonymous namespace
109
110char OptimizePICCall::ID = 0;
111
112/// Return the first MachineOperand of MI if it is a used virtual register.
114 if (MI.getNumOperands() == 0)
115 return nullptr;
116
117 MachineOperand &MO = MI.getOperand(0);
118
119 if (!MO.isReg() || !MO.isUse() || !MO.getReg().isVirtual())
120 return nullptr;
121
122 return &MO;
123}
124
125/// Return type of register Reg.
129 assert(TRI.legalclasstypes_end(*RC) - TRI.legalclasstypes_begin(*RC) == 1);
130 return *TRI.legalclasstypes_begin(*RC);
131}
132
133/// Do the following transformation:
134///
135/// jalr $vreg
136/// =>
137/// copy $t9, $vreg
138/// jalr $t9
141 MachineFunction &MF = *MBB->getParent();
143 Register SrcReg = I->getOperand(0).getReg();
144 MCRegister DstReg = MF.getSubtarget<MipsSubtarget>().getABI().getTempReg(
145 9, getRegTy(SrcReg, MF) != MVT::i32);
146 BuildMI(*MBB, I, I->getDebugLoc(), TII.get(TargetOpcode::COPY), DstReg)
147 .addReg(SrcReg);
148 I->getOperand(0).setReg(DstReg);
149}
150
151/// Search MI's operands for register GP and erase it.
152static bool eraseGPOpnd(const MipsOptions &CLOpts, MachineInstr &MI) {
153 if (!CLOpts.erase_gp_opnd)
154 return false;
155
156 MachineFunction &MF = *MI.getParent()->getParent();
157 MVT::SimpleValueType Ty = getRegTy(MI.getOperand(0).getReg(), MF);
158 unsigned Reg = Ty == MVT::i32 ? Mips::GP : Mips::GP_64;
159
160 for (unsigned I = 0; I < MI.getNumOperands(); ++I) {
161 MachineOperand &MO = MI.getOperand(I);
162 if (MO.isReg() && MO.getReg() == Reg) {
163 MI.removeOperand(I);
164 return true;
165 }
166 }
167
168 llvm_unreachable(nullptr);
169}
170
171MBBInfo::MBBInfo(MachineDomTreeNode *N) : Node(N), HTScope(nullptr) {}
172
173const MachineDomTreeNode *MBBInfo::getNode() const { return Node; }
174
175bool MBBInfo::isVisited() const { return HTScope; }
176
177void MBBInfo::preVisit(ScopedHTType &ScopedHT) {
178 HTScope = new ScopedHTType::ScopeTy(ScopedHT);
179}
180
181void MBBInfo::postVisit() {
182 delete HTScope;
183}
184
185// OptimizePICCall methods.
186bool OptimizePICCall::runOnMachineFunction(MachineFunction &F) {
187 if (F.getSubtarget<MipsSubtarget>().inMips16Mode())
188 return false;
189
190 // Do a pre-order traversal of the dominator tree.
191 MachineDominatorTree *MDT =
192 &getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
193 bool Changed = false;
194
195 SmallVector<MBBInfo, 8> WorkList(1, MBBInfo(MDT->getRootNode()));
196
197 while (!WorkList.empty()) {
198 MBBInfo &MBBI = WorkList.back();
199
200 // If this MBB has already been visited, destroy the scope for the MBB and
201 // pop it from the work list.
202 if (MBBI.isVisited()) {
203 MBBI.postVisit();
204 WorkList.pop_back();
205 continue;
206 }
207
208 // Visit the MBB and add its children to the work list.
209 MBBI.preVisit(ScopedHT);
210 Changed |= visitNode(MBBI);
211 const MachineDomTreeNode *Node = MBBI.getNode();
212 WorkList.append(Node->begin(), Node->end());
213 }
214
215 return Changed;
216}
217
218bool OptimizePICCall::visitNode(MBBInfo &MBBI) {
219 bool Changed = false;
220 MachineBasicBlock *MBB = MBBI.getNode()->getBlock();
221 const MipsSubtarget &STI = MBB->getParent()->getSubtarget<MipsSubtarget>();
222 const MipsOptions &CLOpts = STI.getCLOpts();
223 const MipsRegisterInfo &TRI = *STI.getRegisterInfo();
224
225 // Definition of $gp reaching the current instruction.
226 MachineOperand *GPDef = nullptr;
227
228 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
229 ++I) {
230 unsigned Reg;
232
233 // Handle call instructions via registers.
234 if (isCallViaRegister(*I, Reg, Entry)) {
235 Changed = true;
236 unsigned N = getCount(Entry);
237
238 if (N != 0) {
239 // If a function has been called more than twice, we do not have to emit
240 // a load instruction to get the function address from the GOT, but can
241 // instead reuse the address that has been loaded before.
242 if (N >= 2 && !CLOpts.load_target_from_got)
244
245 // Erase the $gp operand if this isn't the first time a function has
246 // been called. $gp needs to be set up only if the function call can go
247 // through a lazy binding stub.
248 if (eraseGPOpnd(CLOpts, *I) && GPDef)
249 GPDef->setIsDead();
250 }
251
252 if (Entry)
253 incCntAndSetReg(Entry, Reg);
254
256 }
257
258 if (MachineOperand *Def = I->findRegisterDefOperand(Mips::GP, &TRI))
259 GPDef = Def;
260 else if (I->readsRegister(Mips::GP, &TRI))
261 GPDef = nullptr;
262 }
263
264 return Changed;
265}
266
267bool OptimizePICCall::isCallViaRegister(MachineInstr &MI, unsigned &Reg,
268 ValueType &Val) const {
269 if (!MI.isCall())
270 return false;
271
272 MachineOperand *MO = getCallTargetRegOpnd(MI);
273
274 // Return if MI is not a function call via a register.
275 if (!MO)
276 return false;
277
278 // Get the instruction that loads the function address from the GOT.
279 Reg = MO->getReg();
280 Val = nullptr;
281 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
282 MachineInstr *DefMI = MRI.getVRegDef(Reg);
283
284 assert(DefMI);
285
286 // See if DefMI is an instruction that loads from a GOT entry that holds the
287 // address of a lazy binding stub.
288 if (!DefMI->mayLoad() || DefMI->getNumOperands() < 3)
289 return true;
290
291 unsigned Flags = DefMI->getOperand(2).getTargetFlags();
292
293 if (Flags != MipsII::MO_GOT_CALL && Flags != MipsII::MO_CALL_LO16)
294 return true;
295
296 // Return the underlying object for the GOT entry in Val.
298 Val = (*DefMI->memoperands_begin())->getValue();
299 if (!Val)
300 Val = (*DefMI->memoperands_begin())->getPseudoValue();
301 return true;
302}
303
304unsigned OptimizePICCall::getCount(ValueType Entry) {
305 return ScopedHT.lookup(Entry).first;
306}
307
308unsigned OptimizePICCall::getReg(ValueType Entry) {
309 unsigned Reg = ScopedHT.lookup(Entry).second;
310 assert(Reg);
311 return Reg;
312}
313
314void OptimizePICCall::incCntAndSetReg(ValueType Entry, unsigned Reg) {
315 CntRegP P = ScopedHT.lookup(Entry);
316 ScopedHT.insert(Entry, std::make_pair(P.first + 1, Reg));
317}
318
319/// Return an OptimizeCall object.
321 return new OptimizePICCall();
322}
MachineInstrBuilder MachineInstrBuilder & DefMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static msgpack::DocNode getNode(msgpack::DocNode DN, msgpack::Type Type, MCValue Val)
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator MBBI
This file defines the BumpPtrAllocator interface.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
ScopedHashTable< Value *, Align, DenseMapInfo< Value * >, BumpPtrAllocator > ScopedHT
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
static MCRegister getReg(const MCDisassembler *D, unsigned RC, unsigned RegNo)
static void setCallTargetReg(MachineBasicBlock *MBB, MachineBasicBlock::iterator I)
Do the following transformation:
static MachineOperand * getCallTargetRegOpnd(MachineInstr &MI)
Return the first MachineOperand of MI if it is a used virtual register.
static MVT::SimpleValueType getRegTy(unsigned Reg, MachineFunction &MF)
Return type of register Reg.
static bool eraseGPOpnd(const MipsOptions &CLOpts, MachineInstr &MI)
Search MI's operands for register GP and erase it.
#define P(N)
This file defines the PointerUnion class, which is a discriminated union of pointer types.
This file defines the SmallVector class.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
DomTreeNodeBase< NodeT > * getRootNode()
getRootNode - This returns the entry node for the CFG of the function.
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
Wrapper class representing physical registers. Should be passed by value.
Definition MCRegister.h:41
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
MachineInstrBundleIterator< MachineInstr > iterator
Analysis pass which computes a MachineDominatorTree.
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.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
Representation of each machine instruction.
unsigned getNumOperands() const
Retuns the total number of operands.
bool mayLoad(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read memory.
bool hasOneMemOperand() const
Return true if this instruction has exactly one MachineMemOperand.
mmo_iterator memoperands_begin() const
Access to memory operands of the instruction.
const MachineOperand & getOperand(unsigned i) const
MachineOperand class - Representation of each machine instruction operand.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
void setIsDead(bool Val=true)
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
unsigned getTargetFlags() const
Register getReg() const
getReg - Returns the register number.
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
LLVM_ABI LLVM_READONLY MachineInstr * getVRegDef(Register Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
const MipsOptions & getCLOpts() const
const MipsRegisterInfo * getRegisterInfo() const override
A discriminated union of two or more pointer types, with the discriminator in the low bits of the poi...
RecyclingAllocator - This class wraps an Allocator, adding the functionality of recycling deleted obj...
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
void insert(const K &Key, const V &Val)
V lookup(const K &Key) const
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
TargetInstrInfo - Interface to description of machine instruction set.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ Entry
Definition COFF.h:862
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
This is an optimization pass for GlobalISel generic memory operations.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
FunctionPass * createMipsOptimizePICCallPass()
Return an OptimizeCall object.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
DomTreeNodeBase< MachineBasicBlock > MachineDomTreeNode
PointerUnion< const Value *, const PseudoSourceValue * > ValueType
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition Allocator.h:391
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
#define N
An information struct used to provide DenseMap with the various necessary components for a given valu...