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 EHPadStack.push_back(ControlFlowCounter++); 108 return; 109 110 case WebAssembly::END_LOOP: 111 case WebAssembly::END_LOOP_S: 112 if (ControlFlowStack.empty()) { 113 printAnnotation(OS, "End marker mismatch!"); 114 } else { 115 ControlFlowStack.pop_back(); 116 } 117 return; 118 119 case WebAssembly::END_BLOCK: 120 case WebAssembly::END_BLOCK_S: 121 if (ControlFlowStack.empty()) { 122 printAnnotation(OS, "End marker mismatch!"); 123 } else { 124 printAnnotation( 125 OS, "label" + utostr(ControlFlowStack.pop_back_val().first) + ':'); 126 } 127 return; 128 129 case WebAssembly::END_TRY: 130 case WebAssembly::END_TRY_S: 131 if (ControlFlowStack.empty()) { 132 printAnnotation(OS, "End marker mismatch!"); 133 } else { 134 printAnnotation( 135 OS, "label" + utostr(ControlFlowStack.pop_back_val().first) + ':'); 136 } 137 return; 138 139 case WebAssembly::CATCH: 140 case WebAssembly::CATCH_S: 141 case WebAssembly::CATCH_ALL: 142 case WebAssembly::CATCH_ALL_S: 143 if (EHPadStack.empty()) { 144 printAnnotation(OS, "try-catch mismatch!"); 145 } else { 146 printAnnotation(OS, "catch" + utostr(EHPadStack.pop_back_val()) + ':'); 147 } 148 return; 149 150 case WebAssembly::RETHROW: 151 case WebAssembly::RETHROW_S: 152 // 'rethrow' rethrows to the nearest enclosing catch scope, if any. If 153 // there's no enclosing catch scope, it throws up to the caller. 154 if (EHPadStack.empty()) { 155 printAnnotation(OS, "to caller"); 156 } else { 157 printAnnotation(OS, "down to catch" + utostr(EHPadStack.back())); 158 } 159 return; 160 } 161 162 // Annotate any control flow label references. 163 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 static std::string toString(const APFloat &FP) { 196 // Print NaNs with custom payloads specially. 197 if (FP.isNaN() && !FP.bitwiseIsEqual(APFloat::getQNaN(FP.getSemantics())) && 198 !FP.bitwiseIsEqual( 199 APFloat::getQNaN(FP.getSemantics(), /*Negative=*/true))) { 200 APInt AI = FP.bitcastToAPInt(); 201 return std::string(AI.isNegative() ? "-" : "") + "nan:0x" + 202 utohexstr(AI.getZExtValue() & 203 (AI.getBitWidth() == 32 ? INT64_C(0x007fffff) 204 : INT64_C(0x000fffffffffffff)), 205 /*LowerCase=*/true); 206 } 207 208 // Use C99's hexadecimal floating-point representation. 209 static const size_t BufBytes = 128; 210 char Buf[BufBytes]; 211 auto Written = FP.convertToHexString( 212 Buf, /*HexDigits=*/0, /*UpperCase=*/false, APFloat::rmNearestTiesToEven); 213 (void)Written; 214 assert(Written != 0); 215 assert(Written < BufBytes); 216 return Buf; 217 } 218 219 void WebAssemblyInstPrinter::printOperand(const MCInst *MI, unsigned OpNo, 220 raw_ostream &O, bool IsVariadicDef) { 221 const MCOperand &Op = MI->getOperand(OpNo); 222 if (Op.isReg()) { 223 const MCInstrDesc &Desc = MII.get(MI->getOpcode()); 224 unsigned WAReg = Op.getReg(); 225 if (int(WAReg) >= 0) 226 printRegName(O, WAReg); 227 else if (OpNo >= Desc.getNumDefs() && !IsVariadicDef) 228 O << "$pop" << WebAssemblyFunctionInfo::getWARegStackId(WAReg); 229 else if (WAReg != WebAssemblyFunctionInfo::UnusedReg) 230 O << "$push" << WebAssemblyFunctionInfo::getWARegStackId(WAReg); 231 else 232 O << "$drop"; 233 // Add a '=' suffix if this is a def. 234 if (OpNo < MII.get(MI->getOpcode()).getNumDefs() || IsVariadicDef) 235 O << '='; 236 } else if (Op.isImm()) { 237 O << Op.getImm(); 238 } else if (Op.isFPImm()) { 239 const MCInstrDesc &Desc = MII.get(MI->getOpcode()); 240 const MCOperandInfo &Info = Desc.OpInfo[OpNo]; 241 if (Info.OperandType == WebAssembly::OPERAND_F32IMM) { 242 // TODO: MC converts all floating point immediate operands to double. 243 // This is fine for numeric values, but may cause NaNs to change bits. 244 O << ::toString(APFloat(float(Op.getFPImm()))); 245 } else { 246 assert(Info.OperandType == WebAssembly::OPERAND_F64IMM); 247 O << ::toString(APFloat(Op.getFPImm())); 248 } 249 } else { 250 assert(Op.isExpr() && "unknown operand kind in printOperand"); 251 // call_indirect instructions have a TYPEINDEX operand that we print 252 // as a signature here, such that the assembler can recover this 253 // information. 254 auto SRE = static_cast<const MCSymbolRefExpr *>(Op.getExpr()); 255 if (SRE->getKind() == MCSymbolRefExpr::VK_WASM_TYPEINDEX) { 256 auto &Sym = static_cast<const MCSymbolWasm &>(SRE->getSymbol()); 257 O << WebAssembly::signatureToString(Sym.getSignature()); 258 } else { 259 Op.getExpr()->print(O, &MAI); 260 } 261 } 262 } 263 264 void WebAssemblyInstPrinter::printBrList(const MCInst *MI, unsigned OpNo, 265 raw_ostream &O) { 266 O << "{"; 267 for (unsigned I = OpNo, E = MI->getNumOperands(); I != E; ++I) { 268 if (I != OpNo) 269 O << ", "; 270 O << MI->getOperand(I).getImm(); 271 } 272 O << "}"; 273 } 274 275 void WebAssemblyInstPrinter::printWebAssemblyP2AlignOperand(const MCInst *MI, 276 unsigned OpNo, 277 raw_ostream &O) { 278 int64_t Imm = MI->getOperand(OpNo).getImm(); 279 if (Imm == WebAssembly::GetDefaultP2Align(MI->getOpcode())) 280 return; 281 O << ":p2align=" << Imm; 282 } 283 284 void WebAssemblyInstPrinter::printWebAssemblySignatureOperand(const MCInst *MI, 285 unsigned OpNo, 286 raw_ostream &O) { 287 const MCOperand &Op = MI->getOperand(OpNo); 288 if (Op.isImm()) { 289 auto Imm = static_cast<unsigned>(Op.getImm()); 290 if (Imm != wasm::WASM_TYPE_NORESULT) 291 O << WebAssembly::anyTypeToString(Imm); 292 } else { 293 auto Expr = cast<MCSymbolRefExpr>(Op.getExpr()); 294 auto *Sym = cast<MCSymbolWasm>(&Expr->getSymbol()); 295 if (Sym->getSignature()) { 296 O << WebAssembly::signatureToString(Sym->getSignature()); 297 } else { 298 // Disassembler does not currently produce a signature 299 O << "unknown_type"; 300 } 301 } 302 } 303 304 void WebAssemblyInstPrinter::printWebAssemblyHeapTypeOperand(const MCInst *MI, 305 unsigned OpNo, 306 raw_ostream &O) { 307 const MCOperand &Op = MI->getOperand(OpNo); 308 if (Op.isImm()) { 309 switch (Op.getImm()) { 310 case long(wasm::ValType::EXTERNREF): 311 O << "extern"; 312 break; 313 case long(wasm::ValType::FUNCREF): 314 O << "func"; 315 break; 316 default: 317 O << "unsupported_heap_type_value"; 318 break; 319 } 320 } else { 321 // Typed function references and other subtypes of funcref and externref 322 // currently unimplemented. 323 O << "unsupported_heap_type_operand"; 324 } 325 } 326 327 // We have various enums representing a subset of these types, use this 328 // function to convert any of them to text. 329 const char *WebAssembly::anyTypeToString(unsigned Ty) { 330 switch (Ty) { 331 case wasm::WASM_TYPE_I32: 332 return "i32"; 333 case wasm::WASM_TYPE_I64: 334 return "i64"; 335 case wasm::WASM_TYPE_F32: 336 return "f32"; 337 case wasm::WASM_TYPE_F64: 338 return "f64"; 339 case wasm::WASM_TYPE_V128: 340 return "v128"; 341 case wasm::WASM_TYPE_FUNCREF: 342 return "funcref"; 343 case wasm::WASM_TYPE_EXTERNREF: 344 return "externref"; 345 case wasm::WASM_TYPE_FUNC: 346 return "func"; 347 case wasm::WASM_TYPE_NORESULT: 348 return "void"; 349 default: 350 return "invalid_type"; 351 } 352 } 353 354 const char *WebAssembly::typeToString(wasm::ValType Ty) { 355 return anyTypeToString(static_cast<unsigned>(Ty)); 356 } 357 358 std::string WebAssembly::typeListToString(ArrayRef<wasm::ValType> List) { 359 std::string S; 360 for (auto &Ty : List) { 361 if (&Ty != &List[0]) S += ", "; 362 S += WebAssembly::typeToString(Ty); 363 } 364 return S; 365 } 366 367 std::string WebAssembly::signatureToString(const wasm::WasmSignature *Sig) { 368 std::string S("("); 369 S += typeListToString(Sig->Params); 370 S += ") -> ("; 371 S += typeListToString(Sig->Returns); 372 S += ")"; 373 return S; 374 } 375