xref: /freebsd-src/contrib/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyAsmPrinter.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
10b57cec5SDimitry Andric //===-- WebAssemblyAsmPrinter.cpp - WebAssembly LLVM assembly writer ------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric ///
90b57cec5SDimitry Andric /// \file
100b57cec5SDimitry Andric /// This file contains a printer that converts from our internal
110b57cec5SDimitry Andric /// representation of machine-dependent LLVM code to the WebAssembly assembly
120b57cec5SDimitry Andric /// language.
130b57cec5SDimitry Andric ///
140b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
150b57cec5SDimitry Andric 
160b57cec5SDimitry Andric #include "WebAssemblyAsmPrinter.h"
170b57cec5SDimitry Andric #include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
180b57cec5SDimitry Andric #include "MCTargetDesc/WebAssemblyTargetStreamer.h"
190b57cec5SDimitry Andric #include "TargetInfo/WebAssemblyTargetInfo.h"
20fe6060f1SDimitry Andric #include "Utils/WebAssemblyTypeUtilities.h"
210b57cec5SDimitry Andric #include "WebAssembly.h"
220b57cec5SDimitry Andric #include "WebAssemblyMCInstLower.h"
230b57cec5SDimitry Andric #include "WebAssemblyMachineFunctionInfo.h"
240b57cec5SDimitry Andric #include "WebAssemblyRegisterInfo.h"
25fe6060f1SDimitry Andric #include "WebAssemblyRuntimeLibcallSignatures.h"
260b57cec5SDimitry Andric #include "WebAssemblyTargetMachine.h"
275f757f3fSDimitry Andric #include "WebAssemblyUtilities.h"
2806c3fb27SDimitry Andric #include "llvm/ADT/MapVector.h"
290b57cec5SDimitry Andric #include "llvm/ADT/SmallSet.h"
300b57cec5SDimitry Andric #include "llvm/ADT/StringExtras.h"
3106c3fb27SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
320b57cec5SDimitry Andric #include "llvm/BinaryFormat/Wasm.h"
330b57cec5SDimitry Andric #include "llvm/CodeGen/Analysis.h"
340b57cec5SDimitry Andric #include "llvm/CodeGen/AsmPrinter.h"
350b57cec5SDimitry Andric #include "llvm/CodeGen/MachineConstantPool.h"
360b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
370b57cec5SDimitry Andric #include "llvm/CodeGen/MachineModuleInfoImpls.h"
380b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
390b57cec5SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
400b57cec5SDimitry Andric #include "llvm/IR/GlobalVariable.h"
410b57cec5SDimitry Andric #include "llvm/IR/Metadata.h"
42*0fca6ea1SDimitry Andric #include "llvm/IR/Module.h"
430b57cec5SDimitry Andric #include "llvm/MC/MCContext.h"
440b57cec5SDimitry Andric #include "llvm/MC/MCSectionWasm.h"
450b57cec5SDimitry Andric #include "llvm/MC/MCStreamer.h"
460b57cec5SDimitry Andric #include "llvm/MC/MCSymbol.h"
470b57cec5SDimitry Andric #include "llvm/MC/MCSymbolWasm.h"
48349cc55cSDimitry Andric #include "llvm/MC/TargetRegistry.h"
490b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
500b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
510b57cec5SDimitry Andric 
520b57cec5SDimitry Andric using namespace llvm;
530b57cec5SDimitry Andric 
540b57cec5SDimitry Andric #define DEBUG_TYPE "asm-printer"
550b57cec5SDimitry Andric 
560b57cec5SDimitry Andric extern cl::opt<bool> WasmKeepRegisters;
570b57cec5SDimitry Andric 
580b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
590b57cec5SDimitry Andric // Helpers.
600b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
610b57cec5SDimitry Andric 
620b57cec5SDimitry Andric MVT WebAssemblyAsmPrinter::getRegType(unsigned RegNo) const {
630b57cec5SDimitry Andric   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
640b57cec5SDimitry Andric   const TargetRegisterClass *TRC = MRI->getRegClass(RegNo);
650b57cec5SDimitry Andric   for (MVT T : {MVT::i32, MVT::i64, MVT::f32, MVT::f64, MVT::v16i8, MVT::v8i16,
66*0fca6ea1SDimitry Andric                 MVT::v4i32, MVT::v2i64, MVT::v4f32, MVT::v2f64, MVT::v8f16})
670b57cec5SDimitry Andric     if (TRI->isTypeLegalForClass(*TRC, T))
680b57cec5SDimitry Andric       return T;
690b57cec5SDimitry Andric   LLVM_DEBUG(errs() << "Unknown type for register number: " << RegNo);
700b57cec5SDimitry Andric   llvm_unreachable("Unknown register type");
710b57cec5SDimitry Andric   return MVT::Other;
720b57cec5SDimitry Andric }
730b57cec5SDimitry Andric 
740b57cec5SDimitry Andric std::string WebAssemblyAsmPrinter::regToString(const MachineOperand &MO) {
758bcb0991SDimitry Andric   Register RegNo = MO.getReg();
76bdd1243dSDimitry Andric   assert(RegNo.isVirtual() &&
770b57cec5SDimitry Andric          "Unlowered physical register encountered during assembly printing");
780b57cec5SDimitry Andric   assert(!MFI->isVRegStackified(RegNo));
790b57cec5SDimitry Andric   unsigned WAReg = MFI->getWAReg(RegNo);
805f757f3fSDimitry Andric   assert(WAReg != WebAssembly::UnusedReg);
810b57cec5SDimitry Andric   return '$' + utostr(WAReg);
820b57cec5SDimitry Andric }
830b57cec5SDimitry Andric 
840b57cec5SDimitry Andric WebAssemblyTargetStreamer *WebAssemblyAsmPrinter::getTargetStreamer() {
850b57cec5SDimitry Andric   MCTargetStreamer *TS = OutStreamer->getTargetStreamer();
860b57cec5SDimitry Andric   return static_cast<WebAssemblyTargetStreamer *>(TS);
870b57cec5SDimitry Andric }
880b57cec5SDimitry Andric 
89e8d8bef9SDimitry Andric // Emscripten exception handling helpers
90e8d8bef9SDimitry Andric //
91e8d8bef9SDimitry Andric // This converts invoke names generated by LowerEmscriptenEHSjLj to real names
92e8d8bef9SDimitry Andric // that are expected by JavaScript glue code. The invoke names generated by
93e8d8bef9SDimitry Andric // Emscripten JS glue code are based on their argument and return types; for
94e8d8bef9SDimitry Andric // example, for a function that takes an i32 and returns nothing, it is
95e8d8bef9SDimitry Andric // 'invoke_vi'. But the format of invoke generated by LowerEmscriptenEHSjLj pass
96e8d8bef9SDimitry Andric // contains a mangled string generated from their IR types, for example,
97e8d8bef9SDimitry Andric // "__invoke_void_%struct.mystruct*_int", because final wasm types are not
98e8d8bef9SDimitry Andric // available in the IR pass. So we convert those names to the form that
99e8d8bef9SDimitry Andric // Emscripten JS code expects.
100e8d8bef9SDimitry Andric //
101e8d8bef9SDimitry Andric // Refer to LowerEmscriptenEHSjLj pass for more details.
102e8d8bef9SDimitry Andric 
103e8d8bef9SDimitry Andric // Returns true if the given function name is an invoke name generated by
104e8d8bef9SDimitry Andric // LowerEmscriptenEHSjLj pass.
105e8d8bef9SDimitry Andric static bool isEmscriptenInvokeName(StringRef Name) {
106e8d8bef9SDimitry Andric   if (Name.front() == '"' && Name.back() == '"')
107e8d8bef9SDimitry Andric     Name = Name.substr(1, Name.size() - 2);
1085f757f3fSDimitry Andric   return Name.starts_with("__invoke_");
109e8d8bef9SDimitry Andric }
110e8d8bef9SDimitry Andric 
111e8d8bef9SDimitry Andric // Returns a character that represents the given wasm value type in invoke
112e8d8bef9SDimitry Andric // signatures.
113e8d8bef9SDimitry Andric static char getInvokeSig(wasm::ValType VT) {
114e8d8bef9SDimitry Andric   switch (VT) {
115e8d8bef9SDimitry Andric   case wasm::ValType::I32:
116e8d8bef9SDimitry Andric     return 'i';
117e8d8bef9SDimitry Andric   case wasm::ValType::I64:
118e8d8bef9SDimitry Andric     return 'j';
119e8d8bef9SDimitry Andric   case wasm::ValType::F32:
120e8d8bef9SDimitry Andric     return 'f';
121e8d8bef9SDimitry Andric   case wasm::ValType::F64:
122e8d8bef9SDimitry Andric     return 'd';
123e8d8bef9SDimitry Andric   case wasm::ValType::V128:
124e8d8bef9SDimitry Andric     return 'V';
125e8d8bef9SDimitry Andric   case wasm::ValType::FUNCREF:
126e8d8bef9SDimitry Andric     return 'F';
127e8d8bef9SDimitry Andric   case wasm::ValType::EXTERNREF:
128e8d8bef9SDimitry Andric     return 'X';
129*0fca6ea1SDimitry Andric   case wasm::ValType::EXNREF:
130*0fca6ea1SDimitry Andric     return 'E';
131*0fca6ea1SDimitry Andric   default:
132e8d8bef9SDimitry Andric     llvm_unreachable("Unhandled wasm::ValType enum");
133e8d8bef9SDimitry Andric   }
134*0fca6ea1SDimitry Andric }
135e8d8bef9SDimitry Andric 
136e8d8bef9SDimitry Andric // Given the wasm signature, generate the invoke name in the format JS glue code
137e8d8bef9SDimitry Andric // expects.
138e8d8bef9SDimitry Andric static std::string getEmscriptenInvokeSymbolName(wasm::WasmSignature *Sig) {
139e8d8bef9SDimitry Andric   assert(Sig->Returns.size() <= 1);
140e8d8bef9SDimitry Andric   std::string Ret = "invoke_";
141e8d8bef9SDimitry Andric   if (!Sig->Returns.empty())
142e8d8bef9SDimitry Andric     for (auto VT : Sig->Returns)
143e8d8bef9SDimitry Andric       Ret += getInvokeSig(VT);
144e8d8bef9SDimitry Andric   else
145e8d8bef9SDimitry Andric     Ret += 'v';
146e8d8bef9SDimitry Andric   // Invokes' first argument is a pointer to the original function, so skip it
147e8d8bef9SDimitry Andric   for (unsigned I = 1, E = Sig->Params.size(); I < E; I++)
148e8d8bef9SDimitry Andric     Ret += getInvokeSig(Sig->Params[I]);
149e8d8bef9SDimitry Andric   return Ret;
150e8d8bef9SDimitry Andric }
151e8d8bef9SDimitry Andric 
1520b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1530b57cec5SDimitry Andric // WebAssemblyAsmPrinter Implementation.
1540b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1550b57cec5SDimitry Andric 
156e8d8bef9SDimitry Andric MCSymbolWasm *WebAssemblyAsmPrinter::getMCSymbolForFunction(
157e8d8bef9SDimitry Andric     const Function *F, bool EnableEmEH, wasm::WasmSignature *Sig,
158e8d8bef9SDimitry Andric     bool &InvokeDetected) {
159e8d8bef9SDimitry Andric   MCSymbolWasm *WasmSym = nullptr;
160e8d8bef9SDimitry Andric   if (EnableEmEH && isEmscriptenInvokeName(F->getName())) {
161e8d8bef9SDimitry Andric     assert(Sig);
162e8d8bef9SDimitry Andric     InvokeDetected = true;
163e8d8bef9SDimitry Andric     if (Sig->Returns.size() > 1) {
164e8d8bef9SDimitry Andric       std::string Msg =
165e8d8bef9SDimitry Andric           "Emscripten EH/SjLj does not support multivalue returns: " +
166e8d8bef9SDimitry Andric           std::string(F->getName()) + ": " +
167e8d8bef9SDimitry Andric           WebAssembly::signatureToString(Sig);
168349cc55cSDimitry Andric       report_fatal_error(Twine(Msg));
169e8d8bef9SDimitry Andric     }
170e8d8bef9SDimitry Andric     WasmSym = cast<MCSymbolWasm>(
171e8d8bef9SDimitry Andric         GetExternalSymbolSymbol(getEmscriptenInvokeSymbolName(Sig)));
172e8d8bef9SDimitry Andric   } else {
173e8d8bef9SDimitry Andric     WasmSym = cast<MCSymbolWasm>(getSymbol(F));
174e8d8bef9SDimitry Andric   }
175e8d8bef9SDimitry Andric   return WasmSym;
176e8d8bef9SDimitry Andric }
177e8d8bef9SDimitry Andric 
178fe6060f1SDimitry Andric void WebAssemblyAsmPrinter::emitGlobalVariable(const GlobalVariable *GV) {
179fe6060f1SDimitry Andric   if (!WebAssembly::isWasmVarAddressSpace(GV->getAddressSpace())) {
180fe6060f1SDimitry Andric     AsmPrinter::emitGlobalVariable(GV);
181fe6060f1SDimitry Andric     return;
182fe6060f1SDimitry Andric   }
183fe6060f1SDimitry Andric 
184fe6060f1SDimitry Andric   assert(!GV->isThreadLocal());
185fe6060f1SDimitry Andric 
186fe6060f1SDimitry Andric   MCSymbolWasm *Sym = cast<MCSymbolWasm>(getSymbol(GV));
187fe6060f1SDimitry Andric 
188fe6060f1SDimitry Andric   if (!Sym->getType()) {
1891fd87a68SDimitry Andric     SmallVector<MVT, 1> VTs;
1901fd87a68SDimitry Andric     Type *GlobalVT = GV->getValueType();
19181ad6265SDimitry Andric     if (Subtarget) {
19281ad6265SDimitry Andric       // Subtarget is only set when a function is defined, because
19381ad6265SDimitry Andric       // each function can declare a different subtarget. For example,
19481ad6265SDimitry Andric       // on ARM a compilation unit might have a function on ARM and
19581ad6265SDimitry Andric       // another on Thumb. Therefore only if Subtarget is non-null we
19681ad6265SDimitry Andric       // can actually calculate the legal VTs.
19781ad6265SDimitry Andric       const WebAssemblyTargetLowering &TLI = *Subtarget->getTargetLowering();
1981fd87a68SDimitry Andric       computeLegalValueVTs(TLI, GV->getParent()->getContext(),
199*0fca6ea1SDimitry Andric                            GV->getDataLayout(), GlobalVT, VTs);
20081ad6265SDimitry Andric     }
2011fd87a68SDimitry Andric     WebAssembly::wasmSymbolSetType(Sym, GlobalVT, VTs);
202fe6060f1SDimitry Andric   }
203fe6060f1SDimitry Andric 
204fe6060f1SDimitry Andric   emitVisibility(Sym, GV->getVisibility(), !GV->isDeclaration());
20581ad6265SDimitry Andric   emitSymbolType(Sym);
206fe6060f1SDimitry Andric   if (GV->hasInitializer()) {
207fe6060f1SDimitry Andric     assert(getSymbolPreferLocal(*GV) == Sym);
208fe6060f1SDimitry Andric     emitLinkage(GV, Sym);
209fe6060f1SDimitry Andric     OutStreamer->emitLabel(Sym);
210fe6060f1SDimitry Andric     // TODO: Actually emit the initializer value.  Otherwise the global has the
211fe6060f1SDimitry Andric     // default value for its type (0, ref.null, etc).
21281ad6265SDimitry Andric     OutStreamer->addBlankLine();
213fe6060f1SDimitry Andric   }
214fe6060f1SDimitry Andric }
215fe6060f1SDimitry Andric 
216fe6060f1SDimitry Andric MCSymbol *WebAssemblyAsmPrinter::getOrCreateWasmSymbol(StringRef Name) {
217fe6060f1SDimitry Andric   auto *WasmSym = cast<MCSymbolWasm>(GetExternalSymbolSymbol(Name));
218fe6060f1SDimitry Andric 
219fe6060f1SDimitry Andric   // May be called multiple times, so early out.
22081ad6265SDimitry Andric   if (WasmSym->getType())
221fe6060f1SDimitry Andric     return WasmSym;
222fe6060f1SDimitry Andric 
223fe6060f1SDimitry Andric   const WebAssemblySubtarget &Subtarget = getSubtarget();
224fe6060f1SDimitry Andric 
225fe6060f1SDimitry Andric   // Except for certain known symbols, all symbols used by CodeGen are
226fe6060f1SDimitry Andric   // functions. It's OK to hardcode knowledge of specific symbols here; this
227fe6060f1SDimitry Andric   // method is precisely there for fetching the signatures of known
228fe6060f1SDimitry Andric   // Clang-provided symbols.
229fe6060f1SDimitry Andric   if (Name == "__stack_pointer" || Name == "__tls_base" ||
230fe6060f1SDimitry Andric       Name == "__memory_base" || Name == "__table_base" ||
231fe6060f1SDimitry Andric       Name == "__tls_size" || Name == "__tls_align") {
232fe6060f1SDimitry Andric     bool Mutable =
233fe6060f1SDimitry Andric         Name == "__stack_pointer" || Name == "__tls_base";
234fe6060f1SDimitry Andric     WasmSym->setType(wasm::WASM_SYMBOL_TYPE_GLOBAL);
235fe6060f1SDimitry Andric     WasmSym->setGlobalType(wasm::WasmGlobalType{
236fe6060f1SDimitry Andric         uint8_t(Subtarget.hasAddr64() ? wasm::WASM_TYPE_I64
237fe6060f1SDimitry Andric                                       : wasm::WASM_TYPE_I32),
238fe6060f1SDimitry Andric         Mutable});
239fe6060f1SDimitry Andric     return WasmSym;
240fe6060f1SDimitry Andric   }
241fe6060f1SDimitry Andric 
2425f757f3fSDimitry Andric   if (Name.starts_with("GCC_except_table")) {
243349cc55cSDimitry Andric     WasmSym->setType(wasm::WASM_SYMBOL_TYPE_DATA);
244349cc55cSDimitry Andric     return WasmSym;
245349cc55cSDimitry Andric   }
246349cc55cSDimitry Andric 
247fe6060f1SDimitry Andric   SmallVector<wasm::ValType, 4> Returns;
248fe6060f1SDimitry Andric   SmallVector<wasm::ValType, 4> Params;
249349cc55cSDimitry Andric   if (Name == "__cpp_exception" || Name == "__c_longjmp") {
250fe6060f1SDimitry Andric     WasmSym->setType(wasm::WASM_SYMBOL_TYPE_TAG);
251349cc55cSDimitry Andric     // In static linking we define tag symbols in WasmException::endModule().
252349cc55cSDimitry Andric     // But we may have multiple objects to be linked together, each of which
253349cc55cSDimitry Andric     // defines the tag symbols. To resolve them, we declare them as weak. In
254349cc55cSDimitry Andric     // dynamic linking we make tag symbols undefined in the backend, define it
255349cc55cSDimitry Andric     // in JS, and feed them to each importing module.
256349cc55cSDimitry Andric     if (!isPositionIndependent())
257fe6060f1SDimitry Andric       WasmSym->setWeak(true);
258fe6060f1SDimitry Andric     WasmSym->setExternal(true);
259fe6060f1SDimitry Andric 
260349cc55cSDimitry Andric     // Currently both C++ exceptions and C longjmps have a single pointer type
261349cc55cSDimitry Andric     // param. For C++ exceptions it is a pointer to an exception object, and for
262349cc55cSDimitry Andric     // C longjmps it is pointer to a struct that contains a setjmp buffer and a
263349cc55cSDimitry Andric     // longjmp return value. We may consider using multiple value parameters for
264349cc55cSDimitry Andric     // longjmps later when multivalue support is ready.
265349cc55cSDimitry Andric     wasm::ValType AddrType =
266349cc55cSDimitry Andric         Subtarget.hasAddr64() ? wasm::ValType::I64 : wasm::ValType::I32;
267349cc55cSDimitry Andric     Params.push_back(AddrType);
268fe6060f1SDimitry Andric   } else { // Function symbols
269fe6060f1SDimitry Andric     WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
270*0fca6ea1SDimitry Andric     WebAssembly::getLibcallSignature(Subtarget, Name, Returns, Params);
271fe6060f1SDimitry Andric   }
272*0fca6ea1SDimitry Andric   auto Signature = OutContext.createWasmSignature();
273*0fca6ea1SDimitry Andric   Signature->Returns = std::move(Returns);
274*0fca6ea1SDimitry Andric   Signature->Params = std::move(Params);
275*0fca6ea1SDimitry Andric   WasmSym->setSignature(Signature);
276fe6060f1SDimitry Andric 
277fe6060f1SDimitry Andric   return WasmSym;
278fe6060f1SDimitry Andric }
279fe6060f1SDimitry Andric 
28081ad6265SDimitry Andric void WebAssemblyAsmPrinter::emitSymbolType(const MCSymbolWasm *Sym) {
281bdd1243dSDimitry Andric   std::optional<wasm::WasmSymbolType> WasmTy = Sym->getType();
28281ad6265SDimitry Andric   if (!WasmTy)
28381ad6265SDimitry Andric     return;
28481ad6265SDimitry Andric 
28581ad6265SDimitry Andric   switch (*WasmTy) {
28681ad6265SDimitry Andric   case wasm::WASM_SYMBOL_TYPE_GLOBAL:
28781ad6265SDimitry Andric     getTargetStreamer()->emitGlobalType(Sym);
28881ad6265SDimitry Andric     break;
28981ad6265SDimitry Andric   case wasm::WASM_SYMBOL_TYPE_TAG:
29081ad6265SDimitry Andric     getTargetStreamer()->emitTagType(Sym);
29181ad6265SDimitry Andric     break;
29281ad6265SDimitry Andric   case wasm::WASM_SYMBOL_TYPE_TABLE:
29381ad6265SDimitry Andric     getTargetStreamer()->emitTableType(Sym);
29481ad6265SDimitry Andric     break;
29581ad6265SDimitry Andric   default:
29681ad6265SDimitry Andric     break; // We only handle globals, tags and tables here
29781ad6265SDimitry Andric   }
29881ad6265SDimitry Andric }
29981ad6265SDimitry Andric 
30081ad6265SDimitry Andric void WebAssemblyAsmPrinter::emitDecls(const Module &M) {
301fe6060f1SDimitry Andric   if (signaturesEmitted)
302fe6060f1SDimitry Andric     return;
303fe6060f1SDimitry Andric   signaturesEmitted = true;
304fe6060f1SDimitry Andric 
305fe6060f1SDimitry Andric   // Normally symbols for globals get discovered as the MI gets lowered,
30681ad6265SDimitry Andric   // but we need to know about them ahead of time. This will however,
30781ad6265SDimitry Andric   // only find symbols that have been used. Unused symbols from globals will
30881ad6265SDimitry Andric   // not be found here.
309fe6060f1SDimitry Andric   MachineModuleInfoWasm &MMIW = MMI->getObjFileInfo<MachineModuleInfoWasm>();
31006c3fb27SDimitry Andric   for (StringRef Name : MMIW.MachineSymbolsUsed) {
31106c3fb27SDimitry Andric     auto *WasmSym = cast<MCSymbolWasm>(getOrCreateWasmSymbol(Name));
31281ad6265SDimitry Andric     if (WasmSym->isFunction()) {
31381ad6265SDimitry Andric       // TODO(wvo): is there any case where this overlaps with the call to
31481ad6265SDimitry Andric       // emitFunctionType in the loop below?
31581ad6265SDimitry Andric       getTargetStreamer()->emitFunctionType(WasmSym);
31681ad6265SDimitry Andric     }
317fe6060f1SDimitry Andric   }
318fe6060f1SDimitry Andric 
319fe6060f1SDimitry Andric   for (auto &It : OutContext.getSymbols()) {
32081ad6265SDimitry Andric     // Emit .globaltype, .tagtype, or .tabletype declarations for extern
32181ad6265SDimitry Andric     // declarations, i.e. those that have only been declared (but not defined)
32281ad6265SDimitry Andric     // in the current module
323*0fca6ea1SDimitry Andric     auto Sym = cast_or_null<MCSymbolWasm>(It.getValue().Symbol);
324*0fca6ea1SDimitry Andric     if (Sym && !Sym->isDefined())
32581ad6265SDimitry Andric       emitSymbolType(Sym);
3260b57cec5SDimitry Andric   }
3270b57cec5SDimitry Andric 
328e8d8bef9SDimitry Andric   DenseSet<MCSymbol *> InvokeSymbols;
3290b57cec5SDimitry Andric   for (const auto &F : M) {
330480093f4SDimitry Andric     if (F.isIntrinsic())
331480093f4SDimitry Andric       continue;
332480093f4SDimitry Andric 
33381ad6265SDimitry Andric     // Emit function type info for all functions. This will emit duplicate
33481ad6265SDimitry Andric     // information for defined functions (which already have function type
33581ad6265SDimitry Andric     // info emitted alongside their definition), but this is necessary in
33681ad6265SDimitry Andric     // order to enable the single-pass WebAssemblyAsmTypeCheck to succeed.
3370b57cec5SDimitry Andric     SmallVector<MVT, 4> Results;
3380b57cec5SDimitry Andric     SmallVector<MVT, 4> Params;
3395ffd83dbSDimitry Andric     computeSignatureVTs(F.getFunctionType(), &F, F, TM, Params, Results);
340e8d8bef9SDimitry Andric     // At this point these MCSymbols may or may not have been created already
341e8d8bef9SDimitry Andric     // and thus also contain a signature, but we need to get the signature
342e8d8bef9SDimitry Andric     // anyway here in case it is an invoke that has not yet been created. We
343e8d8bef9SDimitry Andric     // will discard it later if it turns out not to be necessary.
344*0fca6ea1SDimitry Andric     auto Signature = signatureFromMVTs(OutContext, Results, Params);
345e8d8bef9SDimitry Andric     bool InvokeDetected = false;
3460eae32dcSDimitry Andric     auto *Sym = getMCSymbolForFunction(
3470eae32dcSDimitry Andric         &F, WebAssembly::WasmEnableEmEH || WebAssembly::WasmEnableEmSjLj,
348*0fca6ea1SDimitry Andric         Signature, InvokeDetected);
349e8d8bef9SDimitry Andric 
350e8d8bef9SDimitry Andric     // Multiple functions can be mapped to the same invoke symbol. For
351e8d8bef9SDimitry Andric     // example, two IR functions '__invoke_void_i8*' and '__invoke_void_i32'
352e8d8bef9SDimitry Andric     // are both mapped to '__invoke_vi'. We keep them in a set once we emit an
353e8d8bef9SDimitry Andric     // Emscripten EH symbol so we don't emit the same symbol twice.
354e8d8bef9SDimitry Andric     if (InvokeDetected && !InvokeSymbols.insert(Sym).second)
355e8d8bef9SDimitry Andric       continue;
356e8d8bef9SDimitry Andric 
3570b57cec5SDimitry Andric     Sym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
3580b57cec5SDimitry Andric     if (!Sym->getSignature()) {
359*0fca6ea1SDimitry Andric       Sym->setSignature(Signature);
3600b57cec5SDimitry Andric     }
361e8d8bef9SDimitry Andric 
3620b57cec5SDimitry Andric     getTargetStreamer()->emitFunctionType(Sym);
3630b57cec5SDimitry Andric 
364e8d8bef9SDimitry Andric     if (F.hasFnAttribute("wasm-import-module")) {
3650b57cec5SDimitry Andric       StringRef Name =
3660b57cec5SDimitry Andric           F.getFnAttribute("wasm-import-module").getValueAsString();
367*0fca6ea1SDimitry Andric       Sym->setImportModule(OutContext.allocateString(Name));
3680b57cec5SDimitry Andric       getTargetStreamer()->emitImportModule(Sym, Name);
3690b57cec5SDimitry Andric     }
370e8d8bef9SDimitry Andric     if (F.hasFnAttribute("wasm-import-name")) {
371e8d8bef9SDimitry Andric       // If this is a converted Emscripten EH/SjLj symbol, we shouldn't use
372e8d8bef9SDimitry Andric       // the original function name but the converted symbol name.
3730b57cec5SDimitry Andric       StringRef Name =
374e8d8bef9SDimitry Andric           InvokeDetected
375e8d8bef9SDimitry Andric               ? Sym->getName()
376e8d8bef9SDimitry Andric               : F.getFnAttribute("wasm-import-name").getValueAsString();
377*0fca6ea1SDimitry Andric       Sym->setImportName(OutContext.allocateString(Name));
3780b57cec5SDimitry Andric       getTargetStreamer()->emitImportName(Sym, Name);
3790b57cec5SDimitry Andric     }
380480093f4SDimitry Andric 
381480093f4SDimitry Andric     if (F.hasFnAttribute("wasm-export-name")) {
382480093f4SDimitry Andric       auto *Sym = cast<MCSymbolWasm>(getSymbol(&F));
383480093f4SDimitry Andric       StringRef Name = F.getFnAttribute("wasm-export-name").getValueAsString();
384*0fca6ea1SDimitry Andric       Sym->setExportName(OutContext.allocateString(Name));
385480093f4SDimitry Andric       getTargetStreamer()->emitExportName(Sym, Name);
386480093f4SDimitry Andric     }
3870b57cec5SDimitry Andric   }
388fe6060f1SDimitry Andric }
389fe6060f1SDimitry Andric 
390fe6060f1SDimitry Andric void WebAssemblyAsmPrinter::emitEndOfAsmFile(Module &M) {
39181ad6265SDimitry Andric   // This is required to emit external declarations (like .functypes) when
39281ad6265SDimitry Andric   // no functions are defined in the compilation unit and therefore,
39381ad6265SDimitry Andric   // emitDecls() is not called until now.
39481ad6265SDimitry Andric   emitDecls(M);
395fe6060f1SDimitry Andric 
396fe6060f1SDimitry Andric   // When a function's address is taken, a TABLE_INDEX relocation is emitted
397fe6060f1SDimitry Andric   // against the function symbol at the use site.  However the relocation
398fe6060f1SDimitry Andric   // doesn't explicitly refer to the table.  In the future we may want to
399fe6060f1SDimitry Andric   // define a new kind of reloc against both the function and the table, so
400fe6060f1SDimitry Andric   // that the linker can see that the function symbol keeps the table alive,
401fe6060f1SDimitry Andric   // but for now manually mark the table as live.
402fe6060f1SDimitry Andric   for (const auto &F : M) {
403fe6060f1SDimitry Andric     if (!F.isIntrinsic() && F.hasAddressTaken()) {
404fe6060f1SDimitry Andric       MCSymbolWasm *FunctionTable =
405fe6060f1SDimitry Andric           WebAssembly::getOrCreateFunctionTableSymbol(OutContext, Subtarget);
406fe6060f1SDimitry Andric       OutStreamer->emitSymbolAttribute(FunctionTable, MCSA_NoDeadStrip);
407fe6060f1SDimitry Andric       break;
408fe6060f1SDimitry Andric     }
409fe6060f1SDimitry Andric   }
4100b57cec5SDimitry Andric 
4110b57cec5SDimitry Andric   for (const auto &G : M.globals()) {
412fe6060f1SDimitry Andric     if (!G.hasInitializer() && G.hasExternalLinkage() &&
413fe6060f1SDimitry Andric         !WebAssembly::isWasmVarAddressSpace(G.getAddressSpace()) &&
414fe6060f1SDimitry Andric         G.getValueType()->isSized()) {
4150b57cec5SDimitry Andric       uint16_t Size = M.getDataLayout().getTypeAllocSize(G.getValueType());
4160b57cec5SDimitry Andric       OutStreamer->emitELFSize(getSymbol(&G),
4170b57cec5SDimitry Andric                                MCConstantExpr::create(Size, OutContext));
4180b57cec5SDimitry Andric     }
4190b57cec5SDimitry Andric   }
4200b57cec5SDimitry Andric 
4210b57cec5SDimitry Andric   if (const NamedMDNode *Named = M.getNamedMetadata("wasm.custom_sections")) {
4220b57cec5SDimitry Andric     for (const Metadata *MD : Named->operands()) {
4230b57cec5SDimitry Andric       const auto *Tuple = dyn_cast<MDTuple>(MD);
4240b57cec5SDimitry Andric       if (!Tuple || Tuple->getNumOperands() != 2)
4250b57cec5SDimitry Andric         continue;
4260b57cec5SDimitry Andric       const MDString *Name = dyn_cast<MDString>(Tuple->getOperand(0));
4270b57cec5SDimitry Andric       const MDString *Contents = dyn_cast<MDString>(Tuple->getOperand(1));
4280b57cec5SDimitry Andric       if (!Name || !Contents)
4290b57cec5SDimitry Andric         continue;
4300b57cec5SDimitry Andric 
43181ad6265SDimitry Andric       OutStreamer->pushSection();
4320b57cec5SDimitry Andric       std::string SectionName = (".custom_section." + Name->getString()).str();
4330b57cec5SDimitry Andric       MCSectionWasm *MySection =
4340b57cec5SDimitry Andric           OutContext.getWasmSection(SectionName, SectionKind::getMetadata());
43581ad6265SDimitry Andric       OutStreamer->switchSection(MySection);
4365ffd83dbSDimitry Andric       OutStreamer->emitBytes(Contents->getString());
43781ad6265SDimitry Andric       OutStreamer->popSection();
4380b57cec5SDimitry Andric     }
4390b57cec5SDimitry Andric   }
4400b57cec5SDimitry Andric 
4410b57cec5SDimitry Andric   EmitProducerInfo(M);
4420b57cec5SDimitry Andric   EmitTargetFeatures(M);
44306c3fb27SDimitry Andric   EmitFunctionAttributes(M);
4440b57cec5SDimitry Andric }
4450b57cec5SDimitry Andric 
4460b57cec5SDimitry Andric void WebAssemblyAsmPrinter::EmitProducerInfo(Module &M) {
4470b57cec5SDimitry Andric   llvm::SmallVector<std::pair<std::string, std::string>, 4> Languages;
4480b57cec5SDimitry Andric   if (const NamedMDNode *Debug = M.getNamedMetadata("llvm.dbg.cu")) {
4490b57cec5SDimitry Andric     llvm::SmallSet<StringRef, 4> SeenLanguages;
4500b57cec5SDimitry Andric     for (size_t I = 0, E = Debug->getNumOperands(); I < E; ++I) {
4510b57cec5SDimitry Andric       const auto *CU = cast<DICompileUnit>(Debug->getOperand(I));
4520b57cec5SDimitry Andric       StringRef Language = dwarf::LanguageString(CU->getSourceLanguage());
4530b57cec5SDimitry Andric       Language.consume_front("DW_LANG_");
4540b57cec5SDimitry Andric       if (SeenLanguages.insert(Language).second)
4550b57cec5SDimitry Andric         Languages.emplace_back(Language.str(), "");
4560b57cec5SDimitry Andric     }
4570b57cec5SDimitry Andric   }
4580b57cec5SDimitry Andric 
4590b57cec5SDimitry Andric   llvm::SmallVector<std::pair<std::string, std::string>, 4> Tools;
4600b57cec5SDimitry Andric   if (const NamedMDNode *Ident = M.getNamedMetadata("llvm.ident")) {
4610b57cec5SDimitry Andric     llvm::SmallSet<StringRef, 4> SeenTools;
4620b57cec5SDimitry Andric     for (size_t I = 0, E = Ident->getNumOperands(); I < E; ++I) {
4630b57cec5SDimitry Andric       const auto *S = cast<MDString>(Ident->getOperand(I)->getOperand(0));
4640b57cec5SDimitry Andric       std::pair<StringRef, StringRef> Field = S->getString().split("version");
4650b57cec5SDimitry Andric       StringRef Name = Field.first.trim();
4660b57cec5SDimitry Andric       StringRef Version = Field.second.trim();
4670b57cec5SDimitry Andric       if (SeenTools.insert(Name).second)
4680b57cec5SDimitry Andric         Tools.emplace_back(Name.str(), Version.str());
4690b57cec5SDimitry Andric     }
4700b57cec5SDimitry Andric   }
4710b57cec5SDimitry Andric 
4720b57cec5SDimitry Andric   int FieldCount = int(!Languages.empty()) + int(!Tools.empty());
4730b57cec5SDimitry Andric   if (FieldCount != 0) {
4740b57cec5SDimitry Andric     MCSectionWasm *Producers = OutContext.getWasmSection(
4750b57cec5SDimitry Andric         ".custom_section.producers", SectionKind::getMetadata());
47681ad6265SDimitry Andric     OutStreamer->pushSection();
47781ad6265SDimitry Andric     OutStreamer->switchSection(Producers);
4785ffd83dbSDimitry Andric     OutStreamer->emitULEB128IntValue(FieldCount);
4790b57cec5SDimitry Andric     for (auto &Producers : {std::make_pair("language", &Languages),
4800b57cec5SDimitry Andric             std::make_pair("processed-by", &Tools)}) {
4810b57cec5SDimitry Andric       if (Producers.second->empty())
4820b57cec5SDimitry Andric         continue;
4835ffd83dbSDimitry Andric       OutStreamer->emitULEB128IntValue(strlen(Producers.first));
4845ffd83dbSDimitry Andric       OutStreamer->emitBytes(Producers.first);
4855ffd83dbSDimitry Andric       OutStreamer->emitULEB128IntValue(Producers.second->size());
4860b57cec5SDimitry Andric       for (auto &Producer : *Producers.second) {
4875ffd83dbSDimitry Andric         OutStreamer->emitULEB128IntValue(Producer.first.size());
4885ffd83dbSDimitry Andric         OutStreamer->emitBytes(Producer.first);
4895ffd83dbSDimitry Andric         OutStreamer->emitULEB128IntValue(Producer.second.size());
4905ffd83dbSDimitry Andric         OutStreamer->emitBytes(Producer.second);
4910b57cec5SDimitry Andric       }
4920b57cec5SDimitry Andric     }
49381ad6265SDimitry Andric     OutStreamer->popSection();
4940b57cec5SDimitry Andric   }
4950b57cec5SDimitry Andric }
4960b57cec5SDimitry Andric 
4970b57cec5SDimitry Andric void WebAssemblyAsmPrinter::EmitTargetFeatures(Module &M) {
4980b57cec5SDimitry Andric   struct FeatureEntry {
4990b57cec5SDimitry Andric     uint8_t Prefix;
5005ffd83dbSDimitry Andric     std::string Name;
5010b57cec5SDimitry Andric   };
5020b57cec5SDimitry Andric 
5030b57cec5SDimitry Andric   // Read target features and linkage policies from module metadata
5040b57cec5SDimitry Andric   SmallVector<FeatureEntry, 4> EmittedFeatures;
5055ffd83dbSDimitry Andric   auto EmitFeature = [&](std::string Feature) {
5065ffd83dbSDimitry Andric     std::string MDKey = (StringRef("wasm-feature-") + Feature).str();
5070b57cec5SDimitry Andric     Metadata *Policy = M.getModuleFlag(MDKey);
5080b57cec5SDimitry Andric     if (Policy == nullptr)
5095ffd83dbSDimitry Andric       return;
5100b57cec5SDimitry Andric 
5110b57cec5SDimitry Andric     FeatureEntry Entry;
5120b57cec5SDimitry Andric     Entry.Prefix = 0;
5135ffd83dbSDimitry Andric     Entry.Name = Feature;
5140b57cec5SDimitry Andric 
5150b57cec5SDimitry Andric     if (auto *MD = cast<ConstantAsMetadata>(Policy))
5160b57cec5SDimitry Andric       if (auto *I = cast<ConstantInt>(MD->getValue()))
5170b57cec5SDimitry Andric         Entry.Prefix = I->getZExtValue();
5180b57cec5SDimitry Andric 
5190b57cec5SDimitry Andric     // Silently ignore invalid metadata
5200b57cec5SDimitry Andric     if (Entry.Prefix != wasm::WASM_FEATURE_PREFIX_USED &&
5210b57cec5SDimitry Andric         Entry.Prefix != wasm::WASM_FEATURE_PREFIX_REQUIRED &&
5220b57cec5SDimitry Andric         Entry.Prefix != wasm::WASM_FEATURE_PREFIX_DISALLOWED)
5235ffd83dbSDimitry Andric       return;
5240b57cec5SDimitry Andric 
5250b57cec5SDimitry Andric     EmittedFeatures.push_back(Entry);
5265ffd83dbSDimitry Andric   };
5275ffd83dbSDimitry Andric 
5285ffd83dbSDimitry Andric   for (const SubtargetFeatureKV &KV : WebAssemblyFeatureKV) {
5295ffd83dbSDimitry Andric     EmitFeature(KV.Key);
5300b57cec5SDimitry Andric   }
5315ffd83dbSDimitry Andric   // This pseudo-feature tells the linker whether shared memory would be safe
5325ffd83dbSDimitry Andric   EmitFeature("shared-mem");
5330b57cec5SDimitry Andric 
534349cc55cSDimitry Andric   // This is an "architecture", not a "feature", but we emit it as such for
535349cc55cSDimitry Andric   // the benefit of tools like Binaryen and consistency with other producers.
536349cc55cSDimitry Andric   // FIXME: Subtarget is null here, so can't Subtarget->hasAddr64() ?
537349cc55cSDimitry Andric   if (M.getDataLayout().getPointerSize() == 8) {
538349cc55cSDimitry Andric     // Can't use EmitFeature since "wasm-feature-memory64" is not a module
539349cc55cSDimitry Andric     // flag.
540349cc55cSDimitry Andric     EmittedFeatures.push_back({wasm::WASM_FEATURE_PREFIX_USED, "memory64"});
541349cc55cSDimitry Andric   }
542349cc55cSDimitry Andric 
5430b57cec5SDimitry Andric   if (EmittedFeatures.size() == 0)
5440b57cec5SDimitry Andric     return;
5450b57cec5SDimitry Andric 
5460b57cec5SDimitry Andric   // Emit features and linkage policies into the "target_features" section
5470b57cec5SDimitry Andric   MCSectionWasm *FeaturesSection = OutContext.getWasmSection(
5480b57cec5SDimitry Andric       ".custom_section.target_features", SectionKind::getMetadata());
54981ad6265SDimitry Andric   OutStreamer->pushSection();
55081ad6265SDimitry Andric   OutStreamer->switchSection(FeaturesSection);
5510b57cec5SDimitry Andric 
5525ffd83dbSDimitry Andric   OutStreamer->emitULEB128IntValue(EmittedFeatures.size());
5530b57cec5SDimitry Andric   for (auto &F : EmittedFeatures) {
5545ffd83dbSDimitry Andric     OutStreamer->emitIntValue(F.Prefix, 1);
5555ffd83dbSDimitry Andric     OutStreamer->emitULEB128IntValue(F.Name.size());
5565ffd83dbSDimitry Andric     OutStreamer->emitBytes(F.Name);
5570b57cec5SDimitry Andric   }
5580b57cec5SDimitry Andric 
55981ad6265SDimitry Andric   OutStreamer->popSection();
5600b57cec5SDimitry Andric }
5610b57cec5SDimitry Andric 
56206c3fb27SDimitry Andric void WebAssemblyAsmPrinter::EmitFunctionAttributes(Module &M) {
56306c3fb27SDimitry Andric   auto V = M.getNamedGlobal("llvm.global.annotations");
56406c3fb27SDimitry Andric   if (!V)
56506c3fb27SDimitry Andric     return;
56606c3fb27SDimitry Andric 
56706c3fb27SDimitry Andric   // Group all the custom attributes by name.
56806c3fb27SDimitry Andric   MapVector<StringRef, SmallVector<MCSymbol *, 4>> CustomSections;
56906c3fb27SDimitry Andric   const ConstantArray *CA = cast<ConstantArray>(V->getOperand(0));
57006c3fb27SDimitry Andric   for (Value *Op : CA->operands()) {
57106c3fb27SDimitry Andric     auto *CS = cast<ConstantStruct>(Op);
57206c3fb27SDimitry Andric     // The first field is a pointer to the annotated variable.
57306c3fb27SDimitry Andric     Value *AnnotatedVar = CS->getOperand(0)->stripPointerCasts();
57406c3fb27SDimitry Andric     // Only annotated functions are supported for now.
57506c3fb27SDimitry Andric     if (!isa<Function>(AnnotatedVar))
57606c3fb27SDimitry Andric       continue;
57706c3fb27SDimitry Andric     auto *F = cast<Function>(AnnotatedVar);
57806c3fb27SDimitry Andric 
57906c3fb27SDimitry Andric     // The second field is a pointer to a global annotation string.
58006c3fb27SDimitry Andric     auto *GV = cast<GlobalVariable>(CS->getOperand(1)->stripPointerCasts());
58106c3fb27SDimitry Andric     StringRef AnnotationString;
58206c3fb27SDimitry Andric     getConstantStringInfo(GV, AnnotationString);
58306c3fb27SDimitry Andric     auto *Sym = cast<MCSymbolWasm>(getSymbol(F));
58406c3fb27SDimitry Andric     CustomSections[AnnotationString].push_back(Sym);
58506c3fb27SDimitry Andric   }
58606c3fb27SDimitry Andric 
58706c3fb27SDimitry Andric   // Emit a custom section for each unique attribute.
58806c3fb27SDimitry Andric   for (const auto &[Name, Symbols] : CustomSections) {
58906c3fb27SDimitry Andric     MCSectionWasm *CustomSection = OutContext.getWasmSection(
59006c3fb27SDimitry Andric         ".custom_section.llvm.func_attr.annotate." + Name, SectionKind::getMetadata());
59106c3fb27SDimitry Andric     OutStreamer->pushSection();
59206c3fb27SDimitry Andric     OutStreamer->switchSection(CustomSection);
59306c3fb27SDimitry Andric 
59406c3fb27SDimitry Andric     for (auto &Sym : Symbols) {
59506c3fb27SDimitry Andric       OutStreamer->emitValue(
59606c3fb27SDimitry Andric           MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_WASM_FUNCINDEX,
59706c3fb27SDimitry Andric                                   OutContext),
59806c3fb27SDimitry Andric           4);
59906c3fb27SDimitry Andric     }
60006c3fb27SDimitry Andric     OutStreamer->popSection();
60106c3fb27SDimitry Andric   }
60206c3fb27SDimitry Andric }
60306c3fb27SDimitry Andric 
6045ffd83dbSDimitry Andric void WebAssemblyAsmPrinter::emitConstantPool() {
60581ad6265SDimitry Andric   emitDecls(*MMI->getModule());
6060b57cec5SDimitry Andric   assert(MF->getConstantPool()->getConstants().empty() &&
6070b57cec5SDimitry Andric          "WebAssembly disables constant pools");
6080b57cec5SDimitry Andric }
6090b57cec5SDimitry Andric 
6105ffd83dbSDimitry Andric void WebAssemblyAsmPrinter::emitJumpTableInfo() {
6110b57cec5SDimitry Andric   // Nothing to do; jump tables are incorporated into the instruction stream.
6120b57cec5SDimitry Andric }
6130b57cec5SDimitry Andric 
6145ffd83dbSDimitry Andric void WebAssemblyAsmPrinter::emitFunctionBodyStart() {
6150b57cec5SDimitry Andric   const Function &F = MF->getFunction();
6160b57cec5SDimitry Andric   SmallVector<MVT, 1> ResultVTs;
6170b57cec5SDimitry Andric   SmallVector<MVT, 4> ParamVTs;
6185ffd83dbSDimitry Andric   computeSignatureVTs(F.getFunctionType(), &F, F, TM, ParamVTs, ResultVTs);
6195ffd83dbSDimitry Andric 
620*0fca6ea1SDimitry Andric   auto Signature = signatureFromMVTs(OutContext, ResultVTs, ParamVTs);
6210b57cec5SDimitry Andric   auto *WasmSym = cast<MCSymbolWasm>(CurrentFnSym);
622*0fca6ea1SDimitry Andric   WasmSym->setSignature(Signature);
6230b57cec5SDimitry Andric   WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
6240b57cec5SDimitry Andric 
6250b57cec5SDimitry Andric   getTargetStreamer()->emitFunctionType(WasmSym);
6260b57cec5SDimitry Andric 
6270b57cec5SDimitry Andric   // Emit the function index.
6280b57cec5SDimitry Andric   if (MDNode *Idx = F.getMetadata("wasm.index")) {
6290b57cec5SDimitry Andric     assert(Idx->getNumOperands() == 1);
6300b57cec5SDimitry Andric 
6310b57cec5SDimitry Andric     getTargetStreamer()->emitIndIdx(AsmPrinter::lowerConstant(
6320b57cec5SDimitry Andric         cast<ConstantAsMetadata>(Idx->getOperand(0))->getValue()));
6330b57cec5SDimitry Andric   }
6340b57cec5SDimitry Andric 
6350b57cec5SDimitry Andric   SmallVector<wasm::ValType, 16> Locals;
6360b57cec5SDimitry Andric   valTypesFromMVTs(MFI->getLocals(), Locals);
6370b57cec5SDimitry Andric   getTargetStreamer()->emitLocal(Locals);
6380b57cec5SDimitry Andric 
6395ffd83dbSDimitry Andric   AsmPrinter::emitFunctionBodyStart();
6400b57cec5SDimitry Andric }
6410b57cec5SDimitry Andric 
6425ffd83dbSDimitry Andric void WebAssemblyAsmPrinter::emitInstruction(const MachineInstr *MI) {
6430b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "EmitInstruction: " << *MI << '\n');
644753f127fSDimitry Andric   WebAssembly_MC::verifyInstructionPredicates(MI->getOpcode(),
645753f127fSDimitry Andric                                               Subtarget->getFeatureBits());
6460b57cec5SDimitry Andric 
6470b57cec5SDimitry Andric   switch (MI->getOpcode()) {
6480b57cec5SDimitry Andric   case WebAssembly::ARGUMENT_i32:
6490b57cec5SDimitry Andric   case WebAssembly::ARGUMENT_i32_S:
6500b57cec5SDimitry Andric   case WebAssembly::ARGUMENT_i64:
6510b57cec5SDimitry Andric   case WebAssembly::ARGUMENT_i64_S:
6520b57cec5SDimitry Andric   case WebAssembly::ARGUMENT_f32:
6530b57cec5SDimitry Andric   case WebAssembly::ARGUMENT_f32_S:
6540b57cec5SDimitry Andric   case WebAssembly::ARGUMENT_f64:
6550b57cec5SDimitry Andric   case WebAssembly::ARGUMENT_f64_S:
6560b57cec5SDimitry Andric   case WebAssembly::ARGUMENT_v16i8:
6570b57cec5SDimitry Andric   case WebAssembly::ARGUMENT_v16i8_S:
6580b57cec5SDimitry Andric   case WebAssembly::ARGUMENT_v8i16:
6590b57cec5SDimitry Andric   case WebAssembly::ARGUMENT_v8i16_S:
6600b57cec5SDimitry Andric   case WebAssembly::ARGUMENT_v4i32:
6610b57cec5SDimitry Andric   case WebAssembly::ARGUMENT_v4i32_S:
6620b57cec5SDimitry Andric   case WebAssembly::ARGUMENT_v2i64:
6630b57cec5SDimitry Andric   case WebAssembly::ARGUMENT_v2i64_S:
6640b57cec5SDimitry Andric   case WebAssembly::ARGUMENT_v4f32:
6650b57cec5SDimitry Andric   case WebAssembly::ARGUMENT_v4f32_S:
6660b57cec5SDimitry Andric   case WebAssembly::ARGUMENT_v2f64:
6670b57cec5SDimitry Andric   case WebAssembly::ARGUMENT_v2f64_S:
668*0fca6ea1SDimitry Andric   case WebAssembly::ARGUMENT_v8f16:
669*0fca6ea1SDimitry Andric   case WebAssembly::ARGUMENT_v8f16_S:
6700b57cec5SDimitry Andric     // These represent values which are live into the function entry, so there's
6710b57cec5SDimitry Andric     // no instruction to emit.
6720b57cec5SDimitry Andric     break;
6738bcb0991SDimitry Andric   case WebAssembly::FALLTHROUGH_RETURN: {
6740b57cec5SDimitry Andric     // These instructions represent the implicit return at the end of a
6758bcb0991SDimitry Andric     // function body.
6760b57cec5SDimitry Andric     if (isVerbose()) {
6778bcb0991SDimitry Andric       OutStreamer->AddComment("fallthrough-return");
67881ad6265SDimitry Andric       OutStreamer->addBlankLine();
6790b57cec5SDimitry Andric     }
6800b57cec5SDimitry Andric     break;
6810b57cec5SDimitry Andric   }
6820b57cec5SDimitry Andric   case WebAssembly::COMPILER_FENCE:
6830b57cec5SDimitry Andric     // This is a compiler barrier that prevents instruction reordering during
6840b57cec5SDimitry Andric     // backend compilation, and should not be emitted.
6850b57cec5SDimitry Andric     break;
6860b57cec5SDimitry Andric   default: {
6870b57cec5SDimitry Andric     WebAssemblyMCInstLower MCInstLowering(OutContext, *this);
6880b57cec5SDimitry Andric     MCInst TmpInst;
6890b57cec5SDimitry Andric     MCInstLowering.lower(MI, TmpInst);
6900b57cec5SDimitry Andric     EmitToStreamer(*OutStreamer, TmpInst);
6910b57cec5SDimitry Andric     break;
6920b57cec5SDimitry Andric   }
6930b57cec5SDimitry Andric   }
6940b57cec5SDimitry Andric }
6950b57cec5SDimitry Andric 
6960b57cec5SDimitry Andric bool WebAssemblyAsmPrinter::PrintAsmOperand(const MachineInstr *MI,
6970b57cec5SDimitry Andric                                             unsigned OpNo,
6980b57cec5SDimitry Andric                                             const char *ExtraCode,
6990b57cec5SDimitry Andric                                             raw_ostream &OS) {
7000b57cec5SDimitry Andric   // First try the generic code, which knows about modifiers like 'c' and 'n'.
7010b57cec5SDimitry Andric   if (!AsmPrinter::PrintAsmOperand(MI, OpNo, ExtraCode, OS))
7020b57cec5SDimitry Andric     return false;
7030b57cec5SDimitry Andric 
7040b57cec5SDimitry Andric   if (!ExtraCode) {
7050b57cec5SDimitry Andric     const MachineOperand &MO = MI->getOperand(OpNo);
7060b57cec5SDimitry Andric     switch (MO.getType()) {
7070b57cec5SDimitry Andric     case MachineOperand::MO_Immediate:
7080b57cec5SDimitry Andric       OS << MO.getImm();
7090b57cec5SDimitry Andric       return false;
7100b57cec5SDimitry Andric     case MachineOperand::MO_Register:
7110b57cec5SDimitry Andric       // FIXME: only opcode that still contains registers, as required by
7120b57cec5SDimitry Andric       // MachineInstr::getDebugVariable().
7130b57cec5SDimitry Andric       assert(MI->getOpcode() == WebAssembly::INLINEASM);
7140b57cec5SDimitry Andric       OS << regToString(MO);
7150b57cec5SDimitry Andric       return false;
7160b57cec5SDimitry Andric     case MachineOperand::MO_GlobalAddress:
7170b57cec5SDimitry Andric       PrintSymbolOperand(MO, OS);
7180b57cec5SDimitry Andric       return false;
7190b57cec5SDimitry Andric     case MachineOperand::MO_ExternalSymbol:
7200b57cec5SDimitry Andric       GetExternalSymbolSymbol(MO.getSymbolName())->print(OS, MAI);
7210b57cec5SDimitry Andric       printOffset(MO.getOffset(), OS);
7220b57cec5SDimitry Andric       return false;
7230b57cec5SDimitry Andric     case MachineOperand::MO_MachineBasicBlock:
7240b57cec5SDimitry Andric       MO.getMBB()->getSymbol()->print(OS, MAI);
7250b57cec5SDimitry Andric       return false;
7260b57cec5SDimitry Andric     default:
7270b57cec5SDimitry Andric       break;
7280b57cec5SDimitry Andric     }
7290b57cec5SDimitry Andric   }
7300b57cec5SDimitry Andric 
7310b57cec5SDimitry Andric   return true;
7320b57cec5SDimitry Andric }
7330b57cec5SDimitry Andric 
7340b57cec5SDimitry Andric bool WebAssemblyAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
7350b57cec5SDimitry Andric                                                   unsigned OpNo,
7360b57cec5SDimitry Andric                                                   const char *ExtraCode,
7370b57cec5SDimitry Andric                                                   raw_ostream &OS) {
7380b57cec5SDimitry Andric   // The current approach to inline asm is that "r" constraints are expressed
7390b57cec5SDimitry Andric   // as local indices, rather than values on the operand stack. This simplifies
7400b57cec5SDimitry Andric   // using "r" as it eliminates the need to push and pop the values in a
7410b57cec5SDimitry Andric   // particular order, however it also makes it impossible to have an "m"
7420b57cec5SDimitry Andric   // constraint. So we don't support it.
7430b57cec5SDimitry Andric 
7440b57cec5SDimitry Andric   return AsmPrinter::PrintAsmMemoryOperand(MI, OpNo, ExtraCode, OS);
7450b57cec5SDimitry Andric }
7460b57cec5SDimitry Andric 
7470b57cec5SDimitry Andric // Force static initialization.
748480093f4SDimitry Andric extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeWebAssemblyAsmPrinter() {
7490b57cec5SDimitry Andric   RegisterAsmPrinter<WebAssemblyAsmPrinter> X(getTheWebAssemblyTarget32());
7500b57cec5SDimitry Andric   RegisterAsmPrinter<WebAssemblyAsmPrinter> Y(getTheWebAssemblyTarget64());
7510b57cec5SDimitry Andric }
752