Home | History | Annotate | Download | only in Driver
      1 //===--- Driver.cpp - Clang GCC Compatible Driver -------------------------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 
     10 #include "clang/Driver/Driver.h"
     11 
     12 #include "clang/Driver/Action.h"
     13 #include "clang/Driver/Arg.h"
     14 #include "clang/Driver/ArgList.h"
     15 #include "clang/Driver/Compilation.h"
     16 #include "clang/Driver/DriverDiagnostic.h"
     17 #include "clang/Driver/Job.h"
     18 #include "clang/Driver/OptTable.h"
     19 #include "clang/Driver/Option.h"
     20 #include "clang/Driver/Options.h"
     21 #include "clang/Driver/Tool.h"
     22 #include "clang/Driver/ToolChain.h"
     23 
     24 #include "clang/Basic/Version.h"
     25 
     26 #include "llvm/ADT/ArrayRef.h"
     27 #include "llvm/ADT/StringSet.h"
     28 #include "llvm/ADT/OwningPtr.h"
     29 #include "llvm/Support/ErrorHandling.h"
     30 #include "llvm/Support/PrettyStackTrace.h"
     31 #include "llvm/Support/raw_ostream.h"
     32 #include "llvm/Support/FileSystem.h"
     33 #include "llvm/Support/Path.h"
     34 #include "llvm/Support/Program.h"
     35 
     36 #include "InputInfo.h"
     37 #include "ToolChains.h"
     38 
     39 #include <map>
     40 
     41 #include "clang/Config/config.h"
     42 
     43 using namespace clang::driver;
     44 using namespace clang;
     45 
     46 Driver::Driver(StringRef ClangExecutable,
     47                StringRef DefaultTargetTriple,
     48                StringRef DefaultImageName,
     49                bool IsProduction,
     50                DiagnosticsEngine &Diags)
     51   : Opts(createDriverOptTable()), Diags(Diags),
     52     ClangExecutable(ClangExecutable), SysRoot(DEFAULT_SYSROOT),
     53     UseStdLib(true), DefaultTargetTriple(DefaultTargetTriple),
     54     DefaultImageName(DefaultImageName),
     55     DriverTitle("clang \"gcc-compatible\" driver"),
     56     CCPrintOptionsFilename(0), CCPrintHeadersFilename(0),
     57     CCLogDiagnosticsFilename(0), CCCIsCXX(false),
     58     CCCIsCPP(false),CCCEcho(false), CCCPrintBindings(false),
     59     CCPrintOptions(false), CCPrintHeaders(false), CCLogDiagnostics(false),
     60     CCGenDiagnostics(false), CCCGenericGCCName(""), CheckInputsExist(true),
     61     CCCUseClang(true), CCCUseClangCXX(true), CCCUseClangCPP(true),
     62     ForcedClangUse(false), CCCUsePCH(true), SuppressMissingInputWarning(false) {
     63   if (IsProduction) {
     64     // In a "production" build, only use clang on architectures we expect to
     65     // work.
     66     //
     67     // During development its more convenient to always have the driver use
     68     // clang, but we don't want users to be confused when things don't work, or
     69     // to file bugs for things we don't support.
     70     CCCClangArchs.insert(llvm::Triple::x86);
     71     CCCClangArchs.insert(llvm::Triple::x86_64);
     72     CCCClangArchs.insert(llvm::Triple::arm);
     73   }
     74 
     75   Name = llvm::sys::path::stem(ClangExecutable);
     76   Dir  = llvm::sys::path::parent_path(ClangExecutable);
     77 
     78   // Compute the path to the resource directory.
     79   StringRef ClangResourceDir(CLANG_RESOURCE_DIR);
     80   SmallString<128> P(Dir);
     81   if (ClangResourceDir != "")
     82     llvm::sys::path::append(P, ClangResourceDir);
     83   else
     84     llvm::sys::path::append(P, "..", "lib", "clang", CLANG_VERSION_STRING);
     85   ResourceDir = P.str();
     86 }
     87 
     88 Driver::~Driver() {
     89   delete Opts;
     90 
     91   for (llvm::StringMap<ToolChain *>::iterator I = ToolChains.begin(),
     92                                               E = ToolChains.end();
     93        I != E; ++I)
     94     delete I->second;
     95 }
     96 
     97 InputArgList *Driver::ParseArgStrings(ArrayRef<const char *> ArgList) {
     98   llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
     99   unsigned MissingArgIndex, MissingArgCount;
    100   InputArgList *Args = getOpts().ParseArgs(ArgList.begin(), ArgList.end(),
    101                                            MissingArgIndex, MissingArgCount);
    102 
    103   // Check for missing argument error.
    104   if (MissingArgCount)
    105     Diag(clang::diag::err_drv_missing_argument)
    106       << Args->getArgString(MissingArgIndex) << MissingArgCount;
    107 
    108   // Check for unsupported options.
    109   for (ArgList::const_iterator it = Args->begin(), ie = Args->end();
    110        it != ie; ++it) {
    111     Arg *A = *it;
    112     if (A->getOption().isUnsupported()) {
    113       Diag(clang::diag::err_drv_unsupported_opt) << A->getAsString(*Args);
    114       continue;
    115     }
    116 
    117     // Warn about -mcpu= without an argument.
    118     if (A->getOption().matches(options::OPT_mcpu_EQ) &&
    119         A->containsValue("")) {
    120       Diag(clang::diag::warn_drv_empty_joined_argument) <<
    121         A->getAsString(*Args);
    122     }
    123   }
    124 
    125   return Args;
    126 }
    127 
    128 // Determine which compilation mode we are in. We look for options which
    129 // affect the phase, starting with the earliest phases, and record which
    130 // option we used to determine the final phase.
    131 phases::ID Driver::getFinalPhase(const DerivedArgList &DAL, Arg **FinalPhaseArg)
    132 const {
    133   Arg *PhaseArg = 0;
    134   phases::ID FinalPhase;
    135 
    136   // -{E,M,MM} only run the preprocessor.
    137   if (CCCIsCPP ||
    138       (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
    139       (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM))) {
    140     FinalPhase = phases::Preprocess;
    141 
    142     // -{fsyntax-only,-analyze,emit-ast,S} only run up to the compiler.
    143   } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
    144              (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
    145              (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
    146              (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
    147              (PhaseArg = DAL.getLastArg(options::OPT__analyze,
    148                                         options::OPT__analyze_auto)) ||
    149              (PhaseArg = DAL.getLastArg(options::OPT_emit_ast)) ||
    150              (PhaseArg = DAL.getLastArg(options::OPT_S))) {
    151     FinalPhase = phases::Compile;
    152 
    153     // -c only runs up to the assembler.
    154   } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
    155     FinalPhase = phases::Assemble;
    156 
    157     // Otherwise do everything.
    158   } else
    159     FinalPhase = phases::Link;
    160 
    161   if (FinalPhaseArg)
    162     *FinalPhaseArg = PhaseArg;
    163 
    164   return FinalPhase;
    165 }
    166 
    167 DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
    168   DerivedArgList *DAL = new DerivedArgList(Args);
    169 
    170   bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
    171   for (ArgList::const_iterator it = Args.begin(),
    172          ie = Args.end(); it != ie; ++it) {
    173     const Arg *A = *it;
    174 
    175     // Unfortunately, we have to parse some forwarding options (-Xassembler,
    176     // -Xlinker, -Xpreprocessor) because we either integrate their functionality
    177     // (assembler and preprocessor), or bypass a previous driver ('collect2').
    178 
    179     // Rewrite linker options, to replace --no-demangle with a custom internal
    180     // option.
    181     if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
    182          A->getOption().matches(options::OPT_Xlinker)) &&
    183         A->containsValue("--no-demangle")) {
    184       // Add the rewritten no-demangle argument.
    185       DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle));
    186 
    187       // Add the remaining values as Xlinker arguments.
    188       for (unsigned i = 0, e = A->getNumValues(); i != e; ++i)
    189         if (StringRef(A->getValue(Args, i)) != "--no-demangle")
    190           DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker),
    191                               A->getValue(Args, i));
    192 
    193       continue;
    194     }
    195 
    196     // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
    197     // some build systems. We don't try to be complete here because we don't
    198     // care to encourage this usage model.
    199     if (A->getOption().matches(options::OPT_Wp_COMMA) &&
    200         A->getNumValues() == 2 &&
    201         (A->getValue(Args, 0) == StringRef("-MD") ||
    202          A->getValue(Args, 0) == StringRef("-MMD"))) {
    203       // Rewrite to -MD/-MMD along with -MF.
    204       if (A->getValue(Args, 0) == StringRef("-MD"))
    205         DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD));
    206       else
    207         DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD));
    208       DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF),
    209                           A->getValue(Args, 1));
    210       continue;
    211     }
    212 
    213     // Rewrite reserved library names.
    214     if (A->getOption().matches(options::OPT_l)) {
    215       StringRef Value = A->getValue(Args);
    216 
    217       // Rewrite unless -nostdlib is present.
    218       if (!HasNostdlib && Value == "stdc++") {
    219         DAL->AddFlagArg(A, Opts->getOption(
    220                               options::OPT_Z_reserved_lib_stdcxx));
    221         continue;
    222       }
    223 
    224       // Rewrite unconditionally.
    225       if (Value == "cc_kext") {
    226         DAL->AddFlagArg(A, Opts->getOption(
    227                               options::OPT_Z_reserved_lib_cckext));
    228         continue;
    229       }
    230     }
    231 
    232     DAL->append(*it);
    233   }
    234 
    235   // Add a default value of -mlinker-version=, if one was given and the user
    236   // didn't specify one.
    237 #if defined(HOST_LINK_VERSION)
    238   if (!Args.hasArg(options::OPT_mlinker_version_EQ)) {
    239     DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ),
    240                       HOST_LINK_VERSION);
    241     DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
    242   }
    243 #endif
    244 
    245   return DAL;
    246 }
    247 
    248 Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
    249   llvm::PrettyStackTraceString CrashInfo("Compilation construction");
    250 
    251   // FIXME: Handle environment options which affect driver behavior, somewhere
    252   // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
    253 
    254   if (char *env = ::getenv("COMPILER_PATH")) {
    255     StringRef CompilerPath = env;
    256     while (!CompilerPath.empty()) {
    257       std::pair<StringRef, StringRef> Split = CompilerPath.split(':');
    258       PrefixDirs.push_back(Split.first);
    259       CompilerPath = Split.second;
    260     }
    261   }
    262 
    263   // FIXME: What are we going to do with -V and -b?
    264 
    265   // FIXME: This stuff needs to go into the Compilation, not the driver.
    266   bool CCCPrintOptions = false, CCCPrintActions = false;
    267 
    268   InputArgList *Args = ParseArgStrings(ArgList.slice(1));
    269 
    270   // -no-canonical-prefixes is used very early in main.
    271   Args->ClaimAllArgs(options::OPT_no_canonical_prefixes);
    272 
    273   // Ignore -pipe.
    274   Args->ClaimAllArgs(options::OPT_pipe);
    275 
    276   // Extract -ccc args.
    277   //
    278   // FIXME: We need to figure out where this behavior should live. Most of it
    279   // should be outside in the client; the parts that aren't should have proper
    280   // options, either by introducing new ones or by overloading gcc ones like -V
    281   // or -b.
    282   CCCPrintOptions = Args->hasArg(options::OPT_ccc_print_options);
    283   CCCPrintActions = Args->hasArg(options::OPT_ccc_print_phases);
    284   CCCPrintBindings = Args->hasArg(options::OPT_ccc_print_bindings);
    285   CCCIsCXX = Args->hasArg(options::OPT_ccc_cxx) || CCCIsCXX;
    286   CCCEcho = Args->hasArg(options::OPT_ccc_echo);
    287   if (const Arg *A = Args->getLastArg(options::OPT_ccc_gcc_name))
    288     CCCGenericGCCName = A->getValue(*Args);
    289   CCCUseClangCXX = Args->hasFlag(options::OPT_ccc_clang_cxx,
    290                                  options::OPT_ccc_no_clang_cxx,
    291                                  CCCUseClangCXX);
    292   CCCUsePCH = Args->hasFlag(options::OPT_ccc_pch_is_pch,
    293                             options::OPT_ccc_pch_is_pth);
    294   CCCUseClang = !Args->hasArg(options::OPT_ccc_no_clang);
    295   CCCUseClangCPP = !Args->hasArg(options::OPT_ccc_no_clang_cpp);
    296   if (const Arg *A = Args->getLastArg(options::OPT_ccc_clang_archs)) {
    297     StringRef Cur = A->getValue(*Args);
    298 
    299     CCCClangArchs.clear();
    300     while (!Cur.empty()) {
    301       std::pair<StringRef, StringRef> Split = Cur.split(',');
    302 
    303       if (!Split.first.empty()) {
    304         llvm::Triple::ArchType Arch =
    305           llvm::Triple(Split.first, "", "").getArch();
    306 
    307         if (Arch == llvm::Triple::UnknownArch)
    308           Diag(clang::diag::err_drv_invalid_arch_name) << Split.first;
    309 
    310         CCCClangArchs.insert(Arch);
    311       }
    312 
    313       Cur = Split.second;
    314     }
    315   }
    316   // FIXME: DefaultTargetTriple is used by the target-prefixed calls to as/ld
    317   // and getToolChain is const.
    318   if (const Arg *A = Args->getLastArg(options::OPT_target))
    319     DefaultTargetTriple = A->getValue(*Args);
    320   if (const Arg *A = Args->getLastArg(options::OPT_ccc_install_dir))
    321     Dir = InstalledDir = A->getValue(*Args);
    322   for (arg_iterator it = Args->filtered_begin(options::OPT_B),
    323          ie = Args->filtered_end(); it != ie; ++it) {
    324     const Arg *A = *it;
    325     A->claim();
    326     PrefixDirs.push_back(A->getValue(*Args, 0));
    327   }
    328   if (const Arg *A = Args->getLastArg(options::OPT__sysroot_EQ))
    329     SysRoot = A->getValue(*Args);
    330   if (Args->hasArg(options::OPT_nostdlib))
    331     UseStdLib = false;
    332 
    333   // Perform the default argument translations.
    334   DerivedArgList *TranslatedArgs = TranslateInputArgs(*Args);
    335 
    336   // Owned by the host.
    337   const ToolChain &TC = getToolChain(*Args);
    338 
    339   // The compilation takes ownership of Args.
    340   Compilation *C = new Compilation(*this, TC, Args, TranslatedArgs);
    341 
    342   // FIXME: This behavior shouldn't be here.
    343   if (CCCPrintOptions) {
    344     PrintOptions(C->getInputArgs());
    345     return C;
    346   }
    347 
    348   if (!HandleImmediateArgs(*C))
    349     return C;
    350 
    351   // Construct the list of inputs.
    352   InputList Inputs;
    353   BuildInputs(C->getDefaultToolChain(), C->getArgs(), Inputs);
    354 
    355   // Construct the list of abstract actions to perform for this compilation. On
    356   // Darwin target OSes this uses the driver-driver and universal actions.
    357   if (TC.getTriple().isOSDarwin())
    358     BuildUniversalActions(C->getDefaultToolChain(), C->getArgs(),
    359                           Inputs, C->getActions());
    360   else
    361     BuildActions(C->getDefaultToolChain(), C->getArgs(), Inputs,
    362                  C->getActions());
    363 
    364   if (CCCPrintActions) {
    365     PrintActions(*C);
    366     return C;
    367   }
    368 
    369   BuildJobs(*C);
    370 
    371   return C;
    372 }
    373 
    374 // When clang crashes, produce diagnostic information including the fully
    375 // preprocessed source file(s).  Request that the developer attach the
    376 // diagnostic information to a bug report.
    377 void Driver::generateCompilationDiagnostics(Compilation &C,
    378                                             const Command *FailingCommand) {
    379   if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
    380     return;
    381 
    382   // Don't try to generate diagnostics for link jobs.
    383   if (FailingCommand && FailingCommand->getCreator().isLinkJob())
    384     return;
    385 
    386   // Print the version of the compiler.
    387   PrintVersion(C, llvm::errs());
    388 
    389   Diag(clang::diag::note_drv_command_failed_diag_msg)
    390     << "PLEASE submit a bug report to " BUG_REPORT_URL " and include the "
    391     "crash backtrace, preprocessed source, and associated run script.";
    392 
    393   // Suppress driver output and emit preprocessor output to temp file.
    394   CCCIsCPP = true;
    395   CCGenDiagnostics = true;
    396   C.getArgs().AddFlagArg(0, Opts->getOption(options::OPT_frewrite_includes));
    397 
    398   // Save the original job command(s).
    399   std::string Cmd;
    400   llvm::raw_string_ostream OS(Cmd);
    401   if (FailingCommand)
    402     C.PrintJob(OS, *FailingCommand, "\n", false);
    403   else
    404     // Crash triggered by FORCE_CLANG_DIAGNOSTICS_CRASH, which doesn't have an
    405     // associated FailingCommand, so just pass all jobs.
    406     C.PrintJob(OS, C.getJobs(), "\n", false);
    407   OS.flush();
    408 
    409   // Clear stale state and suppress tool output.
    410   C.initCompilationForDiagnostics();
    411   Diags.Reset();
    412 
    413   // Construct the list of inputs.
    414   InputList Inputs;
    415   BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
    416 
    417   for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
    418     bool IgnoreInput = false;
    419 
    420     // Ignore input from stdin or any inputs that cannot be preprocessed.
    421     if (!strcmp(it->second->getValue(C.getArgs()), "-")) {
    422       Diag(clang::diag::note_drv_command_failed_diag_msg)
    423         << "Error generating preprocessed source(s) - ignoring input from stdin"
    424         ".";
    425       IgnoreInput = true;
    426     } else if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
    427       IgnoreInput = true;
    428     }
    429 
    430     if (IgnoreInput) {
    431       it = Inputs.erase(it);
    432       ie = Inputs.end();
    433     } else {
    434       ++it;
    435     }
    436   }
    437 
    438   // Don't attempt to generate preprocessed files if multiple -arch options are
    439   // used, unless they're all duplicates.
    440   llvm::StringSet<> ArchNames;
    441   for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end();
    442        it != ie; ++it) {
    443     Arg *A = *it;
    444     if (A->getOption().matches(options::OPT_arch)) {
    445       StringRef ArchName = A->getValue(C.getArgs());
    446       ArchNames.insert(ArchName);
    447     }
    448   }
    449   if (ArchNames.size() > 1) {
    450     Diag(clang::diag::note_drv_command_failed_diag_msg)
    451       << "Error generating preprocessed source(s) - cannot generate "
    452       "preprocessed source with multiple -arch options.";
    453     return;
    454   }
    455 
    456   if (Inputs.empty()) {
    457     Diag(clang::diag::note_drv_command_failed_diag_msg)
    458       << "Error generating preprocessed source(s) - no preprocessable inputs.";
    459     return;
    460   }
    461 
    462   // Construct the list of abstract actions to perform for this compilation. On
    463   // Darwin OSes this uses the driver-driver and builds universal actions.
    464   const ToolChain &TC = C.getDefaultToolChain();
    465   if (TC.getTriple().isOSDarwin())
    466     BuildUniversalActions(TC, C.getArgs(), Inputs, C.getActions());
    467   else
    468     BuildActions(TC, C.getArgs(), Inputs, C.getActions());
    469 
    470   BuildJobs(C);
    471 
    472   // If there were errors building the compilation, quit now.
    473   if (Diags.hasErrorOccurred()) {
    474     Diag(clang::diag::note_drv_command_failed_diag_msg)
    475       << "Error generating preprocessed source(s).";
    476     return;
    477   }
    478 
    479   // Generate preprocessed output.
    480   FailingCommand = 0;
    481   int Res = C.ExecuteJob(C.getJobs(), FailingCommand);
    482 
    483   // If the command succeeded, we are done.
    484   if (Res == 0) {
    485     Diag(clang::diag::note_drv_command_failed_diag_msg)
    486       << "\n********************\n\n"
    487       "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
    488       "Preprocessed source(s) and associated run script(s) are located at:";
    489     ArgStringList Files = C.getTempFiles();
    490     for (ArgStringList::const_iterator it = Files.begin(), ie = Files.end();
    491          it != ie; ++it) {
    492       Diag(clang::diag::note_drv_command_failed_diag_msg) << *it;
    493 
    494       std::string Err;
    495       std::string Script = StringRef(*it).rsplit('.').first;
    496       Script += ".sh";
    497       llvm::raw_fd_ostream ScriptOS(Script.c_str(), Err,
    498                                     llvm::raw_fd_ostream::F_Excl |
    499                                     llvm::raw_fd_ostream::F_Binary);
    500       if (!Err.empty()) {
    501         Diag(clang::diag::note_drv_command_failed_diag_msg)
    502           << "Error generating run script: " + Script + " " + Err;
    503       } else {
    504         // Strip away options not necessary to reproduce the crash.
    505         // FIXME: This doesn't work with quotes (e.g., -D "foo bar").
    506         SmallVector<std::string, 16> Flag;
    507         Flag.push_back("-D ");
    508         Flag.push_back("-F");
    509         Flag.push_back("-I ");
    510         Flag.push_back("-M ");
    511         Flag.push_back("-MD ");
    512         Flag.push_back("-MF ");
    513         Flag.push_back("-MG ");
    514         Flag.push_back("-MM ");
    515         Flag.push_back("-MMD ");
    516         Flag.push_back("-MP ");
    517         Flag.push_back("-MQ ");
    518         Flag.push_back("-MT ");
    519         Flag.push_back("-o ");
    520         Flag.push_back("-coverage-file ");
    521         Flag.push_back("-dependency-file ");
    522         Flag.push_back("-fdebug-compilation-dir ");
    523         Flag.push_back("-fmodule-cache-path ");
    524         Flag.push_back("-idirafter ");
    525         Flag.push_back("-include ");
    526         Flag.push_back("-include-pch ");
    527         Flag.push_back("-internal-isystem ");
    528         Flag.push_back("-internal-externc-isystem ");
    529         Flag.push_back("-iprefix ");
    530         Flag.push_back("-iwithprefix ");
    531         Flag.push_back("-iwithprefixbefore ");
    532         Flag.push_back("-isysroot ");
    533         Flag.push_back("-isystem ");
    534         Flag.push_back("-iquote ");
    535         Flag.push_back("-resource-dir ");
    536         Flag.push_back("-serialize-diagnostic-file ");
    537         for (unsigned i = 0, e = Flag.size(); i < e; ++i) {
    538           size_t I = 0, E = 0;
    539           do {
    540             I = Cmd.find(Flag[i], I);
    541             if (I == std::string::npos) break;
    542 
    543             E = Cmd.find(" ", I + Flag[i].length());
    544             if (E == std::string::npos) break;
    545             // The -D option is not removed.  Instead, the argument is quoted.
    546             if (Flag[i] != "-D ") {
    547               Cmd.erase(I, E - I + 1);
    548             } else {
    549               Cmd.insert(I+3, "\"");
    550               Cmd.insert(++E, "\"");
    551               I = E;
    552             }
    553           } while(1);
    554         }
    555         // Append the new filename with correct preprocessed suffix.
    556         size_t I, E;
    557         I = Cmd.find("-main-file-name ");
    558         assert (I != std::string::npos && "Expected to find -main-file-name");
    559         I += 16;
    560         E = Cmd.find(" ", I);
    561         assert (E != std::string::npos && "-main-file-name missing argument?");
    562         StringRef OldFilename = StringRef(Cmd).slice(I, E);
    563         StringRef NewFilename = llvm::sys::path::filename(*it);
    564         I = StringRef(Cmd).rfind(OldFilename);
    565         E = I + OldFilename.size();
    566         I = Cmd.rfind(" ", I) + 1;
    567         Cmd.replace(I, E - I, NewFilename.data(), NewFilename.size());
    568         ScriptOS << Cmd;
    569         Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
    570       }
    571     }
    572     Diag(clang::diag::note_drv_command_failed_diag_msg)
    573       << "\n\n********************";
    574   } else {
    575     // Failure, remove preprocessed files.
    576     if (!C.getArgs().hasArg(options::OPT_save_temps))
    577       C.CleanupFileList(C.getTempFiles(), true);
    578 
    579     Diag(clang::diag::note_drv_command_failed_diag_msg)
    580       << "Error generating preprocessed source(s).";
    581   }
    582 }
    583 
    584 int Driver::ExecuteCompilation(const Compilation &C,
    585                                const Command *&FailingCommand) const {
    586   // Just print if -### was present.
    587   if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
    588     C.PrintJob(llvm::errs(), C.getJobs(), "\n", true);
    589     return 0;
    590   }
    591 
    592   // If there were errors building the compilation, quit now.
    593   if (Diags.hasErrorOccurred())
    594     return 1;
    595 
    596   int Res = C.ExecuteJob(C.getJobs(), FailingCommand);
    597 
    598   // Remove temp files.
    599   C.CleanupFileList(C.getTempFiles());
    600 
    601   // If the command succeeded, we are done.
    602   if (Res == 0)
    603     return Res;
    604 
    605   // Otherwise, remove result files as well.
    606   if (!C.getArgs().hasArg(options::OPT_save_temps)) {
    607     C.CleanupFileList(C.getResultFiles(), true);
    608 
    609     // Failure result files are valid unless we crashed.
    610     if (Res < 0)
    611       C.CleanupFileList(C.getFailureResultFiles(), true);
    612   }
    613 
    614   // Print extra information about abnormal failures, if possible.
    615   //
    616   // This is ad-hoc, but we don't want to be excessively noisy. If the result
    617   // status was 1, assume the command failed normally. In particular, if it was
    618   // the compiler then assume it gave a reasonable error code. Failures in other
    619   // tools are less common, and they generally have worse diagnostics, so always
    620   // print the diagnostic there.
    621   const Tool &FailingTool = FailingCommand->getCreator();
    622 
    623   if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) {
    624     // FIXME: See FIXME above regarding result code interpretation.
    625     if (Res < 0)
    626       Diag(clang::diag::err_drv_command_signalled)
    627         << FailingTool.getShortName();
    628     else
    629       Diag(clang::diag::err_drv_command_failed)
    630         << FailingTool.getShortName() << Res;
    631   }
    632 
    633   return Res;
    634 }
    635 
    636 void Driver::PrintOptions(const ArgList &Args) const {
    637   unsigned i = 0;
    638   for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
    639        it != ie; ++it, ++i) {
    640     Arg *A = *it;
    641     llvm::errs() << "Option " << i << " - "
    642                  << "Name: \"" << A->getOption().getName() << "\", "
    643                  << "Values: {";
    644     for (unsigned j = 0; j < A->getNumValues(); ++j) {
    645       if (j)
    646         llvm::errs() << ", ";
    647       llvm::errs() << '"' << A->getValue(Args, j) << '"';
    648     }
    649     llvm::errs() << "}\n";
    650   }
    651 }
    652 
    653 void Driver::PrintHelp(bool ShowHidden) const {
    654   getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(),
    655                       ShowHidden);
    656 }
    657 
    658 void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
    659   // FIXME: The following handlers should use a callback mechanism, we don't
    660   // know what the client would like to do.
    661   OS << getClangFullVersion() << '\n';
    662   const ToolChain &TC = C.getDefaultToolChain();
    663   OS << "Target: " << TC.getTripleString() << '\n';
    664 
    665   // Print the threading model.
    666   //
    667   // FIXME: Implement correctly.
    668   OS << "Thread model: " << "posix" << '\n';
    669 }
    670 
    671 /// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
    672 /// option.
    673 static void PrintDiagnosticCategories(raw_ostream &OS) {
    674   // Skip the empty category.
    675   for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories();
    676        i != max; ++i)
    677     OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
    678 }
    679 
    680 bool Driver::HandleImmediateArgs(const Compilation &C) {
    681   // The order these options are handled in gcc is all over the place, but we
    682   // don't expect inconsistencies w.r.t. that to matter in practice.
    683 
    684   if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
    685     llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
    686     return false;
    687   }
    688 
    689   if (C.getArgs().hasArg(options::OPT_dumpversion)) {
    690     // Since -dumpversion is only implemented for pedantic GCC compatibility, we
    691     // return an answer which matches our definition of __VERSION__.
    692     //
    693     // If we want to return a more correct answer some day, then we should
    694     // introduce a non-pedantically GCC compatible mode to Clang in which we
    695     // provide sensible definitions for -dumpversion, __VERSION__, etc.
    696     llvm::outs() << "4.2.1\n";
    697     return false;
    698   }
    699 
    700   if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
    701     PrintDiagnosticCategories(llvm::outs());
    702     return false;
    703   }
    704 
    705   if (C.getArgs().hasArg(options::OPT_help) ||
    706       C.getArgs().hasArg(options::OPT__help_hidden)) {
    707     PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
    708     return false;
    709   }
    710 
    711   if (C.getArgs().hasArg(options::OPT__version)) {
    712     // Follow gcc behavior and use stdout for --version and stderr for -v.
    713     PrintVersion(C, llvm::outs());
    714     return false;
    715   }
    716 
    717   if (C.getArgs().hasArg(options::OPT_v) ||
    718       C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
    719     PrintVersion(C, llvm::errs());
    720     SuppressMissingInputWarning = true;
    721   }
    722 
    723   const ToolChain &TC = C.getDefaultToolChain();
    724   if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
    725     llvm::outs() << "programs: =";
    726     for (ToolChain::path_list::const_iterator it = TC.getProgramPaths().begin(),
    727            ie = TC.getProgramPaths().end(); it != ie; ++it) {
    728       if (it != TC.getProgramPaths().begin())
    729         llvm::outs() << ':';
    730       llvm::outs() << *it;
    731     }
    732     llvm::outs() << "\n";
    733     llvm::outs() << "libraries: =" << ResourceDir;
    734 
    735     StringRef sysroot = C.getSysRoot();
    736 
    737     for (ToolChain::path_list::const_iterator it = TC.getFilePaths().begin(),
    738            ie = TC.getFilePaths().end(); it != ie; ++it) {
    739       llvm::outs() << ':';
    740       const char *path = it->c_str();
    741       if (path[0] == '=')
    742         llvm::outs() << sysroot << path + 1;
    743       else
    744         llvm::outs() << path;
    745     }
    746     llvm::outs() << "\n";
    747     return false;
    748   }
    749 
    750   // FIXME: The following handlers should use a callback mechanism, we don't
    751   // know what the client would like to do.
    752   if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
    753     llvm::outs() << GetFilePath(A->getValue(C.getArgs()), TC) << "\n";
    754     return false;
    755   }
    756 
    757   if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
    758     llvm::outs() << GetProgramPath(A->getValue(C.getArgs()), TC) << "\n";
    759     return false;
    760   }
    761 
    762   if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
    763     llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
    764     return false;
    765   }
    766 
    767   if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
    768     // FIXME: We need tool chain support for this.
    769     llvm::outs() << ".;\n";
    770 
    771     switch (C.getDefaultToolChain().getTriple().getArch()) {
    772     default:
    773       break;
    774 
    775     case llvm::Triple::x86_64:
    776       llvm::outs() << "x86_64;@m64" << "\n";
    777       break;
    778 
    779     case llvm::Triple::ppc64:
    780       llvm::outs() << "ppc64;@m64" << "\n";
    781       break;
    782     }
    783     return false;
    784   }
    785 
    786   // FIXME: What is the difference between print-multi-directory and
    787   // print-multi-os-directory?
    788   if (C.getArgs().hasArg(options::OPT_print_multi_directory) ||
    789       C.getArgs().hasArg(options::OPT_print_multi_os_directory)) {
    790     switch (C.getDefaultToolChain().getTriple().getArch()) {
    791     default:
    792     case llvm::Triple::x86:
    793     case llvm::Triple::ppc:
    794       llvm::outs() << "." << "\n";
    795       break;
    796 
    797     case llvm::Triple::x86_64:
    798       llvm::outs() << "x86_64" << "\n";
    799       break;
    800 
    801     case llvm::Triple::ppc64:
    802       llvm::outs() << "ppc64" << "\n";
    803       break;
    804     }
    805     return false;
    806   }
    807 
    808   return true;
    809 }
    810 
    811 static unsigned PrintActions1(const Compilation &C, Action *A,
    812                               std::map<Action*, unsigned> &Ids) {
    813   if (Ids.count(A))
    814     return Ids[A];
    815 
    816   std::string str;
    817   llvm::raw_string_ostream os(str);
    818 
    819   os << Action::getClassName(A->getKind()) << ", ";
    820   if (InputAction *IA = dyn_cast<InputAction>(A)) {
    821     os << "\"" << IA->getInputArg().getValue(C.getArgs()) << "\"";
    822   } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
    823     os << '"' << BIA->getArchName() << '"'
    824        << ", {" << PrintActions1(C, *BIA->begin(), Ids) << "}";
    825   } else {
    826     os << "{";
    827     for (Action::iterator it = A->begin(), ie = A->end(); it != ie;) {
    828       os << PrintActions1(C, *it, Ids);
    829       ++it;
    830       if (it != ie)
    831         os << ", ";
    832     }
    833     os << "}";
    834   }
    835 
    836   unsigned Id = Ids.size();
    837   Ids[A] = Id;
    838   llvm::errs() << Id << ": " << os.str() << ", "
    839                << types::getTypeName(A->getType()) << "\n";
    840 
    841   return Id;
    842 }
    843 
    844 void Driver::PrintActions(const Compilation &C) const {
    845   std::map<Action*, unsigned> Ids;
    846   for (ActionList::const_iterator it = C.getActions().begin(),
    847          ie = C.getActions().end(); it != ie; ++it)
    848     PrintActions1(C, *it, Ids);
    849 }
    850 
    851 /// \brief Check whether the given input tree contains any compilation or
    852 /// assembly actions.
    853 static bool ContainsCompileOrAssembleAction(const Action *A) {
    854   if (isa<CompileJobAction>(A) || isa<AssembleJobAction>(A))
    855     return true;
    856 
    857   for (Action::const_iterator it = A->begin(), ie = A->end(); it != ie; ++it)
    858     if (ContainsCompileOrAssembleAction(*it))
    859       return true;
    860 
    861   return false;
    862 }
    863 
    864 void Driver::BuildUniversalActions(const ToolChain &TC,
    865                                    const DerivedArgList &Args,
    866                                    const InputList &BAInputs,
    867                                    ActionList &Actions) const {
    868   llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
    869   // Collect the list of architectures. Duplicates are allowed, but should only
    870   // be handled once (in the order seen).
    871   llvm::StringSet<> ArchNames;
    872   SmallVector<const char *, 4> Archs;
    873   for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
    874        it != ie; ++it) {
    875     Arg *A = *it;
    876 
    877     if (A->getOption().matches(options::OPT_arch)) {
    878       // Validate the option here; we don't save the type here because its
    879       // particular spelling may participate in other driver choices.
    880       llvm::Triple::ArchType Arch =
    881         llvm::Triple::getArchTypeForDarwinArchName(A->getValue(Args));
    882       if (Arch == llvm::Triple::UnknownArch) {
    883         Diag(clang::diag::err_drv_invalid_arch_name)
    884           << A->getAsString(Args);
    885         continue;
    886       }
    887 
    888       A->claim();
    889       if (ArchNames.insert(A->getValue(Args)))
    890         Archs.push_back(A->getValue(Args));
    891     }
    892   }
    893 
    894   // When there is no explicit arch for this platform, make sure we still bind
    895   // the architecture (to the default) so that -Xarch_ is handled correctly.
    896   if (!Archs.size())
    897     Archs.push_back(Args.MakeArgString(TC.getArchName()));
    898 
    899   // FIXME: We killed off some others but these aren't yet detected in a
    900   // functional manner. If we added information to jobs about which "auxiliary"
    901   // files they wrote then we could detect the conflict these cause downstream.
    902   if (Archs.size() > 1) {
    903     // No recovery needed, the point of this is just to prevent
    904     // overwriting the same files.
    905     if (const Arg *A = Args.getLastArg(options::OPT_save_temps))
    906       Diag(clang::diag::err_drv_invalid_opt_with_multiple_archs)
    907         << A->getAsString(Args);
    908   }
    909 
    910   ActionList SingleActions;
    911   BuildActions(TC, Args, BAInputs, SingleActions);
    912 
    913   // Add in arch bindings for every top level action, as well as lipo and
    914   // dsymutil steps if needed.
    915   for (unsigned i = 0, e = SingleActions.size(); i != e; ++i) {
    916     Action *Act = SingleActions[i];
    917 
    918     // Make sure we can lipo this kind of output. If not (and it is an actual
    919     // output) then we disallow, since we can't create an output file with the
    920     // right name without overwriting it. We could remove this oddity by just
    921     // changing the output names to include the arch, which would also fix
    922     // -save-temps. Compatibility wins for now.
    923 
    924     if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
    925       Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
    926         << types::getTypeName(Act->getType());
    927 
    928     ActionList Inputs;
    929     for (unsigned i = 0, e = Archs.size(); i != e; ++i) {
    930       Inputs.push_back(new BindArchAction(Act, Archs[i]));
    931       if (i != 0)
    932         Inputs.back()->setOwnsInputs(false);
    933     }
    934 
    935     // Lipo if necessary, we do it this way because we need to set the arch flag
    936     // so that -Xarch_ gets overwritten.
    937     if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
    938       Actions.append(Inputs.begin(), Inputs.end());
    939     else
    940       Actions.push_back(new LipoJobAction(Inputs, Act->getType()));
    941 
    942     // Handle debug info queries.
    943     Arg *A = Args.getLastArg(options::OPT_g_Group);
    944     if (A && !A->getOption().matches(options::OPT_g0) &&
    945         !A->getOption().matches(options::OPT_gstabs) &&
    946         ContainsCompileOrAssembleAction(Actions.back())) {
    947 
    948       // Add a 'dsymutil' step if necessary, when debug info is enabled and we
    949       // have a compile input. We need to run 'dsymutil' ourselves in such cases
    950       // because the debug info will refer to a temporary object file which is
    951       // will be removed at the end of the compilation process.
    952       if (Act->getType() == types::TY_Image) {
    953         ActionList Inputs;
    954         Inputs.push_back(Actions.back());
    955         Actions.pop_back();
    956         Actions.push_back(new DsymutilJobAction(Inputs, types::TY_dSYM));
    957       }
    958 
    959       // Verify the output (debug information only) if we passed '-verify'.
    960       if (Args.hasArg(options::OPT_verify)) {
    961         ActionList VerifyInputs;
    962         VerifyInputs.push_back(Actions.back());
    963         Actions.pop_back();
    964         Actions.push_back(new VerifyJobAction(VerifyInputs,
    965                                               types::TY_Nothing));
    966       }
    967     }
    968   }
    969 }
    970 
    971 // Construct a the list of inputs and their types.
    972 void Driver::BuildInputs(const ToolChain &TC, const DerivedArgList &Args,
    973                          InputList &Inputs) const {
    974   // Track the current user specified (-x) input. We also explicitly track the
    975   // argument used to set the type; we only want to claim the type when we
    976   // actually use it, so we warn about unused -x arguments.
    977   types::ID InputType = types::TY_Nothing;
    978   Arg *InputTypeArg = 0;
    979 
    980   for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
    981        it != ie; ++it) {
    982     Arg *A = *it;
    983 
    984     if (A->getOption().getKind() == Option::InputClass) {
    985       const char *Value = A->getValue(Args);
    986       types::ID Ty = types::TY_INVALID;
    987 
    988       // Infer the input type if necessary.
    989       if (InputType == types::TY_Nothing) {
    990         // If there was an explicit arg for this, claim it.
    991         if (InputTypeArg)
    992           InputTypeArg->claim();
    993 
    994         // stdin must be handled specially.
    995         if (memcmp(Value, "-", 2) == 0) {
    996           // If running with -E, treat as a C input (this changes the builtin
    997           // macros, for example). This may be overridden by -ObjC below.
    998           //
    999           // Otherwise emit an error but still use a valid type to avoid
   1000           // spurious errors (e.g., no inputs).
   1001           if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP)
   1002             Diag(clang::diag::err_drv_unknown_stdin_type);
   1003           Ty = types::TY_C;
   1004         } else {
   1005           // Otherwise lookup by extension.
   1006           // Fallback is C if invoked as C preprocessor or Object otherwise.
   1007           // We use a host hook here because Darwin at least has its own
   1008           // idea of what .s is.
   1009           if (const char *Ext = strrchr(Value, '.'))
   1010             Ty = TC.LookupTypeForExtension(Ext + 1);
   1011 
   1012           if (Ty == types::TY_INVALID) {
   1013             if (CCCIsCPP)
   1014               Ty = types::TY_C;
   1015             else
   1016               Ty = types::TY_Object;
   1017           }
   1018 
   1019           // If the driver is invoked as C++ compiler (like clang++ or c++) it
   1020           // should autodetect some input files as C++ for g++ compatibility.
   1021           if (CCCIsCXX) {
   1022             types::ID OldTy = Ty;
   1023             Ty = types::lookupCXXTypeForCType(Ty);
   1024 
   1025             if (Ty != OldTy)
   1026               Diag(clang::diag::warn_drv_treating_input_as_cxx)
   1027                 << getTypeName(OldTy) << getTypeName(Ty);
   1028           }
   1029         }
   1030 
   1031         // -ObjC and -ObjC++ override the default language, but only for "source
   1032         // files". We just treat everything that isn't a linker input as a
   1033         // source file.
   1034         //
   1035         // FIXME: Clean this up if we move the phase sequence into the type.
   1036         if (Ty != types::TY_Object) {
   1037           if (Args.hasArg(options::OPT_ObjC))
   1038             Ty = types::TY_ObjC;
   1039           else if (Args.hasArg(options::OPT_ObjCXX))
   1040             Ty = types::TY_ObjCXX;
   1041         }
   1042       } else {
   1043         assert(InputTypeArg && "InputType set w/o InputTypeArg");
   1044         InputTypeArg->claim();
   1045         Ty = InputType;
   1046       }
   1047 
   1048       // Check that the file exists, if enabled.
   1049       if (CheckInputsExist && memcmp(Value, "-", 2) != 0) {
   1050         SmallString<64> Path(Value);
   1051         if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory)) {
   1052           SmallString<64> Directory(WorkDir->getValue(Args));
   1053           if (llvm::sys::path::is_absolute(Directory.str())) {
   1054             llvm::sys::path::append(Directory, Value);
   1055             Path.assign(Directory);
   1056           }
   1057         }
   1058 
   1059         bool exists = false;
   1060         if (llvm::sys::fs::exists(Path.c_str(), exists) || !exists)
   1061           Diag(clang::diag::err_drv_no_such_file) << Path.str();
   1062         else
   1063           Inputs.push_back(std::make_pair(Ty, A));
   1064       } else
   1065         Inputs.push_back(std::make_pair(Ty, A));
   1066 
   1067     } else if (A->getOption().isLinkerInput()) {
   1068       // Just treat as object type, we could make a special type for this if
   1069       // necessary.
   1070       Inputs.push_back(std::make_pair(types::TY_Object, A));
   1071 
   1072     } else if (A->getOption().matches(options::OPT_x)) {
   1073       InputTypeArg = A;
   1074       InputType = types::lookupTypeForTypeSpecifier(A->getValue(Args));
   1075       A->claim();
   1076 
   1077       // Follow gcc behavior and treat as linker input for invalid -x
   1078       // options. Its not clear why we shouldn't just revert to unknown; but
   1079       // this isn't very important, we might as well be bug compatible.
   1080       if (!InputType) {
   1081         Diag(clang::diag::err_drv_unknown_language) << A->getValue(Args);
   1082         InputType = types::TY_Object;
   1083       }
   1084     }
   1085   }
   1086   if (CCCIsCPP && Inputs.empty()) {
   1087     // If called as standalone preprocessor, stdin is processed
   1088     // if no other input is present.
   1089     unsigned Index = Args.getBaseArgs().MakeIndex("-");
   1090     Arg *A = Opts->ParseOneArg(Args, Index);
   1091     A->claim();
   1092     Inputs.push_back(std::make_pair(types::TY_C, A));
   1093   }
   1094 }
   1095 
   1096 void Driver::BuildActions(const ToolChain &TC, const DerivedArgList &Args,
   1097                           const InputList &Inputs, ActionList &Actions) const {
   1098   llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
   1099 
   1100   if (!SuppressMissingInputWarning && Inputs.empty()) {
   1101     Diag(clang::diag::err_drv_no_input_files);
   1102     return;
   1103   }
   1104 
   1105   Arg *FinalPhaseArg;
   1106   phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
   1107 
   1108   // Reject -Z* at the top level, these options should never have been exposed
   1109   // by gcc.
   1110   if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
   1111     Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
   1112 
   1113   // Construct the actions to perform.
   1114   ActionList LinkerInputs;
   1115   unsigned NumSteps = 0;
   1116   for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
   1117     types::ID InputType = Inputs[i].first;
   1118     const Arg *InputArg = Inputs[i].second;
   1119 
   1120     NumSteps = types::getNumCompilationPhases(InputType);
   1121     assert(NumSteps && "Invalid number of steps!");
   1122 
   1123     // If the first step comes after the final phase we are doing as part of
   1124     // this compilation, warn the user about it.
   1125     phases::ID InitialPhase = types::getCompilationPhase(InputType, 0);
   1126     if (InitialPhase > FinalPhase) {
   1127       // Claim here to avoid the more general unused warning.
   1128       InputArg->claim();
   1129 
   1130       // Suppress all unused style warnings with -Qunused-arguments
   1131       if (Args.hasArg(options::OPT_Qunused_arguments))
   1132         continue;
   1133 
   1134       // Special case when final phase determined by binary name, rather than
   1135       // by a command-line argument with a corresponding Arg.
   1136       if (CCCIsCPP)
   1137         Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
   1138           << InputArg->getAsString(Args)
   1139           << getPhaseName(InitialPhase);
   1140       // Special case '-E' warning on a previously preprocessed file to make
   1141       // more sense.
   1142       else if (InitialPhase == phases::Compile &&
   1143                FinalPhase == phases::Preprocess &&
   1144                getPreprocessedType(InputType) == types::TY_INVALID)
   1145         Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
   1146           << InputArg->getAsString(Args)
   1147           << !!FinalPhaseArg
   1148           << FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "";
   1149       else
   1150         Diag(clang::diag::warn_drv_input_file_unused)
   1151           << InputArg->getAsString(Args)
   1152           << getPhaseName(InitialPhase)
   1153           << !!FinalPhaseArg
   1154           << FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "";
   1155       continue;
   1156     }
   1157 
   1158     // Build the pipeline for this file.
   1159     OwningPtr<Action> Current(new InputAction(*InputArg, InputType));
   1160     for (unsigned i = 0; i != NumSteps; ++i) {
   1161       phases::ID Phase = types::getCompilationPhase(InputType, i);
   1162 
   1163       // We are done if this step is past what the user requested.
   1164       if (Phase > FinalPhase)
   1165         break;
   1166 
   1167       // Queue linker inputs.
   1168       if (Phase == phases::Link) {
   1169         assert(i + 1 == NumSteps && "linking must be final compilation step.");
   1170         LinkerInputs.push_back(Current.take());
   1171         break;
   1172       }
   1173 
   1174       // Some types skip the assembler phase (e.g., llvm-bc), but we can't
   1175       // encode this in the steps because the intermediate type depends on
   1176       // arguments. Just special case here.
   1177       if (Phase == phases::Assemble && Current->getType() != types::TY_PP_Asm)
   1178         continue;
   1179 
   1180       // Otherwise construct the appropriate action.
   1181       Current.reset(ConstructPhaseAction(Args, Phase, Current.take()));
   1182       if (Current->getType() == types::TY_Nothing)
   1183         break;
   1184     }
   1185 
   1186     // If we ended with something, add to the output list.
   1187     if (Current)
   1188       Actions.push_back(Current.take());
   1189   }
   1190 
   1191   // Add a link action if necessary.
   1192   if (!LinkerInputs.empty())
   1193     Actions.push_back(new LinkJobAction(LinkerInputs, types::TY_Image));
   1194 
   1195   // If we are linking, claim any options which are obviously only used for
   1196   // compilation.
   1197   if (FinalPhase == phases::Link && (NumSteps == 1))
   1198     Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
   1199 }
   1200 
   1201 Action *Driver::ConstructPhaseAction(const ArgList &Args, phases::ID Phase,
   1202                                      Action *Input) const {
   1203   llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
   1204   // Build the appropriate action.
   1205   switch (Phase) {
   1206   case phases::Link: llvm_unreachable("link action invalid here.");
   1207   case phases::Preprocess: {
   1208     types::ID OutputTy;
   1209     // -{M, MM} alter the output type.
   1210     if (Args.hasArg(options::OPT_M, options::OPT_MM)) {
   1211       OutputTy = types::TY_Dependencies;
   1212     } else {
   1213       OutputTy = Input->getType();
   1214       if (!Args.hasFlag(options::OPT_frewrite_includes,
   1215                         options::OPT_fno_rewrite_includes, false))
   1216         OutputTy = types::getPreprocessedType(OutputTy);
   1217       assert(OutputTy != types::TY_INVALID &&
   1218              "Cannot preprocess this input type!");
   1219     }
   1220     return new PreprocessJobAction(Input, OutputTy);
   1221   }
   1222   case phases::Precompile: {
   1223     types::ID OutputTy = types::TY_PCH;
   1224     if (Args.hasArg(options::OPT_fsyntax_only)) {
   1225       // Syntax checks should not emit a PCH file
   1226       OutputTy = types::TY_Nothing;
   1227     }
   1228     return new PrecompileJobAction(Input, OutputTy);
   1229   }
   1230   case phases::Compile: {
   1231     if (Args.hasArg(options::OPT_fsyntax_only)) {
   1232       return new CompileJobAction(Input, types::TY_Nothing);
   1233     } else if (Args.hasArg(options::OPT_rewrite_objc)) {
   1234       return new CompileJobAction(Input, types::TY_RewrittenObjC);
   1235     } else if (Args.hasArg(options::OPT_rewrite_legacy_objc)) {
   1236       return new CompileJobAction(Input, types::TY_RewrittenLegacyObjC);
   1237     } else if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto)) {
   1238       return new AnalyzeJobAction(Input, types::TY_Plist);
   1239     } else if (Args.hasArg(options::OPT__migrate)) {
   1240       return new MigrateJobAction(Input, types::TY_Remap);
   1241     } else if (Args.hasArg(options::OPT_emit_ast)) {
   1242       return new CompileJobAction(Input, types::TY_AST);
   1243     } else if (IsUsingLTO(Args)) {
   1244       types::ID Output =
   1245         Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
   1246       return new CompileJobAction(Input, Output);
   1247     } else {
   1248       return new CompileJobAction(Input, types::TY_PP_Asm);
   1249     }
   1250   }
   1251   case phases::Assemble:
   1252     return new AssembleJobAction(Input, types::TY_Object);
   1253   }
   1254 
   1255   llvm_unreachable("invalid phase in ConstructPhaseAction");
   1256 }
   1257 
   1258 bool Driver::IsUsingLTO(const ArgList &Args) const {
   1259   // Check for -emit-llvm or -flto.
   1260   if (Args.hasArg(options::OPT_emit_llvm) ||
   1261       Args.hasFlag(options::OPT_flto, options::OPT_fno_lto, false))
   1262     return true;
   1263 
   1264   // Check for -O4.
   1265   if (const Arg *A = Args.getLastArg(options::OPT_O_Group))
   1266       return A->getOption().matches(options::OPT_O4);
   1267 
   1268   return false;
   1269 }
   1270 
   1271 void Driver::BuildJobs(Compilation &C) const {
   1272   llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
   1273 
   1274   Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
   1275 
   1276   // It is an error to provide a -o option if we are making multiple output
   1277   // files.
   1278   if (FinalOutput) {
   1279     unsigned NumOutputs = 0;
   1280     for (ActionList::const_iterator it = C.getActions().begin(),
   1281            ie = C.getActions().end(); it != ie; ++it)
   1282       if ((*it)->getType() != types::TY_Nothing)
   1283         ++NumOutputs;
   1284 
   1285     if (NumOutputs > 1) {
   1286       Diag(clang::diag::err_drv_output_argument_with_multiple_files);
   1287       FinalOutput = 0;
   1288     }
   1289   }
   1290 
   1291   for (ActionList::const_iterator it = C.getActions().begin(),
   1292          ie = C.getActions().end(); it != ie; ++it) {
   1293     Action *A = *it;
   1294 
   1295     // If we are linking an image for multiple archs then the linker wants
   1296     // -arch_multiple and -final_output <final image name>. Unfortunately, this
   1297     // doesn't fit in cleanly because we have to pass this information down.
   1298     //
   1299     // FIXME: This is a hack; find a cleaner way to integrate this into the
   1300     // process.
   1301     const char *LinkingOutput = 0;
   1302     if (isa<LipoJobAction>(A)) {
   1303       if (FinalOutput)
   1304         LinkingOutput = FinalOutput->getValue(C.getArgs());
   1305       else
   1306         LinkingOutput = DefaultImageName.c_str();
   1307     }
   1308 
   1309     InputInfo II;
   1310     BuildJobsForAction(C, A, &C.getDefaultToolChain(),
   1311                        /*BoundArch*/0,
   1312                        /*AtTopLevel*/ true,
   1313                        /*LinkingOutput*/ LinkingOutput,
   1314                        II);
   1315   }
   1316 
   1317   // If the user passed -Qunused-arguments or there were errors, don't warn
   1318   // about any unused arguments.
   1319   if (Diags.hasErrorOccurred() ||
   1320       C.getArgs().hasArg(options::OPT_Qunused_arguments))
   1321     return;
   1322 
   1323   // Claim -### here.
   1324   (void) C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
   1325 
   1326   for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end();
   1327        it != ie; ++it) {
   1328     Arg *A = *it;
   1329 
   1330     // FIXME: It would be nice to be able to send the argument to the
   1331     // DiagnosticsEngine, so that extra values, position, and so on could be
   1332     // printed.
   1333     if (!A->isClaimed()) {
   1334       if (A->getOption().hasNoArgumentUnused())
   1335         continue;
   1336 
   1337       // Suppress the warning automatically if this is just a flag, and it is an
   1338       // instance of an argument we already claimed.
   1339       const Option &Opt = A->getOption();
   1340       if (Opt.getKind() == Option::FlagClass) {
   1341         bool DuplicateClaimed = false;
   1342 
   1343         for (arg_iterator it = C.getArgs().filtered_begin(&Opt),
   1344                ie = C.getArgs().filtered_end(); it != ie; ++it) {
   1345           if ((*it)->isClaimed()) {
   1346             DuplicateClaimed = true;
   1347             break;
   1348           }
   1349         }
   1350 
   1351         if (DuplicateClaimed)
   1352           continue;
   1353       }
   1354 
   1355       Diag(clang::diag::warn_drv_unused_argument)
   1356         << A->getAsString(C.getArgs());
   1357     }
   1358   }
   1359 }
   1360 
   1361 static const Tool &SelectToolForJob(Compilation &C, const ToolChain *TC,
   1362                                     const JobAction *JA,
   1363                                     const ActionList *&Inputs) {
   1364   const Tool *ToolForJob = 0;
   1365 
   1366   // See if we should look for a compiler with an integrated assembler. We match
   1367   // bottom up, so what we are actually looking for is an assembler job with a
   1368   // compiler input.
   1369 
   1370   if (C.getArgs().hasFlag(options::OPT_integrated_as,
   1371                           options::OPT_no_integrated_as,
   1372                           TC->IsIntegratedAssemblerDefault()) &&
   1373       !C.getArgs().hasArg(options::OPT_save_temps) &&
   1374       isa<AssembleJobAction>(JA) &&
   1375       Inputs->size() == 1 && isa<CompileJobAction>(*Inputs->begin())) {
   1376     const Tool &Compiler = TC->SelectTool(
   1377       C, cast<JobAction>(**Inputs->begin()), (*Inputs)[0]->getInputs());
   1378     if (Compiler.hasIntegratedAssembler()) {
   1379       Inputs = &(*Inputs)[0]->getInputs();
   1380       ToolForJob = &Compiler;
   1381     }
   1382   }
   1383 
   1384   // Otherwise use the tool for the current job.
   1385   if (!ToolForJob)
   1386     ToolForJob = &TC->SelectTool(C, *JA, *Inputs);
   1387 
   1388   // See if we should use an integrated preprocessor. We do so when we have
   1389   // exactly one input, since this is the only use case we care about
   1390   // (irrelevant since we don't support combine yet).
   1391   if (Inputs->size() == 1 && isa<PreprocessJobAction>(*Inputs->begin()) &&
   1392       !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
   1393       !C.getArgs().hasArg(options::OPT_traditional_cpp) &&
   1394       !C.getArgs().hasArg(options::OPT_save_temps) &&
   1395       ToolForJob->hasIntegratedCPP())
   1396     Inputs = &(*Inputs)[0]->getInputs();
   1397 
   1398   return *ToolForJob;
   1399 }
   1400 
   1401 void Driver::BuildJobsForAction(Compilation &C,
   1402                                 const Action *A,
   1403                                 const ToolChain *TC,
   1404                                 const char *BoundArch,
   1405                                 bool AtTopLevel,
   1406                                 const char *LinkingOutput,
   1407                                 InputInfo &Result) const {
   1408   llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
   1409 
   1410   if (const InputAction *IA = dyn_cast<InputAction>(A)) {
   1411     // FIXME: It would be nice to not claim this here; maybe the old scheme of
   1412     // just using Args was better?
   1413     const Arg &Input = IA->getInputArg();
   1414     Input.claim();
   1415     if (Input.getOption().matches(options::OPT_INPUT)) {
   1416       const char *Name = Input.getValue(C.getArgs());
   1417       Result = InputInfo(Name, A->getType(), Name);
   1418     } else
   1419       Result = InputInfo(&Input, A->getType(), "");
   1420     return;
   1421   }
   1422 
   1423   if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
   1424     const ToolChain *TC;
   1425     const char *ArchName = BAA->getArchName();
   1426 
   1427     if (ArchName)
   1428       TC = &getToolChain(C.getArgs(), ArchName);
   1429     else
   1430       TC = &C.getDefaultToolChain();
   1431 
   1432     BuildJobsForAction(C, *BAA->begin(), TC, BAA->getArchName(),
   1433                        AtTopLevel, LinkingOutput, Result);
   1434     return;
   1435   }
   1436 
   1437   const ActionList *Inputs = &A->getInputs();
   1438 
   1439   const JobAction *JA = cast<JobAction>(A);
   1440   const Tool &T = SelectToolForJob(C, TC, JA, Inputs);
   1441 
   1442   // Only use pipes when there is exactly one input.
   1443   InputInfoList InputInfos;
   1444   for (ActionList::const_iterator it = Inputs->begin(), ie = Inputs->end();
   1445        it != ie; ++it) {
   1446     // Treat dsymutil sub-jobs as being at the top-level too, they shouldn't get
   1447     // temporary output names.
   1448     //
   1449     // FIXME: Clean this up.
   1450     bool SubJobAtTopLevel = false;
   1451     if (AtTopLevel && isa<DsymutilJobAction>(A))
   1452       SubJobAtTopLevel = true;
   1453 
   1454     // Also treat verify sub-jobs as being at the top-level. They don't
   1455     // produce any output and so don't need temporary output names.
   1456     if (AtTopLevel && isa<VerifyJobAction>(A))
   1457       SubJobAtTopLevel = true;
   1458 
   1459     InputInfo II;
   1460     BuildJobsForAction(C, *it, TC, BoundArch,
   1461                        SubJobAtTopLevel, LinkingOutput, II);
   1462     InputInfos.push_back(II);
   1463   }
   1464 
   1465   // Always use the first input as the base input.
   1466   const char *BaseInput = InputInfos[0].getBaseInput();
   1467 
   1468   // ... except dsymutil actions, which use their actual input as the base
   1469   // input.
   1470   if (JA->getType() == types::TY_dSYM)
   1471     BaseInput = InputInfos[0].getFilename();
   1472 
   1473   // Determine the place to write output to, if any.
   1474   if (JA->getType() == types::TY_Nothing) {
   1475     Result = InputInfo(A->getType(), BaseInput);
   1476   } else {
   1477     Result = InputInfo(GetNamedOutputPath(C, *JA, BaseInput, AtTopLevel),
   1478                        A->getType(), BaseInput);
   1479   }
   1480 
   1481   if (CCCPrintBindings && !CCGenDiagnostics) {
   1482     llvm::errs() << "# \"" << T.getToolChain().getTripleString() << '"'
   1483                  << " - \"" << T.getName() << "\", inputs: [";
   1484     for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
   1485       llvm::errs() << InputInfos[i].getAsString();
   1486       if (i + 1 != e)
   1487         llvm::errs() << ", ";
   1488     }
   1489     llvm::errs() << "], output: " << Result.getAsString() << "\n";
   1490   } else {
   1491     T.ConstructJob(C, *JA, Result, InputInfos,
   1492                    C.getArgsForToolChain(TC, BoundArch), LinkingOutput);
   1493   }
   1494 }
   1495 
   1496 const char *Driver::GetNamedOutputPath(Compilation &C,
   1497                                        const JobAction &JA,
   1498                                        const char *BaseInput,
   1499                                        bool AtTopLevel) const {
   1500   llvm::PrettyStackTraceString CrashInfo("Computing output path");
   1501   // Output to a user requested destination?
   1502   if (AtTopLevel && !isa<DsymutilJobAction>(JA) &&
   1503       !isa<VerifyJobAction>(JA)) {
   1504     if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
   1505       return C.addResultFile(FinalOutput->getValue(C.getArgs()));
   1506   }
   1507 
   1508   // Default to writing to stdout?
   1509   if (AtTopLevel && isa<PreprocessJobAction>(JA) && !CCGenDiagnostics)
   1510     return "-";
   1511 
   1512   // Output to a temporary file?
   1513   if ((!AtTopLevel && !C.getArgs().hasArg(options::OPT_save_temps)) ||
   1514       CCGenDiagnostics) {
   1515     StringRef Name = llvm::sys::path::filename(BaseInput);
   1516     std::pair<StringRef, StringRef> Split = Name.split('.');
   1517     std::string TmpName =
   1518       GetTemporaryPath(Split.first, types::getTypeTempSuffix(JA.getType()));
   1519     return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()));
   1520   }
   1521 
   1522   SmallString<128> BasePath(BaseInput);
   1523   StringRef BaseName;
   1524 
   1525   // Dsymutil actions should use the full path.
   1526   if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
   1527     BaseName = BasePath;
   1528   else
   1529     BaseName = llvm::sys::path::filename(BasePath);
   1530 
   1531   // Determine what the derived output name should be.
   1532   const char *NamedOutput;
   1533   if (JA.getType() == types::TY_Image) {
   1534     NamedOutput = DefaultImageName.c_str();
   1535   } else {
   1536     const char *Suffix = types::getTypeTempSuffix(JA.getType());
   1537     assert(Suffix && "All types used for output should have a suffix.");
   1538 
   1539     std::string::size_type End = std::string::npos;
   1540     if (!types::appendSuffixForType(JA.getType()))
   1541       End = BaseName.rfind('.');
   1542     std::string Suffixed(BaseName.substr(0, End));
   1543     Suffixed += '.';
   1544     Suffixed += Suffix;
   1545     NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
   1546   }
   1547 
   1548   // If we're saving temps and the temp file conflicts with the input file,
   1549   // then avoid overwriting input file.
   1550   if (!AtTopLevel && C.getArgs().hasArg(options::OPT_save_temps) &&
   1551       NamedOutput == BaseName) {
   1552 
   1553     bool SameFile = false;
   1554     SmallString<256> Result;
   1555     llvm::sys::fs::current_path(Result);
   1556     llvm::sys::path::append(Result, BaseName);
   1557     llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
   1558     // Must share the same path to conflict.
   1559     if (SameFile) {
   1560       StringRef Name = llvm::sys::path::filename(BaseInput);
   1561       std::pair<StringRef, StringRef> Split = Name.split('.');
   1562       std::string TmpName =
   1563         GetTemporaryPath(Split.first, types::getTypeTempSuffix(JA.getType()));
   1564       return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()));
   1565     }
   1566   }
   1567 
   1568   // As an annoying special case, PCH generation doesn't strip the pathname.
   1569   if (JA.getType() == types::TY_PCH) {
   1570     llvm::sys::path::remove_filename(BasePath);
   1571     if (BasePath.empty())
   1572       BasePath = NamedOutput;
   1573     else
   1574       llvm::sys::path::append(BasePath, NamedOutput);
   1575     return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()));
   1576   } else {
   1577     return C.addResultFile(NamedOutput);
   1578   }
   1579 }
   1580 
   1581 std::string Driver::GetFilePath(const char *Name, const ToolChain &TC) const {
   1582   // Respect a limited subset of the '-Bprefix' functionality in GCC by
   1583   // attempting to use this prefix when lokup up program paths.
   1584   for (Driver::prefix_list::const_iterator it = PrefixDirs.begin(),
   1585        ie = PrefixDirs.end(); it != ie; ++it) {
   1586     std::string Dir(*it);
   1587     if (Dir.empty())
   1588       continue;
   1589     if (Dir[0] == '=')
   1590       Dir = SysRoot + Dir.substr(1);
   1591     llvm::sys::Path P(Dir);
   1592     P.appendComponent(Name);
   1593     bool Exists;
   1594     if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
   1595       return P.str();
   1596   }
   1597 
   1598   llvm::sys::Path P(ResourceDir);
   1599   P.appendComponent(Name);
   1600   bool Exists;
   1601   if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
   1602     return P.str();
   1603 
   1604   const ToolChain::path_list &List = TC.getFilePaths();
   1605   for (ToolChain::path_list::const_iterator
   1606          it = List.begin(), ie = List.end(); it != ie; ++it) {
   1607     std::string Dir(*it);
   1608     if (Dir.empty())
   1609       continue;
   1610     if (Dir[0] == '=')
   1611       Dir = SysRoot + Dir.substr(1);
   1612     llvm::sys::Path P(Dir);
   1613     P.appendComponent(Name);
   1614     bool Exists;
   1615     if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
   1616       return P.str();
   1617   }
   1618 
   1619   return Name;
   1620 }
   1621 
   1622 static bool isPathExecutable(llvm::sys::Path &P, bool WantFile) {
   1623     bool Exists;
   1624     return (WantFile ? !llvm::sys::fs::exists(P.str(), Exists) && Exists
   1625                  : P.canExecute());
   1626 }
   1627 
   1628 std::string Driver::GetProgramPath(const char *Name, const ToolChain &TC,
   1629                                    bool WantFile) const {
   1630   // FIXME: Needs a better variable than DefaultTargetTriple
   1631   std::string TargetSpecificExecutable(DefaultTargetTriple + "-" + Name);
   1632   // Respect a limited subset of the '-Bprefix' functionality in GCC by
   1633   // attempting to use this prefix when lokup up program paths.
   1634   for (Driver::prefix_list::const_iterator it = PrefixDirs.begin(),
   1635        ie = PrefixDirs.end(); it != ie; ++it) {
   1636     llvm::sys::Path P(*it);
   1637     P.appendComponent(TargetSpecificExecutable);
   1638     if (isPathExecutable(P, WantFile)) return P.str();
   1639     P.eraseComponent();
   1640     P.appendComponent(Name);
   1641     if (isPathExecutable(P, WantFile)) return P.str();
   1642   }
   1643 
   1644   const ToolChain::path_list &List = TC.getProgramPaths();
   1645   for (ToolChain::path_list::const_iterator
   1646          it = List.begin(), ie = List.end(); it != ie; ++it) {
   1647     llvm::sys::Path P(*it);
   1648     P.appendComponent(TargetSpecificExecutable);
   1649     if (isPathExecutable(P, WantFile)) return P.str();
   1650     P.eraseComponent();
   1651     P.appendComponent(Name);
   1652     if (isPathExecutable(P, WantFile)) return P.str();
   1653   }
   1654 
   1655   // If all else failed, search the path.
   1656   llvm::sys::Path
   1657       P(llvm::sys::Program::FindProgramByName(TargetSpecificExecutable));
   1658   if (!P.empty())
   1659     return P.str();
   1660 
   1661   P = llvm::sys::Path(llvm::sys::Program::FindProgramByName(Name));
   1662   if (!P.empty())
   1663     return P.str();
   1664 
   1665   return Name;
   1666 }
   1667 
   1668 std::string Driver::GetTemporaryPath(StringRef Prefix, const char *Suffix)
   1669   const {
   1670   // FIXME: This is lame; sys::Path should provide this function (in particular,
   1671   // it should know how to find the temporary files dir).
   1672   std::string Error;
   1673   const char *TmpDir = ::getenv("TMPDIR");
   1674   if (!TmpDir)
   1675     TmpDir = ::getenv("TEMP");
   1676   if (!TmpDir)
   1677     TmpDir = ::getenv("TMP");
   1678   if (!TmpDir)
   1679     TmpDir = "/tmp";
   1680   llvm::sys::Path P(TmpDir);
   1681   P.appendComponent(Prefix);
   1682   if (P.makeUnique(false, &Error)) {
   1683     Diag(clang::diag::err_unable_to_make_temp) << Error;
   1684     return "";
   1685   }
   1686 
   1687   // FIXME: Grumble, makeUnique sometimes leaves the file around!?  PR3837.
   1688   P.eraseFromDisk(false, 0);
   1689 
   1690   if (Suffix)
   1691     P.appendSuffix(Suffix);
   1692   return P.str();
   1693 }
   1694 
   1695 /// \brief Compute target triple from args.
   1696 ///
   1697 /// This routine provides the logic to compute a target triple from various
   1698 /// args passed to the driver and the default triple string.
   1699 static llvm::Triple computeTargetTriple(StringRef DefaultTargetTriple,
   1700                                         const ArgList &Args,
   1701                                         StringRef DarwinArchName) {
   1702   // FIXME: Already done in Compilation *Driver::BuildCompilation
   1703   if (const Arg *A = Args.getLastArg(options::OPT_target))
   1704     DefaultTargetTriple = A->getValue(Args);
   1705 
   1706   llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
   1707 
   1708   // Handle Darwin-specific options available here.
   1709   if (Target.isOSDarwin()) {
   1710     // If an explict Darwin arch name is given, that trumps all.
   1711     if (!DarwinArchName.empty()) {
   1712       Target.setArch(
   1713         llvm::Triple::getArchTypeForDarwinArchName(DarwinArchName));
   1714       return Target;
   1715     }
   1716 
   1717     // Handle the Darwin '-arch' flag.
   1718     if (Arg *A = Args.getLastArg(options::OPT_arch)) {
   1719       llvm::Triple::ArchType DarwinArch
   1720         = llvm::Triple::getArchTypeForDarwinArchName(A->getValue(Args));
   1721       if (DarwinArch != llvm::Triple::UnknownArch)
   1722         Target.setArch(DarwinArch);
   1723     }
   1724   }
   1725 
   1726   // Skip further flag support on OSes which don't support '-m32' or '-m64'.
   1727   if (Target.getArchName() == "tce" ||
   1728       Target.getOS() == llvm::Triple::AuroraUX ||
   1729       Target.getOS() == llvm::Triple::Minix)
   1730     return Target;
   1731 
   1732   // Handle pseudo-target flags '-m32' and '-m64'.
   1733   // FIXME: Should this information be in llvm::Triple?
   1734   if (Arg *A = Args.getLastArg(options::OPT_m32, options::OPT_m64)) {
   1735     if (A->getOption().matches(options::OPT_m32)) {
   1736       if (Target.getArch() == llvm::Triple::x86_64)
   1737         Target.setArch(llvm::Triple::x86);
   1738       if (Target.getArch() == llvm::Triple::ppc64)
   1739         Target.setArch(llvm::Triple::ppc);
   1740     } else {
   1741       if (Target.getArch() == llvm::Triple::x86)
   1742         Target.setArch(llvm::Triple::x86_64);
   1743       if (Target.getArch() == llvm::Triple::ppc)
   1744         Target.setArch(llvm::Triple::ppc64);
   1745     }
   1746   }
   1747 
   1748   return Target;
   1749 }
   1750 
   1751 const ToolChain &Driver::getToolChain(const ArgList &Args,
   1752                                       StringRef DarwinArchName) const {
   1753   llvm::Triple Target = computeTargetTriple(DefaultTargetTriple, Args,
   1754                                             DarwinArchName);
   1755 
   1756   ToolChain *&TC = ToolChains[Target.str()];
   1757   if (!TC) {
   1758     switch (Target.getOS()) {
   1759     case llvm::Triple::AuroraUX:
   1760       TC = new toolchains::AuroraUX(*this, Target, Args);
   1761       break;
   1762     case llvm::Triple::Darwin:
   1763     case llvm::Triple::MacOSX:
   1764     case llvm::Triple::IOS:
   1765       if (Target.getArch() == llvm::Triple::x86 ||
   1766           Target.getArch() == llvm::Triple::x86_64 ||
   1767           Target.getArch() == llvm::Triple::arm ||
   1768           Target.getArch() == llvm::Triple::thumb)
   1769         TC = new toolchains::DarwinClang(*this, Target);
   1770       else
   1771         TC = new toolchains::Darwin_Generic_GCC(*this, Target, Args);
   1772       break;
   1773     case llvm::Triple::DragonFly:
   1774       TC = new toolchains::DragonFly(*this, Target, Args);
   1775       break;
   1776     case llvm::Triple::OpenBSD:
   1777       TC = new toolchains::OpenBSD(*this, Target, Args);
   1778       break;
   1779     case llvm::Triple::Bitrig:
   1780       TC = new toolchains::Bitrig(*this, Target, Args);
   1781       break;
   1782     case llvm::Triple::NetBSD:
   1783       TC = new toolchains::NetBSD(*this, Target, Args);
   1784       break;
   1785     case llvm::Triple::FreeBSD:
   1786       TC = new toolchains::FreeBSD(*this, Target, Args);
   1787       break;
   1788     case llvm::Triple::Minix:
   1789       TC = new toolchains::Minix(*this, Target, Args);
   1790       break;
   1791     case llvm::Triple::Linux:
   1792       if (Target.getArch() == llvm::Triple::hexagon)
   1793         TC = new toolchains::Hexagon_TC(*this, Target);
   1794       else
   1795         TC = new toolchains::Linux(*this, Target, Args);
   1796       break;
   1797     case llvm::Triple::Solaris:
   1798       TC = new toolchains::Solaris(*this, Target, Args);
   1799       break;
   1800     case llvm::Triple::Win32:
   1801       TC = new toolchains::Windows(*this, Target);
   1802       break;
   1803     case llvm::Triple::MinGW32:
   1804       // FIXME: We need a MinGW toolchain. Fallthrough for now.
   1805     default:
   1806       // TCE is an OSless target
   1807       if (Target.getArchName() == "tce") {
   1808         TC = new toolchains::TCEToolChain(*this, Target);
   1809         break;
   1810       }
   1811 
   1812       TC = new toolchains::Generic_GCC(*this, Target, Args);
   1813       break;
   1814     }
   1815   }
   1816   return *TC;
   1817 }
   1818 
   1819 bool Driver::ShouldUseClangCompiler(const Compilation &C, const JobAction &JA,
   1820                                     const llvm::Triple &Triple) const {
   1821   // Check if user requested no clang, or clang doesn't understand this type (we
   1822   // only handle single inputs for now).
   1823   if (!CCCUseClang || JA.size() != 1 ||
   1824       !types::isAcceptedByClang((*JA.begin())->getType()))
   1825     return false;
   1826 
   1827   // Otherwise make sure this is an action clang understands.
   1828   if (isa<PreprocessJobAction>(JA)) {
   1829     if (!CCCUseClangCPP) {
   1830       Diag(clang::diag::warn_drv_not_using_clang_cpp);
   1831       return false;
   1832     }
   1833   } else if (!isa<PrecompileJobAction>(JA) && !isa<CompileJobAction>(JA))
   1834     return false;
   1835 
   1836   // Use clang for C++?
   1837   if (!CCCUseClangCXX && types::isCXX((*JA.begin())->getType())) {
   1838     Diag(clang::diag::warn_drv_not_using_clang_cxx);
   1839     return false;
   1840   }
   1841 
   1842   // Always use clang for precompiling, AST generation, and rewriting,
   1843   // regardless of archs.
   1844   if (isa<PrecompileJobAction>(JA) ||
   1845       types::isOnlyAcceptedByClang(JA.getType()))
   1846     return true;
   1847 
   1848   // Finally, don't use clang if this isn't one of the user specified archs to
   1849   // build.
   1850   if (!CCCClangArchs.empty() && !CCCClangArchs.count(Triple.getArch())) {
   1851     Diag(clang::diag::warn_drv_not_using_clang_arch) << Triple.getArchName();
   1852     return false;
   1853   }
   1854 
   1855   return true;
   1856 }
   1857 
   1858 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
   1859 /// grouped values as integers. Numbers which are not provided are set to 0.
   1860 ///
   1861 /// \return True if the entire string was parsed (9.2), or all groups were
   1862 /// parsed (10.3.5extrastuff).
   1863 bool Driver::GetReleaseVersion(const char *Str, unsigned &Major,
   1864                                unsigned &Minor, unsigned &Micro,
   1865                                bool &HadExtra) {
   1866   HadExtra = false;
   1867 
   1868   Major = Minor = Micro = 0;
   1869   if (*Str == '\0')
   1870     return true;
   1871 
   1872   char *End;
   1873   Major = (unsigned) strtol(Str, &End, 10);
   1874   if (*Str != '\0' && *End == '\0')
   1875     return true;
   1876   if (*End != '.')
   1877     return false;
   1878 
   1879   Str = End+1;
   1880   Minor = (unsigned) strtol(Str, &End, 10);
   1881   if (*Str != '\0' && *End == '\0')
   1882     return true;
   1883   if (*End != '.')
   1884     return false;
   1885 
   1886   Str = End+1;
   1887   Micro = (unsigned) strtol(Str, &End, 10);
   1888   if (*Str != '\0' && *End == '\0')
   1889     return true;
   1890   if (Str == End)
   1891     return false;
   1892   HadExtra = true;
   1893   return true;
   1894 }
   1895