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