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 
219*0ff28fa6SDerek Schuff bool isDwoSection(const MCSection &Sec) {
220*0ff28fa6SDerek Schuff   return Sec.getName().endswith(".dwo");
221*0ff28fa6SDerek Schuff }
222*0ff28fa6SDerek Schuff 
22318eafb6cSDan Gohman class WasmObjectWriter : public MCObjectWriter {
224*0ff28fa6SDerek 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 
267*0ff28fa6SDerek Schuff   enum class DwoMode {
268*0ff28fa6SDerek Schuff     AllSections,
269*0ff28fa6SDerek Schuff     NonDwoOnly,
270*0ff28fa6SDerek Schuff     DwoOnly,
271*0ff28fa6SDerek Schuff   };
272*0ff28fa6SDerek Schuff   bool IsSplitDwarf = false;
273*0ff28fa6SDerek Schuff   raw_pwrite_stream *OS = nullptr;
274*0ff28fa6SDerek Schuff   raw_pwrite_stream *DwoOS = nullptr;
275*0ff28fa6SDerek Schuff 
276*0ff28fa6SDerek 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,
286*0ff28fa6SDerek Schuff                    raw_pwrite_stream &OS_)
287*0ff28fa6SDerek Schuff       : TargetObjectWriter(std::move(MOTW)), OS(&OS_) {}
288*0ff28fa6SDerek Schuff 
289*0ff28fa6SDerek Schuff   WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
290*0ff28fa6SDerek Schuff                    raw_pwrite_stream &OS_, raw_pwrite_stream &DwoOS_)
291*0ff28fa6SDerek Schuff       : TargetObjectWriter(std::move(MOTW)), IsSplitDwarf(true), OS(&OS_),
292*0ff28fa6SDerek 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;
324*0ff28fa6SDerek Schuff   void prepareImports(SmallVectorImpl<wasm::WasmImport> &Imports,
325*0ff28fa6SDerek Schuff                       MCAssembler &Asm, const MCAsmLayout &Layout);
326438390faSPeter Collingbourne   uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
3279e15f359SSam Clegg 
328*0ff28fa6SDerek Schuff   uint64_t writeOneObject(MCAssembler &Asm, const MCAsmLayout &Layout,
329*0ff28fa6SDerek Schuff                           DwoMode Mode);
330*0ff28fa6SDerek Schuff 
331b7787fd0SSam Clegg   void writeString(const StringRef Str) {
332*0ff28fa6SDerek Schuff     encodeULEB128(Str.size(), W->OS);
333*0ff28fa6SDerek 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);
339*0ff28fa6SDerek 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);
345*0ff28fa6SDerek Schuff     W->OS.write(Buffer, sizeof(Buffer));
3460a6c4d8dSSam Clegg   }
3470a6c4d8dSSam Clegg 
348*0ff28fa6SDerek 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");
393*0ff28fa6SDerek Schuff   W->OS << char(SectionId);
394d934cb88SDan Gohman 
395*0ff28fa6SDerek 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.
399*0ff28fa6SDerek Schuff   encodeULEB128(0, W->OS, 5);
400d934cb88SDan Gohman 
401d934cb88SDan Gohman   // The position where the section starts, for measuring its size.
402*0ff28fa6SDerek Schuff   Section.ContentsOffset = W->OS.tell();
403*0ff28fa6SDerek 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.
413*0ff28fa6SDerek 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.
419*0ff28fa6SDerek 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) {
425*0ff28fa6SDerek 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.
439*0ff28fa6SDerek 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) {
445*0ff28fa6SDerek Schuff   W->OS.write(wasm::WasmMagic, sizeof(wasm::WasmMagic));
446*0ff28fa6SDerek 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: {
617f9edbe95SSam Clegg     // Provisional value is address of the global
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;
6237ee758d6SSam Clegg     const wasm::WasmDataReference &Ref = DataLocations[Base];
6246c899ba6SSam Clegg     const WasmDataSegment &Segment = DataSegments[Ref.Segment];
625d934cb88SDan Gohman     // Ignore overflow. LLVM allows address arithmetic to silently wrap.
6266c899ba6SSam Clegg     return Segment.Offset + Ref.Offset + RelEntry.Addend;
62760ec3034SSam Clegg   }
62860ec3034SSam Clegg   default:
62960ec3034SSam Clegg     llvm_unreachable("invalid relocation type");
63060ec3034SSam Clegg   }
631d934cb88SDan Gohman }
632d934cb88SDan Gohman 
633759631c7SSam Clegg static void addData(SmallVectorImpl<char> &DataBytes,
63463ebb813SSam Clegg                     MCSectionWasm &DataSection) {
6357d1ff446SFangrui Song   LLVM_DEBUG(errs() << "addData: " << DataSection.getName() << "\n");
636759631c7SSam Clegg 
63763ebb813SSam Clegg   DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
63863ebb813SSam Clegg 
639759631c7SSam Clegg   for (const MCFragment &Frag : DataSection) {
640759631c7SSam Clegg     if (Frag.hasInstructions())
641759631c7SSam Clegg       report_fatal_error("only data supported in data sections");
642759631c7SSam Clegg 
643759631c7SSam Clegg     if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
644759631c7SSam Clegg       if (Align->getValueSize() != 1)
645759631c7SSam Clegg         report_fatal_error("only byte values supported for alignment");
646759631c7SSam Clegg       // If nops are requested, use zeros, as this is the data section.
647759631c7SSam Clegg       uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
648f208f631SHeejin Ahn       uint64_t Size =
649f208f631SHeejin Ahn           std::min<uint64_t>(alignTo(DataBytes.size(), Align->getAlignment()),
650f208f631SHeejin Ahn                              DataBytes.size() + Align->getMaxBytesToEmit());
651759631c7SSam Clegg       DataBytes.resize(Size, Value);
652759631c7SSam Clegg     } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
653588fad4dSNirav Dave       int64_t NumValues;
654588fad4dSNirav Dave       if (!Fill->getNumValues().evaluateAsAbsolute(NumValues))
655d707c370SRafael Espindola         llvm_unreachable("The fill should be an assembler constant");
656588fad4dSNirav Dave       DataBytes.insert(DataBytes.end(), Fill->getValueSize() * NumValues,
657588fad4dSNirav Dave                        Fill->getValue());
65824faf859SHeejin Ahn     } else if (auto *LEB = dyn_cast<MCLEBFragment>(&Frag)) {
65924faf859SHeejin Ahn       const SmallVectorImpl<char> &Contents = LEB->getContents();
66024faf859SHeejin Ahn       DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
661759631c7SSam Clegg     } else {
662759631c7SSam Clegg       const auto &DataFrag = cast<MCDataFragment>(Frag);
663759631c7SSam Clegg       const SmallVectorImpl<char> &Contents = DataFrag.getContents();
664759631c7SSam Clegg       DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
665759631c7SSam Clegg     }
666759631c7SSam Clegg   }
667759631c7SSam Clegg 
668d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
669759631c7SSam Clegg }
670759631c7SSam Clegg 
67160ec3034SSam Clegg uint32_t
67260ec3034SSam Clegg WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
673d1152a26SSam Clegg   if (RelEntry.Type == wasm::R_WASM_TYPE_INDEX_LEB) {
674b7787fd0SSam Clegg     if (!TypeIndices.count(RelEntry.Symbol))
675b7787fd0SSam Clegg       report_fatal_error("symbol not found in type index space: " +
676b7787fd0SSam Clegg                          RelEntry.Symbol->getName());
677acd7d2b0SSam Clegg     return TypeIndices[RelEntry.Symbol];
678acd7d2b0SSam Clegg   }
67960ec3034SSam Clegg 
68025d8e68bSSam Clegg   return RelEntry.Symbol->getIndex();
681acd7d2b0SSam Clegg }
682acd7d2b0SSam Clegg 
683d934cb88SDan Gohman // Apply the portions of the relocation records that we can handle ourselves
684d934cb88SDan Gohman // directly.
685acd7d2b0SSam Clegg void WasmObjectWriter::applyRelocations(
6867ee758d6SSam Clegg     ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset,
6877ee758d6SSam Clegg     const MCAsmLayout &Layout) {
688*0ff28fa6SDerek Schuff   auto &Stream = static_cast<raw_pwrite_stream &>(W->OS);
689d934cb88SDan Gohman   for (const WasmRelocationEntry &RelEntry : Relocations) {
690d934cb88SDan Gohman     uint64_t Offset = ContentsOffset +
691d934cb88SDan Gohman                       RelEntry.FixupSection->getSectionOffset() +
692d934cb88SDan Gohman                       RelEntry.Offset;
693d934cb88SDan Gohman 
694d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
6957ee758d6SSam Clegg     auto Value = getProvisionalValue(RelEntry, Layout);
69660ec3034SSam Clegg 
697acd7d2b0SSam Clegg     switch (RelEntry.Type) {
698d1152a26SSam Clegg     case wasm::R_WASM_FUNCTION_INDEX_LEB:
699d1152a26SSam Clegg     case wasm::R_WASM_TYPE_INDEX_LEB:
700d1152a26SSam Clegg     case wasm::R_WASM_GLOBAL_INDEX_LEB:
701d1152a26SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_LEB:
702d1152a26SSam Clegg     case wasm::R_WASM_EVENT_INDEX_LEB:
7033b29376eSWouter van Oortmerssen       writePatchableLEB<5>(Stream, Value, Offset);
7043b29376eSWouter van Oortmerssen       break;
7053b29376eSWouter van Oortmerssen     case wasm::R_WASM_MEMORY_ADDR_LEB64:
7063b29376eSWouter van Oortmerssen       writePatchableLEB<10>(Stream, Value, Offset);
707d934cb88SDan Gohman       break;
708d1152a26SSam Clegg     case wasm::R_WASM_TABLE_INDEX_I32:
709d1152a26SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_I32:
710d1152a26SSam Clegg     case wasm::R_WASM_FUNCTION_OFFSET_I32:
711d1152a26SSam Clegg     case wasm::R_WASM_SECTION_OFFSET_I32:
71248139ebcSWouter van Oortmerssen     case wasm::R_WASM_GLOBAL_INDEX_I32:
7130a6c4d8dSSam Clegg       patchI32(Stream, Value, Offset);
714d934cb88SDan Gohman       break;
715cc1b9b68SWouter van Oortmerssen     case wasm::R_WASM_TABLE_INDEX_I64:
7163b29376eSWouter van Oortmerssen     case wasm::R_WASM_MEMORY_ADDR_I64:
7173b29376eSWouter van Oortmerssen       patchI64(Stream, Value, Offset);
7183b29376eSWouter van Oortmerssen       break;
719d1152a26SSam Clegg     case wasm::R_WASM_TABLE_INDEX_SLEB:
7202a7cac93SSam Clegg     case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
721d1152a26SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_SLEB:
7222a7cac93SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
7233b29376eSWouter van Oortmerssen       writePatchableSLEB<5>(Stream, Value, Offset);
7243b29376eSWouter van Oortmerssen       break;
725cc1b9b68SWouter van Oortmerssen     case wasm::R_WASM_TABLE_INDEX_SLEB64:
7263b29376eSWouter van Oortmerssen     case wasm::R_WASM_MEMORY_ADDR_SLEB64:
7273b29376eSWouter van Oortmerssen     case wasm::R_WASM_MEMORY_ADDR_REL_SLEB64:
7283b29376eSWouter van Oortmerssen       writePatchableSLEB<10>(Stream, Value, Offset);
72960ec3034SSam Clegg       break;
730d934cb88SDan Gohman     default:
7319d24fb7fSSam Clegg       llvm_unreachable("invalid relocation type");
732d934cb88SDan Gohman     }
733d934cb88SDan Gohman   }
73418eafb6cSDan Gohman }
73518eafb6cSDan Gohman 
736da419bdbSHeejin Ahn void WasmObjectWriter::writeTypeSection(ArrayRef<WasmSignature> Signatures) {
737da419bdbSHeejin Ahn   if (Signatures.empty())
7389e15f359SSam Clegg     return;
7399e15f359SSam Clegg 
7409e15f359SSam Clegg   SectionBookkeeping Section;
7419e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_TYPE);
7429e15f359SSam Clegg 
743*0ff28fa6SDerek Schuff   encodeULEB128(Signatures.size(), W->OS);
7449e15f359SSam Clegg 
745da419bdbSHeejin Ahn   for (const WasmSignature &Sig : Signatures) {
746*0ff28fa6SDerek Schuff     W->OS << char(wasm::WASM_TYPE_FUNC);
747*0ff28fa6SDerek Schuff     encodeULEB128(Sig.Params.size(), W->OS);
748da419bdbSHeejin Ahn     for (wasm::ValType Ty : Sig.Params)
7499e15f359SSam Clegg       writeValueType(Ty);
750*0ff28fa6SDerek Schuff     encodeULEB128(Sig.Returns.size(), W->OS);
751da419bdbSHeejin Ahn     for (wasm::ValType Ty : Sig.Returns)
7529e15f359SSam Clegg       writeValueType(Ty);
7539e15f359SSam Clegg   }
7549e15f359SSam Clegg 
7559e15f359SSam Clegg   endSection(Section);
7569e15f359SSam Clegg }
7579e15f359SSam Clegg 
7588defa952SSam Clegg void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports,
7594d135b04SWouter van Oortmerssen                                           uint64_t DataSize,
760f950b24aSSam Clegg                                           uint32_t NumElements) {
7619e15f359SSam Clegg   if (Imports.empty())
7629e15f359SSam Clegg     return;
7639e15f359SSam Clegg 
7644d135b04SWouter van Oortmerssen   uint64_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
765f950b24aSSam Clegg 
7669e15f359SSam Clegg   SectionBookkeeping Section;
7679e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_IMPORT);
7689e15f359SSam Clegg 
769*0ff28fa6SDerek Schuff   encodeULEB128(Imports.size(), W->OS);
7708defa952SSam Clegg   for (const wasm::WasmImport &Import : Imports) {
7718defa952SSam Clegg     writeString(Import.Module);
7728defa952SSam Clegg     writeString(Import.Field);
773*0ff28fa6SDerek Schuff     W->OS << char(Import.Kind);
7749e15f359SSam Clegg 
7759e15f359SSam Clegg     switch (Import.Kind) {
7769e15f359SSam Clegg     case wasm::WASM_EXTERNAL_FUNCTION:
777*0ff28fa6SDerek Schuff       encodeULEB128(Import.SigIndex, W->OS);
7789e15f359SSam Clegg       break;
7799e15f359SSam Clegg     case wasm::WASM_EXTERNAL_GLOBAL:
780*0ff28fa6SDerek Schuff       W->OS << char(Import.Global.Type);
781*0ff28fa6SDerek Schuff       W->OS << char(Import.Global.Mutable ? 1 : 0);
7829e15f359SSam Clegg       break;
783f950b24aSSam Clegg     case wasm::WASM_EXTERNAL_MEMORY:
784*0ff28fa6SDerek Schuff       encodeULEB128(Import.Memory.Flags, W->OS);
785*0ff28fa6SDerek Schuff       encodeULEB128(NumPages, W->OS); // initial
786f950b24aSSam Clegg       break;
787f950b24aSSam Clegg     case wasm::WASM_EXTERNAL_TABLE:
788*0ff28fa6SDerek Schuff       W->OS << char(Import.Table.ElemType);
789*0ff28fa6SDerek Schuff       encodeULEB128(0, W->OS);           // flags
790*0ff28fa6SDerek Schuff       encodeULEB128(NumElements, W->OS); // initial
791f950b24aSSam Clegg       break;
792da419bdbSHeejin Ahn     case wasm::WASM_EXTERNAL_EVENT:
793*0ff28fa6SDerek Schuff       encodeULEB128(Import.Event.Attribute, W->OS);
794*0ff28fa6SDerek Schuff       encodeULEB128(Import.Event.SigIndex, W->OS);
795da419bdbSHeejin Ahn       break;
7969e15f359SSam Clegg     default:
7979e15f359SSam Clegg       llvm_unreachable("unsupported import kind");
7989e15f359SSam Clegg     }
7999e15f359SSam Clegg   }
8009e15f359SSam Clegg 
8019e15f359SSam Clegg   endSection(Section);
8029e15f359SSam Clegg }
8039e15f359SSam Clegg 
804457fb0b4SSam Clegg void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
8059e15f359SSam Clegg   if (Functions.empty())
8069e15f359SSam Clegg     return;
8079e15f359SSam Clegg 
8089e15f359SSam Clegg   SectionBookkeeping Section;
8099e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_FUNCTION);
8109e15f359SSam Clegg 
811*0ff28fa6SDerek Schuff   encodeULEB128(Functions.size(), W->OS);
8129e15f359SSam Clegg   for (const WasmFunction &Func : Functions)
813*0ff28fa6SDerek Schuff     encodeULEB128(Func.SigIndex, W->OS);
8149e15f359SSam Clegg 
8159e15f359SSam Clegg   endSection(Section);
8169e15f359SSam Clegg }
8179e15f359SSam Clegg 
818da419bdbSHeejin Ahn void WasmObjectWriter::writeEventSection(ArrayRef<wasm::WasmEventType> Events) {
819da419bdbSHeejin Ahn   if (Events.empty())
820da419bdbSHeejin Ahn     return;
821da419bdbSHeejin Ahn 
822da419bdbSHeejin Ahn   SectionBookkeeping Section;
823da419bdbSHeejin Ahn   startSection(Section, wasm::WASM_SEC_EVENT);
824da419bdbSHeejin Ahn 
825*0ff28fa6SDerek Schuff   encodeULEB128(Events.size(), W->OS);
826da419bdbSHeejin Ahn   for (const wasm::WasmEventType &Event : Events) {
827*0ff28fa6SDerek Schuff     encodeULEB128(Event.Attribute, W->OS);
828*0ff28fa6SDerek Schuff     encodeULEB128(Event.SigIndex, W->OS);
829da419bdbSHeejin Ahn   }
830da419bdbSHeejin Ahn 
831da419bdbSHeejin Ahn   endSection(Section);
832da419bdbSHeejin Ahn }
833da419bdbSHeejin Ahn 
8340a6c4d8dSSam Clegg void WasmObjectWriter::writeGlobalSection(ArrayRef<wasm::WasmGlobal> Globals) {
8350a6c4d8dSSam Clegg   if (Globals.empty())
8360a6c4d8dSSam Clegg     return;
8370a6c4d8dSSam Clegg 
8380a6c4d8dSSam Clegg   SectionBookkeeping Section;
8390a6c4d8dSSam Clegg   startSection(Section, wasm::WASM_SEC_GLOBAL);
8400a6c4d8dSSam Clegg 
841*0ff28fa6SDerek Schuff   encodeULEB128(Globals.size(), W->OS);
8420a6c4d8dSSam Clegg   for (const wasm::WasmGlobal &Global : Globals) {
843*0ff28fa6SDerek Schuff     encodeULEB128(Global.Type.Type, W->OS);
844*0ff28fa6SDerek Schuff     W->OS << char(Global.Type.Mutable);
845*0ff28fa6SDerek Schuff     W->OS << char(Global.InitExpr.Opcode);
8460a6c4d8dSSam Clegg     switch (Global.Type.Type) {
8470a6c4d8dSSam Clegg     case wasm::WASM_TYPE_I32:
848*0ff28fa6SDerek Schuff       encodeSLEB128(0, W->OS);
8490a6c4d8dSSam Clegg       break;
8500a6c4d8dSSam Clegg     case wasm::WASM_TYPE_I64:
851*0ff28fa6SDerek Schuff       encodeSLEB128(0, W->OS);
8520a6c4d8dSSam Clegg       break;
8530a6c4d8dSSam Clegg     case wasm::WASM_TYPE_F32:
8540a6c4d8dSSam Clegg       writeI32(0);
8550a6c4d8dSSam Clegg       break;
8560a6c4d8dSSam Clegg     case wasm::WASM_TYPE_F64:
8570a6c4d8dSSam Clegg       writeI64(0);
8580a6c4d8dSSam Clegg       break;
85979aad89dSSam Clegg     case wasm::WASM_TYPE_EXTERNREF:
86079aad89dSSam Clegg       writeValueType(wasm::ValType::EXTERNREF);
86179aad89dSSam Clegg       break;
8620a6c4d8dSSam Clegg     default:
8630a6c4d8dSSam Clegg       llvm_unreachable("unexpected type");
8640a6c4d8dSSam Clegg     }
865*0ff28fa6SDerek Schuff     W->OS << char(wasm::WASM_OPCODE_END);
8660a6c4d8dSSam Clegg   }
8670a6c4d8dSSam Clegg 
8680a6c4d8dSSam Clegg   endSection(Section);
8690a6c4d8dSSam Clegg }
8700a6c4d8dSSam Clegg 
8718defa952SSam Clegg void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) {
8729e15f359SSam Clegg   if (Exports.empty())
8739e15f359SSam Clegg     return;
8749e15f359SSam Clegg 
8759e15f359SSam Clegg   SectionBookkeeping Section;
8769e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_EXPORT);
8779e15f359SSam Clegg 
878*0ff28fa6SDerek Schuff   encodeULEB128(Exports.size(), W->OS);
8798defa952SSam Clegg   for (const wasm::WasmExport &Export : Exports) {
8808defa952SSam Clegg     writeString(Export.Name);
881*0ff28fa6SDerek Schuff     W->OS << char(Export.Kind);
882*0ff28fa6SDerek Schuff     encodeULEB128(Export.Index, W->OS);
8839e15f359SSam Clegg   }
8849e15f359SSam Clegg 
8859e15f359SSam Clegg   endSection(Section);
8869e15f359SSam Clegg }
8879e15f359SSam Clegg 
888457fb0b4SSam Clegg void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
8899e15f359SSam Clegg   if (TableElems.empty())
8909e15f359SSam Clegg     return;
8919e15f359SSam Clegg 
8929e15f359SSam Clegg   SectionBookkeeping Section;
8939e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_ELEM);
8949e15f359SSam Clegg 
895*0ff28fa6SDerek Schuff   encodeULEB128(1, W->OS); // number of "segments"
896*0ff28fa6SDerek Schuff   encodeULEB128(0, W->OS); // the table index
8979e15f359SSam Clegg 
8989e15f359SSam Clegg   // init expr for starting offset
899*0ff28fa6SDerek Schuff   W->OS << char(wasm::WASM_OPCODE_I32_CONST);
900*0ff28fa6SDerek Schuff   encodeSLEB128(InitialTableOffset, W->OS);
901*0ff28fa6SDerek Schuff   W->OS << char(wasm::WASM_OPCODE_END);
9029e15f359SSam Clegg 
903*0ff28fa6SDerek Schuff   encodeULEB128(TableElems.size(), W->OS);
9049e15f359SSam Clegg   for (uint32_t Elem : TableElems)
905*0ff28fa6SDerek Schuff     encodeULEB128(Elem, W->OS);
9069e15f359SSam Clegg 
9079e15f359SSam Clegg   endSection(Section);
9089e15f359SSam Clegg }
9099e15f359SSam Clegg 
910fef8de66SThomas Lively void WasmObjectWriter::writeDataCountSection() {
911fef8de66SThomas Lively   if (DataSegments.empty())
912fef8de66SThomas Lively     return;
913fef8de66SThomas Lively 
914fef8de66SThomas Lively   SectionBookkeeping Section;
915fef8de66SThomas Lively   startSection(Section, wasm::WASM_SEC_DATACOUNT);
916*0ff28fa6SDerek Schuff   encodeULEB128(DataSegments.size(), W->OS);
917fef8de66SThomas Lively   endSection(Section);
918fef8de66SThomas Lively }
919fef8de66SThomas Lively 
920e49584a3SSam Clegg uint32_t WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
921457fb0b4SSam Clegg                                             const MCAsmLayout &Layout,
922457fb0b4SSam Clegg                                             ArrayRef<WasmFunction> Functions) {
9239e15f359SSam Clegg   if (Functions.empty())
924e49584a3SSam Clegg     return 0;
9259e15f359SSam Clegg 
9269e15f359SSam Clegg   SectionBookkeeping Section;
9279e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_CODE);
9289e15f359SSam Clegg 
929*0ff28fa6SDerek Schuff   encodeULEB128(Functions.size(), W->OS);
9309e15f359SSam Clegg 
9319e15f359SSam Clegg   for (const WasmFunction &Func : Functions) {
932fe6414b0SSam Clegg     auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
9339e15f359SSam Clegg 
9349e15f359SSam Clegg     int64_t Size = 0;
9359e15f359SSam Clegg     if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
9369e15f359SSam Clegg       report_fatal_error(".size expression must be evaluatable");
9379e15f359SSam Clegg 
938*0ff28fa6SDerek Schuff     encodeULEB128(Size, W->OS);
939*0ff28fa6SDerek Schuff     FuncSection.setSectionOffset(W->OS.tell() - Section.ContentsOffset);
940*0ff28fa6SDerek Schuff     Asm.writeSectionData(W->OS, &FuncSection, Layout);
9419e15f359SSam Clegg   }
9429e15f359SSam Clegg 
9439e15f359SSam Clegg   // Apply fixups.
9447ee758d6SSam Clegg   applyRelocations(CodeRelocations, Section.ContentsOffset, Layout);
9459e15f359SSam Clegg 
9469e15f359SSam Clegg   endSection(Section);
947e49584a3SSam Clegg   return Section.Index;
9489e15f359SSam Clegg }
9499e15f359SSam Clegg 
950e49584a3SSam Clegg uint32_t WasmObjectWriter::writeDataSection(const MCAsmLayout &Layout) {
9516c899ba6SSam Clegg   if (DataSegments.empty())
952e49584a3SSam Clegg     return 0;
9539e15f359SSam Clegg 
9549e15f359SSam Clegg   SectionBookkeeping Section;
9559e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_DATA);
9569e15f359SSam Clegg 
957*0ff28fa6SDerek Schuff   encodeULEB128(DataSegments.size(), W->OS); // count
9587c395943SSam Clegg 
9596c899ba6SSam Clegg   for (const WasmDataSegment &Segment : DataSegments) {
960*0ff28fa6SDerek Schuff     encodeULEB128(Segment.InitFlags, W->OS); // flags
9612e150409SThomas Lively     if (Segment.InitFlags & wasm::WASM_SEGMENT_HAS_MEMINDEX)
962*0ff28fa6SDerek Schuff       encodeULEB128(0, W->OS); // memory index
9632e150409SThomas Lively     if ((Segment.InitFlags & wasm::WASM_SEGMENT_IS_PASSIVE) == 0) {
964*0ff28fa6SDerek Schuff       W->OS << char(Segment.Offset > INT32_MAX ? wasm::WASM_OPCODE_I64_CONST
9654d135b04SWouter van Oortmerssen                                                : wasm::WASM_OPCODE_I32_CONST);
966*0ff28fa6SDerek Schuff       encodeSLEB128(Segment.Offset, W->OS); // offset
967*0ff28fa6SDerek Schuff       W->OS << char(wasm::WASM_OPCODE_END);
9682e150409SThomas Lively     }
969*0ff28fa6SDerek Schuff     encodeULEB128(Segment.Data.size(), W->OS); // size
970*0ff28fa6SDerek Schuff     Segment.Section->setSectionOffset(W->OS.tell() - Section.ContentsOffset);
971*0ff28fa6SDerek Schuff     W->OS << Segment.Data; // data
9727c395943SSam Clegg   }
9739e15f359SSam Clegg 
9749e15f359SSam Clegg   // Apply fixups.
9757ee758d6SSam Clegg   applyRelocations(DataRelocations, Section.ContentsOffset, Layout);
9769e15f359SSam Clegg 
9779e15f359SSam Clegg   endSection(Section);
978e49584a3SSam Clegg   return Section.Index;
9799e15f359SSam Clegg }
9809e15f359SSam Clegg 
9816f08c84aSSam Clegg void WasmObjectWriter::writeRelocSection(
9826f08c84aSSam Clegg     uint32_t SectionIndex, StringRef Name,
983f77dc2a8SSam Clegg     std::vector<WasmRelocationEntry> &Relocs) {
9849e15f359SSam Clegg   // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
9859e15f359SSam Clegg   // for descriptions of the reloc sections.
9869e15f359SSam Clegg 
987f77dc2a8SSam Clegg   if (Relocs.empty())
9889e15f359SSam Clegg     return;
9899e15f359SSam Clegg 
990f77dc2a8SSam Clegg   // First, ensure the relocations are sorted in offset order.  In general they
991f77dc2a8SSam Clegg   // should already be sorted since `recordRelocation` is called in offset
992f77dc2a8SSam Clegg   // order, but for the code section we combine many MC sections into single
993f77dc2a8SSam Clegg   // wasm section, and this order is determined by the order of Asm.Symbols()
994f77dc2a8SSam Clegg   // not the sections order.
995efd94c56SFangrui Song   llvm::stable_sort(
996efd94c56SFangrui Song       Relocs, [](const WasmRelocationEntry &A, const WasmRelocationEntry &B) {
997f77dc2a8SSam Clegg         return (A.Offset + A.FixupSection->getSectionOffset()) <
998f77dc2a8SSam Clegg                (B.Offset + B.FixupSection->getSectionOffset());
999f77dc2a8SSam Clegg       });
1000f77dc2a8SSam Clegg 
10019e15f359SSam Clegg   SectionBookkeeping Section;
10026f08c84aSSam Clegg   startCustomSection(Section, std::string("reloc.") + Name.str());
10039e15f359SSam Clegg 
1004*0ff28fa6SDerek Schuff   encodeULEB128(SectionIndex, W->OS);
1005*0ff28fa6SDerek Schuff   encodeULEB128(Relocs.size(), W->OS);
1006f77dc2a8SSam Clegg   for (const WasmRelocationEntry &RelEntry : Relocs) {
1007f208f631SHeejin Ahn     uint64_t Offset =
1008f208f631SHeejin Ahn         RelEntry.Offset + RelEntry.FixupSection->getSectionOffset();
10096f08c84aSSam Clegg     uint32_t Index = getRelocationIndexValue(RelEntry);
10109e15f359SSam Clegg 
1011*0ff28fa6SDerek Schuff     W->OS << char(RelEntry.Type);
1012*0ff28fa6SDerek Schuff     encodeULEB128(Offset, W->OS);
1013*0ff28fa6SDerek Schuff     encodeULEB128(Index, W->OS);
10146f08c84aSSam Clegg     if (RelEntry.hasAddend())
1015*0ff28fa6SDerek Schuff       encodeSLEB128(RelEntry.Addend, W->OS);
10169e15f359SSam Clegg   }
10179e15f359SSam Clegg 
10189e15f359SSam Clegg   endSection(Section);
10199e15f359SSam Clegg }
10209e15f359SSam Clegg 
10216a31a0d6SSam Clegg void WasmObjectWriter::writeCustomRelocSections() {
10226a31a0d6SSam Clegg   for (const auto &Sec : CustomSections) {
10236a31a0d6SSam Clegg     auto &Relocations = CustomSectionsRelocations[Sec.Section];
10246a31a0d6SSam Clegg     writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations);
10256a31a0d6SSam Clegg   }
10266a31a0d6SSam Clegg }
10276a31a0d6SSam Clegg 
10289e15f359SSam Clegg void WasmObjectWriter::writeLinkingMetaDataSection(
102986b4a09aSSam Clegg     ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
1030ea7caceeSSam Clegg     ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
1031ea7caceeSSam Clegg     const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) {
10329e15f359SSam Clegg   SectionBookkeeping Section;
10332322a937SSam Clegg   startCustomSection(Section, "linking");
1034*0ff28fa6SDerek Schuff   encodeULEB128(wasm::WasmMetadataVersion, W->OS);
10359e15f359SSam Clegg 
10366bb5a41fSSam Clegg   SectionBookkeeping SubSection;
10376c899ba6SSam Clegg   if (SymbolInfos.size() != 0) {
10386c899ba6SSam Clegg     startSection(SubSection, wasm::WASM_SYMBOL_TABLE);
1039*0ff28fa6SDerek Schuff     encodeULEB128(SymbolInfos.size(), W->OS);
10406c899ba6SSam Clegg     for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) {
1041*0ff28fa6SDerek Schuff       encodeULEB128(Sym.Kind, W->OS);
1042*0ff28fa6SDerek Schuff       encodeULEB128(Sym.Flags, W->OS);
10436c899ba6SSam Clegg       switch (Sym.Kind) {
10446c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_FUNCTION:
10456c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_GLOBAL:
1046da419bdbSHeejin Ahn       case wasm::WASM_SYMBOL_TYPE_EVENT:
1047*0ff28fa6SDerek Schuff         encodeULEB128(Sym.ElementIndex, W->OS);
104829874ceaSDan Gohman         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0 ||
104929874ceaSDan Gohman             (Sym.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0)
10506c899ba6SSam Clegg           writeString(Sym.Name);
10516c899ba6SSam Clegg         break;
10526c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_DATA:
10536c899ba6SSam Clegg         writeString(Sym.Name);
10546c899ba6SSam Clegg         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) {
1055*0ff28fa6SDerek Schuff           encodeULEB128(Sym.DataRef.Segment, W->OS);
1056*0ff28fa6SDerek Schuff           encodeULEB128(Sym.DataRef.Offset, W->OS);
1057*0ff28fa6SDerek Schuff           encodeULEB128(Sym.DataRef.Size, W->OS);
10586c899ba6SSam Clegg         }
10596c899ba6SSam Clegg         break;
10606a31a0d6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_SECTION: {
10616a31a0d6SSam Clegg         const uint32_t SectionIndex =
10626a31a0d6SSam Clegg             CustomSections[Sym.ElementIndex].OutputIndex;
1063*0ff28fa6SDerek Schuff         encodeULEB128(SectionIndex, W->OS);
10646a31a0d6SSam Clegg         break;
10656a31a0d6SSam Clegg       }
10666c899ba6SSam Clegg       default:
10676c899ba6SSam Clegg         llvm_unreachable("unexpected kind");
10686c899ba6SSam Clegg       }
1069b7787fd0SSam Clegg     }
1070b7787fd0SSam Clegg     endSection(SubSection);
1071b7787fd0SSam Clegg   }
10729e15f359SSam Clegg 
10736c899ba6SSam Clegg   if (DataSegments.size()) {
107463ebb813SSam Clegg     startSection(SubSection, wasm::WASM_SEGMENT_INFO);
1075*0ff28fa6SDerek Schuff     encodeULEB128(DataSegments.size(), W->OS);
10766c899ba6SSam Clegg     for (const WasmDataSegment &Segment : DataSegments) {
1077d95ed959SSam Clegg       writeString(Segment.Name);
1078*0ff28fa6SDerek Schuff       encodeULEB128(Segment.Alignment, W->OS);
1079*0ff28fa6SDerek Schuff       encodeULEB128(Segment.LinkerFlags, W->OS);
108063ebb813SSam Clegg     }
1081d95ed959SSam Clegg     endSection(SubSection);
1082d95ed959SSam Clegg   }
1083d95ed959SSam Clegg 
1084bafe6902SSam Clegg   if (!InitFuncs.empty()) {
1085bafe6902SSam Clegg     startSection(SubSection, wasm::WASM_INIT_FUNCS);
1086*0ff28fa6SDerek Schuff     encodeULEB128(InitFuncs.size(), W->OS);
1087bafe6902SSam Clegg     for (auto &StartFunc : InitFuncs) {
1088*0ff28fa6SDerek Schuff       encodeULEB128(StartFunc.first, W->OS);  // priority
1089*0ff28fa6SDerek Schuff       encodeULEB128(StartFunc.second, W->OS); // function index
1090bafe6902SSam Clegg     }
1091bafe6902SSam Clegg     endSection(SubSection);
1092bafe6902SSam Clegg   }
1093bafe6902SSam Clegg 
1094ea7caceeSSam Clegg   if (Comdats.size()) {
1095ea7caceeSSam Clegg     startSection(SubSection, wasm::WASM_COMDAT_INFO);
1096*0ff28fa6SDerek Schuff     encodeULEB128(Comdats.size(), W->OS);
1097ea7caceeSSam Clegg     for (const auto &C : Comdats) {
1098ea7caceeSSam Clegg       writeString(C.first);
1099*0ff28fa6SDerek Schuff       encodeULEB128(0, W->OS); // flags for future use
1100*0ff28fa6SDerek Schuff       encodeULEB128(C.second.size(), W->OS);
1101ea7caceeSSam Clegg       for (const WasmComdatEntry &Entry : C.second) {
1102*0ff28fa6SDerek Schuff         encodeULEB128(Entry.Kind, W->OS);
1103*0ff28fa6SDerek Schuff         encodeULEB128(Entry.Index, W->OS);
1104ea7caceeSSam Clegg       }
1105ea7caceeSSam Clegg     }
1106ea7caceeSSam Clegg     endSection(SubSection);
1107ea7caceeSSam Clegg   }
1108ea7caceeSSam Clegg 
11099e15f359SSam Clegg   endSection(Section);
11109e15f359SSam Clegg }
11119e15f359SSam Clegg 
1112cbda16ebSThomas Lively void WasmObjectWriter::writeCustomSection(WasmCustomSection &CustomSection,
1113cbda16ebSThomas Lively                                           const MCAssembler &Asm,
11146a31a0d6SSam Clegg                                           const MCAsmLayout &Layout) {
1115cfd44a2eSSam Clegg   SectionBookkeeping Section;
11166a31a0d6SSam Clegg   auto *Sec = CustomSection.Section;
11172322a937SSam Clegg   startCustomSection(Section, CustomSection.Name);
11186a31a0d6SSam Clegg 
1119*0ff28fa6SDerek Schuff   Sec->setSectionOffset(W->OS.tell() - Section.ContentsOffset);
1120*0ff28fa6SDerek Schuff   Asm.writeSectionData(W->OS, Sec, Layout);
11216a31a0d6SSam Clegg 
11226a31a0d6SSam Clegg   CustomSection.OutputContentsOffset = Section.ContentsOffset;
11236a31a0d6SSam Clegg   CustomSection.OutputIndex = Section.Index;
11246a31a0d6SSam Clegg 
1125cfd44a2eSSam Clegg   endSection(Section);
11266a31a0d6SSam Clegg 
11276a31a0d6SSam Clegg   // Apply fixups.
11284d57fbd0SSam Clegg   auto &Relocations = CustomSectionsRelocations[CustomSection.Section];
11297ee758d6SSam Clegg   applyRelocations(Relocations, CustomSection.OutputContentsOffset, Layout);
11306a31a0d6SSam Clegg }
11316a31a0d6SSam Clegg 
11325e3d33a7SSam Clegg uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm &Symbol) {
11335e3d33a7SSam Clegg   assert(Symbol.isFunction());
11345e3d33a7SSam Clegg   assert(TypeIndices.count(&Symbol));
11355e3d33a7SSam Clegg   return TypeIndices[&Symbol];
11365e3d33a7SSam Clegg }
11375e3d33a7SSam Clegg 
1138da419bdbSHeejin Ahn uint32_t WasmObjectWriter::getEventType(const MCSymbolWasm &Symbol) {
1139da419bdbSHeejin Ahn   assert(Symbol.isEvent());
1140da419bdbSHeejin Ahn   assert(TypeIndices.count(&Symbol));
1141da419bdbSHeejin Ahn   return TypeIndices[&Symbol];
1142da419bdbSHeejin Ahn }
1143da419bdbSHeejin Ahn 
114438b12f5eSHeejin Ahn void WasmObjectWriter::registerFunctionType(const MCSymbolWasm &Symbol) {
11455e3d33a7SSam Clegg   assert(Symbol.isFunction());
11465e3d33a7SSam Clegg 
1147da419bdbSHeejin Ahn   WasmSignature S;
11487ee758d6SSam Clegg 
11497ee758d6SSam Clegg   if (auto *Sig = Symbol.getSignature()) {
1150da419bdbSHeejin Ahn     S.Returns = Sig->Returns;
1151da419bdbSHeejin Ahn     S.Params = Sig->Params;
115277a7a380SDerek Schuff   }
11535e3d33a7SSam Clegg 
1154da419bdbSHeejin Ahn   auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
11555e3d33a7SSam Clegg   if (Pair.second)
1156da419bdbSHeejin Ahn     Signatures.push_back(S);
11575e3d33a7SSam Clegg   TypeIndices[&Symbol] = Pair.first->second;
11585e3d33a7SSam Clegg 
1159d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "registerFunctionType: " << Symbol
1160d34e60caSNicola Zaghen                     << " new:" << Pair.second << "\n");
1161d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
11625e3d33a7SSam Clegg }
11635e3d33a7SSam Clegg 
116438b12f5eSHeejin Ahn void WasmObjectWriter::registerEventType(const MCSymbolWasm &Symbol) {
1165da419bdbSHeejin Ahn   assert(Symbol.isEvent());
1166da419bdbSHeejin Ahn 
1167da419bdbSHeejin Ahn   // TODO Currently we don't generate imported exceptions, but if we do, we
1168da419bdbSHeejin Ahn   // should have a way of infering types of imported exceptions.
1169da419bdbSHeejin Ahn   WasmSignature S;
1170da419bdbSHeejin Ahn   if (auto *Sig = Symbol.getSignature()) {
1171da419bdbSHeejin Ahn     S.Returns = Sig->Returns;
1172da419bdbSHeejin Ahn     S.Params = Sig->Params;
1173da419bdbSHeejin Ahn   }
1174da419bdbSHeejin Ahn 
1175da419bdbSHeejin Ahn   auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
1176da419bdbSHeejin Ahn   if (Pair.second)
1177da419bdbSHeejin Ahn     Signatures.push_back(S);
1178da419bdbSHeejin Ahn   TypeIndices[&Symbol] = Pair.first->second;
1179da419bdbSHeejin Ahn 
1180da419bdbSHeejin Ahn   LLVM_DEBUG(dbgs() << "registerEventType: " << Symbol << " new:" << Pair.second
1181da419bdbSHeejin Ahn                     << "\n");
1182da419bdbSHeejin Ahn   LLVM_DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
1183da419bdbSHeejin Ahn }
1184da419bdbSHeejin Ahn 
11854d57fbd0SSam Clegg static bool isInSymtab(const MCSymbolWasm &Sym) {
11863ea1c62cSSam Clegg   if (Sym.isUsedInReloc() || Sym.isUsedInInitArray())
11874d57fbd0SSam Clegg     return true;
11884d57fbd0SSam Clegg 
11894d57fbd0SSam Clegg   if (Sym.isComdat() && !Sym.isDefined())
11904d57fbd0SSam Clegg     return false;
11914d57fbd0SSam Clegg 
11923ea1c62cSSam Clegg   if (Sym.isTemporary())
11934d57fbd0SSam Clegg     return false;
11944d57fbd0SSam Clegg 
11954d57fbd0SSam Clegg   if (Sym.isSection())
11964d57fbd0SSam Clegg     return false;
11974d57fbd0SSam Clegg 
11984d57fbd0SSam Clegg   return true;
11994d57fbd0SSam Clegg }
1200*0ff28fa6SDerek Schuff void WasmObjectWriter::prepareImports(
1201*0ff28fa6SDerek Schuff     SmallVectorImpl<wasm::WasmImport> &Imports, MCAssembler &Asm,
120218eafb6cSDan Gohman     const MCAsmLayout &Layout) {
1203f950b24aSSam Clegg   // For now, always emit the memory import, since loads and stores are not
1204f950b24aSSam Clegg   // valid without it. In the future, we could perhaps be more clever and omit
1205f950b24aSSam Clegg   // it if there are no loads or stores.
12068defa952SSam Clegg   wasm::WasmImport MemImport;
12071ed3a046SSam Clegg   MemImport.Module = "env";
12081ed3a046SSam Clegg   MemImport.Field = "__linear_memory";
1209f950b24aSSam Clegg   MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
1210fd0964aeSWouter van Oortmerssen   MemImport.Memory.Flags = is64Bit() ? wasm::WASM_LIMITS_FLAG_IS_64
1211fd0964aeSWouter van Oortmerssen                                      : wasm::WASM_LIMITS_FLAG_NONE;
1212f950b24aSSam Clegg   Imports.push_back(MemImport);
1213f950b24aSSam Clegg 
1214f950b24aSSam Clegg   // For now, always emit the table section, since indirect calls are not
1215f950b24aSSam Clegg   // valid without it. In the future, we could perhaps be more clever and omit
1216f950b24aSSam Clegg   // it if there are no indirect calls.
12178defa952SSam Clegg   wasm::WasmImport TableImport;
12181ed3a046SSam Clegg   TableImport.Module = "env";
12191ed3a046SSam Clegg   TableImport.Field = "__indirect_function_table";
1220f950b24aSSam Clegg   TableImport.Kind = wasm::WASM_EXTERNAL_TABLE;
12216a87ddacSThomas Lively   TableImport.Table.ElemType = wasm::WASM_TYPE_FUNCREF;
1222f950b24aSSam Clegg   Imports.push_back(TableImport);
1223f950b24aSSam Clegg 
1224da419bdbSHeejin Ahn   // Populate SignatureIndices, and Imports and WasmIndices for undefined
1225586320c0SNicholas Wilson   // symbols.  This must be done before populating WasmIndices for defined
1226586320c0SNicholas Wilson   // symbols.
122732ce5ca0SDan Gohman   for (const MCSymbol &S : Asm.symbols()) {
122832ce5ca0SDan Gohman     const auto &WS = static_cast<const MCSymbolWasm &>(S);
122932ce5ca0SDan Gohman 
123032ce5ca0SDan Gohman     // Register types for all functions, including those with private linkage
12319f3fe42eSSam Clegg     // (because wasm always needs a type signature).
12327ee758d6SSam Clegg     if (WS.isFunction()) {
12337ee758d6SSam Clegg       const MCSymbolWasm *Base = cast<MCSymbolWasm>(Layout.getBaseSymbol(S));
12347ee758d6SSam Clegg       registerFunctionType(*Base);
12357ee758d6SSam Clegg     }
123632ce5ca0SDan Gohman 
1237da419bdbSHeejin Ahn     if (WS.isEvent())
1238da419bdbSHeejin Ahn       registerEventType(WS);
1239da419bdbSHeejin Ahn 
124032ce5ca0SDan Gohman     if (WS.isTemporary())
124132ce5ca0SDan Gohman       continue;
124232ce5ca0SDan Gohman 
124332ce5ca0SDan Gohman     // If the symbol is not defined in this translation unit, import it.
12446c899ba6SSam Clegg     if (!WS.isDefined() && !WS.isComdat()) {
12456c899ba6SSam Clegg       if (WS.isFunction()) {
12468defa952SSam Clegg         wasm::WasmImport Import;
1247f726e445SDan Gohman         Import.Module = WS.getImportModule();
1248f726e445SDan Gohman         Import.Field = WS.getImportName();
124932ce5ca0SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
12508defa952SSam Clegg         Import.SigIndex = getFunctionType(WS);
12516c899ba6SSam Clegg         Imports.push_back(Import);
1252492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
12536c899ba6SSam Clegg         WasmIndices[&WS] = NumFunctionImports++;
12546c899ba6SSam Clegg       } else if (WS.isGlobal()) {
125515f349f7SNicholas Wilson         if (WS.isWeak())
125615f349f7SNicholas Wilson           report_fatal_error("undefined global symbol cannot be weak");
125715f349f7SNicholas Wilson 
12586c899ba6SSam Clegg         wasm::WasmImport Import;
1259f726e445SDan Gohman         Import.Field = WS.getImportName();
126032ce5ca0SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1261492f7529SSam Clegg         Import.Module = WS.getImportModule();
12626c899ba6SSam Clegg         Import.Global = WS.getGlobalType();
12636c899ba6SSam Clegg         Imports.push_back(Import);
1264492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
12656c899ba6SSam Clegg         WasmIndices[&WS] = NumGlobalImports++;
1266da419bdbSHeejin Ahn       } else if (WS.isEvent()) {
1267da419bdbSHeejin Ahn         if (WS.isWeak())
1268da419bdbSHeejin Ahn           report_fatal_error("undefined event symbol cannot be weak");
1269da419bdbSHeejin Ahn 
1270da419bdbSHeejin Ahn         wasm::WasmImport Import;
1271f726e445SDan Gohman         Import.Module = WS.getImportModule();
1272f726e445SDan Gohman         Import.Field = WS.getImportName();
1273da419bdbSHeejin Ahn         Import.Kind = wasm::WASM_EXTERNAL_EVENT;
1274da419bdbSHeejin Ahn         Import.Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
1275da419bdbSHeejin Ahn         Import.Event.SigIndex = getEventType(WS);
1276da419bdbSHeejin Ahn         Imports.push_back(Import);
1277492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
1278da419bdbSHeejin Ahn         WasmIndices[&WS] = NumEventImports++;
127932ce5ca0SDan Gohman       }
128032ce5ca0SDan Gohman     }
128132ce5ca0SDan Gohman   }
128232ce5ca0SDan Gohman 
1283492f7529SSam Clegg   // Add imports for GOT globals
1284492f7529SSam Clegg   for (const MCSymbol &S : Asm.symbols()) {
1285492f7529SSam Clegg     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1286492f7529SSam Clegg     if (WS.isUsedInGOT()) {
1287492f7529SSam Clegg       wasm::WasmImport Import;
1288492f7529SSam Clegg       if (WS.isFunction())
1289492f7529SSam Clegg         Import.Module = "GOT.func";
1290492f7529SSam Clegg       else
1291492f7529SSam Clegg         Import.Module = "GOT.mem";
1292492f7529SSam Clegg       Import.Field = WS.getName();
1293492f7529SSam Clegg       Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1294492f7529SSam Clegg       Import.Global = {wasm::WASM_TYPE_I32, true};
1295492f7529SSam Clegg       Imports.push_back(Import);
1296492f7529SSam Clegg       assert(GOTIndices.count(&WS) == 0);
1297492f7529SSam Clegg       GOTIndices[&WS] = NumGlobalImports++;
1298492f7529SSam Clegg     }
1299492f7529SSam Clegg   }
1300*0ff28fa6SDerek Schuff }
1301492f7529SSam Clegg 
1302*0ff28fa6SDerek Schuff uint64_t WasmObjectWriter::writeObject(MCAssembler &Asm,
1303*0ff28fa6SDerek Schuff                                        const MCAsmLayout &Layout) {
1304*0ff28fa6SDerek Schuff   support::endian::Writer MainWriter(*OS, support::little);
1305*0ff28fa6SDerek Schuff   W = &MainWriter;
1306*0ff28fa6SDerek Schuff   if (IsSplitDwarf) {
1307*0ff28fa6SDerek Schuff     uint64_t TotalSize = writeOneObject(Asm, Layout, DwoMode::NonDwoOnly);
1308*0ff28fa6SDerek Schuff     assert(DwoOS);
1309*0ff28fa6SDerek Schuff     support::endian::Writer DwoWriter(*DwoOS, support::little);
1310*0ff28fa6SDerek Schuff     W = &DwoWriter;
1311*0ff28fa6SDerek Schuff     return TotalSize + writeOneObject(Asm, Layout, DwoMode::DwoOnly);
1312*0ff28fa6SDerek Schuff   } else {
1313*0ff28fa6SDerek Schuff     return writeOneObject(Asm, Layout, DwoMode::AllSections);
1314*0ff28fa6SDerek Schuff   }
1315*0ff28fa6SDerek Schuff }
1316*0ff28fa6SDerek Schuff 
1317*0ff28fa6SDerek Schuff uint64_t WasmObjectWriter::writeOneObject(MCAssembler &Asm,
1318*0ff28fa6SDerek Schuff                                           const MCAsmLayout &Layout,
1319*0ff28fa6SDerek Schuff                                           DwoMode Mode) {
1320*0ff28fa6SDerek Schuff   uint64_t StartOffset = W->OS.tell();
1321*0ff28fa6SDerek Schuff   SectionCount = 0;
1322*0ff28fa6SDerek Schuff   CustomSections.clear();
1323*0ff28fa6SDerek Schuff 
1324*0ff28fa6SDerek Schuff   LLVM_DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
1325*0ff28fa6SDerek Schuff 
1326*0ff28fa6SDerek Schuff   // Collect information from the available symbols.
1327*0ff28fa6SDerek Schuff   SmallVector<WasmFunction, 4> Functions;
1328*0ff28fa6SDerek Schuff   SmallVector<uint32_t, 4> TableElems;
1329*0ff28fa6SDerek Schuff   SmallVector<wasm::WasmImport, 4> Imports;
1330*0ff28fa6SDerek Schuff   SmallVector<wasm::WasmExport, 4> Exports;
1331*0ff28fa6SDerek Schuff   SmallVector<wasm::WasmEventType, 1> Events;
1332*0ff28fa6SDerek Schuff   SmallVector<wasm::WasmGlobal, 1> Globals;
1333*0ff28fa6SDerek Schuff   SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos;
1334*0ff28fa6SDerek Schuff   SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
1335*0ff28fa6SDerek Schuff   std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
1336*0ff28fa6SDerek Schuff   uint64_t DataSize = 0;
1337*0ff28fa6SDerek Schuff   if (Mode != DwoMode::DwoOnly) {
1338*0ff28fa6SDerek Schuff     prepareImports(Imports, Asm, Layout);
1339*0ff28fa6SDerek Schuff   }
13404d57fbd0SSam Clegg   // Populate DataSegments and CustomSections, which must be done before
13414d57fbd0SSam Clegg   // populating DataLocations.
1342759631c7SSam Clegg   for (MCSection &Sec : Asm) {
1343759631c7SSam Clegg     auto &Section = static_cast<MCSectionWasm &>(Sec);
13447d1ff446SFangrui Song     StringRef SectionName = Section.getName();
1345759631c7SSam Clegg 
1346*0ff28fa6SDerek Schuff     if (Mode == DwoMode::NonDwoOnly && isDwoSection(Sec))
1347*0ff28fa6SDerek Schuff       continue;
1348*0ff28fa6SDerek Schuff     if (Mode == DwoMode::DwoOnly && !isDwoSection(Sec))
1349*0ff28fa6SDerek Schuff       continue;
1350*0ff28fa6SDerek Schuff 
1351bafe6902SSam Clegg     // .init_array sections are handled specially elsewhere.
13524d57fbd0SSam Clegg     if (SectionName.startswith(".init_array"))
1353bafe6902SSam Clegg       continue;
1354bafe6902SSam Clegg 
13554d57fbd0SSam Clegg     // Code is handled separately
13564d57fbd0SSam Clegg     if (Section.getKind().isText())
13574d57fbd0SSam Clegg       continue;
13584d57fbd0SSam Clegg 
13594d57fbd0SSam Clegg     if (Section.isWasmData()) {
1360329e76d5SSam Clegg       uint32_t SegmentIndex = DataSegments.size();
1361759631c7SSam Clegg       DataSize = alignTo(DataSize, Section.getAlignment());
1362759631c7SSam Clegg       DataSegments.emplace_back();
1363759631c7SSam Clegg       WasmDataSegment &Segment = DataSegments.back();
13644d57fbd0SSam Clegg       Segment.Name = SectionName;
13659b49f36aSSimon Pilgrim       Segment.InitFlags =
13669b49f36aSSimon Pilgrim           Section.getPassive() ? (uint32_t)wasm::WASM_SEGMENT_IS_PASSIVE : 0;
1367759631c7SSam Clegg       Segment.Offset = DataSize;
1368759631c7SSam Clegg       Segment.Section = &Section;
136963ebb813SSam Clegg       addData(Segment.Data, Section);
137056c587adSSam Clegg       Segment.Alignment = Log2_32(Section.getAlignment());
13712e150409SThomas Lively       Segment.LinkerFlags = 0;
1372759631c7SSam Clegg       DataSize += Segment.Data.size();
13736c899ba6SSam Clegg       Section.setSegmentIndex(SegmentIndex);
1374ea7caceeSSam Clegg 
1375ea7caceeSSam Clegg       if (const MCSymbolWasm *C = Section.getGroup()) {
1376ea7caceeSSam Clegg         Comdats[C->getName()].emplace_back(
1377329e76d5SSam Clegg             WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
1378ea7caceeSSam Clegg       }
13794d57fbd0SSam Clegg     } else {
13804d57fbd0SSam Clegg       // Create custom sections
13814d57fbd0SSam Clegg       assert(Sec.getKind().isMetadata());
13824d57fbd0SSam Clegg 
13834d57fbd0SSam Clegg       StringRef Name = SectionName;
13844d57fbd0SSam Clegg 
13854d57fbd0SSam Clegg       // For user-defined custom sections, strip the prefix
13864d57fbd0SSam Clegg       if (Name.startswith(".custom_section."))
13874d57fbd0SSam Clegg         Name = Name.substr(strlen(".custom_section."));
13884d57fbd0SSam Clegg 
13894d57fbd0SSam Clegg       MCSymbol *Begin = Sec.getBeginSymbol();
1390fb807d4dSSam Clegg       if (Begin) {
13914d57fbd0SSam Clegg         WasmIndices[cast<MCSymbolWasm>(Begin)] = CustomSections.size();
1392b210c64bSSam Clegg         if (SectionName != Begin->getName())
1393fb807d4dSSam Clegg           report_fatal_error("section name and begin symbol should match: " +
1394b210c64bSSam Clegg                              Twine(SectionName));
1395fb807d4dSSam Clegg       }
1396cbda16ebSThomas Lively 
1397f6f4f843SThomas Lively       // Separate out the producers and target features sections
1398cbda16ebSThomas Lively       if (Name == "producers") {
13990eaee545SJonas Devlieghere         ProducersSection = std::make_unique<WasmCustomSection>(Name, &Section);
1400cbda16ebSThomas Lively         continue;
1401cbda16ebSThomas Lively       }
1402f6f4f843SThomas Lively       if (Name == "target_features") {
1403f6f4f843SThomas Lively         TargetFeaturesSection =
14040eaee545SJonas Devlieghere             std::make_unique<WasmCustomSection>(Name, &Section);
1405f6f4f843SThomas Lively         continue;
1406f6f4f843SThomas Lively       }
1407cbda16ebSThomas Lively 
14084d57fbd0SSam Clegg       CustomSections.emplace_back(Name, &Section);
1409759631c7SSam Clegg     }
14106a31a0d6SSam Clegg   }
14116a31a0d6SSam Clegg 
1412586320c0SNicholas Wilson   // Populate WasmIndices and DataLocations for defined symbols.
1413d934cb88SDan Gohman   for (const MCSymbol &S : Asm.symbols()) {
1414d934cb88SDan Gohman     // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1415d934cb88SDan Gohman     // or used in relocations.
1416d934cb88SDan Gohman     if (S.isTemporary() && S.getName().empty())
1417d934cb88SDan Gohman       continue;
1418b7787fd0SSam Clegg 
1419d934cb88SDan Gohman     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1420d34e60caSNicola Zaghen     LLVM_DEBUG(
1421d34e60caSNicola Zaghen         dbgs() << "MCSymbol: " << toString(WS.getType()) << " '" << S << "'"
1422d34e60caSNicola Zaghen                << " isDefined=" << S.isDefined() << " isExternal="
1423d34e60caSNicola Zaghen                << S.isExternal() << " isTemporary=" << S.isTemporary()
1424d34e60caSNicola Zaghen                << " isWeak=" << WS.isWeak() << " isHidden=" << WS.isHidden()
1425b7787fd0SSam Clegg                << " isVariable=" << WS.isVariable() << "\n");
1426b7787fd0SSam Clegg 
14275e3d33a7SSam Clegg     if (WS.isVariable())
14285e3d33a7SSam Clegg       continue;
14296c899ba6SSam Clegg     if (WS.isComdat() && !WS.isDefined())
14306c899ba6SSam Clegg       continue;
1431b7787fd0SSam Clegg 
1432d934cb88SDan Gohman     if (WS.isFunction()) {
14336c899ba6SSam Clegg       unsigned Index;
1434cd65f698SSam Clegg       if (WS.isDefined()) {
1435b7787fd0SSam Clegg         if (WS.getOffset() != 0)
1436b7787fd0SSam Clegg           report_fatal_error(
1437b7787fd0SSam Clegg               "function sections must contain one function each");
1438b7787fd0SSam Clegg 
143918c56a07SHeejin Ahn         if (WS.getSize() == nullptr)
1440b7787fd0SSam Clegg           report_fatal_error(
1441b7787fd0SSam Clegg               "function symbols must have a size set with .size");
1442b7787fd0SSam Clegg 
14436c899ba6SSam Clegg         // A definition. Write out the function body.
14449f3fe42eSSam Clegg         Index = NumFunctionImports + Functions.size();
1445d934cb88SDan Gohman         WasmFunction Func;
1446da419bdbSHeejin Ahn         Func.SigIndex = getFunctionType(WS);
1447d934cb88SDan Gohman         Func.Sym = &WS;
14486c899ba6SSam Clegg         WasmIndices[&WS] = Index;
1449d934cb88SDan Gohman         Functions.push_back(Func);
14506c899ba6SSam Clegg 
14516c899ba6SSam Clegg         auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
14526c899ba6SSam Clegg         if (const MCSymbolWasm *C = Section.getGroup()) {
14536c899ba6SSam Clegg           Comdats[C->getName()].emplace_back(
14546c899ba6SSam Clegg               WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
14556c899ba6SSam Clegg         }
1456881d8778SSam Clegg 
1457881d8778SSam Clegg         if (WS.hasExportName()) {
1458881d8778SSam Clegg           wasm::WasmExport Export;
1459881d8778SSam Clegg           Export.Name = WS.getExportName();
1460881d8778SSam Clegg           Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1461881d8778SSam Clegg           Export.Index = Index;
1462881d8778SSam Clegg           Exports.push_back(Export);
1463881d8778SSam Clegg         }
1464d934cb88SDan Gohman       } else {
1465d934cb88SDan Gohman         // An import; the index was assigned above.
14666c899ba6SSam Clegg         Index = WasmIndices.find(&WS)->second;
1467d934cb88SDan Gohman       }
1468d934cb88SDan Gohman 
1469d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> function index: " << Index << "\n");
1470da419bdbSHeejin Ahn 
14716c899ba6SSam Clegg     } else if (WS.isData()) {
1472f3feb6adSWouter van Oortmerssen       if (!isInSymtab(WS))
1473c38e947eSSam Clegg         continue;
1474c38e947eSSam Clegg 
14756c899ba6SSam Clegg       if (!WS.isDefined()) {
1476d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "  -> segment index: -1"
1477d34e60caSNicola Zaghen                           << "\n");
1478fe6414b0SSam Clegg         continue;
14796c899ba6SSam Clegg       }
1480fe6414b0SSam Clegg 
1481d934cb88SDan Gohman       if (!WS.getSize())
1482c38e947eSSam Clegg         report_fatal_error("data symbols must have a size set with .size: " +
1483c38e947eSSam Clegg                            WS.getName());
1484d934cb88SDan Gohman 
1485d934cb88SDan Gohman       int64_t Size = 0;
1486d934cb88SDan Gohman       if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1487d934cb88SDan Gohman         report_fatal_error(".size expression must be evaluatable");
1488d934cb88SDan Gohman 
1489759631c7SSam Clegg       auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
1490079cba04SSam Clegg       if (!DataSection.isWasmData())
1491079cba04SSam Clegg         report_fatal_error("data symbols must live in a data section: " +
1492079cba04SSam Clegg                            WS.getName());
14937c395943SSam Clegg 
14946c899ba6SSam Clegg       // For each data symbol, export it in the symtab as a reference to the
14956c899ba6SSam Clegg       // corresponding Wasm data segment.
14966c899ba6SSam Clegg       wasm::WasmDataReference Ref = wasm::WasmDataReference{
14973b29376eSWouter van Oortmerssen           DataSection.getSegmentIndex(), Layout.getSymbolOffset(WS),
14983b29376eSWouter van Oortmerssen           static_cast<uint64_t>(Size)};
14996c899ba6SSam Clegg       DataLocations[&WS] = Ref;
1500d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> segment index: " << Ref.Segment << "\n");
1501da419bdbSHeejin Ahn 
1502a165f2d6SSam Clegg     } else if (WS.isGlobal()) {
15036c899ba6SSam Clegg       // A "true" Wasm global (currently just __stack_pointer)
15040a6c4d8dSSam Clegg       if (WS.isDefined()) {
15050a6c4d8dSSam Clegg         assert(WasmIndices.count(&WS) == 0);
15060a6c4d8dSSam Clegg         wasm::WasmGlobal Global;
15070a6c4d8dSSam Clegg         Global.Type = WS.getGlobalType();
15080a6c4d8dSSam Clegg         Global.Index = NumGlobalImports + Globals.size();
15090a6c4d8dSSam Clegg         switch (Global.Type.Type) {
15100a6c4d8dSSam Clegg         case wasm::WASM_TYPE_I32:
15110a6c4d8dSSam Clegg           Global.InitExpr.Opcode = wasm::WASM_OPCODE_I32_CONST;
15120a6c4d8dSSam Clegg           break;
15130a6c4d8dSSam Clegg         case wasm::WASM_TYPE_I64:
15140a6c4d8dSSam Clegg           Global.InitExpr.Opcode = wasm::WASM_OPCODE_I64_CONST;
15150a6c4d8dSSam Clegg           break;
15160a6c4d8dSSam Clegg         case wasm::WASM_TYPE_F32:
15170a6c4d8dSSam Clegg           Global.InitExpr.Opcode = wasm::WASM_OPCODE_F32_CONST;
15180a6c4d8dSSam Clegg           break;
15190a6c4d8dSSam Clegg         case wasm::WASM_TYPE_F64:
15200a6c4d8dSSam Clegg           Global.InitExpr.Opcode = wasm::WASM_OPCODE_F64_CONST;
15210a6c4d8dSSam Clegg           break;
152279aad89dSSam Clegg         case wasm::WASM_TYPE_EXTERNREF:
152379aad89dSSam Clegg           Global.InitExpr.Opcode = wasm::WASM_OPCODE_REF_NULL;
152479aad89dSSam Clegg           break;
15250a6c4d8dSSam Clegg         default:
15260a6c4d8dSSam Clegg           llvm_unreachable("unexpected type");
15270a6c4d8dSSam Clegg         }
15280a6c4d8dSSam Clegg         WasmIndices[&WS] = Global.Index;
15290a6c4d8dSSam Clegg         Globals.push_back(Global);
15300a6c4d8dSSam Clegg       } else {
1531545932beSEric Christopher         // An import; the index was assigned above
1532d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "  -> global index: "
1533d34e60caSNicola Zaghen                           << WasmIndices.find(&WS)->second << "\n");
15340a6c4d8dSSam Clegg       }
1535da419bdbSHeejin Ahn     } else if (WS.isEvent()) {
1536da419bdbSHeejin Ahn       // C++ exception symbol (__cpp_exception)
1537da419bdbSHeejin Ahn       unsigned Index;
1538da419bdbSHeejin Ahn       if (WS.isDefined()) {
15390a6c4d8dSSam Clegg         assert(WasmIndices.count(&WS) == 0);
1540da419bdbSHeejin Ahn         Index = NumEventImports + Events.size();
1541da419bdbSHeejin Ahn         wasm::WasmEventType Event;
1542da419bdbSHeejin Ahn         Event.SigIndex = getEventType(WS);
1543da419bdbSHeejin Ahn         Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
1544da419bdbSHeejin Ahn         WasmIndices[&WS] = Index;
1545da419bdbSHeejin Ahn         Events.push_back(Event);
1546da419bdbSHeejin Ahn       } else {
1547da419bdbSHeejin Ahn         // An import; the index was assigned above.
1548492f7529SSam Clegg         assert(WasmIndices.count(&WS) > 0);
1549da419bdbSHeejin Ahn       }
1550da419bdbSHeejin Ahn       LLVM_DEBUG(dbgs() << "  -> event index: " << WasmIndices.find(&WS)->second
1551da419bdbSHeejin Ahn                         << "\n");
1552da419bdbSHeejin Ahn 
1553a165f2d6SSam Clegg     } else {
1554a165f2d6SSam Clegg       assert(WS.isSection());
1555d934cb88SDan Gohman     }
1556d934cb88SDan Gohman   }
1557d934cb88SDan Gohman 
1558586320c0SNicholas Wilson   // Populate WasmIndices and DataLocations for aliased symbols.  We need to
1559586320c0SNicholas Wilson   // process these in a separate pass because we need to have processed the
1560586320c0SNicholas Wilson   // target of the alias before the alias itself and the symbols are not
1561586320c0SNicholas Wilson   // necessarily ordered in this way.
1562b7787fd0SSam Clegg   for (const MCSymbol &S : Asm.symbols()) {
1563b7787fd0SSam Clegg     if (!S.isVariable())
1564b7787fd0SSam Clegg       continue;
156531a2c809SSam Clegg 
1566cd65f698SSam Clegg     assert(S.isDefined());
1567b7787fd0SSam Clegg 
15687ee758d6SSam Clegg     const MCSymbolWasm *Base = cast<MCSymbolWasm>(Layout.getBaseSymbol(S));
15697ee758d6SSam Clegg 
15705e3d33a7SSam Clegg     // Find the target symbol of this weak alias and export that index
1571aff1c4dfSSam Clegg     const auto &WS = static_cast<const MCSymbolWasm &>(S);
15727ee758d6SSam Clegg     LLVM_DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *Base << "'\n");
1573b7787fd0SSam Clegg 
15747ee758d6SSam Clegg     if (Base->isFunction()) {
15757ee758d6SSam Clegg       assert(WasmIndices.count(Base) > 0);
15767ee758d6SSam Clegg       uint32_t WasmIndex = WasmIndices.find(Base)->second;
1577492f7529SSam Clegg       assert(WasmIndices.count(&WS) == 0);
15786c899ba6SSam Clegg       WasmIndices[&WS] = WasmIndex;
1579d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> index:" << WasmIndex << "\n");
15807ee758d6SSam Clegg     } else if (Base->isData()) {
15817ee758d6SSam Clegg       auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
15827ee758d6SSam Clegg       uint64_t Offset = Layout.getSymbolOffset(S);
15837ee758d6SSam Clegg       int64_t Size = 0;
15847ee758d6SSam Clegg       // For data symbol alias we use the size of the base symbol as the
15857ee758d6SSam Clegg       // size of the alias.  When an offset from the base is involved this
15867ee758d6SSam Clegg       // can result in a offset + size goes past the end of the data section
15877ee758d6SSam Clegg       // which out object format doesn't support.  So we must clamp it.
15887ee758d6SSam Clegg       if (!Base->getSize()->evaluateAsAbsolute(Size, Layout))
15897ee758d6SSam Clegg         report_fatal_error(".size expression must be evaluatable");
15907ee758d6SSam Clegg       const WasmDataSegment &Segment =
15917ee758d6SSam Clegg           DataSegments[DataSection.getSegmentIndex()];
15927ee758d6SSam Clegg       Size =
15937ee758d6SSam Clegg           std::min(static_cast<uint64_t>(Size), Segment.Data.size() - Offset);
15947ee758d6SSam Clegg       wasm::WasmDataReference Ref = wasm::WasmDataReference{
15957ee758d6SSam Clegg           DataSection.getSegmentIndex(),
15967ee758d6SSam Clegg           static_cast<uint32_t>(Layout.getSymbolOffset(S)),
15977ee758d6SSam Clegg           static_cast<uint32_t>(Size)};
15986c899ba6SSam Clegg       DataLocations[&WS] = Ref;
1599d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> index:" << Ref.Segment << "\n");
16006c899ba6SSam Clegg     } else {
1601da419bdbSHeejin Ahn       report_fatal_error("don't yet support global/event aliases");
16026c899ba6SSam Clegg     }
1603586320c0SNicholas Wilson   }
160431a2c809SSam Clegg 
1605586320c0SNicholas Wilson   // Finally, populate the symbol table itself, in its "natural" order.
1606586320c0SNicholas Wilson   for (const MCSymbol &S : Asm.symbols()) {
1607586320c0SNicholas Wilson     const auto &WS = static_cast<const MCSymbolWasm &>(S);
160825d8e68bSSam Clegg     if (!isInSymtab(WS)) {
160918c56a07SHeejin Ahn       WS.setIndex(InvalidIndex);
1610586320c0SNicholas Wilson       continue;
161125d8e68bSSam Clegg     }
1612d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "adding to symtab: " << WS << "\n");
1613586320c0SNicholas Wilson 
1614586320c0SNicholas Wilson     uint32_t Flags = 0;
1615586320c0SNicholas Wilson     if (WS.isWeak())
1616586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_BINDING_WEAK;
1617586320c0SNicholas Wilson     if (WS.isHidden())
1618586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN;
1619586320c0SNicholas Wilson     if (!WS.isExternal() && WS.isDefined())
1620586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;
1621586320c0SNicholas Wilson     if (WS.isUndefined())
1622586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_UNDEFINED;
1623da84b688SDan Gohman     if (WS.isNoStrip()) {
1624da84b688SDan Gohman       Flags |= wasm::WASM_SYMBOL_NO_STRIP;
1625da84b688SDan Gohman       if (isEmscripten()) {
1626d6ef8da3SSam Clegg         Flags |= wasm::WASM_SYMBOL_EXPORTED;
1627da84b688SDan Gohman       }
1628da84b688SDan Gohman     }
1629b4f4e370SSam Clegg     if (WS.hasImportName())
163029874ceaSDan Gohman       Flags |= wasm::WASM_SYMBOL_EXPLICIT_NAME;
1631881d8778SSam Clegg     if (WS.hasExportName())
1632881d8778SSam Clegg       Flags |= wasm::WASM_SYMBOL_EXPORTED;
1633586320c0SNicholas Wilson 
1634586320c0SNicholas Wilson     wasm::WasmSymbolInfo Info;
1635586320c0SNicholas Wilson     Info.Name = WS.getName();
1636586320c0SNicholas Wilson     Info.Kind = WS.getType();
1637586320c0SNicholas Wilson     Info.Flags = Flags;
16384d57fbd0SSam Clegg     if (!WS.isData()) {
16394d57fbd0SSam Clegg       assert(WasmIndices.count(&WS) > 0);
1640586320c0SNicholas Wilson       Info.ElementIndex = WasmIndices.find(&WS)->second;
16414d57fbd0SSam Clegg     } else if (WS.isDefined()) {
16424d57fbd0SSam Clegg       assert(DataLocations.count(&WS) > 0);
1643586320c0SNicholas Wilson       Info.DataRef = DataLocations.find(&WS)->second;
16444d57fbd0SSam Clegg     }
164525d8e68bSSam Clegg     WS.setIndex(SymbolInfos.size());
1646586320c0SNicholas Wilson     SymbolInfos.emplace_back(Info);
1647b7787fd0SSam Clegg   }
1648b7787fd0SSam Clegg 
16496006e091SSam Clegg   {
16506006e091SSam Clegg     auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
1651f9edbe95SSam Clegg       // Functions referenced by a relocation need to put in the table.  This is
1652f9edbe95SSam Clegg       // purely to make the object file's provisional values readable, and is
1653f9edbe95SSam Clegg       // ignored by the linker, which re-calculates the relocations itself.
1654d1152a26SSam Clegg       if (Rel.Type != wasm::R_WASM_TABLE_INDEX_I32 &&
1655cc1b9b68SWouter van Oortmerssen           Rel.Type != wasm::R_WASM_TABLE_INDEX_I64 &&
165681443ac1SSam Clegg           Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB &&
1657cc1b9b68SWouter van Oortmerssen           Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB64 &&
165881443ac1SSam Clegg           Rel.Type != wasm::R_WASM_TABLE_INDEX_REL_SLEB)
1659f9edbe95SSam Clegg         return;
1660f9edbe95SSam Clegg       assert(Rel.Symbol->isFunction());
16617ee758d6SSam Clegg       const MCSymbolWasm *Base =
16627ee758d6SSam Clegg           cast<MCSymbolWasm>(Layout.getBaseSymbol(*Rel.Symbol));
16637ee758d6SSam Clegg       uint32_t FunctionIndex = WasmIndices.find(Base)->second;
166418c56a07SHeejin Ahn       uint32_t TableIndex = TableElems.size() + InitialTableOffset;
16657ee758d6SSam Clegg       if (TableIndices.try_emplace(Base, TableIndex).second) {
16667ee758d6SSam Clegg         LLVM_DEBUG(dbgs() << "  -> adding " << Base->getName()
1667f9edbe95SSam Clegg                           << " to table: " << TableIndex << "\n");
16686c899ba6SSam Clegg         TableElems.push_back(FunctionIndex);
16697ee758d6SSam Clegg         registerFunctionType(*Base);
16706006e091SSam Clegg       }
16716006e091SSam Clegg     };
1672970d02c4SDan Gohman 
16736006e091SSam Clegg     for (const WasmRelocationEntry &RelEntry : CodeRelocations)
16746006e091SSam Clegg       HandleReloc(RelEntry);
16756006e091SSam Clegg     for (const WasmRelocationEntry &RelEntry : DataRelocations)
16766006e091SSam Clegg       HandleReloc(RelEntry);
1677d934cb88SDan Gohman   }
1678d934cb88SDan Gohman 
1679bafe6902SSam Clegg   // Translate .init_array section contents into start functions.
1680bafe6902SSam Clegg   for (const MCSection &S : Asm) {
1681bafe6902SSam Clegg     const auto &WS = static_cast<const MCSectionWasm &>(S);
16827d1ff446SFangrui Song     if (WS.getName().startswith(".fini_array"))
1683bafe6902SSam Clegg       report_fatal_error(".fini_array sections are unsupported");
16847d1ff446SFangrui Song     if (!WS.getName().startswith(".init_array"))
1685bafe6902SSam Clegg       continue;
1686bafe6902SSam Clegg     if (WS.getFragmentList().empty())
1687bafe6902SSam Clegg       continue;
1688b210c64bSSam Clegg 
1689b210c64bSSam Clegg     // init_array is expected to contain a single non-empty data fragment
1690b210c64bSSam Clegg     if (WS.getFragmentList().size() != 3)
1691bafe6902SSam Clegg       report_fatal_error("only one .init_array section fragment supported");
1692b210c64bSSam Clegg 
1693b210c64bSSam Clegg     auto IT = WS.begin();
1694b210c64bSSam Clegg     const MCFragment &EmptyFrag = *IT;
1695b210c64bSSam Clegg     if (EmptyFrag.getKind() != MCFragment::FT_Data)
1696b210c64bSSam Clegg       report_fatal_error(".init_array section should be aligned");
1697b210c64bSSam Clegg 
1698b210c64bSSam Clegg     IT = std::next(IT);
1699b210c64bSSam Clegg     const MCFragment &AlignFrag = *IT;
1700bafe6902SSam Clegg     if (AlignFrag.getKind() != MCFragment::FT_Align)
1701bafe6902SSam Clegg       report_fatal_error(".init_array section should be aligned");
1702bafe6902SSam Clegg     if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
1703bafe6902SSam Clegg       report_fatal_error(".init_array section should be aligned for pointers");
1704b210c64bSSam Clegg 
1705b210c64bSSam Clegg     const MCFragment &Frag = *std::next(IT);
1706bafe6902SSam Clegg     if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1707bafe6902SSam Clegg       report_fatal_error("only data supported in .init_array section");
1708b210c64bSSam Clegg 
1709bafe6902SSam Clegg     uint16_t Priority = UINT16_MAX;
17104d57fbd0SSam Clegg     unsigned PrefixLength = strlen(".init_array");
17117d1ff446SFangrui Song     if (WS.getName().size() > PrefixLength) {
17127d1ff446SFangrui Song       if (WS.getName()[PrefixLength] != '.')
1713f208f631SHeejin Ahn         report_fatal_error(
1714f208f631SHeejin Ahn             ".init_array section priority should start with '.'");
17157d1ff446SFangrui Song       if (WS.getName().substr(PrefixLength + 1).getAsInteger(10, Priority))
1716bafe6902SSam Clegg         report_fatal_error("invalid .init_array section priority");
1717bafe6902SSam Clegg     }
1718bafe6902SSam Clegg     const auto &DataFrag = cast<MCDataFragment>(Frag);
1719bafe6902SSam Clegg     const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1720f208f631SHeejin Ahn     for (const uint8_t *
172118c56a07SHeejin Ahn              P = (const uint8_t *)Contents.data(),
172218c56a07SHeejin Ahn             *End = (const uint8_t *)Contents.data() + Contents.size();
172318c56a07SHeejin Ahn          P != End; ++P) {
172418c56a07SHeejin Ahn       if (*P != 0)
1725bafe6902SSam Clegg         report_fatal_error("non-symbolic data in .init_array section");
1726bafe6902SSam Clegg     }
1727bafe6902SSam Clegg     for (const MCFixup &Fixup : DataFrag.getFixups()) {
1728f208f631SHeejin Ahn       assert(Fixup.getKind() ==
1729f208f631SHeejin Ahn              MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
1730bafe6902SSam Clegg       const MCExpr *Expr = Fixup.getValue();
17318fffa1dfSSam Clegg       auto *SymRef = dyn_cast<MCSymbolRefExpr>(Expr);
17328fffa1dfSSam Clegg       if (!SymRef)
1733bafe6902SSam Clegg         report_fatal_error("fixups in .init_array should be symbol references");
17348fffa1dfSSam Clegg       const auto &TargetSym = cast<const MCSymbolWasm>(SymRef->getSymbol());
17358fffa1dfSSam Clegg       if (TargetSym.getIndex() == InvalidIndex)
17363ea1c62cSSam Clegg         report_fatal_error("symbols in .init_array should exist in symtab");
17378fffa1dfSSam Clegg       if (!TargetSym.isFunction())
17388fffa1dfSSam Clegg         report_fatal_error("symbols in .init_array should be for functions");
173925d8e68bSSam Clegg       InitFuncs.push_back(
17408fffa1dfSSam Clegg           std::make_pair(Priority, TargetSym.getIndex()));
1741bafe6902SSam Clegg     }
1742bafe6902SSam Clegg   }
1743bafe6902SSam Clegg 
174418eafb6cSDan Gohman   // Write out the Wasm header.
174518eafb6cSDan Gohman   writeHeader(Asm);
174618eafb6cSDan Gohman 
1747*0ff28fa6SDerek Schuff   uint32_t CodeSectionIndex, DataSectionIndex;
1748*0ff28fa6SDerek Schuff   if (Mode != DwoMode::DwoOnly) {
1749da419bdbSHeejin Ahn     writeTypeSection(Signatures);
1750f950b24aSSam Clegg     writeImportSection(Imports, DataSize, TableElems.size());
17519e15f359SSam Clegg     writeFunctionSection(Functions);
1752f950b24aSSam Clegg     // Skip the "table" section; we import the table instead.
1753f950b24aSSam Clegg     // Skip the "memory" section; we import the memory instead.
1754da419bdbSHeejin Ahn     writeEventSection(Events);
17550a6c4d8dSSam Clegg     writeGlobalSection(Globals);
17569e15f359SSam Clegg     writeExportSection(Exports);
17579e15f359SSam Clegg     writeElemSection(TableElems);
1758fef8de66SThomas Lively     writeDataCountSection();
1759*0ff28fa6SDerek Schuff 
1760*0ff28fa6SDerek Schuff     CodeSectionIndex = writeCodeSection(Asm, Layout, Functions);
1761*0ff28fa6SDerek Schuff     DataSectionIndex = writeDataSection(Layout);
1762*0ff28fa6SDerek Schuff   }
1763*0ff28fa6SDerek Schuff 
1764*0ff28fa6SDerek Schuff   for (auto &CustomSection : CustomSections) {
1765cbda16ebSThomas Lively     writeCustomSection(CustomSection, Asm, Layout);
1766*0ff28fa6SDerek Schuff   }
1767*0ff28fa6SDerek Schuff 
1768*0ff28fa6SDerek Schuff   if (Mode != DwoMode::DwoOnly) {
1769c22bfb6bSNicholas Wilson     writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats);
1770*0ff28fa6SDerek Schuff 
17716f08c84aSSam Clegg     writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations);
17726f08c84aSSam Clegg     writeRelocSection(DataSectionIndex, "DATA", DataRelocations);
1773*0ff28fa6SDerek Schuff   }
17746a31a0d6SSam Clegg   writeCustomRelocSections();
1775cbda16ebSThomas Lively   if (ProducersSection)
1776cbda16ebSThomas Lively     writeCustomSection(*ProducersSection, Asm, Layout);
1777f6f4f843SThomas Lively   if (TargetFeaturesSection)
1778f6f4f843SThomas Lively     writeCustomSection(*TargetFeaturesSection, Asm, Layout);
1779970d02c4SDan Gohman 
1780d934cb88SDan Gohman   // TODO: Translate the .comment section to the output.
1781*0ff28fa6SDerek Schuff   return W->OS.tell() - StartOffset;
178218eafb6cSDan Gohman }
178318eafb6cSDan Gohman 
178460fbc7ccSLang Hames std::unique_ptr<MCObjectWriter>
17851301a878SLang Hames llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
178618eafb6cSDan Gohman                              raw_pwrite_stream &OS) {
17870eaee545SJonas Devlieghere   return std::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
178818eafb6cSDan Gohman }
1789*0ff28fa6SDerek Schuff 
1790*0ff28fa6SDerek Schuff std::unique_ptr<MCObjectWriter>
1791*0ff28fa6SDerek Schuff llvm::createWasmDwoObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
1792*0ff28fa6SDerek Schuff                                 raw_pwrite_stream &OS,
1793*0ff28fa6SDerek Schuff                                 raw_pwrite_stream &DwoOS) {
1794*0ff28fa6SDerek Schuff   return std::make_unique<WasmObjectWriter>(std::move(MOTW), OS, DwoOS);
1795*0ff28fa6SDerek Schuff }
1796