118eafb6cSDan Gohman //===- lib/MC/WasmObjectWriter.cpp - Wasm File Writer ---------------------===//
218eafb6cSDan Gohman //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
618eafb6cSDan Gohman //
718eafb6cSDan Gohman //===----------------------------------------------------------------------===//
818eafb6cSDan Gohman //
918eafb6cSDan Gohman // This file implements Wasm object file writer information.
1018eafb6cSDan Gohman //
1118eafb6cSDan Gohman //===----------------------------------------------------------------------===//
1218eafb6cSDan Gohman 
1318eafb6cSDan Gohman #include "llvm/ADT/STLExtras.h"
1418eafb6cSDan Gohman #include "llvm/ADT/SmallPtrSet.h"
15264b5d9eSZachary Turner #include "llvm/BinaryFormat/Wasm.h"
16432a3883SNico Weber #include "llvm/Config/llvm-config.h"
1718eafb6cSDan Gohman #include "llvm/MC/MCAsmBackend.h"
1818eafb6cSDan Gohman #include "llvm/MC/MCAsmLayout.h"
1918eafb6cSDan Gohman #include "llvm/MC/MCAssembler.h"
2018eafb6cSDan Gohman #include "llvm/MC/MCContext.h"
2118eafb6cSDan Gohman #include "llvm/MC/MCExpr.h"
2218eafb6cSDan Gohman #include "llvm/MC/MCFixupKindInfo.h"
2318eafb6cSDan Gohman #include "llvm/MC/MCObjectWriter.h"
2418eafb6cSDan Gohman #include "llvm/MC/MCSectionWasm.h"
2518eafb6cSDan Gohman #include "llvm/MC/MCSymbolWasm.h"
2618eafb6cSDan Gohman #include "llvm/MC/MCValue.h"
2718eafb6cSDan Gohman #include "llvm/MC/MCWasmObjectWriter.h"
28d934cb88SDan Gohman #include "llvm/Support/Casting.h"
2918eafb6cSDan Gohman #include "llvm/Support/Debug.h"
3018eafb6cSDan Gohman #include "llvm/Support/ErrorHandling.h"
31d934cb88SDan Gohman #include "llvm/Support/LEB128.h"
3218eafb6cSDan Gohman #include "llvm/Support/StringSaver.h"
3318eafb6cSDan Gohman #include <vector>
3418eafb6cSDan Gohman 
3518eafb6cSDan Gohman using namespace llvm;
3618eafb6cSDan Gohman 
375e3d33a7SSam Clegg #define DEBUG_TYPE "mc"
3818eafb6cSDan Gohman 
3918eafb6cSDan Gohman namespace {
409e15f359SSam Clegg 
4130e1bbc1SSam Clegg // Went we ceate the indirect function table we start at 1, so that there is
4230e1bbc1SSam Clegg // and emtpy slot at 0 and therefore calling a null function pointer will trap.
4318c56a07SHeejin Ahn static const uint32_t InitialTableOffset = 1;
4430e1bbc1SSam Clegg 
45d934cb88SDan Gohman // For patching purposes, we need to remember where each section starts, both
46d934cb88SDan Gohman // for patching up the section size field, and for patching up references to
47d934cb88SDan Gohman // locations within the section.
48d934cb88SDan Gohman struct SectionBookkeeping {
49d934cb88SDan Gohman   // Where the size of the section is written.
50d934cb88SDan Gohman   uint64_t SizeOffset;
516a31a0d6SSam Clegg   // Where the section header ends (without custom section name).
526a31a0d6SSam Clegg   uint64_t PayloadOffset;
536a31a0d6SSam Clegg   // Where the contents of the section starts.
54d934cb88SDan Gohman   uint64_t ContentsOffset;
556f08c84aSSam Clegg   uint32_t Index;
56d934cb88SDan Gohman };
57d934cb88SDan Gohman 
58da419bdbSHeejin Ahn // The signature of a wasm function or event, in a struct capable of being used
59da419bdbSHeejin Ahn // as a DenseMap key.
60da419bdbSHeejin Ahn // TODO: Consider using wasm::WasmSignature directly instead.
61da419bdbSHeejin Ahn struct WasmSignature {
629e15f359SSam Clegg   // Support empty and tombstone instances, needed by DenseMap.
6318c56a07SHeejin Ahn   enum { Plain, Empty, Tombstone } State = Plain;
649e15f359SSam Clegg 
659e15f359SSam Clegg   // The return types of the function.
669e15f359SSam Clegg   SmallVector<wasm::ValType, 1> Returns;
679e15f359SSam Clegg 
689e15f359SSam Clegg   // The parameter types of the function.
699e15f359SSam Clegg   SmallVector<wasm::ValType, 4> Params;
709e15f359SSam Clegg 
71da419bdbSHeejin Ahn   bool operator==(const WasmSignature &Other) const {
729e15f359SSam Clegg     return State == Other.State && Returns == Other.Returns &&
739e15f359SSam Clegg            Params == Other.Params;
749e15f359SSam Clegg   }
759e15f359SSam Clegg };
769e15f359SSam Clegg 
77da419bdbSHeejin Ahn // Traits for using WasmSignature in a DenseMap.
78da419bdbSHeejin Ahn struct WasmSignatureDenseMapInfo {
79da419bdbSHeejin Ahn   static WasmSignature getEmptyKey() {
80da419bdbSHeejin Ahn     WasmSignature Sig;
81da419bdbSHeejin Ahn     Sig.State = WasmSignature::Empty;
82da419bdbSHeejin Ahn     return Sig;
839e15f359SSam Clegg   }
84da419bdbSHeejin Ahn   static WasmSignature getTombstoneKey() {
85da419bdbSHeejin Ahn     WasmSignature Sig;
86da419bdbSHeejin Ahn     Sig.State = WasmSignature::Tombstone;
87da419bdbSHeejin Ahn     return Sig;
889e15f359SSam Clegg   }
89da419bdbSHeejin Ahn   static unsigned getHashValue(const WasmSignature &Sig) {
90da419bdbSHeejin Ahn     uintptr_t Value = Sig.State;
91da419bdbSHeejin Ahn     for (wasm::ValType Ret : Sig.Returns)
924808914aSHeejin Ahn       Value += DenseMapInfo<uint32_t>::getHashValue(uint32_t(Ret));
93da419bdbSHeejin Ahn     for (wasm::ValType Param : Sig.Params)
944808914aSHeejin Ahn       Value += DenseMapInfo<uint32_t>::getHashValue(uint32_t(Param));
959e15f359SSam Clegg     return Value;
969e15f359SSam Clegg   }
97da419bdbSHeejin Ahn   static bool isEqual(const WasmSignature &LHS, const WasmSignature &RHS) {
989e15f359SSam Clegg     return LHS == RHS;
999e15f359SSam Clegg   }
1009e15f359SSam Clegg };
1019e15f359SSam Clegg 
1027c395943SSam Clegg // A wasm data segment.  A wasm binary contains only a single data section
1037c395943SSam Clegg // but that can contain many segments, each with their own virtual location
1047c395943SSam Clegg // in memory.  Each MCSection data created by llvm is modeled as its own
1057c395943SSam Clegg // wasm data segment.
1067c395943SSam Clegg struct WasmDataSegment {
1077c395943SSam Clegg   MCSectionWasm *Section;
108d95ed959SSam Clegg   StringRef Name;
1092e150409SThomas Lively   uint32_t InitFlags;
1107c395943SSam Clegg   uint32_t Offset;
11163ebb813SSam Clegg   uint32_t Alignment;
1122e150409SThomas Lively   uint32_t LinkerFlags;
1137c395943SSam Clegg   SmallVector<char, 4> Data;
1147c395943SSam Clegg };
1157c395943SSam Clegg 
1169e15f359SSam Clegg // A wasm function to be written into the function section.
1179e15f359SSam Clegg struct WasmFunction {
118da419bdbSHeejin Ahn   uint32_t SigIndex;
1199e15f359SSam Clegg   const MCSymbolWasm *Sym;
1209e15f359SSam Clegg };
1219e15f359SSam Clegg 
1229e15f359SSam Clegg // A wasm global to be written into the global section.
1239e15f359SSam Clegg struct WasmGlobal {
1246e7f1826SSam Clegg   wasm::WasmGlobalType Type;
1259e15f359SSam Clegg   uint64_t InitialValue;
1269e15f359SSam Clegg };
1279e15f359SSam Clegg 
128ea7caceeSSam Clegg // Information about a single item which is part of a COMDAT.  For each data
129ea7caceeSSam Clegg // segment or function which is in the COMDAT, there is a corresponding
130ea7caceeSSam Clegg // WasmComdatEntry.
131ea7caceeSSam Clegg struct WasmComdatEntry {
132ea7caceeSSam Clegg   unsigned Kind;
133ea7caceeSSam Clegg   uint32_t Index;
134ea7caceeSSam Clegg };
135ea7caceeSSam Clegg 
1366dc65e91SSam Clegg // Information about a single relocation.
1376dc65e91SSam Clegg struct WasmRelocationEntry {
1386dc65e91SSam Clegg   uint64_t Offset;                   // Where is the relocation.
1396dc65e91SSam Clegg   const MCSymbolWasm *Symbol;        // The symbol to relocate with.
1406dc65e91SSam Clegg   int64_t Addend;                    // A value to add to the symbol.
1416dc65e91SSam Clegg   unsigned Type;                     // The type of the relocation.
142fe6414b0SSam Clegg   const MCSectionWasm *FixupSection; // The section the relocation is targeting.
1436dc65e91SSam Clegg 
1446dc65e91SSam Clegg   WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol,
1456dc65e91SSam Clegg                       int64_t Addend, unsigned Type,
146fe6414b0SSam Clegg                       const MCSectionWasm *FixupSection)
1476dc65e91SSam Clegg       : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type),
1486dc65e91SSam Clegg         FixupSection(FixupSection) {}
1496dc65e91SSam Clegg 
150acd7d2b0SSam Clegg   bool hasAddend() const {
151acd7d2b0SSam Clegg     switch (Type) {
152d1152a26SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_LEB:
153d1152a26SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_SLEB:
154d1152a26SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_I32:
155d1152a26SSam Clegg     case wasm::R_WASM_FUNCTION_OFFSET_I32:
156d1152a26SSam Clegg     case wasm::R_WASM_SECTION_OFFSET_I32:
157acd7d2b0SSam Clegg       return true;
158acd7d2b0SSam Clegg     default:
159acd7d2b0SSam Clegg       return false;
160acd7d2b0SSam Clegg     }
161acd7d2b0SSam Clegg   }
162acd7d2b0SSam Clegg 
1636dc65e91SSam Clegg   void print(raw_ostream &Out) const {
164f208f631SHeejin Ahn     Out << wasm::relocTypetoString(Type) << " Off=" << Offset
165f208f631SHeejin Ahn         << ", Sym=" << *Symbol << ", Addend=" << Addend
166759631c7SSam Clegg         << ", FixupSection=" << FixupSection->getSectionName();
1676dc65e91SSam Clegg   }
168b7787fd0SSam Clegg 
169615eb470SAaron Ballman #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
170b7787fd0SSam Clegg   LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
171b7787fd0SSam Clegg #endif
1726dc65e91SSam Clegg };
1736dc65e91SSam Clegg 
17418c56a07SHeejin Ahn static const uint32_t InvalidIndex = -1;
17525d8e68bSSam Clegg 
176cfd44a2eSSam Clegg struct WasmCustomSection {
177cfd44a2eSSam Clegg 
1786a31a0d6SSam Clegg   StringRef Name;
1796a31a0d6SSam Clegg   MCSectionWasm *Section;
1806a31a0d6SSam Clegg 
1816a31a0d6SSam Clegg   uint32_t OutputContentsOffset;
1826a31a0d6SSam Clegg   uint32_t OutputIndex;
1836a31a0d6SSam Clegg 
1846a31a0d6SSam Clegg   WasmCustomSection(StringRef Name, MCSectionWasm *Section)
1856a31a0d6SSam Clegg       : Name(Name), Section(Section), OutputContentsOffset(0),
18618c56a07SHeejin Ahn         OutputIndex(InvalidIndex) {}
187cfd44a2eSSam Clegg };
188cfd44a2eSSam Clegg 
1891fb8daa6SSam Clegg #if !defined(NDEBUG)
1907f055deeSSam Clegg raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
191b7787fd0SSam Clegg   Rel.print(OS);
192b7787fd0SSam Clegg   return OS;
193b7787fd0SSam Clegg }
1941fb8daa6SSam Clegg #endif
195b7787fd0SSam Clegg 
19619e8befaSSam Clegg // Write X as an (unsigned) LEB value at offset Offset in Stream, padded
19719e8befaSSam Clegg // to allow patching.
19818c56a07SHeejin Ahn static void writePatchableLEB(raw_pwrite_stream &Stream, uint32_t X,
19919e8befaSSam Clegg                               uint64_t Offset) {
20019e8befaSSam Clegg   uint8_t Buffer[5];
20119e8befaSSam Clegg   unsigned SizeLen = encodeULEB128(X, Buffer, 5);
20219e8befaSSam Clegg   assert(SizeLen == 5);
20319e8befaSSam Clegg   Stream.pwrite((char *)Buffer, SizeLen, Offset);
20419e8befaSSam Clegg }
20519e8befaSSam Clegg 
20619e8befaSSam Clegg // Write X as an signed LEB value at offset Offset in Stream, padded
20719e8befaSSam Clegg // to allow patching.
20818c56a07SHeejin Ahn static void writePatchableSLEB(raw_pwrite_stream &Stream, int32_t X,
20919e8befaSSam Clegg                                uint64_t Offset) {
21019e8befaSSam Clegg   uint8_t Buffer[5];
21119e8befaSSam Clegg   unsigned SizeLen = encodeSLEB128(X, Buffer, 5);
21219e8befaSSam Clegg   assert(SizeLen == 5);
21319e8befaSSam Clegg   Stream.pwrite((char *)Buffer, SizeLen, Offset);
21419e8befaSSam Clegg }
21519e8befaSSam Clegg 
21619e8befaSSam Clegg // Write X as a plain integer value at offset Offset in Stream.
21718c56a07SHeejin Ahn static void writeI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
21819e8befaSSam Clegg   uint8_t Buffer[4];
21919e8befaSSam Clegg   support::endian::write32le(Buffer, X);
22019e8befaSSam Clegg   Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
22119e8befaSSam Clegg }
22219e8befaSSam Clegg 
22318eafb6cSDan Gohman class WasmObjectWriter : public MCObjectWriter {
224f17b149dSPeter Collingbourne   support::endian::Writer W;
225f17b149dSPeter Collingbourne 
22618eafb6cSDan Gohman   /// The target specific Wasm writer instance.
22718eafb6cSDan Gohman   std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
22818eafb6cSDan Gohman 
229d934cb88SDan Gohman   // Relocations for fixing up references in the code section.
230d934cb88SDan Gohman   std::vector<WasmRelocationEntry> CodeRelocations;
2316f08c84aSSam Clegg   uint32_t CodeSectionIndex;
232d934cb88SDan Gohman 
233d934cb88SDan Gohman   // Relocations for fixing up references in the data section.
234d934cb88SDan Gohman   std::vector<WasmRelocationEntry> DataRelocations;
2356f08c84aSSam Clegg   uint32_t DataSectionIndex;
236d934cb88SDan Gohman 
237d934cb88SDan Gohman   // Index values to use for fixing up call_indirect type indices.
238acd7d2b0SSam Clegg   // Maps function symbols to the index of the type of the function
239acd7d2b0SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
240d99f6078SSam Clegg   // Maps function symbols to the table element index space. Used
241d99f6078SSam Clegg   // for TABLE_INDEX relocation types (i.e. address taken functions).
242f9edbe95SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> TableIndices;
243da419bdbSHeejin Ahn   // Maps function/global symbols to the function/global/event/section index
244da419bdbSHeejin Ahn   // space.
2456c899ba6SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> WasmIndices;
246*492f7529SSam Clegg   DenseMap<const MCSymbolWasm *, uint32_t> GOTIndices;
2476c899ba6SSam Clegg   // Maps data symbols to the Wasm segment and offset/size with the segment.
2486c899ba6SSam Clegg   DenseMap<const MCSymbolWasm *, wasm::WasmDataReference> DataLocations;
2496a31a0d6SSam Clegg 
2506a31a0d6SSam Clegg   // Stores output data (index, relocations, content offset) for custom
2516a31a0d6SSam Clegg   // section.
2526a31a0d6SSam Clegg   std::vector<WasmCustomSection> CustomSections;
253cbda16ebSThomas Lively   std::unique_ptr<WasmCustomSection> ProducersSection;
254f6f4f843SThomas Lively   std::unique_ptr<WasmCustomSection> TargetFeaturesSection;
2556a31a0d6SSam Clegg   // Relocations for fixing up references in the custom sections.
2566a31a0d6SSam Clegg   DenseMap<const MCSectionWasm *, std::vector<WasmRelocationEntry>>
2576a31a0d6SSam Clegg       CustomSectionsRelocations;
258acd7d2b0SSam Clegg 
259c0d41195SSam Clegg   // Map from section to defining function symbol.
2606ccb59b3SSam Clegg   DenseMap<const MCSection *, const MCSymbol *> SectionFunctions;
2616ccb59b3SSam Clegg 
262da419bdbSHeejin Ahn   DenseMap<WasmSignature, uint32_t, WasmSignatureDenseMapInfo> SignatureIndices;
263da419bdbSHeejin Ahn   SmallVector<WasmSignature, 4> Signatures;
2646c899ba6SSam Clegg   SmallVector<WasmDataSegment, 4> DataSegments;
2659f3fe42eSSam Clegg   unsigned NumFunctionImports = 0;
2667c395943SSam Clegg   unsigned NumGlobalImports = 0;
267da419bdbSHeejin Ahn   unsigned NumEventImports = 0;
2687e1c3345SChandler Carruth   uint32_t SectionCount = 0;
269d934cb88SDan Gohman 
27018eafb6cSDan Gohman   // TargetObjectWriter wrappers.
27118eafb6cSDan Gohman   bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
272ae03c1e7SSam Clegg   unsigned getRelocType(const MCValue &Target, const MCFixup &Fixup) const {
273ae03c1e7SSam Clegg     return TargetObjectWriter->getRelocType(Target, Fixup);
27418eafb6cSDan Gohman   }
27518eafb6cSDan Gohman 
2762322a937SSam Clegg   void startSection(SectionBookkeeping &Section, unsigned SectionId);
2772322a937SSam Clegg   void startCustomSection(SectionBookkeeping &Section, StringRef Name);
278d934cb88SDan Gohman   void endSection(SectionBookkeeping &Section);
279d934cb88SDan Gohman 
28018eafb6cSDan Gohman public:
2811301a878SLang Hames   WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
2821301a878SLang Hames                    raw_pwrite_stream &OS)
28359a6fc46SPeter Collingbourne       : W(OS, support::little), TargetObjectWriter(std::move(MOTW)) {}
28418eafb6cSDan Gohman 
2850917c9e4SDan Gohman private:
286acd7d2b0SSam Clegg   void reset() override {
287acd7d2b0SSam Clegg     CodeRelocations.clear();
288acd7d2b0SSam Clegg     DataRelocations.clear();
289acd7d2b0SSam Clegg     TypeIndices.clear();
2906c899ba6SSam Clegg     WasmIndices.clear();
291*492f7529SSam Clegg     GOTIndices.clear();
292f9edbe95SSam Clegg     TableIndices.clear();
2936c899ba6SSam Clegg     DataLocations.clear();
294cbda16ebSThomas Lively     CustomSections.clear();
295cbda16ebSThomas Lively     ProducersSection.reset();
296f6f4f843SThomas Lively     TargetFeaturesSection.reset();
2976a31a0d6SSam Clegg     CustomSectionsRelocations.clear();
298da419bdbSHeejin Ahn     SignatureIndices.clear();
299da419bdbSHeejin Ahn     Signatures.clear();
3006c899ba6SSam Clegg     DataSegments.clear();
3016ccb59b3SSam Clegg     SectionFunctions.clear();
3029f3fe42eSSam Clegg     NumFunctionImports = 0;
3037c395943SSam Clegg     NumGlobalImports = 0;
304105bdc25SSam Clegg     MCObjectWriter::reset();
305acd7d2b0SSam Clegg   }
306acd7d2b0SSam Clegg 
30718eafb6cSDan Gohman   void writeHeader(const MCAssembler &Asm);
30818eafb6cSDan Gohman 
30918eafb6cSDan Gohman   void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
31018eafb6cSDan Gohman                         const MCFragment *Fragment, const MCFixup &Fixup,
311ceecfe5bSRafael Espindola                         MCValue Target, uint64_t &FixedValue) override;
31218eafb6cSDan Gohman 
31318eafb6cSDan Gohman   void executePostLayoutBinding(MCAssembler &Asm,
31418eafb6cSDan Gohman                                 const MCAsmLayout &Layout) override;
31518eafb6cSDan Gohman 
316438390faSPeter Collingbourne   uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
3179e15f359SSam Clegg 
318b7787fd0SSam Clegg   void writeString(const StringRef Str) {
319f17b149dSPeter Collingbourne     encodeULEB128(Str.size(), W.OS);
320f17b149dSPeter Collingbourne     W.OS << Str;
321b7787fd0SSam Clegg   }
322b7787fd0SSam Clegg 
323f208f631SHeejin Ahn   void writeValueType(wasm::ValType Ty) { W.OS << static_cast<char>(Ty); }
3249e15f359SSam Clegg 
325da419bdbSHeejin Ahn   void writeTypeSection(ArrayRef<WasmSignature> Signatures);
3268defa952SSam Clegg   void writeImportSection(ArrayRef<wasm::WasmImport> Imports, uint32_t DataSize,
327f950b24aSSam Clegg                           uint32_t NumElements);
328457fb0b4SSam Clegg   void writeFunctionSection(ArrayRef<WasmFunction> Functions);
3298defa952SSam Clegg   void writeExportSection(ArrayRef<wasm::WasmExport> Exports);
330457fb0b4SSam Clegg   void writeElemSection(ArrayRef<uint32_t> TableElems);
3319e15f359SSam Clegg   void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
332457fb0b4SSam Clegg                         ArrayRef<WasmFunction> Functions);
3336c899ba6SSam Clegg   void writeDataSection();
334da419bdbSHeejin Ahn   void writeEventSection(ArrayRef<wasm::WasmEventType> Events);
3356f08c84aSSam Clegg   void writeRelocSection(uint32_t SectionIndex, StringRef Name,
336f77dc2a8SSam Clegg                          std::vector<WasmRelocationEntry> &Relocations);
33731a2c809SSam Clegg   void writeLinkingMetaDataSection(
33886b4a09aSSam Clegg       ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
339ea7caceeSSam Clegg       ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
340ea7caceeSSam Clegg       const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats);
341cbda16ebSThomas Lively   void writeCustomSection(WasmCustomSection &CustomSection,
342cbda16ebSThomas Lively                           const MCAssembler &Asm, const MCAsmLayout &Layout);
3436a31a0d6SSam Clegg   void writeCustomRelocSections();
3446a31a0d6SSam Clegg   void
3456a31a0d6SSam Clegg   updateCustomSectionRelocations(const SmallVector<WasmFunction, 4> &Functions,
3466a31a0d6SSam Clegg                                  const MCAsmLayout &Layout);
347acd7d2b0SSam Clegg 
3487c395943SSam Clegg   uint32_t getProvisionalValue(const WasmRelocationEntry &RelEntry);
349acd7d2b0SSam Clegg   void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
350acd7d2b0SSam Clegg                         uint64_t ContentsOffset);
351acd7d2b0SSam Clegg 
352acd7d2b0SSam Clegg   uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
3535e3d33a7SSam Clegg   uint32_t getFunctionType(const MCSymbolWasm &Symbol);
354da419bdbSHeejin Ahn   uint32_t getEventType(const MCSymbolWasm &Symbol);
35538b12f5eSHeejin Ahn   void registerFunctionType(const MCSymbolWasm &Symbol);
35638b12f5eSHeejin Ahn   void registerEventType(const MCSymbolWasm &Symbol);
35718eafb6cSDan Gohman };
3589e15f359SSam Clegg 
35918eafb6cSDan Gohman } // end anonymous namespace
36018eafb6cSDan Gohman 
361d934cb88SDan Gohman // Write out a section header and a patchable section size field.
362d934cb88SDan Gohman void WasmObjectWriter::startSection(SectionBookkeeping &Section,
3632322a937SSam Clegg                                     unsigned SectionId) {
364d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "startSection " << SectionId << "\n");
365f17b149dSPeter Collingbourne   W.OS << char(SectionId);
366d934cb88SDan Gohman 
367f17b149dSPeter Collingbourne   Section.SizeOffset = W.OS.tell();
368d934cb88SDan Gohman 
369d934cb88SDan Gohman   // The section size. We don't know the size yet, so reserve enough space
370d934cb88SDan Gohman   // for any 32-bit value; we'll patch it later.
37119e8befaSSam Clegg   encodeULEB128(0, W.OS, 5);
372d934cb88SDan Gohman 
373d934cb88SDan Gohman   // The position where the section starts, for measuring its size.
374f17b149dSPeter Collingbourne   Section.ContentsOffset = W.OS.tell();
375f17b149dSPeter Collingbourne   Section.PayloadOffset = W.OS.tell();
3766f08c84aSSam Clegg   Section.Index = SectionCount++;
377d934cb88SDan Gohman }
3782322a937SSam Clegg 
3792322a937SSam Clegg void WasmObjectWriter::startCustomSection(SectionBookkeeping &Section,
3802322a937SSam Clegg                                           StringRef Name) {
381d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "startCustomSection " << Name << "\n");
3822322a937SSam Clegg   startSection(Section, wasm::WASM_SEC_CUSTOM);
3836a31a0d6SSam Clegg 
3846a31a0d6SSam Clegg   // The position where the section header ends, for measuring its size.
385f17b149dSPeter Collingbourne   Section.PayloadOffset = W.OS.tell();
3866a31a0d6SSam Clegg 
3872322a937SSam Clegg   // Custom sections in wasm also have a string identifier.
3882322a937SSam Clegg   writeString(Name);
3896a31a0d6SSam Clegg 
3906a31a0d6SSam Clegg   // The position where the custom section starts.
391f17b149dSPeter Collingbourne   Section.ContentsOffset = W.OS.tell();
392d934cb88SDan Gohman }
393d934cb88SDan Gohman 
394d934cb88SDan Gohman // Now that the section is complete and we know how big it is, patch up the
395d934cb88SDan Gohman // section size field at the start of the section.
396d934cb88SDan Gohman void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
397c0affde8SSam Clegg   uint64_t Size = W.OS.tell();
398c0affde8SSam Clegg   // /dev/null doesn't support seek/tell and can report offset of 0.
399c0affde8SSam Clegg   // Simply skip this patching in that case.
400c0affde8SSam Clegg   if (!Size)
401c0affde8SSam Clegg     return;
402c0affde8SSam Clegg 
403c0affde8SSam Clegg   Size -= Section.PayloadOffset;
404d934cb88SDan Gohman   if (uint32_t(Size) != Size)
405d934cb88SDan Gohman     report_fatal_error("section size does not fit in a uint32_t");
406d934cb88SDan Gohman 
407d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "endSection size=" << Size << "\n");
408d934cb88SDan Gohman 
409d934cb88SDan Gohman   // Write the final section size to the payload_len field, which follows
410d934cb88SDan Gohman   // the section id byte.
41118c56a07SHeejin Ahn   writePatchableLEB(static_cast<raw_pwrite_stream &>(W.OS), Size,
412f17b149dSPeter Collingbourne                     Section.SizeOffset);
413d934cb88SDan Gohman }
414d934cb88SDan Gohman 
41518eafb6cSDan Gohman // Emit the Wasm header.
41618eafb6cSDan Gohman void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
417f17b149dSPeter Collingbourne   W.OS.write(wasm::WasmMagic, sizeof(wasm::WasmMagic));
418f17b149dSPeter Collingbourne   W.write<uint32_t>(wasm::WasmVersion);
41918eafb6cSDan Gohman }
42018eafb6cSDan Gohman 
42118eafb6cSDan Gohman void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
42218eafb6cSDan Gohman                                                 const MCAsmLayout &Layout) {
4236ccb59b3SSam Clegg   // Build a map of sections to the function that defines them, for use
4246ccb59b3SSam Clegg   // in recordRelocation.
4256ccb59b3SSam Clegg   for (const MCSymbol &S : Asm.symbols()) {
4266ccb59b3SSam Clegg     const auto &WS = static_cast<const MCSymbolWasm &>(S);
4276ccb59b3SSam Clegg     if (WS.isDefined() && WS.isFunction() && !WS.isVariable()) {
4286ccb59b3SSam Clegg       const auto &Sec = static_cast<const MCSectionWasm &>(S.getSection());
4296ccb59b3SSam Clegg       auto Pair = SectionFunctions.insert(std::make_pair(&Sec, &S));
4306ccb59b3SSam Clegg       if (!Pair.second)
4316ccb59b3SSam Clegg         report_fatal_error("section already has a defining function: " +
4326ccb59b3SSam Clegg                            Sec.getSectionName());
4336ccb59b3SSam Clegg     }
4346ccb59b3SSam Clegg   }
43518eafb6cSDan Gohman }
43618eafb6cSDan Gohman 
43718eafb6cSDan Gohman void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
43818eafb6cSDan Gohman                                         const MCAsmLayout &Layout,
43918eafb6cSDan Gohman                                         const MCFragment *Fragment,
44018eafb6cSDan Gohman                                         const MCFixup &Fixup, MCValue Target,
441ceecfe5bSRafael Espindola                                         uint64_t &FixedValue) {
442ceecfe5bSRafael Espindola   MCAsmBackend &Backend = Asm.getBackend();
443ceecfe5bSRafael Espindola   bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
444ceecfe5bSRafael Espindola                  MCFixupKindInfo::FKF_IsPCRel;
445fe6414b0SSam Clegg   const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
446d934cb88SDan Gohman   uint64_t C = Target.getConstant();
447d934cb88SDan Gohman   uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
448d934cb88SDan Gohman   MCContext &Ctx = Asm.getContext();
449d934cb88SDan Gohman 
450bafe6902SSam Clegg   // The .init_array isn't translated as data, so don't do relocations in it.
451bafe6902SSam Clegg   if (FixupSection.getSectionName().startswith(".init_array"))
452bafe6902SSam Clegg     return;
453bafe6902SSam Clegg 
454d934cb88SDan Gohman   if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
455d934cb88SDan Gohman     assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
456d934cb88SDan Gohman            "Should not have constructed this");
457d934cb88SDan Gohman 
458d934cb88SDan Gohman     // Let A, B and C being the components of Target and R be the location of
459d934cb88SDan Gohman     // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
460d934cb88SDan Gohman     // If it is pcrel, we want to compute (A - B + C - R).
461d934cb88SDan Gohman 
462d934cb88SDan Gohman     // In general, Wasm has no relocations for -B. It can only represent (A + C)
463d934cb88SDan Gohman     // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
464d934cb88SDan Gohman     // replace B to implement it: (A - R - K + C)
465d934cb88SDan Gohman     if (IsPCRel) {
466d934cb88SDan Gohman       Ctx.reportError(
467d934cb88SDan Gohman           Fixup.getLoc(),
468d934cb88SDan Gohman           "No relocation available to represent this relative expression");
469d934cb88SDan Gohman       return;
470d934cb88SDan Gohman     }
471d934cb88SDan Gohman 
472d934cb88SDan Gohman     const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
473d934cb88SDan Gohman 
474d934cb88SDan Gohman     if (SymB.isUndefined()) {
475d934cb88SDan Gohman       Ctx.reportError(Fixup.getLoc(),
476d934cb88SDan Gohman                       Twine("symbol '") + SymB.getName() +
477d934cb88SDan Gohman                           "' can not be undefined in a subtraction expression");
478d934cb88SDan Gohman       return;
479d934cb88SDan Gohman     }
480d934cb88SDan Gohman 
481d934cb88SDan Gohman     assert(!SymB.isAbsolute() && "Should have been folded");
482d934cb88SDan Gohman     const MCSection &SecB = SymB.getSection();
483d934cb88SDan Gohman     if (&SecB != &FixupSection) {
484d934cb88SDan Gohman       Ctx.reportError(Fixup.getLoc(),
485d934cb88SDan Gohman                       "Cannot represent a difference across sections");
486d934cb88SDan Gohman       return;
487d934cb88SDan Gohman     }
488d934cb88SDan Gohman 
489d934cb88SDan Gohman     uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
490d934cb88SDan Gohman     uint64_t K = SymBOffset - FixupOffset;
491d934cb88SDan Gohman     IsPCRel = true;
492d934cb88SDan Gohman     C -= K;
493d934cb88SDan Gohman   }
494d934cb88SDan Gohman 
495d934cb88SDan Gohman   // We either rejected the fixup or folded B into C at this point.
496d934cb88SDan Gohman   const MCSymbolRefExpr *RefA = Target.getSymA();
497d934cb88SDan Gohman   const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr;
498d934cb88SDan Gohman 
499d934cb88SDan Gohman   if (SymA && SymA->isVariable()) {
500d934cb88SDan Gohman     const MCExpr *Expr = SymA->getVariableValue();
5016ad8f190SSam Clegg     const auto *Inner = cast<MCSymbolRefExpr>(Expr);
5026ad8f190SSam Clegg     if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
5036ad8f190SSam Clegg       llvm_unreachable("weakref used in reloc not yet implemented");
504d934cb88SDan Gohman   }
505d934cb88SDan Gohman 
506d934cb88SDan Gohman   // Put any constant offset in an addend. Offsets can be negative, and
507d934cb88SDan Gohman   // LLVM expects wrapping, in contrast to wasm's immediates which can't
508d934cb88SDan Gohman   // be negative and don't wrap.
509d934cb88SDan Gohman   FixedValue = 0;
510d934cb88SDan Gohman 
5114d57fbd0SSam Clegg   unsigned Type = getRelocType(Target, Fixup);
512ae03c1e7SSam Clegg   assert(!IsPCRel);
5139d24fb7fSSam Clegg   assert(SymA);
5149d24fb7fSSam Clegg 
5154d57fbd0SSam Clegg   // Absolute offset within a section or a function.
5164d57fbd0SSam Clegg   // Currently only supported for for metadata sections.
5174d57fbd0SSam Clegg   // See: test/MC/WebAssembly/blockaddress.ll
518d1152a26SSam Clegg   if (Type == wasm::R_WASM_FUNCTION_OFFSET_I32 ||
519d1152a26SSam Clegg       Type == wasm::R_WASM_SECTION_OFFSET_I32) {
5204d57fbd0SSam Clegg     if (!FixupSection.getKind().isMetadata())
5214d57fbd0SSam Clegg       report_fatal_error("relocations for function or section offsets are "
5224d57fbd0SSam Clegg                          "only supported in metadata sections");
5234d57fbd0SSam Clegg 
5244d57fbd0SSam Clegg     const MCSymbol *SectionSymbol = nullptr;
5254d57fbd0SSam Clegg     const MCSection &SecA = SymA->getSection();
5264d57fbd0SSam Clegg     if (SecA.getKind().isText())
5276ccb59b3SSam Clegg       SectionSymbol = SectionFunctions.find(&SecA)->second;
5284d57fbd0SSam Clegg     else
5294d57fbd0SSam Clegg       SectionSymbol = SecA.getBeginSymbol();
5304d57fbd0SSam Clegg     if (!SectionSymbol)
5314d57fbd0SSam Clegg       report_fatal_error("section symbol is required for relocation");
5324d57fbd0SSam Clegg 
5334d57fbd0SSam Clegg     C += Layout.getSymbolOffset(*SymA);
5344d57fbd0SSam Clegg     SymA = cast<MCSymbolWasm>(SectionSymbol);
5354d57fbd0SSam Clegg   }
5364d57fbd0SSam Clegg 
537d1152a26SSam Clegg   // Relocation other than R_WASM_TYPE_INDEX_LEB are required to be
5384d57fbd0SSam Clegg   // against a named symbol.
539d1152a26SSam Clegg   if (Type != wasm::R_WASM_TYPE_INDEX_LEB) {
5404d57fbd0SSam Clegg     if (SymA->getName().empty())
5414d57fbd0SSam Clegg       report_fatal_error("relocations against un-named temporaries are not yet "
5424d57fbd0SSam Clegg                          "supported by wasm");
5434d57fbd0SSam Clegg 
5444d57fbd0SSam Clegg     SymA->setUsedInReloc();
5454d57fbd0SSam Clegg   }
546ae03c1e7SSam Clegg 
547*492f7529SSam Clegg   if (RefA->getKind() == MCSymbolRefExpr::VK_GOT)
548*492f7529SSam Clegg     SymA->setUsedInGOT();
549*492f7529SSam Clegg 
550d934cb88SDan Gohman   WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
551d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
552d934cb88SDan Gohman 
5536a31a0d6SSam Clegg   if (FixupSection.isWasmData()) {
554d934cb88SDan Gohman     DataRelocations.push_back(Rec);
5556a31a0d6SSam Clegg   } else if (FixupSection.getKind().isText()) {
55612fd3da9SSam Clegg     CodeRelocations.push_back(Rec);
5576a31a0d6SSam Clegg   } else if (FixupSection.getKind().isMetadata()) {
5586a31a0d6SSam Clegg     CustomSectionsRelocations[&FixupSection].push_back(Rec);
5596a31a0d6SSam Clegg   } else {
56012fd3da9SSam Clegg     llvm_unreachable("unexpected section type");
561d934cb88SDan Gohman   }
5626a31a0d6SSam Clegg }
563d934cb88SDan Gohman 
56418c56a07SHeejin Ahn static const MCSymbolWasm *resolveSymbol(const MCSymbolWasm &Symbol) {
565ffba00bdSSam Clegg   const MCSymbolWasm* Ret = &Symbol;
566ffba00bdSSam Clegg   while (Ret->isVariable()) {
567ffba00bdSSam Clegg     const MCExpr *Expr = Ret->getVariableValue();
568aff1c4dfSSam Clegg     auto *Inner = cast<MCSymbolRefExpr>(Expr);
569ffba00bdSSam Clegg     Ret = cast<MCSymbolWasm>(&Inner->getSymbol());
570aff1c4dfSSam Clegg   }
571ffba00bdSSam Clegg   return Ret;
572aff1c4dfSSam Clegg }
573aff1c4dfSSam Clegg 
574d934cb88SDan Gohman // Compute a value to write into the code at the location covered
57560ec3034SSam Clegg // by RelEntry. This value isn't used by the static linker; it just serves
57660ec3034SSam Clegg // to make the object format more readable and more likely to be directly
57760ec3034SSam Clegg // useable.
5787c395943SSam Clegg uint32_t
5797c395943SSam Clegg WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) {
580*492f7529SSam Clegg   if (RelEntry.Type == wasm::R_WASM_GLOBAL_INDEX_LEB && !RelEntry.Symbol->isGlobal()) {
581*492f7529SSam Clegg     assert(GOTIndices.count(RelEntry.Symbol) > 0 && "symbol not found in GOT index space");
582*492f7529SSam Clegg     return GOTIndices[RelEntry.Symbol];
583*492f7529SSam Clegg   }
584*492f7529SSam Clegg 
58560ec3034SSam Clegg   switch (RelEntry.Type) {
586d1152a26SSam Clegg   case wasm::R_WASM_TABLE_INDEX_SLEB:
587d1152a26SSam Clegg   case wasm::R_WASM_TABLE_INDEX_I32: {
588f9edbe95SSam Clegg     // Provisional value is table address of the resolved symbol itself
58918c56a07SHeejin Ahn     const MCSymbolWasm *Sym = resolveSymbol(*RelEntry.Symbol);
590f9edbe95SSam Clegg     assert(Sym->isFunction());
591f9edbe95SSam Clegg     return TableIndices[Sym];
592f9edbe95SSam Clegg   }
593d1152a26SSam Clegg   case wasm::R_WASM_TYPE_INDEX_LEB:
5946c899ba6SSam Clegg     // Provisional value is same as the index
59560ec3034SSam Clegg     return getRelocationIndexValue(RelEntry);
596d1152a26SSam Clegg   case wasm::R_WASM_FUNCTION_INDEX_LEB:
597d1152a26SSam Clegg   case wasm::R_WASM_GLOBAL_INDEX_LEB:
598d1152a26SSam Clegg   case wasm::R_WASM_EVENT_INDEX_LEB:
599da419bdbSHeejin Ahn     // Provisional value is function/global/event Wasm index
600*492f7529SSam Clegg     assert(WasmIndices.count(RelEntry.Symbol) > 0 && "symbol not found in wasm index space");
6016c899ba6SSam Clegg     return WasmIndices[RelEntry.Symbol];
602d1152a26SSam Clegg   case wasm::R_WASM_FUNCTION_OFFSET_I32:
603d1152a26SSam Clegg   case wasm::R_WASM_SECTION_OFFSET_I32: {
6046a31a0d6SSam Clegg     const auto &Section =
6056a31a0d6SSam Clegg         static_cast<const MCSectionWasm &>(RelEntry.Symbol->getSection());
6066a31a0d6SSam Clegg     return Section.getSectionOffset() + RelEntry.Addend;
6076a31a0d6SSam Clegg   }
608d1152a26SSam Clegg   case wasm::R_WASM_MEMORY_ADDR_LEB:
609d1152a26SSam Clegg   case wasm::R_WASM_MEMORY_ADDR_I32:
610d1152a26SSam Clegg   case wasm::R_WASM_MEMORY_ADDR_SLEB: {
611f9edbe95SSam Clegg     // Provisional value is address of the global
61218c56a07SHeejin Ahn     const MCSymbolWasm *Sym = resolveSymbol(*RelEntry.Symbol);
613270ed1b3SSam Clegg     // For undefined symbols, use zero
614cd65f698SSam Clegg     if (!Sym->isDefined())
615270ed1b3SSam Clegg       return 0;
6166c899ba6SSam Clegg     const wasm::WasmDataReference &Ref = DataLocations[Sym];
6176c899ba6SSam Clegg     const WasmDataSegment &Segment = DataSegments[Ref.Segment];
618d934cb88SDan Gohman     // Ignore overflow. LLVM allows address arithmetic to silently wrap.
6196c899ba6SSam Clegg     return Segment.Offset + Ref.Offset + RelEntry.Addend;
62060ec3034SSam Clegg   }
62160ec3034SSam Clegg   default:
62260ec3034SSam Clegg     llvm_unreachable("invalid relocation type");
62360ec3034SSam Clegg   }
624d934cb88SDan Gohman }
625d934cb88SDan Gohman 
626759631c7SSam Clegg static void addData(SmallVectorImpl<char> &DataBytes,
62763ebb813SSam Clegg                     MCSectionWasm &DataSection) {
628d34e60caSNicola Zaghen   LLVM_DEBUG(errs() << "addData: " << DataSection.getSectionName() << "\n");
629759631c7SSam Clegg 
63063ebb813SSam Clegg   DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
63163ebb813SSam Clegg 
632759631c7SSam Clegg   for (const MCFragment &Frag : DataSection) {
633759631c7SSam Clegg     if (Frag.hasInstructions())
634759631c7SSam Clegg       report_fatal_error("only data supported in data sections");
635759631c7SSam Clegg 
636759631c7SSam Clegg     if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
637759631c7SSam Clegg       if (Align->getValueSize() != 1)
638759631c7SSam Clegg         report_fatal_error("only byte values supported for alignment");
639759631c7SSam Clegg       // If nops are requested, use zeros, as this is the data section.
640759631c7SSam Clegg       uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
641f208f631SHeejin Ahn       uint64_t Size =
642f208f631SHeejin Ahn           std::min<uint64_t>(alignTo(DataBytes.size(), Align->getAlignment()),
643f208f631SHeejin Ahn                              DataBytes.size() + Align->getMaxBytesToEmit());
644759631c7SSam Clegg       DataBytes.resize(Size, Value);
645759631c7SSam Clegg     } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
646588fad4dSNirav Dave       int64_t NumValues;
647588fad4dSNirav Dave       if (!Fill->getNumValues().evaluateAsAbsolute(NumValues))
648d707c370SRafael Espindola         llvm_unreachable("The fill should be an assembler constant");
649588fad4dSNirav Dave       DataBytes.insert(DataBytes.end(), Fill->getValueSize() * NumValues,
650588fad4dSNirav Dave                        Fill->getValue());
65124faf859SHeejin Ahn     } else if (auto *LEB = dyn_cast<MCLEBFragment>(&Frag)) {
65224faf859SHeejin Ahn       const SmallVectorImpl<char> &Contents = LEB->getContents();
65324faf859SHeejin Ahn       DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
654759631c7SSam Clegg     } else {
655759631c7SSam Clegg       const auto &DataFrag = cast<MCDataFragment>(Frag);
656759631c7SSam Clegg       const SmallVectorImpl<char> &Contents = DataFrag.getContents();
657759631c7SSam Clegg       DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
658759631c7SSam Clegg     }
659759631c7SSam Clegg   }
660759631c7SSam Clegg 
661d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
662759631c7SSam Clegg }
663759631c7SSam Clegg 
66460ec3034SSam Clegg uint32_t
66560ec3034SSam Clegg WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
666d1152a26SSam Clegg   if (RelEntry.Type == wasm::R_WASM_TYPE_INDEX_LEB) {
667b7787fd0SSam Clegg     if (!TypeIndices.count(RelEntry.Symbol))
668b7787fd0SSam Clegg       report_fatal_error("symbol not found in type index space: " +
669b7787fd0SSam Clegg                          RelEntry.Symbol->getName());
670acd7d2b0SSam Clegg     return TypeIndices[RelEntry.Symbol];
671acd7d2b0SSam Clegg   }
67260ec3034SSam Clegg 
67325d8e68bSSam Clegg   return RelEntry.Symbol->getIndex();
674acd7d2b0SSam Clegg }
675acd7d2b0SSam Clegg 
676d934cb88SDan Gohman // Apply the portions of the relocation records that we can handle ourselves
677d934cb88SDan Gohman // directly.
678acd7d2b0SSam Clegg void WasmObjectWriter::applyRelocations(
679acd7d2b0SSam Clegg     ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
680f17b149dSPeter Collingbourne   auto &Stream = static_cast<raw_pwrite_stream &>(W.OS);
681d934cb88SDan Gohman   for (const WasmRelocationEntry &RelEntry : Relocations) {
682d934cb88SDan Gohman     uint64_t Offset = ContentsOffset +
683d934cb88SDan Gohman                       RelEntry.FixupSection->getSectionOffset() +
684d934cb88SDan Gohman                       RelEntry.Offset;
685d934cb88SDan Gohman 
686d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
68760ec3034SSam Clegg     uint32_t Value = getProvisionalValue(RelEntry);
68860ec3034SSam Clegg 
689acd7d2b0SSam Clegg     switch (RelEntry.Type) {
690d1152a26SSam Clegg     case wasm::R_WASM_FUNCTION_INDEX_LEB:
691d1152a26SSam Clegg     case wasm::R_WASM_TYPE_INDEX_LEB:
692d1152a26SSam Clegg     case wasm::R_WASM_GLOBAL_INDEX_LEB:
693d1152a26SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_LEB:
694d1152a26SSam Clegg     case wasm::R_WASM_EVENT_INDEX_LEB:
69518c56a07SHeejin Ahn       writePatchableLEB(Stream, Value, Offset);
696d934cb88SDan Gohman       break;
697d1152a26SSam Clegg     case wasm::R_WASM_TABLE_INDEX_I32:
698d1152a26SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_I32:
699d1152a26SSam Clegg     case wasm::R_WASM_FUNCTION_OFFSET_I32:
700d1152a26SSam Clegg     case wasm::R_WASM_SECTION_OFFSET_I32:
70118c56a07SHeejin Ahn       writeI32(Stream, Value, Offset);
702d934cb88SDan Gohman       break;
703d1152a26SSam Clegg     case wasm::R_WASM_TABLE_INDEX_SLEB:
704d1152a26SSam Clegg     case wasm::R_WASM_MEMORY_ADDR_SLEB:
70518c56a07SHeejin Ahn       writePatchableSLEB(Stream, Value, Offset);
70660ec3034SSam Clegg       break;
707d934cb88SDan Gohman     default:
7089d24fb7fSSam Clegg       llvm_unreachable("invalid relocation type");
709d934cb88SDan Gohman     }
710d934cb88SDan Gohman   }
71118eafb6cSDan Gohman }
71218eafb6cSDan Gohman 
713da419bdbSHeejin Ahn void WasmObjectWriter::writeTypeSection(ArrayRef<WasmSignature> Signatures) {
714da419bdbSHeejin Ahn   if (Signatures.empty())
7159e15f359SSam Clegg     return;
7169e15f359SSam Clegg 
7179e15f359SSam Clegg   SectionBookkeeping Section;
7189e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_TYPE);
7199e15f359SSam Clegg 
720da419bdbSHeejin Ahn   encodeULEB128(Signatures.size(), W.OS);
7219e15f359SSam Clegg 
722da419bdbSHeejin Ahn   for (const WasmSignature &Sig : Signatures) {
723f17b149dSPeter Collingbourne     W.OS << char(wasm::WASM_TYPE_FUNC);
724da419bdbSHeejin Ahn     encodeULEB128(Sig.Params.size(), W.OS);
725da419bdbSHeejin Ahn     for (wasm::ValType Ty : Sig.Params)
7269e15f359SSam Clegg       writeValueType(Ty);
727da419bdbSHeejin Ahn     encodeULEB128(Sig.Returns.size(), W.OS);
728da419bdbSHeejin Ahn     for (wasm::ValType Ty : Sig.Returns)
7299e15f359SSam Clegg       writeValueType(Ty);
7309e15f359SSam Clegg   }
7319e15f359SSam Clegg 
7329e15f359SSam Clegg   endSection(Section);
7339e15f359SSam Clegg }
7349e15f359SSam Clegg 
7358defa952SSam Clegg void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports,
736f950b24aSSam Clegg                                           uint32_t DataSize,
737f950b24aSSam Clegg                                           uint32_t NumElements) {
7389e15f359SSam Clegg   if (Imports.empty())
7399e15f359SSam Clegg     return;
7409e15f359SSam Clegg 
741f950b24aSSam Clegg   uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
742f950b24aSSam Clegg 
7439e15f359SSam Clegg   SectionBookkeeping Section;
7449e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_IMPORT);
7459e15f359SSam Clegg 
746f17b149dSPeter Collingbourne   encodeULEB128(Imports.size(), W.OS);
7478defa952SSam Clegg   for (const wasm::WasmImport &Import : Imports) {
7488defa952SSam Clegg     writeString(Import.Module);
7498defa952SSam Clegg     writeString(Import.Field);
750f17b149dSPeter Collingbourne     W.OS << char(Import.Kind);
7519e15f359SSam Clegg 
7529e15f359SSam Clegg     switch (Import.Kind) {
7539e15f359SSam Clegg     case wasm::WASM_EXTERNAL_FUNCTION:
754f17b149dSPeter Collingbourne       encodeULEB128(Import.SigIndex, W.OS);
7559e15f359SSam Clegg       break;
7569e15f359SSam Clegg     case wasm::WASM_EXTERNAL_GLOBAL:
757f17b149dSPeter Collingbourne       W.OS << char(Import.Global.Type);
758f17b149dSPeter Collingbourne       W.OS << char(Import.Global.Mutable ? 1 : 0);
7599e15f359SSam Clegg       break;
760f950b24aSSam Clegg     case wasm::WASM_EXTERNAL_MEMORY:
761f17b149dSPeter Collingbourne       encodeULEB128(0, W.OS);        // flags
762f17b149dSPeter Collingbourne       encodeULEB128(NumPages, W.OS); // initial
763f950b24aSSam Clegg       break;
764f950b24aSSam Clegg     case wasm::WASM_EXTERNAL_TABLE:
765f17b149dSPeter Collingbourne       W.OS << char(Import.Table.ElemType);
766f17b149dSPeter Collingbourne       encodeULEB128(0, W.OS);           // flags
767f17b149dSPeter Collingbourne       encodeULEB128(NumElements, W.OS); // initial
768f950b24aSSam Clegg       break;
769da419bdbSHeejin Ahn     case wasm::WASM_EXTERNAL_EVENT:
770da419bdbSHeejin Ahn       encodeULEB128(Import.Event.Attribute, W.OS);
771da419bdbSHeejin Ahn       encodeULEB128(Import.Event.SigIndex, W.OS);
772da419bdbSHeejin Ahn       break;
7739e15f359SSam Clegg     default:
7749e15f359SSam Clegg       llvm_unreachable("unsupported import kind");
7759e15f359SSam Clegg     }
7769e15f359SSam Clegg   }
7779e15f359SSam Clegg 
7789e15f359SSam Clegg   endSection(Section);
7799e15f359SSam Clegg }
7809e15f359SSam Clegg 
781457fb0b4SSam Clegg void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
7829e15f359SSam Clegg   if (Functions.empty())
7839e15f359SSam Clegg     return;
7849e15f359SSam Clegg 
7859e15f359SSam Clegg   SectionBookkeeping Section;
7869e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_FUNCTION);
7879e15f359SSam Clegg 
788f17b149dSPeter Collingbourne   encodeULEB128(Functions.size(), W.OS);
7899e15f359SSam Clegg   for (const WasmFunction &Func : Functions)
790da419bdbSHeejin Ahn     encodeULEB128(Func.SigIndex, W.OS);
7919e15f359SSam Clegg 
7929e15f359SSam Clegg   endSection(Section);
7939e15f359SSam Clegg }
7949e15f359SSam Clegg 
795da419bdbSHeejin Ahn void WasmObjectWriter::writeEventSection(ArrayRef<wasm::WasmEventType> Events) {
796da419bdbSHeejin Ahn   if (Events.empty())
797da419bdbSHeejin Ahn     return;
798da419bdbSHeejin Ahn 
799da419bdbSHeejin Ahn   SectionBookkeeping Section;
800da419bdbSHeejin Ahn   startSection(Section, wasm::WASM_SEC_EVENT);
801da419bdbSHeejin Ahn 
802da419bdbSHeejin Ahn   encodeULEB128(Events.size(), W.OS);
803da419bdbSHeejin Ahn   for (const wasm::WasmEventType &Event : Events) {
804da419bdbSHeejin Ahn     encodeULEB128(Event.Attribute, W.OS);
805da419bdbSHeejin Ahn     encodeULEB128(Event.SigIndex, W.OS);
806da419bdbSHeejin Ahn   }
807da419bdbSHeejin Ahn 
808da419bdbSHeejin Ahn   endSection(Section);
809da419bdbSHeejin Ahn }
810da419bdbSHeejin Ahn 
8118defa952SSam Clegg void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) {
8129e15f359SSam Clegg   if (Exports.empty())
8139e15f359SSam Clegg     return;
8149e15f359SSam Clegg 
8159e15f359SSam Clegg   SectionBookkeeping Section;
8169e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_EXPORT);
8179e15f359SSam Clegg 
818f17b149dSPeter Collingbourne   encodeULEB128(Exports.size(), W.OS);
8198defa952SSam Clegg   for (const wasm::WasmExport &Export : Exports) {
8208defa952SSam Clegg     writeString(Export.Name);
821f17b149dSPeter Collingbourne     W.OS << char(Export.Kind);
822f17b149dSPeter Collingbourne     encodeULEB128(Export.Index, W.OS);
8239e15f359SSam Clegg   }
8249e15f359SSam Clegg 
8259e15f359SSam Clegg   endSection(Section);
8269e15f359SSam Clegg }
8279e15f359SSam Clegg 
828457fb0b4SSam Clegg void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
8299e15f359SSam Clegg   if (TableElems.empty())
8309e15f359SSam Clegg     return;
8319e15f359SSam Clegg 
8329e15f359SSam Clegg   SectionBookkeeping Section;
8339e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_ELEM);
8349e15f359SSam Clegg 
835f17b149dSPeter Collingbourne   encodeULEB128(1, W.OS); // number of "segments"
836f17b149dSPeter Collingbourne   encodeULEB128(0, W.OS); // the table index
8379e15f359SSam Clegg 
8389e15f359SSam Clegg   // init expr for starting offset
839f17b149dSPeter Collingbourne   W.OS << char(wasm::WASM_OPCODE_I32_CONST);
84018c56a07SHeejin Ahn   encodeSLEB128(InitialTableOffset, W.OS);
841f17b149dSPeter Collingbourne   W.OS << char(wasm::WASM_OPCODE_END);
8429e15f359SSam Clegg 
843f17b149dSPeter Collingbourne   encodeULEB128(TableElems.size(), W.OS);
8449e15f359SSam Clegg   for (uint32_t Elem : TableElems)
845f17b149dSPeter Collingbourne     encodeULEB128(Elem, W.OS);
8469e15f359SSam Clegg 
8479e15f359SSam Clegg   endSection(Section);
8489e15f359SSam Clegg }
8499e15f359SSam Clegg 
850457fb0b4SSam Clegg void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
851457fb0b4SSam Clegg                                         const MCAsmLayout &Layout,
852457fb0b4SSam Clegg                                         ArrayRef<WasmFunction> Functions) {
8539e15f359SSam Clegg   if (Functions.empty())
8549e15f359SSam Clegg     return;
8559e15f359SSam Clegg 
8569e15f359SSam Clegg   SectionBookkeeping Section;
8579e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_CODE);
8586f08c84aSSam Clegg   CodeSectionIndex = Section.Index;
8599e15f359SSam Clegg 
860f17b149dSPeter Collingbourne   encodeULEB128(Functions.size(), W.OS);
8619e15f359SSam Clegg 
8629e15f359SSam Clegg   for (const WasmFunction &Func : Functions) {
863fe6414b0SSam Clegg     auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
8649e15f359SSam Clegg 
8659e15f359SSam Clegg     int64_t Size = 0;
8669e15f359SSam Clegg     if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
8679e15f359SSam Clegg       report_fatal_error(".size expression must be evaluatable");
8689e15f359SSam Clegg 
869f17b149dSPeter Collingbourne     encodeULEB128(Size, W.OS);
870f17b149dSPeter Collingbourne     FuncSection.setSectionOffset(W.OS.tell() - Section.ContentsOffset);
871f17b149dSPeter Collingbourne     Asm.writeSectionData(W.OS, &FuncSection, Layout);
8729e15f359SSam Clegg   }
8739e15f359SSam Clegg 
8749e15f359SSam Clegg   // Apply fixups.
875acd7d2b0SSam Clegg   applyRelocations(CodeRelocations, Section.ContentsOffset);
8769e15f359SSam Clegg 
8779e15f359SSam Clegg   endSection(Section);
8789e15f359SSam Clegg }
8799e15f359SSam Clegg 
8806c899ba6SSam Clegg void WasmObjectWriter::writeDataSection() {
8816c899ba6SSam Clegg   if (DataSegments.empty())
8827c395943SSam Clegg     return;
8839e15f359SSam Clegg 
8849e15f359SSam Clegg   SectionBookkeeping Section;
8859e15f359SSam Clegg   startSection(Section, wasm::WASM_SEC_DATA);
8866f08c84aSSam Clegg   DataSectionIndex = Section.Index;
8879e15f359SSam Clegg 
888f17b149dSPeter Collingbourne   encodeULEB128(DataSegments.size(), W.OS); // count
8897c395943SSam Clegg 
8906c899ba6SSam Clegg   for (const WasmDataSegment &Segment : DataSegments) {
8912e150409SThomas Lively     encodeULEB128(Segment.InitFlags, W.OS); // flags
8922e150409SThomas Lively     if (Segment.InitFlags & wasm::WASM_SEGMENT_HAS_MEMINDEX)
893f17b149dSPeter Collingbourne       encodeULEB128(0, W.OS); // memory index
8942e150409SThomas Lively     if ((Segment.InitFlags & wasm::WASM_SEGMENT_IS_PASSIVE) == 0) {
895f17b149dSPeter Collingbourne       W.OS << char(wasm::WASM_OPCODE_I32_CONST);
896f17b149dSPeter Collingbourne       encodeSLEB128(Segment.Offset, W.OS); // offset
897f17b149dSPeter Collingbourne       W.OS << char(wasm::WASM_OPCODE_END);
8982e150409SThomas Lively     }
899f17b149dSPeter Collingbourne     encodeULEB128(Segment.Data.size(), W.OS); // size
900f17b149dSPeter Collingbourne     Segment.Section->setSectionOffset(W.OS.tell() - Section.ContentsOffset);
901f17b149dSPeter Collingbourne     W.OS << Segment.Data; // data
9027c395943SSam Clegg   }
9039e15f359SSam Clegg 
9049e15f359SSam Clegg   // Apply fixups.
9057c395943SSam Clegg   applyRelocations(DataRelocations, Section.ContentsOffset);
9069e15f359SSam Clegg 
9079e15f359SSam Clegg   endSection(Section);
9089e15f359SSam Clegg }
9099e15f359SSam Clegg 
9106f08c84aSSam Clegg void WasmObjectWriter::writeRelocSection(
9116f08c84aSSam Clegg     uint32_t SectionIndex, StringRef Name,
912f77dc2a8SSam Clegg     std::vector<WasmRelocationEntry> &Relocs) {
9139e15f359SSam Clegg   // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
9149e15f359SSam Clegg   // for descriptions of the reloc sections.
9159e15f359SSam Clegg 
916f77dc2a8SSam Clegg   if (Relocs.empty())
9179e15f359SSam Clegg     return;
9189e15f359SSam Clegg 
919f77dc2a8SSam Clegg   // First, ensure the relocations are sorted in offset order.  In general they
920f77dc2a8SSam Clegg   // should already be sorted since `recordRelocation` is called in offset
921f77dc2a8SSam Clegg   // order, but for the code section we combine many MC sections into single
922f77dc2a8SSam Clegg   // wasm section, and this order is determined by the order of Asm.Symbols()
923f77dc2a8SSam Clegg   // not the sections order.
924f77dc2a8SSam Clegg   std::stable_sort(
925f77dc2a8SSam Clegg       Relocs.begin(), Relocs.end(),
926f77dc2a8SSam Clegg       [](const WasmRelocationEntry &A, const WasmRelocationEntry &B) {
927f77dc2a8SSam Clegg         return (A.Offset + A.FixupSection->getSectionOffset()) <
928f77dc2a8SSam Clegg                (B.Offset + B.FixupSection->getSectionOffset());
929f77dc2a8SSam Clegg       });
930f77dc2a8SSam Clegg 
9319e15f359SSam Clegg   SectionBookkeeping Section;
9326f08c84aSSam Clegg   startCustomSection(Section, std::string("reloc.") + Name.str());
9339e15f359SSam Clegg 
934f17b149dSPeter Collingbourne   encodeULEB128(SectionIndex, W.OS);
935f77dc2a8SSam Clegg   encodeULEB128(Relocs.size(), W.OS);
936f77dc2a8SSam Clegg   for (const WasmRelocationEntry &RelEntry : Relocs) {
937f208f631SHeejin Ahn     uint64_t Offset =
938f208f631SHeejin Ahn         RelEntry.Offset + RelEntry.FixupSection->getSectionOffset();
9396f08c84aSSam Clegg     uint32_t Index = getRelocationIndexValue(RelEntry);
9409e15f359SSam Clegg 
941f17b149dSPeter Collingbourne     W.OS << char(RelEntry.Type);
942f17b149dSPeter Collingbourne     encodeULEB128(Offset, W.OS);
943f17b149dSPeter Collingbourne     encodeULEB128(Index, W.OS);
9446f08c84aSSam Clegg     if (RelEntry.hasAddend())
945f17b149dSPeter Collingbourne       encodeSLEB128(RelEntry.Addend, W.OS);
9469e15f359SSam Clegg   }
9479e15f359SSam Clegg 
9489e15f359SSam Clegg   endSection(Section);
9499e15f359SSam Clegg }
9509e15f359SSam Clegg 
9516a31a0d6SSam Clegg void WasmObjectWriter::writeCustomRelocSections() {
9526a31a0d6SSam Clegg   for (const auto &Sec : CustomSections) {
9536a31a0d6SSam Clegg     auto &Relocations = CustomSectionsRelocations[Sec.Section];
9546a31a0d6SSam Clegg     writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations);
9556a31a0d6SSam Clegg   }
9566a31a0d6SSam Clegg }
9576a31a0d6SSam Clegg 
9589e15f359SSam Clegg void WasmObjectWriter::writeLinkingMetaDataSection(
95986b4a09aSSam Clegg     ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
960ea7caceeSSam Clegg     ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
961ea7caceeSSam Clegg     const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) {
9629e15f359SSam Clegg   SectionBookkeeping Section;
9632322a937SSam Clegg   startCustomSection(Section, "linking");
964f17b149dSPeter Collingbourne   encodeULEB128(wasm::WasmMetadataVersion, W.OS);
9659e15f359SSam Clegg 
9666bb5a41fSSam Clegg   SectionBookkeeping SubSection;
9676c899ba6SSam Clegg   if (SymbolInfos.size() != 0) {
9686c899ba6SSam Clegg     startSection(SubSection, wasm::WASM_SYMBOL_TABLE);
969f17b149dSPeter Collingbourne     encodeULEB128(SymbolInfos.size(), W.OS);
9706c899ba6SSam Clegg     for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) {
971f17b149dSPeter Collingbourne       encodeULEB128(Sym.Kind, W.OS);
972f17b149dSPeter Collingbourne       encodeULEB128(Sym.Flags, W.OS);
9736c899ba6SSam Clegg       switch (Sym.Kind) {
9746c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_FUNCTION:
9756c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_GLOBAL:
976da419bdbSHeejin Ahn       case wasm::WASM_SYMBOL_TYPE_EVENT:
977f17b149dSPeter Collingbourne         encodeULEB128(Sym.ElementIndex, W.OS);
97829874ceaSDan Gohman         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0 ||
97929874ceaSDan Gohman             (Sym.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0)
9806c899ba6SSam Clegg           writeString(Sym.Name);
9816c899ba6SSam Clegg         break;
9826c899ba6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_DATA:
9836c899ba6SSam Clegg         writeString(Sym.Name);
9846c899ba6SSam Clegg         if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) {
985f17b149dSPeter Collingbourne           encodeULEB128(Sym.DataRef.Segment, W.OS);
986f17b149dSPeter Collingbourne           encodeULEB128(Sym.DataRef.Offset, W.OS);
987f17b149dSPeter Collingbourne           encodeULEB128(Sym.DataRef.Size, W.OS);
9886c899ba6SSam Clegg         }
9896c899ba6SSam Clegg         break;
9906a31a0d6SSam Clegg       case wasm::WASM_SYMBOL_TYPE_SECTION: {
9916a31a0d6SSam Clegg         const uint32_t SectionIndex =
9926a31a0d6SSam Clegg             CustomSections[Sym.ElementIndex].OutputIndex;
993f17b149dSPeter Collingbourne         encodeULEB128(SectionIndex, W.OS);
9946a31a0d6SSam Clegg         break;
9956a31a0d6SSam Clegg       }
9966c899ba6SSam Clegg       default:
9976c899ba6SSam Clegg         llvm_unreachable("unexpected kind");
9986c899ba6SSam Clegg       }
999b7787fd0SSam Clegg     }
1000b7787fd0SSam Clegg     endSection(SubSection);
1001b7787fd0SSam Clegg   }
10029e15f359SSam Clegg 
10036c899ba6SSam Clegg   if (DataSegments.size()) {
100463ebb813SSam Clegg     startSection(SubSection, wasm::WASM_SEGMENT_INFO);
1005f17b149dSPeter Collingbourne     encodeULEB128(DataSegments.size(), W.OS);
10066c899ba6SSam Clegg     for (const WasmDataSegment &Segment : DataSegments) {
1007d95ed959SSam Clegg       writeString(Segment.Name);
1008f17b149dSPeter Collingbourne       encodeULEB128(Segment.Alignment, W.OS);
10092e150409SThomas Lively       encodeULEB128(Segment.LinkerFlags, W.OS);
101063ebb813SSam Clegg     }
1011d95ed959SSam Clegg     endSection(SubSection);
1012d95ed959SSam Clegg   }
1013d95ed959SSam Clegg 
1014bafe6902SSam Clegg   if (!InitFuncs.empty()) {
1015bafe6902SSam Clegg     startSection(SubSection, wasm::WASM_INIT_FUNCS);
1016f17b149dSPeter Collingbourne     encodeULEB128(InitFuncs.size(), W.OS);
1017bafe6902SSam Clegg     for (auto &StartFunc : InitFuncs) {
1018f17b149dSPeter Collingbourne       encodeULEB128(StartFunc.first, W.OS);  // priority
1019f17b149dSPeter Collingbourne       encodeULEB128(StartFunc.second, W.OS); // function index
1020bafe6902SSam Clegg     }
1021bafe6902SSam Clegg     endSection(SubSection);
1022bafe6902SSam Clegg   }
1023bafe6902SSam Clegg 
1024ea7caceeSSam Clegg   if (Comdats.size()) {
1025ea7caceeSSam Clegg     startSection(SubSection, wasm::WASM_COMDAT_INFO);
1026f17b149dSPeter Collingbourne     encodeULEB128(Comdats.size(), W.OS);
1027ea7caceeSSam Clegg     for (const auto &C : Comdats) {
1028ea7caceeSSam Clegg       writeString(C.first);
1029f17b149dSPeter Collingbourne       encodeULEB128(0, W.OS); // flags for future use
1030f17b149dSPeter Collingbourne       encodeULEB128(C.second.size(), W.OS);
1031ea7caceeSSam Clegg       for (const WasmComdatEntry &Entry : C.second) {
1032f17b149dSPeter Collingbourne         encodeULEB128(Entry.Kind, W.OS);
1033f17b149dSPeter Collingbourne         encodeULEB128(Entry.Index, W.OS);
1034ea7caceeSSam Clegg       }
1035ea7caceeSSam Clegg     }
1036ea7caceeSSam Clegg     endSection(SubSection);
1037ea7caceeSSam Clegg   }
1038ea7caceeSSam Clegg 
10399e15f359SSam Clegg   endSection(Section);
10409e15f359SSam Clegg }
10419e15f359SSam Clegg 
1042cbda16ebSThomas Lively void WasmObjectWriter::writeCustomSection(WasmCustomSection &CustomSection,
1043cbda16ebSThomas Lively                                           const MCAssembler &Asm,
10446a31a0d6SSam Clegg                                           const MCAsmLayout &Layout) {
1045cfd44a2eSSam Clegg   SectionBookkeeping Section;
10466a31a0d6SSam Clegg   auto *Sec = CustomSection.Section;
10472322a937SSam Clegg   startCustomSection(Section, CustomSection.Name);
10486a31a0d6SSam Clegg 
1049f17b149dSPeter Collingbourne   Sec->setSectionOffset(W.OS.tell() - Section.ContentsOffset);
1050f17b149dSPeter Collingbourne   Asm.writeSectionData(W.OS, Sec, Layout);
10516a31a0d6SSam Clegg 
10526a31a0d6SSam Clegg   CustomSection.OutputContentsOffset = Section.ContentsOffset;
10536a31a0d6SSam Clegg   CustomSection.OutputIndex = Section.Index;
10546a31a0d6SSam Clegg 
1055cfd44a2eSSam Clegg   endSection(Section);
10566a31a0d6SSam Clegg 
10576a31a0d6SSam Clegg   // Apply fixups.
10584d57fbd0SSam Clegg   auto &Relocations = CustomSectionsRelocations[CustomSection.Section];
10594d57fbd0SSam Clegg   applyRelocations(Relocations, CustomSection.OutputContentsOffset);
10606a31a0d6SSam Clegg }
10616a31a0d6SSam Clegg 
10625e3d33a7SSam Clegg uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm &Symbol) {
10635e3d33a7SSam Clegg   assert(Symbol.isFunction());
10645e3d33a7SSam Clegg   assert(TypeIndices.count(&Symbol));
10655e3d33a7SSam Clegg   return TypeIndices[&Symbol];
10665e3d33a7SSam Clegg }
10675e3d33a7SSam Clegg 
1068da419bdbSHeejin Ahn uint32_t WasmObjectWriter::getEventType(const MCSymbolWasm &Symbol) {
1069da419bdbSHeejin Ahn   assert(Symbol.isEvent());
1070da419bdbSHeejin Ahn   assert(TypeIndices.count(&Symbol));
1071da419bdbSHeejin Ahn   return TypeIndices[&Symbol];
1072da419bdbSHeejin Ahn }
1073da419bdbSHeejin Ahn 
107438b12f5eSHeejin Ahn void WasmObjectWriter::registerFunctionType(const MCSymbolWasm &Symbol) {
10755e3d33a7SSam Clegg   assert(Symbol.isFunction());
10765e3d33a7SSam Clegg 
1077da419bdbSHeejin Ahn   WasmSignature S;
107818c56a07SHeejin Ahn   const MCSymbolWasm *ResolvedSym = resolveSymbol(Symbol);
107977a7a380SDerek Schuff   if (auto *Sig = ResolvedSym->getSignature()) {
1080da419bdbSHeejin Ahn     S.Returns = Sig->Returns;
1081da419bdbSHeejin Ahn     S.Params = Sig->Params;
108277a7a380SDerek Schuff   }
10835e3d33a7SSam Clegg 
1084da419bdbSHeejin Ahn   auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
10855e3d33a7SSam Clegg   if (Pair.second)
1086da419bdbSHeejin Ahn     Signatures.push_back(S);
10875e3d33a7SSam Clegg   TypeIndices[&Symbol] = Pair.first->second;
10885e3d33a7SSam Clegg 
1089d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "registerFunctionType: " << Symbol
1090d34e60caSNicola Zaghen                     << " new:" << Pair.second << "\n");
1091d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
10925e3d33a7SSam Clegg }
10935e3d33a7SSam Clegg 
109438b12f5eSHeejin Ahn void WasmObjectWriter::registerEventType(const MCSymbolWasm &Symbol) {
1095da419bdbSHeejin Ahn   assert(Symbol.isEvent());
1096da419bdbSHeejin Ahn 
1097da419bdbSHeejin Ahn   // TODO Currently we don't generate imported exceptions, but if we do, we
1098da419bdbSHeejin Ahn   // should have a way of infering types of imported exceptions.
1099da419bdbSHeejin Ahn   WasmSignature S;
1100da419bdbSHeejin Ahn   if (auto *Sig = Symbol.getSignature()) {
1101da419bdbSHeejin Ahn     S.Returns = Sig->Returns;
1102da419bdbSHeejin Ahn     S.Params = Sig->Params;
1103da419bdbSHeejin Ahn   }
1104da419bdbSHeejin Ahn 
1105da419bdbSHeejin Ahn   auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
1106da419bdbSHeejin Ahn   if (Pair.second)
1107da419bdbSHeejin Ahn     Signatures.push_back(S);
1108da419bdbSHeejin Ahn   TypeIndices[&Symbol] = Pair.first->second;
1109da419bdbSHeejin Ahn 
1110da419bdbSHeejin Ahn   LLVM_DEBUG(dbgs() << "registerEventType: " << Symbol << " new:" << Pair.second
1111da419bdbSHeejin Ahn                     << "\n");
1112da419bdbSHeejin Ahn   LLVM_DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
1113da419bdbSHeejin Ahn }
1114da419bdbSHeejin Ahn 
11154d57fbd0SSam Clegg static bool isInSymtab(const MCSymbolWasm &Sym) {
11164d57fbd0SSam Clegg   if (Sym.isUsedInReloc())
11174d57fbd0SSam Clegg     return true;
11184d57fbd0SSam Clegg 
11194d57fbd0SSam Clegg   if (Sym.isComdat() && !Sym.isDefined())
11204d57fbd0SSam Clegg     return false;
11214d57fbd0SSam Clegg 
11224d57fbd0SSam Clegg   if (Sym.isTemporary() && Sym.getName().empty())
11234d57fbd0SSam Clegg     return false;
11244d57fbd0SSam Clegg 
11254d57fbd0SSam Clegg   if (Sym.isTemporary() && Sym.isData() && !Sym.getSize())
11264d57fbd0SSam Clegg     return false;
11274d57fbd0SSam Clegg 
11284d57fbd0SSam Clegg   if (Sym.isSection())
11294d57fbd0SSam Clegg     return false;
11304d57fbd0SSam Clegg 
11314d57fbd0SSam Clegg   return true;
11324d57fbd0SSam Clegg }
11334d57fbd0SSam Clegg 
1134438390faSPeter Collingbourne uint64_t WasmObjectWriter::writeObject(MCAssembler &Asm,
113518eafb6cSDan Gohman                                        const MCAsmLayout &Layout) {
1136438390faSPeter Collingbourne   uint64_t StartOffset = W.OS.tell();
1137438390faSPeter Collingbourne 
1138d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
1139d934cb88SDan Gohman 
1140d934cb88SDan Gohman   // Collect information from the available symbols.
1141d934cb88SDan Gohman   SmallVector<WasmFunction, 4> Functions;
1142d934cb88SDan Gohman   SmallVector<uint32_t, 4> TableElems;
11438defa952SSam Clegg   SmallVector<wasm::WasmImport, 4> Imports;
11448defa952SSam Clegg   SmallVector<wasm::WasmExport, 4> Exports;
1145da419bdbSHeejin Ahn   SmallVector<wasm::WasmEventType, 1> Events;
11466c899ba6SSam Clegg   SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos;
1147bafe6902SSam Clegg   SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
1148ea7caceeSSam Clegg   std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
11497c395943SSam Clegg   uint32_t DataSize = 0;
1150d934cb88SDan Gohman 
1151f950b24aSSam Clegg   // For now, always emit the memory import, since loads and stores are not
1152f950b24aSSam Clegg   // valid without it. In the future, we could perhaps be more clever and omit
1153f950b24aSSam Clegg   // it if there are no loads or stores.
11548defa952SSam Clegg   wasm::WasmImport MemImport;
11551ed3a046SSam Clegg   MemImport.Module = "env";
11561ed3a046SSam Clegg   MemImport.Field = "__linear_memory";
1157f950b24aSSam Clegg   MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
1158f950b24aSSam Clegg   Imports.push_back(MemImport);
1159f950b24aSSam Clegg 
1160f950b24aSSam Clegg   // For now, always emit the table section, since indirect calls are not
1161f950b24aSSam Clegg   // valid without it. In the future, we could perhaps be more clever and omit
1162f950b24aSSam Clegg   // it if there are no indirect calls.
11638defa952SSam Clegg   wasm::WasmImport TableImport;
11641ed3a046SSam Clegg   TableImport.Module = "env";
11651ed3a046SSam Clegg   TableImport.Field = "__indirect_function_table";
1166f950b24aSSam Clegg   TableImport.Kind = wasm::WASM_EXTERNAL_TABLE;
11676a87ddacSThomas Lively   TableImport.Table.ElemType = wasm::WASM_TYPE_FUNCREF;
1168f950b24aSSam Clegg   Imports.push_back(TableImport);
1169f950b24aSSam Clegg 
1170da419bdbSHeejin Ahn   // Populate SignatureIndices, and Imports and WasmIndices for undefined
1171586320c0SNicholas Wilson   // symbols.  This must be done before populating WasmIndices for defined
1172586320c0SNicholas Wilson   // symbols.
117332ce5ca0SDan Gohman   for (const MCSymbol &S : Asm.symbols()) {
117432ce5ca0SDan Gohman     const auto &WS = static_cast<const MCSymbolWasm &>(S);
117532ce5ca0SDan Gohman 
117632ce5ca0SDan Gohman     // Register types for all functions, including those with private linkage
11779f3fe42eSSam Clegg     // (because wasm always needs a type signature).
117832ce5ca0SDan Gohman     if (WS.isFunction())
117932ce5ca0SDan Gohman       registerFunctionType(WS);
118032ce5ca0SDan Gohman 
1181da419bdbSHeejin Ahn     if (WS.isEvent())
1182da419bdbSHeejin Ahn       registerEventType(WS);
1183da419bdbSHeejin Ahn 
118432ce5ca0SDan Gohman     if (WS.isTemporary())
118532ce5ca0SDan Gohman       continue;
118632ce5ca0SDan Gohman 
118732ce5ca0SDan Gohman     // If the symbol is not defined in this translation unit, import it.
11886c899ba6SSam Clegg     if (!WS.isDefined() && !WS.isComdat()) {
11896c899ba6SSam Clegg       if (WS.isFunction()) {
11908defa952SSam Clegg         wasm::WasmImport Import;
1191f726e445SDan Gohman         Import.Module = WS.getImportModule();
1192f726e445SDan Gohman         Import.Field = WS.getImportName();
119332ce5ca0SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
11948defa952SSam Clegg         Import.SigIndex = getFunctionType(WS);
11956c899ba6SSam Clegg         Imports.push_back(Import);
1196*492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
11976c899ba6SSam Clegg         WasmIndices[&WS] = NumFunctionImports++;
11986c899ba6SSam Clegg       } else if (WS.isGlobal()) {
119915f349f7SNicholas Wilson         if (WS.isWeak())
120015f349f7SNicholas Wilson           report_fatal_error("undefined global symbol cannot be weak");
120115f349f7SNicholas Wilson 
12026c899ba6SSam Clegg         wasm::WasmImport Import;
1203f726e445SDan Gohman         Import.Field = WS.getImportName();
120432ce5ca0SDan Gohman         Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1205*492f7529SSam Clegg         Import.Module = WS.getImportModule();
12066c899ba6SSam Clegg         Import.Global = WS.getGlobalType();
12076c899ba6SSam Clegg         Imports.push_back(Import);
1208*492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
12096c899ba6SSam Clegg         WasmIndices[&WS] = NumGlobalImports++;
1210da419bdbSHeejin Ahn       } else if (WS.isEvent()) {
1211da419bdbSHeejin Ahn         if (WS.isWeak())
1212da419bdbSHeejin Ahn           report_fatal_error("undefined event symbol cannot be weak");
1213da419bdbSHeejin Ahn 
1214da419bdbSHeejin Ahn         wasm::WasmImport Import;
1215f726e445SDan Gohman         Import.Module = WS.getImportModule();
1216f726e445SDan Gohman         Import.Field = WS.getImportName();
1217da419bdbSHeejin Ahn         Import.Kind = wasm::WASM_EXTERNAL_EVENT;
1218da419bdbSHeejin Ahn         Import.Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
1219da419bdbSHeejin Ahn         Import.Event.SigIndex = getEventType(WS);
1220da419bdbSHeejin Ahn         Imports.push_back(Import);
1221*492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
1222da419bdbSHeejin Ahn         WasmIndices[&WS] = NumEventImports++;
122332ce5ca0SDan Gohman       }
122432ce5ca0SDan Gohman     }
122532ce5ca0SDan Gohman   }
122632ce5ca0SDan Gohman 
1227*492f7529SSam Clegg   // Add imports for GOT globals
1228*492f7529SSam Clegg   for (const MCSymbol &S : Asm.symbols()) {
1229*492f7529SSam Clegg     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1230*492f7529SSam Clegg     if (WS.isUsedInGOT()) {
1231*492f7529SSam Clegg       wasm::WasmImport Import;
1232*492f7529SSam Clegg       if (WS.isFunction())
1233*492f7529SSam Clegg         Import.Module = "GOT.func";
1234*492f7529SSam Clegg       else
1235*492f7529SSam Clegg         Import.Module = "GOT.mem";
1236*492f7529SSam Clegg       Import.Field = WS.getName();
1237*492f7529SSam Clegg       Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1238*492f7529SSam Clegg       Import.Global = {wasm::WASM_TYPE_I32, true};
1239*492f7529SSam Clegg       Imports.push_back(Import);
1240*492f7529SSam Clegg       assert(GOTIndices.count(&WS) == 0);
1241*492f7529SSam Clegg       GOTIndices[&WS] = NumGlobalImports++;
1242*492f7529SSam Clegg     }
1243*492f7529SSam Clegg   }
1244*492f7529SSam Clegg 
12454d57fbd0SSam Clegg   // Populate DataSegments and CustomSections, which must be done before
12464d57fbd0SSam Clegg   // populating DataLocations.
1247759631c7SSam Clegg   for (MCSection &Sec : Asm) {
1248759631c7SSam Clegg     auto &Section = static_cast<MCSectionWasm &>(Sec);
12494d57fbd0SSam Clegg     StringRef SectionName = Section.getSectionName();
1250759631c7SSam Clegg 
1251bafe6902SSam Clegg     // .init_array sections are handled specially elsewhere.
12524d57fbd0SSam Clegg     if (SectionName.startswith(".init_array"))
1253bafe6902SSam Clegg       continue;
1254bafe6902SSam Clegg 
12554d57fbd0SSam Clegg     // Code is handled separately
12564d57fbd0SSam Clegg     if (Section.getKind().isText())
12574d57fbd0SSam Clegg       continue;
12584d57fbd0SSam Clegg 
12594d57fbd0SSam Clegg     if (Section.isWasmData()) {
1260329e76d5SSam Clegg       uint32_t SegmentIndex = DataSegments.size();
1261759631c7SSam Clegg       DataSize = alignTo(DataSize, Section.getAlignment());
1262759631c7SSam Clegg       DataSegments.emplace_back();
1263759631c7SSam Clegg       WasmDataSegment &Segment = DataSegments.back();
12644d57fbd0SSam Clegg       Segment.Name = SectionName;
12659b49f36aSSimon Pilgrim       Segment.InitFlags =
12669b49f36aSSimon Pilgrim           Section.getPassive() ? (uint32_t)wasm::WASM_SEGMENT_IS_PASSIVE : 0;
1267759631c7SSam Clegg       Segment.Offset = DataSize;
1268759631c7SSam Clegg       Segment.Section = &Section;
126963ebb813SSam Clegg       addData(Segment.Data, Section);
127056c587adSSam Clegg       Segment.Alignment = Log2_32(Section.getAlignment());
12712e150409SThomas Lively       Segment.LinkerFlags = 0;
1272759631c7SSam Clegg       DataSize += Segment.Data.size();
12736c899ba6SSam Clegg       Section.setSegmentIndex(SegmentIndex);
1274ea7caceeSSam Clegg 
1275ea7caceeSSam Clegg       if (const MCSymbolWasm *C = Section.getGroup()) {
1276ea7caceeSSam Clegg         Comdats[C->getName()].emplace_back(
1277329e76d5SSam Clegg             WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
1278ea7caceeSSam Clegg       }
12794d57fbd0SSam Clegg     } else {
12804d57fbd0SSam Clegg       // Create custom sections
12814d57fbd0SSam Clegg       assert(Sec.getKind().isMetadata());
12824d57fbd0SSam Clegg 
12834d57fbd0SSam Clegg       StringRef Name = SectionName;
12844d57fbd0SSam Clegg 
12854d57fbd0SSam Clegg       // For user-defined custom sections, strip the prefix
12864d57fbd0SSam Clegg       if (Name.startswith(".custom_section."))
12874d57fbd0SSam Clegg         Name = Name.substr(strlen(".custom_section."));
12884d57fbd0SSam Clegg 
12894d57fbd0SSam Clegg       MCSymbol *Begin = Sec.getBeginSymbol();
1290fb807d4dSSam Clegg       if (Begin) {
12914d57fbd0SSam Clegg         WasmIndices[cast<MCSymbolWasm>(Begin)] = CustomSections.size();
1292b210c64bSSam Clegg         if (SectionName != Begin->getName())
1293fb807d4dSSam Clegg           report_fatal_error("section name and begin symbol should match: " +
1294b210c64bSSam Clegg                              Twine(SectionName));
1295fb807d4dSSam Clegg       }
1296cbda16ebSThomas Lively 
1297f6f4f843SThomas Lively       // Separate out the producers and target features sections
1298cbda16ebSThomas Lively       if (Name == "producers") {
1299cbda16ebSThomas Lively         ProducersSection = llvm::make_unique<WasmCustomSection>(Name, &Section);
1300cbda16ebSThomas Lively         continue;
1301cbda16ebSThomas Lively       }
1302f6f4f843SThomas Lively       if (Name == "target_features") {
1303f6f4f843SThomas Lively         TargetFeaturesSection =
1304f6f4f843SThomas Lively             llvm::make_unique<WasmCustomSection>(Name, &Section);
1305f6f4f843SThomas Lively         continue;
1306f6f4f843SThomas Lively       }
1307cbda16ebSThomas Lively 
13084d57fbd0SSam Clegg       CustomSections.emplace_back(Name, &Section);
1309759631c7SSam Clegg     }
13106a31a0d6SSam Clegg   }
13116a31a0d6SSam Clegg 
1312586320c0SNicholas Wilson   // Populate WasmIndices and DataLocations for defined symbols.
1313d934cb88SDan Gohman   for (const MCSymbol &S : Asm.symbols()) {
1314d934cb88SDan Gohman     // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1315d934cb88SDan Gohman     // or used in relocations.
1316d934cb88SDan Gohman     if (S.isTemporary() && S.getName().empty())
1317d934cb88SDan Gohman       continue;
1318b7787fd0SSam Clegg 
1319d934cb88SDan Gohman     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1320d34e60caSNicola Zaghen     LLVM_DEBUG(
1321d34e60caSNicola Zaghen         dbgs() << "MCSymbol: " << toString(WS.getType()) << " '" << S << "'"
1322d34e60caSNicola Zaghen                << " isDefined=" << S.isDefined() << " isExternal="
1323d34e60caSNicola Zaghen                << S.isExternal() << " isTemporary=" << S.isTemporary()
1324d34e60caSNicola Zaghen                << " isWeak=" << WS.isWeak() << " isHidden=" << WS.isHidden()
1325b7787fd0SSam Clegg                << " isVariable=" << WS.isVariable() << "\n");
1326b7787fd0SSam Clegg 
13275e3d33a7SSam Clegg     if (WS.isVariable())
13285e3d33a7SSam Clegg       continue;
13296c899ba6SSam Clegg     if (WS.isComdat() && !WS.isDefined())
13306c899ba6SSam Clegg       continue;
1331b7787fd0SSam Clegg 
1332d934cb88SDan Gohman     if (WS.isFunction()) {
13336c899ba6SSam Clegg       unsigned Index;
1334cd65f698SSam Clegg       if (WS.isDefined()) {
1335b7787fd0SSam Clegg         if (WS.getOffset() != 0)
1336b7787fd0SSam Clegg           report_fatal_error(
1337b7787fd0SSam Clegg               "function sections must contain one function each");
1338b7787fd0SSam Clegg 
133918c56a07SHeejin Ahn         if (WS.getSize() == nullptr)
1340b7787fd0SSam Clegg           report_fatal_error(
1341b7787fd0SSam Clegg               "function symbols must have a size set with .size");
1342b7787fd0SSam Clegg 
13436c899ba6SSam Clegg         // A definition. Write out the function body.
13449f3fe42eSSam Clegg         Index = NumFunctionImports + Functions.size();
1345d934cb88SDan Gohman         WasmFunction Func;
1346da419bdbSHeejin Ahn         Func.SigIndex = getFunctionType(WS);
1347d934cb88SDan Gohman         Func.Sym = &WS;
13486c899ba6SSam Clegg         WasmIndices[&WS] = Index;
1349d934cb88SDan Gohman         Functions.push_back(Func);
13506c899ba6SSam Clegg 
13516c899ba6SSam Clegg         auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
13526c899ba6SSam Clegg         if (const MCSymbolWasm *C = Section.getGroup()) {
13536c899ba6SSam Clegg           Comdats[C->getName()].emplace_back(
13546c899ba6SSam Clegg               WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
13556c899ba6SSam Clegg         }
1356d934cb88SDan Gohman       } else {
1357d934cb88SDan Gohman         // An import; the index was assigned above.
13586c899ba6SSam Clegg         Index = WasmIndices.find(&WS)->second;
1359d934cb88SDan Gohman       }
1360d934cb88SDan Gohman 
1361d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> function index: " << Index << "\n");
1362da419bdbSHeejin Ahn 
13636c899ba6SSam Clegg     } else if (WS.isData()) {
1364f3feb6adSWouter van Oortmerssen       if (!isInSymtab(WS))
1365c38e947eSSam Clegg         continue;
1366c38e947eSSam Clegg 
13676c899ba6SSam Clegg       if (!WS.isDefined()) {
1368d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "  -> segment index: -1"
1369d34e60caSNicola Zaghen                           << "\n");
1370fe6414b0SSam Clegg         continue;
13716c899ba6SSam Clegg       }
1372fe6414b0SSam Clegg 
1373d934cb88SDan Gohman       if (!WS.getSize())
1374c38e947eSSam Clegg         report_fatal_error("data symbols must have a size set with .size: " +
1375c38e947eSSam Clegg                            WS.getName());
1376d934cb88SDan Gohman 
1377d934cb88SDan Gohman       int64_t Size = 0;
1378d934cb88SDan Gohman       if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1379d934cb88SDan Gohman         report_fatal_error(".size expression must be evaluatable");
1380d934cb88SDan Gohman 
1381759631c7SSam Clegg       auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
1382ea7caceeSSam Clegg       assert(DataSection.isWasmData());
13837c395943SSam Clegg 
13846c899ba6SSam Clegg       // For each data symbol, export it in the symtab as a reference to the
13856c899ba6SSam Clegg       // corresponding Wasm data segment.
13866c899ba6SSam Clegg       wasm::WasmDataReference Ref = wasm::WasmDataReference{
13876c899ba6SSam Clegg           DataSection.getSegmentIndex(),
13886c899ba6SSam Clegg           static_cast<uint32_t>(Layout.getSymbolOffset(WS)),
13896c899ba6SSam Clegg           static_cast<uint32_t>(Size)};
13906c899ba6SSam Clegg       DataLocations[&WS] = Ref;
1391d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> segment index: " << Ref.Segment << "\n");
1392da419bdbSHeejin Ahn 
1393a165f2d6SSam Clegg     } else if (WS.isGlobal()) {
13946c899ba6SSam Clegg       // A "true" Wasm global (currently just __stack_pointer)
1395545932beSEric Christopher       if (WS.isDefined())
13966c899ba6SSam Clegg         report_fatal_error("don't yet support defined globals");
13976c899ba6SSam Clegg 
1398545932beSEric Christopher       // An import; the index was assigned above
1399d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> global index: "
1400d34e60caSNicola Zaghen                         << WasmIndices.find(&WS)->second << "\n");
1401da419bdbSHeejin Ahn 
1402da419bdbSHeejin Ahn     } else if (WS.isEvent()) {
1403da419bdbSHeejin Ahn       // C++ exception symbol (__cpp_exception)
1404da419bdbSHeejin Ahn       unsigned Index;
1405da419bdbSHeejin Ahn       if (WS.isDefined()) {
1406da419bdbSHeejin Ahn         Index = NumEventImports + Events.size();
1407da419bdbSHeejin Ahn         wasm::WasmEventType Event;
1408da419bdbSHeejin Ahn         Event.SigIndex = getEventType(WS);
1409da419bdbSHeejin Ahn         Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
1410*492f7529SSam Clegg         assert(WasmIndices.count(&WS) == 0);
1411da419bdbSHeejin Ahn         WasmIndices[&WS] = Index;
1412da419bdbSHeejin Ahn         Events.push_back(Event);
1413da419bdbSHeejin Ahn       } else {
1414da419bdbSHeejin Ahn         // An import; the index was assigned above.
1415*492f7529SSam Clegg         assert(WasmIndices.count(&WS) > 0);
1416da419bdbSHeejin Ahn         Index = WasmIndices.find(&WS)->second;
1417da419bdbSHeejin Ahn       }
1418da419bdbSHeejin Ahn       LLVM_DEBUG(dbgs() << "  -> event index: " << WasmIndices.find(&WS)->second
1419da419bdbSHeejin Ahn                         << "\n");
1420da419bdbSHeejin Ahn 
1421a165f2d6SSam Clegg     } else {
1422a165f2d6SSam Clegg       assert(WS.isSection());
1423d934cb88SDan Gohman     }
1424d934cb88SDan Gohman   }
1425d934cb88SDan Gohman 
1426586320c0SNicholas Wilson   // Populate WasmIndices and DataLocations for aliased symbols.  We need to
1427586320c0SNicholas Wilson   // process these in a separate pass because we need to have processed the
1428586320c0SNicholas Wilson   // target of the alias before the alias itself and the symbols are not
1429586320c0SNicholas Wilson   // necessarily ordered in this way.
1430b7787fd0SSam Clegg   for (const MCSymbol &S : Asm.symbols()) {
1431b7787fd0SSam Clegg     if (!S.isVariable())
1432b7787fd0SSam Clegg       continue;
143331a2c809SSam Clegg 
1434cd65f698SSam Clegg     assert(S.isDefined());
1435b7787fd0SSam Clegg 
14365e3d33a7SSam Clegg     // Find the target symbol of this weak alias and export that index
1437aff1c4dfSSam Clegg     const auto &WS = static_cast<const MCSymbolWasm &>(S);
143818c56a07SHeejin Ahn     const MCSymbolWasm *ResolvedSym = resolveSymbol(WS);
1439d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym
1440d34e60caSNicola Zaghen                       << "'\n");
1441b7787fd0SSam Clegg 
1442ffba00bdSSam Clegg     if (ResolvedSym->isFunction()) {
14436c899ba6SSam Clegg       assert(WasmIndices.count(ResolvedSym) > 0);
14446c899ba6SSam Clegg       uint32_t WasmIndex = WasmIndices.find(ResolvedSym)->second;
1445*492f7529SSam Clegg       assert(WasmIndices.count(&WS) == 0);
14466c899ba6SSam Clegg       WasmIndices[&WS] = WasmIndex;
1447d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> index:" << WasmIndex << "\n");
1448ffba00bdSSam Clegg     } else if (ResolvedSym->isData()) {
14496c899ba6SSam Clegg       assert(DataLocations.count(ResolvedSym) > 0);
14506c899ba6SSam Clegg       const wasm::WasmDataReference &Ref =
14516c899ba6SSam Clegg           DataLocations.find(ResolvedSym)->second;
14526c899ba6SSam Clegg       DataLocations[&WS] = Ref;
1453d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  -> index:" << Ref.Segment << "\n");
14546c899ba6SSam Clegg     } else {
1455da419bdbSHeejin Ahn       report_fatal_error("don't yet support global/event aliases");
14566c899ba6SSam Clegg     }
1457586320c0SNicholas Wilson   }
145831a2c809SSam Clegg 
1459586320c0SNicholas Wilson   // Finally, populate the symbol table itself, in its "natural" order.
1460586320c0SNicholas Wilson   for (const MCSymbol &S : Asm.symbols()) {
1461586320c0SNicholas Wilson     const auto &WS = static_cast<const MCSymbolWasm &>(S);
146225d8e68bSSam Clegg     if (!isInSymtab(WS)) {
146318c56a07SHeejin Ahn       WS.setIndex(InvalidIndex);
1464586320c0SNicholas Wilson       continue;
146525d8e68bSSam Clegg     }
1466d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "adding to symtab: " << WS << "\n");
1467586320c0SNicholas Wilson 
1468586320c0SNicholas Wilson     uint32_t Flags = 0;
1469586320c0SNicholas Wilson     if (WS.isWeak())
1470586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_BINDING_WEAK;
1471586320c0SNicholas Wilson     if (WS.isHidden())
1472586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN;
1473586320c0SNicholas Wilson     if (!WS.isExternal() && WS.isDefined())
1474586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;
1475586320c0SNicholas Wilson     if (WS.isUndefined())
1476586320c0SNicholas Wilson       Flags |= wasm::WASM_SYMBOL_UNDEFINED;
1477d6ef8da3SSam Clegg     if (WS.isExported())
1478d6ef8da3SSam Clegg       Flags |= wasm::WASM_SYMBOL_EXPORTED;
147929874ceaSDan Gohman     if (WS.getName() != WS.getImportName())
148029874ceaSDan Gohman       Flags |= wasm::WASM_SYMBOL_EXPLICIT_NAME;
1481586320c0SNicholas Wilson 
1482586320c0SNicholas Wilson     wasm::WasmSymbolInfo Info;
1483586320c0SNicholas Wilson     Info.Name = WS.getName();
1484586320c0SNicholas Wilson     Info.Kind = WS.getType();
1485586320c0SNicholas Wilson     Info.Flags = Flags;
14864d57fbd0SSam Clegg     if (!WS.isData()) {
14874d57fbd0SSam Clegg       assert(WasmIndices.count(&WS) > 0);
1488586320c0SNicholas Wilson       Info.ElementIndex = WasmIndices.find(&WS)->second;
14894d57fbd0SSam Clegg     } else if (WS.isDefined()) {
14904d57fbd0SSam Clegg       assert(DataLocations.count(&WS) > 0);
1491586320c0SNicholas Wilson       Info.DataRef = DataLocations.find(&WS)->second;
14924d57fbd0SSam Clegg     }
149325d8e68bSSam Clegg     WS.setIndex(SymbolInfos.size());
1494586320c0SNicholas Wilson     SymbolInfos.emplace_back(Info);
1495b7787fd0SSam Clegg   }
1496b7787fd0SSam Clegg 
14976006e091SSam Clegg   {
14986006e091SSam Clegg     auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
1499f9edbe95SSam Clegg       // Functions referenced by a relocation need to put in the table.  This is
1500f9edbe95SSam Clegg       // purely to make the object file's provisional values readable, and is
1501f9edbe95SSam Clegg       // ignored by the linker, which re-calculates the relocations itself.
1502d1152a26SSam Clegg       if (Rel.Type != wasm::R_WASM_TABLE_INDEX_I32 &&
1503d1152a26SSam Clegg           Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB)
1504f9edbe95SSam Clegg         return;
1505f9edbe95SSam Clegg       assert(Rel.Symbol->isFunction());
150618c56a07SHeejin Ahn       const MCSymbolWasm &WS = *resolveSymbol(*Rel.Symbol);
15076c899ba6SSam Clegg       uint32_t FunctionIndex = WasmIndices.find(&WS)->second;
150818c56a07SHeejin Ahn       uint32_t TableIndex = TableElems.size() + InitialTableOffset;
1509f9edbe95SSam Clegg       if (TableIndices.try_emplace(&WS, TableIndex).second) {
1510d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "  -> adding " << WS.getName()
1511f9edbe95SSam Clegg                           << " to table: " << TableIndex << "\n");
15126c899ba6SSam Clegg         TableElems.push_back(FunctionIndex);
15136006e091SSam Clegg         registerFunctionType(WS);
15146006e091SSam Clegg       }
15156006e091SSam Clegg     };
1516970d02c4SDan Gohman 
15176006e091SSam Clegg     for (const WasmRelocationEntry &RelEntry : CodeRelocations)
15186006e091SSam Clegg       HandleReloc(RelEntry);
15196006e091SSam Clegg     for (const WasmRelocationEntry &RelEntry : DataRelocations)
15206006e091SSam Clegg       HandleReloc(RelEntry);
1521d934cb88SDan Gohman   }
1522d934cb88SDan Gohman 
1523bafe6902SSam Clegg   // Translate .init_array section contents into start functions.
1524bafe6902SSam Clegg   for (const MCSection &S : Asm) {
1525bafe6902SSam Clegg     const auto &WS = static_cast<const MCSectionWasm &>(S);
1526bafe6902SSam Clegg     if (WS.getSectionName().startswith(".fini_array"))
1527bafe6902SSam Clegg       report_fatal_error(".fini_array sections are unsupported");
1528bafe6902SSam Clegg     if (!WS.getSectionName().startswith(".init_array"))
1529bafe6902SSam Clegg       continue;
1530bafe6902SSam Clegg     if (WS.getFragmentList().empty())
1531bafe6902SSam Clegg       continue;
1532b210c64bSSam Clegg 
1533b210c64bSSam Clegg     // init_array is expected to contain a single non-empty data fragment
1534b210c64bSSam Clegg     if (WS.getFragmentList().size() != 3)
1535bafe6902SSam Clegg       report_fatal_error("only one .init_array section fragment supported");
1536b210c64bSSam Clegg 
1537b210c64bSSam Clegg     auto IT = WS.begin();
1538b210c64bSSam Clegg     const MCFragment &EmptyFrag = *IT;
1539b210c64bSSam Clegg     if (EmptyFrag.getKind() != MCFragment::FT_Data)
1540b210c64bSSam Clegg       report_fatal_error(".init_array section should be aligned");
1541b210c64bSSam Clegg 
1542b210c64bSSam Clegg     IT = std::next(IT);
1543b210c64bSSam Clegg     const MCFragment &AlignFrag = *IT;
1544bafe6902SSam Clegg     if (AlignFrag.getKind() != MCFragment::FT_Align)
1545bafe6902SSam Clegg       report_fatal_error(".init_array section should be aligned");
1546bafe6902SSam Clegg     if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
1547bafe6902SSam Clegg       report_fatal_error(".init_array section should be aligned for pointers");
1548b210c64bSSam Clegg 
1549b210c64bSSam Clegg     const MCFragment &Frag = *std::next(IT);
1550bafe6902SSam Clegg     if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1551bafe6902SSam Clegg       report_fatal_error("only data supported in .init_array section");
1552b210c64bSSam Clegg 
1553bafe6902SSam Clegg     uint16_t Priority = UINT16_MAX;
15544d57fbd0SSam Clegg     unsigned PrefixLength = strlen(".init_array");
15554d57fbd0SSam Clegg     if (WS.getSectionName().size() > PrefixLength) {
15564d57fbd0SSam Clegg       if (WS.getSectionName()[PrefixLength] != '.')
1557f208f631SHeejin Ahn         report_fatal_error(
1558f208f631SHeejin Ahn             ".init_array section priority should start with '.'");
15594d57fbd0SSam Clegg       if (WS.getSectionName()
15604d57fbd0SSam Clegg               .substr(PrefixLength + 1)
15614d57fbd0SSam Clegg               .getAsInteger(10, Priority))
1562bafe6902SSam Clegg         report_fatal_error("invalid .init_array section priority");
1563bafe6902SSam Clegg     }
1564bafe6902SSam Clegg     const auto &DataFrag = cast<MCDataFragment>(Frag);
1565bafe6902SSam Clegg     const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1566f208f631SHeejin Ahn     for (const uint8_t *
156718c56a07SHeejin Ahn              P = (const uint8_t *)Contents.data(),
156818c56a07SHeejin Ahn             *End = (const uint8_t *)Contents.data() + Contents.size();
156918c56a07SHeejin Ahn          P != End; ++P) {
157018c56a07SHeejin Ahn       if (*P != 0)
1571bafe6902SSam Clegg         report_fatal_error("non-symbolic data in .init_array section");
1572bafe6902SSam Clegg     }
1573bafe6902SSam Clegg     for (const MCFixup &Fixup : DataFrag.getFixups()) {
1574f208f631SHeejin Ahn       assert(Fixup.getKind() ==
1575f208f631SHeejin Ahn              MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
1576bafe6902SSam Clegg       const MCExpr *Expr = Fixup.getValue();
15778fffa1dfSSam Clegg       auto *SymRef = dyn_cast<MCSymbolRefExpr>(Expr);
15788fffa1dfSSam Clegg       if (!SymRef)
1579bafe6902SSam Clegg         report_fatal_error("fixups in .init_array should be symbol references");
15808fffa1dfSSam Clegg       const auto &TargetSym = cast<const MCSymbolWasm>(SymRef->getSymbol());
15818fffa1dfSSam Clegg       if (TargetSym.getIndex() == InvalidIndex)
158225d8e68bSSam Clegg         report_fatal_error("symbols in .init_array should exist in symbtab");
15838fffa1dfSSam Clegg       if (!TargetSym.isFunction())
15848fffa1dfSSam Clegg         report_fatal_error("symbols in .init_array should be for functions");
158525d8e68bSSam Clegg       InitFuncs.push_back(
15868fffa1dfSSam Clegg           std::make_pair(Priority, TargetSym.getIndex()));
1587bafe6902SSam Clegg     }
1588bafe6902SSam Clegg   }
1589bafe6902SSam Clegg 
159018eafb6cSDan Gohman   // Write out the Wasm header.
159118eafb6cSDan Gohman   writeHeader(Asm);
159218eafb6cSDan Gohman 
1593da419bdbSHeejin Ahn   writeTypeSection(Signatures);
1594f950b24aSSam Clegg   writeImportSection(Imports, DataSize, TableElems.size());
15959e15f359SSam Clegg   writeFunctionSection(Functions);
1596f950b24aSSam Clegg   // Skip the "table" section; we import the table instead.
1597f950b24aSSam Clegg   // Skip the "memory" section; we import the memory instead.
1598da419bdbSHeejin Ahn   writeEventSection(Events);
15999e15f359SSam Clegg   writeExportSection(Exports);
16009e15f359SSam Clegg   writeElemSection(TableElems);
1601acd7d2b0SSam Clegg   writeCodeSection(Asm, Layout, Functions);
16026c899ba6SSam Clegg   writeDataSection();
1603cbda16ebSThomas Lively   for (auto &CustomSection : CustomSections)
1604cbda16ebSThomas Lively     writeCustomSection(CustomSection, Asm, Layout);
1605c22bfb6bSNicholas Wilson   writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats);
16066f08c84aSSam Clegg   writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations);
16076f08c84aSSam Clegg   writeRelocSection(DataSectionIndex, "DATA", DataRelocations);
16086a31a0d6SSam Clegg   writeCustomRelocSections();
1609cbda16ebSThomas Lively   if (ProducersSection)
1610cbda16ebSThomas Lively     writeCustomSection(*ProducersSection, Asm, Layout);
1611f6f4f843SThomas Lively   if (TargetFeaturesSection)
1612f6f4f843SThomas Lively     writeCustomSection(*TargetFeaturesSection, Asm, Layout);
1613970d02c4SDan Gohman 
1614d934cb88SDan Gohman   // TODO: Translate the .comment section to the output.
1615438390faSPeter Collingbourne   return W.OS.tell() - StartOffset;
161618eafb6cSDan Gohman }
161718eafb6cSDan Gohman 
161860fbc7ccSLang Hames std::unique_ptr<MCObjectWriter>
16191301a878SLang Hames llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
162018eafb6cSDan Gohman                              raw_pwrite_stream &OS) {
16210917c9e4SDan Gohman   return llvm::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
162218eafb6cSDan Gohman }
1623