LLVM 23.0.0git
WebAssemblyPeephole.cpp
Go to the documentation of this file.
1//===-- WebAssemblyPeephole.cpp - WebAssembly Peephole Optimiztions -------===//
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/// Late peephole optimizations for WebAssembly.
11///
12//===----------------------------------------------------------------------===//
13
15#include "WebAssembly.h"
23using namespace llvm;
24
25#define DEBUG_TYPE "wasm-peephole"
26
28 "disable-wasm-fallthrough-return-opt", cl::Hidden,
29 cl::desc("WebAssembly: Disable fallthrough-return optimizations."),
30 cl::init(false));
31
32namespace {
33class WebAssemblyPeephole final : public MachineFunctionPass {
34 StringRef getPassName() const override {
35 return "WebAssembly late peephole optimizer";
36 }
37
38 void getAnalysisUsage(AnalysisUsage &AU) const override {
39 AU.setPreservesCFG();
40 AU.addRequired<TargetLibraryInfoWrapperPass>();
41 AU.addRequired<LibcallLoweringInfoWrapper>();
43 }
44
45 bool runOnMachineFunction(MachineFunction &MF) override;
46
47public:
48 static char ID;
49 WebAssemblyPeephole() : MachineFunctionPass(ID) {}
50};
51} // end anonymous namespace
52
53char WebAssemblyPeephole::ID = 0;
54INITIALIZE_PASS(WebAssemblyPeephole, DEBUG_TYPE,
55 "WebAssembly peephole optimizations", false, false)
56
58 return new WebAssemblyPeephole();
59}
60
61/// If desirable, rewrite NewReg to a drop register.
62static bool maybeRewriteToDrop(unsigned OldReg, unsigned NewReg,
65 bool Changed = false;
66 if (OldReg == NewReg) {
67 Changed = true;
68 Register NewReg = MRI.createVirtualRegister(MRI.getRegClass(OldReg));
69 MO.setReg(NewReg);
70 MO.setIsDead();
71 MFI.stackifyVReg(MRI, NewReg);
72 }
73 return Changed;
74}
75
77 const MachineFunction &MF,
82 return false;
83 if (&MBB != &MF.back())
84 return false;
85
87 --End;
88 assert(End->getOpcode() == WebAssembly::END_FUNCTION);
89 --End;
90 if (&MI != &*End)
91 return false;
92
93 for (auto &MO : MI.explicit_operands()) {
94 // If the operand isn't stackified, insert a COPY to read the operands and
95 // stackify them.
96 Register Reg = MO.getReg();
97 if (!MFI.isVRegStackified(Reg)) {
98 unsigned CopyLocalOpc;
99 const TargetRegisterClass *RegClass = MRI.getRegClass(Reg);
100 CopyLocalOpc = WebAssembly::getCopyOpcodeForRegClass(RegClass);
101 Register NewReg = MRI.createVirtualRegister(RegClass);
102 BuildMI(MBB, MI, MI.getDebugLoc(), TII.get(CopyLocalOpc), NewReg)
103 .addReg(Reg);
104 MO.setReg(NewReg);
105 MFI.stackifyVReg(MRI, NewReg);
106 }
107 }
108
109 MI.setDesc(TII.get(WebAssembly::FALLTHROUGH_RETURN));
110 return true;
111}
112
113bool WebAssemblyPeephole::runOnMachineFunction(MachineFunction &MF) {
114 LLVM_DEBUG({
115 dbgs() << "********** Peephole **********\n"
116 << "********** Function: " << MF.getName() << '\n';
117 });
118
119 MachineRegisterInfo &MRI = MF.getRegInfo();
120 WebAssemblyFunctionInfo &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
121 const WebAssemblySubtarget &Subtarget =
122 MF.getSubtarget<WebAssemblySubtarget>();
123 const auto &TII = *Subtarget.getInstrInfo();
124 auto &LibInfo =
125 getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(MF.getFunction());
126
127 const LibcallLoweringInfo &LibcallLowering =
128 getAnalysis<LibcallLoweringInfoWrapper>().getLibcallLowering(
129 *MF.getFunction().getParent(), Subtarget);
130
131 RTLIB::LibcallImpl MemcpyImpl = LibcallLowering.getLibcallImpl(RTLIB::MEMCPY);
132 RTLIB::LibcallImpl MemmoveImpl =
133 LibcallLowering.getLibcallImpl(RTLIB::MEMMOVE);
134 RTLIB::LibcallImpl MemsetImpl = LibcallLowering.getLibcallImpl(RTLIB::MEMSET);
135
136 StringRef MemcpyName =
138 StringRef MemmoveName =
140 StringRef MemsetName =
142
143 bool Changed = false;
144
145 for (auto &MBB : MF)
146 for (auto &MI : MBB)
147 switch (MI.getOpcode()) {
148 default:
149 break;
150 case WebAssembly::CALL: {
151 MachineOperand &Op1 = MI.getOperand(1);
152 if (Op1.isSymbol()) {
153 StringRef Name(Op1.getSymbolName());
154 if (Name == MemcpyName || Name == MemmoveName || Name == MemsetName) {
155 LibFunc Func;
156 if (LibInfo.getLibFunc(Name, Func)) {
157 const auto &Op2 = MI.getOperand(2);
158 if (!Op2.isReg())
159 report_fatal_error("Peephole: call to builtin function with "
160 "wrong signature, not consuming reg");
161 MachineOperand &MO = MI.getOperand(0);
162 Register OldReg = MO.getReg();
163 Register NewReg = Op2.getReg();
164
165 if (MRI.getRegClass(NewReg) != MRI.getRegClass(OldReg))
166 report_fatal_error("Peephole: call to builtin function with "
167 "wrong signature, from/to mismatch");
168 Changed |= maybeRewriteToDrop(OldReg, NewReg, MO, MFI, MRI);
169 }
170 }
171 }
172 break;
173 }
174 // Optimize away an explicit void return at the end of the function.
175 case WebAssembly::RETURN:
177 break;
178 }
179
180 return Changed;
181}
unsigned const MachineRegisterInfo * MRI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
#define DEBUG_TYPE
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
Register Reg
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
#define LLVM_DEBUG(...)
Definition Debug.h:114
This file provides WebAssembly-specific target descriptions.
This file declares WebAssembly-specific per-machine-function information.
static bool maybeRewriteToDrop(unsigned OldReg, unsigned NewReg, MachineOperand &MO, WebAssemblyFunctionInfo &MFI, MachineRegisterInfo &MRI)
If desirable, rewrite NewReg to a drop register.
static bool maybeRewriteToFallthrough(MachineInstr &MI, MachineBasicBlock &MBB, const MachineFunction &MF, WebAssemblyFunctionInfo &MFI, MachineRegisterInfo &MRI, const WebAssemblyInstrInfo &TII)
static cl::opt< bool > DisableWebAssemblyFallthroughReturnOpt("disable-wasm-fallthrough-return-opt", cl::Hidden, cl::desc("WebAssembly: Disable fallthrough-return optimizations."), cl::init(false))
This file declares the WebAssembly-specific subclass of TargetSubtarget.
This file contains the declaration of the WebAssembly-specific utility functions.
This file contains the entry points for global functions defined in the LLVM WebAssembly back-end.
AnalysisUsage & addRequired()
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:270
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
Module * getParent()
Get the module that this global value is contained inside of...
LLVM_ABI RTLIB::LibcallImpl getLibcallImpl(RTLIB::Libcall Call) const
Return the lowering's selection of implementation call for Call.
MachineInstrBundleIterator< MachineInstr > iterator
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.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
const MachineBasicBlock & back() const
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
const MachineInstrBuilder & addReg(Register RegNo, unsigned Flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
Representation of each machine instruction.
MachineOperand class - Representation of each machine instruction operand.
void setIsDead(bool Val=true)
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
bool isSymbol() const
isSymbol - Tests if this is a MO_ExternalSymbol operand.
const char * getSymbolName() const
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
Wrapper class representing virtual and physical registers.
Definition Register.h:20
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
This class is derived from MachineFunctionInfo and contains private WebAssembly-specific information ...
void stackifyVReg(MachineRegisterInfo &MRI, Register VReg)
Changed
unsigned getCopyOpcodeForRegClass(const TargetRegisterClass *RC)
Returns the appropriate copy opcode for the given register class.
initializer< Ty > init(const Ty &Val)
NodeAddr< FuncNode * > Func
Definition RDFGraph.h:393
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
FunctionPass * createWebAssemblyPeephole()
static StringRef getLibcallImplName(RTLIB::LibcallImpl CallImpl)
Get the libcall routine name for the specified libcall implementation.