11a427287SDan Gohman //==- WebAssemblyDisassembler.cpp - Disassembler for WebAssembly -*- C++ -*-==//
21a427287SDan Gohman //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
61a427287SDan Gohman //
71a427287SDan Gohman //===----------------------------------------------------------------------===//
81a427287SDan Gohman ///
91a427287SDan Gohman /// \file
105f8f34e4SAdrian Prantl /// This file is part of the WebAssembly Disassembler.
111a427287SDan Gohman ///
121a427287SDan Gohman /// It contains code to translate the data produced by the decoder into
131a427287SDan Gohman /// MCInsts.
141a427287SDan Gohman ///
151a427287SDan Gohman //===----------------------------------------------------------------------===//
161a427287SDan Gohman 
17c6c42137SRichard Trieu #include "TargetInfo/WebAssemblyTargetInfo.h"
180b2bc69bSHeejin Ahn #include "Utils/WebAssemblyTypeUtilities.h"
191a427287SDan Gohman #include "llvm/MC/MCContext.h"
20*c644488aSSheng #include "llvm/MC/MCDecoderOps.h"
21c50b8907SBenjamin Kramer #include "llvm/MC/MCDisassembler/MCDisassembler.h"
221a427287SDan Gohman #include "llvm/MC/MCInst.h"
231a427287SDan Gohman #include "llvm/MC/MCInstrInfo.h"
241a427287SDan Gohman #include "llvm/MC/MCSubtargetInfo.h"
251a427287SDan Gohman #include "llvm/MC/MCSymbol.h"
262cb27072SThomas Lively #include "llvm/MC/MCSymbolWasm.h"
2789b57061SReid Kleckner #include "llvm/MC/TargetRegistry.h"
281a427287SDan Gohman #include "llvm/Support/Endian.h"
2916c16827SSam Clegg #include "llvm/Support/LEB128.h"
3016c16827SSam Clegg 
311a427287SDan Gohman using namespace llvm;
321a427287SDan Gohman 
331a427287SDan Gohman #define DEBUG_TYPE "wasm-disassembler"
341a427287SDan Gohman 
3516c16827SSam Clegg using DecodeStatus = MCDisassembler::DecodeStatus;
3616c16827SSam Clegg 
3716c16827SSam Clegg #include "WebAssemblyGenDisassemblerTables.inc"
3816c16827SSam Clegg 
391a427287SDan Gohman namespace {
4049550663SFangrui Song static constexpr int WebAssemblyInstructionTableSize = 256;
4149550663SFangrui Song 
421a427287SDan Gohman class WebAssemblyDisassembler final : public MCDisassembler {
431a427287SDan Gohman   std::unique_ptr<const MCInstrInfo> MCII;
441a427287SDan Gohman 
451a427287SDan Gohman   DecodeStatus getInstruction(MCInst &Instr, uint64_t &Size,
461a427287SDan Gohman                               ArrayRef<uint8_t> Bytes, uint64_t Address,
471a427287SDan Gohman                               raw_ostream &CStream) const override;
485bd33de9SRonak Chauhan   Optional<DecodeStatus> onSymbolStart(SymbolInfoTy &Symbol, uint64_t &Size,
49480a16d5SRonak Chauhan                                        ArrayRef<uint8_t> Bytes,
50480a16d5SRonak Chauhan                                        uint64_t Address,
51f3b762a0SWouter van Oortmerssen                                        raw_ostream &CStream) const override;
521a427287SDan Gohman 
531a427287SDan Gohman public:
WebAssemblyDisassembler(const MCSubtargetInfo & STI,MCContext & Ctx,std::unique_ptr<const MCInstrInfo> MCII)541a427287SDan Gohman   WebAssemblyDisassembler(const MCSubtargetInfo &STI, MCContext &Ctx,
551a427287SDan Gohman                           std::unique_ptr<const MCInstrInfo> MCII)
561a427287SDan Gohman       : MCDisassembler(STI, Ctx), MCII(std::move(MCII)) {}
571a427287SDan Gohman };
581a427287SDan Gohman } // end anonymous namespace
591a427287SDan Gohman 
createWebAssemblyDisassembler(const Target & T,const MCSubtargetInfo & STI,MCContext & Ctx)601a427287SDan Gohman static MCDisassembler *createWebAssemblyDisassembler(const Target &T,
611a427287SDan Gohman                                                      const MCSubtargetInfo &STI,
621a427287SDan Gohman                                                      MCContext &Ctx) {
631a427287SDan Gohman   std::unique_ptr<const MCInstrInfo> MCII(T.createMCInstrInfo());
641a427287SDan Gohman   return new WebAssemblyDisassembler(STI, Ctx, std::move(MCII));
651a427287SDan Gohman }
661a427287SDan Gohman 
670dbcb363STom Stellard extern "C" LLVM_EXTERNAL_VISIBILITY void
LLVMInitializeWebAssemblyDisassembler()680dbcb363STom Stellard LLVMInitializeWebAssemblyDisassembler() {
691a427287SDan Gohman   // Register the disassembler for each target.
70f42454b9SMehdi Amini   TargetRegistry::RegisterMCDisassembler(getTheWebAssemblyTarget32(),
711a427287SDan Gohman                                          createWebAssemblyDisassembler);
72f42454b9SMehdi Amini   TargetRegistry::RegisterMCDisassembler(getTheWebAssemblyTarget64(),
731a427287SDan Gohman                                          createWebAssemblyDisassembler);
741a427287SDan Gohman }
751a427287SDan Gohman 
nextByte(ArrayRef<uint8_t> Bytes,uint64_t & Size)76fc3163b6SThomas Lively static int nextByte(ArrayRef<uint8_t> Bytes, uint64_t &Size) {
7716c16827SSam Clegg   if (Size >= Bytes.size())
7816c16827SSam Clegg     return -1;
7916c16827SSam Clegg   auto V = Bytes[Size];
8016c16827SSam Clegg   Size++;
8116c16827SSam Clegg   return V;
8216c16827SSam Clegg }
8316c16827SSam Clegg 
nextLEB(int64_t & Val,ArrayRef<uint8_t> Bytes,uint64_t & Size,bool Signed)842faf0794SThomas Lively static bool nextLEB(int64_t &Val, ArrayRef<uint8_t> Bytes, uint64_t &Size,
85f3b762a0SWouter van Oortmerssen                     bool Signed) {
8616c16827SSam Clegg   unsigned N = 0;
8716c16827SSam Clegg   const char *Error = nullptr;
882faf0794SThomas Lively   Val = Signed ? decodeSLEB128(Bytes.data() + Size, &N,
8916c16827SSam Clegg                                Bytes.data() + Bytes.size(), &Error)
902faf0794SThomas Lively                : static_cast<int64_t>(decodeULEB128(Bytes.data() + Size, &N,
912faf0794SThomas Lively                                                     Bytes.data() + Bytes.size(),
922faf0794SThomas Lively                                                     &Error));
9316c16827SSam Clegg   if (Error)
9416c16827SSam Clegg     return false;
9516c16827SSam Clegg   Size += N;
962faf0794SThomas Lively   return true;
972faf0794SThomas Lively }
982faf0794SThomas Lively 
parseLEBImmediate(MCInst & MI,uint64_t & Size,ArrayRef<uint8_t> Bytes,bool Signed)992faf0794SThomas Lively static bool parseLEBImmediate(MCInst &MI, uint64_t &Size,
1002faf0794SThomas Lively                               ArrayRef<uint8_t> Bytes, bool Signed) {
1012faf0794SThomas Lively   int64_t Val;
1022faf0794SThomas Lively   if (!nextLEB(Val, Bytes, Size, Signed))
1032faf0794SThomas Lively     return false;
10416c16827SSam Clegg   MI.addOperand(MCOperand::createImm(Val));
10516c16827SSam Clegg   return true;
10616c16827SSam Clegg }
10716c16827SSam Clegg 
10816c16827SSam Clegg template <typename T>
parseImmediate(MCInst & MI,uint64_t & Size,ArrayRef<uint8_t> Bytes)10922442924SThomas Lively bool parseImmediate(MCInst &MI, uint64_t &Size, ArrayRef<uint8_t> Bytes) {
11016c16827SSam Clegg   if (Size + sizeof(T) > Bytes.size())
11116c16827SSam Clegg     return false;
112df6770f0SHeejin Ahn   T Val = support::endian::read<T, support::endianness::little, 1>(
1130d9f3f7fSWouter van Oortmerssen       Bytes.data() + Size);
11416c16827SSam Clegg   Size += sizeof(T);
11522442924SThomas Lively   if (std::is_floating_point<T>::value) {
116e5269da9SFangrui Song     MI.addOperand(
117e5269da9SFangrui Song         MCOperand::createDFPImm(bit_cast<uint64_t>(static_cast<double>(Val))));
11822442924SThomas Lively   } else {
11922442924SThomas Lively     MI.addOperand(MCOperand::createImm(static_cast<int64_t>(Val)));
12022442924SThomas Lively   }
12116c16827SSam Clegg   return true;
12216c16827SSam Clegg }
12316c16827SSam Clegg 
onSymbolStart(SymbolInfoTy & Symbol,uint64_t & Size,ArrayRef<uint8_t> Bytes,uint64_t Address,raw_ostream & CStream) const124480a16d5SRonak Chauhan Optional<MCDisassembler::DecodeStatus> WebAssemblyDisassembler::onSymbolStart(
1255bd33de9SRonak Chauhan     SymbolInfoTy &Symbol, uint64_t &Size, ArrayRef<uint8_t> Bytes,
1265bd33de9SRonak Chauhan     uint64_t Address, raw_ostream &CStream) const {
127f3b762a0SWouter van Oortmerssen   Size = 0;
128f3b762a0SWouter van Oortmerssen   if (Address == 0) {
129f3b762a0SWouter van Oortmerssen     // Start of a code section: we're parsing only the function count.
130f3b762a0SWouter van Oortmerssen     int64_t FunctionCount;
131f3b762a0SWouter van Oortmerssen     if (!nextLEB(FunctionCount, Bytes, Size, false))
132480a16d5SRonak Chauhan       return None;
133f3b762a0SWouter van Oortmerssen     outs() << "        # " << FunctionCount << " functions in section.";
134f3b762a0SWouter van Oortmerssen   } else {
135f3b762a0SWouter van Oortmerssen     // Parse the start of a single function.
136f3b762a0SWouter van Oortmerssen     int64_t BodySize, LocalEntryCount;
137f3b762a0SWouter van Oortmerssen     if (!nextLEB(BodySize, Bytes, Size, false) ||
138f3b762a0SWouter van Oortmerssen         !nextLEB(LocalEntryCount, Bytes, Size, false))
139480a16d5SRonak Chauhan       return None;
140f3b762a0SWouter van Oortmerssen     if (LocalEntryCount) {
141f3b762a0SWouter van Oortmerssen       outs() << "        .local ";
142f3b762a0SWouter van Oortmerssen       for (int64_t I = 0; I < LocalEntryCount; I++) {
143f3b762a0SWouter van Oortmerssen         int64_t Count, Type;
144f3b762a0SWouter van Oortmerssen         if (!nextLEB(Count, Bytes, Size, false) ||
145f3b762a0SWouter van Oortmerssen             !nextLEB(Type, Bytes, Size, false))
146480a16d5SRonak Chauhan           return None;
147f3b762a0SWouter van Oortmerssen         for (int64_t J = 0; J < Count; J++) {
148f3b762a0SWouter van Oortmerssen           if (I || J)
149f3b762a0SWouter van Oortmerssen             outs() << ", ";
150f3b762a0SWouter van Oortmerssen           outs() << WebAssembly::anyTypeToString(Type);
151f3b762a0SWouter van Oortmerssen         }
152f3b762a0SWouter van Oortmerssen       }
153f3b762a0SWouter van Oortmerssen     }
154f3b762a0SWouter van Oortmerssen   }
155f3b762a0SWouter van Oortmerssen   outs() << "\n";
156f3b762a0SWouter van Oortmerssen   return MCDisassembler::Success;
157f3b762a0SWouter van Oortmerssen }
158f3b762a0SWouter van Oortmerssen 
getInstruction(MCInst & MI,uint64_t & Size,ArrayRef<uint8_t> Bytes,uint64_t,raw_ostream & CS) const1591a427287SDan Gohman MCDisassembler::DecodeStatus WebAssemblyDisassembler::getInstruction(
1601a427287SDan Gohman     MCInst &MI, uint64_t &Size, ArrayRef<uint8_t> Bytes, uint64_t /*Address*/,
1616fdd6a7bSFangrui Song     raw_ostream &CS) const {
16216c16827SSam Clegg   CommentStream = &CS;
16316c16827SSam Clegg   Size = 0;
164fc3163b6SThomas Lively   int Opc = nextByte(Bytes, Size);
16516c16827SSam Clegg   if (Opc < 0)
1661a427287SDan Gohman     return MCDisassembler::Fail;
16716c16827SSam Clegg   const auto *WasmInst = &InstructionTable0[Opc];
16816c16827SSam Clegg   // If this is a prefix byte, indirect to another table.
16916c16827SSam Clegg   if (WasmInst->ET == ET_Prefix) {
17016c16827SSam Clegg     WasmInst = nullptr;
17116c16827SSam Clegg     // Linear search, so far only 2 entries.
17216c16827SSam Clegg     for (auto PT = PrefixTable; PT->Table; PT++) {
17316c16827SSam Clegg       if (PT->Prefix == Opc) {
17416c16827SSam Clegg         WasmInst = PT->Table;
17516c16827SSam Clegg         break;
17616c16827SSam Clegg       }
17716c16827SSam Clegg     }
17816c16827SSam Clegg     if (!WasmInst)
17916c16827SSam Clegg       return MCDisassembler::Fail;
1802faf0794SThomas Lively     int64_t PrefixedOpc;
181f3b762a0SWouter van Oortmerssen     if (!nextLEB(PrefixedOpc, Bytes, Size, false))
18216c16827SSam Clegg       return MCDisassembler::Fail;
1832faf0794SThomas Lively     if (PrefixedOpc < 0 || PrefixedOpc >= WebAssemblyInstructionTableSize)
1842faf0794SThomas Lively       return MCDisassembler::Fail;
1852faf0794SThomas Lively     WasmInst += PrefixedOpc;
18616c16827SSam Clegg   }
18716c16827SSam Clegg   if (WasmInst->ET == ET_Unused)
18816c16827SSam Clegg     return MCDisassembler::Fail;
18916c16827SSam Clegg   // At this point we must have a valid instruction to decode.
19016c16827SSam Clegg   assert(WasmInst->ET == ET_Instruction);
19116c16827SSam Clegg   MI.setOpcode(WasmInst->Opcode);
19216c16827SSam Clegg   // Parse any operands.
19316c16827SSam Clegg   for (uint8_t OPI = 0; OPI < WasmInst->NumOperands; OPI++) {
194820c6263SWouter van Oortmerssen     auto OT = OperandTable[WasmInst->OperandStart + OPI];
195820c6263SWouter van Oortmerssen     switch (OT) {
19616c16827SSam Clegg     // ULEB operands:
19716c16827SSam Clegg     case WebAssembly::OPERAND_BASIC_BLOCK:
19816c16827SSam Clegg     case WebAssembly::OPERAND_LOCAL:
19916c16827SSam Clegg     case WebAssembly::OPERAND_GLOBAL:
20016c16827SSam Clegg     case WebAssembly::OPERAND_FUNCTION32:
20169e2797eSPaulo Matos     case WebAssembly::OPERAND_TABLE:
20216c16827SSam Clegg     case WebAssembly::OPERAND_OFFSET32:
203d9e0bbd1SWouter van Oortmerssen     case WebAssembly::OPERAND_OFFSET64:
20416c16827SSam Clegg     case WebAssembly::OPERAND_P2ALIGN:
20516c16827SSam Clegg     case WebAssembly::OPERAND_TYPEINDEX:
2061d891d44SHeejin Ahn     case WebAssembly::OPERAND_TAG:
20716c16827SSam Clegg     case MCOI::OPERAND_IMMEDIATE: {
20816c16827SSam Clegg       if (!parseLEBImmediate(MI, Size, Bytes, false))
20916c16827SSam Clegg         return MCDisassembler::Fail;
21016c16827SSam Clegg       break;
21116c16827SSam Clegg     }
21216c16827SSam Clegg     // SLEB operands:
21316c16827SSam Clegg     case WebAssembly::OPERAND_I32IMM:
214ad72f685SWouter van Oortmerssen     case WebAssembly::OPERAND_I64IMM: {
21516c16827SSam Clegg       if (!parseLEBImmediate(MI, Size, Bytes, true))
21616c16827SSam Clegg         return MCDisassembler::Fail;
21716c16827SSam Clegg       break;
21816c16827SSam Clegg     }
2192cb27072SThomas Lively     // block_type operands:
220ad72f685SWouter van Oortmerssen     case WebAssembly::OPERAND_SIGNATURE: {
2212cb27072SThomas Lively       int64_t Val;
2222cb27072SThomas Lively       uint64_t PrevSize = Size;
2232cb27072SThomas Lively       if (!nextLEB(Val, Bytes, Size, true))
224ad72f685SWouter van Oortmerssen         return MCDisassembler::Fail;
2252cb27072SThomas Lively       if (Val < 0) {
2262cb27072SThomas Lively         // Negative values are single septet value types or empty types
2272cb27072SThomas Lively         if (Size != PrevSize + 1) {
2282cb27072SThomas Lively           MI.addOperand(
2292cb27072SThomas Lively               MCOperand::createImm(int64_t(WebAssembly::BlockType::Invalid)));
2302cb27072SThomas Lively         } else {
2312cb27072SThomas Lively           MI.addOperand(MCOperand::createImm(Val & 0x7f));
2322cb27072SThomas Lively         }
2332cb27072SThomas Lively       } else {
2342cb27072SThomas Lively         // We don't have access to the signature, so create a symbol without one
2352cb27072SThomas Lively         MCSymbol *Sym = getContext().createTempSymbol("typeindex", true);
2362cb27072SThomas Lively         auto *WasmSym = cast<MCSymbolWasm>(Sym);
2372cb27072SThomas Lively         WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
2382cb27072SThomas Lively         const MCExpr *Expr = MCSymbolRefExpr::create(
2392cb27072SThomas Lively             WasmSym, MCSymbolRefExpr::VK_WASM_TYPEINDEX, getContext());
2402cb27072SThomas Lively         MI.addOperand(MCOperand::createExpr(Expr));
2412cb27072SThomas Lively       }
242ad72f685SWouter van Oortmerssen       break;
243ad72f685SWouter van Oortmerssen     }
24416c16827SSam Clegg     // FP operands.
24516c16827SSam Clegg     case WebAssembly::OPERAND_F32IMM: {
24622442924SThomas Lively       if (!parseImmediate<float>(MI, Size, Bytes))
24716c16827SSam Clegg         return MCDisassembler::Fail;
24816c16827SSam Clegg       break;
24916c16827SSam Clegg     }
25016c16827SSam Clegg     case WebAssembly::OPERAND_F64IMM: {
25122442924SThomas Lively       if (!parseImmediate<double>(MI, Size, Bytes))
25222442924SThomas Lively         return MCDisassembler::Fail;
25322442924SThomas Lively       break;
25422442924SThomas Lively     }
25522442924SThomas Lively     // Vector lane operands (not LEB encoded).
25622442924SThomas Lively     case WebAssembly::OPERAND_VEC_I8IMM: {
25722442924SThomas Lively       if (!parseImmediate<uint8_t>(MI, Size, Bytes))
25822442924SThomas Lively         return MCDisassembler::Fail;
25922442924SThomas Lively       break;
26022442924SThomas Lively     }
26122442924SThomas Lively     case WebAssembly::OPERAND_VEC_I16IMM: {
26222442924SThomas Lively       if (!parseImmediate<uint16_t>(MI, Size, Bytes))
26322442924SThomas Lively         return MCDisassembler::Fail;
26422442924SThomas Lively       break;
26522442924SThomas Lively     }
26622442924SThomas Lively     case WebAssembly::OPERAND_VEC_I32IMM: {
26722442924SThomas Lively       if (!parseImmediate<uint32_t>(MI, Size, Bytes))
26822442924SThomas Lively         return MCDisassembler::Fail;
26922442924SThomas Lively       break;
27022442924SThomas Lively     }
27122442924SThomas Lively     case WebAssembly::OPERAND_VEC_I64IMM: {
27222442924SThomas Lively       if (!parseImmediate<uint64_t>(MI, Size, Bytes))
27316c16827SSam Clegg         return MCDisassembler::Fail;
27416c16827SSam Clegg       break;
27516c16827SSam Clegg     }
276820c6263SWouter van Oortmerssen     case WebAssembly::OPERAND_BRLIST: {
277820c6263SWouter van Oortmerssen       int64_t TargetTableLen;
278820c6263SWouter van Oortmerssen       if (!nextLEB(TargetTableLen, Bytes, Size, false))
279820c6263SWouter van Oortmerssen         return MCDisassembler::Fail;
280820c6263SWouter van Oortmerssen       for (int64_t I = 0; I < TargetTableLen; I++) {
281820c6263SWouter van Oortmerssen         if (!parseLEBImmediate(MI, Size, Bytes, false))
282820c6263SWouter van Oortmerssen           return MCDisassembler::Fail;
283820c6263SWouter van Oortmerssen       }
284820c6263SWouter van Oortmerssen       // Default case.
285820c6263SWouter van Oortmerssen       if (!parseLEBImmediate(MI, Size, Bytes, false))
286820c6263SWouter van Oortmerssen         return MCDisassembler::Fail;
287820c6263SWouter van Oortmerssen       break;
288820c6263SWouter van Oortmerssen     }
289a733d08dSWouter van Oortmerssen     case MCOI::OPERAND_REGISTER:
290a733d08dSWouter van Oortmerssen       // The tablegen header currently does not have any register operands since
291a733d08dSWouter van Oortmerssen       // we use only the stack (_S) instructions.
292a733d08dSWouter van Oortmerssen       // If you hit this that probably means a bad instruction definition in
293a733d08dSWouter van Oortmerssen       // tablegen.
294a733d08dSWouter van Oortmerssen       llvm_unreachable("Register operand in WebAssemblyDisassembler");
29516c16827SSam Clegg     default:
29616c16827SSam Clegg       llvm_unreachable("Unknown operand type in WebAssemblyDisassembler");
29716c16827SSam Clegg     }
29816c16827SSam Clegg   }
29916c16827SSam Clegg   return MCDisassembler::Success;
3001a427287SDan Gohman }
301