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.
6177a7a380SDerek Schuff // TODO: Consider using WasmSignature directly instead.
629e15f359SSam Clegg struct WasmFunctionType {
639e15f359SSam Clegg   // Support empty and tombstone instances, needed by DenseMap.
649e15f359SSam Clegg   enum { Plain, Empty, Tombstone } State;
659e15f359SSam Clegg 
669e15f359SSam Clegg   // The return types of the function.
679e15f359SSam Clegg   SmallVector<wasm::ValType, 1> Returns;
689e15f359SSam Clegg 
699e15f359SSam Clegg   // The parameter types of the function.
709e15f359SSam Clegg   SmallVector<wasm::ValType, 4> Params;
719e15f359SSam Clegg 
729e15f359SSam Clegg   WasmFunctionType() : State(Plain) {}
739e15f359SSam Clegg 
749e15f359SSam Clegg   bool operator==(const WasmFunctionType &Other) const {
759e15f359SSam Clegg     return State == Other.State && Returns == Other.Returns &&
769e15f359SSam Clegg            Params == Other.Params;
779e15f359SSam Clegg   }
789e15f359SSam Clegg };
799e15f359SSam Clegg 
809e15f359SSam Clegg // Traits for using WasmFunctionType in a DenseMap.
819e15f359SSam Clegg struct WasmFunctionTypeDenseMapInfo {
829e15f359SSam Clegg   static WasmFunctionType getEmptyKey() {
839e15f359SSam Clegg     WasmFunctionType FuncTy;
849e15f359SSam Clegg     FuncTy.State = WasmFunctionType::Empty;
859e15f359SSam Clegg     return FuncTy;
869e15f359SSam Clegg   }
879e15f359SSam Clegg   static WasmFunctionType getTombstoneKey() {
889e15f359SSam Clegg     WasmFunctionType FuncTy;
899e15f359SSam Clegg     FuncTy.State = WasmFunctionType::Tombstone;
909e15f359SSam Clegg     return FuncTy;
919e15f359SSam Clegg   }
929e15f359SSam Clegg   static unsigned getHashValue(const WasmFunctionType &FuncTy) {
939e15f359SSam Clegg     uintptr_t Value = FuncTy.State;
949e15f359SSam Clegg     for (wasm::ValType Ret : FuncTy.Returns)
959e15f359SSam Clegg       Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Ret));
969e15f359SSam Clegg     for (wasm::ValType Param : FuncTy.Params)
979e15f359SSam Clegg       Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Param));
989e15f359SSam Clegg     return Value;
999e15f359SSam Clegg   }
1009e15f359SSam Clegg   static bool isEqual(const WasmFunctionType &LHS,
1019e15f359SSam Clegg                       const WasmFunctionType &RHS) {
1029e15f359SSam Clegg     return LHS == RHS;
1039e15f359SSam Clegg   }
1049e15f359SSam Clegg };
1059e15f359SSam Clegg 
1067c395943SSam Clegg // A wasm data segment.  A wasm binary contains only a single data section
1077c395943SSam Clegg // but that can contain many segments, each with their own virtual location
1087c395943SSam Clegg // in memory.  Each MCSection data created by llvm is modeled as its own
1097c395943SSam Clegg // wasm data segment.
1107c395943SSam Clegg struct WasmDataSegment {
1117c395943SSam Clegg   MCSectionWasm *Section;
112d95ed959SSam Clegg   StringRef Name;
1137c395943SSam Clegg   uint32_t Offset;
11463ebb813SSam Clegg   uint32_t Alignment;
11563ebb813SSam Clegg   uint32_t Flags;
1167c395943SSam Clegg   SmallVector<char, 4> Data;
1177c395943SSam Clegg };
1187c395943SSam Clegg 
1199e15f359SSam Clegg // A wasm function to be written into the function section.
1209e15f359SSam Clegg struct WasmFunction {
1219e15f359SSam Clegg   int32_t Type;
1229e15f359SSam Clegg   const MCSymbolWasm *Sym;
1239e15f359SSam Clegg };
1249e15f359SSam Clegg 
1259e15f359SSam Clegg // A wasm global to be written into the global section.
1269e15f359SSam Clegg struct WasmGlobal {
1276e7f1826SSam Clegg   wasm::WasmGlobalType Type;
1289e15f359SSam Clegg   uint64_t InitialValue;
1299e15f359SSam Clegg };
1309e15f359SSam Clegg 
131ea7caceeSSam Clegg // Information about a single item which is part of a COMDAT.  For each data
132ea7caceeSSam Clegg // segment or function which is in the COMDAT, there is a corresponding
133ea7caceeSSam Clegg // WasmComdatEntry.
134ea7caceeSSam Clegg struct WasmComdatEntry {
135ea7caceeSSam Clegg   unsigned Kind;
136ea7caceeSSam Clegg   uint32_t Index;
137ea7caceeSSam Clegg };
138ea7caceeSSam Clegg 
1396dc65e91SSam Clegg // Information about a single relocation.
1406dc65e91SSam Clegg struct WasmRelocationEntry {
1416dc65e91SSam Clegg   uint64_t Offset;                   // Where is the relocation.
1426dc65e91SSam Clegg   const MCSymbolWasm *Symbol;        // The symbol to relocate with.
1436dc65e91SSam Clegg   int64_t Addend;                    // A value to add to the symbol.
1446dc65e91SSam Clegg   unsigned Type;                     // The type of the relocation.
145fe6414b0SSam Clegg   const MCSectionWasm *FixupSection; // The section the relocation is targeting.
1466dc65e91SSam Clegg 
1476dc65e91SSam Clegg   WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol,
1486dc65e91SSam Clegg                       int64_t Addend, unsigned Type,
149fe6414b0SSam Clegg                       const MCSectionWasm *FixupSection)
1506dc65e91SSam Clegg       : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type),
1516dc65e91SSam Clegg         FixupSection(FixupSection) {}
1526dc65e91SSam Clegg 
153acd7d2b0SSam Clegg   bool hasAddend() const {
154acd7d2b0SSam Clegg     switch (Type) {
15513a2e899SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
15613a2e899SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
15713a2e899SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
1586a31a0d6SSam Clegg     case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32:
1596a31a0d6SSam Clegg     case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32:
160acd7d2b0SSam Clegg       return true;
161acd7d2b0SSam Clegg     default:
162acd7d2b0SSam Clegg       return false;
163acd7d2b0SSam Clegg     }
164acd7d2b0SSam Clegg   }
165acd7d2b0SSam Clegg 
1666dc65e91SSam Clegg   void print(raw_ostream &Out) const {
167f208f631SHeejin Ahn     Out << wasm::relocTypetoString(Type) << " Off=" << Offset
168f208f631SHeejin Ahn         << ", Sym=" << *Symbol << ", Addend=" << Addend
169759631c7SSam Clegg         << ", FixupSection=" << FixupSection->getSectionName();
1706dc65e91SSam Clegg   }
171b7787fd0SSam Clegg 
172615eb470SAaron Ballman #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
173b7787fd0SSam Clegg   LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
174b7787fd0SSam Clegg #endif
1756dc65e91SSam Clegg };
1766dc65e91SSam Clegg 
17725d8e68bSSam Clegg static const uint32_t INVALID_INDEX = -1;
17825d8e68bSSam Clegg 
179cfd44a2eSSam Clegg struct WasmCustomSection {
180cfd44a2eSSam Clegg 
1816a31a0d6SSam Clegg   StringRef Name;
1826a31a0d6SSam Clegg   MCSectionWasm *Section;
1836a31a0d6SSam Clegg 
1846a31a0d6SSam Clegg   uint32_t OutputContentsOffset;
1856a31a0d6SSam Clegg   uint32_t OutputIndex;
1866a31a0d6SSam Clegg 
1876a31a0d6SSam Clegg   WasmCustomSection(StringRef Name, MCSectionWasm *Section)
1886a31a0d6SSam Clegg       : Name(Name), Section(Section), OutputContentsOffset(0),
1896a31a0d6SSam Clegg         OutputIndex(INVALID_INDEX) {}
190cfd44a2eSSam Clegg };
191cfd44a2eSSam Clegg 
1921fb8daa6SSam Clegg #if !defined(NDEBUG)
1937f055deeSSam Clegg raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
194b7787fd0SSam Clegg   Rel.print(OS);
195b7787fd0SSam Clegg   return OS;
196b7787fd0SSam Clegg }
1971fb8daa6SSam Clegg #endif
198b7787fd0SSam Clegg 
19918eafb6cSDan Gohman class WasmObjectWriter : public MCObjectWriter {
200f17b149dSPeter Collingbourne   support::endian::Writer W;
201f17b149dSPeter Collingbourne 
20218eafb6cSDan Gohman   /// The target specific Wasm writer instance.
20318eafb6cSDan Gohman   std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
20418eafb6cSDan Gohman 
205d934cb88SDan Gohman   // Relocations for fixing up references in the code section.
206d934cb88SDan Gohman   std::vector<WasmRelocationEntry> CodeRelocations;
2076f08c84aSSam Clegg   uint32_t CodeSectionIndex;
208d934cb88SDan Gohman 
209d934cb88SDan Gohman   // Relocations for fixing up references in the data section.
210d934cb88SDan Gohman   std::vector<WasmRelocationEntry> DataRelocations;
2116f08c84aSSam Clegg   uint32_t DataSectionIndex;
212d934cb88SDan Gohman 
213d934cb88SDan Gohman   // Index values to use for fixing up call_indirect type indices.
214acd7d2b0SSam Clegg   // Maps function symbols to the index of the type of the function
215acd7d2b0SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
216d99f6078SSam Clegg   // Maps function symbols to the table element index space. Used
217d99f6078SSam Clegg   // for TABLE_INDEX relocation types (i.e. address taken functions).
218f9edbe95SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> TableIndices;
219a165f2d6SSam Clegg   // Maps function/global symbols to the function/global/section index space.
2206c899ba6SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> WasmIndices;
2216c899ba6SSam Clegg   // Maps data symbols to the Wasm segment and offset/size with the segment.
2226c899ba6SSam Clegg   DenseMap<const MCSymbolWasm *, wasm::WasmDataReference> DataLocations;
2236a31a0d6SSam Clegg 
2246a31a0d6SSam Clegg   // Stores output data (index, relocations, content offset) for custom
2256a31a0d6SSam Clegg   // section.
2266a31a0d6SSam Clegg   std::vector<WasmCustomSection> CustomSections;
2276a31a0d6SSam Clegg   // Relocations for fixing up references in the custom sections.
2286a31a0d6SSam Clegg   DenseMap<const MCSectionWasm *, std::vector<WasmRelocationEntry>>
2296a31a0d6SSam Clegg       CustomSectionsRelocations;
230acd7d2b0SSam Clegg 
231c0d41195SSam Clegg   // Map from section to defining function symbol.
2326ccb59b3SSam Clegg   DenseMap<const MCSection *, const MCSymbol *> SectionFunctions;
2336ccb59b3SSam Clegg 
234acd7d2b0SSam Clegg   DenseMap<WasmFunctionType, int32_t, WasmFunctionTypeDenseMapInfo>
235acd7d2b0SSam Clegg       FunctionTypeIndices;
2365e3d33a7SSam Clegg   SmallVector<WasmFunctionType, 4> FunctionTypes;
2377c395943SSam Clegg   SmallVector<WasmGlobal, 4> Globals;
2386c899ba6SSam Clegg   SmallVector<WasmDataSegment, 4> DataSegments;
2399f3fe42eSSam Clegg   unsigned NumFunctionImports = 0;
2407c395943SSam Clegg   unsigned NumGlobalImports = 0;
2417e1c3345SChandler Carruth   uint32_t SectionCount = 0;
242d934cb88SDan Gohman 
24318eafb6cSDan Gohman   // TargetObjectWriter wrappers.
24418eafb6cSDan Gohman   bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
245ae03c1e7SSam Clegg   unsigned getRelocType(const MCValue &Target, const MCFixup &Fixup) const {
246ae03c1e7SSam Clegg     return TargetObjectWriter->getRelocType(Target, Fixup);
24718eafb6cSDan Gohman   }
24818eafb6cSDan Gohman 
2492322a937SSam Clegg   void startSection(SectionBookkeeping &Section, unsigned SectionId);
2502322a937SSam Clegg   void startCustomSection(SectionBookkeeping &Section, StringRef Name);
251d934cb88SDan Gohman   void endSection(SectionBookkeeping &Section);
252d934cb88SDan Gohman 
25318eafb6cSDan Gohman public:
2541301a878SLang Hames   WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
2551301a878SLang Hames                    raw_pwrite_stream &OS)
25659a6fc46SPeter Collingbourne       : W(OS, support::little), TargetObjectWriter(std::move(MOTW)) {}
25718eafb6cSDan Gohman 
25818eafb6cSDan Gohman   ~WasmObjectWriter() override;
25918eafb6cSDan Gohman 
2600917c9e4SDan Gohman private:
261acd7d2b0SSam Clegg   void reset() override {
262acd7d2b0SSam Clegg     CodeRelocations.clear();
263acd7d2b0SSam Clegg     DataRelocations.clear();
264acd7d2b0SSam Clegg     TypeIndices.clear();
2656c899ba6SSam Clegg     WasmIndices.clear();
266f9edbe95SSam Clegg     TableIndices.clear();
2676c899ba6SSam Clegg     DataLocations.clear();
2686a31a0d6SSam Clegg     CustomSectionsRelocations.clear();
269acd7d2b0SSam Clegg     FunctionTypeIndices.clear();
2705e3d33a7SSam Clegg     FunctionTypes.clear();
2717c395943SSam Clegg     Globals.clear();
2726c899ba6SSam Clegg     DataSegments.clear();
2736ccb59b3SSam Clegg     SectionFunctions.clear();
2749f3fe42eSSam Clegg     NumFunctionImports = 0;
2757c395943SSam Clegg     NumGlobalImports = 0;
276105bdc25SSam Clegg     MCObjectWriter::reset();
277acd7d2b0SSam Clegg   }
278acd7d2b0SSam Clegg 
27918eafb6cSDan Gohman   void writeHeader(const MCAssembler &Asm);
28018eafb6cSDan Gohman 
28118eafb6cSDan Gohman   void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
28218eafb6cSDan Gohman                         const MCFragment *Fragment, const MCFixup &Fixup,
283ceecfe5bSRafael Espindola                         MCValue Target, uint64_t &FixedValue) override;
28418eafb6cSDan Gohman 
28518eafb6cSDan Gohman   void executePostLayoutBinding(MCAssembler &Asm,
28618eafb6cSDan Gohman                                 const MCAsmLayout &Layout) override;
28718eafb6cSDan Gohman 
288438390faSPeter Collingbourne   uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
2899e15f359SSam Clegg 
290b7787fd0SSam Clegg   void writeString(const StringRef Str) {
291f17b149dSPeter Collingbourne     encodeULEB128(Str.size(), W.OS);
292f17b149dSPeter Collingbourne     W.OS << Str;
293b7787fd0SSam Clegg   }
294b7787fd0SSam Clegg 
295f208f631SHeejin Ahn   void writeValueType(wasm::ValType Ty) { W.OS << static_cast<char>(Ty); }
2969e15f359SSam Clegg 
297457fb0b4SSam Clegg   void writeTypeSection(ArrayRef<WasmFunctionType> FunctionTypes);
2988defa952SSam Clegg   void writeImportSection(ArrayRef<wasm::WasmImport> Imports, uint32_t DataSize,
299f950b24aSSam Clegg                           uint32_t NumElements);
300457fb0b4SSam Clegg   void writeFunctionSection(ArrayRef<WasmFunction> Functions);
3017c395943SSam Clegg   void writeGlobalSection();
3028defa952SSam Clegg   void writeExportSection(ArrayRef<wasm::WasmExport> Exports);
303457fb0b4SSam Clegg   void writeElemSection(ArrayRef<uint32_t> TableElems);
3049e15f359SSam Clegg   void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
305457fb0b4SSam Clegg                         ArrayRef<WasmFunction> Functions);
3066c899ba6SSam Clegg   void writeDataSection();
3076f08c84aSSam Clegg   void writeRelocSection(uint32_t SectionIndex, StringRef Name,
308f77dc2a8SSam Clegg                          std::vector<WasmRelocationEntry> &Relocations);
30931a2c809SSam Clegg   void writeLinkingMetaDataSection(
31086b4a09aSSam Clegg       ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
311ea7caceeSSam Clegg       ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
312ea7caceeSSam Clegg       const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats);
3136a31a0d6SSam Clegg   void writeCustomSections(const MCAssembler &Asm, const MCAsmLayout &Layout);
3146a31a0d6SSam Clegg   void writeCustomRelocSections();
3156a31a0d6SSam Clegg   void
3166a31a0d6SSam Clegg   updateCustomSectionRelocations(const SmallVector<WasmFunction, 4> &Functions,
3176a31a0d6SSam Clegg                                  const MCAsmLayout &Layout);
318acd7d2b0SSam Clegg 
3197c395943SSam Clegg   uint32_t getProvisionalValue(const WasmRelocationEntry &RelEntry);
320acd7d2b0SSam Clegg   void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
321acd7d2b0SSam Clegg                         uint64_t ContentsOffset);
322acd7d2b0SSam Clegg 
323acd7d2b0SSam Clegg   uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
3245e3d33a7SSam Clegg   uint32_t getFunctionType(const MCSymbolWasm &Symbol);
3255e3d33a7SSam Clegg   uint32_t registerFunctionType(const MCSymbolWasm &Symbol);
32618eafb6cSDan Gohman };
3279e15f359SSam Clegg 
32818eafb6cSDan Gohman } // end anonymous namespace
32918eafb6cSDan Gohman 
33018eafb6cSDan Gohman WasmObjectWriter::~WasmObjectWriter() {}
33118eafb6cSDan Gohman 
332d934cb88SDan Gohman // Write out a section header and a patchable section size field.
333d934cb88SDan Gohman void WasmObjectWriter::startSection(SectionBookkeeping &Section,
3342322a937SSam Clegg                                     unsigned SectionId) {
335d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "startSection " << SectionId << "\n");
336f17b149dSPeter Collingbourne   W.OS << char(SectionId);
337d934cb88SDan Gohman 
338f17b149dSPeter Collingbourne   Section.SizeOffset = W.OS.tell();
339d934cb88SDan Gohman 
340d934cb88SDan Gohman   // The section size. We don't know the size yet, so reserve enough space
341d934cb88SDan Gohman   // for any 32-bit value; we'll patch it later.
342f17b149dSPeter Collingbourne   encodeULEB128(UINT32_MAX, W.OS);
343d934cb88SDan Gohman 
344d934cb88SDan Gohman   // The position where the section starts, for measuring its size.
345f17b149dSPeter Collingbourne   Section.ContentsOffset = W.OS.tell();
346f17b149dSPeter Collingbourne   Section.PayloadOffset = W.OS.tell();
3476f08c84aSSam Clegg   Section.Index = SectionCount++;
348d934cb88SDan Gohman }
3492322a937SSam Clegg 
3502322a937SSam Clegg void WasmObjectWriter::startCustomSection(SectionBookkeeping &Section,
3512322a937SSam Clegg                                           StringRef Name) {
352d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "startCustomSection " << Name << "\n");
3532322a937SSam Clegg   startSection(Section, wasm::WASM_SEC_CUSTOM);
3546a31a0d6SSam Clegg 
3556a31a0d6SSam Clegg   // The position where the section header ends, for measuring its size.
356f17b149dSPeter Collingbourne   Section.PayloadOffset = W.OS.tell();
3576a31a0d6SSam Clegg 
3582322a937SSam Clegg   // Custom sections in wasm also have a string identifier.
3592322a937SSam Clegg   writeString(Name);
3606a31a0d6SSam Clegg 
3616a31a0d6SSam Clegg   // The position where the custom section starts.
362f17b149dSPeter Collingbourne   Section.ContentsOffset = W.OS.tell();
363d934cb88SDan Gohman }
364d934cb88SDan Gohman 
365d934cb88SDan Gohman // Now that the section is complete and we know how big it is, patch up the
366d934cb88SDan Gohman // section size field at the start of the section.
367d934cb88SDan Gohman void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
368f17b149dSPeter Collingbourne   uint64_t Size = W.OS.tell() - Section.PayloadOffset;
369d934cb88SDan Gohman   if (uint32_t(Size) != Size)
370d934cb88SDan Gohman     report_fatal_error("section size does not fit in a uint32_t");
371d934cb88SDan Gohman 
372d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "endSection size=" << Size << "\n");
373d934cb88SDan Gohman 
374d934cb88SDan Gohman   // Write the final section size to the payload_len field, which follows
375d934cb88SDan Gohman   // the section id byte.
376d934cb88SDan Gohman   uint8_t Buffer[16];
37766a99e41SSam Clegg   unsigned SizeLen = encodeULEB128(Size, Buffer, 5);
378d934cb88SDan Gohman   assert(SizeLen == 5);
379f17b149dSPeter Collingbourne   static_cast<raw_pwrite_stream &>(W.OS).pwrite((char *)Buffer, SizeLen,
380f17b149dSPeter Collingbourne                                                 Section.SizeOffset);
381d934cb88SDan Gohman }
382d934cb88SDan Gohman 
38318eafb6cSDan Gohman // Emit the Wasm header.
38418eafb6cSDan Gohman void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
385f17b149dSPeter Collingbourne   W.OS.write(wasm::WasmMagic, sizeof(wasm::WasmMagic));
386f17b149dSPeter Collingbourne   W.write<uint32_t>(wasm::WasmVersion);
38718eafb6cSDan Gohman }
38818eafb6cSDan Gohman 
38918eafb6cSDan Gohman void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
39018eafb6cSDan Gohman                                                 const MCAsmLayout &Layout) {
3916ccb59b3SSam Clegg   // Build a map of sections to the function that defines them, for use
3926ccb59b3SSam Clegg   // in recordRelocation.
3936ccb59b3SSam Clegg   for (const MCSymbol &S : Asm.symbols()) {
3946ccb59b3SSam Clegg     const auto &WS = static_cast<const MCSymbolWasm &>(S);
3956ccb59b3SSam Clegg     if (WS.isDefined() && WS.isFunction() && !WS.isVariable()) {
3966ccb59b3SSam Clegg       const auto &Sec = static_cast<const MCSectionWasm &>(S.getSection());
3976ccb59b3SSam Clegg       auto Pair = SectionFunctions.insert(std::make_pair(&Sec, &S));
3986ccb59b3SSam Clegg       if (!Pair.second)
3996ccb59b3SSam Clegg         report_fatal_error("section already has a defining function: " +
4006ccb59b3SSam Clegg                            Sec.getSectionName());
4016ccb59b3SSam Clegg     }
4026ccb59b3SSam Clegg   }
40318eafb6cSDan Gohman }
40418eafb6cSDan Gohman 
40518eafb6cSDan Gohman void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
40618eafb6cSDan Gohman                                         const MCAsmLayout &Layout,
40718eafb6cSDan Gohman                                         const MCFragment *Fragment,
40818eafb6cSDan Gohman                                         const MCFixup &Fixup, MCValue Target,
409ceecfe5bSRafael Espindola                                         uint64_t &FixedValue) {
410ceecfe5bSRafael Espindola   MCAsmBackend &Backend = Asm.getBackend();
411ceecfe5bSRafael Espindola   bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
412ceecfe5bSRafael Espindola                  MCFixupKindInfo::FKF_IsPCRel;
413fe6414b0SSam Clegg   const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
414d934cb88SDan Gohman   uint64_t C = Target.getConstant();
415d934cb88SDan Gohman   uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
416d934cb88SDan Gohman   MCContext &Ctx = Asm.getContext();
417d934cb88SDan Gohman 
418bafe6902SSam Clegg   // The .init_array isn't translated as data, so don't do relocations in it.
419bafe6902SSam Clegg   if (FixupSection.getSectionName().startswith(".init_array"))
420bafe6902SSam Clegg     return;
421bafe6902SSam Clegg 
422d934cb88SDan Gohman   if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
423d934cb88SDan Gohman     assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
424d934cb88SDan Gohman            "Should not have constructed this");
425d934cb88SDan Gohman 
426d934cb88SDan Gohman     // Let A, B and C being the components of Target and R be the location of
427d934cb88SDan Gohman     // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
428d934cb88SDan Gohman     // If it is pcrel, we want to compute (A - B + C - R).
429d934cb88SDan Gohman 
430d934cb88SDan Gohman     // In general, Wasm has no relocations for -B. It can only represent (A + C)
431d934cb88SDan Gohman     // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
432d934cb88SDan Gohman     // replace B to implement it: (A - R - K + C)
433d934cb88SDan Gohman     if (IsPCRel) {
434d934cb88SDan Gohman       Ctx.reportError(
435d934cb88SDan Gohman           Fixup.getLoc(),
436d934cb88SDan Gohman           "No relocation available to represent this relative expression");
437d934cb88SDan Gohman       return;
438d934cb88SDan Gohman     }
439d934cb88SDan Gohman 
440d934cb88SDan Gohman     const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
441d934cb88SDan Gohman 
442d934cb88SDan Gohman     if (SymB.isUndefined()) {
443d934cb88SDan Gohman       Ctx.reportError(Fixup.getLoc(),
444d934cb88SDan Gohman                       Twine("symbol '") + SymB.getName() +
445d934cb88SDan Gohman                           "' can not be undefined in a subtraction expression");
446d934cb88SDan Gohman       return;
447d934cb88SDan Gohman     }
448d934cb88SDan Gohman 
449d934cb88SDan Gohman     assert(!SymB.isAbsolute() && "Should have been folded");
450d934cb88SDan Gohman     const MCSection &SecB = SymB.getSection();
451d934cb88SDan Gohman     if (&SecB != &FixupSection) {
452d934cb88SDan Gohman       Ctx.reportError(Fixup.getLoc(),
453d934cb88SDan Gohman                       "Cannot represent a difference across sections");
454d934cb88SDan Gohman       return;
455d934cb88SDan Gohman     }
456d934cb88SDan Gohman 
457d934cb88SDan Gohman     uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
458d934cb88SDan Gohman     uint64_t K = SymBOffset - FixupOffset;
459d934cb88SDan Gohman     IsPCRel = true;
460d934cb88SDan Gohman     C -= K;
461d934cb88SDan Gohman   }
462d934cb88SDan Gohman 
463d934cb88SDan Gohman   // We either rejected the fixup or folded B into C at this point.
464d934cb88SDan Gohman   const MCSymbolRefExpr *RefA = Target.getSymA();
465d934cb88SDan Gohman   const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr;
466d934cb88SDan Gohman 
467d934cb88SDan Gohman   if (SymA && SymA->isVariable()) {
468d934cb88SDan Gohman     const MCExpr *Expr = SymA->getVariableValue();
4696ad8f190SSam Clegg     const auto *Inner = cast<MCSymbolRefExpr>(Expr);
4706ad8f190SSam Clegg     if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
4716ad8f190SSam Clegg       llvm_unreachable("weakref used in reloc not yet implemented");
472d934cb88SDan Gohman   }
473d934cb88SDan Gohman 
474d934cb88SDan Gohman   // Put any constant offset in an addend. Offsets can be negative, and
475d934cb88SDan Gohman   // LLVM expects wrapping, in contrast to wasm's immediates which can't
476d934cb88SDan Gohman   // be negative and don't wrap.
477d934cb88SDan Gohman   FixedValue = 0;
478d934cb88SDan Gohman 
4794d57fbd0SSam Clegg   unsigned Type = getRelocType(Target, Fixup);
480ae03c1e7SSam Clegg   assert(!IsPCRel);
4819d24fb7fSSam Clegg   assert(SymA);
4829d24fb7fSSam Clegg 
4834d57fbd0SSam Clegg   // Absolute offset within a section or a function.
4844d57fbd0SSam Clegg   // Currently only supported for for metadata sections.
4854d57fbd0SSam Clegg   // See: test/MC/WebAssembly/blockaddress.ll
4864d57fbd0SSam Clegg   if (Type == wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32 ||
4874d57fbd0SSam Clegg       Type == wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32) {
4884d57fbd0SSam Clegg     if (!FixupSection.getKind().isMetadata())
4894d57fbd0SSam Clegg       report_fatal_error("relocations for function or section offsets are "
4904d57fbd0SSam Clegg                          "only supported in metadata sections");
4914d57fbd0SSam Clegg 
4924d57fbd0SSam Clegg     const MCSymbol *SectionSymbol = nullptr;
4934d57fbd0SSam Clegg     const MCSection &SecA = SymA->getSection();
4944d57fbd0SSam Clegg     if (SecA.getKind().isText())
4956ccb59b3SSam Clegg       SectionSymbol = SectionFunctions.find(&SecA)->second;
4964d57fbd0SSam Clegg     else
4974d57fbd0SSam Clegg       SectionSymbol = SecA.getBeginSymbol();
4984d57fbd0SSam Clegg     if (!SectionSymbol)
4994d57fbd0SSam Clegg       report_fatal_error("section symbol is required for relocation");
5004d57fbd0SSam Clegg 
5014d57fbd0SSam Clegg     C += Layout.getSymbolOffset(*SymA);
5024d57fbd0SSam Clegg     SymA = cast<MCSymbolWasm>(SectionSymbol);
5034d57fbd0SSam Clegg   }
5044d57fbd0SSam Clegg 
5054d57fbd0SSam Clegg   // Relocation other than R_WEBASSEMBLY_TYPE_INDEX_LEB are required to be
5064d57fbd0SSam Clegg   // against a named symbol.
5074d57fbd0SSam Clegg   if (Type != wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB) {
5084d57fbd0SSam Clegg     if (SymA->getName().empty())
5094d57fbd0SSam Clegg       report_fatal_error("relocations against un-named temporaries are not yet "
5104d57fbd0SSam Clegg                          "supported by wasm");
5114d57fbd0SSam Clegg 
5124d57fbd0SSam Clegg     SymA->setUsedInReloc();
5134d57fbd0SSam Clegg   }
514ae03c1e7SSam Clegg 
515d934cb88SDan Gohman   WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
516d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
517d934cb88SDan Gohman 
5186a31a0d6SSam Clegg   if (FixupSection.isWasmData()) {
519d934cb88SDan Gohman     DataRelocations.push_back(Rec);
5206a31a0d6SSam Clegg   } else if (FixupSection.getKind().isText()) {
52112fd3da9SSam Clegg     CodeRelocations.push_back(Rec);
5226a31a0d6SSam Clegg   } else if (FixupSection.getKind().isMetadata()) {
5236a31a0d6SSam Clegg     CustomSectionsRelocations[&FixupSection].push_back(Rec);
5246a31a0d6SSam Clegg   } else {
52512fd3da9SSam Clegg     llvm_unreachable("unexpected section type");
526d934cb88SDan Gohman   }
5276a31a0d6SSam Clegg }
528d934cb88SDan Gohman 
529d934cb88SDan Gohman // Write X as an (unsigned) LEB value at offset Offset in Stream, padded
530d934cb88SDan Gohman // to allow patching.
531f208f631SHeejin Ahn static void WritePatchableLEB(raw_pwrite_stream &Stream, uint32_t X,
532f208f631SHeejin Ahn                               uint64_t Offset) {
533d934cb88SDan Gohman   uint8_t Buffer[5];
53466a99e41SSam Clegg   unsigned SizeLen = encodeULEB128(X, Buffer, 5);
535d934cb88SDan Gohman   assert(SizeLen == 5);
536d934cb88SDan Gohman   Stream.pwrite((char *)Buffer, SizeLen, Offset);
537d934cb88SDan Gohman }
538d934cb88SDan Gohman 
539d934cb88SDan Gohman // Write X as an signed LEB value at offset Offset in Stream, padded
540d934cb88SDan Gohman // to allow patching.
541f208f631SHeejin Ahn static void WritePatchableSLEB(raw_pwrite_stream &Stream, int32_t X,
542f208f631SHeejin Ahn                                uint64_t Offset) {
543d934cb88SDan Gohman   uint8_t Buffer[5];
54466a99e41SSam Clegg   unsigned SizeLen = encodeSLEB128(X, Buffer, 5);
545d934cb88SDan Gohman   assert(SizeLen == 5);
546d934cb88SDan Gohman   Stream.pwrite((char *)Buffer, SizeLen, Offset);
547d934cb88SDan Gohman }
548d934cb88SDan Gohman 
549d934cb88SDan Gohman // Write X as a plain integer value at offset Offset in Stream.
550d934cb88SDan Gohman static void WriteI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
551d934cb88SDan Gohman   uint8_t Buffer[4];
552d934cb88SDan Gohman   support::endian::write32le(Buffer, X);
553d934cb88SDan Gohman   Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
554d934cb88SDan Gohman }
555d934cb88SDan Gohman 
556aff1c4dfSSam Clegg static const MCSymbolWasm *ResolveSymbol(const MCSymbolWasm &Symbol) {
557aff1c4dfSSam Clegg   if (Symbol.isVariable()) {
558aff1c4dfSSam Clegg     const MCExpr *Expr = Symbol.getVariableValue();
559aff1c4dfSSam Clegg     auto *Inner = cast<MCSymbolRefExpr>(Expr);
560aff1c4dfSSam Clegg     return cast<MCSymbolWasm>(&Inner->getSymbol());
561aff1c4dfSSam Clegg   }
562aff1c4dfSSam Clegg   return &Symbol;
563aff1c4dfSSam Clegg }
564aff1c4dfSSam Clegg 
565d934cb88SDan Gohman // Compute a value to write into the code at the location covered
56660ec3034SSam Clegg // by RelEntry. This value isn't used by the static linker; it just serves
56760ec3034SSam Clegg // to make the object format more readable and more likely to be directly
56860ec3034SSam Clegg // useable.
5697c395943SSam Clegg uint32_t
5707c395943SSam Clegg WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) {
57160ec3034SSam Clegg   switch (RelEntry.Type) {
57260ec3034SSam Clegg   case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
573f9edbe95SSam Clegg   case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: {
574f9edbe95SSam Clegg     // Provisional value is table address of the resolved symbol itself
575f9edbe95SSam Clegg     const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
576f9edbe95SSam Clegg     assert(Sym->isFunction());
577f9edbe95SSam Clegg     return TableIndices[Sym];
578f9edbe95SSam Clegg   }
57960ec3034SSam Clegg   case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
5806c899ba6SSam Clegg     // Provisional value is same as the index
58160ec3034SSam Clegg     return getRelocationIndexValue(RelEntry);
5826c899ba6SSam Clegg   case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
5836c899ba6SSam Clegg   case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
5846c899ba6SSam Clegg     // Provisional value is function/global Wasm index
5856c899ba6SSam Clegg     if (!WasmIndices.count(RelEntry.Symbol))
5866c899ba6SSam Clegg       report_fatal_error("symbol not found in wasm index space: " +
5876c899ba6SSam Clegg                          RelEntry.Symbol->getName());
5886c899ba6SSam Clegg     return WasmIndices[RelEntry.Symbol];
5894d57fbd0SSam Clegg   case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32:
5904d57fbd0SSam Clegg   case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32: {
5916a31a0d6SSam Clegg     const auto &Section =
5926a31a0d6SSam Clegg         static_cast<const MCSectionWasm &>(RelEntry.Symbol->getSection());
5936a31a0d6SSam Clegg     return Section.getSectionOffset() + RelEntry.Addend;
5946a31a0d6SSam Clegg   }
59560ec3034SSam Clegg   case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
59660ec3034SSam Clegg   case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
59760ec3034SSam Clegg   case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: {
598f9edbe95SSam Clegg     // Provisional value is address of the global
59960ec3034SSam Clegg     const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
600270ed1b3SSam Clegg     // For undefined symbols, use zero
601cd65f698SSam Clegg     if (!Sym->isDefined())
602270ed1b3SSam Clegg       return 0;
6036c899ba6SSam Clegg     const wasm::WasmDataReference &Ref = DataLocations[Sym];
6046c899ba6SSam Clegg     const WasmDataSegment &Segment = DataSegments[Ref.Segment];
605d934cb88SDan Gohman     // Ignore overflow. LLVM allows address arithmetic to silently wrap.
6066c899ba6SSam Clegg     return Segment.Offset + Ref.Offset + RelEntry.Addend;
60760ec3034SSam Clegg   }
60860ec3034SSam Clegg   default:
60960ec3034SSam Clegg     llvm_unreachable("invalid relocation type");
61060ec3034SSam Clegg   }
611d934cb88SDan Gohman }
612d934cb88SDan Gohman 
613759631c7SSam Clegg static void addData(SmallVectorImpl<char> &DataBytes,
61463ebb813SSam Clegg                     MCSectionWasm &DataSection) {
615d34e60caSNicola Zaghen   LLVM_DEBUG(errs() << "addData: " << DataSection.getSectionName() << "\n");
616759631c7SSam Clegg 
61763ebb813SSam Clegg   DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
61863ebb813SSam Clegg 
619759631c7SSam Clegg   for (const MCFragment &Frag : DataSection) {
620759631c7SSam Clegg     if (Frag.hasInstructions())
621759631c7SSam Clegg       report_fatal_error("only data supported in data sections");
622759631c7SSam Clegg 
623759631c7SSam Clegg     if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
624759631c7SSam Clegg       if (Align->getValueSize() != 1)
625759631c7SSam Clegg         report_fatal_error("only byte values supported for alignment");
626759631c7SSam Clegg       // If nops are requested, use zeros, as this is the data section.
627759631c7SSam Clegg       uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
628f208f631SHeejin Ahn       uint64_t Size =
629f208f631SHeejin Ahn           std::min<uint64_t>(alignTo(DataBytes.size(), Align->getAlignment()),
630f208f631SHeejin Ahn                              DataBytes.size() + Align->getMaxBytesToEmit());
631759631c7SSam Clegg       DataBytes.resize(Size, Value);
632759631c7SSam Clegg     } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
633588fad4dSNirav Dave       int64_t NumValues;
634588fad4dSNirav Dave       if (!Fill->getNumValues().evaluateAsAbsolute(NumValues))
635d707c370SRafael Espindola         llvm_unreachable("The fill should be an assembler constant");
636588fad4dSNirav Dave       DataBytes.insert(DataBytes.end(), Fill->getValueSize() * NumValues,
637588fad4dSNirav Dave                        Fill->getValue());
638*24faf859SHeejin Ahn     } else if (auto *LEB = dyn_cast<MCLEBFragment>(&Frag)) {
639*24faf859SHeejin Ahn       const SmallVectorImpl<char> &Contents = LEB->getContents();
640*24faf859SHeejin Ahn       DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
641759631c7SSam Clegg     } else {
642759631c7SSam Clegg       const auto &DataFrag = cast<MCDataFragment>(Frag);
643759631c7SSam Clegg       const SmallVectorImpl<char> &Contents = DataFrag.getContents();
644759631c7SSam Clegg       DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
645759631c7SSam Clegg     }
646759631c7SSam Clegg   }
647759631c7SSam Clegg 
648d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
649759631c7SSam Clegg }
650759631c7SSam Clegg 
65160ec3034SSam Clegg uint32_t
65260ec3034SSam Clegg WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
65360ec3034SSam Clegg   if (RelEntry.Type == wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB) {
654b7787fd0SSam Clegg     if (!TypeIndices.count(RelEntry.Symbol))
655b7787fd0SSam Clegg       report_fatal_error("symbol not found in type index space: " +
656b7787fd0SSam Clegg                          RelEntry.Symbol->getName());
657acd7d2b0SSam Clegg     return TypeIndices[RelEntry.Symbol];
658acd7d2b0SSam Clegg   }
65960ec3034SSam Clegg 
66025d8e68bSSam Clegg   return RelEntry.Symbol->getIndex();
661acd7d2b0SSam Clegg }
662acd7d2b0SSam Clegg 
663d934cb88SDan Gohman // Apply the portions of the relocation records that we can handle ourselves
664d934cb88SDan Gohman // directly.
665acd7d2b0SSam Clegg void WasmObjectWriter::applyRelocations(
666acd7d2b0SSam Clegg     ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
667f17b149dSPeter Collingbourne   auto &Stream = static_cast<raw_pwrite_stream &>(W.OS);
668d934cb88SDan Gohman   for (const WasmRelocationEntry &RelEntry : Relocations) {
669d934cb88SDan Gohman     uint64_t Offset = ContentsOffset +
670d934cb88SDan Gohman                       RelEntry.FixupSection->getSectionOffset() +
671d934cb88SDan Gohman                       RelEntry.Offset;
672d934cb88SDan Gohman 
673d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
67460ec3034SSam Clegg     uint32_t Value = getProvisionalValue(RelEntry);
67560ec3034SSam Clegg 
676acd7d2b0SSam Clegg     switch (RelEntry.Type) {
677acd7d2b0SSam Clegg     case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
6789d24fb7fSSam Clegg     case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
67960ec3034SSam Clegg     case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
68060ec3034SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
681d934cb88SDan Gohman       WritePatchableLEB(Stream, Value, Offset);
682d934cb88SDan Gohman       break;
68360ec3034SSam Clegg     case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
68460ec3034SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
6856a31a0d6SSam Clegg     case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32:
6866a31a0d6SSam Clegg     case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32:
687d934cb88SDan Gohman       WriteI32(Stream, Value, Offset);
688d934cb88SDan Gohman       break;
68960ec3034SSam Clegg     case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
69060ec3034SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
69160ec3034SSam Clegg       WritePatchableSLEB(Stream, Value, Offset);
69260ec3034SSam Clegg       break;
693d934cb88SDan Gohman     default:
6949d24fb7fSSam Clegg       llvm_unreachable("invalid relocation type");
695d934cb88SDan Gohman     }
696d934cb88SDan Gohman   }
69718eafb6cSDan Gohman }
69818eafb6cSDan Gohman 
6999e15f359SSam Clegg void WasmObjectWriter::writeTypeSection(
700457fb0b4SSam Clegg     ArrayRef<WasmFunctionType> FunctionTypes) {
7019e15f359SSam Clegg   if (FunctionTypes.empty())
7029e15f359SSam Clegg     return;
7039e15f359SSam Clegg 
7049e15f359SSam Clegg   SectionBookkeeping Section;
7059e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_TYPE);
7069e15f359SSam Clegg 
707f17b149dSPeter Collingbourne   encodeULEB128(FunctionTypes.size(), W.OS);
7089e15f359SSam Clegg 
7099e15f359SSam Clegg   for (const WasmFunctionType &FuncTy : FunctionTypes) {
710f17b149dSPeter Collingbourne     W.OS << char(wasm::WASM_TYPE_FUNC);
711f17b149dSPeter Collingbourne     encodeULEB128(FuncTy.Params.size(), W.OS);
7129e15f359SSam Clegg     for (wasm::ValType Ty : FuncTy.Params)
7139e15f359SSam Clegg       writeValueType(Ty);
714f17b149dSPeter Collingbourne     encodeULEB128(FuncTy.Returns.size(), W.OS);
7159e15f359SSam Clegg     for (wasm::ValType Ty : FuncTy.Returns)
7169e15f359SSam Clegg       writeValueType(Ty);
7179e15f359SSam Clegg   }
7189e15f359SSam Clegg 
7199e15f359SSam Clegg   endSection(Section);
7209e15f359SSam Clegg }
7219e15f359SSam Clegg 
7228defa952SSam Clegg void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports,
723f950b24aSSam Clegg                                           uint32_t DataSize,
724f950b24aSSam Clegg                                           uint32_t NumElements) {
7259e15f359SSam Clegg   if (Imports.empty())
7269e15f359SSam Clegg     return;
7279e15f359SSam Clegg 
728f950b24aSSam Clegg   uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
729f950b24aSSam Clegg 
7309e15f359SSam Clegg   SectionBookkeeping Section;
7319e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_IMPORT);
7329e15f359SSam Clegg 
733f17b149dSPeter Collingbourne   encodeULEB128(Imports.size(), W.OS);
7348defa952SSam Clegg   for (const wasm::WasmImport &Import : Imports) {
7358defa952SSam Clegg     writeString(Import.Module);
7368defa952SSam Clegg     writeString(Import.Field);
737f17b149dSPeter Collingbourne     W.OS << char(Import.Kind);
7389e15f359SSam Clegg 
7399e15f359SSam Clegg     switch (Import.Kind) {
7409e15f359SSam Clegg     case wasm::WASM_EXTERNAL_FUNCTION:
741f17b149dSPeter Collingbourne       encodeULEB128(Import.SigIndex, W.OS);
7429e15f359SSam Clegg       break;
7439e15f359SSam Clegg     case wasm::WASM_EXTERNAL_GLOBAL:
744f17b149dSPeter Collingbourne       W.OS << char(Import.Global.Type);
745f17b149dSPeter Collingbourne       W.OS << char(Import.Global.Mutable ? 1 : 0);
7469e15f359SSam Clegg       break;
747f950b24aSSam Clegg     case wasm::WASM_EXTERNAL_MEMORY:
748f17b149dSPeter Collingbourne       encodeULEB128(0, W.OS);        // flags
749f17b149dSPeter Collingbourne       encodeULEB128(NumPages, W.OS); // initial
750f950b24aSSam Clegg       break;
751f950b24aSSam Clegg     case wasm::WASM_EXTERNAL_TABLE:
752f17b149dSPeter Collingbourne       W.OS << char(Import.Table.ElemType);
753f17b149dSPeter Collingbourne       encodeULEB128(0, W.OS);           // flags
754f17b149dSPeter Collingbourne       encodeULEB128(NumElements, W.OS); // initial
755f950b24aSSam Clegg       break;
7569e15f359SSam Clegg     default:
7579e15f359SSam Clegg       llvm_unreachable("unsupported import kind");
7589e15f359SSam Clegg     }
7599e15f359SSam Clegg   }
7609e15f359SSam Clegg 
7619e15f359SSam Clegg   endSection(Section);
7629e15f359SSam Clegg }
7639e15f359SSam Clegg 
764457fb0b4SSam Clegg void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
7659e15f359SSam Clegg   if (Functions.empty())
7669e15f359SSam Clegg     return;
7679e15f359SSam Clegg 
7689e15f359SSam Clegg   SectionBookkeeping Section;
7699e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_FUNCTION);
7709e15f359SSam Clegg 
771f17b149dSPeter Collingbourne   encodeULEB128(Functions.size(), W.OS);
7729e15f359SSam Clegg   for (const WasmFunction &Func : Functions)
773f17b149dSPeter Collingbourne     encodeULEB128(Func.Type, W.OS);
7749e15f359SSam Clegg 
7759e15f359SSam Clegg   endSection(Section);
7769e15f359SSam Clegg }
7779e15f359SSam Clegg 
7787c395943SSam Clegg void WasmObjectWriter::writeGlobalSection() {
7799e15f359SSam Clegg   if (Globals.empty())
7809e15f359SSam Clegg     return;
7819e15f359SSam Clegg 
7829e15f359SSam Clegg   SectionBookkeeping Section;
7839e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_GLOBAL);
7849e15f359SSam Clegg 
785f17b149dSPeter Collingbourne   encodeULEB128(Globals.size(), W.OS);
7869e15f359SSam Clegg   for (const WasmGlobal &Global : Globals) {
7876e7f1826SSam Clegg     writeValueType(static_cast<wasm::ValType>(Global.Type.Type));
788f17b149dSPeter Collingbourne     W.OS << char(Global.Type.Mutable);
7899e15f359SSam Clegg 
790f17b149dSPeter Collingbourne     W.OS << char(wasm::WASM_OPCODE_I32_CONST);
791f17b149dSPeter Collingbourne     encodeSLEB128(Global.InitialValue, W.OS);
792f17b149dSPeter Collingbourne     W.OS << char(wasm::WASM_OPCODE_END);
7939e15f359SSam Clegg   }
7949e15f359SSam Clegg 
7959e15f359SSam Clegg   endSection(Section);
7969e15f359SSam Clegg }
7979e15f359SSam Clegg 
7988defa952SSam Clegg void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) {
7999e15f359SSam Clegg   if (Exports.empty())
8009e15f359SSam Clegg     return;
8019e15f359SSam Clegg 
8029e15f359SSam Clegg   SectionBookkeeping Section;
8039e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_EXPORT);
8049e15f359SSam Clegg 
805f17b149dSPeter Collingbourne   encodeULEB128(Exports.size(), W.OS);
8068defa952SSam Clegg   for (const wasm::WasmExport &Export : Exports) {
8078defa952SSam Clegg     writeString(Export.Name);
808f17b149dSPeter Collingbourne     W.OS << char(Export.Kind);
809f17b149dSPeter Collingbourne     encodeULEB128(Export.Index, W.OS);
8109e15f359SSam Clegg   }
8119e15f359SSam Clegg 
8129e15f359SSam Clegg   endSection(Section);
8139e15f359SSam Clegg }
8149e15f359SSam Clegg 
815457fb0b4SSam Clegg void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
8169e15f359SSam Clegg   if (TableElems.empty())
8179e15f359SSam Clegg     return;
8189e15f359SSam Clegg 
8199e15f359SSam Clegg   SectionBookkeeping Section;
8209e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_ELEM);
8219e15f359SSam Clegg 
822f17b149dSPeter Collingbourne   encodeULEB128(1, W.OS); // number of "segments"
823f17b149dSPeter Collingbourne   encodeULEB128(0, W.OS); // the table index
8249e15f359SSam Clegg 
8259e15f359SSam Clegg   // init expr for starting offset
826f17b149dSPeter Collingbourne   W.OS << char(wasm::WASM_OPCODE_I32_CONST);
827f17b149dSPeter Collingbourne   encodeSLEB128(kInitialTableOffset, W.OS);
828f17b149dSPeter Collingbourne   W.OS << char(wasm::WASM_OPCODE_END);
8299e15f359SSam Clegg 
830f17b149dSPeter Collingbourne   encodeULEB128(TableElems.size(), W.OS);
8319e15f359SSam Clegg   for (uint32_t Elem : TableElems)
832f17b149dSPeter Collingbourne     encodeULEB128(Elem, W.OS);
8339e15f359SSam Clegg 
8349e15f359SSam Clegg   endSection(Section);
8359e15f359SSam Clegg }
8369e15f359SSam Clegg 
837457fb0b4SSam Clegg void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
838457fb0b4SSam Clegg                                         const MCAsmLayout &Layout,
839457fb0b4SSam Clegg                                         ArrayRef<WasmFunction> Functions) {
8409e15f359SSam Clegg   if (Functions.empty())
8419e15f359SSam Clegg     return;
8429e15f359SSam Clegg 
8439e15f359SSam Clegg   SectionBookkeeping Section;
8449e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_CODE);
8456f08c84aSSam Clegg   CodeSectionIndex = Section.Index;
8469e15f359SSam Clegg 
847f17b149dSPeter Collingbourne   encodeULEB128(Functions.size(), W.OS);
8489e15f359SSam Clegg 
8499e15f359SSam Clegg   for (const WasmFunction &Func : Functions) {
850fe6414b0SSam Clegg     auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
8519e15f359SSam Clegg 
8529e15f359SSam Clegg     int64_t Size = 0;
8539e15f359SSam Clegg     if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
8549e15f359SSam Clegg       report_fatal_error(".size expression must be evaluatable");
8559e15f359SSam Clegg 
856f17b149dSPeter Collingbourne     encodeULEB128(Size, W.OS);
857f17b149dSPeter Collingbourne     FuncSection.setSectionOffset(W.OS.tell() - Section.ContentsOffset);
858f17b149dSPeter Collingbourne     Asm.writeSectionData(W.OS, &FuncSection, Layout);
8599e15f359SSam Clegg   }
8609e15f359SSam Clegg 
8619e15f359SSam Clegg   // Apply fixups.
862acd7d2b0SSam Clegg   applyRelocations(CodeRelocations, Section.ContentsOffset);
8639e15f359SSam Clegg 
8649e15f359SSam Clegg   endSection(Section);
8659e15f359SSam Clegg }
8669e15f359SSam Clegg 
8676c899ba6SSam Clegg void WasmObjectWriter::writeDataSection() {
8686c899ba6SSam Clegg   if (DataSegments.empty())
8697c395943SSam Clegg     return;
8709e15f359SSam Clegg 
8719e15f359SSam Clegg   SectionBookkeeping Section;
8729e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_DATA);
8736f08c84aSSam Clegg   DataSectionIndex = Section.Index;
8749e15f359SSam Clegg 
875f17b149dSPeter Collingbourne   encodeULEB128(DataSegments.size(), W.OS); // count
8767c395943SSam Clegg 
8776c899ba6SSam Clegg   for (const WasmDataSegment &Segment : DataSegments) {
878f17b149dSPeter Collingbourne     encodeULEB128(0, W.OS); // memory index
879f17b149dSPeter Collingbourne     W.OS << char(wasm::WASM_OPCODE_I32_CONST);
880f17b149dSPeter Collingbourne     encodeSLEB128(Segment.Offset, W.OS); // offset
881f17b149dSPeter Collingbourne     W.OS << char(wasm::WASM_OPCODE_END);
882f17b149dSPeter Collingbourne     encodeULEB128(Segment.Data.size(), W.OS); // size
883f17b149dSPeter Collingbourne     Segment.Section->setSectionOffset(W.OS.tell() - Section.ContentsOffset);
884f17b149dSPeter Collingbourne     W.OS << Segment.Data; // data
8857c395943SSam Clegg   }
8869e15f359SSam Clegg 
8879e15f359SSam Clegg   // Apply fixups.
8887c395943SSam Clegg   applyRelocations(DataRelocations, Section.ContentsOffset);
8899e15f359SSam Clegg 
8909e15f359SSam Clegg   endSection(Section);
8919e15f359SSam Clegg }
8929e15f359SSam Clegg 
8936f08c84aSSam Clegg void WasmObjectWriter::writeRelocSection(
8946f08c84aSSam Clegg     uint32_t SectionIndex, StringRef Name,
895f77dc2a8SSam Clegg     std::vector<WasmRelocationEntry> &Relocs) {
8969e15f359SSam Clegg   // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
8979e15f359SSam Clegg   // for descriptions of the reloc sections.
8989e15f359SSam Clegg 
899f77dc2a8SSam Clegg   if (Relocs.empty())
9009e15f359SSam Clegg     return;
9019e15f359SSam Clegg 
902f77dc2a8SSam Clegg   // First, ensure the relocations are sorted in offset order.  In general they
903f77dc2a8SSam Clegg   // should already be sorted since `recordRelocation` is called in offset
904f77dc2a8SSam Clegg   // order, but for the code section we combine many MC sections into single
905f77dc2a8SSam Clegg   // wasm section, and this order is determined by the order of Asm.Symbols()
906f77dc2a8SSam Clegg   // not the sections order.
907f77dc2a8SSam Clegg   std::stable_sort(
908f77dc2a8SSam Clegg       Relocs.begin(), Relocs.end(),
909f77dc2a8SSam Clegg       [](const WasmRelocationEntry &A, const WasmRelocationEntry &B) {
910f77dc2a8SSam Clegg         return (A.Offset + A.FixupSection->getSectionOffset()) <
911f77dc2a8SSam Clegg                (B.Offset + B.FixupSection->getSectionOffset());
912f77dc2a8SSam Clegg       });
913f77dc2a8SSam Clegg 
9149e15f359SSam Clegg   SectionBookkeeping Section;
9156f08c84aSSam Clegg   startCustomSection(Section, std::string("reloc.") + Name.str());
9169e15f359SSam Clegg 
917f17b149dSPeter Collingbourne   encodeULEB128(SectionIndex, W.OS);
918f77dc2a8SSam Clegg   encodeULEB128(Relocs.size(), W.OS);
919f77dc2a8SSam Clegg   for (const WasmRelocationEntry &RelEntry : Relocs) {
920f208f631SHeejin Ahn     uint64_t Offset =
921f208f631SHeejin Ahn         RelEntry.Offset + RelEntry.FixupSection->getSectionOffset();
9226f08c84aSSam Clegg     uint32_t Index = getRelocationIndexValue(RelEntry);
9239e15f359SSam Clegg 
924f17b149dSPeter Collingbourne     W.OS << char(RelEntry.Type);
925f17b149dSPeter Collingbourne     encodeULEB128(Offset, W.OS);
926f17b149dSPeter Collingbourne     encodeULEB128(Index, W.OS);
9276f08c84aSSam Clegg     if (RelEntry.hasAddend())
928f17b149dSPeter Collingbourne       encodeSLEB128(RelEntry.Addend, W.OS);
9299e15f359SSam Clegg   }
9309e15f359SSam Clegg 
9319e15f359SSam Clegg   endSection(Section);
9329e15f359SSam Clegg }
9339e15f359SSam Clegg 
9346a31a0d6SSam Clegg void WasmObjectWriter::writeCustomRelocSections() {
9356a31a0d6SSam Clegg   for (const auto &Sec : CustomSections) {
9366a31a0d6SSam Clegg     auto &Relocations = CustomSectionsRelocations[Sec.Section];
9376a31a0d6SSam Clegg     writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations);
9386a31a0d6SSam Clegg   }
9396a31a0d6SSam Clegg }
9406a31a0d6SSam Clegg 
9419e15f359SSam Clegg void WasmObjectWriter::writeLinkingMetaDataSection(
94286b4a09aSSam Clegg     ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
943ea7caceeSSam Clegg     ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
944ea7caceeSSam Clegg     const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) {
9459e15f359SSam Clegg   SectionBookkeeping Section;
9462322a937SSam Clegg   startCustomSection(Section, "linking");
947f17b149dSPeter Collingbourne   encodeULEB128(wasm::WasmMetadataVersion, W.OS);
9489e15f359SSam Clegg 
9496bb5a41fSSam Clegg   SectionBookkeeping SubSection;
9506c899ba6SSam Clegg   if (SymbolInfos.size() != 0) {
9516c899ba6SSam Clegg     startSection(SubSection, wasm::WASM_SYMBOL_TABLE);
952f17b149dSPeter Collingbourne     encodeULEB128(SymbolInfos.size(), W.OS);
9536c899ba6SSam Clegg     for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) {
954f17b149dSPeter Collingbourne       encodeULEB128(Sym.Kind, W.OS);
955f17b149dSPeter Collingbourne       encodeULEB128(Sym.Flags, W.OS);
9566c899ba6SSam Clegg       switch (Sym.Kind) {
9576c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_FUNCTION:
9586c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_GLOBAL:
959f17b149dSPeter Collingbourne         encodeULEB128(Sym.ElementIndex, W.OS);
9606c899ba6SSam Clegg         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0)
9616c899ba6SSam Clegg           writeString(Sym.Name);
9626c899ba6SSam Clegg         break;
9636c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_DATA:
9646c899ba6SSam Clegg         writeString(Sym.Name);
9656c899ba6SSam Clegg         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) {
966f17b149dSPeter Collingbourne           encodeULEB128(Sym.DataRef.Segment, W.OS);
967f17b149dSPeter Collingbourne           encodeULEB128(Sym.DataRef.Offset, W.OS);
968f17b149dSPeter Collingbourne           encodeULEB128(Sym.DataRef.Size, W.OS);
9696c899ba6SSam Clegg         }
9706c899ba6SSam Clegg         break;
9716a31a0d6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_SECTION: {
9726a31a0d6SSam Clegg         const uint32_t SectionIndex =
9736a31a0d6SSam Clegg             CustomSections[Sym.ElementIndex].OutputIndex;
974f17b149dSPeter Collingbourne         encodeULEB128(SectionIndex, W.OS);
9756a31a0d6SSam Clegg         break;
9766a31a0d6SSam Clegg       }
9776c899ba6SSam Clegg       default:
9786c899ba6SSam Clegg         llvm_unreachable("unexpected kind");
9796c899ba6SSam Clegg       }
980b7787fd0SSam Clegg     }
981b7787fd0SSam Clegg     endSection(SubSection);
982b7787fd0SSam Clegg   }
9839e15f359SSam Clegg 
9846c899ba6SSam Clegg   if (DataSegments.size()) {
98563ebb813SSam Clegg     startSection(SubSection, wasm::WASM_SEGMENT_INFO);
986f17b149dSPeter Collingbourne     encodeULEB128(DataSegments.size(), W.OS);
9876c899ba6SSam Clegg     for (const WasmDataSegment &Segment : DataSegments) {
988d95ed959SSam Clegg       writeString(Segment.Name);
989f17b149dSPeter Collingbourne       encodeULEB128(Segment.Alignment, W.OS);
990f17b149dSPeter Collingbourne       encodeULEB128(Segment.Flags, W.OS);
99163ebb813SSam Clegg     }
992d95ed959SSam Clegg     endSection(SubSection);
993d95ed959SSam Clegg   }
994d95ed959SSam Clegg 
995bafe6902SSam Clegg   if (!InitFuncs.empty()) {
996bafe6902SSam Clegg     startSection(SubSection, wasm::WASM_INIT_FUNCS);
997f17b149dSPeter Collingbourne     encodeULEB128(InitFuncs.size(), W.OS);
998bafe6902SSam Clegg     for (auto &StartFunc : InitFuncs) {
999f17b149dSPeter Collingbourne       encodeULEB128(StartFunc.first, W.OS);  // priority
1000f17b149dSPeter Collingbourne       encodeULEB128(StartFunc.second, W.OS); // function index
1001bafe6902SSam Clegg     }
1002bafe6902SSam Clegg     endSection(SubSection);
1003bafe6902SSam Clegg   }
1004bafe6902SSam Clegg 
1005ea7caceeSSam Clegg   if (Comdats.size()) {
1006ea7caceeSSam Clegg     startSection(SubSection, wasm::WASM_COMDAT_INFO);
1007f17b149dSPeter Collingbourne     encodeULEB128(Comdats.size(), W.OS);
1008ea7caceeSSam Clegg     for (const auto &C : Comdats) {
1009ea7caceeSSam Clegg       writeString(C.first);
1010f17b149dSPeter Collingbourne       encodeULEB128(0, W.OS); // flags for future use
1011f17b149dSPeter Collingbourne       encodeULEB128(C.second.size(), W.OS);
1012ea7caceeSSam Clegg       for (const WasmComdatEntry &Entry : C.second) {
1013f17b149dSPeter Collingbourne         encodeULEB128(Entry.Kind, W.OS);
1014f17b149dSPeter Collingbourne         encodeULEB128(Entry.Index, W.OS);
1015ea7caceeSSam Clegg       }
1016ea7caceeSSam Clegg     }
1017ea7caceeSSam Clegg     endSection(SubSection);
1018ea7caceeSSam Clegg   }
1019ea7caceeSSam Clegg 
10209e15f359SSam Clegg   endSection(Section);
10219e15f359SSam Clegg }
10229e15f359SSam Clegg 
10236a31a0d6SSam Clegg void WasmObjectWriter::writeCustomSections(const MCAssembler &Asm,
10246a31a0d6SSam Clegg                                            const MCAsmLayout &Layout) {
10256a31a0d6SSam Clegg   for (auto &CustomSection : CustomSections) {
1026cfd44a2eSSam Clegg     SectionBookkeeping Section;
10276a31a0d6SSam Clegg     auto *Sec = CustomSection.Section;
10282322a937SSam Clegg     startCustomSection(Section, CustomSection.Name);
10296a31a0d6SSam Clegg 
1030f17b149dSPeter Collingbourne     Sec->setSectionOffset(W.OS.tell() - Section.ContentsOffset);
1031f17b149dSPeter Collingbourne     Asm.writeSectionData(W.OS, Sec, Layout);
10326a31a0d6SSam Clegg 
10336a31a0d6SSam Clegg     CustomSection.OutputContentsOffset = Section.ContentsOffset;
10346a31a0d6SSam Clegg     CustomSection.OutputIndex = Section.Index;
10356a31a0d6SSam Clegg 
1036cfd44a2eSSam Clegg     endSection(Section);
10376a31a0d6SSam Clegg 
10386a31a0d6SSam Clegg     // Apply fixups.
10394d57fbd0SSam Clegg     auto &Relocations = CustomSectionsRelocations[CustomSection.Section];
10404d57fbd0SSam Clegg     applyRelocations(Relocations, CustomSection.OutputContentsOffset);
10416a31a0d6SSam Clegg   }
10426a31a0d6SSam Clegg }
10436a31a0d6SSam Clegg 
10445e3d33a7SSam Clegg uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm &Symbol) {
10455e3d33a7SSam Clegg   assert(Symbol.isFunction());
10465e3d33a7SSam Clegg   assert(TypeIndices.count(&Symbol));
10475e3d33a7SSam Clegg   return TypeIndices[&Symbol];
10485e3d33a7SSam Clegg }
10495e3d33a7SSam Clegg 
10505e3d33a7SSam Clegg uint32_t WasmObjectWriter::registerFunctionType(const MCSymbolWasm &Symbol) {
10515e3d33a7SSam Clegg   assert(Symbol.isFunction());
10525e3d33a7SSam Clegg 
10535e3d33a7SSam Clegg   WasmFunctionType F;
1054aff1c4dfSSam Clegg   const MCSymbolWasm *ResolvedSym = ResolveSymbol(Symbol);
105577a7a380SDerek Schuff   if (auto *Sig = ResolvedSym->getSignature()) {
105677a7a380SDerek Schuff     F.Returns = Sig->Returns;
105777a7a380SDerek Schuff     F.Params = Sig->Params;
105877a7a380SDerek Schuff   }
10595e3d33a7SSam Clegg 
10605e3d33a7SSam Clegg   auto Pair =
10615e3d33a7SSam Clegg       FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size()));
10625e3d33a7SSam Clegg   if (Pair.second)
10635e3d33a7SSam Clegg     FunctionTypes.push_back(F);
10645e3d33a7SSam Clegg   TypeIndices[&Symbol] = Pair.first->second;
10655e3d33a7SSam Clegg 
1066d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "registerFunctionType: " << Symbol
1067d34e60caSNicola Zaghen                     << " new:" << Pair.second << "\n");
1068d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
10695e3d33a7SSam Clegg   return Pair.first->second;
10705e3d33a7SSam Clegg }
10715e3d33a7SSam Clegg 
10724d57fbd0SSam Clegg static bool isInSymtab(const MCSymbolWasm &Sym) {
10734d57fbd0SSam Clegg   if (Sym.isUsedInReloc())
10744d57fbd0SSam Clegg     return true;
10754d57fbd0SSam Clegg 
10764d57fbd0SSam Clegg   if (Sym.isComdat() && !Sym.isDefined())
10774d57fbd0SSam Clegg     return false;
10784d57fbd0SSam Clegg 
10794d57fbd0SSam Clegg   if (Sym.isTemporary() && Sym.getName().empty())
10804d57fbd0SSam Clegg     return false;
10814d57fbd0SSam Clegg 
10824d57fbd0SSam Clegg   if (Sym.isTemporary() && Sym.isData() && !Sym.getSize())
10834d57fbd0SSam Clegg     return false;
10844d57fbd0SSam Clegg 
10854d57fbd0SSam Clegg   if (Sym.isSection())
10864d57fbd0SSam Clegg     return false;
10874d57fbd0SSam Clegg 
10884d57fbd0SSam Clegg   return true;
10894d57fbd0SSam Clegg }
10904d57fbd0SSam Clegg 
1091438390faSPeter Collingbourne uint64_t WasmObjectWriter::writeObject(MCAssembler &Asm,
109218eafb6cSDan Gohman                                        const MCAsmLayout &Layout) {
1093438390faSPeter Collingbourne   uint64_t StartOffset = W.OS.tell();
1094438390faSPeter Collingbourne 
1095d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
109682607f56SDan Gohman   MCContext &Ctx = Asm.getContext();
1097d934cb88SDan Gohman 
1098d934cb88SDan Gohman   // Collect information from the available symbols.
1099d934cb88SDan Gohman   SmallVector<WasmFunction, 4> Functions;
1100d934cb88SDan Gohman   SmallVector<uint32_t, 4> TableElems;
11018defa952SSam Clegg   SmallVector<wasm::WasmImport, 4> Imports;
11028defa952SSam Clegg   SmallVector<wasm::WasmExport, 4> Exports;
11036c899ba6SSam Clegg   SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos;
1104bafe6902SSam Clegg   SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
1105ea7caceeSSam Clegg   std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
11067c395943SSam Clegg   uint32_t DataSize = 0;
1107d934cb88SDan Gohman 
1108f950b24aSSam Clegg   // For now, always emit the memory import, since loads and stores are not
1109f950b24aSSam Clegg   // valid without it. In the future, we could perhaps be more clever and omit
1110f950b24aSSam Clegg   // it if there are no loads or stores.
1111f950b24aSSam Clegg   MCSymbolWasm *MemorySym =
1112f950b24aSSam Clegg       cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__linear_memory"));
11138defa952SSam Clegg   wasm::WasmImport MemImport;
11148defa952SSam Clegg   MemImport.Module = MemorySym->getModuleName();
11158defa952SSam Clegg   MemImport.Field = MemorySym->getName();
1116f950b24aSSam Clegg   MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
1117f950b24aSSam Clegg   Imports.push_back(MemImport);
1118f950b24aSSam Clegg 
1119f950b24aSSam Clegg   // For now, always emit the table section, since indirect calls are not
1120f950b24aSSam Clegg   // valid without it. In the future, we could perhaps be more clever and omit
1121f950b24aSSam Clegg   // it if there are no indirect calls.
1122f950b24aSSam Clegg   MCSymbolWasm *TableSym =
1123f950b24aSSam Clegg       cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__indirect_function_table"));
11248defa952SSam Clegg   wasm::WasmImport TableImport;
11258defa952SSam Clegg   TableImport.Module = TableSym->getModuleName();
11268defa952SSam Clegg   TableImport.Field = TableSym->getName();
1127f950b24aSSam Clegg   TableImport.Kind = wasm::WASM_EXTERNAL_TABLE;
11288defa952SSam Clegg   TableImport.Table.ElemType = wasm::WASM_TYPE_ANYFUNC;
1129f950b24aSSam Clegg   Imports.push_back(TableImport);
1130f950b24aSSam Clegg 
1131586320c0SNicholas Wilson   // Populate FunctionTypeIndices, and Imports and WasmIndices for undefined
1132586320c0SNicholas Wilson   // symbols.  This must be done before populating WasmIndices for defined
1133586320c0SNicholas Wilson   // symbols.
113432ce5ca0SDan Gohman   for (const MCSymbol &S : Asm.symbols()) {
113532ce5ca0SDan Gohman     const auto &WS = static_cast<const MCSymbolWasm &>(S);
113632ce5ca0SDan Gohman 
113732ce5ca0SDan Gohman     // Register types for all functions, including those with private linkage
11389f3fe42eSSam Clegg     // (because wasm always needs a type signature).
113932ce5ca0SDan Gohman     if (WS.isFunction())
114032ce5ca0SDan Gohman       registerFunctionType(WS);
114132ce5ca0SDan Gohman 
114232ce5ca0SDan Gohman     if (WS.isTemporary())
114332ce5ca0SDan Gohman       continue;
114432ce5ca0SDan Gohman 
114532ce5ca0SDan Gohman     // If the symbol is not defined in this translation unit, import it.
11466c899ba6SSam Clegg     if (!WS.isDefined() && !WS.isComdat()) {
11476c899ba6SSam Clegg       if (WS.isFunction()) {
11488defa952SSam Clegg         wasm::WasmImport Import;
11498defa952SSam Clegg         Import.Module = WS.getModuleName();
11508defa952SSam Clegg         Import.Field = WS.getName();
115132ce5ca0SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
11528defa952SSam Clegg         Import.SigIndex = getFunctionType(WS);
11536c899ba6SSam Clegg         Imports.push_back(Import);
11546c899ba6SSam Clegg         WasmIndices[&WS] = NumFunctionImports++;
11556c899ba6SSam Clegg       } else if (WS.isGlobal()) {
115615f349f7SNicholas Wilson         if (WS.isWeak())
115715f349f7SNicholas Wilson           report_fatal_error("undefined global symbol cannot be weak");
115815f349f7SNicholas Wilson 
11596c899ba6SSam Clegg         wasm::WasmImport Import;
11606c899ba6SSam Clegg         Import.Module = WS.getModuleName();
11616c899ba6SSam Clegg         Import.Field = WS.getName();
116232ce5ca0SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
11636c899ba6SSam Clegg         Import.Global = WS.getGlobalType();
11646c899ba6SSam Clegg         Imports.push_back(Import);
11656c899ba6SSam Clegg         WasmIndices[&WS] = NumGlobalImports++;
116632ce5ca0SDan Gohman       }
116732ce5ca0SDan Gohman     }
116832ce5ca0SDan Gohman   }
116932ce5ca0SDan Gohman 
11704d57fbd0SSam Clegg   // Populate DataSegments and CustomSections, which must be done before
11714d57fbd0SSam Clegg   // populating DataLocations.
1172759631c7SSam Clegg   for (MCSection &Sec : Asm) {
1173759631c7SSam Clegg     auto &Section = static_cast<MCSectionWasm &>(Sec);
11744d57fbd0SSam Clegg     StringRef SectionName = Section.getSectionName();
1175759631c7SSam Clegg 
1176bafe6902SSam Clegg     // .init_array sections are handled specially elsewhere.
11774d57fbd0SSam Clegg     if (SectionName.startswith(".init_array"))
1178bafe6902SSam Clegg       continue;
1179bafe6902SSam Clegg 
11804d57fbd0SSam Clegg     // Code is handled separately
11814d57fbd0SSam Clegg     if (Section.getKind().isText())
11824d57fbd0SSam Clegg       continue;
11834d57fbd0SSam Clegg 
11844d57fbd0SSam Clegg     if (Section.isWasmData()) {
1185329e76d5SSam Clegg       uint32_t SegmentIndex = DataSegments.size();
1186759631c7SSam Clegg       DataSize = alignTo(DataSize, Section.getAlignment());
1187759631c7SSam Clegg       DataSegments.emplace_back();
1188759631c7SSam Clegg       WasmDataSegment &Segment = DataSegments.back();
11894d57fbd0SSam Clegg       Segment.Name = SectionName;
1190759631c7SSam Clegg       Segment.Offset = DataSize;
1191759631c7SSam Clegg       Segment.Section = &Section;
119263ebb813SSam Clegg       addData(Segment.Data, Section);
119363ebb813SSam Clegg       Segment.Alignment = Section.getAlignment();
119463ebb813SSam Clegg       Segment.Flags = 0;
1195759631c7SSam Clegg       DataSize += Segment.Data.size();
11966c899ba6SSam Clegg       Section.setSegmentIndex(SegmentIndex);
1197ea7caceeSSam Clegg 
1198ea7caceeSSam Clegg       if (const MCSymbolWasm *C = Section.getGroup()) {
1199ea7caceeSSam Clegg         Comdats[C->getName()].emplace_back(
1200329e76d5SSam Clegg             WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
1201ea7caceeSSam Clegg       }
12024d57fbd0SSam Clegg     } else {
12034d57fbd0SSam Clegg       // Create custom sections
12044d57fbd0SSam Clegg       assert(Sec.getKind().isMetadata());
12054d57fbd0SSam Clegg 
12064d57fbd0SSam Clegg       StringRef Name = SectionName;
12074d57fbd0SSam Clegg 
12084d57fbd0SSam Clegg       // For user-defined custom sections, strip the prefix
12094d57fbd0SSam Clegg       if (Name.startswith(".custom_section."))
12104d57fbd0SSam Clegg         Name = Name.substr(strlen(".custom_section."));
12114d57fbd0SSam Clegg 
12124d57fbd0SSam Clegg       MCSymbol *Begin = Sec.getBeginSymbol();
1213fb807d4dSSam Clegg       if (Begin) {
12144d57fbd0SSam Clegg         WasmIndices[cast<MCSymbolWasm>(Begin)] = CustomSections.size();
1215b210c64bSSam Clegg         if (SectionName != Begin->getName())
1216fb807d4dSSam Clegg           report_fatal_error("section name and begin symbol should match: " +
1217b210c64bSSam Clegg                              Twine(SectionName));
1218fb807d4dSSam Clegg       }
12194d57fbd0SSam Clegg       CustomSections.emplace_back(Name, &Section);
1220759631c7SSam Clegg     }
12216a31a0d6SSam Clegg   }
12226a31a0d6SSam Clegg 
1223586320c0SNicholas Wilson   // Populate WasmIndices and DataLocations for defined symbols.
1224d934cb88SDan Gohman   for (const MCSymbol &S : Asm.symbols()) {
1225d934cb88SDan Gohman     // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1226d934cb88SDan Gohman     // or used in relocations.
1227d934cb88SDan Gohman     if (S.isTemporary() && S.getName().empty())
1228d934cb88SDan Gohman       continue;
1229b7787fd0SSam Clegg 
1230d934cb88SDan Gohman     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1231d34e60caSNicola Zaghen     LLVM_DEBUG(
1232d34e60caSNicola Zaghen         dbgs() << "MCSymbol: " << toString(WS.getType()) << " '" << S << "'"
1233d34e60caSNicola Zaghen                << " isDefined=" << S.isDefined() << " isExternal="
1234d34e60caSNicola Zaghen                << S.isExternal() << " isTemporary=" << S.isTemporary()
1235d34e60caSNicola Zaghen                << " isWeak=" << WS.isWeak() << " isHidden=" << WS.isHidden()
1236b7787fd0SSam Clegg                << " isVariable=" << WS.isVariable() << "\n");
1237b7787fd0SSam Clegg 
12385e3d33a7SSam Clegg     if (WS.isVariable())
12395e3d33a7SSam Clegg       continue;
12406c899ba6SSam Clegg     if (WS.isComdat() && !WS.isDefined())
12416c899ba6SSam Clegg       continue;
1242b7787fd0SSam Clegg 
1243d934cb88SDan Gohman     if (WS.isFunction()) {
12446c899ba6SSam Clegg       unsigned Index;
1245cd65f698SSam Clegg       if (WS.isDefined()) {
1246b7787fd0SSam Clegg         if (WS.getOffset() != 0)
1247b7787fd0SSam Clegg           report_fatal_error(
1248b7787fd0SSam Clegg               "function sections must contain one function each");
1249b7787fd0SSam Clegg 
1250b7787fd0SSam Clegg         if (WS.getSize() == 0)
1251b7787fd0SSam Clegg           report_fatal_error(
1252b7787fd0SSam Clegg               "function symbols must have a size set with .size");
1253b7787fd0SSam Clegg 
12546c899ba6SSam Clegg         // A definition. Write out the function body.
12559f3fe42eSSam Clegg         Index = NumFunctionImports + Functions.size();
1256d934cb88SDan Gohman         WasmFunction Func;
12575e3d33a7SSam Clegg         Func.Type = getFunctionType(WS);
1258d934cb88SDan Gohman         Func.Sym = &WS;
12596c899ba6SSam Clegg         WasmIndices[&WS] = Index;
1260d934cb88SDan Gohman         Functions.push_back(Func);
12616c899ba6SSam Clegg 
12626c899ba6SSam Clegg         auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
12636c899ba6SSam Clegg         if (const MCSymbolWasm *C = Section.getGroup()) {
12646c899ba6SSam Clegg           Comdats[C->getName()].emplace_back(
12656c899ba6SSam Clegg               WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
12666c899ba6SSam Clegg         }
1267d934cb88SDan Gohman       } else {
1268d934cb88SDan Gohman         // An import; the index was assigned above.
12696c899ba6SSam Clegg         Index = WasmIndices.find(&WS)->second;
1270d934cb88SDan Gohman       }
1271d934cb88SDan Gohman 
1272d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> function index: " << Index << "\n");
12736c899ba6SSam Clegg     } else if (WS.isData()) {
1274c38e947eSSam Clegg       if (WS.isTemporary() && !WS.getSize())
1275c38e947eSSam Clegg         continue;
1276c38e947eSSam Clegg 
12776c899ba6SSam Clegg       if (!WS.isDefined()) {
1278d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "  -> segment index: -1"
1279d34e60caSNicola Zaghen                           << "\n");
1280fe6414b0SSam Clegg         continue;
12816c899ba6SSam Clegg       }
1282fe6414b0SSam Clegg 
1283d934cb88SDan Gohman       if (!WS.getSize())
1284c38e947eSSam Clegg         report_fatal_error("data symbols must have a size set with .size: " +
1285c38e947eSSam Clegg                            WS.getName());
1286d934cb88SDan Gohman 
1287d934cb88SDan Gohman       int64_t Size = 0;
1288d934cb88SDan Gohman       if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1289d934cb88SDan Gohman         report_fatal_error(".size expression must be evaluatable");
1290d934cb88SDan Gohman 
1291759631c7SSam Clegg       auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
1292ea7caceeSSam Clegg       assert(DataSection.isWasmData());
12937c395943SSam Clegg 
12946c899ba6SSam Clegg       // For each data symbol, export it in the symtab as a reference to the
12956c899ba6SSam Clegg       // corresponding Wasm data segment.
12966c899ba6SSam Clegg       wasm::WasmDataReference Ref = wasm::WasmDataReference{
12976c899ba6SSam Clegg           DataSection.getSegmentIndex(),
12986c899ba6SSam Clegg           static_cast<uint32_t>(Layout.getSymbolOffset(WS)),
12996c899ba6SSam Clegg           static_cast<uint32_t>(Size)};
13006c899ba6SSam Clegg       DataLocations[&WS] = Ref;
1301d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> segment index: " << Ref.Segment << "\n");
1302a165f2d6SSam Clegg     } else if (WS.isGlobal()) {
13036c899ba6SSam Clegg       // A "true" Wasm global (currently just __stack_pointer)
1304545932beSEric Christopher       if (WS.isDefined())
13056c899ba6SSam Clegg         report_fatal_error("don't yet support defined globals");
13066c899ba6SSam Clegg 
1307545932beSEric Christopher       // An import; the index was assigned above
1308d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> global index: "
1309d34e60caSNicola Zaghen                         << WasmIndices.find(&WS)->second << "\n");
1310a165f2d6SSam Clegg     } else {
1311a165f2d6SSam Clegg       assert(WS.isSection());
1312d934cb88SDan Gohman     }
1313d934cb88SDan Gohman   }
1314d934cb88SDan Gohman 
1315586320c0SNicholas Wilson   // Populate WasmIndices and DataLocations for aliased symbols.  We need to
1316586320c0SNicholas Wilson   // process these in a separate pass because we need to have processed the
1317586320c0SNicholas Wilson   // target of the alias before the alias itself and the symbols are not
1318586320c0SNicholas Wilson   // necessarily ordered in this way.
1319b7787fd0SSam Clegg   for (const MCSymbol &S : Asm.symbols()) {
1320b7787fd0SSam Clegg     if (!S.isVariable())
1321b7787fd0SSam Clegg       continue;
132231a2c809SSam Clegg 
1323cd65f698SSam Clegg     assert(S.isDefined());
1324b7787fd0SSam Clegg 
13255e3d33a7SSam Clegg     // Find the target symbol of this weak alias and export that index
1326aff1c4dfSSam Clegg     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1327aff1c4dfSSam Clegg     const MCSymbolWasm *ResolvedSym = ResolveSymbol(WS);
1328d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym
1329d34e60caSNicola Zaghen                       << "'\n");
1330b7787fd0SSam Clegg 
13316c899ba6SSam Clegg     if (WS.isFunction()) {
13326c899ba6SSam Clegg       assert(WasmIndices.count(ResolvedSym) > 0);
13336c899ba6SSam Clegg       uint32_t WasmIndex = WasmIndices.find(ResolvedSym)->second;
13346c899ba6SSam Clegg       WasmIndices[&WS] = WasmIndex;
1335d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> index:" << WasmIndex << "\n");
13366c899ba6SSam Clegg     } else if (WS.isData()) {
13376c899ba6SSam Clegg       assert(DataLocations.count(ResolvedSym) > 0);
13386c899ba6SSam Clegg       const wasm::WasmDataReference &Ref =
13396c899ba6SSam Clegg           DataLocations.find(ResolvedSym)->second;
13406c899ba6SSam Clegg       DataLocations[&WS] = Ref;
1341d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> index:" << Ref.Segment << "\n");
13426c899ba6SSam Clegg     } else {
13436c899ba6SSam Clegg       report_fatal_error("don't yet support global aliases");
13446c899ba6SSam Clegg     }
1345586320c0SNicholas Wilson   }
134631a2c809SSam Clegg 
1347586320c0SNicholas Wilson   // Finally, populate the symbol table itself, in its "natural" order.
1348586320c0SNicholas Wilson   for (const MCSymbol &S : Asm.symbols()) {
1349586320c0SNicholas Wilson     const auto &WS = static_cast<const MCSymbolWasm &>(S);
135025d8e68bSSam Clegg     if (!isInSymtab(WS)) {
135125d8e68bSSam Clegg       WS.setIndex(INVALID_INDEX);
1352586320c0SNicholas Wilson       continue;
135325d8e68bSSam Clegg     }
1354d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "adding to symtab: " << WS << "\n");
1355586320c0SNicholas Wilson 
1356586320c0SNicholas Wilson     uint32_t Flags = 0;
1357586320c0SNicholas Wilson     if (WS.isWeak())
1358586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_BINDING_WEAK;
1359586320c0SNicholas Wilson     if (WS.isHidden())
1360586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN;
1361586320c0SNicholas Wilson     if (!WS.isExternal() && WS.isDefined())
1362586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;
1363586320c0SNicholas Wilson     if (WS.isUndefined())
1364586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_UNDEFINED;
1365586320c0SNicholas Wilson 
1366586320c0SNicholas Wilson     wasm::WasmSymbolInfo Info;
1367586320c0SNicholas Wilson     Info.Name = WS.getName();
1368586320c0SNicholas Wilson     Info.Kind = WS.getType();
1369586320c0SNicholas Wilson     Info.Flags = Flags;
13704d57fbd0SSam Clegg     if (!WS.isData()) {
13714d57fbd0SSam Clegg       assert(WasmIndices.count(&WS) > 0);
1372586320c0SNicholas Wilson       Info.ElementIndex = WasmIndices.find(&WS)->second;
13734d57fbd0SSam Clegg     } else if (WS.isDefined()) {
13744d57fbd0SSam Clegg       assert(DataLocations.count(&WS) > 0);
1375586320c0SNicholas Wilson       Info.DataRef = DataLocations.find(&WS)->second;
13764d57fbd0SSam Clegg     }
137725d8e68bSSam Clegg     WS.setIndex(SymbolInfos.size());
1378586320c0SNicholas Wilson     SymbolInfos.emplace_back(Info);
1379b7787fd0SSam Clegg   }
1380b7787fd0SSam Clegg 
13816006e091SSam Clegg   {
13826006e091SSam Clegg     auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
1383f9edbe95SSam Clegg       // Functions referenced by a relocation need to put in the table.  This is
1384f9edbe95SSam Clegg       // purely to make the object file's provisional values readable, and is
1385f9edbe95SSam Clegg       // ignored by the linker, which re-calculates the relocations itself.
1386f9edbe95SSam Clegg       if (Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_I32 &&
1387f9edbe95SSam Clegg           Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB)
1388f9edbe95SSam Clegg         return;
1389f9edbe95SSam Clegg       assert(Rel.Symbol->isFunction());
1390f9edbe95SSam Clegg       const MCSymbolWasm &WS = *ResolveSymbol(*Rel.Symbol);
13916c899ba6SSam Clegg       uint32_t FunctionIndex = WasmIndices.find(&WS)->second;
1392f9edbe95SSam Clegg       uint32_t TableIndex = TableElems.size() + kInitialTableOffset;
1393f9edbe95SSam Clegg       if (TableIndices.try_emplace(&WS, TableIndex).second) {
1394d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "  -> adding " << WS.getName()
1395f9edbe95SSam Clegg                           << " to table: " << TableIndex << "\n");
13966c899ba6SSam Clegg         TableElems.push_back(FunctionIndex);
13976006e091SSam Clegg         registerFunctionType(WS);
13986006e091SSam Clegg       }
13996006e091SSam Clegg     };
1400970d02c4SDan Gohman 
14016006e091SSam Clegg     for (const WasmRelocationEntry &RelEntry : CodeRelocations)
14026006e091SSam Clegg       HandleReloc(RelEntry);
14036006e091SSam Clegg     for (const WasmRelocationEntry &RelEntry : DataRelocations)
14046006e091SSam Clegg       HandleReloc(RelEntry);
1405d934cb88SDan Gohman   }
1406d934cb88SDan Gohman 
1407bafe6902SSam Clegg   // Translate .init_array section contents into start functions.
1408bafe6902SSam Clegg   for (const MCSection &S : Asm) {
1409bafe6902SSam Clegg     const auto &WS = static_cast<const MCSectionWasm &>(S);
1410bafe6902SSam Clegg     if (WS.getSectionName().startswith(".fini_array"))
1411bafe6902SSam Clegg       report_fatal_error(".fini_array sections are unsupported");
1412bafe6902SSam Clegg     if (!WS.getSectionName().startswith(".init_array"))
1413bafe6902SSam Clegg       continue;
1414bafe6902SSam Clegg     if (WS.getFragmentList().empty())
1415bafe6902SSam Clegg       continue;
1416b210c64bSSam Clegg 
1417b210c64bSSam Clegg     // init_array is expected to contain a single non-empty data fragment
1418b210c64bSSam Clegg     if (WS.getFragmentList().size() != 3)
1419bafe6902SSam Clegg       report_fatal_error("only one .init_array section fragment supported");
1420b210c64bSSam Clegg 
1421b210c64bSSam Clegg     auto IT = WS.begin();
1422b210c64bSSam Clegg     const MCFragment &EmptyFrag = *IT;
1423b210c64bSSam Clegg     if (EmptyFrag.getKind() != MCFragment::FT_Data)
1424b210c64bSSam Clegg       report_fatal_error(".init_array section should be aligned");
1425b210c64bSSam Clegg 
1426b210c64bSSam Clegg     IT = std::next(IT);
1427b210c64bSSam Clegg     const MCFragment &AlignFrag = *IT;
1428bafe6902SSam Clegg     if (AlignFrag.getKind() != MCFragment::FT_Align)
1429bafe6902SSam Clegg       report_fatal_error(".init_array section should be aligned");
1430bafe6902SSam Clegg     if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
1431bafe6902SSam Clegg       report_fatal_error(".init_array section should be aligned for pointers");
1432b210c64bSSam Clegg 
1433b210c64bSSam Clegg     const MCFragment &Frag = *std::next(IT);
1434bafe6902SSam Clegg     if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1435bafe6902SSam Clegg       report_fatal_error("only data supported in .init_array section");
1436b210c64bSSam Clegg 
1437bafe6902SSam Clegg     uint16_t Priority = UINT16_MAX;
14384d57fbd0SSam Clegg     unsigned PrefixLength = strlen(".init_array");
14394d57fbd0SSam Clegg     if (WS.getSectionName().size() > PrefixLength) {
14404d57fbd0SSam Clegg       if (WS.getSectionName()[PrefixLength] != '.')
1441f208f631SHeejin Ahn         report_fatal_error(
1442f208f631SHeejin Ahn             ".init_array section priority should start with '.'");
14434d57fbd0SSam Clegg       if (WS.getSectionName()
14444d57fbd0SSam Clegg               .substr(PrefixLength + 1)
14454d57fbd0SSam Clegg               .getAsInteger(10, Priority))
1446bafe6902SSam Clegg         report_fatal_error("invalid .init_array section priority");
1447bafe6902SSam Clegg     }
1448bafe6902SSam Clegg     const auto &DataFrag = cast<MCDataFragment>(Frag);
1449bafe6902SSam Clegg     const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1450f208f631SHeejin Ahn     for (const uint8_t *
1451f208f631SHeejin Ahn              p = (const uint8_t *)Contents.data(),
1452bafe6902SSam Clegg             *end = (const uint8_t *)Contents.data() + Contents.size();
1453bafe6902SSam Clegg          p != end; ++p) {
1454bafe6902SSam Clegg       if (*p != 0)
1455bafe6902SSam Clegg         report_fatal_error("non-symbolic data in .init_array section");
1456bafe6902SSam Clegg     }
1457bafe6902SSam Clegg     for (const MCFixup &Fixup : DataFrag.getFixups()) {
1458f208f631SHeejin Ahn       assert(Fixup.getKind() ==
1459f208f631SHeejin Ahn              MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
1460bafe6902SSam Clegg       const MCExpr *Expr = Fixup.getValue();
1461bafe6902SSam Clegg       auto *Sym = dyn_cast<MCSymbolRefExpr>(Expr);
1462bafe6902SSam Clegg       if (!Sym)
1463bafe6902SSam Clegg         report_fatal_error("fixups in .init_array should be symbol references");
1464bafe6902SSam Clegg       if (Sym->getKind() != MCSymbolRefExpr::VK_WebAssembly_FUNCTION)
1465bafe6902SSam Clegg         report_fatal_error("symbols in .init_array should be for functions");
146625d8e68bSSam Clegg       if (Sym->getSymbol().getIndex() == INVALID_INDEX)
146725d8e68bSSam Clegg         report_fatal_error("symbols in .init_array should exist in symbtab");
146825d8e68bSSam Clegg       InitFuncs.push_back(
146925d8e68bSSam Clegg           std::make_pair(Priority, Sym->getSymbol().getIndex()));
1470bafe6902SSam Clegg     }
1471bafe6902SSam Clegg   }
1472bafe6902SSam Clegg 
147318eafb6cSDan Gohman   // Write out the Wasm header.
147418eafb6cSDan Gohman   writeHeader(Asm);
147518eafb6cSDan Gohman 
14769e15f359SSam Clegg   writeTypeSection(FunctionTypes);
1477f950b24aSSam Clegg   writeImportSection(Imports, DataSize, TableElems.size());
14789e15f359SSam Clegg   writeFunctionSection(Functions);
1479f950b24aSSam Clegg   // Skip the "table" section; we import the table instead.
1480f950b24aSSam Clegg   // Skip the "memory" section; we import the memory instead.
14817c395943SSam Clegg   writeGlobalSection();
14829e15f359SSam Clegg   writeExportSection(Exports);
14839e15f359SSam Clegg   writeElemSection(TableElems);
1484acd7d2b0SSam Clegg   writeCodeSection(Asm, Layout, Functions);
14856c899ba6SSam Clegg   writeDataSection();
14866a31a0d6SSam Clegg   writeCustomSections(Asm, Layout);
1487c22bfb6bSNicholas Wilson   writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats);
14886f08c84aSSam Clegg   writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations);
14896f08c84aSSam Clegg   writeRelocSection(DataSectionIndex, "DATA", DataRelocations);
14906a31a0d6SSam Clegg   writeCustomRelocSections();
1491970d02c4SDan Gohman 
1492d934cb88SDan Gohman   // TODO: Translate the .comment section to the output.
1493438390faSPeter Collingbourne   return W.OS.tell() - StartOffset;
149418eafb6cSDan Gohman }
149518eafb6cSDan Gohman 
149660fbc7ccSLang Hames std::unique_ptr<MCObjectWriter>
14971301a878SLang Hames llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
149818eafb6cSDan Gohman                              raw_pwrite_stream &OS) {
14990917c9e4SDan Gohman   return llvm::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
150018eafb6cSDan Gohman }
1501