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 
4018eafb6cSDan Gohman namespace {
419e15f359SSam Clegg 
4230e1bbc1SSam Clegg // Went we ceate the indirect function table we start at 1, so that there is
4330e1bbc1SSam Clegg // and emtpy slot at 0 and therefore calling a null function pointer will trap.
4430e1bbc1SSam Clegg static const uint32_t kInitialTableOffset = 1;
4530e1bbc1SSam Clegg 
46d934cb88SDan Gohman // For patching purposes, we need to remember where each section starts, both
47d934cb88SDan Gohman // for patching up the section size field, and for patching up references to
48d934cb88SDan Gohman // locations within the section.
49d934cb88SDan Gohman struct SectionBookkeeping {
50d934cb88SDan Gohman   // Where the size of the section is written.
51d934cb88SDan Gohman   uint64_t SizeOffset;
526a31a0d6SSam Clegg   // Where the section header ends (without custom section name).
536a31a0d6SSam Clegg   uint64_t PayloadOffset;
546a31a0d6SSam Clegg   // Where the contents of the section starts.
55d934cb88SDan Gohman   uint64_t ContentsOffset;
566f08c84aSSam Clegg   uint32_t Index;
57d934cb88SDan Gohman };
58d934cb88SDan Gohman 
599e15f359SSam Clegg // The signature of a wasm function, in a struct capable of being used as a
609e15f359SSam Clegg // DenseMap key.
619e15f359SSam Clegg struct WasmFunctionType {
629e15f359SSam Clegg   // Support empty and tombstone instances, needed by DenseMap.
639e15f359SSam Clegg   enum { Plain, Empty, Tombstone } State;
649e15f359SSam Clegg 
659e15f359SSam Clegg   // The return types of the function.
669e15f359SSam Clegg   SmallVector<wasm::ValType, 1> Returns;
679e15f359SSam Clegg 
689e15f359SSam Clegg   // The parameter types of the function.
699e15f359SSam Clegg   SmallVector<wasm::ValType, 4> Params;
709e15f359SSam Clegg 
719e15f359SSam Clegg   WasmFunctionType() : State(Plain) {}
729e15f359SSam Clegg 
739e15f359SSam Clegg   bool operator==(const WasmFunctionType &Other) const {
749e15f359SSam Clegg     return State == Other.State && Returns == Other.Returns &&
759e15f359SSam Clegg            Params == Other.Params;
769e15f359SSam Clegg   }
779e15f359SSam Clegg };
789e15f359SSam Clegg 
799e15f359SSam Clegg // Traits for using WasmFunctionType in a DenseMap.
809e15f359SSam Clegg struct WasmFunctionTypeDenseMapInfo {
819e15f359SSam Clegg   static WasmFunctionType getEmptyKey() {
829e15f359SSam Clegg     WasmFunctionType FuncTy;
839e15f359SSam Clegg     FuncTy.State = WasmFunctionType::Empty;
849e15f359SSam Clegg     return FuncTy;
859e15f359SSam Clegg   }
869e15f359SSam Clegg   static WasmFunctionType getTombstoneKey() {
879e15f359SSam Clegg     WasmFunctionType FuncTy;
889e15f359SSam Clegg     FuncTy.State = WasmFunctionType::Tombstone;
899e15f359SSam Clegg     return FuncTy;
909e15f359SSam Clegg   }
919e15f359SSam Clegg   static unsigned getHashValue(const WasmFunctionType &FuncTy) {
929e15f359SSam Clegg     uintptr_t Value = FuncTy.State;
939e15f359SSam Clegg     for (wasm::ValType Ret : FuncTy.Returns)
949e15f359SSam Clegg       Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Ret));
959e15f359SSam Clegg     for (wasm::ValType Param : FuncTy.Params)
969e15f359SSam Clegg       Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Param));
979e15f359SSam Clegg     return Value;
989e15f359SSam Clegg   }
999e15f359SSam Clegg   static bool isEqual(const WasmFunctionType &LHS,
1009e15f359SSam Clegg                       const WasmFunctionType &RHS) {
1019e15f359SSam Clegg     return LHS == RHS;
1029e15f359SSam Clegg   }
1039e15f359SSam Clegg };
1049e15f359SSam Clegg 
1057c395943SSam Clegg // A wasm data segment.  A wasm binary contains only a single data section
1067c395943SSam Clegg // but that can contain many segments, each with their own virtual location
1077c395943SSam Clegg // in memory.  Each MCSection data created by llvm is modeled as its own
1087c395943SSam Clegg // wasm data segment.
1097c395943SSam Clegg struct WasmDataSegment {
1107c395943SSam Clegg   MCSectionWasm *Section;
111d95ed959SSam Clegg   StringRef Name;
1127c395943SSam Clegg   uint32_t Offset;
11363ebb813SSam Clegg   uint32_t Alignment;
11463ebb813SSam Clegg   uint32_t Flags;
1157c395943SSam Clegg   SmallVector<char, 4> Data;
1167c395943SSam Clegg };
1177c395943SSam Clegg 
1189e15f359SSam Clegg // A wasm function to be written into the function section.
1199e15f359SSam Clegg struct WasmFunction {
1209e15f359SSam Clegg   int32_t Type;
1219e15f359SSam Clegg   const MCSymbolWasm *Sym;
1229e15f359SSam Clegg };
1239e15f359SSam Clegg 
1249e15f359SSam Clegg // A wasm global to be written into the global section.
1259e15f359SSam Clegg struct WasmGlobal {
1266e7f1826SSam Clegg   wasm::WasmGlobalType Type;
1279e15f359SSam Clegg   uint64_t InitialValue;
1289e15f359SSam Clegg };
1299e15f359SSam Clegg 
130ea7caceeSSam Clegg // Information about a single item which is part of a COMDAT.  For each data
131ea7caceeSSam Clegg // segment or function which is in the COMDAT, there is a corresponding
132ea7caceeSSam Clegg // WasmComdatEntry.
133ea7caceeSSam Clegg struct WasmComdatEntry {
134ea7caceeSSam Clegg   unsigned Kind;
135ea7caceeSSam Clegg   uint32_t Index;
136ea7caceeSSam Clegg };
137ea7caceeSSam Clegg 
1386dc65e91SSam Clegg // Information about a single relocation.
1396dc65e91SSam Clegg struct WasmRelocationEntry {
1406dc65e91SSam Clegg   uint64_t Offset;                  // Where is the relocation.
1416dc65e91SSam Clegg   const MCSymbolWasm *Symbol;       // The symbol to relocate with.
1426dc65e91SSam Clegg   int64_t Addend;                   // A value to add to the symbol.
1436dc65e91SSam Clegg   unsigned Type;                    // The type of the relocation.
144fe6414b0SSam Clegg   const MCSectionWasm *FixupSection;// The section the relocation is targeting.
1456dc65e91SSam Clegg 
1466dc65e91SSam Clegg   WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol,
1476dc65e91SSam Clegg                       int64_t Addend, unsigned Type,
148fe6414b0SSam Clegg                       const MCSectionWasm *FixupSection)
1496dc65e91SSam Clegg       : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type),
1506dc65e91SSam Clegg         FixupSection(FixupSection) {}
1516dc65e91SSam Clegg 
152acd7d2b0SSam Clegg   bool hasAddend() const {
153acd7d2b0SSam Clegg     switch (Type) {
15413a2e899SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
15513a2e899SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
15613a2e899SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
1576a31a0d6SSam Clegg     case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32:
1586a31a0d6SSam Clegg     case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32:
159acd7d2b0SSam Clegg       return true;
160acd7d2b0SSam Clegg     default:
161acd7d2b0SSam Clegg       return false;
162acd7d2b0SSam Clegg     }
163acd7d2b0SSam Clegg   }
164acd7d2b0SSam Clegg 
1656dc65e91SSam Clegg   void print(raw_ostream &Out) const {
166*5f87ab33SSam Clegg     Out << wasm::relocTypetoString(Type)
167a165f2d6SSam Clegg         << " Off=" << Offset << ", Sym=" << *Symbol << ", Addend=" << Addend
168759631c7SSam Clegg         << ", FixupSection=" << FixupSection->getSectionName();
1696dc65e91SSam Clegg   }
170b7787fd0SSam Clegg 
171615eb470SAaron Ballman #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
172b7787fd0SSam Clegg   LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
173b7787fd0SSam Clegg #endif
1746dc65e91SSam Clegg };
1756dc65e91SSam Clegg 
17625d8e68bSSam Clegg static const uint32_t INVALID_INDEX = -1;
17725d8e68bSSam Clegg 
178cfd44a2eSSam Clegg struct WasmCustomSection {
179cfd44a2eSSam Clegg 
1806a31a0d6SSam Clegg   StringRef Name;
1816a31a0d6SSam Clegg   MCSectionWasm *Section;
1826a31a0d6SSam Clegg 
1836a31a0d6SSam Clegg   uint32_t OutputContentsOffset;
1846a31a0d6SSam Clegg   uint32_t OutputIndex;
1856a31a0d6SSam Clegg 
1866a31a0d6SSam Clegg   WasmCustomSection(StringRef Name, MCSectionWasm *Section)
1876a31a0d6SSam Clegg       : Name(Name), Section(Section), OutputContentsOffset(0),
1886a31a0d6SSam Clegg         OutputIndex(INVALID_INDEX) {}
189cfd44a2eSSam Clegg };
190cfd44a2eSSam Clegg 
1911fb8daa6SSam Clegg #if !defined(NDEBUG)
1927f055deeSSam Clegg raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
193b7787fd0SSam Clegg   Rel.print(OS);
194b7787fd0SSam Clegg   return OS;
195b7787fd0SSam Clegg }
1961fb8daa6SSam Clegg #endif
197b7787fd0SSam Clegg 
19818eafb6cSDan Gohman class WasmObjectWriter : public MCObjectWriter {
19918eafb6cSDan Gohman   /// The target specific Wasm writer instance.
20018eafb6cSDan Gohman   std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
20118eafb6cSDan Gohman 
202d934cb88SDan Gohman   // Relocations for fixing up references in the code section.
203d934cb88SDan Gohman   std::vector<WasmRelocationEntry> CodeRelocations;
2046f08c84aSSam Clegg   uint32_t CodeSectionIndex;
205d934cb88SDan Gohman 
206d934cb88SDan Gohman   // Relocations for fixing up references in the data section.
207d934cb88SDan Gohman   std::vector<WasmRelocationEntry> DataRelocations;
2086f08c84aSSam Clegg   uint32_t DataSectionIndex;
209d934cb88SDan Gohman 
210d934cb88SDan Gohman   // Index values to use for fixing up call_indirect type indices.
211acd7d2b0SSam Clegg   // Maps function symbols to the index of the type of the function
212acd7d2b0SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
213d99f6078SSam Clegg   // Maps function symbols to the table element index space. Used
214d99f6078SSam Clegg   // for TABLE_INDEX relocation types (i.e. address taken functions).
215f9edbe95SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> TableIndices;
216a165f2d6SSam Clegg   // Maps function/global symbols to the function/global/section index space.
2176c899ba6SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> WasmIndices;
2186c899ba6SSam Clegg   // Maps data symbols to the Wasm segment and offset/size with the segment.
2196c899ba6SSam Clegg   DenseMap<const MCSymbolWasm *, wasm::WasmDataReference> DataLocations;
2206a31a0d6SSam Clegg 
2216a31a0d6SSam Clegg   // Stores output data (index, relocations, content offset) for custom
2226a31a0d6SSam Clegg   // section.
2236a31a0d6SSam Clegg   std::vector<WasmCustomSection> CustomSections;
2246a31a0d6SSam Clegg   // Relocations for fixing up references in the custom sections.
2256a31a0d6SSam Clegg   DenseMap<const MCSectionWasm *, std::vector<WasmRelocationEntry>>
2266a31a0d6SSam Clegg       CustomSectionsRelocations;
227acd7d2b0SSam Clegg 
228acd7d2b0SSam Clegg   DenseMap<WasmFunctionType, int32_t, WasmFunctionTypeDenseMapInfo>
229acd7d2b0SSam Clegg       FunctionTypeIndices;
2305e3d33a7SSam Clegg   SmallVector<WasmFunctionType, 4> FunctionTypes;
2317c395943SSam Clegg   SmallVector<WasmGlobal, 4> Globals;
2326c899ba6SSam Clegg   SmallVector<WasmDataSegment, 4> DataSegments;
2339f3fe42eSSam Clegg   unsigned NumFunctionImports = 0;
2347c395943SSam Clegg   unsigned NumGlobalImports = 0;
2357e1c3345SChandler Carruth   uint32_t SectionCount = 0;
236d934cb88SDan Gohman 
23718eafb6cSDan Gohman   // TargetObjectWriter wrappers.
23818eafb6cSDan Gohman   bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
239ae03c1e7SSam Clegg   unsigned getRelocType(const MCValue &Target, const MCFixup &Fixup) const {
240ae03c1e7SSam Clegg     return TargetObjectWriter->getRelocType(Target, Fixup);
24118eafb6cSDan Gohman   }
24218eafb6cSDan Gohman 
2432322a937SSam Clegg   void startSection(SectionBookkeeping &Section, unsigned SectionId);
2442322a937SSam Clegg   void startCustomSection(SectionBookkeeping &Section, StringRef Name);
245d934cb88SDan Gohman   void endSection(SectionBookkeeping &Section);
246d934cb88SDan Gohman 
24718eafb6cSDan Gohman public:
2481301a878SLang Hames   WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
2491301a878SLang Hames                    raw_pwrite_stream &OS)
2501301a878SLang Hames       : MCObjectWriter(OS, /*IsLittleEndian=*/true),
2511301a878SLang Hames         TargetObjectWriter(std::move(MOTW)) {}
25218eafb6cSDan Gohman 
25318eafb6cSDan Gohman   ~WasmObjectWriter() override;
25418eafb6cSDan Gohman 
2550917c9e4SDan Gohman private:
256acd7d2b0SSam Clegg   void reset() override {
257acd7d2b0SSam Clegg     CodeRelocations.clear();
258acd7d2b0SSam Clegg     DataRelocations.clear();
259acd7d2b0SSam Clegg     TypeIndices.clear();
2606c899ba6SSam Clegg     WasmIndices.clear();
261f9edbe95SSam Clegg     TableIndices.clear();
2626c899ba6SSam Clegg     DataLocations.clear();
2636a31a0d6SSam Clegg     CustomSectionsRelocations.clear();
264acd7d2b0SSam Clegg     FunctionTypeIndices.clear();
2655e3d33a7SSam Clegg     FunctionTypes.clear();
2667c395943SSam Clegg     Globals.clear();
2676c899ba6SSam Clegg     DataSegments.clear();
268acd7d2b0SSam Clegg     MCObjectWriter::reset();
2699f3fe42eSSam Clegg     NumFunctionImports = 0;
2707c395943SSam Clegg     NumGlobalImports = 0;
271acd7d2b0SSam Clegg   }
272acd7d2b0SSam Clegg 
27318eafb6cSDan Gohman   void writeHeader(const MCAssembler &Asm);
27418eafb6cSDan Gohman 
27518eafb6cSDan Gohman   void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
27618eafb6cSDan Gohman                         const MCFragment *Fragment, const MCFixup &Fixup,
277ceecfe5bSRafael Espindola                         MCValue Target, uint64_t &FixedValue) override;
27818eafb6cSDan Gohman 
27918eafb6cSDan Gohman   void executePostLayoutBinding(MCAssembler &Asm,
28018eafb6cSDan Gohman                                 const MCAsmLayout &Layout) override;
28118eafb6cSDan Gohman 
28218eafb6cSDan Gohman   void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
2839e15f359SSam Clegg 
284b7787fd0SSam Clegg   void writeString(const StringRef Str) {
285b7787fd0SSam Clegg     encodeULEB128(Str.size(), getStream());
286b7787fd0SSam Clegg     writeBytes(Str);
287b7787fd0SSam Clegg   }
288b7787fd0SSam Clegg 
2899e15f359SSam Clegg   void writeValueType(wasm::ValType Ty) {
29003e101f1SSam Clegg     write8(static_cast<uint8_t>(Ty));
2919e15f359SSam Clegg   }
2929e15f359SSam Clegg 
293457fb0b4SSam Clegg   void writeTypeSection(ArrayRef<WasmFunctionType> FunctionTypes);
2948defa952SSam Clegg   void writeImportSection(ArrayRef<wasm::WasmImport> Imports, uint32_t DataSize,
295f950b24aSSam Clegg                           uint32_t NumElements);
296457fb0b4SSam Clegg   void writeFunctionSection(ArrayRef<WasmFunction> Functions);
2977c395943SSam Clegg   void writeGlobalSection();
2988defa952SSam Clegg   void writeExportSection(ArrayRef<wasm::WasmExport> Exports);
299457fb0b4SSam Clegg   void writeElemSection(ArrayRef<uint32_t> TableElems);
3009e15f359SSam Clegg   void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
301457fb0b4SSam Clegg                         ArrayRef<WasmFunction> Functions);
3026c899ba6SSam Clegg   void writeDataSection();
3036f08c84aSSam Clegg   void writeRelocSection(uint32_t SectionIndex, StringRef Name,
3046f08c84aSSam Clegg                          ArrayRef<WasmRelocationEntry> Relocations);
30531a2c809SSam Clegg   void writeLinkingMetaDataSection(
30686b4a09aSSam Clegg       ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
307ea7caceeSSam Clegg       ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
308ea7caceeSSam Clegg       const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats);
3096a31a0d6SSam Clegg   void writeCustomSections(const MCAssembler &Asm, const MCAsmLayout &Layout);
3106a31a0d6SSam Clegg   void writeCustomRelocSections();
3116a31a0d6SSam Clegg   void
3126a31a0d6SSam Clegg   updateCustomSectionRelocations(const SmallVector<WasmFunction, 4> &Functions,
3136a31a0d6SSam Clegg                                  const MCAsmLayout &Layout);
314acd7d2b0SSam Clegg 
3157c395943SSam Clegg   uint32_t getProvisionalValue(const WasmRelocationEntry &RelEntry);
316acd7d2b0SSam Clegg   void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
317acd7d2b0SSam Clegg                         uint64_t ContentsOffset);
318acd7d2b0SSam Clegg 
319acd7d2b0SSam Clegg   uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
3205e3d33a7SSam Clegg   uint32_t getFunctionType(const MCSymbolWasm &Symbol);
3215e3d33a7SSam Clegg   uint32_t registerFunctionType(const MCSymbolWasm &Symbol);
32218eafb6cSDan Gohman };
3239e15f359SSam Clegg 
32418eafb6cSDan Gohman } // end anonymous namespace
32518eafb6cSDan Gohman 
32618eafb6cSDan Gohman WasmObjectWriter::~WasmObjectWriter() {}
32718eafb6cSDan Gohman 
328d934cb88SDan Gohman // Write out a section header and a patchable section size field.
329d934cb88SDan Gohman void WasmObjectWriter::startSection(SectionBookkeeping &Section,
3302322a937SSam Clegg                                     unsigned SectionId) {
331d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "startSection " << SectionId << "\n");
33203e101f1SSam Clegg   write8(SectionId);
333d934cb88SDan Gohman 
334d934cb88SDan Gohman   Section.SizeOffset = getStream().tell();
335d934cb88SDan Gohman 
336d934cb88SDan Gohman   // The section size. We don't know the size yet, so reserve enough space
337d934cb88SDan Gohman   // for any 32-bit value; we'll patch it later.
338d934cb88SDan Gohman   encodeULEB128(UINT32_MAX, getStream());
339d934cb88SDan Gohman 
340d934cb88SDan Gohman   // The position where the section starts, for measuring its size.
341d934cb88SDan Gohman   Section.ContentsOffset = getStream().tell();
3426a31a0d6SSam Clegg   Section.PayloadOffset = getStream().tell();
3436f08c84aSSam Clegg   Section.Index = SectionCount++;
344d934cb88SDan Gohman }
3452322a937SSam Clegg 
3462322a937SSam Clegg void WasmObjectWriter::startCustomSection(SectionBookkeeping &Section,
3472322a937SSam Clegg                                           StringRef Name) {
348d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "startCustomSection " << Name << "\n");
3492322a937SSam Clegg   startSection(Section, wasm::WASM_SEC_CUSTOM);
3506a31a0d6SSam Clegg 
3516a31a0d6SSam Clegg   // The position where the section header ends, for measuring its size.
3526a31a0d6SSam Clegg   Section.PayloadOffset = getStream().tell();
3536a31a0d6SSam Clegg 
3542322a937SSam Clegg   // Custom sections in wasm also have a string identifier.
3552322a937SSam Clegg   writeString(Name);
3566a31a0d6SSam Clegg 
3576a31a0d6SSam Clegg   // The position where the custom section starts.
3586a31a0d6SSam Clegg   Section.ContentsOffset = getStream().tell();
359d934cb88SDan Gohman }
360d934cb88SDan Gohman 
361d934cb88SDan Gohman // Now that the section is complete and we know how big it is, patch up the
362d934cb88SDan Gohman // section size field at the start of the section.
363d934cb88SDan Gohman void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
3646a31a0d6SSam Clegg   uint64_t Size = getStream().tell() - Section.PayloadOffset;
365d934cb88SDan Gohman   if (uint32_t(Size) != Size)
366d934cb88SDan Gohman     report_fatal_error("section size does not fit in a uint32_t");
367d934cb88SDan Gohman 
368d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "endSection size=" << Size << "\n");
369d934cb88SDan Gohman 
370d934cb88SDan Gohman   // Write the final section size to the payload_len field, which follows
371d934cb88SDan Gohman   // the section id byte.
372d934cb88SDan Gohman   uint8_t Buffer[16];
37366a99e41SSam Clegg   unsigned SizeLen = encodeULEB128(Size, Buffer, 5);
374d934cb88SDan Gohman   assert(SizeLen == 5);
375d934cb88SDan Gohman   getStream().pwrite((char *)Buffer, SizeLen, Section.SizeOffset);
376d934cb88SDan Gohman }
377d934cb88SDan Gohman 
37818eafb6cSDan Gohman // Emit the Wasm header.
37918eafb6cSDan Gohman void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
3807ea5adffSDan Gohman   writeBytes(StringRef(wasm::WasmMagic, sizeof(wasm::WasmMagic)));
3817ea5adffSDan Gohman   writeLE32(wasm::WasmVersion);
38218eafb6cSDan Gohman }
38318eafb6cSDan Gohman 
38418eafb6cSDan Gohman void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
38518eafb6cSDan Gohman                                                 const MCAsmLayout &Layout) {
38618eafb6cSDan Gohman }
38718eafb6cSDan Gohman 
38818eafb6cSDan Gohman void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
38918eafb6cSDan Gohman                                         const MCAsmLayout &Layout,
39018eafb6cSDan Gohman                                         const MCFragment *Fragment,
39118eafb6cSDan Gohman                                         const MCFixup &Fixup, MCValue Target,
392ceecfe5bSRafael Espindola                                         uint64_t &FixedValue) {
393ceecfe5bSRafael Espindola   MCAsmBackend &Backend = Asm.getBackend();
394ceecfe5bSRafael Espindola   bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
395ceecfe5bSRafael Espindola                  MCFixupKindInfo::FKF_IsPCRel;
396fe6414b0SSam Clegg   const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
397d934cb88SDan Gohman   uint64_t C = Target.getConstant();
398d934cb88SDan Gohman   uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
399d934cb88SDan Gohman   MCContext &Ctx = Asm.getContext();
400d934cb88SDan Gohman 
401bafe6902SSam Clegg   // The .init_array isn't translated as data, so don't do relocations in it.
402bafe6902SSam Clegg   if (FixupSection.getSectionName().startswith(".init_array"))
403bafe6902SSam Clegg     return;
404bafe6902SSam Clegg 
405d934cb88SDan Gohman   if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
406d934cb88SDan Gohman     assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
407d934cb88SDan Gohman            "Should not have constructed this");
408d934cb88SDan Gohman 
409d934cb88SDan Gohman     // Let A, B and C being the components of Target and R be the location of
410d934cb88SDan Gohman     // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
411d934cb88SDan Gohman     // If it is pcrel, we want to compute (A - B + C - R).
412d934cb88SDan Gohman 
413d934cb88SDan Gohman     // In general, Wasm has no relocations for -B. It can only represent (A + C)
414d934cb88SDan Gohman     // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
415d934cb88SDan Gohman     // replace B to implement it: (A - R - K + C)
416d934cb88SDan Gohman     if (IsPCRel) {
417d934cb88SDan Gohman       Ctx.reportError(
418d934cb88SDan Gohman           Fixup.getLoc(),
419d934cb88SDan Gohman           "No relocation available to represent this relative expression");
420d934cb88SDan Gohman       return;
421d934cb88SDan Gohman     }
422d934cb88SDan Gohman 
423d934cb88SDan Gohman     const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
424d934cb88SDan Gohman 
425d934cb88SDan Gohman     if (SymB.isUndefined()) {
426d934cb88SDan Gohman       Ctx.reportError(Fixup.getLoc(),
427d934cb88SDan Gohman                       Twine("symbol '") + SymB.getName() +
428d934cb88SDan Gohman                           "' can not be undefined in a subtraction expression");
429d934cb88SDan Gohman       return;
430d934cb88SDan Gohman     }
431d934cb88SDan Gohman 
432d934cb88SDan Gohman     assert(!SymB.isAbsolute() && "Should have been folded");
433d934cb88SDan Gohman     const MCSection &SecB = SymB.getSection();
434d934cb88SDan Gohman     if (&SecB != &FixupSection) {
435d934cb88SDan Gohman       Ctx.reportError(Fixup.getLoc(),
436d934cb88SDan Gohman                       "Cannot represent a difference across sections");
437d934cb88SDan Gohman       return;
438d934cb88SDan Gohman     }
439d934cb88SDan Gohman 
440d934cb88SDan Gohman     uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
441d934cb88SDan Gohman     uint64_t K = SymBOffset - FixupOffset;
442d934cb88SDan Gohman     IsPCRel = true;
443d934cb88SDan Gohman     C -= K;
444d934cb88SDan Gohman   }
445d934cb88SDan Gohman 
446d934cb88SDan Gohman   // We either rejected the fixup or folded B into C at this point.
447d934cb88SDan Gohman   const MCSymbolRefExpr *RefA = Target.getSymA();
448d934cb88SDan Gohman   const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr;
449d934cb88SDan Gohman 
450d934cb88SDan Gohman   if (SymA && SymA->isVariable()) {
451d934cb88SDan Gohman     const MCExpr *Expr = SymA->getVariableValue();
4526ad8f190SSam Clegg     const auto *Inner = cast<MCSymbolRefExpr>(Expr);
4536ad8f190SSam Clegg     if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
4546ad8f190SSam Clegg       llvm_unreachable("weakref used in reloc not yet implemented");
455d934cb88SDan Gohman   }
456d934cb88SDan Gohman 
457d934cb88SDan Gohman   // Put any constant offset in an addend. Offsets can be negative, and
458d934cb88SDan Gohman   // LLVM expects wrapping, in contrast to wasm's immediates which can't
459d934cb88SDan Gohman   // be negative and don't wrap.
460d934cb88SDan Gohman   FixedValue = 0;
461d934cb88SDan Gohman 
4624d57fbd0SSam Clegg   unsigned Type = getRelocType(Target, Fixup);
463ae03c1e7SSam Clegg   assert(!IsPCRel);
4649d24fb7fSSam Clegg   assert(SymA);
4659d24fb7fSSam Clegg 
4664d57fbd0SSam Clegg   // Absolute offset within a section or a function.
4674d57fbd0SSam Clegg   // Currently only supported for for metadata sections.
4684d57fbd0SSam Clegg   // See: test/MC/WebAssembly/blockaddress.ll
4694d57fbd0SSam Clegg   if (Type == wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32 ||
4704d57fbd0SSam Clegg       Type == wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32) {
4714d57fbd0SSam Clegg     if (!FixupSection.getKind().isMetadata())
4724d57fbd0SSam Clegg       report_fatal_error("relocations for function or section offsets are "
4734d57fbd0SSam Clegg                          "only supported in metadata sections");
4744d57fbd0SSam Clegg 
4754d57fbd0SSam Clegg     const MCSymbol *SectionSymbol = nullptr;
4764d57fbd0SSam Clegg     const MCSection &SecA = SymA->getSection();
4774d57fbd0SSam Clegg     if (SecA.getKind().isText())
4784d57fbd0SSam Clegg       SectionSymbol = SecA.begin()->getAtom();
4794d57fbd0SSam Clegg     else
4804d57fbd0SSam Clegg       SectionSymbol = SecA.getBeginSymbol();
4814d57fbd0SSam Clegg     if (!SectionSymbol)
4824d57fbd0SSam Clegg       report_fatal_error("section symbol is required for relocation");
4834d57fbd0SSam Clegg 
4844d57fbd0SSam Clegg     C += Layout.getSymbolOffset(*SymA);
4854d57fbd0SSam Clegg     SymA = cast<MCSymbolWasm>(SectionSymbol);
4864d57fbd0SSam Clegg   }
4874d57fbd0SSam Clegg 
4884d57fbd0SSam Clegg   // Relocation other than R_WEBASSEMBLY_TYPE_INDEX_LEB are required to be
4894d57fbd0SSam Clegg   // against a named symbol.
4904d57fbd0SSam Clegg   if (Type != wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB) {
4914d57fbd0SSam Clegg     if (SymA->getName().empty())
4924d57fbd0SSam Clegg       report_fatal_error("relocations against un-named temporaries are not yet "
4934d57fbd0SSam Clegg                          "supported by wasm");
4944d57fbd0SSam Clegg 
4954d57fbd0SSam Clegg     SymA->setUsedInReloc();
4964d57fbd0SSam Clegg   }
497ae03c1e7SSam Clegg 
498d934cb88SDan Gohman   WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
499d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
500d934cb88SDan Gohman 
5016a31a0d6SSam Clegg   if (FixupSection.isWasmData()) {
502d934cb88SDan Gohman     DataRelocations.push_back(Rec);
5036a31a0d6SSam Clegg   } else if (FixupSection.getKind().isText()) {
50412fd3da9SSam Clegg     CodeRelocations.push_back(Rec);
5056a31a0d6SSam Clegg   } else if (FixupSection.getKind().isMetadata()) {
5066a31a0d6SSam Clegg     CustomSectionsRelocations[&FixupSection].push_back(Rec);
5076a31a0d6SSam Clegg   } else {
50812fd3da9SSam Clegg     llvm_unreachable("unexpected section type");
509d934cb88SDan Gohman   }
5106a31a0d6SSam Clegg }
511d934cb88SDan Gohman 
512d934cb88SDan Gohman // Write X as an (unsigned) LEB value at offset Offset in Stream, padded
513d934cb88SDan Gohman // to allow patching.
514d934cb88SDan Gohman static void
515d934cb88SDan Gohman WritePatchableLEB(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
516d934cb88SDan Gohman   uint8_t Buffer[5];
51766a99e41SSam Clegg   unsigned SizeLen = encodeULEB128(X, Buffer, 5);
518d934cb88SDan Gohman   assert(SizeLen == 5);
519d934cb88SDan Gohman   Stream.pwrite((char *)Buffer, SizeLen, Offset);
520d934cb88SDan Gohman }
521d934cb88SDan Gohman 
522d934cb88SDan Gohman // Write X as an signed LEB value at offset Offset in Stream, padded
523d934cb88SDan Gohman // to allow patching.
524d934cb88SDan Gohman static void
525d934cb88SDan Gohman WritePatchableSLEB(raw_pwrite_stream &Stream, int32_t X, uint64_t Offset) {
526d934cb88SDan Gohman   uint8_t Buffer[5];
52766a99e41SSam Clegg   unsigned SizeLen = encodeSLEB128(X, Buffer, 5);
528d934cb88SDan Gohman   assert(SizeLen == 5);
529d934cb88SDan Gohman   Stream.pwrite((char *)Buffer, SizeLen, Offset);
530d934cb88SDan Gohman }
531d934cb88SDan Gohman 
532d934cb88SDan Gohman // Write X as a plain integer value at offset Offset in Stream.
533d934cb88SDan Gohman static void WriteI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
534d934cb88SDan Gohman   uint8_t Buffer[4];
535d934cb88SDan Gohman   support::endian::write32le(Buffer, X);
536d934cb88SDan Gohman   Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
537d934cb88SDan Gohman }
538d934cb88SDan Gohman 
539aff1c4dfSSam Clegg static const MCSymbolWasm* ResolveSymbol(const MCSymbolWasm& Symbol) {
540aff1c4dfSSam Clegg   if (Symbol.isVariable()) {
541aff1c4dfSSam Clegg     const MCExpr *Expr = Symbol.getVariableValue();
542aff1c4dfSSam Clegg     auto *Inner = cast<MCSymbolRefExpr>(Expr);
543aff1c4dfSSam Clegg     return cast<MCSymbolWasm>(&Inner->getSymbol());
544aff1c4dfSSam Clegg   }
545aff1c4dfSSam Clegg   return &Symbol;
546aff1c4dfSSam Clegg }
547aff1c4dfSSam Clegg 
548d934cb88SDan Gohman // Compute a value to write into the code at the location covered
54960ec3034SSam Clegg // by RelEntry. This value isn't used by the static linker; it just serves
55060ec3034SSam Clegg // to make the object format more readable and more likely to be directly
55160ec3034SSam Clegg // useable.
5527c395943SSam Clegg uint32_t
5537c395943SSam Clegg WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) {
55460ec3034SSam Clegg   switch (RelEntry.Type) {
55560ec3034SSam Clegg   case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
556f9edbe95SSam Clegg   case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: {
557f9edbe95SSam Clegg     // Provisional value is table address of the resolved symbol itself
558f9edbe95SSam Clegg     const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
559f9edbe95SSam Clegg     assert(Sym->isFunction());
560f9edbe95SSam Clegg     return TableIndices[Sym];
561f9edbe95SSam Clegg   }
56260ec3034SSam Clegg   case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
5636c899ba6SSam Clegg     // Provisional value is same as the index
56460ec3034SSam Clegg     return getRelocationIndexValue(RelEntry);
5656c899ba6SSam Clegg   case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
5666c899ba6SSam Clegg   case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
5676c899ba6SSam Clegg     // Provisional value is function/global Wasm index
5686c899ba6SSam Clegg     if (!WasmIndices.count(RelEntry.Symbol))
5696c899ba6SSam Clegg       report_fatal_error("symbol not found in wasm index space: " +
5706c899ba6SSam Clegg                          RelEntry.Symbol->getName());
5716c899ba6SSam Clegg     return WasmIndices[RelEntry.Symbol];
5724d57fbd0SSam Clegg   case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32:
5734d57fbd0SSam Clegg   case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32: {
5746a31a0d6SSam Clegg     const auto &Section =
5756a31a0d6SSam Clegg         static_cast<const MCSectionWasm &>(RelEntry.Symbol->getSection());
5766a31a0d6SSam Clegg     return Section.getSectionOffset() + RelEntry.Addend;
5776a31a0d6SSam Clegg   }
57860ec3034SSam Clegg   case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
57960ec3034SSam Clegg   case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
58060ec3034SSam Clegg   case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: {
581f9edbe95SSam Clegg     // Provisional value is address of the global
58260ec3034SSam Clegg     const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
583270ed1b3SSam Clegg     // For undefined symbols, use zero
584cd65f698SSam Clegg     if (!Sym->isDefined())
585270ed1b3SSam Clegg       return 0;
5866c899ba6SSam Clegg     const wasm::WasmDataReference &Ref = DataLocations[Sym];
5876c899ba6SSam Clegg     const WasmDataSegment &Segment = DataSegments[Ref.Segment];
588d934cb88SDan Gohman     // Ignore overflow. LLVM allows address arithmetic to silently wrap.
5896c899ba6SSam Clegg     return Segment.Offset + Ref.Offset + RelEntry.Addend;
59060ec3034SSam Clegg   }
59160ec3034SSam Clegg   default:
59260ec3034SSam Clegg     llvm_unreachable("invalid relocation type");
59360ec3034SSam Clegg   }
594d934cb88SDan Gohman }
595d934cb88SDan Gohman 
596759631c7SSam Clegg static void addData(SmallVectorImpl<char> &DataBytes,
59763ebb813SSam Clegg                     MCSectionWasm &DataSection) {
598d34e60caSNicola Zaghen   LLVM_DEBUG(errs() << "addData: " << DataSection.getSectionName() << "\n");
599759631c7SSam Clegg 
60063ebb813SSam Clegg   DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
60163ebb813SSam Clegg 
602759631c7SSam Clegg   for (const MCFragment &Frag : DataSection) {
603759631c7SSam Clegg     if (Frag.hasInstructions())
604759631c7SSam Clegg       report_fatal_error("only data supported in data sections");
605759631c7SSam Clegg 
606759631c7SSam Clegg     if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
607759631c7SSam Clegg       if (Align->getValueSize() != 1)
608759631c7SSam Clegg         report_fatal_error("only byte values supported for alignment");
609759631c7SSam Clegg       // If nops are requested, use zeros, as this is the data section.
610759631c7SSam Clegg       uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
611759631c7SSam Clegg       uint64_t Size = std::min<uint64_t>(alignTo(DataBytes.size(),
612759631c7SSam Clegg                                                  Align->getAlignment()),
613759631c7SSam Clegg                                          DataBytes.size() +
614759631c7SSam Clegg                                              Align->getMaxBytesToEmit());
615759631c7SSam Clegg       DataBytes.resize(Size, Value);
616759631c7SSam Clegg     } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
617d707c370SRafael Espindola       int64_t Size;
618d707c370SRafael Espindola       if (!Fill->getSize().evaluateAsAbsolute(Size))
619d707c370SRafael Espindola         llvm_unreachable("The fill should be an assembler constant");
620d707c370SRafael Espindola       DataBytes.insert(DataBytes.end(), Size, Fill->getValue());
621759631c7SSam Clegg     } else {
622759631c7SSam Clegg       const auto &DataFrag = cast<MCDataFragment>(Frag);
623759631c7SSam Clegg       const SmallVectorImpl<char> &Contents = DataFrag.getContents();
624759631c7SSam Clegg 
625759631c7SSam Clegg       DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
626759631c7SSam Clegg     }
627759631c7SSam Clegg   }
628759631c7SSam Clegg 
629d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
630759631c7SSam Clegg }
631759631c7SSam Clegg 
63260ec3034SSam Clegg uint32_t
63360ec3034SSam Clegg WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
63460ec3034SSam Clegg   if (RelEntry.Type == wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB) {
635b7787fd0SSam Clegg     if (!TypeIndices.count(RelEntry.Symbol))
636b7787fd0SSam Clegg       report_fatal_error("symbol not found in type index space: " +
637b7787fd0SSam Clegg                          RelEntry.Symbol->getName());
638acd7d2b0SSam Clegg     return TypeIndices[RelEntry.Symbol];
639acd7d2b0SSam Clegg   }
64060ec3034SSam Clegg 
64125d8e68bSSam Clegg   return RelEntry.Symbol->getIndex();
642acd7d2b0SSam Clegg }
643acd7d2b0SSam Clegg 
644d934cb88SDan Gohman // Apply the portions of the relocation records that we can handle ourselves
645d934cb88SDan Gohman // directly.
646acd7d2b0SSam Clegg void WasmObjectWriter::applyRelocations(
647acd7d2b0SSam Clegg     ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
648acd7d2b0SSam Clegg   raw_pwrite_stream &Stream = getStream();
649d934cb88SDan Gohman   for (const WasmRelocationEntry &RelEntry : Relocations) {
650d934cb88SDan Gohman     uint64_t Offset = ContentsOffset +
651d934cb88SDan Gohman                       RelEntry.FixupSection->getSectionOffset() +
652d934cb88SDan Gohman                       RelEntry.Offset;
653d934cb88SDan Gohman 
654d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
65560ec3034SSam Clegg     uint32_t Value = getProvisionalValue(RelEntry);
65660ec3034SSam Clegg 
657acd7d2b0SSam Clegg     switch (RelEntry.Type) {
658acd7d2b0SSam Clegg     case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
6599d24fb7fSSam Clegg     case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
66060ec3034SSam Clegg     case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
66160ec3034SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
662d934cb88SDan Gohman       WritePatchableLEB(Stream, Value, Offset);
663d934cb88SDan Gohman       break;
66460ec3034SSam Clegg     case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
66560ec3034SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
6666a31a0d6SSam Clegg     case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32:
6676a31a0d6SSam Clegg     case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32:
668d934cb88SDan Gohman       WriteI32(Stream, Value, Offset);
669d934cb88SDan Gohman       break;
67060ec3034SSam Clegg     case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
67160ec3034SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
67260ec3034SSam Clegg       WritePatchableSLEB(Stream, Value, Offset);
67360ec3034SSam Clegg       break;
674d934cb88SDan Gohman     default:
6759d24fb7fSSam Clegg       llvm_unreachable("invalid relocation type");
676d934cb88SDan Gohman     }
677d934cb88SDan Gohman   }
67818eafb6cSDan Gohman }
67918eafb6cSDan Gohman 
6809e15f359SSam Clegg void WasmObjectWriter::writeTypeSection(
681457fb0b4SSam Clegg     ArrayRef<WasmFunctionType> FunctionTypes) {
6829e15f359SSam Clegg   if (FunctionTypes.empty())
6839e15f359SSam Clegg     return;
6849e15f359SSam Clegg 
6859e15f359SSam Clegg   SectionBookkeeping Section;
6869e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_TYPE);
6879e15f359SSam Clegg 
6889e15f359SSam Clegg   encodeULEB128(FunctionTypes.size(), getStream());
6899e15f359SSam Clegg 
6909e15f359SSam Clegg   for (const WasmFunctionType &FuncTy : FunctionTypes) {
69103e101f1SSam Clegg     write8(wasm::WASM_TYPE_FUNC);
6929e15f359SSam Clegg     encodeULEB128(FuncTy.Params.size(), getStream());
6939e15f359SSam Clegg     for (wasm::ValType Ty : FuncTy.Params)
6949e15f359SSam Clegg       writeValueType(Ty);
6959e15f359SSam Clegg     encodeULEB128(FuncTy.Returns.size(), getStream());
6969e15f359SSam Clegg     for (wasm::ValType Ty : FuncTy.Returns)
6979e15f359SSam Clegg       writeValueType(Ty);
6989e15f359SSam Clegg   }
6999e15f359SSam Clegg 
7009e15f359SSam Clegg   endSection(Section);
7019e15f359SSam Clegg }
7029e15f359SSam Clegg 
7038defa952SSam Clegg void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports,
704f950b24aSSam Clegg                                           uint32_t DataSize,
705f950b24aSSam Clegg                                           uint32_t NumElements) {
7069e15f359SSam Clegg   if (Imports.empty())
7079e15f359SSam Clegg     return;
7089e15f359SSam Clegg 
709f950b24aSSam Clegg   uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
710f950b24aSSam Clegg 
7119e15f359SSam Clegg   SectionBookkeeping Section;
7129e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_IMPORT);
7139e15f359SSam Clegg 
7149e15f359SSam Clegg   encodeULEB128(Imports.size(), getStream());
7158defa952SSam Clegg   for (const wasm::WasmImport &Import : Imports) {
7168defa952SSam Clegg     writeString(Import.Module);
7178defa952SSam Clegg     writeString(Import.Field);
71803e101f1SSam Clegg     write8(Import.Kind);
7199e15f359SSam Clegg 
7209e15f359SSam Clegg     switch (Import.Kind) {
7219e15f359SSam Clegg     case wasm::WASM_EXTERNAL_FUNCTION:
7228defa952SSam Clegg       encodeULEB128(Import.SigIndex, getStream());
7239e15f359SSam Clegg       break;
7249e15f359SSam Clegg     case wasm::WASM_EXTERNAL_GLOBAL:
72503e101f1SSam Clegg       write8(Import.Global.Type);
72603e101f1SSam Clegg       write8(Import.Global.Mutable ? 1 : 0);
7279e15f359SSam Clegg       break;
728f950b24aSSam Clegg     case wasm::WASM_EXTERNAL_MEMORY:
729f950b24aSSam Clegg       encodeULEB128(0, getStream()); // flags
730f950b24aSSam Clegg       encodeULEB128(NumPages, getStream()); // initial
731f950b24aSSam Clegg       break;
732f950b24aSSam Clegg     case wasm::WASM_EXTERNAL_TABLE:
73303e101f1SSam Clegg       write8(Import.Table.ElemType);
734f950b24aSSam Clegg       encodeULEB128(0, getStream()); // flags
735f950b24aSSam Clegg       encodeULEB128(NumElements, getStream()); // initial
736f950b24aSSam Clegg       break;
7379e15f359SSam Clegg     default:
7389e15f359SSam Clegg       llvm_unreachable("unsupported import kind");
7399e15f359SSam Clegg     }
7409e15f359SSam Clegg   }
7419e15f359SSam Clegg 
7429e15f359SSam Clegg   endSection(Section);
7439e15f359SSam Clegg }
7449e15f359SSam Clegg 
745457fb0b4SSam Clegg void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
7469e15f359SSam Clegg   if (Functions.empty())
7479e15f359SSam Clegg     return;
7489e15f359SSam Clegg 
7499e15f359SSam Clegg   SectionBookkeeping Section;
7509e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_FUNCTION);
7519e15f359SSam Clegg 
7529e15f359SSam Clegg   encodeULEB128(Functions.size(), getStream());
7539e15f359SSam Clegg   for (const WasmFunction &Func : Functions)
7549e15f359SSam Clegg     encodeULEB128(Func.Type, getStream());
7559e15f359SSam Clegg 
7569e15f359SSam Clegg   endSection(Section);
7579e15f359SSam Clegg }
7589e15f359SSam Clegg 
7597c395943SSam Clegg void WasmObjectWriter::writeGlobalSection() {
7609e15f359SSam Clegg   if (Globals.empty())
7619e15f359SSam Clegg     return;
7629e15f359SSam Clegg 
7639e15f359SSam Clegg   SectionBookkeeping Section;
7649e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_GLOBAL);
7659e15f359SSam Clegg 
7669e15f359SSam Clegg   encodeULEB128(Globals.size(), getStream());
7679e15f359SSam Clegg   for (const WasmGlobal &Global : Globals) {
7686e7f1826SSam Clegg     writeValueType(static_cast<wasm::ValType>(Global.Type.Type));
7696e7f1826SSam Clegg     write8(Global.Type.Mutable);
7709e15f359SSam Clegg 
7719e15f359SSam Clegg     write8(wasm::WASM_OPCODE_I32_CONST);
7726e7f1826SSam Clegg     encodeSLEB128(Global.InitialValue, getStream());
7739e15f359SSam Clegg     write8(wasm::WASM_OPCODE_END);
7749e15f359SSam Clegg   }
7759e15f359SSam Clegg 
7769e15f359SSam Clegg   endSection(Section);
7779e15f359SSam Clegg }
7789e15f359SSam Clegg 
7798defa952SSam Clegg void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) {
7809e15f359SSam Clegg   if (Exports.empty())
7819e15f359SSam Clegg     return;
7829e15f359SSam Clegg 
7839e15f359SSam Clegg   SectionBookkeeping Section;
7849e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_EXPORT);
7859e15f359SSam Clegg 
7869e15f359SSam Clegg   encodeULEB128(Exports.size(), getStream());
7878defa952SSam Clegg   for (const wasm::WasmExport &Export : Exports) {
7888defa952SSam Clegg     writeString(Export.Name);
78903e101f1SSam Clegg     write8(Export.Kind);
7909e15f359SSam Clegg     encodeULEB128(Export.Index, getStream());
7919e15f359SSam Clegg   }
7929e15f359SSam Clegg 
7939e15f359SSam Clegg   endSection(Section);
7949e15f359SSam Clegg }
7959e15f359SSam Clegg 
796457fb0b4SSam Clegg void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
7979e15f359SSam Clegg   if (TableElems.empty())
7989e15f359SSam Clegg     return;
7999e15f359SSam Clegg 
8009e15f359SSam Clegg   SectionBookkeeping Section;
8019e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_ELEM);
8029e15f359SSam Clegg 
8039e15f359SSam Clegg   encodeULEB128(1, getStream()); // number of "segments"
8049e15f359SSam Clegg   encodeULEB128(0, getStream()); // the table index
8059e15f359SSam Clegg 
8069e15f359SSam Clegg   // init expr for starting offset
8079e15f359SSam Clegg   write8(wasm::WASM_OPCODE_I32_CONST);
80830e1bbc1SSam Clegg   encodeSLEB128(kInitialTableOffset, getStream());
8099e15f359SSam Clegg   write8(wasm::WASM_OPCODE_END);
8109e15f359SSam Clegg 
8119e15f359SSam Clegg   encodeULEB128(TableElems.size(), getStream());
8129e15f359SSam Clegg   for (uint32_t Elem : TableElems)
8139e15f359SSam Clegg     encodeULEB128(Elem, getStream());
8149e15f359SSam Clegg 
8159e15f359SSam Clegg   endSection(Section);
8169e15f359SSam Clegg }
8179e15f359SSam Clegg 
818457fb0b4SSam Clegg void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
819457fb0b4SSam Clegg                                         const MCAsmLayout &Layout,
820457fb0b4SSam Clegg                                         ArrayRef<WasmFunction> Functions) {
8219e15f359SSam Clegg   if (Functions.empty())
8229e15f359SSam Clegg     return;
8239e15f359SSam Clegg 
8249e15f359SSam Clegg   SectionBookkeeping Section;
8259e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_CODE);
8266f08c84aSSam Clegg   CodeSectionIndex = Section.Index;
8279e15f359SSam Clegg 
8289e15f359SSam Clegg   encodeULEB128(Functions.size(), getStream());
8299e15f359SSam Clegg 
8309e15f359SSam Clegg   for (const WasmFunction &Func : Functions) {
831fe6414b0SSam Clegg     auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
8329e15f359SSam Clegg 
8339e15f359SSam Clegg     int64_t Size = 0;
8349e15f359SSam Clegg     if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
8359e15f359SSam Clegg       report_fatal_error(".size expression must be evaluatable");
8369e15f359SSam Clegg 
8379e15f359SSam Clegg     encodeULEB128(Size, getStream());
838fe6414b0SSam Clegg     FuncSection.setSectionOffset(getStream().tell() - Section.ContentsOffset);
8399e15f359SSam Clegg     Asm.writeSectionData(&FuncSection, Layout);
8409e15f359SSam Clegg   }
8419e15f359SSam Clegg 
8429e15f359SSam Clegg   // Apply fixups.
843acd7d2b0SSam Clegg   applyRelocations(CodeRelocations, Section.ContentsOffset);
8449e15f359SSam Clegg 
8459e15f359SSam Clegg   endSection(Section);
8469e15f359SSam Clegg }
8479e15f359SSam Clegg 
8486c899ba6SSam Clegg void WasmObjectWriter::writeDataSection() {
8496c899ba6SSam Clegg   if (DataSegments.empty())
8507c395943SSam Clegg     return;
8519e15f359SSam Clegg 
8529e15f359SSam Clegg   SectionBookkeeping Section;
8539e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_DATA);
8546f08c84aSSam Clegg   DataSectionIndex = Section.Index;
8559e15f359SSam Clegg 
8566c899ba6SSam Clegg   encodeULEB128(DataSegments.size(), getStream()); // count
8577c395943SSam Clegg 
8586c899ba6SSam Clegg   for (const WasmDataSegment &Segment : DataSegments) {
8599e15f359SSam Clegg     encodeULEB128(0, getStream()); // memory index
8609e15f359SSam Clegg     write8(wasm::WASM_OPCODE_I32_CONST);
8617c395943SSam Clegg     encodeSLEB128(Segment.Offset, getStream()); // offset
8629e15f359SSam Clegg     write8(wasm::WASM_OPCODE_END);
8637c395943SSam Clegg     encodeULEB128(Segment.Data.size(), getStream()); // size
8647c395943SSam Clegg     Segment.Section->setSectionOffset(getStream().tell() - Section.ContentsOffset);
8657c395943SSam Clegg     writeBytes(Segment.Data); // data
8667c395943SSam Clegg   }
8679e15f359SSam Clegg 
8689e15f359SSam Clegg   // Apply fixups.
8697c395943SSam Clegg   applyRelocations(DataRelocations, Section.ContentsOffset);
8709e15f359SSam Clegg 
8719e15f359SSam Clegg   endSection(Section);
8729e15f359SSam Clegg }
8739e15f359SSam Clegg 
8746f08c84aSSam Clegg void WasmObjectWriter::writeRelocSection(
8756f08c84aSSam Clegg     uint32_t SectionIndex, StringRef Name,
8766f08c84aSSam Clegg     ArrayRef<WasmRelocationEntry> Relocations) {
8779e15f359SSam Clegg   // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
8789e15f359SSam Clegg   // for descriptions of the reloc sections.
8799e15f359SSam Clegg 
8806f08c84aSSam Clegg   if (Relocations.empty())
8819e15f359SSam Clegg     return;
8829e15f359SSam Clegg 
8839e15f359SSam Clegg   SectionBookkeeping Section;
8846f08c84aSSam Clegg   startCustomSection(Section, std::string("reloc.") + Name.str());
8859e15f359SSam Clegg 
8866f08c84aSSam Clegg   raw_pwrite_stream &Stream = getStream();
8879e15f359SSam Clegg 
8886f08c84aSSam Clegg   encodeULEB128(SectionIndex, Stream);
8896f08c84aSSam Clegg   encodeULEB128(Relocations.size(), Stream);
8906f08c84aSSam Clegg   for (const WasmRelocationEntry& RelEntry : Relocations) {
8916f08c84aSSam Clegg     uint64_t Offset = RelEntry.Offset +
8926f08c84aSSam Clegg                       RelEntry.FixupSection->getSectionOffset();
8936f08c84aSSam Clegg     uint32_t Index = getRelocationIndexValue(RelEntry);
8949e15f359SSam Clegg 
8956f08c84aSSam Clegg     write8(RelEntry.Type);
8966f08c84aSSam Clegg     encodeULEB128(Offset, Stream);
8976f08c84aSSam Clegg     encodeULEB128(Index, Stream);
8986f08c84aSSam Clegg     if (RelEntry.hasAddend())
8996f08c84aSSam Clegg       encodeSLEB128(RelEntry.Addend, Stream);
9009e15f359SSam Clegg   }
9019e15f359SSam Clegg 
9029e15f359SSam Clegg   endSection(Section);
9039e15f359SSam Clegg }
9049e15f359SSam Clegg 
9056a31a0d6SSam Clegg void WasmObjectWriter::writeCustomRelocSections() {
9066a31a0d6SSam Clegg   for (const auto &Sec : CustomSections) {
9076a31a0d6SSam Clegg     auto &Relocations = CustomSectionsRelocations[Sec.Section];
9086a31a0d6SSam Clegg     writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations);
9096a31a0d6SSam Clegg   }
9106a31a0d6SSam Clegg }
9116a31a0d6SSam Clegg 
9129e15f359SSam Clegg void WasmObjectWriter::writeLinkingMetaDataSection(
91386b4a09aSSam Clegg     ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
914ea7caceeSSam Clegg     ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
915ea7caceeSSam Clegg     const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) {
9169e15f359SSam Clegg   SectionBookkeeping Section;
9172322a937SSam Clegg   startCustomSection(Section, "linking");
9186bb5a41fSSam Clegg   encodeULEB128(wasm::WasmMetadataVersion, getStream());
9199e15f359SSam Clegg 
9206bb5a41fSSam Clegg   SectionBookkeeping SubSection;
9216c899ba6SSam Clegg   if (SymbolInfos.size() != 0) {
9226c899ba6SSam Clegg     startSection(SubSection, wasm::WASM_SYMBOL_TABLE);
9236c899ba6SSam Clegg     encodeULEB128(SymbolInfos.size(), getStream());
9246c899ba6SSam Clegg     for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) {
9256c899ba6SSam Clegg       encodeULEB128(Sym.Kind, getStream());
9266c899ba6SSam Clegg       encodeULEB128(Sym.Flags, getStream());
9276c899ba6SSam Clegg       switch (Sym.Kind) {
9286c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_FUNCTION:
9296c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_GLOBAL:
9306c899ba6SSam Clegg         encodeULEB128(Sym.ElementIndex, getStream());
9316c899ba6SSam Clegg         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0)
9326c899ba6SSam Clegg           writeString(Sym.Name);
9336c899ba6SSam Clegg         break;
9346c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_DATA:
9356c899ba6SSam Clegg         writeString(Sym.Name);
9366c899ba6SSam Clegg         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) {
9376c899ba6SSam Clegg           encodeULEB128(Sym.DataRef.Segment, getStream());
9386c899ba6SSam Clegg           encodeULEB128(Sym.DataRef.Offset, getStream());
9396c899ba6SSam Clegg           encodeULEB128(Sym.DataRef.Size, getStream());
9406c899ba6SSam Clegg         }
9416c899ba6SSam Clegg         break;
9426a31a0d6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_SECTION: {
9436a31a0d6SSam Clegg         const uint32_t SectionIndex =
9446a31a0d6SSam Clegg             CustomSections[Sym.ElementIndex].OutputIndex;
9456a31a0d6SSam Clegg         encodeULEB128(SectionIndex, getStream());
9466a31a0d6SSam Clegg         break;
9476a31a0d6SSam Clegg       }
9486c899ba6SSam Clegg       default:
9496c899ba6SSam Clegg         llvm_unreachable("unexpected kind");
9506c899ba6SSam Clegg       }
951b7787fd0SSam Clegg     }
952b7787fd0SSam Clegg     endSection(SubSection);
953b7787fd0SSam Clegg   }
9549e15f359SSam Clegg 
9556c899ba6SSam Clegg   if (DataSegments.size()) {
95663ebb813SSam Clegg     startSection(SubSection, wasm::WASM_SEGMENT_INFO);
9576c899ba6SSam Clegg     encodeULEB128(DataSegments.size(), getStream());
9586c899ba6SSam Clegg     for (const WasmDataSegment &Segment : DataSegments) {
959d95ed959SSam Clegg       writeString(Segment.Name);
96063ebb813SSam Clegg       encodeULEB128(Segment.Alignment, getStream());
96163ebb813SSam Clegg       encodeULEB128(Segment.Flags, getStream());
96263ebb813SSam Clegg     }
963d95ed959SSam Clegg     endSection(SubSection);
964d95ed959SSam Clegg   }
965d95ed959SSam Clegg 
966bafe6902SSam Clegg   if (!InitFuncs.empty()) {
967bafe6902SSam Clegg     startSection(SubSection, wasm::WASM_INIT_FUNCS);
968bafe6902SSam Clegg     encodeULEB128(InitFuncs.size(), getStream());
969bafe6902SSam Clegg     for (auto &StartFunc : InitFuncs) {
970bafe6902SSam Clegg       encodeULEB128(StartFunc.first, getStream()); // priority
971bafe6902SSam Clegg       encodeULEB128(StartFunc.second, getStream()); // function index
972bafe6902SSam Clegg     }
973bafe6902SSam Clegg     endSection(SubSection);
974bafe6902SSam Clegg   }
975bafe6902SSam Clegg 
976ea7caceeSSam Clegg   if (Comdats.size()) {
977ea7caceeSSam Clegg     startSection(SubSection, wasm::WASM_COMDAT_INFO);
978ea7caceeSSam Clegg     encodeULEB128(Comdats.size(), getStream());
979ea7caceeSSam Clegg     for (const auto &C : Comdats) {
980ea7caceeSSam Clegg       writeString(C.first);
981ea7caceeSSam Clegg       encodeULEB128(0, getStream()); // flags for future use
982ea7caceeSSam Clegg       encodeULEB128(C.second.size(), getStream());
983ea7caceeSSam Clegg       for (const WasmComdatEntry &Entry : C.second) {
984ea7caceeSSam Clegg         encodeULEB128(Entry.Kind, getStream());
985ea7caceeSSam Clegg         encodeULEB128(Entry.Index, getStream());
986ea7caceeSSam Clegg       }
987ea7caceeSSam Clegg     }
988ea7caceeSSam Clegg     endSection(SubSection);
989ea7caceeSSam Clegg   }
990ea7caceeSSam Clegg 
9919e15f359SSam Clegg   endSection(Section);
9929e15f359SSam Clegg }
9939e15f359SSam Clegg 
9946a31a0d6SSam Clegg void WasmObjectWriter::writeCustomSections(const MCAssembler &Asm,
9956a31a0d6SSam Clegg                                            const MCAsmLayout &Layout) {
9966a31a0d6SSam Clegg   for (auto &CustomSection : CustomSections) {
997cfd44a2eSSam Clegg     SectionBookkeeping Section;
9986a31a0d6SSam Clegg     auto *Sec = CustomSection.Section;
9992322a937SSam Clegg     startCustomSection(Section, CustomSection.Name);
10006a31a0d6SSam Clegg 
10016a31a0d6SSam Clegg     Sec->setSectionOffset(getStream().tell() - Section.ContentsOffset);
10026a31a0d6SSam Clegg     Asm.writeSectionData(Sec, Layout);
10036a31a0d6SSam Clegg 
10046a31a0d6SSam Clegg     CustomSection.OutputContentsOffset = Section.ContentsOffset;
10056a31a0d6SSam Clegg     CustomSection.OutputIndex = Section.Index;
10066a31a0d6SSam Clegg 
1007cfd44a2eSSam Clegg     endSection(Section);
10086a31a0d6SSam Clegg 
10096a31a0d6SSam Clegg     // Apply fixups.
10104d57fbd0SSam Clegg     auto &Relocations = CustomSectionsRelocations[CustomSection.Section];
10114d57fbd0SSam Clegg     applyRelocations(Relocations, CustomSection.OutputContentsOffset);
10126a31a0d6SSam Clegg   }
10136a31a0d6SSam Clegg }
10146a31a0d6SSam Clegg 
10155e3d33a7SSam Clegg uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm& Symbol) {
10165e3d33a7SSam Clegg   assert(Symbol.isFunction());
10175e3d33a7SSam Clegg   assert(TypeIndices.count(&Symbol));
10185e3d33a7SSam Clegg   return TypeIndices[&Symbol];
10195e3d33a7SSam Clegg }
10205e3d33a7SSam Clegg 
10215e3d33a7SSam Clegg uint32_t WasmObjectWriter::registerFunctionType(const MCSymbolWasm& Symbol) {
10225e3d33a7SSam Clegg   assert(Symbol.isFunction());
10235e3d33a7SSam Clegg 
10245e3d33a7SSam Clegg   WasmFunctionType F;
1025aff1c4dfSSam Clegg   const MCSymbolWasm* ResolvedSym = ResolveSymbol(Symbol);
10265e3d33a7SSam Clegg   F.Returns = ResolvedSym->getReturns();
10275e3d33a7SSam Clegg   F.Params = ResolvedSym->getParams();
10285e3d33a7SSam Clegg 
10295e3d33a7SSam Clegg   auto Pair =
10305e3d33a7SSam Clegg       FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size()));
10315e3d33a7SSam Clegg   if (Pair.second)
10325e3d33a7SSam Clegg     FunctionTypes.push_back(F);
10335e3d33a7SSam Clegg   TypeIndices[&Symbol] = Pair.first->second;
10345e3d33a7SSam Clegg 
1035d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "registerFunctionType: " << Symbol
1036d34e60caSNicola Zaghen                     << " new:" << Pair.second << "\n");
1037d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
10385e3d33a7SSam Clegg   return Pair.first->second;
10395e3d33a7SSam Clegg }
10405e3d33a7SSam Clegg 
10414d57fbd0SSam Clegg static bool isInSymtab(const MCSymbolWasm &Sym) {
10424d57fbd0SSam Clegg   if (Sym.isUsedInReloc())
10434d57fbd0SSam Clegg     return true;
10444d57fbd0SSam Clegg 
10454d57fbd0SSam Clegg   if (Sym.isComdat() && !Sym.isDefined())
10464d57fbd0SSam Clegg     return false;
10474d57fbd0SSam Clegg 
10484d57fbd0SSam Clegg   if (Sym.isTemporary() && Sym.getName().empty())
10494d57fbd0SSam Clegg     return false;
10504d57fbd0SSam Clegg 
10514d57fbd0SSam Clegg   if (Sym.isTemporary() && Sym.isData() && !Sym.getSize())
10524d57fbd0SSam Clegg     return false;
10534d57fbd0SSam Clegg 
10544d57fbd0SSam Clegg   if (Sym.isSection())
10554d57fbd0SSam Clegg     return false;
10564d57fbd0SSam Clegg 
10574d57fbd0SSam Clegg   return true;
10584d57fbd0SSam Clegg }
10594d57fbd0SSam Clegg 
106018eafb6cSDan Gohman void WasmObjectWriter::writeObject(MCAssembler &Asm,
106118eafb6cSDan Gohman                                    const MCAsmLayout &Layout) {
1062d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
106382607f56SDan Gohman   MCContext &Ctx = Asm.getContext();
1064d934cb88SDan Gohman 
1065d934cb88SDan Gohman   // Collect information from the available symbols.
1066d934cb88SDan Gohman   SmallVector<WasmFunction, 4> Functions;
1067d934cb88SDan Gohman   SmallVector<uint32_t, 4> TableElems;
10688defa952SSam Clegg   SmallVector<wasm::WasmImport, 4> Imports;
10698defa952SSam Clegg   SmallVector<wasm::WasmExport, 4> Exports;
10706c899ba6SSam Clegg   SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos;
1071bafe6902SSam Clegg   SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
1072ea7caceeSSam Clegg   std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
10737c395943SSam Clegg   uint32_t DataSize = 0;
1074d934cb88SDan Gohman 
1075f950b24aSSam Clegg   // For now, always emit the memory import, since loads and stores are not
1076f950b24aSSam Clegg   // valid without it. In the future, we could perhaps be more clever and omit
1077f950b24aSSam Clegg   // it if there are no loads or stores.
1078f950b24aSSam Clegg   MCSymbolWasm *MemorySym =
1079f950b24aSSam Clegg       cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__linear_memory"));
10808defa952SSam Clegg   wasm::WasmImport MemImport;
10818defa952SSam Clegg   MemImport.Module = MemorySym->getModuleName();
10828defa952SSam Clegg   MemImport.Field = MemorySym->getName();
1083f950b24aSSam Clegg   MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
1084f950b24aSSam Clegg   Imports.push_back(MemImport);
1085f950b24aSSam Clegg 
1086f950b24aSSam Clegg   // For now, always emit the table section, since indirect calls are not
1087f950b24aSSam Clegg   // valid without it. In the future, we could perhaps be more clever and omit
1088f950b24aSSam Clegg   // it if there are no indirect calls.
1089f950b24aSSam Clegg   MCSymbolWasm *TableSym =
1090f950b24aSSam Clegg       cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__indirect_function_table"));
10918defa952SSam Clegg   wasm::WasmImport TableImport;
10928defa952SSam Clegg   TableImport.Module = TableSym->getModuleName();
10938defa952SSam Clegg   TableImport.Field = TableSym->getName();
1094f950b24aSSam Clegg   TableImport.Kind = wasm::WASM_EXTERNAL_TABLE;
10958defa952SSam Clegg   TableImport.Table.ElemType = wasm::WASM_TYPE_ANYFUNC;
1096f950b24aSSam Clegg   Imports.push_back(TableImport);
1097f950b24aSSam Clegg 
1098586320c0SNicholas Wilson   // Populate FunctionTypeIndices, and Imports and WasmIndices for undefined
1099586320c0SNicholas Wilson   // symbols.  This must be done before populating WasmIndices for defined
1100586320c0SNicholas Wilson   // symbols.
110132ce5ca0SDan Gohman   for (const MCSymbol &S : Asm.symbols()) {
110232ce5ca0SDan Gohman     const auto &WS = static_cast<const MCSymbolWasm &>(S);
110332ce5ca0SDan Gohman 
110432ce5ca0SDan Gohman     // Register types for all functions, including those with private linkage
11059f3fe42eSSam Clegg     // (because wasm always needs a type signature).
110632ce5ca0SDan Gohman     if (WS.isFunction())
110732ce5ca0SDan Gohman       registerFunctionType(WS);
110832ce5ca0SDan Gohman 
110932ce5ca0SDan Gohman     if (WS.isTemporary())
111032ce5ca0SDan Gohman       continue;
111132ce5ca0SDan Gohman 
111232ce5ca0SDan Gohman     // If the symbol is not defined in this translation unit, import it.
11136c899ba6SSam Clegg     if (!WS.isDefined() && !WS.isComdat()) {
11146c899ba6SSam Clegg       if (WS.isFunction()) {
11158defa952SSam Clegg         wasm::WasmImport Import;
11168defa952SSam Clegg         Import.Module = WS.getModuleName();
11178defa952SSam Clegg         Import.Field = WS.getName();
111832ce5ca0SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
11198defa952SSam Clegg         Import.SigIndex = getFunctionType(WS);
11206c899ba6SSam Clegg         Imports.push_back(Import);
11216c899ba6SSam Clegg         WasmIndices[&WS] = NumFunctionImports++;
11226c899ba6SSam Clegg       } else if (WS.isGlobal()) {
112315f349f7SNicholas Wilson         if (WS.isWeak())
112415f349f7SNicholas Wilson           report_fatal_error("undefined global symbol cannot be weak");
112515f349f7SNicholas Wilson 
11266c899ba6SSam Clegg         wasm::WasmImport Import;
11276c899ba6SSam Clegg         Import.Module = WS.getModuleName();
11286c899ba6SSam Clegg         Import.Field = WS.getName();
112932ce5ca0SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
11306c899ba6SSam Clegg         Import.Global = WS.getGlobalType();
11316c899ba6SSam Clegg         Imports.push_back(Import);
11326c899ba6SSam Clegg         WasmIndices[&WS] = NumGlobalImports++;
113332ce5ca0SDan Gohman       }
113432ce5ca0SDan Gohman     }
113532ce5ca0SDan Gohman   }
113632ce5ca0SDan Gohman 
11374d57fbd0SSam Clegg   // Populate DataSegments and CustomSections, which must be done before
11384d57fbd0SSam Clegg   // populating DataLocations.
1139759631c7SSam Clegg   for (MCSection &Sec : Asm) {
1140759631c7SSam Clegg     auto &Section = static_cast<MCSectionWasm &>(Sec);
11414d57fbd0SSam Clegg     StringRef SectionName = Section.getSectionName();
1142759631c7SSam Clegg 
1143bafe6902SSam Clegg     // .init_array sections are handled specially elsewhere.
11444d57fbd0SSam Clegg     if (SectionName.startswith(".init_array"))
1145bafe6902SSam Clegg       continue;
1146bafe6902SSam Clegg 
11474d57fbd0SSam Clegg     // Code is handled separately
11484d57fbd0SSam Clegg     if (Section.getKind().isText())
11494d57fbd0SSam Clegg       continue;
11504d57fbd0SSam Clegg 
11514d57fbd0SSam Clegg     if (Section.isWasmData()) {
1152329e76d5SSam Clegg       uint32_t SegmentIndex = DataSegments.size();
1153759631c7SSam Clegg       DataSize = alignTo(DataSize, Section.getAlignment());
1154759631c7SSam Clegg       DataSegments.emplace_back();
1155759631c7SSam Clegg       WasmDataSegment &Segment = DataSegments.back();
11564d57fbd0SSam Clegg       Segment.Name = SectionName;
1157759631c7SSam Clegg       Segment.Offset = DataSize;
1158759631c7SSam Clegg       Segment.Section = &Section;
115963ebb813SSam Clegg       addData(Segment.Data, Section);
116063ebb813SSam Clegg       Segment.Alignment = Section.getAlignment();
116163ebb813SSam Clegg       Segment.Flags = 0;
1162759631c7SSam Clegg       DataSize += Segment.Data.size();
11636c899ba6SSam Clegg       Section.setSegmentIndex(SegmentIndex);
1164ea7caceeSSam Clegg 
1165ea7caceeSSam Clegg       if (const MCSymbolWasm *C = Section.getGroup()) {
1166ea7caceeSSam Clegg         Comdats[C->getName()].emplace_back(
1167329e76d5SSam Clegg             WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
1168ea7caceeSSam Clegg       }
11694d57fbd0SSam Clegg     } else {
11704d57fbd0SSam Clegg       // Create custom sections
11714d57fbd0SSam Clegg       assert(Sec.getKind().isMetadata());
11724d57fbd0SSam Clegg 
11734d57fbd0SSam Clegg       StringRef Name = SectionName;
11744d57fbd0SSam Clegg 
11754d57fbd0SSam Clegg       // For user-defined custom sections, strip the prefix
11764d57fbd0SSam Clegg       if (Name.startswith(".custom_section."))
11774d57fbd0SSam Clegg         Name = Name.substr(strlen(".custom_section."));
11784d57fbd0SSam Clegg 
11794d57fbd0SSam Clegg       MCSymbol* Begin = Sec.getBeginSymbol();
1180fb807d4dSSam Clegg       if (Begin) {
11814d57fbd0SSam Clegg         WasmIndices[cast<MCSymbolWasm>(Begin)] = CustomSections.size();
1182b210c64bSSam Clegg         if (SectionName != Begin->getName())
1183fb807d4dSSam Clegg           report_fatal_error("section name and begin symbol should match: " +
1184b210c64bSSam Clegg                              Twine(SectionName));
1185fb807d4dSSam Clegg       }
11864d57fbd0SSam Clegg       CustomSections.emplace_back(Name, &Section);
1187759631c7SSam Clegg     }
11886a31a0d6SSam Clegg   }
11896a31a0d6SSam Clegg 
1190586320c0SNicholas Wilson   // Populate WasmIndices and DataLocations for defined symbols.
1191d934cb88SDan Gohman   for (const MCSymbol &S : Asm.symbols()) {
1192d934cb88SDan Gohman     // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1193d934cb88SDan Gohman     // or used in relocations.
1194d934cb88SDan Gohman     if (S.isTemporary() && S.getName().empty())
1195d934cb88SDan Gohman       continue;
1196b7787fd0SSam Clegg 
1197d934cb88SDan Gohman     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1198d34e60caSNicola Zaghen     LLVM_DEBUG(
1199d34e60caSNicola Zaghen         dbgs() << "MCSymbol: " << toString(WS.getType()) << " '" << S << "'"
1200d34e60caSNicola Zaghen                << " isDefined=" << S.isDefined() << " isExternal="
1201d34e60caSNicola Zaghen                << S.isExternal() << " isTemporary=" << S.isTemporary()
1202d34e60caSNicola Zaghen                << " isWeak=" << WS.isWeak() << " isHidden=" << WS.isHidden()
1203b7787fd0SSam Clegg                << " isVariable=" << WS.isVariable() << "\n");
1204b7787fd0SSam Clegg 
12055e3d33a7SSam Clegg     if (WS.isVariable())
12065e3d33a7SSam Clegg       continue;
12076c899ba6SSam Clegg     if (WS.isComdat() && !WS.isDefined())
12086c899ba6SSam Clegg       continue;
1209b7787fd0SSam Clegg 
1210d934cb88SDan Gohman     if (WS.isFunction()) {
12116c899ba6SSam Clegg       unsigned Index;
1212cd65f698SSam Clegg       if (WS.isDefined()) {
1213b7787fd0SSam Clegg         if (WS.getOffset() != 0)
1214b7787fd0SSam Clegg           report_fatal_error(
1215b7787fd0SSam Clegg               "function sections must contain one function each");
1216b7787fd0SSam Clegg 
1217b7787fd0SSam Clegg         if (WS.getSize() == 0)
1218b7787fd0SSam Clegg           report_fatal_error(
1219b7787fd0SSam Clegg               "function symbols must have a size set with .size");
1220b7787fd0SSam Clegg 
12216c899ba6SSam Clegg         // A definition. Write out the function body.
12229f3fe42eSSam Clegg         Index = NumFunctionImports + Functions.size();
1223d934cb88SDan Gohman         WasmFunction Func;
12245e3d33a7SSam Clegg         Func.Type = getFunctionType(WS);
1225d934cb88SDan Gohman         Func.Sym = &WS;
12266c899ba6SSam Clegg         WasmIndices[&WS] = Index;
1227d934cb88SDan Gohman         Functions.push_back(Func);
12286c899ba6SSam Clegg 
12296c899ba6SSam Clegg         auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
12306c899ba6SSam Clegg         if (const MCSymbolWasm *C = Section.getGroup()) {
12316c899ba6SSam Clegg           Comdats[C->getName()].emplace_back(
12326c899ba6SSam Clegg               WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
12336c899ba6SSam Clegg         }
1234d934cb88SDan Gohman       } else {
1235d934cb88SDan Gohman         // An import; the index was assigned above.
12366c899ba6SSam Clegg         Index = WasmIndices.find(&WS)->second;
1237d934cb88SDan Gohman       }
1238d934cb88SDan Gohman 
1239d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> function index: " << Index << "\n");
12406c899ba6SSam Clegg     } else if (WS.isData()) {
1241c38e947eSSam Clegg       if (WS.isTemporary() && !WS.getSize())
1242c38e947eSSam Clegg         continue;
1243c38e947eSSam Clegg 
12446c899ba6SSam Clegg       if (!WS.isDefined()) {
1245d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "  -> segment index: -1"
1246d34e60caSNicola Zaghen                           << "\n");
1247fe6414b0SSam Clegg         continue;
12486c899ba6SSam Clegg       }
1249fe6414b0SSam Clegg 
1250d934cb88SDan Gohman       if (!WS.getSize())
1251c38e947eSSam Clegg         report_fatal_error("data symbols must have a size set with .size: " +
1252c38e947eSSam Clegg                            WS.getName());
1253d934cb88SDan Gohman 
1254d934cb88SDan Gohman       int64_t Size = 0;
1255d934cb88SDan Gohman       if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1256d934cb88SDan Gohman         report_fatal_error(".size expression must be evaluatable");
1257d934cb88SDan Gohman 
1258759631c7SSam Clegg       auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
1259ea7caceeSSam Clegg       assert(DataSection.isWasmData());
12607c395943SSam Clegg 
12616c899ba6SSam Clegg       // For each data symbol, export it in the symtab as a reference to the
12626c899ba6SSam Clegg       // corresponding Wasm data segment.
12636c899ba6SSam Clegg       wasm::WasmDataReference Ref = wasm::WasmDataReference{
12646c899ba6SSam Clegg           DataSection.getSegmentIndex(),
12656c899ba6SSam Clegg           static_cast<uint32_t>(Layout.getSymbolOffset(WS)),
12666c899ba6SSam Clegg           static_cast<uint32_t>(Size)};
12676c899ba6SSam Clegg       DataLocations[&WS] = Ref;
1268d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> segment index: " << Ref.Segment << "\n");
1269a165f2d6SSam Clegg     } else if (WS.isGlobal()) {
12706c899ba6SSam Clegg       // A "true" Wasm global (currently just __stack_pointer)
1271545932beSEric Christopher       if (WS.isDefined())
12726c899ba6SSam Clegg         report_fatal_error("don't yet support defined globals");
12736c899ba6SSam Clegg 
1274545932beSEric Christopher       // An import; the index was assigned above
1275d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> global index: "
1276d34e60caSNicola Zaghen                         << WasmIndices.find(&WS)->second << "\n");
1277a165f2d6SSam Clegg     } else {
1278a165f2d6SSam Clegg       assert(WS.isSection());
1279d934cb88SDan Gohman     }
1280d934cb88SDan Gohman   }
1281d934cb88SDan Gohman 
1282586320c0SNicholas Wilson   // Populate WasmIndices and DataLocations for aliased symbols.  We need to
1283586320c0SNicholas Wilson   // process these in a separate pass because we need to have processed the
1284586320c0SNicholas Wilson   // target of the alias before the alias itself and the symbols are not
1285586320c0SNicholas Wilson   // necessarily ordered in this way.
1286b7787fd0SSam Clegg   for (const MCSymbol &S : Asm.symbols()) {
1287b7787fd0SSam Clegg     if (!S.isVariable())
1288b7787fd0SSam Clegg       continue;
128931a2c809SSam Clegg 
1290cd65f698SSam Clegg     assert(S.isDefined());
1291b7787fd0SSam Clegg 
12925e3d33a7SSam Clegg     // Find the target symbol of this weak alias and export that index
1293aff1c4dfSSam Clegg     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1294aff1c4dfSSam Clegg     const MCSymbolWasm *ResolvedSym = ResolveSymbol(WS);
1295d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym
1296d34e60caSNicola Zaghen                       << "'\n");
1297b7787fd0SSam Clegg 
12986c899ba6SSam Clegg     if (WS.isFunction()) {
12996c899ba6SSam Clegg       assert(WasmIndices.count(ResolvedSym) > 0);
13006c899ba6SSam Clegg       uint32_t WasmIndex = WasmIndices.find(ResolvedSym)->second;
13016c899ba6SSam Clegg       WasmIndices[&WS] = WasmIndex;
1302d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> index:" << WasmIndex << "\n");
13036c899ba6SSam Clegg     } else if (WS.isData()) {
13046c899ba6SSam Clegg       assert(DataLocations.count(ResolvedSym) > 0);
13056c899ba6SSam Clegg       const wasm::WasmDataReference &Ref =
13066c899ba6SSam Clegg           DataLocations.find(ResolvedSym)->second;
13076c899ba6SSam Clegg       DataLocations[&WS] = Ref;
1308d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> index:" << Ref.Segment << "\n");
13096c899ba6SSam Clegg     } else {
13106c899ba6SSam Clegg       report_fatal_error("don't yet support global aliases");
13116c899ba6SSam Clegg     }
1312586320c0SNicholas Wilson   }
131331a2c809SSam Clegg 
1314586320c0SNicholas Wilson   // Finally, populate the symbol table itself, in its "natural" order.
1315586320c0SNicholas Wilson   for (const MCSymbol &S : Asm.symbols()) {
1316586320c0SNicholas Wilson     const auto &WS = static_cast<const MCSymbolWasm &>(S);
131725d8e68bSSam Clegg     if (!isInSymtab(WS)) {
131825d8e68bSSam Clegg       WS.setIndex(INVALID_INDEX);
1319586320c0SNicholas Wilson       continue;
132025d8e68bSSam Clegg     }
1321d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "adding to symtab: " << WS << "\n");
1322586320c0SNicholas Wilson 
1323586320c0SNicholas Wilson     uint32_t Flags = 0;
1324586320c0SNicholas Wilson     if (WS.isWeak())
1325586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_BINDING_WEAK;
1326586320c0SNicholas Wilson     if (WS.isHidden())
1327586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN;
1328586320c0SNicholas Wilson     if (!WS.isExternal() && WS.isDefined())
1329586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;
1330586320c0SNicholas Wilson     if (WS.isUndefined())
1331586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_UNDEFINED;
1332586320c0SNicholas Wilson 
1333586320c0SNicholas Wilson     wasm::WasmSymbolInfo Info;
1334586320c0SNicholas Wilson     Info.Name = WS.getName();
1335586320c0SNicholas Wilson     Info.Kind = WS.getType();
1336586320c0SNicholas Wilson     Info.Flags = Flags;
13374d57fbd0SSam Clegg     if (!WS.isData()) {
13384d57fbd0SSam Clegg       assert(WasmIndices.count(&WS) > 0);
1339586320c0SNicholas Wilson       Info.ElementIndex = WasmIndices.find(&WS)->second;
13404d57fbd0SSam Clegg     } else if (WS.isDefined()) {
13414d57fbd0SSam Clegg       assert(DataLocations.count(&WS) > 0);
1342586320c0SNicholas Wilson       Info.DataRef = DataLocations.find(&WS)->second;
13434d57fbd0SSam Clegg     }
134425d8e68bSSam Clegg     WS.setIndex(SymbolInfos.size());
1345586320c0SNicholas Wilson     SymbolInfos.emplace_back(Info);
1346b7787fd0SSam Clegg   }
1347b7787fd0SSam Clegg 
13486006e091SSam Clegg   {
13496006e091SSam Clegg     auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
1350f9edbe95SSam Clegg       // Functions referenced by a relocation need to put in the table.  This is
1351f9edbe95SSam Clegg       // purely to make the object file's provisional values readable, and is
1352f9edbe95SSam Clegg       // ignored by the linker, which re-calculates the relocations itself.
1353f9edbe95SSam Clegg       if (Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_I32 &&
1354f9edbe95SSam Clegg           Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB)
1355f9edbe95SSam Clegg         return;
1356f9edbe95SSam Clegg       assert(Rel.Symbol->isFunction());
1357f9edbe95SSam Clegg       const MCSymbolWasm &WS = *ResolveSymbol(*Rel.Symbol);
13586c899ba6SSam Clegg       uint32_t FunctionIndex = WasmIndices.find(&WS)->second;
1359f9edbe95SSam Clegg       uint32_t TableIndex = TableElems.size() + kInitialTableOffset;
1360f9edbe95SSam Clegg       if (TableIndices.try_emplace(&WS, TableIndex).second) {
1361d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "  -> adding " << WS.getName()
1362f9edbe95SSam Clegg                           << " to table: " << TableIndex << "\n");
13636c899ba6SSam Clegg         TableElems.push_back(FunctionIndex);
13646006e091SSam Clegg         registerFunctionType(WS);
13656006e091SSam Clegg       }
13666006e091SSam Clegg     };
1367970d02c4SDan Gohman 
13686006e091SSam Clegg     for (const WasmRelocationEntry &RelEntry : CodeRelocations)
13696006e091SSam Clegg       HandleReloc(RelEntry);
13706006e091SSam Clegg     for (const WasmRelocationEntry &RelEntry : DataRelocations)
13716006e091SSam Clegg       HandleReloc(RelEntry);
1372d934cb88SDan Gohman   }
1373d934cb88SDan Gohman 
1374bafe6902SSam Clegg   // Translate .init_array section contents into start functions.
1375bafe6902SSam Clegg   for (const MCSection &S : Asm) {
1376bafe6902SSam Clegg     const auto &WS = static_cast<const MCSectionWasm &>(S);
1377bafe6902SSam Clegg     if (WS.getSectionName().startswith(".fini_array"))
1378bafe6902SSam Clegg       report_fatal_error(".fini_array sections are unsupported");
1379bafe6902SSam Clegg     if (!WS.getSectionName().startswith(".init_array"))
1380bafe6902SSam Clegg       continue;
1381bafe6902SSam Clegg     if (WS.getFragmentList().empty())
1382bafe6902SSam Clegg       continue;
1383b210c64bSSam Clegg 
1384b210c64bSSam Clegg     // init_array is expected to contain a single non-empty data fragment
1385b210c64bSSam Clegg     if (WS.getFragmentList().size() != 3)
1386bafe6902SSam Clegg       report_fatal_error("only one .init_array section fragment supported");
1387b210c64bSSam Clegg 
1388b210c64bSSam Clegg     auto IT = WS.begin();
1389b210c64bSSam Clegg     const MCFragment &EmptyFrag = *IT;
1390b210c64bSSam Clegg     if (EmptyFrag.getKind() != MCFragment::FT_Data)
1391b210c64bSSam Clegg       report_fatal_error(".init_array section should be aligned");
1392b210c64bSSam Clegg 
1393b210c64bSSam Clegg     IT = std::next(IT);
1394b210c64bSSam Clegg     const MCFragment &AlignFrag = *IT;
1395bafe6902SSam Clegg     if (AlignFrag.getKind() != MCFragment::FT_Align)
1396bafe6902SSam Clegg       report_fatal_error(".init_array section should be aligned");
1397bafe6902SSam Clegg     if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
1398bafe6902SSam Clegg       report_fatal_error(".init_array section should be aligned for pointers");
1399b210c64bSSam Clegg 
1400b210c64bSSam Clegg     const MCFragment &Frag = *std::next(IT);
1401bafe6902SSam Clegg     if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1402bafe6902SSam Clegg       report_fatal_error("only data supported in .init_array section");
1403b210c64bSSam Clegg 
1404bafe6902SSam Clegg     uint16_t Priority = UINT16_MAX;
14054d57fbd0SSam Clegg     unsigned PrefixLength = strlen(".init_array");
14064d57fbd0SSam Clegg     if (WS.getSectionName().size() > PrefixLength) {
14074d57fbd0SSam Clegg       if (WS.getSectionName()[PrefixLength] != '.')
1408bafe6902SSam Clegg         report_fatal_error(".init_array section priority should start with '.'");
14094d57fbd0SSam Clegg       if (WS.getSectionName()
14104d57fbd0SSam Clegg               .substr(PrefixLength + 1)
14114d57fbd0SSam Clegg               .getAsInteger(10, Priority))
1412bafe6902SSam Clegg         report_fatal_error("invalid .init_array section priority");
1413bafe6902SSam Clegg     }
1414bafe6902SSam Clegg     const auto &DataFrag = cast<MCDataFragment>(Frag);
1415bafe6902SSam Clegg     const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1416bafe6902SSam Clegg     for (const uint8_t *p = (const uint8_t *)Contents.data(),
1417bafe6902SSam Clegg                      *end = (const uint8_t *)Contents.data() + Contents.size();
1418bafe6902SSam Clegg          p != end; ++p) {
1419bafe6902SSam Clegg       if (*p != 0)
1420bafe6902SSam Clegg         report_fatal_error("non-symbolic data in .init_array section");
1421bafe6902SSam Clegg     }
1422bafe6902SSam Clegg     for (const MCFixup &Fixup : DataFrag.getFixups()) {
1423bafe6902SSam Clegg       assert(Fixup.getKind() == MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
1424bafe6902SSam Clegg       const MCExpr *Expr = Fixup.getValue();
1425bafe6902SSam Clegg       auto *Sym = dyn_cast<MCSymbolRefExpr>(Expr);
1426bafe6902SSam Clegg       if (!Sym)
1427bafe6902SSam Clegg         report_fatal_error("fixups in .init_array should be symbol references");
1428bafe6902SSam Clegg       if (Sym->getKind() != MCSymbolRefExpr::VK_WebAssembly_FUNCTION)
1429bafe6902SSam Clegg         report_fatal_error("symbols in .init_array should be for functions");
143025d8e68bSSam Clegg       if (Sym->getSymbol().getIndex() == INVALID_INDEX)
143125d8e68bSSam Clegg         report_fatal_error("symbols in .init_array should exist in symbtab");
143225d8e68bSSam Clegg       InitFuncs.push_back(
143325d8e68bSSam Clegg           std::make_pair(Priority, Sym->getSymbol().getIndex()));
1434bafe6902SSam Clegg     }
1435bafe6902SSam Clegg   }
1436bafe6902SSam Clegg 
143718eafb6cSDan Gohman   // Write out the Wasm header.
143818eafb6cSDan Gohman   writeHeader(Asm);
143918eafb6cSDan Gohman 
14409e15f359SSam Clegg   writeTypeSection(FunctionTypes);
1441f950b24aSSam Clegg   writeImportSection(Imports, DataSize, TableElems.size());
14429e15f359SSam Clegg   writeFunctionSection(Functions);
1443f950b24aSSam Clegg   // Skip the "table" section; we import the table instead.
1444f950b24aSSam Clegg   // Skip the "memory" section; we import the memory instead.
14457c395943SSam Clegg   writeGlobalSection();
14469e15f359SSam Clegg   writeExportSection(Exports);
14479e15f359SSam Clegg   writeElemSection(TableElems);
1448acd7d2b0SSam Clegg   writeCodeSection(Asm, Layout, Functions);
14496c899ba6SSam Clegg   writeDataSection();
14506a31a0d6SSam Clegg   writeCustomSections(Asm, Layout);
1451c22bfb6bSNicholas Wilson   writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats);
14526f08c84aSSam Clegg   writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations);
14536f08c84aSSam Clegg   writeRelocSection(DataSectionIndex, "DATA", DataRelocations);
14546a31a0d6SSam Clegg   writeCustomRelocSections();
1455970d02c4SDan Gohman 
1456d934cb88SDan Gohman   // TODO: Translate the .comment section to the output.
145718eafb6cSDan Gohman }
145818eafb6cSDan Gohman 
145960fbc7ccSLang Hames std::unique_ptr<MCObjectWriter>
14601301a878SLang Hames llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
146118eafb6cSDan Gohman                              raw_pwrite_stream &OS) {
14620917c9e4SDan Gohman   return llvm::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
146318eafb6cSDan Gohman }
1464