118eafb6cSDan Gohman //===- lib/MC/WasmObjectWriter.cpp - Wasm File Writer ---------------------===// 218eafb6cSDan Gohman // 318eafb6cSDan Gohman // The LLVM Compiler Infrastructure 418eafb6cSDan Gohman // 518eafb6cSDan Gohman // This file is distributed under the University of Illinois Open Source 618eafb6cSDan Gohman // License. See LICENSE.TXT for details. 718eafb6cSDan Gohman // 818eafb6cSDan Gohman //===----------------------------------------------------------------------===// 918eafb6cSDan Gohman // 1018eafb6cSDan Gohman // This file implements Wasm object file writer information. 1118eafb6cSDan Gohman // 1218eafb6cSDan Gohman //===----------------------------------------------------------------------===// 1318eafb6cSDan Gohman 1418eafb6cSDan Gohman #include "llvm/ADT/STLExtras.h" 1518eafb6cSDan Gohman #include "llvm/ADT/SmallPtrSet.h" 16264b5d9eSZachary Turner #include "llvm/BinaryFormat/Wasm.h" 1718eafb6cSDan Gohman #include "llvm/MC/MCAsmBackend.h" 1818eafb6cSDan Gohman #include "llvm/MC/MCAsmLayout.h" 1918eafb6cSDan Gohman #include "llvm/MC/MCAssembler.h" 2018eafb6cSDan Gohman #include "llvm/MC/MCContext.h" 2118eafb6cSDan Gohman #include "llvm/MC/MCExpr.h" 2218eafb6cSDan Gohman #include "llvm/MC/MCFixupKindInfo.h" 2318eafb6cSDan Gohman #include "llvm/MC/MCObjectWriter.h" 2418eafb6cSDan Gohman #include "llvm/MC/MCSectionWasm.h" 2518eafb6cSDan Gohman #include "llvm/MC/MCSymbolWasm.h" 2618eafb6cSDan Gohman #include "llvm/MC/MCValue.h" 2718eafb6cSDan Gohman #include "llvm/MC/MCWasmObjectWriter.h" 28d934cb88SDan Gohman #include "llvm/Support/Casting.h" 2918eafb6cSDan Gohman #include "llvm/Support/Debug.h" 3018eafb6cSDan Gohman #include "llvm/Support/ErrorHandling.h" 31d934cb88SDan Gohman #include "llvm/Support/LEB128.h" 3218eafb6cSDan Gohman #include "llvm/Support/StringSaver.h" 3318eafb6cSDan Gohman #include <vector> 3418eafb6cSDan Gohman 3518eafb6cSDan Gohman using namespace llvm; 3618eafb6cSDan Gohman 375e3d33a7SSam Clegg #define DEBUG_TYPE "mc" 3818eafb6cSDan Gohman 3918eafb6cSDan Gohman namespace { 409e15f359SSam Clegg 41d934cb88SDan Gohman // For patching purposes, we need to remember where each section starts, both 42d934cb88SDan Gohman // for patching up the section size field, and for patching up references to 43d934cb88SDan Gohman // locations within the section. 44d934cb88SDan Gohman struct SectionBookkeeping { 45d934cb88SDan Gohman // Where the size of the section is written. 46d934cb88SDan Gohman uint64_t SizeOffset; 47d934cb88SDan Gohman // Where the contents of the section starts (after the header). 48d934cb88SDan Gohman uint64_t ContentsOffset; 49d934cb88SDan Gohman }; 50d934cb88SDan Gohman 519e15f359SSam Clegg // The signature of a wasm function, in a struct capable of being used as a 529e15f359SSam Clegg // DenseMap key. 539e15f359SSam Clegg struct WasmFunctionType { 549e15f359SSam Clegg // Support empty and tombstone instances, needed by DenseMap. 559e15f359SSam Clegg enum { Plain, Empty, Tombstone } State; 569e15f359SSam Clegg 579e15f359SSam Clegg // The return types of the function. 589e15f359SSam Clegg SmallVector<wasm::ValType, 1> Returns; 599e15f359SSam Clegg 609e15f359SSam Clegg // The parameter types of the function. 619e15f359SSam Clegg SmallVector<wasm::ValType, 4> Params; 629e15f359SSam Clegg 639e15f359SSam Clegg WasmFunctionType() : State(Plain) {} 649e15f359SSam Clegg 659e15f359SSam Clegg bool operator==(const WasmFunctionType &Other) const { 669e15f359SSam Clegg return State == Other.State && Returns == Other.Returns && 679e15f359SSam Clegg Params == Other.Params; 689e15f359SSam Clegg } 699e15f359SSam Clegg }; 709e15f359SSam Clegg 719e15f359SSam Clegg // Traits for using WasmFunctionType in a DenseMap. 729e15f359SSam Clegg struct WasmFunctionTypeDenseMapInfo { 739e15f359SSam Clegg static WasmFunctionType getEmptyKey() { 749e15f359SSam Clegg WasmFunctionType FuncTy; 759e15f359SSam Clegg FuncTy.State = WasmFunctionType::Empty; 769e15f359SSam Clegg return FuncTy; 779e15f359SSam Clegg } 789e15f359SSam Clegg static WasmFunctionType getTombstoneKey() { 799e15f359SSam Clegg WasmFunctionType FuncTy; 809e15f359SSam Clegg FuncTy.State = WasmFunctionType::Tombstone; 819e15f359SSam Clegg return FuncTy; 829e15f359SSam Clegg } 839e15f359SSam Clegg static unsigned getHashValue(const WasmFunctionType &FuncTy) { 849e15f359SSam Clegg uintptr_t Value = FuncTy.State; 859e15f359SSam Clegg for (wasm::ValType Ret : FuncTy.Returns) 869e15f359SSam Clegg Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Ret)); 879e15f359SSam Clegg for (wasm::ValType Param : FuncTy.Params) 889e15f359SSam Clegg Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Param)); 899e15f359SSam Clegg return Value; 909e15f359SSam Clegg } 919e15f359SSam Clegg static bool isEqual(const WasmFunctionType &LHS, 929e15f359SSam Clegg const WasmFunctionType &RHS) { 939e15f359SSam Clegg return LHS == RHS; 949e15f359SSam Clegg } 959e15f359SSam Clegg }; 969e15f359SSam Clegg 977c395943SSam Clegg // A wasm data segment. A wasm binary contains only a single data section 987c395943SSam Clegg // but that can contain many segments, each with their own virtual location 997c395943SSam Clegg // in memory. Each MCSection data created by llvm is modeled as its own 1007c395943SSam Clegg // wasm data segment. 1017c395943SSam Clegg struct WasmDataSegment { 1027c395943SSam Clegg MCSectionWasm *Section; 103d95ed959SSam Clegg StringRef Name; 1047c395943SSam Clegg uint32_t Offset; 10563ebb813SSam Clegg uint32_t Alignment; 10663ebb813SSam Clegg uint32_t Flags; 1077c395943SSam Clegg SmallVector<char, 4> Data; 1087c395943SSam Clegg }; 1097c395943SSam Clegg 1109e15f359SSam Clegg // A wasm import to be written into the import section. 1119e15f359SSam Clegg struct WasmImport { 1129e15f359SSam Clegg StringRef ModuleName; 1139e15f359SSam Clegg StringRef FieldName; 1149e15f359SSam Clegg unsigned Kind; 1159e15f359SSam Clegg int32_t Type; 11632ce5ca0SDan Gohman bool IsMutable; 1179e15f359SSam Clegg }; 1189e15f359SSam Clegg 1199e15f359SSam Clegg // A wasm function to be written into the function section. 1209e15f359SSam Clegg struct WasmFunction { 1219e15f359SSam Clegg int32_t Type; 1229e15f359SSam Clegg const MCSymbolWasm *Sym; 1239e15f359SSam Clegg }; 1249e15f359SSam Clegg 1259e15f359SSam Clegg // A wasm export to be written into the export section. 1269e15f359SSam Clegg struct WasmExport { 1279e15f359SSam Clegg StringRef FieldName; 1289e15f359SSam Clegg unsigned Kind; 1299e15f359SSam Clegg uint32_t Index; 1309e15f359SSam Clegg }; 1319e15f359SSam Clegg 1329e15f359SSam Clegg // A wasm global to be written into the global section. 1339e15f359SSam Clegg struct WasmGlobal { 1349e15f359SSam Clegg wasm::ValType Type; 1359e15f359SSam Clegg bool IsMutable; 1369e15f359SSam Clegg bool HasImport; 1379e15f359SSam Clegg uint64_t InitialValue; 1389e15f359SSam Clegg uint32_t ImportIndex; 1399e15f359SSam Clegg }; 1409e15f359SSam Clegg 1416dc65e91SSam Clegg // Information about a single relocation. 1426dc65e91SSam Clegg struct WasmRelocationEntry { 1436dc65e91SSam Clegg uint64_t Offset; // Where is the relocation. 1446dc65e91SSam Clegg const MCSymbolWasm *Symbol; // The symbol to relocate with. 1456dc65e91SSam Clegg int64_t Addend; // A value to add to the symbol. 1466dc65e91SSam Clegg unsigned Type; // The type of the relocation. 147fe6414b0SSam Clegg const MCSectionWasm *FixupSection;// The section the relocation is targeting. 1486dc65e91SSam Clegg 1496dc65e91SSam Clegg WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol, 1506dc65e91SSam Clegg int64_t Addend, unsigned Type, 151fe6414b0SSam Clegg const MCSectionWasm *FixupSection) 1526dc65e91SSam Clegg : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type), 1536dc65e91SSam Clegg FixupSection(FixupSection) {} 1546dc65e91SSam Clegg 155acd7d2b0SSam Clegg bool hasAddend() const { 156acd7d2b0SSam Clegg switch (Type) { 15713a2e899SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB: 15813a2e899SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: 15913a2e899SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32: 160acd7d2b0SSam Clegg return true; 161acd7d2b0SSam Clegg default: 162acd7d2b0SSam Clegg return false; 163acd7d2b0SSam Clegg } 164acd7d2b0SSam Clegg } 165acd7d2b0SSam Clegg 1666dc65e91SSam Clegg void print(raw_ostream &Out) const { 1679bf73c07SSam Clegg Out << "Off=" << Offset << ", Sym=" << *Symbol << ", Addend=" << Addend 168759631c7SSam Clegg << ", Type=" << Type 169759631c7SSam Clegg << ", FixupSection=" << FixupSection->getSectionName(); 1706dc65e91SSam Clegg } 171b7787fd0SSam Clegg 172615eb470SAaron Ballman #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 173b7787fd0SSam Clegg LLVM_DUMP_METHOD void dump() const { print(dbgs()); } 174b7787fd0SSam Clegg #endif 1756dc65e91SSam Clegg }; 1766dc65e91SSam Clegg 1771fb8daa6SSam Clegg #if !defined(NDEBUG) 1787f055deeSSam Clegg raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) { 179b7787fd0SSam Clegg Rel.print(OS); 180b7787fd0SSam Clegg return OS; 181b7787fd0SSam Clegg } 1821fb8daa6SSam Clegg #endif 183b7787fd0SSam Clegg 18418eafb6cSDan Gohman class WasmObjectWriter : public MCObjectWriter { 18518eafb6cSDan Gohman /// Helper struct for containing some precomputed information on symbols. 18618eafb6cSDan Gohman struct WasmSymbolData { 18718eafb6cSDan Gohman const MCSymbolWasm *Symbol; 18818eafb6cSDan Gohman StringRef Name; 18918eafb6cSDan Gohman 19018eafb6cSDan Gohman // Support lexicographic sorting. 19118eafb6cSDan Gohman bool operator<(const WasmSymbolData &RHS) const { return Name < RHS.Name; } 19218eafb6cSDan Gohman }; 19318eafb6cSDan Gohman 19418eafb6cSDan Gohman /// The target specific Wasm writer instance. 19518eafb6cSDan Gohman std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter; 19618eafb6cSDan Gohman 197d934cb88SDan Gohman // Relocations for fixing up references in the code section. 198d934cb88SDan Gohman std::vector<WasmRelocationEntry> CodeRelocations; 199d934cb88SDan Gohman 200d934cb88SDan Gohman // Relocations for fixing up references in the data section. 201d934cb88SDan Gohman std::vector<WasmRelocationEntry> DataRelocations; 202d934cb88SDan Gohman 203d934cb88SDan Gohman // Index values to use for fixing up call_indirect type indices. 204acd7d2b0SSam Clegg // Maps function symbols to the index of the type of the function 205acd7d2b0SSam Clegg DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices; 206d99f6078SSam Clegg // Maps function symbols to the table element index space. Used 207d99f6078SSam Clegg // for TABLE_INDEX relocation types (i.e. address taken functions). 208d99f6078SSam Clegg DenseMap<const MCSymbolWasm *, uint32_t> IndirectSymbolIndices; 209d99f6078SSam Clegg // Maps function/global symbols to the function/global index space. 210acd7d2b0SSam Clegg DenseMap<const MCSymbolWasm *, uint32_t> SymbolIndices; 211acd7d2b0SSam Clegg 212acd7d2b0SSam Clegg DenseMap<WasmFunctionType, int32_t, WasmFunctionTypeDenseMapInfo> 213acd7d2b0SSam Clegg FunctionTypeIndices; 2145e3d33a7SSam Clegg SmallVector<WasmFunctionType, 4> FunctionTypes; 2157c395943SSam Clegg SmallVector<WasmGlobal, 4> Globals; 2167c395943SSam Clegg unsigned NumGlobalImports = 0; 217d934cb88SDan Gohman 21818eafb6cSDan Gohman // TargetObjectWriter wrappers. 21918eafb6cSDan Gohman bool is64Bit() const { return TargetObjectWriter->is64Bit(); } 220ae03c1e7SSam Clegg unsigned getRelocType(const MCValue &Target, const MCFixup &Fixup) const { 221ae03c1e7SSam Clegg return TargetObjectWriter->getRelocType(Target, Fixup); 22218eafb6cSDan Gohman } 22318eafb6cSDan Gohman 224d934cb88SDan Gohman void startSection(SectionBookkeeping &Section, unsigned SectionId, 225d934cb88SDan Gohman const char *Name = nullptr); 226d934cb88SDan Gohman void endSection(SectionBookkeeping &Section); 227d934cb88SDan Gohman 22818eafb6cSDan Gohman public: 2291301a878SLang Hames WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW, 2301301a878SLang Hames raw_pwrite_stream &OS) 2311301a878SLang Hames : MCObjectWriter(OS, /*IsLittleEndian=*/true), 2321301a878SLang Hames TargetObjectWriter(std::move(MOTW)) {} 23318eafb6cSDan Gohman 234d934cb88SDan Gohman private: 23518eafb6cSDan Gohman ~WasmObjectWriter() override; 23618eafb6cSDan Gohman 237acd7d2b0SSam Clegg void reset() override { 238acd7d2b0SSam Clegg CodeRelocations.clear(); 239acd7d2b0SSam Clegg DataRelocations.clear(); 240acd7d2b0SSam Clegg TypeIndices.clear(); 241acd7d2b0SSam Clegg SymbolIndices.clear(); 242d99f6078SSam Clegg IndirectSymbolIndices.clear(); 243acd7d2b0SSam Clegg FunctionTypeIndices.clear(); 2445e3d33a7SSam Clegg FunctionTypes.clear(); 2457c395943SSam Clegg Globals.clear(); 246acd7d2b0SSam Clegg MCObjectWriter::reset(); 2477c395943SSam Clegg NumGlobalImports = 0; 248acd7d2b0SSam Clegg } 249acd7d2b0SSam Clegg 25018eafb6cSDan Gohman void writeHeader(const MCAssembler &Asm); 25118eafb6cSDan Gohman 25218eafb6cSDan Gohman void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout, 25318eafb6cSDan Gohman const MCFragment *Fragment, const MCFixup &Fixup, 254ceecfe5bSRafael Espindola MCValue Target, uint64_t &FixedValue) override; 25518eafb6cSDan Gohman 25618eafb6cSDan Gohman void executePostLayoutBinding(MCAssembler &Asm, 25718eafb6cSDan Gohman const MCAsmLayout &Layout) override; 25818eafb6cSDan Gohman 25918eafb6cSDan Gohman void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override; 2609e15f359SSam Clegg 261b7787fd0SSam Clegg void writeString(const StringRef Str) { 262b7787fd0SSam Clegg encodeULEB128(Str.size(), getStream()); 263b7787fd0SSam Clegg writeBytes(Str); 264b7787fd0SSam Clegg } 265b7787fd0SSam Clegg 2669e15f359SSam Clegg void writeValueType(wasm::ValType Ty) { 2679e15f359SSam Clegg encodeSLEB128(int32_t(Ty), getStream()); 2689e15f359SSam Clegg } 2699e15f359SSam Clegg 270457fb0b4SSam Clegg void writeTypeSection(ArrayRef<WasmFunctionType> FunctionTypes); 271f950b24aSSam Clegg void writeImportSection(ArrayRef<WasmImport> Imports, uint32_t DataSize, 272f950b24aSSam Clegg uint32_t NumElements); 273457fb0b4SSam Clegg void writeFunctionSection(ArrayRef<WasmFunction> Functions); 2747c395943SSam Clegg void writeGlobalSection(); 275457fb0b4SSam Clegg void writeExportSection(ArrayRef<WasmExport> Exports); 276457fb0b4SSam Clegg void writeElemSection(ArrayRef<uint32_t> TableElems); 2779e15f359SSam Clegg void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout, 278457fb0b4SSam Clegg ArrayRef<WasmFunction> Functions); 279457fb0b4SSam Clegg void writeDataSection(ArrayRef<WasmDataSegment> Segments); 280457fb0b4SSam Clegg void writeNameSection(ArrayRef<WasmFunction> Functions, 281457fb0b4SSam Clegg ArrayRef<WasmImport> Imports, 2829e15f359SSam Clegg uint32_t NumFuncImports); 283acd7d2b0SSam Clegg void writeCodeRelocSection(); 2847c395943SSam Clegg void writeDataRelocSection(); 28531a2c809SSam Clegg void writeLinkingMetaDataSection( 28631a2c809SSam Clegg ArrayRef<WasmDataSegment> Segments, uint32_t DataSize, 287bafe6902SSam Clegg const SmallVector<std::pair<StringRef, uint32_t>, 4> &SymbolFlags, 288bafe6902SSam Clegg const SmallVector<std::pair<uint16_t, uint32_t>, 2> &InitFuncs); 289acd7d2b0SSam Clegg 2907c395943SSam Clegg uint32_t getProvisionalValue(const WasmRelocationEntry &RelEntry); 291acd7d2b0SSam Clegg void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations, 292acd7d2b0SSam Clegg uint64_t ContentsOffset); 293acd7d2b0SSam Clegg 2947c395943SSam Clegg void writeRelocations(ArrayRef<WasmRelocationEntry> Relocations); 295acd7d2b0SSam Clegg uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry); 2965e3d33a7SSam Clegg uint32_t getFunctionType(const MCSymbolWasm& Symbol); 2975e3d33a7SSam Clegg uint32_t registerFunctionType(const MCSymbolWasm& Symbol); 29818eafb6cSDan Gohman }; 2999e15f359SSam Clegg 30018eafb6cSDan Gohman } // end anonymous namespace 30118eafb6cSDan Gohman 30218eafb6cSDan Gohman WasmObjectWriter::~WasmObjectWriter() {} 30318eafb6cSDan Gohman 304d934cb88SDan Gohman // Write out a section header and a patchable section size field. 305d934cb88SDan Gohman void WasmObjectWriter::startSection(SectionBookkeeping &Section, 306d934cb88SDan Gohman unsigned SectionId, 307d934cb88SDan Gohman const char *Name) { 308d934cb88SDan Gohman assert((Name != nullptr) == (SectionId == wasm::WASM_SEC_CUSTOM) && 309d934cb88SDan Gohman "Only custom sections can have names"); 310d934cb88SDan Gohman 311b7787fd0SSam Clegg DEBUG(dbgs() << "startSection " << SectionId << ": " << Name << "\n"); 312e2688c43SDerek Schuff encodeULEB128(SectionId, getStream()); 313d934cb88SDan Gohman 314d934cb88SDan Gohman Section.SizeOffset = getStream().tell(); 315d934cb88SDan Gohman 316d934cb88SDan Gohman // The section size. We don't know the size yet, so reserve enough space 317d934cb88SDan Gohman // for any 32-bit value; we'll patch it later. 318d934cb88SDan Gohman encodeULEB128(UINT32_MAX, getStream()); 319d934cb88SDan Gohman 320d934cb88SDan Gohman // The position where the section starts, for measuring its size. 321d934cb88SDan Gohman Section.ContentsOffset = getStream().tell(); 322d934cb88SDan Gohman 323d934cb88SDan Gohman // Custom sections in wasm also have a string identifier. 324d934cb88SDan Gohman if (SectionId == wasm::WASM_SEC_CUSTOM) { 325b7787fd0SSam Clegg assert(Name); 326b7787fd0SSam Clegg writeString(StringRef(Name)); 327d934cb88SDan Gohman } 328d934cb88SDan Gohman } 329d934cb88SDan Gohman 330d934cb88SDan Gohman // Now that the section is complete and we know how big it is, patch up the 331d934cb88SDan Gohman // section size field at the start of the section. 332d934cb88SDan Gohman void WasmObjectWriter::endSection(SectionBookkeeping &Section) { 333d934cb88SDan Gohman uint64_t Size = getStream().tell() - Section.ContentsOffset; 334d934cb88SDan Gohman if (uint32_t(Size) != Size) 335d934cb88SDan Gohman report_fatal_error("section size does not fit in a uint32_t"); 336d934cb88SDan Gohman 337b7787fd0SSam Clegg DEBUG(dbgs() << "endSection size=" << Size << "\n"); 338d934cb88SDan Gohman 339d934cb88SDan Gohman // Write the final section size to the payload_len field, which follows 340d934cb88SDan Gohman // the section id byte. 341d934cb88SDan Gohman uint8_t Buffer[16]; 34266a99e41SSam Clegg unsigned SizeLen = encodeULEB128(Size, Buffer, 5); 343d934cb88SDan Gohman assert(SizeLen == 5); 344d934cb88SDan Gohman getStream().pwrite((char *)Buffer, SizeLen, Section.SizeOffset); 345d934cb88SDan Gohman } 346d934cb88SDan Gohman 34718eafb6cSDan Gohman // Emit the Wasm header. 34818eafb6cSDan Gohman void WasmObjectWriter::writeHeader(const MCAssembler &Asm) { 3497ea5adffSDan Gohman writeBytes(StringRef(wasm::WasmMagic, sizeof(wasm::WasmMagic))); 3507ea5adffSDan Gohman writeLE32(wasm::WasmVersion); 35118eafb6cSDan Gohman } 35218eafb6cSDan Gohman 35318eafb6cSDan Gohman void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm, 35418eafb6cSDan Gohman const MCAsmLayout &Layout) { 35518eafb6cSDan Gohman } 35618eafb6cSDan Gohman 35718eafb6cSDan Gohman void WasmObjectWriter::recordRelocation(MCAssembler &Asm, 35818eafb6cSDan Gohman const MCAsmLayout &Layout, 35918eafb6cSDan Gohman const MCFragment *Fragment, 36018eafb6cSDan Gohman const MCFixup &Fixup, MCValue Target, 361ceecfe5bSRafael Espindola uint64_t &FixedValue) { 362ceecfe5bSRafael Espindola MCAsmBackend &Backend = Asm.getBackend(); 363ceecfe5bSRafael Espindola bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags & 364ceecfe5bSRafael Espindola MCFixupKindInfo::FKF_IsPCRel; 365fe6414b0SSam Clegg const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent()); 366d934cb88SDan Gohman uint64_t C = Target.getConstant(); 367d934cb88SDan Gohman uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset(); 368d934cb88SDan Gohman MCContext &Ctx = Asm.getContext(); 369d934cb88SDan Gohman 370bafe6902SSam Clegg // The .init_array isn't translated as data, so don't do relocations in it. 371bafe6902SSam Clegg if (FixupSection.getSectionName().startswith(".init_array")) 372bafe6902SSam Clegg return; 373bafe6902SSam Clegg 374d934cb88SDan Gohman if (const MCSymbolRefExpr *RefB = Target.getSymB()) { 375d934cb88SDan Gohman assert(RefB->getKind() == MCSymbolRefExpr::VK_None && 376d934cb88SDan Gohman "Should not have constructed this"); 377d934cb88SDan Gohman 378d934cb88SDan Gohman // Let A, B and C being the components of Target and R be the location of 379d934cb88SDan Gohman // the fixup. If the fixup is not pcrel, we want to compute (A - B + C). 380d934cb88SDan Gohman // If it is pcrel, we want to compute (A - B + C - R). 381d934cb88SDan Gohman 382d934cb88SDan Gohman // In general, Wasm has no relocations for -B. It can only represent (A + C) 383d934cb88SDan Gohman // or (A + C - R). If B = R + K and the relocation is not pcrel, we can 384d934cb88SDan Gohman // replace B to implement it: (A - R - K + C) 385d934cb88SDan Gohman if (IsPCRel) { 386d934cb88SDan Gohman Ctx.reportError( 387d934cb88SDan Gohman Fixup.getLoc(), 388d934cb88SDan Gohman "No relocation available to represent this relative expression"); 389d934cb88SDan Gohman return; 390d934cb88SDan Gohman } 391d934cb88SDan Gohman 392d934cb88SDan Gohman const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol()); 393d934cb88SDan Gohman 394d934cb88SDan Gohman if (SymB.isUndefined()) { 395d934cb88SDan Gohman Ctx.reportError(Fixup.getLoc(), 396d934cb88SDan Gohman Twine("symbol '") + SymB.getName() + 397d934cb88SDan Gohman "' can not be undefined in a subtraction expression"); 398d934cb88SDan Gohman return; 399d934cb88SDan Gohman } 400d934cb88SDan Gohman 401d934cb88SDan Gohman assert(!SymB.isAbsolute() && "Should have been folded"); 402d934cb88SDan Gohman const MCSection &SecB = SymB.getSection(); 403d934cb88SDan Gohman if (&SecB != &FixupSection) { 404d934cb88SDan Gohman Ctx.reportError(Fixup.getLoc(), 405d934cb88SDan Gohman "Cannot represent a difference across sections"); 406d934cb88SDan Gohman return; 407d934cb88SDan Gohman } 408d934cb88SDan Gohman 409d934cb88SDan Gohman uint64_t SymBOffset = Layout.getSymbolOffset(SymB); 410d934cb88SDan Gohman uint64_t K = SymBOffset - FixupOffset; 411d934cb88SDan Gohman IsPCRel = true; 412d934cb88SDan Gohman C -= K; 413d934cb88SDan Gohman } 414d934cb88SDan Gohman 415d934cb88SDan Gohman // We either rejected the fixup or folded B into C at this point. 416d934cb88SDan Gohman const MCSymbolRefExpr *RefA = Target.getSymA(); 417d934cb88SDan Gohman const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr; 418d934cb88SDan Gohman 419d934cb88SDan Gohman if (SymA && SymA->isVariable()) { 420d934cb88SDan Gohman const MCExpr *Expr = SymA->getVariableValue(); 4216ad8f190SSam Clegg const auto *Inner = cast<MCSymbolRefExpr>(Expr); 4226ad8f190SSam Clegg if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF) 4236ad8f190SSam Clegg llvm_unreachable("weakref used in reloc not yet implemented"); 424d934cb88SDan Gohman } 425d934cb88SDan Gohman 426d934cb88SDan Gohman // Put any constant offset in an addend. Offsets can be negative, and 427d934cb88SDan Gohman // LLVM expects wrapping, in contrast to wasm's immediates which can't 428d934cb88SDan Gohman // be negative and don't wrap. 429d934cb88SDan Gohman FixedValue = 0; 430d934cb88SDan Gohman 4316ad8f190SSam Clegg if (SymA) 432d934cb88SDan Gohman SymA->setUsedInReloc(); 433d934cb88SDan Gohman 434ae03c1e7SSam Clegg assert(!IsPCRel); 4359d24fb7fSSam Clegg assert(SymA); 4369d24fb7fSSam Clegg 437ae03c1e7SSam Clegg unsigned Type = getRelocType(Target, Fixup); 438ae03c1e7SSam Clegg 439d934cb88SDan Gohman WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection); 440b7787fd0SSam Clegg DEBUG(dbgs() << "WasmReloc: " << Rec << "\n"); 441d934cb88SDan Gohman 44212fd3da9SSam Clegg if (FixupSection.isWasmData()) 443d934cb88SDan Gohman DataRelocations.push_back(Rec); 44412fd3da9SSam Clegg else if (FixupSection.getKind().isText()) 44512fd3da9SSam Clegg CodeRelocations.push_back(Rec); 44612fd3da9SSam Clegg else if (!FixupSection.getKind().isMetadata()) 44712fd3da9SSam Clegg // TODO(sbc): Add support for debug sections. 44812fd3da9SSam Clegg llvm_unreachable("unexpected section type"); 449d934cb88SDan Gohman } 450d934cb88SDan Gohman 451d934cb88SDan Gohman // Write X as an (unsigned) LEB value at offset Offset in Stream, padded 452d934cb88SDan Gohman // to allow patching. 453d934cb88SDan Gohman static void 454d934cb88SDan Gohman WritePatchableLEB(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) { 455d934cb88SDan Gohman uint8_t Buffer[5]; 45666a99e41SSam Clegg unsigned SizeLen = encodeULEB128(X, Buffer, 5); 457d934cb88SDan Gohman assert(SizeLen == 5); 458d934cb88SDan Gohman Stream.pwrite((char *)Buffer, SizeLen, Offset); 459d934cb88SDan Gohman } 460d934cb88SDan Gohman 461d934cb88SDan Gohman // Write X as an signed LEB value at offset Offset in Stream, padded 462d934cb88SDan Gohman // to allow patching. 463d934cb88SDan Gohman static void 464d934cb88SDan Gohman WritePatchableSLEB(raw_pwrite_stream &Stream, int32_t X, uint64_t Offset) { 465d934cb88SDan Gohman uint8_t Buffer[5]; 46666a99e41SSam Clegg unsigned SizeLen = encodeSLEB128(X, Buffer, 5); 467d934cb88SDan Gohman assert(SizeLen == 5); 468d934cb88SDan Gohman Stream.pwrite((char *)Buffer, SizeLen, Offset); 469d934cb88SDan Gohman } 470d934cb88SDan Gohman 471d934cb88SDan Gohman // Write X as a plain integer value at offset Offset in Stream. 472d934cb88SDan Gohman static void WriteI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) { 473d934cb88SDan Gohman uint8_t Buffer[4]; 474d934cb88SDan Gohman support::endian::write32le(Buffer, X); 475d934cb88SDan Gohman Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset); 476d934cb88SDan Gohman } 477d934cb88SDan Gohman 478aff1c4dfSSam Clegg static const MCSymbolWasm* ResolveSymbol(const MCSymbolWasm& Symbol) { 479aff1c4dfSSam Clegg if (Symbol.isVariable()) { 480aff1c4dfSSam Clegg const MCExpr *Expr = Symbol.getVariableValue(); 481aff1c4dfSSam Clegg auto *Inner = cast<MCSymbolRefExpr>(Expr); 482aff1c4dfSSam Clegg return cast<MCSymbolWasm>(&Inner->getSymbol()); 483aff1c4dfSSam Clegg } 484aff1c4dfSSam Clegg return &Symbol; 485aff1c4dfSSam Clegg } 486aff1c4dfSSam Clegg 487d934cb88SDan Gohman // Compute a value to write into the code at the location covered 488d934cb88SDan Gohman // by RelEntry. This value isn't used by the static linker, since 489d934cb88SDan Gohman // we have addends; it just serves to make the code more readable 490d934cb88SDan Gohman // and to make standalone wasm modules directly usable. 4917c395943SSam Clegg uint32_t 4927c395943SSam Clegg WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) { 493aff1c4dfSSam Clegg const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol); 494d934cb88SDan Gohman 495270ed1b3SSam Clegg // For undefined symbols, use zero 496b7787fd0SSam Clegg if (!Sym->isDefined(/*SetUsed=*/false)) 497270ed1b3SSam Clegg return 0; 498d934cb88SDan Gohman 4997c395943SSam Clegg uint32_t GlobalIndex = SymbolIndices[Sym]; 5007c395943SSam Clegg const WasmGlobal& Global = Globals[GlobalIndex - NumGlobalImports]; 5017c395943SSam Clegg uint64_t Address = Global.InitialValue + RelEntry.Addend; 502d934cb88SDan Gohman 503d934cb88SDan Gohman // Ignore overflow. LLVM allows address arithmetic to silently wrap. 504d934cb88SDan Gohman uint32_t Value = Address; 505d934cb88SDan Gohman 506d934cb88SDan Gohman return Value; 507d934cb88SDan Gohman } 508d934cb88SDan Gohman 509759631c7SSam Clegg static void addData(SmallVectorImpl<char> &DataBytes, 51063ebb813SSam Clegg MCSectionWasm &DataSection) { 511759631c7SSam Clegg DEBUG(errs() << "addData: " << DataSection.getSectionName() << "\n"); 512759631c7SSam Clegg 51363ebb813SSam Clegg DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment())); 51463ebb813SSam Clegg 515c55d13f4SSam Clegg size_t LastFragmentSize = 0; 516759631c7SSam Clegg for (const MCFragment &Frag : DataSection) { 517759631c7SSam Clegg if (Frag.hasInstructions()) 518759631c7SSam Clegg report_fatal_error("only data supported in data sections"); 519759631c7SSam Clegg 520759631c7SSam Clegg if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) { 521759631c7SSam Clegg if (Align->getValueSize() != 1) 522759631c7SSam Clegg report_fatal_error("only byte values supported for alignment"); 523759631c7SSam Clegg // If nops are requested, use zeros, as this is the data section. 524759631c7SSam Clegg uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue(); 525759631c7SSam Clegg uint64_t Size = std::min<uint64_t>(alignTo(DataBytes.size(), 526759631c7SSam Clegg Align->getAlignment()), 527759631c7SSam Clegg DataBytes.size() + 528759631c7SSam Clegg Align->getMaxBytesToEmit()); 529759631c7SSam Clegg DataBytes.resize(Size, Value); 530759631c7SSam Clegg } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) { 531*d707c370SRafael Espindola int64_t Size; 532*d707c370SRafael Espindola if (!Fill->getSize().evaluateAsAbsolute(Size)) 533*d707c370SRafael Espindola llvm_unreachable("The fill should be an assembler constant"); 534*d707c370SRafael Espindola DataBytes.insert(DataBytes.end(), Size, Fill->getValue()); 535759631c7SSam Clegg } else { 536759631c7SSam Clegg const auto &DataFrag = cast<MCDataFragment>(Frag); 537759631c7SSam Clegg const SmallVectorImpl<char> &Contents = DataFrag.getContents(); 538759631c7SSam Clegg 539759631c7SSam Clegg DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end()); 540c55d13f4SSam Clegg LastFragmentSize = Contents.size(); 541759631c7SSam Clegg } 542759631c7SSam Clegg } 543759631c7SSam Clegg 544c55d13f4SSam Clegg // Don't allow empty segments, or segments that end with zero-sized 545c55d13f4SSam Clegg // fragment, otherwise the linker cannot map symbols to a unique 546c55d13f4SSam Clegg // data segment. This can be triggered by zero-sized structs 547c55d13f4SSam Clegg // See: test/MC/WebAssembly/bss.ll 548c55d13f4SSam Clegg if (LastFragmentSize == 0) 549c55d13f4SSam Clegg DataBytes.resize(DataBytes.size() + 1); 550759631c7SSam Clegg DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n"); 551759631c7SSam Clegg } 552759631c7SSam Clegg 553acd7d2b0SSam Clegg uint32_t WasmObjectWriter::getRelocationIndexValue( 554acd7d2b0SSam Clegg const WasmRelocationEntry &RelEntry) { 555acd7d2b0SSam Clegg switch (RelEntry.Type) { 556acd7d2b0SSam Clegg case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB: 557acd7d2b0SSam Clegg case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: 558b7787fd0SSam Clegg if (!IndirectSymbolIndices.count(RelEntry.Symbol)) 5596006e091SSam Clegg report_fatal_error("symbol not found in table index space: " + 560b7787fd0SSam Clegg RelEntry.Symbol->getName()); 561d99f6078SSam Clegg return IndirectSymbolIndices[RelEntry.Symbol]; 562d99f6078SSam Clegg case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB: 5639d24fb7fSSam Clegg case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB: 56413a2e899SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB: 56513a2e899SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: 56613a2e899SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32: 567b7787fd0SSam Clegg if (!SymbolIndices.count(RelEntry.Symbol)) 5686006e091SSam Clegg report_fatal_error("symbol not found in function/global index space: " + 569b7787fd0SSam Clegg RelEntry.Symbol->getName()); 570acd7d2b0SSam Clegg return SymbolIndices[RelEntry.Symbol]; 571acd7d2b0SSam Clegg case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB: 572b7787fd0SSam Clegg if (!TypeIndices.count(RelEntry.Symbol)) 573b7787fd0SSam Clegg report_fatal_error("symbol not found in type index space: " + 574b7787fd0SSam Clegg RelEntry.Symbol->getName()); 575acd7d2b0SSam Clegg return TypeIndices[RelEntry.Symbol]; 576acd7d2b0SSam Clegg default: 577acd7d2b0SSam Clegg llvm_unreachable("invalid relocation type"); 578acd7d2b0SSam Clegg } 579acd7d2b0SSam Clegg } 580acd7d2b0SSam Clegg 581d934cb88SDan Gohman // Apply the portions of the relocation records that we can handle ourselves 582d934cb88SDan Gohman // directly. 583acd7d2b0SSam Clegg void WasmObjectWriter::applyRelocations( 584acd7d2b0SSam Clegg ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) { 585acd7d2b0SSam Clegg raw_pwrite_stream &Stream = getStream(); 586d934cb88SDan Gohman for (const WasmRelocationEntry &RelEntry : Relocations) { 587d934cb88SDan Gohman uint64_t Offset = ContentsOffset + 588d934cb88SDan Gohman RelEntry.FixupSection->getSectionOffset() + 589d934cb88SDan Gohman RelEntry.Offset; 590d934cb88SDan Gohman 591b7787fd0SSam Clegg DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n"); 592acd7d2b0SSam Clegg switch (RelEntry.Type) { 593acd7d2b0SSam Clegg case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB: 594acd7d2b0SSam Clegg case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB: 5959d24fb7fSSam Clegg case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB: 5969d24fb7fSSam Clegg case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB: { 597acd7d2b0SSam Clegg uint32_t Index = getRelocationIndexValue(RelEntry); 598acd7d2b0SSam Clegg WritePatchableSLEB(Stream, Index, Offset); 599d934cb88SDan Gohman break; 600d934cb88SDan Gohman } 601acd7d2b0SSam Clegg case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: { 602acd7d2b0SSam Clegg uint32_t Index = getRelocationIndexValue(RelEntry); 603acd7d2b0SSam Clegg WriteI32(Stream, Index, Offset); 604d934cb88SDan Gohman break; 605d934cb88SDan Gohman } 60613a2e899SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: { 6077c395943SSam Clegg uint32_t Value = getProvisionalValue(RelEntry); 608d934cb88SDan Gohman WritePatchableSLEB(Stream, Value, Offset); 609d934cb88SDan Gohman break; 610d934cb88SDan Gohman } 61113a2e899SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB: { 6127c395943SSam Clegg uint32_t Value = getProvisionalValue(RelEntry); 613d934cb88SDan Gohman WritePatchableLEB(Stream, Value, Offset); 614d934cb88SDan Gohman break; 615d934cb88SDan Gohman } 61613a2e899SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32: { 6177c395943SSam Clegg uint32_t Value = getProvisionalValue(RelEntry); 618d934cb88SDan Gohman WriteI32(Stream, Value, Offset); 619d934cb88SDan Gohman break; 620d934cb88SDan Gohman } 621d934cb88SDan Gohman default: 6229d24fb7fSSam Clegg llvm_unreachable("invalid relocation type"); 623d934cb88SDan Gohman } 624d934cb88SDan Gohman } 62518eafb6cSDan Gohman } 62618eafb6cSDan Gohman 627acd7d2b0SSam Clegg // Write out the portions of the relocation records that the linker will 628970d02c4SDan Gohman // need to handle. 629acd7d2b0SSam Clegg void WasmObjectWriter::writeRelocations( 6307c395943SSam Clegg ArrayRef<WasmRelocationEntry> Relocations) { 631acd7d2b0SSam Clegg raw_pwrite_stream &Stream = getStream(); 632acd7d2b0SSam Clegg for (const WasmRelocationEntry& RelEntry : Relocations) { 633970d02c4SDan Gohman 634acd7d2b0SSam Clegg uint64_t Offset = RelEntry.Offset + 6357c395943SSam Clegg RelEntry.FixupSection->getSectionOffset(); 636acd7d2b0SSam Clegg uint32_t Index = getRelocationIndexValue(RelEntry); 637970d02c4SDan Gohman 638acd7d2b0SSam Clegg encodeULEB128(RelEntry.Type, Stream); 639970d02c4SDan Gohman encodeULEB128(Offset, Stream); 640acd7d2b0SSam Clegg encodeULEB128(Index, Stream); 641acd7d2b0SSam Clegg if (RelEntry.hasAddend()) 642acd7d2b0SSam Clegg encodeSLEB128(RelEntry.Addend, Stream); 643970d02c4SDan Gohman } 644970d02c4SDan Gohman } 645970d02c4SDan Gohman 6469e15f359SSam Clegg void WasmObjectWriter::writeTypeSection( 647457fb0b4SSam Clegg ArrayRef<WasmFunctionType> FunctionTypes) { 6489e15f359SSam Clegg if (FunctionTypes.empty()) 6499e15f359SSam Clegg return; 6509e15f359SSam Clegg 6519e15f359SSam Clegg SectionBookkeeping Section; 6529e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_TYPE); 6539e15f359SSam Clegg 6549e15f359SSam Clegg encodeULEB128(FunctionTypes.size(), getStream()); 6559e15f359SSam Clegg 6569e15f359SSam Clegg for (const WasmFunctionType &FuncTy : FunctionTypes) { 6579e15f359SSam Clegg encodeSLEB128(wasm::WASM_TYPE_FUNC, getStream()); 6589e15f359SSam Clegg encodeULEB128(FuncTy.Params.size(), getStream()); 6599e15f359SSam Clegg for (wasm::ValType Ty : FuncTy.Params) 6609e15f359SSam Clegg writeValueType(Ty); 6619e15f359SSam Clegg encodeULEB128(FuncTy.Returns.size(), getStream()); 6629e15f359SSam Clegg for (wasm::ValType Ty : FuncTy.Returns) 6639e15f359SSam Clegg writeValueType(Ty); 6649e15f359SSam Clegg } 6659e15f359SSam Clegg 6669e15f359SSam Clegg endSection(Section); 6679e15f359SSam Clegg } 6689e15f359SSam Clegg 669f950b24aSSam Clegg void WasmObjectWriter::writeImportSection(ArrayRef<WasmImport> Imports, 670f950b24aSSam Clegg uint32_t DataSize, 671f950b24aSSam Clegg uint32_t NumElements) { 6729e15f359SSam Clegg if (Imports.empty()) 6739e15f359SSam Clegg return; 6749e15f359SSam Clegg 675f950b24aSSam Clegg uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize; 676f950b24aSSam Clegg 6779e15f359SSam Clegg SectionBookkeeping Section; 6789e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_IMPORT); 6799e15f359SSam Clegg 6809e15f359SSam Clegg encodeULEB128(Imports.size(), getStream()); 6819e15f359SSam Clegg for (const WasmImport &Import : Imports) { 682b7787fd0SSam Clegg writeString(Import.ModuleName); 683b7787fd0SSam Clegg writeString(Import.FieldName); 6849e15f359SSam Clegg 6859e15f359SSam Clegg encodeULEB128(Import.Kind, getStream()); 6869e15f359SSam Clegg 6879e15f359SSam Clegg switch (Import.Kind) { 6889e15f359SSam Clegg case wasm::WASM_EXTERNAL_FUNCTION: 6899e15f359SSam Clegg encodeULEB128(Import.Type, getStream()); 6909e15f359SSam Clegg break; 6919e15f359SSam Clegg case wasm::WASM_EXTERNAL_GLOBAL: 6929e15f359SSam Clegg encodeSLEB128(int32_t(Import.Type), getStream()); 69332ce5ca0SDan Gohman encodeULEB128(int32_t(Import.IsMutable), getStream()); 6949e15f359SSam Clegg break; 695f950b24aSSam Clegg case wasm::WASM_EXTERNAL_MEMORY: 696f950b24aSSam Clegg encodeULEB128(0, getStream()); // flags 697f950b24aSSam Clegg encodeULEB128(NumPages, getStream()); // initial 698f950b24aSSam Clegg break; 699f950b24aSSam Clegg case wasm::WASM_EXTERNAL_TABLE: 700f950b24aSSam Clegg encodeSLEB128(int32_t(Import.Type), getStream()); 701f950b24aSSam Clegg encodeULEB128(0, getStream()); // flags 702f950b24aSSam Clegg encodeULEB128(NumElements, getStream()); // initial 703f950b24aSSam Clegg break; 7049e15f359SSam Clegg default: 7059e15f359SSam Clegg llvm_unreachable("unsupported import kind"); 7069e15f359SSam Clegg } 7079e15f359SSam Clegg } 7089e15f359SSam Clegg 7099e15f359SSam Clegg endSection(Section); 7109e15f359SSam Clegg } 7119e15f359SSam Clegg 712457fb0b4SSam Clegg void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) { 7139e15f359SSam Clegg if (Functions.empty()) 7149e15f359SSam Clegg return; 7159e15f359SSam Clegg 7169e15f359SSam Clegg SectionBookkeeping Section; 7179e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_FUNCTION); 7189e15f359SSam Clegg 7199e15f359SSam Clegg encodeULEB128(Functions.size(), getStream()); 7209e15f359SSam Clegg for (const WasmFunction &Func : Functions) 7219e15f359SSam Clegg encodeULEB128(Func.Type, getStream()); 7229e15f359SSam Clegg 7239e15f359SSam Clegg endSection(Section); 7249e15f359SSam Clegg } 7259e15f359SSam Clegg 7267c395943SSam Clegg void WasmObjectWriter::writeGlobalSection() { 7279e15f359SSam Clegg if (Globals.empty()) 7289e15f359SSam Clegg return; 7299e15f359SSam Clegg 7309e15f359SSam Clegg SectionBookkeeping Section; 7319e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_GLOBAL); 7329e15f359SSam Clegg 7339e15f359SSam Clegg encodeULEB128(Globals.size(), getStream()); 7349e15f359SSam Clegg for (const WasmGlobal &Global : Globals) { 7359e15f359SSam Clegg writeValueType(Global.Type); 7369e15f359SSam Clegg write8(Global.IsMutable); 7379e15f359SSam Clegg 7389e15f359SSam Clegg if (Global.HasImport) { 7399e15f359SSam Clegg assert(Global.InitialValue == 0); 7409e15f359SSam Clegg write8(wasm::WASM_OPCODE_GET_GLOBAL); 7419e15f359SSam Clegg encodeULEB128(Global.ImportIndex, getStream()); 7429e15f359SSam Clegg } else { 7439e15f359SSam Clegg assert(Global.ImportIndex == 0); 7449e15f359SSam Clegg write8(wasm::WASM_OPCODE_I32_CONST); 7459e15f359SSam Clegg encodeSLEB128(Global.InitialValue, getStream()); // offset 7469e15f359SSam Clegg } 7479e15f359SSam Clegg write8(wasm::WASM_OPCODE_END); 7489e15f359SSam Clegg } 7499e15f359SSam Clegg 7509e15f359SSam Clegg endSection(Section); 7519e15f359SSam Clegg } 7529e15f359SSam Clegg 753457fb0b4SSam Clegg void WasmObjectWriter::writeExportSection(ArrayRef<WasmExport> Exports) { 7549e15f359SSam Clegg if (Exports.empty()) 7559e15f359SSam Clegg return; 7569e15f359SSam Clegg 7579e15f359SSam Clegg SectionBookkeeping Section; 7589e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_EXPORT); 7599e15f359SSam Clegg 7609e15f359SSam Clegg encodeULEB128(Exports.size(), getStream()); 7619e15f359SSam Clegg for (const WasmExport &Export : Exports) { 762b7787fd0SSam Clegg writeString(Export.FieldName); 7639e15f359SSam Clegg encodeSLEB128(Export.Kind, getStream()); 7649e15f359SSam Clegg encodeULEB128(Export.Index, getStream()); 7659e15f359SSam Clegg } 7669e15f359SSam Clegg 7679e15f359SSam Clegg endSection(Section); 7689e15f359SSam Clegg } 7699e15f359SSam Clegg 770457fb0b4SSam Clegg void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) { 7719e15f359SSam Clegg if (TableElems.empty()) 7729e15f359SSam Clegg return; 7739e15f359SSam Clegg 7749e15f359SSam Clegg SectionBookkeeping Section; 7759e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_ELEM); 7769e15f359SSam Clegg 7779e15f359SSam Clegg encodeULEB128(1, getStream()); // number of "segments" 7789e15f359SSam Clegg encodeULEB128(0, getStream()); // the table index 7799e15f359SSam Clegg 7809e15f359SSam Clegg // init expr for starting offset 7819e15f359SSam Clegg write8(wasm::WASM_OPCODE_I32_CONST); 7829e15f359SSam Clegg encodeSLEB128(0, getStream()); 7839e15f359SSam Clegg write8(wasm::WASM_OPCODE_END); 7849e15f359SSam Clegg 7859e15f359SSam Clegg encodeULEB128(TableElems.size(), getStream()); 7869e15f359SSam Clegg for (uint32_t Elem : TableElems) 7879e15f359SSam Clegg encodeULEB128(Elem, getStream()); 7889e15f359SSam Clegg 7899e15f359SSam Clegg endSection(Section); 7909e15f359SSam Clegg } 7919e15f359SSam Clegg 792457fb0b4SSam Clegg void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm, 793457fb0b4SSam Clegg const MCAsmLayout &Layout, 794457fb0b4SSam Clegg ArrayRef<WasmFunction> Functions) { 7959e15f359SSam Clegg if (Functions.empty()) 7969e15f359SSam Clegg return; 7979e15f359SSam Clegg 7989e15f359SSam Clegg SectionBookkeeping Section; 7999e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_CODE); 8009e15f359SSam Clegg 8019e15f359SSam Clegg encodeULEB128(Functions.size(), getStream()); 8029e15f359SSam Clegg 8039e15f359SSam Clegg for (const WasmFunction &Func : Functions) { 804fe6414b0SSam Clegg auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection()); 8059e15f359SSam Clegg 8069e15f359SSam Clegg int64_t Size = 0; 8079e15f359SSam Clegg if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout)) 8089e15f359SSam Clegg report_fatal_error(".size expression must be evaluatable"); 8099e15f359SSam Clegg 8109e15f359SSam Clegg encodeULEB128(Size, getStream()); 811fe6414b0SSam Clegg FuncSection.setSectionOffset(getStream().tell() - Section.ContentsOffset); 8129e15f359SSam Clegg Asm.writeSectionData(&FuncSection, Layout); 8139e15f359SSam Clegg } 8149e15f359SSam Clegg 8159e15f359SSam Clegg // Apply fixups. 816acd7d2b0SSam Clegg applyRelocations(CodeRelocations, Section.ContentsOffset); 8179e15f359SSam Clegg 8189e15f359SSam Clegg endSection(Section); 8199e15f359SSam Clegg } 8209e15f359SSam Clegg 821457fb0b4SSam Clegg void WasmObjectWriter::writeDataSection(ArrayRef<WasmDataSegment> Segments) { 8227c395943SSam Clegg if (Segments.empty()) 8237c395943SSam Clegg return; 8249e15f359SSam Clegg 8259e15f359SSam Clegg SectionBookkeeping Section; 8269e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_DATA); 8279e15f359SSam Clegg 8287c395943SSam Clegg encodeULEB128(Segments.size(), getStream()); // count 8297c395943SSam Clegg 8307c395943SSam Clegg for (const WasmDataSegment & Segment : Segments) { 8319e15f359SSam Clegg encodeULEB128(0, getStream()); // memory index 8329e15f359SSam Clegg write8(wasm::WASM_OPCODE_I32_CONST); 8337c395943SSam Clegg encodeSLEB128(Segment.Offset, getStream()); // offset 8349e15f359SSam Clegg write8(wasm::WASM_OPCODE_END); 8357c395943SSam Clegg encodeULEB128(Segment.Data.size(), getStream()); // size 8367c395943SSam Clegg Segment.Section->setSectionOffset(getStream().tell() - Section.ContentsOffset); 8377c395943SSam Clegg writeBytes(Segment.Data); // data 8387c395943SSam Clegg } 8399e15f359SSam Clegg 8409e15f359SSam Clegg // Apply fixups. 8417c395943SSam Clegg applyRelocations(DataRelocations, Section.ContentsOffset); 8429e15f359SSam Clegg 8439e15f359SSam Clegg endSection(Section); 8449e15f359SSam Clegg } 8459e15f359SSam Clegg 8469e15f359SSam Clegg void WasmObjectWriter::writeNameSection( 847457fb0b4SSam Clegg ArrayRef<WasmFunction> Functions, 848457fb0b4SSam Clegg ArrayRef<WasmImport> Imports, 8499e15f359SSam Clegg unsigned NumFuncImports) { 8509e15f359SSam Clegg uint32_t TotalFunctions = NumFuncImports + Functions.size(); 8519e15f359SSam Clegg if (TotalFunctions == 0) 8529e15f359SSam Clegg return; 8539e15f359SSam Clegg 8549e15f359SSam Clegg SectionBookkeeping Section; 8559e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_CUSTOM, "name"); 8569e15f359SSam Clegg SectionBookkeeping SubSection; 8579e15f359SSam Clegg startSection(SubSection, wasm::WASM_NAMES_FUNCTION); 8589e15f359SSam Clegg 8599e15f359SSam Clegg encodeULEB128(TotalFunctions, getStream()); 8609e15f359SSam Clegg uint32_t Index = 0; 8619e15f359SSam Clegg for (const WasmImport &Import : Imports) { 8629e15f359SSam Clegg if (Import.Kind == wasm::WASM_EXTERNAL_FUNCTION) { 8639e15f359SSam Clegg encodeULEB128(Index, getStream()); 864b7787fd0SSam Clegg writeString(Import.FieldName); 8659e15f359SSam Clegg ++Index; 8669e15f359SSam Clegg } 8679e15f359SSam Clegg } 8689e15f359SSam Clegg for (const WasmFunction &Func : Functions) { 8699e15f359SSam Clegg encodeULEB128(Index, getStream()); 870b7787fd0SSam Clegg writeString(Func.Sym->getName()); 8719e15f359SSam Clegg ++Index; 8729e15f359SSam Clegg } 8739e15f359SSam Clegg 8749e15f359SSam Clegg endSection(SubSection); 8759e15f359SSam Clegg endSection(Section); 8769e15f359SSam Clegg } 8779e15f359SSam Clegg 878acd7d2b0SSam Clegg void WasmObjectWriter::writeCodeRelocSection() { 8799e15f359SSam Clegg // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md 8809e15f359SSam Clegg // for descriptions of the reloc sections. 8819e15f359SSam Clegg 8829e15f359SSam Clegg if (CodeRelocations.empty()) 8839e15f359SSam Clegg return; 8849e15f359SSam Clegg 8859e15f359SSam Clegg SectionBookkeeping Section; 8869e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.CODE"); 8879e15f359SSam Clegg 8889e15f359SSam Clegg encodeULEB128(wasm::WASM_SEC_CODE, getStream()); 889acd7d2b0SSam Clegg encodeULEB128(CodeRelocations.size(), getStream()); 8909e15f359SSam Clegg 8917c395943SSam Clegg writeRelocations(CodeRelocations); 8929e15f359SSam Clegg 8939e15f359SSam Clegg endSection(Section); 8949e15f359SSam Clegg } 8959e15f359SSam Clegg 8967c395943SSam Clegg void WasmObjectWriter::writeDataRelocSection() { 8979e15f359SSam Clegg // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md 8989e15f359SSam Clegg // for descriptions of the reloc sections. 8999e15f359SSam Clegg 9009e15f359SSam Clegg if (DataRelocations.empty()) 9019e15f359SSam Clegg return; 9029e15f359SSam Clegg 9039e15f359SSam Clegg SectionBookkeeping Section; 9049e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.DATA"); 9059e15f359SSam Clegg 9069e15f359SSam Clegg encodeULEB128(wasm::WASM_SEC_DATA, getStream()); 9079e15f359SSam Clegg encodeULEB128(DataRelocations.size(), getStream()); 9089e15f359SSam Clegg 9097c395943SSam Clegg writeRelocations(DataRelocations); 9109e15f359SSam Clegg 9119e15f359SSam Clegg endSection(Section); 9129e15f359SSam Clegg } 9139e15f359SSam Clegg 9149e15f359SSam Clegg void WasmObjectWriter::writeLinkingMetaDataSection( 915d95ed959SSam Clegg ArrayRef<WasmDataSegment> Segments, uint32_t DataSize, 916bafe6902SSam Clegg const SmallVector<std::pair<StringRef, uint32_t>, 4> &SymbolFlags, 917bafe6902SSam Clegg const SmallVector<std::pair<uint16_t, uint32_t>, 2> &InitFuncs) { 9189e15f359SSam Clegg SectionBookkeeping Section; 9199e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_CUSTOM, "linking"); 920b7787fd0SSam Clegg SectionBookkeeping SubSection; 9219e15f359SSam Clegg 92231a2c809SSam Clegg if (SymbolFlags.size() != 0) { 923b7787fd0SSam Clegg startSection(SubSection, wasm::WASM_SYMBOL_INFO); 92431a2c809SSam Clegg encodeULEB128(SymbolFlags.size(), getStream()); 92531a2c809SSam Clegg for (auto Pair: SymbolFlags) { 92631a2c809SSam Clegg writeString(Pair.first); 92731a2c809SSam Clegg encodeULEB128(Pair.second, getStream()); 928b7787fd0SSam Clegg } 929b7787fd0SSam Clegg endSection(SubSection); 930b7787fd0SSam Clegg } 9319e15f359SSam Clegg 9329e1ade93SSam Clegg if (DataSize > 0) { 9339e1ade93SSam Clegg startSection(SubSection, wasm::WASM_DATA_SIZE); 9349e1ade93SSam Clegg encodeULEB128(DataSize, getStream()); 9359e1ade93SSam Clegg endSection(SubSection); 9369e1ade93SSam Clegg } 9379e1ade93SSam Clegg 938d95ed959SSam Clegg if (Segments.size()) { 93963ebb813SSam Clegg startSection(SubSection, wasm::WASM_SEGMENT_INFO); 940d95ed959SSam Clegg encodeULEB128(Segments.size(), getStream()); 94163ebb813SSam Clegg for (const WasmDataSegment &Segment : Segments) { 942d95ed959SSam Clegg writeString(Segment.Name); 94363ebb813SSam Clegg encodeULEB128(Segment.Alignment, getStream()); 94463ebb813SSam Clegg encodeULEB128(Segment.Flags, getStream()); 94563ebb813SSam Clegg } 946d95ed959SSam Clegg endSection(SubSection); 947d95ed959SSam Clegg } 948d95ed959SSam Clegg 949bafe6902SSam Clegg if (!InitFuncs.empty()) { 950bafe6902SSam Clegg startSection(SubSection, wasm::WASM_INIT_FUNCS); 951bafe6902SSam Clegg encodeULEB128(InitFuncs.size(), getStream()); 952bafe6902SSam Clegg for (auto &StartFunc : InitFuncs) { 953bafe6902SSam Clegg encodeULEB128(StartFunc.first, getStream()); // priority 954bafe6902SSam Clegg encodeULEB128(StartFunc.second, getStream()); // function index 955bafe6902SSam Clegg } 956bafe6902SSam Clegg endSection(SubSection); 957bafe6902SSam Clegg } 958bafe6902SSam Clegg 9599e15f359SSam Clegg endSection(Section); 9609e15f359SSam Clegg } 9619e15f359SSam Clegg 9625e3d33a7SSam Clegg uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm& Symbol) { 9635e3d33a7SSam Clegg assert(Symbol.isFunction()); 9645e3d33a7SSam Clegg assert(TypeIndices.count(&Symbol)); 9655e3d33a7SSam Clegg return TypeIndices[&Symbol]; 9665e3d33a7SSam Clegg } 9675e3d33a7SSam Clegg 9685e3d33a7SSam Clegg uint32_t WasmObjectWriter::registerFunctionType(const MCSymbolWasm& Symbol) { 9695e3d33a7SSam Clegg assert(Symbol.isFunction()); 9705e3d33a7SSam Clegg 9715e3d33a7SSam Clegg WasmFunctionType F; 972aff1c4dfSSam Clegg const MCSymbolWasm* ResolvedSym = ResolveSymbol(Symbol); 9735e3d33a7SSam Clegg F.Returns = ResolvedSym->getReturns(); 9745e3d33a7SSam Clegg F.Params = ResolvedSym->getParams(); 9755e3d33a7SSam Clegg 9765e3d33a7SSam Clegg auto Pair = 9775e3d33a7SSam Clegg FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size())); 9785e3d33a7SSam Clegg if (Pair.second) 9795e3d33a7SSam Clegg FunctionTypes.push_back(F); 9805e3d33a7SSam Clegg TypeIndices[&Symbol] = Pair.first->second; 9815e3d33a7SSam Clegg 9825e3d33a7SSam Clegg DEBUG(dbgs() << "registerFunctionType: " << Symbol << " new:" << Pair.second << "\n"); 9835e3d33a7SSam Clegg DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n"); 9845e3d33a7SSam Clegg return Pair.first->second; 9855e3d33a7SSam Clegg } 9865e3d33a7SSam Clegg 98718eafb6cSDan Gohman void WasmObjectWriter::writeObject(MCAssembler &Asm, 98818eafb6cSDan Gohman const MCAsmLayout &Layout) { 989b7787fd0SSam Clegg DEBUG(dbgs() << "WasmObjectWriter::writeObject\n"); 99082607f56SDan Gohman MCContext &Ctx = Asm.getContext(); 991b879539aSDerek Schuff wasm::ValType PtrType = is64Bit() ? wasm::ValType::I64 : wasm::ValType::I32; 992d934cb88SDan Gohman 993d934cb88SDan Gohman // Collect information from the available symbols. 994d934cb88SDan Gohman SmallVector<WasmFunction, 4> Functions; 995d934cb88SDan Gohman SmallVector<uint32_t, 4> TableElems; 996d934cb88SDan Gohman SmallVector<WasmImport, 4> Imports; 997d934cb88SDan Gohman SmallVector<WasmExport, 4> Exports; 99831a2c809SSam Clegg SmallVector<std::pair<StringRef, uint32_t>, 4> SymbolFlags; 999bafe6902SSam Clegg SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs; 1000d934cb88SDan Gohman unsigned NumFuncImports = 0; 10017c395943SSam Clegg SmallVector<WasmDataSegment, 4> DataSegments; 10027c395943SSam Clegg uint32_t DataSize = 0; 1003d934cb88SDan Gohman 100482607f56SDan Gohman // In the special .global_variables section, we've encoded global 100582607f56SDan Gohman // variables used by the function. Translate them into the Globals 100682607f56SDan Gohman // list. 100712fd3da9SSam Clegg MCSectionWasm *GlobalVars = 100812fd3da9SSam Clegg Ctx.getWasmSection(".global_variables", SectionKind::getMetadata()); 100982607f56SDan Gohman if (!GlobalVars->getFragmentList().empty()) { 101082607f56SDan Gohman if (GlobalVars->getFragmentList().size() != 1) 101182607f56SDan Gohman report_fatal_error("only one .global_variables fragment supported"); 101282607f56SDan Gohman const MCFragment &Frag = *GlobalVars->begin(); 101382607f56SDan Gohman if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data) 101482607f56SDan Gohman report_fatal_error("only data supported in .global_variables"); 1015fe6414b0SSam Clegg const auto &DataFrag = cast<MCDataFragment>(Frag); 101682607f56SDan Gohman if (!DataFrag.getFixups().empty()) 101782607f56SDan Gohman report_fatal_error("fixups not supported in .global_variables"); 101882607f56SDan Gohman const SmallVectorImpl<char> &Contents = DataFrag.getContents(); 1019970d02c4SDan Gohman for (const uint8_t *p = (const uint8_t *)Contents.data(), 1020970d02c4SDan Gohman *end = (const uint8_t *)Contents.data() + Contents.size(); 1021970d02c4SDan Gohman p != end; ) { 102282607f56SDan Gohman WasmGlobal G; 1023970d02c4SDan Gohman if (end - p < 3) 1024970d02c4SDan Gohman report_fatal_error("truncated global variable encoding"); 1025970d02c4SDan Gohman G.Type = wasm::ValType(int8_t(*p++)); 1026970d02c4SDan Gohman G.IsMutable = bool(*p++); 1027970d02c4SDan Gohman G.HasImport = bool(*p++); 1028970d02c4SDan Gohman if (G.HasImport) { 102982607f56SDan Gohman G.InitialValue = 0; 1030970d02c4SDan Gohman 1031970d02c4SDan Gohman WasmImport Import; 1032970d02c4SDan Gohman Import.ModuleName = (const char *)p; 1033970d02c4SDan Gohman const uint8_t *nul = (const uint8_t *)memchr(p, '\0', end - p); 1034970d02c4SDan Gohman if (!nul) 1035970d02c4SDan Gohman report_fatal_error("global module name must be nul-terminated"); 1036970d02c4SDan Gohman p = nul + 1; 1037970d02c4SDan Gohman nul = (const uint8_t *)memchr(p, '\0', end - p); 1038970d02c4SDan Gohman if (!nul) 1039970d02c4SDan Gohman report_fatal_error("global base name must be nul-terminated"); 1040970d02c4SDan Gohman Import.FieldName = (const char *)p; 1041970d02c4SDan Gohman p = nul + 1; 1042970d02c4SDan Gohman 1043970d02c4SDan Gohman Import.Kind = wasm::WASM_EXTERNAL_GLOBAL; 1044970d02c4SDan Gohman Import.Type = int32_t(G.Type); 1045970d02c4SDan Gohman 1046970d02c4SDan Gohman G.ImportIndex = NumGlobalImports; 1047970d02c4SDan Gohman ++NumGlobalImports; 1048970d02c4SDan Gohman 1049970d02c4SDan Gohman Imports.push_back(Import); 1050970d02c4SDan Gohman } else { 1051970d02c4SDan Gohman unsigned n; 1052970d02c4SDan Gohman G.InitialValue = decodeSLEB128(p, &n); 1053970d02c4SDan Gohman G.ImportIndex = 0; 1054c8da0c0bSSimon Pilgrim if ((ptrdiff_t)n > end - p) 1055970d02c4SDan Gohman report_fatal_error("global initial value must be valid SLEB128"); 1056970d02c4SDan Gohman p += n; 1057970d02c4SDan Gohman } 105882607f56SDan Gohman Globals.push_back(G); 105982607f56SDan Gohman } 106082607f56SDan Gohman } 106182607f56SDan Gohman 1062f950b24aSSam Clegg // For now, always emit the memory import, since loads and stores are not 1063f950b24aSSam Clegg // valid without it. In the future, we could perhaps be more clever and omit 1064f950b24aSSam Clegg // it if there are no loads or stores. 1065f950b24aSSam Clegg MCSymbolWasm *MemorySym = 1066f950b24aSSam Clegg cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__linear_memory")); 1067f950b24aSSam Clegg WasmImport MemImport; 1068f950b24aSSam Clegg MemImport.ModuleName = MemorySym->getModuleName(); 1069f950b24aSSam Clegg MemImport.FieldName = MemorySym->getName(); 1070f950b24aSSam Clegg MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY; 1071f950b24aSSam Clegg Imports.push_back(MemImport); 1072f950b24aSSam Clegg 1073f950b24aSSam Clegg // For now, always emit the table section, since indirect calls are not 1074f950b24aSSam Clegg // valid without it. In the future, we could perhaps be more clever and omit 1075f950b24aSSam Clegg // it if there are no indirect calls. 1076f950b24aSSam Clegg MCSymbolWasm *TableSym = 1077f950b24aSSam Clegg cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__indirect_function_table")); 1078f950b24aSSam Clegg WasmImport TableImport; 1079f950b24aSSam Clegg TableImport.ModuleName = TableSym->getModuleName(); 1080f950b24aSSam Clegg TableImport.FieldName = TableSym->getName(); 1081f950b24aSSam Clegg TableImport.Kind = wasm::WASM_EXTERNAL_TABLE; 1082f950b24aSSam Clegg TableImport.Type = wasm::WASM_TYPE_ANYFUNC; 1083f950b24aSSam Clegg Imports.push_back(TableImport); 1084f950b24aSSam Clegg 108532ce5ca0SDan Gohman // Populate FunctionTypeIndices and Imports. 108632ce5ca0SDan Gohman for (const MCSymbol &S : Asm.symbols()) { 108732ce5ca0SDan Gohman const auto &WS = static_cast<const MCSymbolWasm &>(S); 108832ce5ca0SDan Gohman 108932ce5ca0SDan Gohman // Register types for all functions, including those with private linkage 109032ce5ca0SDan Gohman // (making them 109132ce5ca0SDan Gohman // because wasm always needs a type signature. 109232ce5ca0SDan Gohman if (WS.isFunction()) 109332ce5ca0SDan Gohman registerFunctionType(WS); 109432ce5ca0SDan Gohman 109532ce5ca0SDan Gohman if (WS.isTemporary()) 109632ce5ca0SDan Gohman continue; 109732ce5ca0SDan Gohman 109832ce5ca0SDan Gohman // If the symbol is not defined in this translation unit, import it. 1099b6a42984SSam Clegg if (!WS.isDefined(/*SetUsed=*/false) || WS.isVariable()) { 110032ce5ca0SDan Gohman WasmImport Import; 110132ce5ca0SDan Gohman Import.ModuleName = WS.getModuleName(); 110232ce5ca0SDan Gohman Import.FieldName = WS.getName(); 110332ce5ca0SDan Gohman 110432ce5ca0SDan Gohman if (WS.isFunction()) { 110532ce5ca0SDan Gohman Import.Kind = wasm::WASM_EXTERNAL_FUNCTION; 110632ce5ca0SDan Gohman Import.Type = getFunctionType(WS); 110732ce5ca0SDan Gohman SymbolIndices[&WS] = NumFuncImports; 110832ce5ca0SDan Gohman ++NumFuncImports; 110932ce5ca0SDan Gohman } else { 111032ce5ca0SDan Gohman Import.Kind = wasm::WASM_EXTERNAL_GLOBAL; 111132ce5ca0SDan Gohman Import.Type = int32_t(PtrType); 111232ce5ca0SDan Gohman Import.IsMutable = false; 111332ce5ca0SDan Gohman SymbolIndices[&WS] = NumGlobalImports; 111432ce5ca0SDan Gohman 111583b16226SDan Gohman // If this global is the stack pointer, make it mutable. 1116ad19047dSDan Gohman if (WS.getName() == "__stack_pointer") 111732ce5ca0SDan Gohman Import.IsMutable = true; 111832ce5ca0SDan Gohman 111932ce5ca0SDan Gohman ++NumGlobalImports; 112032ce5ca0SDan Gohman } 112132ce5ca0SDan Gohman 112232ce5ca0SDan Gohman Imports.push_back(Import); 112332ce5ca0SDan Gohman } 112432ce5ca0SDan Gohman } 112532ce5ca0SDan Gohman 1126759631c7SSam Clegg for (MCSection &Sec : Asm) { 1127759631c7SSam Clegg auto &Section = static_cast<MCSectionWasm &>(Sec); 112812fd3da9SSam Clegg if (!Section.isWasmData()) 1129759631c7SSam Clegg continue; 1130759631c7SSam Clegg 1131bafe6902SSam Clegg // .init_array sections are handled specially elsewhere. 1132bafe6902SSam Clegg if (cast<MCSectionWasm>(Sec).getSectionName().startswith(".init_array")) 1133bafe6902SSam Clegg continue; 1134bafe6902SSam Clegg 1135759631c7SSam Clegg DataSize = alignTo(DataSize, Section.getAlignment()); 1136759631c7SSam Clegg DataSegments.emplace_back(); 1137759631c7SSam Clegg WasmDataSegment &Segment = DataSegments.back(); 1138d95ed959SSam Clegg Segment.Name = Section.getSectionName(); 1139759631c7SSam Clegg Segment.Offset = DataSize; 1140759631c7SSam Clegg Segment.Section = &Section; 114163ebb813SSam Clegg addData(Segment.Data, Section); 114263ebb813SSam Clegg Segment.Alignment = Section.getAlignment(); 114363ebb813SSam Clegg Segment.Flags = 0; 1144759631c7SSam Clegg DataSize += Segment.Data.size(); 1145759631c7SSam Clegg Section.setMemoryOffset(Segment.Offset); 1146759631c7SSam Clegg } 1147759631c7SSam Clegg 1148b7787fd0SSam Clegg // Handle regular defined and undefined symbols. 1149d934cb88SDan Gohman for (const MCSymbol &S : Asm.symbols()) { 1150d934cb88SDan Gohman // Ignore unnamed temporary symbols, which aren't ever exported, imported, 1151d934cb88SDan Gohman // or used in relocations. 1152d934cb88SDan Gohman if (S.isTemporary() && S.getName().empty()) 1153d934cb88SDan Gohman continue; 1154b7787fd0SSam Clegg 1155d934cb88SDan Gohman const auto &WS = static_cast<const MCSymbolWasm &>(S); 1156b7787fd0SSam Clegg DEBUG(dbgs() << "MCSymbol: '" << S << "'" 1157b7787fd0SSam Clegg << " isDefined=" << S.isDefined() << " isExternal=" 1158b7787fd0SSam Clegg << S.isExternal() << " isTemporary=" << S.isTemporary() 1159b7787fd0SSam Clegg << " isFunction=" << WS.isFunction() 1160b7787fd0SSam Clegg << " isWeak=" << WS.isWeak() 1161a2b35dacSSam Clegg << " isHidden=" << WS.isHidden() 1162b7787fd0SSam Clegg << " isVariable=" << WS.isVariable() << "\n"); 1163b7787fd0SSam Clegg 1164a2b35dacSSam Clegg if (WS.isWeak() || WS.isHidden()) { 1165a2b35dacSSam Clegg uint32_t Flags = (WS.isWeak() ? wasm::WASM_SYMBOL_BINDING_WEAK : 0) | 1166a2b35dacSSam Clegg (WS.isHidden() ? wasm::WASM_SYMBOL_VISIBILITY_HIDDEN : 0); 1167a2b35dacSSam Clegg SymbolFlags.emplace_back(WS.getName(), Flags); 1168a2b35dacSSam Clegg } 1169b7787fd0SSam Clegg 11705e3d33a7SSam Clegg if (WS.isVariable()) 11715e3d33a7SSam Clegg continue; 11725e3d33a7SSam Clegg 1173d934cb88SDan Gohman unsigned Index; 1174b7787fd0SSam Clegg 1175d934cb88SDan Gohman if (WS.isFunction()) { 1176d934cb88SDan Gohman if (WS.isDefined(/*SetUsed=*/false)) { 1177b7787fd0SSam Clegg if (WS.getOffset() != 0) 1178b7787fd0SSam Clegg report_fatal_error( 1179b7787fd0SSam Clegg "function sections must contain one function each"); 1180b7787fd0SSam Clegg 1181b7787fd0SSam Clegg if (WS.getSize() == 0) 1182b7787fd0SSam Clegg report_fatal_error( 1183b7787fd0SSam Clegg "function symbols must have a size set with .size"); 1184b7787fd0SSam Clegg 1185d934cb88SDan Gohman // A definition. Take the next available index. 1186d934cb88SDan Gohman Index = NumFuncImports + Functions.size(); 1187d934cb88SDan Gohman 1188d934cb88SDan Gohman // Prepare the function. 1189d934cb88SDan Gohman WasmFunction Func; 11905e3d33a7SSam Clegg Func.Type = getFunctionType(WS); 1191d934cb88SDan Gohman Func.Sym = &WS; 1192d934cb88SDan Gohman SymbolIndices[&WS] = Index; 1193d934cb88SDan Gohman Functions.push_back(Func); 1194d934cb88SDan Gohman } else { 1195d934cb88SDan Gohman // An import; the index was assigned above. 1196d934cb88SDan Gohman Index = SymbolIndices.find(&WS)->second; 1197d934cb88SDan Gohman } 1198d934cb88SDan Gohman 11995e3d33a7SSam Clegg DEBUG(dbgs() << " -> function index: " << Index << "\n"); 1200d934cb88SDan Gohman } else { 1201c38e947eSSam Clegg if (WS.isTemporary() && !WS.getSize()) 1202c38e947eSSam Clegg continue; 1203c38e947eSSam Clegg 1204fe6414b0SSam Clegg if (!WS.isDefined(/*SetUsed=*/false)) 1205fe6414b0SSam Clegg continue; 1206fe6414b0SSam Clegg 1207d934cb88SDan Gohman if (!WS.getSize()) 1208c38e947eSSam Clegg report_fatal_error("data symbols must have a size set with .size: " + 1209c38e947eSSam Clegg WS.getName()); 1210d934cb88SDan Gohman 1211d934cb88SDan Gohman int64_t Size = 0; 1212d934cb88SDan Gohman if (!WS.getSize()->evaluateAsAbsolute(Size, Layout)) 1213d934cb88SDan Gohman report_fatal_error(".size expression must be evaluatable"); 1214d934cb88SDan Gohman 12157c395943SSam Clegg // For each global, prepare a corresponding wasm global holding its 12167c395943SSam Clegg // address. For externals these will also be named exports. 12177c395943SSam Clegg Index = NumGlobalImports + Globals.size(); 1218759631c7SSam Clegg auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection()); 12197c395943SSam Clegg 12207c395943SSam Clegg WasmGlobal Global; 12217c395943SSam Clegg Global.Type = PtrType; 12227c395943SSam Clegg Global.IsMutable = false; 12237c395943SSam Clegg Global.HasImport = false; 1224759631c7SSam Clegg Global.InitialValue = DataSection.getMemoryOffset() + Layout.getSymbolOffset(WS); 12257c395943SSam Clegg Global.ImportIndex = 0; 12267c395943SSam Clegg SymbolIndices[&WS] = Index; 12277c395943SSam Clegg DEBUG(dbgs() << " -> global index: " << Index << "\n"); 12287c395943SSam Clegg Globals.push_back(Global); 1229d934cb88SDan Gohman } 1230d934cb88SDan Gohman 1231d934cb88SDan Gohman // If the symbol is visible outside this translation unit, export it. 123231a2c809SSam Clegg if (WS.isDefined(/*SetUsed=*/false)) { 1233d934cb88SDan Gohman WasmExport Export; 1234d934cb88SDan Gohman Export.FieldName = WS.getName(); 1235d934cb88SDan Gohman Export.Index = Index; 1236d934cb88SDan Gohman if (WS.isFunction()) 1237d934cb88SDan Gohman Export.Kind = wasm::WASM_EXTERNAL_FUNCTION; 1238d934cb88SDan Gohman else 1239d934cb88SDan Gohman Export.Kind = wasm::WASM_EXTERNAL_GLOBAL; 12405e3d33a7SSam Clegg DEBUG(dbgs() << " -> export " << Exports.size() << "\n"); 1241d934cb88SDan Gohman Exports.push_back(Export); 124231a2c809SSam Clegg if (!WS.isExternal()) 124331a2c809SSam Clegg SymbolFlags.emplace_back(WS.getName(), wasm::WASM_SYMBOL_BINDING_LOCAL); 1244d934cb88SDan Gohman } 1245d934cb88SDan Gohman } 1246d934cb88SDan Gohman 12475e3d33a7SSam Clegg // Handle weak aliases. We need to process these in a separate pass because 12485e3d33a7SSam Clegg // we need to have processed the target of the alias before the alias itself 12495e3d33a7SSam Clegg // and the symbols are not necessarily ordered in this way. 1250b7787fd0SSam Clegg for (const MCSymbol &S : Asm.symbols()) { 1251b7787fd0SSam Clegg if (!S.isVariable()) 1252b7787fd0SSam Clegg continue; 125331a2c809SSam Clegg 1254b7787fd0SSam Clegg assert(S.isDefined(/*SetUsed=*/false)); 1255b7787fd0SSam Clegg 12565e3d33a7SSam Clegg // Find the target symbol of this weak alias and export that index 1257aff1c4dfSSam Clegg const auto &WS = static_cast<const MCSymbolWasm &>(S); 1258aff1c4dfSSam Clegg const MCSymbolWasm *ResolvedSym = ResolveSymbol(WS); 12595e3d33a7SSam Clegg DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym << "'\n"); 12605e3d33a7SSam Clegg assert(SymbolIndices.count(ResolvedSym) > 0); 1261b7787fd0SSam Clegg uint32_t Index = SymbolIndices.find(ResolvedSym)->second; 12625e3d33a7SSam Clegg DEBUG(dbgs() << " -> index:" << Index << "\n"); 1263b7787fd0SSam Clegg 1264b7787fd0SSam Clegg WasmExport Export; 1265b7787fd0SSam Clegg Export.FieldName = WS.getName(); 1266b7787fd0SSam Clegg Export.Index = Index; 1267b7787fd0SSam Clegg if (WS.isFunction()) 1268b7787fd0SSam Clegg Export.Kind = wasm::WASM_EXTERNAL_FUNCTION; 1269b7787fd0SSam Clegg else 1270b7787fd0SSam Clegg Export.Kind = wasm::WASM_EXTERNAL_GLOBAL; 12715e3d33a7SSam Clegg DEBUG(dbgs() << " -> export " << Exports.size() << "\n"); 1272b7787fd0SSam Clegg Exports.push_back(Export); 127331a2c809SSam Clegg 127431a2c809SSam Clegg if (!WS.isExternal()) 127531a2c809SSam Clegg SymbolFlags.emplace_back(WS.getName(), wasm::WASM_SYMBOL_BINDING_LOCAL); 1276b7787fd0SSam Clegg } 1277b7787fd0SSam Clegg 12786006e091SSam Clegg { 12796006e091SSam Clegg auto HandleReloc = [&](const WasmRelocationEntry &Rel) { 12806006e091SSam Clegg // Functions referenced by a relocation need to prepared to be called 12816006e091SSam Clegg // indirectly. 12826006e091SSam Clegg const MCSymbolWasm& WS = *Rel.Symbol; 12836006e091SSam Clegg if (WS.isFunction() && IndirectSymbolIndices.count(&WS) == 0) { 12846006e091SSam Clegg switch (Rel.Type) { 12856006e091SSam Clegg case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: 12866006e091SSam Clegg case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB: 12876006e091SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32: 12886006e091SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: { 12896006e091SSam Clegg uint32_t Index = SymbolIndices.find(&WS)->second; 12906006e091SSam Clegg IndirectSymbolIndices[&WS] = TableElems.size(); 12916006e091SSam Clegg DEBUG(dbgs() << " -> adding to table: " << TableElems.size() << "\n"); 12926006e091SSam Clegg TableElems.push_back(Index); 12936006e091SSam Clegg registerFunctionType(WS); 12946006e091SSam Clegg break; 12956006e091SSam Clegg } 12966006e091SSam Clegg default: 12976006e091SSam Clegg break; 12986006e091SSam Clegg } 12996006e091SSam Clegg } 13006006e091SSam Clegg }; 1301970d02c4SDan Gohman 13026006e091SSam Clegg for (const WasmRelocationEntry &RelEntry : CodeRelocations) 13036006e091SSam Clegg HandleReloc(RelEntry); 13046006e091SSam Clegg for (const WasmRelocationEntry &RelEntry : DataRelocations) 13056006e091SSam Clegg HandleReloc(RelEntry); 1306d934cb88SDan Gohman } 1307d934cb88SDan Gohman 1308bafe6902SSam Clegg // Translate .init_array section contents into start functions. 1309bafe6902SSam Clegg for (const MCSection &S : Asm) { 1310bafe6902SSam Clegg const auto &WS = static_cast<const MCSectionWasm &>(S); 1311bafe6902SSam Clegg if (WS.getSectionName().startswith(".fini_array")) 1312bafe6902SSam Clegg report_fatal_error(".fini_array sections are unsupported"); 1313bafe6902SSam Clegg if (!WS.getSectionName().startswith(".init_array")) 1314bafe6902SSam Clegg continue; 1315bafe6902SSam Clegg if (WS.getFragmentList().empty()) 1316bafe6902SSam Clegg continue; 1317bafe6902SSam Clegg if (WS.getFragmentList().size() != 2) 1318bafe6902SSam Clegg report_fatal_error("only one .init_array section fragment supported"); 1319bafe6902SSam Clegg const MCFragment &AlignFrag = *WS.begin(); 1320bafe6902SSam Clegg if (AlignFrag.getKind() != MCFragment::FT_Align) 1321bafe6902SSam Clegg report_fatal_error(".init_array section should be aligned"); 1322bafe6902SSam Clegg if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4)) 1323bafe6902SSam Clegg report_fatal_error(".init_array section should be aligned for pointers"); 1324bafe6902SSam Clegg const MCFragment &Frag = *std::next(WS.begin()); 1325bafe6902SSam Clegg if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data) 1326bafe6902SSam Clegg report_fatal_error("only data supported in .init_array section"); 1327bafe6902SSam Clegg uint16_t Priority = UINT16_MAX; 1328bafe6902SSam Clegg if (WS.getSectionName().size() != 11) { 1329bafe6902SSam Clegg if (WS.getSectionName()[11] != '.') 1330bafe6902SSam Clegg report_fatal_error(".init_array section priority should start with '.'"); 1331bafe6902SSam Clegg if (WS.getSectionName().substr(12).getAsInteger(10, Priority)) 1332bafe6902SSam Clegg report_fatal_error("invalid .init_array section priority"); 1333bafe6902SSam Clegg } 1334bafe6902SSam Clegg const auto &DataFrag = cast<MCDataFragment>(Frag); 1335bafe6902SSam Clegg const SmallVectorImpl<char> &Contents = DataFrag.getContents(); 1336bafe6902SSam Clegg for (const uint8_t *p = (const uint8_t *)Contents.data(), 1337bafe6902SSam Clegg *end = (const uint8_t *)Contents.data() + Contents.size(); 1338bafe6902SSam Clegg p != end; ++p) { 1339bafe6902SSam Clegg if (*p != 0) 1340bafe6902SSam Clegg report_fatal_error("non-symbolic data in .init_array section"); 1341bafe6902SSam Clegg } 1342bafe6902SSam Clegg for (const MCFixup &Fixup : DataFrag.getFixups()) { 1343bafe6902SSam Clegg assert(Fixup.getKind() == MCFixup::getKindForSize(is64Bit() ? 8 : 4, false)); 1344bafe6902SSam Clegg const MCExpr *Expr = Fixup.getValue(); 1345bafe6902SSam Clegg auto *Sym = dyn_cast<MCSymbolRefExpr>(Expr); 1346bafe6902SSam Clegg if (!Sym) 1347bafe6902SSam Clegg report_fatal_error("fixups in .init_array should be symbol references"); 1348bafe6902SSam Clegg if (Sym->getKind() != MCSymbolRefExpr::VK_WebAssembly_FUNCTION) 1349bafe6902SSam Clegg report_fatal_error("symbols in .init_array should be for functions"); 1350bafe6902SSam Clegg auto I = SymbolIndices.find(cast<MCSymbolWasm>(&Sym->getSymbol())); 1351bafe6902SSam Clegg if (I == SymbolIndices.end()) 1352bafe6902SSam Clegg report_fatal_error("symbols in .init_array should be defined"); 1353bafe6902SSam Clegg uint32_t Index = I->second; 1354bafe6902SSam Clegg InitFuncs.push_back(std::make_pair(Priority, Index)); 1355bafe6902SSam Clegg } 1356bafe6902SSam Clegg } 1357bafe6902SSam Clegg 135818eafb6cSDan Gohman // Write out the Wasm header. 135918eafb6cSDan Gohman writeHeader(Asm); 136018eafb6cSDan Gohman 13619e15f359SSam Clegg writeTypeSection(FunctionTypes); 1362f950b24aSSam Clegg writeImportSection(Imports, DataSize, TableElems.size()); 13639e15f359SSam Clegg writeFunctionSection(Functions); 1364f950b24aSSam Clegg // Skip the "table" section; we import the table instead. 1365f950b24aSSam Clegg // Skip the "memory" section; we import the memory instead. 13667c395943SSam Clegg writeGlobalSection(); 13679e15f359SSam Clegg writeExportSection(Exports); 13689e15f359SSam Clegg writeElemSection(TableElems); 1369acd7d2b0SSam Clegg writeCodeSection(Asm, Layout, Functions); 13707c395943SSam Clegg writeDataSection(DataSegments); 13719e15f359SSam Clegg writeNameSection(Functions, Imports, NumFuncImports); 1372acd7d2b0SSam Clegg writeCodeRelocSection(); 13737c395943SSam Clegg writeDataRelocSection(); 1374bafe6902SSam Clegg writeLinkingMetaDataSection(DataSegments, DataSize, SymbolFlags, 1375bafe6902SSam Clegg InitFuncs); 1376970d02c4SDan Gohman 1377d934cb88SDan Gohman // TODO: Translate the .comment section to the output. 1378d934cb88SDan Gohman // TODO: Translate debug sections to the output. 137918eafb6cSDan Gohman } 138018eafb6cSDan Gohman 138160fbc7ccSLang Hames std::unique_ptr<MCObjectWriter> 13821301a878SLang Hames llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW, 138318eafb6cSDan Gohman raw_pwrite_stream &OS) { 138460fbc7ccSLang Hames // FIXME: Can't use make_unique<WasmObjectWriter>(...) as WasmObjectWriter's 138560fbc7ccSLang Hames // destructor is private. Is that necessary? 138660fbc7ccSLang Hames return std::unique_ptr<MCObjectWriter>( 138760fbc7ccSLang Hames new WasmObjectWriter(std::move(MOTW), OS)); 138818eafb6cSDan Gohman } 1389