118eafb6cSDan Gohman //===- lib/MC/WasmObjectWriter.cpp - Wasm File Writer ---------------------===//
218eafb6cSDan Gohman //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
618eafb6cSDan Gohman //
718eafb6cSDan Gohman //===----------------------------------------------------------------------===//
818eafb6cSDan Gohman //
918eafb6cSDan Gohman // This file implements Wasm object file writer information.
1018eafb6cSDan Gohman //
1118eafb6cSDan Gohman //===----------------------------------------------------------------------===//
1218eafb6cSDan Gohman 
1318eafb6cSDan Gohman #include "llvm/ADT/STLExtras.h"
1418eafb6cSDan Gohman #include "llvm/ADT/SmallPtrSet.h"
15264b5d9eSZachary Turner #include "llvm/BinaryFormat/Wasm.h"
16b59dff4bSBenjamin Kramer #include "llvm/BinaryFormat/WasmTraits.h"
17432a3883SNico Weber #include "llvm/Config/llvm-config.h"
1818eafb6cSDan Gohman #include "llvm/MC/MCAsmBackend.h"
1918eafb6cSDan Gohman #include "llvm/MC/MCAsmLayout.h"
2018eafb6cSDan Gohman #include "llvm/MC/MCAssembler.h"
2118eafb6cSDan Gohman #include "llvm/MC/MCContext.h"
2218eafb6cSDan Gohman #include "llvm/MC/MCExpr.h"
2318eafb6cSDan Gohman #include "llvm/MC/MCFixupKindInfo.h"
2418eafb6cSDan Gohman #include "llvm/MC/MCObjectWriter.h"
2518eafb6cSDan Gohman #include "llvm/MC/MCSectionWasm.h"
2618eafb6cSDan Gohman #include "llvm/MC/MCSymbolWasm.h"
2718eafb6cSDan Gohman #include "llvm/MC/MCValue.h"
2818eafb6cSDan Gohman #include "llvm/MC/MCWasmObjectWriter.h"
29d934cb88SDan Gohman #include "llvm/Support/Casting.h"
3018eafb6cSDan Gohman #include "llvm/Support/Debug.h"
31bcd7f777SSimon Pilgrim #include "llvm/Support/EndianStream.h"
3218eafb6cSDan Gohman #include "llvm/Support/ErrorHandling.h"
33d934cb88SDan Gohman #include "llvm/Support/LEB128.h"
3418eafb6cSDan Gohman #include "llvm/Support/StringSaver.h"
3518eafb6cSDan Gohman #include <vector>
3618eafb6cSDan Gohman 
3718eafb6cSDan Gohman using namespace llvm;
3818eafb6cSDan Gohman 
395e3d33a7SSam Clegg #define DEBUG_TYPE "mc"
4018eafb6cSDan Gohman 
4118eafb6cSDan Gohman namespace {
429e15f359SSam Clegg 
4330e1bbc1SSam Clegg // Went we ceate the indirect function table we start at 1, so that there is
4430e1bbc1SSam Clegg // and emtpy slot at 0 and therefore calling a null function pointer will trap.
4518c56a07SHeejin Ahn static const uint32_t InitialTableOffset = 1;
4630e1bbc1SSam Clegg 
47d934cb88SDan Gohman // For patching purposes, we need to remember where each section starts, both
48d934cb88SDan Gohman // for patching up the section size field, and for patching up references to
49d934cb88SDan Gohman // locations within the section.
50d934cb88SDan Gohman struct SectionBookkeeping {
51d934cb88SDan Gohman   // Where the size of the section is written.
52d934cb88SDan Gohman   uint64_t SizeOffset;
536a31a0d6SSam Clegg   // Where the section header ends (without custom section name).
546a31a0d6SSam Clegg   uint64_t PayloadOffset;
556a31a0d6SSam Clegg   // Where the contents of the section starts.
56d934cb88SDan Gohman   uint64_t ContentsOffset;
576f08c84aSSam Clegg   uint32_t Index;
58d934cb88SDan Gohman };
59d934cb88SDan Gohman 
607c395943SSam Clegg // A wasm data segment.  A wasm binary contains only a single data section
617c395943SSam Clegg // but that can contain many segments, each with their own virtual location
627c395943SSam Clegg // in memory.  Each MCSection data created by llvm is modeled as its own
637c395943SSam Clegg // wasm data segment.
647c395943SSam Clegg struct WasmDataSegment {
657c395943SSam Clegg   MCSectionWasm *Section;
66d95ed959SSam Clegg   StringRef Name;
672e150409SThomas Lively   uint32_t InitFlags;
684d135b04SWouter van Oortmerssen   uint64_t Offset;
6963ebb813SSam Clegg   uint32_t Alignment;
702e150409SThomas Lively   uint32_t LinkerFlags;
717c395943SSam Clegg   SmallVector<char, 4> Data;
727c395943SSam Clegg };
737c395943SSam Clegg 
749e15f359SSam Clegg // A wasm function to be written into the function section.
759e15f359SSam Clegg struct WasmFunction {
76da419bdbSHeejin Ahn   uint32_t SigIndex;
779e15f359SSam Clegg   const MCSymbolWasm *Sym;
789e15f359SSam Clegg };
799e15f359SSam Clegg 
809e15f359SSam Clegg // A wasm global to be written into the global section.
819e15f359SSam Clegg struct WasmGlobal {
826e7f1826SSam Clegg   wasm::WasmGlobalType Type;
839e15f359SSam Clegg   uint64_t InitialValue;
849e15f359SSam Clegg };
859e15f359SSam Clegg 
86ea7caceeSSam Clegg // Information about a single item which is part of a COMDAT.  For each data
87ea7caceeSSam Clegg // segment or function which is in the COMDAT, there is a corresponding
88ea7caceeSSam Clegg // WasmComdatEntry.
89ea7caceeSSam Clegg struct WasmComdatEntry {
90ea7caceeSSam Clegg   unsigned Kind;
91ea7caceeSSam Clegg   uint32_t Index;
92ea7caceeSSam Clegg };
93ea7caceeSSam Clegg 
946dc65e91SSam Clegg // Information about a single relocation.
956dc65e91SSam Clegg struct WasmRelocationEntry {
966dc65e91SSam Clegg   uint64_t Offset;                   // Where is the relocation.
976dc65e91SSam Clegg   const MCSymbolWasm *Symbol;        // The symbol to relocate with.
986dc65e91SSam Clegg   int64_t Addend;                    // A value to add to the symbol.
996dc65e91SSam Clegg   unsigned Type;                     // The type of the relocation.
100fe6414b0SSam Clegg   const MCSectionWasm *FixupSection; // The section the relocation is targeting.
1016dc65e91SSam Clegg 
1026dc65e91SSam Clegg   WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol,
1036dc65e91SSam Clegg                       int64_t Addend, unsigned Type,
104fe6414b0SSam Clegg                       const MCSectionWasm *FixupSection)
1056dc65e91SSam Clegg       : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type),
1066dc65e91SSam Clegg         FixupSection(FixupSection) {}
1076dc65e91SSam Clegg 
108cadcb9ebSKeno Fischer   bool hasAddend() const { return wasm::relocTypeHasAddend(Type); }
109acd7d2b0SSam Clegg 
1106dc65e91SSam Clegg   void print(raw_ostream &Out) const {
111f208f631SHeejin Ahn     Out << wasm::relocTypetoString(Type) << " Off=" << Offset
112f208f631SHeejin Ahn         << ", Sym=" << *Symbol << ", Addend=" << Addend
1137d1ff446SFangrui Song         << ", FixupSection=" << FixupSection->getName();
1146dc65e91SSam Clegg   }
115b7787fd0SSam Clegg 
116615eb470SAaron Ballman #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
117b7787fd0SSam Clegg   LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
118b7787fd0SSam Clegg #endif
1196dc65e91SSam Clegg };
1206dc65e91SSam Clegg 
12118c56a07SHeejin Ahn static const uint32_t InvalidIndex = -1;
12225d8e68bSSam Clegg 
123cfd44a2eSSam Clegg struct WasmCustomSection {
124cfd44a2eSSam Clegg 
1256a31a0d6SSam Clegg   StringRef Name;
1266a31a0d6SSam Clegg   MCSectionWasm *Section;
1276a31a0d6SSam Clegg 
1286a31a0d6SSam Clegg   uint32_t OutputContentsOffset;
1296a31a0d6SSam Clegg   uint32_t OutputIndex;
1306a31a0d6SSam Clegg 
1316a31a0d6SSam Clegg   WasmCustomSection(StringRef Name, MCSectionWasm *Section)
1326a31a0d6SSam Clegg       : Name(Name), Section(Section), OutputContentsOffset(0),
13318c56a07SHeejin Ahn         OutputIndex(InvalidIndex) {}
134cfd44a2eSSam Clegg };
135cfd44a2eSSam Clegg 
1361fb8daa6SSam Clegg #if !defined(NDEBUG)
1377f055deeSSam Clegg raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
138b7787fd0SSam Clegg   Rel.print(OS);
139b7787fd0SSam Clegg   return OS;
140b7787fd0SSam Clegg }
1411fb8daa6SSam Clegg #endif
142b7787fd0SSam Clegg 
14319e8befaSSam Clegg // Write X as an (unsigned) LEB value at offset Offset in Stream, padded
14419e8befaSSam Clegg // to allow patching.
1453b29376eSWouter van Oortmerssen template <int W>
1463b29376eSWouter van Oortmerssen void writePatchableLEB(raw_pwrite_stream &Stream, uint64_t X, uint64_t Offset) {
1473b29376eSWouter van Oortmerssen   uint8_t Buffer[W];
1483b29376eSWouter van Oortmerssen   unsigned SizeLen = encodeULEB128(X, Buffer, W);
1493b29376eSWouter van Oortmerssen   assert(SizeLen == W);
15019e8befaSSam Clegg   Stream.pwrite((char *)Buffer, SizeLen, Offset);
15119e8befaSSam Clegg }
15219e8befaSSam Clegg 
15319e8befaSSam Clegg // Write X as an signed LEB value at offset Offset in Stream, padded
15419e8befaSSam Clegg // to allow patching.
1553b29376eSWouter van Oortmerssen template <int W>
1563b29376eSWouter van Oortmerssen void writePatchableSLEB(raw_pwrite_stream &Stream, int64_t X, uint64_t Offset) {
1573b29376eSWouter van Oortmerssen   uint8_t Buffer[W];
1583b29376eSWouter van Oortmerssen   unsigned SizeLen = encodeSLEB128(X, Buffer, W);
1593b29376eSWouter van Oortmerssen   assert(SizeLen == W);
16019e8befaSSam Clegg   Stream.pwrite((char *)Buffer, SizeLen, Offset);
16119e8befaSSam Clegg }
16219e8befaSSam Clegg 
16319e8befaSSam Clegg // Write X as a plain integer value at offset Offset in Stream.
1640a6c4d8dSSam Clegg static void patchI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
16519e8befaSSam Clegg   uint8_t Buffer[4];
16619e8befaSSam Clegg   support::endian::write32le(Buffer, X);
16719e8befaSSam Clegg   Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
16819e8befaSSam Clegg }
16919e8befaSSam Clegg 
1703b29376eSWouter van Oortmerssen static void patchI64(raw_pwrite_stream &Stream, uint64_t X, uint64_t Offset) {
1713b29376eSWouter van Oortmerssen   uint8_t Buffer[8];
1723b29376eSWouter van Oortmerssen   support::endian::write64le(Buffer, X);
1733b29376eSWouter van Oortmerssen   Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
1743b29376eSWouter van Oortmerssen }
1753b29376eSWouter van Oortmerssen 
1760ff28fa6SDerek Schuff bool isDwoSection(const MCSection &Sec) {
1770ff28fa6SDerek Schuff   return Sec.getName().endswith(".dwo");
1780ff28fa6SDerek Schuff }
1790ff28fa6SDerek Schuff 
18018eafb6cSDan Gohman class WasmObjectWriter : public MCObjectWriter {
1810ff28fa6SDerek Schuff   support::endian::Writer *W;
182f17b149dSPeter Collingbourne 
18318eafb6cSDan Gohman   /// The target specific Wasm writer instance.
18418eafb6cSDan Gohman   std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
18518eafb6cSDan Gohman 
186d934cb88SDan Gohman   // Relocations for fixing up references in the code section.
187d934cb88SDan Gohman   std::vector<WasmRelocationEntry> CodeRelocations;
188d934cb88SDan Gohman   // Relocations for fixing up references in the data section.
189d934cb88SDan Gohman   std::vector<WasmRelocationEntry> DataRelocations;
190d934cb88SDan Gohman 
191d934cb88SDan Gohman   // Index values to use for fixing up call_indirect type indices.
192acd7d2b0SSam Clegg   // Maps function symbols to the index of the type of the function
193acd7d2b0SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
194d99f6078SSam Clegg   // Maps function symbols to the table element index space. Used
195d99f6078SSam Clegg   // for TABLE_INDEX relocation types (i.e. address taken functions).
196f9edbe95SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> TableIndices;
197388fb67bSPaulo Matos   // Maps function/global/table symbols to the
198388fb67bSPaulo Matos   // function/global/table/event/section index space.
1996c899ba6SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> WasmIndices;
200492f7529SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> GOTIndices;
2016c899ba6SSam Clegg   // Maps data symbols to the Wasm segment and offset/size with the segment.
2026c899ba6SSam Clegg   DenseMap<const MCSymbolWasm *, wasm::WasmDataReference> DataLocations;
2036a31a0d6SSam Clegg 
2046a31a0d6SSam Clegg   // Stores output data (index, relocations, content offset) for custom
2056a31a0d6SSam Clegg   // section.
2066a31a0d6SSam Clegg   std::vector<WasmCustomSection> CustomSections;
207cbda16ebSThomas Lively   std::unique_ptr<WasmCustomSection> ProducersSection;
208f6f4f843SThomas Lively   std::unique_ptr<WasmCustomSection> TargetFeaturesSection;
2096a31a0d6SSam Clegg   // Relocations for fixing up references in the custom sections.
2106a31a0d6SSam Clegg   DenseMap<const MCSectionWasm *, std::vector<WasmRelocationEntry>>
2116a31a0d6SSam Clegg       CustomSectionsRelocations;
212acd7d2b0SSam Clegg 
213c0d41195SSam Clegg   // Map from section to defining function symbol.
2146ccb59b3SSam Clegg   DenseMap<const MCSection *, const MCSymbol *> SectionFunctions;
2156ccb59b3SSam Clegg 
2164c41fb5aSHeejin Ahn   DenseMap<wasm::WasmSignature, uint32_t> SignatureIndices;
2174c41fb5aSHeejin Ahn   SmallVector<wasm::WasmSignature, 4> Signatures;
2186c899ba6SSam Clegg   SmallVector<WasmDataSegment, 4> DataSegments;
2199f3fe42eSSam Clegg   unsigned NumFunctionImports = 0;
2207c395943SSam Clegg   unsigned NumGlobalImports = 0;
221388fb67bSPaulo Matos   // NumTableImports is initialized to 1 to account for the hardcoded import of
222388fb67bSPaulo Matos   // __indirect_function_table
223388fb67bSPaulo Matos   unsigned NumTableImports = 1;
224da419bdbSHeejin Ahn   unsigned NumEventImports = 0;
2257e1c3345SChandler Carruth   uint32_t SectionCount = 0;
226d934cb88SDan Gohman 
2270ff28fa6SDerek Schuff   enum class DwoMode {
2280ff28fa6SDerek Schuff     AllSections,
2290ff28fa6SDerek Schuff     NonDwoOnly,
2300ff28fa6SDerek Schuff     DwoOnly,
2310ff28fa6SDerek Schuff   };
2320ff28fa6SDerek Schuff   bool IsSplitDwarf = false;
2330ff28fa6SDerek Schuff   raw_pwrite_stream *OS = nullptr;
2340ff28fa6SDerek Schuff   raw_pwrite_stream *DwoOS = nullptr;
2350ff28fa6SDerek Schuff 
2360ff28fa6SDerek Schuff   // TargetObjectWriter wranppers.
23718eafb6cSDan Gohman   bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
238da84b688SDan Gohman   bool isEmscripten() const { return TargetObjectWriter->isEmscripten(); }
23918eafb6cSDan Gohman 
2402322a937SSam Clegg   void startSection(SectionBookkeeping &Section, unsigned SectionId);
2412322a937SSam Clegg   void startCustomSection(SectionBookkeeping &Section, StringRef Name);
242d934cb88SDan Gohman   void endSection(SectionBookkeeping &Section);
243d934cb88SDan Gohman 
24418eafb6cSDan Gohman public:
2451301a878SLang Hames   WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
2460ff28fa6SDerek Schuff                    raw_pwrite_stream &OS_)
2470ff28fa6SDerek Schuff       : TargetObjectWriter(std::move(MOTW)), OS(&OS_) {}
2480ff28fa6SDerek Schuff 
2490ff28fa6SDerek Schuff   WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
2500ff28fa6SDerek Schuff                    raw_pwrite_stream &OS_, raw_pwrite_stream &DwoOS_)
2510ff28fa6SDerek Schuff       : TargetObjectWriter(std::move(MOTW)), IsSplitDwarf(true), OS(&OS_),
2520ff28fa6SDerek Schuff         DwoOS(&DwoOS_) {}
25318eafb6cSDan Gohman 
2540917c9e4SDan Gohman private:
255acd7d2b0SSam Clegg   void reset() override {
256acd7d2b0SSam Clegg     CodeRelocations.clear();
257acd7d2b0SSam Clegg     DataRelocations.clear();
258acd7d2b0SSam Clegg     TypeIndices.clear();
2596c899ba6SSam Clegg     WasmIndices.clear();
260492f7529SSam Clegg     GOTIndices.clear();
261f9edbe95SSam Clegg     TableIndices.clear();
2626c899ba6SSam Clegg     DataLocations.clear();
263cbda16ebSThomas Lively     CustomSections.clear();
264cbda16ebSThomas Lively     ProducersSection.reset();
265f6f4f843SThomas Lively     TargetFeaturesSection.reset();
2666a31a0d6SSam Clegg     CustomSectionsRelocations.clear();
267da419bdbSHeejin Ahn     SignatureIndices.clear();
268da419bdbSHeejin Ahn     Signatures.clear();
2696c899ba6SSam Clegg     DataSegments.clear();
2706ccb59b3SSam Clegg     SectionFunctions.clear();
2719f3fe42eSSam Clegg     NumFunctionImports = 0;
2727c395943SSam Clegg     NumGlobalImports = 0;
273388fb67bSPaulo Matos     NumTableImports = 1;
274105bdc25SSam Clegg     MCObjectWriter::reset();
275acd7d2b0SSam Clegg   }
276acd7d2b0SSam Clegg 
27718eafb6cSDan Gohman   void writeHeader(const MCAssembler &Asm);
27818eafb6cSDan Gohman 
27918eafb6cSDan Gohman   void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
28018eafb6cSDan Gohman                         const MCFragment *Fragment, const MCFixup &Fixup,
281ceecfe5bSRafael Espindola                         MCValue Target, uint64_t &FixedValue) override;
28218eafb6cSDan Gohman 
28318eafb6cSDan Gohman   void executePostLayoutBinding(MCAssembler &Asm,
28418eafb6cSDan Gohman                                 const MCAsmLayout &Layout) override;
2850ff28fa6SDerek Schuff   void prepareImports(SmallVectorImpl<wasm::WasmImport> &Imports,
2860ff28fa6SDerek Schuff                       MCAssembler &Asm, const MCAsmLayout &Layout);
287438390faSPeter Collingbourne   uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
2889e15f359SSam Clegg 
2890ff28fa6SDerek Schuff   uint64_t writeOneObject(MCAssembler &Asm, const MCAsmLayout &Layout,
2900ff28fa6SDerek Schuff                           DwoMode Mode);
2910ff28fa6SDerek Schuff 
292b7787fd0SSam Clegg   void writeString(const StringRef Str) {
2930ff28fa6SDerek Schuff     encodeULEB128(Str.size(), W->OS);
2940ff28fa6SDerek Schuff     W->OS << Str;
295b7787fd0SSam Clegg   }
296b7787fd0SSam Clegg 
2970a6c4d8dSSam Clegg   void writeI32(int32_t val) {
2980a6c4d8dSSam Clegg     char Buffer[4];
2990a6c4d8dSSam Clegg     support::endian::write32le(Buffer, val);
3000ff28fa6SDerek Schuff     W->OS.write(Buffer, sizeof(Buffer));
3010a6c4d8dSSam Clegg   }
3020a6c4d8dSSam Clegg 
3030a6c4d8dSSam Clegg   void writeI64(int64_t val) {
3040a6c4d8dSSam Clegg     char Buffer[8];
3050a6c4d8dSSam Clegg     support::endian::write64le(Buffer, val);
3060ff28fa6SDerek Schuff     W->OS.write(Buffer, sizeof(Buffer));
3070a6c4d8dSSam Clegg   }
3080a6c4d8dSSam Clegg 
3090ff28fa6SDerek Schuff   void writeValueType(wasm::ValType Ty) { W->OS << static_cast<char>(Ty); }
3109e15f359SSam Clegg 
3114c41fb5aSHeejin Ahn   void writeTypeSection(ArrayRef<wasm::WasmSignature> Signatures);
3124d135b04SWouter van Oortmerssen   void writeImportSection(ArrayRef<wasm::WasmImport> Imports, uint64_t DataSize,
313f950b24aSSam Clegg                           uint32_t NumElements);
314457fb0b4SSam Clegg   void writeFunctionSection(ArrayRef<WasmFunction> Functions);
3158defa952SSam Clegg   void writeExportSection(ArrayRef<wasm::WasmExport> Exports);
316457fb0b4SSam Clegg   void writeElemSection(ArrayRef<uint32_t> TableElems);
317fef8de66SThomas Lively   void writeDataCountSection();
318e49584a3SSam Clegg   uint32_t writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
319457fb0b4SSam Clegg                             ArrayRef<WasmFunction> Functions);
320e49584a3SSam Clegg   uint32_t writeDataSection(const MCAsmLayout &Layout);
321da419bdbSHeejin Ahn   void writeEventSection(ArrayRef<wasm::WasmEventType> Events);
3220a6c4d8dSSam Clegg   void writeGlobalSection(ArrayRef<wasm::WasmGlobal> Globals);
323388fb67bSPaulo Matos   void writeTableSection(ArrayRef<wasm::WasmTable> Tables);
3246f08c84aSSam Clegg   void writeRelocSection(uint32_t SectionIndex, StringRef Name,
325f77dc2a8SSam Clegg                          std::vector<WasmRelocationEntry> &Relocations);
32631a2c809SSam Clegg   void writeLinkingMetaDataSection(
32786b4a09aSSam Clegg       ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
328ea7caceeSSam Clegg       ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
329ea7caceeSSam Clegg       const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats);
330cbda16ebSThomas Lively   void writeCustomSection(WasmCustomSection &CustomSection,
331cbda16ebSThomas Lively                           const MCAssembler &Asm, const MCAsmLayout &Layout);
3326a31a0d6SSam Clegg   void writeCustomRelocSections();
3336a31a0d6SSam Clegg   void
3346a31a0d6SSam Clegg   updateCustomSectionRelocations(const SmallVector<WasmFunction, 4> &Functions,
3356a31a0d6SSam Clegg                                  const MCAsmLayout &Layout);
336acd7d2b0SSam Clegg 
3377ee758d6SSam Clegg   uint64_t getProvisionalValue(const WasmRelocationEntry &RelEntry,
3387ee758d6SSam Clegg                                const MCAsmLayout &Layout);
339acd7d2b0SSam Clegg   void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
3407ee758d6SSam Clegg                         uint64_t ContentsOffset, const MCAsmLayout &Layout);
341acd7d2b0SSam Clegg 
342acd7d2b0SSam Clegg   uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
3435e3d33a7SSam Clegg   uint32_t getFunctionType(const MCSymbolWasm &Symbol);
344da419bdbSHeejin Ahn   uint32_t getEventType(const MCSymbolWasm &Symbol);
34538b12f5eSHeejin Ahn   void registerFunctionType(const MCSymbolWasm &Symbol);
34638b12f5eSHeejin Ahn   void registerEventType(const MCSymbolWasm &Symbol);
34718eafb6cSDan Gohman };
3489e15f359SSam Clegg 
34918eafb6cSDan Gohman } // end anonymous namespace
35018eafb6cSDan Gohman 
351d934cb88SDan Gohman // Write out a section header and a patchable section size field.
352d934cb88SDan Gohman void WasmObjectWriter::startSection(SectionBookkeeping &Section,
3532322a937SSam Clegg                                     unsigned SectionId) {
354d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "startSection " << SectionId << "\n");
3550ff28fa6SDerek Schuff   W->OS << char(SectionId);
356d934cb88SDan Gohman 
3570ff28fa6SDerek Schuff   Section.SizeOffset = W->OS.tell();
358d934cb88SDan Gohman 
359d934cb88SDan Gohman   // The section size. We don't know the size yet, so reserve enough space
360d934cb88SDan Gohman   // for any 32-bit value; we'll patch it later.
3610ff28fa6SDerek Schuff   encodeULEB128(0, W->OS, 5);
362d934cb88SDan Gohman 
363d934cb88SDan Gohman   // The position where the section starts, for measuring its size.
3640ff28fa6SDerek Schuff   Section.ContentsOffset = W->OS.tell();
3650ff28fa6SDerek Schuff   Section.PayloadOffset = W->OS.tell();
3666f08c84aSSam Clegg   Section.Index = SectionCount++;
367d934cb88SDan Gohman }
3682322a937SSam Clegg 
3692322a937SSam Clegg void WasmObjectWriter::startCustomSection(SectionBookkeeping &Section,
3702322a937SSam Clegg                                           StringRef Name) {
371d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "startCustomSection " << Name << "\n");
3722322a937SSam Clegg   startSection(Section, wasm::WASM_SEC_CUSTOM);
3736a31a0d6SSam Clegg 
3746a31a0d6SSam Clegg   // The position where the section header ends, for measuring its size.
3750ff28fa6SDerek Schuff   Section.PayloadOffset = W->OS.tell();
3766a31a0d6SSam Clegg 
3772322a937SSam Clegg   // Custom sections in wasm also have a string identifier.
3782322a937SSam Clegg   writeString(Name);
3796a31a0d6SSam Clegg 
3806a31a0d6SSam Clegg   // The position where the custom section starts.
3810ff28fa6SDerek Schuff   Section.ContentsOffset = W->OS.tell();
382d934cb88SDan Gohman }
383d934cb88SDan Gohman 
384d934cb88SDan Gohman // Now that the section is complete and we know how big it is, patch up the
385d934cb88SDan Gohman // section size field at the start of the section.
386d934cb88SDan Gohman void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
3870ff28fa6SDerek Schuff   uint64_t Size = W->OS.tell();
388c0affde8SSam Clegg   // /dev/null doesn't support seek/tell and can report offset of 0.
389c0affde8SSam Clegg   // Simply skip this patching in that case.
390c0affde8SSam Clegg   if (!Size)
391c0affde8SSam Clegg     return;
392c0affde8SSam Clegg 
393c0affde8SSam Clegg   Size -= Section.PayloadOffset;
394d934cb88SDan Gohman   if (uint32_t(Size) != Size)
395d934cb88SDan Gohman     report_fatal_error("section size does not fit in a uint32_t");
396d934cb88SDan Gohman 
397d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "endSection size=" << Size << "\n");
398d934cb88SDan Gohman 
399d934cb88SDan Gohman   // Write the final section size to the payload_len field, which follows
400d934cb88SDan Gohman   // the section id byte.
4010ff28fa6SDerek Schuff   writePatchableLEB<5>(static_cast<raw_pwrite_stream &>(W->OS), Size,
402f17b149dSPeter Collingbourne                        Section.SizeOffset);
403d934cb88SDan Gohman }
404d934cb88SDan Gohman 
40518eafb6cSDan Gohman // Emit the Wasm header.
40618eafb6cSDan Gohman void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
4070ff28fa6SDerek Schuff   W->OS.write(wasm::WasmMagic, sizeof(wasm::WasmMagic));
4080ff28fa6SDerek Schuff   W->write<uint32_t>(wasm::WasmVersion);
40918eafb6cSDan Gohman }
41018eafb6cSDan Gohman 
41118eafb6cSDan Gohman void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
41218eafb6cSDan Gohman                                                 const MCAsmLayout &Layout) {
4136ccb59b3SSam Clegg   // Build a map of sections to the function that defines them, for use
4146ccb59b3SSam Clegg   // in recordRelocation.
4156ccb59b3SSam Clegg   for (const MCSymbol &S : Asm.symbols()) {
4166ccb59b3SSam Clegg     const auto &WS = static_cast<const MCSymbolWasm &>(S);
4176ccb59b3SSam Clegg     if (WS.isDefined() && WS.isFunction() && !WS.isVariable()) {
4186ccb59b3SSam Clegg       const auto &Sec = static_cast<const MCSectionWasm &>(S.getSection());
4196ccb59b3SSam Clegg       auto Pair = SectionFunctions.insert(std::make_pair(&Sec, &S));
4206ccb59b3SSam Clegg       if (!Pair.second)
4216ccb59b3SSam Clegg         report_fatal_error("section already has a defining function: " +
4227d1ff446SFangrui Song                            Sec.getName());
4236ccb59b3SSam Clegg     }
4246ccb59b3SSam Clegg   }
42518eafb6cSDan Gohman }
42618eafb6cSDan Gohman 
42718eafb6cSDan Gohman void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
42818eafb6cSDan Gohman                                         const MCAsmLayout &Layout,
42918eafb6cSDan Gohman                                         const MCFragment *Fragment,
43018eafb6cSDan Gohman                                         const MCFixup &Fixup, MCValue Target,
431ceecfe5bSRafael Espindola                                         uint64_t &FixedValue) {
432ecc5e808SSam Clegg   // The WebAssembly backend should never generate FKF_IsPCRel fixups
433e828ce1bSFangrui Song   assert(!(Asm.getBackend().getFixupKindInfo(Fixup.getKind()).Flags &
434ecc5e808SSam Clegg            MCFixupKindInfo::FKF_IsPCRel));
435ecc5e808SSam Clegg 
436fe6414b0SSam Clegg   const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
437d934cb88SDan Gohman   uint64_t C = Target.getConstant();
438d934cb88SDan Gohman   uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
439d934cb88SDan Gohman   MCContext &Ctx = Asm.getContext();
440d934cb88SDan Gohman 
441d934cb88SDan Gohman   if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
442ecc5e808SSam Clegg     // To get here the A - B expression must have failed evaluateAsRelocatable.
443ecc5e808SSam Clegg     // This means either A or B must be undefined and in WebAssembly we can't
444ecc5e808SSam Clegg     // support either of those cases.
445ecc5e808SSam Clegg     const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
446d934cb88SDan Gohman     Ctx.reportError(
447d934cb88SDan Gohman         Fixup.getLoc(),
448d934cb88SDan Gohman         Twine("symbol '") + SymB.getName() +
449ecc5e808SSam Clegg             "': unsupported subtraction expression used in relocation.");
450d934cb88SDan Gohman     return;
451d934cb88SDan Gohman   }
452d934cb88SDan Gohman 
453d934cb88SDan Gohman   // We either rejected the fixup or folded B into C at this point.
454d934cb88SDan Gohman   const MCSymbolRefExpr *RefA = Target.getSymA();
455ecc5e808SSam Clegg   const auto *SymA = cast<MCSymbolWasm>(&RefA->getSymbol());
456d934cb88SDan Gohman 
4573ea1c62cSSam Clegg   // The .init_array isn't translated as data, so don't do relocations in it.
4587d1ff446SFangrui Song   if (FixupSection.getName().startswith(".init_array")) {
4593ea1c62cSSam Clegg     SymA->setUsedInInitArray();
4603ea1c62cSSam Clegg     return;
4613ea1c62cSSam Clegg   }
4623ea1c62cSSam Clegg 
463ecc5e808SSam Clegg   if (SymA->isVariable()) {
464d934cb88SDan Gohman     const MCExpr *Expr = SymA->getVariableValue();
4657ee758d6SSam Clegg     if (const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr))
4666ad8f190SSam Clegg       if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
4676ad8f190SSam Clegg         llvm_unreachable("weakref used in reloc not yet implemented");
468d934cb88SDan Gohman   }
469d934cb88SDan Gohman 
470d934cb88SDan Gohman   // Put any constant offset in an addend. Offsets can be negative, and
471d934cb88SDan Gohman   // LLVM expects wrapping, in contrast to wasm's immediates which can't
472d934cb88SDan Gohman   // be negative and don't wrap.
473d934cb88SDan Gohman   FixedValue = 0;
474d934cb88SDan Gohman 
475a5e175c6SSam Clegg   unsigned Type = TargetObjectWriter->getRelocType(Target, Fixup);
4769d24fb7fSSam Clegg 
4774d57fbd0SSam Clegg   // Absolute offset within a section or a function.
4784d57fbd0SSam Clegg   // Currently only supported for for metadata sections.
4794d57fbd0SSam Clegg   // See: test/MC/WebAssembly/blockaddress.ll
480d1152a26SSam Clegg   if (Type == wasm::R_WASM_FUNCTION_OFFSET_I32 ||
481d1152a26SSam Clegg       Type == wasm::R_WASM_SECTION_OFFSET_I32) {
4824d57fbd0SSam Clegg     if (!FixupSection.getKind().isMetadata())
4834d57fbd0SSam Clegg       report_fatal_error("relocations for function or section offsets are "
4844d57fbd0SSam Clegg                          "only supported in metadata sections");
4854d57fbd0SSam Clegg 
4864d57fbd0SSam Clegg     const MCSymbol *SectionSymbol = nullptr;
4874d57fbd0SSam Clegg     const MCSection &SecA = SymA->getSection();
4884d57fbd0SSam Clegg     if (SecA.getKind().isText())
4896ccb59b3SSam Clegg       SectionSymbol = SectionFunctions.find(&SecA)->second;
4904d57fbd0SSam Clegg     else
4914d57fbd0SSam Clegg       SectionSymbol = SecA.getBeginSymbol();
4924d57fbd0SSam Clegg     if (!SectionSymbol)
4934d57fbd0SSam Clegg       report_fatal_error("section symbol is required for relocation");
4944d57fbd0SSam Clegg 
4954d57fbd0SSam Clegg     C += Layout.getSymbolOffset(*SymA);
4964d57fbd0SSam Clegg     SymA = cast<MCSymbolWasm>(SectionSymbol);
4974d57fbd0SSam Clegg   }
4984d57fbd0SSam Clegg 
499d1152a26SSam Clegg   // Relocation other than R_WASM_TYPE_INDEX_LEB are required to be
5004d57fbd0SSam Clegg   // against a named symbol.
501d1152a26SSam Clegg   if (Type != wasm::R_WASM_TYPE_INDEX_LEB) {
5024d57fbd0SSam Clegg     if (SymA->getName().empty())
5034d57fbd0SSam Clegg       report_fatal_error("relocations against un-named temporaries are not yet "
5044d57fbd0SSam Clegg                          "supported by wasm");
5054d57fbd0SSam Clegg 
5064d57fbd0SSam Clegg     SymA->setUsedInReloc();
5074d57fbd0SSam Clegg   }
508ae03c1e7SSam Clegg 
509492f7529SSam Clegg   if (RefA->getKind() == MCSymbolRefExpr::VK_GOT)
510492f7529SSam Clegg     SymA->setUsedInGOT();
511492f7529SSam Clegg 
512d934cb88SDan Gohman   WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
513d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
514d934cb88SDan Gohman 
5156a31a0d6SSam Clegg   if (FixupSection.isWasmData()) {
516d934cb88SDan Gohman     DataRelocations.push_back(Rec);
5176a31a0d6SSam Clegg   } else if (FixupSection.getKind().isText()) {
51812fd3da9SSam Clegg     CodeRelocations.push_back(Rec);
5196a31a0d6SSam Clegg   } else if (FixupSection.getKind().isMetadata()) {
5206a31a0d6SSam Clegg     CustomSectionsRelocations[&FixupSection].push_back(Rec);
5216a31a0d6SSam Clegg   } else {
52212fd3da9SSam Clegg     llvm_unreachable("unexpected section type");
523d934cb88SDan Gohman   }
5246a31a0d6SSam Clegg }
525d934cb88SDan Gohman 
526d934cb88SDan Gohman // Compute a value to write into the code at the location covered
52760ec3034SSam Clegg // by RelEntry. This value isn't used by the static linker; it just serves
52860ec3034SSam Clegg // to make the object format more readable and more likely to be directly
52960ec3034SSam Clegg // useable.
5303b29376eSWouter van Oortmerssen uint64_t
5317ee758d6SSam Clegg WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry,
5327ee758d6SSam Clegg                                       const MCAsmLayout &Layout) {
53348139ebcSWouter van Oortmerssen   if ((RelEntry.Type == wasm::R_WASM_GLOBAL_INDEX_LEB ||
53448139ebcSWouter van Oortmerssen        RelEntry.Type == wasm::R_WASM_GLOBAL_INDEX_I32) &&
53548139ebcSWouter van Oortmerssen       !RelEntry.Symbol->isGlobal()) {
536492f7529SSam Clegg     assert(GOTIndices.count(RelEntry.Symbol) > 0 && "symbol not found in GOT index space");
537492f7529SSam Clegg     return GOTIndices[RelEntry.Symbol];
538492f7529SSam Clegg   }
539492f7529SSam Clegg 
54060ec3034SSam Clegg   switch (RelEntry.Type) {
5412a7cac93SSam Clegg   case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
542d1152a26SSam Clegg   case wasm::R_WASM_TABLE_INDEX_SLEB:
543cc1b9b68SWouter van Oortmerssen   case wasm::R_WASM_TABLE_INDEX_SLEB64:
544cc1b9b68SWouter van Oortmerssen   case wasm::R_WASM_TABLE_INDEX_I32:
545cc1b9b68SWouter van Oortmerssen   case wasm::R_WASM_TABLE_INDEX_I64: {
546f9edbe95SSam Clegg     // Provisional value is table address of the resolved symbol itself
5477ee758d6SSam Clegg     const MCSymbolWasm *Base =
5487ee758d6SSam Clegg         cast<MCSymbolWasm>(Layout.getBaseSymbol(*RelEntry.Symbol));
5497ee758d6SSam Clegg     assert(Base->isFunction());
55081443ac1SSam Clegg     if (RelEntry.Type == wasm::R_WASM_TABLE_INDEX_REL_SLEB)
5517ee758d6SSam Clegg       return TableIndices[Base] - InitialTableOffset;
55281443ac1SSam Clegg     else
5537ee758d6SSam Clegg       return TableIndices[Base];
554f9edbe95SSam Clegg   }
555d1152a26SSam Clegg   case wasm::R_WASM_TYPE_INDEX_LEB:
5566c899ba6SSam Clegg     // Provisional value is same as the index
55760ec3034SSam Clegg     return getRelocationIndexValue(RelEntry);
558d1152a26SSam Clegg   case wasm::R_WASM_FUNCTION_INDEX_LEB:
559d1152a26SSam Clegg   case wasm::R_WASM_GLOBAL_INDEX_LEB:
56048139ebcSWouter van Oortmerssen   case wasm::R_WASM_GLOBAL_INDEX_I32:
561d1152a26SSam Clegg   case wasm::R_WASM_EVENT_INDEX_LEB:
56269e2797eSPaulo Matos   case wasm::R_WASM_TABLE_NUMBER_LEB:
563da419bdbSHeejin Ahn     // Provisional value is function/global/event Wasm index
564492f7529SSam Clegg     assert(WasmIndices.count(RelEntry.Symbol) > 0 && "symbol not found in wasm index space");
5656c899ba6SSam Clegg     return WasmIndices[RelEntry.Symbol];
566d1152a26SSam Clegg   case wasm::R_WASM_FUNCTION_OFFSET_I32:
567d1152a26SSam Clegg   case wasm::R_WASM_SECTION_OFFSET_I32: {
5686a31a0d6SSam Clegg     const auto &Section =
5696a31a0d6SSam Clegg         static_cast<const MCSectionWasm &>(RelEntry.Symbol->getSection());
5706a31a0d6SSam Clegg     return Section.getSectionOffset() + RelEntry.Addend;
5716a31a0d6SSam Clegg   }
572d1152a26SSam Clegg   case wasm::R_WASM_MEMORY_ADDR_LEB:
5733b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_LEB64:
5743b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_SLEB:
5753b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_SLEB64:
5762a7cac93SSam Clegg   case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
5773b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_REL_SLEB64:
5783b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_I32:
579*a28a4662SSam Clegg   case wasm::R_WASM_MEMORY_ADDR_I64:
580*a28a4662SSam Clegg   case wasm::R_WASM_MEMORY_ADDR_TLS_SLEB: {
5819c7b5808SDominic Chen     // Provisional value is address of the global plus the offset
5827ee758d6SSam Clegg     const MCSymbolWasm *Base =
5837ee758d6SSam Clegg         cast<MCSymbolWasm>(Layout.getBaseSymbol(*RelEntry.Symbol));
584270ed1b3SSam Clegg     // For undefined symbols, use zero
5857ee758d6SSam Clegg     if (!Base->isDefined())
586270ed1b3SSam Clegg       return 0;
5879c7b5808SDominic Chen     const wasm::WasmDataReference &BaseRef = DataLocations[Base],
5889c7b5808SDominic Chen                                   &SymRef = DataLocations[RelEntry.Symbol];
5899c7b5808SDominic Chen     const WasmDataSegment &Segment = DataSegments[BaseRef.Segment];
590d934cb88SDan Gohman     // Ignore overflow. LLVM allows address arithmetic to silently wrap.
5919c7b5808SDominic Chen     return Segment.Offset + BaseRef.Offset + SymRef.Offset + RelEntry.Addend;
59260ec3034SSam Clegg   }
59360ec3034SSam Clegg   default:
59460ec3034SSam Clegg     llvm_unreachable("invalid relocation type");
59560ec3034SSam Clegg   }
596d934cb88SDan Gohman }
597d934cb88SDan Gohman 
598759631c7SSam Clegg static void addData(SmallVectorImpl<char> &DataBytes,
59963ebb813SSam Clegg                     MCSectionWasm &DataSection) {
6007d1ff446SFangrui Song   LLVM_DEBUG(errs() << "addData: " << DataSection.getName() << "\n");
601759631c7SSam Clegg 
60263ebb813SSam Clegg   DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
60363ebb813SSam Clegg 
604759631c7SSam Clegg   for (const MCFragment &Frag : DataSection) {
605759631c7SSam Clegg     if (Frag.hasInstructions())
606759631c7SSam Clegg       report_fatal_error("only data supported in data sections");
607759631c7SSam Clegg 
608759631c7SSam Clegg     if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
609759631c7SSam Clegg       if (Align->getValueSize() != 1)
610759631c7SSam Clegg         report_fatal_error("only byte values supported for alignment");
611759631c7SSam Clegg       // If nops are requested, use zeros, as this is the data section.
612759631c7SSam Clegg       uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
613f208f631SHeejin Ahn       uint64_t Size =
614f208f631SHeejin Ahn           std::min<uint64_t>(alignTo(DataBytes.size(), Align->getAlignment()),
615f208f631SHeejin Ahn                              DataBytes.size() + Align->getMaxBytesToEmit());
616759631c7SSam Clegg       DataBytes.resize(Size, Value);
617759631c7SSam Clegg     } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
618588fad4dSNirav Dave       int64_t NumValues;
619588fad4dSNirav Dave       if (!Fill->getNumValues().evaluateAsAbsolute(NumValues))
620d707c370SRafael Espindola         llvm_unreachable("The fill should be an assembler constant");
621588fad4dSNirav Dave       DataBytes.insert(DataBytes.end(), Fill->getValueSize() * NumValues,
622588fad4dSNirav Dave                        Fill->getValue());
62324faf859SHeejin Ahn     } else if (auto *LEB = dyn_cast<MCLEBFragment>(&Frag)) {
62424faf859SHeejin Ahn       const SmallVectorImpl<char> &Contents = LEB->getContents();
62524faf859SHeejin Ahn       DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
626759631c7SSam Clegg     } else {
627759631c7SSam Clegg       const auto &DataFrag = cast<MCDataFragment>(Frag);
628759631c7SSam Clegg       const SmallVectorImpl<char> &Contents = DataFrag.getContents();
629759631c7SSam Clegg       DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
630759631c7SSam Clegg     }
631759631c7SSam Clegg   }
632759631c7SSam Clegg 
633d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
634759631c7SSam Clegg }
635759631c7SSam Clegg 
63660ec3034SSam Clegg uint32_t
63760ec3034SSam Clegg WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
638d1152a26SSam Clegg   if (RelEntry.Type == wasm::R_WASM_TYPE_INDEX_LEB) {
639b7787fd0SSam Clegg     if (!TypeIndices.count(RelEntry.Symbol))
640b7787fd0SSam Clegg       report_fatal_error("symbol not found in type index space: " +
641b7787fd0SSam Clegg                          RelEntry.Symbol->getName());
642acd7d2b0SSam Clegg     return TypeIndices[RelEntry.Symbol];
643acd7d2b0SSam Clegg   }
64460ec3034SSam Clegg 
64525d8e68bSSam Clegg   return RelEntry.Symbol->getIndex();
646acd7d2b0SSam Clegg }
647acd7d2b0SSam Clegg 
648d934cb88SDan Gohman // Apply the portions of the relocation records that we can handle ourselves
649d934cb88SDan Gohman // directly.
650acd7d2b0SSam Clegg void WasmObjectWriter::applyRelocations(
6517ee758d6SSam Clegg     ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset,
6527ee758d6SSam Clegg     const MCAsmLayout &Layout) {
6530ff28fa6SDerek Schuff   auto &Stream = static_cast<raw_pwrite_stream &>(W->OS);
654d934cb88SDan Gohman   for (const WasmRelocationEntry &RelEntry : Relocations) {
655d934cb88SDan Gohman     uint64_t Offset = ContentsOffset +
656d934cb88SDan Gohman                       RelEntry.FixupSection->getSectionOffset() +
657d934cb88SDan Gohman                       RelEntry.Offset;
658d934cb88SDan Gohman 
659d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
6607ee758d6SSam Clegg     auto Value = getProvisionalValue(RelEntry, Layout);
66160ec3034SSam Clegg 
662acd7d2b0SSam Clegg     switch (RelEntry.Type) {
663d1152a26SSam Clegg     case wasm::R_WASM_FUNCTION_INDEX_LEB:
664d1152a26SSam Clegg     case wasm::R_WASM_TYPE_INDEX_LEB:
665d1152a26SSam Clegg     case wasm::R_WASM_GLOBAL_INDEX_LEB:
666d1152a26SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_LEB:
667d1152a26SSam Clegg     case wasm::R_WASM_EVENT_INDEX_LEB:
66869e2797eSPaulo Matos     case wasm::R_WASM_TABLE_NUMBER_LEB:
6693b29376eSWouter van Oortmerssen       writePatchableLEB<5>(Stream, Value, Offset);
6703b29376eSWouter van Oortmerssen       break;
6713b29376eSWouter van Oortmerssen     case wasm::R_WASM_MEMORY_ADDR_LEB64:
6723b29376eSWouter van Oortmerssen       writePatchableLEB<10>(Stream, Value, Offset);
673d934cb88SDan Gohman       break;
674d1152a26SSam Clegg     case wasm::R_WASM_TABLE_INDEX_I32:
675d1152a26SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_I32:
676d1152a26SSam Clegg     case wasm::R_WASM_FUNCTION_OFFSET_I32:
677d1152a26SSam Clegg     case wasm::R_WASM_SECTION_OFFSET_I32:
67848139ebcSWouter van Oortmerssen     case wasm::R_WASM_GLOBAL_INDEX_I32:
6790a6c4d8dSSam Clegg       patchI32(Stream, Value, Offset);
680d934cb88SDan Gohman       break;
681cc1b9b68SWouter van Oortmerssen     case wasm::R_WASM_TABLE_INDEX_I64:
6823b29376eSWouter van Oortmerssen     case wasm::R_WASM_MEMORY_ADDR_I64:
6833b29376eSWouter van Oortmerssen       patchI64(Stream, Value, Offset);
6843b29376eSWouter van Oortmerssen       break;
685d1152a26SSam Clegg     case wasm::R_WASM_TABLE_INDEX_SLEB:
6862a7cac93SSam Clegg     case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
687d1152a26SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_SLEB:
6882a7cac93SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
689*a28a4662SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_TLS_SLEB:
6903b29376eSWouter van Oortmerssen       writePatchableSLEB<5>(Stream, Value, Offset);
6913b29376eSWouter van Oortmerssen       break;
692cc1b9b68SWouter van Oortmerssen     case wasm::R_WASM_TABLE_INDEX_SLEB64:
6933b29376eSWouter van Oortmerssen     case wasm::R_WASM_MEMORY_ADDR_SLEB64:
6943b29376eSWouter van Oortmerssen     case wasm::R_WASM_MEMORY_ADDR_REL_SLEB64:
6953b29376eSWouter van Oortmerssen       writePatchableSLEB<10>(Stream, Value, Offset);
69660ec3034SSam Clegg       break;
697d934cb88SDan Gohman     default:
6989d24fb7fSSam Clegg       llvm_unreachable("invalid relocation type");
699d934cb88SDan Gohman     }
700d934cb88SDan Gohman   }
70118eafb6cSDan Gohman }
70218eafb6cSDan Gohman 
7034c41fb5aSHeejin Ahn void WasmObjectWriter::writeTypeSection(
7044c41fb5aSHeejin Ahn     ArrayRef<wasm::WasmSignature> Signatures) {
705da419bdbSHeejin Ahn   if (Signatures.empty())
7069e15f359SSam Clegg     return;
7079e15f359SSam Clegg 
7089e15f359SSam Clegg   SectionBookkeeping Section;
7099e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_TYPE);
7109e15f359SSam Clegg 
7110ff28fa6SDerek Schuff   encodeULEB128(Signatures.size(), W->OS);
7129e15f359SSam Clegg 
7134c41fb5aSHeejin Ahn   for (const wasm::WasmSignature &Sig : Signatures) {
7140ff28fa6SDerek Schuff     W->OS << char(wasm::WASM_TYPE_FUNC);
7150ff28fa6SDerek Schuff     encodeULEB128(Sig.Params.size(), W->OS);
716da419bdbSHeejin Ahn     for (wasm::ValType Ty : Sig.Params)
7179e15f359SSam Clegg       writeValueType(Ty);
7180ff28fa6SDerek Schuff     encodeULEB128(Sig.Returns.size(), W->OS);
719da419bdbSHeejin Ahn     for (wasm::ValType Ty : Sig.Returns)
7209e15f359SSam Clegg       writeValueType(Ty);
7219e15f359SSam Clegg   }
7229e15f359SSam Clegg 
7239e15f359SSam Clegg   endSection(Section);
7249e15f359SSam Clegg }
7259e15f359SSam Clegg 
7268defa952SSam Clegg void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports,
7274d135b04SWouter van Oortmerssen                                           uint64_t DataSize,
728f950b24aSSam Clegg                                           uint32_t NumElements) {
7299e15f359SSam Clegg   if (Imports.empty())
7309e15f359SSam Clegg     return;
7319e15f359SSam Clegg 
7324d135b04SWouter van Oortmerssen   uint64_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
733f950b24aSSam Clegg 
7349e15f359SSam Clegg   SectionBookkeeping Section;
7359e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_IMPORT);
7369e15f359SSam Clegg 
7370ff28fa6SDerek Schuff   encodeULEB128(Imports.size(), W->OS);
7388defa952SSam Clegg   for (const wasm::WasmImport &Import : Imports) {
7398defa952SSam Clegg     writeString(Import.Module);
7408defa952SSam Clegg     writeString(Import.Field);
7410ff28fa6SDerek Schuff     W->OS << char(Import.Kind);
7429e15f359SSam Clegg 
7439e15f359SSam Clegg     switch (Import.Kind) {
7449e15f359SSam Clegg     case wasm::WASM_EXTERNAL_FUNCTION:
7450ff28fa6SDerek Schuff       encodeULEB128(Import.SigIndex, W->OS);
7469e15f359SSam Clegg       break;
7479e15f359SSam Clegg     case wasm::WASM_EXTERNAL_GLOBAL:
7480ff28fa6SDerek Schuff       W->OS << char(Import.Global.Type);
7490ff28fa6SDerek Schuff       W->OS << char(Import.Global.Mutable ? 1 : 0);
7509e15f359SSam Clegg       break;
751f950b24aSSam Clegg     case wasm::WASM_EXTERNAL_MEMORY:
7520ff28fa6SDerek Schuff       encodeULEB128(Import.Memory.Flags, W->OS);
7530ff28fa6SDerek Schuff       encodeULEB128(NumPages, W->OS); // initial
754f950b24aSSam Clegg       break;
755f950b24aSSam Clegg     case wasm::WASM_EXTERNAL_TABLE:
7560ff28fa6SDerek Schuff       W->OS << char(Import.Table.ElemType);
7570ff28fa6SDerek Schuff       encodeULEB128(0, W->OS);           // flags
7580ff28fa6SDerek Schuff       encodeULEB128(NumElements, W->OS); // initial
759f950b24aSSam Clegg       break;
760da419bdbSHeejin Ahn     case wasm::WASM_EXTERNAL_EVENT:
7610ff28fa6SDerek Schuff       encodeULEB128(Import.Event.Attribute, W->OS);
7620ff28fa6SDerek Schuff       encodeULEB128(Import.Event.SigIndex, W->OS);
763da419bdbSHeejin Ahn       break;
7649e15f359SSam Clegg     default:
7659e15f359SSam Clegg       llvm_unreachable("unsupported import kind");
7669e15f359SSam Clegg     }
7679e15f359SSam Clegg   }
7689e15f359SSam Clegg 
7699e15f359SSam Clegg   endSection(Section);
7709e15f359SSam Clegg }
7719e15f359SSam Clegg 
772457fb0b4SSam Clegg void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
7739e15f359SSam Clegg   if (Functions.empty())
7749e15f359SSam Clegg     return;
7759e15f359SSam Clegg 
7769e15f359SSam Clegg   SectionBookkeeping Section;
7779e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_FUNCTION);
7789e15f359SSam Clegg 
7790ff28fa6SDerek Schuff   encodeULEB128(Functions.size(), W->OS);
7809e15f359SSam Clegg   for (const WasmFunction &Func : Functions)
7810ff28fa6SDerek Schuff     encodeULEB128(Func.SigIndex, W->OS);
7829e15f359SSam Clegg 
7839e15f359SSam Clegg   endSection(Section);
7849e15f359SSam Clegg }
7859e15f359SSam Clegg 
786da419bdbSHeejin Ahn void WasmObjectWriter::writeEventSection(ArrayRef<wasm::WasmEventType> Events) {
787da419bdbSHeejin Ahn   if (Events.empty())
788da419bdbSHeejin Ahn     return;
789da419bdbSHeejin Ahn 
790da419bdbSHeejin Ahn   SectionBookkeeping Section;
791da419bdbSHeejin Ahn   startSection(Section, wasm::WASM_SEC_EVENT);
792da419bdbSHeejin Ahn 
7930ff28fa6SDerek Schuff   encodeULEB128(Events.size(), W->OS);
794da419bdbSHeejin Ahn   for (const wasm::WasmEventType &Event : Events) {
7950ff28fa6SDerek Schuff     encodeULEB128(Event.Attribute, W->OS);
7960ff28fa6SDerek Schuff     encodeULEB128(Event.SigIndex, W->OS);
797da419bdbSHeejin Ahn   }
798da419bdbSHeejin Ahn 
799da419bdbSHeejin Ahn   endSection(Section);
800da419bdbSHeejin Ahn }
801da419bdbSHeejin Ahn 
8020a6c4d8dSSam Clegg void WasmObjectWriter::writeGlobalSection(ArrayRef<wasm::WasmGlobal> Globals) {
8030a6c4d8dSSam Clegg   if (Globals.empty())
8040a6c4d8dSSam Clegg     return;
8050a6c4d8dSSam Clegg 
8060a6c4d8dSSam Clegg   SectionBookkeeping Section;
8070a6c4d8dSSam Clegg   startSection(Section, wasm::WASM_SEC_GLOBAL);
8080a6c4d8dSSam Clegg 
8090ff28fa6SDerek Schuff   encodeULEB128(Globals.size(), W->OS);
8100a6c4d8dSSam Clegg   for (const wasm::WasmGlobal &Global : Globals) {
8110ff28fa6SDerek Schuff     encodeULEB128(Global.Type.Type, W->OS);
8120ff28fa6SDerek Schuff     W->OS << char(Global.Type.Mutable);
8130ff28fa6SDerek Schuff     W->OS << char(Global.InitExpr.Opcode);
8140a6c4d8dSSam Clegg     switch (Global.Type.Type) {
8150a6c4d8dSSam Clegg     case wasm::WASM_TYPE_I32:
8160ff28fa6SDerek Schuff       encodeSLEB128(0, W->OS);
8170a6c4d8dSSam Clegg       break;
8180a6c4d8dSSam Clegg     case wasm::WASM_TYPE_I64:
8190ff28fa6SDerek Schuff       encodeSLEB128(0, W->OS);
8200a6c4d8dSSam Clegg       break;
8210a6c4d8dSSam Clegg     case wasm::WASM_TYPE_F32:
8220a6c4d8dSSam Clegg       writeI32(0);
8230a6c4d8dSSam Clegg       break;
8240a6c4d8dSSam Clegg     case wasm::WASM_TYPE_F64:
8250a6c4d8dSSam Clegg       writeI64(0);
8260a6c4d8dSSam Clegg       break;
82779aad89dSSam Clegg     case wasm::WASM_TYPE_EXTERNREF:
82879aad89dSSam Clegg       writeValueType(wasm::ValType::EXTERNREF);
82979aad89dSSam Clegg       break;
8300a6c4d8dSSam Clegg     default:
8310a6c4d8dSSam Clegg       llvm_unreachable("unexpected type");
8320a6c4d8dSSam Clegg     }
8330ff28fa6SDerek Schuff     W->OS << char(wasm::WASM_OPCODE_END);
8340a6c4d8dSSam Clegg   }
8350a6c4d8dSSam Clegg 
8360a6c4d8dSSam Clegg   endSection(Section);
8370a6c4d8dSSam Clegg }
8380a6c4d8dSSam Clegg 
839388fb67bSPaulo Matos void WasmObjectWriter::writeTableSection(ArrayRef<wasm::WasmTable> Tables) {
840388fb67bSPaulo Matos   if (Tables.empty())
841388fb67bSPaulo Matos     return;
842388fb67bSPaulo Matos 
843388fb67bSPaulo Matos   SectionBookkeeping Section;
844388fb67bSPaulo Matos   startSection(Section, wasm::WASM_SEC_TABLE);
845388fb67bSPaulo Matos 
846388fb67bSPaulo Matos   encodeULEB128(Tables.size(), W->OS);
847388fb67bSPaulo Matos   for (const wasm::WasmTable &Table : Tables) {
848388fb67bSPaulo Matos     encodeULEB128(Table.ElemType, W->OS);
849388fb67bSPaulo Matos     encodeULEB128(Table.Limits.Flags, W->OS);
850388fb67bSPaulo Matos     encodeULEB128(Table.Limits.Initial, W->OS);
851388fb67bSPaulo Matos     if (Table.Limits.Flags & wasm::WASM_LIMITS_FLAG_HAS_MAX)
852388fb67bSPaulo Matos       encodeULEB128(Table.Limits.Maximum, W->OS);
853388fb67bSPaulo Matos   }
854388fb67bSPaulo Matos   endSection(Section);
855388fb67bSPaulo Matos }
856388fb67bSPaulo Matos 
8578defa952SSam Clegg void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) {
8589e15f359SSam Clegg   if (Exports.empty())
8599e15f359SSam Clegg     return;
8609e15f359SSam Clegg 
8619e15f359SSam Clegg   SectionBookkeeping Section;
8629e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_EXPORT);
8639e15f359SSam Clegg 
8640ff28fa6SDerek Schuff   encodeULEB128(Exports.size(), W->OS);
8658defa952SSam Clegg   for (const wasm::WasmExport &Export : Exports) {
8668defa952SSam Clegg     writeString(Export.Name);
8670ff28fa6SDerek Schuff     W->OS << char(Export.Kind);
8680ff28fa6SDerek Schuff     encodeULEB128(Export.Index, W->OS);
8699e15f359SSam Clegg   }
8709e15f359SSam Clegg 
8719e15f359SSam Clegg   endSection(Section);
8729e15f359SSam Clegg }
8739e15f359SSam Clegg 
874457fb0b4SSam Clegg void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
8759e15f359SSam Clegg   if (TableElems.empty())
8769e15f359SSam Clegg     return;
8779e15f359SSam Clegg 
8789e15f359SSam Clegg   SectionBookkeeping Section;
8799e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_ELEM);
8809e15f359SSam Clegg 
8810ff28fa6SDerek Schuff   encodeULEB128(1, W->OS); // number of "segments"
8820ff28fa6SDerek Schuff   encodeULEB128(0, W->OS); // the table index
8839e15f359SSam Clegg 
8849e15f359SSam Clegg   // init expr for starting offset
8850ff28fa6SDerek Schuff   W->OS << char(wasm::WASM_OPCODE_I32_CONST);
8860ff28fa6SDerek Schuff   encodeSLEB128(InitialTableOffset, W->OS);
8870ff28fa6SDerek Schuff   W->OS << char(wasm::WASM_OPCODE_END);
8889e15f359SSam Clegg 
8890ff28fa6SDerek Schuff   encodeULEB128(TableElems.size(), W->OS);
8909e15f359SSam Clegg   for (uint32_t Elem : TableElems)
8910ff28fa6SDerek Schuff     encodeULEB128(Elem, W->OS);
8929e15f359SSam Clegg 
8939e15f359SSam Clegg   endSection(Section);
8949e15f359SSam Clegg }
8959e15f359SSam Clegg 
896fef8de66SThomas Lively void WasmObjectWriter::writeDataCountSection() {
897fef8de66SThomas Lively   if (DataSegments.empty())
898fef8de66SThomas Lively     return;
899fef8de66SThomas Lively 
900fef8de66SThomas Lively   SectionBookkeeping Section;
901fef8de66SThomas Lively   startSection(Section, wasm::WASM_SEC_DATACOUNT);
9020ff28fa6SDerek Schuff   encodeULEB128(DataSegments.size(), W->OS);
903fef8de66SThomas Lively   endSection(Section);
904fef8de66SThomas Lively }
905fef8de66SThomas Lively 
906e49584a3SSam Clegg uint32_t WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
907457fb0b4SSam Clegg                                             const MCAsmLayout &Layout,
908457fb0b4SSam Clegg                                             ArrayRef<WasmFunction> Functions) {
9099e15f359SSam Clegg   if (Functions.empty())
910e49584a3SSam Clegg     return 0;
9119e15f359SSam Clegg 
9129e15f359SSam Clegg   SectionBookkeeping Section;
9139e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_CODE);
9149e15f359SSam Clegg 
9150ff28fa6SDerek Schuff   encodeULEB128(Functions.size(), W->OS);
9169e15f359SSam Clegg 
9179e15f359SSam Clegg   for (const WasmFunction &Func : Functions) {
918fe6414b0SSam Clegg     auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
9199e15f359SSam Clegg 
9209e15f359SSam Clegg     int64_t Size = 0;
9219e15f359SSam Clegg     if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
9229e15f359SSam Clegg       report_fatal_error(".size expression must be evaluatable");
9239e15f359SSam Clegg 
9240ff28fa6SDerek Schuff     encodeULEB128(Size, W->OS);
9250ff28fa6SDerek Schuff     FuncSection.setSectionOffset(W->OS.tell() - Section.ContentsOffset);
9260ff28fa6SDerek Schuff     Asm.writeSectionData(W->OS, &FuncSection, Layout);
9279e15f359SSam Clegg   }
9289e15f359SSam Clegg 
9299e15f359SSam Clegg   // Apply fixups.
9307ee758d6SSam Clegg   applyRelocations(CodeRelocations, Section.ContentsOffset, Layout);
9319e15f359SSam Clegg 
9329e15f359SSam Clegg   endSection(Section);
933e49584a3SSam Clegg   return Section.Index;
9349e15f359SSam Clegg }
9359e15f359SSam Clegg 
936e49584a3SSam Clegg uint32_t WasmObjectWriter::writeDataSection(const MCAsmLayout &Layout) {
9376c899ba6SSam Clegg   if (DataSegments.empty())
938e49584a3SSam Clegg     return 0;
9399e15f359SSam Clegg 
9409e15f359SSam Clegg   SectionBookkeeping Section;
9419e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_DATA);
9429e15f359SSam Clegg 
9430ff28fa6SDerek Schuff   encodeULEB128(DataSegments.size(), W->OS); // count
9447c395943SSam Clegg 
9456c899ba6SSam Clegg   for (const WasmDataSegment &Segment : DataSegments) {
9460ff28fa6SDerek Schuff     encodeULEB128(Segment.InitFlags, W->OS); // flags
9472e150409SThomas Lively     if (Segment.InitFlags & wasm::WASM_SEGMENT_HAS_MEMINDEX)
9480ff28fa6SDerek Schuff       encodeULEB128(0, W->OS); // memory index
9492e150409SThomas Lively     if ((Segment.InitFlags & wasm::WASM_SEGMENT_IS_PASSIVE) == 0) {
9500ff28fa6SDerek Schuff       W->OS << char(Segment.Offset > INT32_MAX ? wasm::WASM_OPCODE_I64_CONST
9514d135b04SWouter van Oortmerssen                                                : wasm::WASM_OPCODE_I32_CONST);
9520ff28fa6SDerek Schuff       encodeSLEB128(Segment.Offset, W->OS); // offset
9530ff28fa6SDerek Schuff       W->OS << char(wasm::WASM_OPCODE_END);
9542e150409SThomas Lively     }
9550ff28fa6SDerek Schuff     encodeULEB128(Segment.Data.size(), W->OS); // size
9560ff28fa6SDerek Schuff     Segment.Section->setSectionOffset(W->OS.tell() - Section.ContentsOffset);
9570ff28fa6SDerek Schuff     W->OS << Segment.Data; // data
9587c395943SSam Clegg   }
9599e15f359SSam Clegg 
9609e15f359SSam Clegg   // Apply fixups.
9617ee758d6SSam Clegg   applyRelocations(DataRelocations, Section.ContentsOffset, Layout);
9629e15f359SSam Clegg 
9639e15f359SSam Clegg   endSection(Section);
964e49584a3SSam Clegg   return Section.Index;
9659e15f359SSam Clegg }
9669e15f359SSam Clegg 
9676f08c84aSSam Clegg void WasmObjectWriter::writeRelocSection(
9686f08c84aSSam Clegg     uint32_t SectionIndex, StringRef Name,
969f77dc2a8SSam Clegg     std::vector<WasmRelocationEntry> &Relocs) {
9709e15f359SSam Clegg   // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
9719e15f359SSam Clegg   // for descriptions of the reloc sections.
9729e15f359SSam Clegg 
973f77dc2a8SSam Clegg   if (Relocs.empty())
9749e15f359SSam Clegg     return;
9759e15f359SSam Clegg 
976f77dc2a8SSam Clegg   // First, ensure the relocations are sorted in offset order.  In general they
977f77dc2a8SSam Clegg   // should already be sorted since `recordRelocation` is called in offset
978f77dc2a8SSam Clegg   // order, but for the code section we combine many MC sections into single
979f77dc2a8SSam Clegg   // wasm section, and this order is determined by the order of Asm.Symbols()
980f77dc2a8SSam Clegg   // not the sections order.
981efd94c56SFangrui Song   llvm::stable_sort(
982efd94c56SFangrui Song       Relocs, [](const WasmRelocationEntry &A, const WasmRelocationEntry &B) {
983f77dc2a8SSam Clegg         return (A.Offset + A.FixupSection->getSectionOffset()) <
984f77dc2a8SSam Clegg                (B.Offset + B.FixupSection->getSectionOffset());
985f77dc2a8SSam Clegg       });
986f77dc2a8SSam Clegg 
9879e15f359SSam Clegg   SectionBookkeeping Section;
9886f08c84aSSam Clegg   startCustomSection(Section, std::string("reloc.") + Name.str());
9899e15f359SSam Clegg 
9900ff28fa6SDerek Schuff   encodeULEB128(SectionIndex, W->OS);
9910ff28fa6SDerek Schuff   encodeULEB128(Relocs.size(), W->OS);
992f77dc2a8SSam Clegg   for (const WasmRelocationEntry &RelEntry : Relocs) {
993f208f631SHeejin Ahn     uint64_t Offset =
994f208f631SHeejin Ahn         RelEntry.Offset + RelEntry.FixupSection->getSectionOffset();
9956f08c84aSSam Clegg     uint32_t Index = getRelocationIndexValue(RelEntry);
9969e15f359SSam Clegg 
9970ff28fa6SDerek Schuff     W->OS << char(RelEntry.Type);
9980ff28fa6SDerek Schuff     encodeULEB128(Offset, W->OS);
9990ff28fa6SDerek Schuff     encodeULEB128(Index, W->OS);
10006f08c84aSSam Clegg     if (RelEntry.hasAddend())
10010ff28fa6SDerek Schuff       encodeSLEB128(RelEntry.Addend, W->OS);
10029e15f359SSam Clegg   }
10039e15f359SSam Clegg 
10049e15f359SSam Clegg   endSection(Section);
10059e15f359SSam Clegg }
10069e15f359SSam Clegg 
10076a31a0d6SSam Clegg void WasmObjectWriter::writeCustomRelocSections() {
10086a31a0d6SSam Clegg   for (const auto &Sec : CustomSections) {
10096a31a0d6SSam Clegg     auto &Relocations = CustomSectionsRelocations[Sec.Section];
10106a31a0d6SSam Clegg     writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations);
10116a31a0d6SSam Clegg   }
10126a31a0d6SSam Clegg }
10136a31a0d6SSam Clegg 
10149e15f359SSam Clegg void WasmObjectWriter::writeLinkingMetaDataSection(
101586b4a09aSSam Clegg     ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
1016ea7caceeSSam Clegg     ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
1017ea7caceeSSam Clegg     const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) {
10189e15f359SSam Clegg   SectionBookkeeping Section;
10192322a937SSam Clegg   startCustomSection(Section, "linking");
10200ff28fa6SDerek Schuff   encodeULEB128(wasm::WasmMetadataVersion, W->OS);
10219e15f359SSam Clegg 
10226bb5a41fSSam Clegg   SectionBookkeeping SubSection;
10236c899ba6SSam Clegg   if (SymbolInfos.size() != 0) {
10246c899ba6SSam Clegg     startSection(SubSection, wasm::WASM_SYMBOL_TABLE);
10250ff28fa6SDerek Schuff     encodeULEB128(SymbolInfos.size(), W->OS);
10266c899ba6SSam Clegg     for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) {
10270ff28fa6SDerek Schuff       encodeULEB128(Sym.Kind, W->OS);
10280ff28fa6SDerek Schuff       encodeULEB128(Sym.Flags, W->OS);
10296c899ba6SSam Clegg       switch (Sym.Kind) {
10306c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_FUNCTION:
10316c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_GLOBAL:
1032da419bdbSHeejin Ahn       case wasm::WASM_SYMBOL_TYPE_EVENT:
1033388fb67bSPaulo Matos       case wasm::WASM_SYMBOL_TYPE_TABLE:
10340ff28fa6SDerek Schuff         encodeULEB128(Sym.ElementIndex, W->OS);
103529874ceaSDan Gohman         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0 ||
103629874ceaSDan Gohman             (Sym.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0)
10376c899ba6SSam Clegg           writeString(Sym.Name);
10386c899ba6SSam Clegg         break;
10396c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_DATA:
10406c899ba6SSam Clegg         writeString(Sym.Name);
10416c899ba6SSam Clegg         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) {
10420ff28fa6SDerek Schuff           encodeULEB128(Sym.DataRef.Segment, W->OS);
10430ff28fa6SDerek Schuff           encodeULEB128(Sym.DataRef.Offset, W->OS);
10440ff28fa6SDerek Schuff           encodeULEB128(Sym.DataRef.Size, W->OS);
10456c899ba6SSam Clegg         }
10466c899ba6SSam Clegg         break;
10476a31a0d6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_SECTION: {
10486a31a0d6SSam Clegg         const uint32_t SectionIndex =
10496a31a0d6SSam Clegg             CustomSections[Sym.ElementIndex].OutputIndex;
10500ff28fa6SDerek Schuff         encodeULEB128(SectionIndex, W->OS);
10516a31a0d6SSam Clegg         break;
10526a31a0d6SSam Clegg       }
10536c899ba6SSam Clegg       default:
10546c899ba6SSam Clegg         llvm_unreachable("unexpected kind");
10556c899ba6SSam Clegg       }
1056b7787fd0SSam Clegg     }
1057b7787fd0SSam Clegg     endSection(SubSection);
1058b7787fd0SSam Clegg   }
10599e15f359SSam Clegg 
10606c899ba6SSam Clegg   if (DataSegments.size()) {
106163ebb813SSam Clegg     startSection(SubSection, wasm::WASM_SEGMENT_INFO);
10620ff28fa6SDerek Schuff     encodeULEB128(DataSegments.size(), W->OS);
10636c899ba6SSam Clegg     for (const WasmDataSegment &Segment : DataSegments) {
1064d95ed959SSam Clegg       writeString(Segment.Name);
10650ff28fa6SDerek Schuff       encodeULEB128(Segment.Alignment, W->OS);
10660ff28fa6SDerek Schuff       encodeULEB128(Segment.LinkerFlags, W->OS);
106763ebb813SSam Clegg     }
1068d95ed959SSam Clegg     endSection(SubSection);
1069d95ed959SSam Clegg   }
1070d95ed959SSam Clegg 
1071bafe6902SSam Clegg   if (!InitFuncs.empty()) {
1072bafe6902SSam Clegg     startSection(SubSection, wasm::WASM_INIT_FUNCS);
10730ff28fa6SDerek Schuff     encodeULEB128(InitFuncs.size(), W->OS);
1074bafe6902SSam Clegg     for (auto &StartFunc : InitFuncs) {
10750ff28fa6SDerek Schuff       encodeULEB128(StartFunc.first, W->OS);  // priority
10760ff28fa6SDerek Schuff       encodeULEB128(StartFunc.second, W->OS); // function index
1077bafe6902SSam Clegg     }
1078bafe6902SSam Clegg     endSection(SubSection);
1079bafe6902SSam Clegg   }
1080bafe6902SSam Clegg 
1081ea7caceeSSam Clegg   if (Comdats.size()) {
1082ea7caceeSSam Clegg     startSection(SubSection, wasm::WASM_COMDAT_INFO);
10830ff28fa6SDerek Schuff     encodeULEB128(Comdats.size(), W->OS);
1084ea7caceeSSam Clegg     for (const auto &C : Comdats) {
1085ea7caceeSSam Clegg       writeString(C.first);
10860ff28fa6SDerek Schuff       encodeULEB128(0, W->OS); // flags for future use
10870ff28fa6SDerek Schuff       encodeULEB128(C.second.size(), W->OS);
1088ea7caceeSSam Clegg       for (const WasmComdatEntry &Entry : C.second) {
10890ff28fa6SDerek Schuff         encodeULEB128(Entry.Kind, W->OS);
10900ff28fa6SDerek Schuff         encodeULEB128(Entry.Index, W->OS);
1091ea7caceeSSam Clegg       }
1092ea7caceeSSam Clegg     }
1093ea7caceeSSam Clegg     endSection(SubSection);
1094ea7caceeSSam Clegg   }
1095ea7caceeSSam Clegg 
10969e15f359SSam Clegg   endSection(Section);
10979e15f359SSam Clegg }
10989e15f359SSam Clegg 
1099cbda16ebSThomas Lively void WasmObjectWriter::writeCustomSection(WasmCustomSection &CustomSection,
1100cbda16ebSThomas Lively                                           const MCAssembler &Asm,
11016a31a0d6SSam Clegg                                           const MCAsmLayout &Layout) {
1102cfd44a2eSSam Clegg   SectionBookkeeping Section;
11036a31a0d6SSam Clegg   auto *Sec = CustomSection.Section;
11042322a937SSam Clegg   startCustomSection(Section, CustomSection.Name);
11056a31a0d6SSam Clegg 
11060ff28fa6SDerek Schuff   Sec->setSectionOffset(W->OS.tell() - Section.ContentsOffset);
11070ff28fa6SDerek Schuff   Asm.writeSectionData(W->OS, Sec, Layout);
11086a31a0d6SSam Clegg 
11096a31a0d6SSam Clegg   CustomSection.OutputContentsOffset = Section.ContentsOffset;
11106a31a0d6SSam Clegg   CustomSection.OutputIndex = Section.Index;
11116a31a0d6SSam Clegg 
1112cfd44a2eSSam Clegg   endSection(Section);
11136a31a0d6SSam Clegg 
11146a31a0d6SSam Clegg   // Apply fixups.
11154d57fbd0SSam Clegg   auto &Relocations = CustomSectionsRelocations[CustomSection.Section];
11167ee758d6SSam Clegg   applyRelocations(Relocations, CustomSection.OutputContentsOffset, Layout);
11176a31a0d6SSam Clegg }
11186a31a0d6SSam Clegg 
11195e3d33a7SSam Clegg uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm &Symbol) {
11205e3d33a7SSam Clegg   assert(Symbol.isFunction());
11215e3d33a7SSam Clegg   assert(TypeIndices.count(&Symbol));
11225e3d33a7SSam Clegg   return TypeIndices[&Symbol];
11235e3d33a7SSam Clegg }
11245e3d33a7SSam Clegg 
1125da419bdbSHeejin Ahn uint32_t WasmObjectWriter::getEventType(const MCSymbolWasm &Symbol) {
1126da419bdbSHeejin Ahn   assert(Symbol.isEvent());
1127da419bdbSHeejin Ahn   assert(TypeIndices.count(&Symbol));
1128da419bdbSHeejin Ahn   return TypeIndices[&Symbol];
1129da419bdbSHeejin Ahn }
1130da419bdbSHeejin Ahn 
113138b12f5eSHeejin Ahn void WasmObjectWriter::registerFunctionType(const MCSymbolWasm &Symbol) {
11325e3d33a7SSam Clegg   assert(Symbol.isFunction());
11335e3d33a7SSam Clegg 
11344c41fb5aSHeejin Ahn   wasm::WasmSignature S;
11357ee758d6SSam Clegg 
11367ee758d6SSam Clegg   if (auto *Sig = Symbol.getSignature()) {
1137da419bdbSHeejin Ahn     S.Returns = Sig->Returns;
1138da419bdbSHeejin Ahn     S.Params = Sig->Params;
113977a7a380SDerek Schuff   }
11405e3d33a7SSam Clegg 
1141da419bdbSHeejin Ahn   auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
11425e3d33a7SSam Clegg   if (Pair.second)
1143da419bdbSHeejin Ahn     Signatures.push_back(S);
11445e3d33a7SSam Clegg   TypeIndices[&Symbol] = Pair.first->second;
11455e3d33a7SSam Clegg 
1146d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "registerFunctionType: " << Symbol
1147d34e60caSNicola Zaghen                     << " new:" << Pair.second << "\n");
1148d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
11495e3d33a7SSam Clegg }
11505e3d33a7SSam Clegg 
115138b12f5eSHeejin Ahn void WasmObjectWriter::registerEventType(const MCSymbolWasm &Symbol) {
1152da419bdbSHeejin Ahn   assert(Symbol.isEvent());
1153da419bdbSHeejin Ahn 
1154da419bdbSHeejin Ahn   // TODO Currently we don't generate imported exceptions, but if we do, we
1155da419bdbSHeejin Ahn   // should have a way of infering types of imported exceptions.
11564c41fb5aSHeejin Ahn   wasm::WasmSignature S;
1157da419bdbSHeejin Ahn   if (auto *Sig = Symbol.getSignature()) {
1158da419bdbSHeejin Ahn     S.Returns = Sig->Returns;
1159da419bdbSHeejin Ahn     S.Params = Sig->Params;
1160da419bdbSHeejin Ahn   }
1161da419bdbSHeejin Ahn 
1162da419bdbSHeejin Ahn   auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
1163da419bdbSHeejin Ahn   if (Pair.second)
1164da419bdbSHeejin Ahn     Signatures.push_back(S);
1165da419bdbSHeejin Ahn   TypeIndices[&Symbol] = Pair.first->second;
1166da419bdbSHeejin Ahn 
1167da419bdbSHeejin Ahn   LLVM_DEBUG(dbgs() << "registerEventType: " << Symbol << " new:" << Pair.second
1168da419bdbSHeejin Ahn                     << "\n");
1169da419bdbSHeejin Ahn   LLVM_DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
1170da419bdbSHeejin Ahn }
1171da419bdbSHeejin Ahn 
11724d57fbd0SSam Clegg static bool isInSymtab(const MCSymbolWasm &Sym) {
11733ea1c62cSSam Clegg   if (Sym.isUsedInReloc() || Sym.isUsedInInitArray())
11744d57fbd0SSam Clegg     return true;
11754d57fbd0SSam Clegg 
11764d57fbd0SSam Clegg   if (Sym.isComdat() && !Sym.isDefined())
11774d57fbd0SSam Clegg     return false;
11784d57fbd0SSam Clegg 
11793ea1c62cSSam Clegg   if (Sym.isTemporary())
11804d57fbd0SSam Clegg     return false;
11814d57fbd0SSam Clegg 
11824d57fbd0SSam Clegg   if (Sym.isSection())
11834d57fbd0SSam Clegg     return false;
11844d57fbd0SSam Clegg 
11854d57fbd0SSam Clegg   return true;
11864d57fbd0SSam Clegg }
11870ff28fa6SDerek Schuff void WasmObjectWriter::prepareImports(
11880ff28fa6SDerek Schuff     SmallVectorImpl<wasm::WasmImport> &Imports, MCAssembler &Asm,
118918eafb6cSDan Gohman     const MCAsmLayout &Layout) {
1190f950b24aSSam Clegg   // For now, always emit the memory import, since loads and stores are not
1191f950b24aSSam Clegg   // valid without it. In the future, we could perhaps be more clever and omit
1192f950b24aSSam Clegg   // it if there are no loads or stores.
11938defa952SSam Clegg   wasm::WasmImport MemImport;
11941ed3a046SSam Clegg   MemImport.Module = "env";
11951ed3a046SSam Clegg   MemImport.Field = "__linear_memory";
1196f950b24aSSam Clegg   MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
1197fd0964aeSWouter van Oortmerssen   MemImport.Memory.Flags = is64Bit() ? wasm::WASM_LIMITS_FLAG_IS_64
1198fd0964aeSWouter van Oortmerssen                                      : wasm::WASM_LIMITS_FLAG_NONE;
1199f950b24aSSam Clegg   Imports.push_back(MemImport);
1200f950b24aSSam Clegg 
1201f950b24aSSam Clegg   // For now, always emit the table section, since indirect calls are not
1202f950b24aSSam Clegg   // valid without it. In the future, we could perhaps be more clever and omit
1203f950b24aSSam Clegg   // it if there are no indirect calls.
12048defa952SSam Clegg   wasm::WasmImport TableImport;
12051ed3a046SSam Clegg   TableImport.Module = "env";
12061ed3a046SSam Clegg   TableImport.Field = "__indirect_function_table";
1207f950b24aSSam Clegg   TableImport.Kind = wasm::WASM_EXTERNAL_TABLE;
12086a87ddacSThomas Lively   TableImport.Table.ElemType = wasm::WASM_TYPE_FUNCREF;
1209f950b24aSSam Clegg   Imports.push_back(TableImport);
1210f950b24aSSam Clegg 
1211da419bdbSHeejin Ahn   // Populate SignatureIndices, and Imports and WasmIndices for undefined
1212586320c0SNicholas Wilson   // symbols.  This must be done before populating WasmIndices for defined
1213586320c0SNicholas Wilson   // symbols.
121432ce5ca0SDan Gohman   for (const MCSymbol &S : Asm.symbols()) {
121532ce5ca0SDan Gohman     const auto &WS = static_cast<const MCSymbolWasm &>(S);
121632ce5ca0SDan Gohman 
121732ce5ca0SDan Gohman     // Register types for all functions, including those with private linkage
12189f3fe42eSSam Clegg     // (because wasm always needs a type signature).
12197ee758d6SSam Clegg     if (WS.isFunction()) {
12209c7b5808SDominic Chen       const auto *BS = Layout.getBaseSymbol(S);
12219c7b5808SDominic Chen       if (!BS)
12229c7b5808SDominic Chen         report_fatal_error(Twine(S.getName()) +
12239c7b5808SDominic Chen                            ": absolute addressing not supported!");
12249c7b5808SDominic Chen       registerFunctionType(*cast<MCSymbolWasm>(BS));
12257ee758d6SSam Clegg     }
122632ce5ca0SDan Gohman 
1227da419bdbSHeejin Ahn     if (WS.isEvent())
1228da419bdbSHeejin Ahn       registerEventType(WS);
1229da419bdbSHeejin Ahn 
123032ce5ca0SDan Gohman     if (WS.isTemporary())
123132ce5ca0SDan Gohman       continue;
123232ce5ca0SDan Gohman 
123332ce5ca0SDan Gohman     // If the symbol is not defined in this translation unit, import it.
12346c899ba6SSam Clegg     if (!WS.isDefined() && !WS.isComdat()) {
12356c899ba6SSam Clegg       if (WS.isFunction()) {
12368defa952SSam Clegg         wasm::WasmImport Import;
1237f726e445SDan Gohman         Import.Module = WS.getImportModule();
1238f726e445SDan Gohman         Import.Field = WS.getImportName();
123932ce5ca0SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
12408defa952SSam Clegg         Import.SigIndex = getFunctionType(WS);
12416c899ba6SSam Clegg         Imports.push_back(Import);
1242492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
12436c899ba6SSam Clegg         WasmIndices[&WS] = NumFunctionImports++;
12446c899ba6SSam Clegg       } else if (WS.isGlobal()) {
124515f349f7SNicholas Wilson         if (WS.isWeak())
124615f349f7SNicholas Wilson           report_fatal_error("undefined global symbol cannot be weak");
124715f349f7SNicholas Wilson 
12486c899ba6SSam Clegg         wasm::WasmImport Import;
1249f726e445SDan Gohman         Import.Field = WS.getImportName();
125032ce5ca0SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1251492f7529SSam Clegg         Import.Module = WS.getImportModule();
12526c899ba6SSam Clegg         Import.Global = WS.getGlobalType();
12536c899ba6SSam Clegg         Imports.push_back(Import);
1254492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
12556c899ba6SSam Clegg         WasmIndices[&WS] = NumGlobalImports++;
1256da419bdbSHeejin Ahn       } else if (WS.isEvent()) {
1257da419bdbSHeejin Ahn         if (WS.isWeak())
1258da419bdbSHeejin Ahn           report_fatal_error("undefined event symbol cannot be weak");
1259da419bdbSHeejin Ahn 
1260da419bdbSHeejin Ahn         wasm::WasmImport Import;
1261f726e445SDan Gohman         Import.Module = WS.getImportModule();
1262f726e445SDan Gohman         Import.Field = WS.getImportName();
1263da419bdbSHeejin Ahn         Import.Kind = wasm::WASM_EXTERNAL_EVENT;
1264da419bdbSHeejin Ahn         Import.Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
1265da419bdbSHeejin Ahn         Import.Event.SigIndex = getEventType(WS);
1266da419bdbSHeejin Ahn         Imports.push_back(Import);
1267492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
1268da419bdbSHeejin Ahn         WasmIndices[&WS] = NumEventImports++;
126932ce5ca0SDan Gohman       }
127032ce5ca0SDan Gohman     }
127132ce5ca0SDan Gohman   }
127232ce5ca0SDan Gohman 
1273492f7529SSam Clegg   // Add imports for GOT globals
1274492f7529SSam Clegg   for (const MCSymbol &S : Asm.symbols()) {
1275492f7529SSam Clegg     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1276492f7529SSam Clegg     if (WS.isUsedInGOT()) {
1277492f7529SSam Clegg       wasm::WasmImport Import;
1278492f7529SSam Clegg       if (WS.isFunction())
1279492f7529SSam Clegg         Import.Module = "GOT.func";
1280492f7529SSam Clegg       else
1281492f7529SSam Clegg         Import.Module = "GOT.mem";
1282492f7529SSam Clegg       Import.Field = WS.getName();
1283492f7529SSam Clegg       Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1284492f7529SSam Clegg       Import.Global = {wasm::WASM_TYPE_I32, true};
1285492f7529SSam Clegg       Imports.push_back(Import);
1286492f7529SSam Clegg       assert(GOTIndices.count(&WS) == 0);
1287492f7529SSam Clegg       GOTIndices[&WS] = NumGlobalImports++;
1288492f7529SSam Clegg     }
1289492f7529SSam Clegg   }
12900ff28fa6SDerek Schuff }
1291492f7529SSam Clegg 
12920ff28fa6SDerek Schuff uint64_t WasmObjectWriter::writeObject(MCAssembler &Asm,
12930ff28fa6SDerek Schuff                                        const MCAsmLayout &Layout) {
12940ff28fa6SDerek Schuff   support::endian::Writer MainWriter(*OS, support::little);
12950ff28fa6SDerek Schuff   W = &MainWriter;
12960ff28fa6SDerek Schuff   if (IsSplitDwarf) {
12970ff28fa6SDerek Schuff     uint64_t TotalSize = writeOneObject(Asm, Layout, DwoMode::NonDwoOnly);
12980ff28fa6SDerek Schuff     assert(DwoOS);
12990ff28fa6SDerek Schuff     support::endian::Writer DwoWriter(*DwoOS, support::little);
13000ff28fa6SDerek Schuff     W = &DwoWriter;
13010ff28fa6SDerek Schuff     return TotalSize + writeOneObject(Asm, Layout, DwoMode::DwoOnly);
13020ff28fa6SDerek Schuff   } else {
13030ff28fa6SDerek Schuff     return writeOneObject(Asm, Layout, DwoMode::AllSections);
13040ff28fa6SDerek Schuff   }
13050ff28fa6SDerek Schuff }
13060ff28fa6SDerek Schuff 
13070ff28fa6SDerek Schuff uint64_t WasmObjectWriter::writeOneObject(MCAssembler &Asm,
13080ff28fa6SDerek Schuff                                           const MCAsmLayout &Layout,
13090ff28fa6SDerek Schuff                                           DwoMode Mode) {
13100ff28fa6SDerek Schuff   uint64_t StartOffset = W->OS.tell();
13110ff28fa6SDerek Schuff   SectionCount = 0;
13120ff28fa6SDerek Schuff   CustomSections.clear();
13130ff28fa6SDerek Schuff 
13140ff28fa6SDerek Schuff   LLVM_DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
13150ff28fa6SDerek Schuff 
13160ff28fa6SDerek Schuff   // Collect information from the available symbols.
13170ff28fa6SDerek Schuff   SmallVector<WasmFunction, 4> Functions;
13180ff28fa6SDerek Schuff   SmallVector<uint32_t, 4> TableElems;
13190ff28fa6SDerek Schuff   SmallVector<wasm::WasmImport, 4> Imports;
13200ff28fa6SDerek Schuff   SmallVector<wasm::WasmExport, 4> Exports;
13210ff28fa6SDerek Schuff   SmallVector<wasm::WasmEventType, 1> Events;
13220ff28fa6SDerek Schuff   SmallVector<wasm::WasmGlobal, 1> Globals;
1323388fb67bSPaulo Matos   SmallVector<wasm::WasmTable, 1> Tables;
13240ff28fa6SDerek Schuff   SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos;
13250ff28fa6SDerek Schuff   SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
13260ff28fa6SDerek Schuff   std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
13270ff28fa6SDerek Schuff   uint64_t DataSize = 0;
13280ff28fa6SDerek Schuff   if (Mode != DwoMode::DwoOnly) {
13290ff28fa6SDerek Schuff     prepareImports(Imports, Asm, Layout);
13300ff28fa6SDerek Schuff   }
13314d57fbd0SSam Clegg   // Populate DataSegments and CustomSections, which must be done before
13324d57fbd0SSam Clegg   // populating DataLocations.
1333759631c7SSam Clegg   for (MCSection &Sec : Asm) {
1334759631c7SSam Clegg     auto &Section = static_cast<MCSectionWasm &>(Sec);
13357d1ff446SFangrui Song     StringRef SectionName = Section.getName();
1336759631c7SSam Clegg 
13370ff28fa6SDerek Schuff     if (Mode == DwoMode::NonDwoOnly && isDwoSection(Sec))
13380ff28fa6SDerek Schuff       continue;
13390ff28fa6SDerek Schuff     if (Mode == DwoMode::DwoOnly && !isDwoSection(Sec))
13400ff28fa6SDerek Schuff       continue;
13410ff28fa6SDerek Schuff 
1342bafe6902SSam Clegg     // .init_array sections are handled specially elsewhere.
13434d57fbd0SSam Clegg     if (SectionName.startswith(".init_array"))
1344bafe6902SSam Clegg       continue;
1345bafe6902SSam Clegg 
13464d57fbd0SSam Clegg     // Code is handled separately
13474d57fbd0SSam Clegg     if (Section.getKind().isText())
13484d57fbd0SSam Clegg       continue;
13494d57fbd0SSam Clegg 
13504d57fbd0SSam Clegg     if (Section.isWasmData()) {
1351329e76d5SSam Clegg       uint32_t SegmentIndex = DataSegments.size();
1352759631c7SSam Clegg       DataSize = alignTo(DataSize, Section.getAlignment());
1353759631c7SSam Clegg       DataSegments.emplace_back();
1354759631c7SSam Clegg       WasmDataSegment &Segment = DataSegments.back();
13554d57fbd0SSam Clegg       Segment.Name = SectionName;
13569b49f36aSSimon Pilgrim       Segment.InitFlags =
13579b49f36aSSimon Pilgrim           Section.getPassive() ? (uint32_t)wasm::WASM_SEGMENT_IS_PASSIVE : 0;
1358759631c7SSam Clegg       Segment.Offset = DataSize;
1359759631c7SSam Clegg       Segment.Section = &Section;
136063ebb813SSam Clegg       addData(Segment.Data, Section);
136156c587adSSam Clegg       Segment.Alignment = Log2_32(Section.getAlignment());
13622e150409SThomas Lively       Segment.LinkerFlags = 0;
1363759631c7SSam Clegg       DataSize += Segment.Data.size();
13646c899ba6SSam Clegg       Section.setSegmentIndex(SegmentIndex);
1365ea7caceeSSam Clegg 
1366ea7caceeSSam Clegg       if (const MCSymbolWasm *C = Section.getGroup()) {
1367ea7caceeSSam Clegg         Comdats[C->getName()].emplace_back(
1368329e76d5SSam Clegg             WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
1369ea7caceeSSam Clegg       }
13704d57fbd0SSam Clegg     } else {
13714d57fbd0SSam Clegg       // Create custom sections
13724d57fbd0SSam Clegg       assert(Sec.getKind().isMetadata());
13734d57fbd0SSam Clegg 
13744d57fbd0SSam Clegg       StringRef Name = SectionName;
13754d57fbd0SSam Clegg 
13764d57fbd0SSam Clegg       // For user-defined custom sections, strip the prefix
13774d57fbd0SSam Clegg       if (Name.startswith(".custom_section."))
13784d57fbd0SSam Clegg         Name = Name.substr(strlen(".custom_section."));
13794d57fbd0SSam Clegg 
13804d57fbd0SSam Clegg       MCSymbol *Begin = Sec.getBeginSymbol();
1381fb807d4dSSam Clegg       if (Begin) {
13824d57fbd0SSam Clegg         WasmIndices[cast<MCSymbolWasm>(Begin)] = CustomSections.size();
1383fb807d4dSSam Clegg       }
1384cbda16ebSThomas Lively 
1385f6f4f843SThomas Lively       // Separate out the producers and target features sections
1386cbda16ebSThomas Lively       if (Name == "producers") {
13870eaee545SJonas Devlieghere         ProducersSection = std::make_unique<WasmCustomSection>(Name, &Section);
1388cbda16ebSThomas Lively         continue;
1389cbda16ebSThomas Lively       }
1390f6f4f843SThomas Lively       if (Name == "target_features") {
1391f6f4f843SThomas Lively         TargetFeaturesSection =
13920eaee545SJonas Devlieghere             std::make_unique<WasmCustomSection>(Name, &Section);
1393f6f4f843SThomas Lively         continue;
1394f6f4f843SThomas Lively       }
1395cbda16ebSThomas Lively 
13964d57fbd0SSam Clegg       CustomSections.emplace_back(Name, &Section);
1397759631c7SSam Clegg     }
13986a31a0d6SSam Clegg   }
13996a31a0d6SSam Clegg 
1400586320c0SNicholas Wilson   // Populate WasmIndices and DataLocations for defined symbols.
1401d934cb88SDan Gohman   for (const MCSymbol &S : Asm.symbols()) {
1402d934cb88SDan Gohman     // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1403d934cb88SDan Gohman     // or used in relocations.
1404d934cb88SDan Gohman     if (S.isTemporary() && S.getName().empty())
1405d934cb88SDan Gohman       continue;
1406b7787fd0SSam Clegg 
1407d934cb88SDan Gohman     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1408d34e60caSNicola Zaghen     LLVM_DEBUG(
1409d34e60caSNicola Zaghen         dbgs() << "MCSymbol: " << toString(WS.getType()) << " '" << S << "'"
1410d34e60caSNicola Zaghen                << " isDefined=" << S.isDefined() << " isExternal="
1411d34e60caSNicola Zaghen                << S.isExternal() << " isTemporary=" << S.isTemporary()
1412d34e60caSNicola Zaghen                << " isWeak=" << WS.isWeak() << " isHidden=" << WS.isHidden()
1413b7787fd0SSam Clegg                << " isVariable=" << WS.isVariable() << "\n");
1414b7787fd0SSam Clegg 
14155e3d33a7SSam Clegg     if (WS.isVariable())
14165e3d33a7SSam Clegg       continue;
14176c899ba6SSam Clegg     if (WS.isComdat() && !WS.isDefined())
14186c899ba6SSam Clegg       continue;
1419b7787fd0SSam Clegg 
1420d934cb88SDan Gohman     if (WS.isFunction()) {
14216c899ba6SSam Clegg       unsigned Index;
1422cd65f698SSam Clegg       if (WS.isDefined()) {
1423b7787fd0SSam Clegg         if (WS.getOffset() != 0)
1424b7787fd0SSam Clegg           report_fatal_error(
1425b7787fd0SSam Clegg               "function sections must contain one function each");
1426b7787fd0SSam Clegg 
142718c56a07SHeejin Ahn         if (WS.getSize() == nullptr)
1428b7787fd0SSam Clegg           report_fatal_error(
1429b7787fd0SSam Clegg               "function symbols must have a size set with .size");
1430b7787fd0SSam Clegg 
14316c899ba6SSam Clegg         // A definition. Write out the function body.
14329f3fe42eSSam Clegg         Index = NumFunctionImports + Functions.size();
1433d934cb88SDan Gohman         WasmFunction Func;
1434da419bdbSHeejin Ahn         Func.SigIndex = getFunctionType(WS);
1435d934cb88SDan Gohman         Func.Sym = &WS;
14366c899ba6SSam Clegg         WasmIndices[&WS] = Index;
1437d934cb88SDan Gohman         Functions.push_back(Func);
14386c899ba6SSam Clegg 
14396c899ba6SSam Clegg         auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
14406c899ba6SSam Clegg         if (const MCSymbolWasm *C = Section.getGroup()) {
14416c899ba6SSam Clegg           Comdats[C->getName()].emplace_back(
14426c899ba6SSam Clegg               WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
14436c899ba6SSam Clegg         }
1444881d8778SSam Clegg 
1445881d8778SSam Clegg         if (WS.hasExportName()) {
1446881d8778SSam Clegg           wasm::WasmExport Export;
1447881d8778SSam Clegg           Export.Name = WS.getExportName();
1448881d8778SSam Clegg           Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1449881d8778SSam Clegg           Export.Index = Index;
1450881d8778SSam Clegg           Exports.push_back(Export);
1451881d8778SSam Clegg         }
1452d934cb88SDan Gohman       } else {
1453d934cb88SDan Gohman         // An import; the index was assigned above.
14546c899ba6SSam Clegg         Index = WasmIndices.find(&WS)->second;
1455d934cb88SDan Gohman       }
1456d934cb88SDan Gohman 
1457d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> function index: " << Index << "\n");
1458da419bdbSHeejin Ahn 
14596c899ba6SSam Clegg     } else if (WS.isData()) {
1460f3feb6adSWouter van Oortmerssen       if (!isInSymtab(WS))
1461c38e947eSSam Clegg         continue;
1462c38e947eSSam Clegg 
14636c899ba6SSam Clegg       if (!WS.isDefined()) {
1464d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "  -> segment index: -1"
1465d34e60caSNicola Zaghen                           << "\n");
1466fe6414b0SSam Clegg         continue;
14676c899ba6SSam Clegg       }
1468fe6414b0SSam Clegg 
1469d934cb88SDan Gohman       if (!WS.getSize())
1470c38e947eSSam Clegg         report_fatal_error("data symbols must have a size set with .size: " +
1471c38e947eSSam Clegg                            WS.getName());
1472d934cb88SDan Gohman 
1473d934cb88SDan Gohman       int64_t Size = 0;
1474d934cb88SDan Gohman       if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1475d934cb88SDan Gohman         report_fatal_error(".size expression must be evaluatable");
1476d934cb88SDan Gohman 
1477759631c7SSam Clegg       auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
1478079cba04SSam Clegg       if (!DataSection.isWasmData())
1479079cba04SSam Clegg         report_fatal_error("data symbols must live in a data section: " +
1480079cba04SSam Clegg                            WS.getName());
14817c395943SSam Clegg 
14826c899ba6SSam Clegg       // For each data symbol, export it in the symtab as a reference to the
14836c899ba6SSam Clegg       // corresponding Wasm data segment.
14846c899ba6SSam Clegg       wasm::WasmDataReference Ref = wasm::WasmDataReference{
14853b29376eSWouter van Oortmerssen           DataSection.getSegmentIndex(), Layout.getSymbolOffset(WS),
14863b29376eSWouter van Oortmerssen           static_cast<uint64_t>(Size)};
14876c899ba6SSam Clegg       DataLocations[&WS] = Ref;
1488d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> segment index: " << Ref.Segment << "\n");
1489da419bdbSHeejin Ahn 
1490a165f2d6SSam Clegg     } else if (WS.isGlobal()) {
14916c899ba6SSam Clegg       // A "true" Wasm global (currently just __stack_pointer)
14920a6c4d8dSSam Clegg       if (WS.isDefined()) {
14930a6c4d8dSSam Clegg         assert(WasmIndices.count(&WS) == 0);
14940a6c4d8dSSam Clegg         wasm::WasmGlobal Global;
14950a6c4d8dSSam Clegg         Global.Type = WS.getGlobalType();
14960a6c4d8dSSam Clegg         Global.Index = NumGlobalImports + Globals.size();
14970a6c4d8dSSam Clegg         switch (Global.Type.Type) {
14980a6c4d8dSSam Clegg         case wasm::WASM_TYPE_I32:
14990a6c4d8dSSam Clegg           Global.InitExpr.Opcode = wasm::WASM_OPCODE_I32_CONST;
15000a6c4d8dSSam Clegg           break;
15010a6c4d8dSSam Clegg         case wasm::WASM_TYPE_I64:
15020a6c4d8dSSam Clegg           Global.InitExpr.Opcode = wasm::WASM_OPCODE_I64_CONST;
15030a6c4d8dSSam Clegg           break;
15040a6c4d8dSSam Clegg         case wasm::WASM_TYPE_F32:
15050a6c4d8dSSam Clegg           Global.InitExpr.Opcode = wasm::WASM_OPCODE_F32_CONST;
15060a6c4d8dSSam Clegg           break;
15070a6c4d8dSSam Clegg         case wasm::WASM_TYPE_F64:
15080a6c4d8dSSam Clegg           Global.InitExpr.Opcode = wasm::WASM_OPCODE_F64_CONST;
15090a6c4d8dSSam Clegg           break;
151079aad89dSSam Clegg         case wasm::WASM_TYPE_EXTERNREF:
151179aad89dSSam Clegg           Global.InitExpr.Opcode = wasm::WASM_OPCODE_REF_NULL;
151279aad89dSSam Clegg           break;
15130a6c4d8dSSam Clegg         default:
15140a6c4d8dSSam Clegg           llvm_unreachable("unexpected type");
15150a6c4d8dSSam Clegg         }
15160a6c4d8dSSam Clegg         WasmIndices[&WS] = Global.Index;
15170a6c4d8dSSam Clegg         Globals.push_back(Global);
15180a6c4d8dSSam Clegg       } else {
1519545932beSEric Christopher         // An import; the index was assigned above
1520d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "  -> global index: "
1521d34e60caSNicola Zaghen                           << WasmIndices.find(&WS)->second << "\n");
15220a6c4d8dSSam Clegg       }
1523388fb67bSPaulo Matos     } else if (WS.isTable()) {
1524388fb67bSPaulo Matos       if (WS.isDefined()) {
1525388fb67bSPaulo Matos         assert(WasmIndices.count(&WS) == 0);
1526388fb67bSPaulo Matos         wasm::WasmTable Table;
1527388fb67bSPaulo Matos         Table.ElemType = static_cast<uint8_t>(WS.getTableType());
1528388fb67bSPaulo Matos         Table.Index = NumTableImports + Tables.size();
1529388fb67bSPaulo Matos         // FIXME: Work on custom limits is ongoing
1530388fb67bSPaulo Matos         Table.Limits = {wasm::WASM_LIMITS_FLAG_NONE, 0, 0};
1531388fb67bSPaulo Matos 
1532388fb67bSPaulo Matos         WasmIndices[&WS] = Table.Index;
1533388fb67bSPaulo Matos         Tables.push_back(Table);
1534388fb67bSPaulo Matos       }
1535388fb67bSPaulo Matos       LLVM_DEBUG(dbgs() << " -> table index: " << WasmIndices.find(&WS)->second
1536388fb67bSPaulo Matos                         << "\n");
1537da419bdbSHeejin Ahn     } else if (WS.isEvent()) {
1538da419bdbSHeejin Ahn       // C++ exception symbol (__cpp_exception)
1539da419bdbSHeejin Ahn       unsigned Index;
1540da419bdbSHeejin Ahn       if (WS.isDefined()) {
15410a6c4d8dSSam Clegg         assert(WasmIndices.count(&WS) == 0);
1542da419bdbSHeejin Ahn         Index = NumEventImports + Events.size();
1543da419bdbSHeejin Ahn         wasm::WasmEventType Event;
1544da419bdbSHeejin Ahn         Event.SigIndex = getEventType(WS);
1545da419bdbSHeejin Ahn         Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
1546da419bdbSHeejin Ahn         WasmIndices[&WS] = Index;
1547da419bdbSHeejin Ahn         Events.push_back(Event);
1548da419bdbSHeejin Ahn       } else {
1549da419bdbSHeejin Ahn         // An import; the index was assigned above.
1550492f7529SSam Clegg         assert(WasmIndices.count(&WS) > 0);
1551da419bdbSHeejin Ahn       }
1552da419bdbSHeejin Ahn       LLVM_DEBUG(dbgs() << "  -> event index: " << WasmIndices.find(&WS)->second
1553da419bdbSHeejin Ahn                         << "\n");
1554da419bdbSHeejin Ahn 
1555a165f2d6SSam Clegg     } else {
1556a165f2d6SSam Clegg       assert(WS.isSection());
1557d934cb88SDan Gohman     }
1558d934cb88SDan Gohman   }
1559d934cb88SDan Gohman 
1560586320c0SNicholas Wilson   // Populate WasmIndices and DataLocations for aliased symbols.  We need to
1561586320c0SNicholas Wilson   // process these in a separate pass because we need to have processed the
1562586320c0SNicholas Wilson   // target of the alias before the alias itself and the symbols are not
1563586320c0SNicholas Wilson   // necessarily ordered in this way.
1564b7787fd0SSam Clegg   for (const MCSymbol &S : Asm.symbols()) {
1565b7787fd0SSam Clegg     if (!S.isVariable())
1566b7787fd0SSam Clegg       continue;
156731a2c809SSam Clegg 
1568cd65f698SSam Clegg     assert(S.isDefined());
1569b7787fd0SSam Clegg 
15709c7b5808SDominic Chen     const auto *BS = Layout.getBaseSymbol(S);
15719c7b5808SDominic Chen     if (!BS)
15729c7b5808SDominic Chen       report_fatal_error(Twine(S.getName()) +
15739c7b5808SDominic Chen                          ": absolute addressing not supported!");
15749c7b5808SDominic Chen     const MCSymbolWasm *Base = cast<MCSymbolWasm>(BS);
15757ee758d6SSam Clegg 
15765e3d33a7SSam Clegg     // Find the target symbol of this weak alias and export that index
1577aff1c4dfSSam Clegg     const auto &WS = static_cast<const MCSymbolWasm &>(S);
15787ee758d6SSam Clegg     LLVM_DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *Base << "'\n");
1579b7787fd0SSam Clegg 
15807ee758d6SSam Clegg     if (Base->isFunction()) {
15817ee758d6SSam Clegg       assert(WasmIndices.count(Base) > 0);
15827ee758d6SSam Clegg       uint32_t WasmIndex = WasmIndices.find(Base)->second;
1583492f7529SSam Clegg       assert(WasmIndices.count(&WS) == 0);
15846c899ba6SSam Clegg       WasmIndices[&WS] = WasmIndex;
1585d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> index:" << WasmIndex << "\n");
15867ee758d6SSam Clegg     } else if (Base->isData()) {
15877ee758d6SSam Clegg       auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
15887ee758d6SSam Clegg       uint64_t Offset = Layout.getSymbolOffset(S);
15897ee758d6SSam Clegg       int64_t Size = 0;
15907ee758d6SSam Clegg       // For data symbol alias we use the size of the base symbol as the
15917ee758d6SSam Clegg       // size of the alias.  When an offset from the base is involved this
15927ee758d6SSam Clegg       // can result in a offset + size goes past the end of the data section
15937ee758d6SSam Clegg       // which out object format doesn't support.  So we must clamp it.
15947ee758d6SSam Clegg       if (!Base->getSize()->evaluateAsAbsolute(Size, Layout))
15957ee758d6SSam Clegg         report_fatal_error(".size expression must be evaluatable");
15967ee758d6SSam Clegg       const WasmDataSegment &Segment =
15977ee758d6SSam Clegg           DataSegments[DataSection.getSegmentIndex()];
15987ee758d6SSam Clegg       Size =
15997ee758d6SSam Clegg           std::min(static_cast<uint64_t>(Size), Segment.Data.size() - Offset);
16007ee758d6SSam Clegg       wasm::WasmDataReference Ref = wasm::WasmDataReference{
16017ee758d6SSam Clegg           DataSection.getSegmentIndex(),
16027ee758d6SSam Clegg           static_cast<uint32_t>(Layout.getSymbolOffset(S)),
16037ee758d6SSam Clegg           static_cast<uint32_t>(Size)};
16046c899ba6SSam Clegg       DataLocations[&WS] = Ref;
1605d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> index:" << Ref.Segment << "\n");
16066c899ba6SSam Clegg     } else {
1607da419bdbSHeejin Ahn       report_fatal_error("don't yet support global/event aliases");
16086c899ba6SSam Clegg     }
1609586320c0SNicholas Wilson   }
161031a2c809SSam Clegg 
1611586320c0SNicholas Wilson   // Finally, populate the symbol table itself, in its "natural" order.
1612586320c0SNicholas Wilson   for (const MCSymbol &S : Asm.symbols()) {
1613586320c0SNicholas Wilson     const auto &WS = static_cast<const MCSymbolWasm &>(S);
161425d8e68bSSam Clegg     if (!isInSymtab(WS)) {
161518c56a07SHeejin Ahn       WS.setIndex(InvalidIndex);
1616586320c0SNicholas Wilson       continue;
161725d8e68bSSam Clegg     }
1618d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "adding to symtab: " << WS << "\n");
1619586320c0SNicholas Wilson 
1620586320c0SNicholas Wilson     uint32_t Flags = 0;
1621586320c0SNicholas Wilson     if (WS.isWeak())
1622586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_BINDING_WEAK;
1623586320c0SNicholas Wilson     if (WS.isHidden())
1624586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN;
1625586320c0SNicholas Wilson     if (!WS.isExternal() && WS.isDefined())
1626586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;
1627586320c0SNicholas Wilson     if (WS.isUndefined())
1628586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_UNDEFINED;
1629da84b688SDan Gohman     if (WS.isNoStrip()) {
1630da84b688SDan Gohman       Flags |= wasm::WASM_SYMBOL_NO_STRIP;
1631da84b688SDan Gohman       if (isEmscripten()) {
1632d6ef8da3SSam Clegg         Flags |= wasm::WASM_SYMBOL_EXPORTED;
1633da84b688SDan Gohman       }
1634da84b688SDan Gohman     }
1635b4f4e370SSam Clegg     if (WS.hasImportName())
163629874ceaSDan Gohman       Flags |= wasm::WASM_SYMBOL_EXPLICIT_NAME;
1637881d8778SSam Clegg     if (WS.hasExportName())
1638881d8778SSam Clegg       Flags |= wasm::WASM_SYMBOL_EXPORTED;
1639586320c0SNicholas Wilson 
1640586320c0SNicholas Wilson     wasm::WasmSymbolInfo Info;
1641586320c0SNicholas Wilson     Info.Name = WS.getName();
1642586320c0SNicholas Wilson     Info.Kind = WS.getType();
1643586320c0SNicholas Wilson     Info.Flags = Flags;
16444d57fbd0SSam Clegg     if (!WS.isData()) {
16454d57fbd0SSam Clegg       assert(WasmIndices.count(&WS) > 0);
1646586320c0SNicholas Wilson       Info.ElementIndex = WasmIndices.find(&WS)->second;
16474d57fbd0SSam Clegg     } else if (WS.isDefined()) {
16484d57fbd0SSam Clegg       assert(DataLocations.count(&WS) > 0);
1649586320c0SNicholas Wilson       Info.DataRef = DataLocations.find(&WS)->second;
16504d57fbd0SSam Clegg     }
165125d8e68bSSam Clegg     WS.setIndex(SymbolInfos.size());
1652586320c0SNicholas Wilson     SymbolInfos.emplace_back(Info);
1653b7787fd0SSam Clegg   }
1654b7787fd0SSam Clegg 
16556006e091SSam Clegg   {
16566006e091SSam Clegg     auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
1657f9edbe95SSam Clegg       // Functions referenced by a relocation need to put in the table.  This is
1658f9edbe95SSam Clegg       // purely to make the object file's provisional values readable, and is
1659f9edbe95SSam Clegg       // ignored by the linker, which re-calculates the relocations itself.
1660d1152a26SSam Clegg       if (Rel.Type != wasm::R_WASM_TABLE_INDEX_I32 &&
1661cc1b9b68SWouter van Oortmerssen           Rel.Type != wasm::R_WASM_TABLE_INDEX_I64 &&
166281443ac1SSam Clegg           Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB &&
1663cc1b9b68SWouter van Oortmerssen           Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB64 &&
166481443ac1SSam Clegg           Rel.Type != wasm::R_WASM_TABLE_INDEX_REL_SLEB)
1665f9edbe95SSam Clegg         return;
1666f9edbe95SSam Clegg       assert(Rel.Symbol->isFunction());
16677ee758d6SSam Clegg       const MCSymbolWasm *Base =
16687ee758d6SSam Clegg           cast<MCSymbolWasm>(Layout.getBaseSymbol(*Rel.Symbol));
16697ee758d6SSam Clegg       uint32_t FunctionIndex = WasmIndices.find(Base)->second;
167018c56a07SHeejin Ahn       uint32_t TableIndex = TableElems.size() + InitialTableOffset;
16717ee758d6SSam Clegg       if (TableIndices.try_emplace(Base, TableIndex).second) {
16727ee758d6SSam Clegg         LLVM_DEBUG(dbgs() << "  -> adding " << Base->getName()
1673f9edbe95SSam Clegg                           << " to table: " << TableIndex << "\n");
16746c899ba6SSam Clegg         TableElems.push_back(FunctionIndex);
16757ee758d6SSam Clegg         registerFunctionType(*Base);
16766006e091SSam Clegg       }
16776006e091SSam Clegg     };
1678970d02c4SDan Gohman 
16796006e091SSam Clegg     for (const WasmRelocationEntry &RelEntry : CodeRelocations)
16806006e091SSam Clegg       HandleReloc(RelEntry);
16816006e091SSam Clegg     for (const WasmRelocationEntry &RelEntry : DataRelocations)
16826006e091SSam Clegg       HandleReloc(RelEntry);
1683d934cb88SDan Gohman   }
1684d934cb88SDan Gohman 
1685bafe6902SSam Clegg   // Translate .init_array section contents into start functions.
1686bafe6902SSam Clegg   for (const MCSection &S : Asm) {
1687bafe6902SSam Clegg     const auto &WS = static_cast<const MCSectionWasm &>(S);
16887d1ff446SFangrui Song     if (WS.getName().startswith(".fini_array"))
1689bafe6902SSam Clegg       report_fatal_error(".fini_array sections are unsupported");
16907d1ff446SFangrui Song     if (!WS.getName().startswith(".init_array"))
1691bafe6902SSam Clegg       continue;
1692bafe6902SSam Clegg     if (WS.getFragmentList().empty())
1693bafe6902SSam Clegg       continue;
1694b210c64bSSam Clegg 
1695b210c64bSSam Clegg     // init_array is expected to contain a single non-empty data fragment
1696b210c64bSSam Clegg     if (WS.getFragmentList().size() != 3)
1697bafe6902SSam Clegg       report_fatal_error("only one .init_array section fragment supported");
1698b210c64bSSam Clegg 
1699b210c64bSSam Clegg     auto IT = WS.begin();
1700b210c64bSSam Clegg     const MCFragment &EmptyFrag = *IT;
1701b210c64bSSam Clegg     if (EmptyFrag.getKind() != MCFragment::FT_Data)
1702b210c64bSSam Clegg       report_fatal_error(".init_array section should be aligned");
1703b210c64bSSam Clegg 
1704b210c64bSSam Clegg     IT = std::next(IT);
1705b210c64bSSam Clegg     const MCFragment &AlignFrag = *IT;
1706bafe6902SSam Clegg     if (AlignFrag.getKind() != MCFragment::FT_Align)
1707bafe6902SSam Clegg       report_fatal_error(".init_array section should be aligned");
1708bafe6902SSam Clegg     if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
1709bafe6902SSam Clegg       report_fatal_error(".init_array section should be aligned for pointers");
1710b210c64bSSam Clegg 
1711b210c64bSSam Clegg     const MCFragment &Frag = *std::next(IT);
1712bafe6902SSam Clegg     if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1713bafe6902SSam Clegg       report_fatal_error("only data supported in .init_array section");
1714b210c64bSSam Clegg 
1715bafe6902SSam Clegg     uint16_t Priority = UINT16_MAX;
17164d57fbd0SSam Clegg     unsigned PrefixLength = strlen(".init_array");
17177d1ff446SFangrui Song     if (WS.getName().size() > PrefixLength) {
17187d1ff446SFangrui Song       if (WS.getName()[PrefixLength] != '.')
1719f208f631SHeejin Ahn         report_fatal_error(
1720f208f631SHeejin Ahn             ".init_array section priority should start with '.'");
17217d1ff446SFangrui Song       if (WS.getName().substr(PrefixLength + 1).getAsInteger(10, Priority))
1722bafe6902SSam Clegg         report_fatal_error("invalid .init_array section priority");
1723bafe6902SSam Clegg     }
1724bafe6902SSam Clegg     const auto &DataFrag = cast<MCDataFragment>(Frag);
1725bafe6902SSam Clegg     const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1726f208f631SHeejin Ahn     for (const uint8_t *
172718c56a07SHeejin Ahn              P = (const uint8_t *)Contents.data(),
172818c56a07SHeejin Ahn             *End = (const uint8_t *)Contents.data() + Contents.size();
172918c56a07SHeejin Ahn          P != End; ++P) {
173018c56a07SHeejin Ahn       if (*P != 0)
1731bafe6902SSam Clegg         report_fatal_error("non-symbolic data in .init_array section");
1732bafe6902SSam Clegg     }
1733bafe6902SSam Clegg     for (const MCFixup &Fixup : DataFrag.getFixups()) {
1734f208f631SHeejin Ahn       assert(Fixup.getKind() ==
1735f208f631SHeejin Ahn              MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
1736bafe6902SSam Clegg       const MCExpr *Expr = Fixup.getValue();
17378fffa1dfSSam Clegg       auto *SymRef = dyn_cast<MCSymbolRefExpr>(Expr);
17388fffa1dfSSam Clegg       if (!SymRef)
1739bafe6902SSam Clegg         report_fatal_error("fixups in .init_array should be symbol references");
17408fffa1dfSSam Clegg       const auto &TargetSym = cast<const MCSymbolWasm>(SymRef->getSymbol());
17418fffa1dfSSam Clegg       if (TargetSym.getIndex() == InvalidIndex)
17423ea1c62cSSam Clegg         report_fatal_error("symbols in .init_array should exist in symtab");
17438fffa1dfSSam Clegg       if (!TargetSym.isFunction())
17448fffa1dfSSam Clegg         report_fatal_error("symbols in .init_array should be for functions");
174525d8e68bSSam Clegg       InitFuncs.push_back(
17468fffa1dfSSam Clegg           std::make_pair(Priority, TargetSym.getIndex()));
1747bafe6902SSam Clegg     }
1748bafe6902SSam Clegg   }
1749bafe6902SSam Clegg 
175018eafb6cSDan Gohman   // Write out the Wasm header.
175118eafb6cSDan Gohman   writeHeader(Asm);
175218eafb6cSDan Gohman 
17530ff28fa6SDerek Schuff   uint32_t CodeSectionIndex, DataSectionIndex;
17540ff28fa6SDerek Schuff   if (Mode != DwoMode::DwoOnly) {
1755da419bdbSHeejin Ahn     writeTypeSection(Signatures);
1756f950b24aSSam Clegg     writeImportSection(Imports, DataSize, TableElems.size());
17579e15f359SSam Clegg     writeFunctionSection(Functions);
1758f950b24aSSam Clegg     // Skip the "memory" section; we import the memory instead.
1759da419bdbSHeejin Ahn     writeEventSection(Events);
17600a6c4d8dSSam Clegg     writeGlobalSection(Globals);
1761388fb67bSPaulo Matos     writeTableSection(Tables);
17629e15f359SSam Clegg     writeExportSection(Exports);
17639e15f359SSam Clegg     writeElemSection(TableElems);
1764fef8de66SThomas Lively     writeDataCountSection();
17650ff28fa6SDerek Schuff 
17660ff28fa6SDerek Schuff     CodeSectionIndex = writeCodeSection(Asm, Layout, Functions);
17670ff28fa6SDerek Schuff     DataSectionIndex = writeDataSection(Layout);
17680ff28fa6SDerek Schuff   }
17690ff28fa6SDerek Schuff 
17700ff28fa6SDerek Schuff   for (auto &CustomSection : CustomSections) {
1771cbda16ebSThomas Lively     writeCustomSection(CustomSection, Asm, Layout);
17720ff28fa6SDerek Schuff   }
17730ff28fa6SDerek Schuff 
17740ff28fa6SDerek Schuff   if (Mode != DwoMode::DwoOnly) {
1775c22bfb6bSNicholas Wilson     writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats);
17760ff28fa6SDerek Schuff 
17776f08c84aSSam Clegg     writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations);
17786f08c84aSSam Clegg     writeRelocSection(DataSectionIndex, "DATA", DataRelocations);
17790ff28fa6SDerek Schuff   }
17806a31a0d6SSam Clegg   writeCustomRelocSections();
1781cbda16ebSThomas Lively   if (ProducersSection)
1782cbda16ebSThomas Lively     writeCustomSection(*ProducersSection, Asm, Layout);
1783f6f4f843SThomas Lively   if (TargetFeaturesSection)
1784f6f4f843SThomas Lively     writeCustomSection(*TargetFeaturesSection, Asm, Layout);
1785970d02c4SDan Gohman 
1786d934cb88SDan Gohman   // TODO: Translate the .comment section to the output.
17870ff28fa6SDerek Schuff   return W->OS.tell() - StartOffset;
178818eafb6cSDan Gohman }
178918eafb6cSDan Gohman 
179060fbc7ccSLang Hames std::unique_ptr<MCObjectWriter>
17911301a878SLang Hames llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
179218eafb6cSDan Gohman                              raw_pwrite_stream &OS) {
17930eaee545SJonas Devlieghere   return std::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
179418eafb6cSDan Gohman }
17950ff28fa6SDerek Schuff 
17960ff28fa6SDerek Schuff std::unique_ptr<MCObjectWriter>
17970ff28fa6SDerek Schuff llvm::createWasmDwoObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
17980ff28fa6SDerek Schuff                                 raw_pwrite_stream &OS,
17990ff28fa6SDerek Schuff                                 raw_pwrite_stream &DwoOS) {
18000ff28fa6SDerek Schuff   return std::make_unique<WasmObjectWriter>(std::move(MOTW), OS, DwoOS);
18010ff28fa6SDerek Schuff }
1802