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;
197*388fb67bSPaulo Matos   // Maps function/global/table symbols to the
198*388fb67bSPaulo 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;
221*388fb67bSPaulo Matos   // NumTableImports is initialized to 1 to account for the hardcoded import of
222*388fb67bSPaulo Matos   // __indirect_function_table
223*388fb67bSPaulo 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;
273*388fb67bSPaulo 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);
323*388fb67bSPaulo Matos   void writeTableSection(ArrayRef<wasm::WasmTable> Tables);
3246f08c84aSSam Clegg   void writeRelocSection(uint32_t SectionIndex, StringRef Name,
325f77dc2a8SSam Clegg                          std::vector<WasmRelocationEntry> &Relocations);
32631a2c809SSam Clegg   void writeLinkingMetaDataSection(
32786b4a09aSSam Clegg       ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
328ea7caceeSSam Clegg       ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
329ea7caceeSSam Clegg       const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats);
330cbda16ebSThomas Lively   void writeCustomSection(WasmCustomSection &CustomSection,
331cbda16ebSThomas Lively                           const MCAssembler &Asm, const MCAsmLayout &Layout);
3326a31a0d6SSam Clegg   void writeCustomRelocSections();
3336a31a0d6SSam Clegg   void
3346a31a0d6SSam Clegg   updateCustomSectionRelocations(const SmallVector<WasmFunction, 4> &Functions,
3356a31a0d6SSam Clegg                                  const MCAsmLayout &Layout);
336acd7d2b0SSam Clegg 
3377ee758d6SSam Clegg   uint64_t getProvisionalValue(const WasmRelocationEntry &RelEntry,
3387ee758d6SSam Clegg                                const MCAsmLayout &Layout);
339acd7d2b0SSam Clegg   void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
3407ee758d6SSam Clegg                         uint64_t ContentsOffset, const MCAsmLayout &Layout);
341acd7d2b0SSam Clegg 
342acd7d2b0SSam Clegg   uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
3435e3d33a7SSam Clegg   uint32_t getFunctionType(const MCSymbolWasm &Symbol);
344da419bdbSHeejin Ahn   uint32_t getEventType(const MCSymbolWasm &Symbol);
34538b12f5eSHeejin Ahn   void registerFunctionType(const MCSymbolWasm &Symbol);
34638b12f5eSHeejin Ahn   void registerEventType(const MCSymbolWasm &Symbol);
34718eafb6cSDan Gohman };
3489e15f359SSam Clegg 
34918eafb6cSDan Gohman } // end anonymous namespace
35018eafb6cSDan Gohman 
351d934cb88SDan Gohman // Write out a section header and a patchable section size field.
352d934cb88SDan Gohman void WasmObjectWriter::startSection(SectionBookkeeping &Section,
3532322a937SSam Clegg                                     unsigned SectionId) {
354d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "startSection " << SectionId << "\n");
3550ff28fa6SDerek Schuff   W->OS << char(SectionId);
356d934cb88SDan Gohman 
3570ff28fa6SDerek Schuff   Section.SizeOffset = W->OS.tell();
358d934cb88SDan Gohman 
359d934cb88SDan Gohman   // The section size. We don't know the size yet, so reserve enough space
360d934cb88SDan Gohman   // for any 32-bit value; we'll patch it later.
3610ff28fa6SDerek Schuff   encodeULEB128(0, W->OS, 5);
362d934cb88SDan Gohman 
363d934cb88SDan Gohman   // The position where the section starts, for measuring its size.
3640ff28fa6SDerek Schuff   Section.ContentsOffset = W->OS.tell();
3650ff28fa6SDerek Schuff   Section.PayloadOffset = W->OS.tell();
3666f08c84aSSam Clegg   Section.Index = SectionCount++;
367d934cb88SDan Gohman }
3682322a937SSam Clegg 
3692322a937SSam Clegg void WasmObjectWriter::startCustomSection(SectionBookkeeping &Section,
3702322a937SSam Clegg                                           StringRef Name) {
371d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "startCustomSection " << Name << "\n");
3722322a937SSam Clegg   startSection(Section, wasm::WASM_SEC_CUSTOM);
3736a31a0d6SSam Clegg 
3746a31a0d6SSam Clegg   // The position where the section header ends, for measuring its size.
3750ff28fa6SDerek Schuff   Section.PayloadOffset = W->OS.tell();
3766a31a0d6SSam Clegg 
3772322a937SSam Clegg   // Custom sections in wasm also have a string identifier.
3782322a937SSam Clegg   writeString(Name);
3796a31a0d6SSam Clegg 
3806a31a0d6SSam Clegg   // The position where the custom section starts.
3810ff28fa6SDerek Schuff   Section.ContentsOffset = W->OS.tell();
382d934cb88SDan Gohman }
383d934cb88SDan Gohman 
384d934cb88SDan Gohman // Now that the section is complete and we know how big it is, patch up the
385d934cb88SDan Gohman // section size field at the start of the section.
386d934cb88SDan Gohman void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
3870ff28fa6SDerek Schuff   uint64_t Size = W->OS.tell();
388c0affde8SSam Clegg   // /dev/null doesn't support seek/tell and can report offset of 0.
389c0affde8SSam Clegg   // Simply skip this patching in that case.
390c0affde8SSam Clegg   if (!Size)
391c0affde8SSam Clegg     return;
392c0affde8SSam Clegg 
393c0affde8SSam Clegg   Size -= Section.PayloadOffset;
394d934cb88SDan Gohman   if (uint32_t(Size) != Size)
395d934cb88SDan Gohman     report_fatal_error("section size does not fit in a uint32_t");
396d934cb88SDan Gohman 
397d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "endSection size=" << Size << "\n");
398d934cb88SDan Gohman 
399d934cb88SDan Gohman   // Write the final section size to the payload_len field, which follows
400d934cb88SDan Gohman   // the section id byte.
4010ff28fa6SDerek Schuff   writePatchableLEB<5>(static_cast<raw_pwrite_stream &>(W->OS), Size,
402f17b149dSPeter Collingbourne                        Section.SizeOffset);
403d934cb88SDan Gohman }
404d934cb88SDan Gohman 
40518eafb6cSDan Gohman // Emit the Wasm header.
40618eafb6cSDan Gohman void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
4070ff28fa6SDerek Schuff   W->OS.write(wasm::WasmMagic, sizeof(wasm::WasmMagic));
4080ff28fa6SDerek Schuff   W->write<uint32_t>(wasm::WasmVersion);
40918eafb6cSDan Gohman }
41018eafb6cSDan Gohman 
41118eafb6cSDan Gohman void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
41218eafb6cSDan Gohman                                                 const MCAsmLayout &Layout) {
4136ccb59b3SSam Clegg   // Build a map of sections to the function that defines them, for use
4146ccb59b3SSam Clegg   // in recordRelocation.
4156ccb59b3SSam Clegg   for (const MCSymbol &S : Asm.symbols()) {
4166ccb59b3SSam Clegg     const auto &WS = static_cast<const MCSymbolWasm &>(S);
4176ccb59b3SSam Clegg     if (WS.isDefined() && WS.isFunction() && !WS.isVariable()) {
4186ccb59b3SSam Clegg       const auto &Sec = static_cast<const MCSectionWasm &>(S.getSection());
4196ccb59b3SSam Clegg       auto Pair = SectionFunctions.insert(std::make_pair(&Sec, &S));
4206ccb59b3SSam Clegg       if (!Pair.second)
4216ccb59b3SSam Clegg         report_fatal_error("section already has a defining function: " +
4227d1ff446SFangrui Song                            Sec.getName());
4236ccb59b3SSam Clegg     }
4246ccb59b3SSam Clegg   }
42518eafb6cSDan Gohman }
42618eafb6cSDan Gohman 
42718eafb6cSDan Gohman void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
42818eafb6cSDan Gohman                                         const MCAsmLayout &Layout,
42918eafb6cSDan Gohman                                         const MCFragment *Fragment,
43018eafb6cSDan Gohman                                         const MCFixup &Fixup, MCValue Target,
431ceecfe5bSRafael Espindola                                         uint64_t &FixedValue) {
432ecc5e808SSam Clegg   // The WebAssembly backend should never generate FKF_IsPCRel fixups
433e828ce1bSFangrui Song   assert(!(Asm.getBackend().getFixupKindInfo(Fixup.getKind()).Flags &
434ecc5e808SSam Clegg            MCFixupKindInfo::FKF_IsPCRel));
435ecc5e808SSam Clegg 
436fe6414b0SSam Clegg   const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
437d934cb88SDan Gohman   uint64_t C = Target.getConstant();
438d934cb88SDan Gohman   uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
439d934cb88SDan Gohman   MCContext &Ctx = Asm.getContext();
440d934cb88SDan Gohman 
441d934cb88SDan Gohman   if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
442ecc5e808SSam Clegg     // To get here the A - B expression must have failed evaluateAsRelocatable.
443ecc5e808SSam Clegg     // This means either A or B must be undefined and in WebAssembly we can't
444ecc5e808SSam Clegg     // support either of those cases.
445ecc5e808SSam Clegg     const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
446d934cb88SDan Gohman     Ctx.reportError(
447d934cb88SDan Gohman         Fixup.getLoc(),
448d934cb88SDan Gohman         Twine("symbol '") + SymB.getName() +
449ecc5e808SSam Clegg             "': unsupported subtraction expression used in relocation.");
450d934cb88SDan Gohman     return;
451d934cb88SDan Gohman   }
452d934cb88SDan Gohman 
453d934cb88SDan Gohman   // We either rejected the fixup or folded B into C at this point.
454d934cb88SDan Gohman   const MCSymbolRefExpr *RefA = Target.getSymA();
455ecc5e808SSam Clegg   const auto *SymA = cast<MCSymbolWasm>(&RefA->getSymbol());
456d934cb88SDan Gohman 
4573ea1c62cSSam Clegg   // The .init_array isn't translated as data, so don't do relocations in it.
4587d1ff446SFangrui Song   if (FixupSection.getName().startswith(".init_array")) {
4593ea1c62cSSam Clegg     SymA->setUsedInInitArray();
4603ea1c62cSSam Clegg     return;
4613ea1c62cSSam Clegg   }
4623ea1c62cSSam Clegg 
463ecc5e808SSam Clegg   if (SymA->isVariable()) {
464d934cb88SDan Gohman     const MCExpr *Expr = SymA->getVariableValue();
4657ee758d6SSam Clegg     if (const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr))
4666ad8f190SSam Clegg       if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
4676ad8f190SSam Clegg         llvm_unreachable("weakref used in reloc not yet implemented");
468d934cb88SDan Gohman   }
469d934cb88SDan Gohman 
470d934cb88SDan Gohman   // Put any constant offset in an addend. Offsets can be negative, and
471d934cb88SDan Gohman   // LLVM expects wrapping, in contrast to wasm's immediates which can't
472d934cb88SDan Gohman   // be negative and don't wrap.
473d934cb88SDan Gohman   FixedValue = 0;
474d934cb88SDan Gohman 
475a5e175c6SSam Clegg   unsigned Type = TargetObjectWriter->getRelocType(Target, Fixup);
4769d24fb7fSSam Clegg 
4774d57fbd0SSam Clegg   // Absolute offset within a section or a function.
4784d57fbd0SSam Clegg   // Currently only supported for for metadata sections.
4794d57fbd0SSam Clegg   // See: test/MC/WebAssembly/blockaddress.ll
480d1152a26SSam Clegg   if (Type == wasm::R_WASM_FUNCTION_OFFSET_I32 ||
481d1152a26SSam Clegg       Type == wasm::R_WASM_SECTION_OFFSET_I32) {
4824d57fbd0SSam Clegg     if (!FixupSection.getKind().isMetadata())
4834d57fbd0SSam Clegg       report_fatal_error("relocations for function or section offsets are "
4844d57fbd0SSam Clegg                          "only supported in metadata sections");
4854d57fbd0SSam Clegg 
4864d57fbd0SSam Clegg     const MCSymbol *SectionSymbol = nullptr;
4874d57fbd0SSam Clegg     const MCSection &SecA = SymA->getSection();
4884d57fbd0SSam Clegg     if (SecA.getKind().isText())
4896ccb59b3SSam Clegg       SectionSymbol = SectionFunctions.find(&SecA)->second;
4904d57fbd0SSam Clegg     else
4914d57fbd0SSam Clegg       SectionSymbol = SecA.getBeginSymbol();
4924d57fbd0SSam Clegg     if (!SectionSymbol)
4934d57fbd0SSam Clegg       report_fatal_error("section symbol is required for relocation");
4944d57fbd0SSam Clegg 
4954d57fbd0SSam Clegg     C += Layout.getSymbolOffset(*SymA);
4964d57fbd0SSam Clegg     SymA = cast<MCSymbolWasm>(SectionSymbol);
4974d57fbd0SSam Clegg   }
4984d57fbd0SSam Clegg 
499d1152a26SSam Clegg   // Relocation other than R_WASM_TYPE_INDEX_LEB are required to be
5004d57fbd0SSam Clegg   // against a named symbol.
501d1152a26SSam Clegg   if (Type != wasm::R_WASM_TYPE_INDEX_LEB) {
5024d57fbd0SSam Clegg     if (SymA->getName().empty())
5034d57fbd0SSam Clegg       report_fatal_error("relocations against un-named temporaries are not yet "
5044d57fbd0SSam Clegg                          "supported by wasm");
5054d57fbd0SSam Clegg 
5064d57fbd0SSam Clegg     SymA->setUsedInReloc();
5074d57fbd0SSam Clegg   }
508ae03c1e7SSam Clegg 
509492f7529SSam Clegg   if (RefA->getKind() == MCSymbolRefExpr::VK_GOT)
510492f7529SSam Clegg     SymA->setUsedInGOT();
511492f7529SSam Clegg 
512d934cb88SDan Gohman   WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
513d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
514d934cb88SDan Gohman 
5156a31a0d6SSam Clegg   if (FixupSection.isWasmData()) {
516d934cb88SDan Gohman     DataRelocations.push_back(Rec);
5176a31a0d6SSam Clegg   } else if (FixupSection.getKind().isText()) {
51812fd3da9SSam Clegg     CodeRelocations.push_back(Rec);
5196a31a0d6SSam Clegg   } else if (FixupSection.getKind().isMetadata()) {
5206a31a0d6SSam Clegg     CustomSectionsRelocations[&FixupSection].push_back(Rec);
5216a31a0d6SSam Clegg   } else {
52212fd3da9SSam Clegg     llvm_unreachable("unexpected section type");
523d934cb88SDan Gohman   }
5246a31a0d6SSam Clegg }
525d934cb88SDan Gohman 
526d934cb88SDan Gohman // Compute a value to write into the code at the location covered
52760ec3034SSam Clegg // by RelEntry. This value isn't used by the static linker; it just serves
52860ec3034SSam Clegg // to make the object format more readable and more likely to be directly
52960ec3034SSam Clegg // useable.
5303b29376eSWouter van Oortmerssen uint64_t
5317ee758d6SSam Clegg WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry,
5327ee758d6SSam Clegg                                       const MCAsmLayout &Layout) {
53348139ebcSWouter van Oortmerssen   if ((RelEntry.Type == wasm::R_WASM_GLOBAL_INDEX_LEB ||
53448139ebcSWouter van Oortmerssen        RelEntry.Type == wasm::R_WASM_GLOBAL_INDEX_I32) &&
53548139ebcSWouter van Oortmerssen       !RelEntry.Symbol->isGlobal()) {
536492f7529SSam Clegg     assert(GOTIndices.count(RelEntry.Symbol) > 0 && "symbol not found in GOT index space");
537492f7529SSam Clegg     return GOTIndices[RelEntry.Symbol];
538492f7529SSam Clegg   }
539492f7529SSam Clegg 
54060ec3034SSam Clegg   switch (RelEntry.Type) {
5412a7cac93SSam Clegg   case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
542d1152a26SSam Clegg   case wasm::R_WASM_TABLE_INDEX_SLEB:
543cc1b9b68SWouter van Oortmerssen   case wasm::R_WASM_TABLE_INDEX_SLEB64:
544cc1b9b68SWouter van Oortmerssen   case wasm::R_WASM_TABLE_INDEX_I32:
545cc1b9b68SWouter van Oortmerssen   case wasm::R_WASM_TABLE_INDEX_I64: {
546f9edbe95SSam Clegg     // Provisional value is table address of the resolved symbol itself
5477ee758d6SSam Clegg     const MCSymbolWasm *Base =
5487ee758d6SSam Clegg         cast<MCSymbolWasm>(Layout.getBaseSymbol(*RelEntry.Symbol));
5497ee758d6SSam Clegg     assert(Base->isFunction());
55081443ac1SSam Clegg     if (RelEntry.Type == wasm::R_WASM_TABLE_INDEX_REL_SLEB)
5517ee758d6SSam Clegg       return TableIndices[Base] - InitialTableOffset;
55281443ac1SSam Clegg     else
5537ee758d6SSam Clegg       return TableIndices[Base];
554f9edbe95SSam Clegg   }
555d1152a26SSam Clegg   case wasm::R_WASM_TYPE_INDEX_LEB:
5566c899ba6SSam Clegg     // Provisional value is same as the index
55760ec3034SSam Clegg     return getRelocationIndexValue(RelEntry);
558d1152a26SSam Clegg   case wasm::R_WASM_FUNCTION_INDEX_LEB:
559d1152a26SSam Clegg   case wasm::R_WASM_GLOBAL_INDEX_LEB:
56048139ebcSWouter van Oortmerssen   case wasm::R_WASM_GLOBAL_INDEX_I32:
561d1152a26SSam Clegg   case wasm::R_WASM_EVENT_INDEX_LEB:
562da419bdbSHeejin Ahn     // Provisional value is function/global/event Wasm index
563492f7529SSam Clegg     assert(WasmIndices.count(RelEntry.Symbol) > 0 && "symbol not found in wasm index space");
5646c899ba6SSam Clegg     return WasmIndices[RelEntry.Symbol];
565d1152a26SSam Clegg   case wasm::R_WASM_FUNCTION_OFFSET_I32:
566d1152a26SSam Clegg   case wasm::R_WASM_SECTION_OFFSET_I32: {
5676a31a0d6SSam Clegg     const auto &Section =
5686a31a0d6SSam Clegg         static_cast<const MCSectionWasm &>(RelEntry.Symbol->getSection());
5696a31a0d6SSam Clegg     return Section.getSectionOffset() + RelEntry.Addend;
5706a31a0d6SSam Clegg   }
571d1152a26SSam Clegg   case wasm::R_WASM_MEMORY_ADDR_LEB:
5723b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_LEB64:
5733b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_SLEB:
5743b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_SLEB64:
5752a7cac93SSam Clegg   case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
5763b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_REL_SLEB64:
5773b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_I32:
5783b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_I64: {
5799c7b5808SDominic Chen     // Provisional value is address of the global plus the offset
5807ee758d6SSam Clegg     const MCSymbolWasm *Base =
5817ee758d6SSam Clegg         cast<MCSymbolWasm>(Layout.getBaseSymbol(*RelEntry.Symbol));
582270ed1b3SSam Clegg     // For undefined symbols, use zero
5837ee758d6SSam Clegg     if (!Base->isDefined())
584270ed1b3SSam Clegg       return 0;
5859c7b5808SDominic Chen     const wasm::WasmDataReference &BaseRef = DataLocations[Base],
5869c7b5808SDominic Chen                                   &SymRef = DataLocations[RelEntry.Symbol];
5879c7b5808SDominic Chen     const WasmDataSegment &Segment = DataSegments[BaseRef.Segment];
588d934cb88SDan Gohman     // Ignore overflow. LLVM allows address arithmetic to silently wrap.
5899c7b5808SDominic Chen     return Segment.Offset + BaseRef.Offset + SymRef.Offset + RelEntry.Addend;
59060ec3034SSam Clegg   }
59160ec3034SSam Clegg   default:
59260ec3034SSam Clegg     llvm_unreachable("invalid relocation type");
59360ec3034SSam Clegg   }
594d934cb88SDan Gohman }
595d934cb88SDan Gohman 
596759631c7SSam Clegg static void addData(SmallVectorImpl<char> &DataBytes,
59763ebb813SSam Clegg                     MCSectionWasm &DataSection) {
5987d1ff446SFangrui Song   LLVM_DEBUG(errs() << "addData: " << DataSection.getName() << "\n");
599759631c7SSam Clegg 
60063ebb813SSam Clegg   DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
60163ebb813SSam Clegg 
602759631c7SSam Clegg   for (const MCFragment &Frag : DataSection) {
603759631c7SSam Clegg     if (Frag.hasInstructions())
604759631c7SSam Clegg       report_fatal_error("only data supported in data sections");
605759631c7SSam Clegg 
606759631c7SSam Clegg     if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
607759631c7SSam Clegg       if (Align->getValueSize() != 1)
608759631c7SSam Clegg         report_fatal_error("only byte values supported for alignment");
609759631c7SSam Clegg       // If nops are requested, use zeros, as this is the data section.
610759631c7SSam Clegg       uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
611f208f631SHeejin Ahn       uint64_t Size =
612f208f631SHeejin Ahn           std::min<uint64_t>(alignTo(DataBytes.size(), Align->getAlignment()),
613f208f631SHeejin Ahn                              DataBytes.size() + Align->getMaxBytesToEmit());
614759631c7SSam Clegg       DataBytes.resize(Size, Value);
615759631c7SSam Clegg     } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
616588fad4dSNirav Dave       int64_t NumValues;
617588fad4dSNirav Dave       if (!Fill->getNumValues().evaluateAsAbsolute(NumValues))
618d707c370SRafael Espindola         llvm_unreachable("The fill should be an assembler constant");
619588fad4dSNirav Dave       DataBytes.insert(DataBytes.end(), Fill->getValueSize() * NumValues,
620588fad4dSNirav Dave                        Fill->getValue());
62124faf859SHeejin Ahn     } else if (auto *LEB = dyn_cast<MCLEBFragment>(&Frag)) {
62224faf859SHeejin Ahn       const SmallVectorImpl<char> &Contents = LEB->getContents();
62324faf859SHeejin Ahn       DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
624759631c7SSam Clegg     } else {
625759631c7SSam Clegg       const auto &DataFrag = cast<MCDataFragment>(Frag);
626759631c7SSam Clegg       const SmallVectorImpl<char> &Contents = DataFrag.getContents();
627759631c7SSam Clegg       DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
628759631c7SSam Clegg     }
629759631c7SSam Clegg   }
630759631c7SSam Clegg 
631d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
632759631c7SSam Clegg }
633759631c7SSam Clegg 
63460ec3034SSam Clegg uint32_t
63560ec3034SSam Clegg WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
636d1152a26SSam Clegg   if (RelEntry.Type == wasm::R_WASM_TYPE_INDEX_LEB) {
637b7787fd0SSam Clegg     if (!TypeIndices.count(RelEntry.Symbol))
638b7787fd0SSam Clegg       report_fatal_error("symbol not found in type index space: " +
639b7787fd0SSam Clegg                          RelEntry.Symbol->getName());
640acd7d2b0SSam Clegg     return TypeIndices[RelEntry.Symbol];
641acd7d2b0SSam Clegg   }
64260ec3034SSam Clegg 
64325d8e68bSSam Clegg   return RelEntry.Symbol->getIndex();
644acd7d2b0SSam Clegg }
645acd7d2b0SSam Clegg 
646d934cb88SDan Gohman // Apply the portions of the relocation records that we can handle ourselves
647d934cb88SDan Gohman // directly.
648acd7d2b0SSam Clegg void WasmObjectWriter::applyRelocations(
6497ee758d6SSam Clegg     ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset,
6507ee758d6SSam Clegg     const MCAsmLayout &Layout) {
6510ff28fa6SDerek Schuff   auto &Stream = static_cast<raw_pwrite_stream &>(W->OS);
652d934cb88SDan Gohman   for (const WasmRelocationEntry &RelEntry : Relocations) {
653d934cb88SDan Gohman     uint64_t Offset = ContentsOffset +
654d934cb88SDan Gohman                       RelEntry.FixupSection->getSectionOffset() +
655d934cb88SDan Gohman                       RelEntry.Offset;
656d934cb88SDan Gohman 
657d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
6587ee758d6SSam Clegg     auto Value = getProvisionalValue(RelEntry, Layout);
65960ec3034SSam Clegg 
660acd7d2b0SSam Clegg     switch (RelEntry.Type) {
661d1152a26SSam Clegg     case wasm::R_WASM_FUNCTION_INDEX_LEB:
662d1152a26SSam Clegg     case wasm::R_WASM_TYPE_INDEX_LEB:
663d1152a26SSam Clegg     case wasm::R_WASM_GLOBAL_INDEX_LEB:
664d1152a26SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_LEB:
665d1152a26SSam Clegg     case wasm::R_WASM_EVENT_INDEX_LEB:
6663b29376eSWouter van Oortmerssen       writePatchableLEB<5>(Stream, Value, Offset);
6673b29376eSWouter van Oortmerssen       break;
6683b29376eSWouter van Oortmerssen     case wasm::R_WASM_MEMORY_ADDR_LEB64:
6693b29376eSWouter van Oortmerssen       writePatchableLEB<10>(Stream, Value, Offset);
670d934cb88SDan Gohman       break;
671d1152a26SSam Clegg     case wasm::R_WASM_TABLE_INDEX_I32:
672d1152a26SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_I32:
673d1152a26SSam Clegg     case wasm::R_WASM_FUNCTION_OFFSET_I32:
674d1152a26SSam Clegg     case wasm::R_WASM_SECTION_OFFSET_I32:
67548139ebcSWouter van Oortmerssen     case wasm::R_WASM_GLOBAL_INDEX_I32:
6760a6c4d8dSSam Clegg       patchI32(Stream, Value, Offset);
677d934cb88SDan Gohman       break;
678cc1b9b68SWouter van Oortmerssen     case wasm::R_WASM_TABLE_INDEX_I64:
6793b29376eSWouter van Oortmerssen     case wasm::R_WASM_MEMORY_ADDR_I64:
6803b29376eSWouter van Oortmerssen       patchI64(Stream, Value, Offset);
6813b29376eSWouter van Oortmerssen       break;
682d1152a26SSam Clegg     case wasm::R_WASM_TABLE_INDEX_SLEB:
6832a7cac93SSam Clegg     case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
684d1152a26SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_SLEB:
6852a7cac93SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
6863b29376eSWouter van Oortmerssen       writePatchableSLEB<5>(Stream, Value, Offset);
6873b29376eSWouter van Oortmerssen       break;
688cc1b9b68SWouter van Oortmerssen     case wasm::R_WASM_TABLE_INDEX_SLEB64:
6893b29376eSWouter van Oortmerssen     case wasm::R_WASM_MEMORY_ADDR_SLEB64:
6903b29376eSWouter van Oortmerssen     case wasm::R_WASM_MEMORY_ADDR_REL_SLEB64:
6913b29376eSWouter van Oortmerssen       writePatchableSLEB<10>(Stream, Value, Offset);
69260ec3034SSam Clegg       break;
693d934cb88SDan Gohman     default:
6949d24fb7fSSam Clegg       llvm_unreachable("invalid relocation type");
695d934cb88SDan Gohman     }
696d934cb88SDan Gohman   }
69718eafb6cSDan Gohman }
69818eafb6cSDan Gohman 
6994c41fb5aSHeejin Ahn void WasmObjectWriter::writeTypeSection(
7004c41fb5aSHeejin Ahn     ArrayRef<wasm::WasmSignature> Signatures) {
701da419bdbSHeejin Ahn   if (Signatures.empty())
7029e15f359SSam Clegg     return;
7039e15f359SSam Clegg 
7049e15f359SSam Clegg   SectionBookkeeping Section;
7059e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_TYPE);
7069e15f359SSam Clegg 
7070ff28fa6SDerek Schuff   encodeULEB128(Signatures.size(), W->OS);
7089e15f359SSam Clegg 
7094c41fb5aSHeejin Ahn   for (const wasm::WasmSignature &Sig : Signatures) {
7100ff28fa6SDerek Schuff     W->OS << char(wasm::WASM_TYPE_FUNC);
7110ff28fa6SDerek Schuff     encodeULEB128(Sig.Params.size(), W->OS);
712da419bdbSHeejin Ahn     for (wasm::ValType Ty : Sig.Params)
7139e15f359SSam Clegg       writeValueType(Ty);
7140ff28fa6SDerek Schuff     encodeULEB128(Sig.Returns.size(), W->OS);
715da419bdbSHeejin Ahn     for (wasm::ValType Ty : Sig.Returns)
7169e15f359SSam Clegg       writeValueType(Ty);
7179e15f359SSam Clegg   }
7189e15f359SSam Clegg 
7199e15f359SSam Clegg   endSection(Section);
7209e15f359SSam Clegg }
7219e15f359SSam Clegg 
7228defa952SSam Clegg void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports,
7234d135b04SWouter van Oortmerssen                                           uint64_t DataSize,
724f950b24aSSam Clegg                                           uint32_t NumElements) {
7259e15f359SSam Clegg   if (Imports.empty())
7269e15f359SSam Clegg     return;
7279e15f359SSam Clegg 
7284d135b04SWouter van Oortmerssen   uint64_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
729f950b24aSSam Clegg 
7309e15f359SSam Clegg   SectionBookkeeping Section;
7319e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_IMPORT);
7329e15f359SSam Clegg 
7330ff28fa6SDerek Schuff   encodeULEB128(Imports.size(), W->OS);
7348defa952SSam Clegg   for (const wasm::WasmImport &Import : Imports) {
7358defa952SSam Clegg     writeString(Import.Module);
7368defa952SSam Clegg     writeString(Import.Field);
7370ff28fa6SDerek Schuff     W->OS << char(Import.Kind);
7389e15f359SSam Clegg 
7399e15f359SSam Clegg     switch (Import.Kind) {
7409e15f359SSam Clegg     case wasm::WASM_EXTERNAL_FUNCTION:
7410ff28fa6SDerek Schuff       encodeULEB128(Import.SigIndex, W->OS);
7429e15f359SSam Clegg       break;
7439e15f359SSam Clegg     case wasm::WASM_EXTERNAL_GLOBAL:
7440ff28fa6SDerek Schuff       W->OS << char(Import.Global.Type);
7450ff28fa6SDerek Schuff       W->OS << char(Import.Global.Mutable ? 1 : 0);
7469e15f359SSam Clegg       break;
747f950b24aSSam Clegg     case wasm::WASM_EXTERNAL_MEMORY:
7480ff28fa6SDerek Schuff       encodeULEB128(Import.Memory.Flags, W->OS);
7490ff28fa6SDerek Schuff       encodeULEB128(NumPages, W->OS); // initial
750f950b24aSSam Clegg       break;
751f950b24aSSam Clegg     case wasm::WASM_EXTERNAL_TABLE:
7520ff28fa6SDerek Schuff       W->OS << char(Import.Table.ElemType);
7530ff28fa6SDerek Schuff       encodeULEB128(0, W->OS);           // flags
7540ff28fa6SDerek Schuff       encodeULEB128(NumElements, W->OS); // initial
755f950b24aSSam Clegg       break;
756da419bdbSHeejin Ahn     case wasm::WASM_EXTERNAL_EVENT:
7570ff28fa6SDerek Schuff       encodeULEB128(Import.Event.Attribute, W->OS);
7580ff28fa6SDerek Schuff       encodeULEB128(Import.Event.SigIndex, W->OS);
759da419bdbSHeejin Ahn       break;
7609e15f359SSam Clegg     default:
7619e15f359SSam Clegg       llvm_unreachable("unsupported import kind");
7629e15f359SSam Clegg     }
7639e15f359SSam Clegg   }
7649e15f359SSam Clegg 
7659e15f359SSam Clegg   endSection(Section);
7669e15f359SSam Clegg }
7679e15f359SSam Clegg 
768457fb0b4SSam Clegg void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
7699e15f359SSam Clegg   if (Functions.empty())
7709e15f359SSam Clegg     return;
7719e15f359SSam Clegg 
7729e15f359SSam Clegg   SectionBookkeeping Section;
7739e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_FUNCTION);
7749e15f359SSam Clegg 
7750ff28fa6SDerek Schuff   encodeULEB128(Functions.size(), W->OS);
7769e15f359SSam Clegg   for (const WasmFunction &Func : Functions)
7770ff28fa6SDerek Schuff     encodeULEB128(Func.SigIndex, W->OS);
7789e15f359SSam Clegg 
7799e15f359SSam Clegg   endSection(Section);
7809e15f359SSam Clegg }
7819e15f359SSam Clegg 
782da419bdbSHeejin Ahn void WasmObjectWriter::writeEventSection(ArrayRef<wasm::WasmEventType> Events) {
783da419bdbSHeejin Ahn   if (Events.empty())
784da419bdbSHeejin Ahn     return;
785da419bdbSHeejin Ahn 
786da419bdbSHeejin Ahn   SectionBookkeeping Section;
787da419bdbSHeejin Ahn   startSection(Section, wasm::WASM_SEC_EVENT);
788da419bdbSHeejin Ahn 
7890ff28fa6SDerek Schuff   encodeULEB128(Events.size(), W->OS);
790da419bdbSHeejin Ahn   for (const wasm::WasmEventType &Event : Events) {
7910ff28fa6SDerek Schuff     encodeULEB128(Event.Attribute, W->OS);
7920ff28fa6SDerek Schuff     encodeULEB128(Event.SigIndex, W->OS);
793da419bdbSHeejin Ahn   }
794da419bdbSHeejin Ahn 
795da419bdbSHeejin Ahn   endSection(Section);
796da419bdbSHeejin Ahn }
797da419bdbSHeejin Ahn 
7980a6c4d8dSSam Clegg void WasmObjectWriter::writeGlobalSection(ArrayRef<wasm::WasmGlobal> Globals) {
7990a6c4d8dSSam Clegg   if (Globals.empty())
8000a6c4d8dSSam Clegg     return;
8010a6c4d8dSSam Clegg 
8020a6c4d8dSSam Clegg   SectionBookkeeping Section;
8030a6c4d8dSSam Clegg   startSection(Section, wasm::WASM_SEC_GLOBAL);
8040a6c4d8dSSam Clegg 
8050ff28fa6SDerek Schuff   encodeULEB128(Globals.size(), W->OS);
8060a6c4d8dSSam Clegg   for (const wasm::WasmGlobal &Global : Globals) {
8070ff28fa6SDerek Schuff     encodeULEB128(Global.Type.Type, W->OS);
8080ff28fa6SDerek Schuff     W->OS << char(Global.Type.Mutable);
8090ff28fa6SDerek Schuff     W->OS << char(Global.InitExpr.Opcode);
8100a6c4d8dSSam Clegg     switch (Global.Type.Type) {
8110a6c4d8dSSam Clegg     case wasm::WASM_TYPE_I32:
8120ff28fa6SDerek Schuff       encodeSLEB128(0, W->OS);
8130a6c4d8dSSam Clegg       break;
8140a6c4d8dSSam Clegg     case wasm::WASM_TYPE_I64:
8150ff28fa6SDerek Schuff       encodeSLEB128(0, W->OS);
8160a6c4d8dSSam Clegg       break;
8170a6c4d8dSSam Clegg     case wasm::WASM_TYPE_F32:
8180a6c4d8dSSam Clegg       writeI32(0);
8190a6c4d8dSSam Clegg       break;
8200a6c4d8dSSam Clegg     case wasm::WASM_TYPE_F64:
8210a6c4d8dSSam Clegg       writeI64(0);
8220a6c4d8dSSam Clegg       break;
82379aad89dSSam Clegg     case wasm::WASM_TYPE_EXTERNREF:
82479aad89dSSam Clegg       writeValueType(wasm::ValType::EXTERNREF);
82579aad89dSSam Clegg       break;
8260a6c4d8dSSam Clegg     default:
8270a6c4d8dSSam Clegg       llvm_unreachable("unexpected type");
8280a6c4d8dSSam Clegg     }
8290ff28fa6SDerek Schuff     W->OS << char(wasm::WASM_OPCODE_END);
8300a6c4d8dSSam Clegg   }
8310a6c4d8dSSam Clegg 
8320a6c4d8dSSam Clegg   endSection(Section);
8330a6c4d8dSSam Clegg }
8340a6c4d8dSSam Clegg 
835*388fb67bSPaulo Matos void WasmObjectWriter::writeTableSection(ArrayRef<wasm::WasmTable> Tables) {
836*388fb67bSPaulo Matos   if (Tables.empty())
837*388fb67bSPaulo Matos     return;
838*388fb67bSPaulo Matos 
839*388fb67bSPaulo Matos   SectionBookkeeping Section;
840*388fb67bSPaulo Matos   startSection(Section, wasm::WASM_SEC_TABLE);
841*388fb67bSPaulo Matos 
842*388fb67bSPaulo Matos   encodeULEB128(Tables.size(), W->OS);
843*388fb67bSPaulo Matos   for (const wasm::WasmTable &Table : Tables) {
844*388fb67bSPaulo Matos     encodeULEB128(Table.ElemType, W->OS);
845*388fb67bSPaulo Matos     encodeULEB128(Table.Limits.Flags, W->OS);
846*388fb67bSPaulo Matos     encodeULEB128(Table.Limits.Initial, W->OS);
847*388fb67bSPaulo Matos     if (Table.Limits.Flags & wasm::WASM_LIMITS_FLAG_HAS_MAX)
848*388fb67bSPaulo Matos       encodeULEB128(Table.Limits.Maximum, W->OS);
849*388fb67bSPaulo Matos   }
850*388fb67bSPaulo Matos   endSection(Section);
851*388fb67bSPaulo Matos }
852*388fb67bSPaulo Matos 
8538defa952SSam Clegg void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) {
8549e15f359SSam Clegg   if (Exports.empty())
8559e15f359SSam Clegg     return;
8569e15f359SSam Clegg 
8579e15f359SSam Clegg   SectionBookkeeping Section;
8589e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_EXPORT);
8599e15f359SSam Clegg 
8600ff28fa6SDerek Schuff   encodeULEB128(Exports.size(), W->OS);
8618defa952SSam Clegg   for (const wasm::WasmExport &Export : Exports) {
8628defa952SSam Clegg     writeString(Export.Name);
8630ff28fa6SDerek Schuff     W->OS << char(Export.Kind);
8640ff28fa6SDerek Schuff     encodeULEB128(Export.Index, W->OS);
8659e15f359SSam Clegg   }
8669e15f359SSam Clegg 
8679e15f359SSam Clegg   endSection(Section);
8689e15f359SSam Clegg }
8699e15f359SSam Clegg 
870457fb0b4SSam Clegg void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
8719e15f359SSam Clegg   if (TableElems.empty())
8729e15f359SSam Clegg     return;
8739e15f359SSam Clegg 
8749e15f359SSam Clegg   SectionBookkeeping Section;
8759e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_ELEM);
8769e15f359SSam Clegg 
8770ff28fa6SDerek Schuff   encodeULEB128(1, W->OS); // number of "segments"
8780ff28fa6SDerek Schuff   encodeULEB128(0, W->OS); // the table index
8799e15f359SSam Clegg 
8809e15f359SSam Clegg   // init expr for starting offset
8810ff28fa6SDerek Schuff   W->OS << char(wasm::WASM_OPCODE_I32_CONST);
8820ff28fa6SDerek Schuff   encodeSLEB128(InitialTableOffset, W->OS);
8830ff28fa6SDerek Schuff   W->OS << char(wasm::WASM_OPCODE_END);
8849e15f359SSam Clegg 
8850ff28fa6SDerek Schuff   encodeULEB128(TableElems.size(), W->OS);
8869e15f359SSam Clegg   for (uint32_t Elem : TableElems)
8870ff28fa6SDerek Schuff     encodeULEB128(Elem, W->OS);
8889e15f359SSam Clegg 
8899e15f359SSam Clegg   endSection(Section);
8909e15f359SSam Clegg }
8919e15f359SSam Clegg 
892fef8de66SThomas Lively void WasmObjectWriter::writeDataCountSection() {
893fef8de66SThomas Lively   if (DataSegments.empty())
894fef8de66SThomas Lively     return;
895fef8de66SThomas Lively 
896fef8de66SThomas Lively   SectionBookkeeping Section;
897fef8de66SThomas Lively   startSection(Section, wasm::WASM_SEC_DATACOUNT);
8980ff28fa6SDerek Schuff   encodeULEB128(DataSegments.size(), W->OS);
899fef8de66SThomas Lively   endSection(Section);
900fef8de66SThomas Lively }
901fef8de66SThomas Lively 
902e49584a3SSam Clegg uint32_t WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
903457fb0b4SSam Clegg                                             const MCAsmLayout &Layout,
904457fb0b4SSam Clegg                                             ArrayRef<WasmFunction> Functions) {
9059e15f359SSam Clegg   if (Functions.empty())
906e49584a3SSam Clegg     return 0;
9079e15f359SSam Clegg 
9089e15f359SSam Clegg   SectionBookkeeping Section;
9099e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_CODE);
9109e15f359SSam Clegg 
9110ff28fa6SDerek Schuff   encodeULEB128(Functions.size(), W->OS);
9129e15f359SSam Clegg 
9139e15f359SSam Clegg   for (const WasmFunction &Func : Functions) {
914fe6414b0SSam Clegg     auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
9159e15f359SSam Clegg 
9169e15f359SSam Clegg     int64_t Size = 0;
9179e15f359SSam Clegg     if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
9189e15f359SSam Clegg       report_fatal_error(".size expression must be evaluatable");
9199e15f359SSam Clegg 
9200ff28fa6SDerek Schuff     encodeULEB128(Size, W->OS);
9210ff28fa6SDerek Schuff     FuncSection.setSectionOffset(W->OS.tell() - Section.ContentsOffset);
9220ff28fa6SDerek Schuff     Asm.writeSectionData(W->OS, &FuncSection, Layout);
9239e15f359SSam Clegg   }
9249e15f359SSam Clegg 
9259e15f359SSam Clegg   // Apply fixups.
9267ee758d6SSam Clegg   applyRelocations(CodeRelocations, Section.ContentsOffset, Layout);
9279e15f359SSam Clegg 
9289e15f359SSam Clegg   endSection(Section);
929e49584a3SSam Clegg   return Section.Index;
9309e15f359SSam Clegg }
9319e15f359SSam Clegg 
932e49584a3SSam Clegg uint32_t WasmObjectWriter::writeDataSection(const MCAsmLayout &Layout) {
9336c899ba6SSam Clegg   if (DataSegments.empty())
934e49584a3SSam Clegg     return 0;
9359e15f359SSam Clegg 
9369e15f359SSam Clegg   SectionBookkeeping Section;
9379e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_DATA);
9389e15f359SSam Clegg 
9390ff28fa6SDerek Schuff   encodeULEB128(DataSegments.size(), W->OS); // count
9407c395943SSam Clegg 
9416c899ba6SSam Clegg   for (const WasmDataSegment &Segment : DataSegments) {
9420ff28fa6SDerek Schuff     encodeULEB128(Segment.InitFlags, W->OS); // flags
9432e150409SThomas Lively     if (Segment.InitFlags & wasm::WASM_SEGMENT_HAS_MEMINDEX)
9440ff28fa6SDerek Schuff       encodeULEB128(0, W->OS); // memory index
9452e150409SThomas Lively     if ((Segment.InitFlags & wasm::WASM_SEGMENT_IS_PASSIVE) == 0) {
9460ff28fa6SDerek Schuff       W->OS << char(Segment.Offset > INT32_MAX ? wasm::WASM_OPCODE_I64_CONST
9474d135b04SWouter van Oortmerssen                                                : wasm::WASM_OPCODE_I32_CONST);
9480ff28fa6SDerek Schuff       encodeSLEB128(Segment.Offset, W->OS); // offset
9490ff28fa6SDerek Schuff       W->OS << char(wasm::WASM_OPCODE_END);
9502e150409SThomas Lively     }
9510ff28fa6SDerek Schuff     encodeULEB128(Segment.Data.size(), W->OS); // size
9520ff28fa6SDerek Schuff     Segment.Section->setSectionOffset(W->OS.tell() - Section.ContentsOffset);
9530ff28fa6SDerek Schuff     W->OS << Segment.Data; // data
9547c395943SSam Clegg   }
9559e15f359SSam Clegg 
9569e15f359SSam Clegg   // Apply fixups.
9577ee758d6SSam Clegg   applyRelocations(DataRelocations, Section.ContentsOffset, Layout);
9589e15f359SSam Clegg 
9599e15f359SSam Clegg   endSection(Section);
960e49584a3SSam Clegg   return Section.Index;
9619e15f359SSam Clegg }
9629e15f359SSam Clegg 
9636f08c84aSSam Clegg void WasmObjectWriter::writeRelocSection(
9646f08c84aSSam Clegg     uint32_t SectionIndex, StringRef Name,
965f77dc2a8SSam Clegg     std::vector<WasmRelocationEntry> &Relocs) {
9669e15f359SSam Clegg   // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
9679e15f359SSam Clegg   // for descriptions of the reloc sections.
9689e15f359SSam Clegg 
969f77dc2a8SSam Clegg   if (Relocs.empty())
9709e15f359SSam Clegg     return;
9719e15f359SSam Clegg 
972f77dc2a8SSam Clegg   // First, ensure the relocations are sorted in offset order.  In general they
973f77dc2a8SSam Clegg   // should already be sorted since `recordRelocation` is called in offset
974f77dc2a8SSam Clegg   // order, but for the code section we combine many MC sections into single
975f77dc2a8SSam Clegg   // wasm section, and this order is determined by the order of Asm.Symbols()
976f77dc2a8SSam Clegg   // not the sections order.
977efd94c56SFangrui Song   llvm::stable_sort(
978efd94c56SFangrui Song       Relocs, [](const WasmRelocationEntry &A, const WasmRelocationEntry &B) {
979f77dc2a8SSam Clegg         return (A.Offset + A.FixupSection->getSectionOffset()) <
980f77dc2a8SSam Clegg                (B.Offset + B.FixupSection->getSectionOffset());
981f77dc2a8SSam Clegg       });
982f77dc2a8SSam Clegg 
9839e15f359SSam Clegg   SectionBookkeeping Section;
9846f08c84aSSam Clegg   startCustomSection(Section, std::string("reloc.") + Name.str());
9859e15f359SSam Clegg 
9860ff28fa6SDerek Schuff   encodeULEB128(SectionIndex, W->OS);
9870ff28fa6SDerek Schuff   encodeULEB128(Relocs.size(), W->OS);
988f77dc2a8SSam Clegg   for (const WasmRelocationEntry &RelEntry : Relocs) {
989f208f631SHeejin Ahn     uint64_t Offset =
990f208f631SHeejin Ahn         RelEntry.Offset + RelEntry.FixupSection->getSectionOffset();
9916f08c84aSSam Clegg     uint32_t Index = getRelocationIndexValue(RelEntry);
9929e15f359SSam Clegg 
9930ff28fa6SDerek Schuff     W->OS << char(RelEntry.Type);
9940ff28fa6SDerek Schuff     encodeULEB128(Offset, W->OS);
9950ff28fa6SDerek Schuff     encodeULEB128(Index, W->OS);
9966f08c84aSSam Clegg     if (RelEntry.hasAddend())
9970ff28fa6SDerek Schuff       encodeSLEB128(RelEntry.Addend, W->OS);
9989e15f359SSam Clegg   }
9999e15f359SSam Clegg 
10009e15f359SSam Clegg   endSection(Section);
10019e15f359SSam Clegg }
10029e15f359SSam Clegg 
10036a31a0d6SSam Clegg void WasmObjectWriter::writeCustomRelocSections() {
10046a31a0d6SSam Clegg   for (const auto &Sec : CustomSections) {
10056a31a0d6SSam Clegg     auto &Relocations = CustomSectionsRelocations[Sec.Section];
10066a31a0d6SSam Clegg     writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations);
10076a31a0d6SSam Clegg   }
10086a31a0d6SSam Clegg }
10096a31a0d6SSam Clegg 
10109e15f359SSam Clegg void WasmObjectWriter::writeLinkingMetaDataSection(
101186b4a09aSSam Clegg     ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
1012ea7caceeSSam Clegg     ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
1013ea7caceeSSam Clegg     const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) {
10149e15f359SSam Clegg   SectionBookkeeping Section;
10152322a937SSam Clegg   startCustomSection(Section, "linking");
10160ff28fa6SDerek Schuff   encodeULEB128(wasm::WasmMetadataVersion, W->OS);
10179e15f359SSam Clegg 
10186bb5a41fSSam Clegg   SectionBookkeeping SubSection;
10196c899ba6SSam Clegg   if (SymbolInfos.size() != 0) {
10206c899ba6SSam Clegg     startSection(SubSection, wasm::WASM_SYMBOL_TABLE);
10210ff28fa6SDerek Schuff     encodeULEB128(SymbolInfos.size(), W->OS);
10226c899ba6SSam Clegg     for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) {
10230ff28fa6SDerek Schuff       encodeULEB128(Sym.Kind, W->OS);
10240ff28fa6SDerek Schuff       encodeULEB128(Sym.Flags, W->OS);
10256c899ba6SSam Clegg       switch (Sym.Kind) {
10266c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_FUNCTION:
10276c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_GLOBAL:
1028da419bdbSHeejin Ahn       case wasm::WASM_SYMBOL_TYPE_EVENT:
1029*388fb67bSPaulo Matos       case wasm::WASM_SYMBOL_TYPE_TABLE:
10300ff28fa6SDerek Schuff         encodeULEB128(Sym.ElementIndex, W->OS);
103129874ceaSDan Gohman         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0 ||
103229874ceaSDan Gohman             (Sym.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0)
10336c899ba6SSam Clegg           writeString(Sym.Name);
10346c899ba6SSam Clegg         break;
10356c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_DATA:
10366c899ba6SSam Clegg         writeString(Sym.Name);
10376c899ba6SSam Clegg         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) {
10380ff28fa6SDerek Schuff           encodeULEB128(Sym.DataRef.Segment, W->OS);
10390ff28fa6SDerek Schuff           encodeULEB128(Sym.DataRef.Offset, W->OS);
10400ff28fa6SDerek Schuff           encodeULEB128(Sym.DataRef.Size, W->OS);
10416c899ba6SSam Clegg         }
10426c899ba6SSam Clegg         break;
10436a31a0d6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_SECTION: {
10446a31a0d6SSam Clegg         const uint32_t SectionIndex =
10456a31a0d6SSam Clegg             CustomSections[Sym.ElementIndex].OutputIndex;
10460ff28fa6SDerek Schuff         encodeULEB128(SectionIndex, W->OS);
10476a31a0d6SSam Clegg         break;
10486a31a0d6SSam Clegg       }
10496c899ba6SSam Clegg       default:
10506c899ba6SSam Clegg         llvm_unreachable("unexpected kind");
10516c899ba6SSam Clegg       }
1052b7787fd0SSam Clegg     }
1053b7787fd0SSam Clegg     endSection(SubSection);
1054b7787fd0SSam Clegg   }
10559e15f359SSam Clegg 
10566c899ba6SSam Clegg   if (DataSegments.size()) {
105763ebb813SSam Clegg     startSection(SubSection, wasm::WASM_SEGMENT_INFO);
10580ff28fa6SDerek Schuff     encodeULEB128(DataSegments.size(), W->OS);
10596c899ba6SSam Clegg     for (const WasmDataSegment &Segment : DataSegments) {
1060d95ed959SSam Clegg       writeString(Segment.Name);
10610ff28fa6SDerek Schuff       encodeULEB128(Segment.Alignment, W->OS);
10620ff28fa6SDerek Schuff       encodeULEB128(Segment.LinkerFlags, W->OS);
106363ebb813SSam Clegg     }
1064d95ed959SSam Clegg     endSection(SubSection);
1065d95ed959SSam Clegg   }
1066d95ed959SSam Clegg 
1067bafe6902SSam Clegg   if (!InitFuncs.empty()) {
1068bafe6902SSam Clegg     startSection(SubSection, wasm::WASM_INIT_FUNCS);
10690ff28fa6SDerek Schuff     encodeULEB128(InitFuncs.size(), W->OS);
1070bafe6902SSam Clegg     for (auto &StartFunc : InitFuncs) {
10710ff28fa6SDerek Schuff       encodeULEB128(StartFunc.first, W->OS);  // priority
10720ff28fa6SDerek Schuff       encodeULEB128(StartFunc.second, W->OS); // function index
1073bafe6902SSam Clegg     }
1074bafe6902SSam Clegg     endSection(SubSection);
1075bafe6902SSam Clegg   }
1076bafe6902SSam Clegg 
1077ea7caceeSSam Clegg   if (Comdats.size()) {
1078ea7caceeSSam Clegg     startSection(SubSection, wasm::WASM_COMDAT_INFO);
10790ff28fa6SDerek Schuff     encodeULEB128(Comdats.size(), W->OS);
1080ea7caceeSSam Clegg     for (const auto &C : Comdats) {
1081ea7caceeSSam Clegg       writeString(C.first);
10820ff28fa6SDerek Schuff       encodeULEB128(0, W->OS); // flags for future use
10830ff28fa6SDerek Schuff       encodeULEB128(C.second.size(), W->OS);
1084ea7caceeSSam Clegg       for (const WasmComdatEntry &Entry : C.second) {
10850ff28fa6SDerek Schuff         encodeULEB128(Entry.Kind, W->OS);
10860ff28fa6SDerek Schuff         encodeULEB128(Entry.Index, W->OS);
1087ea7caceeSSam Clegg       }
1088ea7caceeSSam Clegg     }
1089ea7caceeSSam Clegg     endSection(SubSection);
1090ea7caceeSSam Clegg   }
1091ea7caceeSSam Clegg 
10929e15f359SSam Clegg   endSection(Section);
10939e15f359SSam Clegg }
10949e15f359SSam Clegg 
1095cbda16ebSThomas Lively void WasmObjectWriter::writeCustomSection(WasmCustomSection &CustomSection,
1096cbda16ebSThomas Lively                                           const MCAssembler &Asm,
10976a31a0d6SSam Clegg                                           const MCAsmLayout &Layout) {
1098cfd44a2eSSam Clegg   SectionBookkeeping Section;
10996a31a0d6SSam Clegg   auto *Sec = CustomSection.Section;
11002322a937SSam Clegg   startCustomSection(Section, CustomSection.Name);
11016a31a0d6SSam Clegg 
11020ff28fa6SDerek Schuff   Sec->setSectionOffset(W->OS.tell() - Section.ContentsOffset);
11030ff28fa6SDerek Schuff   Asm.writeSectionData(W->OS, Sec, Layout);
11046a31a0d6SSam Clegg 
11056a31a0d6SSam Clegg   CustomSection.OutputContentsOffset = Section.ContentsOffset;
11066a31a0d6SSam Clegg   CustomSection.OutputIndex = Section.Index;
11076a31a0d6SSam Clegg 
1108cfd44a2eSSam Clegg   endSection(Section);
11096a31a0d6SSam Clegg 
11106a31a0d6SSam Clegg   // Apply fixups.
11114d57fbd0SSam Clegg   auto &Relocations = CustomSectionsRelocations[CustomSection.Section];
11127ee758d6SSam Clegg   applyRelocations(Relocations, CustomSection.OutputContentsOffset, Layout);
11136a31a0d6SSam Clegg }
11146a31a0d6SSam Clegg 
11155e3d33a7SSam Clegg uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm &Symbol) {
11165e3d33a7SSam Clegg   assert(Symbol.isFunction());
11175e3d33a7SSam Clegg   assert(TypeIndices.count(&Symbol));
11185e3d33a7SSam Clegg   return TypeIndices[&Symbol];
11195e3d33a7SSam Clegg }
11205e3d33a7SSam Clegg 
1121da419bdbSHeejin Ahn uint32_t WasmObjectWriter::getEventType(const MCSymbolWasm &Symbol) {
1122da419bdbSHeejin Ahn   assert(Symbol.isEvent());
1123da419bdbSHeejin Ahn   assert(TypeIndices.count(&Symbol));
1124da419bdbSHeejin Ahn   return TypeIndices[&Symbol];
1125da419bdbSHeejin Ahn }
1126da419bdbSHeejin Ahn 
112738b12f5eSHeejin Ahn void WasmObjectWriter::registerFunctionType(const MCSymbolWasm &Symbol) {
11285e3d33a7SSam Clegg   assert(Symbol.isFunction());
11295e3d33a7SSam Clegg 
11304c41fb5aSHeejin Ahn   wasm::WasmSignature S;
11317ee758d6SSam Clegg 
11327ee758d6SSam Clegg   if (auto *Sig = Symbol.getSignature()) {
1133da419bdbSHeejin Ahn     S.Returns = Sig->Returns;
1134da419bdbSHeejin Ahn     S.Params = Sig->Params;
113577a7a380SDerek Schuff   }
11365e3d33a7SSam Clegg 
1137da419bdbSHeejin Ahn   auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
11385e3d33a7SSam Clegg   if (Pair.second)
1139da419bdbSHeejin Ahn     Signatures.push_back(S);
11405e3d33a7SSam Clegg   TypeIndices[&Symbol] = Pair.first->second;
11415e3d33a7SSam Clegg 
1142d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "registerFunctionType: " << Symbol
1143d34e60caSNicola Zaghen                     << " new:" << Pair.second << "\n");
1144d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
11455e3d33a7SSam Clegg }
11465e3d33a7SSam Clegg 
114738b12f5eSHeejin Ahn void WasmObjectWriter::registerEventType(const MCSymbolWasm &Symbol) {
1148da419bdbSHeejin Ahn   assert(Symbol.isEvent());
1149da419bdbSHeejin Ahn 
1150da419bdbSHeejin Ahn   // TODO Currently we don't generate imported exceptions, but if we do, we
1151da419bdbSHeejin Ahn   // should have a way of infering types of imported exceptions.
11524c41fb5aSHeejin Ahn   wasm::WasmSignature S;
1153da419bdbSHeejin Ahn   if (auto *Sig = Symbol.getSignature()) {
1154da419bdbSHeejin Ahn     S.Returns = Sig->Returns;
1155da419bdbSHeejin Ahn     S.Params = Sig->Params;
1156da419bdbSHeejin Ahn   }
1157da419bdbSHeejin Ahn 
1158da419bdbSHeejin Ahn   auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
1159da419bdbSHeejin Ahn   if (Pair.second)
1160da419bdbSHeejin Ahn     Signatures.push_back(S);
1161da419bdbSHeejin Ahn   TypeIndices[&Symbol] = Pair.first->second;
1162da419bdbSHeejin Ahn 
1163da419bdbSHeejin Ahn   LLVM_DEBUG(dbgs() << "registerEventType: " << Symbol << " new:" << Pair.second
1164da419bdbSHeejin Ahn                     << "\n");
1165da419bdbSHeejin Ahn   LLVM_DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
1166da419bdbSHeejin Ahn }
1167da419bdbSHeejin Ahn 
11684d57fbd0SSam Clegg static bool isInSymtab(const MCSymbolWasm &Sym) {
11693ea1c62cSSam Clegg   if (Sym.isUsedInReloc() || Sym.isUsedInInitArray())
11704d57fbd0SSam Clegg     return true;
11714d57fbd0SSam Clegg 
11724d57fbd0SSam Clegg   if (Sym.isComdat() && !Sym.isDefined())
11734d57fbd0SSam Clegg     return false;
11744d57fbd0SSam Clegg 
11753ea1c62cSSam Clegg   if (Sym.isTemporary())
11764d57fbd0SSam Clegg     return false;
11774d57fbd0SSam Clegg 
11784d57fbd0SSam Clegg   if (Sym.isSection())
11794d57fbd0SSam Clegg     return false;
11804d57fbd0SSam Clegg 
11814d57fbd0SSam Clegg   return true;
11824d57fbd0SSam Clegg }
11830ff28fa6SDerek Schuff void WasmObjectWriter::prepareImports(
11840ff28fa6SDerek Schuff     SmallVectorImpl<wasm::WasmImport> &Imports, MCAssembler &Asm,
118518eafb6cSDan Gohman     const MCAsmLayout &Layout) {
1186f950b24aSSam Clegg   // For now, always emit the memory import, since loads and stores are not
1187f950b24aSSam Clegg   // valid without it. In the future, we could perhaps be more clever and omit
1188f950b24aSSam Clegg   // it if there are no loads or stores.
11898defa952SSam Clegg   wasm::WasmImport MemImport;
11901ed3a046SSam Clegg   MemImport.Module = "env";
11911ed3a046SSam Clegg   MemImport.Field = "__linear_memory";
1192f950b24aSSam Clegg   MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
1193fd0964aeSWouter van Oortmerssen   MemImport.Memory.Flags = is64Bit() ? wasm::WASM_LIMITS_FLAG_IS_64
1194fd0964aeSWouter van Oortmerssen                                      : wasm::WASM_LIMITS_FLAG_NONE;
1195f950b24aSSam Clegg   Imports.push_back(MemImport);
1196f950b24aSSam Clegg 
1197f950b24aSSam Clegg   // For now, always emit the table section, since indirect calls are not
1198f950b24aSSam Clegg   // valid without it. In the future, we could perhaps be more clever and omit
1199f950b24aSSam Clegg   // it if there are no indirect calls.
12008defa952SSam Clegg   wasm::WasmImport TableImport;
12011ed3a046SSam Clegg   TableImport.Module = "env";
12021ed3a046SSam Clegg   TableImport.Field = "__indirect_function_table";
1203f950b24aSSam Clegg   TableImport.Kind = wasm::WASM_EXTERNAL_TABLE;
12046a87ddacSThomas Lively   TableImport.Table.ElemType = wasm::WASM_TYPE_FUNCREF;
1205f950b24aSSam Clegg   Imports.push_back(TableImport);
1206f950b24aSSam Clegg 
1207da419bdbSHeejin Ahn   // Populate SignatureIndices, and Imports and WasmIndices for undefined
1208586320c0SNicholas Wilson   // symbols.  This must be done before populating WasmIndices for defined
1209586320c0SNicholas Wilson   // symbols.
121032ce5ca0SDan Gohman   for (const MCSymbol &S : Asm.symbols()) {
121132ce5ca0SDan Gohman     const auto &WS = static_cast<const MCSymbolWasm &>(S);
121232ce5ca0SDan Gohman 
121332ce5ca0SDan Gohman     // Register types for all functions, including those with private linkage
12149f3fe42eSSam Clegg     // (because wasm always needs a type signature).
12157ee758d6SSam Clegg     if (WS.isFunction()) {
12169c7b5808SDominic Chen       const auto *BS = Layout.getBaseSymbol(S);
12179c7b5808SDominic Chen       if (!BS)
12189c7b5808SDominic Chen         report_fatal_error(Twine(S.getName()) +
12199c7b5808SDominic Chen                            ": absolute addressing not supported!");
12209c7b5808SDominic Chen       registerFunctionType(*cast<MCSymbolWasm>(BS));
12217ee758d6SSam Clegg     }
122232ce5ca0SDan Gohman 
1223da419bdbSHeejin Ahn     if (WS.isEvent())
1224da419bdbSHeejin Ahn       registerEventType(WS);
1225da419bdbSHeejin Ahn 
122632ce5ca0SDan Gohman     if (WS.isTemporary())
122732ce5ca0SDan Gohman       continue;
122832ce5ca0SDan Gohman 
122932ce5ca0SDan Gohman     // If the symbol is not defined in this translation unit, import it.
12306c899ba6SSam Clegg     if (!WS.isDefined() && !WS.isComdat()) {
12316c899ba6SSam Clegg       if (WS.isFunction()) {
12328defa952SSam Clegg         wasm::WasmImport Import;
1233f726e445SDan Gohman         Import.Module = WS.getImportModule();
1234f726e445SDan Gohman         Import.Field = WS.getImportName();
123532ce5ca0SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
12368defa952SSam Clegg         Import.SigIndex = getFunctionType(WS);
12376c899ba6SSam Clegg         Imports.push_back(Import);
1238492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
12396c899ba6SSam Clegg         WasmIndices[&WS] = NumFunctionImports++;
12406c899ba6SSam Clegg       } else if (WS.isGlobal()) {
124115f349f7SNicholas Wilson         if (WS.isWeak())
124215f349f7SNicholas Wilson           report_fatal_error("undefined global symbol cannot be weak");
124315f349f7SNicholas Wilson 
12446c899ba6SSam Clegg         wasm::WasmImport Import;
1245f726e445SDan Gohman         Import.Field = WS.getImportName();
124632ce5ca0SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1247492f7529SSam Clegg         Import.Module = WS.getImportModule();
12486c899ba6SSam Clegg         Import.Global = WS.getGlobalType();
12496c899ba6SSam Clegg         Imports.push_back(Import);
1250492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
12516c899ba6SSam Clegg         WasmIndices[&WS] = NumGlobalImports++;
1252da419bdbSHeejin Ahn       } else if (WS.isEvent()) {
1253da419bdbSHeejin Ahn         if (WS.isWeak())
1254da419bdbSHeejin Ahn           report_fatal_error("undefined event symbol cannot be weak");
1255da419bdbSHeejin Ahn 
1256da419bdbSHeejin Ahn         wasm::WasmImport Import;
1257f726e445SDan Gohman         Import.Module = WS.getImportModule();
1258f726e445SDan Gohman         Import.Field = WS.getImportName();
1259da419bdbSHeejin Ahn         Import.Kind = wasm::WASM_EXTERNAL_EVENT;
1260da419bdbSHeejin Ahn         Import.Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
1261da419bdbSHeejin Ahn         Import.Event.SigIndex = getEventType(WS);
1262da419bdbSHeejin Ahn         Imports.push_back(Import);
1263492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
1264da419bdbSHeejin Ahn         WasmIndices[&WS] = NumEventImports++;
126532ce5ca0SDan Gohman       }
126632ce5ca0SDan Gohman     }
126732ce5ca0SDan Gohman   }
126832ce5ca0SDan Gohman 
1269492f7529SSam Clegg   // Add imports for GOT globals
1270492f7529SSam Clegg   for (const MCSymbol &S : Asm.symbols()) {
1271492f7529SSam Clegg     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1272492f7529SSam Clegg     if (WS.isUsedInGOT()) {
1273492f7529SSam Clegg       wasm::WasmImport Import;
1274492f7529SSam Clegg       if (WS.isFunction())
1275492f7529SSam Clegg         Import.Module = "GOT.func";
1276492f7529SSam Clegg       else
1277492f7529SSam Clegg         Import.Module = "GOT.mem";
1278492f7529SSam Clegg       Import.Field = WS.getName();
1279492f7529SSam Clegg       Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1280492f7529SSam Clegg       Import.Global = {wasm::WASM_TYPE_I32, true};
1281492f7529SSam Clegg       Imports.push_back(Import);
1282492f7529SSam Clegg       assert(GOTIndices.count(&WS) == 0);
1283492f7529SSam Clegg       GOTIndices[&WS] = NumGlobalImports++;
1284492f7529SSam Clegg     }
1285492f7529SSam Clegg   }
12860ff28fa6SDerek Schuff }
1287492f7529SSam Clegg 
12880ff28fa6SDerek Schuff uint64_t WasmObjectWriter::writeObject(MCAssembler &Asm,
12890ff28fa6SDerek Schuff                                        const MCAsmLayout &Layout) {
12900ff28fa6SDerek Schuff   support::endian::Writer MainWriter(*OS, support::little);
12910ff28fa6SDerek Schuff   W = &MainWriter;
12920ff28fa6SDerek Schuff   if (IsSplitDwarf) {
12930ff28fa6SDerek Schuff     uint64_t TotalSize = writeOneObject(Asm, Layout, DwoMode::NonDwoOnly);
12940ff28fa6SDerek Schuff     assert(DwoOS);
12950ff28fa6SDerek Schuff     support::endian::Writer DwoWriter(*DwoOS, support::little);
12960ff28fa6SDerek Schuff     W = &DwoWriter;
12970ff28fa6SDerek Schuff     return TotalSize + writeOneObject(Asm, Layout, DwoMode::DwoOnly);
12980ff28fa6SDerek Schuff   } else {
12990ff28fa6SDerek Schuff     return writeOneObject(Asm, Layout, DwoMode::AllSections);
13000ff28fa6SDerek Schuff   }
13010ff28fa6SDerek Schuff }
13020ff28fa6SDerek Schuff 
13030ff28fa6SDerek Schuff uint64_t WasmObjectWriter::writeOneObject(MCAssembler &Asm,
13040ff28fa6SDerek Schuff                                           const MCAsmLayout &Layout,
13050ff28fa6SDerek Schuff                                           DwoMode Mode) {
13060ff28fa6SDerek Schuff   uint64_t StartOffset = W->OS.tell();
13070ff28fa6SDerek Schuff   SectionCount = 0;
13080ff28fa6SDerek Schuff   CustomSections.clear();
13090ff28fa6SDerek Schuff 
13100ff28fa6SDerek Schuff   LLVM_DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
13110ff28fa6SDerek Schuff 
13120ff28fa6SDerek Schuff   // Collect information from the available symbols.
13130ff28fa6SDerek Schuff   SmallVector<WasmFunction, 4> Functions;
13140ff28fa6SDerek Schuff   SmallVector<uint32_t, 4> TableElems;
13150ff28fa6SDerek Schuff   SmallVector<wasm::WasmImport, 4> Imports;
13160ff28fa6SDerek Schuff   SmallVector<wasm::WasmExport, 4> Exports;
13170ff28fa6SDerek Schuff   SmallVector<wasm::WasmEventType, 1> Events;
13180ff28fa6SDerek Schuff   SmallVector<wasm::WasmGlobal, 1> Globals;
1319*388fb67bSPaulo Matos   SmallVector<wasm::WasmTable, 1> Tables;
13200ff28fa6SDerek Schuff   SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos;
13210ff28fa6SDerek Schuff   SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
13220ff28fa6SDerek Schuff   std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
13230ff28fa6SDerek Schuff   uint64_t DataSize = 0;
13240ff28fa6SDerek Schuff   if (Mode != DwoMode::DwoOnly) {
13250ff28fa6SDerek Schuff     prepareImports(Imports, Asm, Layout);
13260ff28fa6SDerek Schuff   }
13274d57fbd0SSam Clegg   // Populate DataSegments and CustomSections, which must be done before
13284d57fbd0SSam Clegg   // populating DataLocations.
1329759631c7SSam Clegg   for (MCSection &Sec : Asm) {
1330759631c7SSam Clegg     auto &Section = static_cast<MCSectionWasm &>(Sec);
13317d1ff446SFangrui Song     StringRef SectionName = Section.getName();
1332759631c7SSam Clegg 
13330ff28fa6SDerek Schuff     if (Mode == DwoMode::NonDwoOnly && isDwoSection(Sec))
13340ff28fa6SDerek Schuff       continue;
13350ff28fa6SDerek Schuff     if (Mode == DwoMode::DwoOnly && !isDwoSection(Sec))
13360ff28fa6SDerek Schuff       continue;
13370ff28fa6SDerek Schuff 
1338bafe6902SSam Clegg     // .init_array sections are handled specially elsewhere.
13394d57fbd0SSam Clegg     if (SectionName.startswith(".init_array"))
1340bafe6902SSam Clegg       continue;
1341bafe6902SSam Clegg 
13424d57fbd0SSam Clegg     // Code is handled separately
13434d57fbd0SSam Clegg     if (Section.getKind().isText())
13444d57fbd0SSam Clegg       continue;
13454d57fbd0SSam Clegg 
13464d57fbd0SSam Clegg     if (Section.isWasmData()) {
1347329e76d5SSam Clegg       uint32_t SegmentIndex = DataSegments.size();
1348759631c7SSam Clegg       DataSize = alignTo(DataSize, Section.getAlignment());
1349759631c7SSam Clegg       DataSegments.emplace_back();
1350759631c7SSam Clegg       WasmDataSegment &Segment = DataSegments.back();
13514d57fbd0SSam Clegg       Segment.Name = SectionName;
13529b49f36aSSimon Pilgrim       Segment.InitFlags =
13539b49f36aSSimon Pilgrim           Section.getPassive() ? (uint32_t)wasm::WASM_SEGMENT_IS_PASSIVE : 0;
1354759631c7SSam Clegg       Segment.Offset = DataSize;
1355759631c7SSam Clegg       Segment.Section = &Section;
135663ebb813SSam Clegg       addData(Segment.Data, Section);
135756c587adSSam Clegg       Segment.Alignment = Log2_32(Section.getAlignment());
13582e150409SThomas Lively       Segment.LinkerFlags = 0;
1359759631c7SSam Clegg       DataSize += Segment.Data.size();
13606c899ba6SSam Clegg       Section.setSegmentIndex(SegmentIndex);
1361ea7caceeSSam Clegg 
1362ea7caceeSSam Clegg       if (const MCSymbolWasm *C = Section.getGroup()) {
1363ea7caceeSSam Clegg         Comdats[C->getName()].emplace_back(
1364329e76d5SSam Clegg             WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
1365ea7caceeSSam Clegg       }
13664d57fbd0SSam Clegg     } else {
13674d57fbd0SSam Clegg       // Create custom sections
13684d57fbd0SSam Clegg       assert(Sec.getKind().isMetadata());
13694d57fbd0SSam Clegg 
13704d57fbd0SSam Clegg       StringRef Name = SectionName;
13714d57fbd0SSam Clegg 
13724d57fbd0SSam Clegg       // For user-defined custom sections, strip the prefix
13734d57fbd0SSam Clegg       if (Name.startswith(".custom_section."))
13744d57fbd0SSam Clegg         Name = Name.substr(strlen(".custom_section."));
13754d57fbd0SSam Clegg 
13764d57fbd0SSam Clegg       MCSymbol *Begin = Sec.getBeginSymbol();
1377fb807d4dSSam Clegg       if (Begin) {
13784d57fbd0SSam Clegg         WasmIndices[cast<MCSymbolWasm>(Begin)] = CustomSections.size();
1379b210c64bSSam Clegg         if (SectionName != Begin->getName())
1380fb807d4dSSam Clegg           report_fatal_error("section name and begin symbol should match: " +
1381b210c64bSSam Clegg                              Twine(SectionName));
1382fb807d4dSSam Clegg       }
1383cbda16ebSThomas Lively 
1384f6f4f843SThomas Lively       // Separate out the producers and target features sections
1385cbda16ebSThomas Lively       if (Name == "producers") {
13860eaee545SJonas Devlieghere         ProducersSection = std::make_unique<WasmCustomSection>(Name, &Section);
1387cbda16ebSThomas Lively         continue;
1388cbda16ebSThomas Lively       }
1389f6f4f843SThomas Lively       if (Name == "target_features") {
1390f6f4f843SThomas Lively         TargetFeaturesSection =
13910eaee545SJonas Devlieghere             std::make_unique<WasmCustomSection>(Name, &Section);
1392f6f4f843SThomas Lively         continue;
1393f6f4f843SThomas Lively       }
1394cbda16ebSThomas Lively 
13954d57fbd0SSam Clegg       CustomSections.emplace_back(Name, &Section);
1396759631c7SSam Clegg     }
13976a31a0d6SSam Clegg   }
13986a31a0d6SSam Clegg 
1399586320c0SNicholas Wilson   // Populate WasmIndices and DataLocations for defined symbols.
1400d934cb88SDan Gohman   for (const MCSymbol &S : Asm.symbols()) {
1401d934cb88SDan Gohman     // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1402d934cb88SDan Gohman     // or used in relocations.
1403d934cb88SDan Gohman     if (S.isTemporary() && S.getName().empty())
1404d934cb88SDan Gohman       continue;
1405b7787fd0SSam Clegg 
1406d934cb88SDan Gohman     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1407d34e60caSNicola Zaghen     LLVM_DEBUG(
1408d34e60caSNicola Zaghen         dbgs() << "MCSymbol: " << toString(WS.getType()) << " '" << S << "'"
1409d34e60caSNicola Zaghen                << " isDefined=" << S.isDefined() << " isExternal="
1410d34e60caSNicola Zaghen                << S.isExternal() << " isTemporary=" << S.isTemporary()
1411d34e60caSNicola Zaghen                << " isWeak=" << WS.isWeak() << " isHidden=" << WS.isHidden()
1412b7787fd0SSam Clegg                << " isVariable=" << WS.isVariable() << "\n");
1413b7787fd0SSam Clegg 
14145e3d33a7SSam Clegg     if (WS.isVariable())
14155e3d33a7SSam Clegg       continue;
14166c899ba6SSam Clegg     if (WS.isComdat() && !WS.isDefined())
14176c899ba6SSam Clegg       continue;
1418b7787fd0SSam Clegg 
1419d934cb88SDan Gohman     if (WS.isFunction()) {
14206c899ba6SSam Clegg       unsigned Index;
1421cd65f698SSam Clegg       if (WS.isDefined()) {
1422b7787fd0SSam Clegg         if (WS.getOffset() != 0)
1423b7787fd0SSam Clegg           report_fatal_error(
1424b7787fd0SSam Clegg               "function sections must contain one function each");
1425b7787fd0SSam Clegg 
142618c56a07SHeejin Ahn         if (WS.getSize() == nullptr)
1427b7787fd0SSam Clegg           report_fatal_error(
1428b7787fd0SSam Clegg               "function symbols must have a size set with .size");
1429b7787fd0SSam Clegg 
14306c899ba6SSam Clegg         // A definition. Write out the function body.
14319f3fe42eSSam Clegg         Index = NumFunctionImports + Functions.size();
1432d934cb88SDan Gohman         WasmFunction Func;
1433da419bdbSHeejin Ahn         Func.SigIndex = getFunctionType(WS);
1434d934cb88SDan Gohman         Func.Sym = &WS;
14356c899ba6SSam Clegg         WasmIndices[&WS] = Index;
1436d934cb88SDan Gohman         Functions.push_back(Func);
14376c899ba6SSam Clegg 
14386c899ba6SSam Clegg         auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
14396c899ba6SSam Clegg         if (const MCSymbolWasm *C = Section.getGroup()) {
14406c899ba6SSam Clegg           Comdats[C->getName()].emplace_back(
14416c899ba6SSam Clegg               WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
14426c899ba6SSam Clegg         }
1443881d8778SSam Clegg 
1444881d8778SSam Clegg         if (WS.hasExportName()) {
1445881d8778SSam Clegg           wasm::WasmExport Export;
1446881d8778SSam Clegg           Export.Name = WS.getExportName();
1447881d8778SSam Clegg           Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1448881d8778SSam Clegg           Export.Index = Index;
1449881d8778SSam Clegg           Exports.push_back(Export);
1450881d8778SSam Clegg         }
1451d934cb88SDan Gohman       } else {
1452d934cb88SDan Gohman         // An import; the index was assigned above.
14536c899ba6SSam Clegg         Index = WasmIndices.find(&WS)->second;
1454d934cb88SDan Gohman       }
1455d934cb88SDan Gohman 
1456d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> function index: " << Index << "\n");
1457da419bdbSHeejin Ahn 
14586c899ba6SSam Clegg     } else if (WS.isData()) {
1459f3feb6adSWouter van Oortmerssen       if (!isInSymtab(WS))
1460c38e947eSSam Clegg         continue;
1461c38e947eSSam Clegg 
14626c899ba6SSam Clegg       if (!WS.isDefined()) {
1463d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "  -> segment index: -1"
1464d34e60caSNicola Zaghen                           << "\n");
1465fe6414b0SSam Clegg         continue;
14666c899ba6SSam Clegg       }
1467fe6414b0SSam Clegg 
1468d934cb88SDan Gohman       if (!WS.getSize())
1469c38e947eSSam Clegg         report_fatal_error("data symbols must have a size set with .size: " +
1470c38e947eSSam Clegg                            WS.getName());
1471d934cb88SDan Gohman 
1472d934cb88SDan Gohman       int64_t Size = 0;
1473d934cb88SDan Gohman       if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1474d934cb88SDan Gohman         report_fatal_error(".size expression must be evaluatable");
1475d934cb88SDan Gohman 
1476759631c7SSam Clegg       auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
1477079cba04SSam Clegg       if (!DataSection.isWasmData())
1478079cba04SSam Clegg         report_fatal_error("data symbols must live in a data section: " +
1479079cba04SSam Clegg                            WS.getName());
14807c395943SSam Clegg 
14816c899ba6SSam Clegg       // For each data symbol, export it in the symtab as a reference to the
14826c899ba6SSam Clegg       // corresponding Wasm data segment.
14836c899ba6SSam Clegg       wasm::WasmDataReference Ref = wasm::WasmDataReference{
14843b29376eSWouter van Oortmerssen           DataSection.getSegmentIndex(), Layout.getSymbolOffset(WS),
14853b29376eSWouter van Oortmerssen           static_cast<uint64_t>(Size)};
14866c899ba6SSam Clegg       DataLocations[&WS] = Ref;
1487d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> segment index: " << Ref.Segment << "\n");
1488da419bdbSHeejin Ahn 
1489a165f2d6SSam Clegg     } else if (WS.isGlobal()) {
14906c899ba6SSam Clegg       // A "true" Wasm global (currently just __stack_pointer)
14910a6c4d8dSSam Clegg       if (WS.isDefined()) {
14920a6c4d8dSSam Clegg         assert(WasmIndices.count(&WS) == 0);
14930a6c4d8dSSam Clegg         wasm::WasmGlobal Global;
14940a6c4d8dSSam Clegg         Global.Type = WS.getGlobalType();
14950a6c4d8dSSam Clegg         Global.Index = NumGlobalImports + Globals.size();
14960a6c4d8dSSam Clegg         switch (Global.Type.Type) {
14970a6c4d8dSSam Clegg         case wasm::WASM_TYPE_I32:
14980a6c4d8dSSam Clegg           Global.InitExpr.Opcode = wasm::WASM_OPCODE_I32_CONST;
14990a6c4d8dSSam Clegg           break;
15000a6c4d8dSSam Clegg         case wasm::WASM_TYPE_I64:
15010a6c4d8dSSam Clegg           Global.InitExpr.Opcode = wasm::WASM_OPCODE_I64_CONST;
15020a6c4d8dSSam Clegg           break;
15030a6c4d8dSSam Clegg         case wasm::WASM_TYPE_F32:
15040a6c4d8dSSam Clegg           Global.InitExpr.Opcode = wasm::WASM_OPCODE_F32_CONST;
15050a6c4d8dSSam Clegg           break;
15060a6c4d8dSSam Clegg         case wasm::WASM_TYPE_F64:
15070a6c4d8dSSam Clegg           Global.InitExpr.Opcode = wasm::WASM_OPCODE_F64_CONST;
15080a6c4d8dSSam Clegg           break;
150979aad89dSSam Clegg         case wasm::WASM_TYPE_EXTERNREF:
151079aad89dSSam Clegg           Global.InitExpr.Opcode = wasm::WASM_OPCODE_REF_NULL;
151179aad89dSSam Clegg           break;
15120a6c4d8dSSam Clegg         default:
15130a6c4d8dSSam Clegg           llvm_unreachable("unexpected type");
15140a6c4d8dSSam Clegg         }
15150a6c4d8dSSam Clegg         WasmIndices[&WS] = Global.Index;
15160a6c4d8dSSam Clegg         Globals.push_back(Global);
15170a6c4d8dSSam Clegg       } else {
1518545932beSEric Christopher         // An import; the index was assigned above
1519d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "  -> global index: "
1520d34e60caSNicola Zaghen                           << WasmIndices.find(&WS)->second << "\n");
15210a6c4d8dSSam Clegg       }
1522*388fb67bSPaulo Matos     } else if (WS.isTable()) {
1523*388fb67bSPaulo Matos       if (WS.isDefined()) {
1524*388fb67bSPaulo Matos         assert(WasmIndices.count(&WS) == 0);
1525*388fb67bSPaulo Matos         wasm::WasmTable Table;
1526*388fb67bSPaulo Matos         Table.ElemType = static_cast<uint8_t>(WS.getTableType());
1527*388fb67bSPaulo Matos         Table.Index = NumTableImports + Tables.size();
1528*388fb67bSPaulo Matos         // FIXME: Work on custom limits is ongoing
1529*388fb67bSPaulo Matos         Table.Limits = {wasm::WASM_LIMITS_FLAG_NONE, 0, 0};
1530*388fb67bSPaulo Matos 
1531*388fb67bSPaulo Matos         WasmIndices[&WS] = Table.Index;
1532*388fb67bSPaulo Matos         Tables.push_back(Table);
1533*388fb67bSPaulo Matos       }
1534*388fb67bSPaulo Matos       LLVM_DEBUG(dbgs() << " -> table index: " << WasmIndices.find(&WS)->second
1535*388fb67bSPaulo Matos                         << "\n");
1536da419bdbSHeejin Ahn     } else if (WS.isEvent()) {
1537da419bdbSHeejin Ahn       // C++ exception symbol (__cpp_exception)
1538da419bdbSHeejin Ahn       unsigned Index;
1539da419bdbSHeejin Ahn       if (WS.isDefined()) {
15400a6c4d8dSSam Clegg         assert(WasmIndices.count(&WS) == 0);
1541da419bdbSHeejin Ahn         Index = NumEventImports + Events.size();
1542da419bdbSHeejin Ahn         wasm::WasmEventType Event;
1543da419bdbSHeejin Ahn         Event.SigIndex = getEventType(WS);
1544da419bdbSHeejin Ahn         Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
1545da419bdbSHeejin Ahn         WasmIndices[&WS] = Index;
1546da419bdbSHeejin Ahn         Events.push_back(Event);
1547da419bdbSHeejin Ahn       } else {
1548da419bdbSHeejin Ahn         // An import; the index was assigned above.
1549492f7529SSam Clegg         assert(WasmIndices.count(&WS) > 0);
1550da419bdbSHeejin Ahn       }
1551da419bdbSHeejin Ahn       LLVM_DEBUG(dbgs() << "  -> event index: " << WasmIndices.find(&WS)->second
1552da419bdbSHeejin Ahn                         << "\n");
1553da419bdbSHeejin Ahn 
1554a165f2d6SSam Clegg     } else {
1555a165f2d6SSam Clegg       assert(WS.isSection());
1556d934cb88SDan Gohman     }
1557d934cb88SDan Gohman   }
1558d934cb88SDan Gohman 
1559586320c0SNicholas Wilson   // Populate WasmIndices and DataLocations for aliased symbols.  We need to
1560586320c0SNicholas Wilson   // process these in a separate pass because we need to have processed the
1561586320c0SNicholas Wilson   // target of the alias before the alias itself and the symbols are not
1562586320c0SNicholas Wilson   // necessarily ordered in this way.
1563b7787fd0SSam Clegg   for (const MCSymbol &S : Asm.symbols()) {
1564b7787fd0SSam Clegg     if (!S.isVariable())
1565b7787fd0SSam Clegg       continue;
156631a2c809SSam Clegg 
1567cd65f698SSam Clegg     assert(S.isDefined());
1568b7787fd0SSam Clegg 
15699c7b5808SDominic Chen     const auto *BS = Layout.getBaseSymbol(S);
15709c7b5808SDominic Chen     if (!BS)
15719c7b5808SDominic Chen       report_fatal_error(Twine(S.getName()) +
15729c7b5808SDominic Chen                          ": absolute addressing not supported!");
15739c7b5808SDominic Chen     const MCSymbolWasm *Base = cast<MCSymbolWasm>(BS);
15747ee758d6SSam Clegg 
15755e3d33a7SSam Clegg     // Find the target symbol of this weak alias and export that index
1576aff1c4dfSSam Clegg     const auto &WS = static_cast<const MCSymbolWasm &>(S);
15777ee758d6SSam Clegg     LLVM_DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *Base << "'\n");
1578b7787fd0SSam Clegg 
15797ee758d6SSam Clegg     if (Base->isFunction()) {
15807ee758d6SSam Clegg       assert(WasmIndices.count(Base) > 0);
15817ee758d6SSam Clegg       uint32_t WasmIndex = WasmIndices.find(Base)->second;
1582492f7529SSam Clegg       assert(WasmIndices.count(&WS) == 0);
15836c899ba6SSam Clegg       WasmIndices[&WS] = WasmIndex;
1584d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> index:" << WasmIndex << "\n");
15857ee758d6SSam Clegg     } else if (Base->isData()) {
15867ee758d6SSam Clegg       auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
15877ee758d6SSam Clegg       uint64_t Offset = Layout.getSymbolOffset(S);
15887ee758d6SSam Clegg       int64_t Size = 0;
15897ee758d6SSam Clegg       // For data symbol alias we use the size of the base symbol as the
15907ee758d6SSam Clegg       // size of the alias.  When an offset from the base is involved this
15917ee758d6SSam Clegg       // can result in a offset + size goes past the end of the data section
15927ee758d6SSam Clegg       // which out object format doesn't support.  So we must clamp it.
15937ee758d6SSam Clegg       if (!Base->getSize()->evaluateAsAbsolute(Size, Layout))
15947ee758d6SSam Clegg         report_fatal_error(".size expression must be evaluatable");
15957ee758d6SSam Clegg       const WasmDataSegment &Segment =
15967ee758d6SSam Clegg           DataSegments[DataSection.getSegmentIndex()];
15977ee758d6SSam Clegg       Size =
15987ee758d6SSam Clegg           std::min(static_cast<uint64_t>(Size), Segment.Data.size() - Offset);
15997ee758d6SSam Clegg       wasm::WasmDataReference Ref = wasm::WasmDataReference{
16007ee758d6SSam Clegg           DataSection.getSegmentIndex(),
16017ee758d6SSam Clegg           static_cast<uint32_t>(Layout.getSymbolOffset(S)),
16027ee758d6SSam Clegg           static_cast<uint32_t>(Size)};
16036c899ba6SSam Clegg       DataLocations[&WS] = Ref;
1604d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> index:" << Ref.Segment << "\n");
16056c899ba6SSam Clegg     } else {
1606da419bdbSHeejin Ahn       report_fatal_error("don't yet support global/event aliases");
16076c899ba6SSam Clegg     }
1608586320c0SNicholas Wilson   }
160931a2c809SSam Clegg 
1610586320c0SNicholas Wilson   // Finally, populate the symbol table itself, in its "natural" order.
1611586320c0SNicholas Wilson   for (const MCSymbol &S : Asm.symbols()) {
1612586320c0SNicholas Wilson     const auto &WS = static_cast<const MCSymbolWasm &>(S);
161325d8e68bSSam Clegg     if (!isInSymtab(WS)) {
161418c56a07SHeejin Ahn       WS.setIndex(InvalidIndex);
1615586320c0SNicholas Wilson       continue;
161625d8e68bSSam Clegg     }
1617d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "adding to symtab: " << WS << "\n");
1618586320c0SNicholas Wilson 
1619586320c0SNicholas Wilson     uint32_t Flags = 0;
1620586320c0SNicholas Wilson     if (WS.isWeak())
1621586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_BINDING_WEAK;
1622586320c0SNicholas Wilson     if (WS.isHidden())
1623586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN;
1624586320c0SNicholas Wilson     if (!WS.isExternal() && WS.isDefined())
1625586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;
1626586320c0SNicholas Wilson     if (WS.isUndefined())
1627586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_UNDEFINED;
1628da84b688SDan Gohman     if (WS.isNoStrip()) {
1629da84b688SDan Gohman       Flags |= wasm::WASM_SYMBOL_NO_STRIP;
1630da84b688SDan Gohman       if (isEmscripten()) {
1631d6ef8da3SSam Clegg         Flags |= wasm::WASM_SYMBOL_EXPORTED;
1632da84b688SDan Gohman       }
1633da84b688SDan Gohman     }
1634b4f4e370SSam Clegg     if (WS.hasImportName())
163529874ceaSDan Gohman       Flags |= wasm::WASM_SYMBOL_EXPLICIT_NAME;
1636881d8778SSam Clegg     if (WS.hasExportName())
1637881d8778SSam Clegg       Flags |= wasm::WASM_SYMBOL_EXPORTED;
1638586320c0SNicholas Wilson 
1639586320c0SNicholas Wilson     wasm::WasmSymbolInfo Info;
1640586320c0SNicholas Wilson     Info.Name = WS.getName();
1641586320c0SNicholas Wilson     Info.Kind = WS.getType();
1642586320c0SNicholas Wilson     Info.Flags = Flags;
16434d57fbd0SSam Clegg     if (!WS.isData()) {
16444d57fbd0SSam Clegg       assert(WasmIndices.count(&WS) > 0);
1645586320c0SNicholas Wilson       Info.ElementIndex = WasmIndices.find(&WS)->second;
16464d57fbd0SSam Clegg     } else if (WS.isDefined()) {
16474d57fbd0SSam Clegg       assert(DataLocations.count(&WS) > 0);
1648586320c0SNicholas Wilson       Info.DataRef = DataLocations.find(&WS)->second;
16494d57fbd0SSam Clegg     }
165025d8e68bSSam Clegg     WS.setIndex(SymbolInfos.size());
1651586320c0SNicholas Wilson     SymbolInfos.emplace_back(Info);
1652b7787fd0SSam Clegg   }
1653b7787fd0SSam Clegg 
16546006e091SSam Clegg   {
16556006e091SSam Clegg     auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
1656f9edbe95SSam Clegg       // Functions referenced by a relocation need to put in the table.  This is
1657f9edbe95SSam Clegg       // purely to make the object file's provisional values readable, and is
1658f9edbe95SSam Clegg       // ignored by the linker, which re-calculates the relocations itself.
1659d1152a26SSam Clegg       if (Rel.Type != wasm::R_WASM_TABLE_INDEX_I32 &&
1660cc1b9b68SWouter van Oortmerssen           Rel.Type != wasm::R_WASM_TABLE_INDEX_I64 &&
166181443ac1SSam Clegg           Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB &&
1662cc1b9b68SWouter van Oortmerssen           Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB64 &&
166381443ac1SSam Clegg           Rel.Type != wasm::R_WASM_TABLE_INDEX_REL_SLEB)
1664f9edbe95SSam Clegg         return;
1665f9edbe95SSam Clegg       assert(Rel.Symbol->isFunction());
16667ee758d6SSam Clegg       const MCSymbolWasm *Base =
16677ee758d6SSam Clegg           cast<MCSymbolWasm>(Layout.getBaseSymbol(*Rel.Symbol));
16687ee758d6SSam Clegg       uint32_t FunctionIndex = WasmIndices.find(Base)->second;
166918c56a07SHeejin Ahn       uint32_t TableIndex = TableElems.size() + InitialTableOffset;
16707ee758d6SSam Clegg       if (TableIndices.try_emplace(Base, TableIndex).second) {
16717ee758d6SSam Clegg         LLVM_DEBUG(dbgs() << "  -> adding " << Base->getName()
1672f9edbe95SSam Clegg                           << " to table: " << TableIndex << "\n");
16736c899ba6SSam Clegg         TableElems.push_back(FunctionIndex);
16747ee758d6SSam Clegg         registerFunctionType(*Base);
16756006e091SSam Clegg       }
16766006e091SSam Clegg     };
1677970d02c4SDan Gohman 
16786006e091SSam Clegg     for (const WasmRelocationEntry &RelEntry : CodeRelocations)
16796006e091SSam Clegg       HandleReloc(RelEntry);
16806006e091SSam Clegg     for (const WasmRelocationEntry &RelEntry : DataRelocations)
16816006e091SSam Clegg       HandleReloc(RelEntry);
1682d934cb88SDan Gohman   }
1683d934cb88SDan Gohman 
1684bafe6902SSam Clegg   // Translate .init_array section contents into start functions.
1685bafe6902SSam Clegg   for (const MCSection &S : Asm) {
1686bafe6902SSam Clegg     const auto &WS = static_cast<const MCSectionWasm &>(S);
16877d1ff446SFangrui Song     if (WS.getName().startswith(".fini_array"))
1688bafe6902SSam Clegg       report_fatal_error(".fini_array sections are unsupported");
16897d1ff446SFangrui Song     if (!WS.getName().startswith(".init_array"))
1690bafe6902SSam Clegg       continue;
1691bafe6902SSam Clegg     if (WS.getFragmentList().empty())
1692bafe6902SSam Clegg       continue;
1693b210c64bSSam Clegg 
1694b210c64bSSam Clegg     // init_array is expected to contain a single non-empty data fragment
1695b210c64bSSam Clegg     if (WS.getFragmentList().size() != 3)
1696bafe6902SSam Clegg       report_fatal_error("only one .init_array section fragment supported");
1697b210c64bSSam Clegg 
1698b210c64bSSam Clegg     auto IT = WS.begin();
1699b210c64bSSam Clegg     const MCFragment &EmptyFrag = *IT;
1700b210c64bSSam Clegg     if (EmptyFrag.getKind() != MCFragment::FT_Data)
1701b210c64bSSam Clegg       report_fatal_error(".init_array section should be aligned");
1702b210c64bSSam Clegg 
1703b210c64bSSam Clegg     IT = std::next(IT);
1704b210c64bSSam Clegg     const MCFragment &AlignFrag = *IT;
1705bafe6902SSam Clegg     if (AlignFrag.getKind() != MCFragment::FT_Align)
1706bafe6902SSam Clegg       report_fatal_error(".init_array section should be aligned");
1707bafe6902SSam Clegg     if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
1708bafe6902SSam Clegg       report_fatal_error(".init_array section should be aligned for pointers");
1709b210c64bSSam Clegg 
1710b210c64bSSam Clegg     const MCFragment &Frag = *std::next(IT);
1711bafe6902SSam Clegg     if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1712bafe6902SSam Clegg       report_fatal_error("only data supported in .init_array section");
1713b210c64bSSam Clegg 
1714bafe6902SSam Clegg     uint16_t Priority = UINT16_MAX;
17154d57fbd0SSam Clegg     unsigned PrefixLength = strlen(".init_array");
17167d1ff446SFangrui Song     if (WS.getName().size() > PrefixLength) {
17177d1ff446SFangrui Song       if (WS.getName()[PrefixLength] != '.')
1718f208f631SHeejin Ahn         report_fatal_error(
1719f208f631SHeejin Ahn             ".init_array section priority should start with '.'");
17207d1ff446SFangrui Song       if (WS.getName().substr(PrefixLength + 1).getAsInteger(10, Priority))
1721bafe6902SSam Clegg         report_fatal_error("invalid .init_array section priority");
1722bafe6902SSam Clegg     }
1723bafe6902SSam Clegg     const auto &DataFrag = cast<MCDataFragment>(Frag);
1724bafe6902SSam Clegg     const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1725f208f631SHeejin Ahn     for (const uint8_t *
172618c56a07SHeejin Ahn              P = (const uint8_t *)Contents.data(),
172718c56a07SHeejin Ahn             *End = (const uint8_t *)Contents.data() + Contents.size();
172818c56a07SHeejin Ahn          P != End; ++P) {
172918c56a07SHeejin Ahn       if (*P != 0)
1730bafe6902SSam Clegg         report_fatal_error("non-symbolic data in .init_array section");
1731bafe6902SSam Clegg     }
1732bafe6902SSam Clegg     for (const MCFixup &Fixup : DataFrag.getFixups()) {
1733f208f631SHeejin Ahn       assert(Fixup.getKind() ==
1734f208f631SHeejin Ahn              MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
1735bafe6902SSam Clegg       const MCExpr *Expr = Fixup.getValue();
17368fffa1dfSSam Clegg       auto *SymRef = dyn_cast<MCSymbolRefExpr>(Expr);
17378fffa1dfSSam Clegg       if (!SymRef)
1738bafe6902SSam Clegg         report_fatal_error("fixups in .init_array should be symbol references");
17398fffa1dfSSam Clegg       const auto &TargetSym = cast<const MCSymbolWasm>(SymRef->getSymbol());
17408fffa1dfSSam Clegg       if (TargetSym.getIndex() == InvalidIndex)
17413ea1c62cSSam Clegg         report_fatal_error("symbols in .init_array should exist in symtab");
17428fffa1dfSSam Clegg       if (!TargetSym.isFunction())
17438fffa1dfSSam Clegg         report_fatal_error("symbols in .init_array should be for functions");
174425d8e68bSSam Clegg       InitFuncs.push_back(
17458fffa1dfSSam Clegg           std::make_pair(Priority, TargetSym.getIndex()));
1746bafe6902SSam Clegg     }
1747bafe6902SSam Clegg   }
1748bafe6902SSam Clegg 
174918eafb6cSDan Gohman   // Write out the Wasm header.
175018eafb6cSDan Gohman   writeHeader(Asm);
175118eafb6cSDan Gohman 
17520ff28fa6SDerek Schuff   uint32_t CodeSectionIndex, DataSectionIndex;
17530ff28fa6SDerek Schuff   if (Mode != DwoMode::DwoOnly) {
1754da419bdbSHeejin Ahn     writeTypeSection(Signatures);
1755f950b24aSSam Clegg     writeImportSection(Imports, DataSize, TableElems.size());
17569e15f359SSam Clegg     writeFunctionSection(Functions);
1757f950b24aSSam Clegg     // Skip the "memory" section; we import the memory instead.
1758da419bdbSHeejin Ahn     writeEventSection(Events);
17590a6c4d8dSSam Clegg     writeGlobalSection(Globals);
1760*388fb67bSPaulo Matos     writeTableSection(Tables);
17619e15f359SSam Clegg     writeExportSection(Exports);
17629e15f359SSam Clegg     writeElemSection(TableElems);
1763fef8de66SThomas Lively     writeDataCountSection();
17640ff28fa6SDerek Schuff 
17650ff28fa6SDerek Schuff     CodeSectionIndex = writeCodeSection(Asm, Layout, Functions);
17660ff28fa6SDerek Schuff     DataSectionIndex = writeDataSection(Layout);
17670ff28fa6SDerek Schuff   }
17680ff28fa6SDerek Schuff 
17690ff28fa6SDerek Schuff   for (auto &CustomSection : CustomSections) {
1770cbda16ebSThomas Lively     writeCustomSection(CustomSection, Asm, Layout);
17710ff28fa6SDerek Schuff   }
17720ff28fa6SDerek Schuff 
17730ff28fa6SDerek Schuff   if (Mode != DwoMode::DwoOnly) {
1774c22bfb6bSNicholas Wilson     writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats);
17750ff28fa6SDerek Schuff 
17766f08c84aSSam Clegg     writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations);
17776f08c84aSSam Clegg     writeRelocSection(DataSectionIndex, "DATA", DataRelocations);
17780ff28fa6SDerek Schuff   }
17796a31a0d6SSam Clegg   writeCustomRelocSections();
1780cbda16ebSThomas Lively   if (ProducersSection)
1781cbda16ebSThomas Lively     writeCustomSection(*ProducersSection, Asm, Layout);
1782f6f4f843SThomas Lively   if (TargetFeaturesSection)
1783f6f4f843SThomas Lively     writeCustomSection(*TargetFeaturesSection, Asm, Layout);
1784970d02c4SDan Gohman 
1785d934cb88SDan Gohman   // TODO: Translate the .comment section to the output.
17860ff28fa6SDerek Schuff   return W->OS.tell() - StartOffset;
178718eafb6cSDan Gohman }
178818eafb6cSDan Gohman 
178960fbc7ccSLang Hames std::unique_ptr<MCObjectWriter>
17901301a878SLang Hames llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
179118eafb6cSDan Gohman                              raw_pwrite_stream &OS) {
17920eaee545SJonas Devlieghere   return std::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
179318eafb6cSDan Gohman }
17940ff28fa6SDerek Schuff 
17950ff28fa6SDerek Schuff std::unique_ptr<MCObjectWriter>
17960ff28fa6SDerek Schuff llvm::createWasmDwoObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
17970ff28fa6SDerek Schuff                                 raw_pwrite_stream &OS,
17980ff28fa6SDerek Schuff                                 raw_pwrite_stream &DwoOS) {
17990ff28fa6SDerek Schuff   return std::make_unique<WasmObjectWriter>(std::move(MOTW), OS, DwoOS);
18000ff28fa6SDerek Schuff }
1801