118eafb6cSDan Gohman //===- lib/MC/WasmObjectWriter.cpp - Wasm File Writer ---------------------===//
218eafb6cSDan Gohman //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
618eafb6cSDan Gohman //
718eafb6cSDan Gohman //===----------------------------------------------------------------------===//
818eafb6cSDan Gohman //
918eafb6cSDan Gohman // This file implements Wasm object file writer information.
1018eafb6cSDan Gohman //
1118eafb6cSDan Gohman //===----------------------------------------------------------------------===//
1218eafb6cSDan Gohman 
1318eafb6cSDan Gohman #include "llvm/ADT/STLExtras.h"
1418eafb6cSDan Gohman #include "llvm/ADT/SmallPtrSet.h"
15264b5d9eSZachary Turner #include "llvm/BinaryFormat/Wasm.h"
16432a3883SNico Weber #include "llvm/Config/llvm-config.h"
1718eafb6cSDan Gohman #include "llvm/MC/MCAsmBackend.h"
1818eafb6cSDan Gohman #include "llvm/MC/MCAsmLayout.h"
1918eafb6cSDan Gohman #include "llvm/MC/MCAssembler.h"
2018eafb6cSDan Gohman #include "llvm/MC/MCContext.h"
2118eafb6cSDan Gohman #include "llvm/MC/MCExpr.h"
2218eafb6cSDan Gohman #include "llvm/MC/MCFixupKindInfo.h"
2318eafb6cSDan Gohman #include "llvm/MC/MCObjectWriter.h"
2418eafb6cSDan Gohman #include "llvm/MC/MCSectionWasm.h"
2518eafb6cSDan Gohman #include "llvm/MC/MCSymbolWasm.h"
2618eafb6cSDan Gohman #include "llvm/MC/MCValue.h"
2718eafb6cSDan Gohman #include "llvm/MC/MCWasmObjectWriter.h"
28d934cb88SDan Gohman #include "llvm/Support/Casting.h"
2918eafb6cSDan Gohman #include "llvm/Support/Debug.h"
30bcd7f777SSimon Pilgrim #include "llvm/Support/EndianStream.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.
4418c56a07SHeejin Ahn static const uint32_t InitialTableOffset = 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 
59da419bdbSHeejin Ahn // The signature of a wasm function or event, in a struct capable of being used
60da419bdbSHeejin Ahn // as a DenseMap key.
61da419bdbSHeejin Ahn // TODO: Consider using wasm::WasmSignature directly instead.
62da419bdbSHeejin Ahn struct WasmSignature {
639e15f359SSam Clegg   // Support empty and tombstone instances, needed by DenseMap.
6418c56a07SHeejin Ahn   enum { Plain, Empty, Tombstone } State = Plain;
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 
72da419bdbSHeejin Ahn   bool operator==(const WasmSignature &Other) const {
739e15f359SSam Clegg     return State == Other.State && Returns == Other.Returns &&
749e15f359SSam Clegg            Params == Other.Params;
759e15f359SSam Clegg   }
769e15f359SSam Clegg };
779e15f359SSam Clegg 
78da419bdbSHeejin Ahn // Traits for using WasmSignature in a DenseMap.
79da419bdbSHeejin Ahn struct WasmSignatureDenseMapInfo {
80da419bdbSHeejin Ahn   static WasmSignature getEmptyKey() {
81da419bdbSHeejin Ahn     WasmSignature Sig;
82da419bdbSHeejin Ahn     Sig.State = WasmSignature::Empty;
83da419bdbSHeejin Ahn     return Sig;
849e15f359SSam Clegg   }
85da419bdbSHeejin Ahn   static WasmSignature getTombstoneKey() {
86da419bdbSHeejin Ahn     WasmSignature Sig;
87da419bdbSHeejin Ahn     Sig.State = WasmSignature::Tombstone;
88da419bdbSHeejin Ahn     return Sig;
899e15f359SSam Clegg   }
90da419bdbSHeejin Ahn   static unsigned getHashValue(const WasmSignature &Sig) {
91da419bdbSHeejin Ahn     uintptr_t Value = Sig.State;
92da419bdbSHeejin Ahn     for (wasm::ValType Ret : Sig.Returns)
934808914aSHeejin Ahn       Value += DenseMapInfo<uint32_t>::getHashValue(uint32_t(Ret));
94da419bdbSHeejin Ahn     for (wasm::ValType Param : Sig.Params)
954808914aSHeejin Ahn       Value += DenseMapInfo<uint32_t>::getHashValue(uint32_t(Param));
969e15f359SSam Clegg     return Value;
979e15f359SSam Clegg   }
98da419bdbSHeejin Ahn   static bool isEqual(const WasmSignature &LHS, const WasmSignature &RHS) {
999e15f359SSam Clegg     return LHS == RHS;
1009e15f359SSam Clegg   }
1019e15f359SSam Clegg };
1029e15f359SSam Clegg 
1037c395943SSam Clegg // A wasm data segment.  A wasm binary contains only a single data section
1047c395943SSam Clegg // but that can contain many segments, each with their own virtual location
1057c395943SSam Clegg // in memory.  Each MCSection data created by llvm is modeled as its own
1067c395943SSam Clegg // wasm data segment.
1077c395943SSam Clegg struct WasmDataSegment {
1087c395943SSam Clegg   MCSectionWasm *Section;
109d95ed959SSam Clegg   StringRef Name;
1102e150409SThomas Lively   uint32_t InitFlags;
1114d135b04SWouter van Oortmerssen   uint64_t Offset;
11263ebb813SSam Clegg   uint32_t Alignment;
1132e150409SThomas Lively   uint32_t LinkerFlags;
1147c395943SSam Clegg   SmallVector<char, 4> Data;
1157c395943SSam Clegg };
1167c395943SSam Clegg 
1179e15f359SSam Clegg // A wasm function to be written into the function section.
1189e15f359SSam Clegg struct WasmFunction {
119da419bdbSHeejin Ahn   uint32_t SigIndex;
1209e15f359SSam Clegg   const MCSymbolWasm *Sym;
1219e15f359SSam Clegg };
1229e15f359SSam Clegg 
1239e15f359SSam Clegg // A wasm global to be written into the global section.
1249e15f359SSam Clegg struct WasmGlobal {
1256e7f1826SSam Clegg   wasm::WasmGlobalType Type;
1269e15f359SSam Clegg   uint64_t InitialValue;
1279e15f359SSam Clegg };
1289e15f359SSam Clegg 
129ea7caceeSSam Clegg // Information about a single item which is part of a COMDAT.  For each data
130ea7caceeSSam Clegg // segment or function which is in the COMDAT, there is a corresponding
131ea7caceeSSam Clegg // WasmComdatEntry.
132ea7caceeSSam Clegg struct WasmComdatEntry {
133ea7caceeSSam Clegg   unsigned Kind;
134ea7caceeSSam Clegg   uint32_t Index;
135ea7caceeSSam Clegg };
136ea7caceeSSam Clegg 
1376dc65e91SSam Clegg // Information about a single relocation.
1386dc65e91SSam Clegg struct WasmRelocationEntry {
1396dc65e91SSam Clegg   uint64_t Offset;                   // Where is the relocation.
1406dc65e91SSam Clegg   const MCSymbolWasm *Symbol;        // The symbol to relocate with.
1416dc65e91SSam Clegg   int64_t Addend;                    // A value to add to the symbol.
1426dc65e91SSam Clegg   unsigned Type;                     // The type of the relocation.
143fe6414b0SSam Clegg   const MCSectionWasm *FixupSection; // The section the relocation is targeting.
1446dc65e91SSam Clegg 
1456dc65e91SSam Clegg   WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol,
1466dc65e91SSam Clegg                       int64_t Addend, unsigned Type,
147fe6414b0SSam Clegg                       const MCSectionWasm *FixupSection)
1486dc65e91SSam Clegg       : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type),
1496dc65e91SSam Clegg         FixupSection(FixupSection) {}
1506dc65e91SSam Clegg 
151cadcb9ebSKeno Fischer   bool hasAddend() const { return wasm::relocTypeHasAddend(Type); }
152acd7d2b0SSam Clegg 
1536dc65e91SSam Clegg   void print(raw_ostream &Out) const {
154f208f631SHeejin Ahn     Out << wasm::relocTypetoString(Type) << " Off=" << Offset
155f208f631SHeejin Ahn         << ", Sym=" << *Symbol << ", Addend=" << Addend
1567d1ff446SFangrui Song         << ", FixupSection=" << FixupSection->getName();
1576dc65e91SSam Clegg   }
158b7787fd0SSam Clegg 
159615eb470SAaron Ballman #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
160b7787fd0SSam Clegg   LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
161b7787fd0SSam Clegg #endif
1626dc65e91SSam Clegg };
1636dc65e91SSam Clegg 
16418c56a07SHeejin Ahn static const uint32_t InvalidIndex = -1;
16525d8e68bSSam Clegg 
166cfd44a2eSSam Clegg struct WasmCustomSection {
167cfd44a2eSSam Clegg 
1686a31a0d6SSam Clegg   StringRef Name;
1696a31a0d6SSam Clegg   MCSectionWasm *Section;
1706a31a0d6SSam Clegg 
1716a31a0d6SSam Clegg   uint32_t OutputContentsOffset;
1726a31a0d6SSam Clegg   uint32_t OutputIndex;
1736a31a0d6SSam Clegg 
1746a31a0d6SSam Clegg   WasmCustomSection(StringRef Name, MCSectionWasm *Section)
1756a31a0d6SSam Clegg       : Name(Name), Section(Section), OutputContentsOffset(0),
17618c56a07SHeejin Ahn         OutputIndex(InvalidIndex) {}
177cfd44a2eSSam Clegg };
178cfd44a2eSSam Clegg 
1791fb8daa6SSam Clegg #if !defined(NDEBUG)
1807f055deeSSam Clegg raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
181b7787fd0SSam Clegg   Rel.print(OS);
182b7787fd0SSam Clegg   return OS;
183b7787fd0SSam Clegg }
1841fb8daa6SSam Clegg #endif
185b7787fd0SSam Clegg 
18619e8befaSSam Clegg // Write X as an (unsigned) LEB value at offset Offset in Stream, padded
18719e8befaSSam Clegg // to allow patching.
1883b29376eSWouter van Oortmerssen template <int W>
1893b29376eSWouter van Oortmerssen void writePatchableLEB(raw_pwrite_stream &Stream, uint64_t X, uint64_t Offset) {
1903b29376eSWouter van Oortmerssen   uint8_t Buffer[W];
1913b29376eSWouter van Oortmerssen   unsigned SizeLen = encodeULEB128(X, Buffer, W);
1923b29376eSWouter van Oortmerssen   assert(SizeLen == W);
19319e8befaSSam Clegg   Stream.pwrite((char *)Buffer, SizeLen, Offset);
19419e8befaSSam Clegg }
19519e8befaSSam Clegg 
19619e8befaSSam Clegg // Write X as an signed LEB value at offset Offset in Stream, padded
19719e8befaSSam Clegg // to allow patching.
1983b29376eSWouter van Oortmerssen template <int W>
1993b29376eSWouter van Oortmerssen void writePatchableSLEB(raw_pwrite_stream &Stream, int64_t X, uint64_t Offset) {
2003b29376eSWouter van Oortmerssen   uint8_t Buffer[W];
2013b29376eSWouter van Oortmerssen   unsigned SizeLen = encodeSLEB128(X, Buffer, W);
2023b29376eSWouter van Oortmerssen   assert(SizeLen == W);
20319e8befaSSam Clegg   Stream.pwrite((char *)Buffer, SizeLen, Offset);
20419e8befaSSam Clegg }
20519e8befaSSam Clegg 
20619e8befaSSam Clegg // Write X as a plain integer value at offset Offset in Stream.
2070a6c4d8dSSam Clegg static void patchI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
20819e8befaSSam Clegg   uint8_t Buffer[4];
20919e8befaSSam Clegg   support::endian::write32le(Buffer, X);
21019e8befaSSam Clegg   Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
21119e8befaSSam Clegg }
21219e8befaSSam Clegg 
2133b29376eSWouter van Oortmerssen static void patchI64(raw_pwrite_stream &Stream, uint64_t X, uint64_t Offset) {
2143b29376eSWouter van Oortmerssen   uint8_t Buffer[8];
2153b29376eSWouter van Oortmerssen   support::endian::write64le(Buffer, X);
2163b29376eSWouter van Oortmerssen   Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
2173b29376eSWouter van Oortmerssen }
2183b29376eSWouter van Oortmerssen 
21918eafb6cSDan Gohman class WasmObjectWriter : public MCObjectWriter {
220f17b149dSPeter Collingbourne   support::endian::Writer W;
221f17b149dSPeter Collingbourne 
22218eafb6cSDan Gohman   /// The target specific Wasm writer instance.
22318eafb6cSDan Gohman   std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
22418eafb6cSDan Gohman 
225d934cb88SDan Gohman   // Relocations for fixing up references in the code section.
226d934cb88SDan Gohman   std::vector<WasmRelocationEntry> CodeRelocations;
227d934cb88SDan Gohman   // Relocations for fixing up references in the data section.
228d934cb88SDan Gohman   std::vector<WasmRelocationEntry> DataRelocations;
229d934cb88SDan Gohman 
230d934cb88SDan Gohman   // Index values to use for fixing up call_indirect type indices.
231acd7d2b0SSam Clegg   // Maps function symbols to the index of the type of the function
232acd7d2b0SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
233d99f6078SSam Clegg   // Maps function symbols to the table element index space. Used
234d99f6078SSam Clegg   // for TABLE_INDEX relocation types (i.e. address taken functions).
235f9edbe95SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> TableIndices;
236da419bdbSHeejin Ahn   // Maps function/global symbols to the function/global/event/section index
237da419bdbSHeejin Ahn   // space.
2386c899ba6SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> WasmIndices;
239492f7529SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> GOTIndices;
2406c899ba6SSam Clegg   // Maps data symbols to the Wasm segment and offset/size with the segment.
2416c899ba6SSam Clegg   DenseMap<const MCSymbolWasm *, wasm::WasmDataReference> DataLocations;
2426a31a0d6SSam Clegg 
2436a31a0d6SSam Clegg   // Stores output data (index, relocations, content offset) for custom
2446a31a0d6SSam Clegg   // section.
2456a31a0d6SSam Clegg   std::vector<WasmCustomSection> CustomSections;
246cbda16ebSThomas Lively   std::unique_ptr<WasmCustomSection> ProducersSection;
247f6f4f843SThomas Lively   std::unique_ptr<WasmCustomSection> TargetFeaturesSection;
2486a31a0d6SSam Clegg   // Relocations for fixing up references in the custom sections.
2496a31a0d6SSam Clegg   DenseMap<const MCSectionWasm *, std::vector<WasmRelocationEntry>>
2506a31a0d6SSam Clegg       CustomSectionsRelocations;
251acd7d2b0SSam Clegg 
252c0d41195SSam Clegg   // Map from section to defining function symbol.
2536ccb59b3SSam Clegg   DenseMap<const MCSection *, const MCSymbol *> SectionFunctions;
2546ccb59b3SSam Clegg 
255da419bdbSHeejin Ahn   DenseMap<WasmSignature, uint32_t, WasmSignatureDenseMapInfo> SignatureIndices;
256da419bdbSHeejin Ahn   SmallVector<WasmSignature, 4> Signatures;
2576c899ba6SSam Clegg   SmallVector<WasmDataSegment, 4> DataSegments;
2589f3fe42eSSam Clegg   unsigned NumFunctionImports = 0;
2597c395943SSam Clegg   unsigned NumGlobalImports = 0;
260da419bdbSHeejin Ahn   unsigned NumEventImports = 0;
2617e1c3345SChandler Carruth   uint32_t SectionCount = 0;
262d934cb88SDan Gohman 
26318eafb6cSDan Gohman   // TargetObjectWriter wrappers.
26418eafb6cSDan Gohman   bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
265da84b688SDan Gohman   bool isEmscripten() const { return TargetObjectWriter->isEmscripten(); }
26618eafb6cSDan Gohman 
2672322a937SSam Clegg   void startSection(SectionBookkeeping &Section, unsigned SectionId);
2682322a937SSam Clegg   void startCustomSection(SectionBookkeeping &Section, StringRef Name);
269d934cb88SDan Gohman   void endSection(SectionBookkeeping &Section);
270d934cb88SDan Gohman 
27118eafb6cSDan Gohman public:
2721301a878SLang Hames   WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
2731301a878SLang Hames                    raw_pwrite_stream &OS)
27459a6fc46SPeter Collingbourne       : W(OS, support::little), TargetObjectWriter(std::move(MOTW)) {}
27518eafb6cSDan Gohman 
2760917c9e4SDan Gohman private:
277acd7d2b0SSam Clegg   void reset() override {
278acd7d2b0SSam Clegg     CodeRelocations.clear();
279acd7d2b0SSam Clegg     DataRelocations.clear();
280acd7d2b0SSam Clegg     TypeIndices.clear();
2816c899ba6SSam Clegg     WasmIndices.clear();
282492f7529SSam Clegg     GOTIndices.clear();
283f9edbe95SSam Clegg     TableIndices.clear();
2846c899ba6SSam Clegg     DataLocations.clear();
285cbda16ebSThomas Lively     CustomSections.clear();
286cbda16ebSThomas Lively     ProducersSection.reset();
287f6f4f843SThomas Lively     TargetFeaturesSection.reset();
2886a31a0d6SSam Clegg     CustomSectionsRelocations.clear();
289da419bdbSHeejin Ahn     SignatureIndices.clear();
290da419bdbSHeejin Ahn     Signatures.clear();
2916c899ba6SSam Clegg     DataSegments.clear();
2926ccb59b3SSam Clegg     SectionFunctions.clear();
2939f3fe42eSSam Clegg     NumFunctionImports = 0;
2947c395943SSam Clegg     NumGlobalImports = 0;
295105bdc25SSam Clegg     MCObjectWriter::reset();
296acd7d2b0SSam Clegg   }
297acd7d2b0SSam Clegg 
29818eafb6cSDan Gohman   void writeHeader(const MCAssembler &Asm);
29918eafb6cSDan Gohman 
30018eafb6cSDan Gohman   void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
30118eafb6cSDan Gohman                         const MCFragment *Fragment, const MCFixup &Fixup,
302ceecfe5bSRafael Espindola                         MCValue Target, uint64_t &FixedValue) override;
30318eafb6cSDan Gohman 
30418eafb6cSDan Gohman   void executePostLayoutBinding(MCAssembler &Asm,
30518eafb6cSDan Gohman                                 const MCAsmLayout &Layout) override;
30618eafb6cSDan Gohman 
307438390faSPeter Collingbourne   uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
3089e15f359SSam Clegg 
309b7787fd0SSam Clegg   void writeString(const StringRef Str) {
310f17b149dSPeter Collingbourne     encodeULEB128(Str.size(), W.OS);
311f17b149dSPeter Collingbourne     W.OS << Str;
312b7787fd0SSam Clegg   }
313b7787fd0SSam Clegg 
3140a6c4d8dSSam Clegg   void writeI32(int32_t val) {
3150a6c4d8dSSam Clegg     char Buffer[4];
3160a6c4d8dSSam Clegg     support::endian::write32le(Buffer, val);
3170a6c4d8dSSam Clegg     W.OS.write(Buffer, sizeof(Buffer));
3180a6c4d8dSSam Clegg   }
3190a6c4d8dSSam Clegg 
3200a6c4d8dSSam Clegg   void writeI64(int64_t val) {
3210a6c4d8dSSam Clegg     char Buffer[8];
3220a6c4d8dSSam Clegg     support::endian::write64le(Buffer, val);
3230a6c4d8dSSam Clegg     W.OS.write(Buffer, sizeof(Buffer));
3240a6c4d8dSSam Clegg   }
3250a6c4d8dSSam Clegg 
326f208f631SHeejin Ahn   void writeValueType(wasm::ValType Ty) { W.OS << static_cast<char>(Ty); }
3279e15f359SSam Clegg 
328da419bdbSHeejin Ahn   void writeTypeSection(ArrayRef<WasmSignature> Signatures);
3294d135b04SWouter van Oortmerssen   void writeImportSection(ArrayRef<wasm::WasmImport> Imports, uint64_t DataSize,
330f950b24aSSam Clegg                           uint32_t NumElements);
331457fb0b4SSam Clegg   void writeFunctionSection(ArrayRef<WasmFunction> Functions);
3328defa952SSam Clegg   void writeExportSection(ArrayRef<wasm::WasmExport> Exports);
333457fb0b4SSam Clegg   void writeElemSection(ArrayRef<uint32_t> TableElems);
334fef8de66SThomas Lively   void writeDataCountSection();
335e49584a3SSam Clegg   uint32_t writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
336457fb0b4SSam Clegg                             ArrayRef<WasmFunction> Functions);
337e49584a3SSam Clegg   uint32_t writeDataSection(const MCAsmLayout &Layout);
338da419bdbSHeejin Ahn   void writeEventSection(ArrayRef<wasm::WasmEventType> Events);
3390a6c4d8dSSam Clegg   void writeGlobalSection(ArrayRef<wasm::WasmGlobal> Globals);
3406f08c84aSSam Clegg   void writeRelocSection(uint32_t SectionIndex, StringRef Name,
341f77dc2a8SSam Clegg                          std::vector<WasmRelocationEntry> &Relocations);
34231a2c809SSam Clegg   void writeLinkingMetaDataSection(
34386b4a09aSSam Clegg       ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
344ea7caceeSSam Clegg       ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
345ea7caceeSSam Clegg       const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats);
346cbda16ebSThomas Lively   void writeCustomSection(WasmCustomSection &CustomSection,
347cbda16ebSThomas Lively                           const MCAssembler &Asm, const MCAsmLayout &Layout);
3486a31a0d6SSam Clegg   void writeCustomRelocSections();
3496a31a0d6SSam Clegg   void
3506a31a0d6SSam Clegg   updateCustomSectionRelocations(const SmallVector<WasmFunction, 4> &Functions,
3516a31a0d6SSam Clegg                                  const MCAsmLayout &Layout);
352acd7d2b0SSam Clegg 
3537ee758d6SSam Clegg   uint64_t getProvisionalValue(const WasmRelocationEntry &RelEntry,
3547ee758d6SSam Clegg                                const MCAsmLayout &Layout);
355acd7d2b0SSam Clegg   void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
3567ee758d6SSam Clegg                         uint64_t ContentsOffset, const MCAsmLayout &Layout);
357acd7d2b0SSam Clegg 
358acd7d2b0SSam Clegg   uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
3595e3d33a7SSam Clegg   uint32_t getFunctionType(const MCSymbolWasm &Symbol);
360da419bdbSHeejin Ahn   uint32_t getEventType(const MCSymbolWasm &Symbol);
36138b12f5eSHeejin Ahn   void registerFunctionType(const MCSymbolWasm &Symbol);
36238b12f5eSHeejin Ahn   void registerEventType(const MCSymbolWasm &Symbol);
36318eafb6cSDan Gohman };
3649e15f359SSam Clegg 
36518eafb6cSDan Gohman } // end anonymous namespace
36618eafb6cSDan Gohman 
367d934cb88SDan Gohman // Write out a section header and a patchable section size field.
368d934cb88SDan Gohman void WasmObjectWriter::startSection(SectionBookkeeping &Section,
3692322a937SSam Clegg                                     unsigned SectionId) {
370d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "startSection " << SectionId << "\n");
371f17b149dSPeter Collingbourne   W.OS << char(SectionId);
372d934cb88SDan Gohman 
373f17b149dSPeter Collingbourne   Section.SizeOffset = W.OS.tell();
374d934cb88SDan Gohman 
375d934cb88SDan Gohman   // The section size. We don't know the size yet, so reserve enough space
376d934cb88SDan Gohman   // for any 32-bit value; we'll patch it later.
37719e8befaSSam Clegg   encodeULEB128(0, W.OS, 5);
378d934cb88SDan Gohman 
379d934cb88SDan Gohman   // The position where the section starts, for measuring its size.
380f17b149dSPeter Collingbourne   Section.ContentsOffset = W.OS.tell();
381f17b149dSPeter Collingbourne   Section.PayloadOffset = W.OS.tell();
3826f08c84aSSam Clegg   Section.Index = SectionCount++;
383d934cb88SDan Gohman }
3842322a937SSam Clegg 
3852322a937SSam Clegg void WasmObjectWriter::startCustomSection(SectionBookkeeping &Section,
3862322a937SSam Clegg                                           StringRef Name) {
387d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "startCustomSection " << Name << "\n");
3882322a937SSam Clegg   startSection(Section, wasm::WASM_SEC_CUSTOM);
3896a31a0d6SSam Clegg 
3906a31a0d6SSam Clegg   // The position where the section header ends, for measuring its size.
391f17b149dSPeter Collingbourne   Section.PayloadOffset = W.OS.tell();
3926a31a0d6SSam Clegg 
3932322a937SSam Clegg   // Custom sections in wasm also have a string identifier.
3942322a937SSam Clegg   writeString(Name);
3956a31a0d6SSam Clegg 
3966a31a0d6SSam Clegg   // The position where the custom section starts.
397f17b149dSPeter Collingbourne   Section.ContentsOffset = W.OS.tell();
398d934cb88SDan Gohman }
399d934cb88SDan Gohman 
400d934cb88SDan Gohman // Now that the section is complete and we know how big it is, patch up the
401d934cb88SDan Gohman // section size field at the start of the section.
402d934cb88SDan Gohman void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
403c0affde8SSam Clegg   uint64_t Size = W.OS.tell();
404c0affde8SSam Clegg   // /dev/null doesn't support seek/tell and can report offset of 0.
405c0affde8SSam Clegg   // Simply skip this patching in that case.
406c0affde8SSam Clegg   if (!Size)
407c0affde8SSam Clegg     return;
408c0affde8SSam Clegg 
409c0affde8SSam Clegg   Size -= Section.PayloadOffset;
410d934cb88SDan Gohman   if (uint32_t(Size) != Size)
411d934cb88SDan Gohman     report_fatal_error("section size does not fit in a uint32_t");
412d934cb88SDan Gohman 
413d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "endSection size=" << Size << "\n");
414d934cb88SDan Gohman 
415d934cb88SDan Gohman   // Write the final section size to the payload_len field, which follows
416d934cb88SDan Gohman   // the section id byte.
4173b29376eSWouter van Oortmerssen   writePatchableLEB<5>(static_cast<raw_pwrite_stream &>(W.OS), Size,
418f17b149dSPeter Collingbourne                        Section.SizeOffset);
419d934cb88SDan Gohman }
420d934cb88SDan Gohman 
42118eafb6cSDan Gohman // Emit the Wasm header.
42218eafb6cSDan Gohman void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
423f17b149dSPeter Collingbourne   W.OS.write(wasm::WasmMagic, sizeof(wasm::WasmMagic));
424f17b149dSPeter Collingbourne   W.write<uint32_t>(wasm::WasmVersion);
42518eafb6cSDan Gohman }
42618eafb6cSDan Gohman 
42718eafb6cSDan Gohman void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
42818eafb6cSDan Gohman                                                 const MCAsmLayout &Layout) {
4296ccb59b3SSam Clegg   // Build a map of sections to the function that defines them, for use
4306ccb59b3SSam Clegg   // in recordRelocation.
4316ccb59b3SSam Clegg   for (const MCSymbol &S : Asm.symbols()) {
4326ccb59b3SSam Clegg     const auto &WS = static_cast<const MCSymbolWasm &>(S);
4336ccb59b3SSam Clegg     if (WS.isDefined() && WS.isFunction() && !WS.isVariable()) {
4346ccb59b3SSam Clegg       const auto &Sec = static_cast<const MCSectionWasm &>(S.getSection());
4356ccb59b3SSam Clegg       auto Pair = SectionFunctions.insert(std::make_pair(&Sec, &S));
4366ccb59b3SSam Clegg       if (!Pair.second)
4376ccb59b3SSam Clegg         report_fatal_error("section already has a defining function: " +
4387d1ff446SFangrui Song                            Sec.getName());
4396ccb59b3SSam Clegg     }
4406ccb59b3SSam Clegg   }
44118eafb6cSDan Gohman }
44218eafb6cSDan Gohman 
44318eafb6cSDan Gohman void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
44418eafb6cSDan Gohman                                         const MCAsmLayout &Layout,
44518eafb6cSDan Gohman                                         const MCFragment *Fragment,
44618eafb6cSDan Gohman                                         const MCFixup &Fixup, MCValue Target,
447ceecfe5bSRafael Espindola                                         uint64_t &FixedValue) {
448ecc5e808SSam Clegg   // The WebAssembly backend should never generate FKF_IsPCRel fixups
449e828ce1bSFangrui Song   assert(!(Asm.getBackend().getFixupKindInfo(Fixup.getKind()).Flags &
450ecc5e808SSam Clegg            MCFixupKindInfo::FKF_IsPCRel));
451ecc5e808SSam Clegg 
452fe6414b0SSam Clegg   const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
453d934cb88SDan Gohman   uint64_t C = Target.getConstant();
454d934cb88SDan Gohman   uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
455d934cb88SDan Gohman   MCContext &Ctx = Asm.getContext();
456d934cb88SDan Gohman 
457d934cb88SDan Gohman   if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
458ecc5e808SSam Clegg     // To get here the A - B expression must have failed evaluateAsRelocatable.
459ecc5e808SSam Clegg     // This means either A or B must be undefined and in WebAssembly we can't
460ecc5e808SSam Clegg     // support either of those cases.
461ecc5e808SSam Clegg     const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
462d934cb88SDan Gohman     Ctx.reportError(
463d934cb88SDan Gohman         Fixup.getLoc(),
464d934cb88SDan Gohman         Twine("symbol '") + SymB.getName() +
465ecc5e808SSam Clegg             "': unsupported subtraction expression used in relocation.");
466d934cb88SDan Gohman     return;
467d934cb88SDan Gohman   }
468d934cb88SDan Gohman 
469d934cb88SDan Gohman   // We either rejected the fixup or folded B into C at this point.
470d934cb88SDan Gohman   const MCSymbolRefExpr *RefA = Target.getSymA();
471ecc5e808SSam Clegg   const auto *SymA = cast<MCSymbolWasm>(&RefA->getSymbol());
472d934cb88SDan Gohman 
4733ea1c62cSSam Clegg   // The .init_array isn't translated as data, so don't do relocations in it.
4747d1ff446SFangrui Song   if (FixupSection.getName().startswith(".init_array")) {
4753ea1c62cSSam Clegg     SymA->setUsedInInitArray();
4763ea1c62cSSam Clegg     return;
4773ea1c62cSSam Clegg   }
4783ea1c62cSSam Clegg 
479ecc5e808SSam Clegg   if (SymA->isVariable()) {
480d934cb88SDan Gohman     const MCExpr *Expr = SymA->getVariableValue();
4817ee758d6SSam Clegg     if (const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr))
4826ad8f190SSam Clegg       if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
4836ad8f190SSam Clegg         llvm_unreachable("weakref used in reloc not yet implemented");
484d934cb88SDan Gohman   }
485d934cb88SDan Gohman 
486d934cb88SDan Gohman   // Put any constant offset in an addend. Offsets can be negative, and
487d934cb88SDan Gohman   // LLVM expects wrapping, in contrast to wasm's immediates which can't
488d934cb88SDan Gohman   // be negative and don't wrap.
489d934cb88SDan Gohman   FixedValue = 0;
490d934cb88SDan Gohman 
491a5e175c6SSam Clegg   unsigned Type = TargetObjectWriter->getRelocType(Target, Fixup);
4929d24fb7fSSam Clegg 
4934d57fbd0SSam Clegg   // Absolute offset within a section or a function.
4944d57fbd0SSam Clegg   // Currently only supported for for metadata sections.
4954d57fbd0SSam Clegg   // See: test/MC/WebAssembly/blockaddress.ll
496d1152a26SSam Clegg   if (Type == wasm::R_WASM_FUNCTION_OFFSET_I32 ||
497d1152a26SSam Clegg       Type == wasm::R_WASM_SECTION_OFFSET_I32) {
4984d57fbd0SSam Clegg     if (!FixupSection.getKind().isMetadata())
4994d57fbd0SSam Clegg       report_fatal_error("relocations for function or section offsets are "
5004d57fbd0SSam Clegg                          "only supported in metadata sections");
5014d57fbd0SSam Clegg 
5024d57fbd0SSam Clegg     const MCSymbol *SectionSymbol = nullptr;
5034d57fbd0SSam Clegg     const MCSection &SecA = SymA->getSection();
5044d57fbd0SSam Clegg     if (SecA.getKind().isText())
5056ccb59b3SSam Clegg       SectionSymbol = SectionFunctions.find(&SecA)->second;
5064d57fbd0SSam Clegg     else
5074d57fbd0SSam Clegg       SectionSymbol = SecA.getBeginSymbol();
5084d57fbd0SSam Clegg     if (!SectionSymbol)
5094d57fbd0SSam Clegg       report_fatal_error("section symbol is required for relocation");
5104d57fbd0SSam Clegg 
5114d57fbd0SSam Clegg     C += Layout.getSymbolOffset(*SymA);
5124d57fbd0SSam Clegg     SymA = cast<MCSymbolWasm>(SectionSymbol);
5134d57fbd0SSam Clegg   }
5144d57fbd0SSam Clegg 
515d1152a26SSam Clegg   // Relocation other than R_WASM_TYPE_INDEX_LEB are required to be
5164d57fbd0SSam Clegg   // against a named symbol.
517d1152a26SSam Clegg   if (Type != wasm::R_WASM_TYPE_INDEX_LEB) {
5184d57fbd0SSam Clegg     if (SymA->getName().empty())
5194d57fbd0SSam Clegg       report_fatal_error("relocations against un-named temporaries are not yet "
5204d57fbd0SSam Clegg                          "supported by wasm");
5214d57fbd0SSam Clegg 
5224d57fbd0SSam Clegg     SymA->setUsedInReloc();
5234d57fbd0SSam Clegg   }
524ae03c1e7SSam Clegg 
525492f7529SSam Clegg   if (RefA->getKind() == MCSymbolRefExpr::VK_GOT)
526492f7529SSam Clegg     SymA->setUsedInGOT();
527492f7529SSam Clegg 
528d934cb88SDan Gohman   WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
529d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
530d934cb88SDan Gohman 
5316a31a0d6SSam Clegg   if (FixupSection.isWasmData()) {
532d934cb88SDan Gohman     DataRelocations.push_back(Rec);
5336a31a0d6SSam Clegg   } else if (FixupSection.getKind().isText()) {
53412fd3da9SSam Clegg     CodeRelocations.push_back(Rec);
5356a31a0d6SSam Clegg   } else if (FixupSection.getKind().isMetadata()) {
5366a31a0d6SSam Clegg     CustomSectionsRelocations[&FixupSection].push_back(Rec);
5376a31a0d6SSam Clegg   } else {
53812fd3da9SSam Clegg     llvm_unreachable("unexpected section type");
539d934cb88SDan Gohman   }
5406a31a0d6SSam Clegg }
541d934cb88SDan Gohman 
542d934cb88SDan Gohman // Compute a value to write into the code at the location covered
54360ec3034SSam Clegg // by RelEntry. This value isn't used by the static linker; it just serves
54460ec3034SSam Clegg // to make the object format more readable and more likely to be directly
54560ec3034SSam Clegg // useable.
5463b29376eSWouter van Oortmerssen uint64_t
5477ee758d6SSam Clegg WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry,
5487ee758d6SSam Clegg                                       const MCAsmLayout &Layout) {
54948139ebcSWouter van Oortmerssen   if ((RelEntry.Type == wasm::R_WASM_GLOBAL_INDEX_LEB ||
55048139ebcSWouter van Oortmerssen        RelEntry.Type == wasm::R_WASM_GLOBAL_INDEX_I32) &&
55148139ebcSWouter van Oortmerssen       !RelEntry.Symbol->isGlobal()) {
552492f7529SSam Clegg     assert(GOTIndices.count(RelEntry.Symbol) > 0 && "symbol not found in GOT index space");
553492f7529SSam Clegg     return GOTIndices[RelEntry.Symbol];
554492f7529SSam Clegg   }
555492f7529SSam Clegg 
55660ec3034SSam Clegg   switch (RelEntry.Type) {
5572a7cac93SSam Clegg   case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
558d1152a26SSam Clegg   case wasm::R_WASM_TABLE_INDEX_SLEB:
559*cc1b9b68SWouter van Oortmerssen   case wasm::R_WASM_TABLE_INDEX_SLEB64:
560*cc1b9b68SWouter van Oortmerssen   case wasm::R_WASM_TABLE_INDEX_I32:
561*cc1b9b68SWouter van Oortmerssen   case wasm::R_WASM_TABLE_INDEX_I64: {
562f9edbe95SSam Clegg     // Provisional value is table address of the resolved symbol itself
5637ee758d6SSam Clegg     const MCSymbolWasm *Base =
5647ee758d6SSam Clegg         cast<MCSymbolWasm>(Layout.getBaseSymbol(*RelEntry.Symbol));
5657ee758d6SSam Clegg     assert(Base->isFunction());
56681443ac1SSam Clegg     if (RelEntry.Type == wasm::R_WASM_TABLE_INDEX_REL_SLEB)
5677ee758d6SSam Clegg       return TableIndices[Base] - InitialTableOffset;
56881443ac1SSam Clegg     else
5697ee758d6SSam Clegg       return TableIndices[Base];
570f9edbe95SSam Clegg   }
571d1152a26SSam Clegg   case wasm::R_WASM_TYPE_INDEX_LEB:
5726c899ba6SSam Clegg     // Provisional value is same as the index
57360ec3034SSam Clegg     return getRelocationIndexValue(RelEntry);
574d1152a26SSam Clegg   case wasm::R_WASM_FUNCTION_INDEX_LEB:
575d1152a26SSam Clegg   case wasm::R_WASM_GLOBAL_INDEX_LEB:
57648139ebcSWouter van Oortmerssen   case wasm::R_WASM_GLOBAL_INDEX_I32:
577d1152a26SSam Clegg   case wasm::R_WASM_EVENT_INDEX_LEB:
578da419bdbSHeejin Ahn     // Provisional value is function/global/event Wasm index
579492f7529SSam Clegg     assert(WasmIndices.count(RelEntry.Symbol) > 0 && "symbol not found in wasm index space");
5806c899ba6SSam Clegg     return WasmIndices[RelEntry.Symbol];
581d1152a26SSam Clegg   case wasm::R_WASM_FUNCTION_OFFSET_I32:
582d1152a26SSam Clegg   case wasm::R_WASM_SECTION_OFFSET_I32: {
5836a31a0d6SSam Clegg     const auto &Section =
5846a31a0d6SSam Clegg         static_cast<const MCSectionWasm &>(RelEntry.Symbol->getSection());
5856a31a0d6SSam Clegg     return Section.getSectionOffset() + RelEntry.Addend;
5866a31a0d6SSam Clegg   }
587d1152a26SSam Clegg   case wasm::R_WASM_MEMORY_ADDR_LEB:
5883b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_LEB64:
5893b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_SLEB:
5903b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_SLEB64:
5912a7cac93SSam Clegg   case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
5923b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_REL_SLEB64:
5933b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_I32:
5943b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_I64: {
595f9edbe95SSam Clegg     // Provisional value is address of the global
5967ee758d6SSam Clegg     const MCSymbolWasm *Base =
5977ee758d6SSam Clegg         cast<MCSymbolWasm>(Layout.getBaseSymbol(*RelEntry.Symbol));
598270ed1b3SSam Clegg     // For undefined symbols, use zero
5997ee758d6SSam Clegg     if (!Base->isDefined())
600270ed1b3SSam Clegg       return 0;
6017ee758d6SSam Clegg     const wasm::WasmDataReference &Ref = DataLocations[Base];
6026c899ba6SSam Clegg     const WasmDataSegment &Segment = DataSegments[Ref.Segment];
603d934cb88SDan Gohman     // Ignore overflow. LLVM allows address arithmetic to silently wrap.
6046c899ba6SSam Clegg     return Segment.Offset + Ref.Offset + RelEntry.Addend;
60560ec3034SSam Clegg   }
60660ec3034SSam Clegg   default:
60760ec3034SSam Clegg     llvm_unreachable("invalid relocation type");
60860ec3034SSam Clegg   }
609d934cb88SDan Gohman }
610d934cb88SDan Gohman 
611759631c7SSam Clegg static void addData(SmallVectorImpl<char> &DataBytes,
61263ebb813SSam Clegg                     MCSectionWasm &DataSection) {
6137d1ff446SFangrui Song   LLVM_DEBUG(errs() << "addData: " << DataSection.getName() << "\n");
614759631c7SSam Clegg 
61563ebb813SSam Clegg   DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
61663ebb813SSam Clegg 
617759631c7SSam Clegg   for (const MCFragment &Frag : DataSection) {
618759631c7SSam Clegg     if (Frag.hasInstructions())
619759631c7SSam Clegg       report_fatal_error("only data supported in data sections");
620759631c7SSam Clegg 
621759631c7SSam Clegg     if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
622759631c7SSam Clegg       if (Align->getValueSize() != 1)
623759631c7SSam Clegg         report_fatal_error("only byte values supported for alignment");
624759631c7SSam Clegg       // If nops are requested, use zeros, as this is the data section.
625759631c7SSam Clegg       uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
626f208f631SHeejin Ahn       uint64_t Size =
627f208f631SHeejin Ahn           std::min<uint64_t>(alignTo(DataBytes.size(), Align->getAlignment()),
628f208f631SHeejin Ahn                              DataBytes.size() + Align->getMaxBytesToEmit());
629759631c7SSam Clegg       DataBytes.resize(Size, Value);
630759631c7SSam Clegg     } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
631588fad4dSNirav Dave       int64_t NumValues;
632588fad4dSNirav Dave       if (!Fill->getNumValues().evaluateAsAbsolute(NumValues))
633d707c370SRafael Espindola         llvm_unreachable("The fill should be an assembler constant");
634588fad4dSNirav Dave       DataBytes.insert(DataBytes.end(), Fill->getValueSize() * NumValues,
635588fad4dSNirav Dave                        Fill->getValue());
63624faf859SHeejin Ahn     } else if (auto *LEB = dyn_cast<MCLEBFragment>(&Frag)) {
63724faf859SHeejin Ahn       const SmallVectorImpl<char> &Contents = LEB->getContents();
63824faf859SHeejin Ahn       DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
639759631c7SSam Clegg     } else {
640759631c7SSam Clegg       const auto &DataFrag = cast<MCDataFragment>(Frag);
641759631c7SSam Clegg       const SmallVectorImpl<char> &Contents = DataFrag.getContents();
642759631c7SSam Clegg       DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
643759631c7SSam Clegg     }
644759631c7SSam Clegg   }
645759631c7SSam Clegg 
646d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
647759631c7SSam Clegg }
648759631c7SSam Clegg 
64960ec3034SSam Clegg uint32_t
65060ec3034SSam Clegg WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
651d1152a26SSam Clegg   if (RelEntry.Type == wasm::R_WASM_TYPE_INDEX_LEB) {
652b7787fd0SSam Clegg     if (!TypeIndices.count(RelEntry.Symbol))
653b7787fd0SSam Clegg       report_fatal_error("symbol not found in type index space: " +
654b7787fd0SSam Clegg                          RelEntry.Symbol->getName());
655acd7d2b0SSam Clegg     return TypeIndices[RelEntry.Symbol];
656acd7d2b0SSam Clegg   }
65760ec3034SSam Clegg 
65825d8e68bSSam Clegg   return RelEntry.Symbol->getIndex();
659acd7d2b0SSam Clegg }
660acd7d2b0SSam Clegg 
661d934cb88SDan Gohman // Apply the portions of the relocation records that we can handle ourselves
662d934cb88SDan Gohman // directly.
663acd7d2b0SSam Clegg void WasmObjectWriter::applyRelocations(
6647ee758d6SSam Clegg     ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset,
6657ee758d6SSam Clegg     const MCAsmLayout &Layout) {
666f17b149dSPeter Collingbourne   auto &Stream = static_cast<raw_pwrite_stream &>(W.OS);
667d934cb88SDan Gohman   for (const WasmRelocationEntry &RelEntry : Relocations) {
668d934cb88SDan Gohman     uint64_t Offset = ContentsOffset +
669d934cb88SDan Gohman                       RelEntry.FixupSection->getSectionOffset() +
670d934cb88SDan Gohman                       RelEntry.Offset;
671d934cb88SDan Gohman 
672d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
6737ee758d6SSam Clegg     auto Value = getProvisionalValue(RelEntry, Layout);
67460ec3034SSam Clegg 
675acd7d2b0SSam Clegg     switch (RelEntry.Type) {
676d1152a26SSam Clegg     case wasm::R_WASM_FUNCTION_INDEX_LEB:
677d1152a26SSam Clegg     case wasm::R_WASM_TYPE_INDEX_LEB:
678d1152a26SSam Clegg     case wasm::R_WASM_GLOBAL_INDEX_LEB:
679d1152a26SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_LEB:
680d1152a26SSam Clegg     case wasm::R_WASM_EVENT_INDEX_LEB:
6813b29376eSWouter van Oortmerssen       writePatchableLEB<5>(Stream, Value, Offset);
6823b29376eSWouter van Oortmerssen       break;
6833b29376eSWouter van Oortmerssen     case wasm::R_WASM_MEMORY_ADDR_LEB64:
6843b29376eSWouter van Oortmerssen       writePatchableLEB<10>(Stream, Value, Offset);
685d934cb88SDan Gohman       break;
686d1152a26SSam Clegg     case wasm::R_WASM_TABLE_INDEX_I32:
687d1152a26SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_I32:
688d1152a26SSam Clegg     case wasm::R_WASM_FUNCTION_OFFSET_I32:
689d1152a26SSam Clegg     case wasm::R_WASM_SECTION_OFFSET_I32:
69048139ebcSWouter van Oortmerssen     case wasm::R_WASM_GLOBAL_INDEX_I32:
6910a6c4d8dSSam Clegg       patchI32(Stream, Value, Offset);
692d934cb88SDan Gohman       break;
693*cc1b9b68SWouter van Oortmerssen     case wasm::R_WASM_TABLE_INDEX_I64:
6943b29376eSWouter van Oortmerssen     case wasm::R_WASM_MEMORY_ADDR_I64:
6953b29376eSWouter van Oortmerssen       patchI64(Stream, Value, Offset);
6963b29376eSWouter van Oortmerssen       break;
697d1152a26SSam Clegg     case wasm::R_WASM_TABLE_INDEX_SLEB:
6982a7cac93SSam Clegg     case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
699d1152a26SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_SLEB:
7002a7cac93SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
7013b29376eSWouter van Oortmerssen       writePatchableSLEB<5>(Stream, Value, Offset);
7023b29376eSWouter van Oortmerssen       break;
703*cc1b9b68SWouter van Oortmerssen     case wasm::R_WASM_TABLE_INDEX_SLEB64:
7043b29376eSWouter van Oortmerssen     case wasm::R_WASM_MEMORY_ADDR_SLEB64:
7053b29376eSWouter van Oortmerssen     case wasm::R_WASM_MEMORY_ADDR_REL_SLEB64:
7063b29376eSWouter van Oortmerssen       writePatchableSLEB<10>(Stream, Value, Offset);
70760ec3034SSam Clegg       break;
708d934cb88SDan Gohman     default:
7099d24fb7fSSam Clegg       llvm_unreachable("invalid relocation type");
710d934cb88SDan Gohman     }
711d934cb88SDan Gohman   }
71218eafb6cSDan Gohman }
71318eafb6cSDan Gohman 
714da419bdbSHeejin Ahn void WasmObjectWriter::writeTypeSection(ArrayRef<WasmSignature> Signatures) {
715da419bdbSHeejin Ahn   if (Signatures.empty())
7169e15f359SSam Clegg     return;
7179e15f359SSam Clegg 
7189e15f359SSam Clegg   SectionBookkeeping Section;
7199e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_TYPE);
7209e15f359SSam Clegg 
721da419bdbSHeejin Ahn   encodeULEB128(Signatures.size(), W.OS);
7229e15f359SSam Clegg 
723da419bdbSHeejin Ahn   for (const WasmSignature &Sig : Signatures) {
724f17b149dSPeter Collingbourne     W.OS << char(wasm::WASM_TYPE_FUNC);
725da419bdbSHeejin Ahn     encodeULEB128(Sig.Params.size(), W.OS);
726da419bdbSHeejin Ahn     for (wasm::ValType Ty : Sig.Params)
7279e15f359SSam Clegg       writeValueType(Ty);
728da419bdbSHeejin Ahn     encodeULEB128(Sig.Returns.size(), W.OS);
729da419bdbSHeejin Ahn     for (wasm::ValType Ty : Sig.Returns)
7309e15f359SSam Clegg       writeValueType(Ty);
7319e15f359SSam Clegg   }
7329e15f359SSam Clegg 
7339e15f359SSam Clegg   endSection(Section);
7349e15f359SSam Clegg }
7359e15f359SSam Clegg 
7368defa952SSam Clegg void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports,
7374d135b04SWouter van Oortmerssen                                           uint64_t DataSize,
738f950b24aSSam Clegg                                           uint32_t NumElements) {
7399e15f359SSam Clegg   if (Imports.empty())
7409e15f359SSam Clegg     return;
7419e15f359SSam Clegg 
7424d135b04SWouter van Oortmerssen   uint64_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
743f950b24aSSam Clegg 
7449e15f359SSam Clegg   SectionBookkeeping Section;
7459e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_IMPORT);
7469e15f359SSam Clegg 
747f17b149dSPeter Collingbourne   encodeULEB128(Imports.size(), W.OS);
7488defa952SSam Clegg   for (const wasm::WasmImport &Import : Imports) {
7498defa952SSam Clegg     writeString(Import.Module);
7508defa952SSam Clegg     writeString(Import.Field);
751f17b149dSPeter Collingbourne     W.OS << char(Import.Kind);
7529e15f359SSam Clegg 
7539e15f359SSam Clegg     switch (Import.Kind) {
7549e15f359SSam Clegg     case wasm::WASM_EXTERNAL_FUNCTION:
755f17b149dSPeter Collingbourne       encodeULEB128(Import.SigIndex, W.OS);
7569e15f359SSam Clegg       break;
7579e15f359SSam Clegg     case wasm::WASM_EXTERNAL_GLOBAL:
758f17b149dSPeter Collingbourne       W.OS << char(Import.Global.Type);
759f17b149dSPeter Collingbourne       W.OS << char(Import.Global.Mutable ? 1 : 0);
7609e15f359SSam Clegg       break;
761f950b24aSSam Clegg     case wasm::WASM_EXTERNAL_MEMORY:
7624d135b04SWouter van Oortmerssen       encodeULEB128(Import.Memory.Flags, W.OS);
763f17b149dSPeter Collingbourne       encodeULEB128(NumPages, W.OS);  // initial
764f950b24aSSam Clegg       break;
765f950b24aSSam Clegg     case wasm::WASM_EXTERNAL_TABLE:
766f17b149dSPeter Collingbourne       W.OS << char(Import.Table.ElemType);
767f17b149dSPeter Collingbourne       encodeULEB128(0, W.OS);           // flags
768f17b149dSPeter Collingbourne       encodeULEB128(NumElements, W.OS); // initial
769f950b24aSSam Clegg       break;
770da419bdbSHeejin Ahn     case wasm::WASM_EXTERNAL_EVENT:
771da419bdbSHeejin Ahn       encodeULEB128(Import.Event.Attribute, W.OS);
772da419bdbSHeejin Ahn       encodeULEB128(Import.Event.SigIndex, W.OS);
773da419bdbSHeejin Ahn       break;
7749e15f359SSam Clegg     default:
7759e15f359SSam Clegg       llvm_unreachable("unsupported import kind");
7769e15f359SSam Clegg     }
7779e15f359SSam Clegg   }
7789e15f359SSam Clegg 
7799e15f359SSam Clegg   endSection(Section);
7809e15f359SSam Clegg }
7819e15f359SSam Clegg 
782457fb0b4SSam Clegg void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
7839e15f359SSam Clegg   if (Functions.empty())
7849e15f359SSam Clegg     return;
7859e15f359SSam Clegg 
7869e15f359SSam Clegg   SectionBookkeeping Section;
7879e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_FUNCTION);
7889e15f359SSam Clegg 
789f17b149dSPeter Collingbourne   encodeULEB128(Functions.size(), W.OS);
7909e15f359SSam Clegg   for (const WasmFunction &Func : Functions)
791da419bdbSHeejin Ahn     encodeULEB128(Func.SigIndex, W.OS);
7929e15f359SSam Clegg 
7939e15f359SSam Clegg   endSection(Section);
7949e15f359SSam Clegg }
7959e15f359SSam Clegg 
796da419bdbSHeejin Ahn void WasmObjectWriter::writeEventSection(ArrayRef<wasm::WasmEventType> Events) {
797da419bdbSHeejin Ahn   if (Events.empty())
798da419bdbSHeejin Ahn     return;
799da419bdbSHeejin Ahn 
800da419bdbSHeejin Ahn   SectionBookkeeping Section;
801da419bdbSHeejin Ahn   startSection(Section, wasm::WASM_SEC_EVENT);
802da419bdbSHeejin Ahn 
803da419bdbSHeejin Ahn   encodeULEB128(Events.size(), W.OS);
804da419bdbSHeejin Ahn   for (const wasm::WasmEventType &Event : Events) {
805da419bdbSHeejin Ahn     encodeULEB128(Event.Attribute, W.OS);
806da419bdbSHeejin Ahn     encodeULEB128(Event.SigIndex, W.OS);
807da419bdbSHeejin Ahn   }
808da419bdbSHeejin Ahn 
809da419bdbSHeejin Ahn   endSection(Section);
810da419bdbSHeejin Ahn }
811da419bdbSHeejin Ahn 
8120a6c4d8dSSam Clegg void WasmObjectWriter::writeGlobalSection(ArrayRef<wasm::WasmGlobal> Globals) {
8130a6c4d8dSSam Clegg   if (Globals.empty())
8140a6c4d8dSSam Clegg     return;
8150a6c4d8dSSam Clegg 
8160a6c4d8dSSam Clegg   SectionBookkeeping Section;
8170a6c4d8dSSam Clegg   startSection(Section, wasm::WASM_SEC_GLOBAL);
8180a6c4d8dSSam Clegg 
8190a6c4d8dSSam Clegg   encodeULEB128(Globals.size(), W.OS);
8200a6c4d8dSSam Clegg   for (const wasm::WasmGlobal &Global : Globals) {
8210a6c4d8dSSam Clegg     encodeULEB128(Global.Type.Type, W.OS);
8220a6c4d8dSSam Clegg     W.OS << char(Global.Type.Mutable);
8230a6c4d8dSSam Clegg     W.OS << char(Global.InitExpr.Opcode);
8240a6c4d8dSSam Clegg     switch (Global.Type.Type) {
8250a6c4d8dSSam Clegg     case wasm::WASM_TYPE_I32:
8260a6c4d8dSSam Clegg       encodeSLEB128(0, W.OS);
8270a6c4d8dSSam Clegg       break;
8280a6c4d8dSSam Clegg     case wasm::WASM_TYPE_I64:
8290a6c4d8dSSam Clegg       encodeSLEB128(0, W.OS);
8300a6c4d8dSSam Clegg       break;
8310a6c4d8dSSam Clegg     case wasm::WASM_TYPE_F32:
8320a6c4d8dSSam Clegg       writeI32(0);
8330a6c4d8dSSam Clegg       break;
8340a6c4d8dSSam Clegg     case wasm::WASM_TYPE_F64:
8350a6c4d8dSSam Clegg       writeI64(0);
8360a6c4d8dSSam Clegg       break;
83779aad89dSSam Clegg     case wasm::WASM_TYPE_EXTERNREF:
83879aad89dSSam Clegg       writeValueType(wasm::ValType::EXTERNREF);
83979aad89dSSam Clegg       break;
8400a6c4d8dSSam Clegg     default:
8410a6c4d8dSSam Clegg       llvm_unreachable("unexpected type");
8420a6c4d8dSSam Clegg     }
8430a6c4d8dSSam Clegg     W.OS << char(wasm::WASM_OPCODE_END);
8440a6c4d8dSSam Clegg   }
8450a6c4d8dSSam Clegg 
8460a6c4d8dSSam Clegg   endSection(Section);
8470a6c4d8dSSam Clegg }
8480a6c4d8dSSam Clegg 
8498defa952SSam Clegg void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) {
8509e15f359SSam Clegg   if (Exports.empty())
8519e15f359SSam Clegg     return;
8529e15f359SSam Clegg 
8539e15f359SSam Clegg   SectionBookkeeping Section;
8549e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_EXPORT);
8559e15f359SSam Clegg 
856f17b149dSPeter Collingbourne   encodeULEB128(Exports.size(), W.OS);
8578defa952SSam Clegg   for (const wasm::WasmExport &Export : Exports) {
8588defa952SSam Clegg     writeString(Export.Name);
859f17b149dSPeter Collingbourne     W.OS << char(Export.Kind);
860f17b149dSPeter Collingbourne     encodeULEB128(Export.Index, W.OS);
8619e15f359SSam Clegg   }
8629e15f359SSam Clegg 
8639e15f359SSam Clegg   endSection(Section);
8649e15f359SSam Clegg }
8659e15f359SSam Clegg 
866457fb0b4SSam Clegg void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
8679e15f359SSam Clegg   if (TableElems.empty())
8689e15f359SSam Clegg     return;
8699e15f359SSam Clegg 
8709e15f359SSam Clegg   SectionBookkeeping Section;
8719e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_ELEM);
8729e15f359SSam Clegg 
873f17b149dSPeter Collingbourne   encodeULEB128(1, W.OS); // number of "segments"
874f17b149dSPeter Collingbourne   encodeULEB128(0, W.OS); // the table index
8759e15f359SSam Clegg 
8769e15f359SSam Clegg   // init expr for starting offset
877f17b149dSPeter Collingbourne   W.OS << char(wasm::WASM_OPCODE_I32_CONST);
87818c56a07SHeejin Ahn   encodeSLEB128(InitialTableOffset, W.OS);
879f17b149dSPeter Collingbourne   W.OS << char(wasm::WASM_OPCODE_END);
8809e15f359SSam Clegg 
881f17b149dSPeter Collingbourne   encodeULEB128(TableElems.size(), W.OS);
8829e15f359SSam Clegg   for (uint32_t Elem : TableElems)
883f17b149dSPeter Collingbourne     encodeULEB128(Elem, W.OS);
8849e15f359SSam Clegg 
8859e15f359SSam Clegg   endSection(Section);
8869e15f359SSam Clegg }
8879e15f359SSam Clegg 
888fef8de66SThomas Lively void WasmObjectWriter::writeDataCountSection() {
889fef8de66SThomas Lively   if (DataSegments.empty())
890fef8de66SThomas Lively     return;
891fef8de66SThomas Lively 
892fef8de66SThomas Lively   SectionBookkeeping Section;
893fef8de66SThomas Lively   startSection(Section, wasm::WASM_SEC_DATACOUNT);
894fef8de66SThomas Lively   encodeULEB128(DataSegments.size(), W.OS);
895fef8de66SThomas Lively   endSection(Section);
896fef8de66SThomas Lively }
897fef8de66SThomas Lively 
898e49584a3SSam Clegg uint32_t WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
899457fb0b4SSam Clegg                                             const MCAsmLayout &Layout,
900457fb0b4SSam Clegg                                             ArrayRef<WasmFunction> Functions) {
9019e15f359SSam Clegg   if (Functions.empty())
902e49584a3SSam Clegg     return 0;
9039e15f359SSam Clegg 
9049e15f359SSam Clegg   SectionBookkeeping Section;
9059e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_CODE);
9069e15f359SSam Clegg 
907f17b149dSPeter Collingbourne   encodeULEB128(Functions.size(), W.OS);
9089e15f359SSam Clegg 
9099e15f359SSam Clegg   for (const WasmFunction &Func : Functions) {
910fe6414b0SSam Clegg     auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
9119e15f359SSam Clegg 
9129e15f359SSam Clegg     int64_t Size = 0;
9139e15f359SSam Clegg     if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
9149e15f359SSam Clegg       report_fatal_error(".size expression must be evaluatable");
9159e15f359SSam Clegg 
916f17b149dSPeter Collingbourne     encodeULEB128(Size, W.OS);
917f17b149dSPeter Collingbourne     FuncSection.setSectionOffset(W.OS.tell() - Section.ContentsOffset);
918f17b149dSPeter Collingbourne     Asm.writeSectionData(W.OS, &FuncSection, Layout);
9199e15f359SSam Clegg   }
9209e15f359SSam Clegg 
9219e15f359SSam Clegg   // Apply fixups.
9227ee758d6SSam Clegg   applyRelocations(CodeRelocations, Section.ContentsOffset, Layout);
9239e15f359SSam Clegg 
9249e15f359SSam Clegg   endSection(Section);
925e49584a3SSam Clegg   return Section.Index;
9269e15f359SSam Clegg }
9279e15f359SSam Clegg 
928e49584a3SSam Clegg uint32_t WasmObjectWriter::writeDataSection(const MCAsmLayout &Layout) {
9296c899ba6SSam Clegg   if (DataSegments.empty())
930e49584a3SSam Clegg     return 0;
9319e15f359SSam Clegg 
9329e15f359SSam Clegg   SectionBookkeeping Section;
9339e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_DATA);
9349e15f359SSam Clegg 
935f17b149dSPeter Collingbourne   encodeULEB128(DataSegments.size(), W.OS); // count
9367c395943SSam Clegg 
9376c899ba6SSam Clegg   for (const WasmDataSegment &Segment : DataSegments) {
9382e150409SThomas Lively     encodeULEB128(Segment.InitFlags, W.OS); // flags
9392e150409SThomas Lively     if (Segment.InitFlags & wasm::WASM_SEGMENT_HAS_MEMINDEX)
940f17b149dSPeter Collingbourne       encodeULEB128(0, W.OS); // memory index
9412e150409SThomas Lively     if ((Segment.InitFlags & wasm::WASM_SEGMENT_IS_PASSIVE) == 0) {
9424d135b04SWouter van Oortmerssen       W.OS << char(Segment.Offset > std::numeric_limits<int32_t>().max()
9434d135b04SWouter van Oortmerssen                      ? wasm::WASM_OPCODE_I64_CONST
9444d135b04SWouter van Oortmerssen                      : wasm::WASM_OPCODE_I32_CONST);
945f17b149dSPeter Collingbourne       encodeSLEB128(Segment.Offset, W.OS); // offset
946f17b149dSPeter Collingbourne       W.OS << char(wasm::WASM_OPCODE_END);
9472e150409SThomas Lively     }
948f17b149dSPeter Collingbourne     encodeULEB128(Segment.Data.size(), W.OS); // size
949f17b149dSPeter Collingbourne     Segment.Section->setSectionOffset(W.OS.tell() - Section.ContentsOffset);
950f17b149dSPeter Collingbourne     W.OS << Segment.Data; // data
9517c395943SSam Clegg   }
9529e15f359SSam Clegg 
9539e15f359SSam Clegg   // Apply fixups.
9547ee758d6SSam Clegg   applyRelocations(DataRelocations, Section.ContentsOffset, Layout);
9559e15f359SSam Clegg 
9569e15f359SSam Clegg   endSection(Section);
957e49584a3SSam Clegg   return Section.Index;
9589e15f359SSam Clegg }
9599e15f359SSam Clegg 
9606f08c84aSSam Clegg void WasmObjectWriter::writeRelocSection(
9616f08c84aSSam Clegg     uint32_t SectionIndex, StringRef Name,
962f77dc2a8SSam Clegg     std::vector<WasmRelocationEntry> &Relocs) {
9639e15f359SSam Clegg   // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
9649e15f359SSam Clegg   // for descriptions of the reloc sections.
9659e15f359SSam Clegg 
966f77dc2a8SSam Clegg   if (Relocs.empty())
9679e15f359SSam Clegg     return;
9689e15f359SSam Clegg 
969f77dc2a8SSam Clegg   // First, ensure the relocations are sorted in offset order.  In general they
970f77dc2a8SSam Clegg   // should already be sorted since `recordRelocation` is called in offset
971f77dc2a8SSam Clegg   // order, but for the code section we combine many MC sections into single
972f77dc2a8SSam Clegg   // wasm section, and this order is determined by the order of Asm.Symbols()
973f77dc2a8SSam Clegg   // not the sections order.
974efd94c56SFangrui Song   llvm::stable_sort(
975efd94c56SFangrui Song       Relocs, [](const WasmRelocationEntry &A, const WasmRelocationEntry &B) {
976f77dc2a8SSam Clegg         return (A.Offset + A.FixupSection->getSectionOffset()) <
977f77dc2a8SSam Clegg                (B.Offset + B.FixupSection->getSectionOffset());
978f77dc2a8SSam Clegg       });
979f77dc2a8SSam Clegg 
9809e15f359SSam Clegg   SectionBookkeeping Section;
9816f08c84aSSam Clegg   startCustomSection(Section, std::string("reloc.") + Name.str());
9829e15f359SSam Clegg 
983f17b149dSPeter Collingbourne   encodeULEB128(SectionIndex, W.OS);
984f77dc2a8SSam Clegg   encodeULEB128(Relocs.size(), W.OS);
985f77dc2a8SSam Clegg   for (const WasmRelocationEntry &RelEntry : Relocs) {
986f208f631SHeejin Ahn     uint64_t Offset =
987f208f631SHeejin Ahn         RelEntry.Offset + RelEntry.FixupSection->getSectionOffset();
9886f08c84aSSam Clegg     uint32_t Index = getRelocationIndexValue(RelEntry);
9899e15f359SSam Clegg 
990f17b149dSPeter Collingbourne     W.OS << char(RelEntry.Type);
991f17b149dSPeter Collingbourne     encodeULEB128(Offset, W.OS);
992f17b149dSPeter Collingbourne     encodeULEB128(Index, W.OS);
9936f08c84aSSam Clegg     if (RelEntry.hasAddend())
994f17b149dSPeter Collingbourne       encodeSLEB128(RelEntry.Addend, W.OS);
9959e15f359SSam Clegg   }
9969e15f359SSam Clegg 
9979e15f359SSam Clegg   endSection(Section);
9989e15f359SSam Clegg }
9999e15f359SSam Clegg 
10006a31a0d6SSam Clegg void WasmObjectWriter::writeCustomRelocSections() {
10016a31a0d6SSam Clegg   for (const auto &Sec : CustomSections) {
10026a31a0d6SSam Clegg     auto &Relocations = CustomSectionsRelocations[Sec.Section];
10036a31a0d6SSam Clegg     writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations);
10046a31a0d6SSam Clegg   }
10056a31a0d6SSam Clegg }
10066a31a0d6SSam Clegg 
10079e15f359SSam Clegg void WasmObjectWriter::writeLinkingMetaDataSection(
100886b4a09aSSam Clegg     ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
1009ea7caceeSSam Clegg     ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
1010ea7caceeSSam Clegg     const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) {
10119e15f359SSam Clegg   SectionBookkeeping Section;
10122322a937SSam Clegg   startCustomSection(Section, "linking");
1013f17b149dSPeter Collingbourne   encodeULEB128(wasm::WasmMetadataVersion, W.OS);
10149e15f359SSam Clegg 
10156bb5a41fSSam Clegg   SectionBookkeeping SubSection;
10166c899ba6SSam Clegg   if (SymbolInfos.size() != 0) {
10176c899ba6SSam Clegg     startSection(SubSection, wasm::WASM_SYMBOL_TABLE);
1018f17b149dSPeter Collingbourne     encodeULEB128(SymbolInfos.size(), W.OS);
10196c899ba6SSam Clegg     for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) {
1020f17b149dSPeter Collingbourne       encodeULEB128(Sym.Kind, W.OS);
1021f17b149dSPeter Collingbourne       encodeULEB128(Sym.Flags, W.OS);
10226c899ba6SSam Clegg       switch (Sym.Kind) {
10236c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_FUNCTION:
10246c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_GLOBAL:
1025da419bdbSHeejin Ahn       case wasm::WASM_SYMBOL_TYPE_EVENT:
1026f17b149dSPeter Collingbourne         encodeULEB128(Sym.ElementIndex, W.OS);
102729874ceaSDan Gohman         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0 ||
102829874ceaSDan Gohman             (Sym.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0)
10296c899ba6SSam Clegg           writeString(Sym.Name);
10306c899ba6SSam Clegg         break;
10316c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_DATA:
10326c899ba6SSam Clegg         writeString(Sym.Name);
10336c899ba6SSam Clegg         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) {
1034f17b149dSPeter Collingbourne           encodeULEB128(Sym.DataRef.Segment, W.OS);
1035f17b149dSPeter Collingbourne           encodeULEB128(Sym.DataRef.Offset, W.OS);
1036f17b149dSPeter Collingbourne           encodeULEB128(Sym.DataRef.Size, W.OS);
10376c899ba6SSam Clegg         }
10386c899ba6SSam Clegg         break;
10396a31a0d6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_SECTION: {
10406a31a0d6SSam Clegg         const uint32_t SectionIndex =
10416a31a0d6SSam Clegg             CustomSections[Sym.ElementIndex].OutputIndex;
1042f17b149dSPeter Collingbourne         encodeULEB128(SectionIndex, W.OS);
10436a31a0d6SSam Clegg         break;
10446a31a0d6SSam Clegg       }
10456c899ba6SSam Clegg       default:
10466c899ba6SSam Clegg         llvm_unreachable("unexpected kind");
10476c899ba6SSam Clegg       }
1048b7787fd0SSam Clegg     }
1049b7787fd0SSam Clegg     endSection(SubSection);
1050b7787fd0SSam Clegg   }
10519e15f359SSam Clegg 
10526c899ba6SSam Clegg   if (DataSegments.size()) {
105363ebb813SSam Clegg     startSection(SubSection, wasm::WASM_SEGMENT_INFO);
1054f17b149dSPeter Collingbourne     encodeULEB128(DataSegments.size(), W.OS);
10556c899ba6SSam Clegg     for (const WasmDataSegment &Segment : DataSegments) {
1056d95ed959SSam Clegg       writeString(Segment.Name);
1057f17b149dSPeter Collingbourne       encodeULEB128(Segment.Alignment, W.OS);
10582e150409SThomas Lively       encodeULEB128(Segment.LinkerFlags, W.OS);
105963ebb813SSam Clegg     }
1060d95ed959SSam Clegg     endSection(SubSection);
1061d95ed959SSam Clegg   }
1062d95ed959SSam Clegg 
1063bafe6902SSam Clegg   if (!InitFuncs.empty()) {
1064bafe6902SSam Clegg     startSection(SubSection, wasm::WASM_INIT_FUNCS);
1065f17b149dSPeter Collingbourne     encodeULEB128(InitFuncs.size(), W.OS);
1066bafe6902SSam Clegg     for (auto &StartFunc : InitFuncs) {
1067f17b149dSPeter Collingbourne       encodeULEB128(StartFunc.first, W.OS);  // priority
1068f17b149dSPeter Collingbourne       encodeULEB128(StartFunc.second, W.OS); // function index
1069bafe6902SSam Clegg     }
1070bafe6902SSam Clegg     endSection(SubSection);
1071bafe6902SSam Clegg   }
1072bafe6902SSam Clegg 
1073ea7caceeSSam Clegg   if (Comdats.size()) {
1074ea7caceeSSam Clegg     startSection(SubSection, wasm::WASM_COMDAT_INFO);
1075f17b149dSPeter Collingbourne     encodeULEB128(Comdats.size(), W.OS);
1076ea7caceeSSam Clegg     for (const auto &C : Comdats) {
1077ea7caceeSSam Clegg       writeString(C.first);
1078f17b149dSPeter Collingbourne       encodeULEB128(0, W.OS); // flags for future use
1079f17b149dSPeter Collingbourne       encodeULEB128(C.second.size(), W.OS);
1080ea7caceeSSam Clegg       for (const WasmComdatEntry &Entry : C.second) {
1081f17b149dSPeter Collingbourne         encodeULEB128(Entry.Kind, W.OS);
1082f17b149dSPeter Collingbourne         encodeULEB128(Entry.Index, W.OS);
1083ea7caceeSSam Clegg       }
1084ea7caceeSSam Clegg     }
1085ea7caceeSSam Clegg     endSection(SubSection);
1086ea7caceeSSam Clegg   }
1087ea7caceeSSam Clegg 
10889e15f359SSam Clegg   endSection(Section);
10899e15f359SSam Clegg }
10909e15f359SSam Clegg 
1091cbda16ebSThomas Lively void WasmObjectWriter::writeCustomSection(WasmCustomSection &CustomSection,
1092cbda16ebSThomas Lively                                           const MCAssembler &Asm,
10936a31a0d6SSam Clegg                                           const MCAsmLayout &Layout) {
1094cfd44a2eSSam Clegg   SectionBookkeeping Section;
10956a31a0d6SSam Clegg   auto *Sec = CustomSection.Section;
10962322a937SSam Clegg   startCustomSection(Section, CustomSection.Name);
10976a31a0d6SSam Clegg 
1098f17b149dSPeter Collingbourne   Sec->setSectionOffset(W.OS.tell() - Section.ContentsOffset);
1099f17b149dSPeter Collingbourne   Asm.writeSectionData(W.OS, Sec, Layout);
11006a31a0d6SSam Clegg 
11016a31a0d6SSam Clegg   CustomSection.OutputContentsOffset = Section.ContentsOffset;
11026a31a0d6SSam Clegg   CustomSection.OutputIndex = Section.Index;
11036a31a0d6SSam Clegg 
1104cfd44a2eSSam Clegg   endSection(Section);
11056a31a0d6SSam Clegg 
11066a31a0d6SSam Clegg   // Apply fixups.
11074d57fbd0SSam Clegg   auto &Relocations = CustomSectionsRelocations[CustomSection.Section];
11087ee758d6SSam Clegg   applyRelocations(Relocations, CustomSection.OutputContentsOffset, Layout);
11096a31a0d6SSam Clegg }
11106a31a0d6SSam Clegg 
11115e3d33a7SSam Clegg uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm &Symbol) {
11125e3d33a7SSam Clegg   assert(Symbol.isFunction());
11135e3d33a7SSam Clegg   assert(TypeIndices.count(&Symbol));
11145e3d33a7SSam Clegg   return TypeIndices[&Symbol];
11155e3d33a7SSam Clegg }
11165e3d33a7SSam Clegg 
1117da419bdbSHeejin Ahn uint32_t WasmObjectWriter::getEventType(const MCSymbolWasm &Symbol) {
1118da419bdbSHeejin Ahn   assert(Symbol.isEvent());
1119da419bdbSHeejin Ahn   assert(TypeIndices.count(&Symbol));
1120da419bdbSHeejin Ahn   return TypeIndices[&Symbol];
1121da419bdbSHeejin Ahn }
1122da419bdbSHeejin Ahn 
112338b12f5eSHeejin Ahn void WasmObjectWriter::registerFunctionType(const MCSymbolWasm &Symbol) {
11245e3d33a7SSam Clegg   assert(Symbol.isFunction());
11255e3d33a7SSam Clegg 
1126da419bdbSHeejin Ahn   WasmSignature S;
11277ee758d6SSam Clegg 
11287ee758d6SSam Clegg   if (auto *Sig = Symbol.getSignature()) {
1129da419bdbSHeejin Ahn     S.Returns = Sig->Returns;
1130da419bdbSHeejin Ahn     S.Params = Sig->Params;
113177a7a380SDerek Schuff   }
11325e3d33a7SSam Clegg 
1133da419bdbSHeejin Ahn   auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
11345e3d33a7SSam Clegg   if (Pair.second)
1135da419bdbSHeejin Ahn     Signatures.push_back(S);
11365e3d33a7SSam Clegg   TypeIndices[&Symbol] = Pair.first->second;
11375e3d33a7SSam Clegg 
1138d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "registerFunctionType: " << Symbol
1139d34e60caSNicola Zaghen                     << " new:" << Pair.second << "\n");
1140d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
11415e3d33a7SSam Clegg }
11425e3d33a7SSam Clegg 
114338b12f5eSHeejin Ahn void WasmObjectWriter::registerEventType(const MCSymbolWasm &Symbol) {
1144da419bdbSHeejin Ahn   assert(Symbol.isEvent());
1145da419bdbSHeejin Ahn 
1146da419bdbSHeejin Ahn   // TODO Currently we don't generate imported exceptions, but if we do, we
1147da419bdbSHeejin Ahn   // should have a way of infering types of imported exceptions.
1148da419bdbSHeejin Ahn   WasmSignature S;
1149da419bdbSHeejin Ahn   if (auto *Sig = Symbol.getSignature()) {
1150da419bdbSHeejin Ahn     S.Returns = Sig->Returns;
1151da419bdbSHeejin Ahn     S.Params = Sig->Params;
1152da419bdbSHeejin Ahn   }
1153da419bdbSHeejin Ahn 
1154da419bdbSHeejin Ahn   auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
1155da419bdbSHeejin Ahn   if (Pair.second)
1156da419bdbSHeejin Ahn     Signatures.push_back(S);
1157da419bdbSHeejin Ahn   TypeIndices[&Symbol] = Pair.first->second;
1158da419bdbSHeejin Ahn 
1159da419bdbSHeejin Ahn   LLVM_DEBUG(dbgs() << "registerEventType: " << Symbol << " new:" << Pair.second
1160da419bdbSHeejin Ahn                     << "\n");
1161da419bdbSHeejin Ahn   LLVM_DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
1162da419bdbSHeejin Ahn }
1163da419bdbSHeejin Ahn 
11644d57fbd0SSam Clegg static bool isInSymtab(const MCSymbolWasm &Sym) {
11653ea1c62cSSam Clegg   if (Sym.isUsedInReloc() || Sym.isUsedInInitArray())
11664d57fbd0SSam Clegg     return true;
11674d57fbd0SSam Clegg 
11684d57fbd0SSam Clegg   if (Sym.isComdat() && !Sym.isDefined())
11694d57fbd0SSam Clegg     return false;
11704d57fbd0SSam Clegg 
11713ea1c62cSSam Clegg   if (Sym.isTemporary())
11724d57fbd0SSam Clegg     return false;
11734d57fbd0SSam Clegg 
11744d57fbd0SSam Clegg   if (Sym.isSection())
11754d57fbd0SSam Clegg     return false;
11764d57fbd0SSam Clegg 
11774d57fbd0SSam Clegg   return true;
11784d57fbd0SSam Clegg }
11794d57fbd0SSam Clegg 
1180438390faSPeter Collingbourne uint64_t WasmObjectWriter::writeObject(MCAssembler &Asm,
118118eafb6cSDan Gohman                                        const MCAsmLayout &Layout) {
1182438390faSPeter Collingbourne   uint64_t StartOffset = W.OS.tell();
1183438390faSPeter Collingbourne 
1184d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
1185d934cb88SDan Gohman 
1186d934cb88SDan Gohman   // Collect information from the available symbols.
1187d934cb88SDan Gohman   SmallVector<WasmFunction, 4> Functions;
1188d934cb88SDan Gohman   SmallVector<uint32_t, 4> TableElems;
11898defa952SSam Clegg   SmallVector<wasm::WasmImport, 4> Imports;
11908defa952SSam Clegg   SmallVector<wasm::WasmExport, 4> Exports;
1191da419bdbSHeejin Ahn   SmallVector<wasm::WasmEventType, 1> Events;
11920a6c4d8dSSam Clegg   SmallVector<wasm::WasmGlobal, 1> Globals;
11936c899ba6SSam Clegg   SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos;
1194bafe6902SSam Clegg   SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
1195ea7caceeSSam Clegg   std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
11964d135b04SWouter van Oortmerssen   uint64_t DataSize = 0;
1197d934cb88SDan Gohman 
1198f950b24aSSam Clegg   // For now, always emit the memory import, since loads and stores are not
1199f950b24aSSam Clegg   // valid without it. In the future, we could perhaps be more clever and omit
1200f950b24aSSam Clegg   // it if there are no loads or stores.
12018defa952SSam Clegg   wasm::WasmImport MemImport;
12021ed3a046SSam Clegg   MemImport.Module = "env";
12031ed3a046SSam Clegg   MemImport.Field = "__linear_memory";
1204f950b24aSSam Clegg   MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
1205fd0964aeSWouter van Oortmerssen   MemImport.Memory.Flags = is64Bit() ? wasm::WASM_LIMITS_FLAG_IS_64
1206fd0964aeSWouter van Oortmerssen                                      : wasm::WASM_LIMITS_FLAG_NONE;
1207f950b24aSSam Clegg   Imports.push_back(MemImport);
1208f950b24aSSam Clegg 
1209f950b24aSSam Clegg   // For now, always emit the table section, since indirect calls are not
1210f950b24aSSam Clegg   // valid without it. In the future, we could perhaps be more clever and omit
1211f950b24aSSam Clegg   // it if there are no indirect calls.
12128defa952SSam Clegg   wasm::WasmImport TableImport;
12131ed3a046SSam Clegg   TableImport.Module = "env";
12141ed3a046SSam Clegg   TableImport.Field = "__indirect_function_table";
1215f950b24aSSam Clegg   TableImport.Kind = wasm::WASM_EXTERNAL_TABLE;
12166a87ddacSThomas Lively   TableImport.Table.ElemType = wasm::WASM_TYPE_FUNCREF;
1217f950b24aSSam Clegg   Imports.push_back(TableImport);
1218f950b24aSSam Clegg 
1219da419bdbSHeejin Ahn   // Populate SignatureIndices, and Imports and WasmIndices for undefined
1220586320c0SNicholas Wilson   // symbols.  This must be done before populating WasmIndices for defined
1221586320c0SNicholas Wilson   // symbols.
122232ce5ca0SDan Gohman   for (const MCSymbol &S : Asm.symbols()) {
122332ce5ca0SDan Gohman     const auto &WS = static_cast<const MCSymbolWasm &>(S);
122432ce5ca0SDan Gohman 
122532ce5ca0SDan Gohman     // Register types for all functions, including those with private linkage
12269f3fe42eSSam Clegg     // (because wasm always needs a type signature).
12277ee758d6SSam Clegg     if (WS.isFunction()) {
12287ee758d6SSam Clegg       const MCSymbolWasm *Base = cast<MCSymbolWasm>(Layout.getBaseSymbol(S));
12297ee758d6SSam Clegg       registerFunctionType(*Base);
12307ee758d6SSam Clegg     }
123132ce5ca0SDan Gohman 
1232da419bdbSHeejin Ahn     if (WS.isEvent())
1233da419bdbSHeejin Ahn       registerEventType(WS);
1234da419bdbSHeejin Ahn 
123532ce5ca0SDan Gohman     if (WS.isTemporary())
123632ce5ca0SDan Gohman       continue;
123732ce5ca0SDan Gohman 
123832ce5ca0SDan Gohman     // If the symbol is not defined in this translation unit, import it.
12396c899ba6SSam Clegg     if (!WS.isDefined() && !WS.isComdat()) {
12406c899ba6SSam Clegg       if (WS.isFunction()) {
12418defa952SSam Clegg         wasm::WasmImport Import;
1242f726e445SDan Gohman         Import.Module = WS.getImportModule();
1243f726e445SDan Gohman         Import.Field = WS.getImportName();
124432ce5ca0SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
12458defa952SSam Clegg         Import.SigIndex = getFunctionType(WS);
12466c899ba6SSam Clegg         Imports.push_back(Import);
1247492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
12486c899ba6SSam Clegg         WasmIndices[&WS] = NumFunctionImports++;
12496c899ba6SSam Clegg       } else if (WS.isGlobal()) {
125015f349f7SNicholas Wilson         if (WS.isWeak())
125115f349f7SNicholas Wilson           report_fatal_error("undefined global symbol cannot be weak");
125215f349f7SNicholas Wilson 
12536c899ba6SSam Clegg         wasm::WasmImport Import;
1254f726e445SDan Gohman         Import.Field = WS.getImportName();
125532ce5ca0SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1256492f7529SSam Clegg         Import.Module = WS.getImportModule();
12576c899ba6SSam Clegg         Import.Global = WS.getGlobalType();
12586c899ba6SSam Clegg         Imports.push_back(Import);
1259492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
12606c899ba6SSam Clegg         WasmIndices[&WS] = NumGlobalImports++;
1261da419bdbSHeejin Ahn       } else if (WS.isEvent()) {
1262da419bdbSHeejin Ahn         if (WS.isWeak())
1263da419bdbSHeejin Ahn           report_fatal_error("undefined event symbol cannot be weak");
1264da419bdbSHeejin Ahn 
1265da419bdbSHeejin Ahn         wasm::WasmImport Import;
1266f726e445SDan Gohman         Import.Module = WS.getImportModule();
1267f726e445SDan Gohman         Import.Field = WS.getImportName();
1268da419bdbSHeejin Ahn         Import.Kind = wasm::WASM_EXTERNAL_EVENT;
1269da419bdbSHeejin Ahn         Import.Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
1270da419bdbSHeejin Ahn         Import.Event.SigIndex = getEventType(WS);
1271da419bdbSHeejin Ahn         Imports.push_back(Import);
1272492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
1273da419bdbSHeejin Ahn         WasmIndices[&WS] = NumEventImports++;
127432ce5ca0SDan Gohman       }
127532ce5ca0SDan Gohman     }
127632ce5ca0SDan Gohman   }
127732ce5ca0SDan Gohman 
1278492f7529SSam Clegg   // Add imports for GOT globals
1279492f7529SSam Clegg   for (const MCSymbol &S : Asm.symbols()) {
1280492f7529SSam Clegg     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1281492f7529SSam Clegg     if (WS.isUsedInGOT()) {
1282492f7529SSam Clegg       wasm::WasmImport Import;
1283492f7529SSam Clegg       if (WS.isFunction())
1284492f7529SSam Clegg         Import.Module = "GOT.func";
1285492f7529SSam Clegg       else
1286492f7529SSam Clegg         Import.Module = "GOT.mem";
1287492f7529SSam Clegg       Import.Field = WS.getName();
1288492f7529SSam Clegg       Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1289492f7529SSam Clegg       Import.Global = {wasm::WASM_TYPE_I32, true};
1290492f7529SSam Clegg       Imports.push_back(Import);
1291492f7529SSam Clegg       assert(GOTIndices.count(&WS) == 0);
1292492f7529SSam Clegg       GOTIndices[&WS] = NumGlobalImports++;
1293492f7529SSam Clegg     }
1294492f7529SSam Clegg   }
1295492f7529SSam Clegg 
12964d57fbd0SSam Clegg   // Populate DataSegments and CustomSections, which must be done before
12974d57fbd0SSam Clegg   // populating DataLocations.
1298759631c7SSam Clegg   for (MCSection &Sec : Asm) {
1299759631c7SSam Clegg     auto &Section = static_cast<MCSectionWasm &>(Sec);
13007d1ff446SFangrui Song     StringRef SectionName = Section.getName();
1301759631c7SSam Clegg 
1302bafe6902SSam Clegg     // .init_array sections are handled specially elsewhere.
13034d57fbd0SSam Clegg     if (SectionName.startswith(".init_array"))
1304bafe6902SSam Clegg       continue;
1305bafe6902SSam Clegg 
13064d57fbd0SSam Clegg     // Code is handled separately
13074d57fbd0SSam Clegg     if (Section.getKind().isText())
13084d57fbd0SSam Clegg       continue;
13094d57fbd0SSam Clegg 
13104d57fbd0SSam Clegg     if (Section.isWasmData()) {
1311329e76d5SSam Clegg       uint32_t SegmentIndex = DataSegments.size();
1312759631c7SSam Clegg       DataSize = alignTo(DataSize, Section.getAlignment());
1313759631c7SSam Clegg       DataSegments.emplace_back();
1314759631c7SSam Clegg       WasmDataSegment &Segment = DataSegments.back();
13154d57fbd0SSam Clegg       Segment.Name = SectionName;
13169b49f36aSSimon Pilgrim       Segment.InitFlags =
13179b49f36aSSimon Pilgrim           Section.getPassive() ? (uint32_t)wasm::WASM_SEGMENT_IS_PASSIVE : 0;
1318759631c7SSam Clegg       Segment.Offset = DataSize;
1319759631c7SSam Clegg       Segment.Section = &Section;
132063ebb813SSam Clegg       addData(Segment.Data, Section);
132156c587adSSam Clegg       Segment.Alignment = Log2_32(Section.getAlignment());
13222e150409SThomas Lively       Segment.LinkerFlags = 0;
1323759631c7SSam Clegg       DataSize += Segment.Data.size();
13246c899ba6SSam Clegg       Section.setSegmentIndex(SegmentIndex);
1325ea7caceeSSam Clegg 
1326ea7caceeSSam Clegg       if (const MCSymbolWasm *C = Section.getGroup()) {
1327ea7caceeSSam Clegg         Comdats[C->getName()].emplace_back(
1328329e76d5SSam Clegg             WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
1329ea7caceeSSam Clegg       }
13304d57fbd0SSam Clegg     } else {
13314d57fbd0SSam Clegg       // Create custom sections
13324d57fbd0SSam Clegg       assert(Sec.getKind().isMetadata());
13334d57fbd0SSam Clegg 
13344d57fbd0SSam Clegg       StringRef Name = SectionName;
13354d57fbd0SSam Clegg 
13364d57fbd0SSam Clegg       // For user-defined custom sections, strip the prefix
13374d57fbd0SSam Clegg       if (Name.startswith(".custom_section."))
13384d57fbd0SSam Clegg         Name = Name.substr(strlen(".custom_section."));
13394d57fbd0SSam Clegg 
13404d57fbd0SSam Clegg       MCSymbol *Begin = Sec.getBeginSymbol();
1341fb807d4dSSam Clegg       if (Begin) {
13424d57fbd0SSam Clegg         WasmIndices[cast<MCSymbolWasm>(Begin)] = CustomSections.size();
1343b210c64bSSam Clegg         if (SectionName != Begin->getName())
1344fb807d4dSSam Clegg           report_fatal_error("section name and begin symbol should match: " +
1345b210c64bSSam Clegg                              Twine(SectionName));
1346fb807d4dSSam Clegg       }
1347cbda16ebSThomas Lively 
1348f6f4f843SThomas Lively       // Separate out the producers and target features sections
1349cbda16ebSThomas Lively       if (Name == "producers") {
13500eaee545SJonas Devlieghere         ProducersSection = std::make_unique<WasmCustomSection>(Name, &Section);
1351cbda16ebSThomas Lively         continue;
1352cbda16ebSThomas Lively       }
1353f6f4f843SThomas Lively       if (Name == "target_features") {
1354f6f4f843SThomas Lively         TargetFeaturesSection =
13550eaee545SJonas Devlieghere             std::make_unique<WasmCustomSection>(Name, &Section);
1356f6f4f843SThomas Lively         continue;
1357f6f4f843SThomas Lively       }
1358cbda16ebSThomas Lively 
13594d57fbd0SSam Clegg       CustomSections.emplace_back(Name, &Section);
1360759631c7SSam Clegg     }
13616a31a0d6SSam Clegg   }
13626a31a0d6SSam Clegg 
1363586320c0SNicholas Wilson   // Populate WasmIndices and DataLocations for defined symbols.
1364d934cb88SDan Gohman   for (const MCSymbol &S : Asm.symbols()) {
1365d934cb88SDan Gohman     // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1366d934cb88SDan Gohman     // or used in relocations.
1367d934cb88SDan Gohman     if (S.isTemporary() && S.getName().empty())
1368d934cb88SDan Gohman       continue;
1369b7787fd0SSam Clegg 
1370d934cb88SDan Gohman     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1371d34e60caSNicola Zaghen     LLVM_DEBUG(
1372d34e60caSNicola Zaghen         dbgs() << "MCSymbol: " << toString(WS.getType()) << " '" << S << "'"
1373d34e60caSNicola Zaghen                << " isDefined=" << S.isDefined() << " isExternal="
1374d34e60caSNicola Zaghen                << S.isExternal() << " isTemporary=" << S.isTemporary()
1375d34e60caSNicola Zaghen                << " isWeak=" << WS.isWeak() << " isHidden=" << WS.isHidden()
1376b7787fd0SSam Clegg                << " isVariable=" << WS.isVariable() << "\n");
1377b7787fd0SSam Clegg 
13785e3d33a7SSam Clegg     if (WS.isVariable())
13795e3d33a7SSam Clegg       continue;
13806c899ba6SSam Clegg     if (WS.isComdat() && !WS.isDefined())
13816c899ba6SSam Clegg       continue;
1382b7787fd0SSam Clegg 
1383d934cb88SDan Gohman     if (WS.isFunction()) {
13846c899ba6SSam Clegg       unsigned Index;
1385cd65f698SSam Clegg       if (WS.isDefined()) {
1386b7787fd0SSam Clegg         if (WS.getOffset() != 0)
1387b7787fd0SSam Clegg           report_fatal_error(
1388b7787fd0SSam Clegg               "function sections must contain one function each");
1389b7787fd0SSam Clegg 
139018c56a07SHeejin Ahn         if (WS.getSize() == nullptr)
1391b7787fd0SSam Clegg           report_fatal_error(
1392b7787fd0SSam Clegg               "function symbols must have a size set with .size");
1393b7787fd0SSam Clegg 
13946c899ba6SSam Clegg         // A definition. Write out the function body.
13959f3fe42eSSam Clegg         Index = NumFunctionImports + Functions.size();
1396d934cb88SDan Gohman         WasmFunction Func;
1397da419bdbSHeejin Ahn         Func.SigIndex = getFunctionType(WS);
1398d934cb88SDan Gohman         Func.Sym = &WS;
13996c899ba6SSam Clegg         WasmIndices[&WS] = Index;
1400d934cb88SDan Gohman         Functions.push_back(Func);
14016c899ba6SSam Clegg 
14026c899ba6SSam Clegg         auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
14036c899ba6SSam Clegg         if (const MCSymbolWasm *C = Section.getGroup()) {
14046c899ba6SSam Clegg           Comdats[C->getName()].emplace_back(
14056c899ba6SSam Clegg               WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
14066c899ba6SSam Clegg         }
1407881d8778SSam Clegg 
1408881d8778SSam Clegg         if (WS.hasExportName()) {
1409881d8778SSam Clegg           wasm::WasmExport Export;
1410881d8778SSam Clegg           Export.Name = WS.getExportName();
1411881d8778SSam Clegg           Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1412881d8778SSam Clegg           Export.Index = Index;
1413881d8778SSam Clegg           Exports.push_back(Export);
1414881d8778SSam Clegg         }
1415d934cb88SDan Gohman       } else {
1416d934cb88SDan Gohman         // An import; the index was assigned above.
14176c899ba6SSam Clegg         Index = WasmIndices.find(&WS)->second;
1418d934cb88SDan Gohman       }
1419d934cb88SDan Gohman 
1420d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> function index: " << Index << "\n");
1421da419bdbSHeejin Ahn 
14226c899ba6SSam Clegg     } else if (WS.isData()) {
1423f3feb6adSWouter van Oortmerssen       if (!isInSymtab(WS))
1424c38e947eSSam Clegg         continue;
1425c38e947eSSam Clegg 
14266c899ba6SSam Clegg       if (!WS.isDefined()) {
1427d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "  -> segment index: -1"
1428d34e60caSNicola Zaghen                           << "\n");
1429fe6414b0SSam Clegg         continue;
14306c899ba6SSam Clegg       }
1431fe6414b0SSam Clegg 
1432d934cb88SDan Gohman       if (!WS.getSize())
1433c38e947eSSam Clegg         report_fatal_error("data symbols must have a size set with .size: " +
1434c38e947eSSam Clegg                            WS.getName());
1435d934cb88SDan Gohman 
1436d934cb88SDan Gohman       int64_t Size = 0;
1437d934cb88SDan Gohman       if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1438d934cb88SDan Gohman         report_fatal_error(".size expression must be evaluatable");
1439d934cb88SDan Gohman 
1440759631c7SSam Clegg       auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
1441079cba04SSam Clegg       if (!DataSection.isWasmData())
1442079cba04SSam Clegg         report_fatal_error("data symbols must live in a data section: " +
1443079cba04SSam Clegg                            WS.getName());
14447c395943SSam Clegg 
14456c899ba6SSam Clegg       // For each data symbol, export it in the symtab as a reference to the
14466c899ba6SSam Clegg       // corresponding Wasm data segment.
14476c899ba6SSam Clegg       wasm::WasmDataReference Ref = wasm::WasmDataReference{
14483b29376eSWouter van Oortmerssen           DataSection.getSegmentIndex(), Layout.getSymbolOffset(WS),
14493b29376eSWouter van Oortmerssen           static_cast<uint64_t>(Size)};
14506c899ba6SSam Clegg       DataLocations[&WS] = Ref;
1451d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> segment index: " << Ref.Segment << "\n");
1452da419bdbSHeejin Ahn 
1453a165f2d6SSam Clegg     } else if (WS.isGlobal()) {
14546c899ba6SSam Clegg       // A "true" Wasm global (currently just __stack_pointer)
14550a6c4d8dSSam Clegg       if (WS.isDefined()) {
14560a6c4d8dSSam Clegg         assert(WasmIndices.count(&WS) == 0);
14570a6c4d8dSSam Clegg         wasm::WasmGlobal Global;
14580a6c4d8dSSam Clegg         Global.Type = WS.getGlobalType();
14590a6c4d8dSSam Clegg         Global.Index = NumGlobalImports + Globals.size();
14600a6c4d8dSSam Clegg         switch (Global.Type.Type) {
14610a6c4d8dSSam Clegg         case wasm::WASM_TYPE_I32:
14620a6c4d8dSSam Clegg           Global.InitExpr.Opcode = wasm::WASM_OPCODE_I32_CONST;
14630a6c4d8dSSam Clegg           break;
14640a6c4d8dSSam Clegg         case wasm::WASM_TYPE_I64:
14650a6c4d8dSSam Clegg           Global.InitExpr.Opcode = wasm::WASM_OPCODE_I64_CONST;
14660a6c4d8dSSam Clegg           break;
14670a6c4d8dSSam Clegg         case wasm::WASM_TYPE_F32:
14680a6c4d8dSSam Clegg           Global.InitExpr.Opcode = wasm::WASM_OPCODE_F32_CONST;
14690a6c4d8dSSam Clegg           break;
14700a6c4d8dSSam Clegg         case wasm::WASM_TYPE_F64:
14710a6c4d8dSSam Clegg           Global.InitExpr.Opcode = wasm::WASM_OPCODE_F64_CONST;
14720a6c4d8dSSam Clegg           break;
147379aad89dSSam Clegg         case wasm::WASM_TYPE_EXTERNREF:
147479aad89dSSam Clegg           Global.InitExpr.Opcode = wasm::WASM_OPCODE_REF_NULL;
147579aad89dSSam Clegg           break;
14760a6c4d8dSSam Clegg         default:
14770a6c4d8dSSam Clegg           llvm_unreachable("unexpected type");
14780a6c4d8dSSam Clegg         }
14790a6c4d8dSSam Clegg         WasmIndices[&WS] = Global.Index;
14800a6c4d8dSSam Clegg         Globals.push_back(Global);
14810a6c4d8dSSam Clegg       } else {
1482545932beSEric Christopher         // An import; the index was assigned above
1483d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "  -> global index: "
1484d34e60caSNicola Zaghen                           << WasmIndices.find(&WS)->second << "\n");
14850a6c4d8dSSam Clegg       }
1486da419bdbSHeejin Ahn     } else if (WS.isEvent()) {
1487da419bdbSHeejin Ahn       // C++ exception symbol (__cpp_exception)
1488da419bdbSHeejin Ahn       unsigned Index;
1489da419bdbSHeejin Ahn       if (WS.isDefined()) {
14900a6c4d8dSSam Clegg         assert(WasmIndices.count(&WS) == 0);
1491da419bdbSHeejin Ahn         Index = NumEventImports + Events.size();
1492da419bdbSHeejin Ahn         wasm::WasmEventType Event;
1493da419bdbSHeejin Ahn         Event.SigIndex = getEventType(WS);
1494da419bdbSHeejin Ahn         Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
1495da419bdbSHeejin Ahn         WasmIndices[&WS] = Index;
1496da419bdbSHeejin Ahn         Events.push_back(Event);
1497da419bdbSHeejin Ahn       } else {
1498da419bdbSHeejin Ahn         // An import; the index was assigned above.
1499492f7529SSam Clegg         assert(WasmIndices.count(&WS) > 0);
1500da419bdbSHeejin Ahn       }
1501da419bdbSHeejin Ahn       LLVM_DEBUG(dbgs() << "  -> event index: " << WasmIndices.find(&WS)->second
1502da419bdbSHeejin Ahn                         << "\n");
1503da419bdbSHeejin Ahn 
1504a165f2d6SSam Clegg     } else {
1505a165f2d6SSam Clegg       assert(WS.isSection());
1506d934cb88SDan Gohman     }
1507d934cb88SDan Gohman   }
1508d934cb88SDan Gohman 
1509586320c0SNicholas Wilson   // Populate WasmIndices and DataLocations for aliased symbols.  We need to
1510586320c0SNicholas Wilson   // process these in a separate pass because we need to have processed the
1511586320c0SNicholas Wilson   // target of the alias before the alias itself and the symbols are not
1512586320c0SNicholas Wilson   // necessarily ordered in this way.
1513b7787fd0SSam Clegg   for (const MCSymbol &S : Asm.symbols()) {
1514b7787fd0SSam Clegg     if (!S.isVariable())
1515b7787fd0SSam Clegg       continue;
151631a2c809SSam Clegg 
1517cd65f698SSam Clegg     assert(S.isDefined());
1518b7787fd0SSam Clegg 
15197ee758d6SSam Clegg     const MCSymbolWasm *Base = cast<MCSymbolWasm>(Layout.getBaseSymbol(S));
15207ee758d6SSam Clegg 
15215e3d33a7SSam Clegg     // Find the target symbol of this weak alias and export that index
1522aff1c4dfSSam Clegg     const auto &WS = static_cast<const MCSymbolWasm &>(S);
15237ee758d6SSam Clegg     LLVM_DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *Base << "'\n");
1524b7787fd0SSam Clegg 
15257ee758d6SSam Clegg     if (Base->isFunction()) {
15267ee758d6SSam Clegg       assert(WasmIndices.count(Base) > 0);
15277ee758d6SSam Clegg       uint32_t WasmIndex = WasmIndices.find(Base)->second;
1528492f7529SSam Clegg       assert(WasmIndices.count(&WS) == 0);
15296c899ba6SSam Clegg       WasmIndices[&WS] = WasmIndex;
1530d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> index:" << WasmIndex << "\n");
15317ee758d6SSam Clegg     } else if (Base->isData()) {
15327ee758d6SSam Clegg       auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
15337ee758d6SSam Clegg       uint64_t Offset = Layout.getSymbolOffset(S);
15347ee758d6SSam Clegg       int64_t Size = 0;
15357ee758d6SSam Clegg       // For data symbol alias we use the size of the base symbol as the
15367ee758d6SSam Clegg       // size of the alias.  When an offset from the base is involved this
15377ee758d6SSam Clegg       // can result in a offset + size goes past the end of the data section
15387ee758d6SSam Clegg       // which out object format doesn't support.  So we must clamp it.
15397ee758d6SSam Clegg       if (!Base->getSize()->evaluateAsAbsolute(Size, Layout))
15407ee758d6SSam Clegg         report_fatal_error(".size expression must be evaluatable");
15417ee758d6SSam Clegg       const WasmDataSegment &Segment =
15427ee758d6SSam Clegg           DataSegments[DataSection.getSegmentIndex()];
15437ee758d6SSam Clegg       Size =
15447ee758d6SSam Clegg           std::min(static_cast<uint64_t>(Size), Segment.Data.size() - Offset);
15457ee758d6SSam Clegg       wasm::WasmDataReference Ref = wasm::WasmDataReference{
15467ee758d6SSam Clegg           DataSection.getSegmentIndex(),
15477ee758d6SSam Clegg           static_cast<uint32_t>(Layout.getSymbolOffset(S)),
15487ee758d6SSam Clegg           static_cast<uint32_t>(Size)};
15496c899ba6SSam Clegg       DataLocations[&WS] = Ref;
1550d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> index:" << Ref.Segment << "\n");
15516c899ba6SSam Clegg     } else {
1552da419bdbSHeejin Ahn       report_fatal_error("don't yet support global/event aliases");
15536c899ba6SSam Clegg     }
1554586320c0SNicholas Wilson   }
155531a2c809SSam Clegg 
1556586320c0SNicholas Wilson   // Finally, populate the symbol table itself, in its "natural" order.
1557586320c0SNicholas Wilson   for (const MCSymbol &S : Asm.symbols()) {
1558586320c0SNicholas Wilson     const auto &WS = static_cast<const MCSymbolWasm &>(S);
155925d8e68bSSam Clegg     if (!isInSymtab(WS)) {
156018c56a07SHeejin Ahn       WS.setIndex(InvalidIndex);
1561586320c0SNicholas Wilson       continue;
156225d8e68bSSam Clegg     }
1563d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "adding to symtab: " << WS << "\n");
1564586320c0SNicholas Wilson 
1565586320c0SNicholas Wilson     uint32_t Flags = 0;
1566586320c0SNicholas Wilson     if (WS.isWeak())
1567586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_BINDING_WEAK;
1568586320c0SNicholas Wilson     if (WS.isHidden())
1569586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN;
1570586320c0SNicholas Wilson     if (!WS.isExternal() && WS.isDefined())
1571586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;
1572586320c0SNicholas Wilson     if (WS.isUndefined())
1573586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_UNDEFINED;
1574da84b688SDan Gohman     if (WS.isNoStrip()) {
1575da84b688SDan Gohman       Flags |= wasm::WASM_SYMBOL_NO_STRIP;
1576da84b688SDan Gohman       if (isEmscripten()) {
1577d6ef8da3SSam Clegg         Flags |= wasm::WASM_SYMBOL_EXPORTED;
1578da84b688SDan Gohman       }
1579da84b688SDan Gohman     }
1580b4f4e370SSam Clegg     if (WS.hasImportName())
158129874ceaSDan Gohman       Flags |= wasm::WASM_SYMBOL_EXPLICIT_NAME;
1582881d8778SSam Clegg     if (WS.hasExportName())
1583881d8778SSam Clegg       Flags |= wasm::WASM_SYMBOL_EXPORTED;
1584586320c0SNicholas Wilson 
1585586320c0SNicholas Wilson     wasm::WasmSymbolInfo Info;
1586586320c0SNicholas Wilson     Info.Name = WS.getName();
1587586320c0SNicholas Wilson     Info.Kind = WS.getType();
1588586320c0SNicholas Wilson     Info.Flags = Flags;
15894d57fbd0SSam Clegg     if (!WS.isData()) {
15904d57fbd0SSam Clegg       assert(WasmIndices.count(&WS) > 0);
1591586320c0SNicholas Wilson       Info.ElementIndex = WasmIndices.find(&WS)->second;
15924d57fbd0SSam Clegg     } else if (WS.isDefined()) {
15934d57fbd0SSam Clegg       assert(DataLocations.count(&WS) > 0);
1594586320c0SNicholas Wilson       Info.DataRef = DataLocations.find(&WS)->second;
15954d57fbd0SSam Clegg     }
159625d8e68bSSam Clegg     WS.setIndex(SymbolInfos.size());
1597586320c0SNicholas Wilson     SymbolInfos.emplace_back(Info);
1598b7787fd0SSam Clegg   }
1599b7787fd0SSam Clegg 
16006006e091SSam Clegg   {
16016006e091SSam Clegg     auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
1602f9edbe95SSam Clegg       // Functions referenced by a relocation need to put in the table.  This is
1603f9edbe95SSam Clegg       // purely to make the object file's provisional values readable, and is
1604f9edbe95SSam Clegg       // ignored by the linker, which re-calculates the relocations itself.
1605d1152a26SSam Clegg       if (Rel.Type != wasm::R_WASM_TABLE_INDEX_I32 &&
1606*cc1b9b68SWouter van Oortmerssen           Rel.Type != wasm::R_WASM_TABLE_INDEX_I64 &&
160781443ac1SSam Clegg           Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB &&
1608*cc1b9b68SWouter van Oortmerssen           Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB64 &&
160981443ac1SSam Clegg           Rel.Type != wasm::R_WASM_TABLE_INDEX_REL_SLEB)
1610f9edbe95SSam Clegg         return;
1611f9edbe95SSam Clegg       assert(Rel.Symbol->isFunction());
16127ee758d6SSam Clegg       const MCSymbolWasm *Base =
16137ee758d6SSam Clegg           cast<MCSymbolWasm>(Layout.getBaseSymbol(*Rel.Symbol));
16147ee758d6SSam Clegg       uint32_t FunctionIndex = WasmIndices.find(Base)->second;
161518c56a07SHeejin Ahn       uint32_t TableIndex = TableElems.size() + InitialTableOffset;
16167ee758d6SSam Clegg       if (TableIndices.try_emplace(Base, TableIndex).second) {
16177ee758d6SSam Clegg         LLVM_DEBUG(dbgs() << "  -> adding " << Base->getName()
1618f9edbe95SSam Clegg                           << " to table: " << TableIndex << "\n");
16196c899ba6SSam Clegg         TableElems.push_back(FunctionIndex);
16207ee758d6SSam Clegg         registerFunctionType(*Base);
16216006e091SSam Clegg       }
16226006e091SSam Clegg     };
1623970d02c4SDan Gohman 
16246006e091SSam Clegg     for (const WasmRelocationEntry &RelEntry : CodeRelocations)
16256006e091SSam Clegg       HandleReloc(RelEntry);
16266006e091SSam Clegg     for (const WasmRelocationEntry &RelEntry : DataRelocations)
16276006e091SSam Clegg       HandleReloc(RelEntry);
1628d934cb88SDan Gohman   }
1629d934cb88SDan Gohman 
1630bafe6902SSam Clegg   // Translate .init_array section contents into start functions.
1631bafe6902SSam Clegg   for (const MCSection &S : Asm) {
1632bafe6902SSam Clegg     const auto &WS = static_cast<const MCSectionWasm &>(S);
16337d1ff446SFangrui Song     if (WS.getName().startswith(".fini_array"))
1634bafe6902SSam Clegg       report_fatal_error(".fini_array sections are unsupported");
16357d1ff446SFangrui Song     if (!WS.getName().startswith(".init_array"))
1636bafe6902SSam Clegg       continue;
1637bafe6902SSam Clegg     if (WS.getFragmentList().empty())
1638bafe6902SSam Clegg       continue;
1639b210c64bSSam Clegg 
1640b210c64bSSam Clegg     // init_array is expected to contain a single non-empty data fragment
1641b210c64bSSam Clegg     if (WS.getFragmentList().size() != 3)
1642bafe6902SSam Clegg       report_fatal_error("only one .init_array section fragment supported");
1643b210c64bSSam Clegg 
1644b210c64bSSam Clegg     auto IT = WS.begin();
1645b210c64bSSam Clegg     const MCFragment &EmptyFrag = *IT;
1646b210c64bSSam Clegg     if (EmptyFrag.getKind() != MCFragment::FT_Data)
1647b210c64bSSam Clegg       report_fatal_error(".init_array section should be aligned");
1648b210c64bSSam Clegg 
1649b210c64bSSam Clegg     IT = std::next(IT);
1650b210c64bSSam Clegg     const MCFragment &AlignFrag = *IT;
1651bafe6902SSam Clegg     if (AlignFrag.getKind() != MCFragment::FT_Align)
1652bafe6902SSam Clegg       report_fatal_error(".init_array section should be aligned");
1653bafe6902SSam Clegg     if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
1654bafe6902SSam Clegg       report_fatal_error(".init_array section should be aligned for pointers");
1655b210c64bSSam Clegg 
1656b210c64bSSam Clegg     const MCFragment &Frag = *std::next(IT);
1657bafe6902SSam Clegg     if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1658bafe6902SSam Clegg       report_fatal_error("only data supported in .init_array section");
1659b210c64bSSam Clegg 
1660bafe6902SSam Clegg     uint16_t Priority = UINT16_MAX;
16614d57fbd0SSam Clegg     unsigned PrefixLength = strlen(".init_array");
16627d1ff446SFangrui Song     if (WS.getName().size() > PrefixLength) {
16637d1ff446SFangrui Song       if (WS.getName()[PrefixLength] != '.')
1664f208f631SHeejin Ahn         report_fatal_error(
1665f208f631SHeejin Ahn             ".init_array section priority should start with '.'");
16667d1ff446SFangrui Song       if (WS.getName().substr(PrefixLength + 1).getAsInteger(10, Priority))
1667bafe6902SSam Clegg         report_fatal_error("invalid .init_array section priority");
1668bafe6902SSam Clegg     }
1669bafe6902SSam Clegg     const auto &DataFrag = cast<MCDataFragment>(Frag);
1670bafe6902SSam Clegg     const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1671f208f631SHeejin Ahn     for (const uint8_t *
167218c56a07SHeejin Ahn              P = (const uint8_t *)Contents.data(),
167318c56a07SHeejin Ahn             *End = (const uint8_t *)Contents.data() + Contents.size();
167418c56a07SHeejin Ahn          P != End; ++P) {
167518c56a07SHeejin Ahn       if (*P != 0)
1676bafe6902SSam Clegg         report_fatal_error("non-symbolic data in .init_array section");
1677bafe6902SSam Clegg     }
1678bafe6902SSam Clegg     for (const MCFixup &Fixup : DataFrag.getFixups()) {
1679f208f631SHeejin Ahn       assert(Fixup.getKind() ==
1680f208f631SHeejin Ahn              MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
1681bafe6902SSam Clegg       const MCExpr *Expr = Fixup.getValue();
16828fffa1dfSSam Clegg       auto *SymRef = dyn_cast<MCSymbolRefExpr>(Expr);
16838fffa1dfSSam Clegg       if (!SymRef)
1684bafe6902SSam Clegg         report_fatal_error("fixups in .init_array should be symbol references");
16858fffa1dfSSam Clegg       const auto &TargetSym = cast<const MCSymbolWasm>(SymRef->getSymbol());
16868fffa1dfSSam Clegg       if (TargetSym.getIndex() == InvalidIndex)
16873ea1c62cSSam Clegg         report_fatal_error("symbols in .init_array should exist in symtab");
16888fffa1dfSSam Clegg       if (!TargetSym.isFunction())
16898fffa1dfSSam Clegg         report_fatal_error("symbols in .init_array should be for functions");
169025d8e68bSSam Clegg       InitFuncs.push_back(
16918fffa1dfSSam Clegg           std::make_pair(Priority, TargetSym.getIndex()));
1692bafe6902SSam Clegg     }
1693bafe6902SSam Clegg   }
1694bafe6902SSam Clegg 
169518eafb6cSDan Gohman   // Write out the Wasm header.
169618eafb6cSDan Gohman   writeHeader(Asm);
169718eafb6cSDan Gohman 
1698da419bdbSHeejin Ahn   writeTypeSection(Signatures);
1699f950b24aSSam Clegg   writeImportSection(Imports, DataSize, TableElems.size());
17009e15f359SSam Clegg   writeFunctionSection(Functions);
1701f950b24aSSam Clegg   // Skip the "table" section; we import the table instead.
1702f950b24aSSam Clegg   // Skip the "memory" section; we import the memory instead.
1703da419bdbSHeejin Ahn   writeEventSection(Events);
17040a6c4d8dSSam Clegg   writeGlobalSection(Globals);
17059e15f359SSam Clegg   writeExportSection(Exports);
17069e15f359SSam Clegg   writeElemSection(TableElems);
1707fef8de66SThomas Lively   writeDataCountSection();
1708e49584a3SSam Clegg   uint32_t CodeSectionIndex = writeCodeSection(Asm, Layout, Functions);
1709e49584a3SSam Clegg   uint32_t DataSectionIndex = writeDataSection(Layout);
1710cbda16ebSThomas Lively   for (auto &CustomSection : CustomSections)
1711cbda16ebSThomas Lively     writeCustomSection(CustomSection, Asm, Layout);
1712c22bfb6bSNicholas Wilson   writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats);
17136f08c84aSSam Clegg   writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations);
17146f08c84aSSam Clegg   writeRelocSection(DataSectionIndex, "DATA", DataRelocations);
17156a31a0d6SSam Clegg   writeCustomRelocSections();
1716cbda16ebSThomas Lively   if (ProducersSection)
1717cbda16ebSThomas Lively     writeCustomSection(*ProducersSection, Asm, Layout);
1718f6f4f843SThomas Lively   if (TargetFeaturesSection)
1719f6f4f843SThomas Lively     writeCustomSection(*TargetFeaturesSection, Asm, Layout);
1720970d02c4SDan Gohman 
1721d934cb88SDan Gohman   // TODO: Translate the .comment section to the output.
1722438390faSPeter Collingbourne   return W.OS.tell() - StartOffset;
172318eafb6cSDan Gohman }
172418eafb6cSDan Gohman 
172560fbc7ccSLang Hames std::unique_ptr<MCObjectWriter>
17261301a878SLang Hames llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
172718eafb6cSDan Gohman                              raw_pwrite_stream &OS) {
17280eaee545SJonas Devlieghere   return std::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
172918eafb6cSDan Gohman }
1730