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