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"
3018eafb6cSDan Gohman #include "llvm/Support/ErrorHandling.h"
31d934cb88SDan Gohman #include "llvm/Support/LEB128.h"
3218eafb6cSDan Gohman #include "llvm/Support/StringSaver.h"
3318eafb6cSDan Gohman #include <vector>
3418eafb6cSDan Gohman 
3518eafb6cSDan Gohman using namespace llvm;
3618eafb6cSDan Gohman 
375e3d33a7SSam Clegg #define DEBUG_TYPE "mc"
3818eafb6cSDan Gohman 
3918eafb6cSDan Gohman namespace {
409e15f359SSam Clegg 
4130e1bbc1SSam Clegg // Went we ceate the indirect function table we start at 1, so that there is
4230e1bbc1SSam Clegg // and emtpy slot at 0 and therefore calling a null function pointer will trap.
4318c56a07SHeejin Ahn static const uint32_t InitialTableOffset = 1;
4430e1bbc1SSam Clegg 
45d934cb88SDan Gohman // For patching purposes, we need to remember where each section starts, both
46d934cb88SDan Gohman // for patching up the section size field, and for patching up references to
47d934cb88SDan Gohman // locations within the section.
48d934cb88SDan Gohman struct SectionBookkeeping {
49d934cb88SDan Gohman   // Where the size of the section is written.
50d934cb88SDan Gohman   uint64_t SizeOffset;
516a31a0d6SSam Clegg   // Where the section header ends (without custom section name).
526a31a0d6SSam Clegg   uint64_t PayloadOffset;
536a31a0d6SSam Clegg   // Where the contents of the section starts.
54d934cb88SDan Gohman   uint64_t ContentsOffset;
556f08c84aSSam Clegg   uint32_t Index;
56d934cb88SDan Gohman };
57d934cb88SDan Gohman 
58da419bdbSHeejin Ahn // The signature of a wasm function or event, in a struct capable of being used
59da419bdbSHeejin Ahn // as a DenseMap key.
60da419bdbSHeejin Ahn // TODO: Consider using wasm::WasmSignature directly instead.
61da419bdbSHeejin Ahn struct WasmSignature {
629e15f359SSam Clegg   // Support empty and tombstone instances, needed by DenseMap.
6318c56a07SHeejin Ahn   enum { Plain, Empty, Tombstone } State = Plain;
649e15f359SSam Clegg 
659e15f359SSam Clegg   // The return types of the function.
669e15f359SSam Clegg   SmallVector<wasm::ValType, 1> Returns;
679e15f359SSam Clegg 
689e15f359SSam Clegg   // The parameter types of the function.
699e15f359SSam Clegg   SmallVector<wasm::ValType, 4> Params;
709e15f359SSam Clegg 
71da419bdbSHeejin Ahn   bool operator==(const WasmSignature &Other) const {
729e15f359SSam Clegg     return State == Other.State && Returns == Other.Returns &&
739e15f359SSam Clegg            Params == Other.Params;
749e15f359SSam Clegg   }
759e15f359SSam Clegg };
769e15f359SSam Clegg 
77da419bdbSHeejin Ahn // Traits for using WasmSignature in a DenseMap.
78da419bdbSHeejin Ahn struct WasmSignatureDenseMapInfo {
79da419bdbSHeejin Ahn   static WasmSignature getEmptyKey() {
80da419bdbSHeejin Ahn     WasmSignature Sig;
81da419bdbSHeejin Ahn     Sig.State = WasmSignature::Empty;
82da419bdbSHeejin Ahn     return Sig;
839e15f359SSam Clegg   }
84da419bdbSHeejin Ahn   static WasmSignature getTombstoneKey() {
85da419bdbSHeejin Ahn     WasmSignature Sig;
86da419bdbSHeejin Ahn     Sig.State = WasmSignature::Tombstone;
87da419bdbSHeejin Ahn     return Sig;
889e15f359SSam Clegg   }
89da419bdbSHeejin Ahn   static unsigned getHashValue(const WasmSignature &Sig) {
90da419bdbSHeejin Ahn     uintptr_t Value = Sig.State;
91da419bdbSHeejin Ahn     for (wasm::ValType Ret : Sig.Returns)
924808914aSHeejin Ahn       Value += DenseMapInfo<uint32_t>::getHashValue(uint32_t(Ret));
93da419bdbSHeejin Ahn     for (wasm::ValType Param : Sig.Params)
944808914aSHeejin Ahn       Value += DenseMapInfo<uint32_t>::getHashValue(uint32_t(Param));
959e15f359SSam Clegg     return Value;
969e15f359SSam Clegg   }
97da419bdbSHeejin Ahn   static bool isEqual(const WasmSignature &LHS, const WasmSignature &RHS) {
989e15f359SSam Clegg     return LHS == RHS;
999e15f359SSam Clegg   }
1009e15f359SSam Clegg };
1019e15f359SSam Clegg 
1027c395943SSam Clegg // A wasm data segment.  A wasm binary contains only a single data section
1037c395943SSam Clegg // but that can contain many segments, each with their own virtual location
1047c395943SSam Clegg // in memory.  Each MCSection data created by llvm is modeled as its own
1057c395943SSam Clegg // wasm data segment.
1067c395943SSam Clegg struct WasmDataSegment {
1077c395943SSam Clegg   MCSectionWasm *Section;
108d95ed959SSam Clegg   StringRef Name;
1092e150409SThomas Lively   uint32_t InitFlags;
1107c395943SSam Clegg   uint32_t Offset;
11163ebb813SSam Clegg   uint32_t Alignment;
1122e150409SThomas Lively   uint32_t LinkerFlags;
1137c395943SSam Clegg   SmallVector<char, 4> Data;
1147c395943SSam Clegg };
1157c395943SSam Clegg 
1169e15f359SSam Clegg // A wasm function to be written into the function section.
1179e15f359SSam Clegg struct WasmFunction {
118da419bdbSHeejin Ahn   uint32_t SigIndex;
1199e15f359SSam Clegg   const MCSymbolWasm *Sym;
1209e15f359SSam Clegg };
1219e15f359SSam Clegg 
1229e15f359SSam Clegg // A wasm global to be written into the global section.
1239e15f359SSam Clegg struct WasmGlobal {
1246e7f1826SSam Clegg   wasm::WasmGlobalType Type;
1259e15f359SSam Clegg   uint64_t InitialValue;
1269e15f359SSam Clegg };
1279e15f359SSam Clegg 
128ea7caceeSSam Clegg // Information about a single item which is part of a COMDAT.  For each data
129ea7caceeSSam Clegg // segment or function which is in the COMDAT, there is a corresponding
130ea7caceeSSam Clegg // WasmComdatEntry.
131ea7caceeSSam Clegg struct WasmComdatEntry {
132ea7caceeSSam Clegg   unsigned Kind;
133ea7caceeSSam Clegg   uint32_t Index;
134ea7caceeSSam Clegg };
135ea7caceeSSam Clegg 
1366dc65e91SSam Clegg // Information about a single relocation.
1376dc65e91SSam Clegg struct WasmRelocationEntry {
1386dc65e91SSam Clegg   uint64_t Offset;                   // Where is the relocation.
1396dc65e91SSam Clegg   const MCSymbolWasm *Symbol;        // The symbol to relocate with.
1406dc65e91SSam Clegg   int64_t Addend;                    // A value to add to the symbol.
1416dc65e91SSam Clegg   unsigned Type;                     // The type of the relocation.
142fe6414b0SSam Clegg   const MCSectionWasm *FixupSection; // The section the relocation is targeting.
1436dc65e91SSam Clegg 
1446dc65e91SSam Clegg   WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol,
1456dc65e91SSam Clegg                       int64_t Addend, unsigned Type,
146fe6414b0SSam Clegg                       const MCSectionWasm *FixupSection)
1476dc65e91SSam Clegg       : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type),
1486dc65e91SSam Clegg         FixupSection(FixupSection) {}
1496dc65e91SSam Clegg 
150cadcb9ebSKeno Fischer   bool hasAddend() const { return wasm::relocTypeHasAddend(Type); }
151acd7d2b0SSam Clegg 
1526dc65e91SSam Clegg   void print(raw_ostream &Out) const {
153f208f631SHeejin Ahn     Out << wasm::relocTypetoString(Type) << " Off=" << Offset
154f208f631SHeejin Ahn         << ", Sym=" << *Symbol << ", Addend=" << Addend
155*7d1ff446SFangrui Song         << ", FixupSection=" << FixupSection->getName();
1566dc65e91SSam Clegg   }
157b7787fd0SSam Clegg 
158615eb470SAaron Ballman #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
159b7787fd0SSam Clegg   LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
160b7787fd0SSam Clegg #endif
1616dc65e91SSam Clegg };
1626dc65e91SSam Clegg 
16318c56a07SHeejin Ahn static const uint32_t InvalidIndex = -1;
16425d8e68bSSam Clegg 
165cfd44a2eSSam Clegg struct WasmCustomSection {
166cfd44a2eSSam Clegg 
1676a31a0d6SSam Clegg   StringRef Name;
1686a31a0d6SSam Clegg   MCSectionWasm *Section;
1696a31a0d6SSam Clegg 
1706a31a0d6SSam Clegg   uint32_t OutputContentsOffset;
1716a31a0d6SSam Clegg   uint32_t OutputIndex;
1726a31a0d6SSam Clegg 
1736a31a0d6SSam Clegg   WasmCustomSection(StringRef Name, MCSectionWasm *Section)
1746a31a0d6SSam Clegg       : Name(Name), Section(Section), OutputContentsOffset(0),
17518c56a07SHeejin Ahn         OutputIndex(InvalidIndex) {}
176cfd44a2eSSam Clegg };
177cfd44a2eSSam Clegg 
1781fb8daa6SSam Clegg #if !defined(NDEBUG)
1797f055deeSSam Clegg raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
180b7787fd0SSam Clegg   Rel.print(OS);
181b7787fd0SSam Clegg   return OS;
182b7787fd0SSam Clegg }
1831fb8daa6SSam Clegg #endif
184b7787fd0SSam Clegg 
18519e8befaSSam Clegg // Write X as an (unsigned) LEB value at offset Offset in Stream, padded
18619e8befaSSam Clegg // to allow patching.
18718c56a07SHeejin Ahn static void writePatchableLEB(raw_pwrite_stream &Stream, uint32_t X,
18819e8befaSSam Clegg                               uint64_t Offset) {
18919e8befaSSam Clegg   uint8_t Buffer[5];
19019e8befaSSam Clegg   unsigned SizeLen = encodeULEB128(X, Buffer, 5);
19119e8befaSSam Clegg   assert(SizeLen == 5);
19219e8befaSSam Clegg   Stream.pwrite((char *)Buffer, SizeLen, Offset);
19319e8befaSSam Clegg }
19419e8befaSSam Clegg 
19519e8befaSSam Clegg // Write X as an signed LEB value at offset Offset in Stream, padded
19619e8befaSSam Clegg // to allow patching.
19718c56a07SHeejin Ahn static void writePatchableSLEB(raw_pwrite_stream &Stream, int32_t X,
19819e8befaSSam Clegg                                uint64_t Offset) {
19919e8befaSSam Clegg   uint8_t Buffer[5];
20019e8befaSSam Clegg   unsigned SizeLen = encodeSLEB128(X, Buffer, 5);
20119e8befaSSam Clegg   assert(SizeLen == 5);
20219e8befaSSam Clegg   Stream.pwrite((char *)Buffer, SizeLen, Offset);
20319e8befaSSam Clegg }
20419e8befaSSam Clegg 
20519e8befaSSam Clegg // Write X as a plain integer value at offset Offset in Stream.
20618c56a07SHeejin Ahn static void writeI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
20719e8befaSSam Clegg   uint8_t Buffer[4];
20819e8befaSSam Clegg   support::endian::write32le(Buffer, X);
20919e8befaSSam Clegg   Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
21019e8befaSSam Clegg }
21119e8befaSSam Clegg 
21218eafb6cSDan Gohman class WasmObjectWriter : public MCObjectWriter {
213f17b149dSPeter Collingbourne   support::endian::Writer W;
214f17b149dSPeter Collingbourne 
21518eafb6cSDan Gohman   /// The target specific Wasm writer instance.
21618eafb6cSDan Gohman   std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
21718eafb6cSDan Gohman 
218d934cb88SDan Gohman   // Relocations for fixing up references in the code section.
219d934cb88SDan Gohman   std::vector<WasmRelocationEntry> CodeRelocations;
2206f08c84aSSam Clegg   uint32_t CodeSectionIndex;
221d934cb88SDan Gohman 
222d934cb88SDan Gohman   // Relocations for fixing up references in the data section.
223d934cb88SDan Gohman   std::vector<WasmRelocationEntry> DataRelocations;
2246f08c84aSSam Clegg   uint32_t DataSectionIndex;
225d934cb88SDan Gohman 
226d934cb88SDan Gohman   // Index values to use for fixing up call_indirect type indices.
227acd7d2b0SSam Clegg   // Maps function symbols to the index of the type of the function
228acd7d2b0SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
229d99f6078SSam Clegg   // Maps function symbols to the table element index space. Used
230d99f6078SSam Clegg   // for TABLE_INDEX relocation types (i.e. address taken functions).
231f9edbe95SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> TableIndices;
232da419bdbSHeejin Ahn   // Maps function/global symbols to the function/global/event/section index
233da419bdbSHeejin Ahn   // space.
2346c899ba6SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> WasmIndices;
235492f7529SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> GOTIndices;
2366c899ba6SSam Clegg   // Maps data symbols to the Wasm segment and offset/size with the segment.
2376c899ba6SSam Clegg   DenseMap<const MCSymbolWasm *, wasm::WasmDataReference> DataLocations;
2386a31a0d6SSam Clegg 
2396a31a0d6SSam Clegg   // Stores output data (index, relocations, content offset) for custom
2406a31a0d6SSam Clegg   // section.
2416a31a0d6SSam Clegg   std::vector<WasmCustomSection> CustomSections;
242cbda16ebSThomas Lively   std::unique_ptr<WasmCustomSection> ProducersSection;
243f6f4f843SThomas Lively   std::unique_ptr<WasmCustomSection> TargetFeaturesSection;
2446a31a0d6SSam Clegg   // Relocations for fixing up references in the custom sections.
2456a31a0d6SSam Clegg   DenseMap<const MCSectionWasm *, std::vector<WasmRelocationEntry>>
2466a31a0d6SSam Clegg       CustomSectionsRelocations;
247acd7d2b0SSam Clegg 
248c0d41195SSam Clegg   // Map from section to defining function symbol.
2496ccb59b3SSam Clegg   DenseMap<const MCSection *, const MCSymbol *> SectionFunctions;
2506ccb59b3SSam Clegg 
251da419bdbSHeejin Ahn   DenseMap<WasmSignature, uint32_t, WasmSignatureDenseMapInfo> SignatureIndices;
252da419bdbSHeejin Ahn   SmallVector<WasmSignature, 4> Signatures;
2536c899ba6SSam Clegg   SmallVector<WasmDataSegment, 4> DataSegments;
2549f3fe42eSSam Clegg   unsigned NumFunctionImports = 0;
2557c395943SSam Clegg   unsigned NumGlobalImports = 0;
256da419bdbSHeejin Ahn   unsigned NumEventImports = 0;
2577e1c3345SChandler Carruth   uint32_t SectionCount = 0;
258d934cb88SDan Gohman 
25918eafb6cSDan Gohman   // TargetObjectWriter wrappers.
26018eafb6cSDan Gohman   bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
261da84b688SDan Gohman   bool isEmscripten() const { return TargetObjectWriter->isEmscripten(); }
26218eafb6cSDan Gohman 
2632322a937SSam Clegg   void startSection(SectionBookkeeping &Section, unsigned SectionId);
2642322a937SSam Clegg   void startCustomSection(SectionBookkeeping &Section, StringRef Name);
265d934cb88SDan Gohman   void endSection(SectionBookkeeping &Section);
266d934cb88SDan Gohman 
26718eafb6cSDan Gohman public:
2681301a878SLang Hames   WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
2691301a878SLang Hames                    raw_pwrite_stream &OS)
27059a6fc46SPeter Collingbourne       : W(OS, support::little), TargetObjectWriter(std::move(MOTW)) {}
27118eafb6cSDan Gohman 
2720917c9e4SDan Gohman private:
273acd7d2b0SSam Clegg   void reset() override {
274acd7d2b0SSam Clegg     CodeRelocations.clear();
275acd7d2b0SSam Clegg     DataRelocations.clear();
276acd7d2b0SSam Clegg     TypeIndices.clear();
2776c899ba6SSam Clegg     WasmIndices.clear();
278492f7529SSam Clegg     GOTIndices.clear();
279f9edbe95SSam Clegg     TableIndices.clear();
2806c899ba6SSam Clegg     DataLocations.clear();
281cbda16ebSThomas Lively     CustomSections.clear();
282cbda16ebSThomas Lively     ProducersSection.reset();
283f6f4f843SThomas Lively     TargetFeaturesSection.reset();
2846a31a0d6SSam Clegg     CustomSectionsRelocations.clear();
285da419bdbSHeejin Ahn     SignatureIndices.clear();
286da419bdbSHeejin Ahn     Signatures.clear();
2876c899ba6SSam Clegg     DataSegments.clear();
2886ccb59b3SSam Clegg     SectionFunctions.clear();
2899f3fe42eSSam Clegg     NumFunctionImports = 0;
2907c395943SSam Clegg     NumGlobalImports = 0;
291105bdc25SSam Clegg     MCObjectWriter::reset();
292acd7d2b0SSam Clegg   }
293acd7d2b0SSam Clegg 
29418eafb6cSDan Gohman   void writeHeader(const MCAssembler &Asm);
29518eafb6cSDan Gohman 
29618eafb6cSDan Gohman   void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
29718eafb6cSDan Gohman                         const MCFragment *Fragment, const MCFixup &Fixup,
298ceecfe5bSRafael Espindola                         MCValue Target, uint64_t &FixedValue) override;
29918eafb6cSDan Gohman 
30018eafb6cSDan Gohman   void executePostLayoutBinding(MCAssembler &Asm,
30118eafb6cSDan Gohman                                 const MCAsmLayout &Layout) override;
30218eafb6cSDan Gohman 
303438390faSPeter Collingbourne   uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
3049e15f359SSam Clegg 
305b7787fd0SSam Clegg   void writeString(const StringRef Str) {
306f17b149dSPeter Collingbourne     encodeULEB128(Str.size(), W.OS);
307f17b149dSPeter Collingbourne     W.OS << Str;
308b7787fd0SSam Clegg   }
309b7787fd0SSam Clegg 
310f208f631SHeejin Ahn   void writeValueType(wasm::ValType Ty) { W.OS << static_cast<char>(Ty); }
3119e15f359SSam Clegg 
312da419bdbSHeejin Ahn   void writeTypeSection(ArrayRef<WasmSignature> Signatures);
3138defa952SSam Clegg   void writeImportSection(ArrayRef<wasm::WasmImport> Imports, uint32_t DataSize,
314f950b24aSSam Clegg                           uint32_t NumElements);
315457fb0b4SSam Clegg   void writeFunctionSection(ArrayRef<WasmFunction> Functions);
3168defa952SSam Clegg   void writeExportSection(ArrayRef<wasm::WasmExport> Exports);
317457fb0b4SSam Clegg   void writeElemSection(ArrayRef<uint32_t> TableElems);
318fef8de66SThomas Lively   void writeDataCountSection();
3199e15f359SSam Clegg   void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
320457fb0b4SSam Clegg                         ArrayRef<WasmFunction> Functions);
3216c899ba6SSam Clegg   void writeDataSection();
322da419bdbSHeejin Ahn   void writeEventSection(ArrayRef<wasm::WasmEventType> Events);
3236f08c84aSSam Clegg   void writeRelocSection(uint32_t SectionIndex, StringRef Name,
324f77dc2a8SSam Clegg                          std::vector<WasmRelocationEntry> &Relocations);
32531a2c809SSam Clegg   void writeLinkingMetaDataSection(
32686b4a09aSSam Clegg       ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
327ea7caceeSSam Clegg       ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
328ea7caceeSSam Clegg       const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats);
329cbda16ebSThomas Lively   void writeCustomSection(WasmCustomSection &CustomSection,
330cbda16ebSThomas Lively                           const MCAssembler &Asm, const MCAsmLayout &Layout);
3316a31a0d6SSam Clegg   void writeCustomRelocSections();
3326a31a0d6SSam Clegg   void
3336a31a0d6SSam Clegg   updateCustomSectionRelocations(const SmallVector<WasmFunction, 4> &Functions,
3346a31a0d6SSam Clegg                                  const MCAsmLayout &Layout);
335acd7d2b0SSam Clegg 
3367c395943SSam Clegg   uint32_t getProvisionalValue(const WasmRelocationEntry &RelEntry);
337acd7d2b0SSam Clegg   void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
338acd7d2b0SSam Clegg                         uint64_t ContentsOffset);
339acd7d2b0SSam Clegg 
340acd7d2b0SSam Clegg   uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
3415e3d33a7SSam Clegg   uint32_t getFunctionType(const MCSymbolWasm &Symbol);
342da419bdbSHeejin Ahn   uint32_t getEventType(const MCSymbolWasm &Symbol);
34338b12f5eSHeejin Ahn   void registerFunctionType(const MCSymbolWasm &Symbol);
34438b12f5eSHeejin Ahn   void registerEventType(const MCSymbolWasm &Symbol);
34518eafb6cSDan Gohman };
3469e15f359SSam Clegg 
34718eafb6cSDan Gohman } // end anonymous namespace
34818eafb6cSDan Gohman 
349d934cb88SDan Gohman // Write out a section header and a patchable section size field.
350d934cb88SDan Gohman void WasmObjectWriter::startSection(SectionBookkeeping &Section,
3512322a937SSam Clegg                                     unsigned SectionId) {
352d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "startSection " << SectionId << "\n");
353f17b149dSPeter Collingbourne   W.OS << char(SectionId);
354d934cb88SDan Gohman 
355f17b149dSPeter Collingbourne   Section.SizeOffset = W.OS.tell();
356d934cb88SDan Gohman 
357d934cb88SDan Gohman   // The section size. We don't know the size yet, so reserve enough space
358d934cb88SDan Gohman   // for any 32-bit value; we'll patch it later.
35919e8befaSSam Clegg   encodeULEB128(0, W.OS, 5);
360d934cb88SDan Gohman 
361d934cb88SDan Gohman   // The position where the section starts, for measuring its size.
362f17b149dSPeter Collingbourne   Section.ContentsOffset = W.OS.tell();
363f17b149dSPeter Collingbourne   Section.PayloadOffset = W.OS.tell();
3646f08c84aSSam Clegg   Section.Index = SectionCount++;
365d934cb88SDan Gohman }
3662322a937SSam Clegg 
3672322a937SSam Clegg void WasmObjectWriter::startCustomSection(SectionBookkeeping &Section,
3682322a937SSam Clegg                                           StringRef Name) {
369d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "startCustomSection " << Name << "\n");
3702322a937SSam Clegg   startSection(Section, wasm::WASM_SEC_CUSTOM);
3716a31a0d6SSam Clegg 
3726a31a0d6SSam Clegg   // The position where the section header ends, for measuring its size.
373f17b149dSPeter Collingbourne   Section.PayloadOffset = W.OS.tell();
3746a31a0d6SSam Clegg 
3752322a937SSam Clegg   // Custom sections in wasm also have a string identifier.
3762322a937SSam Clegg   writeString(Name);
3776a31a0d6SSam Clegg 
3786a31a0d6SSam Clegg   // The position where the custom section starts.
379f17b149dSPeter Collingbourne   Section.ContentsOffset = W.OS.tell();
380d934cb88SDan Gohman }
381d934cb88SDan Gohman 
382d934cb88SDan Gohman // Now that the section is complete and we know how big it is, patch up the
383d934cb88SDan Gohman // section size field at the start of the section.
384d934cb88SDan Gohman void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
385c0affde8SSam Clegg   uint64_t Size = W.OS.tell();
386c0affde8SSam Clegg   // /dev/null doesn't support seek/tell and can report offset of 0.
387c0affde8SSam Clegg   // Simply skip this patching in that case.
388c0affde8SSam Clegg   if (!Size)
389c0affde8SSam Clegg     return;
390c0affde8SSam Clegg 
391c0affde8SSam Clegg   Size -= Section.PayloadOffset;
392d934cb88SDan Gohman   if (uint32_t(Size) != Size)
393d934cb88SDan Gohman     report_fatal_error("section size does not fit in a uint32_t");
394d934cb88SDan Gohman 
395d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "endSection size=" << Size << "\n");
396d934cb88SDan Gohman 
397d934cb88SDan Gohman   // Write the final section size to the payload_len field, which follows
398d934cb88SDan Gohman   // the section id byte.
39918c56a07SHeejin Ahn   writePatchableLEB(static_cast<raw_pwrite_stream &>(W.OS), Size,
400f17b149dSPeter Collingbourne                     Section.SizeOffset);
401d934cb88SDan Gohman }
402d934cb88SDan Gohman 
40318eafb6cSDan Gohman // Emit the Wasm header.
40418eafb6cSDan Gohman void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
405f17b149dSPeter Collingbourne   W.OS.write(wasm::WasmMagic, sizeof(wasm::WasmMagic));
406f17b149dSPeter Collingbourne   W.write<uint32_t>(wasm::WasmVersion);
40718eafb6cSDan Gohman }
40818eafb6cSDan Gohman 
40918eafb6cSDan Gohman void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
41018eafb6cSDan Gohman                                                 const MCAsmLayout &Layout) {
4116ccb59b3SSam Clegg   // Build a map of sections to the function that defines them, for use
4126ccb59b3SSam Clegg   // in recordRelocation.
4136ccb59b3SSam Clegg   for (const MCSymbol &S : Asm.symbols()) {
4146ccb59b3SSam Clegg     const auto &WS = static_cast<const MCSymbolWasm &>(S);
4156ccb59b3SSam Clegg     if (WS.isDefined() && WS.isFunction() && !WS.isVariable()) {
4166ccb59b3SSam Clegg       const auto &Sec = static_cast<const MCSectionWasm &>(S.getSection());
4176ccb59b3SSam Clegg       auto Pair = SectionFunctions.insert(std::make_pair(&Sec, &S));
4186ccb59b3SSam Clegg       if (!Pair.second)
4196ccb59b3SSam Clegg         report_fatal_error("section already has a defining function: " +
420*7d1ff446SFangrui Song                            Sec.getName());
4216ccb59b3SSam Clegg     }
4226ccb59b3SSam Clegg   }
42318eafb6cSDan Gohman }
42418eafb6cSDan Gohman 
42518eafb6cSDan Gohman void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
42618eafb6cSDan Gohman                                         const MCAsmLayout &Layout,
42718eafb6cSDan Gohman                                         const MCFragment *Fragment,
42818eafb6cSDan Gohman                                         const MCFixup &Fixup, MCValue Target,
429ceecfe5bSRafael Espindola                                         uint64_t &FixedValue) {
430ecc5e808SSam Clegg   // The WebAssembly backend should never generate FKF_IsPCRel fixups
431e828ce1bSFangrui Song   assert(!(Asm.getBackend().getFixupKindInfo(Fixup.getKind()).Flags &
432ecc5e808SSam Clegg            MCFixupKindInfo::FKF_IsPCRel));
433ecc5e808SSam Clegg 
434fe6414b0SSam Clegg   const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
435d934cb88SDan Gohman   uint64_t C = Target.getConstant();
436d934cb88SDan Gohman   uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
437d934cb88SDan Gohman   MCContext &Ctx = Asm.getContext();
438d934cb88SDan Gohman 
439d934cb88SDan Gohman   if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
440ecc5e808SSam Clegg     // To get here the A - B expression must have failed evaluateAsRelocatable.
441ecc5e808SSam Clegg     // This means either A or B must be undefined and in WebAssembly we can't
442ecc5e808SSam Clegg     // support either of those cases.
443ecc5e808SSam Clegg     const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
444d934cb88SDan Gohman     Ctx.reportError(
445d934cb88SDan Gohman         Fixup.getLoc(),
446d934cb88SDan Gohman         Twine("symbol '") + SymB.getName() +
447ecc5e808SSam Clegg             "': unsupported subtraction expression used in relocation.");
448d934cb88SDan Gohman     return;
449d934cb88SDan Gohman   }
450d934cb88SDan Gohman 
451d934cb88SDan Gohman   // We either rejected the fixup or folded B into C at this point.
452d934cb88SDan Gohman   const MCSymbolRefExpr *RefA = Target.getSymA();
453ecc5e808SSam Clegg   const auto *SymA = cast<MCSymbolWasm>(&RefA->getSymbol());
454d934cb88SDan Gohman 
4553ea1c62cSSam Clegg   // The .init_array isn't translated as data, so don't do relocations in it.
456*7d1ff446SFangrui Song   if (FixupSection.getName().startswith(".init_array")) {
4573ea1c62cSSam Clegg     SymA->setUsedInInitArray();
4583ea1c62cSSam Clegg     return;
4593ea1c62cSSam Clegg   }
4603ea1c62cSSam Clegg 
461ecc5e808SSam Clegg   if (SymA->isVariable()) {
462d934cb88SDan Gohman     const MCExpr *Expr = SymA->getVariableValue();
4636ad8f190SSam Clegg     const auto *Inner = cast<MCSymbolRefExpr>(Expr);
4646ad8f190SSam Clegg     if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
4656ad8f190SSam Clegg       llvm_unreachable("weakref used in reloc not yet implemented");
466d934cb88SDan Gohman   }
467d934cb88SDan Gohman 
468d934cb88SDan Gohman   // Put any constant offset in an addend. Offsets can be negative, and
469d934cb88SDan Gohman   // LLVM expects wrapping, in contrast to wasm's immediates which can't
470d934cb88SDan Gohman   // be negative and don't wrap.
471d934cb88SDan Gohman   FixedValue = 0;
472d934cb88SDan Gohman 
473a5e175c6SSam Clegg   unsigned Type = TargetObjectWriter->getRelocType(Target, Fixup);
4749d24fb7fSSam Clegg 
4754d57fbd0SSam Clegg   // Absolute offset within a section or a function.
4764d57fbd0SSam Clegg   // Currently only supported for for metadata sections.
4774d57fbd0SSam Clegg   // See: test/MC/WebAssembly/blockaddress.ll
478d1152a26SSam Clegg   if (Type == wasm::R_WASM_FUNCTION_OFFSET_I32 ||
479d1152a26SSam Clegg       Type == wasm::R_WASM_SECTION_OFFSET_I32) {
4804d57fbd0SSam Clegg     if (!FixupSection.getKind().isMetadata())
4814d57fbd0SSam Clegg       report_fatal_error("relocations for function or section offsets are "
4824d57fbd0SSam Clegg                          "only supported in metadata sections");
4834d57fbd0SSam Clegg 
4844d57fbd0SSam Clegg     const MCSymbol *SectionSymbol = nullptr;
4854d57fbd0SSam Clegg     const MCSection &SecA = SymA->getSection();
4864d57fbd0SSam Clegg     if (SecA.getKind().isText())
4876ccb59b3SSam Clegg       SectionSymbol = SectionFunctions.find(&SecA)->second;
4884d57fbd0SSam Clegg     else
4894d57fbd0SSam Clegg       SectionSymbol = SecA.getBeginSymbol();
4904d57fbd0SSam Clegg     if (!SectionSymbol)
4914d57fbd0SSam Clegg       report_fatal_error("section symbol is required for relocation");
4924d57fbd0SSam Clegg 
4934d57fbd0SSam Clegg     C += Layout.getSymbolOffset(*SymA);
4944d57fbd0SSam Clegg     SymA = cast<MCSymbolWasm>(SectionSymbol);
4954d57fbd0SSam Clegg   }
4964d57fbd0SSam Clegg 
497d1152a26SSam Clegg   // Relocation other than R_WASM_TYPE_INDEX_LEB are required to be
4984d57fbd0SSam Clegg   // against a named symbol.
499d1152a26SSam Clegg   if (Type != wasm::R_WASM_TYPE_INDEX_LEB) {
5004d57fbd0SSam Clegg     if (SymA->getName().empty())
5014d57fbd0SSam Clegg       report_fatal_error("relocations against un-named temporaries are not yet "
5024d57fbd0SSam Clegg                          "supported by wasm");
5034d57fbd0SSam Clegg 
5044d57fbd0SSam Clegg     SymA->setUsedInReloc();
5054d57fbd0SSam Clegg   }
506ae03c1e7SSam Clegg 
507492f7529SSam Clegg   if (RefA->getKind() == MCSymbolRefExpr::VK_GOT)
508492f7529SSam Clegg     SymA->setUsedInGOT();
509492f7529SSam Clegg 
510d934cb88SDan Gohman   WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
511d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
512d934cb88SDan Gohman 
5136a31a0d6SSam Clegg   if (FixupSection.isWasmData()) {
514d934cb88SDan Gohman     DataRelocations.push_back(Rec);
5156a31a0d6SSam Clegg   } else if (FixupSection.getKind().isText()) {
51612fd3da9SSam Clegg     CodeRelocations.push_back(Rec);
5176a31a0d6SSam Clegg   } else if (FixupSection.getKind().isMetadata()) {
5186a31a0d6SSam Clegg     CustomSectionsRelocations[&FixupSection].push_back(Rec);
5196a31a0d6SSam Clegg   } else {
52012fd3da9SSam Clegg     llvm_unreachable("unexpected section type");
521d934cb88SDan Gohman   }
5226a31a0d6SSam Clegg }
523d934cb88SDan Gohman 
52418c56a07SHeejin Ahn static const MCSymbolWasm *resolveSymbol(const MCSymbolWasm &Symbol) {
525ffba00bdSSam Clegg   const MCSymbolWasm* Ret = &Symbol;
526ffba00bdSSam Clegg   while (Ret->isVariable()) {
527ffba00bdSSam Clegg     const MCExpr *Expr = Ret->getVariableValue();
528aff1c4dfSSam Clegg     auto *Inner = cast<MCSymbolRefExpr>(Expr);
529ffba00bdSSam Clegg     Ret = cast<MCSymbolWasm>(&Inner->getSymbol());
530aff1c4dfSSam Clegg   }
531ffba00bdSSam Clegg   return Ret;
532aff1c4dfSSam Clegg }
533aff1c4dfSSam Clegg 
534d934cb88SDan Gohman // Compute a value to write into the code at the location covered
53560ec3034SSam Clegg // by RelEntry. This value isn't used by the static linker; it just serves
53660ec3034SSam Clegg // to make the object format more readable and more likely to be directly
53760ec3034SSam Clegg // useable.
5387c395943SSam Clegg uint32_t
5397c395943SSam Clegg WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) {
540492f7529SSam Clegg   if (RelEntry.Type == wasm::R_WASM_GLOBAL_INDEX_LEB && !RelEntry.Symbol->isGlobal()) {
541492f7529SSam Clegg     assert(GOTIndices.count(RelEntry.Symbol) > 0 && "symbol not found in GOT index space");
542492f7529SSam Clegg     return GOTIndices[RelEntry.Symbol];
543492f7529SSam Clegg   }
544492f7529SSam Clegg 
54560ec3034SSam Clegg   switch (RelEntry.Type) {
5462a7cac93SSam Clegg   case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
547d1152a26SSam Clegg   case wasm::R_WASM_TABLE_INDEX_SLEB:
548d1152a26SSam Clegg   case wasm::R_WASM_TABLE_INDEX_I32: {
549f9edbe95SSam Clegg     // Provisional value is table address of the resolved symbol itself
55018c56a07SHeejin Ahn     const MCSymbolWasm *Sym = resolveSymbol(*RelEntry.Symbol);
551f9edbe95SSam Clegg     assert(Sym->isFunction());
552f9edbe95SSam Clegg     return TableIndices[Sym];
553f9edbe95SSam Clegg   }
554d1152a26SSam Clegg   case wasm::R_WASM_TYPE_INDEX_LEB:
5556c899ba6SSam Clegg     // Provisional value is same as the index
55660ec3034SSam Clegg     return getRelocationIndexValue(RelEntry);
557d1152a26SSam Clegg   case wasm::R_WASM_FUNCTION_INDEX_LEB:
558d1152a26SSam Clegg   case wasm::R_WASM_GLOBAL_INDEX_LEB:
559d1152a26SSam Clegg   case wasm::R_WASM_EVENT_INDEX_LEB:
560da419bdbSHeejin Ahn     // Provisional value is function/global/event Wasm index
561492f7529SSam Clegg     assert(WasmIndices.count(RelEntry.Symbol) > 0 && "symbol not found in wasm index space");
5626c899ba6SSam Clegg     return WasmIndices[RelEntry.Symbol];
563d1152a26SSam Clegg   case wasm::R_WASM_FUNCTION_OFFSET_I32:
564d1152a26SSam Clegg   case wasm::R_WASM_SECTION_OFFSET_I32: {
5656a31a0d6SSam Clegg     const auto &Section =
5666a31a0d6SSam Clegg         static_cast<const MCSectionWasm &>(RelEntry.Symbol->getSection());
5676a31a0d6SSam Clegg     return Section.getSectionOffset() + RelEntry.Addend;
5686a31a0d6SSam Clegg   }
569d1152a26SSam Clegg   case wasm::R_WASM_MEMORY_ADDR_LEB:
570d1152a26SSam Clegg   case wasm::R_WASM_MEMORY_ADDR_I32:
5712a7cac93SSam Clegg   case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
572d1152a26SSam Clegg   case wasm::R_WASM_MEMORY_ADDR_SLEB: {
573f9edbe95SSam Clegg     // Provisional value is address of the global
57418c56a07SHeejin Ahn     const MCSymbolWasm *Sym = resolveSymbol(*RelEntry.Symbol);
575270ed1b3SSam Clegg     // For undefined symbols, use zero
576cd65f698SSam Clegg     if (!Sym->isDefined())
577270ed1b3SSam Clegg       return 0;
5786c899ba6SSam Clegg     const wasm::WasmDataReference &Ref = DataLocations[Sym];
5796c899ba6SSam Clegg     const WasmDataSegment &Segment = DataSegments[Ref.Segment];
580d934cb88SDan Gohman     // Ignore overflow. LLVM allows address arithmetic to silently wrap.
5816c899ba6SSam Clegg     return Segment.Offset + Ref.Offset + RelEntry.Addend;
58260ec3034SSam Clegg   }
58360ec3034SSam Clegg   default:
58460ec3034SSam Clegg     llvm_unreachable("invalid relocation type");
58560ec3034SSam Clegg   }
586d934cb88SDan Gohman }
587d934cb88SDan Gohman 
588759631c7SSam Clegg static void addData(SmallVectorImpl<char> &DataBytes,
58963ebb813SSam Clegg                     MCSectionWasm &DataSection) {
590*7d1ff446SFangrui Song   LLVM_DEBUG(errs() << "addData: " << DataSection.getName() << "\n");
591759631c7SSam Clegg 
59263ebb813SSam Clegg   DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
59363ebb813SSam Clegg 
594759631c7SSam Clegg   for (const MCFragment &Frag : DataSection) {
595759631c7SSam Clegg     if (Frag.hasInstructions())
596759631c7SSam Clegg       report_fatal_error("only data supported in data sections");
597759631c7SSam Clegg 
598759631c7SSam Clegg     if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
599759631c7SSam Clegg       if (Align->getValueSize() != 1)
600759631c7SSam Clegg         report_fatal_error("only byte values supported for alignment");
601759631c7SSam Clegg       // If nops are requested, use zeros, as this is the data section.
602759631c7SSam Clegg       uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
603f208f631SHeejin Ahn       uint64_t Size =
604f208f631SHeejin Ahn           std::min<uint64_t>(alignTo(DataBytes.size(), Align->getAlignment()),
605f208f631SHeejin Ahn                              DataBytes.size() + Align->getMaxBytesToEmit());
606759631c7SSam Clegg       DataBytes.resize(Size, Value);
607759631c7SSam Clegg     } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
608588fad4dSNirav Dave       int64_t NumValues;
609588fad4dSNirav Dave       if (!Fill->getNumValues().evaluateAsAbsolute(NumValues))
610d707c370SRafael Espindola         llvm_unreachable("The fill should be an assembler constant");
611588fad4dSNirav Dave       DataBytes.insert(DataBytes.end(), Fill->getValueSize() * NumValues,
612588fad4dSNirav Dave                        Fill->getValue());
61324faf859SHeejin Ahn     } else if (auto *LEB = dyn_cast<MCLEBFragment>(&Frag)) {
61424faf859SHeejin Ahn       const SmallVectorImpl<char> &Contents = LEB->getContents();
61524faf859SHeejin Ahn       DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
616759631c7SSam Clegg     } else {
617759631c7SSam Clegg       const auto &DataFrag = cast<MCDataFragment>(Frag);
618759631c7SSam Clegg       const SmallVectorImpl<char> &Contents = DataFrag.getContents();
619759631c7SSam Clegg       DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
620759631c7SSam Clegg     }
621759631c7SSam Clegg   }
622759631c7SSam Clegg 
623d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
624759631c7SSam Clegg }
625759631c7SSam Clegg 
62660ec3034SSam Clegg uint32_t
62760ec3034SSam Clegg WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
628d1152a26SSam Clegg   if (RelEntry.Type == wasm::R_WASM_TYPE_INDEX_LEB) {
629b7787fd0SSam Clegg     if (!TypeIndices.count(RelEntry.Symbol))
630b7787fd0SSam Clegg       report_fatal_error("symbol not found in type index space: " +
631b7787fd0SSam Clegg                          RelEntry.Symbol->getName());
632acd7d2b0SSam Clegg     return TypeIndices[RelEntry.Symbol];
633acd7d2b0SSam Clegg   }
63460ec3034SSam Clegg 
63525d8e68bSSam Clegg   return RelEntry.Symbol->getIndex();
636acd7d2b0SSam Clegg }
637acd7d2b0SSam Clegg 
638d934cb88SDan Gohman // Apply the portions of the relocation records that we can handle ourselves
639d934cb88SDan Gohman // directly.
640acd7d2b0SSam Clegg void WasmObjectWriter::applyRelocations(
641acd7d2b0SSam Clegg     ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
642f17b149dSPeter Collingbourne   auto &Stream = static_cast<raw_pwrite_stream &>(W.OS);
643d934cb88SDan Gohman   for (const WasmRelocationEntry &RelEntry : Relocations) {
644d934cb88SDan Gohman     uint64_t Offset = ContentsOffset +
645d934cb88SDan Gohman                       RelEntry.FixupSection->getSectionOffset() +
646d934cb88SDan Gohman                       RelEntry.Offset;
647d934cb88SDan Gohman 
648d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
64960ec3034SSam Clegg     uint32_t Value = getProvisionalValue(RelEntry);
65060ec3034SSam Clegg 
651acd7d2b0SSam Clegg     switch (RelEntry.Type) {
652d1152a26SSam Clegg     case wasm::R_WASM_FUNCTION_INDEX_LEB:
653d1152a26SSam Clegg     case wasm::R_WASM_TYPE_INDEX_LEB:
654d1152a26SSam Clegg     case wasm::R_WASM_GLOBAL_INDEX_LEB:
655d1152a26SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_LEB:
656d1152a26SSam Clegg     case wasm::R_WASM_EVENT_INDEX_LEB:
65718c56a07SHeejin Ahn       writePatchableLEB(Stream, Value, Offset);
658d934cb88SDan Gohman       break;
659d1152a26SSam Clegg     case wasm::R_WASM_TABLE_INDEX_I32:
660d1152a26SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_I32:
661d1152a26SSam Clegg     case wasm::R_WASM_FUNCTION_OFFSET_I32:
662d1152a26SSam Clegg     case wasm::R_WASM_SECTION_OFFSET_I32:
66318c56a07SHeejin Ahn       writeI32(Stream, Value, Offset);
664d934cb88SDan Gohman       break;
665d1152a26SSam Clegg     case wasm::R_WASM_TABLE_INDEX_SLEB:
6662a7cac93SSam Clegg     case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
667d1152a26SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_SLEB:
6682a7cac93SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
66918c56a07SHeejin Ahn       writePatchableSLEB(Stream, Value, Offset);
67060ec3034SSam Clegg       break;
671d934cb88SDan Gohman     default:
6729d24fb7fSSam Clegg       llvm_unreachable("invalid relocation type");
673d934cb88SDan Gohman     }
674d934cb88SDan Gohman   }
67518eafb6cSDan Gohman }
67618eafb6cSDan Gohman 
677da419bdbSHeejin Ahn void WasmObjectWriter::writeTypeSection(ArrayRef<WasmSignature> Signatures) {
678da419bdbSHeejin Ahn   if (Signatures.empty())
6799e15f359SSam Clegg     return;
6809e15f359SSam Clegg 
6819e15f359SSam Clegg   SectionBookkeeping Section;
6829e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_TYPE);
6839e15f359SSam Clegg 
684da419bdbSHeejin Ahn   encodeULEB128(Signatures.size(), W.OS);
6859e15f359SSam Clegg 
686da419bdbSHeejin Ahn   for (const WasmSignature &Sig : Signatures) {
687f17b149dSPeter Collingbourne     W.OS << char(wasm::WASM_TYPE_FUNC);
688da419bdbSHeejin Ahn     encodeULEB128(Sig.Params.size(), W.OS);
689da419bdbSHeejin Ahn     for (wasm::ValType Ty : Sig.Params)
6909e15f359SSam Clegg       writeValueType(Ty);
691da419bdbSHeejin Ahn     encodeULEB128(Sig.Returns.size(), W.OS);
692da419bdbSHeejin Ahn     for (wasm::ValType Ty : Sig.Returns)
6939e15f359SSam Clegg       writeValueType(Ty);
6949e15f359SSam Clegg   }
6959e15f359SSam Clegg 
6969e15f359SSam Clegg   endSection(Section);
6979e15f359SSam Clegg }
6989e15f359SSam Clegg 
6998defa952SSam Clegg void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports,
700f950b24aSSam Clegg                                           uint32_t DataSize,
701f950b24aSSam Clegg                                           uint32_t NumElements) {
7029e15f359SSam Clegg   if (Imports.empty())
7039e15f359SSam Clegg     return;
7049e15f359SSam Clegg 
705f950b24aSSam Clegg   uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
706f950b24aSSam Clegg 
7079e15f359SSam Clegg   SectionBookkeeping Section;
7089e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_IMPORT);
7099e15f359SSam Clegg 
710f17b149dSPeter Collingbourne   encodeULEB128(Imports.size(), W.OS);
7118defa952SSam Clegg   for (const wasm::WasmImport &Import : Imports) {
7128defa952SSam Clegg     writeString(Import.Module);
7138defa952SSam Clegg     writeString(Import.Field);
714f17b149dSPeter Collingbourne     W.OS << char(Import.Kind);
7159e15f359SSam Clegg 
7169e15f359SSam Clegg     switch (Import.Kind) {
7179e15f359SSam Clegg     case wasm::WASM_EXTERNAL_FUNCTION:
718f17b149dSPeter Collingbourne       encodeULEB128(Import.SigIndex, W.OS);
7199e15f359SSam Clegg       break;
7209e15f359SSam Clegg     case wasm::WASM_EXTERNAL_GLOBAL:
721f17b149dSPeter Collingbourne       W.OS << char(Import.Global.Type);
722f17b149dSPeter Collingbourne       W.OS << char(Import.Global.Mutable ? 1 : 0);
7239e15f359SSam Clegg       break;
724f950b24aSSam Clegg     case wasm::WASM_EXTERNAL_MEMORY:
725f17b149dSPeter Collingbourne       encodeULEB128(0, W.OS);        // flags
726f17b149dSPeter Collingbourne       encodeULEB128(NumPages, W.OS); // initial
727f950b24aSSam Clegg       break;
728f950b24aSSam Clegg     case wasm::WASM_EXTERNAL_TABLE:
729f17b149dSPeter Collingbourne       W.OS << char(Import.Table.ElemType);
730f17b149dSPeter Collingbourne       encodeULEB128(0, W.OS);           // flags
731f17b149dSPeter Collingbourne       encodeULEB128(NumElements, W.OS); // initial
732f950b24aSSam Clegg       break;
733da419bdbSHeejin Ahn     case wasm::WASM_EXTERNAL_EVENT:
734da419bdbSHeejin Ahn       encodeULEB128(Import.Event.Attribute, W.OS);
735da419bdbSHeejin Ahn       encodeULEB128(Import.Event.SigIndex, W.OS);
736da419bdbSHeejin Ahn       break;
7379e15f359SSam Clegg     default:
7389e15f359SSam Clegg       llvm_unreachable("unsupported import kind");
7399e15f359SSam Clegg     }
7409e15f359SSam Clegg   }
7419e15f359SSam Clegg 
7429e15f359SSam Clegg   endSection(Section);
7439e15f359SSam Clegg }
7449e15f359SSam Clegg 
745457fb0b4SSam Clegg void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
7469e15f359SSam Clegg   if (Functions.empty())
7479e15f359SSam Clegg     return;
7489e15f359SSam Clegg 
7499e15f359SSam Clegg   SectionBookkeeping Section;
7509e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_FUNCTION);
7519e15f359SSam Clegg 
752f17b149dSPeter Collingbourne   encodeULEB128(Functions.size(), W.OS);
7539e15f359SSam Clegg   for (const WasmFunction &Func : Functions)
754da419bdbSHeejin Ahn     encodeULEB128(Func.SigIndex, W.OS);
7559e15f359SSam Clegg 
7569e15f359SSam Clegg   endSection(Section);
7579e15f359SSam Clegg }
7589e15f359SSam Clegg 
759da419bdbSHeejin Ahn void WasmObjectWriter::writeEventSection(ArrayRef<wasm::WasmEventType> Events) {
760da419bdbSHeejin Ahn   if (Events.empty())
761da419bdbSHeejin Ahn     return;
762da419bdbSHeejin Ahn 
763da419bdbSHeejin Ahn   SectionBookkeeping Section;
764da419bdbSHeejin Ahn   startSection(Section, wasm::WASM_SEC_EVENT);
765da419bdbSHeejin Ahn 
766da419bdbSHeejin Ahn   encodeULEB128(Events.size(), W.OS);
767da419bdbSHeejin Ahn   for (const wasm::WasmEventType &Event : Events) {
768da419bdbSHeejin Ahn     encodeULEB128(Event.Attribute, W.OS);
769da419bdbSHeejin Ahn     encodeULEB128(Event.SigIndex, W.OS);
770da419bdbSHeejin Ahn   }
771da419bdbSHeejin Ahn 
772da419bdbSHeejin Ahn   endSection(Section);
773da419bdbSHeejin Ahn }
774da419bdbSHeejin Ahn 
7758defa952SSam Clegg void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) {
7769e15f359SSam Clegg   if (Exports.empty())
7779e15f359SSam Clegg     return;
7789e15f359SSam Clegg 
7799e15f359SSam Clegg   SectionBookkeeping Section;
7809e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_EXPORT);
7819e15f359SSam Clegg 
782f17b149dSPeter Collingbourne   encodeULEB128(Exports.size(), W.OS);
7838defa952SSam Clegg   for (const wasm::WasmExport &Export : Exports) {
7848defa952SSam Clegg     writeString(Export.Name);
785f17b149dSPeter Collingbourne     W.OS << char(Export.Kind);
786f17b149dSPeter Collingbourne     encodeULEB128(Export.Index, W.OS);
7879e15f359SSam Clegg   }
7889e15f359SSam Clegg 
7899e15f359SSam Clegg   endSection(Section);
7909e15f359SSam Clegg }
7919e15f359SSam Clegg 
792457fb0b4SSam Clegg void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
7939e15f359SSam Clegg   if (TableElems.empty())
7949e15f359SSam Clegg     return;
7959e15f359SSam Clegg 
7969e15f359SSam Clegg   SectionBookkeeping Section;
7979e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_ELEM);
7989e15f359SSam Clegg 
799f17b149dSPeter Collingbourne   encodeULEB128(1, W.OS); // number of "segments"
800f17b149dSPeter Collingbourne   encodeULEB128(0, W.OS); // the table index
8019e15f359SSam Clegg 
8029e15f359SSam Clegg   // init expr for starting offset
803f17b149dSPeter Collingbourne   W.OS << char(wasm::WASM_OPCODE_I32_CONST);
80418c56a07SHeejin Ahn   encodeSLEB128(InitialTableOffset, W.OS);
805f17b149dSPeter Collingbourne   W.OS << char(wasm::WASM_OPCODE_END);
8069e15f359SSam Clegg 
807f17b149dSPeter Collingbourne   encodeULEB128(TableElems.size(), W.OS);
8089e15f359SSam Clegg   for (uint32_t Elem : TableElems)
809f17b149dSPeter Collingbourne     encodeULEB128(Elem, W.OS);
8109e15f359SSam Clegg 
8119e15f359SSam Clegg   endSection(Section);
8129e15f359SSam Clegg }
8139e15f359SSam Clegg 
814fef8de66SThomas Lively void WasmObjectWriter::writeDataCountSection() {
815fef8de66SThomas Lively   if (DataSegments.empty())
816fef8de66SThomas Lively     return;
817fef8de66SThomas Lively 
818fef8de66SThomas Lively   SectionBookkeeping Section;
819fef8de66SThomas Lively   startSection(Section, wasm::WASM_SEC_DATACOUNT);
820fef8de66SThomas Lively   encodeULEB128(DataSegments.size(), W.OS);
821fef8de66SThomas Lively   endSection(Section);
822fef8de66SThomas Lively }
823fef8de66SThomas Lively 
824457fb0b4SSam Clegg void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
825457fb0b4SSam Clegg                                         const MCAsmLayout &Layout,
826457fb0b4SSam Clegg                                         ArrayRef<WasmFunction> Functions) {
8279e15f359SSam Clegg   if (Functions.empty())
8289e15f359SSam Clegg     return;
8299e15f359SSam Clegg 
8309e15f359SSam Clegg   SectionBookkeeping Section;
8319e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_CODE);
8326f08c84aSSam Clegg   CodeSectionIndex = Section.Index;
8339e15f359SSam Clegg 
834f17b149dSPeter Collingbourne   encodeULEB128(Functions.size(), W.OS);
8359e15f359SSam Clegg 
8369e15f359SSam Clegg   for (const WasmFunction &Func : Functions) {
837fe6414b0SSam Clegg     auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
8389e15f359SSam Clegg 
8399e15f359SSam Clegg     int64_t Size = 0;
8409e15f359SSam Clegg     if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
8419e15f359SSam Clegg       report_fatal_error(".size expression must be evaluatable");
8429e15f359SSam Clegg 
843f17b149dSPeter Collingbourne     encodeULEB128(Size, W.OS);
844f17b149dSPeter Collingbourne     FuncSection.setSectionOffset(W.OS.tell() - Section.ContentsOffset);
845f17b149dSPeter Collingbourne     Asm.writeSectionData(W.OS, &FuncSection, Layout);
8469e15f359SSam Clegg   }
8479e15f359SSam Clegg 
8489e15f359SSam Clegg   // Apply fixups.
849acd7d2b0SSam Clegg   applyRelocations(CodeRelocations, Section.ContentsOffset);
8509e15f359SSam Clegg 
8519e15f359SSam Clegg   endSection(Section);
8529e15f359SSam Clegg }
8539e15f359SSam Clegg 
8546c899ba6SSam Clegg void WasmObjectWriter::writeDataSection() {
8556c899ba6SSam Clegg   if (DataSegments.empty())
8567c395943SSam Clegg     return;
8579e15f359SSam Clegg 
8589e15f359SSam Clegg   SectionBookkeeping Section;
8599e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_DATA);
8606f08c84aSSam Clegg   DataSectionIndex = Section.Index;
8619e15f359SSam Clegg 
862f17b149dSPeter Collingbourne   encodeULEB128(DataSegments.size(), W.OS); // count
8637c395943SSam Clegg 
8646c899ba6SSam Clegg   for (const WasmDataSegment &Segment : DataSegments) {
8652e150409SThomas Lively     encodeULEB128(Segment.InitFlags, W.OS); // flags
8662e150409SThomas Lively     if (Segment.InitFlags & wasm::WASM_SEGMENT_HAS_MEMINDEX)
867f17b149dSPeter Collingbourne       encodeULEB128(0, W.OS); // memory index
8682e150409SThomas Lively     if ((Segment.InitFlags & wasm::WASM_SEGMENT_IS_PASSIVE) == 0) {
869f17b149dSPeter Collingbourne       W.OS << char(wasm::WASM_OPCODE_I32_CONST);
870f17b149dSPeter Collingbourne       encodeSLEB128(Segment.Offset, W.OS); // offset
871f17b149dSPeter Collingbourne       W.OS << char(wasm::WASM_OPCODE_END);
8722e150409SThomas Lively     }
873f17b149dSPeter Collingbourne     encodeULEB128(Segment.Data.size(), W.OS); // size
874f17b149dSPeter Collingbourne     Segment.Section->setSectionOffset(W.OS.tell() - Section.ContentsOffset);
875f17b149dSPeter Collingbourne     W.OS << Segment.Data; // data
8767c395943SSam Clegg   }
8779e15f359SSam Clegg 
8789e15f359SSam Clegg   // Apply fixups.
8797c395943SSam Clegg   applyRelocations(DataRelocations, Section.ContentsOffset);
8809e15f359SSam Clegg 
8819e15f359SSam Clegg   endSection(Section);
8829e15f359SSam Clegg }
8839e15f359SSam Clegg 
8846f08c84aSSam Clegg void WasmObjectWriter::writeRelocSection(
8856f08c84aSSam Clegg     uint32_t SectionIndex, StringRef Name,
886f77dc2a8SSam Clegg     std::vector<WasmRelocationEntry> &Relocs) {
8879e15f359SSam Clegg   // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
8889e15f359SSam Clegg   // for descriptions of the reloc sections.
8899e15f359SSam Clegg 
890f77dc2a8SSam Clegg   if (Relocs.empty())
8919e15f359SSam Clegg     return;
8929e15f359SSam Clegg 
893f77dc2a8SSam Clegg   // First, ensure the relocations are sorted in offset order.  In general they
894f77dc2a8SSam Clegg   // should already be sorted since `recordRelocation` is called in offset
895f77dc2a8SSam Clegg   // order, but for the code section we combine many MC sections into single
896f77dc2a8SSam Clegg   // wasm section, and this order is determined by the order of Asm.Symbols()
897f77dc2a8SSam Clegg   // not the sections order.
898efd94c56SFangrui Song   llvm::stable_sort(
899efd94c56SFangrui Song       Relocs, [](const WasmRelocationEntry &A, const WasmRelocationEntry &B) {
900f77dc2a8SSam Clegg         return (A.Offset + A.FixupSection->getSectionOffset()) <
901f77dc2a8SSam Clegg                (B.Offset + B.FixupSection->getSectionOffset());
902f77dc2a8SSam Clegg       });
903f77dc2a8SSam Clegg 
9049e15f359SSam Clegg   SectionBookkeeping Section;
9056f08c84aSSam Clegg   startCustomSection(Section, std::string("reloc.") + Name.str());
9069e15f359SSam Clegg 
907f17b149dSPeter Collingbourne   encodeULEB128(SectionIndex, W.OS);
908f77dc2a8SSam Clegg   encodeULEB128(Relocs.size(), W.OS);
909f77dc2a8SSam Clegg   for (const WasmRelocationEntry &RelEntry : Relocs) {
910f208f631SHeejin Ahn     uint64_t Offset =
911f208f631SHeejin Ahn         RelEntry.Offset + RelEntry.FixupSection->getSectionOffset();
9126f08c84aSSam Clegg     uint32_t Index = getRelocationIndexValue(RelEntry);
9139e15f359SSam Clegg 
914f17b149dSPeter Collingbourne     W.OS << char(RelEntry.Type);
915f17b149dSPeter Collingbourne     encodeULEB128(Offset, W.OS);
916f17b149dSPeter Collingbourne     encodeULEB128(Index, W.OS);
9176f08c84aSSam Clegg     if (RelEntry.hasAddend())
918f17b149dSPeter Collingbourne       encodeSLEB128(RelEntry.Addend, W.OS);
9199e15f359SSam Clegg   }
9209e15f359SSam Clegg 
9219e15f359SSam Clegg   endSection(Section);
9229e15f359SSam Clegg }
9239e15f359SSam Clegg 
9246a31a0d6SSam Clegg void WasmObjectWriter::writeCustomRelocSections() {
9256a31a0d6SSam Clegg   for (const auto &Sec : CustomSections) {
9266a31a0d6SSam Clegg     auto &Relocations = CustomSectionsRelocations[Sec.Section];
9276a31a0d6SSam Clegg     writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations);
9286a31a0d6SSam Clegg   }
9296a31a0d6SSam Clegg }
9306a31a0d6SSam Clegg 
9319e15f359SSam Clegg void WasmObjectWriter::writeLinkingMetaDataSection(
93286b4a09aSSam Clegg     ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
933ea7caceeSSam Clegg     ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
934ea7caceeSSam Clegg     const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) {
9359e15f359SSam Clegg   SectionBookkeeping Section;
9362322a937SSam Clegg   startCustomSection(Section, "linking");
937f17b149dSPeter Collingbourne   encodeULEB128(wasm::WasmMetadataVersion, W.OS);
9389e15f359SSam Clegg 
9396bb5a41fSSam Clegg   SectionBookkeeping SubSection;
9406c899ba6SSam Clegg   if (SymbolInfos.size() != 0) {
9416c899ba6SSam Clegg     startSection(SubSection, wasm::WASM_SYMBOL_TABLE);
942f17b149dSPeter Collingbourne     encodeULEB128(SymbolInfos.size(), W.OS);
9436c899ba6SSam Clegg     for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) {
944f17b149dSPeter Collingbourne       encodeULEB128(Sym.Kind, W.OS);
945f17b149dSPeter Collingbourne       encodeULEB128(Sym.Flags, W.OS);
9466c899ba6SSam Clegg       switch (Sym.Kind) {
9476c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_FUNCTION:
9486c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_GLOBAL:
949da419bdbSHeejin Ahn       case wasm::WASM_SYMBOL_TYPE_EVENT:
950f17b149dSPeter Collingbourne         encodeULEB128(Sym.ElementIndex, W.OS);
95129874ceaSDan Gohman         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0 ||
95229874ceaSDan Gohman             (Sym.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0)
9536c899ba6SSam Clegg           writeString(Sym.Name);
9546c899ba6SSam Clegg         break;
9556c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_DATA:
9566c899ba6SSam Clegg         writeString(Sym.Name);
9576c899ba6SSam Clegg         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) {
958f17b149dSPeter Collingbourne           encodeULEB128(Sym.DataRef.Segment, W.OS);
959f17b149dSPeter Collingbourne           encodeULEB128(Sym.DataRef.Offset, W.OS);
960f17b149dSPeter Collingbourne           encodeULEB128(Sym.DataRef.Size, W.OS);
9616c899ba6SSam Clegg         }
9626c899ba6SSam Clegg         break;
9636a31a0d6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_SECTION: {
9646a31a0d6SSam Clegg         const uint32_t SectionIndex =
9656a31a0d6SSam Clegg             CustomSections[Sym.ElementIndex].OutputIndex;
966f17b149dSPeter Collingbourne         encodeULEB128(SectionIndex, W.OS);
9676a31a0d6SSam Clegg         break;
9686a31a0d6SSam Clegg       }
9696c899ba6SSam Clegg       default:
9706c899ba6SSam Clegg         llvm_unreachable("unexpected kind");
9716c899ba6SSam Clegg       }
972b7787fd0SSam Clegg     }
973b7787fd0SSam Clegg     endSection(SubSection);
974b7787fd0SSam Clegg   }
9759e15f359SSam Clegg 
9766c899ba6SSam Clegg   if (DataSegments.size()) {
97763ebb813SSam Clegg     startSection(SubSection, wasm::WASM_SEGMENT_INFO);
978f17b149dSPeter Collingbourne     encodeULEB128(DataSegments.size(), W.OS);
9796c899ba6SSam Clegg     for (const WasmDataSegment &Segment : DataSegments) {
980d95ed959SSam Clegg       writeString(Segment.Name);
981f17b149dSPeter Collingbourne       encodeULEB128(Segment.Alignment, W.OS);
9822e150409SThomas Lively       encodeULEB128(Segment.LinkerFlags, W.OS);
98363ebb813SSam Clegg     }
984d95ed959SSam Clegg     endSection(SubSection);
985d95ed959SSam Clegg   }
986d95ed959SSam Clegg 
987bafe6902SSam Clegg   if (!InitFuncs.empty()) {
988bafe6902SSam Clegg     startSection(SubSection, wasm::WASM_INIT_FUNCS);
989f17b149dSPeter Collingbourne     encodeULEB128(InitFuncs.size(), W.OS);
990bafe6902SSam Clegg     for (auto &StartFunc : InitFuncs) {
991f17b149dSPeter Collingbourne       encodeULEB128(StartFunc.first, W.OS);  // priority
992f17b149dSPeter Collingbourne       encodeULEB128(StartFunc.second, W.OS); // function index
993bafe6902SSam Clegg     }
994bafe6902SSam Clegg     endSection(SubSection);
995bafe6902SSam Clegg   }
996bafe6902SSam Clegg 
997ea7caceeSSam Clegg   if (Comdats.size()) {
998ea7caceeSSam Clegg     startSection(SubSection, wasm::WASM_COMDAT_INFO);
999f17b149dSPeter Collingbourne     encodeULEB128(Comdats.size(), W.OS);
1000ea7caceeSSam Clegg     for (const auto &C : Comdats) {
1001ea7caceeSSam Clegg       writeString(C.first);
1002f17b149dSPeter Collingbourne       encodeULEB128(0, W.OS); // flags for future use
1003f17b149dSPeter Collingbourne       encodeULEB128(C.second.size(), W.OS);
1004ea7caceeSSam Clegg       for (const WasmComdatEntry &Entry : C.second) {
1005f17b149dSPeter Collingbourne         encodeULEB128(Entry.Kind, W.OS);
1006f17b149dSPeter Collingbourne         encodeULEB128(Entry.Index, W.OS);
1007ea7caceeSSam Clegg       }
1008ea7caceeSSam Clegg     }
1009ea7caceeSSam Clegg     endSection(SubSection);
1010ea7caceeSSam Clegg   }
1011ea7caceeSSam Clegg 
10129e15f359SSam Clegg   endSection(Section);
10139e15f359SSam Clegg }
10149e15f359SSam Clegg 
1015cbda16ebSThomas Lively void WasmObjectWriter::writeCustomSection(WasmCustomSection &CustomSection,
1016cbda16ebSThomas Lively                                           const MCAssembler &Asm,
10176a31a0d6SSam Clegg                                           const MCAsmLayout &Layout) {
1018cfd44a2eSSam Clegg   SectionBookkeeping Section;
10196a31a0d6SSam Clegg   auto *Sec = CustomSection.Section;
10202322a937SSam Clegg   startCustomSection(Section, CustomSection.Name);
10216a31a0d6SSam Clegg 
1022f17b149dSPeter Collingbourne   Sec->setSectionOffset(W.OS.tell() - Section.ContentsOffset);
1023f17b149dSPeter Collingbourne   Asm.writeSectionData(W.OS, Sec, Layout);
10246a31a0d6SSam Clegg 
10256a31a0d6SSam Clegg   CustomSection.OutputContentsOffset = Section.ContentsOffset;
10266a31a0d6SSam Clegg   CustomSection.OutputIndex = Section.Index;
10276a31a0d6SSam Clegg 
1028cfd44a2eSSam Clegg   endSection(Section);
10296a31a0d6SSam Clegg 
10306a31a0d6SSam Clegg   // Apply fixups.
10314d57fbd0SSam Clegg   auto &Relocations = CustomSectionsRelocations[CustomSection.Section];
10324d57fbd0SSam Clegg   applyRelocations(Relocations, CustomSection.OutputContentsOffset);
10336a31a0d6SSam Clegg }
10346a31a0d6SSam Clegg 
10355e3d33a7SSam Clegg uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm &Symbol) {
10365e3d33a7SSam Clegg   assert(Symbol.isFunction());
10375e3d33a7SSam Clegg   assert(TypeIndices.count(&Symbol));
10385e3d33a7SSam Clegg   return TypeIndices[&Symbol];
10395e3d33a7SSam Clegg }
10405e3d33a7SSam Clegg 
1041da419bdbSHeejin Ahn uint32_t WasmObjectWriter::getEventType(const MCSymbolWasm &Symbol) {
1042da419bdbSHeejin Ahn   assert(Symbol.isEvent());
1043da419bdbSHeejin Ahn   assert(TypeIndices.count(&Symbol));
1044da419bdbSHeejin Ahn   return TypeIndices[&Symbol];
1045da419bdbSHeejin Ahn }
1046da419bdbSHeejin Ahn 
104738b12f5eSHeejin Ahn void WasmObjectWriter::registerFunctionType(const MCSymbolWasm &Symbol) {
10485e3d33a7SSam Clegg   assert(Symbol.isFunction());
10495e3d33a7SSam Clegg 
1050da419bdbSHeejin Ahn   WasmSignature S;
105118c56a07SHeejin Ahn   const MCSymbolWasm *ResolvedSym = resolveSymbol(Symbol);
105277a7a380SDerek Schuff   if (auto *Sig = ResolvedSym->getSignature()) {
1053da419bdbSHeejin Ahn     S.Returns = Sig->Returns;
1054da419bdbSHeejin Ahn     S.Params = Sig->Params;
105577a7a380SDerek Schuff   }
10565e3d33a7SSam Clegg 
1057da419bdbSHeejin Ahn   auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
10585e3d33a7SSam Clegg   if (Pair.second)
1059da419bdbSHeejin Ahn     Signatures.push_back(S);
10605e3d33a7SSam Clegg   TypeIndices[&Symbol] = Pair.first->second;
10615e3d33a7SSam Clegg 
1062d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "registerFunctionType: " << Symbol
1063d34e60caSNicola Zaghen                     << " new:" << Pair.second << "\n");
1064d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
10655e3d33a7SSam Clegg }
10665e3d33a7SSam Clegg 
106738b12f5eSHeejin Ahn void WasmObjectWriter::registerEventType(const MCSymbolWasm &Symbol) {
1068da419bdbSHeejin Ahn   assert(Symbol.isEvent());
1069da419bdbSHeejin Ahn 
1070da419bdbSHeejin Ahn   // TODO Currently we don't generate imported exceptions, but if we do, we
1071da419bdbSHeejin Ahn   // should have a way of infering types of imported exceptions.
1072da419bdbSHeejin Ahn   WasmSignature S;
1073da419bdbSHeejin Ahn   if (auto *Sig = Symbol.getSignature()) {
1074da419bdbSHeejin Ahn     S.Returns = Sig->Returns;
1075da419bdbSHeejin Ahn     S.Params = Sig->Params;
1076da419bdbSHeejin Ahn   }
1077da419bdbSHeejin Ahn 
1078da419bdbSHeejin Ahn   auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
1079da419bdbSHeejin Ahn   if (Pair.second)
1080da419bdbSHeejin Ahn     Signatures.push_back(S);
1081da419bdbSHeejin Ahn   TypeIndices[&Symbol] = Pair.first->second;
1082da419bdbSHeejin Ahn 
1083da419bdbSHeejin Ahn   LLVM_DEBUG(dbgs() << "registerEventType: " << Symbol << " new:" << Pair.second
1084da419bdbSHeejin Ahn                     << "\n");
1085da419bdbSHeejin Ahn   LLVM_DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
1086da419bdbSHeejin Ahn }
1087da419bdbSHeejin Ahn 
10884d57fbd0SSam Clegg static bool isInSymtab(const MCSymbolWasm &Sym) {
10893ea1c62cSSam Clegg   if (Sym.isUsedInReloc() || Sym.isUsedInInitArray())
10904d57fbd0SSam Clegg     return true;
10914d57fbd0SSam Clegg 
10924d57fbd0SSam Clegg   if (Sym.isComdat() && !Sym.isDefined())
10934d57fbd0SSam Clegg     return false;
10944d57fbd0SSam Clegg 
10953ea1c62cSSam Clegg   if (Sym.isTemporary())
10964d57fbd0SSam Clegg     return false;
10974d57fbd0SSam Clegg 
10984d57fbd0SSam Clegg   if (Sym.isSection())
10994d57fbd0SSam Clegg     return false;
11004d57fbd0SSam Clegg 
11014d57fbd0SSam Clegg   return true;
11024d57fbd0SSam Clegg }
11034d57fbd0SSam Clegg 
1104438390faSPeter Collingbourne uint64_t WasmObjectWriter::writeObject(MCAssembler &Asm,
110518eafb6cSDan Gohman                                        const MCAsmLayout &Layout) {
1106438390faSPeter Collingbourne   uint64_t StartOffset = W.OS.tell();
1107438390faSPeter Collingbourne 
1108d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
1109d934cb88SDan Gohman 
1110d934cb88SDan Gohman   // Collect information from the available symbols.
1111d934cb88SDan Gohman   SmallVector<WasmFunction, 4> Functions;
1112d934cb88SDan Gohman   SmallVector<uint32_t, 4> TableElems;
11138defa952SSam Clegg   SmallVector<wasm::WasmImport, 4> Imports;
11148defa952SSam Clegg   SmallVector<wasm::WasmExport, 4> Exports;
1115da419bdbSHeejin Ahn   SmallVector<wasm::WasmEventType, 1> Events;
11166c899ba6SSam Clegg   SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos;
1117bafe6902SSam Clegg   SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
1118ea7caceeSSam Clegg   std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
11197c395943SSam Clegg   uint32_t DataSize = 0;
1120d934cb88SDan Gohman 
1121f950b24aSSam Clegg   // For now, always emit the memory import, since loads and stores are not
1122f950b24aSSam Clegg   // valid without it. In the future, we could perhaps be more clever and omit
1123f950b24aSSam Clegg   // it if there are no loads or stores.
11248defa952SSam Clegg   wasm::WasmImport MemImport;
11251ed3a046SSam Clegg   MemImport.Module = "env";
11261ed3a046SSam Clegg   MemImport.Field = "__linear_memory";
1127f950b24aSSam Clegg   MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
1128f950b24aSSam Clegg   Imports.push_back(MemImport);
1129f950b24aSSam Clegg 
1130f950b24aSSam Clegg   // For now, always emit the table section, since indirect calls are not
1131f950b24aSSam Clegg   // valid without it. In the future, we could perhaps be more clever and omit
1132f950b24aSSam Clegg   // it if there are no indirect calls.
11338defa952SSam Clegg   wasm::WasmImport TableImport;
11341ed3a046SSam Clegg   TableImport.Module = "env";
11351ed3a046SSam Clegg   TableImport.Field = "__indirect_function_table";
1136f950b24aSSam Clegg   TableImport.Kind = wasm::WASM_EXTERNAL_TABLE;
11376a87ddacSThomas Lively   TableImport.Table.ElemType = wasm::WASM_TYPE_FUNCREF;
1138f950b24aSSam Clegg   Imports.push_back(TableImport);
1139f950b24aSSam Clegg 
1140da419bdbSHeejin Ahn   // Populate SignatureIndices, and Imports and WasmIndices for undefined
1141586320c0SNicholas Wilson   // symbols.  This must be done before populating WasmIndices for defined
1142586320c0SNicholas Wilson   // symbols.
114332ce5ca0SDan Gohman   for (const MCSymbol &S : Asm.symbols()) {
114432ce5ca0SDan Gohman     const auto &WS = static_cast<const MCSymbolWasm &>(S);
114532ce5ca0SDan Gohman 
114632ce5ca0SDan Gohman     // Register types for all functions, including those with private linkage
11479f3fe42eSSam Clegg     // (because wasm always needs a type signature).
114832ce5ca0SDan Gohman     if (WS.isFunction())
114932ce5ca0SDan Gohman       registerFunctionType(WS);
115032ce5ca0SDan Gohman 
1151da419bdbSHeejin Ahn     if (WS.isEvent())
1152da419bdbSHeejin Ahn       registerEventType(WS);
1153da419bdbSHeejin Ahn 
115432ce5ca0SDan Gohman     if (WS.isTemporary())
115532ce5ca0SDan Gohman       continue;
115632ce5ca0SDan Gohman 
115732ce5ca0SDan Gohman     // If the symbol is not defined in this translation unit, import it.
11586c899ba6SSam Clegg     if (!WS.isDefined() && !WS.isComdat()) {
11596c899ba6SSam Clegg       if (WS.isFunction()) {
11608defa952SSam Clegg         wasm::WasmImport Import;
1161f726e445SDan Gohman         Import.Module = WS.getImportModule();
1162f726e445SDan Gohman         Import.Field = WS.getImportName();
116332ce5ca0SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
11648defa952SSam Clegg         Import.SigIndex = getFunctionType(WS);
11656c899ba6SSam Clegg         Imports.push_back(Import);
1166492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
11676c899ba6SSam Clegg         WasmIndices[&WS] = NumFunctionImports++;
11686c899ba6SSam Clegg       } else if (WS.isGlobal()) {
116915f349f7SNicholas Wilson         if (WS.isWeak())
117015f349f7SNicholas Wilson           report_fatal_error("undefined global symbol cannot be weak");
117115f349f7SNicholas Wilson 
11726c899ba6SSam Clegg         wasm::WasmImport Import;
1173f726e445SDan Gohman         Import.Field = WS.getImportName();
117432ce5ca0SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1175492f7529SSam Clegg         Import.Module = WS.getImportModule();
11766c899ba6SSam Clegg         Import.Global = WS.getGlobalType();
11776c899ba6SSam Clegg         Imports.push_back(Import);
1178492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
11796c899ba6SSam Clegg         WasmIndices[&WS] = NumGlobalImports++;
1180da419bdbSHeejin Ahn       } else if (WS.isEvent()) {
1181da419bdbSHeejin Ahn         if (WS.isWeak())
1182da419bdbSHeejin Ahn           report_fatal_error("undefined event symbol cannot be weak");
1183da419bdbSHeejin Ahn 
1184da419bdbSHeejin Ahn         wasm::WasmImport Import;
1185f726e445SDan Gohman         Import.Module = WS.getImportModule();
1186f726e445SDan Gohman         Import.Field = WS.getImportName();
1187da419bdbSHeejin Ahn         Import.Kind = wasm::WASM_EXTERNAL_EVENT;
1188da419bdbSHeejin Ahn         Import.Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
1189da419bdbSHeejin Ahn         Import.Event.SigIndex = getEventType(WS);
1190da419bdbSHeejin Ahn         Imports.push_back(Import);
1191492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
1192da419bdbSHeejin Ahn         WasmIndices[&WS] = NumEventImports++;
119332ce5ca0SDan Gohman       }
119432ce5ca0SDan Gohman     }
119532ce5ca0SDan Gohman   }
119632ce5ca0SDan Gohman 
1197492f7529SSam Clegg   // Add imports for GOT globals
1198492f7529SSam Clegg   for (const MCSymbol &S : Asm.symbols()) {
1199492f7529SSam Clegg     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1200492f7529SSam Clegg     if (WS.isUsedInGOT()) {
1201492f7529SSam Clegg       wasm::WasmImport Import;
1202492f7529SSam Clegg       if (WS.isFunction())
1203492f7529SSam Clegg         Import.Module = "GOT.func";
1204492f7529SSam Clegg       else
1205492f7529SSam Clegg         Import.Module = "GOT.mem";
1206492f7529SSam Clegg       Import.Field = WS.getName();
1207492f7529SSam Clegg       Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1208492f7529SSam Clegg       Import.Global = {wasm::WASM_TYPE_I32, true};
1209492f7529SSam Clegg       Imports.push_back(Import);
1210492f7529SSam Clegg       assert(GOTIndices.count(&WS) == 0);
1211492f7529SSam Clegg       GOTIndices[&WS] = NumGlobalImports++;
1212492f7529SSam Clegg     }
1213492f7529SSam Clegg   }
1214492f7529SSam Clegg 
12154d57fbd0SSam Clegg   // Populate DataSegments and CustomSections, which must be done before
12164d57fbd0SSam Clegg   // populating DataLocations.
1217759631c7SSam Clegg   for (MCSection &Sec : Asm) {
1218759631c7SSam Clegg     auto &Section = static_cast<MCSectionWasm &>(Sec);
1219*7d1ff446SFangrui Song     StringRef SectionName = Section.getName();
1220759631c7SSam Clegg 
1221bafe6902SSam Clegg     // .init_array sections are handled specially elsewhere.
12224d57fbd0SSam Clegg     if (SectionName.startswith(".init_array"))
1223bafe6902SSam Clegg       continue;
1224bafe6902SSam Clegg 
12254d57fbd0SSam Clegg     // Code is handled separately
12264d57fbd0SSam Clegg     if (Section.getKind().isText())
12274d57fbd0SSam Clegg       continue;
12284d57fbd0SSam Clegg 
12294d57fbd0SSam Clegg     if (Section.isWasmData()) {
1230329e76d5SSam Clegg       uint32_t SegmentIndex = DataSegments.size();
1231759631c7SSam Clegg       DataSize = alignTo(DataSize, Section.getAlignment());
1232759631c7SSam Clegg       DataSegments.emplace_back();
1233759631c7SSam Clegg       WasmDataSegment &Segment = DataSegments.back();
12344d57fbd0SSam Clegg       Segment.Name = SectionName;
12359b49f36aSSimon Pilgrim       Segment.InitFlags =
12369b49f36aSSimon Pilgrim           Section.getPassive() ? (uint32_t)wasm::WASM_SEGMENT_IS_PASSIVE : 0;
1237759631c7SSam Clegg       Segment.Offset = DataSize;
1238759631c7SSam Clegg       Segment.Section = &Section;
123963ebb813SSam Clegg       addData(Segment.Data, Section);
124056c587adSSam Clegg       Segment.Alignment = Log2_32(Section.getAlignment());
12412e150409SThomas Lively       Segment.LinkerFlags = 0;
1242759631c7SSam Clegg       DataSize += Segment.Data.size();
12436c899ba6SSam Clegg       Section.setSegmentIndex(SegmentIndex);
1244ea7caceeSSam Clegg 
1245ea7caceeSSam Clegg       if (const MCSymbolWasm *C = Section.getGroup()) {
1246ea7caceeSSam Clegg         Comdats[C->getName()].emplace_back(
1247329e76d5SSam Clegg             WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
1248ea7caceeSSam Clegg       }
12494d57fbd0SSam Clegg     } else {
12504d57fbd0SSam Clegg       // Create custom sections
12514d57fbd0SSam Clegg       assert(Sec.getKind().isMetadata());
12524d57fbd0SSam Clegg 
12534d57fbd0SSam Clegg       StringRef Name = SectionName;
12544d57fbd0SSam Clegg 
12554d57fbd0SSam Clegg       // For user-defined custom sections, strip the prefix
12564d57fbd0SSam Clegg       if (Name.startswith(".custom_section."))
12574d57fbd0SSam Clegg         Name = Name.substr(strlen(".custom_section."));
12584d57fbd0SSam Clegg 
12594d57fbd0SSam Clegg       MCSymbol *Begin = Sec.getBeginSymbol();
1260fb807d4dSSam Clegg       if (Begin) {
12614d57fbd0SSam Clegg         WasmIndices[cast<MCSymbolWasm>(Begin)] = CustomSections.size();
1262b210c64bSSam Clegg         if (SectionName != Begin->getName())
1263fb807d4dSSam Clegg           report_fatal_error("section name and begin symbol should match: " +
1264b210c64bSSam Clegg                              Twine(SectionName));
1265fb807d4dSSam Clegg       }
1266cbda16ebSThomas Lively 
1267f6f4f843SThomas Lively       // Separate out the producers and target features sections
1268cbda16ebSThomas Lively       if (Name == "producers") {
12690eaee545SJonas Devlieghere         ProducersSection = std::make_unique<WasmCustomSection>(Name, &Section);
1270cbda16ebSThomas Lively         continue;
1271cbda16ebSThomas Lively       }
1272f6f4f843SThomas Lively       if (Name == "target_features") {
1273f6f4f843SThomas Lively         TargetFeaturesSection =
12740eaee545SJonas Devlieghere             std::make_unique<WasmCustomSection>(Name, &Section);
1275f6f4f843SThomas Lively         continue;
1276f6f4f843SThomas Lively       }
1277cbda16ebSThomas Lively 
12784d57fbd0SSam Clegg       CustomSections.emplace_back(Name, &Section);
1279759631c7SSam Clegg     }
12806a31a0d6SSam Clegg   }
12816a31a0d6SSam Clegg 
1282586320c0SNicholas Wilson   // Populate WasmIndices and DataLocations for defined symbols.
1283d934cb88SDan Gohman   for (const MCSymbol &S : Asm.symbols()) {
1284d934cb88SDan Gohman     // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1285d934cb88SDan Gohman     // or used in relocations.
1286d934cb88SDan Gohman     if (S.isTemporary() && S.getName().empty())
1287d934cb88SDan Gohman       continue;
1288b7787fd0SSam Clegg 
1289d934cb88SDan Gohman     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1290d34e60caSNicola Zaghen     LLVM_DEBUG(
1291d34e60caSNicola Zaghen         dbgs() << "MCSymbol: " << toString(WS.getType()) << " '" << S << "'"
1292d34e60caSNicola Zaghen                << " isDefined=" << S.isDefined() << " isExternal="
1293d34e60caSNicola Zaghen                << S.isExternal() << " isTemporary=" << S.isTemporary()
1294d34e60caSNicola Zaghen                << " isWeak=" << WS.isWeak() << " isHidden=" << WS.isHidden()
1295b7787fd0SSam Clegg                << " isVariable=" << WS.isVariable() << "\n");
1296b7787fd0SSam Clegg 
12975e3d33a7SSam Clegg     if (WS.isVariable())
12985e3d33a7SSam Clegg       continue;
12996c899ba6SSam Clegg     if (WS.isComdat() && !WS.isDefined())
13006c899ba6SSam Clegg       continue;
1301b7787fd0SSam Clegg 
1302d934cb88SDan Gohman     if (WS.isFunction()) {
13036c899ba6SSam Clegg       unsigned Index;
1304cd65f698SSam Clegg       if (WS.isDefined()) {
1305b7787fd0SSam Clegg         if (WS.getOffset() != 0)
1306b7787fd0SSam Clegg           report_fatal_error(
1307b7787fd0SSam Clegg               "function sections must contain one function each");
1308b7787fd0SSam Clegg 
130918c56a07SHeejin Ahn         if (WS.getSize() == nullptr)
1310b7787fd0SSam Clegg           report_fatal_error(
1311b7787fd0SSam Clegg               "function symbols must have a size set with .size");
1312b7787fd0SSam Clegg 
13136c899ba6SSam Clegg         // A definition. Write out the function body.
13149f3fe42eSSam Clegg         Index = NumFunctionImports + Functions.size();
1315d934cb88SDan Gohman         WasmFunction Func;
1316da419bdbSHeejin Ahn         Func.SigIndex = getFunctionType(WS);
1317d934cb88SDan Gohman         Func.Sym = &WS;
13186c899ba6SSam Clegg         WasmIndices[&WS] = Index;
1319d934cb88SDan Gohman         Functions.push_back(Func);
13206c899ba6SSam Clegg 
13216c899ba6SSam Clegg         auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
13226c899ba6SSam Clegg         if (const MCSymbolWasm *C = Section.getGroup()) {
13236c899ba6SSam Clegg           Comdats[C->getName()].emplace_back(
13246c899ba6SSam Clegg               WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
13256c899ba6SSam Clegg         }
1326881d8778SSam Clegg 
1327881d8778SSam Clegg         if (WS.hasExportName()) {
1328881d8778SSam Clegg           wasm::WasmExport Export;
1329881d8778SSam Clegg           Export.Name = WS.getExportName();
1330881d8778SSam Clegg           Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1331881d8778SSam Clegg           Export.Index = Index;
1332881d8778SSam Clegg           Exports.push_back(Export);
1333881d8778SSam Clegg         }
1334d934cb88SDan Gohman       } else {
1335d934cb88SDan Gohman         // An import; the index was assigned above.
13366c899ba6SSam Clegg         Index = WasmIndices.find(&WS)->second;
1337d934cb88SDan Gohman       }
1338d934cb88SDan Gohman 
1339d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> function index: " << Index << "\n");
1340da419bdbSHeejin Ahn 
13416c899ba6SSam Clegg     } else if (WS.isData()) {
1342f3feb6adSWouter van Oortmerssen       if (!isInSymtab(WS))
1343c38e947eSSam Clegg         continue;
1344c38e947eSSam Clegg 
13456c899ba6SSam Clegg       if (!WS.isDefined()) {
1346d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "  -> segment index: -1"
1347d34e60caSNicola Zaghen                           << "\n");
1348fe6414b0SSam Clegg         continue;
13496c899ba6SSam Clegg       }
1350fe6414b0SSam Clegg 
1351d934cb88SDan Gohman       if (!WS.getSize())
1352c38e947eSSam Clegg         report_fatal_error("data symbols must have a size set with .size: " +
1353c38e947eSSam Clegg                            WS.getName());
1354d934cb88SDan Gohman 
1355d934cb88SDan Gohman       int64_t Size = 0;
1356d934cb88SDan Gohman       if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1357d934cb88SDan Gohman         report_fatal_error(".size expression must be evaluatable");
1358d934cb88SDan Gohman 
1359759631c7SSam Clegg       auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
1360079cba04SSam Clegg       if (!DataSection.isWasmData())
1361079cba04SSam Clegg         report_fatal_error("data symbols must live in a data section: " +
1362079cba04SSam Clegg                            WS.getName());
13637c395943SSam Clegg 
13646c899ba6SSam Clegg       // For each data symbol, export it in the symtab as a reference to the
13656c899ba6SSam Clegg       // corresponding Wasm data segment.
13666c899ba6SSam Clegg       wasm::WasmDataReference Ref = wasm::WasmDataReference{
13676c899ba6SSam Clegg           DataSection.getSegmentIndex(),
13686c899ba6SSam Clegg           static_cast<uint32_t>(Layout.getSymbolOffset(WS)),
13696c899ba6SSam Clegg           static_cast<uint32_t>(Size)};
13706c899ba6SSam Clegg       DataLocations[&WS] = Ref;
1371d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> segment index: " << Ref.Segment << "\n");
1372da419bdbSHeejin Ahn 
1373a165f2d6SSam Clegg     } else if (WS.isGlobal()) {
13746c899ba6SSam Clegg       // A "true" Wasm global (currently just __stack_pointer)
1375545932beSEric Christopher       if (WS.isDefined())
13766c899ba6SSam Clegg         report_fatal_error("don't yet support defined globals");
13776c899ba6SSam Clegg 
1378545932beSEric Christopher       // An import; the index was assigned above
1379d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> global index: "
1380d34e60caSNicola Zaghen                         << WasmIndices.find(&WS)->second << "\n");
1381da419bdbSHeejin Ahn 
1382da419bdbSHeejin Ahn     } else if (WS.isEvent()) {
1383da419bdbSHeejin Ahn       // C++ exception symbol (__cpp_exception)
1384da419bdbSHeejin Ahn       unsigned Index;
1385da419bdbSHeejin Ahn       if (WS.isDefined()) {
1386da419bdbSHeejin Ahn         Index = NumEventImports + Events.size();
1387da419bdbSHeejin Ahn         wasm::WasmEventType Event;
1388da419bdbSHeejin Ahn         Event.SigIndex = getEventType(WS);
1389da419bdbSHeejin Ahn         Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
1390492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
1391da419bdbSHeejin Ahn         WasmIndices[&WS] = Index;
1392da419bdbSHeejin Ahn         Events.push_back(Event);
1393da419bdbSHeejin Ahn       } else {
1394da419bdbSHeejin Ahn         // An import; the index was assigned above.
1395492f7529SSam Clegg         assert(WasmIndices.count(&WS) > 0);
1396da419bdbSHeejin Ahn       }
1397da419bdbSHeejin Ahn       LLVM_DEBUG(dbgs() << "  -> event index: " << WasmIndices.find(&WS)->second
1398da419bdbSHeejin Ahn                         << "\n");
1399da419bdbSHeejin Ahn 
1400a165f2d6SSam Clegg     } else {
1401a165f2d6SSam Clegg       assert(WS.isSection());
1402d934cb88SDan Gohman     }
1403d934cb88SDan Gohman   }
1404d934cb88SDan Gohman 
1405586320c0SNicholas Wilson   // Populate WasmIndices and DataLocations for aliased symbols.  We need to
1406586320c0SNicholas Wilson   // process these in a separate pass because we need to have processed the
1407586320c0SNicholas Wilson   // target of the alias before the alias itself and the symbols are not
1408586320c0SNicholas Wilson   // necessarily ordered in this way.
1409b7787fd0SSam Clegg   for (const MCSymbol &S : Asm.symbols()) {
1410b7787fd0SSam Clegg     if (!S.isVariable())
1411b7787fd0SSam Clegg       continue;
141231a2c809SSam Clegg 
1413cd65f698SSam Clegg     assert(S.isDefined());
1414b7787fd0SSam Clegg 
14155e3d33a7SSam Clegg     // Find the target symbol of this weak alias and export that index
1416aff1c4dfSSam Clegg     const auto &WS = static_cast<const MCSymbolWasm &>(S);
141718c56a07SHeejin Ahn     const MCSymbolWasm *ResolvedSym = resolveSymbol(WS);
1418d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym
1419d34e60caSNicola Zaghen                       << "'\n");
1420b7787fd0SSam Clegg 
1421ffba00bdSSam Clegg     if (ResolvedSym->isFunction()) {
14226c899ba6SSam Clegg       assert(WasmIndices.count(ResolvedSym) > 0);
14236c899ba6SSam Clegg       uint32_t WasmIndex = WasmIndices.find(ResolvedSym)->second;
1424492f7529SSam Clegg       assert(WasmIndices.count(&WS) == 0);
14256c899ba6SSam Clegg       WasmIndices[&WS] = WasmIndex;
1426d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> index:" << WasmIndex << "\n");
1427ffba00bdSSam Clegg     } else if (ResolvedSym->isData()) {
14286c899ba6SSam Clegg       assert(DataLocations.count(ResolvedSym) > 0);
14296c899ba6SSam Clegg       const wasm::WasmDataReference &Ref =
14306c899ba6SSam Clegg           DataLocations.find(ResolvedSym)->second;
14316c899ba6SSam Clegg       DataLocations[&WS] = Ref;
1432d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> index:" << Ref.Segment << "\n");
14336c899ba6SSam Clegg     } else {
1434da419bdbSHeejin Ahn       report_fatal_error("don't yet support global/event aliases");
14356c899ba6SSam Clegg     }
1436586320c0SNicholas Wilson   }
143731a2c809SSam Clegg 
1438586320c0SNicholas Wilson   // Finally, populate the symbol table itself, in its "natural" order.
1439586320c0SNicholas Wilson   for (const MCSymbol &S : Asm.symbols()) {
1440586320c0SNicholas Wilson     const auto &WS = static_cast<const MCSymbolWasm &>(S);
144125d8e68bSSam Clegg     if (!isInSymtab(WS)) {
144218c56a07SHeejin Ahn       WS.setIndex(InvalidIndex);
1443586320c0SNicholas Wilson       continue;
144425d8e68bSSam Clegg     }
1445d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "adding to symtab: " << WS << "\n");
1446586320c0SNicholas Wilson 
1447586320c0SNicholas Wilson     uint32_t Flags = 0;
1448586320c0SNicholas Wilson     if (WS.isWeak())
1449586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_BINDING_WEAK;
1450586320c0SNicholas Wilson     if (WS.isHidden())
1451586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN;
1452586320c0SNicholas Wilson     if (!WS.isExternal() && WS.isDefined())
1453586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;
1454586320c0SNicholas Wilson     if (WS.isUndefined())
1455586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_UNDEFINED;
1456da84b688SDan Gohman     if (WS.isNoStrip()) {
1457da84b688SDan Gohman       Flags |= wasm::WASM_SYMBOL_NO_STRIP;
1458da84b688SDan Gohman       if (isEmscripten()) {
1459d6ef8da3SSam Clegg         Flags |= wasm::WASM_SYMBOL_EXPORTED;
1460da84b688SDan Gohman       }
1461da84b688SDan Gohman     }
1462b4f4e370SSam Clegg     if (WS.hasImportName())
146329874ceaSDan Gohman       Flags |= wasm::WASM_SYMBOL_EXPLICIT_NAME;
1464881d8778SSam Clegg     if (WS.hasExportName())
1465881d8778SSam Clegg       Flags |= wasm::WASM_SYMBOL_EXPORTED;
1466586320c0SNicholas Wilson 
1467586320c0SNicholas Wilson     wasm::WasmSymbolInfo Info;
1468586320c0SNicholas Wilson     Info.Name = WS.getName();
1469586320c0SNicholas Wilson     Info.Kind = WS.getType();
1470586320c0SNicholas Wilson     Info.Flags = Flags;
14714d57fbd0SSam Clegg     if (!WS.isData()) {
14724d57fbd0SSam Clegg       assert(WasmIndices.count(&WS) > 0);
1473586320c0SNicholas Wilson       Info.ElementIndex = WasmIndices.find(&WS)->second;
14744d57fbd0SSam Clegg     } else if (WS.isDefined()) {
14754d57fbd0SSam Clegg       assert(DataLocations.count(&WS) > 0);
1476586320c0SNicholas Wilson       Info.DataRef = DataLocations.find(&WS)->second;
14774d57fbd0SSam Clegg     }
147825d8e68bSSam Clegg     WS.setIndex(SymbolInfos.size());
1479586320c0SNicholas Wilson     SymbolInfos.emplace_back(Info);
1480b7787fd0SSam Clegg   }
1481b7787fd0SSam Clegg 
14826006e091SSam Clegg   {
14836006e091SSam Clegg     auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
1484f9edbe95SSam Clegg       // Functions referenced by a relocation need to put in the table.  This is
1485f9edbe95SSam Clegg       // purely to make the object file's provisional values readable, and is
1486f9edbe95SSam Clegg       // ignored by the linker, which re-calculates the relocations itself.
1487d1152a26SSam Clegg       if (Rel.Type != wasm::R_WASM_TABLE_INDEX_I32 &&
1488d1152a26SSam Clegg           Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB)
1489f9edbe95SSam Clegg         return;
1490f9edbe95SSam Clegg       assert(Rel.Symbol->isFunction());
149118c56a07SHeejin Ahn       const MCSymbolWasm &WS = *resolveSymbol(*Rel.Symbol);
14926c899ba6SSam Clegg       uint32_t FunctionIndex = WasmIndices.find(&WS)->second;
149318c56a07SHeejin Ahn       uint32_t TableIndex = TableElems.size() + InitialTableOffset;
1494f9edbe95SSam Clegg       if (TableIndices.try_emplace(&WS, TableIndex).second) {
1495d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "  -> adding " << WS.getName()
1496f9edbe95SSam Clegg                           << " to table: " << TableIndex << "\n");
14976c899ba6SSam Clegg         TableElems.push_back(FunctionIndex);
14986006e091SSam Clegg         registerFunctionType(WS);
14996006e091SSam Clegg       }
15006006e091SSam Clegg     };
1501970d02c4SDan Gohman 
15026006e091SSam Clegg     for (const WasmRelocationEntry &RelEntry : CodeRelocations)
15036006e091SSam Clegg       HandleReloc(RelEntry);
15046006e091SSam Clegg     for (const WasmRelocationEntry &RelEntry : DataRelocations)
15056006e091SSam Clegg       HandleReloc(RelEntry);
1506d934cb88SDan Gohman   }
1507d934cb88SDan Gohman 
1508bafe6902SSam Clegg   // Translate .init_array section contents into start functions.
1509bafe6902SSam Clegg   for (const MCSection &S : Asm) {
1510bafe6902SSam Clegg     const auto &WS = static_cast<const MCSectionWasm &>(S);
1511*7d1ff446SFangrui Song     if (WS.getName().startswith(".fini_array"))
1512bafe6902SSam Clegg       report_fatal_error(".fini_array sections are unsupported");
1513*7d1ff446SFangrui Song     if (!WS.getName().startswith(".init_array"))
1514bafe6902SSam Clegg       continue;
1515bafe6902SSam Clegg     if (WS.getFragmentList().empty())
1516bafe6902SSam Clegg       continue;
1517b210c64bSSam Clegg 
1518b210c64bSSam Clegg     // init_array is expected to contain a single non-empty data fragment
1519b210c64bSSam Clegg     if (WS.getFragmentList().size() != 3)
1520bafe6902SSam Clegg       report_fatal_error("only one .init_array section fragment supported");
1521b210c64bSSam Clegg 
1522b210c64bSSam Clegg     auto IT = WS.begin();
1523b210c64bSSam Clegg     const MCFragment &EmptyFrag = *IT;
1524b210c64bSSam Clegg     if (EmptyFrag.getKind() != MCFragment::FT_Data)
1525b210c64bSSam Clegg       report_fatal_error(".init_array section should be aligned");
1526b210c64bSSam Clegg 
1527b210c64bSSam Clegg     IT = std::next(IT);
1528b210c64bSSam Clegg     const MCFragment &AlignFrag = *IT;
1529bafe6902SSam Clegg     if (AlignFrag.getKind() != MCFragment::FT_Align)
1530bafe6902SSam Clegg       report_fatal_error(".init_array section should be aligned");
1531bafe6902SSam Clegg     if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
1532bafe6902SSam Clegg       report_fatal_error(".init_array section should be aligned for pointers");
1533b210c64bSSam Clegg 
1534b210c64bSSam Clegg     const MCFragment &Frag = *std::next(IT);
1535bafe6902SSam Clegg     if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1536bafe6902SSam Clegg       report_fatal_error("only data supported in .init_array section");
1537b210c64bSSam Clegg 
1538bafe6902SSam Clegg     uint16_t Priority = UINT16_MAX;
15394d57fbd0SSam Clegg     unsigned PrefixLength = strlen(".init_array");
1540*7d1ff446SFangrui Song     if (WS.getName().size() > PrefixLength) {
1541*7d1ff446SFangrui Song       if (WS.getName()[PrefixLength] != '.')
1542f208f631SHeejin Ahn         report_fatal_error(
1543f208f631SHeejin Ahn             ".init_array section priority should start with '.'");
1544*7d1ff446SFangrui Song       if (WS.getName().substr(PrefixLength + 1).getAsInteger(10, Priority))
1545bafe6902SSam Clegg         report_fatal_error("invalid .init_array section priority");
1546bafe6902SSam Clegg     }
1547bafe6902SSam Clegg     const auto &DataFrag = cast<MCDataFragment>(Frag);
1548bafe6902SSam Clegg     const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1549f208f631SHeejin Ahn     for (const uint8_t *
155018c56a07SHeejin Ahn              P = (const uint8_t *)Contents.data(),
155118c56a07SHeejin Ahn             *End = (const uint8_t *)Contents.data() + Contents.size();
155218c56a07SHeejin Ahn          P != End; ++P) {
155318c56a07SHeejin Ahn       if (*P != 0)
1554bafe6902SSam Clegg         report_fatal_error("non-symbolic data in .init_array section");
1555bafe6902SSam Clegg     }
1556bafe6902SSam Clegg     for (const MCFixup &Fixup : DataFrag.getFixups()) {
1557f208f631SHeejin Ahn       assert(Fixup.getKind() ==
1558f208f631SHeejin Ahn              MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
1559bafe6902SSam Clegg       const MCExpr *Expr = Fixup.getValue();
15608fffa1dfSSam Clegg       auto *SymRef = dyn_cast<MCSymbolRefExpr>(Expr);
15618fffa1dfSSam Clegg       if (!SymRef)
1562bafe6902SSam Clegg         report_fatal_error("fixups in .init_array should be symbol references");
15638fffa1dfSSam Clegg       const auto &TargetSym = cast<const MCSymbolWasm>(SymRef->getSymbol());
15648fffa1dfSSam Clegg       if (TargetSym.getIndex() == InvalidIndex)
15653ea1c62cSSam Clegg         report_fatal_error("symbols in .init_array should exist in symtab");
15668fffa1dfSSam Clegg       if (!TargetSym.isFunction())
15678fffa1dfSSam Clegg         report_fatal_error("symbols in .init_array should be for functions");
156825d8e68bSSam Clegg       InitFuncs.push_back(
15698fffa1dfSSam Clegg           std::make_pair(Priority, TargetSym.getIndex()));
1570bafe6902SSam Clegg     }
1571bafe6902SSam Clegg   }
1572bafe6902SSam Clegg 
157318eafb6cSDan Gohman   // Write out the Wasm header.
157418eafb6cSDan Gohman   writeHeader(Asm);
157518eafb6cSDan Gohman 
1576da419bdbSHeejin Ahn   writeTypeSection(Signatures);
1577f950b24aSSam Clegg   writeImportSection(Imports, DataSize, TableElems.size());
15789e15f359SSam Clegg   writeFunctionSection(Functions);
1579f950b24aSSam Clegg   // Skip the "table" section; we import the table instead.
1580f950b24aSSam Clegg   // Skip the "memory" section; we import the memory instead.
1581da419bdbSHeejin Ahn   writeEventSection(Events);
15829e15f359SSam Clegg   writeExportSection(Exports);
15839e15f359SSam Clegg   writeElemSection(TableElems);
1584fef8de66SThomas Lively   writeDataCountSection();
1585acd7d2b0SSam Clegg   writeCodeSection(Asm, Layout, Functions);
15866c899ba6SSam Clegg   writeDataSection();
1587cbda16ebSThomas Lively   for (auto &CustomSection : CustomSections)
1588cbda16ebSThomas Lively     writeCustomSection(CustomSection, Asm, Layout);
1589c22bfb6bSNicholas Wilson   writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats);
15906f08c84aSSam Clegg   writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations);
15916f08c84aSSam Clegg   writeRelocSection(DataSectionIndex, "DATA", DataRelocations);
15926a31a0d6SSam Clegg   writeCustomRelocSections();
1593cbda16ebSThomas Lively   if (ProducersSection)
1594cbda16ebSThomas Lively     writeCustomSection(*ProducersSection, Asm, Layout);
1595f6f4f843SThomas Lively   if (TargetFeaturesSection)
1596f6f4f843SThomas Lively     writeCustomSection(*TargetFeaturesSection, Asm, Layout);
1597970d02c4SDan Gohman 
1598d934cb88SDan Gohman   // TODO: Translate the .comment section to the output.
1599438390faSPeter Collingbourne   return W.OS.tell() - StartOffset;
160018eafb6cSDan Gohman }
160118eafb6cSDan Gohman 
160260fbc7ccSLang Hames std::unique_ptr<MCObjectWriter>
16031301a878SLang Hames llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
160418eafb6cSDan Gohman                              raw_pwrite_stream &OS) {
16050eaee545SJonas Devlieghere   return std::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
160618eafb6cSDan Gohman }
1607