Driver.cpp revision 53d2409a223a14d063faf06e4360ede09c41ed80
1868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)//===--- Driver.cpp - Clang GCC Compatible Driver -------------------------===//
25821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//
35821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//                     The LLVM Compiler Infrastructure
45821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//
5868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)// This file is distributed under the University of Illinois Open Source
6868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)// License. See LICENSE.TXT for details.
7868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)//
8868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)//===----------------------------------------------------------------------===//
95821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
102a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "clang/Driver/Driver.h"
11868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)
12c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)#include "clang/Driver/Action.h"
135821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/Driver/Arg.h"
145821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/Driver/ArgList.h"
152a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "clang/Driver/Compilation.h"
16c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)#include "clang/Driver/DriverDiagnostic.h"
177d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)#include "clang/Driver/Job.h"
185821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/Driver/OptTable.h"
195821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/Driver/Option.h"
202a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "clang/Driver/Options.h"
215821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/Driver/Tool.h"
22c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)#include "clang/Driver/ToolChain.h"
235821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
242a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "clang/Basic/Version.h"
255821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
265821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "llvm/ADT/ArrayRef.h"
275821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "llvm/ADT/StringSet.h"
285821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "llvm/ADT/OwningPtr.h"
295821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "llvm/Support/ErrorHandling.h"
305821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "llvm/Support/PrettyStackTrace.h"
312a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "llvm/Support/raw_ostream.h"
325821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "llvm/Support/FileSystem.h"
332a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "llvm/Support/Path.h"
345821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "llvm/Support/Program.h"
352a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
362a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "InputInfo.h"
372a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "ToolChains.h"
382a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
395821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include <map>
40868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)
41868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)#include "clang/Config/config.h"
425821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
4390dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)using namespace clang::driver;
4490dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)using namespace clang;
4590dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)
4690dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)Driver::Driver(StringRef ClangExecutable,
4790dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)               StringRef DefaultTargetTriple,
48868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)               StringRef DefaultImageName,
49868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)               bool IsProduction,
50868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)               DiagnosticsEngine &Diags)
51868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  : Opts(createDriverOptTable()), Diags(Diags),
525821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    ClangExecutable(ClangExecutable), SysRoot(DEFAULT_SYSROOT),
53ca12bfac764ba476d6cd062bf1dde12cc64c3f40Ben Murdoch    UseStdLib(true), DefaultTargetTriple(DefaultTargetTriple),
547dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch    DefaultImageName(DefaultImageName),
557dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch    DriverTitle("clang \"gcc-compatible\" driver"),
56e5d81f57cb97b3b6b7fccc9c5610d21eb81db09dBen Murdoch    CCPrintOptionsFilename(0), CCPrintHeadersFilename(0),
577dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch    CCLogDiagnosticsFilename(0), CCCIsCXX(false),
585821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    CCCIsCPP(false),CCCEcho(false), CCCPrintBindings(false),
595821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    CCPrintOptions(false), CCPrintHeaders(false), CCLogDiagnostics(false),
605821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    CCGenDiagnostics(false), CCCGenericGCCName(""), CheckInputsExist(true),
6190dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    CCCUseClang(true), CCCUseClangCXX(true), CCCUseClangCPP(true),
625821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    CCCUsePCH(true), SuppressMissingInputWarning(false) {
635821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  if (IsProduction) {
6490dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    // In a "production" build, only use clang on architectures we expect to
6590dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    // work.
6690dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    //
6790dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    // During development its more convenient to always have the driver use
6890dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    // clang, but we don't want users to be confused when things don't work, or
6990dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    // to file bugs for things we don't support.
70868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)    CCCClangArchs.insert(llvm::Triple::x86);
71868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)    CCCClangArchs.insert(llvm::Triple::x86_64);
72868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)    CCCClangArchs.insert(llvm::Triple::arm);
73868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  }
74868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)
75868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  Name = llvm::sys::path::stem(ClangExecutable);
76868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  Dir  = llvm::sys::path::parent_path(ClangExecutable);
77868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)
78868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  // Compute the path to the resource directory.
79868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  StringRef ClangResourceDir(CLANG_RESOURCE_DIR);
80868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  SmallString<128> P(Dir);
81868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  if (ClangResourceDir != "")
82868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)    llvm::sys::path::append(P, ClangResourceDir);
83868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  else
84868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)    llvm::sys::path::append(P, "..", "lib", "clang", CLANG_VERSION_STRING);
85868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  ResourceDir = P.str();
86868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)}
87868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)
88868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)Driver::~Driver() {
89868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  delete Opts;
90868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)
91868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  for (llvm::StringMap<ToolChain *>::iterator I = ToolChains.begin(),
92868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)                                              E = ToolChains.end();
93868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)       I != E; ++I)
94868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)    delete I->second;
95868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)}
96868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)
97868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)InputArgList *Driver::ParseArgStrings(ArrayRef<const char *> ArgList) {
98868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
99868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  unsigned MissingArgIndex, MissingArgCount;
100868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  InputArgList *Args = getOpts().ParseArgs(ArgList.begin(), ArgList.end(),
101b2df76ea8fec9e32f6f3718986dba0d95315b29cTorne (Richard Coles)                                           MissingArgIndex, MissingArgCount);
1022a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
1035821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // Check for missing argument error.
104868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  if (MissingArgCount)
105868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)    Diag(clang::diag::err_drv_missing_argument)
106868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)      << Args->getArgString(MissingArgIndex) << MissingArgCount;
107868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)
108868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  // Check for unsupported options.
109868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  for (ArgList::const_iterator it = Args->begin(), ie = Args->end();
1105821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)       it != ie; ++it) {
1115821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    Arg *A = *it;
112868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)    if (A->getOption().isUnsupported()) {
113868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)      Diag(clang::diag::err_drv_unsupported_opt) << A->getAsString(*Args);
114868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)      continue;
1154e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)    }
116a02191e04bc25c4935f804f2c080ae28663d096dBen Murdoch
117868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)    // Warn about -mcpu= without an argument.
118868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)    if (A->getOption().matches(options::OPT_mcpu_EQ) &&
1192a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)        A->containsValue("")) {
120868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)      Diag(clang::diag::warn_drv_empty_joined_argument) << A->getAsString(*Args);
1212a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    }
1222a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  }
1235821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
124868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  return Args;
125868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)}
126868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)
127868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)// Determine which compilation mode we are in. We look for options which
128868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)// affect the phase, starting with the earliest phases, and record which
129868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)// option we used to determine the final phase.
130868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)phases::ID Driver::getFinalPhase(const DerivedArgList &DAL, Arg **FinalPhaseArg)
131868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)const {
1325821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  Arg *PhaseArg = 0;
133868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  phases::ID FinalPhase;
134868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)
1355821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // -{E,M,MM} only run the preprocessor.
1365821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  if (CCCIsCPP ||
137868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)      (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
138868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)      (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM))) {
1395821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    FinalPhase = phases::Preprocess;
140868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)
141868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)    // -{fsyntax-only,-analyze,emit-ast,S} only run up to the compiler.
142868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
143868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)             (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
1445821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)             (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
1455821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)             (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
1465821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)             (PhaseArg = DAL.getLastArg(options::OPT__analyze,
1472a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                                        options::OPT__analyze_auto)) ||
1485821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)             (PhaseArg = DAL.getLastArg(options::OPT_emit_ast)) ||
149ca12bfac764ba476d6cd062bf1dde12cc64c3f40Ben Murdoch             (PhaseArg = DAL.getLastArg(options::OPT_S))) {
1505821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    FinalPhase = phases::Compile;
151a93a17c8d99d686bd4a1511e5504e5e6cc9fcadfTorne (Richard Coles)
15290dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    // -c only runs up to the assembler.
15390dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
1542a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    FinalPhase = phases::Assemble;
1552a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
15690dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    // Otherwise do everything.
1572a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  } else
1585821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    FinalPhase = phases::Link;
159ca12bfac764ba476d6cd062bf1dde12cc64c3f40Ben Murdoch
1605821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  if (FinalPhaseArg)
16190dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    *FinalPhaseArg = PhaseArg;
162b2df76ea8fec9e32f6f3718986dba0d95315b29cTorne (Richard Coles)
16390dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  return FinalPhase;
16490dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)}
165ca12bfac764ba476d6cd062bf1dde12cc64c3f40Ben Murdoch
166ca12bfac764ba476d6cd062bf1dde12cc64c3f40Ben MurdochDerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
1675821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  DerivedArgList *DAL = new DerivedArgList(Args);
1682a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
1695821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
1702a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  for (ArgList::const_iterator it = Args.begin(),
171868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)         ie = Args.end(); it != ie; ++it) {
172c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)    const Arg *A = *it;
173c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)
17490dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    // Unfortunately, we have to parse some forwarding options (-Xassembler,
1755821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    // -Xlinker, -Xpreprocessor) because we either integrate their functionality
1765821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    // (assembler and preprocessor), or bypass a previous driver ('collect2').
177868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)
1782a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    // Rewrite linker options, to replace --no-demangle with a custom internal
1795821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    // option.
180eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
1815821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)         A->getOption().matches(options::OPT_Xlinker)) &&
182eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch        A->containsValue("--no-demangle")) {
183eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch      // Add the rewritten no-demangle argument.
1845821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle));
1855821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
1865821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      // Add the remaining values as Xlinker arguments.
1872a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      for (unsigned i = 0, e = A->getNumValues(); i != e; ++i)
1885821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)        if (StringRef(A->getValue(Args, i)) != "--no-demangle")
189ca12bfac764ba476d6cd062bf1dde12cc64c3f40Ben Murdoch          DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker),
1905821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                              A->getValue(Args, i));
1915821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
19290dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)      continue;
193ca12bfac764ba476d6cd062bf1dde12cc64c3f40Ben Murdoch    }
194ca12bfac764ba476d6cd062bf1dde12cc64c3f40Ben Murdoch
195a93a17c8d99d686bd4a1511e5504e5e6cc9fcadfTorne (Richard Coles)    // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
196a93a17c8d99d686bd4a1511e5504e5e6cc9fcadfTorne (Richard Coles)    // some build systems. We don't try to be complete here because we don't
197a93a17c8d99d686bd4a1511e5504e5e6cc9fcadfTorne (Richard Coles)    // care to encourage this usage model.
1987dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch    if (A->getOption().matches(options::OPT_Wp_COMMA) &&
199a93a17c8d99d686bd4a1511e5504e5e6cc9fcadfTorne (Richard Coles)        A->getNumValues() == 2 &&
200ca12bfac764ba476d6cd062bf1dde12cc64c3f40Ben Murdoch        (A->getValue(Args, 0) == StringRef("-MD") ||
2015821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)         A->getValue(Args, 0) == StringRef("-MMD"))) {
202f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)      // Rewrite to -MD/-MMD along with -MF.
203f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)      if (A->getValue(Args, 0) == StringRef("-MD"))
204f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)        DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD));
205f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)      else
206f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)        DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD));
207f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)      DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF),
2085821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                          A->getValue(Args, 1));
209f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)      continue;
210f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)    }
211eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch
212eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    // Rewrite reserved library names.
2135821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    if (A->getOption().matches(options::OPT_l)) {
214f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)      StringRef Value = A->getValue(Args);
215f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)
2165821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      // Rewrite unless -nostdlib is present.
217f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)      if (!HasNostdlib && Value == "stdc++") {
218eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch        DAL->AddFlagArg(A, Opts->getOption(
2195821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                              options::OPT_Z_reserved_lib_stdcxx));
220ca12bfac764ba476d6cd062bf1dde12cc64c3f40Ben Murdoch        continue;
221ca12bfac764ba476d6cd062bf1dde12cc64c3f40Ben Murdoch      }
222868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)
223eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch      // Rewrite unconditionally.
224eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch      if (Value == "cc_kext") {
225eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch        DAL->AddFlagArg(A, Opts->getOption(
226eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch                              options::OPT_Z_reserved_lib_cckext));
227eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch        continue;
228eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch      }
229f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)    }
230eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch
231ca12bfac764ba476d6cd062bf1dde12cc64c3f40Ben Murdoch    DAL->append(*it);
2325821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  }
2335821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
234868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  // Add a default value of -mlinker-version=, if one was given and the user
2352a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // didn't specify one.
2362a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#if defined(HOST_LINK_VERSION)
2372a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  if (!Args.hasArg(options::OPT_mlinker_version_EQ)) {
2382a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ),
2395821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                      HOST_LINK_VERSION);
240868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)    DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
241868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  }
242868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)#endif
243868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)
244868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  return DAL;
245868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)}
246868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)
247868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
2485821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  llvm::PrettyStackTraceString CrashInfo("Compilation construction");
249868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)
250868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  // FIXME: Handle environment options which affect driver behavior, somewhere
2515821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
2525821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
253868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  if (char *env = ::getenv("COMPILER_PATH")) {
254868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)    StringRef CompilerPath = env;
255868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)    while (!CompilerPath.empty()) {
256868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)      std::pair<StringRef, StringRef> Split = CompilerPath.split(':');
2575821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      PrefixDirs.push_back(Split.first);
2585821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      CompilerPath = Split.second;
2595821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    }
260868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  }
261868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)
2625821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // FIXME: What are we going to do with -V and -b?
2635821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
2645821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // FIXME: This stuff needs to go into the Compilation, not the driver.
2652a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  bool CCCPrintOptions = false, CCCPrintActions = false;
2665821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
267ca12bfac764ba476d6cd062bf1dde12cc64c3f40Ben Murdoch  InputArgList *Args = ParseArgStrings(ArgList.slice(1));
2682a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
269a93a17c8d99d686bd4a1511e5504e5e6cc9fcadfTorne (Richard Coles)  // -no-canonical-prefixes is used very early in main.
27090dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  Args->ClaimAllArgs(options::OPT_no_canonical_prefixes);
27190dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)
2722a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // Ignore -pipe.
2735821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  Args->ClaimAllArgs(options::OPT_pipe);
27490dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)
2752a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // Extract -ccc args.
2765821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  //
277ca12bfac764ba476d6cd062bf1dde12cc64c3f40Ben Murdoch  // FIXME: We need to figure out where this behavior should live. Most of it
2785821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // should be outside in the client; the parts that aren't should have proper
27990dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  // options, either by introducing new ones or by overloading gcc ones like -V
280b2df76ea8fec9e32f6f3718986dba0d95315b29cTorne (Richard Coles)  // or -b.
28190dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  CCCPrintOptions = Args->hasArg(options::OPT_ccc_print_options);
28290dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  CCCPrintActions = Args->hasArg(options::OPT_ccc_print_phases);
283ca12bfac764ba476d6cd062bf1dde12cc64c3f40Ben Murdoch  CCCPrintBindings = Args->hasArg(options::OPT_ccc_print_bindings);
284ca12bfac764ba476d6cd062bf1dde12cc64c3f40Ben Murdoch  CCCIsCXX = Args->hasArg(options::OPT_ccc_cxx) || CCCIsCXX;
2855821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  CCCEcho = Args->hasArg(options::OPT_ccc_echo);
2862a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  if (const Arg *A = Args->getLastArg(options::OPT_ccc_gcc_name))
2875821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    CCCGenericGCCName = A->getValue(*Args);
288a93a17c8d99d686bd4a1511e5504e5e6cc9fcadfTorne (Richard Coles)  CCCUseClangCXX = Args->hasFlag(options::OPT_ccc_clang_cxx,
2895821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                                 options::OPT_ccc_no_clang_cxx,
2902a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                                 CCCUseClangCXX);
291868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  CCCUsePCH = Args->hasFlag(options::OPT_ccc_pch_is_pch,
292c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)                            options::OPT_ccc_pch_is_pth);
293c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)  CCCUseClang = !Args->hasArg(options::OPT_ccc_no_clang);
29490dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  CCCUseClangCPP = !Args->hasArg(options::OPT_ccc_no_clang_cpp);
2955821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  if (const Arg *A = Args->getLastArg(options::OPT_ccc_clang_archs)) {
2965821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    StringRef Cur = A->getValue(*Args);
2975821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
2985821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    CCCClangArchs.clear();
2995821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    while (!Cur.empty()) {
3005821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      std::pair<StringRef, StringRef> Split = Cur.split(',');
3015821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
3025821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      if (!Split.first.empty()) {
3035821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)        llvm::Triple::ArchType Arch =
3045821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)          llvm::Triple(Split.first, "", "").getArch();
3055821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
3065821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)        if (Arch == llvm::Triple::UnknownArch)
3075821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)          Diag(clang::diag::err_drv_invalid_arch_name) << Split.first;
3085821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
3095821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)        CCCClangArchs.insert(Arch);
3105821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      }
3115821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
31290dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)      Cur = Split.second;
31390dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    }
31490dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  }
315868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  // FIXME: DefaultTargetTriple is used by the target-prefixed calls to as/ld
31690dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  // and getToolChain is const.
31790dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  if (const Arg *A = Args->getLastArg(options::OPT_target))
31890dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    DefaultTargetTriple = A->getValue(*Args);
31990dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  if (const Arg *A = Args->getLastArg(options::OPT_ccc_install_dir))
32090dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    Dir = InstalledDir = A->getValue(*Args);
321868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  for (arg_iterator it = Args->filtered_begin(options::OPT_B),
322868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)         ie = Args->filtered_end(); it != ie; ++it) {
323868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)    const Arg *A = *it;
324868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)    A->claim();
32590dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    PrefixDirs.push_back(A->getValue(*Args, 0));
32690dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  }
327868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  if (const Arg *A = Args->getLastArg(options::OPT__sysroot_EQ))
32890dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    SysRoot = A->getValue(*Args);
329868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  if (Args->hasArg(options::OPT_nostdlib))
330868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)    UseStdLib = false;
331868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)
33290dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  // Perform the default argument translations.
333868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  DerivedArgList *TranslatedArgs = TranslateInputArgs(*Args);
33490dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)
335868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  // Owned by the host.
33690dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  const ToolChain &TC = getToolChain(*Args);
337868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)
338868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  // The compilation takes ownership of Args.
339868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  Compilation *C = new Compilation(*this, TC, Args, TranslatedArgs);
340868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)
34190dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  // FIXME: This behavior shouldn't be here.
342868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  if (CCCPrintOptions) {
343868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)    PrintOptions(C->getInputArgs());
34490dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    return C;
34590dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  }
34690dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)
34790dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  if (!HandleImmediateArgs(*C))
34890dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    return C;
349ca12bfac764ba476d6cd062bf1dde12cc64c3f40Ben Murdoch
35090dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  // Construct the list of inputs.
35190dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  InputList Inputs;
35290dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  BuildInputs(C->getDefaultToolChain(), C->getArgs(), Inputs);
35390dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)
35490dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  // Construct the list of abstract actions to perform for this compilation. On
35590dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  // Darwin target OSes this uses the driver-driver and universal actions.
35690dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  if (TC.getTriple().isOSDarwin())
35790dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    BuildUniversalActions(C->getDefaultToolChain(), C->getArgs(),
35890dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)                          Inputs, C->getActions());
35990dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  else
360ca12bfac764ba476d6cd062bf1dde12cc64c3f40Ben Murdoch    BuildActions(C->getDefaultToolChain(), C->getArgs(), Inputs,
36190dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)                 C->getActions());
36290dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)
36390dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  if (CCCPrintActions) {
36490dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    PrintActions(*C);
36590dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    return C;
366ca12bfac764ba476d6cd062bf1dde12cc64c3f40Ben Murdoch  }
367ca12bfac764ba476d6cd062bf1dde12cc64c3f40Ben Murdoch
36890dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  BuildJobs(*C);
36990dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)
37090dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  return C;
37190dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)}
372868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)
37390dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)// When clang crashes, produce diagnostic information including the fully
37490dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)// preprocessed source file(s).  Request that the developer attach the
37590dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)// diagnostic information to a bug report.
37690dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)void Driver::generateCompilationDiagnostics(Compilation &C,
37790dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)                                            const Command *FailingCommand) {
37890dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
37990dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    return;
380868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)
38190dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  // Don't try to generate diagnostics for link jobs.
38290dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  if (FailingCommand && FailingCommand->getCreator().isLinkJob())
38390dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    return;
38490dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)
38590dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  Diag(clang::diag::note_drv_command_failed_diag_msg)
386868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)    << "Please submit a bug report to " BUG_REPORT_URL " and include command"
387868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)    " line arguments and all diagnostic information.";
388868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)
389868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  // Suppress driver output and emit preprocessor output to temp file.
390868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  CCCIsCPP = true;
391868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  CCGenDiagnostics = true;
392868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)
39390dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  // Save the original job command(s).
39490dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  std::string Cmd;
395868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  llvm::raw_string_ostream OS(Cmd);
39690dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  if (FailingCommand)
397868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)    C.PrintJob(OS, *FailingCommand, "\n", false);
398868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  else
399868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)    // Crash triggered by FORCE_CLANG_DIAGNOSTICS_CRASH, which doesn't have an
40090dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    // associated FailingCommand, so just pass all jobs.
401868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)    C.PrintJob(OS, C.getJobs(), "\n", false);
40290dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  OS.flush();
403868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)
404868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  // Clear stale state and suppress tool output.
40590dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  C.initCompilationForDiagnostics();
40690dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  Diags.Reset();
40790dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)
40890dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  // Construct the list of inputs.
40990dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  InputList Inputs;
410ca12bfac764ba476d6cd062bf1dde12cc64c3f40Ben Murdoch  BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
41190dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)
41290dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
41390dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    bool IgnoreInput = false;
41490dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)
41590dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    // Ignore input from stdin or any inputs that cannot be preprocessed.
41690dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    if (!strcmp(it->second->getValue(C.getArgs()), "-")) {
41790dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)      Diag(clang::diag::note_drv_command_failed_diag_msg)
41890dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)        << "Error generating preprocessed source(s) - ignoring input from stdin"
41990dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)        ".";
42090dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)      IgnoreInput = true;
421ca12bfac764ba476d6cd062bf1dde12cc64c3f40Ben Murdoch    } else if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
42290dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)      IgnoreInput = true;
42390dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    }
42490dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)
42590dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    if (IgnoreInput) {
42690dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)      it = Inputs.erase(it);
427ca12bfac764ba476d6cd062bf1dde12cc64c3f40Ben Murdoch      ie = Inputs.end();
428ca12bfac764ba476d6cd062bf1dde12cc64c3f40Ben Murdoch    } else {
42990dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)      ++it;
43090dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    }
43190dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  }
43290dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)
433868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  // Don't attempt to generate preprocessed files if multiple -arch options are
43490dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  // used, unless they're all duplicates.
43590dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  llvm::StringSet<> ArchNames;
43690dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end();
43790dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)       it != ie; ++it) {
438eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    Arg *A = *it;
439eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    if (A->getOption().matches(options::OPT_arch)) {
440eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch      StringRef ArchName = A->getValue(C.getArgs());
441eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch      ArchNames.insert(ArchName);
442eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    }
443eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  }
444eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  if (ArchNames.size() > 1) {
445eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    Diag(clang::diag::note_drv_command_failed_diag_msg)
446eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch      << "Error generating preprocessed source(s) - cannot generate "
447eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch      "preprocessed source with multiple -arch options.";
448eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    return;
449eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  }
450eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch
451eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  if (Inputs.empty()) {
452eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    Diag(clang::diag::note_drv_command_failed_diag_msg)
453eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch      << "Error generating preprocessed source(s) - no preprocessable inputs.";
454eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    return;
455eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  }
456eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch
457eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  // Construct the list of abstract actions to perform for this compilation. On
458eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  // Darwin OSes this uses the driver-driver and builds universal actions.
459eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  const ToolChain &TC = C.getDefaultToolChain();
460eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  if (TC.getTriple().isOSDarwin())
461eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    BuildUniversalActions(TC, C.getArgs(), Inputs, C.getActions());
462eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  else
463eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    BuildActions(TC, C.getArgs(), Inputs, C.getActions());
464eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch
465eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  BuildJobs(C);
466eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch
467eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  // If there were errors building the compilation, quit now.
468ca12bfac764ba476d6cd062bf1dde12cc64c3f40Ben Murdoch  if (Diags.hasErrorOccurred()) {
469eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    Diag(clang::diag::note_drv_command_failed_diag_msg)
470eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch      << "Error generating preprocessed source(s).";
471eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    return;
472eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  }
473eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch
474eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  // Generate preprocessed output.
475eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  FailingCommand = 0;
476eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  int Res = C.ExecuteJob(C.getJobs(), FailingCommand);
477eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch
478ca12bfac764ba476d6cd062bf1dde12cc64c3f40Ben Murdoch  // If the command succeeded, we are done.
479eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  if (Res == 0) {
480eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    Diag(clang::diag::note_drv_command_failed_diag_msg)
481eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch      << "Preprocessed source(s) and associated run script(s) are located at:";
482eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    ArgStringList Files = C.getTempFiles();
483eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    for (ArgStringList::const_iterator it = Files.begin(), ie = Files.end();
484ca12bfac764ba476d6cd062bf1dde12cc64c3f40Ben Murdoch         it != ie; ++it) {
485ca12bfac764ba476d6cd062bf1dde12cc64c3f40Ben Murdoch      Diag(clang::diag::note_drv_command_failed_diag_msg) << *it;
486eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch
487eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch      std::string Err;
488eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch      std::string Script = StringRef(*it).rsplit('.').first;
489eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch      Script += ".sh";
490eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch      llvm::raw_fd_ostream ScriptOS(Script.c_str(), Err,
491eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch                                    llvm::raw_fd_ostream::F_Excl |
492eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch                                    llvm::raw_fd_ostream::F_Binary);
493eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch      if (!Err.empty()) {
494eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch        Diag(clang::diag::note_drv_command_failed_diag_msg)
495eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch          << "Error generating run script: " + Script + " " + Err;
496eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch      } else {
497eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch        // Strip away options not necessary to reproduce the crash.
498eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch        // FIXME: This doesn't work with quotes (e.g., -D "foo bar").
499eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch        SmallVector<std::string, 16> Flag;
500eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch        Flag.push_back("-D ");
501eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch        Flag.push_back("-F");
502eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch        Flag.push_back("-I ");
503eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch        Flag.push_back("-o ");
504eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch        Flag.push_back("-coverage-file ");
505eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch        Flag.push_back("-dependency-file ");
506eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch        Flag.push_back("-fdebug-compilation-dir ");
507eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch        Flag.push_back("-fmodule-cache-path ");
508eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch        Flag.push_back("-include ");
509eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch        Flag.push_back("-include-pch ");
510eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch        Flag.push_back("-isysroot ");
511eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch        Flag.push_back("-resource-dir ");
512eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch        Flag.push_back("-serialize-diagnostic-file ");
513eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch        for (unsigned i = 0, e = Flag.size(); i < e; ++i) {
514eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch          size_t I = 0, E = 0;
515eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch          do {
516eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch            I = Cmd.find(Flag[i], I);
517eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch            if (I == std::string::npos) break;
518eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch
519eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch            E = Cmd.find(" ", I + Flag[i].length());
520eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch            if (E == std::string::npos) break;
521eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch            Cmd.erase(I, E - I + 1);
522eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch          } while(1);
523eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch        }
524eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch        // FIXME: Append the new filename with correct preprocessed suffix.
525eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch        ScriptOS << Cmd;
526ca12bfac764ba476d6cd062bf1dde12cc64c3f40Ben Murdoch        Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
527eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch      }
528eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    }
529eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  } else {
530eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    // Failure, remove preprocessed files.
531eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    if (!C.getArgs().hasArg(options::OPT_save_temps))
532eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch      C.CleanupFileList(C.getTempFiles(), true);
533eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch
534eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    Diag(clang::diag::note_drv_command_failed_diag_msg)
535eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch      << "Error generating preprocessed source(s).";
536ca12bfac764ba476d6cd062bf1dde12cc64c3f40Ben Murdoch  }
537eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch}
538eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch
539eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdochint Driver::ExecuteCompilation(const Compilation &C,
540eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch                               const Command *&FailingCommand) const {
541eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  // Just print if -### was present.
542ca12bfac764ba476d6cd062bf1dde12cc64c3f40Ben Murdoch  if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
543ca12bfac764ba476d6cd062bf1dde12cc64c3f40Ben Murdoch    C.PrintJob(llvm::errs(), C.getJobs(), "\n", true);
544eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    return 0;
545eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  }
546eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch
547eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  // If there were errors building the compilation, quit now.
548eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  if (Diags.hasErrorOccurred())
549eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    return 1;
550eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch
551eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  int Res = C.ExecuteJob(C.getJobs(), FailingCommand);
552eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch
553eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  // Remove temp files.
554eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  C.CleanupFileList(C.getTempFiles());
555eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch
556eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  // If the command succeeded, we are done.
557eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  if (Res == 0)
558eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    return Res;
559eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch
560eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  // Otherwise, remove result files as well.
561eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  if (!C.getArgs().hasArg(options::OPT_save_temps)) {
562eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    C.CleanupFileList(C.getResultFiles(), true);
563eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch
564eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    // Failure result files are valid unless we crashed.
565eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    if (Res < 0) {
566eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch      C.CleanupFileList(C.getFailureResultFiles(), true);
567eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch#ifdef _WIN32
568eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch      // Exit status should not be negative on Win32,
569eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch      // unless abnormal termination.
570eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch      Res = 1;
571eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch#endif
572eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    }
573eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  }
574eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch
575eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  // Print extra information about abnormal failures, if possible.
576eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  //
577eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  // This is ad-hoc, but we don't want to be excessively noisy. If the result
578eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  // status was 1, assume the command failed normally. In particular, if it was
579eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  // the compiler then assume it gave a reasonable error code. Failures in other
580eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  // tools are less common, and they generally have worse diagnostics, so always
581eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  // print the diagnostic there.
582eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  const Tool &FailingTool = FailingCommand->getCreator();
583eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch
584eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) {
585eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    // FIXME: See FIXME above regarding result code interpretation.
586eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    if (Res < 0)
587eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch      Diag(clang::diag::err_drv_command_signalled)
588eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch        << FailingTool.getShortName();
589eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    else
590eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch      Diag(clang::diag::err_drv_command_failed)
591eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch        << FailingTool.getShortName() << Res;
592eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  }
593eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch
594eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  return Res;
595eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch}
596eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch
597eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdochvoid Driver::PrintOptions(const ArgList &Args) const {
598eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  unsigned i = 0;
599eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
600eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch       it != ie; ++it, ++i) {
601ca12bfac764ba476d6cd062bf1dde12cc64c3f40Ben Murdoch    Arg *A = *it;
602eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    llvm::errs() << "Option " << i << " - "
603eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch                 << "Name: \"" << A->getOption().getName() << "\", "
604eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch                 << "Values: {";
605eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    for (unsigned j = 0; j < A->getNumValues(); ++j) {
606eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch      if (j)
607eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch        llvm::errs() << ", ";
608eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch      llvm::errs() << '"' << A->getValue(Args, j) << '"';
609eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    }
610eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    llvm::errs() << "}\n";
611ca12bfac764ba476d6cd062bf1dde12cc64c3f40Ben Murdoch  }
612eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch}
613eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch
614eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdochvoid Driver::PrintHelp(bool ShowHidden) const {
615eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(),
616eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch                      ShowHidden);
617ca12bfac764ba476d6cd062bf1dde12cc64c3f40Ben Murdoch}
618ca12bfac764ba476d6cd062bf1dde12cc64c3f40Ben Murdoch
619eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdochvoid Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
620eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  // FIXME: The following handlers should use a callback mechanism, we don't
621eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  // know what the client would like to do.
622eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  OS << getClangFullVersion() << '\n';
623eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  const ToolChain &TC = C.getDefaultToolChain();
624eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  OS << "Target: " << TC.getTripleString() << '\n';
625eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch
626eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  // Print the threading model.
627eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  //
628eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  // FIXME: Implement correctly.
629eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  OS << "Thread model: " << "posix" << '\n';
630eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch}
631eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch
632eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch/// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
633eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch/// option.
634eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdochstatic void PrintDiagnosticCategories(raw_ostream &OS) {
635eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  // Skip the empty category.
636eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories();
637eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch       i != max; ++i)
638eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
639eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch}
640eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch
641eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdochbool Driver::HandleImmediateArgs(const Compilation &C) {
642eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  // The order these options are handled in gcc is all over the place, but we
643eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  // don't expect inconsistencies w.r.t. that to matter in practice.
644eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch
645eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
646eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
647eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    return false;
648eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  }
649eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch
650eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  if (C.getArgs().hasArg(options::OPT_dumpversion)) {
651eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    // Since -dumpversion is only implemented for pedantic GCC compatibility, we
652eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    // return an answer which matches our definition of __VERSION__.
653eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    //
654eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    // If we want to return a more correct answer some day, then we should
655eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    // introduce a non-pedantically GCC compatible mode to Clang in which we
656eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    // provide sensible definitions for -dumpversion, __VERSION__, etc.
657eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    llvm::outs() << "4.2.1\n";
658eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    return false;
659eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  }
660eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch
661eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
662eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    PrintDiagnosticCategories(llvm::outs());
663eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    return false;
664eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  }
665eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch
666eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  if (C.getArgs().hasArg(options::OPT_help) ||
667eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch      C.getArgs().hasArg(options::OPT__help_hidden)) {
668eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
669eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    return false;
670eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  }
671eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch
672eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  if (C.getArgs().hasArg(options::OPT__version)) {
673eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    // Follow gcc behavior and use stdout for --version and stderr for -v.
674eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    PrintVersion(C, llvm::outs());
675eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    return false;
676eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  }
677eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch
678eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  if (C.getArgs().hasArg(options::OPT_v) ||
679eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch      C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
680eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    PrintVersion(C, llvm::errs());
681ca12bfac764ba476d6cd062bf1dde12cc64c3f40Ben Murdoch    SuppressMissingInputWarning = true;
682eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  }
683eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch
684eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  const ToolChain &TC = C.getDefaultToolChain();
685eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
686eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    llvm::outs() << "programs: =";
687eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    for (ToolChain::path_list::const_iterator it = TC.getProgramPaths().begin(),
688eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch           ie = TC.getProgramPaths().end(); it != ie; ++it) {
689eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch      if (it != TC.getProgramPaths().begin())
690eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch        llvm::outs() << ':';
691ca12bfac764ba476d6cd062bf1dde12cc64c3f40Ben Murdoch      llvm::outs() << *it;
692eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    }
693eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    llvm::outs() << "\n";
694eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    llvm::outs() << "libraries: =" << ResourceDir;
695eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch
696eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    StringRef sysroot = C.getSysRoot();
697ca12bfac764ba476d6cd062bf1dde12cc64c3f40Ben Murdoch
698ca12bfac764ba476d6cd062bf1dde12cc64c3f40Ben Murdoch    for (ToolChain::path_list::const_iterator it = TC.getFilePaths().begin(),
699eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch           ie = TC.getFilePaths().end(); it != ie; ++it) {
700eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch      llvm::outs() << ':';
701eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch      const char *path = it->c_str();
702eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch      if (path[0] == '=')
703eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch        llvm::outs() << sysroot << path + 1;
704eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch      else
705eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch        llvm::outs() << path;
706eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    }
707eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    llvm::outs() << "\n";
708eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    return false;
709eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  }
710eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch
711eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  // FIXME: The following handlers should use a callback mechanism, we don't
712eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  // know what the client would like to do.
713eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
714eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    llvm::outs() << GetFilePath(A->getValue(C.getArgs()), TC) << "\n";
715eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    return false;
716868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  }
717868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)
7182a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
7192a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    llvm::outs() << GetProgramPath(A->getValue(C.getArgs()), TC) << "\n";
7202a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    return false;
721868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  }
722868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)
723868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
724868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)    llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
725a93a17c8d99d686bd4a1511e5504e5e6cc9fcadfTorne (Richard Coles)    return false;
726a93a17c8d99d686bd4a1511e5504e5e6cc9fcadfTorne (Richard Coles)  }
7272a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
728a93a17c8d99d686bd4a1511e5504e5e6cc9fcadfTorne (Richard Coles)  if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
729868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)    // FIXME: We need tool chain support for this.
730868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)    llvm::outs() << ".;\n";
731868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)
732868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)    switch (C.getDefaultToolChain().getTriple().getArch()) {
7332a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    default:
7342a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      break;
7352a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
73690dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    case llvm::Triple::x86_64:
737868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)      llvm::outs() << "x86_64;@m64" << "\n";
738868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)      break;
739868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)
7402a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    case llvm::Triple::ppc64:
7412a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      llvm::outs() << "ppc64;@m64" << "\n";
7422a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      break;
743868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)    }
744868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)    return false;
7452a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  }
7462a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
7472a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // FIXME: What is the difference between print-multi-directory and
748a93a17c8d99d686bd4a1511e5504e5e6cc9fcadfTorne (Richard Coles)  // print-multi-os-directory?
7492a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  if (C.getArgs().hasArg(options::OPT_print_multi_directory) ||
750ca12bfac764ba476d6cd062bf1dde12cc64c3f40Ben Murdoch      C.getArgs().hasArg(options::OPT_print_multi_os_directory)) {
7512a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    switch (C.getDefaultToolChain().getTriple().getArch()) {
7522a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    default:
753a93a17c8d99d686bd4a1511e5504e5e6cc9fcadfTorne (Richard Coles)    case llvm::Triple::x86:
75490dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    case llvm::Triple::ppc:
75590dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)      llvm::outs() << "." << "\n";
7562a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      break;
75790dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)
7582a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    case llvm::Triple::x86_64:
7592a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      llvm::outs() << "x86_64" << "\n";
76090dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)      break;
761a93a17c8d99d686bd4a1511e5504e5e6cc9fcadfTorne (Richard Coles)
76290dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    case llvm::Triple::ppc64:
76390dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)      llvm::outs() << "ppc64" << "\n";
764ca12bfac764ba476d6cd062bf1dde12cc64c3f40Ben Murdoch      break;
765ca12bfac764ba476d6cd062bf1dde12cc64c3f40Ben Murdoch    }
766a93a17c8d99d686bd4a1511e5504e5e6cc9fcadfTorne (Richard Coles)    return false;
767a93a17c8d99d686bd4a1511e5504e5e6cc9fcadfTorne (Richard Coles)  }
7682a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
7692a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  return true;
7702a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)}
7712a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
7722a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)static unsigned PrintActions1(const Compilation &C, Action *A,
773a93a17c8d99d686bd4a1511e5504e5e6cc9fcadfTorne (Richard Coles)                              std::map<Action*, unsigned> &Ids) {
7742a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  if (Ids.count(A))
775a93a17c8d99d686bd4a1511e5504e5e6cc9fcadfTorne (Richard Coles)    return Ids[A];
776a93a17c8d99d686bd4a1511e5504e5e6cc9fcadfTorne (Richard Coles)
777a93a17c8d99d686bd4a1511e5504e5e6cc9fcadfTorne (Richard Coles)  std::string str;
7782a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  llvm::raw_string_ostream os(str);
7792a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
78090dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  os << Action::getClassName(A->getKind()) << ", ";
78190dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  if (InputAction *IA = dyn_cast<InputAction>(A)) {
78290dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    os << "\"" << IA->getInputArg().getValue(C.getArgs()) << "\"";
78390dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
78490dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    os << '"' << BIA->getArchName() << '"'
78590dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)       << ", {" << PrintActions1(C, *BIA->begin(), Ids) << "}";
78690dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  } else {
78790dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    os << "{";
78890dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    for (Action::iterator it = A->begin(), ie = A->end(); it != ie;) {
78990dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)      os << PrintActions1(C, *it, Ids);
79090dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)      ++it;
79190dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)      if (it != ie)
79290dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)        os << ", ";
79390dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    }
79490dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    os << "}";
79590dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  }
79690dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)
79790dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  unsigned Id = Ids.size();
79890dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  Ids[A] = Id;
79990dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  llvm::errs() << Id << ": " << os.str() << ", "
80090dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)               << types::getTypeName(A->getType()) << "\n";
80190dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)
80290dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  return Id;
80390dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)}
80490dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)
80590dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)void Driver::PrintActions(const Compilation &C) const {
80690dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  std::map<Action*, unsigned> Ids;
80790dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  for (ActionList::const_iterator it = C.getActions().begin(),
80890dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)         ie = C.getActions().end(); it != ie; ++it)
80990dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    PrintActions1(C, *it, Ids);
81090dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)}
81190dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)
81290dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)/// \brief Check whether the given input tree contains any compilation or
813868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)/// assembly actions.
81490dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)static bool ContainsCompileOrAssembleAction(const Action *A) {
8152a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  if (isa<CompileJobAction>(A) || isa<AssembleJobAction>(A))
8162a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    return true;
8172a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
8182a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  for (Action::const_iterator it = A->begin(), ie = A->end(); it != ie; ++it)
8192a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    if (ContainsCompileOrAssembleAction(*it))
8202a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      return true;
821868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)
822868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  return false;
823868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)}
824868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)
82590dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)void Driver::BuildUniversalActions(const ToolChain &TC,
826868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)                                   const DerivedArgList &Args,
827868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)                                   const InputList &BAInputs,
8282a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                                   ActionList &Actions) const {
829868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
830868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  // Collect the list of architectures. Duplicates are allowed, but should only
831868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  // be handled once (in the order seen).
832868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  llvm::StringSet<> ArchNames;
8332a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  SmallVector<const char *, 4> Archs;
834868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
835868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)       it != ie; ++it) {
8362a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    Arg *A = *it;
8372a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
8382a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    if (A->getOption().matches(options::OPT_arch)) {
8392a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      // Validate the option here; we don't save the type here because its
8402a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      // particular spelling may participate in other driver choices.
841ca12bfac764ba476d6cd062bf1dde12cc64c3f40Ben Murdoch      llvm::Triple::ArchType Arch =
8422a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)        llvm::Triple::getArchTypeForDarwinArchName(A->getValue(Args));
843a93a17c8d99d686bd4a1511e5504e5e6cc9fcadfTorne (Richard Coles)      if (Arch == llvm::Triple::UnknownArch) {
84490dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)        Diag(clang::diag::err_drv_invalid_arch_name)
84590dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)          << A->getAsString(Args);
8462a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)        continue;
8472a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      }
848a93a17c8d99d686bd4a1511e5504e5e6cc9fcadfTorne (Richard Coles)
8492a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      A->claim();
8502a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      if (ArchNames.insert(A->getValue(Args)))
851ca12bfac764ba476d6cd062bf1dde12cc64c3f40Ben Murdoch        Archs.push_back(A->getValue(Args));
85290dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    }
8532a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  }
85490dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)
855b2df76ea8fec9e32f6f3718986dba0d95315b29cTorne (Richard Coles)  // When there is no explicit arch for this platform, make sure we still bind
85690dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  // the architecture (to the default) so that -Xarch_ is handled correctly.
85790dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  if (!Archs.size())
858ca12bfac764ba476d6cd062bf1dde12cc64c3f40Ben Murdoch    Archs.push_back(Args.MakeArgString(TC.getArchName()));
859ca12bfac764ba476d6cd062bf1dde12cc64c3f40Ben Murdoch
8602a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // FIXME: We killed off some others but these aren't yet detected in a
86190dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  // functional manner. If we added information to jobs about which "auxiliary"
8622a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // files they wrote then we could detect the conflict these cause downstream.
86390dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  if (Archs.size() > 1) {
8642a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    // No recovery needed, the point of this is just to prevent
8652a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    // overwriting the same files.
8662a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    if (const Arg *A = Args.getLastArg(options::OPT_save_temps))
86790dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)      Diag(clang::diag::err_drv_invalid_opt_with_multiple_archs)
8682a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)        << A->getAsString(Args);
8692a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  }
8702a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
8712a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  ActionList SingleActions;
8722a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  BuildActions(TC, Args, BAInputs, SingleActions);
8732a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
8742a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // Add in arch bindings for every top level action, as well as lipo and
8752a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // dsymutil steps if needed.
8762a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  for (unsigned i = 0, e = SingleActions.size(); i != e; ++i) {
87790dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    Action *Act = SingleActions[i];
87890dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)
8792a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    // Make sure we can lipo this kind of output. If not (and it is an actual
8802a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    // output) then we disallow, since we can't create an output file with the
881868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)    // right name without overwriting it. We could remove this oddity by just
882eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    // changing the output names to include the arch, which would also fix
883eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    // -save-temps. Compatibility wins for now.
884eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch
88590dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
88690dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)      Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
88790dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)        << types::getTypeName(Act->getType());
88890dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)
889868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)    ActionList Inputs;
890eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    for (unsigned i = 0, e = Archs.size(); i != e; ++i) {
891eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch      Inputs.push_back(new BindArchAction(Act, Archs[i]));
892eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch      if (i != 0)
89390dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)        Inputs.back()->setOwnsInputs(false);
89490dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    }
89590dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)
89690dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    // Lipo if necessary, we do it this way because we need to set the arch flag
89790dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    // so that -Xarch_ gets overwritten.
89890dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
89990dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)      Actions.append(Inputs.begin(), Inputs.end());
900868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)    else
90190dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)      Actions.push_back(new LipoJobAction(Inputs, Act->getType()));
9022a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
9032a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    // Handle debug info queries.
9042a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    Arg *A = Args.getLastArg(options::OPT_g_Group);
9052a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    if (A && !A->getOption().matches(options::OPT_g0) &&
9062a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)        !A->getOption().matches(options::OPT_gstabs) &&
9072a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)        ContainsCompileOrAssembleAction(Actions.back())) {
908868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)
909868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)      // Add a 'dsymutil' step if necessary, when debug info is enabled and we
910868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)      // have a compile input. We need to run 'dsymutil' ourselves in such cases
911868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)      // because the debug info will refer to a temporary object file which is
912868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)      // will be removed at the end of the compilation process.
913868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)      if (Act->getType() == types::TY_Image) {
914868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)        ActionList Inputs;
9152a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)        Inputs.push_back(Actions.back());
916868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)        Actions.pop_back();
917868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)        Actions.push_back(new DsymutilJobAction(Inputs, types::TY_dSYM));
9182a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      }
9192a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
920868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)      // Verify the output (debug information only) if we passed '-verify'.
921868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)      if (Args.hasArg(options::OPT_verify)) {
9222a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)        ActionList VerifyInputs;
923868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)        VerifyInputs.push_back(Actions.back());
924868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)        Actions.pop_back();
925868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)        Actions.push_back(new VerifyJobAction(VerifyInputs,
926868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)                                              types::TY_Nothing));
9272a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      }
9282a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    }
9292a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  }
9302a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)}
9312a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
932ca12bfac764ba476d6cd062bf1dde12cc64c3f40Ben Murdoch// Construct a the list of inputs and their types.
9332a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)void Driver::BuildInputs(const ToolChain &TC, const DerivedArgList &Args,
934a93a17c8d99d686bd4a1511e5504e5e6cc9fcadfTorne (Richard Coles)                         InputList &Inputs) const {
93590dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  // Track the current user specified (-x) input. We also explicitly track the
93690dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  // argument used to set the type; we only want to claim the type when we
9372a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // actually use it, so we warn about unused -x arguments.
9382a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  types::ID InputType = types::TY_Nothing;
93990dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  Arg *InputTypeArg = 0;
9402a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
9412a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
942ca12bfac764ba476d6cd062bf1dde12cc64c3f40Ben Murdoch       it != ie; ++it) {
9432a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    Arg *A = *it;
94490dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)
945b2df76ea8fec9e32f6f3718986dba0d95315b29cTorne (Richard Coles)    if (isa<InputOption>(A->getOption())) {
94690dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)      const char *Value = A->getValue(Args);
94790dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)      types::ID Ty = types::TY_INVALID;
948ca12bfac764ba476d6cd062bf1dde12cc64c3f40Ben Murdoch
949ca12bfac764ba476d6cd062bf1dde12cc64c3f40Ben Murdoch      // Infer the input type if necessary.
9502a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      if (InputType == types::TY_Nothing) {
95190dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)        // If there was an explicit arg for this, claim it.
9522a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)        if (InputTypeArg)
9532a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)          InputTypeArg->claim();
9542a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
95590dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)        // stdin must be handled specially.
9562a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)        if (memcmp(Value, "-", 2) == 0) {
95790dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)          // If running with -E, treat as a C input (this changes the builtin
9582a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)          // macros, for example). This may be overridden by -ObjC below.
9592a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)          //
9602a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)          // Otherwise emit an error but still use a valid type to avoid
96190dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)          // spurious errors (e.g., no inputs).
9622a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)          if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP)
9632a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)            Diag(clang::diag::err_drv_unknown_stdin_type);
9642a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)          Ty = types::TY_C;
9652a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)        } else {
9662a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)          // Otherwise lookup by extension.
9672a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)          // Fallback is C if invoked as C preprocessor or Object otherwise.
9682a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)          // We use a host hook here because Darwin at least has its own
9692a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)          // idea of what .s is.
9702a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)          if (const char *Ext = strrchr(Value, '.'))
971c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)            Ty = TC.LookupTypeForExtension(Ext + 1);
972c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)
97390dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)          if (Ty == types::TY_INVALID) {
97490dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)            if (CCCIsCPP)
97590dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)              Ty = types::TY_C;
976868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)            else
977eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch              Ty = types::TY_Object;
978eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch          }
979eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch
98090dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)          // If the driver is invoked as C++ compiler (like clang++ or c++) it
98190dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)          // should autodetect some input files as C++ for g++ compatibility.
98290dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)          if (CCCIsCXX) {
98390dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)            types::ID OldTy = Ty;
984868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)            Ty = types::lookupCXXTypeForCType(Ty);
985eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch
986eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch            if (Ty != OldTy)
987eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch              Diag(clang::diag::warn_drv_treating_input_as_cxx)
98890dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)                << getTypeName(OldTy) << getTypeName(Ty);
98990dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)          }
9902a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)        }
9912a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
992a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)        // -ObjC and -ObjC++ override the default language, but only for "source
993a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)        // files". We just treat everything that isn't a linker input as a
994a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)        // source file.
995a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)        //
996a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)        // FIXME: Clean this up if we move the phase sequence into the type.
997a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)        if (Ty != types::TY_Object) {
998a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)          if (Args.hasArg(options::OPT_ObjC))
999a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)            Ty = types::TY_ObjC;
1000a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)          else if (Args.hasArg(options::OPT_ObjCXX))
1001a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)            Ty = types::TY_ObjCXX;
1002a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)        }
1003a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)      } else {
1004a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)        assert(InputTypeArg && "InputType set w/o InputTypeArg");
1005a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)        InputTypeArg->claim();
1006a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)        Ty = InputType;
1007a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)      }
1008a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)
1009a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)      // Check that the file exists, if enabled.
1010a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)      if (CheckInputsExist && memcmp(Value, "-", 2) != 0) {
1011a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)        SmallString<64> Path(Value);
1012a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)        if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory)) {
1013a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)          SmallString<64> Directory(WorkDir->getValue(Args));
1014a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)          if (llvm::sys::path::is_absolute(Directory.str())) {
1015a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)            llvm::sys::path::append(Directory, Value);
1016a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)            Path.assign(Directory);
1017a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)          }
1018a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)        }
1019a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)
1020a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)        bool exists = false;
1021a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)        if (llvm::sys::fs::exists(Path.c_str(), exists) || !exists)
1022a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)          Diag(clang::diag::err_drv_no_such_file) << Path.str();
1023a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)        else
1024a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)          Inputs.push_back(std::make_pair(Ty, A));
1025a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)      } else
1026a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)        Inputs.push_back(std::make_pair(Ty, A));
1027a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)
1028a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)    } else if (A->getOption().isLinkerInput()) {
1029a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)      // Just treat as object type, we could make a special type for this if
1030a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)      // necessary.
1031a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)      Inputs.push_back(std::make_pair(types::TY_Object, A));
1032a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)
1033a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)    } else if (A->getOption().matches(options::OPT_x)) {
1034a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)      InputTypeArg = A;
1035a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)      InputType = types::lookupTypeForTypeSpecifier(A->getValue(Args));
1036a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)      A->claim();
1037a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)
1038a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)      // Follow gcc behavior and treat as linker input for invalid -x
1039a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)      // options. Its not clear why we shouldn't just revert to unknown; but
1040c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdoch      // this isn't very important, we might as well be bug compatible.
1041c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdoch      if (!InputType) {
1042a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)        Diag(clang::diag::err_drv_unknown_language) << A->getValue(Args);
1043a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)        InputType = types::TY_Object;
1044a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)      }
1045a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)    }
1046a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)  }
1047a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)  if (CCCIsCPP && Inputs.empty()) {
1048a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)    // If called as standalone preprocessor, stdin is processed
1049a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)    // if no other input is present.
1050a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)    unsigned Index = Args.getBaseArgs().MakeIndex("-");
1051a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)    Arg *A = Opts->ParseOneArg(Args, Index);
1052a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)    A->claim();
1053a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)    Inputs.push_back(std::make_pair(types::TY_C, A));
1054a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)  }
1055a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)}
1056a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)
10572a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)void Driver::BuildActions(const ToolChain &TC, const DerivedArgList &Args,
10582a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                          const InputList &Inputs, ActionList &Actions) const {
10595821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
10605821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
10615821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  if (!SuppressMissingInputWarning && Inputs.empty()) {
1062    Diag(clang::diag::err_drv_no_input_files);
1063    return;
1064  }
1065
1066  Arg *FinalPhaseArg;
1067  phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
1068
1069  // Reject -Z* at the top level, these options should never have been exposed
1070  // by gcc.
1071  if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
1072    Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
1073
1074  // Construct the actions to perform.
1075  ActionList LinkerInputs;
1076  unsigned NumSteps = 0;
1077  for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
1078    types::ID InputType = Inputs[i].first;
1079    const Arg *InputArg = Inputs[i].second;
1080
1081    NumSteps = types::getNumCompilationPhases(InputType);
1082    assert(NumSteps && "Invalid number of steps!");
1083
1084    // If the first step comes after the final phase we are doing as part of
1085    // this compilation, warn the user about it.
1086    phases::ID InitialPhase = types::getCompilationPhase(InputType, 0);
1087    if (InitialPhase > FinalPhase) {
1088      // Claim here to avoid the more general unused warning.
1089      InputArg->claim();
1090
1091      // Suppress all unused style warnings with -Qunused-arguments
1092      if (Args.hasArg(options::OPT_Qunused_arguments))
1093        continue;
1094
1095      // Special case '-E' warning on a previously preprocessed file to make
1096      // more sense.
1097      if (InitialPhase == phases::Compile && FinalPhase == phases::Preprocess &&
1098          getPreprocessedType(InputType) == types::TY_INVALID)
1099        Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
1100          << InputArg->getAsString(Args)
1101          << FinalPhaseArg->getOption().getName();
1102      else
1103        Diag(clang::diag::warn_drv_input_file_unused)
1104          << InputArg->getAsString(Args)
1105          << getPhaseName(InitialPhase)
1106          << FinalPhaseArg->getOption().getName();
1107      continue;
1108    }
1109
1110    // Build the pipeline for this file.
1111    OwningPtr<Action> Current(new InputAction(*InputArg, InputType));
1112    for (unsigned i = 0; i != NumSteps; ++i) {
1113      phases::ID Phase = types::getCompilationPhase(InputType, i);
1114
1115      // We are done if this step is past what the user requested.
1116      if (Phase > FinalPhase)
1117        break;
1118
1119      // Queue linker inputs.
1120      if (Phase == phases::Link) {
1121        assert(i + 1 == NumSteps && "linking must be final compilation step.");
1122        LinkerInputs.push_back(Current.take());
1123        break;
1124      }
1125
1126      // Some types skip the assembler phase (e.g., llvm-bc), but we can't
1127      // encode this in the steps because the intermediate type depends on
1128      // arguments. Just special case here.
1129      if (Phase == phases::Assemble && Current->getType() != types::TY_PP_Asm)
1130        continue;
1131
1132      // Otherwise construct the appropriate action.
1133      Current.reset(ConstructPhaseAction(Args, Phase, Current.take()));
1134      if (Current->getType() == types::TY_Nothing)
1135        break;
1136    }
1137
1138    // If we ended with something, add to the output list.
1139    if (Current)
1140      Actions.push_back(Current.take());
1141  }
1142
1143  // Add a link action if necessary.
1144  if (!LinkerInputs.empty())
1145    Actions.push_back(new LinkJobAction(LinkerInputs, types::TY_Image));
1146
1147  // If we are linking, claim any options which are obviously only used for
1148  // compilation.
1149  if (FinalPhase == phases::Link && (NumSteps == 1))
1150    Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
1151}
1152
1153Action *Driver::ConstructPhaseAction(const ArgList &Args, phases::ID Phase,
1154                                     Action *Input) const {
1155  llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
1156  // Build the appropriate action.
1157  switch (Phase) {
1158  case phases::Link: llvm_unreachable("link action invalid here.");
1159  case phases::Preprocess: {
1160    types::ID OutputTy;
1161    // -{M, MM} alter the output type.
1162    if (Args.hasArg(options::OPT_M, options::OPT_MM)) {
1163      OutputTy = types::TY_Dependencies;
1164    } else {
1165      OutputTy = types::getPreprocessedType(Input->getType());
1166      assert(OutputTy != types::TY_INVALID &&
1167             "Cannot preprocess this input type!");
1168    }
1169    return new PreprocessJobAction(Input, OutputTy);
1170  }
1171  case phases::Precompile:
1172    return new PrecompileJobAction(Input, types::TY_PCH);
1173  case phases::Compile: {
1174    if (Args.hasArg(options::OPT_fsyntax_only)) {
1175      return new CompileJobAction(Input, types::TY_Nothing);
1176    } else if (Args.hasArg(options::OPT_rewrite_objc)) {
1177      return new CompileJobAction(Input, types::TY_RewrittenObjC);
1178    } else if (Args.hasArg(options::OPT_rewrite_legacy_objc)) {
1179      return new CompileJobAction(Input, types::TY_RewrittenLegacyObjC);
1180    } else if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto)) {
1181      return new AnalyzeJobAction(Input, types::TY_Plist);
1182    } else if (Args.hasArg(options::OPT__migrate)) {
1183      return new MigrateJobAction(Input, types::TY_Remap);
1184    } else if (Args.hasArg(options::OPT_emit_ast)) {
1185      return new CompileJobAction(Input, types::TY_AST);
1186    } else if (IsUsingLTO(Args)) {
1187      types::ID Output =
1188        Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
1189      return new CompileJobAction(Input, Output);
1190    } else {
1191      return new CompileJobAction(Input, types::TY_PP_Asm);
1192    }
1193  }
1194  case phases::Assemble:
1195    return new AssembleJobAction(Input, types::TY_Object);
1196  }
1197
1198  llvm_unreachable("invalid phase in ConstructPhaseAction");
1199}
1200
1201bool Driver::IsUsingLTO(const ArgList &Args) const {
1202  // Check for -emit-llvm or -flto.
1203  if (Args.hasArg(options::OPT_emit_llvm) ||
1204      Args.hasFlag(options::OPT_flto, options::OPT_fno_lto, false))
1205    return true;
1206
1207  // Check for -O4.
1208  if (const Arg *A = Args.getLastArg(options::OPT_O_Group))
1209      return A->getOption().matches(options::OPT_O4);
1210
1211  return false;
1212}
1213
1214void Driver::BuildJobs(Compilation &C) const {
1215  llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
1216
1217  Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
1218
1219  // It is an error to provide a -o option if we are making multiple output
1220  // files.
1221  if (FinalOutput) {
1222    unsigned NumOutputs = 0;
1223    for (ActionList::const_iterator it = C.getActions().begin(),
1224           ie = C.getActions().end(); it != ie; ++it)
1225      if ((*it)->getType() != types::TY_Nothing)
1226        ++NumOutputs;
1227
1228    if (NumOutputs > 1) {
1229      Diag(clang::diag::err_drv_output_argument_with_multiple_files);
1230      FinalOutput = 0;
1231    }
1232  }
1233
1234  for (ActionList::const_iterator it = C.getActions().begin(),
1235         ie = C.getActions().end(); it != ie; ++it) {
1236    Action *A = *it;
1237
1238    // If we are linking an image for multiple archs then the linker wants
1239    // -arch_multiple and -final_output <final image name>. Unfortunately, this
1240    // doesn't fit in cleanly because we have to pass this information down.
1241    //
1242    // FIXME: This is a hack; find a cleaner way to integrate this into the
1243    // process.
1244    const char *LinkingOutput = 0;
1245    if (isa<LipoJobAction>(A)) {
1246      if (FinalOutput)
1247        LinkingOutput = FinalOutput->getValue(C.getArgs());
1248      else
1249        LinkingOutput = DefaultImageName.c_str();
1250    }
1251
1252    InputInfo II;
1253    BuildJobsForAction(C, A, &C.getDefaultToolChain(),
1254                       /*BoundArch*/0,
1255                       /*AtTopLevel*/ true,
1256                       /*LinkingOutput*/ LinkingOutput,
1257                       II);
1258  }
1259
1260  // If the user passed -Qunused-arguments or there were errors, don't warn
1261  // about any unused arguments.
1262  if (Diags.hasErrorOccurred() ||
1263      C.getArgs().hasArg(options::OPT_Qunused_arguments))
1264    return;
1265
1266  // Claim -### here.
1267  (void) C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
1268
1269  for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end();
1270       it != ie; ++it) {
1271    Arg *A = *it;
1272
1273    // FIXME: It would be nice to be able to send the argument to the
1274    // DiagnosticsEngine, so that extra values, position, and so on could be
1275    // printed.
1276    if (!A->isClaimed()) {
1277      if (A->getOption().hasNoArgumentUnused())
1278        continue;
1279
1280      // Suppress the warning automatically if this is just a flag, and it is an
1281      // instance of an argument we already claimed.
1282      const Option &Opt = A->getOption();
1283      if (isa<FlagOption>(Opt)) {
1284        bool DuplicateClaimed = false;
1285
1286        for (arg_iterator it = C.getArgs().filtered_begin(&Opt),
1287               ie = C.getArgs().filtered_end(); it != ie; ++it) {
1288          if ((*it)->isClaimed()) {
1289            DuplicateClaimed = true;
1290            break;
1291          }
1292        }
1293
1294        if (DuplicateClaimed)
1295          continue;
1296      }
1297
1298      Diag(clang::diag::warn_drv_unused_argument)
1299        << A->getAsString(C.getArgs());
1300    }
1301  }
1302}
1303
1304static const Tool &SelectToolForJob(Compilation &C, const ToolChain *TC,
1305                                    const JobAction *JA,
1306                                    const ActionList *&Inputs) {
1307  const Tool *ToolForJob = 0;
1308
1309  // See if we should look for a compiler with an integrated assembler. We match
1310  // bottom up, so what we are actually looking for is an assembler job with a
1311  // compiler input.
1312
1313  if (C.getArgs().hasFlag(options::OPT_integrated_as,
1314                          options::OPT_no_integrated_as,
1315                          TC->IsIntegratedAssemblerDefault()) &&
1316      !C.getArgs().hasArg(options::OPT_save_temps) &&
1317      isa<AssembleJobAction>(JA) &&
1318      Inputs->size() == 1 && isa<CompileJobAction>(*Inputs->begin())) {
1319    const Tool &Compiler = TC->SelectTool(
1320      C, cast<JobAction>(**Inputs->begin()), (*Inputs)[0]->getInputs());
1321    if (Compiler.hasIntegratedAssembler()) {
1322      Inputs = &(*Inputs)[0]->getInputs();
1323      ToolForJob = &Compiler;
1324    }
1325  }
1326
1327  // Otherwise use the tool for the current job.
1328  if (!ToolForJob)
1329    ToolForJob = &TC->SelectTool(C, *JA, *Inputs);
1330
1331  // See if we should use an integrated preprocessor. We do so when we have
1332  // exactly one input, since this is the only use case we care about
1333  // (irrelevant since we don't support combine yet).
1334  if (Inputs->size() == 1 && isa<PreprocessJobAction>(*Inputs->begin()) &&
1335      !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
1336      !C.getArgs().hasArg(options::OPT_traditional_cpp) &&
1337      !C.getArgs().hasArg(options::OPT_save_temps) &&
1338      ToolForJob->hasIntegratedCPP())
1339    Inputs = &(*Inputs)[0]->getInputs();
1340
1341  return *ToolForJob;
1342}
1343
1344void Driver::BuildJobsForAction(Compilation &C,
1345                                const Action *A,
1346                                const ToolChain *TC,
1347                                const char *BoundArch,
1348                                bool AtTopLevel,
1349                                const char *LinkingOutput,
1350                                InputInfo &Result) const {
1351  llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
1352
1353  if (const InputAction *IA = dyn_cast<InputAction>(A)) {
1354    // FIXME: It would be nice to not claim this here; maybe the old scheme of
1355    // just using Args was better?
1356    const Arg &Input = IA->getInputArg();
1357    Input.claim();
1358    if (Input.getOption().matches(options::OPT_INPUT)) {
1359      const char *Name = Input.getValue(C.getArgs());
1360      Result = InputInfo(Name, A->getType(), Name);
1361    } else
1362      Result = InputInfo(&Input, A->getType(), "");
1363    return;
1364  }
1365
1366  if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
1367    const ToolChain *TC;
1368    const char *ArchName = BAA->getArchName();
1369
1370    if (ArchName)
1371      TC = &getToolChain(C.getArgs(), ArchName);
1372    else
1373      TC = &C.getDefaultToolChain();
1374
1375    BuildJobsForAction(C, *BAA->begin(), TC, BAA->getArchName(),
1376                       AtTopLevel, LinkingOutput, Result);
1377    return;
1378  }
1379
1380  const ActionList *Inputs = &A->getInputs();
1381
1382  const JobAction *JA = cast<JobAction>(A);
1383  const Tool &T = SelectToolForJob(C, TC, JA, Inputs);
1384
1385  // Only use pipes when there is exactly one input.
1386  InputInfoList InputInfos;
1387  for (ActionList::const_iterator it = Inputs->begin(), ie = Inputs->end();
1388       it != ie; ++it) {
1389    // Treat dsymutil sub-jobs as being at the top-level too, they shouldn't get
1390    // temporary output names.
1391    //
1392    // FIXME: Clean this up.
1393    bool SubJobAtTopLevel = false;
1394    if (AtTopLevel && isa<DsymutilJobAction>(A))
1395      SubJobAtTopLevel = true;
1396
1397    // Also treat verify sub-jobs as being at the top-level. They don't
1398    // produce any output and so don't need temporary output names.
1399    if (AtTopLevel && isa<VerifyJobAction>(A))
1400      SubJobAtTopLevel = true;
1401
1402    InputInfo II;
1403    BuildJobsForAction(C, *it, TC, BoundArch,
1404                       SubJobAtTopLevel, LinkingOutput, II);
1405    InputInfos.push_back(II);
1406  }
1407
1408  // Always use the first input as the base input.
1409  const char *BaseInput = InputInfos[0].getBaseInput();
1410
1411  // ... except dsymutil actions, which use their actual input as the base
1412  // input.
1413  if (JA->getType() == types::TY_dSYM)
1414    BaseInput = InputInfos[0].getFilename();
1415
1416  // Determine the place to write output to, if any.
1417  if (JA->getType() == types::TY_Nothing) {
1418    Result = InputInfo(A->getType(), BaseInput);
1419  } else {
1420    Result = InputInfo(GetNamedOutputPath(C, *JA, BaseInput, AtTopLevel),
1421                       A->getType(), BaseInput);
1422  }
1423
1424  if (CCCPrintBindings && !CCGenDiagnostics) {
1425    llvm::errs() << "# \"" << T.getToolChain().getTripleString() << '"'
1426                 << " - \"" << T.getName() << "\", inputs: [";
1427    for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
1428      llvm::errs() << InputInfos[i].getAsString();
1429      if (i + 1 != e)
1430        llvm::errs() << ", ";
1431    }
1432    llvm::errs() << "], output: " << Result.getAsString() << "\n";
1433  } else {
1434    T.ConstructJob(C, *JA, Result, InputInfos,
1435                   C.getArgsForToolChain(TC, BoundArch), LinkingOutput);
1436  }
1437}
1438
1439const char *Driver::GetNamedOutputPath(Compilation &C,
1440                                       const JobAction &JA,
1441                                       const char *BaseInput,
1442                                       bool AtTopLevel) const {
1443  llvm::PrettyStackTraceString CrashInfo("Computing output path");
1444  // Output to a user requested destination?
1445  if (AtTopLevel && !isa<DsymutilJobAction>(JA) &&
1446      !isa<VerifyJobAction>(JA)) {
1447    if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
1448      return C.addResultFile(FinalOutput->getValue(C.getArgs()));
1449  }
1450
1451  // Default to writing to stdout?
1452  if (AtTopLevel && isa<PreprocessJobAction>(JA) && !CCGenDiagnostics)
1453    return "-";
1454
1455  // Output to a temporary file?
1456  if ((!AtTopLevel && !C.getArgs().hasArg(options::OPT_save_temps)) ||
1457      CCGenDiagnostics) {
1458    StringRef Name = llvm::sys::path::filename(BaseInput);
1459    std::pair<StringRef, StringRef> Split = Name.split('.');
1460    std::string TmpName =
1461      GetTemporaryPath(Split.first, types::getTypeTempSuffix(JA.getType()));
1462    return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()));
1463  }
1464
1465  SmallString<128> BasePath(BaseInput);
1466  StringRef BaseName;
1467
1468  // Dsymutil actions should use the full path.
1469  if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
1470    BaseName = BasePath;
1471  else
1472    BaseName = llvm::sys::path::filename(BasePath);
1473
1474  // Determine what the derived output name should be.
1475  const char *NamedOutput;
1476  if (JA.getType() == types::TY_Image) {
1477    NamedOutput = DefaultImageName.c_str();
1478  } else {
1479    const char *Suffix = types::getTypeTempSuffix(JA.getType());
1480    assert(Suffix && "All types used for output should have a suffix.");
1481
1482    std::string::size_type End = std::string::npos;
1483    if (!types::appendSuffixForType(JA.getType()))
1484      End = BaseName.rfind('.');
1485    std::string Suffixed(BaseName.substr(0, End));
1486    Suffixed += '.';
1487    Suffixed += Suffix;
1488    NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
1489  }
1490
1491  // If we're saving temps and the temp file conflicts with the input file,
1492  // then avoid overwriting input file.
1493  if (!AtTopLevel && C.getArgs().hasArg(options::OPT_save_temps) &&
1494      NamedOutput == BaseName) {
1495
1496    bool SameFile = false;
1497    SmallString<256> Result;
1498    llvm::sys::fs::current_path(Result);
1499    llvm::sys::path::append(Result, BaseName);
1500    llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
1501    // Must share the same path to conflict.
1502    if (SameFile) {
1503      StringRef Name = llvm::sys::path::filename(BaseInput);
1504      std::pair<StringRef, StringRef> Split = Name.split('.');
1505      std::string TmpName =
1506        GetTemporaryPath(Split.first, types::getTypeTempSuffix(JA.getType()));
1507      return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()));
1508    }
1509  }
1510
1511  // As an annoying special case, PCH generation doesn't strip the pathname.
1512  if (JA.getType() == types::TY_PCH) {
1513    llvm::sys::path::remove_filename(BasePath);
1514    if (BasePath.empty())
1515      BasePath = NamedOutput;
1516    else
1517      llvm::sys::path::append(BasePath, NamedOutput);
1518    return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()));
1519  } else {
1520    return C.addResultFile(NamedOutput);
1521  }
1522}
1523
1524std::string Driver::GetFilePath(const char *Name, const ToolChain &TC) const {
1525  // Respect a limited subset of the '-Bprefix' functionality in GCC by
1526  // attempting to use this prefix when lokup up program paths.
1527  for (Driver::prefix_list::const_iterator it = PrefixDirs.begin(),
1528       ie = PrefixDirs.end(); it != ie; ++it) {
1529    std::string Dir(*it);
1530    if (Dir.empty())
1531      continue;
1532    if (Dir[0] == '=')
1533      Dir = SysRoot + Dir.substr(1);
1534    llvm::sys::Path P(Dir);
1535    P.appendComponent(Name);
1536    bool Exists;
1537    if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
1538      return P.str();
1539  }
1540
1541  llvm::sys::Path P(ResourceDir);
1542  P.appendComponent(Name);
1543  bool Exists;
1544  if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
1545    return P.str();
1546
1547  const ToolChain::path_list &List = TC.getFilePaths();
1548  for (ToolChain::path_list::const_iterator
1549         it = List.begin(), ie = List.end(); it != ie; ++it) {
1550    std::string Dir(*it);
1551    if (Dir.empty())
1552      continue;
1553    if (Dir[0] == '=')
1554      Dir = SysRoot + Dir.substr(1);
1555    llvm::sys::Path P(Dir);
1556    P.appendComponent(Name);
1557    bool Exists;
1558    if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
1559      return P.str();
1560  }
1561
1562  return Name;
1563}
1564
1565static bool isPathExecutable(llvm::sys::Path &P, bool WantFile) {
1566    bool Exists;
1567    return (WantFile ? !llvm::sys::fs::exists(P.str(), Exists) && Exists
1568                 : P.canExecute());
1569}
1570
1571std::string Driver::GetProgramPath(const char *Name, const ToolChain &TC,
1572                                   bool WantFile) const {
1573  // FIXME: Needs a better variable than DefaultTargetTriple
1574  std::string TargetSpecificExecutable(DefaultTargetTriple + "-" + Name);
1575  // Respect a limited subset of the '-Bprefix' functionality in GCC by
1576  // attempting to use this prefix when lokup up program paths.
1577  for (Driver::prefix_list::const_iterator it = PrefixDirs.begin(),
1578       ie = PrefixDirs.end(); it != ie; ++it) {
1579    llvm::sys::Path P(*it);
1580    P.appendComponent(TargetSpecificExecutable);
1581    if (isPathExecutable(P, WantFile)) return P.str();
1582    P.eraseComponent();
1583    P.appendComponent(Name);
1584    if (isPathExecutable(P, WantFile)) return P.str();
1585  }
1586
1587  const ToolChain::path_list &List = TC.getProgramPaths();
1588  for (ToolChain::path_list::const_iterator
1589         it = List.begin(), ie = List.end(); it != ie; ++it) {
1590    llvm::sys::Path P(*it);
1591    P.appendComponent(TargetSpecificExecutable);
1592    if (isPathExecutable(P, WantFile)) return P.str();
1593    P.eraseComponent();
1594    P.appendComponent(Name);
1595    if (isPathExecutable(P, WantFile)) return P.str();
1596  }
1597
1598  // If all else failed, search the path.
1599  llvm::sys::Path
1600      P(llvm::sys::Program::FindProgramByName(TargetSpecificExecutable));
1601  if (!P.empty())
1602    return P.str();
1603
1604  P = llvm::sys::Path(llvm::sys::Program::FindProgramByName(Name));
1605  if (!P.empty())
1606    return P.str();
1607
1608  return Name;
1609}
1610
1611std::string Driver::GetTemporaryPath(StringRef Prefix, const char *Suffix)
1612  const {
1613  // FIXME: This is lame; sys::Path should provide this function (in particular,
1614  // it should know how to find the temporary files dir).
1615  std::string Error;
1616  const char *TmpDir = ::getenv("TMPDIR");
1617  if (!TmpDir)
1618    TmpDir = ::getenv("TEMP");
1619  if (!TmpDir)
1620    TmpDir = ::getenv("TMP");
1621  if (!TmpDir)
1622    TmpDir = "/tmp";
1623  llvm::sys::Path P(TmpDir);
1624  P.appendComponent(Prefix);
1625  if (P.makeUnique(false, &Error)) {
1626    Diag(clang::diag::err_drv_unable_to_make_temp) << Error;
1627    return "";
1628  }
1629
1630  // FIXME: Grumble, makeUnique sometimes leaves the file around!?  PR3837.
1631  P.eraseFromDisk(false, 0);
1632
1633  P.appendSuffix(Suffix);
1634  return P.str();
1635}
1636
1637/// \brief Compute target triple from args.
1638///
1639/// This routine provides the logic to compute a target triple from various
1640/// args passed to the driver and the default triple string.
1641static llvm::Triple computeTargetTriple(StringRef DefaultTargetTriple,
1642                                        const ArgList &Args,
1643                                        StringRef DarwinArchName) {
1644  // FIXME: Already done in Compilation *Driver::BuildCompilation
1645  if (const Arg *A = Args.getLastArg(options::OPT_target))
1646    DefaultTargetTriple = A->getValue(Args);
1647
1648  llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
1649
1650  // Handle Darwin-specific options available here.
1651  if (Target.isOSDarwin()) {
1652    // If an explict Darwin arch name is given, that trumps all.
1653    if (!DarwinArchName.empty()) {
1654      Target.setArch(
1655        llvm::Triple::getArchTypeForDarwinArchName(DarwinArchName));
1656      return Target;
1657    }
1658
1659    // Handle the Darwin '-arch' flag.
1660    if (Arg *A = Args.getLastArg(options::OPT_arch)) {
1661      llvm::Triple::ArchType DarwinArch
1662        = llvm::Triple::getArchTypeForDarwinArchName(A->getValue(Args));
1663      if (DarwinArch != llvm::Triple::UnknownArch)
1664        Target.setArch(DarwinArch);
1665    }
1666  }
1667
1668  // Skip further flag support on OSes which don't support '-m32' or '-m64'.
1669  if (Target.getArchName() == "tce" ||
1670      Target.getOS() == llvm::Triple::AuroraUX ||
1671      Target.getOS() == llvm::Triple::Minix)
1672    return Target;
1673
1674  // Handle pseudo-target flags '-m32' and '-m64'.
1675  // FIXME: Should this information be in llvm::Triple?
1676  if (Arg *A = Args.getLastArg(options::OPT_m32, options::OPT_m64)) {
1677    if (A->getOption().matches(options::OPT_m32)) {
1678      if (Target.getArch() == llvm::Triple::x86_64)
1679        Target.setArch(llvm::Triple::x86);
1680      if (Target.getArch() == llvm::Triple::ppc64)
1681        Target.setArch(llvm::Triple::ppc);
1682    } else {
1683      if (Target.getArch() == llvm::Triple::x86)
1684        Target.setArch(llvm::Triple::x86_64);
1685      if (Target.getArch() == llvm::Triple::ppc)
1686        Target.setArch(llvm::Triple::ppc64);
1687    }
1688  }
1689
1690  return Target;
1691}
1692
1693const ToolChain &Driver::getToolChain(const ArgList &Args,
1694                                      StringRef DarwinArchName) const {
1695  llvm::Triple Target = computeTargetTriple(DefaultTargetTriple, Args,
1696                                            DarwinArchName);
1697
1698  ToolChain *&TC = ToolChains[Target.str()];
1699  if (!TC) {
1700    switch (Target.getOS()) {
1701    case llvm::Triple::AuroraUX:
1702      TC = new toolchains::AuroraUX(*this, Target, Args);
1703      break;
1704    case llvm::Triple::Darwin:
1705    case llvm::Triple::MacOSX:
1706    case llvm::Triple::IOS:
1707      if (Target.getArch() == llvm::Triple::x86 ||
1708          Target.getArch() == llvm::Triple::x86_64 ||
1709          Target.getArch() == llvm::Triple::arm ||
1710          Target.getArch() == llvm::Triple::thumb)
1711        TC = new toolchains::DarwinClang(*this, Target);
1712      else
1713        TC = new toolchains::Darwin_Generic_GCC(*this, Target, Args);
1714      break;
1715    case llvm::Triple::DragonFly:
1716      TC = new toolchains::DragonFly(*this, Target, Args);
1717      break;
1718    case llvm::Triple::OpenBSD:
1719      TC = new toolchains::OpenBSD(*this, Target, Args);
1720      break;
1721    case llvm::Triple::NetBSD:
1722      TC = new toolchains::NetBSD(*this, Target, Args);
1723      break;
1724    case llvm::Triple::FreeBSD:
1725      TC = new toolchains::FreeBSD(*this, Target, Args);
1726      break;
1727    case llvm::Triple::Minix:
1728      TC = new toolchains::Minix(*this, Target, Args);
1729      break;
1730    case llvm::Triple::Linux:
1731      if (Target.getArch() == llvm::Triple::hexagon)
1732        TC = new toolchains::Hexagon_TC(*this, Target);
1733      else
1734        TC = new toolchains::Linux(*this, Target, Args);
1735      break;
1736    case llvm::Triple::Solaris:
1737      TC = new toolchains::Solaris(*this, Target, Args);
1738      break;
1739    case llvm::Triple::Win32:
1740      TC = new toolchains::Windows(*this, Target);
1741      break;
1742    case llvm::Triple::MinGW32:
1743      // FIXME: We need a MinGW toolchain. Fallthrough for now.
1744    default:
1745      // TCE is an OSless target
1746      if (Target.getArchName() == "tce") {
1747        TC = new toolchains::TCEToolChain(*this, Target);
1748        break;
1749      }
1750
1751      TC = new toolchains::Generic_GCC(*this, Target, Args);
1752      break;
1753    }
1754  }
1755  return *TC;
1756}
1757
1758bool Driver::ShouldUseClangCompiler(const Compilation &C, const JobAction &JA,
1759                                    const llvm::Triple &Triple) const {
1760  // Check if user requested no clang, or clang doesn't understand this type (we
1761  // only handle single inputs for now).
1762  if (!CCCUseClang || JA.size() != 1 ||
1763      !types::isAcceptedByClang((*JA.begin())->getType()))
1764    return false;
1765
1766  // Otherwise make sure this is an action clang understands.
1767  if (isa<PreprocessJobAction>(JA)) {
1768    if (!CCCUseClangCPP) {
1769      Diag(clang::diag::warn_drv_not_using_clang_cpp);
1770      return false;
1771    }
1772  } else if (!isa<PrecompileJobAction>(JA) && !isa<CompileJobAction>(JA))
1773    return false;
1774
1775  // Use clang for C++?
1776  if (!CCCUseClangCXX && types::isCXX((*JA.begin())->getType())) {
1777    Diag(clang::diag::warn_drv_not_using_clang_cxx);
1778    return false;
1779  }
1780
1781  // Always use clang for precompiling, AST generation, and rewriting,
1782  // regardless of archs.
1783  if (isa<PrecompileJobAction>(JA) ||
1784      types::isOnlyAcceptedByClang(JA.getType()))
1785    return true;
1786
1787  // Finally, don't use clang if this isn't one of the user specified archs to
1788  // build.
1789  if (!CCCClangArchs.empty() && !CCCClangArchs.count(Triple.getArch())) {
1790    Diag(clang::diag::warn_drv_not_using_clang_arch) << Triple.getArchName();
1791    return false;
1792  }
1793
1794  return true;
1795}
1796
1797/// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
1798/// grouped values as integers. Numbers which are not provided are set to 0.
1799///
1800/// \return True if the entire string was parsed (9.2), or all groups were
1801/// parsed (10.3.5extrastuff).
1802bool Driver::GetReleaseVersion(const char *Str, unsigned &Major,
1803                               unsigned &Minor, unsigned &Micro,
1804                               bool &HadExtra) {
1805  HadExtra = false;
1806
1807  Major = Minor = Micro = 0;
1808  if (*Str == '\0')
1809    return true;
1810
1811  char *End;
1812  Major = (unsigned) strtol(Str, &End, 10);
1813  if (*Str != '\0' && *End == '\0')
1814    return true;
1815  if (*End != '.')
1816    return false;
1817
1818  Str = End+1;
1819  Minor = (unsigned) strtol(Str, &End, 10);
1820  if (*Str != '\0' && *End == '\0')
1821    return true;
1822  if (*End != '.')
1823    return false;
1824
1825  Str = End+1;
1826  Micro = (unsigned) strtol(Str, &End, 10);
1827  if (*Str != '\0' && *End == '\0')
1828    return true;
1829  if (Str == End)
1830    return false;
1831  HadExtra = true;
1832  return true;
1833}
1834