1//===-- WebAssemblyAsmPrinter.cpp - WebAssembly LLVM assembly writer ------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
10/// This file contains a printer that converts from our internal
11/// representation of machine-dependent LLVM code to the WebAssembly assembly
12/// language.
13///
14//===----------------------------------------------------------------------===//
15
16#include "WebAssemblyAsmPrinter.h"
17#include "MCTargetDesc/WebAssemblyMCAsmInfo.h"
18#include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
19#include "MCTargetDesc/WebAssemblyTargetStreamer.h"
20#include "TargetInfo/WebAssemblyTargetInfo.h"
21#include "Utils/WebAssemblyTypeUtilities.h"
22#include "WebAssembly.h"
23#include "WebAssemblyMCInstLower.h"
24#include "WebAssemblyMachineFunctionInfo.h"
25#include "WebAssemblyRegisterInfo.h"
26#include "WebAssemblyRuntimeLibcallSignatures.h"
27#include "WebAssemblyTargetMachine.h"
28#include "WebAssemblyUtilities.h"
29#include "llvm/ADT/MapVector.h"
30#include "llvm/ADT/SmallSet.h"
31#include "llvm/ADT/StringExtras.h"
32#include "llvm/Analysis/ValueTracking.h"
33#include "llvm/BinaryFormat/Wasm.h"
34#include "llvm/CodeGen/Analysis.h"
35#include "llvm/CodeGen/AsmPrinter.h"
36#include "llvm/CodeGen/AsmPrinterAnalysis.h"
37#include "llvm/CodeGen/MachineConstantPool.h"
38#include "llvm/CodeGen/MachineFunction.h"
39#include "llvm/CodeGen/MachineFunctionAnalysisManager.h"
40#include "llvm/CodeGen/MachineInstr.h"
41#include "llvm/CodeGen/MachineModuleInfoImpls.h"
42#include "llvm/CodeGen/MachinePassManager.h"
43#include "llvm/IR/Analysis.h"
44#include "llvm/IR/DataLayout.h"
45#include "llvm/IR/DebugInfoMetadata.h"
46#include "llvm/IR/GlobalVariable.h"
47#include "llvm/IR/Metadata.h"
48#include "llvm/IR/Module.h"
49#include "llvm/IR/PassManager.h"
50#include "llvm/MC/MCContext.h"
51#include "llvm/MC/MCSectionWasm.h"
52#include "llvm/MC/MCStreamer.h"
53#include "llvm/MC/MCSymbol.h"
54#include "llvm/MC/MCSymbolWasm.h"
55#include "llvm/MC/TargetRegistry.h"
56#include "llvm/Support/Compiler.h"
57#include "llvm/Support/Debug.h"
58#include "llvm/Support/raw_ostream.h"
59
60using namespace llvm;
61
62#define DEBUG_TYPE "asm-printer"
63
64extern cl::opt<bool> WasmKeepRegisters;
65
66//===----------------------------------------------------------------------===//
67// Helpers.
68//===----------------------------------------------------------------------===//
69
70MVT WebAssemblyAsmPrinter::getRegType(unsigned RegNo) const {
71 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
72 const TargetRegisterClass *TRC = MRI->getRegClass(Reg: RegNo);
73 for (MVT T : {MVT::i32, MVT::i64, MVT::f32, MVT::f64, MVT::v16i8, MVT::v8i16,
74 MVT::v4i32, MVT::v2i64, MVT::v4f32, MVT::v2f64, MVT::v8f16})
75 if (TRI->isTypeLegalForClass(RC: *TRC, T))
76 return T;
77 LLVM_DEBUG(errs() << "Unknown type for register number: " << RegNo);
78 llvm_unreachable("Unknown register type");
79 return MVT::Other;
80}
81
82std::string WebAssemblyAsmPrinter::regToString(const MachineOperand &MO) {
83 Register RegNo = MO.getReg();
84 assert(RegNo.isVirtual() &&
85 "Unlowered physical register encountered during assembly printing");
86 assert(!MFI->isVRegStackified(RegNo));
87 unsigned WAReg = MFI->getWAReg(VReg: RegNo);
88 assert(WAReg != WebAssembly::UnusedReg);
89 return '$' + utostr(X: WAReg);
90}
91
92WebAssemblyTargetStreamer *WebAssemblyAsmPrinter::getTargetStreamer() {
93 MCTargetStreamer *TS = OutStreamer->getTargetStreamer();
94 return static_cast<WebAssemblyTargetStreamer *>(TS);
95}
96
97// Emscripten exception handling helpers
98//
99// This converts invoke names generated by LowerEmscriptenEHSjLj to real names
100// that are expected by JavaScript glue code. The invoke names generated by
101// Emscripten JS glue code are based on their argument and return types; for
102// example, for a function that takes an i32 and returns nothing, it is
103// 'invoke_vi'. But the format of invoke generated by LowerEmscriptenEHSjLj pass
104// contains a mangled string generated from their IR types, for example,
105// "__invoke_void_%struct.mystruct*_int", because final wasm types are not
106// available in the IR pass. So we convert those names to the form that
107// Emscripten JS code expects.
108//
109// Refer to LowerEmscriptenEHSjLj pass for more details.
110
111// Returns true if the given function name is an invoke name generated by
112// LowerEmscriptenEHSjLj pass.
113static bool isEmscriptenInvokeName(StringRef Name) {
114 if (Name.front() == '"' && Name.back() == '"')
115 Name = Name.substr(Start: 1, N: Name.size() - 2);
116 return Name.starts_with(Prefix: "__invoke_");
117}
118
119// Returns a character that represents the given wasm value type in invoke
120// signatures.
121static char getInvokeSig(wasm::ValType VT) {
122 switch (VT) {
123 case wasm::ValType::I32:
124 return 'i';
125 case wasm::ValType::I64:
126 return 'j';
127 case wasm::ValType::F32:
128 return 'f';
129 case wasm::ValType::F64:
130 return 'd';
131 case wasm::ValType::V128:
132 return 'V';
133 case wasm::ValType::FUNCREF:
134 return 'F';
135 case wasm::ValType::EXTERNREF:
136 return 'X';
137 case wasm::ValType::EXNREF:
138 return 'E';
139 default:
140 llvm_unreachable("Unhandled wasm::ValType enum");
141 }
142}
143
144// Given the wasm signature, generate the invoke name in the format JS glue code
145// expects.
146static std::string getEmscriptenInvokeSymbolName(wasm::WasmSignature *Sig) {
147 assert(Sig->Returns.size() <= 1);
148 std::string Ret = "invoke_";
149 if (!Sig->Returns.empty())
150 for (auto VT : Sig->Returns)
151 Ret += getInvokeSig(VT);
152 else
153 Ret += 'v';
154 // Invokes' first argument is a pointer to the original function, so skip it
155 for (unsigned I = 1, E = Sig->Params.size(); I < E; I++)
156 Ret += getInvokeSig(VT: Sig->Params[I]);
157 return Ret;
158}
159
160//===----------------------------------------------------------------------===//
161// WebAssemblyAsmPrinter Implementation.
162//===----------------------------------------------------------------------===//
163
164MCSymbolWasm *WebAssemblyAsmPrinter::getMCSymbolForFunction(
165 const Function *F, wasm::WasmSignature *Sig, bool &InvokeDetected) {
166 MCSymbolWasm *WasmSym = nullptr;
167
168 // Prefer the "exception-model" module flag, else the TargetOptions default.
169 ExceptionHandling EM = F->getParent()->getExceptionModel();
170 if (EM == ExceptionHandling::Default)
171 EM = TM.getExceptionModel();
172 const bool EnableEmEH =
173 EM == ExceptionHandling::Emscripten || WebAssembly::WasmEnableEmSjLj;
174 if (EnableEmEH && isEmscriptenInvokeName(Name: F->getName())) {
175 assert(Sig);
176 InvokeDetected = true;
177 if (Sig->Returns.size() > 1) {
178 std::string Msg =
179 "Emscripten EH/SjLj does not support multivalue returns: " +
180 std::string(F->getName()) + ": " +
181 WebAssembly::signatureToString(Sig);
182 report_fatal_error(reason: Twine(Msg));
183 }
184 WasmSym = static_cast<MCSymbolWasm *>(
185 GetExternalSymbolSymbol(Sym: getEmscriptenInvokeSymbolName(Sig)));
186 } else {
187 WasmSym = static_cast<MCSymbolWasm *>(getSymbol(GV: F));
188 }
189 return WasmSym;
190}
191
192void WebAssemblyAsmPrinter::emitGlobalVariable(const GlobalVariable *GV) {
193 if (GV->hasAttribute(Kind: "wasm-import-module") ||
194 GV->hasAttribute(Kind: "wasm-import-name")) {
195 if (!GV->isDeclaration()) {
196 OutContext.reportError(L: SMLoc(), Msg: "definition of global '" + GV->getName() +
197 "' cannot have import attribute");
198 return;
199 }
200 if (!WebAssembly::isWasmVarAddressSpace(AS: GV->getAddressSpace())) {
201 OutContext.reportError(L: SMLoc(),
202 Msg: "imported global '" + GV->getName() +
203 "' must be in a wasm variable address space");
204 return;
205 }
206 }
207 if (!WebAssembly::isWasmVarAddressSpace(AS: GV->getAddressSpace())) {
208 if (GV->hasAttribute(Kind: "wasm-export-name")) {
209 auto *Sym = static_cast<MCSymbolWasm *>(getSymbol(GV));
210 StringRef Name = GV->getAttribute(Kind: "wasm-export-name").getValueAsString();
211 Sym->setExportName(OutContext.allocateString(s: Name));
212 getTargetStreamer()->emitExportName(Sym, ExportName: Name);
213 }
214 AsmPrinter::emitGlobalVariable(GV);
215 return;
216 }
217
218 assert(!GV->isThreadLocal());
219 auto *Sym = static_cast<MCSymbolWasm *>(getSymbol(GV));
220 if (!Sym->getType()) {
221 SmallVector<MVT, 1> VTs;
222 Type *GlobalVT = GV->getValueType();
223 // Function-specific subtargets are not needed here: WebAssembly
224 // coalesces features before isel, so use the TargetMachine's
225 // module-wide subtarget to compute legal value types.
226 auto &WasmTM = static_cast<const WebAssemblyTargetMachine &>(TM);
227 const WebAssemblySubtarget *ST = WasmTM.getSubtargetImpl(
228 CPU: WasmTM.getTargetCPU(), FS: WasmTM.getTargetFeatureString(),
229 ABIName: WasmTM.getTargetABIName(M: *GV->getParent()));
230 const WebAssemblyTargetLowering &TLI = *ST->getTargetLowering();
231 computeLegalValueVTs(TLI, Ctx&: GV->getParent()->getContext(),
232 DL: GV->getDataLayout(), Ty: GlobalVT, ValueVTs&: VTs);
233
234 WebAssembly::wasmSymbolSetType(Sym, GlobalVT, VTs,
235 /*Mutable=*/!GV->isConstant());
236 }
237
238 emitVisibility(Sym, Visibility: GV->getVisibility(), IsDefinition: !GV->isDeclaration());
239 emitSymbolType(Sym);
240 if (GV->isDeclaration()) {
241 if (GV->hasAttribute(Kind: "wasm-import-module")) {
242 StringRef ImportModule =
243 GV->getAttribute(Kind: "wasm-import-module").getValueAsString();
244 Sym->setImportModule(OutContext.allocateString(s: ImportModule));
245 getTargetStreamer()->emitImportModule(Sym, ImportModule);
246 }
247 if (GV->hasAttribute(Kind: "wasm-import-name")) {
248 StringRef ImportName =
249 GV->getAttribute(Kind: "wasm-import-name").getValueAsString();
250 Sym->setImportName(OutContext.allocateString(s: ImportName));
251 getTargetStreamer()->emitImportName(Sym, ImportName);
252 }
253 }
254 if (GV->hasInitializer()) {
255 assert(getSymbolPreferLocal(*GV) == Sym);
256 emitLinkage(GV, GVSym: Sym);
257 OutStreamer->emitLabel(Symbol: Sym);
258 if (GV->hasAttribute(Kind: "wasm-export-name")) {
259 StringRef ExportName =
260 GV->getAttribute(Kind: "wasm-export-name").getValueAsString();
261 Sym->setExportName(OutContext.allocateString(s: ExportName));
262 getTargetStreamer()->emitExportName(Sym, ExportName);
263 }
264 // TODO: Actually emit the initializer value. Otherwise the global has the
265 // default value for its type (0, ref.null, etc).
266 OutStreamer->addBlankLine();
267 }
268}
269
270MCSymbol *WebAssemblyAsmPrinter::getOrCreateWasmSymbol(StringRef Name) {
271 auto *WasmSym = static_cast<MCSymbolWasm *>(GetExternalSymbolSymbol(Sym: Name));
272 // May be called multiple times, so early out.
273 if (WasmSym->getType())
274 return WasmSym;
275
276 const WebAssemblySubtarget &Subtarget = getSubtarget();
277
278 // Except for certain known symbols, all symbols used by CodeGen are
279 // functions. It's OK to hardcode knowledge of specific symbols here; this
280 // method is precisely there for fetching the signatures of known
281 // Clang-provided symbols.
282 if (Name == "__stack_pointer" || Name == "__tls_base" ||
283 Name == "__memory_base" || Name == "__table_base" ||
284 Name == "__tls_size" || Name == "__tls_align") {
285 bool Mutable = Name == "__stack_pointer" || Name == "__tls_base";
286 WasmSym->setType(wasm::WASM_SYMBOL_TYPE_GLOBAL);
287 WasmSym->setGlobalType(wasm::WasmGlobalType{
288 .Type: uint8_t(Subtarget.hasAddr64() ? wasm::WASM_TYPE_I64
289 : wasm::WASM_TYPE_I32),
290 .Mutable: Mutable});
291 return WasmSym;
292 }
293
294 if (Name.starts_with(Prefix: "GCC_except_table")) {
295 WasmSym->setType(wasm::WASM_SYMBOL_TYPE_DATA);
296 return WasmSym;
297 }
298
299 SmallVector<wasm::ValType, 4> Returns;
300 SmallVector<wasm::ValType, 4> Params;
301 if (Name == "__cpp_exception" || Name == "__c_longjmp") {
302 WasmSym->setType(wasm::WASM_SYMBOL_TYPE_TAG);
303 WasmSym->setExternal(true);
304
305 // Currently both C++ exceptions and C longjmps have a single pointer type
306 // param. For C++ exceptions it is a pointer to an exception object, and for
307 // C longjmps it is pointer to a struct that contains a setjmp buffer and a
308 // longjmp return value. We may consider using multiple value parameters for
309 // longjmps later when multivalue support is ready.
310 wasm::ValType AddrType =
311 Subtarget.hasAddr64() ? wasm::ValType::I64 : wasm::ValType::I32;
312 Params.push_back(Elt: AddrType);
313 } else if (Name == "__wasm_get_stack_pointer" ||
314 Name == "__wasm_get_tls_base") {
315 WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
316 Returns.push_back(Elt: wasm::ValType::I32);
317 } else if (Name == "__wasm_set_stack_pointer" ||
318 Name == "__wasm_set_tls_base") {
319 WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
320 Params.push_back(Elt: wasm::ValType::I32);
321 } else { // Function symbols
322 WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
323 WebAssembly::getLibcallSignature(Subtarget, Name, Rets&: Returns, Params);
324 }
325 auto Signature = OutContext.createWasmSignature();
326 Signature->Returns = std::move(Returns);
327 Signature->Params = std::move(Params);
328 WasmSym->setSignature(Signature);
329
330 return WasmSym;
331}
332
333void WebAssemblyAsmPrinter::emitSymbolType(const MCSymbolWasm *Sym) {
334 std::optional<wasm::WasmSymbolType> WasmTy = Sym->getType();
335 if (!WasmTy)
336 return;
337
338 switch (*WasmTy) {
339 case wasm::WASM_SYMBOL_TYPE_GLOBAL:
340 getTargetStreamer()->emitGlobalType(Sym);
341 break;
342 case wasm::WASM_SYMBOL_TYPE_TAG:
343 getTargetStreamer()->emitTagType(Sym);
344 break;
345 case wasm::WASM_SYMBOL_TYPE_TABLE:
346 getTargetStreamer()->emitTableType(Sym);
347 break;
348 default:
349 break; // We only handle globals, tags and tables here
350 }
351}
352
353void WebAssemblyAsmPrinter::emitDecls(const Module &M) {
354 if (signaturesEmitted)
355 return;
356 signaturesEmitted = true;
357
358 // Normally symbols for globals get discovered as the MI gets lowered,
359 // but we need to know about them ahead of time. This will however,
360 // only find symbols that have been used. Unused symbols from globals will
361 // not be found here.
362 MachineModuleInfoWasm &MMIW = MMI->getObjFileInfo<MachineModuleInfoWasm>();
363 for (StringRef Name : MMIW.MachineSymbolsUsed) {
364 auto *WasmSym = static_cast<MCSymbolWasm *>(getOrCreateWasmSymbol(Name));
365 if (WasmSym->isFunction()) {
366 // TODO(wvo): is there any case where this overlaps with the call to
367 // emitFunctionType in the loop below?
368 getTargetStreamer()->emitFunctionType(Sym: WasmSym);
369 }
370 }
371
372 for (auto &It : OutContext.getSymbols()) {
373 // Emit .globaltype, .tagtype, or .tabletype declarations for extern
374 // declarations, i.e. those that have only been declared (but not defined)
375 // in the current module
376 auto Sym = static_cast<MCSymbolWasm *>(It.getValue().Symbol);
377 if (Sym && !Sym->isDefined())
378 emitSymbolType(Sym);
379 }
380
381 // We handle `__funcref_call_table` specially here.
382 //
383 // Unlike most table symbols, which are attached to a `GlobalVariable`
384 // this one is a directly created, freestanding MCSymbol, much like
385 // `__indirect_function_table`. However, given that the table is always
386 // identical (single element, default initialized), we declare it
387 // weak in each object, and define it here rather than in the linker.
388 //
389 // TODO: consider moving this definition elsewhere, or doing away with
390 // the table entirely (in favor of `call_ref` exclusively).
391 {
392 StringRef Name = "__funcref_call_table";
393 auto *Sym = static_cast<MCSymbolWasm *>(OutContext.lookupSymbol(Name));
394 if (Sym) {
395 if (!Sym->isFunctionTable())
396 OutContext.reportError(L: SMLoc(), Msg: "symbol is not a wasm funcref table");
397
398 // symbol is declared weak in `getOrCreateFuncrefCallTableSymbol`
399 assert(Sym->isWeak());
400 OutStreamer->emitSymbolAttribute(Symbol: Sym, Attribute: MCSA_Weak);
401
402 // Make sure we haven't already emitted it for whatever reason.
403 assert(!Sym->isDefined());
404
405 // Actually define the symbol.
406 // Confusingly enough, `emitLabel` is what "defines" a MCSymbol.
407 // Provides it a fragment, so that it `!isUndefined`
408 OutStreamer->emitLabel(Symbol: Sym);
409 // No initializer needed. Default ref.null is good
410 OutStreamer->addBlankLine();
411 }
412 }
413
414 DenseSet<MCSymbol *> InvokeSymbols;
415 for (const auto &F : M) {
416 if (F.isIntrinsic())
417 continue;
418
419 // Emit function type info for all functions. This will emit duplicate
420 // information for defined functions (which already have function type
421 // info emitted alongside their definition), but this is necessary in
422 // order to enable the single-pass WebAssemblyAsmTypeCheck to succeed.
423 SmallVector<MVT, 4> Results;
424 SmallVector<MVT, 4> Params;
425 computeSignatureVTs(Ty: F.getFunctionType(), TargetFunc: &F, ContextFunc: F, TM, Params, Results);
426 // At this point these MCSymbols may or may not have been created already
427 // and thus also contain a signature, but we need to get the signature
428 // anyway here in case it is an invoke that has not yet been created. We
429 // will discard it later if it turns out not to be necessary.
430 auto Signature = signatureFromMVTs(Ctx&: OutContext, Results, Params);
431 bool InvokeDetected = false;
432 auto *Sym = getMCSymbolForFunction(F: &F, Sig: Signature, InvokeDetected);
433
434 // Multiple functions can be mapped to the same invoke symbol. For
435 // example, two IR functions '__invoke_void_i8*' and '__invoke_void_i32'
436 // are both mapped to '__invoke_vi'. We keep them in a set once we emit an
437 // Emscripten EH symbol so we don't emit the same symbol twice.
438 if (InvokeDetected && !InvokeSymbols.insert(V: Sym).second)
439 continue;
440
441 Sym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
442 if (!Sym->getSignature()) {
443 Sym->setSignature(Signature);
444 }
445
446 getTargetStreamer()->emitFunctionType(Sym);
447
448 if (F.hasFnAttribute(Kind: "wasm-import-module")) {
449 StringRef Name =
450 F.getFnAttribute(Kind: "wasm-import-module").getValueAsString();
451 Sym->setImportModule(OutContext.allocateString(s: Name));
452 getTargetStreamer()->emitImportModule(Sym, ImportModule: Name);
453 }
454 if (F.hasFnAttribute(Kind: "wasm-import-name")) {
455 // If this is a converted Emscripten EH/SjLj symbol, we shouldn't use
456 // the original function name but the converted symbol name.
457 StringRef Name =
458 InvokeDetected
459 ? Sym->getName()
460 : F.getFnAttribute(Kind: "wasm-import-name").getValueAsString();
461 Sym->setImportName(OutContext.allocateString(s: Name));
462 getTargetStreamer()->emitImportName(Sym, ImportName: Name);
463 }
464
465 if (F.hasFnAttribute(Kind: "wasm-export-name")) {
466 auto *Sym = static_cast<MCSymbolWasm *>(getSymbol(GV: &F));
467 StringRef Name = F.getFnAttribute(Kind: "wasm-export-name").getValueAsString();
468 Sym->setExportName(OutContext.allocateString(s: Name));
469 getTargetStreamer()->emitExportName(Sym, ExportName: Name);
470 }
471 }
472}
473
474void WebAssemblyAsmPrinter::emitEndOfAsmFile(Module &M) {
475 // This is required to emit external declarations (like .functypes) when
476 // no functions are defined in the compilation unit and therefore,
477 // emitDecls() is not called until now.
478 emitDecls(M);
479
480 // When a function's address is taken, a TABLE_INDEX relocation is emitted
481 // against the function symbol at the use site. However the relocation
482 // doesn't explicitly refer to the table. In the future we may want to
483 // define a new kind of reloc against both the function and the table, so
484 // that the linker can see that the function symbol keeps the table alive,
485 // but for now manually mark the table as live.
486 for (const auto &F : M) {
487 if (!F.isIntrinsic() && F.hasAddressTaken()) {
488 MCSymbolWasm *FunctionTable =
489 WebAssembly::getOrCreateFunctionTableSymbol(Ctx&: OutContext, Subtarget);
490 OutStreamer->emitSymbolAttribute(Symbol: FunctionTable, Attribute: MCSA_NoDeadStrip);
491 break;
492 }
493 }
494
495 for (const auto &G : M.globals()) {
496 if (!G.hasInitializer() && G.hasExternalLinkage() &&
497 !WebAssembly::isWasmVarAddressSpace(AS: G.getAddressSpace()) &&
498 G.getValueType()->isSized()) {
499 uint16_t Size = G.getGlobalSize(DL: M.getDataLayout());
500 OutStreamer->emitELFSize(Symbol: getSymbol(GV: &G),
501 Value: MCConstantExpr::create(Value: Size, Ctx&: OutContext));
502 }
503 }
504
505 if (const NamedMDNode *Named = M.getNamedMetadata(Name: "wasm.custom_sections")) {
506 for (const Metadata *MD : Named->operands()) {
507 const auto *Tuple = dyn_cast<MDTuple>(Val: MD);
508 if (!Tuple || Tuple->getNumOperands() != 2)
509 continue;
510 const MDString *Name = dyn_cast<MDString>(Val: Tuple->getOperand(I: 0));
511 const MDString *Contents = dyn_cast<MDString>(Val: Tuple->getOperand(I: 1));
512 if (!Name || !Contents)
513 continue;
514
515 OutStreamer->pushSection();
516 std::string SectionName = (".custom_section." + Name->getString()).str();
517 MCSectionWasm *MySection =
518 OutContext.getWasmSection(Section: SectionName, K: SectionKind::getMetadata());
519 OutStreamer->switchSection(Section: MySection);
520 OutStreamer->emitBytes(Data: Contents->getString());
521 OutStreamer->popSection();
522 }
523 }
524
525 EmitProducerInfo(M);
526 EmitTargetFeatures(M);
527 EmitFunctionAttributes(M);
528}
529
530void WebAssemblyAsmPrinter::EmitProducerInfo(Module &M) {
531 llvm::SmallVector<std::pair<std::string, std::string>, 4> Languages;
532 if (const NamedMDNode *Debug = M.getNamedMetadata(Name: "llvm.dbg.cu")) {
533 llvm::SmallSet<StringRef, 4> SeenLanguages;
534 for (size_t I = 0, E = Debug->getNumOperands(); I < E; ++I) {
535 const auto *CU = cast<DICompileUnit>(Val: Debug->getOperand(i: I));
536 StringRef Language =
537 dwarf::LanguageString(Language: CU->getSourceLanguage().getUnversionedName());
538
539 Language.consume_front(Prefix: "DW_LANG_");
540 if (SeenLanguages.insert(V: Language).second)
541 Languages.emplace_back(Args: Language.str(), Args: "");
542 }
543 }
544
545 llvm::SmallVector<std::pair<std::string, std::string>, 4> Tools;
546 if (const NamedMDNode *Ident = M.getNamedMetadata(Name: "llvm.ident")) {
547 llvm::SmallSet<StringRef, 4> SeenTools;
548 for (size_t I = 0, E = Ident->getNumOperands(); I < E; ++I) {
549 const auto *S = cast<MDString>(Val: Ident->getOperand(i: I)->getOperand(I: 0));
550 std::pair<StringRef, StringRef> Field = S->getString().split(Separator: "version");
551 StringRef Name = Field.first.trim();
552 StringRef Version = Field.second.trim();
553 if (SeenTools.insert(V: Name).second)
554 Tools.emplace_back(Args: Name.str(), Args: Version.str());
555 }
556 }
557
558 int FieldCount = int(!Languages.empty()) + int(!Tools.empty());
559 if (FieldCount != 0) {
560 MCSectionWasm *Producers = OutContext.getWasmSection(
561 Section: ".custom_section.producers", K: SectionKind::getMetadata());
562 OutStreamer->pushSection();
563 OutStreamer->switchSection(Section: Producers);
564 OutStreamer->emitULEB128IntValue(Value: FieldCount);
565 for (auto &Producers : {std::make_pair(x: "language", y: &Languages),
566 std::make_pair(x: "processed-by", y: &Tools)}) {
567 if (Producers.second->empty())
568 continue;
569 OutStreamer->emitULEB128IntValue(Value: strlen(s: Producers.first));
570 OutStreamer->emitBytes(Data: Producers.first);
571 OutStreamer->emitULEB128IntValue(Value: Producers.second->size());
572 for (auto &Producer : *Producers.second) {
573 OutStreamer->emitULEB128IntValue(Value: Producer.first.size());
574 OutStreamer->emitBytes(Data: Producer.first);
575 OutStreamer->emitULEB128IntValue(Value: Producer.second.size());
576 OutStreamer->emitBytes(Data: Producer.second);
577 }
578 }
579 OutStreamer->popSection();
580 }
581}
582
583void WebAssemblyAsmPrinter::EmitTargetFeatures(Module &M) {
584 struct FeatureEntry {
585 uint8_t Prefix;
586 std::string Name;
587 };
588
589 // Read target features and linkage policies from module metadata
590 SmallVector<FeatureEntry, 4> EmittedFeatures;
591 auto EmitFeature = [&](std::string Feature) {
592 std::string MDKey = (StringRef("wasm-feature-") + Feature).str();
593 Metadata *Policy = M.getModuleFlag(Key: MDKey);
594 if (Policy == nullptr)
595 return;
596
597 FeatureEntry Entry;
598 Entry.Prefix = 0;
599 Entry.Name = Feature;
600
601 if (auto *MD = cast<ConstantAsMetadata>(Val: Policy))
602 if (auto *I = cast<ConstantInt>(Val: MD->getValue()))
603 Entry.Prefix = I->getZExtValue();
604
605 // Silently ignore invalid metadata
606 if (Entry.Prefix != wasm::WASM_FEATURE_PREFIX_USED &&
607 Entry.Prefix != wasm::WASM_FEATURE_PREFIX_DISALLOWED)
608 return;
609
610 EmittedFeatures.push_back(Elt: Entry);
611 };
612
613 // If we never compiled a single function, Subtarget is null.
614 if (!Subtarget) {
615 Subtarget = static_cast<WebAssemblyTargetMachine &>(TM).getSubtargetImpl(
616 CPU: TM.getTargetCPU(), FS: TM.getTargetFeatureString(), ABIName: TM.getTargetABIName(M));
617 }
618 for (const SubtargetFeatureKV &KV : Subtarget->getAllProcessorFeatures()) {
619 EmitFeature(KV.key());
620 }
621 // This pseudo-feature tells the linker whether shared memory would be safe
622 EmitFeature("shared-mem");
623
624 // This is an "architecture", not a "feature", but we emit it as such for
625 // the benefit of tools like Binaryen and consistency with other producers.
626 if (Subtarget->hasAddr64()) {
627 // Can't use EmitFeature since "wasm-feature-memory64" is not a module
628 // flag.
629 EmittedFeatures.push_back(Elt: {.Prefix: wasm::WASM_FEATURE_PREFIX_USED, .Name: "memory64"});
630 }
631
632 if (EmittedFeatures.size() == 0)
633 return;
634
635 // Emit features and linkage policies into the "target_features" section
636 MCSectionWasm *FeaturesSection = OutContext.getWasmSection(
637 Section: ".custom_section.target_features", K: SectionKind::getMetadata());
638 OutStreamer->pushSection();
639 OutStreamer->switchSection(Section: FeaturesSection);
640
641 OutStreamer->emitULEB128IntValue(Value: EmittedFeatures.size());
642 for (auto &F : EmittedFeatures) {
643 OutStreamer->emitIntValue(Value: F.Prefix, Size: 1);
644 OutStreamer->emitULEB128IntValue(Value: F.Name.size());
645 OutStreamer->emitBytes(Data: F.Name);
646 }
647
648 OutStreamer->popSection();
649}
650
651void WebAssemblyAsmPrinter::EmitFunctionAttributes(Module &M) {
652 auto V = M.getNamedGlobal(Name: "llvm.global.annotations");
653 if (!V)
654 return;
655
656 // Group all the custom attributes by name.
657 MapVector<StringRef, SmallVector<MCSymbol *, 4>> CustomSections;
658 const ConstantArray *CA = cast<ConstantArray>(Val: V->getOperand(i_nocapture: 0));
659 for (Value *Op : CA->operands()) {
660 auto *CS = cast<ConstantStruct>(Val: Op);
661 // The first field is a pointer to the annotated variable.
662 Value *AnnotatedVar = CS->getOperand(i_nocapture: 0)->stripPointerCasts();
663 // Only annotated functions are supported for now.
664 if (!isa<Function>(Val: AnnotatedVar))
665 continue;
666 auto *F = cast<Function>(Val: AnnotatedVar);
667
668 // The second field is a pointer to a global annotation string.
669 auto *GV = cast<GlobalVariable>(Val: CS->getOperand(i_nocapture: 1)->stripPointerCasts());
670 StringRef AnnotationString;
671 getConstantStringInfo(V: GV, Str&: AnnotationString);
672 auto *Sym = static_cast<MCSymbolWasm *>(getSymbol(GV: F));
673 CustomSections[AnnotationString].push_back(Elt: Sym);
674 }
675
676 // Emit a custom section for each unique attribute.
677 for (const auto &[Name, Symbols] : CustomSections) {
678 MCSectionWasm *CustomSection = OutContext.getWasmSection(
679 Section: ".custom_section.llvm.func_attr.annotate." + Name, K: SectionKind::getMetadata());
680 OutStreamer->pushSection();
681 OutStreamer->switchSection(Section: CustomSection);
682
683 for (auto &Sym : Symbols) {
684 OutStreamer->emitValue(
685 Value: MCSymbolRefExpr::create(Symbol: Sym, specifier: WebAssembly::S_FUNCINDEX, Ctx&: OutContext),
686 Size: 4);
687 }
688 OutStreamer->popSection();
689 }
690}
691
692void WebAssemblyAsmPrinter::emitConstantPool() {
693 emitDecls(M: *MMI->getModule());
694 assert(MF->getConstantPool()->getConstants().empty() &&
695 "WebAssembly disables constant pools");
696}
697
698void WebAssemblyAsmPrinter::emitJumpTableInfo() {
699 // Nothing to do; jump tables are incorporated into the instruction stream.
700}
701
702void WebAssemblyAsmPrinter::emitFunctionBodyStart() {
703 const Function &F = MF->getFunction();
704 SmallVector<MVT, 1> ResultVTs;
705 SmallVector<MVT, 4> ParamVTs;
706 computeSignatureVTs(Ty: F.getFunctionType(), TargetFunc: &F, ContextFunc: F, TM, Params&: ParamVTs, Results&: ResultVTs);
707
708 auto Signature = signatureFromMVTs(Ctx&: OutContext, Results: ResultVTs, Params: ParamVTs);
709 auto *WasmSym = static_cast<MCSymbolWasm *>(CurrentFnSym);
710 WasmSym->setSignature(Signature);
711 WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
712
713 getTargetStreamer()->emitFunctionType(Sym: WasmSym);
714
715 // Emit the function index.
716 if (MDNode *Idx = F.getMetadata(Kind: "wasm.index")) {
717 assert(Idx->getNumOperands() == 1);
718
719 getTargetStreamer()->emitIndIdx(Value: AsmPrinter::lowerConstant(
720 CV: cast<ConstantAsMetadata>(Val: Idx->getOperand(I: 0))->getValue()));
721 }
722
723 SmallVector<wasm::ValType, 16> Locals;
724 valTypesFromMVTs(In: MFI->getLocals(), Out&: Locals);
725 getTargetStreamer()->emitLocal(Types: Locals);
726
727 AsmPrinter::emitFunctionBodyStart();
728}
729
730void WebAssemblyAsmPrinter::emitInstruction(const MachineInstr *MI) {
731 LLVM_DEBUG(dbgs() << "EmitInstruction: " << *MI << '\n');
732 WebAssembly_MC::verifyInstructionPredicates(Opcode: MI->getOpcode(),
733 Features: Subtarget->getFeatureBits());
734
735 switch (MI->getOpcode()) {
736 case WebAssembly::ARGUMENT_i32:
737 case WebAssembly::ARGUMENT_i32_S:
738 case WebAssembly::ARGUMENT_i64:
739 case WebAssembly::ARGUMENT_i64_S:
740 case WebAssembly::ARGUMENT_f32:
741 case WebAssembly::ARGUMENT_f32_S:
742 case WebAssembly::ARGUMENT_f64:
743 case WebAssembly::ARGUMENT_f64_S:
744 case WebAssembly::ARGUMENT_v16i8:
745 case WebAssembly::ARGUMENT_v16i8_S:
746 case WebAssembly::ARGUMENT_v8i16:
747 case WebAssembly::ARGUMENT_v8i16_S:
748 case WebAssembly::ARGUMENT_v4i32:
749 case WebAssembly::ARGUMENT_v4i32_S:
750 case WebAssembly::ARGUMENT_v2i64:
751 case WebAssembly::ARGUMENT_v2i64_S:
752 case WebAssembly::ARGUMENT_v4f32:
753 case WebAssembly::ARGUMENT_v4f32_S:
754 case WebAssembly::ARGUMENT_v2f64:
755 case WebAssembly::ARGUMENT_v2f64_S:
756 case WebAssembly::ARGUMENT_v8f16:
757 case WebAssembly::ARGUMENT_v8f16_S:
758 case WebAssembly::ARGUMENT_externref:
759 case WebAssembly::ARGUMENT_externref_S:
760 case WebAssembly::ARGUMENT_funcref:
761 case WebAssembly::ARGUMENT_funcref_S:
762 case WebAssembly::ARGUMENT_exnref:
763 case WebAssembly::ARGUMENT_exnref_S:
764 // These represent values which are live into the function entry, so there's
765 // no instruction to emit.
766 break;
767 case WebAssembly::FALLTHROUGH_RETURN: {
768 // These instructions represent the implicit return at the end of a
769 // function body.
770 if (isVerbose()) {
771 OutStreamer->AddComment(T: "fallthrough-return");
772 OutStreamer->addBlankLine();
773 }
774 break;
775 }
776 case WebAssembly::COMPILER_FENCE:
777 // This is a compiler barrier that prevents instruction reordering during
778 // backend compilation, and should not be emitted.
779 break;
780 case WebAssembly::CATCH:
781 case WebAssembly::CATCH_S:
782 case WebAssembly::CATCH_REF:
783 case WebAssembly::CATCH_REF_S:
784 case WebAssembly::CATCH_ALL:
785 case WebAssembly::CATCH_ALL_S:
786 case WebAssembly::CATCH_ALL_REF:
787 case WebAssembly::CATCH_ALL_REF_S:
788 // These are pseudo instructions to represent catch clauses in try_table
789 // instruction to simulate block return values.
790 break;
791 default: {
792 WebAssemblyMCInstLower MCInstLowering(OutContext, *this);
793 MCInst TmpInst;
794 MCInstLowering.lower(MI, OutMI&: TmpInst);
795 EmitToStreamer(S&: *OutStreamer, Inst: TmpInst);
796 break;
797 }
798 }
799}
800
801bool WebAssemblyAsmPrinter::PrintAsmOperand(const MachineInstr *MI,
802 unsigned OpNo,
803 const char *ExtraCode,
804 raw_ostream &OS) {
805 // First try the generic code, which knows about modifiers like 'c' and 'n'.
806 if (!AsmPrinter::PrintAsmOperand(MI, OpNo, ExtraCode, OS))
807 return false;
808
809 if (!ExtraCode) {
810 const MachineOperand &MO = MI->getOperand(i: OpNo);
811 switch (MO.getType()) {
812 case MachineOperand::MO_Immediate:
813 OS << MO.getImm();
814 return false;
815 case MachineOperand::MO_Register:
816 // FIXME: only opcode that still contains registers, as required by
817 // MachineInstr::getDebugVariable().
818 assert(MI->getOpcode() == WebAssembly::INLINEASM);
819 OS << regToString(MO);
820 return false;
821 case MachineOperand::MO_GlobalAddress:
822 PrintSymbolOperand(MO, OS);
823 return false;
824 case MachineOperand::MO_ExternalSymbol:
825 GetExternalSymbolSymbol(Sym: MO.getSymbolName())->print(OS, MAI);
826 printOffset(Offset: MO.getOffset(), OS);
827 return false;
828 case MachineOperand::MO_MachineBasicBlock:
829 MO.getMBB()->getSymbol()->print(OS, MAI);
830 return false;
831 default:
832 break;
833 }
834 }
835
836 return true;
837}
838
839bool WebAssemblyAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
840 unsigned OpNo,
841 const char *ExtraCode,
842 raw_ostream &OS) {
843 // The current approach to inline asm is that "r" constraints are expressed
844 // as local indices, rather than values on the operand stack. This simplifies
845 // using "r" as it eliminates the need to push and pop the values in a
846 // particular order, however it also makes it impossible to have an "m"
847 // constraint. So we don't support it.
848
849 return AsmPrinter::PrintAsmMemoryOperand(MI, OpNo, ExtraCode, OS);
850}
851
852char WebAssemblyAsmPrinter::ID = 0;
853
854INITIALIZE_PASS(WebAssemblyAsmPrinter, "webassembly-asm-printer",
855 "WebAssembly Assembly Printer", false, false)
856
857// Force static initialization.
858extern "C" LLVM_ABI LLVM_EXTERNAL_VISIBILITY void
859LLVMInitializeWebAssemblyAsmPrinter() {
860 RegisterAsmPrinter<WebAssemblyAsmPrinter> X(getTheWebAssemblyTarget32());
861 RegisterAsmPrinter<WebAssemblyAsmPrinter> Y(getTheWebAssemblyTarget64());
862}
863
864PreservedAnalyses
865WebAssemblyAsmPrinterBeginPass::run(Module &M, ModuleAnalysisManager &MAM) {
866 WebAssemblyAsmPrinter &AsmPrinter = static_cast<WebAssemblyAsmPrinter &>(
867 MAM.getResult<AsmPrinterAnalysis>(IR&: M).getPrinter());
868 setupModuleAsmPrinter(M, MAM, AsmPrinter);
869 AsmPrinter.doInitialization(M);
870 return PreservedAnalyses::all();
871}
872
873PreservedAnalyses
874WebAssemblyAsmPrinterPass::run(MachineFunction &MF,
875 MachineFunctionAnalysisManager &MFAM) {
876 WebAssemblyAsmPrinter &AsmPrinter = static_cast<WebAssemblyAsmPrinter &>(
877 MFAM.getResult<ModuleAnalysisManagerMachineFunctionProxy>(IR&: MF)
878 .getCachedResult<AsmPrinterAnalysis>(IR&: *MF.getFunction().getParent())
879 ->getPrinter());
880 setupMachineFunctionAsmPrinter(MFAM, MF, AsmPrinter);
881 AsmPrinter.runOnMachineFunction(MF);
882 return PreservedAnalyses::all();
883}
884
885PreservedAnalyses
886WebAssemblyAsmPrinterEndPass::run(Module &M, ModuleAnalysisManager &MAM) {
887 WebAssemblyAsmPrinter &AsmPrinter = static_cast<WebAssemblyAsmPrinter &>(
888 MAM.getResult<AsmPrinterAnalysis>(IR&: M).getPrinter());
889 setupModuleAsmPrinter(M, MAM, AsmPrinter);
890 AsmPrinter.doFinalization(M);
891 return PreservedAnalyses::all();
892}
893