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" 1618eafb6cSDan Gohman #include "llvm/MC/MCAsmBackend.h" 1718eafb6cSDan Gohman #include "llvm/MC/MCAsmInfo.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/MCObjectFileInfo.h" 2418eafb6cSDan Gohman #include "llvm/MC/MCObjectWriter.h" 2518eafb6cSDan Gohman #include "llvm/MC/MCSectionWasm.h" 2618eafb6cSDan Gohman #include "llvm/MC/MCSymbolWasm.h" 2718eafb6cSDan Gohman #include "llvm/MC/MCValue.h" 2818eafb6cSDan Gohman #include "llvm/MC/MCWasmObjectWriter.h" 29d934cb88SDan Gohman #include "llvm/Support/Casting.h" 3018eafb6cSDan Gohman #include "llvm/Support/Debug.h" 3118eafb6cSDan Gohman #include "llvm/Support/ErrorHandling.h" 32d934cb88SDan Gohman #include "llvm/Support/LEB128.h" 3318eafb6cSDan Gohman #include "llvm/Support/StringSaver.h" 347ea5adffSDan Gohman #include "llvm/Support/Wasm.h" 3518eafb6cSDan Gohman #include <vector> 3618eafb6cSDan Gohman 3718eafb6cSDan Gohman using namespace llvm; 3818eafb6cSDan Gohman 3918eafb6cSDan Gohman #undef DEBUG_TYPE 4018eafb6cSDan Gohman #define DEBUG_TYPE "reloc-info" 4118eafb6cSDan Gohman 4218eafb6cSDan Gohman namespace { 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 53d934cb88SDan Gohman // This record records information about a call_indirect which needs its 54d934cb88SDan Gohman // type index fixed up once we've computed type indices. 55d934cb88SDan Gohman struct TypeIndexFixup { 56d934cb88SDan Gohman uint64_t Offset; 57d934cb88SDan Gohman const MCSymbolWasm *Symbol; 58d934cb88SDan Gohman const MCSectionWasm *FixupSection; 59d934cb88SDan Gohman TypeIndexFixup(uint64_t O, const MCSymbolWasm *S, MCSectionWasm *F) 60d934cb88SDan Gohman : Offset(O), Symbol(S), FixupSection(F) {} 61d934cb88SDan Gohman }; 6218eafb6cSDan Gohman 6318eafb6cSDan Gohman class WasmObjectWriter : public MCObjectWriter { 6418eafb6cSDan Gohman /// Helper struct for containing some precomputed information on symbols. 6518eafb6cSDan Gohman struct WasmSymbolData { 6618eafb6cSDan Gohman const MCSymbolWasm *Symbol; 6718eafb6cSDan Gohman StringRef Name; 6818eafb6cSDan Gohman 6918eafb6cSDan Gohman // Support lexicographic sorting. 7018eafb6cSDan Gohman bool operator<(const WasmSymbolData &RHS) const { return Name < RHS.Name; } 7118eafb6cSDan Gohman }; 7218eafb6cSDan Gohman 7318eafb6cSDan Gohman /// The target specific Wasm writer instance. 7418eafb6cSDan Gohman std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter; 7518eafb6cSDan Gohman 76d934cb88SDan Gohman // Relocations for fixing up references in the code section. 77d934cb88SDan Gohman std::vector<WasmRelocationEntry> CodeRelocations; 78d934cb88SDan Gohman 79d934cb88SDan Gohman // Relocations for fixing up references in the data section. 80d934cb88SDan Gohman std::vector<WasmRelocationEntry> DataRelocations; 81d934cb88SDan Gohman 82d934cb88SDan Gohman // Fixups for call_indirect type indices. 83d934cb88SDan Gohman std::vector<TypeIndexFixup> TypeIndexFixups; 84d934cb88SDan Gohman 85d934cb88SDan Gohman // Index values to use for fixing up call_indirect type indices. 86d934cb88SDan Gohman std::vector<uint32_t> TypeIndexFixupTypes; 87d934cb88SDan Gohman 8818eafb6cSDan Gohman // TargetObjectWriter wrappers. 8918eafb6cSDan Gohman bool is64Bit() const { return TargetObjectWriter->is64Bit(); } 9018eafb6cSDan Gohman unsigned getRelocType(MCContext &Ctx, const MCValue &Target, 9118eafb6cSDan Gohman const MCFixup &Fixup, bool IsPCRel) const { 9218eafb6cSDan Gohman return TargetObjectWriter->getRelocType(Ctx, Target, Fixup, IsPCRel); 9318eafb6cSDan Gohman } 9418eafb6cSDan Gohman 95d934cb88SDan Gohman void startSection(SectionBookkeeping &Section, unsigned SectionId, 96d934cb88SDan Gohman const char *Name = nullptr); 97d934cb88SDan Gohman void endSection(SectionBookkeeping &Section); 98d934cb88SDan Gohman 9918eafb6cSDan Gohman public: 10018eafb6cSDan Gohman WasmObjectWriter(MCWasmObjectTargetWriter *MOTW, raw_pwrite_stream &OS) 10118eafb6cSDan Gohman : MCObjectWriter(OS, /*IsLittleEndian=*/true), TargetObjectWriter(MOTW) {} 10218eafb6cSDan Gohman 103d934cb88SDan Gohman private: 10418eafb6cSDan Gohman void reset() override { 10518eafb6cSDan Gohman MCObjectWriter::reset(); 10618eafb6cSDan Gohman } 10718eafb6cSDan Gohman 10818eafb6cSDan Gohman ~WasmObjectWriter() override; 10918eafb6cSDan Gohman 11018eafb6cSDan Gohman void writeHeader(const MCAssembler &Asm); 11118eafb6cSDan Gohman 11218eafb6cSDan Gohman void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout, 11318eafb6cSDan Gohman const MCFragment *Fragment, const MCFixup &Fixup, 11418eafb6cSDan Gohman MCValue Target, bool &IsPCRel, 11518eafb6cSDan Gohman uint64_t &FixedValue) override; 11618eafb6cSDan Gohman 11718eafb6cSDan Gohman void executePostLayoutBinding(MCAssembler &Asm, 11818eafb6cSDan Gohman const MCAsmLayout &Layout) override; 11918eafb6cSDan Gohman 12018eafb6cSDan Gohman void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override; 12118eafb6cSDan Gohman }; 12218eafb6cSDan Gohman } // end anonymous namespace 12318eafb6cSDan Gohman 12418eafb6cSDan Gohman WasmObjectWriter::~WasmObjectWriter() {} 12518eafb6cSDan Gohman 126d934cb88SDan Gohman // Return the padding size to write a 32-bit value into a 5-byte ULEB128. 127d934cb88SDan Gohman static unsigned PaddingFor5ByteULEB128(uint32_t X) { 128d934cb88SDan Gohman return X == 0 ? 4 : (4u - (31u - countLeadingZeros(X)) / 7u); 129d934cb88SDan Gohman } 130d934cb88SDan Gohman 131d934cb88SDan Gohman // Return the padding size to write a 32-bit value into a 5-byte SLEB128. 132d934cb88SDan Gohman static unsigned PaddingFor5ByteSLEB128(int32_t X) { 133d934cb88SDan Gohman return 5 - getSLEB128Size(X); 134d934cb88SDan Gohman } 135d934cb88SDan Gohman 136d934cb88SDan Gohman // Write out a section header and a patchable section size field. 137d934cb88SDan Gohman void WasmObjectWriter::startSection(SectionBookkeeping &Section, 138d934cb88SDan Gohman unsigned SectionId, 139d934cb88SDan Gohman const char *Name) { 140d934cb88SDan Gohman assert((Name != nullptr) == (SectionId == wasm::WASM_SEC_CUSTOM) && 141d934cb88SDan Gohman "Only custom sections can have names"); 142d934cb88SDan Gohman 143d934cb88SDan Gohman write8(SectionId); 144d934cb88SDan Gohman 145d934cb88SDan Gohman Section.SizeOffset = getStream().tell(); 146d934cb88SDan Gohman 147d934cb88SDan Gohman // The section size. We don't know the size yet, so reserve enough space 148d934cb88SDan Gohman // for any 32-bit value; we'll patch it later. 149d934cb88SDan Gohman encodeULEB128(UINT32_MAX, getStream()); 150d934cb88SDan Gohman 151d934cb88SDan Gohman // The position where the section starts, for measuring its size. 152d934cb88SDan Gohman Section.ContentsOffset = getStream().tell(); 153d934cb88SDan Gohman 154d934cb88SDan Gohman // Custom sections in wasm also have a string identifier. 155d934cb88SDan Gohman if (SectionId == wasm::WASM_SEC_CUSTOM) { 156d934cb88SDan Gohman encodeULEB128(strlen(Name), getStream()); 157d934cb88SDan Gohman writeBytes(Name); 158d934cb88SDan Gohman } 159d934cb88SDan Gohman } 160d934cb88SDan Gohman 161d934cb88SDan Gohman // Now that the section is complete and we know how big it is, patch up the 162d934cb88SDan Gohman // section size field at the start of the section. 163d934cb88SDan Gohman void WasmObjectWriter::endSection(SectionBookkeeping &Section) { 164d934cb88SDan Gohman uint64_t Size = getStream().tell() - Section.ContentsOffset; 165d934cb88SDan Gohman if (uint32_t(Size) != Size) 166d934cb88SDan Gohman report_fatal_error("section size does not fit in a uint32_t"); 167d934cb88SDan Gohman 168d934cb88SDan Gohman unsigned Padding = PaddingFor5ByteULEB128(Size); 169d934cb88SDan Gohman 170d934cb88SDan Gohman // Write the final section size to the payload_len field, which follows 171d934cb88SDan Gohman // the section id byte. 172d934cb88SDan Gohman uint8_t Buffer[16]; 173d934cb88SDan Gohman unsigned SizeLen = encodeULEB128(Size, Buffer, Padding); 174d934cb88SDan Gohman assert(SizeLen == 5); 175d934cb88SDan Gohman getStream().pwrite((char *)Buffer, SizeLen, Section.SizeOffset); 176d934cb88SDan Gohman } 177d934cb88SDan Gohman 17818eafb6cSDan Gohman // Emit the Wasm header. 17918eafb6cSDan Gohman void WasmObjectWriter::writeHeader(const MCAssembler &Asm) { 1807ea5adffSDan Gohman writeBytes(StringRef(wasm::WasmMagic, sizeof(wasm::WasmMagic))); 1817ea5adffSDan Gohman writeLE32(wasm::WasmVersion); 18218eafb6cSDan Gohman } 18318eafb6cSDan Gohman 18418eafb6cSDan Gohman void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm, 18518eafb6cSDan Gohman const MCAsmLayout &Layout) { 18618eafb6cSDan Gohman } 18718eafb6cSDan Gohman 18818eafb6cSDan Gohman void WasmObjectWriter::recordRelocation(MCAssembler &Asm, 18918eafb6cSDan Gohman const MCAsmLayout &Layout, 19018eafb6cSDan Gohman const MCFragment *Fragment, 19118eafb6cSDan Gohman const MCFixup &Fixup, MCValue Target, 19218eafb6cSDan Gohman bool &IsPCRel, uint64_t &FixedValue) { 193d934cb88SDan Gohman MCSectionWasm &FixupSection = cast<MCSectionWasm>(*Fragment->getParent()); 194d934cb88SDan Gohman uint64_t C = Target.getConstant(); 195d934cb88SDan Gohman uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset(); 196d934cb88SDan Gohman MCContext &Ctx = Asm.getContext(); 197d934cb88SDan Gohman 198d934cb88SDan Gohman if (const MCSymbolRefExpr *RefB = Target.getSymB()) { 199d934cb88SDan Gohman assert(RefB->getKind() == MCSymbolRefExpr::VK_None && 200d934cb88SDan Gohman "Should not have constructed this"); 201d934cb88SDan Gohman 202d934cb88SDan Gohman // Let A, B and C being the components of Target and R be the location of 203d934cb88SDan Gohman // the fixup. If the fixup is not pcrel, we want to compute (A - B + C). 204d934cb88SDan Gohman // If it is pcrel, we want to compute (A - B + C - R). 205d934cb88SDan Gohman 206d934cb88SDan Gohman // In general, Wasm has no relocations for -B. It can only represent (A + C) 207d934cb88SDan Gohman // or (A + C - R). If B = R + K and the relocation is not pcrel, we can 208d934cb88SDan Gohman // replace B to implement it: (A - R - K + C) 209d934cb88SDan Gohman if (IsPCRel) { 210d934cb88SDan Gohman Ctx.reportError( 211d934cb88SDan Gohman Fixup.getLoc(), 212d934cb88SDan Gohman "No relocation available to represent this relative expression"); 213d934cb88SDan Gohman return; 214d934cb88SDan Gohman } 215d934cb88SDan Gohman 216d934cb88SDan Gohman const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol()); 217d934cb88SDan Gohman 218d934cb88SDan Gohman if (SymB.isUndefined()) { 219d934cb88SDan Gohman Ctx.reportError(Fixup.getLoc(), 220d934cb88SDan Gohman Twine("symbol '") + SymB.getName() + 221d934cb88SDan Gohman "' can not be undefined in a subtraction expression"); 222d934cb88SDan Gohman return; 223d934cb88SDan Gohman } 224d934cb88SDan Gohman 225d934cb88SDan Gohman assert(!SymB.isAbsolute() && "Should have been folded"); 226d934cb88SDan Gohman const MCSection &SecB = SymB.getSection(); 227d934cb88SDan Gohman if (&SecB != &FixupSection) { 228d934cb88SDan Gohman Ctx.reportError(Fixup.getLoc(), 229d934cb88SDan Gohman "Cannot represent a difference across sections"); 230d934cb88SDan Gohman return; 231d934cb88SDan Gohman } 232d934cb88SDan Gohman 233d934cb88SDan Gohman uint64_t SymBOffset = Layout.getSymbolOffset(SymB); 234d934cb88SDan Gohman uint64_t K = SymBOffset - FixupOffset; 235d934cb88SDan Gohman IsPCRel = true; 236d934cb88SDan Gohman C -= K; 237d934cb88SDan Gohman } 238d934cb88SDan Gohman 239d934cb88SDan Gohman // We either rejected the fixup or folded B into C at this point. 240d934cb88SDan Gohman const MCSymbolRefExpr *RefA = Target.getSymA(); 241d934cb88SDan Gohman const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr; 242d934cb88SDan Gohman 243d934cb88SDan Gohman bool ViaWeakRef = false; 244d934cb88SDan Gohman if (SymA && SymA->isVariable()) { 245d934cb88SDan Gohman const MCExpr *Expr = SymA->getVariableValue(); 246d934cb88SDan Gohman if (const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr)) { 247d934cb88SDan Gohman if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF) { 248d934cb88SDan Gohman SymA = cast<MCSymbolWasm>(&Inner->getSymbol()); 249d934cb88SDan Gohman ViaWeakRef = true; 250d934cb88SDan Gohman } 251d934cb88SDan Gohman } 252d934cb88SDan Gohman } 253d934cb88SDan Gohman 254d934cb88SDan Gohman // Put any constant offset in an addend. Offsets can be negative, and 255d934cb88SDan Gohman // LLVM expects wrapping, in contrast to wasm's immediates which can't 256d934cb88SDan Gohman // be negative and don't wrap. 257d934cb88SDan Gohman FixedValue = 0; 258d934cb88SDan Gohman 259d934cb88SDan Gohman if (SymA) { 260d934cb88SDan Gohman if (ViaWeakRef) 261d934cb88SDan Gohman llvm_unreachable("weakref used in reloc not yet implemented"); 262d934cb88SDan Gohman else 263d934cb88SDan Gohman SymA->setUsedInReloc(); 264d934cb88SDan Gohman } 265d934cb88SDan Gohman 266d934cb88SDan Gohman if (RefA) { 267d934cb88SDan Gohman if (RefA->getKind() == MCSymbolRefExpr::VK_WebAssembly_TYPEINDEX) { 268d934cb88SDan Gohman TypeIndexFixups.push_back(TypeIndexFixup(FixupOffset, SymA, 269d934cb88SDan Gohman &FixupSection)); 270d934cb88SDan Gohman return; 271d934cb88SDan Gohman } 272d934cb88SDan Gohman } 273d934cb88SDan Gohman 274d934cb88SDan Gohman unsigned Type = getRelocType(Ctx, Target, Fixup, IsPCRel); 275d934cb88SDan Gohman 276d934cb88SDan Gohman WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection); 277d934cb88SDan Gohman 278d934cb88SDan Gohman if (FixupSection.hasInstructions()) 279d934cb88SDan Gohman CodeRelocations.push_back(Rec); 280d934cb88SDan Gohman else 281d934cb88SDan Gohman DataRelocations.push_back(Rec); 282d934cb88SDan Gohman } 283d934cb88SDan Gohman 284d934cb88SDan Gohman namespace { 285d934cb88SDan Gohman 286d934cb88SDan Gohman // 287d934cb88SDan Gohman struct WasmFunctionType { 288d934cb88SDan Gohman // Support empty and tombstone instances, needed by DenseMap. 289d934cb88SDan Gohman enum { Plain, Empty, Tombstone } State; 290d934cb88SDan Gohman 291d934cb88SDan Gohman // The return types of the function. 292d934cb88SDan Gohman SmallVector<unsigned, 1> Returns; 293d934cb88SDan Gohman 294d934cb88SDan Gohman // The parameter types of the function. 295d934cb88SDan Gohman SmallVector<unsigned, 4> Params; 296d934cb88SDan Gohman 297d934cb88SDan Gohman WasmFunctionType() : State(Plain) {} 298d934cb88SDan Gohman 299d934cb88SDan Gohman bool operator==(const WasmFunctionType &Other) const { 300d934cb88SDan Gohman return State == Other.State && Returns == Other.Returns && 301d934cb88SDan Gohman Params == Other.Params; 302d934cb88SDan Gohman } 303d934cb88SDan Gohman }; 304d934cb88SDan Gohman 305d934cb88SDan Gohman // Traits for using WasmFunctionType in a DenseMap. 306d934cb88SDan Gohman struct WasmFunctionTypeDenseMapInfo { 307d934cb88SDan Gohman static WasmFunctionType getEmptyKey() { 308d934cb88SDan Gohman WasmFunctionType FuncTy; 309d934cb88SDan Gohman FuncTy.State = WasmFunctionType::Empty; 310d934cb88SDan Gohman return FuncTy; 311d934cb88SDan Gohman } 312d934cb88SDan Gohman static WasmFunctionType getTombstoneKey() { 313d934cb88SDan Gohman WasmFunctionType FuncTy; 314d934cb88SDan Gohman FuncTy.State = WasmFunctionType::Tombstone; 315d934cb88SDan Gohman return FuncTy; 316d934cb88SDan Gohman } 317d934cb88SDan Gohman static unsigned getHashValue(const WasmFunctionType &FuncTy) { 318d934cb88SDan Gohman uintptr_t Value = FuncTy.State; 319d934cb88SDan Gohman for (unsigned Ret : FuncTy.Returns) 320d934cb88SDan Gohman Value += DenseMapInfo<unsigned>::getHashValue(Ret); 321d934cb88SDan Gohman for (unsigned Param : FuncTy.Params) 322d934cb88SDan Gohman Value += DenseMapInfo<unsigned>::getHashValue(Param); 323d934cb88SDan Gohman return Value; 324d934cb88SDan Gohman } 325d934cb88SDan Gohman static bool isEqual(const WasmFunctionType &LHS, 326d934cb88SDan Gohman const WasmFunctionType &RHS) { 327d934cb88SDan Gohman return LHS == RHS; 328d934cb88SDan Gohman } 329d934cb88SDan Gohman }; 330d934cb88SDan Gohman 331d934cb88SDan Gohman // A wasm import to be written into the import section. 332d934cb88SDan Gohman struct WasmImport { 333d934cb88SDan Gohman StringRef ModuleName; 334d934cb88SDan Gohman StringRef FieldName; 335d934cb88SDan Gohman unsigned Kind; 336d934cb88SDan Gohman uint32_t Type; 337d934cb88SDan Gohman }; 338d934cb88SDan Gohman 339d934cb88SDan Gohman // A wasm function to be written into the function section. 340d934cb88SDan Gohman struct WasmFunction { 341d934cb88SDan Gohman unsigned Type; 342d934cb88SDan Gohman const MCSymbolWasm *Sym; 343d934cb88SDan Gohman }; 344d934cb88SDan Gohman 345d934cb88SDan Gohman // A wasm export to be written into the export section. 346d934cb88SDan Gohman struct WasmExport { 347d934cb88SDan Gohman StringRef FieldName; 348d934cb88SDan Gohman unsigned Kind; 349d934cb88SDan Gohman uint32_t Index; 350d934cb88SDan Gohman }; 351d934cb88SDan Gohman 352d934cb88SDan Gohman // A wasm global to be written into the global section. 353d934cb88SDan Gohman struct WasmGlobal { 354d934cb88SDan Gohman unsigned Type; 355d934cb88SDan Gohman bool IsMutable; 356d934cb88SDan Gohman uint32_t InitialValue; 357d934cb88SDan Gohman }; 358d934cb88SDan Gohman 359d934cb88SDan Gohman } // end anonymous namespace 360d934cb88SDan Gohman 361d934cb88SDan Gohman // Write X as an (unsigned) LEB value at offset Offset in Stream, padded 362d934cb88SDan Gohman // to allow patching. 363d934cb88SDan Gohman static void 364d934cb88SDan Gohman WritePatchableLEB(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) { 365d934cb88SDan Gohman uint8_t Buffer[5]; 366d934cb88SDan Gohman unsigned Padding = PaddingFor5ByteULEB128(X); 367d934cb88SDan Gohman unsigned SizeLen = encodeULEB128(X, Buffer, Padding); 368d934cb88SDan Gohman assert(SizeLen == 5); 369d934cb88SDan Gohman Stream.pwrite((char *)Buffer, SizeLen, Offset); 370d934cb88SDan Gohman } 371d934cb88SDan Gohman 372d934cb88SDan Gohman // Write X as an signed LEB value at offset Offset in Stream, padded 373d934cb88SDan Gohman // to allow patching. 374d934cb88SDan Gohman static void 375d934cb88SDan Gohman WritePatchableSLEB(raw_pwrite_stream &Stream, int32_t X, uint64_t Offset) { 376d934cb88SDan Gohman uint8_t Buffer[5]; 377d934cb88SDan Gohman unsigned Padding = PaddingFor5ByteSLEB128(X); 378d934cb88SDan Gohman unsigned SizeLen = encodeSLEB128(X, Buffer, Padding); 379d934cb88SDan Gohman assert(SizeLen == 5); 380d934cb88SDan Gohman Stream.pwrite((char *)Buffer, SizeLen, Offset); 381d934cb88SDan Gohman } 382d934cb88SDan Gohman 383d934cb88SDan Gohman // Write X as a plain integer value at offset Offset in Stream. 384d934cb88SDan Gohman static void WriteI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) { 385d934cb88SDan Gohman uint8_t Buffer[4]; 386d934cb88SDan Gohman support::endian::write32le(Buffer, X); 387d934cb88SDan Gohman Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset); 388d934cb88SDan Gohman } 389d934cb88SDan Gohman 390d934cb88SDan Gohman // Compute a value to write into the code at the location covered 391d934cb88SDan Gohman // by RelEntry. This value isn't used by the static linker, since 392d934cb88SDan Gohman // we have addends; it just serves to make the code more readable 393d934cb88SDan Gohman // and to make standalone wasm modules directly usable. 394d934cb88SDan Gohman static uint32_t ProvisionalValue(const WasmRelocationEntry &RelEntry) { 395d934cb88SDan Gohman const MCSymbolWasm *Sym = RelEntry.Symbol; 396d934cb88SDan Gohman 397d934cb88SDan Gohman // For undefined symbols, use a hopefully invalid value. 398d934cb88SDan Gohman if (!Sym->isDefined(false)) 399d934cb88SDan Gohman return UINT32_MAX; 400d934cb88SDan Gohman 401d934cb88SDan Gohman MCSectionWasm &Section = 402d934cb88SDan Gohman cast<MCSectionWasm>(RelEntry.Symbol->getSection(false)); 403d934cb88SDan Gohman uint64_t Address = Section.getSectionOffset() + RelEntry.Addend; 404d934cb88SDan Gohman 405d934cb88SDan Gohman // Ignore overflow. LLVM allows address arithmetic to silently wrap. 406d934cb88SDan Gohman uint32_t Value = Address; 407d934cb88SDan Gohman 408d934cb88SDan Gohman return Value; 409d934cb88SDan Gohman } 410d934cb88SDan Gohman 411d934cb88SDan Gohman // Apply the portions of the relocation records that we can handle ourselves 412d934cb88SDan Gohman // directly. 413d934cb88SDan Gohman static void ApplyRelocations( 414d934cb88SDan Gohman ArrayRef<WasmRelocationEntry> Relocations, 415d934cb88SDan Gohman raw_pwrite_stream &Stream, 416d934cb88SDan Gohman DenseMap<const MCSymbolWasm *, uint32_t> &SymbolIndices, 417d934cb88SDan Gohman uint64_t ContentsOffset) 418d934cb88SDan Gohman { 419d934cb88SDan Gohman for (const WasmRelocationEntry &RelEntry : Relocations) { 420d934cb88SDan Gohman uint64_t Offset = ContentsOffset + 421d934cb88SDan Gohman RelEntry.FixupSection->getSectionOffset() + 422d934cb88SDan Gohman RelEntry.Offset; 423d934cb88SDan Gohman switch (RelEntry.Type) { 424d934cb88SDan Gohman case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB: { 425d934cb88SDan Gohman uint32_t Index = SymbolIndices[RelEntry.Symbol]; 426d934cb88SDan Gohman assert(RelEntry.Addend == 0); 427d934cb88SDan Gohman 428d934cb88SDan Gohman WritePatchableLEB(Stream, Index, Offset); 429d934cb88SDan Gohman break; 430d934cb88SDan Gohman } 431d934cb88SDan Gohman case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB: { 432d934cb88SDan Gohman uint32_t Index = SymbolIndices[RelEntry.Symbol]; 433d934cb88SDan Gohman assert(RelEntry.Addend == 0); 434d934cb88SDan Gohman 435d934cb88SDan Gohman WritePatchableSLEB(Stream, Index, Offset); 436d934cb88SDan Gohman break; 437d934cb88SDan Gohman } 438d934cb88SDan Gohman case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_SLEB: { 439d934cb88SDan Gohman uint32_t Value = ProvisionalValue(RelEntry); 440d934cb88SDan Gohman 441d934cb88SDan Gohman WritePatchableSLEB(Stream, Value, Offset); 442d934cb88SDan Gohman break; 443d934cb88SDan Gohman } 444d934cb88SDan Gohman case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_LEB: { 445d934cb88SDan Gohman uint32_t Value = ProvisionalValue(RelEntry); 446d934cb88SDan Gohman 447d934cb88SDan Gohman WritePatchableLEB(Stream, Value, Offset); 448d934cb88SDan Gohman break; 449d934cb88SDan Gohman } 450d934cb88SDan Gohman case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: { 451d934cb88SDan Gohman uint32_t Index = SymbolIndices[RelEntry.Symbol]; 452d934cb88SDan Gohman assert(RelEntry.Addend == 0); 453d934cb88SDan Gohman 454d934cb88SDan Gohman WriteI32(Stream, Index, Offset); 455d934cb88SDan Gohman break; 456d934cb88SDan Gohman } 457d934cb88SDan Gohman case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_I32: { 458d934cb88SDan Gohman uint32_t Value = ProvisionalValue(RelEntry); 459d934cb88SDan Gohman 460d934cb88SDan Gohman WriteI32(Stream, Value, Offset); 461d934cb88SDan Gohman break; 462d934cb88SDan Gohman } 463d934cb88SDan Gohman default: 464d934cb88SDan Gohman break; 465d934cb88SDan Gohman } 466d934cb88SDan Gohman } 467d934cb88SDan Gohman } 468d934cb88SDan Gohman 469d934cb88SDan Gohman // Write out the portions of the relocation records that the linker will 470d934cb88SDan Gohman // need to handle. 471d934cb88SDan Gohman static void WriteRelocations( 472d934cb88SDan Gohman ArrayRef<WasmRelocationEntry> Relocations, 473d934cb88SDan Gohman raw_pwrite_stream &Stream, 474d934cb88SDan Gohman DenseMap<const MCSymbolWasm *, uint32_t> &SymbolIndices) 475d934cb88SDan Gohman { 476d934cb88SDan Gohman for (const WasmRelocationEntry RelEntry : Relocations) { 477d934cb88SDan Gohman encodeULEB128(RelEntry.Type, Stream); 478d934cb88SDan Gohman 479d934cb88SDan Gohman uint64_t Offset = RelEntry.Offset + 480d934cb88SDan Gohman RelEntry.FixupSection->getSectionOffset(); 481d934cb88SDan Gohman uint32_t Index = SymbolIndices[RelEntry.Symbol]; 482d934cb88SDan Gohman int64_t Addend = RelEntry.Addend; 483d934cb88SDan Gohman 484d934cb88SDan Gohman switch (RelEntry.Type) { 485d934cb88SDan Gohman case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB: 486d934cb88SDan Gohman case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB: 487d934cb88SDan Gohman case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: 488d934cb88SDan Gohman encodeULEB128(Offset, Stream); 489d934cb88SDan Gohman encodeULEB128(Index, Stream); 490d934cb88SDan Gohman assert(Addend == 0 && "addends not supported for functions"); 491d934cb88SDan Gohman break; 492d934cb88SDan Gohman case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_LEB: 493d934cb88SDan Gohman case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_SLEB: 494d934cb88SDan Gohman case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_I32: 495d934cb88SDan Gohman encodeULEB128(Offset, Stream); 496d934cb88SDan Gohman encodeULEB128(Index, Stream); 497d934cb88SDan Gohman encodeSLEB128(Addend, Stream); 498d934cb88SDan Gohman break; 499d934cb88SDan Gohman default: 500d934cb88SDan Gohman llvm_unreachable("unsupported relocation type"); 501d934cb88SDan Gohman } 502d934cb88SDan Gohman } 50318eafb6cSDan Gohman } 50418eafb6cSDan Gohman 50518eafb6cSDan Gohman void WasmObjectWriter::writeObject(MCAssembler &Asm, 50618eafb6cSDan Gohman const MCAsmLayout &Layout) { 507*82607f56SDan Gohman MCContext &Ctx = Asm.getContext(); 508d934cb88SDan Gohman unsigned PtrType = is64Bit() ? wasm::WASM_TYPE_I64 : wasm::WASM_TYPE_I32; 509d934cb88SDan Gohman 510d934cb88SDan Gohman // Collect information from the available symbols. 511d934cb88SDan Gohman DenseMap<WasmFunctionType, unsigned, WasmFunctionTypeDenseMapInfo> 512d934cb88SDan Gohman FunctionTypeIndices; 513d934cb88SDan Gohman SmallVector<WasmFunctionType, 4> FunctionTypes; 514d934cb88SDan Gohman SmallVector<WasmFunction, 4> Functions; 515d934cb88SDan Gohman SmallVector<uint32_t, 4> TableElems; 516d934cb88SDan Gohman SmallVector<WasmGlobal, 4> Globals; 517d934cb88SDan Gohman SmallVector<WasmImport, 4> Imports; 518d934cb88SDan Gohman SmallVector<WasmExport, 4> Exports; 519d934cb88SDan Gohman DenseMap<const MCSymbolWasm *, uint32_t> SymbolIndices; 520d934cb88SDan Gohman SmallPtrSet<const MCSymbolWasm *, 4> IsAddressTaken; 521d934cb88SDan Gohman unsigned NumFuncImports = 0; 522d934cb88SDan Gohman unsigned NumGlobalImports = 0; 523d934cb88SDan Gohman SmallVector<char, 0> DataBytes; 524d934cb88SDan Gohman 525d934cb88SDan Gohman // Populate the IsAddressTaken set. 526d934cb88SDan Gohman for (WasmRelocationEntry RelEntry : CodeRelocations) { 527d934cb88SDan Gohman switch (RelEntry.Type) { 528d934cb88SDan Gohman case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB: 529d934cb88SDan Gohman case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_SLEB: 530d934cb88SDan Gohman IsAddressTaken.insert(RelEntry.Symbol); 531d934cb88SDan Gohman break; 532d934cb88SDan Gohman default: 533d934cb88SDan Gohman break; 534d934cb88SDan Gohman } 535d934cb88SDan Gohman } 536d934cb88SDan Gohman for (WasmRelocationEntry RelEntry : DataRelocations) { 537d934cb88SDan Gohman switch (RelEntry.Type) { 538d934cb88SDan Gohman case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: 539d934cb88SDan Gohman case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_I32: 540d934cb88SDan Gohman IsAddressTaken.insert(RelEntry.Symbol); 541d934cb88SDan Gohman break; 542d934cb88SDan Gohman default: 543d934cb88SDan Gohman break; 544d934cb88SDan Gohman } 545d934cb88SDan Gohman } 546d934cb88SDan Gohman 547d934cb88SDan Gohman // Populate the Imports set. 548d934cb88SDan Gohman for (const MCSymbol &S : Asm.symbols()) { 549d934cb88SDan Gohman const auto &WS = static_cast<const MCSymbolWasm &>(S); 550d934cb88SDan Gohman unsigned Type; 551d934cb88SDan Gohman 552d934cb88SDan Gohman if (WS.isFunction()) { 553d934cb88SDan Gohman // Prepare the function's type, if we haven't seen it yet. 554d934cb88SDan Gohman WasmFunctionType F; 555d934cb88SDan Gohman F.Returns = WS.getReturns(); 556d934cb88SDan Gohman F.Params = WS.getParams(); 557d934cb88SDan Gohman auto Pair = 558d934cb88SDan Gohman FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size())); 559d934cb88SDan Gohman if (Pair.second) 560d934cb88SDan Gohman FunctionTypes.push_back(F); 561d934cb88SDan Gohman 562d934cb88SDan Gohman Type = Pair.first->second; 563d934cb88SDan Gohman } else { 564d934cb88SDan Gohman Type = PtrType; 565d934cb88SDan Gohman } 566d934cb88SDan Gohman 567d934cb88SDan Gohman // If the symbol is not defined in this translation unit, import it. 568d934cb88SDan Gohman if (!WS.isTemporary() && !WS.isDefined(/*SetUsed=*/false)) { 569d934cb88SDan Gohman WasmImport Import; 570d934cb88SDan Gohman Import.ModuleName = WS.getModuleName(); 571d934cb88SDan Gohman Import.FieldName = WS.getName(); 572d934cb88SDan Gohman 573d934cb88SDan Gohman if (WS.isFunction()) { 574d934cb88SDan Gohman Import.Kind = wasm::WASM_EXTERNAL_FUNCTION; 575d934cb88SDan Gohman Import.Type = Type; 576d934cb88SDan Gohman SymbolIndices[&WS] = NumFuncImports; 577d934cb88SDan Gohman ++NumFuncImports; 578d934cb88SDan Gohman } else { 579d934cb88SDan Gohman Import.Kind = wasm::WASM_EXTERNAL_GLOBAL; 580d934cb88SDan Gohman Import.Type = Type; 581d934cb88SDan Gohman SymbolIndices[&WS] = NumGlobalImports; 582d934cb88SDan Gohman ++NumGlobalImports; 583d934cb88SDan Gohman } 584d934cb88SDan Gohman 585d934cb88SDan Gohman Imports.push_back(Import); 586d934cb88SDan Gohman } 587d934cb88SDan Gohman } 588d934cb88SDan Gohman 589*82607f56SDan Gohman // In the special .global_variables section, we've encoded global 590*82607f56SDan Gohman // variables used by the function. Translate them into the Globals 591*82607f56SDan Gohman // list. 592*82607f56SDan Gohman MCSectionWasm *GlobalVars = Ctx.getWasmSection(".global_variables", 0, 0); 593*82607f56SDan Gohman if (!GlobalVars->getFragmentList().empty()) { 594*82607f56SDan Gohman if (GlobalVars->getFragmentList().size() != 1) 595*82607f56SDan Gohman report_fatal_error("only one .global_variables fragment supported"); 596*82607f56SDan Gohman const MCFragment &Frag = *GlobalVars->begin(); 597*82607f56SDan Gohman if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data) 598*82607f56SDan Gohman report_fatal_error("only data supported in .global_variables"); 599*82607f56SDan Gohman const MCDataFragment &DataFrag = cast<MCDataFragment>(Frag); 600*82607f56SDan Gohman if (!DataFrag.getFixups().empty()) 601*82607f56SDan Gohman report_fatal_error("fixups not supported in .global_variables"); 602*82607f56SDan Gohman const SmallVectorImpl<char> &Contents = DataFrag.getContents(); 603*82607f56SDan Gohman for (char p : Contents) { 604*82607f56SDan Gohman WasmGlobal G; 605*82607f56SDan Gohman G.Type = uint8_t(p); 606*82607f56SDan Gohman G.IsMutable = true; 607*82607f56SDan Gohman G.InitialValue = 0; 608*82607f56SDan Gohman Globals.push_back(G); 609*82607f56SDan Gohman } 610*82607f56SDan Gohman } 611*82607f56SDan Gohman 612d934cb88SDan Gohman // Handle defined symbols. 613d934cb88SDan Gohman for (const MCSymbol &S : Asm.symbols()) { 614d934cb88SDan Gohman // Ignore unnamed temporary symbols, which aren't ever exported, imported, 615d934cb88SDan Gohman // or used in relocations. 616d934cb88SDan Gohman if (S.isTemporary() && S.getName().empty()) 617d934cb88SDan Gohman continue; 618d934cb88SDan Gohman const auto &WS = static_cast<const MCSymbolWasm &>(S); 619d934cb88SDan Gohman unsigned Index; 620d934cb88SDan Gohman if (WS.isFunction()) { 621d934cb88SDan Gohman // Prepare the function's type, if we haven't seen it yet. 622d934cb88SDan Gohman WasmFunctionType F; 623d934cb88SDan Gohman F.Returns = WS.getReturns(); 624d934cb88SDan Gohman F.Params = WS.getParams(); 625d934cb88SDan Gohman auto Pair = 626d934cb88SDan Gohman FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size())); 627d934cb88SDan Gohman if (Pair.second) 628d934cb88SDan Gohman FunctionTypes.push_back(F); 629d934cb88SDan Gohman 630d934cb88SDan Gohman unsigned Type = Pair.first->second; 631d934cb88SDan Gohman 632d934cb88SDan Gohman if (WS.isDefined(/*SetUsed=*/false)) { 633d934cb88SDan Gohman // A definition. Take the next available index. 634d934cb88SDan Gohman Index = NumFuncImports + Functions.size(); 635d934cb88SDan Gohman 636d934cb88SDan Gohman // Prepare the function. 637d934cb88SDan Gohman WasmFunction Func; 638d934cb88SDan Gohman Func.Type = Type; 639d934cb88SDan Gohman Func.Sym = &WS; 640d934cb88SDan Gohman SymbolIndices[&WS] = Index; 641d934cb88SDan Gohman Functions.push_back(Func); 642d934cb88SDan Gohman } else { 643d934cb88SDan Gohman // An import; the index was assigned above. 644d934cb88SDan Gohman Index = SymbolIndices.find(&WS)->second; 645d934cb88SDan Gohman } 646d934cb88SDan Gohman 647d934cb88SDan Gohman // If needed, prepare the function to be called indirectly. 648d934cb88SDan Gohman if (IsAddressTaken.count(&WS)) 649d934cb88SDan Gohman TableElems.push_back(Index); 650d934cb88SDan Gohman } else { 651d934cb88SDan Gohman // For now, ignore temporary non-function symbols. 652d934cb88SDan Gohman if (S.isTemporary()) 653d934cb88SDan Gohman continue; 654d934cb88SDan Gohman 655d934cb88SDan Gohman if (WS.getOffset() != 0) 656d934cb88SDan Gohman report_fatal_error("data sections must contain one variable each"); 657d934cb88SDan Gohman if (!WS.getSize()) 658d934cb88SDan Gohman report_fatal_error("data symbols must have a size set with .size"); 659d934cb88SDan Gohman 660d934cb88SDan Gohman int64_t Size = 0; 661d934cb88SDan Gohman if (!WS.getSize()->evaluateAsAbsolute(Size, Layout)) 662d934cb88SDan Gohman report_fatal_error(".size expression must be evaluatable"); 663d934cb88SDan Gohman 664d934cb88SDan Gohman if (WS.isDefined(false)) { 665d934cb88SDan Gohman MCSectionWasm &DataSection = 666d934cb88SDan Gohman static_cast<MCSectionWasm &>(WS.getSection()); 667d934cb88SDan Gohman 668d934cb88SDan Gohman if (uint64_t(Size) != Layout.getSectionFileSize(&DataSection)) 669d934cb88SDan Gohman report_fatal_error("data sections must contain at most one variable"); 670d934cb88SDan Gohman 671d934cb88SDan Gohman DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment())); 672d934cb88SDan Gohman 673d934cb88SDan Gohman DataSection.setSectionOffset(DataBytes.size()); 674d934cb88SDan Gohman 675d934cb88SDan Gohman for (MCSection::iterator I = DataSection.begin(), E = DataSection.end(); 676d934cb88SDan Gohman I != E; ++I) { 677d934cb88SDan Gohman const MCFragment &Frag = *I; 678d934cb88SDan Gohman if (Frag.hasInstructions()) 679d934cb88SDan Gohman report_fatal_error("only data supported in data sections"); 680d934cb88SDan Gohman 681d934cb88SDan Gohman if (const MCAlignFragment *Align = dyn_cast<MCAlignFragment>(&Frag)) { 682d934cb88SDan Gohman if (Align->getValueSize() != 1) 683d934cb88SDan Gohman report_fatal_error("only byte values supported for alignment"); 684d934cb88SDan Gohman // If nops are requested, use zeros, as this is the data section. 685d934cb88SDan Gohman uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue(); 686d934cb88SDan Gohman uint64_t Size = std::min<uint64_t>(alignTo(DataBytes.size(), 687d934cb88SDan Gohman Align->getAlignment()), 688d934cb88SDan Gohman DataBytes.size() + 689d934cb88SDan Gohman Align->getMaxBytesToEmit()); 690d934cb88SDan Gohman DataBytes.resize(Size, Value); 691d934cb88SDan Gohman } else if (const MCFillFragment *Fill = 692d934cb88SDan Gohman dyn_cast<MCFillFragment>(&Frag)) { 693d934cb88SDan Gohman DataBytes.insert(DataBytes.end(), Size, Fill->getValue()); 694d934cb88SDan Gohman } else { 695d934cb88SDan Gohman const MCDataFragment &DataFrag = cast<MCDataFragment>(Frag); 696d934cb88SDan Gohman const SmallVectorImpl<char> &Contents = DataFrag.getContents(); 697d934cb88SDan Gohman 698d934cb88SDan Gohman DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end()); 699d934cb88SDan Gohman } 700d934cb88SDan Gohman } 701d934cb88SDan Gohman 702d934cb88SDan Gohman // For each external global, prepare a corresponding wasm global 703d934cb88SDan Gohman // holding its address. 704d934cb88SDan Gohman if (WS.isExternal()) { 705d934cb88SDan Gohman Index = NumGlobalImports + Globals.size(); 706d934cb88SDan Gohman 707d934cb88SDan Gohman WasmGlobal Global; 708d934cb88SDan Gohman Global.Type = PtrType; 709d934cb88SDan Gohman Global.IsMutable = false; 710d934cb88SDan Gohman Global.InitialValue = DataSection.getSectionOffset(); 711d934cb88SDan Gohman SymbolIndices[&WS] = Index; 712d934cb88SDan Gohman Globals.push_back(Global); 713d934cb88SDan Gohman } 714d934cb88SDan Gohman } 715d934cb88SDan Gohman } 716d934cb88SDan Gohman 717d934cb88SDan Gohman // If the symbol is visible outside this translation unit, export it. 718d934cb88SDan Gohman if (WS.isExternal()) { 719d934cb88SDan Gohman assert(WS.isDefined(false)); 720d934cb88SDan Gohman WasmExport Export; 721d934cb88SDan Gohman Export.FieldName = WS.getName(); 722d934cb88SDan Gohman Export.Index = Index; 723d934cb88SDan Gohman 724d934cb88SDan Gohman if (WS.isFunction()) 725d934cb88SDan Gohman Export.Kind = wasm::WASM_EXTERNAL_FUNCTION; 726d934cb88SDan Gohman else 727d934cb88SDan Gohman Export.Kind = wasm::WASM_EXTERNAL_GLOBAL; 728d934cb88SDan Gohman 729d934cb88SDan Gohman Exports.push_back(Export); 730d934cb88SDan Gohman } 731d934cb88SDan Gohman } 732d934cb88SDan Gohman 733d934cb88SDan Gohman // Add types for indirect function calls. 734d934cb88SDan Gohman for (const TypeIndexFixup &Fixup : TypeIndexFixups) { 735d934cb88SDan Gohman WasmFunctionType F; 736d934cb88SDan Gohman F.Returns = Fixup.Symbol->getReturns(); 737d934cb88SDan Gohman F.Params = Fixup.Symbol->getParams(); 738d934cb88SDan Gohman auto Pair = 739d934cb88SDan Gohman FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size())); 740d934cb88SDan Gohman if (Pair.second) 741d934cb88SDan Gohman FunctionTypes.push_back(F); 742d934cb88SDan Gohman 743d934cb88SDan Gohman TypeIndexFixupTypes.push_back(Pair.first->second); 744d934cb88SDan Gohman } 745d934cb88SDan Gohman 74618eafb6cSDan Gohman // Write out the Wasm header. 74718eafb6cSDan Gohman writeHeader(Asm); 74818eafb6cSDan Gohman 749d934cb88SDan Gohman SectionBookkeeping Section; 750d934cb88SDan Gohman 751d934cb88SDan Gohman // === Type Section ========================================================= 752d934cb88SDan Gohman if (!FunctionTypes.empty()) { 753d934cb88SDan Gohman startSection(Section, wasm::WASM_SEC_TYPE); 754d934cb88SDan Gohman 755d934cb88SDan Gohman encodeULEB128(FunctionTypes.size(), getStream()); 756d934cb88SDan Gohman 757d934cb88SDan Gohman for (WasmFunctionType &FuncTy : FunctionTypes) { 758d934cb88SDan Gohman write8(wasm::WASM_TYPE_FUNC); 759d934cb88SDan Gohman encodeULEB128(FuncTy.Params.size(), getStream()); 760d934cb88SDan Gohman for (unsigned Ty : FuncTy.Params) 761d934cb88SDan Gohman write8(Ty); 762d934cb88SDan Gohman encodeULEB128(FuncTy.Returns.size(), getStream()); 763d934cb88SDan Gohman for (unsigned Ty : FuncTy.Returns) 764d934cb88SDan Gohman write8(Ty); 765d934cb88SDan Gohman } 766d934cb88SDan Gohman 767d934cb88SDan Gohman endSection(Section); 768d934cb88SDan Gohman } 769d934cb88SDan Gohman 770d934cb88SDan Gohman // === Import Section ======================================================== 771d934cb88SDan Gohman if (!Imports.empty()) { 772d934cb88SDan Gohman startSection(Section, wasm::WASM_SEC_IMPORT); 773d934cb88SDan Gohman 774d934cb88SDan Gohman encodeULEB128(Imports.size(), getStream()); 775d934cb88SDan Gohman for (const WasmImport &Import : Imports) { 776d934cb88SDan Gohman StringRef ModuleName = Import.ModuleName; 777d934cb88SDan Gohman encodeULEB128(ModuleName.size(), getStream()); 778d934cb88SDan Gohman writeBytes(ModuleName); 779d934cb88SDan Gohman 780d934cb88SDan Gohman StringRef FieldName = Import.FieldName; 781d934cb88SDan Gohman encodeULEB128(FieldName.size(), getStream()); 782d934cb88SDan Gohman writeBytes(FieldName); 783d934cb88SDan Gohman 784d934cb88SDan Gohman write8(Import.Kind); 785d934cb88SDan Gohman 786d934cb88SDan Gohman switch (Import.Kind) { 787d934cb88SDan Gohman case wasm::WASM_EXTERNAL_FUNCTION: 788d934cb88SDan Gohman encodeULEB128(Import.Type, getStream()); 789d934cb88SDan Gohman break; 790d934cb88SDan Gohman case wasm::WASM_EXTERNAL_GLOBAL: 791d934cb88SDan Gohman write8(Import.Type); 792d934cb88SDan Gohman write8(0); // mutability 793d934cb88SDan Gohman break; 794d934cb88SDan Gohman default: 795d934cb88SDan Gohman llvm_unreachable("unsupported import kind"); 796d934cb88SDan Gohman } 797d934cb88SDan Gohman } 798d934cb88SDan Gohman 799d934cb88SDan Gohman endSection(Section); 800d934cb88SDan Gohman } 801d934cb88SDan Gohman 802d934cb88SDan Gohman // === Function Section ====================================================== 803d934cb88SDan Gohman if (!Functions.empty()) { 804d934cb88SDan Gohman startSection(Section, wasm::WASM_SEC_FUNCTION); 805d934cb88SDan Gohman 806d934cb88SDan Gohman encodeULEB128(Functions.size(), getStream()); 807d934cb88SDan Gohman for (const WasmFunction &Func : Functions) 808d934cb88SDan Gohman encodeULEB128(Func.Type, getStream()); 809d934cb88SDan Gohman 810d934cb88SDan Gohman endSection(Section); 811d934cb88SDan Gohman } 812d934cb88SDan Gohman 813d934cb88SDan Gohman // === Table Section ========================================================= 814d934cb88SDan Gohman // For now, always emit the table section, since indirect calls are not 815d934cb88SDan Gohman // valid without it. In the future, we could perhaps be more clever and omit 816d934cb88SDan Gohman // it if there are no indirect calls. 817d934cb88SDan Gohman startSection(Section, wasm::WASM_SEC_TABLE); 818d934cb88SDan Gohman 819d934cb88SDan Gohman // The number of tables, fixed to 1 for now. 820d934cb88SDan Gohman encodeULEB128(1, getStream()); 821d934cb88SDan Gohman 822d934cb88SDan Gohman write8(wasm::WASM_TYPE_ANYFUNC); 823d934cb88SDan Gohman 824d934cb88SDan Gohman encodeULEB128(0, getStream()); // flags 825d934cb88SDan Gohman encodeULEB128(TableElems.size(), getStream()); // initial 826d934cb88SDan Gohman 827d934cb88SDan Gohman endSection(Section); 828d934cb88SDan Gohman 829d934cb88SDan Gohman // === Memory Section ======================================================== 830d934cb88SDan Gohman // For now, always emit the memory section, since loads and stores are not 831d934cb88SDan Gohman // valid without it. In the future, we could perhaps be more clever and omit 832d934cb88SDan Gohman // it if there are no loads or stores. 833d934cb88SDan Gohman startSection(Section, wasm::WASM_SEC_MEMORY); 834d934cb88SDan Gohman 835d934cb88SDan Gohman encodeULEB128(1, getStream()); // number of memory spaces 836d934cb88SDan Gohman 837d934cb88SDan Gohman encodeULEB128(0, getStream()); // flags 838d934cb88SDan Gohman encodeULEB128(DataBytes.size(), getStream()); // initial 839d934cb88SDan Gohman 840d934cb88SDan Gohman endSection(Section); 841d934cb88SDan Gohman 842d934cb88SDan Gohman // === Global Section ======================================================== 843d934cb88SDan Gohman if (!Globals.empty()) { 844d934cb88SDan Gohman startSection(Section, wasm::WASM_SEC_GLOBAL); 845d934cb88SDan Gohman 846d934cb88SDan Gohman encodeULEB128(Globals.size(), getStream()); 847d934cb88SDan Gohman for (const WasmGlobal &Global : Globals) { 848d934cb88SDan Gohman write8(Global.Type); 849d934cb88SDan Gohman write8(Global.IsMutable); 850d934cb88SDan Gohman 851d934cb88SDan Gohman write8(wasm::WASM_OPCODE_I32_CONST); 852d934cb88SDan Gohman encodeSLEB128(Global.InitialValue, getStream()); // offset 853d934cb88SDan Gohman write8(wasm::WASM_OPCODE_END); 854d934cb88SDan Gohman } 855d934cb88SDan Gohman 856d934cb88SDan Gohman endSection(Section); 857d934cb88SDan Gohman } 858d934cb88SDan Gohman 859d934cb88SDan Gohman // === Export Section ======================================================== 860d934cb88SDan Gohman if (!Exports.empty()) { 861d934cb88SDan Gohman startSection(Section, wasm::WASM_SEC_EXPORT); 862d934cb88SDan Gohman 863d934cb88SDan Gohman encodeULEB128(Exports.size(), getStream()); 864d934cb88SDan Gohman for (const WasmExport &Export : Exports) { 865d934cb88SDan Gohman encodeULEB128(Export.FieldName.size(), getStream()); 866d934cb88SDan Gohman writeBytes(Export.FieldName); 867d934cb88SDan Gohman 868d934cb88SDan Gohman write8(Export.Kind); 869d934cb88SDan Gohman 870d934cb88SDan Gohman encodeULEB128(Export.Index, getStream()); 871d934cb88SDan Gohman } 872d934cb88SDan Gohman 873d934cb88SDan Gohman endSection(Section); 874d934cb88SDan Gohman } 875d934cb88SDan Gohman 876d934cb88SDan Gohman #if 0 // TODO: Start Section 877d934cb88SDan Gohman if (HaveStartFunction) { 878d934cb88SDan Gohman // === Start Section ========================================================= 879d934cb88SDan Gohman startSection(Section, wasm::WASM_SEC_START); 880d934cb88SDan Gohman 881d934cb88SDan Gohman encodeSLEB128(StartFunction, getStream()); 882d934cb88SDan Gohman 883d934cb88SDan Gohman endSection(Section); 884d934cb88SDan Gohman } 885d934cb88SDan Gohman #endif 886d934cb88SDan Gohman 887d934cb88SDan Gohman // === Elem Section ========================================================== 888d934cb88SDan Gohman if (!TableElems.empty()) { 889d934cb88SDan Gohman startSection(Section, wasm::WASM_SEC_ELEM); 890d934cb88SDan Gohman 891d934cb88SDan Gohman encodeULEB128(1, getStream()); // number of "segments" 892d934cb88SDan Gohman encodeULEB128(0, getStream()); // the table index 893d934cb88SDan Gohman 894d934cb88SDan Gohman // init expr for starting offset 895d934cb88SDan Gohman write8(wasm::WASM_OPCODE_I32_CONST); 896d934cb88SDan Gohman encodeSLEB128(0, getStream()); 897d934cb88SDan Gohman write8(wasm::WASM_OPCODE_END); 898d934cb88SDan Gohman 899d934cb88SDan Gohman encodeULEB128(TableElems.size(), getStream()); 900d934cb88SDan Gohman for (uint32_t Elem : TableElems) 901d934cb88SDan Gohman encodeULEB128(Elem, getStream()); 902d934cb88SDan Gohman 903d934cb88SDan Gohman endSection(Section); 904d934cb88SDan Gohman } 905d934cb88SDan Gohman 906d934cb88SDan Gohman // === Code Section ========================================================== 907d934cb88SDan Gohman if (!Functions.empty()) { 908d934cb88SDan Gohman startSection(Section, wasm::WASM_SEC_CODE); 909d934cb88SDan Gohman 910d934cb88SDan Gohman encodeULEB128(Functions.size(), getStream()); 911d934cb88SDan Gohman 912d934cb88SDan Gohman for (const WasmFunction &Func : Functions) { 913d934cb88SDan Gohman MCSectionWasm &FuncSection = 914d934cb88SDan Gohman static_cast<MCSectionWasm &>(Func.Sym->getSection()); 915d934cb88SDan Gohman 916d934cb88SDan Gohman if (Func.Sym->isVariable()) 917d934cb88SDan Gohman report_fatal_error("weak symbols not supported yet"); 918d934cb88SDan Gohman 919d934cb88SDan Gohman if (Func.Sym->getOffset() != 0) 920d934cb88SDan Gohman report_fatal_error("function sections must contain one function each"); 921d934cb88SDan Gohman 922d934cb88SDan Gohman if (!Func.Sym->getSize()) 923d934cb88SDan Gohman report_fatal_error("function symbols must have a size set with .size"); 924d934cb88SDan Gohman 925d934cb88SDan Gohman int64_t Size = 0; 926d934cb88SDan Gohman if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout)) 927d934cb88SDan Gohman report_fatal_error(".size expression must be evaluatable"); 928d934cb88SDan Gohman 929d934cb88SDan Gohman encodeULEB128(Size, getStream()); 930d934cb88SDan Gohman 931d934cb88SDan Gohman FuncSection.setSectionOffset(getStream().tell() - 932d934cb88SDan Gohman Section.ContentsOffset); 933d934cb88SDan Gohman 934d934cb88SDan Gohman Asm.writeSectionData(&FuncSection, Layout); 935d934cb88SDan Gohman } 936d934cb88SDan Gohman 937d934cb88SDan Gohman // Apply the type index fixups for call_indirect etc. instructions. 938d934cb88SDan Gohman for (size_t i = 0, e = TypeIndexFixups.size(); i < e; ++i) { 939d934cb88SDan Gohman uint32_t Type = TypeIndexFixupTypes[i]; 940d934cb88SDan Gohman unsigned Padding = PaddingFor5ByteULEB128(Type); 941d934cb88SDan Gohman 942d934cb88SDan Gohman const TypeIndexFixup &Fixup = TypeIndexFixups[i]; 943d934cb88SDan Gohman uint64_t Offset = Fixup.Offset + 944d934cb88SDan Gohman Fixup.FixupSection->getSectionOffset(); 945d934cb88SDan Gohman 946d934cb88SDan Gohman uint8_t Buffer[16]; 947d934cb88SDan Gohman unsigned SizeLen = encodeULEB128(Type, Buffer, Padding); 948d934cb88SDan Gohman assert(SizeLen == 5); 949d934cb88SDan Gohman getStream().pwrite((char *)Buffer, SizeLen, 950d934cb88SDan Gohman Section.ContentsOffset + Offset); 951d934cb88SDan Gohman } 952d934cb88SDan Gohman 953d934cb88SDan Gohman // Apply fixups. 954d934cb88SDan Gohman ApplyRelocations(CodeRelocations, getStream(), SymbolIndices, 955d934cb88SDan Gohman Section.ContentsOffset); 956d934cb88SDan Gohman 957d934cb88SDan Gohman endSection(Section); 958d934cb88SDan Gohman } 959d934cb88SDan Gohman 960d934cb88SDan Gohman // === Data Section ========================================================== 961d934cb88SDan Gohman if (!DataBytes.empty()) { 962d934cb88SDan Gohman startSection(Section, wasm::WASM_SEC_DATA); 963d934cb88SDan Gohman 964d934cb88SDan Gohman encodeULEB128(1, getStream()); // count 965d934cb88SDan Gohman encodeULEB128(0, getStream()); // memory index 966d934cb88SDan Gohman write8(wasm::WASM_OPCODE_I32_CONST); 967d934cb88SDan Gohman encodeSLEB128(0, getStream()); // offset 968d934cb88SDan Gohman write8(wasm::WASM_OPCODE_END); 969d934cb88SDan Gohman encodeULEB128(DataBytes.size(), getStream()); // size 970d934cb88SDan Gohman writeBytes(DataBytes); // data 971d934cb88SDan Gohman 972d934cb88SDan Gohman // Apply fixups. 973d934cb88SDan Gohman ApplyRelocations(DataRelocations, getStream(), SymbolIndices, 974d934cb88SDan Gohman Section.ContentsOffset); 975d934cb88SDan Gohman 976d934cb88SDan Gohman endSection(Section); 977d934cb88SDan Gohman } 978d934cb88SDan Gohman 979d934cb88SDan Gohman // === Name Section ========================================================== 980d934cb88SDan Gohman if (NumFuncImports != 0 || !Functions.empty()) { 981d934cb88SDan Gohman startSection(Section, wasm::WASM_SEC_CUSTOM, "name"); 982d934cb88SDan Gohman 983d934cb88SDan Gohman encodeULEB128(NumFuncImports + Functions.size(), getStream()); 984d934cb88SDan Gohman for (const WasmImport &Import : Imports) { 985d934cb88SDan Gohman if (Import.Kind == wasm::WASM_EXTERNAL_FUNCTION) { 986d934cb88SDan Gohman encodeULEB128(Import.FieldName.size(), getStream()); 987d934cb88SDan Gohman writeBytes(Import.FieldName); 988d934cb88SDan Gohman encodeULEB128(0, getStream()); // local count, meaningless for imports 989d934cb88SDan Gohman } 990d934cb88SDan Gohman } 991d934cb88SDan Gohman for (const WasmFunction &Func : Functions) { 992d934cb88SDan Gohman encodeULEB128(Func.Sym->getName().size(), getStream()); 993d934cb88SDan Gohman writeBytes(Func.Sym->getName()); 994d934cb88SDan Gohman 995d934cb88SDan Gohman // TODO: Local names. 996d934cb88SDan Gohman encodeULEB128(0, getStream()); // local count 997d934cb88SDan Gohman } 998d934cb88SDan Gohman 999d934cb88SDan Gohman endSection(Section); 1000d934cb88SDan Gohman } 1001d934cb88SDan Gohman 1002d934cb88SDan Gohman // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md 1003d934cb88SDan Gohman // for descriptions of the reloc sections. 1004d934cb88SDan Gohman 1005d934cb88SDan Gohman // === Code Reloc Section ==================================================== 1006d934cb88SDan Gohman if (!CodeRelocations.empty()) { 1007d934cb88SDan Gohman startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.CODE"); 1008d934cb88SDan Gohman 1009d934cb88SDan Gohman write8(wasm::WASM_SEC_CODE); 1010d934cb88SDan Gohman 1011d934cb88SDan Gohman encodeULEB128(CodeRelocations.size(), getStream()); 1012d934cb88SDan Gohman 1013d934cb88SDan Gohman WriteRelocations(CodeRelocations, getStream(), SymbolIndices); 1014d934cb88SDan Gohman 1015d934cb88SDan Gohman endSection(Section); 1016d934cb88SDan Gohman } 1017d934cb88SDan Gohman 1018d934cb88SDan Gohman // === Data Reloc Section ==================================================== 1019d934cb88SDan Gohman if (!DataRelocations.empty()) { 1020d934cb88SDan Gohman startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.DATA"); 1021d934cb88SDan Gohman 1022d934cb88SDan Gohman write8(wasm::WASM_SEC_DATA); 1023d934cb88SDan Gohman 1024d934cb88SDan Gohman encodeULEB128(DataRelocations.size(), getStream()); 1025d934cb88SDan Gohman 1026d934cb88SDan Gohman WriteRelocations(DataRelocations, getStream(), SymbolIndices); 1027d934cb88SDan Gohman 1028d934cb88SDan Gohman endSection(Section); 1029d934cb88SDan Gohman } 1030d934cb88SDan Gohman 1031d934cb88SDan Gohman // TODO: Translate the .comment section to the output. 1032d934cb88SDan Gohman 1033d934cb88SDan Gohman // TODO: Translate debug sections to the output. 103418eafb6cSDan Gohman } 103518eafb6cSDan Gohman 103618eafb6cSDan Gohman MCObjectWriter *llvm::createWasmObjectWriter(MCWasmObjectTargetWriter *MOTW, 103718eafb6cSDan Gohman raw_pwrite_stream &OS) { 103818eafb6cSDan Gohman return new WasmObjectWriter(MOTW, OS); 103918eafb6cSDan Gohman } 1040