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"
14264b5d9eSZachary Turner #include "llvm/BinaryFormat/Wasm.h"
15b59dff4bSBenjamin Kramer #include "llvm/BinaryFormat/WasmTraits.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 <vector>
3418eafb6cSDan Gohman 
3518eafb6cSDan Gohman using namespace llvm;
3618eafb6cSDan Gohman 
375e3d33a7SSam Clegg #define DEBUG_TYPE "mc"
3818eafb6cSDan Gohman 
3918eafb6cSDan Gohman namespace {
409e15f359SSam Clegg 
41feac819eSAndy Wingo // When we create the indirect function table we start at 1, so that there is
42feac819eSAndy Wingo // and empty slot at 0 and therefore calling a null function pointer will trap.
4318c56a07SHeejin Ahn static const uint32_t InitialTableOffset = 1;
4430e1bbc1SSam Clegg 
45d934cb88SDan Gohman // For patching purposes, we need to remember where each section starts, both
46d934cb88SDan Gohman // for patching up the section size field, and for patching up references to
47d934cb88SDan Gohman // locations within the section.
48d934cb88SDan Gohman struct SectionBookkeeping {
49d934cb88SDan Gohman   // Where the size of the section is written.
50d934cb88SDan Gohman   uint64_t SizeOffset;
516a31a0d6SSam Clegg   // Where the section header ends (without custom section name).
526a31a0d6SSam Clegg   uint64_t PayloadOffset;
536a31a0d6SSam Clegg   // Where the contents of the section starts.
54d934cb88SDan Gohman   uint64_t ContentsOffset;
556f08c84aSSam Clegg   uint32_t Index;
56d934cb88SDan Gohman };
57d934cb88SDan Gohman 
587c395943SSam Clegg // A wasm data segment.  A wasm binary contains only a single data section
597c395943SSam Clegg // but that can contain many segments, each with their own virtual location
607c395943SSam Clegg // in memory.  Each MCSection data created by llvm is modeled as its own
617c395943SSam Clegg // wasm data segment.
627c395943SSam Clegg struct WasmDataSegment {
637c395943SSam Clegg   MCSectionWasm *Section;
64d95ed959SSam Clegg   StringRef Name;
652e150409SThomas Lively   uint32_t InitFlags;
664d135b04SWouter van Oortmerssen   uint64_t Offset;
6763ebb813SSam Clegg   uint32_t Alignment;
683b8d2be5SSam Clegg   uint32_t LinkingFlags;
697c395943SSam Clegg   SmallVector<char, 4> Data;
707c395943SSam Clegg };
717c395943SSam Clegg 
729e15f359SSam Clegg // A wasm function to be written into the function section.
739e15f359SSam Clegg struct WasmFunction {
74da419bdbSHeejin Ahn   uint32_t SigIndex;
759e15f359SSam Clegg   const MCSymbolWasm *Sym;
769e15f359SSam Clegg };
779e15f359SSam Clegg 
789e15f359SSam Clegg // A wasm global to be written into the global section.
799e15f359SSam Clegg struct WasmGlobal {
806e7f1826SSam Clegg   wasm::WasmGlobalType Type;
819e15f359SSam Clegg   uint64_t InitialValue;
829e15f359SSam Clegg };
839e15f359SSam Clegg 
84ea7caceeSSam Clegg // Information about a single item which is part of a COMDAT.  For each data
85ea7caceeSSam Clegg // segment or function which is in the COMDAT, there is a corresponding
86ea7caceeSSam Clegg // WasmComdatEntry.
87ea7caceeSSam Clegg struct WasmComdatEntry {
88ea7caceeSSam Clegg   unsigned Kind;
89ea7caceeSSam Clegg   uint32_t Index;
90ea7caceeSSam Clegg };
91ea7caceeSSam Clegg 
926dc65e91SSam Clegg // Information about a single relocation.
936dc65e91SSam Clegg struct WasmRelocationEntry {
946dc65e91SSam Clegg   uint64_t Offset;                   // Where is the relocation.
956dc65e91SSam Clegg   const MCSymbolWasm *Symbol;        // The symbol to relocate with.
966dc65e91SSam Clegg   int64_t Addend;                    // A value to add to the symbol.
976dc65e91SSam Clegg   unsigned Type;                     // The type of the relocation.
98fe6414b0SSam Clegg   const MCSectionWasm *FixupSection; // The section the relocation is targeting.
996dc65e91SSam Clegg 
1006dc65e91SSam Clegg   WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol,
1016dc65e91SSam Clegg                       int64_t Addend, unsigned Type,
102fe6414b0SSam Clegg                       const MCSectionWasm *FixupSection)
1036dc65e91SSam Clegg       : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type),
1046dc65e91SSam Clegg         FixupSection(FixupSection) {}
1056dc65e91SSam Clegg 
106cadcb9ebSKeno Fischer   bool hasAddend() const { return wasm::relocTypeHasAddend(Type); }
107acd7d2b0SSam Clegg 
1086dc65e91SSam Clegg   void print(raw_ostream &Out) const {
109f208f631SHeejin Ahn     Out << wasm::relocTypetoString(Type) << " Off=" << Offset
110f208f631SHeejin Ahn         << ", Sym=" << *Symbol << ", Addend=" << Addend
1117d1ff446SFangrui Song         << ", FixupSection=" << FixupSection->getName();
1126dc65e91SSam Clegg   }
113b7787fd0SSam Clegg 
114615eb470SAaron Ballman #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
115b7787fd0SSam Clegg   LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
116b7787fd0SSam Clegg #endif
1176dc65e91SSam Clegg };
1186dc65e91SSam Clegg 
11918c56a07SHeejin Ahn static const uint32_t InvalidIndex = -1;
12025d8e68bSSam Clegg 
121cfd44a2eSSam Clegg struct WasmCustomSection {
122cfd44a2eSSam Clegg 
1236a31a0d6SSam Clegg   StringRef Name;
1246a31a0d6SSam Clegg   MCSectionWasm *Section;
1256a31a0d6SSam Clegg 
12670fc36d8SKazu Hirata   uint32_t OutputContentsOffset = 0;
12770fc36d8SKazu Hirata   uint32_t OutputIndex = InvalidIndex;
1286a31a0d6SSam Clegg 
1296a31a0d6SSam Clegg   WasmCustomSection(StringRef Name, MCSectionWasm *Section)
13070fc36d8SKazu Hirata       : Name(Name), Section(Section) {}
131cfd44a2eSSam Clegg };
132cfd44a2eSSam Clegg 
1331fb8daa6SSam Clegg #if !defined(NDEBUG)
1347f055deeSSam Clegg raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
135b7787fd0SSam Clegg   Rel.print(OS);
136b7787fd0SSam Clegg   return OS;
137b7787fd0SSam Clegg }
1381fb8daa6SSam Clegg #endif
139b7787fd0SSam Clegg 
1404c75521cSSam Clegg // Write Value as an (unsigned) LEB value at offset Offset in Stream, padded
14119e8befaSSam Clegg // to allow patching.
1424c75521cSSam Clegg template <typename T, int W>
1434c75521cSSam Clegg void writePatchableULEB(raw_pwrite_stream &Stream, T Value, uint64_t Offset) {
1443b29376eSWouter van Oortmerssen   uint8_t Buffer[W];
1454c75521cSSam Clegg   unsigned SizeLen = encodeULEB128(Value, Buffer, W);
1463b29376eSWouter van Oortmerssen   assert(SizeLen == W);
14719e8befaSSam Clegg   Stream.pwrite((char *)Buffer, SizeLen, Offset);
14819e8befaSSam Clegg }
14919e8befaSSam Clegg 
1504c75521cSSam Clegg // Write Value as an signed LEB value at offset Offset in Stream, padded
15119e8befaSSam Clegg // to allow patching.
1524c75521cSSam Clegg template <typename T, int W>
1534c75521cSSam Clegg void writePatchableSLEB(raw_pwrite_stream &Stream, T Value, uint64_t Offset) {
1543b29376eSWouter van Oortmerssen   uint8_t Buffer[W];
1554c75521cSSam Clegg   unsigned SizeLen = encodeSLEB128(Value, Buffer, W);
1563b29376eSWouter van Oortmerssen   assert(SizeLen == W);
15719e8befaSSam Clegg   Stream.pwrite((char *)Buffer, SizeLen, Offset);
15819e8befaSSam Clegg }
15919e8befaSSam Clegg 
1604c75521cSSam Clegg static void writePatchableU32(raw_pwrite_stream &Stream, uint32_t Value,
1614c75521cSSam Clegg                               uint64_t Offset) {
1624c75521cSSam Clegg   writePatchableULEB<uint32_t, 5>(Stream, Value, Offset);
1634c75521cSSam Clegg }
1644c75521cSSam Clegg 
1654c75521cSSam Clegg static void writePatchableS32(raw_pwrite_stream &Stream, int32_t Value,
1664c75521cSSam Clegg                               uint64_t Offset) {
1674c75521cSSam Clegg   writePatchableSLEB<int32_t, 5>(Stream, Value, Offset);
1684c75521cSSam Clegg }
1694c75521cSSam Clegg 
1704c75521cSSam Clegg static void writePatchableU64(raw_pwrite_stream &Stream, uint64_t Value,
1714c75521cSSam Clegg                               uint64_t Offset) {
1724c75521cSSam Clegg   writePatchableSLEB<uint64_t, 10>(Stream, Value, Offset);
1734c75521cSSam Clegg }
1744c75521cSSam Clegg 
1754c75521cSSam Clegg static void writePatchableS64(raw_pwrite_stream &Stream, int64_t Value,
1764c75521cSSam Clegg                               uint64_t Offset) {
1774c75521cSSam Clegg   writePatchableSLEB<int64_t, 10>(Stream, Value, Offset);
1784c75521cSSam Clegg }
1794c75521cSSam Clegg 
1804c75521cSSam Clegg // Write Value as a plain integer value at offset Offset in Stream.
1814c75521cSSam Clegg static void patchI32(raw_pwrite_stream &Stream, uint32_t Value,
1824c75521cSSam Clegg                      uint64_t Offset) {
18319e8befaSSam Clegg   uint8_t Buffer[4];
1844c75521cSSam Clegg   support::endian::write32le(Buffer, Value);
18519e8befaSSam Clegg   Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
18619e8befaSSam Clegg }
18719e8befaSSam Clegg 
1884c75521cSSam Clegg static void patchI64(raw_pwrite_stream &Stream, uint64_t Value,
1894c75521cSSam Clegg                      uint64_t Offset) {
1903b29376eSWouter van Oortmerssen   uint8_t Buffer[8];
1914c75521cSSam Clegg   support::endian::write64le(Buffer, Value);
1923b29376eSWouter van Oortmerssen   Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
1933b29376eSWouter van Oortmerssen }
1943b29376eSWouter van Oortmerssen 
1950ff28fa6SDerek Schuff bool isDwoSection(const MCSection &Sec) {
1960ff28fa6SDerek Schuff   return Sec.getName().endswith(".dwo");
1970ff28fa6SDerek Schuff }
1980ff28fa6SDerek Schuff 
19918eafb6cSDan Gohman class WasmObjectWriter : public MCObjectWriter {
2000ff28fa6SDerek Schuff   support::endian::Writer *W;
201f17b149dSPeter Collingbourne 
20218eafb6cSDan Gohman   /// The target specific Wasm writer instance.
20318eafb6cSDan Gohman   std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
20418eafb6cSDan Gohman 
205d934cb88SDan Gohman   // Relocations for fixing up references in the code section.
206d934cb88SDan Gohman   std::vector<WasmRelocationEntry> CodeRelocations;
207d934cb88SDan Gohman   // Relocations for fixing up references in the data section.
208d934cb88SDan Gohman   std::vector<WasmRelocationEntry> DataRelocations;
209d934cb88SDan Gohman 
210d934cb88SDan Gohman   // Index values to use for fixing up call_indirect type indices.
211acd7d2b0SSam Clegg   // Maps function symbols to the index of the type of the function
212acd7d2b0SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
213d99f6078SSam Clegg   // Maps function symbols to the table element index space. Used
214d99f6078SSam Clegg   // for TABLE_INDEX relocation types (i.e. address taken functions).
215f9edbe95SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> TableIndices;
216388fb67bSPaulo Matos   // Maps function/global/table symbols to the
2171d891d44SHeejin Ahn   // function/global/table/tag/section index space.
2186c899ba6SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> WasmIndices;
219492f7529SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> GOTIndices;
2206c899ba6SSam Clegg   // Maps data symbols to the Wasm segment and offset/size with the segment.
2216c899ba6SSam Clegg   DenseMap<const MCSymbolWasm *, wasm::WasmDataReference> DataLocations;
2226a31a0d6SSam Clegg 
2236a31a0d6SSam Clegg   // Stores output data (index, relocations, content offset) for custom
2246a31a0d6SSam Clegg   // section.
2256a31a0d6SSam Clegg   std::vector<WasmCustomSection> CustomSections;
226cbda16ebSThomas Lively   std::unique_ptr<WasmCustomSection> ProducersSection;
227f6f4f843SThomas Lively   std::unique_ptr<WasmCustomSection> TargetFeaturesSection;
2286a31a0d6SSam Clegg   // Relocations for fixing up references in the custom sections.
2296a31a0d6SSam Clegg   DenseMap<const MCSectionWasm *, std::vector<WasmRelocationEntry>>
2306a31a0d6SSam Clegg       CustomSectionsRelocations;
231acd7d2b0SSam Clegg 
232c0d41195SSam Clegg   // Map from section to defining function symbol.
2336ccb59b3SSam Clegg   DenseMap<const MCSection *, const MCSymbol *> SectionFunctions;
2346ccb59b3SSam Clegg 
2354c41fb5aSHeejin Ahn   DenseMap<wasm::WasmSignature, uint32_t> SignatureIndices;
2364c41fb5aSHeejin Ahn   SmallVector<wasm::WasmSignature, 4> Signatures;
2376c899ba6SSam Clegg   SmallVector<WasmDataSegment, 4> DataSegments;
2389f3fe42eSSam Clegg   unsigned NumFunctionImports = 0;
2397c395943SSam Clegg   unsigned NumGlobalImports = 0;
240feac819eSAndy Wingo   unsigned NumTableImports = 0;
2411d891d44SHeejin Ahn   unsigned NumTagImports = 0;
2427e1c3345SChandler Carruth   uint32_t SectionCount = 0;
243d934cb88SDan Gohman 
2440ff28fa6SDerek Schuff   enum class DwoMode {
2450ff28fa6SDerek Schuff     AllSections,
2460ff28fa6SDerek Schuff     NonDwoOnly,
2470ff28fa6SDerek Schuff     DwoOnly,
2480ff28fa6SDerek Schuff   };
2490ff28fa6SDerek Schuff   bool IsSplitDwarf = false;
2500ff28fa6SDerek Schuff   raw_pwrite_stream *OS = nullptr;
2510ff28fa6SDerek Schuff   raw_pwrite_stream *DwoOS = nullptr;
2520ff28fa6SDerek Schuff 
2530ff28fa6SDerek Schuff   // TargetObjectWriter wranppers.
25418eafb6cSDan Gohman   bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
255da84b688SDan Gohman   bool isEmscripten() const { return TargetObjectWriter->isEmscripten(); }
25618eafb6cSDan Gohman 
2572322a937SSam Clegg   void startSection(SectionBookkeeping &Section, unsigned SectionId);
2582322a937SSam Clegg   void startCustomSection(SectionBookkeeping &Section, StringRef Name);
259d934cb88SDan Gohman   void endSection(SectionBookkeeping &Section);
260d934cb88SDan Gohman 
26118eafb6cSDan Gohman public:
2621301a878SLang Hames   WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
2630ff28fa6SDerek Schuff                    raw_pwrite_stream &OS_)
2640ff28fa6SDerek Schuff       : TargetObjectWriter(std::move(MOTW)), OS(&OS_) {}
2650ff28fa6SDerek Schuff 
2660ff28fa6SDerek Schuff   WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
2670ff28fa6SDerek Schuff                    raw_pwrite_stream &OS_, raw_pwrite_stream &DwoOS_)
2680ff28fa6SDerek Schuff       : TargetObjectWriter(std::move(MOTW)), IsSplitDwarf(true), OS(&OS_),
2690ff28fa6SDerek Schuff         DwoOS(&DwoOS_) {}
27018eafb6cSDan Gohman 
2710917c9e4SDan Gohman private:
272acd7d2b0SSam Clegg   void reset() override {
273acd7d2b0SSam Clegg     CodeRelocations.clear();
274acd7d2b0SSam Clegg     DataRelocations.clear();
275acd7d2b0SSam Clegg     TypeIndices.clear();
2766c899ba6SSam Clegg     WasmIndices.clear();
277492f7529SSam Clegg     GOTIndices.clear();
278f9edbe95SSam Clegg     TableIndices.clear();
2796c899ba6SSam Clegg     DataLocations.clear();
280cbda16ebSThomas Lively     CustomSections.clear();
281cbda16ebSThomas Lively     ProducersSection.reset();
282f6f4f843SThomas Lively     TargetFeaturesSection.reset();
2836a31a0d6SSam Clegg     CustomSectionsRelocations.clear();
284da419bdbSHeejin Ahn     SignatureIndices.clear();
285da419bdbSHeejin Ahn     Signatures.clear();
2866c899ba6SSam Clegg     DataSegments.clear();
2876ccb59b3SSam Clegg     SectionFunctions.clear();
2889f3fe42eSSam Clegg     NumFunctionImports = 0;
2897c395943SSam Clegg     NumGlobalImports = 0;
290feac819eSAndy Wingo     NumTableImports = 0;
291105bdc25SSam Clegg     MCObjectWriter::reset();
292acd7d2b0SSam Clegg   }
293acd7d2b0SSam Clegg 
29418eafb6cSDan Gohman   void writeHeader(const MCAssembler &Asm);
29518eafb6cSDan Gohman 
29618eafb6cSDan Gohman   void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
29718eafb6cSDan Gohman                         const MCFragment *Fragment, const MCFixup &Fixup,
298ceecfe5bSRafael Espindola                         MCValue Target, uint64_t &FixedValue) override;
29918eafb6cSDan Gohman 
30018eafb6cSDan Gohman   void executePostLayoutBinding(MCAssembler &Asm,
30118eafb6cSDan Gohman                                 const MCAsmLayout &Layout) override;
3020ff28fa6SDerek Schuff   void prepareImports(SmallVectorImpl<wasm::WasmImport> &Imports,
3030ff28fa6SDerek Schuff                       MCAssembler &Asm, const MCAsmLayout &Layout);
304438390faSPeter Collingbourne   uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
3059e15f359SSam Clegg 
3060ff28fa6SDerek Schuff   uint64_t writeOneObject(MCAssembler &Asm, const MCAsmLayout &Layout,
3070ff28fa6SDerek Schuff                           DwoMode Mode);
3080ff28fa6SDerek Schuff 
309b7787fd0SSam Clegg   void writeString(const StringRef Str) {
3100ff28fa6SDerek Schuff     encodeULEB128(Str.size(), W->OS);
3110ff28fa6SDerek Schuff     W->OS << Str;
312b7787fd0SSam Clegg   }
313b7787fd0SSam Clegg 
3141813fde9SYuta Saito   void writeStringWithAlignment(const StringRef Str, unsigned Alignment);
3151813fde9SYuta Saito 
3160a6c4d8dSSam Clegg   void writeI32(int32_t val) {
3170a6c4d8dSSam Clegg     char Buffer[4];
3180a6c4d8dSSam Clegg     support::endian::write32le(Buffer, val);
3190ff28fa6SDerek Schuff     W->OS.write(Buffer, sizeof(Buffer));
3200a6c4d8dSSam Clegg   }
3210a6c4d8dSSam Clegg 
3220a6c4d8dSSam Clegg   void writeI64(int64_t val) {
3230a6c4d8dSSam Clegg     char Buffer[8];
3240a6c4d8dSSam Clegg     support::endian::write64le(Buffer, val);
3250ff28fa6SDerek Schuff     W->OS.write(Buffer, sizeof(Buffer));
3260a6c4d8dSSam Clegg   }
3270a6c4d8dSSam Clegg 
3280ff28fa6SDerek Schuff   void writeValueType(wasm::ValType Ty) { W->OS << static_cast<char>(Ty); }
3299e15f359SSam Clegg 
3304c41fb5aSHeejin Ahn   void writeTypeSection(ArrayRef<wasm::WasmSignature> Signatures);
3314d135b04SWouter van Oortmerssen   void writeImportSection(ArrayRef<wasm::WasmImport> Imports, uint64_t DataSize,
332f950b24aSSam Clegg                           uint32_t NumElements);
333457fb0b4SSam Clegg   void writeFunctionSection(ArrayRef<WasmFunction> Functions);
3348defa952SSam Clegg   void writeExportSection(ArrayRef<wasm::WasmExport> Exports);
335a5a3659dSAndy Wingo   void writeElemSection(const MCSymbolWasm *IndirectFunctionTable,
336a5a3659dSAndy Wingo                         ArrayRef<uint32_t> TableElems);
337fef8de66SThomas Lively   void writeDataCountSection();
338e49584a3SSam Clegg   uint32_t writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
339457fb0b4SSam Clegg                             ArrayRef<WasmFunction> Functions);
340e49584a3SSam Clegg   uint32_t writeDataSection(const MCAsmLayout &Layout);
3413ec1760dSHeejin Ahn   void writeTagSection(ArrayRef<uint32_t> TagTypes);
3420a6c4d8dSSam Clegg   void writeGlobalSection(ArrayRef<wasm::WasmGlobal> Globals);
343388fb67bSPaulo Matos   void writeTableSection(ArrayRef<wasm::WasmTable> Tables);
3446f08c84aSSam Clegg   void writeRelocSection(uint32_t SectionIndex, StringRef Name,
345f77dc2a8SSam Clegg                          std::vector<WasmRelocationEntry> &Relocations);
34631a2c809SSam Clegg   void writeLinkingMetaDataSection(
34786b4a09aSSam Clegg       ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
348ea7caceeSSam Clegg       ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
349ea7caceeSSam Clegg       const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats);
350cbda16ebSThomas Lively   void writeCustomSection(WasmCustomSection &CustomSection,
351cbda16ebSThomas Lively                           const MCAssembler &Asm, const MCAsmLayout &Layout);
3526a31a0d6SSam Clegg   void writeCustomRelocSections();
353acd7d2b0SSam Clegg 
3547ee758d6SSam Clegg   uint64_t getProvisionalValue(const WasmRelocationEntry &RelEntry,
3557ee758d6SSam Clegg                                const MCAsmLayout &Layout);
356acd7d2b0SSam Clegg   void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
3577ee758d6SSam Clegg                         uint64_t ContentsOffset, const MCAsmLayout &Layout);
358acd7d2b0SSam Clegg 
359acd7d2b0SSam Clegg   uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
3605e3d33a7SSam Clegg   uint32_t getFunctionType(const MCSymbolWasm &Symbol);
3611d891d44SHeejin Ahn   uint32_t getTagType(const MCSymbolWasm &Symbol);
36238b12f5eSHeejin Ahn   void registerFunctionType(const MCSymbolWasm &Symbol);
3631d891d44SHeejin Ahn   void registerTagType(const MCSymbolWasm &Symbol);
36418eafb6cSDan Gohman };
3659e15f359SSam Clegg 
36618eafb6cSDan Gohman } // end anonymous namespace
36718eafb6cSDan Gohman 
368d934cb88SDan Gohman // Write out a section header and a patchable section size field.
369d934cb88SDan Gohman void WasmObjectWriter::startSection(SectionBookkeeping &Section,
3702322a937SSam Clegg                                     unsigned SectionId) {
371d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "startSection " << SectionId << "\n");
3720ff28fa6SDerek Schuff   W->OS << char(SectionId);
373d934cb88SDan Gohman 
3740ff28fa6SDerek Schuff   Section.SizeOffset = W->OS.tell();
375d934cb88SDan Gohman 
376d934cb88SDan Gohman   // The section size. We don't know the size yet, so reserve enough space
377d934cb88SDan Gohman   // for any 32-bit value; we'll patch it later.
3780ff28fa6SDerek Schuff   encodeULEB128(0, W->OS, 5);
379d934cb88SDan Gohman 
380d934cb88SDan Gohman   // The position where the section starts, for measuring its size.
3810ff28fa6SDerek Schuff   Section.ContentsOffset = W->OS.tell();
3820ff28fa6SDerek Schuff   Section.PayloadOffset = W->OS.tell();
3836f08c84aSSam Clegg   Section.Index = SectionCount++;
384d934cb88SDan Gohman }
3852322a937SSam Clegg 
3861813fde9SYuta Saito // Write a string with extra paddings for trailing alignment
3871813fde9SYuta Saito // TODO: support alignment at asm and llvm level?
3881813fde9SYuta Saito void WasmObjectWriter::writeStringWithAlignment(const StringRef Str,
3891813fde9SYuta Saito                                                 unsigned Alignment) {
3901813fde9SYuta Saito 
3911813fde9SYuta Saito   // Calculate the encoded size of str length and add pads based on it and
3921813fde9SYuta Saito   // alignment.
3931813fde9SYuta Saito   raw_null_ostream NullOS;
3941813fde9SYuta Saito   uint64_t StrSizeLength = encodeULEB128(Str.size(), NullOS);
3951813fde9SYuta Saito   uint64_t Offset = W->OS.tell() + StrSizeLength + Str.size();
3961813fde9SYuta Saito   uint64_t Paddings = offsetToAlignment(Offset, Align(Alignment));
3971813fde9SYuta Saito   Offset += Paddings;
3981813fde9SYuta Saito 
3991813fde9SYuta Saito   // LEB128 greater than 5 bytes is invalid
4001813fde9SYuta Saito   assert((StrSizeLength + Paddings) <= 5 && "too long string to align");
4011813fde9SYuta Saito 
4021813fde9SYuta Saito   encodeSLEB128(Str.size(), W->OS, StrSizeLength + Paddings);
4031813fde9SYuta Saito   W->OS << Str;
4041813fde9SYuta Saito 
4051813fde9SYuta Saito   assert(W->OS.tell() == Offset && "invalid padding");
4061813fde9SYuta Saito }
4071813fde9SYuta Saito 
4082322a937SSam Clegg void WasmObjectWriter::startCustomSection(SectionBookkeeping &Section,
4092322a937SSam Clegg                                           StringRef Name) {
410d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "startCustomSection " << Name << "\n");
4112322a937SSam Clegg   startSection(Section, wasm::WASM_SEC_CUSTOM);
4126a31a0d6SSam Clegg 
4136a31a0d6SSam Clegg   // The position where the section header ends, for measuring its size.
4140ff28fa6SDerek Schuff   Section.PayloadOffset = W->OS.tell();
4156a31a0d6SSam Clegg 
4162322a937SSam Clegg   // Custom sections in wasm also have a string identifier.
4171813fde9SYuta Saito   if (Name != "__clangast") {
4182322a937SSam Clegg     writeString(Name);
4191813fde9SYuta Saito   } else {
4201813fde9SYuta Saito     // The on-disk hashtable in clangast needs to be aligned by 4 bytes.
4211813fde9SYuta Saito     writeStringWithAlignment(Name, 4);
4221813fde9SYuta Saito   }
4236a31a0d6SSam Clegg 
4246a31a0d6SSam Clegg   // The position where the custom section starts.
4250ff28fa6SDerek Schuff   Section.ContentsOffset = W->OS.tell();
426d934cb88SDan Gohman }
427d934cb88SDan Gohman 
428d934cb88SDan Gohman // Now that the section is complete and we know how big it is, patch up the
429d934cb88SDan Gohman // section size field at the start of the section.
430d934cb88SDan Gohman void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
4310ff28fa6SDerek Schuff   uint64_t Size = W->OS.tell();
432c0affde8SSam Clegg   // /dev/null doesn't support seek/tell and can report offset of 0.
433c0affde8SSam Clegg   // Simply skip this patching in that case.
434c0affde8SSam Clegg   if (!Size)
435c0affde8SSam Clegg     return;
436c0affde8SSam Clegg 
437c0affde8SSam Clegg   Size -= Section.PayloadOffset;
438d934cb88SDan Gohman   if (uint32_t(Size) != Size)
439d934cb88SDan Gohman     report_fatal_error("section size does not fit in a uint32_t");
440d934cb88SDan Gohman 
441d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "endSection size=" << Size << "\n");
442d934cb88SDan Gohman 
443d934cb88SDan Gohman   // Write the final section size to the payload_len field, which follows
444d934cb88SDan Gohman   // the section id byte.
4454c75521cSSam Clegg   writePatchableU32(static_cast<raw_pwrite_stream &>(W->OS), Size,
446f17b149dSPeter Collingbourne                     Section.SizeOffset);
447d934cb88SDan Gohman }
448d934cb88SDan Gohman 
44918eafb6cSDan Gohman // Emit the Wasm header.
45018eafb6cSDan Gohman void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
4510ff28fa6SDerek Schuff   W->OS.write(wasm::WasmMagic, sizeof(wasm::WasmMagic));
4520ff28fa6SDerek Schuff   W->write<uint32_t>(wasm::WasmVersion);
45318eafb6cSDan Gohman }
45418eafb6cSDan Gohman 
45518eafb6cSDan Gohman void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
45618eafb6cSDan Gohman                                                 const MCAsmLayout &Layout) {
4572632ba6aSAndy Wingo   // Some compilation units require the indirect function table to be present
4582632ba6aSAndy Wingo   // but don't explicitly reference it.  This is the case for call_indirect
4592632ba6aSAndy Wingo   // without the reference-types feature, and also function bitcasts in all
4602632ba6aSAndy Wingo   // cases.  In those cases the __indirect_function_table has the
4612632ba6aSAndy Wingo   // WASM_SYMBOL_NO_STRIP attribute.  Here we make sure this symbol makes it to
4622632ba6aSAndy Wingo   // the assembler, if needed.
4632632ba6aSAndy Wingo   if (auto *Sym = Asm.getContext().lookupSymbol("__indirect_function_table")) {
4642632ba6aSAndy Wingo     const auto *WasmSym = static_cast<const MCSymbolWasm *>(Sym);
4652632ba6aSAndy Wingo     if (WasmSym->isNoStrip())
46696ef4f30SSam Clegg       Asm.registerSymbol(*Sym);
4672632ba6aSAndy Wingo   }
46896ef4f30SSam Clegg 
4696ccb59b3SSam Clegg   // Build a map of sections to the function that defines them, for use
4706ccb59b3SSam Clegg   // in recordRelocation.
4716ccb59b3SSam Clegg   for (const MCSymbol &S : Asm.symbols()) {
4726ccb59b3SSam Clegg     const auto &WS = static_cast<const MCSymbolWasm &>(S);
4736ccb59b3SSam Clegg     if (WS.isDefined() && WS.isFunction() && !WS.isVariable()) {
4746ccb59b3SSam Clegg       const auto &Sec = static_cast<const MCSectionWasm &>(S.getSection());
4756ccb59b3SSam Clegg       auto Pair = SectionFunctions.insert(std::make_pair(&Sec, &S));
4766ccb59b3SSam Clegg       if (!Pair.second)
4776ccb59b3SSam Clegg         report_fatal_error("section already has a defining function: " +
4787d1ff446SFangrui Song                            Sec.getName());
4796ccb59b3SSam Clegg     }
4806ccb59b3SSam Clegg   }
48118eafb6cSDan Gohman }
48218eafb6cSDan Gohman 
48318eafb6cSDan Gohman void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
48418eafb6cSDan Gohman                                         const MCAsmLayout &Layout,
48518eafb6cSDan Gohman                                         const MCFragment *Fragment,
48618eafb6cSDan Gohman                                         const MCFixup &Fixup, MCValue Target,
487ceecfe5bSRafael Espindola                                         uint64_t &FixedValue) {
488ecc5e808SSam Clegg   // The WebAssembly backend should never generate FKF_IsPCRel fixups
489e828ce1bSFangrui Song   assert(!(Asm.getBackend().getFixupKindInfo(Fixup.getKind()).Flags &
490ecc5e808SSam Clegg            MCFixupKindInfo::FKF_IsPCRel));
491ecc5e808SSam Clegg 
492fe6414b0SSam Clegg   const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
493d934cb88SDan Gohman   uint64_t C = Target.getConstant();
494d934cb88SDan Gohman   uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
495d934cb88SDan Gohman   MCContext &Ctx = Asm.getContext();
496aa0c571aSYuta Saito   bool IsLocRel = false;
497d934cb88SDan Gohman 
498d934cb88SDan Gohman   if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
499aa0c571aSYuta Saito 
500ecc5e808SSam Clegg     const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
501aa0c571aSYuta Saito 
502aa0c571aSYuta Saito     if (FixupSection.getKind().isText()) {
503aa0c571aSYuta Saito       Ctx.reportError(Fixup.getLoc(),
504d934cb88SDan Gohman                       Twine("symbol '") + SymB.getName() +
505aa0c571aSYuta Saito                           "' unsupported subtraction expression used in "
506aa0c571aSYuta Saito                           "relocation in code section.");
507d934cb88SDan Gohman       return;
508d934cb88SDan Gohman     }
509d934cb88SDan Gohman 
510aa0c571aSYuta Saito     if (SymB.isUndefined()) {
511aa0c571aSYuta Saito       Ctx.reportError(Fixup.getLoc(),
512aa0c571aSYuta Saito                       Twine("symbol '") + SymB.getName() +
513aa0c571aSYuta Saito                           "' can not be undefined in a subtraction expression");
514aa0c571aSYuta Saito       return;
515aa0c571aSYuta Saito     }
516aa0c571aSYuta Saito     const MCSection &SecB = SymB.getSection();
517aa0c571aSYuta Saito     if (&SecB != &FixupSection) {
518aa0c571aSYuta Saito       Ctx.reportError(Fixup.getLoc(),
519aa0c571aSYuta Saito                       Twine("symbol '") + SymB.getName() +
520aa0c571aSYuta Saito                           "' can not be placed in a different section");
521aa0c571aSYuta Saito       return;
522aa0c571aSYuta Saito     }
523aa0c571aSYuta Saito     IsLocRel = true;
524aa0c571aSYuta Saito     C += FixupOffset - Layout.getSymbolOffset(SymB);
525aa0c571aSYuta Saito   }
526aa0c571aSYuta Saito 
527d934cb88SDan Gohman   // We either rejected the fixup or folded B into C at this point.
528d934cb88SDan Gohman   const MCSymbolRefExpr *RefA = Target.getSymA();
529ecc5e808SSam Clegg   const auto *SymA = cast<MCSymbolWasm>(&RefA->getSymbol());
530d934cb88SDan Gohman 
5313ea1c62cSSam Clegg   // The .init_array isn't translated as data, so don't do relocations in it.
5327d1ff446SFangrui Song   if (FixupSection.getName().startswith(".init_array")) {
5333ea1c62cSSam Clegg     SymA->setUsedInInitArray();
5343ea1c62cSSam Clegg     return;
5353ea1c62cSSam Clegg   }
5363ea1c62cSSam Clegg 
537ecc5e808SSam Clegg   if (SymA->isVariable()) {
538d934cb88SDan Gohman     const MCExpr *Expr = SymA->getVariableValue();
5397ee758d6SSam Clegg     if (const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr))
5406ad8f190SSam Clegg       if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
5416ad8f190SSam Clegg         llvm_unreachable("weakref used in reloc not yet implemented");
542d934cb88SDan Gohman   }
543d934cb88SDan Gohman 
544d934cb88SDan Gohman   // Put any constant offset in an addend. Offsets can be negative, and
545d934cb88SDan Gohman   // LLVM expects wrapping, in contrast to wasm's immediates which can't
546d934cb88SDan Gohman   // be negative and don't wrap.
547d934cb88SDan Gohman   FixedValue = 0;
548d934cb88SDan Gohman 
549ad1f5457SDerek Schuff   unsigned Type =
550ad1f5457SDerek Schuff       TargetObjectWriter->getRelocType(Target, Fixup, FixupSection, IsLocRel);
5519d24fb7fSSam Clegg 
5524d57fbd0SSam Clegg   // Absolute offset within a section or a function.
5534d57fbd0SSam Clegg   // Currently only supported for for metadata sections.
5544d57fbd0SSam Clegg   // See: test/MC/WebAssembly/blockaddress.ll
555ad1f5457SDerek Schuff   if ((Type == wasm::R_WASM_FUNCTION_OFFSET_I32 ||
55616f02431SWouter van Oortmerssen        Type == wasm::R_WASM_FUNCTION_OFFSET_I64 ||
557ad1f5457SDerek Schuff        Type == wasm::R_WASM_SECTION_OFFSET_I32) &&
558ad1f5457SDerek Schuff       SymA->isDefined()) {
559ad1f5457SDerek Schuff     // SymA can be a temp data symbol that represents a function (in which case
560ad1f5457SDerek Schuff     // it needs to be replaced by the section symbol), [XXX and it apparently
561ad1f5457SDerek Schuff     // later gets changed again to a func symbol?] or it can be a real
562ad1f5457SDerek Schuff     // function symbol, in which case it can be left as-is.
563ad1f5457SDerek Schuff 
5644d57fbd0SSam Clegg     if (!FixupSection.getKind().isMetadata())
5654d57fbd0SSam Clegg       report_fatal_error("relocations for function or section offsets are "
5664d57fbd0SSam Clegg                          "only supported in metadata sections");
5674d57fbd0SSam Clegg 
5684d57fbd0SSam Clegg     const MCSymbol *SectionSymbol = nullptr;
5694d57fbd0SSam Clegg     const MCSection &SecA = SymA->getSection();
5705e5b2cb1SWouter van Oortmerssen     if (SecA.getKind().isText()) {
5715e5b2cb1SWouter van Oortmerssen       auto SecSymIt = SectionFunctions.find(&SecA);
5725e5b2cb1SWouter van Oortmerssen       if (SecSymIt == SectionFunctions.end())
5735e5b2cb1SWouter van Oortmerssen         report_fatal_error("section doesn\'t have defining symbol");
5745e5b2cb1SWouter van Oortmerssen       SectionSymbol = SecSymIt->second;
5755e5b2cb1SWouter van Oortmerssen     } else {
5764d57fbd0SSam Clegg       SectionSymbol = SecA.getBeginSymbol();
5775e5b2cb1SWouter van Oortmerssen     }
5784d57fbd0SSam Clegg     if (!SectionSymbol)
5794d57fbd0SSam Clegg       report_fatal_error("section symbol is required for relocation");
5804d57fbd0SSam Clegg 
5814d57fbd0SSam Clegg     C += Layout.getSymbolOffset(*SymA);
5824d57fbd0SSam Clegg     SymA = cast<MCSymbolWasm>(SectionSymbol);
5834d57fbd0SSam Clegg   }
5844d57fbd0SSam Clegg 
585feac819eSAndy Wingo   if (Type == wasm::R_WASM_TABLE_INDEX_REL_SLEB ||
5863a293cbfSWouter van Oortmerssen       Type == wasm::R_WASM_TABLE_INDEX_REL_SLEB64 ||
587feac819eSAndy Wingo       Type == wasm::R_WASM_TABLE_INDEX_SLEB ||
588feac819eSAndy Wingo       Type == wasm::R_WASM_TABLE_INDEX_SLEB64 ||
589feac819eSAndy Wingo       Type == wasm::R_WASM_TABLE_INDEX_I32 ||
590feac819eSAndy Wingo       Type == wasm::R_WASM_TABLE_INDEX_I64) {
591feac819eSAndy Wingo     // TABLE_INDEX relocs implicitly use the default indirect function table.
5922632ba6aSAndy Wingo     // We require the function table to have already been defined.
593feac819eSAndy Wingo     auto TableName = "__indirect_function_table";
594feac819eSAndy Wingo     MCSymbolWasm *Sym = cast_or_null<MCSymbolWasm>(Ctx.lookupSymbol(TableName));
595f23b259eSSam Clegg     if (!Sym) {
596f23b259eSSam Clegg       report_fatal_error("missing indirect function table symbol");
597feac819eSAndy Wingo     } else {
598f23b259eSSam Clegg       if (!Sym->isFunctionTable())
599f23b259eSSam Clegg         report_fatal_error("__indirect_function_table symbol has wrong type");
6002632ba6aSAndy Wingo       // Ensure that __indirect_function_table reaches the output.
6012632ba6aSAndy Wingo       Sym->setNoStrip();
6027dc98adbSAndy Wingo       Asm.registerSymbol(*Sym);
603861dbe1aSAndy Wingo     }
6042632ba6aSAndy Wingo   }
605feac819eSAndy Wingo 
606d1152a26SSam Clegg   // Relocation other than R_WASM_TYPE_INDEX_LEB are required to be
6074d57fbd0SSam Clegg   // against a named symbol.
608d1152a26SSam Clegg   if (Type != wasm::R_WASM_TYPE_INDEX_LEB) {
6094d57fbd0SSam Clegg     if (SymA->getName().empty())
6104d57fbd0SSam Clegg       report_fatal_error("relocations against un-named temporaries are not yet "
6114d57fbd0SSam Clegg                          "supported by wasm");
6124d57fbd0SSam Clegg 
6134d57fbd0SSam Clegg     SymA->setUsedInReloc();
6144d57fbd0SSam Clegg   }
615ae03c1e7SSam Clegg 
616ef8c9135SSam Clegg   switch (RefA->getKind()) {
617ef8c9135SSam Clegg   case MCSymbolRefExpr::VK_GOT:
618ef8c9135SSam Clegg   case MCSymbolRefExpr::VK_WASM_GOT_TLS:
619492f7529SSam Clegg     SymA->setUsedInGOT();
620ef8c9135SSam Clegg     break;
621ef8c9135SSam Clegg   default:
622ef8c9135SSam Clegg     break;
623ef8c9135SSam Clegg   }
624492f7529SSam Clegg 
625d934cb88SDan Gohman   WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
626d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
627d934cb88SDan Gohman 
6286a31a0d6SSam Clegg   if (FixupSection.isWasmData()) {
629d934cb88SDan Gohman     DataRelocations.push_back(Rec);
6306a31a0d6SSam Clegg   } else if (FixupSection.getKind().isText()) {
63112fd3da9SSam Clegg     CodeRelocations.push_back(Rec);
6326a31a0d6SSam Clegg   } else if (FixupSection.getKind().isMetadata()) {
6336a31a0d6SSam Clegg     CustomSectionsRelocations[&FixupSection].push_back(Rec);
6346a31a0d6SSam Clegg   } else {
63512fd3da9SSam Clegg     llvm_unreachable("unexpected section type");
636d934cb88SDan Gohman   }
6376a31a0d6SSam Clegg }
638d934cb88SDan Gohman 
639d934cb88SDan Gohman // Compute a value to write into the code at the location covered
64060ec3034SSam Clegg // by RelEntry. This value isn't used by the static linker; it just serves
64160ec3034SSam Clegg // to make the object format more readable and more likely to be directly
64260ec3034SSam Clegg // useable.
6433b29376eSWouter van Oortmerssen uint64_t
6447ee758d6SSam Clegg WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry,
6457ee758d6SSam Clegg                                       const MCAsmLayout &Layout) {
64648139ebcSWouter van Oortmerssen   if ((RelEntry.Type == wasm::R_WASM_GLOBAL_INDEX_LEB ||
64748139ebcSWouter van Oortmerssen        RelEntry.Type == wasm::R_WASM_GLOBAL_INDEX_I32) &&
64848139ebcSWouter van Oortmerssen       !RelEntry.Symbol->isGlobal()) {
649492f7529SSam Clegg     assert(GOTIndices.count(RelEntry.Symbol) > 0 && "symbol not found in GOT index space");
650492f7529SSam Clegg     return GOTIndices[RelEntry.Symbol];
651492f7529SSam Clegg   }
652492f7529SSam Clegg 
65360ec3034SSam Clegg   switch (RelEntry.Type) {
6542a7cac93SSam Clegg   case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
6553a293cbfSWouter van Oortmerssen   case wasm::R_WASM_TABLE_INDEX_REL_SLEB64:
656d1152a26SSam Clegg   case wasm::R_WASM_TABLE_INDEX_SLEB:
657cc1b9b68SWouter van Oortmerssen   case wasm::R_WASM_TABLE_INDEX_SLEB64:
658cc1b9b68SWouter van Oortmerssen   case wasm::R_WASM_TABLE_INDEX_I32:
659cc1b9b68SWouter van Oortmerssen   case wasm::R_WASM_TABLE_INDEX_I64: {
660f9edbe95SSam Clegg     // Provisional value is table address of the resolved symbol itself
6617ee758d6SSam Clegg     const MCSymbolWasm *Base =
6627ee758d6SSam Clegg         cast<MCSymbolWasm>(Layout.getBaseSymbol(*RelEntry.Symbol));
6637ee758d6SSam Clegg     assert(Base->isFunction());
6643a293cbfSWouter van Oortmerssen     if (RelEntry.Type == wasm::R_WASM_TABLE_INDEX_REL_SLEB ||
6653a293cbfSWouter van Oortmerssen         RelEntry.Type == wasm::R_WASM_TABLE_INDEX_REL_SLEB64)
6667ee758d6SSam Clegg       return TableIndices[Base] - InitialTableOffset;
66781443ac1SSam Clegg     else
6687ee758d6SSam Clegg       return TableIndices[Base];
669f9edbe95SSam Clegg   }
670d1152a26SSam Clegg   case wasm::R_WASM_TYPE_INDEX_LEB:
6716c899ba6SSam Clegg     // Provisional value is same as the index
67260ec3034SSam Clegg     return getRelocationIndexValue(RelEntry);
673d1152a26SSam Clegg   case wasm::R_WASM_FUNCTION_INDEX_LEB:
674d1152a26SSam Clegg   case wasm::R_WASM_GLOBAL_INDEX_LEB:
67548139ebcSWouter van Oortmerssen   case wasm::R_WASM_GLOBAL_INDEX_I32:
6761d891d44SHeejin Ahn   case wasm::R_WASM_TAG_INDEX_LEB:
67769e2797eSPaulo Matos   case wasm::R_WASM_TABLE_NUMBER_LEB:
6781d891d44SHeejin Ahn     // Provisional value is function/global/tag Wasm index
679492f7529SSam Clegg     assert(WasmIndices.count(RelEntry.Symbol) > 0 && "symbol not found in wasm index space");
6806c899ba6SSam Clegg     return WasmIndices[RelEntry.Symbol];
681d1152a26SSam Clegg   case wasm::R_WASM_FUNCTION_OFFSET_I32:
68216f02431SWouter van Oortmerssen   case wasm::R_WASM_FUNCTION_OFFSET_I64:
683d1152a26SSam Clegg   case wasm::R_WASM_SECTION_OFFSET_I32: {
684ad1f5457SDerek Schuff     if (!RelEntry.Symbol->isDefined())
685ad1f5457SDerek Schuff       return 0;
6866a31a0d6SSam Clegg     const auto &Section =
6876a31a0d6SSam Clegg         static_cast<const MCSectionWasm &>(RelEntry.Symbol->getSection());
6886a31a0d6SSam Clegg     return Section.getSectionOffset() + RelEntry.Addend;
6896a31a0d6SSam Clegg   }
690d1152a26SSam Clegg   case wasm::R_WASM_MEMORY_ADDR_LEB:
6913b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_LEB64:
6923b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_SLEB:
6933b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_SLEB64:
6942a7cac93SSam Clegg   case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
6953b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_REL_SLEB64:
6963b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_I32:
697a28a4662SSam Clegg   case wasm::R_WASM_MEMORY_ADDR_I64:
698aa0c571aSYuta Saito   case wasm::R_WASM_MEMORY_ADDR_TLS_SLEB:
699670944fbSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_TLS_SLEB64:
700aa0c571aSYuta Saito   case wasm::R_WASM_MEMORY_ADDR_LOCREL_I32: {
7019c7b5808SDominic Chen     // Provisional value is address of the global plus the offset
702270ed1b3SSam Clegg     // For undefined symbols, use zero
70301a48535SSam Clegg     if (!RelEntry.Symbol->isDefined())
704270ed1b3SSam Clegg       return 0;
70501a48535SSam Clegg     const wasm::WasmDataReference &SymRef = DataLocations[RelEntry.Symbol];
70601a48535SSam Clegg     const WasmDataSegment &Segment = DataSegments[SymRef.Segment];
707d934cb88SDan Gohman     // Ignore overflow. LLVM allows address arithmetic to silently wrap.
70801a48535SSam Clegg     return Segment.Offset + SymRef.Offset + RelEntry.Addend;
70960ec3034SSam Clegg   }
71060ec3034SSam Clegg   default:
71160ec3034SSam Clegg     llvm_unreachable("invalid relocation type");
71260ec3034SSam Clegg   }
713d934cb88SDan Gohman }
714d934cb88SDan Gohman 
715759631c7SSam Clegg static void addData(SmallVectorImpl<char> &DataBytes,
71663ebb813SSam Clegg                     MCSectionWasm &DataSection) {
7177d1ff446SFangrui Song   LLVM_DEBUG(errs() << "addData: " << DataSection.getName() << "\n");
718759631c7SSam Clegg 
71963ebb813SSam Clegg   DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
72063ebb813SSam Clegg 
721759631c7SSam Clegg   for (const MCFragment &Frag : DataSection) {
722759631c7SSam Clegg     if (Frag.hasInstructions())
723759631c7SSam Clegg       report_fatal_error("only data supported in data sections");
724759631c7SSam Clegg 
725759631c7SSam Clegg     if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
726759631c7SSam Clegg       if (Align->getValueSize() != 1)
727759631c7SSam Clegg         report_fatal_error("only byte values supported for alignment");
728759631c7SSam Clegg       // If nops are requested, use zeros, as this is the data section.
729759631c7SSam Clegg       uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
730f208f631SHeejin Ahn       uint64_t Size =
731f208f631SHeejin Ahn           std::min<uint64_t>(alignTo(DataBytes.size(), Align->getAlignment()),
732f208f631SHeejin Ahn                              DataBytes.size() + Align->getMaxBytesToEmit());
733759631c7SSam Clegg       DataBytes.resize(Size, Value);
734759631c7SSam Clegg     } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
735588fad4dSNirav Dave       int64_t NumValues;
736588fad4dSNirav Dave       if (!Fill->getNumValues().evaluateAsAbsolute(NumValues))
737d707c370SRafael Espindola         llvm_unreachable("The fill should be an assembler constant");
738588fad4dSNirav Dave       DataBytes.insert(DataBytes.end(), Fill->getValueSize() * NumValues,
739588fad4dSNirav Dave                        Fill->getValue());
74024faf859SHeejin Ahn     } else if (auto *LEB = dyn_cast<MCLEBFragment>(&Frag)) {
74124faf859SHeejin Ahn       const SmallVectorImpl<char> &Contents = LEB->getContents();
7421d0bc055SKazu Hirata       llvm::append_range(DataBytes, Contents);
743759631c7SSam Clegg     } else {
744759631c7SSam Clegg       const auto &DataFrag = cast<MCDataFragment>(Frag);
745759631c7SSam Clegg       const SmallVectorImpl<char> &Contents = DataFrag.getContents();
7461d0bc055SKazu Hirata       llvm::append_range(DataBytes, Contents);
747759631c7SSam Clegg     }
748759631c7SSam Clegg   }
749759631c7SSam Clegg 
750d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
751759631c7SSam Clegg }
752759631c7SSam Clegg 
75360ec3034SSam Clegg uint32_t
75460ec3034SSam Clegg WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
755d1152a26SSam Clegg   if (RelEntry.Type == wasm::R_WASM_TYPE_INDEX_LEB) {
756b7787fd0SSam Clegg     if (!TypeIndices.count(RelEntry.Symbol))
757b7787fd0SSam Clegg       report_fatal_error("symbol not found in type index space: " +
758b7787fd0SSam Clegg                          RelEntry.Symbol->getName());
759acd7d2b0SSam Clegg     return TypeIndices[RelEntry.Symbol];
760acd7d2b0SSam Clegg   }
76160ec3034SSam Clegg 
76225d8e68bSSam Clegg   return RelEntry.Symbol->getIndex();
763acd7d2b0SSam Clegg }
764acd7d2b0SSam Clegg 
765d934cb88SDan Gohman // Apply the portions of the relocation records that we can handle ourselves
766d934cb88SDan Gohman // directly.
767acd7d2b0SSam Clegg void WasmObjectWriter::applyRelocations(
7687ee758d6SSam Clegg     ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset,
7697ee758d6SSam Clegg     const MCAsmLayout &Layout) {
7700ff28fa6SDerek Schuff   auto &Stream = static_cast<raw_pwrite_stream &>(W->OS);
771d934cb88SDan Gohman   for (const WasmRelocationEntry &RelEntry : Relocations) {
772d934cb88SDan Gohman     uint64_t Offset = ContentsOffset +
773d934cb88SDan Gohman                       RelEntry.FixupSection->getSectionOffset() +
774d934cb88SDan Gohman                       RelEntry.Offset;
775d934cb88SDan Gohman 
776d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
7774c75521cSSam Clegg     uint64_t Value = getProvisionalValue(RelEntry, Layout);
77860ec3034SSam Clegg 
779acd7d2b0SSam Clegg     switch (RelEntry.Type) {
780d1152a26SSam Clegg     case wasm::R_WASM_FUNCTION_INDEX_LEB:
781d1152a26SSam Clegg     case wasm::R_WASM_TYPE_INDEX_LEB:
782d1152a26SSam Clegg     case wasm::R_WASM_GLOBAL_INDEX_LEB:
783d1152a26SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_LEB:
7841d891d44SHeejin Ahn     case wasm::R_WASM_TAG_INDEX_LEB:
78569e2797eSPaulo Matos     case wasm::R_WASM_TABLE_NUMBER_LEB:
7864c75521cSSam Clegg       writePatchableU32(Stream, Value, Offset);
7873b29376eSWouter van Oortmerssen       break;
7883b29376eSWouter van Oortmerssen     case wasm::R_WASM_MEMORY_ADDR_LEB64:
7894c75521cSSam Clegg       writePatchableU64(Stream, Value, Offset);
790d934cb88SDan Gohman       break;
791d1152a26SSam Clegg     case wasm::R_WASM_TABLE_INDEX_I32:
792d1152a26SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_I32:
793d1152a26SSam Clegg     case wasm::R_WASM_FUNCTION_OFFSET_I32:
794d1152a26SSam Clegg     case wasm::R_WASM_SECTION_OFFSET_I32:
79548139ebcSWouter van Oortmerssen     case wasm::R_WASM_GLOBAL_INDEX_I32:
796aa0c571aSYuta Saito     case wasm::R_WASM_MEMORY_ADDR_LOCREL_I32:
7970a6c4d8dSSam Clegg       patchI32(Stream, Value, Offset);
798d934cb88SDan Gohman       break;
799cc1b9b68SWouter van Oortmerssen     case wasm::R_WASM_TABLE_INDEX_I64:
8003b29376eSWouter van Oortmerssen     case wasm::R_WASM_MEMORY_ADDR_I64:
80116f02431SWouter van Oortmerssen     case wasm::R_WASM_FUNCTION_OFFSET_I64:
8023b29376eSWouter van Oortmerssen       patchI64(Stream, Value, Offset);
8033b29376eSWouter van Oortmerssen       break;
804d1152a26SSam Clegg     case wasm::R_WASM_TABLE_INDEX_SLEB:
8052a7cac93SSam Clegg     case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
806d1152a26SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_SLEB:
8072a7cac93SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
808a28a4662SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_TLS_SLEB:
8094c75521cSSam Clegg       writePatchableS32(Stream, Value, Offset);
8103b29376eSWouter van Oortmerssen       break;
811cc1b9b68SWouter van Oortmerssen     case wasm::R_WASM_TABLE_INDEX_SLEB64:
8123a293cbfSWouter van Oortmerssen     case wasm::R_WASM_TABLE_INDEX_REL_SLEB64:
8133b29376eSWouter van Oortmerssen     case wasm::R_WASM_MEMORY_ADDR_SLEB64:
8143b29376eSWouter van Oortmerssen     case wasm::R_WASM_MEMORY_ADDR_REL_SLEB64:
815670944fbSWouter van Oortmerssen     case wasm::R_WASM_MEMORY_ADDR_TLS_SLEB64:
8164c75521cSSam Clegg       writePatchableS64(Stream, Value, Offset);
81760ec3034SSam Clegg       break;
818d934cb88SDan Gohman     default:
8199d24fb7fSSam Clegg       llvm_unreachable("invalid relocation type");
820d934cb88SDan Gohman     }
821d934cb88SDan Gohman   }
82218eafb6cSDan Gohman }
82318eafb6cSDan Gohman 
8244c41fb5aSHeejin Ahn void WasmObjectWriter::writeTypeSection(
8254c41fb5aSHeejin Ahn     ArrayRef<wasm::WasmSignature> Signatures) {
826da419bdbSHeejin Ahn   if (Signatures.empty())
8279e15f359SSam Clegg     return;
8289e15f359SSam Clegg 
8299e15f359SSam Clegg   SectionBookkeeping Section;
8309e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_TYPE);
8319e15f359SSam Clegg 
8320ff28fa6SDerek Schuff   encodeULEB128(Signatures.size(), W->OS);
8339e15f359SSam Clegg 
8344c41fb5aSHeejin Ahn   for (const wasm::WasmSignature &Sig : Signatures) {
8350ff28fa6SDerek Schuff     W->OS << char(wasm::WASM_TYPE_FUNC);
8360ff28fa6SDerek Schuff     encodeULEB128(Sig.Params.size(), W->OS);
837da419bdbSHeejin Ahn     for (wasm::ValType Ty : Sig.Params)
8389e15f359SSam Clegg       writeValueType(Ty);
8390ff28fa6SDerek Schuff     encodeULEB128(Sig.Returns.size(), W->OS);
840da419bdbSHeejin Ahn     for (wasm::ValType Ty : Sig.Returns)
8419e15f359SSam Clegg       writeValueType(Ty);
8429e15f359SSam Clegg   }
8439e15f359SSam Clegg 
8449e15f359SSam Clegg   endSection(Section);
8459e15f359SSam Clegg }
8469e15f359SSam Clegg 
8478defa952SSam Clegg void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports,
8484d135b04SWouter van Oortmerssen                                           uint64_t DataSize,
849f950b24aSSam Clegg                                           uint32_t NumElements) {
8509e15f359SSam Clegg   if (Imports.empty())
8519e15f359SSam Clegg     return;
8529e15f359SSam Clegg 
8534d135b04SWouter van Oortmerssen   uint64_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
854f950b24aSSam Clegg 
8559e15f359SSam Clegg   SectionBookkeeping Section;
8569e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_IMPORT);
8579e15f359SSam Clegg 
8580ff28fa6SDerek Schuff   encodeULEB128(Imports.size(), W->OS);
8598defa952SSam Clegg   for (const wasm::WasmImport &Import : Imports) {
8608defa952SSam Clegg     writeString(Import.Module);
8618defa952SSam Clegg     writeString(Import.Field);
8620ff28fa6SDerek Schuff     W->OS << char(Import.Kind);
8639e15f359SSam Clegg 
8649e15f359SSam Clegg     switch (Import.Kind) {
8659e15f359SSam Clegg     case wasm::WASM_EXTERNAL_FUNCTION:
8660ff28fa6SDerek Schuff       encodeULEB128(Import.SigIndex, W->OS);
8679e15f359SSam Clegg       break;
8689e15f359SSam Clegg     case wasm::WASM_EXTERNAL_GLOBAL:
8690ff28fa6SDerek Schuff       W->OS << char(Import.Global.Type);
8700ff28fa6SDerek Schuff       W->OS << char(Import.Global.Mutable ? 1 : 0);
8719e15f359SSam Clegg       break;
872f950b24aSSam Clegg     case wasm::WASM_EXTERNAL_MEMORY:
8730ff28fa6SDerek Schuff       encodeULEB128(Import.Memory.Flags, W->OS);
8740ff28fa6SDerek Schuff       encodeULEB128(NumPages, W->OS); // initial
875f950b24aSSam Clegg       break;
876f950b24aSSam Clegg     case wasm::WASM_EXTERNAL_TABLE:
8770ff28fa6SDerek Schuff       W->OS << char(Import.Table.ElemType);
8780ff28fa6SDerek Schuff       encodeULEB128(0, W->OS);           // flags
8790ff28fa6SDerek Schuff       encodeULEB128(NumElements, W->OS); // initial
880f950b24aSSam Clegg       break;
8811d891d44SHeejin Ahn     case wasm::WASM_EXTERNAL_TAG:
8823ec1760dSHeejin Ahn       W->OS << char(0); // Reserved 'attribute' field
8833ec1760dSHeejin Ahn       encodeULEB128(Import.SigIndex, W->OS);
884da419bdbSHeejin Ahn       break;
8859e15f359SSam Clegg     default:
8869e15f359SSam Clegg       llvm_unreachable("unsupported import kind");
8879e15f359SSam Clegg     }
8889e15f359SSam Clegg   }
8899e15f359SSam Clegg 
8909e15f359SSam Clegg   endSection(Section);
8919e15f359SSam Clegg }
8929e15f359SSam Clegg 
893457fb0b4SSam Clegg void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
8949e15f359SSam Clegg   if (Functions.empty())
8959e15f359SSam Clegg     return;
8969e15f359SSam Clegg 
8979e15f359SSam Clegg   SectionBookkeeping Section;
8989e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_FUNCTION);
8999e15f359SSam Clegg 
9000ff28fa6SDerek Schuff   encodeULEB128(Functions.size(), W->OS);
9019e15f359SSam Clegg   for (const WasmFunction &Func : Functions)
9020ff28fa6SDerek Schuff     encodeULEB128(Func.SigIndex, W->OS);
9039e15f359SSam Clegg 
9049e15f359SSam Clegg   endSection(Section);
9059e15f359SSam Clegg }
9069e15f359SSam Clegg 
9073ec1760dSHeejin Ahn void WasmObjectWriter::writeTagSection(ArrayRef<uint32_t> TagTypes) {
9083ec1760dSHeejin Ahn   if (TagTypes.empty())
909da419bdbSHeejin Ahn     return;
910da419bdbSHeejin Ahn 
911da419bdbSHeejin Ahn   SectionBookkeeping Section;
9121d891d44SHeejin Ahn   startSection(Section, wasm::WASM_SEC_TAG);
913da419bdbSHeejin Ahn 
9143ec1760dSHeejin Ahn   encodeULEB128(TagTypes.size(), W->OS);
9153ec1760dSHeejin Ahn   for (uint32_t Index : TagTypes) {
9163ec1760dSHeejin Ahn     W->OS << char(0); // Reserved 'attribute' field
9173ec1760dSHeejin Ahn     encodeULEB128(Index, W->OS);
918da419bdbSHeejin Ahn   }
919da419bdbSHeejin Ahn 
920da419bdbSHeejin Ahn   endSection(Section);
921da419bdbSHeejin Ahn }
922da419bdbSHeejin Ahn 
9230a6c4d8dSSam Clegg void WasmObjectWriter::writeGlobalSection(ArrayRef<wasm::WasmGlobal> Globals) {
9240a6c4d8dSSam Clegg   if (Globals.empty())
9250a6c4d8dSSam Clegg     return;
9260a6c4d8dSSam Clegg 
9270a6c4d8dSSam Clegg   SectionBookkeeping Section;
9280a6c4d8dSSam Clegg   startSection(Section, wasm::WASM_SEC_GLOBAL);
9290a6c4d8dSSam Clegg 
9300ff28fa6SDerek Schuff   encodeULEB128(Globals.size(), W->OS);
9310a6c4d8dSSam Clegg   for (const wasm::WasmGlobal &Global : Globals) {
9320ff28fa6SDerek Schuff     encodeULEB128(Global.Type.Type, W->OS);
9330ff28fa6SDerek Schuff     W->OS << char(Global.Type.Mutable);
9349504ab32SSam Clegg     if (Global.InitExpr.Extended) {
9359504ab32SSam Clegg       llvm_unreachable("extected init expressions not supported");
9369504ab32SSam Clegg     } else {
9379504ab32SSam Clegg       W->OS << char(Global.InitExpr.Inst.Opcode);
9380a6c4d8dSSam Clegg       switch (Global.Type.Type) {
9390a6c4d8dSSam Clegg       case wasm::WASM_TYPE_I32:
9400ff28fa6SDerek Schuff         encodeSLEB128(0, W->OS);
9410a6c4d8dSSam Clegg         break;
9420a6c4d8dSSam Clegg       case wasm::WASM_TYPE_I64:
9430ff28fa6SDerek Schuff         encodeSLEB128(0, W->OS);
9440a6c4d8dSSam Clegg         break;
9450a6c4d8dSSam Clegg       case wasm::WASM_TYPE_F32:
9460a6c4d8dSSam Clegg         writeI32(0);
9470a6c4d8dSSam Clegg         break;
9480a6c4d8dSSam Clegg       case wasm::WASM_TYPE_F64:
9490a6c4d8dSSam Clegg         writeI64(0);
9500a6c4d8dSSam Clegg         break;
95179aad89dSSam Clegg       case wasm::WASM_TYPE_EXTERNREF:
95279aad89dSSam Clegg         writeValueType(wasm::ValType::EXTERNREF);
95379aad89dSSam Clegg         break;
9540a6c4d8dSSam Clegg       default:
9550a6c4d8dSSam Clegg         llvm_unreachable("unexpected type");
9560a6c4d8dSSam Clegg       }
9579504ab32SSam Clegg     }
9580ff28fa6SDerek Schuff     W->OS << char(wasm::WASM_OPCODE_END);
9590a6c4d8dSSam Clegg   }
9600a6c4d8dSSam Clegg 
9610a6c4d8dSSam Clegg   endSection(Section);
9620a6c4d8dSSam Clegg }
9630a6c4d8dSSam Clegg 
964388fb67bSPaulo Matos void WasmObjectWriter::writeTableSection(ArrayRef<wasm::WasmTable> Tables) {
965388fb67bSPaulo Matos   if (Tables.empty())
966388fb67bSPaulo Matos     return;
967388fb67bSPaulo Matos 
968388fb67bSPaulo Matos   SectionBookkeeping Section;
969388fb67bSPaulo Matos   startSection(Section, wasm::WASM_SEC_TABLE);
970388fb67bSPaulo Matos 
971388fb67bSPaulo Matos   encodeULEB128(Tables.size(), W->OS);
972388fb67bSPaulo Matos   for (const wasm::WasmTable &Table : Tables) {
9731933c9d4SAndy Wingo     encodeULEB128(Table.Type.ElemType, W->OS);
9741933c9d4SAndy Wingo     encodeULEB128(Table.Type.Limits.Flags, W->OS);
9759ac5620cSAndy Wingo     encodeULEB128(Table.Type.Limits.Minimum, W->OS);
9761933c9d4SAndy Wingo     if (Table.Type.Limits.Flags & wasm::WASM_LIMITS_FLAG_HAS_MAX)
9771933c9d4SAndy Wingo       encodeULEB128(Table.Type.Limits.Maximum, W->OS);
978388fb67bSPaulo Matos   }
979388fb67bSPaulo Matos   endSection(Section);
980388fb67bSPaulo Matos }
981388fb67bSPaulo Matos 
9828defa952SSam Clegg void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) {
9839e15f359SSam Clegg   if (Exports.empty())
9849e15f359SSam Clegg     return;
9859e15f359SSam Clegg 
9869e15f359SSam Clegg   SectionBookkeeping Section;
9879e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_EXPORT);
9889e15f359SSam Clegg 
9890ff28fa6SDerek Schuff   encodeULEB128(Exports.size(), W->OS);
9908defa952SSam Clegg   for (const wasm::WasmExport &Export : Exports) {
9918defa952SSam Clegg     writeString(Export.Name);
9920ff28fa6SDerek Schuff     W->OS << char(Export.Kind);
9930ff28fa6SDerek Schuff     encodeULEB128(Export.Index, W->OS);
9949e15f359SSam Clegg   }
9959e15f359SSam Clegg 
9969e15f359SSam Clegg   endSection(Section);
9979e15f359SSam Clegg }
9989e15f359SSam Clegg 
999a5a3659dSAndy Wingo void WasmObjectWriter::writeElemSection(
1000a5a3659dSAndy Wingo     const MCSymbolWasm *IndirectFunctionTable, ArrayRef<uint32_t> TableElems) {
10019e15f359SSam Clegg   if (TableElems.empty())
10029e15f359SSam Clegg     return;
10039e15f359SSam Clegg 
1004a5a3659dSAndy Wingo   assert(IndirectFunctionTable);
1005a5a3659dSAndy Wingo 
10069e15f359SSam Clegg   SectionBookkeeping Section;
10079e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_ELEM);
10089e15f359SSam Clegg 
10090ff28fa6SDerek Schuff   encodeULEB128(1, W->OS); // number of "segments"
1010a5a3659dSAndy Wingo 
1011a5a3659dSAndy Wingo   assert(WasmIndices.count(IndirectFunctionTable));
1012a5a3659dSAndy Wingo   uint32_t TableNumber = WasmIndices.find(IndirectFunctionTable)->second;
1013a5a3659dSAndy Wingo   uint32_t Flags = 0;
1014a5a3659dSAndy Wingo   if (TableNumber)
1015a5a3659dSAndy Wingo     Flags |= wasm::WASM_ELEM_SEGMENT_HAS_TABLE_NUMBER;
1016a5a3659dSAndy Wingo   encodeULEB128(Flags, W->OS);
1017a5a3659dSAndy Wingo   if (Flags & wasm::WASM_ELEM_SEGMENT_HAS_TABLE_NUMBER)
1018a5a3659dSAndy Wingo     encodeULEB128(TableNumber, W->OS); // the table number
10199e15f359SSam Clegg 
10209e15f359SSam Clegg   // init expr for starting offset
10210ff28fa6SDerek Schuff   W->OS << char(wasm::WASM_OPCODE_I32_CONST);
10220ff28fa6SDerek Schuff   encodeSLEB128(InitialTableOffset, W->OS);
10230ff28fa6SDerek Schuff   W->OS << char(wasm::WASM_OPCODE_END);
10249e15f359SSam Clegg 
1025a5a3659dSAndy Wingo   if (Flags & wasm::WASM_ELEM_SEGMENT_MASK_HAS_ELEM_KIND) {
1026a5a3659dSAndy Wingo     // We only write active function table initializers, for which the elem kind
1027a5a3659dSAndy Wingo     // is specified to be written as 0x00 and interpreted to mean "funcref".
1028a5a3659dSAndy Wingo     const uint8_t ElemKind = 0;
1029a5a3659dSAndy Wingo     W->OS << ElemKind;
1030a5a3659dSAndy Wingo   }
1031a5a3659dSAndy Wingo 
10320ff28fa6SDerek Schuff   encodeULEB128(TableElems.size(), W->OS);
10339e15f359SSam Clegg   for (uint32_t Elem : TableElems)
10340ff28fa6SDerek Schuff     encodeULEB128(Elem, W->OS);
10359e15f359SSam Clegg 
10369e15f359SSam Clegg   endSection(Section);
10379e15f359SSam Clegg }
10389e15f359SSam Clegg 
1039fef8de66SThomas Lively void WasmObjectWriter::writeDataCountSection() {
1040fef8de66SThomas Lively   if (DataSegments.empty())
1041fef8de66SThomas Lively     return;
1042fef8de66SThomas Lively 
1043fef8de66SThomas Lively   SectionBookkeeping Section;
1044fef8de66SThomas Lively   startSection(Section, wasm::WASM_SEC_DATACOUNT);
10450ff28fa6SDerek Schuff   encodeULEB128(DataSegments.size(), W->OS);
1046fef8de66SThomas Lively   endSection(Section);
1047fef8de66SThomas Lively }
1048fef8de66SThomas Lively 
1049e49584a3SSam Clegg uint32_t WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
1050457fb0b4SSam Clegg                                             const MCAsmLayout &Layout,
1051457fb0b4SSam Clegg                                             ArrayRef<WasmFunction> Functions) {
10529e15f359SSam Clegg   if (Functions.empty())
1053e49584a3SSam Clegg     return 0;
10549e15f359SSam Clegg 
10559e15f359SSam Clegg   SectionBookkeeping Section;
10569e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_CODE);
10579e15f359SSam Clegg 
10580ff28fa6SDerek Schuff   encodeULEB128(Functions.size(), W->OS);
10599e15f359SSam Clegg 
10609e15f359SSam Clegg   for (const WasmFunction &Func : Functions) {
1061fe6414b0SSam Clegg     auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
10629e15f359SSam Clegg 
10639e15f359SSam Clegg     int64_t Size = 0;
10649e15f359SSam Clegg     if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
10659e15f359SSam Clegg       report_fatal_error(".size expression must be evaluatable");
10669e15f359SSam Clegg 
10670ff28fa6SDerek Schuff     encodeULEB128(Size, W->OS);
10680ff28fa6SDerek Schuff     FuncSection.setSectionOffset(W->OS.tell() - Section.ContentsOffset);
10690ff28fa6SDerek Schuff     Asm.writeSectionData(W->OS, &FuncSection, Layout);
10709e15f359SSam Clegg   }
10719e15f359SSam Clegg 
10729e15f359SSam Clegg   // Apply fixups.
10737ee758d6SSam Clegg   applyRelocations(CodeRelocations, Section.ContentsOffset, Layout);
10749e15f359SSam Clegg 
10759e15f359SSam Clegg   endSection(Section);
1076e49584a3SSam Clegg   return Section.Index;
10779e15f359SSam Clegg }
10789e15f359SSam Clegg 
1079e49584a3SSam Clegg uint32_t WasmObjectWriter::writeDataSection(const MCAsmLayout &Layout) {
10806c899ba6SSam Clegg   if (DataSegments.empty())
1081e49584a3SSam Clegg     return 0;
10829e15f359SSam Clegg 
10839e15f359SSam Clegg   SectionBookkeeping Section;
10849e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_DATA);
10859e15f359SSam Clegg 
10860ff28fa6SDerek Schuff   encodeULEB128(DataSegments.size(), W->OS); // count
10877c395943SSam Clegg 
10886c899ba6SSam Clegg   for (const WasmDataSegment &Segment : DataSegments) {
10890ff28fa6SDerek Schuff     encodeULEB128(Segment.InitFlags, W->OS); // flags
1090831a143eSAndy Wingo     if (Segment.InitFlags & wasm::WASM_DATA_SEGMENT_HAS_MEMINDEX)
10910ff28fa6SDerek Schuff       encodeULEB128(0, W->OS); // memory index
1092831a143eSAndy Wingo     if ((Segment.InitFlags & wasm::WASM_DATA_SEGMENT_IS_PASSIVE) == 0) {
10930d9b17d0SWouter van Oortmerssen       W->OS << char(is64Bit() ? wasm::WASM_OPCODE_I64_CONST
10944d135b04SWouter van Oortmerssen                               : wasm::WASM_OPCODE_I32_CONST);
10950ff28fa6SDerek Schuff       encodeSLEB128(Segment.Offset, W->OS); // offset
10960ff28fa6SDerek Schuff       W->OS << char(wasm::WASM_OPCODE_END);
10972e150409SThomas Lively     }
10980ff28fa6SDerek Schuff     encodeULEB128(Segment.Data.size(), W->OS); // size
10990ff28fa6SDerek Schuff     Segment.Section->setSectionOffset(W->OS.tell() - Section.ContentsOffset);
11000ff28fa6SDerek Schuff     W->OS << Segment.Data; // data
11017c395943SSam Clegg   }
11029e15f359SSam Clegg 
11039e15f359SSam Clegg   // Apply fixups.
11047ee758d6SSam Clegg   applyRelocations(DataRelocations, Section.ContentsOffset, Layout);
11059e15f359SSam Clegg 
11069e15f359SSam Clegg   endSection(Section);
1107e49584a3SSam Clegg   return Section.Index;
11089e15f359SSam Clegg }
11099e15f359SSam Clegg 
11106f08c84aSSam Clegg void WasmObjectWriter::writeRelocSection(
11116f08c84aSSam Clegg     uint32_t SectionIndex, StringRef Name,
1112f77dc2a8SSam Clegg     std::vector<WasmRelocationEntry> &Relocs) {
1113c71fbdd8SQuinn Pham   // See: https://github.com/WebAssembly/tool-conventions/blob/main/Linking.md
11149e15f359SSam Clegg   // for descriptions of the reloc sections.
11159e15f359SSam Clegg 
1116f77dc2a8SSam Clegg   if (Relocs.empty())
11179e15f359SSam Clegg     return;
11189e15f359SSam Clegg 
1119f77dc2a8SSam Clegg   // First, ensure the relocations are sorted in offset order.  In general they
1120f77dc2a8SSam Clegg   // should already be sorted since `recordRelocation` is called in offset
1121f77dc2a8SSam Clegg   // order, but for the code section we combine many MC sections into single
1122f77dc2a8SSam Clegg   // wasm section, and this order is determined by the order of Asm.Symbols()
1123f77dc2a8SSam Clegg   // not the sections order.
1124efd94c56SFangrui Song   llvm::stable_sort(
1125efd94c56SFangrui Song       Relocs, [](const WasmRelocationEntry &A, const WasmRelocationEntry &B) {
1126f77dc2a8SSam Clegg         return (A.Offset + A.FixupSection->getSectionOffset()) <
1127f77dc2a8SSam Clegg                (B.Offset + B.FixupSection->getSectionOffset());
1128f77dc2a8SSam Clegg       });
1129f77dc2a8SSam Clegg 
11309e15f359SSam Clegg   SectionBookkeeping Section;
11316f08c84aSSam Clegg   startCustomSection(Section, std::string("reloc.") + Name.str());
11329e15f359SSam Clegg 
11330ff28fa6SDerek Schuff   encodeULEB128(SectionIndex, W->OS);
11340ff28fa6SDerek Schuff   encodeULEB128(Relocs.size(), W->OS);
1135f77dc2a8SSam Clegg   for (const WasmRelocationEntry &RelEntry : Relocs) {
1136f208f631SHeejin Ahn     uint64_t Offset =
1137f208f631SHeejin Ahn         RelEntry.Offset + RelEntry.FixupSection->getSectionOffset();
11386f08c84aSSam Clegg     uint32_t Index = getRelocationIndexValue(RelEntry);
11399e15f359SSam Clegg 
11400ff28fa6SDerek Schuff     W->OS << char(RelEntry.Type);
11410ff28fa6SDerek Schuff     encodeULEB128(Offset, W->OS);
11420ff28fa6SDerek Schuff     encodeULEB128(Index, W->OS);
11436f08c84aSSam Clegg     if (RelEntry.hasAddend())
11440ff28fa6SDerek Schuff       encodeSLEB128(RelEntry.Addend, W->OS);
11459e15f359SSam Clegg   }
11469e15f359SSam Clegg 
11479e15f359SSam Clegg   endSection(Section);
11489e15f359SSam Clegg }
11499e15f359SSam Clegg 
11506a31a0d6SSam Clegg void WasmObjectWriter::writeCustomRelocSections() {
11516a31a0d6SSam Clegg   for (const auto &Sec : CustomSections) {
11526a31a0d6SSam Clegg     auto &Relocations = CustomSectionsRelocations[Sec.Section];
11536a31a0d6SSam Clegg     writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations);
11546a31a0d6SSam Clegg   }
11556a31a0d6SSam Clegg }
11566a31a0d6SSam Clegg 
11579e15f359SSam Clegg void WasmObjectWriter::writeLinkingMetaDataSection(
115886b4a09aSSam Clegg     ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
1159ea7caceeSSam Clegg     ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
1160ea7caceeSSam Clegg     const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) {
11619e15f359SSam Clegg   SectionBookkeeping Section;
11622322a937SSam Clegg   startCustomSection(Section, "linking");
11630ff28fa6SDerek Schuff   encodeULEB128(wasm::WasmMetadataVersion, W->OS);
11649e15f359SSam Clegg 
11656bb5a41fSSam Clegg   SectionBookkeeping SubSection;
11666c899ba6SSam Clegg   if (SymbolInfos.size() != 0) {
11676c899ba6SSam Clegg     startSection(SubSection, wasm::WASM_SYMBOL_TABLE);
11680ff28fa6SDerek Schuff     encodeULEB128(SymbolInfos.size(), W->OS);
11696c899ba6SSam Clegg     for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) {
11700ff28fa6SDerek Schuff       encodeULEB128(Sym.Kind, W->OS);
11710ff28fa6SDerek Schuff       encodeULEB128(Sym.Flags, W->OS);
11726c899ba6SSam Clegg       switch (Sym.Kind) {
11736c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_FUNCTION:
11746c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_GLOBAL:
11751d891d44SHeejin Ahn       case wasm::WASM_SYMBOL_TYPE_TAG:
1176388fb67bSPaulo Matos       case wasm::WASM_SYMBOL_TYPE_TABLE:
11770ff28fa6SDerek Schuff         encodeULEB128(Sym.ElementIndex, W->OS);
117829874ceaSDan Gohman         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0 ||
117929874ceaSDan Gohman             (Sym.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0)
11806c899ba6SSam Clegg           writeString(Sym.Name);
11816c899ba6SSam Clegg         break;
11826c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_DATA:
11836c899ba6SSam Clegg         writeString(Sym.Name);
11846c899ba6SSam Clegg         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) {
11850ff28fa6SDerek Schuff           encodeULEB128(Sym.DataRef.Segment, W->OS);
11860ff28fa6SDerek Schuff           encodeULEB128(Sym.DataRef.Offset, W->OS);
11870ff28fa6SDerek Schuff           encodeULEB128(Sym.DataRef.Size, W->OS);
11886c899ba6SSam Clegg         }
11896c899ba6SSam Clegg         break;
11906a31a0d6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_SECTION: {
11916a31a0d6SSam Clegg         const uint32_t SectionIndex =
11926a31a0d6SSam Clegg             CustomSections[Sym.ElementIndex].OutputIndex;
11930ff28fa6SDerek Schuff         encodeULEB128(SectionIndex, W->OS);
11946a31a0d6SSam Clegg         break;
11956a31a0d6SSam Clegg       }
11966c899ba6SSam Clegg       default:
11976c899ba6SSam Clegg         llvm_unreachable("unexpected kind");
11986c899ba6SSam Clegg       }
1199b7787fd0SSam Clegg     }
1200b7787fd0SSam Clegg     endSection(SubSection);
1201b7787fd0SSam Clegg   }
12029e15f359SSam Clegg 
12036c899ba6SSam Clegg   if (DataSegments.size()) {
120463ebb813SSam Clegg     startSection(SubSection, wasm::WASM_SEGMENT_INFO);
12050ff28fa6SDerek Schuff     encodeULEB128(DataSegments.size(), W->OS);
12066c899ba6SSam Clegg     for (const WasmDataSegment &Segment : DataSegments) {
1207d95ed959SSam Clegg       writeString(Segment.Name);
12080ff28fa6SDerek Schuff       encodeULEB128(Segment.Alignment, W->OS);
12093b8d2be5SSam Clegg       encodeULEB128(Segment.LinkingFlags, W->OS);
121063ebb813SSam Clegg     }
1211d95ed959SSam Clegg     endSection(SubSection);
1212d95ed959SSam Clegg   }
1213d95ed959SSam Clegg 
1214bafe6902SSam Clegg   if (!InitFuncs.empty()) {
1215bafe6902SSam Clegg     startSection(SubSection, wasm::WASM_INIT_FUNCS);
12160ff28fa6SDerek Schuff     encodeULEB128(InitFuncs.size(), W->OS);
1217bafe6902SSam Clegg     for (auto &StartFunc : InitFuncs) {
12180ff28fa6SDerek Schuff       encodeULEB128(StartFunc.first, W->OS);  // priority
12190ff28fa6SDerek Schuff       encodeULEB128(StartFunc.second, W->OS); // function index
1220bafe6902SSam Clegg     }
1221bafe6902SSam Clegg     endSection(SubSection);
1222bafe6902SSam Clegg   }
1223bafe6902SSam Clegg 
1224ea7caceeSSam Clegg   if (Comdats.size()) {
1225ea7caceeSSam Clegg     startSection(SubSection, wasm::WASM_COMDAT_INFO);
12260ff28fa6SDerek Schuff     encodeULEB128(Comdats.size(), W->OS);
1227ea7caceeSSam Clegg     for (const auto &C : Comdats) {
1228ea7caceeSSam Clegg       writeString(C.first);
12290ff28fa6SDerek Schuff       encodeULEB128(0, W->OS); // flags for future use
12300ff28fa6SDerek Schuff       encodeULEB128(C.second.size(), W->OS);
1231ea7caceeSSam Clegg       for (const WasmComdatEntry &Entry : C.second) {
12320ff28fa6SDerek Schuff         encodeULEB128(Entry.Kind, W->OS);
12330ff28fa6SDerek Schuff         encodeULEB128(Entry.Index, W->OS);
1234ea7caceeSSam Clegg       }
1235ea7caceeSSam Clegg     }
1236ea7caceeSSam Clegg     endSection(SubSection);
1237ea7caceeSSam Clegg   }
1238ea7caceeSSam Clegg 
12399e15f359SSam Clegg   endSection(Section);
12409e15f359SSam Clegg }
12419e15f359SSam Clegg 
1242cbda16ebSThomas Lively void WasmObjectWriter::writeCustomSection(WasmCustomSection &CustomSection,
1243cbda16ebSThomas Lively                                           const MCAssembler &Asm,
12446a31a0d6SSam Clegg                                           const MCAsmLayout &Layout) {
1245cfd44a2eSSam Clegg   SectionBookkeeping Section;
12466a31a0d6SSam Clegg   auto *Sec = CustomSection.Section;
12472322a937SSam Clegg   startCustomSection(Section, CustomSection.Name);
12486a31a0d6SSam Clegg 
12490ff28fa6SDerek Schuff   Sec->setSectionOffset(W->OS.tell() - Section.ContentsOffset);
12500ff28fa6SDerek Schuff   Asm.writeSectionData(W->OS, Sec, Layout);
12516a31a0d6SSam Clegg 
12526a31a0d6SSam Clegg   CustomSection.OutputContentsOffset = Section.ContentsOffset;
12536a31a0d6SSam Clegg   CustomSection.OutputIndex = Section.Index;
12546a31a0d6SSam Clegg 
1255cfd44a2eSSam Clegg   endSection(Section);
12566a31a0d6SSam Clegg 
12576a31a0d6SSam Clegg   // Apply fixups.
12584d57fbd0SSam Clegg   auto &Relocations = CustomSectionsRelocations[CustomSection.Section];
12597ee758d6SSam Clegg   applyRelocations(Relocations, CustomSection.OutputContentsOffset, Layout);
12606a31a0d6SSam Clegg }
12616a31a0d6SSam Clegg 
12625e3d33a7SSam Clegg uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm &Symbol) {
12635e3d33a7SSam Clegg   assert(Symbol.isFunction());
12645e3d33a7SSam Clegg   assert(TypeIndices.count(&Symbol));
12655e3d33a7SSam Clegg   return TypeIndices[&Symbol];
12665e3d33a7SSam Clegg }
12675e3d33a7SSam Clegg 
12681d891d44SHeejin Ahn uint32_t WasmObjectWriter::getTagType(const MCSymbolWasm &Symbol) {
12691d891d44SHeejin Ahn   assert(Symbol.isTag());
1270da419bdbSHeejin Ahn   assert(TypeIndices.count(&Symbol));
1271da419bdbSHeejin Ahn   return TypeIndices[&Symbol];
1272da419bdbSHeejin Ahn }
1273da419bdbSHeejin Ahn 
127438b12f5eSHeejin Ahn void WasmObjectWriter::registerFunctionType(const MCSymbolWasm &Symbol) {
12755e3d33a7SSam Clegg   assert(Symbol.isFunction());
12765e3d33a7SSam Clegg 
12774c41fb5aSHeejin Ahn   wasm::WasmSignature S;
12787ee758d6SSam Clegg 
12797ee758d6SSam Clegg   if (auto *Sig = Symbol.getSignature()) {
1280da419bdbSHeejin Ahn     S.Returns = Sig->Returns;
1281da419bdbSHeejin Ahn     S.Params = Sig->Params;
128277a7a380SDerek Schuff   }
12835e3d33a7SSam Clegg 
1284da419bdbSHeejin Ahn   auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
12855e3d33a7SSam Clegg   if (Pair.second)
1286da419bdbSHeejin Ahn     Signatures.push_back(S);
12875e3d33a7SSam Clegg   TypeIndices[&Symbol] = Pair.first->second;
12885e3d33a7SSam Clegg 
1289d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "registerFunctionType: " << Symbol
1290d34e60caSNicola Zaghen                     << " new:" << Pair.second << "\n");
1291d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
12925e3d33a7SSam Clegg }
12935e3d33a7SSam Clegg 
12941d891d44SHeejin Ahn void WasmObjectWriter::registerTagType(const MCSymbolWasm &Symbol) {
12951d891d44SHeejin Ahn   assert(Symbol.isTag());
1296da419bdbSHeejin Ahn 
1297da419bdbSHeejin Ahn   // TODO Currently we don't generate imported exceptions, but if we do, we
1298da419bdbSHeejin Ahn   // should have a way of infering types of imported exceptions.
12994c41fb5aSHeejin Ahn   wasm::WasmSignature S;
1300da419bdbSHeejin Ahn   if (auto *Sig = Symbol.getSignature()) {
1301da419bdbSHeejin Ahn     S.Returns = Sig->Returns;
1302da419bdbSHeejin Ahn     S.Params = Sig->Params;
1303da419bdbSHeejin Ahn   }
1304da419bdbSHeejin Ahn 
1305da419bdbSHeejin Ahn   auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
1306da419bdbSHeejin Ahn   if (Pair.second)
1307da419bdbSHeejin Ahn     Signatures.push_back(S);
1308da419bdbSHeejin Ahn   TypeIndices[&Symbol] = Pair.first->second;
1309da419bdbSHeejin Ahn 
13101d891d44SHeejin Ahn   LLVM_DEBUG(dbgs() << "registerTagType: " << Symbol << " new:" << Pair.second
1311da419bdbSHeejin Ahn                     << "\n");
1312da419bdbSHeejin Ahn   LLVM_DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
1313da419bdbSHeejin Ahn }
1314da419bdbSHeejin Ahn 
13154d57fbd0SSam Clegg static bool isInSymtab(const MCSymbolWasm &Sym) {
13163ea1c62cSSam Clegg   if (Sym.isUsedInReloc() || Sym.isUsedInInitArray())
13174d57fbd0SSam Clegg     return true;
13184d57fbd0SSam Clegg 
13194d57fbd0SSam Clegg   if (Sym.isComdat() && !Sym.isDefined())
13204d57fbd0SSam Clegg     return false;
13214d57fbd0SSam Clegg 
13223ea1c62cSSam Clegg   if (Sym.isTemporary())
13234d57fbd0SSam Clegg     return false;
13244d57fbd0SSam Clegg 
13254d57fbd0SSam Clegg   if (Sym.isSection())
13264d57fbd0SSam Clegg     return false;
13274d57fbd0SSam Clegg 
13282632ba6aSAndy Wingo   if (Sym.omitFromLinkingSection())
13292632ba6aSAndy Wingo     return false;
13302632ba6aSAndy Wingo 
13314d57fbd0SSam Clegg   return true;
13324d57fbd0SSam Clegg }
133330d314aaSSam Clegg 
13340ff28fa6SDerek Schuff void WasmObjectWriter::prepareImports(
13350ff28fa6SDerek Schuff     SmallVectorImpl<wasm::WasmImport> &Imports, MCAssembler &Asm,
133618eafb6cSDan Gohman     const MCAsmLayout &Layout) {
1337f950b24aSSam Clegg   // For now, always emit the memory import, since loads and stores are not
1338f950b24aSSam Clegg   // valid without it. In the future, we could perhaps be more clever and omit
1339f950b24aSSam Clegg   // it if there are no loads or stores.
13408defa952SSam Clegg   wasm::WasmImport MemImport;
13411ed3a046SSam Clegg   MemImport.Module = "env";
13421ed3a046SSam Clegg   MemImport.Field = "__linear_memory";
1343f950b24aSSam Clegg   MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
1344fd0964aeSWouter van Oortmerssen   MemImport.Memory.Flags = is64Bit() ? wasm::WASM_LIMITS_FLAG_IS_64
1345fd0964aeSWouter van Oortmerssen                                      : wasm::WASM_LIMITS_FLAG_NONE;
1346f950b24aSSam Clegg   Imports.push_back(MemImport);
1347f950b24aSSam Clegg 
1348da419bdbSHeejin Ahn   // Populate SignatureIndices, and Imports and WasmIndices for undefined
1349586320c0SNicholas Wilson   // symbols.  This must be done before populating WasmIndices for defined
1350586320c0SNicholas Wilson   // symbols.
135132ce5ca0SDan Gohman   for (const MCSymbol &S : Asm.symbols()) {
135232ce5ca0SDan Gohman     const auto &WS = static_cast<const MCSymbolWasm &>(S);
135332ce5ca0SDan Gohman 
135432ce5ca0SDan Gohman     // Register types for all functions, including those with private linkage
13559f3fe42eSSam Clegg     // (because wasm always needs a type signature).
13567ee758d6SSam Clegg     if (WS.isFunction()) {
13579c7b5808SDominic Chen       const auto *BS = Layout.getBaseSymbol(S);
13589c7b5808SDominic Chen       if (!BS)
13599c7b5808SDominic Chen         report_fatal_error(Twine(S.getName()) +
13609c7b5808SDominic Chen                            ": absolute addressing not supported!");
13619c7b5808SDominic Chen       registerFunctionType(*cast<MCSymbolWasm>(BS));
13627ee758d6SSam Clegg     }
136332ce5ca0SDan Gohman 
13641d891d44SHeejin Ahn     if (WS.isTag())
13651d891d44SHeejin Ahn       registerTagType(WS);
1366da419bdbSHeejin Ahn 
136732ce5ca0SDan Gohman     if (WS.isTemporary())
136832ce5ca0SDan Gohman       continue;
136932ce5ca0SDan Gohman 
137032ce5ca0SDan Gohman     // If the symbol is not defined in this translation unit, import it.
13716c899ba6SSam Clegg     if (!WS.isDefined() && !WS.isComdat()) {
13726c899ba6SSam Clegg       if (WS.isFunction()) {
13738defa952SSam Clegg         wasm::WasmImport Import;
1374f726e445SDan Gohman         Import.Module = WS.getImportModule();
1375f726e445SDan Gohman         Import.Field = WS.getImportName();
137632ce5ca0SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
13778defa952SSam Clegg         Import.SigIndex = getFunctionType(WS);
13786c899ba6SSam Clegg         Imports.push_back(Import);
1379492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
13806c899ba6SSam Clegg         WasmIndices[&WS] = NumFunctionImports++;
13816c899ba6SSam Clegg       } else if (WS.isGlobal()) {
138215f349f7SNicholas Wilson         if (WS.isWeak())
138315f349f7SNicholas Wilson           report_fatal_error("undefined global symbol cannot be weak");
138415f349f7SNicholas Wilson 
13856c899ba6SSam Clegg         wasm::WasmImport Import;
1386f726e445SDan Gohman         Import.Field = WS.getImportName();
138732ce5ca0SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1388492f7529SSam Clegg         Import.Module = WS.getImportModule();
13896c899ba6SSam Clegg         Import.Global = WS.getGlobalType();
13906c899ba6SSam Clegg         Imports.push_back(Import);
1391492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
13926c899ba6SSam Clegg         WasmIndices[&WS] = NumGlobalImports++;
13931d891d44SHeejin Ahn       } else if (WS.isTag()) {
1394da419bdbSHeejin Ahn         if (WS.isWeak())
13951d891d44SHeejin Ahn           report_fatal_error("undefined tag symbol cannot be weak");
1396da419bdbSHeejin Ahn 
1397da419bdbSHeejin Ahn         wasm::WasmImport Import;
1398f726e445SDan Gohman         Import.Module = WS.getImportModule();
1399f726e445SDan Gohman         Import.Field = WS.getImportName();
14001d891d44SHeejin Ahn         Import.Kind = wasm::WASM_EXTERNAL_TAG;
14013ec1760dSHeejin Ahn         Import.SigIndex = getTagType(WS);
1402da419bdbSHeejin Ahn         Imports.push_back(Import);
1403492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
14041d891d44SHeejin Ahn         WasmIndices[&WS] = NumTagImports++;
1405feac819eSAndy Wingo       } else if (WS.isTable()) {
1406feac819eSAndy Wingo         if (WS.isWeak())
1407feac819eSAndy Wingo           report_fatal_error("undefined table symbol cannot be weak");
1408feac819eSAndy Wingo 
1409feac819eSAndy Wingo         wasm::WasmImport Import;
1410feac819eSAndy Wingo         Import.Module = WS.getImportModule();
1411feac819eSAndy Wingo         Import.Field = WS.getImportName();
1412feac819eSAndy Wingo         Import.Kind = wasm::WASM_EXTERNAL_TABLE;
1413c9801db2SAndy Wingo         Import.Table = WS.getTableType();
1414feac819eSAndy Wingo         Imports.push_back(Import);
1415feac819eSAndy Wingo         assert(WasmIndices.count(&WS) == 0);
1416feac819eSAndy Wingo         WasmIndices[&WS] = NumTableImports++;
141732ce5ca0SDan Gohman       }
141832ce5ca0SDan Gohman     }
141932ce5ca0SDan Gohman   }
142032ce5ca0SDan Gohman 
1421492f7529SSam Clegg   // Add imports for GOT globals
1422492f7529SSam Clegg   for (const MCSymbol &S : Asm.symbols()) {
1423492f7529SSam Clegg     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1424492f7529SSam Clegg     if (WS.isUsedInGOT()) {
1425492f7529SSam Clegg       wasm::WasmImport Import;
1426492f7529SSam Clegg       if (WS.isFunction())
1427492f7529SSam Clegg         Import.Module = "GOT.func";
1428492f7529SSam Clegg       else
1429492f7529SSam Clegg         Import.Module = "GOT.mem";
1430492f7529SSam Clegg       Import.Field = WS.getName();
1431492f7529SSam Clegg       Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1432492f7529SSam Clegg       Import.Global = {wasm::WASM_TYPE_I32, true};
1433492f7529SSam Clegg       Imports.push_back(Import);
1434492f7529SSam Clegg       assert(GOTIndices.count(&WS) == 0);
1435492f7529SSam Clegg       GOTIndices[&WS] = NumGlobalImports++;
1436492f7529SSam Clegg     }
1437492f7529SSam Clegg   }
14380ff28fa6SDerek Schuff }
1439492f7529SSam Clegg 
14400ff28fa6SDerek Schuff uint64_t WasmObjectWriter::writeObject(MCAssembler &Asm,
14410ff28fa6SDerek Schuff                                        const MCAsmLayout &Layout) {
14420ff28fa6SDerek Schuff   support::endian::Writer MainWriter(*OS, support::little);
14430ff28fa6SDerek Schuff   W = &MainWriter;
14440ff28fa6SDerek Schuff   if (IsSplitDwarf) {
14450ff28fa6SDerek Schuff     uint64_t TotalSize = writeOneObject(Asm, Layout, DwoMode::NonDwoOnly);
14460ff28fa6SDerek Schuff     assert(DwoOS);
14470ff28fa6SDerek Schuff     support::endian::Writer DwoWriter(*DwoOS, support::little);
14480ff28fa6SDerek Schuff     W = &DwoWriter;
14490ff28fa6SDerek Schuff     return TotalSize + writeOneObject(Asm, Layout, DwoMode::DwoOnly);
14500ff28fa6SDerek Schuff   } else {
14510ff28fa6SDerek Schuff     return writeOneObject(Asm, Layout, DwoMode::AllSections);
14520ff28fa6SDerek Schuff   }
14530ff28fa6SDerek Schuff }
14540ff28fa6SDerek Schuff 
14550ff28fa6SDerek Schuff uint64_t WasmObjectWriter::writeOneObject(MCAssembler &Asm,
14560ff28fa6SDerek Schuff                                           const MCAsmLayout &Layout,
14570ff28fa6SDerek Schuff                                           DwoMode Mode) {
14580ff28fa6SDerek Schuff   uint64_t StartOffset = W->OS.tell();
14590ff28fa6SDerek Schuff   SectionCount = 0;
14600ff28fa6SDerek Schuff   CustomSections.clear();
14610ff28fa6SDerek Schuff 
14620ff28fa6SDerek Schuff   LLVM_DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
14630ff28fa6SDerek Schuff 
14640ff28fa6SDerek Schuff   // Collect information from the available symbols.
14650ff28fa6SDerek Schuff   SmallVector<WasmFunction, 4> Functions;
14660ff28fa6SDerek Schuff   SmallVector<uint32_t, 4> TableElems;
14670ff28fa6SDerek Schuff   SmallVector<wasm::WasmImport, 4> Imports;
14680ff28fa6SDerek Schuff   SmallVector<wasm::WasmExport, 4> Exports;
14693ec1760dSHeejin Ahn   SmallVector<uint32_t, 2> TagTypes;
14700ff28fa6SDerek Schuff   SmallVector<wasm::WasmGlobal, 1> Globals;
1471388fb67bSPaulo Matos   SmallVector<wasm::WasmTable, 1> Tables;
14720ff28fa6SDerek Schuff   SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos;
14730ff28fa6SDerek Schuff   SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
14740ff28fa6SDerek Schuff   std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
14750ff28fa6SDerek Schuff   uint64_t DataSize = 0;
14760ff28fa6SDerek Schuff   if (Mode != DwoMode::DwoOnly) {
14770ff28fa6SDerek Schuff     prepareImports(Imports, Asm, Layout);
14780ff28fa6SDerek Schuff   }
147930d314aaSSam Clegg 
14804d57fbd0SSam Clegg   // Populate DataSegments and CustomSections, which must be done before
14814d57fbd0SSam Clegg   // populating DataLocations.
1482759631c7SSam Clegg   for (MCSection &Sec : Asm) {
1483759631c7SSam Clegg     auto &Section = static_cast<MCSectionWasm &>(Sec);
14847d1ff446SFangrui Song     StringRef SectionName = Section.getName();
1485759631c7SSam Clegg 
14860ff28fa6SDerek Schuff     if (Mode == DwoMode::NonDwoOnly && isDwoSection(Sec))
14870ff28fa6SDerek Schuff       continue;
14880ff28fa6SDerek Schuff     if (Mode == DwoMode::DwoOnly && !isDwoSection(Sec))
14890ff28fa6SDerek Schuff       continue;
14900ff28fa6SDerek Schuff 
14918d396acaSDerek Schuff     LLVM_DEBUG(dbgs() << "Processing Section " << SectionName << "  group "
14928d396acaSDerek Schuff                       << Section.getGroup() << "\n";);
14938d396acaSDerek Schuff 
1494bafe6902SSam Clegg     // .init_array sections are handled specially elsewhere.
14954d57fbd0SSam Clegg     if (SectionName.startswith(".init_array"))
1496bafe6902SSam Clegg       continue;
1497bafe6902SSam Clegg 
14984d57fbd0SSam Clegg     // Code is handled separately
14994d57fbd0SSam Clegg     if (Section.getKind().isText())
15004d57fbd0SSam Clegg       continue;
15014d57fbd0SSam Clegg 
15024d57fbd0SSam Clegg     if (Section.isWasmData()) {
1503329e76d5SSam Clegg       uint32_t SegmentIndex = DataSegments.size();
1504759631c7SSam Clegg       DataSize = alignTo(DataSize, Section.getAlignment());
1505759631c7SSam Clegg       DataSegments.emplace_back();
1506759631c7SSam Clegg       WasmDataSegment &Segment = DataSegments.back();
15074d57fbd0SSam Clegg       Segment.Name = SectionName;
1508831a143eSAndy Wingo       Segment.InitFlags = Section.getPassive()
1509831a143eSAndy Wingo                               ? (uint32_t)wasm::WASM_DATA_SEGMENT_IS_PASSIVE
1510831a143eSAndy Wingo                               : 0;
1511759631c7SSam Clegg       Segment.Offset = DataSize;
1512759631c7SSam Clegg       Segment.Section = &Section;
151363ebb813SSam Clegg       addData(Segment.Data, Section);
151456c587adSSam Clegg       Segment.Alignment = Log2_32(Section.getAlignment());
15153b8d2be5SSam Clegg       Segment.LinkingFlags = Section.getSegmentFlags();
1516759631c7SSam Clegg       DataSize += Segment.Data.size();
15176c899ba6SSam Clegg       Section.setSegmentIndex(SegmentIndex);
1518ea7caceeSSam Clegg 
1519ea7caceeSSam Clegg       if (const MCSymbolWasm *C = Section.getGroup()) {
1520ea7caceeSSam Clegg         Comdats[C->getName()].emplace_back(
1521329e76d5SSam Clegg             WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
1522ea7caceeSSam Clegg       }
15234d57fbd0SSam Clegg     } else {
15244d57fbd0SSam Clegg       // Create custom sections
15254d57fbd0SSam Clegg       assert(Sec.getKind().isMetadata());
15264d57fbd0SSam Clegg 
15274d57fbd0SSam Clegg       StringRef Name = SectionName;
15284d57fbd0SSam Clegg 
15294d57fbd0SSam Clegg       // For user-defined custom sections, strip the prefix
15304d57fbd0SSam Clegg       if (Name.startswith(".custom_section."))
15314d57fbd0SSam Clegg         Name = Name.substr(strlen(".custom_section."));
15324d57fbd0SSam Clegg 
15334d57fbd0SSam Clegg       MCSymbol *Begin = Sec.getBeginSymbol();
1534fb807d4dSSam Clegg       if (Begin) {
153530d314aaSSam Clegg         assert(WasmIndices.count(cast<MCSymbolWasm>(Begin)) == 0);
15364d57fbd0SSam Clegg         WasmIndices[cast<MCSymbolWasm>(Begin)] = CustomSections.size();
1537fb807d4dSSam Clegg       }
1538cbda16ebSThomas Lively 
1539f6f4f843SThomas Lively       // Separate out the producers and target features sections
1540cbda16ebSThomas Lively       if (Name == "producers") {
15410eaee545SJonas Devlieghere         ProducersSection = std::make_unique<WasmCustomSection>(Name, &Section);
1542cbda16ebSThomas Lively         continue;
1543cbda16ebSThomas Lively       }
1544f6f4f843SThomas Lively       if (Name == "target_features") {
1545f6f4f843SThomas Lively         TargetFeaturesSection =
15460eaee545SJonas Devlieghere             std::make_unique<WasmCustomSection>(Name, &Section);
1547f6f4f843SThomas Lively         continue;
1548f6f4f843SThomas Lively       }
1549cbda16ebSThomas Lively 
15500a391060SDerek Schuff       // Custom sections can also belong to COMDAT groups. In this case the
15510a391060SDerek Schuff       // decriptor's "index" field is the section index (in the final object
15520a391060SDerek Schuff       // file), but that is not known until after layout, so it must be fixed up
15530a391060SDerek Schuff       // later
15540a391060SDerek Schuff       if (const MCSymbolWasm *C = Section.getGroup()) {
15550a391060SDerek Schuff         Comdats[C->getName()].emplace_back(
15560a391060SDerek Schuff             WasmComdatEntry{wasm::WASM_COMDAT_SECTION,
15570a391060SDerek Schuff                             static_cast<uint32_t>(CustomSections.size())});
15580a391060SDerek Schuff       }
15590a391060SDerek Schuff 
15604d57fbd0SSam Clegg       CustomSections.emplace_back(Name, &Section);
1561759631c7SSam Clegg     }
15626a31a0d6SSam Clegg   }
15636a31a0d6SSam Clegg 
156430d314aaSSam Clegg   if (Mode != DwoMode::DwoOnly) {
1565586320c0SNicholas Wilson     // Populate WasmIndices and DataLocations for defined symbols.
1566d934cb88SDan Gohman     for (const MCSymbol &S : Asm.symbols()) {
1567d934cb88SDan Gohman       // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1568d934cb88SDan Gohman       // or used in relocations.
1569d934cb88SDan Gohman       if (S.isTemporary() && S.getName().empty())
1570d934cb88SDan Gohman         continue;
1571b7787fd0SSam Clegg 
1572d934cb88SDan Gohman       const auto &WS = static_cast<const MCSymbolWasm &>(S);
15735e5b2cb1SWouter van Oortmerssen       LLVM_DEBUG(dbgs()
15745e5b2cb1SWouter van Oortmerssen                  << "MCSymbol: "
15755e5b2cb1SWouter van Oortmerssen                  << toString(WS.getType().getValueOr(wasm::WASM_SYMBOL_TYPE_DATA))
15765e5b2cb1SWouter van Oortmerssen                  << " '" << S << "'"
1577d34e60caSNicola Zaghen                  << " isDefined=" << S.isDefined() << " isExternal="
1578d34e60caSNicola Zaghen                  << S.isExternal() << " isTemporary=" << S.isTemporary()
1579d34e60caSNicola Zaghen                  << " isWeak=" << WS.isWeak() << " isHidden=" << WS.isHidden()
1580b7787fd0SSam Clegg                  << " isVariable=" << WS.isVariable() << "\n");
1581b7787fd0SSam Clegg 
15825e3d33a7SSam Clegg       if (WS.isVariable())
15835e3d33a7SSam Clegg         continue;
15846c899ba6SSam Clegg       if (WS.isComdat() && !WS.isDefined())
15856c899ba6SSam Clegg         continue;
1586b7787fd0SSam Clegg 
1587d934cb88SDan Gohman       if (WS.isFunction()) {
15886c899ba6SSam Clegg         unsigned Index;
1589cd65f698SSam Clegg         if (WS.isDefined()) {
1590b7787fd0SSam Clegg           if (WS.getOffset() != 0)
1591b7787fd0SSam Clegg             report_fatal_error(
1592b7787fd0SSam Clegg                 "function sections must contain one function each");
1593b7787fd0SSam Clegg 
159418c56a07SHeejin Ahn           if (WS.getSize() == nullptr)
1595b7787fd0SSam Clegg             report_fatal_error(
1596b7787fd0SSam Clegg                 "function symbols must have a size set with .size");
1597b7787fd0SSam Clegg 
15986c899ba6SSam Clegg           // A definition. Write out the function body.
15999f3fe42eSSam Clegg           Index = NumFunctionImports + Functions.size();
1600d934cb88SDan Gohman           WasmFunction Func;
1601da419bdbSHeejin Ahn           Func.SigIndex = getFunctionType(WS);
1602d934cb88SDan Gohman           Func.Sym = &WS;
160330d314aaSSam Clegg           assert(WasmIndices.count(&WS) == 0);
16046c899ba6SSam Clegg           WasmIndices[&WS] = Index;
1605d934cb88SDan Gohman           Functions.push_back(Func);
16066c899ba6SSam Clegg 
16076c899ba6SSam Clegg           auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
16086c899ba6SSam Clegg           if (const MCSymbolWasm *C = Section.getGroup()) {
16096c899ba6SSam Clegg             Comdats[C->getName()].emplace_back(
16106c899ba6SSam Clegg                 WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
16116c899ba6SSam Clegg           }
1612881d8778SSam Clegg 
1613881d8778SSam Clegg           if (WS.hasExportName()) {
1614881d8778SSam Clegg             wasm::WasmExport Export;
1615881d8778SSam Clegg             Export.Name = WS.getExportName();
1616881d8778SSam Clegg             Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1617881d8778SSam Clegg             Export.Index = Index;
1618881d8778SSam Clegg             Exports.push_back(Export);
1619881d8778SSam Clegg           }
1620d934cb88SDan Gohman         } else {
1621d934cb88SDan Gohman           // An import; the index was assigned above.
16226c899ba6SSam Clegg           Index = WasmIndices.find(&WS)->second;
1623d934cb88SDan Gohman         }
1624d934cb88SDan Gohman 
1625d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "  -> function index: " << Index << "\n");
1626da419bdbSHeejin Ahn 
16276c899ba6SSam Clegg       } else if (WS.isData()) {
1628f3feb6adSWouter van Oortmerssen         if (!isInSymtab(WS))
1629c38e947eSSam Clegg           continue;
1630c38e947eSSam Clegg 
16316c899ba6SSam Clegg         if (!WS.isDefined()) {
1632d34e60caSNicola Zaghen           LLVM_DEBUG(dbgs() << "  -> segment index: -1"
1633d34e60caSNicola Zaghen                             << "\n");
1634fe6414b0SSam Clegg           continue;
16356c899ba6SSam Clegg         }
1636fe6414b0SSam Clegg 
1637d934cb88SDan Gohman         if (!WS.getSize())
1638c38e947eSSam Clegg           report_fatal_error("data symbols must have a size set with .size: " +
1639c38e947eSSam Clegg                              WS.getName());
1640d934cb88SDan Gohman 
1641d934cb88SDan Gohman         int64_t Size = 0;
1642d934cb88SDan Gohman         if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1643d934cb88SDan Gohman           report_fatal_error(".size expression must be evaluatable");
1644d934cb88SDan Gohman 
1645759631c7SSam Clegg         auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
1646079cba04SSam Clegg         if (!DataSection.isWasmData())
1647079cba04SSam Clegg           report_fatal_error("data symbols must live in a data section: " +
1648079cba04SSam Clegg                              WS.getName());
16497c395943SSam Clegg 
16506c899ba6SSam Clegg         // For each data symbol, export it in the symtab as a reference to the
16516c899ba6SSam Clegg         // corresponding Wasm data segment.
16526c899ba6SSam Clegg         wasm::WasmDataReference Ref = wasm::WasmDataReference{
16533b29376eSWouter van Oortmerssen             DataSection.getSegmentIndex(), Layout.getSymbolOffset(WS),
16543b29376eSWouter van Oortmerssen             static_cast<uint64_t>(Size)};
165530d314aaSSam Clegg         assert(DataLocations.count(&WS) == 0);
16566c899ba6SSam Clegg         DataLocations[&WS] = Ref;
1657d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "  -> segment index: " << Ref.Segment << "\n");
1658da419bdbSHeejin Ahn 
1659a165f2d6SSam Clegg       } else if (WS.isGlobal()) {
16606c899ba6SSam Clegg         // A "true" Wasm global (currently just __stack_pointer)
16610a6c4d8dSSam Clegg         if (WS.isDefined()) {
16620a6c4d8dSSam Clegg           wasm::WasmGlobal Global;
16630a6c4d8dSSam Clegg           Global.Type = WS.getGlobalType();
16640a6c4d8dSSam Clegg           Global.Index = NumGlobalImports + Globals.size();
16659504ab32SSam Clegg           Global.InitExpr.Extended = false;
16660a6c4d8dSSam Clegg           switch (Global.Type.Type) {
16670a6c4d8dSSam Clegg           case wasm::WASM_TYPE_I32:
16689504ab32SSam Clegg             Global.InitExpr.Inst.Opcode = wasm::WASM_OPCODE_I32_CONST;
16690a6c4d8dSSam Clegg             break;
16700a6c4d8dSSam Clegg           case wasm::WASM_TYPE_I64:
16719504ab32SSam Clegg             Global.InitExpr.Inst.Opcode = wasm::WASM_OPCODE_I64_CONST;
16720a6c4d8dSSam Clegg             break;
16730a6c4d8dSSam Clegg           case wasm::WASM_TYPE_F32:
16749504ab32SSam Clegg             Global.InitExpr.Inst.Opcode = wasm::WASM_OPCODE_F32_CONST;
16750a6c4d8dSSam Clegg             break;
16760a6c4d8dSSam Clegg           case wasm::WASM_TYPE_F64:
16779504ab32SSam Clegg             Global.InitExpr.Inst.Opcode = wasm::WASM_OPCODE_F64_CONST;
16780a6c4d8dSSam Clegg             break;
167979aad89dSSam Clegg           case wasm::WASM_TYPE_EXTERNREF:
16809504ab32SSam Clegg             Global.InitExpr.Inst.Opcode = wasm::WASM_OPCODE_REF_NULL;
168179aad89dSSam Clegg             break;
16820a6c4d8dSSam Clegg           default:
16830a6c4d8dSSam Clegg             llvm_unreachable("unexpected type");
16840a6c4d8dSSam Clegg           }
168530d314aaSSam Clegg           assert(WasmIndices.count(&WS) == 0);
16860a6c4d8dSSam Clegg           WasmIndices[&WS] = Global.Index;
16870a6c4d8dSSam Clegg           Globals.push_back(Global);
16880a6c4d8dSSam Clegg         } else {
1689545932beSEric Christopher           // An import; the index was assigned above
1690d34e60caSNicola Zaghen           LLVM_DEBUG(dbgs() << "  -> global index: "
1691d34e60caSNicola Zaghen                             << WasmIndices.find(&WS)->second << "\n");
16920a6c4d8dSSam Clegg         }
1693388fb67bSPaulo Matos       } else if (WS.isTable()) {
1694388fb67bSPaulo Matos         if (WS.isDefined()) {
1695388fb67bSPaulo Matos           wasm::WasmTable Table;
1696388fb67bSPaulo Matos           Table.Index = NumTableImports + Tables.size();
1697c9801db2SAndy Wingo           Table.Type = WS.getTableType();
169830d314aaSSam Clegg           assert(WasmIndices.count(&WS) == 0);
1699388fb67bSPaulo Matos           WasmIndices[&WS] = Table.Index;
1700388fb67bSPaulo Matos           Tables.push_back(Table);
1701388fb67bSPaulo Matos         }
170230d314aaSSam Clegg         LLVM_DEBUG(dbgs() << " -> table index: "
170330d314aaSSam Clegg                           << WasmIndices.find(&WS)->second << "\n");
17041d891d44SHeejin Ahn       } else if (WS.isTag()) {
170528780e59SHeejin Ahn         // C++ exception symbol (__cpp_exception) or longjmp symbol
170628780e59SHeejin Ahn         // (__c_longjmp)
1707da419bdbSHeejin Ahn         unsigned Index;
1708da419bdbSHeejin Ahn         if (WS.isDefined()) {
17093ec1760dSHeejin Ahn           Index = NumTagImports + TagTypes.size();
17103ec1760dSHeejin Ahn           uint32_t SigIndex = getTagType(WS);
171130d314aaSSam Clegg           assert(WasmIndices.count(&WS) == 0);
1712da419bdbSHeejin Ahn           WasmIndices[&WS] = Index;
17133ec1760dSHeejin Ahn           TagTypes.push_back(SigIndex);
1714da419bdbSHeejin Ahn         } else {
1715da419bdbSHeejin Ahn           // An import; the index was assigned above.
1716492f7529SSam Clegg           assert(WasmIndices.count(&WS) > 0);
1717da419bdbSHeejin Ahn         }
17181d891d44SHeejin Ahn         LLVM_DEBUG(dbgs() << "  -> tag index: " << WasmIndices.find(&WS)->second
17191d891d44SHeejin Ahn                           << "\n");
1720da419bdbSHeejin Ahn 
1721a165f2d6SSam Clegg       } else {
1722a165f2d6SSam Clegg         assert(WS.isSection());
1723d934cb88SDan Gohman       }
1724d934cb88SDan Gohman     }
1725d934cb88SDan Gohman 
1726586320c0SNicholas Wilson     // Populate WasmIndices and DataLocations for aliased symbols.  We need to
1727586320c0SNicholas Wilson     // process these in a separate pass because we need to have processed the
1728586320c0SNicholas Wilson     // target of the alias before the alias itself and the symbols are not
1729586320c0SNicholas Wilson     // necessarily ordered in this way.
1730b7787fd0SSam Clegg     for (const MCSymbol &S : Asm.symbols()) {
1731b7787fd0SSam Clegg       if (!S.isVariable())
1732b7787fd0SSam Clegg         continue;
173331a2c809SSam Clegg 
1734cd65f698SSam Clegg       assert(S.isDefined());
1735b7787fd0SSam Clegg 
17369c7b5808SDominic Chen       const auto *BS = Layout.getBaseSymbol(S);
17379c7b5808SDominic Chen       if (!BS)
17389c7b5808SDominic Chen         report_fatal_error(Twine(S.getName()) +
17399c7b5808SDominic Chen                            ": absolute addressing not supported!");
17409c7b5808SDominic Chen       const MCSymbolWasm *Base = cast<MCSymbolWasm>(BS);
17417ee758d6SSam Clegg 
17425e3d33a7SSam Clegg       // Find the target symbol of this weak alias and export that index
1743aff1c4dfSSam Clegg       const auto &WS = static_cast<const MCSymbolWasm &>(S);
174430d314aaSSam Clegg       LLVM_DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *Base
174530d314aaSSam Clegg                         << "'\n");
1746b7787fd0SSam Clegg 
17477ee758d6SSam Clegg       if (Base->isFunction()) {
17487ee758d6SSam Clegg         assert(WasmIndices.count(Base) > 0);
17497ee758d6SSam Clegg         uint32_t WasmIndex = WasmIndices.find(Base)->second;
1750492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
17516c899ba6SSam Clegg         WasmIndices[&WS] = WasmIndex;
1752d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "  -> index:" << WasmIndex << "\n");
17537ee758d6SSam Clegg       } else if (Base->isData()) {
17547ee758d6SSam Clegg         auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
17557ee758d6SSam Clegg         uint64_t Offset = Layout.getSymbolOffset(S);
17567ee758d6SSam Clegg         int64_t Size = 0;
17577ee758d6SSam Clegg         // For data symbol alias we use the size of the base symbol as the
17587ee758d6SSam Clegg         // size of the alias.  When an offset from the base is involved this
17597ee758d6SSam Clegg         // can result in a offset + size goes past the end of the data section
17607ee758d6SSam Clegg         // which out object format doesn't support.  So we must clamp it.
17617ee758d6SSam Clegg         if (!Base->getSize()->evaluateAsAbsolute(Size, Layout))
17627ee758d6SSam Clegg           report_fatal_error(".size expression must be evaluatable");
17637ee758d6SSam Clegg         const WasmDataSegment &Segment =
17647ee758d6SSam Clegg             DataSegments[DataSection.getSegmentIndex()];
17657ee758d6SSam Clegg         Size =
17667ee758d6SSam Clegg             std::min(static_cast<uint64_t>(Size), Segment.Data.size() - Offset);
17677ee758d6SSam Clegg         wasm::WasmDataReference Ref = wasm::WasmDataReference{
17687ee758d6SSam Clegg             DataSection.getSegmentIndex(),
17697ee758d6SSam Clegg             static_cast<uint32_t>(Layout.getSymbolOffset(S)),
17707ee758d6SSam Clegg             static_cast<uint32_t>(Size)};
17716c899ba6SSam Clegg         DataLocations[&WS] = Ref;
1772d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "  -> index:" << Ref.Segment << "\n");
17736c899ba6SSam Clegg       } else {
17741d891d44SHeejin Ahn         report_fatal_error("don't yet support global/tag aliases");
17756c899ba6SSam Clegg       }
1776586320c0SNicholas Wilson     }
177730d314aaSSam Clegg   }
177831a2c809SSam Clegg 
1779586320c0SNicholas Wilson   // Finally, populate the symbol table itself, in its "natural" order.
1780586320c0SNicholas Wilson   for (const MCSymbol &S : Asm.symbols()) {
1781586320c0SNicholas Wilson     const auto &WS = static_cast<const MCSymbolWasm &>(S);
178225d8e68bSSam Clegg     if (!isInSymtab(WS)) {
178318c56a07SHeejin Ahn       WS.setIndex(InvalidIndex);
1784586320c0SNicholas Wilson       continue;
178525d8e68bSSam Clegg     }
1786d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "adding to symtab: " << WS << "\n");
1787586320c0SNicholas Wilson 
1788586320c0SNicholas Wilson     uint32_t Flags = 0;
1789586320c0SNicholas Wilson     if (WS.isWeak())
1790586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_BINDING_WEAK;
1791586320c0SNicholas Wilson     if (WS.isHidden())
1792586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN;
1793586320c0SNicholas Wilson     if (!WS.isExternal() && WS.isDefined())
1794586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;
1795586320c0SNicholas Wilson     if (WS.isUndefined())
1796586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_UNDEFINED;
1797da84b688SDan Gohman     if (WS.isNoStrip()) {
1798da84b688SDan Gohman       Flags |= wasm::WASM_SYMBOL_NO_STRIP;
1799da84b688SDan Gohman       if (isEmscripten()) {
1800d6ef8da3SSam Clegg         Flags |= wasm::WASM_SYMBOL_EXPORTED;
1801da84b688SDan Gohman       }
1802da84b688SDan Gohman     }
1803b4f4e370SSam Clegg     if (WS.hasImportName())
180429874ceaSDan Gohman       Flags |= wasm::WASM_SYMBOL_EXPLICIT_NAME;
1805881d8778SSam Clegg     if (WS.hasExportName())
1806881d8778SSam Clegg       Flags |= wasm::WASM_SYMBOL_EXPORTED;
180744177e5fSSam Clegg     if (WS.isTLS())
180844177e5fSSam Clegg       Flags |= wasm::WASM_SYMBOL_TLS;
1809586320c0SNicholas Wilson 
1810586320c0SNicholas Wilson     wasm::WasmSymbolInfo Info;
1811586320c0SNicholas Wilson     Info.Name = WS.getName();
18125e5b2cb1SWouter van Oortmerssen     Info.Kind = WS.getType().getValueOr(wasm::WASM_SYMBOL_TYPE_DATA);
1813586320c0SNicholas Wilson     Info.Flags = Flags;
18144d57fbd0SSam Clegg     if (!WS.isData()) {
18154d57fbd0SSam Clegg       assert(WasmIndices.count(&WS) > 0);
1816586320c0SNicholas Wilson       Info.ElementIndex = WasmIndices.find(&WS)->second;
18174d57fbd0SSam Clegg     } else if (WS.isDefined()) {
18184d57fbd0SSam Clegg       assert(DataLocations.count(&WS) > 0);
1819586320c0SNicholas Wilson       Info.DataRef = DataLocations.find(&WS)->second;
18204d57fbd0SSam Clegg     }
182125d8e68bSSam Clegg     WS.setIndex(SymbolInfos.size());
1822586320c0SNicholas Wilson     SymbolInfos.emplace_back(Info);
1823b7787fd0SSam Clegg   }
1824b7787fd0SSam Clegg 
18256006e091SSam Clegg   {
18266006e091SSam Clegg     auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
1827f9edbe95SSam Clegg       // Functions referenced by a relocation need to put in the table.  This is
1828f9edbe95SSam Clegg       // purely to make the object file's provisional values readable, and is
1829f9edbe95SSam Clegg       // ignored by the linker, which re-calculates the relocations itself.
1830d1152a26SSam Clegg       if (Rel.Type != wasm::R_WASM_TABLE_INDEX_I32 &&
1831cc1b9b68SWouter van Oortmerssen           Rel.Type != wasm::R_WASM_TABLE_INDEX_I64 &&
183281443ac1SSam Clegg           Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB &&
1833cc1b9b68SWouter van Oortmerssen           Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB64 &&
18343a293cbfSWouter van Oortmerssen           Rel.Type != wasm::R_WASM_TABLE_INDEX_REL_SLEB &&
18353a293cbfSWouter van Oortmerssen           Rel.Type != wasm::R_WASM_TABLE_INDEX_REL_SLEB64)
1836f9edbe95SSam Clegg         return;
1837f9edbe95SSam Clegg       assert(Rel.Symbol->isFunction());
18387ee758d6SSam Clegg       const MCSymbolWasm *Base =
18397ee758d6SSam Clegg           cast<MCSymbolWasm>(Layout.getBaseSymbol(*Rel.Symbol));
18407ee758d6SSam Clegg       uint32_t FunctionIndex = WasmIndices.find(Base)->second;
184118c56a07SHeejin Ahn       uint32_t TableIndex = TableElems.size() + InitialTableOffset;
18427ee758d6SSam Clegg       if (TableIndices.try_emplace(Base, TableIndex).second) {
18437ee758d6SSam Clegg         LLVM_DEBUG(dbgs() << "  -> adding " << Base->getName()
1844f9edbe95SSam Clegg                           << " to table: " << TableIndex << "\n");
18456c899ba6SSam Clegg         TableElems.push_back(FunctionIndex);
18467ee758d6SSam Clegg         registerFunctionType(*Base);
18476006e091SSam Clegg       }
18486006e091SSam Clegg     };
1849970d02c4SDan Gohman 
18506006e091SSam Clegg     for (const WasmRelocationEntry &RelEntry : CodeRelocations)
18516006e091SSam Clegg       HandleReloc(RelEntry);
18526006e091SSam Clegg     for (const WasmRelocationEntry &RelEntry : DataRelocations)
18536006e091SSam Clegg       HandleReloc(RelEntry);
1854d934cb88SDan Gohman   }
1855d934cb88SDan Gohman 
1856bafe6902SSam Clegg   // Translate .init_array section contents into start functions.
1857bafe6902SSam Clegg   for (const MCSection &S : Asm) {
1858bafe6902SSam Clegg     const auto &WS = static_cast<const MCSectionWasm &>(S);
18597d1ff446SFangrui Song     if (WS.getName().startswith(".fini_array"))
1860bafe6902SSam Clegg       report_fatal_error(".fini_array sections are unsupported");
18617d1ff446SFangrui Song     if (!WS.getName().startswith(".init_array"))
1862bafe6902SSam Clegg       continue;
1863bafe6902SSam Clegg     if (WS.getFragmentList().empty())
1864bafe6902SSam Clegg       continue;
1865b210c64bSSam Clegg 
1866b210c64bSSam Clegg     // init_array is expected to contain a single non-empty data fragment
1867b210c64bSSam Clegg     if (WS.getFragmentList().size() != 3)
1868bafe6902SSam Clegg       report_fatal_error("only one .init_array section fragment supported");
1869b210c64bSSam Clegg 
1870b210c64bSSam Clegg     auto IT = WS.begin();
1871b210c64bSSam Clegg     const MCFragment &EmptyFrag = *IT;
1872b210c64bSSam Clegg     if (EmptyFrag.getKind() != MCFragment::FT_Data)
1873b210c64bSSam Clegg       report_fatal_error(".init_array section should be aligned");
1874b210c64bSSam Clegg 
1875b210c64bSSam Clegg     IT = std::next(IT);
1876b210c64bSSam Clegg     const MCFragment &AlignFrag = *IT;
1877bafe6902SSam Clegg     if (AlignFrag.getKind() != MCFragment::FT_Align)
1878bafe6902SSam Clegg       report_fatal_error(".init_array section should be aligned");
1879*412c788aSGuillaume Chatelet     if (cast<MCAlignFragment>(AlignFrag).getAlignment() !=
1880*412c788aSGuillaume Chatelet         Align(is64Bit() ? 8 : 4))
1881bafe6902SSam Clegg       report_fatal_error(".init_array section should be aligned for pointers");
1882b210c64bSSam Clegg 
1883b210c64bSSam Clegg     const MCFragment &Frag = *std::next(IT);
1884bafe6902SSam Clegg     if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1885bafe6902SSam Clegg       report_fatal_error("only data supported in .init_array section");
1886b210c64bSSam Clegg 
1887bafe6902SSam Clegg     uint16_t Priority = UINT16_MAX;
18884d57fbd0SSam Clegg     unsigned PrefixLength = strlen(".init_array");
18897d1ff446SFangrui Song     if (WS.getName().size() > PrefixLength) {
18907d1ff446SFangrui Song       if (WS.getName()[PrefixLength] != '.')
1891f208f631SHeejin Ahn         report_fatal_error(
1892f208f631SHeejin Ahn             ".init_array section priority should start with '.'");
18937d1ff446SFangrui Song       if (WS.getName().substr(PrefixLength + 1).getAsInteger(10, Priority))
1894bafe6902SSam Clegg         report_fatal_error("invalid .init_array section priority");
1895bafe6902SSam Clegg     }
1896bafe6902SSam Clegg     const auto &DataFrag = cast<MCDataFragment>(Frag);
1897bafe6902SSam Clegg     const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1898f208f631SHeejin Ahn     for (const uint8_t *
189918c56a07SHeejin Ahn              P = (const uint8_t *)Contents.data(),
190018c56a07SHeejin Ahn             *End = (const uint8_t *)Contents.data() + Contents.size();
190118c56a07SHeejin Ahn          P != End; ++P) {
190218c56a07SHeejin Ahn       if (*P != 0)
1903bafe6902SSam Clegg         report_fatal_error("non-symbolic data in .init_array section");
1904bafe6902SSam Clegg     }
1905bafe6902SSam Clegg     for (const MCFixup &Fixup : DataFrag.getFixups()) {
1906f208f631SHeejin Ahn       assert(Fixup.getKind() ==
1907f208f631SHeejin Ahn              MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
1908bafe6902SSam Clegg       const MCExpr *Expr = Fixup.getValue();
19098fffa1dfSSam Clegg       auto *SymRef = dyn_cast<MCSymbolRefExpr>(Expr);
19108fffa1dfSSam Clegg       if (!SymRef)
1911bafe6902SSam Clegg         report_fatal_error("fixups in .init_array should be symbol references");
19128fffa1dfSSam Clegg       const auto &TargetSym = cast<const MCSymbolWasm>(SymRef->getSymbol());
19138fffa1dfSSam Clegg       if (TargetSym.getIndex() == InvalidIndex)
19143ea1c62cSSam Clegg         report_fatal_error("symbols in .init_array should exist in symtab");
19158fffa1dfSSam Clegg       if (!TargetSym.isFunction())
19168fffa1dfSSam Clegg         report_fatal_error("symbols in .init_array should be for functions");
191725d8e68bSSam Clegg       InitFuncs.push_back(
19188fffa1dfSSam Clegg           std::make_pair(Priority, TargetSym.getIndex()));
1919bafe6902SSam Clegg     }
1920bafe6902SSam Clegg   }
1921bafe6902SSam Clegg 
192218eafb6cSDan Gohman   // Write out the Wasm header.
192318eafb6cSDan Gohman   writeHeader(Asm);
192418eafb6cSDan Gohman 
19250ff28fa6SDerek Schuff   uint32_t CodeSectionIndex, DataSectionIndex;
19260ff28fa6SDerek Schuff   if (Mode != DwoMode::DwoOnly) {
1927da419bdbSHeejin Ahn     writeTypeSection(Signatures);
1928f950b24aSSam Clegg     writeImportSection(Imports, DataSize, TableElems.size());
19299e15f359SSam Clegg     writeFunctionSection(Functions);
1930d823cc7cSAndy Wingo     writeTableSection(Tables);
1931f950b24aSSam Clegg     // Skip the "memory" section; we import the memory instead.
19323ec1760dSHeejin Ahn     writeTagSection(TagTypes);
19330a6c4d8dSSam Clegg     writeGlobalSection(Globals);
19349e15f359SSam Clegg     writeExportSection(Exports);
1935a5a3659dSAndy Wingo     const MCSymbol *IndirectFunctionTable =
1936a5a3659dSAndy Wingo         Asm.getContext().lookupSymbol("__indirect_function_table");
1937a5a3659dSAndy Wingo     writeElemSection(cast_or_null<const MCSymbolWasm>(IndirectFunctionTable),
1938a5a3659dSAndy Wingo                      TableElems);
1939fef8de66SThomas Lively     writeDataCountSection();
19400ff28fa6SDerek Schuff 
19410ff28fa6SDerek Schuff     CodeSectionIndex = writeCodeSection(Asm, Layout, Functions);
19420ff28fa6SDerek Schuff     DataSectionIndex = writeDataSection(Layout);
19430ff28fa6SDerek Schuff   }
19440ff28fa6SDerek Schuff 
19450a391060SDerek Schuff   // The Sections in the COMDAT list have placeholder indices (their index among
19460a391060SDerek Schuff   // custom sections, rather than among all sections). Fix them up here.
19470a391060SDerek Schuff   for (auto &Group : Comdats) {
19480a391060SDerek Schuff     for (auto &Entry : Group.second) {
19490a391060SDerek Schuff       if (Entry.Kind == wasm::WASM_COMDAT_SECTION) {
19500a391060SDerek Schuff         Entry.Index += SectionCount;
19510ff28fa6SDerek Schuff       }
19520a391060SDerek Schuff     }
19530a391060SDerek Schuff   }
19540a391060SDerek Schuff   for (auto &CustomSection : CustomSections)
19550a391060SDerek Schuff     writeCustomSection(CustomSection, Asm, Layout);
19560ff28fa6SDerek Schuff 
19570ff28fa6SDerek Schuff   if (Mode != DwoMode::DwoOnly) {
1958c22bfb6bSNicholas Wilson     writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats);
19590ff28fa6SDerek Schuff 
19606f08c84aSSam Clegg     writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations);
19616f08c84aSSam Clegg     writeRelocSection(DataSectionIndex, "DATA", DataRelocations);
19620ff28fa6SDerek Schuff   }
19636a31a0d6SSam Clegg   writeCustomRelocSections();
1964cbda16ebSThomas Lively   if (ProducersSection)
1965cbda16ebSThomas Lively     writeCustomSection(*ProducersSection, Asm, Layout);
1966f6f4f843SThomas Lively   if (TargetFeaturesSection)
1967f6f4f843SThomas Lively     writeCustomSection(*TargetFeaturesSection, Asm, Layout);
1968970d02c4SDan Gohman 
1969d934cb88SDan Gohman   // TODO: Translate the .comment section to the output.
19700ff28fa6SDerek Schuff   return W->OS.tell() - StartOffset;
197118eafb6cSDan Gohman }
197218eafb6cSDan Gohman 
197360fbc7ccSLang Hames std::unique_ptr<MCObjectWriter>
19741301a878SLang Hames llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
197518eafb6cSDan Gohman                              raw_pwrite_stream &OS) {
19760eaee545SJonas Devlieghere   return std::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
197718eafb6cSDan Gohman }
19780ff28fa6SDerek Schuff 
19790ff28fa6SDerek Schuff std::unique_ptr<MCObjectWriter>
19800ff28fa6SDerek Schuff llvm::createWasmDwoObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
19810ff28fa6SDerek Schuff                                 raw_pwrite_stream &OS,
19820ff28fa6SDerek Schuff                                 raw_pwrite_stream &DwoOS) {
19830ff28fa6SDerek Schuff   return std::make_unique<WasmObjectWriter>(std::move(MOTW), OS, DwoOS);
19840ff28fa6SDerek Schuff }
1985