LCOV - code coverage report
Current view: top level - lib/MC - WasmObjectWriter.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 502 606 82.8 %
Date: 2018-09-23 13:06:45 Functions: 31 37 83.8 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : //===- lib/MC/WasmObjectWriter.cpp - Wasm File Writer ---------------------===//
       2             : //
       3             : //                     The LLVM Compiler Infrastructure
       4             : //
       5             : // This file is distributed under the University of Illinois Open Source
       6             : // License. See LICENSE.TXT for details.
       7             : //
       8             : //===----------------------------------------------------------------------===//
       9             : //
      10             : // This file implements Wasm object file writer information.
      11             : //
      12             : //===----------------------------------------------------------------------===//
      13             : 
      14             : #include "llvm/ADT/STLExtras.h"
      15             : #include "llvm/ADT/SmallPtrSet.h"
      16             : #include "llvm/BinaryFormat/Wasm.h"
      17             : #include "llvm/Config/llvm-config.h"
      18             : #include "llvm/MC/MCAsmBackend.h"
      19             : #include "llvm/MC/MCAsmLayout.h"
      20             : #include "llvm/MC/MCAssembler.h"
      21             : #include "llvm/MC/MCContext.h"
      22             : #include "llvm/MC/MCExpr.h"
      23             : #include "llvm/MC/MCFixupKindInfo.h"
      24             : #include "llvm/MC/MCObjectWriter.h"
      25             : #include "llvm/MC/MCSectionWasm.h"
      26             : #include "llvm/MC/MCSymbolWasm.h"
      27             : #include "llvm/MC/MCValue.h"
      28             : #include "llvm/MC/MCWasmObjectWriter.h"
      29             : #include "llvm/Support/Casting.h"
      30             : #include "llvm/Support/Debug.h"
      31             : #include "llvm/Support/ErrorHandling.h"
      32             : #include "llvm/Support/LEB128.h"
      33             : #include "llvm/Support/StringSaver.h"
      34             : #include <vector>
      35             : 
      36             : using namespace llvm;
      37             : 
      38             : #define DEBUG_TYPE "mc"
      39             : 
      40             : namespace {
      41             : 
      42             : // Went we ceate the indirect function table we start at 1, so that there is
      43             : // and emtpy slot at 0 and therefore calling a null function pointer will trap.
      44             : static const uint32_t kInitialTableOffset = 1;
      45             : 
      46             : // For patching purposes, we need to remember where each section starts, both
      47             : // for patching up the section size field, and for patching up references to
      48             : // locations within the section.
      49             : struct SectionBookkeeping {
      50             :   // Where the size of the section is written.
      51             :   uint64_t SizeOffset;
      52             :   // Where the section header ends (without custom section name).
      53             :   uint64_t PayloadOffset;
      54             :   // Where the contents of the section starts.
      55             :   uint64_t ContentsOffset;
      56             :   uint32_t Index;
      57             : };
      58             : 
      59             : // The signature of a wasm function, in a struct capable of being used as a
      60             : // DenseMap key.
      61         364 : struct WasmFunctionType {
      62             :   // Support empty and tombstone instances, needed by DenseMap.
      63             :   enum { Plain, Empty, Tombstone } State;
      64             : 
      65             :   // The return types of the function.
      66             :   SmallVector<wasm::ValType, 1> Returns;
      67             : 
      68             :   // The parameter types of the function.
      69             :   SmallVector<wasm::ValType, 4> Params;
      70             : 
      71         461 :   WasmFunctionType() : State(Plain) {}
      72             : 
      73       16888 :   bool operator==(const WasmFunctionType &Other) const {
      74       49554 :     return State == Other.State && Returns == Other.Returns &&
      75       16888 :            Params == Other.Params;
      76             :   }
      77             : };
      78             : 
      79             : // Traits for using WasmFunctionType in a DenseMap.
      80             : struct WasmFunctionTypeDenseMapInfo {
      81             :   static WasmFunctionType getEmptyKey() {
      82             :     WasmFunctionType FuncTy;
      83         833 :     FuncTy.State = WasmFunctionType::Empty;
      84             :     return FuncTy;
      85             :   }
      86             :   static WasmFunctionType getTombstoneKey() {
      87             :     WasmFunctionType FuncTy;
      88         709 :     FuncTy.State = WasmFunctionType::Tombstone;
      89             :     return FuncTy;
      90             :   }
      91         461 :   static unsigned getHashValue(const WasmFunctionType &FuncTy) {
      92         461 :     uintptr_t Value = FuncTy.State;
      93         774 :     for (wasm::ValType Ret : FuncTy.Returns)
      94         313 :       Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Ret));
      95         533 :     for (wasm::ValType Param : FuncTy.Params)
      96          72 :       Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Param));
      97         461 :     return Value;
      98             :   }
      99             :   static bool isEqual(const WasmFunctionType &LHS,
     100             :                       const WasmFunctionType &RHS) {
     101       16706 :     return LHS == RHS;
     102             :   }
     103             : };
     104             : 
     105             : // A wasm data segment.  A wasm binary contains only a single data section
     106             : // but that can contain many segments, each with their own virtual location
     107             : // in memory.  Each MCSection data created by llvm is modeled as its own
     108             : // wasm data segment.
     109          95 : struct WasmDataSegment {
     110             :   MCSectionWasm *Section;
     111             :   StringRef Name;
     112             :   uint32_t Offset;
     113             :   uint32_t Alignment;
     114             :   uint32_t Flags;
     115             :   SmallVector<char, 4> Data;
     116             : };
     117             : 
     118             : // A wasm function to be written into the function section.
     119             : struct WasmFunction {
     120             :   int32_t Type;
     121             :   const MCSymbolWasm *Sym;
     122             : };
     123             : 
     124             : // A wasm global to be written into the global section.
     125             : struct WasmGlobal {
     126             :   wasm::WasmGlobalType Type;
     127             :   uint64_t InitialValue;
     128             : };
     129             : 
     130             : // Information about a single item which is part of a COMDAT.  For each data
     131             : // segment or function which is in the COMDAT, there is a corresponding
     132             : // WasmComdatEntry.
     133             : struct WasmComdatEntry {
     134             :   unsigned Kind;
     135             :   uint32_t Index;
     136             : };
     137             : 
     138             : // Information about a single relocation.
     139             : struct WasmRelocationEntry {
     140             :   uint64_t Offset;                   // Where is the relocation.
     141             :   const MCSymbolWasm *Symbol;        // The symbol to relocate with.
     142             :   int64_t Addend;                    // A value to add to the symbol.
     143             :   unsigned Type;                     // The type of the relocation.
     144             :   const MCSectionWasm *FixupSection; // The section the relocation is targeting.
     145             : 
     146             :   WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol,
     147             :                       int64_t Addend, unsigned Type,
     148             :                       const MCSectionWasm *FixupSection)
     149         409 :       : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type),
     150         409 :         FixupSection(FixupSection) {}
     151             : 
     152           0 :   bool hasAddend() const {
     153           0 :     switch (Type) {
     154             :     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
     155             :     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
     156             :     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
     157             :     case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32:
     158             :     case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32:
     159             :       return true;
     160           0 :     default:
     161           0 :       return false;
     162             :     }
     163             :   }
     164             : 
     165             :   void print(raw_ostream &Out) const {
     166             :     Out << wasm::relocTypetoString(Type) << " Off=" << Offset
     167             :         << ", Sym=" << *Symbol << ", Addend=" << Addend
     168             :         << ", FixupSection=" << FixupSection->getSectionName();
     169             :   }
     170             : 
     171             : #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
     172             :   LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
     173             : #endif
     174             : };
     175             : 
     176             : static const uint32_t INVALID_INDEX = -1;
     177             : 
     178             : struct WasmCustomSection {
     179             : 
     180             :   StringRef Name;
     181             :   MCSectionWasm *Section;
     182             : 
     183             :   uint32_t OutputContentsOffset;
     184             :   uint32_t OutputIndex;
     185             : 
     186             :   WasmCustomSection(StringRef Name, MCSectionWasm *Section)
     187          34 :       : Name(Name), Section(Section), OutputContentsOffset(0),
     188          34 :         OutputIndex(INVALID_INDEX) {}
     189             : };
     190             : 
     191             : #if !defined(NDEBUG)
     192             : raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
     193             :   Rel.print(OS);
     194             :   return OS;
     195             : }
     196             : #endif
     197             : 
     198             : class WasmObjectWriter : public MCObjectWriter {
     199             :   support::endian::Writer W;
     200             : 
     201             :   /// The target specific Wasm writer instance.
     202             :   std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
     203             : 
     204             :   // Relocations for fixing up references in the code section.
     205             :   std::vector<WasmRelocationEntry> CodeRelocations;
     206             :   uint32_t CodeSectionIndex;
     207             : 
     208             :   // Relocations for fixing up references in the data section.
     209             :   std::vector<WasmRelocationEntry> DataRelocations;
     210             :   uint32_t DataSectionIndex;
     211             : 
     212             :   // Index values to use for fixing up call_indirect type indices.
     213             :   // Maps function symbols to the index of the type of the function
     214             :   DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
     215             :   // Maps function symbols to the table element index space. Used
     216             :   // for TABLE_INDEX relocation types (i.e. address taken functions).
     217             :   DenseMap<const MCSymbolWasm *, uint32_t> TableIndices;
     218             :   // Maps function/global symbols to the function/global/section index space.
     219             :   DenseMap<const MCSymbolWasm *, uint32_t> WasmIndices;
     220             :   // Maps data symbols to the Wasm segment and offset/size with the segment.
     221             :   DenseMap<const MCSymbolWasm *, wasm::WasmDataReference> DataLocations;
     222             : 
     223             :   // Stores output data (index, relocations, content offset) for custom
     224             :   // section.
     225             :   std::vector<WasmCustomSection> CustomSections;
     226             :   // Relocations for fixing up references in the custom sections.
     227             :   DenseMap<const MCSectionWasm *, std::vector<WasmRelocationEntry>>
     228             :       CustomSectionsRelocations;
     229             : 
     230             :   // Map from section to defining function symbol.
     231             :   DenseMap<const MCSection *, const MCSymbol *> SectionFunctions;
     232             : 
     233             :   DenseMap<WasmFunctionType, int32_t, WasmFunctionTypeDenseMapInfo>
     234             :       FunctionTypeIndices;
     235             :   SmallVector<WasmFunctionType, 4> FunctionTypes;
     236             :   SmallVector<WasmGlobal, 4> Globals;
     237             :   SmallVector<WasmDataSegment, 4> DataSegments;
     238             :   unsigned NumFunctionImports = 0;
     239             :   unsigned NumGlobalImports = 0;
     240             :   uint32_t SectionCount = 0;
     241             : 
     242             :   // TargetObjectWriter wrappers.
     243             :   bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
     244             :   unsigned getRelocType(const MCValue &Target, const MCFixup &Fixup) const {
     245         410 :     return TargetObjectWriter->getRelocType(Target, Fixup);
     246             :   }
     247             : 
     248             :   void startSection(SectionBookkeeping &Section, unsigned SectionId);
     249             :   void startCustomSection(SectionBookkeeping &Section, StringRef Name);
     250             :   void endSection(SectionBookkeeping &Section);
     251             : 
     252             : public:
     253         295 :   WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
     254             :                    raw_pwrite_stream &OS)
     255         590 :       : W(OS, support::little), TargetObjectWriter(std::move(MOTW)) {}
     256             : 
     257             :   ~WasmObjectWriter() override;
     258             : 
     259             : private:
     260         147 :   void reset() override {
     261             :     CodeRelocations.clear();
     262             :     DataRelocations.clear();
     263         147 :     TypeIndices.clear();
     264         147 :     WasmIndices.clear();
     265         147 :     TableIndices.clear();
     266         147 :     DataLocations.clear();
     267         147 :     CustomSectionsRelocations.clear();
     268         147 :     FunctionTypeIndices.clear();
     269             :     FunctionTypes.clear();
     270             :     Globals.clear();
     271         147 :     DataSegments.clear();
     272         147 :     SectionFunctions.clear();
     273         147 :     NumFunctionImports = 0;
     274         147 :     NumGlobalImports = 0;
     275             :     MCObjectWriter::reset();
     276         147 :   }
     277             : 
     278             :   void writeHeader(const MCAssembler &Asm);
     279             : 
     280             :   void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
     281             :                         const MCFragment *Fragment, const MCFixup &Fixup,
     282             :                         MCValue Target, uint64_t &FixedValue) override;
     283             : 
     284             :   void executePostLayoutBinding(MCAssembler &Asm,
     285             :                                 const MCAsmLayout &Layout) override;
     286             : 
     287             :   uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
     288             : 
     289           0 :   void writeString(const StringRef Str) {
     290           0 :     encodeULEB128(Str.size(), W.OS);
     291           0 :     W.OS << Str;
     292           0 :   }
     293             : 
     294           0 :   void writeValueType(wasm::ValType Ty) { W.OS << static_cast<char>(Ty); }
     295             : 
     296             :   void writeTypeSection(ArrayRef<WasmFunctionType> FunctionTypes);
     297             :   void writeImportSection(ArrayRef<wasm::WasmImport> Imports, uint32_t DataSize,
     298             :                           uint32_t NumElements);
     299             :   void writeFunctionSection(ArrayRef<WasmFunction> Functions);
     300             :   void writeGlobalSection();
     301             :   void writeExportSection(ArrayRef<wasm::WasmExport> Exports);
     302             :   void writeElemSection(ArrayRef<uint32_t> TableElems);
     303             :   void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
     304             :                         ArrayRef<WasmFunction> Functions);
     305             :   void writeDataSection();
     306             :   void writeRelocSection(uint32_t SectionIndex, StringRef Name,
     307             :                          std::vector<WasmRelocationEntry> &Relocations);
     308             :   void writeLinkingMetaDataSection(
     309             :       ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
     310             :       ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
     311             :       const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats);
     312             :   void writeCustomSections(const MCAssembler &Asm, const MCAsmLayout &Layout);
     313             :   void writeCustomRelocSections();
     314             :   void
     315             :   updateCustomSectionRelocations(const SmallVector<WasmFunction, 4> &Functions,
     316             :                                  const MCAsmLayout &Layout);
     317             : 
     318             :   uint32_t getProvisionalValue(const WasmRelocationEntry &RelEntry);
     319             :   void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
     320             :                         uint64_t ContentsOffset);
     321             : 
     322             :   uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
     323             :   uint32_t getFunctionType(const MCSymbolWasm &Symbol);
     324             :   uint32_t registerFunctionType(const MCSymbolWasm &Symbol);
     325             : };
     326             : 
     327             : } // end anonymous namespace
     328             : 
     329        1160 : WasmObjectWriter::~WasmObjectWriter() {}
     330             : 
     331             : // Write out a section header and a patchable section size field.
     332           0 : void WasmObjectWriter::startSection(SectionBookkeeping &Section,
     333             :                                     unsigned SectionId) {
     334             :   LLVM_DEBUG(dbgs() << "startSection " << SectionId << "\n");
     335           0 :   W.OS << char(SectionId);
     336             : 
     337           0 :   Section.SizeOffset = W.OS.tell();
     338             : 
     339             :   // The section size. We don't know the size yet, so reserve enough space
     340             :   // for any 32-bit value; we'll patch it later.
     341           0 :   encodeULEB128(UINT32_MAX, W.OS);
     342             : 
     343             :   // The position where the section starts, for measuring its size.
     344           0 :   Section.ContentsOffset = W.OS.tell();
     345           0 :   Section.PayloadOffset = W.OS.tell();
     346           0 :   Section.Index = SectionCount++;
     347           0 : }
     348             : 
     349         275 : void WasmObjectWriter::startCustomSection(SectionBookkeeping &Section,
     350             :                                           StringRef Name) {
     351             :   LLVM_DEBUG(dbgs() << "startCustomSection " << Name << "\n");
     352         275 :   startSection(Section, wasm::WASM_SEC_CUSTOM);
     353             : 
     354             :   // The position where the section header ends, for measuring its size.
     355         275 :   Section.PayloadOffset = W.OS.tell();
     356             : 
     357             :   // Custom sections in wasm also have a string identifier.
     358         275 :   writeString(Name);
     359             : 
     360             :   // The position where the custom section starts.
     361         275 :   Section.ContentsOffset = W.OS.tell();
     362         275 : }
     363             : 
     364             : // Now that the section is complete and we know how big it is, patch up the
     365             : // section size field at the start of the section.
     366           0 : void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
     367           0 :   uint64_t Size = W.OS.tell() - Section.PayloadOffset;
     368           0 :   if (uint32_t(Size) != Size)
     369           0 :     report_fatal_error("section size does not fit in a uint32_t");
     370             : 
     371             :   LLVM_DEBUG(dbgs() << "endSection size=" << Size << "\n");
     372             : 
     373             :   // Write the final section size to the payload_len field, which follows
     374             :   // the section id byte.
     375             :   uint8_t Buffer[16];
     376           0 :   unsigned SizeLen = encodeULEB128(Size, Buffer, 5);
     377             :   assert(SizeLen == 5);
     378           0 :   static_cast<raw_pwrite_stream &>(W.OS).pwrite((char *)Buffer, SizeLen,
     379             :                                                 Section.SizeOffset);
     380           0 : }
     381             : 
     382             : // Emit the Wasm header.
     383           0 : void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
     384           0 :   W.OS.write(wasm::WasmMagic, sizeof(wasm::WasmMagic));
     385           0 :   W.write<uint32_t>(wasm::WasmVersion);
     386           0 : }
     387             : 
     388         148 : void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
     389             :                                                 const MCAsmLayout &Layout) {
     390             :   // Build a map of sections to the function that defines them, for use
     391             :   // in recordRelocation.
     392        1741 :   for (const MCSymbol &S : Asm.symbols()) {
     393             :     const auto &WS = static_cast<const MCSymbolWasm &>(S);
     394        1593 :     if (WS.isDefined() && WS.isFunction() && !WS.isVariable()) {
     395             :       const auto &Sec = static_cast<const MCSectionWasm &>(S.getSection());
     396         342 :       auto Pair = SectionFunctions.insert(std::make_pair(&Sec, &S));
     397         342 :       if (!Pair.second)
     398           0 :         report_fatal_error("section already has a defining function: " +
     399           0 :                            Sec.getSectionName());
     400             :     }
     401             :   }
     402         148 : }
     403             : 
     404         427 : void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
     405             :                                         const MCAsmLayout &Layout,
     406             :                                         const MCFragment *Fragment,
     407             :                                         const MCFixup &Fixup, MCValue Target,
     408             :                                         uint64_t &FixedValue) {
     409             :   MCAsmBackend &Backend = Asm.getBackend();
     410         427 :   bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
     411             :                  MCFixupKindInfo::FKF_IsPCRel;
     412         427 :   const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
     413         427 :   uint64_t C = Target.getConstant();
     414         427 :   uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
     415         427 :   MCContext &Ctx = Asm.getContext();
     416             : 
     417             :   // The .init_array isn't translated as data, so don't do relocations in it.
     418             :   if (FixupSection.getSectionName().startswith(".init_array"))
     419          17 :     return;
     420             : 
     421         410 :   if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
     422             :     assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
     423             :            "Should not have constructed this");
     424             : 
     425             :     // Let A, B and C being the components of Target and R be the location of
     426             :     // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
     427             :     // If it is pcrel, we want to compute (A - B + C - R).
     428             : 
     429             :     // In general, Wasm has no relocations for -B. It can only represent (A + C)
     430             :     // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
     431             :     // replace B to implement it: (A - R - K + C)
     432           0 :     if (IsPCRel) {
     433           0 :       Ctx.reportError(
     434             :           Fixup.getLoc(),
     435             :           "No relocation available to represent this relative expression");
     436           0 :       return;
     437             :     }
     438             : 
     439           0 :     const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
     440             : 
     441           0 :     if (SymB.isUndefined()) {
     442           0 :       Ctx.reportError(Fixup.getLoc(),
     443           0 :                       Twine("symbol '") + SymB.getName() +
     444           0 :                           "' can not be undefined in a subtraction expression");
     445           0 :       return;
     446             :     }
     447             : 
     448             :     assert(!SymB.isAbsolute() && "Should have been folded");
     449             :     const MCSection &SecB = SymB.getSection();
     450           0 :     if (&SecB != &FixupSection) {
     451           0 :       Ctx.reportError(Fixup.getLoc(),
     452             :                       "Cannot represent a difference across sections");
     453           0 :       return;
     454             :     }
     455             : 
     456           0 :     uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
     457             :     uint64_t K = SymBOffset - FixupOffset;
     458             :     IsPCRel = true;
     459           0 :     C -= K;
     460             :   }
     461             : 
     462             :   // We either rejected the fixup or folded B into C at this point.
     463         410 :   const MCSymbolRefExpr *RefA = Target.getSymA();
     464         410 :   const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr;
     465             : 
     466         410 :   if (SymA && SymA->isVariable()) {
     467             :     const MCExpr *Expr = SymA->getVariableValue();
     468             :     const auto *Inner = cast<MCSymbolRefExpr>(Expr);
     469           8 :     if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
     470           0 :       llvm_unreachable("weakref used in reloc not yet implemented");
     471             :   }
     472             : 
     473             :   // Put any constant offset in an addend. Offsets can be negative, and
     474             :   // LLVM expects wrapping, in contrast to wasm's immediates which can't
     475             :   // be negative and don't wrap.
     476         410 :   FixedValue = 0;
     477             : 
     478             :   unsigned Type = getRelocType(Target, Fixup);
     479             :   assert(!IsPCRel);
     480             :   assert(SymA);
     481             : 
     482             :   // Absolute offset within a section or a function.
     483             :   // Currently only supported for for metadata sections.
     484             :   // See: test/MC/WebAssembly/blockaddress.ll
     485         410 :   if (Type == wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32 ||
     486             :       Type == wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32) {
     487          65 :     if (!FixupSection.getKind().isMetadata())
     488           1 :       report_fatal_error("relocations for function or section offsets are "
     489             :                          "only supported in metadata sections");
     490             : 
     491             :     const MCSymbol *SectionSymbol = nullptr;
     492          64 :     const MCSection &SecA = SymA->getSection();
     493          64 :     if (SecA.getKind().isText())
     494          17 :       SectionSymbol = SectionFunctions.find(&SecA)->second;
     495             :     else
     496             :       SectionSymbol = SecA.getBeginSymbol();
     497          64 :     if (!SectionSymbol)
     498           0 :       report_fatal_error("section symbol is required for relocation");
     499             : 
     500          64 :     C += Layout.getSymbolOffset(*SymA);
     501             :     SymA = cast<MCSymbolWasm>(SectionSymbol);
     502             :   }
     503             : 
     504             :   // Relocation other than R_WEBASSEMBLY_TYPE_INDEX_LEB are required to be
     505             :   // against a named symbol.
     506         409 :   if (Type != wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB) {
     507         398 :     if (SymA->getName().empty())
     508           0 :       report_fatal_error("relocations against un-named temporaries are not yet "
     509             :                          "supported by wasm");
     510             : 
     511             :     SymA->setUsedInReloc();
     512             :   }
     513             : 
     514         409 :   WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
     515             :   LLVM_DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
     516             : 
     517         409 :   if (FixupSection.isWasmData()) {
     518          30 :     DataRelocations.push_back(Rec);
     519         379 :   } else if (FixupSection.getKind().isText()) {
     520         309 :     CodeRelocations.push_back(Rec);
     521          70 :   } else if (FixupSection.getKind().isMetadata()) {
     522          70 :     CustomSectionsRelocations[&FixupSection].push_back(Rec);
     523             :   } else {
     524           0 :     llvm_unreachable("unexpected section type");
     525             :   }
     526             : }
     527             : 
     528             : // Write X as an (unsigned) LEB value at offset Offset in Stream, padded
     529             : // to allow patching.
     530         260 : static void WritePatchableLEB(raw_pwrite_stream &Stream, uint32_t X,
     531             :                               uint64_t Offset) {
     532             :   uint8_t Buffer[5];
     533         260 :   unsigned SizeLen = encodeULEB128(X, Buffer, 5);
     534             :   assert(SizeLen == 5);
     535         260 :   Stream.pwrite((char *)Buffer, SizeLen, Offset);
     536         260 : }
     537             : 
     538             : // Write X as an signed LEB value at offset Offset in Stream, padded
     539             : // to allow patching.
     540          49 : static void WritePatchableSLEB(raw_pwrite_stream &Stream, int32_t X,
     541             :                                uint64_t Offset) {
     542             :   uint8_t Buffer[5];
     543          49 :   unsigned SizeLen = encodeSLEB128(X, Buffer, 5);
     544             :   assert(SizeLen == 5);
     545          49 :   Stream.pwrite((char *)Buffer, SizeLen, Offset);
     546          49 : }
     547             : 
     548             : // Write X as a plain integer value at offset Offset in Stream.
     549             : static void WriteI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
     550             :   uint8_t Buffer[4];
     551             :   support::endian::write32le(Buffer, X);
     552             :   Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
     553             : }
     554             : 
     555             : static const MCSymbolWasm *ResolveSymbol(const MCSymbolWasm &Symbol) {
     556         689 :   if (Symbol.isVariable()) {
     557             :     const MCExpr *Expr = Symbol.getVariableValue();
     558             :     auto *Inner = cast<MCSymbolRefExpr>(Expr);
     559           7 :     return cast<MCSymbolWasm>(&Inner->getSymbol());
     560             :   }
     561             :   return &Symbol;
     562             : }
     563             : 
     564             : // Compute a value to write into the code at the location covered
     565             : // by RelEntry. This value isn't used by the static linker; it just serves
     566             : // to make the object format more readable and more likely to be directly
     567             : // useable.
     568             : uint32_t
     569         409 : WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) {
     570         409 :   switch (RelEntry.Type) {
     571          42 :   case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
     572             :   case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: {
     573             :     // Provisional value is table address of the resolved symbol itself
     574          42 :     const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
     575             :     assert(Sym->isFunction());
     576          42 :     return TableIndices[Sym];
     577             :   }
     578          11 :   case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
     579             :     // Provisional value is same as the index
     580          11 :     return getRelocationIndexValue(RelEntry);
     581         106 :   case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
     582             :   case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
     583             :     // Provisional value is function/global Wasm index
     584         106 :     if (!WasmIndices.count(RelEntry.Symbol))
     585           0 :       report_fatal_error("symbol not found in wasm index space: " +
     586           0 :                          RelEntry.Symbol->getName());
     587         106 :     return WasmIndices[RelEntry.Symbol];
     588          64 :   case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32:
     589             :   case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32: {
     590             :     const auto &Section =
     591          64 :         static_cast<const MCSectionWasm &>(RelEntry.Symbol->getSection());
     592          64 :     return Section.getSectionOffset() + RelEntry.Addend;
     593             :   }
     594         186 :   case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
     595             :   case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
     596             :   case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: {
     597             :     // Provisional value is address of the global
     598         186 :     const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
     599             :     // For undefined symbols, use zero
     600         186 :     if (!Sym->isDefined())
     601             :       return 0;
     602         165 :     const wasm::WasmDataReference &Ref = DataLocations[Sym];
     603         165 :     const WasmDataSegment &Segment = DataSegments[Ref.Segment];
     604             :     // Ignore overflow. LLVM allows address arithmetic to silently wrap.
     605         165 :     return Segment.Offset + Ref.Offset + RelEntry.Addend;
     606             :   }
     607           0 :   default:
     608           0 :     llvm_unreachable("invalid relocation type");
     609             :   }
     610             : }
     611             : 
     612          83 : static void addData(SmallVectorImpl<char> &DataBytes,
     613             :                     MCSectionWasm &DataSection) {
     614             :   LLVM_DEBUG(errs() << "addData: " << DataSection.getSectionName() << "\n");
     615             : 
     616         166 :   DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
     617             : 
     618         310 :   for (const MCFragment &Frag : DataSection) {
     619         227 :     if (Frag.hasInstructions())
     620           0 :       report_fatal_error("only data supported in data sections");
     621             : 
     622             :     if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
     623          68 :       if (Align->getValueSize() != 1)
     624           0 :         report_fatal_error("only byte values supported for alignment");
     625             :       // If nops are requested, use zeros, as this is the data section.
     626          68 :       uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
     627             :       uint64_t Size =
     628          68 :           std::min<uint64_t>(alignTo(DataBytes.size(), Align->getAlignment()),
     629         136 :                              DataBytes.size() + Align->getMaxBytesToEmit());
     630          68 :       DataBytes.resize(Size, Value);
     631             :     } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
     632             :       int64_t NumValues;
     633           6 :       if (!Fill->getNumValues().evaluateAsAbsolute(NumValues))
     634           0 :         llvm_unreachable("The fill should be an assembler constant");
     635           6 :       DataBytes.insert(DataBytes.end(), Fill->getValueSize() * NumValues,
     636           6 :                        Fill->getValue());
     637             :     } else {
     638             :       const auto &DataFrag = cast<MCDataFragment>(Frag);
     639             :       const SmallVectorImpl<char> &Contents = DataFrag.getContents();
     640             : 
     641         153 :       DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
     642             :     }
     643             :   }
     644             : 
     645             :   LLVM_DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
     646          83 : }
     647             : 
     648             : uint32_t
     649         420 : WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
     650         420 :   if (RelEntry.Type == wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB) {
     651          22 :     if (!TypeIndices.count(RelEntry.Symbol))
     652           0 :       report_fatal_error("symbol not found in type index space: " +
     653           0 :                          RelEntry.Symbol->getName());
     654          22 :     return TypeIndices[RelEntry.Symbol];
     655             :   }
     656             : 
     657         398 :   return RelEntry.Symbol->getIndex();
     658             : }
     659             : 
     660             : // Apply the portions of the relocation records that we can handle ourselves
     661             : // directly.
     662         198 : void WasmObjectWriter::applyRelocations(
     663             :     ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
     664         198 :   auto &Stream = static_cast<raw_pwrite_stream &>(W.OS);
     665         607 :   for (const WasmRelocationEntry &RelEntry : Relocations) {
     666         409 :     uint64_t Offset = ContentsOffset +
     667         409 :                       RelEntry.FixupSection->getSectionOffset() +
     668         409 :                       RelEntry.Offset;
     669             : 
     670             :     LLVM_DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
     671         409 :     uint32_t Value = getProvisionalValue(RelEntry);
     672             : 
     673         409 :     switch (RelEntry.Type) {
     674         260 :     case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
     675             :     case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
     676             :     case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
     677             :     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
     678         260 :       WritePatchableLEB(Stream, Value, Offset);
     679         260 :       break;
     680             :     case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
     681             :     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
     682             :     case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32:
     683             :     case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32:
     684             :       WriteI32(Stream, Value, Offset);
     685             :       break;
     686          49 :     case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
     687             :     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
     688          49 :       WritePatchableSLEB(Stream, Value, Offset);
     689          49 :       break;
     690           0 :     default:
     691           0 :       llvm_unreachable("invalid relocation type");
     692             :     }
     693             :   }
     694         198 : }
     695             : 
     696         147 : void WasmObjectWriter::writeTypeSection(
     697             :     ArrayRef<WasmFunctionType> FunctionTypes) {
     698         147 :   if (FunctionTypes.empty())
     699          23 :     return;
     700             : 
     701             :   SectionBookkeeping Section;
     702         124 :   startSection(Section, wasm::WASM_SEC_TYPE);
     703             : 
     704         124 :   encodeULEB128(FunctionTypes.size(), W.OS);
     705             : 
     706         306 :   for (const WasmFunctionType &FuncTy : FunctionTypes) {
     707         182 :     W.OS << char(wasm::WASM_TYPE_FUNC);
     708         364 :     encodeULEB128(FuncTy.Params.size(), W.OS);
     709         237 :     for (wasm::ValType Ty : FuncTy.Params)
     710          55 :       writeValueType(Ty);
     711         364 :     encodeULEB128(FuncTy.Returns.size(), W.OS);
     712         269 :     for (wasm::ValType Ty : FuncTy.Returns)
     713          87 :       writeValueType(Ty);
     714             :   }
     715             : 
     716         124 :   endSection(Section);
     717             : }
     718             : 
     719         147 : void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports,
     720             :                                           uint32_t DataSize,
     721             :                                           uint32_t NumElements) {
     722         147 :   if (Imports.empty())
     723           0 :     return;
     724             : 
     725         147 :   uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
     726             : 
     727             :   SectionBookkeeping Section;
     728         147 :   startSection(Section, wasm::WASM_SEC_IMPORT);
     729             : 
     730         147 :   encodeULEB128(Imports.size(), W.OS);
     731         514 :   for (const wasm::WasmImport &Import : Imports) {
     732         367 :     writeString(Import.Module);
     733         367 :     writeString(Import.Field);
     734         367 :     W.OS << char(Import.Kind);
     735             : 
     736         367 :     switch (Import.Kind) {
     737          66 :     case wasm::WASM_EXTERNAL_FUNCTION:
     738          66 :       encodeULEB128(Import.SigIndex, W.OS);
     739          66 :       break;
     740           7 :     case wasm::WASM_EXTERNAL_GLOBAL:
     741           7 :       W.OS << char(Import.Global.Type);
     742           7 :       W.OS << char(Import.Global.Mutable ? 1 : 0);
     743             :       break;
     744         147 :     case wasm::WASM_EXTERNAL_MEMORY:
     745         147 :       encodeULEB128(0, W.OS);        // flags
     746         147 :       encodeULEB128(NumPages, W.OS); // initial
     747         147 :       break;
     748         147 :     case wasm::WASM_EXTERNAL_TABLE:
     749         147 :       W.OS << char(Import.Table.ElemType);
     750         147 :       encodeULEB128(0, W.OS);           // flags
     751         147 :       encodeULEB128(NumElements, W.OS); // initial
     752         147 :       break;
     753           0 :     default:
     754           0 :       llvm_unreachable("unsupported import kind");
     755             :     }
     756             :   }
     757             : 
     758         147 :   endSection(Section);
     759             : }
     760             : 
     761         147 : void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
     762         147 :   if (Functions.empty())
     763          24 :     return;
     764             : 
     765             :   SectionBookkeeping Section;
     766         123 :   startSection(Section, wasm::WASM_SEC_FUNCTION);
     767             : 
     768         123 :   encodeULEB128(Functions.size(), W.OS);
     769         464 :   for (const WasmFunction &Func : Functions)
     770         341 :     encodeULEB128(Func.Type, W.OS);
     771             : 
     772         123 :   endSection(Section);
     773             : }
     774             : 
     775         147 : void WasmObjectWriter::writeGlobalSection() {
     776         147 :   if (Globals.empty())
     777         147 :     return;
     778             : 
     779             :   SectionBookkeeping Section;
     780           0 :   startSection(Section, wasm::WASM_SEC_GLOBAL);
     781             : 
     782           0 :   encodeULEB128(Globals.size(), W.OS);
     783           0 :   for (const WasmGlobal &Global : Globals) {
     784           0 :     writeValueType(static_cast<wasm::ValType>(Global.Type.Type));
     785           0 :     W.OS << char(Global.Type.Mutable);
     786             : 
     787           0 :     W.OS << char(wasm::WASM_OPCODE_I32_CONST);
     788           0 :     encodeSLEB128(Global.InitialValue, W.OS);
     789           0 :     W.OS << char(wasm::WASM_OPCODE_END);
     790             :   }
     791             : 
     792           0 :   endSection(Section);
     793             : }
     794             : 
     795         147 : void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) {
     796         147 :   if (Exports.empty())
     797         147 :     return;
     798             : 
     799             :   SectionBookkeeping Section;
     800           0 :   startSection(Section, wasm::WASM_SEC_EXPORT);
     801             : 
     802           0 :   encodeULEB128(Exports.size(), W.OS);
     803           0 :   for (const wasm::WasmExport &Export : Exports) {
     804           0 :     writeString(Export.Name);
     805           0 :     W.OS << char(Export.Kind);
     806           0 :     encodeULEB128(Export.Index, W.OS);
     807             :   }
     808             : 
     809           0 :   endSection(Section);
     810             : }
     811             : 
     812         147 : void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
     813         147 :   if (TableElems.empty())
     814         123 :     return;
     815             : 
     816             :   SectionBookkeeping Section;
     817          24 :   startSection(Section, wasm::WASM_SEC_ELEM);
     818             : 
     819          24 :   encodeULEB128(1, W.OS); // number of "segments"
     820          24 :   encodeULEB128(0, W.OS); // the table index
     821             : 
     822             :   // init expr for starting offset
     823          24 :   W.OS << char(wasm::WASM_OPCODE_I32_CONST);
     824          24 :   encodeSLEB128(kInitialTableOffset, W.OS);
     825          24 :   W.OS << char(wasm::WASM_OPCODE_END);
     826             : 
     827          24 :   encodeULEB128(TableElems.size(), W.OS);
     828          63 :   for (uint32_t Elem : TableElems)
     829          39 :     encodeULEB128(Elem, W.OS);
     830             : 
     831          24 :   endSection(Section);
     832             : }
     833             : 
     834         147 : void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
     835             :                                         const MCAsmLayout &Layout,
     836             :                                         ArrayRef<WasmFunction> Functions) {
     837         147 :   if (Functions.empty())
     838          24 :     return;
     839             : 
     840             :   SectionBookkeeping Section;
     841         123 :   startSection(Section, wasm::WASM_SEC_CODE);
     842         123 :   CodeSectionIndex = Section.Index;
     843             : 
     844         123 :   encodeULEB128(Functions.size(), W.OS);
     845             : 
     846         464 :   for (const WasmFunction &Func : Functions) {
     847         341 :     auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
     848             : 
     849         341 :     int64_t Size = 0;
     850         341 :     if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
     851           0 :       report_fatal_error(".size expression must be evaluatable");
     852             : 
     853         341 :     encodeULEB128(Size, W.OS);
     854         341 :     FuncSection.setSectionOffset(W.OS.tell() - Section.ContentsOffset);
     855         341 :     Asm.writeSectionData(W.OS, &FuncSection, Layout);
     856             :   }
     857             : 
     858             :   // Apply fixups.
     859         246 :   applyRelocations(CodeRelocations, Section.ContentsOffset);
     860             : 
     861         123 :   endSection(Section);
     862             : }
     863             : 
     864         147 : void WasmObjectWriter::writeDataSection() {
     865         147 :   if (DataSegments.empty())
     866         106 :     return;
     867             : 
     868             :   SectionBookkeeping Section;
     869          41 :   startSection(Section, wasm::WASM_SEC_DATA);
     870          41 :   DataSectionIndex = Section.Index;
     871             : 
     872          82 :   encodeULEB128(DataSegments.size(), W.OS); // count
     873             : 
     874         124 :   for (const WasmDataSegment &Segment : DataSegments) {
     875          83 :     encodeULEB128(0, W.OS); // memory index
     876          83 :     W.OS << char(wasm::WASM_OPCODE_I32_CONST);
     877          83 :     encodeSLEB128(Segment.Offset, W.OS); // offset
     878          83 :     W.OS << char(wasm::WASM_OPCODE_END);
     879         166 :     encodeULEB128(Segment.Data.size(), W.OS); // size
     880          83 :     Segment.Section->setSectionOffset(W.OS.tell() - Section.ContentsOffset);
     881          83 :     W.OS << Segment.Data; // data
     882             :   }
     883             : 
     884             :   // Apply fixups.
     885          82 :   applyRelocations(DataRelocations, Section.ContentsOffset);
     886             : 
     887          41 :   endSection(Section);
     888             : }
     889             : 
     890         328 : void WasmObjectWriter::writeRelocSection(
     891             :     uint32_t SectionIndex, StringRef Name,
     892             :     std::vector<WasmRelocationEntry> &Relocs) {
     893             :   // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
     894             :   // for descriptions of the reloc sections.
     895             : 
     896         328 :   if (Relocs.empty())
     897         234 :     return;
     898             : 
     899             :   // First, ensure the relocations are sorted in offset order.  In general they
     900             :   // should already be sorted since `recordRelocation` is called in offset
     901             :   // order, but for the code section we combine many MC sections into single
     902             :   // wasm section, and this order is determined by the order of Asm.Symbols()
     903             :   // not the sections order.
     904          94 :   std::stable_sort(
     905             :       Relocs.begin(), Relocs.end(),
     906             :       [](const WasmRelocationEntry &A, const WasmRelocationEntry &B) {
     907           0 :         return (A.Offset + A.FixupSection->getSectionOffset()) <
     908           0 :                (B.Offset + B.FixupSection->getSectionOffset());
     909             :       });
     910             : 
     911             :   SectionBookkeeping Section;
     912         205 :   startCustomSection(Section, std::string("reloc.") + Name.str());
     913             : 
     914          94 :   encodeULEB128(SectionIndex, W.OS);
     915         188 :   encodeULEB128(Relocs.size(), W.OS);
     916         503 :   for (const WasmRelocationEntry &RelEntry : Relocs) {
     917             :     uint64_t Offset =
     918         409 :         RelEntry.Offset + RelEntry.FixupSection->getSectionOffset();
     919         409 :     uint32_t Index = getRelocationIndexValue(RelEntry);
     920             : 
     921         409 :     W.OS << char(RelEntry.Type);
     922         409 :     encodeULEB128(Offset, W.OS);
     923         409 :     encodeULEB128(Index, W.OS);
     924         409 :     if (RelEntry.hasAddend())
     925         250 :       encodeSLEB128(RelEntry.Addend, W.OS);
     926             :   }
     927             : 
     928          94 :   endSection(Section);
     929             : }
     930             : 
     931         147 : void WasmObjectWriter::writeCustomRelocSections() {
     932         181 :   for (const auto &Sec : CustomSections) {
     933          34 :     auto &Relocations = CustomSectionsRelocations[Sec.Section];
     934          34 :     writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations);
     935             :   }
     936         147 : }
     937             : 
     938         147 : void WasmObjectWriter::writeLinkingMetaDataSection(
     939             :     ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
     940             :     ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
     941             :     const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) {
     942             :   SectionBookkeeping Section;
     943         147 :   startCustomSection(Section, "linking");
     944         147 :   encodeULEB128(wasm::WasmMetadataVersion, W.OS);
     945             : 
     946             :   SectionBookkeeping SubSection;
     947         147 :   if (SymbolInfos.size() != 0) {
     948         136 :     startSection(SubSection, wasm::WASM_SYMBOL_TABLE);
     949         136 :     encodeULEB128(SymbolInfos.size(), W.OS);
     950         670 :     for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) {
     951         534 :       encodeULEB128(Sym.Kind, W.OS);
     952         534 :       encodeULEB128(Sym.Flags, W.OS);
     953         534 :       switch (Sym.Kind) {
     954         418 :       case wasm::WASM_SYMBOL_TYPE_FUNCTION:
     955             :       case wasm::WASM_SYMBOL_TYPE_GLOBAL:
     956         418 :         encodeULEB128(Sym.ElementIndex, W.OS);
     957         418 :         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0)
     958         345 :           writeString(Sym.Name);
     959             :         break;
     960          99 :       case wasm::WASM_SYMBOL_TYPE_DATA:
     961          99 :         writeString(Sym.Name);
     962          99 :         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) {
     963          85 :           encodeULEB128(Sym.DataRef.Segment, W.OS);
     964          85 :           encodeULEB128(Sym.DataRef.Offset, W.OS);
     965          85 :           encodeULEB128(Sym.DataRef.Size, W.OS);
     966             :         }
     967             :         break;
     968          17 :       case wasm::WASM_SYMBOL_TYPE_SECTION: {
     969             :         const uint32_t SectionIndex =
     970          17 :             CustomSections[Sym.ElementIndex].OutputIndex;
     971          17 :         encodeULEB128(SectionIndex, W.OS);
     972          17 :         break;
     973             :       }
     974           0 :       default:
     975           0 :         llvm_unreachable("unexpected kind");
     976             :       }
     977             :     }
     978         136 :     endSection(SubSection);
     979             :   }
     980             : 
     981         147 :   if (DataSegments.size()) {
     982          41 :     startSection(SubSection, wasm::WASM_SEGMENT_INFO);
     983          82 :     encodeULEB128(DataSegments.size(), W.OS);
     984         124 :     for (const WasmDataSegment &Segment : DataSegments) {
     985          83 :       writeString(Segment.Name);
     986          83 :       encodeULEB128(Segment.Alignment, W.OS);
     987          83 :       encodeULEB128(Segment.Flags, W.OS);
     988             :     }
     989          41 :     endSection(SubSection);
     990             :   }
     991             : 
     992         147 :   if (!InitFuncs.empty()) {
     993           3 :     startSection(SubSection, wasm::WASM_INIT_FUNCS);
     994           3 :     encodeULEB128(InitFuncs.size(), W.OS);
     995          20 :     for (auto &StartFunc : InitFuncs) {
     996          17 :       encodeULEB128(StartFunc.first, W.OS);  // priority
     997          17 :       encodeULEB128(StartFunc.second, W.OS); // function index
     998             :     }
     999           3 :     endSection(SubSection);
    1000             :   }
    1001             : 
    1002         147 :   if (Comdats.size()) {
    1003           4 :     startSection(SubSection, wasm::WASM_COMDAT_INFO);
    1004           8 :     encodeULEB128(Comdats.size(), W.OS);
    1005           9 :     for (const auto &C : Comdats) {
    1006           5 :       writeString(C.first);
    1007           5 :       encodeULEB128(0, W.OS); // flags for future use
    1008          10 :       encodeULEB128(C.second.size(), W.OS);
    1009          14 :       for (const WasmComdatEntry &Entry : C.second) {
    1010           9 :         encodeULEB128(Entry.Kind, W.OS);
    1011           9 :         encodeULEB128(Entry.Index, W.OS);
    1012             :       }
    1013             :     }
    1014           4 :     endSection(SubSection);
    1015             :   }
    1016             : 
    1017         147 :   endSection(Section);
    1018         147 : }
    1019             : 
    1020         147 : void WasmObjectWriter::writeCustomSections(const MCAssembler &Asm,
    1021             :                                            const MCAsmLayout &Layout) {
    1022         181 :   for (auto &CustomSection : CustomSections) {
    1023             :     SectionBookkeeping Section;
    1024          34 :     auto *Sec = CustomSection.Section;
    1025          34 :     startCustomSection(Section, CustomSection.Name);
    1026             : 
    1027          34 :     Sec->setSectionOffset(W.OS.tell() - Section.ContentsOffset);
    1028          34 :     Asm.writeSectionData(W.OS, Sec, Layout);
    1029             : 
    1030          34 :     CustomSection.OutputContentsOffset = Section.ContentsOffset;
    1031          34 :     CustomSection.OutputIndex = Section.Index;
    1032             : 
    1033          34 :     endSection(Section);
    1034             : 
    1035             :     // Apply fixups.
    1036          34 :     auto &Relocations = CustomSectionsRelocations[CustomSection.Section];
    1037          68 :     applyRelocations(Relocations, CustomSection.OutputContentsOffset);
    1038             :   }
    1039         147 : }
    1040             : 
    1041             : uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm &Symbol) {
    1042             :   assert(Symbol.isFunction());
    1043             :   assert(TypeIndices.count(&Symbol));
    1044         814 :   return TypeIndices[&Symbol];
    1045             : }
    1046             : 
    1047         461 : uint32_t WasmObjectWriter::registerFunctionType(const MCSymbolWasm &Symbol) {
    1048             :   assert(Symbol.isFunction());
    1049             : 
    1050         461 :   WasmFunctionType F;
    1051             :   const MCSymbolWasm *ResolvedSym = ResolveSymbol(Symbol);
    1052             :   F.Returns = ResolvedSym->getReturns();
    1053             :   F.Params = ResolvedSym->getParams();
    1054             : 
    1055             :   auto Pair =
    1056         922 :       FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size()));
    1057         461 :   if (Pair.second)
    1058         182 :     FunctionTypes.push_back(F);
    1059         461 :   TypeIndices[&Symbol] = Pair.first->second;
    1060             : 
    1061             :   LLVM_DEBUG(dbgs() << "registerFunctionType: " << Symbol
    1062             :                     << " new:" << Pair.second << "\n");
    1063             :   LLVM_DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
    1064         461 :   return Pair.first->second;
    1065             : }
    1066             : 
    1067        1586 : static bool isInSymtab(const MCSymbolWasm &Sym) {
    1068        1586 :   if (Sym.isUsedInReloc())
    1069             :     return true;
    1070             : 
    1071        1399 :   if (Sym.isComdat() && !Sym.isDefined())
    1072             :     return false;
    1073             : 
    1074        1863 :   if (Sym.isTemporary() && Sym.getName().empty())
    1075         442 :     return false;
    1076             : 
    1077         956 :   if (Sym.isTemporary() && Sym.isData() && !Sym.getSize())
    1078             :     return false;
    1079             : 
    1080         943 :   if (Sym.isSection())
    1081         596 :     return false;
    1082             : 
    1083             :   return true;
    1084             : }
    1085             : 
    1086         147 : uint64_t WasmObjectWriter::writeObject(MCAssembler &Asm,
    1087             :                                        const MCAsmLayout &Layout) {
    1088         147 :   uint64_t StartOffset = W.OS.tell();
    1089             : 
    1090             :   LLVM_DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
    1091         147 :   MCContext &Ctx = Asm.getContext();
    1092             : 
    1093             :   // Collect information from the available symbols.
    1094         147 :   SmallVector<WasmFunction, 4> Functions;
    1095             :   SmallVector<uint32_t, 4> TableElems;
    1096             :   SmallVector<wasm::WasmImport, 4> Imports;
    1097             :   SmallVector<wasm::WasmExport, 4> Exports;
    1098             :   SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos;
    1099             :   SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
    1100             :   std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
    1101             :   uint32_t DataSize = 0;
    1102             : 
    1103             :   // For now, always emit the memory import, since loads and stores are not
    1104             :   // valid without it. In the future, we could perhaps be more clever and omit
    1105             :   // it if there are no loads or stores.
    1106             :   MCSymbolWasm *MemorySym =
    1107         147 :       cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__linear_memory"));
    1108             :   wasm::WasmImport MemImport;
    1109         147 :   MemImport.Module = MemorySym->getModuleName();
    1110         147 :   MemImport.Field = MemorySym->getName();
    1111         147 :   MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
    1112         147 :   Imports.push_back(MemImport);
    1113             : 
    1114             :   // For now, always emit the table section, since indirect calls are not
    1115             :   // valid without it. In the future, we could perhaps be more clever and omit
    1116             :   // it if there are no indirect calls.
    1117             :   MCSymbolWasm *TableSym =
    1118         147 :       cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__indirect_function_table"));
    1119             :   wasm::WasmImport TableImport;
    1120         147 :   TableImport.Module = TableSym->getModuleName();
    1121         147 :   TableImport.Field = TableSym->getName();
    1122         147 :   TableImport.Kind = wasm::WASM_EXTERNAL_TABLE;
    1123         147 :   TableImport.Table.ElemType = wasm::WASM_TYPE_ANYFUNC;
    1124         147 :   Imports.push_back(TableImport);
    1125             : 
    1126             :   // Populate FunctionTypeIndices, and Imports and WasmIndices for undefined
    1127             :   // symbols.  This must be done before populating WasmIndices for defined
    1128             :   // symbols.
    1129        1733 :   for (const MCSymbol &S : Asm.symbols()) {
    1130             :     const auto &WS = static_cast<const MCSymbolWasm &>(S);
    1131             : 
    1132             :     // Register types for all functions, including those with private linkage
    1133             :     // (because wasm always needs a type signature).
    1134        1586 :     if (WS.isFunction())
    1135         422 :       registerFunctionType(WS);
    1136             : 
    1137        1586 :     if (WS.isTemporary())
    1138             :       continue;
    1139             : 
    1140             :     // If the symbol is not defined in this translation unit, import it.
    1141        1111 :     if (!WS.isDefined() && !WS.isComdat()) {
    1142          87 :       if (WS.isFunction()) {
    1143             :         wasm::WasmImport Import;
    1144          66 :         Import.Module = WS.getModuleName();
    1145          66 :         Import.Field = WS.getName();
    1146          66 :         Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
    1147          66 :         Import.SigIndex = getFunctionType(WS);
    1148          66 :         Imports.push_back(Import);
    1149          66 :         WasmIndices[&WS] = NumFunctionImports++;
    1150          21 :       } else if (WS.isGlobal()) {
    1151           7 :         if (WS.isWeak())
    1152           0 :           report_fatal_error("undefined global symbol cannot be weak");
    1153             : 
    1154             :         wasm::WasmImport Import;
    1155           7 :         Import.Module = WS.getModuleName();
    1156           7 :         Import.Field = WS.getName();
    1157           7 :         Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
    1158           7 :         Import.Global = WS.getGlobalType();
    1159           7 :         Imports.push_back(Import);
    1160           7 :         WasmIndices[&WS] = NumGlobalImports++;
    1161             :       }
    1162             :     }
    1163             :   }
    1164             : 
    1165             :   // Populate DataSegments and CustomSections, which must be done before
    1166             :   // populating DataLocations.
    1167         760 :   for (MCSection &Sec : Asm) {
    1168             :     auto &Section = static_cast<MCSectionWasm &>(Sec);
    1169         613 :     StringRef SectionName = Section.getSectionName();
    1170             : 
    1171             :     // .init_array sections are handled specially elsewhere.
    1172             :     if (SectionName.startswith(".init_array"))
    1173         496 :       continue;
    1174             : 
    1175             :     // Code is handled separately
    1176         605 :     if (Section.getKind().isText())
    1177             :       continue;
    1178             : 
    1179         117 :     if (Section.isWasmData()) {
    1180          83 :       uint32_t SegmentIndex = DataSegments.size();
    1181          83 :       DataSize = alignTo(DataSize, Section.getAlignment());
    1182          83 :       DataSegments.emplace_back();
    1183             :       WasmDataSegment &Segment = DataSegments.back();
    1184          83 :       Segment.Name = SectionName;
    1185          83 :       Segment.Offset = DataSize;
    1186          83 :       Segment.Section = &Section;
    1187          83 :       addData(Segment.Data, Section);
    1188          83 :       Segment.Alignment = Section.getAlignment();
    1189          83 :       Segment.Flags = 0;
    1190          83 :       DataSize += Segment.Data.size();
    1191             :       Section.setSegmentIndex(SegmentIndex);
    1192             : 
    1193          83 :       if (const MCSymbolWasm *C = Section.getGroup()) {
    1194           4 :         Comdats[C->getName()].emplace_back(
    1195           4 :             WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
    1196             :       }
    1197             :     } else {
    1198             :       // Create custom sections
    1199             :       assert(Sec.getKind().isMetadata());
    1200             : 
    1201          34 :       StringRef Name = SectionName;
    1202             : 
    1203             :       // For user-defined custom sections, strip the prefix
    1204             :       if (Name.startswith(".custom_section."))
    1205           5 :         Name = Name.substr(strlen(".custom_section."));
    1206             : 
    1207          34 :       MCSymbol *Begin = Sec.getBeginSymbol();
    1208          34 :       if (Begin) {
    1209          68 :         WasmIndices[cast<MCSymbolWasm>(Begin)] = CustomSections.size();
    1210             :         if (SectionName != Begin->getName())
    1211           0 :           report_fatal_error("section name and begin symbol should match: " +
    1212             :                              Twine(SectionName));
    1213             :       }
    1214          34 :       CustomSections.emplace_back(Name, &Section);
    1215             :     }
    1216             :   }
    1217             : 
    1218             :   // Populate WasmIndices and DataLocations for defined symbols.
    1219        1733 :   for (const MCSymbol &S : Asm.symbols()) {
    1220             :     // Ignore unnamed temporary symbols, which aren't ever exported, imported,
    1221             :     // or used in relocations.
    1222        2061 :     if (S.isTemporary() && S.getName().empty())
    1223             :       continue;
    1224             : 
    1225             :     const auto &WS = static_cast<const MCSymbolWasm &>(S);
    1226             :     LLVM_DEBUG(
    1227             :         dbgs() << "MCSymbol: " << toString(WS.getType()) << " '" << S << "'"
    1228             :                << " isDefined=" << S.isDefined() << " isExternal="
    1229             :                << S.isExternal() << " isTemporary=" << S.isTemporary()
    1230             :                << " isWeak=" << WS.isWeak() << " isHidden=" << WS.isHidden()
    1231             :                << " isVariable=" << WS.isVariable() << "\n");
    1232             : 
    1233        1144 :     if (WS.isVariable())
    1234             :       continue;
    1235        1139 :     if (WS.isComdat() && !WS.isDefined())
    1236             :       continue;
    1237             : 
    1238        1138 :     if (WS.isFunction()) {
    1239             :       unsigned Index;
    1240         407 :       if (WS.isDefined()) {
    1241         341 :         if (WS.getOffset() != 0)
    1242           0 :           report_fatal_error(
    1243             :               "function sections must contain one function each");
    1244             : 
    1245         341 :         if (WS.getSize() == 0)
    1246           0 :           report_fatal_error(
    1247             :               "function symbols must have a size set with .size");
    1248             : 
    1249             :         // A definition. Write out the function body.
    1250         341 :         Index = NumFunctionImports + Functions.size();
    1251             :         WasmFunction Func;
    1252         341 :         Func.Type = getFunctionType(WS);
    1253         341 :         Func.Sym = &WS;
    1254         341 :         WasmIndices[&WS] = Index;
    1255         341 :         Functions.push_back(Func);
    1256             : 
    1257             :         auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
    1258         341 :         if (const MCSymbolWasm *C = Section.getGroup()) {
    1259           5 :           Comdats[C->getName()].emplace_back(
    1260           5 :               WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
    1261             :         }
    1262             :       } else {
    1263             :         // An import; the index was assigned above.
    1264          66 :         Index = WasmIndices.find(&WS)->second;
    1265             :       }
    1266             : 
    1267             :       LLVM_DEBUG(dbgs() << "  -> function index: " << Index << "\n");
    1268         731 :     } else if (WS.isData()) {
    1269         111 :       if (WS.isTemporary() && !WS.getSize())
    1270          27 :         continue;
    1271             : 
    1272          98 :       if (!WS.isDefined()) {
    1273             :         LLVM_DEBUG(dbgs() << "  -> segment index: -1"
    1274             :                           << "\n");
    1275             :         continue;
    1276             :       }
    1277             : 
    1278          84 :       if (!WS.getSize())
    1279           0 :         report_fatal_error("data symbols must have a size set with .size: " +
    1280           0 :                            WS.getName());
    1281             : 
    1282          84 :       int64_t Size = 0;
    1283          84 :       if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
    1284           0 :         report_fatal_error(".size expression must be evaluatable");
    1285             : 
    1286             :       auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
    1287             :       assert(DataSection.isWasmData());
    1288             : 
    1289             :       // For each data symbol, export it in the symtab as a reference to the
    1290             :       // corresponding Wasm data segment.
    1291             :       wasm::WasmDataReference Ref = wasm::WasmDataReference{
    1292          84 :           DataSection.getSegmentIndex(),
    1293          84 :           static_cast<uint32_t>(Layout.getSymbolOffset(WS)),
    1294          84 :           static_cast<uint32_t>(Size)};
    1295          84 :       DataLocations[&WS] = Ref;
    1296             :       LLVM_DEBUG(dbgs() << "  -> segment index: " << Ref.Segment << "\n");
    1297         620 :     } else if (WS.isGlobal()) {
    1298             :       // A "true" Wasm global (currently just __stack_pointer)
    1299           7 :       if (WS.isDefined())
    1300           0 :         report_fatal_error("don't yet support defined globals");
    1301             : 
    1302             :       // An import; the index was assigned above
    1303             :       LLVM_DEBUG(dbgs() << "  -> global index: "
    1304             :                         << WasmIndices.find(&WS)->second << "\n");
    1305             :     } else {
    1306             :       assert(WS.isSection());
    1307             :     }
    1308             :   }
    1309             : 
    1310             :   // Populate WasmIndices and DataLocations for aliased symbols.  We need to
    1311             :   // process these in a separate pass because we need to have processed the
    1312             :   // target of the alias before the alias itself and the symbols are not
    1313             :   // necessarily ordered in this way.
    1314        1733 :   for (const MCSymbol &S : Asm.symbols()) {
    1315        1586 :     if (!S.isVariable())
    1316             :       continue;
    1317             : 
    1318             :     assert(S.isDefined());
    1319             : 
    1320             :     // Find the target symbol of this weak alias and export that index
    1321             :     const auto &WS = static_cast<const MCSymbolWasm &>(S);
    1322             :     const MCSymbolWasm *ResolvedSym = ResolveSymbol(WS);
    1323             :     LLVM_DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym
    1324             :                       << "'\n");
    1325             : 
    1326           5 :     if (WS.isFunction()) {
    1327             :       assert(WasmIndices.count(ResolvedSym) > 0);
    1328           4 :       uint32_t WasmIndex = WasmIndices.find(ResolvedSym)->second;
    1329           4 :       WasmIndices[&WS] = WasmIndex;
    1330             :       LLVM_DEBUG(dbgs() << "  -> index:" << WasmIndex << "\n");
    1331           1 :     } else if (WS.isData()) {
    1332             :       assert(DataLocations.count(ResolvedSym) > 0);
    1333             :       const wasm::WasmDataReference &Ref =
    1334           1 :           DataLocations.find(ResolvedSym)->second;
    1335           1 :       DataLocations[&WS] = Ref;
    1336             :       LLVM_DEBUG(dbgs() << "  -> index:" << Ref.Segment << "\n");
    1337             :     } else {
    1338           0 :       report_fatal_error("don't yet support global aliases");
    1339             :     }
    1340             :   }
    1341             : 
    1342             :   // Finally, populate the symbol table itself, in its "natural" order.
    1343        1733 :   for (const MCSymbol &S : Asm.symbols()) {
    1344             :     const auto &WS = static_cast<const MCSymbolWasm &>(S);
    1345        1586 :     if (!isInSymtab(WS)) {
    1346             :       WS.setIndex(INVALID_INDEX);
    1347        1052 :       continue;
    1348             :     }
    1349             :     LLVM_DEBUG(dbgs() << "adding to symtab: " << WS << "\n");
    1350             : 
    1351             :     uint32_t Flags = 0;
    1352         534 :     if (WS.isWeak())
    1353             :       Flags |= wasm::WASM_SYMBOL_BINDING_WEAK;
    1354         534 :     if (WS.isHidden())
    1355         101 :       Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN;
    1356         534 :     if (!WS.isExternal() && WS.isDefined())
    1357          54 :       Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;
    1358         534 :     if (WS.isUndefined())
    1359          87 :       Flags |= wasm::WASM_SYMBOL_UNDEFINED;
    1360             : 
    1361             :     wasm::WasmSymbolInfo Info;
    1362         534 :     Info.Name = WS.getName();
    1363         534 :     Info.Kind = WS.getType();
    1364         534 :     Info.Flags = Flags;
    1365         534 :     if (!WS.isData()) {
    1366             :       assert(WasmIndices.count(&WS) > 0);
    1367         435 :       Info.ElementIndex = WasmIndices.find(&WS)->second;
    1368          99 :     } else if (WS.isDefined()) {
    1369             :       assert(DataLocations.count(&WS) > 0);
    1370          85 :       Info.DataRef = DataLocations.find(&WS)->second;
    1371             :     }
    1372         534 :     WS.setIndex(SymbolInfos.size());
    1373         534 :     SymbolInfos.emplace_back(Info);
    1374             :   }
    1375             : 
    1376             :   {
    1377             :     auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
    1378             :       // Functions referenced by a relocation need to put in the table.  This is
    1379             :       // purely to make the object file's provisional values readable, and is
    1380             :       // ignored by the linker, which re-calculates the relocations itself.
    1381             :       if (Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_I32 &&
    1382             :           Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB)
    1383             :         return;
    1384             :       assert(Rel.Symbol->isFunction());
    1385             :       const MCSymbolWasm &WS = *ResolveSymbol(*Rel.Symbol);
    1386             :       uint32_t FunctionIndex = WasmIndices.find(&WS)->second;
    1387             :       uint32_t TableIndex = TableElems.size() + kInitialTableOffset;
    1388             :       if (TableIndices.try_emplace(&WS, TableIndex).second) {
    1389             :         LLVM_DEBUG(dbgs() << "  -> adding " << WS.getName()
    1390             :                           << " to table: " << TableIndex << "\n");
    1391             :         TableElems.push_back(FunctionIndex);
    1392             :         registerFunctionType(WS);
    1393             :       }
    1394         147 :     };
    1395             : 
    1396         456 :     for (const WasmRelocationEntry &RelEntry : CodeRelocations)
    1397         309 :       HandleReloc(RelEntry);
    1398         177 :     for (const WasmRelocationEntry &RelEntry : DataRelocations)
    1399          30 :       HandleReloc(RelEntry);
    1400             :   }
    1401             : 
    1402             :   // Translate .init_array section contents into start functions.
    1403         760 :   for (const MCSection &S : Asm) {
    1404             :     const auto &WS = static_cast<const MCSectionWasm &>(S);
    1405             :     if (WS.getSectionName().startswith(".fini_array"))
    1406           0 :       report_fatal_error(".fini_array sections are unsupported");
    1407             :     if (!WS.getSectionName().startswith(".init_array"))
    1408             :       continue;
    1409           8 :     if (WS.getFragmentList().empty())
    1410             :       continue;
    1411             : 
    1412             :     // init_array is expected to contain a single non-empty data fragment
    1413           8 :     if (WS.getFragmentList().size() != 3)
    1414           0 :       report_fatal_error("only one .init_array section fragment supported");
    1415             : 
    1416             :     auto IT = WS.begin();
    1417             :     const MCFragment &EmptyFrag = *IT;
    1418           8 :     if (EmptyFrag.getKind() != MCFragment::FT_Data)
    1419           0 :       report_fatal_error(".init_array section should be aligned");
    1420             : 
    1421             :     IT = std::next(IT);
    1422             :     const MCFragment &AlignFrag = *IT;
    1423           8 :     if (AlignFrag.getKind() != MCFragment::FT_Align)
    1424           0 :       report_fatal_error(".init_array section should be aligned");
    1425          24 :     if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
    1426           0 :       report_fatal_error(".init_array section should be aligned for pointers");
    1427             : 
    1428             :     const MCFragment &Frag = *std::next(IT);
    1429           8 :     if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
    1430           0 :       report_fatal_error("only data supported in .init_array section");
    1431             : 
    1432             :     uint16_t Priority = UINT16_MAX;
    1433             :     unsigned PrefixLength = strlen(".init_array");
    1434           8 :     if (WS.getSectionName().size() > PrefixLength) {
    1435           7 :       if (WS.getSectionName()[PrefixLength] != '.')
    1436           0 :         report_fatal_error(
    1437             :             ".init_array section priority should start with '.'");
    1438           7 :       if (WS.getSectionName()
    1439           7 :               .substr(PrefixLength + 1)
    1440           7 :               .getAsInteger(10, Priority))
    1441           0 :         report_fatal_error("invalid .init_array section priority");
    1442             :     }
    1443             :     const auto &DataFrag = cast<MCDataFragment>(Frag);
    1444             :     const SmallVectorImpl<char> &Contents = DataFrag.getContents();
    1445          68 :     for (const uint8_t *
    1446           8 :              p = (const uint8_t *)Contents.data(),
    1447          16 :             *end = (const uint8_t *)Contents.data() + Contents.size();
    1448          76 :          p != end; ++p) {
    1449          68 :       if (*p != 0)
    1450           0 :         report_fatal_error("non-symbolic data in .init_array section");
    1451             :     }
    1452          25 :     for (const MCFixup &Fixup : DataFrag.getFixups()) {
    1453             :       assert(Fixup.getKind() ==
    1454             :              MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
    1455          17 :       const MCExpr *Expr = Fixup.getValue();
    1456             :       auto *Sym = dyn_cast<MCSymbolRefExpr>(Expr);
    1457             :       if (!Sym)
    1458           0 :         report_fatal_error("fixups in .init_array should be symbol references");
    1459          17 :       if (Sym->getKind() != MCSymbolRefExpr::VK_WebAssembly_FUNCTION)
    1460           0 :         report_fatal_error("symbols in .init_array should be for functions");
    1461          17 :       if (Sym->getSymbol().getIndex() == INVALID_INDEX)
    1462           0 :         report_fatal_error("symbols in .init_array should exist in symbtab");
    1463          17 :       InitFuncs.push_back(
    1464          17 :           std::make_pair(Priority, Sym->getSymbol().getIndex()));
    1465             :     }
    1466             :   }
    1467             : 
    1468             :   // Write out the Wasm header.
    1469         147 :   writeHeader(Asm);
    1470             : 
    1471         147 :   writeTypeSection(FunctionTypes);
    1472         294 :   writeImportSection(Imports, DataSize, TableElems.size());
    1473         147 :   writeFunctionSection(Functions);
    1474             :   // Skip the "table" section; we import the table instead.
    1475             :   // Skip the "memory" section; we import the memory instead.
    1476         147 :   writeGlobalSection();
    1477         147 :   writeExportSection(Exports);
    1478         147 :   writeElemSection(TableElems);
    1479         147 :   writeCodeSection(Asm, Layout, Functions);
    1480         147 :   writeDataSection();
    1481         147 :   writeCustomSections(Asm, Layout);
    1482         147 :   writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats);
    1483         294 :   writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations);
    1484         294 :   writeRelocSection(DataSectionIndex, "DATA", DataRelocations);
    1485         147 :   writeCustomRelocSections();
    1486             : 
    1487             :   // TODO: Translate the .comment section to the output.
    1488         147 :   return W.OS.tell() - StartOffset;
    1489             : }
    1490             : 
    1491             : std::unique_ptr<MCObjectWriter>
    1492         295 : llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
    1493             :                              raw_pwrite_stream &OS) {
    1494         295 :   return llvm::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
    1495             : }

Generated by: LCOV version 1.13