LLVM  13.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"
23 #include "llvm/MC/MCInst.h"
24 #include "llvm/MC/MCInstrInfo.h"
26 #include "llvm/MC/MCSymbol.h"
27 #include "llvm/MC/MCSymbolWasm.h"
28 #include "llvm/Support/Endian.h"
29 #include "llvm/Support/LEB128.h"
31 
32 using namespace llvm;
33 
34 #define DEBUG_TYPE "wasm-disassembler"
35 
37 
38 #include "WebAssemblyGenDisassemblerTables.inc"
39 
40 namespace {
41 static constexpr int WebAssemblyInstructionTableSize = 256;
42 
43 class WebAssemblyDisassembler final : public MCDisassembler {
44  std::unique_ptr<const MCInstrInfo> MCII;
45 
46  DecodeStatus getInstruction(MCInst &Instr, uint64_t &Size,
47  ArrayRef<uint8_t> Bytes, uint64_t Address,
48  raw_ostream &CStream) const override;
49  Optional<DecodeStatus> onSymbolStart(SymbolInfoTy &Symbol, uint64_t &Size,
50  ArrayRef<uint8_t> Bytes,
51  uint64_t Address,
52  raw_ostream &CStream) const override;
53 
54 public:
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 
68 extern "C" LLVM_EXTERNAL_VISIBILITY void
70  // Register the disassembler for each target.
75 }
76 
77 static int nextByte(ArrayRef<uint8_t> Bytes, uint64_t &Size) {
78  if (Size >= Bytes.size())
79  return -1;
80  auto V = Bytes[Size];
81  Size++;
82  return V;
83 }
84 
85 static 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 
100 static bool parseLEBImmediate(MCInst &MI, uint64_t &Size,
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 
109 template <typename T>
110 bool parseImmediate(MCInst &MI, uint64_t &Size, ArrayRef<uint8_t> Bytes) {
111  if (Size + sizeof(T) > Bytes.size())
112  return false;
113  T Val = support::endian::read<T, support::endianness::little, 1>(
114  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 
125 Optional<MCDisassembler::DecodeStatus> WebAssemblyDisassembler::onSymbolStart(
126  SymbolInfoTy &Symbol, uint64_t &Size, ArrayRef<uint8_t> Bytes,
127  uint64_t Address, raw_ostream &CStream) const {
128  Size = 0;
129  if (Address == 0) {
130  // Start of a code section: we're parsing only the function count.
131  int64_t FunctionCount;
132  if (!nextLEB(FunctionCount, Bytes, Size, false))
133  return None;
134  outs() << " # " << FunctionCount << " functions in section.";
135  } else {
136  // Parse the start of a single function.
137  int64_t BodySize, LocalEntryCount;
138  if (!nextLEB(BodySize, Bytes, Size, false) ||
139  !nextLEB(LocalEntryCount, Bytes, Size, false))
140  return None;
141  if (LocalEntryCount) {
142  outs() << " .local ";
143  for (int64_t I = 0; I < LocalEntryCount; I++) {
144  int64_t Count, Type;
145  if (!nextLEB(Count, Bytes, Size, false) ||
146  !nextLEB(Type, Bytes, Size, false))
147  return None;
148  for (int64_t J = 0; J < Count; J++) {
149  if (I || J)
150  outs() << ", ";
152  }
153  }
154  }
155  }
156  outs() << "\n";
158 }
159 
160 MCDisassembler::DecodeStatus WebAssemblyDisassembler::getInstruction(
161  MCInst &MI, uint64_t &Size, ArrayRef<uint8_t> Bytes, uint64_t /*Address*/,
162  raw_ostream &CS) const {
163  CommentStream = &CS;
164  Size = 0;
165  int Opc = nextByte(Bytes, Size);
166  if (Opc < 0)
167  return MCDisassembler::Fail;
168  const auto *WasmInst = &InstructionTable0[Opc];
169  // If this is a prefix byte, indirect to another table.
170  if (WasmInst->ET == ET_Prefix) {
171  WasmInst = nullptr;
172  // Linear search, so far only 2 entries.
173  for (auto PT = PrefixTable; PT->Table; PT++) {
174  if (PT->Prefix == Opc) {
175  WasmInst = PT->Table;
176  break;
177  }
178  }
179  if (!WasmInst)
180  return MCDisassembler::Fail;
181  int64_t PrefixedOpc;
182  if (!nextLEB(PrefixedOpc, Bytes, Size, false))
183  return MCDisassembler::Fail;
184  if (PrefixedOpc < 0 || PrefixedOpc >= WebAssemblyInstructionTableSize)
185  return MCDisassembler::Fail;
186  WasmInst += PrefixedOpc;
187  }
188  if (WasmInst->ET == ET_Unused)
189  return MCDisassembler::Fail;
190  // At this point we must have a valid instruction to decode.
191  assert(WasmInst->ET == ET_Instruction);
192  MI.setOpcode(WasmInst->Opcode);
193  // Parse any operands.
194  for (uint8_t OPI = 0; OPI < WasmInst->NumOperands; OPI++) {
195  auto OT = OperandTable[WasmInst->OperandStart + OPI];
196  switch (OT) {
197  // ULEB operands:
209  if (!parseLEBImmediate(MI, Size, Bytes, false))
210  return MCDisassembler::Fail;
211  break;
212  }
213  // SLEB operands:
216  if (!parseLEBImmediate(MI, Size, Bytes, true))
217  return MCDisassembler::Fail;
218  break;
219  }
220  // block_type operands:
222  int64_t Val;
223  uint64_t PrevSize = Size;
224  if (!nextLEB(Val, Bytes, Size, true))
225  return MCDisassembler::Fail;
226  if (Val < 0) {
227  // Negative values are single septet value types or empty types
228  if (Size != PrevSize + 1) {
229  MI.addOperand(
231  } else {
232  MI.addOperand(MCOperand::createImm(Val & 0x7f));
233  }
234  } else {
235  // We don't have access to the signature, so create a symbol without one
236  MCSymbol *Sym = getContext().createTempSymbol("typeindex", true);
237  auto *WasmSym = cast<MCSymbolWasm>(Sym);
238  WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
239  const MCExpr *Expr = MCSymbolRefExpr::create(
240  WasmSym, MCSymbolRefExpr::VK_WASM_TYPEINDEX, getContext());
241  MI.addOperand(MCOperand::createExpr(Expr));
242  }
243  break;
244  }
245  // heap_type operands, for e.g. ref.null:
247  int64_t Val;
248  uint64_t PrevSize = Size;
249  if (!nextLEB(Val, Bytes, Size, true))
250  return MCDisassembler::Fail;
251  if (Val < 0 && Size == PrevSize + 1) {
252  // The HeapType encoding is like BlockType, in that encodings that
253  // decode as negative values indicate ValTypes. In practice we expect
254  // either wasm::ValType::EXTERNREF or wasm::ValType::FUNCREF here.
255  //
256  // The positive SLEB values are reserved for future expansion and are
257  // expected to be type indices in the typed function references
258  // proposal, and should disassemble as MCSymbolRefExpr as in BlockType
259  // above.
260  MI.addOperand(MCOperand::createImm(Val & 0x7f));
261  } else {
262  MI.addOperand(
264  }
265  break;
266  }
267  // FP operands.
269  if (!parseImmediate<float>(MI, Size, Bytes))
270  return MCDisassembler::Fail;
271  break;
272  }
274  if (!parseImmediate<double>(MI, Size, Bytes))
275  return MCDisassembler::Fail;
276  break;
277  }
278  // Vector lane operands (not LEB encoded).
280  if (!parseImmediate<uint8_t>(MI, Size, Bytes))
281  return MCDisassembler::Fail;
282  break;
283  }
285  if (!parseImmediate<uint16_t>(MI, Size, Bytes))
286  return MCDisassembler::Fail;
287  break;
288  }
290  if (!parseImmediate<uint32_t>(MI, Size, Bytes))
291  return MCDisassembler::Fail;
292  break;
293  }
295  if (!parseImmediate<uint64_t>(MI, Size, Bytes))
296  return MCDisassembler::Fail;
297  break;
298  }
300  int64_t TargetTableLen;
301  if (!nextLEB(TargetTableLen, Bytes, Size, false))
302  return MCDisassembler::Fail;
303  for (int64_t I = 0; I < TargetTableLen; I++) {
304  if (!parseLEBImmediate(MI, Size, Bytes, false))
305  return MCDisassembler::Fail;
306  }
307  // Default case.
308  if (!parseLEBImmediate(MI, Size, Bytes, false))
309  return MCDisassembler::Fail;
310  break;
311  }
313  // The tablegen header currently does not have any register operands since
314  // we use only the stack (_S) instructions.
315  // If you hit this that probably means a bad instruction definition in
316  // tablegen.
317  llvm_unreachable("Register operand in WebAssemblyDisassembler");
318  default:
319  llvm_unreachable("Unknown operand type in WebAssemblyDisassembler");
320  }
321  }
323 }
llvm::Check::Size
@ Size
Definition: FileCheck.h:73
MCFixedLenDisassembler.h
Signed
@ Signed
Definition: NVPTXISelLowering.cpp:4550
MI
IRTranslator LLVM IR MI
Definition: IRTranslator.cpp:100
llvm
This class represents lattice values for constants.
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:172
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:59
llvm::MCOperand::createImm
static MCOperand createImm(int64_t Val)
Definition: MCInst.h:145
llvm::MCContext
Context object for machine code objects.
Definition: MCContext.h:68
llvm::SymbolInfoTy
Definition: MCDisassembler.h:33
llvm::Target
Target - Wrapper for Target specific information.
Definition: TargetRegistry.h:124
llvm::WebAssembly::anyTypeToString
const char * anyTypeToString(unsigned Ty)
Definition: WebAssemblyInstPrinter.cpp:367
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:46
nextByte
static int nextByte(ArrayRef< uint8_t > Bytes, uint64_t &Size)
Definition: WebAssemblyDisassembler.cpp:77
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:819
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::MCInst
Instances of this class represent a single low-level machine instruction.
Definition: MCInst.h:194
llvm::ArrayRef::data
const T * data() const
Definition: ArrayRef.h:153
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:886
llvm::WebAssembly::OPERAND_VEC_I64IMM
@ OPERAND_VEC_I64IMM
64-bit vector lane immediate
Definition: WebAssemblyMCTargetDesc.h:62
llvm::WebAssembly::OPERAND_EVENT
@ OPERAND_EVENT
Event index.
Definition: WebAssemblyMCTargetDesc.h:76
MCSymbolWasm.h
MCContext.h
MCInstrInfo.h
MCSymbol.h
llvm::MCDisassembler::Success
@ Success
Definition: MCDisassembler.h:103
MCInst.h
MCSubtargetInfo.h
llvm::raw_ostream
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:50
llvm::wasm::WASM_SYMBOL_TYPE_FUNCTION
@ WASM_SYMBOL_TYPE_FUNCTION
Definition: Wasm.h:343
llvm::MCDisassembler::DecodeStatus
DecodeStatus
Ternary decode status.
Definition: MCDisassembler.h:100
llvm::None
const NoneType None
Definition: None.h:23
WebAssemblyMCTargetDesc.h
nextLEB
static bool nextLEB(int64_t &Val, ArrayRef< uint8_t > Bytes, uint64_t &Size, bool Signed)
Definition: WebAssemblyDisassembler.cpp:85
LLVM_EXTERNAL_VISIBILITY
#define LLVM_EXTERNAL_VISIBILITY
Definition: Compiler.h:131
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
WebAssemblyInstPrinter.h
I
#define I(x, y, z)
Definition: MD5.cpp:59
WebAssemblyTargetInfo.h
llvm::MCOI::OPERAND_REGISTER
@ OPERAND_REGISTER
Definition: MCInstrDesc.h:60
llvm::HighlightColor::Address
@ Address
assert
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVMInitializeWebAssemblyDisassembler
LLVM_EXTERNAL_VISIBILITY void LLVMInitializeWebAssemblyDisassembler()
Definition: WebAssemblyDisassembler.cpp:69
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:159
llvm::getTheWebAssemblyTarget64
Target & getTheWebAssemblyTarget64()
Definition: WebAssemblyTargetInfo.cpp:24
createWebAssemblyDisassembler
static MCDisassembler * createWebAssemblyDisassembler(const Target &T, const MCSubtargetInfo &STI, MCContext &Ctx)
Definition: WebAssemblyDisassembler.cpp:61
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:325
parseImmediate
bool parseImmediate(MCInst &MI, uint64_t &Size, ArrayRef< uint8_t > Bytes)
Definition: WebAssemblyDisassembler.cpp:110
llvm::MCSymbolRefExpr::create
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx)
Definition: MCExpr.h:382
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:156
parseLEBImmediate
static bool parseLEBImmediate(MCInst &MI, uint64_t &Size, ArrayRef< uint8_t > Bytes, bool Signed)
Definition: WebAssemblyDisassembler.cpp:100
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