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"
30*bcd7f777SSimon Pilgrim #include "llvm/Support/EndianStream.h"
3118eafb6cSDan Gohman #include "llvm/Support/ErrorHandling.h"
32d934cb88SDan Gohman #include "llvm/Support/LEB128.h"
3318eafb6cSDan Gohman #include "llvm/Support/StringSaver.h"
3418eafb6cSDan Gohman #include <vector>
3518eafb6cSDan Gohman 
3618eafb6cSDan Gohman using namespace llvm;
3718eafb6cSDan Gohman 
385e3d33a7SSam Clegg #define DEBUG_TYPE "mc"
3918eafb6cSDan Gohman 
4018eafb6cSDan Gohman namespace {
419e15f359SSam Clegg 
4230e1bbc1SSam Clegg // Went we ceate the indirect function table we start at 1, so that there is
4330e1bbc1SSam Clegg // and emtpy slot at 0 and therefore calling a null function pointer will trap.
4418c56a07SHeejin Ahn static const uint32_t InitialTableOffset = 1;
4530e1bbc1SSam Clegg 
46d934cb88SDan Gohman // For patching purposes, we need to remember where each section starts, both
47d934cb88SDan Gohman // for patching up the section size field, and for patching up references to
48d934cb88SDan Gohman // locations within the section.
49d934cb88SDan Gohman struct SectionBookkeeping {
50d934cb88SDan Gohman   // Where the size of the section is written.
51d934cb88SDan Gohman   uint64_t SizeOffset;
526a31a0d6SSam Clegg   // Where the section header ends (without custom section name).
536a31a0d6SSam Clegg   uint64_t PayloadOffset;
546a31a0d6SSam Clegg   // Where the contents of the section starts.
55d934cb88SDan Gohman   uint64_t ContentsOffset;
566f08c84aSSam Clegg   uint32_t Index;
57d934cb88SDan Gohman };
58d934cb88SDan Gohman 
59da419bdbSHeejin Ahn // The signature of a wasm function or event, in a struct capable of being used
60da419bdbSHeejin Ahn // as a DenseMap key.
61da419bdbSHeejin Ahn // TODO: Consider using wasm::WasmSignature directly instead.
62da419bdbSHeejin Ahn struct WasmSignature {
639e15f359SSam Clegg   // Support empty and tombstone instances, needed by DenseMap.
6418c56a07SHeejin Ahn   enum { Plain, Empty, Tombstone } State = Plain;
659e15f359SSam Clegg 
669e15f359SSam Clegg   // The return types of the function.
679e15f359SSam Clegg   SmallVector<wasm::ValType, 1> Returns;
689e15f359SSam Clegg 
699e15f359SSam Clegg   // The parameter types of the function.
709e15f359SSam Clegg   SmallVector<wasm::ValType, 4> Params;
719e15f359SSam Clegg 
72da419bdbSHeejin Ahn   bool operator==(const WasmSignature &Other) const {
739e15f359SSam Clegg     return State == Other.State && Returns == Other.Returns &&
749e15f359SSam Clegg            Params == Other.Params;
759e15f359SSam Clegg   }
769e15f359SSam Clegg };
779e15f359SSam Clegg 
78da419bdbSHeejin Ahn // Traits for using WasmSignature in a DenseMap.
79da419bdbSHeejin Ahn struct WasmSignatureDenseMapInfo {
80da419bdbSHeejin Ahn   static WasmSignature getEmptyKey() {
81da419bdbSHeejin Ahn     WasmSignature Sig;
82da419bdbSHeejin Ahn     Sig.State = WasmSignature::Empty;
83da419bdbSHeejin Ahn     return Sig;
849e15f359SSam Clegg   }
85da419bdbSHeejin Ahn   static WasmSignature getTombstoneKey() {
86da419bdbSHeejin Ahn     WasmSignature Sig;
87da419bdbSHeejin Ahn     Sig.State = WasmSignature::Tombstone;
88da419bdbSHeejin Ahn     return Sig;
899e15f359SSam Clegg   }
90da419bdbSHeejin Ahn   static unsigned getHashValue(const WasmSignature &Sig) {
91da419bdbSHeejin Ahn     uintptr_t Value = Sig.State;
92da419bdbSHeejin Ahn     for (wasm::ValType Ret : Sig.Returns)
934808914aSHeejin Ahn       Value += DenseMapInfo<uint32_t>::getHashValue(uint32_t(Ret));
94da419bdbSHeejin Ahn     for (wasm::ValType Param : Sig.Params)
954808914aSHeejin Ahn       Value += DenseMapInfo<uint32_t>::getHashValue(uint32_t(Param));
969e15f359SSam Clegg     return Value;
979e15f359SSam Clegg   }
98da419bdbSHeejin Ahn   static bool isEqual(const WasmSignature &LHS, const WasmSignature &RHS) {
999e15f359SSam Clegg     return LHS == RHS;
1009e15f359SSam Clegg   }
1019e15f359SSam Clegg };
1029e15f359SSam Clegg 
1037c395943SSam Clegg // A wasm data segment.  A wasm binary contains only a single data section
1047c395943SSam Clegg // but that can contain many segments, each with their own virtual location
1057c395943SSam Clegg // in memory.  Each MCSection data created by llvm is modeled as its own
1067c395943SSam Clegg // wasm data segment.
1077c395943SSam Clegg struct WasmDataSegment {
1087c395943SSam Clegg   MCSectionWasm *Section;
109d95ed959SSam Clegg   StringRef Name;
1102e150409SThomas Lively   uint32_t InitFlags;
1117c395943SSam Clegg   uint32_t Offset;
11263ebb813SSam Clegg   uint32_t Alignment;
1132e150409SThomas Lively   uint32_t LinkerFlags;
1147c395943SSam Clegg   SmallVector<char, 4> Data;
1157c395943SSam Clegg };
1167c395943SSam Clegg 
1179e15f359SSam Clegg // A wasm function to be written into the function section.
1189e15f359SSam Clegg struct WasmFunction {
119da419bdbSHeejin Ahn   uint32_t SigIndex;
1209e15f359SSam Clegg   const MCSymbolWasm *Sym;
1219e15f359SSam Clegg };
1229e15f359SSam Clegg 
1239e15f359SSam Clegg // A wasm global to be written into the global section.
1249e15f359SSam Clegg struct WasmGlobal {
1256e7f1826SSam Clegg   wasm::WasmGlobalType Type;
1269e15f359SSam Clegg   uint64_t InitialValue;
1279e15f359SSam Clegg };
1289e15f359SSam Clegg 
129ea7caceeSSam Clegg // Information about a single item which is part of a COMDAT.  For each data
130ea7caceeSSam Clegg // segment or function which is in the COMDAT, there is a corresponding
131ea7caceeSSam Clegg // WasmComdatEntry.
132ea7caceeSSam Clegg struct WasmComdatEntry {
133ea7caceeSSam Clegg   unsigned Kind;
134ea7caceeSSam Clegg   uint32_t Index;
135ea7caceeSSam Clegg };
136ea7caceeSSam Clegg 
1376dc65e91SSam Clegg // Information about a single relocation.
1386dc65e91SSam Clegg struct WasmRelocationEntry {
1396dc65e91SSam Clegg   uint64_t Offset;                   // Where is the relocation.
1406dc65e91SSam Clegg   const MCSymbolWasm *Symbol;        // The symbol to relocate with.
1416dc65e91SSam Clegg   int64_t Addend;                    // A value to add to the symbol.
1426dc65e91SSam Clegg   unsigned Type;                     // The type of the relocation.
143fe6414b0SSam Clegg   const MCSectionWasm *FixupSection; // The section the relocation is targeting.
1446dc65e91SSam Clegg 
1456dc65e91SSam Clegg   WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol,
1466dc65e91SSam Clegg                       int64_t Addend, unsigned Type,
147fe6414b0SSam Clegg                       const MCSectionWasm *FixupSection)
1486dc65e91SSam Clegg       : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type),
1496dc65e91SSam Clegg         FixupSection(FixupSection) {}
1506dc65e91SSam Clegg 
151cadcb9ebSKeno Fischer   bool hasAddend() const { return wasm::relocTypeHasAddend(Type); }
152acd7d2b0SSam Clegg 
1536dc65e91SSam Clegg   void print(raw_ostream &Out) const {
154f208f631SHeejin Ahn     Out << wasm::relocTypetoString(Type) << " Off=" << Offset
155f208f631SHeejin Ahn         << ", Sym=" << *Symbol << ", Addend=" << Addend
1567d1ff446SFangrui Song         << ", FixupSection=" << FixupSection->getName();
1576dc65e91SSam Clegg   }
158b7787fd0SSam Clegg 
159615eb470SAaron Ballman #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
160b7787fd0SSam Clegg   LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
161b7787fd0SSam Clegg #endif
1626dc65e91SSam Clegg };
1636dc65e91SSam Clegg 
16418c56a07SHeejin Ahn static const uint32_t InvalidIndex = -1;
16525d8e68bSSam Clegg 
166cfd44a2eSSam Clegg struct WasmCustomSection {
167cfd44a2eSSam Clegg 
1686a31a0d6SSam Clegg   StringRef Name;
1696a31a0d6SSam Clegg   MCSectionWasm *Section;
1706a31a0d6SSam Clegg 
1716a31a0d6SSam Clegg   uint32_t OutputContentsOffset;
1726a31a0d6SSam Clegg   uint32_t OutputIndex;
1736a31a0d6SSam Clegg 
1746a31a0d6SSam Clegg   WasmCustomSection(StringRef Name, MCSectionWasm *Section)
1756a31a0d6SSam Clegg       : Name(Name), Section(Section), OutputContentsOffset(0),
17618c56a07SHeejin Ahn         OutputIndex(InvalidIndex) {}
177cfd44a2eSSam Clegg };
178cfd44a2eSSam Clegg 
1791fb8daa6SSam Clegg #if !defined(NDEBUG)
1807f055deeSSam Clegg raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
181b7787fd0SSam Clegg   Rel.print(OS);
182b7787fd0SSam Clegg   return OS;
183b7787fd0SSam Clegg }
1841fb8daa6SSam Clegg #endif
185b7787fd0SSam Clegg 
18619e8befaSSam Clegg // Write X as an (unsigned) LEB value at offset Offset in Stream, padded
18719e8befaSSam Clegg // to allow patching.
18818c56a07SHeejin Ahn static void writePatchableLEB(raw_pwrite_stream &Stream, uint32_t X,
18919e8befaSSam Clegg                               uint64_t Offset) {
19019e8befaSSam Clegg   uint8_t Buffer[5];
19119e8befaSSam Clegg   unsigned SizeLen = encodeULEB128(X, Buffer, 5);
19219e8befaSSam Clegg   assert(SizeLen == 5);
19319e8befaSSam Clegg   Stream.pwrite((char *)Buffer, SizeLen, Offset);
19419e8befaSSam Clegg }
19519e8befaSSam Clegg 
19619e8befaSSam Clegg // Write X as an signed LEB value at offset Offset in Stream, padded
19719e8befaSSam Clegg // to allow patching.
19818c56a07SHeejin Ahn static void writePatchableSLEB(raw_pwrite_stream &Stream, int32_t X,
19919e8befaSSam Clegg                                uint64_t Offset) {
20019e8befaSSam Clegg   uint8_t Buffer[5];
20119e8befaSSam Clegg   unsigned SizeLen = encodeSLEB128(X, Buffer, 5);
20219e8befaSSam Clegg   assert(SizeLen == 5);
20319e8befaSSam Clegg   Stream.pwrite((char *)Buffer, SizeLen, Offset);
20419e8befaSSam Clegg }
20519e8befaSSam Clegg 
20619e8befaSSam Clegg // Write X as a plain integer value at offset Offset in Stream.
20718c56a07SHeejin Ahn static void writeI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
20819e8befaSSam Clegg   uint8_t Buffer[4];
20919e8befaSSam Clegg   support::endian::write32le(Buffer, X);
21019e8befaSSam Clegg   Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
21119e8befaSSam Clegg }
21219e8befaSSam Clegg 
21318eafb6cSDan Gohman class WasmObjectWriter : public MCObjectWriter {
214f17b149dSPeter Collingbourne   support::endian::Writer W;
215f17b149dSPeter Collingbourne 
21618eafb6cSDan Gohman   /// The target specific Wasm writer instance.
21718eafb6cSDan Gohman   std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
21818eafb6cSDan Gohman 
219d934cb88SDan Gohman   // Relocations for fixing up references in the code section.
220d934cb88SDan Gohman   std::vector<WasmRelocationEntry> CodeRelocations;
2216f08c84aSSam Clegg   uint32_t CodeSectionIndex;
222d934cb88SDan Gohman 
223d934cb88SDan Gohman   // Relocations for fixing up references in the data section.
224d934cb88SDan Gohman   std::vector<WasmRelocationEntry> DataRelocations;
2256f08c84aSSam Clegg   uint32_t DataSectionIndex;
226d934cb88SDan Gohman 
227d934cb88SDan Gohman   // Index values to use for fixing up call_indirect type indices.
228acd7d2b0SSam Clegg   // Maps function symbols to the index of the type of the function
229acd7d2b0SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
230d99f6078SSam Clegg   // Maps function symbols to the table element index space. Used
231d99f6078SSam Clegg   // for TABLE_INDEX relocation types (i.e. address taken functions).
232f9edbe95SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> TableIndices;
233da419bdbSHeejin Ahn   // Maps function/global symbols to the function/global/event/section index
234da419bdbSHeejin Ahn   // space.
2356c899ba6SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> WasmIndices;
236492f7529SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> GOTIndices;
2376c899ba6SSam Clegg   // Maps data symbols to the Wasm segment and offset/size with the segment.
2386c899ba6SSam Clegg   DenseMap<const MCSymbolWasm *, wasm::WasmDataReference> DataLocations;
2396a31a0d6SSam Clegg 
2406a31a0d6SSam Clegg   // Stores output data (index, relocations, content offset) for custom
2416a31a0d6SSam Clegg   // section.
2426a31a0d6SSam Clegg   std::vector<WasmCustomSection> CustomSections;
243cbda16ebSThomas Lively   std::unique_ptr<WasmCustomSection> ProducersSection;
244f6f4f843SThomas Lively   std::unique_ptr<WasmCustomSection> TargetFeaturesSection;
2456a31a0d6SSam Clegg   // Relocations for fixing up references in the custom sections.
2466a31a0d6SSam Clegg   DenseMap<const MCSectionWasm *, std::vector<WasmRelocationEntry>>
2476a31a0d6SSam Clegg       CustomSectionsRelocations;
248acd7d2b0SSam Clegg 
249c0d41195SSam Clegg   // Map from section to defining function symbol.
2506ccb59b3SSam Clegg   DenseMap<const MCSection *, const MCSymbol *> SectionFunctions;
2516ccb59b3SSam Clegg 
252da419bdbSHeejin Ahn   DenseMap<WasmSignature, uint32_t, WasmSignatureDenseMapInfo> SignatureIndices;
253da419bdbSHeejin Ahn   SmallVector<WasmSignature, 4> Signatures;
2546c899ba6SSam Clegg   SmallVector<WasmDataSegment, 4> DataSegments;
2559f3fe42eSSam Clegg   unsigned NumFunctionImports = 0;
2567c395943SSam Clegg   unsigned NumGlobalImports = 0;
257da419bdbSHeejin Ahn   unsigned NumEventImports = 0;
2587e1c3345SChandler Carruth   uint32_t SectionCount = 0;
259d934cb88SDan Gohman 
26018eafb6cSDan Gohman   // TargetObjectWriter wrappers.
26118eafb6cSDan Gohman   bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
262da84b688SDan Gohman   bool isEmscripten() const { return TargetObjectWriter->isEmscripten(); }
26318eafb6cSDan Gohman 
2642322a937SSam Clegg   void startSection(SectionBookkeeping &Section, unsigned SectionId);
2652322a937SSam Clegg   void startCustomSection(SectionBookkeeping &Section, StringRef Name);
266d934cb88SDan Gohman   void endSection(SectionBookkeeping &Section);
267d934cb88SDan Gohman 
26818eafb6cSDan Gohman public:
2691301a878SLang Hames   WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
2701301a878SLang Hames                    raw_pwrite_stream &OS)
27159a6fc46SPeter Collingbourne       : W(OS, support::little), TargetObjectWriter(std::move(MOTW)) {}
27218eafb6cSDan Gohman 
2730917c9e4SDan Gohman private:
274acd7d2b0SSam Clegg   void reset() override {
275acd7d2b0SSam Clegg     CodeRelocations.clear();
276acd7d2b0SSam Clegg     DataRelocations.clear();
277acd7d2b0SSam Clegg     TypeIndices.clear();
2786c899ba6SSam Clegg     WasmIndices.clear();
279492f7529SSam Clegg     GOTIndices.clear();
280f9edbe95SSam Clegg     TableIndices.clear();
2816c899ba6SSam Clegg     DataLocations.clear();
282cbda16ebSThomas Lively     CustomSections.clear();
283cbda16ebSThomas Lively     ProducersSection.reset();
284f6f4f843SThomas Lively     TargetFeaturesSection.reset();
2856a31a0d6SSam Clegg     CustomSectionsRelocations.clear();
286da419bdbSHeejin Ahn     SignatureIndices.clear();
287da419bdbSHeejin Ahn     Signatures.clear();
2886c899ba6SSam Clegg     DataSegments.clear();
2896ccb59b3SSam Clegg     SectionFunctions.clear();
2909f3fe42eSSam Clegg     NumFunctionImports = 0;
2917c395943SSam Clegg     NumGlobalImports = 0;
292105bdc25SSam Clegg     MCObjectWriter::reset();
293acd7d2b0SSam Clegg   }
294acd7d2b0SSam Clegg 
29518eafb6cSDan Gohman   void writeHeader(const MCAssembler &Asm);
29618eafb6cSDan Gohman 
29718eafb6cSDan Gohman   void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
29818eafb6cSDan Gohman                         const MCFragment *Fragment, const MCFixup &Fixup,
299ceecfe5bSRafael Espindola                         MCValue Target, uint64_t &FixedValue) override;
30018eafb6cSDan Gohman 
30118eafb6cSDan Gohman   void executePostLayoutBinding(MCAssembler &Asm,
30218eafb6cSDan Gohman                                 const MCAsmLayout &Layout) override;
30318eafb6cSDan Gohman 
304438390faSPeter Collingbourne   uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
3059e15f359SSam Clegg 
306b7787fd0SSam Clegg   void writeString(const StringRef Str) {
307f17b149dSPeter Collingbourne     encodeULEB128(Str.size(), W.OS);
308f17b149dSPeter Collingbourne     W.OS << Str;
309b7787fd0SSam Clegg   }
310b7787fd0SSam Clegg 
311f208f631SHeejin Ahn   void writeValueType(wasm::ValType Ty) { W.OS << static_cast<char>(Ty); }
3129e15f359SSam Clegg 
313da419bdbSHeejin Ahn   void writeTypeSection(ArrayRef<WasmSignature> Signatures);
3148defa952SSam Clegg   void writeImportSection(ArrayRef<wasm::WasmImport> Imports, uint32_t DataSize,
315f950b24aSSam Clegg                           uint32_t NumElements);
316457fb0b4SSam Clegg   void writeFunctionSection(ArrayRef<WasmFunction> Functions);
3178defa952SSam Clegg   void writeExportSection(ArrayRef<wasm::WasmExport> Exports);
318457fb0b4SSam Clegg   void writeElemSection(ArrayRef<uint32_t> TableElems);
319fef8de66SThomas Lively   void writeDataCountSection();
3209e15f359SSam Clegg   void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
321457fb0b4SSam Clegg                         ArrayRef<WasmFunction> Functions);
3226c899ba6SSam Clegg   void writeDataSection();
323da419bdbSHeejin Ahn   void writeEventSection(ArrayRef<wasm::WasmEventType> Events);
3246f08c84aSSam Clegg   void writeRelocSection(uint32_t SectionIndex, StringRef Name,
325f77dc2a8SSam Clegg                          std::vector<WasmRelocationEntry> &Relocations);
32631a2c809SSam Clegg   void writeLinkingMetaDataSection(
32786b4a09aSSam Clegg       ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
328ea7caceeSSam Clegg       ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
329ea7caceeSSam Clegg       const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats);
330cbda16ebSThomas Lively   void writeCustomSection(WasmCustomSection &CustomSection,
331cbda16ebSThomas Lively                           const MCAssembler &Asm, const MCAsmLayout &Layout);
3326a31a0d6SSam Clegg   void writeCustomRelocSections();
3336a31a0d6SSam Clegg   void
3346a31a0d6SSam Clegg   updateCustomSectionRelocations(const SmallVector<WasmFunction, 4> &Functions,
3356a31a0d6SSam Clegg                                  const MCAsmLayout &Layout);
336acd7d2b0SSam Clegg 
3377c395943SSam Clegg   uint32_t getProvisionalValue(const WasmRelocationEntry &RelEntry);
338acd7d2b0SSam Clegg   void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
339acd7d2b0SSam Clegg                         uint64_t ContentsOffset);
340acd7d2b0SSam Clegg 
341acd7d2b0SSam Clegg   uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
3425e3d33a7SSam Clegg   uint32_t getFunctionType(const MCSymbolWasm &Symbol);
343da419bdbSHeejin Ahn   uint32_t getEventType(const MCSymbolWasm &Symbol);
34438b12f5eSHeejin Ahn   void registerFunctionType(const MCSymbolWasm &Symbol);
34538b12f5eSHeejin Ahn   void registerEventType(const MCSymbolWasm &Symbol);
34618eafb6cSDan Gohman };
3479e15f359SSam Clegg 
34818eafb6cSDan Gohman } // end anonymous namespace
34918eafb6cSDan Gohman 
350d934cb88SDan Gohman // Write out a section header and a patchable section size field.
351d934cb88SDan Gohman void WasmObjectWriter::startSection(SectionBookkeeping &Section,
3522322a937SSam Clegg                                     unsigned SectionId) {
353d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "startSection " << SectionId << "\n");
354f17b149dSPeter Collingbourne   W.OS << char(SectionId);
355d934cb88SDan Gohman 
356f17b149dSPeter Collingbourne   Section.SizeOffset = W.OS.tell();
357d934cb88SDan Gohman 
358d934cb88SDan Gohman   // The section size. We don't know the size yet, so reserve enough space
359d934cb88SDan Gohman   // for any 32-bit value; we'll patch it later.
36019e8befaSSam Clegg   encodeULEB128(0, W.OS, 5);
361d934cb88SDan Gohman 
362d934cb88SDan Gohman   // The position where the section starts, for measuring its size.
363f17b149dSPeter Collingbourne   Section.ContentsOffset = W.OS.tell();
364f17b149dSPeter Collingbourne   Section.PayloadOffset = W.OS.tell();
3656f08c84aSSam Clegg   Section.Index = SectionCount++;
366d934cb88SDan Gohman }
3672322a937SSam Clegg 
3682322a937SSam Clegg void WasmObjectWriter::startCustomSection(SectionBookkeeping &Section,
3692322a937SSam Clegg                                           StringRef Name) {
370d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "startCustomSection " << Name << "\n");
3712322a937SSam Clegg   startSection(Section, wasm::WASM_SEC_CUSTOM);
3726a31a0d6SSam Clegg 
3736a31a0d6SSam Clegg   // The position where the section header ends, for measuring its size.
374f17b149dSPeter Collingbourne   Section.PayloadOffset = W.OS.tell();
3756a31a0d6SSam Clegg 
3762322a937SSam Clegg   // Custom sections in wasm also have a string identifier.
3772322a937SSam Clegg   writeString(Name);
3786a31a0d6SSam Clegg 
3796a31a0d6SSam Clegg   // The position where the custom section starts.
380f17b149dSPeter Collingbourne   Section.ContentsOffset = W.OS.tell();
381d934cb88SDan Gohman }
382d934cb88SDan Gohman 
383d934cb88SDan Gohman // Now that the section is complete and we know how big it is, patch up the
384d934cb88SDan Gohman // section size field at the start of the section.
385d934cb88SDan Gohman void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
386c0affde8SSam Clegg   uint64_t Size = W.OS.tell();
387c0affde8SSam Clegg   // /dev/null doesn't support seek/tell and can report offset of 0.
388c0affde8SSam Clegg   // Simply skip this patching in that case.
389c0affde8SSam Clegg   if (!Size)
390c0affde8SSam Clegg     return;
391c0affde8SSam Clegg 
392c0affde8SSam Clegg   Size -= Section.PayloadOffset;
393d934cb88SDan Gohman   if (uint32_t(Size) != Size)
394d934cb88SDan Gohman     report_fatal_error("section size does not fit in a uint32_t");
395d934cb88SDan Gohman 
396d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "endSection size=" << Size << "\n");
397d934cb88SDan Gohman 
398d934cb88SDan Gohman   // Write the final section size to the payload_len field, which follows
399d934cb88SDan Gohman   // the section id byte.
40018c56a07SHeejin Ahn   writePatchableLEB(static_cast<raw_pwrite_stream &>(W.OS), Size,
401f17b149dSPeter Collingbourne                     Section.SizeOffset);
402d934cb88SDan Gohman }
403d934cb88SDan Gohman 
40418eafb6cSDan Gohman // Emit the Wasm header.
40518eafb6cSDan Gohman void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
406f17b149dSPeter Collingbourne   W.OS.write(wasm::WasmMagic, sizeof(wasm::WasmMagic));
407f17b149dSPeter Collingbourne   W.write<uint32_t>(wasm::WasmVersion);
40818eafb6cSDan Gohman }
40918eafb6cSDan Gohman 
41018eafb6cSDan Gohman void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
41118eafb6cSDan Gohman                                                 const MCAsmLayout &Layout) {
4126ccb59b3SSam Clegg   // Build a map of sections to the function that defines them, for use
4136ccb59b3SSam Clegg   // in recordRelocation.
4146ccb59b3SSam Clegg   for (const MCSymbol &S : Asm.symbols()) {
4156ccb59b3SSam Clegg     const auto &WS = static_cast<const MCSymbolWasm &>(S);
4166ccb59b3SSam Clegg     if (WS.isDefined() && WS.isFunction() && !WS.isVariable()) {
4176ccb59b3SSam Clegg       const auto &Sec = static_cast<const MCSectionWasm &>(S.getSection());
4186ccb59b3SSam Clegg       auto Pair = SectionFunctions.insert(std::make_pair(&Sec, &S));
4196ccb59b3SSam Clegg       if (!Pair.second)
4206ccb59b3SSam Clegg         report_fatal_error("section already has a defining function: " +
4217d1ff446SFangrui Song                            Sec.getName());
4226ccb59b3SSam Clegg     }
4236ccb59b3SSam Clegg   }
42418eafb6cSDan Gohman }
42518eafb6cSDan Gohman 
42618eafb6cSDan Gohman void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
42718eafb6cSDan Gohman                                         const MCAsmLayout &Layout,
42818eafb6cSDan Gohman                                         const MCFragment *Fragment,
42918eafb6cSDan Gohman                                         const MCFixup &Fixup, MCValue Target,
430ceecfe5bSRafael Espindola                                         uint64_t &FixedValue) {
431ecc5e808SSam Clegg   // The WebAssembly backend should never generate FKF_IsPCRel fixups
432e828ce1bSFangrui Song   assert(!(Asm.getBackend().getFixupKindInfo(Fixup.getKind()).Flags &
433ecc5e808SSam Clegg            MCFixupKindInfo::FKF_IsPCRel));
434ecc5e808SSam Clegg 
435fe6414b0SSam Clegg   const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
436d934cb88SDan Gohman   uint64_t C = Target.getConstant();
437d934cb88SDan Gohman   uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
438d934cb88SDan Gohman   MCContext &Ctx = Asm.getContext();
439d934cb88SDan Gohman 
440d934cb88SDan Gohman   if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
441ecc5e808SSam Clegg     // To get here the A - B expression must have failed evaluateAsRelocatable.
442ecc5e808SSam Clegg     // This means either A or B must be undefined and in WebAssembly we can't
443ecc5e808SSam Clegg     // support either of those cases.
444ecc5e808SSam Clegg     const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
445d934cb88SDan Gohman     Ctx.reportError(
446d934cb88SDan Gohman         Fixup.getLoc(),
447d934cb88SDan Gohman         Twine("symbol '") + SymB.getName() +
448ecc5e808SSam Clegg             "': unsupported subtraction expression used in relocation.");
449d934cb88SDan Gohman     return;
450d934cb88SDan Gohman   }
451d934cb88SDan Gohman 
452d934cb88SDan Gohman   // We either rejected the fixup or folded B into C at this point.
453d934cb88SDan Gohman   const MCSymbolRefExpr *RefA = Target.getSymA();
454ecc5e808SSam Clegg   const auto *SymA = cast<MCSymbolWasm>(&RefA->getSymbol());
455d934cb88SDan Gohman 
4563ea1c62cSSam Clegg   // The .init_array isn't translated as data, so don't do relocations in it.
4577d1ff446SFangrui Song   if (FixupSection.getName().startswith(".init_array")) {
4583ea1c62cSSam Clegg     SymA->setUsedInInitArray();
4593ea1c62cSSam Clegg     return;
4603ea1c62cSSam Clegg   }
4613ea1c62cSSam Clegg 
462ecc5e808SSam Clegg   if (SymA->isVariable()) {
463d934cb88SDan Gohman     const MCExpr *Expr = SymA->getVariableValue();
4646ad8f190SSam Clegg     const auto *Inner = cast<MCSymbolRefExpr>(Expr);
4656ad8f190SSam Clegg     if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
4666ad8f190SSam Clegg       llvm_unreachable("weakref used in reloc not yet implemented");
467d934cb88SDan Gohman   }
468d934cb88SDan Gohman 
469d934cb88SDan Gohman   // Put any constant offset in an addend. Offsets can be negative, and
470d934cb88SDan Gohman   // LLVM expects wrapping, in contrast to wasm's immediates which can't
471d934cb88SDan Gohman   // be negative and don't wrap.
472d934cb88SDan Gohman   FixedValue = 0;
473d934cb88SDan Gohman 
474a5e175c6SSam Clegg   unsigned Type = TargetObjectWriter->getRelocType(Target, Fixup);
4759d24fb7fSSam Clegg 
4764d57fbd0SSam Clegg   // Absolute offset within a section or a function.
4774d57fbd0SSam Clegg   // Currently only supported for for metadata sections.
4784d57fbd0SSam Clegg   // See: test/MC/WebAssembly/blockaddress.ll
479d1152a26SSam Clegg   if (Type == wasm::R_WASM_FUNCTION_OFFSET_I32 ||
480d1152a26SSam Clegg       Type == wasm::R_WASM_SECTION_OFFSET_I32) {
4814d57fbd0SSam Clegg     if (!FixupSection.getKind().isMetadata())
4824d57fbd0SSam Clegg       report_fatal_error("relocations for function or section offsets are "
4834d57fbd0SSam Clegg                          "only supported in metadata sections");
4844d57fbd0SSam Clegg 
4854d57fbd0SSam Clegg     const MCSymbol *SectionSymbol = nullptr;
4864d57fbd0SSam Clegg     const MCSection &SecA = SymA->getSection();
4874d57fbd0SSam Clegg     if (SecA.getKind().isText())
4886ccb59b3SSam Clegg       SectionSymbol = SectionFunctions.find(&SecA)->second;
4894d57fbd0SSam Clegg     else
4904d57fbd0SSam Clegg       SectionSymbol = SecA.getBeginSymbol();
4914d57fbd0SSam Clegg     if (!SectionSymbol)
4924d57fbd0SSam Clegg       report_fatal_error("section symbol is required for relocation");
4934d57fbd0SSam Clegg 
4944d57fbd0SSam Clegg     C += Layout.getSymbolOffset(*SymA);
4954d57fbd0SSam Clegg     SymA = cast<MCSymbolWasm>(SectionSymbol);
4964d57fbd0SSam Clegg   }
4974d57fbd0SSam Clegg 
498d1152a26SSam Clegg   // Relocation other than R_WASM_TYPE_INDEX_LEB are required to be
4994d57fbd0SSam Clegg   // against a named symbol.
500d1152a26SSam Clegg   if (Type != wasm::R_WASM_TYPE_INDEX_LEB) {
5014d57fbd0SSam Clegg     if (SymA->getName().empty())
5024d57fbd0SSam Clegg       report_fatal_error("relocations against un-named temporaries are not yet "
5034d57fbd0SSam Clegg                          "supported by wasm");
5044d57fbd0SSam Clegg 
5054d57fbd0SSam Clegg     SymA->setUsedInReloc();
5064d57fbd0SSam Clegg   }
507ae03c1e7SSam Clegg 
508492f7529SSam Clegg   if (RefA->getKind() == MCSymbolRefExpr::VK_GOT)
509492f7529SSam Clegg     SymA->setUsedInGOT();
510492f7529SSam Clegg 
511d934cb88SDan Gohman   WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
512d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
513d934cb88SDan Gohman 
5146a31a0d6SSam Clegg   if (FixupSection.isWasmData()) {
515d934cb88SDan Gohman     DataRelocations.push_back(Rec);
5166a31a0d6SSam Clegg   } else if (FixupSection.getKind().isText()) {
51712fd3da9SSam Clegg     CodeRelocations.push_back(Rec);
5186a31a0d6SSam Clegg   } else if (FixupSection.getKind().isMetadata()) {
5196a31a0d6SSam Clegg     CustomSectionsRelocations[&FixupSection].push_back(Rec);
5206a31a0d6SSam Clegg   } else {
52112fd3da9SSam Clegg     llvm_unreachable("unexpected section type");
522d934cb88SDan Gohman   }
5236a31a0d6SSam Clegg }
524d934cb88SDan Gohman 
52518c56a07SHeejin Ahn static const MCSymbolWasm *resolveSymbol(const MCSymbolWasm &Symbol) {
526ffba00bdSSam Clegg   const MCSymbolWasm* Ret = &Symbol;
527ffba00bdSSam Clegg   while (Ret->isVariable()) {
528ffba00bdSSam Clegg     const MCExpr *Expr = Ret->getVariableValue();
529aff1c4dfSSam Clegg     auto *Inner = cast<MCSymbolRefExpr>(Expr);
530ffba00bdSSam Clegg     Ret = cast<MCSymbolWasm>(&Inner->getSymbol());
531aff1c4dfSSam Clegg   }
532ffba00bdSSam Clegg   return Ret;
533aff1c4dfSSam Clegg }
534aff1c4dfSSam Clegg 
535d934cb88SDan Gohman // Compute a value to write into the code at the location covered
53660ec3034SSam Clegg // by RelEntry. This value isn't used by the static linker; it just serves
53760ec3034SSam Clegg // to make the object format more readable and more likely to be directly
53860ec3034SSam Clegg // useable.
5397c395943SSam Clegg uint32_t
5407c395943SSam Clegg WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) {
54148139ebcSWouter van Oortmerssen   if ((RelEntry.Type == wasm::R_WASM_GLOBAL_INDEX_LEB ||
54248139ebcSWouter van Oortmerssen        RelEntry.Type == wasm::R_WASM_GLOBAL_INDEX_I32) &&
54348139ebcSWouter van Oortmerssen       !RelEntry.Symbol->isGlobal()) {
544492f7529SSam Clegg     assert(GOTIndices.count(RelEntry.Symbol) > 0 && "symbol not found in GOT index space");
545492f7529SSam Clegg     return GOTIndices[RelEntry.Symbol];
546492f7529SSam Clegg   }
547492f7529SSam Clegg 
54860ec3034SSam Clegg   switch (RelEntry.Type) {
5492a7cac93SSam Clegg   case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
550d1152a26SSam Clegg   case wasm::R_WASM_TABLE_INDEX_SLEB:
551d1152a26SSam Clegg   case wasm::R_WASM_TABLE_INDEX_I32: {
552f9edbe95SSam Clegg     // Provisional value is table address of the resolved symbol itself
55318c56a07SHeejin Ahn     const MCSymbolWasm *Sym = resolveSymbol(*RelEntry.Symbol);
554f9edbe95SSam Clegg     assert(Sym->isFunction());
555f9edbe95SSam Clegg     return TableIndices[Sym];
556f9edbe95SSam Clegg   }
557d1152a26SSam Clegg   case wasm::R_WASM_TYPE_INDEX_LEB:
5586c899ba6SSam Clegg     // Provisional value is same as the index
55960ec3034SSam Clegg     return getRelocationIndexValue(RelEntry);
560d1152a26SSam Clegg   case wasm::R_WASM_FUNCTION_INDEX_LEB:
561d1152a26SSam Clegg   case wasm::R_WASM_GLOBAL_INDEX_LEB:
56248139ebcSWouter van Oortmerssen   case wasm::R_WASM_GLOBAL_INDEX_I32:
563d1152a26SSam Clegg   case wasm::R_WASM_EVENT_INDEX_LEB:
564da419bdbSHeejin Ahn     // Provisional value is function/global/event Wasm index
565492f7529SSam Clegg     assert(WasmIndices.count(RelEntry.Symbol) > 0 && "symbol not found in wasm index space");
5666c899ba6SSam Clegg     return WasmIndices[RelEntry.Symbol];
567d1152a26SSam Clegg   case wasm::R_WASM_FUNCTION_OFFSET_I32:
568d1152a26SSam Clegg   case wasm::R_WASM_SECTION_OFFSET_I32: {
5696a31a0d6SSam Clegg     const auto &Section =
5706a31a0d6SSam Clegg         static_cast<const MCSectionWasm &>(RelEntry.Symbol->getSection());
5716a31a0d6SSam Clegg     return Section.getSectionOffset() + RelEntry.Addend;
5726a31a0d6SSam Clegg   }
573d1152a26SSam Clegg   case wasm::R_WASM_MEMORY_ADDR_LEB:
574d1152a26SSam Clegg   case wasm::R_WASM_MEMORY_ADDR_I32:
5752a7cac93SSam Clegg   case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
576d1152a26SSam Clegg   case wasm::R_WASM_MEMORY_ADDR_SLEB: {
577f9edbe95SSam Clegg     // Provisional value is address of the global
57818c56a07SHeejin Ahn     const MCSymbolWasm *Sym = resolveSymbol(*RelEntry.Symbol);
579270ed1b3SSam Clegg     // For undefined symbols, use zero
580cd65f698SSam Clegg     if (!Sym->isDefined())
581270ed1b3SSam Clegg       return 0;
5826c899ba6SSam Clegg     const wasm::WasmDataReference &Ref = DataLocations[Sym];
5836c899ba6SSam Clegg     const WasmDataSegment &Segment = DataSegments[Ref.Segment];
584d934cb88SDan Gohman     // Ignore overflow. LLVM allows address arithmetic to silently wrap.
5856c899ba6SSam Clegg     return Segment.Offset + Ref.Offset + RelEntry.Addend;
58660ec3034SSam Clegg   }
58760ec3034SSam Clegg   default:
58860ec3034SSam Clegg     llvm_unreachable("invalid relocation type");
58960ec3034SSam Clegg   }
590d934cb88SDan Gohman }
591d934cb88SDan Gohman 
592759631c7SSam Clegg static void addData(SmallVectorImpl<char> &DataBytes,
59363ebb813SSam Clegg                     MCSectionWasm &DataSection) {
5947d1ff446SFangrui Song   LLVM_DEBUG(errs() << "addData: " << DataSection.getName() << "\n");
595759631c7SSam Clegg 
59663ebb813SSam Clegg   DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
59763ebb813SSam Clegg 
598759631c7SSam Clegg   for (const MCFragment &Frag : DataSection) {
599759631c7SSam Clegg     if (Frag.hasInstructions())
600759631c7SSam Clegg       report_fatal_error("only data supported in data sections");
601759631c7SSam Clegg 
602759631c7SSam Clegg     if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
603759631c7SSam Clegg       if (Align->getValueSize() != 1)
604759631c7SSam Clegg         report_fatal_error("only byte values supported for alignment");
605759631c7SSam Clegg       // If nops are requested, use zeros, as this is the data section.
606759631c7SSam Clegg       uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
607f208f631SHeejin Ahn       uint64_t Size =
608f208f631SHeejin Ahn           std::min<uint64_t>(alignTo(DataBytes.size(), Align->getAlignment()),
609f208f631SHeejin Ahn                              DataBytes.size() + Align->getMaxBytesToEmit());
610759631c7SSam Clegg       DataBytes.resize(Size, Value);
611759631c7SSam Clegg     } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
612588fad4dSNirav Dave       int64_t NumValues;
613588fad4dSNirav Dave       if (!Fill->getNumValues().evaluateAsAbsolute(NumValues))
614d707c370SRafael Espindola         llvm_unreachable("The fill should be an assembler constant");
615588fad4dSNirav Dave       DataBytes.insert(DataBytes.end(), Fill->getValueSize() * NumValues,
616588fad4dSNirav Dave                        Fill->getValue());
61724faf859SHeejin Ahn     } else if (auto *LEB = dyn_cast<MCLEBFragment>(&Frag)) {
61824faf859SHeejin Ahn       const SmallVectorImpl<char> &Contents = LEB->getContents();
61924faf859SHeejin Ahn       DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
620759631c7SSam Clegg     } else {
621759631c7SSam Clegg       const auto &DataFrag = cast<MCDataFragment>(Frag);
622759631c7SSam Clegg       const SmallVectorImpl<char> &Contents = DataFrag.getContents();
623759631c7SSam Clegg       DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
624759631c7SSam Clegg     }
625759631c7SSam Clegg   }
626759631c7SSam Clegg 
627d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
628759631c7SSam Clegg }
629759631c7SSam Clegg 
63060ec3034SSam Clegg uint32_t
63160ec3034SSam Clegg WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
632d1152a26SSam Clegg   if (RelEntry.Type == wasm::R_WASM_TYPE_INDEX_LEB) {
633b7787fd0SSam Clegg     if (!TypeIndices.count(RelEntry.Symbol))
634b7787fd0SSam Clegg       report_fatal_error("symbol not found in type index space: " +
635b7787fd0SSam Clegg                          RelEntry.Symbol->getName());
636acd7d2b0SSam Clegg     return TypeIndices[RelEntry.Symbol];
637acd7d2b0SSam Clegg   }
63860ec3034SSam Clegg 
63925d8e68bSSam Clegg   return RelEntry.Symbol->getIndex();
640acd7d2b0SSam Clegg }
641acd7d2b0SSam Clegg 
642d934cb88SDan Gohman // Apply the portions of the relocation records that we can handle ourselves
643d934cb88SDan Gohman // directly.
644acd7d2b0SSam Clegg void WasmObjectWriter::applyRelocations(
645acd7d2b0SSam Clegg     ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
646f17b149dSPeter Collingbourne   auto &Stream = static_cast<raw_pwrite_stream &>(W.OS);
647d934cb88SDan Gohman   for (const WasmRelocationEntry &RelEntry : Relocations) {
648d934cb88SDan Gohman     uint64_t Offset = ContentsOffset +
649d934cb88SDan Gohman                       RelEntry.FixupSection->getSectionOffset() +
650d934cb88SDan Gohman                       RelEntry.Offset;
651d934cb88SDan Gohman 
652d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
65360ec3034SSam Clegg     uint32_t Value = getProvisionalValue(RelEntry);
65460ec3034SSam Clegg 
655acd7d2b0SSam Clegg     switch (RelEntry.Type) {
656d1152a26SSam Clegg     case wasm::R_WASM_FUNCTION_INDEX_LEB:
657d1152a26SSam Clegg     case wasm::R_WASM_TYPE_INDEX_LEB:
658d1152a26SSam Clegg     case wasm::R_WASM_GLOBAL_INDEX_LEB:
659d1152a26SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_LEB:
660d1152a26SSam Clegg     case wasm::R_WASM_EVENT_INDEX_LEB:
66118c56a07SHeejin Ahn       writePatchableLEB(Stream, Value, Offset);
662d934cb88SDan Gohman       break;
663d1152a26SSam Clegg     case wasm::R_WASM_TABLE_INDEX_I32:
664d1152a26SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_I32:
665d1152a26SSam Clegg     case wasm::R_WASM_FUNCTION_OFFSET_I32:
666d1152a26SSam Clegg     case wasm::R_WASM_SECTION_OFFSET_I32:
66748139ebcSWouter van Oortmerssen     case wasm::R_WASM_GLOBAL_INDEX_I32:
66818c56a07SHeejin Ahn       writeI32(Stream, Value, Offset);
669d934cb88SDan Gohman       break;
670d1152a26SSam Clegg     case wasm::R_WASM_TABLE_INDEX_SLEB:
6712a7cac93SSam Clegg     case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
672d1152a26SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_SLEB:
6732a7cac93SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
67418c56a07SHeejin Ahn       writePatchableSLEB(Stream, Value, Offset);
67560ec3034SSam Clegg       break;
676d934cb88SDan Gohman     default:
6779d24fb7fSSam Clegg       llvm_unreachable("invalid relocation type");
678d934cb88SDan Gohman     }
679d934cb88SDan Gohman   }
68018eafb6cSDan Gohman }
68118eafb6cSDan Gohman 
682da419bdbSHeejin Ahn void WasmObjectWriter::writeTypeSection(ArrayRef<WasmSignature> Signatures) {
683da419bdbSHeejin Ahn   if (Signatures.empty())
6849e15f359SSam Clegg     return;
6859e15f359SSam Clegg 
6869e15f359SSam Clegg   SectionBookkeeping Section;
6879e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_TYPE);
6889e15f359SSam Clegg 
689da419bdbSHeejin Ahn   encodeULEB128(Signatures.size(), W.OS);
6909e15f359SSam Clegg 
691da419bdbSHeejin Ahn   for (const WasmSignature &Sig : Signatures) {
692f17b149dSPeter Collingbourne     W.OS << char(wasm::WASM_TYPE_FUNC);
693da419bdbSHeejin Ahn     encodeULEB128(Sig.Params.size(), W.OS);
694da419bdbSHeejin Ahn     for (wasm::ValType Ty : Sig.Params)
6959e15f359SSam Clegg       writeValueType(Ty);
696da419bdbSHeejin Ahn     encodeULEB128(Sig.Returns.size(), W.OS);
697da419bdbSHeejin Ahn     for (wasm::ValType Ty : Sig.Returns)
6989e15f359SSam Clegg       writeValueType(Ty);
6999e15f359SSam Clegg   }
7009e15f359SSam Clegg 
7019e15f359SSam Clegg   endSection(Section);
7029e15f359SSam Clegg }
7039e15f359SSam Clegg 
7048defa952SSam Clegg void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports,
705f950b24aSSam Clegg                                           uint32_t DataSize,
706f950b24aSSam Clegg                                           uint32_t NumElements) {
7079e15f359SSam Clegg   if (Imports.empty())
7089e15f359SSam Clegg     return;
7099e15f359SSam Clegg 
710f950b24aSSam Clegg   uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
711f950b24aSSam Clegg 
7129e15f359SSam Clegg   SectionBookkeeping Section;
7139e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_IMPORT);
7149e15f359SSam Clegg 
715f17b149dSPeter Collingbourne   encodeULEB128(Imports.size(), W.OS);
7168defa952SSam Clegg   for (const wasm::WasmImport &Import : Imports) {
7178defa952SSam Clegg     writeString(Import.Module);
7188defa952SSam Clegg     writeString(Import.Field);
719f17b149dSPeter Collingbourne     W.OS << char(Import.Kind);
7209e15f359SSam Clegg 
7219e15f359SSam Clegg     switch (Import.Kind) {
7229e15f359SSam Clegg     case wasm::WASM_EXTERNAL_FUNCTION:
723f17b149dSPeter Collingbourne       encodeULEB128(Import.SigIndex, W.OS);
7249e15f359SSam Clegg       break;
7259e15f359SSam Clegg     case wasm::WASM_EXTERNAL_GLOBAL:
726f17b149dSPeter Collingbourne       W.OS << char(Import.Global.Type);
727f17b149dSPeter Collingbourne       W.OS << char(Import.Global.Mutable ? 1 : 0);
7289e15f359SSam Clegg       break;
729f950b24aSSam Clegg     case wasm::WASM_EXTERNAL_MEMORY:
730f17b149dSPeter Collingbourne       encodeULEB128(0, W.OS);        // flags
731f17b149dSPeter Collingbourne       encodeULEB128(NumPages, W.OS); // initial
732f950b24aSSam Clegg       break;
733f950b24aSSam Clegg     case wasm::WASM_EXTERNAL_TABLE:
734f17b149dSPeter Collingbourne       W.OS << char(Import.Table.ElemType);
735f17b149dSPeter Collingbourne       encodeULEB128(0, W.OS);           // flags
736f17b149dSPeter Collingbourne       encodeULEB128(NumElements, W.OS); // initial
737f950b24aSSam Clegg       break;
738da419bdbSHeejin Ahn     case wasm::WASM_EXTERNAL_EVENT:
739da419bdbSHeejin Ahn       encodeULEB128(Import.Event.Attribute, W.OS);
740da419bdbSHeejin Ahn       encodeULEB128(Import.Event.SigIndex, W.OS);
741da419bdbSHeejin Ahn       break;
7429e15f359SSam Clegg     default:
7439e15f359SSam Clegg       llvm_unreachable("unsupported import kind");
7449e15f359SSam Clegg     }
7459e15f359SSam Clegg   }
7469e15f359SSam Clegg 
7479e15f359SSam Clegg   endSection(Section);
7489e15f359SSam Clegg }
7499e15f359SSam Clegg 
750457fb0b4SSam Clegg void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
7519e15f359SSam Clegg   if (Functions.empty())
7529e15f359SSam Clegg     return;
7539e15f359SSam Clegg 
7549e15f359SSam Clegg   SectionBookkeeping Section;
7559e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_FUNCTION);
7569e15f359SSam Clegg 
757f17b149dSPeter Collingbourne   encodeULEB128(Functions.size(), W.OS);
7589e15f359SSam Clegg   for (const WasmFunction &Func : Functions)
759da419bdbSHeejin Ahn     encodeULEB128(Func.SigIndex, W.OS);
7609e15f359SSam Clegg 
7619e15f359SSam Clegg   endSection(Section);
7629e15f359SSam Clegg }
7639e15f359SSam Clegg 
764da419bdbSHeejin Ahn void WasmObjectWriter::writeEventSection(ArrayRef<wasm::WasmEventType> Events) {
765da419bdbSHeejin Ahn   if (Events.empty())
766da419bdbSHeejin Ahn     return;
767da419bdbSHeejin Ahn 
768da419bdbSHeejin Ahn   SectionBookkeeping Section;
769da419bdbSHeejin Ahn   startSection(Section, wasm::WASM_SEC_EVENT);
770da419bdbSHeejin Ahn 
771da419bdbSHeejin Ahn   encodeULEB128(Events.size(), W.OS);
772da419bdbSHeejin Ahn   for (const wasm::WasmEventType &Event : Events) {
773da419bdbSHeejin Ahn     encodeULEB128(Event.Attribute, W.OS);
774da419bdbSHeejin Ahn     encodeULEB128(Event.SigIndex, W.OS);
775da419bdbSHeejin Ahn   }
776da419bdbSHeejin Ahn 
777da419bdbSHeejin Ahn   endSection(Section);
778da419bdbSHeejin Ahn }
779da419bdbSHeejin Ahn 
7808defa952SSam Clegg void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) {
7819e15f359SSam Clegg   if (Exports.empty())
7829e15f359SSam Clegg     return;
7839e15f359SSam Clegg 
7849e15f359SSam Clegg   SectionBookkeeping Section;
7859e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_EXPORT);
7869e15f359SSam Clegg 
787f17b149dSPeter Collingbourne   encodeULEB128(Exports.size(), W.OS);
7888defa952SSam Clegg   for (const wasm::WasmExport &Export : Exports) {
7898defa952SSam Clegg     writeString(Export.Name);
790f17b149dSPeter Collingbourne     W.OS << char(Export.Kind);
791f17b149dSPeter Collingbourne     encodeULEB128(Export.Index, W.OS);
7929e15f359SSam Clegg   }
7939e15f359SSam Clegg 
7949e15f359SSam Clegg   endSection(Section);
7959e15f359SSam Clegg }
7969e15f359SSam Clegg 
797457fb0b4SSam Clegg void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
7989e15f359SSam Clegg   if (TableElems.empty())
7999e15f359SSam Clegg     return;
8009e15f359SSam Clegg 
8019e15f359SSam Clegg   SectionBookkeeping Section;
8029e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_ELEM);
8039e15f359SSam Clegg 
804f17b149dSPeter Collingbourne   encodeULEB128(1, W.OS); // number of "segments"
805f17b149dSPeter Collingbourne   encodeULEB128(0, W.OS); // the table index
8069e15f359SSam Clegg 
8079e15f359SSam Clegg   // init expr for starting offset
808f17b149dSPeter Collingbourne   W.OS << char(wasm::WASM_OPCODE_I32_CONST);
80918c56a07SHeejin Ahn   encodeSLEB128(InitialTableOffset, W.OS);
810f17b149dSPeter Collingbourne   W.OS << char(wasm::WASM_OPCODE_END);
8119e15f359SSam Clegg 
812f17b149dSPeter Collingbourne   encodeULEB128(TableElems.size(), W.OS);
8139e15f359SSam Clegg   for (uint32_t Elem : TableElems)
814f17b149dSPeter Collingbourne     encodeULEB128(Elem, W.OS);
8159e15f359SSam Clegg 
8169e15f359SSam Clegg   endSection(Section);
8179e15f359SSam Clegg }
8189e15f359SSam Clegg 
819fef8de66SThomas Lively void WasmObjectWriter::writeDataCountSection() {
820fef8de66SThomas Lively   if (DataSegments.empty())
821fef8de66SThomas Lively     return;
822fef8de66SThomas Lively 
823fef8de66SThomas Lively   SectionBookkeeping Section;
824fef8de66SThomas Lively   startSection(Section, wasm::WASM_SEC_DATACOUNT);
825fef8de66SThomas Lively   encodeULEB128(DataSegments.size(), W.OS);
826fef8de66SThomas Lively   endSection(Section);
827fef8de66SThomas Lively }
828fef8de66SThomas Lively 
829457fb0b4SSam Clegg void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
830457fb0b4SSam Clegg                                         const MCAsmLayout &Layout,
831457fb0b4SSam Clegg                                         ArrayRef<WasmFunction> Functions) {
8329e15f359SSam Clegg   if (Functions.empty())
8339e15f359SSam Clegg     return;
8349e15f359SSam Clegg 
8359e15f359SSam Clegg   SectionBookkeeping Section;
8369e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_CODE);
8376f08c84aSSam Clegg   CodeSectionIndex = Section.Index;
8389e15f359SSam Clegg 
839f17b149dSPeter Collingbourne   encodeULEB128(Functions.size(), W.OS);
8409e15f359SSam Clegg 
8419e15f359SSam Clegg   for (const WasmFunction &Func : Functions) {
842fe6414b0SSam Clegg     auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
8439e15f359SSam Clegg 
8449e15f359SSam Clegg     int64_t Size = 0;
8459e15f359SSam Clegg     if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
8469e15f359SSam Clegg       report_fatal_error(".size expression must be evaluatable");
8479e15f359SSam Clegg 
848f17b149dSPeter Collingbourne     encodeULEB128(Size, W.OS);
849f17b149dSPeter Collingbourne     FuncSection.setSectionOffset(W.OS.tell() - Section.ContentsOffset);
850f17b149dSPeter Collingbourne     Asm.writeSectionData(W.OS, &FuncSection, Layout);
8519e15f359SSam Clegg   }
8529e15f359SSam Clegg 
8539e15f359SSam Clegg   // Apply fixups.
854acd7d2b0SSam Clegg   applyRelocations(CodeRelocations, Section.ContentsOffset);
8559e15f359SSam Clegg 
8569e15f359SSam Clegg   endSection(Section);
8579e15f359SSam Clegg }
8589e15f359SSam Clegg 
8596c899ba6SSam Clegg void WasmObjectWriter::writeDataSection() {
8606c899ba6SSam Clegg   if (DataSegments.empty())
8617c395943SSam Clegg     return;
8629e15f359SSam Clegg 
8639e15f359SSam Clegg   SectionBookkeeping Section;
8649e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_DATA);
8656f08c84aSSam Clegg   DataSectionIndex = Section.Index;
8669e15f359SSam Clegg 
867f17b149dSPeter Collingbourne   encodeULEB128(DataSegments.size(), W.OS); // count
8687c395943SSam Clegg 
8696c899ba6SSam Clegg   for (const WasmDataSegment &Segment : DataSegments) {
8702e150409SThomas Lively     encodeULEB128(Segment.InitFlags, W.OS); // flags
8712e150409SThomas Lively     if (Segment.InitFlags & wasm::WASM_SEGMENT_HAS_MEMINDEX)
872f17b149dSPeter Collingbourne       encodeULEB128(0, W.OS); // memory index
8732e150409SThomas Lively     if ((Segment.InitFlags & wasm::WASM_SEGMENT_IS_PASSIVE) == 0) {
874f17b149dSPeter Collingbourne       W.OS << char(wasm::WASM_OPCODE_I32_CONST);
875f17b149dSPeter Collingbourne       encodeSLEB128(Segment.Offset, W.OS); // offset
876f17b149dSPeter Collingbourne       W.OS << char(wasm::WASM_OPCODE_END);
8772e150409SThomas Lively     }
878f17b149dSPeter Collingbourne     encodeULEB128(Segment.Data.size(), W.OS); // size
879f17b149dSPeter Collingbourne     Segment.Section->setSectionOffset(W.OS.tell() - Section.ContentsOffset);
880f17b149dSPeter Collingbourne     W.OS << Segment.Data; // data
8817c395943SSam Clegg   }
8829e15f359SSam Clegg 
8839e15f359SSam Clegg   // Apply fixups.
8847c395943SSam Clegg   applyRelocations(DataRelocations, Section.ContentsOffset);
8859e15f359SSam Clegg 
8869e15f359SSam Clegg   endSection(Section);
8879e15f359SSam Clegg }
8889e15f359SSam Clegg 
8896f08c84aSSam Clegg void WasmObjectWriter::writeRelocSection(
8906f08c84aSSam Clegg     uint32_t SectionIndex, StringRef Name,
891f77dc2a8SSam Clegg     std::vector<WasmRelocationEntry> &Relocs) {
8929e15f359SSam Clegg   // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
8939e15f359SSam Clegg   // for descriptions of the reloc sections.
8949e15f359SSam Clegg 
895f77dc2a8SSam Clegg   if (Relocs.empty())
8969e15f359SSam Clegg     return;
8979e15f359SSam Clegg 
898f77dc2a8SSam Clegg   // First, ensure the relocations are sorted in offset order.  In general they
899f77dc2a8SSam Clegg   // should already be sorted since `recordRelocation` is called in offset
900f77dc2a8SSam Clegg   // order, but for the code section we combine many MC sections into single
901f77dc2a8SSam Clegg   // wasm section, and this order is determined by the order of Asm.Symbols()
902f77dc2a8SSam Clegg   // not the sections order.
903efd94c56SFangrui Song   llvm::stable_sort(
904efd94c56SFangrui Song       Relocs, [](const WasmRelocationEntry &A, const WasmRelocationEntry &B) {
905f77dc2a8SSam Clegg         return (A.Offset + A.FixupSection->getSectionOffset()) <
906f77dc2a8SSam Clegg                (B.Offset + B.FixupSection->getSectionOffset());
907f77dc2a8SSam Clegg       });
908f77dc2a8SSam Clegg 
9099e15f359SSam Clegg   SectionBookkeeping Section;
9106f08c84aSSam Clegg   startCustomSection(Section, std::string("reloc.") + Name.str());
9119e15f359SSam Clegg 
912f17b149dSPeter Collingbourne   encodeULEB128(SectionIndex, W.OS);
913f77dc2a8SSam Clegg   encodeULEB128(Relocs.size(), W.OS);
914f77dc2a8SSam Clegg   for (const WasmRelocationEntry &RelEntry : Relocs) {
915f208f631SHeejin Ahn     uint64_t Offset =
916f208f631SHeejin Ahn         RelEntry.Offset + RelEntry.FixupSection->getSectionOffset();
9176f08c84aSSam Clegg     uint32_t Index = getRelocationIndexValue(RelEntry);
9189e15f359SSam Clegg 
919f17b149dSPeter Collingbourne     W.OS << char(RelEntry.Type);
920f17b149dSPeter Collingbourne     encodeULEB128(Offset, W.OS);
921f17b149dSPeter Collingbourne     encodeULEB128(Index, W.OS);
9226f08c84aSSam Clegg     if (RelEntry.hasAddend())
923f17b149dSPeter Collingbourne       encodeSLEB128(RelEntry.Addend, W.OS);
9249e15f359SSam Clegg   }
9259e15f359SSam Clegg 
9269e15f359SSam Clegg   endSection(Section);
9279e15f359SSam Clegg }
9289e15f359SSam Clegg 
9296a31a0d6SSam Clegg void WasmObjectWriter::writeCustomRelocSections() {
9306a31a0d6SSam Clegg   for (const auto &Sec : CustomSections) {
9316a31a0d6SSam Clegg     auto &Relocations = CustomSectionsRelocations[Sec.Section];
9326a31a0d6SSam Clegg     writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations);
9336a31a0d6SSam Clegg   }
9346a31a0d6SSam Clegg }
9356a31a0d6SSam Clegg 
9369e15f359SSam Clegg void WasmObjectWriter::writeLinkingMetaDataSection(
93786b4a09aSSam Clegg     ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
938ea7caceeSSam Clegg     ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
939ea7caceeSSam Clegg     const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) {
9409e15f359SSam Clegg   SectionBookkeeping Section;
9412322a937SSam Clegg   startCustomSection(Section, "linking");
942f17b149dSPeter Collingbourne   encodeULEB128(wasm::WasmMetadataVersion, W.OS);
9439e15f359SSam Clegg 
9446bb5a41fSSam Clegg   SectionBookkeeping SubSection;
9456c899ba6SSam Clegg   if (SymbolInfos.size() != 0) {
9466c899ba6SSam Clegg     startSection(SubSection, wasm::WASM_SYMBOL_TABLE);
947f17b149dSPeter Collingbourne     encodeULEB128(SymbolInfos.size(), W.OS);
9486c899ba6SSam Clegg     for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) {
949f17b149dSPeter Collingbourne       encodeULEB128(Sym.Kind, W.OS);
950f17b149dSPeter Collingbourne       encodeULEB128(Sym.Flags, W.OS);
9516c899ba6SSam Clegg       switch (Sym.Kind) {
9526c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_FUNCTION:
9536c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_GLOBAL:
954da419bdbSHeejin Ahn       case wasm::WASM_SYMBOL_TYPE_EVENT:
955f17b149dSPeter Collingbourne         encodeULEB128(Sym.ElementIndex, W.OS);
95629874ceaSDan Gohman         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0 ||
95729874ceaSDan Gohman             (Sym.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0)
9586c899ba6SSam Clegg           writeString(Sym.Name);
9596c899ba6SSam Clegg         break;
9606c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_DATA:
9616c899ba6SSam Clegg         writeString(Sym.Name);
9626c899ba6SSam Clegg         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) {
963f17b149dSPeter Collingbourne           encodeULEB128(Sym.DataRef.Segment, W.OS);
964f17b149dSPeter Collingbourne           encodeULEB128(Sym.DataRef.Offset, W.OS);
965f17b149dSPeter Collingbourne           encodeULEB128(Sym.DataRef.Size, W.OS);
9666c899ba6SSam Clegg         }
9676c899ba6SSam Clegg         break;
9686a31a0d6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_SECTION: {
9696a31a0d6SSam Clegg         const uint32_t SectionIndex =
9706a31a0d6SSam Clegg             CustomSections[Sym.ElementIndex].OutputIndex;
971f17b149dSPeter Collingbourne         encodeULEB128(SectionIndex, W.OS);
9726a31a0d6SSam Clegg         break;
9736a31a0d6SSam Clegg       }
9746c899ba6SSam Clegg       default:
9756c899ba6SSam Clegg         llvm_unreachable("unexpected kind");
9766c899ba6SSam Clegg       }
977b7787fd0SSam Clegg     }
978b7787fd0SSam Clegg     endSection(SubSection);
979b7787fd0SSam Clegg   }
9809e15f359SSam Clegg 
9816c899ba6SSam Clegg   if (DataSegments.size()) {
98263ebb813SSam Clegg     startSection(SubSection, wasm::WASM_SEGMENT_INFO);
983f17b149dSPeter Collingbourne     encodeULEB128(DataSegments.size(), W.OS);
9846c899ba6SSam Clegg     for (const WasmDataSegment &Segment : DataSegments) {
985d95ed959SSam Clegg       writeString(Segment.Name);
986f17b149dSPeter Collingbourne       encodeULEB128(Segment.Alignment, W.OS);
9872e150409SThomas Lively       encodeULEB128(Segment.LinkerFlags, W.OS);
98863ebb813SSam Clegg     }
989d95ed959SSam Clegg     endSection(SubSection);
990d95ed959SSam Clegg   }
991d95ed959SSam Clegg 
992bafe6902SSam Clegg   if (!InitFuncs.empty()) {
993bafe6902SSam Clegg     startSection(SubSection, wasm::WASM_INIT_FUNCS);
994f17b149dSPeter Collingbourne     encodeULEB128(InitFuncs.size(), W.OS);
995bafe6902SSam Clegg     for (auto &StartFunc : InitFuncs) {
996f17b149dSPeter Collingbourne       encodeULEB128(StartFunc.first, W.OS);  // priority
997f17b149dSPeter Collingbourne       encodeULEB128(StartFunc.second, W.OS); // function index
998bafe6902SSam Clegg     }
999bafe6902SSam Clegg     endSection(SubSection);
1000bafe6902SSam Clegg   }
1001bafe6902SSam Clegg 
1002ea7caceeSSam Clegg   if (Comdats.size()) {
1003ea7caceeSSam Clegg     startSection(SubSection, wasm::WASM_COMDAT_INFO);
1004f17b149dSPeter Collingbourne     encodeULEB128(Comdats.size(), W.OS);
1005ea7caceeSSam Clegg     for (const auto &C : Comdats) {
1006ea7caceeSSam Clegg       writeString(C.first);
1007f17b149dSPeter Collingbourne       encodeULEB128(0, W.OS); // flags for future use
1008f17b149dSPeter Collingbourne       encodeULEB128(C.second.size(), W.OS);
1009ea7caceeSSam Clegg       for (const WasmComdatEntry &Entry : C.second) {
1010f17b149dSPeter Collingbourne         encodeULEB128(Entry.Kind, W.OS);
1011f17b149dSPeter Collingbourne         encodeULEB128(Entry.Index, W.OS);
1012ea7caceeSSam Clegg       }
1013ea7caceeSSam Clegg     }
1014ea7caceeSSam Clegg     endSection(SubSection);
1015ea7caceeSSam Clegg   }
1016ea7caceeSSam Clegg 
10179e15f359SSam Clegg   endSection(Section);
10189e15f359SSam Clegg }
10199e15f359SSam Clegg 
1020cbda16ebSThomas Lively void WasmObjectWriter::writeCustomSection(WasmCustomSection &CustomSection,
1021cbda16ebSThomas Lively                                           const MCAssembler &Asm,
10226a31a0d6SSam Clegg                                           const MCAsmLayout &Layout) {
1023cfd44a2eSSam Clegg   SectionBookkeeping Section;
10246a31a0d6SSam Clegg   auto *Sec = CustomSection.Section;
10252322a937SSam Clegg   startCustomSection(Section, CustomSection.Name);
10266a31a0d6SSam Clegg 
1027f17b149dSPeter Collingbourne   Sec->setSectionOffset(W.OS.tell() - Section.ContentsOffset);
1028f17b149dSPeter Collingbourne   Asm.writeSectionData(W.OS, Sec, Layout);
10296a31a0d6SSam Clegg 
10306a31a0d6SSam Clegg   CustomSection.OutputContentsOffset = Section.ContentsOffset;
10316a31a0d6SSam Clegg   CustomSection.OutputIndex = Section.Index;
10326a31a0d6SSam Clegg 
1033cfd44a2eSSam Clegg   endSection(Section);
10346a31a0d6SSam Clegg 
10356a31a0d6SSam Clegg   // Apply fixups.
10364d57fbd0SSam Clegg   auto &Relocations = CustomSectionsRelocations[CustomSection.Section];
10374d57fbd0SSam Clegg   applyRelocations(Relocations, CustomSection.OutputContentsOffset);
10386a31a0d6SSam Clegg }
10396a31a0d6SSam Clegg 
10405e3d33a7SSam Clegg uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm &Symbol) {
10415e3d33a7SSam Clegg   assert(Symbol.isFunction());
10425e3d33a7SSam Clegg   assert(TypeIndices.count(&Symbol));
10435e3d33a7SSam Clegg   return TypeIndices[&Symbol];
10445e3d33a7SSam Clegg }
10455e3d33a7SSam Clegg 
1046da419bdbSHeejin Ahn uint32_t WasmObjectWriter::getEventType(const MCSymbolWasm &Symbol) {
1047da419bdbSHeejin Ahn   assert(Symbol.isEvent());
1048da419bdbSHeejin Ahn   assert(TypeIndices.count(&Symbol));
1049da419bdbSHeejin Ahn   return TypeIndices[&Symbol];
1050da419bdbSHeejin Ahn }
1051da419bdbSHeejin Ahn 
105238b12f5eSHeejin Ahn void WasmObjectWriter::registerFunctionType(const MCSymbolWasm &Symbol) {
10535e3d33a7SSam Clegg   assert(Symbol.isFunction());
10545e3d33a7SSam Clegg 
1055da419bdbSHeejin Ahn   WasmSignature S;
105618c56a07SHeejin Ahn   const MCSymbolWasm *ResolvedSym = resolveSymbol(Symbol);
105777a7a380SDerek Schuff   if (auto *Sig = ResolvedSym->getSignature()) {
1058da419bdbSHeejin Ahn     S.Returns = Sig->Returns;
1059da419bdbSHeejin Ahn     S.Params = Sig->Params;
106077a7a380SDerek Schuff   }
10615e3d33a7SSam Clegg 
1062da419bdbSHeejin Ahn   auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
10635e3d33a7SSam Clegg   if (Pair.second)
1064da419bdbSHeejin Ahn     Signatures.push_back(S);
10655e3d33a7SSam Clegg   TypeIndices[&Symbol] = Pair.first->second;
10665e3d33a7SSam Clegg 
1067d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "registerFunctionType: " << Symbol
1068d34e60caSNicola Zaghen                     << " new:" << Pair.second << "\n");
1069d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
10705e3d33a7SSam Clegg }
10715e3d33a7SSam Clegg 
107238b12f5eSHeejin Ahn void WasmObjectWriter::registerEventType(const MCSymbolWasm &Symbol) {
1073da419bdbSHeejin Ahn   assert(Symbol.isEvent());
1074da419bdbSHeejin Ahn 
1075da419bdbSHeejin Ahn   // TODO Currently we don't generate imported exceptions, but if we do, we
1076da419bdbSHeejin Ahn   // should have a way of infering types of imported exceptions.
1077da419bdbSHeejin Ahn   WasmSignature S;
1078da419bdbSHeejin Ahn   if (auto *Sig = Symbol.getSignature()) {
1079da419bdbSHeejin Ahn     S.Returns = Sig->Returns;
1080da419bdbSHeejin Ahn     S.Params = Sig->Params;
1081da419bdbSHeejin Ahn   }
1082da419bdbSHeejin Ahn 
1083da419bdbSHeejin Ahn   auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
1084da419bdbSHeejin Ahn   if (Pair.second)
1085da419bdbSHeejin Ahn     Signatures.push_back(S);
1086da419bdbSHeejin Ahn   TypeIndices[&Symbol] = Pair.first->second;
1087da419bdbSHeejin Ahn 
1088da419bdbSHeejin Ahn   LLVM_DEBUG(dbgs() << "registerEventType: " << Symbol << " new:" << Pair.second
1089da419bdbSHeejin Ahn                     << "\n");
1090da419bdbSHeejin Ahn   LLVM_DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
1091da419bdbSHeejin Ahn }
1092da419bdbSHeejin Ahn 
10934d57fbd0SSam Clegg static bool isInSymtab(const MCSymbolWasm &Sym) {
10943ea1c62cSSam Clegg   if (Sym.isUsedInReloc() || Sym.isUsedInInitArray())
10954d57fbd0SSam Clegg     return true;
10964d57fbd0SSam Clegg 
10974d57fbd0SSam Clegg   if (Sym.isComdat() && !Sym.isDefined())
10984d57fbd0SSam Clegg     return false;
10994d57fbd0SSam Clegg 
11003ea1c62cSSam Clegg   if (Sym.isTemporary())
11014d57fbd0SSam Clegg     return false;
11024d57fbd0SSam Clegg 
11034d57fbd0SSam Clegg   if (Sym.isSection())
11044d57fbd0SSam Clegg     return false;
11054d57fbd0SSam Clegg 
11064d57fbd0SSam Clegg   return true;
11074d57fbd0SSam Clegg }
11084d57fbd0SSam Clegg 
1109438390faSPeter Collingbourne uint64_t WasmObjectWriter::writeObject(MCAssembler &Asm,
111018eafb6cSDan Gohman                                        const MCAsmLayout &Layout) {
1111438390faSPeter Collingbourne   uint64_t StartOffset = W.OS.tell();
1112438390faSPeter Collingbourne 
1113d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
1114d934cb88SDan Gohman 
1115d934cb88SDan Gohman   // Collect information from the available symbols.
1116d934cb88SDan Gohman   SmallVector<WasmFunction, 4> Functions;
1117d934cb88SDan Gohman   SmallVector<uint32_t, 4> TableElems;
11188defa952SSam Clegg   SmallVector<wasm::WasmImport, 4> Imports;
11198defa952SSam Clegg   SmallVector<wasm::WasmExport, 4> Exports;
1120da419bdbSHeejin Ahn   SmallVector<wasm::WasmEventType, 1> Events;
11216c899ba6SSam Clegg   SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos;
1122bafe6902SSam Clegg   SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
1123ea7caceeSSam Clegg   std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
11247c395943SSam Clegg   uint32_t DataSize = 0;
1125d934cb88SDan Gohman 
1126f950b24aSSam Clegg   // For now, always emit the memory import, since loads and stores are not
1127f950b24aSSam Clegg   // valid without it. In the future, we could perhaps be more clever and omit
1128f950b24aSSam Clegg   // it if there are no loads or stores.
11298defa952SSam Clegg   wasm::WasmImport MemImport;
11301ed3a046SSam Clegg   MemImport.Module = "env";
11311ed3a046SSam Clegg   MemImport.Field = "__linear_memory";
1132f950b24aSSam Clegg   MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
1133f950b24aSSam Clegg   Imports.push_back(MemImport);
1134f950b24aSSam Clegg 
1135f950b24aSSam Clegg   // For now, always emit the table section, since indirect calls are not
1136f950b24aSSam Clegg   // valid without it. In the future, we could perhaps be more clever and omit
1137f950b24aSSam Clegg   // it if there are no indirect calls.
11388defa952SSam Clegg   wasm::WasmImport TableImport;
11391ed3a046SSam Clegg   TableImport.Module = "env";
11401ed3a046SSam Clegg   TableImport.Field = "__indirect_function_table";
1141f950b24aSSam Clegg   TableImport.Kind = wasm::WASM_EXTERNAL_TABLE;
11426a87ddacSThomas Lively   TableImport.Table.ElemType = wasm::WASM_TYPE_FUNCREF;
1143f950b24aSSam Clegg   Imports.push_back(TableImport);
1144f950b24aSSam Clegg 
1145da419bdbSHeejin Ahn   // Populate SignatureIndices, and Imports and WasmIndices for undefined
1146586320c0SNicholas Wilson   // symbols.  This must be done before populating WasmIndices for defined
1147586320c0SNicholas Wilson   // symbols.
114832ce5ca0SDan Gohman   for (const MCSymbol &S : Asm.symbols()) {
114932ce5ca0SDan Gohman     const auto &WS = static_cast<const MCSymbolWasm &>(S);
115032ce5ca0SDan Gohman 
115132ce5ca0SDan Gohman     // Register types for all functions, including those with private linkage
11529f3fe42eSSam Clegg     // (because wasm always needs a type signature).
115332ce5ca0SDan Gohman     if (WS.isFunction())
115432ce5ca0SDan Gohman       registerFunctionType(WS);
115532ce5ca0SDan Gohman 
1156da419bdbSHeejin Ahn     if (WS.isEvent())
1157da419bdbSHeejin Ahn       registerEventType(WS);
1158da419bdbSHeejin Ahn 
115932ce5ca0SDan Gohman     if (WS.isTemporary())
116032ce5ca0SDan Gohman       continue;
116132ce5ca0SDan Gohman 
116232ce5ca0SDan Gohman     // If the symbol is not defined in this translation unit, import it.
11636c899ba6SSam Clegg     if (!WS.isDefined() && !WS.isComdat()) {
11646c899ba6SSam Clegg       if (WS.isFunction()) {
11658defa952SSam Clegg         wasm::WasmImport Import;
1166f726e445SDan Gohman         Import.Module = WS.getImportModule();
1167f726e445SDan Gohman         Import.Field = WS.getImportName();
116832ce5ca0SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
11698defa952SSam Clegg         Import.SigIndex = getFunctionType(WS);
11706c899ba6SSam Clegg         Imports.push_back(Import);
1171492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
11726c899ba6SSam Clegg         WasmIndices[&WS] = NumFunctionImports++;
11736c899ba6SSam Clegg       } else if (WS.isGlobal()) {
117415f349f7SNicholas Wilson         if (WS.isWeak())
117515f349f7SNicholas Wilson           report_fatal_error("undefined global symbol cannot be weak");
117615f349f7SNicholas Wilson 
11776c899ba6SSam Clegg         wasm::WasmImport Import;
1178f726e445SDan Gohman         Import.Field = WS.getImportName();
117932ce5ca0SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1180492f7529SSam Clegg         Import.Module = WS.getImportModule();
11816c899ba6SSam Clegg         Import.Global = WS.getGlobalType();
11826c899ba6SSam Clegg         Imports.push_back(Import);
1183492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
11846c899ba6SSam Clegg         WasmIndices[&WS] = NumGlobalImports++;
1185da419bdbSHeejin Ahn       } else if (WS.isEvent()) {
1186da419bdbSHeejin Ahn         if (WS.isWeak())
1187da419bdbSHeejin Ahn           report_fatal_error("undefined event symbol cannot be weak");
1188da419bdbSHeejin Ahn 
1189da419bdbSHeejin Ahn         wasm::WasmImport Import;
1190f726e445SDan Gohman         Import.Module = WS.getImportModule();
1191f726e445SDan Gohman         Import.Field = WS.getImportName();
1192da419bdbSHeejin Ahn         Import.Kind = wasm::WASM_EXTERNAL_EVENT;
1193da419bdbSHeejin Ahn         Import.Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
1194da419bdbSHeejin Ahn         Import.Event.SigIndex = getEventType(WS);
1195da419bdbSHeejin Ahn         Imports.push_back(Import);
1196492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
1197da419bdbSHeejin Ahn         WasmIndices[&WS] = NumEventImports++;
119832ce5ca0SDan Gohman       }
119932ce5ca0SDan Gohman     }
120032ce5ca0SDan Gohman   }
120132ce5ca0SDan Gohman 
1202492f7529SSam Clegg   // Add imports for GOT globals
1203492f7529SSam Clegg   for (const MCSymbol &S : Asm.symbols()) {
1204492f7529SSam Clegg     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1205492f7529SSam Clegg     if (WS.isUsedInGOT()) {
1206492f7529SSam Clegg       wasm::WasmImport Import;
1207492f7529SSam Clegg       if (WS.isFunction())
1208492f7529SSam Clegg         Import.Module = "GOT.func";
1209492f7529SSam Clegg       else
1210492f7529SSam Clegg         Import.Module = "GOT.mem";
1211492f7529SSam Clegg       Import.Field = WS.getName();
1212492f7529SSam Clegg       Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1213492f7529SSam Clegg       Import.Global = {wasm::WASM_TYPE_I32, true};
1214492f7529SSam Clegg       Imports.push_back(Import);
1215492f7529SSam Clegg       assert(GOTIndices.count(&WS) == 0);
1216492f7529SSam Clegg       GOTIndices[&WS] = NumGlobalImports++;
1217492f7529SSam Clegg     }
1218492f7529SSam Clegg   }
1219492f7529SSam Clegg 
12204d57fbd0SSam Clegg   // Populate DataSegments and CustomSections, which must be done before
12214d57fbd0SSam Clegg   // populating DataLocations.
1222759631c7SSam Clegg   for (MCSection &Sec : Asm) {
1223759631c7SSam Clegg     auto &Section = static_cast<MCSectionWasm &>(Sec);
12247d1ff446SFangrui Song     StringRef SectionName = Section.getName();
1225759631c7SSam Clegg 
1226bafe6902SSam Clegg     // .init_array sections are handled specially elsewhere.
12274d57fbd0SSam Clegg     if (SectionName.startswith(".init_array"))
1228bafe6902SSam Clegg       continue;
1229bafe6902SSam Clegg 
12304d57fbd0SSam Clegg     // Code is handled separately
12314d57fbd0SSam Clegg     if (Section.getKind().isText())
12324d57fbd0SSam Clegg       continue;
12334d57fbd0SSam Clegg 
12344d57fbd0SSam Clegg     if (Section.isWasmData()) {
1235329e76d5SSam Clegg       uint32_t SegmentIndex = DataSegments.size();
1236759631c7SSam Clegg       DataSize = alignTo(DataSize, Section.getAlignment());
1237759631c7SSam Clegg       DataSegments.emplace_back();
1238759631c7SSam Clegg       WasmDataSegment &Segment = DataSegments.back();
12394d57fbd0SSam Clegg       Segment.Name = SectionName;
12409b49f36aSSimon Pilgrim       Segment.InitFlags =
12419b49f36aSSimon Pilgrim           Section.getPassive() ? (uint32_t)wasm::WASM_SEGMENT_IS_PASSIVE : 0;
1242759631c7SSam Clegg       Segment.Offset = DataSize;
1243759631c7SSam Clegg       Segment.Section = &Section;
124463ebb813SSam Clegg       addData(Segment.Data, Section);
124556c587adSSam Clegg       Segment.Alignment = Log2_32(Section.getAlignment());
12462e150409SThomas Lively       Segment.LinkerFlags = 0;
1247759631c7SSam Clegg       DataSize += Segment.Data.size();
12486c899ba6SSam Clegg       Section.setSegmentIndex(SegmentIndex);
1249ea7caceeSSam Clegg 
1250ea7caceeSSam Clegg       if (const MCSymbolWasm *C = Section.getGroup()) {
1251ea7caceeSSam Clegg         Comdats[C->getName()].emplace_back(
1252329e76d5SSam Clegg             WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
1253ea7caceeSSam Clegg       }
12544d57fbd0SSam Clegg     } else {
12554d57fbd0SSam Clegg       // Create custom sections
12564d57fbd0SSam Clegg       assert(Sec.getKind().isMetadata());
12574d57fbd0SSam Clegg 
12584d57fbd0SSam Clegg       StringRef Name = SectionName;
12594d57fbd0SSam Clegg 
12604d57fbd0SSam Clegg       // For user-defined custom sections, strip the prefix
12614d57fbd0SSam Clegg       if (Name.startswith(".custom_section."))
12624d57fbd0SSam Clegg         Name = Name.substr(strlen(".custom_section."));
12634d57fbd0SSam Clegg 
12644d57fbd0SSam Clegg       MCSymbol *Begin = Sec.getBeginSymbol();
1265fb807d4dSSam Clegg       if (Begin) {
12664d57fbd0SSam Clegg         WasmIndices[cast<MCSymbolWasm>(Begin)] = CustomSections.size();
1267b210c64bSSam Clegg         if (SectionName != Begin->getName())
1268fb807d4dSSam Clegg           report_fatal_error("section name and begin symbol should match: " +
1269b210c64bSSam Clegg                              Twine(SectionName));
1270fb807d4dSSam Clegg       }
1271cbda16ebSThomas Lively 
1272f6f4f843SThomas Lively       // Separate out the producers and target features sections
1273cbda16ebSThomas Lively       if (Name == "producers") {
12740eaee545SJonas Devlieghere         ProducersSection = std::make_unique<WasmCustomSection>(Name, &Section);
1275cbda16ebSThomas Lively         continue;
1276cbda16ebSThomas Lively       }
1277f6f4f843SThomas Lively       if (Name == "target_features") {
1278f6f4f843SThomas Lively         TargetFeaturesSection =
12790eaee545SJonas Devlieghere             std::make_unique<WasmCustomSection>(Name, &Section);
1280f6f4f843SThomas Lively         continue;
1281f6f4f843SThomas Lively       }
1282cbda16ebSThomas Lively 
12834d57fbd0SSam Clegg       CustomSections.emplace_back(Name, &Section);
1284759631c7SSam Clegg     }
12856a31a0d6SSam Clegg   }
12866a31a0d6SSam Clegg 
1287586320c0SNicholas Wilson   // Populate WasmIndices and DataLocations for defined symbols.
1288d934cb88SDan Gohman   for (const MCSymbol &S : Asm.symbols()) {
1289d934cb88SDan Gohman     // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1290d934cb88SDan Gohman     // or used in relocations.
1291d934cb88SDan Gohman     if (S.isTemporary() && S.getName().empty())
1292d934cb88SDan Gohman       continue;
1293b7787fd0SSam Clegg 
1294d934cb88SDan Gohman     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1295d34e60caSNicola Zaghen     LLVM_DEBUG(
1296d34e60caSNicola Zaghen         dbgs() << "MCSymbol: " << toString(WS.getType()) << " '" << S << "'"
1297d34e60caSNicola Zaghen                << " isDefined=" << S.isDefined() << " isExternal="
1298d34e60caSNicola Zaghen                << S.isExternal() << " isTemporary=" << S.isTemporary()
1299d34e60caSNicola Zaghen                << " isWeak=" << WS.isWeak() << " isHidden=" << WS.isHidden()
1300b7787fd0SSam Clegg                << " isVariable=" << WS.isVariable() << "\n");
1301b7787fd0SSam Clegg 
13025e3d33a7SSam Clegg     if (WS.isVariable())
13035e3d33a7SSam Clegg       continue;
13046c899ba6SSam Clegg     if (WS.isComdat() && !WS.isDefined())
13056c899ba6SSam Clegg       continue;
1306b7787fd0SSam Clegg 
1307d934cb88SDan Gohman     if (WS.isFunction()) {
13086c899ba6SSam Clegg       unsigned Index;
1309cd65f698SSam Clegg       if (WS.isDefined()) {
1310b7787fd0SSam Clegg         if (WS.getOffset() != 0)
1311b7787fd0SSam Clegg           report_fatal_error(
1312b7787fd0SSam Clegg               "function sections must contain one function each");
1313b7787fd0SSam Clegg 
131418c56a07SHeejin Ahn         if (WS.getSize() == nullptr)
1315b7787fd0SSam Clegg           report_fatal_error(
1316b7787fd0SSam Clegg               "function symbols must have a size set with .size");
1317b7787fd0SSam Clegg 
13186c899ba6SSam Clegg         // A definition. Write out the function body.
13199f3fe42eSSam Clegg         Index = NumFunctionImports + Functions.size();
1320d934cb88SDan Gohman         WasmFunction Func;
1321da419bdbSHeejin Ahn         Func.SigIndex = getFunctionType(WS);
1322d934cb88SDan Gohman         Func.Sym = &WS;
13236c899ba6SSam Clegg         WasmIndices[&WS] = Index;
1324d934cb88SDan Gohman         Functions.push_back(Func);
13256c899ba6SSam Clegg 
13266c899ba6SSam Clegg         auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
13276c899ba6SSam Clegg         if (const MCSymbolWasm *C = Section.getGroup()) {
13286c899ba6SSam Clegg           Comdats[C->getName()].emplace_back(
13296c899ba6SSam Clegg               WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
13306c899ba6SSam Clegg         }
1331881d8778SSam Clegg 
1332881d8778SSam Clegg         if (WS.hasExportName()) {
1333881d8778SSam Clegg           wasm::WasmExport Export;
1334881d8778SSam Clegg           Export.Name = WS.getExportName();
1335881d8778SSam Clegg           Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1336881d8778SSam Clegg           Export.Index = Index;
1337881d8778SSam Clegg           Exports.push_back(Export);
1338881d8778SSam Clegg         }
1339d934cb88SDan Gohman       } else {
1340d934cb88SDan Gohman         // An import; the index was assigned above.
13416c899ba6SSam Clegg         Index = WasmIndices.find(&WS)->second;
1342d934cb88SDan Gohman       }
1343d934cb88SDan Gohman 
1344d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> function index: " << Index << "\n");
1345da419bdbSHeejin Ahn 
13466c899ba6SSam Clegg     } else if (WS.isData()) {
1347f3feb6adSWouter van Oortmerssen       if (!isInSymtab(WS))
1348c38e947eSSam Clegg         continue;
1349c38e947eSSam Clegg 
13506c899ba6SSam Clegg       if (!WS.isDefined()) {
1351d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "  -> segment index: -1"
1352d34e60caSNicola Zaghen                           << "\n");
1353fe6414b0SSam Clegg         continue;
13546c899ba6SSam Clegg       }
1355fe6414b0SSam Clegg 
1356d934cb88SDan Gohman       if (!WS.getSize())
1357c38e947eSSam Clegg         report_fatal_error("data symbols must have a size set with .size: " +
1358c38e947eSSam Clegg                            WS.getName());
1359d934cb88SDan Gohman 
1360d934cb88SDan Gohman       int64_t Size = 0;
1361d934cb88SDan Gohman       if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1362d934cb88SDan Gohman         report_fatal_error(".size expression must be evaluatable");
1363d934cb88SDan Gohman 
1364759631c7SSam Clegg       auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
1365079cba04SSam Clegg       if (!DataSection.isWasmData())
1366079cba04SSam Clegg         report_fatal_error("data symbols must live in a data section: " +
1367079cba04SSam Clegg                            WS.getName());
13687c395943SSam Clegg 
13696c899ba6SSam Clegg       // For each data symbol, export it in the symtab as a reference to the
13706c899ba6SSam Clegg       // corresponding Wasm data segment.
13716c899ba6SSam Clegg       wasm::WasmDataReference Ref = wasm::WasmDataReference{
13726c899ba6SSam Clegg           DataSection.getSegmentIndex(),
13736c899ba6SSam Clegg           static_cast<uint32_t>(Layout.getSymbolOffset(WS)),
13746c899ba6SSam Clegg           static_cast<uint32_t>(Size)};
13756c899ba6SSam Clegg       DataLocations[&WS] = Ref;
1376d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> segment index: " << Ref.Segment << "\n");
1377da419bdbSHeejin Ahn 
1378a165f2d6SSam Clegg     } else if (WS.isGlobal()) {
13796c899ba6SSam Clegg       // A "true" Wasm global (currently just __stack_pointer)
1380545932beSEric Christopher       if (WS.isDefined())
13816c899ba6SSam Clegg         report_fatal_error("don't yet support defined globals");
13826c899ba6SSam Clegg 
1383545932beSEric Christopher       // An import; the index was assigned above
1384d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> global index: "
1385d34e60caSNicola Zaghen                         << WasmIndices.find(&WS)->second << "\n");
1386da419bdbSHeejin Ahn 
1387da419bdbSHeejin Ahn     } else if (WS.isEvent()) {
1388da419bdbSHeejin Ahn       // C++ exception symbol (__cpp_exception)
1389da419bdbSHeejin Ahn       unsigned Index;
1390da419bdbSHeejin Ahn       if (WS.isDefined()) {
1391da419bdbSHeejin Ahn         Index = NumEventImports + Events.size();
1392da419bdbSHeejin Ahn         wasm::WasmEventType Event;
1393da419bdbSHeejin Ahn         Event.SigIndex = getEventType(WS);
1394da419bdbSHeejin Ahn         Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
1395492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
1396da419bdbSHeejin Ahn         WasmIndices[&WS] = Index;
1397da419bdbSHeejin Ahn         Events.push_back(Event);
1398da419bdbSHeejin Ahn       } else {
1399da419bdbSHeejin Ahn         // An import; the index was assigned above.
1400492f7529SSam Clegg         assert(WasmIndices.count(&WS) > 0);
1401da419bdbSHeejin Ahn       }
1402da419bdbSHeejin Ahn       LLVM_DEBUG(dbgs() << "  -> event index: " << WasmIndices.find(&WS)->second
1403da419bdbSHeejin Ahn                         << "\n");
1404da419bdbSHeejin Ahn 
1405a165f2d6SSam Clegg     } else {
1406a165f2d6SSam Clegg       assert(WS.isSection());
1407d934cb88SDan Gohman     }
1408d934cb88SDan Gohman   }
1409d934cb88SDan Gohman 
1410586320c0SNicholas Wilson   // Populate WasmIndices and DataLocations for aliased symbols.  We need to
1411586320c0SNicholas Wilson   // process these in a separate pass because we need to have processed the
1412586320c0SNicholas Wilson   // target of the alias before the alias itself and the symbols are not
1413586320c0SNicholas Wilson   // necessarily ordered in this way.
1414b7787fd0SSam Clegg   for (const MCSymbol &S : Asm.symbols()) {
1415b7787fd0SSam Clegg     if (!S.isVariable())
1416b7787fd0SSam Clegg       continue;
141731a2c809SSam Clegg 
1418cd65f698SSam Clegg     assert(S.isDefined());
1419b7787fd0SSam Clegg 
14205e3d33a7SSam Clegg     // Find the target symbol of this weak alias and export that index
1421aff1c4dfSSam Clegg     const auto &WS = static_cast<const MCSymbolWasm &>(S);
142218c56a07SHeejin Ahn     const MCSymbolWasm *ResolvedSym = resolveSymbol(WS);
1423d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym
1424d34e60caSNicola Zaghen                       << "'\n");
1425b7787fd0SSam Clegg 
1426ffba00bdSSam Clegg     if (ResolvedSym->isFunction()) {
14276c899ba6SSam Clegg       assert(WasmIndices.count(ResolvedSym) > 0);
14286c899ba6SSam Clegg       uint32_t WasmIndex = WasmIndices.find(ResolvedSym)->second;
1429492f7529SSam Clegg       assert(WasmIndices.count(&WS) == 0);
14306c899ba6SSam Clegg       WasmIndices[&WS] = WasmIndex;
1431d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> index:" << WasmIndex << "\n");
1432ffba00bdSSam Clegg     } else if (ResolvedSym->isData()) {
14336c899ba6SSam Clegg       assert(DataLocations.count(ResolvedSym) > 0);
14346c899ba6SSam Clegg       const wasm::WasmDataReference &Ref =
14356c899ba6SSam Clegg           DataLocations.find(ResolvedSym)->second;
14366c899ba6SSam Clegg       DataLocations[&WS] = Ref;
1437d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> index:" << Ref.Segment << "\n");
14386c899ba6SSam Clegg     } else {
1439da419bdbSHeejin Ahn       report_fatal_error("don't yet support global/event aliases");
14406c899ba6SSam Clegg     }
1441586320c0SNicholas Wilson   }
144231a2c809SSam Clegg 
1443586320c0SNicholas Wilson   // Finally, populate the symbol table itself, in its "natural" order.
1444586320c0SNicholas Wilson   for (const MCSymbol &S : Asm.symbols()) {
1445586320c0SNicholas Wilson     const auto &WS = static_cast<const MCSymbolWasm &>(S);
144625d8e68bSSam Clegg     if (!isInSymtab(WS)) {
144718c56a07SHeejin Ahn       WS.setIndex(InvalidIndex);
1448586320c0SNicholas Wilson       continue;
144925d8e68bSSam Clegg     }
1450d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "adding to symtab: " << WS << "\n");
1451586320c0SNicholas Wilson 
1452586320c0SNicholas Wilson     uint32_t Flags = 0;
1453586320c0SNicholas Wilson     if (WS.isWeak())
1454586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_BINDING_WEAK;
1455586320c0SNicholas Wilson     if (WS.isHidden())
1456586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN;
1457586320c0SNicholas Wilson     if (!WS.isExternal() && WS.isDefined())
1458586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;
1459586320c0SNicholas Wilson     if (WS.isUndefined())
1460586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_UNDEFINED;
1461da84b688SDan Gohman     if (WS.isNoStrip()) {
1462da84b688SDan Gohman       Flags |= wasm::WASM_SYMBOL_NO_STRIP;
1463da84b688SDan Gohman       if (isEmscripten()) {
1464d6ef8da3SSam Clegg         Flags |= wasm::WASM_SYMBOL_EXPORTED;
1465da84b688SDan Gohman       }
1466da84b688SDan Gohman     }
1467b4f4e370SSam Clegg     if (WS.hasImportName())
146829874ceaSDan Gohman       Flags |= wasm::WASM_SYMBOL_EXPLICIT_NAME;
1469881d8778SSam Clegg     if (WS.hasExportName())
1470881d8778SSam Clegg       Flags |= wasm::WASM_SYMBOL_EXPORTED;
1471586320c0SNicholas Wilson 
1472586320c0SNicholas Wilson     wasm::WasmSymbolInfo Info;
1473586320c0SNicholas Wilson     Info.Name = WS.getName();
1474586320c0SNicholas Wilson     Info.Kind = WS.getType();
1475586320c0SNicholas Wilson     Info.Flags = Flags;
14764d57fbd0SSam Clegg     if (!WS.isData()) {
14774d57fbd0SSam Clegg       assert(WasmIndices.count(&WS) > 0);
1478586320c0SNicholas Wilson       Info.ElementIndex = WasmIndices.find(&WS)->second;
14794d57fbd0SSam Clegg     } else if (WS.isDefined()) {
14804d57fbd0SSam Clegg       assert(DataLocations.count(&WS) > 0);
1481586320c0SNicholas Wilson       Info.DataRef = DataLocations.find(&WS)->second;
14824d57fbd0SSam Clegg     }
148325d8e68bSSam Clegg     WS.setIndex(SymbolInfos.size());
1484586320c0SNicholas Wilson     SymbolInfos.emplace_back(Info);
1485b7787fd0SSam Clegg   }
1486b7787fd0SSam Clegg 
14876006e091SSam Clegg   {
14886006e091SSam Clegg     auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
1489f9edbe95SSam Clegg       // Functions referenced by a relocation need to put in the table.  This is
1490f9edbe95SSam Clegg       // purely to make the object file's provisional values readable, and is
1491f9edbe95SSam Clegg       // ignored by the linker, which re-calculates the relocations itself.
1492d1152a26SSam Clegg       if (Rel.Type != wasm::R_WASM_TABLE_INDEX_I32 &&
1493d1152a26SSam Clegg           Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB)
1494f9edbe95SSam Clegg         return;
1495f9edbe95SSam Clegg       assert(Rel.Symbol->isFunction());
149618c56a07SHeejin Ahn       const MCSymbolWasm &WS = *resolveSymbol(*Rel.Symbol);
14976c899ba6SSam Clegg       uint32_t FunctionIndex = WasmIndices.find(&WS)->second;
149818c56a07SHeejin Ahn       uint32_t TableIndex = TableElems.size() + InitialTableOffset;
1499f9edbe95SSam Clegg       if (TableIndices.try_emplace(&WS, TableIndex).second) {
1500d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "  -> adding " << WS.getName()
1501f9edbe95SSam Clegg                           << " to table: " << TableIndex << "\n");
15026c899ba6SSam Clegg         TableElems.push_back(FunctionIndex);
15036006e091SSam Clegg         registerFunctionType(WS);
15046006e091SSam Clegg       }
15056006e091SSam Clegg     };
1506970d02c4SDan Gohman 
15076006e091SSam Clegg     for (const WasmRelocationEntry &RelEntry : CodeRelocations)
15086006e091SSam Clegg       HandleReloc(RelEntry);
15096006e091SSam Clegg     for (const WasmRelocationEntry &RelEntry : DataRelocations)
15106006e091SSam Clegg       HandleReloc(RelEntry);
1511d934cb88SDan Gohman   }
1512d934cb88SDan Gohman 
1513bafe6902SSam Clegg   // Translate .init_array section contents into start functions.
1514bafe6902SSam Clegg   for (const MCSection &S : Asm) {
1515bafe6902SSam Clegg     const auto &WS = static_cast<const MCSectionWasm &>(S);
15167d1ff446SFangrui Song     if (WS.getName().startswith(".fini_array"))
1517bafe6902SSam Clegg       report_fatal_error(".fini_array sections are unsupported");
15187d1ff446SFangrui Song     if (!WS.getName().startswith(".init_array"))
1519bafe6902SSam Clegg       continue;
1520bafe6902SSam Clegg     if (WS.getFragmentList().empty())
1521bafe6902SSam Clegg       continue;
1522b210c64bSSam Clegg 
1523b210c64bSSam Clegg     // init_array is expected to contain a single non-empty data fragment
1524b210c64bSSam Clegg     if (WS.getFragmentList().size() != 3)
1525bafe6902SSam Clegg       report_fatal_error("only one .init_array section fragment supported");
1526b210c64bSSam Clegg 
1527b210c64bSSam Clegg     auto IT = WS.begin();
1528b210c64bSSam Clegg     const MCFragment &EmptyFrag = *IT;
1529b210c64bSSam Clegg     if (EmptyFrag.getKind() != MCFragment::FT_Data)
1530b210c64bSSam Clegg       report_fatal_error(".init_array section should be aligned");
1531b210c64bSSam Clegg 
1532b210c64bSSam Clegg     IT = std::next(IT);
1533b210c64bSSam Clegg     const MCFragment &AlignFrag = *IT;
1534bafe6902SSam Clegg     if (AlignFrag.getKind() != MCFragment::FT_Align)
1535bafe6902SSam Clegg       report_fatal_error(".init_array section should be aligned");
1536bafe6902SSam Clegg     if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
1537bafe6902SSam Clegg       report_fatal_error(".init_array section should be aligned for pointers");
1538b210c64bSSam Clegg 
1539b210c64bSSam Clegg     const MCFragment &Frag = *std::next(IT);
1540bafe6902SSam Clegg     if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1541bafe6902SSam Clegg       report_fatal_error("only data supported in .init_array section");
1542b210c64bSSam Clegg 
1543bafe6902SSam Clegg     uint16_t Priority = UINT16_MAX;
15444d57fbd0SSam Clegg     unsigned PrefixLength = strlen(".init_array");
15457d1ff446SFangrui Song     if (WS.getName().size() > PrefixLength) {
15467d1ff446SFangrui Song       if (WS.getName()[PrefixLength] != '.')
1547f208f631SHeejin Ahn         report_fatal_error(
1548f208f631SHeejin Ahn             ".init_array section priority should start with '.'");
15497d1ff446SFangrui Song       if (WS.getName().substr(PrefixLength + 1).getAsInteger(10, Priority))
1550bafe6902SSam Clegg         report_fatal_error("invalid .init_array section priority");
1551bafe6902SSam Clegg     }
1552bafe6902SSam Clegg     const auto &DataFrag = cast<MCDataFragment>(Frag);
1553bafe6902SSam Clegg     const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1554f208f631SHeejin Ahn     for (const uint8_t *
155518c56a07SHeejin Ahn              P = (const uint8_t *)Contents.data(),
155618c56a07SHeejin Ahn             *End = (const uint8_t *)Contents.data() + Contents.size();
155718c56a07SHeejin Ahn          P != End; ++P) {
155818c56a07SHeejin Ahn       if (*P != 0)
1559bafe6902SSam Clegg         report_fatal_error("non-symbolic data in .init_array section");
1560bafe6902SSam Clegg     }
1561bafe6902SSam Clegg     for (const MCFixup &Fixup : DataFrag.getFixups()) {
1562f208f631SHeejin Ahn       assert(Fixup.getKind() ==
1563f208f631SHeejin Ahn              MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
1564bafe6902SSam Clegg       const MCExpr *Expr = Fixup.getValue();
15658fffa1dfSSam Clegg       auto *SymRef = dyn_cast<MCSymbolRefExpr>(Expr);
15668fffa1dfSSam Clegg       if (!SymRef)
1567bafe6902SSam Clegg         report_fatal_error("fixups in .init_array should be symbol references");
15688fffa1dfSSam Clegg       const auto &TargetSym = cast<const MCSymbolWasm>(SymRef->getSymbol());
15698fffa1dfSSam Clegg       if (TargetSym.getIndex() == InvalidIndex)
15703ea1c62cSSam Clegg         report_fatal_error("symbols in .init_array should exist in symtab");
15718fffa1dfSSam Clegg       if (!TargetSym.isFunction())
15728fffa1dfSSam Clegg         report_fatal_error("symbols in .init_array should be for functions");
157325d8e68bSSam Clegg       InitFuncs.push_back(
15748fffa1dfSSam Clegg           std::make_pair(Priority, TargetSym.getIndex()));
1575bafe6902SSam Clegg     }
1576bafe6902SSam Clegg   }
1577bafe6902SSam Clegg 
157818eafb6cSDan Gohman   // Write out the Wasm header.
157918eafb6cSDan Gohman   writeHeader(Asm);
158018eafb6cSDan Gohman 
1581da419bdbSHeejin Ahn   writeTypeSection(Signatures);
1582f950b24aSSam Clegg   writeImportSection(Imports, DataSize, TableElems.size());
15839e15f359SSam Clegg   writeFunctionSection(Functions);
1584f950b24aSSam Clegg   // Skip the "table" section; we import the table instead.
1585f950b24aSSam Clegg   // Skip the "memory" section; we import the memory instead.
1586da419bdbSHeejin Ahn   writeEventSection(Events);
15879e15f359SSam Clegg   writeExportSection(Exports);
15889e15f359SSam Clegg   writeElemSection(TableElems);
1589fef8de66SThomas Lively   writeDataCountSection();
1590acd7d2b0SSam Clegg   writeCodeSection(Asm, Layout, Functions);
15916c899ba6SSam Clegg   writeDataSection();
1592cbda16ebSThomas Lively   for (auto &CustomSection : CustomSections)
1593cbda16ebSThomas Lively     writeCustomSection(CustomSection, Asm, Layout);
1594c22bfb6bSNicholas Wilson   writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats);
15956f08c84aSSam Clegg   writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations);
15966f08c84aSSam Clegg   writeRelocSection(DataSectionIndex, "DATA", DataRelocations);
15976a31a0d6SSam Clegg   writeCustomRelocSections();
1598cbda16ebSThomas Lively   if (ProducersSection)
1599cbda16ebSThomas Lively     writeCustomSection(*ProducersSection, Asm, Layout);
1600f6f4f843SThomas Lively   if (TargetFeaturesSection)
1601f6f4f843SThomas Lively     writeCustomSection(*TargetFeaturesSection, Asm, Layout);
1602970d02c4SDan Gohman 
1603d934cb88SDan Gohman   // TODO: Translate the .comment section to the output.
1604438390faSPeter Collingbourne   return W.OS.tell() - StartOffset;
160518eafb6cSDan Gohman }
160618eafb6cSDan Gohman 
160760fbc7ccSLang Hames std::unique_ptr<MCObjectWriter>
16081301a878SLang Hames llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
160918eafb6cSDan Gohman                              raw_pwrite_stream &OS) {
16100eaee545SJonas Devlieghere   return std::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
161118eafb6cSDan Gohman }
1612