1 //===--- Driver.cpp - Clang GCC Compatible Driver -------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #ifdef HAVE_CLANG_CONFIG_H
11 # include "clang/Config/config.h"
14 #include "clang/Driver/Driver.h"
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"
29 #include "clang/Basic/Version.h"
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"
42 #include "InputInfo.h"
46 using namespace clang::driver;
47 using namespace clang;
49 Driver::Driver(StringRef ClangExecutable,
50 StringRef DefaultHostTriple,
51 StringRef DefaultImageName,
53 DiagnosticsEngine &Diags)
54 : Opts(createDriverOptTable()), Diags(Diags),
55 ClangExecutable(ClangExecutable), UseStdLib(true),
56 DefaultHostTriple(DefaultHostTriple), DefaultImageName(DefaultImageName),
57 DriverTitle("clang \"gcc-compatible\" driver"),
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) {
67 // In a "production" build, only use clang on architectures we expect to
68 // work, and don't use clang C++.
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);
78 Name = llvm::sys::path::stem(ClangExecutable);
79 Dir = llvm::sys::path::parent_path(ClangExecutable);
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);
87 llvm::sys::path::append(P, "..", "lib", "clang", CLANG_VERSION_STRING);
88 ResourceDir = P.str();
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);
102 // Check for missing argument error.
104 Diag(clang::diag::err_drv_missing_argument)
105 << Args->getArgString(MissingArgIndex) << MissingArgCount;
107 // Check for unsupported options.
108 for (ArgList::const_iterator it = Args->begin(), ie = Args->end();
111 if (A->getOption().isUnsupported()) {
112 Diag(clang::diag::err_drv_unsupported_opt) << A->getAsString(*Args);
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)
126 phases::ID FinalPhase;
128 // -{E,M,MM} only run the preprocessor.
130 (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
131 (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM))) {
132 FinalPhase = phases::Preprocess;
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;
143 // -c only runs up to the assembler.
144 } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
145 FinalPhase = phases::Assemble;
147 // Otherwise do everything.
149 FinalPhase = phases::Link;
152 *FinalPhaseArg = PhaseArg;
157 DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
158 DerivedArgList *DAL = new DerivedArgList(Args);
160 bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
161 for (ArgList::const_iterator it = Args.begin(),
162 ie = Args.end(); it != ie; ++it) {
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').
169 // Rewrite linker options, to replace --no-demangle with a custom internal
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));
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));
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));
197 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD));
198 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF),
199 A->getValue(Args, 1));
203 // Rewrite reserved library names.
204 if (A->getOption().matches(options::OPT_l)) {
205 StringRef Value = A->getValue(Args);
207 // Rewrite unless -nostdlib is present.
208 if (!HasNostdlib && Value == "stdc++") {
209 DAL->AddFlagArg(A, Opts->getOption(
210 options::OPT_Z_reserved_lib_stdcxx));
214 // Rewrite unconditionally.
215 if (Value == "cc_kext") {
216 DAL->AddFlagArg(A, Opts->getOption(
217 options::OPT_Z_reserved_lib_cckext));
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),
231 DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
238 Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
239 llvm::PrettyStackTraceString CrashInfo("Compilation construction");
241 // FIXME: Handle environment options which affect driver behavior, somewhere
242 // (client?). GCC_EXEC_PREFIX, LIBRARY_PATH, LPATH, CC_PRINT_OPTIONS.
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;
253 // FIXME: What are we going to do with -V and -b?
255 // FIXME: This stuff needs to go into the Compilation, not the driver.
256 bool CCCPrintOptions = false, CCCPrintActions = false;
258 InputArgList *Args = ParseArgStrings(ArgList.slice(1));
260 // -no-canonical-prefixes is used very early in main.
261 Args->ClaimAllArgs(options::OPT_no_canonical_prefixes);
264 Args->ClaimAllArgs(options::OPT_pipe);
266 // Extract -ccc args.
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
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,
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);
289 CCCClangArchs.clear();
290 while (!Cur.empty()) {
291 std::pair<StringRef, StringRef> Split = Cur.split(',');
293 if (!Split.first.empty()) {
294 llvm::Triple::ArchType Arch =
295 llvm::Triple(Split.first, "", "").getArch();
297 if (Arch == llvm::Triple::UnknownArch)
298 Diag(clang::diag::err_drv_invalid_arch_name) << Split.first;
300 CCCClangArchs.insert(Arch);
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) {
316 PrefixDirs.push_back(A->getValue(*Args, 0));
318 if (const Arg *A = Args->getLastArg(options::OPT__sysroot_EQ))
319 SysRoot = A->getValue(*Args);
320 if (Args->hasArg(options::OPT_nostdlib))
323 Host = GetHostInfo(DefaultHostTriple.c_str());
325 // Perform the default argument translations.
326 DerivedArgList *TranslatedArgs = TranslateInputArgs(*Args);
328 // The compilation takes ownership of Args.
329 Compilation *C = new Compilation(*this, *Host->CreateToolChain(*Args), Args,
332 // FIXME: This behavior shouldn't be here.
333 if (CCCPrintOptions) {
334 PrintOptions(C->getInputArgs());
338 if (!HandleImmediateArgs(*C))
341 // Construct the list of inputs.
343 BuildInputs(C->getDefaultToolChain(), C->getArgs(), Inputs);
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());
350 BuildActions(C->getDefaultToolChain(), C->getArgs(), Inputs,
353 if (CCCPrintActions) {
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.";
372 // Suppress driver output and emit preprocessor output to temp file.
374 CCGenDiagnostics = true;
376 // Clear stale state and suppress tool output.
377 C.initCompilationForDiagnostics();
380 // Construct the list of inputs.
382 BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
384 for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
385 bool IgnoreInput = false;
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"
393 } else if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
398 it = Inputs.erase(it);
405 // Don't attempt to generate preprocessed files if multiple -arch options are
408 for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end();
411 if (A->getOption().matches(options::OPT_arch)) {
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.";
422 if (Inputs.empty()) {
423 Diag(clang::diag::note_drv_command_failed_diag_msg)
424 << "Error generating preprocessed source(s) - no preprocessable inputs.";
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());
433 BuildActions(C.getDefaultToolChain(), C.getArgs(), Inputs,
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).";
445 // Generate preprocessed output.
447 int Res = C.ExecuteJob(C.getJobs(), FailingCommand);
449 // If the command succeeded, we are done.
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();
456 Diag(clang::diag::note_drv_command_failed_diag_msg) << *it;
458 // Failure, remove preprocessed files.
459 if (!C.getArgs().hasArg(options::OPT_save_temps))
460 C.CleanupFileList(C.getTempFiles(), true);
462 Diag(clang::diag::note_drv_command_failed_diag_msg)
463 << "Error generating preprocessed source(s).";
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);
475 // If there were errors building the compilation, quit now.
476 if (Diags.hasErrorOccurred())
479 int Res = C.ExecuteJob(C.getJobs(), FailingCommand);
481 // Remove temp files.
482 C.CleanupFileList(C.getTempFiles());
484 // If the command succeeded, we are done.
488 // Otherwise, remove result files as well.
489 if (!C.getArgs().hasArg(options::OPT_save_temps))
490 C.CleanupFileList(C.getResultFiles(), true);
492 // Print extra information about abnormal failures, if possible.
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();
501 if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) {
502 // FIXME: See FIXME above regarding result code interpretation.
504 Diag(clang::diag::err_drv_command_signalled)
505 << FailingTool.getShortName() << -Res;
507 Diag(clang::diag::err_drv_command_failed)
508 << FailingTool.getShortName() << Res;
514 void Driver::PrintOptions(const ArgList &Args) const {
516 for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
517 it != ie; ++it, ++i) {
519 llvm::errs() << "Option " << i << " - "
520 << "Name: \"" << A->getOption().getName() << "\", "
522 for (unsigned j = 0; j < A->getNumValues(); ++j) {
524 llvm::errs() << ", ";
525 llvm::errs() << '"' << A->getValue(Args, j) << '"';
527 llvm::errs() << "}\n";
531 void Driver::PrintHelp(bool ShowHidden) const {
532 getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(),
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';
543 // Print the threading model.
545 // FIXME: Implement correctly.
546 OS << "Thread model: " << "posix" << '\n';
549 /// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
551 static void PrintDiagnosticCategories(raw_ostream &OS) {
552 // Skip the empty category.
553 for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories();
555 OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
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.
562 if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
563 llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
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__.
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";
578 if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
579 PrintDiagnosticCategories(llvm::outs());
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));
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());
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;
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())
610 llvm::outs() << "\n";
611 llvm::outs() << "libraries: =" << ResourceDir;
614 if (Arg *A = C.getArgs().getLastArg(options::OPT__sysroot_EQ))
615 sysroot = A->getValue(C.getArgs());
617 for (ToolChain::path_list::const_iterator it = TC.getFilePaths().begin(),
618 ie = TC.getFilePaths().end(); it != ie; ++it) {
620 const char *path = it->c_str();
622 llvm::outs() << sysroot << path + 1;
624 llvm::outs() << path;
626 llvm::outs() << "\n";
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";
637 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
638 llvm::outs() << GetProgramPath(A->getValue(C.getArgs()), TC) << "\n";
642 if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
643 llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
647 if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
648 // FIXME: We need tool chain support for this.
649 llvm::outs() << ".;\n";
651 switch (C.getDefaultToolChain().getTriple().getArch()) {
655 case llvm::Triple::x86_64:
656 llvm::outs() << "x86_64;@m64" << "\n";
659 case llvm::Triple::ppc64:
660 llvm::outs() << "ppc64;@m64" << "\n";
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()) {
672 case llvm::Triple::x86:
673 case llvm::Triple::ppc:
674 llvm::outs() << "." << "\n";
677 case llvm::Triple::x86_64:
678 llvm::outs() << "." << "\n";
681 case llvm::Triple::ppc64:
682 llvm::outs() << "ppc64" << "\n";
691 static unsigned PrintActions1(const Compilation &C, Action *A,
692 std::map<Action*, unsigned> &Ids) {
697 llvm::raw_string_ostream os(str);
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) << "}";
708 for (Action::iterator it = A->begin(), ie = A->end(); it != ie;) {
709 os << PrintActions1(C, *it, Ids);
717 unsigned Id = Ids.size();
719 llvm::errs() << Id << ": " << os.str() << ", "
720 << types::getTypeName(A->getType()) << "\n";
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);
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))
738 for (Action::const_iterator it = A->begin(), ie = A->end(); it != ie; ++it)
739 if (ContainsCompileOrAssembleAction(*it))
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();
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);
770 if (ArchNames.insert(A->getValue(Args)))
771 Archs.push_back(A->getValue(Args));
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.
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);
791 ActionList SingleActions;
792 BuildActions(TC, Args, BAInputs, SingleActions);
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];
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.
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());
810 for (unsigned i = 0, e = Archs.size(); i != e; ++i) {
811 Inputs.push_back(new BindArchAction(Act, Archs[i]));
813 Inputs.back()->setOwnsInputs(false);
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());
821 Actions.push_back(new LipoJobAction(Inputs, Act->getType()));
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())) {
833 Inputs.push_back(Actions.back());
836 Actions.push_back(new DsymutilJobAction(Inputs, types::TY_dSYM));
838 // Verify the debug output if we're in assert mode.
839 // TODO: The verifier is noisy by default so put this under an
842 if (Args.hasArg(options::OPT_verify)) {
843 ActionList VerifyInputs;
844 VerifyInputs.push_back(Actions.back());
846 Actions.push_back(new VerifyJobAction(VerifyInputs,
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;
864 for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
868 if (isa<InputOption>(A->getOption())) {
869 const char *Value = A->getValue(Args);
870 types::ID Ty = types::TY_INVALID;
872 // Infer the input type if necessary.
873 if (InputType == types::TY_Nothing) {
874 // If there was an explicit arg for this, claim it.
876 InputTypeArg->claim();
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.
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);
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);
896 if (Ty == types::TY_INVALID) {
900 Ty = types::TY_Object;
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.
906 types::ID OldTy = Ty;
907 Ty = types::lookupCXXTypeForCType(Ty);
910 Diag(clang::diag::warn_drv_treating_input_as_cxx)
911 << getTypeName(OldTy) << getTypeName(Ty);
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
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))
923 else if (Args.hasArg(options::OPT_ObjCXX))
924 Ty = types::TY_ObjCXX;
927 assert(InputTypeArg && "InputType set w/o InputTypeArg");
928 InputTypeArg->claim();
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);
942 if (/*error_code ec =*/llvm::sys::fs::exists(Value, exists) || !exists)
943 Diag(clang::diag::err_drv_no_such_file) << Path.str();
945 Inputs.push_back(std::make_pair(Ty, A));
947 Inputs.push_back(std::make_pair(Ty, A));
949 } else if (A->getOption().isLinkerInput()) {
950 // Just treat as object type, we could make a special type for this if
952 Inputs.push_back(std::make_pair(types::TY_Object, A));
954 } else if (A->getOption().matches(options::OPT_x)) {
956 InputType = types::lookupTypeForTypeSpecifier(A->getValue(Args));
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.
962 Diag(clang::diag::err_drv_unknown_language) << A->getValue(Args);
963 InputType = types::TY_Object;
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);
973 Inputs.push_back(std::make_pair(types::TY_C, A));
977 void Driver::BuildActions(const ToolChain &TC, const DerivedArgList &Args,
978 const InputList &Inputs, ActionList &Actions) const {
979 llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
981 if (!SuppressMissingInputWarning && Inputs.empty()) {
982 Diag(clang::diag::err_drv_no_input_files);
987 phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
989 // Reject -Z* at the top level, these options should never have been exposed
991 if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
992 Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
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;
1000 unsigned NumSteps = types::getNumCompilationPhases(InputType);
1001 assert(NumSteps && "Invalid number of steps!");
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.
1010 // Suppress all unused style warnings with -Qunused-arguments
1011 if (Args.hasArg(options::OPT_Qunused_arguments))
1014 // Special case '-E' warning on a previously preprocessed file to make
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();
1022 Diag(clang::diag::warn_drv_input_file_unused)
1023 << InputArg->getAsString(Args)
1024 << getPhaseName(InitialPhase)
1025 << FinalPhaseArg->getOption().getName();
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);
1034 // We are done if this step is past what the user requested.
1035 if (Phase > FinalPhase)
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());
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)
1051 // Otherwise construct the appropriate action.
1052 Current.reset(ConstructPhaseAction(Args, Phase, Current.take()));
1053 if (Current->getType() == types::TY_Nothing)
1057 // If we ended with something, add to the output list.
1059 Actions.push_back(Current.take());
1062 // Add a link action if necessary.
1063 if (!LinkerInputs.empty())
1064 Actions.push_back(new LinkJobAction(LinkerInputs, types::TY_Image));
1066 // If we are linking, claim any options which are obviously only used for
1068 if (FinalPhase == phases::Link)
1069 Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
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.
1077 case phases::Link: llvm_unreachable("link action invalid here.");
1078 case phases::Preprocess: {
1080 // -{M, MM} alter the output type.
1081 if (Args.hasArg(options::OPT_M, options::OPT_MM)) {
1082 OutputTy = types::TY_Dependencies;
1084 OutputTy = types::getPreprocessedType(Input->getType());
1085 assert(OutputTy != types::TY_INVALID &&
1086 "Cannot preprocess this input type!");
1088 return new PreprocessJobAction(Input, OutputTy);
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)) {
1103 Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
1104 return new CompileJobAction(Input, Output);
1106 return new CompileJobAction(Input, types::TY_PP_Asm);
1109 case phases::Assemble:
1110 return new AssembleJobAction(Input, types::TY_Object);
1113 llvm_unreachable("invalid phase in ConstructPhaseAction");
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))
1123 if (const Arg *A = Args.getLastArg(options::OPT_O_Group))
1124 return A->getOption().matches(options::OPT_O4);
1129 void Driver::BuildJobs(Compilation &C) const {
1130 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
1132 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
1134 // It is an error to provide a -o option if we are making multiple output
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)
1143 if (NumOutputs > 1) {
1144 Diag(clang::diag::err_drv_output_argument_with_multiple_files);
1149 for (ActionList::const_iterator it = C.getActions().begin(),
1150 ie = C.getActions().end(); it != ie; ++it) {
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.
1157 // FIXME: This is a hack; find a cleaner way to integrate this into the
1159 const char *LinkingOutput = 0;
1160 if (isa<LipoJobAction>(A)) {
1162 LinkingOutput = FinalOutput->getValue(C.getArgs());
1164 LinkingOutput = DefaultImageName.c_str();
1168 BuildJobsForAction(C, A, &C.getDefaultToolChain(),
1170 /*AtTopLevel*/ true,
1171 /*LinkingOutput*/ LinkingOutput,
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))
1182 (void) C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
1184 for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end();
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
1191 if (!A->isClaimed()) {
1192 if (A->getOption().hasNoArgumentUnused())
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;
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;
1209 if (DuplicateClaimed)
1213 Diag(clang::diag::warn_drv_unused_argument)
1214 << A->getAsString(C.getArgs());
1219 static const Tool &SelectToolForJob(Compilation &C, const ToolChain *TC,
1220 const JobAction *JA,
1221 const ActionList *&Inputs) {
1222 const Tool *ToolForJob = 0;
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
1228 // FIXME: This doesn't belong here, but ideally we will support static soon
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,
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;
1250 // Otherwise use the tool for the current job.
1252 ToolForJob = &TC->SelectTool(C, *JA, *Inputs);
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();
1267 void Driver::BuildJobsForAction(Compilation &C,
1269 const ToolChain *TC,
1270 const char *BoundArch,
1272 const char *LinkingOutput,
1273 InputInfo &Result) const {
1274 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
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();
1281 if (Input.getOption().matches(options::OPT_INPUT)) {
1282 const char *Name = Input.getValue(C.getArgs());
1283 Result = InputInfo(Name, A->getType(), Name);
1285 Result = InputInfo(&Input, A->getType(), "");
1289 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
1290 const ToolChain *TC = &C.getDefaultToolChain();
1293 if (BAA->getArchName())
1294 TC = Host->CreateToolChain(C.getArgs(), BAA->getArchName());
1296 BuildJobsForAction(C, *BAA->begin(), TC, BAA->getArchName(),
1297 AtTopLevel, LinkingOutput, Result);
1301 const ActionList *Inputs = &A->getInputs();
1303 const JobAction *JA = cast<JobAction>(A);
1304 const Tool &T = SelectToolForJob(C, TC, JA, Inputs);
1306 // Only use pipes when there is exactly one input.
1307 InputInfoList InputInfos;
1308 for (ActionList::const_iterator it = Inputs->begin(), ie = Inputs->end();
1310 // Treat dsymutil sub-jobs as being at the top-level too, they shouldn't get
1311 // temporary output names.
1313 // FIXME: Clean this up.
1314 bool SubJobAtTopLevel = false;
1315 if (AtTopLevel && isa<DsymutilJobAction>(A))
1316 SubJobAtTopLevel = true;
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;
1324 BuildJobsForAction(C, *it, TC, BoundArch,
1325 SubJobAtTopLevel, LinkingOutput, II);
1326 InputInfos.push_back(II);
1329 // Always use the first input as the base input.
1330 const char *BaseInput = InputInfos[0].getBaseInput();
1332 // ... except dsymutil actions, which use their actual input as the base
1334 if (JA->getType() == types::TY_dSYM)
1335 BaseInput = InputInfos[0].getFilename();
1337 // Determine the place to write output to, if any.
1338 if (JA->getType() == types::TY_Nothing) {
1339 Result = InputInfo(A->getType(), BaseInput);
1341 Result = InputInfo(GetNamedOutputPath(C, *JA, BaseInput, AtTopLevel),
1342 A->getType(), BaseInput);
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();
1351 llvm::errs() << ", ";
1353 llvm::errs() << "], output: " << Result.getAsString() << "\n";
1355 T.ConstructJob(C, *JA, Result, InputInfos,
1356 C.getArgsForToolChain(TC, BoundArch), LinkingOutput);
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()));
1372 // Default to writing to stdout?
1373 if (AtTopLevel && isa<PreprocessJobAction>(JA) && !CCGenDiagnostics)
1376 // Output to a temporary file?
1377 if ((!AtTopLevel && !C.getArgs().hasArg(options::OPT_save_temps)) ||
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()));
1386 llvm::SmallString<128> BasePath(BaseInput);
1389 // Dsymutil actions should use the full path.
1390 if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
1391 BaseName = BasePath;
1393 BaseName = llvm::sys::path::filename(BasePath);
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();
1400 const char *Suffix = types::getTypeTempSuffix(JA.getType());
1401 assert(Suffix && "All types used for output should have a suffix.");
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));
1409 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
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()));
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;
1429 llvm::sys::path::append(BasePath, NamedOutput);
1430 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()));
1432 return C.addResultFile(NamedOutput);
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);
1445 Dir = SysRoot + Dir.substr(1);
1446 llvm::sys::Path P(Dir);
1447 P.appendComponent(Name);
1449 if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
1453 llvm::sys::Path P(ResourceDir);
1454 P.appendComponent(Name);
1456 if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
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);
1466 Dir = SysRoot + Dir.substr(1);
1467 llvm::sys::Path P(Dir);
1468 P.appendComponent(Name);
1470 if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
1477 static bool isPathExecutable(llvm::sys::Path &P, bool WantFile) {
1479 return (WantFile ? !llvm::sys::fs::exists(P.str(), Exists) && Exists
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();
1494 P.appendComponent(Name);
1495 if (isPathExecutable(P, WantFile)) return P.str();
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();
1505 P.appendComponent(Name);
1506 if (isPathExecutable(P, WantFile)) return P.str();
1509 // If all else failed, search the path.
1511 P(llvm::sys::Program::FindProgramByName(TargetSpecificExecutable));
1515 P = llvm::sys::Path(llvm::sys::Program::FindProgramByName(Name));
1522 std::string Driver::GetTemporaryPath(StringRef Prefix, const char *Suffix)
1524 // FIXME: This is lame; sys::Path should provide this function (in particular,
1525 // it should know how to find the temporary files dir).
1527 const char *TmpDir = ::getenv("TMPDIR");
1529 TmpDir = ::getenv("TEMP");
1531 TmpDir = ::getenv("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;
1541 // FIXME: Grumble, makeUnique sometimes leaves the file around!? PR3837.
1542 P.eraseFromDisk(false, 0);
1544 P.appendSuffix(Suffix);
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());
1552 // TCE is an osless target
1553 if (Triple.getArchName() == "tce")
1554 return createTCEHostInfo(*this, Triple);
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);
1580 return createUnknownHostInfo(*this, Triple);
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()))
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);
1598 } else if (!isa<PrecompileJobAction>(JA) && !isa<CompileJobAction>(JA))
1601 // Use clang for C++?
1602 if (!CCCUseClangCXX && types::isCXX((*JA.begin())->getType())) {
1603 Diag(clang::diag::warn_drv_not_using_clang_cxx);
1607 // Always use clang for precompiling, AST generation, and rewriting,
1608 // regardless of archs.
1609 if (isa<PrecompileJobAction>(JA) ||
1610 types::isOnlyAcceptedByClang(JA.getType()))
1613 // Finally, don't use clang if this isn't one of the user specified archs to
1615 if (!CCCClangArchs.empty() && !CCCClangArchs.count(Triple.getArch())) {
1616 Diag(clang::diag::warn_drv_not_using_clang_arch) << Triple.getArchName();
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.
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,
1633 Major = Minor = Micro = 0;
1638 Major = (unsigned) strtol(Str, &End, 10);
1639 if (*Str != '\0' && *End == '\0')
1645 Minor = (unsigned) strtol(Str, &End, 10);
1646 if (*Str != '\0' && *End == '\0')
1652 Micro = (unsigned) strtol(Str, &End, 10);
1653 if (*Str != '\0' && *End == '\0')