118eafb6cSDan Gohman //===- lib/MC/WasmObjectWriter.cpp - Wasm File Writer ---------------------===//
218eafb6cSDan Gohman //
318eafb6cSDan Gohman //                     The LLVM Compiler Infrastructure
418eafb6cSDan Gohman //
518eafb6cSDan Gohman // This file is distributed under the University of Illinois Open Source
618eafb6cSDan Gohman // License. See LICENSE.TXT for details.
718eafb6cSDan Gohman //
818eafb6cSDan Gohman //===----------------------------------------------------------------------===//
918eafb6cSDan Gohman //
1018eafb6cSDan Gohman // This file implements Wasm object file writer information.
1118eafb6cSDan Gohman //
1218eafb6cSDan Gohman //===----------------------------------------------------------------------===//
1318eafb6cSDan Gohman 
1418eafb6cSDan Gohman #include "llvm/ADT/STLExtras.h"
1518eafb6cSDan Gohman #include "llvm/ADT/SmallPtrSet.h"
16264b5d9eSZachary Turner #include "llvm/BinaryFormat/Wasm.h"
17432a3883SNico Weber #include "llvm/Config/llvm-config.h"
1818eafb6cSDan Gohman #include "llvm/MC/MCAsmBackend.h"
1918eafb6cSDan Gohman #include "llvm/MC/MCAsmLayout.h"
2018eafb6cSDan Gohman #include "llvm/MC/MCAssembler.h"
2118eafb6cSDan Gohman #include "llvm/MC/MCContext.h"
2218eafb6cSDan Gohman #include "llvm/MC/MCExpr.h"
2318eafb6cSDan Gohman #include "llvm/MC/MCFixupKindInfo.h"
2418eafb6cSDan Gohman #include "llvm/MC/MCObjectWriter.h"
2518eafb6cSDan Gohman #include "llvm/MC/MCSectionWasm.h"
2618eafb6cSDan Gohman #include "llvm/MC/MCSymbolWasm.h"
2718eafb6cSDan Gohman #include "llvm/MC/MCValue.h"
2818eafb6cSDan Gohman #include "llvm/MC/MCWasmObjectWriter.h"
29d934cb88SDan Gohman #include "llvm/Support/Casting.h"
3018eafb6cSDan Gohman #include "llvm/Support/Debug.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 
40*d1f0910aSSam Clegg #if !defined(NDEBUG)
41a165f2d6SSam Clegg static std::string toString(wasm::WasmSymbolType type) {
42a165f2d6SSam Clegg   switch (type) {
43a165f2d6SSam Clegg   case wasm::WASM_SYMBOL_TYPE_FUNCTION:
44a165f2d6SSam Clegg     return "WASM_SYMBOL_TYPE_FUNCTION";
45a165f2d6SSam Clegg   case wasm::WASM_SYMBOL_TYPE_GLOBAL:
46a165f2d6SSam Clegg     return "WASM_SYMBOL_TYPE_GLOBAL";
47a165f2d6SSam Clegg   case wasm::WASM_SYMBOL_TYPE_DATA:
48a165f2d6SSam Clegg     return "WASM_SYMBOL_TYPE_DATA";
49a165f2d6SSam Clegg   case wasm::WASM_SYMBOL_TYPE_SECTION:
50a165f2d6SSam Clegg     return "WASM_SYMBOL_TYPE_SECTION";
51a165f2d6SSam Clegg   }
52ba4d85eeSFlorian Hahn   llvm_unreachable("unknown symbol type");
53a165f2d6SSam Clegg }
54*d1f0910aSSam Clegg #endif
55a165f2d6SSam Clegg 
56a165f2d6SSam Clegg static std::string relocTypetoString(uint32_t type) {
57a165f2d6SSam Clegg   switch (type) {
58a165f2d6SSam Clegg #define WASM_RELOC(NAME, VALUE) case VALUE: return #NAME;
59a165f2d6SSam Clegg #include "llvm/BinaryFormat/WasmRelocs.def"
60a165f2d6SSam Clegg #undef WASM_RELOC
61a165f2d6SSam Clegg   default:
62a165f2d6SSam Clegg     llvm_unreachable("uknown reloc type");
63a165f2d6SSam Clegg   }
64a165f2d6SSam Clegg }
65a165f2d6SSam Clegg 
6618eafb6cSDan Gohman namespace {
679e15f359SSam Clegg 
6830e1bbc1SSam Clegg // Went we ceate the indirect function table we start at 1, so that there is
6930e1bbc1SSam Clegg // and emtpy slot at 0 and therefore calling a null function pointer will trap.
7030e1bbc1SSam Clegg static const uint32_t kInitialTableOffset = 1;
7130e1bbc1SSam Clegg 
72d934cb88SDan Gohman // For patching purposes, we need to remember where each section starts, both
73d934cb88SDan Gohman // for patching up the section size field, and for patching up references to
74d934cb88SDan Gohman // locations within the section.
75d934cb88SDan Gohman struct SectionBookkeeping {
76d934cb88SDan Gohman   // Where the size of the section is written.
77d934cb88SDan Gohman   uint64_t SizeOffset;
786a31a0d6SSam Clegg   // Where the section header ends (without custom section name).
796a31a0d6SSam Clegg   uint64_t PayloadOffset;
806a31a0d6SSam Clegg   // Where the contents of the section starts.
81d934cb88SDan Gohman   uint64_t ContentsOffset;
826f08c84aSSam Clegg   uint32_t Index;
83d934cb88SDan Gohman };
84d934cb88SDan Gohman 
859e15f359SSam Clegg // The signature of a wasm function, in a struct capable of being used as a
869e15f359SSam Clegg // DenseMap key.
879e15f359SSam Clegg struct WasmFunctionType {
889e15f359SSam Clegg   // Support empty and tombstone instances, needed by DenseMap.
899e15f359SSam Clegg   enum { Plain, Empty, Tombstone } State;
909e15f359SSam Clegg 
919e15f359SSam Clegg   // The return types of the function.
929e15f359SSam Clegg   SmallVector<wasm::ValType, 1> Returns;
939e15f359SSam Clegg 
949e15f359SSam Clegg   // The parameter types of the function.
959e15f359SSam Clegg   SmallVector<wasm::ValType, 4> Params;
969e15f359SSam Clegg 
979e15f359SSam Clegg   WasmFunctionType() : State(Plain) {}
989e15f359SSam Clegg 
999e15f359SSam Clegg   bool operator==(const WasmFunctionType &Other) const {
1009e15f359SSam Clegg     return State == Other.State && Returns == Other.Returns &&
1019e15f359SSam Clegg            Params == Other.Params;
1029e15f359SSam Clegg   }
1039e15f359SSam Clegg };
1049e15f359SSam Clegg 
1059e15f359SSam Clegg // Traits for using WasmFunctionType in a DenseMap.
1069e15f359SSam Clegg struct WasmFunctionTypeDenseMapInfo {
1079e15f359SSam Clegg   static WasmFunctionType getEmptyKey() {
1089e15f359SSam Clegg     WasmFunctionType FuncTy;
1099e15f359SSam Clegg     FuncTy.State = WasmFunctionType::Empty;
1109e15f359SSam Clegg     return FuncTy;
1119e15f359SSam Clegg   }
1129e15f359SSam Clegg   static WasmFunctionType getTombstoneKey() {
1139e15f359SSam Clegg     WasmFunctionType FuncTy;
1149e15f359SSam Clegg     FuncTy.State = WasmFunctionType::Tombstone;
1159e15f359SSam Clegg     return FuncTy;
1169e15f359SSam Clegg   }
1179e15f359SSam Clegg   static unsigned getHashValue(const WasmFunctionType &FuncTy) {
1189e15f359SSam Clegg     uintptr_t Value = FuncTy.State;
1199e15f359SSam Clegg     for (wasm::ValType Ret : FuncTy.Returns)
1209e15f359SSam Clegg       Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Ret));
1219e15f359SSam Clegg     for (wasm::ValType Param : FuncTy.Params)
1229e15f359SSam Clegg       Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Param));
1239e15f359SSam Clegg     return Value;
1249e15f359SSam Clegg   }
1259e15f359SSam Clegg   static bool isEqual(const WasmFunctionType &LHS,
1269e15f359SSam Clegg                       const WasmFunctionType &RHS) {
1279e15f359SSam Clegg     return LHS == RHS;
1289e15f359SSam Clegg   }
1299e15f359SSam Clegg };
1309e15f359SSam Clegg 
1317c395943SSam Clegg // A wasm data segment.  A wasm binary contains only a single data section
1327c395943SSam Clegg // but that can contain many segments, each with their own virtual location
1337c395943SSam Clegg // in memory.  Each MCSection data created by llvm is modeled as its own
1347c395943SSam Clegg // wasm data segment.
1357c395943SSam Clegg struct WasmDataSegment {
1367c395943SSam Clegg   MCSectionWasm *Section;
137d95ed959SSam Clegg   StringRef Name;
1387c395943SSam Clegg   uint32_t Offset;
13963ebb813SSam Clegg   uint32_t Alignment;
14063ebb813SSam Clegg   uint32_t Flags;
1417c395943SSam Clegg   SmallVector<char, 4> Data;
1427c395943SSam Clegg };
1437c395943SSam Clegg 
1449e15f359SSam Clegg // A wasm function to be written into the function section.
1459e15f359SSam Clegg struct WasmFunction {
1469e15f359SSam Clegg   int32_t Type;
1479e15f359SSam Clegg   const MCSymbolWasm *Sym;
1489e15f359SSam Clegg };
1499e15f359SSam Clegg 
1509e15f359SSam Clegg // A wasm global to be written into the global section.
1519e15f359SSam Clegg struct WasmGlobal {
1526e7f1826SSam Clegg   wasm::WasmGlobalType Type;
1539e15f359SSam Clegg   uint64_t InitialValue;
1549e15f359SSam Clegg };
1559e15f359SSam Clegg 
156ea7caceeSSam Clegg // Information about a single item which is part of a COMDAT.  For each data
157ea7caceeSSam Clegg // segment or function which is in the COMDAT, there is a corresponding
158ea7caceeSSam Clegg // WasmComdatEntry.
159ea7caceeSSam Clegg struct WasmComdatEntry {
160ea7caceeSSam Clegg   unsigned Kind;
161ea7caceeSSam Clegg   uint32_t Index;
162ea7caceeSSam Clegg };
163ea7caceeSSam Clegg 
1646dc65e91SSam Clegg // Information about a single relocation.
1656dc65e91SSam Clegg struct WasmRelocationEntry {
1666dc65e91SSam Clegg   uint64_t Offset;                  // Where is the relocation.
1676dc65e91SSam Clegg   const MCSymbolWasm *Symbol;       // The symbol to relocate with.
1686dc65e91SSam Clegg   int64_t Addend;                   // A value to add to the symbol.
1696dc65e91SSam Clegg   unsigned Type;                    // The type of the relocation.
170fe6414b0SSam Clegg   const MCSectionWasm *FixupSection;// The section the relocation is targeting.
1716dc65e91SSam Clegg 
1726dc65e91SSam Clegg   WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol,
1736dc65e91SSam Clegg                       int64_t Addend, unsigned Type,
174fe6414b0SSam Clegg                       const MCSectionWasm *FixupSection)
1756dc65e91SSam Clegg       : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type),
1766dc65e91SSam Clegg         FixupSection(FixupSection) {}
1776dc65e91SSam Clegg 
178acd7d2b0SSam Clegg   bool hasAddend() const {
179acd7d2b0SSam Clegg     switch (Type) {
18013a2e899SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
18113a2e899SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
18213a2e899SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
1836a31a0d6SSam Clegg     case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32:
1846a31a0d6SSam Clegg     case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32:
185acd7d2b0SSam Clegg       return true;
186acd7d2b0SSam Clegg     default:
187acd7d2b0SSam Clegg       return false;
188acd7d2b0SSam Clegg     }
189acd7d2b0SSam Clegg   }
190acd7d2b0SSam Clegg 
1916dc65e91SSam Clegg   void print(raw_ostream &Out) const {
192a165f2d6SSam Clegg     Out << relocTypetoString(Type)
193a165f2d6SSam Clegg         << " Off=" << Offset << ", Sym=" << *Symbol << ", Addend=" << Addend
194759631c7SSam Clegg         << ", FixupSection=" << FixupSection->getSectionName();
1956dc65e91SSam Clegg   }
196b7787fd0SSam Clegg 
197615eb470SAaron Ballman #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
198b7787fd0SSam Clegg   LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
199b7787fd0SSam Clegg #endif
2006dc65e91SSam Clegg };
2016dc65e91SSam Clegg 
202cfd44a2eSSam Clegg struct WasmCustomSection {
2036a31a0d6SSam Clegg   const uint32_t INVALID_INDEX = -1;
204cfd44a2eSSam Clegg 
2056a31a0d6SSam Clegg   StringRef Name;
2066a31a0d6SSam Clegg   MCSectionWasm *Section;
2076a31a0d6SSam Clegg 
2086a31a0d6SSam Clegg   uint32_t OutputContentsOffset;
2096a31a0d6SSam Clegg   uint32_t OutputIndex;
2106a31a0d6SSam Clegg 
2116a31a0d6SSam Clegg   WasmCustomSection(StringRef Name, MCSectionWasm *Section)
2126a31a0d6SSam Clegg       : Name(Name), Section(Section), OutputContentsOffset(0),
2136a31a0d6SSam Clegg         OutputIndex(INVALID_INDEX) {}
214cfd44a2eSSam Clegg };
215cfd44a2eSSam Clegg 
2161fb8daa6SSam Clegg #if !defined(NDEBUG)
2177f055deeSSam Clegg raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
218b7787fd0SSam Clegg   Rel.print(OS);
219b7787fd0SSam Clegg   return OS;
220b7787fd0SSam Clegg }
2211fb8daa6SSam Clegg #endif
222b7787fd0SSam Clegg 
22318eafb6cSDan Gohman class WasmObjectWriter : public MCObjectWriter {
22418eafb6cSDan Gohman   /// The target specific Wasm writer instance.
22518eafb6cSDan Gohman   std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
22618eafb6cSDan Gohman 
227d934cb88SDan Gohman   // Relocations for fixing up references in the code section.
228d934cb88SDan Gohman   std::vector<WasmRelocationEntry> CodeRelocations;
2296f08c84aSSam Clegg   uint32_t CodeSectionIndex;
230d934cb88SDan Gohman 
231d934cb88SDan Gohman   // Relocations for fixing up references in the data section.
232d934cb88SDan Gohman   std::vector<WasmRelocationEntry> DataRelocations;
2336f08c84aSSam Clegg   uint32_t DataSectionIndex;
234d934cb88SDan Gohman 
235d934cb88SDan Gohman   // Index values to use for fixing up call_indirect type indices.
236acd7d2b0SSam Clegg   // Maps function symbols to the index of the type of the function
237acd7d2b0SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
238d99f6078SSam Clegg   // Maps function symbols to the table element index space. Used
239d99f6078SSam Clegg   // for TABLE_INDEX relocation types (i.e. address taken functions).
240f9edbe95SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> TableIndices;
2416c899ba6SSam Clegg   // Maps function/global symbols to the (shared) Symbol index space.
242acd7d2b0SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> SymbolIndices;
243a165f2d6SSam Clegg   // Maps function/global symbols to the function/global/section index space.
2446c899ba6SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> WasmIndices;
2456c899ba6SSam Clegg   // Maps data symbols to the Wasm segment and offset/size with the segment.
2466c899ba6SSam Clegg   DenseMap<const MCSymbolWasm *, wasm::WasmDataReference> DataLocations;
2476a31a0d6SSam Clegg   // Maps section symbols to the section.
2486a31a0d6SSam Clegg   DenseMap<const MCSymbolWasm *, const MCSectionWasm *> CustomSectionSymbols;
2496a31a0d6SSam Clegg 
2506a31a0d6SSam Clegg   // Stores output data (index, relocations, content offset) for custom
2516a31a0d6SSam Clegg   // section.
2526a31a0d6SSam Clegg   std::vector<WasmCustomSection> CustomSections;
2536a31a0d6SSam Clegg   // Relocations for fixing up references in the custom sections.
2546a31a0d6SSam Clegg   DenseMap<const MCSectionWasm *, std::vector<WasmRelocationEntry>>
2556a31a0d6SSam Clegg       CustomSectionsRelocations;
256acd7d2b0SSam Clegg 
257acd7d2b0SSam Clegg   DenseMap<WasmFunctionType, int32_t, WasmFunctionTypeDenseMapInfo>
258acd7d2b0SSam Clegg       FunctionTypeIndices;
2595e3d33a7SSam Clegg   SmallVector<WasmFunctionType, 4> FunctionTypes;
2607c395943SSam Clegg   SmallVector<WasmGlobal, 4> Globals;
2616c899ba6SSam Clegg   SmallVector<WasmDataSegment, 4> DataSegments;
2629f3fe42eSSam Clegg   unsigned NumFunctionImports = 0;
2637c395943SSam Clegg   unsigned NumGlobalImports = 0;
2647e1c3345SChandler Carruth   uint32_t SectionCount = 0;
265d934cb88SDan Gohman 
26618eafb6cSDan Gohman   // TargetObjectWriter wrappers.
26718eafb6cSDan Gohman   bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
268ae03c1e7SSam Clegg   unsigned getRelocType(const MCValue &Target, const MCFixup &Fixup) const {
269ae03c1e7SSam Clegg     return TargetObjectWriter->getRelocType(Target, Fixup);
27018eafb6cSDan Gohman   }
27118eafb6cSDan Gohman 
2722322a937SSam Clegg   void startSection(SectionBookkeeping &Section, unsigned SectionId);
2732322a937SSam Clegg   void startCustomSection(SectionBookkeeping &Section, StringRef Name);
274d934cb88SDan Gohman   void endSection(SectionBookkeeping &Section);
275d934cb88SDan Gohman 
27618eafb6cSDan Gohman public:
2771301a878SLang Hames   WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
2781301a878SLang Hames                    raw_pwrite_stream &OS)
2791301a878SLang Hames       : MCObjectWriter(OS, /*IsLittleEndian=*/true),
2801301a878SLang Hames         TargetObjectWriter(std::move(MOTW)) {}
28118eafb6cSDan Gohman 
28218eafb6cSDan Gohman   ~WasmObjectWriter() override;
28318eafb6cSDan Gohman 
2840917c9e4SDan Gohman private:
285acd7d2b0SSam Clegg   void reset() override {
286acd7d2b0SSam Clegg     CodeRelocations.clear();
287acd7d2b0SSam Clegg     DataRelocations.clear();
288acd7d2b0SSam Clegg     TypeIndices.clear();
289acd7d2b0SSam Clegg     SymbolIndices.clear();
2906c899ba6SSam Clegg     WasmIndices.clear();
291f9edbe95SSam Clegg     TableIndices.clear();
2926c899ba6SSam Clegg     DataLocations.clear();
2936a31a0d6SSam Clegg     CustomSectionsRelocations.clear();
294acd7d2b0SSam Clegg     FunctionTypeIndices.clear();
2955e3d33a7SSam Clegg     FunctionTypes.clear();
2967c395943SSam Clegg     Globals.clear();
2976c899ba6SSam Clegg     DataSegments.clear();
2986a31a0d6SSam Clegg     CustomSectionSymbols.clear();
299acd7d2b0SSam Clegg     MCObjectWriter::reset();
3009f3fe42eSSam Clegg     NumFunctionImports = 0;
3017c395943SSam Clegg     NumGlobalImports = 0;
302acd7d2b0SSam Clegg   }
303acd7d2b0SSam Clegg 
30418eafb6cSDan Gohman   void writeHeader(const MCAssembler &Asm);
30518eafb6cSDan Gohman 
30618eafb6cSDan Gohman   void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
30718eafb6cSDan Gohman                         const MCFragment *Fragment, const MCFixup &Fixup,
308ceecfe5bSRafael Espindola                         MCValue Target, uint64_t &FixedValue) override;
30918eafb6cSDan Gohman 
31018eafb6cSDan Gohman   void executePostLayoutBinding(MCAssembler &Asm,
31118eafb6cSDan Gohman                                 const MCAsmLayout &Layout) override;
31218eafb6cSDan Gohman 
31318eafb6cSDan Gohman   void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
3149e15f359SSam Clegg 
315b7787fd0SSam Clegg   void writeString(const StringRef Str) {
316b7787fd0SSam Clegg     encodeULEB128(Str.size(), getStream());
317b7787fd0SSam Clegg     writeBytes(Str);
318b7787fd0SSam Clegg   }
319b7787fd0SSam Clegg 
3209e15f359SSam Clegg   void writeValueType(wasm::ValType Ty) {
32103e101f1SSam Clegg     write8(static_cast<uint8_t>(Ty));
3229e15f359SSam Clegg   }
3239e15f359SSam Clegg 
324457fb0b4SSam Clegg   void writeTypeSection(ArrayRef<WasmFunctionType> FunctionTypes);
3258defa952SSam Clegg   void writeImportSection(ArrayRef<wasm::WasmImport> Imports, uint32_t DataSize,
326f950b24aSSam Clegg                           uint32_t NumElements);
327457fb0b4SSam Clegg   void writeFunctionSection(ArrayRef<WasmFunction> Functions);
3287c395943SSam Clegg   void writeGlobalSection();
3298defa952SSam Clegg   void writeExportSection(ArrayRef<wasm::WasmExport> Exports);
330457fb0b4SSam Clegg   void writeElemSection(ArrayRef<uint32_t> TableElems);
3319e15f359SSam Clegg   void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
332457fb0b4SSam Clegg                         ArrayRef<WasmFunction> Functions);
3336c899ba6SSam Clegg   void writeDataSection();
3346f08c84aSSam Clegg   void writeRelocSection(uint32_t SectionIndex, StringRef Name,
3356f08c84aSSam Clegg                          ArrayRef<WasmRelocationEntry> Relocations);
33631a2c809SSam Clegg   void writeLinkingMetaDataSection(
33786b4a09aSSam Clegg       ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
338ea7caceeSSam Clegg       ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
339ea7caceeSSam Clegg       const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats);
3406a31a0d6SSam Clegg   void writeCustomSections(const MCAssembler &Asm, const MCAsmLayout &Layout);
3416a31a0d6SSam Clegg   void writeCustomRelocSections();
3426a31a0d6SSam Clegg   void
3436a31a0d6SSam Clegg   updateCustomSectionRelocations(const SmallVector<WasmFunction, 4> &Functions,
3446a31a0d6SSam Clegg                                  const MCAsmLayout &Layout);
345acd7d2b0SSam Clegg 
3467c395943SSam Clegg   uint32_t getProvisionalValue(const WasmRelocationEntry &RelEntry);
347acd7d2b0SSam Clegg   void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
348acd7d2b0SSam Clegg                         uint64_t ContentsOffset);
349acd7d2b0SSam Clegg 
350acd7d2b0SSam Clegg   uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
3515e3d33a7SSam Clegg   uint32_t getFunctionType(const MCSymbolWasm &Symbol);
3525e3d33a7SSam Clegg   uint32_t registerFunctionType(const MCSymbolWasm &Symbol);
35318eafb6cSDan Gohman };
3549e15f359SSam Clegg 
35518eafb6cSDan Gohman } // end anonymous namespace
35618eafb6cSDan Gohman 
35718eafb6cSDan Gohman WasmObjectWriter::~WasmObjectWriter() {}
35818eafb6cSDan Gohman 
359d934cb88SDan Gohman // Write out a section header and a patchable section size field.
360d934cb88SDan Gohman void WasmObjectWriter::startSection(SectionBookkeeping &Section,
3612322a937SSam Clegg                                     unsigned SectionId) {
3622322a937SSam Clegg   DEBUG(dbgs() << "startSection " << SectionId << "\n");
36303e101f1SSam Clegg   write8(SectionId);
364d934cb88SDan Gohman 
365d934cb88SDan Gohman   Section.SizeOffset = getStream().tell();
366d934cb88SDan Gohman 
367d934cb88SDan Gohman   // The section size. We don't know the size yet, so reserve enough space
368d934cb88SDan Gohman   // for any 32-bit value; we'll patch it later.
369d934cb88SDan Gohman   encodeULEB128(UINT32_MAX, getStream());
370d934cb88SDan Gohman 
371d934cb88SDan Gohman   // The position where the section starts, for measuring its size.
372d934cb88SDan Gohman   Section.ContentsOffset = getStream().tell();
3736a31a0d6SSam Clegg   Section.PayloadOffset = getStream().tell();
3746f08c84aSSam Clegg   Section.Index = SectionCount++;
375d934cb88SDan Gohman }
3762322a937SSam Clegg 
3772322a937SSam Clegg void WasmObjectWriter::startCustomSection(SectionBookkeeping &Section,
3782322a937SSam Clegg                                           StringRef Name) {
3792322a937SSam Clegg   DEBUG(dbgs() << "startCustomSection " << Name << "\n");
3802322a937SSam Clegg   startSection(Section, wasm::WASM_SEC_CUSTOM);
3816a31a0d6SSam Clegg 
3826a31a0d6SSam Clegg   // The position where the section header ends, for measuring its size.
3836a31a0d6SSam Clegg   Section.PayloadOffset = getStream().tell();
3846a31a0d6SSam Clegg 
3852322a937SSam Clegg   // Custom sections in wasm also have a string identifier.
3862322a937SSam Clegg   writeString(Name);
3876a31a0d6SSam Clegg 
3886a31a0d6SSam Clegg   // The position where the custom section starts.
3896a31a0d6SSam Clegg   Section.ContentsOffset = getStream().tell();
390d934cb88SDan Gohman }
391d934cb88SDan Gohman 
392d934cb88SDan Gohman // Now that the section is complete and we know how big it is, patch up the
393d934cb88SDan Gohman // section size field at the start of the section.
394d934cb88SDan Gohman void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
3956a31a0d6SSam Clegg   uint64_t Size = getStream().tell() - Section.PayloadOffset;
396d934cb88SDan Gohman   if (uint32_t(Size) != Size)
397d934cb88SDan Gohman     report_fatal_error("section size does not fit in a uint32_t");
398d934cb88SDan Gohman 
399b7787fd0SSam Clegg   DEBUG(dbgs() << "endSection size=" << Size << "\n");
400d934cb88SDan Gohman 
401d934cb88SDan Gohman   // Write the final section size to the payload_len field, which follows
402d934cb88SDan Gohman   // the section id byte.
403d934cb88SDan Gohman   uint8_t Buffer[16];
40466a99e41SSam Clegg   unsigned SizeLen = encodeULEB128(Size, Buffer, 5);
405d934cb88SDan Gohman   assert(SizeLen == 5);
406d934cb88SDan Gohman   getStream().pwrite((char *)Buffer, SizeLen, Section.SizeOffset);
407d934cb88SDan Gohman }
408d934cb88SDan Gohman 
40918eafb6cSDan Gohman // Emit the Wasm header.
41018eafb6cSDan Gohman void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
4117ea5adffSDan Gohman   writeBytes(StringRef(wasm::WasmMagic, sizeof(wasm::WasmMagic)));
4127ea5adffSDan Gohman   writeLE32(wasm::WasmVersion);
41318eafb6cSDan Gohman }
41418eafb6cSDan Gohman 
41518eafb6cSDan Gohman void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
41618eafb6cSDan Gohman                                                 const MCAsmLayout &Layout) {
41718eafb6cSDan Gohman }
41818eafb6cSDan Gohman 
41918eafb6cSDan Gohman void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
42018eafb6cSDan Gohman                                         const MCAsmLayout &Layout,
42118eafb6cSDan Gohman                                         const MCFragment *Fragment,
42218eafb6cSDan Gohman                                         const MCFixup &Fixup, MCValue Target,
423ceecfe5bSRafael Espindola                                         uint64_t &FixedValue) {
424ceecfe5bSRafael Espindola   MCAsmBackend &Backend = Asm.getBackend();
425ceecfe5bSRafael Espindola   bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
426ceecfe5bSRafael Espindola                  MCFixupKindInfo::FKF_IsPCRel;
427fe6414b0SSam Clegg   const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
428d934cb88SDan Gohman   uint64_t C = Target.getConstant();
429d934cb88SDan Gohman   uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
430d934cb88SDan Gohman   MCContext &Ctx = Asm.getContext();
431d934cb88SDan Gohman 
432bafe6902SSam Clegg   // The .init_array isn't translated as data, so don't do relocations in it.
433bafe6902SSam Clegg   if (FixupSection.getSectionName().startswith(".init_array"))
434bafe6902SSam Clegg     return;
435bafe6902SSam Clegg 
4366a31a0d6SSam Clegg   // TODO: Add support for non-debug metadata sections?
4376a31a0d6SSam Clegg   if (FixupSection.getKind().isMetadata() &&
4386a31a0d6SSam Clegg       !FixupSection.getSectionName().startswith(".debug_"))
439b7a5469cSSam Clegg     return;
440b7a5469cSSam Clegg 
441d934cb88SDan Gohman   if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
442d934cb88SDan Gohman     assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
443d934cb88SDan Gohman            "Should not have constructed this");
444d934cb88SDan Gohman 
445d934cb88SDan Gohman     // Let A, B and C being the components of Target and R be the location of
446d934cb88SDan Gohman     // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
447d934cb88SDan Gohman     // If it is pcrel, we want to compute (A - B + C - R).
448d934cb88SDan Gohman 
449d934cb88SDan Gohman     // In general, Wasm has no relocations for -B. It can only represent (A + C)
450d934cb88SDan Gohman     // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
451d934cb88SDan Gohman     // replace B to implement it: (A - R - K + C)
452d934cb88SDan Gohman     if (IsPCRel) {
453d934cb88SDan Gohman       Ctx.reportError(
454d934cb88SDan Gohman           Fixup.getLoc(),
455d934cb88SDan Gohman           "No relocation available to represent this relative expression");
456d934cb88SDan Gohman       return;
457d934cb88SDan Gohman     }
458d934cb88SDan Gohman 
459d934cb88SDan Gohman     const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
460d934cb88SDan Gohman 
461d934cb88SDan Gohman     if (SymB.isUndefined()) {
462d934cb88SDan Gohman       Ctx.reportError(Fixup.getLoc(),
463d934cb88SDan Gohman                       Twine("symbol '") + SymB.getName() +
464d934cb88SDan Gohman                           "' can not be undefined in a subtraction expression");
465d934cb88SDan Gohman       return;
466d934cb88SDan Gohman     }
467d934cb88SDan Gohman 
468d934cb88SDan Gohman     assert(!SymB.isAbsolute() && "Should have been folded");
469d934cb88SDan Gohman     const MCSection &SecB = SymB.getSection();
470d934cb88SDan Gohman     if (&SecB != &FixupSection) {
471d934cb88SDan Gohman       Ctx.reportError(Fixup.getLoc(),
472d934cb88SDan Gohman                       "Cannot represent a difference across sections");
473d934cb88SDan Gohman       return;
474d934cb88SDan Gohman     }
475d934cb88SDan Gohman 
476d934cb88SDan Gohman     uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
477d934cb88SDan Gohman     uint64_t K = SymBOffset - FixupOffset;
478d934cb88SDan Gohman     IsPCRel = true;
479d934cb88SDan Gohman     C -= K;
480d934cb88SDan Gohman   }
481d934cb88SDan Gohman 
482d934cb88SDan Gohman   // We either rejected the fixup or folded B into C at this point.
483d934cb88SDan Gohman   const MCSymbolRefExpr *RefA = Target.getSymA();
484d934cb88SDan Gohman   const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr;
485d934cb88SDan Gohman 
486d934cb88SDan Gohman   if (SymA && SymA->isVariable()) {
487d934cb88SDan Gohman     const MCExpr *Expr = SymA->getVariableValue();
4886ad8f190SSam Clegg     const auto *Inner = cast<MCSymbolRefExpr>(Expr);
4896ad8f190SSam Clegg     if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
4906ad8f190SSam Clegg       llvm_unreachable("weakref used in reloc not yet implemented");
491d934cb88SDan Gohman   }
492d934cb88SDan Gohman 
493d934cb88SDan Gohman   // Put any constant offset in an addend. Offsets can be negative, and
494d934cb88SDan Gohman   // LLVM expects wrapping, in contrast to wasm's immediates which can't
495d934cb88SDan Gohman   // be negative and don't wrap.
496d934cb88SDan Gohman   FixedValue = 0;
497d934cb88SDan Gohman 
4986ad8f190SSam Clegg   if (SymA)
499d934cb88SDan Gohman     SymA->setUsedInReloc();
500d934cb88SDan Gohman 
501ae03c1e7SSam Clegg   assert(!IsPCRel);
5029d24fb7fSSam Clegg   assert(SymA);
5039d24fb7fSSam Clegg 
504ae03c1e7SSam Clegg   unsigned Type = getRelocType(Target, Fixup);
505ae03c1e7SSam Clegg 
506d934cb88SDan Gohman   WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
507b7787fd0SSam Clegg   DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
508d934cb88SDan Gohman 
5096a31a0d6SSam Clegg   // Relocation other than R_WEBASSEMBLY_TYPE_INDEX_LEB,
5106a31a0d6SSam Clegg   // R_WEBASSEMBLY_SECTION_OFFSET_I32 or R_WEBASSEMBLY_FUNCTION_OFFSET_I32
5116a31a0d6SSam Clegg   // are currently required to be against a named symbol.
512b7a5469cSSam Clegg   // TODO(sbc): Add support for relocations against unnamed temporaries such
513b7a5469cSSam Clegg   // as those generated by llvm's `blockaddress`.
514b7a5469cSSam Clegg   // See: test/MC/WebAssembly/blockaddress.ll
5156a31a0d6SSam Clegg   if (SymA->getName().empty() &&
5166a31a0d6SSam Clegg       !(Type == wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB ||
5176a31a0d6SSam Clegg         Type == wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32 ||
5186a31a0d6SSam Clegg         Type == wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32))
519b7a5469cSSam Clegg     report_fatal_error("relocations against un-named temporaries are not yet "
520b7a5469cSSam Clegg                        "supported by wasm");
521b7a5469cSSam Clegg 
5226a31a0d6SSam Clegg   if (FixupSection.isWasmData()) {
523d934cb88SDan Gohman     DataRelocations.push_back(Rec);
5246a31a0d6SSam Clegg   } else if (FixupSection.getKind().isText()) {
52512fd3da9SSam Clegg     CodeRelocations.push_back(Rec);
5266a31a0d6SSam Clegg   } else if (FixupSection.getKind().isMetadata()) {
5276a31a0d6SSam Clegg     assert(FixupSection.getSectionName().startswith(".debug_"));
5286a31a0d6SSam Clegg     CustomSectionsRelocations[&FixupSection].push_back(Rec);
5296a31a0d6SSam Clegg   } else {
53012fd3da9SSam Clegg     llvm_unreachable("unexpected section type");
531d934cb88SDan Gohman   }
5326a31a0d6SSam Clegg }
533d934cb88SDan Gohman 
534d934cb88SDan Gohman // Write X as an (unsigned) LEB value at offset Offset in Stream, padded
535d934cb88SDan Gohman // to allow patching.
536d934cb88SDan Gohman static void
537d934cb88SDan Gohman WritePatchableLEB(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
538d934cb88SDan Gohman   uint8_t Buffer[5];
53966a99e41SSam Clegg   unsigned SizeLen = encodeULEB128(X, Buffer, 5);
540d934cb88SDan Gohman   assert(SizeLen == 5);
541d934cb88SDan Gohman   Stream.pwrite((char *)Buffer, SizeLen, Offset);
542d934cb88SDan Gohman }
543d934cb88SDan Gohman 
544d934cb88SDan Gohman // Write X as an signed LEB value at offset Offset in Stream, padded
545d934cb88SDan Gohman // to allow patching.
546d934cb88SDan Gohman static void
547d934cb88SDan Gohman WritePatchableSLEB(raw_pwrite_stream &Stream, int32_t X, uint64_t Offset) {
548d934cb88SDan Gohman   uint8_t Buffer[5];
54966a99e41SSam Clegg   unsigned SizeLen = encodeSLEB128(X, Buffer, 5);
550d934cb88SDan Gohman   assert(SizeLen == 5);
551d934cb88SDan Gohman   Stream.pwrite((char *)Buffer, SizeLen, Offset);
552d934cb88SDan Gohman }
553d934cb88SDan Gohman 
554d934cb88SDan Gohman // Write X as a plain integer value at offset Offset in Stream.
555d934cb88SDan Gohman static void WriteI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
556d934cb88SDan Gohman   uint8_t Buffer[4];
557d934cb88SDan Gohman   support::endian::write32le(Buffer, X);
558d934cb88SDan Gohman   Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
559d934cb88SDan Gohman }
560d934cb88SDan Gohman 
561aff1c4dfSSam Clegg static const MCSymbolWasm* ResolveSymbol(const MCSymbolWasm& Symbol) {
562aff1c4dfSSam Clegg   if (Symbol.isVariable()) {
563aff1c4dfSSam Clegg     const MCExpr *Expr = Symbol.getVariableValue();
564aff1c4dfSSam Clegg     auto *Inner = cast<MCSymbolRefExpr>(Expr);
565aff1c4dfSSam Clegg     return cast<MCSymbolWasm>(&Inner->getSymbol());
566aff1c4dfSSam Clegg   }
567aff1c4dfSSam Clegg   return &Symbol;
568aff1c4dfSSam Clegg }
569aff1c4dfSSam Clegg 
570d934cb88SDan Gohman // Compute a value to write into the code at the location covered
57160ec3034SSam Clegg // by RelEntry. This value isn't used by the static linker; it just serves
57260ec3034SSam Clegg // to make the object format more readable and more likely to be directly
57360ec3034SSam Clegg // useable.
5747c395943SSam Clegg uint32_t
5757c395943SSam Clegg WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) {
57660ec3034SSam Clegg   switch (RelEntry.Type) {
57760ec3034SSam Clegg   case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
578f9edbe95SSam Clegg   case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: {
579f9edbe95SSam Clegg     // Provisional value is table address of the resolved symbol itself
580f9edbe95SSam Clegg     const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
581f9edbe95SSam Clegg     assert(Sym->isFunction());
582f9edbe95SSam Clegg     return TableIndices[Sym];
583f9edbe95SSam Clegg   }
58460ec3034SSam Clegg   case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
5856c899ba6SSam Clegg     // Provisional value is same as the index
58660ec3034SSam Clegg     return getRelocationIndexValue(RelEntry);
5876c899ba6SSam Clegg   case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
5886c899ba6SSam Clegg   case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
5896c899ba6SSam Clegg     // Provisional value is function/global Wasm index
5906c899ba6SSam Clegg     if (!WasmIndices.count(RelEntry.Symbol))
5916c899ba6SSam Clegg       report_fatal_error("symbol not found in wasm index space: " +
5926c899ba6SSam Clegg                          RelEntry.Symbol->getName());
5936c899ba6SSam Clegg     return WasmIndices[RelEntry.Symbol];
5946a31a0d6SSam Clegg   case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32: {
5956a31a0d6SSam Clegg     const auto &Section =
5966a31a0d6SSam Clegg         static_cast<const MCSectionWasm &>(RelEntry.Symbol->getSection());
5976a31a0d6SSam Clegg     return Section.getSectionOffset() + RelEntry.Addend;
5986a31a0d6SSam Clegg   }
5996a31a0d6SSam Clegg   case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32: {
6006a31a0d6SSam Clegg     const auto &Section = *CustomSectionSymbols.find(RelEntry.Symbol)->second;
6016a31a0d6SSam Clegg     return Section.getSectionOffset() + RelEntry.Addend;
6026a31a0d6SSam Clegg   }
60360ec3034SSam Clegg   case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
60460ec3034SSam Clegg   case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
60560ec3034SSam Clegg   case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: {
606f9edbe95SSam Clegg     // Provisional value is address of the global
60760ec3034SSam Clegg     const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
608270ed1b3SSam Clegg     // For undefined symbols, use zero
609cd65f698SSam Clegg     if (!Sym->isDefined())
610270ed1b3SSam Clegg       return 0;
6116c899ba6SSam Clegg     const wasm::WasmDataReference &Ref = DataLocations[Sym];
6126c899ba6SSam Clegg     const WasmDataSegment &Segment = DataSegments[Ref.Segment];
613d934cb88SDan Gohman     // Ignore overflow. LLVM allows address arithmetic to silently wrap.
6146c899ba6SSam Clegg     return Segment.Offset + Ref.Offset + RelEntry.Addend;
61560ec3034SSam Clegg   }
61660ec3034SSam Clegg   default:
61760ec3034SSam Clegg     llvm_unreachable("invalid relocation type");
61860ec3034SSam Clegg   }
619d934cb88SDan Gohman }
620d934cb88SDan Gohman 
621759631c7SSam Clegg static void addData(SmallVectorImpl<char> &DataBytes,
62263ebb813SSam Clegg                     MCSectionWasm &DataSection) {
623759631c7SSam Clegg   DEBUG(errs() << "addData: " << DataSection.getSectionName() << "\n");
624759631c7SSam Clegg 
62563ebb813SSam Clegg   DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
62663ebb813SSam Clegg 
627759631c7SSam Clegg   for (const MCFragment &Frag : DataSection) {
628759631c7SSam Clegg     if (Frag.hasInstructions())
629759631c7SSam Clegg       report_fatal_error("only data supported in data sections");
630759631c7SSam Clegg 
631759631c7SSam Clegg     if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
632759631c7SSam Clegg       if (Align->getValueSize() != 1)
633759631c7SSam Clegg         report_fatal_error("only byte values supported for alignment");
634759631c7SSam Clegg       // If nops are requested, use zeros, as this is the data section.
635759631c7SSam Clegg       uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
636759631c7SSam Clegg       uint64_t Size = std::min<uint64_t>(alignTo(DataBytes.size(),
637759631c7SSam Clegg                                                  Align->getAlignment()),
638759631c7SSam Clegg                                          DataBytes.size() +
639759631c7SSam Clegg                                              Align->getMaxBytesToEmit());
640759631c7SSam Clegg       DataBytes.resize(Size, Value);
641759631c7SSam Clegg     } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
642d707c370SRafael Espindola       int64_t Size;
643d707c370SRafael Espindola       if (!Fill->getSize().evaluateAsAbsolute(Size))
644d707c370SRafael Espindola         llvm_unreachable("The fill should be an assembler constant");
645d707c370SRafael Espindola       DataBytes.insert(DataBytes.end(), Size, Fill->getValue());
646759631c7SSam Clegg     } else {
647759631c7SSam Clegg       const auto &DataFrag = cast<MCDataFragment>(Frag);
648759631c7SSam Clegg       const SmallVectorImpl<char> &Contents = DataFrag.getContents();
649759631c7SSam Clegg 
650759631c7SSam Clegg       DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
651759631c7SSam Clegg     }
652759631c7SSam Clegg   }
653759631c7SSam Clegg 
654759631c7SSam Clegg   DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
655759631c7SSam Clegg }
656759631c7SSam Clegg 
65760ec3034SSam Clegg uint32_t
65860ec3034SSam Clegg WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
65960ec3034SSam Clegg   if (RelEntry.Type == wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB) {
660b7787fd0SSam Clegg     if (!TypeIndices.count(RelEntry.Symbol))
661b7787fd0SSam Clegg       report_fatal_error("symbol not found in type index space: " +
662b7787fd0SSam Clegg                          RelEntry.Symbol->getName());
663acd7d2b0SSam Clegg     return TypeIndices[RelEntry.Symbol];
664acd7d2b0SSam Clegg   }
66560ec3034SSam Clegg 
66660ec3034SSam Clegg   if (!SymbolIndices.count(RelEntry.Symbol))
6676c899ba6SSam Clegg     report_fatal_error("symbol not found in symbol index space: " +
66860ec3034SSam Clegg                        RelEntry.Symbol->getName());
66960ec3034SSam Clegg   return SymbolIndices[RelEntry.Symbol];
670acd7d2b0SSam Clegg }
671acd7d2b0SSam Clegg 
672d934cb88SDan Gohman // Apply the portions of the relocation records that we can handle ourselves
673d934cb88SDan Gohman // directly.
674acd7d2b0SSam Clegg void WasmObjectWriter::applyRelocations(
675acd7d2b0SSam Clegg     ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
676acd7d2b0SSam Clegg   raw_pwrite_stream &Stream = getStream();
677d934cb88SDan Gohman   for (const WasmRelocationEntry &RelEntry : Relocations) {
678d934cb88SDan Gohman     uint64_t Offset = ContentsOffset +
679d934cb88SDan Gohman                       RelEntry.FixupSection->getSectionOffset() +
680d934cb88SDan Gohman                       RelEntry.Offset;
681d934cb88SDan Gohman 
682b7787fd0SSam Clegg     DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
68360ec3034SSam Clegg     uint32_t Value = getProvisionalValue(RelEntry);
68460ec3034SSam Clegg 
685acd7d2b0SSam Clegg     switch (RelEntry.Type) {
686acd7d2b0SSam Clegg     case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
6879d24fb7fSSam Clegg     case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
68860ec3034SSam Clegg     case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
68960ec3034SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
690d934cb88SDan Gohman       WritePatchableLEB(Stream, Value, Offset);
691d934cb88SDan Gohman       break;
69260ec3034SSam Clegg     case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
69360ec3034SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
6946a31a0d6SSam Clegg     case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32:
6956a31a0d6SSam Clegg     case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32:
696d934cb88SDan Gohman       WriteI32(Stream, Value, Offset);
697d934cb88SDan Gohman       break;
69860ec3034SSam Clegg     case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
69960ec3034SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
70060ec3034SSam Clegg       WritePatchableSLEB(Stream, Value, Offset);
70160ec3034SSam Clegg       break;
702d934cb88SDan Gohman     default:
7039d24fb7fSSam Clegg       llvm_unreachable("invalid relocation type");
704d934cb88SDan Gohman     }
705d934cb88SDan Gohman   }
70618eafb6cSDan Gohman }
70718eafb6cSDan Gohman 
7089e15f359SSam Clegg void WasmObjectWriter::writeTypeSection(
709457fb0b4SSam Clegg     ArrayRef<WasmFunctionType> FunctionTypes) {
7109e15f359SSam Clegg   if (FunctionTypes.empty())
7119e15f359SSam Clegg     return;
7129e15f359SSam Clegg 
7139e15f359SSam Clegg   SectionBookkeeping Section;
7149e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_TYPE);
7159e15f359SSam Clegg 
7169e15f359SSam Clegg   encodeULEB128(FunctionTypes.size(), getStream());
7179e15f359SSam Clegg 
7189e15f359SSam Clegg   for (const WasmFunctionType &FuncTy : FunctionTypes) {
71903e101f1SSam Clegg     write8(wasm::WASM_TYPE_FUNC);
7209e15f359SSam Clegg     encodeULEB128(FuncTy.Params.size(), getStream());
7219e15f359SSam Clegg     for (wasm::ValType Ty : FuncTy.Params)
7229e15f359SSam Clegg       writeValueType(Ty);
7239e15f359SSam Clegg     encodeULEB128(FuncTy.Returns.size(), getStream());
7249e15f359SSam Clegg     for (wasm::ValType Ty : FuncTy.Returns)
7259e15f359SSam Clegg       writeValueType(Ty);
7269e15f359SSam Clegg   }
7279e15f359SSam Clegg 
7289e15f359SSam Clegg   endSection(Section);
7299e15f359SSam Clegg }
7309e15f359SSam Clegg 
7318defa952SSam Clegg void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports,
732f950b24aSSam Clegg                                           uint32_t DataSize,
733f950b24aSSam Clegg                                           uint32_t NumElements) {
7349e15f359SSam Clegg   if (Imports.empty())
7359e15f359SSam Clegg     return;
7369e15f359SSam Clegg 
737f950b24aSSam Clegg   uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
738f950b24aSSam Clegg 
7399e15f359SSam Clegg   SectionBookkeeping Section;
7409e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_IMPORT);
7419e15f359SSam Clegg 
7429e15f359SSam Clegg   encodeULEB128(Imports.size(), getStream());
7438defa952SSam Clegg   for (const wasm::WasmImport &Import : Imports) {
7448defa952SSam Clegg     writeString(Import.Module);
7458defa952SSam Clegg     writeString(Import.Field);
74603e101f1SSam Clegg     write8(Import.Kind);
7479e15f359SSam Clegg 
7489e15f359SSam Clegg     switch (Import.Kind) {
7499e15f359SSam Clegg     case wasm::WASM_EXTERNAL_FUNCTION:
7508defa952SSam Clegg       encodeULEB128(Import.SigIndex, getStream());
7519e15f359SSam Clegg       break;
7529e15f359SSam Clegg     case wasm::WASM_EXTERNAL_GLOBAL:
75303e101f1SSam Clegg       write8(Import.Global.Type);
75403e101f1SSam Clegg       write8(Import.Global.Mutable ? 1 : 0);
7559e15f359SSam Clegg       break;
756f950b24aSSam Clegg     case wasm::WASM_EXTERNAL_MEMORY:
757f950b24aSSam Clegg       encodeULEB128(0, getStream()); // flags
758f950b24aSSam Clegg       encodeULEB128(NumPages, getStream()); // initial
759f950b24aSSam Clegg       break;
760f950b24aSSam Clegg     case wasm::WASM_EXTERNAL_TABLE:
76103e101f1SSam Clegg       write8(Import.Table.ElemType);
762f950b24aSSam Clegg       encodeULEB128(0, getStream()); // flags
763f950b24aSSam Clegg       encodeULEB128(NumElements, getStream()); // initial
764f950b24aSSam Clegg       break;
7659e15f359SSam Clegg     default:
7669e15f359SSam Clegg       llvm_unreachable("unsupported import kind");
7679e15f359SSam Clegg     }
7689e15f359SSam Clegg   }
7699e15f359SSam Clegg 
7709e15f359SSam Clegg   endSection(Section);
7719e15f359SSam Clegg }
7729e15f359SSam Clegg 
773457fb0b4SSam Clegg void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
7749e15f359SSam Clegg   if (Functions.empty())
7759e15f359SSam Clegg     return;
7769e15f359SSam Clegg 
7779e15f359SSam Clegg   SectionBookkeeping Section;
7789e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_FUNCTION);
7799e15f359SSam Clegg 
7809e15f359SSam Clegg   encodeULEB128(Functions.size(), getStream());
7819e15f359SSam Clegg   for (const WasmFunction &Func : Functions)
7829e15f359SSam Clegg     encodeULEB128(Func.Type, getStream());
7839e15f359SSam Clegg 
7849e15f359SSam Clegg   endSection(Section);
7859e15f359SSam Clegg }
7869e15f359SSam Clegg 
7877c395943SSam Clegg void WasmObjectWriter::writeGlobalSection() {
7889e15f359SSam Clegg   if (Globals.empty())
7899e15f359SSam Clegg     return;
7909e15f359SSam Clegg 
7919e15f359SSam Clegg   SectionBookkeeping Section;
7929e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_GLOBAL);
7939e15f359SSam Clegg 
7949e15f359SSam Clegg   encodeULEB128(Globals.size(), getStream());
7959e15f359SSam Clegg   for (const WasmGlobal &Global : Globals) {
7966e7f1826SSam Clegg     writeValueType(static_cast<wasm::ValType>(Global.Type.Type));
7976e7f1826SSam Clegg     write8(Global.Type.Mutable);
7989e15f359SSam Clegg 
7999e15f359SSam Clegg     write8(wasm::WASM_OPCODE_I32_CONST);
8006e7f1826SSam Clegg     encodeSLEB128(Global.InitialValue, getStream());
8019e15f359SSam Clegg     write8(wasm::WASM_OPCODE_END);
8029e15f359SSam Clegg   }
8039e15f359SSam Clegg 
8049e15f359SSam Clegg   endSection(Section);
8059e15f359SSam Clegg }
8069e15f359SSam Clegg 
8078defa952SSam Clegg void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) {
8089e15f359SSam Clegg   if (Exports.empty())
8099e15f359SSam Clegg     return;
8109e15f359SSam Clegg 
8119e15f359SSam Clegg   SectionBookkeeping Section;
8129e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_EXPORT);
8139e15f359SSam Clegg 
8149e15f359SSam Clegg   encodeULEB128(Exports.size(), getStream());
8158defa952SSam Clegg   for (const wasm::WasmExport &Export : Exports) {
8168defa952SSam Clegg     writeString(Export.Name);
81703e101f1SSam Clegg     write8(Export.Kind);
8189e15f359SSam Clegg     encodeULEB128(Export.Index, getStream());
8199e15f359SSam Clegg   }
8209e15f359SSam Clegg 
8219e15f359SSam Clegg   endSection(Section);
8229e15f359SSam Clegg }
8239e15f359SSam Clegg 
824457fb0b4SSam Clegg void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
8259e15f359SSam Clegg   if (TableElems.empty())
8269e15f359SSam Clegg     return;
8279e15f359SSam Clegg 
8289e15f359SSam Clegg   SectionBookkeeping Section;
8299e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_ELEM);
8309e15f359SSam Clegg 
8319e15f359SSam Clegg   encodeULEB128(1, getStream()); // number of "segments"
8329e15f359SSam Clegg   encodeULEB128(0, getStream()); // the table index
8339e15f359SSam Clegg 
8349e15f359SSam Clegg   // init expr for starting offset
8359e15f359SSam Clegg   write8(wasm::WASM_OPCODE_I32_CONST);
83630e1bbc1SSam Clegg   encodeSLEB128(kInitialTableOffset, getStream());
8379e15f359SSam Clegg   write8(wasm::WASM_OPCODE_END);
8389e15f359SSam Clegg 
8399e15f359SSam Clegg   encodeULEB128(TableElems.size(), getStream());
8409e15f359SSam Clegg   for (uint32_t Elem : TableElems)
8419e15f359SSam Clegg     encodeULEB128(Elem, getStream());
8429e15f359SSam Clegg 
8439e15f359SSam Clegg   endSection(Section);
8449e15f359SSam Clegg }
8459e15f359SSam Clegg 
846457fb0b4SSam Clegg void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
847457fb0b4SSam Clegg                                         const MCAsmLayout &Layout,
848457fb0b4SSam Clegg                                         ArrayRef<WasmFunction> Functions) {
8499e15f359SSam Clegg   if (Functions.empty())
8509e15f359SSam Clegg     return;
8519e15f359SSam Clegg 
8529e15f359SSam Clegg   SectionBookkeeping Section;
8539e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_CODE);
8546f08c84aSSam Clegg   CodeSectionIndex = Section.Index;
8559e15f359SSam Clegg 
8569e15f359SSam Clegg   encodeULEB128(Functions.size(), getStream());
8579e15f359SSam Clegg 
8589e15f359SSam Clegg   for (const WasmFunction &Func : Functions) {
859fe6414b0SSam Clegg     auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
8609e15f359SSam Clegg 
8619e15f359SSam Clegg     int64_t Size = 0;
8629e15f359SSam Clegg     if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
8639e15f359SSam Clegg       report_fatal_error(".size expression must be evaluatable");
8649e15f359SSam Clegg 
8659e15f359SSam Clegg     encodeULEB128(Size, getStream());
866fe6414b0SSam Clegg     FuncSection.setSectionOffset(getStream().tell() - Section.ContentsOffset);
8679e15f359SSam Clegg     Asm.writeSectionData(&FuncSection, Layout);
8689e15f359SSam Clegg   }
8699e15f359SSam Clegg 
8709e15f359SSam Clegg   // Apply fixups.
871acd7d2b0SSam Clegg   applyRelocations(CodeRelocations, Section.ContentsOffset);
8729e15f359SSam Clegg 
8739e15f359SSam Clegg   endSection(Section);
8749e15f359SSam Clegg }
8759e15f359SSam Clegg 
8766c899ba6SSam Clegg void WasmObjectWriter::writeDataSection() {
8776c899ba6SSam Clegg   if (DataSegments.empty())
8787c395943SSam Clegg     return;
8799e15f359SSam Clegg 
8809e15f359SSam Clegg   SectionBookkeeping Section;
8819e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_DATA);
8826f08c84aSSam Clegg   DataSectionIndex = Section.Index;
8839e15f359SSam Clegg 
8846c899ba6SSam Clegg   encodeULEB128(DataSegments.size(), getStream()); // count
8857c395943SSam Clegg 
8866c899ba6SSam Clegg   for (const WasmDataSegment &Segment : DataSegments) {
8879e15f359SSam Clegg     encodeULEB128(0, getStream()); // memory index
8889e15f359SSam Clegg     write8(wasm::WASM_OPCODE_I32_CONST);
8897c395943SSam Clegg     encodeSLEB128(Segment.Offset, getStream()); // offset
8909e15f359SSam Clegg     write8(wasm::WASM_OPCODE_END);
8917c395943SSam Clegg     encodeULEB128(Segment.Data.size(), getStream()); // size
8927c395943SSam Clegg     Segment.Section->setSectionOffset(getStream().tell() - Section.ContentsOffset);
8937c395943SSam Clegg     writeBytes(Segment.Data); // data
8947c395943SSam Clegg   }
8959e15f359SSam Clegg 
8969e15f359SSam Clegg   // Apply fixups.
8977c395943SSam Clegg   applyRelocations(DataRelocations, Section.ContentsOffset);
8989e15f359SSam Clegg 
8999e15f359SSam Clegg   endSection(Section);
9009e15f359SSam Clegg }
9019e15f359SSam Clegg 
9026f08c84aSSam Clegg void WasmObjectWriter::writeRelocSection(
9036f08c84aSSam Clegg     uint32_t SectionIndex, StringRef Name,
9046f08c84aSSam Clegg     ArrayRef<WasmRelocationEntry> Relocations) {
9059e15f359SSam Clegg   // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
9069e15f359SSam Clegg   // for descriptions of the reloc sections.
9079e15f359SSam Clegg 
9086f08c84aSSam Clegg   if (Relocations.empty())
9099e15f359SSam Clegg     return;
9109e15f359SSam Clegg 
9119e15f359SSam Clegg   SectionBookkeeping Section;
9126f08c84aSSam Clegg   startCustomSection(Section, std::string("reloc.") + Name.str());
9139e15f359SSam Clegg 
9146f08c84aSSam Clegg   raw_pwrite_stream &Stream = getStream();
9159e15f359SSam Clegg 
9166f08c84aSSam Clegg   encodeULEB128(SectionIndex, Stream);
9176f08c84aSSam Clegg   encodeULEB128(Relocations.size(), Stream);
9186f08c84aSSam Clegg   for (const WasmRelocationEntry& RelEntry : Relocations) {
9196f08c84aSSam Clegg     uint64_t Offset = RelEntry.Offset +
9206f08c84aSSam Clegg                       RelEntry.FixupSection->getSectionOffset();
9216f08c84aSSam Clegg     uint32_t Index = getRelocationIndexValue(RelEntry);
9229e15f359SSam Clegg 
9236f08c84aSSam Clegg     write8(RelEntry.Type);
9246f08c84aSSam Clegg     encodeULEB128(Offset, Stream);
9256f08c84aSSam Clegg     encodeULEB128(Index, Stream);
9266f08c84aSSam Clegg     if (RelEntry.hasAddend())
9276f08c84aSSam Clegg       encodeSLEB128(RelEntry.Addend, Stream);
9289e15f359SSam Clegg   }
9299e15f359SSam Clegg 
9309e15f359SSam Clegg   endSection(Section);
9319e15f359SSam Clegg }
9329e15f359SSam Clegg 
9336a31a0d6SSam Clegg void WasmObjectWriter::writeCustomRelocSections() {
9346a31a0d6SSam Clegg   for (const auto &Sec : CustomSections) {
9356a31a0d6SSam Clegg     auto &Relocations = CustomSectionsRelocations[Sec.Section];
9366a31a0d6SSam Clegg     writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations);
9376a31a0d6SSam Clegg   }
9386a31a0d6SSam Clegg }
9396a31a0d6SSam Clegg 
9409e15f359SSam Clegg void WasmObjectWriter::writeLinkingMetaDataSection(
94186b4a09aSSam Clegg     ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
942ea7caceeSSam Clegg     ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
943ea7caceeSSam Clegg     const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) {
9449e15f359SSam Clegg   SectionBookkeeping Section;
9452322a937SSam Clegg   startCustomSection(Section, "linking");
9466bb5a41fSSam Clegg   encodeULEB128(wasm::WasmMetadataVersion, getStream());
9479e15f359SSam Clegg 
9486bb5a41fSSam Clegg   SectionBookkeeping SubSection;
9496c899ba6SSam Clegg   if (SymbolInfos.size() != 0) {
9506c899ba6SSam Clegg     startSection(SubSection, wasm::WASM_SYMBOL_TABLE);
9516c899ba6SSam Clegg     encodeULEB128(SymbolInfos.size(), getStream());
9526c899ba6SSam Clegg     for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) {
9536c899ba6SSam Clegg       encodeULEB128(Sym.Kind, getStream());
9546c899ba6SSam Clegg       encodeULEB128(Sym.Flags, getStream());
9556c899ba6SSam Clegg       switch (Sym.Kind) {
9566c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_FUNCTION:
9576c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_GLOBAL:
9586c899ba6SSam Clegg         encodeULEB128(Sym.ElementIndex, getStream());
9596c899ba6SSam Clegg         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0)
9606c899ba6SSam Clegg           writeString(Sym.Name);
9616c899ba6SSam Clegg         break;
9626c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_DATA:
9636c899ba6SSam Clegg         writeString(Sym.Name);
9646c899ba6SSam Clegg         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) {
9656c899ba6SSam Clegg           encodeULEB128(Sym.DataRef.Segment, getStream());
9666c899ba6SSam Clegg           encodeULEB128(Sym.DataRef.Offset, getStream());
9676c899ba6SSam Clegg           encodeULEB128(Sym.DataRef.Size, getStream());
9686c899ba6SSam Clegg         }
9696c899ba6SSam Clegg         break;
9706a31a0d6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_SECTION: {
9716a31a0d6SSam Clegg         const uint32_t SectionIndex =
9726a31a0d6SSam Clegg             CustomSections[Sym.ElementIndex].OutputIndex;
9736a31a0d6SSam Clegg         encodeULEB128(SectionIndex, getStream());
9746a31a0d6SSam Clegg         break;
9756a31a0d6SSam Clegg       }
9766c899ba6SSam Clegg       default:
9776c899ba6SSam Clegg         llvm_unreachable("unexpected kind");
9786c899ba6SSam Clegg       }
979b7787fd0SSam Clegg     }
980b7787fd0SSam Clegg     endSection(SubSection);
981b7787fd0SSam Clegg   }
9829e15f359SSam Clegg 
9836c899ba6SSam Clegg   if (DataSegments.size()) {
98463ebb813SSam Clegg     startSection(SubSection, wasm::WASM_SEGMENT_INFO);
9856c899ba6SSam Clegg     encodeULEB128(DataSegments.size(), getStream());
9866c899ba6SSam Clegg     for (const WasmDataSegment &Segment : DataSegments) {
987d95ed959SSam Clegg       writeString(Segment.Name);
98863ebb813SSam Clegg       encodeULEB128(Segment.Alignment, getStream());
98963ebb813SSam Clegg       encodeULEB128(Segment.Flags, getStream());
99063ebb813SSam Clegg     }
991d95ed959SSam Clegg     endSection(SubSection);
992d95ed959SSam Clegg   }
993d95ed959SSam Clegg 
994bafe6902SSam Clegg   if (!InitFuncs.empty()) {
995bafe6902SSam Clegg     startSection(SubSection, wasm::WASM_INIT_FUNCS);
996bafe6902SSam Clegg     encodeULEB128(InitFuncs.size(), getStream());
997bafe6902SSam Clegg     for (auto &StartFunc : InitFuncs) {
998bafe6902SSam Clegg       encodeULEB128(StartFunc.first, getStream()); // priority
999bafe6902SSam Clegg       encodeULEB128(StartFunc.second, getStream()); // function index
1000bafe6902SSam Clegg     }
1001bafe6902SSam Clegg     endSection(SubSection);
1002bafe6902SSam Clegg   }
1003bafe6902SSam Clegg 
1004ea7caceeSSam Clegg   if (Comdats.size()) {
1005ea7caceeSSam Clegg     startSection(SubSection, wasm::WASM_COMDAT_INFO);
1006ea7caceeSSam Clegg     encodeULEB128(Comdats.size(), getStream());
1007ea7caceeSSam Clegg     for (const auto &C : Comdats) {
1008ea7caceeSSam Clegg       writeString(C.first);
1009ea7caceeSSam Clegg       encodeULEB128(0, getStream()); // flags for future use
1010ea7caceeSSam Clegg       encodeULEB128(C.second.size(), getStream());
1011ea7caceeSSam Clegg       for (const WasmComdatEntry &Entry : C.second) {
1012ea7caceeSSam Clegg         encodeULEB128(Entry.Kind, getStream());
1013ea7caceeSSam Clegg         encodeULEB128(Entry.Index, getStream());
1014ea7caceeSSam Clegg       }
1015ea7caceeSSam Clegg     }
1016ea7caceeSSam Clegg     endSection(SubSection);
1017ea7caceeSSam Clegg   }
1018ea7caceeSSam Clegg 
10199e15f359SSam Clegg   endSection(Section);
10209e15f359SSam Clegg }
10219e15f359SSam Clegg 
10226a31a0d6SSam Clegg void WasmObjectWriter::writeCustomSections(const MCAssembler &Asm,
10236a31a0d6SSam Clegg                                            const MCAsmLayout &Layout) {
10246a31a0d6SSam Clegg   for (auto &CustomSection : CustomSections) {
1025cfd44a2eSSam Clegg     SectionBookkeeping Section;
10266a31a0d6SSam Clegg     auto *Sec = CustomSection.Section;
10272322a937SSam Clegg     startCustomSection(Section, CustomSection.Name);
10286a31a0d6SSam Clegg 
10296a31a0d6SSam Clegg     Sec->setSectionOffset(getStream().tell() - Section.ContentsOffset);
10306a31a0d6SSam Clegg     Asm.writeSectionData(Sec, Layout);
10316a31a0d6SSam Clegg 
10326a31a0d6SSam Clegg     CustomSection.OutputContentsOffset = Section.ContentsOffset;
10336a31a0d6SSam Clegg     CustomSection.OutputIndex = Section.Index;
10346a31a0d6SSam Clegg 
1035cfd44a2eSSam Clegg     endSection(Section);
1036cfd44a2eSSam Clegg   }
1037cfd44a2eSSam Clegg }
1038cfd44a2eSSam Clegg 
10396a31a0d6SSam Clegg void WasmObjectWriter::updateCustomSectionRelocations(
10406a31a0d6SSam Clegg     const SmallVector<WasmFunction, 4> &Functions, const MCAsmLayout &Layout) {
10416a31a0d6SSam Clegg   std::map<const MCSection *, const MCSymbolWasm *> SectionSymbols;
10426a31a0d6SSam Clegg   for (const auto &P : CustomSectionSymbols)
10436a31a0d6SSam Clegg     SectionSymbols[P.second] = P.first;
10446a31a0d6SSam Clegg   std::map<const MCSection *, const MCSymbolWasm *> FuncSymbols;
10456a31a0d6SSam Clegg   for (const auto &FuncInfo : Functions)
10466a31a0d6SSam Clegg     FuncSymbols[&FuncInfo.Sym->getSection()] = FuncInfo.Sym;
10476a31a0d6SSam Clegg 
10486a31a0d6SSam Clegg   // Patch relocation records for R_WEBASSEMBLY_FUNCTION_OFFSET_I32 and
10496a31a0d6SSam Clegg   // R_WEBASSEMBLY_SECTION_OFFSET_I32. The Addend is stuffed the offset from
10506a31a0d6SSam Clegg   // the beginning of the function or custom section -- all such relocations
10516a31a0d6SSam Clegg   // target the function or custom section starts.
10526a31a0d6SSam Clegg   for (auto &Section : CustomSections) {
10536a31a0d6SSam Clegg     auto &Relocations = CustomSectionsRelocations[Section.Section];
10546a31a0d6SSam Clegg     for (WasmRelocationEntry &RelEntry : Relocations) {
10556a31a0d6SSam Clegg       switch (RelEntry.Type) {
10566a31a0d6SSam Clegg       case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32: {
10576a31a0d6SSam Clegg         assert(RelEntry.hasAddend());
10586a31a0d6SSam Clegg         auto &Section =
10596a31a0d6SSam Clegg             static_cast<MCSectionWasm &>(RelEntry.Symbol->getSection());
10606a31a0d6SSam Clegg         RelEntry.Addend += Layout.getSymbolOffset(*RelEntry.Symbol);
10616a31a0d6SSam Clegg         RelEntry.Symbol = FuncSymbols[&Section];
10626a31a0d6SSam Clegg         break;
10636a31a0d6SSam Clegg       }
10646a31a0d6SSam Clegg       case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32: {
10656a31a0d6SSam Clegg         assert(RelEntry.hasAddend());
10666a31a0d6SSam Clegg         auto &Section =
10676a31a0d6SSam Clegg             static_cast<MCSectionWasm &>(RelEntry.Symbol->getSection());
10686a31a0d6SSam Clegg         RelEntry.Addend += Layout.getSymbolOffset(*RelEntry.Symbol);
10696a31a0d6SSam Clegg         RelEntry.Symbol = SectionSymbols[&Section];
10706a31a0d6SSam Clegg         break;
10716a31a0d6SSam Clegg       }
10726a31a0d6SSam Clegg       default:
10736a31a0d6SSam Clegg         break;
10746a31a0d6SSam Clegg       }
10756a31a0d6SSam Clegg     }
10766a31a0d6SSam Clegg 
10776a31a0d6SSam Clegg     // Apply fixups.
10786a31a0d6SSam Clegg     applyRelocations(Relocations, Section.OutputContentsOffset);
10796a31a0d6SSam Clegg   }
10806a31a0d6SSam Clegg }
10816a31a0d6SSam Clegg 
10825e3d33a7SSam Clegg uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm& Symbol) {
10835e3d33a7SSam Clegg   assert(Symbol.isFunction());
10845e3d33a7SSam Clegg   assert(TypeIndices.count(&Symbol));
10855e3d33a7SSam Clegg   return TypeIndices[&Symbol];
10865e3d33a7SSam Clegg }
10875e3d33a7SSam Clegg 
10885e3d33a7SSam Clegg uint32_t WasmObjectWriter::registerFunctionType(const MCSymbolWasm& Symbol) {
10895e3d33a7SSam Clegg   assert(Symbol.isFunction());
10905e3d33a7SSam Clegg 
10915e3d33a7SSam Clegg   WasmFunctionType F;
1092aff1c4dfSSam Clegg   const MCSymbolWasm* ResolvedSym = ResolveSymbol(Symbol);
10935e3d33a7SSam Clegg   F.Returns = ResolvedSym->getReturns();
10945e3d33a7SSam Clegg   F.Params = ResolvedSym->getParams();
10955e3d33a7SSam Clegg 
10965e3d33a7SSam Clegg   auto Pair =
10975e3d33a7SSam Clegg       FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size()));
10985e3d33a7SSam Clegg   if (Pair.second)
10995e3d33a7SSam Clegg     FunctionTypes.push_back(F);
11005e3d33a7SSam Clegg   TypeIndices[&Symbol] = Pair.first->second;
11015e3d33a7SSam Clegg 
11025e3d33a7SSam Clegg   DEBUG(dbgs() << "registerFunctionType: " << Symbol << " new:" << Pair.second << "\n");
11035e3d33a7SSam Clegg   DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
11045e3d33a7SSam Clegg   return Pair.first->second;
11055e3d33a7SSam Clegg }
11065e3d33a7SSam Clegg 
110718eafb6cSDan Gohman void WasmObjectWriter::writeObject(MCAssembler &Asm,
110818eafb6cSDan Gohman                                    const MCAsmLayout &Layout) {
1109b7787fd0SSam Clegg   DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
111082607f56SDan Gohman   MCContext &Ctx = Asm.getContext();
1111d934cb88SDan Gohman 
1112d934cb88SDan Gohman   // Collect information from the available symbols.
1113d934cb88SDan Gohman   SmallVector<WasmFunction, 4> Functions;
1114d934cb88SDan Gohman   SmallVector<uint32_t, 4> TableElems;
11158defa952SSam Clegg   SmallVector<wasm::WasmImport, 4> Imports;
11168defa952SSam Clegg   SmallVector<wasm::WasmExport, 4> Exports;
11176c899ba6SSam Clegg   SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos;
1118bafe6902SSam Clegg   SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
1119ea7caceeSSam Clegg   std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
11207c395943SSam Clegg   uint32_t DataSize = 0;
1121d934cb88SDan Gohman 
1122f950b24aSSam Clegg   // For now, always emit the memory import, since loads and stores are not
1123f950b24aSSam Clegg   // valid without it. In the future, we could perhaps be more clever and omit
1124f950b24aSSam Clegg   // it if there are no loads or stores.
1125f950b24aSSam Clegg   MCSymbolWasm *MemorySym =
1126f950b24aSSam Clegg       cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__linear_memory"));
11278defa952SSam Clegg   wasm::WasmImport MemImport;
11288defa952SSam Clegg   MemImport.Module = MemorySym->getModuleName();
11298defa952SSam Clegg   MemImport.Field = MemorySym->getName();
1130f950b24aSSam Clegg   MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
1131f950b24aSSam Clegg   Imports.push_back(MemImport);
1132f950b24aSSam Clegg 
1133f950b24aSSam Clegg   // For now, always emit the table section, since indirect calls are not
1134f950b24aSSam Clegg   // valid without it. In the future, we could perhaps be more clever and omit
1135f950b24aSSam Clegg   // it if there are no indirect calls.
1136f950b24aSSam Clegg   MCSymbolWasm *TableSym =
1137f950b24aSSam Clegg       cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__indirect_function_table"));
11388defa952SSam Clegg   wasm::WasmImport TableImport;
11398defa952SSam Clegg   TableImport.Module = TableSym->getModuleName();
11408defa952SSam Clegg   TableImport.Field = TableSym->getName();
1141f950b24aSSam Clegg   TableImport.Kind = wasm::WASM_EXTERNAL_TABLE;
11428defa952SSam Clegg   TableImport.Table.ElemType = wasm::WASM_TYPE_ANYFUNC;
1143f950b24aSSam Clegg   Imports.push_back(TableImport);
1144f950b24aSSam Clegg 
1145586320c0SNicholas Wilson   // Populate FunctionTypeIndices, 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 
115632ce5ca0SDan Gohman     if (WS.isTemporary())
115732ce5ca0SDan Gohman       continue;
115832ce5ca0SDan Gohman 
115932ce5ca0SDan Gohman     // If the symbol is not defined in this translation unit, import it.
11606c899ba6SSam Clegg     if (!WS.isDefined() && !WS.isComdat()) {
11616c899ba6SSam Clegg       if (WS.isFunction()) {
11628defa952SSam Clegg         wasm::WasmImport Import;
11638defa952SSam Clegg         Import.Module = WS.getModuleName();
11648defa952SSam Clegg         Import.Field = WS.getName();
116532ce5ca0SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
11668defa952SSam Clegg         Import.SigIndex = getFunctionType(WS);
11676c899ba6SSam Clegg         Imports.push_back(Import);
11686c899ba6SSam Clegg         WasmIndices[&WS] = NumFunctionImports++;
11696c899ba6SSam Clegg       } else if (WS.isGlobal()) {
117015f349f7SNicholas Wilson         if (WS.isWeak())
117115f349f7SNicholas Wilson           report_fatal_error("undefined global symbol cannot be weak");
117215f349f7SNicholas Wilson 
11736c899ba6SSam Clegg         wasm::WasmImport Import;
11746c899ba6SSam Clegg         Import.Module = WS.getModuleName();
11756c899ba6SSam Clegg         Import.Field = WS.getName();
117632ce5ca0SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
11776c899ba6SSam Clegg         Import.Global = WS.getGlobalType();
11786c899ba6SSam Clegg         Imports.push_back(Import);
11796c899ba6SSam Clegg         WasmIndices[&WS] = NumGlobalImports++;
118032ce5ca0SDan Gohman       }
118132ce5ca0SDan Gohman     }
118232ce5ca0SDan Gohman   }
118332ce5ca0SDan Gohman 
1184586320c0SNicholas Wilson   // Populate DataSegments, which must be done before populating DataLocations.
1185759631c7SSam Clegg   for (MCSection &Sec : Asm) {
1186759631c7SSam Clegg     auto &Section = static_cast<MCSectionWasm &>(Sec);
1187cfd44a2eSSam Clegg 
11886a31a0d6SSam Clegg     if (Section.getSectionName().startswith(".custom_section.")) {
1189cfd44a2eSSam Clegg       if (Section.getFragmentList().empty())
1190cfd44a2eSSam Clegg         continue;
1191cfd44a2eSSam Clegg       if (Section.getFragmentList().size() != 1)
1192cfd44a2eSSam Clegg         report_fatal_error(
1193cfd44a2eSSam Clegg             "only one .custom_section section fragment supported");
1194cfd44a2eSSam Clegg       const MCFragment &Frag = *Section.begin();
1195cfd44a2eSSam Clegg       if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1196cfd44a2eSSam Clegg         report_fatal_error("only data supported in .custom_section section");
1197cfd44a2eSSam Clegg       const auto &DataFrag = cast<MCDataFragment>(Frag);
1198cfd44a2eSSam Clegg       if (!DataFrag.getFixups().empty())
1199cfd44a2eSSam Clegg         report_fatal_error("fixups not supported in .custom_section section");
1200cfd44a2eSSam Clegg       StringRef UserName = Section.getSectionName().substr(16);
12016a31a0d6SSam Clegg       CustomSections.emplace_back(UserName, &Section);
1202cfd44a2eSSam Clegg       continue;
1203cfd44a2eSSam Clegg     }
1204cfd44a2eSSam Clegg 
120512fd3da9SSam Clegg     if (!Section.isWasmData())
1206759631c7SSam Clegg       continue;
1207759631c7SSam Clegg 
1208bafe6902SSam Clegg     // .init_array sections are handled specially elsewhere.
1209bafe6902SSam Clegg     if (cast<MCSectionWasm>(Sec).getSectionName().startswith(".init_array"))
1210bafe6902SSam Clegg       continue;
1211bafe6902SSam Clegg 
1212329e76d5SSam Clegg     uint32_t SegmentIndex = DataSegments.size();
1213759631c7SSam Clegg     DataSize = alignTo(DataSize, Section.getAlignment());
1214759631c7SSam Clegg     DataSegments.emplace_back();
1215759631c7SSam Clegg     WasmDataSegment &Segment = DataSegments.back();
1216d95ed959SSam Clegg     Segment.Name = Section.getSectionName();
1217759631c7SSam Clegg     Segment.Offset = DataSize;
1218759631c7SSam Clegg     Segment.Section = &Section;
121963ebb813SSam Clegg     addData(Segment.Data, Section);
122063ebb813SSam Clegg     Segment.Alignment = Section.getAlignment();
122163ebb813SSam Clegg     Segment.Flags = 0;
1222759631c7SSam Clegg     DataSize += Segment.Data.size();
12236c899ba6SSam Clegg     Section.setSegmentIndex(SegmentIndex);
1224ea7caceeSSam Clegg 
1225ea7caceeSSam Clegg     if (const MCSymbolWasm *C = Section.getGroup()) {
1226ea7caceeSSam Clegg       Comdats[C->getName()].emplace_back(
1227329e76d5SSam Clegg           WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
1228ea7caceeSSam Clegg     }
1229759631c7SSam Clegg   }
1230759631c7SSam Clegg 
12316a31a0d6SSam Clegg   // Create symbols for debug/custom sections.
12326a31a0d6SSam Clegg   for (MCSection &Sec : Asm) {
12336a31a0d6SSam Clegg     auto &DebugSection = static_cast<MCSectionWasm &>(Sec);
12346a31a0d6SSam Clegg     StringRef SectionName = DebugSection.getSectionName();
12356a31a0d6SSam Clegg 
12366a31a0d6SSam Clegg     // TODO: Add support for non-debug metadata sections?
12376a31a0d6SSam Clegg     if (!Sec.getKind().isMetadata() || !SectionName.startswith(".debug_"))
12386a31a0d6SSam Clegg       continue;
12396a31a0d6SSam Clegg 
12406a31a0d6SSam Clegg     uint32_t ElementIndex = CustomSections.size();
12416a31a0d6SSam Clegg     CustomSections.emplace_back(SectionName, &DebugSection);
12426a31a0d6SSam Clegg 
12436a31a0d6SSam Clegg     MCSymbolWasm *SectionSym =
12446a31a0d6SSam Clegg         cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SectionName));
12456a31a0d6SSam Clegg     CustomSectionSymbols[SectionSym] = &DebugSection;
12466a31a0d6SSam Clegg 
12476a31a0d6SSam Clegg     wasm::WasmSymbolInfo Info;
12486a31a0d6SSam Clegg     Info.Name = SectionSym->getName();
12496a31a0d6SSam Clegg     Info.Kind = wasm::WASM_SYMBOL_TYPE_SECTION;
1250d5504a0aSSam Clegg     Info.Flags = wasm::WASM_SYMBOL_BINDING_LOCAL;
12516a31a0d6SSam Clegg     Info.ElementIndex = ElementIndex;
12526a31a0d6SSam Clegg     SymbolIndices[SectionSym] = SymbolInfos.size();
12536a31a0d6SSam Clegg     SymbolInfos.emplace_back(Info);
12546a31a0d6SSam Clegg   }
12556a31a0d6SSam Clegg 
1256586320c0SNicholas Wilson   // Populate WasmIndices and DataLocations for defined symbols.
1257d934cb88SDan Gohman   for (const MCSymbol &S : Asm.symbols()) {
1258d934cb88SDan Gohman     // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1259d934cb88SDan Gohman     // or used in relocations.
1260d934cb88SDan Gohman     if (S.isTemporary() && S.getName().empty())
1261d934cb88SDan Gohman       continue;
1262b7787fd0SSam Clegg 
1263d934cb88SDan Gohman     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1264a165f2d6SSam Clegg     DEBUG(dbgs() << "MCSymbol: " << toString(WS.getType())
1265a165f2d6SSam Clegg                  << " '" << S << "'"
1266329e76d5SSam Clegg                  << " isDefined=" << S.isDefined()
1267329e76d5SSam Clegg                  << " isExternal=" << S.isExternal()
1268329e76d5SSam Clegg                  << " isTemporary=" << S.isTemporary()
1269b7787fd0SSam Clegg                  << " isWeak=" << WS.isWeak()
1270a2b35dacSSam Clegg                  << " isHidden=" << WS.isHidden()
1271b7787fd0SSam Clegg                  << " isVariable=" << WS.isVariable() << "\n");
1272b7787fd0SSam Clegg 
12735e3d33a7SSam Clegg     if (WS.isVariable())
12745e3d33a7SSam Clegg       continue;
12756c899ba6SSam Clegg     if (WS.isComdat() && !WS.isDefined())
12766c899ba6SSam Clegg       continue;
1277b7787fd0SSam Clegg 
1278d934cb88SDan Gohman     if (WS.isFunction()) {
12796c899ba6SSam Clegg       unsigned Index;
1280cd65f698SSam Clegg       if (WS.isDefined()) {
1281b7787fd0SSam Clegg         if (WS.getOffset() != 0)
1282b7787fd0SSam Clegg           report_fatal_error(
1283b7787fd0SSam Clegg               "function sections must contain one function each");
1284b7787fd0SSam Clegg 
1285b7787fd0SSam Clegg         if (WS.getSize() == 0)
1286b7787fd0SSam Clegg           report_fatal_error(
1287b7787fd0SSam Clegg               "function symbols must have a size set with .size");
1288b7787fd0SSam Clegg 
12896c899ba6SSam Clegg         // A definition. Write out the function body.
12909f3fe42eSSam Clegg         Index = NumFunctionImports + Functions.size();
1291d934cb88SDan Gohman         WasmFunction Func;
12925e3d33a7SSam Clegg         Func.Type = getFunctionType(WS);
1293d934cb88SDan Gohman         Func.Sym = &WS;
12946c899ba6SSam Clegg         WasmIndices[&WS] = Index;
1295d934cb88SDan Gohman         Functions.push_back(Func);
12966c899ba6SSam Clegg 
12976c899ba6SSam Clegg         auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
12986c899ba6SSam Clegg         if (const MCSymbolWasm *C = Section.getGroup()) {
12996c899ba6SSam Clegg           Comdats[C->getName()].emplace_back(
13006c899ba6SSam Clegg               WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
13016c899ba6SSam Clegg         }
1302d934cb88SDan Gohman       } else {
1303d934cb88SDan Gohman         // An import; the index was assigned above.
13046c899ba6SSam Clegg         Index = WasmIndices.find(&WS)->second;
1305d934cb88SDan Gohman       }
1306d934cb88SDan Gohman 
13075e3d33a7SSam Clegg       DEBUG(dbgs() << "  -> function index: " << Index << "\n");
13086c899ba6SSam Clegg     } else if (WS.isData()) {
1309c38e947eSSam Clegg       if (WS.isTemporary() && !WS.getSize())
1310c38e947eSSam Clegg         continue;
1311c38e947eSSam Clegg 
13126c899ba6SSam Clegg       if (!WS.isDefined()) {
1313a165f2d6SSam Clegg         DEBUG(dbgs() << "  -> segment index: -1" << "\n");
1314fe6414b0SSam Clegg         continue;
13156c899ba6SSam Clegg       }
1316fe6414b0SSam Clegg 
1317d934cb88SDan Gohman       if (!WS.getSize())
1318c38e947eSSam Clegg         report_fatal_error("data symbols must have a size set with .size: " +
1319c38e947eSSam Clegg                            WS.getName());
1320d934cb88SDan Gohman 
1321d934cb88SDan Gohman       int64_t Size = 0;
1322d934cb88SDan Gohman       if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1323d934cb88SDan Gohman         report_fatal_error(".size expression must be evaluatable");
1324d934cb88SDan Gohman 
1325759631c7SSam Clegg       auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
1326ea7caceeSSam Clegg       assert(DataSection.isWasmData());
13277c395943SSam Clegg 
13286c899ba6SSam Clegg       // For each data symbol, export it in the symtab as a reference to the
13296c899ba6SSam Clegg       // corresponding Wasm data segment.
13306c899ba6SSam Clegg       wasm::WasmDataReference Ref = wasm::WasmDataReference{
13316c899ba6SSam Clegg           DataSection.getSegmentIndex(),
13326c899ba6SSam Clegg           static_cast<uint32_t>(Layout.getSymbolOffset(WS)),
13336c899ba6SSam Clegg           static_cast<uint32_t>(Size)};
13346c899ba6SSam Clegg       DataLocations[&WS] = Ref;
1335a165f2d6SSam Clegg       DEBUG(dbgs() << "  -> segment index: " << Ref.Segment << "\n");
1336a165f2d6SSam Clegg     } else if (WS.isGlobal()) {
13376c899ba6SSam Clegg       // A "true" Wasm global (currently just __stack_pointer)
1338545932beSEric Christopher       if (WS.isDefined())
13396c899ba6SSam Clegg         report_fatal_error("don't yet support defined globals");
13406c899ba6SSam Clegg 
1341545932beSEric Christopher       // An import; the index was assigned above
1342545932beSEric Christopher       DEBUG(dbgs() << "  -> global index: " << WasmIndices.find(&WS)->second
1343545932beSEric Christopher                    << "\n");
1344a165f2d6SSam Clegg     } else {
1345a165f2d6SSam Clegg       assert(WS.isSection());
1346d934cb88SDan Gohman     }
1347d934cb88SDan Gohman   }
1348d934cb88SDan Gohman 
1349586320c0SNicholas Wilson   // Populate WasmIndices and DataLocations for aliased symbols.  We need to
1350586320c0SNicholas Wilson   // process these in a separate pass because we need to have processed the
1351586320c0SNicholas Wilson   // target of the alias before the alias itself and the symbols are not
1352586320c0SNicholas Wilson   // necessarily ordered in this way.
1353b7787fd0SSam Clegg   for (const MCSymbol &S : Asm.symbols()) {
1354b7787fd0SSam Clegg     if (!S.isVariable())
1355b7787fd0SSam Clegg       continue;
135631a2c809SSam Clegg 
1357cd65f698SSam Clegg     assert(S.isDefined());
1358b7787fd0SSam Clegg 
13595e3d33a7SSam Clegg     // Find the target symbol of this weak alias and export that index
1360aff1c4dfSSam Clegg     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1361aff1c4dfSSam Clegg     const MCSymbolWasm *ResolvedSym = ResolveSymbol(WS);
13625e3d33a7SSam Clegg     DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym << "'\n");
1363b7787fd0SSam Clegg 
13646c899ba6SSam Clegg     if (WS.isFunction()) {
13656c899ba6SSam Clegg       assert(WasmIndices.count(ResolvedSym) > 0);
13666c899ba6SSam Clegg       uint32_t WasmIndex = WasmIndices.find(ResolvedSym)->second;
13676c899ba6SSam Clegg       WasmIndices[&WS] = WasmIndex;
13686c899ba6SSam Clegg       DEBUG(dbgs() << "  -> index:" << WasmIndex << "\n");
13696c899ba6SSam Clegg     } else if (WS.isData()) {
13706c899ba6SSam Clegg       assert(DataLocations.count(ResolvedSym) > 0);
13716c899ba6SSam Clegg       const wasm::WasmDataReference &Ref =
13726c899ba6SSam Clegg           DataLocations.find(ResolvedSym)->second;
13736c899ba6SSam Clegg       DataLocations[&WS] = Ref;
13746c899ba6SSam Clegg       DEBUG(dbgs() << "  -> index:" << Ref.Segment << "\n");
13756c899ba6SSam Clegg     } else {
13766c899ba6SSam Clegg       report_fatal_error("don't yet support global aliases");
13776c899ba6SSam Clegg     }
1378586320c0SNicholas Wilson   }
137931a2c809SSam Clegg 
1380586320c0SNicholas Wilson   // Finally, populate the symbol table itself, in its "natural" order.
1381586320c0SNicholas Wilson   for (const MCSymbol &S : Asm.symbols()) {
1382586320c0SNicholas Wilson     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1383586320c0SNicholas Wilson     if (WS.isTemporary() && WS.getName().empty())
1384586320c0SNicholas Wilson       continue;
1385586320c0SNicholas Wilson     if (WS.isComdat() && !WS.isDefined())
1386586320c0SNicholas Wilson       continue;
1387586320c0SNicholas Wilson     if (WS.isTemporary() && WS.isData() && !WS.getSize())
1388586320c0SNicholas Wilson       continue;
1389586320c0SNicholas Wilson 
1390586320c0SNicholas Wilson     uint32_t Flags = 0;
1391586320c0SNicholas Wilson     if (WS.isWeak())
1392586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_BINDING_WEAK;
1393586320c0SNicholas Wilson     if (WS.isHidden())
1394586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN;
1395586320c0SNicholas Wilson     if (!WS.isExternal() && WS.isDefined())
1396586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;
1397586320c0SNicholas Wilson     if (WS.isUndefined())
1398586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_UNDEFINED;
1399586320c0SNicholas Wilson 
1400586320c0SNicholas Wilson     wasm::WasmSymbolInfo Info;
1401586320c0SNicholas Wilson     Info.Name = WS.getName();
1402586320c0SNicholas Wilson     Info.Kind = WS.getType();
1403586320c0SNicholas Wilson     Info.Flags = Flags;
1404586320c0SNicholas Wilson     if (!WS.isData())
1405586320c0SNicholas Wilson       Info.ElementIndex = WasmIndices.find(&WS)->second;
1406586320c0SNicholas Wilson     else if (WS.isDefined())
1407586320c0SNicholas Wilson       Info.DataRef = DataLocations.find(&WS)->second;
1408586320c0SNicholas Wilson     SymbolIndices[&WS] = SymbolInfos.size();
1409586320c0SNicholas Wilson     SymbolInfos.emplace_back(Info);
1410b7787fd0SSam Clegg   }
1411b7787fd0SSam Clegg 
14126006e091SSam Clegg   {
14136006e091SSam Clegg     auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
1414f9edbe95SSam Clegg       // Functions referenced by a relocation need to put in the table.  This is
1415f9edbe95SSam Clegg       // purely to make the object file's provisional values readable, and is
1416f9edbe95SSam Clegg       // ignored by the linker, which re-calculates the relocations itself.
1417f9edbe95SSam Clegg       if (Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_I32 &&
1418f9edbe95SSam Clegg           Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB)
1419f9edbe95SSam Clegg         return;
1420f9edbe95SSam Clegg       assert(Rel.Symbol->isFunction());
1421f9edbe95SSam Clegg       const MCSymbolWasm &WS = *ResolveSymbol(*Rel.Symbol);
14226c899ba6SSam Clegg       uint32_t FunctionIndex = WasmIndices.find(&WS)->second;
1423f9edbe95SSam Clegg       uint32_t TableIndex = TableElems.size() + kInitialTableOffset;
1424f9edbe95SSam Clegg       if (TableIndices.try_emplace(&WS, TableIndex).second) {
1425329e76d5SSam Clegg         DEBUG(dbgs() << "  -> adding " << WS.getName()
1426f9edbe95SSam Clegg                      << " to table: " << TableIndex << "\n");
14276c899ba6SSam Clegg         TableElems.push_back(FunctionIndex);
14286006e091SSam Clegg         registerFunctionType(WS);
14296006e091SSam Clegg       }
14306006e091SSam Clegg     };
1431970d02c4SDan Gohman 
14326006e091SSam Clegg     for (const WasmRelocationEntry &RelEntry : CodeRelocations)
14336006e091SSam Clegg       HandleReloc(RelEntry);
14346006e091SSam Clegg     for (const WasmRelocationEntry &RelEntry : DataRelocations)
14356006e091SSam Clegg       HandleReloc(RelEntry);
1436d934cb88SDan Gohman   }
1437d934cb88SDan Gohman 
1438bafe6902SSam Clegg   // Translate .init_array section contents into start functions.
1439bafe6902SSam Clegg   for (const MCSection &S : Asm) {
1440bafe6902SSam Clegg     const auto &WS = static_cast<const MCSectionWasm &>(S);
1441bafe6902SSam Clegg     if (WS.getSectionName().startswith(".fini_array"))
1442bafe6902SSam Clegg       report_fatal_error(".fini_array sections are unsupported");
1443bafe6902SSam Clegg     if (!WS.getSectionName().startswith(".init_array"))
1444bafe6902SSam Clegg       continue;
1445bafe6902SSam Clegg     if (WS.getFragmentList().empty())
1446bafe6902SSam Clegg       continue;
1447bafe6902SSam Clegg     if (WS.getFragmentList().size() != 2)
1448bafe6902SSam Clegg       report_fatal_error("only one .init_array section fragment supported");
1449bafe6902SSam Clegg     const MCFragment &AlignFrag = *WS.begin();
1450bafe6902SSam Clegg     if (AlignFrag.getKind() != MCFragment::FT_Align)
1451bafe6902SSam Clegg       report_fatal_error(".init_array section should be aligned");
1452bafe6902SSam Clegg     if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
1453bafe6902SSam Clegg       report_fatal_error(".init_array section should be aligned for pointers");
1454bafe6902SSam Clegg     const MCFragment &Frag = *std::next(WS.begin());
1455bafe6902SSam Clegg     if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1456bafe6902SSam Clegg       report_fatal_error("only data supported in .init_array section");
1457bafe6902SSam Clegg     uint16_t Priority = UINT16_MAX;
1458bafe6902SSam Clegg     if (WS.getSectionName().size() != 11) {
1459bafe6902SSam Clegg       if (WS.getSectionName()[11] != '.')
1460bafe6902SSam Clegg         report_fatal_error(".init_array section priority should start with '.'");
1461bafe6902SSam Clegg       if (WS.getSectionName().substr(12).getAsInteger(10, Priority))
1462bafe6902SSam Clegg         report_fatal_error("invalid .init_array section priority");
1463bafe6902SSam Clegg     }
1464bafe6902SSam Clegg     const auto &DataFrag = cast<MCDataFragment>(Frag);
1465bafe6902SSam Clegg     const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1466bafe6902SSam Clegg     for (const uint8_t *p = (const uint8_t *)Contents.data(),
1467bafe6902SSam Clegg                      *end = (const uint8_t *)Contents.data() + Contents.size();
1468bafe6902SSam Clegg          p != end; ++p) {
1469bafe6902SSam Clegg       if (*p != 0)
1470bafe6902SSam Clegg         report_fatal_error("non-symbolic data in .init_array section");
1471bafe6902SSam Clegg     }
1472bafe6902SSam Clegg     for (const MCFixup &Fixup : DataFrag.getFixups()) {
1473bafe6902SSam Clegg       assert(Fixup.getKind() == MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
1474bafe6902SSam Clegg       const MCExpr *Expr = Fixup.getValue();
1475bafe6902SSam Clegg       auto *Sym = dyn_cast<MCSymbolRefExpr>(Expr);
1476bafe6902SSam Clegg       if (!Sym)
1477bafe6902SSam Clegg         report_fatal_error("fixups in .init_array should be symbol references");
1478bafe6902SSam Clegg       if (Sym->getKind() != MCSymbolRefExpr::VK_WebAssembly_FUNCTION)
1479bafe6902SSam Clegg         report_fatal_error("symbols in .init_array should be for functions");
1480bafe6902SSam Clegg       auto I = SymbolIndices.find(cast<MCSymbolWasm>(&Sym->getSymbol()));
1481bafe6902SSam Clegg       if (I == SymbolIndices.end())
1482bafe6902SSam Clegg         report_fatal_error("symbols in .init_array should be defined");
1483bafe6902SSam Clegg       uint32_t Index = I->second;
1484bafe6902SSam Clegg       InitFuncs.push_back(std::make_pair(Priority, Index));
1485bafe6902SSam Clegg     }
1486bafe6902SSam Clegg   }
1487bafe6902SSam Clegg 
148818eafb6cSDan Gohman   // Write out the Wasm header.
148918eafb6cSDan Gohman   writeHeader(Asm);
149018eafb6cSDan Gohman 
14919e15f359SSam Clegg   writeTypeSection(FunctionTypes);
1492f950b24aSSam Clegg   writeImportSection(Imports, DataSize, TableElems.size());
14939e15f359SSam Clegg   writeFunctionSection(Functions);
1494f950b24aSSam Clegg   // Skip the "table" section; we import the table instead.
1495f950b24aSSam Clegg   // Skip the "memory" section; we import the memory instead.
14967c395943SSam Clegg   writeGlobalSection();
14979e15f359SSam Clegg   writeExportSection(Exports);
14989e15f359SSam Clegg   writeElemSection(TableElems);
1499acd7d2b0SSam Clegg   writeCodeSection(Asm, Layout, Functions);
15006c899ba6SSam Clegg   writeDataSection();
15016a31a0d6SSam Clegg   writeCustomSections(Asm, Layout);
15026a31a0d6SSam Clegg   updateCustomSectionRelocations(Functions, Layout);
1503c22bfb6bSNicholas Wilson   writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats);
15046f08c84aSSam Clegg   writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations);
15056f08c84aSSam Clegg   writeRelocSection(DataSectionIndex, "DATA", DataRelocations);
15066a31a0d6SSam Clegg   writeCustomRelocSections();
1507970d02c4SDan Gohman 
1508d934cb88SDan Gohman   // TODO: Translate the .comment section to the output.
150918eafb6cSDan Gohman }
151018eafb6cSDan Gohman 
151160fbc7ccSLang Hames std::unique_ptr<MCObjectWriter>
15121301a878SLang Hames llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
151318eafb6cSDan Gohman                              raw_pwrite_stream &OS) {
15140917c9e4SDan Gohman   return llvm::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
151518eafb6cSDan Gohman }
1516