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