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