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       break;
98 
99     case WebAssembly::BLOCK:
100     case WebAssembly::BLOCK_S:
101       ControlFlowStack.push_back(std::make_pair(ControlFlowCounter++, false));
102       break;
103 
104     case WebAssembly::TRY:
105     case WebAssembly::TRY_S:
106       ControlFlowStack.push_back(std::make_pair(ControlFlowCounter++, false));
107       EHPadStack.push_back(EHPadStackCounter++);
108       LastSeenEHInst = TRY;
109       break;
110 
111     case WebAssembly::END_LOOP:
112     case WebAssembly::END_LOOP_S:
113       if (ControlFlowStack.empty()) {
114         printAnnotation(OS, "End marker mismatch!");
115       } else {
116         ControlFlowStack.pop_back();
117       }
118       break;
119 
120     case WebAssembly::END_BLOCK:
121     case WebAssembly::END_BLOCK_S:
122       if (ControlFlowStack.empty()) {
123         printAnnotation(OS, "End marker mismatch!");
124       } else {
125         printAnnotation(
126             OS, "label" + utostr(ControlFlowStack.pop_back_val().first) + ':');
127       }
128       break;
129 
130     case WebAssembly::END_TRY:
131     case WebAssembly::END_TRY_S:
132       if (ControlFlowStack.empty()) {
133         printAnnotation(OS, "End marker mismatch!");
134       } else {
135         printAnnotation(
136             OS, "label" + utostr(ControlFlowStack.pop_back_val().first) + ':');
137         LastSeenEHInst = END_TRY;
138       }
139       break;
140 
141     case WebAssembly::CATCH:
142     case WebAssembly::CATCH_S:
143       if (EHPadStack.empty()) {
144         printAnnotation(OS, "try-catch mismatch!");
145       } else {
146         printAnnotation(OS, "catch" + utostr(EHPadStack.pop_back_val()) + ':');
147       }
148       break;
149     }
150 
151     // Annotate any control flow label references.
152 
153     // rethrow instruction does not take any depth argument and rethrows to the
154     // nearest enclosing catch scope, if any. If there's no enclosing catch
155     // scope, it throws up to the caller.
156     if (Opc == WebAssembly::RETHROW || Opc == WebAssembly::RETHROW_S) {
157       if (EHPadStack.empty()) {
158         printAnnotation(OS, "to caller");
159       } else {
160         printAnnotation(OS, "down to catch" + utostr(EHPadStack.back()));
161       }
162 
163     } else {
164       unsigned NumFixedOperands = Desc.NumOperands;
165       SmallSet<uint64_t, 8> Printed;
166       for (unsigned I = 0, E = MI->getNumOperands(); I < E; ++I) {
167         // See if this operand denotes a basic block target.
168         if (I < NumFixedOperands) {
169           // A non-variable_ops operand, check its type.
170           if (Desc.OpInfo[I].OperandType != WebAssembly::OPERAND_BASIC_BLOCK)
171             continue;
172         } else {
173           // A variable_ops operand, which currently can be immediates (used in
174           // br_table) which are basic block targets, or for call instructions
175           // when using -wasm-keep-registers (in which case they are registers,
176           // and should not be processed).
177           if (!MI->getOperand(I).isImm())
178             continue;
179         }
180         uint64_t Depth = MI->getOperand(I).getImm();
181         if (!Printed.insert(Depth).second)
182           continue;
183         if (Depth >= ControlFlowStack.size()) {
184           printAnnotation(OS, "Invalid depth argument!");
185         } else {
186           const auto &Pair = ControlFlowStack.rbegin()[Depth];
187           printAnnotation(OS, utostr(Depth) + ": " +
188                                   (Pair.second ? "up" : "down") + " to label" +
189                                   utostr(Pair.first));
190         }
191       }
192     }
193   }
194 }
195 
196 static std::string toString(const APFloat &FP) {
197   // Print NaNs with custom payloads specially.
198   if (FP.isNaN() && !FP.bitwiseIsEqual(APFloat::getQNaN(FP.getSemantics())) &&
199       !FP.bitwiseIsEqual(
200           APFloat::getQNaN(FP.getSemantics(), /*Negative=*/true))) {
201     APInt AI = FP.bitcastToAPInt();
202     return std::string(AI.isNegative() ? "-" : "") + "nan:0x" +
203            utohexstr(AI.getZExtValue() &
204                          (AI.getBitWidth() == 32 ? INT64_C(0x007fffff)
205                                                  : INT64_C(0x000fffffffffffff)),
206                      /*LowerCase=*/true);
207   }
208 
209   // Use C99's hexadecimal floating-point representation.
210   static const size_t BufBytes = 128;
211   char Buf[BufBytes];
212   auto Written = FP.convertToHexString(
213       Buf, /*HexDigits=*/0, /*UpperCase=*/false, APFloat::rmNearestTiesToEven);
214   (void)Written;
215   assert(Written != 0);
216   assert(Written < BufBytes);
217   return Buf;
218 }
219 
220 void WebAssemblyInstPrinter::printOperand(const MCInst *MI, unsigned OpNo,
221                                           raw_ostream &O, bool IsVariadicDef) {
222   const MCOperand &Op = MI->getOperand(OpNo);
223   if (Op.isReg()) {
224     const MCInstrDesc &Desc = MII.get(MI->getOpcode());
225     unsigned WAReg = Op.getReg();
226     if (int(WAReg) >= 0)
227       printRegName(O, WAReg);
228     else if (OpNo >= Desc.getNumDefs() && !IsVariadicDef)
229       O << "$pop" << WebAssemblyFunctionInfo::getWARegStackId(WAReg);
230     else if (WAReg != WebAssemblyFunctionInfo::UnusedReg)
231       O << "$push" << WebAssemblyFunctionInfo::getWARegStackId(WAReg);
232     else
233       O << "$drop";
234     // Add a '=' suffix if this is a def.
235     if (OpNo < MII.get(MI->getOpcode()).getNumDefs() || IsVariadicDef)
236       O << '=';
237   } else if (Op.isImm()) {
238     O << Op.getImm();
239   } else if (Op.isFPImm()) {
240     const MCInstrDesc &Desc = MII.get(MI->getOpcode());
241     const MCOperandInfo &Info = Desc.OpInfo[OpNo];
242     if (Info.OperandType == WebAssembly::OPERAND_F32IMM) {
243       // TODO: MC converts all floating point immediate operands to double.
244       // This is fine for numeric values, but may cause NaNs to change bits.
245       O << ::toString(APFloat(float(Op.getFPImm())));
246     } else {
247       assert(Info.OperandType == WebAssembly::OPERAND_F64IMM);
248       O << ::toString(APFloat(Op.getFPImm()));
249     }
250   } else {
251     assert(Op.isExpr() && "unknown operand kind in printOperand");
252     // call_indirect instructions have a TYPEINDEX operand that we print
253     // as a signature here, such that the assembler can recover this
254     // information.
255     auto SRE = static_cast<const MCSymbolRefExpr *>(Op.getExpr());
256     if (SRE->getKind() == MCSymbolRefExpr::VK_WASM_TYPEINDEX) {
257       auto &Sym = static_cast<const MCSymbolWasm &>(SRE->getSymbol());
258       O << WebAssembly::signatureToString(Sym.getSignature());
259     } else {
260       Op.getExpr()->print(O, &MAI);
261     }
262   }
263 }
264 
265 void WebAssemblyInstPrinter::printBrList(const MCInst *MI, unsigned OpNo,
266                                          raw_ostream &O) {
267   O << "{";
268   for (unsigned I = OpNo, E = MI->getNumOperands(); I != E; ++I) {
269     if (I != OpNo)
270       O << ", ";
271     O << MI->getOperand(I).getImm();
272   }
273   O << "}";
274 }
275 
276 void WebAssemblyInstPrinter::printWebAssemblyP2AlignOperand(const MCInst *MI,
277                                                             unsigned OpNo,
278                                                             raw_ostream &O) {
279   int64_t Imm = MI->getOperand(OpNo).getImm();
280   if (Imm == WebAssembly::GetDefaultP2Align(MI->getOpcode()))
281     return;
282   O << ":p2align=" << Imm;
283 }
284 
285 void WebAssemblyInstPrinter::printWebAssemblySignatureOperand(const MCInst *MI,
286                                                               unsigned OpNo,
287                                                               raw_ostream &O) {
288   const MCOperand &Op = MI->getOperand(OpNo);
289   if (Op.isImm()) {
290     auto Imm = static_cast<unsigned>(Op.getImm());
291     if (Imm != wasm::WASM_TYPE_NORESULT)
292       O << WebAssembly::anyTypeToString(Imm);
293   } else {
294     auto Expr = cast<MCSymbolRefExpr>(Op.getExpr());
295     auto *Sym = cast<MCSymbolWasm>(&Expr->getSymbol());
296     if (Sym->getSignature()) {
297       O << WebAssembly::signatureToString(Sym->getSignature());
298     } else {
299       // Disassembler does not currently produce a signature
300       O << "unknown_type";
301     }
302   }
303 }
304 
305 // We have various enums representing a subset of these types, use this
306 // function to convert any of them to text.
307 const char *WebAssembly::anyTypeToString(unsigned Ty) {
308   switch (Ty) {
309   case wasm::WASM_TYPE_I32:
310     return "i32";
311   case wasm::WASM_TYPE_I64:
312     return "i64";
313   case wasm::WASM_TYPE_F32:
314     return "f32";
315   case wasm::WASM_TYPE_F64:
316     return "f64";
317   case wasm::WASM_TYPE_V128:
318     return "v128";
319   case wasm::WASM_TYPE_FUNCREF:
320     return "funcref";
321   case wasm::WASM_TYPE_FUNC:
322     return "func";
323   case wasm::WASM_TYPE_EXNREF:
324     return "exnref";
325   case wasm::WASM_TYPE_NORESULT:
326     return "void";
327   default:
328     return "invalid_type";
329   }
330 }
331 
332 const char *WebAssembly::typeToString(wasm::ValType Ty) {
333   return anyTypeToString(static_cast<unsigned>(Ty));
334 }
335 
336 std::string WebAssembly::typeListToString(ArrayRef<wasm::ValType> List) {
337   std::string S;
338   for (auto &Ty : List) {
339     if (&Ty != &List[0]) S += ", ";
340     S += WebAssembly::typeToString(Ty);
341   }
342   return S;
343 }
344 
345 std::string WebAssembly::signatureToString(const wasm::WasmSignature *Sig) {
346   std::string S("(");
347   S += typeListToString(Sig->Params);
348   S += ") -> (";
349   S += typeListToString(Sig->Returns);
350   S += ")";
351   return S;
352 }
353