10b57cec5SDimitry Andric //===- lib/MC/WasmObjectWriter.cpp - Wasm File Writer ---------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file implements Wasm object file writer information.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric 
130b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
140b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
150b57cec5SDimitry Andric #include "llvm/BinaryFormat/Wasm.h"
16e8d8bef9SDimitry Andric #include "llvm/BinaryFormat/WasmTraits.h"
170b57cec5SDimitry Andric #include "llvm/Config/llvm-config.h"
180b57cec5SDimitry Andric #include "llvm/MC/MCAsmBackend.h"
190b57cec5SDimitry Andric #include "llvm/MC/MCAsmLayout.h"
200b57cec5SDimitry Andric #include "llvm/MC/MCAssembler.h"
210b57cec5SDimitry Andric #include "llvm/MC/MCContext.h"
220b57cec5SDimitry Andric #include "llvm/MC/MCExpr.h"
230b57cec5SDimitry Andric #include "llvm/MC/MCFixupKindInfo.h"
240b57cec5SDimitry Andric #include "llvm/MC/MCObjectWriter.h"
250b57cec5SDimitry Andric #include "llvm/MC/MCSectionWasm.h"
260b57cec5SDimitry Andric #include "llvm/MC/MCSymbolWasm.h"
270b57cec5SDimitry Andric #include "llvm/MC/MCValue.h"
280b57cec5SDimitry Andric #include "llvm/MC/MCWasmObjectWriter.h"
290b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
300b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
315ffd83dbSDimitry Andric #include "llvm/Support/EndianStream.h"
320b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
330b57cec5SDimitry Andric #include "llvm/Support/LEB128.h"
340b57cec5SDimitry Andric #include "llvm/Support/StringSaver.h"
350b57cec5SDimitry Andric #include <vector>
360b57cec5SDimitry Andric 
370b57cec5SDimitry Andric using namespace llvm;
380b57cec5SDimitry Andric 
390b57cec5SDimitry Andric #define DEBUG_TYPE "mc"
400b57cec5SDimitry Andric 
410b57cec5SDimitry Andric namespace {
420b57cec5SDimitry Andric 
43e8d8bef9SDimitry Andric // When we create the indirect function table we start at 1, so that there is
44e8d8bef9SDimitry Andric // and empty slot at 0 and therefore calling a null function pointer will trap.
450b57cec5SDimitry Andric static const uint32_t InitialTableOffset = 1;
460b57cec5SDimitry Andric 
470b57cec5SDimitry Andric // For patching purposes, we need to remember where each section starts, both
480b57cec5SDimitry Andric // for patching up the section size field, and for patching up references to
490b57cec5SDimitry Andric // locations within the section.
500b57cec5SDimitry Andric struct SectionBookkeeping {
510b57cec5SDimitry Andric   // Where the size of the section is written.
520b57cec5SDimitry Andric   uint64_t SizeOffset;
530b57cec5SDimitry Andric   // Where the section header ends (without custom section name).
540b57cec5SDimitry Andric   uint64_t PayloadOffset;
550b57cec5SDimitry Andric   // Where the contents of the section starts.
560b57cec5SDimitry Andric   uint64_t ContentsOffset;
570b57cec5SDimitry Andric   uint32_t Index;
580b57cec5SDimitry Andric };
590b57cec5SDimitry Andric 
600b57cec5SDimitry Andric // A wasm data segment.  A wasm binary contains only a single data section
610b57cec5SDimitry Andric // but that can contain many segments, each with their own virtual location
620b57cec5SDimitry Andric // in memory.  Each MCSection data created by llvm is modeled as its own
630b57cec5SDimitry Andric // wasm data segment.
640b57cec5SDimitry Andric struct WasmDataSegment {
650b57cec5SDimitry Andric   MCSectionWasm *Section;
660b57cec5SDimitry Andric   StringRef Name;
670b57cec5SDimitry Andric   uint32_t InitFlags;
685ffd83dbSDimitry Andric   uint64_t Offset;
690b57cec5SDimitry Andric   uint32_t Alignment;
700b57cec5SDimitry Andric   uint32_t LinkerFlags;
710b57cec5SDimitry Andric   SmallVector<char, 4> Data;
720b57cec5SDimitry Andric };
730b57cec5SDimitry Andric 
740b57cec5SDimitry Andric // A wasm function to be written into the function section.
750b57cec5SDimitry Andric struct WasmFunction {
760b57cec5SDimitry Andric   uint32_t SigIndex;
770b57cec5SDimitry Andric   const MCSymbolWasm *Sym;
780b57cec5SDimitry Andric };
790b57cec5SDimitry Andric 
800b57cec5SDimitry Andric // A wasm global to be written into the global section.
810b57cec5SDimitry Andric struct WasmGlobal {
820b57cec5SDimitry Andric   wasm::WasmGlobalType Type;
830b57cec5SDimitry Andric   uint64_t InitialValue;
840b57cec5SDimitry Andric };
850b57cec5SDimitry Andric 
860b57cec5SDimitry Andric // Information about a single item which is part of a COMDAT.  For each data
870b57cec5SDimitry Andric // segment or function which is in the COMDAT, there is a corresponding
880b57cec5SDimitry Andric // WasmComdatEntry.
890b57cec5SDimitry Andric struct WasmComdatEntry {
900b57cec5SDimitry Andric   unsigned Kind;
910b57cec5SDimitry Andric   uint32_t Index;
920b57cec5SDimitry Andric };
930b57cec5SDimitry Andric 
940b57cec5SDimitry Andric // Information about a single relocation.
950b57cec5SDimitry Andric struct WasmRelocationEntry {
960b57cec5SDimitry Andric   uint64_t Offset;                   // Where is the relocation.
970b57cec5SDimitry Andric   const MCSymbolWasm *Symbol;        // The symbol to relocate with.
980b57cec5SDimitry Andric   int64_t Addend;                    // A value to add to the symbol.
990b57cec5SDimitry Andric   unsigned Type;                     // The type of the relocation.
1000b57cec5SDimitry Andric   const MCSectionWasm *FixupSection; // The section the relocation is targeting.
1010b57cec5SDimitry Andric 
1020b57cec5SDimitry Andric   WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol,
1030b57cec5SDimitry Andric                       int64_t Addend, unsigned Type,
1040b57cec5SDimitry Andric                       const MCSectionWasm *FixupSection)
1050b57cec5SDimitry Andric       : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type),
1060b57cec5SDimitry Andric         FixupSection(FixupSection) {}
1070b57cec5SDimitry Andric 
1080b57cec5SDimitry Andric   bool hasAddend() const { return wasm::relocTypeHasAddend(Type); }
1090b57cec5SDimitry Andric 
1100b57cec5SDimitry Andric   void print(raw_ostream &Out) const {
1110b57cec5SDimitry Andric     Out << wasm::relocTypetoString(Type) << " Off=" << Offset
1120b57cec5SDimitry Andric         << ", Sym=" << *Symbol << ", Addend=" << Addend
1135ffd83dbSDimitry Andric         << ", FixupSection=" << FixupSection->getName();
1140b57cec5SDimitry Andric   }
1150b57cec5SDimitry Andric 
1160b57cec5SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1170b57cec5SDimitry Andric   LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
1180b57cec5SDimitry Andric #endif
1190b57cec5SDimitry Andric };
1200b57cec5SDimitry Andric 
1210b57cec5SDimitry Andric static const uint32_t InvalidIndex = -1;
1220b57cec5SDimitry Andric 
1230b57cec5SDimitry Andric struct WasmCustomSection {
1240b57cec5SDimitry Andric 
1250b57cec5SDimitry Andric   StringRef Name;
1260b57cec5SDimitry Andric   MCSectionWasm *Section;
1270b57cec5SDimitry Andric 
1280b57cec5SDimitry Andric   uint32_t OutputContentsOffset;
1290b57cec5SDimitry Andric   uint32_t OutputIndex;
1300b57cec5SDimitry Andric 
1310b57cec5SDimitry Andric   WasmCustomSection(StringRef Name, MCSectionWasm *Section)
1320b57cec5SDimitry Andric       : Name(Name), Section(Section), OutputContentsOffset(0),
1330b57cec5SDimitry Andric         OutputIndex(InvalidIndex) {}
1340b57cec5SDimitry Andric };
1350b57cec5SDimitry Andric 
1360b57cec5SDimitry Andric #if !defined(NDEBUG)
1370b57cec5SDimitry Andric raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
1380b57cec5SDimitry Andric   Rel.print(OS);
1390b57cec5SDimitry Andric   return OS;
1400b57cec5SDimitry Andric }
1410b57cec5SDimitry Andric #endif
1420b57cec5SDimitry Andric 
1430b57cec5SDimitry Andric // Write X as an (unsigned) LEB value at offset Offset in Stream, padded
1440b57cec5SDimitry Andric // to allow patching.
1455ffd83dbSDimitry Andric template <int W>
1465ffd83dbSDimitry Andric void writePatchableLEB(raw_pwrite_stream &Stream, uint64_t X, uint64_t Offset) {
1475ffd83dbSDimitry Andric   uint8_t Buffer[W];
1485ffd83dbSDimitry Andric   unsigned SizeLen = encodeULEB128(X, Buffer, W);
1495ffd83dbSDimitry Andric   assert(SizeLen == W);
1500b57cec5SDimitry Andric   Stream.pwrite((char *)Buffer, SizeLen, Offset);
1510b57cec5SDimitry Andric }
1520b57cec5SDimitry Andric 
1530b57cec5SDimitry Andric // Write X as an signed LEB value at offset Offset in Stream, padded
1540b57cec5SDimitry Andric // to allow patching.
1555ffd83dbSDimitry Andric template <int W>
1565ffd83dbSDimitry Andric void writePatchableSLEB(raw_pwrite_stream &Stream, int64_t X, uint64_t Offset) {
1575ffd83dbSDimitry Andric   uint8_t Buffer[W];
1585ffd83dbSDimitry Andric   unsigned SizeLen = encodeSLEB128(X, Buffer, W);
1595ffd83dbSDimitry Andric   assert(SizeLen == W);
1600b57cec5SDimitry Andric   Stream.pwrite((char *)Buffer, SizeLen, Offset);
1610b57cec5SDimitry Andric }
1620b57cec5SDimitry Andric 
1630b57cec5SDimitry Andric // Write X as a plain integer value at offset Offset in Stream.
1645ffd83dbSDimitry Andric static void patchI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
1650b57cec5SDimitry Andric   uint8_t Buffer[4];
1660b57cec5SDimitry Andric   support::endian::write32le(Buffer, X);
1670b57cec5SDimitry Andric   Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
1680b57cec5SDimitry Andric }
1690b57cec5SDimitry Andric 
1705ffd83dbSDimitry Andric static void patchI64(raw_pwrite_stream &Stream, uint64_t X, uint64_t Offset) {
1715ffd83dbSDimitry Andric   uint8_t Buffer[8];
1725ffd83dbSDimitry Andric   support::endian::write64le(Buffer, X);
1735ffd83dbSDimitry Andric   Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
1745ffd83dbSDimitry Andric }
1755ffd83dbSDimitry Andric 
176e8d8bef9SDimitry Andric bool isDwoSection(const MCSection &Sec) {
177e8d8bef9SDimitry Andric   return Sec.getName().endswith(".dwo");
178e8d8bef9SDimitry Andric }
179e8d8bef9SDimitry Andric 
1800b57cec5SDimitry Andric class WasmObjectWriter : public MCObjectWriter {
181e8d8bef9SDimitry Andric   support::endian::Writer *W;
1820b57cec5SDimitry Andric 
1830b57cec5SDimitry Andric   /// The target specific Wasm writer instance.
1840b57cec5SDimitry Andric   std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
1850b57cec5SDimitry Andric 
1860b57cec5SDimitry Andric   // Relocations for fixing up references in the code section.
1870b57cec5SDimitry Andric   std::vector<WasmRelocationEntry> CodeRelocations;
1880b57cec5SDimitry Andric   // Relocations for fixing up references in the data section.
1890b57cec5SDimitry Andric   std::vector<WasmRelocationEntry> DataRelocations;
1900b57cec5SDimitry Andric 
1910b57cec5SDimitry Andric   // Index values to use for fixing up call_indirect type indices.
1920b57cec5SDimitry Andric   // Maps function symbols to the index of the type of the function
1930b57cec5SDimitry Andric   DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
1940b57cec5SDimitry Andric   // Maps function symbols to the table element index space. Used
1950b57cec5SDimitry Andric   // for TABLE_INDEX relocation types (i.e. address taken functions).
1960b57cec5SDimitry Andric   DenseMap<const MCSymbolWasm *, uint32_t> TableIndices;
197e8d8bef9SDimitry Andric   // Maps function/global/table symbols to the
198e8d8bef9SDimitry Andric   // function/global/table/event/section index space.
1990b57cec5SDimitry Andric   DenseMap<const MCSymbolWasm *, uint32_t> WasmIndices;
2000b57cec5SDimitry Andric   DenseMap<const MCSymbolWasm *, uint32_t> GOTIndices;
2010b57cec5SDimitry Andric   // Maps data symbols to the Wasm segment and offset/size with the segment.
2020b57cec5SDimitry Andric   DenseMap<const MCSymbolWasm *, wasm::WasmDataReference> DataLocations;
2030b57cec5SDimitry Andric 
2040b57cec5SDimitry Andric   // Stores output data (index, relocations, content offset) for custom
2050b57cec5SDimitry Andric   // section.
2060b57cec5SDimitry Andric   std::vector<WasmCustomSection> CustomSections;
2070b57cec5SDimitry Andric   std::unique_ptr<WasmCustomSection> ProducersSection;
2080b57cec5SDimitry Andric   std::unique_ptr<WasmCustomSection> TargetFeaturesSection;
2090b57cec5SDimitry Andric   // Relocations for fixing up references in the custom sections.
2100b57cec5SDimitry Andric   DenseMap<const MCSectionWasm *, std::vector<WasmRelocationEntry>>
2110b57cec5SDimitry Andric       CustomSectionsRelocations;
2120b57cec5SDimitry Andric 
2130b57cec5SDimitry Andric   // Map from section to defining function symbol.
2140b57cec5SDimitry Andric   DenseMap<const MCSection *, const MCSymbol *> SectionFunctions;
2150b57cec5SDimitry Andric 
216e8d8bef9SDimitry Andric   DenseMap<wasm::WasmSignature, uint32_t> SignatureIndices;
217e8d8bef9SDimitry Andric   SmallVector<wasm::WasmSignature, 4> Signatures;
2180b57cec5SDimitry Andric   SmallVector<WasmDataSegment, 4> DataSegments;
2190b57cec5SDimitry Andric   unsigned NumFunctionImports = 0;
2200b57cec5SDimitry Andric   unsigned NumGlobalImports = 0;
221e8d8bef9SDimitry Andric   unsigned NumTableImports = 0;
2220b57cec5SDimitry Andric   unsigned NumEventImports = 0;
2230b57cec5SDimitry Andric   uint32_t SectionCount = 0;
2240b57cec5SDimitry Andric 
225e8d8bef9SDimitry Andric   enum class DwoMode {
226e8d8bef9SDimitry Andric     AllSections,
227e8d8bef9SDimitry Andric     NonDwoOnly,
228e8d8bef9SDimitry Andric     DwoOnly,
229e8d8bef9SDimitry Andric   };
230e8d8bef9SDimitry Andric   bool IsSplitDwarf = false;
231e8d8bef9SDimitry Andric   raw_pwrite_stream *OS = nullptr;
232e8d8bef9SDimitry Andric   raw_pwrite_stream *DwoOS = nullptr;
233e8d8bef9SDimitry Andric 
234e8d8bef9SDimitry Andric   // TargetObjectWriter wranppers.
2350b57cec5SDimitry Andric   bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
2368bcb0991SDimitry Andric   bool isEmscripten() const { return TargetObjectWriter->isEmscripten(); }
2370b57cec5SDimitry Andric 
2380b57cec5SDimitry Andric   void startSection(SectionBookkeeping &Section, unsigned SectionId);
2390b57cec5SDimitry Andric   void startCustomSection(SectionBookkeeping &Section, StringRef Name);
2400b57cec5SDimitry Andric   void endSection(SectionBookkeeping &Section);
2410b57cec5SDimitry Andric 
2420b57cec5SDimitry Andric public:
2430b57cec5SDimitry Andric   WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
244e8d8bef9SDimitry Andric                    raw_pwrite_stream &OS_)
245e8d8bef9SDimitry Andric       : TargetObjectWriter(std::move(MOTW)), OS(&OS_) {}
246e8d8bef9SDimitry Andric 
247e8d8bef9SDimitry Andric   WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
248e8d8bef9SDimitry Andric                    raw_pwrite_stream &OS_, raw_pwrite_stream &DwoOS_)
249e8d8bef9SDimitry Andric       : TargetObjectWriter(std::move(MOTW)), IsSplitDwarf(true), OS(&OS_),
250e8d8bef9SDimitry Andric         DwoOS(&DwoOS_) {}
2510b57cec5SDimitry Andric 
2520b57cec5SDimitry Andric private:
2530b57cec5SDimitry Andric   void reset() override {
2540b57cec5SDimitry Andric     CodeRelocations.clear();
2550b57cec5SDimitry Andric     DataRelocations.clear();
2560b57cec5SDimitry Andric     TypeIndices.clear();
2570b57cec5SDimitry Andric     WasmIndices.clear();
2580b57cec5SDimitry Andric     GOTIndices.clear();
2590b57cec5SDimitry Andric     TableIndices.clear();
2600b57cec5SDimitry Andric     DataLocations.clear();
2610b57cec5SDimitry Andric     CustomSections.clear();
2620b57cec5SDimitry Andric     ProducersSection.reset();
2630b57cec5SDimitry Andric     TargetFeaturesSection.reset();
2640b57cec5SDimitry Andric     CustomSectionsRelocations.clear();
2650b57cec5SDimitry Andric     SignatureIndices.clear();
2660b57cec5SDimitry Andric     Signatures.clear();
2670b57cec5SDimitry Andric     DataSegments.clear();
2680b57cec5SDimitry Andric     SectionFunctions.clear();
2690b57cec5SDimitry Andric     NumFunctionImports = 0;
2700b57cec5SDimitry Andric     NumGlobalImports = 0;
271e8d8bef9SDimitry Andric     NumTableImports = 0;
2720b57cec5SDimitry Andric     MCObjectWriter::reset();
2730b57cec5SDimitry Andric   }
2740b57cec5SDimitry Andric 
2750b57cec5SDimitry Andric   void writeHeader(const MCAssembler &Asm);
2760b57cec5SDimitry Andric 
2770b57cec5SDimitry Andric   void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
2780b57cec5SDimitry Andric                         const MCFragment *Fragment, const MCFixup &Fixup,
2790b57cec5SDimitry Andric                         MCValue Target, uint64_t &FixedValue) override;
2800b57cec5SDimitry Andric 
2810b57cec5SDimitry Andric   void executePostLayoutBinding(MCAssembler &Asm,
2820b57cec5SDimitry Andric                                 const MCAsmLayout &Layout) override;
283e8d8bef9SDimitry Andric   void prepareImports(SmallVectorImpl<wasm::WasmImport> &Imports,
284e8d8bef9SDimitry Andric                       MCAssembler &Asm, const MCAsmLayout &Layout);
2850b57cec5SDimitry Andric   uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
2860b57cec5SDimitry Andric 
287e8d8bef9SDimitry Andric   uint64_t writeOneObject(MCAssembler &Asm, const MCAsmLayout &Layout,
288e8d8bef9SDimitry Andric                           DwoMode Mode);
289e8d8bef9SDimitry Andric 
2900b57cec5SDimitry Andric   void writeString(const StringRef Str) {
291e8d8bef9SDimitry Andric     encodeULEB128(Str.size(), W->OS);
292e8d8bef9SDimitry Andric     W->OS << Str;
2930b57cec5SDimitry Andric   }
2940b57cec5SDimitry Andric 
2955ffd83dbSDimitry Andric   void writeI32(int32_t val) {
2965ffd83dbSDimitry Andric     char Buffer[4];
2975ffd83dbSDimitry Andric     support::endian::write32le(Buffer, val);
298e8d8bef9SDimitry Andric     W->OS.write(Buffer, sizeof(Buffer));
2995ffd83dbSDimitry Andric   }
3005ffd83dbSDimitry Andric 
3015ffd83dbSDimitry Andric   void writeI64(int64_t val) {
3025ffd83dbSDimitry Andric     char Buffer[8];
3035ffd83dbSDimitry Andric     support::endian::write64le(Buffer, val);
304e8d8bef9SDimitry Andric     W->OS.write(Buffer, sizeof(Buffer));
3055ffd83dbSDimitry Andric   }
3065ffd83dbSDimitry Andric 
307e8d8bef9SDimitry Andric   void writeValueType(wasm::ValType Ty) { W->OS << static_cast<char>(Ty); }
3080b57cec5SDimitry Andric 
309e8d8bef9SDimitry Andric   void writeTypeSection(ArrayRef<wasm::WasmSignature> Signatures);
3105ffd83dbSDimitry Andric   void writeImportSection(ArrayRef<wasm::WasmImport> Imports, uint64_t DataSize,
3110b57cec5SDimitry Andric                           uint32_t NumElements);
3120b57cec5SDimitry Andric   void writeFunctionSection(ArrayRef<WasmFunction> Functions);
3130b57cec5SDimitry Andric   void writeExportSection(ArrayRef<wasm::WasmExport> Exports);
3140b57cec5SDimitry Andric   void writeElemSection(ArrayRef<uint32_t> TableElems);
3150b57cec5SDimitry Andric   void writeDataCountSection();
3165ffd83dbSDimitry Andric   uint32_t writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
3170b57cec5SDimitry Andric                             ArrayRef<WasmFunction> Functions);
3185ffd83dbSDimitry Andric   uint32_t writeDataSection(const MCAsmLayout &Layout);
3190b57cec5SDimitry Andric   void writeEventSection(ArrayRef<wasm::WasmEventType> Events);
3205ffd83dbSDimitry Andric   void writeGlobalSection(ArrayRef<wasm::WasmGlobal> Globals);
321e8d8bef9SDimitry Andric   void writeTableSection(ArrayRef<wasm::WasmTable> Tables);
3220b57cec5SDimitry Andric   void writeRelocSection(uint32_t SectionIndex, StringRef Name,
3230b57cec5SDimitry Andric                          std::vector<WasmRelocationEntry> &Relocations);
3240b57cec5SDimitry Andric   void writeLinkingMetaDataSection(
3250b57cec5SDimitry Andric       ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
3260b57cec5SDimitry Andric       ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
3270b57cec5SDimitry Andric       const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats);
3280b57cec5SDimitry Andric   void writeCustomSection(WasmCustomSection &CustomSection,
3290b57cec5SDimitry Andric                           const MCAssembler &Asm, const MCAsmLayout &Layout);
3300b57cec5SDimitry Andric   void writeCustomRelocSections();
3310b57cec5SDimitry Andric 
3325ffd83dbSDimitry Andric   uint64_t getProvisionalValue(const WasmRelocationEntry &RelEntry,
3335ffd83dbSDimitry Andric                                const MCAsmLayout &Layout);
3340b57cec5SDimitry Andric   void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
3355ffd83dbSDimitry Andric                         uint64_t ContentsOffset, const MCAsmLayout &Layout);
3360b57cec5SDimitry Andric 
3370b57cec5SDimitry Andric   uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
3380b57cec5SDimitry Andric   uint32_t getFunctionType(const MCSymbolWasm &Symbol);
3390b57cec5SDimitry Andric   uint32_t getEventType(const MCSymbolWasm &Symbol);
3400b57cec5SDimitry Andric   void registerFunctionType(const MCSymbolWasm &Symbol);
3410b57cec5SDimitry Andric   void registerEventType(const MCSymbolWasm &Symbol);
3420b57cec5SDimitry Andric };
3430b57cec5SDimitry Andric 
3440b57cec5SDimitry Andric } // end anonymous namespace
3450b57cec5SDimitry Andric 
3460b57cec5SDimitry Andric // Write out a section header and a patchable section size field.
3470b57cec5SDimitry Andric void WasmObjectWriter::startSection(SectionBookkeeping &Section,
3480b57cec5SDimitry Andric                                     unsigned SectionId) {
3490b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "startSection " << SectionId << "\n");
350e8d8bef9SDimitry Andric   W->OS << char(SectionId);
3510b57cec5SDimitry Andric 
352e8d8bef9SDimitry Andric   Section.SizeOffset = W->OS.tell();
3530b57cec5SDimitry Andric 
3540b57cec5SDimitry Andric   // The section size. We don't know the size yet, so reserve enough space
3550b57cec5SDimitry Andric   // for any 32-bit value; we'll patch it later.
356e8d8bef9SDimitry Andric   encodeULEB128(0, W->OS, 5);
3570b57cec5SDimitry Andric 
3580b57cec5SDimitry Andric   // The position where the section starts, for measuring its size.
359e8d8bef9SDimitry Andric   Section.ContentsOffset = W->OS.tell();
360e8d8bef9SDimitry Andric   Section.PayloadOffset = W->OS.tell();
3610b57cec5SDimitry Andric   Section.Index = SectionCount++;
3620b57cec5SDimitry Andric }
3630b57cec5SDimitry Andric 
3640b57cec5SDimitry Andric void WasmObjectWriter::startCustomSection(SectionBookkeeping &Section,
3650b57cec5SDimitry Andric                                           StringRef Name) {
3660b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "startCustomSection " << Name << "\n");
3670b57cec5SDimitry Andric   startSection(Section, wasm::WASM_SEC_CUSTOM);
3680b57cec5SDimitry Andric 
3690b57cec5SDimitry Andric   // The position where the section header ends, for measuring its size.
370e8d8bef9SDimitry Andric   Section.PayloadOffset = W->OS.tell();
3710b57cec5SDimitry Andric 
3720b57cec5SDimitry Andric   // Custom sections in wasm also have a string identifier.
3730b57cec5SDimitry Andric   writeString(Name);
3740b57cec5SDimitry Andric 
3750b57cec5SDimitry Andric   // The position where the custom section starts.
376e8d8bef9SDimitry Andric   Section.ContentsOffset = W->OS.tell();
3770b57cec5SDimitry Andric }
3780b57cec5SDimitry Andric 
3790b57cec5SDimitry Andric // Now that the section is complete and we know how big it is, patch up the
3800b57cec5SDimitry Andric // section size field at the start of the section.
3810b57cec5SDimitry Andric void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
382e8d8bef9SDimitry Andric   uint64_t Size = W->OS.tell();
3830b57cec5SDimitry Andric   // /dev/null doesn't support seek/tell and can report offset of 0.
3840b57cec5SDimitry Andric   // Simply skip this patching in that case.
3850b57cec5SDimitry Andric   if (!Size)
3860b57cec5SDimitry Andric     return;
3870b57cec5SDimitry Andric 
3880b57cec5SDimitry Andric   Size -= Section.PayloadOffset;
3890b57cec5SDimitry Andric   if (uint32_t(Size) != Size)
3900b57cec5SDimitry Andric     report_fatal_error("section size does not fit in a uint32_t");
3910b57cec5SDimitry Andric 
3920b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "endSection size=" << Size << "\n");
3930b57cec5SDimitry Andric 
3940b57cec5SDimitry Andric   // Write the final section size to the payload_len field, which follows
3950b57cec5SDimitry Andric   // the section id byte.
396e8d8bef9SDimitry Andric   writePatchableLEB<5>(static_cast<raw_pwrite_stream &>(W->OS), Size,
3970b57cec5SDimitry Andric                        Section.SizeOffset);
3980b57cec5SDimitry Andric }
3990b57cec5SDimitry Andric 
4000b57cec5SDimitry Andric // Emit the Wasm header.
4010b57cec5SDimitry Andric void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
402e8d8bef9SDimitry Andric   W->OS.write(wasm::WasmMagic, sizeof(wasm::WasmMagic));
403e8d8bef9SDimitry Andric   W->write<uint32_t>(wasm::WasmVersion);
4040b57cec5SDimitry Andric }
4050b57cec5SDimitry Andric 
4060b57cec5SDimitry Andric void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
4070b57cec5SDimitry Andric                                                 const MCAsmLayout &Layout) {
408e8d8bef9SDimitry Andric   // As a stopgap measure until call_indirect instructions start explicitly
409e8d8bef9SDimitry Andric   // referencing the indirect function table via TABLE_NUMBER relocs, ensure
410e8d8bef9SDimitry Andric   // that the indirect function table import makes it to the output if anything
411e8d8bef9SDimitry Andric   // in the compilation unit has caused it to be present.
412e8d8bef9SDimitry Andric   if (auto *Sym = Asm.getContext().lookupSymbol("__indirect_function_table"))
413e8d8bef9SDimitry Andric     Asm.registerSymbol(*Sym);
414e8d8bef9SDimitry Andric 
4150b57cec5SDimitry Andric   // Build a map of sections to the function that defines them, for use
4160b57cec5SDimitry Andric   // in recordRelocation.
4170b57cec5SDimitry Andric   for (const MCSymbol &S : Asm.symbols()) {
4180b57cec5SDimitry Andric     const auto &WS = static_cast<const MCSymbolWasm &>(S);
4190b57cec5SDimitry Andric     if (WS.isDefined() && WS.isFunction() && !WS.isVariable()) {
4200b57cec5SDimitry Andric       const auto &Sec = static_cast<const MCSectionWasm &>(S.getSection());
4210b57cec5SDimitry Andric       auto Pair = SectionFunctions.insert(std::make_pair(&Sec, &S));
4220b57cec5SDimitry Andric       if (!Pair.second)
4230b57cec5SDimitry Andric         report_fatal_error("section already has a defining function: " +
4245ffd83dbSDimitry Andric                            Sec.getName());
4250b57cec5SDimitry Andric     }
4260b57cec5SDimitry Andric   }
4270b57cec5SDimitry Andric }
4280b57cec5SDimitry Andric 
4290b57cec5SDimitry Andric void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
4300b57cec5SDimitry Andric                                         const MCAsmLayout &Layout,
4310b57cec5SDimitry Andric                                         const MCFragment *Fragment,
4320b57cec5SDimitry Andric                                         const MCFixup &Fixup, MCValue Target,
4330b57cec5SDimitry Andric                                         uint64_t &FixedValue) {
4348bcb0991SDimitry Andric   // The WebAssembly backend should never generate FKF_IsPCRel fixups
4358bcb0991SDimitry Andric   assert(!(Asm.getBackend().getFixupKindInfo(Fixup.getKind()).Flags &
4368bcb0991SDimitry Andric            MCFixupKindInfo::FKF_IsPCRel));
4378bcb0991SDimitry Andric 
4380b57cec5SDimitry Andric   const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
4390b57cec5SDimitry Andric   uint64_t C = Target.getConstant();
4400b57cec5SDimitry Andric   uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
4410b57cec5SDimitry Andric   MCContext &Ctx = Asm.getContext();
4420b57cec5SDimitry Andric 
4430b57cec5SDimitry Andric   if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
4448bcb0991SDimitry Andric     // To get here the A - B expression must have failed evaluateAsRelocatable.
4458bcb0991SDimitry Andric     // This means either A or B must be undefined and in WebAssembly we can't
4468bcb0991SDimitry Andric     // support either of those cases.
4478bcb0991SDimitry Andric     const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
4480b57cec5SDimitry Andric     Ctx.reportError(
4490b57cec5SDimitry Andric         Fixup.getLoc(),
4500b57cec5SDimitry Andric         Twine("symbol '") + SymB.getName() +
4518bcb0991SDimitry Andric             "': unsupported subtraction expression used in relocation.");
4520b57cec5SDimitry Andric     return;
4530b57cec5SDimitry Andric   }
4540b57cec5SDimitry Andric 
4550b57cec5SDimitry Andric   // We either rejected the fixup or folded B into C at this point.
4560b57cec5SDimitry Andric   const MCSymbolRefExpr *RefA = Target.getSymA();
4578bcb0991SDimitry Andric   const auto *SymA = cast<MCSymbolWasm>(&RefA->getSymbol());
4580b57cec5SDimitry Andric 
4595ffd83dbSDimitry Andric   // The .init_array isn't translated as data, so don't do relocations in it.
4605ffd83dbSDimitry Andric   if (FixupSection.getName().startswith(".init_array")) {
4615ffd83dbSDimitry Andric     SymA->setUsedInInitArray();
4625ffd83dbSDimitry Andric     return;
4635ffd83dbSDimitry Andric   }
4645ffd83dbSDimitry Andric 
4658bcb0991SDimitry Andric   if (SymA->isVariable()) {
4660b57cec5SDimitry Andric     const MCExpr *Expr = SymA->getVariableValue();
4675ffd83dbSDimitry Andric     if (const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr))
4680b57cec5SDimitry Andric       if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
4690b57cec5SDimitry Andric         llvm_unreachable("weakref used in reloc not yet implemented");
4700b57cec5SDimitry Andric   }
4710b57cec5SDimitry Andric 
4720b57cec5SDimitry Andric   // Put any constant offset in an addend. Offsets can be negative, and
4730b57cec5SDimitry Andric   // LLVM expects wrapping, in contrast to wasm's immediates which can't
4740b57cec5SDimitry Andric   // be negative and don't wrap.
4750b57cec5SDimitry Andric   FixedValue = 0;
4760b57cec5SDimitry Andric 
4770b57cec5SDimitry Andric   unsigned Type = TargetObjectWriter->getRelocType(Target, Fixup);
4780b57cec5SDimitry Andric 
4790b57cec5SDimitry Andric   // Absolute offset within a section or a function.
4800b57cec5SDimitry Andric   // Currently only supported for for metadata sections.
4810b57cec5SDimitry Andric   // See: test/MC/WebAssembly/blockaddress.ll
4820b57cec5SDimitry Andric   if (Type == wasm::R_WASM_FUNCTION_OFFSET_I32 ||
483e8d8bef9SDimitry Andric       Type == wasm::R_WASM_FUNCTION_OFFSET_I64 ||
4840b57cec5SDimitry Andric       Type == wasm::R_WASM_SECTION_OFFSET_I32) {
4850b57cec5SDimitry Andric     if (!FixupSection.getKind().isMetadata())
4860b57cec5SDimitry Andric       report_fatal_error("relocations for function or section offsets are "
4870b57cec5SDimitry Andric                          "only supported in metadata sections");
4880b57cec5SDimitry Andric 
4890b57cec5SDimitry Andric     const MCSymbol *SectionSymbol = nullptr;
4900b57cec5SDimitry Andric     const MCSection &SecA = SymA->getSection();
4910b57cec5SDimitry Andric     if (SecA.getKind().isText())
4920b57cec5SDimitry Andric       SectionSymbol = SectionFunctions.find(&SecA)->second;
4930b57cec5SDimitry Andric     else
4940b57cec5SDimitry Andric       SectionSymbol = SecA.getBeginSymbol();
4950b57cec5SDimitry Andric     if (!SectionSymbol)
4960b57cec5SDimitry Andric       report_fatal_error("section symbol is required for relocation");
4970b57cec5SDimitry Andric 
4980b57cec5SDimitry Andric     C += Layout.getSymbolOffset(*SymA);
4990b57cec5SDimitry Andric     SymA = cast<MCSymbolWasm>(SectionSymbol);
5000b57cec5SDimitry Andric   }
5010b57cec5SDimitry Andric 
502e8d8bef9SDimitry Andric   if (Type == wasm::R_WASM_TABLE_INDEX_REL_SLEB ||
503e8d8bef9SDimitry Andric       Type == wasm::R_WASM_TABLE_INDEX_SLEB ||
504e8d8bef9SDimitry Andric       Type == wasm::R_WASM_TABLE_INDEX_SLEB64 ||
505e8d8bef9SDimitry Andric       Type == wasm::R_WASM_TABLE_INDEX_I32 ||
506e8d8bef9SDimitry Andric       Type == wasm::R_WASM_TABLE_INDEX_I64) {
507e8d8bef9SDimitry Andric     // TABLE_INDEX relocs implicitly use the default indirect function table.
508e8d8bef9SDimitry Andric     auto TableName = "__indirect_function_table";
509e8d8bef9SDimitry Andric     MCSymbolWasm *Sym = cast_or_null<MCSymbolWasm>(Ctx.lookupSymbol(TableName));
510e8d8bef9SDimitry Andric     if (Sym) {
511e8d8bef9SDimitry Andric       if (!Sym->isFunctionTable())
512e8d8bef9SDimitry Andric         Ctx.reportError(
513e8d8bef9SDimitry Andric             Fixup.getLoc(),
514e8d8bef9SDimitry Andric             "symbol '__indirect_function_table' is not a function table");
515e8d8bef9SDimitry Andric     } else {
516e8d8bef9SDimitry Andric       Sym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(TableName));
517e8d8bef9SDimitry Andric       Sym->setFunctionTable();
518e8d8bef9SDimitry Andric       // The default function table is synthesized by the linker.
519e8d8bef9SDimitry Andric       Sym->setUndefined();
520e8d8bef9SDimitry Andric     }
521e8d8bef9SDimitry Andric     Sym->setUsedInReloc();
522e8d8bef9SDimitry Andric     Asm.registerSymbol(*Sym);
523e8d8bef9SDimitry Andric   }
524e8d8bef9SDimitry Andric 
5250b57cec5SDimitry Andric   // Relocation other than R_WASM_TYPE_INDEX_LEB are required to be
5260b57cec5SDimitry Andric   // against a named symbol.
5270b57cec5SDimitry Andric   if (Type != wasm::R_WASM_TYPE_INDEX_LEB) {
5280b57cec5SDimitry Andric     if (SymA->getName().empty())
5290b57cec5SDimitry Andric       report_fatal_error("relocations against un-named temporaries are not yet "
5300b57cec5SDimitry Andric                          "supported by wasm");
5310b57cec5SDimitry Andric 
5320b57cec5SDimitry Andric     SymA->setUsedInReloc();
5330b57cec5SDimitry Andric   }
5340b57cec5SDimitry Andric 
5350b57cec5SDimitry Andric   if (RefA->getKind() == MCSymbolRefExpr::VK_GOT)
5360b57cec5SDimitry Andric     SymA->setUsedInGOT();
5370b57cec5SDimitry Andric 
5380b57cec5SDimitry Andric   WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
5390b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
5400b57cec5SDimitry Andric 
5410b57cec5SDimitry Andric   if (FixupSection.isWasmData()) {
5420b57cec5SDimitry Andric     DataRelocations.push_back(Rec);
5430b57cec5SDimitry Andric   } else if (FixupSection.getKind().isText()) {
5440b57cec5SDimitry Andric     CodeRelocations.push_back(Rec);
5450b57cec5SDimitry Andric   } else if (FixupSection.getKind().isMetadata()) {
5460b57cec5SDimitry Andric     CustomSectionsRelocations[&FixupSection].push_back(Rec);
5470b57cec5SDimitry Andric   } else {
5480b57cec5SDimitry Andric     llvm_unreachable("unexpected section type");
5490b57cec5SDimitry Andric   }
5500b57cec5SDimitry Andric }
5510b57cec5SDimitry Andric 
5520b57cec5SDimitry Andric // Compute a value to write into the code at the location covered
5530b57cec5SDimitry Andric // by RelEntry. This value isn't used by the static linker; it just serves
5540b57cec5SDimitry Andric // to make the object format more readable and more likely to be directly
5550b57cec5SDimitry Andric // useable.
5565ffd83dbSDimitry Andric uint64_t
5575ffd83dbSDimitry Andric WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry,
5585ffd83dbSDimitry Andric                                       const MCAsmLayout &Layout) {
5595ffd83dbSDimitry Andric   if ((RelEntry.Type == wasm::R_WASM_GLOBAL_INDEX_LEB ||
5605ffd83dbSDimitry Andric        RelEntry.Type == wasm::R_WASM_GLOBAL_INDEX_I32) &&
5615ffd83dbSDimitry Andric       !RelEntry.Symbol->isGlobal()) {
5620b57cec5SDimitry Andric     assert(GOTIndices.count(RelEntry.Symbol) > 0 && "symbol not found in GOT index space");
5630b57cec5SDimitry Andric     return GOTIndices[RelEntry.Symbol];
5640b57cec5SDimitry Andric   }
5650b57cec5SDimitry Andric 
5660b57cec5SDimitry Andric   switch (RelEntry.Type) {
5670b57cec5SDimitry Andric   case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
5680b57cec5SDimitry Andric   case wasm::R_WASM_TABLE_INDEX_SLEB:
569e8d8bef9SDimitry Andric   case wasm::R_WASM_TABLE_INDEX_SLEB64:
570e8d8bef9SDimitry Andric   case wasm::R_WASM_TABLE_INDEX_I32:
571e8d8bef9SDimitry Andric   case wasm::R_WASM_TABLE_INDEX_I64: {
5720b57cec5SDimitry Andric     // Provisional value is table address of the resolved symbol itself
5735ffd83dbSDimitry Andric     const MCSymbolWasm *Base =
5745ffd83dbSDimitry Andric         cast<MCSymbolWasm>(Layout.getBaseSymbol(*RelEntry.Symbol));
5755ffd83dbSDimitry Andric     assert(Base->isFunction());
5765ffd83dbSDimitry Andric     if (RelEntry.Type == wasm::R_WASM_TABLE_INDEX_REL_SLEB)
5775ffd83dbSDimitry Andric       return TableIndices[Base] - InitialTableOffset;
5785ffd83dbSDimitry Andric     else
5795ffd83dbSDimitry Andric       return TableIndices[Base];
5800b57cec5SDimitry Andric   }
5810b57cec5SDimitry Andric   case wasm::R_WASM_TYPE_INDEX_LEB:
5820b57cec5SDimitry Andric     // Provisional value is same as the index
5830b57cec5SDimitry Andric     return getRelocationIndexValue(RelEntry);
5840b57cec5SDimitry Andric   case wasm::R_WASM_FUNCTION_INDEX_LEB:
5850b57cec5SDimitry Andric   case wasm::R_WASM_GLOBAL_INDEX_LEB:
5865ffd83dbSDimitry Andric   case wasm::R_WASM_GLOBAL_INDEX_I32:
5870b57cec5SDimitry Andric   case wasm::R_WASM_EVENT_INDEX_LEB:
588e8d8bef9SDimitry Andric   case wasm::R_WASM_TABLE_NUMBER_LEB:
5890b57cec5SDimitry Andric     // Provisional value is function/global/event Wasm index
5900b57cec5SDimitry Andric     assert(WasmIndices.count(RelEntry.Symbol) > 0 && "symbol not found in wasm index space");
5910b57cec5SDimitry Andric     return WasmIndices[RelEntry.Symbol];
5920b57cec5SDimitry Andric   case wasm::R_WASM_FUNCTION_OFFSET_I32:
593e8d8bef9SDimitry Andric   case wasm::R_WASM_FUNCTION_OFFSET_I64:
5940b57cec5SDimitry Andric   case wasm::R_WASM_SECTION_OFFSET_I32: {
5950b57cec5SDimitry Andric     const auto &Section =
5960b57cec5SDimitry Andric         static_cast<const MCSectionWasm &>(RelEntry.Symbol->getSection());
5970b57cec5SDimitry Andric     return Section.getSectionOffset() + RelEntry.Addend;
5980b57cec5SDimitry Andric   }
5990b57cec5SDimitry Andric   case wasm::R_WASM_MEMORY_ADDR_LEB:
6005ffd83dbSDimitry Andric   case wasm::R_WASM_MEMORY_ADDR_LEB64:
6015ffd83dbSDimitry Andric   case wasm::R_WASM_MEMORY_ADDR_SLEB:
6025ffd83dbSDimitry Andric   case wasm::R_WASM_MEMORY_ADDR_SLEB64:
6030b57cec5SDimitry Andric   case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
6045ffd83dbSDimitry Andric   case wasm::R_WASM_MEMORY_ADDR_REL_SLEB64:
6055ffd83dbSDimitry Andric   case wasm::R_WASM_MEMORY_ADDR_I32:
606e8d8bef9SDimitry Andric   case wasm::R_WASM_MEMORY_ADDR_I64:
607e8d8bef9SDimitry Andric   case wasm::R_WASM_MEMORY_ADDR_TLS_SLEB: {
608e8d8bef9SDimitry Andric     // Provisional value is address of the global plus the offset
6095ffd83dbSDimitry Andric     const MCSymbolWasm *Base =
6105ffd83dbSDimitry Andric         cast<MCSymbolWasm>(Layout.getBaseSymbol(*RelEntry.Symbol));
6110b57cec5SDimitry Andric     // For undefined symbols, use zero
6125ffd83dbSDimitry Andric     if (!Base->isDefined())
6130b57cec5SDimitry Andric       return 0;
614e8d8bef9SDimitry Andric     const wasm::WasmDataReference &BaseRef = DataLocations[Base],
615e8d8bef9SDimitry Andric                                   &SymRef = DataLocations[RelEntry.Symbol];
616e8d8bef9SDimitry Andric     const WasmDataSegment &Segment = DataSegments[BaseRef.Segment];
6170b57cec5SDimitry Andric     // Ignore overflow. LLVM allows address arithmetic to silently wrap.
618e8d8bef9SDimitry Andric     return Segment.Offset + BaseRef.Offset + SymRef.Offset + RelEntry.Addend;
6190b57cec5SDimitry Andric   }
6200b57cec5SDimitry Andric   default:
6210b57cec5SDimitry Andric     llvm_unreachable("invalid relocation type");
6220b57cec5SDimitry Andric   }
6230b57cec5SDimitry Andric }
6240b57cec5SDimitry Andric 
6250b57cec5SDimitry Andric static void addData(SmallVectorImpl<char> &DataBytes,
6260b57cec5SDimitry Andric                     MCSectionWasm &DataSection) {
6275ffd83dbSDimitry Andric   LLVM_DEBUG(errs() << "addData: " << DataSection.getName() << "\n");
6280b57cec5SDimitry Andric 
6290b57cec5SDimitry Andric   DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
6300b57cec5SDimitry Andric 
6310b57cec5SDimitry Andric   for (const MCFragment &Frag : DataSection) {
6320b57cec5SDimitry Andric     if (Frag.hasInstructions())
6330b57cec5SDimitry Andric       report_fatal_error("only data supported in data sections");
6340b57cec5SDimitry Andric 
6350b57cec5SDimitry Andric     if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
6360b57cec5SDimitry Andric       if (Align->getValueSize() != 1)
6370b57cec5SDimitry Andric         report_fatal_error("only byte values supported for alignment");
6380b57cec5SDimitry Andric       // If nops are requested, use zeros, as this is the data section.
6390b57cec5SDimitry Andric       uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
6400b57cec5SDimitry Andric       uint64_t Size =
6410b57cec5SDimitry Andric           std::min<uint64_t>(alignTo(DataBytes.size(), Align->getAlignment()),
6420b57cec5SDimitry Andric                              DataBytes.size() + Align->getMaxBytesToEmit());
6430b57cec5SDimitry Andric       DataBytes.resize(Size, Value);
6440b57cec5SDimitry Andric     } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
6450b57cec5SDimitry Andric       int64_t NumValues;
6460b57cec5SDimitry Andric       if (!Fill->getNumValues().evaluateAsAbsolute(NumValues))
6470b57cec5SDimitry Andric         llvm_unreachable("The fill should be an assembler constant");
6480b57cec5SDimitry Andric       DataBytes.insert(DataBytes.end(), Fill->getValueSize() * NumValues,
6490b57cec5SDimitry Andric                        Fill->getValue());
6500b57cec5SDimitry Andric     } else if (auto *LEB = dyn_cast<MCLEBFragment>(&Frag)) {
6510b57cec5SDimitry Andric       const SmallVectorImpl<char> &Contents = LEB->getContents();
652e8d8bef9SDimitry Andric       llvm::append_range(DataBytes, Contents);
6530b57cec5SDimitry Andric     } else {
6540b57cec5SDimitry Andric       const auto &DataFrag = cast<MCDataFragment>(Frag);
6550b57cec5SDimitry Andric       const SmallVectorImpl<char> &Contents = DataFrag.getContents();
656e8d8bef9SDimitry Andric       llvm::append_range(DataBytes, Contents);
6570b57cec5SDimitry Andric     }
6580b57cec5SDimitry Andric   }
6590b57cec5SDimitry Andric 
6600b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
6610b57cec5SDimitry Andric }
6620b57cec5SDimitry Andric 
6630b57cec5SDimitry Andric uint32_t
6640b57cec5SDimitry Andric WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
6650b57cec5SDimitry Andric   if (RelEntry.Type == wasm::R_WASM_TYPE_INDEX_LEB) {
6660b57cec5SDimitry Andric     if (!TypeIndices.count(RelEntry.Symbol))
6670b57cec5SDimitry Andric       report_fatal_error("symbol not found in type index space: " +
6680b57cec5SDimitry Andric                          RelEntry.Symbol->getName());
6690b57cec5SDimitry Andric     return TypeIndices[RelEntry.Symbol];
6700b57cec5SDimitry Andric   }
6710b57cec5SDimitry Andric 
6720b57cec5SDimitry Andric   return RelEntry.Symbol->getIndex();
6730b57cec5SDimitry Andric }
6740b57cec5SDimitry Andric 
6750b57cec5SDimitry Andric // Apply the portions of the relocation records that we can handle ourselves
6760b57cec5SDimitry Andric // directly.
6770b57cec5SDimitry Andric void WasmObjectWriter::applyRelocations(
6785ffd83dbSDimitry Andric     ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset,
6795ffd83dbSDimitry Andric     const MCAsmLayout &Layout) {
680e8d8bef9SDimitry Andric   auto &Stream = static_cast<raw_pwrite_stream &>(W->OS);
6810b57cec5SDimitry Andric   for (const WasmRelocationEntry &RelEntry : Relocations) {
6820b57cec5SDimitry Andric     uint64_t Offset = ContentsOffset +
6830b57cec5SDimitry Andric                       RelEntry.FixupSection->getSectionOffset() +
6840b57cec5SDimitry Andric                       RelEntry.Offset;
6850b57cec5SDimitry Andric 
6860b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
6875ffd83dbSDimitry Andric     auto Value = getProvisionalValue(RelEntry, Layout);
6880b57cec5SDimitry Andric 
6890b57cec5SDimitry Andric     switch (RelEntry.Type) {
6900b57cec5SDimitry Andric     case wasm::R_WASM_FUNCTION_INDEX_LEB:
6910b57cec5SDimitry Andric     case wasm::R_WASM_TYPE_INDEX_LEB:
6920b57cec5SDimitry Andric     case wasm::R_WASM_GLOBAL_INDEX_LEB:
6930b57cec5SDimitry Andric     case wasm::R_WASM_MEMORY_ADDR_LEB:
6940b57cec5SDimitry Andric     case wasm::R_WASM_EVENT_INDEX_LEB:
695e8d8bef9SDimitry Andric     case wasm::R_WASM_TABLE_NUMBER_LEB:
6965ffd83dbSDimitry Andric       writePatchableLEB<5>(Stream, Value, Offset);
6975ffd83dbSDimitry Andric       break;
6985ffd83dbSDimitry Andric     case wasm::R_WASM_MEMORY_ADDR_LEB64:
6995ffd83dbSDimitry Andric       writePatchableLEB<10>(Stream, Value, Offset);
7000b57cec5SDimitry Andric       break;
7010b57cec5SDimitry Andric     case wasm::R_WASM_TABLE_INDEX_I32:
7020b57cec5SDimitry Andric     case wasm::R_WASM_MEMORY_ADDR_I32:
7030b57cec5SDimitry Andric     case wasm::R_WASM_FUNCTION_OFFSET_I32:
7040b57cec5SDimitry Andric     case wasm::R_WASM_SECTION_OFFSET_I32:
7055ffd83dbSDimitry Andric     case wasm::R_WASM_GLOBAL_INDEX_I32:
7065ffd83dbSDimitry Andric       patchI32(Stream, Value, Offset);
7075ffd83dbSDimitry Andric       break;
708e8d8bef9SDimitry Andric     case wasm::R_WASM_TABLE_INDEX_I64:
7095ffd83dbSDimitry Andric     case wasm::R_WASM_MEMORY_ADDR_I64:
710e8d8bef9SDimitry Andric     case wasm::R_WASM_FUNCTION_OFFSET_I64:
7115ffd83dbSDimitry Andric       patchI64(Stream, Value, Offset);
7120b57cec5SDimitry Andric       break;
7130b57cec5SDimitry Andric     case wasm::R_WASM_TABLE_INDEX_SLEB:
7140b57cec5SDimitry Andric     case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
7150b57cec5SDimitry Andric     case wasm::R_WASM_MEMORY_ADDR_SLEB:
7160b57cec5SDimitry Andric     case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
717e8d8bef9SDimitry Andric     case wasm::R_WASM_MEMORY_ADDR_TLS_SLEB:
7185ffd83dbSDimitry Andric       writePatchableSLEB<5>(Stream, Value, Offset);
7195ffd83dbSDimitry Andric       break;
720e8d8bef9SDimitry Andric     case wasm::R_WASM_TABLE_INDEX_SLEB64:
7215ffd83dbSDimitry Andric     case wasm::R_WASM_MEMORY_ADDR_SLEB64:
7225ffd83dbSDimitry Andric     case wasm::R_WASM_MEMORY_ADDR_REL_SLEB64:
7235ffd83dbSDimitry Andric       writePatchableSLEB<10>(Stream, Value, Offset);
7240b57cec5SDimitry Andric       break;
7250b57cec5SDimitry Andric     default:
7260b57cec5SDimitry Andric       llvm_unreachable("invalid relocation type");
7270b57cec5SDimitry Andric     }
7280b57cec5SDimitry Andric   }
7290b57cec5SDimitry Andric }
7300b57cec5SDimitry Andric 
731e8d8bef9SDimitry Andric void WasmObjectWriter::writeTypeSection(
732e8d8bef9SDimitry Andric     ArrayRef<wasm::WasmSignature> Signatures) {
7330b57cec5SDimitry Andric   if (Signatures.empty())
7340b57cec5SDimitry Andric     return;
7350b57cec5SDimitry Andric 
7360b57cec5SDimitry Andric   SectionBookkeeping Section;
7370b57cec5SDimitry Andric   startSection(Section, wasm::WASM_SEC_TYPE);
7380b57cec5SDimitry Andric 
739e8d8bef9SDimitry Andric   encodeULEB128(Signatures.size(), W->OS);
7400b57cec5SDimitry Andric 
741e8d8bef9SDimitry Andric   for (const wasm::WasmSignature &Sig : Signatures) {
742e8d8bef9SDimitry Andric     W->OS << char(wasm::WASM_TYPE_FUNC);
743e8d8bef9SDimitry Andric     encodeULEB128(Sig.Params.size(), W->OS);
7440b57cec5SDimitry Andric     for (wasm::ValType Ty : Sig.Params)
7450b57cec5SDimitry Andric       writeValueType(Ty);
746e8d8bef9SDimitry Andric     encodeULEB128(Sig.Returns.size(), W->OS);
7470b57cec5SDimitry Andric     for (wasm::ValType Ty : Sig.Returns)
7480b57cec5SDimitry Andric       writeValueType(Ty);
7490b57cec5SDimitry Andric   }
7500b57cec5SDimitry Andric 
7510b57cec5SDimitry Andric   endSection(Section);
7520b57cec5SDimitry Andric }
7530b57cec5SDimitry Andric 
7540b57cec5SDimitry Andric void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports,
7555ffd83dbSDimitry Andric                                           uint64_t DataSize,
7560b57cec5SDimitry Andric                                           uint32_t NumElements) {
7570b57cec5SDimitry Andric   if (Imports.empty())
7580b57cec5SDimitry Andric     return;
7590b57cec5SDimitry Andric 
7605ffd83dbSDimitry Andric   uint64_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
7610b57cec5SDimitry Andric 
7620b57cec5SDimitry Andric   SectionBookkeeping Section;
7630b57cec5SDimitry Andric   startSection(Section, wasm::WASM_SEC_IMPORT);
7640b57cec5SDimitry Andric 
765e8d8bef9SDimitry Andric   encodeULEB128(Imports.size(), W->OS);
7660b57cec5SDimitry Andric   for (const wasm::WasmImport &Import : Imports) {
7670b57cec5SDimitry Andric     writeString(Import.Module);
7680b57cec5SDimitry Andric     writeString(Import.Field);
769e8d8bef9SDimitry Andric     W->OS << char(Import.Kind);
7700b57cec5SDimitry Andric 
7710b57cec5SDimitry Andric     switch (Import.Kind) {
7720b57cec5SDimitry Andric     case wasm::WASM_EXTERNAL_FUNCTION:
773e8d8bef9SDimitry Andric       encodeULEB128(Import.SigIndex, W->OS);
7740b57cec5SDimitry Andric       break;
7750b57cec5SDimitry Andric     case wasm::WASM_EXTERNAL_GLOBAL:
776e8d8bef9SDimitry Andric       W->OS << char(Import.Global.Type);
777e8d8bef9SDimitry Andric       W->OS << char(Import.Global.Mutable ? 1 : 0);
7780b57cec5SDimitry Andric       break;
7790b57cec5SDimitry Andric     case wasm::WASM_EXTERNAL_MEMORY:
780e8d8bef9SDimitry Andric       encodeULEB128(Import.Memory.Flags, W->OS);
781e8d8bef9SDimitry Andric       encodeULEB128(NumPages, W->OS); // initial
7820b57cec5SDimitry Andric       break;
7830b57cec5SDimitry Andric     case wasm::WASM_EXTERNAL_TABLE:
784e8d8bef9SDimitry Andric       W->OS << char(Import.Table.ElemType);
785e8d8bef9SDimitry Andric       encodeULEB128(0, W->OS);           // flags
786e8d8bef9SDimitry Andric       encodeULEB128(NumElements, W->OS); // initial
7870b57cec5SDimitry Andric       break;
7880b57cec5SDimitry Andric     case wasm::WASM_EXTERNAL_EVENT:
789e8d8bef9SDimitry Andric       encodeULEB128(Import.Event.Attribute, W->OS);
790e8d8bef9SDimitry Andric       encodeULEB128(Import.Event.SigIndex, W->OS);
7910b57cec5SDimitry Andric       break;
7920b57cec5SDimitry Andric     default:
7930b57cec5SDimitry Andric       llvm_unreachable("unsupported import kind");
7940b57cec5SDimitry Andric     }
7950b57cec5SDimitry Andric   }
7960b57cec5SDimitry Andric 
7970b57cec5SDimitry Andric   endSection(Section);
7980b57cec5SDimitry Andric }
7990b57cec5SDimitry Andric 
8000b57cec5SDimitry Andric void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
8010b57cec5SDimitry Andric   if (Functions.empty())
8020b57cec5SDimitry Andric     return;
8030b57cec5SDimitry Andric 
8040b57cec5SDimitry Andric   SectionBookkeeping Section;
8050b57cec5SDimitry Andric   startSection(Section, wasm::WASM_SEC_FUNCTION);
8060b57cec5SDimitry Andric 
807e8d8bef9SDimitry Andric   encodeULEB128(Functions.size(), W->OS);
8080b57cec5SDimitry Andric   for (const WasmFunction &Func : Functions)
809e8d8bef9SDimitry Andric     encodeULEB128(Func.SigIndex, W->OS);
8100b57cec5SDimitry Andric 
8110b57cec5SDimitry Andric   endSection(Section);
8120b57cec5SDimitry Andric }
8130b57cec5SDimitry Andric 
8140b57cec5SDimitry Andric void WasmObjectWriter::writeEventSection(ArrayRef<wasm::WasmEventType> Events) {
8150b57cec5SDimitry Andric   if (Events.empty())
8160b57cec5SDimitry Andric     return;
8170b57cec5SDimitry Andric 
8180b57cec5SDimitry Andric   SectionBookkeeping Section;
8190b57cec5SDimitry Andric   startSection(Section, wasm::WASM_SEC_EVENT);
8200b57cec5SDimitry Andric 
821e8d8bef9SDimitry Andric   encodeULEB128(Events.size(), W->OS);
8220b57cec5SDimitry Andric   for (const wasm::WasmEventType &Event : Events) {
823e8d8bef9SDimitry Andric     encodeULEB128(Event.Attribute, W->OS);
824e8d8bef9SDimitry Andric     encodeULEB128(Event.SigIndex, W->OS);
8250b57cec5SDimitry Andric   }
8260b57cec5SDimitry Andric 
8270b57cec5SDimitry Andric   endSection(Section);
8280b57cec5SDimitry Andric }
8290b57cec5SDimitry Andric 
8305ffd83dbSDimitry Andric void WasmObjectWriter::writeGlobalSection(ArrayRef<wasm::WasmGlobal> Globals) {
8315ffd83dbSDimitry Andric   if (Globals.empty())
8325ffd83dbSDimitry Andric     return;
8335ffd83dbSDimitry Andric 
8345ffd83dbSDimitry Andric   SectionBookkeeping Section;
8355ffd83dbSDimitry Andric   startSection(Section, wasm::WASM_SEC_GLOBAL);
8365ffd83dbSDimitry Andric 
837e8d8bef9SDimitry Andric   encodeULEB128(Globals.size(), W->OS);
8385ffd83dbSDimitry Andric   for (const wasm::WasmGlobal &Global : Globals) {
839e8d8bef9SDimitry Andric     encodeULEB128(Global.Type.Type, W->OS);
840e8d8bef9SDimitry Andric     W->OS << char(Global.Type.Mutable);
841e8d8bef9SDimitry Andric     W->OS << char(Global.InitExpr.Opcode);
8425ffd83dbSDimitry Andric     switch (Global.Type.Type) {
8435ffd83dbSDimitry Andric     case wasm::WASM_TYPE_I32:
844e8d8bef9SDimitry Andric       encodeSLEB128(0, W->OS);
8455ffd83dbSDimitry Andric       break;
8465ffd83dbSDimitry Andric     case wasm::WASM_TYPE_I64:
847e8d8bef9SDimitry Andric       encodeSLEB128(0, W->OS);
8485ffd83dbSDimitry Andric       break;
8495ffd83dbSDimitry Andric     case wasm::WASM_TYPE_F32:
8505ffd83dbSDimitry Andric       writeI32(0);
8515ffd83dbSDimitry Andric       break;
8525ffd83dbSDimitry Andric     case wasm::WASM_TYPE_F64:
8535ffd83dbSDimitry Andric       writeI64(0);
8545ffd83dbSDimitry Andric       break;
8555ffd83dbSDimitry Andric     case wasm::WASM_TYPE_EXTERNREF:
8565ffd83dbSDimitry Andric       writeValueType(wasm::ValType::EXTERNREF);
8575ffd83dbSDimitry Andric       break;
8585ffd83dbSDimitry Andric     default:
8595ffd83dbSDimitry Andric       llvm_unreachable("unexpected type");
8605ffd83dbSDimitry Andric     }
861e8d8bef9SDimitry Andric     W->OS << char(wasm::WASM_OPCODE_END);
8625ffd83dbSDimitry Andric   }
8635ffd83dbSDimitry Andric 
8645ffd83dbSDimitry Andric   endSection(Section);
8655ffd83dbSDimitry Andric }
8665ffd83dbSDimitry Andric 
867e8d8bef9SDimitry Andric void WasmObjectWriter::writeTableSection(ArrayRef<wasm::WasmTable> Tables) {
868e8d8bef9SDimitry Andric   if (Tables.empty())
869e8d8bef9SDimitry Andric     return;
870e8d8bef9SDimitry Andric 
871e8d8bef9SDimitry Andric   SectionBookkeeping Section;
872e8d8bef9SDimitry Andric   startSection(Section, wasm::WASM_SEC_TABLE);
873e8d8bef9SDimitry Andric 
874e8d8bef9SDimitry Andric   encodeULEB128(Tables.size(), W->OS);
875e8d8bef9SDimitry Andric   for (const wasm::WasmTable &Table : Tables) {
876e8d8bef9SDimitry Andric     encodeULEB128(Table.Type.ElemType, W->OS);
877e8d8bef9SDimitry Andric     encodeULEB128(Table.Type.Limits.Flags, W->OS);
878e8d8bef9SDimitry Andric     encodeULEB128(Table.Type.Limits.Initial, W->OS);
879e8d8bef9SDimitry Andric     if (Table.Type.Limits.Flags & wasm::WASM_LIMITS_FLAG_HAS_MAX)
880e8d8bef9SDimitry Andric       encodeULEB128(Table.Type.Limits.Maximum, W->OS);
881e8d8bef9SDimitry Andric   }
882e8d8bef9SDimitry Andric   endSection(Section);
883e8d8bef9SDimitry Andric }
884e8d8bef9SDimitry Andric 
8850b57cec5SDimitry Andric void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) {
8860b57cec5SDimitry Andric   if (Exports.empty())
8870b57cec5SDimitry Andric     return;
8880b57cec5SDimitry Andric 
8890b57cec5SDimitry Andric   SectionBookkeeping Section;
8900b57cec5SDimitry Andric   startSection(Section, wasm::WASM_SEC_EXPORT);
8910b57cec5SDimitry Andric 
892e8d8bef9SDimitry Andric   encodeULEB128(Exports.size(), W->OS);
8930b57cec5SDimitry Andric   for (const wasm::WasmExport &Export : Exports) {
8940b57cec5SDimitry Andric     writeString(Export.Name);
895e8d8bef9SDimitry Andric     W->OS << char(Export.Kind);
896e8d8bef9SDimitry Andric     encodeULEB128(Export.Index, W->OS);
8970b57cec5SDimitry Andric   }
8980b57cec5SDimitry Andric 
8990b57cec5SDimitry Andric   endSection(Section);
9000b57cec5SDimitry Andric }
9010b57cec5SDimitry Andric 
9020b57cec5SDimitry Andric void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
9030b57cec5SDimitry Andric   if (TableElems.empty())
9040b57cec5SDimitry Andric     return;
9050b57cec5SDimitry Andric 
9060b57cec5SDimitry Andric   SectionBookkeeping Section;
9070b57cec5SDimitry Andric   startSection(Section, wasm::WASM_SEC_ELEM);
9080b57cec5SDimitry Andric 
909e8d8bef9SDimitry Andric   encodeULEB128(1, W->OS); // number of "segments"
910e8d8bef9SDimitry Andric   encodeULEB128(0, W->OS); // the table index
9110b57cec5SDimitry Andric 
9120b57cec5SDimitry Andric   // init expr for starting offset
913e8d8bef9SDimitry Andric   W->OS << char(wasm::WASM_OPCODE_I32_CONST);
914e8d8bef9SDimitry Andric   encodeSLEB128(InitialTableOffset, W->OS);
915e8d8bef9SDimitry Andric   W->OS << char(wasm::WASM_OPCODE_END);
9160b57cec5SDimitry Andric 
917e8d8bef9SDimitry Andric   encodeULEB128(TableElems.size(), W->OS);
9180b57cec5SDimitry Andric   for (uint32_t Elem : TableElems)
919e8d8bef9SDimitry Andric     encodeULEB128(Elem, W->OS);
9200b57cec5SDimitry Andric 
9210b57cec5SDimitry Andric   endSection(Section);
9220b57cec5SDimitry Andric }
9230b57cec5SDimitry Andric 
9240b57cec5SDimitry Andric void WasmObjectWriter::writeDataCountSection() {
9250b57cec5SDimitry Andric   if (DataSegments.empty())
9260b57cec5SDimitry Andric     return;
9270b57cec5SDimitry Andric 
9280b57cec5SDimitry Andric   SectionBookkeeping Section;
9290b57cec5SDimitry Andric   startSection(Section, wasm::WASM_SEC_DATACOUNT);
930e8d8bef9SDimitry Andric   encodeULEB128(DataSegments.size(), W->OS);
9310b57cec5SDimitry Andric   endSection(Section);
9320b57cec5SDimitry Andric }
9330b57cec5SDimitry Andric 
9345ffd83dbSDimitry Andric uint32_t WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
9350b57cec5SDimitry Andric                                             const MCAsmLayout &Layout,
9360b57cec5SDimitry Andric                                             ArrayRef<WasmFunction> Functions) {
9370b57cec5SDimitry Andric   if (Functions.empty())
9385ffd83dbSDimitry Andric     return 0;
9390b57cec5SDimitry Andric 
9400b57cec5SDimitry Andric   SectionBookkeeping Section;
9410b57cec5SDimitry Andric   startSection(Section, wasm::WASM_SEC_CODE);
9420b57cec5SDimitry Andric 
943e8d8bef9SDimitry Andric   encodeULEB128(Functions.size(), W->OS);
9440b57cec5SDimitry Andric 
9450b57cec5SDimitry Andric   for (const WasmFunction &Func : Functions) {
9460b57cec5SDimitry Andric     auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
9470b57cec5SDimitry Andric 
9480b57cec5SDimitry Andric     int64_t Size = 0;
9490b57cec5SDimitry Andric     if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
9500b57cec5SDimitry Andric       report_fatal_error(".size expression must be evaluatable");
9510b57cec5SDimitry Andric 
952e8d8bef9SDimitry Andric     encodeULEB128(Size, W->OS);
953e8d8bef9SDimitry Andric     FuncSection.setSectionOffset(W->OS.tell() - Section.ContentsOffset);
954e8d8bef9SDimitry Andric     Asm.writeSectionData(W->OS, &FuncSection, Layout);
9550b57cec5SDimitry Andric   }
9560b57cec5SDimitry Andric 
9570b57cec5SDimitry Andric   // Apply fixups.
9585ffd83dbSDimitry Andric   applyRelocations(CodeRelocations, Section.ContentsOffset, Layout);
9590b57cec5SDimitry Andric 
9600b57cec5SDimitry Andric   endSection(Section);
9615ffd83dbSDimitry Andric   return Section.Index;
9620b57cec5SDimitry Andric }
9630b57cec5SDimitry Andric 
9645ffd83dbSDimitry Andric uint32_t WasmObjectWriter::writeDataSection(const MCAsmLayout &Layout) {
9650b57cec5SDimitry Andric   if (DataSegments.empty())
9665ffd83dbSDimitry Andric     return 0;
9670b57cec5SDimitry Andric 
9680b57cec5SDimitry Andric   SectionBookkeeping Section;
9690b57cec5SDimitry Andric   startSection(Section, wasm::WASM_SEC_DATA);
9700b57cec5SDimitry Andric 
971e8d8bef9SDimitry Andric   encodeULEB128(DataSegments.size(), W->OS); // count
9720b57cec5SDimitry Andric 
9730b57cec5SDimitry Andric   for (const WasmDataSegment &Segment : DataSegments) {
974e8d8bef9SDimitry Andric     encodeULEB128(Segment.InitFlags, W->OS); // flags
975e8d8bef9SDimitry Andric     if (Segment.InitFlags & wasm::WASM_DATA_SEGMENT_HAS_MEMINDEX)
976e8d8bef9SDimitry Andric       encodeULEB128(0, W->OS); // memory index
977e8d8bef9SDimitry Andric     if ((Segment.InitFlags & wasm::WASM_DATA_SEGMENT_IS_PASSIVE) == 0) {
978e8d8bef9SDimitry Andric       W->OS << char(Segment.Offset > INT32_MAX ? wasm::WASM_OPCODE_I64_CONST
9795ffd83dbSDimitry Andric                                                : wasm::WASM_OPCODE_I32_CONST);
980e8d8bef9SDimitry Andric       encodeSLEB128(Segment.Offset, W->OS); // offset
981e8d8bef9SDimitry Andric       W->OS << char(wasm::WASM_OPCODE_END);
9820b57cec5SDimitry Andric     }
983e8d8bef9SDimitry Andric     encodeULEB128(Segment.Data.size(), W->OS); // size
984e8d8bef9SDimitry Andric     Segment.Section->setSectionOffset(W->OS.tell() - Section.ContentsOffset);
985e8d8bef9SDimitry Andric     W->OS << Segment.Data; // data
9860b57cec5SDimitry Andric   }
9870b57cec5SDimitry Andric 
9880b57cec5SDimitry Andric   // Apply fixups.
9895ffd83dbSDimitry Andric   applyRelocations(DataRelocations, Section.ContentsOffset, Layout);
9900b57cec5SDimitry Andric 
9910b57cec5SDimitry Andric   endSection(Section);
9925ffd83dbSDimitry Andric   return Section.Index;
9930b57cec5SDimitry Andric }
9940b57cec5SDimitry Andric 
9950b57cec5SDimitry Andric void WasmObjectWriter::writeRelocSection(
9960b57cec5SDimitry Andric     uint32_t SectionIndex, StringRef Name,
9970b57cec5SDimitry Andric     std::vector<WasmRelocationEntry> &Relocs) {
9980b57cec5SDimitry Andric   // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
9990b57cec5SDimitry Andric   // for descriptions of the reloc sections.
10000b57cec5SDimitry Andric 
10010b57cec5SDimitry Andric   if (Relocs.empty())
10020b57cec5SDimitry Andric     return;
10030b57cec5SDimitry Andric 
10040b57cec5SDimitry Andric   // First, ensure the relocations are sorted in offset order.  In general they
10050b57cec5SDimitry Andric   // should already be sorted since `recordRelocation` is called in offset
10060b57cec5SDimitry Andric   // order, but for the code section we combine many MC sections into single
10070b57cec5SDimitry Andric   // wasm section, and this order is determined by the order of Asm.Symbols()
10080b57cec5SDimitry Andric   // not the sections order.
10090b57cec5SDimitry Andric   llvm::stable_sort(
10100b57cec5SDimitry Andric       Relocs, [](const WasmRelocationEntry &A, const WasmRelocationEntry &B) {
10110b57cec5SDimitry Andric         return (A.Offset + A.FixupSection->getSectionOffset()) <
10120b57cec5SDimitry Andric                (B.Offset + B.FixupSection->getSectionOffset());
10130b57cec5SDimitry Andric       });
10140b57cec5SDimitry Andric 
10150b57cec5SDimitry Andric   SectionBookkeeping Section;
10160b57cec5SDimitry Andric   startCustomSection(Section, std::string("reloc.") + Name.str());
10170b57cec5SDimitry Andric 
1018e8d8bef9SDimitry Andric   encodeULEB128(SectionIndex, W->OS);
1019e8d8bef9SDimitry Andric   encodeULEB128(Relocs.size(), W->OS);
10200b57cec5SDimitry Andric   for (const WasmRelocationEntry &RelEntry : Relocs) {
10210b57cec5SDimitry Andric     uint64_t Offset =
10220b57cec5SDimitry Andric         RelEntry.Offset + RelEntry.FixupSection->getSectionOffset();
10230b57cec5SDimitry Andric     uint32_t Index = getRelocationIndexValue(RelEntry);
10240b57cec5SDimitry Andric 
1025e8d8bef9SDimitry Andric     W->OS << char(RelEntry.Type);
1026e8d8bef9SDimitry Andric     encodeULEB128(Offset, W->OS);
1027e8d8bef9SDimitry Andric     encodeULEB128(Index, W->OS);
10280b57cec5SDimitry Andric     if (RelEntry.hasAddend())
1029e8d8bef9SDimitry Andric       encodeSLEB128(RelEntry.Addend, W->OS);
10300b57cec5SDimitry Andric   }
10310b57cec5SDimitry Andric 
10320b57cec5SDimitry Andric   endSection(Section);
10330b57cec5SDimitry Andric }
10340b57cec5SDimitry Andric 
10350b57cec5SDimitry Andric void WasmObjectWriter::writeCustomRelocSections() {
10360b57cec5SDimitry Andric   for (const auto &Sec : CustomSections) {
10370b57cec5SDimitry Andric     auto &Relocations = CustomSectionsRelocations[Sec.Section];
10380b57cec5SDimitry Andric     writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations);
10390b57cec5SDimitry Andric   }
10400b57cec5SDimitry Andric }
10410b57cec5SDimitry Andric 
10420b57cec5SDimitry Andric void WasmObjectWriter::writeLinkingMetaDataSection(
10430b57cec5SDimitry Andric     ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
10440b57cec5SDimitry Andric     ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
10450b57cec5SDimitry Andric     const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) {
10460b57cec5SDimitry Andric   SectionBookkeeping Section;
10470b57cec5SDimitry Andric   startCustomSection(Section, "linking");
1048e8d8bef9SDimitry Andric   encodeULEB128(wasm::WasmMetadataVersion, W->OS);
10490b57cec5SDimitry Andric 
10500b57cec5SDimitry Andric   SectionBookkeeping SubSection;
10510b57cec5SDimitry Andric   if (SymbolInfos.size() != 0) {
10520b57cec5SDimitry Andric     startSection(SubSection, wasm::WASM_SYMBOL_TABLE);
1053e8d8bef9SDimitry Andric     encodeULEB128(SymbolInfos.size(), W->OS);
10540b57cec5SDimitry Andric     for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) {
1055e8d8bef9SDimitry Andric       encodeULEB128(Sym.Kind, W->OS);
1056e8d8bef9SDimitry Andric       encodeULEB128(Sym.Flags, W->OS);
10570b57cec5SDimitry Andric       switch (Sym.Kind) {
10580b57cec5SDimitry Andric       case wasm::WASM_SYMBOL_TYPE_FUNCTION:
10590b57cec5SDimitry Andric       case wasm::WASM_SYMBOL_TYPE_GLOBAL:
10600b57cec5SDimitry Andric       case wasm::WASM_SYMBOL_TYPE_EVENT:
1061e8d8bef9SDimitry Andric       case wasm::WASM_SYMBOL_TYPE_TABLE:
1062e8d8bef9SDimitry Andric         encodeULEB128(Sym.ElementIndex, W->OS);
10630b57cec5SDimitry Andric         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0 ||
10640b57cec5SDimitry Andric             (Sym.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0)
10650b57cec5SDimitry Andric           writeString(Sym.Name);
10660b57cec5SDimitry Andric         break;
10670b57cec5SDimitry Andric       case wasm::WASM_SYMBOL_TYPE_DATA:
10680b57cec5SDimitry Andric         writeString(Sym.Name);
10690b57cec5SDimitry Andric         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) {
1070e8d8bef9SDimitry Andric           encodeULEB128(Sym.DataRef.Segment, W->OS);
1071e8d8bef9SDimitry Andric           encodeULEB128(Sym.DataRef.Offset, W->OS);
1072e8d8bef9SDimitry Andric           encodeULEB128(Sym.DataRef.Size, W->OS);
10730b57cec5SDimitry Andric         }
10740b57cec5SDimitry Andric         break;
10750b57cec5SDimitry Andric       case wasm::WASM_SYMBOL_TYPE_SECTION: {
10760b57cec5SDimitry Andric         const uint32_t SectionIndex =
10770b57cec5SDimitry Andric             CustomSections[Sym.ElementIndex].OutputIndex;
1078e8d8bef9SDimitry Andric         encodeULEB128(SectionIndex, W->OS);
10790b57cec5SDimitry Andric         break;
10800b57cec5SDimitry Andric       }
10810b57cec5SDimitry Andric       default:
10820b57cec5SDimitry Andric         llvm_unreachable("unexpected kind");
10830b57cec5SDimitry Andric       }
10840b57cec5SDimitry Andric     }
10850b57cec5SDimitry Andric     endSection(SubSection);
10860b57cec5SDimitry Andric   }
10870b57cec5SDimitry Andric 
10880b57cec5SDimitry Andric   if (DataSegments.size()) {
10890b57cec5SDimitry Andric     startSection(SubSection, wasm::WASM_SEGMENT_INFO);
1090e8d8bef9SDimitry Andric     encodeULEB128(DataSegments.size(), W->OS);
10910b57cec5SDimitry Andric     for (const WasmDataSegment &Segment : DataSegments) {
10920b57cec5SDimitry Andric       writeString(Segment.Name);
1093e8d8bef9SDimitry Andric       encodeULEB128(Segment.Alignment, W->OS);
1094e8d8bef9SDimitry Andric       encodeULEB128(Segment.LinkerFlags, W->OS);
10950b57cec5SDimitry Andric     }
10960b57cec5SDimitry Andric     endSection(SubSection);
10970b57cec5SDimitry Andric   }
10980b57cec5SDimitry Andric 
10990b57cec5SDimitry Andric   if (!InitFuncs.empty()) {
11000b57cec5SDimitry Andric     startSection(SubSection, wasm::WASM_INIT_FUNCS);
1101e8d8bef9SDimitry Andric     encodeULEB128(InitFuncs.size(), W->OS);
11020b57cec5SDimitry Andric     for (auto &StartFunc : InitFuncs) {
1103e8d8bef9SDimitry Andric       encodeULEB128(StartFunc.first, W->OS);  // priority
1104e8d8bef9SDimitry Andric       encodeULEB128(StartFunc.second, W->OS); // function index
11050b57cec5SDimitry Andric     }
11060b57cec5SDimitry Andric     endSection(SubSection);
11070b57cec5SDimitry Andric   }
11080b57cec5SDimitry Andric 
11090b57cec5SDimitry Andric   if (Comdats.size()) {
11100b57cec5SDimitry Andric     startSection(SubSection, wasm::WASM_COMDAT_INFO);
1111e8d8bef9SDimitry Andric     encodeULEB128(Comdats.size(), W->OS);
11120b57cec5SDimitry Andric     for (const auto &C : Comdats) {
11130b57cec5SDimitry Andric       writeString(C.first);
1114e8d8bef9SDimitry Andric       encodeULEB128(0, W->OS); // flags for future use
1115e8d8bef9SDimitry Andric       encodeULEB128(C.second.size(), W->OS);
11160b57cec5SDimitry Andric       for (const WasmComdatEntry &Entry : C.second) {
1117e8d8bef9SDimitry Andric         encodeULEB128(Entry.Kind, W->OS);
1118e8d8bef9SDimitry Andric         encodeULEB128(Entry.Index, W->OS);
11190b57cec5SDimitry Andric       }
11200b57cec5SDimitry Andric     }
11210b57cec5SDimitry Andric     endSection(SubSection);
11220b57cec5SDimitry Andric   }
11230b57cec5SDimitry Andric 
11240b57cec5SDimitry Andric   endSection(Section);
11250b57cec5SDimitry Andric }
11260b57cec5SDimitry Andric 
11270b57cec5SDimitry Andric void WasmObjectWriter::writeCustomSection(WasmCustomSection &CustomSection,
11280b57cec5SDimitry Andric                                           const MCAssembler &Asm,
11290b57cec5SDimitry Andric                                           const MCAsmLayout &Layout) {
11300b57cec5SDimitry Andric   SectionBookkeeping Section;
11310b57cec5SDimitry Andric   auto *Sec = CustomSection.Section;
11320b57cec5SDimitry Andric   startCustomSection(Section, CustomSection.Name);
11330b57cec5SDimitry Andric 
1134e8d8bef9SDimitry Andric   Sec->setSectionOffset(W->OS.tell() - Section.ContentsOffset);
1135e8d8bef9SDimitry Andric   Asm.writeSectionData(W->OS, Sec, Layout);
11360b57cec5SDimitry Andric 
11370b57cec5SDimitry Andric   CustomSection.OutputContentsOffset = Section.ContentsOffset;
11380b57cec5SDimitry Andric   CustomSection.OutputIndex = Section.Index;
11390b57cec5SDimitry Andric 
11400b57cec5SDimitry Andric   endSection(Section);
11410b57cec5SDimitry Andric 
11420b57cec5SDimitry Andric   // Apply fixups.
11430b57cec5SDimitry Andric   auto &Relocations = CustomSectionsRelocations[CustomSection.Section];
11445ffd83dbSDimitry Andric   applyRelocations(Relocations, CustomSection.OutputContentsOffset, Layout);
11450b57cec5SDimitry Andric }
11460b57cec5SDimitry Andric 
11470b57cec5SDimitry Andric uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm &Symbol) {
11480b57cec5SDimitry Andric   assert(Symbol.isFunction());
11490b57cec5SDimitry Andric   assert(TypeIndices.count(&Symbol));
11500b57cec5SDimitry Andric   return TypeIndices[&Symbol];
11510b57cec5SDimitry Andric }
11520b57cec5SDimitry Andric 
11530b57cec5SDimitry Andric uint32_t WasmObjectWriter::getEventType(const MCSymbolWasm &Symbol) {
11540b57cec5SDimitry Andric   assert(Symbol.isEvent());
11550b57cec5SDimitry Andric   assert(TypeIndices.count(&Symbol));
11560b57cec5SDimitry Andric   return TypeIndices[&Symbol];
11570b57cec5SDimitry Andric }
11580b57cec5SDimitry Andric 
11590b57cec5SDimitry Andric void WasmObjectWriter::registerFunctionType(const MCSymbolWasm &Symbol) {
11600b57cec5SDimitry Andric   assert(Symbol.isFunction());
11610b57cec5SDimitry Andric 
1162e8d8bef9SDimitry Andric   wasm::WasmSignature S;
11635ffd83dbSDimitry Andric 
11645ffd83dbSDimitry Andric   if (auto *Sig = Symbol.getSignature()) {
11650b57cec5SDimitry Andric     S.Returns = Sig->Returns;
11660b57cec5SDimitry Andric     S.Params = Sig->Params;
11670b57cec5SDimitry Andric   }
11680b57cec5SDimitry Andric 
11690b57cec5SDimitry Andric   auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
11700b57cec5SDimitry Andric   if (Pair.second)
11710b57cec5SDimitry Andric     Signatures.push_back(S);
11720b57cec5SDimitry Andric   TypeIndices[&Symbol] = Pair.first->second;
11730b57cec5SDimitry Andric 
11740b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "registerFunctionType: " << Symbol
11750b57cec5SDimitry Andric                     << " new:" << Pair.second << "\n");
11760b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
11770b57cec5SDimitry Andric }
11780b57cec5SDimitry Andric 
11790b57cec5SDimitry Andric void WasmObjectWriter::registerEventType(const MCSymbolWasm &Symbol) {
11800b57cec5SDimitry Andric   assert(Symbol.isEvent());
11810b57cec5SDimitry Andric 
11820b57cec5SDimitry Andric   // TODO Currently we don't generate imported exceptions, but if we do, we
11830b57cec5SDimitry Andric   // should have a way of infering types of imported exceptions.
1184e8d8bef9SDimitry Andric   wasm::WasmSignature S;
11850b57cec5SDimitry Andric   if (auto *Sig = Symbol.getSignature()) {
11860b57cec5SDimitry Andric     S.Returns = Sig->Returns;
11870b57cec5SDimitry Andric     S.Params = Sig->Params;
11880b57cec5SDimitry Andric   }
11890b57cec5SDimitry Andric 
11900b57cec5SDimitry Andric   auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
11910b57cec5SDimitry Andric   if (Pair.second)
11920b57cec5SDimitry Andric     Signatures.push_back(S);
11930b57cec5SDimitry Andric   TypeIndices[&Symbol] = Pair.first->second;
11940b57cec5SDimitry Andric 
11950b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "registerEventType: " << Symbol << " new:" << Pair.second
11960b57cec5SDimitry Andric                     << "\n");
11970b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
11980b57cec5SDimitry Andric }
11990b57cec5SDimitry Andric 
12000b57cec5SDimitry Andric static bool isInSymtab(const MCSymbolWasm &Sym) {
12015ffd83dbSDimitry Andric   if (Sym.isUsedInReloc() || Sym.isUsedInInitArray())
12020b57cec5SDimitry Andric     return true;
12030b57cec5SDimitry Andric 
12040b57cec5SDimitry Andric   if (Sym.isComdat() && !Sym.isDefined())
12050b57cec5SDimitry Andric     return false;
12060b57cec5SDimitry Andric 
12075ffd83dbSDimitry Andric   if (Sym.isTemporary())
12080b57cec5SDimitry Andric     return false;
12090b57cec5SDimitry Andric 
12100b57cec5SDimitry Andric   if (Sym.isSection())
12110b57cec5SDimitry Andric     return false;
12120b57cec5SDimitry Andric 
12130b57cec5SDimitry Andric   return true;
12140b57cec5SDimitry Andric }
12150b57cec5SDimitry Andric 
1216e8d8bef9SDimitry Andric void WasmObjectWriter::prepareImports(
1217e8d8bef9SDimitry Andric     SmallVectorImpl<wasm::WasmImport> &Imports, MCAssembler &Asm,
12180b57cec5SDimitry Andric     const MCAsmLayout &Layout) {
12190b57cec5SDimitry Andric   // For now, always emit the memory import, since loads and stores are not
12200b57cec5SDimitry Andric   // valid without it. In the future, we could perhaps be more clever and omit
12210b57cec5SDimitry Andric   // it if there are no loads or stores.
12220b57cec5SDimitry Andric   wasm::WasmImport MemImport;
12230b57cec5SDimitry Andric   MemImport.Module = "env";
12240b57cec5SDimitry Andric   MemImport.Field = "__linear_memory";
12250b57cec5SDimitry Andric   MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
12265ffd83dbSDimitry Andric   MemImport.Memory.Flags = is64Bit() ? wasm::WASM_LIMITS_FLAG_IS_64
12275ffd83dbSDimitry Andric                                      : wasm::WASM_LIMITS_FLAG_NONE;
12280b57cec5SDimitry Andric   Imports.push_back(MemImport);
12290b57cec5SDimitry Andric 
12300b57cec5SDimitry Andric   // Populate SignatureIndices, and Imports and WasmIndices for undefined
12310b57cec5SDimitry Andric   // symbols.  This must be done before populating WasmIndices for defined
12320b57cec5SDimitry Andric   // symbols.
12330b57cec5SDimitry Andric   for (const MCSymbol &S : Asm.symbols()) {
12340b57cec5SDimitry Andric     const auto &WS = static_cast<const MCSymbolWasm &>(S);
12350b57cec5SDimitry Andric 
12360b57cec5SDimitry Andric     // Register types for all functions, including those with private linkage
12370b57cec5SDimitry Andric     // (because wasm always needs a type signature).
12385ffd83dbSDimitry Andric     if (WS.isFunction()) {
1239e8d8bef9SDimitry Andric       const auto *BS = Layout.getBaseSymbol(S);
1240e8d8bef9SDimitry Andric       if (!BS)
1241e8d8bef9SDimitry Andric         report_fatal_error(Twine(S.getName()) +
1242e8d8bef9SDimitry Andric                            ": absolute addressing not supported!");
1243e8d8bef9SDimitry Andric       registerFunctionType(*cast<MCSymbolWasm>(BS));
12445ffd83dbSDimitry Andric     }
12450b57cec5SDimitry Andric 
12460b57cec5SDimitry Andric     if (WS.isEvent())
12470b57cec5SDimitry Andric       registerEventType(WS);
12480b57cec5SDimitry Andric 
12490b57cec5SDimitry Andric     if (WS.isTemporary())
12500b57cec5SDimitry Andric       continue;
12510b57cec5SDimitry Andric 
12520b57cec5SDimitry Andric     // If the symbol is not defined in this translation unit, import it.
12530b57cec5SDimitry Andric     if (!WS.isDefined() && !WS.isComdat()) {
12540b57cec5SDimitry Andric       if (WS.isFunction()) {
12550b57cec5SDimitry Andric         wasm::WasmImport Import;
12560b57cec5SDimitry Andric         Import.Module = WS.getImportModule();
12570b57cec5SDimitry Andric         Import.Field = WS.getImportName();
12580b57cec5SDimitry Andric         Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
12590b57cec5SDimitry Andric         Import.SigIndex = getFunctionType(WS);
12600b57cec5SDimitry Andric         Imports.push_back(Import);
12610b57cec5SDimitry Andric         assert(WasmIndices.count(&WS) == 0);
12620b57cec5SDimitry Andric         WasmIndices[&WS] = NumFunctionImports++;
12630b57cec5SDimitry Andric       } else if (WS.isGlobal()) {
12640b57cec5SDimitry Andric         if (WS.isWeak())
12650b57cec5SDimitry Andric           report_fatal_error("undefined global symbol cannot be weak");
12660b57cec5SDimitry Andric 
12670b57cec5SDimitry Andric         wasm::WasmImport Import;
12680b57cec5SDimitry Andric         Import.Field = WS.getImportName();
12690b57cec5SDimitry Andric         Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
12700b57cec5SDimitry Andric         Import.Module = WS.getImportModule();
12710b57cec5SDimitry Andric         Import.Global = WS.getGlobalType();
12720b57cec5SDimitry Andric         Imports.push_back(Import);
12730b57cec5SDimitry Andric         assert(WasmIndices.count(&WS) == 0);
12740b57cec5SDimitry Andric         WasmIndices[&WS] = NumGlobalImports++;
12750b57cec5SDimitry Andric       } else if (WS.isEvent()) {
12760b57cec5SDimitry Andric         if (WS.isWeak())
12770b57cec5SDimitry Andric           report_fatal_error("undefined event symbol cannot be weak");
12780b57cec5SDimitry Andric 
12790b57cec5SDimitry Andric         wasm::WasmImport Import;
12800b57cec5SDimitry Andric         Import.Module = WS.getImportModule();
12810b57cec5SDimitry Andric         Import.Field = WS.getImportName();
12820b57cec5SDimitry Andric         Import.Kind = wasm::WASM_EXTERNAL_EVENT;
12830b57cec5SDimitry Andric         Import.Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
12840b57cec5SDimitry Andric         Import.Event.SigIndex = getEventType(WS);
12850b57cec5SDimitry Andric         Imports.push_back(Import);
12860b57cec5SDimitry Andric         assert(WasmIndices.count(&WS) == 0);
12870b57cec5SDimitry Andric         WasmIndices[&WS] = NumEventImports++;
1288e8d8bef9SDimitry Andric       } else if (WS.isTable()) {
1289e8d8bef9SDimitry Andric         if (WS.isWeak())
1290e8d8bef9SDimitry Andric           report_fatal_error("undefined table symbol cannot be weak");
1291e8d8bef9SDimitry Andric 
1292e8d8bef9SDimitry Andric         wasm::WasmImport Import;
1293e8d8bef9SDimitry Andric         Import.Module = WS.getImportModule();
1294e8d8bef9SDimitry Andric         Import.Field = WS.getImportName();
1295e8d8bef9SDimitry Andric         Import.Kind = wasm::WASM_EXTERNAL_TABLE;
1296e8d8bef9SDimitry Andric         wasm::ValType ElemType = WS.getTableType();
1297e8d8bef9SDimitry Andric         Import.Table.ElemType = uint8_t(ElemType);
1298e8d8bef9SDimitry Andric         // FIXME: Extend table type to include limits? For now we don't specify
1299e8d8bef9SDimitry Andric         // a min or max which does not place any restrictions on the size of the
1300e8d8bef9SDimitry Andric         // imported table.
1301e8d8bef9SDimitry Andric         Import.Table.Limits = {wasm::WASM_LIMITS_FLAG_NONE, 0, 0};
1302e8d8bef9SDimitry Andric         Imports.push_back(Import);
1303e8d8bef9SDimitry Andric         assert(WasmIndices.count(&WS) == 0);
1304e8d8bef9SDimitry Andric         WasmIndices[&WS] = NumTableImports++;
13050b57cec5SDimitry Andric       }
13060b57cec5SDimitry Andric     }
13070b57cec5SDimitry Andric   }
13080b57cec5SDimitry Andric 
13090b57cec5SDimitry Andric   // Add imports for GOT globals
13100b57cec5SDimitry Andric   for (const MCSymbol &S : Asm.symbols()) {
13110b57cec5SDimitry Andric     const auto &WS = static_cast<const MCSymbolWasm &>(S);
13120b57cec5SDimitry Andric     if (WS.isUsedInGOT()) {
13130b57cec5SDimitry Andric       wasm::WasmImport Import;
13140b57cec5SDimitry Andric       if (WS.isFunction())
13150b57cec5SDimitry Andric         Import.Module = "GOT.func";
13160b57cec5SDimitry Andric       else
13170b57cec5SDimitry Andric         Import.Module = "GOT.mem";
13180b57cec5SDimitry Andric       Import.Field = WS.getName();
13190b57cec5SDimitry Andric       Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
13200b57cec5SDimitry Andric       Import.Global = {wasm::WASM_TYPE_I32, true};
13210b57cec5SDimitry Andric       Imports.push_back(Import);
13220b57cec5SDimitry Andric       assert(GOTIndices.count(&WS) == 0);
13230b57cec5SDimitry Andric       GOTIndices[&WS] = NumGlobalImports++;
13240b57cec5SDimitry Andric     }
13250b57cec5SDimitry Andric   }
1326e8d8bef9SDimitry Andric }
1327e8d8bef9SDimitry Andric 
1328e8d8bef9SDimitry Andric uint64_t WasmObjectWriter::writeObject(MCAssembler &Asm,
1329e8d8bef9SDimitry Andric                                        const MCAsmLayout &Layout) {
1330e8d8bef9SDimitry Andric   support::endian::Writer MainWriter(*OS, support::little);
1331e8d8bef9SDimitry Andric   W = &MainWriter;
1332e8d8bef9SDimitry Andric   if (IsSplitDwarf) {
1333e8d8bef9SDimitry Andric     uint64_t TotalSize = writeOneObject(Asm, Layout, DwoMode::NonDwoOnly);
1334e8d8bef9SDimitry Andric     assert(DwoOS);
1335e8d8bef9SDimitry Andric     support::endian::Writer DwoWriter(*DwoOS, support::little);
1336e8d8bef9SDimitry Andric     W = &DwoWriter;
1337e8d8bef9SDimitry Andric     return TotalSize + writeOneObject(Asm, Layout, DwoMode::DwoOnly);
1338e8d8bef9SDimitry Andric   } else {
1339e8d8bef9SDimitry Andric     return writeOneObject(Asm, Layout, DwoMode::AllSections);
1340e8d8bef9SDimitry Andric   }
1341e8d8bef9SDimitry Andric }
1342e8d8bef9SDimitry Andric 
1343e8d8bef9SDimitry Andric uint64_t WasmObjectWriter::writeOneObject(MCAssembler &Asm,
1344e8d8bef9SDimitry Andric                                           const MCAsmLayout &Layout,
1345e8d8bef9SDimitry Andric                                           DwoMode Mode) {
1346e8d8bef9SDimitry Andric   uint64_t StartOffset = W->OS.tell();
1347e8d8bef9SDimitry Andric   SectionCount = 0;
1348e8d8bef9SDimitry Andric   CustomSections.clear();
1349e8d8bef9SDimitry Andric 
1350e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
1351e8d8bef9SDimitry Andric 
1352e8d8bef9SDimitry Andric   // Collect information from the available symbols.
1353e8d8bef9SDimitry Andric   SmallVector<WasmFunction, 4> Functions;
1354e8d8bef9SDimitry Andric   SmallVector<uint32_t, 4> TableElems;
1355e8d8bef9SDimitry Andric   SmallVector<wasm::WasmImport, 4> Imports;
1356e8d8bef9SDimitry Andric   SmallVector<wasm::WasmExport, 4> Exports;
1357e8d8bef9SDimitry Andric   SmallVector<wasm::WasmEventType, 1> Events;
1358e8d8bef9SDimitry Andric   SmallVector<wasm::WasmGlobal, 1> Globals;
1359e8d8bef9SDimitry Andric   SmallVector<wasm::WasmTable, 1> Tables;
1360e8d8bef9SDimitry Andric   SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos;
1361e8d8bef9SDimitry Andric   SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
1362e8d8bef9SDimitry Andric   std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
1363e8d8bef9SDimitry Andric   uint64_t DataSize = 0;
1364e8d8bef9SDimitry Andric   if (Mode != DwoMode::DwoOnly) {
1365e8d8bef9SDimitry Andric     prepareImports(Imports, Asm, Layout);
1366e8d8bef9SDimitry Andric   }
13670b57cec5SDimitry Andric 
13680b57cec5SDimitry Andric   // Populate DataSegments and CustomSections, which must be done before
13690b57cec5SDimitry Andric   // populating DataLocations.
13700b57cec5SDimitry Andric   for (MCSection &Sec : Asm) {
13710b57cec5SDimitry Andric     auto &Section = static_cast<MCSectionWasm &>(Sec);
13725ffd83dbSDimitry Andric     StringRef SectionName = Section.getName();
13730b57cec5SDimitry Andric 
1374e8d8bef9SDimitry Andric     if (Mode == DwoMode::NonDwoOnly && isDwoSection(Sec))
1375e8d8bef9SDimitry Andric       continue;
1376e8d8bef9SDimitry Andric     if (Mode == DwoMode::DwoOnly && !isDwoSection(Sec))
1377e8d8bef9SDimitry Andric       continue;
1378e8d8bef9SDimitry Andric 
1379e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Processing Section " << SectionName << "  group "
1380e8d8bef9SDimitry Andric                       << Section.getGroup() << "\n";);
1381e8d8bef9SDimitry Andric 
13820b57cec5SDimitry Andric     // .init_array sections are handled specially elsewhere.
13830b57cec5SDimitry Andric     if (SectionName.startswith(".init_array"))
13840b57cec5SDimitry Andric       continue;
13850b57cec5SDimitry Andric 
13860b57cec5SDimitry Andric     // Code is handled separately
13870b57cec5SDimitry Andric     if (Section.getKind().isText())
13880b57cec5SDimitry Andric       continue;
13890b57cec5SDimitry Andric 
13900b57cec5SDimitry Andric     if (Section.isWasmData()) {
13910b57cec5SDimitry Andric       uint32_t SegmentIndex = DataSegments.size();
13920b57cec5SDimitry Andric       DataSize = alignTo(DataSize, Section.getAlignment());
13930b57cec5SDimitry Andric       DataSegments.emplace_back();
13940b57cec5SDimitry Andric       WasmDataSegment &Segment = DataSegments.back();
13950b57cec5SDimitry Andric       Segment.Name = SectionName;
1396e8d8bef9SDimitry Andric       Segment.InitFlags = Section.getPassive()
1397e8d8bef9SDimitry Andric                               ? (uint32_t)wasm::WASM_DATA_SEGMENT_IS_PASSIVE
1398e8d8bef9SDimitry Andric                               : 0;
13990b57cec5SDimitry Andric       Segment.Offset = DataSize;
14000b57cec5SDimitry Andric       Segment.Section = &Section;
14010b57cec5SDimitry Andric       addData(Segment.Data, Section);
14020b57cec5SDimitry Andric       Segment.Alignment = Log2_32(Section.getAlignment());
14030b57cec5SDimitry Andric       Segment.LinkerFlags = 0;
14040b57cec5SDimitry Andric       DataSize += Segment.Data.size();
14050b57cec5SDimitry Andric       Section.setSegmentIndex(SegmentIndex);
14060b57cec5SDimitry Andric 
14070b57cec5SDimitry Andric       if (const MCSymbolWasm *C = Section.getGroup()) {
14080b57cec5SDimitry Andric         Comdats[C->getName()].emplace_back(
14090b57cec5SDimitry Andric             WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
14100b57cec5SDimitry Andric       }
14110b57cec5SDimitry Andric     } else {
14120b57cec5SDimitry Andric       // Create custom sections
14130b57cec5SDimitry Andric       assert(Sec.getKind().isMetadata());
14140b57cec5SDimitry Andric 
14150b57cec5SDimitry Andric       StringRef Name = SectionName;
14160b57cec5SDimitry Andric 
14170b57cec5SDimitry Andric       // For user-defined custom sections, strip the prefix
14180b57cec5SDimitry Andric       if (Name.startswith(".custom_section."))
14190b57cec5SDimitry Andric         Name = Name.substr(strlen(".custom_section."));
14200b57cec5SDimitry Andric 
14210b57cec5SDimitry Andric       MCSymbol *Begin = Sec.getBeginSymbol();
14220b57cec5SDimitry Andric       if (Begin) {
1423e8d8bef9SDimitry Andric         assert(WasmIndices.count(cast<MCSymbolWasm>(Begin)) == 0);
14240b57cec5SDimitry Andric         WasmIndices[cast<MCSymbolWasm>(Begin)] = CustomSections.size();
14250b57cec5SDimitry Andric       }
14260b57cec5SDimitry Andric 
14270b57cec5SDimitry Andric       // Separate out the producers and target features sections
14280b57cec5SDimitry Andric       if (Name == "producers") {
14298bcb0991SDimitry Andric         ProducersSection = std::make_unique<WasmCustomSection>(Name, &Section);
14300b57cec5SDimitry Andric         continue;
14310b57cec5SDimitry Andric       }
14320b57cec5SDimitry Andric       if (Name == "target_features") {
14330b57cec5SDimitry Andric         TargetFeaturesSection =
14348bcb0991SDimitry Andric             std::make_unique<WasmCustomSection>(Name, &Section);
14350b57cec5SDimitry Andric         continue;
14360b57cec5SDimitry Andric       }
14370b57cec5SDimitry Andric 
1438e8d8bef9SDimitry Andric       // Custom sections can also belong to COMDAT groups. In this case the
1439e8d8bef9SDimitry Andric       // decriptor's "index" field is the section index (in the final object
1440e8d8bef9SDimitry Andric       // file), but that is not known until after layout, so it must be fixed up
1441e8d8bef9SDimitry Andric       // later
1442e8d8bef9SDimitry Andric       if (const MCSymbolWasm *C = Section.getGroup()) {
1443e8d8bef9SDimitry Andric         Comdats[C->getName()].emplace_back(
1444e8d8bef9SDimitry Andric             WasmComdatEntry{wasm::WASM_COMDAT_SECTION,
1445e8d8bef9SDimitry Andric                             static_cast<uint32_t>(CustomSections.size())});
1446e8d8bef9SDimitry Andric       }
1447e8d8bef9SDimitry Andric 
14480b57cec5SDimitry Andric       CustomSections.emplace_back(Name, &Section);
14490b57cec5SDimitry Andric     }
14500b57cec5SDimitry Andric   }
14510b57cec5SDimitry Andric 
1452e8d8bef9SDimitry Andric   if (Mode != DwoMode::DwoOnly) {
14530b57cec5SDimitry Andric     // Populate WasmIndices and DataLocations for defined symbols.
14540b57cec5SDimitry Andric     for (const MCSymbol &S : Asm.symbols()) {
14550b57cec5SDimitry Andric       // Ignore unnamed temporary symbols, which aren't ever exported, imported,
14560b57cec5SDimitry Andric       // or used in relocations.
14570b57cec5SDimitry Andric       if (S.isTemporary() && S.getName().empty())
14580b57cec5SDimitry Andric         continue;
14590b57cec5SDimitry Andric 
14600b57cec5SDimitry Andric       const auto &WS = static_cast<const MCSymbolWasm &>(S);
14610b57cec5SDimitry Andric       LLVM_DEBUG(
14620b57cec5SDimitry Andric           dbgs() << "MCSymbol: " << toString(WS.getType()) << " '" << S << "'"
14630b57cec5SDimitry Andric                  << " isDefined=" << S.isDefined() << " isExternal="
14640b57cec5SDimitry Andric                  << S.isExternal() << " isTemporary=" << S.isTemporary()
14650b57cec5SDimitry Andric                  << " isWeak=" << WS.isWeak() << " isHidden=" << WS.isHidden()
14660b57cec5SDimitry Andric                  << " isVariable=" << WS.isVariable() << "\n");
14670b57cec5SDimitry Andric 
14680b57cec5SDimitry Andric       if (WS.isVariable())
14690b57cec5SDimitry Andric         continue;
14700b57cec5SDimitry Andric       if (WS.isComdat() && !WS.isDefined())
14710b57cec5SDimitry Andric         continue;
14720b57cec5SDimitry Andric 
14730b57cec5SDimitry Andric       if (WS.isFunction()) {
14740b57cec5SDimitry Andric         unsigned Index;
14750b57cec5SDimitry Andric         if (WS.isDefined()) {
14760b57cec5SDimitry Andric           if (WS.getOffset() != 0)
14770b57cec5SDimitry Andric             report_fatal_error(
14780b57cec5SDimitry Andric                 "function sections must contain one function each");
14790b57cec5SDimitry Andric 
14800b57cec5SDimitry Andric           if (WS.getSize() == nullptr)
14810b57cec5SDimitry Andric             report_fatal_error(
14820b57cec5SDimitry Andric                 "function symbols must have a size set with .size");
14830b57cec5SDimitry Andric 
14840b57cec5SDimitry Andric           // A definition. Write out the function body.
14850b57cec5SDimitry Andric           Index = NumFunctionImports + Functions.size();
14860b57cec5SDimitry Andric           WasmFunction Func;
14870b57cec5SDimitry Andric           Func.SigIndex = getFunctionType(WS);
14880b57cec5SDimitry Andric           Func.Sym = &WS;
1489e8d8bef9SDimitry Andric           assert(WasmIndices.count(&WS) == 0);
14900b57cec5SDimitry Andric           WasmIndices[&WS] = Index;
14910b57cec5SDimitry Andric           Functions.push_back(Func);
14920b57cec5SDimitry Andric 
14930b57cec5SDimitry Andric           auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
14940b57cec5SDimitry Andric           if (const MCSymbolWasm *C = Section.getGroup()) {
14950b57cec5SDimitry Andric             Comdats[C->getName()].emplace_back(
14960b57cec5SDimitry Andric                 WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
14970b57cec5SDimitry Andric           }
1498480093f4SDimitry Andric 
1499480093f4SDimitry Andric           if (WS.hasExportName()) {
1500480093f4SDimitry Andric             wasm::WasmExport Export;
1501480093f4SDimitry Andric             Export.Name = WS.getExportName();
1502480093f4SDimitry Andric             Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1503480093f4SDimitry Andric             Export.Index = Index;
1504480093f4SDimitry Andric             Exports.push_back(Export);
1505480093f4SDimitry Andric           }
15060b57cec5SDimitry Andric         } else {
15070b57cec5SDimitry Andric           // An import; the index was assigned above.
15080b57cec5SDimitry Andric           Index = WasmIndices.find(&WS)->second;
15090b57cec5SDimitry Andric         }
15100b57cec5SDimitry Andric 
15110b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "  -> function index: " << Index << "\n");
15120b57cec5SDimitry Andric 
15130b57cec5SDimitry Andric       } else if (WS.isData()) {
15140b57cec5SDimitry Andric         if (!isInSymtab(WS))
15150b57cec5SDimitry Andric           continue;
15160b57cec5SDimitry Andric 
15170b57cec5SDimitry Andric         if (!WS.isDefined()) {
15180b57cec5SDimitry Andric           LLVM_DEBUG(dbgs() << "  -> segment index: -1"
15190b57cec5SDimitry Andric                             << "\n");
15200b57cec5SDimitry Andric           continue;
15210b57cec5SDimitry Andric         }
15220b57cec5SDimitry Andric 
15230b57cec5SDimitry Andric         if (!WS.getSize())
15240b57cec5SDimitry Andric           report_fatal_error("data symbols must have a size set with .size: " +
15250b57cec5SDimitry Andric                              WS.getName());
15260b57cec5SDimitry Andric 
15270b57cec5SDimitry Andric         int64_t Size = 0;
15280b57cec5SDimitry Andric         if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
15290b57cec5SDimitry Andric           report_fatal_error(".size expression must be evaluatable");
15300b57cec5SDimitry Andric 
15310b57cec5SDimitry Andric         auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
15328bcb0991SDimitry Andric         if (!DataSection.isWasmData())
15338bcb0991SDimitry Andric           report_fatal_error("data symbols must live in a data section: " +
15348bcb0991SDimitry Andric                              WS.getName());
15350b57cec5SDimitry Andric 
15360b57cec5SDimitry Andric         // For each data symbol, export it in the symtab as a reference to the
15370b57cec5SDimitry Andric         // corresponding Wasm data segment.
15380b57cec5SDimitry Andric         wasm::WasmDataReference Ref = wasm::WasmDataReference{
15395ffd83dbSDimitry Andric             DataSection.getSegmentIndex(), Layout.getSymbolOffset(WS),
15405ffd83dbSDimitry Andric             static_cast<uint64_t>(Size)};
1541e8d8bef9SDimitry Andric         assert(DataLocations.count(&WS) == 0);
15420b57cec5SDimitry Andric         DataLocations[&WS] = Ref;
15430b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "  -> segment index: " << Ref.Segment << "\n");
15440b57cec5SDimitry Andric 
15450b57cec5SDimitry Andric       } else if (WS.isGlobal()) {
15460b57cec5SDimitry Andric         // A "true" Wasm global (currently just __stack_pointer)
15475ffd83dbSDimitry Andric         if (WS.isDefined()) {
15485ffd83dbSDimitry Andric           wasm::WasmGlobal Global;
15495ffd83dbSDimitry Andric           Global.Type = WS.getGlobalType();
15505ffd83dbSDimitry Andric           Global.Index = NumGlobalImports + Globals.size();
15515ffd83dbSDimitry Andric           switch (Global.Type.Type) {
15525ffd83dbSDimitry Andric           case wasm::WASM_TYPE_I32:
15535ffd83dbSDimitry Andric             Global.InitExpr.Opcode = wasm::WASM_OPCODE_I32_CONST;
15545ffd83dbSDimitry Andric             break;
15555ffd83dbSDimitry Andric           case wasm::WASM_TYPE_I64:
15565ffd83dbSDimitry Andric             Global.InitExpr.Opcode = wasm::WASM_OPCODE_I64_CONST;
15575ffd83dbSDimitry Andric             break;
15585ffd83dbSDimitry Andric           case wasm::WASM_TYPE_F32:
15595ffd83dbSDimitry Andric             Global.InitExpr.Opcode = wasm::WASM_OPCODE_F32_CONST;
15605ffd83dbSDimitry Andric             break;
15615ffd83dbSDimitry Andric           case wasm::WASM_TYPE_F64:
15625ffd83dbSDimitry Andric             Global.InitExpr.Opcode = wasm::WASM_OPCODE_F64_CONST;
15635ffd83dbSDimitry Andric             break;
15645ffd83dbSDimitry Andric           case wasm::WASM_TYPE_EXTERNREF:
15655ffd83dbSDimitry Andric             Global.InitExpr.Opcode = wasm::WASM_OPCODE_REF_NULL;
15665ffd83dbSDimitry Andric             break;
15675ffd83dbSDimitry Andric           default:
15685ffd83dbSDimitry Andric             llvm_unreachable("unexpected type");
15695ffd83dbSDimitry Andric           }
1570e8d8bef9SDimitry Andric           assert(WasmIndices.count(&WS) == 0);
15715ffd83dbSDimitry Andric           WasmIndices[&WS] = Global.Index;
15725ffd83dbSDimitry Andric           Globals.push_back(Global);
15735ffd83dbSDimitry Andric         } else {
15740b57cec5SDimitry Andric           // An import; the index was assigned above
15750b57cec5SDimitry Andric           LLVM_DEBUG(dbgs() << "  -> global index: "
15760b57cec5SDimitry Andric                             << WasmIndices.find(&WS)->second << "\n");
15775ffd83dbSDimitry Andric         }
1578e8d8bef9SDimitry Andric       } else if (WS.isTable()) {
1579e8d8bef9SDimitry Andric         if (WS.isDefined()) {
1580e8d8bef9SDimitry Andric           wasm::WasmTable Table;
1581e8d8bef9SDimitry Andric           Table.Index = NumTableImports + Tables.size();
1582e8d8bef9SDimitry Andric           Table.Type.ElemType = static_cast<uint8_t>(WS.getTableType());
1583e8d8bef9SDimitry Andric           // FIXME: Work on custom limits is ongoing
1584e8d8bef9SDimitry Andric           Table.Type.Limits = {wasm::WASM_LIMITS_FLAG_NONE, 0, 0};
1585e8d8bef9SDimitry Andric           assert(WasmIndices.count(&WS) == 0);
1586e8d8bef9SDimitry Andric           WasmIndices[&WS] = Table.Index;
1587e8d8bef9SDimitry Andric           Tables.push_back(Table);
1588e8d8bef9SDimitry Andric         }
1589e8d8bef9SDimitry Andric         LLVM_DEBUG(dbgs() << " -> table index: "
1590e8d8bef9SDimitry Andric                           << WasmIndices.find(&WS)->second << "\n");
15910b57cec5SDimitry Andric       } else if (WS.isEvent()) {
15920b57cec5SDimitry Andric         // C++ exception symbol (__cpp_exception)
15930b57cec5SDimitry Andric         unsigned Index;
15940b57cec5SDimitry Andric         if (WS.isDefined()) {
15950b57cec5SDimitry Andric           Index = NumEventImports + Events.size();
15960b57cec5SDimitry Andric           wasm::WasmEventType Event;
15970b57cec5SDimitry Andric           Event.SigIndex = getEventType(WS);
15980b57cec5SDimitry Andric           Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
1599e8d8bef9SDimitry Andric           assert(WasmIndices.count(&WS) == 0);
16000b57cec5SDimitry Andric           WasmIndices[&WS] = Index;
16010b57cec5SDimitry Andric           Events.push_back(Event);
16020b57cec5SDimitry Andric         } else {
16030b57cec5SDimitry Andric           // An import; the index was assigned above.
16040b57cec5SDimitry Andric           assert(WasmIndices.count(&WS) > 0);
16050b57cec5SDimitry Andric         }
1606e8d8bef9SDimitry Andric         LLVM_DEBUG(dbgs() << "  -> event index: "
1607e8d8bef9SDimitry Andric                           << WasmIndices.find(&WS)->second << "\n");
16080b57cec5SDimitry Andric 
16090b57cec5SDimitry Andric       } else {
16100b57cec5SDimitry Andric         assert(WS.isSection());
16110b57cec5SDimitry Andric       }
16120b57cec5SDimitry Andric     }
16130b57cec5SDimitry Andric 
16140b57cec5SDimitry Andric     // Populate WasmIndices and DataLocations for aliased symbols.  We need to
16150b57cec5SDimitry Andric     // process these in a separate pass because we need to have processed the
16160b57cec5SDimitry Andric     // target of the alias before the alias itself and the symbols are not
16170b57cec5SDimitry Andric     // necessarily ordered in this way.
16180b57cec5SDimitry Andric     for (const MCSymbol &S : Asm.symbols()) {
16190b57cec5SDimitry Andric       if (!S.isVariable())
16200b57cec5SDimitry Andric         continue;
16210b57cec5SDimitry Andric 
16220b57cec5SDimitry Andric       assert(S.isDefined());
16230b57cec5SDimitry Andric 
1624e8d8bef9SDimitry Andric       const auto *BS = Layout.getBaseSymbol(S);
1625e8d8bef9SDimitry Andric       if (!BS)
1626e8d8bef9SDimitry Andric         report_fatal_error(Twine(S.getName()) +
1627e8d8bef9SDimitry Andric                            ": absolute addressing not supported!");
1628e8d8bef9SDimitry Andric       const MCSymbolWasm *Base = cast<MCSymbolWasm>(BS);
16295ffd83dbSDimitry Andric 
16300b57cec5SDimitry Andric       // Find the target symbol of this weak alias and export that index
16310b57cec5SDimitry Andric       const auto &WS = static_cast<const MCSymbolWasm &>(S);
1632e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *Base
1633e8d8bef9SDimitry Andric                         << "'\n");
16340b57cec5SDimitry Andric 
16355ffd83dbSDimitry Andric       if (Base->isFunction()) {
16365ffd83dbSDimitry Andric         assert(WasmIndices.count(Base) > 0);
16375ffd83dbSDimitry Andric         uint32_t WasmIndex = WasmIndices.find(Base)->second;
16380b57cec5SDimitry Andric         assert(WasmIndices.count(&WS) == 0);
16390b57cec5SDimitry Andric         WasmIndices[&WS] = WasmIndex;
16400b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "  -> index:" << WasmIndex << "\n");
16415ffd83dbSDimitry Andric       } else if (Base->isData()) {
16425ffd83dbSDimitry Andric         auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
16435ffd83dbSDimitry Andric         uint64_t Offset = Layout.getSymbolOffset(S);
16445ffd83dbSDimitry Andric         int64_t Size = 0;
16455ffd83dbSDimitry Andric         // For data symbol alias we use the size of the base symbol as the
16465ffd83dbSDimitry Andric         // size of the alias.  When an offset from the base is involved this
16475ffd83dbSDimitry Andric         // can result in a offset + size goes past the end of the data section
16485ffd83dbSDimitry Andric         // which out object format doesn't support.  So we must clamp it.
16495ffd83dbSDimitry Andric         if (!Base->getSize()->evaluateAsAbsolute(Size, Layout))
16505ffd83dbSDimitry Andric           report_fatal_error(".size expression must be evaluatable");
16515ffd83dbSDimitry Andric         const WasmDataSegment &Segment =
16525ffd83dbSDimitry Andric             DataSegments[DataSection.getSegmentIndex()];
16535ffd83dbSDimitry Andric         Size =
16545ffd83dbSDimitry Andric             std::min(static_cast<uint64_t>(Size), Segment.Data.size() - Offset);
16555ffd83dbSDimitry Andric         wasm::WasmDataReference Ref = wasm::WasmDataReference{
16565ffd83dbSDimitry Andric             DataSection.getSegmentIndex(),
16575ffd83dbSDimitry Andric             static_cast<uint32_t>(Layout.getSymbolOffset(S)),
16585ffd83dbSDimitry Andric             static_cast<uint32_t>(Size)};
16590b57cec5SDimitry Andric         DataLocations[&WS] = Ref;
16600b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "  -> index:" << Ref.Segment << "\n");
16610b57cec5SDimitry Andric       } else {
16620b57cec5SDimitry Andric         report_fatal_error("don't yet support global/event aliases");
16630b57cec5SDimitry Andric       }
16640b57cec5SDimitry Andric     }
1665e8d8bef9SDimitry Andric   }
16660b57cec5SDimitry Andric 
16670b57cec5SDimitry Andric   // Finally, populate the symbol table itself, in its "natural" order.
16680b57cec5SDimitry Andric   for (const MCSymbol &S : Asm.symbols()) {
16690b57cec5SDimitry Andric     const auto &WS = static_cast<const MCSymbolWasm &>(S);
16700b57cec5SDimitry Andric     if (!isInSymtab(WS)) {
16710b57cec5SDimitry Andric       WS.setIndex(InvalidIndex);
16720b57cec5SDimitry Andric       continue;
16730b57cec5SDimitry Andric     }
1674e8d8bef9SDimitry Andric     if (WS.isTable() && WS.getName() == "__indirect_function_table") {
1675e8d8bef9SDimitry Andric       // For the moment, don't emit table symbols -- wasm-ld can't handle them.
1676e8d8bef9SDimitry Andric       continue;
1677e8d8bef9SDimitry Andric     }
16780b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "adding to symtab: " << WS << "\n");
16790b57cec5SDimitry Andric 
16800b57cec5SDimitry Andric     uint32_t Flags = 0;
16810b57cec5SDimitry Andric     if (WS.isWeak())
16820b57cec5SDimitry Andric       Flags |= wasm::WASM_SYMBOL_BINDING_WEAK;
16830b57cec5SDimitry Andric     if (WS.isHidden())
16840b57cec5SDimitry Andric       Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN;
16850b57cec5SDimitry Andric     if (!WS.isExternal() && WS.isDefined())
16860b57cec5SDimitry Andric       Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;
16870b57cec5SDimitry Andric     if (WS.isUndefined())
16880b57cec5SDimitry Andric       Flags |= wasm::WASM_SYMBOL_UNDEFINED;
16898bcb0991SDimitry Andric     if (WS.isNoStrip()) {
16908bcb0991SDimitry Andric       Flags |= wasm::WASM_SYMBOL_NO_STRIP;
16918bcb0991SDimitry Andric       if (isEmscripten()) {
16920b57cec5SDimitry Andric         Flags |= wasm::WASM_SYMBOL_EXPORTED;
16938bcb0991SDimitry Andric       }
16948bcb0991SDimitry Andric     }
1695480093f4SDimitry Andric     if (WS.hasImportName())
16960b57cec5SDimitry Andric       Flags |= wasm::WASM_SYMBOL_EXPLICIT_NAME;
1697480093f4SDimitry Andric     if (WS.hasExportName())
1698480093f4SDimitry Andric       Flags |= wasm::WASM_SYMBOL_EXPORTED;
16990b57cec5SDimitry Andric 
17000b57cec5SDimitry Andric     wasm::WasmSymbolInfo Info;
17010b57cec5SDimitry Andric     Info.Name = WS.getName();
17020b57cec5SDimitry Andric     Info.Kind = WS.getType();
17030b57cec5SDimitry Andric     Info.Flags = Flags;
17040b57cec5SDimitry Andric     if (!WS.isData()) {
17050b57cec5SDimitry Andric       assert(WasmIndices.count(&WS) > 0);
17060b57cec5SDimitry Andric       Info.ElementIndex = WasmIndices.find(&WS)->second;
17070b57cec5SDimitry Andric     } else if (WS.isDefined()) {
17080b57cec5SDimitry Andric       assert(DataLocations.count(&WS) > 0);
17090b57cec5SDimitry Andric       Info.DataRef = DataLocations.find(&WS)->second;
17100b57cec5SDimitry Andric     }
17110b57cec5SDimitry Andric     WS.setIndex(SymbolInfos.size());
17120b57cec5SDimitry Andric     SymbolInfos.emplace_back(Info);
17130b57cec5SDimitry Andric   }
17140b57cec5SDimitry Andric 
17150b57cec5SDimitry Andric   {
17160b57cec5SDimitry Andric     auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
17170b57cec5SDimitry Andric       // Functions referenced by a relocation need to put in the table.  This is
17180b57cec5SDimitry Andric       // purely to make the object file's provisional values readable, and is
17190b57cec5SDimitry Andric       // ignored by the linker, which re-calculates the relocations itself.
17200b57cec5SDimitry Andric       if (Rel.Type != wasm::R_WASM_TABLE_INDEX_I32 &&
1721e8d8bef9SDimitry Andric           Rel.Type != wasm::R_WASM_TABLE_INDEX_I64 &&
17225ffd83dbSDimitry Andric           Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB &&
1723e8d8bef9SDimitry Andric           Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB64 &&
17245ffd83dbSDimitry Andric           Rel.Type != wasm::R_WASM_TABLE_INDEX_REL_SLEB)
17250b57cec5SDimitry Andric         return;
17260b57cec5SDimitry Andric       assert(Rel.Symbol->isFunction());
17275ffd83dbSDimitry Andric       const MCSymbolWasm *Base =
17285ffd83dbSDimitry Andric           cast<MCSymbolWasm>(Layout.getBaseSymbol(*Rel.Symbol));
17295ffd83dbSDimitry Andric       uint32_t FunctionIndex = WasmIndices.find(Base)->second;
17300b57cec5SDimitry Andric       uint32_t TableIndex = TableElems.size() + InitialTableOffset;
17315ffd83dbSDimitry Andric       if (TableIndices.try_emplace(Base, TableIndex).second) {
17325ffd83dbSDimitry Andric         LLVM_DEBUG(dbgs() << "  -> adding " << Base->getName()
17330b57cec5SDimitry Andric                           << " to table: " << TableIndex << "\n");
17340b57cec5SDimitry Andric         TableElems.push_back(FunctionIndex);
17355ffd83dbSDimitry Andric         registerFunctionType(*Base);
17360b57cec5SDimitry Andric       }
17370b57cec5SDimitry Andric     };
17380b57cec5SDimitry Andric 
17390b57cec5SDimitry Andric     for (const WasmRelocationEntry &RelEntry : CodeRelocations)
17400b57cec5SDimitry Andric       HandleReloc(RelEntry);
17410b57cec5SDimitry Andric     for (const WasmRelocationEntry &RelEntry : DataRelocations)
17420b57cec5SDimitry Andric       HandleReloc(RelEntry);
17430b57cec5SDimitry Andric   }
17440b57cec5SDimitry Andric 
17450b57cec5SDimitry Andric   // Translate .init_array section contents into start functions.
17460b57cec5SDimitry Andric   for (const MCSection &S : Asm) {
17470b57cec5SDimitry Andric     const auto &WS = static_cast<const MCSectionWasm &>(S);
17485ffd83dbSDimitry Andric     if (WS.getName().startswith(".fini_array"))
17490b57cec5SDimitry Andric       report_fatal_error(".fini_array sections are unsupported");
17505ffd83dbSDimitry Andric     if (!WS.getName().startswith(".init_array"))
17510b57cec5SDimitry Andric       continue;
17520b57cec5SDimitry Andric     if (WS.getFragmentList().empty())
17530b57cec5SDimitry Andric       continue;
17540b57cec5SDimitry Andric 
17550b57cec5SDimitry Andric     // init_array is expected to contain a single non-empty data fragment
17560b57cec5SDimitry Andric     if (WS.getFragmentList().size() != 3)
17570b57cec5SDimitry Andric       report_fatal_error("only one .init_array section fragment supported");
17580b57cec5SDimitry Andric 
17590b57cec5SDimitry Andric     auto IT = WS.begin();
17600b57cec5SDimitry Andric     const MCFragment &EmptyFrag = *IT;
17610b57cec5SDimitry Andric     if (EmptyFrag.getKind() != MCFragment::FT_Data)
17620b57cec5SDimitry Andric       report_fatal_error(".init_array section should be aligned");
17630b57cec5SDimitry Andric 
17640b57cec5SDimitry Andric     IT = std::next(IT);
17650b57cec5SDimitry Andric     const MCFragment &AlignFrag = *IT;
17660b57cec5SDimitry Andric     if (AlignFrag.getKind() != MCFragment::FT_Align)
17670b57cec5SDimitry Andric       report_fatal_error(".init_array section should be aligned");
17680b57cec5SDimitry Andric     if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
17690b57cec5SDimitry Andric       report_fatal_error(".init_array section should be aligned for pointers");
17700b57cec5SDimitry Andric 
17710b57cec5SDimitry Andric     const MCFragment &Frag = *std::next(IT);
17720b57cec5SDimitry Andric     if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
17730b57cec5SDimitry Andric       report_fatal_error("only data supported in .init_array section");
17740b57cec5SDimitry Andric 
17750b57cec5SDimitry Andric     uint16_t Priority = UINT16_MAX;
17760b57cec5SDimitry Andric     unsigned PrefixLength = strlen(".init_array");
17775ffd83dbSDimitry Andric     if (WS.getName().size() > PrefixLength) {
17785ffd83dbSDimitry Andric       if (WS.getName()[PrefixLength] != '.')
17790b57cec5SDimitry Andric         report_fatal_error(
17800b57cec5SDimitry Andric             ".init_array section priority should start with '.'");
17815ffd83dbSDimitry Andric       if (WS.getName().substr(PrefixLength + 1).getAsInteger(10, Priority))
17820b57cec5SDimitry Andric         report_fatal_error("invalid .init_array section priority");
17830b57cec5SDimitry Andric     }
17840b57cec5SDimitry Andric     const auto &DataFrag = cast<MCDataFragment>(Frag);
17850b57cec5SDimitry Andric     const SmallVectorImpl<char> &Contents = DataFrag.getContents();
17860b57cec5SDimitry Andric     for (const uint8_t *
17870b57cec5SDimitry Andric              P = (const uint8_t *)Contents.data(),
17880b57cec5SDimitry Andric             *End = (const uint8_t *)Contents.data() + Contents.size();
17890b57cec5SDimitry Andric          P != End; ++P) {
17900b57cec5SDimitry Andric       if (*P != 0)
17910b57cec5SDimitry Andric         report_fatal_error("non-symbolic data in .init_array section");
17920b57cec5SDimitry Andric     }
17930b57cec5SDimitry Andric     for (const MCFixup &Fixup : DataFrag.getFixups()) {
17940b57cec5SDimitry Andric       assert(Fixup.getKind() ==
17950b57cec5SDimitry Andric              MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
17960b57cec5SDimitry Andric       const MCExpr *Expr = Fixup.getValue();
17970b57cec5SDimitry Andric       auto *SymRef = dyn_cast<MCSymbolRefExpr>(Expr);
17980b57cec5SDimitry Andric       if (!SymRef)
17990b57cec5SDimitry Andric         report_fatal_error("fixups in .init_array should be symbol references");
18000b57cec5SDimitry Andric       const auto &TargetSym = cast<const MCSymbolWasm>(SymRef->getSymbol());
18010b57cec5SDimitry Andric       if (TargetSym.getIndex() == InvalidIndex)
18025ffd83dbSDimitry Andric         report_fatal_error("symbols in .init_array should exist in symtab");
18030b57cec5SDimitry Andric       if (!TargetSym.isFunction())
18040b57cec5SDimitry Andric         report_fatal_error("symbols in .init_array should be for functions");
18050b57cec5SDimitry Andric       InitFuncs.push_back(
18060b57cec5SDimitry Andric           std::make_pair(Priority, TargetSym.getIndex()));
18070b57cec5SDimitry Andric     }
18080b57cec5SDimitry Andric   }
18090b57cec5SDimitry Andric 
18100b57cec5SDimitry Andric   // Write out the Wasm header.
18110b57cec5SDimitry Andric   writeHeader(Asm);
18120b57cec5SDimitry Andric 
1813e8d8bef9SDimitry Andric   uint32_t CodeSectionIndex, DataSectionIndex;
1814e8d8bef9SDimitry Andric   if (Mode != DwoMode::DwoOnly) {
18150b57cec5SDimitry Andric     writeTypeSection(Signatures);
18160b57cec5SDimitry Andric     writeImportSection(Imports, DataSize, TableElems.size());
18170b57cec5SDimitry Andric     writeFunctionSection(Functions);
1818e8d8bef9SDimitry Andric     writeTableSection(Tables);
18190b57cec5SDimitry Andric     // Skip the "memory" section; we import the memory instead.
18200b57cec5SDimitry Andric     writeEventSection(Events);
18215ffd83dbSDimitry Andric     writeGlobalSection(Globals);
18220b57cec5SDimitry Andric     writeExportSection(Exports);
18230b57cec5SDimitry Andric     writeElemSection(TableElems);
18240b57cec5SDimitry Andric     writeDataCountSection();
1825e8d8bef9SDimitry Andric 
1826e8d8bef9SDimitry Andric     CodeSectionIndex = writeCodeSection(Asm, Layout, Functions);
1827e8d8bef9SDimitry Andric     DataSectionIndex = writeDataSection(Layout);
1828e8d8bef9SDimitry Andric   }
1829e8d8bef9SDimitry Andric 
1830e8d8bef9SDimitry Andric   // The Sections in the COMDAT list have placeholder indices (their index among
1831e8d8bef9SDimitry Andric   // custom sections, rather than among all sections). Fix them up here.
1832e8d8bef9SDimitry Andric   for (auto &Group : Comdats) {
1833e8d8bef9SDimitry Andric     for (auto &Entry : Group.second) {
1834e8d8bef9SDimitry Andric       if (Entry.Kind == wasm::WASM_COMDAT_SECTION) {
1835e8d8bef9SDimitry Andric         Entry.Index += SectionCount;
1836e8d8bef9SDimitry Andric       }
1837e8d8bef9SDimitry Andric     }
1838e8d8bef9SDimitry Andric   }
18390b57cec5SDimitry Andric   for (auto &CustomSection : CustomSections)
18400b57cec5SDimitry Andric     writeCustomSection(CustomSection, Asm, Layout);
1841e8d8bef9SDimitry Andric 
1842e8d8bef9SDimitry Andric   if (Mode != DwoMode::DwoOnly) {
18430b57cec5SDimitry Andric     writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats);
1844e8d8bef9SDimitry Andric 
18450b57cec5SDimitry Andric     writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations);
18460b57cec5SDimitry Andric     writeRelocSection(DataSectionIndex, "DATA", DataRelocations);
1847e8d8bef9SDimitry Andric   }
18480b57cec5SDimitry Andric   writeCustomRelocSections();
18490b57cec5SDimitry Andric   if (ProducersSection)
18500b57cec5SDimitry Andric     writeCustomSection(*ProducersSection, Asm, Layout);
18510b57cec5SDimitry Andric   if (TargetFeaturesSection)
18520b57cec5SDimitry Andric     writeCustomSection(*TargetFeaturesSection, Asm, Layout);
18530b57cec5SDimitry Andric 
18540b57cec5SDimitry Andric   // TODO: Translate the .comment section to the output.
1855e8d8bef9SDimitry Andric   return W->OS.tell() - StartOffset;
18560b57cec5SDimitry Andric }
18570b57cec5SDimitry Andric 
18580b57cec5SDimitry Andric std::unique_ptr<MCObjectWriter>
18590b57cec5SDimitry Andric llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
18600b57cec5SDimitry Andric                              raw_pwrite_stream &OS) {
18618bcb0991SDimitry Andric   return std::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
18620b57cec5SDimitry Andric }
1863e8d8bef9SDimitry Andric 
1864e8d8bef9SDimitry Andric std::unique_ptr<MCObjectWriter>
1865e8d8bef9SDimitry Andric llvm::createWasmDwoObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
1866e8d8bef9SDimitry Andric                                 raw_pwrite_stream &OS,
1867e8d8bef9SDimitry Andric                                 raw_pwrite_stream &DwoOS) {
1868e8d8bef9SDimitry Andric   return std::make_unique<WasmObjectWriter>(std::move(MOTW), OS, DwoOS);
1869e8d8bef9SDimitry Andric }
1870