WebAssembly: emit `(func (param t) (result t))` s-expressions
[oota-llvm.git] / lib / Target / WebAssembly / WebAssemblyAsmPrinter.cpp
1 //===-- WebAssemblyAsmPrinter.cpp - WebAssembly LLVM assembly writer ------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 ///
10 /// \file
11 /// \brief This file contains a printer that converts from our internal
12 /// representation of machine-dependent LLVM code to the WebAssembly assembly
13 /// language.
14 ///
15 //===----------------------------------------------------------------------===//
16
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"
23
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"
34
35 using namespace llvm;
36
37 #define DEBUG_TYPE "asm-printer"
38
39 namespace {
40
41 class WebAssemblyAsmPrinter final : public AsmPrinter {
42   const WebAssemblyInstrInfo *TII;
43
44 public:
45   WebAssemblyAsmPrinter(TargetMachine &TM, std::unique_ptr<MCStreamer> Streamer)
46       : AsmPrinter(TM, std::move(Streamer)), TII(nullptr) {}
47
48 private:
49   const char *getPassName() const override {
50     return "WebAssembly Assembly Printer";
51   }
52
53   //===------------------------------------------------------------------===//
54   // MachineFunctionPass Implementation.
55   //===------------------------------------------------------------------===//
56
57   void getAnalysisUsage(AnalysisUsage &AU) const override {
58     AsmPrinter::getAnalysisUsage(AU);
59   }
60
61   bool runOnMachineFunction(MachineFunction &MF) override {
62     TII = MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
63     return AsmPrinter::runOnMachineFunction(MF);
64   }
65
66   //===------------------------------------------------------------------===//
67   // AsmPrinter Implementation.
68   //===------------------------------------------------------------------===//
69
70   void EmitFunctionEntryLabel() override;
71   void EmitFunctionBodyStart() override;
72   void EmitFunctionBodyEnd() override;
73
74   void EmitInstruction(const MachineInstr *MI) override;
75 };
76
77 } // end anonymous namespace
78
79 //===----------------------------------------------------------------------===//
80
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]);
90 }
91
92 static std::string toSymbol(StringRef S) { return ("$" + S).str(); }
93
94 static const char *toType(const Type *Ty) {
95   switch (Ty->getTypeID()) {
96   default: break;
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";
103     default: break;
104     }
105   }
106   DEBUG(dbgs() << "Invalid type "; Ty->print(dbgs()); dbgs() << '\n');
107   llvm_unreachable("invalid type");
108   return "<invalid>";
109 }
110
111 void WebAssemblyAsmPrinter::EmitFunctionEntryLabel() {
112   SmallString<128> Str;
113   raw_svector_ostream OS(Str);
114
115   CurrentFnSym->redefineIfPossible();
116
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");
125
126   OS << "(func " << toSymbol(CurrentFnSym->getName());
127   OutStreamer->EmitRawText(OS.str());
128 }
129
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();
137   if (!Rt->isVoidTy())
138     OS << " (result " << toType(Rt) << ')';
139   OS << '\n';
140   OutStreamer->EmitRawText(OS.str());
141 }
142
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());
148 }
149
150 void WebAssemblyAsmPrinter::EmitInstruction(const MachineInstr *MI) {
151   DEBUG(dbgs() << "EmitInstruction: " << *MI << '\n');
152   SmallString<128> Str;
153   raw_svector_ostream OS(Str);
154
155   unsigned NumDefs = MI->getDesc().getNumDefs();
156   assert(NumDefs <= 1 &&
157          "Instructions with multiple result values not implemented");
158
159   OS << '\t';
160
161   if (NumDefs != 0) {
162     const MachineOperand &MO = MI->getOperand(0);
163     unsigned Reg = MO.getReg();
164     OS << "(setlocal @" << TargetRegisterInfo::virtReg2Index(Reg) << ' ';
165   }
166
167   OS << '(' << Name(TII, MI);
168   for (const MachineOperand &MO : MI->uses())
169     switch (MO.getType()) {
170     default:
171       llvm_unreachable("unexpected machine operand type");
172     case MachineOperand::MO_Register: {
173       if (MO.isImplicit())
174         continue;
175       unsigned Reg = MO.getReg();
176       OS << " @" << TargetRegisterInfo::virtReg2Index(Reg);
177     } break;
178     case MachineOperand::MO_Immediate: {
179       OS << ' ' << MO.getImm();
180     } break;
181     case MachineOperand::MO_FPImmediate: {
182       static const size_t BufBytes = 128;
183       char buf[BufBytes];
184       APFloat FP = MO.getFPImm()->getValueAPF();
185       if (FP.isNaN())
186         assert((FP.bitwiseIsEqual(APFloat::getQNaN(FP.getSemantics())) ||
187                 FP.bitwiseIsEqual(
188                     APFloat::getQNaN(FP.getSemantics(), /*Negative=*/true))) &&
189                "convertToHexString handles neither SNaN nor NaN payloads");
190       // Use C99's hexadecimal floating-point representation.
191       auto Written =
192           FP.convertToHexString(buf, /*hexDigits=*/0, /*upperCase=*/false,
193                                 APFloat::rmNearestTiesToEven);
194       (void)Written;
195       assert(Written != 0);
196       assert(Written < BufBytes);
197       OS << ' ' << buf;
198     } break;
199     case MachineOperand::MO_GlobalAddress: {
200       OS << ' ' << toSymbol(MO.getGlobal()->getName());
201     } break;
202     }
203   OS << ')';
204
205   if (NumDefs != 0)
206     OS << ')';
207
208   OS << '\n';
209
210   OutStreamer->EmitRawText(OS.str());
211 }
212
213 // Force static initialization.
214 extern "C" void LLVMInitializeWebAssemblyAsmPrinter() {
215   RegisterAsmPrinter<WebAssemblyAsmPrinter> X(TheWebAssemblyTarget32);
216   RegisterAsmPrinter<WebAssemblyAsmPrinter> Y(TheWebAssemblyTarget64);
217 }