118eafb6cSDan Gohman //===- lib/MC/WasmObjectWriter.cpp - Wasm File Writer ---------------------===//
218eafb6cSDan Gohman //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
618eafb6cSDan Gohman //
718eafb6cSDan Gohman //===----------------------------------------------------------------------===//
818eafb6cSDan Gohman //
918eafb6cSDan Gohman // This file implements Wasm object file writer information.
1018eafb6cSDan Gohman //
1118eafb6cSDan Gohman //===----------------------------------------------------------------------===//
1218eafb6cSDan Gohman 
1318eafb6cSDan Gohman #include "llvm/ADT/STLExtras.h"
1418eafb6cSDan Gohman #include "llvm/ADT/SmallPtrSet.h"
15264b5d9eSZachary Turner #include "llvm/BinaryFormat/Wasm.h"
16432a3883SNico Weber #include "llvm/Config/llvm-config.h"
1718eafb6cSDan Gohman #include "llvm/MC/MCAsmBackend.h"
1818eafb6cSDan Gohman #include "llvm/MC/MCAsmLayout.h"
1918eafb6cSDan Gohman #include "llvm/MC/MCAssembler.h"
2018eafb6cSDan Gohman #include "llvm/MC/MCContext.h"
2118eafb6cSDan Gohman #include "llvm/MC/MCExpr.h"
2218eafb6cSDan Gohman #include "llvm/MC/MCFixupKindInfo.h"
2318eafb6cSDan Gohman #include "llvm/MC/MCObjectWriter.h"
2418eafb6cSDan Gohman #include "llvm/MC/MCSectionWasm.h"
2518eafb6cSDan Gohman #include "llvm/MC/MCSymbolWasm.h"
2618eafb6cSDan Gohman #include "llvm/MC/MCValue.h"
2718eafb6cSDan Gohman #include "llvm/MC/MCWasmObjectWriter.h"
28d934cb88SDan Gohman #include "llvm/Support/Casting.h"
2918eafb6cSDan Gohman #include "llvm/Support/Debug.h"
30bcd7f777SSimon Pilgrim #include "llvm/Support/EndianStream.h"
3118eafb6cSDan Gohman #include "llvm/Support/ErrorHandling.h"
32d934cb88SDan Gohman #include "llvm/Support/LEB128.h"
3318eafb6cSDan Gohman #include "llvm/Support/StringSaver.h"
3418eafb6cSDan Gohman #include <vector>
3518eafb6cSDan Gohman 
3618eafb6cSDan Gohman using namespace llvm;
3718eafb6cSDan Gohman 
385e3d33a7SSam Clegg #define DEBUG_TYPE "mc"
3918eafb6cSDan Gohman 
4018eafb6cSDan Gohman namespace {
419e15f359SSam Clegg 
4230e1bbc1SSam Clegg // Went we ceate the indirect function table we start at 1, so that there is
4330e1bbc1SSam Clegg // and emtpy slot at 0 and therefore calling a null function pointer will trap.
4418c56a07SHeejin Ahn static const uint32_t InitialTableOffset = 1;
4530e1bbc1SSam Clegg 
46d934cb88SDan Gohman // For patching purposes, we need to remember where each section starts, both
47d934cb88SDan Gohman // for patching up the section size field, and for patching up references to
48d934cb88SDan Gohman // locations within the section.
49d934cb88SDan Gohman struct SectionBookkeeping {
50d934cb88SDan Gohman   // Where the size of the section is written.
51d934cb88SDan Gohman   uint64_t SizeOffset;
526a31a0d6SSam Clegg   // Where the section header ends (without custom section name).
536a31a0d6SSam Clegg   uint64_t PayloadOffset;
546a31a0d6SSam Clegg   // Where the contents of the section starts.
55d934cb88SDan Gohman   uint64_t ContentsOffset;
566f08c84aSSam Clegg   uint32_t Index;
57d934cb88SDan Gohman };
58d934cb88SDan Gohman 
59da419bdbSHeejin Ahn // The signature of a wasm function or event, in a struct capable of being used
60da419bdbSHeejin Ahn // as a DenseMap key.
61da419bdbSHeejin Ahn // TODO: Consider using wasm::WasmSignature directly instead.
62da419bdbSHeejin Ahn struct WasmSignature {
639e15f359SSam Clegg   // Support empty and tombstone instances, needed by DenseMap.
6418c56a07SHeejin Ahn   enum { Plain, Empty, Tombstone } State = Plain;
659e15f359SSam Clegg 
669e15f359SSam Clegg   // The return types of the function.
679e15f359SSam Clegg   SmallVector<wasm::ValType, 1> Returns;
689e15f359SSam Clegg 
699e15f359SSam Clegg   // The parameter types of the function.
709e15f359SSam Clegg   SmallVector<wasm::ValType, 4> Params;
719e15f359SSam Clegg 
72da419bdbSHeejin Ahn   bool operator==(const WasmSignature &Other) const {
739e15f359SSam Clegg     return State == Other.State && Returns == Other.Returns &&
749e15f359SSam Clegg            Params == Other.Params;
759e15f359SSam Clegg   }
769e15f359SSam Clegg };
779e15f359SSam Clegg 
78da419bdbSHeejin Ahn // Traits for using WasmSignature in a DenseMap.
79da419bdbSHeejin Ahn struct WasmSignatureDenseMapInfo {
80da419bdbSHeejin Ahn   static WasmSignature getEmptyKey() {
81da419bdbSHeejin Ahn     WasmSignature Sig;
82da419bdbSHeejin Ahn     Sig.State = WasmSignature::Empty;
83da419bdbSHeejin Ahn     return Sig;
849e15f359SSam Clegg   }
85da419bdbSHeejin Ahn   static WasmSignature getTombstoneKey() {
86da419bdbSHeejin Ahn     WasmSignature Sig;
87da419bdbSHeejin Ahn     Sig.State = WasmSignature::Tombstone;
88da419bdbSHeejin Ahn     return Sig;
899e15f359SSam Clegg   }
90da419bdbSHeejin Ahn   static unsigned getHashValue(const WasmSignature &Sig) {
91da419bdbSHeejin Ahn     uintptr_t Value = Sig.State;
92da419bdbSHeejin Ahn     for (wasm::ValType Ret : Sig.Returns)
934808914aSHeejin Ahn       Value += DenseMapInfo<uint32_t>::getHashValue(uint32_t(Ret));
94da419bdbSHeejin Ahn     for (wasm::ValType Param : Sig.Params)
954808914aSHeejin Ahn       Value += DenseMapInfo<uint32_t>::getHashValue(uint32_t(Param));
969e15f359SSam Clegg     return Value;
979e15f359SSam Clegg   }
98da419bdbSHeejin Ahn   static bool isEqual(const WasmSignature &LHS, const WasmSignature &RHS) {
999e15f359SSam Clegg     return LHS == RHS;
1009e15f359SSam Clegg   }
1019e15f359SSam Clegg };
1029e15f359SSam Clegg 
1037c395943SSam Clegg // A wasm data segment.  A wasm binary contains only a single data section
1047c395943SSam Clegg // but that can contain many segments, each with their own virtual location
1057c395943SSam Clegg // in memory.  Each MCSection data created by llvm is modeled as its own
1067c395943SSam Clegg // wasm data segment.
1077c395943SSam Clegg struct WasmDataSegment {
1087c395943SSam Clegg   MCSectionWasm *Section;
109d95ed959SSam Clegg   StringRef Name;
1102e150409SThomas Lively   uint32_t InitFlags;
1114d135b04SWouter van Oortmerssen   uint64_t Offset;
11263ebb813SSam Clegg   uint32_t Alignment;
1132e150409SThomas Lively   uint32_t LinkerFlags;
1147c395943SSam Clegg   SmallVector<char, 4> Data;
1157c395943SSam Clegg };
1167c395943SSam Clegg 
1179e15f359SSam Clegg // A wasm function to be written into the function section.
1189e15f359SSam Clegg struct WasmFunction {
119da419bdbSHeejin Ahn   uint32_t SigIndex;
1209e15f359SSam Clegg   const MCSymbolWasm *Sym;
1219e15f359SSam Clegg };
1229e15f359SSam Clegg 
1239e15f359SSam Clegg // A wasm global to be written into the global section.
1249e15f359SSam Clegg struct WasmGlobal {
1256e7f1826SSam Clegg   wasm::WasmGlobalType Type;
1269e15f359SSam Clegg   uint64_t InitialValue;
1279e15f359SSam Clegg };
1289e15f359SSam Clegg 
129ea7caceeSSam Clegg // Information about a single item which is part of a COMDAT.  For each data
130ea7caceeSSam Clegg // segment or function which is in the COMDAT, there is a corresponding
131ea7caceeSSam Clegg // WasmComdatEntry.
132ea7caceeSSam Clegg struct WasmComdatEntry {
133ea7caceeSSam Clegg   unsigned Kind;
134ea7caceeSSam Clegg   uint32_t Index;
135ea7caceeSSam Clegg };
136ea7caceeSSam Clegg 
1376dc65e91SSam Clegg // Information about a single relocation.
1386dc65e91SSam Clegg struct WasmRelocationEntry {
1396dc65e91SSam Clegg   uint64_t Offset;                   // Where is the relocation.
1406dc65e91SSam Clegg   const MCSymbolWasm *Symbol;        // The symbol to relocate with.
1416dc65e91SSam Clegg   int64_t Addend;                    // A value to add to the symbol.
1426dc65e91SSam Clegg   unsigned Type;                     // The type of the relocation.
143fe6414b0SSam Clegg   const MCSectionWasm *FixupSection; // The section the relocation is targeting.
1446dc65e91SSam Clegg 
1456dc65e91SSam Clegg   WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol,
1466dc65e91SSam Clegg                       int64_t Addend, unsigned Type,
147fe6414b0SSam Clegg                       const MCSectionWasm *FixupSection)
1486dc65e91SSam Clegg       : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type),
1496dc65e91SSam Clegg         FixupSection(FixupSection) {}
1506dc65e91SSam Clegg 
151cadcb9ebSKeno Fischer   bool hasAddend() const { return wasm::relocTypeHasAddend(Type); }
152acd7d2b0SSam Clegg 
1536dc65e91SSam Clegg   void print(raw_ostream &Out) const {
154f208f631SHeejin Ahn     Out << wasm::relocTypetoString(Type) << " Off=" << Offset
155f208f631SHeejin Ahn         << ", Sym=" << *Symbol << ", Addend=" << Addend
1567d1ff446SFangrui Song         << ", FixupSection=" << FixupSection->getName();
1576dc65e91SSam Clegg   }
158b7787fd0SSam Clegg 
159615eb470SAaron Ballman #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
160b7787fd0SSam Clegg   LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
161b7787fd0SSam Clegg #endif
1626dc65e91SSam Clegg };
1636dc65e91SSam Clegg 
16418c56a07SHeejin Ahn static const uint32_t InvalidIndex = -1;
16525d8e68bSSam Clegg 
166cfd44a2eSSam Clegg struct WasmCustomSection {
167cfd44a2eSSam Clegg 
1686a31a0d6SSam Clegg   StringRef Name;
1696a31a0d6SSam Clegg   MCSectionWasm *Section;
1706a31a0d6SSam Clegg 
1716a31a0d6SSam Clegg   uint32_t OutputContentsOffset;
1726a31a0d6SSam Clegg   uint32_t OutputIndex;
1736a31a0d6SSam Clegg 
1746a31a0d6SSam Clegg   WasmCustomSection(StringRef Name, MCSectionWasm *Section)
1756a31a0d6SSam Clegg       : Name(Name), Section(Section), OutputContentsOffset(0),
17618c56a07SHeejin Ahn         OutputIndex(InvalidIndex) {}
177cfd44a2eSSam Clegg };
178cfd44a2eSSam Clegg 
1791fb8daa6SSam Clegg #if !defined(NDEBUG)
1807f055deeSSam Clegg raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
181b7787fd0SSam Clegg   Rel.print(OS);
182b7787fd0SSam Clegg   return OS;
183b7787fd0SSam Clegg }
1841fb8daa6SSam Clegg #endif
185b7787fd0SSam Clegg 
18619e8befaSSam Clegg // Write X as an (unsigned) LEB value at offset Offset in Stream, padded
18719e8befaSSam Clegg // to allow patching.
1883b29376eSWouter van Oortmerssen template <int W>
1893b29376eSWouter van Oortmerssen void writePatchableLEB(raw_pwrite_stream &Stream, uint64_t X, uint64_t Offset) {
1903b29376eSWouter van Oortmerssen   uint8_t Buffer[W];
1913b29376eSWouter van Oortmerssen   unsigned SizeLen = encodeULEB128(X, Buffer, W);
1923b29376eSWouter van Oortmerssen   assert(SizeLen == W);
19319e8befaSSam Clegg   Stream.pwrite((char *)Buffer, SizeLen, Offset);
19419e8befaSSam Clegg }
19519e8befaSSam Clegg 
19619e8befaSSam Clegg // Write X as an signed LEB value at offset Offset in Stream, padded
19719e8befaSSam Clegg // to allow patching.
1983b29376eSWouter van Oortmerssen template <int W>
1993b29376eSWouter van Oortmerssen void writePatchableSLEB(raw_pwrite_stream &Stream, int64_t X, uint64_t Offset) {
2003b29376eSWouter van Oortmerssen   uint8_t Buffer[W];
2013b29376eSWouter van Oortmerssen   unsigned SizeLen = encodeSLEB128(X, Buffer, W);
2023b29376eSWouter van Oortmerssen   assert(SizeLen == W);
20319e8befaSSam Clegg   Stream.pwrite((char *)Buffer, SizeLen, Offset);
20419e8befaSSam Clegg }
20519e8befaSSam Clegg 
20619e8befaSSam Clegg // Write X as a plain integer value at offset Offset in Stream.
2070a6c4d8dSSam Clegg static void patchI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
20819e8befaSSam Clegg   uint8_t Buffer[4];
20919e8befaSSam Clegg   support::endian::write32le(Buffer, X);
21019e8befaSSam Clegg   Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
21119e8befaSSam Clegg }
21219e8befaSSam Clegg 
2133b29376eSWouter van Oortmerssen static void patchI64(raw_pwrite_stream &Stream, uint64_t X, uint64_t Offset) {
2143b29376eSWouter van Oortmerssen   uint8_t Buffer[8];
2153b29376eSWouter van Oortmerssen   support::endian::write64le(Buffer, X);
2163b29376eSWouter van Oortmerssen   Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
2173b29376eSWouter van Oortmerssen }
2183b29376eSWouter van Oortmerssen 
2190ff28fa6SDerek Schuff bool isDwoSection(const MCSection &Sec) {
2200ff28fa6SDerek Schuff   return Sec.getName().endswith(".dwo");
2210ff28fa6SDerek Schuff }
2220ff28fa6SDerek Schuff 
22318eafb6cSDan Gohman class WasmObjectWriter : public MCObjectWriter {
2240ff28fa6SDerek Schuff   support::endian::Writer *W;
225f17b149dSPeter Collingbourne 
22618eafb6cSDan Gohman   /// The target specific Wasm writer instance.
22718eafb6cSDan Gohman   std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
22818eafb6cSDan Gohman 
229d934cb88SDan Gohman   // Relocations for fixing up references in the code section.
230d934cb88SDan Gohman   std::vector<WasmRelocationEntry> CodeRelocations;
231d934cb88SDan Gohman   // Relocations for fixing up references in the data section.
232d934cb88SDan Gohman   std::vector<WasmRelocationEntry> DataRelocations;
233d934cb88SDan Gohman 
234d934cb88SDan Gohman   // Index values to use for fixing up call_indirect type indices.
235acd7d2b0SSam Clegg   // Maps function symbols to the index of the type of the function
236acd7d2b0SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
237d99f6078SSam Clegg   // Maps function symbols to the table element index space. Used
238d99f6078SSam Clegg   // for TABLE_INDEX relocation types (i.e. address taken functions).
239f9edbe95SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> TableIndices;
240da419bdbSHeejin Ahn   // Maps function/global symbols to the function/global/event/section index
241da419bdbSHeejin Ahn   // space.
2426c899ba6SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> WasmIndices;
243492f7529SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> GOTIndices;
2446c899ba6SSam Clegg   // Maps data symbols to the Wasm segment and offset/size with the segment.
2456c899ba6SSam Clegg   DenseMap<const MCSymbolWasm *, wasm::WasmDataReference> DataLocations;
2466a31a0d6SSam Clegg 
2476a31a0d6SSam Clegg   // Stores output data (index, relocations, content offset) for custom
2486a31a0d6SSam Clegg   // section.
2496a31a0d6SSam Clegg   std::vector<WasmCustomSection> CustomSections;
250cbda16ebSThomas Lively   std::unique_ptr<WasmCustomSection> ProducersSection;
251f6f4f843SThomas Lively   std::unique_ptr<WasmCustomSection> TargetFeaturesSection;
2526a31a0d6SSam Clegg   // Relocations for fixing up references in the custom sections.
2536a31a0d6SSam Clegg   DenseMap<const MCSectionWasm *, std::vector<WasmRelocationEntry>>
2546a31a0d6SSam Clegg       CustomSectionsRelocations;
255acd7d2b0SSam Clegg 
256c0d41195SSam Clegg   // Map from section to defining function symbol.
2576ccb59b3SSam Clegg   DenseMap<const MCSection *, const MCSymbol *> SectionFunctions;
2586ccb59b3SSam Clegg 
259da419bdbSHeejin Ahn   DenseMap<WasmSignature, uint32_t, WasmSignatureDenseMapInfo> SignatureIndices;
260da419bdbSHeejin Ahn   SmallVector<WasmSignature, 4> Signatures;
2616c899ba6SSam Clegg   SmallVector<WasmDataSegment, 4> DataSegments;
2629f3fe42eSSam Clegg   unsigned NumFunctionImports = 0;
2637c395943SSam Clegg   unsigned NumGlobalImports = 0;
264da419bdbSHeejin Ahn   unsigned NumEventImports = 0;
2657e1c3345SChandler Carruth   uint32_t SectionCount = 0;
266d934cb88SDan Gohman 
2670ff28fa6SDerek Schuff   enum class DwoMode {
2680ff28fa6SDerek Schuff     AllSections,
2690ff28fa6SDerek Schuff     NonDwoOnly,
2700ff28fa6SDerek Schuff     DwoOnly,
2710ff28fa6SDerek Schuff   };
2720ff28fa6SDerek Schuff   bool IsSplitDwarf = false;
2730ff28fa6SDerek Schuff   raw_pwrite_stream *OS = nullptr;
2740ff28fa6SDerek Schuff   raw_pwrite_stream *DwoOS = nullptr;
2750ff28fa6SDerek Schuff 
2760ff28fa6SDerek Schuff   // TargetObjectWriter wranppers.
27718eafb6cSDan Gohman   bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
278da84b688SDan Gohman   bool isEmscripten() const { return TargetObjectWriter->isEmscripten(); }
27918eafb6cSDan Gohman 
2802322a937SSam Clegg   void startSection(SectionBookkeeping &Section, unsigned SectionId);
2812322a937SSam Clegg   void startCustomSection(SectionBookkeeping &Section, StringRef Name);
282d934cb88SDan Gohman   void endSection(SectionBookkeeping &Section);
283d934cb88SDan Gohman 
28418eafb6cSDan Gohman public:
2851301a878SLang Hames   WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
2860ff28fa6SDerek Schuff                    raw_pwrite_stream &OS_)
2870ff28fa6SDerek Schuff       : TargetObjectWriter(std::move(MOTW)), OS(&OS_) {}
2880ff28fa6SDerek Schuff 
2890ff28fa6SDerek Schuff   WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
2900ff28fa6SDerek Schuff                    raw_pwrite_stream &OS_, raw_pwrite_stream &DwoOS_)
2910ff28fa6SDerek Schuff       : TargetObjectWriter(std::move(MOTW)), IsSplitDwarf(true), OS(&OS_),
2920ff28fa6SDerek Schuff         DwoOS(&DwoOS_) {}
29318eafb6cSDan Gohman 
2940917c9e4SDan Gohman private:
295acd7d2b0SSam Clegg   void reset() override {
296acd7d2b0SSam Clegg     CodeRelocations.clear();
297acd7d2b0SSam Clegg     DataRelocations.clear();
298acd7d2b0SSam Clegg     TypeIndices.clear();
2996c899ba6SSam Clegg     WasmIndices.clear();
300492f7529SSam Clegg     GOTIndices.clear();
301f9edbe95SSam Clegg     TableIndices.clear();
3026c899ba6SSam Clegg     DataLocations.clear();
303cbda16ebSThomas Lively     CustomSections.clear();
304cbda16ebSThomas Lively     ProducersSection.reset();
305f6f4f843SThomas Lively     TargetFeaturesSection.reset();
3066a31a0d6SSam Clegg     CustomSectionsRelocations.clear();
307da419bdbSHeejin Ahn     SignatureIndices.clear();
308da419bdbSHeejin Ahn     Signatures.clear();
3096c899ba6SSam Clegg     DataSegments.clear();
3106ccb59b3SSam Clegg     SectionFunctions.clear();
3119f3fe42eSSam Clegg     NumFunctionImports = 0;
3127c395943SSam Clegg     NumGlobalImports = 0;
313105bdc25SSam Clegg     MCObjectWriter::reset();
314acd7d2b0SSam Clegg   }
315acd7d2b0SSam Clegg 
31618eafb6cSDan Gohman   void writeHeader(const MCAssembler &Asm);
31718eafb6cSDan Gohman 
31818eafb6cSDan Gohman   void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
31918eafb6cSDan Gohman                         const MCFragment *Fragment, const MCFixup &Fixup,
320ceecfe5bSRafael Espindola                         MCValue Target, uint64_t &FixedValue) override;
32118eafb6cSDan Gohman 
32218eafb6cSDan Gohman   void executePostLayoutBinding(MCAssembler &Asm,
32318eafb6cSDan Gohman                                 const MCAsmLayout &Layout) override;
3240ff28fa6SDerek Schuff   void prepareImports(SmallVectorImpl<wasm::WasmImport> &Imports,
3250ff28fa6SDerek Schuff                       MCAssembler &Asm, const MCAsmLayout &Layout);
326438390faSPeter Collingbourne   uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
3279e15f359SSam Clegg 
3280ff28fa6SDerek Schuff   uint64_t writeOneObject(MCAssembler &Asm, const MCAsmLayout &Layout,
3290ff28fa6SDerek Schuff                           DwoMode Mode);
3300ff28fa6SDerek Schuff 
331b7787fd0SSam Clegg   void writeString(const StringRef Str) {
3320ff28fa6SDerek Schuff     encodeULEB128(Str.size(), W->OS);
3330ff28fa6SDerek Schuff     W->OS << Str;
334b7787fd0SSam Clegg   }
335b7787fd0SSam Clegg 
3360a6c4d8dSSam Clegg   void writeI32(int32_t val) {
3370a6c4d8dSSam Clegg     char Buffer[4];
3380a6c4d8dSSam Clegg     support::endian::write32le(Buffer, val);
3390ff28fa6SDerek Schuff     W->OS.write(Buffer, sizeof(Buffer));
3400a6c4d8dSSam Clegg   }
3410a6c4d8dSSam Clegg 
3420a6c4d8dSSam Clegg   void writeI64(int64_t val) {
3430a6c4d8dSSam Clegg     char Buffer[8];
3440a6c4d8dSSam Clegg     support::endian::write64le(Buffer, val);
3450ff28fa6SDerek Schuff     W->OS.write(Buffer, sizeof(Buffer));
3460a6c4d8dSSam Clegg   }
3470a6c4d8dSSam Clegg 
3480ff28fa6SDerek Schuff   void writeValueType(wasm::ValType Ty) { W->OS << static_cast<char>(Ty); }
3499e15f359SSam Clegg 
350da419bdbSHeejin Ahn   void writeTypeSection(ArrayRef<WasmSignature> Signatures);
3514d135b04SWouter van Oortmerssen   void writeImportSection(ArrayRef<wasm::WasmImport> Imports, uint64_t DataSize,
352f950b24aSSam Clegg                           uint32_t NumElements);
353457fb0b4SSam Clegg   void writeFunctionSection(ArrayRef<WasmFunction> Functions);
3548defa952SSam Clegg   void writeExportSection(ArrayRef<wasm::WasmExport> Exports);
355457fb0b4SSam Clegg   void writeElemSection(ArrayRef<uint32_t> TableElems);
356fef8de66SThomas Lively   void writeDataCountSection();
357e49584a3SSam Clegg   uint32_t writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
358457fb0b4SSam Clegg                             ArrayRef<WasmFunction> Functions);
359e49584a3SSam Clegg   uint32_t writeDataSection(const MCAsmLayout &Layout);
360da419bdbSHeejin Ahn   void writeEventSection(ArrayRef<wasm::WasmEventType> Events);
3610a6c4d8dSSam Clegg   void writeGlobalSection(ArrayRef<wasm::WasmGlobal> Globals);
3626f08c84aSSam Clegg   void writeRelocSection(uint32_t SectionIndex, StringRef Name,
363f77dc2a8SSam Clegg                          std::vector<WasmRelocationEntry> &Relocations);
36431a2c809SSam Clegg   void writeLinkingMetaDataSection(
36586b4a09aSSam Clegg       ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
366ea7caceeSSam Clegg       ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
367ea7caceeSSam Clegg       const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats);
368cbda16ebSThomas Lively   void writeCustomSection(WasmCustomSection &CustomSection,
369cbda16ebSThomas Lively                           const MCAssembler &Asm, const MCAsmLayout &Layout);
3706a31a0d6SSam Clegg   void writeCustomRelocSections();
3716a31a0d6SSam Clegg   void
3726a31a0d6SSam Clegg   updateCustomSectionRelocations(const SmallVector<WasmFunction, 4> &Functions,
3736a31a0d6SSam Clegg                                  const MCAsmLayout &Layout);
374acd7d2b0SSam Clegg 
3757ee758d6SSam Clegg   uint64_t getProvisionalValue(const WasmRelocationEntry &RelEntry,
3767ee758d6SSam Clegg                                const MCAsmLayout &Layout);
377acd7d2b0SSam Clegg   void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
3787ee758d6SSam Clegg                         uint64_t ContentsOffset, const MCAsmLayout &Layout);
379acd7d2b0SSam Clegg 
380acd7d2b0SSam Clegg   uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
3815e3d33a7SSam Clegg   uint32_t getFunctionType(const MCSymbolWasm &Symbol);
382da419bdbSHeejin Ahn   uint32_t getEventType(const MCSymbolWasm &Symbol);
38338b12f5eSHeejin Ahn   void registerFunctionType(const MCSymbolWasm &Symbol);
38438b12f5eSHeejin Ahn   void registerEventType(const MCSymbolWasm &Symbol);
38518eafb6cSDan Gohman };
3869e15f359SSam Clegg 
38718eafb6cSDan Gohman } // end anonymous namespace
38818eafb6cSDan Gohman 
389d934cb88SDan Gohman // Write out a section header and a patchable section size field.
390d934cb88SDan Gohman void WasmObjectWriter::startSection(SectionBookkeeping &Section,
3912322a937SSam Clegg                                     unsigned SectionId) {
392d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "startSection " << SectionId << "\n");
3930ff28fa6SDerek Schuff   W->OS << char(SectionId);
394d934cb88SDan Gohman 
3950ff28fa6SDerek Schuff   Section.SizeOffset = W->OS.tell();
396d934cb88SDan Gohman 
397d934cb88SDan Gohman   // The section size. We don't know the size yet, so reserve enough space
398d934cb88SDan Gohman   // for any 32-bit value; we'll patch it later.
3990ff28fa6SDerek Schuff   encodeULEB128(0, W->OS, 5);
400d934cb88SDan Gohman 
401d934cb88SDan Gohman   // The position where the section starts, for measuring its size.
4020ff28fa6SDerek Schuff   Section.ContentsOffset = W->OS.tell();
4030ff28fa6SDerek Schuff   Section.PayloadOffset = W->OS.tell();
4046f08c84aSSam Clegg   Section.Index = SectionCount++;
405d934cb88SDan Gohman }
4062322a937SSam Clegg 
4072322a937SSam Clegg void WasmObjectWriter::startCustomSection(SectionBookkeeping &Section,
4082322a937SSam Clegg                                           StringRef Name) {
409d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "startCustomSection " << Name << "\n");
4102322a937SSam Clegg   startSection(Section, wasm::WASM_SEC_CUSTOM);
4116a31a0d6SSam Clegg 
4126a31a0d6SSam Clegg   // The position where the section header ends, for measuring its size.
4130ff28fa6SDerek Schuff   Section.PayloadOffset = W->OS.tell();
4146a31a0d6SSam Clegg 
4152322a937SSam Clegg   // Custom sections in wasm also have a string identifier.
4162322a937SSam Clegg   writeString(Name);
4176a31a0d6SSam Clegg 
4186a31a0d6SSam Clegg   // The position where the custom section starts.
4190ff28fa6SDerek Schuff   Section.ContentsOffset = W->OS.tell();
420d934cb88SDan Gohman }
421d934cb88SDan Gohman 
422d934cb88SDan Gohman // Now that the section is complete and we know how big it is, patch up the
423d934cb88SDan Gohman // section size field at the start of the section.
424d934cb88SDan Gohman void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
4250ff28fa6SDerek Schuff   uint64_t Size = W->OS.tell();
426c0affde8SSam Clegg   // /dev/null doesn't support seek/tell and can report offset of 0.
427c0affde8SSam Clegg   // Simply skip this patching in that case.
428c0affde8SSam Clegg   if (!Size)
429c0affde8SSam Clegg     return;
430c0affde8SSam Clegg 
431c0affde8SSam Clegg   Size -= Section.PayloadOffset;
432d934cb88SDan Gohman   if (uint32_t(Size) != Size)
433d934cb88SDan Gohman     report_fatal_error("section size does not fit in a uint32_t");
434d934cb88SDan Gohman 
435d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "endSection size=" << Size << "\n");
436d934cb88SDan Gohman 
437d934cb88SDan Gohman   // Write the final section size to the payload_len field, which follows
438d934cb88SDan Gohman   // the section id byte.
4390ff28fa6SDerek Schuff   writePatchableLEB<5>(static_cast<raw_pwrite_stream &>(W->OS), Size,
440f17b149dSPeter Collingbourne                        Section.SizeOffset);
441d934cb88SDan Gohman }
442d934cb88SDan Gohman 
44318eafb6cSDan Gohman // Emit the Wasm header.
44418eafb6cSDan Gohman void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
4450ff28fa6SDerek Schuff   W->OS.write(wasm::WasmMagic, sizeof(wasm::WasmMagic));
4460ff28fa6SDerek Schuff   W->write<uint32_t>(wasm::WasmVersion);
44718eafb6cSDan Gohman }
44818eafb6cSDan Gohman 
44918eafb6cSDan Gohman void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
45018eafb6cSDan Gohman                                                 const MCAsmLayout &Layout) {
4516ccb59b3SSam Clegg   // Build a map of sections to the function that defines them, for use
4526ccb59b3SSam Clegg   // in recordRelocation.
4536ccb59b3SSam Clegg   for (const MCSymbol &S : Asm.symbols()) {
4546ccb59b3SSam Clegg     const auto &WS = static_cast<const MCSymbolWasm &>(S);
4556ccb59b3SSam Clegg     if (WS.isDefined() && WS.isFunction() && !WS.isVariable()) {
4566ccb59b3SSam Clegg       const auto &Sec = static_cast<const MCSectionWasm &>(S.getSection());
4576ccb59b3SSam Clegg       auto Pair = SectionFunctions.insert(std::make_pair(&Sec, &S));
4586ccb59b3SSam Clegg       if (!Pair.second)
4596ccb59b3SSam Clegg         report_fatal_error("section already has a defining function: " +
4607d1ff446SFangrui Song                            Sec.getName());
4616ccb59b3SSam Clegg     }
4626ccb59b3SSam Clegg   }
46318eafb6cSDan Gohman }
46418eafb6cSDan Gohman 
46518eafb6cSDan Gohman void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
46618eafb6cSDan Gohman                                         const MCAsmLayout &Layout,
46718eafb6cSDan Gohman                                         const MCFragment *Fragment,
46818eafb6cSDan Gohman                                         const MCFixup &Fixup, MCValue Target,
469ceecfe5bSRafael Espindola                                         uint64_t &FixedValue) {
470ecc5e808SSam Clegg   // The WebAssembly backend should never generate FKF_IsPCRel fixups
471e828ce1bSFangrui Song   assert(!(Asm.getBackend().getFixupKindInfo(Fixup.getKind()).Flags &
472ecc5e808SSam Clegg            MCFixupKindInfo::FKF_IsPCRel));
473ecc5e808SSam Clegg 
474fe6414b0SSam Clegg   const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
475d934cb88SDan Gohman   uint64_t C = Target.getConstant();
476d934cb88SDan Gohman   uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
477d934cb88SDan Gohman   MCContext &Ctx = Asm.getContext();
478d934cb88SDan Gohman 
479d934cb88SDan Gohman   if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
480ecc5e808SSam Clegg     // To get here the A - B expression must have failed evaluateAsRelocatable.
481ecc5e808SSam Clegg     // This means either A or B must be undefined and in WebAssembly we can't
482ecc5e808SSam Clegg     // support either of those cases.
483ecc5e808SSam Clegg     const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
484d934cb88SDan Gohman     Ctx.reportError(
485d934cb88SDan Gohman         Fixup.getLoc(),
486d934cb88SDan Gohman         Twine("symbol '") + SymB.getName() +
487ecc5e808SSam Clegg             "': unsupported subtraction expression used in relocation.");
488d934cb88SDan Gohman     return;
489d934cb88SDan Gohman   }
490d934cb88SDan Gohman 
491d934cb88SDan Gohman   // We either rejected the fixup or folded B into C at this point.
492d934cb88SDan Gohman   const MCSymbolRefExpr *RefA = Target.getSymA();
493ecc5e808SSam Clegg   const auto *SymA = cast<MCSymbolWasm>(&RefA->getSymbol());
494d934cb88SDan Gohman 
4953ea1c62cSSam Clegg   // The .init_array isn't translated as data, so don't do relocations in it.
4967d1ff446SFangrui Song   if (FixupSection.getName().startswith(".init_array")) {
4973ea1c62cSSam Clegg     SymA->setUsedInInitArray();
4983ea1c62cSSam Clegg     return;
4993ea1c62cSSam Clegg   }
5003ea1c62cSSam Clegg 
501ecc5e808SSam Clegg   if (SymA->isVariable()) {
502d934cb88SDan Gohman     const MCExpr *Expr = SymA->getVariableValue();
5037ee758d6SSam Clegg     if (const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr))
5046ad8f190SSam Clegg       if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
5056ad8f190SSam Clegg         llvm_unreachable("weakref used in reloc not yet implemented");
506d934cb88SDan Gohman   }
507d934cb88SDan Gohman 
508d934cb88SDan Gohman   // Put any constant offset in an addend. Offsets can be negative, and
509d934cb88SDan Gohman   // LLVM expects wrapping, in contrast to wasm's immediates which can't
510d934cb88SDan Gohman   // be negative and don't wrap.
511d934cb88SDan Gohman   FixedValue = 0;
512d934cb88SDan Gohman 
513a5e175c6SSam Clegg   unsigned Type = TargetObjectWriter->getRelocType(Target, Fixup);
5149d24fb7fSSam Clegg 
5154d57fbd0SSam Clegg   // Absolute offset within a section or a function.
5164d57fbd0SSam Clegg   // Currently only supported for for metadata sections.
5174d57fbd0SSam Clegg   // See: test/MC/WebAssembly/blockaddress.ll
518d1152a26SSam Clegg   if (Type == wasm::R_WASM_FUNCTION_OFFSET_I32 ||
519d1152a26SSam Clegg       Type == wasm::R_WASM_SECTION_OFFSET_I32) {
5204d57fbd0SSam Clegg     if (!FixupSection.getKind().isMetadata())
5214d57fbd0SSam Clegg       report_fatal_error("relocations for function or section offsets are "
5224d57fbd0SSam Clegg                          "only supported in metadata sections");
5234d57fbd0SSam Clegg 
5244d57fbd0SSam Clegg     const MCSymbol *SectionSymbol = nullptr;
5254d57fbd0SSam Clegg     const MCSection &SecA = SymA->getSection();
5264d57fbd0SSam Clegg     if (SecA.getKind().isText())
5276ccb59b3SSam Clegg       SectionSymbol = SectionFunctions.find(&SecA)->second;
5284d57fbd0SSam Clegg     else
5294d57fbd0SSam Clegg       SectionSymbol = SecA.getBeginSymbol();
5304d57fbd0SSam Clegg     if (!SectionSymbol)
5314d57fbd0SSam Clegg       report_fatal_error("section symbol is required for relocation");
5324d57fbd0SSam Clegg 
5334d57fbd0SSam Clegg     C += Layout.getSymbolOffset(*SymA);
5344d57fbd0SSam Clegg     SymA = cast<MCSymbolWasm>(SectionSymbol);
5354d57fbd0SSam Clegg   }
5364d57fbd0SSam Clegg 
537d1152a26SSam Clegg   // Relocation other than R_WASM_TYPE_INDEX_LEB are required to be
5384d57fbd0SSam Clegg   // against a named symbol.
539d1152a26SSam Clegg   if (Type != wasm::R_WASM_TYPE_INDEX_LEB) {
5404d57fbd0SSam Clegg     if (SymA->getName().empty())
5414d57fbd0SSam Clegg       report_fatal_error("relocations against un-named temporaries are not yet "
5424d57fbd0SSam Clegg                          "supported by wasm");
5434d57fbd0SSam Clegg 
5444d57fbd0SSam Clegg     SymA->setUsedInReloc();
5454d57fbd0SSam Clegg   }
546ae03c1e7SSam Clegg 
547492f7529SSam Clegg   if (RefA->getKind() == MCSymbolRefExpr::VK_GOT)
548492f7529SSam Clegg     SymA->setUsedInGOT();
549492f7529SSam Clegg 
550d934cb88SDan Gohman   WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
551d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
552d934cb88SDan Gohman 
5536a31a0d6SSam Clegg   if (FixupSection.isWasmData()) {
554d934cb88SDan Gohman     DataRelocations.push_back(Rec);
5556a31a0d6SSam Clegg   } else if (FixupSection.getKind().isText()) {
55612fd3da9SSam Clegg     CodeRelocations.push_back(Rec);
5576a31a0d6SSam Clegg   } else if (FixupSection.getKind().isMetadata()) {
5586a31a0d6SSam Clegg     CustomSectionsRelocations[&FixupSection].push_back(Rec);
5596a31a0d6SSam Clegg   } else {
56012fd3da9SSam Clegg     llvm_unreachable("unexpected section type");
561d934cb88SDan Gohman   }
5626a31a0d6SSam Clegg }
563d934cb88SDan Gohman 
564d934cb88SDan Gohman // Compute a value to write into the code at the location covered
56560ec3034SSam Clegg // by RelEntry. This value isn't used by the static linker; it just serves
56660ec3034SSam Clegg // to make the object format more readable and more likely to be directly
56760ec3034SSam Clegg // useable.
5683b29376eSWouter van Oortmerssen uint64_t
5697ee758d6SSam Clegg WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry,
5707ee758d6SSam Clegg                                       const MCAsmLayout &Layout) {
57148139ebcSWouter van Oortmerssen   if ((RelEntry.Type == wasm::R_WASM_GLOBAL_INDEX_LEB ||
57248139ebcSWouter van Oortmerssen        RelEntry.Type == wasm::R_WASM_GLOBAL_INDEX_I32) &&
57348139ebcSWouter van Oortmerssen       !RelEntry.Symbol->isGlobal()) {
574492f7529SSam Clegg     assert(GOTIndices.count(RelEntry.Symbol) > 0 && "symbol not found in GOT index space");
575492f7529SSam Clegg     return GOTIndices[RelEntry.Symbol];
576492f7529SSam Clegg   }
577492f7529SSam Clegg 
57860ec3034SSam Clegg   switch (RelEntry.Type) {
5792a7cac93SSam Clegg   case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
580d1152a26SSam Clegg   case wasm::R_WASM_TABLE_INDEX_SLEB:
581cc1b9b68SWouter van Oortmerssen   case wasm::R_WASM_TABLE_INDEX_SLEB64:
582cc1b9b68SWouter van Oortmerssen   case wasm::R_WASM_TABLE_INDEX_I32:
583cc1b9b68SWouter van Oortmerssen   case wasm::R_WASM_TABLE_INDEX_I64: {
584f9edbe95SSam Clegg     // Provisional value is table address of the resolved symbol itself
5857ee758d6SSam Clegg     const MCSymbolWasm *Base =
5867ee758d6SSam Clegg         cast<MCSymbolWasm>(Layout.getBaseSymbol(*RelEntry.Symbol));
5877ee758d6SSam Clegg     assert(Base->isFunction());
58881443ac1SSam Clegg     if (RelEntry.Type == wasm::R_WASM_TABLE_INDEX_REL_SLEB)
5897ee758d6SSam Clegg       return TableIndices[Base] - InitialTableOffset;
59081443ac1SSam Clegg     else
5917ee758d6SSam Clegg       return TableIndices[Base];
592f9edbe95SSam Clegg   }
593d1152a26SSam Clegg   case wasm::R_WASM_TYPE_INDEX_LEB:
5946c899ba6SSam Clegg     // Provisional value is same as the index
59560ec3034SSam Clegg     return getRelocationIndexValue(RelEntry);
596d1152a26SSam Clegg   case wasm::R_WASM_FUNCTION_INDEX_LEB:
597d1152a26SSam Clegg   case wasm::R_WASM_GLOBAL_INDEX_LEB:
59848139ebcSWouter van Oortmerssen   case wasm::R_WASM_GLOBAL_INDEX_I32:
599d1152a26SSam Clegg   case wasm::R_WASM_EVENT_INDEX_LEB:
600da419bdbSHeejin Ahn     // Provisional value is function/global/event Wasm index
601492f7529SSam Clegg     assert(WasmIndices.count(RelEntry.Symbol) > 0 && "symbol not found in wasm index space");
6026c899ba6SSam Clegg     return WasmIndices[RelEntry.Symbol];
603d1152a26SSam Clegg   case wasm::R_WASM_FUNCTION_OFFSET_I32:
604d1152a26SSam Clegg   case wasm::R_WASM_SECTION_OFFSET_I32: {
6056a31a0d6SSam Clegg     const auto &Section =
6066a31a0d6SSam Clegg         static_cast<const MCSectionWasm &>(RelEntry.Symbol->getSection());
6076a31a0d6SSam Clegg     return Section.getSectionOffset() + RelEntry.Addend;
6086a31a0d6SSam Clegg   }
609d1152a26SSam Clegg   case wasm::R_WASM_MEMORY_ADDR_LEB:
6103b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_LEB64:
6113b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_SLEB:
6123b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_SLEB64:
6132a7cac93SSam Clegg   case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
6143b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_REL_SLEB64:
6153b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_I32:
6163b29376eSWouter van Oortmerssen   case wasm::R_WASM_MEMORY_ADDR_I64: {
617*9c7b5808SDominic Chen     // Provisional value is address of the global plus the offset
6187ee758d6SSam Clegg     const MCSymbolWasm *Base =
6197ee758d6SSam Clegg         cast<MCSymbolWasm>(Layout.getBaseSymbol(*RelEntry.Symbol));
620270ed1b3SSam Clegg     // For undefined symbols, use zero
6217ee758d6SSam Clegg     if (!Base->isDefined())
622270ed1b3SSam Clegg       return 0;
623*9c7b5808SDominic Chen     const wasm::WasmDataReference &BaseRef = DataLocations[Base],
624*9c7b5808SDominic Chen                                   &SymRef = DataLocations[RelEntry.Symbol];
625*9c7b5808SDominic Chen     const WasmDataSegment &Segment = DataSegments[BaseRef.Segment];
626d934cb88SDan Gohman     // Ignore overflow. LLVM allows address arithmetic to silently wrap.
627*9c7b5808SDominic Chen     return Segment.Offset + BaseRef.Offset + SymRef.Offset + RelEntry.Addend;
62860ec3034SSam Clegg   }
62960ec3034SSam Clegg   default:
63060ec3034SSam Clegg     llvm_unreachable("invalid relocation type");
63160ec3034SSam Clegg   }
632d934cb88SDan Gohman }
633d934cb88SDan Gohman 
634759631c7SSam Clegg static void addData(SmallVectorImpl<char> &DataBytes,
63563ebb813SSam Clegg                     MCSectionWasm &DataSection) {
6367d1ff446SFangrui Song   LLVM_DEBUG(errs() << "addData: " << DataSection.getName() << "\n");
637759631c7SSam Clegg 
63863ebb813SSam Clegg   DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
63963ebb813SSam Clegg 
640759631c7SSam Clegg   for (const MCFragment &Frag : DataSection) {
641759631c7SSam Clegg     if (Frag.hasInstructions())
642759631c7SSam Clegg       report_fatal_error("only data supported in data sections");
643759631c7SSam Clegg 
644759631c7SSam Clegg     if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
645759631c7SSam Clegg       if (Align->getValueSize() != 1)
646759631c7SSam Clegg         report_fatal_error("only byte values supported for alignment");
647759631c7SSam Clegg       // If nops are requested, use zeros, as this is the data section.
648759631c7SSam Clegg       uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
649f208f631SHeejin Ahn       uint64_t Size =
650f208f631SHeejin Ahn           std::min<uint64_t>(alignTo(DataBytes.size(), Align->getAlignment()),
651f208f631SHeejin Ahn                              DataBytes.size() + Align->getMaxBytesToEmit());
652759631c7SSam Clegg       DataBytes.resize(Size, Value);
653759631c7SSam Clegg     } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
654588fad4dSNirav Dave       int64_t NumValues;
655588fad4dSNirav Dave       if (!Fill->getNumValues().evaluateAsAbsolute(NumValues))
656d707c370SRafael Espindola         llvm_unreachable("The fill should be an assembler constant");
657588fad4dSNirav Dave       DataBytes.insert(DataBytes.end(), Fill->getValueSize() * NumValues,
658588fad4dSNirav Dave                        Fill->getValue());
65924faf859SHeejin Ahn     } else if (auto *LEB = dyn_cast<MCLEBFragment>(&Frag)) {
66024faf859SHeejin Ahn       const SmallVectorImpl<char> &Contents = LEB->getContents();
66124faf859SHeejin Ahn       DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
662759631c7SSam Clegg     } else {
663759631c7SSam Clegg       const auto &DataFrag = cast<MCDataFragment>(Frag);
664759631c7SSam Clegg       const SmallVectorImpl<char> &Contents = DataFrag.getContents();
665759631c7SSam Clegg       DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
666759631c7SSam Clegg     }
667759631c7SSam Clegg   }
668759631c7SSam Clegg 
669d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
670759631c7SSam Clegg }
671759631c7SSam Clegg 
67260ec3034SSam Clegg uint32_t
67360ec3034SSam Clegg WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
674d1152a26SSam Clegg   if (RelEntry.Type == wasm::R_WASM_TYPE_INDEX_LEB) {
675b7787fd0SSam Clegg     if (!TypeIndices.count(RelEntry.Symbol))
676b7787fd0SSam Clegg       report_fatal_error("symbol not found in type index space: " +
677b7787fd0SSam Clegg                          RelEntry.Symbol->getName());
678acd7d2b0SSam Clegg     return TypeIndices[RelEntry.Symbol];
679acd7d2b0SSam Clegg   }
68060ec3034SSam Clegg 
68125d8e68bSSam Clegg   return RelEntry.Symbol->getIndex();
682acd7d2b0SSam Clegg }
683acd7d2b0SSam Clegg 
684d934cb88SDan Gohman // Apply the portions of the relocation records that we can handle ourselves
685d934cb88SDan Gohman // directly.
686acd7d2b0SSam Clegg void WasmObjectWriter::applyRelocations(
6877ee758d6SSam Clegg     ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset,
6887ee758d6SSam Clegg     const MCAsmLayout &Layout) {
6890ff28fa6SDerek Schuff   auto &Stream = static_cast<raw_pwrite_stream &>(W->OS);
690d934cb88SDan Gohman   for (const WasmRelocationEntry &RelEntry : Relocations) {
691d934cb88SDan Gohman     uint64_t Offset = ContentsOffset +
692d934cb88SDan Gohman                       RelEntry.FixupSection->getSectionOffset() +
693d934cb88SDan Gohman                       RelEntry.Offset;
694d934cb88SDan Gohman 
695d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
6967ee758d6SSam Clegg     auto Value = getProvisionalValue(RelEntry, Layout);
69760ec3034SSam Clegg 
698acd7d2b0SSam Clegg     switch (RelEntry.Type) {
699d1152a26SSam Clegg     case wasm::R_WASM_FUNCTION_INDEX_LEB:
700d1152a26SSam Clegg     case wasm::R_WASM_TYPE_INDEX_LEB:
701d1152a26SSam Clegg     case wasm::R_WASM_GLOBAL_INDEX_LEB:
702d1152a26SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_LEB:
703d1152a26SSam Clegg     case wasm::R_WASM_EVENT_INDEX_LEB:
7043b29376eSWouter van Oortmerssen       writePatchableLEB<5>(Stream, Value, Offset);
7053b29376eSWouter van Oortmerssen       break;
7063b29376eSWouter van Oortmerssen     case wasm::R_WASM_MEMORY_ADDR_LEB64:
7073b29376eSWouter van Oortmerssen       writePatchableLEB<10>(Stream, Value, Offset);
708d934cb88SDan Gohman       break;
709d1152a26SSam Clegg     case wasm::R_WASM_TABLE_INDEX_I32:
710d1152a26SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_I32:
711d1152a26SSam Clegg     case wasm::R_WASM_FUNCTION_OFFSET_I32:
712d1152a26SSam Clegg     case wasm::R_WASM_SECTION_OFFSET_I32:
71348139ebcSWouter van Oortmerssen     case wasm::R_WASM_GLOBAL_INDEX_I32:
7140a6c4d8dSSam Clegg       patchI32(Stream, Value, Offset);
715d934cb88SDan Gohman       break;
716cc1b9b68SWouter van Oortmerssen     case wasm::R_WASM_TABLE_INDEX_I64:
7173b29376eSWouter van Oortmerssen     case wasm::R_WASM_MEMORY_ADDR_I64:
7183b29376eSWouter van Oortmerssen       patchI64(Stream, Value, Offset);
7193b29376eSWouter van Oortmerssen       break;
720d1152a26SSam Clegg     case wasm::R_WASM_TABLE_INDEX_SLEB:
7212a7cac93SSam Clegg     case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
722d1152a26SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_SLEB:
7232a7cac93SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
7243b29376eSWouter van Oortmerssen       writePatchableSLEB<5>(Stream, Value, Offset);
7253b29376eSWouter van Oortmerssen       break;
726cc1b9b68SWouter van Oortmerssen     case wasm::R_WASM_TABLE_INDEX_SLEB64:
7273b29376eSWouter van Oortmerssen     case wasm::R_WASM_MEMORY_ADDR_SLEB64:
7283b29376eSWouter van Oortmerssen     case wasm::R_WASM_MEMORY_ADDR_REL_SLEB64:
7293b29376eSWouter van Oortmerssen       writePatchableSLEB<10>(Stream, Value, Offset);
73060ec3034SSam Clegg       break;
731d934cb88SDan Gohman     default:
7329d24fb7fSSam Clegg       llvm_unreachable("invalid relocation type");
733d934cb88SDan Gohman     }
734d934cb88SDan Gohman   }
73518eafb6cSDan Gohman }
73618eafb6cSDan Gohman 
737da419bdbSHeejin Ahn void WasmObjectWriter::writeTypeSection(ArrayRef<WasmSignature> Signatures) {
738da419bdbSHeejin Ahn   if (Signatures.empty())
7399e15f359SSam Clegg     return;
7409e15f359SSam Clegg 
7419e15f359SSam Clegg   SectionBookkeeping Section;
7429e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_TYPE);
7439e15f359SSam Clegg 
7440ff28fa6SDerek Schuff   encodeULEB128(Signatures.size(), W->OS);
7459e15f359SSam Clegg 
746da419bdbSHeejin Ahn   for (const WasmSignature &Sig : Signatures) {
7470ff28fa6SDerek Schuff     W->OS << char(wasm::WASM_TYPE_FUNC);
7480ff28fa6SDerek Schuff     encodeULEB128(Sig.Params.size(), W->OS);
749da419bdbSHeejin Ahn     for (wasm::ValType Ty : Sig.Params)
7509e15f359SSam Clegg       writeValueType(Ty);
7510ff28fa6SDerek Schuff     encodeULEB128(Sig.Returns.size(), W->OS);
752da419bdbSHeejin Ahn     for (wasm::ValType Ty : Sig.Returns)
7539e15f359SSam Clegg       writeValueType(Ty);
7549e15f359SSam Clegg   }
7559e15f359SSam Clegg 
7569e15f359SSam Clegg   endSection(Section);
7579e15f359SSam Clegg }
7589e15f359SSam Clegg 
7598defa952SSam Clegg void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports,
7604d135b04SWouter van Oortmerssen                                           uint64_t DataSize,
761f950b24aSSam Clegg                                           uint32_t NumElements) {
7629e15f359SSam Clegg   if (Imports.empty())
7639e15f359SSam Clegg     return;
7649e15f359SSam Clegg 
7654d135b04SWouter van Oortmerssen   uint64_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
766f950b24aSSam Clegg 
7679e15f359SSam Clegg   SectionBookkeeping Section;
7689e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_IMPORT);
7699e15f359SSam Clegg 
7700ff28fa6SDerek Schuff   encodeULEB128(Imports.size(), W->OS);
7718defa952SSam Clegg   for (const wasm::WasmImport &Import : Imports) {
7728defa952SSam Clegg     writeString(Import.Module);
7738defa952SSam Clegg     writeString(Import.Field);
7740ff28fa6SDerek Schuff     W->OS << char(Import.Kind);
7759e15f359SSam Clegg 
7769e15f359SSam Clegg     switch (Import.Kind) {
7779e15f359SSam Clegg     case wasm::WASM_EXTERNAL_FUNCTION:
7780ff28fa6SDerek Schuff       encodeULEB128(Import.SigIndex, W->OS);
7799e15f359SSam Clegg       break;
7809e15f359SSam Clegg     case wasm::WASM_EXTERNAL_GLOBAL:
7810ff28fa6SDerek Schuff       W->OS << char(Import.Global.Type);
7820ff28fa6SDerek Schuff       W->OS << char(Import.Global.Mutable ? 1 : 0);
7839e15f359SSam Clegg       break;
784f950b24aSSam Clegg     case wasm::WASM_EXTERNAL_MEMORY:
7850ff28fa6SDerek Schuff       encodeULEB128(Import.Memory.Flags, W->OS);
7860ff28fa6SDerek Schuff       encodeULEB128(NumPages, W->OS); // initial
787f950b24aSSam Clegg       break;
788f950b24aSSam Clegg     case wasm::WASM_EXTERNAL_TABLE:
7890ff28fa6SDerek Schuff       W->OS << char(Import.Table.ElemType);
7900ff28fa6SDerek Schuff       encodeULEB128(0, W->OS);           // flags
7910ff28fa6SDerek Schuff       encodeULEB128(NumElements, W->OS); // initial
792f950b24aSSam Clegg       break;
793da419bdbSHeejin Ahn     case wasm::WASM_EXTERNAL_EVENT:
7940ff28fa6SDerek Schuff       encodeULEB128(Import.Event.Attribute, W->OS);
7950ff28fa6SDerek Schuff       encodeULEB128(Import.Event.SigIndex, W->OS);
796da419bdbSHeejin Ahn       break;
7979e15f359SSam Clegg     default:
7989e15f359SSam Clegg       llvm_unreachable("unsupported import kind");
7999e15f359SSam Clegg     }
8009e15f359SSam Clegg   }
8019e15f359SSam Clegg 
8029e15f359SSam Clegg   endSection(Section);
8039e15f359SSam Clegg }
8049e15f359SSam Clegg 
805457fb0b4SSam Clegg void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
8069e15f359SSam Clegg   if (Functions.empty())
8079e15f359SSam Clegg     return;
8089e15f359SSam Clegg 
8099e15f359SSam Clegg   SectionBookkeeping Section;
8109e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_FUNCTION);
8119e15f359SSam Clegg 
8120ff28fa6SDerek Schuff   encodeULEB128(Functions.size(), W->OS);
8139e15f359SSam Clegg   for (const WasmFunction &Func : Functions)
8140ff28fa6SDerek Schuff     encodeULEB128(Func.SigIndex, W->OS);
8159e15f359SSam Clegg 
8169e15f359SSam Clegg   endSection(Section);
8179e15f359SSam Clegg }
8189e15f359SSam Clegg 
819da419bdbSHeejin Ahn void WasmObjectWriter::writeEventSection(ArrayRef<wasm::WasmEventType> Events) {
820da419bdbSHeejin Ahn   if (Events.empty())
821da419bdbSHeejin Ahn     return;
822da419bdbSHeejin Ahn 
823da419bdbSHeejin Ahn   SectionBookkeeping Section;
824da419bdbSHeejin Ahn   startSection(Section, wasm::WASM_SEC_EVENT);
825da419bdbSHeejin Ahn 
8260ff28fa6SDerek Schuff   encodeULEB128(Events.size(), W->OS);
827da419bdbSHeejin Ahn   for (const wasm::WasmEventType &Event : Events) {
8280ff28fa6SDerek Schuff     encodeULEB128(Event.Attribute, W->OS);
8290ff28fa6SDerek Schuff     encodeULEB128(Event.SigIndex, W->OS);
830da419bdbSHeejin Ahn   }
831da419bdbSHeejin Ahn 
832da419bdbSHeejin Ahn   endSection(Section);
833da419bdbSHeejin Ahn }
834da419bdbSHeejin Ahn 
8350a6c4d8dSSam Clegg void WasmObjectWriter::writeGlobalSection(ArrayRef<wasm::WasmGlobal> Globals) {
8360a6c4d8dSSam Clegg   if (Globals.empty())
8370a6c4d8dSSam Clegg     return;
8380a6c4d8dSSam Clegg 
8390a6c4d8dSSam Clegg   SectionBookkeeping Section;
8400a6c4d8dSSam Clegg   startSection(Section, wasm::WASM_SEC_GLOBAL);
8410a6c4d8dSSam Clegg 
8420ff28fa6SDerek Schuff   encodeULEB128(Globals.size(), W->OS);
8430a6c4d8dSSam Clegg   for (const wasm::WasmGlobal &Global : Globals) {
8440ff28fa6SDerek Schuff     encodeULEB128(Global.Type.Type, W->OS);
8450ff28fa6SDerek Schuff     W->OS << char(Global.Type.Mutable);
8460ff28fa6SDerek Schuff     W->OS << char(Global.InitExpr.Opcode);
8470a6c4d8dSSam Clegg     switch (Global.Type.Type) {
8480a6c4d8dSSam Clegg     case wasm::WASM_TYPE_I32:
8490ff28fa6SDerek Schuff       encodeSLEB128(0, W->OS);
8500a6c4d8dSSam Clegg       break;
8510a6c4d8dSSam Clegg     case wasm::WASM_TYPE_I64:
8520ff28fa6SDerek Schuff       encodeSLEB128(0, W->OS);
8530a6c4d8dSSam Clegg       break;
8540a6c4d8dSSam Clegg     case wasm::WASM_TYPE_F32:
8550a6c4d8dSSam Clegg       writeI32(0);
8560a6c4d8dSSam Clegg       break;
8570a6c4d8dSSam Clegg     case wasm::WASM_TYPE_F64:
8580a6c4d8dSSam Clegg       writeI64(0);
8590a6c4d8dSSam Clegg       break;
86079aad89dSSam Clegg     case wasm::WASM_TYPE_EXTERNREF:
86179aad89dSSam Clegg       writeValueType(wasm::ValType::EXTERNREF);
86279aad89dSSam Clegg       break;
8630a6c4d8dSSam Clegg     default:
8640a6c4d8dSSam Clegg       llvm_unreachable("unexpected type");
8650a6c4d8dSSam Clegg     }
8660ff28fa6SDerek Schuff     W->OS << char(wasm::WASM_OPCODE_END);
8670a6c4d8dSSam Clegg   }
8680a6c4d8dSSam Clegg 
8690a6c4d8dSSam Clegg   endSection(Section);
8700a6c4d8dSSam Clegg }
8710a6c4d8dSSam Clegg 
8728defa952SSam Clegg void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) {
8739e15f359SSam Clegg   if (Exports.empty())
8749e15f359SSam Clegg     return;
8759e15f359SSam Clegg 
8769e15f359SSam Clegg   SectionBookkeeping Section;
8779e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_EXPORT);
8789e15f359SSam Clegg 
8790ff28fa6SDerek Schuff   encodeULEB128(Exports.size(), W->OS);
8808defa952SSam Clegg   for (const wasm::WasmExport &Export : Exports) {
8818defa952SSam Clegg     writeString(Export.Name);
8820ff28fa6SDerek Schuff     W->OS << char(Export.Kind);
8830ff28fa6SDerek Schuff     encodeULEB128(Export.Index, W->OS);
8849e15f359SSam Clegg   }
8859e15f359SSam Clegg 
8869e15f359SSam Clegg   endSection(Section);
8879e15f359SSam Clegg }
8889e15f359SSam Clegg 
889457fb0b4SSam Clegg void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
8909e15f359SSam Clegg   if (TableElems.empty())
8919e15f359SSam Clegg     return;
8929e15f359SSam Clegg 
8939e15f359SSam Clegg   SectionBookkeeping Section;
8949e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_ELEM);
8959e15f359SSam Clegg 
8960ff28fa6SDerek Schuff   encodeULEB128(1, W->OS); // number of "segments"
8970ff28fa6SDerek Schuff   encodeULEB128(0, W->OS); // the table index
8989e15f359SSam Clegg 
8999e15f359SSam Clegg   // init expr for starting offset
9000ff28fa6SDerek Schuff   W->OS << char(wasm::WASM_OPCODE_I32_CONST);
9010ff28fa6SDerek Schuff   encodeSLEB128(InitialTableOffset, W->OS);
9020ff28fa6SDerek Schuff   W->OS << char(wasm::WASM_OPCODE_END);
9039e15f359SSam Clegg 
9040ff28fa6SDerek Schuff   encodeULEB128(TableElems.size(), W->OS);
9059e15f359SSam Clegg   for (uint32_t Elem : TableElems)
9060ff28fa6SDerek Schuff     encodeULEB128(Elem, W->OS);
9079e15f359SSam Clegg 
9089e15f359SSam Clegg   endSection(Section);
9099e15f359SSam Clegg }
9109e15f359SSam Clegg 
911fef8de66SThomas Lively void WasmObjectWriter::writeDataCountSection() {
912fef8de66SThomas Lively   if (DataSegments.empty())
913fef8de66SThomas Lively     return;
914fef8de66SThomas Lively 
915fef8de66SThomas Lively   SectionBookkeeping Section;
916fef8de66SThomas Lively   startSection(Section, wasm::WASM_SEC_DATACOUNT);
9170ff28fa6SDerek Schuff   encodeULEB128(DataSegments.size(), W->OS);
918fef8de66SThomas Lively   endSection(Section);
919fef8de66SThomas Lively }
920fef8de66SThomas Lively 
921e49584a3SSam Clegg uint32_t WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
922457fb0b4SSam Clegg                                             const MCAsmLayout &Layout,
923457fb0b4SSam Clegg                                             ArrayRef<WasmFunction> Functions) {
9249e15f359SSam Clegg   if (Functions.empty())
925e49584a3SSam Clegg     return 0;
9269e15f359SSam Clegg 
9279e15f359SSam Clegg   SectionBookkeeping Section;
9289e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_CODE);
9299e15f359SSam Clegg 
9300ff28fa6SDerek Schuff   encodeULEB128(Functions.size(), W->OS);
9319e15f359SSam Clegg 
9329e15f359SSam Clegg   for (const WasmFunction &Func : Functions) {
933fe6414b0SSam Clegg     auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
9349e15f359SSam Clegg 
9359e15f359SSam Clegg     int64_t Size = 0;
9369e15f359SSam Clegg     if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
9379e15f359SSam Clegg       report_fatal_error(".size expression must be evaluatable");
9389e15f359SSam Clegg 
9390ff28fa6SDerek Schuff     encodeULEB128(Size, W->OS);
9400ff28fa6SDerek Schuff     FuncSection.setSectionOffset(W->OS.tell() - Section.ContentsOffset);
9410ff28fa6SDerek Schuff     Asm.writeSectionData(W->OS, &FuncSection, Layout);
9429e15f359SSam Clegg   }
9439e15f359SSam Clegg 
9449e15f359SSam Clegg   // Apply fixups.
9457ee758d6SSam Clegg   applyRelocations(CodeRelocations, Section.ContentsOffset, Layout);
9469e15f359SSam Clegg 
9479e15f359SSam Clegg   endSection(Section);
948e49584a3SSam Clegg   return Section.Index;
9499e15f359SSam Clegg }
9509e15f359SSam Clegg 
951e49584a3SSam Clegg uint32_t WasmObjectWriter::writeDataSection(const MCAsmLayout &Layout) {
9526c899ba6SSam Clegg   if (DataSegments.empty())
953e49584a3SSam Clegg     return 0;
9549e15f359SSam Clegg 
9559e15f359SSam Clegg   SectionBookkeeping Section;
9569e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_DATA);
9579e15f359SSam Clegg 
9580ff28fa6SDerek Schuff   encodeULEB128(DataSegments.size(), W->OS); // count
9597c395943SSam Clegg 
9606c899ba6SSam Clegg   for (const WasmDataSegment &Segment : DataSegments) {
9610ff28fa6SDerek Schuff     encodeULEB128(Segment.InitFlags, W->OS); // flags
9622e150409SThomas Lively     if (Segment.InitFlags & wasm::WASM_SEGMENT_HAS_MEMINDEX)
9630ff28fa6SDerek Schuff       encodeULEB128(0, W->OS); // memory index
9642e150409SThomas Lively     if ((Segment.InitFlags & wasm::WASM_SEGMENT_IS_PASSIVE) == 0) {
9650ff28fa6SDerek Schuff       W->OS << char(Segment.Offset > INT32_MAX ? wasm::WASM_OPCODE_I64_CONST
9664d135b04SWouter van Oortmerssen                                                : wasm::WASM_OPCODE_I32_CONST);
9670ff28fa6SDerek Schuff       encodeSLEB128(Segment.Offset, W->OS); // offset
9680ff28fa6SDerek Schuff       W->OS << char(wasm::WASM_OPCODE_END);
9692e150409SThomas Lively     }
9700ff28fa6SDerek Schuff     encodeULEB128(Segment.Data.size(), W->OS); // size
9710ff28fa6SDerek Schuff     Segment.Section->setSectionOffset(W->OS.tell() - Section.ContentsOffset);
9720ff28fa6SDerek Schuff     W->OS << Segment.Data; // data
9737c395943SSam Clegg   }
9749e15f359SSam Clegg 
9759e15f359SSam Clegg   // Apply fixups.
9767ee758d6SSam Clegg   applyRelocations(DataRelocations, Section.ContentsOffset, Layout);
9779e15f359SSam Clegg 
9789e15f359SSam Clegg   endSection(Section);
979e49584a3SSam Clegg   return Section.Index;
9809e15f359SSam Clegg }
9819e15f359SSam Clegg 
9826f08c84aSSam Clegg void WasmObjectWriter::writeRelocSection(
9836f08c84aSSam Clegg     uint32_t SectionIndex, StringRef Name,
984f77dc2a8SSam Clegg     std::vector<WasmRelocationEntry> &Relocs) {
9859e15f359SSam Clegg   // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
9869e15f359SSam Clegg   // for descriptions of the reloc sections.
9879e15f359SSam Clegg 
988f77dc2a8SSam Clegg   if (Relocs.empty())
9899e15f359SSam Clegg     return;
9909e15f359SSam Clegg 
991f77dc2a8SSam Clegg   // First, ensure the relocations are sorted in offset order.  In general they
992f77dc2a8SSam Clegg   // should already be sorted since `recordRelocation` is called in offset
993f77dc2a8SSam Clegg   // order, but for the code section we combine many MC sections into single
994f77dc2a8SSam Clegg   // wasm section, and this order is determined by the order of Asm.Symbols()
995f77dc2a8SSam Clegg   // not the sections order.
996efd94c56SFangrui Song   llvm::stable_sort(
997efd94c56SFangrui Song       Relocs, [](const WasmRelocationEntry &A, const WasmRelocationEntry &B) {
998f77dc2a8SSam Clegg         return (A.Offset + A.FixupSection->getSectionOffset()) <
999f77dc2a8SSam Clegg                (B.Offset + B.FixupSection->getSectionOffset());
1000f77dc2a8SSam Clegg       });
1001f77dc2a8SSam Clegg 
10029e15f359SSam Clegg   SectionBookkeeping Section;
10036f08c84aSSam Clegg   startCustomSection(Section, std::string("reloc.") + Name.str());
10049e15f359SSam Clegg 
10050ff28fa6SDerek Schuff   encodeULEB128(SectionIndex, W->OS);
10060ff28fa6SDerek Schuff   encodeULEB128(Relocs.size(), W->OS);
1007f77dc2a8SSam Clegg   for (const WasmRelocationEntry &RelEntry : Relocs) {
1008f208f631SHeejin Ahn     uint64_t Offset =
1009f208f631SHeejin Ahn         RelEntry.Offset + RelEntry.FixupSection->getSectionOffset();
10106f08c84aSSam Clegg     uint32_t Index = getRelocationIndexValue(RelEntry);
10119e15f359SSam Clegg 
10120ff28fa6SDerek Schuff     W->OS << char(RelEntry.Type);
10130ff28fa6SDerek Schuff     encodeULEB128(Offset, W->OS);
10140ff28fa6SDerek Schuff     encodeULEB128(Index, W->OS);
10156f08c84aSSam Clegg     if (RelEntry.hasAddend())
10160ff28fa6SDerek Schuff       encodeSLEB128(RelEntry.Addend, W->OS);
10179e15f359SSam Clegg   }
10189e15f359SSam Clegg 
10199e15f359SSam Clegg   endSection(Section);
10209e15f359SSam Clegg }
10219e15f359SSam Clegg 
10226a31a0d6SSam Clegg void WasmObjectWriter::writeCustomRelocSections() {
10236a31a0d6SSam Clegg   for (const auto &Sec : CustomSections) {
10246a31a0d6SSam Clegg     auto &Relocations = CustomSectionsRelocations[Sec.Section];
10256a31a0d6SSam Clegg     writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations);
10266a31a0d6SSam Clegg   }
10276a31a0d6SSam Clegg }
10286a31a0d6SSam Clegg 
10299e15f359SSam Clegg void WasmObjectWriter::writeLinkingMetaDataSection(
103086b4a09aSSam Clegg     ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
1031ea7caceeSSam Clegg     ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
1032ea7caceeSSam Clegg     const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) {
10339e15f359SSam Clegg   SectionBookkeeping Section;
10342322a937SSam Clegg   startCustomSection(Section, "linking");
10350ff28fa6SDerek Schuff   encodeULEB128(wasm::WasmMetadataVersion, W->OS);
10369e15f359SSam Clegg 
10376bb5a41fSSam Clegg   SectionBookkeeping SubSection;
10386c899ba6SSam Clegg   if (SymbolInfos.size() != 0) {
10396c899ba6SSam Clegg     startSection(SubSection, wasm::WASM_SYMBOL_TABLE);
10400ff28fa6SDerek Schuff     encodeULEB128(SymbolInfos.size(), W->OS);
10416c899ba6SSam Clegg     for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) {
10420ff28fa6SDerek Schuff       encodeULEB128(Sym.Kind, W->OS);
10430ff28fa6SDerek Schuff       encodeULEB128(Sym.Flags, W->OS);
10446c899ba6SSam Clegg       switch (Sym.Kind) {
10456c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_FUNCTION:
10466c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_GLOBAL:
1047da419bdbSHeejin Ahn       case wasm::WASM_SYMBOL_TYPE_EVENT:
10480ff28fa6SDerek Schuff         encodeULEB128(Sym.ElementIndex, W->OS);
104929874ceaSDan Gohman         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0 ||
105029874ceaSDan Gohman             (Sym.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0)
10516c899ba6SSam Clegg           writeString(Sym.Name);
10526c899ba6SSam Clegg         break;
10536c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_DATA:
10546c899ba6SSam Clegg         writeString(Sym.Name);
10556c899ba6SSam Clegg         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) {
10560ff28fa6SDerek Schuff           encodeULEB128(Sym.DataRef.Segment, W->OS);
10570ff28fa6SDerek Schuff           encodeULEB128(Sym.DataRef.Offset, W->OS);
10580ff28fa6SDerek Schuff           encodeULEB128(Sym.DataRef.Size, W->OS);
10596c899ba6SSam Clegg         }
10606c899ba6SSam Clegg         break;
10616a31a0d6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_SECTION: {
10626a31a0d6SSam Clegg         const uint32_t SectionIndex =
10636a31a0d6SSam Clegg             CustomSections[Sym.ElementIndex].OutputIndex;
10640ff28fa6SDerek Schuff         encodeULEB128(SectionIndex, W->OS);
10656a31a0d6SSam Clegg         break;
10666a31a0d6SSam Clegg       }
10676c899ba6SSam Clegg       default:
10686c899ba6SSam Clegg         llvm_unreachable("unexpected kind");
10696c899ba6SSam Clegg       }
1070b7787fd0SSam Clegg     }
1071b7787fd0SSam Clegg     endSection(SubSection);
1072b7787fd0SSam Clegg   }
10739e15f359SSam Clegg 
10746c899ba6SSam Clegg   if (DataSegments.size()) {
107563ebb813SSam Clegg     startSection(SubSection, wasm::WASM_SEGMENT_INFO);
10760ff28fa6SDerek Schuff     encodeULEB128(DataSegments.size(), W->OS);
10776c899ba6SSam Clegg     for (const WasmDataSegment &Segment : DataSegments) {
1078d95ed959SSam Clegg       writeString(Segment.Name);
10790ff28fa6SDerek Schuff       encodeULEB128(Segment.Alignment, W->OS);
10800ff28fa6SDerek Schuff       encodeULEB128(Segment.LinkerFlags, W->OS);
108163ebb813SSam Clegg     }
1082d95ed959SSam Clegg     endSection(SubSection);
1083d95ed959SSam Clegg   }
1084d95ed959SSam Clegg 
1085bafe6902SSam Clegg   if (!InitFuncs.empty()) {
1086bafe6902SSam Clegg     startSection(SubSection, wasm::WASM_INIT_FUNCS);
10870ff28fa6SDerek Schuff     encodeULEB128(InitFuncs.size(), W->OS);
1088bafe6902SSam Clegg     for (auto &StartFunc : InitFuncs) {
10890ff28fa6SDerek Schuff       encodeULEB128(StartFunc.first, W->OS);  // priority
10900ff28fa6SDerek Schuff       encodeULEB128(StartFunc.second, W->OS); // function index
1091bafe6902SSam Clegg     }
1092bafe6902SSam Clegg     endSection(SubSection);
1093bafe6902SSam Clegg   }
1094bafe6902SSam Clegg 
1095ea7caceeSSam Clegg   if (Comdats.size()) {
1096ea7caceeSSam Clegg     startSection(SubSection, wasm::WASM_COMDAT_INFO);
10970ff28fa6SDerek Schuff     encodeULEB128(Comdats.size(), W->OS);
1098ea7caceeSSam Clegg     for (const auto &C : Comdats) {
1099ea7caceeSSam Clegg       writeString(C.first);
11000ff28fa6SDerek Schuff       encodeULEB128(0, W->OS); // flags for future use
11010ff28fa6SDerek Schuff       encodeULEB128(C.second.size(), W->OS);
1102ea7caceeSSam Clegg       for (const WasmComdatEntry &Entry : C.second) {
11030ff28fa6SDerek Schuff         encodeULEB128(Entry.Kind, W->OS);
11040ff28fa6SDerek Schuff         encodeULEB128(Entry.Index, W->OS);
1105ea7caceeSSam Clegg       }
1106ea7caceeSSam Clegg     }
1107ea7caceeSSam Clegg     endSection(SubSection);
1108ea7caceeSSam Clegg   }
1109ea7caceeSSam Clegg 
11109e15f359SSam Clegg   endSection(Section);
11119e15f359SSam Clegg }
11129e15f359SSam Clegg 
1113cbda16ebSThomas Lively void WasmObjectWriter::writeCustomSection(WasmCustomSection &CustomSection,
1114cbda16ebSThomas Lively                                           const MCAssembler &Asm,
11156a31a0d6SSam Clegg                                           const MCAsmLayout &Layout) {
1116cfd44a2eSSam Clegg   SectionBookkeeping Section;
11176a31a0d6SSam Clegg   auto *Sec = CustomSection.Section;
11182322a937SSam Clegg   startCustomSection(Section, CustomSection.Name);
11196a31a0d6SSam Clegg 
11200ff28fa6SDerek Schuff   Sec->setSectionOffset(W->OS.tell() - Section.ContentsOffset);
11210ff28fa6SDerek Schuff   Asm.writeSectionData(W->OS, Sec, Layout);
11226a31a0d6SSam Clegg 
11236a31a0d6SSam Clegg   CustomSection.OutputContentsOffset = Section.ContentsOffset;
11246a31a0d6SSam Clegg   CustomSection.OutputIndex = Section.Index;
11256a31a0d6SSam Clegg 
1126cfd44a2eSSam Clegg   endSection(Section);
11276a31a0d6SSam Clegg 
11286a31a0d6SSam Clegg   // Apply fixups.
11294d57fbd0SSam Clegg   auto &Relocations = CustomSectionsRelocations[CustomSection.Section];
11307ee758d6SSam Clegg   applyRelocations(Relocations, CustomSection.OutputContentsOffset, Layout);
11316a31a0d6SSam Clegg }
11326a31a0d6SSam Clegg 
11335e3d33a7SSam Clegg uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm &Symbol) {
11345e3d33a7SSam Clegg   assert(Symbol.isFunction());
11355e3d33a7SSam Clegg   assert(TypeIndices.count(&Symbol));
11365e3d33a7SSam Clegg   return TypeIndices[&Symbol];
11375e3d33a7SSam Clegg }
11385e3d33a7SSam Clegg 
1139da419bdbSHeejin Ahn uint32_t WasmObjectWriter::getEventType(const MCSymbolWasm &Symbol) {
1140da419bdbSHeejin Ahn   assert(Symbol.isEvent());
1141da419bdbSHeejin Ahn   assert(TypeIndices.count(&Symbol));
1142da419bdbSHeejin Ahn   return TypeIndices[&Symbol];
1143da419bdbSHeejin Ahn }
1144da419bdbSHeejin Ahn 
114538b12f5eSHeejin Ahn void WasmObjectWriter::registerFunctionType(const MCSymbolWasm &Symbol) {
11465e3d33a7SSam Clegg   assert(Symbol.isFunction());
11475e3d33a7SSam Clegg 
1148da419bdbSHeejin Ahn   WasmSignature S;
11497ee758d6SSam Clegg 
11507ee758d6SSam Clegg   if (auto *Sig = Symbol.getSignature()) {
1151da419bdbSHeejin Ahn     S.Returns = Sig->Returns;
1152da419bdbSHeejin Ahn     S.Params = Sig->Params;
115377a7a380SDerek Schuff   }
11545e3d33a7SSam Clegg 
1155da419bdbSHeejin Ahn   auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
11565e3d33a7SSam Clegg   if (Pair.second)
1157da419bdbSHeejin Ahn     Signatures.push_back(S);
11585e3d33a7SSam Clegg   TypeIndices[&Symbol] = Pair.first->second;
11595e3d33a7SSam Clegg 
1160d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "registerFunctionType: " << Symbol
1161d34e60caSNicola Zaghen                     << " new:" << Pair.second << "\n");
1162d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
11635e3d33a7SSam Clegg }
11645e3d33a7SSam Clegg 
116538b12f5eSHeejin Ahn void WasmObjectWriter::registerEventType(const MCSymbolWasm &Symbol) {
1166da419bdbSHeejin Ahn   assert(Symbol.isEvent());
1167da419bdbSHeejin Ahn 
1168da419bdbSHeejin Ahn   // TODO Currently we don't generate imported exceptions, but if we do, we
1169da419bdbSHeejin Ahn   // should have a way of infering types of imported exceptions.
1170da419bdbSHeejin Ahn   WasmSignature S;
1171da419bdbSHeejin Ahn   if (auto *Sig = Symbol.getSignature()) {
1172da419bdbSHeejin Ahn     S.Returns = Sig->Returns;
1173da419bdbSHeejin Ahn     S.Params = Sig->Params;
1174da419bdbSHeejin Ahn   }
1175da419bdbSHeejin Ahn 
1176da419bdbSHeejin Ahn   auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
1177da419bdbSHeejin Ahn   if (Pair.second)
1178da419bdbSHeejin Ahn     Signatures.push_back(S);
1179da419bdbSHeejin Ahn   TypeIndices[&Symbol] = Pair.first->second;
1180da419bdbSHeejin Ahn 
1181da419bdbSHeejin Ahn   LLVM_DEBUG(dbgs() << "registerEventType: " << Symbol << " new:" << Pair.second
1182da419bdbSHeejin Ahn                     << "\n");
1183da419bdbSHeejin Ahn   LLVM_DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
1184da419bdbSHeejin Ahn }
1185da419bdbSHeejin Ahn 
11864d57fbd0SSam Clegg static bool isInSymtab(const MCSymbolWasm &Sym) {
11873ea1c62cSSam Clegg   if (Sym.isUsedInReloc() || Sym.isUsedInInitArray())
11884d57fbd0SSam Clegg     return true;
11894d57fbd0SSam Clegg 
11904d57fbd0SSam Clegg   if (Sym.isComdat() && !Sym.isDefined())
11914d57fbd0SSam Clegg     return false;
11924d57fbd0SSam Clegg 
11933ea1c62cSSam Clegg   if (Sym.isTemporary())
11944d57fbd0SSam Clegg     return false;
11954d57fbd0SSam Clegg 
11964d57fbd0SSam Clegg   if (Sym.isSection())
11974d57fbd0SSam Clegg     return false;
11984d57fbd0SSam Clegg 
11994d57fbd0SSam Clegg   return true;
12004d57fbd0SSam Clegg }
12010ff28fa6SDerek Schuff void WasmObjectWriter::prepareImports(
12020ff28fa6SDerek Schuff     SmallVectorImpl<wasm::WasmImport> &Imports, MCAssembler &Asm,
120318eafb6cSDan Gohman     const MCAsmLayout &Layout) {
1204f950b24aSSam Clegg   // For now, always emit the memory import, since loads and stores are not
1205f950b24aSSam Clegg   // valid without it. In the future, we could perhaps be more clever and omit
1206f950b24aSSam Clegg   // it if there are no loads or stores.
12078defa952SSam Clegg   wasm::WasmImport MemImport;
12081ed3a046SSam Clegg   MemImport.Module = "env";
12091ed3a046SSam Clegg   MemImport.Field = "__linear_memory";
1210f950b24aSSam Clegg   MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
1211fd0964aeSWouter van Oortmerssen   MemImport.Memory.Flags = is64Bit() ? wasm::WASM_LIMITS_FLAG_IS_64
1212fd0964aeSWouter van Oortmerssen                                      : wasm::WASM_LIMITS_FLAG_NONE;
1213f950b24aSSam Clegg   Imports.push_back(MemImport);
1214f950b24aSSam Clegg 
1215f950b24aSSam Clegg   // For now, always emit the table section, since indirect calls are not
1216f950b24aSSam Clegg   // valid without it. In the future, we could perhaps be more clever and omit
1217f950b24aSSam Clegg   // it if there are no indirect calls.
12188defa952SSam Clegg   wasm::WasmImport TableImport;
12191ed3a046SSam Clegg   TableImport.Module = "env";
12201ed3a046SSam Clegg   TableImport.Field = "__indirect_function_table";
1221f950b24aSSam Clegg   TableImport.Kind = wasm::WASM_EXTERNAL_TABLE;
12226a87ddacSThomas Lively   TableImport.Table.ElemType = wasm::WASM_TYPE_FUNCREF;
1223f950b24aSSam Clegg   Imports.push_back(TableImport);
1224f950b24aSSam Clegg 
1225da419bdbSHeejin Ahn   // Populate SignatureIndices, and Imports and WasmIndices for undefined
1226586320c0SNicholas Wilson   // symbols.  This must be done before populating WasmIndices for defined
1227586320c0SNicholas Wilson   // symbols.
122832ce5ca0SDan Gohman   for (const MCSymbol &S : Asm.symbols()) {
122932ce5ca0SDan Gohman     const auto &WS = static_cast<const MCSymbolWasm &>(S);
123032ce5ca0SDan Gohman 
123132ce5ca0SDan Gohman     // Register types for all functions, including those with private linkage
12329f3fe42eSSam Clegg     // (because wasm always needs a type signature).
12337ee758d6SSam Clegg     if (WS.isFunction()) {
1234*9c7b5808SDominic Chen       const auto *BS = Layout.getBaseSymbol(S);
1235*9c7b5808SDominic Chen       if (!BS)
1236*9c7b5808SDominic Chen         report_fatal_error(Twine(S.getName()) +
1237*9c7b5808SDominic Chen                            ": absolute addressing not supported!");
1238*9c7b5808SDominic Chen       registerFunctionType(*cast<MCSymbolWasm>(BS));
12397ee758d6SSam Clegg     }
124032ce5ca0SDan Gohman 
1241da419bdbSHeejin Ahn     if (WS.isEvent())
1242da419bdbSHeejin Ahn       registerEventType(WS);
1243da419bdbSHeejin Ahn 
124432ce5ca0SDan Gohman     if (WS.isTemporary())
124532ce5ca0SDan Gohman       continue;
124632ce5ca0SDan Gohman 
124732ce5ca0SDan Gohman     // If the symbol is not defined in this translation unit, import it.
12486c899ba6SSam Clegg     if (!WS.isDefined() && !WS.isComdat()) {
12496c899ba6SSam Clegg       if (WS.isFunction()) {
12508defa952SSam Clegg         wasm::WasmImport Import;
1251f726e445SDan Gohman         Import.Module = WS.getImportModule();
1252f726e445SDan Gohman         Import.Field = WS.getImportName();
125332ce5ca0SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
12548defa952SSam Clegg         Import.SigIndex = getFunctionType(WS);
12556c899ba6SSam Clegg         Imports.push_back(Import);
1256492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
12576c899ba6SSam Clegg         WasmIndices[&WS] = NumFunctionImports++;
12586c899ba6SSam Clegg       } else if (WS.isGlobal()) {
125915f349f7SNicholas Wilson         if (WS.isWeak())
126015f349f7SNicholas Wilson           report_fatal_error("undefined global symbol cannot be weak");
126115f349f7SNicholas Wilson 
12626c899ba6SSam Clegg         wasm::WasmImport Import;
1263f726e445SDan Gohman         Import.Field = WS.getImportName();
126432ce5ca0SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1265492f7529SSam Clegg         Import.Module = WS.getImportModule();
12666c899ba6SSam Clegg         Import.Global = WS.getGlobalType();
12676c899ba6SSam Clegg         Imports.push_back(Import);
1268492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
12696c899ba6SSam Clegg         WasmIndices[&WS] = NumGlobalImports++;
1270da419bdbSHeejin Ahn       } else if (WS.isEvent()) {
1271da419bdbSHeejin Ahn         if (WS.isWeak())
1272da419bdbSHeejin Ahn           report_fatal_error("undefined event symbol cannot be weak");
1273da419bdbSHeejin Ahn 
1274da419bdbSHeejin Ahn         wasm::WasmImport Import;
1275f726e445SDan Gohman         Import.Module = WS.getImportModule();
1276f726e445SDan Gohman         Import.Field = WS.getImportName();
1277da419bdbSHeejin Ahn         Import.Kind = wasm::WASM_EXTERNAL_EVENT;
1278da419bdbSHeejin Ahn         Import.Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
1279da419bdbSHeejin Ahn         Import.Event.SigIndex = getEventType(WS);
1280da419bdbSHeejin Ahn         Imports.push_back(Import);
1281492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
1282da419bdbSHeejin Ahn         WasmIndices[&WS] = NumEventImports++;
128332ce5ca0SDan Gohman       }
128432ce5ca0SDan Gohman     }
128532ce5ca0SDan Gohman   }
128632ce5ca0SDan Gohman 
1287492f7529SSam Clegg   // Add imports for GOT globals
1288492f7529SSam Clegg   for (const MCSymbol &S : Asm.symbols()) {
1289492f7529SSam Clegg     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1290492f7529SSam Clegg     if (WS.isUsedInGOT()) {
1291492f7529SSam Clegg       wasm::WasmImport Import;
1292492f7529SSam Clegg       if (WS.isFunction())
1293492f7529SSam Clegg         Import.Module = "GOT.func";
1294492f7529SSam Clegg       else
1295492f7529SSam Clegg         Import.Module = "GOT.mem";
1296492f7529SSam Clegg       Import.Field = WS.getName();
1297492f7529SSam Clegg       Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1298492f7529SSam Clegg       Import.Global = {wasm::WASM_TYPE_I32, true};
1299492f7529SSam Clegg       Imports.push_back(Import);
1300492f7529SSam Clegg       assert(GOTIndices.count(&WS) == 0);
1301492f7529SSam Clegg       GOTIndices[&WS] = NumGlobalImports++;
1302492f7529SSam Clegg     }
1303492f7529SSam Clegg   }
13040ff28fa6SDerek Schuff }
1305492f7529SSam Clegg 
13060ff28fa6SDerek Schuff uint64_t WasmObjectWriter::writeObject(MCAssembler &Asm,
13070ff28fa6SDerek Schuff                                        const MCAsmLayout &Layout) {
13080ff28fa6SDerek Schuff   support::endian::Writer MainWriter(*OS, support::little);
13090ff28fa6SDerek Schuff   W = &MainWriter;
13100ff28fa6SDerek Schuff   if (IsSplitDwarf) {
13110ff28fa6SDerek Schuff     uint64_t TotalSize = writeOneObject(Asm, Layout, DwoMode::NonDwoOnly);
13120ff28fa6SDerek Schuff     assert(DwoOS);
13130ff28fa6SDerek Schuff     support::endian::Writer DwoWriter(*DwoOS, support::little);
13140ff28fa6SDerek Schuff     W = &DwoWriter;
13150ff28fa6SDerek Schuff     return TotalSize + writeOneObject(Asm, Layout, DwoMode::DwoOnly);
13160ff28fa6SDerek Schuff   } else {
13170ff28fa6SDerek Schuff     return writeOneObject(Asm, Layout, DwoMode::AllSections);
13180ff28fa6SDerek Schuff   }
13190ff28fa6SDerek Schuff }
13200ff28fa6SDerek Schuff 
13210ff28fa6SDerek Schuff uint64_t WasmObjectWriter::writeOneObject(MCAssembler &Asm,
13220ff28fa6SDerek Schuff                                           const MCAsmLayout &Layout,
13230ff28fa6SDerek Schuff                                           DwoMode Mode) {
13240ff28fa6SDerek Schuff   uint64_t StartOffset = W->OS.tell();
13250ff28fa6SDerek Schuff   SectionCount = 0;
13260ff28fa6SDerek Schuff   CustomSections.clear();
13270ff28fa6SDerek Schuff 
13280ff28fa6SDerek Schuff   LLVM_DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
13290ff28fa6SDerek Schuff 
13300ff28fa6SDerek Schuff   // Collect information from the available symbols.
13310ff28fa6SDerek Schuff   SmallVector<WasmFunction, 4> Functions;
13320ff28fa6SDerek Schuff   SmallVector<uint32_t, 4> TableElems;
13330ff28fa6SDerek Schuff   SmallVector<wasm::WasmImport, 4> Imports;
13340ff28fa6SDerek Schuff   SmallVector<wasm::WasmExport, 4> Exports;
13350ff28fa6SDerek Schuff   SmallVector<wasm::WasmEventType, 1> Events;
13360ff28fa6SDerek Schuff   SmallVector<wasm::WasmGlobal, 1> Globals;
13370ff28fa6SDerek Schuff   SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos;
13380ff28fa6SDerek Schuff   SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
13390ff28fa6SDerek Schuff   std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
13400ff28fa6SDerek Schuff   uint64_t DataSize = 0;
13410ff28fa6SDerek Schuff   if (Mode != DwoMode::DwoOnly) {
13420ff28fa6SDerek Schuff     prepareImports(Imports, Asm, Layout);
13430ff28fa6SDerek Schuff   }
13444d57fbd0SSam Clegg   // Populate DataSegments and CustomSections, which must be done before
13454d57fbd0SSam Clegg   // populating DataLocations.
1346759631c7SSam Clegg   for (MCSection &Sec : Asm) {
1347759631c7SSam Clegg     auto &Section = static_cast<MCSectionWasm &>(Sec);
13487d1ff446SFangrui Song     StringRef SectionName = Section.getName();
1349759631c7SSam Clegg 
13500ff28fa6SDerek Schuff     if (Mode == DwoMode::NonDwoOnly && isDwoSection(Sec))
13510ff28fa6SDerek Schuff       continue;
13520ff28fa6SDerek Schuff     if (Mode == DwoMode::DwoOnly && !isDwoSection(Sec))
13530ff28fa6SDerek Schuff       continue;
13540ff28fa6SDerek Schuff 
1355bafe6902SSam Clegg     // .init_array sections are handled specially elsewhere.
13564d57fbd0SSam Clegg     if (SectionName.startswith(".init_array"))
1357bafe6902SSam Clegg       continue;
1358bafe6902SSam Clegg 
13594d57fbd0SSam Clegg     // Code is handled separately
13604d57fbd0SSam Clegg     if (Section.getKind().isText())
13614d57fbd0SSam Clegg       continue;
13624d57fbd0SSam Clegg 
13634d57fbd0SSam Clegg     if (Section.isWasmData()) {
1364329e76d5SSam Clegg       uint32_t SegmentIndex = DataSegments.size();
1365759631c7SSam Clegg       DataSize = alignTo(DataSize, Section.getAlignment());
1366759631c7SSam Clegg       DataSegments.emplace_back();
1367759631c7SSam Clegg       WasmDataSegment &Segment = DataSegments.back();
13684d57fbd0SSam Clegg       Segment.Name = SectionName;
13699b49f36aSSimon Pilgrim       Segment.InitFlags =
13709b49f36aSSimon Pilgrim           Section.getPassive() ? (uint32_t)wasm::WASM_SEGMENT_IS_PASSIVE : 0;
1371759631c7SSam Clegg       Segment.Offset = DataSize;
1372759631c7SSam Clegg       Segment.Section = &Section;
137363ebb813SSam Clegg       addData(Segment.Data, Section);
137456c587adSSam Clegg       Segment.Alignment = Log2_32(Section.getAlignment());
13752e150409SThomas Lively       Segment.LinkerFlags = 0;
1376759631c7SSam Clegg       DataSize += Segment.Data.size();
13776c899ba6SSam Clegg       Section.setSegmentIndex(SegmentIndex);
1378ea7caceeSSam Clegg 
1379ea7caceeSSam Clegg       if (const MCSymbolWasm *C = Section.getGroup()) {
1380ea7caceeSSam Clegg         Comdats[C->getName()].emplace_back(
1381329e76d5SSam Clegg             WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
1382ea7caceeSSam Clegg       }
13834d57fbd0SSam Clegg     } else {
13844d57fbd0SSam Clegg       // Create custom sections
13854d57fbd0SSam Clegg       assert(Sec.getKind().isMetadata());
13864d57fbd0SSam Clegg 
13874d57fbd0SSam Clegg       StringRef Name = SectionName;
13884d57fbd0SSam Clegg 
13894d57fbd0SSam Clegg       // For user-defined custom sections, strip the prefix
13904d57fbd0SSam Clegg       if (Name.startswith(".custom_section."))
13914d57fbd0SSam Clegg         Name = Name.substr(strlen(".custom_section."));
13924d57fbd0SSam Clegg 
13934d57fbd0SSam Clegg       MCSymbol *Begin = Sec.getBeginSymbol();
1394fb807d4dSSam Clegg       if (Begin) {
13954d57fbd0SSam Clegg         WasmIndices[cast<MCSymbolWasm>(Begin)] = CustomSections.size();
1396b210c64bSSam Clegg         if (SectionName != Begin->getName())
1397fb807d4dSSam Clegg           report_fatal_error("section name and begin symbol should match: " +
1398b210c64bSSam Clegg                              Twine(SectionName));
1399fb807d4dSSam Clegg       }
1400cbda16ebSThomas Lively 
1401f6f4f843SThomas Lively       // Separate out the producers and target features sections
1402cbda16ebSThomas Lively       if (Name == "producers") {
14030eaee545SJonas Devlieghere         ProducersSection = std::make_unique<WasmCustomSection>(Name, &Section);
1404cbda16ebSThomas Lively         continue;
1405cbda16ebSThomas Lively       }
1406f6f4f843SThomas Lively       if (Name == "target_features") {
1407f6f4f843SThomas Lively         TargetFeaturesSection =
14080eaee545SJonas Devlieghere             std::make_unique<WasmCustomSection>(Name, &Section);
1409f6f4f843SThomas Lively         continue;
1410f6f4f843SThomas Lively       }
1411cbda16ebSThomas Lively 
14124d57fbd0SSam Clegg       CustomSections.emplace_back(Name, &Section);
1413759631c7SSam Clegg     }
14146a31a0d6SSam Clegg   }
14156a31a0d6SSam Clegg 
1416586320c0SNicholas Wilson   // Populate WasmIndices and DataLocations for defined symbols.
1417d934cb88SDan Gohman   for (const MCSymbol &S : Asm.symbols()) {
1418d934cb88SDan Gohman     // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1419d934cb88SDan Gohman     // or used in relocations.
1420d934cb88SDan Gohman     if (S.isTemporary() && S.getName().empty())
1421d934cb88SDan Gohman       continue;
1422b7787fd0SSam Clegg 
1423d934cb88SDan Gohman     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1424d34e60caSNicola Zaghen     LLVM_DEBUG(
1425d34e60caSNicola Zaghen         dbgs() << "MCSymbol: " << toString(WS.getType()) << " '" << S << "'"
1426d34e60caSNicola Zaghen                << " isDefined=" << S.isDefined() << " isExternal="
1427d34e60caSNicola Zaghen                << S.isExternal() << " isTemporary=" << S.isTemporary()
1428d34e60caSNicola Zaghen                << " isWeak=" << WS.isWeak() << " isHidden=" << WS.isHidden()
1429b7787fd0SSam Clegg                << " isVariable=" << WS.isVariable() << "\n");
1430b7787fd0SSam Clegg 
14315e3d33a7SSam Clegg     if (WS.isVariable())
14325e3d33a7SSam Clegg       continue;
14336c899ba6SSam Clegg     if (WS.isComdat() && !WS.isDefined())
14346c899ba6SSam Clegg       continue;
1435b7787fd0SSam Clegg 
1436d934cb88SDan Gohman     if (WS.isFunction()) {
14376c899ba6SSam Clegg       unsigned Index;
1438cd65f698SSam Clegg       if (WS.isDefined()) {
1439b7787fd0SSam Clegg         if (WS.getOffset() != 0)
1440b7787fd0SSam Clegg           report_fatal_error(
1441b7787fd0SSam Clegg               "function sections must contain one function each");
1442b7787fd0SSam Clegg 
144318c56a07SHeejin Ahn         if (WS.getSize() == nullptr)
1444b7787fd0SSam Clegg           report_fatal_error(
1445b7787fd0SSam Clegg               "function symbols must have a size set with .size");
1446b7787fd0SSam Clegg 
14476c899ba6SSam Clegg         // A definition. Write out the function body.
14489f3fe42eSSam Clegg         Index = NumFunctionImports + Functions.size();
1449d934cb88SDan Gohman         WasmFunction Func;
1450da419bdbSHeejin Ahn         Func.SigIndex = getFunctionType(WS);
1451d934cb88SDan Gohman         Func.Sym = &WS;
14526c899ba6SSam Clegg         WasmIndices[&WS] = Index;
1453d934cb88SDan Gohman         Functions.push_back(Func);
14546c899ba6SSam Clegg 
14556c899ba6SSam Clegg         auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
14566c899ba6SSam Clegg         if (const MCSymbolWasm *C = Section.getGroup()) {
14576c899ba6SSam Clegg           Comdats[C->getName()].emplace_back(
14586c899ba6SSam Clegg               WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
14596c899ba6SSam Clegg         }
1460881d8778SSam Clegg 
1461881d8778SSam Clegg         if (WS.hasExportName()) {
1462881d8778SSam Clegg           wasm::WasmExport Export;
1463881d8778SSam Clegg           Export.Name = WS.getExportName();
1464881d8778SSam Clegg           Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1465881d8778SSam Clegg           Export.Index = Index;
1466881d8778SSam Clegg           Exports.push_back(Export);
1467881d8778SSam Clegg         }
1468d934cb88SDan Gohman       } else {
1469d934cb88SDan Gohman         // An import; the index was assigned above.
14706c899ba6SSam Clegg         Index = WasmIndices.find(&WS)->second;
1471d934cb88SDan Gohman       }
1472d934cb88SDan Gohman 
1473d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> function index: " << Index << "\n");
1474da419bdbSHeejin Ahn 
14756c899ba6SSam Clegg     } else if (WS.isData()) {
1476f3feb6adSWouter van Oortmerssen       if (!isInSymtab(WS))
1477c38e947eSSam Clegg         continue;
1478c38e947eSSam Clegg 
14796c899ba6SSam Clegg       if (!WS.isDefined()) {
1480d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "  -> segment index: -1"
1481d34e60caSNicola Zaghen                           << "\n");
1482fe6414b0SSam Clegg         continue;
14836c899ba6SSam Clegg       }
1484fe6414b0SSam Clegg 
1485d934cb88SDan Gohman       if (!WS.getSize())
1486c38e947eSSam Clegg         report_fatal_error("data symbols must have a size set with .size: " +
1487c38e947eSSam Clegg                            WS.getName());
1488d934cb88SDan Gohman 
1489d934cb88SDan Gohman       int64_t Size = 0;
1490d934cb88SDan Gohman       if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1491d934cb88SDan Gohman         report_fatal_error(".size expression must be evaluatable");
1492d934cb88SDan Gohman 
1493759631c7SSam Clegg       auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
1494079cba04SSam Clegg       if (!DataSection.isWasmData())
1495079cba04SSam Clegg         report_fatal_error("data symbols must live in a data section: " +
1496079cba04SSam Clegg                            WS.getName());
14977c395943SSam Clegg 
14986c899ba6SSam Clegg       // For each data symbol, export it in the symtab as a reference to the
14996c899ba6SSam Clegg       // corresponding Wasm data segment.
15006c899ba6SSam Clegg       wasm::WasmDataReference Ref = wasm::WasmDataReference{
15013b29376eSWouter van Oortmerssen           DataSection.getSegmentIndex(), Layout.getSymbolOffset(WS),
15023b29376eSWouter van Oortmerssen           static_cast<uint64_t>(Size)};
15036c899ba6SSam Clegg       DataLocations[&WS] = Ref;
1504d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> segment index: " << Ref.Segment << "\n");
1505da419bdbSHeejin Ahn 
1506a165f2d6SSam Clegg     } else if (WS.isGlobal()) {
15076c899ba6SSam Clegg       // A "true" Wasm global (currently just __stack_pointer)
15080a6c4d8dSSam Clegg       if (WS.isDefined()) {
15090a6c4d8dSSam Clegg         assert(WasmIndices.count(&WS) == 0);
15100a6c4d8dSSam Clegg         wasm::WasmGlobal Global;
15110a6c4d8dSSam Clegg         Global.Type = WS.getGlobalType();
15120a6c4d8dSSam Clegg         Global.Index = NumGlobalImports + Globals.size();
15130a6c4d8dSSam Clegg         switch (Global.Type.Type) {
15140a6c4d8dSSam Clegg         case wasm::WASM_TYPE_I32:
15150a6c4d8dSSam Clegg           Global.InitExpr.Opcode = wasm::WASM_OPCODE_I32_CONST;
15160a6c4d8dSSam Clegg           break;
15170a6c4d8dSSam Clegg         case wasm::WASM_TYPE_I64:
15180a6c4d8dSSam Clegg           Global.InitExpr.Opcode = wasm::WASM_OPCODE_I64_CONST;
15190a6c4d8dSSam Clegg           break;
15200a6c4d8dSSam Clegg         case wasm::WASM_TYPE_F32:
15210a6c4d8dSSam Clegg           Global.InitExpr.Opcode = wasm::WASM_OPCODE_F32_CONST;
15220a6c4d8dSSam Clegg           break;
15230a6c4d8dSSam Clegg         case wasm::WASM_TYPE_F64:
15240a6c4d8dSSam Clegg           Global.InitExpr.Opcode = wasm::WASM_OPCODE_F64_CONST;
15250a6c4d8dSSam Clegg           break;
152679aad89dSSam Clegg         case wasm::WASM_TYPE_EXTERNREF:
152779aad89dSSam Clegg           Global.InitExpr.Opcode = wasm::WASM_OPCODE_REF_NULL;
152879aad89dSSam Clegg           break;
15290a6c4d8dSSam Clegg         default:
15300a6c4d8dSSam Clegg           llvm_unreachable("unexpected type");
15310a6c4d8dSSam Clegg         }
15320a6c4d8dSSam Clegg         WasmIndices[&WS] = Global.Index;
15330a6c4d8dSSam Clegg         Globals.push_back(Global);
15340a6c4d8dSSam Clegg       } else {
1535545932beSEric Christopher         // An import; the index was assigned above
1536d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "  -> global index: "
1537d34e60caSNicola Zaghen                           << WasmIndices.find(&WS)->second << "\n");
15380a6c4d8dSSam Clegg       }
1539da419bdbSHeejin Ahn     } else if (WS.isEvent()) {
1540da419bdbSHeejin Ahn       // C++ exception symbol (__cpp_exception)
1541da419bdbSHeejin Ahn       unsigned Index;
1542da419bdbSHeejin Ahn       if (WS.isDefined()) {
15430a6c4d8dSSam Clegg         assert(WasmIndices.count(&WS) == 0);
1544da419bdbSHeejin Ahn         Index = NumEventImports + Events.size();
1545da419bdbSHeejin Ahn         wasm::WasmEventType Event;
1546da419bdbSHeejin Ahn         Event.SigIndex = getEventType(WS);
1547da419bdbSHeejin Ahn         Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
1548da419bdbSHeejin Ahn         WasmIndices[&WS] = Index;
1549da419bdbSHeejin Ahn         Events.push_back(Event);
1550da419bdbSHeejin Ahn       } else {
1551da419bdbSHeejin Ahn         // An import; the index was assigned above.
1552492f7529SSam Clegg         assert(WasmIndices.count(&WS) > 0);
1553da419bdbSHeejin Ahn       }
1554da419bdbSHeejin Ahn       LLVM_DEBUG(dbgs() << "  -> event index: " << WasmIndices.find(&WS)->second
1555da419bdbSHeejin Ahn                         << "\n");
1556da419bdbSHeejin Ahn 
1557a165f2d6SSam Clegg     } else {
1558a165f2d6SSam Clegg       assert(WS.isSection());
1559d934cb88SDan Gohman     }
1560d934cb88SDan Gohman   }
1561d934cb88SDan Gohman 
1562586320c0SNicholas Wilson   // Populate WasmIndices and DataLocations for aliased symbols.  We need to
1563586320c0SNicholas Wilson   // process these in a separate pass because we need to have processed the
1564586320c0SNicholas Wilson   // target of the alias before the alias itself and the symbols are not
1565586320c0SNicholas Wilson   // necessarily ordered in this way.
1566b7787fd0SSam Clegg   for (const MCSymbol &S : Asm.symbols()) {
1567b7787fd0SSam Clegg     if (!S.isVariable())
1568b7787fd0SSam Clegg       continue;
156931a2c809SSam Clegg 
1570cd65f698SSam Clegg     assert(S.isDefined());
1571b7787fd0SSam Clegg 
1572*9c7b5808SDominic Chen     const auto *BS = Layout.getBaseSymbol(S);
1573*9c7b5808SDominic Chen     if (!BS)
1574*9c7b5808SDominic Chen       report_fatal_error(Twine(S.getName()) +
1575*9c7b5808SDominic Chen                          ": absolute addressing not supported!");
1576*9c7b5808SDominic Chen     const MCSymbolWasm *Base = cast<MCSymbolWasm>(BS);
15777ee758d6SSam Clegg 
15785e3d33a7SSam Clegg     // Find the target symbol of this weak alias and export that index
1579aff1c4dfSSam Clegg     const auto &WS = static_cast<const MCSymbolWasm &>(S);
15807ee758d6SSam Clegg     LLVM_DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *Base << "'\n");
1581b7787fd0SSam Clegg 
15827ee758d6SSam Clegg     if (Base->isFunction()) {
15837ee758d6SSam Clegg       assert(WasmIndices.count(Base) > 0);
15847ee758d6SSam Clegg       uint32_t WasmIndex = WasmIndices.find(Base)->second;
1585492f7529SSam Clegg       assert(WasmIndices.count(&WS) == 0);
15866c899ba6SSam Clegg       WasmIndices[&WS] = WasmIndex;
1587d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> index:" << WasmIndex << "\n");
15887ee758d6SSam Clegg     } else if (Base->isData()) {
15897ee758d6SSam Clegg       auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
15907ee758d6SSam Clegg       uint64_t Offset = Layout.getSymbolOffset(S);
15917ee758d6SSam Clegg       int64_t Size = 0;
15927ee758d6SSam Clegg       // For data symbol alias we use the size of the base symbol as the
15937ee758d6SSam Clegg       // size of the alias.  When an offset from the base is involved this
15947ee758d6SSam Clegg       // can result in a offset + size goes past the end of the data section
15957ee758d6SSam Clegg       // which out object format doesn't support.  So we must clamp it.
15967ee758d6SSam Clegg       if (!Base->getSize()->evaluateAsAbsolute(Size, Layout))
15977ee758d6SSam Clegg         report_fatal_error(".size expression must be evaluatable");
15987ee758d6SSam Clegg       const WasmDataSegment &Segment =
15997ee758d6SSam Clegg           DataSegments[DataSection.getSegmentIndex()];
16007ee758d6SSam Clegg       Size =
16017ee758d6SSam Clegg           std::min(static_cast<uint64_t>(Size), Segment.Data.size() - Offset);
16027ee758d6SSam Clegg       wasm::WasmDataReference Ref = wasm::WasmDataReference{
16037ee758d6SSam Clegg           DataSection.getSegmentIndex(),
16047ee758d6SSam Clegg           static_cast<uint32_t>(Layout.getSymbolOffset(S)),
16057ee758d6SSam Clegg           static_cast<uint32_t>(Size)};
16066c899ba6SSam Clegg       DataLocations[&WS] = Ref;
1607d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> index:" << Ref.Segment << "\n");
16086c899ba6SSam Clegg     } else {
1609da419bdbSHeejin Ahn       report_fatal_error("don't yet support global/event aliases");
16106c899ba6SSam Clegg     }
1611586320c0SNicholas Wilson   }
161231a2c809SSam Clegg 
1613586320c0SNicholas Wilson   // Finally, populate the symbol table itself, in its "natural" order.
1614586320c0SNicholas Wilson   for (const MCSymbol &S : Asm.symbols()) {
1615586320c0SNicholas Wilson     const auto &WS = static_cast<const MCSymbolWasm &>(S);
161625d8e68bSSam Clegg     if (!isInSymtab(WS)) {
161718c56a07SHeejin Ahn       WS.setIndex(InvalidIndex);
1618586320c0SNicholas Wilson       continue;
161925d8e68bSSam Clegg     }
1620d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "adding to symtab: " << WS << "\n");
1621586320c0SNicholas Wilson 
1622586320c0SNicholas Wilson     uint32_t Flags = 0;
1623586320c0SNicholas Wilson     if (WS.isWeak())
1624586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_BINDING_WEAK;
1625586320c0SNicholas Wilson     if (WS.isHidden())
1626586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN;
1627586320c0SNicholas Wilson     if (!WS.isExternal() && WS.isDefined())
1628586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;
1629586320c0SNicholas Wilson     if (WS.isUndefined())
1630586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_UNDEFINED;
1631da84b688SDan Gohman     if (WS.isNoStrip()) {
1632da84b688SDan Gohman       Flags |= wasm::WASM_SYMBOL_NO_STRIP;
1633da84b688SDan Gohman       if (isEmscripten()) {
1634d6ef8da3SSam Clegg         Flags |= wasm::WASM_SYMBOL_EXPORTED;
1635da84b688SDan Gohman       }
1636da84b688SDan Gohman     }
1637b4f4e370SSam Clegg     if (WS.hasImportName())
163829874ceaSDan Gohman       Flags |= wasm::WASM_SYMBOL_EXPLICIT_NAME;
1639881d8778SSam Clegg     if (WS.hasExportName())
1640881d8778SSam Clegg       Flags |= wasm::WASM_SYMBOL_EXPORTED;
1641586320c0SNicholas Wilson 
1642586320c0SNicholas Wilson     wasm::WasmSymbolInfo Info;
1643586320c0SNicholas Wilson     Info.Name = WS.getName();
1644586320c0SNicholas Wilson     Info.Kind = WS.getType();
1645586320c0SNicholas Wilson     Info.Flags = Flags;
16464d57fbd0SSam Clegg     if (!WS.isData()) {
16474d57fbd0SSam Clegg       assert(WasmIndices.count(&WS) > 0);
1648586320c0SNicholas Wilson       Info.ElementIndex = WasmIndices.find(&WS)->second;
16494d57fbd0SSam Clegg     } else if (WS.isDefined()) {
16504d57fbd0SSam Clegg       assert(DataLocations.count(&WS) > 0);
1651586320c0SNicholas Wilson       Info.DataRef = DataLocations.find(&WS)->second;
16524d57fbd0SSam Clegg     }
165325d8e68bSSam Clegg     WS.setIndex(SymbolInfos.size());
1654586320c0SNicholas Wilson     SymbolInfos.emplace_back(Info);
1655b7787fd0SSam Clegg   }
1656b7787fd0SSam Clegg 
16576006e091SSam Clegg   {
16586006e091SSam Clegg     auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
1659f9edbe95SSam Clegg       // Functions referenced by a relocation need to put in the table.  This is
1660f9edbe95SSam Clegg       // purely to make the object file's provisional values readable, and is
1661f9edbe95SSam Clegg       // ignored by the linker, which re-calculates the relocations itself.
1662d1152a26SSam Clegg       if (Rel.Type != wasm::R_WASM_TABLE_INDEX_I32 &&
1663cc1b9b68SWouter van Oortmerssen           Rel.Type != wasm::R_WASM_TABLE_INDEX_I64 &&
166481443ac1SSam Clegg           Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB &&
1665cc1b9b68SWouter van Oortmerssen           Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB64 &&
166681443ac1SSam Clegg           Rel.Type != wasm::R_WASM_TABLE_INDEX_REL_SLEB)
1667f9edbe95SSam Clegg         return;
1668f9edbe95SSam Clegg       assert(Rel.Symbol->isFunction());
16697ee758d6SSam Clegg       const MCSymbolWasm *Base =
16707ee758d6SSam Clegg           cast<MCSymbolWasm>(Layout.getBaseSymbol(*Rel.Symbol));
16717ee758d6SSam Clegg       uint32_t FunctionIndex = WasmIndices.find(Base)->second;
167218c56a07SHeejin Ahn       uint32_t TableIndex = TableElems.size() + InitialTableOffset;
16737ee758d6SSam Clegg       if (TableIndices.try_emplace(Base, TableIndex).second) {
16747ee758d6SSam Clegg         LLVM_DEBUG(dbgs() << "  -> adding " << Base->getName()
1675f9edbe95SSam Clegg                           << " to table: " << TableIndex << "\n");
16766c899ba6SSam Clegg         TableElems.push_back(FunctionIndex);
16777ee758d6SSam Clegg         registerFunctionType(*Base);
16786006e091SSam Clegg       }
16796006e091SSam Clegg     };
1680970d02c4SDan Gohman 
16816006e091SSam Clegg     for (const WasmRelocationEntry &RelEntry : CodeRelocations)
16826006e091SSam Clegg       HandleReloc(RelEntry);
16836006e091SSam Clegg     for (const WasmRelocationEntry &RelEntry : DataRelocations)
16846006e091SSam Clegg       HandleReloc(RelEntry);
1685d934cb88SDan Gohman   }
1686d934cb88SDan Gohman 
1687bafe6902SSam Clegg   // Translate .init_array section contents into start functions.
1688bafe6902SSam Clegg   for (const MCSection &S : Asm) {
1689bafe6902SSam Clegg     const auto &WS = static_cast<const MCSectionWasm &>(S);
16907d1ff446SFangrui Song     if (WS.getName().startswith(".fini_array"))
1691bafe6902SSam Clegg       report_fatal_error(".fini_array sections are unsupported");
16927d1ff446SFangrui Song     if (!WS.getName().startswith(".init_array"))
1693bafe6902SSam Clegg       continue;
1694bafe6902SSam Clegg     if (WS.getFragmentList().empty())
1695bafe6902SSam Clegg       continue;
1696b210c64bSSam Clegg 
1697b210c64bSSam Clegg     // init_array is expected to contain a single non-empty data fragment
1698b210c64bSSam Clegg     if (WS.getFragmentList().size() != 3)
1699bafe6902SSam Clegg       report_fatal_error("only one .init_array section fragment supported");
1700b210c64bSSam Clegg 
1701b210c64bSSam Clegg     auto IT = WS.begin();
1702b210c64bSSam Clegg     const MCFragment &EmptyFrag = *IT;
1703b210c64bSSam Clegg     if (EmptyFrag.getKind() != MCFragment::FT_Data)
1704b210c64bSSam Clegg       report_fatal_error(".init_array section should be aligned");
1705b210c64bSSam Clegg 
1706b210c64bSSam Clegg     IT = std::next(IT);
1707b210c64bSSam Clegg     const MCFragment &AlignFrag = *IT;
1708bafe6902SSam Clegg     if (AlignFrag.getKind() != MCFragment::FT_Align)
1709bafe6902SSam Clegg       report_fatal_error(".init_array section should be aligned");
1710bafe6902SSam Clegg     if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
1711bafe6902SSam Clegg       report_fatal_error(".init_array section should be aligned for pointers");
1712b210c64bSSam Clegg 
1713b210c64bSSam Clegg     const MCFragment &Frag = *std::next(IT);
1714bafe6902SSam Clegg     if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1715bafe6902SSam Clegg       report_fatal_error("only data supported in .init_array section");
1716b210c64bSSam Clegg 
1717bafe6902SSam Clegg     uint16_t Priority = UINT16_MAX;
17184d57fbd0SSam Clegg     unsigned PrefixLength = strlen(".init_array");
17197d1ff446SFangrui Song     if (WS.getName().size() > PrefixLength) {
17207d1ff446SFangrui Song       if (WS.getName()[PrefixLength] != '.')
1721f208f631SHeejin Ahn         report_fatal_error(
1722f208f631SHeejin Ahn             ".init_array section priority should start with '.'");
17237d1ff446SFangrui Song       if (WS.getName().substr(PrefixLength + 1).getAsInteger(10, Priority))
1724bafe6902SSam Clegg         report_fatal_error("invalid .init_array section priority");
1725bafe6902SSam Clegg     }
1726bafe6902SSam Clegg     const auto &DataFrag = cast<MCDataFragment>(Frag);
1727bafe6902SSam Clegg     const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1728f208f631SHeejin Ahn     for (const uint8_t *
172918c56a07SHeejin Ahn              P = (const uint8_t *)Contents.data(),
173018c56a07SHeejin Ahn             *End = (const uint8_t *)Contents.data() + Contents.size();
173118c56a07SHeejin Ahn          P != End; ++P) {
173218c56a07SHeejin Ahn       if (*P != 0)
1733bafe6902SSam Clegg         report_fatal_error("non-symbolic data in .init_array section");
1734bafe6902SSam Clegg     }
1735bafe6902SSam Clegg     for (const MCFixup &Fixup : DataFrag.getFixups()) {
1736f208f631SHeejin Ahn       assert(Fixup.getKind() ==
1737f208f631SHeejin Ahn              MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
1738bafe6902SSam Clegg       const MCExpr *Expr = Fixup.getValue();
17398fffa1dfSSam Clegg       auto *SymRef = dyn_cast<MCSymbolRefExpr>(Expr);
17408fffa1dfSSam Clegg       if (!SymRef)
1741bafe6902SSam Clegg         report_fatal_error("fixups in .init_array should be symbol references");
17428fffa1dfSSam Clegg       const auto &TargetSym = cast<const MCSymbolWasm>(SymRef->getSymbol());
17438fffa1dfSSam Clegg       if (TargetSym.getIndex() == InvalidIndex)
17443ea1c62cSSam Clegg         report_fatal_error("symbols in .init_array should exist in symtab");
17458fffa1dfSSam Clegg       if (!TargetSym.isFunction())
17468fffa1dfSSam Clegg         report_fatal_error("symbols in .init_array should be for functions");
174725d8e68bSSam Clegg       InitFuncs.push_back(
17488fffa1dfSSam Clegg           std::make_pair(Priority, TargetSym.getIndex()));
1749bafe6902SSam Clegg     }
1750bafe6902SSam Clegg   }
1751bafe6902SSam Clegg 
175218eafb6cSDan Gohman   // Write out the Wasm header.
175318eafb6cSDan Gohman   writeHeader(Asm);
175418eafb6cSDan Gohman 
17550ff28fa6SDerek Schuff   uint32_t CodeSectionIndex, DataSectionIndex;
17560ff28fa6SDerek Schuff   if (Mode != DwoMode::DwoOnly) {
1757da419bdbSHeejin Ahn     writeTypeSection(Signatures);
1758f950b24aSSam Clegg     writeImportSection(Imports, DataSize, TableElems.size());
17599e15f359SSam Clegg     writeFunctionSection(Functions);
1760f950b24aSSam Clegg     // Skip the "table" section; we import the table instead.
1761f950b24aSSam Clegg     // Skip the "memory" section; we import the memory instead.
1762da419bdbSHeejin Ahn     writeEventSection(Events);
17630a6c4d8dSSam Clegg     writeGlobalSection(Globals);
17649e15f359SSam Clegg     writeExportSection(Exports);
17659e15f359SSam Clegg     writeElemSection(TableElems);
1766fef8de66SThomas Lively     writeDataCountSection();
17670ff28fa6SDerek Schuff 
17680ff28fa6SDerek Schuff     CodeSectionIndex = writeCodeSection(Asm, Layout, Functions);
17690ff28fa6SDerek Schuff     DataSectionIndex = writeDataSection(Layout);
17700ff28fa6SDerek Schuff   }
17710ff28fa6SDerek Schuff 
17720ff28fa6SDerek Schuff   for (auto &CustomSection : CustomSections) {
1773cbda16ebSThomas Lively     writeCustomSection(CustomSection, Asm, Layout);
17740ff28fa6SDerek Schuff   }
17750ff28fa6SDerek Schuff 
17760ff28fa6SDerek Schuff   if (Mode != DwoMode::DwoOnly) {
1777c22bfb6bSNicholas Wilson     writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats);
17780ff28fa6SDerek Schuff 
17796f08c84aSSam Clegg     writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations);
17806f08c84aSSam Clegg     writeRelocSection(DataSectionIndex, "DATA", DataRelocations);
17810ff28fa6SDerek Schuff   }
17826a31a0d6SSam Clegg   writeCustomRelocSections();
1783cbda16ebSThomas Lively   if (ProducersSection)
1784cbda16ebSThomas Lively     writeCustomSection(*ProducersSection, Asm, Layout);
1785f6f4f843SThomas Lively   if (TargetFeaturesSection)
1786f6f4f843SThomas Lively     writeCustomSection(*TargetFeaturesSection, Asm, Layout);
1787970d02c4SDan Gohman 
1788d934cb88SDan Gohman   // TODO: Translate the .comment section to the output.
17890ff28fa6SDerek Schuff   return W->OS.tell() - StartOffset;
179018eafb6cSDan Gohman }
179118eafb6cSDan Gohman 
179260fbc7ccSLang Hames std::unique_ptr<MCObjectWriter>
17931301a878SLang Hames llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
179418eafb6cSDan Gohman                              raw_pwrite_stream &OS) {
17950eaee545SJonas Devlieghere   return std::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
179618eafb6cSDan Gohman }
17970ff28fa6SDerek Schuff 
17980ff28fa6SDerek Schuff std::unique_ptr<MCObjectWriter>
17990ff28fa6SDerek Schuff llvm::createWasmDwoObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
18000ff28fa6SDerek Schuff                                 raw_pwrite_stream &OS,
18010ff28fa6SDerek Schuff                                 raw_pwrite_stream &DwoOS) {
18020ff28fa6SDerek Schuff   return std::make_unique<WasmObjectWriter>(std::move(MOTW), OS, DwoOS);
18030ff28fa6SDerek Schuff }
1804