Update aosp/master clang for rebase to r230699.

Change-Id: I6a546ab3d4ae37119eebb735e102cca4f80ab520
diff --git a/lib/Driver/Driver.cpp b/lib/Driver/Driver.cpp
index d459e4b..61aaa97 100644
--- a/lib/Driver/Driver.cpp
+++ b/lib/Driver/Driver.cpp
@@ -17,6 +17,7 @@
 #include "clang/Driver/DriverDiagnostic.h"
 #include "clang/Driver/Job.h"
 #include "clang/Driver/Options.h"
+#include "clang/Driver/SanitizerArgs.h"
 #include "clang/Driver/Tool.h"
 #include "clang/Driver/ToolChain.h"
 #include "llvm/ADT/ArrayRef.h"
@@ -44,20 +45,17 @@
 using namespace clang;
 using namespace llvm::opt;
 
-Driver::Driver(StringRef ClangExecutable,
-               StringRef DefaultTargetTriple,
+Driver::Driver(StringRef ClangExecutable, StringRef DefaultTargetTriple,
                DiagnosticsEngine &Diags)
-  : Opts(createDriverOptTable()), Diags(Diags), Mode(GCCMode),
-    ClangExecutable(ClangExecutable), SysRoot(DEFAULT_SYSROOT),
-    UseStdLib(true), DefaultTargetTriple(DefaultTargetTriple),
-    DefaultImageName("a.out"),
-    DriverTitle("clang LLVM compiler"),
-    CCPrintOptionsFilename(nullptr), CCPrintHeadersFilename(nullptr),
-    CCLogDiagnosticsFilename(nullptr),
-    CCCPrintBindings(false),
-    CCPrintHeaders(false), CCLogDiagnostics(false),
-    CCGenDiagnostics(false), CCCGenericGCCName(""), CheckInputsExist(true),
-    CCCUsePCH(true), SuppressMissingInputWarning(false) {
+    : Opts(createDriverOptTable()), Diags(Diags), Mode(GCCMode),
+      SaveTemps(SaveTempsNone), ClangExecutable(ClangExecutable),
+      SysRoot(DEFAULT_SYSROOT), UseStdLib(true),
+      DefaultTargetTriple(DefaultTargetTriple),
+      DriverTitle("clang LLVM compiler"), CCPrintOptionsFilename(nullptr),
+      CCPrintHeadersFilename(nullptr), CCLogDiagnosticsFilename(nullptr),
+      CCCPrintBindings(false), CCPrintHeaders(false), CCLogDiagnostics(false),
+      CCGenDiagnostics(false), CCCGenericGCCName(""), CheckInputsExist(true),
+      CCCUsePCH(true), SuppressMissingInputWarning(false) {
 
   Name = llvm::sys::path::stem(ClangExecutable);
   Dir  = llvm::sys::path::parent_path(ClangExecutable);
@@ -65,10 +63,13 @@
   // Compute the path to the resource directory.
   StringRef ClangResourceDir(CLANG_RESOURCE_DIR);
   SmallString<128> P(Dir);
-  if (ClangResourceDir != "")
+  if (ClangResourceDir != "") {
     llvm::sys::path::append(P, ClangResourceDir);
-  else
-    llvm::sys::path::append(P, "..", "lib", "clang", CLANG_VERSION_STRING);
+  } else {
+    StringRef ClangLibdirSuffix(CLANG_LIBDIR_SUFFIX);
+    llvm::sys::path::append(P, "..", Twine("lib") + ClangLibdirSuffix, "clang",
+                            CLANG_VERSION_STRING);
+  }
   ResourceDir = P.str();
 }
 
@@ -125,9 +126,7 @@
       << Args->getArgString(MissingArgIndex) << MissingArgCount;
 
   // Check for unsupported options.
-  for (ArgList::const_iterator it = Args->begin(), ie = Args->end();
-       it != ie; ++it) {
-    Arg *A = *it;
+  for (const Arg *A : *Args) {
     if (A->getOption().hasFlag(options::Unsupported)) {
       Diag(clang::diag::err_drv_unsupported_opt) << A->getAsString(*Args);
       continue;
@@ -165,7 +164,7 @@
       (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P))) {
     FinalPhase = phases::Preprocess;
 
-    // -{fsyntax-only,-analyze,emit-ast,S} only run up to the compiler.
+    // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
   } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
              (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) ||
              (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) ||
@@ -174,10 +173,13 @@
              (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
              (PhaseArg = DAL.getLastArg(options::OPT__analyze,
                                         options::OPT__analyze_auto)) ||
-             (PhaseArg = DAL.getLastArg(options::OPT_emit_ast)) ||
-             (PhaseArg = DAL.getLastArg(options::OPT_S))) {
+             (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) {
     FinalPhase = phases::Compile;
 
+    // -S only runs up to the backend.
+  } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) {
+    FinalPhase = phases::Backend;
+
     // -c only runs up to the assembler.
   } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
     FinalPhase = phases::Assemble;
@@ -205,10 +207,7 @@
   DerivedArgList *DAL = new DerivedArgList(Args);
 
   bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
-  for (ArgList::const_iterator it = Args.begin(),
-         ie = Args.end(); it != ie; ++it) {
-    const Arg *A = *it;
-
+  for (Arg *A : Args) {
     // Unfortunately, we have to parse some forwarding options (-Xassembler,
     // -Xlinker, -Xpreprocessor) because we either integrate their functionality
     // (assembler and preprocessor), or bypass a previous driver ('collect2').
@@ -274,7 +273,7 @@
       continue;
     }
 
-    DAL->append(*it);
+    DAL->append(A);
   }
 
   // Add a default value of -mlinker-version=, if one was given and the user
@@ -364,6 +363,13 @@
   if (const Arg *A = Args->getLastArg(options::OPT_resource_dir))
     ResourceDir = A->getValue();
 
+  if (const Arg *A = Args->getLastArg(options::OPT_save_temps_EQ)) {
+    SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue())
+                    .Case("cwd", SaveTempsCwd)
+                    .Case("obj", SaveTempsObj)
+                    .Default(SaveTempsCwd);
+  }
+
   // Perform the default argument translations.
   DerivedArgList *TranslatedArgs = TranslateInputArgs(*Args);
 
@@ -468,9 +474,7 @@
   // Don't attempt to generate preprocessed files if multiple -arch options are
   // used, unless they're all duplicates.
   llvm::StringSet<> ArchNames;
-  for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end();
-       it != ie; ++it) {
-    Arg *A = *it;
+  for (const Arg *A : C.getArgs()) {
     if (A->getOption().matches(options::OPT_arch)) {
       StringRef ArchName = A->getValue();
       ArchNames.insert(ArchName);
@@ -506,7 +510,7 @@
 
   // If any of the preprocessing commands failed, clean up and exit.
   if (!FailingCommands.empty()) {
-    if (!C.getArgs().hasArg(options::OPT_save_temps))
+    if (!isSaveTempsEnabled())
       C.CleanupFileList(C.getTempFiles(), true);
 
     Diag(clang::diag::note_drv_command_failed_diag_msg)
@@ -550,6 +554,11 @@
     Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo);
     Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
   }
+
+  for (const auto &A : C.getArgs().filtered(options::OPT_frewrite_map_file,
+                                            options::OPT_frewrite_map_file_EQ))
+    Diag(clang::diag::note_drv_command_failed_diag_msg) << A->getValue();
+
   Diag(clang::diag::note_drv_command_failed_diag_msg)
       << "\n\n********************";
 }
@@ -609,7 +618,7 @@
     const Command *FailingCommand = it->second;
 
     // Remove result files if we're not saving temps.
-    if (!C.getArgs().hasArg(options::OPT_save_temps)) {
+    if (!isSaveTempsEnabled()) {
       const JobAction *JA = cast<JobAction>(&FailingCommand->getSource());
       C.CleanupFileMap(C.getResultFiles(), JA, true);
 
@@ -849,7 +858,9 @@
 /// \brief Check whether the given input tree contains any compilation or
 /// assembly actions.
 static bool ContainsCompileOrAssembleAction(const Action *A) {
-  if (isa<CompileJobAction>(A) || isa<AssembleJobAction>(A))
+  if (isa<CompileJobAction>(A) ||
+      isa<BackendJobAction>(A) ||
+      isa<AssembleJobAction>(A))
     return true;
 
   for (Action::const_iterator it = A->begin(), ie = A->end(); it != ie; ++it)
@@ -868,10 +879,7 @@
   // be handled once (in the order seen).
   llvm::StringSet<> ArchNames;
   SmallVector<const char *, 4> Archs;
-  for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
-       it != ie; ++it) {
-    Arg *A = *it;
-
+  for (Arg *A : Args) {
     if (A->getOption().matches(options::OPT_arch)) {
       // Validate the option here; we don't save the type here because its
       // particular spelling may participate in other driver choices.
@@ -1019,10 +1027,7 @@
     assert(!Args.hasArg(options::OPT_x) && "-x and /TC or /TP is not allowed");
   }
 
-  for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
-       it != ie; ++it) {
-    Arg *A = *it;
-
+  for (Arg *A : Args) {
     if (A->getOption().getKind() == Option::InputClass) {
       const char *Value = A->getValue();
       types::ID Ty = types::TY_INVALID;
@@ -1265,7 +1270,7 @@
         continue;
 
       // Otherwise construct the appropriate action.
-      Current = ConstructPhaseAction(Args, Phase, std::move(Current));
+      Current = ConstructPhaseAction(TC, Args, Phase, std::move(Current));
       if (Current->getType() == types::TY_Nothing)
         break;
     }
@@ -1291,7 +1296,8 @@
 }
 
 std::unique_ptr<Action>
-Driver::ConstructPhaseAction(const ArgList &Args, phases::ID Phase,
+Driver::ConstructPhaseAction(const ToolChain &TC, const ArgList &Args,
+                             phases::ID Phase,
                              std::unique_ptr<Action> Input) const {
   llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
   // Build the appropriate action.
@@ -1346,17 +1352,21 @@
     if (Args.hasArg(options::OPT_verify_pch))
       return llvm::make_unique<VerifyPCHJobAction>(std::move(Input),
                                                    types::TY_Nothing);
-    if (IsUsingLTO(Args)) {
+    return llvm::make_unique<CompileJobAction>(std::move(Input),
+                                               types::TY_LLVM_BC);
+  }
+  case phases::Backend: {
+    if (IsUsingLTO(TC, Args)) {
       types::ID Output =
         Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
-      return llvm::make_unique<CompileJobAction>(std::move(Input), Output);
+      return llvm::make_unique<BackendJobAction>(std::move(Input), Output);
     }
     if (Args.hasArg(options::OPT_emit_llvm)) {
       types::ID Output =
         Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC;
-      return llvm::make_unique<CompileJobAction>(std::move(Input), Output);
+      return llvm::make_unique<BackendJobAction>(std::move(Input), Output);
     }
-    return llvm::make_unique<CompileJobAction>(std::move(Input),
+    return llvm::make_unique<BackendJobAction>(std::move(Input),
                                                types::TY_PP_Asm);
   }
   case phases::Assemble:
@@ -1367,7 +1377,10 @@
   llvm_unreachable("invalid phase in ConstructPhaseAction");
 }
 
-bool Driver::IsUsingLTO(const ArgList &Args) const {
+bool Driver::IsUsingLTO(const ToolChain &TC, const ArgList &Args) const {
+  if (TC.getSanitizerArgs().needsLTO())
+    return true;
+
   if (Args.hasFlag(options::OPT_flto, options::OPT_fno_lto, false))
     return true;
 
@@ -1383,9 +1396,8 @@
   // files.
   if (FinalOutput) {
     unsigned NumOutputs = 0;
-    for (ActionList::const_iterator it = C.getActions().begin(),
-           ie = C.getActions().end(); it != ie; ++it)
-      if ((*it)->getType() != types::TY_Nothing)
+    for (const Action *A : C.getActions())
+      if (A->getType() != types::TY_Nothing)
         ++NumOutputs;
 
     if (NumOutputs > 1) {
@@ -1396,19 +1408,12 @@
 
   // Collect the list of architectures.
   llvm::StringSet<> ArchNames;
-  if (C.getDefaultToolChain().getTriple().isOSBinFormatMachO()) {
-    for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end();
-         it != ie; ++it) {
-      Arg *A = *it;
+  if (C.getDefaultToolChain().getTriple().isOSBinFormatMachO())
+    for (const Arg *A : C.getArgs())
       if (A->getOption().matches(options::OPT_arch))
         ArchNames.insert(A->getValue());
-    }
-  }
 
-  for (ActionList::const_iterator it = C.getActions().begin(),
-         ie = C.getActions().end(); it != ie; ++it) {
-    Action *A = *it;
-
+  for (Action *A : C.getActions()) {
     // If we are linking an image for multiple archs then the linker wants
     // -arch_multiple and -final_output <final image name>. Unfortunately, this
     // doesn't fit in cleanly because we have to pass this information down.
@@ -1420,7 +1425,7 @@
       if (FinalOutput)
         LinkingOutput = FinalOutput->getValue();
       else
-        LinkingOutput = DefaultImageName.c_str();
+        LinkingOutput = getDefaultImageName();
     }
 
     InputInfo II;
@@ -1444,10 +1449,7 @@
   // Claim --driver-mode, it was handled earlier.
   (void) C.getArgs().hasArg(options::OPT_driver_mode);
 
-  for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end();
-       it != ie; ++it) {
-    Arg *A = *it;
-
+  for (Arg *A : C.getArgs()) {
     // FIXME: It would be nice to be able to send the argument to the
     // DiagnosticsEngine, so that extra values, position, and so on could be
     // printed.
@@ -1479,8 +1481,8 @@
   }
 }
 
-static const Tool *SelectToolForJob(Compilation &C, const ToolChain *TC,
-                                    const JobAction *JA,
+static const Tool *SelectToolForJob(Compilation &C, bool SaveTemps,
+                                    const ToolChain *TC, const JobAction *JA,
                                     const ActionList *&Inputs) {
   const Tool *ToolForJob = nullptr;
 
@@ -1489,17 +1491,38 @@
   // compiler input.
 
   if (TC->useIntegratedAs() &&
-      !C.getArgs().hasArg(options::OPT_save_temps) &&
+      !SaveTemps &&
       !C.getArgs().hasArg(options::OPT_via_file_asm) &&
       !C.getArgs().hasArg(options::OPT__SLASH_FA) &&
       !C.getArgs().hasArg(options::OPT__SLASH_Fa) &&
       isa<AssembleJobAction>(JA) &&
-      Inputs->size() == 1 && isa<CompileJobAction>(*Inputs->begin())) {
-    const Tool *Compiler =
-      TC->SelectTool(cast<JobAction>(**Inputs->begin()));
+      Inputs->size() == 1 && isa<BackendJobAction>(*Inputs->begin())) {
+    // A BackendJob is always preceded by a CompileJob, and without
+    // -save-temps they will always get combined together, so instead of
+    // checking the backend tool, check if the tool for the CompileJob
+    // has an integrated assembler.
+    const ActionList *BackendInputs = &(*Inputs)[0]->getInputs();
+    JobAction *CompileJA = cast<CompileJobAction>(*BackendInputs->begin());
+    const Tool *Compiler = TC->SelectTool(*CompileJA);
     if (!Compiler)
       return nullptr;
     if (Compiler->hasIntegratedAssembler()) {
+      Inputs = &(*BackendInputs)[0]->getInputs();
+      ToolForJob = Compiler;
+    }
+  }
+
+  // A backend job should always be combined with the preceding compile job
+  // unless OPT_save_temps is enabled and the compiler is capable of emitting
+  // LLVM IR as an intermediate output.
+  if (isa<BackendJobAction>(JA)) {
+    // Check if the compiler supports emitting LLVM IR.
+    assert(Inputs->size() == 1);
+    JobAction *CompileJA = cast<CompileJobAction>(*Inputs->begin());
+    const Tool *Compiler = TC->SelectTool(*CompileJA);
+    if (!Compiler)
+      return nullptr;
+    if (!Compiler->canEmitIR() || !SaveTemps) {
       Inputs = &(*Inputs)[0]->getInputs();
       ToolForJob = Compiler;
     }
@@ -1515,7 +1538,7 @@
   if (Inputs->size() == 1 && isa<PreprocessJobAction>(*Inputs->begin()) &&
       !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
       !C.getArgs().hasArg(options::OPT_traditional_cpp) &&
-      !C.getArgs().hasArg(options::OPT_save_temps) &&
+      !SaveTemps &&
       !C.getArgs().hasArg(options::OPT_rewrite_objc) &&
       ToolForJob->hasIntegratedCPP())
     Inputs = &(*Inputs)[0]->getInputs();
@@ -1563,14 +1586,13 @@
   const ActionList *Inputs = &A->getInputs();
 
   const JobAction *JA = cast<JobAction>(A);
-  const Tool *T = SelectToolForJob(C, TC, JA, Inputs);
+  const Tool *T = SelectToolForJob(C, isSaveTempsEnabled(), TC, JA, Inputs);
   if (!T)
     return;
 
   // Only use pipes when there is exactly one input.
   InputInfoList InputInfos;
-  for (ActionList::const_iterator it = Inputs->begin(), ie = Inputs->end();
-       it != ie; ++it) {
+  for (const Action *Input : *Inputs) {
     // Treat dsymutil and verify sub-jobs as being at the top-level too, they
     // shouldn't get temporary output names.
     // FIXME: Clean this up.
@@ -1579,7 +1601,7 @@
       SubJobAtTopLevel = true;
 
     InputInfo II;
-    BuildJobsForAction(C, *it, TC, BoundArch, SubJobAtTopLevel, MultipleArchs,
+    BuildJobsForAction(C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs,
                        LinkingOutput, II);
     InputInfos.push_back(II);
   }
@@ -1615,6 +1637,11 @@
   }
 }
 
+const char *Driver::getDefaultImageName() const {
+  llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
+  return Target.isOSWindows() ? "a.exe" : "a.out";
+}
+
 /// \brief Create output filename based on ArgValue, which could either be a
 /// full filename, filename without extension, or a directory. If ArgValue
 /// does not provide a filename, then use BaseName, and use the extension
@@ -1690,7 +1717,7 @@
   }
 
   // Output to a temporary file?
-  if ((!AtTopLevel && !C.getArgs().hasArg(options::OPT_save_temps) &&
+  if ((!AtTopLevel && !isSaveTempsEnabled() &&
         !C.getArgs().hasArg(options::OPT__SLASH_Fo)) ||
       CCGenDiagnostics) {
     StringRef Name = llvm::sys::path::filename(BaseInput);
@@ -1733,12 +1760,12 @@
       NamedOutput = MakeCLOutputFilename(C.getArgs(), "", BaseName,
                                          types::TY_Image);
     } else if (MultipleArchs && BoundArch) {
-      SmallString<128> Output(DefaultImageName.c_str());
+      SmallString<128> Output(getDefaultImageName());
       Output += "-";
       Output.append(BoundArch);
       NamedOutput = C.getArgs().MakeArgString(Output.c_str());
     } else
-      NamedOutput = DefaultImageName.c_str();
+      NamedOutput = getDefaultImageName();
   } else {
     const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
     assert(Suffix && "All types used for output should have a suffix.");
@@ -1751,16 +1778,31 @@
       Suffixed += "-";
       Suffixed.append(BoundArch);
     }
+    // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for
+    // the unoptimized bitcode so that it does not get overwritten by the ".bc"
+    // optimized bitcode output.
+    if (!AtTopLevel && C.getArgs().hasArg(options::OPT_emit_llvm) &&
+        JA.getType() == types::TY_LLVM_BC)
+      Suffixed += ".tmp";
     Suffixed += '.';
     Suffixed += Suffix;
     NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
   }
 
+  // Prepend object file path if -save-temps=obj
+  if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) &&
+      JA.getType() != types::TY_PCH) {
+    Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
+    SmallString<128> TempPath(FinalOutput->getValue());
+    llvm::sys::path::remove_filename(TempPath);
+    StringRef OutputFileName = llvm::sys::path::filename(NamedOutput);
+    llvm::sys::path::append(TempPath, OutputFileName);
+    NamedOutput = C.getArgs().MakeArgString(TempPath.c_str());
+  }
+
   // If we're saving temps and the temp file conflicts with the input file,
   // then avoid overwriting input file.
-  if (!AtTopLevel && C.getArgs().hasArg(options::OPT_save_temps) &&
-      NamedOutput == BaseName) {
-
+  if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) {
     bool SameFile = false;
     SmallString<256> Result;
     llvm::sys::fs::current_path(Result);
@@ -2063,7 +2105,7 @@
         TC = new toolchains::Generic_ELF(*this, Target, Args);
         break;
       }
-      if (Target.getObjectFormat() == llvm::Triple::MachO) {
+      if (Target.isOSBinFormatMachO()) {
         TC = new toolchains::MachO(*this, Target, Args);
         break;
       }
@@ -2083,7 +2125,7 @@
 
   // Otherwise make sure this is an action clang understands.
   if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) &&
-      !isa<CompileJobAction>(JA))
+      !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
     return false;
 
   return true;