118eafb6cSDan Gohman //===- lib/MC/WasmObjectWriter.cpp - Wasm File Writer ---------------------===//
218eafb6cSDan Gohman //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
618eafb6cSDan Gohman //
718eafb6cSDan Gohman //===----------------------------------------------------------------------===//
818eafb6cSDan Gohman //
918eafb6cSDan Gohman // This file implements Wasm object file writer information.
1018eafb6cSDan Gohman //
1118eafb6cSDan Gohman //===----------------------------------------------------------------------===//
1218eafb6cSDan Gohman 
1318eafb6cSDan Gohman #include "llvm/ADT/STLExtras.h"
1418eafb6cSDan Gohman #include "llvm/ADT/SmallPtrSet.h"
15264b5d9eSZachary Turner #include "llvm/BinaryFormat/Wasm.h"
16b59dff4bSBenjamin Kramer #include "llvm/BinaryFormat/WasmTraits.h"
17432a3883SNico Weber #include "llvm/Config/llvm-config.h"
1818eafb6cSDan Gohman #include "llvm/MC/MCAsmBackend.h"
1918eafb6cSDan Gohman #include "llvm/MC/MCAsmLayout.h"
2018eafb6cSDan Gohman #include "llvm/MC/MCAssembler.h"
2118eafb6cSDan Gohman #include "llvm/MC/MCContext.h"
2218eafb6cSDan Gohman #include "llvm/MC/MCExpr.h"
2318eafb6cSDan Gohman #include "llvm/MC/MCFixupKindInfo.h"
2418eafb6cSDan Gohman #include "llvm/MC/MCObjectWriter.h"
2518eafb6cSDan Gohman #include "llvm/MC/MCSectionWasm.h"
2618eafb6cSDan Gohman #include "llvm/MC/MCSymbolWasm.h"
2718eafb6cSDan Gohman #include "llvm/MC/MCValue.h"
2818eafb6cSDan Gohman #include "llvm/MC/MCWasmObjectWriter.h"
29d934cb88SDan Gohman #include "llvm/Support/Casting.h"
3018eafb6cSDan Gohman #include "llvm/Support/Debug.h"
31bcd7f777SSimon Pilgrim #include "llvm/Support/EndianStream.h"
3218eafb6cSDan Gohman #include "llvm/Support/ErrorHandling.h"
33d934cb88SDan Gohman #include "llvm/Support/LEB128.h"
3418eafb6cSDan Gohman #include "llvm/Support/StringSaver.h"
3518eafb6cSDan Gohman #include <vector>
3618eafb6cSDan Gohman 
3718eafb6cSDan Gohman using namespace llvm;
3818eafb6cSDan Gohman 
395e3d33a7SSam Clegg #define DEBUG_TYPE "mc"
4018eafb6cSDan Gohman 
4118eafb6cSDan Gohman namespace {
429e15f359SSam Clegg 
43feac819eSAndy Wingo // When we create the indirect function table we start at 1, so that there is
44feac819eSAndy Wingo // and empty slot at 0 and therefore calling a null function pointer will trap.
4518c56a07SHeejin Ahn static const uint32_t InitialTableOffset = 1;
4630e1bbc1SSam Clegg 
47d934cb88SDan Gohman // For patching purposes, we need to remember where each section starts, both
48d934cb88SDan Gohman // for patching up the section size field, and for patching up references to
49d934cb88SDan Gohman // locations within the section.
50d934cb88SDan Gohman struct SectionBookkeeping {
51d934cb88SDan Gohman   // Where the size of the section is written.
52d934cb88SDan Gohman   uint64_t SizeOffset;
536a31a0d6SSam Clegg   // Where the section header ends (without custom section name).
546a31a0d6SSam Clegg   uint64_t PayloadOffset;
556a31a0d6SSam Clegg   // Where the contents of the section starts.
56d934cb88SDan Gohman   uint64_t ContentsOffset;
576f08c84aSSam Clegg   uint32_t Index;
58d934cb88SDan Gohman };
59d934cb88SDan Gohman 
607c395943SSam Clegg // A wasm data segment.  A wasm binary contains only a single data section
617c395943SSam Clegg // but that can contain many segments, each with their own virtual location
627c395943SSam Clegg // in memory.  Each MCSection data created by llvm is modeled as its own
637c395943SSam Clegg // wasm data segment.
647c395943SSam Clegg struct WasmDataSegment {
657c395943SSam Clegg   MCSectionWasm *Section;
66d95ed959SSam Clegg   StringRef Name;
672e150409SThomas Lively   uint32_t InitFlags;
684d135b04SWouter van Oortmerssen   uint64_t Offset;
6963ebb813SSam Clegg   uint32_t Alignment;
702e150409SThomas Lively   uint32_t LinkerFlags;
717c395943SSam Clegg   SmallVector<char, 4> Data;
727c395943SSam Clegg };
737c395943SSam Clegg 
749e15f359SSam Clegg // A wasm function to be written into the function section.
759e15f359SSam Clegg struct WasmFunction {
76da419bdbSHeejin Ahn   uint32_t SigIndex;
779e15f359SSam Clegg   const MCSymbolWasm *Sym;
789e15f359SSam Clegg };
799e15f359SSam Clegg 
809e15f359SSam Clegg // A wasm global to be written into the global section.
819e15f359SSam Clegg struct WasmGlobal {
826e7f1826SSam Clegg   wasm::WasmGlobalType Type;
839e15f359SSam Clegg   uint64_t InitialValue;
849e15f359SSam Clegg };
859e15f359SSam Clegg 
86ea7caceeSSam Clegg // Information about a single item which is part of a COMDAT.  For each data
87ea7caceeSSam Clegg // segment or function which is in the COMDAT, there is a corresponding
88ea7caceeSSam Clegg // WasmComdatEntry.
89ea7caceeSSam Clegg struct WasmComdatEntry {
90ea7caceeSSam Clegg   unsigned Kind;
91ea7caceeSSam Clegg   uint32_t Index;
92ea7caceeSSam Clegg };
93ea7caceeSSam Clegg 
946dc65e91SSam Clegg // Information about a single relocation.
956dc65e91SSam Clegg struct WasmRelocationEntry {
966dc65e91SSam Clegg   uint64_t Offset;                   // Where is the relocation.
976dc65e91SSam Clegg   const MCSymbolWasm *Symbol;        // The symbol to relocate with.
986dc65e91SSam Clegg   int64_t Addend;                    // A value to add to the symbol.
996dc65e91SSam Clegg   unsigned Type;                     // The type of the relocation.
100fe6414b0SSam Clegg   const MCSectionWasm *FixupSection; // The section the relocation is targeting.
1016dc65e91SSam Clegg 
1026dc65e91SSam Clegg   WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol,
1036dc65e91SSam Clegg                       int64_t Addend, unsigned Type,
104fe6414b0SSam Clegg                       const MCSectionWasm *FixupSection)
1056dc65e91SSam Clegg       : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type),
1066dc65e91SSam Clegg         FixupSection(FixupSection) {}
1076dc65e91SSam Clegg 
108cadcb9ebSKeno Fischer   bool hasAddend() const { return wasm::relocTypeHasAddend(Type); }
109acd7d2b0SSam Clegg 
1106dc65e91SSam Clegg   void print(raw_ostream &Out) const {
111f208f631SHeejin Ahn     Out << wasm::relocTypetoString(Type) << " Off=" << Offset
112f208f631SHeejin Ahn         << ", Sym=" << *Symbol << ", Addend=" << Addend
1137d1ff446SFangrui Song         << ", FixupSection=" << FixupSection->getName();
1146dc65e91SSam Clegg   }
115b7787fd0SSam Clegg 
116615eb470SAaron Ballman #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
117b7787fd0SSam Clegg   LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
118b7787fd0SSam Clegg #endif
1196dc65e91SSam Clegg };
1206dc65e91SSam Clegg 
12118c56a07SHeejin Ahn static const uint32_t InvalidIndex = -1;
12225d8e68bSSam Clegg 
123cfd44a2eSSam Clegg struct WasmCustomSection {
124cfd44a2eSSam Clegg 
1256a31a0d6SSam Clegg   StringRef Name;
1266a31a0d6SSam Clegg   MCSectionWasm *Section;
1276a31a0d6SSam Clegg 
1286a31a0d6SSam Clegg   uint32_t OutputContentsOffset;
1296a31a0d6SSam Clegg   uint32_t OutputIndex;
1306a31a0d6SSam Clegg 
1316a31a0d6SSam Clegg   WasmCustomSection(StringRef Name, MCSectionWasm *Section)
1326a31a0d6SSam Clegg       : Name(Name), Section(Section), OutputContentsOffset(0),
13318c56a07SHeejin Ahn         OutputIndex(InvalidIndex) {}
134cfd44a2eSSam Clegg };
135cfd44a2eSSam Clegg 
1361fb8daa6SSam Clegg #if !defined(NDEBUG)
1377f055deeSSam Clegg raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
138b7787fd0SSam Clegg   Rel.print(OS);
139b7787fd0SSam Clegg   return OS;
140b7787fd0SSam Clegg }
1411fb8daa6SSam Clegg #endif
142b7787fd0SSam Clegg 
14319e8befaSSam Clegg // Write X as an (unsigned) LEB value at offset Offset in Stream, padded
14419e8befaSSam Clegg // to allow patching.
1453b29376eSWouter van Oortmerssen template <int W>
1463b29376eSWouter van Oortmerssen void writePatchableLEB(raw_pwrite_stream &Stream, uint64_t X, uint64_t Offset) {
1473b29376eSWouter van Oortmerssen   uint8_t Buffer[W];
1483b29376eSWouter van Oortmerssen   unsigned SizeLen = encodeULEB128(X, Buffer, W);
1493b29376eSWouter van Oortmerssen   assert(SizeLen == W);
15019e8befaSSam Clegg   Stream.pwrite((char *)Buffer, SizeLen, Offset);
15119e8befaSSam Clegg }
15219e8befaSSam Clegg 
15319e8befaSSam Clegg // Write X as an signed LEB value at offset Offset in Stream, padded
15419e8befaSSam Clegg // to allow patching.
1553b29376eSWouter van Oortmerssen template <int W>
1563b29376eSWouter van Oortmerssen void writePatchableSLEB(raw_pwrite_stream &Stream, int64_t X, uint64_t Offset) {
1573b29376eSWouter van Oortmerssen   uint8_t Buffer[W];
1583b29376eSWouter van Oortmerssen   unsigned SizeLen = encodeSLEB128(X, Buffer, W);
1593b29376eSWouter van Oortmerssen   assert(SizeLen == W);
16019e8befaSSam Clegg   Stream.pwrite((char *)Buffer, SizeLen, Offset);
16119e8befaSSam Clegg }
16219e8befaSSam Clegg 
16319e8befaSSam Clegg // Write X as a plain integer value at offset Offset in Stream.
1640a6c4d8dSSam Clegg static void patchI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
16519e8befaSSam Clegg   uint8_t Buffer[4];
16619e8befaSSam Clegg   support::endian::write32le(Buffer, X);
16719e8befaSSam Clegg   Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
16819e8befaSSam Clegg }
16919e8befaSSam Clegg 
1703b29376eSWouter van Oortmerssen static void patchI64(raw_pwrite_stream &Stream, uint64_t X, uint64_t Offset) {
1713b29376eSWouter van Oortmerssen   uint8_t Buffer[8];
1723b29376eSWouter van Oortmerssen   support::endian::write64le(Buffer, X);
1733b29376eSWouter van Oortmerssen   Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
1743b29376eSWouter van Oortmerssen }
1753b29376eSWouter van Oortmerssen 
1760ff28fa6SDerek Schuff bool isDwoSection(const MCSection &Sec) {
1770ff28fa6SDerek Schuff   return Sec.getName().endswith(".dwo");
1780ff28fa6SDerek Schuff }
1790ff28fa6SDerek Schuff 
18018eafb6cSDan Gohman class WasmObjectWriter : public MCObjectWriter {
1810ff28fa6SDerek Schuff   support::endian::Writer *W;
182f17b149dSPeter Collingbourne 
18318eafb6cSDan Gohman   /// The target specific Wasm writer instance.
18418eafb6cSDan Gohman   std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
18518eafb6cSDan Gohman 
186d934cb88SDan Gohman   // Relocations for fixing up references in the code section.
187d934cb88SDan Gohman   std::vector<WasmRelocationEntry> CodeRelocations;
188d934cb88SDan Gohman   // Relocations for fixing up references in the data section.
189d934cb88SDan Gohman   std::vector<WasmRelocationEntry> DataRelocations;
190d934cb88SDan Gohman 
191d934cb88SDan Gohman   // Index values to use for fixing up call_indirect type indices.
192acd7d2b0SSam Clegg   // Maps function symbols to the index of the type of the function
193acd7d2b0SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
194d99f6078SSam Clegg   // Maps function symbols to the table element index space. Used
195d99f6078SSam Clegg   // for TABLE_INDEX relocation types (i.e. address taken functions).
196f9edbe95SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> TableIndices;
197388fb67bSPaulo Matos   // Maps function/global/table symbols to the
198388fb67bSPaulo Matos   // function/global/table/event/section index space.
1996c899ba6SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> WasmIndices;
200492f7529SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> GOTIndices;
2016c899ba6SSam Clegg   // Maps data symbols to the Wasm segment and offset/size with the segment.
2026c899ba6SSam Clegg   DenseMap<const MCSymbolWasm *, wasm::WasmDataReference> DataLocations;
2036a31a0d6SSam Clegg 
2046a31a0d6SSam Clegg   // Stores output data (index, relocations, content offset) for custom
2056a31a0d6SSam Clegg   // section.
2066a31a0d6SSam Clegg   std::vector<WasmCustomSection> CustomSections;
207cbda16ebSThomas Lively   std::unique_ptr<WasmCustomSection> ProducersSection;
208f6f4f843SThomas Lively   std::unique_ptr<WasmCustomSection> TargetFeaturesSection;
2096a31a0d6SSam Clegg   // Relocations for fixing up references in the custom sections.
2106a31a0d6SSam Clegg   DenseMap<const MCSectionWasm *, std::vector<WasmRelocationEntry>>
2116a31a0d6SSam Clegg       CustomSectionsRelocations;
212acd7d2b0SSam Clegg 
213c0d41195SSam Clegg   // Map from section to defining function symbol.
2146ccb59b3SSam Clegg   DenseMap<const MCSection *, const MCSymbol *> SectionFunctions;
2156ccb59b3SSam Clegg 
2164c41fb5aSHeejin Ahn   DenseMap<wasm::WasmSignature, uint32_t> SignatureIndices;
2174c41fb5aSHeejin Ahn   SmallVector<wasm::WasmSignature, 4> Signatures;
2186c899ba6SSam Clegg   SmallVector<WasmDataSegment, 4> DataSegments;
2199f3fe42eSSam Clegg   unsigned NumFunctionImports = 0;
2207c395943SSam Clegg   unsigned NumGlobalImports = 0;
221feac819eSAndy Wingo   unsigned NumTableImports = 0;
222da419bdbSHeejin Ahn   unsigned NumEventImports = 0;
2237e1c3345SChandler Carruth   uint32_t SectionCount = 0;
224d934cb88SDan Gohman 
2250ff28fa6SDerek Schuff   enum class DwoMode {
2260ff28fa6SDerek Schuff     AllSections,
2270ff28fa6SDerek Schuff     NonDwoOnly,
2280ff28fa6SDerek Schuff     DwoOnly,
2290ff28fa6SDerek Schuff   };
2300ff28fa6SDerek Schuff   bool IsSplitDwarf = false;
2310ff28fa6SDerek Schuff   raw_pwrite_stream *OS = nullptr;
2320ff28fa6SDerek Schuff   raw_pwrite_stream *DwoOS = nullptr;
2330ff28fa6SDerek Schuff 
2340ff28fa6SDerek Schuff   // TargetObjectWriter wranppers.
23518eafb6cSDan Gohman   bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
236da84b688SDan Gohman   bool isEmscripten() const { return TargetObjectWriter->isEmscripten(); }
23718eafb6cSDan Gohman 
2382322a937SSam Clegg   void startSection(SectionBookkeeping &Section, unsigned SectionId);
2392322a937SSam Clegg   void startCustomSection(SectionBookkeeping &Section, StringRef Name);
240d934cb88SDan Gohman   void endSection(SectionBookkeeping &Section);
241d934cb88SDan Gohman 
24218eafb6cSDan Gohman public:
2431301a878SLang Hames   WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
2440ff28fa6SDerek Schuff                    raw_pwrite_stream &OS_)
2450ff28fa6SDerek Schuff       : TargetObjectWriter(std::move(MOTW)), OS(&OS_) {}
2460ff28fa6SDerek Schuff 
2470ff28fa6SDerek Schuff   WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
2480ff28fa6SDerek Schuff                    raw_pwrite_stream &OS_, raw_pwrite_stream &DwoOS_)
2490ff28fa6SDerek Schuff       : TargetObjectWriter(std::move(MOTW)), IsSplitDwarf(true), OS(&OS_),
2500ff28fa6SDerek Schuff         DwoOS(&DwoOS_) {}
25118eafb6cSDan Gohman 
2520917c9e4SDan Gohman private:
253acd7d2b0SSam Clegg   void reset() override {
254acd7d2b0SSam Clegg     CodeRelocations.clear();
255acd7d2b0SSam Clegg     DataRelocations.clear();
256acd7d2b0SSam Clegg     TypeIndices.clear();
2576c899ba6SSam Clegg     WasmIndices.clear();
258492f7529SSam Clegg     GOTIndices.clear();
259f9edbe95SSam Clegg     TableIndices.clear();
2606c899ba6SSam Clegg     DataLocations.clear();
261cbda16ebSThomas Lively     CustomSections.clear();
262cbda16ebSThomas Lively     ProducersSection.reset();
263f6f4f843SThomas Lively     TargetFeaturesSection.reset();
2646a31a0d6SSam Clegg     CustomSectionsRelocations.clear();
265da419bdbSHeejin Ahn     SignatureIndices.clear();
266da419bdbSHeejin Ahn     Signatures.clear();
2676c899ba6SSam Clegg     DataSegments.clear();
2686ccb59b3SSam Clegg     SectionFunctions.clear();
2699f3fe42eSSam Clegg     NumFunctionImports = 0;
2707c395943SSam Clegg     NumGlobalImports = 0;
271feac819eSAndy Wingo     NumTableImports = 0;
272105bdc25SSam Clegg     MCObjectWriter::reset();
273acd7d2b0SSam Clegg   }
274acd7d2b0SSam Clegg 
27518eafb6cSDan Gohman   void writeHeader(const MCAssembler &Asm);
27618eafb6cSDan Gohman 
27718eafb6cSDan Gohman   void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
27818eafb6cSDan Gohman                         const MCFragment *Fragment, const MCFixup &Fixup,
279ceecfe5bSRafael Espindola                         MCValue Target, uint64_t &FixedValue) override;
28018eafb6cSDan Gohman 
28118eafb6cSDan Gohman   void executePostLayoutBinding(MCAssembler &Asm,
28218eafb6cSDan Gohman                                 const MCAsmLayout &Layout) override;
2830ff28fa6SDerek Schuff   void prepareImports(SmallVectorImpl<wasm::WasmImport> &Imports,
2840ff28fa6SDerek Schuff                       MCAssembler &Asm, const MCAsmLayout &Layout);
285438390faSPeter Collingbourne   uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
2869e15f359SSam Clegg 
2870ff28fa6SDerek Schuff   uint64_t writeOneObject(MCAssembler &Asm, const MCAsmLayout &Layout,
2880ff28fa6SDerek Schuff                           DwoMode Mode);
2890ff28fa6SDerek Schuff 
290b7787fd0SSam Clegg   void writeString(const StringRef Str) {
2910ff28fa6SDerek Schuff     encodeULEB128(Str.size(), W->OS);
2920ff28fa6SDerek Schuff     W->OS << Str;
293b7787fd0SSam Clegg   }
294b7787fd0SSam Clegg 
2950a6c4d8dSSam Clegg   void writeI32(int32_t val) {
2960a6c4d8dSSam Clegg     char Buffer[4];
2970a6c4d8dSSam Clegg     support::endian::write32le(Buffer, val);
2980ff28fa6SDerek Schuff     W->OS.write(Buffer, sizeof(Buffer));
2990a6c4d8dSSam Clegg   }
3000a6c4d8dSSam Clegg 
3010a6c4d8dSSam Clegg   void writeI64(int64_t val) {
3020a6c4d8dSSam Clegg     char Buffer[8];
3030a6c4d8dSSam Clegg     support::endian::write64le(Buffer, val);
3040ff28fa6SDerek Schuff     W->OS.write(Buffer, sizeof(Buffer));
3050a6c4d8dSSam Clegg   }
3060a6c4d8dSSam Clegg 
3070ff28fa6SDerek Schuff   void writeValueType(wasm::ValType Ty) { W->OS << static_cast<char>(Ty); }
3089e15f359SSam Clegg 
3094c41fb5aSHeejin Ahn   void writeTypeSection(ArrayRef<wasm::WasmSignature> Signatures);
3104d135b04SWouter van Oortmerssen   void writeImportSection(ArrayRef<wasm::WasmImport> Imports, uint64_t DataSize,
311f950b24aSSam Clegg                           uint32_t NumElements);
312457fb0b4SSam Clegg   void writeFunctionSection(ArrayRef<WasmFunction> Functions);
3138defa952SSam Clegg   void writeExportSection(ArrayRef<wasm::WasmExport> Exports);
314*a5a3659dSAndy Wingo   void writeElemSection(const MCSymbolWasm *IndirectFunctionTable,
315*a5a3659dSAndy Wingo                         ArrayRef<uint32_t> TableElems);
316fef8de66SThomas Lively   void writeDataCountSection();
317e49584a3SSam Clegg   uint32_t writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
318457fb0b4SSam Clegg                             ArrayRef<WasmFunction> Functions);
319e49584a3SSam Clegg   uint32_t writeDataSection(const MCAsmLayout &Layout);
320da419bdbSHeejin Ahn   void writeEventSection(ArrayRef<wasm::WasmEventType> Events);
3210a6c4d8dSSam Clegg   void writeGlobalSection(ArrayRef<wasm::WasmGlobal> Globals);
322388fb67bSPaulo Matos   void writeTableSection(ArrayRef<wasm::WasmTable> Tables);
3236f08c84aSSam Clegg   void writeRelocSection(uint32_t SectionIndex, StringRef Name,
324f77dc2a8SSam Clegg                          std::vector<WasmRelocationEntry> &Relocations);
32531a2c809SSam Clegg   void writeLinkingMetaDataSection(
32686b4a09aSSam Clegg       ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
327ea7caceeSSam Clegg       ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
328ea7caceeSSam Clegg       const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats);
329cbda16ebSThomas Lively   void writeCustomSection(WasmCustomSection &CustomSection,
330cbda16ebSThomas Lively                           const MCAssembler &Asm, const MCAsmLayout &Layout);
3316a31a0d6SSam Clegg   void writeCustomRelocSections();
332acd7d2b0SSam Clegg 
3337ee758d6SSam Clegg   uint64_t getProvisionalValue(const WasmRelocationEntry &RelEntry,
3347ee758d6SSam Clegg                                const MCAsmLayout &Layout);
335acd7d2b0SSam Clegg   void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
3367ee758d6SSam Clegg                         uint64_t ContentsOffset, const MCAsmLayout &Layout);
337acd7d2b0SSam Clegg 
338acd7d2b0SSam Clegg   uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
3395e3d33a7SSam Clegg   uint32_t getFunctionType(const MCSymbolWasm &Symbol);
340da419bdbSHeejin Ahn   uint32_t getEventType(const MCSymbolWasm &Symbol);
34138b12f5eSHeejin Ahn   void registerFunctionType(const MCSymbolWasm &Symbol);
34238b12f5eSHeejin Ahn   void registerEventType(const MCSymbolWasm &Symbol);
34318eafb6cSDan Gohman };
3449e15f359SSam Clegg 
34518eafb6cSDan Gohman } // end anonymous namespace
34618eafb6cSDan Gohman 
347d934cb88SDan Gohman // Write out a section header and a patchable section size field.
348d934cb88SDan Gohman void WasmObjectWriter::startSection(SectionBookkeeping &Section,
3492322a937SSam Clegg                                     unsigned SectionId) {
350d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "startSection " << SectionId << "\n");
3510ff28fa6SDerek Schuff   W->OS << char(SectionId);
352d934cb88SDan Gohman 
3530ff28fa6SDerek Schuff   Section.SizeOffset = W->OS.tell();
354d934cb88SDan Gohman 
355d934cb88SDan Gohman   // The section size. We don't know the size yet, so reserve enough space
356d934cb88SDan Gohman   // for any 32-bit value; we'll patch it later.
3570ff28fa6SDerek Schuff   encodeULEB128(0, W->OS, 5);
358d934cb88SDan Gohman 
359d934cb88SDan Gohman   // The position where the section starts, for measuring its size.
3600ff28fa6SDerek Schuff   Section.ContentsOffset = W->OS.tell();
3610ff28fa6SDerek Schuff   Section.PayloadOffset = W->OS.tell();
3626f08c84aSSam Clegg   Section.Index = SectionCount++;
363d934cb88SDan Gohman }
3642322a937SSam Clegg 
3652322a937SSam Clegg void WasmObjectWriter::startCustomSection(SectionBookkeeping &Section,
3662322a937SSam Clegg                                           StringRef Name) {
367d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "startCustomSection " << Name << "\n");
3682322a937SSam Clegg   startSection(Section, wasm::WASM_SEC_CUSTOM);
3696a31a0d6SSam Clegg 
3706a31a0d6SSam Clegg   // The position where the section header ends, for measuring its size.
3710ff28fa6SDerek Schuff   Section.PayloadOffset = W->OS.tell();
3726a31a0d6SSam Clegg 
3732322a937SSam Clegg   // Custom sections in wasm also have a string identifier.
3742322a937SSam Clegg   writeString(Name);
3756a31a0d6SSam Clegg 
3766a31a0d6SSam Clegg   // The position where the custom section starts.
3770ff28fa6SDerek Schuff   Section.ContentsOffset = W->OS.tell();
378d934cb88SDan Gohman }
379d934cb88SDan Gohman 
380d934cb88SDan Gohman // Now that the section is complete and we know how big it is, patch up the
381d934cb88SDan Gohman // section size field at the start of the section.
382d934cb88SDan Gohman void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
3830ff28fa6SDerek Schuff   uint64_t Size = W->OS.tell();
384c0affde8SSam Clegg   // /dev/null doesn't support seek/tell and can report offset of 0.
385c0affde8SSam Clegg   // Simply skip this patching in that case.
386c0affde8SSam Clegg   if (!Size)
387c0affde8SSam Clegg     return;
388c0affde8SSam Clegg 
389c0affde8SSam Clegg   Size -= Section.PayloadOffset;
390d934cb88SDan Gohman   if (uint32_t(Size) != Size)
391d934cb88SDan Gohman     report_fatal_error("section size does not fit in a uint32_t");
392d934cb88SDan Gohman 
393d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "endSection size=" << Size << "\n");
394d934cb88SDan Gohman 
395d934cb88SDan Gohman   // Write the final section size to the payload_len field, which follows
396d934cb88SDan Gohman   // the section id byte.
3970ff28fa6SDerek Schuff   writePatchableLEB<5>(static_cast<raw_pwrite_stream &>(W->OS), Size,
398f17b149dSPeter Collingbourne                        Section.SizeOffset);
399d934cb88SDan Gohman }
400d934cb88SDan Gohman 
40118eafb6cSDan Gohman // Emit the Wasm header.
40218eafb6cSDan Gohman void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
4030ff28fa6SDerek Schuff   W->OS.write(wasm::WasmMagic, sizeof(wasm::WasmMagic));
4040ff28fa6SDerek Schuff   W->write<uint32_t>(wasm::WasmVersion);
40518eafb6cSDan Gohman }
40618eafb6cSDan Gohman 
40718eafb6cSDan Gohman void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
40818eafb6cSDan Gohman                                                 const MCAsmLayout &Layout) {
4092632ba6aSAndy Wingo   // Some compilation units require the indirect function table to be present
4102632ba6aSAndy Wingo   // but don't explicitly reference it.  This is the case for call_indirect
4112632ba6aSAndy Wingo   // without the reference-types feature, and also function bitcasts in all
4122632ba6aSAndy Wingo   // cases.  In those cases the __indirect_function_table has the
4132632ba6aSAndy Wingo   // WASM_SYMBOL_NO_STRIP attribute.  Here we make sure this symbol makes it to
4142632ba6aSAndy Wingo   // the assembler, if needed.
4152632ba6aSAndy Wingo   if (auto *Sym = Asm.getContext().lookupSymbol("__indirect_function_table")) {
4162632ba6aSAndy Wingo     const auto *WasmSym = static_cast<const MCSymbolWasm *>(Sym);
4172632ba6aSAndy Wingo     if (WasmSym->isNoStrip())
41896ef4f30SSam Clegg       Asm.registerSymbol(*Sym);
4192632ba6aSAndy Wingo   }
42096ef4f30SSam Clegg 
4216ccb59b3SSam Clegg   // Build a map of sections to the function that defines them, for use
4226ccb59b3SSam Clegg   // in recordRelocation.
4236ccb59b3SSam Clegg   for (const MCSymbol &S : Asm.symbols()) {
4246ccb59b3SSam Clegg     const auto &WS = static_cast<const MCSymbolWasm &>(S);
4256ccb59b3SSam Clegg     if (WS.isDefined() && WS.isFunction() && !WS.isVariable()) {
4266ccb59b3SSam Clegg       const auto &Sec = static_cast<const MCSectionWasm &>(S.getSection());
4276ccb59b3SSam Clegg       auto Pair = SectionFunctions.insert(std::make_pair(&Sec, &S));
4286ccb59b3SSam Clegg       if (!Pair.second)
4296ccb59b3SSam Clegg         report_fatal_error("section already has a defining function: " +
4307d1ff446SFangrui Song                            Sec.getName());
4316ccb59b3SSam Clegg     }
4326ccb59b3SSam Clegg   }
43318eafb6cSDan Gohman }
43418eafb6cSDan Gohman 
43518eafb6cSDan Gohman void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
43618eafb6cSDan Gohman                                         const MCAsmLayout &Layout,
43718eafb6cSDan Gohman                                         const MCFragment *Fragment,
43818eafb6cSDan Gohman                                         const MCFixup &Fixup, MCValue Target,
439ceecfe5bSRafael Espindola                                         uint64_t &FixedValue) {
440ecc5e808SSam Clegg   // The WebAssembly backend should never generate FKF_IsPCRel fixups
441e828ce1bSFangrui Song   assert(!(Asm.getBackend().getFixupKindInfo(Fixup.getKind()).Flags &
442ecc5e808SSam Clegg            MCFixupKindInfo::FKF_IsPCRel));
443ecc5e808SSam Clegg 
444fe6414b0SSam Clegg   const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
445d934cb88SDan Gohman   uint64_t C = Target.getConstant();
446d934cb88SDan Gohman   uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
447d934cb88SDan Gohman   MCContext &Ctx = Asm.getContext();
448d934cb88SDan Gohman 
449d934cb88SDan Gohman   if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
450ecc5e808SSam Clegg     // To get here the A - B expression must have failed evaluateAsRelocatable.
451ecc5e808SSam Clegg     // This means either A or B must be undefined and in WebAssembly we can't
452ecc5e808SSam Clegg     // support either of those cases.
453ecc5e808SSam Clegg     const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
454d934cb88SDan Gohman     Ctx.reportError(
455d934cb88SDan Gohman         Fixup.getLoc(),
456d934cb88SDan Gohman         Twine("symbol '") + SymB.getName() +
457ecc5e808SSam Clegg             "': unsupported subtraction expression used in relocation.");
458d934cb88SDan Gohman     return;
459d934cb88SDan Gohman   }
460d934cb88SDan Gohman 
461d934cb88SDan Gohman   // We either rejected the fixup or folded B into C at this point.
462d934cb88SDan Gohman   const MCSymbolRefExpr *RefA = Target.getSymA();
463ecc5e808SSam Clegg   const auto *SymA = cast<MCSymbolWasm>(&RefA->getSymbol());
464d934cb88SDan Gohman 
4653ea1c62cSSam Clegg   // The .init_array isn't translated as data, so don't do relocations in it.
4667d1ff446SFangrui Song   if (FixupSection.getName().startswith(".init_array")) {
4673ea1c62cSSam Clegg     SymA->setUsedInInitArray();
4683ea1c62cSSam Clegg     return;
4693ea1c62cSSam Clegg   }
4703ea1c62cSSam Clegg 
471ecc5e808SSam Clegg   if (SymA->isVariable()) {
472d934cb88SDan Gohman     const MCExpr *Expr = SymA->getVariableValue();
4737ee758d6SSam Clegg     if (const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr))
4746ad8f190SSam Clegg       if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
4756ad8f190SSam Clegg         llvm_unreachable("weakref used in reloc not yet implemented");
476d934cb88SDan Gohman   }
477d934cb88SDan Gohman 
478d934cb88SDan Gohman   // Put any constant offset in an addend. Offsets can be negative, and
479d934cb88SDan Gohman   // LLVM expects wrapping, in contrast to wasm's immediates which can't
480d934cb88SDan Gohman   // be negative and don't wrap.
481d934cb88SDan Gohman   FixedValue = 0;
482d934cb88SDan Gohman 
483a5e175c6SSam Clegg   unsigned Type = TargetObjectWriter->getRelocType(Target, Fixup);
4849d24fb7fSSam Clegg 
4854d57fbd0SSam Clegg   // Absolute offset within a section or a function.
4864d57fbd0SSam Clegg   // Currently only supported for for metadata sections.
4874d57fbd0SSam Clegg   // See: test/MC/WebAssembly/blockaddress.ll
488d1152a26SSam Clegg   if (Type == wasm::R_WASM_FUNCTION_OFFSET_I32 ||
48916f02431SWouter van Oortmerssen       Type == wasm::R_WASM_FUNCTION_OFFSET_I64 ||
490d1152a26SSam Clegg       Type == wasm::R_WASM_SECTION_OFFSET_I32) {
4914d57fbd0SSam Clegg     if (!FixupSection.getKind().isMetadata())
4924d57fbd0SSam Clegg       report_fatal_error("relocations for function or section offsets are "
4934d57fbd0SSam Clegg                          "only supported in metadata sections");
4944d57fbd0SSam Clegg 
4954d57fbd0SSam Clegg     const MCSymbol *SectionSymbol = nullptr;
4964d57fbd0SSam Clegg     const MCSection &SecA = SymA->getSection();
4975e5b2cb1SWouter van Oortmerssen     if (SecA.getKind().isText()) {
4985e5b2cb1SWouter van Oortmerssen       auto SecSymIt = SectionFunctions.find(&SecA);
4995e5b2cb1SWouter van Oortmerssen       if (SecSymIt == SectionFunctions.end())
5005e5b2cb1SWouter van Oortmerssen         report_fatal_error("section doesn\'t have defining symbol");
5015e5b2cb1SWouter van Oortmerssen       SectionSymbol = SecSymIt->second;
5025e5b2cb1SWouter van Oortmerssen     } else {
5034d57fbd0SSam Clegg       SectionSymbol = SecA.getBeginSymbol();
5045e5b2cb1SWouter van Oortmerssen     }
5054d57fbd0SSam Clegg     if (!SectionSymbol)
5064d57fbd0SSam Clegg       report_fatal_error("section symbol is required for relocation");
5074d57fbd0SSam Clegg 
5084d57fbd0SSam Clegg     C += Layout.getSymbolOffset(*SymA);
5094d57fbd0SSam Clegg     SymA = cast<MCSymbolWasm>(SectionSymbol);
5104d57fbd0SSam Clegg   }
5114d57fbd0SSam Clegg 
512feac819eSAndy Wingo   if (Type == wasm::R_WASM_TABLE_INDEX_REL_SLEB ||
513feac819eSAndy Wingo       Type == wasm::R_WASM_TABLE_INDEX_SLEB ||
514feac819eSAndy Wingo       Type == wasm::R_WASM_TABLE_INDEX_SLEB64 ||
515feac819eSAndy Wingo       Type == wasm::R_WASM_TABLE_INDEX_I32 ||
516feac819eSAndy Wingo       Type == wasm::R_WASM_TABLE_INDEX_I64) {
517feac819eSAndy Wingo     // TABLE_INDEX relocs implicitly use the default indirect function table.
5182632ba6aSAndy Wingo     // We require the function table to have already been defined.
519feac819eSAndy Wingo     auto TableName = "__indirect_function_table";
520feac819eSAndy Wingo     MCSymbolWasm *Sym = cast_or_null<MCSymbolWasm>(Ctx.lookupSymbol(TableName));
5212632ba6aSAndy Wingo     if (!Sym || !Sym->isFunctionTable()) {
522feac819eSAndy Wingo       Ctx.reportError(
523feac819eSAndy Wingo           Fixup.getLoc(),
524feac819eSAndy Wingo           "symbol '__indirect_function_table' is not a function table");
525feac819eSAndy Wingo     } else {
5262632ba6aSAndy Wingo       // Ensure that __indirect_function_table reaches the output.
5272632ba6aSAndy Wingo       Sym->setNoStrip();
5287dc98adbSAndy Wingo       Asm.registerSymbol(*Sym);
529861dbe1aSAndy Wingo     }
5302632ba6aSAndy Wingo   }
531feac819eSAndy Wingo 
532d1152a26SSam Clegg   // Relocation other than R_WASM_TYPE_INDEX_LEB are required to be
5334d57fbd0SSam Clegg   // against a named symbol.
534d1152a26SSam Clegg   if (Type != wasm::R_WASM_TYPE_INDEX_LEB) {
5354d57fbd0SSam Clegg     if (SymA->getName().empty())
5364d57fbd0SSam Clegg       report_fatal_error("relocations against un-named temporaries are not yet "
5374d57fbd0SSam Clegg                          "supported by wasm");
5384d57fbd0SSam Clegg 
5394d57fbd0SSam Clegg     SymA->setUsedInReloc();
5404d57fbd0SSam Clegg   }
541ae03c1e7SSam Clegg 
542492f7529SSam Clegg   if (RefA->getKind() == MCSymbolRefExpr::VK_GOT)
543492f7529SSam Clegg     SymA->setUsedInGOT();
544492f7529SSam Clegg 
545d934cb88SDan Gohman   WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
546d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
547d934cb88SDan Gohman 
5486a31a0d6SSam Clegg   if (FixupSection.isWasmData()) {
549d934cb88SDan Gohman     DataRelocations.push_back(Rec);
5506a31a0d6SSam Clegg   } else if (FixupSection.getKind().isText()) {
55112fd3da9SSam Clegg     CodeRelocations.push_back(Rec);
5526a31a0d6SSam Clegg   } else if (FixupSection.getKind().isMetadata()) {
5536a31a0d6SSam Clegg     CustomSectionsRelocations[&FixupSection].push_back(Rec);
5546a31a0d6SSam Clegg   } else {
55512fd3da9SSam Clegg     llvm_unreachable("unexpected section type");
556d934cb88SDan Gohman   }
5576a31a0d6SSam Clegg }
558d934cb88SDan Gohman 
559d934cb88SDan Gohman // Compute a value to write into the code at the location covered
56060ec3034SSam Clegg // by RelEntry. This value isn't used by the static linker; it just serves
56160ec3034SSam Clegg // to make the object format more readable and more likely to be directly
56260ec3034SSam Clegg // useable.
5633b29376eSWouter van Oortmerssen uint64_t
5647ee758d6SSam Clegg WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry,
5657ee758d6SSam Clegg                                       const MCAsmLayout &Layout) {
56648139ebcSWouter van Oortmerssen   if ((RelEntry.Type == wasm::R_WASM_GLOBAL_INDEX_LEB ||
56748139ebcSWouter van Oortmerssen        RelEntry.Type == wasm::R_WASM_GLOBAL_INDEX_I32) &&
56848139ebcSWouter van Oortmerssen       !RelEntry.Symbol->isGlobal()) {
569492f7529SSam Clegg     assert(GOTIndices.count(RelEntry.Symbol) > 0 && "symbol not found in GOT index space");
570492f7529SSam Clegg     return GOTIndices[RelEntry.Symbol];
571492f7529SSam Clegg   }
572492f7529SSam Clegg 
57360ec3034SSam Clegg   switch (RelEntry.Type) {
5742a7cac93SSam Clegg   case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
575d1152a26SSam Clegg   case wasm::R_WASM_TABLE_INDEX_SLEB:
576cc1b9b68SWouter van Oortmerssen   case wasm::R_WASM_TABLE_INDEX_SLEB64:
577cc1b9b68SWouter van Oortmerssen   case wasm::R_WASM_TABLE_INDEX_I32:
578cc1b9b68SWouter van Oortmerssen   case wasm::R_WASM_TABLE_INDEX_I64: {
579f9edbe95SSam Clegg     // Provisional value is table address of the resolved symbol itself
5807ee758d6SSam Clegg     const MCSymbolWasm *Base =
5817ee758d6SSam Clegg         cast<MCSymbolWasm>(Layout.getBaseSymbol(*RelEntry.Symbol));
5827ee758d6SSam Clegg     assert(Base->isFunction());
58381443ac1SSam Clegg     if (RelEntry.Type == wasm::R_WASM_TABLE_INDEX_REL_SLEB)
5847ee758d6SSam Clegg       return TableIndices[Base] - InitialTableOffset;
58581443ac1SSam Clegg     else
5867ee758d6SSam Clegg       return TableIndices[Base];
587f9edbe95SSam Clegg   }
588d1152a26SSam Clegg   case wasm::R_WASM_TYPE_INDEX_LEB:
5896c899ba6SSam Clegg     // Provisional value is same as the index
59060ec3034SSam Clegg     return getRelocationIndexValue(RelEntry);
591d1152a26SSam Clegg   case wasm::R_WASM_FUNCTION_INDEX_LEB:
592d1152a26SSam Clegg   case wasm::R_WASM_GLOBAL_INDEX_LEB:
59348139ebcSWouter van Oortmerssen   case wasm::R_WASM_GLOBAL_INDEX_I32:
594d1152a26SSam Clegg   case wasm::R_WASM_EVENT_INDEX_LEB:
59569e2797eSPaulo Matos   case wasm::R_WASM_TABLE_NUMBER_LEB:
596da419bdbSHeejin Ahn     // Provisional value is function/global/event Wasm index
597492f7529SSam Clegg     assert(WasmIndices.count(RelEntry.Symbol) > 0 && "symbol not found in wasm index space");
5986c899ba6SSam Clegg     return WasmIndices[RelEntry.Symbol];
599d1152a26SSam Clegg   case wasm::R_WASM_FUNCTION_OFFSET_I32:
60016f02431SWouter van Oortmerssen   case wasm::R_WASM_FUNCTION_OFFSET_I64:
601d1152a26SSam Clegg   case wasm::R_WASM_SECTION_OFFSET_I32: {
6026a31a0d6SSam Clegg     const auto &Section =
6036a31a0d6SSam Clegg         static_cast<const MCSectionWasm &>(RelEntry.Symbol->getSection());
6046a31a0d6SSam Clegg     return Section.getSectionOffset() + RelEntry.Addend;
6056a31a0d6SSam Clegg   }
606d1152a26SSam Clegg   case wasm::R_WASM_MEMORY_ADDR_LEB:
6073b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_LEB64:
6083b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_SLEB:
6093b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_SLEB64:
6102a7cac93SSam Clegg   case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
6113b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_REL_SLEB64:
6123b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_I32:
613a28a4662SSam Clegg   case wasm::R_WASM_MEMORY_ADDR_I64:
614a28a4662SSam Clegg   case wasm::R_WASM_MEMORY_ADDR_TLS_SLEB: {
6159c7b5808SDominic Chen     // Provisional value is address of the global plus the offset
616270ed1b3SSam Clegg     // For undefined symbols, use zero
61701a48535SSam Clegg     if (!RelEntry.Symbol->isDefined())
618270ed1b3SSam Clegg       return 0;
61901a48535SSam Clegg     const wasm::WasmDataReference &SymRef = DataLocations[RelEntry.Symbol];
62001a48535SSam Clegg     const WasmDataSegment &Segment = DataSegments[SymRef.Segment];
621d934cb88SDan Gohman     // Ignore overflow. LLVM allows address arithmetic to silently wrap.
62201a48535SSam Clegg     return Segment.Offset + SymRef.Offset + RelEntry.Addend;
62360ec3034SSam Clegg   }
62460ec3034SSam Clegg   default:
62560ec3034SSam Clegg     llvm_unreachable("invalid relocation type");
62660ec3034SSam Clegg   }
627d934cb88SDan Gohman }
628d934cb88SDan Gohman 
629759631c7SSam Clegg static void addData(SmallVectorImpl<char> &DataBytes,
63063ebb813SSam Clegg                     MCSectionWasm &DataSection) {
6317d1ff446SFangrui Song   LLVM_DEBUG(errs() << "addData: " << DataSection.getName() << "\n");
632759631c7SSam Clegg 
63363ebb813SSam Clegg   DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
63463ebb813SSam Clegg 
635759631c7SSam Clegg   for (const MCFragment &Frag : DataSection) {
636759631c7SSam Clegg     if (Frag.hasInstructions())
637759631c7SSam Clegg       report_fatal_error("only data supported in data sections");
638759631c7SSam Clegg 
639759631c7SSam Clegg     if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
640759631c7SSam Clegg       if (Align->getValueSize() != 1)
641759631c7SSam Clegg         report_fatal_error("only byte values supported for alignment");
642759631c7SSam Clegg       // If nops are requested, use zeros, as this is the data section.
643759631c7SSam Clegg       uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
644f208f631SHeejin Ahn       uint64_t Size =
645f208f631SHeejin Ahn           std::min<uint64_t>(alignTo(DataBytes.size(), Align->getAlignment()),
646f208f631SHeejin Ahn                              DataBytes.size() + Align->getMaxBytesToEmit());
647759631c7SSam Clegg       DataBytes.resize(Size, Value);
648759631c7SSam Clegg     } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
649588fad4dSNirav Dave       int64_t NumValues;
650588fad4dSNirav Dave       if (!Fill->getNumValues().evaluateAsAbsolute(NumValues))
651d707c370SRafael Espindola         llvm_unreachable("The fill should be an assembler constant");
652588fad4dSNirav Dave       DataBytes.insert(DataBytes.end(), Fill->getValueSize() * NumValues,
653588fad4dSNirav Dave                        Fill->getValue());
65424faf859SHeejin Ahn     } else if (auto *LEB = dyn_cast<MCLEBFragment>(&Frag)) {
65524faf859SHeejin Ahn       const SmallVectorImpl<char> &Contents = LEB->getContents();
6561d0bc055SKazu Hirata       llvm::append_range(DataBytes, Contents);
657759631c7SSam Clegg     } else {
658759631c7SSam Clegg       const auto &DataFrag = cast<MCDataFragment>(Frag);
659759631c7SSam Clegg       const SmallVectorImpl<char> &Contents = DataFrag.getContents();
6601d0bc055SKazu Hirata       llvm::append_range(DataBytes, Contents);
661759631c7SSam Clegg     }
662759631c7SSam Clegg   }
663759631c7SSam Clegg 
664d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
665759631c7SSam Clegg }
666759631c7SSam Clegg 
66760ec3034SSam Clegg uint32_t
66860ec3034SSam Clegg WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
669d1152a26SSam Clegg   if (RelEntry.Type == wasm::R_WASM_TYPE_INDEX_LEB) {
670b7787fd0SSam Clegg     if (!TypeIndices.count(RelEntry.Symbol))
671b7787fd0SSam Clegg       report_fatal_error("symbol not found in type index space: " +
672b7787fd0SSam Clegg                          RelEntry.Symbol->getName());
673acd7d2b0SSam Clegg     return TypeIndices[RelEntry.Symbol];
674acd7d2b0SSam Clegg   }
67560ec3034SSam Clegg 
67625d8e68bSSam Clegg   return RelEntry.Symbol->getIndex();
677acd7d2b0SSam Clegg }
678acd7d2b0SSam Clegg 
679d934cb88SDan Gohman // Apply the portions of the relocation records that we can handle ourselves
680d934cb88SDan Gohman // directly.
681acd7d2b0SSam Clegg void WasmObjectWriter::applyRelocations(
6827ee758d6SSam Clegg     ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset,
6837ee758d6SSam Clegg     const MCAsmLayout &Layout) {
6840ff28fa6SDerek Schuff   auto &Stream = static_cast<raw_pwrite_stream &>(W->OS);
685d934cb88SDan Gohman   for (const WasmRelocationEntry &RelEntry : Relocations) {
686d934cb88SDan Gohman     uint64_t Offset = ContentsOffset +
687d934cb88SDan Gohman                       RelEntry.FixupSection->getSectionOffset() +
688d934cb88SDan Gohman                       RelEntry.Offset;
689d934cb88SDan Gohman 
690d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
6917ee758d6SSam Clegg     auto Value = getProvisionalValue(RelEntry, Layout);
69260ec3034SSam Clegg 
693acd7d2b0SSam Clegg     switch (RelEntry.Type) {
694d1152a26SSam Clegg     case wasm::R_WASM_FUNCTION_INDEX_LEB:
695d1152a26SSam Clegg     case wasm::R_WASM_TYPE_INDEX_LEB:
696d1152a26SSam Clegg     case wasm::R_WASM_GLOBAL_INDEX_LEB:
697d1152a26SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_LEB:
698d1152a26SSam Clegg     case wasm::R_WASM_EVENT_INDEX_LEB:
69969e2797eSPaulo Matos     case wasm::R_WASM_TABLE_NUMBER_LEB:
7003b29376eSWouter van Oortmerssen       writePatchableLEB<5>(Stream, Value, Offset);
7013b29376eSWouter van Oortmerssen       break;
7023b29376eSWouter van Oortmerssen     case wasm::R_WASM_MEMORY_ADDR_LEB64:
7033b29376eSWouter van Oortmerssen       writePatchableLEB<10>(Stream, Value, Offset);
704d934cb88SDan Gohman       break;
705d1152a26SSam Clegg     case wasm::R_WASM_TABLE_INDEX_I32:
706d1152a26SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_I32:
707d1152a26SSam Clegg     case wasm::R_WASM_FUNCTION_OFFSET_I32:
708d1152a26SSam Clegg     case wasm::R_WASM_SECTION_OFFSET_I32:
70948139ebcSWouter van Oortmerssen     case wasm::R_WASM_GLOBAL_INDEX_I32:
7100a6c4d8dSSam Clegg       patchI32(Stream, Value, Offset);
711d934cb88SDan Gohman       break;
712cc1b9b68SWouter van Oortmerssen     case wasm::R_WASM_TABLE_INDEX_I64:
7133b29376eSWouter van Oortmerssen     case wasm::R_WASM_MEMORY_ADDR_I64:
71416f02431SWouter van Oortmerssen     case wasm::R_WASM_FUNCTION_OFFSET_I64:
7153b29376eSWouter van Oortmerssen       patchI64(Stream, Value, Offset);
7163b29376eSWouter van Oortmerssen       break;
717d1152a26SSam Clegg     case wasm::R_WASM_TABLE_INDEX_SLEB:
7182a7cac93SSam Clegg     case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
719d1152a26SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_SLEB:
7202a7cac93SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
721a28a4662SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_TLS_SLEB:
7223b29376eSWouter van Oortmerssen       writePatchableSLEB<5>(Stream, Value, Offset);
7233b29376eSWouter van Oortmerssen       break;
724cc1b9b68SWouter van Oortmerssen     case wasm::R_WASM_TABLE_INDEX_SLEB64:
7253b29376eSWouter van Oortmerssen     case wasm::R_WASM_MEMORY_ADDR_SLEB64:
7263b29376eSWouter van Oortmerssen     case wasm::R_WASM_MEMORY_ADDR_REL_SLEB64:
7273b29376eSWouter van Oortmerssen       writePatchableSLEB<10>(Stream, Value, Offset);
72860ec3034SSam Clegg       break;
729d934cb88SDan Gohman     default:
7309d24fb7fSSam Clegg       llvm_unreachable("invalid relocation type");
731d934cb88SDan Gohman     }
732d934cb88SDan Gohman   }
73318eafb6cSDan Gohman }
73418eafb6cSDan Gohman 
7354c41fb5aSHeejin Ahn void WasmObjectWriter::writeTypeSection(
7364c41fb5aSHeejin Ahn     ArrayRef<wasm::WasmSignature> Signatures) {
737da419bdbSHeejin Ahn   if (Signatures.empty())
7389e15f359SSam Clegg     return;
7399e15f359SSam Clegg 
7409e15f359SSam Clegg   SectionBookkeeping Section;
7419e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_TYPE);
7429e15f359SSam Clegg 
7430ff28fa6SDerek Schuff   encodeULEB128(Signatures.size(), W->OS);
7449e15f359SSam Clegg 
7454c41fb5aSHeejin Ahn   for (const wasm::WasmSignature &Sig : Signatures) {
7460ff28fa6SDerek Schuff     W->OS << char(wasm::WASM_TYPE_FUNC);
7470ff28fa6SDerek Schuff     encodeULEB128(Sig.Params.size(), W->OS);
748da419bdbSHeejin Ahn     for (wasm::ValType Ty : Sig.Params)
7499e15f359SSam Clegg       writeValueType(Ty);
7500ff28fa6SDerek Schuff     encodeULEB128(Sig.Returns.size(), W->OS);
751da419bdbSHeejin Ahn     for (wasm::ValType Ty : Sig.Returns)
7529e15f359SSam Clegg       writeValueType(Ty);
7539e15f359SSam Clegg   }
7549e15f359SSam Clegg 
7559e15f359SSam Clegg   endSection(Section);
7569e15f359SSam Clegg }
7579e15f359SSam Clegg 
7588defa952SSam Clegg void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports,
7594d135b04SWouter van Oortmerssen                                           uint64_t DataSize,
760f950b24aSSam Clegg                                           uint32_t NumElements) {
7619e15f359SSam Clegg   if (Imports.empty())
7629e15f359SSam Clegg     return;
7639e15f359SSam Clegg 
7644d135b04SWouter van Oortmerssen   uint64_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
765f950b24aSSam Clegg 
7669e15f359SSam Clegg   SectionBookkeeping Section;
7679e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_IMPORT);
7689e15f359SSam Clegg 
7690ff28fa6SDerek Schuff   encodeULEB128(Imports.size(), W->OS);
7708defa952SSam Clegg   for (const wasm::WasmImport &Import : Imports) {
7718defa952SSam Clegg     writeString(Import.Module);
7728defa952SSam Clegg     writeString(Import.Field);
7730ff28fa6SDerek Schuff     W->OS << char(Import.Kind);
7749e15f359SSam Clegg 
7759e15f359SSam Clegg     switch (Import.Kind) {
7769e15f359SSam Clegg     case wasm::WASM_EXTERNAL_FUNCTION:
7770ff28fa6SDerek Schuff       encodeULEB128(Import.SigIndex, W->OS);
7789e15f359SSam Clegg       break;
7799e15f359SSam Clegg     case wasm::WASM_EXTERNAL_GLOBAL:
7800ff28fa6SDerek Schuff       W->OS << char(Import.Global.Type);
7810ff28fa6SDerek Schuff       W->OS << char(Import.Global.Mutable ? 1 : 0);
7829e15f359SSam Clegg       break;
783f950b24aSSam Clegg     case wasm::WASM_EXTERNAL_MEMORY:
7840ff28fa6SDerek Schuff       encodeULEB128(Import.Memory.Flags, W->OS);
7850ff28fa6SDerek Schuff       encodeULEB128(NumPages, W->OS); // initial
786f950b24aSSam Clegg       break;
787f950b24aSSam Clegg     case wasm::WASM_EXTERNAL_TABLE:
7880ff28fa6SDerek Schuff       W->OS << char(Import.Table.ElemType);
7890ff28fa6SDerek Schuff       encodeULEB128(0, W->OS);           // flags
7900ff28fa6SDerek Schuff       encodeULEB128(NumElements, W->OS); // initial
791f950b24aSSam Clegg       break;
792da419bdbSHeejin Ahn     case wasm::WASM_EXTERNAL_EVENT:
7930ff28fa6SDerek Schuff       encodeULEB128(Import.Event.Attribute, W->OS);
7940ff28fa6SDerek Schuff       encodeULEB128(Import.Event.SigIndex, W->OS);
795da419bdbSHeejin Ahn       break;
7969e15f359SSam Clegg     default:
7979e15f359SSam Clegg       llvm_unreachable("unsupported import kind");
7989e15f359SSam Clegg     }
7999e15f359SSam Clegg   }
8009e15f359SSam Clegg 
8019e15f359SSam Clegg   endSection(Section);
8029e15f359SSam Clegg }
8039e15f359SSam Clegg 
804457fb0b4SSam Clegg void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
8059e15f359SSam Clegg   if (Functions.empty())
8069e15f359SSam Clegg     return;
8079e15f359SSam Clegg 
8089e15f359SSam Clegg   SectionBookkeeping Section;
8099e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_FUNCTION);
8109e15f359SSam Clegg 
8110ff28fa6SDerek Schuff   encodeULEB128(Functions.size(), W->OS);
8129e15f359SSam Clegg   for (const WasmFunction &Func : Functions)
8130ff28fa6SDerek Schuff     encodeULEB128(Func.SigIndex, W->OS);
8149e15f359SSam Clegg 
8159e15f359SSam Clegg   endSection(Section);
8169e15f359SSam Clegg }
8179e15f359SSam Clegg 
818da419bdbSHeejin Ahn void WasmObjectWriter::writeEventSection(ArrayRef<wasm::WasmEventType> Events) {
819da419bdbSHeejin Ahn   if (Events.empty())
820da419bdbSHeejin Ahn     return;
821da419bdbSHeejin Ahn 
822da419bdbSHeejin Ahn   SectionBookkeeping Section;
823da419bdbSHeejin Ahn   startSection(Section, wasm::WASM_SEC_EVENT);
824da419bdbSHeejin Ahn 
8250ff28fa6SDerek Schuff   encodeULEB128(Events.size(), W->OS);
826da419bdbSHeejin Ahn   for (const wasm::WasmEventType &Event : Events) {
8270ff28fa6SDerek Schuff     encodeULEB128(Event.Attribute, W->OS);
8280ff28fa6SDerek Schuff     encodeULEB128(Event.SigIndex, W->OS);
829da419bdbSHeejin Ahn   }
830da419bdbSHeejin Ahn 
831da419bdbSHeejin Ahn   endSection(Section);
832da419bdbSHeejin Ahn }
833da419bdbSHeejin Ahn 
8340a6c4d8dSSam Clegg void WasmObjectWriter::writeGlobalSection(ArrayRef<wasm::WasmGlobal> Globals) {
8350a6c4d8dSSam Clegg   if (Globals.empty())
8360a6c4d8dSSam Clegg     return;
8370a6c4d8dSSam Clegg 
8380a6c4d8dSSam Clegg   SectionBookkeeping Section;
8390a6c4d8dSSam Clegg   startSection(Section, wasm::WASM_SEC_GLOBAL);
8400a6c4d8dSSam Clegg 
8410ff28fa6SDerek Schuff   encodeULEB128(Globals.size(), W->OS);
8420a6c4d8dSSam Clegg   for (const wasm::WasmGlobal &Global : Globals) {
8430ff28fa6SDerek Schuff     encodeULEB128(Global.Type.Type, W->OS);
8440ff28fa6SDerek Schuff     W->OS << char(Global.Type.Mutable);
8450ff28fa6SDerek Schuff     W->OS << char(Global.InitExpr.Opcode);
8460a6c4d8dSSam Clegg     switch (Global.Type.Type) {
8470a6c4d8dSSam Clegg     case wasm::WASM_TYPE_I32:
8480ff28fa6SDerek Schuff       encodeSLEB128(0, W->OS);
8490a6c4d8dSSam Clegg       break;
8500a6c4d8dSSam Clegg     case wasm::WASM_TYPE_I64:
8510ff28fa6SDerek Schuff       encodeSLEB128(0, W->OS);
8520a6c4d8dSSam Clegg       break;
8530a6c4d8dSSam Clegg     case wasm::WASM_TYPE_F32:
8540a6c4d8dSSam Clegg       writeI32(0);
8550a6c4d8dSSam Clegg       break;
8560a6c4d8dSSam Clegg     case wasm::WASM_TYPE_F64:
8570a6c4d8dSSam Clegg       writeI64(0);
8580a6c4d8dSSam Clegg       break;
85979aad89dSSam Clegg     case wasm::WASM_TYPE_EXTERNREF:
86079aad89dSSam Clegg       writeValueType(wasm::ValType::EXTERNREF);
86179aad89dSSam Clegg       break;
8620a6c4d8dSSam Clegg     default:
8630a6c4d8dSSam Clegg       llvm_unreachable("unexpected type");
8640a6c4d8dSSam Clegg     }
8650ff28fa6SDerek Schuff     W->OS << char(wasm::WASM_OPCODE_END);
8660a6c4d8dSSam Clegg   }
8670a6c4d8dSSam Clegg 
8680a6c4d8dSSam Clegg   endSection(Section);
8690a6c4d8dSSam Clegg }
8700a6c4d8dSSam Clegg 
871388fb67bSPaulo Matos void WasmObjectWriter::writeTableSection(ArrayRef<wasm::WasmTable> Tables) {
872388fb67bSPaulo Matos   if (Tables.empty())
873388fb67bSPaulo Matos     return;
874388fb67bSPaulo Matos 
875388fb67bSPaulo Matos   SectionBookkeeping Section;
876388fb67bSPaulo Matos   startSection(Section, wasm::WASM_SEC_TABLE);
877388fb67bSPaulo Matos 
878388fb67bSPaulo Matos   encodeULEB128(Tables.size(), W->OS);
879388fb67bSPaulo Matos   for (const wasm::WasmTable &Table : Tables) {
8801933c9d4SAndy Wingo     encodeULEB128(Table.Type.ElemType, W->OS);
8811933c9d4SAndy Wingo     encodeULEB128(Table.Type.Limits.Flags, W->OS);
8821933c9d4SAndy Wingo     encodeULEB128(Table.Type.Limits.Initial, W->OS);
8831933c9d4SAndy Wingo     if (Table.Type.Limits.Flags & wasm::WASM_LIMITS_FLAG_HAS_MAX)
8841933c9d4SAndy Wingo       encodeULEB128(Table.Type.Limits.Maximum, W->OS);
885388fb67bSPaulo Matos   }
886388fb67bSPaulo Matos   endSection(Section);
887388fb67bSPaulo Matos }
888388fb67bSPaulo Matos 
8898defa952SSam Clegg void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) {
8909e15f359SSam Clegg   if (Exports.empty())
8919e15f359SSam Clegg     return;
8929e15f359SSam Clegg 
8939e15f359SSam Clegg   SectionBookkeeping Section;
8949e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_EXPORT);
8959e15f359SSam Clegg 
8960ff28fa6SDerek Schuff   encodeULEB128(Exports.size(), W->OS);
8978defa952SSam Clegg   for (const wasm::WasmExport &Export : Exports) {
8988defa952SSam Clegg     writeString(Export.Name);
8990ff28fa6SDerek Schuff     W->OS << char(Export.Kind);
9000ff28fa6SDerek Schuff     encodeULEB128(Export.Index, W->OS);
9019e15f359SSam Clegg   }
9029e15f359SSam Clegg 
9039e15f359SSam Clegg   endSection(Section);
9049e15f359SSam Clegg }
9059e15f359SSam Clegg 
906*a5a3659dSAndy Wingo void WasmObjectWriter::writeElemSection(
907*a5a3659dSAndy Wingo     const MCSymbolWasm *IndirectFunctionTable, ArrayRef<uint32_t> TableElems) {
9089e15f359SSam Clegg   if (TableElems.empty())
9099e15f359SSam Clegg     return;
9109e15f359SSam Clegg 
911*a5a3659dSAndy Wingo   assert(IndirectFunctionTable);
912*a5a3659dSAndy Wingo 
9139e15f359SSam Clegg   SectionBookkeeping Section;
9149e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_ELEM);
9159e15f359SSam Clegg 
9160ff28fa6SDerek Schuff   encodeULEB128(1, W->OS); // number of "segments"
917*a5a3659dSAndy Wingo 
918*a5a3659dSAndy Wingo   assert(WasmIndices.count(IndirectFunctionTable));
919*a5a3659dSAndy Wingo   uint32_t TableNumber = WasmIndices.find(IndirectFunctionTable)->second;
920*a5a3659dSAndy Wingo   uint32_t Flags = 0;
921*a5a3659dSAndy Wingo   if (TableNumber)
922*a5a3659dSAndy Wingo     Flags |= wasm::WASM_ELEM_SEGMENT_HAS_TABLE_NUMBER;
923*a5a3659dSAndy Wingo   encodeULEB128(Flags, W->OS);
924*a5a3659dSAndy Wingo   if (Flags & wasm::WASM_ELEM_SEGMENT_HAS_TABLE_NUMBER)
925*a5a3659dSAndy Wingo     encodeULEB128(TableNumber, W->OS); // the table number
9269e15f359SSam Clegg 
9279e15f359SSam Clegg   // init expr for starting offset
9280ff28fa6SDerek Schuff   W->OS << char(wasm::WASM_OPCODE_I32_CONST);
9290ff28fa6SDerek Schuff   encodeSLEB128(InitialTableOffset, W->OS);
9300ff28fa6SDerek Schuff   W->OS << char(wasm::WASM_OPCODE_END);
9319e15f359SSam Clegg 
932*a5a3659dSAndy Wingo   if (Flags & wasm::WASM_ELEM_SEGMENT_MASK_HAS_ELEM_KIND) {
933*a5a3659dSAndy Wingo     // We only write active function table initializers, for which the elem kind
934*a5a3659dSAndy Wingo     // is specified to be written as 0x00 and interpreted to mean "funcref".
935*a5a3659dSAndy Wingo     const uint8_t ElemKind = 0;
936*a5a3659dSAndy Wingo     W->OS << ElemKind;
937*a5a3659dSAndy Wingo   }
938*a5a3659dSAndy Wingo 
9390ff28fa6SDerek Schuff   encodeULEB128(TableElems.size(), W->OS);
9409e15f359SSam Clegg   for (uint32_t Elem : TableElems)
9410ff28fa6SDerek Schuff     encodeULEB128(Elem, W->OS);
9429e15f359SSam Clegg 
9439e15f359SSam Clegg   endSection(Section);
9449e15f359SSam Clegg }
9459e15f359SSam Clegg 
946fef8de66SThomas Lively void WasmObjectWriter::writeDataCountSection() {
947fef8de66SThomas Lively   if (DataSegments.empty())
948fef8de66SThomas Lively     return;
949fef8de66SThomas Lively 
950fef8de66SThomas Lively   SectionBookkeeping Section;
951fef8de66SThomas Lively   startSection(Section, wasm::WASM_SEC_DATACOUNT);
9520ff28fa6SDerek Schuff   encodeULEB128(DataSegments.size(), W->OS);
953fef8de66SThomas Lively   endSection(Section);
954fef8de66SThomas Lively }
955fef8de66SThomas Lively 
956e49584a3SSam Clegg uint32_t WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
957457fb0b4SSam Clegg                                             const MCAsmLayout &Layout,
958457fb0b4SSam Clegg                                             ArrayRef<WasmFunction> Functions) {
9599e15f359SSam Clegg   if (Functions.empty())
960e49584a3SSam Clegg     return 0;
9619e15f359SSam Clegg 
9629e15f359SSam Clegg   SectionBookkeeping Section;
9639e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_CODE);
9649e15f359SSam Clegg 
9650ff28fa6SDerek Schuff   encodeULEB128(Functions.size(), W->OS);
9669e15f359SSam Clegg 
9679e15f359SSam Clegg   for (const WasmFunction &Func : Functions) {
968fe6414b0SSam Clegg     auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
9699e15f359SSam Clegg 
9709e15f359SSam Clegg     int64_t Size = 0;
9719e15f359SSam Clegg     if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
9729e15f359SSam Clegg       report_fatal_error(".size expression must be evaluatable");
9739e15f359SSam Clegg 
9740ff28fa6SDerek Schuff     encodeULEB128(Size, W->OS);
9750ff28fa6SDerek Schuff     FuncSection.setSectionOffset(W->OS.tell() - Section.ContentsOffset);
9760ff28fa6SDerek Schuff     Asm.writeSectionData(W->OS, &FuncSection, Layout);
9779e15f359SSam Clegg   }
9789e15f359SSam Clegg 
9799e15f359SSam Clegg   // Apply fixups.
9807ee758d6SSam Clegg   applyRelocations(CodeRelocations, Section.ContentsOffset, Layout);
9819e15f359SSam Clegg 
9829e15f359SSam Clegg   endSection(Section);
983e49584a3SSam Clegg   return Section.Index;
9849e15f359SSam Clegg }
9859e15f359SSam Clegg 
986e49584a3SSam Clegg uint32_t WasmObjectWriter::writeDataSection(const MCAsmLayout &Layout) {
9876c899ba6SSam Clegg   if (DataSegments.empty())
988e49584a3SSam Clegg     return 0;
9899e15f359SSam Clegg 
9909e15f359SSam Clegg   SectionBookkeeping Section;
9919e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_DATA);
9929e15f359SSam Clegg 
9930ff28fa6SDerek Schuff   encodeULEB128(DataSegments.size(), W->OS); // count
9947c395943SSam Clegg 
9956c899ba6SSam Clegg   for (const WasmDataSegment &Segment : DataSegments) {
9960ff28fa6SDerek Schuff     encodeULEB128(Segment.InitFlags, W->OS); // flags
997831a143eSAndy Wingo     if (Segment.InitFlags & wasm::WASM_DATA_SEGMENT_HAS_MEMINDEX)
9980ff28fa6SDerek Schuff       encodeULEB128(0, W->OS); // memory index
999831a143eSAndy Wingo     if ((Segment.InitFlags & wasm::WASM_DATA_SEGMENT_IS_PASSIVE) == 0) {
10000d9b17d0SWouter van Oortmerssen       W->OS << char(is64Bit() ? wasm::WASM_OPCODE_I64_CONST
10014d135b04SWouter van Oortmerssen                               : wasm::WASM_OPCODE_I32_CONST);
10020ff28fa6SDerek Schuff       encodeSLEB128(Segment.Offset, W->OS); // offset
10030ff28fa6SDerek Schuff       W->OS << char(wasm::WASM_OPCODE_END);
10042e150409SThomas Lively     }
10050ff28fa6SDerek Schuff     encodeULEB128(Segment.Data.size(), W->OS); // size
10060ff28fa6SDerek Schuff     Segment.Section->setSectionOffset(W->OS.tell() - Section.ContentsOffset);
10070ff28fa6SDerek Schuff     W->OS << Segment.Data; // data
10087c395943SSam Clegg   }
10099e15f359SSam Clegg 
10109e15f359SSam Clegg   // Apply fixups.
10117ee758d6SSam Clegg   applyRelocations(DataRelocations, Section.ContentsOffset, Layout);
10129e15f359SSam Clegg 
10139e15f359SSam Clegg   endSection(Section);
1014e49584a3SSam Clegg   return Section.Index;
10159e15f359SSam Clegg }
10169e15f359SSam Clegg 
10176f08c84aSSam Clegg void WasmObjectWriter::writeRelocSection(
10186f08c84aSSam Clegg     uint32_t SectionIndex, StringRef Name,
1019f77dc2a8SSam Clegg     std::vector<WasmRelocationEntry> &Relocs) {
10209e15f359SSam Clegg   // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
10219e15f359SSam Clegg   // for descriptions of the reloc sections.
10229e15f359SSam Clegg 
1023f77dc2a8SSam Clegg   if (Relocs.empty())
10249e15f359SSam Clegg     return;
10259e15f359SSam Clegg 
1026f77dc2a8SSam Clegg   // First, ensure the relocations are sorted in offset order.  In general they
1027f77dc2a8SSam Clegg   // should already be sorted since `recordRelocation` is called in offset
1028f77dc2a8SSam Clegg   // order, but for the code section we combine many MC sections into single
1029f77dc2a8SSam Clegg   // wasm section, and this order is determined by the order of Asm.Symbols()
1030f77dc2a8SSam Clegg   // not the sections order.
1031efd94c56SFangrui Song   llvm::stable_sort(
1032efd94c56SFangrui Song       Relocs, [](const WasmRelocationEntry &A, const WasmRelocationEntry &B) {
1033f77dc2a8SSam Clegg         return (A.Offset + A.FixupSection->getSectionOffset()) <
1034f77dc2a8SSam Clegg                (B.Offset + B.FixupSection->getSectionOffset());
1035f77dc2a8SSam Clegg       });
1036f77dc2a8SSam Clegg 
10379e15f359SSam Clegg   SectionBookkeeping Section;
10386f08c84aSSam Clegg   startCustomSection(Section, std::string("reloc.") + Name.str());
10399e15f359SSam Clegg 
10400ff28fa6SDerek Schuff   encodeULEB128(SectionIndex, W->OS);
10410ff28fa6SDerek Schuff   encodeULEB128(Relocs.size(), W->OS);
1042f77dc2a8SSam Clegg   for (const WasmRelocationEntry &RelEntry : Relocs) {
1043f208f631SHeejin Ahn     uint64_t Offset =
1044f208f631SHeejin Ahn         RelEntry.Offset + RelEntry.FixupSection->getSectionOffset();
10456f08c84aSSam Clegg     uint32_t Index = getRelocationIndexValue(RelEntry);
10469e15f359SSam Clegg 
10470ff28fa6SDerek Schuff     W->OS << char(RelEntry.Type);
10480ff28fa6SDerek Schuff     encodeULEB128(Offset, W->OS);
10490ff28fa6SDerek Schuff     encodeULEB128(Index, W->OS);
10506f08c84aSSam Clegg     if (RelEntry.hasAddend())
10510ff28fa6SDerek Schuff       encodeSLEB128(RelEntry.Addend, W->OS);
10529e15f359SSam Clegg   }
10539e15f359SSam Clegg 
10549e15f359SSam Clegg   endSection(Section);
10559e15f359SSam Clegg }
10569e15f359SSam Clegg 
10576a31a0d6SSam Clegg void WasmObjectWriter::writeCustomRelocSections() {
10586a31a0d6SSam Clegg   for (const auto &Sec : CustomSections) {
10596a31a0d6SSam Clegg     auto &Relocations = CustomSectionsRelocations[Sec.Section];
10606a31a0d6SSam Clegg     writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations);
10616a31a0d6SSam Clegg   }
10626a31a0d6SSam Clegg }
10636a31a0d6SSam Clegg 
10649e15f359SSam Clegg void WasmObjectWriter::writeLinkingMetaDataSection(
106586b4a09aSSam Clegg     ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
1066ea7caceeSSam Clegg     ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
1067ea7caceeSSam Clegg     const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) {
10689e15f359SSam Clegg   SectionBookkeeping Section;
10692322a937SSam Clegg   startCustomSection(Section, "linking");
10700ff28fa6SDerek Schuff   encodeULEB128(wasm::WasmMetadataVersion, W->OS);
10719e15f359SSam Clegg 
10726bb5a41fSSam Clegg   SectionBookkeeping SubSection;
10736c899ba6SSam Clegg   if (SymbolInfos.size() != 0) {
10746c899ba6SSam Clegg     startSection(SubSection, wasm::WASM_SYMBOL_TABLE);
10750ff28fa6SDerek Schuff     encodeULEB128(SymbolInfos.size(), W->OS);
10766c899ba6SSam Clegg     for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) {
10770ff28fa6SDerek Schuff       encodeULEB128(Sym.Kind, W->OS);
10780ff28fa6SDerek Schuff       encodeULEB128(Sym.Flags, W->OS);
10796c899ba6SSam Clegg       switch (Sym.Kind) {
10806c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_FUNCTION:
10816c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_GLOBAL:
1082da419bdbSHeejin Ahn       case wasm::WASM_SYMBOL_TYPE_EVENT:
1083388fb67bSPaulo Matos       case wasm::WASM_SYMBOL_TYPE_TABLE:
10840ff28fa6SDerek Schuff         encodeULEB128(Sym.ElementIndex, W->OS);
108529874ceaSDan Gohman         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0 ||
108629874ceaSDan Gohman             (Sym.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0)
10876c899ba6SSam Clegg           writeString(Sym.Name);
10886c899ba6SSam Clegg         break;
10896c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_DATA:
10906c899ba6SSam Clegg         writeString(Sym.Name);
10916c899ba6SSam Clegg         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) {
10920ff28fa6SDerek Schuff           encodeULEB128(Sym.DataRef.Segment, W->OS);
10930ff28fa6SDerek Schuff           encodeULEB128(Sym.DataRef.Offset, W->OS);
10940ff28fa6SDerek Schuff           encodeULEB128(Sym.DataRef.Size, W->OS);
10956c899ba6SSam Clegg         }
10966c899ba6SSam Clegg         break;
10976a31a0d6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_SECTION: {
10986a31a0d6SSam Clegg         const uint32_t SectionIndex =
10996a31a0d6SSam Clegg             CustomSections[Sym.ElementIndex].OutputIndex;
11000ff28fa6SDerek Schuff         encodeULEB128(SectionIndex, W->OS);
11016a31a0d6SSam Clegg         break;
11026a31a0d6SSam Clegg       }
11036c899ba6SSam Clegg       default:
11046c899ba6SSam Clegg         llvm_unreachable("unexpected kind");
11056c899ba6SSam Clegg       }
1106b7787fd0SSam Clegg     }
1107b7787fd0SSam Clegg     endSection(SubSection);
1108b7787fd0SSam Clegg   }
11099e15f359SSam Clegg 
11106c899ba6SSam Clegg   if (DataSegments.size()) {
111163ebb813SSam Clegg     startSection(SubSection, wasm::WASM_SEGMENT_INFO);
11120ff28fa6SDerek Schuff     encodeULEB128(DataSegments.size(), W->OS);
11136c899ba6SSam Clegg     for (const WasmDataSegment &Segment : DataSegments) {
1114d95ed959SSam Clegg       writeString(Segment.Name);
11150ff28fa6SDerek Schuff       encodeULEB128(Segment.Alignment, W->OS);
11160ff28fa6SDerek Schuff       encodeULEB128(Segment.LinkerFlags, W->OS);
111763ebb813SSam Clegg     }
1118d95ed959SSam Clegg     endSection(SubSection);
1119d95ed959SSam Clegg   }
1120d95ed959SSam Clegg 
1121bafe6902SSam Clegg   if (!InitFuncs.empty()) {
1122bafe6902SSam Clegg     startSection(SubSection, wasm::WASM_INIT_FUNCS);
11230ff28fa6SDerek Schuff     encodeULEB128(InitFuncs.size(), W->OS);
1124bafe6902SSam Clegg     for (auto &StartFunc : InitFuncs) {
11250ff28fa6SDerek Schuff       encodeULEB128(StartFunc.first, W->OS);  // priority
11260ff28fa6SDerek Schuff       encodeULEB128(StartFunc.second, W->OS); // function index
1127bafe6902SSam Clegg     }
1128bafe6902SSam Clegg     endSection(SubSection);
1129bafe6902SSam Clegg   }
1130bafe6902SSam Clegg 
1131ea7caceeSSam Clegg   if (Comdats.size()) {
1132ea7caceeSSam Clegg     startSection(SubSection, wasm::WASM_COMDAT_INFO);
11330ff28fa6SDerek Schuff     encodeULEB128(Comdats.size(), W->OS);
1134ea7caceeSSam Clegg     for (const auto &C : Comdats) {
1135ea7caceeSSam Clegg       writeString(C.first);
11360ff28fa6SDerek Schuff       encodeULEB128(0, W->OS); // flags for future use
11370ff28fa6SDerek Schuff       encodeULEB128(C.second.size(), W->OS);
1138ea7caceeSSam Clegg       for (const WasmComdatEntry &Entry : C.second) {
11390ff28fa6SDerek Schuff         encodeULEB128(Entry.Kind, W->OS);
11400ff28fa6SDerek Schuff         encodeULEB128(Entry.Index, W->OS);
1141ea7caceeSSam Clegg       }
1142ea7caceeSSam Clegg     }
1143ea7caceeSSam Clegg     endSection(SubSection);
1144ea7caceeSSam Clegg   }
1145ea7caceeSSam Clegg 
11469e15f359SSam Clegg   endSection(Section);
11479e15f359SSam Clegg }
11489e15f359SSam Clegg 
1149cbda16ebSThomas Lively void WasmObjectWriter::writeCustomSection(WasmCustomSection &CustomSection,
1150cbda16ebSThomas Lively                                           const MCAssembler &Asm,
11516a31a0d6SSam Clegg                                           const MCAsmLayout &Layout) {
1152cfd44a2eSSam Clegg   SectionBookkeeping Section;
11536a31a0d6SSam Clegg   auto *Sec = CustomSection.Section;
11542322a937SSam Clegg   startCustomSection(Section, CustomSection.Name);
11556a31a0d6SSam Clegg 
11560ff28fa6SDerek Schuff   Sec->setSectionOffset(W->OS.tell() - Section.ContentsOffset);
11570ff28fa6SDerek Schuff   Asm.writeSectionData(W->OS, Sec, Layout);
11586a31a0d6SSam Clegg 
11596a31a0d6SSam Clegg   CustomSection.OutputContentsOffset = Section.ContentsOffset;
11606a31a0d6SSam Clegg   CustomSection.OutputIndex = Section.Index;
11616a31a0d6SSam Clegg 
1162cfd44a2eSSam Clegg   endSection(Section);
11636a31a0d6SSam Clegg 
11646a31a0d6SSam Clegg   // Apply fixups.
11654d57fbd0SSam Clegg   auto &Relocations = CustomSectionsRelocations[CustomSection.Section];
11667ee758d6SSam Clegg   applyRelocations(Relocations, CustomSection.OutputContentsOffset, Layout);
11676a31a0d6SSam Clegg }
11686a31a0d6SSam Clegg 
11695e3d33a7SSam Clegg uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm &Symbol) {
11705e3d33a7SSam Clegg   assert(Symbol.isFunction());
11715e3d33a7SSam Clegg   assert(TypeIndices.count(&Symbol));
11725e3d33a7SSam Clegg   return TypeIndices[&Symbol];
11735e3d33a7SSam Clegg }
11745e3d33a7SSam Clegg 
1175da419bdbSHeejin Ahn uint32_t WasmObjectWriter::getEventType(const MCSymbolWasm &Symbol) {
1176da419bdbSHeejin Ahn   assert(Symbol.isEvent());
1177da419bdbSHeejin Ahn   assert(TypeIndices.count(&Symbol));
1178da419bdbSHeejin Ahn   return TypeIndices[&Symbol];
1179da419bdbSHeejin Ahn }
1180da419bdbSHeejin Ahn 
118138b12f5eSHeejin Ahn void WasmObjectWriter::registerFunctionType(const MCSymbolWasm &Symbol) {
11825e3d33a7SSam Clegg   assert(Symbol.isFunction());
11835e3d33a7SSam Clegg 
11844c41fb5aSHeejin Ahn   wasm::WasmSignature S;
11857ee758d6SSam Clegg 
11867ee758d6SSam Clegg   if (auto *Sig = Symbol.getSignature()) {
1187da419bdbSHeejin Ahn     S.Returns = Sig->Returns;
1188da419bdbSHeejin Ahn     S.Params = Sig->Params;
118977a7a380SDerek Schuff   }
11905e3d33a7SSam Clegg 
1191da419bdbSHeejin Ahn   auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
11925e3d33a7SSam Clegg   if (Pair.second)
1193da419bdbSHeejin Ahn     Signatures.push_back(S);
11945e3d33a7SSam Clegg   TypeIndices[&Symbol] = Pair.first->second;
11955e3d33a7SSam Clegg 
1196d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "registerFunctionType: " << Symbol
1197d34e60caSNicola Zaghen                     << " new:" << Pair.second << "\n");
1198d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
11995e3d33a7SSam Clegg }
12005e3d33a7SSam Clegg 
120138b12f5eSHeejin Ahn void WasmObjectWriter::registerEventType(const MCSymbolWasm &Symbol) {
1202da419bdbSHeejin Ahn   assert(Symbol.isEvent());
1203da419bdbSHeejin Ahn 
1204da419bdbSHeejin Ahn   // TODO Currently we don't generate imported exceptions, but if we do, we
1205da419bdbSHeejin Ahn   // should have a way of infering types of imported exceptions.
12064c41fb5aSHeejin Ahn   wasm::WasmSignature S;
1207da419bdbSHeejin Ahn   if (auto *Sig = Symbol.getSignature()) {
1208da419bdbSHeejin Ahn     S.Returns = Sig->Returns;
1209da419bdbSHeejin Ahn     S.Params = Sig->Params;
1210da419bdbSHeejin Ahn   }
1211da419bdbSHeejin Ahn 
1212da419bdbSHeejin Ahn   auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
1213da419bdbSHeejin Ahn   if (Pair.second)
1214da419bdbSHeejin Ahn     Signatures.push_back(S);
1215da419bdbSHeejin Ahn   TypeIndices[&Symbol] = Pair.first->second;
1216da419bdbSHeejin Ahn 
1217da419bdbSHeejin Ahn   LLVM_DEBUG(dbgs() << "registerEventType: " << Symbol << " new:" << Pair.second
1218da419bdbSHeejin Ahn                     << "\n");
1219da419bdbSHeejin Ahn   LLVM_DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
1220da419bdbSHeejin Ahn }
1221da419bdbSHeejin Ahn 
12224d57fbd0SSam Clegg static bool isInSymtab(const MCSymbolWasm &Sym) {
12233ea1c62cSSam Clegg   if (Sym.isUsedInReloc() || Sym.isUsedInInitArray())
12244d57fbd0SSam Clegg     return true;
12254d57fbd0SSam Clegg 
12264d57fbd0SSam Clegg   if (Sym.isComdat() && !Sym.isDefined())
12274d57fbd0SSam Clegg     return false;
12284d57fbd0SSam Clegg 
12293ea1c62cSSam Clegg   if (Sym.isTemporary())
12304d57fbd0SSam Clegg     return false;
12314d57fbd0SSam Clegg 
12324d57fbd0SSam Clegg   if (Sym.isSection())
12334d57fbd0SSam Clegg     return false;
12344d57fbd0SSam Clegg 
12352632ba6aSAndy Wingo   if (Sym.omitFromLinkingSection())
12362632ba6aSAndy Wingo     return false;
12372632ba6aSAndy Wingo 
12384d57fbd0SSam Clegg   return true;
12394d57fbd0SSam Clegg }
124030d314aaSSam Clegg 
12410ff28fa6SDerek Schuff void WasmObjectWriter::prepareImports(
12420ff28fa6SDerek Schuff     SmallVectorImpl<wasm::WasmImport> &Imports, MCAssembler &Asm,
124318eafb6cSDan Gohman     const MCAsmLayout &Layout) {
1244f950b24aSSam Clegg   // For now, always emit the memory import, since loads and stores are not
1245f950b24aSSam Clegg   // valid without it. In the future, we could perhaps be more clever and omit
1246f950b24aSSam Clegg   // it if there are no loads or stores.
12478defa952SSam Clegg   wasm::WasmImport MemImport;
12481ed3a046SSam Clegg   MemImport.Module = "env";
12491ed3a046SSam Clegg   MemImport.Field = "__linear_memory";
1250f950b24aSSam Clegg   MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
1251fd0964aeSWouter van Oortmerssen   MemImport.Memory.Flags = is64Bit() ? wasm::WASM_LIMITS_FLAG_IS_64
1252fd0964aeSWouter van Oortmerssen                                      : wasm::WASM_LIMITS_FLAG_NONE;
1253f950b24aSSam Clegg   Imports.push_back(MemImport);
1254f950b24aSSam Clegg 
1255da419bdbSHeejin Ahn   // Populate SignatureIndices, and Imports and WasmIndices for undefined
1256586320c0SNicholas Wilson   // symbols.  This must be done before populating WasmIndices for defined
1257586320c0SNicholas Wilson   // symbols.
125832ce5ca0SDan Gohman   for (const MCSymbol &S : Asm.symbols()) {
125932ce5ca0SDan Gohman     const auto &WS = static_cast<const MCSymbolWasm &>(S);
126032ce5ca0SDan Gohman 
126132ce5ca0SDan Gohman     // Register types for all functions, including those with private linkage
12629f3fe42eSSam Clegg     // (because wasm always needs a type signature).
12637ee758d6SSam Clegg     if (WS.isFunction()) {
12649c7b5808SDominic Chen       const auto *BS = Layout.getBaseSymbol(S);
12659c7b5808SDominic Chen       if (!BS)
12669c7b5808SDominic Chen         report_fatal_error(Twine(S.getName()) +
12679c7b5808SDominic Chen                            ": absolute addressing not supported!");
12689c7b5808SDominic Chen       registerFunctionType(*cast<MCSymbolWasm>(BS));
12697ee758d6SSam Clegg     }
127032ce5ca0SDan Gohman 
1271da419bdbSHeejin Ahn     if (WS.isEvent())
1272da419bdbSHeejin Ahn       registerEventType(WS);
1273da419bdbSHeejin Ahn 
127432ce5ca0SDan Gohman     if (WS.isTemporary())
127532ce5ca0SDan Gohman       continue;
127632ce5ca0SDan Gohman 
127732ce5ca0SDan Gohman     // If the symbol is not defined in this translation unit, import it.
12786c899ba6SSam Clegg     if (!WS.isDefined() && !WS.isComdat()) {
12796c899ba6SSam Clegg       if (WS.isFunction()) {
12808defa952SSam Clegg         wasm::WasmImport Import;
1281f726e445SDan Gohman         Import.Module = WS.getImportModule();
1282f726e445SDan Gohman         Import.Field = WS.getImportName();
128332ce5ca0SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
12848defa952SSam Clegg         Import.SigIndex = getFunctionType(WS);
12856c899ba6SSam Clegg         Imports.push_back(Import);
1286492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
12876c899ba6SSam Clegg         WasmIndices[&WS] = NumFunctionImports++;
12886c899ba6SSam Clegg       } else if (WS.isGlobal()) {
128915f349f7SNicholas Wilson         if (WS.isWeak())
129015f349f7SNicholas Wilson           report_fatal_error("undefined global symbol cannot be weak");
129115f349f7SNicholas Wilson 
12926c899ba6SSam Clegg         wasm::WasmImport Import;
1293f726e445SDan Gohman         Import.Field = WS.getImportName();
129432ce5ca0SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1295492f7529SSam Clegg         Import.Module = WS.getImportModule();
12966c899ba6SSam Clegg         Import.Global = WS.getGlobalType();
12976c899ba6SSam Clegg         Imports.push_back(Import);
1298492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
12996c899ba6SSam Clegg         WasmIndices[&WS] = NumGlobalImports++;
1300da419bdbSHeejin Ahn       } else if (WS.isEvent()) {
1301da419bdbSHeejin Ahn         if (WS.isWeak())
1302da419bdbSHeejin Ahn           report_fatal_error("undefined event symbol cannot be weak");
1303da419bdbSHeejin Ahn 
1304da419bdbSHeejin Ahn         wasm::WasmImport Import;
1305f726e445SDan Gohman         Import.Module = WS.getImportModule();
1306f726e445SDan Gohman         Import.Field = WS.getImportName();
1307da419bdbSHeejin Ahn         Import.Kind = wasm::WASM_EXTERNAL_EVENT;
1308da419bdbSHeejin Ahn         Import.Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
1309da419bdbSHeejin Ahn         Import.Event.SigIndex = getEventType(WS);
1310da419bdbSHeejin Ahn         Imports.push_back(Import);
1311492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
1312da419bdbSHeejin Ahn         WasmIndices[&WS] = NumEventImports++;
1313feac819eSAndy Wingo       } else if (WS.isTable()) {
1314feac819eSAndy Wingo         if (WS.isWeak())
1315feac819eSAndy Wingo           report_fatal_error("undefined table symbol cannot be weak");
1316feac819eSAndy Wingo 
1317feac819eSAndy Wingo         wasm::WasmImport Import;
1318feac819eSAndy Wingo         Import.Module = WS.getImportModule();
1319feac819eSAndy Wingo         Import.Field = WS.getImportName();
1320feac819eSAndy Wingo         Import.Kind = wasm::WASM_EXTERNAL_TABLE;
1321feac819eSAndy Wingo         wasm::ValType ElemType = WS.getTableType();
1322feac819eSAndy Wingo         Import.Table.ElemType = uint8_t(ElemType);
1323feac819eSAndy Wingo         // FIXME: Extend table type to include limits? For now we don't specify
1324feac819eSAndy Wingo         // a min or max which does not place any restrictions on the size of the
1325feac819eSAndy Wingo         // imported table.
1326feac819eSAndy Wingo         Import.Table.Limits = {wasm::WASM_LIMITS_FLAG_NONE, 0, 0};
1327feac819eSAndy Wingo         Imports.push_back(Import);
1328feac819eSAndy Wingo         assert(WasmIndices.count(&WS) == 0);
1329feac819eSAndy Wingo         WasmIndices[&WS] = NumTableImports++;
133032ce5ca0SDan Gohman       }
133132ce5ca0SDan Gohman     }
133232ce5ca0SDan Gohman   }
133332ce5ca0SDan Gohman 
1334492f7529SSam Clegg   // Add imports for GOT globals
1335492f7529SSam Clegg   for (const MCSymbol &S : Asm.symbols()) {
1336492f7529SSam Clegg     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1337492f7529SSam Clegg     if (WS.isUsedInGOT()) {
1338492f7529SSam Clegg       wasm::WasmImport Import;
1339492f7529SSam Clegg       if (WS.isFunction())
1340492f7529SSam Clegg         Import.Module = "GOT.func";
1341492f7529SSam Clegg       else
1342492f7529SSam Clegg         Import.Module = "GOT.mem";
1343492f7529SSam Clegg       Import.Field = WS.getName();
1344492f7529SSam Clegg       Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1345492f7529SSam Clegg       Import.Global = {wasm::WASM_TYPE_I32, true};
1346492f7529SSam Clegg       Imports.push_back(Import);
1347492f7529SSam Clegg       assert(GOTIndices.count(&WS) == 0);
1348492f7529SSam Clegg       GOTIndices[&WS] = NumGlobalImports++;
1349492f7529SSam Clegg     }
1350492f7529SSam Clegg   }
13510ff28fa6SDerek Schuff }
1352492f7529SSam Clegg 
13530ff28fa6SDerek Schuff uint64_t WasmObjectWriter::writeObject(MCAssembler &Asm,
13540ff28fa6SDerek Schuff                                        const MCAsmLayout &Layout) {
13550ff28fa6SDerek Schuff   support::endian::Writer MainWriter(*OS, support::little);
13560ff28fa6SDerek Schuff   W = &MainWriter;
13570ff28fa6SDerek Schuff   if (IsSplitDwarf) {
13580ff28fa6SDerek Schuff     uint64_t TotalSize = writeOneObject(Asm, Layout, DwoMode::NonDwoOnly);
13590ff28fa6SDerek Schuff     assert(DwoOS);
13600ff28fa6SDerek Schuff     support::endian::Writer DwoWriter(*DwoOS, support::little);
13610ff28fa6SDerek Schuff     W = &DwoWriter;
13620ff28fa6SDerek Schuff     return TotalSize + writeOneObject(Asm, Layout, DwoMode::DwoOnly);
13630ff28fa6SDerek Schuff   } else {
13640ff28fa6SDerek Schuff     return writeOneObject(Asm, Layout, DwoMode::AllSections);
13650ff28fa6SDerek Schuff   }
13660ff28fa6SDerek Schuff }
13670ff28fa6SDerek Schuff 
13680ff28fa6SDerek Schuff uint64_t WasmObjectWriter::writeOneObject(MCAssembler &Asm,
13690ff28fa6SDerek Schuff                                           const MCAsmLayout &Layout,
13700ff28fa6SDerek Schuff                                           DwoMode Mode) {
13710ff28fa6SDerek Schuff   uint64_t StartOffset = W->OS.tell();
13720ff28fa6SDerek Schuff   SectionCount = 0;
13730ff28fa6SDerek Schuff   CustomSections.clear();
13740ff28fa6SDerek Schuff 
13750ff28fa6SDerek Schuff   LLVM_DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
13760ff28fa6SDerek Schuff 
13770ff28fa6SDerek Schuff   // Collect information from the available symbols.
13780ff28fa6SDerek Schuff   SmallVector<WasmFunction, 4> Functions;
13790ff28fa6SDerek Schuff   SmallVector<uint32_t, 4> TableElems;
13800ff28fa6SDerek Schuff   SmallVector<wasm::WasmImport, 4> Imports;
13810ff28fa6SDerek Schuff   SmallVector<wasm::WasmExport, 4> Exports;
13820ff28fa6SDerek Schuff   SmallVector<wasm::WasmEventType, 1> Events;
13830ff28fa6SDerek Schuff   SmallVector<wasm::WasmGlobal, 1> Globals;
1384388fb67bSPaulo Matos   SmallVector<wasm::WasmTable, 1> Tables;
13850ff28fa6SDerek Schuff   SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos;
13860ff28fa6SDerek Schuff   SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
13870ff28fa6SDerek Schuff   std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
13880ff28fa6SDerek Schuff   uint64_t DataSize = 0;
13890ff28fa6SDerek Schuff   if (Mode != DwoMode::DwoOnly) {
13900ff28fa6SDerek Schuff     prepareImports(Imports, Asm, Layout);
13910ff28fa6SDerek Schuff   }
139230d314aaSSam Clegg 
13934d57fbd0SSam Clegg   // Populate DataSegments and CustomSections, which must be done before
13944d57fbd0SSam Clegg   // populating DataLocations.
1395759631c7SSam Clegg   for (MCSection &Sec : Asm) {
1396759631c7SSam Clegg     auto &Section = static_cast<MCSectionWasm &>(Sec);
13977d1ff446SFangrui Song     StringRef SectionName = Section.getName();
1398759631c7SSam Clegg 
13990ff28fa6SDerek Schuff     if (Mode == DwoMode::NonDwoOnly && isDwoSection(Sec))
14000ff28fa6SDerek Schuff       continue;
14010ff28fa6SDerek Schuff     if (Mode == DwoMode::DwoOnly && !isDwoSection(Sec))
14020ff28fa6SDerek Schuff       continue;
14030ff28fa6SDerek Schuff 
14048d396acaSDerek Schuff     LLVM_DEBUG(dbgs() << "Processing Section " << SectionName << "  group "
14058d396acaSDerek Schuff                       << Section.getGroup() << "\n";);
14068d396acaSDerek Schuff 
1407bafe6902SSam Clegg     // .init_array sections are handled specially elsewhere.
14084d57fbd0SSam Clegg     if (SectionName.startswith(".init_array"))
1409bafe6902SSam Clegg       continue;
1410bafe6902SSam Clegg 
14114d57fbd0SSam Clegg     // Code is handled separately
14124d57fbd0SSam Clegg     if (Section.getKind().isText())
14134d57fbd0SSam Clegg       continue;
14144d57fbd0SSam Clegg 
14154d57fbd0SSam Clegg     if (Section.isWasmData()) {
1416329e76d5SSam Clegg       uint32_t SegmentIndex = DataSegments.size();
1417759631c7SSam Clegg       DataSize = alignTo(DataSize, Section.getAlignment());
1418759631c7SSam Clegg       DataSegments.emplace_back();
1419759631c7SSam Clegg       WasmDataSegment &Segment = DataSegments.back();
14204d57fbd0SSam Clegg       Segment.Name = SectionName;
1421831a143eSAndy Wingo       Segment.InitFlags = Section.getPassive()
1422831a143eSAndy Wingo                               ? (uint32_t)wasm::WASM_DATA_SEGMENT_IS_PASSIVE
1423831a143eSAndy Wingo                               : 0;
1424759631c7SSam Clegg       Segment.Offset = DataSize;
1425759631c7SSam Clegg       Segment.Section = &Section;
142663ebb813SSam Clegg       addData(Segment.Data, Section);
142756c587adSSam Clegg       Segment.Alignment = Log2_32(Section.getAlignment());
14282e150409SThomas Lively       Segment.LinkerFlags = 0;
1429759631c7SSam Clegg       DataSize += Segment.Data.size();
14306c899ba6SSam Clegg       Section.setSegmentIndex(SegmentIndex);
1431ea7caceeSSam Clegg 
1432ea7caceeSSam Clegg       if (const MCSymbolWasm *C = Section.getGroup()) {
1433ea7caceeSSam Clegg         Comdats[C->getName()].emplace_back(
1434329e76d5SSam Clegg             WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
1435ea7caceeSSam Clegg       }
14364d57fbd0SSam Clegg     } else {
14374d57fbd0SSam Clegg       // Create custom sections
14384d57fbd0SSam Clegg       assert(Sec.getKind().isMetadata());
14394d57fbd0SSam Clegg 
14404d57fbd0SSam Clegg       StringRef Name = SectionName;
14414d57fbd0SSam Clegg 
14424d57fbd0SSam Clegg       // For user-defined custom sections, strip the prefix
14434d57fbd0SSam Clegg       if (Name.startswith(".custom_section."))
14444d57fbd0SSam Clegg         Name = Name.substr(strlen(".custom_section."));
14454d57fbd0SSam Clegg 
14464d57fbd0SSam Clegg       MCSymbol *Begin = Sec.getBeginSymbol();
1447fb807d4dSSam Clegg       if (Begin) {
144830d314aaSSam Clegg         assert(WasmIndices.count(cast<MCSymbolWasm>(Begin)) == 0);
14494d57fbd0SSam Clegg         WasmIndices[cast<MCSymbolWasm>(Begin)] = CustomSections.size();
1450fb807d4dSSam Clegg       }
1451cbda16ebSThomas Lively 
1452f6f4f843SThomas Lively       // Separate out the producers and target features sections
1453cbda16ebSThomas Lively       if (Name == "producers") {
14540eaee545SJonas Devlieghere         ProducersSection = std::make_unique<WasmCustomSection>(Name, &Section);
1455cbda16ebSThomas Lively         continue;
1456cbda16ebSThomas Lively       }
1457f6f4f843SThomas Lively       if (Name == "target_features") {
1458f6f4f843SThomas Lively         TargetFeaturesSection =
14590eaee545SJonas Devlieghere             std::make_unique<WasmCustomSection>(Name, &Section);
1460f6f4f843SThomas Lively         continue;
1461f6f4f843SThomas Lively       }
1462cbda16ebSThomas Lively 
14630a391060SDerek Schuff       // Custom sections can also belong to COMDAT groups. In this case the
14640a391060SDerek Schuff       // decriptor's "index" field is the section index (in the final object
14650a391060SDerek Schuff       // file), but that is not known until after layout, so it must be fixed up
14660a391060SDerek Schuff       // later
14670a391060SDerek Schuff       if (const MCSymbolWasm *C = Section.getGroup()) {
14680a391060SDerek Schuff         Comdats[C->getName()].emplace_back(
14690a391060SDerek Schuff             WasmComdatEntry{wasm::WASM_COMDAT_SECTION,
14700a391060SDerek Schuff                             static_cast<uint32_t>(CustomSections.size())});
14710a391060SDerek Schuff       }
14720a391060SDerek Schuff 
14734d57fbd0SSam Clegg       CustomSections.emplace_back(Name, &Section);
1474759631c7SSam Clegg     }
14756a31a0d6SSam Clegg   }
14766a31a0d6SSam Clegg 
147730d314aaSSam Clegg   if (Mode != DwoMode::DwoOnly) {
1478586320c0SNicholas Wilson     // Populate WasmIndices and DataLocations for defined symbols.
1479d934cb88SDan Gohman     for (const MCSymbol &S : Asm.symbols()) {
1480d934cb88SDan Gohman       // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1481d934cb88SDan Gohman       // or used in relocations.
1482d934cb88SDan Gohman       if (S.isTemporary() && S.getName().empty())
1483d934cb88SDan Gohman         continue;
1484b7787fd0SSam Clegg 
1485d934cb88SDan Gohman       const auto &WS = static_cast<const MCSymbolWasm &>(S);
14865e5b2cb1SWouter van Oortmerssen       LLVM_DEBUG(dbgs()
14875e5b2cb1SWouter van Oortmerssen                  << "MCSymbol: "
14885e5b2cb1SWouter van Oortmerssen                  << toString(WS.getType().getValueOr(wasm::WASM_SYMBOL_TYPE_DATA))
14895e5b2cb1SWouter van Oortmerssen                  << " '" << S << "'"
1490d34e60caSNicola Zaghen                  << " isDefined=" << S.isDefined() << " isExternal="
1491d34e60caSNicola Zaghen                  << S.isExternal() << " isTemporary=" << S.isTemporary()
1492d34e60caSNicola Zaghen                  << " isWeak=" << WS.isWeak() << " isHidden=" << WS.isHidden()
1493b7787fd0SSam Clegg                  << " isVariable=" << WS.isVariable() << "\n");
1494b7787fd0SSam Clegg 
14955e3d33a7SSam Clegg       if (WS.isVariable())
14965e3d33a7SSam Clegg         continue;
14976c899ba6SSam Clegg       if (WS.isComdat() && !WS.isDefined())
14986c899ba6SSam Clegg         continue;
1499b7787fd0SSam Clegg 
1500d934cb88SDan Gohman       if (WS.isFunction()) {
15016c899ba6SSam Clegg         unsigned Index;
1502cd65f698SSam Clegg         if (WS.isDefined()) {
1503b7787fd0SSam Clegg           if (WS.getOffset() != 0)
1504b7787fd0SSam Clegg             report_fatal_error(
1505b7787fd0SSam Clegg                 "function sections must contain one function each");
1506b7787fd0SSam Clegg 
150718c56a07SHeejin Ahn           if (WS.getSize() == nullptr)
1508b7787fd0SSam Clegg             report_fatal_error(
1509b7787fd0SSam Clegg                 "function symbols must have a size set with .size");
1510b7787fd0SSam Clegg 
15116c899ba6SSam Clegg           // A definition. Write out the function body.
15129f3fe42eSSam Clegg           Index = NumFunctionImports + Functions.size();
1513d934cb88SDan Gohman           WasmFunction Func;
1514da419bdbSHeejin Ahn           Func.SigIndex = getFunctionType(WS);
1515d934cb88SDan Gohman           Func.Sym = &WS;
151630d314aaSSam Clegg           assert(WasmIndices.count(&WS) == 0);
15176c899ba6SSam Clegg           WasmIndices[&WS] = Index;
1518d934cb88SDan Gohman           Functions.push_back(Func);
15196c899ba6SSam Clegg 
15206c899ba6SSam Clegg           auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
15216c899ba6SSam Clegg           if (const MCSymbolWasm *C = Section.getGroup()) {
15226c899ba6SSam Clegg             Comdats[C->getName()].emplace_back(
15236c899ba6SSam Clegg                 WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
15246c899ba6SSam Clegg           }
1525881d8778SSam Clegg 
1526881d8778SSam Clegg           if (WS.hasExportName()) {
1527881d8778SSam Clegg             wasm::WasmExport Export;
1528881d8778SSam Clegg             Export.Name = WS.getExportName();
1529881d8778SSam Clegg             Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1530881d8778SSam Clegg             Export.Index = Index;
1531881d8778SSam Clegg             Exports.push_back(Export);
1532881d8778SSam Clegg           }
1533d934cb88SDan Gohman         } else {
1534d934cb88SDan Gohman           // An import; the index was assigned above.
15356c899ba6SSam Clegg           Index = WasmIndices.find(&WS)->second;
1536d934cb88SDan Gohman         }
1537d934cb88SDan Gohman 
1538d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "  -> function index: " << Index << "\n");
1539da419bdbSHeejin Ahn 
15406c899ba6SSam Clegg       } else if (WS.isData()) {
1541f3feb6adSWouter van Oortmerssen         if (!isInSymtab(WS))
1542c38e947eSSam Clegg           continue;
1543c38e947eSSam Clegg 
15446c899ba6SSam Clegg         if (!WS.isDefined()) {
1545d34e60caSNicola Zaghen           LLVM_DEBUG(dbgs() << "  -> segment index: -1"
1546d34e60caSNicola Zaghen                             << "\n");
1547fe6414b0SSam Clegg           continue;
15486c899ba6SSam Clegg         }
1549fe6414b0SSam Clegg 
1550d934cb88SDan Gohman         if (!WS.getSize())
1551c38e947eSSam Clegg           report_fatal_error("data symbols must have a size set with .size: " +
1552c38e947eSSam Clegg                              WS.getName());
1553d934cb88SDan Gohman 
1554d934cb88SDan Gohman         int64_t Size = 0;
1555d934cb88SDan Gohman         if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1556d934cb88SDan Gohman           report_fatal_error(".size expression must be evaluatable");
1557d934cb88SDan Gohman 
1558759631c7SSam Clegg         auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
1559079cba04SSam Clegg         if (!DataSection.isWasmData())
1560079cba04SSam Clegg           report_fatal_error("data symbols must live in a data section: " +
1561079cba04SSam Clegg                              WS.getName());
15627c395943SSam Clegg 
15636c899ba6SSam Clegg         // For each data symbol, export it in the symtab as a reference to the
15646c899ba6SSam Clegg         // corresponding Wasm data segment.
15656c899ba6SSam Clegg         wasm::WasmDataReference Ref = wasm::WasmDataReference{
15663b29376eSWouter van Oortmerssen             DataSection.getSegmentIndex(), Layout.getSymbolOffset(WS),
15673b29376eSWouter van Oortmerssen             static_cast<uint64_t>(Size)};
156830d314aaSSam Clegg         assert(DataLocations.count(&WS) == 0);
15696c899ba6SSam Clegg         DataLocations[&WS] = Ref;
1570d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "  -> segment index: " << Ref.Segment << "\n");
1571da419bdbSHeejin Ahn 
1572a165f2d6SSam Clegg       } else if (WS.isGlobal()) {
15736c899ba6SSam Clegg         // A "true" Wasm global (currently just __stack_pointer)
15740a6c4d8dSSam Clegg         if (WS.isDefined()) {
15750a6c4d8dSSam Clegg           wasm::WasmGlobal Global;
15760a6c4d8dSSam Clegg           Global.Type = WS.getGlobalType();
15770a6c4d8dSSam Clegg           Global.Index = NumGlobalImports + Globals.size();
15780a6c4d8dSSam Clegg           switch (Global.Type.Type) {
15790a6c4d8dSSam Clegg           case wasm::WASM_TYPE_I32:
15800a6c4d8dSSam Clegg             Global.InitExpr.Opcode = wasm::WASM_OPCODE_I32_CONST;
15810a6c4d8dSSam Clegg             break;
15820a6c4d8dSSam Clegg           case wasm::WASM_TYPE_I64:
15830a6c4d8dSSam Clegg             Global.InitExpr.Opcode = wasm::WASM_OPCODE_I64_CONST;
15840a6c4d8dSSam Clegg             break;
15850a6c4d8dSSam Clegg           case wasm::WASM_TYPE_F32:
15860a6c4d8dSSam Clegg             Global.InitExpr.Opcode = wasm::WASM_OPCODE_F32_CONST;
15870a6c4d8dSSam Clegg             break;
15880a6c4d8dSSam Clegg           case wasm::WASM_TYPE_F64:
15890a6c4d8dSSam Clegg             Global.InitExpr.Opcode = wasm::WASM_OPCODE_F64_CONST;
15900a6c4d8dSSam Clegg             break;
159179aad89dSSam Clegg           case wasm::WASM_TYPE_EXTERNREF:
159279aad89dSSam Clegg             Global.InitExpr.Opcode = wasm::WASM_OPCODE_REF_NULL;
159379aad89dSSam Clegg             break;
15940a6c4d8dSSam Clegg           default:
15950a6c4d8dSSam Clegg             llvm_unreachable("unexpected type");
15960a6c4d8dSSam Clegg           }
159730d314aaSSam Clegg           assert(WasmIndices.count(&WS) == 0);
15980a6c4d8dSSam Clegg           WasmIndices[&WS] = Global.Index;
15990a6c4d8dSSam Clegg           Globals.push_back(Global);
16000a6c4d8dSSam Clegg         } else {
1601545932beSEric Christopher           // An import; the index was assigned above
1602d34e60caSNicola Zaghen           LLVM_DEBUG(dbgs() << "  -> global index: "
1603d34e60caSNicola Zaghen                             << WasmIndices.find(&WS)->second << "\n");
16040a6c4d8dSSam Clegg         }
1605388fb67bSPaulo Matos       } else if (WS.isTable()) {
1606388fb67bSPaulo Matos         if (WS.isDefined()) {
1607388fb67bSPaulo Matos           wasm::WasmTable Table;
1608388fb67bSPaulo Matos           Table.Index = NumTableImports + Tables.size();
16091933c9d4SAndy Wingo           Table.Type.ElemType = static_cast<uint8_t>(WS.getTableType());
1610388fb67bSPaulo Matos           // FIXME: Work on custom limits is ongoing
16111933c9d4SAndy Wingo           Table.Type.Limits = {wasm::WASM_LIMITS_FLAG_NONE, 0, 0};
161230d314aaSSam Clegg           assert(WasmIndices.count(&WS) == 0);
1613388fb67bSPaulo Matos           WasmIndices[&WS] = Table.Index;
1614388fb67bSPaulo Matos           Tables.push_back(Table);
1615388fb67bSPaulo Matos         }
161630d314aaSSam Clegg         LLVM_DEBUG(dbgs() << " -> table index: "
161730d314aaSSam Clegg                           << WasmIndices.find(&WS)->second << "\n");
1618da419bdbSHeejin Ahn       } else if (WS.isEvent()) {
1619da419bdbSHeejin Ahn         // C++ exception symbol (__cpp_exception)
1620da419bdbSHeejin Ahn         unsigned Index;
1621da419bdbSHeejin Ahn         if (WS.isDefined()) {
1622da419bdbSHeejin Ahn           Index = NumEventImports + Events.size();
1623da419bdbSHeejin Ahn           wasm::WasmEventType Event;
1624da419bdbSHeejin Ahn           Event.SigIndex = getEventType(WS);
1625da419bdbSHeejin Ahn           Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
162630d314aaSSam Clegg           assert(WasmIndices.count(&WS) == 0);
1627da419bdbSHeejin Ahn           WasmIndices[&WS] = Index;
1628da419bdbSHeejin Ahn           Events.push_back(Event);
1629da419bdbSHeejin Ahn         } else {
1630da419bdbSHeejin Ahn           // An import; the index was assigned above.
1631492f7529SSam Clegg           assert(WasmIndices.count(&WS) > 0);
1632da419bdbSHeejin Ahn         }
163330d314aaSSam Clegg         LLVM_DEBUG(dbgs() << "  -> event index: "
163430d314aaSSam Clegg                           << WasmIndices.find(&WS)->second << "\n");
1635da419bdbSHeejin Ahn 
1636a165f2d6SSam Clegg       } else {
1637a165f2d6SSam Clegg         assert(WS.isSection());
1638d934cb88SDan Gohman       }
1639d934cb88SDan Gohman     }
1640d934cb88SDan Gohman 
1641586320c0SNicholas Wilson     // Populate WasmIndices and DataLocations for aliased symbols.  We need to
1642586320c0SNicholas Wilson     // process these in a separate pass because we need to have processed the
1643586320c0SNicholas Wilson     // target of the alias before the alias itself and the symbols are not
1644586320c0SNicholas Wilson     // necessarily ordered in this way.
1645b7787fd0SSam Clegg     for (const MCSymbol &S : Asm.symbols()) {
1646b7787fd0SSam Clegg       if (!S.isVariable())
1647b7787fd0SSam Clegg         continue;
164831a2c809SSam Clegg 
1649cd65f698SSam Clegg       assert(S.isDefined());
1650b7787fd0SSam Clegg 
16519c7b5808SDominic Chen       const auto *BS = Layout.getBaseSymbol(S);
16529c7b5808SDominic Chen       if (!BS)
16539c7b5808SDominic Chen         report_fatal_error(Twine(S.getName()) +
16549c7b5808SDominic Chen                            ": absolute addressing not supported!");
16559c7b5808SDominic Chen       const MCSymbolWasm *Base = cast<MCSymbolWasm>(BS);
16567ee758d6SSam Clegg 
16575e3d33a7SSam Clegg       // Find the target symbol of this weak alias and export that index
1658aff1c4dfSSam Clegg       const auto &WS = static_cast<const MCSymbolWasm &>(S);
165930d314aaSSam Clegg       LLVM_DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *Base
166030d314aaSSam Clegg                         << "'\n");
1661b7787fd0SSam Clegg 
16627ee758d6SSam Clegg       if (Base->isFunction()) {
16637ee758d6SSam Clegg         assert(WasmIndices.count(Base) > 0);
16647ee758d6SSam Clegg         uint32_t WasmIndex = WasmIndices.find(Base)->second;
1665492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
16666c899ba6SSam Clegg         WasmIndices[&WS] = WasmIndex;
1667d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "  -> index:" << WasmIndex << "\n");
16687ee758d6SSam Clegg       } else if (Base->isData()) {
16697ee758d6SSam Clegg         auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
16707ee758d6SSam Clegg         uint64_t Offset = Layout.getSymbolOffset(S);
16717ee758d6SSam Clegg         int64_t Size = 0;
16727ee758d6SSam Clegg         // For data symbol alias we use the size of the base symbol as the
16737ee758d6SSam Clegg         // size of the alias.  When an offset from the base is involved this
16747ee758d6SSam Clegg         // can result in a offset + size goes past the end of the data section
16757ee758d6SSam Clegg         // which out object format doesn't support.  So we must clamp it.
16767ee758d6SSam Clegg         if (!Base->getSize()->evaluateAsAbsolute(Size, Layout))
16777ee758d6SSam Clegg           report_fatal_error(".size expression must be evaluatable");
16787ee758d6SSam Clegg         const WasmDataSegment &Segment =
16797ee758d6SSam Clegg             DataSegments[DataSection.getSegmentIndex()];
16807ee758d6SSam Clegg         Size =
16817ee758d6SSam Clegg             std::min(static_cast<uint64_t>(Size), Segment.Data.size() - Offset);
16827ee758d6SSam Clegg         wasm::WasmDataReference Ref = wasm::WasmDataReference{
16837ee758d6SSam Clegg             DataSection.getSegmentIndex(),
16847ee758d6SSam Clegg             static_cast<uint32_t>(Layout.getSymbolOffset(S)),
16857ee758d6SSam Clegg             static_cast<uint32_t>(Size)};
16866c899ba6SSam Clegg         DataLocations[&WS] = Ref;
1687d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "  -> index:" << Ref.Segment << "\n");
16886c899ba6SSam Clegg       } else {
1689da419bdbSHeejin Ahn         report_fatal_error("don't yet support global/event aliases");
16906c899ba6SSam Clegg       }
1691586320c0SNicholas Wilson     }
169230d314aaSSam Clegg   }
169331a2c809SSam Clegg 
1694586320c0SNicholas Wilson   // Finally, populate the symbol table itself, in its "natural" order.
1695586320c0SNicholas Wilson   for (const MCSymbol &S : Asm.symbols()) {
1696586320c0SNicholas Wilson     const auto &WS = static_cast<const MCSymbolWasm &>(S);
169725d8e68bSSam Clegg     if (!isInSymtab(WS)) {
169818c56a07SHeejin Ahn       WS.setIndex(InvalidIndex);
1699586320c0SNicholas Wilson       continue;
170025d8e68bSSam Clegg     }
1701d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "adding to symtab: " << WS << "\n");
1702586320c0SNicholas Wilson 
1703586320c0SNicholas Wilson     uint32_t Flags = 0;
1704586320c0SNicholas Wilson     if (WS.isWeak())
1705586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_BINDING_WEAK;
1706586320c0SNicholas Wilson     if (WS.isHidden())
1707586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN;
1708586320c0SNicholas Wilson     if (!WS.isExternal() && WS.isDefined())
1709586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;
1710586320c0SNicholas Wilson     if (WS.isUndefined())
1711586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_UNDEFINED;
1712da84b688SDan Gohman     if (WS.isNoStrip()) {
1713da84b688SDan Gohman       Flags |= wasm::WASM_SYMBOL_NO_STRIP;
1714da84b688SDan Gohman       if (isEmscripten()) {
1715d6ef8da3SSam Clegg         Flags |= wasm::WASM_SYMBOL_EXPORTED;
1716da84b688SDan Gohman       }
1717da84b688SDan Gohman     }
1718b4f4e370SSam Clegg     if (WS.hasImportName())
171929874ceaSDan Gohman       Flags |= wasm::WASM_SYMBOL_EXPLICIT_NAME;
1720881d8778SSam Clegg     if (WS.hasExportName())
1721881d8778SSam Clegg       Flags |= wasm::WASM_SYMBOL_EXPORTED;
1722586320c0SNicholas Wilson 
1723586320c0SNicholas Wilson     wasm::WasmSymbolInfo Info;
1724586320c0SNicholas Wilson     Info.Name = WS.getName();
17255e5b2cb1SWouter van Oortmerssen     Info.Kind = WS.getType().getValueOr(wasm::WASM_SYMBOL_TYPE_DATA);
1726586320c0SNicholas Wilson     Info.Flags = Flags;
17274d57fbd0SSam Clegg     if (!WS.isData()) {
17284d57fbd0SSam Clegg       assert(WasmIndices.count(&WS) > 0);
1729586320c0SNicholas Wilson       Info.ElementIndex = WasmIndices.find(&WS)->second;
17304d57fbd0SSam Clegg     } else if (WS.isDefined()) {
17314d57fbd0SSam Clegg       assert(DataLocations.count(&WS) > 0);
1732586320c0SNicholas Wilson       Info.DataRef = DataLocations.find(&WS)->second;
17334d57fbd0SSam Clegg     }
173425d8e68bSSam Clegg     WS.setIndex(SymbolInfos.size());
1735586320c0SNicholas Wilson     SymbolInfos.emplace_back(Info);
1736b7787fd0SSam Clegg   }
1737b7787fd0SSam Clegg 
17386006e091SSam Clegg   {
17396006e091SSam Clegg     auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
1740f9edbe95SSam Clegg       // Functions referenced by a relocation need to put in the table.  This is
1741f9edbe95SSam Clegg       // purely to make the object file's provisional values readable, and is
1742f9edbe95SSam Clegg       // ignored by the linker, which re-calculates the relocations itself.
1743d1152a26SSam Clegg       if (Rel.Type != wasm::R_WASM_TABLE_INDEX_I32 &&
1744cc1b9b68SWouter van Oortmerssen           Rel.Type != wasm::R_WASM_TABLE_INDEX_I64 &&
174581443ac1SSam Clegg           Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB &&
1746cc1b9b68SWouter van Oortmerssen           Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB64 &&
174781443ac1SSam Clegg           Rel.Type != wasm::R_WASM_TABLE_INDEX_REL_SLEB)
1748f9edbe95SSam Clegg         return;
1749f9edbe95SSam Clegg       assert(Rel.Symbol->isFunction());
17507ee758d6SSam Clegg       const MCSymbolWasm *Base =
17517ee758d6SSam Clegg           cast<MCSymbolWasm>(Layout.getBaseSymbol(*Rel.Symbol));
17527ee758d6SSam Clegg       uint32_t FunctionIndex = WasmIndices.find(Base)->second;
175318c56a07SHeejin Ahn       uint32_t TableIndex = TableElems.size() + InitialTableOffset;
17547ee758d6SSam Clegg       if (TableIndices.try_emplace(Base, TableIndex).second) {
17557ee758d6SSam Clegg         LLVM_DEBUG(dbgs() << "  -> adding " << Base->getName()
1756f9edbe95SSam Clegg                           << " to table: " << TableIndex << "\n");
17576c899ba6SSam Clegg         TableElems.push_back(FunctionIndex);
17587ee758d6SSam Clegg         registerFunctionType(*Base);
17596006e091SSam Clegg       }
17606006e091SSam Clegg     };
1761970d02c4SDan Gohman 
17626006e091SSam Clegg     for (const WasmRelocationEntry &RelEntry : CodeRelocations)
17636006e091SSam Clegg       HandleReloc(RelEntry);
17646006e091SSam Clegg     for (const WasmRelocationEntry &RelEntry : DataRelocations)
17656006e091SSam Clegg       HandleReloc(RelEntry);
1766d934cb88SDan Gohman   }
1767d934cb88SDan Gohman 
1768bafe6902SSam Clegg   // Translate .init_array section contents into start functions.
1769bafe6902SSam Clegg   for (const MCSection &S : Asm) {
1770bafe6902SSam Clegg     const auto &WS = static_cast<const MCSectionWasm &>(S);
17717d1ff446SFangrui Song     if (WS.getName().startswith(".fini_array"))
1772bafe6902SSam Clegg       report_fatal_error(".fini_array sections are unsupported");
17737d1ff446SFangrui Song     if (!WS.getName().startswith(".init_array"))
1774bafe6902SSam Clegg       continue;
1775bafe6902SSam Clegg     if (WS.getFragmentList().empty())
1776bafe6902SSam Clegg       continue;
1777b210c64bSSam Clegg 
1778b210c64bSSam Clegg     // init_array is expected to contain a single non-empty data fragment
1779b210c64bSSam Clegg     if (WS.getFragmentList().size() != 3)
1780bafe6902SSam Clegg       report_fatal_error("only one .init_array section fragment supported");
1781b210c64bSSam Clegg 
1782b210c64bSSam Clegg     auto IT = WS.begin();
1783b210c64bSSam Clegg     const MCFragment &EmptyFrag = *IT;
1784b210c64bSSam Clegg     if (EmptyFrag.getKind() != MCFragment::FT_Data)
1785b210c64bSSam Clegg       report_fatal_error(".init_array section should be aligned");
1786b210c64bSSam Clegg 
1787b210c64bSSam Clegg     IT = std::next(IT);
1788b210c64bSSam Clegg     const MCFragment &AlignFrag = *IT;
1789bafe6902SSam Clegg     if (AlignFrag.getKind() != MCFragment::FT_Align)
1790bafe6902SSam Clegg       report_fatal_error(".init_array section should be aligned");
1791bafe6902SSam Clegg     if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
1792bafe6902SSam Clegg       report_fatal_error(".init_array section should be aligned for pointers");
1793b210c64bSSam Clegg 
1794b210c64bSSam Clegg     const MCFragment &Frag = *std::next(IT);
1795bafe6902SSam Clegg     if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1796bafe6902SSam Clegg       report_fatal_error("only data supported in .init_array section");
1797b210c64bSSam Clegg 
1798bafe6902SSam Clegg     uint16_t Priority = UINT16_MAX;
17994d57fbd0SSam Clegg     unsigned PrefixLength = strlen(".init_array");
18007d1ff446SFangrui Song     if (WS.getName().size() > PrefixLength) {
18017d1ff446SFangrui Song       if (WS.getName()[PrefixLength] != '.')
1802f208f631SHeejin Ahn         report_fatal_error(
1803f208f631SHeejin Ahn             ".init_array section priority should start with '.'");
18047d1ff446SFangrui Song       if (WS.getName().substr(PrefixLength + 1).getAsInteger(10, Priority))
1805bafe6902SSam Clegg         report_fatal_error("invalid .init_array section priority");
1806bafe6902SSam Clegg     }
1807bafe6902SSam Clegg     const auto &DataFrag = cast<MCDataFragment>(Frag);
1808bafe6902SSam Clegg     const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1809f208f631SHeejin Ahn     for (const uint8_t *
181018c56a07SHeejin Ahn              P = (const uint8_t *)Contents.data(),
181118c56a07SHeejin Ahn             *End = (const uint8_t *)Contents.data() + Contents.size();
181218c56a07SHeejin Ahn          P != End; ++P) {
181318c56a07SHeejin Ahn       if (*P != 0)
1814bafe6902SSam Clegg         report_fatal_error("non-symbolic data in .init_array section");
1815bafe6902SSam Clegg     }
1816bafe6902SSam Clegg     for (const MCFixup &Fixup : DataFrag.getFixups()) {
1817f208f631SHeejin Ahn       assert(Fixup.getKind() ==
1818f208f631SHeejin Ahn              MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
1819bafe6902SSam Clegg       const MCExpr *Expr = Fixup.getValue();
18208fffa1dfSSam Clegg       auto *SymRef = dyn_cast<MCSymbolRefExpr>(Expr);
18218fffa1dfSSam Clegg       if (!SymRef)
1822bafe6902SSam Clegg         report_fatal_error("fixups in .init_array should be symbol references");
18238fffa1dfSSam Clegg       const auto &TargetSym = cast<const MCSymbolWasm>(SymRef->getSymbol());
18248fffa1dfSSam Clegg       if (TargetSym.getIndex() == InvalidIndex)
18253ea1c62cSSam Clegg         report_fatal_error("symbols in .init_array should exist in symtab");
18268fffa1dfSSam Clegg       if (!TargetSym.isFunction())
18278fffa1dfSSam Clegg         report_fatal_error("symbols in .init_array should be for functions");
182825d8e68bSSam Clegg       InitFuncs.push_back(
18298fffa1dfSSam Clegg           std::make_pair(Priority, TargetSym.getIndex()));
1830bafe6902SSam Clegg     }
1831bafe6902SSam Clegg   }
1832bafe6902SSam Clegg 
183318eafb6cSDan Gohman   // Write out the Wasm header.
183418eafb6cSDan Gohman   writeHeader(Asm);
183518eafb6cSDan Gohman 
18360ff28fa6SDerek Schuff   uint32_t CodeSectionIndex, DataSectionIndex;
18370ff28fa6SDerek Schuff   if (Mode != DwoMode::DwoOnly) {
1838da419bdbSHeejin Ahn     writeTypeSection(Signatures);
1839f950b24aSSam Clegg     writeImportSection(Imports, DataSize, TableElems.size());
18409e15f359SSam Clegg     writeFunctionSection(Functions);
1841d823cc7cSAndy Wingo     writeTableSection(Tables);
1842f950b24aSSam Clegg     // Skip the "memory" section; we import the memory instead.
1843da419bdbSHeejin Ahn     writeEventSection(Events);
18440a6c4d8dSSam Clegg     writeGlobalSection(Globals);
18459e15f359SSam Clegg     writeExportSection(Exports);
1846*a5a3659dSAndy Wingo     const MCSymbol *IndirectFunctionTable =
1847*a5a3659dSAndy Wingo         Asm.getContext().lookupSymbol("__indirect_function_table");
1848*a5a3659dSAndy Wingo     writeElemSection(cast_or_null<const MCSymbolWasm>(IndirectFunctionTable),
1849*a5a3659dSAndy Wingo                      TableElems);
1850fef8de66SThomas Lively     writeDataCountSection();
18510ff28fa6SDerek Schuff 
18520ff28fa6SDerek Schuff     CodeSectionIndex = writeCodeSection(Asm, Layout, Functions);
18530ff28fa6SDerek Schuff     DataSectionIndex = writeDataSection(Layout);
18540ff28fa6SDerek Schuff   }
18550ff28fa6SDerek Schuff 
18560a391060SDerek Schuff   // The Sections in the COMDAT list have placeholder indices (their index among
18570a391060SDerek Schuff   // custom sections, rather than among all sections). Fix them up here.
18580a391060SDerek Schuff   for (auto &Group : Comdats) {
18590a391060SDerek Schuff     for (auto &Entry : Group.second) {
18600a391060SDerek Schuff       if (Entry.Kind == wasm::WASM_COMDAT_SECTION) {
18610a391060SDerek Schuff         Entry.Index += SectionCount;
18620ff28fa6SDerek Schuff       }
18630a391060SDerek Schuff     }
18640a391060SDerek Schuff   }
18650a391060SDerek Schuff   for (auto &CustomSection : CustomSections)
18660a391060SDerek Schuff     writeCustomSection(CustomSection, Asm, Layout);
18670ff28fa6SDerek Schuff 
18680ff28fa6SDerek Schuff   if (Mode != DwoMode::DwoOnly) {
1869c22bfb6bSNicholas Wilson     writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats);
18700ff28fa6SDerek Schuff 
18716f08c84aSSam Clegg     writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations);
18726f08c84aSSam Clegg     writeRelocSection(DataSectionIndex, "DATA", DataRelocations);
18730ff28fa6SDerek Schuff   }
18746a31a0d6SSam Clegg   writeCustomRelocSections();
1875cbda16ebSThomas Lively   if (ProducersSection)
1876cbda16ebSThomas Lively     writeCustomSection(*ProducersSection, Asm, Layout);
1877f6f4f843SThomas Lively   if (TargetFeaturesSection)
1878f6f4f843SThomas Lively     writeCustomSection(*TargetFeaturesSection, Asm, Layout);
1879970d02c4SDan Gohman 
1880d934cb88SDan Gohman   // TODO: Translate the .comment section to the output.
18810ff28fa6SDerek Schuff   return W->OS.tell() - StartOffset;
188218eafb6cSDan Gohman }
188318eafb6cSDan Gohman 
188460fbc7ccSLang Hames std::unique_ptr<MCObjectWriter>
18851301a878SLang Hames llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
188618eafb6cSDan Gohman                              raw_pwrite_stream &OS) {
18870eaee545SJonas Devlieghere   return std::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
188818eafb6cSDan Gohman }
18890ff28fa6SDerek Schuff 
18900ff28fa6SDerek Schuff std::unique_ptr<MCObjectWriter>
18910ff28fa6SDerek Schuff llvm::createWasmDwoObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
18920ff28fa6SDerek Schuff                                 raw_pwrite_stream &OS,
18930ff28fa6SDerek Schuff                                 raw_pwrite_stream &DwoOS) {
18940ff28fa6SDerek Schuff   return std::make_unique<WasmObjectWriter>(std::move(MOTW), OS, DwoOS);
18950ff28fa6SDerek Schuff }
1896