Move clearOutputSections earlier.

Now removeUnusedSyntheticSections operates entirely on the linker
script.

llvm-svn: 307043
diff --git a/lld/ELF/Writer.cpp b/lld/ELF/Writer.cpp
index 551ca26..3a8af2d 100644
--- a/lld/ELF/Writer.cpp
+++ b/lld/ELF/Writer.cpp
@@ -1132,7 +1132,7 @@
 // to make them visible from linkescript side. But not all sections are always
 // required to be in output. For example we don't need dynamic section content
 // sometimes. This function filters out such unused sections from the output.
-static void removeUnusedSyntheticSections(std::vector<OutputSection *> &V) {
+static void removeUnusedSyntheticSections() {
   // All input synthetic sections that can be empty are placed after
   // all regular ones. We iterate over them all and exit at first
   // non-synthetic.
@@ -1145,12 +1145,24 @@
       continue;
     if ((SS == InX::Got || SS == InX::MipsGot) && ElfSym::GlobalOffsetTable)
       continue;
-    OS->Sections.erase(std::find(OS->Sections.begin(), OS->Sections.end(), SS));
-    SS->Live = false;
+
+    OutputSectionCommand *Cmd = Script->getCmd(OS);
+    BaseCommand **Empty = nullptr;
+    for (BaseCommand *&B : Cmd->Commands) {
+      if (auto *ISD = dyn_cast<InputSectionDescription>(B)) {
+        auto I = std::find(ISD->Sections.begin(), ISD->Sections.end(), SS);
+        if (I != ISD->Sections.end())
+          ISD->Sections.erase(I);
+        if (ISD->Sections.empty())
+          Empty = &B;
+      }
+    }
+    if (Empty)
+      Cmd->Commands.erase(std::vector<BaseCommand *>::iterator(Empty));
+
     // If there are no other sections in the output section, remove it from the
     // output.
-    if (OS->Sections.empty()) {
-      V.erase(std::find(V.begin(), V.end(), OS));
+    if (Cmd->Commands.empty()) {
       // Also remove script commands matching the output section.
       auto &Cmds = Script->Opt.Commands;
       auto I = std::remove_if(Cmds.begin(), Cmds.end(), [&](BaseCommand *Cmd) {
@@ -1227,9 +1239,9 @@
     return;
 
   addPredefinedSections();
-  removeUnusedSyntheticSections(OutputSections);
-
   clearOutputSections();
+  removeUnusedSyntheticSections();
+
   sortSections();
 
   // Now that we have the final list, create a list of all the