LLVM 20.0.0git
WebAssemblyDisassembler.cpp
Go to the documentation of this file.
1//==- WebAssemblyDisassembler.cpp - Disassembler for WebAssembly -*- C++ -*-==//
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/// This file is part of the WebAssembly Disassembler.
11///
12/// It contains code to translate the data produced by the decoder into
13/// MCInsts.
14///
15//===----------------------------------------------------------------------===//
16
20#include "llvm/MC/MCContext.h"
22#include "llvm/MC/MCInst.h"
23#include "llvm/MC/MCInstrInfo.h"
25#include "llvm/MC/MCSymbol.h"
29#include "llvm/Support/Endian.h"
30#include "llvm/Support/LEB128.h"
31
32using namespace llvm;
33
34#define DEBUG_TYPE "wasm-disassembler"
35
37
38#include "WebAssemblyGenDisassemblerTables.inc"
39
40namespace {
41static constexpr int WebAssemblyInstructionTableSize = 256;
42
43class WebAssemblyDisassembler final : public MCDisassembler {
44 std::unique_ptr<const MCInstrInfo> MCII;
45
48 raw_ostream &CStream) const override;
49
52 uint64_t Address) const override;
53
54public:
55 WebAssemblyDisassembler(const MCSubtargetInfo &STI, MCContext &Ctx,
56 std::unique_ptr<const MCInstrInfo> MCII)
57 : MCDisassembler(STI, Ctx), MCII(std::move(MCII)) {}
58};
59} // end anonymous namespace
60
62 const MCSubtargetInfo &STI,
63 MCContext &Ctx) {
64 std::unique_ptr<const MCInstrInfo> MCII(T.createMCInstrInfo());
65 return new WebAssemblyDisassembler(STI, Ctx, std::move(MCII));
66}
67
68extern "C" LLVM_EXTERNAL_VISIBILITY void
70 // Register the disassembler for each target.
75}
76
78 if (Size >= Bytes.size())
79 return -1;
80 auto V = Bytes[Size];
81 Size++;
82 return V;
83}
84
85static bool nextLEB(int64_t &Val, ArrayRef<uint8_t> Bytes, uint64_t &Size,
86 bool Signed) {
87 unsigned N = 0;
88 const char *Error = nullptr;
89 Val = Signed ? decodeSLEB128(Bytes.data() + Size, &N,
90 Bytes.data() + Bytes.size(), &Error)
91 : static_cast<int64_t>(decodeULEB128(Bytes.data() + Size, &N,
92 Bytes.data() + Bytes.size(),
93 &Error));
94 if (Error)
95 return false;
96 Size += N;
97 return true;
98}
99
101 ArrayRef<uint8_t> Bytes, bool Signed) {
102 int64_t Val;
103 if (!nextLEB(Val, Bytes, Size, Signed))
104 return false;
105 MI.addOperand(MCOperand::createImm(Val));
106 return true;
107}
108
109template <typename T>
111 if (Size + sizeof(T) > Bytes.size())
112 return false;
113 T Val =
114 support::endian::read<T, llvm::endianness::little>(Bytes.data() + Size);
115 Size += sizeof(T);
116 if (std::is_floating_point<T>::value) {
117 MI.addOperand(
118 MCOperand::createDFPImm(bit_cast<uint64_t>(static_cast<double>(Val))));
119 } else {
120 MI.addOperand(MCOperand::createImm(static_cast<int64_t>(Val)));
121 }
122 return true;
123}
124
125Expected<bool> WebAssemblyDisassembler::onSymbolStart(SymbolInfoTy &Symbol,
126 uint64_t &Size,
127 ArrayRef<uint8_t> Bytes,
128 uint64_t Address) const {
129 Size = 0;
131 // Start of a code section: we're parsing only the function count.
132 int64_t FunctionCount;
133 if (!nextLEB(FunctionCount, Bytes, Size, false))
134 return false;
135 outs() << " # " << FunctionCount << " functions in section.";
136 } else {
137 // Parse the start of a single function.
138 int64_t BodySize, LocalEntryCount;
139 if (!nextLEB(BodySize, Bytes, Size, false) ||
140 !nextLEB(LocalEntryCount, Bytes, Size, false))
141 return false;
142 if (LocalEntryCount) {
143 outs() << " .local ";
144 for (int64_t I = 0; I < LocalEntryCount; I++) {
145 int64_t Count, Type;
146 if (!nextLEB(Count, Bytes, Size, false) ||
147 !nextLEB(Type, Bytes, Size, false))
148 return false;
149 for (int64_t J = 0; J < Count; J++) {
150 if (I || J)
151 outs() << ", ";
153 }
154 }
155 }
156 }
157 outs() << "\n";
158 return true;
159}
160
161MCDisassembler::DecodeStatus WebAssemblyDisassembler::getInstruction(
162 MCInst &MI, uint64_t &Size, ArrayRef<uint8_t> Bytes, uint64_t /*Address*/,
163 raw_ostream &CS) const {
164 CommentStream = &CS;
165 Size = 0;
166 int Opc = nextByte(Bytes, Size);
167 if (Opc < 0)
169 const auto *WasmInst = &InstructionTable0[Opc];
170 // If this is a prefix byte, indirect to another table.
171 if (WasmInst->ET == ET_Prefix) {
172 WasmInst = nullptr;
173 // Linear search, so far only 2 entries.
174 for (auto PT = PrefixTable; PT->Table; PT++) {
175 if (PT->Prefix == Opc) {
176 WasmInst = PT->Table;
177 break;
178 }
179 }
180 if (!WasmInst)
182 int64_t PrefixedOpc;
183 if (!nextLEB(PrefixedOpc, Bytes, Size, false))
185 if (PrefixedOpc < 0 || PrefixedOpc >= WebAssemblyInstructionTableSize)
187 WasmInst += PrefixedOpc;
188 }
189 if (WasmInst->ET == ET_Unused)
191 // At this point we must have a valid instruction to decode.
192 assert(WasmInst->ET == ET_Instruction);
193 MI.setOpcode(WasmInst->Opcode);
194 // Parse any operands.
195 for (uint8_t OPI = 0; OPI < WasmInst->NumOperands; OPI++) {
196 auto OT = OperandTable[WasmInst->OperandStart + OPI];
197 switch (OT) {
198 // ULEB operands:
210 if (!parseLEBImmediate(MI, Size, Bytes, false))
212 break;
213 }
214 // SLEB operands:
217 if (!parseLEBImmediate(MI, Size, Bytes, true))
219 break;
220 }
221 // block_type operands:
223 int64_t Val;
224 uint64_t PrevSize = Size;
225 if (!nextLEB(Val, Bytes, Size, true))
227 if (Val < 0) {
228 // Negative values are single septet value types or empty types
229 if (Size != PrevSize + 1) {
230 MI.addOperand(
231 MCOperand::createImm(int64_t(WebAssembly::BlockType::Invalid)));
232 } else {
233 MI.addOperand(MCOperand::createImm(Val & 0x7f));
234 }
235 } else {
236 // We don't have access to the signature, so create a symbol without one
237 MCSymbol *Sym = getContext().createTempSymbol("typeindex", true);
238 auto *WasmSym = cast<MCSymbolWasm>(Sym);
239 WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
240 const MCExpr *Expr = MCSymbolRefExpr::create(
241 WasmSym, MCSymbolRefExpr::VK_WASM_TYPEINDEX, getContext());
242 MI.addOperand(MCOperand::createExpr(Expr));
243 }
244 break;
245 }
246 // FP operands.
248 if (!parseImmediate<float>(MI, Size, Bytes))
250 break;
251 }
253 if (!parseImmediate<double>(MI, Size, Bytes))
255 break;
256 }
257 // Vector lane operands (not LEB encoded).
259 if (!parseImmediate<uint8_t>(MI, Size, Bytes))
261 break;
262 }
264 if (!parseImmediate<uint16_t>(MI, Size, Bytes))
266 break;
267 }
269 if (!parseImmediate<uint32_t>(MI, Size, Bytes))
271 break;
272 }
274 if (!parseImmediate<uint64_t>(MI, Size, Bytes))
276 break;
277 }
279 int64_t TargetTableLen;
280 if (!nextLEB(TargetTableLen, Bytes, Size, false))
282 for (int64_t I = 0; I < TargetTableLen; I++) {
283 if (!parseLEBImmediate(MI, Size, Bytes, false))
285 }
286 // Default case.
287 if (!parseLEBImmediate(MI, Size, Bytes, false))
289 break;
290 }
292 if (!parseLEBImmediate(MI, Size, Bytes, false))
294 int64_t NumCatches = MI.getOperand(MI.getNumOperands() - 1).getImm();
295 for (int64_t I = 0; I < NumCatches; I++) {
296 if (!parseImmediate<uint8_t>(MI, Size, Bytes))
298 int64_t CatchOpcode = MI.getOperand(MI.getNumOperands() - 1).getImm();
299 if (CatchOpcode == wasm::WASM_OPCODE_CATCH ||
300 CatchOpcode == wasm::WASM_OPCODE_CATCH_REF) {
301 if (!parseLEBImmediate(MI, Size, Bytes, false)) // tag index
303 }
304 if (!parseLEBImmediate(MI, Size, Bytes, false)) // destination
306 }
307 break;
308 }
310 // The tablegen header currently does not have any register operands since
311 // we use only the stack (_S) instructions.
312 // If you hit this that probably means a bad instruction definition in
313 // tablegen.
314 llvm_unreachable("Register operand in WebAssemblyDisassembler");
315 default:
316 llvm_unreachable("Unknown operand type in WebAssemblyDisassembler");
317 }
318 }
320}
#define LLVM_EXTERNAL_VISIBILITY
Definition: Compiler.h:128
uint64_t Size
Symbol * Sym
Definition: ELF_riscv.cpp:479
IRTranslator LLVM IR MI
#define I(x, y, z)
Definition: MD5.cpp:58
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM_EXTERNAL_VISIBILITY void LLVMInitializeWebAssemblyDisassembler()
static int nextByte(ArrayRef< uint8_t > Bytes, uint64_t &Size)
static bool nextLEB(int64_t &Val, ArrayRef< uint8_t > Bytes, uint64_t &Size, bool Signed)
static MCDisassembler * createWebAssemblyDisassembler(const Target &T, const MCSubtargetInfo &STI, MCContext &Ctx)
bool parseImmediate(MCInst &MI, uint64_t &Size, ArrayRef< uint8_t > Bytes)
static bool parseLEBImmediate(MCInst &MI, uint64_t &Size, ArrayRef< uint8_t > Bytes, bool Signed)
This file contains the declaration of the WebAssembly-specific type parsing utility functions.
This file registers the WebAssembly target.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:168
const T * data() const
Definition: ArrayRef.h:165
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
Tagged union holding either a T or a Error.
Definition: Error.h:481
Context object for machine code objects.
Definition: MCContext.h:83
Superclass for all disassemblers.
virtual Expected< bool > onSymbolStart(SymbolInfoTy &Symbol, uint64_t &Size, ArrayRef< uint8_t > Bytes, uint64_t Address) const
Used to perform separate target specific disassembly for a particular symbol.
DecodeStatus
Ternary decode status.
virtual DecodeStatus getInstruction(MCInst &Instr, uint64_t &Size, ArrayRef< uint8_t > Bytes, uint64_t Address, raw_ostream &CStream) const =0
Returns the disassembly of a single instruction.
Base class for the full range of assembler expressions which are needed for parsing.
Definition: MCExpr.h:34
Instances of this class represent a single low-level machine instruction.
Definition: MCInst.h:185
static MCOperand createExpr(const MCExpr *Val)
Definition: MCInst.h:163
static MCOperand createImm(int64_t Val)
Definition: MCInst.h:142
static MCOperand createDFPImm(uint64_t Val)
Definition: MCInst.h:156
Generic base class for all target subtargets.
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx)
Definition: MCExpr.h:398
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:41
Target - Wrapper for Target specific information.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ OPERAND_REGISTER
Definition: MCInstrDesc.h:61
@ OPERAND_IMMEDIATE
Definition: MCInstrDesc.h:60
@ OPERAND_GLOBAL
Global index.
@ OPERAND_CATCH_LIST
A list of catch clauses for try_table.
@ OPERAND_OFFSET64
64-bit unsigned memory offsets.
@ OPERAND_I32IMM
32-bit integer immediates.
@ OPERAND_P2ALIGN
p2align immediate for load and store address alignment.
@ OPERAND_TABLE
32-bit unsigned table number.
@ OPERAND_VEC_I64IMM
64-bit vector lane immediate
@ OPERAND_VEC_I16IMM
16-bit vector lane immediate
@ OPERAND_TYPEINDEX
type signature immediate for call_indirect.
@ OPERAND_FUNCTION32
32-bit unsigned function indices.
@ OPERAND_F32IMM
32-bit floating-point immediates.
@ OPERAND_BASIC_BLOCK
Basic block label in a branch construct.
@ OPERAND_VEC_I32IMM
32-bit vector lane immediate
@ OPERAND_BRLIST
A list of branch targets for br_list.
@ OPERAND_F64IMM
64-bit floating-point immediates.
@ OPERAND_VEC_I8IMM
8-bit vector lane immediate
@ OPERAND_SIGNATURE
signature immediate for block/loop.
@ OPERAND_I64IMM
64-bit integer immediates.
@ OPERAND_OFFSET32
32-bit unsigned memory offsets.
const char * anyTypeToString(unsigned Type)
@ WASM_SYMBOL_TYPE_SECTION
Definition: Wasm.h:219
@ WASM_SYMBOL_TYPE_FUNCTION
Definition: Wasm.h:216
@ WASM_OPCODE_CATCH
Definition: Wasm.h:149
@ WASM_OPCODE_CATCH_REF
Definition: Wasm.h:150
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
raw_fd_ostream & outs()
This returns a reference to a raw_fd_ostream for standard output.
uint64_t decodeULEB128(const uint8_t *p, unsigned *n=nullptr, const uint8_t *end=nullptr, const char **error=nullptr)
Utility function to decode a ULEB128 value.
Definition: LEB128.h:131
int64_t decodeSLEB128(const uint8_t *p, unsigned *n=nullptr, const uint8_t *end=nullptr, const char **error=nullptr)
Utility function to decode a SLEB128 value.
Definition: LEB128.h:165
Target & getTheWebAssemblyTarget32()
Target & getTheWebAssemblyTarget64()
#define N
static void RegisterMCDisassembler(Target &T, Target::MCDisassemblerCtorTy Fn)
RegisterMCDisassembler - Register a MCDisassembler implementation for the given target.