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"
1718eafb6cSDan Gohman #include "llvm/MC/MCAsmBackend.h"
1818eafb6cSDan Gohman #include "llvm/MC/MCAsmInfo.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/MCObjectFileInfo.h"
2518eafb6cSDan Gohman #include "llvm/MC/MCObjectWriter.h"
2618eafb6cSDan Gohman #include "llvm/MC/MCSectionWasm.h"
2718eafb6cSDan Gohman #include "llvm/MC/MCSymbolWasm.h"
2818eafb6cSDan Gohman #include "llvm/MC/MCValue.h"
2918eafb6cSDan Gohman #include "llvm/MC/MCWasmObjectWriter.h"
30d934cb88SDan Gohman #include "llvm/Support/Casting.h"
3118eafb6cSDan Gohman #include "llvm/Support/Debug.h"
3218eafb6cSDan Gohman #include "llvm/Support/ErrorHandling.h"
33d934cb88SDan Gohman #include "llvm/Support/LEB128.h"
3418eafb6cSDan Gohman #include "llvm/Support/StringSaver.h"
3518eafb6cSDan Gohman #include <vector>
3618eafb6cSDan Gohman 
3718eafb6cSDan Gohman using namespace llvm;
3818eafb6cSDan Gohman 
3918eafb6cSDan Gohman #undef DEBUG_TYPE
4018eafb6cSDan Gohman #define DEBUG_TYPE "reloc-info"
4118eafb6cSDan Gohman 
4218eafb6cSDan Gohman namespace {
439e15f359SSam Clegg 
44d934cb88SDan Gohman // For patching purposes, we need to remember where each section starts, both
45d934cb88SDan Gohman // for patching up the section size field, and for patching up references to
46d934cb88SDan Gohman // locations within the section.
47d934cb88SDan Gohman struct SectionBookkeeping {
48d934cb88SDan Gohman   // Where the size of the section is written.
49d934cb88SDan Gohman   uint64_t SizeOffset;
50d934cb88SDan Gohman   // Where the contents of the section starts (after the header).
51d934cb88SDan Gohman   uint64_t ContentsOffset;
52d934cb88SDan Gohman };
53d934cb88SDan Gohman 
549e15f359SSam Clegg // The signature of a wasm function, in a struct capable of being used as a
559e15f359SSam Clegg // DenseMap key.
569e15f359SSam Clegg struct WasmFunctionType {
579e15f359SSam Clegg   // Support empty and tombstone instances, needed by DenseMap.
589e15f359SSam Clegg   enum { Plain, Empty, Tombstone } State;
599e15f359SSam Clegg 
609e15f359SSam Clegg   // The return types of the function.
619e15f359SSam Clegg   SmallVector<wasm::ValType, 1> Returns;
629e15f359SSam Clegg 
639e15f359SSam Clegg   // The parameter types of the function.
649e15f359SSam Clegg   SmallVector<wasm::ValType, 4> Params;
659e15f359SSam Clegg 
669e15f359SSam Clegg   WasmFunctionType() : State(Plain) {}
679e15f359SSam Clegg 
689e15f359SSam Clegg   bool operator==(const WasmFunctionType &Other) const {
699e15f359SSam Clegg     return State == Other.State && Returns == Other.Returns &&
709e15f359SSam Clegg            Params == Other.Params;
719e15f359SSam Clegg   }
729e15f359SSam Clegg };
739e15f359SSam Clegg 
749e15f359SSam Clegg // Traits for using WasmFunctionType in a DenseMap.
759e15f359SSam Clegg struct WasmFunctionTypeDenseMapInfo {
769e15f359SSam Clegg   static WasmFunctionType getEmptyKey() {
779e15f359SSam Clegg     WasmFunctionType FuncTy;
789e15f359SSam Clegg     FuncTy.State = WasmFunctionType::Empty;
799e15f359SSam Clegg     return FuncTy;
809e15f359SSam Clegg   }
819e15f359SSam Clegg   static WasmFunctionType getTombstoneKey() {
829e15f359SSam Clegg     WasmFunctionType FuncTy;
839e15f359SSam Clegg     FuncTy.State = WasmFunctionType::Tombstone;
849e15f359SSam Clegg     return FuncTy;
859e15f359SSam Clegg   }
869e15f359SSam Clegg   static unsigned getHashValue(const WasmFunctionType &FuncTy) {
879e15f359SSam Clegg     uintptr_t Value = FuncTy.State;
889e15f359SSam Clegg     for (wasm::ValType Ret : FuncTy.Returns)
899e15f359SSam Clegg       Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Ret));
909e15f359SSam Clegg     for (wasm::ValType Param : FuncTy.Params)
919e15f359SSam Clegg       Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Param));
929e15f359SSam Clegg     return Value;
939e15f359SSam Clegg   }
949e15f359SSam Clegg   static bool isEqual(const WasmFunctionType &LHS,
959e15f359SSam Clegg                       const WasmFunctionType &RHS) {
969e15f359SSam Clegg     return LHS == RHS;
979e15f359SSam Clegg   }
989e15f359SSam Clegg };
999e15f359SSam Clegg 
1009e15f359SSam Clegg // A wasm import to be written into the import section.
1019e15f359SSam Clegg struct WasmImport {
1029e15f359SSam Clegg   StringRef ModuleName;
1039e15f359SSam Clegg   StringRef FieldName;
1049e15f359SSam Clegg   unsigned Kind;
1059e15f359SSam Clegg   int32_t Type;
1069e15f359SSam Clegg };
1079e15f359SSam Clegg 
1089e15f359SSam Clegg // A wasm function to be written into the function section.
1099e15f359SSam Clegg struct WasmFunction {
1109e15f359SSam Clegg   int32_t Type;
1119e15f359SSam Clegg   const MCSymbolWasm *Sym;
1129e15f359SSam Clegg };
1139e15f359SSam Clegg 
1149e15f359SSam Clegg // A wasm export to be written into the export section.
1159e15f359SSam Clegg struct WasmExport {
1169e15f359SSam Clegg   StringRef FieldName;
1179e15f359SSam Clegg   unsigned Kind;
1189e15f359SSam Clegg   uint32_t Index;
1199e15f359SSam Clegg };
1209e15f359SSam Clegg 
1219e15f359SSam Clegg // A wasm global to be written into the global section.
1229e15f359SSam Clegg struct WasmGlobal {
1239e15f359SSam Clegg   wasm::ValType Type;
1249e15f359SSam Clegg   bool IsMutable;
1259e15f359SSam Clegg   bool HasImport;
1269e15f359SSam Clegg   uint64_t InitialValue;
1279e15f359SSam Clegg   uint32_t ImportIndex;
1289e15f359SSam Clegg };
1299e15f359SSam Clegg 
1306dc65e91SSam Clegg // Information about a single relocation.
1316dc65e91SSam Clegg struct WasmRelocationEntry {
1326dc65e91SSam Clegg   uint64_t Offset;                  // Where is the relocation.
1336dc65e91SSam Clegg   const MCSymbolWasm *Symbol;       // The symbol to relocate with.
1346dc65e91SSam Clegg   int64_t Addend;                   // A value to add to the symbol.
1356dc65e91SSam Clegg   unsigned Type;                    // The type of the relocation.
136*fe6414b0SSam Clegg   const MCSectionWasm *FixupSection;// The section the relocation is targeting.
1376dc65e91SSam Clegg 
1386dc65e91SSam Clegg   WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol,
1396dc65e91SSam Clegg                       int64_t Addend, unsigned Type,
140*fe6414b0SSam Clegg                       const MCSectionWasm *FixupSection)
1416dc65e91SSam Clegg       : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type),
1426dc65e91SSam Clegg         FixupSection(FixupSection) {}
1436dc65e91SSam Clegg 
144acd7d2b0SSam Clegg   bool hasAddend() const {
145acd7d2b0SSam Clegg     switch (Type) {
146acd7d2b0SSam Clegg     case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_LEB:
147acd7d2b0SSam Clegg     case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_SLEB:
148acd7d2b0SSam Clegg     case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_I32:
149acd7d2b0SSam Clegg       return true;
150acd7d2b0SSam Clegg     default:
151acd7d2b0SSam Clegg       return false;
152acd7d2b0SSam Clegg     }
153acd7d2b0SSam Clegg   }
154acd7d2b0SSam Clegg 
1556dc65e91SSam Clegg   void print(raw_ostream &Out) const {
1566dc65e91SSam Clegg     Out << "Off=" << Offset << ", Sym=" << Symbol << ", Addend=" << Addend
1576dc65e91SSam Clegg         << ", Type=" << Type << ", FixupSection=" << FixupSection;
1586dc65e91SSam Clegg   }
159b7787fd0SSam Clegg 
160b7787fd0SSam Clegg #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
161b7787fd0SSam Clegg   LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
162b7787fd0SSam Clegg #endif
1636dc65e91SSam Clegg };
1646dc65e91SSam Clegg 
1651fb8daa6SSam Clegg #if !defined(NDEBUG)
1667f055deeSSam Clegg raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
167b7787fd0SSam Clegg   Rel.print(OS);
168b7787fd0SSam Clegg   return OS;
169b7787fd0SSam Clegg }
1701fb8daa6SSam Clegg #endif
171b7787fd0SSam Clegg 
17218eafb6cSDan Gohman class WasmObjectWriter : public MCObjectWriter {
17318eafb6cSDan Gohman   /// Helper struct for containing some precomputed information on symbols.
17418eafb6cSDan Gohman   struct WasmSymbolData {
17518eafb6cSDan Gohman     const MCSymbolWasm *Symbol;
17618eafb6cSDan Gohman     StringRef Name;
17718eafb6cSDan Gohman 
17818eafb6cSDan Gohman     // Support lexicographic sorting.
17918eafb6cSDan Gohman     bool operator<(const WasmSymbolData &RHS) const { return Name < RHS.Name; }
18018eafb6cSDan Gohman   };
18118eafb6cSDan Gohman 
18218eafb6cSDan Gohman   /// The target specific Wasm writer instance.
18318eafb6cSDan Gohman   std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
18418eafb6cSDan Gohman 
185d934cb88SDan Gohman   // Relocations for fixing up references in the code section.
186d934cb88SDan Gohman   std::vector<WasmRelocationEntry> CodeRelocations;
187d934cb88SDan Gohman 
188d934cb88SDan Gohman   // Relocations for fixing up references in the data section.
189d934cb88SDan Gohman   std::vector<WasmRelocationEntry> DataRelocations;
190d934cb88SDan Gohman 
191d934cb88SDan Gohman   // Index values to use for fixing up call_indirect type indices.
192acd7d2b0SSam Clegg   // Maps function symbols to the index of the type of the function
193acd7d2b0SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
194d99f6078SSam Clegg   // Maps function symbols to the table element index space. Used
195d99f6078SSam Clegg   // for TABLE_INDEX relocation types (i.e. address taken functions).
196d99f6078SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> IndirectSymbolIndices;
197d99f6078SSam Clegg   // Maps function/global symbols to the function/global index space.
198acd7d2b0SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> SymbolIndices;
199acd7d2b0SSam Clegg 
200acd7d2b0SSam Clegg   DenseMap<WasmFunctionType, int32_t, WasmFunctionTypeDenseMapInfo>
201acd7d2b0SSam Clegg       FunctionTypeIndices;
202d934cb88SDan Gohman 
20318eafb6cSDan Gohman   // TargetObjectWriter wrappers.
20418eafb6cSDan Gohman   bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
205ae03c1e7SSam Clegg   unsigned getRelocType(const MCValue &Target, const MCFixup &Fixup) const {
206ae03c1e7SSam Clegg     return TargetObjectWriter->getRelocType(Target, Fixup);
20718eafb6cSDan Gohman   }
20818eafb6cSDan Gohman 
209d934cb88SDan Gohman   void startSection(SectionBookkeeping &Section, unsigned SectionId,
210d934cb88SDan Gohman                     const char *Name = nullptr);
211d934cb88SDan Gohman   void endSection(SectionBookkeeping &Section);
212d934cb88SDan Gohman 
21318eafb6cSDan Gohman public:
21418eafb6cSDan Gohman   WasmObjectWriter(MCWasmObjectTargetWriter *MOTW, raw_pwrite_stream &OS)
21518eafb6cSDan Gohman       : MCObjectWriter(OS, /*IsLittleEndian=*/true), TargetObjectWriter(MOTW) {}
21618eafb6cSDan Gohman 
217d934cb88SDan Gohman private:
21818eafb6cSDan Gohman   ~WasmObjectWriter() override;
21918eafb6cSDan Gohman 
220acd7d2b0SSam Clegg   void reset() override {
221acd7d2b0SSam Clegg     CodeRelocations.clear();
222acd7d2b0SSam Clegg     DataRelocations.clear();
223acd7d2b0SSam Clegg     TypeIndices.clear();
224acd7d2b0SSam Clegg     SymbolIndices.clear();
225d99f6078SSam Clegg     IndirectSymbolIndices.clear();
226acd7d2b0SSam Clegg     FunctionTypeIndices.clear();
227acd7d2b0SSam Clegg     MCObjectWriter::reset();
228acd7d2b0SSam Clegg   }
229acd7d2b0SSam Clegg 
23018eafb6cSDan Gohman   void writeHeader(const MCAssembler &Asm);
23118eafb6cSDan Gohman 
23218eafb6cSDan Gohman   void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
23318eafb6cSDan Gohman                         const MCFragment *Fragment, const MCFixup &Fixup,
23418eafb6cSDan Gohman                         MCValue Target, bool &IsPCRel,
23518eafb6cSDan Gohman                         uint64_t &FixedValue) override;
23618eafb6cSDan Gohman 
23718eafb6cSDan Gohman   void executePostLayoutBinding(MCAssembler &Asm,
23818eafb6cSDan Gohman                                 const MCAsmLayout &Layout) override;
23918eafb6cSDan Gohman 
24018eafb6cSDan Gohman   void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
2419e15f359SSam Clegg 
242b7787fd0SSam Clegg   void writeString(const StringRef Str) {
243b7787fd0SSam Clegg     encodeULEB128(Str.size(), getStream());
244b7787fd0SSam Clegg     writeBytes(Str);
245b7787fd0SSam Clegg   }
246b7787fd0SSam Clegg 
2479e15f359SSam Clegg   void writeValueType(wasm::ValType Ty) {
2489e15f359SSam Clegg     encodeSLEB128(int32_t(Ty), getStream());
2499e15f359SSam Clegg   }
2509e15f359SSam Clegg 
2519e15f359SSam Clegg   void writeTypeSection(const SmallVector<WasmFunctionType, 4> &FunctionTypes);
2529e15f359SSam Clegg   void writeImportSection(const SmallVector<WasmImport, 4> &Imports);
2539e15f359SSam Clegg   void writeFunctionSection(const SmallVector<WasmFunction, 4> &Functions);
254d99f6078SSam Clegg   void writeTableSection(uint32_t NumElements);
2559e15f359SSam Clegg   void writeMemorySection(const SmallVector<char, 0> &DataBytes);
2569e15f359SSam Clegg   void writeGlobalSection(const SmallVector<WasmGlobal, 4> &Globals);
2579e15f359SSam Clegg   void writeExportSection(const SmallVector<WasmExport, 4> &Exports);
2589e15f359SSam Clegg   void writeElemSection(const SmallVector<uint32_t, 4> &TableElems);
2599e15f359SSam Clegg   void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
2609e15f359SSam Clegg                         const SmallVector<WasmFunction, 4> &Functions);
2619e15f359SSam Clegg   uint64_t
262acd7d2b0SSam Clegg   writeDataSection(const SmallVector<char, 0> &DataBytes);
2639e15f359SSam Clegg   void writeNameSection(const SmallVector<WasmFunction, 4> &Functions,
2649e15f359SSam Clegg                         const SmallVector<WasmImport, 4> &Imports,
2659e15f359SSam Clegg                         uint32_t NumFuncImports);
266acd7d2b0SSam Clegg   void writeCodeRelocSection();
267acd7d2b0SSam Clegg   void writeDataRelocSection(uint64_t DataSectionHeaderSize);
268b7787fd0SSam Clegg   void writeLinkingMetaDataSection(ArrayRef<StringRef> WeakSymbols,
269b7787fd0SSam Clegg                                    bool HasStackPointer,
2709e15f359SSam Clegg                                    uint32_t StackPointerGlobal);
271acd7d2b0SSam Clegg 
272acd7d2b0SSam Clegg   void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
273acd7d2b0SSam Clegg                         uint64_t ContentsOffset);
274acd7d2b0SSam Clegg 
275acd7d2b0SSam Clegg   void writeRelocations(ArrayRef<WasmRelocationEntry> Relocations,
276acd7d2b0SSam Clegg                         uint64_t HeaderSize);
277acd7d2b0SSam Clegg   uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
27818eafb6cSDan Gohman };
2799e15f359SSam Clegg 
28018eafb6cSDan Gohman } // end anonymous namespace
28118eafb6cSDan Gohman 
28218eafb6cSDan Gohman WasmObjectWriter::~WasmObjectWriter() {}
28318eafb6cSDan Gohman 
284d934cb88SDan Gohman // Return the padding size to write a 32-bit value into a 5-byte ULEB128.
285d934cb88SDan Gohman static unsigned PaddingFor5ByteULEB128(uint32_t X) {
286d934cb88SDan Gohman   return X == 0 ? 4 : (4u - (31u - countLeadingZeros(X)) / 7u);
287d934cb88SDan Gohman }
288d934cb88SDan Gohman 
289d934cb88SDan Gohman // Return the padding size to write a 32-bit value into a 5-byte SLEB128.
290d934cb88SDan Gohman static unsigned PaddingFor5ByteSLEB128(int32_t X) {
291d934cb88SDan Gohman   return 5 - getSLEB128Size(X);
292d934cb88SDan Gohman }
293d934cb88SDan Gohman 
294d934cb88SDan Gohman // Write out a section header and a patchable section size field.
295d934cb88SDan Gohman void WasmObjectWriter::startSection(SectionBookkeeping &Section,
296d934cb88SDan Gohman                                     unsigned SectionId,
297d934cb88SDan Gohman                                     const char *Name) {
298d934cb88SDan Gohman   assert((Name != nullptr) == (SectionId == wasm::WASM_SEC_CUSTOM) &&
299d934cb88SDan Gohman          "Only custom sections can have names");
300d934cb88SDan Gohman 
301b7787fd0SSam Clegg   DEBUG(dbgs() << "startSection " << SectionId << ": " << Name << "\n");
302e2688c43SDerek Schuff   encodeULEB128(SectionId, getStream());
303d934cb88SDan Gohman 
304d934cb88SDan Gohman   Section.SizeOffset = getStream().tell();
305d934cb88SDan Gohman 
306d934cb88SDan Gohman   // The section size. We don't know the size yet, so reserve enough space
307d934cb88SDan Gohman   // for any 32-bit value; we'll patch it later.
308d934cb88SDan Gohman   encodeULEB128(UINT32_MAX, getStream());
309d934cb88SDan Gohman 
310d934cb88SDan Gohman   // The position where the section starts, for measuring its size.
311d934cb88SDan Gohman   Section.ContentsOffset = getStream().tell();
312d934cb88SDan Gohman 
313d934cb88SDan Gohman   // Custom sections in wasm also have a string identifier.
314d934cb88SDan Gohman   if (SectionId == wasm::WASM_SEC_CUSTOM) {
315b7787fd0SSam Clegg     assert(Name);
316b7787fd0SSam Clegg     writeString(StringRef(Name));
317d934cb88SDan Gohman   }
318d934cb88SDan Gohman }
319d934cb88SDan Gohman 
320d934cb88SDan Gohman // Now that the section is complete and we know how big it is, patch up the
321d934cb88SDan Gohman // section size field at the start of the section.
322d934cb88SDan Gohman void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
323d934cb88SDan Gohman   uint64_t Size = getStream().tell() - Section.ContentsOffset;
324d934cb88SDan Gohman   if (uint32_t(Size) != Size)
325d934cb88SDan Gohman     report_fatal_error("section size does not fit in a uint32_t");
326d934cb88SDan Gohman 
327b7787fd0SSam Clegg   DEBUG(dbgs() << "endSection size=" << Size << "\n");
328d934cb88SDan Gohman   unsigned Padding = PaddingFor5ByteULEB128(Size);
329d934cb88SDan Gohman 
330d934cb88SDan Gohman   // Write the final section size to the payload_len field, which follows
331d934cb88SDan Gohman   // the section id byte.
332d934cb88SDan Gohman   uint8_t Buffer[16];
333d934cb88SDan Gohman   unsigned SizeLen = encodeULEB128(Size, Buffer, Padding);
334d934cb88SDan Gohman   assert(SizeLen == 5);
335d934cb88SDan Gohman   getStream().pwrite((char *)Buffer, SizeLen, Section.SizeOffset);
336d934cb88SDan Gohman }
337d934cb88SDan Gohman 
33818eafb6cSDan Gohman // Emit the Wasm header.
33918eafb6cSDan Gohman void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
3407ea5adffSDan Gohman   writeBytes(StringRef(wasm::WasmMagic, sizeof(wasm::WasmMagic)));
3417ea5adffSDan Gohman   writeLE32(wasm::WasmVersion);
34218eafb6cSDan Gohman }
34318eafb6cSDan Gohman 
34418eafb6cSDan Gohman void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
34518eafb6cSDan Gohman                                                 const MCAsmLayout &Layout) {
34618eafb6cSDan Gohman }
34718eafb6cSDan Gohman 
34818eafb6cSDan Gohman void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
34918eafb6cSDan Gohman                                         const MCAsmLayout &Layout,
35018eafb6cSDan Gohman                                         const MCFragment *Fragment,
35118eafb6cSDan Gohman                                         const MCFixup &Fixup, MCValue Target,
35218eafb6cSDan Gohman                                         bool &IsPCRel, uint64_t &FixedValue) {
353*fe6414b0SSam Clegg   const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
354d934cb88SDan Gohman   uint64_t C = Target.getConstant();
355d934cb88SDan Gohman   uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
356d934cb88SDan Gohman   MCContext &Ctx = Asm.getContext();
357d934cb88SDan Gohman 
358d934cb88SDan Gohman   if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
359d934cb88SDan Gohman     assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
360d934cb88SDan Gohman            "Should not have constructed this");
361d934cb88SDan Gohman 
362d934cb88SDan Gohman     // Let A, B and C being the components of Target and R be the location of
363d934cb88SDan Gohman     // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
364d934cb88SDan Gohman     // If it is pcrel, we want to compute (A - B + C - R).
365d934cb88SDan Gohman 
366d934cb88SDan Gohman     // In general, Wasm has no relocations for -B. It can only represent (A + C)
367d934cb88SDan Gohman     // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
368d934cb88SDan Gohman     // replace B to implement it: (A - R - K + C)
369d934cb88SDan Gohman     if (IsPCRel) {
370d934cb88SDan Gohman       Ctx.reportError(
371d934cb88SDan Gohman           Fixup.getLoc(),
372d934cb88SDan Gohman           "No relocation available to represent this relative expression");
373d934cb88SDan Gohman       return;
374d934cb88SDan Gohman     }
375d934cb88SDan Gohman 
376d934cb88SDan Gohman     const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
377d934cb88SDan Gohman 
378d934cb88SDan Gohman     if (SymB.isUndefined()) {
379d934cb88SDan Gohman       Ctx.reportError(Fixup.getLoc(),
380d934cb88SDan Gohman                       Twine("symbol '") + SymB.getName() +
381d934cb88SDan Gohman                           "' can not be undefined in a subtraction expression");
382d934cb88SDan Gohman       return;
383d934cb88SDan Gohman     }
384d934cb88SDan Gohman 
385d934cb88SDan Gohman     assert(!SymB.isAbsolute() && "Should have been folded");
386d934cb88SDan Gohman     const MCSection &SecB = SymB.getSection();
387d934cb88SDan Gohman     if (&SecB != &FixupSection) {
388d934cb88SDan Gohman       Ctx.reportError(Fixup.getLoc(),
389d934cb88SDan Gohman                       "Cannot represent a difference across sections");
390d934cb88SDan Gohman       return;
391d934cb88SDan Gohman     }
392d934cb88SDan Gohman 
393d934cb88SDan Gohman     uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
394d934cb88SDan Gohman     uint64_t K = SymBOffset - FixupOffset;
395d934cb88SDan Gohman     IsPCRel = true;
396d934cb88SDan Gohman     C -= K;
397d934cb88SDan Gohman   }
398d934cb88SDan Gohman 
399d934cb88SDan Gohman   // We either rejected the fixup or folded B into C at this point.
400d934cb88SDan Gohman   const MCSymbolRefExpr *RefA = Target.getSymA();
401d934cb88SDan Gohman   const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr;
402d934cb88SDan Gohman 
403d934cb88SDan Gohman   bool ViaWeakRef = false;
404d934cb88SDan Gohman   if (SymA && SymA->isVariable()) {
405d934cb88SDan Gohman     const MCExpr *Expr = SymA->getVariableValue();
406d934cb88SDan Gohman     if (const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr)) {
407d934cb88SDan Gohman       if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF) {
408d934cb88SDan Gohman         SymA = cast<MCSymbolWasm>(&Inner->getSymbol());
409d934cb88SDan Gohman         ViaWeakRef = true;
410d934cb88SDan Gohman       }
411d934cb88SDan Gohman     }
412d934cb88SDan Gohman   }
413d934cb88SDan Gohman 
414d934cb88SDan Gohman   // Put any constant offset in an addend. Offsets can be negative, and
415d934cb88SDan Gohman   // LLVM expects wrapping, in contrast to wasm's immediates which can't
416d934cb88SDan Gohman   // be negative and don't wrap.
417d934cb88SDan Gohman   FixedValue = 0;
418d934cb88SDan Gohman 
419d934cb88SDan Gohman   if (SymA) {
420d934cb88SDan Gohman     if (ViaWeakRef)
421d934cb88SDan Gohman       llvm_unreachable("weakref used in reloc not yet implemented");
422d934cb88SDan Gohman     else
423d934cb88SDan Gohman       SymA->setUsedInReloc();
424d934cb88SDan Gohman   }
425d934cb88SDan Gohman 
426ae03c1e7SSam Clegg   assert(!IsPCRel);
4279d24fb7fSSam Clegg   assert(SymA);
4289d24fb7fSSam Clegg 
429ae03c1e7SSam Clegg   unsigned Type = getRelocType(Target, Fixup);
430ae03c1e7SSam Clegg 
431d934cb88SDan Gohman   WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
432b7787fd0SSam Clegg   DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
433d934cb88SDan Gohman 
434d934cb88SDan Gohman   if (FixupSection.hasInstructions())
435d934cb88SDan Gohman     CodeRelocations.push_back(Rec);
436d934cb88SDan Gohman   else
437d934cb88SDan Gohman     DataRelocations.push_back(Rec);
438d934cb88SDan Gohman }
439d934cb88SDan Gohman 
440d934cb88SDan Gohman // Write X as an (unsigned) LEB value at offset Offset in Stream, padded
441d934cb88SDan Gohman // to allow patching.
442d934cb88SDan Gohman static void
443d934cb88SDan Gohman WritePatchableLEB(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
444d934cb88SDan Gohman   uint8_t Buffer[5];
445d934cb88SDan Gohman   unsigned Padding = PaddingFor5ByteULEB128(X);
446d934cb88SDan Gohman   unsigned SizeLen = encodeULEB128(X, Buffer, Padding);
447d934cb88SDan Gohman   assert(SizeLen == 5);
448d934cb88SDan Gohman   Stream.pwrite((char *)Buffer, SizeLen, Offset);
449d934cb88SDan Gohman }
450d934cb88SDan Gohman 
451d934cb88SDan Gohman // Write X as an signed LEB value at offset Offset in Stream, padded
452d934cb88SDan Gohman // to allow patching.
453d934cb88SDan Gohman static void
454d934cb88SDan Gohman WritePatchableSLEB(raw_pwrite_stream &Stream, int32_t X, uint64_t Offset) {
455d934cb88SDan Gohman   uint8_t Buffer[5];
456d934cb88SDan Gohman   unsigned Padding = PaddingFor5ByteSLEB128(X);
457d934cb88SDan Gohman   unsigned SizeLen = encodeSLEB128(X, Buffer, Padding);
458d934cb88SDan Gohman   assert(SizeLen == 5);
459d934cb88SDan Gohman   Stream.pwrite((char *)Buffer, SizeLen, Offset);
460d934cb88SDan Gohman }
461d934cb88SDan Gohman 
462d934cb88SDan Gohman // Write X as a plain integer value at offset Offset in Stream.
463d934cb88SDan Gohman static void WriteI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
464d934cb88SDan Gohman   uint8_t Buffer[4];
465d934cb88SDan Gohman   support::endian::write32le(Buffer, X);
466d934cb88SDan Gohman   Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
467d934cb88SDan Gohman }
468d934cb88SDan Gohman 
469d934cb88SDan Gohman // Compute a value to write into the code at the location covered
470d934cb88SDan Gohman // by RelEntry. This value isn't used by the static linker, since
471d934cb88SDan Gohman // we have addends; it just serves to make the code more readable
472d934cb88SDan Gohman // and to make standalone wasm modules directly usable.
473d934cb88SDan Gohman static uint32_t ProvisionalValue(const WasmRelocationEntry &RelEntry) {
474d934cb88SDan Gohman   const MCSymbolWasm *Sym = RelEntry.Symbol;
475d934cb88SDan Gohman 
476d934cb88SDan Gohman   // For undefined symbols, use a hopefully invalid value.
477b7787fd0SSam Clegg   if (!Sym->isDefined(/*SetUsed=*/false))
478d934cb88SDan Gohman     return UINT32_MAX;
479d934cb88SDan Gohman 
480*fe6414b0SSam Clegg   const auto &Section = cast<MCSectionWasm>(RelEntry.Symbol->getSection(false));
481d934cb88SDan Gohman   uint64_t Address = Section.getSectionOffset() + RelEntry.Addend;
482d934cb88SDan Gohman 
483d934cb88SDan Gohman   // Ignore overflow. LLVM allows address arithmetic to silently wrap.
484d934cb88SDan Gohman   uint32_t Value = Address;
485d934cb88SDan Gohman 
486d934cb88SDan Gohman   return Value;
487d934cb88SDan Gohman }
488d934cb88SDan Gohman 
489acd7d2b0SSam Clegg uint32_t WasmObjectWriter::getRelocationIndexValue(
490acd7d2b0SSam Clegg     const WasmRelocationEntry &RelEntry) {
491acd7d2b0SSam Clegg   switch (RelEntry.Type) {
492acd7d2b0SSam Clegg   case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
493acd7d2b0SSam Clegg   case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
494b7787fd0SSam Clegg     if (!IndirectSymbolIndices.count(RelEntry.Symbol))
495b7787fd0SSam Clegg       report_fatal_error("symbol not found table index space:" +
496b7787fd0SSam Clegg                          RelEntry.Symbol->getName());
497d99f6078SSam Clegg     return IndirectSymbolIndices[RelEntry.Symbol];
498d99f6078SSam Clegg   case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
4999d24fb7fSSam Clegg   case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
500acd7d2b0SSam Clegg   case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_LEB:
501acd7d2b0SSam Clegg   case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_SLEB:
502acd7d2b0SSam Clegg   case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_I32:
503b7787fd0SSam Clegg     if (!SymbolIndices.count(RelEntry.Symbol))
504b7787fd0SSam Clegg       report_fatal_error("symbol not found function/global index space:" +
505b7787fd0SSam Clegg                          RelEntry.Symbol->getName());
506acd7d2b0SSam Clegg     return SymbolIndices[RelEntry.Symbol];
507acd7d2b0SSam Clegg   case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
508b7787fd0SSam Clegg     if (!TypeIndices.count(RelEntry.Symbol))
509b7787fd0SSam Clegg       report_fatal_error("symbol not found in type index space:" +
510b7787fd0SSam Clegg                          RelEntry.Symbol->getName());
511acd7d2b0SSam Clegg     return TypeIndices[RelEntry.Symbol];
512acd7d2b0SSam Clegg   default:
513acd7d2b0SSam Clegg     llvm_unreachable("invalid relocation type");
514acd7d2b0SSam Clegg   }
515acd7d2b0SSam Clegg }
516acd7d2b0SSam Clegg 
517d934cb88SDan Gohman // Apply the portions of the relocation records that we can handle ourselves
518d934cb88SDan Gohman // directly.
519acd7d2b0SSam Clegg void WasmObjectWriter::applyRelocations(
520acd7d2b0SSam Clegg     ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
521acd7d2b0SSam Clegg   raw_pwrite_stream &Stream = getStream();
522d934cb88SDan Gohman   for (const WasmRelocationEntry &RelEntry : Relocations) {
523d934cb88SDan Gohman     uint64_t Offset = ContentsOffset +
524d934cb88SDan Gohman                       RelEntry.FixupSection->getSectionOffset() +
525d934cb88SDan Gohman                       RelEntry.Offset;
526d934cb88SDan Gohman 
527b7787fd0SSam Clegg     DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
528acd7d2b0SSam Clegg     switch (RelEntry.Type) {
529acd7d2b0SSam Clegg     case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
530acd7d2b0SSam Clegg     case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
5319d24fb7fSSam Clegg     case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
5329d24fb7fSSam Clegg     case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB: {
533acd7d2b0SSam Clegg       uint32_t Index = getRelocationIndexValue(RelEntry);
534acd7d2b0SSam Clegg       WritePatchableSLEB(Stream, Index, Offset);
535d934cb88SDan Gohman       break;
536d934cb88SDan Gohman     }
537acd7d2b0SSam Clegg     case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: {
538acd7d2b0SSam Clegg       uint32_t Index = getRelocationIndexValue(RelEntry);
539acd7d2b0SSam Clegg       WriteI32(Stream, Index, Offset);
540d934cb88SDan Gohman       break;
541d934cb88SDan Gohman     }
542d934cb88SDan Gohman     case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_SLEB: {
543d934cb88SDan Gohman       uint32_t Value = ProvisionalValue(RelEntry);
544d934cb88SDan Gohman       WritePatchableSLEB(Stream, Value, Offset);
545d934cb88SDan Gohman       break;
546d934cb88SDan Gohman     }
547d934cb88SDan Gohman     case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_LEB: {
548d934cb88SDan Gohman       uint32_t Value = ProvisionalValue(RelEntry);
549d934cb88SDan Gohman       WritePatchableLEB(Stream, Value, Offset);
550d934cb88SDan Gohman       break;
551d934cb88SDan Gohman     }
552d934cb88SDan Gohman     case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_I32: {
553d934cb88SDan Gohman       uint32_t Value = ProvisionalValue(RelEntry);
554d934cb88SDan Gohman       WriteI32(Stream, Value, Offset);
555d934cb88SDan Gohman       break;
556d934cb88SDan Gohman     }
557d934cb88SDan Gohman     default:
5589d24fb7fSSam Clegg       llvm_unreachable("invalid relocation type");
559d934cb88SDan Gohman     }
560d934cb88SDan Gohman   }
56118eafb6cSDan Gohman }
56218eafb6cSDan Gohman 
563acd7d2b0SSam Clegg // Write out the portions of the relocation records that the linker will
564970d02c4SDan Gohman // need to handle.
565acd7d2b0SSam Clegg void WasmObjectWriter::writeRelocations(
566acd7d2b0SSam Clegg     ArrayRef<WasmRelocationEntry> Relocations, uint64_t HeaderSize) {
567acd7d2b0SSam Clegg   raw_pwrite_stream &Stream = getStream();
568acd7d2b0SSam Clegg   for (const WasmRelocationEntry& RelEntry : Relocations) {
569970d02c4SDan Gohman 
570acd7d2b0SSam Clegg     uint64_t Offset = RelEntry.Offset +
571acd7d2b0SSam Clegg                       RelEntry.FixupSection->getSectionOffset() + HeaderSize;
572acd7d2b0SSam Clegg     uint32_t Index = getRelocationIndexValue(RelEntry);
573970d02c4SDan Gohman 
574acd7d2b0SSam Clegg     encodeULEB128(RelEntry.Type, Stream);
575970d02c4SDan Gohman     encodeULEB128(Offset, Stream);
576acd7d2b0SSam Clegg     encodeULEB128(Index, Stream);
577acd7d2b0SSam Clegg     if (RelEntry.hasAddend())
578acd7d2b0SSam Clegg       encodeSLEB128(RelEntry.Addend, Stream);
579970d02c4SDan Gohman   }
580970d02c4SDan Gohman }
581970d02c4SDan Gohman 
5829e15f359SSam Clegg void WasmObjectWriter::writeTypeSection(
5839e15f359SSam Clegg     const SmallVector<WasmFunctionType, 4> &FunctionTypes) {
5849e15f359SSam Clegg   if (FunctionTypes.empty())
5859e15f359SSam Clegg     return;
5869e15f359SSam Clegg 
5879e15f359SSam Clegg   SectionBookkeeping Section;
5889e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_TYPE);
5899e15f359SSam Clegg 
5909e15f359SSam Clegg   encodeULEB128(FunctionTypes.size(), getStream());
5919e15f359SSam Clegg 
5929e15f359SSam Clegg   for (const WasmFunctionType &FuncTy : FunctionTypes) {
5939e15f359SSam Clegg     encodeSLEB128(wasm::WASM_TYPE_FUNC, getStream());
5949e15f359SSam Clegg     encodeULEB128(FuncTy.Params.size(), getStream());
5959e15f359SSam Clegg     for (wasm::ValType Ty : FuncTy.Params)
5969e15f359SSam Clegg       writeValueType(Ty);
5979e15f359SSam Clegg     encodeULEB128(FuncTy.Returns.size(), getStream());
5989e15f359SSam Clegg     for (wasm::ValType Ty : FuncTy.Returns)
5999e15f359SSam Clegg       writeValueType(Ty);
6009e15f359SSam Clegg   }
6019e15f359SSam Clegg 
6029e15f359SSam Clegg   endSection(Section);
6039e15f359SSam Clegg }
6049e15f359SSam Clegg 
605b7787fd0SSam Clegg 
6069e15f359SSam Clegg void WasmObjectWriter::writeImportSection(
6079e15f359SSam Clegg     const SmallVector<WasmImport, 4> &Imports) {
6089e15f359SSam Clegg   if (Imports.empty())
6099e15f359SSam Clegg     return;
6109e15f359SSam Clegg 
6119e15f359SSam Clegg   SectionBookkeeping Section;
6129e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_IMPORT);
6139e15f359SSam Clegg 
6149e15f359SSam Clegg   encodeULEB128(Imports.size(), getStream());
6159e15f359SSam Clegg   for (const WasmImport &Import : Imports) {
616b7787fd0SSam Clegg     writeString(Import.ModuleName);
617b7787fd0SSam Clegg     writeString(Import.FieldName);
6189e15f359SSam Clegg 
6199e15f359SSam Clegg     encodeULEB128(Import.Kind, getStream());
6209e15f359SSam Clegg 
6219e15f359SSam Clegg     switch (Import.Kind) {
6229e15f359SSam Clegg     case wasm::WASM_EXTERNAL_FUNCTION:
6239e15f359SSam Clegg       encodeULEB128(Import.Type, getStream());
6249e15f359SSam Clegg       break;
6259e15f359SSam Clegg     case wasm::WASM_EXTERNAL_GLOBAL:
6269e15f359SSam Clegg       encodeSLEB128(int32_t(Import.Type), getStream());
6279e15f359SSam Clegg       encodeULEB128(0, getStream()); // mutability
6289e15f359SSam Clegg       break;
6299e15f359SSam Clegg     default:
6309e15f359SSam Clegg       llvm_unreachable("unsupported import kind");
6319e15f359SSam Clegg     }
6329e15f359SSam Clegg   }
6339e15f359SSam Clegg 
6349e15f359SSam Clegg   endSection(Section);
6359e15f359SSam Clegg }
6369e15f359SSam Clegg 
6379e15f359SSam Clegg void WasmObjectWriter::writeFunctionSection(
6389e15f359SSam Clegg     const SmallVector<WasmFunction, 4> &Functions) {
6399e15f359SSam Clegg   if (Functions.empty())
6409e15f359SSam Clegg     return;
6419e15f359SSam Clegg 
6429e15f359SSam Clegg   SectionBookkeeping Section;
6439e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_FUNCTION);
6449e15f359SSam Clegg 
6459e15f359SSam Clegg   encodeULEB128(Functions.size(), getStream());
6469e15f359SSam Clegg   for (const WasmFunction &Func : Functions)
6479e15f359SSam Clegg     encodeULEB128(Func.Type, getStream());
6489e15f359SSam Clegg 
6499e15f359SSam Clegg   endSection(Section);
6509e15f359SSam Clegg }
6519e15f359SSam Clegg 
652d99f6078SSam Clegg void WasmObjectWriter::writeTableSection(uint32_t NumElements) {
6539e15f359SSam Clegg   // For now, always emit the table section, since indirect calls are not
6549e15f359SSam Clegg   // valid without it. In the future, we could perhaps be more clever and omit
6559e15f359SSam Clegg   // it if there are no indirect calls.
656d99f6078SSam Clegg 
6579e15f359SSam Clegg   SectionBookkeeping Section;
6589e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_TABLE);
6599e15f359SSam Clegg 
660d99f6078SSam Clegg   encodeULEB128(1, getStream());                       // The number of tables.
661d99f6078SSam Clegg                                                        // Fixed to 1 for now.
662d99f6078SSam Clegg   encodeSLEB128(wasm::WASM_TYPE_ANYFUNC, getStream()); // Type of table
6639e15f359SSam Clegg   encodeULEB128(0, getStream());                       // flags
664d99f6078SSam Clegg   encodeULEB128(NumElements, getStream());             // initial
6659e15f359SSam Clegg 
6669e15f359SSam Clegg   endSection(Section);
6679e15f359SSam Clegg }
6689e15f359SSam Clegg 
6699e15f359SSam Clegg void WasmObjectWriter::writeMemorySection(
6709e15f359SSam Clegg     const SmallVector<char, 0> &DataBytes) {
6719e15f359SSam Clegg   // For now, always emit the memory section, since loads and stores are not
6729e15f359SSam Clegg   // valid without it. In the future, we could perhaps be more clever and omit
6739e15f359SSam Clegg   // it if there are no loads or stores.
6749e15f359SSam Clegg   SectionBookkeeping Section;
6759e15f359SSam Clegg   uint32_t NumPages =
6769e15f359SSam Clegg       (DataBytes.size() + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
6779e15f359SSam Clegg 
6789e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_MEMORY);
6799e15f359SSam Clegg   encodeULEB128(1, getStream()); // number of memory spaces
6809e15f359SSam Clegg 
6819e15f359SSam Clegg   encodeULEB128(0, getStream()); // flags
6829e15f359SSam Clegg   encodeULEB128(NumPages, getStream()); // initial
6839e15f359SSam Clegg 
6849e15f359SSam Clegg   endSection(Section);
6859e15f359SSam Clegg }
6869e15f359SSam Clegg 
6879e15f359SSam Clegg void WasmObjectWriter::writeGlobalSection(
6889e15f359SSam Clegg     const SmallVector<WasmGlobal, 4> &Globals) {
6899e15f359SSam Clegg   if (Globals.empty())
6909e15f359SSam Clegg     return;
6919e15f359SSam Clegg 
6929e15f359SSam Clegg   SectionBookkeeping Section;
6939e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_GLOBAL);
6949e15f359SSam Clegg 
6959e15f359SSam Clegg   encodeULEB128(Globals.size(), getStream());
6969e15f359SSam Clegg   for (const WasmGlobal &Global : Globals) {
6979e15f359SSam Clegg     writeValueType(Global.Type);
6989e15f359SSam Clegg     write8(Global.IsMutable);
6999e15f359SSam Clegg 
7009e15f359SSam Clegg     if (Global.HasImport) {
7019e15f359SSam Clegg       assert(Global.InitialValue == 0);
7029e15f359SSam Clegg       write8(wasm::WASM_OPCODE_GET_GLOBAL);
7039e15f359SSam Clegg       encodeULEB128(Global.ImportIndex, getStream());
7049e15f359SSam Clegg     } else {
7059e15f359SSam Clegg       assert(Global.ImportIndex == 0);
7069e15f359SSam Clegg       write8(wasm::WASM_OPCODE_I32_CONST);
7079e15f359SSam Clegg       encodeSLEB128(Global.InitialValue, getStream()); // offset
7089e15f359SSam Clegg     }
7099e15f359SSam Clegg     write8(wasm::WASM_OPCODE_END);
7109e15f359SSam Clegg   }
7119e15f359SSam Clegg 
7129e15f359SSam Clegg   endSection(Section);
7139e15f359SSam Clegg }
7149e15f359SSam Clegg 
7159e15f359SSam Clegg void WasmObjectWriter::writeExportSection(
7169e15f359SSam Clegg     const SmallVector<WasmExport, 4> &Exports) {
7179e15f359SSam Clegg   if (Exports.empty())
7189e15f359SSam Clegg     return;
7199e15f359SSam Clegg 
7209e15f359SSam Clegg   SectionBookkeeping Section;
7219e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_EXPORT);
7229e15f359SSam Clegg 
7239e15f359SSam Clegg   encodeULEB128(Exports.size(), getStream());
7249e15f359SSam Clegg   for (const WasmExport &Export : Exports) {
725b7787fd0SSam Clegg     writeString(Export.FieldName);
7269e15f359SSam Clegg     encodeSLEB128(Export.Kind, getStream());
7279e15f359SSam Clegg     encodeULEB128(Export.Index, getStream());
7289e15f359SSam Clegg   }
7299e15f359SSam Clegg 
7309e15f359SSam Clegg   endSection(Section);
7319e15f359SSam Clegg }
7329e15f359SSam Clegg 
7339e15f359SSam Clegg void WasmObjectWriter::writeElemSection(
7349e15f359SSam Clegg     const SmallVector<uint32_t, 4> &TableElems) {
7359e15f359SSam Clegg   if (TableElems.empty())
7369e15f359SSam Clegg     return;
7379e15f359SSam Clegg 
7389e15f359SSam Clegg   SectionBookkeeping Section;
7399e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_ELEM);
7409e15f359SSam Clegg 
7419e15f359SSam Clegg   encodeULEB128(1, getStream()); // number of "segments"
7429e15f359SSam Clegg   encodeULEB128(0, getStream()); // the table index
7439e15f359SSam Clegg 
7449e15f359SSam Clegg   // init expr for starting offset
7459e15f359SSam Clegg   write8(wasm::WASM_OPCODE_I32_CONST);
7469e15f359SSam Clegg   encodeSLEB128(0, getStream());
7479e15f359SSam Clegg   write8(wasm::WASM_OPCODE_END);
7489e15f359SSam Clegg 
7499e15f359SSam Clegg   encodeULEB128(TableElems.size(), getStream());
7509e15f359SSam Clegg   for (uint32_t Elem : TableElems)
7519e15f359SSam Clegg     encodeULEB128(Elem, getStream());
7529e15f359SSam Clegg 
7539e15f359SSam Clegg   endSection(Section);
7549e15f359SSam Clegg }
7559e15f359SSam Clegg 
7569e15f359SSam Clegg void WasmObjectWriter::writeCodeSection(
7579e15f359SSam Clegg     const MCAssembler &Asm, const MCAsmLayout &Layout,
7589e15f359SSam Clegg     const SmallVector<WasmFunction, 4> &Functions) {
7599e15f359SSam Clegg   if (Functions.empty())
7609e15f359SSam Clegg     return;
7619e15f359SSam Clegg 
7629e15f359SSam Clegg   SectionBookkeeping Section;
7639e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_CODE);
7649e15f359SSam Clegg 
7659e15f359SSam Clegg   encodeULEB128(Functions.size(), getStream());
7669e15f359SSam Clegg 
7679e15f359SSam Clegg   for (const WasmFunction &Func : Functions) {
768*fe6414b0SSam Clegg     auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
7699e15f359SSam Clegg 
7709e15f359SSam Clegg     int64_t Size = 0;
7719e15f359SSam Clegg     if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
7729e15f359SSam Clegg       report_fatal_error(".size expression must be evaluatable");
7739e15f359SSam Clegg 
7749e15f359SSam Clegg     encodeULEB128(Size, getStream());
7759e15f359SSam Clegg 
776*fe6414b0SSam Clegg     FuncSection.setSectionOffset(getStream().tell() - Section.ContentsOffset);
7779e15f359SSam Clegg 
7789e15f359SSam Clegg     Asm.writeSectionData(&FuncSection, Layout);
7799e15f359SSam Clegg   }
7809e15f359SSam Clegg 
7819e15f359SSam Clegg   // Apply fixups.
782acd7d2b0SSam Clegg   applyRelocations(CodeRelocations, Section.ContentsOffset);
7839e15f359SSam Clegg 
7849e15f359SSam Clegg   endSection(Section);
7859e15f359SSam Clegg }
7869e15f359SSam Clegg 
7879e15f359SSam Clegg uint64_t WasmObjectWriter::writeDataSection(
788acd7d2b0SSam Clegg     const SmallVector<char, 0> &DataBytes) {
7899e15f359SSam Clegg   if (DataBytes.empty())
7909e15f359SSam Clegg     return 0;
7919e15f359SSam Clegg 
7929e15f359SSam Clegg   SectionBookkeeping Section;
7939e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_DATA);
7949e15f359SSam Clegg 
7959e15f359SSam Clegg   encodeULEB128(1, getStream()); // count
7969e15f359SSam Clegg   encodeULEB128(0, getStream()); // memory index
7979e15f359SSam Clegg   write8(wasm::WASM_OPCODE_I32_CONST);
7989e15f359SSam Clegg   encodeSLEB128(0, getStream()); // offset
7999e15f359SSam Clegg   write8(wasm::WASM_OPCODE_END);
8009e15f359SSam Clegg   encodeULEB128(DataBytes.size(), getStream()); // size
8019e15f359SSam Clegg   uint32_t HeaderSize = getStream().tell() - Section.ContentsOffset;
8029e15f359SSam Clegg   writeBytes(DataBytes); // data
8039e15f359SSam Clegg 
8049e15f359SSam Clegg   // Apply fixups.
805acd7d2b0SSam Clegg   applyRelocations(DataRelocations, Section.ContentsOffset + HeaderSize);
8069e15f359SSam Clegg 
8079e15f359SSam Clegg   endSection(Section);
8089e15f359SSam Clegg   return HeaderSize;
8099e15f359SSam Clegg }
8109e15f359SSam Clegg 
8119e15f359SSam Clegg void WasmObjectWriter::writeNameSection(
8129e15f359SSam Clegg     const SmallVector<WasmFunction, 4> &Functions,
8139e15f359SSam Clegg     const SmallVector<WasmImport, 4> &Imports,
8149e15f359SSam Clegg     unsigned NumFuncImports) {
8159e15f359SSam Clegg   uint32_t TotalFunctions = NumFuncImports + Functions.size();
8169e15f359SSam Clegg   if (TotalFunctions == 0)
8179e15f359SSam Clegg     return;
8189e15f359SSam Clegg 
8199e15f359SSam Clegg   SectionBookkeeping Section;
8209e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_CUSTOM, "name");
8219e15f359SSam Clegg   SectionBookkeeping SubSection;
8229e15f359SSam Clegg   startSection(SubSection, wasm::WASM_NAMES_FUNCTION);
8239e15f359SSam Clegg 
8249e15f359SSam Clegg   encodeULEB128(TotalFunctions, getStream());
8259e15f359SSam Clegg   uint32_t Index = 0;
8269e15f359SSam Clegg   for (const WasmImport &Import : Imports) {
8279e15f359SSam Clegg     if (Import.Kind == wasm::WASM_EXTERNAL_FUNCTION) {
8289e15f359SSam Clegg       encodeULEB128(Index, getStream());
829b7787fd0SSam Clegg       writeString(Import.FieldName);
8309e15f359SSam Clegg       ++Index;
8319e15f359SSam Clegg     }
8329e15f359SSam Clegg   }
8339e15f359SSam Clegg   for (const WasmFunction &Func : Functions) {
8349e15f359SSam Clegg     encodeULEB128(Index, getStream());
835b7787fd0SSam Clegg     writeString(Func.Sym->getName());
8369e15f359SSam Clegg     ++Index;
8379e15f359SSam Clegg   }
8389e15f359SSam Clegg 
8399e15f359SSam Clegg   endSection(SubSection);
8409e15f359SSam Clegg   endSection(Section);
8419e15f359SSam Clegg }
8429e15f359SSam Clegg 
843acd7d2b0SSam Clegg void WasmObjectWriter::writeCodeRelocSection() {
8449e15f359SSam Clegg   // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
8459e15f359SSam Clegg   // for descriptions of the reloc sections.
8469e15f359SSam Clegg 
8479e15f359SSam Clegg   if (CodeRelocations.empty())
8489e15f359SSam Clegg     return;
8499e15f359SSam Clegg 
8509e15f359SSam Clegg   SectionBookkeeping Section;
8519e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.CODE");
8529e15f359SSam Clegg 
8539e15f359SSam Clegg   encodeULEB128(wasm::WASM_SEC_CODE, getStream());
854acd7d2b0SSam Clegg   encodeULEB128(CodeRelocations.size(), getStream());
8559e15f359SSam Clegg 
856acd7d2b0SSam Clegg   writeRelocations(CodeRelocations, 0);
8579e15f359SSam Clegg 
8589e15f359SSam Clegg   endSection(Section);
8599e15f359SSam Clegg }
8609e15f359SSam Clegg 
861acd7d2b0SSam Clegg void WasmObjectWriter::writeDataRelocSection(uint64_t DataSectionHeaderSize) {
8629e15f359SSam Clegg   // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
8639e15f359SSam Clegg   // for descriptions of the reloc sections.
8649e15f359SSam Clegg 
8659e15f359SSam Clegg   if (DataRelocations.empty())
8669e15f359SSam Clegg     return;
8679e15f359SSam Clegg 
8689e15f359SSam Clegg   SectionBookkeeping Section;
8699e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.DATA");
8709e15f359SSam Clegg 
8719e15f359SSam Clegg   encodeULEB128(wasm::WASM_SEC_DATA, getStream());
8729e15f359SSam Clegg   encodeULEB128(DataRelocations.size(), getStream());
8739e15f359SSam Clegg 
874acd7d2b0SSam Clegg   writeRelocations(DataRelocations, DataSectionHeaderSize);
8759e15f359SSam Clegg 
8769e15f359SSam Clegg   endSection(Section);
8779e15f359SSam Clegg }
8789e15f359SSam Clegg 
8799e15f359SSam Clegg void WasmObjectWriter::writeLinkingMetaDataSection(
880b7787fd0SSam Clegg     ArrayRef<StringRef> WeakSymbols, bool HasStackPointer,
881b7787fd0SSam Clegg     uint32_t StackPointerGlobal) {
882b7787fd0SSam Clegg   if (!HasStackPointer && WeakSymbols.empty())
8839e15f359SSam Clegg     return;
884b7787fd0SSam Clegg 
8859e15f359SSam Clegg   SectionBookkeeping Section;
8869e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_CUSTOM, "linking");
887b7787fd0SSam Clegg   SectionBookkeeping SubSection;
8889e15f359SSam Clegg 
889b7787fd0SSam Clegg   if (HasStackPointer) {
890b7787fd0SSam Clegg     startSection(SubSection, wasm::WASM_STACK_POINTER);
8919e15f359SSam Clegg     encodeULEB128(StackPointerGlobal, getStream()); // id
892b7787fd0SSam Clegg     endSection(SubSection);
893b7787fd0SSam Clegg   }
894b7787fd0SSam Clegg 
895b7787fd0SSam Clegg   if (WeakSymbols.size() != 0) {
896b7787fd0SSam Clegg     startSection(SubSection, wasm::WASM_SYMBOL_INFO);
897b7787fd0SSam Clegg     encodeULEB128(WeakSymbols.size(), getStream());
898b7787fd0SSam Clegg     for (const StringRef Export: WeakSymbols) {
899b7787fd0SSam Clegg       writeString(Export);
900b7787fd0SSam Clegg       encodeULEB128(wasm::WASM_SYMBOL_FLAG_WEAK, getStream());
901b7787fd0SSam Clegg     }
902b7787fd0SSam Clegg     endSection(SubSection);
903b7787fd0SSam Clegg   }
9049e15f359SSam Clegg 
9059e15f359SSam Clegg   endSection(Section);
9069e15f359SSam Clegg }
9079e15f359SSam Clegg 
90818eafb6cSDan Gohman void WasmObjectWriter::writeObject(MCAssembler &Asm,
90918eafb6cSDan Gohman                                    const MCAsmLayout &Layout) {
910b7787fd0SSam Clegg   DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
91182607f56SDan Gohman   MCContext &Ctx = Asm.getContext();
912b879539aSDerek Schuff   wasm::ValType PtrType = is64Bit() ? wasm::ValType::I64 : wasm::ValType::I32;
913d934cb88SDan Gohman 
914d934cb88SDan Gohman   // Collect information from the available symbols.
915d934cb88SDan Gohman   SmallVector<WasmFunctionType, 4> FunctionTypes;
916d934cb88SDan Gohman   SmallVector<WasmFunction, 4> Functions;
917d934cb88SDan Gohman   SmallVector<uint32_t, 4> TableElems;
918d934cb88SDan Gohman   SmallVector<WasmGlobal, 4> Globals;
919d934cb88SDan Gohman   SmallVector<WasmImport, 4> Imports;
920d934cb88SDan Gohman   SmallVector<WasmExport, 4> Exports;
921b7787fd0SSam Clegg   SmallVector<StringRef, 4> WeakSymbols;
922d934cb88SDan Gohman   SmallPtrSet<const MCSymbolWasm *, 4> IsAddressTaken;
923d934cb88SDan Gohman   unsigned NumFuncImports = 0;
924d934cb88SDan Gohman   unsigned NumGlobalImports = 0;
925d934cb88SDan Gohman   SmallVector<char, 0> DataBytes;
926970d02c4SDan Gohman   uint32_t StackPointerGlobal = 0;
927970d02c4SDan Gohman   bool HasStackPointer = false;
928d934cb88SDan Gohman 
929d934cb88SDan Gohman   // Populate the IsAddressTaken set.
930b7787fd0SSam Clegg   for (const WasmRelocationEntry &RelEntry : CodeRelocations) {
931d934cb88SDan Gohman     switch (RelEntry.Type) {
932d934cb88SDan Gohman     case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
933d934cb88SDan Gohman     case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_SLEB:
934d934cb88SDan Gohman       IsAddressTaken.insert(RelEntry.Symbol);
935d934cb88SDan Gohman       break;
936d934cb88SDan Gohman     default:
937d934cb88SDan Gohman       break;
938d934cb88SDan Gohman     }
939d934cb88SDan Gohman   }
940b7787fd0SSam Clegg   for (const WasmRelocationEntry &RelEntry : DataRelocations) {
941d934cb88SDan Gohman     switch (RelEntry.Type) {
942d934cb88SDan Gohman     case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
943d934cb88SDan Gohman     case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_I32:
944d934cb88SDan Gohman       IsAddressTaken.insert(RelEntry.Symbol);
945d934cb88SDan Gohman       break;
946d934cb88SDan Gohman     default:
947d934cb88SDan Gohman       break;
948d934cb88SDan Gohman     }
949d934cb88SDan Gohman   }
950d934cb88SDan Gohman 
951d934cb88SDan Gohman   // Populate the Imports set.
952d934cb88SDan Gohman   for (const MCSymbol &S : Asm.symbols()) {
953d934cb88SDan Gohman     const auto &WS = static_cast<const MCSymbolWasm &>(S);
954b879539aSDerek Schuff     int32_t Type;
955d934cb88SDan Gohman 
956d934cb88SDan Gohman     if (WS.isFunction()) {
957d934cb88SDan Gohman       // Prepare the function's type, if we haven't seen it yet.
958d934cb88SDan Gohman       WasmFunctionType F;
959d934cb88SDan Gohman       F.Returns = WS.getReturns();
960d934cb88SDan Gohman       F.Params = WS.getParams();
961d934cb88SDan Gohman       auto Pair =
962d934cb88SDan Gohman           FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size()));
963d934cb88SDan Gohman       if (Pair.second)
964d934cb88SDan Gohman         FunctionTypes.push_back(F);
965d934cb88SDan Gohman 
966d934cb88SDan Gohman       Type = Pair.first->second;
967d934cb88SDan Gohman     } else {
968b879539aSDerek Schuff       Type = int32_t(PtrType);
969d934cb88SDan Gohman     }
970d934cb88SDan Gohman 
971d934cb88SDan Gohman     // If the symbol is not defined in this translation unit, import it.
972d934cb88SDan Gohman     if (!WS.isTemporary() && !WS.isDefined(/*SetUsed=*/false)) {
973d934cb88SDan Gohman       WasmImport Import;
974d934cb88SDan Gohman       Import.ModuleName = WS.getModuleName();
975d934cb88SDan Gohman       Import.FieldName = WS.getName();
976d934cb88SDan Gohman 
977d934cb88SDan Gohman       if (WS.isFunction()) {
978d934cb88SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
979d934cb88SDan Gohman         Import.Type = Type;
980d934cb88SDan Gohman         SymbolIndices[&WS] = NumFuncImports;
981d934cb88SDan Gohman         ++NumFuncImports;
982d934cb88SDan Gohman       } else {
983d934cb88SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
984d934cb88SDan Gohman         Import.Type = Type;
985d934cb88SDan Gohman         SymbolIndices[&WS] = NumGlobalImports;
986d934cb88SDan Gohman         ++NumGlobalImports;
987d934cb88SDan Gohman       }
988d934cb88SDan Gohman 
989d934cb88SDan Gohman       Imports.push_back(Import);
990d934cb88SDan Gohman     }
991d934cb88SDan Gohman   }
992d934cb88SDan Gohman 
99382607f56SDan Gohman   // In the special .global_variables section, we've encoded global
99482607f56SDan Gohman   // variables used by the function. Translate them into the Globals
99582607f56SDan Gohman   // list.
99682607f56SDan Gohman   MCSectionWasm *GlobalVars = Ctx.getWasmSection(".global_variables", 0, 0);
99782607f56SDan Gohman   if (!GlobalVars->getFragmentList().empty()) {
99882607f56SDan Gohman     if (GlobalVars->getFragmentList().size() != 1)
99982607f56SDan Gohman       report_fatal_error("only one .global_variables fragment supported");
100082607f56SDan Gohman     const MCFragment &Frag = *GlobalVars->begin();
100182607f56SDan Gohman     if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
100282607f56SDan Gohman       report_fatal_error("only data supported in .global_variables");
1003*fe6414b0SSam Clegg     const auto &DataFrag = cast<MCDataFragment>(Frag);
100482607f56SDan Gohman     if (!DataFrag.getFixups().empty())
100582607f56SDan Gohman       report_fatal_error("fixups not supported in .global_variables");
100682607f56SDan Gohman     const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1007970d02c4SDan Gohman     for (const uint8_t *p = (const uint8_t *)Contents.data(),
1008970d02c4SDan Gohman                      *end = (const uint8_t *)Contents.data() + Contents.size();
1009970d02c4SDan Gohman          p != end; ) {
101082607f56SDan Gohman       WasmGlobal G;
1011970d02c4SDan Gohman       if (end - p < 3)
1012970d02c4SDan Gohman         report_fatal_error("truncated global variable encoding");
1013970d02c4SDan Gohman       G.Type = wasm::ValType(int8_t(*p++));
1014970d02c4SDan Gohman       G.IsMutable = bool(*p++);
1015970d02c4SDan Gohman       G.HasImport = bool(*p++);
1016970d02c4SDan Gohman       if (G.HasImport) {
101782607f56SDan Gohman         G.InitialValue = 0;
1018970d02c4SDan Gohman 
1019970d02c4SDan Gohman         WasmImport Import;
1020970d02c4SDan Gohman         Import.ModuleName = (const char *)p;
1021970d02c4SDan Gohman         const uint8_t *nul = (const uint8_t *)memchr(p, '\0', end - p);
1022970d02c4SDan Gohman         if (!nul)
1023970d02c4SDan Gohman           report_fatal_error("global module name must be nul-terminated");
1024970d02c4SDan Gohman         p = nul + 1;
1025970d02c4SDan Gohman         nul = (const uint8_t *)memchr(p, '\0', end - p);
1026970d02c4SDan Gohman         if (!nul)
1027970d02c4SDan Gohman           report_fatal_error("global base name must be nul-terminated");
1028970d02c4SDan Gohman         Import.FieldName = (const char *)p;
1029970d02c4SDan Gohman         p = nul + 1;
1030970d02c4SDan Gohman 
1031970d02c4SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1032970d02c4SDan Gohman         Import.Type = int32_t(G.Type);
1033970d02c4SDan Gohman 
1034970d02c4SDan Gohman         G.ImportIndex = NumGlobalImports;
1035970d02c4SDan Gohman         ++NumGlobalImports;
1036970d02c4SDan Gohman 
1037970d02c4SDan Gohman         Imports.push_back(Import);
1038970d02c4SDan Gohman       } else {
1039970d02c4SDan Gohman         unsigned n;
1040970d02c4SDan Gohman         G.InitialValue = decodeSLEB128(p, &n);
1041970d02c4SDan Gohman         G.ImportIndex = 0;
1042c8da0c0bSSimon Pilgrim         if ((ptrdiff_t)n > end - p)
1043970d02c4SDan Gohman           report_fatal_error("global initial value must be valid SLEB128");
1044970d02c4SDan Gohman         p += n;
1045970d02c4SDan Gohman       }
104682607f56SDan Gohman       Globals.push_back(G);
104782607f56SDan Gohman     }
104882607f56SDan Gohman   }
104982607f56SDan Gohman 
1050970d02c4SDan Gohman   // In the special .stack_pointer section, we've encoded the stack pointer
1051970d02c4SDan Gohman   // index.
1052970d02c4SDan Gohman   MCSectionWasm *StackPtr = Ctx.getWasmSection(".stack_pointer", 0, 0);
1053970d02c4SDan Gohman   if (!StackPtr->getFragmentList().empty()) {
1054970d02c4SDan Gohman     if (StackPtr->getFragmentList().size() != 1)
1055970d02c4SDan Gohman       report_fatal_error("only one .stack_pointer fragment supported");
1056970d02c4SDan Gohman     const MCFragment &Frag = *StackPtr->begin();
1057970d02c4SDan Gohman     if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1058970d02c4SDan Gohman       report_fatal_error("only data supported in .stack_pointer");
1059*fe6414b0SSam Clegg     const auto &DataFrag = cast<MCDataFragment>(Frag);
1060970d02c4SDan Gohman     if (!DataFrag.getFixups().empty())
1061970d02c4SDan Gohman       report_fatal_error("fixups not supported in .stack_pointer");
1062970d02c4SDan Gohman     const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1063970d02c4SDan Gohman     if (Contents.size() != 4)
1064970d02c4SDan Gohman       report_fatal_error("only one entry supported in .stack_pointer");
1065970d02c4SDan Gohman     HasStackPointer = true;
1066970d02c4SDan Gohman     StackPointerGlobal = NumGlobalImports + *(const int32_t *)Contents.data();
1067970d02c4SDan Gohman   }
1068970d02c4SDan Gohman 
1069b7787fd0SSam Clegg   // Handle regular defined and undefined symbols.
1070d934cb88SDan Gohman   for (const MCSymbol &S : Asm.symbols()) {
1071d934cb88SDan Gohman     // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1072d934cb88SDan Gohman     // or used in relocations.
1073d934cb88SDan Gohman     if (S.isTemporary() && S.getName().empty())
1074d934cb88SDan Gohman       continue;
1075b7787fd0SSam Clegg 
1076b7787fd0SSam Clegg     // Variable references (weak references) are handled in a second pass
1077b7787fd0SSam Clegg     if (S.isVariable())
1078b7787fd0SSam Clegg       continue;
1079b7787fd0SSam Clegg 
1080d934cb88SDan Gohman     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1081b7787fd0SSam Clegg     DEBUG(dbgs() << "MCSymbol: '" << S << "'"
1082b7787fd0SSam Clegg                  << " isDefined=" << S.isDefined() << " isExternal="
1083b7787fd0SSam Clegg                  << S.isExternal() << " isTemporary=" << S.isTemporary()
1084b7787fd0SSam Clegg                  << " isFunction=" << WS.isFunction()
1085b7787fd0SSam Clegg                  << " isWeak=" << WS.isWeak()
1086b7787fd0SSam Clegg                  << " isVariable=" << WS.isVariable() << "\n");
1087b7787fd0SSam Clegg 
1088b7787fd0SSam Clegg     if (WS.isWeak())
1089b7787fd0SSam Clegg       WeakSymbols.push_back(WS.getName());
1090b7787fd0SSam Clegg 
1091d934cb88SDan Gohman     unsigned Index;
1092b7787fd0SSam Clegg 
1093d934cb88SDan Gohman     if (WS.isFunction()) {
1094d934cb88SDan Gohman       // Prepare the function's type, if we haven't seen it yet.
1095d934cb88SDan Gohman       WasmFunctionType F;
1096d934cb88SDan Gohman       F.Returns = WS.getReturns();
1097d934cb88SDan Gohman       F.Params = WS.getParams();
1098d934cb88SDan Gohman       auto Pair =
1099d934cb88SDan Gohman           FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size()));
1100d934cb88SDan Gohman       if (Pair.second)
1101d934cb88SDan Gohman         FunctionTypes.push_back(F);
1102d934cb88SDan Gohman 
1103b879539aSDerek Schuff       int32_t Type = Pair.first->second;
1104d934cb88SDan Gohman 
1105d934cb88SDan Gohman       if (WS.isDefined(/*SetUsed=*/false)) {
1106b7787fd0SSam Clegg         if (WS.getOffset() != 0)
1107b7787fd0SSam Clegg           report_fatal_error(
1108b7787fd0SSam Clegg               "function sections must contain one function each");
1109b7787fd0SSam Clegg 
1110b7787fd0SSam Clegg         if (WS.getSize() == 0)
1111b7787fd0SSam Clegg           report_fatal_error(
1112b7787fd0SSam Clegg               "function symbols must have a size set with .size");
1113b7787fd0SSam Clegg 
1114d934cb88SDan Gohman         // A definition. Take the next available index.
1115d934cb88SDan Gohman         Index = NumFuncImports + Functions.size();
1116d934cb88SDan Gohman 
1117d934cb88SDan Gohman         // Prepare the function.
1118d934cb88SDan Gohman         WasmFunction Func;
1119d934cb88SDan Gohman         Func.Type = Type;
1120d934cb88SDan Gohman         Func.Sym = &WS;
1121d934cb88SDan Gohman         SymbolIndices[&WS] = Index;
1122d934cb88SDan Gohman         Functions.push_back(Func);
1123d934cb88SDan Gohman       } else {
1124b7787fd0SSam Clegg         // Should be no such thing as weak undefined symbol
1125b7787fd0SSam Clegg         assert(!WS.isVariable());
1126b7787fd0SSam Clegg 
1127d934cb88SDan Gohman         // An import; the index was assigned above.
1128d934cb88SDan Gohman         Index = SymbolIndices.find(&WS)->second;
1129d934cb88SDan Gohman       }
1130d934cb88SDan Gohman 
1131d934cb88SDan Gohman       // If needed, prepare the function to be called indirectly.
1132d99f6078SSam Clegg       if (IsAddressTaken.count(&WS)) {
1133d99f6078SSam Clegg         IndirectSymbolIndices[&WS] = TableElems.size();
1134d934cb88SDan Gohman         TableElems.push_back(Index);
1135d99f6078SSam Clegg       }
1136d934cb88SDan Gohman     } else {
1137c38e947eSSam Clegg       if (WS.isTemporary() && !WS.getSize())
1138c38e947eSSam Clegg         continue;
1139c38e947eSSam Clegg 
1140*fe6414b0SSam Clegg       if (!WS.isDefined(/*SetUsed=*/false))
1141*fe6414b0SSam Clegg         continue;
1142*fe6414b0SSam Clegg 
1143d934cb88SDan Gohman       if (WS.getOffset() != 0)
1144c38e947eSSam Clegg         report_fatal_error("data sections must contain one variable each: " +
1145c38e947eSSam Clegg                            WS.getName());
1146d934cb88SDan Gohman       if (!WS.getSize())
1147c38e947eSSam Clegg         report_fatal_error("data symbols must have a size set with .size: " +
1148c38e947eSSam Clegg                            WS.getName());
1149d934cb88SDan Gohman 
1150d934cb88SDan Gohman       int64_t Size = 0;
1151d934cb88SDan Gohman       if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1152d934cb88SDan Gohman         report_fatal_error(".size expression must be evaluatable");
1153d934cb88SDan Gohman 
1154*fe6414b0SSam Clegg       auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
1155d934cb88SDan Gohman 
1156d934cb88SDan Gohman       if (uint64_t(Size) != Layout.getSectionFileSize(&DataSection))
1157d934cb88SDan Gohman         report_fatal_error("data sections must contain at most one variable");
1158d934cb88SDan Gohman 
1159d934cb88SDan Gohman       DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
1160d934cb88SDan Gohman 
1161d934cb88SDan Gohman       DataSection.setSectionOffset(DataBytes.size());
1162d934cb88SDan Gohman 
1163*fe6414b0SSam Clegg       for (const MCFragment &Frag : DataSection) {
1164d934cb88SDan Gohman         if (Frag.hasInstructions())
1165d934cb88SDan Gohman           report_fatal_error("only data supported in data sections");
1166d934cb88SDan Gohman 
1167*fe6414b0SSam Clegg         if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
1168d934cb88SDan Gohman           if (Align->getValueSize() != 1)
1169d934cb88SDan Gohman             report_fatal_error("only byte values supported for alignment");
1170d934cb88SDan Gohman           // If nops are requested, use zeros, as this is the data section.
1171d934cb88SDan Gohman           uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
1172d934cb88SDan Gohman           uint64_t Size = std::min<uint64_t>(alignTo(DataBytes.size(),
1173d934cb88SDan Gohman                                                      Align->getAlignment()),
1174d934cb88SDan Gohman                                              DataBytes.size() +
1175d934cb88SDan Gohman                                                  Align->getMaxBytesToEmit());
1176d934cb88SDan Gohman           DataBytes.resize(Size, Value);
1177*fe6414b0SSam Clegg         } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
1178d934cb88SDan Gohman           DataBytes.insert(DataBytes.end(), Size, Fill->getValue());
1179d934cb88SDan Gohman         } else {
1180*fe6414b0SSam Clegg           const auto &DataFrag = cast<MCDataFragment>(Frag);
1181d934cb88SDan Gohman           const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1182d934cb88SDan Gohman 
1183d934cb88SDan Gohman           DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
1184d934cb88SDan Gohman         }
1185d934cb88SDan Gohman       }
1186d934cb88SDan Gohman 
11871c154a61SSam Clegg       // For each global, prepare a corresponding wasm global holding its
11881c154a61SSam Clegg       // address.  For externals these will also be named exports.
1189d934cb88SDan Gohman       Index = NumGlobalImports + Globals.size();
1190d934cb88SDan Gohman 
1191d934cb88SDan Gohman       WasmGlobal Global;
1192d934cb88SDan Gohman       Global.Type = PtrType;
1193d934cb88SDan Gohman       Global.IsMutable = false;
1194970d02c4SDan Gohman       Global.HasImport = false;
1195d934cb88SDan Gohman       Global.InitialValue = DataSection.getSectionOffset();
1196970d02c4SDan Gohman       Global.ImportIndex = 0;
1197d934cb88SDan Gohman       SymbolIndices[&WS] = Index;
1198d934cb88SDan Gohman       Globals.push_back(Global);
1199d934cb88SDan Gohman     }
1200d934cb88SDan Gohman 
1201d934cb88SDan Gohman     // If the symbol is visible outside this translation unit, export it.
1202b7787fd0SSam Clegg     if (WS.isExternal() && WS.isDefined(/*SetUsed=*/false)) {
1203d934cb88SDan Gohman       WasmExport Export;
1204d934cb88SDan Gohman       Export.FieldName = WS.getName();
1205d934cb88SDan Gohman       Export.Index = Index;
1206d934cb88SDan Gohman       if (WS.isFunction())
1207d934cb88SDan Gohman         Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1208d934cb88SDan Gohman       else
1209d934cb88SDan Gohman         Export.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1210d934cb88SDan Gohman       Exports.push_back(Export);
1211d934cb88SDan Gohman     }
1212d934cb88SDan Gohman   }
1213d934cb88SDan Gohman 
1214b7787fd0SSam Clegg   // Handle weak aliases
1215b7787fd0SSam Clegg   for (const MCSymbol &S : Asm.symbols()) {
1216b7787fd0SSam Clegg     if (!S.isVariable())
1217b7787fd0SSam Clegg       continue;
1218b7787fd0SSam Clegg     assert(S.isExternal());
1219b7787fd0SSam Clegg     assert(S.isDefined(/*SetUsed=*/false));
1220b7787fd0SSam Clegg 
1221b7787fd0SSam Clegg     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1222b7787fd0SSam Clegg 
1223b7787fd0SSam Clegg     // Find the target symbol of this weak alias
1224b7787fd0SSam Clegg     const MCExpr *Expr = WS.getVariableValue();
1225b7787fd0SSam Clegg     auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr);
1226*fe6414b0SSam Clegg     const auto *ResolvedSym = cast<MCSymbolWasm>(&Inner->getSymbol());
1227b7787fd0SSam Clegg     uint32_t Index = SymbolIndices.find(ResolvedSym)->second;
1228b7787fd0SSam Clegg     DEBUG(dbgs() << "Weak alias: '" << WS << "' -> '" << ResolvedSym << "' = " << Index << "\n");
1229b7787fd0SSam Clegg     SymbolIndices[&WS] = Index;
1230b7787fd0SSam Clegg 
1231b7787fd0SSam Clegg     WasmExport Export;
1232b7787fd0SSam Clegg     Export.FieldName = WS.getName();
1233b7787fd0SSam Clegg     Export.Index = Index;
1234b7787fd0SSam Clegg     if (WS.isFunction())
1235b7787fd0SSam Clegg       Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1236b7787fd0SSam Clegg     else
1237b7787fd0SSam Clegg       Export.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1238b7787fd0SSam Clegg     WeakSymbols.push_back(Export.FieldName);
1239b7787fd0SSam Clegg     Exports.push_back(Export);
1240b7787fd0SSam Clegg   }
1241b7787fd0SSam Clegg 
1242d934cb88SDan Gohman   // Add types for indirect function calls.
1243acd7d2b0SSam Clegg   for (const WasmRelocationEntry &Fixup : CodeRelocations) {
1244acd7d2b0SSam Clegg     if (Fixup.Type != wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB)
1245acd7d2b0SSam Clegg       continue;
1246970d02c4SDan Gohman 
1247d934cb88SDan Gohman     WasmFunctionType F;
1248d934cb88SDan Gohman     F.Returns = Fixup.Symbol->getReturns();
1249d934cb88SDan Gohman     F.Params = Fixup.Symbol->getParams();
1250d934cb88SDan Gohman     auto Pair =
1251d934cb88SDan Gohman         FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size()));
1252d934cb88SDan Gohman     if (Pair.second)
1253d934cb88SDan Gohman       FunctionTypes.push_back(F);
1254d934cb88SDan Gohman 
1255acd7d2b0SSam Clegg     TypeIndices[Fixup.Symbol] = Pair.first->second;
1256d934cb88SDan Gohman   }
1257d934cb88SDan Gohman 
125818eafb6cSDan Gohman   // Write out the Wasm header.
125918eafb6cSDan Gohman   writeHeader(Asm);
126018eafb6cSDan Gohman 
12619e15f359SSam Clegg   writeTypeSection(FunctionTypes);
12629e15f359SSam Clegg   writeImportSection(Imports);
12639e15f359SSam Clegg   writeFunctionSection(Functions);
1264d99f6078SSam Clegg   writeTableSection(TableElems.size());
12659e15f359SSam Clegg   writeMemorySection(DataBytes);
12669e15f359SSam Clegg   writeGlobalSection(Globals);
12679e15f359SSam Clegg   writeExportSection(Exports);
12689e15f359SSam Clegg   // TODO: Start Section
12699e15f359SSam Clegg   writeElemSection(TableElems);
1270acd7d2b0SSam Clegg   writeCodeSection(Asm, Layout, Functions);
1271acd7d2b0SSam Clegg   uint64_t DataSectionHeaderSize = writeDataSection(DataBytes);
12729e15f359SSam Clegg   writeNameSection(Functions, Imports, NumFuncImports);
1273acd7d2b0SSam Clegg   writeCodeRelocSection();
1274acd7d2b0SSam Clegg   writeDataRelocSection(DataSectionHeaderSize);
1275b7787fd0SSam Clegg   writeLinkingMetaDataSection(WeakSymbols, HasStackPointer, StackPointerGlobal);
1276970d02c4SDan Gohman 
1277d934cb88SDan Gohman   // TODO: Translate the .comment section to the output.
1278d934cb88SDan Gohman   // TODO: Translate debug sections to the output.
127918eafb6cSDan Gohman }
128018eafb6cSDan Gohman 
128118eafb6cSDan Gohman MCObjectWriter *llvm::createWasmObjectWriter(MCWasmObjectTargetWriter *MOTW,
128218eafb6cSDan Gohman                                              raw_pwrite_stream &OS) {
128318eafb6cSDan Gohman   return new WasmObjectWriter(MOTW, OS);
128418eafb6cSDan Gohman }
1285