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 "MCTargetDesc/WebAssemblyMCTargetDesc.h"
18 #include "MCTargetDesc/WebAssemblyTargetStreamer.h"
19 #include "TargetInfo/WebAssemblyTargetInfo.h"
20 #include "Utils/WebAssemblyTypeUtilities.h"
21 #include "Utils/WebAssemblyUtilities.h"
22 #include "WebAssembly.h"
23 #include "WebAssemblyMCInstLower.h"
24 #include "WebAssemblyMachineFunctionInfo.h"
25 #include "WebAssemblyRegisterInfo.h"
26 #include "WebAssemblyRuntimeLibcallSignatures.h"
27 #include "WebAssemblyTargetMachine.h"
28 #include "llvm/ADT/SmallSet.h"
29 #include "llvm/ADT/StringExtras.h"
30 #include "llvm/BinaryFormat/Wasm.h"
31 #include "llvm/CodeGen/Analysis.h"
32 #include "llvm/CodeGen/AsmPrinter.h"
33 #include "llvm/CodeGen/MachineConstantPool.h"
34 #include "llvm/CodeGen/MachineInstr.h"
35 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
36 #include "llvm/IR/DataLayout.h"
37 #include "llvm/IR/DebugInfoMetadata.h"
38 #include "llvm/IR/GlobalVariable.h"
39 #include "llvm/IR/Metadata.h"
40 #include "llvm/MC/MCContext.h"
41 #include "llvm/MC/MCSectionWasm.h"
42 #include "llvm/MC/MCStreamer.h"
43 #include "llvm/MC/MCSymbol.h"
44 #include "llvm/MC/MCSymbolWasm.h"
45 #include "llvm/MC/TargetRegistry.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/raw_ostream.h"
48 
49 using namespace llvm;
50 
51 #define DEBUG_TYPE "asm-printer"
52 
53 extern cl::opt<bool> WasmKeepRegisters;
54 
55 //===----------------------------------------------------------------------===//
56 // Helpers.
57 //===----------------------------------------------------------------------===//
58 
59 MVT WebAssemblyAsmPrinter::getRegType(unsigned RegNo) const {
60   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
61   const TargetRegisterClass *TRC = MRI->getRegClass(RegNo);
62   for (MVT T : {MVT::i32, MVT::i64, MVT::f32, MVT::f64, MVT::v16i8, MVT::v8i16,
63                 MVT::v4i32, MVT::v2i64, MVT::v4f32, MVT::v2f64})
64     if (TRI->isTypeLegalForClass(*TRC, T))
65       return T;
66   LLVM_DEBUG(errs() << "Unknown type for register number: " << RegNo);
67   llvm_unreachable("Unknown register type");
68   return MVT::Other;
69 }
70 
71 std::string WebAssemblyAsmPrinter::regToString(const MachineOperand &MO) {
72   Register RegNo = MO.getReg();
73   assert(Register::isVirtualRegister(RegNo) &&
74          "Unlowered physical register encountered during assembly printing");
75   assert(!MFI->isVRegStackified(RegNo));
76   unsigned WAReg = MFI->getWAReg(RegNo);
77   assert(WAReg != WebAssemblyFunctionInfo::UnusedReg);
78   return '$' + utostr(WAReg);
79 }
80 
81 WebAssemblyTargetStreamer *WebAssemblyAsmPrinter::getTargetStreamer() {
82   MCTargetStreamer *TS = OutStreamer->getTargetStreamer();
83   return static_cast<WebAssemblyTargetStreamer *>(TS);
84 }
85 
86 // Emscripten exception handling helpers
87 //
88 // This converts invoke names generated by LowerEmscriptenEHSjLj to real names
89 // that are expected by JavaScript glue code. The invoke names generated by
90 // Emscripten JS glue code are based on their argument and return types; for
91 // example, for a function that takes an i32 and returns nothing, it is
92 // 'invoke_vi'. But the format of invoke generated by LowerEmscriptenEHSjLj pass
93 // contains a mangled string generated from their IR types, for example,
94 // "__invoke_void_%struct.mystruct*_int", because final wasm types are not
95 // available in the IR pass. So we convert those names to the form that
96 // Emscripten JS code expects.
97 //
98 // Refer to LowerEmscriptenEHSjLj pass for more details.
99 
100 // Returns true if the given function name is an invoke name generated by
101 // LowerEmscriptenEHSjLj pass.
102 static bool isEmscriptenInvokeName(StringRef Name) {
103   if (Name.front() == '"' && Name.back() == '"')
104     Name = Name.substr(1, Name.size() - 2);
105   return Name.startswith("__invoke_");
106 }
107 
108 // Returns a character that represents the given wasm value type in invoke
109 // signatures.
110 static char getInvokeSig(wasm::ValType VT) {
111   switch (VT) {
112   case wasm::ValType::I32:
113     return 'i';
114   case wasm::ValType::I64:
115     return 'j';
116   case wasm::ValType::F32:
117     return 'f';
118   case wasm::ValType::F64:
119     return 'd';
120   case wasm::ValType::V128:
121     return 'V';
122   case wasm::ValType::FUNCREF:
123     return 'F';
124   case wasm::ValType::EXTERNREF:
125     return 'X';
126   }
127   llvm_unreachable("Unhandled wasm::ValType enum");
128 }
129 
130 // Given the wasm signature, generate the invoke name in the format JS glue code
131 // expects.
132 static std::string getEmscriptenInvokeSymbolName(wasm::WasmSignature *Sig) {
133   assert(Sig->Returns.size() <= 1);
134   std::string Ret = "invoke_";
135   if (!Sig->Returns.empty())
136     for (auto VT : Sig->Returns)
137       Ret += getInvokeSig(VT);
138   else
139     Ret += 'v';
140   // Invokes' first argument is a pointer to the original function, so skip it
141   for (unsigned I = 1, E = Sig->Params.size(); I < E; I++)
142     Ret += getInvokeSig(Sig->Params[I]);
143   return Ret;
144 }
145 
146 //===----------------------------------------------------------------------===//
147 // WebAssemblyAsmPrinter Implementation.
148 //===----------------------------------------------------------------------===//
149 
150 MCSymbolWasm *WebAssemblyAsmPrinter::getMCSymbolForFunction(
151     const Function *F, bool EnableEmEH, wasm::WasmSignature *Sig,
152     bool &InvokeDetected) {
153   MCSymbolWasm *WasmSym = nullptr;
154   if (EnableEmEH && isEmscriptenInvokeName(F->getName())) {
155     assert(Sig);
156     InvokeDetected = true;
157     if (Sig->Returns.size() > 1) {
158       std::string Msg =
159           "Emscripten EH/SjLj does not support multivalue returns: " +
160           std::string(F->getName()) + ": " +
161           WebAssembly::signatureToString(Sig);
162       report_fatal_error(Twine(Msg));
163     }
164     WasmSym = cast<MCSymbolWasm>(
165         GetExternalSymbolSymbol(getEmscriptenInvokeSymbolName(Sig)));
166   } else {
167     WasmSym = cast<MCSymbolWasm>(getSymbol(F));
168   }
169   return WasmSym;
170 }
171 
172 void WebAssemblyAsmPrinter::emitGlobalVariable(const GlobalVariable *GV) {
173   if (!WebAssembly::isWasmVarAddressSpace(GV->getAddressSpace())) {
174     AsmPrinter::emitGlobalVariable(GV);
175     return;
176   }
177 
178   assert(!GV->isThreadLocal());
179 
180   MCSymbolWasm *Sym = cast<MCSymbolWasm>(getSymbol(GV));
181 
182   if (!Sym->getType()) {
183     const WebAssemblyTargetLowering &TLI = *Subtarget->getTargetLowering();
184     SmallVector<EVT, 1> VTs;
185     ComputeValueVTs(TLI, GV->getParent()->getDataLayout(), GV->getValueType(),
186                     VTs);
187     if (VTs.size() != 1 ||
188         TLI.getNumRegisters(GV->getParent()->getContext(), VTs[0]) != 1)
189       report_fatal_error("Aggregate globals not yet implemented");
190     MVT VT = TLI.getRegisterType(GV->getParent()->getContext(), VTs[0]);
191     bool Mutable = true;
192     wasm::ValType Type = WebAssembly::toValType(VT);
193     Sym->setType(wasm::WASM_SYMBOL_TYPE_GLOBAL);
194     Sym->setGlobalType(wasm::WasmGlobalType{uint8_t(Type), Mutable});
195   }
196 
197   // If the GlobalVariable refers to a table, we handle it here instead of
198   // in emitExternalDecls
199   if (Sym->isTable()) {
200     getTargetStreamer()->emitTableType(Sym);
201     return;
202   }
203 
204   emitVisibility(Sym, GV->getVisibility(), !GV->isDeclaration());
205   if (GV->hasInitializer()) {
206     assert(getSymbolPreferLocal(*GV) == Sym);
207     emitLinkage(GV, Sym);
208     getTargetStreamer()->emitGlobalType(Sym);
209     OutStreamer->emitLabel(Sym);
210     // TODO: Actually emit the initializer value.  Otherwise the global has the
211     // default value for its type (0, ref.null, etc).
212     OutStreamer->AddBlankLine();
213   }
214 }
215 
216 MCSymbol *WebAssemblyAsmPrinter::getOrCreateWasmSymbol(StringRef Name) {
217   auto *WasmSym = cast<MCSymbolWasm>(GetExternalSymbolSymbol(Name));
218 
219   // May be called multiple times, so early out.
220   if (WasmSym->getType().hasValue())
221     return WasmSym;
222 
223   const WebAssemblySubtarget &Subtarget = getSubtarget();
224 
225   // Except for certain known symbols, all symbols used by CodeGen are
226   // functions. It's OK to hardcode knowledge of specific symbols here; this
227   // method is precisely there for fetching the signatures of known
228   // Clang-provided symbols.
229   if (Name == "__stack_pointer" || Name == "__tls_base" ||
230       Name == "__memory_base" || Name == "__table_base" ||
231       Name == "__tls_size" || Name == "__tls_align") {
232     bool Mutable =
233         Name == "__stack_pointer" || Name == "__tls_base";
234     WasmSym->setType(wasm::WASM_SYMBOL_TYPE_GLOBAL);
235     WasmSym->setGlobalType(wasm::WasmGlobalType{
236         uint8_t(Subtarget.hasAddr64() ? wasm::WASM_TYPE_I64
237                                       : wasm::WASM_TYPE_I32),
238         Mutable});
239     return WasmSym;
240   }
241 
242   if (Name.startswith("GCC_except_table")) {
243     WasmSym->setType(wasm::WASM_SYMBOL_TYPE_DATA);
244     return WasmSym;
245   }
246 
247   SmallVector<wasm::ValType, 4> Returns;
248   SmallVector<wasm::ValType, 4> Params;
249   if (Name == "__cpp_exception" || Name == "__c_longjmp") {
250     WasmSym->setType(wasm::WASM_SYMBOL_TYPE_TAG);
251     // In static linking we define tag symbols in WasmException::endModule().
252     // But we may have multiple objects to be linked together, each of which
253     // defines the tag symbols. To resolve them, we declare them as weak. In
254     // dynamic linking we make tag symbols undefined in the backend, define it
255     // in JS, and feed them to each importing module.
256     if (!isPositionIndependent())
257       WasmSym->setWeak(true);
258     WasmSym->setExternal(true);
259 
260     // Currently both C++ exceptions and C longjmps have a single pointer type
261     // param. For C++ exceptions it is a pointer to an exception object, and for
262     // C longjmps it is pointer to a struct that contains a setjmp buffer and a
263     // longjmp return value. We may consider using multiple value parameters for
264     // longjmps later when multivalue support is ready.
265     wasm::ValType AddrType =
266         Subtarget.hasAddr64() ? wasm::ValType::I64 : wasm::ValType::I32;
267     Params.push_back(AddrType);
268   } else { // Function symbols
269     WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
270     getLibcallSignature(Subtarget, Name, Returns, Params);
271   }
272   auto Signature = std::make_unique<wasm::WasmSignature>(std::move(Returns),
273                                                          std::move(Params));
274   WasmSym->setSignature(Signature.get());
275   addSignature(std::move(Signature));
276 
277   return WasmSym;
278 }
279 
280 void WebAssemblyAsmPrinter::emitExternalDecls(const Module &M) {
281   if (signaturesEmitted)
282     return;
283   signaturesEmitted = true;
284 
285   // Normally symbols for globals get discovered as the MI gets lowered,
286   // but we need to know about them ahead of time.
287   MachineModuleInfoWasm &MMIW = MMI->getObjFileInfo<MachineModuleInfoWasm>();
288   for (const auto &Name : MMIW.MachineSymbolsUsed) {
289     getOrCreateWasmSymbol(Name.getKey());
290   }
291 
292   for (auto &It : OutContext.getSymbols()) {
293     // Emit .globaltype, .tagtype, or .tabletype declarations.
294     auto Sym = cast<MCSymbolWasm>(It.getValue());
295     if (Sym->getType() == wasm::WASM_SYMBOL_TYPE_GLOBAL) {
296       // .globaltype already handled by emitGlobalVariable for defined
297       // variables; here we make sure the types of external wasm globals get
298       // written to the file.
299       if (Sym->isUndefined())
300         getTargetStreamer()->emitGlobalType(Sym);
301     } else if (Sym->getType() == wasm::WASM_SYMBOL_TYPE_TAG)
302       getTargetStreamer()->emitTagType(Sym);
303     else if (Sym->getType() == wasm::WASM_SYMBOL_TYPE_TABLE)
304       getTargetStreamer()->emitTableType(Sym);
305   }
306 
307   DenseSet<MCSymbol *> InvokeSymbols;
308   for (const auto &F : M) {
309     if (F.isIntrinsic())
310       continue;
311 
312     // Emit function type info for all undefined functions
313     if (F.isDeclarationForLinker()) {
314       SmallVector<MVT, 4> Results;
315       SmallVector<MVT, 4> Params;
316       computeSignatureVTs(F.getFunctionType(), &F, F, TM, Params, Results);
317       // At this point these MCSymbols may or may not have been created already
318       // and thus also contain a signature, but we need to get the signature
319       // anyway here in case it is an invoke that has not yet been created. We
320       // will discard it later if it turns out not to be necessary.
321       auto Signature = signatureFromMVTs(Results, Params);
322       bool InvokeDetected = false;
323       auto *Sym = getMCSymbolForFunction(
324           &F, WebAssembly::WasmEnableEmEH || WebAssembly::WasmEnableEmSjLj,
325           Signature.get(), InvokeDetected);
326 
327       // Multiple functions can be mapped to the same invoke symbol. For
328       // example, two IR functions '__invoke_void_i8*' and '__invoke_void_i32'
329       // are both mapped to '__invoke_vi'. We keep them in a set once we emit an
330       // Emscripten EH symbol so we don't emit the same symbol twice.
331       if (InvokeDetected && !InvokeSymbols.insert(Sym).second)
332         continue;
333 
334       Sym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
335       if (!Sym->getSignature()) {
336         Sym->setSignature(Signature.get());
337         addSignature(std::move(Signature));
338       } else {
339         // This symbol has already been created and had a signature. Discard it.
340         Signature.reset();
341       }
342 
343       getTargetStreamer()->emitFunctionType(Sym);
344 
345       if (F.hasFnAttribute("wasm-import-module")) {
346         StringRef Name =
347             F.getFnAttribute("wasm-import-module").getValueAsString();
348         Sym->setImportModule(storeName(Name));
349         getTargetStreamer()->emitImportModule(Sym, Name);
350       }
351       if (F.hasFnAttribute("wasm-import-name")) {
352         // If this is a converted Emscripten EH/SjLj symbol, we shouldn't use
353         // the original function name but the converted symbol name.
354         StringRef Name =
355             InvokeDetected
356                 ? Sym->getName()
357                 : F.getFnAttribute("wasm-import-name").getValueAsString();
358         Sym->setImportName(storeName(Name));
359         getTargetStreamer()->emitImportName(Sym, Name);
360       }
361     }
362 
363     if (F.hasFnAttribute("wasm-export-name")) {
364       auto *Sym = cast<MCSymbolWasm>(getSymbol(&F));
365       StringRef Name = F.getFnAttribute("wasm-export-name").getValueAsString();
366       Sym->setExportName(storeName(Name));
367       getTargetStreamer()->emitExportName(Sym, Name);
368     }
369   }
370 }
371 
372 void WebAssemblyAsmPrinter::emitEndOfAsmFile(Module &M) {
373   emitExternalDecls(M);
374 
375   // When a function's address is taken, a TABLE_INDEX relocation is emitted
376   // against the function symbol at the use site.  However the relocation
377   // doesn't explicitly refer to the table.  In the future we may want to
378   // define a new kind of reloc against both the function and the table, so
379   // that the linker can see that the function symbol keeps the table alive,
380   // but for now manually mark the table as live.
381   for (const auto &F : M) {
382     if (!F.isIntrinsic() && F.hasAddressTaken()) {
383       MCSymbolWasm *FunctionTable =
384           WebAssembly::getOrCreateFunctionTableSymbol(OutContext, Subtarget);
385       OutStreamer->emitSymbolAttribute(FunctionTable, MCSA_NoDeadStrip);
386       break;
387     }
388   }
389 
390   for (const auto &G : M.globals()) {
391     if (!G.hasInitializer() && G.hasExternalLinkage() &&
392         !WebAssembly::isWasmVarAddressSpace(G.getAddressSpace()) &&
393         G.getValueType()->isSized()) {
394       uint16_t Size = M.getDataLayout().getTypeAllocSize(G.getValueType());
395       OutStreamer->emitELFSize(getSymbol(&G),
396                                MCConstantExpr::create(Size, OutContext));
397     }
398   }
399 
400   if (const NamedMDNode *Named = M.getNamedMetadata("wasm.custom_sections")) {
401     for (const Metadata *MD : Named->operands()) {
402       const auto *Tuple = dyn_cast<MDTuple>(MD);
403       if (!Tuple || Tuple->getNumOperands() != 2)
404         continue;
405       const MDString *Name = dyn_cast<MDString>(Tuple->getOperand(0));
406       const MDString *Contents = dyn_cast<MDString>(Tuple->getOperand(1));
407       if (!Name || !Contents)
408         continue;
409 
410       OutStreamer->PushSection();
411       std::string SectionName = (".custom_section." + Name->getString()).str();
412       MCSectionWasm *MySection =
413           OutContext.getWasmSection(SectionName, SectionKind::getMetadata());
414       OutStreamer->SwitchSection(MySection);
415       OutStreamer->emitBytes(Contents->getString());
416       OutStreamer->PopSection();
417     }
418   }
419 
420   EmitProducerInfo(M);
421   EmitTargetFeatures(M);
422 }
423 
424 void WebAssemblyAsmPrinter::EmitProducerInfo(Module &M) {
425   llvm::SmallVector<std::pair<std::string, std::string>, 4> Languages;
426   if (const NamedMDNode *Debug = M.getNamedMetadata("llvm.dbg.cu")) {
427     llvm::SmallSet<StringRef, 4> SeenLanguages;
428     for (size_t I = 0, E = Debug->getNumOperands(); I < E; ++I) {
429       const auto *CU = cast<DICompileUnit>(Debug->getOperand(I));
430       StringRef Language = dwarf::LanguageString(CU->getSourceLanguage());
431       Language.consume_front("DW_LANG_");
432       if (SeenLanguages.insert(Language).second)
433         Languages.emplace_back(Language.str(), "");
434     }
435   }
436 
437   llvm::SmallVector<std::pair<std::string, std::string>, 4> Tools;
438   if (const NamedMDNode *Ident = M.getNamedMetadata("llvm.ident")) {
439     llvm::SmallSet<StringRef, 4> SeenTools;
440     for (size_t I = 0, E = Ident->getNumOperands(); I < E; ++I) {
441       const auto *S = cast<MDString>(Ident->getOperand(I)->getOperand(0));
442       std::pair<StringRef, StringRef> Field = S->getString().split("version");
443       StringRef Name = Field.first.trim();
444       StringRef Version = Field.second.trim();
445       if (SeenTools.insert(Name).second)
446         Tools.emplace_back(Name.str(), Version.str());
447     }
448   }
449 
450   int FieldCount = int(!Languages.empty()) + int(!Tools.empty());
451   if (FieldCount != 0) {
452     MCSectionWasm *Producers = OutContext.getWasmSection(
453         ".custom_section.producers", SectionKind::getMetadata());
454     OutStreamer->PushSection();
455     OutStreamer->SwitchSection(Producers);
456     OutStreamer->emitULEB128IntValue(FieldCount);
457     for (auto &Producers : {std::make_pair("language", &Languages),
458             std::make_pair("processed-by", &Tools)}) {
459       if (Producers.second->empty())
460         continue;
461       OutStreamer->emitULEB128IntValue(strlen(Producers.first));
462       OutStreamer->emitBytes(Producers.first);
463       OutStreamer->emitULEB128IntValue(Producers.second->size());
464       for (auto &Producer : *Producers.second) {
465         OutStreamer->emitULEB128IntValue(Producer.first.size());
466         OutStreamer->emitBytes(Producer.first);
467         OutStreamer->emitULEB128IntValue(Producer.second.size());
468         OutStreamer->emitBytes(Producer.second);
469       }
470     }
471     OutStreamer->PopSection();
472   }
473 }
474 
475 void WebAssemblyAsmPrinter::EmitTargetFeatures(Module &M) {
476   struct FeatureEntry {
477     uint8_t Prefix;
478     std::string Name;
479   };
480 
481   // Read target features and linkage policies from module metadata
482   SmallVector<FeatureEntry, 4> EmittedFeatures;
483   auto EmitFeature = [&](std::string Feature) {
484     std::string MDKey = (StringRef("wasm-feature-") + Feature).str();
485     Metadata *Policy = M.getModuleFlag(MDKey);
486     if (Policy == nullptr)
487       return;
488 
489     FeatureEntry Entry;
490     Entry.Prefix = 0;
491     Entry.Name = Feature;
492 
493     if (auto *MD = cast<ConstantAsMetadata>(Policy))
494       if (auto *I = cast<ConstantInt>(MD->getValue()))
495         Entry.Prefix = I->getZExtValue();
496 
497     // Silently ignore invalid metadata
498     if (Entry.Prefix != wasm::WASM_FEATURE_PREFIX_USED &&
499         Entry.Prefix != wasm::WASM_FEATURE_PREFIX_REQUIRED &&
500         Entry.Prefix != wasm::WASM_FEATURE_PREFIX_DISALLOWED)
501       return;
502 
503     EmittedFeatures.push_back(Entry);
504   };
505 
506   for (const SubtargetFeatureKV &KV : WebAssemblyFeatureKV) {
507     EmitFeature(KV.Key);
508   }
509   // This pseudo-feature tells the linker whether shared memory would be safe
510   EmitFeature("shared-mem");
511 
512   // This is an "architecture", not a "feature", but we emit it as such for
513   // the benefit of tools like Binaryen and consistency with other producers.
514   // FIXME: Subtarget is null here, so can't Subtarget->hasAddr64() ?
515   if (M.getDataLayout().getPointerSize() == 8) {
516     // Can't use EmitFeature since "wasm-feature-memory64" is not a module
517     // flag.
518     EmittedFeatures.push_back({wasm::WASM_FEATURE_PREFIX_USED, "memory64"});
519   }
520 
521   if (EmittedFeatures.size() == 0)
522     return;
523 
524   // Emit features and linkage policies into the "target_features" section
525   MCSectionWasm *FeaturesSection = OutContext.getWasmSection(
526       ".custom_section.target_features", SectionKind::getMetadata());
527   OutStreamer->PushSection();
528   OutStreamer->SwitchSection(FeaturesSection);
529 
530   OutStreamer->emitULEB128IntValue(EmittedFeatures.size());
531   for (auto &F : EmittedFeatures) {
532     OutStreamer->emitIntValue(F.Prefix, 1);
533     OutStreamer->emitULEB128IntValue(F.Name.size());
534     OutStreamer->emitBytes(F.Name);
535   }
536 
537   OutStreamer->PopSection();
538 }
539 
540 void WebAssemblyAsmPrinter::emitConstantPool() {
541   assert(MF->getConstantPool()->getConstants().empty() &&
542          "WebAssembly disables constant pools");
543 }
544 
545 void WebAssemblyAsmPrinter::emitJumpTableInfo() {
546   // Nothing to do; jump tables are incorporated into the instruction stream.
547 }
548 
549 void WebAssemblyAsmPrinter::emitLinkage(const GlobalValue *GV, MCSymbol *Sym)
550   const {
551   AsmPrinter::emitLinkage(GV, Sym);
552   // This gets called before the function label and type are emitted.
553   // We use it to emit signatures of external functions.
554   // FIXME casts!
555   const_cast<WebAssemblyAsmPrinter *>(this)
556     ->emitExternalDecls(*MMI->getModule());
557 }
558 
559 
560 void WebAssemblyAsmPrinter::emitFunctionBodyStart() {
561   const Function &F = MF->getFunction();
562   SmallVector<MVT, 1> ResultVTs;
563   SmallVector<MVT, 4> ParamVTs;
564   computeSignatureVTs(F.getFunctionType(), &F, F, TM, ParamVTs, ResultVTs);
565 
566   auto Signature = signatureFromMVTs(ResultVTs, ParamVTs);
567   auto *WasmSym = cast<MCSymbolWasm>(CurrentFnSym);
568   WasmSym->setSignature(Signature.get());
569   addSignature(std::move(Signature));
570   WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
571 
572   getTargetStreamer()->emitFunctionType(WasmSym);
573 
574   // Emit the function index.
575   if (MDNode *Idx = F.getMetadata("wasm.index")) {
576     assert(Idx->getNumOperands() == 1);
577 
578     getTargetStreamer()->emitIndIdx(AsmPrinter::lowerConstant(
579         cast<ConstantAsMetadata>(Idx->getOperand(0))->getValue()));
580   }
581 
582   SmallVector<wasm::ValType, 16> Locals;
583   valTypesFromMVTs(MFI->getLocals(), Locals);
584   getTargetStreamer()->emitLocal(Locals);
585 
586   AsmPrinter::emitFunctionBodyStart();
587 }
588 
589 void WebAssemblyAsmPrinter::emitInstruction(const MachineInstr *MI) {
590   LLVM_DEBUG(dbgs() << "EmitInstruction: " << *MI << '\n');
591 
592   switch (MI->getOpcode()) {
593   case WebAssembly::ARGUMENT_i32:
594   case WebAssembly::ARGUMENT_i32_S:
595   case WebAssembly::ARGUMENT_i64:
596   case WebAssembly::ARGUMENT_i64_S:
597   case WebAssembly::ARGUMENT_f32:
598   case WebAssembly::ARGUMENT_f32_S:
599   case WebAssembly::ARGUMENT_f64:
600   case WebAssembly::ARGUMENT_f64_S:
601   case WebAssembly::ARGUMENT_v16i8:
602   case WebAssembly::ARGUMENT_v16i8_S:
603   case WebAssembly::ARGUMENT_v8i16:
604   case WebAssembly::ARGUMENT_v8i16_S:
605   case WebAssembly::ARGUMENT_v4i32:
606   case WebAssembly::ARGUMENT_v4i32_S:
607   case WebAssembly::ARGUMENT_v2i64:
608   case WebAssembly::ARGUMENT_v2i64_S:
609   case WebAssembly::ARGUMENT_v4f32:
610   case WebAssembly::ARGUMENT_v4f32_S:
611   case WebAssembly::ARGUMENT_v2f64:
612   case WebAssembly::ARGUMENT_v2f64_S:
613     // These represent values which are live into the function entry, so there's
614     // no instruction to emit.
615     break;
616   case WebAssembly::FALLTHROUGH_RETURN: {
617     // These instructions represent the implicit return at the end of a
618     // function body.
619     if (isVerbose()) {
620       OutStreamer->AddComment("fallthrough-return");
621       OutStreamer->AddBlankLine();
622     }
623     break;
624   }
625   case WebAssembly::COMPILER_FENCE:
626     // This is a compiler barrier that prevents instruction reordering during
627     // backend compilation, and should not be emitted.
628     break;
629   default: {
630     WebAssemblyMCInstLower MCInstLowering(OutContext, *this);
631     MCInst TmpInst;
632     MCInstLowering.lower(MI, TmpInst);
633     EmitToStreamer(*OutStreamer, TmpInst);
634     break;
635   }
636   }
637 }
638 
639 bool WebAssemblyAsmPrinter::PrintAsmOperand(const MachineInstr *MI,
640                                             unsigned OpNo,
641                                             const char *ExtraCode,
642                                             raw_ostream &OS) {
643   // First try the generic code, which knows about modifiers like 'c' and 'n'.
644   if (!AsmPrinter::PrintAsmOperand(MI, OpNo, ExtraCode, OS))
645     return false;
646 
647   if (!ExtraCode) {
648     const MachineOperand &MO = MI->getOperand(OpNo);
649     switch (MO.getType()) {
650     case MachineOperand::MO_Immediate:
651       OS << MO.getImm();
652       return false;
653     case MachineOperand::MO_Register:
654       // FIXME: only opcode that still contains registers, as required by
655       // MachineInstr::getDebugVariable().
656       assert(MI->getOpcode() == WebAssembly::INLINEASM);
657       OS << regToString(MO);
658       return false;
659     case MachineOperand::MO_GlobalAddress:
660       PrintSymbolOperand(MO, OS);
661       return false;
662     case MachineOperand::MO_ExternalSymbol:
663       GetExternalSymbolSymbol(MO.getSymbolName())->print(OS, MAI);
664       printOffset(MO.getOffset(), OS);
665       return false;
666     case MachineOperand::MO_MachineBasicBlock:
667       MO.getMBB()->getSymbol()->print(OS, MAI);
668       return false;
669     default:
670       break;
671     }
672   }
673 
674   return true;
675 }
676 
677 bool WebAssemblyAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
678                                                   unsigned OpNo,
679                                                   const char *ExtraCode,
680                                                   raw_ostream &OS) {
681   // The current approach to inline asm is that "r" constraints are expressed
682   // as local indices, rather than values on the operand stack. This simplifies
683   // using "r" as it eliminates the need to push and pop the values in a
684   // particular order, however it also makes it impossible to have an "m"
685   // constraint. So we don't support it.
686 
687   return AsmPrinter::PrintAsmMemoryOperand(MI, OpNo, ExtraCode, OS);
688 }
689 
690 // Force static initialization.
691 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeWebAssemblyAsmPrinter() {
692   RegisterAsmPrinter<WebAssemblyAsmPrinter> X(getTheWebAssemblyTarget32());
693   RegisterAsmPrinter<WebAssemblyAsmPrinter> Y(getTheWebAssemblyTarget64());
694 }
695