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"
16*b59dff4bSBenjamin 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;
197da419bdbSHeejin Ahn   // Maps function/global symbols to the function/global/event/section index
198da419bdbSHeejin Ahn   // 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;
221da419bdbSHeejin Ahn   unsigned NumEventImports = 0;
2227e1c3345SChandler Carruth   uint32_t SectionCount = 0;
223d934cb88SDan Gohman 
2240ff28fa6SDerek Schuff   enum class DwoMode {
2250ff28fa6SDerek Schuff     AllSections,
2260ff28fa6SDerek Schuff     NonDwoOnly,
2270ff28fa6SDerek Schuff     DwoOnly,
2280ff28fa6SDerek Schuff   };
2290ff28fa6SDerek Schuff   bool IsSplitDwarf = false;
2300ff28fa6SDerek Schuff   raw_pwrite_stream *OS = nullptr;
2310ff28fa6SDerek Schuff   raw_pwrite_stream *DwoOS = nullptr;
2320ff28fa6SDerek Schuff 
2330ff28fa6SDerek Schuff   // TargetObjectWriter wranppers.
23418eafb6cSDan Gohman   bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
235da84b688SDan Gohman   bool isEmscripten() const { return TargetObjectWriter->isEmscripten(); }
23618eafb6cSDan Gohman 
2372322a937SSam Clegg   void startSection(SectionBookkeeping &Section, unsigned SectionId);
2382322a937SSam Clegg   void startCustomSection(SectionBookkeeping &Section, StringRef Name);
239d934cb88SDan Gohman   void endSection(SectionBookkeeping &Section);
240d934cb88SDan Gohman 
24118eafb6cSDan Gohman public:
2421301a878SLang Hames   WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
2430ff28fa6SDerek Schuff                    raw_pwrite_stream &OS_)
2440ff28fa6SDerek Schuff       : TargetObjectWriter(std::move(MOTW)), OS(&OS_) {}
2450ff28fa6SDerek Schuff 
2460ff28fa6SDerek Schuff   WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
2470ff28fa6SDerek Schuff                    raw_pwrite_stream &OS_, raw_pwrite_stream &DwoOS_)
2480ff28fa6SDerek Schuff       : TargetObjectWriter(std::move(MOTW)), IsSplitDwarf(true), OS(&OS_),
2490ff28fa6SDerek Schuff         DwoOS(&DwoOS_) {}
25018eafb6cSDan Gohman 
2510917c9e4SDan Gohman private:
252acd7d2b0SSam Clegg   void reset() override {
253acd7d2b0SSam Clegg     CodeRelocations.clear();
254acd7d2b0SSam Clegg     DataRelocations.clear();
255acd7d2b0SSam Clegg     TypeIndices.clear();
2566c899ba6SSam Clegg     WasmIndices.clear();
257492f7529SSam Clegg     GOTIndices.clear();
258f9edbe95SSam Clegg     TableIndices.clear();
2596c899ba6SSam Clegg     DataLocations.clear();
260cbda16ebSThomas Lively     CustomSections.clear();
261cbda16ebSThomas Lively     ProducersSection.reset();
262f6f4f843SThomas Lively     TargetFeaturesSection.reset();
2636a31a0d6SSam Clegg     CustomSectionsRelocations.clear();
264da419bdbSHeejin Ahn     SignatureIndices.clear();
265da419bdbSHeejin Ahn     Signatures.clear();
2666c899ba6SSam Clegg     DataSegments.clear();
2676ccb59b3SSam Clegg     SectionFunctions.clear();
2689f3fe42eSSam Clegg     NumFunctionImports = 0;
2697c395943SSam Clegg     NumGlobalImports = 0;
270105bdc25SSam Clegg     MCObjectWriter::reset();
271acd7d2b0SSam Clegg   }
272acd7d2b0SSam Clegg 
27318eafb6cSDan Gohman   void writeHeader(const MCAssembler &Asm);
27418eafb6cSDan Gohman 
27518eafb6cSDan Gohman   void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
27618eafb6cSDan Gohman                         const MCFragment *Fragment, const MCFixup &Fixup,
277ceecfe5bSRafael Espindola                         MCValue Target, uint64_t &FixedValue) override;
27818eafb6cSDan Gohman 
27918eafb6cSDan Gohman   void executePostLayoutBinding(MCAssembler &Asm,
28018eafb6cSDan Gohman                                 const MCAsmLayout &Layout) override;
2810ff28fa6SDerek Schuff   void prepareImports(SmallVectorImpl<wasm::WasmImport> &Imports,
2820ff28fa6SDerek Schuff                       MCAssembler &Asm, const MCAsmLayout &Layout);
283438390faSPeter Collingbourne   uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
2849e15f359SSam Clegg 
2850ff28fa6SDerek Schuff   uint64_t writeOneObject(MCAssembler &Asm, const MCAsmLayout &Layout,
2860ff28fa6SDerek Schuff                           DwoMode Mode);
2870ff28fa6SDerek Schuff 
288b7787fd0SSam Clegg   void writeString(const StringRef Str) {
2890ff28fa6SDerek Schuff     encodeULEB128(Str.size(), W->OS);
2900ff28fa6SDerek Schuff     W->OS << Str;
291b7787fd0SSam Clegg   }
292b7787fd0SSam Clegg 
2930a6c4d8dSSam Clegg   void writeI32(int32_t val) {
2940a6c4d8dSSam Clegg     char Buffer[4];
2950a6c4d8dSSam Clegg     support::endian::write32le(Buffer, val);
2960ff28fa6SDerek Schuff     W->OS.write(Buffer, sizeof(Buffer));
2970a6c4d8dSSam Clegg   }
2980a6c4d8dSSam Clegg 
2990a6c4d8dSSam Clegg   void writeI64(int64_t val) {
3000a6c4d8dSSam Clegg     char Buffer[8];
3010a6c4d8dSSam Clegg     support::endian::write64le(Buffer, val);
3020ff28fa6SDerek Schuff     W->OS.write(Buffer, sizeof(Buffer));
3030a6c4d8dSSam Clegg   }
3040a6c4d8dSSam Clegg 
3050ff28fa6SDerek Schuff   void writeValueType(wasm::ValType Ty) { W->OS << static_cast<char>(Ty); }
3069e15f359SSam Clegg 
3074c41fb5aSHeejin Ahn   void writeTypeSection(ArrayRef<wasm::WasmSignature> Signatures);
3084d135b04SWouter van Oortmerssen   void writeImportSection(ArrayRef<wasm::WasmImport> Imports, uint64_t DataSize,
309f950b24aSSam Clegg                           uint32_t NumElements);
310457fb0b4SSam Clegg   void writeFunctionSection(ArrayRef<WasmFunction> Functions);
3118defa952SSam Clegg   void writeExportSection(ArrayRef<wasm::WasmExport> Exports);
312457fb0b4SSam Clegg   void writeElemSection(ArrayRef<uint32_t> TableElems);
313fef8de66SThomas Lively   void writeDataCountSection();
314e49584a3SSam Clegg   uint32_t writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
315457fb0b4SSam Clegg                             ArrayRef<WasmFunction> Functions);
316e49584a3SSam Clegg   uint32_t writeDataSection(const MCAsmLayout &Layout);
317da419bdbSHeejin Ahn   void writeEventSection(ArrayRef<wasm::WasmEventType> Events);
3180a6c4d8dSSam Clegg   void writeGlobalSection(ArrayRef<wasm::WasmGlobal> Globals);
3196f08c84aSSam Clegg   void writeRelocSection(uint32_t SectionIndex, StringRef Name,
320f77dc2a8SSam Clegg                          std::vector<WasmRelocationEntry> &Relocations);
32131a2c809SSam Clegg   void writeLinkingMetaDataSection(
32286b4a09aSSam Clegg       ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
323ea7caceeSSam Clegg       ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
324ea7caceeSSam Clegg       const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats);
325cbda16ebSThomas Lively   void writeCustomSection(WasmCustomSection &CustomSection,
326cbda16ebSThomas Lively                           const MCAssembler &Asm, const MCAsmLayout &Layout);
3276a31a0d6SSam Clegg   void writeCustomRelocSections();
3286a31a0d6SSam Clegg   void
3296a31a0d6SSam Clegg   updateCustomSectionRelocations(const SmallVector<WasmFunction, 4> &Functions,
3306a31a0d6SSam Clegg                                  const MCAsmLayout &Layout);
331acd7d2b0SSam Clegg 
3327ee758d6SSam Clegg   uint64_t getProvisionalValue(const WasmRelocationEntry &RelEntry,
3337ee758d6SSam Clegg                                const MCAsmLayout &Layout);
334acd7d2b0SSam Clegg   void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
3357ee758d6SSam Clegg                         uint64_t ContentsOffset, const MCAsmLayout &Layout);
336acd7d2b0SSam Clegg 
337acd7d2b0SSam Clegg   uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
3385e3d33a7SSam Clegg   uint32_t getFunctionType(const MCSymbolWasm &Symbol);
339da419bdbSHeejin Ahn   uint32_t getEventType(const MCSymbolWasm &Symbol);
34038b12f5eSHeejin Ahn   void registerFunctionType(const MCSymbolWasm &Symbol);
34138b12f5eSHeejin Ahn   void registerEventType(const MCSymbolWasm &Symbol);
34218eafb6cSDan Gohman };
3439e15f359SSam Clegg 
34418eafb6cSDan Gohman } // end anonymous namespace
34518eafb6cSDan Gohman 
346d934cb88SDan Gohman // Write out a section header and a patchable section size field.
347d934cb88SDan Gohman void WasmObjectWriter::startSection(SectionBookkeeping &Section,
3482322a937SSam Clegg                                     unsigned SectionId) {
349d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "startSection " << SectionId << "\n");
3500ff28fa6SDerek Schuff   W->OS << char(SectionId);
351d934cb88SDan Gohman 
3520ff28fa6SDerek Schuff   Section.SizeOffset = W->OS.tell();
353d934cb88SDan Gohman 
354d934cb88SDan Gohman   // The section size. We don't know the size yet, so reserve enough space
355d934cb88SDan Gohman   // for any 32-bit value; we'll patch it later.
3560ff28fa6SDerek Schuff   encodeULEB128(0, W->OS, 5);
357d934cb88SDan Gohman 
358d934cb88SDan Gohman   // The position where the section starts, for measuring its size.
3590ff28fa6SDerek Schuff   Section.ContentsOffset = W->OS.tell();
3600ff28fa6SDerek Schuff   Section.PayloadOffset = W->OS.tell();
3616f08c84aSSam Clegg   Section.Index = SectionCount++;
362d934cb88SDan Gohman }
3632322a937SSam Clegg 
3642322a937SSam Clegg void WasmObjectWriter::startCustomSection(SectionBookkeeping &Section,
3652322a937SSam Clegg                                           StringRef Name) {
366d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "startCustomSection " << Name << "\n");
3672322a937SSam Clegg   startSection(Section, wasm::WASM_SEC_CUSTOM);
3686a31a0d6SSam Clegg 
3696a31a0d6SSam Clegg   // The position where the section header ends, for measuring its size.
3700ff28fa6SDerek Schuff   Section.PayloadOffset = W->OS.tell();
3716a31a0d6SSam Clegg 
3722322a937SSam Clegg   // Custom sections in wasm also have a string identifier.
3732322a937SSam Clegg   writeString(Name);
3746a31a0d6SSam Clegg 
3756a31a0d6SSam Clegg   // The position where the custom section starts.
3760ff28fa6SDerek Schuff   Section.ContentsOffset = W->OS.tell();
377d934cb88SDan Gohman }
378d934cb88SDan Gohman 
379d934cb88SDan Gohman // Now that the section is complete and we know how big it is, patch up the
380d934cb88SDan Gohman // section size field at the start of the section.
381d934cb88SDan Gohman void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
3820ff28fa6SDerek Schuff   uint64_t Size = W->OS.tell();
383c0affde8SSam Clegg   // /dev/null doesn't support seek/tell and can report offset of 0.
384c0affde8SSam Clegg   // Simply skip this patching in that case.
385c0affde8SSam Clegg   if (!Size)
386c0affde8SSam Clegg     return;
387c0affde8SSam Clegg 
388c0affde8SSam Clegg   Size -= Section.PayloadOffset;
389d934cb88SDan Gohman   if (uint32_t(Size) != Size)
390d934cb88SDan Gohman     report_fatal_error("section size does not fit in a uint32_t");
391d934cb88SDan Gohman 
392d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "endSection size=" << Size << "\n");
393d934cb88SDan Gohman 
394d934cb88SDan Gohman   // Write the final section size to the payload_len field, which follows
395d934cb88SDan Gohman   // the section id byte.
3960ff28fa6SDerek Schuff   writePatchableLEB<5>(static_cast<raw_pwrite_stream &>(W->OS), Size,
397f17b149dSPeter Collingbourne                        Section.SizeOffset);
398d934cb88SDan Gohman }
399d934cb88SDan Gohman 
40018eafb6cSDan Gohman // Emit the Wasm header.
40118eafb6cSDan Gohman void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
4020ff28fa6SDerek Schuff   W->OS.write(wasm::WasmMagic, sizeof(wasm::WasmMagic));
4030ff28fa6SDerek Schuff   W->write<uint32_t>(wasm::WasmVersion);
40418eafb6cSDan Gohman }
40518eafb6cSDan Gohman 
40618eafb6cSDan Gohman void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
40718eafb6cSDan Gohman                                                 const MCAsmLayout &Layout) {
4086ccb59b3SSam Clegg   // Build a map of sections to the function that defines them, for use
4096ccb59b3SSam Clegg   // in recordRelocation.
4106ccb59b3SSam Clegg   for (const MCSymbol &S : Asm.symbols()) {
4116ccb59b3SSam Clegg     const auto &WS = static_cast<const MCSymbolWasm &>(S);
4126ccb59b3SSam Clegg     if (WS.isDefined() && WS.isFunction() && !WS.isVariable()) {
4136ccb59b3SSam Clegg       const auto &Sec = static_cast<const MCSectionWasm &>(S.getSection());
4146ccb59b3SSam Clegg       auto Pair = SectionFunctions.insert(std::make_pair(&Sec, &S));
4156ccb59b3SSam Clegg       if (!Pair.second)
4166ccb59b3SSam Clegg         report_fatal_error("section already has a defining function: " +
4177d1ff446SFangrui Song                            Sec.getName());
4186ccb59b3SSam Clegg     }
4196ccb59b3SSam Clegg   }
42018eafb6cSDan Gohman }
42118eafb6cSDan Gohman 
42218eafb6cSDan Gohman void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
42318eafb6cSDan Gohman                                         const MCAsmLayout &Layout,
42418eafb6cSDan Gohman                                         const MCFragment *Fragment,
42518eafb6cSDan Gohman                                         const MCFixup &Fixup, MCValue Target,
426ceecfe5bSRafael Espindola                                         uint64_t &FixedValue) {
427ecc5e808SSam Clegg   // The WebAssembly backend should never generate FKF_IsPCRel fixups
428e828ce1bSFangrui Song   assert(!(Asm.getBackend().getFixupKindInfo(Fixup.getKind()).Flags &
429ecc5e808SSam Clegg            MCFixupKindInfo::FKF_IsPCRel));
430ecc5e808SSam Clegg 
431fe6414b0SSam Clegg   const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
432d934cb88SDan Gohman   uint64_t C = Target.getConstant();
433d934cb88SDan Gohman   uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
434d934cb88SDan Gohman   MCContext &Ctx = Asm.getContext();
435d934cb88SDan Gohman 
436d934cb88SDan Gohman   if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
437ecc5e808SSam Clegg     // To get here the A - B expression must have failed evaluateAsRelocatable.
438ecc5e808SSam Clegg     // This means either A or B must be undefined and in WebAssembly we can't
439ecc5e808SSam Clegg     // support either of those cases.
440ecc5e808SSam Clegg     const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
441d934cb88SDan Gohman     Ctx.reportError(
442d934cb88SDan Gohman         Fixup.getLoc(),
443d934cb88SDan Gohman         Twine("symbol '") + SymB.getName() +
444ecc5e808SSam Clegg             "': unsupported subtraction expression used in relocation.");
445d934cb88SDan Gohman     return;
446d934cb88SDan Gohman   }
447d934cb88SDan Gohman 
448d934cb88SDan Gohman   // We either rejected the fixup or folded B into C at this point.
449d934cb88SDan Gohman   const MCSymbolRefExpr *RefA = Target.getSymA();
450ecc5e808SSam Clegg   const auto *SymA = cast<MCSymbolWasm>(&RefA->getSymbol());
451d934cb88SDan Gohman 
4523ea1c62cSSam Clegg   // The .init_array isn't translated as data, so don't do relocations in it.
4537d1ff446SFangrui Song   if (FixupSection.getName().startswith(".init_array")) {
4543ea1c62cSSam Clegg     SymA->setUsedInInitArray();
4553ea1c62cSSam Clegg     return;
4563ea1c62cSSam Clegg   }
4573ea1c62cSSam Clegg 
458ecc5e808SSam Clegg   if (SymA->isVariable()) {
459d934cb88SDan Gohman     const MCExpr *Expr = SymA->getVariableValue();
4607ee758d6SSam Clegg     if (const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr))
4616ad8f190SSam Clegg       if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
4626ad8f190SSam Clegg         llvm_unreachable("weakref used in reloc not yet implemented");
463d934cb88SDan Gohman   }
464d934cb88SDan Gohman 
465d934cb88SDan Gohman   // Put any constant offset in an addend. Offsets can be negative, and
466d934cb88SDan Gohman   // LLVM expects wrapping, in contrast to wasm's immediates which can't
467d934cb88SDan Gohman   // be negative and don't wrap.
468d934cb88SDan Gohman   FixedValue = 0;
469d934cb88SDan Gohman 
470a5e175c6SSam Clegg   unsigned Type = TargetObjectWriter->getRelocType(Target, Fixup);
4719d24fb7fSSam Clegg 
4724d57fbd0SSam Clegg   // Absolute offset within a section or a function.
4734d57fbd0SSam Clegg   // Currently only supported for for metadata sections.
4744d57fbd0SSam Clegg   // See: test/MC/WebAssembly/blockaddress.ll
475d1152a26SSam Clegg   if (Type == wasm::R_WASM_FUNCTION_OFFSET_I32 ||
476d1152a26SSam Clegg       Type == wasm::R_WASM_SECTION_OFFSET_I32) {
4774d57fbd0SSam Clegg     if (!FixupSection.getKind().isMetadata())
4784d57fbd0SSam Clegg       report_fatal_error("relocations for function or section offsets are "
4794d57fbd0SSam Clegg                          "only supported in metadata sections");
4804d57fbd0SSam Clegg 
4814d57fbd0SSam Clegg     const MCSymbol *SectionSymbol = nullptr;
4824d57fbd0SSam Clegg     const MCSection &SecA = SymA->getSection();
4834d57fbd0SSam Clegg     if (SecA.getKind().isText())
4846ccb59b3SSam Clegg       SectionSymbol = SectionFunctions.find(&SecA)->second;
4854d57fbd0SSam Clegg     else
4864d57fbd0SSam Clegg       SectionSymbol = SecA.getBeginSymbol();
4874d57fbd0SSam Clegg     if (!SectionSymbol)
4884d57fbd0SSam Clegg       report_fatal_error("section symbol is required for relocation");
4894d57fbd0SSam Clegg 
4904d57fbd0SSam Clegg     C += Layout.getSymbolOffset(*SymA);
4914d57fbd0SSam Clegg     SymA = cast<MCSymbolWasm>(SectionSymbol);
4924d57fbd0SSam Clegg   }
4934d57fbd0SSam Clegg 
494d1152a26SSam Clegg   // Relocation other than R_WASM_TYPE_INDEX_LEB are required to be
4954d57fbd0SSam Clegg   // against a named symbol.
496d1152a26SSam Clegg   if (Type != wasm::R_WASM_TYPE_INDEX_LEB) {
4974d57fbd0SSam Clegg     if (SymA->getName().empty())
4984d57fbd0SSam Clegg       report_fatal_error("relocations against un-named temporaries are not yet "
4994d57fbd0SSam Clegg                          "supported by wasm");
5004d57fbd0SSam Clegg 
5014d57fbd0SSam Clegg     SymA->setUsedInReloc();
5024d57fbd0SSam Clegg   }
503ae03c1e7SSam Clegg 
504492f7529SSam Clegg   if (RefA->getKind() == MCSymbolRefExpr::VK_GOT)
505492f7529SSam Clegg     SymA->setUsedInGOT();
506492f7529SSam Clegg 
507d934cb88SDan Gohman   WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
508d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
509d934cb88SDan Gohman 
5106a31a0d6SSam Clegg   if (FixupSection.isWasmData()) {
511d934cb88SDan Gohman     DataRelocations.push_back(Rec);
5126a31a0d6SSam Clegg   } else if (FixupSection.getKind().isText()) {
51312fd3da9SSam Clegg     CodeRelocations.push_back(Rec);
5146a31a0d6SSam Clegg   } else if (FixupSection.getKind().isMetadata()) {
5156a31a0d6SSam Clegg     CustomSectionsRelocations[&FixupSection].push_back(Rec);
5166a31a0d6SSam Clegg   } else {
51712fd3da9SSam Clegg     llvm_unreachable("unexpected section type");
518d934cb88SDan Gohman   }
5196a31a0d6SSam Clegg }
520d934cb88SDan Gohman 
521d934cb88SDan Gohman // Compute a value to write into the code at the location covered
52260ec3034SSam Clegg // by RelEntry. This value isn't used by the static linker; it just serves
52360ec3034SSam Clegg // to make the object format more readable and more likely to be directly
52460ec3034SSam Clegg // useable.
5253b29376eSWouter van Oortmerssen uint64_t
5267ee758d6SSam Clegg WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry,
5277ee758d6SSam Clegg                                       const MCAsmLayout &Layout) {
52848139ebcSWouter van Oortmerssen   if ((RelEntry.Type == wasm::R_WASM_GLOBAL_INDEX_LEB ||
52948139ebcSWouter van Oortmerssen        RelEntry.Type == wasm::R_WASM_GLOBAL_INDEX_I32) &&
53048139ebcSWouter van Oortmerssen       !RelEntry.Symbol->isGlobal()) {
531492f7529SSam Clegg     assert(GOTIndices.count(RelEntry.Symbol) > 0 && "symbol not found in GOT index space");
532492f7529SSam Clegg     return GOTIndices[RelEntry.Symbol];
533492f7529SSam Clegg   }
534492f7529SSam Clegg 
53560ec3034SSam Clegg   switch (RelEntry.Type) {
5362a7cac93SSam Clegg   case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
537d1152a26SSam Clegg   case wasm::R_WASM_TABLE_INDEX_SLEB:
538cc1b9b68SWouter van Oortmerssen   case wasm::R_WASM_TABLE_INDEX_SLEB64:
539cc1b9b68SWouter van Oortmerssen   case wasm::R_WASM_TABLE_INDEX_I32:
540cc1b9b68SWouter van Oortmerssen   case wasm::R_WASM_TABLE_INDEX_I64: {
541f9edbe95SSam Clegg     // Provisional value is table address of the resolved symbol itself
5427ee758d6SSam Clegg     const MCSymbolWasm *Base =
5437ee758d6SSam Clegg         cast<MCSymbolWasm>(Layout.getBaseSymbol(*RelEntry.Symbol));
5447ee758d6SSam Clegg     assert(Base->isFunction());
54581443ac1SSam Clegg     if (RelEntry.Type == wasm::R_WASM_TABLE_INDEX_REL_SLEB)
5467ee758d6SSam Clegg       return TableIndices[Base] - InitialTableOffset;
54781443ac1SSam Clegg     else
5487ee758d6SSam Clegg       return TableIndices[Base];
549f9edbe95SSam Clegg   }
550d1152a26SSam Clegg   case wasm::R_WASM_TYPE_INDEX_LEB:
5516c899ba6SSam Clegg     // Provisional value is same as the index
55260ec3034SSam Clegg     return getRelocationIndexValue(RelEntry);
553d1152a26SSam Clegg   case wasm::R_WASM_FUNCTION_INDEX_LEB:
554d1152a26SSam Clegg   case wasm::R_WASM_GLOBAL_INDEX_LEB:
55548139ebcSWouter van Oortmerssen   case wasm::R_WASM_GLOBAL_INDEX_I32:
556d1152a26SSam Clegg   case wasm::R_WASM_EVENT_INDEX_LEB:
557da419bdbSHeejin Ahn     // Provisional value is function/global/event Wasm index
558492f7529SSam Clegg     assert(WasmIndices.count(RelEntry.Symbol) > 0 && "symbol not found in wasm index space");
5596c899ba6SSam Clegg     return WasmIndices[RelEntry.Symbol];
560d1152a26SSam Clegg   case wasm::R_WASM_FUNCTION_OFFSET_I32:
561d1152a26SSam Clegg   case wasm::R_WASM_SECTION_OFFSET_I32: {
5626a31a0d6SSam Clegg     const auto &Section =
5636a31a0d6SSam Clegg         static_cast<const MCSectionWasm &>(RelEntry.Symbol->getSection());
5646a31a0d6SSam Clegg     return Section.getSectionOffset() + RelEntry.Addend;
5656a31a0d6SSam Clegg   }
566d1152a26SSam Clegg   case wasm::R_WASM_MEMORY_ADDR_LEB:
5673b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_LEB64:
5683b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_SLEB:
5693b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_SLEB64:
5702a7cac93SSam Clegg   case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
5713b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_REL_SLEB64:
5723b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_I32:
5733b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_I64: {
5749c7b5808SDominic Chen     // Provisional value is address of the global plus the offset
5757ee758d6SSam Clegg     const MCSymbolWasm *Base =
5767ee758d6SSam Clegg         cast<MCSymbolWasm>(Layout.getBaseSymbol(*RelEntry.Symbol));
577270ed1b3SSam Clegg     // For undefined symbols, use zero
5787ee758d6SSam Clegg     if (!Base->isDefined())
579270ed1b3SSam Clegg       return 0;
5809c7b5808SDominic Chen     const wasm::WasmDataReference &BaseRef = DataLocations[Base],
5819c7b5808SDominic Chen                                   &SymRef = DataLocations[RelEntry.Symbol];
5829c7b5808SDominic Chen     const WasmDataSegment &Segment = DataSegments[BaseRef.Segment];
583d934cb88SDan Gohman     // Ignore overflow. LLVM allows address arithmetic to silently wrap.
5849c7b5808SDominic Chen     return Segment.Offset + BaseRef.Offset + SymRef.Offset + RelEntry.Addend;
58560ec3034SSam Clegg   }
58660ec3034SSam Clegg   default:
58760ec3034SSam Clegg     llvm_unreachable("invalid relocation type");
58860ec3034SSam Clegg   }
589d934cb88SDan Gohman }
590d934cb88SDan Gohman 
591759631c7SSam Clegg static void addData(SmallVectorImpl<char> &DataBytes,
59263ebb813SSam Clegg                     MCSectionWasm &DataSection) {
5937d1ff446SFangrui Song   LLVM_DEBUG(errs() << "addData: " << DataSection.getName() << "\n");
594759631c7SSam Clegg 
59563ebb813SSam Clegg   DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
59663ebb813SSam Clegg 
597759631c7SSam Clegg   for (const MCFragment &Frag : DataSection) {
598759631c7SSam Clegg     if (Frag.hasInstructions())
599759631c7SSam Clegg       report_fatal_error("only data supported in data sections");
600759631c7SSam Clegg 
601759631c7SSam Clegg     if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
602759631c7SSam Clegg       if (Align->getValueSize() != 1)
603759631c7SSam Clegg         report_fatal_error("only byte values supported for alignment");
604759631c7SSam Clegg       // If nops are requested, use zeros, as this is the data section.
605759631c7SSam Clegg       uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
606f208f631SHeejin Ahn       uint64_t Size =
607f208f631SHeejin Ahn           std::min<uint64_t>(alignTo(DataBytes.size(), Align->getAlignment()),
608f208f631SHeejin Ahn                              DataBytes.size() + Align->getMaxBytesToEmit());
609759631c7SSam Clegg       DataBytes.resize(Size, Value);
610759631c7SSam Clegg     } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
611588fad4dSNirav Dave       int64_t NumValues;
612588fad4dSNirav Dave       if (!Fill->getNumValues().evaluateAsAbsolute(NumValues))
613d707c370SRafael Espindola         llvm_unreachable("The fill should be an assembler constant");
614588fad4dSNirav Dave       DataBytes.insert(DataBytes.end(), Fill->getValueSize() * NumValues,
615588fad4dSNirav Dave                        Fill->getValue());
61624faf859SHeejin Ahn     } else if (auto *LEB = dyn_cast<MCLEBFragment>(&Frag)) {
61724faf859SHeejin Ahn       const SmallVectorImpl<char> &Contents = LEB->getContents();
61824faf859SHeejin Ahn       DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
619759631c7SSam Clegg     } else {
620759631c7SSam Clegg       const auto &DataFrag = cast<MCDataFragment>(Frag);
621759631c7SSam Clegg       const SmallVectorImpl<char> &Contents = DataFrag.getContents();
622759631c7SSam Clegg       DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
623759631c7SSam Clegg     }
624759631c7SSam Clegg   }
625759631c7SSam Clegg 
626d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
627759631c7SSam Clegg }
628759631c7SSam Clegg 
62960ec3034SSam Clegg uint32_t
63060ec3034SSam Clegg WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
631d1152a26SSam Clegg   if (RelEntry.Type == wasm::R_WASM_TYPE_INDEX_LEB) {
632b7787fd0SSam Clegg     if (!TypeIndices.count(RelEntry.Symbol))
633b7787fd0SSam Clegg       report_fatal_error("symbol not found in type index space: " +
634b7787fd0SSam Clegg                          RelEntry.Symbol->getName());
635acd7d2b0SSam Clegg     return TypeIndices[RelEntry.Symbol];
636acd7d2b0SSam Clegg   }
63760ec3034SSam Clegg 
63825d8e68bSSam Clegg   return RelEntry.Symbol->getIndex();
639acd7d2b0SSam Clegg }
640acd7d2b0SSam Clegg 
641d934cb88SDan Gohman // Apply the portions of the relocation records that we can handle ourselves
642d934cb88SDan Gohman // directly.
643acd7d2b0SSam Clegg void WasmObjectWriter::applyRelocations(
6447ee758d6SSam Clegg     ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset,
6457ee758d6SSam Clegg     const MCAsmLayout &Layout) {
6460ff28fa6SDerek Schuff   auto &Stream = static_cast<raw_pwrite_stream &>(W->OS);
647d934cb88SDan Gohman   for (const WasmRelocationEntry &RelEntry : Relocations) {
648d934cb88SDan Gohman     uint64_t Offset = ContentsOffset +
649d934cb88SDan Gohman                       RelEntry.FixupSection->getSectionOffset() +
650d934cb88SDan Gohman                       RelEntry.Offset;
651d934cb88SDan Gohman 
652d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
6537ee758d6SSam Clegg     auto Value = getProvisionalValue(RelEntry, Layout);
65460ec3034SSam Clegg 
655acd7d2b0SSam Clegg     switch (RelEntry.Type) {
656d1152a26SSam Clegg     case wasm::R_WASM_FUNCTION_INDEX_LEB:
657d1152a26SSam Clegg     case wasm::R_WASM_TYPE_INDEX_LEB:
658d1152a26SSam Clegg     case wasm::R_WASM_GLOBAL_INDEX_LEB:
659d1152a26SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_LEB:
660d1152a26SSam Clegg     case wasm::R_WASM_EVENT_INDEX_LEB:
6613b29376eSWouter van Oortmerssen       writePatchableLEB<5>(Stream, Value, Offset);
6623b29376eSWouter van Oortmerssen       break;
6633b29376eSWouter van Oortmerssen     case wasm::R_WASM_MEMORY_ADDR_LEB64:
6643b29376eSWouter van Oortmerssen       writePatchableLEB<10>(Stream, Value, Offset);
665d934cb88SDan Gohman       break;
666d1152a26SSam Clegg     case wasm::R_WASM_TABLE_INDEX_I32:
667d1152a26SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_I32:
668d1152a26SSam Clegg     case wasm::R_WASM_FUNCTION_OFFSET_I32:
669d1152a26SSam Clegg     case wasm::R_WASM_SECTION_OFFSET_I32:
67048139ebcSWouter van Oortmerssen     case wasm::R_WASM_GLOBAL_INDEX_I32:
6710a6c4d8dSSam Clegg       patchI32(Stream, Value, Offset);
672d934cb88SDan Gohman       break;
673cc1b9b68SWouter van Oortmerssen     case wasm::R_WASM_TABLE_INDEX_I64:
6743b29376eSWouter van Oortmerssen     case wasm::R_WASM_MEMORY_ADDR_I64:
6753b29376eSWouter van Oortmerssen       patchI64(Stream, Value, Offset);
6763b29376eSWouter van Oortmerssen       break;
677d1152a26SSam Clegg     case wasm::R_WASM_TABLE_INDEX_SLEB:
6782a7cac93SSam Clegg     case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
679d1152a26SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_SLEB:
6802a7cac93SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
6813b29376eSWouter van Oortmerssen       writePatchableSLEB<5>(Stream, Value, Offset);
6823b29376eSWouter van Oortmerssen       break;
683cc1b9b68SWouter van Oortmerssen     case wasm::R_WASM_TABLE_INDEX_SLEB64:
6843b29376eSWouter van Oortmerssen     case wasm::R_WASM_MEMORY_ADDR_SLEB64:
6853b29376eSWouter van Oortmerssen     case wasm::R_WASM_MEMORY_ADDR_REL_SLEB64:
6863b29376eSWouter van Oortmerssen       writePatchableSLEB<10>(Stream, Value, Offset);
68760ec3034SSam Clegg       break;
688d934cb88SDan Gohman     default:
6899d24fb7fSSam Clegg       llvm_unreachable("invalid relocation type");
690d934cb88SDan Gohman     }
691d934cb88SDan Gohman   }
69218eafb6cSDan Gohman }
69318eafb6cSDan Gohman 
6944c41fb5aSHeejin Ahn void WasmObjectWriter::writeTypeSection(
6954c41fb5aSHeejin Ahn     ArrayRef<wasm::WasmSignature> Signatures) {
696da419bdbSHeejin Ahn   if (Signatures.empty())
6979e15f359SSam Clegg     return;
6989e15f359SSam Clegg 
6999e15f359SSam Clegg   SectionBookkeeping Section;
7009e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_TYPE);
7019e15f359SSam Clegg 
7020ff28fa6SDerek Schuff   encodeULEB128(Signatures.size(), W->OS);
7039e15f359SSam Clegg 
7044c41fb5aSHeejin Ahn   for (const wasm::WasmSignature &Sig : Signatures) {
7050ff28fa6SDerek Schuff     W->OS << char(wasm::WASM_TYPE_FUNC);
7060ff28fa6SDerek Schuff     encodeULEB128(Sig.Params.size(), W->OS);
707da419bdbSHeejin Ahn     for (wasm::ValType Ty : Sig.Params)
7089e15f359SSam Clegg       writeValueType(Ty);
7090ff28fa6SDerek Schuff     encodeULEB128(Sig.Returns.size(), W->OS);
710da419bdbSHeejin Ahn     for (wasm::ValType Ty : Sig.Returns)
7119e15f359SSam Clegg       writeValueType(Ty);
7129e15f359SSam Clegg   }
7139e15f359SSam Clegg 
7149e15f359SSam Clegg   endSection(Section);
7159e15f359SSam Clegg }
7169e15f359SSam Clegg 
7178defa952SSam Clegg void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports,
7184d135b04SWouter van Oortmerssen                                           uint64_t DataSize,
719f950b24aSSam Clegg                                           uint32_t NumElements) {
7209e15f359SSam Clegg   if (Imports.empty())
7219e15f359SSam Clegg     return;
7229e15f359SSam Clegg 
7234d135b04SWouter van Oortmerssen   uint64_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
724f950b24aSSam Clegg 
7259e15f359SSam Clegg   SectionBookkeeping Section;
7269e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_IMPORT);
7279e15f359SSam Clegg 
7280ff28fa6SDerek Schuff   encodeULEB128(Imports.size(), W->OS);
7298defa952SSam Clegg   for (const wasm::WasmImport &Import : Imports) {
7308defa952SSam Clegg     writeString(Import.Module);
7318defa952SSam Clegg     writeString(Import.Field);
7320ff28fa6SDerek Schuff     W->OS << char(Import.Kind);
7339e15f359SSam Clegg 
7349e15f359SSam Clegg     switch (Import.Kind) {
7359e15f359SSam Clegg     case wasm::WASM_EXTERNAL_FUNCTION:
7360ff28fa6SDerek Schuff       encodeULEB128(Import.SigIndex, W->OS);
7379e15f359SSam Clegg       break;
7389e15f359SSam Clegg     case wasm::WASM_EXTERNAL_GLOBAL:
7390ff28fa6SDerek Schuff       W->OS << char(Import.Global.Type);
7400ff28fa6SDerek Schuff       W->OS << char(Import.Global.Mutable ? 1 : 0);
7419e15f359SSam Clegg       break;
742f950b24aSSam Clegg     case wasm::WASM_EXTERNAL_MEMORY:
7430ff28fa6SDerek Schuff       encodeULEB128(Import.Memory.Flags, W->OS);
7440ff28fa6SDerek Schuff       encodeULEB128(NumPages, W->OS); // initial
745f950b24aSSam Clegg       break;
746f950b24aSSam Clegg     case wasm::WASM_EXTERNAL_TABLE:
7470ff28fa6SDerek Schuff       W->OS << char(Import.Table.ElemType);
7480ff28fa6SDerek Schuff       encodeULEB128(0, W->OS);           // flags
7490ff28fa6SDerek Schuff       encodeULEB128(NumElements, W->OS); // initial
750f950b24aSSam Clegg       break;
751da419bdbSHeejin Ahn     case wasm::WASM_EXTERNAL_EVENT:
7520ff28fa6SDerek Schuff       encodeULEB128(Import.Event.Attribute, W->OS);
7530ff28fa6SDerek Schuff       encodeULEB128(Import.Event.SigIndex, W->OS);
754da419bdbSHeejin Ahn       break;
7559e15f359SSam Clegg     default:
7569e15f359SSam Clegg       llvm_unreachable("unsupported import kind");
7579e15f359SSam Clegg     }
7589e15f359SSam Clegg   }
7599e15f359SSam Clegg 
7609e15f359SSam Clegg   endSection(Section);
7619e15f359SSam Clegg }
7629e15f359SSam Clegg 
763457fb0b4SSam Clegg void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
7649e15f359SSam Clegg   if (Functions.empty())
7659e15f359SSam Clegg     return;
7669e15f359SSam Clegg 
7679e15f359SSam Clegg   SectionBookkeeping Section;
7689e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_FUNCTION);
7699e15f359SSam Clegg 
7700ff28fa6SDerek Schuff   encodeULEB128(Functions.size(), W->OS);
7719e15f359SSam Clegg   for (const WasmFunction &Func : Functions)
7720ff28fa6SDerek Schuff     encodeULEB128(Func.SigIndex, W->OS);
7739e15f359SSam Clegg 
7749e15f359SSam Clegg   endSection(Section);
7759e15f359SSam Clegg }
7769e15f359SSam Clegg 
777da419bdbSHeejin Ahn void WasmObjectWriter::writeEventSection(ArrayRef<wasm::WasmEventType> Events) {
778da419bdbSHeejin Ahn   if (Events.empty())
779da419bdbSHeejin Ahn     return;
780da419bdbSHeejin Ahn 
781da419bdbSHeejin Ahn   SectionBookkeeping Section;
782da419bdbSHeejin Ahn   startSection(Section, wasm::WASM_SEC_EVENT);
783da419bdbSHeejin Ahn 
7840ff28fa6SDerek Schuff   encodeULEB128(Events.size(), W->OS);
785da419bdbSHeejin Ahn   for (const wasm::WasmEventType &Event : Events) {
7860ff28fa6SDerek Schuff     encodeULEB128(Event.Attribute, W->OS);
7870ff28fa6SDerek Schuff     encodeULEB128(Event.SigIndex, W->OS);
788da419bdbSHeejin Ahn   }
789da419bdbSHeejin Ahn 
790da419bdbSHeejin Ahn   endSection(Section);
791da419bdbSHeejin Ahn }
792da419bdbSHeejin Ahn 
7930a6c4d8dSSam Clegg void WasmObjectWriter::writeGlobalSection(ArrayRef<wasm::WasmGlobal> Globals) {
7940a6c4d8dSSam Clegg   if (Globals.empty())
7950a6c4d8dSSam Clegg     return;
7960a6c4d8dSSam Clegg 
7970a6c4d8dSSam Clegg   SectionBookkeeping Section;
7980a6c4d8dSSam Clegg   startSection(Section, wasm::WASM_SEC_GLOBAL);
7990a6c4d8dSSam Clegg 
8000ff28fa6SDerek Schuff   encodeULEB128(Globals.size(), W->OS);
8010a6c4d8dSSam Clegg   for (const wasm::WasmGlobal &Global : Globals) {
8020ff28fa6SDerek Schuff     encodeULEB128(Global.Type.Type, W->OS);
8030ff28fa6SDerek Schuff     W->OS << char(Global.Type.Mutable);
8040ff28fa6SDerek Schuff     W->OS << char(Global.InitExpr.Opcode);
8050a6c4d8dSSam Clegg     switch (Global.Type.Type) {
8060a6c4d8dSSam Clegg     case wasm::WASM_TYPE_I32:
8070ff28fa6SDerek Schuff       encodeSLEB128(0, W->OS);
8080a6c4d8dSSam Clegg       break;
8090a6c4d8dSSam Clegg     case wasm::WASM_TYPE_I64:
8100ff28fa6SDerek Schuff       encodeSLEB128(0, W->OS);
8110a6c4d8dSSam Clegg       break;
8120a6c4d8dSSam Clegg     case wasm::WASM_TYPE_F32:
8130a6c4d8dSSam Clegg       writeI32(0);
8140a6c4d8dSSam Clegg       break;
8150a6c4d8dSSam Clegg     case wasm::WASM_TYPE_F64:
8160a6c4d8dSSam Clegg       writeI64(0);
8170a6c4d8dSSam Clegg       break;
81879aad89dSSam Clegg     case wasm::WASM_TYPE_EXTERNREF:
81979aad89dSSam Clegg       writeValueType(wasm::ValType::EXTERNREF);
82079aad89dSSam Clegg       break;
8210a6c4d8dSSam Clegg     default:
8220a6c4d8dSSam Clegg       llvm_unreachable("unexpected type");
8230a6c4d8dSSam Clegg     }
8240ff28fa6SDerek Schuff     W->OS << char(wasm::WASM_OPCODE_END);
8250a6c4d8dSSam Clegg   }
8260a6c4d8dSSam Clegg 
8270a6c4d8dSSam Clegg   endSection(Section);
8280a6c4d8dSSam Clegg }
8290a6c4d8dSSam Clegg 
8308defa952SSam Clegg void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) {
8319e15f359SSam Clegg   if (Exports.empty())
8329e15f359SSam Clegg     return;
8339e15f359SSam Clegg 
8349e15f359SSam Clegg   SectionBookkeeping Section;
8359e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_EXPORT);
8369e15f359SSam Clegg 
8370ff28fa6SDerek Schuff   encodeULEB128(Exports.size(), W->OS);
8388defa952SSam Clegg   for (const wasm::WasmExport &Export : Exports) {
8398defa952SSam Clegg     writeString(Export.Name);
8400ff28fa6SDerek Schuff     W->OS << char(Export.Kind);
8410ff28fa6SDerek Schuff     encodeULEB128(Export.Index, W->OS);
8429e15f359SSam Clegg   }
8439e15f359SSam Clegg 
8449e15f359SSam Clegg   endSection(Section);
8459e15f359SSam Clegg }
8469e15f359SSam Clegg 
847457fb0b4SSam Clegg void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
8489e15f359SSam Clegg   if (TableElems.empty())
8499e15f359SSam Clegg     return;
8509e15f359SSam Clegg 
8519e15f359SSam Clegg   SectionBookkeeping Section;
8529e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_ELEM);
8539e15f359SSam Clegg 
8540ff28fa6SDerek Schuff   encodeULEB128(1, W->OS); // number of "segments"
8550ff28fa6SDerek Schuff   encodeULEB128(0, W->OS); // the table index
8569e15f359SSam Clegg 
8579e15f359SSam Clegg   // init expr for starting offset
8580ff28fa6SDerek Schuff   W->OS << char(wasm::WASM_OPCODE_I32_CONST);
8590ff28fa6SDerek Schuff   encodeSLEB128(InitialTableOffset, W->OS);
8600ff28fa6SDerek Schuff   W->OS << char(wasm::WASM_OPCODE_END);
8619e15f359SSam Clegg 
8620ff28fa6SDerek Schuff   encodeULEB128(TableElems.size(), W->OS);
8639e15f359SSam Clegg   for (uint32_t Elem : TableElems)
8640ff28fa6SDerek Schuff     encodeULEB128(Elem, W->OS);
8659e15f359SSam Clegg 
8669e15f359SSam Clegg   endSection(Section);
8679e15f359SSam Clegg }
8689e15f359SSam Clegg 
869fef8de66SThomas Lively void WasmObjectWriter::writeDataCountSection() {
870fef8de66SThomas Lively   if (DataSegments.empty())
871fef8de66SThomas Lively     return;
872fef8de66SThomas Lively 
873fef8de66SThomas Lively   SectionBookkeeping Section;
874fef8de66SThomas Lively   startSection(Section, wasm::WASM_SEC_DATACOUNT);
8750ff28fa6SDerek Schuff   encodeULEB128(DataSegments.size(), W->OS);
876fef8de66SThomas Lively   endSection(Section);
877fef8de66SThomas Lively }
878fef8de66SThomas Lively 
879e49584a3SSam Clegg uint32_t WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
880457fb0b4SSam Clegg                                             const MCAsmLayout &Layout,
881457fb0b4SSam Clegg                                             ArrayRef<WasmFunction> Functions) {
8829e15f359SSam Clegg   if (Functions.empty())
883e49584a3SSam Clegg     return 0;
8849e15f359SSam Clegg 
8859e15f359SSam Clegg   SectionBookkeeping Section;
8869e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_CODE);
8879e15f359SSam Clegg 
8880ff28fa6SDerek Schuff   encodeULEB128(Functions.size(), W->OS);
8899e15f359SSam Clegg 
8909e15f359SSam Clegg   for (const WasmFunction &Func : Functions) {
891fe6414b0SSam Clegg     auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
8929e15f359SSam Clegg 
8939e15f359SSam Clegg     int64_t Size = 0;
8949e15f359SSam Clegg     if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
8959e15f359SSam Clegg       report_fatal_error(".size expression must be evaluatable");
8969e15f359SSam Clegg 
8970ff28fa6SDerek Schuff     encodeULEB128(Size, W->OS);
8980ff28fa6SDerek Schuff     FuncSection.setSectionOffset(W->OS.tell() - Section.ContentsOffset);
8990ff28fa6SDerek Schuff     Asm.writeSectionData(W->OS, &FuncSection, Layout);
9009e15f359SSam Clegg   }
9019e15f359SSam Clegg 
9029e15f359SSam Clegg   // Apply fixups.
9037ee758d6SSam Clegg   applyRelocations(CodeRelocations, Section.ContentsOffset, Layout);
9049e15f359SSam Clegg 
9059e15f359SSam Clegg   endSection(Section);
906e49584a3SSam Clegg   return Section.Index;
9079e15f359SSam Clegg }
9089e15f359SSam Clegg 
909e49584a3SSam Clegg uint32_t WasmObjectWriter::writeDataSection(const MCAsmLayout &Layout) {
9106c899ba6SSam Clegg   if (DataSegments.empty())
911e49584a3SSam Clegg     return 0;
9129e15f359SSam Clegg 
9139e15f359SSam Clegg   SectionBookkeeping Section;
9149e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_DATA);
9159e15f359SSam Clegg 
9160ff28fa6SDerek Schuff   encodeULEB128(DataSegments.size(), W->OS); // count
9177c395943SSam Clegg 
9186c899ba6SSam Clegg   for (const WasmDataSegment &Segment : DataSegments) {
9190ff28fa6SDerek Schuff     encodeULEB128(Segment.InitFlags, W->OS); // flags
9202e150409SThomas Lively     if (Segment.InitFlags & wasm::WASM_SEGMENT_HAS_MEMINDEX)
9210ff28fa6SDerek Schuff       encodeULEB128(0, W->OS); // memory index
9222e150409SThomas Lively     if ((Segment.InitFlags & wasm::WASM_SEGMENT_IS_PASSIVE) == 0) {
9230ff28fa6SDerek Schuff       W->OS << char(Segment.Offset > INT32_MAX ? wasm::WASM_OPCODE_I64_CONST
9244d135b04SWouter van Oortmerssen                                                : wasm::WASM_OPCODE_I32_CONST);
9250ff28fa6SDerek Schuff       encodeSLEB128(Segment.Offset, W->OS); // offset
9260ff28fa6SDerek Schuff       W->OS << char(wasm::WASM_OPCODE_END);
9272e150409SThomas Lively     }
9280ff28fa6SDerek Schuff     encodeULEB128(Segment.Data.size(), W->OS); // size
9290ff28fa6SDerek Schuff     Segment.Section->setSectionOffset(W->OS.tell() - Section.ContentsOffset);
9300ff28fa6SDerek Schuff     W->OS << Segment.Data; // data
9317c395943SSam Clegg   }
9329e15f359SSam Clegg 
9339e15f359SSam Clegg   // Apply fixups.
9347ee758d6SSam Clegg   applyRelocations(DataRelocations, Section.ContentsOffset, Layout);
9359e15f359SSam Clegg 
9369e15f359SSam Clegg   endSection(Section);
937e49584a3SSam Clegg   return Section.Index;
9389e15f359SSam Clegg }
9399e15f359SSam Clegg 
9406f08c84aSSam Clegg void WasmObjectWriter::writeRelocSection(
9416f08c84aSSam Clegg     uint32_t SectionIndex, StringRef Name,
942f77dc2a8SSam Clegg     std::vector<WasmRelocationEntry> &Relocs) {
9439e15f359SSam Clegg   // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
9449e15f359SSam Clegg   // for descriptions of the reloc sections.
9459e15f359SSam Clegg 
946f77dc2a8SSam Clegg   if (Relocs.empty())
9479e15f359SSam Clegg     return;
9489e15f359SSam Clegg 
949f77dc2a8SSam Clegg   // First, ensure the relocations are sorted in offset order.  In general they
950f77dc2a8SSam Clegg   // should already be sorted since `recordRelocation` is called in offset
951f77dc2a8SSam Clegg   // order, but for the code section we combine many MC sections into single
952f77dc2a8SSam Clegg   // wasm section, and this order is determined by the order of Asm.Symbols()
953f77dc2a8SSam Clegg   // not the sections order.
954efd94c56SFangrui Song   llvm::stable_sort(
955efd94c56SFangrui Song       Relocs, [](const WasmRelocationEntry &A, const WasmRelocationEntry &B) {
956f77dc2a8SSam Clegg         return (A.Offset + A.FixupSection->getSectionOffset()) <
957f77dc2a8SSam Clegg                (B.Offset + B.FixupSection->getSectionOffset());
958f77dc2a8SSam Clegg       });
959f77dc2a8SSam Clegg 
9609e15f359SSam Clegg   SectionBookkeeping Section;
9616f08c84aSSam Clegg   startCustomSection(Section, std::string("reloc.") + Name.str());
9629e15f359SSam Clegg 
9630ff28fa6SDerek Schuff   encodeULEB128(SectionIndex, W->OS);
9640ff28fa6SDerek Schuff   encodeULEB128(Relocs.size(), W->OS);
965f77dc2a8SSam Clegg   for (const WasmRelocationEntry &RelEntry : Relocs) {
966f208f631SHeejin Ahn     uint64_t Offset =
967f208f631SHeejin Ahn         RelEntry.Offset + RelEntry.FixupSection->getSectionOffset();
9686f08c84aSSam Clegg     uint32_t Index = getRelocationIndexValue(RelEntry);
9699e15f359SSam Clegg 
9700ff28fa6SDerek Schuff     W->OS << char(RelEntry.Type);
9710ff28fa6SDerek Schuff     encodeULEB128(Offset, W->OS);
9720ff28fa6SDerek Schuff     encodeULEB128(Index, W->OS);
9736f08c84aSSam Clegg     if (RelEntry.hasAddend())
9740ff28fa6SDerek Schuff       encodeSLEB128(RelEntry.Addend, W->OS);
9759e15f359SSam Clegg   }
9769e15f359SSam Clegg 
9779e15f359SSam Clegg   endSection(Section);
9789e15f359SSam Clegg }
9799e15f359SSam Clegg 
9806a31a0d6SSam Clegg void WasmObjectWriter::writeCustomRelocSections() {
9816a31a0d6SSam Clegg   for (const auto &Sec : CustomSections) {
9826a31a0d6SSam Clegg     auto &Relocations = CustomSectionsRelocations[Sec.Section];
9836a31a0d6SSam Clegg     writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations);
9846a31a0d6SSam Clegg   }
9856a31a0d6SSam Clegg }
9866a31a0d6SSam Clegg 
9879e15f359SSam Clegg void WasmObjectWriter::writeLinkingMetaDataSection(
98886b4a09aSSam Clegg     ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
989ea7caceeSSam Clegg     ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
990ea7caceeSSam Clegg     const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) {
9919e15f359SSam Clegg   SectionBookkeeping Section;
9922322a937SSam Clegg   startCustomSection(Section, "linking");
9930ff28fa6SDerek Schuff   encodeULEB128(wasm::WasmMetadataVersion, W->OS);
9949e15f359SSam Clegg 
9956bb5a41fSSam Clegg   SectionBookkeeping SubSection;
9966c899ba6SSam Clegg   if (SymbolInfos.size() != 0) {
9976c899ba6SSam Clegg     startSection(SubSection, wasm::WASM_SYMBOL_TABLE);
9980ff28fa6SDerek Schuff     encodeULEB128(SymbolInfos.size(), W->OS);
9996c899ba6SSam Clegg     for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) {
10000ff28fa6SDerek Schuff       encodeULEB128(Sym.Kind, W->OS);
10010ff28fa6SDerek Schuff       encodeULEB128(Sym.Flags, W->OS);
10026c899ba6SSam Clegg       switch (Sym.Kind) {
10036c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_FUNCTION:
10046c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_GLOBAL:
1005da419bdbSHeejin Ahn       case wasm::WASM_SYMBOL_TYPE_EVENT:
10060ff28fa6SDerek Schuff         encodeULEB128(Sym.ElementIndex, W->OS);
100729874ceaSDan Gohman         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0 ||
100829874ceaSDan Gohman             (Sym.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0)
10096c899ba6SSam Clegg           writeString(Sym.Name);
10106c899ba6SSam Clegg         break;
10116c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_DATA:
10126c899ba6SSam Clegg         writeString(Sym.Name);
10136c899ba6SSam Clegg         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) {
10140ff28fa6SDerek Schuff           encodeULEB128(Sym.DataRef.Segment, W->OS);
10150ff28fa6SDerek Schuff           encodeULEB128(Sym.DataRef.Offset, W->OS);
10160ff28fa6SDerek Schuff           encodeULEB128(Sym.DataRef.Size, W->OS);
10176c899ba6SSam Clegg         }
10186c899ba6SSam Clegg         break;
10196a31a0d6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_SECTION: {
10206a31a0d6SSam Clegg         const uint32_t SectionIndex =
10216a31a0d6SSam Clegg             CustomSections[Sym.ElementIndex].OutputIndex;
10220ff28fa6SDerek Schuff         encodeULEB128(SectionIndex, W->OS);
10236a31a0d6SSam Clegg         break;
10246a31a0d6SSam Clegg       }
10256c899ba6SSam Clegg       default:
10266c899ba6SSam Clegg         llvm_unreachable("unexpected kind");
10276c899ba6SSam Clegg       }
1028b7787fd0SSam Clegg     }
1029b7787fd0SSam Clegg     endSection(SubSection);
1030b7787fd0SSam Clegg   }
10319e15f359SSam Clegg 
10326c899ba6SSam Clegg   if (DataSegments.size()) {
103363ebb813SSam Clegg     startSection(SubSection, wasm::WASM_SEGMENT_INFO);
10340ff28fa6SDerek Schuff     encodeULEB128(DataSegments.size(), W->OS);
10356c899ba6SSam Clegg     for (const WasmDataSegment &Segment : DataSegments) {
1036d95ed959SSam Clegg       writeString(Segment.Name);
10370ff28fa6SDerek Schuff       encodeULEB128(Segment.Alignment, W->OS);
10380ff28fa6SDerek Schuff       encodeULEB128(Segment.LinkerFlags, W->OS);
103963ebb813SSam Clegg     }
1040d95ed959SSam Clegg     endSection(SubSection);
1041d95ed959SSam Clegg   }
1042d95ed959SSam Clegg 
1043bafe6902SSam Clegg   if (!InitFuncs.empty()) {
1044bafe6902SSam Clegg     startSection(SubSection, wasm::WASM_INIT_FUNCS);
10450ff28fa6SDerek Schuff     encodeULEB128(InitFuncs.size(), W->OS);
1046bafe6902SSam Clegg     for (auto &StartFunc : InitFuncs) {
10470ff28fa6SDerek Schuff       encodeULEB128(StartFunc.first, W->OS);  // priority
10480ff28fa6SDerek Schuff       encodeULEB128(StartFunc.second, W->OS); // function index
1049bafe6902SSam Clegg     }
1050bafe6902SSam Clegg     endSection(SubSection);
1051bafe6902SSam Clegg   }
1052bafe6902SSam Clegg 
1053ea7caceeSSam Clegg   if (Comdats.size()) {
1054ea7caceeSSam Clegg     startSection(SubSection, wasm::WASM_COMDAT_INFO);
10550ff28fa6SDerek Schuff     encodeULEB128(Comdats.size(), W->OS);
1056ea7caceeSSam Clegg     for (const auto &C : Comdats) {
1057ea7caceeSSam Clegg       writeString(C.first);
10580ff28fa6SDerek Schuff       encodeULEB128(0, W->OS); // flags for future use
10590ff28fa6SDerek Schuff       encodeULEB128(C.second.size(), W->OS);
1060ea7caceeSSam Clegg       for (const WasmComdatEntry &Entry : C.second) {
10610ff28fa6SDerek Schuff         encodeULEB128(Entry.Kind, W->OS);
10620ff28fa6SDerek Schuff         encodeULEB128(Entry.Index, W->OS);
1063ea7caceeSSam Clegg       }
1064ea7caceeSSam Clegg     }
1065ea7caceeSSam Clegg     endSection(SubSection);
1066ea7caceeSSam Clegg   }
1067ea7caceeSSam Clegg 
10689e15f359SSam Clegg   endSection(Section);
10699e15f359SSam Clegg }
10709e15f359SSam Clegg 
1071cbda16ebSThomas Lively void WasmObjectWriter::writeCustomSection(WasmCustomSection &CustomSection,
1072cbda16ebSThomas Lively                                           const MCAssembler &Asm,
10736a31a0d6SSam Clegg                                           const MCAsmLayout &Layout) {
1074cfd44a2eSSam Clegg   SectionBookkeeping Section;
10756a31a0d6SSam Clegg   auto *Sec = CustomSection.Section;
10762322a937SSam Clegg   startCustomSection(Section, CustomSection.Name);
10776a31a0d6SSam Clegg 
10780ff28fa6SDerek Schuff   Sec->setSectionOffset(W->OS.tell() - Section.ContentsOffset);
10790ff28fa6SDerek Schuff   Asm.writeSectionData(W->OS, Sec, Layout);
10806a31a0d6SSam Clegg 
10816a31a0d6SSam Clegg   CustomSection.OutputContentsOffset = Section.ContentsOffset;
10826a31a0d6SSam Clegg   CustomSection.OutputIndex = Section.Index;
10836a31a0d6SSam Clegg 
1084cfd44a2eSSam Clegg   endSection(Section);
10856a31a0d6SSam Clegg 
10866a31a0d6SSam Clegg   // Apply fixups.
10874d57fbd0SSam Clegg   auto &Relocations = CustomSectionsRelocations[CustomSection.Section];
10887ee758d6SSam Clegg   applyRelocations(Relocations, CustomSection.OutputContentsOffset, Layout);
10896a31a0d6SSam Clegg }
10906a31a0d6SSam Clegg 
10915e3d33a7SSam Clegg uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm &Symbol) {
10925e3d33a7SSam Clegg   assert(Symbol.isFunction());
10935e3d33a7SSam Clegg   assert(TypeIndices.count(&Symbol));
10945e3d33a7SSam Clegg   return TypeIndices[&Symbol];
10955e3d33a7SSam Clegg }
10965e3d33a7SSam Clegg 
1097da419bdbSHeejin Ahn uint32_t WasmObjectWriter::getEventType(const MCSymbolWasm &Symbol) {
1098da419bdbSHeejin Ahn   assert(Symbol.isEvent());
1099da419bdbSHeejin Ahn   assert(TypeIndices.count(&Symbol));
1100da419bdbSHeejin Ahn   return TypeIndices[&Symbol];
1101da419bdbSHeejin Ahn }
1102da419bdbSHeejin Ahn 
110338b12f5eSHeejin Ahn void WasmObjectWriter::registerFunctionType(const MCSymbolWasm &Symbol) {
11045e3d33a7SSam Clegg   assert(Symbol.isFunction());
11055e3d33a7SSam Clegg 
11064c41fb5aSHeejin Ahn   wasm::WasmSignature S;
11077ee758d6SSam Clegg 
11087ee758d6SSam Clegg   if (auto *Sig = Symbol.getSignature()) {
1109da419bdbSHeejin Ahn     S.Returns = Sig->Returns;
1110da419bdbSHeejin Ahn     S.Params = Sig->Params;
111177a7a380SDerek Schuff   }
11125e3d33a7SSam Clegg 
1113da419bdbSHeejin Ahn   auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
11145e3d33a7SSam Clegg   if (Pair.second)
1115da419bdbSHeejin Ahn     Signatures.push_back(S);
11165e3d33a7SSam Clegg   TypeIndices[&Symbol] = Pair.first->second;
11175e3d33a7SSam Clegg 
1118d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "registerFunctionType: " << Symbol
1119d34e60caSNicola Zaghen                     << " new:" << Pair.second << "\n");
1120d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
11215e3d33a7SSam Clegg }
11225e3d33a7SSam Clegg 
112338b12f5eSHeejin Ahn void WasmObjectWriter::registerEventType(const MCSymbolWasm &Symbol) {
1124da419bdbSHeejin Ahn   assert(Symbol.isEvent());
1125da419bdbSHeejin Ahn 
1126da419bdbSHeejin Ahn   // TODO Currently we don't generate imported exceptions, but if we do, we
1127da419bdbSHeejin Ahn   // should have a way of infering types of imported exceptions.
11284c41fb5aSHeejin Ahn   wasm::WasmSignature S;
1129da419bdbSHeejin Ahn   if (auto *Sig = Symbol.getSignature()) {
1130da419bdbSHeejin Ahn     S.Returns = Sig->Returns;
1131da419bdbSHeejin Ahn     S.Params = Sig->Params;
1132da419bdbSHeejin Ahn   }
1133da419bdbSHeejin Ahn 
1134da419bdbSHeejin Ahn   auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
1135da419bdbSHeejin Ahn   if (Pair.second)
1136da419bdbSHeejin Ahn     Signatures.push_back(S);
1137da419bdbSHeejin Ahn   TypeIndices[&Symbol] = Pair.first->second;
1138da419bdbSHeejin Ahn 
1139da419bdbSHeejin Ahn   LLVM_DEBUG(dbgs() << "registerEventType: " << Symbol << " new:" << Pair.second
1140da419bdbSHeejin Ahn                     << "\n");
1141da419bdbSHeejin Ahn   LLVM_DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
1142da419bdbSHeejin Ahn }
1143da419bdbSHeejin Ahn 
11444d57fbd0SSam Clegg static bool isInSymtab(const MCSymbolWasm &Sym) {
11453ea1c62cSSam Clegg   if (Sym.isUsedInReloc() || Sym.isUsedInInitArray())
11464d57fbd0SSam Clegg     return true;
11474d57fbd0SSam Clegg 
11484d57fbd0SSam Clegg   if (Sym.isComdat() && !Sym.isDefined())
11494d57fbd0SSam Clegg     return false;
11504d57fbd0SSam Clegg 
11513ea1c62cSSam Clegg   if (Sym.isTemporary())
11524d57fbd0SSam Clegg     return false;
11534d57fbd0SSam Clegg 
11544d57fbd0SSam Clegg   if (Sym.isSection())
11554d57fbd0SSam Clegg     return false;
11564d57fbd0SSam Clegg 
11574d57fbd0SSam Clegg   return true;
11584d57fbd0SSam Clegg }
11590ff28fa6SDerek Schuff void WasmObjectWriter::prepareImports(
11600ff28fa6SDerek Schuff     SmallVectorImpl<wasm::WasmImport> &Imports, MCAssembler &Asm,
116118eafb6cSDan Gohman     const MCAsmLayout &Layout) {
1162f950b24aSSam Clegg   // For now, always emit the memory import, since loads and stores are not
1163f950b24aSSam Clegg   // valid without it. In the future, we could perhaps be more clever and omit
1164f950b24aSSam Clegg   // it if there are no loads or stores.
11658defa952SSam Clegg   wasm::WasmImport MemImport;
11661ed3a046SSam Clegg   MemImport.Module = "env";
11671ed3a046SSam Clegg   MemImport.Field = "__linear_memory";
1168f950b24aSSam Clegg   MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
1169fd0964aeSWouter van Oortmerssen   MemImport.Memory.Flags = is64Bit() ? wasm::WASM_LIMITS_FLAG_IS_64
1170fd0964aeSWouter van Oortmerssen                                      : wasm::WASM_LIMITS_FLAG_NONE;
1171f950b24aSSam Clegg   Imports.push_back(MemImport);
1172f950b24aSSam Clegg 
1173f950b24aSSam Clegg   // For now, always emit the table section, since indirect calls are not
1174f950b24aSSam Clegg   // valid without it. In the future, we could perhaps be more clever and omit
1175f950b24aSSam Clegg   // it if there are no indirect calls.
11768defa952SSam Clegg   wasm::WasmImport TableImport;
11771ed3a046SSam Clegg   TableImport.Module = "env";
11781ed3a046SSam Clegg   TableImport.Field = "__indirect_function_table";
1179f950b24aSSam Clegg   TableImport.Kind = wasm::WASM_EXTERNAL_TABLE;
11806a87ddacSThomas Lively   TableImport.Table.ElemType = wasm::WASM_TYPE_FUNCREF;
1181f950b24aSSam Clegg   Imports.push_back(TableImport);
1182f950b24aSSam Clegg 
1183da419bdbSHeejin Ahn   // Populate SignatureIndices, and Imports and WasmIndices for undefined
1184586320c0SNicholas Wilson   // symbols.  This must be done before populating WasmIndices for defined
1185586320c0SNicholas Wilson   // symbols.
118632ce5ca0SDan Gohman   for (const MCSymbol &S : Asm.symbols()) {
118732ce5ca0SDan Gohman     const auto &WS = static_cast<const MCSymbolWasm &>(S);
118832ce5ca0SDan Gohman 
118932ce5ca0SDan Gohman     // Register types for all functions, including those with private linkage
11909f3fe42eSSam Clegg     // (because wasm always needs a type signature).
11917ee758d6SSam Clegg     if (WS.isFunction()) {
11929c7b5808SDominic Chen       const auto *BS = Layout.getBaseSymbol(S);
11939c7b5808SDominic Chen       if (!BS)
11949c7b5808SDominic Chen         report_fatal_error(Twine(S.getName()) +
11959c7b5808SDominic Chen                            ": absolute addressing not supported!");
11969c7b5808SDominic Chen       registerFunctionType(*cast<MCSymbolWasm>(BS));
11977ee758d6SSam Clegg     }
119832ce5ca0SDan Gohman 
1199da419bdbSHeejin Ahn     if (WS.isEvent())
1200da419bdbSHeejin Ahn       registerEventType(WS);
1201da419bdbSHeejin Ahn 
120232ce5ca0SDan Gohman     if (WS.isTemporary())
120332ce5ca0SDan Gohman       continue;
120432ce5ca0SDan Gohman 
120532ce5ca0SDan Gohman     // If the symbol is not defined in this translation unit, import it.
12066c899ba6SSam Clegg     if (!WS.isDefined() && !WS.isComdat()) {
12076c899ba6SSam Clegg       if (WS.isFunction()) {
12088defa952SSam Clegg         wasm::WasmImport Import;
1209f726e445SDan Gohman         Import.Module = WS.getImportModule();
1210f726e445SDan Gohman         Import.Field = WS.getImportName();
121132ce5ca0SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
12128defa952SSam Clegg         Import.SigIndex = getFunctionType(WS);
12136c899ba6SSam Clegg         Imports.push_back(Import);
1214492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
12156c899ba6SSam Clegg         WasmIndices[&WS] = NumFunctionImports++;
12166c899ba6SSam Clegg       } else if (WS.isGlobal()) {
121715f349f7SNicholas Wilson         if (WS.isWeak())
121815f349f7SNicholas Wilson           report_fatal_error("undefined global symbol cannot be weak");
121915f349f7SNicholas Wilson 
12206c899ba6SSam Clegg         wasm::WasmImport Import;
1221f726e445SDan Gohman         Import.Field = WS.getImportName();
122232ce5ca0SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1223492f7529SSam Clegg         Import.Module = WS.getImportModule();
12246c899ba6SSam Clegg         Import.Global = WS.getGlobalType();
12256c899ba6SSam Clegg         Imports.push_back(Import);
1226492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
12276c899ba6SSam Clegg         WasmIndices[&WS] = NumGlobalImports++;
1228da419bdbSHeejin Ahn       } else if (WS.isEvent()) {
1229da419bdbSHeejin Ahn         if (WS.isWeak())
1230da419bdbSHeejin Ahn           report_fatal_error("undefined event symbol cannot be weak");
1231da419bdbSHeejin Ahn 
1232da419bdbSHeejin Ahn         wasm::WasmImport Import;
1233f726e445SDan Gohman         Import.Module = WS.getImportModule();
1234f726e445SDan Gohman         Import.Field = WS.getImportName();
1235da419bdbSHeejin Ahn         Import.Kind = wasm::WASM_EXTERNAL_EVENT;
1236da419bdbSHeejin Ahn         Import.Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
1237da419bdbSHeejin Ahn         Import.Event.SigIndex = getEventType(WS);
1238da419bdbSHeejin Ahn         Imports.push_back(Import);
1239492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
1240da419bdbSHeejin Ahn         WasmIndices[&WS] = NumEventImports++;
124132ce5ca0SDan Gohman       }
124232ce5ca0SDan Gohman     }
124332ce5ca0SDan Gohman   }
124432ce5ca0SDan Gohman 
1245492f7529SSam Clegg   // Add imports for GOT globals
1246492f7529SSam Clegg   for (const MCSymbol &S : Asm.symbols()) {
1247492f7529SSam Clegg     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1248492f7529SSam Clegg     if (WS.isUsedInGOT()) {
1249492f7529SSam Clegg       wasm::WasmImport Import;
1250492f7529SSam Clegg       if (WS.isFunction())
1251492f7529SSam Clegg         Import.Module = "GOT.func";
1252492f7529SSam Clegg       else
1253492f7529SSam Clegg         Import.Module = "GOT.mem";
1254492f7529SSam Clegg       Import.Field = WS.getName();
1255492f7529SSam Clegg       Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1256492f7529SSam Clegg       Import.Global = {wasm::WASM_TYPE_I32, true};
1257492f7529SSam Clegg       Imports.push_back(Import);
1258492f7529SSam Clegg       assert(GOTIndices.count(&WS) == 0);
1259492f7529SSam Clegg       GOTIndices[&WS] = NumGlobalImports++;
1260492f7529SSam Clegg     }
1261492f7529SSam Clegg   }
12620ff28fa6SDerek Schuff }
1263492f7529SSam Clegg 
12640ff28fa6SDerek Schuff uint64_t WasmObjectWriter::writeObject(MCAssembler &Asm,
12650ff28fa6SDerek Schuff                                        const MCAsmLayout &Layout) {
12660ff28fa6SDerek Schuff   support::endian::Writer MainWriter(*OS, support::little);
12670ff28fa6SDerek Schuff   W = &MainWriter;
12680ff28fa6SDerek Schuff   if (IsSplitDwarf) {
12690ff28fa6SDerek Schuff     uint64_t TotalSize = writeOneObject(Asm, Layout, DwoMode::NonDwoOnly);
12700ff28fa6SDerek Schuff     assert(DwoOS);
12710ff28fa6SDerek Schuff     support::endian::Writer DwoWriter(*DwoOS, support::little);
12720ff28fa6SDerek Schuff     W = &DwoWriter;
12730ff28fa6SDerek Schuff     return TotalSize + writeOneObject(Asm, Layout, DwoMode::DwoOnly);
12740ff28fa6SDerek Schuff   } else {
12750ff28fa6SDerek Schuff     return writeOneObject(Asm, Layout, DwoMode::AllSections);
12760ff28fa6SDerek Schuff   }
12770ff28fa6SDerek Schuff }
12780ff28fa6SDerek Schuff 
12790ff28fa6SDerek Schuff uint64_t WasmObjectWriter::writeOneObject(MCAssembler &Asm,
12800ff28fa6SDerek Schuff                                           const MCAsmLayout &Layout,
12810ff28fa6SDerek Schuff                                           DwoMode Mode) {
12820ff28fa6SDerek Schuff   uint64_t StartOffset = W->OS.tell();
12830ff28fa6SDerek Schuff   SectionCount = 0;
12840ff28fa6SDerek Schuff   CustomSections.clear();
12850ff28fa6SDerek Schuff 
12860ff28fa6SDerek Schuff   LLVM_DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
12870ff28fa6SDerek Schuff 
12880ff28fa6SDerek Schuff   // Collect information from the available symbols.
12890ff28fa6SDerek Schuff   SmallVector<WasmFunction, 4> Functions;
12900ff28fa6SDerek Schuff   SmallVector<uint32_t, 4> TableElems;
12910ff28fa6SDerek Schuff   SmallVector<wasm::WasmImport, 4> Imports;
12920ff28fa6SDerek Schuff   SmallVector<wasm::WasmExport, 4> Exports;
12930ff28fa6SDerek Schuff   SmallVector<wasm::WasmEventType, 1> Events;
12940ff28fa6SDerek Schuff   SmallVector<wasm::WasmGlobal, 1> Globals;
12950ff28fa6SDerek Schuff   SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos;
12960ff28fa6SDerek Schuff   SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
12970ff28fa6SDerek Schuff   std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
12980ff28fa6SDerek Schuff   uint64_t DataSize = 0;
12990ff28fa6SDerek Schuff   if (Mode != DwoMode::DwoOnly) {
13000ff28fa6SDerek Schuff     prepareImports(Imports, Asm, Layout);
13010ff28fa6SDerek Schuff   }
13024d57fbd0SSam Clegg   // Populate DataSegments and CustomSections, which must be done before
13034d57fbd0SSam Clegg   // populating DataLocations.
1304759631c7SSam Clegg   for (MCSection &Sec : Asm) {
1305759631c7SSam Clegg     auto &Section = static_cast<MCSectionWasm &>(Sec);
13067d1ff446SFangrui Song     StringRef SectionName = Section.getName();
1307759631c7SSam Clegg 
13080ff28fa6SDerek Schuff     if (Mode == DwoMode::NonDwoOnly && isDwoSection(Sec))
13090ff28fa6SDerek Schuff       continue;
13100ff28fa6SDerek Schuff     if (Mode == DwoMode::DwoOnly && !isDwoSection(Sec))
13110ff28fa6SDerek Schuff       continue;
13120ff28fa6SDerek Schuff 
1313bafe6902SSam Clegg     // .init_array sections are handled specially elsewhere.
13144d57fbd0SSam Clegg     if (SectionName.startswith(".init_array"))
1315bafe6902SSam Clegg       continue;
1316bafe6902SSam Clegg 
13174d57fbd0SSam Clegg     // Code is handled separately
13184d57fbd0SSam Clegg     if (Section.getKind().isText())
13194d57fbd0SSam Clegg       continue;
13204d57fbd0SSam Clegg 
13214d57fbd0SSam Clegg     if (Section.isWasmData()) {
1322329e76d5SSam Clegg       uint32_t SegmentIndex = DataSegments.size();
1323759631c7SSam Clegg       DataSize = alignTo(DataSize, Section.getAlignment());
1324759631c7SSam Clegg       DataSegments.emplace_back();
1325759631c7SSam Clegg       WasmDataSegment &Segment = DataSegments.back();
13264d57fbd0SSam Clegg       Segment.Name = SectionName;
13279b49f36aSSimon Pilgrim       Segment.InitFlags =
13289b49f36aSSimon Pilgrim           Section.getPassive() ? (uint32_t)wasm::WASM_SEGMENT_IS_PASSIVE : 0;
1329759631c7SSam Clegg       Segment.Offset = DataSize;
1330759631c7SSam Clegg       Segment.Section = &Section;
133163ebb813SSam Clegg       addData(Segment.Data, Section);
133256c587adSSam Clegg       Segment.Alignment = Log2_32(Section.getAlignment());
13332e150409SThomas Lively       Segment.LinkerFlags = 0;
1334759631c7SSam Clegg       DataSize += Segment.Data.size();
13356c899ba6SSam Clegg       Section.setSegmentIndex(SegmentIndex);
1336ea7caceeSSam Clegg 
1337ea7caceeSSam Clegg       if (const MCSymbolWasm *C = Section.getGroup()) {
1338ea7caceeSSam Clegg         Comdats[C->getName()].emplace_back(
1339329e76d5SSam Clegg             WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
1340ea7caceeSSam Clegg       }
13414d57fbd0SSam Clegg     } else {
13424d57fbd0SSam Clegg       // Create custom sections
13434d57fbd0SSam Clegg       assert(Sec.getKind().isMetadata());
13444d57fbd0SSam Clegg 
13454d57fbd0SSam Clegg       StringRef Name = SectionName;
13464d57fbd0SSam Clegg 
13474d57fbd0SSam Clegg       // For user-defined custom sections, strip the prefix
13484d57fbd0SSam Clegg       if (Name.startswith(".custom_section."))
13494d57fbd0SSam Clegg         Name = Name.substr(strlen(".custom_section."));
13504d57fbd0SSam Clegg 
13514d57fbd0SSam Clegg       MCSymbol *Begin = Sec.getBeginSymbol();
1352fb807d4dSSam Clegg       if (Begin) {
13534d57fbd0SSam Clegg         WasmIndices[cast<MCSymbolWasm>(Begin)] = CustomSections.size();
1354b210c64bSSam Clegg         if (SectionName != Begin->getName())
1355fb807d4dSSam Clegg           report_fatal_error("section name and begin symbol should match: " +
1356b210c64bSSam Clegg                              Twine(SectionName));
1357fb807d4dSSam Clegg       }
1358cbda16ebSThomas Lively 
1359f6f4f843SThomas Lively       // Separate out the producers and target features sections
1360cbda16ebSThomas Lively       if (Name == "producers") {
13610eaee545SJonas Devlieghere         ProducersSection = std::make_unique<WasmCustomSection>(Name, &Section);
1362cbda16ebSThomas Lively         continue;
1363cbda16ebSThomas Lively       }
1364f6f4f843SThomas Lively       if (Name == "target_features") {
1365f6f4f843SThomas Lively         TargetFeaturesSection =
13660eaee545SJonas Devlieghere             std::make_unique<WasmCustomSection>(Name, &Section);
1367f6f4f843SThomas Lively         continue;
1368f6f4f843SThomas Lively       }
1369cbda16ebSThomas Lively 
13704d57fbd0SSam Clegg       CustomSections.emplace_back(Name, &Section);
1371759631c7SSam Clegg     }
13726a31a0d6SSam Clegg   }
13736a31a0d6SSam Clegg 
1374586320c0SNicholas Wilson   // Populate WasmIndices and DataLocations for defined symbols.
1375d934cb88SDan Gohman   for (const MCSymbol &S : Asm.symbols()) {
1376d934cb88SDan Gohman     // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1377d934cb88SDan Gohman     // or used in relocations.
1378d934cb88SDan Gohman     if (S.isTemporary() && S.getName().empty())
1379d934cb88SDan Gohman       continue;
1380b7787fd0SSam Clegg 
1381d934cb88SDan Gohman     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1382d34e60caSNicola Zaghen     LLVM_DEBUG(
1383d34e60caSNicola Zaghen         dbgs() << "MCSymbol: " << toString(WS.getType()) << " '" << S << "'"
1384d34e60caSNicola Zaghen                << " isDefined=" << S.isDefined() << " isExternal="
1385d34e60caSNicola Zaghen                << S.isExternal() << " isTemporary=" << S.isTemporary()
1386d34e60caSNicola Zaghen                << " isWeak=" << WS.isWeak() << " isHidden=" << WS.isHidden()
1387b7787fd0SSam Clegg                << " isVariable=" << WS.isVariable() << "\n");
1388b7787fd0SSam Clegg 
13895e3d33a7SSam Clegg     if (WS.isVariable())
13905e3d33a7SSam Clegg       continue;
13916c899ba6SSam Clegg     if (WS.isComdat() && !WS.isDefined())
13926c899ba6SSam Clegg       continue;
1393b7787fd0SSam Clegg 
1394d934cb88SDan Gohman     if (WS.isFunction()) {
13956c899ba6SSam Clegg       unsigned Index;
1396cd65f698SSam Clegg       if (WS.isDefined()) {
1397b7787fd0SSam Clegg         if (WS.getOffset() != 0)
1398b7787fd0SSam Clegg           report_fatal_error(
1399b7787fd0SSam Clegg               "function sections must contain one function each");
1400b7787fd0SSam Clegg 
140118c56a07SHeejin Ahn         if (WS.getSize() == nullptr)
1402b7787fd0SSam Clegg           report_fatal_error(
1403b7787fd0SSam Clegg               "function symbols must have a size set with .size");
1404b7787fd0SSam Clegg 
14056c899ba6SSam Clegg         // A definition. Write out the function body.
14069f3fe42eSSam Clegg         Index = NumFunctionImports + Functions.size();
1407d934cb88SDan Gohman         WasmFunction Func;
1408da419bdbSHeejin Ahn         Func.SigIndex = getFunctionType(WS);
1409d934cb88SDan Gohman         Func.Sym = &WS;
14106c899ba6SSam Clegg         WasmIndices[&WS] = Index;
1411d934cb88SDan Gohman         Functions.push_back(Func);
14126c899ba6SSam Clegg 
14136c899ba6SSam Clegg         auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
14146c899ba6SSam Clegg         if (const MCSymbolWasm *C = Section.getGroup()) {
14156c899ba6SSam Clegg           Comdats[C->getName()].emplace_back(
14166c899ba6SSam Clegg               WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
14176c899ba6SSam Clegg         }
1418881d8778SSam Clegg 
1419881d8778SSam Clegg         if (WS.hasExportName()) {
1420881d8778SSam Clegg           wasm::WasmExport Export;
1421881d8778SSam Clegg           Export.Name = WS.getExportName();
1422881d8778SSam Clegg           Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1423881d8778SSam Clegg           Export.Index = Index;
1424881d8778SSam Clegg           Exports.push_back(Export);
1425881d8778SSam Clegg         }
1426d934cb88SDan Gohman       } else {
1427d934cb88SDan Gohman         // An import; the index was assigned above.
14286c899ba6SSam Clegg         Index = WasmIndices.find(&WS)->second;
1429d934cb88SDan Gohman       }
1430d934cb88SDan Gohman 
1431d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> function index: " << Index << "\n");
1432da419bdbSHeejin Ahn 
14336c899ba6SSam Clegg     } else if (WS.isData()) {
1434f3feb6adSWouter van Oortmerssen       if (!isInSymtab(WS))
1435c38e947eSSam Clegg         continue;
1436c38e947eSSam Clegg 
14376c899ba6SSam Clegg       if (!WS.isDefined()) {
1438d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "  -> segment index: -1"
1439d34e60caSNicola Zaghen                           << "\n");
1440fe6414b0SSam Clegg         continue;
14416c899ba6SSam Clegg       }
1442fe6414b0SSam Clegg 
1443d934cb88SDan Gohman       if (!WS.getSize())
1444c38e947eSSam Clegg         report_fatal_error("data symbols must have a size set with .size: " +
1445c38e947eSSam Clegg                            WS.getName());
1446d934cb88SDan Gohman 
1447d934cb88SDan Gohman       int64_t Size = 0;
1448d934cb88SDan Gohman       if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1449d934cb88SDan Gohman         report_fatal_error(".size expression must be evaluatable");
1450d934cb88SDan Gohman 
1451759631c7SSam Clegg       auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
1452079cba04SSam Clegg       if (!DataSection.isWasmData())
1453079cba04SSam Clegg         report_fatal_error("data symbols must live in a data section: " +
1454079cba04SSam Clegg                            WS.getName());
14557c395943SSam Clegg 
14566c899ba6SSam Clegg       // For each data symbol, export it in the symtab as a reference to the
14576c899ba6SSam Clegg       // corresponding Wasm data segment.
14586c899ba6SSam Clegg       wasm::WasmDataReference Ref = wasm::WasmDataReference{
14593b29376eSWouter van Oortmerssen           DataSection.getSegmentIndex(), Layout.getSymbolOffset(WS),
14603b29376eSWouter van Oortmerssen           static_cast<uint64_t>(Size)};
14616c899ba6SSam Clegg       DataLocations[&WS] = Ref;
1462d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> segment index: " << Ref.Segment << "\n");
1463da419bdbSHeejin Ahn 
1464a165f2d6SSam Clegg     } else if (WS.isGlobal()) {
14656c899ba6SSam Clegg       // A "true" Wasm global (currently just __stack_pointer)
14660a6c4d8dSSam Clegg       if (WS.isDefined()) {
14670a6c4d8dSSam Clegg         assert(WasmIndices.count(&WS) == 0);
14680a6c4d8dSSam Clegg         wasm::WasmGlobal Global;
14690a6c4d8dSSam Clegg         Global.Type = WS.getGlobalType();
14700a6c4d8dSSam Clegg         Global.Index = NumGlobalImports + Globals.size();
14710a6c4d8dSSam Clegg         switch (Global.Type.Type) {
14720a6c4d8dSSam Clegg         case wasm::WASM_TYPE_I32:
14730a6c4d8dSSam Clegg           Global.InitExpr.Opcode = wasm::WASM_OPCODE_I32_CONST;
14740a6c4d8dSSam Clegg           break;
14750a6c4d8dSSam Clegg         case wasm::WASM_TYPE_I64:
14760a6c4d8dSSam Clegg           Global.InitExpr.Opcode = wasm::WASM_OPCODE_I64_CONST;
14770a6c4d8dSSam Clegg           break;
14780a6c4d8dSSam Clegg         case wasm::WASM_TYPE_F32:
14790a6c4d8dSSam Clegg           Global.InitExpr.Opcode = wasm::WASM_OPCODE_F32_CONST;
14800a6c4d8dSSam Clegg           break;
14810a6c4d8dSSam Clegg         case wasm::WASM_TYPE_F64:
14820a6c4d8dSSam Clegg           Global.InitExpr.Opcode = wasm::WASM_OPCODE_F64_CONST;
14830a6c4d8dSSam Clegg           break;
148479aad89dSSam Clegg         case wasm::WASM_TYPE_EXTERNREF:
148579aad89dSSam Clegg           Global.InitExpr.Opcode = wasm::WASM_OPCODE_REF_NULL;
148679aad89dSSam Clegg           break;
14870a6c4d8dSSam Clegg         default:
14880a6c4d8dSSam Clegg           llvm_unreachable("unexpected type");
14890a6c4d8dSSam Clegg         }
14900a6c4d8dSSam Clegg         WasmIndices[&WS] = Global.Index;
14910a6c4d8dSSam Clegg         Globals.push_back(Global);
14920a6c4d8dSSam Clegg       } else {
1493545932beSEric Christopher         // An import; the index was assigned above
1494d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "  -> global index: "
1495d34e60caSNicola Zaghen                           << WasmIndices.find(&WS)->second << "\n");
14960a6c4d8dSSam Clegg       }
1497da419bdbSHeejin Ahn     } else if (WS.isEvent()) {
1498da419bdbSHeejin Ahn       // C++ exception symbol (__cpp_exception)
1499da419bdbSHeejin Ahn       unsigned Index;
1500da419bdbSHeejin Ahn       if (WS.isDefined()) {
15010a6c4d8dSSam Clegg         assert(WasmIndices.count(&WS) == 0);
1502da419bdbSHeejin Ahn         Index = NumEventImports + Events.size();
1503da419bdbSHeejin Ahn         wasm::WasmEventType Event;
1504da419bdbSHeejin Ahn         Event.SigIndex = getEventType(WS);
1505da419bdbSHeejin Ahn         Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
1506da419bdbSHeejin Ahn         WasmIndices[&WS] = Index;
1507da419bdbSHeejin Ahn         Events.push_back(Event);
1508da419bdbSHeejin Ahn       } else {
1509da419bdbSHeejin Ahn         // An import; the index was assigned above.
1510492f7529SSam Clegg         assert(WasmIndices.count(&WS) > 0);
1511da419bdbSHeejin Ahn       }
1512da419bdbSHeejin Ahn       LLVM_DEBUG(dbgs() << "  -> event index: " << WasmIndices.find(&WS)->second
1513da419bdbSHeejin Ahn                         << "\n");
1514da419bdbSHeejin Ahn 
1515a165f2d6SSam Clegg     } else {
1516a165f2d6SSam Clegg       assert(WS.isSection());
1517d934cb88SDan Gohman     }
1518d934cb88SDan Gohman   }
1519d934cb88SDan Gohman 
1520586320c0SNicholas Wilson   // Populate WasmIndices and DataLocations for aliased symbols.  We need to
1521586320c0SNicholas Wilson   // process these in a separate pass because we need to have processed the
1522586320c0SNicholas Wilson   // target of the alias before the alias itself and the symbols are not
1523586320c0SNicholas Wilson   // necessarily ordered in this way.
1524b7787fd0SSam Clegg   for (const MCSymbol &S : Asm.symbols()) {
1525b7787fd0SSam Clegg     if (!S.isVariable())
1526b7787fd0SSam Clegg       continue;
152731a2c809SSam Clegg 
1528cd65f698SSam Clegg     assert(S.isDefined());
1529b7787fd0SSam Clegg 
15309c7b5808SDominic Chen     const auto *BS = Layout.getBaseSymbol(S);
15319c7b5808SDominic Chen     if (!BS)
15329c7b5808SDominic Chen       report_fatal_error(Twine(S.getName()) +
15339c7b5808SDominic Chen                          ": absolute addressing not supported!");
15349c7b5808SDominic Chen     const MCSymbolWasm *Base = cast<MCSymbolWasm>(BS);
15357ee758d6SSam Clegg 
15365e3d33a7SSam Clegg     // Find the target symbol of this weak alias and export that index
1537aff1c4dfSSam Clegg     const auto &WS = static_cast<const MCSymbolWasm &>(S);
15387ee758d6SSam Clegg     LLVM_DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *Base << "'\n");
1539b7787fd0SSam Clegg 
15407ee758d6SSam Clegg     if (Base->isFunction()) {
15417ee758d6SSam Clegg       assert(WasmIndices.count(Base) > 0);
15427ee758d6SSam Clegg       uint32_t WasmIndex = WasmIndices.find(Base)->second;
1543492f7529SSam Clegg       assert(WasmIndices.count(&WS) == 0);
15446c899ba6SSam Clegg       WasmIndices[&WS] = WasmIndex;
1545d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> index:" << WasmIndex << "\n");
15467ee758d6SSam Clegg     } else if (Base->isData()) {
15477ee758d6SSam Clegg       auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
15487ee758d6SSam Clegg       uint64_t Offset = Layout.getSymbolOffset(S);
15497ee758d6SSam Clegg       int64_t Size = 0;
15507ee758d6SSam Clegg       // For data symbol alias we use the size of the base symbol as the
15517ee758d6SSam Clegg       // size of the alias.  When an offset from the base is involved this
15527ee758d6SSam Clegg       // can result in a offset + size goes past the end of the data section
15537ee758d6SSam Clegg       // which out object format doesn't support.  So we must clamp it.
15547ee758d6SSam Clegg       if (!Base->getSize()->evaluateAsAbsolute(Size, Layout))
15557ee758d6SSam Clegg         report_fatal_error(".size expression must be evaluatable");
15567ee758d6SSam Clegg       const WasmDataSegment &Segment =
15577ee758d6SSam Clegg           DataSegments[DataSection.getSegmentIndex()];
15587ee758d6SSam Clegg       Size =
15597ee758d6SSam Clegg           std::min(static_cast<uint64_t>(Size), Segment.Data.size() - Offset);
15607ee758d6SSam Clegg       wasm::WasmDataReference Ref = wasm::WasmDataReference{
15617ee758d6SSam Clegg           DataSection.getSegmentIndex(),
15627ee758d6SSam Clegg           static_cast<uint32_t>(Layout.getSymbolOffset(S)),
15637ee758d6SSam Clegg           static_cast<uint32_t>(Size)};
15646c899ba6SSam Clegg       DataLocations[&WS] = Ref;
1565d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> index:" << Ref.Segment << "\n");
15666c899ba6SSam Clegg     } else {
1567da419bdbSHeejin Ahn       report_fatal_error("don't yet support global/event aliases");
15686c899ba6SSam Clegg     }
1569586320c0SNicholas Wilson   }
157031a2c809SSam Clegg 
1571586320c0SNicholas Wilson   // Finally, populate the symbol table itself, in its "natural" order.
1572586320c0SNicholas Wilson   for (const MCSymbol &S : Asm.symbols()) {
1573586320c0SNicholas Wilson     const auto &WS = static_cast<const MCSymbolWasm &>(S);
157425d8e68bSSam Clegg     if (!isInSymtab(WS)) {
157518c56a07SHeejin Ahn       WS.setIndex(InvalidIndex);
1576586320c0SNicholas Wilson       continue;
157725d8e68bSSam Clegg     }
1578d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "adding to symtab: " << WS << "\n");
1579586320c0SNicholas Wilson 
1580586320c0SNicholas Wilson     uint32_t Flags = 0;
1581586320c0SNicholas Wilson     if (WS.isWeak())
1582586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_BINDING_WEAK;
1583586320c0SNicholas Wilson     if (WS.isHidden())
1584586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN;
1585586320c0SNicholas Wilson     if (!WS.isExternal() && WS.isDefined())
1586586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;
1587586320c0SNicholas Wilson     if (WS.isUndefined())
1588586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_UNDEFINED;
1589da84b688SDan Gohman     if (WS.isNoStrip()) {
1590da84b688SDan Gohman       Flags |= wasm::WASM_SYMBOL_NO_STRIP;
1591da84b688SDan Gohman       if (isEmscripten()) {
1592d6ef8da3SSam Clegg         Flags |= wasm::WASM_SYMBOL_EXPORTED;
1593da84b688SDan Gohman       }
1594da84b688SDan Gohman     }
1595b4f4e370SSam Clegg     if (WS.hasImportName())
159629874ceaSDan Gohman       Flags |= wasm::WASM_SYMBOL_EXPLICIT_NAME;
1597881d8778SSam Clegg     if (WS.hasExportName())
1598881d8778SSam Clegg       Flags |= wasm::WASM_SYMBOL_EXPORTED;
1599586320c0SNicholas Wilson 
1600586320c0SNicholas Wilson     wasm::WasmSymbolInfo Info;
1601586320c0SNicholas Wilson     Info.Name = WS.getName();
1602586320c0SNicholas Wilson     Info.Kind = WS.getType();
1603586320c0SNicholas Wilson     Info.Flags = Flags;
16044d57fbd0SSam Clegg     if (!WS.isData()) {
16054d57fbd0SSam Clegg       assert(WasmIndices.count(&WS) > 0);
1606586320c0SNicholas Wilson       Info.ElementIndex = WasmIndices.find(&WS)->second;
16074d57fbd0SSam Clegg     } else if (WS.isDefined()) {
16084d57fbd0SSam Clegg       assert(DataLocations.count(&WS) > 0);
1609586320c0SNicholas Wilson       Info.DataRef = DataLocations.find(&WS)->second;
16104d57fbd0SSam Clegg     }
161125d8e68bSSam Clegg     WS.setIndex(SymbolInfos.size());
1612586320c0SNicholas Wilson     SymbolInfos.emplace_back(Info);
1613b7787fd0SSam Clegg   }
1614b7787fd0SSam Clegg 
16156006e091SSam Clegg   {
16166006e091SSam Clegg     auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
1617f9edbe95SSam Clegg       // Functions referenced by a relocation need to put in the table.  This is
1618f9edbe95SSam Clegg       // purely to make the object file's provisional values readable, and is
1619f9edbe95SSam Clegg       // ignored by the linker, which re-calculates the relocations itself.
1620d1152a26SSam Clegg       if (Rel.Type != wasm::R_WASM_TABLE_INDEX_I32 &&
1621cc1b9b68SWouter van Oortmerssen           Rel.Type != wasm::R_WASM_TABLE_INDEX_I64 &&
162281443ac1SSam Clegg           Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB &&
1623cc1b9b68SWouter van Oortmerssen           Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB64 &&
162481443ac1SSam Clegg           Rel.Type != wasm::R_WASM_TABLE_INDEX_REL_SLEB)
1625f9edbe95SSam Clegg         return;
1626f9edbe95SSam Clegg       assert(Rel.Symbol->isFunction());
16277ee758d6SSam Clegg       const MCSymbolWasm *Base =
16287ee758d6SSam Clegg           cast<MCSymbolWasm>(Layout.getBaseSymbol(*Rel.Symbol));
16297ee758d6SSam Clegg       uint32_t FunctionIndex = WasmIndices.find(Base)->second;
163018c56a07SHeejin Ahn       uint32_t TableIndex = TableElems.size() + InitialTableOffset;
16317ee758d6SSam Clegg       if (TableIndices.try_emplace(Base, TableIndex).second) {
16327ee758d6SSam Clegg         LLVM_DEBUG(dbgs() << "  -> adding " << Base->getName()
1633f9edbe95SSam Clegg                           << " to table: " << TableIndex << "\n");
16346c899ba6SSam Clegg         TableElems.push_back(FunctionIndex);
16357ee758d6SSam Clegg         registerFunctionType(*Base);
16366006e091SSam Clegg       }
16376006e091SSam Clegg     };
1638970d02c4SDan Gohman 
16396006e091SSam Clegg     for (const WasmRelocationEntry &RelEntry : CodeRelocations)
16406006e091SSam Clegg       HandleReloc(RelEntry);
16416006e091SSam Clegg     for (const WasmRelocationEntry &RelEntry : DataRelocations)
16426006e091SSam Clegg       HandleReloc(RelEntry);
1643d934cb88SDan Gohman   }
1644d934cb88SDan Gohman 
1645bafe6902SSam Clegg   // Translate .init_array section contents into start functions.
1646bafe6902SSam Clegg   for (const MCSection &S : Asm) {
1647bafe6902SSam Clegg     const auto &WS = static_cast<const MCSectionWasm &>(S);
16487d1ff446SFangrui Song     if (WS.getName().startswith(".fini_array"))
1649bafe6902SSam Clegg       report_fatal_error(".fini_array sections are unsupported");
16507d1ff446SFangrui Song     if (!WS.getName().startswith(".init_array"))
1651bafe6902SSam Clegg       continue;
1652bafe6902SSam Clegg     if (WS.getFragmentList().empty())
1653bafe6902SSam Clegg       continue;
1654b210c64bSSam Clegg 
1655b210c64bSSam Clegg     // init_array is expected to contain a single non-empty data fragment
1656b210c64bSSam Clegg     if (WS.getFragmentList().size() != 3)
1657bafe6902SSam Clegg       report_fatal_error("only one .init_array section fragment supported");
1658b210c64bSSam Clegg 
1659b210c64bSSam Clegg     auto IT = WS.begin();
1660b210c64bSSam Clegg     const MCFragment &EmptyFrag = *IT;
1661b210c64bSSam Clegg     if (EmptyFrag.getKind() != MCFragment::FT_Data)
1662b210c64bSSam Clegg       report_fatal_error(".init_array section should be aligned");
1663b210c64bSSam Clegg 
1664b210c64bSSam Clegg     IT = std::next(IT);
1665b210c64bSSam Clegg     const MCFragment &AlignFrag = *IT;
1666bafe6902SSam Clegg     if (AlignFrag.getKind() != MCFragment::FT_Align)
1667bafe6902SSam Clegg       report_fatal_error(".init_array section should be aligned");
1668bafe6902SSam Clegg     if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
1669bafe6902SSam Clegg       report_fatal_error(".init_array section should be aligned for pointers");
1670b210c64bSSam Clegg 
1671b210c64bSSam Clegg     const MCFragment &Frag = *std::next(IT);
1672bafe6902SSam Clegg     if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1673bafe6902SSam Clegg       report_fatal_error("only data supported in .init_array section");
1674b210c64bSSam Clegg 
1675bafe6902SSam Clegg     uint16_t Priority = UINT16_MAX;
16764d57fbd0SSam Clegg     unsigned PrefixLength = strlen(".init_array");
16777d1ff446SFangrui Song     if (WS.getName().size() > PrefixLength) {
16787d1ff446SFangrui Song       if (WS.getName()[PrefixLength] != '.')
1679f208f631SHeejin Ahn         report_fatal_error(
1680f208f631SHeejin Ahn             ".init_array section priority should start with '.'");
16817d1ff446SFangrui Song       if (WS.getName().substr(PrefixLength + 1).getAsInteger(10, Priority))
1682bafe6902SSam Clegg         report_fatal_error("invalid .init_array section priority");
1683bafe6902SSam Clegg     }
1684bafe6902SSam Clegg     const auto &DataFrag = cast<MCDataFragment>(Frag);
1685bafe6902SSam Clegg     const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1686f208f631SHeejin Ahn     for (const uint8_t *
168718c56a07SHeejin Ahn              P = (const uint8_t *)Contents.data(),
168818c56a07SHeejin Ahn             *End = (const uint8_t *)Contents.data() + Contents.size();
168918c56a07SHeejin Ahn          P != End; ++P) {
169018c56a07SHeejin Ahn       if (*P != 0)
1691bafe6902SSam Clegg         report_fatal_error("non-symbolic data in .init_array section");
1692bafe6902SSam Clegg     }
1693bafe6902SSam Clegg     for (const MCFixup &Fixup : DataFrag.getFixups()) {
1694f208f631SHeejin Ahn       assert(Fixup.getKind() ==
1695f208f631SHeejin Ahn              MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
1696bafe6902SSam Clegg       const MCExpr *Expr = Fixup.getValue();
16978fffa1dfSSam Clegg       auto *SymRef = dyn_cast<MCSymbolRefExpr>(Expr);
16988fffa1dfSSam Clegg       if (!SymRef)
1699bafe6902SSam Clegg         report_fatal_error("fixups in .init_array should be symbol references");
17008fffa1dfSSam Clegg       const auto &TargetSym = cast<const MCSymbolWasm>(SymRef->getSymbol());
17018fffa1dfSSam Clegg       if (TargetSym.getIndex() == InvalidIndex)
17023ea1c62cSSam Clegg         report_fatal_error("symbols in .init_array should exist in symtab");
17038fffa1dfSSam Clegg       if (!TargetSym.isFunction())
17048fffa1dfSSam Clegg         report_fatal_error("symbols in .init_array should be for functions");
170525d8e68bSSam Clegg       InitFuncs.push_back(
17068fffa1dfSSam Clegg           std::make_pair(Priority, TargetSym.getIndex()));
1707bafe6902SSam Clegg     }
1708bafe6902SSam Clegg   }
1709bafe6902SSam Clegg 
171018eafb6cSDan Gohman   // Write out the Wasm header.
171118eafb6cSDan Gohman   writeHeader(Asm);
171218eafb6cSDan Gohman 
17130ff28fa6SDerek Schuff   uint32_t CodeSectionIndex, DataSectionIndex;
17140ff28fa6SDerek Schuff   if (Mode != DwoMode::DwoOnly) {
1715da419bdbSHeejin Ahn     writeTypeSection(Signatures);
1716f950b24aSSam Clegg     writeImportSection(Imports, DataSize, TableElems.size());
17179e15f359SSam Clegg     writeFunctionSection(Functions);
1718f950b24aSSam Clegg     // Skip the "table" section; we import the table instead.
1719f950b24aSSam Clegg     // Skip the "memory" section; we import the memory instead.
1720da419bdbSHeejin Ahn     writeEventSection(Events);
17210a6c4d8dSSam Clegg     writeGlobalSection(Globals);
17229e15f359SSam Clegg     writeExportSection(Exports);
17239e15f359SSam Clegg     writeElemSection(TableElems);
1724fef8de66SThomas Lively     writeDataCountSection();
17250ff28fa6SDerek Schuff 
17260ff28fa6SDerek Schuff     CodeSectionIndex = writeCodeSection(Asm, Layout, Functions);
17270ff28fa6SDerek Schuff     DataSectionIndex = writeDataSection(Layout);
17280ff28fa6SDerek Schuff   }
17290ff28fa6SDerek Schuff 
17300ff28fa6SDerek Schuff   for (auto &CustomSection : CustomSections) {
1731cbda16ebSThomas Lively     writeCustomSection(CustomSection, Asm, Layout);
17320ff28fa6SDerek Schuff   }
17330ff28fa6SDerek Schuff 
17340ff28fa6SDerek Schuff   if (Mode != DwoMode::DwoOnly) {
1735c22bfb6bSNicholas Wilson     writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats);
17360ff28fa6SDerek Schuff 
17376f08c84aSSam Clegg     writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations);
17386f08c84aSSam Clegg     writeRelocSection(DataSectionIndex, "DATA", DataRelocations);
17390ff28fa6SDerek Schuff   }
17406a31a0d6SSam Clegg   writeCustomRelocSections();
1741cbda16ebSThomas Lively   if (ProducersSection)
1742cbda16ebSThomas Lively     writeCustomSection(*ProducersSection, Asm, Layout);
1743f6f4f843SThomas Lively   if (TargetFeaturesSection)
1744f6f4f843SThomas Lively     writeCustomSection(*TargetFeaturesSection, Asm, Layout);
1745970d02c4SDan Gohman 
1746d934cb88SDan Gohman   // TODO: Translate the .comment section to the output.
17470ff28fa6SDerek Schuff   return W->OS.tell() - StartOffset;
174818eafb6cSDan Gohman }
174918eafb6cSDan Gohman 
175060fbc7ccSLang Hames std::unique_ptr<MCObjectWriter>
17511301a878SLang Hames llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
175218eafb6cSDan Gohman                              raw_pwrite_stream &OS) {
17530eaee545SJonas Devlieghere   return std::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
175418eafb6cSDan Gohman }
17550ff28fa6SDerek Schuff 
17560ff28fa6SDerek Schuff std::unique_ptr<MCObjectWriter>
17570ff28fa6SDerek Schuff llvm::createWasmDwoObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
17580ff28fa6SDerek Schuff                                 raw_pwrite_stream &OS,
17590ff28fa6SDerek Schuff                                 raw_pwrite_stream &DwoOS) {
17600ff28fa6SDerek Schuff   return std::make_unique<WasmObjectWriter>(std::move(MOTW), OS, DwoOS);
17610ff28fa6SDerek Schuff }
1762