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/MCAsmLayout.h"
1918eafb6cSDan Gohman #include "llvm/MC/MCAssembler.h"
2018eafb6cSDan Gohman #include "llvm/MC/MCContext.h"
2118eafb6cSDan Gohman #include "llvm/MC/MCExpr.h"
2218eafb6cSDan Gohman #include "llvm/MC/MCFixupKindInfo.h"
2318eafb6cSDan Gohman #include "llvm/MC/MCObjectWriter.h"
2418eafb6cSDan Gohman #include "llvm/MC/MCSectionWasm.h"
2518eafb6cSDan Gohman #include "llvm/MC/MCSymbolWasm.h"
2618eafb6cSDan Gohman #include "llvm/MC/MCValue.h"
2718eafb6cSDan Gohman #include "llvm/MC/MCWasmObjectWriter.h"
28d934cb88SDan Gohman #include "llvm/Support/Casting.h"
2918eafb6cSDan Gohman #include "llvm/Support/Debug.h"
3018eafb6cSDan Gohman #include "llvm/Support/ErrorHandling.h"
31d934cb88SDan Gohman #include "llvm/Support/LEB128.h"
3218eafb6cSDan Gohman #include "llvm/Support/StringSaver.h"
3318eafb6cSDan Gohman #include <vector>
3418eafb6cSDan Gohman 
3518eafb6cSDan Gohman using namespace llvm;
3618eafb6cSDan Gohman 
375e3d33a7SSam Clegg #define DEBUG_TYPE "mc"
3818eafb6cSDan Gohman 
3918eafb6cSDan Gohman namespace {
409e15f359SSam Clegg 
4130e1bbc1SSam Clegg // Went we ceate the indirect function table we start at 1, so that there is
4230e1bbc1SSam Clegg // and emtpy slot at 0 and therefore calling a null function pointer will trap.
4330e1bbc1SSam Clegg static const uint32_t kInitialTableOffset = 1;
4430e1bbc1SSam Clegg 
45d934cb88SDan Gohman // For patching purposes, we need to remember where each section starts, both
46d934cb88SDan Gohman // for patching up the section size field, and for patching up references to
47d934cb88SDan Gohman // locations within the section.
48d934cb88SDan Gohman struct SectionBookkeeping {
49d934cb88SDan Gohman   // Where the size of the section is written.
50d934cb88SDan Gohman   uint64_t SizeOffset;
51d934cb88SDan Gohman   // Where the contents of the section starts (after the header).
52d934cb88SDan Gohman   uint64_t ContentsOffset;
53*6f08c84aSSam Clegg   uint32_t Index;
54d934cb88SDan Gohman };
55d934cb88SDan Gohman 
569e15f359SSam Clegg // The signature of a wasm function, in a struct capable of being used as a
579e15f359SSam Clegg // DenseMap key.
589e15f359SSam Clegg struct WasmFunctionType {
599e15f359SSam Clegg   // Support empty and tombstone instances, needed by DenseMap.
609e15f359SSam Clegg   enum { Plain, Empty, Tombstone } State;
619e15f359SSam Clegg 
629e15f359SSam Clegg   // The return types of the function.
639e15f359SSam Clegg   SmallVector<wasm::ValType, 1> Returns;
649e15f359SSam Clegg 
659e15f359SSam Clegg   // The parameter types of the function.
669e15f359SSam Clegg   SmallVector<wasm::ValType, 4> Params;
679e15f359SSam Clegg 
689e15f359SSam Clegg   WasmFunctionType() : State(Plain) {}
699e15f359SSam Clegg 
709e15f359SSam Clegg   bool operator==(const WasmFunctionType &Other) const {
719e15f359SSam Clegg     return State == Other.State && Returns == Other.Returns &&
729e15f359SSam Clegg            Params == Other.Params;
739e15f359SSam Clegg   }
749e15f359SSam Clegg };
759e15f359SSam Clegg 
769e15f359SSam Clegg // Traits for using WasmFunctionType in a DenseMap.
779e15f359SSam Clegg struct WasmFunctionTypeDenseMapInfo {
789e15f359SSam Clegg   static WasmFunctionType getEmptyKey() {
799e15f359SSam Clegg     WasmFunctionType FuncTy;
809e15f359SSam Clegg     FuncTy.State = WasmFunctionType::Empty;
819e15f359SSam Clegg     return FuncTy;
829e15f359SSam Clegg   }
839e15f359SSam Clegg   static WasmFunctionType getTombstoneKey() {
849e15f359SSam Clegg     WasmFunctionType FuncTy;
859e15f359SSam Clegg     FuncTy.State = WasmFunctionType::Tombstone;
869e15f359SSam Clegg     return FuncTy;
879e15f359SSam Clegg   }
889e15f359SSam Clegg   static unsigned getHashValue(const WasmFunctionType &FuncTy) {
899e15f359SSam Clegg     uintptr_t Value = FuncTy.State;
909e15f359SSam Clegg     for (wasm::ValType Ret : FuncTy.Returns)
919e15f359SSam Clegg       Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Ret));
929e15f359SSam Clegg     for (wasm::ValType Param : FuncTy.Params)
939e15f359SSam Clegg       Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Param));
949e15f359SSam Clegg     return Value;
959e15f359SSam Clegg   }
969e15f359SSam Clegg   static bool isEqual(const WasmFunctionType &LHS,
979e15f359SSam Clegg                       const WasmFunctionType &RHS) {
989e15f359SSam Clegg     return LHS == RHS;
999e15f359SSam Clegg   }
1009e15f359SSam Clegg };
1019e15f359SSam Clegg 
1027c395943SSam Clegg // A wasm data segment.  A wasm binary contains only a single data section
1037c395943SSam Clegg // but that can contain many segments, each with their own virtual location
1047c395943SSam Clegg // in memory.  Each MCSection data created by llvm is modeled as its own
1057c395943SSam Clegg // wasm data segment.
1067c395943SSam Clegg struct WasmDataSegment {
1077c395943SSam Clegg   MCSectionWasm *Section;
108d95ed959SSam Clegg   StringRef Name;
1097c395943SSam Clegg   uint32_t Offset;
11063ebb813SSam Clegg   uint32_t Alignment;
11163ebb813SSam Clegg   uint32_t Flags;
1127c395943SSam Clegg   SmallVector<char, 4> Data;
1137c395943SSam Clegg };
1147c395943SSam Clegg 
1159e15f359SSam Clegg // A wasm function to be written into the function section.
1169e15f359SSam Clegg struct WasmFunction {
1179e15f359SSam Clegg   int32_t Type;
1189e15f359SSam Clegg   const MCSymbolWasm *Sym;
1199e15f359SSam Clegg };
1209e15f359SSam Clegg 
1219e15f359SSam Clegg // A wasm global to be written into the global section.
1229e15f359SSam Clegg struct WasmGlobal {
1236e7f1826SSam Clegg   wasm::WasmGlobalType Type;
1249e15f359SSam Clegg   uint64_t InitialValue;
1259e15f359SSam Clegg };
1269e15f359SSam Clegg 
127ea7caceeSSam Clegg // Information about a single item which is part of a COMDAT.  For each data
128ea7caceeSSam Clegg // segment or function which is in the COMDAT, there is a corresponding
129ea7caceeSSam Clegg // WasmComdatEntry.
130ea7caceeSSam Clegg struct WasmComdatEntry {
131ea7caceeSSam Clegg   unsigned Kind;
132ea7caceeSSam Clegg   uint32_t Index;
133ea7caceeSSam Clegg };
134ea7caceeSSam Clegg 
1356dc65e91SSam Clegg // Information about a single relocation.
1366dc65e91SSam Clegg struct WasmRelocationEntry {
1376dc65e91SSam Clegg   uint64_t Offset;                  // Where is the relocation.
1386dc65e91SSam Clegg   const MCSymbolWasm *Symbol;       // The symbol to relocate with.
1396dc65e91SSam Clegg   int64_t Addend;                   // A value to add to the symbol.
1406dc65e91SSam Clegg   unsigned Type;                    // The type of the relocation.
141fe6414b0SSam Clegg   const MCSectionWasm *FixupSection;// The section the relocation is targeting.
1426dc65e91SSam Clegg 
1436dc65e91SSam Clegg   WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol,
1446dc65e91SSam Clegg                       int64_t Addend, unsigned Type,
145fe6414b0SSam Clegg                       const MCSectionWasm *FixupSection)
1466dc65e91SSam Clegg       : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type),
1476dc65e91SSam Clegg         FixupSection(FixupSection) {}
1486dc65e91SSam Clegg 
149acd7d2b0SSam Clegg   bool hasAddend() const {
150acd7d2b0SSam Clegg     switch (Type) {
15113a2e899SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
15213a2e899SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
15313a2e899SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
154acd7d2b0SSam Clegg       return true;
155acd7d2b0SSam Clegg     default:
156acd7d2b0SSam Clegg       return false;
157acd7d2b0SSam Clegg     }
158acd7d2b0SSam Clegg   }
159acd7d2b0SSam Clegg 
1606dc65e91SSam Clegg   void print(raw_ostream &Out) const {
1619bf73c07SSam Clegg     Out << "Off=" << Offset << ", Sym=" << *Symbol << ", Addend=" << Addend
162759631c7SSam Clegg         << ", Type=" << Type
163759631c7SSam Clegg         << ", FixupSection=" << FixupSection->getSectionName();
1646dc65e91SSam Clegg   }
165b7787fd0SSam Clegg 
166615eb470SAaron Ballman #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
167b7787fd0SSam Clegg   LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
168b7787fd0SSam Clegg #endif
1696dc65e91SSam Clegg };
1706dc65e91SSam Clegg 
171cfd44a2eSSam Clegg struct WasmCustomSection {
172cfd44a2eSSam Clegg   StringRef Name;
173cfd44a2eSSam Clegg   const SmallVectorImpl<char> &Contents;
174cfd44a2eSSam Clegg 
175cfd44a2eSSam Clegg   WasmCustomSection(StringRef Name, const SmallVectorImpl<char> &Contents)
176cfd44a2eSSam Clegg       : Name(Name), Contents(Contents) {}
177cfd44a2eSSam Clegg };
178cfd44a2eSSam Clegg 
1791fb8daa6SSam Clegg #if !defined(NDEBUG)
1807f055deeSSam Clegg raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
181b7787fd0SSam Clegg   Rel.print(OS);
182b7787fd0SSam Clegg   return OS;
183b7787fd0SSam Clegg }
1841fb8daa6SSam Clegg #endif
185b7787fd0SSam Clegg 
18618eafb6cSDan Gohman class WasmObjectWriter : public MCObjectWriter {
18718eafb6cSDan Gohman   /// The target specific Wasm writer instance.
18818eafb6cSDan Gohman   std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
18918eafb6cSDan Gohman 
190d934cb88SDan Gohman   // Relocations for fixing up references in the code section.
191d934cb88SDan Gohman   std::vector<WasmRelocationEntry> CodeRelocations;
192*6f08c84aSSam Clegg   uint32_t CodeSectionIndex;
193d934cb88SDan Gohman 
194d934cb88SDan Gohman   // Relocations for fixing up references in the data section.
195d934cb88SDan Gohman   std::vector<WasmRelocationEntry> DataRelocations;
196*6f08c84aSSam Clegg   uint32_t DataSectionIndex;
197d934cb88SDan Gohman 
198d934cb88SDan Gohman   // Index values to use for fixing up call_indirect type indices.
199acd7d2b0SSam Clegg   // Maps function symbols to the index of the type of the function
200acd7d2b0SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
201d99f6078SSam Clegg   // Maps function symbols to the table element index space. Used
202d99f6078SSam Clegg   // for TABLE_INDEX relocation types (i.e. address taken functions).
203f9edbe95SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> TableIndices;
2046c899ba6SSam Clegg   // Maps function/global symbols to the (shared) Symbol index space.
205acd7d2b0SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> SymbolIndices;
2066c899ba6SSam Clegg   // Maps function/global symbols to the function/global Wasm index space.
2076c899ba6SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> WasmIndices;
2086c899ba6SSam Clegg   // Maps data symbols to the Wasm segment and offset/size with the segment.
2096c899ba6SSam Clegg   DenseMap<const MCSymbolWasm *, wasm::WasmDataReference> DataLocations;
210acd7d2b0SSam Clegg 
211acd7d2b0SSam Clegg   DenseMap<WasmFunctionType, int32_t, WasmFunctionTypeDenseMapInfo>
212acd7d2b0SSam Clegg       FunctionTypeIndices;
2135e3d33a7SSam Clegg   SmallVector<WasmFunctionType, 4> FunctionTypes;
2147c395943SSam Clegg   SmallVector<WasmGlobal, 4> Globals;
2156c899ba6SSam Clegg   SmallVector<WasmDataSegment, 4> DataSegments;
216cfd44a2eSSam Clegg   std::vector<WasmCustomSection> CustomSections;
2179f3fe42eSSam Clegg   unsigned NumFunctionImports = 0;
2187c395943SSam Clegg   unsigned NumGlobalImports = 0;
219*6f08c84aSSam Clegg   uint32_t SectionCount;
220d934cb88SDan Gohman 
22118eafb6cSDan Gohman   // TargetObjectWriter wrappers.
22218eafb6cSDan Gohman   bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
223ae03c1e7SSam Clegg   unsigned getRelocType(const MCValue &Target, const MCFixup &Fixup) const {
224ae03c1e7SSam Clegg     return TargetObjectWriter->getRelocType(Target, Fixup);
22518eafb6cSDan Gohman   }
22618eafb6cSDan Gohman 
2272322a937SSam Clegg   void startSection(SectionBookkeeping &Section, unsigned SectionId);
2282322a937SSam Clegg   void startCustomSection(SectionBookkeeping &Section, StringRef Name);
229d934cb88SDan Gohman   void endSection(SectionBookkeeping &Section);
230d934cb88SDan Gohman 
23118eafb6cSDan Gohman public:
2321301a878SLang Hames   WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
2331301a878SLang Hames                    raw_pwrite_stream &OS)
2341301a878SLang Hames       : MCObjectWriter(OS, /*IsLittleEndian=*/true),
2351301a878SLang Hames         TargetObjectWriter(std::move(MOTW)) {}
23618eafb6cSDan Gohman 
23718eafb6cSDan Gohman   ~WasmObjectWriter() override;
23818eafb6cSDan Gohman 
2390917c9e4SDan Gohman private:
240acd7d2b0SSam Clegg   void reset() override {
241acd7d2b0SSam Clegg     CodeRelocations.clear();
242acd7d2b0SSam Clegg     DataRelocations.clear();
243acd7d2b0SSam Clegg     TypeIndices.clear();
244acd7d2b0SSam Clegg     SymbolIndices.clear();
2456c899ba6SSam Clegg     WasmIndices.clear();
246f9edbe95SSam Clegg     TableIndices.clear();
2476c899ba6SSam Clegg     DataLocations.clear();
248acd7d2b0SSam Clegg     FunctionTypeIndices.clear();
2495e3d33a7SSam Clegg     FunctionTypes.clear();
2507c395943SSam Clegg     Globals.clear();
2516c899ba6SSam Clegg     DataSegments.clear();
252acd7d2b0SSam Clegg     MCObjectWriter::reset();
2539f3fe42eSSam Clegg     NumFunctionImports = 0;
2547c395943SSam Clegg     NumGlobalImports = 0;
255acd7d2b0SSam Clegg   }
256acd7d2b0SSam Clegg 
25718eafb6cSDan Gohman   void writeHeader(const MCAssembler &Asm);
25818eafb6cSDan Gohman 
25918eafb6cSDan Gohman   void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
26018eafb6cSDan Gohman                         const MCFragment *Fragment, const MCFixup &Fixup,
261ceecfe5bSRafael Espindola                         MCValue Target, uint64_t &FixedValue) override;
26218eafb6cSDan Gohman 
26318eafb6cSDan Gohman   void executePostLayoutBinding(MCAssembler &Asm,
26418eafb6cSDan Gohman                                 const MCAsmLayout &Layout) override;
26518eafb6cSDan Gohman 
26618eafb6cSDan Gohman   void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
2679e15f359SSam Clegg 
268b7787fd0SSam Clegg   void writeString(const StringRef Str) {
269b7787fd0SSam Clegg     encodeULEB128(Str.size(), getStream());
270b7787fd0SSam Clegg     writeBytes(Str);
271b7787fd0SSam Clegg   }
272b7787fd0SSam Clegg 
2739e15f359SSam Clegg   void writeValueType(wasm::ValType Ty) {
27403e101f1SSam Clegg     write8(static_cast<uint8_t>(Ty));
2759e15f359SSam Clegg   }
2769e15f359SSam Clegg 
277457fb0b4SSam Clegg   void writeTypeSection(ArrayRef<WasmFunctionType> FunctionTypes);
2788defa952SSam Clegg   void writeImportSection(ArrayRef<wasm::WasmImport> Imports, uint32_t DataSize,
279f950b24aSSam Clegg                           uint32_t NumElements);
280457fb0b4SSam Clegg   void writeFunctionSection(ArrayRef<WasmFunction> Functions);
2817c395943SSam Clegg   void writeGlobalSection();
2828defa952SSam Clegg   void writeExportSection(ArrayRef<wasm::WasmExport> Exports);
283457fb0b4SSam Clegg   void writeElemSection(ArrayRef<uint32_t> TableElems);
2849e15f359SSam Clegg   void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
285457fb0b4SSam Clegg                         ArrayRef<WasmFunction> Functions);
2866c899ba6SSam Clegg   void writeDataSection();
287*6f08c84aSSam Clegg   void writeRelocSection(uint32_t SectionIndex, StringRef Name,
288*6f08c84aSSam Clegg                          ArrayRef<WasmRelocationEntry> Relocations);
28931a2c809SSam Clegg   void writeLinkingMetaDataSection(
29086b4a09aSSam Clegg       ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
291ea7caceeSSam Clegg       ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
292ea7caceeSSam Clegg       const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats);
293cfd44a2eSSam Clegg   void writeUserCustomSections(ArrayRef<WasmCustomSection> CustomSections);
294acd7d2b0SSam Clegg 
2957c395943SSam Clegg   uint32_t getProvisionalValue(const WasmRelocationEntry &RelEntry);
296acd7d2b0SSam Clegg   void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
297acd7d2b0SSam Clegg                         uint64_t ContentsOffset);
298acd7d2b0SSam Clegg 
299acd7d2b0SSam Clegg   uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
3005e3d33a7SSam Clegg   uint32_t getFunctionType(const MCSymbolWasm &Symbol);
3015e3d33a7SSam Clegg   uint32_t registerFunctionType(const MCSymbolWasm &Symbol);
30218eafb6cSDan Gohman };
3039e15f359SSam Clegg 
30418eafb6cSDan Gohman } // end anonymous namespace
30518eafb6cSDan Gohman 
30618eafb6cSDan Gohman WasmObjectWriter::~WasmObjectWriter() {}
30718eafb6cSDan Gohman 
308d934cb88SDan Gohman // Write out a section header and a patchable section size field.
309d934cb88SDan Gohman void WasmObjectWriter::startSection(SectionBookkeeping &Section,
3102322a937SSam Clegg                                     unsigned SectionId) {
3112322a937SSam Clegg   DEBUG(dbgs() << "startSection " << SectionId << "\n");
31203e101f1SSam Clegg   write8(SectionId);
313d934cb88SDan Gohman 
314d934cb88SDan Gohman   Section.SizeOffset = getStream().tell();
315d934cb88SDan Gohman 
316d934cb88SDan Gohman   // The section size. We don't know the size yet, so reserve enough space
317d934cb88SDan Gohman   // for any 32-bit value; we'll patch it later.
318d934cb88SDan Gohman   encodeULEB128(UINT32_MAX, getStream());
319d934cb88SDan Gohman 
320d934cb88SDan Gohman   // The position where the section starts, for measuring its size.
321d934cb88SDan Gohman   Section.ContentsOffset = getStream().tell();
322*6f08c84aSSam Clegg   Section.Index = SectionCount++;
323d934cb88SDan Gohman }
3242322a937SSam Clegg 
3252322a937SSam Clegg void WasmObjectWriter::startCustomSection(SectionBookkeeping &Section,
3262322a937SSam Clegg                                           StringRef Name) {
3272322a937SSam Clegg   DEBUG(dbgs() << "startCustomSection " << Name << "\n");
3282322a937SSam Clegg   startSection(Section, wasm::WASM_SEC_CUSTOM);
3292322a937SSam Clegg   // Custom sections in wasm also have a string identifier.
3302322a937SSam Clegg   writeString(Name);
331d934cb88SDan Gohman }
332d934cb88SDan Gohman 
333d934cb88SDan Gohman // Now that the section is complete and we know how big it is, patch up the
334d934cb88SDan Gohman // section size field at the start of the section.
335d934cb88SDan Gohman void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
336d934cb88SDan Gohman   uint64_t Size = getStream().tell() - Section.ContentsOffset;
337d934cb88SDan Gohman   if (uint32_t(Size) != Size)
338d934cb88SDan Gohman     report_fatal_error("section size does not fit in a uint32_t");
339d934cb88SDan Gohman 
340b7787fd0SSam Clegg   DEBUG(dbgs() << "endSection size=" << Size << "\n");
341d934cb88SDan Gohman 
342d934cb88SDan Gohman   // Write the final section size to the payload_len field, which follows
343d934cb88SDan Gohman   // the section id byte.
344d934cb88SDan Gohman   uint8_t Buffer[16];
34566a99e41SSam Clegg   unsigned SizeLen = encodeULEB128(Size, Buffer, 5);
346d934cb88SDan Gohman   assert(SizeLen == 5);
347d934cb88SDan Gohman   getStream().pwrite((char *)Buffer, SizeLen, Section.SizeOffset);
348d934cb88SDan Gohman }
349d934cb88SDan Gohman 
35018eafb6cSDan Gohman // Emit the Wasm header.
35118eafb6cSDan Gohman void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
3527ea5adffSDan Gohman   writeBytes(StringRef(wasm::WasmMagic, sizeof(wasm::WasmMagic)));
3537ea5adffSDan Gohman   writeLE32(wasm::WasmVersion);
35418eafb6cSDan Gohman }
35518eafb6cSDan Gohman 
35618eafb6cSDan Gohman void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
35718eafb6cSDan Gohman                                                 const MCAsmLayout &Layout) {
35818eafb6cSDan Gohman }
35918eafb6cSDan Gohman 
36018eafb6cSDan Gohman void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
36118eafb6cSDan Gohman                                         const MCAsmLayout &Layout,
36218eafb6cSDan Gohman                                         const MCFragment *Fragment,
36318eafb6cSDan Gohman                                         const MCFixup &Fixup, MCValue Target,
364ceecfe5bSRafael Espindola                                         uint64_t &FixedValue) {
365ceecfe5bSRafael Espindola   MCAsmBackend &Backend = Asm.getBackend();
366ceecfe5bSRafael Espindola   bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
367ceecfe5bSRafael Espindola                  MCFixupKindInfo::FKF_IsPCRel;
368fe6414b0SSam Clegg   const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
369d934cb88SDan Gohman   uint64_t C = Target.getConstant();
370d934cb88SDan Gohman   uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
371d934cb88SDan Gohman   MCContext &Ctx = Asm.getContext();
372d934cb88SDan Gohman 
373bafe6902SSam Clegg   // The .init_array isn't translated as data, so don't do relocations in it.
374bafe6902SSam Clegg   if (FixupSection.getSectionName().startswith(".init_array"))
375bafe6902SSam Clegg     return;
376bafe6902SSam Clegg 
377b7a5469cSSam Clegg   // TODO(sbc): Add support for debug sections.
378b7a5469cSSam Clegg   if (FixupSection.getKind().isMetadata())
379b7a5469cSSam Clegg     return;
380b7a5469cSSam Clegg 
381d934cb88SDan Gohman   if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
382d934cb88SDan Gohman     assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
383d934cb88SDan Gohman            "Should not have constructed this");
384d934cb88SDan Gohman 
385d934cb88SDan Gohman     // Let A, B and C being the components of Target and R be the location of
386d934cb88SDan Gohman     // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
387d934cb88SDan Gohman     // If it is pcrel, we want to compute (A - B + C - R).
388d934cb88SDan Gohman 
389d934cb88SDan Gohman     // In general, Wasm has no relocations for -B. It can only represent (A + C)
390d934cb88SDan Gohman     // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
391d934cb88SDan Gohman     // replace B to implement it: (A - R - K + C)
392d934cb88SDan Gohman     if (IsPCRel) {
393d934cb88SDan Gohman       Ctx.reportError(
394d934cb88SDan Gohman           Fixup.getLoc(),
395d934cb88SDan Gohman           "No relocation available to represent this relative expression");
396d934cb88SDan Gohman       return;
397d934cb88SDan Gohman     }
398d934cb88SDan Gohman 
399d934cb88SDan Gohman     const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
400d934cb88SDan Gohman 
401d934cb88SDan Gohman     if (SymB.isUndefined()) {
402d934cb88SDan Gohman       Ctx.reportError(Fixup.getLoc(),
403d934cb88SDan Gohman                       Twine("symbol '") + SymB.getName() +
404d934cb88SDan Gohman                           "' can not be undefined in a subtraction expression");
405d934cb88SDan Gohman       return;
406d934cb88SDan Gohman     }
407d934cb88SDan Gohman 
408d934cb88SDan Gohman     assert(!SymB.isAbsolute() && "Should have been folded");
409d934cb88SDan Gohman     const MCSection &SecB = SymB.getSection();
410d934cb88SDan Gohman     if (&SecB != &FixupSection) {
411d934cb88SDan Gohman       Ctx.reportError(Fixup.getLoc(),
412d934cb88SDan Gohman                       "Cannot represent a difference across sections");
413d934cb88SDan Gohman       return;
414d934cb88SDan Gohman     }
415d934cb88SDan Gohman 
416d934cb88SDan Gohman     uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
417d934cb88SDan Gohman     uint64_t K = SymBOffset - FixupOffset;
418d934cb88SDan Gohman     IsPCRel = true;
419d934cb88SDan Gohman     C -= K;
420d934cb88SDan Gohman   }
421d934cb88SDan Gohman 
422d934cb88SDan Gohman   // We either rejected the fixup or folded B into C at this point.
423d934cb88SDan Gohman   const MCSymbolRefExpr *RefA = Target.getSymA();
424d934cb88SDan Gohman   const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr;
425d934cb88SDan Gohman 
426d934cb88SDan Gohman   if (SymA && SymA->isVariable()) {
427d934cb88SDan Gohman     const MCExpr *Expr = SymA->getVariableValue();
4286ad8f190SSam Clegg     const auto *Inner = cast<MCSymbolRefExpr>(Expr);
4296ad8f190SSam Clegg     if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
4306ad8f190SSam Clegg       llvm_unreachable("weakref used in reloc not yet implemented");
431d934cb88SDan Gohman   }
432d934cb88SDan Gohman 
433d934cb88SDan Gohman   // Put any constant offset in an addend. Offsets can be negative, and
434d934cb88SDan Gohman   // LLVM expects wrapping, in contrast to wasm's immediates which can't
435d934cb88SDan Gohman   // be negative and don't wrap.
436d934cb88SDan Gohman   FixedValue = 0;
437d934cb88SDan Gohman 
4386ad8f190SSam Clegg   if (SymA)
439d934cb88SDan Gohman     SymA->setUsedInReloc();
440d934cb88SDan Gohman 
441ae03c1e7SSam Clegg   assert(!IsPCRel);
4429d24fb7fSSam Clegg   assert(SymA);
4439d24fb7fSSam Clegg 
444ae03c1e7SSam Clegg   unsigned Type = getRelocType(Target, Fixup);
445ae03c1e7SSam Clegg 
446d934cb88SDan Gohman   WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
447b7787fd0SSam Clegg   DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
448d934cb88SDan Gohman 
449b7a5469cSSam Clegg   // Relocation other than R_WEBASSEMBLY_TYPE_INDEX_LEB are currently required
450b7a5469cSSam Clegg   // to be against a named symbol.
451b7a5469cSSam Clegg   // TODO(sbc): Add support for relocations against unnamed temporaries such
452b7a5469cSSam Clegg   // as those generated by llvm's `blockaddress`.
453b7a5469cSSam Clegg   // See: test/MC/WebAssembly/blockaddress.ll
454b7a5469cSSam Clegg   if (SymA->getName().empty() && Type != wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB)
455b7a5469cSSam Clegg     report_fatal_error("relocations against un-named temporaries are not yet "
456b7a5469cSSam Clegg                        "supported by wasm");
457b7a5469cSSam Clegg 
45812fd3da9SSam Clegg   if (FixupSection.isWasmData())
459d934cb88SDan Gohman     DataRelocations.push_back(Rec);
46012fd3da9SSam Clegg   else if (FixupSection.getKind().isText())
46112fd3da9SSam Clegg     CodeRelocations.push_back(Rec);
462b7a5469cSSam Clegg   else
46312fd3da9SSam Clegg     llvm_unreachable("unexpected section type");
464d934cb88SDan Gohman }
465d934cb88SDan Gohman 
466d934cb88SDan Gohman // Write X as an (unsigned) LEB value at offset Offset in Stream, padded
467d934cb88SDan Gohman // to allow patching.
468d934cb88SDan Gohman static void
469d934cb88SDan Gohman WritePatchableLEB(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
470d934cb88SDan Gohman   uint8_t Buffer[5];
47166a99e41SSam Clegg   unsigned SizeLen = encodeULEB128(X, Buffer, 5);
472d934cb88SDan Gohman   assert(SizeLen == 5);
473d934cb88SDan Gohman   Stream.pwrite((char *)Buffer, SizeLen, Offset);
474d934cb88SDan Gohman }
475d934cb88SDan Gohman 
476d934cb88SDan Gohman // Write X as an signed LEB value at offset Offset in Stream, padded
477d934cb88SDan Gohman // to allow patching.
478d934cb88SDan Gohman static void
479d934cb88SDan Gohman WritePatchableSLEB(raw_pwrite_stream &Stream, int32_t X, uint64_t Offset) {
480d934cb88SDan Gohman   uint8_t Buffer[5];
48166a99e41SSam Clegg   unsigned SizeLen = encodeSLEB128(X, Buffer, 5);
482d934cb88SDan Gohman   assert(SizeLen == 5);
483d934cb88SDan Gohman   Stream.pwrite((char *)Buffer, SizeLen, Offset);
484d934cb88SDan Gohman }
485d934cb88SDan Gohman 
486d934cb88SDan Gohman // Write X as a plain integer value at offset Offset in Stream.
487d934cb88SDan Gohman static void WriteI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
488d934cb88SDan Gohman   uint8_t Buffer[4];
489d934cb88SDan Gohman   support::endian::write32le(Buffer, X);
490d934cb88SDan Gohman   Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
491d934cb88SDan Gohman }
492d934cb88SDan Gohman 
493aff1c4dfSSam Clegg static const MCSymbolWasm* ResolveSymbol(const MCSymbolWasm& Symbol) {
494aff1c4dfSSam Clegg   if (Symbol.isVariable()) {
495aff1c4dfSSam Clegg     const MCExpr *Expr = Symbol.getVariableValue();
496aff1c4dfSSam Clegg     auto *Inner = cast<MCSymbolRefExpr>(Expr);
497aff1c4dfSSam Clegg     return cast<MCSymbolWasm>(&Inner->getSymbol());
498aff1c4dfSSam Clegg   }
499aff1c4dfSSam Clegg   return &Symbol;
500aff1c4dfSSam Clegg }
501aff1c4dfSSam Clegg 
502d934cb88SDan Gohman // Compute a value to write into the code at the location covered
50360ec3034SSam Clegg // by RelEntry. This value isn't used by the static linker; it just serves
50460ec3034SSam Clegg // to make the object format more readable and more likely to be directly
50560ec3034SSam Clegg // useable.
5067c395943SSam Clegg uint32_t
5077c395943SSam Clegg WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) {
50860ec3034SSam Clegg   switch (RelEntry.Type) {
50960ec3034SSam Clegg   case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
510f9edbe95SSam Clegg   case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: {
511f9edbe95SSam Clegg     // Provisional value is table address of the resolved symbol itself
512f9edbe95SSam Clegg     const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
513f9edbe95SSam Clegg     assert(Sym->isFunction());
514f9edbe95SSam Clegg     return TableIndices[Sym];
515f9edbe95SSam Clegg   }
51660ec3034SSam Clegg   case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
5176c899ba6SSam Clegg     // Provisional value is same as the index
51860ec3034SSam Clegg     return getRelocationIndexValue(RelEntry);
5196c899ba6SSam Clegg   case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
5206c899ba6SSam Clegg   case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
5216c899ba6SSam Clegg     // Provisional value is function/global Wasm index
5226c899ba6SSam Clegg     if (!WasmIndices.count(RelEntry.Symbol))
5236c899ba6SSam Clegg       report_fatal_error("symbol not found in wasm index space: " +
5246c899ba6SSam Clegg                          RelEntry.Symbol->getName());
5256c899ba6SSam Clegg     return WasmIndices[RelEntry.Symbol];
52660ec3034SSam Clegg   case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
52760ec3034SSam Clegg   case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
52860ec3034SSam Clegg   case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: {
529f9edbe95SSam Clegg     // Provisional value is address of the global
53060ec3034SSam Clegg     const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
531270ed1b3SSam Clegg     // For undefined symbols, use zero
532cd65f698SSam Clegg     if (!Sym->isDefined())
533270ed1b3SSam Clegg       return 0;
5346c899ba6SSam Clegg     const wasm::WasmDataReference &Ref = DataLocations[Sym];
5356c899ba6SSam Clegg     const WasmDataSegment &Segment = DataSegments[Ref.Segment];
536d934cb88SDan Gohman     // Ignore overflow. LLVM allows address arithmetic to silently wrap.
5376c899ba6SSam Clegg     return Segment.Offset + Ref.Offset + RelEntry.Addend;
53860ec3034SSam Clegg   }
53960ec3034SSam Clegg   default:
54060ec3034SSam Clegg     llvm_unreachable("invalid relocation type");
54160ec3034SSam Clegg   }
542d934cb88SDan Gohman }
543d934cb88SDan Gohman 
544759631c7SSam Clegg static void addData(SmallVectorImpl<char> &DataBytes,
54563ebb813SSam Clegg                     MCSectionWasm &DataSection) {
546759631c7SSam Clegg   DEBUG(errs() << "addData: " << DataSection.getSectionName() << "\n");
547759631c7SSam Clegg 
54863ebb813SSam Clegg   DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
54963ebb813SSam Clegg 
550759631c7SSam Clegg   for (const MCFragment &Frag : DataSection) {
551759631c7SSam Clegg     if (Frag.hasInstructions())
552759631c7SSam Clegg       report_fatal_error("only data supported in data sections");
553759631c7SSam Clegg 
554759631c7SSam Clegg     if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
555759631c7SSam Clegg       if (Align->getValueSize() != 1)
556759631c7SSam Clegg         report_fatal_error("only byte values supported for alignment");
557759631c7SSam Clegg       // If nops are requested, use zeros, as this is the data section.
558759631c7SSam Clegg       uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
559759631c7SSam Clegg       uint64_t Size = std::min<uint64_t>(alignTo(DataBytes.size(),
560759631c7SSam Clegg                                                  Align->getAlignment()),
561759631c7SSam Clegg                                          DataBytes.size() +
562759631c7SSam Clegg                                              Align->getMaxBytesToEmit());
563759631c7SSam Clegg       DataBytes.resize(Size, Value);
564759631c7SSam Clegg     } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
565d707c370SRafael Espindola       int64_t Size;
566d707c370SRafael Espindola       if (!Fill->getSize().evaluateAsAbsolute(Size))
567d707c370SRafael Espindola         llvm_unreachable("The fill should be an assembler constant");
568d707c370SRafael Espindola       DataBytes.insert(DataBytes.end(), Size, Fill->getValue());
569759631c7SSam Clegg     } else {
570759631c7SSam Clegg       const auto &DataFrag = cast<MCDataFragment>(Frag);
571759631c7SSam Clegg       const SmallVectorImpl<char> &Contents = DataFrag.getContents();
572759631c7SSam Clegg 
573759631c7SSam Clegg       DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
574759631c7SSam Clegg     }
575759631c7SSam Clegg   }
576759631c7SSam Clegg 
577759631c7SSam Clegg   DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
578759631c7SSam Clegg }
579759631c7SSam Clegg 
58060ec3034SSam Clegg uint32_t
58160ec3034SSam Clegg WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
58260ec3034SSam Clegg   if (RelEntry.Type == wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB) {
583b7787fd0SSam Clegg     if (!TypeIndices.count(RelEntry.Symbol))
584b7787fd0SSam Clegg       report_fatal_error("symbol not found in type index space: " +
585b7787fd0SSam Clegg                          RelEntry.Symbol->getName());
586acd7d2b0SSam Clegg     return TypeIndices[RelEntry.Symbol];
587acd7d2b0SSam Clegg   }
58860ec3034SSam Clegg 
58960ec3034SSam Clegg   if (!SymbolIndices.count(RelEntry.Symbol))
5906c899ba6SSam Clegg     report_fatal_error("symbol not found in symbol index space: " +
59160ec3034SSam Clegg                        RelEntry.Symbol->getName());
59260ec3034SSam Clegg   return SymbolIndices[RelEntry.Symbol];
593acd7d2b0SSam Clegg }
594acd7d2b0SSam Clegg 
595d934cb88SDan Gohman // Apply the portions of the relocation records that we can handle ourselves
596d934cb88SDan Gohman // directly.
597acd7d2b0SSam Clegg void WasmObjectWriter::applyRelocations(
598acd7d2b0SSam Clegg     ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
599acd7d2b0SSam Clegg   raw_pwrite_stream &Stream = getStream();
600d934cb88SDan Gohman   for (const WasmRelocationEntry &RelEntry : Relocations) {
601d934cb88SDan Gohman     uint64_t Offset = ContentsOffset +
602d934cb88SDan Gohman                       RelEntry.FixupSection->getSectionOffset() +
603d934cb88SDan Gohman                       RelEntry.Offset;
604d934cb88SDan Gohman 
605b7787fd0SSam Clegg     DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
60660ec3034SSam Clegg     uint32_t Value = getProvisionalValue(RelEntry);
60760ec3034SSam Clegg 
608acd7d2b0SSam Clegg     switch (RelEntry.Type) {
609acd7d2b0SSam Clegg     case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
6109d24fb7fSSam Clegg     case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
61160ec3034SSam Clegg     case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
61260ec3034SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
613d934cb88SDan Gohman       WritePatchableLEB(Stream, Value, Offset);
614d934cb88SDan Gohman       break;
61560ec3034SSam Clegg     case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
61660ec3034SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
617d934cb88SDan Gohman       WriteI32(Stream, Value, Offset);
618d934cb88SDan Gohman       break;
61960ec3034SSam Clegg     case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
62060ec3034SSam Clegg     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
62160ec3034SSam Clegg       WritePatchableSLEB(Stream, Value, Offset);
62260ec3034SSam Clegg       break;
623d934cb88SDan Gohman     default:
6249d24fb7fSSam Clegg       llvm_unreachable("invalid relocation type");
625d934cb88SDan Gohman     }
626d934cb88SDan Gohman   }
62718eafb6cSDan Gohman }
62818eafb6cSDan Gohman 
6299e15f359SSam Clegg void WasmObjectWriter::writeTypeSection(
630457fb0b4SSam Clegg     ArrayRef<WasmFunctionType> FunctionTypes) {
6319e15f359SSam Clegg   if (FunctionTypes.empty())
6329e15f359SSam Clegg     return;
6339e15f359SSam Clegg 
6349e15f359SSam Clegg   SectionBookkeeping Section;
6359e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_TYPE);
6369e15f359SSam Clegg 
6379e15f359SSam Clegg   encodeULEB128(FunctionTypes.size(), getStream());
6389e15f359SSam Clegg 
6399e15f359SSam Clegg   for (const WasmFunctionType &FuncTy : FunctionTypes) {
64003e101f1SSam Clegg     write8(wasm::WASM_TYPE_FUNC);
6419e15f359SSam Clegg     encodeULEB128(FuncTy.Params.size(), getStream());
6429e15f359SSam Clegg     for (wasm::ValType Ty : FuncTy.Params)
6439e15f359SSam Clegg       writeValueType(Ty);
6449e15f359SSam Clegg     encodeULEB128(FuncTy.Returns.size(), getStream());
6459e15f359SSam Clegg     for (wasm::ValType Ty : FuncTy.Returns)
6469e15f359SSam Clegg       writeValueType(Ty);
6479e15f359SSam Clegg   }
6489e15f359SSam Clegg 
6499e15f359SSam Clegg   endSection(Section);
6509e15f359SSam Clegg }
6519e15f359SSam Clegg 
6528defa952SSam Clegg void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports,
653f950b24aSSam Clegg                                           uint32_t DataSize,
654f950b24aSSam Clegg                                           uint32_t NumElements) {
6559e15f359SSam Clegg   if (Imports.empty())
6569e15f359SSam Clegg     return;
6579e15f359SSam Clegg 
658f950b24aSSam Clegg   uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
659f950b24aSSam Clegg 
6609e15f359SSam Clegg   SectionBookkeeping Section;
6619e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_IMPORT);
6629e15f359SSam Clegg 
6639e15f359SSam Clegg   encodeULEB128(Imports.size(), getStream());
6648defa952SSam Clegg   for (const wasm::WasmImport &Import : Imports) {
6658defa952SSam Clegg     writeString(Import.Module);
6668defa952SSam Clegg     writeString(Import.Field);
66703e101f1SSam Clegg     write8(Import.Kind);
6689e15f359SSam Clegg 
6699e15f359SSam Clegg     switch (Import.Kind) {
6709e15f359SSam Clegg     case wasm::WASM_EXTERNAL_FUNCTION:
6718defa952SSam Clegg       encodeULEB128(Import.SigIndex, getStream());
6729e15f359SSam Clegg       break;
6739e15f359SSam Clegg     case wasm::WASM_EXTERNAL_GLOBAL:
67403e101f1SSam Clegg       write8(Import.Global.Type);
67503e101f1SSam Clegg       write8(Import.Global.Mutable ? 1 : 0);
6769e15f359SSam Clegg       break;
677f950b24aSSam Clegg     case wasm::WASM_EXTERNAL_MEMORY:
678f950b24aSSam Clegg       encodeULEB128(0, getStream()); // flags
679f950b24aSSam Clegg       encodeULEB128(NumPages, getStream()); // initial
680f950b24aSSam Clegg       break;
681f950b24aSSam Clegg     case wasm::WASM_EXTERNAL_TABLE:
68203e101f1SSam Clegg       write8(Import.Table.ElemType);
683f950b24aSSam Clegg       encodeULEB128(0, getStream()); // flags
684f950b24aSSam Clegg       encodeULEB128(NumElements, getStream()); // initial
685f950b24aSSam Clegg       break;
6869e15f359SSam Clegg     default:
6879e15f359SSam Clegg       llvm_unreachable("unsupported import kind");
6889e15f359SSam Clegg     }
6899e15f359SSam Clegg   }
6909e15f359SSam Clegg 
6919e15f359SSam Clegg   endSection(Section);
6929e15f359SSam Clegg }
6939e15f359SSam Clegg 
694457fb0b4SSam Clegg void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
6959e15f359SSam Clegg   if (Functions.empty())
6969e15f359SSam Clegg     return;
6979e15f359SSam Clegg 
6989e15f359SSam Clegg   SectionBookkeeping Section;
6999e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_FUNCTION);
7009e15f359SSam Clegg 
7019e15f359SSam Clegg   encodeULEB128(Functions.size(), getStream());
7029e15f359SSam Clegg   for (const WasmFunction &Func : Functions)
7039e15f359SSam Clegg     encodeULEB128(Func.Type, getStream());
7049e15f359SSam Clegg 
7059e15f359SSam Clegg   endSection(Section);
7069e15f359SSam Clegg }
7079e15f359SSam Clegg 
7087c395943SSam Clegg void WasmObjectWriter::writeGlobalSection() {
7099e15f359SSam Clegg   if (Globals.empty())
7109e15f359SSam Clegg     return;
7119e15f359SSam Clegg 
7129e15f359SSam Clegg   SectionBookkeeping Section;
7139e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_GLOBAL);
7149e15f359SSam Clegg 
7159e15f359SSam Clegg   encodeULEB128(Globals.size(), getStream());
7169e15f359SSam Clegg   for (const WasmGlobal &Global : Globals) {
7176e7f1826SSam Clegg     writeValueType(static_cast<wasm::ValType>(Global.Type.Type));
7186e7f1826SSam Clegg     write8(Global.Type.Mutable);
7199e15f359SSam Clegg 
7209e15f359SSam Clegg     write8(wasm::WASM_OPCODE_I32_CONST);
7216e7f1826SSam Clegg     encodeSLEB128(Global.InitialValue, getStream());
7229e15f359SSam Clegg     write8(wasm::WASM_OPCODE_END);
7239e15f359SSam Clegg   }
7249e15f359SSam Clegg 
7259e15f359SSam Clegg   endSection(Section);
7269e15f359SSam Clegg }
7279e15f359SSam Clegg 
7288defa952SSam Clegg void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) {
7299e15f359SSam Clegg   if (Exports.empty())
7309e15f359SSam Clegg     return;
7319e15f359SSam Clegg 
7329e15f359SSam Clegg   SectionBookkeeping Section;
7339e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_EXPORT);
7349e15f359SSam Clegg 
7359e15f359SSam Clegg   encodeULEB128(Exports.size(), getStream());
7368defa952SSam Clegg   for (const wasm::WasmExport &Export : Exports) {
7378defa952SSam Clegg     writeString(Export.Name);
73803e101f1SSam Clegg     write8(Export.Kind);
7399e15f359SSam Clegg     encodeULEB128(Export.Index, getStream());
7409e15f359SSam Clegg   }
7419e15f359SSam Clegg 
7429e15f359SSam Clegg   endSection(Section);
7439e15f359SSam Clegg }
7449e15f359SSam Clegg 
745457fb0b4SSam Clegg void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
7469e15f359SSam Clegg   if (TableElems.empty())
7479e15f359SSam Clegg     return;
7489e15f359SSam Clegg 
7499e15f359SSam Clegg   SectionBookkeeping Section;
7509e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_ELEM);
7519e15f359SSam Clegg 
7529e15f359SSam Clegg   encodeULEB128(1, getStream()); // number of "segments"
7539e15f359SSam Clegg   encodeULEB128(0, getStream()); // the table index
7549e15f359SSam Clegg 
7559e15f359SSam Clegg   // init expr for starting offset
7569e15f359SSam Clegg   write8(wasm::WASM_OPCODE_I32_CONST);
75730e1bbc1SSam Clegg   encodeSLEB128(kInitialTableOffset, getStream());
7589e15f359SSam Clegg   write8(wasm::WASM_OPCODE_END);
7599e15f359SSam Clegg 
7609e15f359SSam Clegg   encodeULEB128(TableElems.size(), getStream());
7619e15f359SSam Clegg   for (uint32_t Elem : TableElems)
7629e15f359SSam Clegg     encodeULEB128(Elem, getStream());
7639e15f359SSam Clegg 
7649e15f359SSam Clegg   endSection(Section);
7659e15f359SSam Clegg }
7669e15f359SSam Clegg 
767457fb0b4SSam Clegg void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
768457fb0b4SSam Clegg                                         const MCAsmLayout &Layout,
769457fb0b4SSam Clegg                                         ArrayRef<WasmFunction> Functions) {
7709e15f359SSam Clegg   if (Functions.empty())
7719e15f359SSam Clegg     return;
7729e15f359SSam Clegg 
7739e15f359SSam Clegg   SectionBookkeeping Section;
7749e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_CODE);
775*6f08c84aSSam Clegg   CodeSectionIndex = Section.Index;
7769e15f359SSam Clegg 
7779e15f359SSam Clegg   encodeULEB128(Functions.size(), getStream());
7789e15f359SSam Clegg 
7799e15f359SSam Clegg   for (const WasmFunction &Func : Functions) {
780fe6414b0SSam Clegg     auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
7819e15f359SSam Clegg 
7829e15f359SSam Clegg     int64_t Size = 0;
7839e15f359SSam Clegg     if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
7849e15f359SSam Clegg       report_fatal_error(".size expression must be evaluatable");
7859e15f359SSam Clegg 
7869e15f359SSam Clegg     encodeULEB128(Size, getStream());
787fe6414b0SSam Clegg     FuncSection.setSectionOffset(getStream().tell() - Section.ContentsOffset);
7889e15f359SSam Clegg     Asm.writeSectionData(&FuncSection, Layout);
7899e15f359SSam Clegg   }
7909e15f359SSam Clegg 
7919e15f359SSam Clegg   // Apply fixups.
792acd7d2b0SSam Clegg   applyRelocations(CodeRelocations, Section.ContentsOffset);
7939e15f359SSam Clegg 
7949e15f359SSam Clegg   endSection(Section);
7959e15f359SSam Clegg }
7969e15f359SSam Clegg 
7976c899ba6SSam Clegg void WasmObjectWriter::writeDataSection() {
7986c899ba6SSam Clegg   if (DataSegments.empty())
7997c395943SSam Clegg     return;
8009e15f359SSam Clegg 
8019e15f359SSam Clegg   SectionBookkeeping Section;
8029e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_DATA);
803*6f08c84aSSam Clegg   DataSectionIndex = Section.Index;
8049e15f359SSam Clegg 
8056c899ba6SSam Clegg   encodeULEB128(DataSegments.size(), getStream()); // count
8067c395943SSam Clegg 
8076c899ba6SSam Clegg   for (const WasmDataSegment &Segment : DataSegments) {
8089e15f359SSam Clegg     encodeULEB128(0, getStream()); // memory index
8099e15f359SSam Clegg     write8(wasm::WASM_OPCODE_I32_CONST);
8107c395943SSam Clegg     encodeSLEB128(Segment.Offset, getStream()); // offset
8119e15f359SSam Clegg     write8(wasm::WASM_OPCODE_END);
8127c395943SSam Clegg     encodeULEB128(Segment.Data.size(), getStream()); // size
8137c395943SSam Clegg     Segment.Section->setSectionOffset(getStream().tell() - Section.ContentsOffset);
8147c395943SSam Clegg     writeBytes(Segment.Data); // data
8157c395943SSam Clegg   }
8169e15f359SSam Clegg 
8179e15f359SSam Clegg   // Apply fixups.
8187c395943SSam Clegg   applyRelocations(DataRelocations, Section.ContentsOffset);
8199e15f359SSam Clegg 
8209e15f359SSam Clegg   endSection(Section);
8219e15f359SSam Clegg }
8229e15f359SSam Clegg 
823*6f08c84aSSam Clegg void WasmObjectWriter::writeRelocSection(
824*6f08c84aSSam Clegg     uint32_t SectionIndex, StringRef Name,
825*6f08c84aSSam Clegg     ArrayRef<WasmRelocationEntry> Relocations) {
8269e15f359SSam Clegg   // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
8279e15f359SSam Clegg   // for descriptions of the reloc sections.
8289e15f359SSam Clegg 
829*6f08c84aSSam Clegg   if (Relocations.empty())
8309e15f359SSam Clegg     return;
8319e15f359SSam Clegg 
8329e15f359SSam Clegg   SectionBookkeeping Section;
833*6f08c84aSSam Clegg   startCustomSection(Section, std::string("reloc.") + Name.str());
8349e15f359SSam Clegg 
835*6f08c84aSSam Clegg   raw_pwrite_stream &Stream = getStream();
8369e15f359SSam Clegg 
837*6f08c84aSSam Clegg   encodeULEB128(SectionIndex, Stream);
838*6f08c84aSSam Clegg   encodeULEB128(Relocations.size(), Stream);
839*6f08c84aSSam Clegg   for (const WasmRelocationEntry& RelEntry : Relocations) {
840*6f08c84aSSam Clegg     uint64_t Offset = RelEntry.Offset +
841*6f08c84aSSam Clegg                       RelEntry.FixupSection->getSectionOffset();
842*6f08c84aSSam Clegg     uint32_t Index = getRelocationIndexValue(RelEntry);
8439e15f359SSam Clegg 
844*6f08c84aSSam Clegg     write8(RelEntry.Type);
845*6f08c84aSSam Clegg     encodeULEB128(Offset, Stream);
846*6f08c84aSSam Clegg     encodeULEB128(Index, Stream);
847*6f08c84aSSam Clegg     if (RelEntry.hasAddend())
848*6f08c84aSSam Clegg       encodeSLEB128(RelEntry.Addend, Stream);
8499e15f359SSam Clegg   }
8509e15f359SSam Clegg 
8519e15f359SSam Clegg   endSection(Section);
8529e15f359SSam Clegg }
8539e15f359SSam Clegg 
8549e15f359SSam Clegg void WasmObjectWriter::writeLinkingMetaDataSection(
85586b4a09aSSam Clegg     ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
856ea7caceeSSam Clegg     ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
857ea7caceeSSam Clegg     const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) {
8589e15f359SSam Clegg   SectionBookkeeping Section;
8592322a937SSam Clegg   startCustomSection(Section, "linking");
860b7787fd0SSam Clegg   SectionBookkeeping SubSection;
8619e15f359SSam Clegg 
8626c899ba6SSam Clegg   if (SymbolInfos.size() != 0) {
8636c899ba6SSam Clegg     startSection(SubSection, wasm::WASM_SYMBOL_TABLE);
8646c899ba6SSam Clegg     encodeULEB128(SymbolInfos.size(), getStream());
8656c899ba6SSam Clegg     for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) {
8666c899ba6SSam Clegg       encodeULEB128(Sym.Kind, getStream());
8676c899ba6SSam Clegg       encodeULEB128(Sym.Flags, getStream());
8686c899ba6SSam Clegg       switch (Sym.Kind) {
8696c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_FUNCTION:
8706c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_GLOBAL:
8716c899ba6SSam Clegg         encodeULEB128(Sym.ElementIndex, getStream());
8726c899ba6SSam Clegg         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0)
8736c899ba6SSam Clegg           writeString(Sym.Name);
8746c899ba6SSam Clegg         break;
8756c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_DATA:
8766c899ba6SSam Clegg         writeString(Sym.Name);
8776c899ba6SSam Clegg         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) {
8786c899ba6SSam Clegg           encodeULEB128(Sym.DataRef.Segment, getStream());
8796c899ba6SSam Clegg           encodeULEB128(Sym.DataRef.Offset, getStream());
8806c899ba6SSam Clegg           encodeULEB128(Sym.DataRef.Size, getStream());
8816c899ba6SSam Clegg         }
8826c899ba6SSam Clegg         break;
8836c899ba6SSam Clegg       default:
8846c899ba6SSam Clegg         llvm_unreachable("unexpected kind");
8856c899ba6SSam Clegg       }
886b7787fd0SSam Clegg     }
887b7787fd0SSam Clegg     endSection(SubSection);
888b7787fd0SSam Clegg   }
8899e15f359SSam Clegg 
8906c899ba6SSam Clegg   if (DataSegments.size()) {
89163ebb813SSam Clegg     startSection(SubSection, wasm::WASM_SEGMENT_INFO);
8926c899ba6SSam Clegg     encodeULEB128(DataSegments.size(), getStream());
8936c899ba6SSam Clegg     for (const WasmDataSegment &Segment : DataSegments) {
894d95ed959SSam Clegg       writeString(Segment.Name);
89563ebb813SSam Clegg       encodeULEB128(Segment.Alignment, getStream());
89663ebb813SSam Clegg       encodeULEB128(Segment.Flags, getStream());
89763ebb813SSam Clegg     }
898d95ed959SSam Clegg     endSection(SubSection);
899d95ed959SSam Clegg   }
900d95ed959SSam Clegg 
901bafe6902SSam Clegg   if (!InitFuncs.empty()) {
902bafe6902SSam Clegg     startSection(SubSection, wasm::WASM_INIT_FUNCS);
903bafe6902SSam Clegg     encodeULEB128(InitFuncs.size(), getStream());
904bafe6902SSam Clegg     for (auto &StartFunc : InitFuncs) {
905bafe6902SSam Clegg       encodeULEB128(StartFunc.first, getStream()); // priority
906bafe6902SSam Clegg       encodeULEB128(StartFunc.second, getStream()); // function index
907bafe6902SSam Clegg     }
908bafe6902SSam Clegg     endSection(SubSection);
909bafe6902SSam Clegg   }
910bafe6902SSam Clegg 
911ea7caceeSSam Clegg   if (Comdats.size()) {
912ea7caceeSSam Clegg     startSection(SubSection, wasm::WASM_COMDAT_INFO);
913ea7caceeSSam Clegg     encodeULEB128(Comdats.size(), getStream());
914ea7caceeSSam Clegg     for (const auto &C : Comdats) {
915ea7caceeSSam Clegg       writeString(C.first);
916ea7caceeSSam Clegg       encodeULEB128(0, getStream()); // flags for future use
917ea7caceeSSam Clegg       encodeULEB128(C.second.size(), getStream());
918ea7caceeSSam Clegg       for (const WasmComdatEntry &Entry : C.second) {
919ea7caceeSSam Clegg         encodeULEB128(Entry.Kind, getStream());
920ea7caceeSSam Clegg         encodeULEB128(Entry.Index, getStream());
921ea7caceeSSam Clegg       }
922ea7caceeSSam Clegg     }
923ea7caceeSSam Clegg     endSection(SubSection);
924ea7caceeSSam Clegg   }
925ea7caceeSSam Clegg 
9269e15f359SSam Clegg   endSection(Section);
9279e15f359SSam Clegg }
9289e15f359SSam Clegg 
929cfd44a2eSSam Clegg void WasmObjectWriter::writeUserCustomSections(
930cfd44a2eSSam Clegg     ArrayRef<WasmCustomSection> CustomSections) {
931cfd44a2eSSam Clegg   for (const auto &CustomSection : CustomSections) {
932cfd44a2eSSam Clegg     SectionBookkeeping Section;
9332322a937SSam Clegg     startCustomSection(Section, CustomSection.Name);
934cfd44a2eSSam Clegg     writeBytes(CustomSection.Contents);
935cfd44a2eSSam Clegg     endSection(Section);
936cfd44a2eSSam Clegg   }
937cfd44a2eSSam Clegg }
938cfd44a2eSSam Clegg 
9395e3d33a7SSam Clegg uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm& Symbol) {
9405e3d33a7SSam Clegg   assert(Symbol.isFunction());
9415e3d33a7SSam Clegg   assert(TypeIndices.count(&Symbol));
9425e3d33a7SSam Clegg   return TypeIndices[&Symbol];
9435e3d33a7SSam Clegg }
9445e3d33a7SSam Clegg 
9455e3d33a7SSam Clegg uint32_t WasmObjectWriter::registerFunctionType(const MCSymbolWasm& Symbol) {
9465e3d33a7SSam Clegg   assert(Symbol.isFunction());
9475e3d33a7SSam Clegg 
9485e3d33a7SSam Clegg   WasmFunctionType F;
949aff1c4dfSSam Clegg   const MCSymbolWasm* ResolvedSym = ResolveSymbol(Symbol);
9505e3d33a7SSam Clegg   F.Returns = ResolvedSym->getReturns();
9515e3d33a7SSam Clegg   F.Params = ResolvedSym->getParams();
9525e3d33a7SSam Clegg 
9535e3d33a7SSam Clegg   auto Pair =
9545e3d33a7SSam Clegg       FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size()));
9555e3d33a7SSam Clegg   if (Pair.second)
9565e3d33a7SSam Clegg     FunctionTypes.push_back(F);
9575e3d33a7SSam Clegg   TypeIndices[&Symbol] = Pair.first->second;
9585e3d33a7SSam Clegg 
9595e3d33a7SSam Clegg   DEBUG(dbgs() << "registerFunctionType: " << Symbol << " new:" << Pair.second << "\n");
9605e3d33a7SSam Clegg   DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
9615e3d33a7SSam Clegg   return Pair.first->second;
9625e3d33a7SSam Clegg }
9635e3d33a7SSam Clegg 
96418eafb6cSDan Gohman void WasmObjectWriter::writeObject(MCAssembler &Asm,
96518eafb6cSDan Gohman                                    const MCAsmLayout &Layout) {
966b7787fd0SSam Clegg   DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
96782607f56SDan Gohman   MCContext &Ctx = Asm.getContext();
968d934cb88SDan Gohman 
969d934cb88SDan Gohman   // Collect information from the available symbols.
970d934cb88SDan Gohman   SmallVector<WasmFunction, 4> Functions;
971d934cb88SDan Gohman   SmallVector<uint32_t, 4> TableElems;
9728defa952SSam Clegg   SmallVector<wasm::WasmImport, 4> Imports;
9738defa952SSam Clegg   SmallVector<wasm::WasmExport, 4> Exports;
9746c899ba6SSam Clegg   SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos;
975bafe6902SSam Clegg   SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
976ea7caceeSSam Clegg   std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
9777c395943SSam Clegg   uint32_t DataSize = 0;
978d934cb88SDan Gohman 
979f950b24aSSam Clegg   // For now, always emit the memory import, since loads and stores are not
980f950b24aSSam Clegg   // valid without it. In the future, we could perhaps be more clever and omit
981f950b24aSSam Clegg   // it if there are no loads or stores.
982f950b24aSSam Clegg   MCSymbolWasm *MemorySym =
983f950b24aSSam Clegg       cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__linear_memory"));
9848defa952SSam Clegg   wasm::WasmImport MemImport;
9858defa952SSam Clegg   MemImport.Module = MemorySym->getModuleName();
9868defa952SSam Clegg   MemImport.Field = MemorySym->getName();
987f950b24aSSam Clegg   MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
988f950b24aSSam Clegg   Imports.push_back(MemImport);
989f950b24aSSam Clegg 
990f950b24aSSam Clegg   // For now, always emit the table section, since indirect calls are not
991f950b24aSSam Clegg   // valid without it. In the future, we could perhaps be more clever and omit
992f950b24aSSam Clegg   // it if there are no indirect calls.
993f950b24aSSam Clegg   MCSymbolWasm *TableSym =
994f950b24aSSam Clegg       cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__indirect_function_table"));
9958defa952SSam Clegg   wasm::WasmImport TableImport;
9968defa952SSam Clegg   TableImport.Module = TableSym->getModuleName();
9978defa952SSam Clegg   TableImport.Field = TableSym->getName();
998f950b24aSSam Clegg   TableImport.Kind = wasm::WASM_EXTERNAL_TABLE;
9998defa952SSam Clegg   TableImport.Table.ElemType = wasm::WASM_TYPE_ANYFUNC;
1000f950b24aSSam Clegg   Imports.push_back(TableImport);
1001f950b24aSSam Clegg 
1002586320c0SNicholas Wilson   // Populate FunctionTypeIndices, and Imports and WasmIndices for undefined
1003586320c0SNicholas Wilson   // symbols.  This must be done before populating WasmIndices for defined
1004586320c0SNicholas Wilson   // symbols.
100532ce5ca0SDan Gohman   for (const MCSymbol &S : Asm.symbols()) {
100632ce5ca0SDan Gohman     const auto &WS = static_cast<const MCSymbolWasm &>(S);
100732ce5ca0SDan Gohman 
100832ce5ca0SDan Gohman     // Register types for all functions, including those with private linkage
10099f3fe42eSSam Clegg     // (because wasm always needs a type signature).
101032ce5ca0SDan Gohman     if (WS.isFunction())
101132ce5ca0SDan Gohman       registerFunctionType(WS);
101232ce5ca0SDan Gohman 
101332ce5ca0SDan Gohman     if (WS.isTemporary())
101432ce5ca0SDan Gohman       continue;
101532ce5ca0SDan Gohman 
101632ce5ca0SDan Gohman     // If the symbol is not defined in this translation unit, import it.
10176c899ba6SSam Clegg     if (!WS.isDefined() && !WS.isComdat()) {
10186c899ba6SSam Clegg       if (WS.isFunction()) {
10198defa952SSam Clegg         wasm::WasmImport Import;
10208defa952SSam Clegg         Import.Module = WS.getModuleName();
10218defa952SSam Clegg         Import.Field = WS.getName();
102232ce5ca0SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
10238defa952SSam Clegg         Import.SigIndex = getFunctionType(WS);
10246c899ba6SSam Clegg         Imports.push_back(Import);
10256c899ba6SSam Clegg         WasmIndices[&WS] = NumFunctionImports++;
10266c899ba6SSam Clegg       } else if (WS.isGlobal()) {
102715f349f7SNicholas Wilson         if (WS.isWeak())
102815f349f7SNicholas Wilson           report_fatal_error("undefined global symbol cannot be weak");
102915f349f7SNicholas Wilson 
10306c899ba6SSam Clegg         wasm::WasmImport Import;
10316c899ba6SSam Clegg         Import.Module = WS.getModuleName();
10326c899ba6SSam Clegg         Import.Field = WS.getName();
103332ce5ca0SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
10346c899ba6SSam Clegg         Import.Global = WS.getGlobalType();
10356c899ba6SSam Clegg         Imports.push_back(Import);
10366c899ba6SSam Clegg         WasmIndices[&WS] = NumGlobalImports++;
103732ce5ca0SDan Gohman       }
103832ce5ca0SDan Gohman     }
103932ce5ca0SDan Gohman   }
104032ce5ca0SDan Gohman 
1041586320c0SNicholas Wilson   // Populate DataSegments, which must be done before populating DataLocations.
1042759631c7SSam Clegg   for (MCSection &Sec : Asm) {
1043759631c7SSam Clegg     auto &Section = static_cast<MCSectionWasm &>(Sec);
1044cfd44a2eSSam Clegg 
1045cfd44a2eSSam Clegg     if (cast<MCSectionWasm>(Sec).getSectionName().startswith(
1046cfd44a2eSSam Clegg             ".custom_section.")) {
1047cfd44a2eSSam Clegg       if (Section.getFragmentList().empty())
1048cfd44a2eSSam Clegg         continue;
1049cfd44a2eSSam Clegg       if (Section.getFragmentList().size() != 1)
1050cfd44a2eSSam Clegg         report_fatal_error(
1051cfd44a2eSSam Clegg             "only one .custom_section section fragment supported");
1052cfd44a2eSSam Clegg       const MCFragment &Frag = *Section.begin();
1053cfd44a2eSSam Clegg       if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1054cfd44a2eSSam Clegg         report_fatal_error("only data supported in .custom_section section");
1055cfd44a2eSSam Clegg       const auto &DataFrag = cast<MCDataFragment>(Frag);
1056cfd44a2eSSam Clegg       if (!DataFrag.getFixups().empty())
1057cfd44a2eSSam Clegg         report_fatal_error("fixups not supported in .custom_section section");
1058cfd44a2eSSam Clegg       StringRef UserName = Section.getSectionName().substr(16);
1059cfd44a2eSSam Clegg       const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1060cfd44a2eSSam Clegg       CustomSections.push_back(WasmCustomSection(UserName, Contents));
1061cfd44a2eSSam Clegg       continue;
1062cfd44a2eSSam Clegg     }
1063cfd44a2eSSam Clegg 
106412fd3da9SSam Clegg     if (!Section.isWasmData())
1065759631c7SSam Clegg       continue;
1066759631c7SSam Clegg 
1067bafe6902SSam Clegg     // .init_array sections are handled specially elsewhere.
1068bafe6902SSam Clegg     if (cast<MCSectionWasm>(Sec).getSectionName().startswith(".init_array"))
1069bafe6902SSam Clegg       continue;
1070bafe6902SSam Clegg 
1071329e76d5SSam Clegg     uint32_t SegmentIndex = DataSegments.size();
1072759631c7SSam Clegg     DataSize = alignTo(DataSize, Section.getAlignment());
1073759631c7SSam Clegg     DataSegments.emplace_back();
1074759631c7SSam Clegg     WasmDataSegment &Segment = DataSegments.back();
1075d95ed959SSam Clegg     Segment.Name = Section.getSectionName();
1076759631c7SSam Clegg     Segment.Offset = DataSize;
1077759631c7SSam Clegg     Segment.Section = &Section;
107863ebb813SSam Clegg     addData(Segment.Data, Section);
107963ebb813SSam Clegg     Segment.Alignment = Section.getAlignment();
108063ebb813SSam Clegg     Segment.Flags = 0;
1081759631c7SSam Clegg     DataSize += Segment.Data.size();
10826c899ba6SSam Clegg     Section.setSegmentIndex(SegmentIndex);
1083ea7caceeSSam Clegg 
1084ea7caceeSSam Clegg     if (const MCSymbolWasm *C = Section.getGroup()) {
1085ea7caceeSSam Clegg       Comdats[C->getName()].emplace_back(
1086329e76d5SSam Clegg           WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
1087ea7caceeSSam Clegg     }
1088759631c7SSam Clegg   }
1089759631c7SSam Clegg 
1090586320c0SNicholas Wilson   // Populate WasmIndices and DataLocations for defined symbols.
1091d934cb88SDan Gohman   for (const MCSymbol &S : Asm.symbols()) {
1092d934cb88SDan Gohman     // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1093d934cb88SDan Gohman     // or used in relocations.
1094d934cb88SDan Gohman     if (S.isTemporary() && S.getName().empty())
1095d934cb88SDan Gohman       continue;
1096b7787fd0SSam Clegg 
1097d934cb88SDan Gohman     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1098b7787fd0SSam Clegg     DEBUG(dbgs() << "MCSymbol: '" << S << "'"
1099329e76d5SSam Clegg                  << " isDefined=" << S.isDefined()
1100329e76d5SSam Clegg                  << " isExternal=" << S.isExternal()
1101329e76d5SSam Clegg                  << " isTemporary=" << S.isTemporary()
1102b7787fd0SSam Clegg                  << " isFunction=" << WS.isFunction()
1103b7787fd0SSam Clegg                  << " isWeak=" << WS.isWeak()
1104a2b35dacSSam Clegg                  << " isHidden=" << WS.isHidden()
1105b7787fd0SSam Clegg                  << " isVariable=" << WS.isVariable() << "\n");
1106b7787fd0SSam Clegg 
11075e3d33a7SSam Clegg     if (WS.isVariable())
11085e3d33a7SSam Clegg       continue;
11096c899ba6SSam Clegg     if (WS.isComdat() && !WS.isDefined())
11106c899ba6SSam Clegg       continue;
1111b7787fd0SSam Clegg 
1112d934cb88SDan Gohman     if (WS.isFunction()) {
11136c899ba6SSam Clegg       unsigned Index;
1114cd65f698SSam Clegg       if (WS.isDefined()) {
1115b7787fd0SSam Clegg         if (WS.getOffset() != 0)
1116b7787fd0SSam Clegg           report_fatal_error(
1117b7787fd0SSam Clegg               "function sections must contain one function each");
1118b7787fd0SSam Clegg 
1119b7787fd0SSam Clegg         if (WS.getSize() == 0)
1120b7787fd0SSam Clegg           report_fatal_error(
1121b7787fd0SSam Clegg               "function symbols must have a size set with .size");
1122b7787fd0SSam Clegg 
11236c899ba6SSam Clegg         // A definition. Write out the function body.
11249f3fe42eSSam Clegg         Index = NumFunctionImports + Functions.size();
1125d934cb88SDan Gohman         WasmFunction Func;
11265e3d33a7SSam Clegg         Func.Type = getFunctionType(WS);
1127d934cb88SDan Gohman         Func.Sym = &WS;
11286c899ba6SSam Clegg         WasmIndices[&WS] = Index;
1129d934cb88SDan Gohman         Functions.push_back(Func);
11306c899ba6SSam Clegg 
11316c899ba6SSam Clegg         auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
11326c899ba6SSam Clegg         if (const MCSymbolWasm *C = Section.getGroup()) {
11336c899ba6SSam Clegg           Comdats[C->getName()].emplace_back(
11346c899ba6SSam Clegg               WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
11356c899ba6SSam Clegg         }
1136d934cb88SDan Gohman       } else {
1137d934cb88SDan Gohman         // An import; the index was assigned above.
11386c899ba6SSam Clegg         Index = WasmIndices.find(&WS)->second;
1139d934cb88SDan Gohman       }
1140d934cb88SDan Gohman 
11415e3d33a7SSam Clegg       DEBUG(dbgs() << "  -> function index: " << Index << "\n");
11426c899ba6SSam Clegg     } else if (WS.isData()) {
1143c38e947eSSam Clegg       if (WS.isTemporary() && !WS.getSize())
1144c38e947eSSam Clegg         continue;
1145c38e947eSSam Clegg 
11466c899ba6SSam Clegg       if (!WS.isDefined()) {
11476c899ba6SSam Clegg         DEBUG(dbgs() << "  -> segment index: -1");
1148fe6414b0SSam Clegg         continue;
11496c899ba6SSam Clegg       }
1150fe6414b0SSam Clegg 
1151d934cb88SDan Gohman       if (!WS.getSize())
1152c38e947eSSam Clegg         report_fatal_error("data symbols must have a size set with .size: " +
1153c38e947eSSam Clegg                            WS.getName());
1154d934cb88SDan Gohman 
1155d934cb88SDan Gohman       int64_t Size = 0;
1156d934cb88SDan Gohman       if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1157d934cb88SDan Gohman         report_fatal_error(".size expression must be evaluatable");
1158d934cb88SDan Gohman 
1159759631c7SSam Clegg       auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
1160ea7caceeSSam Clegg       assert(DataSection.isWasmData());
11617c395943SSam Clegg 
11626c899ba6SSam Clegg       // For each data symbol, export it in the symtab as a reference to the
11636c899ba6SSam Clegg       // corresponding Wasm data segment.
11646c899ba6SSam Clegg       wasm::WasmDataReference Ref = wasm::WasmDataReference{
11656c899ba6SSam Clegg           DataSection.getSegmentIndex(),
11666c899ba6SSam Clegg           static_cast<uint32_t>(Layout.getSymbolOffset(WS)),
11676c899ba6SSam Clegg           static_cast<uint32_t>(Size)};
11686c899ba6SSam Clegg       DataLocations[&WS] = Ref;
11696c899ba6SSam Clegg       DEBUG(dbgs() << "  -> segment index: " << Ref.Segment);
11706c899ba6SSam Clegg     } else {
11716c899ba6SSam Clegg       // A "true" Wasm global (currently just __stack_pointer)
1172545932beSEric Christopher       if (WS.isDefined())
11736c899ba6SSam Clegg         report_fatal_error("don't yet support defined globals");
11746c899ba6SSam Clegg 
1175545932beSEric Christopher       // An import; the index was assigned above
1176545932beSEric Christopher       DEBUG(dbgs() << "  -> global index: " << WasmIndices.find(&WS)->second
1177545932beSEric Christopher                    << "\n");
1178d934cb88SDan Gohman     }
1179d934cb88SDan Gohman   }
1180d934cb88SDan Gohman 
1181586320c0SNicholas Wilson   // Populate WasmIndices and DataLocations for aliased symbols.  We need to
1182586320c0SNicholas Wilson   // process these in a separate pass because we need to have processed the
1183586320c0SNicholas Wilson   // target of the alias before the alias itself and the symbols are not
1184586320c0SNicholas Wilson   // necessarily ordered in this way.
1185b7787fd0SSam Clegg   for (const MCSymbol &S : Asm.symbols()) {
1186b7787fd0SSam Clegg     if (!S.isVariable())
1187b7787fd0SSam Clegg       continue;
118831a2c809SSam Clegg 
1189cd65f698SSam Clegg     assert(S.isDefined());
1190b7787fd0SSam Clegg 
11915e3d33a7SSam Clegg     // Find the target symbol of this weak alias and export that index
1192aff1c4dfSSam Clegg     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1193aff1c4dfSSam Clegg     const MCSymbolWasm *ResolvedSym = ResolveSymbol(WS);
11945e3d33a7SSam Clegg     DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym << "'\n");
1195b7787fd0SSam Clegg 
11966c899ba6SSam Clegg     if (WS.isFunction()) {
11976c899ba6SSam Clegg       assert(WasmIndices.count(ResolvedSym) > 0);
11986c899ba6SSam Clegg       uint32_t WasmIndex = WasmIndices.find(ResolvedSym)->second;
11996c899ba6SSam Clegg       WasmIndices[&WS] = WasmIndex;
12006c899ba6SSam Clegg       DEBUG(dbgs() << "  -> index:" << WasmIndex << "\n");
12016c899ba6SSam Clegg     } else if (WS.isData()) {
12026c899ba6SSam Clegg       assert(DataLocations.count(ResolvedSym) > 0);
12036c899ba6SSam Clegg       const wasm::WasmDataReference &Ref =
12046c899ba6SSam Clegg           DataLocations.find(ResolvedSym)->second;
12056c899ba6SSam Clegg       DataLocations[&WS] = Ref;
12066c899ba6SSam Clegg       DEBUG(dbgs() << "  -> index:" << Ref.Segment << "\n");
12076c899ba6SSam Clegg     } else {
12086c899ba6SSam Clegg       report_fatal_error("don't yet support global aliases");
12096c899ba6SSam Clegg     }
1210586320c0SNicholas Wilson   }
121131a2c809SSam Clegg 
1212586320c0SNicholas Wilson   // Finally, populate the symbol table itself, in its "natural" order.
1213586320c0SNicholas Wilson   for (const MCSymbol &S : Asm.symbols()) {
1214586320c0SNicholas Wilson     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1215586320c0SNicholas Wilson     if (WS.isTemporary() && WS.getName().empty())
1216586320c0SNicholas Wilson       continue;
1217586320c0SNicholas Wilson     if (WS.isComdat() && !WS.isDefined())
1218586320c0SNicholas Wilson       continue;
1219586320c0SNicholas Wilson     if (WS.isTemporary() && WS.isData() && !WS.getSize())
1220586320c0SNicholas Wilson       continue;
1221586320c0SNicholas Wilson 
1222586320c0SNicholas Wilson     uint32_t Flags = 0;
1223586320c0SNicholas Wilson     if (WS.isWeak())
1224586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_BINDING_WEAK;
1225586320c0SNicholas Wilson     if (WS.isHidden())
1226586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN;
1227586320c0SNicholas Wilson     if (!WS.isExternal() && WS.isDefined())
1228586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;
1229586320c0SNicholas Wilson     if (WS.isUndefined())
1230586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_UNDEFINED;
1231586320c0SNicholas Wilson 
1232586320c0SNicholas Wilson     wasm::WasmSymbolInfo Info;
1233586320c0SNicholas Wilson     Info.Name = WS.getName();
1234586320c0SNicholas Wilson     Info.Kind = WS.getType();
1235586320c0SNicholas Wilson     Info.Flags = Flags;
1236586320c0SNicholas Wilson     if (!WS.isData())
1237586320c0SNicholas Wilson       Info.ElementIndex = WasmIndices.find(&WS)->second;
1238586320c0SNicholas Wilson     else if (WS.isDefined())
1239586320c0SNicholas Wilson       Info.DataRef = DataLocations.find(&WS)->second;
1240586320c0SNicholas Wilson     SymbolIndices[&WS] = SymbolInfos.size();
1241586320c0SNicholas Wilson     SymbolInfos.emplace_back(Info);
1242b7787fd0SSam Clegg   }
1243b7787fd0SSam Clegg 
12446006e091SSam Clegg   {
12456006e091SSam Clegg     auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
1246f9edbe95SSam Clegg       // Functions referenced by a relocation need to put in the table.  This is
1247f9edbe95SSam Clegg       // purely to make the object file's provisional values readable, and is
1248f9edbe95SSam Clegg       // ignored by the linker, which re-calculates the relocations itself.
1249f9edbe95SSam Clegg       if (Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_I32 &&
1250f9edbe95SSam Clegg           Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB)
1251f9edbe95SSam Clegg         return;
1252f9edbe95SSam Clegg       assert(Rel.Symbol->isFunction());
1253f9edbe95SSam Clegg       const MCSymbolWasm &WS = *ResolveSymbol(*Rel.Symbol);
12546c899ba6SSam Clegg       uint32_t FunctionIndex = WasmIndices.find(&WS)->second;
1255f9edbe95SSam Clegg       uint32_t TableIndex = TableElems.size() + kInitialTableOffset;
1256f9edbe95SSam Clegg       if (TableIndices.try_emplace(&WS, TableIndex).second) {
1257329e76d5SSam Clegg         DEBUG(dbgs() << "  -> adding " << WS.getName()
1258f9edbe95SSam Clegg                      << " to table: " << TableIndex << "\n");
12596c899ba6SSam Clegg         TableElems.push_back(FunctionIndex);
12606006e091SSam Clegg         registerFunctionType(WS);
12616006e091SSam Clegg       }
12626006e091SSam Clegg     };
1263970d02c4SDan Gohman 
12646006e091SSam Clegg     for (const WasmRelocationEntry &RelEntry : CodeRelocations)
12656006e091SSam Clegg       HandleReloc(RelEntry);
12666006e091SSam Clegg     for (const WasmRelocationEntry &RelEntry : DataRelocations)
12676006e091SSam Clegg       HandleReloc(RelEntry);
1268d934cb88SDan Gohman   }
1269d934cb88SDan Gohman 
1270bafe6902SSam Clegg   // Translate .init_array section contents into start functions.
1271bafe6902SSam Clegg   for (const MCSection &S : Asm) {
1272bafe6902SSam Clegg     const auto &WS = static_cast<const MCSectionWasm &>(S);
1273bafe6902SSam Clegg     if (WS.getSectionName().startswith(".fini_array"))
1274bafe6902SSam Clegg       report_fatal_error(".fini_array sections are unsupported");
1275bafe6902SSam Clegg     if (!WS.getSectionName().startswith(".init_array"))
1276bafe6902SSam Clegg       continue;
1277bafe6902SSam Clegg     if (WS.getFragmentList().empty())
1278bafe6902SSam Clegg       continue;
1279bafe6902SSam Clegg     if (WS.getFragmentList().size() != 2)
1280bafe6902SSam Clegg       report_fatal_error("only one .init_array section fragment supported");
1281bafe6902SSam Clegg     const MCFragment &AlignFrag = *WS.begin();
1282bafe6902SSam Clegg     if (AlignFrag.getKind() != MCFragment::FT_Align)
1283bafe6902SSam Clegg       report_fatal_error(".init_array section should be aligned");
1284bafe6902SSam Clegg     if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
1285bafe6902SSam Clegg       report_fatal_error(".init_array section should be aligned for pointers");
1286bafe6902SSam Clegg     const MCFragment &Frag = *std::next(WS.begin());
1287bafe6902SSam Clegg     if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1288bafe6902SSam Clegg       report_fatal_error("only data supported in .init_array section");
1289bafe6902SSam Clegg     uint16_t Priority = UINT16_MAX;
1290bafe6902SSam Clegg     if (WS.getSectionName().size() != 11) {
1291bafe6902SSam Clegg       if (WS.getSectionName()[11] != '.')
1292bafe6902SSam Clegg         report_fatal_error(".init_array section priority should start with '.'");
1293bafe6902SSam Clegg       if (WS.getSectionName().substr(12).getAsInteger(10, Priority))
1294bafe6902SSam Clegg         report_fatal_error("invalid .init_array section priority");
1295bafe6902SSam Clegg     }
1296bafe6902SSam Clegg     const auto &DataFrag = cast<MCDataFragment>(Frag);
1297bafe6902SSam Clegg     const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1298bafe6902SSam Clegg     for (const uint8_t *p = (const uint8_t *)Contents.data(),
1299bafe6902SSam Clegg                      *end = (const uint8_t *)Contents.data() + Contents.size();
1300bafe6902SSam Clegg          p != end; ++p) {
1301bafe6902SSam Clegg       if (*p != 0)
1302bafe6902SSam Clegg         report_fatal_error("non-symbolic data in .init_array section");
1303bafe6902SSam Clegg     }
1304bafe6902SSam Clegg     for (const MCFixup &Fixup : DataFrag.getFixups()) {
1305bafe6902SSam Clegg       assert(Fixup.getKind() == MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
1306bafe6902SSam Clegg       const MCExpr *Expr = Fixup.getValue();
1307bafe6902SSam Clegg       auto *Sym = dyn_cast<MCSymbolRefExpr>(Expr);
1308bafe6902SSam Clegg       if (!Sym)
1309bafe6902SSam Clegg         report_fatal_error("fixups in .init_array should be symbol references");
1310bafe6902SSam Clegg       if (Sym->getKind() != MCSymbolRefExpr::VK_WebAssembly_FUNCTION)
1311bafe6902SSam Clegg         report_fatal_error("symbols in .init_array should be for functions");
1312bafe6902SSam Clegg       auto I = SymbolIndices.find(cast<MCSymbolWasm>(&Sym->getSymbol()));
1313bafe6902SSam Clegg       if (I == SymbolIndices.end())
1314bafe6902SSam Clegg         report_fatal_error("symbols in .init_array should be defined");
1315bafe6902SSam Clegg       uint32_t Index = I->second;
1316bafe6902SSam Clegg       InitFuncs.push_back(std::make_pair(Priority, Index));
1317bafe6902SSam Clegg     }
1318bafe6902SSam Clegg   }
1319bafe6902SSam Clegg 
132018eafb6cSDan Gohman   // Write out the Wasm header.
132118eafb6cSDan Gohman   writeHeader(Asm);
132218eafb6cSDan Gohman 
13239e15f359SSam Clegg   writeTypeSection(FunctionTypes);
1324f950b24aSSam Clegg   writeImportSection(Imports, DataSize, TableElems.size());
13259e15f359SSam Clegg   writeFunctionSection(Functions);
1326f950b24aSSam Clegg   // Skip the "table" section; we import the table instead.
1327f950b24aSSam Clegg   // Skip the "memory" section; we import the memory instead.
13287c395943SSam Clegg   writeGlobalSection();
13299e15f359SSam Clegg   writeExportSection(Exports);
13309e15f359SSam Clegg   writeElemSection(TableElems);
1331acd7d2b0SSam Clegg   writeCodeSection(Asm, Layout, Functions);
13326c899ba6SSam Clegg   writeDataSection();
1333cfd44a2eSSam Clegg   writeUserCustomSections(CustomSections);
1334c22bfb6bSNicholas Wilson   writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats);
1335*6f08c84aSSam Clegg   writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations);
1336*6f08c84aSSam Clegg   writeRelocSection(DataSectionIndex, "DATA", DataRelocations);
1337970d02c4SDan Gohman 
1338d934cb88SDan Gohman   // TODO: Translate the .comment section to the output.
1339d934cb88SDan Gohman   // TODO: Translate debug sections to the output.
134018eafb6cSDan Gohman }
134118eafb6cSDan Gohman 
134260fbc7ccSLang Hames std::unique_ptr<MCObjectWriter>
13431301a878SLang Hames llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
134418eafb6cSDan Gohman                              raw_pwrite_stream &OS) {
13450917c9e4SDan Gohman   return llvm::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
134618eafb6cSDan Gohman }
1347