blob: eb1343292d3c067487f67191846ddcb188304498 [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"
25#include "llvm/CodeGen/AsmPrinter.h"
JF Bastien54be3b12015-08-25 23:19:49 +000026#include "llvm/CodeGen/MachineConstantPool.h"
JF Bastienb9073fb2015-07-22 21:28:15 +000027#include "llvm/CodeGen/MachineInstr.h"
28#include "llvm/IR/DataLayout.h"
29#include "llvm/IR/DebugInfo.h"
30#include "llvm/MC/MCStreamer.h"
JF Bastienb6091df2015-08-25 22:58:05 +000031#include "llvm/MC/MCSymbol.h"
JF Bastienb9073fb2015-07-22 21:28:15 +000032#include "llvm/Support/Debug.h"
33#include "llvm/Support/TargetRegistry.h"
34#include "llvm/Support/raw_ostream.h"
35
36using namespace llvm;
37
38#define DEBUG_TYPE "asm-printer"
39
40namespace {
41
42class WebAssemblyAsmPrinter final : public AsmPrinter {
JF Bastien73ff6af2015-08-31 22:24:11 +000043 bool hasAddr64;
JF Bastien600aee92015-07-31 17:53:38 +000044 const WebAssemblyInstrInfo *TII;
45
JF Bastienb9073fb2015-07-22 21:28:15 +000046public:
47 WebAssemblyAsmPrinter(TargetMachine &TM, std::unique_ptr<MCStreamer> Streamer)
JF Bastien600aee92015-07-31 17:53:38 +000048 : AsmPrinter(TM, std::move(Streamer)), TII(nullptr) {}
JF Bastienb9073fb2015-07-22 21:28:15 +000049
50private:
51 const char *getPassName() const override {
52 return "WebAssembly Assembly Printer";
53 }
54
55 //===------------------------------------------------------------------===//
56 // MachineFunctionPass Implementation.
57 //===------------------------------------------------------------------===//
58
59 void getAnalysisUsage(AnalysisUsage &AU) const override {
60 AsmPrinter::getAnalysisUsage(AU);
61 }
62
JF Bastien600aee92015-07-31 17:53:38 +000063 bool runOnMachineFunction(MachineFunction &MF) override {
JF Bastien73ff6af2015-08-31 22:24:11 +000064 const auto &Subtarget = MF.getSubtarget<WebAssemblySubtarget>();
65 hasAddr64 = Subtarget.hasAddr64();
66 TII = Subtarget.getInstrInfo();
JF Bastien600aee92015-07-31 17:53:38 +000067 return AsmPrinter::runOnMachineFunction(MF);
JF Bastienb9073fb2015-07-22 21:28:15 +000068 }
69
70 //===------------------------------------------------------------------===//
71 // AsmPrinter Implementation.
72 //===------------------------------------------------------------------===//
73
JF Bastien45479f62015-08-26 22:09:54 +000074 void EmitGlobalVariable(const GlobalVariable *GV) override;
75
JF Bastien54be3b12015-08-25 23:19:49 +000076 void EmitConstantPool() override;
JF Bastienb6091df2015-08-25 22:58:05 +000077 void EmitFunctionEntryLabel() override;
78 void EmitFunctionBodyStart() override;
79 void EmitFunctionBodyEnd() override;
80
JF Bastienb9073fb2015-07-22 21:28:15 +000081 void EmitInstruction(const MachineInstr *MI) override;
82};
83
84} // end anonymous namespace
85
86//===----------------------------------------------------------------------===//
JF Bastien45479f62015-08-26 22:09:54 +000087// Helpers.
88//===----------------------------------------------------------------------===//
JF Bastienb9073fb2015-07-22 21:28:15 +000089
JF Bastien315cc062015-08-07 01:57:03 +000090// Untyped, lower-case version of the opcode's name matching the names
91// WebAssembly opcodes are expected to have. The tablegen names are uppercase
92// and suffixed with their type (after an underscore).
JF Bastien45479f62015-08-26 22:09:54 +000093static SmallString<32> OpcodeName(const WebAssemblyInstrInfo *TII,
94 const MachineInstr *MI) {
JF Bastien315cc062015-08-07 01:57:03 +000095 std::string N(StringRef(TII->getName(MI->getOpcode())).lower());
Dan Gohman69c4c762015-08-24 21:03:24 +000096 std::string::size_type End = N.rfind('_');
JF Bastien315cc062015-08-07 01:57:03 +000097 End = std::string::npos == End ? N.length() : End;
98 return SmallString<32>(&N[0], &N[End]);
99}
100
JF Bastienaf111db2015-08-24 22:16:48 +0000101static std::string toSymbol(StringRef S) { return ("$" + S).str(); }
102
JF Bastien45479f62015-08-26 22:09:54 +0000103static std::string toString(const APFloat &FP) {
104 static const size_t BufBytes = 128;
105 char buf[BufBytes];
106 if (FP.isNaN())
107 assert((FP.bitwiseIsEqual(APFloat::getQNaN(FP.getSemantics())) ||
108 FP.bitwiseIsEqual(
109 APFloat::getQNaN(FP.getSemantics(), /*Negative=*/true))) &&
110 "convertToHexString handles neither SNaN nor NaN payloads");
111 // Use C99's hexadecimal floating-point representation.
112 auto Written = FP.convertToHexString(
113 buf, /*hexDigits=*/0, /*upperCase=*/false, APFloat::rmNearestTiesToEven);
114 (void)Written;
115 assert(Written != 0);
116 assert(Written < BufBytes);
117 return buf;
118}
119
JF Bastien73ff6af2015-08-31 22:24:11 +0000120static const char *toString(const Type *Ty, bool hasAddr64) {
121 switch (Ty->getTypeID()) {
122 default: break;
123 // Treat all pointers as the underlying integer into linear memory.
124 case Type::PointerTyID: return hasAddr64 ? "i64" : "i32";
125 case Type::FloatTyID: return "f32";
126 case Type::DoubleTyID: return "f64";
127 case Type::IntegerTyID:
128 switch (Ty->getIntegerBitWidth()) {
129 case 8: return "i8";
130 case 16: return "i16";
131 case 32: return "i32";
132 case 64: return "i64";
133 default: break;
134 }
135 }
136 DEBUG(dbgs() << "Invalid type "; Ty->print(dbgs()); dbgs() << '\n');
137 llvm_unreachable("invalid type");
138 return "<invalid>";
139}
140
141
JF Bastien45479f62015-08-26 22:09:54 +0000142//===----------------------------------------------------------------------===//
143// WebAssemblyAsmPrinter Implementation.
144//===----------------------------------------------------------------------===//
145
146void WebAssemblyAsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
147 SmallString<128> Str;
148 raw_svector_ostream OS(Str);
149 StringRef Name = GV->getName();
150 DEBUG(dbgs() << "Global " << Name << '\n');
151
152 if (!GV->hasInitializer()) {
153 DEBUG(dbgs() << " Skipping declaration.\n");
154 return;
155 }
156
157 // Check to see if this is a special global used by LLVM.
158 static const char *Ignored[] = {"llvm.used", "llvm.metadata"};
159 for (const char *I : Ignored)
160 if (Name == I)
161 return;
162 // FIXME: Handle the following globals.
163 static const char *Unhandled[] = {"llvm.global_ctors", "llvm.global_dtors"};
164 for (const char *U : Unhandled)
165 if (Name == U)
166 report_fatal_error("Unhandled global");
167 if (Name.startswith("llvm."))
168 report_fatal_error("Unknown LLVM-internal global");
169
170 if (GV->isThreadLocal())
171 report_fatal_error("TLS isn't yet supported by WebAssembly");
172
173 const DataLayout &DL = getDataLayout();
174 const Constant *Init = GV->getInitializer();
175 if (isa<UndefValue>(Init))
176 Init = Constant::getNullValue(Init->getType());
177 unsigned Align = DL.getPrefTypeAlignment(Init->getType());
178
179 switch (GV->getLinkage()) {
180 case GlobalValue::InternalLinkage:
181 case GlobalValue::PrivateLinkage:
182 break;
183 case GlobalValue::AppendingLinkage:
184 case GlobalValue::LinkOnceAnyLinkage:
185 case GlobalValue::LinkOnceODRLinkage:
186 case GlobalValue::WeakAnyLinkage:
187 case GlobalValue::WeakODRLinkage:
188 case GlobalValue::ExternalLinkage:
189 case GlobalValue::CommonLinkage:
190 report_fatal_error("Linkage types other than internal and private aren't "
JF Bastienb1b61eb2015-08-26 23:03:07 +0000191 "supported by WebAssembly yet");
JF Bastien45479f62015-08-26 22:09:54 +0000192 default:
193 llvm_unreachable("Unknown linkage type");
194 return;
195 }
196
JF Bastien73ff6af2015-08-31 22:24:11 +0000197 OS << "(global " << toSymbol(Name) << ' '
198 << toString(Init->getType(), hasAddr64) << ' ';
JF Bastien45479f62015-08-26 22:09:54 +0000199 if (const auto *C = dyn_cast<ConstantInt>(Init)) {
200 assert(C->getBitWidth() <= 64 && "Printing wider types unimplemented");
201 OS << C->getZExtValue();
202 } else if (const auto *C = dyn_cast<ConstantFP>(Init)) {
203 OS << toString(C->getValueAPF());
204 } else {
205 assert(false && "Only integer and floating-point constants are supported");
206 }
207 OS << ") ;; align " << Align << "\n";
208 OutStreamer->EmitRawText(OS.str());
209}
210
JF Bastien54be3b12015-08-25 23:19:49 +0000211void WebAssemblyAsmPrinter::EmitConstantPool() {
212 assert(MF->getConstantPool()->getConstants().empty() &&
213 "WebAssembly disables constant pools");
214}
215
JF Bastienb6091df2015-08-25 22:58:05 +0000216void WebAssemblyAsmPrinter::EmitFunctionEntryLabel() {
217 SmallString<128> Str;
218 raw_svector_ostream OS(Str);
219
220 CurrentFnSym->redefineIfPossible();
221
222 // The function label could have already been emitted if two symbols end up
223 // conflicting due to asm renaming. Detect this and emit an error.
224 if (CurrentFnSym->isVariable())
225 report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
226 "' is a protected alias");
227 if (CurrentFnSym->isDefined())
228 report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
229 "' label emitted multiple times to assembly file");
230
231 OS << "(func " << toSymbol(CurrentFnSym->getName());
232 OutStreamer->EmitRawText(OS.str());
233}
234
235void WebAssemblyAsmPrinter::EmitFunctionBodyStart() {
236 SmallString<128> Str;
237 raw_svector_ostream OS(Str);
238 const Function *F = MF->getFunction();
239 for (const Argument &A : F->args())
JF Bastien73ff6af2015-08-31 22:24:11 +0000240 OS << " (param " << toString(A.getType(), hasAddr64) << ')';
JF Bastienb6091df2015-08-25 22:58:05 +0000241 const Type *Rt = F->getReturnType();
242 if (!Rt->isVoidTy())
JF Bastien73ff6af2015-08-31 22:24:11 +0000243 OS << " (result " << toString(Rt, hasAddr64) << ')';
JF Bastienb6091df2015-08-25 22:58:05 +0000244 OS << '\n';
245 OutStreamer->EmitRawText(OS.str());
246}
247
248void WebAssemblyAsmPrinter::EmitFunctionBodyEnd() {
249 SmallString<128> Str;
250 raw_svector_ostream OS(Str);
251 OS << ") ;; end func " << toSymbol(CurrentFnSym->getName()) << '\n';
252 OutStreamer->EmitRawText(OS.str());
253}
254
JF Bastienb9073fb2015-07-22 21:28:15 +0000255void WebAssemblyAsmPrinter::EmitInstruction(const MachineInstr *MI) {
JF Bastienaf111db2015-08-24 22:16:48 +0000256 DEBUG(dbgs() << "EmitInstruction: " << *MI << '\n');
JF Bastienb9073fb2015-07-22 21:28:15 +0000257 SmallString<128> Str;
258 raw_svector_ostream OS(Str);
259
JF Bastien600aee92015-07-31 17:53:38 +0000260 unsigned NumDefs = MI->getDesc().getNumDefs();
261 assert(NumDefs <= 1 &&
262 "Instructions with multiple result values not implemented");
263
Dan Gohman12e19972015-08-24 21:19:48 +0000264 OS << '\t';
265
JF Bastien600aee92015-07-31 17:53:38 +0000266 if (NumDefs != 0) {
267 const MachineOperand &MO = MI->getOperand(0);
268 unsigned Reg = MO.getReg();
269 OS << "(setlocal @" << TargetRegisterInfo::virtReg2Index(Reg) << ' ';
270 }
271
JF Bastien45479f62015-08-26 22:09:54 +0000272 OS << '(' << OpcodeName(TII, MI);
JF Bastien4a642252015-08-10 22:36:48 +0000273 for (const MachineOperand &MO : MI->uses())
274 switch (MO.getType()) {
275 default:
276 llvm_unreachable("unexpected machine operand type");
277 case MachineOperand::MO_Register: {
278 if (MO.isImplicit())
JF Bastien600aee92015-07-31 17:53:38 +0000279 continue;
280 unsigned Reg = MO.getReg();
281 OS << " @" << TargetRegisterInfo::virtReg2Index(Reg);
JF Bastien4a642252015-08-10 22:36:48 +0000282 } break;
283 case MachineOperand::MO_Immediate: {
284 OS << ' ' << MO.getImm();
285 } break;
286 case MachineOperand::MO_FPImmediate: {
JF Bastien45479f62015-08-26 22:09:54 +0000287 OS << ' ' << toString(MO.getFPImm()->getValueAPF());
JF Bastien4a642252015-08-10 22:36:48 +0000288 } break;
JF Bastienaf111db2015-08-24 22:16:48 +0000289 case MachineOperand::MO_GlobalAddress: {
290 OS << ' ' << toSymbol(MO.getGlobal()->getName());
291 } break;
JF Bastien600aee92015-07-31 17:53:38 +0000292 }
293 OS << ')';
294
295 if (NumDefs != 0)
296 OS << ')';
297
298 OS << '\n';
299
JF Bastienb9073fb2015-07-22 21:28:15 +0000300 OutStreamer->EmitRawText(OS.str());
301}
302
303// Force static initialization.
304extern "C" void LLVMInitializeWebAssemblyAsmPrinter() {
305 RegisterAsmPrinter<WebAssemblyAsmPrinter> X(TheWebAssemblyTarget32);
306 RegisterAsmPrinter<WebAssemblyAsmPrinter> Y(TheWebAssemblyTarget64);
307}