xref: /llvm-project/llvm/utils/TableGen/WebAssemblyDisassemblerEmitter.cpp (revision 2ac3cd20cacdf37135eeb64ad2b7baefb9769e99)
1 //===- WebAssemblyDisassemblerEmitter.cpp - Disassembler tables -*- 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 // This file is part of the WebAssembly Disassembler Emitter.
10 // It contains the implementation of the disassembler tables.
11 // Documentation for the disassembler emitter in general can be found in
12 // WebAssemblyDisassemblerEmitter.h.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "WebAssemblyDisassemblerEmitter.h"
17 #include "CodeGenInstruction.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/Support/raw_ostream.h"
20 #include "llvm/TableGen/Record.h"
21 
22 namespace llvm {
23 
24 static constexpr int WebAssemblyInstructionTableSize = 256;
25 
26 void emitWebAssemblyDisassemblerTables(
27     raw_ostream &OS,
28     const ArrayRef<const CodeGenInstruction *> &NumberedInstructions) {
29   // First lets organize all opcodes by (prefix) byte. Prefix 0 is the
30   // starting table.
31   std::map<unsigned,
32            std::map<unsigned, std::pair<unsigned, const CodeGenInstruction *>>>
33       OpcodeTable;
34   for (unsigned I = 0; I != NumberedInstructions.size(); ++I) {
35     auto &CGI = *NumberedInstructions[I];
36     auto &Def = *CGI.TheDef;
37     if (!Def.getValue("Inst"))
38       continue;
39     auto &Inst = *Def.getValueAsBitsInit("Inst");
40     RecordKeeper &RK = Inst.getRecordKeeper();
41     unsigned Opc = static_cast<unsigned>(
42         cast<IntInit>(Inst.convertInitializerTo(IntRecTy::get(RK)))
43             ->getValue());
44     if (Opc == 0xFFFFFFFF)
45       continue; // No opcode defined.
46     assert(Opc <= 0xFFFFFF);
47     unsigned Prefix;
48     if (Opc <= 0xFFFF) {
49       Prefix = Opc >> 8;
50       Opc = Opc & 0xFF;
51     } else {
52       Prefix = Opc >> 16;
53       Opc = Opc & 0xFFFF;
54     }
55     auto &CGIP = OpcodeTable[Prefix][Opc];
56     // All wasm instructions have a StackBased field of type string, we only
57     // want the instructions for which this is "true".
58     auto StackString =
59         Def.getValue("StackBased")->getValue()->getCastTo(StringRecTy::get(RK));
60     auto IsStackBased =
61         StackString &&
62         reinterpret_cast<const StringInit *>(StackString)->getValue() == "true";
63     if (!IsStackBased)
64       continue;
65     if (CGIP.second) {
66       // We already have an instruction for this slot, so decide which one
67       // should be the canonical one. This determines which variant gets
68       // printed in a disassembly. We want e.g. "call" not "i32.call", and
69       // "end" when we don't know if its "end_loop" or "end_block" etc.
70       auto IsCanonicalExisting = CGIP.second->TheDef->getValue("IsCanonical")
71                                      ->getValue()
72                                      ->getAsString() == "1";
73       // We already have one marked explicitly as canonical, so keep it.
74       if (IsCanonicalExisting)
75         continue;
76       auto IsCanonicalNew =
77           Def.getValue("IsCanonical")->getValue()->getAsString() == "1";
78       // If the new one is explicitly marked as canonical, take it.
79       if (!IsCanonicalNew) {
80         // Neither the existing or new instruction is canonical.
81         // Pick the one with the shortest name as heuristic.
82         // Though ideally IsCanonical is always defined for at least one
83         // variant so this never has to apply.
84         if (CGIP.second->AsmString.size() <= CGI.AsmString.size())
85           continue;
86       }
87     }
88     // Set this instruction as the one to use.
89     CGIP = std::make_pair(I, &CGI);
90   }
91   OS << "#include \"MCTargetDesc/WebAssemblyMCTargetDesc.h\"\n";
92   OS << "\n";
93   OS << "namespace llvm {\n\n";
94   OS << "static constexpr int WebAssemblyInstructionTableSize = ";
95   OS << WebAssemblyInstructionTableSize << ";\n\n";
96   OS << "enum EntryType : uint8_t { ";
97   OS << "ET_Unused, ET_Prefix, ET_Instruction };\n\n";
98   OS << "struct WebAssemblyInstruction {\n";
99   OS << "  uint16_t Opcode;\n";
100   OS << "  EntryType ET;\n";
101   OS << "  uint8_t NumOperands;\n";
102   OS << "  uint16_t OperandStart;\n";
103   OS << "};\n\n";
104   std::vector<std::string> OperandTable, CurOperandList;
105   // Output one table per prefix.
106   for (auto &PrefixPair : OpcodeTable) {
107     if (PrefixPair.second.empty())
108       continue;
109     OS << "WebAssemblyInstruction InstructionTable" << PrefixPair.first;
110     OS << "[] = {\n";
111     for (unsigned I = 0; I < WebAssemblyInstructionTableSize; I++) {
112       auto InstIt = PrefixPair.second.find(I);
113       if (InstIt != PrefixPair.second.end()) {
114         // Regular instruction.
115         assert(InstIt->second.second);
116         auto &CGI = *InstIt->second.second;
117         OS << "  // 0x";
118         OS.write_hex(static_cast<unsigned long long>(I));
119         OS << ": " << CGI.AsmString << "\n";
120         OS << "  { " << InstIt->second.first << ", ET_Instruction, ";
121         OS << CGI.Operands.OperandList.size() << ", ";
122         // Collect operand types for storage in a shared list.
123         CurOperandList.clear();
124         for (auto &Op : CGI.Operands.OperandList) {
125           assert(Op.OperandType != "MCOI::OPERAND_UNKNOWN");
126           CurOperandList.push_back(Op.OperandType);
127         }
128         // See if we already have stored this sequence before. This is not
129         // strictly necessary but makes the table really small.
130         size_t OperandStart = OperandTable.size();
131         if (CurOperandList.size() <= OperandTable.size()) {
132           for (size_t J = 0; J <= OperandTable.size() - CurOperandList.size();
133                ++J) {
134             size_t K = 0;
135             for (; K < CurOperandList.size(); ++K) {
136               if (OperandTable[J + K] != CurOperandList[K]) break;
137             }
138             if (K == CurOperandList.size()) {
139               OperandStart = J;
140               break;
141             }
142           }
143         }
144         // Store operands if no prior occurrence.
145         if (OperandStart == OperandTable.size()) {
146           llvm::append_range(OperandTable, CurOperandList);
147         }
148         OS << OperandStart;
149       } else {
150         auto PrefixIt = OpcodeTable.find(I);
151         // If we have a non-empty table for it that's not 0, this is a prefix.
152         if (PrefixIt != OpcodeTable.end() && I && !PrefixPair.first) {
153           OS << "  { 0, ET_Prefix, 0, 0";
154         } else {
155           OS << "  { 0, ET_Unused, 0, 0";
156         }
157       }
158       OS << "  },\n";
159     }
160     OS << "};\n\n";
161   }
162   // Create a table of all operands:
163   OS << "const uint8_t OperandTable[] = {\n";
164   for (auto &Op : OperandTable) {
165     OS << "  " << Op << ",\n";
166   }
167   OS << "};\n\n";
168   // Create a table of all extension tables:
169   OS << "struct { uint8_t Prefix; const WebAssemblyInstruction *Table; }\n";
170   OS << "PrefixTable[] = {\n";
171   for (auto &PrefixPair : OpcodeTable) {
172     if (PrefixPair.second.empty() || !PrefixPair.first)
173       continue;
174     OS << "  { " << PrefixPair.first << ", InstructionTable"
175        << PrefixPair.first;
176     OS << " },\n";
177   }
178   OS << "  { 0, nullptr }\n};\n\n";
179   OS << "} // end namespace llvm\n";
180 }
181 
182 } // namespace llvm
183