LLVM  10.0.0svn
WebAssemblyInstPrinter.cpp
Go to the documentation of this file.
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 
16 #include "WebAssembly.h"
18 #include "WebAssemblyUtilities.h"
19 #include "llvm/ADT/SmallSet.h"
20 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/MC/MCExpr.h"
23 #include "llvm/MC/MCInst.h"
24 #include "llvm/MC/MCInstrInfo.h"
26 #include "llvm/MC/MCSymbol.h"
29 using namespace llvm;
30 
31 #define DEBUG_TYPE "asm-printer"
32 
33 #include "WebAssemblyGenAsmWriter.inc"
34 
36  const MCInstrInfo &MII,
37  const MCRegisterInfo &MRI)
38  : MCInstPrinter(MAI, MII, MRI) {}
39 
41  unsigned RegNo) const {
43  // Note that there's an implicit local.get/local.set here!
44  OS << "$" << RegNo;
45 }
46 
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 
106  case WebAssembly::END_BLOCK_S:
107  if (ControlFlowStack.empty()) {
108  printAnnotation(OS, "End marker mismatch!");
109  } else {
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 {
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.
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];
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 {
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 
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 
270  unsigned OpNo,
271  raw_ostream &O) {
272  auto Imm = static_cast<unsigned>(MI->getOperand(OpNo).getImm());
273  if (Imm != wasm::WASM_TYPE_NORESULT)
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";
290  return "v128";
292  return "funcref";
294  return "func";
296  return "exnref";
298  return "void";
299  default:
300  return "invalid_type";
301  }
302 }
303 
305  return anyTypeToString(static_cast<unsigned>(Ty));
306 }
307 
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 
318  std::string S("(");
319  S += typeListToString(Sig->Params);
320  S += ") -> (";
321  S += typeListToString(Sig->Returns);
322  S += ")";
323  return S;
324 }
32-bit floating-point immediates.
void printWebAssemblySignatureOperand(const MCInst *MI, unsigned OpNo, raw_ostream &O)
bool isImm() const
Definition: MCInst.h:58
uint64_t getZExtValue() const
Get zero extended value.
Definition: APInt.h:1571
void printOperand(const MCInst *MI, unsigned OpNo, raw_ostream &O)
This class represents lattice values for constants.
Definition: AllocatorList.h:23
void push_back(const T &Elt)
Definition: SmallVector.h:211
This class prints an WebAssembly MCInst to wasm file syntax.
Describe properties that are true of each instruction in the target description file.
Definition: MCInstrDesc.h:178
void printWebAssemblyP2AlignOperand(const MCInst *MI, unsigned OpNo, raw_ostream &O)
unsigned GetDefaultP2Align(unsigned Opc)
bool isReg() const
Definition: MCInst.h:57
void printRegName(raw_ostream &OS, unsigned RegNo) const override
Print the assembler register name.
Basic block label in a branch construct.
const char * anyTypeToString(unsigned Ty)
const fltSemantics & getSemantics() const
Definition: APFloat.h:1170
This file contains the entry points for global functions defined in the LLVM WebAssembly back-end...
WebAssemblyInstPrinter(const MCAsmInfo &MAI, const MCInstrInfo &MII, const MCRegisterInfo &MRI)
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition: APInt.h:1517
std::string toString(Error E)
Write all error messages (if any) in E to a string.
Definition: Error.h:966
unsigned getNumOperands() const
Return the number of declared MachineOperands for this MachineInstruction.
Definition: MCInstrDesc.h:225
SmallVector< ValType, 1 > Returns
Definition: Wasm.h:354
std::string signatureToString(const wasm::WasmSignature *Sig)
Represent a reference to a symbol from inside an expression.
Definition: MCExpr.h:169
unsigned getReg() const
Returns the register number.
Definition: MCInst.h:64
SmallVector< ValType, 4 > Params
Definition: Wasm.h:355
uint8_t OperandType
Information about the type of the operand.
Definition: MCInstrDesc.h:82
void printBrList(const MCInst *MI, unsigned OpNo, raw_ostream &O)
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:32
const MCExpr * getExpr() const
Definition: MCInst.h:95
Analysis containing CSE Info
Definition: CSEInfo.cpp:20
Instances of this class represent a single low-level machine instruction.
Definition: MCInst.h:158
unsigned short NumOperands
Definition: MCInstrDesc.h:181
MCRegisterInfo base class - We assume that the target defines a static array of MCRegisterDesc object...
This class is intended to be used as a base class for asm properties and features specific to the tar...
Definition: MCAsmInfo.h:56
This file contains the declaration of the WebAssembly-specific utility functions. ...
int64_t getImm() const
Definition: MCInst.h:75
bool isNegative() const
Determine sign of this APInt.
Definition: APInt.h:363
void print(raw_ostream &OS, const MCAsmInfo *MAI, bool InParens=false) const
Definition: MCExpr.cpp:42
unsigned const MachineRegisterInfo * MRI
bool isVariadic() const
Return true if this instruction can have a variable number of operands.
Definition: MCInstrDesc.h:249
bool isNaN() const
Definition: APFloat.h:1160
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition: SmallSet.h:134
bool isFPImm() const
Definition: MCInst.h:59
This file provides WebAssembly-specific target descriptions.
std::string typeListToString(ArrayRef< wasm::ValType > List)
Interface to description of machine instruction set.
Definition: MCInstrInfo.h:23
bool isExpr() const
Definition: MCInst.h:60
unsigned getNumOperands() const
Definition: MCInst.h:181
std::pair< NoneType, bool > insert(const T &V)
insert - Insert an element into the set if it isn&#39;t already there.
Definition: SmallSet.h:180
size_t size() const
Definition: SmallVector.h:52
void printInst(const MCInst *MI, raw_ostream &OS, StringRef Annot, const MCSubtargetInfo &STI) override
Print the specified MCInst to the specified raw_ostream.
const MCOperand & getOperand(unsigned i) const
Definition: MCInst.h:179
LLVM_NODISCARD T pop_back_val()
Definition: SmallVector.h:374
raw_ostream * CommentStream
A stream that comments can be emitted to if desired.
Definition: MCInstPrinter.h:44
std::string utostr(uint64_t X, bool isNeg=false)
Definition: StringExtras.h:223
Class for arbitrary precision integers.
Definition: APInt.h:69
64-bit floating-point immediates.
unsigned int convertToHexString(char *DST, unsigned int HexDigits, bool UpperCase, roundingMode RM) const
Definition: APFloat.h:1152
const MCAsmInfo & MAI
Definition: MCInstPrinter.h:45
This is an instance of a target assembly language printer that converts an MCInst to valid target ass...
Definition: MCInstPrinter.h:39
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:55
const MCInstrDesc & get(unsigned Opcode) const
Return the machine instruction descriptor that corresponds to the specified instruction opcode...
Definition: MCInstrInfo.h:44
const NodeList & List
Definition: RDFGraph.cpp:201
#define I(x, y, z)
Definition: MD5.cpp:58
This file declares WebAssembly-specific per-machine-function information.
Generic base class for all target subtargets.
const MCInstrInfo & MII
Definition: MCInstPrinter.h:46
void printInstruction(const MCInst *MI, raw_ostream &O)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
void printAnnotation(raw_ostream &OS, StringRef Annot)
Utility function for printing annotations.
bool bitwiseIsEqual(const APFloat &RHS) const
Definition: APFloat.h:1127
const MCOperandInfo * OpInfo
Definition: MCInstrDesc.h:189
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:45
IRTranslator LLVM IR MI
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:48
APInt bitcastToAPInt() const
Definition: APFloat.h:1109
This holds information about one operand of a machine instruction, indicating the register class for ...
Definition: MCInstrDesc.h:70
unsigned getOpcode() const
Definition: MCInst.h:171
const char * typeToString(wasm::ValType Ty)
Instances of this class represent operands of the MCInst class.
Definition: MCInst.h:34
static APFloat getQNaN(const fltSemantics &Sem, bool Negative=false, const APInt *payload=nullptr)
Factory for QNaN values.
Definition: APFloat.h:901
double getFPImm() const
Definition: MCInst.h:85
std::string utohexstr(uint64_t X, bool LowerCase=false)
Definition: StringExtras.h:124
static unsigned getWARegStackId(unsigned Reg)