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