LLVM  14.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 
19 #include "llvm/MC/MCContext.h"
22 #include "llvm/MC/MCInst.h"
23 #include "llvm/MC/MCInstrInfo.h"
25 #include "llvm/MC/MCSymbol.h"
26 #include "llvm/MC/MCSymbolWasm.h"
27 #include "llvm/Support/Endian.h"
28 #include "llvm/Support/LEB128.h"
30 
31 using namespace llvm;
32 
33 #define DEBUG_TYPE "wasm-disassembler"
34 
36 
37 #include "WebAssemblyGenDisassemblerTables.inc"
38 
39 namespace {
40 static constexpr int WebAssemblyInstructionTableSize = 256;
41 
42 class WebAssemblyDisassembler final : public MCDisassembler {
43  std::unique_ptr<const MCInstrInfo> MCII;
44 
45  DecodeStatus getInstruction(MCInst &Instr, uint64_t &Size,
46  ArrayRef<uint8_t> Bytes, uint64_t Address,
47  raw_ostream &CStream) const override;
48  Optional<DecodeStatus> onSymbolStart(SymbolInfoTy &Symbol, uint64_t &Size,
49  ArrayRef<uint8_t> Bytes,
50  uint64_t Address,
51  raw_ostream &CStream) const override;
52 
53 public:
54  WebAssemblyDisassembler(const MCSubtargetInfo &STI, MCContext &Ctx,
55  std::unique_ptr<const MCInstrInfo> MCII)
56  : MCDisassembler(STI, Ctx), MCII(std::move(MCII)) {}
57 };
58 } // end anonymous namespace
59 
61  const MCSubtargetInfo &STI,
62  MCContext &Ctx) {
63  std::unique_ptr<const MCInstrInfo> MCII(T.createMCInstrInfo());
64  return new WebAssemblyDisassembler(STI, Ctx, std::move(MCII));
65 }
66 
67 extern "C" LLVM_EXTERNAL_VISIBILITY void
69  // Register the disassembler for each target.
74 }
75 
76 static int nextByte(ArrayRef<uint8_t> Bytes, uint64_t &Size) {
77  if (Size >= Bytes.size())
78  return -1;
79  auto V = Bytes[Size];
80  Size++;
81  return V;
82 }
83 
84 static bool nextLEB(int64_t &Val, ArrayRef<uint8_t> Bytes, uint64_t &Size,
85  bool Signed) {
86  unsigned N = 0;
87  const char *Error = nullptr;
88  Val = Signed ? decodeSLEB128(Bytes.data() + Size, &N,
89  Bytes.data() + Bytes.size(), &Error)
90  : static_cast<int64_t>(decodeULEB128(Bytes.data() + Size, &N,
91  Bytes.data() + Bytes.size(),
92  &Error));
93  if (Error)
94  return false;
95  Size += N;
96  return true;
97 }
98 
99 static bool parseLEBImmediate(MCInst &MI, uint64_t &Size,
100  ArrayRef<uint8_t> Bytes, bool Signed) {
101  int64_t Val;
102  if (!nextLEB(Val, Bytes, Size, Signed))
103  return false;
104  MI.addOperand(MCOperand::createImm(Val));
105  return true;
106 }
107 
108 template <typename T>
109 bool parseImmediate(MCInst &MI, uint64_t &Size, ArrayRef<uint8_t> Bytes) {
110  if (Size + sizeof(T) > Bytes.size())
111  return false;
112  T Val = support::endian::read<T, support::endianness::little, 1>(
113  Bytes.data() + Size);
114  Size += sizeof(T);
115  if (std::is_floating_point<T>::value) {
116  MI.addOperand(
117  MCOperand::createDFPImm(bit_cast<uint64_t>(static_cast<double>(Val))));
118  } else {
119  MI.addOperand(MCOperand::createImm(static_cast<int64_t>(Val)));
120  }
121  return true;
122 }
123 
124 Optional<MCDisassembler::DecodeStatus> WebAssemblyDisassembler::onSymbolStart(
125  SymbolInfoTy &Symbol, uint64_t &Size, ArrayRef<uint8_t> Bytes,
126  uint64_t Address, raw_ostream &CStream) const {
127  Size = 0;
128  if (Address == 0) {
129  // Start of a code section: we're parsing only the function count.
130  int64_t FunctionCount;
131  if (!nextLEB(FunctionCount, Bytes, Size, false))
132  return None;
133  outs() << " # " << FunctionCount << " functions in section.";
134  } else {
135  // Parse the start of a single function.
136  int64_t BodySize, LocalEntryCount;
137  if (!nextLEB(BodySize, Bytes, Size, false) ||
138  !nextLEB(LocalEntryCount, Bytes, Size, false))
139  return None;
140  if (LocalEntryCount) {
141  outs() << " .local ";
142  for (int64_t I = 0; I < LocalEntryCount; I++) {
143  int64_t Count, Type;
144  if (!nextLEB(Count, Bytes, Size, false) ||
145  !nextLEB(Type, Bytes, Size, false))
146  return None;
147  for (int64_t J = 0; J < Count; J++) {
148  if (I || J)
149  outs() << ", ";
151  }
152  }
153  }
154  }
155  outs() << "\n";
157 }
158 
159 MCDisassembler::DecodeStatus WebAssemblyDisassembler::getInstruction(
160  MCInst &MI, uint64_t &Size, ArrayRef<uint8_t> Bytes, uint64_t /*Address*/,
161  raw_ostream &CS) const {
162  CommentStream = &CS;
163  Size = 0;
164  int Opc = nextByte(Bytes, Size);
165  if (Opc < 0)
166  return MCDisassembler::Fail;
167  const auto *WasmInst = &InstructionTable0[Opc];
168  // If this is a prefix byte, indirect to another table.
169  if (WasmInst->ET == ET_Prefix) {
170  WasmInst = nullptr;
171  // Linear search, so far only 2 entries.
172  for (auto PT = PrefixTable; PT->Table; PT++) {
173  if (PT->Prefix == Opc) {
174  WasmInst = PT->Table;
175  break;
176  }
177  }
178  if (!WasmInst)
179  return MCDisassembler::Fail;
180  int64_t PrefixedOpc;
181  if (!nextLEB(PrefixedOpc, Bytes, Size, false))
182  return MCDisassembler::Fail;
183  if (PrefixedOpc < 0 || PrefixedOpc >= WebAssemblyInstructionTableSize)
184  return MCDisassembler::Fail;
185  WasmInst += PrefixedOpc;
186  }
187  if (WasmInst->ET == ET_Unused)
188  return MCDisassembler::Fail;
189  // At this point we must have a valid instruction to decode.
190  assert(WasmInst->ET == ET_Instruction);
191  MI.setOpcode(WasmInst->Opcode);
192  // Parse any operands.
193  for (uint8_t OPI = 0; OPI < WasmInst->NumOperands; OPI++) {
194  auto OT = OperandTable[WasmInst->OperandStart + OPI];
195  switch (OT) {
196  // ULEB operands:
208  if (!parseLEBImmediate(MI, Size, Bytes, false))
209  return MCDisassembler::Fail;
210  break;
211  }
212  // SLEB operands:
215  if (!parseLEBImmediate(MI, Size, Bytes, true))
216  return MCDisassembler::Fail;
217  break;
218  }
219  // block_type operands:
221  int64_t Val;
222  uint64_t PrevSize = Size;
223  if (!nextLEB(Val, Bytes, Size, true))
224  return MCDisassembler::Fail;
225  if (Val < 0) {
226  // Negative values are single septet value types or empty types
227  if (Size != PrevSize + 1) {
228  MI.addOperand(
230  } else {
231  MI.addOperand(MCOperand::createImm(Val & 0x7f));
232  }
233  } else {
234  // We don't have access to the signature, so create a symbol without one
235  MCSymbol *Sym = getContext().createTempSymbol("typeindex", true);
236  auto *WasmSym = cast<MCSymbolWasm>(Sym);
237  WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
238  const MCExpr *Expr = MCSymbolRefExpr::create(
239  WasmSym, MCSymbolRefExpr::VK_WASM_TYPEINDEX, getContext());
240  MI.addOperand(MCOperand::createExpr(Expr));
241  }
242  break;
243  }
244  // heap_type operands, for e.g. ref.null:
246  int64_t Val;
247  uint64_t PrevSize = Size;
248  if (!nextLEB(Val, Bytes, Size, true))
249  return MCDisassembler::Fail;
250  if (Val < 0 && Size == PrevSize + 1) {
251  // The HeapType encoding is like BlockType, in that encodings that
252  // decode as negative values indicate ValTypes. In practice we expect
253  // either wasm::ValType::EXTERNREF or wasm::ValType::FUNCREF here.
254  //
255  // The positive SLEB values are reserved for future expansion and are
256  // expected to be type indices in the typed function references
257  // proposal, and should disassemble as MCSymbolRefExpr as in BlockType
258  // above.
259  MI.addOperand(MCOperand::createImm(Val & 0x7f));
260  } else {
261  MI.addOperand(
263  }
264  break;
265  }
266  // FP operands.
268  if (!parseImmediate<float>(MI, Size, Bytes))
269  return MCDisassembler::Fail;
270  break;
271  }
273  if (!parseImmediate<double>(MI, Size, Bytes))
274  return MCDisassembler::Fail;
275  break;
276  }
277  // Vector lane operands (not LEB encoded).
279  if (!parseImmediate<uint8_t>(MI, Size, Bytes))
280  return MCDisassembler::Fail;
281  break;
282  }
284  if (!parseImmediate<uint16_t>(MI, Size, Bytes))
285  return MCDisassembler::Fail;
286  break;
287  }
289  if (!parseImmediate<uint32_t>(MI, Size, Bytes))
290  return MCDisassembler::Fail;
291  break;
292  }
294  if (!parseImmediate<uint64_t>(MI, Size, Bytes))
295  return MCDisassembler::Fail;
296  break;
297  }
299  int64_t TargetTableLen;
300  if (!nextLEB(TargetTableLen, Bytes, Size, false))
301  return MCDisassembler::Fail;
302  for (int64_t I = 0; I < TargetTableLen; I++) {
303  if (!parseLEBImmediate(MI, Size, Bytes, false))
304  return MCDisassembler::Fail;
305  }
306  // Default case.
307  if (!parseLEBImmediate(MI, Size, Bytes, false))
308  return MCDisassembler::Fail;
309  break;
310  }
312  // The tablegen header currently does not have any register operands since
313  // we use only the stack (_S) instructions.
314  // If you hit this that probably means a bad instruction definition in
315  // tablegen.
316  llvm_unreachable("Register operand in WebAssemblyDisassembler");
317  default:
318  llvm_unreachable("Unknown operand type in WebAssemblyDisassembler");
319  }
320  }
322 }
llvm::Check::Size
@ Size
Definition: FileCheck.h:73
MCFixedLenDisassembler.h
Signed
@ Signed
Definition: NVPTXISelLowering.cpp:4630
MI
IRTranslator LLVM IR MI
Definition: IRTranslator.cpp:102
llvm
---------------------— PointerInfo ------------------------------------—
Definition: AllocatorList.h:23
llvm::MCSymbol
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:41
llvm::WebAssembly::OPERAND_HEAPTYPE
@ OPERAND_HEAPTYPE
heap type immediate for ref.null.
Definition: WebAssemblyMCTargetDesc.h:82
llvm::MCOperand::createExpr
static MCOperand createExpr(const MCExpr *Val)
Definition: MCInst.h:162
llvm::getTheWebAssemblyTarget32
Target & getTheWebAssemblyTarget32()
Definition: WebAssemblyTargetInfo.cpp:20
MCDisassembler.h
llvm::WebAssembly::OPERAND_TABLE
@ OPERAND_TABLE
32-bit unsigned table number.
Definition: WebAssemblyMCTargetDesc.h:80
llvm::MCOI::OPERAND_IMMEDIATE
@ OPERAND_IMMEDIATE
Definition: MCInstrDesc.h:58
llvm::MCOperand::createImm
static MCOperand createImm(int64_t Val)
Definition: MCInst.h:141
llvm::MCContext
Context object for machine code objects.
Definition: MCContext.h:72
llvm::SymbolInfoTy
Definition: MCDisassembler.h:33
llvm::Target
Target - Wrapper for Target specific information.
Definition: TargetRegistry.h:137
llvm::WebAssembly::OPERAND_VEC_I32IMM
@ OPERAND_VEC_I32IMM
32-bit vector lane immediate
Definition: WebAssemblyMCTargetDesc.h:60
llvm::WebAssembly::OPERAND_F64IMM
@ OPERAND_F64IMM
64-bit floating-point immediates.
Definition: WebAssemblyMCTargetDesc.h:54
llvm::WebAssembly::OPERAND_OFFSET32
@ OPERAND_OFFSET32
32-bit unsigned memory offsets.
Definition: WebAssemblyMCTargetDesc.h:66
llvm::Type
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
nextByte
static int nextByte(ArrayRef< uint8_t > Bytes, uint64_t &Size)
Definition: WebAssemblyDisassembler.cpp:76
llvm::WebAssembly::OPERAND_GLOBAL
@ OPERAND_GLOBAL
Global index.
Definition: WebAssemblyMCTargetDesc.h:46
llvm::TargetRegistry::RegisterMCDisassembler
static void RegisterMCDisassembler(Target &T, Target::MCDisassemblerCtorTy Fn)
RegisterMCDisassembler - Register a MCDisassembler implementation for the given target.
Definition: TargetRegistry.h:916
llvm::Optional
Definition: APInt.h:33
llvm::WebAssembly::BlockType::Invalid
@ Invalid
T
#define T
Definition: Mips16ISelLowering.cpp:341
llvm::WebAssembly::OPERAND_SIGNATURE
@ OPERAND_SIGNATURE
signature immediate for block/loop.
Definition: WebAssemblyMCTargetDesc.h:72
llvm::WebAssembly::OPERAND_TAG
@ OPERAND_TAG
Tag index.
Definition: WebAssemblyMCTargetDesc.h:76
llvm::MCInst
Instances of this class represent a single low-level machine instruction.
Definition: MCInst.h:184
llvm::ArrayRef::data
const T * data() const
Definition: ArrayRef.h:162
llvm::decodeULEB128
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:128
llvm::outs
raw_fd_ostream & outs()
This returns a reference to a raw_fd_ostream for standard output.
Definition: raw_ostream.cpp:884
llvm::WebAssembly::OPERAND_VEC_I64IMM
@ OPERAND_VEC_I64IMM
64-bit vector lane immediate
Definition: WebAssemblyMCTargetDesc.h:62
MCSymbolWasm.h
MCContext.h
MCInstrInfo.h
MCSymbol.h
llvm::MCDisassembler::Success
@ Success
Definition: MCDisassembler.h:103
MCInst.h
MCSubtargetInfo.h
WebAssemblyTypeUtilities.h
llvm::raw_ostream
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:53
llvm::wasm::WASM_SYMBOL_TYPE_FUNCTION
@ WASM_SYMBOL_TYPE_FUNCTION
Definition: Wasm.h:352
llvm::MCDisassembler::DecodeStatus
DecodeStatus
Ternary decode status.
Definition: MCDisassembler.h:100
llvm::None
const NoneType None
Definition: None.h:23
nextLEB
static bool nextLEB(int64_t &Val, ArrayRef< uint8_t > Bytes, uint64_t &Size, bool Signed)
Definition: WebAssemblyDisassembler.cpp:84
LLVM_EXTERNAL_VISIBILITY
#define LLVM_EXTERNAL_VISIBILITY
Definition: Compiler.h:132
LEB128.h
move
compiles ldr LCPI1_0 ldr ldr mov lsr tst moveq r1 ldr LCPI1_1 and r0 bx lr It would be better to do something like to fold the shift into the conditional move
Definition: README.txt:546
llvm::MCDisassembler
Superclass for all disassemblers.
Definition: MCDisassembler.h:76
I
#define I(x, y, z)
Definition: MD5.cpp:59
WebAssemblyTargetInfo.h
llvm::MCOI::OPERAND_REGISTER
@ OPERAND_REGISTER
Definition: MCInstrDesc.h:59
llvm::HighlightColor::Address
@ Address
assert
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVMInitializeWebAssemblyDisassembler
LLVM_EXTERNAL_VISIBILITY void LLVMInitializeWebAssemblyDisassembler()
Definition: WebAssemblyDisassembler.cpp:68
llvm::WebAssembly::OPERAND_FUNCTION32
@ OPERAND_FUNCTION32
32-bit unsigned function indices.
Definition: WebAssemblyMCTargetDesc.h:64
llvm::WebAssembly::OPERAND_F32IMM
@ OPERAND_F32IMM
32-bit floating-point immediates.
Definition: WebAssemblyMCTargetDesc.h:52
llvm::ArrayRef< uint8_t >
llvm_unreachable
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Definition: ErrorHandling.h:136
llvm::MCDisassembler::Fail
@ Fail
Definition: MCDisassembler.h:101
llvm::WebAssembly::OPERAND_TYPEINDEX
@ OPERAND_TYPEINDEX
type signature immediate for call_indirect.
Definition: WebAssemblyMCTargetDesc.h:74
llvm::MCOperand::createDFPImm
static MCOperand createDFPImm(uint64_t Val)
Definition: MCInst.h:155
llvm::getTheWebAssemblyTarget64
Target & getTheWebAssemblyTarget64()
Definition: WebAssemblyTargetInfo.cpp:24
createWebAssemblyDisassembler
static MCDisassembler * createWebAssemblyDisassembler(const Target &T, const MCSubtargetInfo &STI, MCContext &Ctx)
Definition: WebAssemblyDisassembler.cpp:60
llvm::WebAssembly::OPERAND_BRLIST
@ OPERAND_BRLIST
A list of branch targets for br_list.
Definition: WebAssemblyMCTargetDesc.h:78
llvm::WebAssembly::OPERAND_VEC_I16IMM
@ OPERAND_VEC_I16IMM
16-bit vector lane immediate
Definition: WebAssemblyMCTargetDesc.h:58
llvm::Error
Lightweight error class with error context and mandatory checking.
Definition: Error.h:157
llvm::MCSymbolRefExpr::VK_WASM_TYPEINDEX
@ VK_WASM_TYPEINDEX
Definition: MCExpr.h:327
parseImmediate
bool parseImmediate(MCInst &MI, uint64_t &Size, ArrayRef< uint8_t > Bytes)
Definition: WebAssemblyDisassembler.cpp:109
llvm::MCSymbolRefExpr::create
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx)
Definition: MCExpr.h:384
llvm::WebAssembly::OPERAND_P2ALIGN
@ OPERAND_P2ALIGN
p2align immediate for load and store address alignment.
Definition: WebAssemblyMCTargetDesc.h:70
llvm::ARMBuildAttrs::Symbol
@ Symbol
Definition: ARMBuildAttributes.h:79
llvm::WebAssembly::OPERAND_OFFSET64
@ OPERAND_OFFSET64
64-bit unsigned memory offsets.
Definition: WebAssemblyMCTargetDesc.h:68
llvm::decodeSLEB128
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:161
llvm::WebAssembly::HeapType::Invalid
@ Invalid
N
#define N
llvm::WebAssembly::OPERAND_I64IMM
@ OPERAND_I64IMM
64-bit integer immediates.
Definition: WebAssemblyMCTargetDesc.h:50
llvm::ArrayRef::size
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:165
parseLEBImmediate
static bool parseLEBImmediate(MCInst &MI, uint64_t &Size, ArrayRef< uint8_t > Bytes, bool Signed)
Definition: WebAssemblyDisassembler.cpp:99
llvm::WebAssembly::anyTypeToString
const char * anyTypeToString(unsigned Type)
Definition: WebAssemblyTypeUtilities.cpp:83
llvm::WebAssembly::OPERAND_VEC_I8IMM
@ OPERAND_VEC_I8IMM
8-bit vector lane immediate
Definition: WebAssemblyMCTargetDesc.h:56
llvm::WebAssembly::OPERAND_LOCAL
@ OPERAND_LOCAL
Local index.
Definition: WebAssemblyMCTargetDesc.h:44
Endian.h
TargetRegistry.h
llvm::MCSubtargetInfo
Generic base class for all target subtargets.
Definition: MCSubtargetInfo.h:75
llvm::WebAssembly::OPERAND_I32IMM
@ OPERAND_I32IMM
32-bit integer immediates.
Definition: WebAssemblyMCTargetDesc.h:48
llvm::MCExpr
Base class for the full range of assembler expressions which are needed for parsing.
Definition: MCExpr.h:35
llvm::WebAssembly::OPERAND_BASIC_BLOCK
@ OPERAND_BASIC_BLOCK
Basic block label in a branch construct.
Definition: WebAssemblyMCTargetDesc.h:42