blob: 9c5899991c7675d6c196e07d0483300ac6fde22b [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 Bastien600aee92015-07-31 17:53:38 +000043 const WebAssemblyInstrInfo *TII;
44
JF Bastienb9073fb2015-07-22 21:28:15 +000045public:
46 WebAssemblyAsmPrinter(TargetMachine &TM, std::unique_ptr<MCStreamer> Streamer)
Dan Gohman979840d2015-09-23 16:59:10 +000047 : AsmPrinter(TM, std::move(Streamer)), TII(nullptr) {}
JF Bastienb9073fb2015-07-22 21:28:15 +000048
49private:
50 const char *getPassName() const override {
51 return "WebAssembly Assembly Printer";
52 }
53
54 //===------------------------------------------------------------------===//
55 // MachineFunctionPass Implementation.
56 //===------------------------------------------------------------------===//
57
58 void getAnalysisUsage(AnalysisUsage &AU) const override {
59 AsmPrinter::getAnalysisUsage(AU);
60 }
61
JF Bastien600aee92015-07-31 17:53:38 +000062 bool runOnMachineFunction(MachineFunction &MF) override {
JF Bastien73ff6af2015-08-31 22:24:11 +000063 const auto &Subtarget = MF.getSubtarget<WebAssemblySubtarget>();
JF Bastien73ff6af2015-08-31 22:24:11 +000064 TII = Subtarget.getInstrInfo();
JF Bastien600aee92015-07-31 17:53:38 +000065 return AsmPrinter::runOnMachineFunction(MF);
JF Bastienb9073fb2015-07-22 21:28:15 +000066 }
67
68 //===------------------------------------------------------------------===//
69 // AsmPrinter Implementation.
70 //===------------------------------------------------------------------===//
71
JF Bastien45479f62015-08-26 22:09:54 +000072 void EmitGlobalVariable(const GlobalVariable *GV) override;
73
Dan Gohman950a13c2015-09-16 16:51:30 +000074 void EmitJumpTableInfo() override;
JF Bastien54be3b12015-08-25 23:19:49 +000075 void EmitConstantPool() override;
JF Bastienb6091df2015-08-25 22:58:05 +000076 void EmitFunctionEntryLabel() override;
77 void EmitFunctionBodyStart() override;
78 void EmitFunctionBodyEnd() override;
79
JF Bastienb9073fb2015-07-22 21:28:15 +000080 void EmitInstruction(const MachineInstr *MI) override;
Dan Gohman979840d2015-09-23 16:59:10 +000081
82 static std::string toString(const APFloat &APF);
83 const char *toString(Type *Ty) const;
JF Bastienb9073fb2015-07-22 21:28:15 +000084};
85
86} // end anonymous namespace
87
88//===----------------------------------------------------------------------===//
JF Bastien45479f62015-08-26 22:09:54 +000089// Helpers.
90//===----------------------------------------------------------------------===//
JF Bastienb9073fb2015-07-22 21:28:15 +000091
JF Bastien315cc062015-08-07 01:57:03 +000092// Untyped, lower-case version of the opcode's name matching the names
93// WebAssembly opcodes are expected to have. The tablegen names are uppercase
94// and suffixed with their type (after an underscore).
JF Bastien45479f62015-08-26 22:09:54 +000095static SmallString<32> OpcodeName(const WebAssemblyInstrInfo *TII,
96 const MachineInstr *MI) {
JF Bastien315cc062015-08-07 01:57:03 +000097 std::string N(StringRef(TII->getName(MI->getOpcode())).lower());
Dan Gohman69c4c762015-08-24 21:03:24 +000098 std::string::size_type End = N.rfind('_');
JF Bastien315cc062015-08-07 01:57:03 +000099 End = std::string::npos == End ? N.length() : End;
100 return SmallString<32>(&N[0], &N[End]);
101}
102
JF Bastienaf111db2015-08-24 22:16:48 +0000103static std::string toSymbol(StringRef S) { return ("$" + S).str(); }
104
Dan Gohman979840d2015-09-23 16:59:10 +0000105std::string WebAssemblyAsmPrinter::toString(const APFloat &FP) {
JF Bastien45479f62015-08-26 22:09:54 +0000106 static const size_t BufBytes = 128;
107 char buf[BufBytes];
108 if (FP.isNaN())
109 assert((FP.bitwiseIsEqual(APFloat::getQNaN(FP.getSemantics())) ||
110 FP.bitwiseIsEqual(
111 APFloat::getQNaN(FP.getSemantics(), /*Negative=*/true))) &&
112 "convertToHexString handles neither SNaN nor NaN payloads");
113 // Use C99's hexadecimal floating-point representation.
114 auto Written = FP.convertToHexString(
115 buf, /*hexDigits=*/0, /*upperCase=*/false, APFloat::rmNearestTiesToEven);
116 (void)Written;
117 assert(Written != 0);
118 assert(Written < BufBytes);
119 return buf;
120}
121
Dan Gohman979840d2015-09-23 16:59:10 +0000122const char *WebAssemblyAsmPrinter::toString(Type *Ty) const {
JF Bastien73ff6af2015-08-31 22:24:11 +0000123 switch (Ty->getTypeID()) {
Dan Gohman979840d2015-09-23 16:59:10 +0000124 default:
125 break;
JF Bastien73ff6af2015-08-31 22:24:11 +0000126 // Treat all pointers as the underlying integer into linear memory.
Dan Gohman979840d2015-09-23 16:59:10 +0000127 case Type::PointerTyID:
128 switch (getPointerSize()) {
129 case 4:
130 return "i32";
131 case 8:
132 return "i64";
133 default:
134 llvm_unreachable("unsupported pointer size");
135 }
136 break;
137 case Type::FloatTyID:
138 return "f32";
139 case Type::DoubleTyID:
140 return "f64";
JF Bastien73ff6af2015-08-31 22:24:11 +0000141 case Type::IntegerTyID:
142 switch (Ty->getIntegerBitWidth()) {
Dan Gohman979840d2015-09-23 16:59:10 +0000143 case 8:
144 return "i8";
145 case 16:
146 return "i16";
147 case 32:
148 return "i32";
149 case 64:
150 return "i64";
151 default:
152 break;
JF Bastien73ff6af2015-08-31 22:24:11 +0000153 }
154 }
155 DEBUG(dbgs() << "Invalid type "; Ty->print(dbgs()); dbgs() << '\n');
156 llvm_unreachable("invalid type");
157 return "<invalid>";
158}
159
JF Bastien45479f62015-08-26 22:09:54 +0000160//===----------------------------------------------------------------------===//
161// WebAssemblyAsmPrinter Implementation.
162//===----------------------------------------------------------------------===//
163
164void WebAssemblyAsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
165 SmallString<128> Str;
166 raw_svector_ostream OS(Str);
167 StringRef Name = GV->getName();
168 DEBUG(dbgs() << "Global " << Name << '\n');
169
170 if (!GV->hasInitializer()) {
171 DEBUG(dbgs() << " Skipping declaration.\n");
172 return;
173 }
174
175 // Check to see if this is a special global used by LLVM.
176 static const char *Ignored[] = {"llvm.used", "llvm.metadata"};
177 for (const char *I : Ignored)
178 if (Name == I)
179 return;
180 // FIXME: Handle the following globals.
181 static const char *Unhandled[] = {"llvm.global_ctors", "llvm.global_dtors"};
182 for (const char *U : Unhandled)
183 if (Name == U)
184 report_fatal_error("Unhandled global");
185 if (Name.startswith("llvm."))
186 report_fatal_error("Unknown LLVM-internal global");
187
188 if (GV->isThreadLocal())
189 report_fatal_error("TLS isn't yet supported by WebAssembly");
190
191 const DataLayout &DL = getDataLayout();
192 const Constant *Init = GV->getInitializer();
193 if (isa<UndefValue>(Init))
194 Init = Constant::getNullValue(Init->getType());
195 unsigned Align = DL.getPrefTypeAlignment(Init->getType());
196
197 switch (GV->getLinkage()) {
198 case GlobalValue::InternalLinkage:
199 case GlobalValue::PrivateLinkage:
200 break;
201 case GlobalValue::AppendingLinkage:
202 case GlobalValue::LinkOnceAnyLinkage:
203 case GlobalValue::LinkOnceODRLinkage:
204 case GlobalValue::WeakAnyLinkage:
205 case GlobalValue::WeakODRLinkage:
206 case GlobalValue::ExternalLinkage:
207 case GlobalValue::CommonLinkage:
208 report_fatal_error("Linkage types other than internal and private aren't "
JF Bastienb1b61eb2015-08-26 23:03:07 +0000209 "supported by WebAssembly yet");
JF Bastien45479f62015-08-26 22:09:54 +0000210 default:
211 llvm_unreachable("Unknown linkage type");
212 return;
213 }
214
Dan Gohman979840d2015-09-23 16:59:10 +0000215 OS << "(global " << toSymbol(Name) << ' ' << toString(Init->getType()) << ' ';
JF Bastien45479f62015-08-26 22:09:54 +0000216 if (const auto *C = dyn_cast<ConstantInt>(Init)) {
217 assert(C->getBitWidth() <= 64 && "Printing wider types unimplemented");
218 OS << C->getZExtValue();
219 } else if (const auto *C = dyn_cast<ConstantFP>(Init)) {
220 OS << toString(C->getValueAPF());
221 } else {
222 assert(false && "Only integer and floating-point constants are supported");
223 }
Dan Gohman1ce7ba52015-09-09 15:13:36 +0000224 OS << ") ;; align " << Align;
JF Bastien45479f62015-08-26 22:09:54 +0000225 OutStreamer->EmitRawText(OS.str());
226}
227
JF Bastien54be3b12015-08-25 23:19:49 +0000228void WebAssemblyAsmPrinter::EmitConstantPool() {
229 assert(MF->getConstantPool()->getConstants().empty() &&
230 "WebAssembly disables constant pools");
231}
232
Dan Gohman950a13c2015-09-16 16:51:30 +0000233void WebAssemblyAsmPrinter::EmitJumpTableInfo() {
234 // Nothing to do; jump tables are incorporated into the instruction stream.
235}
236
JF Bastienb6091df2015-08-25 22:58:05 +0000237void WebAssemblyAsmPrinter::EmitFunctionEntryLabel() {
238 SmallString<128> Str;
239 raw_svector_ostream OS(Str);
240
241 CurrentFnSym->redefineIfPossible();
242
243 // The function label could have already been emitted if two symbols end up
244 // conflicting due to asm renaming. Detect this and emit an error.
245 if (CurrentFnSym->isVariable())
246 report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
247 "' is a protected alias");
248 if (CurrentFnSym->isDefined())
249 report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
250 "' label emitted multiple times to assembly file");
251
252 OS << "(func " << toSymbol(CurrentFnSym->getName());
253 OutStreamer->EmitRawText(OS.str());
254}
255
256void WebAssemblyAsmPrinter::EmitFunctionBodyStart() {
257 SmallString<128> Str;
258 raw_svector_ostream OS(Str);
259 const Function *F = MF->getFunction();
Dan Gohman979840d2015-09-23 16:59:10 +0000260 Type *Rt = F->getReturnType();
Dan Gohman1ce7ba52015-09-09 15:13:36 +0000261 if (!Rt->isVoidTy() || !F->arg_empty()) {
262 for (const Argument &A : F->args())
Dan Gohman979840d2015-09-23 16:59:10 +0000263 OS << " (param " << toString(A.getType()) << ')';
Dan Gohman1ce7ba52015-09-09 15:13:36 +0000264 if (!Rt->isVoidTy())
Dan Gohman979840d2015-09-23 16:59:10 +0000265 OS << " (result " << toString(Rt) << ')';
Dan Gohman1ce7ba52015-09-09 15:13:36 +0000266 OutStreamer->EmitRawText(OS.str());
267 }
JF Bastienb6091df2015-08-25 22:58:05 +0000268}
269
270void WebAssemblyAsmPrinter::EmitFunctionBodyEnd() {
271 SmallString<128> Str;
272 raw_svector_ostream OS(Str);
Dan Gohman1ce7ba52015-09-09 15:13:36 +0000273 OS << ") ;; end func " << toSymbol(CurrentFnSym->getName());
JF Bastienb6091df2015-08-25 22:58:05 +0000274 OutStreamer->EmitRawText(OS.str());
275}
276
JF Bastienb9073fb2015-07-22 21:28:15 +0000277void WebAssemblyAsmPrinter::EmitInstruction(const MachineInstr *MI) {
JF Bastienaf111db2015-08-24 22:16:48 +0000278 DEBUG(dbgs() << "EmitInstruction: " << *MI << '\n');
JF Bastienb9073fb2015-07-22 21:28:15 +0000279 SmallString<128> Str;
280 raw_svector_ostream OS(Str);
281
JF Bastien600aee92015-07-31 17:53:38 +0000282 unsigned NumDefs = MI->getDesc().getNumDefs();
283 assert(NumDefs <= 1 &&
284 "Instructions with multiple result values not implemented");
285
Dan Gohman12e19972015-08-24 21:19:48 +0000286 OS << '\t';
287
JF Bastien600aee92015-07-31 17:53:38 +0000288 if (NumDefs != 0) {
289 const MachineOperand &MO = MI->getOperand(0);
290 unsigned Reg = MO.getReg();
291 OS << "(setlocal @" << TargetRegisterInfo::virtReg2Index(Reg) << ' ';
292 }
293
Dan Gohman4f52e002015-09-09 00:52:47 +0000294 if (MI->getOpcode() == WebAssembly::COPY) {
295 OS << '@' << TargetRegisterInfo::virtReg2Index(MI->getOperand(1).getReg());
296 } else {
297 OS << '(' << OpcodeName(TII, MI);
298 for (const MachineOperand &MO : MI->uses())
299 switch (MO.getType()) {
300 default:
301 llvm_unreachable("unexpected machine operand type");
302 case MachineOperand::MO_Register: {
303 if (MO.isImplicit())
304 continue;
305 unsigned Reg = MO.getReg();
306 OS << " @" << TargetRegisterInfo::virtReg2Index(Reg);
307 } break;
308 case MachineOperand::MO_Immediate: {
309 OS << ' ' << MO.getImm();
310 } break;
311 case MachineOperand::MO_FPImmediate: {
312 OS << ' ' << toString(MO.getFPImm()->getValueAPF());
313 } break;
314 case MachineOperand::MO_GlobalAddress: {
315 OS << ' ' << toSymbol(MO.getGlobal()->getName());
316 } break;
Dan Gohman950a13c2015-09-16 16:51:30 +0000317 case MachineOperand::MO_MachineBasicBlock: {
318 OS << ' ' << toSymbol(MO.getMBB()->getSymbol()->getName());
319 } break;
Dan Gohman4f52e002015-09-09 00:52:47 +0000320 }
321 OS << ')';
322 }
JF Bastien600aee92015-07-31 17:53:38 +0000323
324 if (NumDefs != 0)
325 OS << ')';
326
JF Bastienb9073fb2015-07-22 21:28:15 +0000327 OutStreamer->EmitRawText(OS.str());
328}
329
330// Force static initialization.
331extern "C" void LLVMInitializeWebAssemblyAsmPrinter() {
332 RegisterAsmPrinter<WebAssemblyAsmPrinter> X(TheWebAssemblyTarget32);
333 RegisterAsmPrinter<WebAssemblyAsmPrinter> Y(TheWebAssemblyTarget64);
334}