LLVM 19.0.0git
WebAssemblyAsmPrinter.cpp
Go to the documentation of this file.
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
21#include "WebAssembly.h"
28#include "llvm/ADT/MapVector.h"
29#include "llvm/ADT/SmallSet.h"
38#include "llvm/IR/DataLayout.h"
41#include "llvm/IR/Metadata.h"
42#include "llvm/MC/MCContext.h"
44#include "llvm/MC/MCStreamer.h"
45#include "llvm/MC/MCSymbol.h"
48#include "llvm/Support/Debug.h"
50
51using namespace llvm;
52
53#define DEBUG_TYPE "asm-printer"
54
56
57//===----------------------------------------------------------------------===//
58// Helpers.
59//===----------------------------------------------------------------------===//
60
62 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
63 const TargetRegisterClass *TRC = MRI->getRegClass(RegNo);
64 for (MVT T : {MVT::i32, MVT::i64, MVT::f32, MVT::f64, MVT::v16i8, MVT::v8i16,
65 MVT::v4i32, MVT::v2i64, MVT::v4f32, MVT::v2f64, MVT::v8f16})
66 if (TRI->isTypeLegalForClass(*TRC, T))
67 return T;
68 LLVM_DEBUG(errs() << "Unknown type for register number: " << RegNo);
69 llvm_unreachable("Unknown register type");
70 return MVT::Other;
71}
72
74 Register RegNo = MO.getReg();
75 assert(RegNo.isVirtual() &&
76 "Unlowered physical register encountered during assembly printing");
77 assert(!MFI->isVRegStackified(RegNo));
78 unsigned WAReg = MFI->getWAReg(RegNo);
80 return '$' + utostr(WAReg);
81}
82
84 MCTargetStreamer *TS = OutStreamer->getTargetStreamer();
85 return static_cast<WebAssemblyTargetStreamer *>(TS);
86}
87
88// Emscripten exception handling helpers
89//
90// This converts invoke names generated by LowerEmscriptenEHSjLj to real names
91// that are expected by JavaScript glue code. The invoke names generated by
92// Emscripten JS glue code are based on their argument and return types; for
93// example, for a function that takes an i32 and returns nothing, it is
94// 'invoke_vi'. But the format of invoke generated by LowerEmscriptenEHSjLj pass
95// contains a mangled string generated from their IR types, for example,
96// "__invoke_void_%struct.mystruct*_int", because final wasm types are not
97// available in the IR pass. So we convert those names to the form that
98// Emscripten JS code expects.
99//
100// Refer to LowerEmscriptenEHSjLj pass for more details.
101
102// Returns true if the given function name is an invoke name generated by
103// LowerEmscriptenEHSjLj pass.
105 if (Name.front() == '"' && Name.back() == '"')
106 Name = Name.substr(1, Name.size() - 2);
107 return Name.starts_with("__invoke_");
108}
109
110// Returns a character that represents the given wasm value type in invoke
111// signatures.
113 switch (VT) {
115 return 'i';
117 return 'j';
119 return 'f';
121 return 'd';
123 return 'V';
125 return 'F';
127 return 'X';
129 return 'E';
130 default:
131 llvm_unreachable("Unhandled wasm::ValType enum");
132 }
133}
134
135// Given the wasm signature, generate the invoke name in the format JS glue code
136// expects.
138 assert(Sig->Returns.size() <= 1);
139 std::string Ret = "invoke_";
140 if (!Sig->Returns.empty())
141 for (auto VT : Sig->Returns)
142 Ret += getInvokeSig(VT);
143 else
144 Ret += 'v';
145 // Invokes' first argument is a pointer to the original function, so skip it
146 for (unsigned I = 1, E = Sig->Params.size(); I < E; I++)
147 Ret += getInvokeSig(Sig->Params[I]);
148 return Ret;
149}
150
151//===----------------------------------------------------------------------===//
152// WebAssemblyAsmPrinter Implementation.
153//===----------------------------------------------------------------------===//
154
156 const Function *F, bool EnableEmEH, wasm::WasmSignature *Sig,
157 bool &InvokeDetected) {
158 MCSymbolWasm *WasmSym = nullptr;
159 if (EnableEmEH && isEmscriptenInvokeName(F->getName())) {
160 assert(Sig);
161 InvokeDetected = true;
162 if (Sig->Returns.size() > 1) {
163 std::string Msg =
164 "Emscripten EH/SjLj does not support multivalue returns: " +
165 std::string(F->getName()) + ": " +
168 }
169 WasmSym = cast<MCSymbolWasm>(
171 } else {
172 WasmSym = cast<MCSymbolWasm>(getSymbol(F));
173 }
174 return WasmSym;
175}
176
180 return;
181 }
182
183 assert(!GV->isThreadLocal());
184
185 MCSymbolWasm *Sym = cast<MCSymbolWasm>(getSymbol(GV));
186
187 if (!Sym->getType()) {
189 Type *GlobalVT = GV->getValueType();
190 if (Subtarget) {
191 // Subtarget is only set when a function is defined, because
192 // each function can declare a different subtarget. For example,
193 // on ARM a compilation unit might have a function on ARM and
194 // another on Thumb. Therefore only if Subtarget is non-null we
195 // can actually calculate the legal VTs.
196 const WebAssemblyTargetLowering &TLI = *Subtarget->getTargetLowering();
198 GV->getParent()->getDataLayout(), GlobalVT, VTs);
199 }
200 WebAssembly::wasmSymbolSetType(Sym, GlobalVT, VTs);
201 }
202
205 if (GV->hasInitializer()) {
207 emitLinkage(GV, Sym);
208 OutStreamer->emitLabel(Sym);
209 // TODO: Actually emit the initializer value. Otherwise the global has the
210 // default value for its type (0, ref.null, etc).
211 OutStreamer->addBlankLine();
212 }
213}
214
216 auto *WasmSym = cast<MCSymbolWasm>(GetExternalSymbolSymbol(Name));
217
218 // May be called multiple times, so early out.
219 if (WasmSym->getType())
220 return WasmSym;
221
222 const WebAssemblySubtarget &Subtarget = getSubtarget();
223
224 // Except for certain known symbols, all symbols used by CodeGen are
225 // functions. It's OK to hardcode knowledge of specific symbols here; this
226 // method is precisely there for fetching the signatures of known
227 // Clang-provided symbols.
228 if (Name == "__stack_pointer" || Name == "__tls_base" ||
229 Name == "__memory_base" || Name == "__table_base" ||
230 Name == "__tls_size" || Name == "__tls_align") {
231 bool Mutable =
232 Name == "__stack_pointer" || Name == "__tls_base";
233 WasmSym->setType(wasm::WASM_SYMBOL_TYPE_GLOBAL);
234 WasmSym->setGlobalType(wasm::WasmGlobalType{
235 uint8_t(Subtarget.hasAddr64() ? wasm::WASM_TYPE_I64
237 Mutable});
238 return WasmSym;
239 }
240
241 if (Name.starts_with("GCC_except_table")) {
242 WasmSym->setType(wasm::WASM_SYMBOL_TYPE_DATA);
243 return WasmSym;
244 }
245
248 if (Name == "__cpp_exception" || Name == "__c_longjmp") {
249 WasmSym->setType(wasm::WASM_SYMBOL_TYPE_TAG);
250 // In static linking we define tag symbols in WasmException::endModule().
251 // But we may have multiple objects to be linked together, each of which
252 // defines the tag symbols. To resolve them, we declare them as weak. In
253 // dynamic linking we make tag symbols undefined in the backend, define it
254 // in JS, and feed them to each importing module.
256 WasmSym->setWeak(true);
257 WasmSym->setExternal(true);
258
259 // Currently both C++ exceptions and C longjmps have a single pointer type
260 // param. For C++ exceptions it is a pointer to an exception object, and for
261 // C longjmps it is pointer to a struct that contains a setjmp buffer and a
262 // longjmp return value. We may consider using multiple value parameters for
263 // longjmps later when multivalue support is ready.
264 wasm::ValType AddrType =
266 Params.push_back(AddrType);
267 } else { // Function symbols
268 WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
269 WebAssembly::getLibcallSignature(Subtarget, Name, Returns, Params);
270 }
271 auto Signature = OutContext.createWasmSignature();
272 Signature->Returns = std::move(Returns);
273 Signature->Params = std::move(Params);
274 WasmSym->setSignature(Signature);
275
276 return WasmSym;
277}
278
280 std::optional<wasm::WasmSymbolType> WasmTy = Sym->getType();
281 if (!WasmTy)
282 return;
283
284 switch (*WasmTy) {
287 break;
290 break;
293 break;
294 default:
295 break; // We only handle globals, tags and tables here
296 }
297}
298
300 if (signaturesEmitted)
301 return;
302 signaturesEmitted = true;
303
304 // Normally symbols for globals get discovered as the MI gets lowered,
305 // but we need to know about them ahead of time. This will however,
306 // only find symbols that have been used. Unused symbols from globals will
307 // not be found here.
309 for (StringRef Name : MMIW.MachineSymbolsUsed) {
310 auto *WasmSym = cast<MCSymbolWasm>(getOrCreateWasmSymbol(Name));
311 if (WasmSym->isFunction()) {
312 // TODO(wvo): is there any case where this overlaps with the call to
313 // emitFunctionType in the loop below?
315 }
316 }
317
318 for (auto &It : OutContext.getSymbols()) {
319 // Emit .globaltype, .tagtype, or .tabletype declarations for extern
320 // declarations, i.e. those that have only been declared (but not defined)
321 // in the current module
322 auto Sym = cast<MCSymbolWasm>(It.getValue());
323 if (!Sym->isDefined())
325 }
326
327 DenseSet<MCSymbol *> InvokeSymbols;
328 for (const auto &F : M) {
329 if (F.isIntrinsic())
330 continue;
331
332 // Emit function type info for all functions. This will emit duplicate
333 // information for defined functions (which already have function type
334 // info emitted alongside their definition), but this is necessary in
335 // order to enable the single-pass WebAssemblyAsmTypeCheck to succeed.
337 SmallVector<MVT, 4> Params;
338 computeSignatureVTs(F.getFunctionType(), &F, F, TM, Params, Results);
339 // At this point these MCSymbols may or may not have been created already
340 // and thus also contain a signature, but we need to get the signature
341 // anyway here in case it is an invoke that has not yet been created. We
342 // will discard it later if it turns out not to be necessary.
343 auto Signature = signatureFromMVTs(OutContext, Results, Params);
344 bool InvokeDetected = false;
347 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(Sym).second)
354 continue;
355
357 if (!Sym->getSignature()) {
358 Sym->setSignature(Signature);
359 }
360
362
363 if (F.hasFnAttribute("wasm-import-module")) {
365 F.getFnAttribute("wasm-import-module").getValueAsString();
366 Sym->setImportModule(OutContext.allocateString(Name));
368 }
369 if (F.hasFnAttribute("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.
373 InvokeDetected
374 ? Sym->getName()
375 : F.getFnAttribute("wasm-import-name").getValueAsString();
376 Sym->setImportName(OutContext.allocateString(Name));
378 }
379
380 if (F.hasFnAttribute("wasm-export-name")) {
381 auto *Sym = cast<MCSymbolWasm>(getSymbol(&F));
382 StringRef Name = F.getFnAttribute("wasm-export-name").getValueAsString();
383 Sym->setExportName(OutContext.allocateString(Name));
385 }
386 }
387}
388
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 =
405 OutStreamer->emitSymbolAttribute(FunctionTable, MCSA_NoDeadStrip);
406 break;
407 }
408 }
409
410 for (const auto &G : M.globals()) {
411 if (!G.hasInitializer() && G.hasExternalLinkage() &&
412 !WebAssembly::isWasmVarAddressSpace(G.getAddressSpace()) &&
413 G.getValueType()->isSized()) {
414 uint16_t Size = M.getDataLayout().getTypeAllocSize(G.getValueType());
415 OutStreamer->emitELFSize(getSymbol(&G),
417 }
418 }
419
420 if (const NamedMDNode *Named = M.getNamedMetadata("wasm.custom_sections")) {
421 for (const Metadata *MD : Named->operands()) {
422 const auto *Tuple = dyn_cast<MDTuple>(MD);
423 if (!Tuple || Tuple->getNumOperands() != 2)
424 continue;
425 const MDString *Name = dyn_cast<MDString>(Tuple->getOperand(0));
426 const MDString *Contents = dyn_cast<MDString>(Tuple->getOperand(1));
427 if (!Name || !Contents)
428 continue;
429
430 OutStreamer->pushSection();
431 std::string SectionName = (".custom_section." + Name->getString()).str();
432 MCSectionWasm *MySection =
434 OutStreamer->switchSection(MySection);
435 OutStreamer->emitBytes(Contents->getString());
436 OutStreamer->popSection();
437 }
438 }
439
443}
444
447 if (const NamedMDNode *Debug = M.getNamedMetadata("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>(Debug->getOperand(I));
451 StringRef Language = dwarf::LanguageString(CU->getSourceLanguage());
452 Language.consume_front("DW_LANG_");
453 if (SeenLanguages.insert(Language).second)
454 Languages.emplace_back(Language.str(), "");
455 }
456 }
457
459 if (const NamedMDNode *Ident = M.getNamedMetadata("llvm.ident")) {
461 for (size_t I = 0, E = Ident->getNumOperands(); I < E; ++I) {
462 const auto *S = cast<MDString>(Ident->getOperand(I)->getOperand(0));
463 std::pair<StringRef, StringRef> Field = S->getString().split("version");
464 StringRef Name = Field.first.trim();
465 StringRef Version = Field.second.trim();
466 if (SeenTools.insert(Name).second)
467 Tools.emplace_back(Name.str(), Version.str());
468 }
469 }
470
471 int FieldCount = int(!Languages.empty()) + int(!Tools.empty());
472 if (FieldCount != 0) {
474 ".custom_section.producers", SectionKind::getMetadata());
475 OutStreamer->pushSection();
476 OutStreamer->switchSection(Producers);
477 OutStreamer->emitULEB128IntValue(FieldCount);
478 for (auto &Producers : {std::make_pair("language", &Languages),
479 std::make_pair("processed-by", &Tools)}) {
480 if (Producers.second->empty())
481 continue;
482 OutStreamer->emitULEB128IntValue(strlen(Producers.first));
483 OutStreamer->emitBytes(Producers.first);
484 OutStreamer->emitULEB128IntValue(Producers.second->size());
485 for (auto &Producer : *Producers.second) {
486 OutStreamer->emitULEB128IntValue(Producer.first.size());
487 OutStreamer->emitBytes(Producer.first);
488 OutStreamer->emitULEB128IntValue(Producer.second.size());
489 OutStreamer->emitBytes(Producer.second);
490 }
491 }
492 OutStreamer->popSection();
493 }
494}
495
497 struct FeatureEntry {
498 uint8_t Prefix;
499 std::string Name;
500 };
501
502 // Read target features and linkage policies from module metadata
503 SmallVector<FeatureEntry, 4> EmittedFeatures;
504 auto EmitFeature = [&](std::string Feature) {
505 std::string MDKey = (StringRef("wasm-feature-") + Feature).str();
506 Metadata *Policy = M.getModuleFlag(MDKey);
507 if (Policy == nullptr)
508 return;
509
510 FeatureEntry Entry;
511 Entry.Prefix = 0;
512 Entry.Name = Feature;
513
514 if (auto *MD = cast<ConstantAsMetadata>(Policy))
515 if (auto *I = cast<ConstantInt>(MD->getValue()))
516 Entry.Prefix = I->getZExtValue();
517
518 // Silently ignore invalid metadata
519 if (Entry.Prefix != wasm::WASM_FEATURE_PREFIX_USED &&
520 Entry.Prefix != wasm::WASM_FEATURE_PREFIX_REQUIRED &&
522 return;
523
524 EmittedFeatures.push_back(Entry);
525 };
526
527 for (const SubtargetFeatureKV &KV : WebAssemblyFeatureKV) {
528 EmitFeature(KV.Key);
529 }
530 // This pseudo-feature tells the linker whether shared memory would be safe
531 EmitFeature("shared-mem");
532
533 // This is an "architecture", not a "feature", but we emit it as such for
534 // the benefit of tools like Binaryen and consistency with other producers.
535 // FIXME: Subtarget is null here, so can't Subtarget->hasAddr64() ?
536 if (M.getDataLayout().getPointerSize() == 8) {
537 // Can't use EmitFeature since "wasm-feature-memory64" is not a module
538 // flag.
539 EmittedFeatures.push_back({wasm::WASM_FEATURE_PREFIX_USED, "memory64"});
540 }
541
542 if (EmittedFeatures.size() == 0)
543 return;
544
545 // Emit features and linkage policies into the "target_features" section
546 MCSectionWasm *FeaturesSection = OutContext.getWasmSection(
547 ".custom_section.target_features", SectionKind::getMetadata());
548 OutStreamer->pushSection();
549 OutStreamer->switchSection(FeaturesSection);
550
551 OutStreamer->emitULEB128IntValue(EmittedFeatures.size());
552 for (auto &F : EmittedFeatures) {
553 OutStreamer->emitIntValue(F.Prefix, 1);
554 OutStreamer->emitULEB128IntValue(F.Name.size());
555 OutStreamer->emitBytes(F.Name);
556 }
557
558 OutStreamer->popSection();
559}
560
562 auto V = M.getNamedGlobal("llvm.global.annotations");
563 if (!V)
564 return;
565
566 // Group all the custom attributes by name.
568 const ConstantArray *CA = cast<ConstantArray>(V->getOperand(0));
569 for (Value *Op : CA->operands()) {
570 auto *CS = cast<ConstantStruct>(Op);
571 // The first field is a pointer to the annotated variable.
572 Value *AnnotatedVar = CS->getOperand(0)->stripPointerCasts();
573 // Only annotated functions are supported for now.
574 if (!isa<Function>(AnnotatedVar))
575 continue;
576 auto *F = cast<Function>(AnnotatedVar);
577
578 // The second field is a pointer to a global annotation string.
579 auto *GV = cast<GlobalVariable>(CS->getOperand(1)->stripPointerCasts());
580 StringRef AnnotationString;
581 getConstantStringInfo(GV, AnnotationString);
582 auto *Sym = cast<MCSymbolWasm>(getSymbol(F));
583 CustomSections[AnnotationString].push_back(Sym);
584 }
585
586 // Emit a custom section for each unique attribute.
587 for (const auto &[Name, Symbols] : CustomSections) {
588 MCSectionWasm *CustomSection = OutContext.getWasmSection(
589 ".custom_section.llvm.func_attr.annotate." + Name, SectionKind::getMetadata());
590 OutStreamer->pushSection();
591 OutStreamer->switchSection(CustomSection);
592
593 for (auto &Sym : Symbols) {
594 OutStreamer->emitValue(
596 OutContext),
597 4);
598 }
599 OutStreamer->popSection();
600 }
601}
602
605 assert(MF->getConstantPool()->getConstants().empty() &&
606 "WebAssembly disables constant pools");
607}
608
610 // Nothing to do; jump tables are incorporated into the instruction stream.
611}
612
614 const Function &F = MF->getFunction();
615 SmallVector<MVT, 1> ResultVTs;
616 SmallVector<MVT, 4> ParamVTs;
617 computeSignatureVTs(F.getFunctionType(), &F, F, TM, ParamVTs, ResultVTs);
618
619 auto Signature = signatureFromMVTs(OutContext, ResultVTs, ParamVTs);
620 auto *WasmSym = cast<MCSymbolWasm>(CurrentFnSym);
621 WasmSym->setSignature(Signature);
622 WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
623
625
626 // Emit the function index.
627 if (MDNode *Idx = F.getMetadata("wasm.index")) {
628 assert(Idx->getNumOperands() == 1);
629
631 cast<ConstantAsMetadata>(Idx->getOperand(0))->getValue()));
632 }
633
635 valTypesFromMVTs(MFI->getLocals(), Locals);
636 getTargetStreamer()->emitLocal(Locals);
637
639}
640
642 LLVM_DEBUG(dbgs() << "EmitInstruction: " << *MI << '\n');
643 WebAssembly_MC::verifyInstructionPredicates(MI->getOpcode(),
644 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 // These represent values which are live into the function entry, so there's
670 // no instruction to emit.
671 break;
672 case WebAssembly::FALLTHROUGH_RETURN: {
673 // These instructions represent the implicit return at the end of a
674 // function body.
675 if (isVerbose()) {
676 OutStreamer->AddComment("fallthrough-return");
677 OutStreamer->addBlankLine();
678 }
679 break;
680 }
681 case WebAssembly::COMPILER_FENCE:
682 // This is a compiler barrier that prevents instruction reordering during
683 // backend compilation, and should not be emitted.
684 break;
685 default: {
686 WebAssemblyMCInstLower MCInstLowering(OutContext, *this);
687 MCInst TmpInst;
688 MCInstLowering.lower(MI, TmpInst);
689 EmitToStreamer(*OutStreamer, TmpInst);
690 break;
691 }
692 }
693}
694
696 unsigned OpNo,
697 const char *ExtraCode,
698 raw_ostream &OS) {
699 // First try the generic code, which knows about modifiers like 'c' and 'n'.
700 if (!AsmPrinter::PrintAsmOperand(MI, OpNo, ExtraCode, OS))
701 return false;
702
703 if (!ExtraCode) {
704 const MachineOperand &MO = MI->getOperand(OpNo);
705 switch (MO.getType()) {
707 OS << MO.getImm();
708 return false;
710 // FIXME: only opcode that still contains registers, as required by
711 // MachineInstr::getDebugVariable().
712 assert(MI->getOpcode() == WebAssembly::INLINEASM);
713 OS << regToString(MO);
714 return false;
717 return false;
720 printOffset(MO.getOffset(), OS);
721 return false;
723 MO.getMBB()->getSymbol()->print(OS, MAI);
724 return false;
725 default:
726 break;
727 }
728 }
729
730 return true;
731}
732
734 unsigned OpNo,
735 const char *ExtraCode,
736 raw_ostream &OS) {
737 // The current approach to inline asm is that "r" constraints are expressed
738 // as local indices, rather than values on the operand stack. This simplifies
739 // using "r" as it eliminates the need to push and pop the values in a
740 // particular order, however it also makes it impossible to have an "m"
741 // constraint. So we don't support it.
742
743 return AsmPrinter::PrintAsmMemoryOperand(MI, OpNo, ExtraCode, OS);
744}
745
746// Force static initialization.
750}
Function Alias Analysis Results
#define LLVM_EXTERNAL_VISIBILITY
Definition: Compiler.h:135
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
#define LLVM_DEBUG(X)
Definition: Debug.h:101
std::string Name
uint64_t Size
Symbol * Sym
Definition: ELF_riscv.cpp:479
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
IRTranslator LLVM IR MI
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
#define G(x, y, z)
Definition: MD5.cpp:56
This file declares the MachineConstantPool class which is an abstract constant pool to keep track of ...
unsigned const TargetRegisterInfo * TRI
This file implements a map that provides insertion order iteration.
This file contains the declarations for metadata subclasses.
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
raw_pwrite_stream & OS
This file defines the SmallSet class.
This file contains some functions that are useful when dealing with strings.
static std::string getEmscriptenInvokeSymbolName(wasm::WasmSignature *Sig)
static bool isEmscriptenInvokeName(StringRef Name)
static char getInvokeSig(wasm::ValType VT)
LLVM_EXTERNAL_VISIBILITY void LLVMInitializeWebAssemblyAsmPrinter()
cl::opt< bool > WasmKeepRegisters
This file declares the class to lower WebAssembly MachineInstrs to their corresponding MCInst records...
This file provides WebAssembly-specific target descriptions.
This file declares WebAssembly-specific per-machine-function information.
This file contains the WebAssembly implementation of the WebAssemblyRegisterInfo class.
This file provides signature information for runtime libcalls.
This file registers the WebAssembly target.
This file declares the WebAssembly-specific subclass of TargetMachine.
This file declares WebAssembly-specific target streamer classes.
This file contains the declaration of the WebAssembly-specific type parsing utility functions.
This file contains the declaration of the WebAssembly-specific utility functions.
This file contains the entry points for global functions defined in the LLVM WebAssembly back-end.
MCSymbol * getSymbol(const GlobalValue *GV) const
Definition: AsmPrinter.cpp:704
void EmitToStreamer(MCStreamer &S, const MCInst &Inst)
Definition: AsmPrinter.cpp:419
virtual void emitGlobalVariable(const GlobalVariable *GV)
Emit the specified global variable to the .s file.
Definition: AsmPrinter.cpp:726
TargetMachine & TM
Target machine description.
Definition: AsmPrinter.h:88
virtual void PrintSymbolOperand(const MachineOperand &MO, raw_ostream &OS)
Print the MachineOperand as a symbol.
const MCAsmInfo * MAI
Target Asm Printer information.
Definition: AsmPrinter.h:91
MachineFunction * MF
The current machine function.
Definition: AsmPrinter.h:103
virtual void emitFunctionBodyStart()
Targets can override this to emit stuff before the first basic block in the function.
Definition: AsmPrinter.h:552
virtual void emitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const
This emits linkage information about GVSym based on GV, if this is supported by the target.
Definition: AsmPrinter.cpp:659
void printOffset(int64_t Offset, raw_ostream &OS) const
This is just convenient handler for printing offsets.
MCSymbol * getSymbolPreferLocal(const GlobalValue &GV) const
Similar to getSymbol() but preferred for references.
Definition: AsmPrinter.cpp:708
MCSymbol * CurrentFnSym
The symbol for the current function.
Definition: AsmPrinter.h:122
MachineModuleInfo * MMI
This is a pointer to the current MachineModuleInfo.
Definition: AsmPrinter.h:106
MCContext & OutContext
This is the context for the output file that we are streaming.
Definition: AsmPrinter.h:95
MCSymbol * GetExternalSymbolSymbol(Twine Sym) const
Return the MCSymbol for the specified ExternalSymbol.
bool isPositionIndependent() const
Definition: AsmPrinter.cpp:390
void emitVisibility(MCSymbol *Sym, unsigned Visibility, bool IsDefinition=true) const
This emits visibility information about symbol, if this is supported by the target.
std::unique_ptr< MCStreamer > OutStreamer
This is the MCStreamer object for the file we are generating.
Definition: AsmPrinter.h:100
virtual const MCExpr * lowerConstant(const Constant *CV)
Lower the specified LLVM Constant to an MCExpr.
virtual bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo, const char *ExtraCode, raw_ostream &OS)
Print the specified operand of MI, an INLINEASM instruction, using the specified assembler variant as...
bool isVerbose() const
Return true if assembly output should contain comments.
Definition: AsmPrinter.h:266
@ Debug
Emit .debug_frame.
virtual bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, const char *ExtraCode, raw_ostream &OS)
Print the specified operand of MI, an INLINEASM instruction, using the specified assembler variant.
ConstantArray - Constant Array Declarations.
Definition: Constants.h:424
This class represents an Operation in the Expression.
Implements a dense probed hash-table based set.
Definition: DenseSet.h:271
bool isThreadLocal() const
If the value is "Thread Local", its value isn't shared by the threads.
Definition: GlobalValue.h:262
VisibilityTypes getVisibility() const
Definition: GlobalValue.h:247
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition: Globals.cpp:286
unsigned getAddressSpace() const
Definition: GlobalValue.h:204
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:655
Type * getValueType() const
Definition: GlobalValue.h:295
bool hasInitializer() const
Definitions have initializers, declarations don't.
static const MCConstantExpr * create(int64_t Value, MCContext &Ctx, bool PrintInHex=false, unsigned SizeInBytes=0)
Definition: MCExpr.cpp:194
MCSectionWasm * getWasmSection(const Twine &Section, SectionKind K, unsigned Flags=0)
Definition: MCContext.h:624
wasm::WasmSignature * createWasmSignature()
Allocates and returns a new WasmSignature instance (with empty parameter and return type lists).
Definition: MCContext.cpp:388
StringRef allocateString(StringRef s)
Allocates a copy of the given string on the allocator managed by this context and returns the result.
Definition: MCContext.h:831
const SymbolTable & getSymbols() const
getSymbols - Get a reference for the symbol table for clients that want to, for example,...
Definition: MCContext.h:501
Instances of this class represent a single low-level machine instruction.
Definition: MCInst.h:184
This represents a section on wasm.
Definition: MCSectionWasm.h:26
bool empty() const
Definition: MCSection.h:193
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx)
Definition: MCExpr.h:397
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:40
void print(raw_ostream &OS, const MCAsmInfo *MAI) const
print - Print the value to the stream OS.
Definition: MCSymbol.cpp:58
Target specific streamer interface.
Definition: MCStreamer.h:93
Metadata node.
Definition: Metadata.h:1067
A single uniqued string.
Definition: Metadata.h:720
StringRef getString() const
Definition: Metadata.cpp:610
Machine Value Type.
MCSymbol * getSymbol() const
Return the MCSymbol for this basic block.
const std::vector< MachineConstantPoolEntry > & getConstants() const
Function & getFunction()
Return the LLVM function that this machine code represents.
MachineConstantPool * getConstantPool()
getConstantPool - Return the constant pool object for the current function.
Representation of each machine instruction.
Definition: MachineInstr.h:69
MachineModuleInfoWasm - This is a MachineModuleInfoImpl implementation for Wasm targets.
SetVector< StringRef > MachineSymbolsUsed
const Module * getModule() const
Ty & getObjFileInfo()
Keep track of various per-module pieces of information for backends that would like to do so.
MachineOperand class - Representation of each machine instruction operand.
int64_t getImm() const
MachineBasicBlock * getMBB() const
MachineOperandType getType() const
getType - Returns the MachineOperandType for this operand.
const char * getSymbolName() const
Register getReg() const
getReg - Returns the register number.
@ MO_Immediate
Immediate operand.
@ MO_GlobalAddress
Address of a global value.
@ MO_MachineBasicBlock
MachineBasicBlock reference.
@ MO_Register
Register operand.
@ MO_ExternalSymbol
Name of external global symbol.
int64_t getOffset() const
Return the offset from the symbol in this operand.
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
This class implements a map that also provides access to all stored values in a deterministic order.
Definition: MapVector.h:36
Root of the metadata hierarchy.
Definition: Metadata.h:62
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
LLVMContext & getContext() const
Get the global data context.
Definition: Module.h:301
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Definition: Module.h:293
A tuple of MDNodes.
Definition: Metadata.h:1729
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition: Register.h:91
static SectionKind getMetadata()
Definition: SectionKind.h:188
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition: SmallSet.h:135
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition: SmallSet.h:179
bool empty() const
Definition: SmallVector.h:94
size_t size() const
Definition: SmallVector.h:91
reference emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:950
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
op_range operands()
Definition: User.h:242
LLVM Value Representation.
Definition: Value.h:74
const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition: Value.cpp:693
void emitJumpTableInfo() override
Print assembly representations of the jump tables used by the current function to the current output ...
void emitGlobalVariable(const GlobalVariable *GV) override
Emit the specified global variable to the .s file.
bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo, const char *ExtraCode, raw_ostream &OS) override
Print the specified operand of MI, an INLINEASM instruction, using the specified assembler variant as...
const WebAssemblySubtarget & getSubtarget() const
WebAssemblyTargetStreamer * getTargetStreamer()
void emitInstruction(const MachineInstr *MI) override
Targets should implement this to emit instructions.
std::string regToString(const MachineOperand &MO)
void emitSymbolType(const MCSymbolWasm *Sym)
MCSymbol * getOrCreateWasmSymbol(StringRef Name)
void emitConstantPool() override
Print to the current output stream assembly representations of the constants in the constant pool MCP...
MVT getRegType(unsigned RegNo) const
void emitFunctionBodyStart() override
Targets can override this to emit stuff before the first basic block in the function.
bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, const char *ExtraCode, raw_ostream &OS) override
Print the specified operand of MI, an INLINEASM instruction, using the specified assembler variant.
MCSymbolWasm * getMCSymbolForFunction(const Function *F, bool EnableEmEH, wasm::WasmSignature *Sig, bool &InvokeDetected)
void emitEndOfAsmFile(Module &M) override
This virtual method can be overridden by targets that want to emit something at the end of their file...
unsigned getWAReg(unsigned VReg) const
const std::vector< MVT > & getLocals() const
This class is used to lower an MachineInstr into an MCInst.
void lower(const MachineInstr *MI, MCInst &OutMI) const
const WebAssemblyTargetLowering * getTargetLowering() const override
const WebAssemblyRegisterInfo * getRegisterInfo() const override
WebAssembly-specific streamer interface, to implement support WebAssembly-specific assembly directive...
virtual void emitFunctionType(const MCSymbolWasm *Sym)=0
.functype
virtual void emitLocal(ArrayRef< wasm::ValType > Types)=0
.local
virtual void emitTagType(const MCSymbolWasm *Sym)=0
.tagtype
virtual void emitExportName(const MCSymbolWasm *Sym, StringRef ExportName)=0
.export_name
virtual void emitGlobalType(const MCSymbolWasm *Sym)=0
.globaltype
virtual void emitImportModule(const MCSymbolWasm *Sym, StringRef ImportModule)=0
.import_module
virtual void emitTableType(const MCSymbolWasm *Sym)=0
.tabletype
virtual void emitImportName(const MCSymbolWasm *Sym, StringRef ImportName)=0
.import_name
virtual void emitIndIdx(const MCExpr *Value)=0
.indidx
std::pair< iterator, bool > insert(const ValueT &V)
Definition: DenseSet.h:206
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
StringRef LanguageString(unsigned Language)
Definition: Dwarf.cpp:393
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
MCSymbolWasm * getOrCreateFunctionTableSymbol(MCContext &Ctx, const WebAssemblySubtarget *Subtarget)
Returns the __indirect_function_table, for use in call_indirect and in function bitcasts.
void wasmSymbolSetType(MCSymbolWasm *Sym, const Type *GlobalVT, ArrayRef< MVT > VTs)
Sets a Wasm Symbol Type.
static const unsigned UnusedReg
cl::opt< bool > WasmEnableEmEH
cl::opt< bool > WasmEnableEmSjLj
std::string signatureToString(const wasm::WasmSignature *Sig)
void getLibcallSignature(const WebAssemblySubtarget &Subtarget, RTLIB::Libcall LC, SmallVectorImpl< wasm::ValType > &Rets, SmallVectorImpl< wasm::ValType > &Params)
bool isWasmVarAddressSpace(unsigned AS)
@ WASM_TYPE_I64
Definition: Wasm.h:55
@ WASM_TYPE_I32
Definition: Wasm.h:54
@ WASM_SYMBOL_TYPE_GLOBAL
Definition: Wasm.h:211
@ WASM_SYMBOL_TYPE_DATA
Definition: Wasm.h:210
@ WASM_SYMBOL_TYPE_TAG
Definition: Wasm.h:213
@ WASM_SYMBOL_TYPE_TABLE
Definition: Wasm.h:214
@ WASM_SYMBOL_TYPE_FUNCTION
Definition: Wasm.h:209
@ WASM_FEATURE_PREFIX_USED
Definition: Wasm.h:169
@ WASM_FEATURE_PREFIX_REQUIRED
Definition: Wasm.h:170
@ WASM_FEATURE_PREFIX_DISALLOWED
Definition: Wasm.h:171
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
void computeSignatureVTs(const FunctionType *Ty, const Function *TargetFunc, const Function &ContextFunc, const TargetMachine &TM, SmallVectorImpl< MVT > &Params, SmallVectorImpl< MVT > &Results)
const SubtargetFeatureKV WebAssemblyFeatureKV[WebAssembly::NumSubtargetFeatures]
bool getConstantStringInfo(const Value *V, StringRef &Str, bool TrimAtNul=true)
This function computes the length of a null-terminated C string pointed to by V.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
Target & getTheWebAssemblyTarget32()
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:167
raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
Target & getTheWebAssemblyTarget64()
void valTypesFromMVTs(ArrayRef< MVT > In, SmallVectorImpl< wasm::ValType > &Out)
wasm::WasmSignature * signatureFromMVTs(MCContext &Ctx, const SmallVectorImpl< MVT > &Results, const SmallVectorImpl< MVT > &Params)
void computeLegalValueVTs(const WebAssemblyTargetLowering &TLI, LLVMContext &Ctx, const DataLayout &DL, Type *Ty, SmallVectorImpl< MVT > &ValueVTs)
@ MCSA_NoDeadStrip
.no_dead_strip (MachO)
Definition: MCDirectives.h:39
RegisterAsmPrinter - Helper template for registering a target specific assembly printer,...
Used to provide key value pairs for feature and CPU bit flags.
SmallVector< ValType, 1 > Returns
Definition: Wasm.h:488
SmallVector< ValType, 4 > Params
Definition: Wasm.h:489