OSDN Git Service

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