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 /// 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 "WebAssemblyAsmPrinter.h"
18 #include "InstPrinter/WebAssemblyInstPrinter.h"
19 #include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
20 #include "MCTargetDesc/WebAssemblyTargetStreamer.h"
21 #include "WebAssembly.h"
22 #include "WebAssemblyMCInstLower.h"
23 #include "WebAssemblyMachineFunctionInfo.h"
24 #include "WebAssemblyRegisterInfo.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/CodeGen/Analysis.h"
27 #include "llvm/CodeGen/AsmPrinter.h"
28 #include "llvm/CodeGen/MachineConstantPool.h"
29 #include "llvm/CodeGen/MachineInstr.h"
30 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
31 #include "llvm/IR/DataLayout.h"
32 #include "llvm/IR/GlobalVariable.h"
33 #include "llvm/MC/MCContext.h"
34 #include "llvm/MC/MCSectionWasm.h"
35 #include "llvm/MC/MCStreamer.h"
36 #include "llvm/MC/MCSymbol.h"
37 #include "llvm/MC/MCSymbolWasm.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/TargetRegistry.h"
40 #include "llvm/Support/raw_ostream.h"
41 using namespace llvm;
42 
43 #define DEBUG_TYPE "asm-printer"
44 
45 //===----------------------------------------------------------------------===//
46 // Helpers.
47 //===----------------------------------------------------------------------===//
48 
getRegType(unsigned RegNo) const49 MVT WebAssemblyAsmPrinter::getRegType(unsigned RegNo) const {
50   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
51   const TargetRegisterClass *TRC = MRI->getRegClass(RegNo);
52   for (MVT T : {MVT::i32, MVT::i64, MVT::f32, MVT::f64, MVT::v16i8, MVT::v8i16,
53                 MVT::v4i32, MVT::v2i64, MVT::v4f32, MVT::v2f64})
54     if (TRI->isTypeLegalForClass(*TRC, T))
55       return T;
56   LLVM_DEBUG(errs() << "Unknown type for register number: " << RegNo);
57   llvm_unreachable("Unknown register type");
58   return MVT::Other;
59 }
60 
regToString(const MachineOperand & MO)61 std::string WebAssemblyAsmPrinter::regToString(const MachineOperand &MO) {
62   unsigned RegNo = MO.getReg();
63   assert(TargetRegisterInfo::isVirtualRegister(RegNo) &&
64          "Unlowered physical register encountered during assembly printing");
65   assert(!MFI->isVRegStackified(RegNo));
66   unsigned WAReg = MFI->getWAReg(RegNo);
67   assert(WAReg != WebAssemblyFunctionInfo::UnusedReg);
68   return '$' + utostr(WAReg);
69 }
70 
getTargetStreamer()71 WebAssemblyTargetStreamer *WebAssemblyAsmPrinter::getTargetStreamer() {
72   MCTargetStreamer *TS = OutStreamer->getTargetStreamer();
73   return static_cast<WebAssemblyTargetStreamer *>(TS);
74 }
75 
76 //===----------------------------------------------------------------------===//
77 // WebAssemblyAsmPrinter Implementation.
78 //===----------------------------------------------------------------------===//
79 
EmitEndOfAsmFile(Module & M)80 void WebAssemblyAsmPrinter::EmitEndOfAsmFile(Module &M) {
81   for (auto &It : OutContext.getSymbols()) {
82     // Emit a .globaltype and .eventtype declaration.
83     auto Sym = cast<MCSymbolWasm>(It.getValue());
84     if (Sym->getType() == wasm::WASM_SYMBOL_TYPE_GLOBAL)
85       getTargetStreamer()->emitGlobalType(Sym);
86     else if (Sym->getType() == wasm::WASM_SYMBOL_TYPE_EVENT)
87       getTargetStreamer()->emitEventType(Sym);
88   }
89 
90   for (const auto &F : M) {
91     // Emit function type info for all undefined functions
92     if (F.isDeclarationForLinker() && !F.isIntrinsic()) {
93       SmallVector<MVT, 4> Results;
94       SmallVector<MVT, 4> Params;
95       ComputeSignatureVTs(F.getFunctionType(), F, TM, Params, Results);
96       auto *Sym = cast<MCSymbolWasm>(getSymbol(&F));
97       Sym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
98       if (!Sym->getSignature()) {
99         auto Signature = SignatureFromMVTs(Results, Params);
100         Sym->setSignature(Signature.get());
101         addSignature(std::move(Signature));
102       }
103       // FIXME: this was originally intended for post-linking and was only used
104       // for imports that were only called indirectly (i.e. s2wasm could not
105       // infer the type from a call). With object files it applies to all
106       // imports. so fix the names and the tests, or rethink how import
107       // delcarations work in asm files.
108       getTargetStreamer()->emitFunctionType(Sym);
109 
110       if (TM.getTargetTriple().isOSBinFormatWasm() &&
111           F.hasFnAttribute("wasm-import-module")) {
112         StringRef Name =
113             F.getFnAttribute("wasm-import-module").getValueAsString();
114         Sym->setImportModule(Name);
115         getTargetStreamer()->emitImportModule(Sym, Name);
116       }
117       if (TM.getTargetTriple().isOSBinFormatWasm() &&
118           F.hasFnAttribute("wasm-import-name")) {
119         StringRef Name =
120             F.getFnAttribute("wasm-import-name").getValueAsString();
121         Sym->setImportName(Name);
122         getTargetStreamer()->emitImportName(Sym, Name);
123       }
124     }
125   }
126 
127   for (const auto &G : M.globals()) {
128     if (!G.hasInitializer() && G.hasExternalLinkage()) {
129       if (G.getValueType()->isSized()) {
130         uint16_t Size = M.getDataLayout().getTypeAllocSize(G.getValueType());
131         OutStreamer->emitELFSize(getSymbol(&G),
132                                  MCConstantExpr::create(Size, OutContext));
133       }
134     }
135   }
136 
137   if (const NamedMDNode *Named = M.getNamedMetadata("wasm.custom_sections")) {
138     for (const Metadata *MD : Named->operands()) {
139       const MDTuple *Tuple = dyn_cast<MDTuple>(MD);
140       if (!Tuple || Tuple->getNumOperands() != 2)
141         continue;
142       const MDString *Name = dyn_cast<MDString>(Tuple->getOperand(0));
143       const MDString *Contents = dyn_cast<MDString>(Tuple->getOperand(1));
144       if (!Name || !Contents)
145         continue;
146 
147       OutStreamer->PushSection();
148       std::string SectionName = (".custom_section." + Name->getString()).str();
149       MCSectionWasm *mySection =
150           OutContext.getWasmSection(SectionName, SectionKind::getMetadata());
151       OutStreamer->SwitchSection(mySection);
152       OutStreamer->EmitBytes(Contents->getString());
153       OutStreamer->PopSection();
154     }
155   }
156 }
157 
EmitConstantPool()158 void WebAssemblyAsmPrinter::EmitConstantPool() {
159   assert(MF->getConstantPool()->getConstants().empty() &&
160          "WebAssembly disables constant pools");
161 }
162 
EmitJumpTableInfo()163 void WebAssemblyAsmPrinter::EmitJumpTableInfo() {
164   // Nothing to do; jump tables are incorporated into the instruction stream.
165 }
166 
EmitFunctionBodyStart()167 void WebAssemblyAsmPrinter::EmitFunctionBodyStart() {
168   const Function &F = MF->getFunction();
169   SmallVector<MVT, 1> ResultVTs;
170   SmallVector<MVT, 4> ParamVTs;
171   ComputeSignatureVTs(F.getFunctionType(), F, TM, ParamVTs, ResultVTs);
172   auto Signature = SignatureFromMVTs(ResultVTs, ParamVTs);
173   auto *WasmSym = cast<MCSymbolWasm>(CurrentFnSym);
174   WasmSym->setSignature(Signature.get());
175   addSignature(std::move(Signature));
176   WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
177 
178   // FIXME: clean up how params and results are emitted (use signatures)
179   getTargetStreamer()->emitFunctionType(WasmSym);
180 
181   // Emit the function index.
182   if (MDNode *Idx = F.getMetadata("wasm.index")) {
183     assert(Idx->getNumOperands() == 1);
184 
185     getTargetStreamer()->emitIndIdx(AsmPrinter::lowerConstant(
186         cast<ConstantAsMetadata>(Idx->getOperand(0))->getValue()));
187   }
188 
189   SmallVector<wasm::ValType, 16> Locals;
190   ValTypesFromMVTs(MFI->getLocals(), Locals);
191   getTargetStreamer()->emitLocal(Locals);
192 
193   AsmPrinter::EmitFunctionBodyStart();
194 }
195 
EmitInstruction(const MachineInstr * MI)196 void WebAssemblyAsmPrinter::EmitInstruction(const MachineInstr *MI) {
197   LLVM_DEBUG(dbgs() << "EmitInstruction: " << *MI << '\n');
198 
199   switch (MI->getOpcode()) {
200   case WebAssembly::ARGUMENT_i32:
201   case WebAssembly::ARGUMENT_i32_S:
202   case WebAssembly::ARGUMENT_i64:
203   case WebAssembly::ARGUMENT_i64_S:
204   case WebAssembly::ARGUMENT_f32:
205   case WebAssembly::ARGUMENT_f32_S:
206   case WebAssembly::ARGUMENT_f64:
207   case WebAssembly::ARGUMENT_f64_S:
208   case WebAssembly::ARGUMENT_v16i8:
209   case WebAssembly::ARGUMENT_v16i8_S:
210   case WebAssembly::ARGUMENT_v8i16:
211   case WebAssembly::ARGUMENT_v8i16_S:
212   case WebAssembly::ARGUMENT_v4i32:
213   case WebAssembly::ARGUMENT_v4i32_S:
214   case WebAssembly::ARGUMENT_v2i64:
215   case WebAssembly::ARGUMENT_v2i64_S:
216   case WebAssembly::ARGUMENT_v4f32:
217   case WebAssembly::ARGUMENT_v4f32_S:
218   case WebAssembly::ARGUMENT_v2f64:
219   case WebAssembly::ARGUMENT_v2f64_S:
220     // These represent values which are live into the function entry, so there's
221     // no instruction to emit.
222     break;
223   case WebAssembly::FALLTHROUGH_RETURN_I32:
224   case WebAssembly::FALLTHROUGH_RETURN_I32_S:
225   case WebAssembly::FALLTHROUGH_RETURN_I64:
226   case WebAssembly::FALLTHROUGH_RETURN_I64_S:
227   case WebAssembly::FALLTHROUGH_RETURN_F32:
228   case WebAssembly::FALLTHROUGH_RETURN_F32_S:
229   case WebAssembly::FALLTHROUGH_RETURN_F64:
230   case WebAssembly::FALLTHROUGH_RETURN_F64_S:
231   case WebAssembly::FALLTHROUGH_RETURN_v16i8:
232   case WebAssembly::FALLTHROUGH_RETURN_v16i8_S:
233   case WebAssembly::FALLTHROUGH_RETURN_v8i16:
234   case WebAssembly::FALLTHROUGH_RETURN_v8i16_S:
235   case WebAssembly::FALLTHROUGH_RETURN_v4i32:
236   case WebAssembly::FALLTHROUGH_RETURN_v4i32_S:
237   case WebAssembly::FALLTHROUGH_RETURN_v2i64:
238   case WebAssembly::FALLTHROUGH_RETURN_v2i64_S:
239   case WebAssembly::FALLTHROUGH_RETURN_v4f32:
240   case WebAssembly::FALLTHROUGH_RETURN_v4f32_S:
241   case WebAssembly::FALLTHROUGH_RETURN_v2f64:
242   case WebAssembly::FALLTHROUGH_RETURN_v2f64_S: {
243     // These instructions represent the implicit return at the end of a
244     // function body. Always pops one value off the stack.
245     if (isVerbose()) {
246       OutStreamer->AddComment("fallthrough-return-value");
247       OutStreamer->AddBlankLine();
248     }
249     break;
250   }
251   case WebAssembly::FALLTHROUGH_RETURN_VOID:
252   case WebAssembly::FALLTHROUGH_RETURN_VOID_S:
253     // This instruction represents the implicit return at the end of a
254     // function body with no return value.
255     if (isVerbose()) {
256       OutStreamer->AddComment("fallthrough-return-void");
257       OutStreamer->AddBlankLine();
258     }
259     break;
260   default: {
261     WebAssemblyMCInstLower MCInstLowering(OutContext, *this);
262     MCInst TmpInst;
263     MCInstLowering.Lower(MI, TmpInst);
264     EmitToStreamer(*OutStreamer, TmpInst);
265     break;
266   }
267   }
268 }
269 
lowerConstant(const Constant * CV)270 const MCExpr *WebAssemblyAsmPrinter::lowerConstant(const Constant *CV) {
271   if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
272     if (GV->getValueType()->isFunctionTy()) {
273       return MCSymbolRefExpr::create(
274           getSymbol(GV), MCSymbolRefExpr::VK_WebAssembly_FUNCTION, OutContext);
275     }
276   return AsmPrinter::lowerConstant(CV);
277 }
278 
PrintAsmOperand(const MachineInstr * MI,unsigned OpNo,unsigned AsmVariant,const char * ExtraCode,raw_ostream & OS)279 bool WebAssemblyAsmPrinter::PrintAsmOperand(const MachineInstr *MI,
280                                             unsigned OpNo, unsigned AsmVariant,
281                                             const char *ExtraCode,
282                                             raw_ostream &OS) {
283   if (AsmVariant != 0)
284     report_fatal_error("There are no defined alternate asm variants");
285 
286   // First try the generic code, which knows about modifiers like 'c' and 'n'.
287   if (!AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, OS))
288     return false;
289 
290   if (!ExtraCode) {
291     const MachineOperand &MO = MI->getOperand(OpNo);
292     switch (MO.getType()) {
293     case MachineOperand::MO_Immediate:
294       OS << MO.getImm();
295       return false;
296     case MachineOperand::MO_Register:
297       // FIXME: only opcode that still contains registers, as required by
298       // MachineInstr::getDebugVariable().
299       assert(MI->getOpcode() == WebAssembly::INLINEASM);
300       OS << regToString(MO);
301       return false;
302     case MachineOperand::MO_GlobalAddress:
303       getSymbol(MO.getGlobal())->print(OS, MAI);
304       printOffset(MO.getOffset(), OS);
305       return false;
306     case MachineOperand::MO_ExternalSymbol:
307       GetExternalSymbolSymbol(MO.getSymbolName())->print(OS, MAI);
308       printOffset(MO.getOffset(), OS);
309       return false;
310     case MachineOperand::MO_MachineBasicBlock:
311       MO.getMBB()->getSymbol()->print(OS, MAI);
312       return false;
313     default:
314       break;
315     }
316   }
317 
318   return true;
319 }
320 
PrintAsmMemoryOperand(const MachineInstr * MI,unsigned OpNo,unsigned AsmVariant,const char * ExtraCode,raw_ostream & OS)321 bool WebAssemblyAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
322                                                   unsigned OpNo,
323                                                   unsigned AsmVariant,
324                                                   const char *ExtraCode,
325                                                   raw_ostream &OS) {
326   if (AsmVariant != 0)
327     report_fatal_error("There are no defined alternate asm variants");
328 
329   // The current approach to inline asm is that "r" constraints are expressed
330   // as local indices, rather than values on the operand stack. This simplifies
331   // using "r" as it eliminates the need to push and pop the values in a
332   // particular order, however it also makes it impossible to have an "m"
333   // constraint. So we don't support it.
334 
335   return AsmPrinter::PrintAsmMemoryOperand(MI, OpNo, AsmVariant, ExtraCode, OS);
336 }
337 
338 // Force static initialization.
LLVMInitializeWebAssemblyAsmPrinter()339 extern "C" void LLVMInitializeWebAssemblyAsmPrinter() {
340   RegisterAsmPrinter<WebAssemblyAsmPrinter> X(getTheWebAssemblyTarget32());
341   RegisterAsmPrinter<WebAssemblyAsmPrinter> Y(getTheWebAssemblyTarget64());
342 }
343