Path: blob/main/contrib/llvm-project/llvm/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyInstPrinter.cpp
35293 views
//=- WebAssemblyInstPrinter.cpp - WebAssembly assembly instruction printing -=//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7///8/// \file9/// Print MCInst instructions to wasm format.10///11//===----------------------------------------------------------------------===//1213#include "MCTargetDesc/WebAssemblyInstPrinter.h"14#include "MCTargetDesc/WebAssemblyMCTargetDesc.h"15#include "MCTargetDesc/WebAssemblyMCTypeUtilities.h"16#include "WebAssembly.h"17#include "llvm/ADT/APFloat.h"18#include "llvm/ADT/SmallSet.h"19#include "llvm/ADT/StringExtras.h"20#include "llvm/MC/MCExpr.h"21#include "llvm/MC/MCInst.h"22#include "llvm/MC/MCInstrInfo.h"23#include "llvm/MC/MCSubtargetInfo.h"24#include "llvm/MC/MCSymbol.h"25#include "llvm/MC/MCSymbolWasm.h"26#include "llvm/Support/Casting.h"27#include "llvm/Support/ErrorHandling.h"28#include "llvm/Support/FormattedStream.h"29using namespace llvm;3031#define DEBUG_TYPE "asm-printer"3233#include "WebAssemblyGenAsmWriter.inc"3435WebAssemblyInstPrinter::WebAssemblyInstPrinter(const MCAsmInfo &MAI,36const MCInstrInfo &MII,37const MCRegisterInfo &MRI)38: MCInstPrinter(MAI, MII, MRI) {}3940void WebAssemblyInstPrinter::printRegName(raw_ostream &OS,41MCRegister Reg) const {42assert(Reg.id() != WebAssembly::UnusedReg);43// Note that there's an implicit local.get/local.set here!44OS << "$" << Reg.id();45}4647void WebAssemblyInstPrinter::printInst(const MCInst *MI, uint64_t Address,48StringRef Annot,49const MCSubtargetInfo &STI,50raw_ostream &OS) {51switch (MI->getOpcode()) {52case WebAssembly::CALL_INDIRECT_S:53case WebAssembly::RET_CALL_INDIRECT_S: {54// A special case for call_indirect (and ret_call_indirect), if the table55// operand is a symbol: the order of the type and table operands is inverted56// in the text format relative to the binary format. Otherwise if table the57// operand isn't a symbol, then we have an MVP compilation unit, and the58// table shouldn't appear in the output.59OS << "\t";60OS << getMnemonic(MI).first;61OS << " ";6263assert(MI->getNumOperands() == 2);64const unsigned TypeOperand = 0;65const unsigned TableOperand = 1;66if (MI->getOperand(TableOperand).isExpr()) {67printOperand(MI, TableOperand, OS);68OS << ", ";69} else {70assert(MI->getOperand(TableOperand).getImm() == 0);71}72printOperand(MI, TypeOperand, OS);73break;74}75default:76// Print the instruction (this uses the AsmStrings from the .td files).77printInstruction(MI, Address, OS);78break;79}8081// Print any additional variadic operands.82const MCInstrDesc &Desc = MII.get(MI->getOpcode());83if (Desc.isVariadic()) {84if ((Desc.getNumOperands() == 0 && MI->getNumOperands() > 0) ||85Desc.variadicOpsAreDefs())86OS << "\t";87unsigned Start = Desc.getNumOperands();88unsigned NumVariadicDefs = 0;89if (Desc.variadicOpsAreDefs()) {90// The number of variadic defs is encoded in an immediate by MCInstLower91NumVariadicDefs = MI->getOperand(0).getImm();92Start = 1;93}94bool NeedsComma = Desc.getNumOperands() > 0 && !Desc.variadicOpsAreDefs();95for (auto I = Start, E = MI->getNumOperands(); I < E; ++I) {96if (MI->getOpcode() == WebAssembly::CALL_INDIRECT &&97I - Start == NumVariadicDefs) {98// Skip type and table arguments when printing for tests.99++I;100continue;101}102if (NeedsComma)103OS << ", ";104printOperand(MI, I, OS, I - Start < NumVariadicDefs);105NeedsComma = true;106}107}108109// Print any added annotation.110printAnnotation(OS, Annot);111112if (CommentStream) {113// Observe any effects on the control flow stack, for use in annotating114// control flow label references.115unsigned Opc = MI->getOpcode();116switch (Opc) {117default:118break;119120case WebAssembly::LOOP:121case WebAssembly::LOOP_S:122printAnnotation(OS, "label" + utostr(ControlFlowCounter) + ':');123ControlFlowStack.push_back(std::make_pair(ControlFlowCounter++, true));124return;125126case WebAssembly::BLOCK:127case WebAssembly::BLOCK_S:128ControlFlowStack.push_back(std::make_pair(ControlFlowCounter++, false));129return;130131case WebAssembly::TRY:132case WebAssembly::TRY_S:133ControlFlowStack.push_back(std::make_pair(ControlFlowCounter, false));134TryStack.push_back(ControlFlowCounter++);135EHInstStack.push_back(TRY);136return;137138case WebAssembly::END_LOOP:139case WebAssembly::END_LOOP_S:140if (ControlFlowStack.empty()) {141printAnnotation(OS, "End marker mismatch!");142} else {143ControlFlowStack.pop_back();144}145return;146147case WebAssembly::END_BLOCK:148case WebAssembly::END_BLOCK_S:149if (ControlFlowStack.empty()) {150printAnnotation(OS, "End marker mismatch!");151} else {152printAnnotation(153OS, "label" + utostr(ControlFlowStack.pop_back_val().first) + ':');154}155return;156157case WebAssembly::END_TRY:158case WebAssembly::END_TRY_S:159if (ControlFlowStack.empty() || EHInstStack.empty()) {160printAnnotation(OS, "End marker mismatch!");161} else {162printAnnotation(163OS, "label" + utostr(ControlFlowStack.pop_back_val().first) + ':');164EHInstStack.pop_back();165}166return;167168case WebAssembly::CATCH:169case WebAssembly::CATCH_S:170case WebAssembly::CATCH_ALL:171case WebAssembly::CATCH_ALL_S:172// There can be multiple catch instructions for one try instruction, so173// we print a label only for the first 'catch' label.174if (EHInstStack.empty()) {175printAnnotation(OS, "try-catch mismatch!");176} else if (EHInstStack.back() == CATCH_ALL) {177printAnnotation(OS, "catch/catch_all cannot occur after catch_all");178} else if (EHInstStack.back() == TRY) {179if (TryStack.empty()) {180printAnnotation(OS, "try-catch mismatch!");181} else {182printAnnotation(OS, "catch" + utostr(TryStack.pop_back_val()) + ':');183}184EHInstStack.pop_back();185if (Opc == WebAssembly::CATCH || Opc == WebAssembly::CATCH_S) {186EHInstStack.push_back(CATCH);187} else {188EHInstStack.push_back(CATCH_ALL);189}190}191return;192193case WebAssembly::RETHROW:194case WebAssembly::RETHROW_S:195// 'rethrow' rethrows to the nearest enclosing catch scope, if any. If196// there's no enclosing catch scope, it throws up to the caller.197if (TryStack.empty()) {198printAnnotation(OS, "to caller");199} else {200printAnnotation(OS, "down to catch" + utostr(TryStack.back()));201}202return;203204case WebAssembly::DELEGATE:205case WebAssembly::DELEGATE_S:206if (ControlFlowStack.empty() || TryStack.empty() || EHInstStack.empty()) {207printAnnotation(OS, "try-delegate mismatch!");208} else {209// 'delegate' is210// 1. A marker for the end of block label211// 2. A destination for throwing instructions212// 3. An instruction that itself rethrows to another 'catch'213assert(ControlFlowStack.back().first == TryStack.back());214std::string Label = "label/catch" +215utostr(ControlFlowStack.pop_back_val().first) +216": ";217TryStack.pop_back();218EHInstStack.pop_back();219uint64_t Depth = MI->getOperand(0).getImm();220if (Depth >= ControlFlowStack.size()) {221Label += "to caller";222} else {223const auto &Pair = ControlFlowStack.rbegin()[Depth];224if (Pair.second)225printAnnotation(OS, "delegate cannot target a loop");226else227Label += "down to catch" + utostr(Pair.first);228}229printAnnotation(OS, Label);230}231return;232}233234// Annotate any control flow label references.235236unsigned NumFixedOperands = Desc.NumOperands;237SmallSet<uint64_t, 8> Printed;238for (unsigned I = 0, E = MI->getNumOperands(); I < E; ++I) {239// See if this operand denotes a basic block target.240if (I < NumFixedOperands) {241// A non-variable_ops operand, check its type.242if (Desc.operands()[I].OperandType != WebAssembly::OPERAND_BASIC_BLOCK)243continue;244} else {245// A variable_ops operand, which currently can be immediates (used in246// br_table) which are basic block targets, or for call instructions247// when using -wasm-keep-registers (in which case they are registers,248// and should not be processed).249if (!MI->getOperand(I).isImm())250continue;251}252uint64_t Depth = MI->getOperand(I).getImm();253if (!Printed.insert(Depth).second)254continue;255if (Depth >= ControlFlowStack.size()) {256printAnnotation(OS, "Invalid depth argument!");257} else {258const auto &Pair = ControlFlowStack.rbegin()[Depth];259printAnnotation(OS, utostr(Depth) + ": " +260(Pair.second ? "up" : "down") + " to label" +261utostr(Pair.first));262}263}264}265}266267static std::string toString(const APFloat &FP) {268// Print NaNs with custom payloads specially.269if (FP.isNaN() && !FP.bitwiseIsEqual(APFloat::getQNaN(FP.getSemantics())) &&270!FP.bitwiseIsEqual(271APFloat::getQNaN(FP.getSemantics(), /*Negative=*/true))) {272APInt AI = FP.bitcastToAPInt();273return std::string(AI.isNegative() ? "-" : "") + "nan:0x" +274utohexstr(AI.getZExtValue() &275(AI.getBitWidth() == 32 ? INT64_C(0x007fffff)276: INT64_C(0x000fffffffffffff)),277/*LowerCase=*/true);278}279280// Use C99's hexadecimal floating-point representation.281static const size_t BufBytes = 128;282char Buf[BufBytes];283auto Written = FP.convertToHexString(284Buf, /*HexDigits=*/0, /*UpperCase=*/false, APFloat::rmNearestTiesToEven);285(void)Written;286assert(Written != 0);287assert(Written < BufBytes);288return Buf;289}290291void WebAssemblyInstPrinter::printOperand(const MCInst *MI, unsigned OpNo,292raw_ostream &O, bool IsVariadicDef) {293const MCOperand &Op = MI->getOperand(OpNo);294if (Op.isReg()) {295const MCInstrDesc &Desc = MII.get(MI->getOpcode());296unsigned WAReg = Op.getReg();297if (int(WAReg) >= 0)298printRegName(O, WAReg);299else if (OpNo >= Desc.getNumDefs() && !IsVariadicDef)300O << "$pop" << WebAssembly::getWARegStackId(WAReg);301else if (WAReg != WebAssembly::UnusedReg)302O << "$push" << WebAssembly::getWARegStackId(WAReg);303else304O << "$drop";305// Add a '=' suffix if this is a def.306if (OpNo < MII.get(MI->getOpcode()).getNumDefs() || IsVariadicDef)307O << '=';308} else if (Op.isImm()) {309O << Op.getImm();310} else if (Op.isSFPImm()) {311O << ::toString(APFloat(APFloat::IEEEsingle(), APInt(32, Op.getSFPImm())));312} else if (Op.isDFPImm()) {313O << ::toString(APFloat(APFloat::IEEEdouble(), APInt(64, Op.getDFPImm())));314} else {315assert(Op.isExpr() && "unknown operand kind in printOperand");316// call_indirect instructions have a TYPEINDEX operand that we print317// as a signature here, such that the assembler can recover this318// information.319auto SRE = static_cast<const MCSymbolRefExpr *>(Op.getExpr());320if (SRE->getKind() == MCSymbolRefExpr::VK_WASM_TYPEINDEX) {321auto &Sym = static_cast<const MCSymbolWasm &>(SRE->getSymbol());322O << WebAssembly::signatureToString(Sym.getSignature());323} else {324Op.getExpr()->print(O, &MAI);325}326}327}328329void WebAssemblyInstPrinter::printBrList(const MCInst *MI, unsigned OpNo,330raw_ostream &O) {331O << "{";332for (unsigned I = OpNo, E = MI->getNumOperands(); I != E; ++I) {333if (I != OpNo)334O << ", ";335O << MI->getOperand(I).getImm();336}337O << "}";338}339340void WebAssemblyInstPrinter::printWebAssemblyP2AlignOperand(const MCInst *MI,341unsigned OpNo,342raw_ostream &O) {343int64_t Imm = MI->getOperand(OpNo).getImm();344if (Imm == WebAssembly::GetDefaultP2Align(MI->getOpcode()))345return;346O << ":p2align=" << Imm;347}348349void WebAssemblyInstPrinter::printWebAssemblySignatureOperand(const MCInst *MI,350unsigned OpNo,351raw_ostream &O) {352const MCOperand &Op = MI->getOperand(OpNo);353if (Op.isImm()) {354auto Imm = static_cast<unsigned>(Op.getImm());355if (Imm != wasm::WASM_TYPE_NORESULT)356O << WebAssembly::anyTypeToString(Imm);357} else {358auto Expr = cast<MCSymbolRefExpr>(Op.getExpr());359auto *Sym = cast<MCSymbolWasm>(&Expr->getSymbol());360if (Sym->getSignature()) {361O << WebAssembly::signatureToString(Sym->getSignature());362} else {363// Disassembler does not currently produce a signature364O << "unknown_type";365}366}367}368369370