| 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 "WebAssemblyUtilities.h" |
| 28 | #include "llvm/ADT/MapVector.h" |
| 29 | #include "llvm/ADT/SmallSet.h" |
| 30 | #include "llvm/ADT/StringExtras.h" |
| 31 | #include "llvm/Analysis/ValueTracking.h" |
| 32 | #include "llvm/BinaryFormat/Wasm.h" |
| 33 | #include "llvm/CodeGen/Analysis.h" |
| 34 | #include "llvm/CodeGen/AsmPrinter.h" |
| 35 | #include "llvm/CodeGen/MachineConstantPool.h" |
| 36 | #include "llvm/CodeGen/MachineInstr.h" |
| 37 | #include "llvm/CodeGen/MachineModuleInfoImpls.h" |
| 38 | #include "llvm/IR/DataLayout.h" |
| 39 | #include "llvm/IR/DebugInfoMetadata.h" |
| 40 | #include "llvm/IR/GlobalVariable.h" |
| 41 | #include "llvm/IR/Metadata.h" |
| 42 | #include "llvm/IR/Module.h" |
| 43 | #include "llvm/MC/MCContext.h" |
| 44 | #include "llvm/MC/MCSectionWasm.h" |
| 45 | #include "llvm/MC/MCStreamer.h" |
| 46 | #include "llvm/MC/MCSymbol.h" |
| 47 | #include "llvm/MC/MCSymbolWasm.h" |
| 48 | #include "llvm/MC/TargetRegistry.h" |
| 49 | #include "llvm/Support/Compiler.h" |
| 50 | #include "llvm/Support/Debug.h" |
| 51 | #include "llvm/Support/raw_ostream.h" |
| 52 | |
| 53 | using namespace llvm; |
| 54 | |
| 55 | #define DEBUG_TYPE "asm-printer" |
| 56 | |
| 57 | extern cl::opt<bool> WasmKeepRegisters; |
| 58 | |
| 59 | //===----------------------------------------------------------------------===// |
| 60 | // Helpers. |
| 61 | //===----------------------------------------------------------------------===// |
| 62 | |
| 63 | MVT WebAssemblyAsmPrinter::getRegType(unsigned RegNo) const { |
| 64 | const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo(); |
| 65 | const TargetRegisterClass *TRC = MRI->getRegClass(Reg: RegNo); |
| 66 | for (MVT T : {MVT::i32, MVT::i64, MVT::f32, MVT::f64, MVT::v16i8, MVT::v8i16, |
| 67 | MVT::v4i32, MVT::v2i64, MVT::v4f32, MVT::v2f64, MVT::v8f16}) |
| 68 | if (TRI->isTypeLegalForClass(RC: *TRC, T)) |
| 69 | return T; |
| 70 | LLVM_DEBUG(errs() << "Unknown type for register number: " << RegNo); |
| 71 | llvm_unreachable("Unknown register type" ); |
| 72 | return MVT::Other; |
| 73 | } |
| 74 | |
| 75 | std::string WebAssemblyAsmPrinter::regToString(const MachineOperand &MO) { |
| 76 | Register RegNo = MO.getReg(); |
| 77 | assert(RegNo.isVirtual() && |
| 78 | "Unlowered physical register encountered during assembly printing" ); |
| 79 | assert(!MFI->isVRegStackified(RegNo)); |
| 80 | unsigned WAReg = MFI->getWAReg(VReg: RegNo); |
| 81 | assert(WAReg != WebAssembly::UnusedReg); |
| 82 | return '$' + utostr(X: WAReg); |
| 83 | } |
| 84 | |
| 85 | WebAssemblyTargetStreamer *WebAssemblyAsmPrinter::getTargetStreamer() { |
| 86 | MCTargetStreamer *TS = OutStreamer->getTargetStreamer(); |
| 87 | return static_cast<WebAssemblyTargetStreamer *>(TS); |
| 88 | } |
| 89 | |
| 90 | // Emscripten exception handling helpers |
| 91 | // |
| 92 | // This converts invoke names generated by LowerEmscriptenEHSjLj to real names |
| 93 | // that are expected by JavaScript glue code. The invoke names generated by |
| 94 | // Emscripten JS glue code are based on their argument and return types; for |
| 95 | // example, for a function that takes an i32 and returns nothing, it is |
| 96 | // 'invoke_vi'. But the format of invoke generated by LowerEmscriptenEHSjLj pass |
| 97 | // contains a mangled string generated from their IR types, for example, |
| 98 | // "__invoke_void_%struct.mystruct*_int", because final wasm types are not |
| 99 | // available in the IR pass. So we convert those names to the form that |
| 100 | // Emscripten JS code expects. |
| 101 | // |
| 102 | // Refer to LowerEmscriptenEHSjLj pass for more details. |
| 103 | |
| 104 | // Returns true if the given function name is an invoke name generated by |
| 105 | // LowerEmscriptenEHSjLj pass. |
| 106 | static bool isEmscriptenInvokeName(StringRef Name) { |
| 107 | if (Name.front() == '"' && Name.back() == '"') |
| 108 | Name = Name.substr(Start: 1, N: Name.size() - 2); |
| 109 | return Name.starts_with(Prefix: "__invoke_" ); |
| 110 | } |
| 111 | |
| 112 | // Returns a character that represents the given wasm value type in invoke |
| 113 | // signatures. |
| 114 | static char getInvokeSig(wasm::ValType VT) { |
| 115 | switch (VT) { |
| 116 | case wasm::ValType::I32: |
| 117 | return 'i'; |
| 118 | case wasm::ValType::I64: |
| 119 | return 'j'; |
| 120 | case wasm::ValType::F32: |
| 121 | return 'f'; |
| 122 | case wasm::ValType::F64: |
| 123 | return 'd'; |
| 124 | case wasm::ValType::V128: |
| 125 | return 'V'; |
| 126 | case wasm::ValType::FUNCREF: |
| 127 | return 'F'; |
| 128 | case wasm::ValType::EXTERNREF: |
| 129 | return 'X'; |
| 130 | case wasm::ValType::EXNREF: |
| 131 | return 'E'; |
| 132 | default: |
| 133 | llvm_unreachable("Unhandled wasm::ValType enum" ); |
| 134 | } |
| 135 | } |
| 136 | |
| 137 | // Given the wasm signature, generate the invoke name in the format JS glue code |
| 138 | // expects. |
| 139 | static std::string getEmscriptenInvokeSymbolName(wasm::WasmSignature *Sig) { |
| 140 | assert(Sig->Returns.size() <= 1); |
| 141 | std::string Ret = "invoke_" ; |
| 142 | if (!Sig->Returns.empty()) |
| 143 | for (auto VT : Sig->Returns) |
| 144 | Ret += getInvokeSig(VT); |
| 145 | else |
| 146 | Ret += 'v'; |
| 147 | // Invokes' first argument is a pointer to the original function, so skip it |
| 148 | for (unsigned I = 1, E = Sig->Params.size(); I < E; I++) |
| 149 | Ret += getInvokeSig(VT: Sig->Params[I]); |
| 150 | return Ret; |
| 151 | } |
| 152 | |
| 153 | //===----------------------------------------------------------------------===// |
| 154 | // WebAssemblyAsmPrinter Implementation. |
| 155 | //===----------------------------------------------------------------------===// |
| 156 | |
| 157 | MCSymbolWasm *WebAssemblyAsmPrinter::getMCSymbolForFunction( |
| 158 | const Function *F, bool EnableEmEH, wasm::WasmSignature *Sig, |
| 159 | bool &InvokeDetected) { |
| 160 | MCSymbolWasm *WasmSym = nullptr; |
| 161 | if (EnableEmEH && isEmscriptenInvokeName(Name: F->getName())) { |
| 162 | assert(Sig); |
| 163 | InvokeDetected = true; |
| 164 | if (Sig->Returns.size() > 1) { |
| 165 | std::string Msg = |
| 166 | "Emscripten EH/SjLj does not support multivalue returns: " + |
| 167 | std::string(F->getName()) + ": " + |
| 168 | WebAssembly::signatureToString(Sig); |
| 169 | report_fatal_error(reason: Twine(Msg)); |
| 170 | } |
| 171 | WasmSym = cast<MCSymbolWasm>( |
| 172 | Val: GetExternalSymbolSymbol(Sym: getEmscriptenInvokeSymbolName(Sig))); |
| 173 | } else { |
| 174 | WasmSym = cast<MCSymbolWasm>(Val: getSymbol(GV: F)); |
| 175 | } |
| 176 | return WasmSym; |
| 177 | } |
| 178 | |
| 179 | void WebAssemblyAsmPrinter::emitGlobalVariable(const GlobalVariable *GV) { |
| 180 | if (!WebAssembly::isWasmVarAddressSpace(AS: GV->getAddressSpace())) { |
| 181 | AsmPrinter::emitGlobalVariable(GV); |
| 182 | return; |
| 183 | } |
| 184 | |
| 185 | assert(!GV->isThreadLocal()); |
| 186 | |
| 187 | MCSymbolWasm *Sym = cast<MCSymbolWasm>(Val: getSymbol(GV)); |
| 188 | |
| 189 | if (!Sym->getType()) { |
| 190 | SmallVector<MVT, 1> VTs; |
| 191 | Type *GlobalVT = GV->getValueType(); |
| 192 | if (Subtarget) { |
| 193 | // Subtarget is only set when a function is defined, because |
| 194 | // each function can declare a different subtarget. For example, |
| 195 | // on ARM a compilation unit might have a function on ARM and |
| 196 | // another on Thumb. Therefore only if Subtarget is non-null we |
| 197 | // can actually calculate the legal VTs. |
| 198 | const WebAssemblyTargetLowering &TLI = *Subtarget->getTargetLowering(); |
| 199 | computeLegalValueVTs(TLI, Ctx&: GV->getParent()->getContext(), |
| 200 | DL: GV->getDataLayout(), Ty: GlobalVT, ValueVTs&: VTs); |
| 201 | } |
| 202 | WebAssembly::wasmSymbolSetType(Sym, GlobalVT, VTs); |
| 203 | } |
| 204 | |
| 205 | emitVisibility(Sym, Visibility: GV->getVisibility(), IsDefinition: !GV->isDeclaration()); |
| 206 | emitSymbolType(Sym); |
| 207 | if (GV->hasInitializer()) { |
| 208 | assert(getSymbolPreferLocal(*GV) == Sym); |
| 209 | emitLinkage(GV, GVSym: Sym); |
| 210 | OutStreamer->emitLabel(Symbol: Sym); |
| 211 | // TODO: Actually emit the initializer value. Otherwise the global has the |
| 212 | // default value for its type (0, ref.null, etc). |
| 213 | OutStreamer->addBlankLine(); |
| 214 | } |
| 215 | } |
| 216 | |
| 217 | MCSymbol *WebAssemblyAsmPrinter::getOrCreateWasmSymbol(StringRef Name) { |
| 218 | auto *WasmSym = cast<MCSymbolWasm>(Val: GetExternalSymbolSymbol(Sym: Name)); |
| 219 | |
| 220 | // May be called multiple times, so early out. |
| 221 | if (WasmSym->getType()) |
| 222 | return WasmSym; |
| 223 | |
| 224 | const WebAssemblySubtarget &Subtarget = getSubtarget(); |
| 225 | |
| 226 | // Except for certain known symbols, all symbols used by CodeGen are |
| 227 | // functions. It's OK to hardcode knowledge of specific symbols here; this |
| 228 | // method is precisely there for fetching the signatures of known |
| 229 | // Clang-provided symbols. |
| 230 | if (Name == "__stack_pointer" || Name == "__tls_base" || |
| 231 | Name == "__memory_base" || Name == "__table_base" || |
| 232 | Name == "__tls_size" || Name == "__tls_align" ) { |
| 233 | bool Mutable = |
| 234 | Name == "__stack_pointer" || Name == "__tls_base" ; |
| 235 | WasmSym->setType(wasm::WASM_SYMBOL_TYPE_GLOBAL); |
| 236 | WasmSym->setGlobalType(wasm::WasmGlobalType{ |
| 237 | .Type: uint8_t(Subtarget.hasAddr64() ? wasm::WASM_TYPE_I64 |
| 238 | : wasm::WASM_TYPE_I32), |
| 239 | .Mutable: Mutable}); |
| 240 | return WasmSym; |
| 241 | } |
| 242 | |
| 243 | if (Name.starts_with(Prefix: "GCC_except_table" )) { |
| 244 | WasmSym->setType(wasm::WASM_SYMBOL_TYPE_DATA); |
| 245 | return WasmSym; |
| 246 | } |
| 247 | |
| 248 | SmallVector<wasm::ValType, 4> Returns; |
| 249 | SmallVector<wasm::ValType, 4> Params; |
| 250 | if (Name == "__cpp_exception" || Name == "__c_longjmp" ) { |
| 251 | WasmSym->setType(wasm::WASM_SYMBOL_TYPE_TAG); |
| 252 | // In static linking we define tag symbols in WasmException::endModule(). |
| 253 | // But we may have multiple objects to be linked together, each of which |
| 254 | // defines the tag symbols. To resolve them, we declare them as weak. In |
| 255 | // dynamic linking we make tag symbols undefined in the backend, define it |
| 256 | // in JS, and feed them to each importing module. |
| 257 | if (!isPositionIndependent()) |
| 258 | WasmSym->setWeak(true); |
| 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 | |
| 281 | void 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 | |
| 301 | void 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 = cast<MCSymbolWasm>(Val: 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 = cast_or_null<MCSymbolWasm>(Val: 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( |
| 348 | F: &F, EnableEmEH: WebAssembly::WasmEnableEmEH || WebAssembly::WasmEnableEmSjLj, |
| 349 | Sig: Signature, InvokeDetected); |
| 350 | |
| 351 | // Multiple functions can be mapped to the same invoke symbol. For |
| 352 | // example, two IR functions '__invoke_void_i8*' and '__invoke_void_i32' |
| 353 | // are both mapped to '__invoke_vi'. We keep them in a set once we emit an |
| 354 | // Emscripten EH symbol so we don't emit the same symbol twice. |
| 355 | if (InvokeDetected && !InvokeSymbols.insert(V: Sym).second) |
| 356 | continue; |
| 357 | |
| 358 | Sym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION); |
| 359 | if (!Sym->getSignature()) { |
| 360 | Sym->setSignature(Signature); |
| 361 | } |
| 362 | |
| 363 | getTargetStreamer()->emitFunctionType(Sym); |
| 364 | |
| 365 | if (F.hasFnAttribute(Kind: "wasm-import-module" )) { |
| 366 | StringRef Name = |
| 367 | F.getFnAttribute(Kind: "wasm-import-module" ).getValueAsString(); |
| 368 | Sym->setImportModule(OutContext.allocateString(s: Name)); |
| 369 | getTargetStreamer()->emitImportModule(Sym, ImportModule: Name); |
| 370 | } |
| 371 | if (F.hasFnAttribute(Kind: "wasm-import-name" )) { |
| 372 | // If this is a converted Emscripten EH/SjLj symbol, we shouldn't use |
| 373 | // the original function name but the converted symbol name. |
| 374 | StringRef Name = |
| 375 | InvokeDetected |
| 376 | ? Sym->getName() |
| 377 | : F.getFnAttribute(Kind: "wasm-import-name" ).getValueAsString(); |
| 378 | Sym->setImportName(OutContext.allocateString(s: Name)); |
| 379 | getTargetStreamer()->emitImportName(Sym, ImportName: Name); |
| 380 | } |
| 381 | |
| 382 | if (F.hasFnAttribute(Kind: "wasm-export-name" )) { |
| 383 | auto *Sym = cast<MCSymbolWasm>(Val: getSymbol(GV: &F)); |
| 384 | StringRef Name = F.getFnAttribute(Kind: "wasm-export-name" ).getValueAsString(); |
| 385 | Sym->setExportName(OutContext.allocateString(s: Name)); |
| 386 | getTargetStreamer()->emitExportName(Sym, ExportName: Name); |
| 387 | } |
| 388 | } |
| 389 | } |
| 390 | |
| 391 | void WebAssemblyAsmPrinter::emitEndOfAsmFile(Module &M) { |
| 392 | // This is required to emit external declarations (like .functypes) when |
| 393 | // no functions are defined in the compilation unit and therefore, |
| 394 | // emitDecls() is not called until now. |
| 395 | emitDecls(M); |
| 396 | |
| 397 | // When a function's address is taken, a TABLE_INDEX relocation is emitted |
| 398 | // against the function symbol at the use site. However the relocation |
| 399 | // doesn't explicitly refer to the table. In the future we may want to |
| 400 | // define a new kind of reloc against both the function and the table, so |
| 401 | // that the linker can see that the function symbol keeps the table alive, |
| 402 | // but for now manually mark the table as live. |
| 403 | for (const auto &F : M) { |
| 404 | if (!F.isIntrinsic() && F.hasAddressTaken()) { |
| 405 | MCSymbolWasm *FunctionTable = |
| 406 | WebAssembly::getOrCreateFunctionTableSymbol(Ctx&: OutContext, Subtarget); |
| 407 | OutStreamer->emitSymbolAttribute(Symbol: FunctionTable, Attribute: MCSA_NoDeadStrip); |
| 408 | break; |
| 409 | } |
| 410 | } |
| 411 | |
| 412 | for (const auto &G : M.globals()) { |
| 413 | if (!G.hasInitializer() && G.hasExternalLinkage() && |
| 414 | !WebAssembly::isWasmVarAddressSpace(AS: G.getAddressSpace()) && |
| 415 | G.getValueType()->isSized()) { |
| 416 | uint16_t Size = M.getDataLayout().getTypeAllocSize(Ty: G.getValueType()); |
| 417 | OutStreamer->emitELFSize(Symbol: getSymbol(GV: &G), |
| 418 | Value: MCConstantExpr::create(Value: Size, Ctx&: OutContext)); |
| 419 | } |
| 420 | } |
| 421 | |
| 422 | if (const NamedMDNode *Named = M.getNamedMetadata(Name: "wasm.custom_sections" )) { |
| 423 | for (const Metadata *MD : Named->operands()) { |
| 424 | const auto *Tuple = dyn_cast<MDTuple>(Val: MD); |
| 425 | if (!Tuple || Tuple->getNumOperands() != 2) |
| 426 | continue; |
| 427 | const MDString *Name = dyn_cast<MDString>(Val: Tuple->getOperand(I: 0)); |
| 428 | const MDString *Contents = dyn_cast<MDString>(Val: Tuple->getOperand(I: 1)); |
| 429 | if (!Name || !Contents) |
| 430 | continue; |
| 431 | |
| 432 | OutStreamer->pushSection(); |
| 433 | std::string SectionName = (".custom_section." + Name->getString()).str(); |
| 434 | MCSectionWasm *MySection = |
| 435 | OutContext.getWasmSection(Section: SectionName, K: SectionKind::getMetadata()); |
| 436 | OutStreamer->switchSection(Section: MySection); |
| 437 | OutStreamer->emitBytes(Data: Contents->getString()); |
| 438 | OutStreamer->popSection(); |
| 439 | } |
| 440 | } |
| 441 | |
| 442 | EmitProducerInfo(M); |
| 443 | EmitTargetFeatures(M); |
| 444 | EmitFunctionAttributes(M); |
| 445 | } |
| 446 | |
| 447 | void WebAssemblyAsmPrinter::EmitProducerInfo(Module &M) { |
| 448 | llvm::SmallVector<std::pair<std::string, std::string>, 4> Languages; |
| 449 | if (const NamedMDNode *Debug = M.getNamedMetadata(Name: "llvm.dbg.cu" )) { |
| 450 | llvm::SmallSet<StringRef, 4> SeenLanguages; |
| 451 | for (size_t I = 0, E = Debug->getNumOperands(); I < E; ++I) { |
| 452 | const auto *CU = cast<DICompileUnit>(Val: Debug->getOperand(i: I)); |
| 453 | StringRef Language = dwarf::LanguageString(Language: CU->getSourceLanguage()); |
| 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 | |
| 498 | void 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 | |
| 562 | void 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 = cast<MCSymbolWasm>(Val: 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 | |
| 603 | void WebAssemblyAsmPrinter::emitConstantPool() { |
| 604 | emitDecls(M: *MMI->getModule()); |
| 605 | assert(MF->getConstantPool()->getConstants().empty() && |
| 606 | "WebAssembly disables constant pools" ); |
| 607 | } |
| 608 | |
| 609 | void WebAssemblyAsmPrinter::emitJumpTableInfo() { |
| 610 | // Nothing to do; jump tables are incorporated into the instruction stream. |
| 611 | } |
| 612 | |
| 613 | void 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 = cast<MCSymbolWasm>(Val: 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 | |
| 641 | void 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 | // 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(T: "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 | case WebAssembly::CATCH: |
| 686 | case WebAssembly::CATCH_S: |
| 687 | case WebAssembly::CATCH_REF: |
| 688 | case WebAssembly::CATCH_REF_S: |
| 689 | case WebAssembly::CATCH_ALL: |
| 690 | case WebAssembly::CATCH_ALL_S: |
| 691 | case WebAssembly::CATCH_ALL_REF: |
| 692 | case WebAssembly::CATCH_ALL_REF_S: |
| 693 | // These are pseudo instructions to represent catch clauses in try_table |
| 694 | // instruction to simulate block return values. |
| 695 | break; |
| 696 | default: { |
| 697 | WebAssemblyMCInstLower MCInstLowering(OutContext, *this); |
| 698 | MCInst TmpInst; |
| 699 | MCInstLowering.lower(MI, OutMI&: TmpInst); |
| 700 | EmitToStreamer(S&: *OutStreamer, Inst: TmpInst); |
| 701 | break; |
| 702 | } |
| 703 | } |
| 704 | } |
| 705 | |
| 706 | bool WebAssemblyAsmPrinter::PrintAsmOperand(const MachineInstr *MI, |
| 707 | unsigned OpNo, |
| 708 | const char *, |
| 709 | raw_ostream &OS) { |
| 710 | // First try the generic code, which knows about modifiers like 'c' and 'n'. |
| 711 | if (!AsmPrinter::PrintAsmOperand(MI, OpNo, ExtraCode, OS)) |
| 712 | return false; |
| 713 | |
| 714 | if (!ExtraCode) { |
| 715 | const MachineOperand &MO = MI->getOperand(i: OpNo); |
| 716 | switch (MO.getType()) { |
| 717 | case MachineOperand::MO_Immediate: |
| 718 | OS << MO.getImm(); |
| 719 | return false; |
| 720 | case MachineOperand::MO_Register: |
| 721 | // FIXME: only opcode that still contains registers, as required by |
| 722 | // MachineInstr::getDebugVariable(). |
| 723 | assert(MI->getOpcode() == WebAssembly::INLINEASM); |
| 724 | OS << regToString(MO); |
| 725 | return false; |
| 726 | case MachineOperand::MO_GlobalAddress: |
| 727 | PrintSymbolOperand(MO, OS); |
| 728 | return false; |
| 729 | case MachineOperand::MO_ExternalSymbol: |
| 730 | GetExternalSymbolSymbol(Sym: MO.getSymbolName())->print(OS, MAI); |
| 731 | printOffset(Offset: MO.getOffset(), OS); |
| 732 | return false; |
| 733 | case MachineOperand::MO_MachineBasicBlock: |
| 734 | MO.getMBB()->getSymbol()->print(OS, MAI); |
| 735 | return false; |
| 736 | default: |
| 737 | break; |
| 738 | } |
| 739 | } |
| 740 | |
| 741 | return true; |
| 742 | } |
| 743 | |
| 744 | bool WebAssemblyAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, |
| 745 | unsigned OpNo, |
| 746 | const char *, |
| 747 | raw_ostream &OS) { |
| 748 | // The current approach to inline asm is that "r" constraints are expressed |
| 749 | // as local indices, rather than values on the operand stack. This simplifies |
| 750 | // using "r" as it eliminates the need to push and pop the values in a |
| 751 | // particular order, however it also makes it impossible to have an "m" |
| 752 | // constraint. So we don't support it. |
| 753 | |
| 754 | return AsmPrinter::PrintAsmMemoryOperand(MI, OpNo, ExtraCode, OS); |
| 755 | } |
| 756 | |
| 757 | char WebAssemblyAsmPrinter::ID = 0; |
| 758 | |
| 759 | INITIALIZE_PASS(WebAssemblyAsmPrinter, "webassembly-asm-printer" , |
| 760 | "WebAssembly Assmebly Printer" , false, false) |
| 761 | |
| 762 | // Force static initialization. |
| 763 | extern "C" LLVM_ABI LLVM_EXTERNAL_VISIBILITY void |
| 764 | LLVMInitializeWebAssemblyAsmPrinter() { |
| 765 | RegisterAsmPrinter<WebAssemblyAsmPrinter> X(getTheWebAssemblyTarget32()); |
| 766 | RegisterAsmPrinter<WebAssemblyAsmPrinter> Y(getTheWebAssemblyTarget64()); |
| 767 | } |
| 768 | |