blob: 7034892de8eb835c11bd072fd3f2d39ebfe25b92 [file] [log] [blame]
JF Bastienb9073fb2015-07-22 21:28:15 +00001//===-- 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"
Dan Gohmane51c0582015-10-06 00:27:55 +000025#include "llvm/ADT/StringExtras.h"
JF Bastienb9073fb2015-07-22 21:28:15 +000026#include "llvm/CodeGen/AsmPrinter.h"
JF Bastien54be3b12015-08-25 23:19:49 +000027#include "llvm/CodeGen/MachineConstantPool.h"
JF Bastienb9073fb2015-07-22 21:28:15 +000028#include "llvm/CodeGen/MachineInstr.h"
29#include "llvm/IR/DataLayout.h"
30#include "llvm/IR/DebugInfo.h"
31#include "llvm/MC/MCStreamer.h"
JF Bastienb6091df2015-08-25 22:58:05 +000032#include "llvm/MC/MCSymbol.h"
JF Bastienb9073fb2015-07-22 21:28:15 +000033#include "llvm/Support/Debug.h"
34#include "llvm/Support/TargetRegistry.h"
35#include "llvm/Support/raw_ostream.h"
36
37using namespace llvm;
38
39#define DEBUG_TYPE "asm-printer"
40
41namespace {
42
43class WebAssemblyAsmPrinter final : public AsmPrinter {
JF Bastien600aee92015-07-31 17:53:38 +000044 const WebAssemblyInstrInfo *TII;
JF Bastien1d20a5e2015-10-16 00:53:49 +000045 const MachineRegisterInfo *MRI;
Dan Gohmane51c0582015-10-06 00:27:55 +000046 unsigned NumArgs;
JF Bastien600aee92015-07-31 17:53:38 +000047
JF Bastienb9073fb2015-07-22 21:28:15 +000048public:
49 WebAssemblyAsmPrinter(TargetMachine &TM, std::unique_ptr<MCStreamer> Streamer)
JF Bastien1d20a5e2015-10-16 00:53:49 +000050 : AsmPrinter(TM, std::move(Streamer)), TII(nullptr), MRI(nullptr) {}
JF Bastienb9073fb2015-07-22 21:28:15 +000051
52private:
53 const char *getPassName() const override {
54 return "WebAssembly Assembly Printer";
55 }
56
57 //===------------------------------------------------------------------===//
58 // MachineFunctionPass Implementation.
59 //===------------------------------------------------------------------===//
60
61 void getAnalysisUsage(AnalysisUsage &AU) const override {
62 AsmPrinter::getAnalysisUsage(AU);
63 }
64
JF Bastien600aee92015-07-31 17:53:38 +000065 bool runOnMachineFunction(MachineFunction &MF) override {
JF Bastien73ff6af2015-08-31 22:24:11 +000066 const auto &Subtarget = MF.getSubtarget<WebAssemblySubtarget>();
JF Bastien73ff6af2015-08-31 22:24:11 +000067 TII = Subtarget.getInstrInfo();
JF Bastien1d20a5e2015-10-16 00:53:49 +000068 MRI = &MF.getRegInfo();
Dan Gohmane51c0582015-10-06 00:27:55 +000069 NumArgs = MF.getInfo<WebAssemblyFunctionInfo>()->getNumArguments();
JF Bastien600aee92015-07-31 17:53:38 +000070 return AsmPrinter::runOnMachineFunction(MF);
JF Bastienb9073fb2015-07-22 21:28:15 +000071 }
72
73 //===------------------------------------------------------------------===//
74 // AsmPrinter Implementation.
75 //===------------------------------------------------------------------===//
76
Dan Gohman950a13c2015-09-16 16:51:30 +000077 void EmitJumpTableInfo() override;
JF Bastien54be3b12015-08-25 23:19:49 +000078 void EmitConstantPool() override;
JF Bastienb6091df2015-08-25 22:58:05 +000079 void EmitFunctionBodyStart() override;
JF Bastienb9073fb2015-07-22 21:28:15 +000080 void EmitInstruction(const MachineInstr *MI) override;
JF Bastien1a59c6b2015-10-21 02:23:09 +000081 void EmitEndOfAsmFile(Module &M) override;
Dan Gohman979840d2015-09-23 16:59:10 +000082
JF Bastien1d20a5e2015-10-16 00:53:49 +000083 std::string getRegTypeName(unsigned RegNo) const;
Dan Gohman979840d2015-09-23 16:59:10 +000084 static std::string toString(const APFloat &APF);
85 const char *toString(Type *Ty) const;
JF Bastien1d20a5e2015-10-16 00:53:49 +000086 std::string regToString(const MachineOperand &MO);
87 std::string argToString(const MachineOperand &MO);
JF Bastienb9073fb2015-07-22 21:28:15 +000088};
89
90} // end anonymous namespace
91
92//===----------------------------------------------------------------------===//
JF Bastien45479f62015-08-26 22:09:54 +000093// Helpers.
94//===----------------------------------------------------------------------===//
JF Bastienb9073fb2015-07-22 21:28:15 +000095
JF Bastien1d20a5e2015-10-16 00:53:49 +000096// 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
JF Bastien7b452e22015-10-29 04:10:52 +000099// underscore). Conversions are additionally prefixed with their input type
100// (before a double underscore).
JF Bastien1d20a5e2015-10-16 00:53:49 +0000101static std::string OpcodeName(const WebAssemblyInstrInfo *TII,
102 const MachineInstr *MI) {
JF Bastien315cc062015-08-07 01:57:03 +0000103 std::string N(StringRef(TII->getName(MI->getOpcode())).lower());
JF Bastien1d20a5e2015-10-16 00:53:49 +0000104 std::string::size_type Len = N.length();
105 std::string::size_type Under = N.rfind('_');
106 bool HasType = std::string::npos != Under;
107 std::string::size_type NameEnd = HasType ? Under : Len;
108 std::string Name(&N[0], &N[NameEnd]);
JF Bastienc8f89e82015-10-20 01:26:54 +0000109 if (!HasType)
110 return Name;
JF Bastienf2364bf2015-10-22 02:32:50 +0000111 for (const char *typelessOpcode : { "return", "call", "br_if" })
JF Bastienc8f89e82015-10-20 01:26:54 +0000112 if (Name == typelessOpcode)
113 return Name;
JF Bastien7b452e22015-10-29 04:10:52 +0000114 std::string Type(&N[NameEnd + 1], &N[Len]);
115 std::string::size_type DoubleUnder = Name.find("__");
116 bool IsConv = std::string::npos != DoubleUnder;
117 if (!IsConv)
118 return Type + '.' + Name;
119 std::string InType(&Name[0], &Name[DoubleUnder]);
120 return Type + '.' + std::string(&Name[DoubleUnder + 2], &Name[NameEnd]) +
121 '/' + InType;
JF Bastien315cc062015-08-07 01:57:03 +0000122}
123
JF Bastienaf111db2015-08-24 22:16:48 +0000124static std::string toSymbol(StringRef S) { return ("$" + S).str(); }
125
JF Bastien1d20a5e2015-10-16 00:53:49 +0000126std::string WebAssemblyAsmPrinter::getRegTypeName(unsigned RegNo) const {
127 const TargetRegisterClass *TRC = MRI->getRegClass(RegNo);
128 for (MVT T : {MVT::i32, MVT::i64, MVT::f32, MVT::f64})
129 if (TRC->hasType(T))
130 return EVT(T).getEVTString();
131 DEBUG(errs() << "Unknown type for register number: " << RegNo);
132 llvm_unreachable("Unknown register type");
133 return "?";
134}
135
Dan Gohman979840d2015-09-23 16:59:10 +0000136std::string WebAssemblyAsmPrinter::toString(const APFloat &FP) {
JF Bastien45479f62015-08-26 22:09:54 +0000137 static const size_t BufBytes = 128;
138 char buf[BufBytes];
139 if (FP.isNaN())
140 assert((FP.bitwiseIsEqual(APFloat::getQNaN(FP.getSemantics())) ||
141 FP.bitwiseIsEqual(
142 APFloat::getQNaN(FP.getSemantics(), /*Negative=*/true))) &&
143 "convertToHexString handles neither SNaN nor NaN payloads");
144 // Use C99's hexadecimal floating-point representation.
145 auto Written = FP.convertToHexString(
146 buf, /*hexDigits=*/0, /*upperCase=*/false, APFloat::rmNearestTiesToEven);
147 (void)Written;
148 assert(Written != 0);
149 assert(Written < BufBytes);
150 return buf;
151}
152
JF Bastien1d20a5e2015-10-16 00:53:49 +0000153std::string WebAssemblyAsmPrinter::regToString(const MachineOperand &MO) {
154 unsigned RegNo = MO.getReg();
Dan Gohmane51c0582015-10-06 00:27:55 +0000155 if (TargetRegisterInfo::isPhysicalRegister(RegNo))
156 return WebAssemblyInstPrinter::getRegisterName(RegNo);
157
158 // WebAssembly arguments and local variables are in the same index space, and
159 // there are no explicit varargs, so we just add the number of arguments to
160 // the virtual register number to get the local variable number.
JF Bastien1d20a5e2015-10-16 00:53:49 +0000161 return utostr(TargetRegisterInfo::virtReg2Index(RegNo) + NumArgs);
Dan Gohmane51c0582015-10-06 00:27:55 +0000162}
163
JF Bastien1d20a5e2015-10-16 00:53:49 +0000164std::string WebAssemblyAsmPrinter::argToString(const MachineOperand &MO) {
165 unsigned ArgNo = MO.getImm();
Dan Gohmane51c0582015-10-06 00:27:55 +0000166 // Same as above, but we don't need to add NumArgs here.
JF Bastien1d20a5e2015-10-16 00:53:49 +0000167 return utostr(ArgNo);
Dan Gohmane51c0582015-10-06 00:27:55 +0000168}
169
Dan Gohman979840d2015-09-23 16:59:10 +0000170const char *WebAssemblyAsmPrinter::toString(Type *Ty) const {
JF Bastien73ff6af2015-08-31 22:24:11 +0000171 switch (Ty->getTypeID()) {
Dan Gohman979840d2015-09-23 16:59:10 +0000172 default:
173 break;
JF Bastien73ff6af2015-08-31 22:24:11 +0000174 // Treat all pointers as the underlying integer into linear memory.
Dan Gohman979840d2015-09-23 16:59:10 +0000175 case Type::PointerTyID:
176 switch (getPointerSize()) {
177 case 4:
178 return "i32";
179 case 8:
180 return "i64";
181 default:
182 llvm_unreachable("unsupported pointer size");
183 }
184 break;
185 case Type::FloatTyID:
186 return "f32";
187 case Type::DoubleTyID:
188 return "f64";
JF Bastien73ff6af2015-08-31 22:24:11 +0000189 case Type::IntegerTyID:
190 switch (Ty->getIntegerBitWidth()) {
Dan Gohman979840d2015-09-23 16:59:10 +0000191 case 8:
192 return "i8";
193 case 16:
194 return "i16";
195 case 32:
196 return "i32";
197 case 64:
198 return "i64";
199 default:
200 break;
JF Bastien73ff6af2015-08-31 22:24:11 +0000201 }
202 }
203 DEBUG(dbgs() << "Invalid type "; Ty->print(dbgs()); dbgs() << '\n');
204 llvm_unreachable("invalid type");
205 return "<invalid>";
206}
207
JF Bastien45479f62015-08-26 22:09:54 +0000208//===----------------------------------------------------------------------===//
209// WebAssemblyAsmPrinter Implementation.
210//===----------------------------------------------------------------------===//
211
JF Bastien54be3b12015-08-25 23:19:49 +0000212void WebAssemblyAsmPrinter::EmitConstantPool() {
213 assert(MF->getConstantPool()->getConstants().empty() &&
214 "WebAssembly disables constant pools");
215}
216
Dan Gohman950a13c2015-09-16 16:51:30 +0000217void WebAssemblyAsmPrinter::EmitJumpTableInfo() {
218 // Nothing to do; jump tables are incorporated into the instruction stream.
219}
220
JF Bastienb6091df2015-08-25 22:58:05 +0000221void WebAssemblyAsmPrinter::EmitFunctionBodyStart() {
JF Bastienb6091df2015-08-25 22:58:05 +0000222 const Function *F = MF->getFunction();
Dan Gohman979840d2015-09-23 16:59:10 +0000223 Type *Rt = F->getReturnType();
JF Bastien1d20a5e2015-10-16 00:53:49 +0000224 SmallString<128> Str;
225 raw_svector_ostream OS(Str);
226 bool First = true;
Dan Gohmane51c0582015-10-06 00:27:55 +0000227
Dan Gohman1ce7ba52015-09-09 15:13:36 +0000228 if (!Rt->isVoidTy() || !F->arg_empty()) {
Dan Gohmane51c0582015-10-06 00:27:55 +0000229 for (const Argument &A : F->args()) {
JF Bastien1d20a5e2015-10-16 00:53:49 +0000230 OS << (First ? "" : "\n") << "\t.param " << toString(A.getType());
Dan Gohmane51c0582015-10-06 00:27:55 +0000231 First = false;
232 }
233 if (!Rt->isVoidTy()) {
JF Bastien1d20a5e2015-10-16 00:53:49 +0000234 OS << (First ? "" : "\n") << "\t.result " << toString(Rt);
Dan Gohmane51c0582015-10-06 00:27:55 +0000235 First = false;
236 }
Dan Gohman1ce7ba52015-09-09 15:13:36 +0000237 }
JF Bastienb6091df2015-08-25 22:58:05 +0000238
JF Bastien1d20a5e2015-10-16 00:53:49 +0000239 bool FirstVReg = true;
240 for (unsigned Idx = 0, IdxE = MRI->getNumVirtRegs(); Idx != IdxE; ++Idx) {
241 unsigned VReg = TargetRegisterInfo::index2VirtReg(Idx);
JF Bastien3428ed42015-10-17 00:25:38 +0000242 // FIXME: Don't skip dead virtual registers for now: that would require
243 // remapping all locals' numbers.
244 //if (!MRI->use_empty(VReg)) {
JF Bastien1d20a5e2015-10-16 00:53:49 +0000245 if (FirstVReg) {
246 OS << (First ? "" : "\n") << "\t.local ";
247 First = false;
248 }
249 OS << (FirstVReg ? "" : ", ") << getRegTypeName(VReg);
250 FirstVReg = false;
JF Bastien3428ed42015-10-17 00:25:38 +0000251 //}
JF Bastien1d20a5e2015-10-16 00:53:49 +0000252 }
253
254 if (!First)
255 OutStreamer->EmitRawText(OS.str());
Dan Gohmane51c0582015-10-06 00:27:55 +0000256 AsmPrinter::EmitFunctionBodyStart();
JF Bastienb6091df2015-08-25 22:58:05 +0000257}
258
JF Bastienb9073fb2015-07-22 21:28:15 +0000259void WebAssemblyAsmPrinter::EmitInstruction(const MachineInstr *MI) {
JF Bastienaf111db2015-08-24 22:16:48 +0000260 DEBUG(dbgs() << "EmitInstruction: " << *MI << '\n');
JF Bastienb9073fb2015-07-22 21:28:15 +0000261 SmallString<128> Str;
262 raw_svector_ostream OS(Str);
263
JF Bastien600aee92015-07-31 17:53:38 +0000264 unsigned NumDefs = MI->getDesc().getNumDefs();
265 assert(NumDefs <= 1 &&
266 "Instructions with multiple result values not implemented");
267
Dan Gohman12e19972015-08-24 21:19:48 +0000268 OS << '\t';
269
Dan Gohmane51c0582015-10-06 00:27:55 +0000270 switch (MI->getOpcode()) {
271 case TargetOpcode::COPY:
Dan Gohman4b96d8d2015-11-06 19:45:01 +0000272 OS << "get_local push, " << regToString(MI->getOperand(1));
Dan Gohmane51c0582015-10-06 00:27:55 +0000273 break;
274 case WebAssembly::GLOBAL:
275 // TODO: wasm64
Dan Gohman4b96d8d2015-11-06 19:45:01 +0000276 OS << "i32.const push, " << toSymbol(MI->getOperand(1).getGlobal()->getName());
Dan Gohmane51c0582015-10-06 00:27:55 +0000277 break;
278 case WebAssembly::ARGUMENT_I32:
279 case WebAssembly::ARGUMENT_I64:
280 case WebAssembly::ARGUMENT_F32:
281 case WebAssembly::ARGUMENT_F64:
Dan Gohman4b96d8d2015-11-06 19:45:01 +0000282 OS << "get_local push, " << argToString(MI->getOperand(1));
Dan Gohmane51c0582015-10-06 00:27:55 +0000283 break;
Dan Gohmanda7f4282015-11-05 20:44:29 +0000284 case WebAssembly::Const_I32:
Dan Gohman4b96d8d2015-11-06 19:45:01 +0000285 OS << "i32.const push, " << MI->getOperand(1).getImm();
Dan Gohmane51c0582015-10-06 00:27:55 +0000286 break;
Dan Gohmanda7f4282015-11-05 20:44:29 +0000287 case WebAssembly::Const_I64:
Dan Gohman4b96d8d2015-11-06 19:45:01 +0000288 OS << "i64.const push, " << MI->getOperand(1).getImm();
Dan Gohmane51c0582015-10-06 00:27:55 +0000289 break;
Dan Gohmanda7f4282015-11-05 20:44:29 +0000290 case WebAssembly::Const_F32:
Dan Gohman4b96d8d2015-11-06 19:45:01 +0000291 OS << "f32.const push, " << toString(MI->getOperand(1).getFPImm()->getValueAPF());
Dan Gohmane51c0582015-10-06 00:27:55 +0000292 break;
Dan Gohmanda7f4282015-11-05 20:44:29 +0000293 case WebAssembly::Const_F64:
Dan Gohman4b96d8d2015-11-06 19:45:01 +0000294 OS << "f64.const push, " << toString(MI->getOperand(1).getFPImm()->getValueAPF());
Dan Gohmane51c0582015-10-06 00:27:55 +0000295 break;
296 default: {
297 OS << OpcodeName(TII, MI);
298 bool NeedComma = false;
Dan Gohman4b96d8d2015-11-06 19:45:01 +0000299 bool DefsPushed = false;
300 if (NumDefs != 0 && !MI->isCall()) {
301 OS << " push";
302 NeedComma = true;
303 DefsPushed = true;
304 }
Dan Gohmane51c0582015-10-06 00:27:55 +0000305 for (const MachineOperand &MO : MI->uses()) {
306 if (MO.isReg() && MO.isImplicit())
307 continue;
308 if (NeedComma)
309 OS << ',';
310 NeedComma = true;
311 OS << ' ';
Dan Gohman4f52e002015-09-09 00:52:47 +0000312 switch (MO.getType()) {
313 default:
314 llvm_unreachable("unexpected machine operand type");
Dan Gohmane51c0582015-10-06 00:27:55 +0000315 case MachineOperand::MO_Register:
JF Bastien1d20a5e2015-10-16 00:53:49 +0000316 OS << "(get_local " << regToString(MO) << ')';
Dan Gohmane51c0582015-10-06 00:27:55 +0000317 break;
318 case MachineOperand::MO_Immediate:
319 OS << MO.getImm();
320 break;
321 case MachineOperand::MO_FPImmediate:
322 OS << toString(MO.getFPImm()->getValueAPF());
323 break;
324 case MachineOperand::MO_GlobalAddress:
325 OS << toSymbol(MO.getGlobal()->getName());
326 break;
327 case MachineOperand::MO_MachineBasicBlock:
328 OS << toSymbol(MO.getMBB()->getSymbol()->getName());
329 break;
Dan Gohman4f52e002015-09-09 00:52:47 +0000330 }
Dan Gohman4b96d8d2015-11-06 19:45:01 +0000331 if (NumDefs != 0 && !DefsPushed) {
332 // Special-case for calls; print the push after the callee.
333 assert(MI->isCall());
334 OS << ", push";
335 DefsPushed = true;
336 }
Dan Gohmane51c0582015-10-06 00:27:55 +0000337 }
338 break;
339 }
Dan Gohman4f52e002015-09-09 00:52:47 +0000340 }
JF Bastien600aee92015-07-31 17:53:38 +0000341
JF Bastienb9073fb2015-07-22 21:28:15 +0000342 OutStreamer->EmitRawText(OS.str());
Dan Gohmane51c0582015-10-06 00:27:55 +0000343
344 if (NumDefs != 0) {
345 SmallString<128> Str;
346 raw_svector_ostream OS(Str);
JF Bastien1d20a5e2015-10-16 00:53:49 +0000347 const MachineOperand &Operand = MI->getOperand(0);
348 OS << "\tset_local " << regToString(Operand) << ", pop";
Dan Gohmane51c0582015-10-06 00:27:55 +0000349 OutStreamer->EmitRawText(OS.str());
350 }
JF Bastienb9073fb2015-07-22 21:28:15 +0000351}
352
JF Bastien1a59c6b2015-10-21 02:23:09 +0000353void WebAssemblyAsmPrinter::EmitEndOfAsmFile(Module &M) {
JF Bastien5789a692015-10-30 16:41:21 +0000354 SmallString<128> Str;
355 raw_svector_ostream OS(Str);
JF Bastien1a59c6b2015-10-21 02:23:09 +0000356 for (const Function &F : M)
357 if (F.isDeclarationForLinker()) {
358 assert(F.hasName() && "imported functions must have a name");
359 if (F.getName().startswith("llvm."))
JF Bastien5789a692015-10-30 16:41:21 +0000360 continue;
JF Bastien1a59c6b2015-10-21 02:23:09 +0000361 if (Str.empty())
JF Bastien5789a692015-10-30 16:41:21 +0000362 OS << "\t.imports\n";
JF Bastien1a59c6b2015-10-21 02:23:09 +0000363 Type *Rt = F.getReturnType();
JF Bastien5789a692015-10-30 16:41:21 +0000364 OS << "\t.import " << toSymbol(F.getName()) << " \"\" \"" << F.getName()
365 << "\" (param";
JF Bastien1a59c6b2015-10-21 02:23:09 +0000366 for (const Argument &A : F.args())
JF Bastien5789a692015-10-30 16:41:21 +0000367 OS << ' ' << toString(A.getType());
368 OS << ')';
JF Bastien1a59c6b2015-10-21 02:23:09 +0000369 if (!Rt->isVoidTy())
JF Bastien5789a692015-10-30 16:41:21 +0000370 OS << " (result " << toString(Rt) << ')';
JF Bastien1a59c6b2015-10-21 02:23:09 +0000371 OS << '\n';
JF Bastien5789a692015-10-30 16:41:21 +0000372 }
JF Bastien1a59c6b2015-10-21 02:23:09 +0000373 OutStreamer->EmitRawText(OS.str());
374}
375
JF Bastienb9073fb2015-07-22 21:28:15 +0000376// Force static initialization.
377extern "C" void LLVMInitializeWebAssemblyAsmPrinter() {
378 RegisterAsmPrinter<WebAssemblyAsmPrinter> X(TheWebAssemblyTarget32);
379 RegisterAsmPrinter<WebAssemblyAsmPrinter> Y(TheWebAssemblyTarget64);
380}