Reland "[WebAssembly] Add support for naming wasm data segments"

Add adds support for naming data segments.  This is useful
useful linkers so that they can merge similar sections.

Differential Revision: https://reviews.llvm.org/D37886

llvm-svn: 313795
diff --git a/llvm/lib/MC/WasmObjectWriter.cpp b/llvm/lib/MC/WasmObjectWriter.cpp
index 7ed20d32..6ec9324 100644
--- a/llvm/lib/MC/WasmObjectWriter.cpp
+++ b/llvm/lib/MC/WasmObjectWriter.cpp
@@ -102,6 +102,7 @@
 // wasm data segment.
 struct WasmDataSegment {
   MCSectionWasm *Section;
+  StringRef Name;
   uint32_t Offset;
   SmallVector<char, 4> Data;
 };
@@ -279,7 +280,8 @@
                         uint32_t NumFuncImports);
   void writeCodeRelocSection();
   void writeDataRelocSection();
-  void writeLinkingMetaDataSection(uint32_t DataSize, uint32_t DataAlignment,
+  void writeLinkingMetaDataSection(ArrayRef<WasmDataSegment> Segments,
+                                   uint32_t DataSize, uint32_t DataAlignment,
                                    ArrayRef<StringRef> WeakSymbols,
                                    bool HasStackPointer,
                                    uint32_t StackPointerGlobal);
@@ -911,7 +913,8 @@
 }
 
 void WasmObjectWriter::writeLinkingMetaDataSection(
-    uint32_t DataSize, uint32_t DataAlignment, ArrayRef<StringRef> WeakSymbols,
+    ArrayRef<WasmDataSegment> Segments, uint32_t DataSize,
+    uint32_t DataAlignment, ArrayRef<StringRef> WeakSymbols,
     bool HasStackPointer, uint32_t StackPointerGlobal) {
   SectionBookkeeping Section;
   startSection(Section, wasm::WASM_SEC_CUSTOM, "linking");
@@ -943,6 +946,14 @@
     endSection(SubSection);
   }
 
+  if (Segments.size()) {
+    startSection(SubSection, wasm::WASM_SEGMENT_NAMES);
+    encodeULEB128(Segments.size(), getStream());
+    for (const WasmDataSegment &Segment : Segments)
+      writeString(Segment.Name);
+    endSection(SubSection);
+  }
+
   endSection(Section);
 }
 
@@ -1129,6 +1140,7 @@
     DataSize = alignTo(DataSize, Section.getAlignment());
     DataSegments.emplace_back();
     WasmDataSegment &Segment = DataSegments.back();
+    Segment.Name = Section.getSectionName();
     Segment.Offset = DataSize;
     Segment.Section = &Section;
     addData(Segment.Data, Section, DataAlignment);
@@ -1288,7 +1300,8 @@
   writeNameSection(Functions, Imports, NumFuncImports);
   writeCodeRelocSection();
   writeDataRelocSection();
-  writeLinkingMetaDataSection(DataSize, DataAlignment, WeakSymbols, HasStackPointer, StackPointerGlobal);
+  writeLinkingMetaDataSection(DataSegments, DataSize, DataAlignment,
+                              WeakSymbols, HasStackPointer, StackPointerGlobal);
 
   // TODO: Translate the .comment section to the output.
   // TODO: Translate debug sections to the output.