1 //===-- WebAssemblyAsmPrinter.cpp - WebAssembly LLVM assembly writer ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// \brief This file contains a printer that converts from our internal
12 /// representation of machine-dependent LLVM code to the WebAssembly assembly
15 //===----------------------------------------------------------------------===//
17 #include "WebAssembly.h"
18 #include "WebAssemblyMachineFunctionInfo.h"
19 #include "WebAssemblyRegisterInfo.h"
20 #include "WebAssemblySubtarget.h"
21 #include "InstPrinter/WebAssemblyInstPrinter.h"
22 #include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/CodeGen/AsmPrinter.h"
27 #include "llvm/CodeGen/MachineConstantPool.h"
28 #include "llvm/CodeGen/MachineInstr.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/DebugInfo.h"
31 #include "llvm/MC/MCStreamer.h"
32 #include "llvm/MC/MCSymbol.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/TargetRegistry.h"
35 #include "llvm/Support/raw_ostream.h"
39 #define DEBUG_TYPE "asm-printer"
43 class WebAssemblyAsmPrinter final : public AsmPrinter {
44 const WebAssemblyInstrInfo *TII;
45 const MachineRegisterInfo *MRI;
49 WebAssemblyAsmPrinter(TargetMachine &TM, std::unique_ptr<MCStreamer> Streamer)
50 : AsmPrinter(TM, std::move(Streamer)), TII(nullptr), MRI(nullptr) {}
53 const char *getPassName() const override {
54 return "WebAssembly Assembly Printer";
57 //===------------------------------------------------------------------===//
58 // MachineFunctionPass Implementation.
59 //===------------------------------------------------------------------===//
61 void getAnalysisUsage(AnalysisUsage &AU) const override {
62 AsmPrinter::getAnalysisUsage(AU);
65 bool runOnMachineFunction(MachineFunction &MF) override {
66 const auto &Subtarget = MF.getSubtarget<WebAssemblySubtarget>();
67 TII = Subtarget.getInstrInfo();
68 MRI = &MF.getRegInfo();
69 NumArgs = MF.getInfo<WebAssemblyFunctionInfo>()->getNumArguments();
70 return AsmPrinter::runOnMachineFunction(MF);
73 //===------------------------------------------------------------------===//
74 // AsmPrinter Implementation.
75 //===------------------------------------------------------------------===//
77 void EmitJumpTableInfo() override;
78 void EmitConstantPool() override;
79 void EmitFunctionBodyStart() override;
80 void EmitInstruction(const MachineInstr *MI) override;
81 void EmitEndOfAsmFile(Module &M) override;
83 std::string getRegTypeName(unsigned RegNo) const;
84 static std::string toString(const APFloat &APF);
85 const char *toString(Type *Ty) const;
86 std::string regToString(const MachineOperand &MO);
87 std::string argToString(const MachineOperand &MO);
90 } // end anonymous namespace
92 //===----------------------------------------------------------------------===//
94 //===----------------------------------------------------------------------===//
96 // Operand type (if any), followed by the lower-case version of the opcode's
97 // name matching the names WebAssembly opcodes are expected to have. The
98 // tablegen names are uppercase and suffixed with their type (after an
100 static std::string OpcodeName(const WebAssemblyInstrInfo *TII,
101 const MachineInstr *MI) {
102 std::string N(StringRef(TII->getName(MI->getOpcode())).lower());
103 std::string::size_type Len = N.length();
104 std::string::size_type Under = N.rfind('_');
105 bool HasType = std::string::npos != Under;
106 std::string::size_type NameEnd = HasType ? Under : Len;
107 std::string Name(&N[0], &N[NameEnd]);
110 for (const char *typelessOpcode : { "return", "call" })
111 if (Name == typelessOpcode)
113 return std::string(&N[NameEnd + 1], &N[Len]) + '.' + Name;
116 static std::string toSymbol(StringRef S) { return ("$" + S).str(); }
118 std::string WebAssemblyAsmPrinter::getRegTypeName(unsigned RegNo) const {
119 const TargetRegisterClass *TRC = MRI->getRegClass(RegNo);
120 for (MVT T : {MVT::i32, MVT::i64, MVT::f32, MVT::f64})
122 return EVT(T).getEVTString();
123 DEBUG(errs() << "Unknown type for register number: " << RegNo);
124 llvm_unreachable("Unknown register type");
128 std::string WebAssemblyAsmPrinter::toString(const APFloat &FP) {
129 static const size_t BufBytes = 128;
132 assert((FP.bitwiseIsEqual(APFloat::getQNaN(FP.getSemantics())) ||
134 APFloat::getQNaN(FP.getSemantics(), /*Negative=*/true))) &&
135 "convertToHexString handles neither SNaN nor NaN payloads");
136 // Use C99's hexadecimal floating-point representation.
137 auto Written = FP.convertToHexString(
138 buf, /*hexDigits=*/0, /*upperCase=*/false, APFloat::rmNearestTiesToEven);
140 assert(Written != 0);
141 assert(Written < BufBytes);
145 std::string WebAssemblyAsmPrinter::regToString(const MachineOperand &MO) {
146 unsigned RegNo = MO.getReg();
147 if (TargetRegisterInfo::isPhysicalRegister(RegNo))
148 return WebAssemblyInstPrinter::getRegisterName(RegNo);
150 // WebAssembly arguments and local variables are in the same index space, and
151 // there are no explicit varargs, so we just add the number of arguments to
152 // the virtual register number to get the local variable number.
153 return utostr(TargetRegisterInfo::virtReg2Index(RegNo) + NumArgs);
156 std::string WebAssemblyAsmPrinter::argToString(const MachineOperand &MO) {
157 unsigned ArgNo = MO.getImm();
158 // Same as above, but we don't need to add NumArgs here.
159 return utostr(ArgNo);
162 const char *WebAssemblyAsmPrinter::toString(Type *Ty) const {
163 switch (Ty->getTypeID()) {
166 // Treat all pointers as the underlying integer into linear memory.
167 case Type::PointerTyID:
168 switch (getPointerSize()) {
174 llvm_unreachable("unsupported pointer size");
177 case Type::FloatTyID:
179 case Type::DoubleTyID:
181 case Type::IntegerTyID:
182 switch (Ty->getIntegerBitWidth()) {
195 DEBUG(dbgs() << "Invalid type "; Ty->print(dbgs()); dbgs() << '\n');
196 llvm_unreachable("invalid type");
200 //===----------------------------------------------------------------------===//
201 // WebAssemblyAsmPrinter Implementation.
202 //===----------------------------------------------------------------------===//
204 void WebAssemblyAsmPrinter::EmitConstantPool() {
205 assert(MF->getConstantPool()->getConstants().empty() &&
206 "WebAssembly disables constant pools");
209 void WebAssemblyAsmPrinter::EmitJumpTableInfo() {
210 // Nothing to do; jump tables are incorporated into the instruction stream.
213 void WebAssemblyAsmPrinter::EmitFunctionBodyStart() {
214 const Function *F = MF->getFunction();
215 Type *Rt = F->getReturnType();
216 SmallString<128> Str;
217 raw_svector_ostream OS(Str);
220 if (!Rt->isVoidTy() || !F->arg_empty()) {
221 for (const Argument &A : F->args()) {
222 OS << (First ? "" : "\n") << "\t.param " << toString(A.getType());
225 if (!Rt->isVoidTy()) {
226 OS << (First ? "" : "\n") << "\t.result " << toString(Rt);
231 bool FirstVReg = true;
232 for (unsigned Idx = 0, IdxE = MRI->getNumVirtRegs(); Idx != IdxE; ++Idx) {
233 unsigned VReg = TargetRegisterInfo::index2VirtReg(Idx);
234 // FIXME: Don't skip dead virtual registers for now: that would require
235 // remapping all locals' numbers.
236 //if (!MRI->use_empty(VReg)) {
238 OS << (First ? "" : "\n") << "\t.local ";
241 OS << (FirstVReg ? "" : ", ") << getRegTypeName(VReg);
247 OutStreamer->EmitRawText(OS.str());
248 AsmPrinter::EmitFunctionBodyStart();
251 void WebAssemblyAsmPrinter::EmitInstruction(const MachineInstr *MI) {
252 DEBUG(dbgs() << "EmitInstruction: " << *MI << '\n');
253 SmallString<128> Str;
254 raw_svector_ostream OS(Str);
256 unsigned NumDefs = MI->getDesc().getNumDefs();
257 assert(NumDefs <= 1 &&
258 "Instructions with multiple result values not implemented");
262 switch (MI->getOpcode()) {
263 case TargetOpcode::COPY:
264 OS << "get_local " << regToString(MI->getOperand(1));
266 case WebAssembly::GLOBAL:
268 OS << "i32.const " << toSymbol(MI->getOperand(1).getGlobal()->getName());
270 case WebAssembly::ARGUMENT_I32:
271 case WebAssembly::ARGUMENT_I64:
272 case WebAssembly::ARGUMENT_F32:
273 case WebAssembly::ARGUMENT_F64:
274 OS << "get_local " << argToString(MI->getOperand(1));
276 case WebAssembly::Immediate_I32:
277 OS << "i32.const " << MI->getOperand(1).getImm();
279 case WebAssembly::Immediate_I64:
280 OS << "i64.const " << MI->getOperand(1).getImm();
282 case WebAssembly::Immediate_F32:
283 OS << "f32.const " << toString(MI->getOperand(1).getFPImm()->getValueAPF());
285 case WebAssembly::Immediate_F64:
286 OS << "f64.const " << toString(MI->getOperand(1).getFPImm()->getValueAPF());
289 OS << OpcodeName(TII, MI);
290 bool NeedComma = false;
291 for (const MachineOperand &MO : MI->uses()) {
292 if (MO.isReg() && MO.isImplicit())
298 switch (MO.getType()) {
300 llvm_unreachable("unexpected machine operand type");
301 case MachineOperand::MO_Register:
302 OS << "(get_local " << regToString(MO) << ')';
304 case MachineOperand::MO_Immediate:
307 case MachineOperand::MO_FPImmediate:
308 OS << toString(MO.getFPImm()->getValueAPF());
310 case MachineOperand::MO_GlobalAddress:
311 OS << toSymbol(MO.getGlobal()->getName());
313 case MachineOperand::MO_MachineBasicBlock:
314 OS << toSymbol(MO.getMBB()->getSymbol()->getName());
322 OutStreamer->EmitRawText(OS.str());
325 SmallString<128> Str;
326 raw_svector_ostream OS(Str);
327 const MachineOperand &Operand = MI->getOperand(0);
328 OS << "\tset_local " << regToString(Operand) << ", pop";
329 OutStreamer->EmitRawText(OS.str());
333 void WebAssemblyAsmPrinter::EmitEndOfAsmFile(Module &M) {
334 SmallString<128> Str;
335 raw_svector_ostream OS(Str);
336 for (const Function &F : M)
337 if (F.isDeclarationForLinker()) {
338 assert(F.hasName() && "imported functions must have a name");
339 if (F.getName().startswith("llvm."))
342 OS << "\t.imports\n";
343 Type *Rt = F.getReturnType();
344 OS << "\t.import " << toSymbol(F.getName()) << " \"\" \"" << F.getName()
346 for (const Argument &A : F.args())
347 OS << " (param " << toString(A.getType()) << ')';
349 OS << " (result " << toString(Rt) << ')';
352 OutStreamer->EmitRawText(OS.str());
355 // Force static initialization.
356 extern "C" void LLVMInitializeWebAssemblyAsmPrinter() {
357 RegisterAsmPrinter<WebAssemblyAsmPrinter> X(TheWebAssemblyTarget32);
358 RegisterAsmPrinter<WebAssemblyAsmPrinter> Y(TheWebAssemblyTarget64);