blob: ea42470ab00fec45f0e127fc3f9324b7073e2dae [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)
JF Bastien600aee92015-07-31 17:53:38 +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 {
Dan Gohmane419a7c2015-08-24 16:46:31 +000063 TII = MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
JF Bastien600aee92015-07-31 17:53:38 +000064 return AsmPrinter::runOnMachineFunction(MF);
JF Bastienb9073fb2015-07-22 21:28:15 +000065 }
66
67 //===------------------------------------------------------------------===//
68 // AsmPrinter Implementation.
69 //===------------------------------------------------------------------===//
70
JF Bastien45479f62015-08-26 22:09:54 +000071 void EmitGlobalVariable(const GlobalVariable *GV) override;
72
JF Bastien54be3b12015-08-25 23:19:49 +000073 void EmitConstantPool() override;
JF Bastienb6091df2015-08-25 22:58:05 +000074 void EmitFunctionEntryLabel() override;
75 void EmitFunctionBodyStart() override;
76 void EmitFunctionBodyEnd() override;
77
JF Bastienb9073fb2015-07-22 21:28:15 +000078 void EmitInstruction(const MachineInstr *MI) override;
79};
80
81} // end anonymous namespace
82
83//===----------------------------------------------------------------------===//
JF Bastien45479f62015-08-26 22:09:54 +000084// Helpers.
85//===----------------------------------------------------------------------===//
JF Bastienb9073fb2015-07-22 21:28:15 +000086
JF Bastien315cc062015-08-07 01:57:03 +000087// Untyped, lower-case version of the opcode's name matching the names
88// WebAssembly opcodes are expected to have. The tablegen names are uppercase
89// and suffixed with their type (after an underscore).
JF Bastien45479f62015-08-26 22:09:54 +000090static SmallString<32> OpcodeName(const WebAssemblyInstrInfo *TII,
91 const MachineInstr *MI) {
JF Bastien315cc062015-08-07 01:57:03 +000092 std::string N(StringRef(TII->getName(MI->getOpcode())).lower());
Dan Gohman69c4c762015-08-24 21:03:24 +000093 std::string::size_type End = N.rfind('_');
JF Bastien315cc062015-08-07 01:57:03 +000094 End = std::string::npos == End ? N.length() : End;
95 return SmallString<32>(&N[0], &N[End]);
96}
97
JF Bastienaf111db2015-08-24 22:16:48 +000098static std::string toSymbol(StringRef S) { return ("$" + S).str(); }
99
JF Bastien45479f62015-08-26 22:09:54 +0000100static const char *toString(const Type *Ty) {
JF Bastienb6091df2015-08-25 22:58:05 +0000101 switch (Ty->getTypeID()) {
102 default: break;
103 case Type::FloatTyID: return "f32";
104 case Type::DoubleTyID: return "f64";
105 case Type::IntegerTyID:
106 switch (Ty->getIntegerBitWidth()) {
107 case 32: return "i32";
108 case 64: return "i64";
109 default: break;
110 }
111 }
112 DEBUG(dbgs() << "Invalid type "; Ty->print(dbgs()); dbgs() << '\n');
113 llvm_unreachable("invalid type");
114 return "<invalid>";
115}
116
JF Bastien45479f62015-08-26 22:09:54 +0000117static std::string toString(const APFloat &FP) {
118 static const size_t BufBytes = 128;
119 char buf[BufBytes];
120 if (FP.isNaN())
121 assert((FP.bitwiseIsEqual(APFloat::getQNaN(FP.getSemantics())) ||
122 FP.bitwiseIsEqual(
123 APFloat::getQNaN(FP.getSemantics(), /*Negative=*/true))) &&
124 "convertToHexString handles neither SNaN nor NaN payloads");
125 // Use C99's hexadecimal floating-point representation.
126 auto Written = FP.convertToHexString(
127 buf, /*hexDigits=*/0, /*upperCase=*/false, APFloat::rmNearestTiesToEven);
128 (void)Written;
129 assert(Written != 0);
130 assert(Written < BufBytes);
131 return buf;
132}
133
134//===----------------------------------------------------------------------===//
135// WebAssemblyAsmPrinter Implementation.
136//===----------------------------------------------------------------------===//
137
138void WebAssemblyAsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
139 SmallString<128> Str;
140 raw_svector_ostream OS(Str);
141 StringRef Name = GV->getName();
142 DEBUG(dbgs() << "Global " << Name << '\n');
143
144 if (!GV->hasInitializer()) {
145 DEBUG(dbgs() << " Skipping declaration.\n");
146 return;
147 }
148
149 // Check to see if this is a special global used by LLVM.
150 static const char *Ignored[] = {"llvm.used", "llvm.metadata"};
151 for (const char *I : Ignored)
152 if (Name == I)
153 return;
154 // FIXME: Handle the following globals.
155 static const char *Unhandled[] = {"llvm.global_ctors", "llvm.global_dtors"};
156 for (const char *U : Unhandled)
157 if (Name == U)
158 report_fatal_error("Unhandled global");
159 if (Name.startswith("llvm."))
160 report_fatal_error("Unknown LLVM-internal global");
161
162 if (GV->isThreadLocal())
163 report_fatal_error("TLS isn't yet supported by WebAssembly");
164
165 const DataLayout &DL = getDataLayout();
166 const Constant *Init = GV->getInitializer();
167 if (isa<UndefValue>(Init))
168 Init = Constant::getNullValue(Init->getType());
169 unsigned Align = DL.getPrefTypeAlignment(Init->getType());
170
171 switch (GV->getLinkage()) {
172 case GlobalValue::InternalLinkage:
173 case GlobalValue::PrivateLinkage:
174 break;
175 case GlobalValue::AppendingLinkage:
176 case GlobalValue::LinkOnceAnyLinkage:
177 case GlobalValue::LinkOnceODRLinkage:
178 case GlobalValue::WeakAnyLinkage:
179 case GlobalValue::WeakODRLinkage:
180 case GlobalValue::ExternalLinkage:
181 case GlobalValue::CommonLinkage:
182 report_fatal_error("Linkage types other than internal and private aren't "
183 "supported by WebAssembly");
184 default:
185 llvm_unreachable("Unknown linkage type");
186 return;
187 }
188
189 OS << "(global " << toSymbol(Name) << ' ' << toString(Init->getType()) << ' ';
190 if (const auto *C = dyn_cast<ConstantInt>(Init)) {
191 assert(C->getBitWidth() <= 64 && "Printing wider types unimplemented");
192 OS << C->getZExtValue();
193 } else if (const auto *C = dyn_cast<ConstantFP>(Init)) {
194 OS << toString(C->getValueAPF());
195 } else {
196 assert(false && "Only integer and floating-point constants are supported");
197 }
198 OS << ") ;; align " << Align << "\n";
199 OutStreamer->EmitRawText(OS.str());
200}
201
JF Bastien54be3b12015-08-25 23:19:49 +0000202void WebAssemblyAsmPrinter::EmitConstantPool() {
203 assert(MF->getConstantPool()->getConstants().empty() &&
204 "WebAssembly disables constant pools");
205}
206
JF Bastienb6091df2015-08-25 22:58:05 +0000207void WebAssemblyAsmPrinter::EmitFunctionEntryLabel() {
208 SmallString<128> Str;
209 raw_svector_ostream OS(Str);
210
211 CurrentFnSym->redefineIfPossible();
212
213 // The function label could have already been emitted if two symbols end up
214 // conflicting due to asm renaming. Detect this and emit an error.
215 if (CurrentFnSym->isVariable())
216 report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
217 "' is a protected alias");
218 if (CurrentFnSym->isDefined())
219 report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
220 "' label emitted multiple times to assembly file");
221
222 OS << "(func " << toSymbol(CurrentFnSym->getName());
223 OutStreamer->EmitRawText(OS.str());
224}
225
226void WebAssemblyAsmPrinter::EmitFunctionBodyStart() {
227 SmallString<128> Str;
228 raw_svector_ostream OS(Str);
229 const Function *F = MF->getFunction();
230 for (const Argument &A : F->args())
JF Bastien45479f62015-08-26 22:09:54 +0000231 OS << " (param " << toString(A.getType()) << ')';
JF Bastienb6091df2015-08-25 22:58:05 +0000232 const Type *Rt = F->getReturnType();
233 if (!Rt->isVoidTy())
JF Bastien45479f62015-08-26 22:09:54 +0000234 OS << " (result " << toString(Rt) << ')';
JF Bastienb6091df2015-08-25 22:58:05 +0000235 OS << '\n';
236 OutStreamer->EmitRawText(OS.str());
237}
238
239void WebAssemblyAsmPrinter::EmitFunctionBodyEnd() {
240 SmallString<128> Str;
241 raw_svector_ostream OS(Str);
242 OS << ") ;; end func " << toSymbol(CurrentFnSym->getName()) << '\n';
243 OutStreamer->EmitRawText(OS.str());
244}
245
JF Bastienb9073fb2015-07-22 21:28:15 +0000246void WebAssemblyAsmPrinter::EmitInstruction(const MachineInstr *MI) {
JF Bastienaf111db2015-08-24 22:16:48 +0000247 DEBUG(dbgs() << "EmitInstruction: " << *MI << '\n');
JF Bastienb9073fb2015-07-22 21:28:15 +0000248 SmallString<128> Str;
249 raw_svector_ostream OS(Str);
250
JF Bastien600aee92015-07-31 17:53:38 +0000251 unsigned NumDefs = MI->getDesc().getNumDefs();
252 assert(NumDefs <= 1 &&
253 "Instructions with multiple result values not implemented");
254
Dan Gohman12e19972015-08-24 21:19:48 +0000255 OS << '\t';
256
JF Bastien600aee92015-07-31 17:53:38 +0000257 if (NumDefs != 0) {
258 const MachineOperand &MO = MI->getOperand(0);
259 unsigned Reg = MO.getReg();
260 OS << "(setlocal @" << TargetRegisterInfo::virtReg2Index(Reg) << ' ';
261 }
262
JF Bastien45479f62015-08-26 22:09:54 +0000263 OS << '(' << OpcodeName(TII, MI);
JF Bastien4a642252015-08-10 22:36:48 +0000264 for (const MachineOperand &MO : MI->uses())
265 switch (MO.getType()) {
266 default:
267 llvm_unreachable("unexpected machine operand type");
268 case MachineOperand::MO_Register: {
269 if (MO.isImplicit())
JF Bastien600aee92015-07-31 17:53:38 +0000270 continue;
271 unsigned Reg = MO.getReg();
272 OS << " @" << TargetRegisterInfo::virtReg2Index(Reg);
JF Bastien4a642252015-08-10 22:36:48 +0000273 } break;
274 case MachineOperand::MO_Immediate: {
275 OS << ' ' << MO.getImm();
276 } break;
277 case MachineOperand::MO_FPImmediate: {
JF Bastien45479f62015-08-26 22:09:54 +0000278 OS << ' ' << toString(MO.getFPImm()->getValueAPF());
JF Bastien4a642252015-08-10 22:36:48 +0000279 } break;
JF Bastienaf111db2015-08-24 22:16:48 +0000280 case MachineOperand::MO_GlobalAddress: {
281 OS << ' ' << toSymbol(MO.getGlobal()->getName());
282 } break;
JF Bastien600aee92015-07-31 17:53:38 +0000283 }
284 OS << ')';
285
286 if (NumDefs != 0)
287 OS << ')';
288
289 OS << '\n';
290
JF Bastienb9073fb2015-07-22 21:28:15 +0000291 OutStreamer->EmitRawText(OS.str());
292}
293
294// Force static initialization.
295extern "C" void LLVMInitializeWebAssemblyAsmPrinter() {
296 RegisterAsmPrinter<WebAssemblyAsmPrinter> X(TheWebAssemblyTarget32);
297 RegisterAsmPrinter<WebAssemblyAsmPrinter> Y(TheWebAssemblyTarget64);
298}