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