[ELF] - Fix "--symbol-ordering-file doesn't work with linker scripts"

This is PR33889,

Patch adds support of combination of linkerscript and
-symbol-ordering-file option.

If no sorting commands are present in script inside section declaration
and no --sort-section option specified, code uses sorting from ordering 
file if any exist.

Differential revision: https://reviews.llvm.org/D35843

llvm-svn: 310045
diff --git a/lld/ELF/LinkerScript.cpp b/lld/ELF/LinkerScript.cpp
index d7da4a2..71d8f32 100644
--- a/lld/ELF/LinkerScript.cpp
+++ b/lld/ELF/LinkerScript.cpp
@@ -228,6 +228,29 @@
     std::stable_sort(Begin, End, getComparator(K));
 }
 
+static llvm::DenseMap<SectionBase *, int> getSectionOrder() {
+  switch (Config->EKind) {
+  case ELF32LEKind:
+    return buildSectionOrder<ELF32LE>();
+  case ELF32BEKind:
+    return buildSectionOrder<ELF32BE>();
+  case ELF64LEKind:
+    return buildSectionOrder<ELF64LE>();
+  case ELF64BEKind:
+    return buildSectionOrder<ELF64BE>();
+  default:
+    llvm_unreachable("unknown ELF type");
+  }
+}
+
+static void sortBySymbolOrder(InputSection **Begin, InputSection **End) {
+  if (Config->SymbolOrderingFile.empty())
+    return;
+  static llvm::DenseMap<SectionBase *, int> Order = getSectionOrder();
+  MutableArrayRef<InputSection *> In(Begin, End - Begin);
+  sortByOrder(In, [&](InputSectionBase *S) { return Order.lookup(S); });
+}
+
 // Compute and remember which sections the InputSectionDescription matches.
 std::vector<InputSection *>
 LinkerScript::computeInputSections(const InputSectionDescription *Cmd) {
@@ -273,8 +296,15 @@
     //    --sort-section is handled as an inner SORT command.
     // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
     // 4. If no SORT command is given, sort according to --sort-section.
+    // 5. If no SORT commands are given and --sort-section is not specified,
+    //    apply sorting provided by --symbol-ordering-file if any exist.
     InputSection **Begin = Ret.data() + SizeBefore;
     InputSection **End = Ret.data() + Ret.size();
+    if (Pat.SortOuter == SortSectionPolicy::Default &&
+        Config->SortSection == SortSectionPolicy::Default) {
+      sortBySymbolOrder(Begin, End);
+      continue;
+    }
     if (Pat.SortOuter != SortSectionPolicy::None) {
       if (Pat.SortInner == SortSectionPolicy::Default)
         sortSections(Begin, End, Config->SortSection);