[WebAssembly] Add COMDAT support

This adds COMDAT support to the Wasm object-file format.
Spec: https://github.com/WebAssembly/tool-conventions/pull/31

Corresponding LLD change:
https://bugs.llvm.org/show_bug.cgi?id=35533, and D40845

Patch by Nicholas Wilson

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

llvm-svn: 322135
diff --git a/llvm/tools/obj2yaml/wasm2yaml.cpp b/llvm/tools/obj2yaml/wasm2yaml.cpp
index 476fb6c..e3577d4 100644
--- a/llvm/tools/obj2yaml/wasm2yaml.cpp
+++ b/llvm/tools/obj2yaml/wasm2yaml.cpp
@@ -65,17 +65,34 @@
     CustomSec = std::move(NameSec);
   } else if (WasmSec.Name == "linking") {
     std::unique_ptr<WasmYAML::LinkingSection> LinkingSec = make_unique<WasmYAML::LinkingSection>();
-    size_t Index = 0;
+    std::map<StringRef,size_t> ComdatIndexes;
+    for (StringRef ComdatName : Obj.comdats()) {
+      ComdatIndexes[ComdatName] = LinkingSec->Comdats.size();
+      LinkingSec->Comdats.emplace_back(WasmYAML::Comdat{ComdatName, {}});
+    }
+    for (auto &Func : Obj.functions()) {
+      if (!Func.Comdat.empty()) {
+        auto &Comdat = LinkingSec->Comdats[ComdatIndexes[Func.Comdat]];
+        Comdat.Entries.emplace_back(
+                WasmYAML::ComdatEntry{wasm::WASM_COMDAT_FUNCTION, Func.Index});
+      }
+    }
+    uint32_t SegmentIndex = 0;
     for (const object::WasmSegment &Segment : Obj.dataSegments()) {
       if (!Segment.Data.Name.empty()) {
         WasmYAML::SegmentInfo SegmentInfo;
         SegmentInfo.Name = Segment.Data.Name;
-        SegmentInfo.Index = Index;
+        SegmentInfo.Index = SegmentIndex;
         SegmentInfo.Alignment = Segment.Data.Alignment;
         SegmentInfo.Flags = Segment.Data.Flags;
         LinkingSec->SegmentInfos.push_back(SegmentInfo);
       }
-      Index++;
+      if (!Segment.Data.Comdat.empty()) {
+        auto &Comdat = LinkingSec->Comdats[ComdatIndexes[Segment.Data.Comdat]];
+        Comdat.Entries.emplace_back(
+            WasmYAML::ComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
+      }
+      SegmentIndex++;
     }
     for (const object::SymbolRef& Sym: Obj.symbols()) {
       const object::WasmSymbol Symbol = Obj.getWasmSymbol(Sym);