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/CodeGen/AsmPrinter.h"
26 #include "llvm/CodeGen/MachineInstr.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DebugInfo.h"
29 #include "llvm/MC/MCStreamer.h"
30 #include "llvm/MC/MCSymbol.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/TargetRegistry.h"
33 #include "llvm/Support/raw_ostream.h"
37 #define DEBUG_TYPE "asm-printer"
41 class WebAssemblyAsmPrinter final : public AsmPrinter {
42 const WebAssemblyInstrInfo *TII;
45 WebAssemblyAsmPrinter(TargetMachine &TM, std::unique_ptr<MCStreamer> Streamer)
46 : AsmPrinter(TM, std::move(Streamer)), TII(nullptr) {}
49 const char *getPassName() const override {
50 return "WebAssembly Assembly Printer";
53 //===------------------------------------------------------------------===//
54 // MachineFunctionPass Implementation.
55 //===------------------------------------------------------------------===//
57 void getAnalysisUsage(AnalysisUsage &AU) const override {
58 AsmPrinter::getAnalysisUsage(AU);
61 bool runOnMachineFunction(MachineFunction &MF) override {
62 TII = MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
63 return AsmPrinter::runOnMachineFunction(MF);
66 //===------------------------------------------------------------------===//
67 // AsmPrinter Implementation.
68 //===------------------------------------------------------------------===//
70 void EmitFunctionEntryLabel() override;
71 void EmitFunctionBodyStart() override;
72 void EmitFunctionBodyEnd() override;
74 void EmitInstruction(const MachineInstr *MI) override;
77 } // end anonymous namespace
79 //===----------------------------------------------------------------------===//
81 // Untyped, lower-case version of the opcode's name matching the names
82 // WebAssembly opcodes are expected to have. The tablegen names are uppercase
83 // and suffixed with their type (after an underscore).
84 static SmallString<32> Name(const WebAssemblyInstrInfo *TII,
85 const MachineInstr *MI) {
86 std::string N(StringRef(TII->getName(MI->getOpcode())).lower());
87 std::string::size_type End = N.rfind('_');
88 End = std::string::npos == End ? N.length() : End;
89 return SmallString<32>(&N[0], &N[End]);
92 static std::string toSymbol(StringRef S) { return ("$" + S).str(); }
94 static const char *toType(const Type *Ty) {
95 switch (Ty->getTypeID()) {
97 case Type::FloatTyID: return "f32";
98 case Type::DoubleTyID: return "f64";
99 case Type::IntegerTyID:
100 switch (Ty->getIntegerBitWidth()) {
101 case 32: return "i32";
102 case 64: return "i64";
106 DEBUG(dbgs() << "Invalid type "; Ty->print(dbgs()); dbgs() << '\n');
107 llvm_unreachable("invalid type");
111 void WebAssemblyAsmPrinter::EmitFunctionEntryLabel() {
112 SmallString<128> Str;
113 raw_svector_ostream OS(Str);
115 CurrentFnSym->redefineIfPossible();
117 // The function label could have already been emitted if two symbols end up
118 // conflicting due to asm renaming. Detect this and emit an error.
119 if (CurrentFnSym->isVariable())
120 report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
121 "' is a protected alias");
122 if (CurrentFnSym->isDefined())
123 report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
124 "' label emitted multiple times to assembly file");
126 OS << "(func " << toSymbol(CurrentFnSym->getName());
127 OutStreamer->EmitRawText(OS.str());
130 void WebAssemblyAsmPrinter::EmitFunctionBodyStart() {
131 SmallString<128> Str;
132 raw_svector_ostream OS(Str);
133 const Function *F = MF->getFunction();
134 for (const Argument &A : F->args())
135 OS << " (param " << toType(A.getType()) << ')';
136 const Type *Rt = F->getReturnType();
138 OS << " (result " << toType(Rt) << ')';
140 OutStreamer->EmitRawText(OS.str());
143 void WebAssemblyAsmPrinter::EmitFunctionBodyEnd() {
144 SmallString<128> Str;
145 raw_svector_ostream OS(Str);
146 OS << ") ;; end func " << toSymbol(CurrentFnSym->getName()) << '\n';
147 OutStreamer->EmitRawText(OS.str());
150 void WebAssemblyAsmPrinter::EmitInstruction(const MachineInstr *MI) {
151 DEBUG(dbgs() << "EmitInstruction: " << *MI << '\n');
152 SmallString<128> Str;
153 raw_svector_ostream OS(Str);
155 unsigned NumDefs = MI->getDesc().getNumDefs();
156 assert(NumDefs <= 1 &&
157 "Instructions with multiple result values not implemented");
162 const MachineOperand &MO = MI->getOperand(0);
163 unsigned Reg = MO.getReg();
164 OS << "(setlocal @" << TargetRegisterInfo::virtReg2Index(Reg) << ' ';
167 OS << '(' << Name(TII, MI);
168 for (const MachineOperand &MO : MI->uses())
169 switch (MO.getType()) {
171 llvm_unreachable("unexpected machine operand type");
172 case MachineOperand::MO_Register: {
175 unsigned Reg = MO.getReg();
176 OS << " @" << TargetRegisterInfo::virtReg2Index(Reg);
178 case MachineOperand::MO_Immediate: {
179 OS << ' ' << MO.getImm();
181 case MachineOperand::MO_FPImmediate: {
182 static const size_t BufBytes = 128;
184 APFloat FP = MO.getFPImm()->getValueAPF();
186 assert((FP.bitwiseIsEqual(APFloat::getQNaN(FP.getSemantics())) ||
188 APFloat::getQNaN(FP.getSemantics(), /*Negative=*/true))) &&
189 "convertToHexString handles neither SNaN nor NaN payloads");
190 // Use C99's hexadecimal floating-point representation.
192 FP.convertToHexString(buf, /*hexDigits=*/0, /*upperCase=*/false,
193 APFloat::rmNearestTiesToEven);
195 assert(Written != 0);
196 assert(Written < BufBytes);
199 case MachineOperand::MO_GlobalAddress: {
200 OS << ' ' << toSymbol(MO.getGlobal()->getName());
210 OutStreamer->EmitRawText(OS.str());
213 // Force static initialization.
214 extern "C" void LLVMInitializeWebAssemblyAsmPrinter() {
215 RegisterAsmPrinter<WebAssemblyAsmPrinter> X(TheWebAssemblyTarget32);
216 RegisterAsmPrinter<WebAssemblyAsmPrinter> Y(TheWebAssemblyTarget64);