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"
1618eafb6cSDan Gohman #include "llvm/MC/MCAsmBackend.h"
1718eafb6cSDan Gohman #include "llvm/MC/MCAsmInfo.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/MCObjectFileInfo.h"
2418eafb6cSDan Gohman #include "llvm/MC/MCObjectWriter.h"
2518eafb6cSDan Gohman #include "llvm/MC/MCSectionWasm.h"
2618eafb6cSDan Gohman #include "llvm/MC/MCSymbolWasm.h"
2718eafb6cSDan Gohman #include "llvm/MC/MCValue.h"
2818eafb6cSDan Gohman #include "llvm/MC/MCWasmObjectWriter.h"
29d934cb88SDan Gohman #include "llvm/Support/Casting.h"
3018eafb6cSDan Gohman #include "llvm/Support/Debug.h"
3118eafb6cSDan Gohman #include "llvm/Support/ErrorHandling.h"
32d934cb88SDan Gohman #include "llvm/Support/LEB128.h"
3318eafb6cSDan Gohman #include "llvm/Support/StringSaver.h"
3418eafb6cSDan Gohman #include <vector>
3518eafb6cSDan Gohman 
3618eafb6cSDan Gohman using namespace llvm;
3718eafb6cSDan Gohman 
3818eafb6cSDan Gohman #undef DEBUG_TYPE
3918eafb6cSDan Gohman #define DEBUG_TYPE "reloc-info"
4018eafb6cSDan Gohman 
4118eafb6cSDan Gohman namespace {
429e15f359SSam Clegg 
43d934cb88SDan Gohman // For patching purposes, we need to remember where each section starts, both
44d934cb88SDan Gohman // for patching up the section size field, and for patching up references to
45d934cb88SDan Gohman // locations within the section.
46d934cb88SDan Gohman struct SectionBookkeeping {
47d934cb88SDan Gohman   // Where the size of the section is written.
48d934cb88SDan Gohman   uint64_t SizeOffset;
49d934cb88SDan Gohman   // Where the contents of the section starts (after the header).
50d934cb88SDan Gohman   uint64_t ContentsOffset;
51d934cb88SDan Gohman };
52d934cb88SDan Gohman 
539e15f359SSam Clegg // The signature of a wasm function, in a struct capable of being used as a
549e15f359SSam Clegg // DenseMap key.
559e15f359SSam Clegg struct WasmFunctionType {
569e15f359SSam Clegg   // Support empty and tombstone instances, needed by DenseMap.
579e15f359SSam Clegg   enum { Plain, Empty, Tombstone } State;
589e15f359SSam Clegg 
599e15f359SSam Clegg   // The return types of the function.
609e15f359SSam Clegg   SmallVector<wasm::ValType, 1> Returns;
619e15f359SSam Clegg 
629e15f359SSam Clegg   // The parameter types of the function.
639e15f359SSam Clegg   SmallVector<wasm::ValType, 4> Params;
649e15f359SSam Clegg 
659e15f359SSam Clegg   WasmFunctionType() : State(Plain) {}
669e15f359SSam Clegg 
679e15f359SSam Clegg   bool operator==(const WasmFunctionType &Other) const {
689e15f359SSam Clegg     return State == Other.State && Returns == Other.Returns &&
699e15f359SSam Clegg            Params == Other.Params;
709e15f359SSam Clegg   }
719e15f359SSam Clegg };
729e15f359SSam Clegg 
739e15f359SSam Clegg // Traits for using WasmFunctionType in a DenseMap.
749e15f359SSam Clegg struct WasmFunctionTypeDenseMapInfo {
759e15f359SSam Clegg   static WasmFunctionType getEmptyKey() {
769e15f359SSam Clegg     WasmFunctionType FuncTy;
779e15f359SSam Clegg     FuncTy.State = WasmFunctionType::Empty;
789e15f359SSam Clegg     return FuncTy;
799e15f359SSam Clegg   }
809e15f359SSam Clegg   static WasmFunctionType getTombstoneKey() {
819e15f359SSam Clegg     WasmFunctionType FuncTy;
829e15f359SSam Clegg     FuncTy.State = WasmFunctionType::Tombstone;
839e15f359SSam Clegg     return FuncTy;
849e15f359SSam Clegg   }
859e15f359SSam Clegg   static unsigned getHashValue(const WasmFunctionType &FuncTy) {
869e15f359SSam Clegg     uintptr_t Value = FuncTy.State;
879e15f359SSam Clegg     for (wasm::ValType Ret : FuncTy.Returns)
889e15f359SSam Clegg       Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Ret));
899e15f359SSam Clegg     for (wasm::ValType Param : FuncTy.Params)
909e15f359SSam Clegg       Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Param));
919e15f359SSam Clegg     return Value;
929e15f359SSam Clegg   }
939e15f359SSam Clegg   static bool isEqual(const WasmFunctionType &LHS,
949e15f359SSam Clegg                       const WasmFunctionType &RHS) {
959e15f359SSam Clegg     return LHS == RHS;
969e15f359SSam Clegg   }
979e15f359SSam Clegg };
989e15f359SSam Clegg 
999e15f359SSam Clegg // A wasm import to be written into the import section.
1009e15f359SSam Clegg struct WasmImport {
1019e15f359SSam Clegg   StringRef ModuleName;
1029e15f359SSam Clegg   StringRef FieldName;
1039e15f359SSam Clegg   unsigned Kind;
1049e15f359SSam Clegg   int32_t Type;
1059e15f359SSam Clegg };
1069e15f359SSam Clegg 
1079e15f359SSam Clegg // A wasm function to be written into the function section.
1089e15f359SSam Clegg struct WasmFunction {
1099e15f359SSam Clegg   int32_t Type;
1109e15f359SSam Clegg   const MCSymbolWasm *Sym;
1119e15f359SSam Clegg };
1129e15f359SSam Clegg 
1139e15f359SSam Clegg // A wasm export to be written into the export section.
1149e15f359SSam Clegg struct WasmExport {
1159e15f359SSam Clegg   StringRef FieldName;
1169e15f359SSam Clegg   unsigned Kind;
1179e15f359SSam Clegg   uint32_t Index;
1189e15f359SSam Clegg };
1199e15f359SSam Clegg 
1209e15f359SSam Clegg // A wasm global to be written into the global section.
1219e15f359SSam Clegg struct WasmGlobal {
1229e15f359SSam Clegg   wasm::ValType Type;
1239e15f359SSam Clegg   bool IsMutable;
1249e15f359SSam Clegg   bool HasImport;
1259e15f359SSam Clegg   uint64_t InitialValue;
1269e15f359SSam Clegg   uint32_t ImportIndex;
1279e15f359SSam Clegg };
1289e15f359SSam Clegg 
1296dc65e91SSam Clegg // Information about a single relocation.
1306dc65e91SSam Clegg struct WasmRelocationEntry {
1316dc65e91SSam Clegg   uint64_t Offset;            // Where is the relocation.
1326dc65e91SSam Clegg   const MCSymbolWasm *Symbol; // The symbol to relocate with.
1336dc65e91SSam Clegg   int64_t Addend;             // A value to add to the symbol.
1346dc65e91SSam Clegg   unsigned Type;              // The type of the relocation.
1356dc65e91SSam Clegg   MCSectionWasm *FixupSection;// The section the relocation is targeting.
1366dc65e91SSam Clegg 
1376dc65e91SSam Clegg   WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol,
1386dc65e91SSam Clegg                       int64_t Addend, unsigned Type,
1396dc65e91SSam Clegg                       MCSectionWasm *FixupSection)
1406dc65e91SSam Clegg       : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type),
1416dc65e91SSam Clegg         FixupSection(FixupSection) {}
1426dc65e91SSam Clegg 
143*acd7d2b0SSam Clegg   bool hasAddend() const {
144*acd7d2b0SSam Clegg     switch (Type) {
145*acd7d2b0SSam Clegg     case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_LEB:
146*acd7d2b0SSam Clegg     case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_SLEB:
147*acd7d2b0SSam Clegg     case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_I32:
148*acd7d2b0SSam Clegg       return true;
149*acd7d2b0SSam Clegg     default:
150*acd7d2b0SSam Clegg       return false;
151*acd7d2b0SSam Clegg     }
152*acd7d2b0SSam Clegg   }
153*acd7d2b0SSam Clegg 
1546dc65e91SSam Clegg   void print(raw_ostream &Out) const {
1556dc65e91SSam Clegg     Out << "Off=" << Offset << ", Sym=" << Symbol << ", Addend=" << Addend
1566dc65e91SSam Clegg         << ", Type=" << Type << ", FixupSection=" << FixupSection;
1576dc65e91SSam Clegg   }
1586dc65e91SSam Clegg   void dump() const { print(errs()); }
1596dc65e91SSam Clegg };
1606dc65e91SSam Clegg 
16118eafb6cSDan Gohman class WasmObjectWriter : public MCObjectWriter {
16218eafb6cSDan Gohman   /// Helper struct for containing some precomputed information on symbols.
16318eafb6cSDan Gohman   struct WasmSymbolData {
16418eafb6cSDan Gohman     const MCSymbolWasm *Symbol;
16518eafb6cSDan Gohman     StringRef Name;
16618eafb6cSDan Gohman 
16718eafb6cSDan Gohman     // Support lexicographic sorting.
16818eafb6cSDan Gohman     bool operator<(const WasmSymbolData &RHS) const { return Name < RHS.Name; }
16918eafb6cSDan Gohman   };
17018eafb6cSDan Gohman 
17118eafb6cSDan Gohman   /// The target specific Wasm writer instance.
17218eafb6cSDan Gohman   std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
17318eafb6cSDan Gohman 
174d934cb88SDan Gohman   // Relocations for fixing up references in the code section.
175d934cb88SDan Gohman   std::vector<WasmRelocationEntry> CodeRelocations;
176d934cb88SDan Gohman 
177d934cb88SDan Gohman   // Relocations for fixing up references in the data section.
178d934cb88SDan Gohman   std::vector<WasmRelocationEntry> DataRelocations;
179d934cb88SDan Gohman 
180d934cb88SDan Gohman   // Index values to use for fixing up call_indirect type indices.
181*acd7d2b0SSam Clegg   // Maps function symbols to the index of the type of the function
182*acd7d2b0SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
183*acd7d2b0SSam Clegg 
184*acd7d2b0SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> SymbolIndices;
185*acd7d2b0SSam Clegg 
186*acd7d2b0SSam Clegg   DenseMap<WasmFunctionType, int32_t, WasmFunctionTypeDenseMapInfo>
187*acd7d2b0SSam Clegg       FunctionTypeIndices;
188d934cb88SDan Gohman 
18918eafb6cSDan Gohman   // TargetObjectWriter wrappers.
19018eafb6cSDan Gohman   bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
19118eafb6cSDan Gohman   unsigned getRelocType(MCContext &Ctx, const MCValue &Target,
19218eafb6cSDan Gohman                         const MCFixup &Fixup, bool IsPCRel) const {
19318eafb6cSDan Gohman     return TargetObjectWriter->getRelocType(Ctx, Target, Fixup, IsPCRel);
19418eafb6cSDan Gohman   }
19518eafb6cSDan Gohman 
196d934cb88SDan Gohman   void startSection(SectionBookkeeping &Section, unsigned SectionId,
197d934cb88SDan Gohman                     const char *Name = nullptr);
198d934cb88SDan Gohman   void endSection(SectionBookkeeping &Section);
199d934cb88SDan Gohman 
20018eafb6cSDan Gohman public:
20118eafb6cSDan Gohman   WasmObjectWriter(MCWasmObjectTargetWriter *MOTW, raw_pwrite_stream &OS)
20218eafb6cSDan Gohman       : MCObjectWriter(OS, /*IsLittleEndian=*/true), TargetObjectWriter(MOTW) {}
20318eafb6cSDan Gohman 
204d934cb88SDan Gohman private:
20518eafb6cSDan Gohman   ~WasmObjectWriter() override;
20618eafb6cSDan Gohman 
207*acd7d2b0SSam Clegg   void reset() override {
208*acd7d2b0SSam Clegg     CodeRelocations.clear();
209*acd7d2b0SSam Clegg     DataRelocations.clear();
210*acd7d2b0SSam Clegg     TypeIndices.clear();
211*acd7d2b0SSam Clegg     SymbolIndices.clear();
212*acd7d2b0SSam Clegg     FunctionTypeIndices.clear();
213*acd7d2b0SSam Clegg     MCObjectWriter::reset();
214*acd7d2b0SSam Clegg   }
215*acd7d2b0SSam Clegg 
21618eafb6cSDan Gohman   void writeHeader(const MCAssembler &Asm);
21718eafb6cSDan Gohman 
21818eafb6cSDan Gohman   void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
21918eafb6cSDan Gohman                         const MCFragment *Fragment, const MCFixup &Fixup,
22018eafb6cSDan Gohman                         MCValue Target, bool &IsPCRel,
22118eafb6cSDan Gohman                         uint64_t &FixedValue) override;
22218eafb6cSDan Gohman 
22318eafb6cSDan Gohman   void executePostLayoutBinding(MCAssembler &Asm,
22418eafb6cSDan Gohman                                 const MCAsmLayout &Layout) override;
22518eafb6cSDan Gohman 
22618eafb6cSDan Gohman   void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
2279e15f359SSam Clegg 
2289e15f359SSam Clegg   void writeValueType(wasm::ValType Ty) {
2299e15f359SSam Clegg     encodeSLEB128(int32_t(Ty), getStream());
2309e15f359SSam Clegg   }
2319e15f359SSam Clegg 
2329e15f359SSam Clegg   void writeTypeSection(const SmallVector<WasmFunctionType, 4> &FunctionTypes);
2339e15f359SSam Clegg   void writeImportSection(const SmallVector<WasmImport, 4> &Imports);
2349e15f359SSam Clegg   void writeFunctionSection(const SmallVector<WasmFunction, 4> &Functions);
2359e15f359SSam Clegg   void writeTableSection(const SmallVector<uint32_t, 4> &TableElems);
2369e15f359SSam Clegg   void writeMemorySection(const SmallVector<char, 0> &DataBytes);
2379e15f359SSam Clegg   void writeGlobalSection(const SmallVector<WasmGlobal, 4> &Globals);
2389e15f359SSam Clegg   void writeExportSection(const SmallVector<WasmExport, 4> &Exports);
2399e15f359SSam Clegg   void writeElemSection(const SmallVector<uint32_t, 4> &TableElems);
2409e15f359SSam Clegg   void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
2419e15f359SSam Clegg                         const SmallVector<WasmFunction, 4> &Functions);
2429e15f359SSam Clegg   uint64_t
243*acd7d2b0SSam Clegg   writeDataSection(const SmallVector<char, 0> &DataBytes);
2449e15f359SSam Clegg   void writeNameSection(const SmallVector<WasmFunction, 4> &Functions,
2459e15f359SSam Clegg                         const SmallVector<WasmImport, 4> &Imports,
2469e15f359SSam Clegg                         uint32_t NumFuncImports);
247*acd7d2b0SSam Clegg   void writeCodeRelocSection();
248*acd7d2b0SSam Clegg   void writeDataRelocSection(uint64_t DataSectionHeaderSize);
2499e15f359SSam Clegg   void writeLinkingMetaDataSection(bool HasStackPointer,
2509e15f359SSam Clegg                                    uint32_t StackPointerGlobal);
251*acd7d2b0SSam Clegg 
252*acd7d2b0SSam Clegg   void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
253*acd7d2b0SSam Clegg                         uint64_t ContentsOffset);
254*acd7d2b0SSam Clegg 
255*acd7d2b0SSam Clegg   void writeRelocations(ArrayRef<WasmRelocationEntry> Relocations,
256*acd7d2b0SSam Clegg                         uint64_t HeaderSize);
257*acd7d2b0SSam Clegg   uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
25818eafb6cSDan Gohman };
2599e15f359SSam Clegg 
26018eafb6cSDan Gohman } // end anonymous namespace
26118eafb6cSDan Gohman 
26218eafb6cSDan Gohman WasmObjectWriter::~WasmObjectWriter() {}
26318eafb6cSDan Gohman 
264d934cb88SDan Gohman // Return the padding size to write a 32-bit value into a 5-byte ULEB128.
265d934cb88SDan Gohman static unsigned PaddingFor5ByteULEB128(uint32_t X) {
266d934cb88SDan Gohman   return X == 0 ? 4 : (4u - (31u - countLeadingZeros(X)) / 7u);
267d934cb88SDan Gohman }
268d934cb88SDan Gohman 
269d934cb88SDan Gohman // Return the padding size to write a 32-bit value into a 5-byte SLEB128.
270d934cb88SDan Gohman static unsigned PaddingFor5ByteSLEB128(int32_t X) {
271d934cb88SDan Gohman   return 5 - getSLEB128Size(X);
272d934cb88SDan Gohman }
273d934cb88SDan Gohman 
274d934cb88SDan Gohman // Write out a section header and a patchable section size field.
275d934cb88SDan Gohman void WasmObjectWriter::startSection(SectionBookkeeping &Section,
276d934cb88SDan Gohman                                     unsigned SectionId,
277d934cb88SDan Gohman                                     const char *Name) {
278d934cb88SDan Gohman   assert((Name != nullptr) == (SectionId == wasm::WASM_SEC_CUSTOM) &&
279d934cb88SDan Gohman          "Only custom sections can have names");
280d934cb88SDan Gohman 
281e2688c43SDerek Schuff   encodeULEB128(SectionId, getStream());
282d934cb88SDan Gohman 
283d934cb88SDan Gohman   Section.SizeOffset = getStream().tell();
284d934cb88SDan Gohman 
285d934cb88SDan Gohman   // The section size. We don't know the size yet, so reserve enough space
286d934cb88SDan Gohman   // for any 32-bit value; we'll patch it later.
287d934cb88SDan Gohman   encodeULEB128(UINT32_MAX, getStream());
288d934cb88SDan Gohman 
289d934cb88SDan Gohman   // The position where the section starts, for measuring its size.
290d934cb88SDan Gohman   Section.ContentsOffset = getStream().tell();
291d934cb88SDan Gohman 
292d934cb88SDan Gohman   // Custom sections in wasm also have a string identifier.
293d934cb88SDan Gohman   if (SectionId == wasm::WASM_SEC_CUSTOM) {
294d934cb88SDan Gohman     encodeULEB128(strlen(Name), getStream());
295d934cb88SDan Gohman     writeBytes(Name);
296d934cb88SDan Gohman   }
297d934cb88SDan Gohman }
298d934cb88SDan Gohman 
299d934cb88SDan Gohman // Now that the section is complete and we know how big it is, patch up the
300d934cb88SDan Gohman // section size field at the start of the section.
301d934cb88SDan Gohman void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
302d934cb88SDan Gohman   uint64_t Size = getStream().tell() - Section.ContentsOffset;
303d934cb88SDan Gohman   if (uint32_t(Size) != Size)
304d934cb88SDan Gohman     report_fatal_error("section size does not fit in a uint32_t");
305d934cb88SDan Gohman 
306d934cb88SDan Gohman   unsigned Padding = PaddingFor5ByteULEB128(Size);
307d934cb88SDan Gohman 
308d934cb88SDan Gohman   // Write the final section size to the payload_len field, which follows
309d934cb88SDan Gohman   // the section id byte.
310d934cb88SDan Gohman   uint8_t Buffer[16];
311d934cb88SDan Gohman   unsigned SizeLen = encodeULEB128(Size, Buffer, Padding);
312d934cb88SDan Gohman   assert(SizeLen == 5);
313d934cb88SDan Gohman   getStream().pwrite((char *)Buffer, SizeLen, Section.SizeOffset);
314d934cb88SDan Gohman }
315d934cb88SDan Gohman 
31618eafb6cSDan Gohman // Emit the Wasm header.
31718eafb6cSDan Gohman void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
3187ea5adffSDan Gohman   writeBytes(StringRef(wasm::WasmMagic, sizeof(wasm::WasmMagic)));
3197ea5adffSDan Gohman   writeLE32(wasm::WasmVersion);
32018eafb6cSDan Gohman }
32118eafb6cSDan Gohman 
32218eafb6cSDan Gohman void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
32318eafb6cSDan Gohman                                                 const MCAsmLayout &Layout) {
32418eafb6cSDan Gohman }
32518eafb6cSDan Gohman 
32618eafb6cSDan Gohman void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
32718eafb6cSDan Gohman                                         const MCAsmLayout &Layout,
32818eafb6cSDan Gohman                                         const MCFragment *Fragment,
32918eafb6cSDan Gohman                                         const MCFixup &Fixup, MCValue Target,
33018eafb6cSDan Gohman                                         bool &IsPCRel, uint64_t &FixedValue) {
331d934cb88SDan Gohman   MCSectionWasm &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
332d934cb88SDan Gohman   uint64_t C = Target.getConstant();
333d934cb88SDan Gohman   uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
334d934cb88SDan Gohman   MCContext &Ctx = Asm.getContext();
335d934cb88SDan Gohman 
336d934cb88SDan Gohman   if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
337d934cb88SDan Gohman     assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
338d934cb88SDan Gohman            "Should not have constructed this");
339d934cb88SDan Gohman 
340d934cb88SDan Gohman     // Let A, B and C being the components of Target and R be the location of
341d934cb88SDan Gohman     // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
342d934cb88SDan Gohman     // If it is pcrel, we want to compute (A - B + C - R).
343d934cb88SDan Gohman 
344d934cb88SDan Gohman     // In general, Wasm has no relocations for -B. It can only represent (A + C)
345d934cb88SDan Gohman     // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
346d934cb88SDan Gohman     // replace B to implement it: (A - R - K + C)
347d934cb88SDan Gohman     if (IsPCRel) {
348d934cb88SDan Gohman       Ctx.reportError(
349d934cb88SDan Gohman           Fixup.getLoc(),
350d934cb88SDan Gohman           "No relocation available to represent this relative expression");
351d934cb88SDan Gohman       return;
352d934cb88SDan Gohman     }
353d934cb88SDan Gohman 
354d934cb88SDan Gohman     const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
355d934cb88SDan Gohman 
356d934cb88SDan Gohman     if (SymB.isUndefined()) {
357d934cb88SDan Gohman       Ctx.reportError(Fixup.getLoc(),
358d934cb88SDan Gohman                       Twine("symbol '") + SymB.getName() +
359d934cb88SDan Gohman                           "' can not be undefined in a subtraction expression");
360d934cb88SDan Gohman       return;
361d934cb88SDan Gohman     }
362d934cb88SDan Gohman 
363d934cb88SDan Gohman     assert(!SymB.isAbsolute() && "Should have been folded");
364d934cb88SDan Gohman     const MCSection &SecB = SymB.getSection();
365d934cb88SDan Gohman     if (&SecB != &FixupSection) {
366d934cb88SDan Gohman       Ctx.reportError(Fixup.getLoc(),
367d934cb88SDan Gohman                       "Cannot represent a difference across sections");
368d934cb88SDan Gohman       return;
369d934cb88SDan Gohman     }
370d934cb88SDan Gohman 
371d934cb88SDan Gohman     uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
372d934cb88SDan Gohman     uint64_t K = SymBOffset - FixupOffset;
373d934cb88SDan Gohman     IsPCRel = true;
374d934cb88SDan Gohman     C -= K;
375d934cb88SDan Gohman   }
376d934cb88SDan Gohman 
377d934cb88SDan Gohman   // We either rejected the fixup or folded B into C at this point.
378d934cb88SDan Gohman   const MCSymbolRefExpr *RefA = Target.getSymA();
379d934cb88SDan Gohman   const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr;
380d934cb88SDan Gohman 
381d934cb88SDan Gohman   bool ViaWeakRef = false;
382d934cb88SDan Gohman   if (SymA && SymA->isVariable()) {
383d934cb88SDan Gohman     const MCExpr *Expr = SymA->getVariableValue();
384d934cb88SDan Gohman     if (const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr)) {
385d934cb88SDan Gohman       if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF) {
386d934cb88SDan Gohman         SymA = cast<MCSymbolWasm>(&Inner->getSymbol());
387d934cb88SDan Gohman         ViaWeakRef = true;
388d934cb88SDan Gohman       }
389d934cb88SDan Gohman     }
390d934cb88SDan Gohman   }
391d934cb88SDan Gohman 
392d934cb88SDan Gohman   // Put any constant offset in an addend. Offsets can be negative, and
393d934cb88SDan Gohman   // LLVM expects wrapping, in contrast to wasm's immediates which can't
394d934cb88SDan Gohman   // be negative and don't wrap.
395d934cb88SDan Gohman   FixedValue = 0;
396d934cb88SDan Gohman 
397d934cb88SDan Gohman   if (SymA) {
398d934cb88SDan Gohman     if (ViaWeakRef)
399d934cb88SDan Gohman       llvm_unreachable("weakref used in reloc not yet implemented");
400d934cb88SDan Gohman     else
401d934cb88SDan Gohman       SymA->setUsedInReloc();
402d934cb88SDan Gohman   }
403d934cb88SDan Gohman 
404d934cb88SDan Gohman   unsigned Type = getRelocType(Ctx, Target, Fixup, IsPCRel);
405d934cb88SDan Gohman   WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
406d934cb88SDan Gohman 
407d934cb88SDan Gohman   if (FixupSection.hasInstructions())
408d934cb88SDan Gohman     CodeRelocations.push_back(Rec);
409d934cb88SDan Gohman   else
410d934cb88SDan Gohman     DataRelocations.push_back(Rec);
411d934cb88SDan Gohman }
412d934cb88SDan Gohman 
413d934cb88SDan Gohman // Write X as an (unsigned) LEB value at offset Offset in Stream, padded
414d934cb88SDan Gohman // to allow patching.
415d934cb88SDan Gohman static void
416d934cb88SDan Gohman WritePatchableLEB(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
417d934cb88SDan Gohman   uint8_t Buffer[5];
418d934cb88SDan Gohman   unsigned Padding = PaddingFor5ByteULEB128(X);
419d934cb88SDan Gohman   unsigned SizeLen = encodeULEB128(X, Buffer, Padding);
420d934cb88SDan Gohman   assert(SizeLen == 5);
421d934cb88SDan Gohman   Stream.pwrite((char *)Buffer, SizeLen, Offset);
422d934cb88SDan Gohman }
423d934cb88SDan Gohman 
424d934cb88SDan Gohman // Write X as an signed LEB value at offset Offset in Stream, padded
425d934cb88SDan Gohman // to allow patching.
426d934cb88SDan Gohman static void
427d934cb88SDan Gohman WritePatchableSLEB(raw_pwrite_stream &Stream, int32_t X, uint64_t Offset) {
428d934cb88SDan Gohman   uint8_t Buffer[5];
429d934cb88SDan Gohman   unsigned Padding = PaddingFor5ByteSLEB128(X);
430d934cb88SDan Gohman   unsigned SizeLen = encodeSLEB128(X, Buffer, Padding);
431d934cb88SDan Gohman   assert(SizeLen == 5);
432d934cb88SDan Gohman   Stream.pwrite((char *)Buffer, SizeLen, Offset);
433d934cb88SDan Gohman }
434d934cb88SDan Gohman 
435d934cb88SDan Gohman // Write X as a plain integer value at offset Offset in Stream.
436d934cb88SDan Gohman static void WriteI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
437d934cb88SDan Gohman   uint8_t Buffer[4];
438d934cb88SDan Gohman   support::endian::write32le(Buffer, X);
439d934cb88SDan Gohman   Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
440d934cb88SDan Gohman }
441d934cb88SDan Gohman 
442d934cb88SDan Gohman // Compute a value to write into the code at the location covered
443d934cb88SDan Gohman // by RelEntry. This value isn't used by the static linker, since
444d934cb88SDan Gohman // we have addends; it just serves to make the code more readable
445d934cb88SDan Gohman // and to make standalone wasm modules directly usable.
446d934cb88SDan Gohman static uint32_t ProvisionalValue(const WasmRelocationEntry &RelEntry) {
447d934cb88SDan Gohman   const MCSymbolWasm *Sym = RelEntry.Symbol;
448d934cb88SDan Gohman 
449d934cb88SDan Gohman   // For undefined symbols, use a hopefully invalid value.
450d934cb88SDan Gohman   if (!Sym->isDefined(false))
451d934cb88SDan Gohman     return UINT32_MAX;
452d934cb88SDan Gohman 
453d934cb88SDan Gohman   MCSectionWasm &Section =
454d934cb88SDan Gohman     cast<MCSectionWasm>(RelEntry.Symbol->getSection(false));
455d934cb88SDan Gohman   uint64_t Address = Section.getSectionOffset() + RelEntry.Addend;
456d934cb88SDan Gohman 
457d934cb88SDan Gohman   // Ignore overflow. LLVM allows address arithmetic to silently wrap.
458d934cb88SDan Gohman   uint32_t Value = Address;
459d934cb88SDan Gohman 
460d934cb88SDan Gohman   return Value;
461d934cb88SDan Gohman }
462d934cb88SDan Gohman 
463*acd7d2b0SSam Clegg uint32_t WasmObjectWriter::getRelocationIndexValue(
464*acd7d2b0SSam Clegg     const WasmRelocationEntry &RelEntry) {
465*acd7d2b0SSam Clegg   switch (RelEntry.Type) {
466*acd7d2b0SSam Clegg   case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
467*acd7d2b0SSam Clegg   case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
468*acd7d2b0SSam Clegg   case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
469*acd7d2b0SSam Clegg   case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_LEB:
470*acd7d2b0SSam Clegg   case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_SLEB:
471*acd7d2b0SSam Clegg   case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_I32:
472*acd7d2b0SSam Clegg     assert(SymbolIndices.count(RelEntry.Symbol));
473*acd7d2b0SSam Clegg     return SymbolIndices[RelEntry.Symbol];
474*acd7d2b0SSam Clegg   case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
475*acd7d2b0SSam Clegg     assert(TypeIndices.count(RelEntry.Symbol));
476*acd7d2b0SSam Clegg     return TypeIndices[RelEntry.Symbol];
477*acd7d2b0SSam Clegg   default:
478*acd7d2b0SSam Clegg     llvm_unreachable("invalid relocation type");
479*acd7d2b0SSam Clegg   }
480*acd7d2b0SSam Clegg }
481*acd7d2b0SSam Clegg 
482d934cb88SDan Gohman // Apply the portions of the relocation records that we can handle ourselves
483d934cb88SDan Gohman // directly.
484*acd7d2b0SSam Clegg void WasmObjectWriter::applyRelocations(
485*acd7d2b0SSam Clegg     ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
486*acd7d2b0SSam Clegg   raw_pwrite_stream &Stream = getStream();
487d934cb88SDan Gohman   for (const WasmRelocationEntry &RelEntry : Relocations) {
488d934cb88SDan Gohman     uint64_t Offset = ContentsOffset +
489d934cb88SDan Gohman                       RelEntry.FixupSection->getSectionOffset() +
490d934cb88SDan Gohman                       RelEntry.Offset;
491d934cb88SDan Gohman 
492*acd7d2b0SSam Clegg     switch (RelEntry.Type) {
493*acd7d2b0SSam Clegg     case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
494*acd7d2b0SSam Clegg     case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
495*acd7d2b0SSam Clegg     case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB: {
496*acd7d2b0SSam Clegg       uint32_t Index = getRelocationIndexValue(RelEntry);
497*acd7d2b0SSam Clegg       WritePatchableSLEB(Stream, Index, Offset);
498d934cb88SDan Gohman       break;
499d934cb88SDan Gohman     }
500*acd7d2b0SSam Clegg     case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: {
501*acd7d2b0SSam Clegg       uint32_t Index = getRelocationIndexValue(RelEntry);
502*acd7d2b0SSam Clegg       WriteI32(Stream, Index, Offset);
503d934cb88SDan Gohman       break;
504d934cb88SDan Gohman     }
505d934cb88SDan Gohman     case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_SLEB: {
506d934cb88SDan Gohman       uint32_t Value = ProvisionalValue(RelEntry);
507d934cb88SDan Gohman       WritePatchableSLEB(Stream, Value, Offset);
508d934cb88SDan Gohman       break;
509d934cb88SDan Gohman     }
510d934cb88SDan Gohman     case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_LEB: {
511d934cb88SDan Gohman       uint32_t Value = ProvisionalValue(RelEntry);
512d934cb88SDan Gohman       WritePatchableLEB(Stream, Value, Offset);
513d934cb88SDan Gohman       break;
514d934cb88SDan Gohman     }
515d934cb88SDan Gohman     case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_I32: {
516d934cb88SDan Gohman       uint32_t Value = ProvisionalValue(RelEntry);
517d934cb88SDan Gohman       WriteI32(Stream, Value, Offset);
518d934cb88SDan Gohman       break;
519d934cb88SDan Gohman     }
520d934cb88SDan Gohman     default:
521d934cb88SDan Gohman       llvm_unreachable("unsupported relocation type");
522d934cb88SDan Gohman     }
523d934cb88SDan Gohman   }
52418eafb6cSDan Gohman }
52518eafb6cSDan Gohman 
526*acd7d2b0SSam Clegg // Write out the portions of the relocation records that the linker will
527970d02c4SDan Gohman // need to handle.
528*acd7d2b0SSam Clegg void WasmObjectWriter::writeRelocations(
529*acd7d2b0SSam Clegg     ArrayRef<WasmRelocationEntry> Relocations, uint64_t HeaderSize) {
530*acd7d2b0SSam Clegg   raw_pwrite_stream &Stream = getStream();
531*acd7d2b0SSam Clegg   for (const WasmRelocationEntry& RelEntry : Relocations) {
532970d02c4SDan Gohman 
533*acd7d2b0SSam Clegg     uint64_t Offset = RelEntry.Offset +
534*acd7d2b0SSam Clegg                       RelEntry.FixupSection->getSectionOffset() + HeaderSize;
535*acd7d2b0SSam Clegg     uint32_t Index = getRelocationIndexValue(RelEntry);
536970d02c4SDan Gohman 
537*acd7d2b0SSam Clegg     encodeULEB128(RelEntry.Type, Stream);
538970d02c4SDan Gohman     encodeULEB128(Offset, Stream);
539*acd7d2b0SSam Clegg     encodeULEB128(Index, Stream);
540*acd7d2b0SSam Clegg     if (RelEntry.hasAddend())
541*acd7d2b0SSam Clegg       encodeSLEB128(RelEntry.Addend, Stream);
542970d02c4SDan Gohman   }
543970d02c4SDan Gohman }
544970d02c4SDan Gohman 
5459e15f359SSam Clegg void WasmObjectWriter::writeTypeSection(
5469e15f359SSam Clegg     const SmallVector<WasmFunctionType, 4> &FunctionTypes) {
5479e15f359SSam Clegg   if (FunctionTypes.empty())
5489e15f359SSam Clegg     return;
5499e15f359SSam Clegg 
5509e15f359SSam Clegg   SectionBookkeeping Section;
5519e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_TYPE);
5529e15f359SSam Clegg 
5539e15f359SSam Clegg   encodeULEB128(FunctionTypes.size(), getStream());
5549e15f359SSam Clegg 
5559e15f359SSam Clegg   for (const WasmFunctionType &FuncTy : FunctionTypes) {
5569e15f359SSam Clegg     encodeSLEB128(wasm::WASM_TYPE_FUNC, getStream());
5579e15f359SSam Clegg     encodeULEB128(FuncTy.Params.size(), getStream());
5589e15f359SSam Clegg     for (wasm::ValType Ty : FuncTy.Params)
5599e15f359SSam Clegg       writeValueType(Ty);
5609e15f359SSam Clegg     encodeULEB128(FuncTy.Returns.size(), getStream());
5619e15f359SSam Clegg     for (wasm::ValType Ty : FuncTy.Returns)
5629e15f359SSam Clegg       writeValueType(Ty);
5639e15f359SSam Clegg   }
5649e15f359SSam Clegg 
5659e15f359SSam Clegg   endSection(Section);
5669e15f359SSam Clegg }
5679e15f359SSam Clegg 
5689e15f359SSam Clegg void WasmObjectWriter::writeImportSection(
5699e15f359SSam Clegg     const SmallVector<WasmImport, 4> &Imports) {
5709e15f359SSam Clegg   if (Imports.empty())
5719e15f359SSam Clegg     return;
5729e15f359SSam Clegg 
5739e15f359SSam Clegg   SectionBookkeeping Section;
5749e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_IMPORT);
5759e15f359SSam Clegg 
5769e15f359SSam Clegg   encodeULEB128(Imports.size(), getStream());
5779e15f359SSam Clegg   for (const WasmImport &Import : Imports) {
5789e15f359SSam Clegg     StringRef ModuleName = Import.ModuleName;
5799e15f359SSam Clegg     encodeULEB128(ModuleName.size(), getStream());
5809e15f359SSam Clegg     writeBytes(ModuleName);
5819e15f359SSam Clegg 
5829e15f359SSam Clegg     StringRef FieldName = Import.FieldName;
5839e15f359SSam Clegg     encodeULEB128(FieldName.size(), getStream());
5849e15f359SSam Clegg     writeBytes(FieldName);
5859e15f359SSam Clegg 
5869e15f359SSam Clegg     encodeULEB128(Import.Kind, getStream());
5879e15f359SSam Clegg 
5889e15f359SSam Clegg     switch (Import.Kind) {
5899e15f359SSam Clegg     case wasm::WASM_EXTERNAL_FUNCTION:
5909e15f359SSam Clegg       encodeULEB128(Import.Type, getStream());
5919e15f359SSam Clegg       break;
5929e15f359SSam Clegg     case wasm::WASM_EXTERNAL_GLOBAL:
5939e15f359SSam Clegg       encodeSLEB128(int32_t(Import.Type), getStream());
5949e15f359SSam Clegg       encodeULEB128(0, getStream()); // mutability
5959e15f359SSam Clegg       break;
5969e15f359SSam Clegg     default:
5979e15f359SSam Clegg       llvm_unreachable("unsupported import kind");
5989e15f359SSam Clegg     }
5999e15f359SSam Clegg   }
6009e15f359SSam Clegg 
6019e15f359SSam Clegg   endSection(Section);
6029e15f359SSam Clegg }
6039e15f359SSam Clegg 
6049e15f359SSam Clegg void WasmObjectWriter::writeFunctionSection(
6059e15f359SSam Clegg     const SmallVector<WasmFunction, 4> &Functions) {
6069e15f359SSam Clegg   if (Functions.empty())
6079e15f359SSam Clegg     return;
6089e15f359SSam Clegg 
6099e15f359SSam Clegg   SectionBookkeeping Section;
6109e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_FUNCTION);
6119e15f359SSam Clegg 
6129e15f359SSam Clegg   encodeULEB128(Functions.size(), getStream());
6139e15f359SSam Clegg   for (const WasmFunction &Func : Functions)
6149e15f359SSam Clegg     encodeULEB128(Func.Type, getStream());
6159e15f359SSam Clegg 
6169e15f359SSam Clegg   endSection(Section);
6179e15f359SSam Clegg }
6189e15f359SSam Clegg 
6199e15f359SSam Clegg void WasmObjectWriter::writeTableSection(
6209e15f359SSam Clegg     const SmallVector<uint32_t, 4> &TableElems) {
6219e15f359SSam Clegg   // For now, always emit the table section, since indirect calls are not
6229e15f359SSam Clegg   // valid without it. In the future, we could perhaps be more clever and omit
6239e15f359SSam Clegg   // it if there are no indirect calls.
6249e15f359SSam Clegg   SectionBookkeeping Section;
6259e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_TABLE);
6269e15f359SSam Clegg 
6279e15f359SSam Clegg   // The number of tables, fixed to 1 for now.
6289e15f359SSam Clegg   encodeULEB128(1, getStream());
6299e15f359SSam Clegg 
6309e15f359SSam Clegg   encodeSLEB128(wasm::WASM_TYPE_ANYFUNC, getStream());
6319e15f359SSam Clegg 
6329e15f359SSam Clegg   encodeULEB128(0, getStream());                 // flags
6339e15f359SSam Clegg   encodeULEB128(TableElems.size(), getStream()); // initial
6349e15f359SSam Clegg 
6359e15f359SSam Clegg   endSection(Section);
6369e15f359SSam Clegg }
6379e15f359SSam Clegg 
6389e15f359SSam Clegg void WasmObjectWriter::writeMemorySection(
6399e15f359SSam Clegg     const SmallVector<char, 0> &DataBytes) {
6409e15f359SSam Clegg   // For now, always emit the memory section, since loads and stores are not
6419e15f359SSam Clegg   // valid without it. In the future, we could perhaps be more clever and omit
6429e15f359SSam Clegg   // it if there are no loads or stores.
6439e15f359SSam Clegg   SectionBookkeeping Section;
6449e15f359SSam Clegg   uint32_t NumPages =
6459e15f359SSam Clegg       (DataBytes.size() + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
6469e15f359SSam Clegg 
6479e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_MEMORY);
6489e15f359SSam Clegg   encodeULEB128(1, getStream()); // number of memory spaces
6499e15f359SSam Clegg 
6509e15f359SSam Clegg   encodeULEB128(0, getStream()); // flags
6519e15f359SSam Clegg   encodeULEB128(NumPages, getStream()); // initial
6529e15f359SSam Clegg 
6539e15f359SSam Clegg   endSection(Section);
6549e15f359SSam Clegg }
6559e15f359SSam Clegg 
6569e15f359SSam Clegg void WasmObjectWriter::writeGlobalSection(
6579e15f359SSam Clegg     const SmallVector<WasmGlobal, 4> &Globals) {
6589e15f359SSam Clegg   if (Globals.empty())
6599e15f359SSam Clegg     return;
6609e15f359SSam Clegg 
6619e15f359SSam Clegg   SectionBookkeeping Section;
6629e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_GLOBAL);
6639e15f359SSam Clegg 
6649e15f359SSam Clegg   encodeULEB128(Globals.size(), getStream());
6659e15f359SSam Clegg   for (const WasmGlobal &Global : Globals) {
6669e15f359SSam Clegg     writeValueType(Global.Type);
6679e15f359SSam Clegg     write8(Global.IsMutable);
6689e15f359SSam Clegg 
6699e15f359SSam Clegg     if (Global.HasImport) {
6709e15f359SSam Clegg       assert(Global.InitialValue == 0);
6719e15f359SSam Clegg       write8(wasm::WASM_OPCODE_GET_GLOBAL);
6729e15f359SSam Clegg       encodeULEB128(Global.ImportIndex, getStream());
6739e15f359SSam Clegg     } else {
6749e15f359SSam Clegg       assert(Global.ImportIndex == 0);
6759e15f359SSam Clegg       write8(wasm::WASM_OPCODE_I32_CONST);
6769e15f359SSam Clegg       encodeSLEB128(Global.InitialValue, getStream()); // offset
6779e15f359SSam Clegg     }
6789e15f359SSam Clegg     write8(wasm::WASM_OPCODE_END);
6799e15f359SSam Clegg   }
6809e15f359SSam Clegg 
6819e15f359SSam Clegg   endSection(Section);
6829e15f359SSam Clegg }
6839e15f359SSam Clegg 
6849e15f359SSam Clegg void WasmObjectWriter::writeExportSection(
6859e15f359SSam Clegg     const SmallVector<WasmExport, 4> &Exports) {
6869e15f359SSam Clegg   if (Exports.empty())
6879e15f359SSam Clegg     return;
6889e15f359SSam Clegg 
6899e15f359SSam Clegg   SectionBookkeeping Section;
6909e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_EXPORT);
6919e15f359SSam Clegg 
6929e15f359SSam Clegg   encodeULEB128(Exports.size(), getStream());
6939e15f359SSam Clegg   for (const WasmExport &Export : Exports) {
6949e15f359SSam Clegg     encodeULEB128(Export.FieldName.size(), getStream());
6959e15f359SSam Clegg     writeBytes(Export.FieldName);
6969e15f359SSam Clegg 
6979e15f359SSam Clegg     encodeSLEB128(Export.Kind, getStream());
6989e15f359SSam Clegg 
6999e15f359SSam Clegg     encodeULEB128(Export.Index, getStream());
7009e15f359SSam Clegg   }
7019e15f359SSam Clegg 
7029e15f359SSam Clegg   endSection(Section);
7039e15f359SSam Clegg }
7049e15f359SSam Clegg 
7059e15f359SSam Clegg void WasmObjectWriter::writeElemSection(
7069e15f359SSam Clegg     const SmallVector<uint32_t, 4> &TableElems) {
7079e15f359SSam Clegg   if (TableElems.empty())
7089e15f359SSam Clegg     return;
7099e15f359SSam Clegg 
7109e15f359SSam Clegg   SectionBookkeeping Section;
7119e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_ELEM);
7129e15f359SSam Clegg 
7139e15f359SSam Clegg   encodeULEB128(1, getStream()); // number of "segments"
7149e15f359SSam Clegg   encodeULEB128(0, getStream()); // the table index
7159e15f359SSam Clegg 
7169e15f359SSam Clegg   // init expr for starting offset
7179e15f359SSam Clegg   write8(wasm::WASM_OPCODE_I32_CONST);
7189e15f359SSam Clegg   encodeSLEB128(0, getStream());
7199e15f359SSam Clegg   write8(wasm::WASM_OPCODE_END);
7209e15f359SSam Clegg 
7219e15f359SSam Clegg   encodeULEB128(TableElems.size(), getStream());
7229e15f359SSam Clegg   for (uint32_t Elem : TableElems)
7239e15f359SSam Clegg     encodeULEB128(Elem, getStream());
7249e15f359SSam Clegg 
7259e15f359SSam Clegg   endSection(Section);
7269e15f359SSam Clegg }
7279e15f359SSam Clegg 
7289e15f359SSam Clegg void WasmObjectWriter::writeCodeSection(
7299e15f359SSam Clegg     const MCAssembler &Asm, const MCAsmLayout &Layout,
7309e15f359SSam Clegg     const SmallVector<WasmFunction, 4> &Functions) {
7319e15f359SSam Clegg   if (Functions.empty())
7329e15f359SSam Clegg     return;
7339e15f359SSam Clegg 
7349e15f359SSam Clegg   SectionBookkeeping Section;
7359e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_CODE);
7369e15f359SSam Clegg 
7379e15f359SSam Clegg   encodeULEB128(Functions.size(), getStream());
7389e15f359SSam Clegg 
7399e15f359SSam Clegg   for (const WasmFunction &Func : Functions) {
7409e15f359SSam Clegg     MCSectionWasm &FuncSection =
7419e15f359SSam Clegg         static_cast<MCSectionWasm &>(Func.Sym->getSection());
7429e15f359SSam Clegg 
7439e15f359SSam Clegg     if (Func.Sym->isVariable())
7449e15f359SSam Clegg       report_fatal_error("weak symbols not supported yet");
7459e15f359SSam Clegg 
7469e15f359SSam Clegg     if (Func.Sym->getOffset() != 0)
7479e15f359SSam Clegg       report_fatal_error("function sections must contain one function each");
7489e15f359SSam Clegg 
7499e15f359SSam Clegg     if (!Func.Sym->getSize())
7509e15f359SSam Clegg       report_fatal_error("function symbols must have a size set with .size");
7519e15f359SSam Clegg 
7529e15f359SSam Clegg     int64_t Size = 0;
7539e15f359SSam Clegg     if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
7549e15f359SSam Clegg       report_fatal_error(".size expression must be evaluatable");
7559e15f359SSam Clegg 
7569e15f359SSam Clegg     encodeULEB128(Size, getStream());
7579e15f359SSam Clegg 
7589e15f359SSam Clegg     FuncSection.setSectionOffset(getStream().tell() -
7599e15f359SSam Clegg                                  Section.ContentsOffset);
7609e15f359SSam Clegg 
7619e15f359SSam Clegg     Asm.writeSectionData(&FuncSection, Layout);
7629e15f359SSam Clegg   }
7639e15f359SSam Clegg 
7649e15f359SSam Clegg   // Apply fixups.
765*acd7d2b0SSam Clegg   applyRelocations(CodeRelocations, Section.ContentsOffset);
7669e15f359SSam Clegg 
7679e15f359SSam Clegg   endSection(Section);
7689e15f359SSam Clegg }
7699e15f359SSam Clegg 
7709e15f359SSam Clegg uint64_t WasmObjectWriter::writeDataSection(
771*acd7d2b0SSam Clegg     const SmallVector<char, 0> &DataBytes) {
7729e15f359SSam Clegg   if (DataBytes.empty())
7739e15f359SSam Clegg     return 0;
7749e15f359SSam Clegg 
7759e15f359SSam Clegg   SectionBookkeeping Section;
7769e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_DATA);
7779e15f359SSam Clegg 
7789e15f359SSam Clegg   encodeULEB128(1, getStream()); // count
7799e15f359SSam Clegg   encodeULEB128(0, getStream()); // memory index
7809e15f359SSam Clegg   write8(wasm::WASM_OPCODE_I32_CONST);
7819e15f359SSam Clegg   encodeSLEB128(0, getStream()); // offset
7829e15f359SSam Clegg   write8(wasm::WASM_OPCODE_END);
7839e15f359SSam Clegg   encodeULEB128(DataBytes.size(), getStream()); // size
7849e15f359SSam Clegg   uint32_t HeaderSize = getStream().tell() - Section.ContentsOffset;
7859e15f359SSam Clegg   writeBytes(DataBytes); // data
7869e15f359SSam Clegg 
7879e15f359SSam Clegg   // Apply fixups.
788*acd7d2b0SSam Clegg   applyRelocations(DataRelocations, Section.ContentsOffset + HeaderSize);
7899e15f359SSam Clegg 
7909e15f359SSam Clegg   endSection(Section);
7919e15f359SSam Clegg   return HeaderSize;
7929e15f359SSam Clegg }
7939e15f359SSam Clegg 
7949e15f359SSam Clegg void WasmObjectWriter::writeNameSection(
7959e15f359SSam Clegg     const SmallVector<WasmFunction, 4> &Functions,
7969e15f359SSam Clegg     const SmallVector<WasmImport, 4> &Imports,
7979e15f359SSam Clegg     unsigned NumFuncImports) {
7989e15f359SSam Clegg   uint32_t TotalFunctions = NumFuncImports + Functions.size();
7999e15f359SSam Clegg   if (TotalFunctions == 0)
8009e15f359SSam Clegg     return;
8019e15f359SSam Clegg 
8029e15f359SSam Clegg   SectionBookkeeping Section;
8039e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_CUSTOM, "name");
8049e15f359SSam Clegg   SectionBookkeeping SubSection;
8059e15f359SSam Clegg   startSection(SubSection, wasm::WASM_NAMES_FUNCTION);
8069e15f359SSam Clegg 
8079e15f359SSam Clegg   encodeULEB128(TotalFunctions, getStream());
8089e15f359SSam Clegg   uint32_t Index = 0;
8099e15f359SSam Clegg   for (const WasmImport &Import : Imports) {
8109e15f359SSam Clegg     if (Import.Kind == wasm::WASM_EXTERNAL_FUNCTION) {
8119e15f359SSam Clegg       encodeULEB128(Index, getStream());
8129e15f359SSam Clegg       encodeULEB128(Import.FieldName.size(), getStream());
8139e15f359SSam Clegg       writeBytes(Import.FieldName);
8149e15f359SSam Clegg       ++Index;
8159e15f359SSam Clegg     }
8169e15f359SSam Clegg   }
8179e15f359SSam Clegg   for (const WasmFunction &Func : Functions) {
8189e15f359SSam Clegg     encodeULEB128(Index, getStream());
8199e15f359SSam Clegg     encodeULEB128(Func.Sym->getName().size(), getStream());
8209e15f359SSam Clegg     writeBytes(Func.Sym->getName());
8219e15f359SSam Clegg     ++Index;
8229e15f359SSam Clegg   }
8239e15f359SSam Clegg 
8249e15f359SSam Clegg   endSection(SubSection);
8259e15f359SSam Clegg   endSection(Section);
8269e15f359SSam Clegg }
8279e15f359SSam Clegg 
828*acd7d2b0SSam Clegg void WasmObjectWriter::writeCodeRelocSection() {
8299e15f359SSam Clegg   // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
8309e15f359SSam Clegg   // for descriptions of the reloc sections.
8319e15f359SSam Clegg 
8329e15f359SSam Clegg   if (CodeRelocations.empty())
8339e15f359SSam Clegg     return;
8349e15f359SSam Clegg 
8359e15f359SSam Clegg   SectionBookkeeping Section;
8369e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.CODE");
8379e15f359SSam Clegg 
8389e15f359SSam Clegg   encodeULEB128(wasm::WASM_SEC_CODE, getStream());
839*acd7d2b0SSam Clegg   encodeULEB128(CodeRelocations.size(), getStream());
8409e15f359SSam Clegg 
841*acd7d2b0SSam Clegg   writeRelocations(CodeRelocations, 0);
8429e15f359SSam Clegg 
8439e15f359SSam Clegg   endSection(Section);
8449e15f359SSam Clegg }
8459e15f359SSam Clegg 
846*acd7d2b0SSam Clegg void WasmObjectWriter::writeDataRelocSection(uint64_t DataSectionHeaderSize) {
8479e15f359SSam Clegg   // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
8489e15f359SSam Clegg   // for descriptions of the reloc sections.
8499e15f359SSam Clegg 
8509e15f359SSam Clegg   if (DataRelocations.empty())
8519e15f359SSam Clegg     return;
8529e15f359SSam Clegg 
8539e15f359SSam Clegg   SectionBookkeeping Section;
8549e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.DATA");
8559e15f359SSam Clegg 
8569e15f359SSam Clegg   encodeULEB128(wasm::WASM_SEC_DATA, getStream());
8579e15f359SSam Clegg   encodeULEB128(DataRelocations.size(), getStream());
8589e15f359SSam Clegg 
859*acd7d2b0SSam Clegg   writeRelocations(DataRelocations, DataSectionHeaderSize);
8609e15f359SSam Clegg 
8619e15f359SSam Clegg   endSection(Section);
8629e15f359SSam Clegg }
8639e15f359SSam Clegg 
8649e15f359SSam Clegg void WasmObjectWriter::writeLinkingMetaDataSection(
8659e15f359SSam Clegg     bool HasStackPointer, uint32_t StackPointerGlobal) {
8669e15f359SSam Clegg   if (!HasStackPointer)
8679e15f359SSam Clegg     return;
8689e15f359SSam Clegg   SectionBookkeeping Section;
8699e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_CUSTOM, "linking");
8709e15f359SSam Clegg 
8719e15f359SSam Clegg   encodeULEB128(1, getStream()); // count
8729e15f359SSam Clegg 
8739e15f359SSam Clegg   encodeULEB128(wasm::WASM_STACK_POINTER, getStream()); // type
8749e15f359SSam Clegg   encodeULEB128(StackPointerGlobal, getStream()); // id
8759e15f359SSam Clegg 
8769e15f359SSam Clegg   endSection(Section);
8779e15f359SSam Clegg }
8789e15f359SSam Clegg 
87918eafb6cSDan Gohman void WasmObjectWriter::writeObject(MCAssembler &Asm,
88018eafb6cSDan Gohman                                    const MCAsmLayout &Layout) {
88182607f56SDan Gohman   MCContext &Ctx = Asm.getContext();
882b879539aSDerek Schuff   wasm::ValType PtrType = is64Bit() ? wasm::ValType::I64 : wasm::ValType::I32;
883d934cb88SDan Gohman 
884d934cb88SDan Gohman   // Collect information from the available symbols.
885d934cb88SDan Gohman   SmallVector<WasmFunctionType, 4> FunctionTypes;
886d934cb88SDan Gohman   SmallVector<WasmFunction, 4> Functions;
887d934cb88SDan Gohman   SmallVector<uint32_t, 4> TableElems;
888d934cb88SDan Gohman   SmallVector<WasmGlobal, 4> Globals;
889d934cb88SDan Gohman   SmallVector<WasmImport, 4> Imports;
890d934cb88SDan Gohman   SmallVector<WasmExport, 4> Exports;
891d934cb88SDan Gohman   SmallPtrSet<const MCSymbolWasm *, 4> IsAddressTaken;
892d934cb88SDan Gohman   unsigned NumFuncImports = 0;
893d934cb88SDan Gohman   unsigned NumGlobalImports = 0;
894d934cb88SDan Gohman   SmallVector<char, 0> DataBytes;
895970d02c4SDan Gohman   uint32_t StackPointerGlobal = 0;
896970d02c4SDan Gohman   bool HasStackPointer = false;
897d934cb88SDan Gohman 
898d934cb88SDan Gohman   // Populate the IsAddressTaken set.
899d934cb88SDan Gohman   for (WasmRelocationEntry RelEntry : CodeRelocations) {
900d934cb88SDan Gohman     switch (RelEntry.Type) {
901d934cb88SDan Gohman     case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
902d934cb88SDan Gohman     case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_SLEB:
903d934cb88SDan Gohman       IsAddressTaken.insert(RelEntry.Symbol);
904d934cb88SDan Gohman       break;
905d934cb88SDan Gohman     default:
906d934cb88SDan Gohman       break;
907d934cb88SDan Gohman     }
908d934cb88SDan Gohman   }
909d934cb88SDan Gohman   for (WasmRelocationEntry RelEntry : DataRelocations) {
910d934cb88SDan Gohman     switch (RelEntry.Type) {
911d934cb88SDan Gohman     case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
912d934cb88SDan Gohman     case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_I32:
913d934cb88SDan Gohman       IsAddressTaken.insert(RelEntry.Symbol);
914d934cb88SDan Gohman       break;
915d934cb88SDan Gohman     default:
916d934cb88SDan Gohman       break;
917d934cb88SDan Gohman     }
918d934cb88SDan Gohman   }
919d934cb88SDan Gohman 
920d934cb88SDan Gohman   // Populate the Imports set.
921d934cb88SDan Gohman   for (const MCSymbol &S : Asm.symbols()) {
922d934cb88SDan Gohman     const auto &WS = static_cast<const MCSymbolWasm &>(S);
923b879539aSDerek Schuff     int32_t Type;
924d934cb88SDan Gohman 
925d934cb88SDan Gohman     if (WS.isFunction()) {
926d934cb88SDan Gohman       // Prepare the function's type, if we haven't seen it yet.
927d934cb88SDan Gohman       WasmFunctionType F;
928d934cb88SDan Gohman       F.Returns = WS.getReturns();
929d934cb88SDan Gohman       F.Params = WS.getParams();
930d934cb88SDan Gohman       auto Pair =
931d934cb88SDan Gohman           FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size()));
932d934cb88SDan Gohman       if (Pair.second)
933d934cb88SDan Gohman         FunctionTypes.push_back(F);
934d934cb88SDan Gohman 
935d934cb88SDan Gohman       Type = Pair.first->second;
936d934cb88SDan Gohman     } else {
937b879539aSDerek Schuff       Type = int32_t(PtrType);
938d934cb88SDan Gohman     }
939d934cb88SDan Gohman 
940d934cb88SDan Gohman     // If the symbol is not defined in this translation unit, import it.
941d934cb88SDan Gohman     if (!WS.isTemporary() && !WS.isDefined(/*SetUsed=*/false)) {
942d934cb88SDan Gohman       WasmImport Import;
943d934cb88SDan Gohman       Import.ModuleName = WS.getModuleName();
944d934cb88SDan Gohman       Import.FieldName = WS.getName();
945d934cb88SDan Gohman 
946d934cb88SDan Gohman       if (WS.isFunction()) {
947d934cb88SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
948d934cb88SDan Gohman         Import.Type = Type;
949d934cb88SDan Gohman         SymbolIndices[&WS] = NumFuncImports;
950d934cb88SDan Gohman         ++NumFuncImports;
951d934cb88SDan Gohman       } else {
952d934cb88SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
953d934cb88SDan Gohman         Import.Type = Type;
954d934cb88SDan Gohman         SymbolIndices[&WS] = NumGlobalImports;
955d934cb88SDan Gohman         ++NumGlobalImports;
956d934cb88SDan Gohman       }
957d934cb88SDan Gohman 
958d934cb88SDan Gohman       Imports.push_back(Import);
959d934cb88SDan Gohman     }
960d934cb88SDan Gohman   }
961d934cb88SDan Gohman 
96282607f56SDan Gohman   // In the special .global_variables section, we've encoded global
96382607f56SDan Gohman   // variables used by the function. Translate them into the Globals
96482607f56SDan Gohman   // list.
96582607f56SDan Gohman   MCSectionWasm *GlobalVars = Ctx.getWasmSection(".global_variables", 0, 0);
96682607f56SDan Gohman   if (!GlobalVars->getFragmentList().empty()) {
96782607f56SDan Gohman     if (GlobalVars->getFragmentList().size() != 1)
96882607f56SDan Gohman       report_fatal_error("only one .global_variables fragment supported");
96982607f56SDan Gohman     const MCFragment &Frag = *GlobalVars->begin();
97082607f56SDan Gohman     if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
97182607f56SDan Gohman       report_fatal_error("only data supported in .global_variables");
97282607f56SDan Gohman     const MCDataFragment &DataFrag = cast<MCDataFragment>(Frag);
97382607f56SDan Gohman     if (!DataFrag.getFixups().empty())
97482607f56SDan Gohman       report_fatal_error("fixups not supported in .global_variables");
97582607f56SDan Gohman     const SmallVectorImpl<char> &Contents = DataFrag.getContents();
976970d02c4SDan Gohman     for (const uint8_t *p = (const uint8_t *)Contents.data(),
977970d02c4SDan Gohman                      *end = (const uint8_t *)Contents.data() + Contents.size();
978970d02c4SDan Gohman          p != end; ) {
97982607f56SDan Gohman       WasmGlobal G;
980970d02c4SDan Gohman       if (end - p < 3)
981970d02c4SDan Gohman         report_fatal_error("truncated global variable encoding");
982970d02c4SDan Gohman       G.Type = wasm::ValType(int8_t(*p++));
983970d02c4SDan Gohman       G.IsMutable = bool(*p++);
984970d02c4SDan Gohman       G.HasImport = bool(*p++);
985970d02c4SDan Gohman       if (G.HasImport) {
98682607f56SDan Gohman         G.InitialValue = 0;
987970d02c4SDan Gohman 
988970d02c4SDan Gohman         WasmImport Import;
989970d02c4SDan Gohman         Import.ModuleName = (const char *)p;
990970d02c4SDan Gohman         const uint8_t *nul = (const uint8_t *)memchr(p, '\0', end - p);
991970d02c4SDan Gohman         if (!nul)
992970d02c4SDan Gohman           report_fatal_error("global module name must be nul-terminated");
993970d02c4SDan Gohman         p = nul + 1;
994970d02c4SDan Gohman         nul = (const uint8_t *)memchr(p, '\0', end - p);
995970d02c4SDan Gohman         if (!nul)
996970d02c4SDan Gohman           report_fatal_error("global base name must be nul-terminated");
997970d02c4SDan Gohman         Import.FieldName = (const char *)p;
998970d02c4SDan Gohman         p = nul + 1;
999970d02c4SDan Gohman 
1000970d02c4SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1001970d02c4SDan Gohman         Import.Type = int32_t(G.Type);
1002970d02c4SDan Gohman 
1003970d02c4SDan Gohman         G.ImportIndex = NumGlobalImports;
1004970d02c4SDan Gohman         ++NumGlobalImports;
1005970d02c4SDan Gohman 
1006970d02c4SDan Gohman         Imports.push_back(Import);
1007970d02c4SDan Gohman       } else {
1008970d02c4SDan Gohman         unsigned n;
1009970d02c4SDan Gohman         G.InitialValue = decodeSLEB128(p, &n);
1010970d02c4SDan Gohman         G.ImportIndex = 0;
1011c8da0c0bSSimon Pilgrim         if ((ptrdiff_t)n > end - p)
1012970d02c4SDan Gohman           report_fatal_error("global initial value must be valid SLEB128");
1013970d02c4SDan Gohman         p += n;
1014970d02c4SDan Gohman       }
101582607f56SDan Gohman       Globals.push_back(G);
101682607f56SDan Gohman     }
101782607f56SDan Gohman   }
101882607f56SDan Gohman 
1019970d02c4SDan Gohman   // In the special .stack_pointer section, we've encoded the stack pointer
1020970d02c4SDan Gohman   // index.
1021970d02c4SDan Gohman   MCSectionWasm *StackPtr = Ctx.getWasmSection(".stack_pointer", 0, 0);
1022970d02c4SDan Gohman   if (!StackPtr->getFragmentList().empty()) {
1023970d02c4SDan Gohman     if (StackPtr->getFragmentList().size() != 1)
1024970d02c4SDan Gohman       report_fatal_error("only one .stack_pointer fragment supported");
1025970d02c4SDan Gohman     const MCFragment &Frag = *StackPtr->begin();
1026970d02c4SDan Gohman     if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1027970d02c4SDan Gohman       report_fatal_error("only data supported in .stack_pointer");
1028970d02c4SDan Gohman     const MCDataFragment &DataFrag = cast<MCDataFragment>(Frag);
1029970d02c4SDan Gohman     if (!DataFrag.getFixups().empty())
1030970d02c4SDan Gohman       report_fatal_error("fixups not supported in .stack_pointer");
1031970d02c4SDan Gohman     const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1032970d02c4SDan Gohman     if (Contents.size() != 4)
1033970d02c4SDan Gohman       report_fatal_error("only one entry supported in .stack_pointer");
1034970d02c4SDan Gohman     HasStackPointer = true;
1035970d02c4SDan Gohman     StackPointerGlobal = NumGlobalImports + *(const int32_t *)Contents.data();
1036970d02c4SDan Gohman   }
1037970d02c4SDan Gohman 
1038d934cb88SDan Gohman   // Handle defined symbols.
1039d934cb88SDan Gohman   for (const MCSymbol &S : Asm.symbols()) {
1040d934cb88SDan Gohman     // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1041d934cb88SDan Gohman     // or used in relocations.
1042d934cb88SDan Gohman     if (S.isTemporary() && S.getName().empty())
1043d934cb88SDan Gohman       continue;
1044d934cb88SDan Gohman     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1045d934cb88SDan Gohman     unsigned Index;
1046d934cb88SDan Gohman     if (WS.isFunction()) {
1047d934cb88SDan Gohman       // Prepare the function's type, if we haven't seen it yet.
1048d934cb88SDan Gohman       WasmFunctionType F;
1049d934cb88SDan Gohman       F.Returns = WS.getReturns();
1050d934cb88SDan Gohman       F.Params = WS.getParams();
1051d934cb88SDan Gohman       auto Pair =
1052d934cb88SDan Gohman           FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size()));
1053d934cb88SDan Gohman       if (Pair.second)
1054d934cb88SDan Gohman         FunctionTypes.push_back(F);
1055d934cb88SDan Gohman 
1056b879539aSDerek Schuff       int32_t Type = Pair.first->second;
1057d934cb88SDan Gohman 
1058d934cb88SDan Gohman       if (WS.isDefined(/*SetUsed=*/false)) {
1059d934cb88SDan Gohman         // A definition. Take the next available index.
1060d934cb88SDan Gohman         Index = NumFuncImports + Functions.size();
1061d934cb88SDan Gohman 
1062d934cb88SDan Gohman         // Prepare the function.
1063d934cb88SDan Gohman         WasmFunction Func;
1064d934cb88SDan Gohman         Func.Type = Type;
1065d934cb88SDan Gohman         Func.Sym = &WS;
1066d934cb88SDan Gohman         SymbolIndices[&WS] = Index;
1067d934cb88SDan Gohman         Functions.push_back(Func);
1068d934cb88SDan Gohman       } else {
1069d934cb88SDan Gohman         // An import; the index was assigned above.
1070d934cb88SDan Gohman         Index = SymbolIndices.find(&WS)->second;
1071d934cb88SDan Gohman       }
1072d934cb88SDan Gohman 
1073d934cb88SDan Gohman       // If needed, prepare the function to be called indirectly.
1074d934cb88SDan Gohman       if (IsAddressTaken.count(&WS))
1075d934cb88SDan Gohman         TableElems.push_back(Index);
1076d934cb88SDan Gohman     } else {
1077c38e947eSSam Clegg       if (WS.isTemporary() && !WS.getSize())
1078c38e947eSSam Clegg         continue;
1079c38e947eSSam Clegg 
1080c38e947eSSam Clegg       if (WS.isDefined(false)) {
1081d934cb88SDan Gohman         if (WS.getOffset() != 0)
1082c38e947eSSam Clegg           report_fatal_error("data sections must contain one variable each: " +
1083c38e947eSSam Clegg                              WS.getName());
1084d934cb88SDan Gohman         if (!WS.getSize())
1085c38e947eSSam Clegg           report_fatal_error("data symbols must have a size set with .size: " +
1086c38e947eSSam Clegg                              WS.getName());
1087d934cb88SDan Gohman 
1088d934cb88SDan Gohman         int64_t Size = 0;
1089d934cb88SDan Gohman         if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1090d934cb88SDan Gohman           report_fatal_error(".size expression must be evaluatable");
1091d934cb88SDan Gohman 
1092d934cb88SDan Gohman         MCSectionWasm &DataSection =
1093d934cb88SDan Gohman             static_cast<MCSectionWasm &>(WS.getSection());
1094d934cb88SDan Gohman 
1095d934cb88SDan Gohman         if (uint64_t(Size) != Layout.getSectionFileSize(&DataSection))
1096d934cb88SDan Gohman           report_fatal_error("data sections must contain at most one variable");
1097d934cb88SDan Gohman 
1098d934cb88SDan Gohman         DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
1099d934cb88SDan Gohman 
1100d934cb88SDan Gohman         DataSection.setSectionOffset(DataBytes.size());
1101d934cb88SDan Gohman 
1102d934cb88SDan Gohman         for (MCSection::iterator I = DataSection.begin(), E = DataSection.end();
1103d934cb88SDan Gohman              I != E; ++I) {
1104d934cb88SDan Gohman           const MCFragment &Frag = *I;
1105d934cb88SDan Gohman           if (Frag.hasInstructions())
1106d934cb88SDan Gohman             report_fatal_error("only data supported in data sections");
1107d934cb88SDan Gohman 
1108d934cb88SDan Gohman           if (const MCAlignFragment *Align = dyn_cast<MCAlignFragment>(&Frag)) {
1109d934cb88SDan Gohman             if (Align->getValueSize() != 1)
1110d934cb88SDan Gohman               report_fatal_error("only byte values supported for alignment");
1111d934cb88SDan Gohman             // If nops are requested, use zeros, as this is the data section.
1112d934cb88SDan Gohman             uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
1113d934cb88SDan Gohman             uint64_t Size = std::min<uint64_t>(alignTo(DataBytes.size(),
1114d934cb88SDan Gohman                                                        Align->getAlignment()),
1115d934cb88SDan Gohman                                                DataBytes.size() +
1116d934cb88SDan Gohman                                                    Align->getMaxBytesToEmit());
1117d934cb88SDan Gohman             DataBytes.resize(Size, Value);
1118d934cb88SDan Gohman           } else if (const MCFillFragment *Fill =
1119d934cb88SDan Gohman                                               dyn_cast<MCFillFragment>(&Frag)) {
1120d934cb88SDan Gohman             DataBytes.insert(DataBytes.end(), Size, Fill->getValue());
1121d934cb88SDan Gohman           } else {
1122d934cb88SDan Gohman             const MCDataFragment &DataFrag = cast<MCDataFragment>(Frag);
1123d934cb88SDan Gohman             const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1124d934cb88SDan Gohman 
1125d934cb88SDan Gohman             DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
1126d934cb88SDan Gohman           }
1127d934cb88SDan Gohman         }
1128d934cb88SDan Gohman 
11291c154a61SSam Clegg         // For each global, prepare a corresponding wasm global holding its
11301c154a61SSam Clegg         // address.  For externals these will also be named exports.
1131d934cb88SDan Gohman         Index = NumGlobalImports + Globals.size();
1132d934cb88SDan Gohman 
1133d934cb88SDan Gohman         WasmGlobal Global;
1134d934cb88SDan Gohman         Global.Type = PtrType;
1135d934cb88SDan Gohman         Global.IsMutable = false;
1136970d02c4SDan Gohman         Global.HasImport = false;
1137d934cb88SDan Gohman         Global.InitialValue = DataSection.getSectionOffset();
1138970d02c4SDan Gohman         Global.ImportIndex = 0;
1139d934cb88SDan Gohman         SymbolIndices[&WS] = Index;
1140d934cb88SDan Gohman         Globals.push_back(Global);
1141d934cb88SDan Gohman       }
1142d934cb88SDan Gohman     }
1143d934cb88SDan Gohman 
1144d934cb88SDan Gohman     // If the symbol is visible outside this translation unit, export it.
1145d934cb88SDan Gohman     if (WS.isExternal()) {
1146d934cb88SDan Gohman       assert(WS.isDefined(false));
1147d934cb88SDan Gohman       WasmExport Export;
1148d934cb88SDan Gohman       Export.FieldName = WS.getName();
1149d934cb88SDan Gohman       Export.Index = Index;
1150d934cb88SDan Gohman 
1151d934cb88SDan Gohman       if (WS.isFunction())
1152d934cb88SDan Gohman         Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1153d934cb88SDan Gohman       else
1154d934cb88SDan Gohman         Export.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1155d934cb88SDan Gohman 
1156d934cb88SDan Gohman       Exports.push_back(Export);
1157d934cb88SDan Gohman     }
1158d934cb88SDan Gohman   }
1159d934cb88SDan Gohman 
1160d934cb88SDan Gohman   // Add types for indirect function calls.
1161*acd7d2b0SSam Clegg   for (const WasmRelocationEntry &Fixup : CodeRelocations) {
1162*acd7d2b0SSam Clegg     if (Fixup.Type != wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB)
1163*acd7d2b0SSam Clegg       continue;
1164970d02c4SDan Gohman 
1165d934cb88SDan Gohman     WasmFunctionType F;
1166d934cb88SDan Gohman     F.Returns = Fixup.Symbol->getReturns();
1167d934cb88SDan Gohman     F.Params = Fixup.Symbol->getParams();
1168d934cb88SDan Gohman     auto Pair =
1169d934cb88SDan Gohman         FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size()));
1170d934cb88SDan Gohman     if (Pair.second)
1171d934cb88SDan Gohman       FunctionTypes.push_back(F);
1172d934cb88SDan Gohman 
1173*acd7d2b0SSam Clegg     TypeIndices[Fixup.Symbol] = Pair.first->second;
1174d934cb88SDan Gohman   }
1175d934cb88SDan Gohman 
117618eafb6cSDan Gohman   // Write out the Wasm header.
117718eafb6cSDan Gohman   writeHeader(Asm);
117818eafb6cSDan Gohman 
11799e15f359SSam Clegg   writeTypeSection(FunctionTypes);
11809e15f359SSam Clegg   writeImportSection(Imports);
11819e15f359SSam Clegg   writeFunctionSection(Functions);
11829e15f359SSam Clegg   writeTableSection(TableElems);
11839e15f359SSam Clegg   writeMemorySection(DataBytes);
11849e15f359SSam Clegg   writeGlobalSection(Globals);
11859e15f359SSam Clegg   writeExportSection(Exports);
11869e15f359SSam Clegg   // TODO: Start Section
11879e15f359SSam Clegg   writeElemSection(TableElems);
1188*acd7d2b0SSam Clegg   writeCodeSection(Asm, Layout, Functions);
1189*acd7d2b0SSam Clegg   uint64_t DataSectionHeaderSize = writeDataSection(DataBytes);
11909e15f359SSam Clegg   writeNameSection(Functions, Imports, NumFuncImports);
1191*acd7d2b0SSam Clegg   writeCodeRelocSection();
1192*acd7d2b0SSam Clegg   writeDataRelocSection(DataSectionHeaderSize);
11939e15f359SSam Clegg   writeLinkingMetaDataSection(HasStackPointer, StackPointerGlobal);
1194970d02c4SDan Gohman 
1195d934cb88SDan Gohman   // TODO: Translate the .comment section to the output.
1196d934cb88SDan Gohman   // TODO: Translate debug sections to the output.
119718eafb6cSDan Gohman }
119818eafb6cSDan Gohman 
119918eafb6cSDan Gohman MCObjectWriter *llvm::createWasmObjectWriter(MCWasmObjectTargetWriter *MOTW,
120018eafb6cSDan Gohman                                              raw_pwrite_stream &OS) {
120118eafb6cSDan Gohman   return new WasmObjectWriter(MOTW, OS);
120218eafb6cSDan Gohman }
1203