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