1 //===- lib/MC/WasmObjectWriter.cpp - Wasm File Writer ---------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements Wasm object file writer information.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/ADT/STLExtras.h"
15 #include "llvm/ADT/SmallPtrSet.h"
16 #include "llvm/BinaryFormat/Wasm.h"
17 #include "llvm/MC/MCAsmBackend.h"
18 #include "llvm/MC/MCAsmInfo.h"
19 #include "llvm/MC/MCAsmLayout.h"
20 #include "llvm/MC/MCAssembler.h"
21 #include "llvm/MC/MCContext.h"
22 #include "llvm/MC/MCExpr.h"
23 #include "llvm/MC/MCFixupKindInfo.h"
24 #include "llvm/MC/MCObjectFileInfo.h"
25 #include "llvm/MC/MCObjectWriter.h"
26 #include "llvm/MC/MCSectionWasm.h"
27 #include "llvm/MC/MCSymbolWasm.h"
28 #include "llvm/MC/MCValue.h"
29 #include "llvm/MC/MCWasmObjectWriter.h"
30 #include "llvm/Support/Casting.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/LEB128.h"
34 #include "llvm/Support/StringSaver.h"
35 #include <vector>
36 
37 using namespace llvm;
38 
39 #define DEBUG_TYPE "mc"
40 
41 namespace {
42 
43 // For patching purposes, we need to remember where each section starts, both
44 // for patching up the section size field, and for patching up references to
45 // locations within the section.
46 struct SectionBookkeeping {
47   // Where the size of the section is written.
48   uint64_t SizeOffset;
49   // Where the contents of the section starts (after the header).
50   uint64_t ContentsOffset;
51 };
52 
53 // The signature of a wasm function, in a struct capable of being used as a
54 // DenseMap key.
55 struct WasmFunctionType {
56   // Support empty and tombstone instances, needed by DenseMap.
57   enum { Plain, Empty, Tombstone } State;
58 
59   // The return types of the function.
60   SmallVector<wasm::ValType, 1> Returns;
61 
62   // The parameter types of the function.
63   SmallVector<wasm::ValType, 4> Params;
64 
65   WasmFunctionType() : State(Plain) {}
66 
67   bool operator==(const WasmFunctionType &Other) const {
68     return State == Other.State && Returns == Other.Returns &&
69            Params == Other.Params;
70   }
71 };
72 
73 // Traits for using WasmFunctionType in a DenseMap.
74 struct WasmFunctionTypeDenseMapInfo {
75   static WasmFunctionType getEmptyKey() {
76     WasmFunctionType FuncTy;
77     FuncTy.State = WasmFunctionType::Empty;
78     return FuncTy;
79   }
80   static WasmFunctionType getTombstoneKey() {
81     WasmFunctionType FuncTy;
82     FuncTy.State = WasmFunctionType::Tombstone;
83     return FuncTy;
84   }
85   static unsigned getHashValue(const WasmFunctionType &FuncTy) {
86     uintptr_t Value = FuncTy.State;
87     for (wasm::ValType Ret : FuncTy.Returns)
88       Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Ret));
89     for (wasm::ValType Param : FuncTy.Params)
90       Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Param));
91     return Value;
92   }
93   static bool isEqual(const WasmFunctionType &LHS,
94                       const WasmFunctionType &RHS) {
95     return LHS == RHS;
96   }
97 };
98 
99 // A wasm data segment.  A wasm binary contains only a single data section
100 // but that can contain many segments, each with their own virtual location
101 // in memory.  Each MCSection data created by llvm is modeled as its own
102 // wasm data segment.
103 struct WasmDataSegment {
104   MCSectionWasm *Section;
105   StringRef Name;
106   uint32_t Offset;
107   SmallVector<char, 4> Data;
108 };
109 
110 // A wasm import to be written into the import section.
111 struct WasmImport {
112   StringRef ModuleName;
113   StringRef FieldName;
114   unsigned Kind;
115   int32_t Type;
116 };
117 
118 // A wasm function to be written into the function section.
119 struct WasmFunction {
120   int32_t Type;
121   const MCSymbolWasm *Sym;
122 };
123 
124 // A wasm export to be written into the export section.
125 struct WasmExport {
126   StringRef FieldName;
127   unsigned Kind;
128   uint32_t Index;
129 };
130 
131 // A wasm global to be written into the global section.
132 struct WasmGlobal {
133   wasm::ValType Type;
134   bool IsMutable;
135   bool HasImport;
136   uint64_t InitialValue;
137   uint32_t ImportIndex;
138 };
139 
140 // Information about a single relocation.
141 struct WasmRelocationEntry {
142   uint64_t Offset;                  // Where is the relocation.
143   const MCSymbolWasm *Symbol;       // The symbol to relocate with.
144   int64_t Addend;                   // A value to add to the symbol.
145   unsigned Type;                    // The type of the relocation.
146   const MCSectionWasm *FixupSection;// The section the relocation is targeting.
147 
148   WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol,
149                       int64_t Addend, unsigned Type,
150                       const MCSectionWasm *FixupSection)
151       : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type),
152         FixupSection(FixupSection) {}
153 
154   bool hasAddend() const {
155     switch (Type) {
156     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
157     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
158     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
159       return true;
160     default:
161       return false;
162     }
163   }
164 
165   void print(raw_ostream &Out) const {
166     Out << "Off=" << Offset << ", Sym=" << *Symbol << ", Addend=" << Addend
167         << ", Type=" << Type
168         << ", FixupSection=" << FixupSection->getSectionName();
169   }
170 
171 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
172   LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
173 #endif
174 };
175 
176 #if !defined(NDEBUG)
177 raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
178   Rel.print(OS);
179   return OS;
180 }
181 #endif
182 
183 class WasmObjectWriter : public MCObjectWriter {
184   /// Helper struct for containing some precomputed information on symbols.
185   struct WasmSymbolData {
186     const MCSymbolWasm *Symbol;
187     StringRef Name;
188 
189     // Support lexicographic sorting.
190     bool operator<(const WasmSymbolData &RHS) const { return Name < RHS.Name; }
191   };
192 
193   /// The target specific Wasm writer instance.
194   std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
195 
196   // Relocations for fixing up references in the code section.
197   std::vector<WasmRelocationEntry> CodeRelocations;
198 
199   // Relocations for fixing up references in the data section.
200   std::vector<WasmRelocationEntry> DataRelocations;
201 
202   // Index values to use for fixing up call_indirect type indices.
203   // Maps function symbols to the index of the type of the function
204   DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
205   // Maps function symbols to the table element index space. Used
206   // for TABLE_INDEX relocation types (i.e. address taken functions).
207   DenseMap<const MCSymbolWasm *, uint32_t> IndirectSymbolIndices;
208   // Maps function/global symbols to the function/global index space.
209   DenseMap<const MCSymbolWasm *, uint32_t> SymbolIndices;
210 
211   DenseMap<WasmFunctionType, int32_t, WasmFunctionTypeDenseMapInfo>
212       FunctionTypeIndices;
213   SmallVector<WasmFunctionType, 4> FunctionTypes;
214   SmallVector<WasmGlobal, 4> Globals;
215   unsigned NumGlobalImports = 0;
216 
217   // TargetObjectWriter wrappers.
218   bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
219   unsigned getRelocType(const MCValue &Target, const MCFixup &Fixup) const {
220     return TargetObjectWriter->getRelocType(Target, Fixup);
221   }
222 
223   void startSection(SectionBookkeeping &Section, unsigned SectionId,
224                     const char *Name = nullptr);
225   void endSection(SectionBookkeeping &Section);
226 
227 public:
228   WasmObjectWriter(MCWasmObjectTargetWriter *MOTW, raw_pwrite_stream &OS)
229       : MCObjectWriter(OS, /*IsLittleEndian=*/true), TargetObjectWriter(MOTW) {}
230 
231 private:
232   ~WasmObjectWriter() override;
233 
234   void reset() override {
235     CodeRelocations.clear();
236     DataRelocations.clear();
237     TypeIndices.clear();
238     SymbolIndices.clear();
239     IndirectSymbolIndices.clear();
240     FunctionTypeIndices.clear();
241     FunctionTypes.clear();
242     Globals.clear();
243     MCObjectWriter::reset();
244     NumGlobalImports = 0;
245   }
246 
247   void writeHeader(const MCAssembler &Asm);
248 
249   void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
250                         const MCFragment *Fragment, const MCFixup &Fixup,
251                         MCValue Target, uint64_t &FixedValue) override;
252 
253   void executePostLayoutBinding(MCAssembler &Asm,
254                                 const MCAsmLayout &Layout) override;
255 
256   void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
257 
258   void writeString(const StringRef Str) {
259     encodeULEB128(Str.size(), getStream());
260     writeBytes(Str);
261   }
262 
263   void writeValueType(wasm::ValType Ty) {
264     encodeSLEB128(int32_t(Ty), getStream());
265   }
266 
267   void writeTypeSection(ArrayRef<WasmFunctionType> FunctionTypes);
268   void writeImportSection(ArrayRef<WasmImport> Imports);
269   void writeFunctionSection(ArrayRef<WasmFunction> Functions);
270   void writeTableSection(uint32_t NumElements);
271   void writeMemorySection(uint32_t DataSize);
272   void writeGlobalSection();
273   void writeExportSection(ArrayRef<WasmExport> Exports);
274   void writeElemSection(ArrayRef<uint32_t> TableElems);
275   void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
276                         ArrayRef<WasmFunction> Functions);
277   void writeDataSection(ArrayRef<WasmDataSegment> Segments);
278   void writeNameSection(ArrayRef<WasmFunction> Functions,
279                         ArrayRef<WasmImport> Imports,
280                         uint32_t NumFuncImports);
281   void writeCodeRelocSection();
282   void writeDataRelocSection();
283   void writeLinkingMetaDataSection(ArrayRef<WasmDataSegment> Segments,
284                                    uint32_t DataSize, uint32_t DataAlignment,
285                                    ArrayRef<StringRef> WeakSymbols,
286                                    bool HasStackPointer,
287                                    uint32_t StackPointerGlobal);
288 
289   uint32_t getProvisionalValue(const WasmRelocationEntry &RelEntry);
290   void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
291                         uint64_t ContentsOffset);
292 
293   void writeRelocations(ArrayRef<WasmRelocationEntry> Relocations);
294   uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
295   uint32_t getFunctionType(const MCSymbolWasm& Symbol);
296   uint32_t registerFunctionType(const MCSymbolWasm& Symbol);
297 };
298 
299 } // end anonymous namespace
300 
301 WasmObjectWriter::~WasmObjectWriter() {}
302 
303 // Write out a section header and a patchable section size field.
304 void WasmObjectWriter::startSection(SectionBookkeeping &Section,
305                                     unsigned SectionId,
306                                     const char *Name) {
307   assert((Name != nullptr) == (SectionId == wasm::WASM_SEC_CUSTOM) &&
308          "Only custom sections can have names");
309 
310   DEBUG(dbgs() << "startSection " << SectionId << ": " << Name << "\n");
311   encodeULEB128(SectionId, getStream());
312 
313   Section.SizeOffset = getStream().tell();
314 
315   // The section size. We don't know the size yet, so reserve enough space
316   // for any 32-bit value; we'll patch it later.
317   encodeULEB128(UINT32_MAX, getStream());
318 
319   // The position where the section starts, for measuring its size.
320   Section.ContentsOffset = getStream().tell();
321 
322   // Custom sections in wasm also have a string identifier.
323   if (SectionId == wasm::WASM_SEC_CUSTOM) {
324     assert(Name);
325     writeString(StringRef(Name));
326   }
327 }
328 
329 // Now that the section is complete and we know how big it is, patch up the
330 // section size field at the start of the section.
331 void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
332   uint64_t Size = getStream().tell() - Section.ContentsOffset;
333   if (uint32_t(Size) != Size)
334     report_fatal_error("section size does not fit in a uint32_t");
335 
336   DEBUG(dbgs() << "endSection size=" << Size << "\n");
337 
338   // Write the final section size to the payload_len field, which follows
339   // the section id byte.
340   uint8_t Buffer[16];
341   unsigned SizeLen = encodeULEB128(Size, Buffer, 5);
342   assert(SizeLen == 5);
343   getStream().pwrite((char *)Buffer, SizeLen, Section.SizeOffset);
344 }
345 
346 // Emit the Wasm header.
347 void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
348   writeBytes(StringRef(wasm::WasmMagic, sizeof(wasm::WasmMagic)));
349   writeLE32(wasm::WasmVersion);
350 }
351 
352 void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
353                                                 const MCAsmLayout &Layout) {
354 }
355 
356 void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
357                                         const MCAsmLayout &Layout,
358                                         const MCFragment *Fragment,
359                                         const MCFixup &Fixup, MCValue Target,
360                                         uint64_t &FixedValue) {
361   MCAsmBackend &Backend = Asm.getBackend();
362   bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
363                  MCFixupKindInfo::FKF_IsPCRel;
364   const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
365   uint64_t C = Target.getConstant();
366   uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
367   MCContext &Ctx = Asm.getContext();
368 
369   if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
370     assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
371            "Should not have constructed this");
372 
373     // Let A, B and C being the components of Target and R be the location of
374     // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
375     // If it is pcrel, we want to compute (A - B + C - R).
376 
377     // In general, Wasm has no relocations for -B. It can only represent (A + C)
378     // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
379     // replace B to implement it: (A - R - K + C)
380     if (IsPCRel) {
381       Ctx.reportError(
382           Fixup.getLoc(),
383           "No relocation available to represent this relative expression");
384       return;
385     }
386 
387     const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
388 
389     if (SymB.isUndefined()) {
390       Ctx.reportError(Fixup.getLoc(),
391                       Twine("symbol '") + SymB.getName() +
392                           "' can not be undefined in a subtraction expression");
393       return;
394     }
395 
396     assert(!SymB.isAbsolute() && "Should have been folded");
397     const MCSection &SecB = SymB.getSection();
398     if (&SecB != &FixupSection) {
399       Ctx.reportError(Fixup.getLoc(),
400                       "Cannot represent a difference across sections");
401       return;
402     }
403 
404     uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
405     uint64_t K = SymBOffset - FixupOffset;
406     IsPCRel = true;
407     C -= K;
408   }
409 
410   // We either rejected the fixup or folded B into C at this point.
411   const MCSymbolRefExpr *RefA = Target.getSymA();
412   const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr;
413 
414   if (SymA && SymA->isVariable()) {
415     const MCExpr *Expr = SymA->getVariableValue();
416     const auto *Inner = cast<MCSymbolRefExpr>(Expr);
417     if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
418       llvm_unreachable("weakref used in reloc not yet implemented");
419   }
420 
421   // Put any constant offset in an addend. Offsets can be negative, and
422   // LLVM expects wrapping, in contrast to wasm's immediates which can't
423   // be negative and don't wrap.
424   FixedValue = 0;
425 
426   if (SymA)
427     SymA->setUsedInReloc();
428 
429   assert(!IsPCRel);
430   assert(SymA);
431 
432   unsigned Type = getRelocType(Target, Fixup);
433 
434   WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
435   DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
436 
437   if (FixupSection.hasInstructions())
438     CodeRelocations.push_back(Rec);
439   else
440     DataRelocations.push_back(Rec);
441 }
442 
443 // Write X as an (unsigned) LEB value at offset Offset in Stream, padded
444 // to allow patching.
445 static void
446 WritePatchableLEB(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
447   uint8_t Buffer[5];
448   unsigned SizeLen = encodeULEB128(X, Buffer, 5);
449   assert(SizeLen == 5);
450   Stream.pwrite((char *)Buffer, SizeLen, Offset);
451 }
452 
453 // Write X as an signed LEB value at offset Offset in Stream, padded
454 // to allow patching.
455 static void
456 WritePatchableSLEB(raw_pwrite_stream &Stream, int32_t X, uint64_t Offset) {
457   uint8_t Buffer[5];
458   unsigned SizeLen = encodeSLEB128(X, Buffer, 5);
459   assert(SizeLen == 5);
460   Stream.pwrite((char *)Buffer, SizeLen, Offset);
461 }
462 
463 // Write X as a plain integer value at offset Offset in Stream.
464 static void WriteI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
465   uint8_t Buffer[4];
466   support::endian::write32le(Buffer, X);
467   Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
468 }
469 
470 static const MCSymbolWasm* ResolveSymbol(const MCSymbolWasm& Symbol) {
471   if (Symbol.isVariable()) {
472     const MCExpr *Expr = Symbol.getVariableValue();
473     auto *Inner = cast<MCSymbolRefExpr>(Expr);
474     return cast<MCSymbolWasm>(&Inner->getSymbol());
475   }
476   return &Symbol;
477 }
478 
479 // Compute a value to write into the code at the location covered
480 // by RelEntry. This value isn't used by the static linker, since
481 // we have addends; it just serves to make the code more readable
482 // and to make standalone wasm modules directly usable.
483 uint32_t
484 WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) {
485   const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
486 
487   // For undefined symbols, use a hopefully invalid value.
488   if (!Sym->isDefined(/*SetUsed=*/false))
489     return UINT32_MAX;
490 
491   uint32_t GlobalIndex = SymbolIndices[Sym];
492   const WasmGlobal& Global = Globals[GlobalIndex - NumGlobalImports];
493   uint64_t Address = Global.InitialValue + RelEntry.Addend;
494 
495   // Ignore overflow. LLVM allows address arithmetic to silently wrap.
496   uint32_t Value = Address;
497 
498   return Value;
499 }
500 
501 static void addData(SmallVectorImpl<char> &DataBytes,
502                     MCSectionWasm &DataSection, uint32_t &DataAlignment) {
503   DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
504   DataAlignment = std::max(DataAlignment, DataSection.getAlignment());
505   DEBUG(errs() << "addData: " << DataSection.getSectionName() << "\n");
506 
507   for (const MCFragment &Frag : DataSection) {
508     if (Frag.hasInstructions())
509       report_fatal_error("only data supported in data sections");
510 
511     if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
512       if (Align->getValueSize() != 1)
513         report_fatal_error("only byte values supported for alignment");
514       // If nops are requested, use zeros, as this is the data section.
515       uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
516       uint64_t Size = std::min<uint64_t>(alignTo(DataBytes.size(),
517                                                  Align->getAlignment()),
518                                          DataBytes.size() +
519                                              Align->getMaxBytesToEmit());
520       DataBytes.resize(Size, Value);
521     } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
522       DataBytes.insert(DataBytes.end(), Fill->getSize(), Fill->getValue());
523     } else {
524       const auto &DataFrag = cast<MCDataFragment>(Frag);
525       const SmallVectorImpl<char> &Contents = DataFrag.getContents();
526 
527       DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
528     }
529   }
530 
531   DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
532 }
533 
534 uint32_t WasmObjectWriter::getRelocationIndexValue(
535     const WasmRelocationEntry &RelEntry) {
536   switch (RelEntry.Type) {
537   case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
538   case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
539     if (!IndirectSymbolIndices.count(RelEntry.Symbol))
540       report_fatal_error("symbol not found table index space: " +
541                          RelEntry.Symbol->getName());
542     return IndirectSymbolIndices[RelEntry.Symbol];
543   case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
544   case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
545   case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
546   case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
547   case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
548     if (!SymbolIndices.count(RelEntry.Symbol))
549       report_fatal_error("symbol not found function/global index space: " +
550                          RelEntry.Symbol->getName());
551     return SymbolIndices[RelEntry.Symbol];
552   case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
553     if (!TypeIndices.count(RelEntry.Symbol))
554       report_fatal_error("symbol not found in type index space: " +
555                          RelEntry.Symbol->getName());
556     return TypeIndices[RelEntry.Symbol];
557   default:
558     llvm_unreachable("invalid relocation type");
559   }
560 }
561 
562 // Apply the portions of the relocation records that we can handle ourselves
563 // directly.
564 void WasmObjectWriter::applyRelocations(
565     ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
566   raw_pwrite_stream &Stream = getStream();
567   for (const WasmRelocationEntry &RelEntry : Relocations) {
568     uint64_t Offset = ContentsOffset +
569                       RelEntry.FixupSection->getSectionOffset() +
570                       RelEntry.Offset;
571 
572     DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
573     switch (RelEntry.Type) {
574     case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
575     case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
576     case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
577     case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB: {
578       uint32_t Index = getRelocationIndexValue(RelEntry);
579       WritePatchableSLEB(Stream, Index, Offset);
580       break;
581     }
582     case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: {
583       uint32_t Index = getRelocationIndexValue(RelEntry);
584       WriteI32(Stream, Index, Offset);
585       break;
586     }
587     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: {
588       uint32_t Value = getProvisionalValue(RelEntry);
589       WritePatchableSLEB(Stream, Value, Offset);
590       break;
591     }
592     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB: {
593       uint32_t Value = getProvisionalValue(RelEntry);
594       WritePatchableLEB(Stream, Value, Offset);
595       break;
596     }
597     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32: {
598       uint32_t Value = getProvisionalValue(RelEntry);
599       WriteI32(Stream, Value, Offset);
600       break;
601     }
602     default:
603       llvm_unreachable("invalid relocation type");
604     }
605   }
606 }
607 
608 // Write out the portions of the relocation records that the linker will
609 // need to handle.
610 void WasmObjectWriter::writeRelocations(
611     ArrayRef<WasmRelocationEntry> Relocations) {
612   raw_pwrite_stream &Stream = getStream();
613   for (const WasmRelocationEntry& RelEntry : Relocations) {
614 
615     uint64_t Offset = RelEntry.Offset +
616                       RelEntry.FixupSection->getSectionOffset();
617     uint32_t Index = getRelocationIndexValue(RelEntry);
618 
619     encodeULEB128(RelEntry.Type, Stream);
620     encodeULEB128(Offset, Stream);
621     encodeULEB128(Index, Stream);
622     if (RelEntry.hasAddend())
623       encodeSLEB128(RelEntry.Addend, Stream);
624   }
625 }
626 
627 void WasmObjectWriter::writeTypeSection(
628     ArrayRef<WasmFunctionType> FunctionTypes) {
629   if (FunctionTypes.empty())
630     return;
631 
632   SectionBookkeeping Section;
633   startSection(Section, wasm::WASM_SEC_TYPE);
634 
635   encodeULEB128(FunctionTypes.size(), getStream());
636 
637   for (const WasmFunctionType &FuncTy : FunctionTypes) {
638     encodeSLEB128(wasm::WASM_TYPE_FUNC, getStream());
639     encodeULEB128(FuncTy.Params.size(), getStream());
640     for (wasm::ValType Ty : FuncTy.Params)
641       writeValueType(Ty);
642     encodeULEB128(FuncTy.Returns.size(), getStream());
643     for (wasm::ValType Ty : FuncTy.Returns)
644       writeValueType(Ty);
645   }
646 
647   endSection(Section);
648 }
649 
650 void WasmObjectWriter::writeImportSection(ArrayRef<WasmImport> Imports) {
651   if (Imports.empty())
652     return;
653 
654   SectionBookkeeping Section;
655   startSection(Section, wasm::WASM_SEC_IMPORT);
656 
657   encodeULEB128(Imports.size(), getStream());
658   for (const WasmImport &Import : Imports) {
659     writeString(Import.ModuleName);
660     writeString(Import.FieldName);
661 
662     encodeULEB128(Import.Kind, getStream());
663 
664     switch (Import.Kind) {
665     case wasm::WASM_EXTERNAL_FUNCTION:
666       encodeULEB128(Import.Type, getStream());
667       break;
668     case wasm::WASM_EXTERNAL_GLOBAL:
669       encodeSLEB128(int32_t(Import.Type), getStream());
670       encodeULEB128(0, getStream()); // mutability
671       break;
672     default:
673       llvm_unreachable("unsupported import kind");
674     }
675   }
676 
677   endSection(Section);
678 }
679 
680 void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
681   if (Functions.empty())
682     return;
683 
684   SectionBookkeeping Section;
685   startSection(Section, wasm::WASM_SEC_FUNCTION);
686 
687   encodeULEB128(Functions.size(), getStream());
688   for (const WasmFunction &Func : Functions)
689     encodeULEB128(Func.Type, getStream());
690 
691   endSection(Section);
692 }
693 
694 void WasmObjectWriter::writeTableSection(uint32_t NumElements) {
695   // For now, always emit the table section, since indirect calls are not
696   // valid without it. In the future, we could perhaps be more clever and omit
697   // it if there are no indirect calls.
698 
699   SectionBookkeeping Section;
700   startSection(Section, wasm::WASM_SEC_TABLE);
701 
702   encodeULEB128(1, getStream());                       // The number of tables.
703                                                        // Fixed to 1 for now.
704   encodeSLEB128(wasm::WASM_TYPE_ANYFUNC, getStream()); // Type of table
705   encodeULEB128(0, getStream());                       // flags
706   encodeULEB128(NumElements, getStream());             // initial
707 
708   endSection(Section);
709 }
710 
711 void WasmObjectWriter::writeMemorySection(uint32_t DataSize) {
712   // For now, always emit the memory section, since loads and stores are not
713   // valid without it. In the future, we could perhaps be more clever and omit
714   // it if there are no loads or stores.
715   SectionBookkeeping Section;
716   uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
717 
718   startSection(Section, wasm::WASM_SEC_MEMORY);
719   encodeULEB128(1, getStream()); // number of memory spaces
720 
721   encodeULEB128(0, getStream()); // flags
722   encodeULEB128(NumPages, getStream()); // initial
723 
724   endSection(Section);
725 }
726 
727 void WasmObjectWriter::writeGlobalSection() {
728   if (Globals.empty())
729     return;
730 
731   SectionBookkeeping Section;
732   startSection(Section, wasm::WASM_SEC_GLOBAL);
733 
734   encodeULEB128(Globals.size(), getStream());
735   for (const WasmGlobal &Global : Globals) {
736     writeValueType(Global.Type);
737     write8(Global.IsMutable);
738 
739     if (Global.HasImport) {
740       assert(Global.InitialValue == 0);
741       write8(wasm::WASM_OPCODE_GET_GLOBAL);
742       encodeULEB128(Global.ImportIndex, getStream());
743     } else {
744       assert(Global.ImportIndex == 0);
745       write8(wasm::WASM_OPCODE_I32_CONST);
746       encodeSLEB128(Global.InitialValue, getStream()); // offset
747     }
748     write8(wasm::WASM_OPCODE_END);
749   }
750 
751   endSection(Section);
752 }
753 
754 void WasmObjectWriter::writeExportSection(ArrayRef<WasmExport> Exports) {
755   if (Exports.empty())
756     return;
757 
758   SectionBookkeeping Section;
759   startSection(Section, wasm::WASM_SEC_EXPORT);
760 
761   encodeULEB128(Exports.size(), getStream());
762   for (const WasmExport &Export : Exports) {
763     writeString(Export.FieldName);
764     encodeSLEB128(Export.Kind, getStream());
765     encodeULEB128(Export.Index, getStream());
766   }
767 
768   endSection(Section);
769 }
770 
771 void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
772   if (TableElems.empty())
773     return;
774 
775   SectionBookkeeping Section;
776   startSection(Section, wasm::WASM_SEC_ELEM);
777 
778   encodeULEB128(1, getStream()); // number of "segments"
779   encodeULEB128(0, getStream()); // the table index
780 
781   // init expr for starting offset
782   write8(wasm::WASM_OPCODE_I32_CONST);
783   encodeSLEB128(0, getStream());
784   write8(wasm::WASM_OPCODE_END);
785 
786   encodeULEB128(TableElems.size(), getStream());
787   for (uint32_t Elem : TableElems)
788     encodeULEB128(Elem, getStream());
789 
790   endSection(Section);
791 }
792 
793 void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
794                                         const MCAsmLayout &Layout,
795                                         ArrayRef<WasmFunction> Functions) {
796   if (Functions.empty())
797     return;
798 
799   SectionBookkeeping Section;
800   startSection(Section, wasm::WASM_SEC_CODE);
801 
802   encodeULEB128(Functions.size(), getStream());
803 
804   for (const WasmFunction &Func : Functions) {
805     auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
806 
807     int64_t Size = 0;
808     if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
809       report_fatal_error(".size expression must be evaluatable");
810 
811     encodeULEB128(Size, getStream());
812     FuncSection.setSectionOffset(getStream().tell() - Section.ContentsOffset);
813     Asm.writeSectionData(&FuncSection, Layout);
814   }
815 
816   // Apply fixups.
817   applyRelocations(CodeRelocations, Section.ContentsOffset);
818 
819   endSection(Section);
820 }
821 
822 void WasmObjectWriter::writeDataSection(ArrayRef<WasmDataSegment> Segments) {
823   if (Segments.empty())
824     return;
825 
826   SectionBookkeeping Section;
827   startSection(Section, wasm::WASM_SEC_DATA);
828 
829   encodeULEB128(Segments.size(), getStream()); // count
830 
831   for (const WasmDataSegment & Segment : Segments) {
832     encodeULEB128(0, getStream()); // memory index
833     write8(wasm::WASM_OPCODE_I32_CONST);
834     encodeSLEB128(Segment.Offset, getStream()); // offset
835     write8(wasm::WASM_OPCODE_END);
836     encodeULEB128(Segment.Data.size(), getStream()); // size
837     Segment.Section->setSectionOffset(getStream().tell() - Section.ContentsOffset);
838     writeBytes(Segment.Data); // data
839   }
840 
841   // Apply fixups.
842   applyRelocations(DataRelocations, Section.ContentsOffset);
843 
844   endSection(Section);
845 }
846 
847 void WasmObjectWriter::writeNameSection(
848     ArrayRef<WasmFunction> Functions,
849     ArrayRef<WasmImport> Imports,
850     unsigned NumFuncImports) {
851   uint32_t TotalFunctions = NumFuncImports + Functions.size();
852   if (TotalFunctions == 0)
853     return;
854 
855   SectionBookkeeping Section;
856   startSection(Section, wasm::WASM_SEC_CUSTOM, "name");
857   SectionBookkeeping SubSection;
858   startSection(SubSection, wasm::WASM_NAMES_FUNCTION);
859 
860   encodeULEB128(TotalFunctions, getStream());
861   uint32_t Index = 0;
862   for (const WasmImport &Import : Imports) {
863     if (Import.Kind == wasm::WASM_EXTERNAL_FUNCTION) {
864       encodeULEB128(Index, getStream());
865       writeString(Import.FieldName);
866       ++Index;
867     }
868   }
869   for (const WasmFunction &Func : Functions) {
870     encodeULEB128(Index, getStream());
871     writeString(Func.Sym->getName());
872     ++Index;
873   }
874 
875   endSection(SubSection);
876   endSection(Section);
877 }
878 
879 void WasmObjectWriter::writeCodeRelocSection() {
880   // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
881   // for descriptions of the reloc sections.
882 
883   if (CodeRelocations.empty())
884     return;
885 
886   SectionBookkeeping Section;
887   startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.CODE");
888 
889   encodeULEB128(wasm::WASM_SEC_CODE, getStream());
890   encodeULEB128(CodeRelocations.size(), getStream());
891 
892   writeRelocations(CodeRelocations);
893 
894   endSection(Section);
895 }
896 
897 void WasmObjectWriter::writeDataRelocSection() {
898   // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
899   // for descriptions of the reloc sections.
900 
901   if (DataRelocations.empty())
902     return;
903 
904   SectionBookkeeping Section;
905   startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.DATA");
906 
907   encodeULEB128(wasm::WASM_SEC_DATA, getStream());
908   encodeULEB128(DataRelocations.size(), getStream());
909 
910   writeRelocations(DataRelocations);
911 
912   endSection(Section);
913 }
914 
915 void WasmObjectWriter::writeLinkingMetaDataSection(
916     ArrayRef<WasmDataSegment> Segments, uint32_t DataSize,
917     uint32_t DataAlignment, ArrayRef<StringRef> WeakSymbols,
918     bool HasStackPointer, uint32_t StackPointerGlobal) {
919   SectionBookkeeping Section;
920   startSection(Section, wasm::WASM_SEC_CUSTOM, "linking");
921   SectionBookkeeping SubSection;
922 
923   if (HasStackPointer) {
924     startSection(SubSection, wasm::WASM_STACK_POINTER);
925     encodeULEB128(StackPointerGlobal, getStream()); // id
926     endSection(SubSection);
927   }
928 
929   if (WeakSymbols.size() != 0) {
930     startSection(SubSection, wasm::WASM_SYMBOL_INFO);
931     encodeULEB128(WeakSymbols.size(), getStream());
932     for (const StringRef Export: WeakSymbols) {
933       writeString(Export);
934       encodeULEB128(wasm::WASM_SYMBOL_FLAG_WEAK, getStream());
935     }
936     endSection(SubSection);
937   }
938 
939   if (DataSize > 0) {
940     startSection(SubSection, wasm::WASM_DATA_SIZE);
941     encodeULEB128(DataSize, getStream());
942     endSection(SubSection);
943 
944     startSection(SubSection, wasm::WASM_DATA_ALIGNMENT);
945     encodeULEB128(DataAlignment, getStream());
946     endSection(SubSection);
947   }
948 
949   if (Segments.size()) {
950     startSection(SubSection, wasm::WASM_SEGMENT_NAMES);
951     encodeULEB128(Segments.size(), getStream());
952     for (const WasmDataSegment &Segment : Segments)
953       writeString(Segment.Name);
954     endSection(SubSection);
955   }
956 
957   endSection(Section);
958 }
959 
960 uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm& Symbol) {
961   assert(Symbol.isFunction());
962   assert(TypeIndices.count(&Symbol));
963   return TypeIndices[&Symbol];
964 }
965 
966 uint32_t WasmObjectWriter::registerFunctionType(const MCSymbolWasm& Symbol) {
967   assert(Symbol.isFunction());
968 
969   WasmFunctionType F;
970   const MCSymbolWasm* ResolvedSym = ResolveSymbol(Symbol);
971   F.Returns = ResolvedSym->getReturns();
972   F.Params = ResolvedSym->getParams();
973 
974   auto Pair =
975       FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size()));
976   if (Pair.second)
977     FunctionTypes.push_back(F);
978   TypeIndices[&Symbol] = Pair.first->second;
979 
980   DEBUG(dbgs() << "registerFunctionType: " << Symbol << " new:" << Pair.second << "\n");
981   DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
982   return Pair.first->second;
983 }
984 
985 void WasmObjectWriter::writeObject(MCAssembler &Asm,
986                                    const MCAsmLayout &Layout) {
987   DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
988   MCContext &Ctx = Asm.getContext();
989   wasm::ValType PtrType = is64Bit() ? wasm::ValType::I64 : wasm::ValType::I32;
990 
991   // Collect information from the available symbols.
992   SmallVector<WasmFunction, 4> Functions;
993   SmallVector<uint32_t, 4> TableElems;
994   SmallVector<WasmImport, 4> Imports;
995   SmallVector<WasmExport, 4> Exports;
996   SmallVector<StringRef, 4> WeakSymbols;
997   SmallPtrSet<const MCSymbolWasm *, 4> IsAddressTaken;
998   unsigned NumFuncImports = 0;
999   SmallVector<WasmDataSegment, 4> DataSegments;
1000   uint32_t DataAlignment = 1;
1001   uint32_t StackPointerGlobal = 0;
1002   uint32_t DataSize = 0;
1003   bool HasStackPointer = false;
1004 
1005   // Populate the IsAddressTaken set.
1006   for (const WasmRelocationEntry &RelEntry : CodeRelocations) {
1007     switch (RelEntry.Type) {
1008     case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
1009     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
1010       IsAddressTaken.insert(RelEntry.Symbol);
1011       break;
1012     default:
1013       break;
1014     }
1015   }
1016   for (const WasmRelocationEntry &RelEntry : DataRelocations) {
1017     switch (RelEntry.Type) {
1018     case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
1019     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
1020       IsAddressTaken.insert(RelEntry.Symbol);
1021       break;
1022     default:
1023       break;
1024     }
1025   }
1026 
1027   // Populate FunctionTypeIndices and Imports.
1028   for (const MCSymbol &S : Asm.symbols()) {
1029     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1030 
1031     if (WS.isTemporary())
1032       continue;
1033 
1034     if (WS.isFunction())
1035       registerFunctionType(WS);
1036 
1037     // If the symbol is not defined in this translation unit, import it.
1038     if (!WS.isDefined(/*SetUsed=*/false) || WS.isVariable()) {
1039       WasmImport Import;
1040       Import.ModuleName = WS.getModuleName();
1041       Import.FieldName = WS.getName();
1042 
1043       if (WS.isFunction()) {
1044         Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1045         Import.Type = getFunctionType(WS);
1046         SymbolIndices[&WS] = NumFuncImports;
1047         ++NumFuncImports;
1048       } else {
1049         Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1050         Import.Type = int32_t(PtrType);
1051         SymbolIndices[&WS] = NumGlobalImports;
1052         ++NumGlobalImports;
1053       }
1054 
1055       Imports.push_back(Import);
1056     }
1057   }
1058 
1059   // In the special .global_variables section, we've encoded global
1060   // variables used by the function. Translate them into the Globals
1061   // list.
1062   MCSectionWasm *GlobalVars = Ctx.getWasmSection(".global_variables", wasm::WASM_SEC_DATA);
1063   if (!GlobalVars->getFragmentList().empty()) {
1064     if (GlobalVars->getFragmentList().size() != 1)
1065       report_fatal_error("only one .global_variables fragment supported");
1066     const MCFragment &Frag = *GlobalVars->begin();
1067     if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1068       report_fatal_error("only data supported in .global_variables");
1069     const auto &DataFrag = cast<MCDataFragment>(Frag);
1070     if (!DataFrag.getFixups().empty())
1071       report_fatal_error("fixups not supported in .global_variables");
1072     const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1073     for (const uint8_t *p = (const uint8_t *)Contents.data(),
1074                      *end = (const uint8_t *)Contents.data() + Contents.size();
1075          p != end; ) {
1076       WasmGlobal G;
1077       if (end - p < 3)
1078         report_fatal_error("truncated global variable encoding");
1079       G.Type = wasm::ValType(int8_t(*p++));
1080       G.IsMutable = bool(*p++);
1081       G.HasImport = bool(*p++);
1082       if (G.HasImport) {
1083         G.InitialValue = 0;
1084 
1085         WasmImport Import;
1086         Import.ModuleName = (const char *)p;
1087         const uint8_t *nul = (const uint8_t *)memchr(p, '\0', end - p);
1088         if (!nul)
1089           report_fatal_error("global module name must be nul-terminated");
1090         p = nul + 1;
1091         nul = (const uint8_t *)memchr(p, '\0', end - p);
1092         if (!nul)
1093           report_fatal_error("global base name must be nul-terminated");
1094         Import.FieldName = (const char *)p;
1095         p = nul + 1;
1096 
1097         Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1098         Import.Type = int32_t(G.Type);
1099 
1100         G.ImportIndex = NumGlobalImports;
1101         ++NumGlobalImports;
1102 
1103         Imports.push_back(Import);
1104       } else {
1105         unsigned n;
1106         G.InitialValue = decodeSLEB128(p, &n);
1107         G.ImportIndex = 0;
1108         if ((ptrdiff_t)n > end - p)
1109           report_fatal_error("global initial value must be valid SLEB128");
1110         p += n;
1111       }
1112       Globals.push_back(G);
1113     }
1114   }
1115 
1116   // In the special .stack_pointer section, we've encoded the stack pointer
1117   // index.
1118   MCSectionWasm *StackPtr = Ctx.getWasmSection(".stack_pointer", wasm::WASM_SEC_DATA);
1119   if (!StackPtr->getFragmentList().empty()) {
1120     if (StackPtr->getFragmentList().size() != 1)
1121       report_fatal_error("only one .stack_pointer fragment supported");
1122     const MCFragment &Frag = *StackPtr->begin();
1123     if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1124       report_fatal_error("only data supported in .stack_pointer");
1125     const auto &DataFrag = cast<MCDataFragment>(Frag);
1126     if (!DataFrag.getFixups().empty())
1127       report_fatal_error("fixups not supported in .stack_pointer");
1128     const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1129     if (Contents.size() != 4)
1130       report_fatal_error("only one entry supported in .stack_pointer");
1131     HasStackPointer = true;
1132     StackPointerGlobal = NumGlobalImports + *(const int32_t *)Contents.data();
1133   }
1134 
1135   for (MCSection &Sec : Asm) {
1136     auto &Section = static_cast<MCSectionWasm &>(Sec);
1137     if (Section.getType() != wasm::WASM_SEC_DATA)
1138       continue;
1139 
1140     DataSize = alignTo(DataSize, Section.getAlignment());
1141     DataSegments.emplace_back();
1142     WasmDataSegment &Segment = DataSegments.back();
1143     Segment.Name = Section.getSectionName();
1144     Segment.Offset = DataSize;
1145     Segment.Section = &Section;
1146     addData(Segment.Data, Section, DataAlignment);
1147     DataSize += Segment.Data.size();
1148     Section.setMemoryOffset(Segment.Offset);
1149   }
1150 
1151   // Handle regular defined and undefined symbols.
1152   for (const MCSymbol &S : Asm.symbols()) {
1153     // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1154     // or used in relocations.
1155     if (S.isTemporary() && S.getName().empty())
1156       continue;
1157 
1158     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1159     DEBUG(dbgs() << "MCSymbol: '" << S << "'"
1160                  << " isDefined=" << S.isDefined() << " isExternal="
1161                  << S.isExternal() << " isTemporary=" << S.isTemporary()
1162                  << " isFunction=" << WS.isFunction()
1163                  << " isWeak=" << WS.isWeak()
1164                  << " isVariable=" << WS.isVariable() << "\n");
1165 
1166     if (WS.isWeak())
1167       WeakSymbols.push_back(WS.getName());
1168 
1169     if (WS.isVariable())
1170       continue;
1171 
1172     unsigned Index;
1173 
1174     if (WS.isFunction()) {
1175       if (WS.isDefined(/*SetUsed=*/false)) {
1176         if (WS.getOffset() != 0)
1177           report_fatal_error(
1178               "function sections must contain one function each");
1179 
1180         if (WS.getSize() == 0)
1181           report_fatal_error(
1182               "function symbols must have a size set with .size");
1183 
1184         // A definition. Take the next available index.
1185         Index = NumFuncImports + Functions.size();
1186 
1187         // Prepare the function.
1188         WasmFunction Func;
1189         Func.Type = getFunctionType(WS);
1190         Func.Sym = &WS;
1191         SymbolIndices[&WS] = Index;
1192         Functions.push_back(Func);
1193       } else {
1194         // An import; the index was assigned above.
1195         Index = SymbolIndices.find(&WS)->second;
1196       }
1197 
1198       DEBUG(dbgs() << "  -> function index: " << Index << "\n");
1199 
1200       // If needed, prepare the function to be called indirectly.
1201       if (IsAddressTaken.count(&WS) != 0) {
1202         IndirectSymbolIndices[&WS] = TableElems.size();
1203         DEBUG(dbgs() << "  -> adding to table: " << TableElems.size() << "\n");
1204         TableElems.push_back(Index);
1205       }
1206     } else {
1207       if (WS.isTemporary() && !WS.getSize())
1208         continue;
1209 
1210       if (!WS.isDefined(/*SetUsed=*/false))
1211         continue;
1212 
1213       if (!WS.getSize())
1214         report_fatal_error("data symbols must have a size set with .size: " +
1215                            WS.getName());
1216 
1217       int64_t Size = 0;
1218       if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1219         report_fatal_error(".size expression must be evaluatable");
1220 
1221       // For each global, prepare a corresponding wasm global holding its
1222       // address.  For externals these will also be named exports.
1223       Index = NumGlobalImports + Globals.size();
1224       auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
1225 
1226       WasmGlobal Global;
1227       Global.Type = PtrType;
1228       Global.IsMutable = false;
1229       Global.HasImport = false;
1230       Global.InitialValue = DataSection.getMemoryOffset() + Layout.getSymbolOffset(WS);
1231       Global.ImportIndex = 0;
1232       SymbolIndices[&WS] = Index;
1233       DEBUG(dbgs() << "  -> global index: " << Index << "\n");
1234       Globals.push_back(Global);
1235     }
1236 
1237     // If the symbol is visible outside this translation unit, export it.
1238     if ((WS.isExternal() && WS.isDefined(/*SetUsed=*/false))) {
1239       WasmExport Export;
1240       Export.FieldName = WS.getName();
1241       Export.Index = Index;
1242       if (WS.isFunction())
1243         Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1244       else
1245         Export.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1246       DEBUG(dbgs() << "  -> export " << Exports.size() << "\n");
1247       Exports.push_back(Export);
1248     }
1249   }
1250 
1251   // Handle weak aliases. We need to process these in a separate pass because
1252   // we need to have processed the target of the alias before the alias itself
1253   // and the symbols are not necessarily ordered in this way.
1254   for (const MCSymbol &S : Asm.symbols()) {
1255     if (!S.isVariable())
1256       continue;
1257     assert(S.isDefined(/*SetUsed=*/false));
1258 
1259     // Find the target symbol of this weak alias and export that index
1260     const auto &WS = static_cast<const MCSymbolWasm &>(S);
1261     const MCSymbolWasm *ResolvedSym = ResolveSymbol(WS);
1262     DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym << "'\n");
1263     assert(SymbolIndices.count(ResolvedSym) > 0);
1264     uint32_t Index = SymbolIndices.find(ResolvedSym)->second;
1265     DEBUG(dbgs() << "  -> index:" << Index << "\n");
1266 
1267     WasmExport Export;
1268     Export.FieldName = WS.getName();
1269     Export.Index = Index;
1270     if (WS.isFunction())
1271       Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1272     else
1273       Export.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1274     DEBUG(dbgs() << "  -> export " << Exports.size() << "\n");
1275     Exports.push_back(Export);
1276   }
1277 
1278   // Add types for indirect function calls.
1279   for (const WasmRelocationEntry &Fixup : CodeRelocations) {
1280     if (Fixup.Type != wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB)
1281       continue;
1282 
1283     registerFunctionType(*Fixup.Symbol);
1284   }
1285 
1286   // Write out the Wasm header.
1287   writeHeader(Asm);
1288 
1289   writeTypeSection(FunctionTypes);
1290   writeImportSection(Imports);
1291   writeFunctionSection(Functions);
1292   writeTableSection(TableElems.size());
1293   writeMemorySection(DataSize);
1294   writeGlobalSection();
1295   writeExportSection(Exports);
1296   // TODO: Start Section
1297   writeElemSection(TableElems);
1298   writeCodeSection(Asm, Layout, Functions);
1299   writeDataSection(DataSegments);
1300   writeNameSection(Functions, Imports, NumFuncImports);
1301   writeCodeRelocSection();
1302   writeDataRelocSection();
1303   writeLinkingMetaDataSection(DataSegments, DataSize, DataAlignment,
1304                               WeakSymbols, HasStackPointer, StackPointerGlobal);
1305 
1306   // TODO: Translate the .comment section to the output.
1307   // TODO: Translate debug sections to the output.
1308 }
1309 
1310 MCObjectWriter *llvm::createWasmObjectWriter(MCWasmObjectTargetWriter *MOTW,
1311                                              raw_pwrite_stream &OS) {
1312   return new WasmObjectWriter(MOTW, OS);
1313 }
1314