Fix an annoying little bug I found while debugging another LTO issue. Gold
requires the -plugin to come before any -plugin-opt options, we were passing
them the other way around. With this one can run (for example):

clang -o foo foo.c -O4 -Wl,-plugin-opt=generate-api-file

git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@154357 91177308-0d34-0410-b5e6-96231b3b80d8
diff --git a/lib/Driver/Tools.cpp b/lib/Driver/Tools.cpp
index 3a1778d..e575092 100644
--- a/lib/Driver/Tools.cpp
+++ b/lib/Driver/Tools.cpp
@@ -5259,6 +5259,15 @@
        i != e; ++i)
     CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + *i));
 
+  // Tell the linker to load the plugin. This has to come before AddLinkerInputs
+  // as gold requires -plugin to come before any -plugin-opt that -Wl might
+  // forward.
+  if (D.IsUsingLTO(Args) || Args.hasArg(options::OPT_use_gold_plugin)) {
+    CmdArgs.push_back("-plugin");
+    std::string Plugin = ToolChain.getDriver().Dir + "/../lib/LLVMgold.so";
+    CmdArgs.push_back(Args.MakeArgString(Plugin));
+  }
+
   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
 
   if (D.CCCIsCXX && !Args.hasArg(options::OPT_nostdlib)) {
@@ -5307,12 +5316,6 @@
 
   addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
 
-  if (D.IsUsingLTO(Args) || Args.hasArg(options::OPT_use_gold_plugin)) {
-    CmdArgs.push_back("-plugin");
-    std::string Plugin = ToolChain.getDriver().Dir + "/../lib/LLVMgold.so";
-    CmdArgs.push_back(Args.MakeArgString(Plugin));
-  }
-
   C.addCommand(new Command(JA, *this, ToolChain.Linker.c_str(), CmdArgs));
 }
 
diff --git a/test/Driver/gold-lto.c b/test/Driver/gold-lto.c
new file mode 100644
index 0000000..646a59b
--- /dev/null
+++ b/test/Driver/gold-lto.c
@@ -0,0 +1,6 @@
+// RUN: touch %t.o
+// RUN: %clang -target x86_64-pc-linux-gnu -### %t.o -O4 -Wl,-plugin-opt=foo 2> %t.log
+// RUN: FileCheck %s < %t.log
+
+// CHECK: "-plugin" "{{.*}}/LLVMgold.so"
+// CHECK: "-plugin-arg=foo"