WebAssemblyInstPrinter.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  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. #include "MCTargetDesc/WebAssemblyInstPrinter.h"
  14. #include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
  15. #include "Utils/WebAssemblyTypeUtilities.h"
  16. #include "Utils/WebAssemblyUtilities.h"
  17. #include "WebAssembly.h"
  18. #include "WebAssemblyMachineFunctionInfo.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. #define DEBUG_TYPE "asm-printer"
  31. #include "WebAssemblyGenAsmWriter.inc"
  32. WebAssemblyInstPrinter::WebAssemblyInstPrinter(const MCAsmInfo &MAI,
  33. const MCInstrInfo &MII,
  34. const MCRegisterInfo &MRI)
  35. : MCInstPrinter(MAI, MII, MRI) {}
  36. void WebAssemblyInstPrinter::printRegName(raw_ostream &OS,
  37. MCRegister Reg) const {
  38. assert(Reg.id() != WebAssemblyFunctionInfo::UnusedReg);
  39. // Note that there's an implicit local.get/local.set here!
  40. OS << "$" << Reg.id();
  41. }
  42. void WebAssemblyInstPrinter::printInst(const MCInst *MI, uint64_t Address,
  43. StringRef Annot,
  44. const MCSubtargetInfo &STI,
  45. raw_ostream &OS) {
  46. switch (MI->getOpcode()) {
  47. case WebAssembly::CALL_INDIRECT_S:
  48. case WebAssembly::RET_CALL_INDIRECT_S: {
  49. // A special case for call_indirect (and ret_call_indirect), if the table
  50. // operand is a symbol: the order of the type and table operands is inverted
  51. // in the text format relative to the binary format. Otherwise if table the
  52. // operand isn't a symbol, then we have an MVP compilation unit, and the
  53. // table shouldn't appear in the output.
  54. OS << "\t";
  55. OS << getMnemonic(MI).first;
  56. OS << " ";
  57. assert(MI->getNumOperands() == 2);
  58. const unsigned TypeOperand = 0;
  59. const unsigned TableOperand = 1;
  60. if (MI->getOperand(TableOperand).isExpr()) {
  61. printOperand(MI, TableOperand, OS);
  62. OS << ", ";
  63. } else {
  64. assert(MI->getOperand(TableOperand).getImm() == 0);
  65. }
  66. printOperand(MI, TypeOperand, OS);
  67. break;
  68. }
  69. default:
  70. // Print the instruction (this uses the AsmStrings from the .td files).
  71. printInstruction(MI, Address, OS);
  72. break;
  73. }
  74. // Print any additional variadic operands.
  75. const MCInstrDesc &Desc = MII.get(MI->getOpcode());
  76. if (Desc.isVariadic()) {
  77. if ((Desc.getNumOperands() == 0 && MI->getNumOperands() > 0) ||
  78. Desc.variadicOpsAreDefs())
  79. OS << "\t";
  80. unsigned Start = Desc.getNumOperands();
  81. unsigned NumVariadicDefs = 0;
  82. if (Desc.variadicOpsAreDefs()) {
  83. // The number of variadic defs is encoded in an immediate by MCInstLower
  84. NumVariadicDefs = MI->getOperand(0).getImm();
  85. Start = 1;
  86. }
  87. bool NeedsComma = Desc.getNumOperands() > 0 && !Desc.variadicOpsAreDefs();
  88. for (auto I = Start, E = MI->getNumOperands(); I < E; ++I) {
  89. if (MI->getOpcode() == WebAssembly::CALL_INDIRECT &&
  90. I - Start == NumVariadicDefs) {
  91. // Skip type and table arguments when printing for tests.
  92. ++I;
  93. continue;
  94. }
  95. if (NeedsComma)
  96. OS << ", ";
  97. printOperand(MI, I, OS, I - Start < NumVariadicDefs);
  98. NeedsComma = true;
  99. }
  100. }
  101. // Print any added annotation.
  102. printAnnotation(OS, Annot);
  103. if (CommentStream) {
  104. // Observe any effects on the control flow stack, for use in annotating
  105. // control flow label references.
  106. unsigned Opc = MI->getOpcode();
  107. switch (Opc) {
  108. default:
  109. break;
  110. case WebAssembly::LOOP:
  111. case WebAssembly::LOOP_S:
  112. printAnnotation(OS, "label" + utostr(ControlFlowCounter) + ':');
  113. ControlFlowStack.push_back(std::make_pair(ControlFlowCounter++, true));
  114. return;
  115. case WebAssembly::BLOCK:
  116. case WebAssembly::BLOCK_S:
  117. ControlFlowStack.push_back(std::make_pair(ControlFlowCounter++, false));
  118. return;
  119. case WebAssembly::TRY:
  120. case WebAssembly::TRY_S:
  121. ControlFlowStack.push_back(std::make_pair(ControlFlowCounter, false));
  122. TryStack.push_back(ControlFlowCounter++);
  123. EHInstStack.push_back(TRY);
  124. return;
  125. case WebAssembly::END_LOOP:
  126. case WebAssembly::END_LOOP_S:
  127. if (ControlFlowStack.empty()) {
  128. printAnnotation(OS, "End marker mismatch!");
  129. } else {
  130. ControlFlowStack.pop_back();
  131. }
  132. return;
  133. case WebAssembly::END_BLOCK:
  134. case WebAssembly::END_BLOCK_S:
  135. if (ControlFlowStack.empty()) {
  136. printAnnotation(OS, "End marker mismatch!");
  137. } else {
  138. printAnnotation(
  139. OS, "label" + utostr(ControlFlowStack.pop_back_val().first) + ':');
  140. }
  141. return;
  142. case WebAssembly::END_TRY:
  143. case WebAssembly::END_TRY_S:
  144. if (ControlFlowStack.empty() || EHInstStack.empty()) {
  145. printAnnotation(OS, "End marker mismatch!");
  146. } else {
  147. printAnnotation(
  148. OS, "label" + utostr(ControlFlowStack.pop_back_val().first) + ':');
  149. EHInstStack.pop_back();
  150. }
  151. return;
  152. case WebAssembly::CATCH:
  153. case WebAssembly::CATCH_S:
  154. case WebAssembly::CATCH_ALL:
  155. case WebAssembly::CATCH_ALL_S:
  156. // There can be multiple catch instructions for one try instruction, so
  157. // we print a label only for the first 'catch' label.
  158. if (EHInstStack.empty()) {
  159. printAnnotation(OS, "try-catch mismatch!");
  160. } else if (EHInstStack.back() == CATCH_ALL) {
  161. printAnnotation(OS, "catch/catch_all cannot occur after catch_all");
  162. } else if (EHInstStack.back() == TRY) {
  163. if (TryStack.empty()) {
  164. printAnnotation(OS, "try-catch mismatch!");
  165. } else {
  166. printAnnotation(OS, "catch" + utostr(TryStack.pop_back_val()) + ':');
  167. }
  168. EHInstStack.pop_back();
  169. if (Opc == WebAssembly::CATCH || Opc == WebAssembly::CATCH_S) {
  170. EHInstStack.push_back(CATCH);
  171. } else {
  172. EHInstStack.push_back(CATCH_ALL);
  173. }
  174. }
  175. return;
  176. case WebAssembly::RETHROW:
  177. case WebAssembly::RETHROW_S:
  178. // 'rethrow' rethrows to the nearest enclosing catch scope, if any. If
  179. // there's no enclosing catch scope, it throws up to the caller.
  180. if (TryStack.empty()) {
  181. printAnnotation(OS, "to caller");
  182. } else {
  183. printAnnotation(OS, "down to catch" + utostr(TryStack.back()));
  184. }
  185. return;
  186. case WebAssembly::DELEGATE:
  187. case WebAssembly::DELEGATE_S:
  188. if (ControlFlowStack.empty() || TryStack.empty() || EHInstStack.empty()) {
  189. printAnnotation(OS, "try-delegate mismatch!");
  190. } else {
  191. // 'delegate' is
  192. // 1. A marker for the end of block label
  193. // 2. A destination for throwing instructions
  194. // 3. An instruction that itself rethrows to another 'catch'
  195. assert(ControlFlowStack.back().first == TryStack.back());
  196. std::string Label = "label/catch" +
  197. utostr(ControlFlowStack.pop_back_val().first) +
  198. ": ";
  199. TryStack.pop_back();
  200. EHInstStack.pop_back();
  201. uint64_t Depth = MI->getOperand(0).getImm();
  202. if (Depth >= ControlFlowStack.size()) {
  203. Label += "to caller";
  204. } else {
  205. const auto &Pair = ControlFlowStack.rbegin()[Depth];
  206. if (Pair.second)
  207. printAnnotation(OS, "delegate cannot target a loop");
  208. else
  209. Label += "down to catch" + utostr(Pair.first);
  210. }
  211. printAnnotation(OS, Label);
  212. }
  213. return;
  214. }
  215. // Annotate any control flow label references.
  216. unsigned NumFixedOperands = Desc.NumOperands;
  217. SmallSet<uint64_t, 8> Printed;
  218. for (unsigned I = 0, E = MI->getNumOperands(); I < E; ++I) {
  219. // See if this operand denotes a basic block target.
  220. if (I < NumFixedOperands) {
  221. // A non-variable_ops operand, check its type.
  222. if (Desc.operands()[I].OperandType != WebAssembly::OPERAND_BASIC_BLOCK)
  223. continue;
  224. } else {
  225. // A variable_ops operand, which currently can be immediates (used in
  226. // br_table) which are basic block targets, or for call instructions
  227. // when using -wasm-keep-registers (in which case they are registers,
  228. // and should not be processed).
  229. if (!MI->getOperand(I).isImm())
  230. continue;
  231. }
  232. uint64_t Depth = MI->getOperand(I).getImm();
  233. if (!Printed.insert(Depth).second)
  234. continue;
  235. if (Depth >= ControlFlowStack.size()) {
  236. printAnnotation(OS, "Invalid depth argument!");
  237. } else {
  238. const auto &Pair = ControlFlowStack.rbegin()[Depth];
  239. printAnnotation(OS, utostr(Depth) + ": " +
  240. (Pair.second ? "up" : "down") + " to label" +
  241. utostr(Pair.first));
  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. // Use C99's hexadecimal floating-point representation.
  259. static const size_t BufBytes = 128;
  260. char Buf[BufBytes];
  261. auto Written = FP.convertToHexString(
  262. Buf, /*HexDigits=*/0, /*UpperCase=*/false, APFloat::rmNearestTiesToEven);
  263. (void)Written;
  264. assert(Written != 0);
  265. assert(Written < BufBytes);
  266. return Buf;
  267. }
  268. void WebAssemblyInstPrinter::printOperand(const MCInst *MI, unsigned OpNo,
  269. raw_ostream &O, bool IsVariadicDef) {
  270. const MCOperand &Op = MI->getOperand(OpNo);
  271. if (Op.isReg()) {
  272. const MCInstrDesc &Desc = MII.get(MI->getOpcode());
  273. unsigned WAReg = Op.getReg();
  274. if (int(WAReg) >= 0)
  275. printRegName(O, WAReg);
  276. else if (OpNo >= Desc.getNumDefs() && !IsVariadicDef)
  277. O << "$pop" << WebAssemblyFunctionInfo::getWARegStackId(WAReg);
  278. else if (WAReg != WebAssemblyFunctionInfo::UnusedReg)
  279. O << "$push" << WebAssemblyFunctionInfo::getWARegStackId(WAReg);
  280. else
  281. O << "$drop";
  282. // Add a '=' suffix if this is a def.
  283. if (OpNo < MII.get(MI->getOpcode()).getNumDefs() || IsVariadicDef)
  284. O << '=';
  285. } else if (Op.isImm()) {
  286. O << Op.getImm();
  287. } else if (Op.isSFPImm()) {
  288. O << ::toString(APFloat(APFloat::IEEEsingle(), APInt(32, Op.getSFPImm())));
  289. } else if (Op.isDFPImm()) {
  290. O << ::toString(APFloat(APFloat::IEEEdouble(), APInt(64, Op.getDFPImm())));
  291. } else {
  292. assert(Op.isExpr() && "unknown operand kind in printOperand");
  293. // call_indirect instructions have a TYPEINDEX operand that we print
  294. // as a signature here, such that the assembler can recover this
  295. // information.
  296. auto SRE = static_cast<const MCSymbolRefExpr *>(Op.getExpr());
  297. if (SRE->getKind() == MCSymbolRefExpr::VK_WASM_TYPEINDEX) {
  298. auto &Sym = static_cast<const MCSymbolWasm &>(SRE->getSymbol());
  299. O << WebAssembly::signatureToString(Sym.getSignature());
  300. } else {
  301. Op.getExpr()->print(O, &MAI);
  302. }
  303. }
  304. }
  305. void WebAssemblyInstPrinter::printBrList(const MCInst *MI, unsigned OpNo,
  306. raw_ostream &O) {
  307. O << "{";
  308. for (unsigned I = OpNo, E = MI->getNumOperands(); I != E; ++I) {
  309. if (I != OpNo)
  310. O << ", ";
  311. O << MI->getOperand(I).getImm();
  312. }
  313. O << "}";
  314. }
  315. void WebAssemblyInstPrinter::printWebAssemblyP2AlignOperand(const MCInst *MI,
  316. unsigned OpNo,
  317. raw_ostream &O) {
  318. int64_t Imm = MI->getOperand(OpNo).getImm();
  319. if (Imm == WebAssembly::GetDefaultP2Align(MI->getOpcode()))
  320. return;
  321. O << ":p2align=" << Imm;
  322. }
  323. void WebAssemblyInstPrinter::printWebAssemblySignatureOperand(const MCInst *MI,
  324. unsigned OpNo,
  325. raw_ostream &O) {
  326. const MCOperand &Op = MI->getOperand(OpNo);
  327. if (Op.isImm()) {
  328. auto Imm = static_cast<unsigned>(Op.getImm());
  329. if (Imm != wasm::WASM_TYPE_NORESULT)
  330. O << WebAssembly::anyTypeToString(Imm);
  331. } else {
  332. auto Expr = cast<MCSymbolRefExpr>(Op.getExpr());
  333. auto *Sym = cast<MCSymbolWasm>(&Expr->getSymbol());
  334. if (Sym->getSignature()) {
  335. O << WebAssembly::signatureToString(Sym->getSignature());
  336. } else {
  337. // Disassembler does not currently produce a signature
  338. O << "unknown_type";
  339. }
  340. }
  341. }