LLVM 24.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"
26#include "llvm/IR/Analysis.h"
28using namespace llvm;
29
30#define DEBUG_TYPE "wasm-peephole"
31
33 "disable-wasm-fallthrough-return-opt", cl::Hidden,
34 cl::desc("WebAssembly: Disable fallthrough-return optimizations."),
35 cl::init(false));
36
37namespace {
38class WebAssemblyPeepholeLegacy final : public MachineFunctionPass {
39 StringRef getPassName() const override {
40 return "WebAssembly late peephole optimizer";
41 }
42
43 void getAnalysisUsage(AnalysisUsage &AU) const override {
44 AU.setPreservesCFG();
45 AU.addRequired<TargetLibraryInfoWrapperPass>();
46 AU.addRequired<LibcallLoweringInfoWrapper>();
48 }
49
50 bool runOnMachineFunction(MachineFunction &MF) override;
51
52public:
53 static char ID;
54 WebAssemblyPeepholeLegacy() : MachineFunctionPass(ID) {}
55};
56} // end anonymous namespace
57
58char WebAssemblyPeepholeLegacy::ID = 0;
59INITIALIZE_PASS(WebAssemblyPeepholeLegacy, DEBUG_TYPE,
60 "WebAssembly peephole optimizations", false, false)
61
63 return new WebAssemblyPeepholeLegacy();
64}
65
66/// If desirable, rewrite NewReg to a drop register.
67static bool maybeRewriteToDrop(unsigned OldReg, unsigned NewReg,
70 bool Changed = false;
71 if (OldReg == NewReg) {
72 Changed = true;
73 Register NewReg = MRI.createVirtualRegister(MRI.getRegClass(OldReg));
74 MO.setReg(NewReg);
75 MO.setIsDead();
76 MFI.stackifyVReg(MRI, NewReg);
77 }
78 return Changed;
79}
80
82 const MachineFunction &MF,
87 return false;
88 if (&MBB != &MF.back())
89 return false;
90
92 --End;
93 assert(End->getOpcode() == WebAssembly::END_FUNCTION);
94 --End;
95 if (&MI != &*End)
96 return false;
97
98 for (auto &MO : MI.explicit_operands()) {
99 // If the operand isn't stackified, insert a COPY to read the operands and
100 // stackify them.
101 Register Reg = MO.getReg();
102 if (!MFI.isVRegStackified(Reg)) {
103 unsigned CopyLocalOpc;
104 const TargetRegisterClass *RegClass = MRI.getRegClass(Reg);
105 CopyLocalOpc = WebAssembly::getCopyOpcodeForRegClass(RegClass);
106 Register NewReg = MRI.createVirtualRegister(RegClass);
107 BuildMI(MBB, MI, MI.getDebugLoc(), TII.get(CopyLocalOpc), NewReg)
108 .addReg(Reg);
109 MO.setReg(NewReg);
110 MFI.stackifyVReg(MRI, NewReg);
111 }
112 }
113
114 MI.setDesc(TII.get(WebAssembly::FALLTHROUGH_RETURN));
115 return true;
116}
117
119 const LibcallLoweringInfo &LibcallLowering) {
120 LLVM_DEBUG({
121 dbgs() << "********** Peephole **********\n"
122 << "********** Function: " << MF.getName() << '\n';
123 });
124
127 const WebAssemblySubtarget &Subtarget =
129 const auto &TII = *Subtarget.getInstrInfo();
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 if (LibInfo.getLibFunc(Name) != NotLibFunc) {
156 const auto &Op2 = MI.getOperand(2);
157 if (!Op2.isReg())
158 report_fatal_error("Peephole: call to builtin function with "
159 "wrong signature, not consuming reg");
160 MachineOperand &MO = MI.getOperand(0);
161 Register OldReg = MO.getReg();
162 Register NewReg = Op2.getReg();
163
164 if (MRI.getRegClass(NewReg) != MRI.getRegClass(OldReg))
165 report_fatal_error("Peephole: call to builtin function with "
166 "wrong signature, from/to mismatch");
167 Changed |= maybeRewriteToDrop(OldReg, NewReg, MO, MFI, MRI);
168 }
169 }
170 }
171 break;
172 }
173 // Optimize away an explicit void return at the end of the function.
174 case WebAssembly::RETURN:
175 Changed |= maybeRewriteToFallthrough(MI, MBB, MF, MFI, MRI, TII);
176 break;
177 }
178
179 return Changed;
180}
181
182bool WebAssemblyPeepholeLegacy::runOnMachineFunction(MachineFunction &MF) {
183 TargetLibraryInfo &LibInfo =
184 getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(MF.getFunction());
185 const WebAssemblySubtarget &Subtarget =
186 MF.getSubtarget<WebAssemblySubtarget>();
187 const LibcallLoweringInfo &LibcallLowering =
188 getAnalysis<LibcallLoweringInfoWrapper>().getLibcallLowering(
189 *MF.getFunction().getParent(), Subtarget);
190 return peephole(MF, LibInfo, LibcallLowering);
191}
192
193PreservedAnalyses
196 TargetLibraryInfo &LibInfo =
198 .getManager()
199 .getResult<TargetLibraryAnalysis>(MF.getFunction());
200 const WebAssemblySubtarget &Subtarget =
202 const LibcallLoweringInfo &LibcallLowering = getLibcallLowering(
204 .getCachedResult<LibcallLoweringModuleAnalysis>(
205 *MF.getFunction().getParent()),
206 Subtarget);
207 return peephole(MF, LibInfo, LibcallLowering)
211}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
#define DEBUG_TYPE
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
Register Reg
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
#define LLVM_DEBUG(...)
Definition Debug.h:119
This file provides WebAssembly-specific target descriptions.
This file declares WebAssembly-specific per-machine-function information.
static bool peephole(MachineFunction &MF, TargetLibraryInfo &LibInfo, const LibcallLoweringInfo &LibcallLowering)
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.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
AnalysisUsage & addRequired()
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:275
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
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...
Tracks which library functions to use for a particular subtarget or function.
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, RegState Flags={}, 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,...
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
Wrapper class representing virtual and physical registers.
Definition Register.h:20
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
LibFunc getLibFunc(StringRef funcName) const
Searches for a particular function name.
This class is derived from MachineFunctionInfo and contains private WebAssembly-specific information ...
void stackifyVReg(MachineRegisterInfo &MRI, Register VReg)
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
Changed
Pass manager infrastructure for declaring and invalidating analyses.
unsigned getCopyOpcodeForRegClass(const TargetRegisterClass *RC)
Returns the appropriate copy opcode for the given register class.
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
OuterAnalysisManagerProxy< ModuleAnalysisManager, MachineFunction > ModuleAnalysisManagerMachineFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
LLVM_ABI const LibcallLoweringInfo & getLibcallLowering(const ModuleLibcallLoweringInfo &ModuleInfo, const TargetSubtargetInfo &Subtarget)
Resolve the LibcallLoweringInfo for Subtarget from the module-level ModuleInfo, applying the subtarge...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
FunctionPass * createWebAssemblyPeepholeLegacyPass()
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
static StringRef getLibcallImplName(RTLIB::LibcallImpl CallImpl)
Get the libcall routine name for the specified libcall implementation.