xref: /llvm-project/llvm/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyInstPrinter.cpp (revision 35f5f797a616c0eb8d6ae23ca24e3b80d3e3efdf)
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       return;
98 
99     case WebAssembly::BLOCK:
100     case WebAssembly::BLOCK_S:
101       ControlFlowStack.push_back(std::make_pair(ControlFlowCounter++, false));
102       return;
103 
104     case WebAssembly::TRY:
105     case WebAssembly::TRY_S:
106       ControlFlowStack.push_back(std::make_pair(ControlFlowCounter, false));
107       TryStack.push_back(ControlFlowCounter++);
108       EHInstStack.push_back(TRY);
109       return;
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       return;
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       return;
129 
130     case WebAssembly::END_TRY:
131     case WebAssembly::END_TRY_S:
132       if (ControlFlowStack.empty() || EHInstStack.empty()) {
133         printAnnotation(OS, "End marker mismatch!");
134       } else {
135         printAnnotation(
136             OS, "label" + utostr(ControlFlowStack.pop_back_val().first) + ':');
137         EHInstStack.pop_back();
138       }
139       return;
140 
141     case WebAssembly::CATCH:
142     case WebAssembly::CATCH_S:
143     case WebAssembly::CATCH_ALL:
144     case WebAssembly::CATCH_ALL_S:
145       // There can be multiple catch instructions for one try instruction, so
146       // we print a label only for the first 'catch' label.
147       if (EHInstStack.empty()) {
148         printAnnotation(OS, "try-catch mismatch!");
149       } else if (EHInstStack.back() == CATCH_ALL) {
150         printAnnotation(OS, "catch/catch_all cannot occur after catch_all");
151       } else if (EHInstStack.back() == TRY) {
152         if (TryStack.empty()) {
153           printAnnotation(OS, "try-catch mismatch!");
154         } else {
155           printAnnotation(OS, "catch" + utostr(TryStack.pop_back_val()) + ':');
156         }
157         EHInstStack.pop_back();
158         if (Opc == WebAssembly::CATCH || Opc == WebAssembly::CATCH_S) {
159           EHInstStack.push_back(CATCH);
160         } else {
161           EHInstStack.push_back(CATCH_ALL);
162         }
163       }
164       return;
165 
166     case WebAssembly::RETHROW:
167     case WebAssembly::RETHROW_S:
168       // 'rethrow' rethrows to the nearest enclosing catch scope, if any. If
169       // there's no enclosing catch scope, it throws up to the caller.
170       if (TryStack.empty()) {
171         printAnnotation(OS, "to caller");
172       } else {
173         printAnnotation(OS, "down to catch" + utostr(TryStack.back()));
174       }
175       return;
176 
177     case WebAssembly::DELEGATE:
178     case WebAssembly::DELEGATE_S:
179       if (ControlFlowStack.empty() || TryStack.empty() || EHInstStack.empty()) {
180         printAnnotation(OS, "try-delegate mismatch!");
181       } else {
182         // 'delegate' is
183         // 1. A marker for the end of block label
184         // 2. A destination for throwing instructions
185         // 3. An instruction that itself rethrows to another 'catch'
186         assert(ControlFlowStack.back().first == TryStack.back());
187         std::string Label = "label/catch" +
188                             utostr(ControlFlowStack.pop_back_val().first) +
189                             ": ";
190         TryStack.pop_back();
191         EHInstStack.pop_back();
192         uint64_t Depth = MI->getOperand(0).getImm();
193         if (Depth >= ControlFlowStack.size()) {
194           Label += "to caller";
195         } else {
196           const auto &Pair = ControlFlowStack.rbegin()[Depth];
197           if (Pair.second)
198             printAnnotation(OS, "delegate cannot target a loop");
199           else
200             Label += "down to catch" + utostr(Pair.first);
201         }
202         printAnnotation(OS, Label);
203       }
204       return;
205     }
206 
207     // Annotate any control flow label references.
208 
209     unsigned NumFixedOperands = Desc.NumOperands;
210     SmallSet<uint64_t, 8> Printed;
211     for (unsigned I = 0, E = MI->getNumOperands(); I < E; ++I) {
212       // See if this operand denotes a basic block target.
213       if (I < NumFixedOperands) {
214         // A non-variable_ops operand, check its type.
215         if (Desc.OpInfo[I].OperandType != WebAssembly::OPERAND_BASIC_BLOCK)
216           continue;
217       } else {
218         // A variable_ops operand, which currently can be immediates (used in
219         // br_table) which are basic block targets, or for call instructions
220         // when using -wasm-keep-registers (in which case they are registers,
221         // and should not be processed).
222         if (!MI->getOperand(I).isImm())
223           continue;
224       }
225       uint64_t Depth = MI->getOperand(I).getImm();
226       if (!Printed.insert(Depth).second)
227         continue;
228       if (Depth >= ControlFlowStack.size()) {
229         printAnnotation(OS, "Invalid depth argument!");
230       } else {
231         const auto &Pair = ControlFlowStack.rbegin()[Depth];
232         printAnnotation(OS, utostr(Depth) + ": " +
233                                 (Pair.second ? "up" : "down") + " to label" +
234                                 utostr(Pair.first));
235       }
236     }
237   }
238 }
239 
240 static std::string toString(const APFloat &FP) {
241   // Print NaNs with custom payloads specially.
242   if (FP.isNaN() && !FP.bitwiseIsEqual(APFloat::getQNaN(FP.getSemantics())) &&
243       !FP.bitwiseIsEqual(
244           APFloat::getQNaN(FP.getSemantics(), /*Negative=*/true))) {
245     APInt AI = FP.bitcastToAPInt();
246     return std::string(AI.isNegative() ? "-" : "") + "nan:0x" +
247            utohexstr(AI.getZExtValue() &
248                          (AI.getBitWidth() == 32 ? INT64_C(0x007fffff)
249                                                  : INT64_C(0x000fffffffffffff)),
250                      /*LowerCase=*/true);
251   }
252 
253   // Use C99's hexadecimal floating-point representation.
254   static const size_t BufBytes = 128;
255   char Buf[BufBytes];
256   auto Written = FP.convertToHexString(
257       Buf, /*HexDigits=*/0, /*UpperCase=*/false, APFloat::rmNearestTiesToEven);
258   (void)Written;
259   assert(Written != 0);
260   assert(Written < BufBytes);
261   return Buf;
262 }
263 
264 void WebAssemblyInstPrinter::printOperand(const MCInst *MI, unsigned OpNo,
265                                           raw_ostream &O, bool IsVariadicDef) {
266   const MCOperand &Op = MI->getOperand(OpNo);
267   if (Op.isReg()) {
268     const MCInstrDesc &Desc = MII.get(MI->getOpcode());
269     unsigned WAReg = Op.getReg();
270     if (int(WAReg) >= 0)
271       printRegName(O, WAReg);
272     else if (OpNo >= Desc.getNumDefs() && !IsVariadicDef)
273       O << "$pop" << WebAssemblyFunctionInfo::getWARegStackId(WAReg);
274     else if (WAReg != WebAssemblyFunctionInfo::UnusedReg)
275       O << "$push" << WebAssemblyFunctionInfo::getWARegStackId(WAReg);
276     else
277       O << "$drop";
278     // Add a '=' suffix if this is a def.
279     if (OpNo < MII.get(MI->getOpcode()).getNumDefs() || IsVariadicDef)
280       O << '=';
281   } else if (Op.isImm()) {
282     O << Op.getImm();
283   } else if (Op.isSFPImm()) {
284     O << ::toString(APFloat(bit_cast<float>(Op.getSFPImm())));
285   } else if (Op.isDFPImm()) {
286     O << ::toString(APFloat(bit_cast<double>(Op.getDFPImm())));
287   } else {
288     assert(Op.isExpr() && "unknown operand kind in printOperand");
289     // call_indirect instructions have a TYPEINDEX operand that we print
290     // as a signature here, such that the assembler can recover this
291     // information.
292     auto SRE = static_cast<const MCSymbolRefExpr *>(Op.getExpr());
293     if (SRE->getKind() == MCSymbolRefExpr::VK_WASM_TYPEINDEX) {
294       auto &Sym = static_cast<const MCSymbolWasm &>(SRE->getSymbol());
295       O << WebAssembly::signatureToString(Sym.getSignature());
296     } else {
297       Op.getExpr()->print(O, &MAI);
298     }
299   }
300 }
301 
302 void WebAssemblyInstPrinter::printBrList(const MCInst *MI, unsigned OpNo,
303                                          raw_ostream &O) {
304   O << "{";
305   for (unsigned I = OpNo, E = MI->getNumOperands(); I != E; ++I) {
306     if (I != OpNo)
307       O << ", ";
308     O << MI->getOperand(I).getImm();
309   }
310   O << "}";
311 }
312 
313 void WebAssemblyInstPrinter::printWebAssemblyP2AlignOperand(const MCInst *MI,
314                                                             unsigned OpNo,
315                                                             raw_ostream &O) {
316   int64_t Imm = MI->getOperand(OpNo).getImm();
317   if (Imm == WebAssembly::GetDefaultP2Align(MI->getOpcode()))
318     return;
319   O << ":p2align=" << Imm;
320 }
321 
322 void WebAssemblyInstPrinter::printWebAssemblySignatureOperand(const MCInst *MI,
323                                                               unsigned OpNo,
324                                                               raw_ostream &O) {
325   const MCOperand &Op = MI->getOperand(OpNo);
326   if (Op.isImm()) {
327     auto Imm = static_cast<unsigned>(Op.getImm());
328     if (Imm != wasm::WASM_TYPE_NORESULT)
329       O << WebAssembly::anyTypeToString(Imm);
330   } else {
331     auto Expr = cast<MCSymbolRefExpr>(Op.getExpr());
332     auto *Sym = cast<MCSymbolWasm>(&Expr->getSymbol());
333     if (Sym->getSignature()) {
334       O << WebAssembly::signatureToString(Sym->getSignature());
335     } else {
336       // Disassembler does not currently produce a signature
337       O << "unknown_type";
338     }
339   }
340 }
341 
342 void WebAssemblyInstPrinter::printWebAssemblyHeapTypeOperand(const MCInst *MI,
343                                                              unsigned OpNo,
344                                                              raw_ostream &O) {
345   const MCOperand &Op = MI->getOperand(OpNo);
346   if (Op.isImm()) {
347     switch (Op.getImm()) {
348     case long(wasm::ValType::EXTERNREF):
349       O << "extern";
350       break;
351     case long(wasm::ValType::FUNCREF):
352       O << "func";
353       break;
354     default:
355       O << "unsupported_heap_type_value";
356       break;
357     }
358   } else {
359     // Typed function references and other subtypes of funcref and externref
360     // currently unimplemented.
361     O << "unsupported_heap_type_operand";
362   }
363 }
364 
365 // We have various enums representing a subset of these types, use this
366 // function to convert any of them to text.
367 const char *WebAssembly::anyTypeToString(unsigned Ty) {
368   switch (Ty) {
369   case wasm::WASM_TYPE_I32:
370     return "i32";
371   case wasm::WASM_TYPE_I64:
372     return "i64";
373   case wasm::WASM_TYPE_F32:
374     return "f32";
375   case wasm::WASM_TYPE_F64:
376     return "f64";
377   case wasm::WASM_TYPE_V128:
378     return "v128";
379   case wasm::WASM_TYPE_FUNCREF:
380     return "funcref";
381   case wasm::WASM_TYPE_EXTERNREF:
382     return "externref";
383   case wasm::WASM_TYPE_FUNC:
384     return "func";
385   case wasm::WASM_TYPE_NORESULT:
386     return "void";
387   default:
388     return "invalid_type";
389   }
390 }
391 
392 const char *WebAssembly::typeToString(wasm::ValType Ty) {
393   return anyTypeToString(static_cast<unsigned>(Ty));
394 }
395 
396 std::string WebAssembly::typeListToString(ArrayRef<wasm::ValType> List) {
397   std::string S;
398   for (auto &Ty : List) {
399     if (&Ty != &List[0]) S += ", ";
400     S += WebAssembly::typeToString(Ty);
401   }
402   return S;
403 }
404 
405 std::string WebAssembly::signatureToString(const wasm::WasmSignature *Sig) {
406   std::string S("(");
407   S += typeListToString(Sig->Params);
408   S += ") -> (";
409   S += typeListToString(Sig->Returns);
410   S += ")";
411   return S;
412 }
413