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