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"
17432a3883SNico Weber #include "llvm/Config/llvm-config.h"
1818eafb6cSDan Gohman #include "llvm/MC/MCAsmBackend.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/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"
3418eafb6cSDan Gohman #include <vector>
3518eafb6cSDan Gohman 
3618eafb6cSDan Gohman using namespace llvm;
3718eafb6cSDan Gohman 
385e3d33a7SSam Clegg #define DEBUG_TYPE "mc"
3918eafb6cSDan Gohman 
40a165f2d6SSam Clegg static std::string toString(wasm::WasmSymbolType type) {
41a165f2d6SSam Clegg   switch (type) {
42a165f2d6SSam Clegg   case wasm::WASM_SYMBOL_TYPE_FUNCTION:
43a165f2d6SSam Clegg     return "WASM_SYMBOL_TYPE_FUNCTION";
44a165f2d6SSam Clegg   case wasm::WASM_SYMBOL_TYPE_GLOBAL:
45a165f2d6SSam Clegg     return "WASM_SYMBOL_TYPE_GLOBAL";
46a165f2d6SSam Clegg   case wasm::WASM_SYMBOL_TYPE_DATA:
47a165f2d6SSam Clegg     return "WASM_SYMBOL_TYPE_DATA";
48a165f2d6SSam Clegg   case wasm::WASM_SYMBOL_TYPE_SECTION:
49a165f2d6SSam Clegg     return "WASM_SYMBOL_TYPE_SECTION";
50a165f2d6SSam Clegg   }
51*ba4d85eeSFlorian Hahn   llvm_unreachable("unknown symbol type");
52a165f2d6SSam Clegg }
53a165f2d6SSam Clegg 
54a165f2d6SSam Clegg static std::string relocTypetoString(uint32_t type) {
55a165f2d6SSam Clegg   switch (type) {
56a165f2d6SSam Clegg #define WASM_RELOC(NAME, VALUE) case VALUE: return #NAME;
57a165f2d6SSam Clegg #include "llvm/BinaryFormat/WasmRelocs.def"
58a165f2d6SSam Clegg #undef WASM_RELOC
59a165f2d6SSam Clegg   default:
60a165f2d6SSam Clegg     llvm_unreachable("uknown reloc type");
61a165f2d6SSam Clegg   }
62a165f2d6SSam Clegg }
63a165f2d6SSam Clegg 
6418eafb6cSDan Gohman namespace {
659e15f359SSam Clegg 
6630e1bbc1SSam Clegg // Went we ceate the indirect function table we start at 1, so that there is
6730e1bbc1SSam Clegg // and emtpy slot at 0 and therefore calling a null function pointer will trap.
6830e1bbc1SSam Clegg static const uint32_t kInitialTableOffset = 1;
6930e1bbc1SSam Clegg 
70d934cb88SDan Gohman // For patching purposes, we need to remember where each section starts, both
71d934cb88SDan Gohman // for patching up the section size field, and for patching up references to
72d934cb88SDan Gohman // locations within the section.
73d934cb88SDan Gohman struct SectionBookkeeping {
74d934cb88SDan Gohman   // Where the size of the section is written.
75d934cb88SDan Gohman   uint64_t SizeOffset;
766a31a0d6SSam Clegg   // Where the section header ends (without custom section name).
776a31a0d6SSam Clegg   uint64_t PayloadOffset;
786a31a0d6SSam Clegg   // Where the contents of the section starts.
79d934cb88SDan Gohman   uint64_t ContentsOffset;
806f08c84aSSam Clegg   uint32_t Index;
81d934cb88SDan Gohman };
82d934cb88SDan Gohman 
839e15f359SSam Clegg // The signature of a wasm function, in a struct capable of being used as a
849e15f359SSam Clegg // DenseMap key.
859e15f359SSam Clegg struct WasmFunctionType {
869e15f359SSam Clegg   // Support empty and tombstone instances, needed by DenseMap.
879e15f359SSam Clegg   enum { Plain, Empty, Tombstone } State;
889e15f359SSam Clegg 
899e15f359SSam Clegg   // The return types of the function.
909e15f359SSam Clegg   SmallVector<wasm::ValType, 1> Returns;
919e15f359SSam Clegg 
929e15f359SSam Clegg   // The parameter types of the function.
939e15f359SSam Clegg   SmallVector<wasm::ValType, 4> Params;
949e15f359SSam Clegg 
959e15f359SSam Clegg   WasmFunctionType() : State(Plain) {}
969e15f359SSam Clegg 
979e15f359SSam Clegg   bool operator==(const WasmFunctionType &Other) const {
989e15f359SSam Clegg     return State == Other.State && Returns == Other.Returns &&
999e15f359SSam Clegg            Params == Other.Params;
1009e15f359SSam Clegg   }
1019e15f359SSam Clegg };
1029e15f359SSam Clegg 
1039e15f359SSam Clegg // Traits for using WasmFunctionType in a DenseMap.
1049e15f359SSam Clegg struct WasmFunctionTypeDenseMapInfo {
1059e15f359SSam Clegg   static WasmFunctionType getEmptyKey() {
1069e15f359SSam Clegg     WasmFunctionType FuncTy;
1079e15f359SSam Clegg     FuncTy.State = WasmFunctionType::Empty;
1089e15f359SSam Clegg     return FuncTy;
1099e15f359SSam Clegg   }
1109e15f359SSam Clegg   static WasmFunctionType getTombstoneKey() {
1119e15f359SSam Clegg     WasmFunctionType FuncTy;
1129e15f359SSam Clegg     FuncTy.State = WasmFunctionType::Tombstone;
1139e15f359SSam Clegg     return FuncTy;
1149e15f359SSam Clegg   }
1159e15f359SSam Clegg   static unsigned getHashValue(const WasmFunctionType &FuncTy) {
1169e15f359SSam Clegg     uintptr_t Value = FuncTy.State;
1179e15f359SSam Clegg     for (wasm::ValType Ret : FuncTy.Returns)
1189e15f359SSam Clegg       Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Ret));
1199e15f359SSam Clegg     for (wasm::ValType Param : FuncTy.Params)
1209e15f359SSam Clegg       Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Param));
1219e15f359SSam Clegg     return Value;
1229e15f359SSam Clegg   }
1239e15f359SSam Clegg   static bool isEqual(const WasmFunctionType &LHS,
1249e15f359SSam Clegg                       const WasmFunctionType &RHS) {
1259e15f359SSam Clegg     return LHS == RHS;
1269e15f359SSam Clegg   }
1279e15f359SSam Clegg };
1289e15f359SSam Clegg 
1297c395943SSam Clegg // A wasm data segment.  A wasm binary contains only a single data section
1307c395943SSam Clegg // but that can contain many segments, each with their own virtual location
1317c395943SSam Clegg // in memory.  Each MCSection data created by llvm is modeled as its own
1327c395943SSam Clegg // wasm data segment.
1337c395943SSam Clegg struct WasmDataSegment {
1347c395943SSam Clegg   MCSectionWasm *Section;
135d95ed959SSam Clegg   StringRef Name;
1367c395943SSam Clegg   uint32_t Offset;
13763ebb813SSam Clegg   uint32_t Alignment;
13863ebb813SSam Clegg   uint32_t Flags;
1397c395943SSam Clegg   SmallVector<char, 4> Data;
1407c395943SSam Clegg };
1417c395943SSam Clegg 
1429e15f359SSam Clegg // A wasm function to be written into the function section.
1439e15f359SSam Clegg struct WasmFunction {
1449e15f359SSam Clegg   int32_t Type;
1459e15f359SSam Clegg   const MCSymbolWasm *Sym;
1469e15f359SSam Clegg };
1479e15f359SSam Clegg 
1489e15f359SSam Clegg // A wasm global to be written into the global section.
1499e15f359SSam Clegg struct WasmGlobal {
1506e7f1826SSam Clegg   wasm::WasmGlobalType Type;
1519e15f359SSam Clegg   uint64_t InitialValue;
1529e15f359SSam Clegg };
1539e15f359SSam Clegg 
154ea7caceeSSam Clegg // Information about a single item which is part of a COMDAT.  For each data
155ea7caceeSSam Clegg // segment or function which is in the COMDAT, there is a corresponding
156ea7caceeSSam Clegg // WasmComdatEntry.
157ea7caceeSSam Clegg struct WasmComdatEntry {
158ea7caceeSSam Clegg   unsigned Kind;
159ea7caceeSSam Clegg   uint32_t Index;
160ea7caceeSSam Clegg };
161ea7caceeSSam Clegg 
1626dc65e91SSam Clegg // Information about a single relocation.
1636dc65e91SSam Clegg struct WasmRelocationEntry {
1646dc65e91SSam Clegg   uint64_t Offset;                  // Where is the relocation.
1656dc65e91SSam Clegg   const MCSymbolWasm *Symbol;       // The symbol to relocate with.
1666dc65e91SSam Clegg   int64_t Addend;                   // A value to add to the symbol.
1676dc65e91SSam Clegg   unsigned Type;                    // The type of the relocation.
168fe6414b0SSam Clegg   const MCSectionWasm *FixupSection;// The section the relocation is targeting.
1696dc65e91SSam Clegg 
1706dc65e91SSam Clegg   WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol,
1716dc65e91SSam Clegg                       int64_t Addend, unsigned Type,
172fe6414b0SSam Clegg                       const MCSectionWasm *FixupSection)
1736dc65e91SSam Clegg       : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type),
1746dc65e91SSam Clegg         FixupSection(FixupSection) {}
1756dc65e91SSam Clegg 
176acd7d2b0SSam Clegg   bool hasAddend() const {
177acd7d2b0SSam Clegg     switch (Type) {
17813a2e899SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
17913a2e899SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
18013a2e899SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
1816a31a0d6SSam Clegg     case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32:
1826a31a0d6SSam Clegg     case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32:
183acd7d2b0SSam Clegg       return true;
184acd7d2b0SSam Clegg     default:
185acd7d2b0SSam Clegg       return false;
186acd7d2b0SSam Clegg     }
187acd7d2b0SSam Clegg   }
188acd7d2b0SSam Clegg 
1896dc65e91SSam Clegg   void print(raw_ostream &Out) const {
190a165f2d6SSam Clegg     Out << relocTypetoString(Type)
191a165f2d6SSam Clegg         << " Off=" << Offset << ", Sym=" << *Symbol << ", Addend=" << Addend
192759631c7SSam Clegg         << ", FixupSection=" << FixupSection->getSectionName();
1936dc65e91SSam Clegg   }
194b7787fd0SSam Clegg 
195615eb470SAaron Ballman #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
196b7787fd0SSam Clegg   LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
197b7787fd0SSam Clegg #endif
1986dc65e91SSam Clegg };
1996dc65e91SSam Clegg 
200cfd44a2eSSam Clegg struct WasmCustomSection {
2016a31a0d6SSam Clegg   const uint32_t INVALID_INDEX = -1;
202cfd44a2eSSam Clegg 
2036a31a0d6SSam Clegg   StringRef Name;
2046a31a0d6SSam Clegg   MCSectionWasm *Section;
2056a31a0d6SSam Clegg 
2066a31a0d6SSam Clegg   uint32_t OutputContentsOffset;
2076a31a0d6SSam Clegg   uint32_t OutputIndex;
2086a31a0d6SSam Clegg 
2096a31a0d6SSam Clegg   WasmCustomSection(StringRef Name, MCSectionWasm *Section)
2106a31a0d6SSam Clegg       : Name(Name), Section(Section), OutputContentsOffset(0),
2116a31a0d6SSam Clegg         OutputIndex(INVALID_INDEX) {}
212cfd44a2eSSam Clegg };
213cfd44a2eSSam Clegg 
2141fb8daa6SSam Clegg #if !defined(NDEBUG)
2157f055deeSSam Clegg raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
216b7787fd0SSam Clegg   Rel.print(OS);
217b7787fd0SSam Clegg   return OS;
218b7787fd0SSam Clegg }
2191fb8daa6SSam Clegg #endif
220b7787fd0SSam Clegg 
22118eafb6cSDan Gohman class WasmObjectWriter : public MCObjectWriter {
22218eafb6cSDan Gohman   /// The target specific Wasm writer instance.
22318eafb6cSDan Gohman   std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
22418eafb6cSDan Gohman 
225d934cb88SDan Gohman   // Relocations for fixing up references in the code section.
226d934cb88SDan Gohman   std::vector<WasmRelocationEntry> CodeRelocations;
2276f08c84aSSam Clegg   uint32_t CodeSectionIndex;
228d934cb88SDan Gohman 
229d934cb88SDan Gohman   // Relocations for fixing up references in the data section.
230d934cb88SDan Gohman   std::vector<WasmRelocationEntry> DataRelocations;
2316f08c84aSSam Clegg   uint32_t DataSectionIndex;
232d934cb88SDan Gohman 
233d934cb88SDan Gohman   // Index values to use for fixing up call_indirect type indices.
234acd7d2b0SSam Clegg   // Maps function symbols to the index of the type of the function
235acd7d2b0SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
236d99f6078SSam Clegg   // Maps function symbols to the table element index space. Used
237d99f6078SSam Clegg   // for TABLE_INDEX relocation types (i.e. address taken functions).
238f9edbe95SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> TableIndices;
2396c899ba6SSam Clegg   // Maps function/global symbols to the (shared) Symbol index space.
240acd7d2b0SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> SymbolIndices;
241a165f2d6SSam Clegg   // Maps function/global symbols to the function/global/section index space.
2426c899ba6SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> WasmIndices;
2436c899ba6SSam Clegg   // Maps data symbols to the Wasm segment and offset/size with the segment.
2446c899ba6SSam Clegg   DenseMap<const MCSymbolWasm *, wasm::WasmDataReference> DataLocations;
2456a31a0d6SSam Clegg   // Maps section symbols to the section.
2466a31a0d6SSam Clegg   DenseMap<const MCSymbolWasm *, const MCSectionWasm *> CustomSectionSymbols;
2476a31a0d6SSam Clegg 
2486a31a0d6SSam Clegg   // Stores output data (index, relocations, content offset) for custom
2496a31a0d6SSam Clegg   // section.
2506a31a0d6SSam Clegg   std::vector<WasmCustomSection> CustomSections;
2516a31a0d6SSam Clegg   // Relocations for fixing up references in the custom sections.
2526a31a0d6SSam Clegg   DenseMap<const MCSectionWasm *, std::vector<WasmRelocationEntry>>
2536a31a0d6SSam Clegg       CustomSectionsRelocations;
254acd7d2b0SSam Clegg 
255acd7d2b0SSam Clegg   DenseMap<WasmFunctionType, int32_t, WasmFunctionTypeDenseMapInfo>
256acd7d2b0SSam Clegg       FunctionTypeIndices;
2575e3d33a7SSam Clegg   SmallVector<WasmFunctionType, 4> FunctionTypes;
2587c395943SSam Clegg   SmallVector<WasmGlobal, 4> Globals;
2596c899ba6SSam Clegg   SmallVector<WasmDataSegment, 4> DataSegments;
2609f3fe42eSSam Clegg   unsigned NumFunctionImports = 0;
2617c395943SSam Clegg   unsigned NumGlobalImports = 0;
2627e1c3345SChandler Carruth   uint32_t SectionCount = 0;
263d934cb88SDan Gohman 
26418eafb6cSDan Gohman   // TargetObjectWriter wrappers.
26518eafb6cSDan Gohman   bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
266ae03c1e7SSam Clegg   unsigned getRelocType(const MCValue &Target, const MCFixup &Fixup) const {
267ae03c1e7SSam Clegg     return TargetObjectWriter->getRelocType(Target, Fixup);
26818eafb6cSDan Gohman   }
26918eafb6cSDan Gohman 
2702322a937SSam Clegg   void startSection(SectionBookkeeping &Section, unsigned SectionId);
2712322a937SSam Clegg   void startCustomSection(SectionBookkeeping &Section, StringRef Name);
272d934cb88SDan Gohman   void endSection(SectionBookkeeping &Section);
273d934cb88SDan Gohman 
27418eafb6cSDan Gohman public:
2751301a878SLang Hames   WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
2761301a878SLang Hames                    raw_pwrite_stream &OS)
2771301a878SLang Hames       : MCObjectWriter(OS, /*IsLittleEndian=*/true),
2781301a878SLang Hames         TargetObjectWriter(std::move(MOTW)) {}
27918eafb6cSDan Gohman 
28018eafb6cSDan Gohman   ~WasmObjectWriter() override;
28118eafb6cSDan Gohman 
2820917c9e4SDan Gohman private:
283acd7d2b0SSam Clegg   void reset() override {
284acd7d2b0SSam Clegg     CodeRelocations.clear();
285acd7d2b0SSam Clegg     DataRelocations.clear();
286acd7d2b0SSam Clegg     TypeIndices.clear();
287acd7d2b0SSam Clegg     SymbolIndices.clear();
2886c899ba6SSam Clegg     WasmIndices.clear();
289f9edbe95SSam Clegg     TableIndices.clear();
2906c899ba6SSam Clegg     DataLocations.clear();
2916a31a0d6SSam Clegg     CustomSectionsRelocations.clear();
292acd7d2b0SSam Clegg     FunctionTypeIndices.clear();
2935e3d33a7SSam Clegg     FunctionTypes.clear();
2947c395943SSam Clegg     Globals.clear();
2956c899ba6SSam Clegg     DataSegments.clear();
2966a31a0d6SSam Clegg     CustomSectionSymbols.clear();
297acd7d2b0SSam Clegg     MCObjectWriter::reset();
2989f3fe42eSSam Clegg     NumFunctionImports = 0;
2997c395943SSam Clegg     NumGlobalImports = 0;
300acd7d2b0SSam Clegg   }
301acd7d2b0SSam Clegg 
30218eafb6cSDan Gohman   void writeHeader(const MCAssembler &Asm);
30318eafb6cSDan Gohman 
30418eafb6cSDan Gohman   void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
30518eafb6cSDan Gohman                         const MCFragment *Fragment, const MCFixup &Fixup,
306ceecfe5bSRafael Espindola                         MCValue Target, uint64_t &FixedValue) override;
30718eafb6cSDan Gohman 
30818eafb6cSDan Gohman   void executePostLayoutBinding(MCAssembler &Asm,
30918eafb6cSDan Gohman                                 const MCAsmLayout &Layout) override;
31018eafb6cSDan Gohman 
31118eafb6cSDan Gohman   void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
3129e15f359SSam Clegg 
313b7787fd0SSam Clegg   void writeString(const StringRef Str) {
314b7787fd0SSam Clegg     encodeULEB128(Str.size(), getStream());
315b7787fd0SSam Clegg     writeBytes(Str);
316b7787fd0SSam Clegg   }
317b7787fd0SSam Clegg 
3189e15f359SSam Clegg   void writeValueType(wasm::ValType Ty) {
31903e101f1SSam Clegg     write8(static_cast<uint8_t>(Ty));
3209e15f359SSam Clegg   }
3219e15f359SSam Clegg 
322457fb0b4SSam Clegg   void writeTypeSection(ArrayRef<WasmFunctionType> FunctionTypes);
3238defa952SSam Clegg   void writeImportSection(ArrayRef<wasm::WasmImport> Imports, uint32_t DataSize,
324f950b24aSSam Clegg                           uint32_t NumElements);
325457fb0b4SSam Clegg   void writeFunctionSection(ArrayRef<WasmFunction> Functions);
3267c395943SSam Clegg   void writeGlobalSection();
3278defa952SSam Clegg   void writeExportSection(ArrayRef<wasm::WasmExport> Exports);
328457fb0b4SSam Clegg   void writeElemSection(ArrayRef<uint32_t> TableElems);
3299e15f359SSam Clegg   void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
330457fb0b4SSam Clegg                         ArrayRef<WasmFunction> Functions);
3316c899ba6SSam Clegg   void writeDataSection();
3326f08c84aSSam Clegg   void writeRelocSection(uint32_t SectionIndex, StringRef Name,
3336f08c84aSSam Clegg                          ArrayRef<WasmRelocationEntry> Relocations);
33431a2c809SSam Clegg   void writeLinkingMetaDataSection(
33586b4a09aSSam Clegg       ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
336ea7caceeSSam Clegg       ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
337ea7caceeSSam Clegg       const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats);
3386a31a0d6SSam Clegg   void writeCustomSections(const MCAssembler &Asm, const MCAsmLayout &Layout);
3396a31a0d6SSam Clegg   void writeCustomRelocSections();
3406a31a0d6SSam Clegg   void
3416a31a0d6SSam Clegg   updateCustomSectionRelocations(const SmallVector<WasmFunction, 4> &Functions,
3426a31a0d6SSam Clegg                                  const MCAsmLayout &Layout);
343acd7d2b0SSam Clegg 
3447c395943SSam Clegg   uint32_t getProvisionalValue(const WasmRelocationEntry &RelEntry);
345acd7d2b0SSam Clegg   void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
346acd7d2b0SSam Clegg                         uint64_t ContentsOffset);
347acd7d2b0SSam Clegg 
348acd7d2b0SSam Clegg   uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
3495e3d33a7SSam Clegg   uint32_t getFunctionType(const MCSymbolWasm &Symbol);
3505e3d33a7SSam Clegg   uint32_t registerFunctionType(const MCSymbolWasm &Symbol);
35118eafb6cSDan Gohman };
3529e15f359SSam Clegg 
35318eafb6cSDan Gohman } // end anonymous namespace
35418eafb6cSDan Gohman 
35518eafb6cSDan Gohman WasmObjectWriter::~WasmObjectWriter() {}
35618eafb6cSDan Gohman 
357d934cb88SDan Gohman // Write out a section header and a patchable section size field.
358d934cb88SDan Gohman void WasmObjectWriter::startSection(SectionBookkeeping &Section,
3592322a937SSam Clegg                                     unsigned SectionId) {
3602322a937SSam Clegg   DEBUG(dbgs() << "startSection " << SectionId << "\n");
36103e101f1SSam Clegg   write8(SectionId);
362d934cb88SDan Gohman 
363d934cb88SDan Gohman   Section.SizeOffset = getStream().tell();
364d934cb88SDan Gohman 
365d934cb88SDan Gohman   // The section size. We don't know the size yet, so reserve enough space
366d934cb88SDan Gohman   // for any 32-bit value; we'll patch it later.
367d934cb88SDan Gohman   encodeULEB128(UINT32_MAX, getStream());
368d934cb88SDan Gohman 
369d934cb88SDan Gohman   // The position where the section starts, for measuring its size.
370d934cb88SDan Gohman   Section.ContentsOffset = getStream().tell();
3716a31a0d6SSam Clegg   Section.PayloadOffset = getStream().tell();
3726f08c84aSSam Clegg   Section.Index = SectionCount++;
373d934cb88SDan Gohman }
3742322a937SSam Clegg 
3752322a937SSam Clegg void WasmObjectWriter::startCustomSection(SectionBookkeeping &Section,
3762322a937SSam Clegg                                           StringRef Name) {
3772322a937SSam Clegg   DEBUG(dbgs() << "startCustomSection " << Name << "\n");
3782322a937SSam Clegg   startSection(Section, wasm::WASM_SEC_CUSTOM);
3796a31a0d6SSam Clegg 
3806a31a0d6SSam Clegg   // The position where the section header ends, for measuring its size.
3816a31a0d6SSam Clegg   Section.PayloadOffset = getStream().tell();
3826a31a0d6SSam Clegg 
3832322a937SSam Clegg   // Custom sections in wasm also have a string identifier.
3842322a937SSam Clegg   writeString(Name);
3856a31a0d6SSam Clegg 
3866a31a0d6SSam Clegg   // The position where the custom section starts.
3876a31a0d6SSam Clegg   Section.ContentsOffset = getStream().tell();
388d934cb88SDan Gohman }
389d934cb88SDan Gohman 
390d934cb88SDan Gohman // Now that the section is complete and we know how big it is, patch up the
391d934cb88SDan Gohman // section size field at the start of the section.
392d934cb88SDan Gohman void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
3936a31a0d6SSam Clegg   uint64_t Size = getStream().tell() - Section.PayloadOffset;
394d934cb88SDan Gohman   if (uint32_t(Size) != Size)
395d934cb88SDan Gohman     report_fatal_error("section size does not fit in a uint32_t");
396d934cb88SDan Gohman 
397b7787fd0SSam Clegg   DEBUG(dbgs() << "endSection size=" << Size << "\n");
398d934cb88SDan Gohman 
399d934cb88SDan Gohman   // Write the final section size to the payload_len field, which follows
400d934cb88SDan Gohman   // the section id byte.
401d934cb88SDan Gohman   uint8_t Buffer[16];
40266a99e41SSam Clegg   unsigned SizeLen = encodeULEB128(Size, Buffer, 5);
403d934cb88SDan Gohman   assert(SizeLen == 5);
404d934cb88SDan Gohman   getStream().pwrite((char *)Buffer, SizeLen, Section.SizeOffset);
405d934cb88SDan Gohman }
406d934cb88SDan Gohman 
40718eafb6cSDan Gohman // Emit the Wasm header.
40818eafb6cSDan Gohman void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
4097ea5adffSDan Gohman   writeBytes(StringRef(wasm::WasmMagic, sizeof(wasm::WasmMagic)));
4107ea5adffSDan Gohman   writeLE32(wasm::WasmVersion);
41118eafb6cSDan Gohman }
41218eafb6cSDan Gohman 
41318eafb6cSDan Gohman void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
41418eafb6cSDan Gohman                                                 const MCAsmLayout &Layout) {
41518eafb6cSDan Gohman }
41618eafb6cSDan Gohman 
41718eafb6cSDan Gohman void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
41818eafb6cSDan Gohman                                         const MCAsmLayout &Layout,
41918eafb6cSDan Gohman                                         const MCFragment *Fragment,
42018eafb6cSDan Gohman                                         const MCFixup &Fixup, MCValue Target,
421ceecfe5bSRafael Espindola                                         uint64_t &FixedValue) {
422ceecfe5bSRafael Espindola   MCAsmBackend &Backend = Asm.getBackend();
423ceecfe5bSRafael Espindola   bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
424ceecfe5bSRafael Espindola                  MCFixupKindInfo::FKF_IsPCRel;
425fe6414b0SSam Clegg   const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
426d934cb88SDan Gohman   uint64_t C = Target.getConstant();
427d934cb88SDan Gohman   uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
428d934cb88SDan Gohman   MCContext &Ctx = Asm.getContext();
429d934cb88SDan Gohman 
430bafe6902SSam Clegg   // The .init_array isn't translated as data, so don't do relocations in it.
431bafe6902SSam Clegg   if (FixupSection.getSectionName().startswith(".init_array"))
432bafe6902SSam Clegg     return;
433bafe6902SSam Clegg 
4346a31a0d6SSam Clegg   // TODO: Add support for non-debug metadata sections?
4356a31a0d6SSam Clegg   if (FixupSection.getKind().isMetadata() &&
4366a31a0d6SSam Clegg       !FixupSection.getSectionName().startswith(".debug_"))
437b7a5469cSSam Clegg     return;
438b7a5469cSSam Clegg 
439d934cb88SDan Gohman   if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
440d934cb88SDan Gohman     assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
441d934cb88SDan Gohman            "Should not have constructed this");
442d934cb88SDan Gohman 
443d934cb88SDan Gohman     // Let A, B and C being the components of Target and R be the location of
444d934cb88SDan Gohman     // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
445d934cb88SDan Gohman     // If it is pcrel, we want to compute (A - B + C - R).
446d934cb88SDan Gohman 
447d934cb88SDan Gohman     // In general, Wasm has no relocations for -B. It can only represent (A + C)
448d934cb88SDan Gohman     // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
449d934cb88SDan Gohman     // replace B to implement it: (A - R - K + C)
450d934cb88SDan Gohman     if (IsPCRel) {
451d934cb88SDan Gohman       Ctx.reportError(
452d934cb88SDan Gohman           Fixup.getLoc(),
453d934cb88SDan Gohman           "No relocation available to represent this relative expression");
454d934cb88SDan Gohman       return;
455d934cb88SDan Gohman     }
456d934cb88SDan Gohman 
457d934cb88SDan Gohman     const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
458d934cb88SDan Gohman 
459d934cb88SDan Gohman     if (SymB.isUndefined()) {
460d934cb88SDan Gohman       Ctx.reportError(Fixup.getLoc(),
461d934cb88SDan Gohman                       Twine("symbol '") + SymB.getName() +
462d934cb88SDan Gohman                           "' can not be undefined in a subtraction expression");
463d934cb88SDan Gohman       return;
464d934cb88SDan Gohman     }
465d934cb88SDan Gohman 
466d934cb88SDan Gohman     assert(!SymB.isAbsolute() && "Should have been folded");
467d934cb88SDan Gohman     const MCSection &SecB = SymB.getSection();
468d934cb88SDan Gohman     if (&SecB != &FixupSection) {
469d934cb88SDan Gohman       Ctx.reportError(Fixup.getLoc(),
470d934cb88SDan Gohman                       "Cannot represent a difference across sections");
471d934cb88SDan Gohman       return;
472d934cb88SDan Gohman     }
473d934cb88SDan Gohman 
474d934cb88SDan Gohman     uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
475d934cb88SDan Gohman     uint64_t K = SymBOffset - FixupOffset;
476d934cb88SDan Gohman     IsPCRel = true;
477d934cb88SDan Gohman     C -= K;
478d934cb88SDan Gohman   }
479d934cb88SDan Gohman 
480d934cb88SDan Gohman   // We either rejected the fixup or folded B into C at this point.
481d934cb88SDan Gohman   const MCSymbolRefExpr *RefA = Target.getSymA();
482d934cb88SDan Gohman   const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr;
483d934cb88SDan Gohman 
484d934cb88SDan Gohman   if (SymA && SymA->isVariable()) {
485d934cb88SDan Gohman     const MCExpr *Expr = SymA->getVariableValue();
4866ad8f190SSam Clegg     const auto *Inner = cast<MCSymbolRefExpr>(Expr);
4876ad8f190SSam Clegg     if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
4886ad8f190SSam Clegg       llvm_unreachable("weakref used in reloc not yet implemented");
489d934cb88SDan Gohman   }
490d934cb88SDan Gohman 
491d934cb88SDan Gohman   // Put any constant offset in an addend. Offsets can be negative, and
492d934cb88SDan Gohman   // LLVM expects wrapping, in contrast to wasm's immediates which can't
493d934cb88SDan Gohman   // be negative and don't wrap.
494d934cb88SDan Gohman   FixedValue = 0;
495d934cb88SDan Gohman 
4966ad8f190SSam Clegg   if (SymA)
497d934cb88SDan Gohman     SymA->setUsedInReloc();
498d934cb88SDan Gohman 
499ae03c1e7SSam Clegg   assert(!IsPCRel);
5009d24fb7fSSam Clegg   assert(SymA);
5019d24fb7fSSam Clegg 
502ae03c1e7SSam Clegg   unsigned Type = getRelocType(Target, Fixup);
503ae03c1e7SSam Clegg 
504d934cb88SDan Gohman   WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
505b7787fd0SSam Clegg   DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
506d934cb88SDan Gohman 
5076a31a0d6SSam Clegg   // Relocation other than R_WEBASSEMBLY_TYPE_INDEX_LEB,
5086a31a0d6SSam Clegg   // R_WEBASSEMBLY_SECTION_OFFSET_I32 or R_WEBASSEMBLY_FUNCTION_OFFSET_I32
5096a31a0d6SSam Clegg   // are currently required to be against a named symbol.
510b7a5469cSSam Clegg   // TODO(sbc): Add support for relocations against unnamed temporaries such
511b7a5469cSSam Clegg   // as those generated by llvm's `blockaddress`.
512b7a5469cSSam Clegg   // See: test/MC/WebAssembly/blockaddress.ll
5136a31a0d6SSam Clegg   if (SymA->getName().empty() &&
5146a31a0d6SSam Clegg       !(Type == wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB ||
5156a31a0d6SSam Clegg         Type == wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32 ||
5166a31a0d6SSam Clegg         Type == wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32))
517b7a5469cSSam Clegg     report_fatal_error("relocations against un-named temporaries are not yet "
518b7a5469cSSam Clegg                        "supported by wasm");
519b7a5469cSSam Clegg 
5206a31a0d6SSam Clegg   if (FixupSection.isWasmData()) {
521d934cb88SDan Gohman     DataRelocations.push_back(Rec);
5226a31a0d6SSam Clegg   } else if (FixupSection.getKind().isText()) {
52312fd3da9SSam Clegg     CodeRelocations.push_back(Rec);
5246a31a0d6SSam Clegg   } else if (FixupSection.getKind().isMetadata()) {
5256a31a0d6SSam Clegg     assert(FixupSection.getSectionName().startswith(".debug_"));
5266a31a0d6SSam Clegg     CustomSectionsRelocations[&FixupSection].push_back(Rec);
5276a31a0d6SSam Clegg   } else {
52812fd3da9SSam Clegg     llvm_unreachable("unexpected section type");
529d934cb88SDan Gohman   }
5306a31a0d6SSam Clegg }
531d934cb88SDan Gohman 
532d934cb88SDan Gohman // Write X as an (unsigned) LEB value at offset Offset in Stream, padded
533d934cb88SDan Gohman // to allow patching.
534d934cb88SDan Gohman static void
535d934cb88SDan Gohman WritePatchableLEB(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
536d934cb88SDan Gohman   uint8_t Buffer[5];
53766a99e41SSam Clegg   unsigned SizeLen = encodeULEB128(X, Buffer, 5);
538d934cb88SDan Gohman   assert(SizeLen == 5);
539d934cb88SDan Gohman   Stream.pwrite((char *)Buffer, SizeLen, Offset);
540d934cb88SDan Gohman }
541d934cb88SDan Gohman 
542d934cb88SDan Gohman // Write X as an signed LEB value at offset Offset in Stream, padded
543d934cb88SDan Gohman // to allow patching.
544d934cb88SDan Gohman static void
545d934cb88SDan Gohman WritePatchableSLEB(raw_pwrite_stream &Stream, int32_t X, uint64_t Offset) {
546d934cb88SDan Gohman   uint8_t Buffer[5];
54766a99e41SSam Clegg   unsigned SizeLen = encodeSLEB128(X, Buffer, 5);
548d934cb88SDan Gohman   assert(SizeLen == 5);
549d934cb88SDan Gohman   Stream.pwrite((char *)Buffer, SizeLen, Offset);
550d934cb88SDan Gohman }
551d934cb88SDan Gohman 
552d934cb88SDan Gohman // Write X as a plain integer value at offset Offset in Stream.
553d934cb88SDan Gohman static void WriteI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
554d934cb88SDan Gohman   uint8_t Buffer[4];
555d934cb88SDan Gohman   support::endian::write32le(Buffer, X);
556d934cb88SDan Gohman   Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
557d934cb88SDan Gohman }
558d934cb88SDan Gohman 
559aff1c4dfSSam Clegg static const MCSymbolWasm* ResolveSymbol(const MCSymbolWasm& Symbol) {
560aff1c4dfSSam Clegg   if (Symbol.isVariable()) {
561aff1c4dfSSam Clegg     const MCExpr *Expr = Symbol.getVariableValue();
562aff1c4dfSSam Clegg     auto *Inner = cast<MCSymbolRefExpr>(Expr);
563aff1c4dfSSam Clegg     return cast<MCSymbolWasm>(&Inner->getSymbol());
564aff1c4dfSSam Clegg   }
565aff1c4dfSSam Clegg   return &Symbol;
566aff1c4dfSSam Clegg }
567aff1c4dfSSam Clegg 
568d934cb88SDan Gohman // Compute a value to write into the code at the location covered
56960ec3034SSam Clegg // by RelEntry. This value isn't used by the static linker; it just serves
57060ec3034SSam Clegg // to make the object format more readable and more likely to be directly
57160ec3034SSam Clegg // useable.
5727c395943SSam Clegg uint32_t
5737c395943SSam Clegg WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) {
57460ec3034SSam Clegg   switch (RelEntry.Type) {
57560ec3034SSam Clegg   case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
576f9edbe95SSam Clegg   case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: {
577f9edbe95SSam Clegg     // Provisional value is table address of the resolved symbol itself
578f9edbe95SSam Clegg     const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
579f9edbe95SSam Clegg     assert(Sym->isFunction());
580f9edbe95SSam Clegg     return TableIndices[Sym];
581f9edbe95SSam Clegg   }
58260ec3034SSam Clegg   case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
5836c899ba6SSam Clegg     // Provisional value is same as the index
58460ec3034SSam Clegg     return getRelocationIndexValue(RelEntry);
5856c899ba6SSam Clegg   case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
5866c899ba6SSam Clegg   case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
5876c899ba6SSam Clegg     // Provisional value is function/global Wasm index
5886c899ba6SSam Clegg     if (!WasmIndices.count(RelEntry.Symbol))
5896c899ba6SSam Clegg       report_fatal_error("symbol not found in wasm index space: " +
5906c899ba6SSam Clegg                          RelEntry.Symbol->getName());
5916c899ba6SSam Clegg     return WasmIndices[RelEntry.Symbol];
5926a31a0d6SSam Clegg   case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32: {
5936a31a0d6SSam Clegg     const auto &Section =
5946a31a0d6SSam Clegg         static_cast<const MCSectionWasm &>(RelEntry.Symbol->getSection());
5956a31a0d6SSam Clegg     return Section.getSectionOffset() + RelEntry.Addend;
5966a31a0d6SSam Clegg   }
5976a31a0d6SSam Clegg   case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32: {
5986a31a0d6SSam Clegg     const auto &Section = *CustomSectionSymbols.find(RelEntry.Symbol)->second;
5996a31a0d6SSam Clegg     return Section.getSectionOffset() + RelEntry.Addend;
6006a31a0d6SSam Clegg   }
60160ec3034SSam Clegg   case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
60260ec3034SSam Clegg   case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
60360ec3034SSam Clegg   case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: {
604f9edbe95SSam Clegg     // Provisional value is address of the global
60560ec3034SSam Clegg     const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
606270ed1b3SSam Clegg     // For undefined symbols, use zero
607cd65f698SSam Clegg     if (!Sym->isDefined())
608270ed1b3SSam Clegg       return 0;
6096c899ba6SSam Clegg     const wasm::WasmDataReference &Ref = DataLocations[Sym];
6106c899ba6SSam Clegg     const WasmDataSegment &Segment = DataSegments[Ref.Segment];
611d934cb88SDan Gohman     // Ignore overflow. LLVM allows address arithmetic to silently wrap.
6126c899ba6SSam Clegg     return Segment.Offset + Ref.Offset + RelEntry.Addend;
61360ec3034SSam Clegg   }
61460ec3034SSam Clegg   default:
61560ec3034SSam Clegg     llvm_unreachable("invalid relocation type");
61660ec3034SSam Clegg   }
617d934cb88SDan Gohman }
618d934cb88SDan Gohman 
619759631c7SSam Clegg static void addData(SmallVectorImpl<char> &DataBytes,
62063ebb813SSam Clegg                     MCSectionWasm &DataSection) {
621759631c7SSam Clegg   DEBUG(errs() << "addData: " << DataSection.getSectionName() << "\n");
622759631c7SSam Clegg 
62363ebb813SSam Clegg   DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
62463ebb813SSam Clegg 
625759631c7SSam Clegg   for (const MCFragment &Frag : DataSection) {
626759631c7SSam Clegg     if (Frag.hasInstructions())
627759631c7SSam Clegg       report_fatal_error("only data supported in data sections");
628759631c7SSam Clegg 
629759631c7SSam Clegg     if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
630759631c7SSam Clegg       if (Align->getValueSize() != 1)
631759631c7SSam Clegg         report_fatal_error("only byte values supported for alignment");
632759631c7SSam Clegg       // If nops are requested, use zeros, as this is the data section.
633759631c7SSam Clegg       uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
634759631c7SSam Clegg       uint64_t Size = std::min<uint64_t>(alignTo(DataBytes.size(),
635759631c7SSam Clegg                                                  Align->getAlignment()),
636759631c7SSam Clegg                                          DataBytes.size() +
637759631c7SSam Clegg                                              Align->getMaxBytesToEmit());
638759631c7SSam Clegg       DataBytes.resize(Size, Value);
639759631c7SSam Clegg     } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
640d707c370SRafael Espindola       int64_t Size;
641d707c370SRafael Espindola       if (!Fill->getSize().evaluateAsAbsolute(Size))
642d707c370SRafael Espindola         llvm_unreachable("The fill should be an assembler constant");
643d707c370SRafael Espindola       DataBytes.insert(DataBytes.end(), Size, Fill->getValue());
644759631c7SSam Clegg     } else {
645759631c7SSam Clegg       const auto &DataFrag = cast<MCDataFragment>(Frag);
646759631c7SSam Clegg       const SmallVectorImpl<char> &Contents = DataFrag.getContents();
647759631c7SSam Clegg 
648759631c7SSam Clegg       DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
649759631c7SSam Clegg     }
650759631c7SSam Clegg   }
651759631c7SSam Clegg 
652759631c7SSam Clegg   DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
653759631c7SSam Clegg }
654759631c7SSam Clegg 
65560ec3034SSam Clegg uint32_t
65660ec3034SSam Clegg WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
65760ec3034SSam Clegg   if (RelEntry.Type == wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB) {
658b7787fd0SSam Clegg     if (!TypeIndices.count(RelEntry.Symbol))
659b7787fd0SSam Clegg       report_fatal_error("symbol not found in type index space: " +
660b7787fd0SSam Clegg                          RelEntry.Symbol->getName());
661acd7d2b0SSam Clegg     return TypeIndices[RelEntry.Symbol];
662acd7d2b0SSam Clegg   }
66360ec3034SSam Clegg 
66460ec3034SSam Clegg   if (!SymbolIndices.count(RelEntry.Symbol))
6656c899ba6SSam Clegg     report_fatal_error("symbol not found in symbol index space: " +
66660ec3034SSam Clegg                        RelEntry.Symbol->getName());
66760ec3034SSam Clegg   return SymbolIndices[RelEntry.Symbol];
668acd7d2b0SSam Clegg }
669acd7d2b0SSam Clegg 
670d934cb88SDan Gohman // Apply the portions of the relocation records that we can handle ourselves
671d934cb88SDan Gohman // directly.
672acd7d2b0SSam Clegg void WasmObjectWriter::applyRelocations(
673acd7d2b0SSam Clegg     ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
674acd7d2b0SSam Clegg   raw_pwrite_stream &Stream = getStream();
675d934cb88SDan Gohman   for (const WasmRelocationEntry &RelEntry : Relocations) {
676d934cb88SDan Gohman     uint64_t Offset = ContentsOffset +
677d934cb88SDan Gohman                       RelEntry.FixupSection->getSectionOffset() +
678d934cb88SDan Gohman                       RelEntry.Offset;
679d934cb88SDan Gohman 
680b7787fd0SSam Clegg     DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
68160ec3034SSam Clegg     uint32_t Value = getProvisionalValue(RelEntry);
68260ec3034SSam Clegg 
683acd7d2b0SSam Clegg     switch (RelEntry.Type) {
684acd7d2b0SSam Clegg     case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
6859d24fb7fSSam Clegg     case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
68660ec3034SSam Clegg     case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
68760ec3034SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
688d934cb88SDan Gohman       WritePatchableLEB(Stream, Value, Offset);
689d934cb88SDan Gohman       break;
69060ec3034SSam Clegg     case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
69160ec3034SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
6926a31a0d6SSam Clegg     case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32:
6936a31a0d6SSam Clegg     case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32:
694d934cb88SDan Gohman       WriteI32(Stream, Value, Offset);
695d934cb88SDan Gohman       break;
69660ec3034SSam Clegg     case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
69760ec3034SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
69860ec3034SSam Clegg       WritePatchableSLEB(Stream, Value, Offset);
69960ec3034SSam Clegg       break;
700d934cb88SDan Gohman     default:
7019d24fb7fSSam Clegg       llvm_unreachable("invalid relocation type");
702d934cb88SDan Gohman     }
703d934cb88SDan Gohman   }
70418eafb6cSDan Gohman }
70518eafb6cSDan Gohman 
7069e15f359SSam Clegg void WasmObjectWriter::writeTypeSection(
707457fb0b4SSam Clegg     ArrayRef<WasmFunctionType> FunctionTypes) {
7089e15f359SSam Clegg   if (FunctionTypes.empty())
7099e15f359SSam Clegg     return;
7109e15f359SSam Clegg 
7119e15f359SSam Clegg   SectionBookkeeping Section;
7129e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_TYPE);
7139e15f359SSam Clegg 
7149e15f359SSam Clegg   encodeULEB128(FunctionTypes.size(), getStream());
7159e15f359SSam Clegg 
7169e15f359SSam Clegg   for (const WasmFunctionType &FuncTy : FunctionTypes) {
71703e101f1SSam Clegg     write8(wasm::WASM_TYPE_FUNC);
7189e15f359SSam Clegg     encodeULEB128(FuncTy.Params.size(), getStream());
7199e15f359SSam Clegg     for (wasm::ValType Ty : FuncTy.Params)
7209e15f359SSam Clegg       writeValueType(Ty);
7219e15f359SSam Clegg     encodeULEB128(FuncTy.Returns.size(), getStream());
7229e15f359SSam Clegg     for (wasm::ValType Ty : FuncTy.Returns)
7239e15f359SSam Clegg       writeValueType(Ty);
7249e15f359SSam Clegg   }
7259e15f359SSam Clegg 
7269e15f359SSam Clegg   endSection(Section);
7279e15f359SSam Clegg }
7289e15f359SSam Clegg 
7298defa952SSam Clegg void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports,
730f950b24aSSam Clegg                                           uint32_t DataSize,
731f950b24aSSam Clegg                                           uint32_t NumElements) {
7329e15f359SSam Clegg   if (Imports.empty())
7339e15f359SSam Clegg     return;
7349e15f359SSam Clegg 
735f950b24aSSam Clegg   uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
736f950b24aSSam Clegg 
7379e15f359SSam Clegg   SectionBookkeeping Section;
7389e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_IMPORT);
7399e15f359SSam Clegg 
7409e15f359SSam Clegg   encodeULEB128(Imports.size(), getStream());
7418defa952SSam Clegg   for (const wasm::WasmImport &Import : Imports) {
7428defa952SSam Clegg     writeString(Import.Module);
7438defa952SSam Clegg     writeString(Import.Field);
74403e101f1SSam Clegg     write8(Import.Kind);
7459e15f359SSam Clegg 
7469e15f359SSam Clegg     switch (Import.Kind) {
7479e15f359SSam Clegg     case wasm::WASM_EXTERNAL_FUNCTION:
7488defa952SSam Clegg       encodeULEB128(Import.SigIndex, getStream());
7499e15f359SSam Clegg       break;
7509e15f359SSam Clegg     case wasm::WASM_EXTERNAL_GLOBAL:
75103e101f1SSam Clegg       write8(Import.Global.Type);
75203e101f1SSam Clegg       write8(Import.Global.Mutable ? 1 : 0);
7539e15f359SSam Clegg       break;
754f950b24aSSam Clegg     case wasm::WASM_EXTERNAL_MEMORY:
755f950b24aSSam Clegg       encodeULEB128(0, getStream()); // flags
756f950b24aSSam Clegg       encodeULEB128(NumPages, getStream()); // initial
757f950b24aSSam Clegg       break;
758f950b24aSSam Clegg     case wasm::WASM_EXTERNAL_TABLE:
75903e101f1SSam Clegg       write8(Import.Table.ElemType);
760f950b24aSSam Clegg       encodeULEB128(0, getStream()); // flags
761f950b24aSSam Clegg       encodeULEB128(NumElements, getStream()); // initial
762f950b24aSSam Clegg       break;
7639e15f359SSam Clegg     default:
7649e15f359SSam Clegg       llvm_unreachable("unsupported import kind");
7659e15f359SSam Clegg     }
7669e15f359SSam Clegg   }
7679e15f359SSam Clegg 
7689e15f359SSam Clegg   endSection(Section);
7699e15f359SSam Clegg }
7709e15f359SSam Clegg 
771457fb0b4SSam Clegg void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
7729e15f359SSam Clegg   if (Functions.empty())
7739e15f359SSam Clegg     return;
7749e15f359SSam Clegg 
7759e15f359SSam Clegg   SectionBookkeeping Section;
7769e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_FUNCTION);
7779e15f359SSam Clegg 
7789e15f359SSam Clegg   encodeULEB128(Functions.size(), getStream());
7799e15f359SSam Clegg   for (const WasmFunction &Func : Functions)
7809e15f359SSam Clegg     encodeULEB128(Func.Type, getStream());
7819e15f359SSam Clegg 
7829e15f359SSam Clegg   endSection(Section);
7839e15f359SSam Clegg }
7849e15f359SSam Clegg 
7857c395943SSam Clegg void WasmObjectWriter::writeGlobalSection() {
7869e15f359SSam Clegg   if (Globals.empty())
7879e15f359SSam Clegg     return;
7889e15f359SSam Clegg 
7899e15f359SSam Clegg   SectionBookkeeping Section;
7909e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_GLOBAL);
7919e15f359SSam Clegg 
7929e15f359SSam Clegg   encodeULEB128(Globals.size(), getStream());
7939e15f359SSam Clegg   for (const WasmGlobal &Global : Globals) {
7946e7f1826SSam Clegg     writeValueType(static_cast<wasm::ValType>(Global.Type.Type));
7956e7f1826SSam Clegg     write8(Global.Type.Mutable);
7969e15f359SSam Clegg 
7979e15f359SSam Clegg     write8(wasm::WASM_OPCODE_I32_CONST);
7986e7f1826SSam Clegg     encodeSLEB128(Global.InitialValue, getStream());
7999e15f359SSam Clegg     write8(wasm::WASM_OPCODE_END);
8009e15f359SSam Clegg   }
8019e15f359SSam Clegg 
8029e15f359SSam Clegg   endSection(Section);
8039e15f359SSam Clegg }
8049e15f359SSam Clegg 
8058defa952SSam Clegg void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) {
8069e15f359SSam Clegg   if (Exports.empty())
8079e15f359SSam Clegg     return;
8089e15f359SSam Clegg 
8099e15f359SSam Clegg   SectionBookkeeping Section;
8109e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_EXPORT);
8119e15f359SSam Clegg 
8129e15f359SSam Clegg   encodeULEB128(Exports.size(), getStream());
8138defa952SSam Clegg   for (const wasm::WasmExport &Export : Exports) {
8148defa952SSam Clegg     writeString(Export.Name);
81503e101f1SSam Clegg     write8(Export.Kind);
8169e15f359SSam Clegg     encodeULEB128(Export.Index, getStream());
8179e15f359SSam Clegg   }
8189e15f359SSam Clegg 
8199e15f359SSam Clegg   endSection(Section);
8209e15f359SSam Clegg }
8219e15f359SSam Clegg 
822457fb0b4SSam Clegg void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
8239e15f359SSam Clegg   if (TableElems.empty())
8249e15f359SSam Clegg     return;
8259e15f359SSam Clegg 
8269e15f359SSam Clegg   SectionBookkeeping Section;
8279e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_ELEM);
8289e15f359SSam Clegg 
8299e15f359SSam Clegg   encodeULEB128(1, getStream()); // number of "segments"
8309e15f359SSam Clegg   encodeULEB128(0, getStream()); // the table index
8319e15f359SSam Clegg 
8329e15f359SSam Clegg   // init expr for starting offset
8339e15f359SSam Clegg   write8(wasm::WASM_OPCODE_I32_CONST);
83430e1bbc1SSam Clegg   encodeSLEB128(kInitialTableOffset, getStream());
8359e15f359SSam Clegg   write8(wasm::WASM_OPCODE_END);
8369e15f359SSam Clegg 
8379e15f359SSam Clegg   encodeULEB128(TableElems.size(), getStream());
8389e15f359SSam Clegg   for (uint32_t Elem : TableElems)
8399e15f359SSam Clegg     encodeULEB128(Elem, getStream());
8409e15f359SSam Clegg 
8419e15f359SSam Clegg   endSection(Section);
8429e15f359SSam Clegg }
8439e15f359SSam Clegg 
844457fb0b4SSam Clegg void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
845457fb0b4SSam Clegg                                         const MCAsmLayout &Layout,
846457fb0b4SSam Clegg                                         ArrayRef<WasmFunction> Functions) {
8479e15f359SSam Clegg   if (Functions.empty())
8489e15f359SSam Clegg     return;
8499e15f359SSam Clegg 
8509e15f359SSam Clegg   SectionBookkeeping Section;
8519e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_CODE);
8526f08c84aSSam Clegg   CodeSectionIndex = Section.Index;
8539e15f359SSam Clegg 
8549e15f359SSam Clegg   encodeULEB128(Functions.size(), getStream());
8559e15f359SSam Clegg 
8569e15f359SSam Clegg   for (const WasmFunction &Func : Functions) {
857fe6414b0SSam Clegg     auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
8589e15f359SSam Clegg 
8599e15f359SSam Clegg     int64_t Size = 0;
8609e15f359SSam Clegg     if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
8619e15f359SSam Clegg       report_fatal_error(".size expression must be evaluatable");
8629e15f359SSam Clegg 
8639e15f359SSam Clegg     encodeULEB128(Size, getStream());
864fe6414b0SSam Clegg     FuncSection.setSectionOffset(getStream().tell() - Section.ContentsOffset);
8659e15f359SSam Clegg     Asm.writeSectionData(&FuncSection, Layout);
8669e15f359SSam Clegg   }
8679e15f359SSam Clegg 
8689e15f359SSam Clegg   // Apply fixups.
869acd7d2b0SSam Clegg   applyRelocations(CodeRelocations, Section.ContentsOffset);
8709e15f359SSam Clegg 
8719e15f359SSam Clegg   endSection(Section);
8729e15f359SSam Clegg }
8739e15f359SSam Clegg 
8746c899ba6SSam Clegg void WasmObjectWriter::writeDataSection() {
8756c899ba6SSam Clegg   if (DataSegments.empty())
8767c395943SSam Clegg     return;
8779e15f359SSam Clegg 
8789e15f359SSam Clegg   SectionBookkeeping Section;
8799e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_DATA);
8806f08c84aSSam Clegg   DataSectionIndex = Section.Index;
8819e15f359SSam Clegg 
8826c899ba6SSam Clegg   encodeULEB128(DataSegments.size(), getStream()); // count
8837c395943SSam Clegg 
8846c899ba6SSam Clegg   for (const WasmDataSegment &Segment : DataSegments) {
8859e15f359SSam Clegg     encodeULEB128(0, getStream()); // memory index
8869e15f359SSam Clegg     write8(wasm::WASM_OPCODE_I32_CONST);
8877c395943SSam Clegg     encodeSLEB128(Segment.Offset, getStream()); // offset
8889e15f359SSam Clegg     write8(wasm::WASM_OPCODE_END);
8897c395943SSam Clegg     encodeULEB128(Segment.Data.size(), getStream()); // size
8907c395943SSam Clegg     Segment.Section->setSectionOffset(getStream().tell() - Section.ContentsOffset);
8917c395943SSam Clegg     writeBytes(Segment.Data); // data
8927c395943SSam Clegg   }
8939e15f359SSam Clegg 
8949e15f359SSam Clegg   // Apply fixups.
8957c395943SSam Clegg   applyRelocations(DataRelocations, Section.ContentsOffset);
8969e15f359SSam Clegg 
8979e15f359SSam Clegg   endSection(Section);
8989e15f359SSam Clegg }
8999e15f359SSam Clegg 
9006f08c84aSSam Clegg void WasmObjectWriter::writeRelocSection(
9016f08c84aSSam Clegg     uint32_t SectionIndex, StringRef Name,
9026f08c84aSSam Clegg     ArrayRef<WasmRelocationEntry> Relocations) {
9039e15f359SSam Clegg   // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
9049e15f359SSam Clegg   // for descriptions of the reloc sections.
9059e15f359SSam Clegg 
9066f08c84aSSam Clegg   if (Relocations.empty())
9079e15f359SSam Clegg     return;
9089e15f359SSam Clegg 
9099e15f359SSam Clegg   SectionBookkeeping Section;
9106f08c84aSSam Clegg   startCustomSection(Section, std::string("reloc.") + Name.str());
9119e15f359SSam Clegg 
9126f08c84aSSam Clegg   raw_pwrite_stream &Stream = getStream();
9139e15f359SSam Clegg 
9146f08c84aSSam Clegg   encodeULEB128(SectionIndex, Stream);
9156f08c84aSSam Clegg   encodeULEB128(Relocations.size(), Stream);
9166f08c84aSSam Clegg   for (const WasmRelocationEntry& RelEntry : Relocations) {
9176f08c84aSSam Clegg     uint64_t Offset = RelEntry.Offset +
9186f08c84aSSam Clegg                       RelEntry.FixupSection->getSectionOffset();
9196f08c84aSSam Clegg     uint32_t Index = getRelocationIndexValue(RelEntry);
9209e15f359SSam Clegg 
9216f08c84aSSam Clegg     write8(RelEntry.Type);
9226f08c84aSSam Clegg     encodeULEB128(Offset, Stream);
9236f08c84aSSam Clegg     encodeULEB128(Index, Stream);
9246f08c84aSSam Clegg     if (RelEntry.hasAddend())
9256f08c84aSSam Clegg       encodeSLEB128(RelEntry.Addend, Stream);
9269e15f359SSam Clegg   }
9279e15f359SSam Clegg 
9289e15f359SSam Clegg   endSection(Section);
9299e15f359SSam Clegg }
9309e15f359SSam Clegg 
9316a31a0d6SSam Clegg void WasmObjectWriter::writeCustomRelocSections() {
9326a31a0d6SSam Clegg   for (const auto &Sec : CustomSections) {
9336a31a0d6SSam Clegg     auto &Relocations = CustomSectionsRelocations[Sec.Section];
9346a31a0d6SSam Clegg     writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations);
9356a31a0d6SSam Clegg   }
9366a31a0d6SSam Clegg }
9376a31a0d6SSam Clegg 
9389e15f359SSam Clegg void WasmObjectWriter::writeLinkingMetaDataSection(
93986b4a09aSSam Clegg     ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
940ea7caceeSSam Clegg     ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
941ea7caceeSSam Clegg     const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) {
9429e15f359SSam Clegg   SectionBookkeeping Section;
9432322a937SSam Clegg   startCustomSection(Section, "linking");
9446bb5a41fSSam Clegg   encodeULEB128(wasm::WasmMetadataVersion, getStream());
9459e15f359SSam Clegg 
9466bb5a41fSSam Clegg   SectionBookkeeping SubSection;
9476c899ba6SSam Clegg   if (SymbolInfos.size() != 0) {
9486c899ba6SSam Clegg     startSection(SubSection, wasm::WASM_SYMBOL_TABLE);
9496c899ba6SSam Clegg     encodeULEB128(SymbolInfos.size(), getStream());
9506c899ba6SSam Clegg     for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) {
9516c899ba6SSam Clegg       encodeULEB128(Sym.Kind, getStream());
9526c899ba6SSam Clegg       encodeULEB128(Sym.Flags, getStream());
9536c899ba6SSam Clegg       switch (Sym.Kind) {
9546c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_FUNCTION:
9556c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_GLOBAL:
9566c899ba6SSam Clegg         encodeULEB128(Sym.ElementIndex, getStream());
9576c899ba6SSam Clegg         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0)
9586c899ba6SSam Clegg           writeString(Sym.Name);
9596c899ba6SSam Clegg         break;
9606c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_DATA:
9616c899ba6SSam Clegg         writeString(Sym.Name);
9626c899ba6SSam Clegg         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) {
9636c899ba6SSam Clegg           encodeULEB128(Sym.DataRef.Segment, getStream());
9646c899ba6SSam Clegg           encodeULEB128(Sym.DataRef.Offset, getStream());
9656c899ba6SSam Clegg           encodeULEB128(Sym.DataRef.Size, getStream());
9666c899ba6SSam Clegg         }
9676c899ba6SSam Clegg         break;
9686a31a0d6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_SECTION: {
9696a31a0d6SSam Clegg         const uint32_t SectionIndex =
9706a31a0d6SSam Clegg             CustomSections[Sym.ElementIndex].OutputIndex;
9716a31a0d6SSam Clegg         encodeULEB128(SectionIndex, getStream());
9726a31a0d6SSam Clegg         break;
9736a31a0d6SSam Clegg       }
9746c899ba6SSam Clegg       default:
9756c899ba6SSam Clegg         llvm_unreachable("unexpected kind");
9766c899ba6SSam Clegg       }
977b7787fd0SSam Clegg     }
978b7787fd0SSam Clegg     endSection(SubSection);
979b7787fd0SSam Clegg   }
9809e15f359SSam Clegg 
9816c899ba6SSam Clegg   if (DataSegments.size()) {
98263ebb813SSam Clegg     startSection(SubSection, wasm::WASM_SEGMENT_INFO);
9836c899ba6SSam Clegg     encodeULEB128(DataSegments.size(), getStream());
9846c899ba6SSam Clegg     for (const WasmDataSegment &Segment : DataSegments) {
985d95ed959SSam Clegg       writeString(Segment.Name);
98663ebb813SSam Clegg       encodeULEB128(Segment.Alignment, getStream());
98763ebb813SSam Clegg       encodeULEB128(Segment.Flags, getStream());
98863ebb813SSam Clegg     }
989d95ed959SSam Clegg     endSection(SubSection);
990d95ed959SSam Clegg   }
991d95ed959SSam Clegg 
992bafe6902SSam Clegg   if (!InitFuncs.empty()) {
993bafe6902SSam Clegg     startSection(SubSection, wasm::WASM_INIT_FUNCS);
994bafe6902SSam Clegg     encodeULEB128(InitFuncs.size(), getStream());
995bafe6902SSam Clegg     for (auto &StartFunc : InitFuncs) {
996bafe6902SSam Clegg       encodeULEB128(StartFunc.first, getStream()); // priority
997bafe6902SSam Clegg       encodeULEB128(StartFunc.second, getStream()); // function index
998bafe6902SSam Clegg     }
999bafe6902SSam Clegg     endSection(SubSection);
1000bafe6902SSam Clegg   }
1001bafe6902SSam Clegg 
1002ea7caceeSSam Clegg   if (Comdats.size()) {
1003ea7caceeSSam Clegg     startSection(SubSection, wasm::WASM_COMDAT_INFO);
1004ea7caceeSSam Clegg     encodeULEB128(Comdats.size(), getStream());
1005ea7caceeSSam Clegg     for (const auto &C : Comdats) {
1006ea7caceeSSam Clegg       writeString(C.first);
1007ea7caceeSSam Clegg       encodeULEB128(0, getStream()); // flags for future use
1008ea7caceeSSam Clegg       encodeULEB128(C.second.size(), getStream());
1009ea7caceeSSam Clegg       for (const WasmComdatEntry &Entry : C.second) {
1010ea7caceeSSam Clegg         encodeULEB128(Entry.Kind, getStream());
1011ea7caceeSSam Clegg         encodeULEB128(Entry.Index, getStream());
1012ea7caceeSSam Clegg       }
1013ea7caceeSSam Clegg     }
1014ea7caceeSSam Clegg     endSection(SubSection);
1015ea7caceeSSam Clegg   }
1016ea7caceeSSam Clegg 
10179e15f359SSam Clegg   endSection(Section);
10189e15f359SSam Clegg }
10199e15f359SSam Clegg 
10206a31a0d6SSam Clegg void WasmObjectWriter::writeCustomSections(const MCAssembler &Asm,
10216a31a0d6SSam Clegg                                            const MCAsmLayout &Layout) {
10226a31a0d6SSam Clegg   for (auto &CustomSection : CustomSections) {
1023cfd44a2eSSam Clegg     SectionBookkeeping Section;
10246a31a0d6SSam Clegg     auto *Sec = CustomSection.Section;
10252322a937SSam Clegg     startCustomSection(Section, CustomSection.Name);
10266a31a0d6SSam Clegg 
10276a31a0d6SSam Clegg     Sec->setSectionOffset(getStream().tell() - Section.ContentsOffset);
10286a31a0d6SSam Clegg     Asm.writeSectionData(Sec, Layout);
10296a31a0d6SSam Clegg 
10306a31a0d6SSam Clegg     CustomSection.OutputContentsOffset = Section.ContentsOffset;
10316a31a0d6SSam Clegg     CustomSection.OutputIndex = Section.Index;
10326a31a0d6SSam Clegg 
1033cfd44a2eSSam Clegg     endSection(Section);
1034cfd44a2eSSam Clegg   }
1035cfd44a2eSSam Clegg }
1036cfd44a2eSSam Clegg 
10376a31a0d6SSam Clegg void WasmObjectWriter::updateCustomSectionRelocations(
10386a31a0d6SSam Clegg     const SmallVector<WasmFunction, 4> &Functions, const MCAsmLayout &Layout) {
10396a31a0d6SSam Clegg   std::map<const MCSection *, const MCSymbolWasm *> SectionSymbols;
10406a31a0d6SSam Clegg   for (const auto &P : CustomSectionSymbols)
10416a31a0d6SSam Clegg     SectionSymbols[P.second] = P.first;
10426a31a0d6SSam Clegg   std::map<const MCSection *, const MCSymbolWasm *> FuncSymbols;
10436a31a0d6SSam Clegg   for (const auto &FuncInfo : Functions)
10446a31a0d6SSam Clegg     FuncSymbols[&FuncInfo.Sym->getSection()] = FuncInfo.Sym;
10456a31a0d6SSam Clegg 
10466a31a0d6SSam Clegg   // Patch relocation records for R_WEBASSEMBLY_FUNCTION_OFFSET_I32 and
10476a31a0d6SSam Clegg   // R_WEBASSEMBLY_SECTION_OFFSET_I32. The Addend is stuffed the offset from
10486a31a0d6SSam Clegg   // the beginning of the function or custom section -- all such relocations
10496a31a0d6SSam Clegg   // target the function or custom section starts.
10506a31a0d6SSam Clegg   for (auto &Section : CustomSections) {
10516a31a0d6SSam Clegg     auto &Relocations = CustomSectionsRelocations[Section.Section];
10526a31a0d6SSam Clegg     for (WasmRelocationEntry &RelEntry : Relocations) {
10536a31a0d6SSam Clegg       switch (RelEntry.Type) {
10546a31a0d6SSam Clegg       case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32: {
10556a31a0d6SSam Clegg         assert(RelEntry.hasAddend());
10566a31a0d6SSam Clegg         auto &Section =
10576a31a0d6SSam Clegg             static_cast<MCSectionWasm &>(RelEntry.Symbol->getSection());
10586a31a0d6SSam Clegg         RelEntry.Addend += Layout.getSymbolOffset(*RelEntry.Symbol);
10596a31a0d6SSam Clegg         RelEntry.Symbol = FuncSymbols[&Section];
10606a31a0d6SSam Clegg         break;
10616a31a0d6SSam Clegg       }
10626a31a0d6SSam Clegg       case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32: {
10636a31a0d6SSam Clegg         assert(RelEntry.hasAddend());
10646a31a0d6SSam Clegg         auto &Section =
10656a31a0d6SSam Clegg             static_cast<MCSectionWasm &>(RelEntry.Symbol->getSection());
10666a31a0d6SSam Clegg         RelEntry.Addend += Layout.getSymbolOffset(*RelEntry.Symbol);
10676a31a0d6SSam Clegg         RelEntry.Symbol = SectionSymbols[&Section];
10686a31a0d6SSam Clegg         break;
10696a31a0d6SSam Clegg       }
10706a31a0d6SSam Clegg       default:
10716a31a0d6SSam Clegg         break;
10726a31a0d6SSam Clegg       }
10736a31a0d6SSam Clegg     }
10746a31a0d6SSam Clegg 
10756a31a0d6SSam Clegg     // Apply fixups.
10766a31a0d6SSam Clegg     applyRelocations(Relocations, Section.OutputContentsOffset);
10776a31a0d6SSam Clegg   }
10786a31a0d6SSam Clegg }
10796a31a0d6SSam Clegg 
10805e3d33a7SSam Clegg uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm& Symbol) {
10815e3d33a7SSam Clegg   assert(Symbol.isFunction());
10825e3d33a7SSam Clegg   assert(TypeIndices.count(&Symbol));
10835e3d33a7SSam Clegg   return TypeIndices[&Symbol];
10845e3d33a7SSam Clegg }
10855e3d33a7SSam Clegg 
10865e3d33a7SSam Clegg uint32_t WasmObjectWriter::registerFunctionType(const MCSymbolWasm& Symbol) {
10875e3d33a7SSam Clegg   assert(Symbol.isFunction());
10885e3d33a7SSam Clegg 
10895e3d33a7SSam Clegg   WasmFunctionType F;
1090aff1c4dfSSam Clegg   const MCSymbolWasm* ResolvedSym = ResolveSymbol(Symbol);
10915e3d33a7SSam Clegg   F.Returns = ResolvedSym->getReturns();
10925e3d33a7SSam Clegg   F.Params = ResolvedSym->getParams();
10935e3d33a7SSam Clegg 
10945e3d33a7SSam Clegg   auto Pair =
10955e3d33a7SSam Clegg       FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size()));
10965e3d33a7SSam Clegg   if (Pair.second)
10975e3d33a7SSam Clegg     FunctionTypes.push_back(F);
10985e3d33a7SSam Clegg   TypeIndices[&Symbol] = Pair.first->second;
10995e3d33a7SSam Clegg 
11005e3d33a7SSam Clegg   DEBUG(dbgs() << "registerFunctionType: " << Symbol << " new:" << Pair.second << "\n");
11015e3d33a7SSam Clegg   DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
11025e3d33a7SSam Clegg   return Pair.first->second;
11035e3d33a7SSam Clegg }
11045e3d33a7SSam Clegg 
110518eafb6cSDan Gohman void WasmObjectWriter::writeObject(MCAssembler &Asm,
110618eafb6cSDan Gohman                                    const MCAsmLayout &Layout) {
1107b7787fd0SSam Clegg   DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
110882607f56SDan Gohman   MCContext &Ctx = Asm.getContext();
1109d934cb88SDan Gohman 
1110d934cb88SDan Gohman   // Collect information from the available symbols.
1111d934cb88SDan Gohman   SmallVector<WasmFunction, 4> Functions;
1112d934cb88SDan Gohman   SmallVector<uint32_t, 4> TableElems;
11138defa952SSam Clegg   SmallVector<wasm::WasmImport, 4> Imports;
11148defa952SSam Clegg   SmallVector<wasm::WasmExport, 4> Exports;
11156c899ba6SSam Clegg   SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos;
1116bafe6902SSam Clegg   SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
1117ea7caceeSSam Clegg   std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
11187c395943SSam Clegg   uint32_t DataSize = 0;
1119d934cb88SDan Gohman 
1120f950b24aSSam Clegg   // For now, always emit the memory import, since loads and stores are not
1121f950b24aSSam Clegg   // valid without it. In the future, we could perhaps be more clever and omit
1122f950b24aSSam Clegg   // it if there are no loads or stores.
1123f950b24aSSam Clegg   MCSymbolWasm *MemorySym =
1124f950b24aSSam Clegg       cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__linear_memory"));
11258defa952SSam Clegg   wasm::WasmImport MemImport;
11268defa952SSam Clegg   MemImport.Module = MemorySym->getModuleName();
11278defa952SSam Clegg   MemImport.Field = MemorySym->getName();
1128f950b24aSSam Clegg   MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
1129f950b24aSSam Clegg   Imports.push_back(MemImport);
1130f950b24aSSam Clegg 
1131f950b24aSSam Clegg   // For now, always emit the table section, since indirect calls are not
1132f950b24aSSam Clegg   // valid without it. In the future, we could perhaps be more clever and omit
1133f950b24aSSam Clegg   // it if there are no indirect calls.
1134f950b24aSSam Clegg   MCSymbolWasm *TableSym =
1135f950b24aSSam Clegg       cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__indirect_function_table"));
11368defa952SSam Clegg   wasm::WasmImport TableImport;
11378defa952SSam Clegg   TableImport.Module = TableSym->getModuleName();
11388defa952SSam Clegg   TableImport.Field = TableSym->getName();
1139f950b24aSSam Clegg   TableImport.Kind = wasm::WASM_EXTERNAL_TABLE;
11408defa952SSam Clegg   TableImport.Table.ElemType = wasm::WASM_TYPE_ANYFUNC;
1141f950b24aSSam Clegg   Imports.push_back(TableImport);
1142f950b24aSSam Clegg 
1143586320c0SNicholas Wilson   // Populate FunctionTypeIndices, and Imports and WasmIndices for undefined
1144586320c0SNicholas Wilson   // symbols.  This must be done before populating WasmIndices for defined
1145586320c0SNicholas Wilson   // symbols.
114632ce5ca0SDan Gohman   for (const MCSymbol &S : Asm.symbols()) {
114732ce5ca0SDan Gohman     const auto &WS = static_cast<const MCSymbolWasm &>(S);
114832ce5ca0SDan Gohman 
114932ce5ca0SDan Gohman     // Register types for all functions, including those with private linkage
11509f3fe42eSSam Clegg     // (because wasm always needs a type signature).
115132ce5ca0SDan Gohman     if (WS.isFunction())
115232ce5ca0SDan Gohman       registerFunctionType(WS);
115332ce5ca0SDan Gohman 
115432ce5ca0SDan Gohman     if (WS.isTemporary())
115532ce5ca0SDan Gohman       continue;
115632ce5ca0SDan Gohman 
115732ce5ca0SDan Gohman     // If the symbol is not defined in this translation unit, import it.
11586c899ba6SSam Clegg     if (!WS.isDefined() && !WS.isComdat()) {
11596c899ba6SSam Clegg       if (WS.isFunction()) {
11608defa952SSam Clegg         wasm::WasmImport Import;
11618defa952SSam Clegg         Import.Module = WS.getModuleName();
11628defa952SSam Clegg         Import.Field = WS.getName();
116332ce5ca0SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
11648defa952SSam Clegg         Import.SigIndex = getFunctionType(WS);
11656c899ba6SSam Clegg         Imports.push_back(Import);
11666c899ba6SSam Clegg         WasmIndices[&WS] = NumFunctionImports++;
11676c899ba6SSam Clegg       } else if (WS.isGlobal()) {
116815f349f7SNicholas Wilson         if (WS.isWeak())
116915f349f7SNicholas Wilson           report_fatal_error("undefined global symbol cannot be weak");
117015f349f7SNicholas Wilson 
11716c899ba6SSam Clegg         wasm::WasmImport Import;
11726c899ba6SSam Clegg         Import.Module = WS.getModuleName();
11736c899ba6SSam Clegg         Import.Field = WS.getName();
117432ce5ca0SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
11756c899ba6SSam Clegg         Import.Global = WS.getGlobalType();
11766c899ba6SSam Clegg         Imports.push_back(Import);
11776c899ba6SSam Clegg         WasmIndices[&WS] = NumGlobalImports++;
117832ce5ca0SDan Gohman       }
117932ce5ca0SDan Gohman     }
118032ce5ca0SDan Gohman   }
118132ce5ca0SDan Gohman 
1182586320c0SNicholas Wilson   // Populate DataSegments, which must be done before populating DataLocations.
1183759631c7SSam Clegg   for (MCSection &Sec : Asm) {
1184759631c7SSam Clegg     auto &Section = static_cast<MCSectionWasm &>(Sec);
1185cfd44a2eSSam Clegg 
11866a31a0d6SSam Clegg     if (Section.getSectionName().startswith(".custom_section.")) {
1187cfd44a2eSSam Clegg       if (Section.getFragmentList().empty())
1188cfd44a2eSSam Clegg         continue;
1189cfd44a2eSSam Clegg       if (Section.getFragmentList().size() != 1)
1190cfd44a2eSSam Clegg         report_fatal_error(
1191cfd44a2eSSam Clegg             "only one .custom_section section fragment supported");
1192cfd44a2eSSam Clegg       const MCFragment &Frag = *Section.begin();
1193cfd44a2eSSam Clegg       if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1194cfd44a2eSSam Clegg         report_fatal_error("only data supported in .custom_section section");
1195cfd44a2eSSam Clegg       const auto &DataFrag = cast<MCDataFragment>(Frag);
1196cfd44a2eSSam Clegg       if (!DataFrag.getFixups().empty())
1197cfd44a2eSSam Clegg         report_fatal_error("fixups not supported in .custom_section section");
1198cfd44a2eSSam Clegg       StringRef UserName = Section.getSectionName().substr(16);
11996a31a0d6SSam Clegg       CustomSections.emplace_back(UserName, &Section);
1200cfd44a2eSSam Clegg       continue;
1201cfd44a2eSSam Clegg     }
1202cfd44a2eSSam Clegg 
120312fd3da9SSam Clegg     if (!Section.isWasmData())
1204759631c7SSam Clegg       continue;
1205759631c7SSam Clegg 
1206bafe6902SSam Clegg     // .init_array sections are handled specially elsewhere.
1207bafe6902SSam Clegg     if (cast<MCSectionWasm>(Sec).getSectionName().startswith(".init_array"))
1208bafe6902SSam Clegg       continue;
1209bafe6902SSam Clegg 
1210329e76d5SSam Clegg     uint32_t SegmentIndex = DataSegments.size();
1211759631c7SSam Clegg     DataSize = alignTo(DataSize, Section.getAlignment());
1212759631c7SSam Clegg     DataSegments.emplace_back();
1213759631c7SSam Clegg     WasmDataSegment &Segment = DataSegments.back();
1214d95ed959SSam Clegg     Segment.Name = Section.getSectionName();
1215759631c7SSam Clegg     Segment.Offset = DataSize;
1216759631c7SSam Clegg     Segment.Section = &Section;
121763ebb813SSam Clegg     addData(Segment.Data, Section);
121863ebb813SSam Clegg     Segment.Alignment = Section.getAlignment();
121963ebb813SSam Clegg     Segment.Flags = 0;
1220759631c7SSam Clegg     DataSize += Segment.Data.size();
12216c899ba6SSam Clegg     Section.setSegmentIndex(SegmentIndex);
1222ea7caceeSSam Clegg 
1223ea7caceeSSam Clegg     if (const MCSymbolWasm *C = Section.getGroup()) {
1224ea7caceeSSam Clegg       Comdats[C->getName()].emplace_back(
1225329e76d5SSam Clegg           WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
1226ea7caceeSSam Clegg     }
1227759631c7SSam Clegg   }
1228759631c7SSam Clegg 
12296a31a0d6SSam Clegg   // Create symbols for debug/custom sections.
12306a31a0d6SSam Clegg   for (MCSection &Sec : Asm) {
12316a31a0d6SSam Clegg     auto &DebugSection = static_cast<MCSectionWasm &>(Sec);
12326a31a0d6SSam Clegg     StringRef SectionName = DebugSection.getSectionName();
12336a31a0d6SSam Clegg 
12346a31a0d6SSam Clegg     // TODO: Add support for non-debug metadata sections?
12356a31a0d6SSam Clegg     if (!Sec.getKind().isMetadata() || !SectionName.startswith(".debug_"))
12366a31a0d6SSam Clegg       continue;
12376a31a0d6SSam Clegg 
12386a31a0d6SSam Clegg     uint32_t ElementIndex = CustomSections.size();
12396a31a0d6SSam Clegg     CustomSections.emplace_back(SectionName, &DebugSection);
12406a31a0d6SSam Clegg 
12416a31a0d6SSam Clegg     MCSymbolWasm *SectionSym =
12426a31a0d6SSam Clegg         cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SectionName));
12436a31a0d6SSam Clegg     CustomSectionSymbols[SectionSym] = &DebugSection;
12446a31a0d6SSam Clegg 
12456a31a0d6SSam Clegg     wasm::WasmSymbolInfo Info;
12466a31a0d6SSam Clegg     Info.Name = SectionSym->getName();
12476a31a0d6SSam Clegg     Info.Kind = wasm::WASM_SYMBOL_TYPE_SECTION;
1248d5504a0aSSam Clegg     Info.Flags = wasm::WASM_SYMBOL_BINDING_LOCAL;
12496a31a0d6SSam Clegg     Info.ElementIndex = ElementIndex;
12506a31a0d6SSam Clegg     SymbolIndices[SectionSym] = SymbolInfos.size();
12516a31a0d6SSam Clegg     SymbolInfos.emplace_back(Info);
12526a31a0d6SSam Clegg   }
12536a31a0d6SSam Clegg 
1254586320c0SNicholas Wilson   // Populate WasmIndices and DataLocations for defined symbols.
1255d934cb88SDan Gohman   for (const MCSymbol &S : Asm.symbols()) {
1256d934cb88SDan Gohman     // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1257d934cb88SDan Gohman     // or used in relocations.
1258d934cb88SDan Gohman     if (S.isTemporary() && S.getName().empty())
1259d934cb88SDan Gohman       continue;
1260b7787fd0SSam Clegg 
1261d934cb88SDan Gohman     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1262a165f2d6SSam Clegg     DEBUG(dbgs() << "MCSymbol: " << toString(WS.getType())
1263a165f2d6SSam Clegg                  << " '" << S << "'"
1264329e76d5SSam Clegg                  << " isDefined=" << S.isDefined()
1265329e76d5SSam Clegg                  << " isExternal=" << S.isExternal()
1266329e76d5SSam Clegg                  << " isTemporary=" << S.isTemporary()
1267b7787fd0SSam Clegg                  << " isWeak=" << WS.isWeak()
1268a2b35dacSSam Clegg                  << " isHidden=" << WS.isHidden()
1269b7787fd0SSam Clegg                  << " isVariable=" << WS.isVariable() << "\n");
1270b7787fd0SSam Clegg 
12715e3d33a7SSam Clegg     if (WS.isVariable())
12725e3d33a7SSam Clegg       continue;
12736c899ba6SSam Clegg     if (WS.isComdat() && !WS.isDefined())
12746c899ba6SSam Clegg       continue;
1275b7787fd0SSam Clegg 
1276d934cb88SDan Gohman     if (WS.isFunction()) {
12776c899ba6SSam Clegg       unsigned Index;
1278cd65f698SSam Clegg       if (WS.isDefined()) {
1279b7787fd0SSam Clegg         if (WS.getOffset() != 0)
1280b7787fd0SSam Clegg           report_fatal_error(
1281b7787fd0SSam Clegg               "function sections must contain one function each");
1282b7787fd0SSam Clegg 
1283b7787fd0SSam Clegg         if (WS.getSize() == 0)
1284b7787fd0SSam Clegg           report_fatal_error(
1285b7787fd0SSam Clegg               "function symbols must have a size set with .size");
1286b7787fd0SSam Clegg 
12876c899ba6SSam Clegg         // A definition. Write out the function body.
12889f3fe42eSSam Clegg         Index = NumFunctionImports + Functions.size();
1289d934cb88SDan Gohman         WasmFunction Func;
12905e3d33a7SSam Clegg         Func.Type = getFunctionType(WS);
1291d934cb88SDan Gohman         Func.Sym = &WS;
12926c899ba6SSam Clegg         WasmIndices[&WS] = Index;
1293d934cb88SDan Gohman         Functions.push_back(Func);
12946c899ba6SSam Clegg 
12956c899ba6SSam Clegg         auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
12966c899ba6SSam Clegg         if (const MCSymbolWasm *C = Section.getGroup()) {
12976c899ba6SSam Clegg           Comdats[C->getName()].emplace_back(
12986c899ba6SSam Clegg               WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
12996c899ba6SSam Clegg         }
1300d934cb88SDan Gohman       } else {
1301d934cb88SDan Gohman         // An import; the index was assigned above.
13026c899ba6SSam Clegg         Index = WasmIndices.find(&WS)->second;
1303d934cb88SDan Gohman       }
1304d934cb88SDan Gohman 
13055e3d33a7SSam Clegg       DEBUG(dbgs() << "  -> function index: " << Index << "\n");
13066c899ba6SSam Clegg     } else if (WS.isData()) {
1307c38e947eSSam Clegg       if (WS.isTemporary() && !WS.getSize())
1308c38e947eSSam Clegg         continue;
1309c38e947eSSam Clegg 
13106c899ba6SSam Clegg       if (!WS.isDefined()) {
1311a165f2d6SSam Clegg         DEBUG(dbgs() << "  -> segment index: -1" << "\n");
1312fe6414b0SSam Clegg         continue;
13136c899ba6SSam Clegg       }
1314fe6414b0SSam Clegg 
1315d934cb88SDan Gohman       if (!WS.getSize())
1316c38e947eSSam Clegg         report_fatal_error("data symbols must have a size set with .size: " +
1317c38e947eSSam Clegg                            WS.getName());
1318d934cb88SDan Gohman 
1319d934cb88SDan Gohman       int64_t Size = 0;
1320d934cb88SDan Gohman       if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1321d934cb88SDan Gohman         report_fatal_error(".size expression must be evaluatable");
1322d934cb88SDan Gohman 
1323759631c7SSam Clegg       auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
1324ea7caceeSSam Clegg       assert(DataSection.isWasmData());
13257c395943SSam Clegg 
13266c899ba6SSam Clegg       // For each data symbol, export it in the symtab as a reference to the
13276c899ba6SSam Clegg       // corresponding Wasm data segment.
13286c899ba6SSam Clegg       wasm::WasmDataReference Ref = wasm::WasmDataReference{
13296c899ba6SSam Clegg           DataSection.getSegmentIndex(),
13306c899ba6SSam Clegg           static_cast<uint32_t>(Layout.getSymbolOffset(WS)),
13316c899ba6SSam Clegg           static_cast<uint32_t>(Size)};
13326c899ba6SSam Clegg       DataLocations[&WS] = Ref;
1333a165f2d6SSam Clegg       DEBUG(dbgs() << "  -> segment index: " << Ref.Segment << "\n");
1334a165f2d6SSam Clegg     } else if (WS.isGlobal()) {
13356c899ba6SSam Clegg       // A "true" Wasm global (currently just __stack_pointer)
1336545932beSEric Christopher       if (WS.isDefined())
13376c899ba6SSam Clegg         report_fatal_error("don't yet support defined globals");
13386c899ba6SSam Clegg 
1339545932beSEric Christopher       // An import; the index was assigned above
1340545932beSEric Christopher       DEBUG(dbgs() << "  -> global index: " << WasmIndices.find(&WS)->second
1341545932beSEric Christopher                    << "\n");
1342a165f2d6SSam Clegg     } else {
1343a165f2d6SSam Clegg       assert(WS.isSection());
1344d934cb88SDan Gohman     }
1345d934cb88SDan Gohman   }
1346d934cb88SDan Gohman 
1347586320c0SNicholas Wilson   // Populate WasmIndices and DataLocations for aliased symbols.  We need to
1348586320c0SNicholas Wilson   // process these in a separate pass because we need to have processed the
1349586320c0SNicholas Wilson   // target of the alias before the alias itself and the symbols are not
1350586320c0SNicholas Wilson   // necessarily ordered in this way.
1351b7787fd0SSam Clegg   for (const MCSymbol &S : Asm.symbols()) {
1352b7787fd0SSam Clegg     if (!S.isVariable())
1353b7787fd0SSam Clegg       continue;
135431a2c809SSam Clegg 
1355cd65f698SSam Clegg     assert(S.isDefined());
1356b7787fd0SSam Clegg 
13575e3d33a7SSam Clegg     // Find the target symbol of this weak alias and export that index
1358aff1c4dfSSam Clegg     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1359aff1c4dfSSam Clegg     const MCSymbolWasm *ResolvedSym = ResolveSymbol(WS);
13605e3d33a7SSam Clegg     DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym << "'\n");
1361b7787fd0SSam Clegg 
13626c899ba6SSam Clegg     if (WS.isFunction()) {
13636c899ba6SSam Clegg       assert(WasmIndices.count(ResolvedSym) > 0);
13646c899ba6SSam Clegg       uint32_t WasmIndex = WasmIndices.find(ResolvedSym)->second;
13656c899ba6SSam Clegg       WasmIndices[&WS] = WasmIndex;
13666c899ba6SSam Clegg       DEBUG(dbgs() << "  -> index:" << WasmIndex << "\n");
13676c899ba6SSam Clegg     } else if (WS.isData()) {
13686c899ba6SSam Clegg       assert(DataLocations.count(ResolvedSym) > 0);
13696c899ba6SSam Clegg       const wasm::WasmDataReference &Ref =
13706c899ba6SSam Clegg           DataLocations.find(ResolvedSym)->second;
13716c899ba6SSam Clegg       DataLocations[&WS] = Ref;
13726c899ba6SSam Clegg       DEBUG(dbgs() << "  -> index:" << Ref.Segment << "\n");
13736c899ba6SSam Clegg     } else {
13746c899ba6SSam Clegg       report_fatal_error("don't yet support global aliases");
13756c899ba6SSam Clegg     }
1376586320c0SNicholas Wilson   }
137731a2c809SSam Clegg 
1378586320c0SNicholas Wilson   // Finally, populate the symbol table itself, in its "natural" order.
1379586320c0SNicholas Wilson   for (const MCSymbol &S : Asm.symbols()) {
1380586320c0SNicholas Wilson     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1381586320c0SNicholas Wilson     if (WS.isTemporary() && WS.getName().empty())
1382586320c0SNicholas Wilson       continue;
1383586320c0SNicholas Wilson     if (WS.isComdat() && !WS.isDefined())
1384586320c0SNicholas Wilson       continue;
1385586320c0SNicholas Wilson     if (WS.isTemporary() && WS.isData() && !WS.getSize())
1386586320c0SNicholas Wilson       continue;
1387586320c0SNicholas Wilson 
1388586320c0SNicholas Wilson     uint32_t Flags = 0;
1389586320c0SNicholas Wilson     if (WS.isWeak())
1390586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_BINDING_WEAK;
1391586320c0SNicholas Wilson     if (WS.isHidden())
1392586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN;
1393586320c0SNicholas Wilson     if (!WS.isExternal() && WS.isDefined())
1394586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;
1395586320c0SNicholas Wilson     if (WS.isUndefined())
1396586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_UNDEFINED;
1397586320c0SNicholas Wilson 
1398586320c0SNicholas Wilson     wasm::WasmSymbolInfo Info;
1399586320c0SNicholas Wilson     Info.Name = WS.getName();
1400586320c0SNicholas Wilson     Info.Kind = WS.getType();
1401586320c0SNicholas Wilson     Info.Flags = Flags;
1402586320c0SNicholas Wilson     if (!WS.isData())
1403586320c0SNicholas Wilson       Info.ElementIndex = WasmIndices.find(&WS)->second;
1404586320c0SNicholas Wilson     else if (WS.isDefined())
1405586320c0SNicholas Wilson       Info.DataRef = DataLocations.find(&WS)->second;
1406586320c0SNicholas Wilson     SymbolIndices[&WS] = SymbolInfos.size();
1407586320c0SNicholas Wilson     SymbolInfos.emplace_back(Info);
1408b7787fd0SSam Clegg   }
1409b7787fd0SSam Clegg 
14106006e091SSam Clegg   {
14116006e091SSam Clegg     auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
1412f9edbe95SSam Clegg       // Functions referenced by a relocation need to put in the table.  This is
1413f9edbe95SSam Clegg       // purely to make the object file's provisional values readable, and is
1414f9edbe95SSam Clegg       // ignored by the linker, which re-calculates the relocations itself.
1415f9edbe95SSam Clegg       if (Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_I32 &&
1416f9edbe95SSam Clegg           Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB)
1417f9edbe95SSam Clegg         return;
1418f9edbe95SSam Clegg       assert(Rel.Symbol->isFunction());
1419f9edbe95SSam Clegg       const MCSymbolWasm &WS = *ResolveSymbol(*Rel.Symbol);
14206c899ba6SSam Clegg       uint32_t FunctionIndex = WasmIndices.find(&WS)->second;
1421f9edbe95SSam Clegg       uint32_t TableIndex = TableElems.size() + kInitialTableOffset;
1422f9edbe95SSam Clegg       if (TableIndices.try_emplace(&WS, TableIndex).second) {
1423329e76d5SSam Clegg         DEBUG(dbgs() << "  -> adding " << WS.getName()
1424f9edbe95SSam Clegg                      << " to table: " << TableIndex << "\n");
14256c899ba6SSam Clegg         TableElems.push_back(FunctionIndex);
14266006e091SSam Clegg         registerFunctionType(WS);
14276006e091SSam Clegg       }
14286006e091SSam Clegg     };
1429970d02c4SDan Gohman 
14306006e091SSam Clegg     for (const WasmRelocationEntry &RelEntry : CodeRelocations)
14316006e091SSam Clegg       HandleReloc(RelEntry);
14326006e091SSam Clegg     for (const WasmRelocationEntry &RelEntry : DataRelocations)
14336006e091SSam Clegg       HandleReloc(RelEntry);
1434d934cb88SDan Gohman   }
1435d934cb88SDan Gohman 
1436bafe6902SSam Clegg   // Translate .init_array section contents into start functions.
1437bafe6902SSam Clegg   for (const MCSection &S : Asm) {
1438bafe6902SSam Clegg     const auto &WS = static_cast<const MCSectionWasm &>(S);
1439bafe6902SSam Clegg     if (WS.getSectionName().startswith(".fini_array"))
1440bafe6902SSam Clegg       report_fatal_error(".fini_array sections are unsupported");
1441bafe6902SSam Clegg     if (!WS.getSectionName().startswith(".init_array"))
1442bafe6902SSam Clegg       continue;
1443bafe6902SSam Clegg     if (WS.getFragmentList().empty())
1444bafe6902SSam Clegg       continue;
1445bafe6902SSam Clegg     if (WS.getFragmentList().size() != 2)
1446bafe6902SSam Clegg       report_fatal_error("only one .init_array section fragment supported");
1447bafe6902SSam Clegg     const MCFragment &AlignFrag = *WS.begin();
1448bafe6902SSam Clegg     if (AlignFrag.getKind() != MCFragment::FT_Align)
1449bafe6902SSam Clegg       report_fatal_error(".init_array section should be aligned");
1450bafe6902SSam Clegg     if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
1451bafe6902SSam Clegg       report_fatal_error(".init_array section should be aligned for pointers");
1452bafe6902SSam Clegg     const MCFragment &Frag = *std::next(WS.begin());
1453bafe6902SSam Clegg     if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1454bafe6902SSam Clegg       report_fatal_error("only data supported in .init_array section");
1455bafe6902SSam Clegg     uint16_t Priority = UINT16_MAX;
1456bafe6902SSam Clegg     if (WS.getSectionName().size() != 11) {
1457bafe6902SSam Clegg       if (WS.getSectionName()[11] != '.')
1458bafe6902SSam Clegg         report_fatal_error(".init_array section priority should start with '.'");
1459bafe6902SSam Clegg       if (WS.getSectionName().substr(12).getAsInteger(10, Priority))
1460bafe6902SSam Clegg         report_fatal_error("invalid .init_array section priority");
1461bafe6902SSam Clegg     }
1462bafe6902SSam Clegg     const auto &DataFrag = cast<MCDataFragment>(Frag);
1463bafe6902SSam Clegg     const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1464bafe6902SSam Clegg     for (const uint8_t *p = (const uint8_t *)Contents.data(),
1465bafe6902SSam Clegg                      *end = (const uint8_t *)Contents.data() + Contents.size();
1466bafe6902SSam Clegg          p != end; ++p) {
1467bafe6902SSam Clegg       if (*p != 0)
1468bafe6902SSam Clegg         report_fatal_error("non-symbolic data in .init_array section");
1469bafe6902SSam Clegg     }
1470bafe6902SSam Clegg     for (const MCFixup &Fixup : DataFrag.getFixups()) {
1471bafe6902SSam Clegg       assert(Fixup.getKind() == MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
1472bafe6902SSam Clegg       const MCExpr *Expr = Fixup.getValue();
1473bafe6902SSam Clegg       auto *Sym = dyn_cast<MCSymbolRefExpr>(Expr);
1474bafe6902SSam Clegg       if (!Sym)
1475bafe6902SSam Clegg         report_fatal_error("fixups in .init_array should be symbol references");
1476bafe6902SSam Clegg       if (Sym->getKind() != MCSymbolRefExpr::VK_WebAssembly_FUNCTION)
1477bafe6902SSam Clegg         report_fatal_error("symbols in .init_array should be for functions");
1478bafe6902SSam Clegg       auto I = SymbolIndices.find(cast<MCSymbolWasm>(&Sym->getSymbol()));
1479bafe6902SSam Clegg       if (I == SymbolIndices.end())
1480bafe6902SSam Clegg         report_fatal_error("symbols in .init_array should be defined");
1481bafe6902SSam Clegg       uint32_t Index = I->second;
1482bafe6902SSam Clegg       InitFuncs.push_back(std::make_pair(Priority, Index));
1483bafe6902SSam Clegg     }
1484bafe6902SSam Clegg   }
1485bafe6902SSam Clegg 
148618eafb6cSDan Gohman   // Write out the Wasm header.
148718eafb6cSDan Gohman   writeHeader(Asm);
148818eafb6cSDan Gohman 
14899e15f359SSam Clegg   writeTypeSection(FunctionTypes);
1490f950b24aSSam Clegg   writeImportSection(Imports, DataSize, TableElems.size());
14919e15f359SSam Clegg   writeFunctionSection(Functions);
1492f950b24aSSam Clegg   // Skip the "table" section; we import the table instead.
1493f950b24aSSam Clegg   // Skip the "memory" section; we import the memory instead.
14947c395943SSam Clegg   writeGlobalSection();
14959e15f359SSam Clegg   writeExportSection(Exports);
14969e15f359SSam Clegg   writeElemSection(TableElems);
1497acd7d2b0SSam Clegg   writeCodeSection(Asm, Layout, Functions);
14986c899ba6SSam Clegg   writeDataSection();
14996a31a0d6SSam Clegg   writeCustomSections(Asm, Layout);
15006a31a0d6SSam Clegg   updateCustomSectionRelocations(Functions, Layout);
1501c22bfb6bSNicholas Wilson   writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats);
15026f08c84aSSam Clegg   writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations);
15036f08c84aSSam Clegg   writeRelocSection(DataSectionIndex, "DATA", DataRelocations);
15046a31a0d6SSam Clegg   writeCustomRelocSections();
1505970d02c4SDan Gohman 
1506d934cb88SDan Gohman   // TODO: Translate the .comment section to the output.
150718eafb6cSDan Gohman }
150818eafb6cSDan Gohman 
150960fbc7ccSLang Hames std::unique_ptr<MCObjectWriter>
15101301a878SLang Hames llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
151118eafb6cSDan Gohman                              raw_pwrite_stream &OS) {
15120917c9e4SDan Gohman   return llvm::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
151318eafb6cSDan Gohman }
1514