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/MCAsmInfo.h" 1918eafb6cSDan Gohman #include "llvm/MC/MCAsmLayout.h" 2018eafb6cSDan Gohman #include "llvm/MC/MCAssembler.h" 2118eafb6cSDan Gohman #include "llvm/MC/MCContext.h" 2218eafb6cSDan Gohman #include "llvm/MC/MCExpr.h" 2318eafb6cSDan Gohman #include "llvm/MC/MCFixupKindInfo.h" 2418eafb6cSDan Gohman #include "llvm/MC/MCObjectFileInfo.h" 2518eafb6cSDan Gohman #include "llvm/MC/MCObjectWriter.h" 2618eafb6cSDan Gohman #include "llvm/MC/MCSectionWasm.h" 2718eafb6cSDan Gohman #include "llvm/MC/MCSymbolWasm.h" 2818eafb6cSDan Gohman #include "llvm/MC/MCValue.h" 2918eafb6cSDan Gohman #include "llvm/MC/MCWasmObjectWriter.h" 30d934cb88SDan Gohman #include "llvm/Support/Casting.h" 3118eafb6cSDan Gohman #include "llvm/Support/Debug.h" 3218eafb6cSDan Gohman #include "llvm/Support/ErrorHandling.h" 33d934cb88SDan Gohman #include "llvm/Support/LEB128.h" 3418eafb6cSDan Gohman #include "llvm/Support/StringSaver.h" 3518eafb6cSDan Gohman #include <vector> 3618eafb6cSDan Gohman 3718eafb6cSDan Gohman using namespace llvm; 3818eafb6cSDan Gohman 395e3d33a7SSam Clegg #define DEBUG_TYPE "mc" 4018eafb6cSDan Gohman 4118eafb6cSDan Gohman namespace { 429e15f359SSam Clegg 43d934cb88SDan Gohman // For patching purposes, we need to remember where each section starts, both 44d934cb88SDan Gohman // for patching up the section size field, and for patching up references to 45d934cb88SDan Gohman // locations within the section. 46d934cb88SDan Gohman struct SectionBookkeeping { 47d934cb88SDan Gohman // Where the size of the section is written. 48d934cb88SDan Gohman uint64_t SizeOffset; 49d934cb88SDan Gohman // Where the contents of the section starts (after the header). 50d934cb88SDan Gohman uint64_t ContentsOffset; 51d934cb88SDan Gohman }; 52d934cb88SDan Gohman 539e15f359SSam Clegg // The signature of a wasm function, in a struct capable of being used as a 549e15f359SSam Clegg // DenseMap key. 559e15f359SSam Clegg struct WasmFunctionType { 569e15f359SSam Clegg // Support empty and tombstone instances, needed by DenseMap. 579e15f359SSam Clegg enum { Plain, Empty, Tombstone } State; 589e15f359SSam Clegg 599e15f359SSam Clegg // The return types of the function. 609e15f359SSam Clegg SmallVector<wasm::ValType, 1> Returns; 619e15f359SSam Clegg 629e15f359SSam Clegg // The parameter types of the function. 639e15f359SSam Clegg SmallVector<wasm::ValType, 4> Params; 649e15f359SSam Clegg 659e15f359SSam Clegg WasmFunctionType() : State(Plain) {} 669e15f359SSam Clegg 679e15f359SSam Clegg bool operator==(const WasmFunctionType &Other) const { 689e15f359SSam Clegg return State == Other.State && Returns == Other.Returns && 699e15f359SSam Clegg Params == Other.Params; 709e15f359SSam Clegg } 719e15f359SSam Clegg }; 729e15f359SSam Clegg 739e15f359SSam Clegg // Traits for using WasmFunctionType in a DenseMap. 749e15f359SSam Clegg struct WasmFunctionTypeDenseMapInfo { 759e15f359SSam Clegg static WasmFunctionType getEmptyKey() { 769e15f359SSam Clegg WasmFunctionType FuncTy; 779e15f359SSam Clegg FuncTy.State = WasmFunctionType::Empty; 789e15f359SSam Clegg return FuncTy; 799e15f359SSam Clegg } 809e15f359SSam Clegg static WasmFunctionType getTombstoneKey() { 819e15f359SSam Clegg WasmFunctionType FuncTy; 829e15f359SSam Clegg FuncTy.State = WasmFunctionType::Tombstone; 839e15f359SSam Clegg return FuncTy; 849e15f359SSam Clegg } 859e15f359SSam Clegg static unsigned getHashValue(const WasmFunctionType &FuncTy) { 869e15f359SSam Clegg uintptr_t Value = FuncTy.State; 879e15f359SSam Clegg for (wasm::ValType Ret : FuncTy.Returns) 889e15f359SSam Clegg Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Ret)); 899e15f359SSam Clegg for (wasm::ValType Param : FuncTy.Params) 909e15f359SSam Clegg Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Param)); 919e15f359SSam Clegg return Value; 929e15f359SSam Clegg } 939e15f359SSam Clegg static bool isEqual(const WasmFunctionType &LHS, 949e15f359SSam Clegg const WasmFunctionType &RHS) { 959e15f359SSam Clegg return LHS == RHS; 969e15f359SSam Clegg } 979e15f359SSam Clegg }; 989e15f359SSam Clegg 997c395943SSam Clegg // A wasm data segment. A wasm binary contains only a single data section 1007c395943SSam Clegg // but that can contain many segments, each with their own virtual location 1017c395943SSam Clegg // in memory. Each MCSection data created by llvm is modeled as its own 1027c395943SSam Clegg // wasm data segment. 1037c395943SSam Clegg struct WasmDataSegment { 1047c395943SSam Clegg MCSectionWasm *Section; 105d95ed959SSam Clegg StringRef Name; 1067c395943SSam Clegg uint32_t Offset; 10763ebb813SSam Clegg uint32_t Alignment; 10863ebb813SSam Clegg uint32_t Flags; 1097c395943SSam Clegg SmallVector<char, 4> Data; 1107c395943SSam Clegg }; 1117c395943SSam Clegg 1129e15f359SSam Clegg // A wasm import to be written into the import section. 1139e15f359SSam Clegg struct WasmImport { 1149e15f359SSam Clegg StringRef ModuleName; 1159e15f359SSam Clegg StringRef FieldName; 1169e15f359SSam Clegg unsigned Kind; 1179e15f359SSam Clegg int32_t Type; 118*32ce5ca0SDan Gohman bool IsMutable; 1199e15f359SSam Clegg }; 1209e15f359SSam Clegg 1219e15f359SSam Clegg // A wasm function to be written into the function section. 1229e15f359SSam Clegg struct WasmFunction { 1239e15f359SSam Clegg int32_t Type; 1249e15f359SSam Clegg const MCSymbolWasm *Sym; 1259e15f359SSam Clegg }; 1269e15f359SSam Clegg 1279e15f359SSam Clegg // A wasm export to be written into the export section. 1289e15f359SSam Clegg struct WasmExport { 1299e15f359SSam Clegg StringRef FieldName; 1309e15f359SSam Clegg unsigned Kind; 1319e15f359SSam Clegg uint32_t Index; 1329e15f359SSam Clegg }; 1339e15f359SSam Clegg 1349e15f359SSam Clegg // A wasm global to be written into the global section. 1359e15f359SSam Clegg struct WasmGlobal { 1369e15f359SSam Clegg wasm::ValType Type; 1379e15f359SSam Clegg bool IsMutable; 1389e15f359SSam Clegg bool HasImport; 1399e15f359SSam Clegg uint64_t InitialValue; 1409e15f359SSam Clegg uint32_t ImportIndex; 1419e15f359SSam Clegg }; 1429e15f359SSam Clegg 1436dc65e91SSam Clegg // Information about a single relocation. 1446dc65e91SSam Clegg struct WasmRelocationEntry { 1456dc65e91SSam Clegg uint64_t Offset; // Where is the relocation. 1466dc65e91SSam Clegg const MCSymbolWasm *Symbol; // The symbol to relocate with. 1476dc65e91SSam Clegg int64_t Addend; // A value to add to the symbol. 1486dc65e91SSam Clegg unsigned Type; // The type of the relocation. 149fe6414b0SSam Clegg const MCSectionWasm *FixupSection;// The section the relocation is targeting. 1506dc65e91SSam Clegg 1516dc65e91SSam Clegg WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol, 1526dc65e91SSam Clegg int64_t Addend, unsigned Type, 153fe6414b0SSam Clegg const MCSectionWasm *FixupSection) 1546dc65e91SSam Clegg : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type), 1556dc65e91SSam Clegg FixupSection(FixupSection) {} 1566dc65e91SSam Clegg 157acd7d2b0SSam Clegg bool hasAddend() const { 158acd7d2b0SSam Clegg switch (Type) { 15913a2e899SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB: 16013a2e899SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: 16113a2e899SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32: 162acd7d2b0SSam Clegg return true; 163acd7d2b0SSam Clegg default: 164acd7d2b0SSam Clegg return false; 165acd7d2b0SSam Clegg } 166acd7d2b0SSam Clegg } 167acd7d2b0SSam Clegg 1686dc65e91SSam Clegg void print(raw_ostream &Out) const { 1699bf73c07SSam Clegg Out << "Off=" << Offset << ", Sym=" << *Symbol << ", Addend=" << Addend 170759631c7SSam Clegg << ", Type=" << Type 171759631c7SSam Clegg << ", FixupSection=" << FixupSection->getSectionName(); 1726dc65e91SSam Clegg } 173b7787fd0SSam Clegg 174615eb470SAaron Ballman #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 175b7787fd0SSam Clegg LLVM_DUMP_METHOD void dump() const { print(dbgs()); } 176b7787fd0SSam Clegg #endif 1776dc65e91SSam Clegg }; 1786dc65e91SSam Clegg 1791fb8daa6SSam Clegg #if !defined(NDEBUG) 1807f055deeSSam Clegg raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) { 181b7787fd0SSam Clegg Rel.print(OS); 182b7787fd0SSam Clegg return OS; 183b7787fd0SSam Clegg } 1841fb8daa6SSam Clegg #endif 185b7787fd0SSam Clegg 18618eafb6cSDan Gohman class WasmObjectWriter : public MCObjectWriter { 18718eafb6cSDan Gohman /// Helper struct for containing some precomputed information on symbols. 18818eafb6cSDan Gohman struct WasmSymbolData { 18918eafb6cSDan Gohman const MCSymbolWasm *Symbol; 19018eafb6cSDan Gohman StringRef Name; 19118eafb6cSDan Gohman 19218eafb6cSDan Gohman // Support lexicographic sorting. 19318eafb6cSDan Gohman bool operator<(const WasmSymbolData &RHS) const { return Name < RHS.Name; } 19418eafb6cSDan Gohman }; 19518eafb6cSDan Gohman 19618eafb6cSDan Gohman /// The target specific Wasm writer instance. 19718eafb6cSDan Gohman std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter; 19818eafb6cSDan Gohman 199d934cb88SDan Gohman // Relocations for fixing up references in the code section. 200d934cb88SDan Gohman std::vector<WasmRelocationEntry> CodeRelocations; 201d934cb88SDan Gohman 202d934cb88SDan Gohman // Relocations for fixing up references in the data section. 203d934cb88SDan Gohman std::vector<WasmRelocationEntry> DataRelocations; 204d934cb88SDan Gohman 205d934cb88SDan Gohman // Index values to use for fixing up call_indirect type indices. 206acd7d2b0SSam Clegg // Maps function symbols to the index of the type of the function 207acd7d2b0SSam Clegg DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices; 208d99f6078SSam Clegg // Maps function symbols to the table element index space. Used 209d99f6078SSam Clegg // for TABLE_INDEX relocation types (i.e. address taken functions). 210d99f6078SSam Clegg DenseMap<const MCSymbolWasm *, uint32_t> IndirectSymbolIndices; 211d99f6078SSam Clegg // Maps function/global symbols to the function/global index space. 212acd7d2b0SSam Clegg DenseMap<const MCSymbolWasm *, uint32_t> SymbolIndices; 213acd7d2b0SSam Clegg 214acd7d2b0SSam Clegg DenseMap<WasmFunctionType, int32_t, WasmFunctionTypeDenseMapInfo> 215acd7d2b0SSam Clegg FunctionTypeIndices; 2165e3d33a7SSam Clegg SmallVector<WasmFunctionType, 4> FunctionTypes; 2177c395943SSam Clegg SmallVector<WasmGlobal, 4> Globals; 2187c395943SSam Clegg unsigned NumGlobalImports = 0; 219d934cb88SDan Gohman 22018eafb6cSDan Gohman // TargetObjectWriter wrappers. 22118eafb6cSDan Gohman bool is64Bit() const { return TargetObjectWriter->is64Bit(); } 222ae03c1e7SSam Clegg unsigned getRelocType(const MCValue &Target, const MCFixup &Fixup) const { 223ae03c1e7SSam Clegg return TargetObjectWriter->getRelocType(Target, Fixup); 22418eafb6cSDan Gohman } 22518eafb6cSDan Gohman 226d934cb88SDan Gohman void startSection(SectionBookkeeping &Section, unsigned SectionId, 227d934cb88SDan Gohman const char *Name = nullptr); 228d934cb88SDan Gohman void endSection(SectionBookkeeping &Section); 229d934cb88SDan Gohman 23018eafb6cSDan Gohman public: 2311301a878SLang Hames WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW, 2321301a878SLang Hames raw_pwrite_stream &OS) 2331301a878SLang Hames : MCObjectWriter(OS, /*IsLittleEndian=*/true), 2341301a878SLang Hames TargetObjectWriter(std::move(MOTW)) {} 23518eafb6cSDan Gohman 236d934cb88SDan Gohman private: 23718eafb6cSDan Gohman ~WasmObjectWriter() override; 23818eafb6cSDan Gohman 239acd7d2b0SSam Clegg void reset() override { 240acd7d2b0SSam Clegg CodeRelocations.clear(); 241acd7d2b0SSam Clegg DataRelocations.clear(); 242acd7d2b0SSam Clegg TypeIndices.clear(); 243acd7d2b0SSam Clegg SymbolIndices.clear(); 244d99f6078SSam Clegg IndirectSymbolIndices.clear(); 245acd7d2b0SSam Clegg FunctionTypeIndices.clear(); 2465e3d33a7SSam Clegg FunctionTypes.clear(); 2477c395943SSam Clegg Globals.clear(); 248acd7d2b0SSam Clegg MCObjectWriter::reset(); 2497c395943SSam Clegg NumGlobalImports = 0; 250acd7d2b0SSam Clegg } 251acd7d2b0SSam Clegg 25218eafb6cSDan Gohman void writeHeader(const MCAssembler &Asm); 25318eafb6cSDan Gohman 25418eafb6cSDan Gohman void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout, 25518eafb6cSDan Gohman const MCFragment *Fragment, const MCFixup &Fixup, 256ceecfe5bSRafael Espindola MCValue Target, uint64_t &FixedValue) override; 25718eafb6cSDan Gohman 25818eafb6cSDan Gohman void executePostLayoutBinding(MCAssembler &Asm, 25918eafb6cSDan Gohman const MCAsmLayout &Layout) override; 26018eafb6cSDan Gohman 26118eafb6cSDan Gohman void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override; 2629e15f359SSam Clegg 263b7787fd0SSam Clegg void writeString(const StringRef Str) { 264b7787fd0SSam Clegg encodeULEB128(Str.size(), getStream()); 265b7787fd0SSam Clegg writeBytes(Str); 266b7787fd0SSam Clegg } 267b7787fd0SSam Clegg 2689e15f359SSam Clegg void writeValueType(wasm::ValType Ty) { 2699e15f359SSam Clegg encodeSLEB128(int32_t(Ty), getStream()); 2709e15f359SSam Clegg } 2719e15f359SSam Clegg 272457fb0b4SSam Clegg void writeTypeSection(ArrayRef<WasmFunctionType> FunctionTypes); 273457fb0b4SSam Clegg void writeImportSection(ArrayRef<WasmImport> Imports); 274457fb0b4SSam Clegg void writeFunctionSection(ArrayRef<WasmFunction> Functions); 275d99f6078SSam Clegg void writeTableSection(uint32_t NumElements); 2767c395943SSam Clegg void writeMemorySection(uint32_t DataSize); 2777c395943SSam Clegg void writeGlobalSection(); 278457fb0b4SSam Clegg void writeExportSection(ArrayRef<WasmExport> Exports); 279457fb0b4SSam Clegg void writeElemSection(ArrayRef<uint32_t> TableElems); 2809e15f359SSam Clegg void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout, 281457fb0b4SSam Clegg ArrayRef<WasmFunction> Functions); 282457fb0b4SSam Clegg void writeDataSection(ArrayRef<WasmDataSegment> Segments); 283457fb0b4SSam Clegg void writeNameSection(ArrayRef<WasmFunction> Functions, 284457fb0b4SSam Clegg ArrayRef<WasmImport> Imports, 2859e15f359SSam Clegg uint32_t NumFuncImports); 286acd7d2b0SSam Clegg void writeCodeRelocSection(); 2877c395943SSam Clegg void writeDataRelocSection(); 28831a2c809SSam Clegg void writeLinkingMetaDataSection( 28931a2c809SSam Clegg ArrayRef<WasmDataSegment> Segments, uint32_t DataSize, 29031a2c809SSam Clegg SmallVector<std::pair<StringRef, uint32_t>, 4> SymbolFlags, 291c2c99771SDan Gohman Optional<uint32_t> StackPointerGlobal); 292acd7d2b0SSam Clegg 2937c395943SSam Clegg uint32_t getProvisionalValue(const WasmRelocationEntry &RelEntry); 294acd7d2b0SSam Clegg void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations, 295acd7d2b0SSam Clegg uint64_t ContentsOffset); 296acd7d2b0SSam Clegg 2977c395943SSam Clegg void writeRelocations(ArrayRef<WasmRelocationEntry> Relocations); 298acd7d2b0SSam Clegg uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry); 2995e3d33a7SSam Clegg uint32_t getFunctionType(const MCSymbolWasm& Symbol); 3005e3d33a7SSam Clegg uint32_t registerFunctionType(const MCSymbolWasm& Symbol); 30118eafb6cSDan Gohman }; 3029e15f359SSam Clegg 30318eafb6cSDan Gohman } // end anonymous namespace 30418eafb6cSDan Gohman 30518eafb6cSDan Gohman WasmObjectWriter::~WasmObjectWriter() {} 30618eafb6cSDan Gohman 307d934cb88SDan Gohman // Write out a section header and a patchable section size field. 308d934cb88SDan Gohman void WasmObjectWriter::startSection(SectionBookkeeping &Section, 309d934cb88SDan Gohman unsigned SectionId, 310d934cb88SDan Gohman const char *Name) { 311d934cb88SDan Gohman assert((Name != nullptr) == (SectionId == wasm::WASM_SEC_CUSTOM) && 312d934cb88SDan Gohman "Only custom sections can have names"); 313d934cb88SDan Gohman 314b7787fd0SSam Clegg DEBUG(dbgs() << "startSection " << SectionId << ": " << Name << "\n"); 315e2688c43SDerek Schuff encodeULEB128(SectionId, getStream()); 316d934cb88SDan Gohman 317d934cb88SDan Gohman Section.SizeOffset = getStream().tell(); 318d934cb88SDan Gohman 319d934cb88SDan Gohman // The section size. We don't know the size yet, so reserve enough space 320d934cb88SDan Gohman // for any 32-bit value; we'll patch it later. 321d934cb88SDan Gohman encodeULEB128(UINT32_MAX, getStream()); 322d934cb88SDan Gohman 323d934cb88SDan Gohman // The position where the section starts, for measuring its size. 324d934cb88SDan Gohman Section.ContentsOffset = getStream().tell(); 325d934cb88SDan Gohman 326d934cb88SDan Gohman // Custom sections in wasm also have a string identifier. 327d934cb88SDan Gohman if (SectionId == wasm::WASM_SEC_CUSTOM) { 328b7787fd0SSam Clegg assert(Name); 329b7787fd0SSam Clegg writeString(StringRef(Name)); 330d934cb88SDan Gohman } 331d934cb88SDan Gohman } 332d934cb88SDan Gohman 333d934cb88SDan Gohman // Now that the section is complete and we know how big it is, patch up the 334d934cb88SDan Gohman // section size field at the start of the section. 335d934cb88SDan Gohman void WasmObjectWriter::endSection(SectionBookkeeping &Section) { 336d934cb88SDan Gohman uint64_t Size = getStream().tell() - Section.ContentsOffset; 337d934cb88SDan Gohman if (uint32_t(Size) != Size) 338d934cb88SDan Gohman report_fatal_error("section size does not fit in a uint32_t"); 339d934cb88SDan Gohman 340b7787fd0SSam Clegg DEBUG(dbgs() << "endSection size=" << Size << "\n"); 341d934cb88SDan Gohman 342d934cb88SDan Gohman // Write the final section size to the payload_len field, which follows 343d934cb88SDan Gohman // the section id byte. 344d934cb88SDan Gohman uint8_t Buffer[16]; 34566a99e41SSam Clegg unsigned SizeLen = encodeULEB128(Size, Buffer, 5); 346d934cb88SDan Gohman assert(SizeLen == 5); 347d934cb88SDan Gohman getStream().pwrite((char *)Buffer, SizeLen, Section.SizeOffset); 348d934cb88SDan Gohman } 349d934cb88SDan Gohman 35018eafb6cSDan Gohman // Emit the Wasm header. 35118eafb6cSDan Gohman void WasmObjectWriter::writeHeader(const MCAssembler &Asm) { 3527ea5adffSDan Gohman writeBytes(StringRef(wasm::WasmMagic, sizeof(wasm::WasmMagic))); 3537ea5adffSDan Gohman writeLE32(wasm::WasmVersion); 35418eafb6cSDan Gohman } 35518eafb6cSDan Gohman 35618eafb6cSDan Gohman void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm, 35718eafb6cSDan Gohman const MCAsmLayout &Layout) { 35818eafb6cSDan Gohman } 35918eafb6cSDan Gohman 36018eafb6cSDan Gohman void WasmObjectWriter::recordRelocation(MCAssembler &Asm, 36118eafb6cSDan Gohman const MCAsmLayout &Layout, 36218eafb6cSDan Gohman const MCFragment *Fragment, 36318eafb6cSDan Gohman const MCFixup &Fixup, MCValue Target, 364ceecfe5bSRafael Espindola uint64_t &FixedValue) { 365ceecfe5bSRafael Espindola MCAsmBackend &Backend = Asm.getBackend(); 366ceecfe5bSRafael Espindola bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags & 367ceecfe5bSRafael Espindola MCFixupKindInfo::FKF_IsPCRel; 368fe6414b0SSam Clegg const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent()); 369d934cb88SDan Gohman uint64_t C = Target.getConstant(); 370d934cb88SDan Gohman uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset(); 371d934cb88SDan Gohman MCContext &Ctx = Asm.getContext(); 372d934cb88SDan Gohman 373d934cb88SDan Gohman if (const MCSymbolRefExpr *RefB = Target.getSymB()) { 374d934cb88SDan Gohman assert(RefB->getKind() == MCSymbolRefExpr::VK_None && 375d934cb88SDan Gohman "Should not have constructed this"); 376d934cb88SDan Gohman 377d934cb88SDan Gohman // Let A, B and C being the components of Target and R be the location of 378d934cb88SDan Gohman // the fixup. If the fixup is not pcrel, we want to compute (A - B + C). 379d934cb88SDan Gohman // If it is pcrel, we want to compute (A - B + C - R). 380d934cb88SDan Gohman 381d934cb88SDan Gohman // In general, Wasm has no relocations for -B. It can only represent (A + C) 382d934cb88SDan Gohman // or (A + C - R). If B = R + K and the relocation is not pcrel, we can 383d934cb88SDan Gohman // replace B to implement it: (A - R - K + C) 384d934cb88SDan Gohman if (IsPCRel) { 385d934cb88SDan Gohman Ctx.reportError( 386d934cb88SDan Gohman Fixup.getLoc(), 387d934cb88SDan Gohman "No relocation available to represent this relative expression"); 388d934cb88SDan Gohman return; 389d934cb88SDan Gohman } 390d934cb88SDan Gohman 391d934cb88SDan Gohman const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol()); 392d934cb88SDan Gohman 393d934cb88SDan Gohman if (SymB.isUndefined()) { 394d934cb88SDan Gohman Ctx.reportError(Fixup.getLoc(), 395d934cb88SDan Gohman Twine("symbol '") + SymB.getName() + 396d934cb88SDan Gohman "' can not be undefined in a subtraction expression"); 397d934cb88SDan Gohman return; 398d934cb88SDan Gohman } 399d934cb88SDan Gohman 400d934cb88SDan Gohman assert(!SymB.isAbsolute() && "Should have been folded"); 401d934cb88SDan Gohman const MCSection &SecB = SymB.getSection(); 402d934cb88SDan Gohman if (&SecB != &FixupSection) { 403d934cb88SDan Gohman Ctx.reportError(Fixup.getLoc(), 404d934cb88SDan Gohman "Cannot represent a difference across sections"); 405d934cb88SDan Gohman return; 406d934cb88SDan Gohman } 407d934cb88SDan Gohman 408d934cb88SDan Gohman uint64_t SymBOffset = Layout.getSymbolOffset(SymB); 409d934cb88SDan Gohman uint64_t K = SymBOffset - FixupOffset; 410d934cb88SDan Gohman IsPCRel = true; 411d934cb88SDan Gohman C -= K; 412d934cb88SDan Gohman } 413d934cb88SDan Gohman 414d934cb88SDan Gohman // We either rejected the fixup or folded B into C at this point. 415d934cb88SDan Gohman const MCSymbolRefExpr *RefA = Target.getSymA(); 416d934cb88SDan Gohman const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr; 417d934cb88SDan Gohman 418d934cb88SDan Gohman if (SymA && SymA->isVariable()) { 419d934cb88SDan Gohman const MCExpr *Expr = SymA->getVariableValue(); 4206ad8f190SSam Clegg const auto *Inner = cast<MCSymbolRefExpr>(Expr); 4216ad8f190SSam Clegg if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF) 4226ad8f190SSam Clegg llvm_unreachable("weakref used in reloc not yet implemented"); 423d934cb88SDan Gohman } 424d934cb88SDan Gohman 425d934cb88SDan Gohman // Put any constant offset in an addend. Offsets can be negative, and 426d934cb88SDan Gohman // LLVM expects wrapping, in contrast to wasm's immediates which can't 427d934cb88SDan Gohman // be negative and don't wrap. 428d934cb88SDan Gohman FixedValue = 0; 429d934cb88SDan Gohman 4306ad8f190SSam Clegg if (SymA) 431d934cb88SDan Gohman SymA->setUsedInReloc(); 432d934cb88SDan Gohman 433ae03c1e7SSam Clegg assert(!IsPCRel); 4349d24fb7fSSam Clegg assert(SymA); 4359d24fb7fSSam Clegg 436ae03c1e7SSam Clegg unsigned Type = getRelocType(Target, Fixup); 437ae03c1e7SSam Clegg 438d934cb88SDan Gohman WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection); 439b7787fd0SSam Clegg DEBUG(dbgs() << "WasmReloc: " << Rec << "\n"); 440d934cb88SDan Gohman 44112fd3da9SSam Clegg if (FixupSection.isWasmData()) 442d934cb88SDan Gohman DataRelocations.push_back(Rec); 44312fd3da9SSam Clegg else if (FixupSection.getKind().isText()) 44412fd3da9SSam Clegg CodeRelocations.push_back(Rec); 44512fd3da9SSam Clegg else if (!FixupSection.getKind().isMetadata()) 44612fd3da9SSam Clegg // TODO(sbc): Add support for debug sections. 44712fd3da9SSam Clegg llvm_unreachable("unexpected section type"); 448d934cb88SDan Gohman } 449d934cb88SDan Gohman 450d934cb88SDan Gohman // Write X as an (unsigned) LEB value at offset Offset in Stream, padded 451d934cb88SDan Gohman // to allow patching. 452d934cb88SDan Gohman static void 453d934cb88SDan Gohman WritePatchableLEB(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) { 454d934cb88SDan Gohman uint8_t Buffer[5]; 45566a99e41SSam Clegg unsigned SizeLen = encodeULEB128(X, Buffer, 5); 456d934cb88SDan Gohman assert(SizeLen == 5); 457d934cb88SDan Gohman Stream.pwrite((char *)Buffer, SizeLen, Offset); 458d934cb88SDan Gohman } 459d934cb88SDan Gohman 460d934cb88SDan Gohman // Write X as an signed LEB value at offset Offset in Stream, padded 461d934cb88SDan Gohman // to allow patching. 462d934cb88SDan Gohman static void 463d934cb88SDan Gohman WritePatchableSLEB(raw_pwrite_stream &Stream, int32_t X, uint64_t Offset) { 464d934cb88SDan Gohman uint8_t Buffer[5]; 46566a99e41SSam Clegg unsigned SizeLen = encodeSLEB128(X, Buffer, 5); 466d934cb88SDan Gohman assert(SizeLen == 5); 467d934cb88SDan Gohman Stream.pwrite((char *)Buffer, SizeLen, Offset); 468d934cb88SDan Gohman } 469d934cb88SDan Gohman 470d934cb88SDan Gohman // Write X as a plain integer value at offset Offset in Stream. 471d934cb88SDan Gohman static void WriteI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) { 472d934cb88SDan Gohman uint8_t Buffer[4]; 473d934cb88SDan Gohman support::endian::write32le(Buffer, X); 474d934cb88SDan Gohman Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset); 475d934cb88SDan Gohman } 476d934cb88SDan Gohman 477aff1c4dfSSam Clegg static const MCSymbolWasm* ResolveSymbol(const MCSymbolWasm& Symbol) { 478aff1c4dfSSam Clegg if (Symbol.isVariable()) { 479aff1c4dfSSam Clegg const MCExpr *Expr = Symbol.getVariableValue(); 480aff1c4dfSSam Clegg auto *Inner = cast<MCSymbolRefExpr>(Expr); 481aff1c4dfSSam Clegg return cast<MCSymbolWasm>(&Inner->getSymbol()); 482aff1c4dfSSam Clegg } 483aff1c4dfSSam Clegg return &Symbol; 484aff1c4dfSSam Clegg } 485aff1c4dfSSam Clegg 486d934cb88SDan Gohman // Compute a value to write into the code at the location covered 487d934cb88SDan Gohman // by RelEntry. This value isn't used by the static linker, since 488d934cb88SDan Gohman // we have addends; it just serves to make the code more readable 489d934cb88SDan Gohman // and to make standalone wasm modules directly usable. 4907c395943SSam Clegg uint32_t 4917c395943SSam Clegg WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) { 492aff1c4dfSSam Clegg const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol); 493d934cb88SDan Gohman 494d934cb88SDan Gohman // For undefined symbols, use a hopefully invalid value. 495b7787fd0SSam Clegg if (!Sym->isDefined(/*SetUsed=*/false)) 496d934cb88SDan Gohman return UINT32_MAX; 497d934cb88SDan Gohman 4987c395943SSam Clegg uint32_t GlobalIndex = SymbolIndices[Sym]; 4997c395943SSam Clegg const WasmGlobal& Global = Globals[GlobalIndex - NumGlobalImports]; 5007c395943SSam Clegg uint64_t Address = Global.InitialValue + RelEntry.Addend; 501d934cb88SDan Gohman 502d934cb88SDan Gohman // Ignore overflow. LLVM allows address arithmetic to silently wrap. 503d934cb88SDan Gohman uint32_t Value = Address; 504d934cb88SDan Gohman 505d934cb88SDan Gohman return Value; 506d934cb88SDan Gohman } 507d934cb88SDan Gohman 508759631c7SSam Clegg static void addData(SmallVectorImpl<char> &DataBytes, 50963ebb813SSam Clegg MCSectionWasm &DataSection) { 510759631c7SSam Clegg DEBUG(errs() << "addData: " << DataSection.getSectionName() << "\n"); 511759631c7SSam Clegg 51263ebb813SSam Clegg DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment())); 51363ebb813SSam Clegg 514c55d13f4SSam Clegg size_t LastFragmentSize = 0; 515759631c7SSam Clegg for (const MCFragment &Frag : DataSection) { 516759631c7SSam Clegg if (Frag.hasInstructions()) 517759631c7SSam Clegg report_fatal_error("only data supported in data sections"); 518759631c7SSam Clegg 519759631c7SSam Clegg if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) { 520759631c7SSam Clegg if (Align->getValueSize() != 1) 521759631c7SSam Clegg report_fatal_error("only byte values supported for alignment"); 522759631c7SSam Clegg // If nops are requested, use zeros, as this is the data section. 523759631c7SSam Clegg uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue(); 524759631c7SSam Clegg uint64_t Size = std::min<uint64_t>(alignTo(DataBytes.size(), 525759631c7SSam Clegg Align->getAlignment()), 526759631c7SSam Clegg DataBytes.size() + 527759631c7SSam Clegg Align->getMaxBytesToEmit()); 528759631c7SSam Clegg DataBytes.resize(Size, Value); 529759631c7SSam Clegg } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) { 530759631c7SSam Clegg DataBytes.insert(DataBytes.end(), Fill->getSize(), Fill->getValue()); 531759631c7SSam Clegg } else { 532759631c7SSam Clegg const auto &DataFrag = cast<MCDataFragment>(Frag); 533759631c7SSam Clegg const SmallVectorImpl<char> &Contents = DataFrag.getContents(); 534759631c7SSam Clegg 535759631c7SSam Clegg DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end()); 536c55d13f4SSam Clegg LastFragmentSize = Contents.size(); 537759631c7SSam Clegg } 538759631c7SSam Clegg } 539759631c7SSam Clegg 540c55d13f4SSam Clegg // Don't allow empty segments, or segments that end with zero-sized 541c55d13f4SSam Clegg // fragment, otherwise the linker cannot map symbols to a unique 542c55d13f4SSam Clegg // data segment. This can be triggered by zero-sized structs 543c55d13f4SSam Clegg // See: test/MC/WebAssembly/bss.ll 544c55d13f4SSam Clegg if (LastFragmentSize == 0) 545c55d13f4SSam Clegg DataBytes.resize(DataBytes.size() + 1); 546759631c7SSam Clegg DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n"); 547759631c7SSam Clegg } 548759631c7SSam Clegg 549acd7d2b0SSam Clegg uint32_t WasmObjectWriter::getRelocationIndexValue( 550acd7d2b0SSam Clegg const WasmRelocationEntry &RelEntry) { 551acd7d2b0SSam Clegg switch (RelEntry.Type) { 552acd7d2b0SSam Clegg case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB: 553acd7d2b0SSam Clegg case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: 554b7787fd0SSam Clegg if (!IndirectSymbolIndices.count(RelEntry.Symbol)) 555b7787fd0SSam Clegg report_fatal_error("symbol not found table index space: " + 556b7787fd0SSam Clegg RelEntry.Symbol->getName()); 557d99f6078SSam Clegg return IndirectSymbolIndices[RelEntry.Symbol]; 558d99f6078SSam Clegg case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB: 5599d24fb7fSSam Clegg case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB: 56013a2e899SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB: 56113a2e899SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: 56213a2e899SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32: 563b7787fd0SSam Clegg if (!SymbolIndices.count(RelEntry.Symbol)) 564b7787fd0SSam Clegg report_fatal_error("symbol not found function/global index space: " + 565b7787fd0SSam Clegg RelEntry.Symbol->getName()); 566acd7d2b0SSam Clegg return SymbolIndices[RelEntry.Symbol]; 567acd7d2b0SSam Clegg case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB: 568b7787fd0SSam Clegg if (!TypeIndices.count(RelEntry.Symbol)) 569b7787fd0SSam Clegg report_fatal_error("symbol not found in type index space: " + 570b7787fd0SSam Clegg RelEntry.Symbol->getName()); 571acd7d2b0SSam Clegg return TypeIndices[RelEntry.Symbol]; 572acd7d2b0SSam Clegg default: 573acd7d2b0SSam Clegg llvm_unreachable("invalid relocation type"); 574acd7d2b0SSam Clegg } 575acd7d2b0SSam Clegg } 576acd7d2b0SSam Clegg 577d934cb88SDan Gohman // Apply the portions of the relocation records that we can handle ourselves 578d934cb88SDan Gohman // directly. 579acd7d2b0SSam Clegg void WasmObjectWriter::applyRelocations( 580acd7d2b0SSam Clegg ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) { 581acd7d2b0SSam Clegg raw_pwrite_stream &Stream = getStream(); 582d934cb88SDan Gohman for (const WasmRelocationEntry &RelEntry : Relocations) { 583d934cb88SDan Gohman uint64_t Offset = ContentsOffset + 584d934cb88SDan Gohman RelEntry.FixupSection->getSectionOffset() + 585d934cb88SDan Gohman RelEntry.Offset; 586d934cb88SDan Gohman 587b7787fd0SSam Clegg DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n"); 588acd7d2b0SSam Clegg switch (RelEntry.Type) { 589acd7d2b0SSam Clegg case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB: 590acd7d2b0SSam Clegg case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB: 5919d24fb7fSSam Clegg case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB: 5929d24fb7fSSam Clegg case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB: { 593acd7d2b0SSam Clegg uint32_t Index = getRelocationIndexValue(RelEntry); 594acd7d2b0SSam Clegg WritePatchableSLEB(Stream, Index, Offset); 595d934cb88SDan Gohman break; 596d934cb88SDan Gohman } 597acd7d2b0SSam Clegg case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: { 598acd7d2b0SSam Clegg uint32_t Index = getRelocationIndexValue(RelEntry); 599acd7d2b0SSam Clegg WriteI32(Stream, Index, Offset); 600d934cb88SDan Gohman break; 601d934cb88SDan Gohman } 60213a2e899SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: { 6037c395943SSam Clegg uint32_t Value = getProvisionalValue(RelEntry); 604d934cb88SDan Gohman WritePatchableSLEB(Stream, Value, Offset); 605d934cb88SDan Gohman break; 606d934cb88SDan Gohman } 60713a2e899SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB: { 6087c395943SSam Clegg uint32_t Value = getProvisionalValue(RelEntry); 609d934cb88SDan Gohman WritePatchableLEB(Stream, Value, Offset); 610d934cb88SDan Gohman break; 611d934cb88SDan Gohman } 61213a2e899SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32: { 6137c395943SSam Clegg uint32_t Value = getProvisionalValue(RelEntry); 614d934cb88SDan Gohman WriteI32(Stream, Value, Offset); 615d934cb88SDan Gohman break; 616d934cb88SDan Gohman } 617d934cb88SDan Gohman default: 6189d24fb7fSSam Clegg llvm_unreachable("invalid relocation type"); 619d934cb88SDan Gohman } 620d934cb88SDan Gohman } 62118eafb6cSDan Gohman } 62218eafb6cSDan Gohman 623acd7d2b0SSam Clegg // Write out the portions of the relocation records that the linker will 624970d02c4SDan Gohman // need to handle. 625acd7d2b0SSam Clegg void WasmObjectWriter::writeRelocations( 6267c395943SSam Clegg ArrayRef<WasmRelocationEntry> Relocations) { 627acd7d2b0SSam Clegg raw_pwrite_stream &Stream = getStream(); 628acd7d2b0SSam Clegg for (const WasmRelocationEntry& RelEntry : Relocations) { 629970d02c4SDan Gohman 630acd7d2b0SSam Clegg uint64_t Offset = RelEntry.Offset + 6317c395943SSam Clegg RelEntry.FixupSection->getSectionOffset(); 632acd7d2b0SSam Clegg uint32_t Index = getRelocationIndexValue(RelEntry); 633970d02c4SDan Gohman 634acd7d2b0SSam Clegg encodeULEB128(RelEntry.Type, Stream); 635970d02c4SDan Gohman encodeULEB128(Offset, Stream); 636acd7d2b0SSam Clegg encodeULEB128(Index, Stream); 637acd7d2b0SSam Clegg if (RelEntry.hasAddend()) 638acd7d2b0SSam Clegg encodeSLEB128(RelEntry.Addend, Stream); 639970d02c4SDan Gohman } 640970d02c4SDan Gohman } 641970d02c4SDan Gohman 6429e15f359SSam Clegg void WasmObjectWriter::writeTypeSection( 643457fb0b4SSam Clegg ArrayRef<WasmFunctionType> FunctionTypes) { 6449e15f359SSam Clegg if (FunctionTypes.empty()) 6459e15f359SSam Clegg return; 6469e15f359SSam Clegg 6479e15f359SSam Clegg SectionBookkeeping Section; 6489e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_TYPE); 6499e15f359SSam Clegg 6509e15f359SSam Clegg encodeULEB128(FunctionTypes.size(), getStream()); 6519e15f359SSam Clegg 6529e15f359SSam Clegg for (const WasmFunctionType &FuncTy : FunctionTypes) { 6539e15f359SSam Clegg encodeSLEB128(wasm::WASM_TYPE_FUNC, getStream()); 6549e15f359SSam Clegg encodeULEB128(FuncTy.Params.size(), getStream()); 6559e15f359SSam Clegg for (wasm::ValType Ty : FuncTy.Params) 6569e15f359SSam Clegg writeValueType(Ty); 6579e15f359SSam Clegg encodeULEB128(FuncTy.Returns.size(), getStream()); 6589e15f359SSam Clegg for (wasm::ValType Ty : FuncTy.Returns) 6599e15f359SSam Clegg writeValueType(Ty); 6609e15f359SSam Clegg } 6619e15f359SSam Clegg 6629e15f359SSam Clegg endSection(Section); 6639e15f359SSam Clegg } 6649e15f359SSam Clegg 665457fb0b4SSam Clegg void WasmObjectWriter::writeImportSection(ArrayRef<WasmImport> Imports) { 6669e15f359SSam Clegg if (Imports.empty()) 6679e15f359SSam Clegg return; 6689e15f359SSam Clegg 6699e15f359SSam Clegg SectionBookkeeping Section; 6709e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_IMPORT); 6719e15f359SSam Clegg 6729e15f359SSam Clegg encodeULEB128(Imports.size(), getStream()); 6739e15f359SSam Clegg for (const WasmImport &Import : Imports) { 674b7787fd0SSam Clegg writeString(Import.ModuleName); 675b7787fd0SSam Clegg writeString(Import.FieldName); 6769e15f359SSam Clegg 6779e15f359SSam Clegg encodeULEB128(Import.Kind, getStream()); 6789e15f359SSam Clegg 6799e15f359SSam Clegg switch (Import.Kind) { 6809e15f359SSam Clegg case wasm::WASM_EXTERNAL_FUNCTION: 6819e15f359SSam Clegg encodeULEB128(Import.Type, getStream()); 6829e15f359SSam Clegg break; 6839e15f359SSam Clegg case wasm::WASM_EXTERNAL_GLOBAL: 6849e15f359SSam Clegg encodeSLEB128(int32_t(Import.Type), getStream()); 685*32ce5ca0SDan Gohman encodeULEB128(int32_t(Import.IsMutable), getStream()); 6869e15f359SSam Clegg break; 6879e15f359SSam Clegg default: 6889e15f359SSam Clegg llvm_unreachable("unsupported import kind"); 6899e15f359SSam Clegg } 6909e15f359SSam Clegg } 6919e15f359SSam Clegg 6929e15f359SSam Clegg endSection(Section); 6939e15f359SSam Clegg } 6949e15f359SSam Clegg 695457fb0b4SSam Clegg void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) { 6969e15f359SSam Clegg if (Functions.empty()) 6979e15f359SSam Clegg return; 6989e15f359SSam Clegg 6999e15f359SSam Clegg SectionBookkeeping Section; 7009e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_FUNCTION); 7019e15f359SSam Clegg 7029e15f359SSam Clegg encodeULEB128(Functions.size(), getStream()); 7039e15f359SSam Clegg for (const WasmFunction &Func : Functions) 7049e15f359SSam Clegg encodeULEB128(Func.Type, getStream()); 7059e15f359SSam Clegg 7069e15f359SSam Clegg endSection(Section); 7079e15f359SSam Clegg } 7089e15f359SSam Clegg 709d99f6078SSam Clegg void WasmObjectWriter::writeTableSection(uint32_t NumElements) { 7109e15f359SSam Clegg // For now, always emit the table section, since indirect calls are not 7119e15f359SSam Clegg // valid without it. In the future, we could perhaps be more clever and omit 7129e15f359SSam Clegg // it if there are no indirect calls. 713d99f6078SSam Clegg 7149e15f359SSam Clegg SectionBookkeeping Section; 7159e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_TABLE); 7169e15f359SSam Clegg 717d99f6078SSam Clegg encodeULEB128(1, getStream()); // The number of tables. 718d99f6078SSam Clegg // Fixed to 1 for now. 719d99f6078SSam Clegg encodeSLEB128(wasm::WASM_TYPE_ANYFUNC, getStream()); // Type of table 7209e15f359SSam Clegg encodeULEB128(0, getStream()); // flags 721d99f6078SSam Clegg encodeULEB128(NumElements, getStream()); // initial 7229e15f359SSam Clegg 7239e15f359SSam Clegg endSection(Section); 7249e15f359SSam Clegg } 7259e15f359SSam Clegg 7267c395943SSam Clegg void WasmObjectWriter::writeMemorySection(uint32_t DataSize) { 7279e15f359SSam Clegg // For now, always emit the memory section, since loads and stores are not 7289e15f359SSam Clegg // valid without it. In the future, we could perhaps be more clever and omit 7299e15f359SSam Clegg // it if there are no loads or stores. 7309e15f359SSam Clegg SectionBookkeeping Section; 7317c395943SSam Clegg uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize; 7329e15f359SSam Clegg 7339e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_MEMORY); 7349e15f359SSam Clegg encodeULEB128(1, getStream()); // number of memory spaces 7359e15f359SSam Clegg 7369e15f359SSam Clegg encodeULEB128(0, getStream()); // flags 7379e15f359SSam Clegg encodeULEB128(NumPages, getStream()); // initial 7389e15f359SSam Clegg 7399e15f359SSam Clegg endSection(Section); 7409e15f359SSam Clegg } 7419e15f359SSam Clegg 7427c395943SSam Clegg void WasmObjectWriter::writeGlobalSection() { 7439e15f359SSam Clegg if (Globals.empty()) 7449e15f359SSam Clegg return; 7459e15f359SSam Clegg 7469e15f359SSam Clegg SectionBookkeeping Section; 7479e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_GLOBAL); 7489e15f359SSam Clegg 7499e15f359SSam Clegg encodeULEB128(Globals.size(), getStream()); 7509e15f359SSam Clegg for (const WasmGlobal &Global : Globals) { 7519e15f359SSam Clegg writeValueType(Global.Type); 7529e15f359SSam Clegg write8(Global.IsMutable); 7539e15f359SSam Clegg 7549e15f359SSam Clegg if (Global.HasImport) { 7559e15f359SSam Clegg assert(Global.InitialValue == 0); 7569e15f359SSam Clegg write8(wasm::WASM_OPCODE_GET_GLOBAL); 7579e15f359SSam Clegg encodeULEB128(Global.ImportIndex, getStream()); 7589e15f359SSam Clegg } else { 7599e15f359SSam Clegg assert(Global.ImportIndex == 0); 7609e15f359SSam Clegg write8(wasm::WASM_OPCODE_I32_CONST); 7619e15f359SSam Clegg encodeSLEB128(Global.InitialValue, getStream()); // offset 7629e15f359SSam Clegg } 7639e15f359SSam Clegg write8(wasm::WASM_OPCODE_END); 7649e15f359SSam Clegg } 7659e15f359SSam Clegg 7669e15f359SSam Clegg endSection(Section); 7679e15f359SSam Clegg } 7689e15f359SSam Clegg 769457fb0b4SSam Clegg void WasmObjectWriter::writeExportSection(ArrayRef<WasmExport> Exports) { 7709e15f359SSam Clegg if (Exports.empty()) 7719e15f359SSam Clegg return; 7729e15f359SSam Clegg 7739e15f359SSam Clegg SectionBookkeeping Section; 7749e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_EXPORT); 7759e15f359SSam Clegg 7769e15f359SSam Clegg encodeULEB128(Exports.size(), getStream()); 7779e15f359SSam Clegg for (const WasmExport &Export : Exports) { 778b7787fd0SSam Clegg writeString(Export.FieldName); 7799e15f359SSam Clegg encodeSLEB128(Export.Kind, getStream()); 7809e15f359SSam Clegg encodeULEB128(Export.Index, getStream()); 7819e15f359SSam Clegg } 7829e15f359SSam Clegg 7839e15f359SSam Clegg endSection(Section); 7849e15f359SSam Clegg } 7859e15f359SSam Clegg 786457fb0b4SSam Clegg void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) { 7879e15f359SSam Clegg if (TableElems.empty()) 7889e15f359SSam Clegg return; 7899e15f359SSam Clegg 7909e15f359SSam Clegg SectionBookkeeping Section; 7919e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_ELEM); 7929e15f359SSam Clegg 7939e15f359SSam Clegg encodeULEB128(1, getStream()); // number of "segments" 7949e15f359SSam Clegg encodeULEB128(0, getStream()); // the table index 7959e15f359SSam Clegg 7969e15f359SSam Clegg // init expr for starting offset 7979e15f359SSam Clegg write8(wasm::WASM_OPCODE_I32_CONST); 7989e15f359SSam Clegg encodeSLEB128(0, getStream()); 7999e15f359SSam Clegg write8(wasm::WASM_OPCODE_END); 8009e15f359SSam Clegg 8019e15f359SSam Clegg encodeULEB128(TableElems.size(), getStream()); 8029e15f359SSam Clegg for (uint32_t Elem : TableElems) 8039e15f359SSam Clegg encodeULEB128(Elem, getStream()); 8049e15f359SSam Clegg 8059e15f359SSam Clegg endSection(Section); 8069e15f359SSam Clegg } 8079e15f359SSam Clegg 808457fb0b4SSam Clegg void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm, 809457fb0b4SSam Clegg const MCAsmLayout &Layout, 810457fb0b4SSam Clegg ArrayRef<WasmFunction> Functions) { 8119e15f359SSam Clegg if (Functions.empty()) 8129e15f359SSam Clegg return; 8139e15f359SSam Clegg 8149e15f359SSam Clegg SectionBookkeeping Section; 8159e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_CODE); 8169e15f359SSam Clegg 8179e15f359SSam Clegg encodeULEB128(Functions.size(), getStream()); 8189e15f359SSam Clegg 8199e15f359SSam Clegg for (const WasmFunction &Func : Functions) { 820fe6414b0SSam Clegg auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection()); 8219e15f359SSam Clegg 8229e15f359SSam Clegg int64_t Size = 0; 8239e15f359SSam Clegg if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout)) 8249e15f359SSam Clegg report_fatal_error(".size expression must be evaluatable"); 8259e15f359SSam Clegg 8269e15f359SSam Clegg encodeULEB128(Size, getStream()); 827fe6414b0SSam Clegg FuncSection.setSectionOffset(getStream().tell() - Section.ContentsOffset); 8289e15f359SSam Clegg Asm.writeSectionData(&FuncSection, Layout); 8299e15f359SSam Clegg } 8309e15f359SSam Clegg 8319e15f359SSam Clegg // Apply fixups. 832acd7d2b0SSam Clegg applyRelocations(CodeRelocations, Section.ContentsOffset); 8339e15f359SSam Clegg 8349e15f359SSam Clegg endSection(Section); 8359e15f359SSam Clegg } 8369e15f359SSam Clegg 837457fb0b4SSam Clegg void WasmObjectWriter::writeDataSection(ArrayRef<WasmDataSegment> Segments) { 8387c395943SSam Clegg if (Segments.empty()) 8397c395943SSam Clegg return; 8409e15f359SSam Clegg 8419e15f359SSam Clegg SectionBookkeeping Section; 8429e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_DATA); 8439e15f359SSam Clegg 8447c395943SSam Clegg encodeULEB128(Segments.size(), getStream()); // count 8457c395943SSam Clegg 8467c395943SSam Clegg for (const WasmDataSegment & Segment : Segments) { 8479e15f359SSam Clegg encodeULEB128(0, getStream()); // memory index 8489e15f359SSam Clegg write8(wasm::WASM_OPCODE_I32_CONST); 8497c395943SSam Clegg encodeSLEB128(Segment.Offset, getStream()); // offset 8509e15f359SSam Clegg write8(wasm::WASM_OPCODE_END); 8517c395943SSam Clegg encodeULEB128(Segment.Data.size(), getStream()); // size 8527c395943SSam Clegg Segment.Section->setSectionOffset(getStream().tell() - Section.ContentsOffset); 8537c395943SSam Clegg writeBytes(Segment.Data); // data 8547c395943SSam Clegg } 8559e15f359SSam Clegg 8569e15f359SSam Clegg // Apply fixups. 8577c395943SSam Clegg applyRelocations(DataRelocations, Section.ContentsOffset); 8589e15f359SSam Clegg 8599e15f359SSam Clegg endSection(Section); 8609e15f359SSam Clegg } 8619e15f359SSam Clegg 8629e15f359SSam Clegg void WasmObjectWriter::writeNameSection( 863457fb0b4SSam Clegg ArrayRef<WasmFunction> Functions, 864457fb0b4SSam Clegg ArrayRef<WasmImport> Imports, 8659e15f359SSam Clegg unsigned NumFuncImports) { 8669e15f359SSam Clegg uint32_t TotalFunctions = NumFuncImports + Functions.size(); 8679e15f359SSam Clegg if (TotalFunctions == 0) 8689e15f359SSam Clegg return; 8699e15f359SSam Clegg 8709e15f359SSam Clegg SectionBookkeeping Section; 8719e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_CUSTOM, "name"); 8729e15f359SSam Clegg SectionBookkeeping SubSection; 8739e15f359SSam Clegg startSection(SubSection, wasm::WASM_NAMES_FUNCTION); 8749e15f359SSam Clegg 8759e15f359SSam Clegg encodeULEB128(TotalFunctions, getStream()); 8769e15f359SSam Clegg uint32_t Index = 0; 8779e15f359SSam Clegg for (const WasmImport &Import : Imports) { 8789e15f359SSam Clegg if (Import.Kind == wasm::WASM_EXTERNAL_FUNCTION) { 8799e15f359SSam Clegg encodeULEB128(Index, getStream()); 880b7787fd0SSam Clegg writeString(Import.FieldName); 8819e15f359SSam Clegg ++Index; 8829e15f359SSam Clegg } 8839e15f359SSam Clegg } 8849e15f359SSam Clegg for (const WasmFunction &Func : Functions) { 8859e15f359SSam Clegg encodeULEB128(Index, getStream()); 886b7787fd0SSam Clegg writeString(Func.Sym->getName()); 8879e15f359SSam Clegg ++Index; 8889e15f359SSam Clegg } 8899e15f359SSam Clegg 8909e15f359SSam Clegg endSection(SubSection); 8919e15f359SSam Clegg endSection(Section); 8929e15f359SSam Clegg } 8939e15f359SSam Clegg 894acd7d2b0SSam Clegg void WasmObjectWriter::writeCodeRelocSection() { 8959e15f359SSam Clegg // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md 8969e15f359SSam Clegg // for descriptions of the reloc sections. 8979e15f359SSam Clegg 8989e15f359SSam Clegg if (CodeRelocations.empty()) 8999e15f359SSam Clegg return; 9009e15f359SSam Clegg 9019e15f359SSam Clegg SectionBookkeeping Section; 9029e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.CODE"); 9039e15f359SSam Clegg 9049e15f359SSam Clegg encodeULEB128(wasm::WASM_SEC_CODE, getStream()); 905acd7d2b0SSam Clegg encodeULEB128(CodeRelocations.size(), getStream()); 9069e15f359SSam Clegg 9077c395943SSam Clegg writeRelocations(CodeRelocations); 9089e15f359SSam Clegg 9099e15f359SSam Clegg endSection(Section); 9109e15f359SSam Clegg } 9119e15f359SSam Clegg 9127c395943SSam Clegg void WasmObjectWriter::writeDataRelocSection() { 9139e15f359SSam Clegg // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md 9149e15f359SSam Clegg // for descriptions of the reloc sections. 9159e15f359SSam Clegg 9169e15f359SSam Clegg if (DataRelocations.empty()) 9179e15f359SSam Clegg return; 9189e15f359SSam Clegg 9199e15f359SSam Clegg SectionBookkeeping Section; 9209e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.DATA"); 9219e15f359SSam Clegg 9229e15f359SSam Clegg encodeULEB128(wasm::WASM_SEC_DATA, getStream()); 9239e15f359SSam Clegg encodeULEB128(DataRelocations.size(), getStream()); 9249e15f359SSam Clegg 9257c395943SSam Clegg writeRelocations(DataRelocations); 9269e15f359SSam Clegg 9279e15f359SSam Clegg endSection(Section); 9289e15f359SSam Clegg } 9299e15f359SSam Clegg 9309e15f359SSam Clegg void WasmObjectWriter::writeLinkingMetaDataSection( 931d95ed959SSam Clegg ArrayRef<WasmDataSegment> Segments, uint32_t DataSize, 93231a2c809SSam Clegg SmallVector<std::pair<StringRef, uint32_t>, 4> SymbolFlags, 933c2c99771SDan Gohman Optional<uint32_t> StackPointerGlobal) { 9349e15f359SSam Clegg SectionBookkeeping Section; 9359e15f359SSam Clegg startSection(Section, wasm::WASM_SEC_CUSTOM, "linking"); 936b7787fd0SSam Clegg SectionBookkeeping SubSection; 9379e15f359SSam Clegg 938c2c99771SDan Gohman if (StackPointerGlobal.hasValue()) { 939b7787fd0SSam Clegg startSection(SubSection, wasm::WASM_STACK_POINTER); 940c2c99771SDan Gohman encodeULEB128(StackPointerGlobal.getValue(), getStream()); // id 941b7787fd0SSam Clegg endSection(SubSection); 942b7787fd0SSam Clegg } 943b7787fd0SSam Clegg 94431a2c809SSam Clegg if (SymbolFlags.size() != 0) { 945b7787fd0SSam Clegg startSection(SubSection, wasm::WASM_SYMBOL_INFO); 94631a2c809SSam Clegg encodeULEB128(SymbolFlags.size(), getStream()); 94731a2c809SSam Clegg for (auto Pair: SymbolFlags) { 94831a2c809SSam Clegg writeString(Pair.first); 94931a2c809SSam Clegg encodeULEB128(Pair.second, getStream()); 950b7787fd0SSam Clegg } 951b7787fd0SSam Clegg endSection(SubSection); 952b7787fd0SSam Clegg } 9539e15f359SSam Clegg 9549e1ade93SSam Clegg if (DataSize > 0) { 9559e1ade93SSam Clegg startSection(SubSection, wasm::WASM_DATA_SIZE); 9569e1ade93SSam Clegg encodeULEB128(DataSize, getStream()); 9579e1ade93SSam Clegg endSection(SubSection); 9589e1ade93SSam Clegg } 9599e1ade93SSam Clegg 960d95ed959SSam Clegg if (Segments.size()) { 96163ebb813SSam Clegg startSection(SubSection, wasm::WASM_SEGMENT_INFO); 962d95ed959SSam Clegg encodeULEB128(Segments.size(), getStream()); 96363ebb813SSam Clegg for (const WasmDataSegment &Segment : Segments) { 964d95ed959SSam Clegg writeString(Segment.Name); 96563ebb813SSam Clegg encodeULEB128(Segment.Alignment, getStream()); 96663ebb813SSam Clegg encodeULEB128(Segment.Flags, getStream()); 96763ebb813SSam Clegg } 968d95ed959SSam Clegg endSection(SubSection); 969d95ed959SSam Clegg } 970d95ed959SSam Clegg 9719e15f359SSam Clegg endSection(Section); 9729e15f359SSam Clegg } 9739e15f359SSam Clegg 9745e3d33a7SSam Clegg uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm& Symbol) { 9755e3d33a7SSam Clegg assert(Symbol.isFunction()); 9765e3d33a7SSam Clegg assert(TypeIndices.count(&Symbol)); 9775e3d33a7SSam Clegg return TypeIndices[&Symbol]; 9785e3d33a7SSam Clegg } 9795e3d33a7SSam Clegg 9805e3d33a7SSam Clegg uint32_t WasmObjectWriter::registerFunctionType(const MCSymbolWasm& Symbol) { 9815e3d33a7SSam Clegg assert(Symbol.isFunction()); 9825e3d33a7SSam Clegg 9835e3d33a7SSam Clegg WasmFunctionType F; 984aff1c4dfSSam Clegg const MCSymbolWasm* ResolvedSym = ResolveSymbol(Symbol); 9855e3d33a7SSam Clegg F.Returns = ResolvedSym->getReturns(); 9865e3d33a7SSam Clegg F.Params = ResolvedSym->getParams(); 9875e3d33a7SSam Clegg 9885e3d33a7SSam Clegg auto Pair = 9895e3d33a7SSam Clegg FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size())); 9905e3d33a7SSam Clegg if (Pair.second) 9915e3d33a7SSam Clegg FunctionTypes.push_back(F); 9925e3d33a7SSam Clegg TypeIndices[&Symbol] = Pair.first->second; 9935e3d33a7SSam Clegg 9945e3d33a7SSam Clegg DEBUG(dbgs() << "registerFunctionType: " << Symbol << " new:" << Pair.second << "\n"); 9955e3d33a7SSam Clegg DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n"); 9965e3d33a7SSam Clegg return Pair.first->second; 9975e3d33a7SSam Clegg } 9985e3d33a7SSam Clegg 99918eafb6cSDan Gohman void WasmObjectWriter::writeObject(MCAssembler &Asm, 100018eafb6cSDan Gohman const MCAsmLayout &Layout) { 1001b7787fd0SSam Clegg DEBUG(dbgs() << "WasmObjectWriter::writeObject\n"); 100282607f56SDan Gohman MCContext &Ctx = Asm.getContext(); 1003b879539aSDerek Schuff wasm::ValType PtrType = is64Bit() ? wasm::ValType::I64 : wasm::ValType::I32; 1004d934cb88SDan Gohman 1005d934cb88SDan Gohman // Collect information from the available symbols. 1006d934cb88SDan Gohman SmallVector<WasmFunction, 4> Functions; 1007d934cb88SDan Gohman SmallVector<uint32_t, 4> TableElems; 1008d934cb88SDan Gohman SmallVector<WasmImport, 4> Imports; 1009d934cb88SDan Gohman SmallVector<WasmExport, 4> Exports; 101031a2c809SSam Clegg SmallVector<std::pair<StringRef, uint32_t>, 4> SymbolFlags; 1011d934cb88SDan Gohman SmallPtrSet<const MCSymbolWasm *, 4> IsAddressTaken; 1012d934cb88SDan Gohman unsigned NumFuncImports = 0; 10137c395943SSam Clegg SmallVector<WasmDataSegment, 4> DataSegments; 1014c2c99771SDan Gohman Optional<StringRef> StackPointerGlobalName; 1015c2c99771SDan Gohman Optional<uint32_t> StackPointerGlobal; 10167c395943SSam Clegg uint32_t DataSize = 0; 1017d934cb88SDan Gohman 1018d934cb88SDan Gohman // Populate the IsAddressTaken set. 1019b7787fd0SSam Clegg for (const WasmRelocationEntry &RelEntry : CodeRelocations) { 1020d934cb88SDan Gohman switch (RelEntry.Type) { 1021d934cb88SDan Gohman case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB: 102213a2e899SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: 1023d934cb88SDan Gohman IsAddressTaken.insert(RelEntry.Symbol); 1024d934cb88SDan Gohman break; 1025d934cb88SDan Gohman default: 1026d934cb88SDan Gohman break; 1027d934cb88SDan Gohman } 1028d934cb88SDan Gohman } 1029b7787fd0SSam Clegg for (const WasmRelocationEntry &RelEntry : DataRelocations) { 1030d934cb88SDan Gohman switch (RelEntry.Type) { 1031d934cb88SDan Gohman case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: 103213a2e899SSam Clegg case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32: 1033d934cb88SDan Gohman IsAddressTaken.insert(RelEntry.Symbol); 1034d934cb88SDan Gohman break; 1035d934cb88SDan Gohman default: 1036d934cb88SDan Gohman break; 1037d934cb88SDan Gohman } 1038d934cb88SDan Gohman } 1039d934cb88SDan Gohman 104082607f56SDan Gohman // In the special .global_variables section, we've encoded global 104182607f56SDan Gohman // variables used by the function. Translate them into the Globals 104282607f56SDan Gohman // list. 104312fd3da9SSam Clegg MCSectionWasm *GlobalVars = 104412fd3da9SSam Clegg Ctx.getWasmSection(".global_variables", SectionKind::getMetadata()); 104582607f56SDan Gohman if (!GlobalVars->getFragmentList().empty()) { 104682607f56SDan Gohman if (GlobalVars->getFragmentList().size() != 1) 104782607f56SDan Gohman report_fatal_error("only one .global_variables fragment supported"); 104882607f56SDan Gohman const MCFragment &Frag = *GlobalVars->begin(); 104982607f56SDan Gohman if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data) 105082607f56SDan Gohman report_fatal_error("only data supported in .global_variables"); 1051fe6414b0SSam Clegg const auto &DataFrag = cast<MCDataFragment>(Frag); 105282607f56SDan Gohman if (!DataFrag.getFixups().empty()) 105382607f56SDan Gohman report_fatal_error("fixups not supported in .global_variables"); 105482607f56SDan Gohman const SmallVectorImpl<char> &Contents = DataFrag.getContents(); 1055970d02c4SDan Gohman for (const uint8_t *p = (const uint8_t *)Contents.data(), 1056970d02c4SDan Gohman *end = (const uint8_t *)Contents.data() + Contents.size(); 1057970d02c4SDan Gohman p != end; ) { 105882607f56SDan Gohman WasmGlobal G; 1059970d02c4SDan Gohman if (end - p < 3) 1060970d02c4SDan Gohman report_fatal_error("truncated global variable encoding"); 1061970d02c4SDan Gohman G.Type = wasm::ValType(int8_t(*p++)); 1062970d02c4SDan Gohman G.IsMutable = bool(*p++); 1063970d02c4SDan Gohman G.HasImport = bool(*p++); 1064970d02c4SDan Gohman if (G.HasImport) { 106582607f56SDan Gohman G.InitialValue = 0; 1066970d02c4SDan Gohman 1067970d02c4SDan Gohman WasmImport Import; 1068970d02c4SDan Gohman Import.ModuleName = (const char *)p; 1069970d02c4SDan Gohman const uint8_t *nul = (const uint8_t *)memchr(p, '\0', end - p); 1070970d02c4SDan Gohman if (!nul) 1071970d02c4SDan Gohman report_fatal_error("global module name must be nul-terminated"); 1072970d02c4SDan Gohman p = nul + 1; 1073970d02c4SDan Gohman nul = (const uint8_t *)memchr(p, '\0', end - p); 1074970d02c4SDan Gohman if (!nul) 1075970d02c4SDan Gohman report_fatal_error("global base name must be nul-terminated"); 1076970d02c4SDan Gohman Import.FieldName = (const char *)p; 1077970d02c4SDan Gohman p = nul + 1; 1078970d02c4SDan Gohman 1079970d02c4SDan Gohman Import.Kind = wasm::WASM_EXTERNAL_GLOBAL; 1080970d02c4SDan Gohman Import.Type = int32_t(G.Type); 1081970d02c4SDan Gohman 1082970d02c4SDan Gohman G.ImportIndex = NumGlobalImports; 1083970d02c4SDan Gohman ++NumGlobalImports; 1084970d02c4SDan Gohman 1085970d02c4SDan Gohman Imports.push_back(Import); 1086970d02c4SDan Gohman } else { 1087970d02c4SDan Gohman unsigned n; 1088970d02c4SDan Gohman G.InitialValue = decodeSLEB128(p, &n); 1089970d02c4SDan Gohman G.ImportIndex = 0; 1090c8da0c0bSSimon Pilgrim if ((ptrdiff_t)n > end - p) 1091970d02c4SDan Gohman report_fatal_error("global initial value must be valid SLEB128"); 1092970d02c4SDan Gohman p += n; 1093970d02c4SDan Gohman } 109482607f56SDan Gohman Globals.push_back(G); 109582607f56SDan Gohman } 109682607f56SDan Gohman } 109782607f56SDan Gohman 1098970d02c4SDan Gohman // In the special .stack_pointer section, we've encoded the stack pointer 1099970d02c4SDan Gohman // index. 110012fd3da9SSam Clegg MCSectionWasm *StackPtr = 110112fd3da9SSam Clegg Ctx.getWasmSection(".stack_pointer", SectionKind::getMetadata()); 1102970d02c4SDan Gohman if (!StackPtr->getFragmentList().empty()) { 1103970d02c4SDan Gohman if (StackPtr->getFragmentList().size() != 1) 1104970d02c4SDan Gohman report_fatal_error("only one .stack_pointer fragment supported"); 1105970d02c4SDan Gohman const MCFragment &Frag = *StackPtr->begin(); 1106970d02c4SDan Gohman if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data) 1107970d02c4SDan Gohman report_fatal_error("only data supported in .stack_pointer"); 1108fe6414b0SSam Clegg const auto &DataFrag = cast<MCDataFragment>(Frag); 1109970d02c4SDan Gohman if (!DataFrag.getFixups().empty()) 1110970d02c4SDan Gohman report_fatal_error("fixups not supported in .stack_pointer"); 1111970d02c4SDan Gohman const SmallVectorImpl<char> &Contents = DataFrag.getContents(); 1112c2c99771SDan Gohman StackPointerGlobalName = StringRef(Contents.data(), Contents.size()); 1113970d02c4SDan Gohman } 1114970d02c4SDan Gohman 1115*32ce5ca0SDan Gohman // Populate FunctionTypeIndices and Imports. 1116*32ce5ca0SDan Gohman for (const MCSymbol &S : Asm.symbols()) { 1117*32ce5ca0SDan Gohman const auto &WS = static_cast<const MCSymbolWasm &>(S); 1118*32ce5ca0SDan Gohman 1119*32ce5ca0SDan Gohman // Register types for all functions, including those with private linkage 1120*32ce5ca0SDan Gohman // (making them 1121*32ce5ca0SDan Gohman // because wasm always needs a type signature. 1122*32ce5ca0SDan Gohman if (WS.isFunction()) 1123*32ce5ca0SDan Gohman registerFunctionType(WS); 1124*32ce5ca0SDan Gohman 1125*32ce5ca0SDan Gohman if (WS.isTemporary()) 1126*32ce5ca0SDan Gohman continue; 1127*32ce5ca0SDan Gohman 1128*32ce5ca0SDan Gohman // If the symbol is not defined in this translation unit, import it. 1129*32ce5ca0SDan Gohman if (!WS.isDefined(/*SetUsed=*/false)) { 1130*32ce5ca0SDan Gohman WasmImport Import; 1131*32ce5ca0SDan Gohman Import.ModuleName = WS.getModuleName(); 1132*32ce5ca0SDan Gohman Import.FieldName = WS.getName(); 1133*32ce5ca0SDan Gohman 1134*32ce5ca0SDan Gohman if (WS.isFunction()) { 1135*32ce5ca0SDan Gohman Import.Kind = wasm::WASM_EXTERNAL_FUNCTION; 1136*32ce5ca0SDan Gohman Import.Type = getFunctionType(WS); 1137*32ce5ca0SDan Gohman SymbolIndices[&WS] = NumFuncImports; 1138*32ce5ca0SDan Gohman ++NumFuncImports; 1139*32ce5ca0SDan Gohman } else { 1140*32ce5ca0SDan Gohman Import.Kind = wasm::WASM_EXTERNAL_GLOBAL; 1141*32ce5ca0SDan Gohman Import.Type = int32_t(PtrType); 1142*32ce5ca0SDan Gohman Import.IsMutable = false; 1143*32ce5ca0SDan Gohman SymbolIndices[&WS] = NumGlobalImports; 1144*32ce5ca0SDan Gohman 1145*32ce5ca0SDan Gohman // If this global is the stack pointer, make it mutable and remember it 1146*32ce5ca0SDan Gohman // so that we can emit metadata for it. 1147*32ce5ca0SDan Gohman if (StackPointerGlobalName.hasValue() && 1148*32ce5ca0SDan Gohman WS.getName() == StackPointerGlobalName.getValue()) { 1149*32ce5ca0SDan Gohman Import.IsMutable = true; 1150*32ce5ca0SDan Gohman StackPointerGlobal = NumGlobalImports; 1151*32ce5ca0SDan Gohman } 1152*32ce5ca0SDan Gohman 1153*32ce5ca0SDan Gohman ++NumGlobalImports; 1154*32ce5ca0SDan Gohman } 1155*32ce5ca0SDan Gohman 1156*32ce5ca0SDan Gohman Imports.push_back(Import); 1157*32ce5ca0SDan Gohman } 1158*32ce5ca0SDan Gohman } 1159*32ce5ca0SDan Gohman 1160759631c7SSam Clegg for (MCSection &Sec : Asm) { 1161759631c7SSam Clegg auto &Section = static_cast<MCSectionWasm &>(Sec); 116212fd3da9SSam Clegg if (!Section.isWasmData()) 1163759631c7SSam Clegg continue; 1164759631c7SSam Clegg 1165759631c7SSam Clegg DataSize = alignTo(DataSize, Section.getAlignment()); 1166759631c7SSam Clegg DataSegments.emplace_back(); 1167759631c7SSam Clegg WasmDataSegment &Segment = DataSegments.back(); 1168d95ed959SSam Clegg Segment.Name = Section.getSectionName(); 1169759631c7SSam Clegg Segment.Offset = DataSize; 1170759631c7SSam Clegg Segment.Section = &Section; 117163ebb813SSam Clegg addData(Segment.Data, Section); 117263ebb813SSam Clegg Segment.Alignment = Section.getAlignment(); 117363ebb813SSam Clegg Segment.Flags = 0; 1174759631c7SSam Clegg DataSize += Segment.Data.size(); 1175759631c7SSam Clegg Section.setMemoryOffset(Segment.Offset); 1176759631c7SSam Clegg } 1177759631c7SSam Clegg 1178b7787fd0SSam Clegg // Handle regular defined and undefined symbols. 1179d934cb88SDan Gohman for (const MCSymbol &S : Asm.symbols()) { 1180d934cb88SDan Gohman // Ignore unnamed temporary symbols, which aren't ever exported, imported, 1181d934cb88SDan Gohman // or used in relocations. 1182d934cb88SDan Gohman if (S.isTemporary() && S.getName().empty()) 1183d934cb88SDan Gohman continue; 1184b7787fd0SSam Clegg 1185d934cb88SDan Gohman const auto &WS = static_cast<const MCSymbolWasm &>(S); 1186b7787fd0SSam Clegg DEBUG(dbgs() << "MCSymbol: '" << S << "'" 1187b7787fd0SSam Clegg << " isDefined=" << S.isDefined() << " isExternal=" 1188b7787fd0SSam Clegg << S.isExternal() << " isTemporary=" << S.isTemporary() 1189b7787fd0SSam Clegg << " isFunction=" << WS.isFunction() 1190b7787fd0SSam Clegg << " isWeak=" << WS.isWeak() 1191a2b35dacSSam Clegg << " isHidden=" << WS.isHidden() 1192b7787fd0SSam Clegg << " isVariable=" << WS.isVariable() << "\n"); 1193b7787fd0SSam Clegg 1194a2b35dacSSam Clegg if (WS.isWeak() || WS.isHidden()) { 1195a2b35dacSSam Clegg uint32_t Flags = (WS.isWeak() ? wasm::WASM_SYMBOL_BINDING_WEAK : 0) | 1196a2b35dacSSam Clegg (WS.isHidden() ? wasm::WASM_SYMBOL_VISIBILITY_HIDDEN : 0); 1197a2b35dacSSam Clegg SymbolFlags.emplace_back(WS.getName(), Flags); 1198a2b35dacSSam Clegg } 1199b7787fd0SSam Clegg 12005e3d33a7SSam Clegg if (WS.isVariable()) 12015e3d33a7SSam Clegg continue; 12025e3d33a7SSam Clegg 1203d934cb88SDan Gohman unsigned Index; 1204b7787fd0SSam Clegg 1205d934cb88SDan Gohman if (WS.isFunction()) { 1206d934cb88SDan Gohman if (WS.isDefined(/*SetUsed=*/false)) { 1207b7787fd0SSam Clegg if (WS.getOffset() != 0) 1208b7787fd0SSam Clegg report_fatal_error( 1209b7787fd0SSam Clegg "function sections must contain one function each"); 1210b7787fd0SSam Clegg 1211b7787fd0SSam Clegg if (WS.getSize() == 0) 1212b7787fd0SSam Clegg report_fatal_error( 1213b7787fd0SSam Clegg "function symbols must have a size set with .size"); 1214b7787fd0SSam Clegg 1215d934cb88SDan Gohman // A definition. Take the next available index. 1216d934cb88SDan Gohman Index = NumFuncImports + Functions.size(); 1217d934cb88SDan Gohman 1218d934cb88SDan Gohman // Prepare the function. 1219d934cb88SDan Gohman WasmFunction Func; 12205e3d33a7SSam Clegg Func.Type = getFunctionType(WS); 1221d934cb88SDan Gohman Func.Sym = &WS; 1222d934cb88SDan Gohman SymbolIndices[&WS] = Index; 1223d934cb88SDan Gohman Functions.push_back(Func); 1224d934cb88SDan Gohman } else { 1225d934cb88SDan Gohman // An import; the index was assigned above. 1226d934cb88SDan Gohman Index = SymbolIndices.find(&WS)->second; 1227d934cb88SDan Gohman } 1228d934cb88SDan Gohman 12295e3d33a7SSam Clegg DEBUG(dbgs() << " -> function index: " << Index << "\n"); 12305e3d33a7SSam Clegg 1231d934cb88SDan Gohman // If needed, prepare the function to be called indirectly. 12325e3d33a7SSam Clegg if (IsAddressTaken.count(&WS) != 0) { 1233d99f6078SSam Clegg IndirectSymbolIndices[&WS] = TableElems.size(); 12345e3d33a7SSam Clegg DEBUG(dbgs() << " -> adding to table: " << TableElems.size() << "\n"); 1235d934cb88SDan Gohman TableElems.push_back(Index); 1236d99f6078SSam Clegg } 1237d934cb88SDan Gohman } else { 1238c38e947eSSam Clegg if (WS.isTemporary() && !WS.getSize()) 1239c38e947eSSam Clegg continue; 1240c38e947eSSam Clegg 1241fe6414b0SSam Clegg if (!WS.isDefined(/*SetUsed=*/false)) 1242fe6414b0SSam Clegg continue; 1243fe6414b0SSam Clegg 1244d934cb88SDan Gohman if (!WS.getSize()) 1245c38e947eSSam Clegg report_fatal_error("data symbols must have a size set with .size: " + 1246c38e947eSSam Clegg WS.getName()); 1247d934cb88SDan Gohman 1248d934cb88SDan Gohman int64_t Size = 0; 1249d934cb88SDan Gohman if (!WS.getSize()->evaluateAsAbsolute(Size, Layout)) 1250d934cb88SDan Gohman report_fatal_error(".size expression must be evaluatable"); 1251d934cb88SDan Gohman 12527c395943SSam Clegg // For each global, prepare a corresponding wasm global holding its 12537c395943SSam Clegg // address. For externals these will also be named exports. 12547c395943SSam Clegg Index = NumGlobalImports + Globals.size(); 1255759631c7SSam Clegg auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection()); 12567c395943SSam Clegg 12577c395943SSam Clegg WasmGlobal Global; 12587c395943SSam Clegg Global.Type = PtrType; 12597c395943SSam Clegg Global.IsMutable = false; 12607c395943SSam Clegg Global.HasImport = false; 1261759631c7SSam Clegg Global.InitialValue = DataSection.getMemoryOffset() + Layout.getSymbolOffset(WS); 12627c395943SSam Clegg Global.ImportIndex = 0; 12637c395943SSam Clegg SymbolIndices[&WS] = Index; 12647c395943SSam Clegg DEBUG(dbgs() << " -> global index: " << Index << "\n"); 12657c395943SSam Clegg Globals.push_back(Global); 1266d934cb88SDan Gohman } 1267d934cb88SDan Gohman 1268d934cb88SDan Gohman // If the symbol is visible outside this translation unit, export it. 126931a2c809SSam Clegg if (WS.isDefined(/*SetUsed=*/false)) { 1270d934cb88SDan Gohman WasmExport Export; 1271d934cb88SDan Gohman Export.FieldName = WS.getName(); 1272d934cb88SDan Gohman Export.Index = Index; 1273d934cb88SDan Gohman if (WS.isFunction()) 1274d934cb88SDan Gohman Export.Kind = wasm::WASM_EXTERNAL_FUNCTION; 1275d934cb88SDan Gohman else 1276d934cb88SDan Gohman Export.Kind = wasm::WASM_EXTERNAL_GLOBAL; 12775e3d33a7SSam Clegg DEBUG(dbgs() << " -> export " << Exports.size() << "\n"); 1278d934cb88SDan Gohman Exports.push_back(Export); 127931a2c809SSam Clegg if (!WS.isExternal()) 128031a2c809SSam Clegg SymbolFlags.emplace_back(WS.getName(), wasm::WASM_SYMBOL_BINDING_LOCAL); 1281d934cb88SDan Gohman } 1282d934cb88SDan Gohman } 1283d934cb88SDan Gohman 12845e3d33a7SSam Clegg // Handle weak aliases. We need to process these in a separate pass because 12855e3d33a7SSam Clegg // we need to have processed the target of the alias before the alias itself 12865e3d33a7SSam Clegg // and the symbols are not necessarily ordered in this way. 1287b7787fd0SSam Clegg for (const MCSymbol &S : Asm.symbols()) { 1288b7787fd0SSam Clegg if (!S.isVariable()) 1289b7787fd0SSam Clegg continue; 129031a2c809SSam Clegg 1291b7787fd0SSam Clegg assert(S.isDefined(/*SetUsed=*/false)); 1292b7787fd0SSam Clegg 12935e3d33a7SSam Clegg // Find the target symbol of this weak alias and export that index 1294aff1c4dfSSam Clegg const auto &WS = static_cast<const MCSymbolWasm &>(S); 1295aff1c4dfSSam Clegg const MCSymbolWasm *ResolvedSym = ResolveSymbol(WS); 12965e3d33a7SSam Clegg DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym << "'\n"); 12975e3d33a7SSam Clegg assert(SymbolIndices.count(ResolvedSym) > 0); 1298b7787fd0SSam Clegg uint32_t Index = SymbolIndices.find(ResolvedSym)->second; 12995e3d33a7SSam Clegg DEBUG(dbgs() << " -> index:" << Index << "\n"); 1300b7787fd0SSam Clegg 1301ba9fa9fdSSam Clegg SymbolIndices[&WS] = Index; 1302b7787fd0SSam Clegg WasmExport Export; 1303b7787fd0SSam Clegg Export.FieldName = WS.getName(); 1304b7787fd0SSam Clegg Export.Index = Index; 1305b7787fd0SSam Clegg if (WS.isFunction()) 1306b7787fd0SSam Clegg Export.Kind = wasm::WASM_EXTERNAL_FUNCTION; 1307b7787fd0SSam Clegg else 1308b7787fd0SSam Clegg Export.Kind = wasm::WASM_EXTERNAL_GLOBAL; 13095e3d33a7SSam Clegg DEBUG(dbgs() << " -> export " << Exports.size() << "\n"); 1310b7787fd0SSam Clegg Exports.push_back(Export); 131131a2c809SSam Clegg 131231a2c809SSam Clegg if (!WS.isExternal()) 131331a2c809SSam Clegg SymbolFlags.emplace_back(WS.getName(), wasm::WASM_SYMBOL_BINDING_LOCAL); 1314b7787fd0SSam Clegg } 1315b7787fd0SSam Clegg 1316d934cb88SDan Gohman // Add types for indirect function calls. 1317acd7d2b0SSam Clegg for (const WasmRelocationEntry &Fixup : CodeRelocations) { 1318acd7d2b0SSam Clegg if (Fixup.Type != wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB) 1319acd7d2b0SSam Clegg continue; 1320970d02c4SDan Gohman 13215e3d33a7SSam Clegg registerFunctionType(*Fixup.Symbol); 1322d934cb88SDan Gohman } 1323d934cb88SDan Gohman 132418eafb6cSDan Gohman // Write out the Wasm header. 132518eafb6cSDan Gohman writeHeader(Asm); 132618eafb6cSDan Gohman 13279e15f359SSam Clegg writeTypeSection(FunctionTypes); 13289e15f359SSam Clegg writeImportSection(Imports); 13299e15f359SSam Clegg writeFunctionSection(Functions); 1330d99f6078SSam Clegg writeTableSection(TableElems.size()); 13317c395943SSam Clegg writeMemorySection(DataSize); 13327c395943SSam Clegg writeGlobalSection(); 13339e15f359SSam Clegg writeExportSection(Exports); 13349e15f359SSam Clegg // TODO: Start Section 13359e15f359SSam Clegg writeElemSection(TableElems); 1336acd7d2b0SSam Clegg writeCodeSection(Asm, Layout, Functions); 13377c395943SSam Clegg writeDataSection(DataSegments); 13389e15f359SSam Clegg writeNameSection(Functions, Imports, NumFuncImports); 1339acd7d2b0SSam Clegg writeCodeRelocSection(); 13407c395943SSam Clegg writeDataRelocSection(); 134163ebb813SSam Clegg writeLinkingMetaDataSection(DataSegments, DataSize, SymbolFlags, 1342c2c99771SDan Gohman StackPointerGlobal); 1343970d02c4SDan Gohman 1344d934cb88SDan Gohman // TODO: Translate the .comment section to the output. 1345d934cb88SDan Gohman // TODO: Translate debug sections to the output. 134618eafb6cSDan Gohman } 134718eafb6cSDan Gohman 134860fbc7ccSLang Hames std::unique_ptr<MCObjectWriter> 13491301a878SLang Hames llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW, 135018eafb6cSDan Gohman raw_pwrite_stream &OS) { 135160fbc7ccSLang Hames // FIXME: Can't use make_unique<WasmObjectWriter>(...) as WasmObjectWriter's 135260fbc7ccSLang Hames // destructor is private. Is that necessary? 135360fbc7ccSLang Hames return std::unique_ptr<MCObjectWriter>( 135460fbc7ccSLang Hames new WasmObjectWriter(std::move(MOTW), OS)); 135518eafb6cSDan Gohman } 1356