1b9073fb2SJF Bastien //===-- WebAssemblyAsmPrinter.cpp - WebAssembly LLVM assembly writer ------===//
2b9073fb2SJF Bastien //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6b9073fb2SJF Bastien //
7b9073fb2SJF Bastien //===----------------------------------------------------------------------===//
8b9073fb2SJF Bastien ///
9b9073fb2SJF Bastien /// \file
105f8f34e4SAdrian Prantl /// This file contains a printer that converts from our internal
11b9073fb2SJF Bastien /// representation of machine-dependent LLVM code to the WebAssembly assembly
12b9073fb2SJF Bastien /// language.
13b9073fb2SJF Bastien ///
14b9073fb2SJF Bastien //===----------------------------------------------------------------------===//
15b9073fb2SJF Bastien 
16d934cb88SDan Gohman #include "WebAssemblyAsmPrinter.h"
17cf4748f1SDan Gohman #include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
183469ee12SDan Gohman #include "MCTargetDesc/WebAssemblyTargetStreamer.h"
19c6c42137SRichard Trieu #include "TargetInfo/WebAssemblyTargetInfo.h"
200b2bc69bSHeejin Ahn #include "Utils/WebAssemblyTypeUtilities.h"
210b2bc69bSHeejin Ahn #include "Utils/WebAssemblyUtilities.h"
22c64d7655SDerek Schuff #include "WebAssembly.h"
23cf4748f1SDan Gohman #include "WebAssemblyMCInstLower.h"
24b9073fb2SJF Bastien #include "WebAssemblyMachineFunctionInfo.h"
25b9073fb2SJF Bastien #include "WebAssemblyRegisterInfo.h"
269647a6f7SWouter van Oortmerssen #include "WebAssemblyRuntimeLibcallSignatures.h"
27f6f4f843SThomas Lively #include "WebAssemblyTargetMachine.h"
28cbda16ebSThomas Lively #include "llvm/ADT/SmallSet.h"
29e51c058eSDan Gohman #include "llvm/ADT/StringExtras.h"
30f6f4f843SThomas Lively #include "llvm/BinaryFormat/Wasm.h"
31754cd11dSDan Gohman #include "llvm/CodeGen/Analysis.h"
32b9073fb2SJF Bastien #include "llvm/CodeGen/AsmPrinter.h"
3354be3b1fSJF Bastien #include "llvm/CodeGen/MachineConstantPool.h"
34b9073fb2SJF Bastien #include "llvm/CodeGen/MachineInstr.h"
3582607f56SDan Gohman #include "llvm/CodeGen/MachineModuleInfoImpls.h"
36b9073fb2SJF Bastien #include "llvm/IR/DataLayout.h"
37c6795e07SThomas Lively #include "llvm/IR/DebugInfoMetadata.h"
38d934cb88SDan Gohman #include "llvm/IR/GlobalVariable.h"
393f34e1b8SThomas Lively #include "llvm/IR/Metadata.h"
40cf4748f1SDan Gohman #include "llvm/MC/MCContext.h"
41cfd44a2eSSam Clegg #include "llvm/MC/MCSectionWasm.h"
42b9073fb2SJF Bastien #include "llvm/MC/MCStreamer.h"
43b6091dfeSJF Bastien #include "llvm/MC/MCSymbol.h"
44cfd44a2eSSam Clegg #include "llvm/MC/MCSymbolWasm.h"
4589b57061SReid Kleckner #include "llvm/MC/TargetRegistry.h"
46b9073fb2SJF Bastien #include "llvm/Support/Debug.h"
47b9073fb2SJF Bastien #include "llvm/Support/raw_ostream.h"
482e150409SThomas Lively 
49b9073fb2SJF Bastien using namespace llvm;
50b9073fb2SJF Bastien 
51b9073fb2SJF Bastien #define DEBUG_TYPE "asm-printer"
52b9073fb2SJF Bastien 
53d6f48786SHeejin Ahn extern cl::opt<bool> WasmKeepRegisters;
54d6f48786SHeejin Ahn 
55b9073fb2SJF Bastien //===----------------------------------------------------------------------===//
5645479f62SJF Bastien // Helpers.
5745479f62SJF Bastien //===----------------------------------------------------------------------===//
58b9073fb2SJF Bastien 
getRegType(unsigned RegNo) const5953828fd7SDan Gohman MVT WebAssemblyAsmPrinter::getRegType(unsigned RegNo) const {
60c8e8e2a0SKrzysztof Parzyszek   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
610cfb5f85SDan Gohman   const TargetRegisterClass *TRC = MRI->getRegClass(RegNo);
6239bf39f3SDerek Schuff   for (MVT T : {MVT::i32, MVT::i64, MVT::f32, MVT::f64, MVT::v16i8, MVT::v8i16,
6351ed131eSDerek Schuff                 MVT::v4i32, MVT::v2i64, MVT::v4f32, MVT::v2f64})
64c8e8e2a0SKrzysztof Parzyszek     if (TRI->isTypeLegalForClass(*TRC, T))
6553828fd7SDan Gohman       return T;
66d34e60caSNicola Zaghen   LLVM_DEBUG(errs() << "Unknown type for register number: " << RegNo);
671d20a5e9SJF Bastien   llvm_unreachable("Unknown register type");
6853828fd7SDan Gohman   return MVT::Other;
691d20a5e9SJF Bastien }
701d20a5e9SJF Bastien 
regToString(const MachineOperand & MO)711d20a5e9SJF Bastien std::string WebAssemblyAsmPrinter::regToString(const MachineOperand &MO) {
7205c145d6SDaniel Sanders   Register RegNo = MO.getReg();
732bea69bfSDaniel Sanders   assert(Register::isVirtualRegister(RegNo) &&
74d9625276SDan Gohman          "Unlowered physical register encountered during assembly printing");
754ba4816bSDan Gohman   assert(!MFI->isVRegStackified(RegNo));
76058fce54SDan Gohman   unsigned WAReg = MFI->getWAReg(RegNo);
77058fce54SDan Gohman   assert(WAReg != WebAssemblyFunctionInfo::UnusedReg);
784ba4816bSDan Gohman   return '$' + utostr(WAReg);
79e51c058eSDan Gohman }
80e51c058eSDan Gohman 
getTargetStreamer()81ec977b07SDan Gohman WebAssemblyTargetStreamer *WebAssemblyAsmPrinter::getTargetStreamer() {
823469ee12SDan Gohman   MCTargetStreamer *TS = OutStreamer->getTargetStreamer();
833469ee12SDan Gohman   return static_cast<WebAssemblyTargetStreamer *>(TS);
8473ff6afaSJF Bastien }
8573ff6afaSJF Bastien 
863bba91f6SHeejin Ahn // Emscripten exception handling helpers
873bba91f6SHeejin Ahn //
883bba91f6SHeejin Ahn // This converts invoke names generated by LowerEmscriptenEHSjLj to real names
893bba91f6SHeejin Ahn // that are expected by JavaScript glue code. The invoke names generated by
903bba91f6SHeejin Ahn // Emscripten JS glue code are based on their argument and return types; for
913bba91f6SHeejin Ahn // example, for a function that takes an i32 and returns nothing, it is
923bba91f6SHeejin Ahn // 'invoke_vi'. But the format of invoke generated by LowerEmscriptenEHSjLj pass
933bba91f6SHeejin Ahn // contains a mangled string generated from their IR types, for example,
943bba91f6SHeejin Ahn // "__invoke_void_%struct.mystruct*_int", because final wasm types are not
953bba91f6SHeejin Ahn // available in the IR pass. So we convert those names to the form that
963bba91f6SHeejin Ahn // Emscripten JS code expects.
973bba91f6SHeejin Ahn //
983bba91f6SHeejin Ahn // Refer to LowerEmscriptenEHSjLj pass for more details.
993bba91f6SHeejin Ahn 
1003bba91f6SHeejin Ahn // Returns true if the given function name is an invoke name generated by
1013bba91f6SHeejin Ahn // LowerEmscriptenEHSjLj pass.
isEmscriptenInvokeName(StringRef Name)1023bba91f6SHeejin Ahn static bool isEmscriptenInvokeName(StringRef Name) {
1033bba91f6SHeejin Ahn   if (Name.front() == '"' && Name.back() == '"')
1043bba91f6SHeejin Ahn     Name = Name.substr(1, Name.size() - 2);
1053bba91f6SHeejin Ahn   return Name.startswith("__invoke_");
1063bba91f6SHeejin Ahn }
1073bba91f6SHeejin Ahn 
1083bba91f6SHeejin Ahn // Returns a character that represents the given wasm value type in invoke
1093bba91f6SHeejin Ahn // signatures.
getInvokeSig(wasm::ValType VT)1103bba91f6SHeejin Ahn static char getInvokeSig(wasm::ValType VT) {
1113bba91f6SHeejin Ahn   switch (VT) {
1123bba91f6SHeejin Ahn   case wasm::ValType::I32:
1133bba91f6SHeejin Ahn     return 'i';
1143bba91f6SHeejin Ahn   case wasm::ValType::I64:
1153bba91f6SHeejin Ahn     return 'j';
1163bba91f6SHeejin Ahn   case wasm::ValType::F32:
1173bba91f6SHeejin Ahn     return 'f';
1183bba91f6SHeejin Ahn   case wasm::ValType::F64:
1193bba91f6SHeejin Ahn     return 'd';
1203bba91f6SHeejin Ahn   case wasm::ValType::V128:
1213bba91f6SHeejin Ahn     return 'V';
122388fb67bSPaulo Matos   case wasm::ValType::FUNCREF:
123388fb67bSPaulo Matos     return 'F';
1243bba91f6SHeejin Ahn   case wasm::ValType::EXTERNREF:
1253bba91f6SHeejin Ahn     return 'X';
1263bba91f6SHeejin Ahn   }
12703280055SSimon Pilgrim   llvm_unreachable("Unhandled wasm::ValType enum");
1283bba91f6SHeejin Ahn }
1293bba91f6SHeejin Ahn 
1303bba91f6SHeejin Ahn // Given the wasm signature, generate the invoke name in the format JS glue code
1313bba91f6SHeejin Ahn // expects.
getEmscriptenInvokeSymbolName(wasm::WasmSignature * Sig)1323bba91f6SHeejin Ahn static std::string getEmscriptenInvokeSymbolName(wasm::WasmSignature *Sig) {
1333bba91f6SHeejin Ahn   assert(Sig->Returns.size() <= 1);
1343bba91f6SHeejin Ahn   std::string Ret = "invoke_";
1353bba91f6SHeejin Ahn   if (!Sig->Returns.empty())
1363bba91f6SHeejin Ahn     for (auto VT : Sig->Returns)
1373bba91f6SHeejin Ahn       Ret += getInvokeSig(VT);
1383bba91f6SHeejin Ahn   else
1393bba91f6SHeejin Ahn     Ret += 'v';
1403bba91f6SHeejin Ahn   // Invokes' first argument is a pointer to the original function, so skip it
1413bba91f6SHeejin Ahn   for (unsigned I = 1, E = Sig->Params.size(); I < E; I++)
1423bba91f6SHeejin Ahn     Ret += getInvokeSig(Sig->Params[I]);
1433bba91f6SHeejin Ahn   return Ret;
1443bba91f6SHeejin Ahn }
1453bba91f6SHeejin Ahn 
14645479f62SJF Bastien //===----------------------------------------------------------------------===//
14745479f62SJF Bastien // WebAssemblyAsmPrinter Implementation.
14845479f62SJF Bastien //===----------------------------------------------------------------------===//
14946e33168SDerek Schuff 
getMCSymbolForFunction(const Function * F,bool EnableEmEH,wasm::WasmSignature * Sig,bool & InvokeDetected)1503bba91f6SHeejin Ahn MCSymbolWasm *WebAssemblyAsmPrinter::getMCSymbolForFunction(
1513bba91f6SHeejin Ahn     const Function *F, bool EnableEmEH, wasm::WasmSignature *Sig,
1523bba91f6SHeejin Ahn     bool &InvokeDetected) {
1533bba91f6SHeejin Ahn   MCSymbolWasm *WasmSym = nullptr;
1543bba91f6SHeejin Ahn   if (EnableEmEH && isEmscriptenInvokeName(F->getName())) {
1553bba91f6SHeejin Ahn     assert(Sig);
1563bba91f6SHeejin Ahn     InvokeDetected = true;
1573bba91f6SHeejin Ahn     if (Sig->Returns.size() > 1) {
1583bba91f6SHeejin Ahn       std::string Msg =
1593bba91f6SHeejin Ahn           "Emscripten EH/SjLj does not support multivalue returns: " +
1603bba91f6SHeejin Ahn           std::string(F->getName()) + ": " +
1613bba91f6SHeejin Ahn           WebAssembly::signatureToString(Sig);
16221661607SSimon Pilgrim       report_fatal_error(Twine(Msg));
1633bba91f6SHeejin Ahn     }
1643bba91f6SHeejin Ahn     WasmSym = cast<MCSymbolWasm>(
1653bba91f6SHeejin Ahn         GetExternalSymbolSymbol(getEmscriptenInvokeSymbolName(Sig)));
1663bba91f6SHeejin Ahn   } else {
1673bba91f6SHeejin Ahn     WasmSym = cast<MCSymbolWasm>(getSymbol(F));
1683bba91f6SHeejin Ahn   }
1693bba91f6SHeejin Ahn   return WasmSym;
1703bba91f6SHeejin Ahn }
1713bba91f6SHeejin Ahn 
emitGlobalVariable(const GlobalVariable * GV)172b2f21b14SAndy Wingo void WebAssemblyAsmPrinter::emitGlobalVariable(const GlobalVariable *GV) {
173b2f21b14SAndy Wingo   if (!WebAssembly::isWasmVarAddressSpace(GV->getAddressSpace())) {
174b2f21b14SAndy Wingo     AsmPrinter::emitGlobalVariable(GV);
175b2f21b14SAndy Wingo     return;
176b2f21b14SAndy Wingo   }
177b2f21b14SAndy Wingo 
178b2f21b14SAndy Wingo   assert(!GV->isThreadLocal());
179b2f21b14SAndy Wingo 
180b2f21b14SAndy Wingo   MCSymbolWasm *Sym = cast<MCSymbolWasm>(getSymbol(GV));
181b2f21b14SAndy Wingo 
182b2f21b14SAndy Wingo   if (!Sym->getType()) {
183864767abSPaulo Matos     SmallVector<MVT, 1> VTs;
184864767abSPaulo Matos     Type *GlobalVT = GV->getValueType();
185c67c9cfeSPaulo Matos     if (Subtarget) {
186c67c9cfeSPaulo Matos       // Subtarget is only set when a function is defined, because
187c67c9cfeSPaulo Matos       // each function can declare a different subtarget. For example,
188c67c9cfeSPaulo Matos       // on ARM a compilation unit might have a function on ARM and
189c67c9cfeSPaulo Matos       // another on Thumb. Therefore only if Subtarget is non-null we
190c67c9cfeSPaulo Matos       // can actually calculate the legal VTs.
191c67c9cfeSPaulo Matos       const WebAssemblyTargetLowering &TLI = *Subtarget->getTargetLowering();
192864767abSPaulo Matos       computeLegalValueVTs(TLI, GV->getParent()->getContext(),
193864767abSPaulo Matos                            GV->getParent()->getDataLayout(), GlobalVT, VTs);
194c67c9cfeSPaulo Matos     }
195864767abSPaulo Matos     WebAssembly::wasmSymbolSetType(Sym, GlobalVT, VTs);
196b2f21b14SAndy Wingo   }
197b2f21b14SAndy Wingo 
198b2f21b14SAndy Wingo   emitVisibility(Sym, GV->getVisibility(), !GV->isDeclaration());
199c67c9cfeSPaulo Matos   emitSymbolType(Sym);
200b2f21b14SAndy Wingo   if (GV->hasInitializer()) {
201b2f21b14SAndy Wingo     assert(getSymbolPreferLocal(*GV) == Sym);
202b2f21b14SAndy Wingo     emitLinkage(GV, Sym);
203b2f21b14SAndy Wingo     OutStreamer->emitLabel(Sym);
204b2f21b14SAndy Wingo     // TODO: Actually emit the initializer value.  Otherwise the global has the
205b2f21b14SAndy Wingo     // default value for its type (0, ref.null, etc).
20615d82c62SFangrui Song     OutStreamer->addBlankLine();
207b2f21b14SAndy Wingo   }
208b2f21b14SAndy Wingo }
209b2f21b14SAndy Wingo 
getOrCreateWasmSymbol(StringRef Name)2109647a6f7SWouter van Oortmerssen MCSymbol *WebAssemblyAsmPrinter::getOrCreateWasmSymbol(StringRef Name) {
2119647a6f7SWouter van Oortmerssen   auto *WasmSym = cast<MCSymbolWasm>(GetExternalSymbolSymbol(Name));
2129647a6f7SWouter van Oortmerssen 
2139647a6f7SWouter van Oortmerssen   // May be called multiple times, so early out.
214e0e687a6SKazu Hirata   if (WasmSym->getType())
2159647a6f7SWouter van Oortmerssen     return WasmSym;
2169647a6f7SWouter van Oortmerssen 
2179647a6f7SWouter van Oortmerssen   const WebAssemblySubtarget &Subtarget = getSubtarget();
2189647a6f7SWouter van Oortmerssen 
2199647a6f7SWouter van Oortmerssen   // Except for certain known symbols, all symbols used by CodeGen are
2209647a6f7SWouter van Oortmerssen   // functions. It's OK to hardcode knowledge of specific symbols here; this
2219647a6f7SWouter van Oortmerssen   // method is precisely there for fetching the signatures of known
2229647a6f7SWouter van Oortmerssen   // Clang-provided symbols.
2239647a6f7SWouter van Oortmerssen   if (Name == "__stack_pointer" || Name == "__tls_base" ||
2249647a6f7SWouter van Oortmerssen       Name == "__memory_base" || Name == "__table_base" ||
2259647a6f7SWouter van Oortmerssen       Name == "__tls_size" || Name == "__tls_align") {
2269647a6f7SWouter van Oortmerssen     bool Mutable =
2279647a6f7SWouter van Oortmerssen         Name == "__stack_pointer" || Name == "__tls_base";
2289647a6f7SWouter van Oortmerssen     WasmSym->setType(wasm::WASM_SYMBOL_TYPE_GLOBAL);
2299647a6f7SWouter van Oortmerssen     WasmSym->setGlobalType(wasm::WasmGlobalType{
2309647a6f7SWouter van Oortmerssen         uint8_t(Subtarget.hasAddr64() ? wasm::WASM_TYPE_I64
2319647a6f7SWouter van Oortmerssen                                       : wasm::WASM_TYPE_I32),
2329647a6f7SWouter van Oortmerssen         Mutable});
2339647a6f7SWouter van Oortmerssen     return WasmSym;
2349647a6f7SWouter van Oortmerssen   }
2359647a6f7SWouter van Oortmerssen 
2369261ee32SHeejin Ahn   if (Name.startswith("GCC_except_table")) {
2379261ee32SHeejin Ahn     WasmSym->setType(wasm::WASM_SYMBOL_TYPE_DATA);
2389261ee32SHeejin Ahn     return WasmSym;
2399261ee32SHeejin Ahn   }
2409261ee32SHeejin Ahn 
2419647a6f7SWouter van Oortmerssen   SmallVector<wasm::ValType, 4> Returns;
2429647a6f7SWouter van Oortmerssen   SmallVector<wasm::ValType, 4> Params;
24328780e59SHeejin Ahn   if (Name == "__cpp_exception" || Name == "__c_longjmp") {
2449647a6f7SWouter van Oortmerssen     WasmSym->setType(wasm::WASM_SYMBOL_TYPE_TAG);
2459261ee32SHeejin Ahn     // In static linking we define tag symbols in WasmException::endModule().
2469261ee32SHeejin Ahn     // But we may have multiple objects to be linked together, each of which
2479261ee32SHeejin Ahn     // defines the tag symbols. To resolve them, we declare them as weak. In
2489261ee32SHeejin Ahn     // dynamic linking we make tag symbols undefined in the backend, define it
2499261ee32SHeejin Ahn     // in JS, and feed them to each importing module.
2509261ee32SHeejin Ahn     if (!isPositionIndependent())
2519647a6f7SWouter van Oortmerssen       WasmSym->setWeak(true);
2529647a6f7SWouter van Oortmerssen     WasmSym->setExternal(true);
2539647a6f7SWouter van Oortmerssen 
25428780e59SHeejin Ahn     // Currently both C++ exceptions and C longjmps have a single pointer type
25528780e59SHeejin Ahn     // param. For C++ exceptions it is a pointer to an exception object, and for
25628780e59SHeejin Ahn     // C longjmps it is pointer to a struct that contains a setjmp buffer and a
25728780e59SHeejin Ahn     // longjmp return value. We may consider using multiple value parameters for
25828780e59SHeejin Ahn     // longjmps later when multivalue support is ready.
25928780e59SHeejin Ahn     wasm::ValType AddrType =
26028780e59SHeejin Ahn         Subtarget.hasAddr64() ? wasm::ValType::I64 : wasm::ValType::I32;
26128780e59SHeejin Ahn     Params.push_back(AddrType);
2629647a6f7SWouter van Oortmerssen   } else { // Function symbols
2639647a6f7SWouter van Oortmerssen     WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
2649647a6f7SWouter van Oortmerssen     getLibcallSignature(Subtarget, Name, Returns, Params);
2659647a6f7SWouter van Oortmerssen   }
2669647a6f7SWouter van Oortmerssen   auto Signature = std::make_unique<wasm::WasmSignature>(std::move(Returns),
2679647a6f7SWouter van Oortmerssen                                                          std::move(Params));
2689647a6f7SWouter van Oortmerssen   WasmSym->setSignature(Signature.get());
2699647a6f7SWouter van Oortmerssen   addSignature(std::move(Signature));
2709647a6f7SWouter van Oortmerssen 
2719647a6f7SWouter van Oortmerssen   return WasmSym;
2729647a6f7SWouter van Oortmerssen }
2739647a6f7SWouter van Oortmerssen 
emitSymbolType(const MCSymbolWasm * Sym)274c67c9cfeSPaulo Matos void WebAssemblyAsmPrinter::emitSymbolType(const MCSymbolWasm *Sym) {
275c67c9cfeSPaulo Matos   Optional<wasm::WasmSymbolType> WasmTy = Sym->getType();
276c67c9cfeSPaulo Matos   if (!WasmTy)
277c67c9cfeSPaulo Matos     return;
278c67c9cfeSPaulo Matos 
2797a47ee51SKazu Hirata   switch (*WasmTy) {
280c67c9cfeSPaulo Matos   case wasm::WASM_SYMBOL_TYPE_GLOBAL:
281c67c9cfeSPaulo Matos     getTargetStreamer()->emitGlobalType(Sym);
282c67c9cfeSPaulo Matos     break;
283c67c9cfeSPaulo Matos   case wasm::WASM_SYMBOL_TYPE_TAG:
284c67c9cfeSPaulo Matos     getTargetStreamer()->emitTagType(Sym);
285c67c9cfeSPaulo Matos     break;
286c67c9cfeSPaulo Matos   case wasm::WASM_SYMBOL_TYPE_TABLE:
287c67c9cfeSPaulo Matos     getTargetStreamer()->emitTableType(Sym);
288c67c9cfeSPaulo Matos     break;
289c67c9cfeSPaulo Matos   default:
290c67c9cfeSPaulo Matos     break; // We only handle globals, tags and tables here
291c67c9cfeSPaulo Matos   }
292c67c9cfeSPaulo Matos }
293c67c9cfeSPaulo Matos 
emitDecls(const Module & M)29486cc731fSAlex Bradbury void WebAssemblyAsmPrinter::emitDecls(const Module &M) {
2959647a6f7SWouter van Oortmerssen   if (signaturesEmitted)
2969647a6f7SWouter van Oortmerssen     return;
2979647a6f7SWouter van Oortmerssen   signaturesEmitted = true;
2989647a6f7SWouter van Oortmerssen 
2999647a6f7SWouter van Oortmerssen   // Normally symbols for globals get discovered as the MI gets lowered,
300c67c9cfeSPaulo Matos   // but we need to know about them ahead of time. This will however,
301c67c9cfeSPaulo Matos   // only find symbols that have been used. Unused symbols from globals will
302c67c9cfeSPaulo Matos   // not be found here.
3039647a6f7SWouter van Oortmerssen   MachineModuleInfoWasm &MMIW = MMI->getObjFileInfo<MachineModuleInfoWasm>();
3049647a6f7SWouter van Oortmerssen   for (const auto &Name : MMIW.MachineSymbolsUsed) {
3052368f18eSWouter van Oortmerssen     auto *WasmSym = cast<MCSymbolWasm>(getOrCreateWasmSymbol(Name.getKey()));
3062368f18eSWouter van Oortmerssen     if (WasmSym->isFunction()) {
3072368f18eSWouter van Oortmerssen       // TODO(wvo): is there any case where this overlaps with the call to
3082368f18eSWouter van Oortmerssen       // emitFunctionType in the loop below?
3092368f18eSWouter van Oortmerssen       getTargetStreamer()->emitFunctionType(WasmSym);
3102368f18eSWouter van Oortmerssen     }
3119647a6f7SWouter van Oortmerssen   }
3129647a6f7SWouter van Oortmerssen 
3133231e518SWouter van Oortmerssen   for (auto &It : OutContext.getSymbols()) {
314c67c9cfeSPaulo Matos     // Emit .globaltype, .tagtype, or .tabletype declarations for extern
315c67c9cfeSPaulo Matos     // declarations, i.e. those that have only been declared (but not defined)
316c67c9cfeSPaulo Matos     // in the current module
3173231e518SWouter van Oortmerssen     auto Sym = cast<MCSymbolWasm>(It.getValue());
318c67c9cfeSPaulo Matos     if (!Sym->isDefined())
319c67c9cfeSPaulo Matos       emitSymbolType(Sym);
3203231e518SWouter van Oortmerssen   }
3213231e518SWouter van Oortmerssen 
3223bba91f6SHeejin Ahn   DenseSet<MCSymbol *> InvokeSymbols;
3235859a9edSDerek Schuff   for (const auto &F : M) {
324881d8778SSam Clegg     if (F.isIntrinsic())
325881d8778SSam Clegg       continue;
326881d8778SSam Clegg 
32786cc731fSAlex Bradbury     // Emit function type info for all functions. This will emit duplicate
32886cc731fSAlex Bradbury     // information for defined functions (which already have function type
32986cc731fSAlex Bradbury     // info emitted alongside their definition), but this is necessary in
33086cc731fSAlex Bradbury     // order to enable the single-pass WebAssemblyAsmTypeCheck to succeed.
3312726b88cSDan Gohman     SmallVector<MVT, 4> Results;
3322726b88cSDan Gohman     SmallVector<MVT, 4> Params;
33308670d43SYuta Saito     computeSignatureVTs(F.getFunctionType(), &F, F, TM, Params, Results);
3343bba91f6SHeejin Ahn     // At this point these MCSymbols may or may not have been created already
3353bba91f6SHeejin Ahn     // and thus also contain a signature, but we need to get the signature
3363bba91f6SHeejin Ahn     // anyway here in case it is an invoke that has not yet been created. We
3373bba91f6SHeejin Ahn     // will discard it later if it turns out not to be necessary.
3383bba91f6SHeejin Ahn     auto Signature = signatureFromMVTs(Results, Params);
3393bba91f6SHeejin Ahn     bool InvokeDetected = false;
3404625b848SHeejin Ahn     auto *Sym = getMCSymbolForFunction(
3414625b848SHeejin Ahn         &F, WebAssembly::WasmEnableEmEH || WebAssembly::WasmEnableEmSjLj,
3423bba91f6SHeejin Ahn         Signature.get(), InvokeDetected);
3433bba91f6SHeejin Ahn 
3443bba91f6SHeejin Ahn     // Multiple functions can be mapped to the same invoke symbol. For
3453bba91f6SHeejin Ahn     // example, two IR functions '__invoke_void_i8*' and '__invoke_void_i32'
3463bba91f6SHeejin Ahn     // are both mapped to '__invoke_vi'. We keep them in a set once we emit an
3473bba91f6SHeejin Ahn     // Emscripten EH symbol so we don't emit the same symbol twice.
3483bba91f6SHeejin Ahn     if (InvokeDetected && !InvokeSymbols.insert(Sym).second)
3493bba91f6SHeejin Ahn       continue;
3503bba91f6SHeejin Ahn 
35121d45a2cSHeejin Ahn     Sym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
35277a7a380SDerek Schuff     if (!Sym->getSignature()) {
35377a7a380SDerek Schuff       Sym->setSignature(Signature.get());
35477a7a380SDerek Schuff       addSignature(std::move(Signature));
3553bba91f6SHeejin Ahn     } else {
3563bba91f6SHeejin Ahn       // This symbol has already been created and had a signature. Discard it.
3573bba91f6SHeejin Ahn       Signature.reset();
35877a7a380SDerek Schuff     }
3593bba91f6SHeejin Ahn 
36049482f82SWouter van Oortmerssen     getTargetStreamer()->emitFunctionType(Sym);
361db1916a6SDan Gohman 
3623bba91f6SHeejin Ahn     if (F.hasFnAttribute("wasm-import-module")) {
363f208f631SHeejin Ahn       StringRef Name =
364f208f631SHeejin Ahn           F.getFnAttribute("wasm-import-module").getValueAsString();
3655be42f36SSam Clegg       Sym->setImportModule(storeName(Name));
36677a7a380SDerek Schuff       getTargetStreamer()->emitImportModule(Sym, Name);
367db1916a6SDan Gohman     }
3683bba91f6SHeejin Ahn     if (F.hasFnAttribute("wasm-import-name")) {
3693bba91f6SHeejin Ahn       // If this is a converted Emscripten EH/SjLj symbol, we shouldn't use
3703bba91f6SHeejin Ahn       // the original function name but the converted symbol name.
371f726e445SDan Gohman       StringRef Name =
3723bba91f6SHeejin Ahn           InvokeDetected
3733bba91f6SHeejin Ahn               ? Sym->getName()
3743bba91f6SHeejin Ahn               : F.getFnAttribute("wasm-import-name").getValueAsString();
3755be42f36SSam Clegg       Sym->setImportName(storeName(Name));
376f726e445SDan Gohman       getTargetStreamer()->emitImportName(Sym, Name);
377f726e445SDan Gohman     }
378881d8778SSam Clegg 
379881d8778SSam Clegg     if (F.hasFnAttribute("wasm-export-name")) {
380881d8778SSam Clegg       auto *Sym = cast<MCSymbolWasm>(getSymbol(&F));
381881d8778SSam Clegg       StringRef Name = F.getFnAttribute("wasm-export-name").getValueAsString();
3825be42f36SSam Clegg       Sym->setExportName(storeName(Name));
383881d8778SSam Clegg       getTargetStreamer()->emitExportName(Sym, Name);
384881d8778SSam Clegg     }
3855859a9edSDerek Schuff   }
3869647a6f7SWouter van Oortmerssen }
3879647a6f7SWouter van Oortmerssen 
emitEndOfAsmFile(Module & M)3889647a6f7SWouter van Oortmerssen void WebAssemblyAsmPrinter::emitEndOfAsmFile(Module &M) {
389c67c9cfeSPaulo Matos   // This is required to emit external declarations (like .functypes) when
390c67c9cfeSPaulo Matos   // no functions are defined in the compilation unit and therefore,
39186cc731fSAlex Bradbury   // emitDecls() is not called until now.
39286cc731fSAlex Bradbury   emitDecls(M);
3933e230d15SSam Clegg 
3942632ba6aSAndy Wingo   // When a function's address is taken, a TABLE_INDEX relocation is emitted
3952632ba6aSAndy Wingo   // against the function symbol at the use site.  However the relocation
3962632ba6aSAndy Wingo   // doesn't explicitly refer to the table.  In the future we may want to
3972632ba6aSAndy Wingo   // define a new kind of reloc against both the function and the table, so
3982632ba6aSAndy Wingo   // that the linker can see that the function symbol keeps the table alive,
3992632ba6aSAndy Wingo   // but for now manually mark the table as live.
4009647a6f7SWouter van Oortmerssen   for (const auto &F : M) {
4019647a6f7SWouter van Oortmerssen     if (!F.isIntrinsic() && F.hasAddressTaken()) {
4022632ba6aSAndy Wingo       MCSymbolWasm *FunctionTable =
4032632ba6aSAndy Wingo           WebAssembly::getOrCreateFunctionTableSymbol(OutContext, Subtarget);
4042632ba6aSAndy Wingo       OutStreamer->emitSymbolAttribute(FunctionTable, MCSA_NoDeadStrip);
4059647a6f7SWouter van Oortmerssen       break;
4069647a6f7SWouter van Oortmerssen     }
4072632ba6aSAndy Wingo   }
4082632ba6aSAndy Wingo 
4097747d703SDerek Schuff   for (const auto &G : M.globals()) {
410b2f21b14SAndy Wingo     if (!G.hasInitializer() && G.hasExternalLinkage() &&
411b2f21b14SAndy Wingo         !WebAssembly::isWasmVarAddressSpace(G.getAddressSpace()) &&
412b2f21b14SAndy Wingo         G.getValueType()->isSized()) {
413d934cb88SDan Gohman       uint16_t Size = M.getDataLayout().getTypeAllocSize(G.getValueType());
414d934cb88SDan Gohman       OutStreamer->emitELFSize(getSymbol(&G),
415d934cb88SDan Gohman                                MCConstantExpr::create(Size, OutContext));
4167747d703SDerek Schuff     }
4177747d703SDerek Schuff   }
418cfd44a2eSSam Clegg 
419cfd44a2eSSam Clegg   if (const NamedMDNode *Named = M.getNamedMetadata("wasm.custom_sections")) {
420cfd44a2eSSam Clegg     for (const Metadata *MD : Named->operands()) {
42118c56a07SHeejin Ahn       const auto *Tuple = dyn_cast<MDTuple>(MD);
422cfd44a2eSSam Clegg       if (!Tuple || Tuple->getNumOperands() != 2)
423cfd44a2eSSam Clegg         continue;
424cfd44a2eSSam Clegg       const MDString *Name = dyn_cast<MDString>(Tuple->getOperand(0));
425cfd44a2eSSam Clegg       const MDString *Contents = dyn_cast<MDString>(Tuple->getOperand(1));
426cfd44a2eSSam Clegg       if (!Name || !Contents)
427cfd44a2eSSam Clegg         continue;
428cfd44a2eSSam Clegg 
42915d82c62SFangrui Song       OutStreamer->pushSection();
430cfd44a2eSSam Clegg       std::string SectionName = (".custom_section." + Name->getString()).str();
43118c56a07SHeejin Ahn       MCSectionWasm *MySection =
432cfd44a2eSSam Clegg           OutContext.getWasmSection(SectionName, SectionKind::getMetadata());
433adf4142fSFangrui Song       OutStreamer->switchSection(MySection);
434a55daa14SFangrui Song       OutStreamer->emitBytes(Contents->getString());
43515d82c62SFangrui Song       OutStreamer->popSection();
436cfd44a2eSSam Clegg     }
437cfd44a2eSSam Clegg   }
438cbda16ebSThomas Lively 
439c6795e07SThomas Lively   EmitProducerInfo(M);
4403f34e1b8SThomas Lively   EmitTargetFeatures(M);
441c6795e07SThomas Lively }
442c6795e07SThomas Lively 
EmitProducerInfo(Module & M)443c6795e07SThomas Lively void WebAssemblyAsmPrinter::EmitProducerInfo(Module &M) {
444c6795e07SThomas Lively   llvm::SmallVector<std::pair<std::string, std::string>, 4> Languages;
445c6795e07SThomas Lively   if (const NamedMDNode *Debug = M.getNamedMetadata("llvm.dbg.cu")) {
446c6795e07SThomas Lively     llvm::SmallSet<StringRef, 4> SeenLanguages;
44718c56a07SHeejin Ahn     for (size_t I = 0, E = Debug->getNumOperands(); I < E; ++I) {
44818c56a07SHeejin Ahn       const auto *CU = cast<DICompileUnit>(Debug->getOperand(I));
449c6795e07SThomas Lively       StringRef Language = dwarf::LanguageString(CU->getSourceLanguage());
450c6795e07SThomas Lively       Language.consume_front("DW_LANG_");
451c6795e07SThomas Lively       if (SeenLanguages.insert(Language).second)
452c6795e07SThomas Lively         Languages.emplace_back(Language.str(), "");
453c6795e07SThomas Lively     }
454c6795e07SThomas Lively   }
455c6795e07SThomas Lively 
456c6795e07SThomas Lively   llvm::SmallVector<std::pair<std::string, std::string>, 4> Tools;
457cbda16ebSThomas Lively   if (const NamedMDNode *Ident = M.getNamedMetadata("llvm.ident")) {
458cbda16ebSThomas Lively     llvm::SmallSet<StringRef, 4> SeenTools;
45918c56a07SHeejin Ahn     for (size_t I = 0, E = Ident->getNumOperands(); I < E; ++I) {
46018c56a07SHeejin Ahn       const auto *S = cast<MDString>(Ident->getOperand(I)->getOperand(0));
461cbda16ebSThomas Lively       std::pair<StringRef, StringRef> Field = S->getString().split("version");
462cbda16ebSThomas Lively       StringRef Name = Field.first.trim();
463cbda16ebSThomas Lively       StringRef Version = Field.second.trim();
464c6795e07SThomas Lively       if (SeenTools.insert(Name).second)
465c6795e07SThomas Lively         Tools.emplace_back(Name.str(), Version.str());
466cbda16ebSThomas Lively     }
467c6795e07SThomas Lively   }
468c6795e07SThomas Lively 
469c6795e07SThomas Lively   int FieldCount = int(!Languages.empty()) + int(!Tools.empty());
470c6795e07SThomas Lively   if (FieldCount != 0) {
471cbda16ebSThomas Lively     MCSectionWasm *Producers = OutContext.getWasmSection(
472cbda16ebSThomas Lively         ".custom_section.producers", SectionKind::getMetadata());
47315d82c62SFangrui Song     OutStreamer->pushSection();
474adf4142fSFangrui Song     OutStreamer->switchSection(Producers);
4750bc77a0fSFangrui Song     OutStreamer->emitULEB128IntValue(FieldCount);
476c6795e07SThomas Lively     for (auto &Producers : {std::make_pair("language", &Languages),
477c6795e07SThomas Lively             std::make_pair("processed-by", &Tools)}) {
478c6795e07SThomas Lively       if (Producers.second->empty())
479c6795e07SThomas Lively         continue;
4800bc77a0fSFangrui Song       OutStreamer->emitULEB128IntValue(strlen(Producers.first));
481a55daa14SFangrui Song       OutStreamer->emitBytes(Producers.first);
4820bc77a0fSFangrui Song       OutStreamer->emitULEB128IntValue(Producers.second->size());
483c6795e07SThomas Lively       for (auto &Producer : *Producers.second) {
4840bc77a0fSFangrui Song         OutStreamer->emitULEB128IntValue(Producer.first.size());
485a55daa14SFangrui Song         OutStreamer->emitBytes(Producer.first);
4860bc77a0fSFangrui Song         OutStreamer->emitULEB128IntValue(Producer.second.size());
487a55daa14SFangrui Song         OutStreamer->emitBytes(Producer.second);
488c6795e07SThomas Lively       }
489cbda16ebSThomas Lively     }
49015d82c62SFangrui Song     OutStreamer->popSection();
491cbda16ebSThomas Lively   }
4925cf64739SDan Gohman }
4935859a9edSDerek Schuff 
EmitTargetFeatures(Module & M)4943f34e1b8SThomas Lively void WebAssemblyAsmPrinter::EmitTargetFeatures(Module &M) {
495f6f4f843SThomas Lively   struct FeatureEntry {
496f6f4f843SThomas Lively     uint8_t Prefix;
497a1ae9566SThomas Lively     std::string Name;
498f6f4f843SThomas Lively   };
499f6f4f843SThomas Lively 
5003f34e1b8SThomas Lively   // Read target features and linkage policies from module metadata
501f6f4f843SThomas Lively   SmallVector<FeatureEntry, 4> EmittedFeatures;
502a1ae9566SThomas Lively   auto EmitFeature = [&](std::string Feature) {
503a1ae9566SThomas Lively     std::string MDKey = (StringRef("wasm-feature-") + Feature).str();
5043f34e1b8SThomas Lively     Metadata *Policy = M.getModuleFlag(MDKey);
5053f34e1b8SThomas Lively     if (Policy == nullptr)
506a1ae9566SThomas Lively       return;
5073f34e1b8SThomas Lively 
508f6f4f843SThomas Lively     FeatureEntry Entry;
5093f34e1b8SThomas Lively     Entry.Prefix = 0;
510a1ae9566SThomas Lively     Entry.Name = Feature;
5113f34e1b8SThomas Lively 
5123f34e1b8SThomas Lively     if (auto *MD = cast<ConstantAsMetadata>(Policy))
5133f34e1b8SThomas Lively       if (auto *I = cast<ConstantInt>(MD->getValue()))
5143f34e1b8SThomas Lively         Entry.Prefix = I->getZExtValue();
5153f34e1b8SThomas Lively 
5163f34e1b8SThomas Lively     // Silently ignore invalid metadata
5173f34e1b8SThomas Lively     if (Entry.Prefix != wasm::WASM_FEATURE_PREFIX_USED &&
5183f34e1b8SThomas Lively         Entry.Prefix != wasm::WASM_FEATURE_PREFIX_REQUIRED &&
5193f34e1b8SThomas Lively         Entry.Prefix != wasm::WASM_FEATURE_PREFIX_DISALLOWED)
520a1ae9566SThomas Lively       return;
5213f34e1b8SThomas Lively 
522f6f4f843SThomas Lively     EmittedFeatures.push_back(Entry);
523a1ae9566SThomas Lively   };
524a1ae9566SThomas Lively 
525a1ae9566SThomas Lively   for (const SubtargetFeatureKV &KV : WebAssemblyFeatureKV) {
526a1ae9566SThomas Lively     EmitFeature(KV.Key);
527f6f4f843SThomas Lively   }
528a1ae9566SThomas Lively   // This pseudo-feature tells the linker whether shared memory would be safe
529a1ae9566SThomas Lively   EmitFeature("shared-mem");
5303f34e1b8SThomas Lively 
5315694dbccSWouter van Oortmerssen   // This is an "architecture", not a "feature", but we emit it as such for
5325694dbccSWouter van Oortmerssen   // the benefit of tools like Binaryen and consistency with other producers.
5335694dbccSWouter van Oortmerssen   // FIXME: Subtarget is null here, so can't Subtarget->hasAddr64() ?
534a8c318b5SNikita Popov   if (M.getDataLayout().getPointerSize() == 8) {
5355694dbccSWouter van Oortmerssen     // Can't use EmitFeature since "wasm-feature-memory64" is not a module
5365694dbccSWouter van Oortmerssen     // flag.
5375694dbccSWouter van Oortmerssen     EmittedFeatures.push_back({wasm::WASM_FEATURE_PREFIX_USED, "memory64"});
5385694dbccSWouter van Oortmerssen   }
5395694dbccSWouter van Oortmerssen 
5403f34e1b8SThomas Lively   if (EmittedFeatures.size() == 0)
5413f34e1b8SThomas Lively     return;
542f6f4f843SThomas Lively 
543f6f4f843SThomas Lively   // Emit features and linkage policies into the "target_features" section
544f6f4f843SThomas Lively   MCSectionWasm *FeaturesSection = OutContext.getWasmSection(
545f6f4f843SThomas Lively       ".custom_section.target_features", SectionKind::getMetadata());
54615d82c62SFangrui Song   OutStreamer->pushSection();
547adf4142fSFangrui Song   OutStreamer->switchSection(FeaturesSection);
548f6f4f843SThomas Lively 
5490bc77a0fSFangrui Song   OutStreamer->emitULEB128IntValue(EmittedFeatures.size());
550f6f4f843SThomas Lively   for (auto &F : EmittedFeatures) {
55177497103SFangrui Song     OutStreamer->emitIntValue(F.Prefix, 1);
5520bc77a0fSFangrui Song     OutStreamer->emitULEB128IntValue(F.Name.size());
553a55daa14SFangrui Song     OutStreamer->emitBytes(F.Name);
554f6f4f843SThomas Lively   }
555f6f4f843SThomas Lively 
55615d82c62SFangrui Song   OutStreamer->popSection();
557f6f4f843SThomas Lively }
558f6f4f843SThomas Lively 
emitConstantPool()5591d49eb00SFangrui Song void WebAssemblyAsmPrinter::emitConstantPool() {
56086cc731fSAlex Bradbury   emitDecls(*MMI->getModule());
5615859a9edSDerek Schuff   assert(MF->getConstantPool()->getConstants().empty() &&
5625859a9edSDerek Schuff          "WebAssembly disables constant pools");
5635859a9edSDerek Schuff }
5645859a9edSDerek Schuff 
emitJumpTableInfo()5651d49eb00SFangrui Song void WebAssemblyAsmPrinter::emitJumpTableInfo() {
5665859a9edSDerek Schuff   // Nothing to do; jump tables are incorporated into the instruction stream.
5675859a9edSDerek Schuff }
5685859a9edSDerek Schuff 
emitFunctionBodyStart()5690dce409cSFangrui Song void WebAssemblyAsmPrinter::emitFunctionBodyStart() {
57021109249SDavid Blaikie   const Function &F = MF->getFunction();
57177a7a380SDerek Schuff   SmallVector<MVT, 1> ResultVTs;
57277a7a380SDerek Schuff   SmallVector<MVT, 4> ParamVTs;
57308670d43SYuta Saito   computeSignatureVTs(F.getFunctionType(), &F, F, TM, ParamVTs, ResultVTs);
57408670d43SYuta Saito 
57518c56a07SHeejin Ahn   auto Signature = signatureFromMVTs(ResultVTs, ParamVTs);
57677a7a380SDerek Schuff   auto *WasmSym = cast<MCSymbolWasm>(CurrentFnSym);
57777a7a380SDerek Schuff   WasmSym->setSignature(Signature.get());
57877a7a380SDerek Schuff   addSignature(std::move(Signature));
57921d45a2cSHeejin Ahn   WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
58077a7a380SDerek Schuff 
58149482f82SWouter van Oortmerssen   getTargetStreamer()->emitFunctionType(WasmSym);
582c64d7655SDerek Schuff 
583c64d7655SDerek Schuff   // Emit the function index.
584c64d7655SDerek Schuff   if (MDNode *Idx = F.getMetadata("wasm.index")) {
585c64d7655SDerek Schuff     assert(Idx->getNumOperands() == 1);
586c64d7655SDerek Schuff 
587c64d7655SDerek Schuff     getTargetStreamer()->emitIndIdx(AsmPrinter::lowerConstant(
588c64d7655SDerek Schuff         cast<ConstantAsMetadata>(Idx->getOperand(0))->getValue()));
589c64d7655SDerek Schuff   }
590c64d7655SDerek Schuff 
59149482f82SWouter van Oortmerssen   SmallVector<wasm::ValType, 16> Locals;
59218c56a07SHeejin Ahn   valTypesFromMVTs(MFI->getLocals(), Locals);
59349482f82SWouter van Oortmerssen   getTargetStreamer()->emitLocal(Locals);
5941d20a5e9SJF Bastien 
5950dce409cSFangrui Song   AsmPrinter::emitFunctionBodyStart();
596e51c058eSDan Gohman }
597e51c058eSDan Gohman 
emitInstruction(const MachineInstr * MI)598bcd24b2dSFangrui Song void WebAssemblyAsmPrinter::emitInstruction(const MachineInstr *MI) {
599d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "EmitInstruction: " << *MI << '\n');
600*3e0bf1c7SDavid Green   WebAssembly_MC::verifyInstructionPredicates(MI->getOpcode(),
601*3e0bf1c7SDavid Green                                               Subtarget->getFeatureBits());
602b9073fb2SJF Bastien 
603e51c058eSDan Gohman   switch (MI->getOpcode()) {
6040ff82ac1SThomas Lively   case WebAssembly::ARGUMENT_i32:
6050ff82ac1SThomas Lively   case WebAssembly::ARGUMENT_i32_S:
6060ff82ac1SThomas Lively   case WebAssembly::ARGUMENT_i64:
6070ff82ac1SThomas Lively   case WebAssembly::ARGUMENT_i64_S:
6080ff82ac1SThomas Lively   case WebAssembly::ARGUMENT_f32:
6090ff82ac1SThomas Lively   case WebAssembly::ARGUMENT_f32_S:
6100ff82ac1SThomas Lively   case WebAssembly::ARGUMENT_f64:
6110ff82ac1SThomas Lively   case WebAssembly::ARGUMENT_f64_S:
61239bf39f3SDerek Schuff   case WebAssembly::ARGUMENT_v16i8:
6138a9cb242SWouter van Oortmerssen   case WebAssembly::ARGUMENT_v16i8_S:
61439bf39f3SDerek Schuff   case WebAssembly::ARGUMENT_v8i16:
6158a9cb242SWouter van Oortmerssen   case WebAssembly::ARGUMENT_v8i16_S:
61639bf39f3SDerek Schuff   case WebAssembly::ARGUMENT_v4i32:
6178a9cb242SWouter van Oortmerssen   case WebAssembly::ARGUMENT_v4i32_S:
61851ed131eSDerek Schuff   case WebAssembly::ARGUMENT_v2i64:
6198a9cb242SWouter van Oortmerssen   case WebAssembly::ARGUMENT_v2i64_S:
62039bf39f3SDerek Schuff   case WebAssembly::ARGUMENT_v4f32:
6218a9cb242SWouter van Oortmerssen   case WebAssembly::ARGUMENT_v4f32_S:
62251ed131eSDerek Schuff   case WebAssembly::ARGUMENT_v2f64:
6238a9cb242SWouter van Oortmerssen   case WebAssembly::ARGUMENT_v2f64_S:
624cf4748f1SDan Gohman     // These represent values which are live into the function entry, so there's
625cf4748f1SDan Gohman     // no instruction to emit.
626e51c058eSDan Gohman     break;
62700f9e5aaSThomas Lively   case WebAssembly::FALLTHROUGH_RETURN: {
628b7c2400fSDan Gohman     // These instructions represent the implicit return at the end of a
62900f9e5aaSThomas Lively     // function body.
630b7c2400fSDan Gohman     if (isVerbose()) {
63100f9e5aaSThomas Lively       OutStreamer->AddComment("fallthrough-return");
63215d82c62SFangrui Song       OutStreamer->addBlankLine();
633b7c2400fSDan Gohman     }
634b7c2400fSDan Gohman     break;
635b7c2400fSDan Gohman   }
63655146585SHeejin Ahn   case WebAssembly::COMPILER_FENCE:
63755146585SHeejin Ahn     // This is a compiler barrier that prevents instruction reordering during
63855146585SHeejin Ahn     // backend compilation, and should not be emitted.
63955146585SHeejin Ahn     break;
640e51c058eSDan Gohman   default: {
641cf4748f1SDan Gohman     WebAssemblyMCInstLower MCInstLowering(OutContext, *this);
642cf4748f1SDan Gohman     MCInst TmpInst;
64318c56a07SHeejin Ahn     MCInstLowering.lower(MI, TmpInst);
644cf4748f1SDan Gohman     EmitToStreamer(*OutStreamer, TmpInst);
645e51c058eSDan Gohman     break;
646600aee98SJF Bastien   }
647e51c058eSDan Gohman   }
648b9073fb2SJF Bastien }
649b9073fb2SJF Bastien 
PrintAsmOperand(const MachineInstr * MI,unsigned OpNo,const char * ExtraCode,raw_ostream & OS)650f19ed562SDan Gohman bool WebAssemblyAsmPrinter::PrintAsmOperand(const MachineInstr *MI,
6515277b3ffSNick Desaulniers                                             unsigned OpNo,
652f19ed562SDan Gohman                                             const char *ExtraCode,
653f19ed562SDan Gohman                                             raw_ostream &OS) {
65430a42bf5SDan Gohman   // First try the generic code, which knows about modifiers like 'c' and 'n'.
6555277b3ffSNick Desaulniers   if (!AsmPrinter::PrintAsmOperand(MI, OpNo, ExtraCode, OS))
65630a42bf5SDan Gohman     return false;
65730a42bf5SDan Gohman 
658f19ed562SDan Gohman   if (!ExtraCode) {
659f19ed562SDan Gohman     const MachineOperand &MO = MI->getOperand(OpNo);
66030a42bf5SDan Gohman     switch (MO.getType()) {
66130a42bf5SDan Gohman     case MachineOperand::MO_Immediate:
662f19ed562SDan Gohman       OS << MO.getImm();
66330a42bf5SDan Gohman       return false;
66430a42bf5SDan Gohman     case MachineOperand::MO_Register:
6658a9cb242SWouter van Oortmerssen       // FIXME: only opcode that still contains registers, as required by
6668a9cb242SWouter van Oortmerssen       // MachineInstr::getDebugVariable().
6678a9cb242SWouter van Oortmerssen       assert(MI->getOpcode() == WebAssembly::INLINEASM);
668f19ed562SDan Gohman       OS << regToString(MO);
669f19ed562SDan Gohman       return false;
67030a42bf5SDan Gohman     case MachineOperand::MO_GlobalAddress:
6717ab164c4SNick Desaulniers       PrintSymbolOperand(MO, OS);
67230a42bf5SDan Gohman       return false;
67330a42bf5SDan Gohman     case MachineOperand::MO_ExternalSymbol:
67430a42bf5SDan Gohman       GetExternalSymbolSymbol(MO.getSymbolName())->print(OS, MAI);
67530a42bf5SDan Gohman       printOffset(MO.getOffset(), OS);
67630a42bf5SDan Gohman       return false;
67730a42bf5SDan Gohman     case MachineOperand::MO_MachineBasicBlock:
67830a42bf5SDan Gohman       MO.getMBB()->getSymbol()->print(OS, MAI);
67930a42bf5SDan Gohman       return false;
68030a42bf5SDan Gohman     default:
68130a42bf5SDan Gohman       break;
68230a42bf5SDan Gohman     }
683f19ed562SDan Gohman   }
684f19ed562SDan Gohman 
68530a42bf5SDan Gohman   return true;
686f19ed562SDan Gohman }
687f19ed562SDan Gohman 
PrintAsmMemoryOperand(const MachineInstr * MI,unsigned OpNo,const char * ExtraCode,raw_ostream & OS)688f19ed562SDan Gohman bool WebAssemblyAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
689f19ed562SDan Gohman                                                   unsigned OpNo,
690f19ed562SDan Gohman                                                   const char *ExtraCode,
691f19ed562SDan Gohman                                                   raw_ostream &OS) {
692b465aa05SDan Gohman   // The current approach to inline asm is that "r" constraints are expressed
693b465aa05SDan Gohman   // as local indices, rather than values on the operand stack. This simplifies
694b465aa05SDan Gohman   // using "r" as it eliminates the need to push and pop the values in a
695b465aa05SDan Gohman   // particular order, however it also makes it impossible to have an "m"
696b465aa05SDan Gohman   // constraint. So we don't support it.
697f19ed562SDan Gohman 
6985277b3ffSNick Desaulniers   return AsmPrinter::PrintAsmMemoryOperand(MI, OpNo, ExtraCode, OS);
699f19ed562SDan Gohman }
700f19ed562SDan Gohman 
701b9073fb2SJF Bastien // Force static initialization.
LLVMInitializeWebAssemblyAsmPrinter()7020dbcb363STom Stellard extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeWebAssemblyAsmPrinter() {
703f42454b9SMehdi Amini   RegisterAsmPrinter<WebAssemblyAsmPrinter> X(getTheWebAssemblyTarget32());
704f42454b9SMehdi Amini   RegisterAsmPrinter<WebAssemblyAsmPrinter> Y(getTheWebAssemblyTarget64());
705b9073fb2SJF Bastien }
706