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 ||
481*16f02431SWouter van Oortmerssen       Type == wasm::R_WASM_FUNCTION_OFFSET_I64 ||
482d1152a26SSam Clegg       Type == wasm::R_WASM_SECTION_OFFSET_I32) {
4834d57fbd0SSam Clegg     if (!FixupSection.getKind().isMetadata())
4844d57fbd0SSam Clegg       report_fatal_error("relocations for function or section offsets are "
4854d57fbd0SSam Clegg                          "only supported in metadata sections");
4864d57fbd0SSam Clegg 
4874d57fbd0SSam Clegg     const MCSymbol *SectionSymbol = nullptr;
4884d57fbd0SSam Clegg     const MCSection &SecA = SymA->getSection();
4894d57fbd0SSam Clegg     if (SecA.getKind().isText())
4906ccb59b3SSam Clegg       SectionSymbol = SectionFunctions.find(&SecA)->second;
4914d57fbd0SSam Clegg     else
4924d57fbd0SSam Clegg       SectionSymbol = SecA.getBeginSymbol();
4934d57fbd0SSam Clegg     if (!SectionSymbol)
4944d57fbd0SSam Clegg       report_fatal_error("section symbol is required for relocation");
4954d57fbd0SSam Clegg 
4964d57fbd0SSam Clegg     C += Layout.getSymbolOffset(*SymA);
4974d57fbd0SSam Clegg     SymA = cast<MCSymbolWasm>(SectionSymbol);
4984d57fbd0SSam Clegg   }
4994d57fbd0SSam Clegg 
500d1152a26SSam Clegg   // Relocation other than R_WASM_TYPE_INDEX_LEB are required to be
5014d57fbd0SSam Clegg   // against a named symbol.
502d1152a26SSam Clegg   if (Type != wasm::R_WASM_TYPE_INDEX_LEB) {
5034d57fbd0SSam Clegg     if (SymA->getName().empty())
5044d57fbd0SSam Clegg       report_fatal_error("relocations against un-named temporaries are not yet "
5054d57fbd0SSam Clegg                          "supported by wasm");
5064d57fbd0SSam Clegg 
5074d57fbd0SSam Clegg     SymA->setUsedInReloc();
5084d57fbd0SSam Clegg   }
509ae03c1e7SSam Clegg 
510492f7529SSam Clegg   if (RefA->getKind() == MCSymbolRefExpr::VK_GOT)
511492f7529SSam Clegg     SymA->setUsedInGOT();
512492f7529SSam Clegg 
513d934cb88SDan Gohman   WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
514d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
515d934cb88SDan Gohman 
5166a31a0d6SSam Clegg   if (FixupSection.isWasmData()) {
517d934cb88SDan Gohman     DataRelocations.push_back(Rec);
5186a31a0d6SSam Clegg   } else if (FixupSection.getKind().isText()) {
51912fd3da9SSam Clegg     CodeRelocations.push_back(Rec);
5206a31a0d6SSam Clegg   } else if (FixupSection.getKind().isMetadata()) {
5216a31a0d6SSam Clegg     CustomSectionsRelocations[&FixupSection].push_back(Rec);
5226a31a0d6SSam Clegg   } else {
52312fd3da9SSam Clegg     llvm_unreachable("unexpected section type");
524d934cb88SDan Gohman   }
5256a31a0d6SSam Clegg }
526d934cb88SDan Gohman 
527d934cb88SDan Gohman // Compute a value to write into the code at the location covered
52860ec3034SSam Clegg // by RelEntry. This value isn't used by the static linker; it just serves
52960ec3034SSam Clegg // to make the object format more readable and more likely to be directly
53060ec3034SSam Clegg // useable.
5313b29376eSWouter van Oortmerssen uint64_t
5327ee758d6SSam Clegg WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry,
5337ee758d6SSam Clegg                                       const MCAsmLayout &Layout) {
53448139ebcSWouter van Oortmerssen   if ((RelEntry.Type == wasm::R_WASM_GLOBAL_INDEX_LEB ||
53548139ebcSWouter van Oortmerssen        RelEntry.Type == wasm::R_WASM_GLOBAL_INDEX_I32) &&
53648139ebcSWouter van Oortmerssen       !RelEntry.Symbol->isGlobal()) {
537492f7529SSam Clegg     assert(GOTIndices.count(RelEntry.Symbol) > 0 && "symbol not found in GOT index space");
538492f7529SSam Clegg     return GOTIndices[RelEntry.Symbol];
539492f7529SSam Clegg   }
540492f7529SSam Clegg 
54160ec3034SSam Clegg   switch (RelEntry.Type) {
5422a7cac93SSam Clegg   case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
543d1152a26SSam Clegg   case wasm::R_WASM_TABLE_INDEX_SLEB:
544cc1b9b68SWouter van Oortmerssen   case wasm::R_WASM_TABLE_INDEX_SLEB64:
545cc1b9b68SWouter van Oortmerssen   case wasm::R_WASM_TABLE_INDEX_I32:
546cc1b9b68SWouter van Oortmerssen   case wasm::R_WASM_TABLE_INDEX_I64: {
547f9edbe95SSam Clegg     // Provisional value is table address of the resolved symbol itself
5487ee758d6SSam Clegg     const MCSymbolWasm *Base =
5497ee758d6SSam Clegg         cast<MCSymbolWasm>(Layout.getBaseSymbol(*RelEntry.Symbol));
5507ee758d6SSam Clegg     assert(Base->isFunction());
55181443ac1SSam Clegg     if (RelEntry.Type == wasm::R_WASM_TABLE_INDEX_REL_SLEB)
5527ee758d6SSam Clegg       return TableIndices[Base] - InitialTableOffset;
55381443ac1SSam Clegg     else
5547ee758d6SSam Clegg       return TableIndices[Base];
555f9edbe95SSam Clegg   }
556d1152a26SSam Clegg   case wasm::R_WASM_TYPE_INDEX_LEB:
5576c899ba6SSam Clegg     // Provisional value is same as the index
55860ec3034SSam Clegg     return getRelocationIndexValue(RelEntry);
559d1152a26SSam Clegg   case wasm::R_WASM_FUNCTION_INDEX_LEB:
560d1152a26SSam Clegg   case wasm::R_WASM_GLOBAL_INDEX_LEB:
56148139ebcSWouter van Oortmerssen   case wasm::R_WASM_GLOBAL_INDEX_I32:
562d1152a26SSam Clegg   case wasm::R_WASM_EVENT_INDEX_LEB:
56369e2797eSPaulo Matos   case wasm::R_WASM_TABLE_NUMBER_LEB:
564da419bdbSHeejin Ahn     // Provisional value is function/global/event Wasm index
565492f7529SSam Clegg     assert(WasmIndices.count(RelEntry.Symbol) > 0 && "symbol not found in wasm index space");
5666c899ba6SSam Clegg     return WasmIndices[RelEntry.Symbol];
567d1152a26SSam Clegg   case wasm::R_WASM_FUNCTION_OFFSET_I32:
568*16f02431SWouter van Oortmerssen   case wasm::R_WASM_FUNCTION_OFFSET_I64:
569d1152a26SSam Clegg   case wasm::R_WASM_SECTION_OFFSET_I32: {
5706a31a0d6SSam Clegg     const auto &Section =
5716a31a0d6SSam Clegg         static_cast<const MCSectionWasm &>(RelEntry.Symbol->getSection());
5726a31a0d6SSam Clegg     return Section.getSectionOffset() + RelEntry.Addend;
5736a31a0d6SSam Clegg   }
574d1152a26SSam Clegg   case wasm::R_WASM_MEMORY_ADDR_LEB:
5753b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_LEB64:
5763b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_SLEB:
5773b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_SLEB64:
5782a7cac93SSam Clegg   case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
5793b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_REL_SLEB64:
5803b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_I32:
581a28a4662SSam Clegg   case wasm::R_WASM_MEMORY_ADDR_I64:
582a28a4662SSam Clegg   case wasm::R_WASM_MEMORY_ADDR_TLS_SLEB: {
5839c7b5808SDominic Chen     // Provisional value is address of the global plus the offset
5847ee758d6SSam Clegg     const MCSymbolWasm *Base =
5857ee758d6SSam Clegg         cast<MCSymbolWasm>(Layout.getBaseSymbol(*RelEntry.Symbol));
586270ed1b3SSam Clegg     // For undefined symbols, use zero
5877ee758d6SSam Clegg     if (!Base->isDefined())
588270ed1b3SSam Clegg       return 0;
5899c7b5808SDominic Chen     const wasm::WasmDataReference &BaseRef = DataLocations[Base],
5909c7b5808SDominic Chen                                   &SymRef = DataLocations[RelEntry.Symbol];
5919c7b5808SDominic Chen     const WasmDataSegment &Segment = DataSegments[BaseRef.Segment];
592d934cb88SDan Gohman     // Ignore overflow. LLVM allows address arithmetic to silently wrap.
5939c7b5808SDominic Chen     return Segment.Offset + BaseRef.Offset + SymRef.Offset + RelEntry.Addend;
59460ec3034SSam Clegg   }
59560ec3034SSam Clegg   default:
59660ec3034SSam Clegg     llvm_unreachable("invalid relocation type");
59760ec3034SSam Clegg   }
598d934cb88SDan Gohman }
599d934cb88SDan Gohman 
600759631c7SSam Clegg static void addData(SmallVectorImpl<char> &DataBytes,
60163ebb813SSam Clegg                     MCSectionWasm &DataSection) {
6027d1ff446SFangrui Song   LLVM_DEBUG(errs() << "addData: " << DataSection.getName() << "\n");
603759631c7SSam Clegg 
60463ebb813SSam Clegg   DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
60563ebb813SSam Clegg 
606759631c7SSam Clegg   for (const MCFragment &Frag : DataSection) {
607759631c7SSam Clegg     if (Frag.hasInstructions())
608759631c7SSam Clegg       report_fatal_error("only data supported in data sections");
609759631c7SSam Clegg 
610759631c7SSam Clegg     if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
611759631c7SSam Clegg       if (Align->getValueSize() != 1)
612759631c7SSam Clegg         report_fatal_error("only byte values supported for alignment");
613759631c7SSam Clegg       // If nops are requested, use zeros, as this is the data section.
614759631c7SSam Clegg       uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
615f208f631SHeejin Ahn       uint64_t Size =
616f208f631SHeejin Ahn           std::min<uint64_t>(alignTo(DataBytes.size(), Align->getAlignment()),
617f208f631SHeejin Ahn                              DataBytes.size() + Align->getMaxBytesToEmit());
618759631c7SSam Clegg       DataBytes.resize(Size, Value);
619759631c7SSam Clegg     } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
620588fad4dSNirav Dave       int64_t NumValues;
621588fad4dSNirav Dave       if (!Fill->getNumValues().evaluateAsAbsolute(NumValues))
622d707c370SRafael Espindola         llvm_unreachable("The fill should be an assembler constant");
623588fad4dSNirav Dave       DataBytes.insert(DataBytes.end(), Fill->getValueSize() * NumValues,
624588fad4dSNirav Dave                        Fill->getValue());
62524faf859SHeejin Ahn     } else if (auto *LEB = dyn_cast<MCLEBFragment>(&Frag)) {
62624faf859SHeejin Ahn       const SmallVectorImpl<char> &Contents = LEB->getContents();
62724faf859SHeejin Ahn       DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
628759631c7SSam Clegg     } else {
629759631c7SSam Clegg       const auto &DataFrag = cast<MCDataFragment>(Frag);
630759631c7SSam Clegg       const SmallVectorImpl<char> &Contents = DataFrag.getContents();
631759631c7SSam Clegg       DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
632759631c7SSam Clegg     }
633759631c7SSam Clegg   }
634759631c7SSam Clegg 
635d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
636759631c7SSam Clegg }
637759631c7SSam Clegg 
63860ec3034SSam Clegg uint32_t
63960ec3034SSam Clegg WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
640d1152a26SSam Clegg   if (RelEntry.Type == wasm::R_WASM_TYPE_INDEX_LEB) {
641b7787fd0SSam Clegg     if (!TypeIndices.count(RelEntry.Symbol))
642b7787fd0SSam Clegg       report_fatal_error("symbol not found in type index space: " +
643b7787fd0SSam Clegg                          RelEntry.Symbol->getName());
644acd7d2b0SSam Clegg     return TypeIndices[RelEntry.Symbol];
645acd7d2b0SSam Clegg   }
64660ec3034SSam Clegg 
64725d8e68bSSam Clegg   return RelEntry.Symbol->getIndex();
648acd7d2b0SSam Clegg }
649acd7d2b0SSam Clegg 
650d934cb88SDan Gohman // Apply the portions of the relocation records that we can handle ourselves
651d934cb88SDan Gohman // directly.
652acd7d2b0SSam Clegg void WasmObjectWriter::applyRelocations(
6537ee758d6SSam Clegg     ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset,
6547ee758d6SSam Clegg     const MCAsmLayout &Layout) {
6550ff28fa6SDerek Schuff   auto &Stream = static_cast<raw_pwrite_stream &>(W->OS);
656d934cb88SDan Gohman   for (const WasmRelocationEntry &RelEntry : Relocations) {
657d934cb88SDan Gohman     uint64_t Offset = ContentsOffset +
658d934cb88SDan Gohman                       RelEntry.FixupSection->getSectionOffset() +
659d934cb88SDan Gohman                       RelEntry.Offset;
660d934cb88SDan Gohman 
661d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
6627ee758d6SSam Clegg     auto Value = getProvisionalValue(RelEntry, Layout);
66360ec3034SSam Clegg 
664acd7d2b0SSam Clegg     switch (RelEntry.Type) {
665d1152a26SSam Clegg     case wasm::R_WASM_FUNCTION_INDEX_LEB:
666d1152a26SSam Clegg     case wasm::R_WASM_TYPE_INDEX_LEB:
667d1152a26SSam Clegg     case wasm::R_WASM_GLOBAL_INDEX_LEB:
668d1152a26SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_LEB:
669d1152a26SSam Clegg     case wasm::R_WASM_EVENT_INDEX_LEB:
67069e2797eSPaulo Matos     case wasm::R_WASM_TABLE_NUMBER_LEB:
6713b29376eSWouter van Oortmerssen       writePatchableLEB<5>(Stream, Value, Offset);
6723b29376eSWouter van Oortmerssen       break;
6733b29376eSWouter van Oortmerssen     case wasm::R_WASM_MEMORY_ADDR_LEB64:
6743b29376eSWouter van Oortmerssen       writePatchableLEB<10>(Stream, Value, Offset);
675d934cb88SDan Gohman       break;
676d1152a26SSam Clegg     case wasm::R_WASM_TABLE_INDEX_I32:
677d1152a26SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_I32:
678d1152a26SSam Clegg     case wasm::R_WASM_FUNCTION_OFFSET_I32:
679d1152a26SSam Clegg     case wasm::R_WASM_SECTION_OFFSET_I32:
68048139ebcSWouter van Oortmerssen     case wasm::R_WASM_GLOBAL_INDEX_I32:
6810a6c4d8dSSam Clegg       patchI32(Stream, Value, Offset);
682d934cb88SDan Gohman       break;
683cc1b9b68SWouter van Oortmerssen     case wasm::R_WASM_TABLE_INDEX_I64:
6843b29376eSWouter van Oortmerssen     case wasm::R_WASM_MEMORY_ADDR_I64:
685*16f02431SWouter van Oortmerssen     case wasm::R_WASM_FUNCTION_OFFSET_I64:
6863b29376eSWouter van Oortmerssen       patchI64(Stream, Value, Offset);
6873b29376eSWouter van Oortmerssen       break;
688d1152a26SSam Clegg     case wasm::R_WASM_TABLE_INDEX_SLEB:
6892a7cac93SSam Clegg     case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
690d1152a26SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_SLEB:
6912a7cac93SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
692a28a4662SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_TLS_SLEB:
6933b29376eSWouter van Oortmerssen       writePatchableSLEB<5>(Stream, Value, Offset);
6943b29376eSWouter van Oortmerssen       break;
695cc1b9b68SWouter van Oortmerssen     case wasm::R_WASM_TABLE_INDEX_SLEB64:
6963b29376eSWouter van Oortmerssen     case wasm::R_WASM_MEMORY_ADDR_SLEB64:
6973b29376eSWouter van Oortmerssen     case wasm::R_WASM_MEMORY_ADDR_REL_SLEB64:
6983b29376eSWouter van Oortmerssen       writePatchableSLEB<10>(Stream, Value, Offset);
69960ec3034SSam Clegg       break;
700d934cb88SDan Gohman     default:
7019d24fb7fSSam Clegg       llvm_unreachable("invalid relocation type");
702d934cb88SDan Gohman     }
703d934cb88SDan Gohman   }
70418eafb6cSDan Gohman }
70518eafb6cSDan Gohman 
7064c41fb5aSHeejin Ahn void WasmObjectWriter::writeTypeSection(
7074c41fb5aSHeejin Ahn     ArrayRef<wasm::WasmSignature> Signatures) {
708da419bdbSHeejin Ahn   if (Signatures.empty())
7099e15f359SSam Clegg     return;
7109e15f359SSam Clegg 
7119e15f359SSam Clegg   SectionBookkeeping Section;
7129e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_TYPE);
7139e15f359SSam Clegg 
7140ff28fa6SDerek Schuff   encodeULEB128(Signatures.size(), W->OS);
7159e15f359SSam Clegg 
7164c41fb5aSHeejin Ahn   for (const wasm::WasmSignature &Sig : Signatures) {
7170ff28fa6SDerek Schuff     W->OS << char(wasm::WASM_TYPE_FUNC);
7180ff28fa6SDerek Schuff     encodeULEB128(Sig.Params.size(), W->OS);
719da419bdbSHeejin Ahn     for (wasm::ValType Ty : Sig.Params)
7209e15f359SSam Clegg       writeValueType(Ty);
7210ff28fa6SDerek Schuff     encodeULEB128(Sig.Returns.size(), W->OS);
722da419bdbSHeejin Ahn     for (wasm::ValType Ty : Sig.Returns)
7239e15f359SSam Clegg       writeValueType(Ty);
7249e15f359SSam Clegg   }
7259e15f359SSam Clegg 
7269e15f359SSam Clegg   endSection(Section);
7279e15f359SSam Clegg }
7289e15f359SSam Clegg 
7298defa952SSam Clegg void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports,
7304d135b04SWouter van Oortmerssen                                           uint64_t DataSize,
731f950b24aSSam Clegg                                           uint32_t NumElements) {
7329e15f359SSam Clegg   if (Imports.empty())
7339e15f359SSam Clegg     return;
7349e15f359SSam Clegg 
7354d135b04SWouter van Oortmerssen   uint64_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
736f950b24aSSam Clegg 
7379e15f359SSam Clegg   SectionBookkeeping Section;
7389e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_IMPORT);
7399e15f359SSam Clegg 
7400ff28fa6SDerek Schuff   encodeULEB128(Imports.size(), W->OS);
7418defa952SSam Clegg   for (const wasm::WasmImport &Import : Imports) {
7428defa952SSam Clegg     writeString(Import.Module);
7438defa952SSam Clegg     writeString(Import.Field);
7440ff28fa6SDerek Schuff     W->OS << char(Import.Kind);
7459e15f359SSam Clegg 
7469e15f359SSam Clegg     switch (Import.Kind) {
7479e15f359SSam Clegg     case wasm::WASM_EXTERNAL_FUNCTION:
7480ff28fa6SDerek Schuff       encodeULEB128(Import.SigIndex, W->OS);
7499e15f359SSam Clegg       break;
7509e15f359SSam Clegg     case wasm::WASM_EXTERNAL_GLOBAL:
7510ff28fa6SDerek Schuff       W->OS << char(Import.Global.Type);
7520ff28fa6SDerek Schuff       W->OS << char(Import.Global.Mutable ? 1 : 0);
7539e15f359SSam Clegg       break;
754f950b24aSSam Clegg     case wasm::WASM_EXTERNAL_MEMORY:
7550ff28fa6SDerek Schuff       encodeULEB128(Import.Memory.Flags, W->OS);
7560ff28fa6SDerek Schuff       encodeULEB128(NumPages, W->OS); // initial
757f950b24aSSam Clegg       break;
758f950b24aSSam Clegg     case wasm::WASM_EXTERNAL_TABLE:
7590ff28fa6SDerek Schuff       W->OS << char(Import.Table.ElemType);
7600ff28fa6SDerek Schuff       encodeULEB128(0, W->OS);           // flags
7610ff28fa6SDerek Schuff       encodeULEB128(NumElements, W->OS); // initial
762f950b24aSSam Clegg       break;
763da419bdbSHeejin Ahn     case wasm::WASM_EXTERNAL_EVENT:
7640ff28fa6SDerek Schuff       encodeULEB128(Import.Event.Attribute, W->OS);
7650ff28fa6SDerek Schuff       encodeULEB128(Import.Event.SigIndex, W->OS);
766da419bdbSHeejin Ahn       break;
7679e15f359SSam Clegg     default:
7689e15f359SSam Clegg       llvm_unreachable("unsupported import kind");
7699e15f359SSam Clegg     }
7709e15f359SSam Clegg   }
7719e15f359SSam Clegg 
7729e15f359SSam Clegg   endSection(Section);
7739e15f359SSam Clegg }
7749e15f359SSam Clegg 
775457fb0b4SSam Clegg void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
7769e15f359SSam Clegg   if (Functions.empty())
7779e15f359SSam Clegg     return;
7789e15f359SSam Clegg 
7799e15f359SSam Clegg   SectionBookkeeping Section;
7809e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_FUNCTION);
7819e15f359SSam Clegg 
7820ff28fa6SDerek Schuff   encodeULEB128(Functions.size(), W->OS);
7839e15f359SSam Clegg   for (const WasmFunction &Func : Functions)
7840ff28fa6SDerek Schuff     encodeULEB128(Func.SigIndex, W->OS);
7859e15f359SSam Clegg 
7869e15f359SSam Clegg   endSection(Section);
7879e15f359SSam Clegg }
7889e15f359SSam Clegg 
789da419bdbSHeejin Ahn void WasmObjectWriter::writeEventSection(ArrayRef<wasm::WasmEventType> Events) {
790da419bdbSHeejin Ahn   if (Events.empty())
791da419bdbSHeejin Ahn     return;
792da419bdbSHeejin Ahn 
793da419bdbSHeejin Ahn   SectionBookkeeping Section;
794da419bdbSHeejin Ahn   startSection(Section, wasm::WASM_SEC_EVENT);
795da419bdbSHeejin Ahn 
7960ff28fa6SDerek Schuff   encodeULEB128(Events.size(), W->OS);
797da419bdbSHeejin Ahn   for (const wasm::WasmEventType &Event : Events) {
7980ff28fa6SDerek Schuff     encodeULEB128(Event.Attribute, W->OS);
7990ff28fa6SDerek Schuff     encodeULEB128(Event.SigIndex, W->OS);
800da419bdbSHeejin Ahn   }
801da419bdbSHeejin Ahn 
802da419bdbSHeejin Ahn   endSection(Section);
803da419bdbSHeejin Ahn }
804da419bdbSHeejin Ahn 
8050a6c4d8dSSam Clegg void WasmObjectWriter::writeGlobalSection(ArrayRef<wasm::WasmGlobal> Globals) {
8060a6c4d8dSSam Clegg   if (Globals.empty())
8070a6c4d8dSSam Clegg     return;
8080a6c4d8dSSam Clegg 
8090a6c4d8dSSam Clegg   SectionBookkeeping Section;
8100a6c4d8dSSam Clegg   startSection(Section, wasm::WASM_SEC_GLOBAL);
8110a6c4d8dSSam Clegg 
8120ff28fa6SDerek Schuff   encodeULEB128(Globals.size(), W->OS);
8130a6c4d8dSSam Clegg   for (const wasm::WasmGlobal &Global : Globals) {
8140ff28fa6SDerek Schuff     encodeULEB128(Global.Type.Type, W->OS);
8150ff28fa6SDerek Schuff     W->OS << char(Global.Type.Mutable);
8160ff28fa6SDerek Schuff     W->OS << char(Global.InitExpr.Opcode);
8170a6c4d8dSSam Clegg     switch (Global.Type.Type) {
8180a6c4d8dSSam Clegg     case wasm::WASM_TYPE_I32:
8190ff28fa6SDerek Schuff       encodeSLEB128(0, W->OS);
8200a6c4d8dSSam Clegg       break;
8210a6c4d8dSSam Clegg     case wasm::WASM_TYPE_I64:
8220ff28fa6SDerek Schuff       encodeSLEB128(0, W->OS);
8230a6c4d8dSSam Clegg       break;
8240a6c4d8dSSam Clegg     case wasm::WASM_TYPE_F32:
8250a6c4d8dSSam Clegg       writeI32(0);
8260a6c4d8dSSam Clegg       break;
8270a6c4d8dSSam Clegg     case wasm::WASM_TYPE_F64:
8280a6c4d8dSSam Clegg       writeI64(0);
8290a6c4d8dSSam Clegg       break;
83079aad89dSSam Clegg     case wasm::WASM_TYPE_EXTERNREF:
83179aad89dSSam Clegg       writeValueType(wasm::ValType::EXTERNREF);
83279aad89dSSam Clegg       break;
8330a6c4d8dSSam Clegg     default:
8340a6c4d8dSSam Clegg       llvm_unreachable("unexpected type");
8350a6c4d8dSSam Clegg     }
8360ff28fa6SDerek Schuff     W->OS << char(wasm::WASM_OPCODE_END);
8370a6c4d8dSSam Clegg   }
8380a6c4d8dSSam Clegg 
8390a6c4d8dSSam Clegg   endSection(Section);
8400a6c4d8dSSam Clegg }
8410a6c4d8dSSam Clegg 
842388fb67bSPaulo Matos void WasmObjectWriter::writeTableSection(ArrayRef<wasm::WasmTable> Tables) {
843388fb67bSPaulo Matos   if (Tables.empty())
844388fb67bSPaulo Matos     return;
845388fb67bSPaulo Matos 
846388fb67bSPaulo Matos   SectionBookkeeping Section;
847388fb67bSPaulo Matos   startSection(Section, wasm::WASM_SEC_TABLE);
848388fb67bSPaulo Matos 
849388fb67bSPaulo Matos   encodeULEB128(Tables.size(), W->OS);
850388fb67bSPaulo Matos   for (const wasm::WasmTable &Table : Tables) {
851388fb67bSPaulo Matos     encodeULEB128(Table.ElemType, W->OS);
852388fb67bSPaulo Matos     encodeULEB128(Table.Limits.Flags, W->OS);
853388fb67bSPaulo Matos     encodeULEB128(Table.Limits.Initial, W->OS);
854388fb67bSPaulo Matos     if (Table.Limits.Flags & wasm::WASM_LIMITS_FLAG_HAS_MAX)
855388fb67bSPaulo Matos       encodeULEB128(Table.Limits.Maximum, W->OS);
856388fb67bSPaulo Matos   }
857388fb67bSPaulo Matos   endSection(Section);
858388fb67bSPaulo Matos }
859388fb67bSPaulo Matos 
8608defa952SSam Clegg void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) {
8619e15f359SSam Clegg   if (Exports.empty())
8629e15f359SSam Clegg     return;
8639e15f359SSam Clegg 
8649e15f359SSam Clegg   SectionBookkeeping Section;
8659e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_EXPORT);
8669e15f359SSam Clegg 
8670ff28fa6SDerek Schuff   encodeULEB128(Exports.size(), W->OS);
8688defa952SSam Clegg   for (const wasm::WasmExport &Export : Exports) {
8698defa952SSam Clegg     writeString(Export.Name);
8700ff28fa6SDerek Schuff     W->OS << char(Export.Kind);
8710ff28fa6SDerek Schuff     encodeULEB128(Export.Index, W->OS);
8729e15f359SSam Clegg   }
8739e15f359SSam Clegg 
8749e15f359SSam Clegg   endSection(Section);
8759e15f359SSam Clegg }
8769e15f359SSam Clegg 
877457fb0b4SSam Clegg void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
8789e15f359SSam Clegg   if (TableElems.empty())
8799e15f359SSam Clegg     return;
8809e15f359SSam Clegg 
8819e15f359SSam Clegg   SectionBookkeeping Section;
8829e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_ELEM);
8839e15f359SSam Clegg 
8840ff28fa6SDerek Schuff   encodeULEB128(1, W->OS); // number of "segments"
8850ff28fa6SDerek Schuff   encodeULEB128(0, W->OS); // the table index
8869e15f359SSam Clegg 
8879e15f359SSam Clegg   // init expr for starting offset
8880ff28fa6SDerek Schuff   W->OS << char(wasm::WASM_OPCODE_I32_CONST);
8890ff28fa6SDerek Schuff   encodeSLEB128(InitialTableOffset, W->OS);
8900ff28fa6SDerek Schuff   W->OS << char(wasm::WASM_OPCODE_END);
8919e15f359SSam Clegg 
8920ff28fa6SDerek Schuff   encodeULEB128(TableElems.size(), W->OS);
8939e15f359SSam Clegg   for (uint32_t Elem : TableElems)
8940ff28fa6SDerek Schuff     encodeULEB128(Elem, W->OS);
8959e15f359SSam Clegg 
8969e15f359SSam Clegg   endSection(Section);
8979e15f359SSam Clegg }
8989e15f359SSam Clegg 
899fef8de66SThomas Lively void WasmObjectWriter::writeDataCountSection() {
900fef8de66SThomas Lively   if (DataSegments.empty())
901fef8de66SThomas Lively     return;
902fef8de66SThomas Lively 
903fef8de66SThomas Lively   SectionBookkeeping Section;
904fef8de66SThomas Lively   startSection(Section, wasm::WASM_SEC_DATACOUNT);
9050ff28fa6SDerek Schuff   encodeULEB128(DataSegments.size(), W->OS);
906fef8de66SThomas Lively   endSection(Section);
907fef8de66SThomas Lively }
908fef8de66SThomas Lively 
909e49584a3SSam Clegg uint32_t WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
910457fb0b4SSam Clegg                                             const MCAsmLayout &Layout,
911457fb0b4SSam Clegg                                             ArrayRef<WasmFunction> Functions) {
9129e15f359SSam Clegg   if (Functions.empty())
913e49584a3SSam Clegg     return 0;
9149e15f359SSam Clegg 
9159e15f359SSam Clegg   SectionBookkeeping Section;
9169e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_CODE);
9179e15f359SSam Clegg 
9180ff28fa6SDerek Schuff   encodeULEB128(Functions.size(), W->OS);
9199e15f359SSam Clegg 
9209e15f359SSam Clegg   for (const WasmFunction &Func : Functions) {
921fe6414b0SSam Clegg     auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
9229e15f359SSam Clegg 
9239e15f359SSam Clegg     int64_t Size = 0;
9249e15f359SSam Clegg     if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
9259e15f359SSam Clegg       report_fatal_error(".size expression must be evaluatable");
9269e15f359SSam Clegg 
9270ff28fa6SDerek Schuff     encodeULEB128(Size, W->OS);
9280ff28fa6SDerek Schuff     FuncSection.setSectionOffset(W->OS.tell() - Section.ContentsOffset);
9290ff28fa6SDerek Schuff     Asm.writeSectionData(W->OS, &FuncSection, Layout);
9309e15f359SSam Clegg   }
9319e15f359SSam Clegg 
9329e15f359SSam Clegg   // Apply fixups.
9337ee758d6SSam Clegg   applyRelocations(CodeRelocations, Section.ContentsOffset, Layout);
9349e15f359SSam Clegg 
9359e15f359SSam Clegg   endSection(Section);
936e49584a3SSam Clegg   return Section.Index;
9379e15f359SSam Clegg }
9389e15f359SSam Clegg 
939e49584a3SSam Clegg uint32_t WasmObjectWriter::writeDataSection(const MCAsmLayout &Layout) {
9406c899ba6SSam Clegg   if (DataSegments.empty())
941e49584a3SSam Clegg     return 0;
9429e15f359SSam Clegg 
9439e15f359SSam Clegg   SectionBookkeeping Section;
9449e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_DATA);
9459e15f359SSam Clegg 
9460ff28fa6SDerek Schuff   encodeULEB128(DataSegments.size(), W->OS); // count
9477c395943SSam Clegg 
9486c899ba6SSam Clegg   for (const WasmDataSegment &Segment : DataSegments) {
9490ff28fa6SDerek Schuff     encodeULEB128(Segment.InitFlags, W->OS); // flags
9502e150409SThomas Lively     if (Segment.InitFlags & wasm::WASM_SEGMENT_HAS_MEMINDEX)
9510ff28fa6SDerek Schuff       encodeULEB128(0, W->OS); // memory index
9522e150409SThomas Lively     if ((Segment.InitFlags & wasm::WASM_SEGMENT_IS_PASSIVE) == 0) {
9530ff28fa6SDerek Schuff       W->OS << char(Segment.Offset > INT32_MAX ? wasm::WASM_OPCODE_I64_CONST
9544d135b04SWouter van Oortmerssen                                                : wasm::WASM_OPCODE_I32_CONST);
9550ff28fa6SDerek Schuff       encodeSLEB128(Segment.Offset, W->OS); // offset
9560ff28fa6SDerek Schuff       W->OS << char(wasm::WASM_OPCODE_END);
9572e150409SThomas Lively     }
9580ff28fa6SDerek Schuff     encodeULEB128(Segment.Data.size(), W->OS); // size
9590ff28fa6SDerek Schuff     Segment.Section->setSectionOffset(W->OS.tell() - Section.ContentsOffset);
9600ff28fa6SDerek Schuff     W->OS << Segment.Data; // data
9617c395943SSam Clegg   }
9629e15f359SSam Clegg 
9639e15f359SSam Clegg   // Apply fixups.
9647ee758d6SSam Clegg   applyRelocations(DataRelocations, Section.ContentsOffset, Layout);
9659e15f359SSam Clegg 
9669e15f359SSam Clegg   endSection(Section);
967e49584a3SSam Clegg   return Section.Index;
9689e15f359SSam Clegg }
9699e15f359SSam Clegg 
9706f08c84aSSam Clegg void WasmObjectWriter::writeRelocSection(
9716f08c84aSSam Clegg     uint32_t SectionIndex, StringRef Name,
972f77dc2a8SSam Clegg     std::vector<WasmRelocationEntry> &Relocs) {
9739e15f359SSam Clegg   // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
9749e15f359SSam Clegg   // for descriptions of the reloc sections.
9759e15f359SSam Clegg 
976f77dc2a8SSam Clegg   if (Relocs.empty())
9779e15f359SSam Clegg     return;
9789e15f359SSam Clegg 
979f77dc2a8SSam Clegg   // First, ensure the relocations are sorted in offset order.  In general they
980f77dc2a8SSam Clegg   // should already be sorted since `recordRelocation` is called in offset
981f77dc2a8SSam Clegg   // order, but for the code section we combine many MC sections into single
982f77dc2a8SSam Clegg   // wasm section, and this order is determined by the order of Asm.Symbols()
983f77dc2a8SSam Clegg   // not the sections order.
984efd94c56SFangrui Song   llvm::stable_sort(
985efd94c56SFangrui Song       Relocs, [](const WasmRelocationEntry &A, const WasmRelocationEntry &B) {
986f77dc2a8SSam Clegg         return (A.Offset + A.FixupSection->getSectionOffset()) <
987f77dc2a8SSam Clegg                (B.Offset + B.FixupSection->getSectionOffset());
988f77dc2a8SSam Clegg       });
989f77dc2a8SSam Clegg 
9909e15f359SSam Clegg   SectionBookkeeping Section;
9916f08c84aSSam Clegg   startCustomSection(Section, std::string("reloc.") + Name.str());
9929e15f359SSam Clegg 
9930ff28fa6SDerek Schuff   encodeULEB128(SectionIndex, W->OS);
9940ff28fa6SDerek Schuff   encodeULEB128(Relocs.size(), W->OS);
995f77dc2a8SSam Clegg   for (const WasmRelocationEntry &RelEntry : Relocs) {
996f208f631SHeejin Ahn     uint64_t Offset =
997f208f631SHeejin Ahn         RelEntry.Offset + RelEntry.FixupSection->getSectionOffset();
9986f08c84aSSam Clegg     uint32_t Index = getRelocationIndexValue(RelEntry);
9999e15f359SSam Clegg 
10000ff28fa6SDerek Schuff     W->OS << char(RelEntry.Type);
10010ff28fa6SDerek Schuff     encodeULEB128(Offset, W->OS);
10020ff28fa6SDerek Schuff     encodeULEB128(Index, W->OS);
10036f08c84aSSam Clegg     if (RelEntry.hasAddend())
10040ff28fa6SDerek Schuff       encodeSLEB128(RelEntry.Addend, W->OS);
10059e15f359SSam Clegg   }
10069e15f359SSam Clegg 
10079e15f359SSam Clegg   endSection(Section);
10089e15f359SSam Clegg }
10099e15f359SSam Clegg 
10106a31a0d6SSam Clegg void WasmObjectWriter::writeCustomRelocSections() {
10116a31a0d6SSam Clegg   for (const auto &Sec : CustomSections) {
10126a31a0d6SSam Clegg     auto &Relocations = CustomSectionsRelocations[Sec.Section];
10136a31a0d6SSam Clegg     writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations);
10146a31a0d6SSam Clegg   }
10156a31a0d6SSam Clegg }
10166a31a0d6SSam Clegg 
10179e15f359SSam Clegg void WasmObjectWriter::writeLinkingMetaDataSection(
101886b4a09aSSam Clegg     ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
1019ea7caceeSSam Clegg     ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
1020ea7caceeSSam Clegg     const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) {
10219e15f359SSam Clegg   SectionBookkeeping Section;
10222322a937SSam Clegg   startCustomSection(Section, "linking");
10230ff28fa6SDerek Schuff   encodeULEB128(wasm::WasmMetadataVersion, W->OS);
10249e15f359SSam Clegg 
10256bb5a41fSSam Clegg   SectionBookkeeping SubSection;
10266c899ba6SSam Clegg   if (SymbolInfos.size() != 0) {
10276c899ba6SSam Clegg     startSection(SubSection, wasm::WASM_SYMBOL_TABLE);
10280ff28fa6SDerek Schuff     encodeULEB128(SymbolInfos.size(), W->OS);
10296c899ba6SSam Clegg     for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) {
10300ff28fa6SDerek Schuff       encodeULEB128(Sym.Kind, W->OS);
10310ff28fa6SDerek Schuff       encodeULEB128(Sym.Flags, W->OS);
10326c899ba6SSam Clegg       switch (Sym.Kind) {
10336c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_FUNCTION:
10346c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_GLOBAL:
1035da419bdbSHeejin Ahn       case wasm::WASM_SYMBOL_TYPE_EVENT:
1036388fb67bSPaulo Matos       case wasm::WASM_SYMBOL_TYPE_TABLE:
10370ff28fa6SDerek Schuff         encodeULEB128(Sym.ElementIndex, W->OS);
103829874ceaSDan Gohman         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0 ||
103929874ceaSDan Gohman             (Sym.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0)
10406c899ba6SSam Clegg           writeString(Sym.Name);
10416c899ba6SSam Clegg         break;
10426c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_DATA:
10436c899ba6SSam Clegg         writeString(Sym.Name);
10446c899ba6SSam Clegg         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) {
10450ff28fa6SDerek Schuff           encodeULEB128(Sym.DataRef.Segment, W->OS);
10460ff28fa6SDerek Schuff           encodeULEB128(Sym.DataRef.Offset, W->OS);
10470ff28fa6SDerek Schuff           encodeULEB128(Sym.DataRef.Size, W->OS);
10486c899ba6SSam Clegg         }
10496c899ba6SSam Clegg         break;
10506a31a0d6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_SECTION: {
10516a31a0d6SSam Clegg         const uint32_t SectionIndex =
10526a31a0d6SSam Clegg             CustomSections[Sym.ElementIndex].OutputIndex;
10530ff28fa6SDerek Schuff         encodeULEB128(SectionIndex, W->OS);
10546a31a0d6SSam Clegg         break;
10556a31a0d6SSam Clegg       }
10566c899ba6SSam Clegg       default:
10576c899ba6SSam Clegg         llvm_unreachable("unexpected kind");
10586c899ba6SSam Clegg       }
1059b7787fd0SSam Clegg     }
1060b7787fd0SSam Clegg     endSection(SubSection);
1061b7787fd0SSam Clegg   }
10629e15f359SSam Clegg 
10636c899ba6SSam Clegg   if (DataSegments.size()) {
106463ebb813SSam Clegg     startSection(SubSection, wasm::WASM_SEGMENT_INFO);
10650ff28fa6SDerek Schuff     encodeULEB128(DataSegments.size(), W->OS);
10666c899ba6SSam Clegg     for (const WasmDataSegment &Segment : DataSegments) {
1067d95ed959SSam Clegg       writeString(Segment.Name);
10680ff28fa6SDerek Schuff       encodeULEB128(Segment.Alignment, W->OS);
10690ff28fa6SDerek Schuff       encodeULEB128(Segment.LinkerFlags, W->OS);
107063ebb813SSam Clegg     }
1071d95ed959SSam Clegg     endSection(SubSection);
1072d95ed959SSam Clegg   }
1073d95ed959SSam Clegg 
1074bafe6902SSam Clegg   if (!InitFuncs.empty()) {
1075bafe6902SSam Clegg     startSection(SubSection, wasm::WASM_INIT_FUNCS);
10760ff28fa6SDerek Schuff     encodeULEB128(InitFuncs.size(), W->OS);
1077bafe6902SSam Clegg     for (auto &StartFunc : InitFuncs) {
10780ff28fa6SDerek Schuff       encodeULEB128(StartFunc.first, W->OS);  // priority
10790ff28fa6SDerek Schuff       encodeULEB128(StartFunc.second, W->OS); // function index
1080bafe6902SSam Clegg     }
1081bafe6902SSam Clegg     endSection(SubSection);
1082bafe6902SSam Clegg   }
1083bafe6902SSam Clegg 
1084ea7caceeSSam Clegg   if (Comdats.size()) {
1085ea7caceeSSam Clegg     startSection(SubSection, wasm::WASM_COMDAT_INFO);
10860ff28fa6SDerek Schuff     encodeULEB128(Comdats.size(), W->OS);
1087ea7caceeSSam Clegg     for (const auto &C : Comdats) {
1088ea7caceeSSam Clegg       writeString(C.first);
10890ff28fa6SDerek Schuff       encodeULEB128(0, W->OS); // flags for future use
10900ff28fa6SDerek Schuff       encodeULEB128(C.second.size(), W->OS);
1091ea7caceeSSam Clegg       for (const WasmComdatEntry &Entry : C.second) {
10920ff28fa6SDerek Schuff         encodeULEB128(Entry.Kind, W->OS);
10930ff28fa6SDerek Schuff         encodeULEB128(Entry.Index, W->OS);
1094ea7caceeSSam Clegg       }
1095ea7caceeSSam Clegg     }
1096ea7caceeSSam Clegg     endSection(SubSection);
1097ea7caceeSSam Clegg   }
1098ea7caceeSSam Clegg 
10999e15f359SSam Clegg   endSection(Section);
11009e15f359SSam Clegg }
11019e15f359SSam Clegg 
1102cbda16ebSThomas Lively void WasmObjectWriter::writeCustomSection(WasmCustomSection &CustomSection,
1103cbda16ebSThomas Lively                                           const MCAssembler &Asm,
11046a31a0d6SSam Clegg                                           const MCAsmLayout &Layout) {
1105cfd44a2eSSam Clegg   SectionBookkeeping Section;
11066a31a0d6SSam Clegg   auto *Sec = CustomSection.Section;
11072322a937SSam Clegg   startCustomSection(Section, CustomSection.Name);
11086a31a0d6SSam Clegg 
11090ff28fa6SDerek Schuff   Sec->setSectionOffset(W->OS.tell() - Section.ContentsOffset);
11100ff28fa6SDerek Schuff   Asm.writeSectionData(W->OS, Sec, Layout);
11116a31a0d6SSam Clegg 
11126a31a0d6SSam Clegg   CustomSection.OutputContentsOffset = Section.ContentsOffset;
11136a31a0d6SSam Clegg   CustomSection.OutputIndex = Section.Index;
11146a31a0d6SSam Clegg 
1115cfd44a2eSSam Clegg   endSection(Section);
11166a31a0d6SSam Clegg 
11176a31a0d6SSam Clegg   // Apply fixups.
11184d57fbd0SSam Clegg   auto &Relocations = CustomSectionsRelocations[CustomSection.Section];
11197ee758d6SSam Clegg   applyRelocations(Relocations, CustomSection.OutputContentsOffset, Layout);
11206a31a0d6SSam Clegg }
11216a31a0d6SSam Clegg 
11225e3d33a7SSam Clegg uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm &Symbol) {
11235e3d33a7SSam Clegg   assert(Symbol.isFunction());
11245e3d33a7SSam Clegg   assert(TypeIndices.count(&Symbol));
11255e3d33a7SSam Clegg   return TypeIndices[&Symbol];
11265e3d33a7SSam Clegg }
11275e3d33a7SSam Clegg 
1128da419bdbSHeejin Ahn uint32_t WasmObjectWriter::getEventType(const MCSymbolWasm &Symbol) {
1129da419bdbSHeejin Ahn   assert(Symbol.isEvent());
1130da419bdbSHeejin Ahn   assert(TypeIndices.count(&Symbol));
1131da419bdbSHeejin Ahn   return TypeIndices[&Symbol];
1132da419bdbSHeejin Ahn }
1133da419bdbSHeejin Ahn 
113438b12f5eSHeejin Ahn void WasmObjectWriter::registerFunctionType(const MCSymbolWasm &Symbol) {
11355e3d33a7SSam Clegg   assert(Symbol.isFunction());
11365e3d33a7SSam Clegg 
11374c41fb5aSHeejin Ahn   wasm::WasmSignature S;
11387ee758d6SSam Clegg 
11397ee758d6SSam Clegg   if (auto *Sig = Symbol.getSignature()) {
1140da419bdbSHeejin Ahn     S.Returns = Sig->Returns;
1141da419bdbSHeejin Ahn     S.Params = Sig->Params;
114277a7a380SDerek Schuff   }
11435e3d33a7SSam Clegg 
1144da419bdbSHeejin Ahn   auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
11455e3d33a7SSam Clegg   if (Pair.second)
1146da419bdbSHeejin Ahn     Signatures.push_back(S);
11475e3d33a7SSam Clegg   TypeIndices[&Symbol] = Pair.first->second;
11485e3d33a7SSam Clegg 
1149d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "registerFunctionType: " << Symbol
1150d34e60caSNicola Zaghen                     << " new:" << Pair.second << "\n");
1151d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
11525e3d33a7SSam Clegg }
11535e3d33a7SSam Clegg 
115438b12f5eSHeejin Ahn void WasmObjectWriter::registerEventType(const MCSymbolWasm &Symbol) {
1155da419bdbSHeejin Ahn   assert(Symbol.isEvent());
1156da419bdbSHeejin Ahn 
1157da419bdbSHeejin Ahn   // TODO Currently we don't generate imported exceptions, but if we do, we
1158da419bdbSHeejin Ahn   // should have a way of infering types of imported exceptions.
11594c41fb5aSHeejin Ahn   wasm::WasmSignature S;
1160da419bdbSHeejin Ahn   if (auto *Sig = Symbol.getSignature()) {
1161da419bdbSHeejin Ahn     S.Returns = Sig->Returns;
1162da419bdbSHeejin Ahn     S.Params = Sig->Params;
1163da419bdbSHeejin Ahn   }
1164da419bdbSHeejin Ahn 
1165da419bdbSHeejin Ahn   auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
1166da419bdbSHeejin Ahn   if (Pair.second)
1167da419bdbSHeejin Ahn     Signatures.push_back(S);
1168da419bdbSHeejin Ahn   TypeIndices[&Symbol] = Pair.first->second;
1169da419bdbSHeejin Ahn 
1170da419bdbSHeejin Ahn   LLVM_DEBUG(dbgs() << "registerEventType: " << Symbol << " new:" << Pair.second
1171da419bdbSHeejin Ahn                     << "\n");
1172da419bdbSHeejin Ahn   LLVM_DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
1173da419bdbSHeejin Ahn }
1174da419bdbSHeejin Ahn 
11754d57fbd0SSam Clegg static bool isInSymtab(const MCSymbolWasm &Sym) {
11763ea1c62cSSam Clegg   if (Sym.isUsedInReloc() || Sym.isUsedInInitArray())
11774d57fbd0SSam Clegg     return true;
11784d57fbd0SSam Clegg 
11794d57fbd0SSam Clegg   if (Sym.isComdat() && !Sym.isDefined())
11804d57fbd0SSam Clegg     return false;
11814d57fbd0SSam Clegg 
11823ea1c62cSSam Clegg   if (Sym.isTemporary())
11834d57fbd0SSam Clegg     return false;
11844d57fbd0SSam Clegg 
11854d57fbd0SSam Clegg   if (Sym.isSection())
11864d57fbd0SSam Clegg     return false;
11874d57fbd0SSam Clegg 
11884d57fbd0SSam Clegg   return true;
11894d57fbd0SSam Clegg }
11900ff28fa6SDerek Schuff void WasmObjectWriter::prepareImports(
11910ff28fa6SDerek Schuff     SmallVectorImpl<wasm::WasmImport> &Imports, MCAssembler &Asm,
119218eafb6cSDan Gohman     const MCAsmLayout &Layout) {
1193f950b24aSSam Clegg   // For now, always emit the memory import, since loads and stores are not
1194f950b24aSSam Clegg   // valid without it. In the future, we could perhaps be more clever and omit
1195f950b24aSSam Clegg   // it if there are no loads or stores.
11968defa952SSam Clegg   wasm::WasmImport MemImport;
11971ed3a046SSam Clegg   MemImport.Module = "env";
11981ed3a046SSam Clegg   MemImport.Field = "__linear_memory";
1199f950b24aSSam Clegg   MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
1200fd0964aeSWouter van Oortmerssen   MemImport.Memory.Flags = is64Bit() ? wasm::WASM_LIMITS_FLAG_IS_64
1201fd0964aeSWouter van Oortmerssen                                      : wasm::WASM_LIMITS_FLAG_NONE;
1202f950b24aSSam Clegg   Imports.push_back(MemImport);
1203f950b24aSSam Clegg 
1204f950b24aSSam Clegg   // For now, always emit the table section, since indirect calls are not
1205f950b24aSSam Clegg   // valid without it. In the future, we could perhaps be more clever and omit
1206f950b24aSSam Clegg   // it if there are no indirect calls.
12078defa952SSam Clegg   wasm::WasmImport TableImport;
12081ed3a046SSam Clegg   TableImport.Module = "env";
12091ed3a046SSam Clegg   TableImport.Field = "__indirect_function_table";
1210f950b24aSSam Clegg   TableImport.Kind = wasm::WASM_EXTERNAL_TABLE;
12116a87ddacSThomas Lively   TableImport.Table.ElemType = wasm::WASM_TYPE_FUNCREF;
1212f950b24aSSam Clegg   Imports.push_back(TableImport);
1213f950b24aSSam Clegg 
1214da419bdbSHeejin Ahn   // Populate SignatureIndices, and Imports and WasmIndices for undefined
1215586320c0SNicholas Wilson   // symbols.  This must be done before populating WasmIndices for defined
1216586320c0SNicholas Wilson   // symbols.
121732ce5ca0SDan Gohman   for (const MCSymbol &S : Asm.symbols()) {
121832ce5ca0SDan Gohman     const auto &WS = static_cast<const MCSymbolWasm &>(S);
121932ce5ca0SDan Gohman 
122032ce5ca0SDan Gohman     // Register types for all functions, including those with private linkage
12219f3fe42eSSam Clegg     // (because wasm always needs a type signature).
12227ee758d6SSam Clegg     if (WS.isFunction()) {
12239c7b5808SDominic Chen       const auto *BS = Layout.getBaseSymbol(S);
12249c7b5808SDominic Chen       if (!BS)
12259c7b5808SDominic Chen         report_fatal_error(Twine(S.getName()) +
12269c7b5808SDominic Chen                            ": absolute addressing not supported!");
12279c7b5808SDominic Chen       registerFunctionType(*cast<MCSymbolWasm>(BS));
12287ee758d6SSam Clegg     }
122932ce5ca0SDan Gohman 
1230da419bdbSHeejin Ahn     if (WS.isEvent())
1231da419bdbSHeejin Ahn       registerEventType(WS);
1232da419bdbSHeejin Ahn 
123332ce5ca0SDan Gohman     if (WS.isTemporary())
123432ce5ca0SDan Gohman       continue;
123532ce5ca0SDan Gohman 
123632ce5ca0SDan Gohman     // If the symbol is not defined in this translation unit, import it.
12376c899ba6SSam Clegg     if (!WS.isDefined() && !WS.isComdat()) {
12386c899ba6SSam Clegg       if (WS.isFunction()) {
12398defa952SSam Clegg         wasm::WasmImport Import;
1240f726e445SDan Gohman         Import.Module = WS.getImportModule();
1241f726e445SDan Gohman         Import.Field = WS.getImportName();
124232ce5ca0SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
12438defa952SSam Clegg         Import.SigIndex = getFunctionType(WS);
12446c899ba6SSam Clegg         Imports.push_back(Import);
1245492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
12466c899ba6SSam Clegg         WasmIndices[&WS] = NumFunctionImports++;
12476c899ba6SSam Clegg       } else if (WS.isGlobal()) {
124815f349f7SNicholas Wilson         if (WS.isWeak())
124915f349f7SNicholas Wilson           report_fatal_error("undefined global symbol cannot be weak");
125015f349f7SNicholas Wilson 
12516c899ba6SSam Clegg         wasm::WasmImport Import;
1252f726e445SDan Gohman         Import.Field = WS.getImportName();
125332ce5ca0SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1254492f7529SSam Clegg         Import.Module = WS.getImportModule();
12556c899ba6SSam Clegg         Import.Global = WS.getGlobalType();
12566c899ba6SSam Clegg         Imports.push_back(Import);
1257492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
12586c899ba6SSam Clegg         WasmIndices[&WS] = NumGlobalImports++;
1259da419bdbSHeejin Ahn       } else if (WS.isEvent()) {
1260da419bdbSHeejin Ahn         if (WS.isWeak())
1261da419bdbSHeejin Ahn           report_fatal_error("undefined event symbol cannot be weak");
1262da419bdbSHeejin Ahn 
1263da419bdbSHeejin Ahn         wasm::WasmImport Import;
1264f726e445SDan Gohman         Import.Module = WS.getImportModule();
1265f726e445SDan Gohman         Import.Field = WS.getImportName();
1266da419bdbSHeejin Ahn         Import.Kind = wasm::WASM_EXTERNAL_EVENT;
1267da419bdbSHeejin Ahn         Import.Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
1268da419bdbSHeejin Ahn         Import.Event.SigIndex = getEventType(WS);
1269da419bdbSHeejin Ahn         Imports.push_back(Import);
1270492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
1271da419bdbSHeejin Ahn         WasmIndices[&WS] = NumEventImports++;
127232ce5ca0SDan Gohman       }
127332ce5ca0SDan Gohman     }
127432ce5ca0SDan Gohman   }
127532ce5ca0SDan Gohman 
1276492f7529SSam Clegg   // Add imports for GOT globals
1277492f7529SSam Clegg   for (const MCSymbol &S : Asm.symbols()) {
1278492f7529SSam Clegg     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1279492f7529SSam Clegg     if (WS.isUsedInGOT()) {
1280492f7529SSam Clegg       wasm::WasmImport Import;
1281492f7529SSam Clegg       if (WS.isFunction())
1282492f7529SSam Clegg         Import.Module = "GOT.func";
1283492f7529SSam Clegg       else
1284492f7529SSam Clegg         Import.Module = "GOT.mem";
1285492f7529SSam Clegg       Import.Field = WS.getName();
1286492f7529SSam Clegg       Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1287492f7529SSam Clegg       Import.Global = {wasm::WASM_TYPE_I32, true};
1288492f7529SSam Clegg       Imports.push_back(Import);
1289492f7529SSam Clegg       assert(GOTIndices.count(&WS) == 0);
1290492f7529SSam Clegg       GOTIndices[&WS] = NumGlobalImports++;
1291492f7529SSam Clegg     }
1292492f7529SSam Clegg   }
12930ff28fa6SDerek Schuff }
1294492f7529SSam Clegg 
12950ff28fa6SDerek Schuff uint64_t WasmObjectWriter::writeObject(MCAssembler &Asm,
12960ff28fa6SDerek Schuff                                        const MCAsmLayout &Layout) {
12970ff28fa6SDerek Schuff   support::endian::Writer MainWriter(*OS, support::little);
12980ff28fa6SDerek Schuff   W = &MainWriter;
12990ff28fa6SDerek Schuff   if (IsSplitDwarf) {
13000ff28fa6SDerek Schuff     uint64_t TotalSize = writeOneObject(Asm, Layout, DwoMode::NonDwoOnly);
13010ff28fa6SDerek Schuff     assert(DwoOS);
13020ff28fa6SDerek Schuff     support::endian::Writer DwoWriter(*DwoOS, support::little);
13030ff28fa6SDerek Schuff     W = &DwoWriter;
13040ff28fa6SDerek Schuff     return TotalSize + writeOneObject(Asm, Layout, DwoMode::DwoOnly);
13050ff28fa6SDerek Schuff   } else {
13060ff28fa6SDerek Schuff     return writeOneObject(Asm, Layout, DwoMode::AllSections);
13070ff28fa6SDerek Schuff   }
13080ff28fa6SDerek Schuff }
13090ff28fa6SDerek Schuff 
13100ff28fa6SDerek Schuff uint64_t WasmObjectWriter::writeOneObject(MCAssembler &Asm,
13110ff28fa6SDerek Schuff                                           const MCAsmLayout &Layout,
13120ff28fa6SDerek Schuff                                           DwoMode Mode) {
13130ff28fa6SDerek Schuff   uint64_t StartOffset = W->OS.tell();
13140ff28fa6SDerek Schuff   SectionCount = 0;
13150ff28fa6SDerek Schuff   CustomSections.clear();
13160ff28fa6SDerek Schuff 
13170ff28fa6SDerek Schuff   LLVM_DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
13180ff28fa6SDerek Schuff 
13190ff28fa6SDerek Schuff   // Collect information from the available symbols.
13200ff28fa6SDerek Schuff   SmallVector<WasmFunction, 4> Functions;
13210ff28fa6SDerek Schuff   SmallVector<uint32_t, 4> TableElems;
13220ff28fa6SDerek Schuff   SmallVector<wasm::WasmImport, 4> Imports;
13230ff28fa6SDerek Schuff   SmallVector<wasm::WasmExport, 4> Exports;
13240ff28fa6SDerek Schuff   SmallVector<wasm::WasmEventType, 1> Events;
13250ff28fa6SDerek Schuff   SmallVector<wasm::WasmGlobal, 1> Globals;
1326388fb67bSPaulo Matos   SmallVector<wasm::WasmTable, 1> Tables;
13270ff28fa6SDerek Schuff   SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos;
13280ff28fa6SDerek Schuff   SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
13290ff28fa6SDerek Schuff   std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
13300ff28fa6SDerek Schuff   uint64_t DataSize = 0;
13310ff28fa6SDerek Schuff   if (Mode != DwoMode::DwoOnly) {
13320ff28fa6SDerek Schuff     prepareImports(Imports, Asm, Layout);
13330ff28fa6SDerek Schuff   }
13344d57fbd0SSam Clegg   // Populate DataSegments and CustomSections, which must be done before
13354d57fbd0SSam Clegg   // populating DataLocations.
1336759631c7SSam Clegg   for (MCSection &Sec : Asm) {
1337759631c7SSam Clegg     auto &Section = static_cast<MCSectionWasm &>(Sec);
13387d1ff446SFangrui Song     StringRef SectionName = Section.getName();
1339759631c7SSam Clegg 
13400ff28fa6SDerek Schuff     if (Mode == DwoMode::NonDwoOnly && isDwoSection(Sec))
13410ff28fa6SDerek Schuff       continue;
13420ff28fa6SDerek Schuff     if (Mode == DwoMode::DwoOnly && !isDwoSection(Sec))
13430ff28fa6SDerek Schuff       continue;
13440ff28fa6SDerek Schuff 
1345bafe6902SSam Clegg     // .init_array sections are handled specially elsewhere.
13464d57fbd0SSam Clegg     if (SectionName.startswith(".init_array"))
1347bafe6902SSam Clegg       continue;
1348bafe6902SSam Clegg 
13494d57fbd0SSam Clegg     // Code is handled separately
13504d57fbd0SSam Clegg     if (Section.getKind().isText())
13514d57fbd0SSam Clegg       continue;
13524d57fbd0SSam Clegg 
13534d57fbd0SSam Clegg     if (Section.isWasmData()) {
1354329e76d5SSam Clegg       uint32_t SegmentIndex = DataSegments.size();
1355759631c7SSam Clegg       DataSize = alignTo(DataSize, Section.getAlignment());
1356759631c7SSam Clegg       DataSegments.emplace_back();
1357759631c7SSam Clegg       WasmDataSegment &Segment = DataSegments.back();
13584d57fbd0SSam Clegg       Segment.Name = SectionName;
13599b49f36aSSimon Pilgrim       Segment.InitFlags =
13609b49f36aSSimon Pilgrim           Section.getPassive() ? (uint32_t)wasm::WASM_SEGMENT_IS_PASSIVE : 0;
1361759631c7SSam Clegg       Segment.Offset = DataSize;
1362759631c7SSam Clegg       Segment.Section = &Section;
136363ebb813SSam Clegg       addData(Segment.Data, Section);
136456c587adSSam Clegg       Segment.Alignment = Log2_32(Section.getAlignment());
13652e150409SThomas Lively       Segment.LinkerFlags = 0;
1366759631c7SSam Clegg       DataSize += Segment.Data.size();
13676c899ba6SSam Clegg       Section.setSegmentIndex(SegmentIndex);
1368ea7caceeSSam Clegg 
1369ea7caceeSSam Clegg       if (const MCSymbolWasm *C = Section.getGroup()) {
1370ea7caceeSSam Clegg         Comdats[C->getName()].emplace_back(
1371329e76d5SSam Clegg             WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
1372ea7caceeSSam Clegg       }
13734d57fbd0SSam Clegg     } else {
13744d57fbd0SSam Clegg       // Create custom sections
13754d57fbd0SSam Clegg       assert(Sec.getKind().isMetadata());
13764d57fbd0SSam Clegg 
13774d57fbd0SSam Clegg       StringRef Name = SectionName;
13784d57fbd0SSam Clegg 
13794d57fbd0SSam Clegg       // For user-defined custom sections, strip the prefix
13804d57fbd0SSam Clegg       if (Name.startswith(".custom_section."))
13814d57fbd0SSam Clegg         Name = Name.substr(strlen(".custom_section."));
13824d57fbd0SSam Clegg 
13834d57fbd0SSam Clegg       MCSymbol *Begin = Sec.getBeginSymbol();
1384fb807d4dSSam Clegg       if (Begin) {
13854d57fbd0SSam Clegg         WasmIndices[cast<MCSymbolWasm>(Begin)] = CustomSections.size();
1386fb807d4dSSam Clegg       }
1387cbda16ebSThomas Lively 
1388f6f4f843SThomas Lively       // Separate out the producers and target features sections
1389cbda16ebSThomas Lively       if (Name == "producers") {
13900eaee545SJonas Devlieghere         ProducersSection = std::make_unique<WasmCustomSection>(Name, &Section);
1391cbda16ebSThomas Lively         continue;
1392cbda16ebSThomas Lively       }
1393f6f4f843SThomas Lively       if (Name == "target_features") {
1394f6f4f843SThomas Lively         TargetFeaturesSection =
13950eaee545SJonas Devlieghere             std::make_unique<WasmCustomSection>(Name, &Section);
1396f6f4f843SThomas Lively         continue;
1397f6f4f843SThomas Lively       }
1398cbda16ebSThomas Lively 
13994d57fbd0SSam Clegg       CustomSections.emplace_back(Name, &Section);
1400759631c7SSam Clegg     }
14016a31a0d6SSam Clegg   }
14026a31a0d6SSam Clegg 
1403586320c0SNicholas Wilson   // Populate WasmIndices and DataLocations for defined symbols.
1404d934cb88SDan Gohman   for (const MCSymbol &S : Asm.symbols()) {
1405d934cb88SDan Gohman     // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1406d934cb88SDan Gohman     // or used in relocations.
1407d934cb88SDan Gohman     if (S.isTemporary() && S.getName().empty())
1408d934cb88SDan Gohman       continue;
1409b7787fd0SSam Clegg 
1410d934cb88SDan Gohman     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1411d34e60caSNicola Zaghen     LLVM_DEBUG(
1412d34e60caSNicola Zaghen         dbgs() << "MCSymbol: " << toString(WS.getType()) << " '" << S << "'"
1413d34e60caSNicola Zaghen                << " isDefined=" << S.isDefined() << " isExternal="
1414d34e60caSNicola Zaghen                << S.isExternal() << " isTemporary=" << S.isTemporary()
1415d34e60caSNicola Zaghen                << " isWeak=" << WS.isWeak() << " isHidden=" << WS.isHidden()
1416b7787fd0SSam Clegg                << " isVariable=" << WS.isVariable() << "\n");
1417b7787fd0SSam Clegg 
14185e3d33a7SSam Clegg     if (WS.isVariable())
14195e3d33a7SSam Clegg       continue;
14206c899ba6SSam Clegg     if (WS.isComdat() && !WS.isDefined())
14216c899ba6SSam Clegg       continue;
1422b7787fd0SSam Clegg 
1423d934cb88SDan Gohman     if (WS.isFunction()) {
14246c899ba6SSam Clegg       unsigned Index;
1425cd65f698SSam Clegg       if (WS.isDefined()) {
1426b7787fd0SSam Clegg         if (WS.getOffset() != 0)
1427b7787fd0SSam Clegg           report_fatal_error(
1428b7787fd0SSam Clegg               "function sections must contain one function each");
1429b7787fd0SSam Clegg 
143018c56a07SHeejin Ahn         if (WS.getSize() == nullptr)
1431b7787fd0SSam Clegg           report_fatal_error(
1432b7787fd0SSam Clegg               "function symbols must have a size set with .size");
1433b7787fd0SSam Clegg 
14346c899ba6SSam Clegg         // A definition. Write out the function body.
14359f3fe42eSSam Clegg         Index = NumFunctionImports + Functions.size();
1436d934cb88SDan Gohman         WasmFunction Func;
1437da419bdbSHeejin Ahn         Func.SigIndex = getFunctionType(WS);
1438d934cb88SDan Gohman         Func.Sym = &WS;
14396c899ba6SSam Clegg         WasmIndices[&WS] = Index;
1440d934cb88SDan Gohman         Functions.push_back(Func);
14416c899ba6SSam Clegg 
14426c899ba6SSam Clegg         auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
14436c899ba6SSam Clegg         if (const MCSymbolWasm *C = Section.getGroup()) {
14446c899ba6SSam Clegg           Comdats[C->getName()].emplace_back(
14456c899ba6SSam Clegg               WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
14466c899ba6SSam Clegg         }
1447881d8778SSam Clegg 
1448881d8778SSam Clegg         if (WS.hasExportName()) {
1449881d8778SSam Clegg           wasm::WasmExport Export;
1450881d8778SSam Clegg           Export.Name = WS.getExportName();
1451881d8778SSam Clegg           Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1452881d8778SSam Clegg           Export.Index = Index;
1453881d8778SSam Clegg           Exports.push_back(Export);
1454881d8778SSam Clegg         }
1455d934cb88SDan Gohman       } else {
1456d934cb88SDan Gohman         // An import; the index was assigned above.
14576c899ba6SSam Clegg         Index = WasmIndices.find(&WS)->second;
1458d934cb88SDan Gohman       }
1459d934cb88SDan Gohman 
1460d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> function index: " << Index << "\n");
1461da419bdbSHeejin Ahn 
14626c899ba6SSam Clegg     } else if (WS.isData()) {
1463f3feb6adSWouter van Oortmerssen       if (!isInSymtab(WS))
1464c38e947eSSam Clegg         continue;
1465c38e947eSSam Clegg 
14666c899ba6SSam Clegg       if (!WS.isDefined()) {
1467d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "  -> segment index: -1"
1468d34e60caSNicola Zaghen                           << "\n");
1469fe6414b0SSam Clegg         continue;
14706c899ba6SSam Clegg       }
1471fe6414b0SSam Clegg 
1472d934cb88SDan Gohman       if (!WS.getSize())
1473c38e947eSSam Clegg         report_fatal_error("data symbols must have a size set with .size: " +
1474c38e947eSSam Clegg                            WS.getName());
1475d934cb88SDan Gohman 
1476d934cb88SDan Gohman       int64_t Size = 0;
1477d934cb88SDan Gohman       if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1478d934cb88SDan Gohman         report_fatal_error(".size expression must be evaluatable");
1479d934cb88SDan Gohman 
1480759631c7SSam Clegg       auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
1481079cba04SSam Clegg       if (!DataSection.isWasmData())
1482079cba04SSam Clegg         report_fatal_error("data symbols must live in a data section: " +
1483079cba04SSam Clegg                            WS.getName());
14847c395943SSam Clegg 
14856c899ba6SSam Clegg       // For each data symbol, export it in the symtab as a reference to the
14866c899ba6SSam Clegg       // corresponding Wasm data segment.
14876c899ba6SSam Clegg       wasm::WasmDataReference Ref = wasm::WasmDataReference{
14883b29376eSWouter van Oortmerssen           DataSection.getSegmentIndex(), Layout.getSymbolOffset(WS),
14893b29376eSWouter van Oortmerssen           static_cast<uint64_t>(Size)};
14906c899ba6SSam Clegg       DataLocations[&WS] = Ref;
1491d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> segment index: " << Ref.Segment << "\n");
1492da419bdbSHeejin Ahn 
1493a165f2d6SSam Clegg     } else if (WS.isGlobal()) {
14946c899ba6SSam Clegg       // A "true" Wasm global (currently just __stack_pointer)
14950a6c4d8dSSam Clegg       if (WS.isDefined()) {
14960a6c4d8dSSam Clegg         assert(WasmIndices.count(&WS) == 0);
14970a6c4d8dSSam Clegg         wasm::WasmGlobal Global;
14980a6c4d8dSSam Clegg         Global.Type = WS.getGlobalType();
14990a6c4d8dSSam Clegg         Global.Index = NumGlobalImports + Globals.size();
15000a6c4d8dSSam Clegg         switch (Global.Type.Type) {
15010a6c4d8dSSam Clegg         case wasm::WASM_TYPE_I32:
15020a6c4d8dSSam Clegg           Global.InitExpr.Opcode = wasm::WASM_OPCODE_I32_CONST;
15030a6c4d8dSSam Clegg           break;
15040a6c4d8dSSam Clegg         case wasm::WASM_TYPE_I64:
15050a6c4d8dSSam Clegg           Global.InitExpr.Opcode = wasm::WASM_OPCODE_I64_CONST;
15060a6c4d8dSSam Clegg           break;
15070a6c4d8dSSam Clegg         case wasm::WASM_TYPE_F32:
15080a6c4d8dSSam Clegg           Global.InitExpr.Opcode = wasm::WASM_OPCODE_F32_CONST;
15090a6c4d8dSSam Clegg           break;
15100a6c4d8dSSam Clegg         case wasm::WASM_TYPE_F64:
15110a6c4d8dSSam Clegg           Global.InitExpr.Opcode = wasm::WASM_OPCODE_F64_CONST;
15120a6c4d8dSSam Clegg           break;
151379aad89dSSam Clegg         case wasm::WASM_TYPE_EXTERNREF:
151479aad89dSSam Clegg           Global.InitExpr.Opcode = wasm::WASM_OPCODE_REF_NULL;
151579aad89dSSam Clegg           break;
15160a6c4d8dSSam Clegg         default:
15170a6c4d8dSSam Clegg           llvm_unreachable("unexpected type");
15180a6c4d8dSSam Clegg         }
15190a6c4d8dSSam Clegg         WasmIndices[&WS] = Global.Index;
15200a6c4d8dSSam Clegg         Globals.push_back(Global);
15210a6c4d8dSSam Clegg       } else {
1522545932beSEric Christopher         // An import; the index was assigned above
1523d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "  -> global index: "
1524d34e60caSNicola Zaghen                           << WasmIndices.find(&WS)->second << "\n");
15250a6c4d8dSSam Clegg       }
1526388fb67bSPaulo Matos     } else if (WS.isTable()) {
1527388fb67bSPaulo Matos       if (WS.isDefined()) {
1528388fb67bSPaulo Matos         assert(WasmIndices.count(&WS) == 0);
1529388fb67bSPaulo Matos         wasm::WasmTable Table;
1530388fb67bSPaulo Matos         Table.ElemType = static_cast<uint8_t>(WS.getTableType());
1531388fb67bSPaulo Matos         Table.Index = NumTableImports + Tables.size();
1532388fb67bSPaulo Matos         // FIXME: Work on custom limits is ongoing
1533388fb67bSPaulo Matos         Table.Limits = {wasm::WASM_LIMITS_FLAG_NONE, 0, 0};
1534388fb67bSPaulo Matos 
1535388fb67bSPaulo Matos         WasmIndices[&WS] = Table.Index;
1536388fb67bSPaulo Matos         Tables.push_back(Table);
1537388fb67bSPaulo Matos       }
1538388fb67bSPaulo Matos       LLVM_DEBUG(dbgs() << " -> table index: " << WasmIndices.find(&WS)->second
1539388fb67bSPaulo Matos                         << "\n");
1540da419bdbSHeejin Ahn     } else if (WS.isEvent()) {
1541da419bdbSHeejin Ahn       // C++ exception symbol (__cpp_exception)
1542da419bdbSHeejin Ahn       unsigned Index;
1543da419bdbSHeejin Ahn       if (WS.isDefined()) {
15440a6c4d8dSSam Clegg         assert(WasmIndices.count(&WS) == 0);
1545da419bdbSHeejin Ahn         Index = NumEventImports + Events.size();
1546da419bdbSHeejin Ahn         wasm::WasmEventType Event;
1547da419bdbSHeejin Ahn         Event.SigIndex = getEventType(WS);
1548da419bdbSHeejin Ahn         Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
1549da419bdbSHeejin Ahn         WasmIndices[&WS] = Index;
1550da419bdbSHeejin Ahn         Events.push_back(Event);
1551da419bdbSHeejin Ahn       } else {
1552da419bdbSHeejin Ahn         // An import; the index was assigned above.
1553492f7529SSam Clegg         assert(WasmIndices.count(&WS) > 0);
1554da419bdbSHeejin Ahn       }
1555da419bdbSHeejin Ahn       LLVM_DEBUG(dbgs() << "  -> event index: " << WasmIndices.find(&WS)->second
1556da419bdbSHeejin Ahn                         << "\n");
1557da419bdbSHeejin Ahn 
1558a165f2d6SSam Clegg     } else {
1559a165f2d6SSam Clegg       assert(WS.isSection());
1560d934cb88SDan Gohman     }
1561d934cb88SDan Gohman   }
1562d934cb88SDan Gohman 
1563586320c0SNicholas Wilson   // Populate WasmIndices and DataLocations for aliased symbols.  We need to
1564586320c0SNicholas Wilson   // process these in a separate pass because we need to have processed the
1565586320c0SNicholas Wilson   // target of the alias before the alias itself and the symbols are not
1566586320c0SNicholas Wilson   // necessarily ordered in this way.
1567b7787fd0SSam Clegg   for (const MCSymbol &S : Asm.symbols()) {
1568b7787fd0SSam Clegg     if (!S.isVariable())
1569b7787fd0SSam Clegg       continue;
157031a2c809SSam Clegg 
1571cd65f698SSam Clegg     assert(S.isDefined());
1572b7787fd0SSam Clegg 
15739c7b5808SDominic Chen     const auto *BS = Layout.getBaseSymbol(S);
15749c7b5808SDominic Chen     if (!BS)
15759c7b5808SDominic Chen       report_fatal_error(Twine(S.getName()) +
15769c7b5808SDominic Chen                          ": absolute addressing not supported!");
15779c7b5808SDominic Chen     const MCSymbolWasm *Base = cast<MCSymbolWasm>(BS);
15787ee758d6SSam Clegg 
15795e3d33a7SSam Clegg     // Find the target symbol of this weak alias and export that index
1580aff1c4dfSSam Clegg     const auto &WS = static_cast<const MCSymbolWasm &>(S);
15817ee758d6SSam Clegg     LLVM_DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *Base << "'\n");
1582b7787fd0SSam Clegg 
15837ee758d6SSam Clegg     if (Base->isFunction()) {
15847ee758d6SSam Clegg       assert(WasmIndices.count(Base) > 0);
15857ee758d6SSam Clegg       uint32_t WasmIndex = WasmIndices.find(Base)->second;
1586492f7529SSam Clegg       assert(WasmIndices.count(&WS) == 0);
15876c899ba6SSam Clegg       WasmIndices[&WS] = WasmIndex;
1588d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> index:" << WasmIndex << "\n");
15897ee758d6SSam Clegg     } else if (Base->isData()) {
15907ee758d6SSam Clegg       auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
15917ee758d6SSam Clegg       uint64_t Offset = Layout.getSymbolOffset(S);
15927ee758d6SSam Clegg       int64_t Size = 0;
15937ee758d6SSam Clegg       // For data symbol alias we use the size of the base symbol as the
15947ee758d6SSam Clegg       // size of the alias.  When an offset from the base is involved this
15957ee758d6SSam Clegg       // can result in a offset + size goes past the end of the data section
15967ee758d6SSam Clegg       // which out object format doesn't support.  So we must clamp it.
15977ee758d6SSam Clegg       if (!Base->getSize()->evaluateAsAbsolute(Size, Layout))
15987ee758d6SSam Clegg         report_fatal_error(".size expression must be evaluatable");
15997ee758d6SSam Clegg       const WasmDataSegment &Segment =
16007ee758d6SSam Clegg           DataSegments[DataSection.getSegmentIndex()];
16017ee758d6SSam Clegg       Size =
16027ee758d6SSam Clegg           std::min(static_cast<uint64_t>(Size), Segment.Data.size() - Offset);
16037ee758d6SSam Clegg       wasm::WasmDataReference Ref = wasm::WasmDataReference{
16047ee758d6SSam Clegg           DataSection.getSegmentIndex(),
16057ee758d6SSam Clegg           static_cast<uint32_t>(Layout.getSymbolOffset(S)),
16067ee758d6SSam Clegg           static_cast<uint32_t>(Size)};
16076c899ba6SSam Clegg       DataLocations[&WS] = Ref;
1608d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> index:" << Ref.Segment << "\n");
16096c899ba6SSam Clegg     } else {
1610da419bdbSHeejin Ahn       report_fatal_error("don't yet support global/event aliases");
16116c899ba6SSam Clegg     }
1612586320c0SNicholas Wilson   }
161331a2c809SSam Clegg 
1614586320c0SNicholas Wilson   // Finally, populate the symbol table itself, in its "natural" order.
1615586320c0SNicholas Wilson   for (const MCSymbol &S : Asm.symbols()) {
1616586320c0SNicholas Wilson     const auto &WS = static_cast<const MCSymbolWasm &>(S);
161725d8e68bSSam Clegg     if (!isInSymtab(WS)) {
161818c56a07SHeejin Ahn       WS.setIndex(InvalidIndex);
1619586320c0SNicholas Wilson       continue;
162025d8e68bSSam Clegg     }
1621d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "adding to symtab: " << WS << "\n");
1622586320c0SNicholas Wilson 
1623586320c0SNicholas Wilson     uint32_t Flags = 0;
1624586320c0SNicholas Wilson     if (WS.isWeak())
1625586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_BINDING_WEAK;
1626586320c0SNicholas Wilson     if (WS.isHidden())
1627586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN;
1628586320c0SNicholas Wilson     if (!WS.isExternal() && WS.isDefined())
1629586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;
1630586320c0SNicholas Wilson     if (WS.isUndefined())
1631586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_UNDEFINED;
1632da84b688SDan Gohman     if (WS.isNoStrip()) {
1633da84b688SDan Gohman       Flags |= wasm::WASM_SYMBOL_NO_STRIP;
1634da84b688SDan Gohman       if (isEmscripten()) {
1635d6ef8da3SSam Clegg         Flags |= wasm::WASM_SYMBOL_EXPORTED;
1636da84b688SDan Gohman       }
1637da84b688SDan Gohman     }
1638b4f4e370SSam Clegg     if (WS.hasImportName())
163929874ceaSDan Gohman       Flags |= wasm::WASM_SYMBOL_EXPLICIT_NAME;
1640881d8778SSam Clegg     if (WS.hasExportName())
1641881d8778SSam Clegg       Flags |= wasm::WASM_SYMBOL_EXPORTED;
1642586320c0SNicholas Wilson 
1643586320c0SNicholas Wilson     wasm::WasmSymbolInfo Info;
1644586320c0SNicholas Wilson     Info.Name = WS.getName();
1645586320c0SNicholas Wilson     Info.Kind = WS.getType();
1646586320c0SNicholas Wilson     Info.Flags = Flags;
16474d57fbd0SSam Clegg     if (!WS.isData()) {
16484d57fbd0SSam Clegg       assert(WasmIndices.count(&WS) > 0);
1649586320c0SNicholas Wilson       Info.ElementIndex = WasmIndices.find(&WS)->second;
16504d57fbd0SSam Clegg     } else if (WS.isDefined()) {
16514d57fbd0SSam Clegg       assert(DataLocations.count(&WS) > 0);
1652586320c0SNicholas Wilson       Info.DataRef = DataLocations.find(&WS)->second;
16534d57fbd0SSam Clegg     }
165425d8e68bSSam Clegg     WS.setIndex(SymbolInfos.size());
1655586320c0SNicholas Wilson     SymbolInfos.emplace_back(Info);
1656b7787fd0SSam Clegg   }
1657b7787fd0SSam Clegg 
16586006e091SSam Clegg   {
16596006e091SSam Clegg     auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
1660f9edbe95SSam Clegg       // Functions referenced by a relocation need to put in the table.  This is
1661f9edbe95SSam Clegg       // purely to make the object file's provisional values readable, and is
1662f9edbe95SSam Clegg       // ignored by the linker, which re-calculates the relocations itself.
1663d1152a26SSam Clegg       if (Rel.Type != wasm::R_WASM_TABLE_INDEX_I32 &&
1664cc1b9b68SWouter van Oortmerssen           Rel.Type != wasm::R_WASM_TABLE_INDEX_I64 &&
166581443ac1SSam Clegg           Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB &&
1666cc1b9b68SWouter van Oortmerssen           Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB64 &&
166781443ac1SSam Clegg           Rel.Type != wasm::R_WASM_TABLE_INDEX_REL_SLEB)
1668f9edbe95SSam Clegg         return;
1669f9edbe95SSam Clegg       assert(Rel.Symbol->isFunction());
16707ee758d6SSam Clegg       const MCSymbolWasm *Base =
16717ee758d6SSam Clegg           cast<MCSymbolWasm>(Layout.getBaseSymbol(*Rel.Symbol));
16727ee758d6SSam Clegg       uint32_t FunctionIndex = WasmIndices.find(Base)->second;
167318c56a07SHeejin Ahn       uint32_t TableIndex = TableElems.size() + InitialTableOffset;
16747ee758d6SSam Clegg       if (TableIndices.try_emplace(Base, TableIndex).second) {
16757ee758d6SSam Clegg         LLVM_DEBUG(dbgs() << "  -> adding " << Base->getName()
1676f9edbe95SSam Clegg                           << " to table: " << TableIndex << "\n");
16776c899ba6SSam Clegg         TableElems.push_back(FunctionIndex);
16787ee758d6SSam Clegg         registerFunctionType(*Base);
16796006e091SSam Clegg       }
16806006e091SSam Clegg     };
1681970d02c4SDan Gohman 
16826006e091SSam Clegg     for (const WasmRelocationEntry &RelEntry : CodeRelocations)
16836006e091SSam Clegg       HandleReloc(RelEntry);
16846006e091SSam Clegg     for (const WasmRelocationEntry &RelEntry : DataRelocations)
16856006e091SSam Clegg       HandleReloc(RelEntry);
1686d934cb88SDan Gohman   }
1687d934cb88SDan Gohman 
1688bafe6902SSam Clegg   // Translate .init_array section contents into start functions.
1689bafe6902SSam Clegg   for (const MCSection &S : Asm) {
1690bafe6902SSam Clegg     const auto &WS = static_cast<const MCSectionWasm &>(S);
16917d1ff446SFangrui Song     if (WS.getName().startswith(".fini_array"))
1692bafe6902SSam Clegg       report_fatal_error(".fini_array sections are unsupported");
16937d1ff446SFangrui Song     if (!WS.getName().startswith(".init_array"))
1694bafe6902SSam Clegg       continue;
1695bafe6902SSam Clegg     if (WS.getFragmentList().empty())
1696bafe6902SSam Clegg       continue;
1697b210c64bSSam Clegg 
1698b210c64bSSam Clegg     // init_array is expected to contain a single non-empty data fragment
1699b210c64bSSam Clegg     if (WS.getFragmentList().size() != 3)
1700bafe6902SSam Clegg       report_fatal_error("only one .init_array section fragment supported");
1701b210c64bSSam Clegg 
1702b210c64bSSam Clegg     auto IT = WS.begin();
1703b210c64bSSam Clegg     const MCFragment &EmptyFrag = *IT;
1704b210c64bSSam Clegg     if (EmptyFrag.getKind() != MCFragment::FT_Data)
1705b210c64bSSam Clegg       report_fatal_error(".init_array section should be aligned");
1706b210c64bSSam Clegg 
1707b210c64bSSam Clegg     IT = std::next(IT);
1708b210c64bSSam Clegg     const MCFragment &AlignFrag = *IT;
1709bafe6902SSam Clegg     if (AlignFrag.getKind() != MCFragment::FT_Align)
1710bafe6902SSam Clegg       report_fatal_error(".init_array section should be aligned");
1711bafe6902SSam Clegg     if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
1712bafe6902SSam Clegg       report_fatal_error(".init_array section should be aligned for pointers");
1713b210c64bSSam Clegg 
1714b210c64bSSam Clegg     const MCFragment &Frag = *std::next(IT);
1715bafe6902SSam Clegg     if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1716bafe6902SSam Clegg       report_fatal_error("only data supported in .init_array section");
1717b210c64bSSam Clegg 
1718bafe6902SSam Clegg     uint16_t Priority = UINT16_MAX;
17194d57fbd0SSam Clegg     unsigned PrefixLength = strlen(".init_array");
17207d1ff446SFangrui Song     if (WS.getName().size() > PrefixLength) {
17217d1ff446SFangrui Song       if (WS.getName()[PrefixLength] != '.')
1722f208f631SHeejin Ahn         report_fatal_error(
1723f208f631SHeejin Ahn             ".init_array section priority should start with '.'");
17247d1ff446SFangrui Song       if (WS.getName().substr(PrefixLength + 1).getAsInteger(10, Priority))
1725bafe6902SSam Clegg         report_fatal_error("invalid .init_array section priority");
1726bafe6902SSam Clegg     }
1727bafe6902SSam Clegg     const auto &DataFrag = cast<MCDataFragment>(Frag);
1728bafe6902SSam Clegg     const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1729f208f631SHeejin Ahn     for (const uint8_t *
173018c56a07SHeejin Ahn              P = (const uint8_t *)Contents.data(),
173118c56a07SHeejin Ahn             *End = (const uint8_t *)Contents.data() + Contents.size();
173218c56a07SHeejin Ahn          P != End; ++P) {
173318c56a07SHeejin Ahn       if (*P != 0)
1734bafe6902SSam Clegg         report_fatal_error("non-symbolic data in .init_array section");
1735bafe6902SSam Clegg     }
1736bafe6902SSam Clegg     for (const MCFixup &Fixup : DataFrag.getFixups()) {
1737f208f631SHeejin Ahn       assert(Fixup.getKind() ==
1738f208f631SHeejin Ahn              MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
1739bafe6902SSam Clegg       const MCExpr *Expr = Fixup.getValue();
17408fffa1dfSSam Clegg       auto *SymRef = dyn_cast<MCSymbolRefExpr>(Expr);
17418fffa1dfSSam Clegg       if (!SymRef)
1742bafe6902SSam Clegg         report_fatal_error("fixups in .init_array should be symbol references");
17438fffa1dfSSam Clegg       const auto &TargetSym = cast<const MCSymbolWasm>(SymRef->getSymbol());
17448fffa1dfSSam Clegg       if (TargetSym.getIndex() == InvalidIndex)
17453ea1c62cSSam Clegg         report_fatal_error("symbols in .init_array should exist in symtab");
17468fffa1dfSSam Clegg       if (!TargetSym.isFunction())
17478fffa1dfSSam Clegg         report_fatal_error("symbols in .init_array should be for functions");
174825d8e68bSSam Clegg       InitFuncs.push_back(
17498fffa1dfSSam Clegg           std::make_pair(Priority, TargetSym.getIndex()));
1750bafe6902SSam Clegg     }
1751bafe6902SSam Clegg   }
1752bafe6902SSam Clegg 
175318eafb6cSDan Gohman   // Write out the Wasm header.
175418eafb6cSDan Gohman   writeHeader(Asm);
175518eafb6cSDan Gohman 
17560ff28fa6SDerek Schuff   uint32_t CodeSectionIndex, DataSectionIndex;
17570ff28fa6SDerek Schuff   if (Mode != DwoMode::DwoOnly) {
1758da419bdbSHeejin Ahn     writeTypeSection(Signatures);
1759f950b24aSSam Clegg     writeImportSection(Imports, DataSize, TableElems.size());
17609e15f359SSam Clegg     writeFunctionSection(Functions);
1761f950b24aSSam Clegg     // Skip the "memory" section; we import the memory instead.
1762da419bdbSHeejin Ahn     writeEventSection(Events);
17630a6c4d8dSSam Clegg     writeGlobalSection(Globals);
1764388fb67bSPaulo Matos     writeTableSection(Tables);
17659e15f359SSam Clegg     writeExportSection(Exports);
17669e15f359SSam Clegg     writeElemSection(TableElems);
1767fef8de66SThomas Lively     writeDataCountSection();
17680ff28fa6SDerek Schuff 
17690ff28fa6SDerek Schuff     CodeSectionIndex = writeCodeSection(Asm, Layout, Functions);
17700ff28fa6SDerek Schuff     DataSectionIndex = writeDataSection(Layout);
17710ff28fa6SDerek Schuff   }
17720ff28fa6SDerek Schuff 
17730ff28fa6SDerek Schuff   for (auto &CustomSection : CustomSections) {
1774cbda16ebSThomas Lively     writeCustomSection(CustomSection, Asm, Layout);
17750ff28fa6SDerek Schuff   }
17760ff28fa6SDerek Schuff 
17770ff28fa6SDerek Schuff   if (Mode != DwoMode::DwoOnly) {
1778c22bfb6bSNicholas Wilson     writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats);
17790ff28fa6SDerek Schuff 
17806f08c84aSSam Clegg     writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations);
17816f08c84aSSam Clegg     writeRelocSection(DataSectionIndex, "DATA", DataRelocations);
17820ff28fa6SDerek Schuff   }
17836a31a0d6SSam Clegg   writeCustomRelocSections();
1784cbda16ebSThomas Lively   if (ProducersSection)
1785cbda16ebSThomas Lively     writeCustomSection(*ProducersSection, Asm, Layout);
1786f6f4f843SThomas Lively   if (TargetFeaturesSection)
1787f6f4f843SThomas Lively     writeCustomSection(*TargetFeaturesSection, Asm, Layout);
1788970d02c4SDan Gohman 
1789d934cb88SDan Gohman   // TODO: Translate the .comment section to the output.
17900ff28fa6SDerek Schuff   return W->OS.tell() - StartOffset;
179118eafb6cSDan Gohman }
179218eafb6cSDan Gohman 
179360fbc7ccSLang Hames std::unique_ptr<MCObjectWriter>
17941301a878SLang Hames llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
179518eafb6cSDan Gohman                              raw_pwrite_stream &OS) {
17960eaee545SJonas Devlieghere   return std::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
179718eafb6cSDan Gohman }
17980ff28fa6SDerek Schuff 
17990ff28fa6SDerek Schuff std::unique_ptr<MCObjectWriter>
18000ff28fa6SDerek Schuff llvm::createWasmDwoObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
18010ff28fa6SDerek Schuff                                 raw_pwrite_stream &OS,
18020ff28fa6SDerek Schuff                                 raw_pwrite_stream &DwoOS) {
18030ff28fa6SDerek Schuff   return std::make_unique<WasmObjectWriter>(std::move(MOTW), OS, DwoOS);
18040ff28fa6SDerek Schuff }
1805