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 #include "clang/Driver/Driver.h"
12 #include "clang/Driver/Action.h"
13 #include "clang/Driver/Arg.h"
14 #include "clang/Driver/ArgList.h"
15 #include "clang/Driver/Compilation.h"
16 #include "clang/Driver/DriverDiagnostic.h"
17 #include "clang/Driver/HostInfo.h"
18 #include "clang/Driver/Job.h"
19 #include "clang/Driver/Option.h"
20 #include "clang/Driver/Options.h"
21 #include "clang/Driver/Tool.h"
22 #include "clang/Driver/ToolChain.h"
23 #include "clang/Driver/Types.h"
25 #include "clang/Basic/Version.h"
27 #include "llvm/ADT/StringSet.h"
28 #include "llvm/Support/PrettyStackTrace.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/System/Path.h"
31 #include "llvm/System/Program.h"
33 #include "InputInfo.h"
37 using namespace clang::driver;
38 using namespace clang;
40 Driver::Driver(const char *_Name, const char *_Dir,
41 const char *_DefaultHostTriple,
42 const char *_DefaultImageName,
44 : Opts(new OptTable()), Diags(_Diags),
45 Name(_Name), Dir(_Dir), DefaultHostTriple(_DefaultHostTriple),
46 DefaultImageName(_DefaultImageName),
48 CCCIsCXX(false), CCCEcho(false), CCCPrintBindings(false),
49 CCCGenericGCCName("gcc"), CCCUseClang(true), CCCUseClangCXX(false),
50 CCCUseClangCPP(true), CCCUsePCH(true),
51 SuppressMissingInputWarning(false)
53 // Only use clang on i386 and x86_64 by default.
54 CCCClangArchs.insert("i386");
55 CCCClangArchs.insert("x86_64");
63 InputArgList *Driver::ParseArgStrings(const char **ArgBegin,
64 const char **ArgEnd) {
65 llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
66 InputArgList *Args = new InputArgList(ArgBegin, ArgEnd);
68 // FIXME: Handle '@' args (or at least error on them).
70 unsigned Index = 0, End = ArgEnd - ArgBegin;
72 // gcc's handling of empty arguments doesn't make
73 // sense, but this is not a common use case. :)
75 // We just ignore them here (note that other things may
76 // still take them as arguments).
77 if (Args->getArgString(Index)[0] == '\0') {
82 unsigned Prev = Index;
83 Arg *A = getOpts().ParseOneArg(*Args, Index);
84 assert(Index > Prev && "Parser failed to consume argument.");
86 // Check for missing argument error.
88 assert(Index >= End && "Unexpected parser error.");
89 Diag(clang::diag::err_drv_missing_argument)
90 << Args->getArgString(Prev)
91 << (Index - Prev - 1);
95 if (A->getOption().isUnsupported()) {
96 Diag(clang::diag::err_drv_unsupported_opt) << A->getAsString(*Args);
105 Compilation *Driver::BuildCompilation(int argc, const char **argv) {
106 llvm::PrettyStackTraceString CrashInfo("Compilation construction");
108 // FIXME: Handle environment options which effect driver behavior,
109 // somewhere (client?). GCC_EXEC_PREFIX, COMPILER_PATH,
110 // LIBRARY_PATH, LPATH, CC_PRINT_OPTIONS, QA_OVERRIDE_GCC3_OPTIONS.
112 // FIXME: What are we going to do with -V and -b?
114 // FIXME: This stuff needs to go into the Compilation, not the
116 bool CCCPrintOptions = false, CCCPrintActions = false;
118 const char **Start = argv + 1, **End = argv + argc;
119 const char *HostTriple = DefaultHostTriple.c_str();
123 // FIXME: We need to figure out where this behavior should
124 // live. Most of it should be outside in the client; the parts that
125 // aren't should have proper options, either by introducing new ones
126 // or by overloading gcc ones like -V or -b.
127 for (; Start != End && memcmp(*Start, "-ccc-", 5) == 0; ++Start) {
128 const char *Opt = *Start + 5;
130 if (!strcmp(Opt, "print-options")) {
131 CCCPrintOptions = true;
132 } else if (!strcmp(Opt, "print-phases")) {
133 CCCPrintActions = true;
134 } else if (!strcmp(Opt, "print-bindings")) {
135 CCCPrintBindings = true;
136 } else if (!strcmp(Opt, "cxx")) {
138 } else if (!strcmp(Opt, "echo")) {
141 } else if (!strcmp(Opt, "gcc-name")) {
142 assert(Start+1 < End && "FIXME: -ccc- argument handling.");
143 CCCGenericGCCName = *++Start;
145 } else if (!strcmp(Opt, "clang-cxx")) {
146 CCCUseClangCXX = true;
147 } else if (!strcmp(Opt, "pch-is-pch")) {
149 } else if (!strcmp(Opt, "pch-is-pth")) {
151 } else if (!strcmp(Opt, "no-clang")) {
153 } else if (!strcmp(Opt, "no-clang-cpp")) {
154 CCCUseClangCPP = false;
155 } else if (!strcmp(Opt, "clang-archs")) {
156 assert(Start+1 < End && "FIXME: -ccc- argument handling.");
157 const char *Cur = *++Start;
159 CCCClangArchs.clear();
161 const char *Next = strchr(Cur, ',');
165 CCCClangArchs.insert(std::string(Cur, Next));
169 CCCClangArchs.insert(std::string(Cur));
174 } else if (!strcmp(Opt, "host-triple")) {
175 assert(Start+1 < End && "FIXME: -ccc- argument handling.");
176 HostTriple = *++Start;
179 // FIXME: Error handling.
180 llvm::errs() << "invalid option: " << *Start << "\n";
185 InputArgList *Args = ParseArgStrings(Start, End);
187 Host = GetHostInfo(HostTriple);
189 // The compilation takes ownership of Args.
190 Compilation *C = new Compilation(*this, *Host->getToolChain(*Args), Args);
192 // FIXME: This behavior shouldn't be here.
193 if (CCCPrintOptions) {
194 PrintOptions(C->getArgs());
198 if (!HandleImmediateArgs(*C))
201 // Construct the list of abstract actions to perform for this
202 // compilation. We avoid passing a Compilation here simply to
203 // enforce the abstraction that pipelining is not host or toolchain
204 // dependent (other than the driver driver test).
205 if (Host->useDriverDriver())
206 BuildUniversalActions(C->getArgs(), C->getActions());
208 BuildActions(C->getArgs(), C->getActions());
210 if (CCCPrintActions) {
220 void Driver::PrintOptions(const ArgList &Args) const {
222 for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
223 it != ie; ++it, ++i) {
225 llvm::errs() << "Option " << i << " - "
226 << "Name: \"" << A->getOption().getName() << "\", "
228 for (unsigned j = 0; j < A->getNumValues(); ++j) {
230 llvm::errs() << ", ";
231 llvm::errs() << '"' << A->getValue(Args, j) << '"';
233 llvm::errs() << "}\n";
237 static std::string getOptionHelpName(const OptTable &Opts, options::ID Id) {
238 std::string Name = Opts.getOptionName(Id);
240 // Add metavar, if used.
241 switch (Opts.getOptionKind(Id)) {
242 case Option::GroupClass: case Option::InputClass: case Option::UnknownClass:
243 assert(0 && "Invalid option with help text.");
245 case Option::MultiArgClass: case Option::JoinedAndSeparateClass:
246 assert(0 && "Cannot print metavar for this kind of option.");
248 case Option::FlagClass:
251 case Option::SeparateClass: case Option::JoinedOrSeparateClass:
254 case Option::JoinedClass: case Option::CommaJoinedClass:
255 Name += Opts.getOptionMetaVar(Id);
262 void Driver::PrintHelp(bool ShowHidden) const {
263 llvm::raw_ostream &OS = llvm::outs();
265 OS << "OVERVIEW: clang \"gcc-compatible\" driver\n";
267 OS << "USAGE: " << Name << " [options] <input files>\n";
271 // Render help text into (option, help) pairs.
272 std::vector< std::pair<std::string, const char*> > OptionHelp;
274 for (unsigned i = options::OPT_INPUT, e = options::LastOption; i != e; ++i) {
275 options::ID Id = (options::ID) i;
276 if (const char *Text = getOpts().getOptionHelpText(Id))
277 OptionHelp.push_back(std::make_pair(getOptionHelpName(getOpts(), Id),
282 OptionHelp.push_back(std::make_pair("\nDRIVER OPTIONS:",""));
283 OptionHelp.push_back(std::make_pair("-ccc-cxx",
284 "Act as a C++ driver"));
285 OptionHelp.push_back(std::make_pair("-ccc-gcc-name",
286 "Name for native GCC compiler"));
287 OptionHelp.push_back(std::make_pair("-ccc-clang-cxx",
288 "Use the clang compiler for C++"));
289 OptionHelp.push_back(std::make_pair("-ccc-no-clang",
290 "Never use the clang compiler"));
291 OptionHelp.push_back(std::make_pair("-ccc-no-clang-cpp",
292 "Never use the clang preprocessor"));
293 OptionHelp.push_back(std::make_pair("-ccc-clang-archs",
294 "Comma separate list of architectures "
295 "to use the clang compiler for"));
296 OptionHelp.push_back(std::make_pair("-ccc-pch-is-pch",
297 "Use lazy PCH for precompiled headers"));
298 OptionHelp.push_back(std::make_pair("-ccc-pch-is-pth",
299 "Use pretokenized headers for precompiled headers"));
301 OptionHelp.push_back(std::make_pair("\nDEBUG/DEVELOPMENT OPTIONS:",""));
302 OptionHelp.push_back(std::make_pair("-ccc-host-triple",
303 "Simulate running on the given target"));
304 OptionHelp.push_back(std::make_pair("-ccc-print-options",
305 "Dump parsed command line arguments"));
306 OptionHelp.push_back(std::make_pair("-ccc-print-phases",
307 "Dump list of actions to perform"));
308 OptionHelp.push_back(std::make_pair("-ccc-print-bindings",
309 "Show bindings of tools to actions"));
310 OptionHelp.push_back(std::make_pair("CCC_ADD_ARGS",
311 "(ENVIRONMENT VARIABLE) Comma separated list of "
312 "arguments to prepend to the command line"));
315 // Find the maximum option length.
316 unsigned OptionFieldWidth = 0;
317 for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
319 if (!OptionHelp[i].second)
322 // Limit the amount of padding we are willing to give up for
324 unsigned Length = OptionHelp[i].first.size();
326 OptionFieldWidth = std::max(OptionFieldWidth, Length);
329 for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
330 const std::string &Option = OptionHelp[i].first;
332 for (int j = Option.length(), e = OptionFieldWidth; j < e; ++j)
334 OS << ' ' << OptionHelp[i].second << '\n';
340 void Driver::PrintVersion(const Compilation &C) const {
341 static char buf[] = "$URL: https://ed@llvm.org/svn/llvm-project/cfe/trunk/lib/Driver/Driver.cpp $";
342 char *zap = strstr(buf, "/lib/Driver");
345 zap = strstr(buf, "/clang/tools/clang");
348 const char *vers = buf+6;
349 // FIXME: Add cmake support and remove #ifdef
351 const char *revision = SVN_REVISION;
353 const char *revision = "";
355 // FIXME: The following handlers should use a callback mechanism, we
356 // don't know what the client would like to do.
358 llvm::errs() << "clang version " CLANG_VERSION_STRING " ("
359 << vers << " " << revision << ")" << "\n";
361 const ToolChain &TC = C.getDefaultToolChain();
362 llvm::errs() << "Target: " << TC.getTripleString() << '\n';
365 bool Driver::HandleImmediateArgs(const Compilation &C) {
366 // The order these options are handled in in gcc is all over the
367 // place, but we don't expect inconsistencies w.r.t. that to matter
370 if (C.getArgs().hasArg(options::OPT_dumpversion)) {
371 llvm::outs() << CLANG_VERSION_STRING "\n";
375 if (C.getArgs().hasArg(options::OPT__help) ||
376 C.getArgs().hasArg(options::OPT__help_hidden)) {
377 PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
381 if (C.getArgs().hasArg(options::OPT__version)) {
386 if (C.getArgs().hasArg(options::OPT_v) ||
387 C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
389 SuppressMissingInputWarning = true;
392 const ToolChain &TC = C.getDefaultToolChain();
393 if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
394 llvm::outs() << "programs: =";
395 for (ToolChain::path_list::const_iterator it = TC.getProgramPaths().begin(),
396 ie = TC.getProgramPaths().end(); it != ie; ++it) {
397 if (it != TC.getProgramPaths().begin())
401 llvm::outs() << "\n";
402 llvm::outs() << "libraries: =";
403 for (ToolChain::path_list::const_iterator it = TC.getFilePaths().begin(),
404 ie = TC.getFilePaths().end(); it != ie; ++it) {
405 if (it != TC.getFilePaths().begin())
409 llvm::outs() << "\n";
413 // FIXME: The following handlers should use a callback mechanism, we
414 // don't know what the client would like to do.
415 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
416 llvm::outs() << GetFilePath(A->getValue(C.getArgs()), TC).toString()
421 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
422 llvm::outs() << GetProgramPath(A->getValue(C.getArgs()), TC).toString()
427 if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
428 llvm::outs() << GetFilePath("libgcc.a", TC).toString() << "\n";
435 static unsigned PrintActions1(const Compilation &C,
437 std::map<Action*, unsigned> &Ids) {
442 llvm::raw_string_ostream os(str);
444 os << Action::getClassName(A->getKind()) << ", ";
445 if (InputAction *IA = dyn_cast<InputAction>(A)) {
446 os << "\"" << IA->getInputArg().getValue(C.getArgs()) << "\"";
447 } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
448 os << '"' << (BIA->getArchName() ? BIA->getArchName() :
449 C.getDefaultToolChain().getArchName()) << '"'
450 << ", {" << PrintActions1(C, *BIA->begin(), Ids) << "}";
453 for (Action::iterator it = A->begin(), ie = A->end(); it != ie;) {
454 os << PrintActions1(C, *it, Ids);
462 unsigned Id = Ids.size();
464 llvm::errs() << Id << ": " << os.str() << ", "
465 << types::getTypeName(A->getType()) << "\n";
470 void Driver::PrintActions(const Compilation &C) const {
471 std::map<Action*, unsigned> Ids;
472 for (ActionList::const_iterator it = C.getActions().begin(),
473 ie = C.getActions().end(); it != ie; ++it)
474 PrintActions1(C, *it, Ids);
477 void Driver::BuildUniversalActions(const ArgList &Args,
478 ActionList &Actions) const {
479 llvm::PrettyStackTraceString CrashInfo("Building actions for universal build");
480 // Collect the list of architectures. Duplicates are allowed, but
481 // should only be handled once (in the order seen).
482 llvm::StringSet<> ArchNames;
483 llvm::SmallVector<const char *, 4> Archs;
484 for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
488 if (A->getOption().getId() == options::OPT_arch) {
489 const char *Name = A->getValue(Args);
491 // FIXME: We need to handle canonicalization of the specified
495 if (ArchNames.insert(Name))
496 Archs.push_back(Name);
500 // When there is no explicit arch for this platform, make sure we
501 // still bind the architecture (to the default) so that -Xarch_ is
502 // handled correctly.
506 // FIXME: We killed off some others but these aren't yet detected in
507 // a functional manner. If we added information to jobs about which
508 // "auxiliary" files they wrote then we could detect the conflict
509 // these cause downstream.
510 if (Archs.size() > 1) {
511 // No recovery needed, the point of this is just to prevent
512 // overwriting the same files.
513 if (const Arg *A = Args.getLastArg(options::OPT_save_temps))
514 Diag(clang::diag::err_drv_invalid_opt_with_multiple_archs)
515 << A->getAsString(Args);
518 ActionList SingleActions;
519 BuildActions(Args, SingleActions);
521 // Add in arch binding and lipo (if necessary) for every top level
523 for (unsigned i = 0, e = SingleActions.size(); i != e; ++i) {
524 Action *Act = SingleActions[i];
526 // Make sure we can lipo this kind of output. If not (and it is an
527 // actual output) then we disallow, since we can't create an
528 // output file with the right name without overwriting it. We
529 // could remove this oddity by just changing the output names to
530 // include the arch, which would also fix
531 // -save-temps. Compatibility wins for now.
533 if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
534 Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
535 << types::getTypeName(Act->getType());
538 for (unsigned i = 0, e = Archs.size(); i != e; ++i)
539 Inputs.push_back(new BindArchAction(Act, Archs[i]));
541 // Lipo if necessary, We do it this way because we need to set the
542 // arch flag so that -Xarch_ gets overwritten.
543 if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
544 Actions.append(Inputs.begin(), Inputs.end());
546 Actions.push_back(new LipoJobAction(Inputs, Act->getType()));
550 void Driver::BuildActions(const ArgList &Args, ActionList &Actions) const {
551 llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
552 // Start by constructing the list of inputs and their types.
554 // Track the current user specified (-x) input. We also explicitly
555 // track the argument used to set the type; we only want to claim
556 // the type when we actually use it, so we warn about unused -x
558 types::ID InputType = types::TY_Nothing;
559 Arg *InputTypeArg = 0;
561 llvm::SmallVector<std::pair<types::ID, const Arg*>, 16> Inputs;
562 for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
566 if (isa<InputOption>(A->getOption())) {
567 const char *Value = A->getValue(Args);
568 types::ID Ty = types::TY_INVALID;
570 // Infer the input type if necessary.
571 if (InputType == types::TY_Nothing) {
572 // If there was an explicit arg for this, claim it.
574 InputTypeArg->claim();
576 // stdin must be handled specially.
577 if (memcmp(Value, "-", 2) == 0) {
578 // If running with -E, treat as a C input (this changes the
579 // builtin macros, for example). This may be overridden by
582 // Otherwise emit an error but still use a valid type to
583 // avoid spurious errors (e.g., no inputs).
584 if (!Args.hasArg(options::OPT_E, false))
585 Diag(clang::diag::err_drv_unknown_stdin_type);
588 // Otherwise lookup by extension, and fallback to ObjectType
589 // if not found. We use a host hook here because Darwin at
590 // least has its own idea of what .s is.
591 if (const char *Ext = strrchr(Value, '.'))
592 Ty = Host->lookupTypeForExtension(Ext + 1);
594 if (Ty == types::TY_INVALID)
595 Ty = types::TY_Object;
598 // -ObjC and -ObjC++ override the default language, but only for "source
599 // files". We just treat everything that isn't a linker input as a
602 // FIXME: Clean this up if we move the phase sequence into the type.
603 if (Ty != types::TY_Object) {
604 if (Args.hasArg(options::OPT_ObjC))
606 else if (Args.hasArg(options::OPT_ObjCXX))
607 Ty = types::TY_ObjCXX;
610 assert(InputTypeArg && "InputType set w/o InputTypeArg");
611 InputTypeArg->claim();
615 // Check that the file exists. It isn't clear this is worth
616 // doing, since the tool presumably does this anyway, and this
617 // just adds an extra stat to the equation, but this is gcc
619 if (memcmp(Value, "-", 2) != 0 && !llvm::sys::Path(Value).exists())
620 Diag(clang::diag::err_drv_no_such_file) << A->getValue(Args);
622 Inputs.push_back(std::make_pair(Ty, A));
624 } else if (A->getOption().isLinkerInput()) {
625 // Just treat as object type, we could make a special type for
626 // this if necessary.
627 Inputs.push_back(std::make_pair(types::TY_Object, A));
629 } else if (A->getOption().getId() == options::OPT_x) {
631 InputType = types::lookupTypeForTypeSpecifier(A->getValue(Args));
633 // Follow gcc behavior and treat as linker input for invalid -x
634 // options. Its not clear why we shouldn't just revert to
635 // unknown; but this isn't very important, we might as well be
638 Diag(clang::diag::err_drv_unknown_language) << A->getValue(Args);
639 InputType = types::TY_Object;
644 if (!SuppressMissingInputWarning && Inputs.empty()) {
645 Diag(clang::diag::err_drv_no_input_files);
649 // Determine which compilation mode we are in. We look for options
650 // which affect the phase, starting with the earliest phases, and
651 // record which option we used to determine the final phase.
652 Arg *FinalPhaseArg = 0;
653 phases::ID FinalPhase;
655 // -{E,M,MM} only run the preprocessor.
656 if ((FinalPhaseArg = Args.getLastArg(options::OPT_E)) ||
657 (FinalPhaseArg = Args.getLastArg(options::OPT_M)) ||
658 (FinalPhaseArg = Args.getLastArg(options::OPT_MM))) {
659 FinalPhase = phases::Preprocess;
661 // -{fsyntax-only,-analyze,emit-llvm,S} only run up to the compiler.
662 } else if ((FinalPhaseArg = Args.getLastArg(options::OPT_fsyntax_only)) ||
663 (FinalPhaseArg = Args.getLastArg(options::OPT__analyze,
664 options::OPT__analyze_auto)) ||
665 (FinalPhaseArg = Args.getLastArg(options::OPT_S))) {
666 FinalPhase = phases::Compile;
668 // -c only runs up to the assembler.
669 } else if ((FinalPhaseArg = Args.getLastArg(options::OPT_c))) {
670 FinalPhase = phases::Assemble;
672 // Otherwise do everything.
674 FinalPhase = phases::Link;
676 // Reject -Z* at the top level, these options should never have been
678 if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
679 Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
681 // Construct the actions to perform.
682 ActionList LinkerInputs;
683 for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
684 types::ID InputType = Inputs[i].first;
685 const Arg *InputArg = Inputs[i].second;
687 unsigned NumSteps = types::getNumCompilationPhases(InputType);
688 assert(NumSteps && "Invalid number of steps!");
690 // If the first step comes after the final phase we are doing as
691 // part of this compilation, warn the user about it.
692 phases::ID InitialPhase = types::getCompilationPhase(InputType, 0);
693 if (InitialPhase > FinalPhase) {
694 // Claim here to avoid the more general unused warning.
696 Diag(clang::diag::warn_drv_input_file_unused)
697 << InputArg->getAsString(Args)
698 << getPhaseName(InitialPhase)
699 << FinalPhaseArg->getOption().getName();
703 // Build the pipeline for this file.
704 Action *Current = new InputAction(*InputArg, InputType);
705 for (unsigned i = 0; i != NumSteps; ++i) {
706 phases::ID Phase = types::getCompilationPhase(InputType, i);
708 // We are done if this step is past what the user requested.
709 if (Phase > FinalPhase)
712 // Queue linker inputs.
713 if (Phase == phases::Link) {
714 assert(i + 1 == NumSteps && "linking must be final compilation step.");
715 LinkerInputs.push_back(Current);
720 // Some types skip the assembler phase (e.g., llvm-bc), but we
721 // can't encode this in the steps because the intermediate type
722 // depends on arguments. Just special case here.
723 if (Phase == phases::Assemble && Current->getType() != types::TY_PP_Asm)
726 // Otherwise construct the appropriate action.
727 Current = ConstructPhaseAction(Args, Phase, Current);
728 if (Current->getType() == types::TY_Nothing)
732 // If we ended with something, add to the output list.
734 Actions.push_back(Current);
737 // Add a link action if necessary.
738 if (!LinkerInputs.empty())
739 Actions.push_back(new LinkJobAction(LinkerInputs, types::TY_Image));
742 Action *Driver::ConstructPhaseAction(const ArgList &Args, phases::ID Phase,
743 Action *Input) const {
744 llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
745 // Build the appropriate action.
747 case phases::Link: assert(0 && "link action invalid here.");
748 case phases::Preprocess: {
750 // -{M, MM} alter the output type.
751 if (Args.hasArg(options::OPT_M) || Args.hasArg(options::OPT_MM)) {
752 OutputTy = types::TY_Dependencies;
754 OutputTy = types::getPreprocessedType(Input->getType());
755 assert(OutputTy != types::TY_INVALID &&
756 "Cannot preprocess this input type!");
758 return new PreprocessJobAction(Input, OutputTy);
760 case phases::Precompile:
761 return new PrecompileJobAction(Input, types::TY_PCH);
762 case phases::Compile: {
763 if (Args.hasArg(options::OPT_fsyntax_only)) {
764 return new CompileJobAction(Input, types::TY_Nothing);
765 } else if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto)) {
766 return new AnalyzeJobAction(Input, types::TY_Plist);
767 } else if (Args.hasArg(options::OPT_emit_llvm) ||
768 Args.hasArg(options::OPT_flto) ||
769 Args.hasArg(options::OPT_O4)) {
771 Args.hasArg(options::OPT_S) ? types::TY_LLVMAsm : types::TY_LLVMBC;
772 return new CompileJobAction(Input, Output);
774 return new CompileJobAction(Input, types::TY_PP_Asm);
777 case phases::Assemble:
778 return new AssembleJobAction(Input, types::TY_Object);
781 assert(0 && "invalid phase in ConstructPhaseAction");
785 void Driver::BuildJobs(Compilation &C) const {
786 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
787 bool SaveTemps = C.getArgs().hasArg(options::OPT_save_temps);
788 bool UsePipes = C.getArgs().hasArg(options::OPT_pipe);
790 // FIXME: Pipes are forcibly disabled until we support executing
792 if (!CCCPrintBindings)
795 // -save-temps inhibits pipes.
796 if (SaveTemps && UsePipes) {
797 Diag(clang::diag::warn_drv_pipe_ignored_with_save_temps);
801 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
803 // It is an error to provide a -o option if we are making multiple
806 unsigned NumOutputs = 0;
807 for (ActionList::const_iterator it = C.getActions().begin(),
808 ie = C.getActions().end(); it != ie; ++it)
809 if ((*it)->getType() != types::TY_Nothing)
812 if (NumOutputs > 1) {
813 Diag(clang::diag::err_drv_output_argument_with_multiple_files);
818 for (ActionList::const_iterator it = C.getActions().begin(),
819 ie = C.getActions().end(); it != ie; ++it) {
822 // If we are linking an image for multiple archs then the linker
823 // wants -arch_multiple and -final_output <final image
824 // name>. Unfortunately, this doesn't fit in cleanly because we
825 // have to pass this information down.
827 // FIXME: This is a hack; find a cleaner way to integrate this
829 const char *LinkingOutput = 0;
830 if (isa<LipoJobAction>(A)) {
832 LinkingOutput = FinalOutput->getValue(C.getArgs());
834 LinkingOutput = DefaultImageName.c_str();
838 BuildJobsForAction(C, A, &C.getDefaultToolChain(),
839 /*CanAcceptPipe*/ true,
841 /*LinkingOutput*/ LinkingOutput,
845 // If the user passed -Qunused-arguments or there were errors, don't
846 // warn about any unused arguments.
847 if (Diags.getNumErrors() ||
848 C.getArgs().hasArg(options::OPT_Qunused_arguments))
852 (void) C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
854 for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end();
858 // FIXME: It would be nice to be able to send the argument to the
859 // Diagnostic, so that extra values, position, and so on could be
861 if (!A->isClaimed()) {
862 if (A->getOption().hasNoArgumentUnused())
865 // Suppress the warning automatically if this is just a flag,
866 // and it is an instance of an argument we already claimed.
867 const Option &Opt = A->getOption();
868 if (isa<FlagOption>(Opt)) {
869 bool DuplicateClaimed = false;
871 // FIXME: Use iterator.
872 for (ArgList::const_iterator it = C.getArgs().begin(),
873 ie = C.getArgs().end(); it != ie; ++it) {
874 if ((*it)->isClaimed() && (*it)->getOption().matches(Opt.getId())) {
875 DuplicateClaimed = true;
880 if (DuplicateClaimed)
884 Diag(clang::diag::warn_drv_unused_argument)
885 << A->getAsString(C.getArgs());
890 void Driver::BuildJobsForAction(Compilation &C,
895 const char *LinkingOutput,
896 InputInfo &Result) const {
897 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs for action");
899 bool UsePipes = C.getArgs().hasArg(options::OPT_pipe);
900 // FIXME: Pipes are forcibly disabled until we support executing
902 if (!CCCPrintBindings)
905 if (const InputAction *IA = dyn_cast<InputAction>(A)) {
906 // FIXME: It would be nice to not claim this here; maybe the old
907 // scheme of just using Args was better?
908 const Arg &Input = IA->getInputArg();
910 if (isa<PositionalArg>(Input)) {
911 const char *Name = Input.getValue(C.getArgs());
912 Result = InputInfo(Name, A->getType(), Name);
914 Result = InputInfo(&Input, A->getType(), "");
918 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
919 const char *ArchName = BAA->getArchName();
922 Arch = C.getDefaultToolChain().getArchName();
923 ArchName = Arch.c_str();
925 BuildJobsForAction(C,
927 Host->getToolChain(C.getArgs(), ArchName),
935 const JobAction *JA = cast<JobAction>(A);
936 const Tool &T = TC->SelectTool(C, *JA);
938 // See if we should use an integrated preprocessor. We do so when we
939 // have exactly one input, since this is the only use case we care
940 // about (irrelevant since we don't support combine yet).
941 bool UseIntegratedCPP = false;
942 const ActionList *Inputs = &A->getInputs();
943 if (Inputs->size() == 1 && isa<PreprocessJobAction>(*Inputs->begin())) {
944 if (!C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
945 !C.getArgs().hasArg(options::OPT_traditional_cpp) &&
946 !C.getArgs().hasArg(options::OPT_save_temps) &&
947 T.hasIntegratedCPP()) {
948 UseIntegratedCPP = true;
949 Inputs = &(*Inputs)[0]->getInputs();
953 // Only use pipes when there is exactly one input.
954 bool TryToUsePipeInput = Inputs->size() == 1 && T.acceptsPipedInput();
955 InputInfoList InputInfos;
956 for (ActionList::const_iterator it = Inputs->begin(), ie = Inputs->end();
959 BuildJobsForAction(C, *it, TC, TryToUsePipeInput,
963 InputInfos.push_back(II);
966 // Determine if we should output to a pipe.
967 bool OutputToPipe = false;
968 if (CanAcceptPipe && T.canPipeOutput()) {
969 // Some actions default to writing to a pipe if they are the top
970 // level phase and there was no user override.
972 // FIXME: Is there a better way to handle this?
974 if (isa<PreprocessJobAction>(A) && !C.getArgs().hasArg(options::OPT_o))
980 // Figure out where to put the job (pipes).
981 Job *Dest = &C.getJobs();
982 if (InputInfos[0].isPipe()) {
983 assert(TryToUsePipeInput && "Unrequested pipe!");
984 assert(InputInfos.size() == 1 && "Unexpected pipe with multiple inputs.");
985 Dest = &InputInfos[0].getPipe();
988 // Always use the first input as the base input.
989 const char *BaseInput = InputInfos[0].getBaseInput();
991 // Determine the place to write output to (nothing, pipe, or
992 // filename) and where to put the new job.
993 if (JA->getType() == types::TY_Nothing) {
994 Result = InputInfo(A->getType(), BaseInput);
995 } else if (OutputToPipe) {
996 // Append to current piped job or create a new one as appropriate.
997 PipedJob *PJ = dyn_cast<PipedJob>(Dest);
1000 // FIXME: Temporary hack so that -ccc-print-bindings work until
1001 // we have pipe support. Please remove later.
1002 if (!CCCPrintBindings)
1003 cast<JobList>(Dest)->addJob(PJ);
1006 Result = InputInfo(PJ, A->getType(), BaseInput);
1008 Result = InputInfo(GetNamedOutputPath(C, *JA, BaseInput, AtTopLevel),
1009 A->getType(), BaseInput);
1012 if (CCCPrintBindings) {
1013 llvm::errs() << "# \"" << T.getToolChain().getTripleString() << '"'
1014 << " - \"" << T.getName() << "\", inputs: [";
1015 for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
1016 llvm::errs() << InputInfos[i].getAsString();
1018 llvm::errs() << ", ";
1020 llvm::errs() << "], output: " << Result.getAsString() << "\n";
1022 T.ConstructJob(C, *JA, *Dest, Result, InputInfos,
1023 C.getArgsForToolChain(TC), LinkingOutput);
1027 const char *Driver::GetNamedOutputPath(Compilation &C,
1028 const JobAction &JA,
1029 const char *BaseInput,
1030 bool AtTopLevel) const {
1031 llvm::PrettyStackTraceString CrashInfo("Computing output path");
1032 // Output to a user requested destination?
1034 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
1035 return C.addResultFile(FinalOutput->getValue(C.getArgs()));
1038 // Output to a temporary file?
1039 if (!AtTopLevel && !C.getArgs().hasArg(options::OPT_save_temps)) {
1040 std::string TmpName =
1041 GetTemporaryPath(types::getTypeTempSuffix(JA.getType()));
1042 return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()));
1045 llvm::sys::Path BasePath(BaseInput);
1046 std::string BaseName(BasePath.getLast());
1048 // Determine what the derived output name should be.
1049 const char *NamedOutput;
1050 if (JA.getType() == types::TY_Image) {
1051 NamedOutput = DefaultImageName.c_str();
1053 const char *Suffix = types::getTypeTempSuffix(JA.getType());
1054 assert(Suffix && "All types used for output should have a suffix.");
1056 std::string::size_type End = std::string::npos;
1057 if (!types::appendSuffixForType(JA.getType()))
1058 End = BaseName.rfind('.');
1059 std::string Suffixed(BaseName.substr(0, End));
1062 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
1065 // As an annoying special case, PCH generation doesn't strip the
1067 if (JA.getType() == types::TY_PCH) {
1068 BasePath.eraseComponent();
1069 if (BasePath.isEmpty())
1070 BasePath = NamedOutput;
1072 BasePath.appendComponent(NamedOutput);
1073 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()));
1075 return C.addResultFile(NamedOutput);
1079 llvm::sys::Path Driver::GetFilePath(const char *Name,
1080 const ToolChain &TC) const {
1081 const ToolChain::path_list &List = TC.getFilePaths();
1082 for (ToolChain::path_list::const_iterator
1083 it = List.begin(), ie = List.end(); it != ie; ++it) {
1084 llvm::sys::Path P(*it);
1085 P.appendComponent(Name);
1090 return llvm::sys::Path(Name);
1093 llvm::sys::Path Driver::GetProgramPath(const char *Name,
1094 const ToolChain &TC,
1095 bool WantFile) const {
1096 const ToolChain::path_list &List = TC.getProgramPaths();
1097 for (ToolChain::path_list::const_iterator
1098 it = List.begin(), ie = List.end(); it != ie; ++it) {
1099 llvm::sys::Path P(*it);
1100 P.appendComponent(Name);
1101 if (WantFile ? P.exists() : P.canExecute())
1105 // If all else failed, search the path.
1106 llvm::sys::Path P(llvm::sys::Program::FindProgramByName(Name));
1110 return llvm::sys::Path(Name);
1113 std::string Driver::GetTemporaryPath(const char *Suffix) const {
1114 // FIXME: This is lame; sys::Path should provide this function (in
1115 // particular, it should know how to find the temporary files dir).
1117 const char *TmpDir = ::getenv("TMPDIR");
1119 TmpDir = ::getenv("TEMP");
1121 TmpDir = ::getenv("TMP");
1124 llvm::sys::Path P(TmpDir);
1125 P.appendComponent("cc");
1126 if (P.makeUnique(false, &Error)) {
1127 Diag(clang::diag::err_drv_unable_to_make_temp) << Error;
1131 // FIXME: Grumble, makeUnique sometimes leaves the file around!?
1133 P.eraseFromDisk(false, 0);
1135 P.appendSuffix(Suffix);
1136 return P.toString();
1139 const HostInfo *Driver::GetHostInfo(const char *TripleStr) const {
1140 llvm::PrettyStackTraceString CrashInfo("Constructing host");
1141 llvm::Triple Triple(TripleStr);
1143 // Normalize Arch a bit.
1145 // FIXME: We shouldn't need to do this once everything goes through the triple
1147 if (Triple.getArchName() == "i686")
1148 Triple.setArchName("i386");
1149 else if (Triple.getArchName() == "amd64")
1150 Triple.setArchName("x86_64");
1151 else if (Triple.getArchName() == "ppc" ||
1152 Triple.getArchName() == "Power Macintosh")
1153 Triple.setArchName("powerpc");
1154 else if (Triple.getArchName() == "ppc64")
1155 Triple.setArchName("powerpc64");
1157 switch (Triple.getOS()) {
1158 case llvm::Triple::Darwin:
1159 return createDarwinHostInfo(*this, Triple);
1160 case llvm::Triple::DragonFly:
1161 return createDragonFlyHostInfo(*this, Triple);
1162 case llvm::Triple::FreeBSD:
1163 return createFreeBSDHostInfo(*this, Triple);
1164 case llvm::Triple::Linux:
1165 return createLinuxHostInfo(*this, Triple);
1167 return createUnknownHostInfo(*this, Triple);
1171 bool Driver::ShouldUseClangCompiler(const Compilation &C, const JobAction &JA,
1172 const std::string &ArchNameStr) const {
1173 // FIXME: Remove this hack.
1174 const char *ArchName = ArchNameStr.c_str();
1175 if (ArchNameStr == "powerpc")
1177 else if (ArchNameStr == "powerpc64")
1180 // Check if user requested no clang, or clang doesn't understand
1181 // this type (we only handle single inputs for now).
1182 if (!CCCUseClang || JA.size() != 1 ||
1183 !types::isAcceptedByClang((*JA.begin())->getType()))
1186 // Otherwise make sure this is an action clang understands.
1187 if (isa<PreprocessJobAction>(JA)) {
1188 if (!CCCUseClangCPP) {
1189 Diag(clang::diag::warn_drv_not_using_clang_cpp);
1192 } else if (!isa<PrecompileJobAction>(JA) && !isa<CompileJobAction>(JA))
1195 // Use clang for C++?
1196 if (!CCCUseClangCXX && types::isCXX((*JA.begin())->getType())) {
1197 Diag(clang::diag::warn_drv_not_using_clang_cxx);
1201 // Always use clang for precompiling, regardless of archs. PTH is
1202 // platform independent, and this allows the use of the static
1203 // analyzer on platforms we don't have full IRgen support for.
1204 if (isa<PrecompileJobAction>(JA))
1207 // Finally, don't use clang if this isn't one of the user specified
1209 if (!CCCClangArchs.empty() && !CCCClangArchs.count(ArchName)) {
1210 Diag(clang::diag::warn_drv_not_using_clang_arch) << ArchName;
1217 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and
1218 /// return the grouped values as integers. Numbers which are not
1219 /// provided are set to 0.
1221 /// \return True if the entire string was parsed (9.2), or all groups
1222 /// were parsed (10.3.5extrastuff).
1223 bool Driver::GetReleaseVersion(const char *Str, unsigned &Major,
1224 unsigned &Minor, unsigned &Micro,
1228 Major = Minor = Micro = 0;
1233 Major = (unsigned) strtol(Str, &End, 10);
1234 if (*Str != '\0' && *End == '\0')
1240 Minor = (unsigned) strtol(Str, &End, 10);
1241 if (*Str != '\0' && *End == '\0')
1247 Micro = (unsigned) strtol(Str, &End, 10);
1248 if (*Str != '\0' && *End == '\0')