1 //=- WebAssemblyInstPrinter.cpp - WebAssembly assembly instruction printing -=//
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 /// Print MCInst instructions to wasm format.
11 ///
12 //===----------------------------------------------------------------------===//
13 
14 #include "MCTargetDesc/WebAssemblyInstPrinter.h"
15 #include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
16 #include "WebAssembly.h"
17 #include "WebAssemblyMachineFunctionInfo.h"
18 #include "WebAssemblyUtilities.h"
19 #include "llvm/ADT/SmallSet.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/CodeGen/TargetRegisterInfo.h"
22 #include "llvm/MC/MCExpr.h"
23 #include "llvm/MC/MCInst.h"
24 #include "llvm/MC/MCInstrInfo.h"
25 #include "llvm/MC/MCSubtargetInfo.h"
26 #include "llvm/MC/MCSymbol.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/FormattedStream.h"
29 using namespace llvm;
30 
31 #define DEBUG_TYPE "asm-printer"
32 
33 #include "WebAssemblyGenAsmWriter.inc"
34 
35 WebAssemblyInstPrinter::WebAssemblyInstPrinter(const MCAsmInfo &MAI,
36                                                const MCInstrInfo &MII,
37                                                const MCRegisterInfo &MRI)
38     : MCInstPrinter(MAI, MII, MRI) {}
39 
40 void WebAssemblyInstPrinter::printRegName(raw_ostream &OS,
41                                           unsigned RegNo) const {
42   assert(RegNo != WebAssemblyFunctionInfo::UnusedReg);
43   // Note that there's an implicit local.get/local.set here!
44   OS << "$" << RegNo;
45 }
46 
47 void WebAssemblyInstPrinter::printInst(const MCInst *MI, uint64_t Address,
48                                        StringRef Annot,
49                                        const MCSubtargetInfo &STI,
50                                        raw_ostream &OS) {
51   // Print the instruction (this uses the AsmStrings from the .td files).
52   printInstruction(MI, Address, OS);
53 
54   // Print any additional variadic operands.
55   const MCInstrDesc &Desc = MII.get(MI->getOpcode());
56   if (Desc.isVariadic()) {
57     if ((Desc.getNumOperands() == 0 && MI->getNumOperands() > 0) ||
58         Desc.variadicOpsAreDefs())
59       OS << "\t";
60     unsigned Start = Desc.getNumOperands();
61     unsigned NumVariadicDefs = 0;
62     if (Desc.variadicOpsAreDefs()) {
63       // The number of variadic defs is encoded in an immediate by MCInstLower
64       NumVariadicDefs = MI->getOperand(0).getImm();
65       Start = 1;
66     }
67     bool NeedsComma = Desc.getNumOperands() > 0 && !Desc.variadicOpsAreDefs();
68     for (auto I = Start, E = MI->getNumOperands(); I < E; ++I) {
69       if (MI->getOpcode() == WebAssembly::CALL_INDIRECT &&
70           I - Start == NumVariadicDefs) {
71         // Skip type and flags arguments when printing for tests
72         ++I;
73         continue;
74       }
75       if (NeedsComma)
76         OS << ", ";
77       printOperand(MI, I, OS, I - Start < NumVariadicDefs);
78       NeedsComma = true;
79     }
80   }
81 
82   // Print any added annotation.
83   printAnnotation(OS, Annot);
84 
85   if (CommentStream) {
86     // Observe any effects on the control flow stack, for use in annotating
87     // control flow label references.
88     unsigned Opc = MI->getOpcode();
89     switch (Opc) {
90     default:
91       break;
92 
93     case WebAssembly::LOOP:
94     case WebAssembly::LOOP_S:
95       printAnnotation(OS, "label" + utostr(ControlFlowCounter) + ':');
96       ControlFlowStack.push_back(std::make_pair(ControlFlowCounter, true));
97       DelegateStack.push_back(ControlFlowCounter++);
98       return;
99 
100     case WebAssembly::BLOCK:
101     case WebAssembly::BLOCK_S:
102       ControlFlowStack.push_back(std::make_pair(ControlFlowCounter, false));
103       DelegateStack.push_back(ControlFlowCounter++);
104       return;
105 
106     case WebAssembly::TRY:
107     case WebAssembly::TRY_S:
108       ControlFlowStack.push_back(std::make_pair(ControlFlowCounter, false));
109       EHPadStack.push_back(ControlFlowCounter);
110       DelegateStack.push_back(ControlFlowCounter++);
111       return;
112 
113     case WebAssembly::END_LOOP:
114     case WebAssembly::END_LOOP_S:
115       if (ControlFlowStack.empty() || DelegateStack.empty()) {
116         printAnnotation(OS, "End marker mismatch!");
117       } else {
118         ControlFlowStack.pop_back();
119         DelegateStack.pop_back();
120       }
121       return;
122 
123     case WebAssembly::END_BLOCK:
124     case WebAssembly::END_BLOCK_S:
125       if (ControlFlowStack.empty() || DelegateStack.empty()) {
126         printAnnotation(OS, "End marker mismatch!");
127       } else {
128         printAnnotation(
129             OS, "label" + utostr(ControlFlowStack.pop_back_val().first) + ':');
130         DelegateStack.pop_back();
131       }
132       return;
133 
134     case WebAssembly::END_TRY:
135     case WebAssembly::END_TRY_S:
136       if (ControlFlowStack.empty()) {
137         printAnnotation(OS, "End marker mismatch!");
138       } else {
139         printAnnotation(
140             OS, "label" + utostr(ControlFlowStack.pop_back_val().first) + ':');
141       }
142       return;
143 
144     case WebAssembly::CATCH:
145     case WebAssembly::CATCH_S:
146     case WebAssembly::CATCH_ALL:
147     case WebAssembly::CATCH_ALL_S:
148       if (EHPadStack.empty() || DelegateStack.empty()) {
149         printAnnotation(OS, "try-catch mismatch!");
150       } else {
151         printAnnotation(OS, "catch" + utostr(EHPadStack.pop_back_val()) + ':');
152         DelegateStack.pop_back();
153       }
154       return;
155 
156     case WebAssembly::RETHROW:
157     case WebAssembly::RETHROW_S:
158       // 'rethrow' rethrows to the nearest enclosing catch scope, if any. If
159       // there's no enclosing catch scope, it throws up to the caller.
160       if (EHPadStack.empty()) {
161         printAnnotation(OS, "to caller");
162       } else {
163         printAnnotation(OS, "down to catch" + utostr(EHPadStack.back()));
164       }
165       return;
166 
167     case WebAssembly::DELEGATE:
168     case WebAssembly::DELEGATE_S:
169       if (ControlFlowStack.empty() || EHPadStack.empty() ||
170           DelegateStack.empty()) {
171         printAnnotation(OS, "try-delegate mismatch!");
172       } else {
173         // 'delegate' is
174         // 1. A marker for the end of block label
175         // 2. A destination for throwing instructions
176         // 3. An instruction that itself rethrows to another 'catch'
177         assert(ControlFlowStack.back().first == EHPadStack.back() &&
178                EHPadStack.back() == DelegateStack.back());
179         std::string Label = "label/catch" +
180                             utostr(ControlFlowStack.pop_back_val().first) +
181                             ": ";
182         EHPadStack.pop_back();
183         DelegateStack.pop_back();
184         uint64_t Depth = MI->getOperand(0).getImm();
185         if (Depth >= DelegateStack.size()) {
186           Label += "to caller";
187         } else {
188           Label += "down to catch" + utostr(DelegateStack.rbegin()[Depth]);
189         }
190         printAnnotation(OS, Label);
191       }
192       return;
193     }
194 
195     // Annotate any control flow label references.
196 
197     unsigned NumFixedOperands = Desc.NumOperands;
198     SmallSet<uint64_t, 8> Printed;
199     for (unsigned I = 0, E = MI->getNumOperands(); I < E; ++I) {
200       // See if this operand denotes a basic block target.
201       if (I < NumFixedOperands) {
202         // A non-variable_ops operand, check its type.
203         if (Desc.OpInfo[I].OperandType != WebAssembly::OPERAND_BASIC_BLOCK)
204           continue;
205       } else {
206         // A variable_ops operand, which currently can be immediates (used in
207         // br_table) which are basic block targets, or for call instructions
208         // when using -wasm-keep-registers (in which case they are registers,
209         // and should not be processed).
210         if (!MI->getOperand(I).isImm())
211           continue;
212       }
213       uint64_t Depth = MI->getOperand(I).getImm();
214       if (!Printed.insert(Depth).second)
215         continue;
216       if (Depth >= ControlFlowStack.size()) {
217         printAnnotation(OS, "Invalid depth argument!");
218       } else {
219         const auto &Pair = ControlFlowStack.rbegin()[Depth];
220         printAnnotation(OS, utostr(Depth) + ": " +
221                                 (Pair.second ? "up" : "down") + " to label" +
222                                 utostr(Pair.first));
223       }
224     }
225   }
226 }
227 
228 static std::string toString(const APFloat &FP) {
229   // Print NaNs with custom payloads specially.
230   if (FP.isNaN() && !FP.bitwiseIsEqual(APFloat::getQNaN(FP.getSemantics())) &&
231       !FP.bitwiseIsEqual(
232           APFloat::getQNaN(FP.getSemantics(), /*Negative=*/true))) {
233     APInt AI = FP.bitcastToAPInt();
234     return std::string(AI.isNegative() ? "-" : "") + "nan:0x" +
235            utohexstr(AI.getZExtValue() &
236                          (AI.getBitWidth() == 32 ? INT64_C(0x007fffff)
237                                                  : INT64_C(0x000fffffffffffff)),
238                      /*LowerCase=*/true);
239   }
240 
241   // Use C99's hexadecimal floating-point representation.
242   static const size_t BufBytes = 128;
243   char Buf[BufBytes];
244   auto Written = FP.convertToHexString(
245       Buf, /*HexDigits=*/0, /*UpperCase=*/false, APFloat::rmNearestTiesToEven);
246   (void)Written;
247   assert(Written != 0);
248   assert(Written < BufBytes);
249   return Buf;
250 }
251 
252 void WebAssemblyInstPrinter::printOperand(const MCInst *MI, unsigned OpNo,
253                                           raw_ostream &O, bool IsVariadicDef) {
254   const MCOperand &Op = MI->getOperand(OpNo);
255   if (Op.isReg()) {
256     const MCInstrDesc &Desc = MII.get(MI->getOpcode());
257     unsigned WAReg = Op.getReg();
258     if (int(WAReg) >= 0)
259       printRegName(O, WAReg);
260     else if (OpNo >= Desc.getNumDefs() && !IsVariadicDef)
261       O << "$pop" << WebAssemblyFunctionInfo::getWARegStackId(WAReg);
262     else if (WAReg != WebAssemblyFunctionInfo::UnusedReg)
263       O << "$push" << WebAssemblyFunctionInfo::getWARegStackId(WAReg);
264     else
265       O << "$drop";
266     // Add a '=' suffix if this is a def.
267     if (OpNo < MII.get(MI->getOpcode()).getNumDefs() || IsVariadicDef)
268       O << '=';
269   } else if (Op.isImm()) {
270     O << Op.getImm();
271   } else if (Op.isSFPImm()) {
272     O << ::toString(APFloat(bit_cast<float>(Op.getSFPImm())));
273   } else if (Op.isDFPImm()) {
274     O << ::toString(APFloat(bit_cast<double>(Op.getDFPImm())));
275   } else {
276     assert(Op.isExpr() && "unknown operand kind in printOperand");
277     // call_indirect instructions have a TYPEINDEX operand that we print
278     // as a signature here, such that the assembler can recover this
279     // information.
280     auto SRE = static_cast<const MCSymbolRefExpr *>(Op.getExpr());
281     if (SRE->getKind() == MCSymbolRefExpr::VK_WASM_TYPEINDEX) {
282       auto &Sym = static_cast<const MCSymbolWasm &>(SRE->getSymbol());
283       O << WebAssembly::signatureToString(Sym.getSignature());
284     } else {
285       Op.getExpr()->print(O, &MAI);
286     }
287   }
288 }
289 
290 void WebAssemblyInstPrinter::printBrList(const MCInst *MI, unsigned OpNo,
291                                          raw_ostream &O) {
292   O << "{";
293   for (unsigned I = OpNo, E = MI->getNumOperands(); I != E; ++I) {
294     if (I != OpNo)
295       O << ", ";
296     O << MI->getOperand(I).getImm();
297   }
298   O << "}";
299 }
300 
301 void WebAssemblyInstPrinter::printWebAssemblyP2AlignOperand(const MCInst *MI,
302                                                             unsigned OpNo,
303                                                             raw_ostream &O) {
304   int64_t Imm = MI->getOperand(OpNo).getImm();
305   if (Imm == WebAssembly::GetDefaultP2Align(MI->getOpcode()))
306     return;
307   O << ":p2align=" << Imm;
308 }
309 
310 void WebAssemblyInstPrinter::printWebAssemblySignatureOperand(const MCInst *MI,
311                                                               unsigned OpNo,
312                                                               raw_ostream &O) {
313   const MCOperand &Op = MI->getOperand(OpNo);
314   if (Op.isImm()) {
315     auto Imm = static_cast<unsigned>(Op.getImm());
316     if (Imm != wasm::WASM_TYPE_NORESULT)
317       O << WebAssembly::anyTypeToString(Imm);
318   } else {
319     auto Expr = cast<MCSymbolRefExpr>(Op.getExpr());
320     auto *Sym = cast<MCSymbolWasm>(&Expr->getSymbol());
321     if (Sym->getSignature()) {
322       O << WebAssembly::signatureToString(Sym->getSignature());
323     } else {
324       // Disassembler does not currently produce a signature
325       O << "unknown_type";
326     }
327   }
328 }
329 
330 void WebAssemblyInstPrinter::printWebAssemblyHeapTypeOperand(const MCInst *MI,
331                                                              unsigned OpNo,
332                                                              raw_ostream &O) {
333   const MCOperand &Op = MI->getOperand(OpNo);
334   if (Op.isImm()) {
335     switch (Op.getImm()) {
336     case long(wasm::ValType::EXTERNREF):
337       O << "extern";
338       break;
339     case long(wasm::ValType::FUNCREF):
340       O << "func";
341       break;
342     default:
343       O << "unsupported_heap_type_value";
344       break;
345     }
346   } else {
347     // Typed function references and other subtypes of funcref and externref
348     // currently unimplemented.
349     O << "unsupported_heap_type_operand";
350   }
351 }
352 
353 // We have various enums representing a subset of these types, use this
354 // function to convert any of them to text.
355 const char *WebAssembly::anyTypeToString(unsigned Ty) {
356   switch (Ty) {
357   case wasm::WASM_TYPE_I32:
358     return "i32";
359   case wasm::WASM_TYPE_I64:
360     return "i64";
361   case wasm::WASM_TYPE_F32:
362     return "f32";
363   case wasm::WASM_TYPE_F64:
364     return "f64";
365   case wasm::WASM_TYPE_V128:
366     return "v128";
367   case wasm::WASM_TYPE_FUNCREF:
368     return "funcref";
369   case wasm::WASM_TYPE_EXTERNREF:
370     return "externref";
371   case wasm::WASM_TYPE_FUNC:
372     return "func";
373   case wasm::WASM_TYPE_NORESULT:
374     return "void";
375   default:
376     return "invalid_type";
377   }
378 }
379 
380 const char *WebAssembly::typeToString(wasm::ValType Ty) {
381   return anyTypeToString(static_cast<unsigned>(Ty));
382 }
383 
384 std::string WebAssembly::typeListToString(ArrayRef<wasm::ValType> List) {
385   std::string S;
386   for (auto &Ty : List) {
387     if (&Ty != &List[0]) S += ", ";
388     S += WebAssembly::typeToString(Ty);
389   }
390   return S;
391 }
392 
393 std::string WebAssembly::signatureToString(const wasm::WasmSignature *Sig) {
394   std::string S("(");
395   S += typeListToString(Sig->Params);
396   S += ") -> (";
397   S += typeListToString(Sig->Returns);
398   S += ")";
399   return S;
400 }
401