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 int Driver::ExecuteCompilation(const Compilation
&C
) const {
221 // Just print if -### was present.
222 if (C
.getArgs().hasArg(options::OPT__HASH_HASH_HASH
)) {
223 C
.PrintJob(llvm::errs(), C
.getJobs(), "\n", true);
227 // If there were errors building the compilation, quit now.
228 if (getDiags().getNumErrors())
231 const Command
*FailingCommand
= 0;
232 int Res
= C
.ExecuteJob(C
.getJobs(), FailingCommand
);
234 // Remove temp files.
235 C
.CleanupFileList(C
.getTempFiles());
237 // If the compilation failed, remove result files as well.
238 if (Res
!= 0 && !C
.getArgs().hasArg(options::OPT_save_temps
))
239 C
.CleanupFileList(C
.getResultFiles(), true);
241 // Print extra information about abnormal failures, if possible.
243 // This is ad-hoc, but we don't want to be excessively noisy. If the result
244 // status was 1, assume the command failed normally. In particular, if it
245 // was the compiler then assume it gave a reasonable error code. Failures in
246 // other tools are less common, and they generally have worse diagnostics,
247 // so always print the diagnostic there.
248 const Action
&Source
= FailingCommand
->getSource();
249 bool IsFriendlyTool
= (isa
<PreprocessJobAction
>(Source
) ||
250 isa
<PrecompileJobAction
>(Source
) ||
251 isa
<AnalyzeJobAction
>(Source
) ||
252 isa
<CompileJobAction
>(Source
));
254 if (!IsFriendlyTool
|| Res
!= 1) {
255 // FIXME: See FIXME above regarding result code interpretation.
257 Diag(clang::diag::err_drv_command_signalled
)
258 << Source
.getClassName() << -Res
;
260 Diag(clang::diag::err_drv_command_failed
)
261 << Source
.getClassName() << Res
;
268 void Driver::PrintOptions(const ArgList
&Args
) const {
270 for (ArgList::const_iterator it
= Args
.begin(), ie
= Args
.end();
271 it
!= ie
; ++it
, ++i
) {
273 llvm::errs() << "Option " << i
<< " - "
274 << "Name: \"" << A
->getOption().getName() << "\", "
276 for (unsigned j
= 0; j
< A
->getNumValues(); ++j
) {
278 llvm::errs() << ", ";
279 llvm::errs() << '"' << A
->getValue(Args
, j
) << '"';
281 llvm::errs() << "}\n";
285 static std::string
getOptionHelpName(const OptTable
&Opts
, options::ID Id
) {
286 std::string Name
= Opts
.getOptionName(Id
);
288 // Add metavar, if used.
289 switch (Opts
.getOptionKind(Id
)) {
290 case Option::GroupClass
: case Option::InputClass
: case Option::UnknownClass
:
291 assert(0 && "Invalid option with help text.");
293 case Option::MultiArgClass
: case Option::JoinedAndSeparateClass
:
294 assert(0 && "Cannot print metavar for this kind of option.");
296 case Option::FlagClass
:
299 case Option::SeparateClass
: case Option::JoinedOrSeparateClass
:
302 case Option::JoinedClass
: case Option::CommaJoinedClass
:
303 Name
+= Opts
.getOptionMetaVar(Id
);
310 void Driver::PrintHelp(bool ShowHidden
) const {
311 llvm::raw_ostream
&OS
= llvm::outs();
313 OS
<< "OVERVIEW: clang \"gcc-compatible\" driver\n";
315 OS
<< "USAGE: " << Name
<< " [options] <input files>\n";
319 // Render help text into (option, help) pairs.
320 std::vector
< std::pair
<std::string
, const char*> > OptionHelp
;
322 for (unsigned i
= options::OPT_INPUT
, e
= options::LastOption
; i
!= e
; ++i
) {
323 options::ID Id
= (options::ID
) i
;
324 if (const char *Text
= getOpts().getOptionHelpText(Id
))
325 OptionHelp
.push_back(std::make_pair(getOptionHelpName(getOpts(), Id
),
330 OptionHelp
.push_back(std::make_pair("\nDRIVER OPTIONS:",""));
331 OptionHelp
.push_back(std::make_pair("-ccc-cxx",
332 "Act as a C++ driver"));
333 OptionHelp
.push_back(std::make_pair("-ccc-gcc-name",
334 "Name for native GCC compiler"));
335 OptionHelp
.push_back(std::make_pair("-ccc-clang-cxx",
336 "Use the clang compiler for C++"));
337 OptionHelp
.push_back(std::make_pair("-ccc-no-clang",
338 "Never use the clang compiler"));
339 OptionHelp
.push_back(std::make_pair("-ccc-no-clang-cpp",
340 "Never use the clang preprocessor"));
341 OptionHelp
.push_back(std::make_pair("-ccc-clang-archs",
342 "Comma separate list of architectures "
343 "to use the clang compiler for"));
344 OptionHelp
.push_back(std::make_pair("-ccc-pch-is-pch",
345 "Use lazy PCH for precompiled headers"));
346 OptionHelp
.push_back(std::make_pair("-ccc-pch-is-pth",
347 "Use pretokenized headers for precompiled headers"));
349 OptionHelp
.push_back(std::make_pair("\nDEBUG/DEVELOPMENT OPTIONS:",""));
350 OptionHelp
.push_back(std::make_pair("-ccc-host-triple",
351 "Simulate running on the given target"));
352 OptionHelp
.push_back(std::make_pair("-ccc-print-options",
353 "Dump parsed command line arguments"));
354 OptionHelp
.push_back(std::make_pair("-ccc-print-phases",
355 "Dump list of actions to perform"));
356 OptionHelp
.push_back(std::make_pair("-ccc-print-bindings",
357 "Show bindings of tools to actions"));
358 OptionHelp
.push_back(std::make_pair("CCC_ADD_ARGS",
359 "(ENVIRONMENT VARIABLE) Comma separated list of "
360 "arguments to prepend to the command line"));
363 // Find the maximum option length.
364 unsigned OptionFieldWidth
= 0;
365 for (unsigned i
= 0, e
= OptionHelp
.size(); i
!= e
; ++i
) {
367 if (!OptionHelp
[i
].second
)
370 // Limit the amount of padding we are willing to give up for
372 unsigned Length
= OptionHelp
[i
].first
.size();
374 OptionFieldWidth
= std::max(OptionFieldWidth
, Length
);
377 for (unsigned i
= 0, e
= OptionHelp
.size(); i
!= e
; ++i
) {
378 const std::string
&Option
= OptionHelp
[i
].first
;
380 for (int j
= Option
.length(), e
= OptionFieldWidth
; j
< e
; ++j
)
382 OS
<< ' ' << OptionHelp
[i
].second
<< '\n';
388 void Driver::PrintVersion(const Compilation
&C
) const {
389 static char buf
[] = "$URL$";
390 char *zap
= strstr(buf
, "/lib/Driver");
393 zap
= strstr(buf
, "/clang/tools/clang");
396 const char *vers
= buf
+6;
397 // FIXME: Add cmake support and remove #ifdef
399 const char *revision
= SVN_REVISION
;
401 const char *revision
= "";
403 // FIXME: The following handlers should use a callback mechanism, we
404 // don't know what the client would like to do.
406 llvm::errs() << "clang version " CLANG_VERSION_STRING
" ("
407 << vers
<< " " << revision
<< ")" << '\n';
409 const ToolChain
&TC
= C
.getDefaultToolChain();
410 llvm::errs() << "Target: " << TC
.getTripleString() << '\n';
412 // Print the threading model.
414 // FIXME: Implement correctly.
415 llvm::errs() << "Thread model: " << "posix" << '\n';
418 bool Driver::HandleImmediateArgs(const Compilation
&C
) {
419 // The order these options are handled in in gcc is all over the
420 // place, but we don't expect inconsistencies w.r.t. that to matter
423 if (C
.getArgs().hasArg(options::OPT_dumpversion
)) {
424 llvm::outs() << CLANG_VERSION_STRING
"\n";
428 if (C
.getArgs().hasArg(options::OPT__help
) ||
429 C
.getArgs().hasArg(options::OPT__help_hidden
)) {
430 PrintHelp(C
.getArgs().hasArg(options::OPT__help_hidden
));
434 if (C
.getArgs().hasArg(options::OPT__version
)) {
439 if (C
.getArgs().hasArg(options::OPT_v
) ||
440 C
.getArgs().hasArg(options::OPT__HASH_HASH_HASH
)) {
442 SuppressMissingInputWarning
= true;
445 const ToolChain
&TC
= C
.getDefaultToolChain();
446 if (C
.getArgs().hasArg(options::OPT_print_search_dirs
)) {
447 llvm::outs() << "programs: =";
448 for (ToolChain::path_list::const_iterator it
= TC
.getProgramPaths().begin(),
449 ie
= TC
.getProgramPaths().end(); it
!= ie
; ++it
) {
450 if (it
!= TC
.getProgramPaths().begin())
454 llvm::outs() << "\n";
455 llvm::outs() << "libraries: =";
456 for (ToolChain::path_list::const_iterator it
= TC
.getFilePaths().begin(),
457 ie
= TC
.getFilePaths().end(); it
!= ie
; ++it
) {
458 if (it
!= TC
.getFilePaths().begin())
462 llvm::outs() << "\n";
466 // FIXME: The following handlers should use a callback mechanism, we
467 // don't know what the client would like to do.
468 if (Arg
*A
= C
.getArgs().getLastArg(options::OPT_print_file_name_EQ
)) {
469 llvm::outs() << GetFilePath(A
->getValue(C
.getArgs()), TC
).toString()
474 if (Arg
*A
= C
.getArgs().getLastArg(options::OPT_print_prog_name_EQ
)) {
475 llvm::outs() << GetProgramPath(A
->getValue(C
.getArgs()), TC
).toString()
480 if (C
.getArgs().hasArg(options::OPT_print_libgcc_file_name
)) {
481 llvm::outs() << GetFilePath("libgcc.a", TC
).toString() << "\n";
485 if (C
.getArgs().hasArg(options::OPT_print_multi_lib
)) {
486 // FIXME: We need tool chain support for this.
487 llvm::outs() << ".;\n";
489 switch (C
.getDefaultToolChain().getTriple().getArch()) {
493 case llvm::Triple::x86_64
:
494 llvm::outs() << "x86_64;@m64" << "\n";
497 case llvm::Triple::ppc64
:
498 llvm::outs() << "ppc64;@m64" << "\n";
504 // FIXME: What is the difference between print-multi-directory and
505 // print-multi-os-directory?
506 if (C
.getArgs().hasArg(options::OPT_print_multi_directory
) ||
507 C
.getArgs().hasArg(options::OPT_print_multi_os_directory
)) {
508 switch (C
.getDefaultToolChain().getTriple().getArch()) {
510 case llvm::Triple::x86
:
511 case llvm::Triple::ppc
:
512 llvm::outs() << "." << "\n";
515 case llvm::Triple::x86_64
:
516 llvm::outs() << "x86_64" << "\n";
519 case llvm::Triple::ppc64
:
520 llvm::outs() << "ppc64" << "\n";
529 static unsigned PrintActions1(const Compilation
&C
,
531 std::map
<Action
*, unsigned> &Ids
) {
536 llvm::raw_string_ostream
os(str
);
538 os
<< Action::getClassName(A
->getKind()) << ", ";
539 if (InputAction
*IA
= dyn_cast
<InputAction
>(A
)) {
540 os
<< "\"" << IA
->getInputArg().getValue(C
.getArgs()) << "\"";
541 } else if (BindArchAction
*BIA
= dyn_cast
<BindArchAction
>(A
)) {
542 os
<< '"' << (BIA
->getArchName() ? BIA
->getArchName() :
543 C
.getDefaultToolChain().getArchName()) << '"'
544 << ", {" << PrintActions1(C
, *BIA
->begin(), Ids
) << "}";
547 for (Action::iterator it
= A
->begin(), ie
= A
->end(); it
!= ie
;) {
548 os
<< PrintActions1(C
, *it
, Ids
);
556 unsigned Id
= Ids
.size();
558 llvm::errs() << Id
<< ": " << os
.str() << ", "
559 << types::getTypeName(A
->getType()) << "\n";
564 void Driver::PrintActions(const Compilation
&C
) const {
565 std::map
<Action
*, unsigned> Ids
;
566 for (ActionList::const_iterator it
= C
.getActions().begin(),
567 ie
= C
.getActions().end(); it
!= ie
; ++it
)
568 PrintActions1(C
, *it
, Ids
);
571 void Driver::BuildUniversalActions(const ArgList
&Args
,
572 ActionList
&Actions
) const {
573 llvm::PrettyStackTraceString
CrashInfo("Building actions for universal build");
574 // Collect the list of architectures. Duplicates are allowed, but
575 // should only be handled once (in the order seen).
576 llvm::StringSet
<> ArchNames
;
577 llvm::SmallVector
<const char *, 4> Archs
;
578 for (ArgList::const_iterator it
= Args
.begin(), ie
= Args
.end();
582 if (A
->getOption().getId() == options::OPT_arch
) {
583 const char *Name
= A
->getValue(Args
);
585 // FIXME: We need to handle canonicalization of the specified
589 if (ArchNames
.insert(Name
))
590 Archs
.push_back(Name
);
594 // When there is no explicit arch for this platform, make sure we
595 // still bind the architecture (to the default) so that -Xarch_ is
596 // handled correctly.
600 // FIXME: We killed off some others but these aren't yet detected in
601 // a functional manner. If we added information to jobs about which
602 // "auxiliary" files they wrote then we could detect the conflict
603 // these cause downstream.
604 if (Archs
.size() > 1) {
605 // No recovery needed, the point of this is just to prevent
606 // overwriting the same files.
607 if (const Arg
*A
= Args
.getLastArg(options::OPT_save_temps
))
608 Diag(clang::diag::err_drv_invalid_opt_with_multiple_archs
)
609 << A
->getAsString(Args
);
612 ActionList SingleActions
;
613 BuildActions(Args
, SingleActions
);
615 // Add in arch binding and lipo (if necessary) for every top level
617 for (unsigned i
= 0, e
= SingleActions
.size(); i
!= e
; ++i
) {
618 Action
*Act
= SingleActions
[i
];
620 // Make sure we can lipo this kind of output. If not (and it is an
621 // actual output) then we disallow, since we can't create an
622 // output file with the right name without overwriting it. We
623 // could remove this oddity by just changing the output names to
624 // include the arch, which would also fix
625 // -save-temps. Compatibility wins for now.
627 if (Archs
.size() > 1 && !types::canLipoType(Act
->getType()))
628 Diag(clang::diag::err_drv_invalid_output_with_multiple_archs
)
629 << types::getTypeName(Act
->getType());
632 for (unsigned i
= 0, e
= Archs
.size(); i
!= e
; ++i
)
633 Inputs
.push_back(new BindArchAction(Act
, Archs
[i
]));
635 // Lipo if necessary, We do it this way because we need to set the
636 // arch flag so that -Xarch_ gets overwritten.
637 if (Inputs
.size() == 1 || Act
->getType() == types::TY_Nothing
)
638 Actions
.append(Inputs
.begin(), Inputs
.end());
640 Actions
.push_back(new LipoJobAction(Inputs
, Act
->getType()));
644 void Driver::BuildActions(const ArgList
&Args
, ActionList
&Actions
) const {
645 llvm::PrettyStackTraceString
CrashInfo("Building compilation actions");
646 // Start by constructing the list of inputs and their types.
648 // Track the current user specified (-x) input. We also explicitly
649 // track the argument used to set the type; we only want to claim
650 // the type when we actually use it, so we warn about unused -x
652 types::ID InputType
= types::TY_Nothing
;
653 Arg
*InputTypeArg
= 0;
655 llvm::SmallVector
<std::pair
<types::ID
, const Arg
*>, 16> Inputs
;
656 for (ArgList::const_iterator it
= Args
.begin(), ie
= Args
.end();
660 if (isa
<InputOption
>(A
->getOption())) {
661 const char *Value
= A
->getValue(Args
);
662 types::ID Ty
= types::TY_INVALID
;
664 // Infer the input type if necessary.
665 if (InputType
== types::TY_Nothing
) {
666 // If there was an explicit arg for this, claim it.
668 InputTypeArg
->claim();
670 // stdin must be handled specially.
671 if (memcmp(Value
, "-", 2) == 0) {
672 // If running with -E, treat as a C input (this changes the
673 // builtin macros, for example). This may be overridden by
676 // Otherwise emit an error but still use a valid type to
677 // avoid spurious errors (e.g., no inputs).
678 if (!Args
.hasArg(options::OPT_E
, false))
679 Diag(clang::diag::err_drv_unknown_stdin_type
);
682 // Otherwise lookup by extension, and fallback to ObjectType
683 // if not found. We use a host hook here because Darwin at
684 // least has its own idea of what .s is.
685 if (const char *Ext
= strrchr(Value
, '.'))
686 Ty
= Host
->lookupTypeForExtension(Ext
+ 1);
688 if (Ty
== types::TY_INVALID
)
689 Ty
= types::TY_Object
;
692 // -ObjC and -ObjC++ override the default language, but only for "source
693 // files". We just treat everything that isn't a linker input as a
696 // FIXME: Clean this up if we move the phase sequence into the type.
697 if (Ty
!= types::TY_Object
) {
698 if (Args
.hasArg(options::OPT_ObjC
))
700 else if (Args
.hasArg(options::OPT_ObjCXX
))
701 Ty
= types::TY_ObjCXX
;
704 assert(InputTypeArg
&& "InputType set w/o InputTypeArg");
705 InputTypeArg
->claim();
709 // Check that the file exists. It isn't clear this is worth
710 // doing, since the tool presumably does this anyway, and this
711 // just adds an extra stat to the equation, but this is gcc
713 if (memcmp(Value
, "-", 2) != 0 && !llvm::sys::Path(Value
).exists())
714 Diag(clang::diag::err_drv_no_such_file
) << A
->getValue(Args
);
716 Inputs
.push_back(std::make_pair(Ty
, A
));
718 } else if (A
->getOption().isLinkerInput()) {
719 // Just treat as object type, we could make a special type for
720 // this if necessary.
721 Inputs
.push_back(std::make_pair(types::TY_Object
, A
));
723 } else if (A
->getOption().getId() == options::OPT_x
) {
725 InputType
= types::lookupTypeForTypeSpecifier(A
->getValue(Args
));
727 // Follow gcc behavior and treat as linker input for invalid -x
728 // options. Its not clear why we shouldn't just revert to
729 // unknown; but this isn't very important, we might as well be
732 Diag(clang::diag::err_drv_unknown_language
) << A
->getValue(Args
);
733 InputType
= types::TY_Object
;
738 if (!SuppressMissingInputWarning
&& Inputs
.empty()) {
739 Diag(clang::diag::err_drv_no_input_files
);
743 // Determine which compilation mode we are in. We look for options
744 // which affect the phase, starting with the earliest phases, and
745 // record which option we used to determine the final phase.
746 Arg
*FinalPhaseArg
= 0;
747 phases::ID FinalPhase
;
749 // -{E,M,MM} only run the preprocessor.
750 if ((FinalPhaseArg
= Args
.getLastArg(options::OPT_E
)) ||
751 (FinalPhaseArg
= Args
.getLastArg(options::OPT_M
)) ||
752 (FinalPhaseArg
= Args
.getLastArg(options::OPT_MM
))) {
753 FinalPhase
= phases::Preprocess
;
755 // -{fsyntax-only,-analyze,emit-llvm,S} only run up to the compiler.
756 } else if ((FinalPhaseArg
= Args
.getLastArg(options::OPT_fsyntax_only
)) ||
757 (FinalPhaseArg
= Args
.getLastArg(options::OPT__analyze
,
758 options::OPT__analyze_auto
)) ||
759 (FinalPhaseArg
= Args
.getLastArg(options::OPT_S
))) {
760 FinalPhase
= phases::Compile
;
762 // -c only runs up to the assembler.
763 } else if ((FinalPhaseArg
= Args
.getLastArg(options::OPT_c
))) {
764 FinalPhase
= phases::Assemble
;
766 // Otherwise do everything.
768 FinalPhase
= phases::Link
;
770 // Reject -Z* at the top level, these options should never have been
772 if (Arg
*A
= Args
.getLastArg(options::OPT_Z_Joined
))
773 Diag(clang::diag::err_drv_use_of_Z_option
) << A
->getAsString(Args
);
775 // Construct the actions to perform.
776 ActionList LinkerInputs
;
777 for (unsigned i
= 0, e
= Inputs
.size(); i
!= e
; ++i
) {
778 types::ID InputType
= Inputs
[i
].first
;
779 const Arg
*InputArg
= Inputs
[i
].second
;
781 unsigned NumSteps
= types::getNumCompilationPhases(InputType
);
782 assert(NumSteps
&& "Invalid number of steps!");
784 // If the first step comes after the final phase we are doing as
785 // part of this compilation, warn the user about it.
786 phases::ID InitialPhase
= types::getCompilationPhase(InputType
, 0);
787 if (InitialPhase
> FinalPhase
) {
788 // Claim here to avoid the more general unused warning.
790 Diag(clang::diag::warn_drv_input_file_unused
)
791 << InputArg
->getAsString(Args
)
792 << getPhaseName(InitialPhase
)
793 << FinalPhaseArg
->getOption().getName();
797 // Build the pipeline for this file.
798 Action
*Current
= new InputAction(*InputArg
, InputType
);
799 for (unsigned i
= 0; i
!= NumSteps
; ++i
) {
800 phases::ID Phase
= types::getCompilationPhase(InputType
, i
);
802 // We are done if this step is past what the user requested.
803 if (Phase
> FinalPhase
)
806 // Queue linker inputs.
807 if (Phase
== phases::Link
) {
808 assert(i
+ 1 == NumSteps
&& "linking must be final compilation step.");
809 LinkerInputs
.push_back(Current
);
814 // Some types skip the assembler phase (e.g., llvm-bc), but we
815 // can't encode this in the steps because the intermediate type
816 // depends on arguments. Just special case here.
817 if (Phase
== phases::Assemble
&& Current
->getType() != types::TY_PP_Asm
)
820 // Otherwise construct the appropriate action.
821 Current
= ConstructPhaseAction(Args
, Phase
, Current
);
822 if (Current
->getType() == types::TY_Nothing
)
826 // If we ended with something, add to the output list.
828 Actions
.push_back(Current
);
831 // Add a link action if necessary.
832 if (!LinkerInputs
.empty())
833 Actions
.push_back(new LinkJobAction(LinkerInputs
, types::TY_Image
));
836 Action
*Driver::ConstructPhaseAction(const ArgList
&Args
, phases::ID Phase
,
837 Action
*Input
) const {
838 llvm::PrettyStackTraceString
CrashInfo("Constructing phase actions");
839 // Build the appropriate action.
841 case phases::Link
: assert(0 && "link action invalid here.");
842 case phases::Preprocess
: {
844 // -{M, MM} alter the output type.
845 if (Args
.hasArg(options::OPT_M
) || Args
.hasArg(options::OPT_MM
)) {
846 OutputTy
= types::TY_Dependencies
;
848 OutputTy
= types::getPreprocessedType(Input
->getType());
849 assert(OutputTy
!= types::TY_INVALID
&&
850 "Cannot preprocess this input type!");
852 return new PreprocessJobAction(Input
, OutputTy
);
854 case phases::Precompile
:
855 return new PrecompileJobAction(Input
, types::TY_PCH
);
856 case phases::Compile
: {
857 if (Args
.hasArg(options::OPT_fsyntax_only
)) {
858 return new CompileJobAction(Input
, types::TY_Nothing
);
859 } else if (Args
.hasArg(options::OPT__analyze
, options::OPT__analyze_auto
)) {
860 return new AnalyzeJobAction(Input
, types::TY_Plist
);
861 } else if (Args
.hasArg(options::OPT_emit_llvm
) ||
862 Args
.hasArg(options::OPT_flto
) ||
863 Args
.hasArg(options::OPT_O4
)) {
865 Args
.hasArg(options::OPT_S
) ? types::TY_LLVMAsm
: types::TY_LLVMBC
;
866 return new CompileJobAction(Input
, Output
);
868 return new CompileJobAction(Input
, types::TY_PP_Asm
);
871 case phases::Assemble
:
872 return new AssembleJobAction(Input
, types::TY_Object
);
875 assert(0 && "invalid phase in ConstructPhaseAction");
879 void Driver::BuildJobs(Compilation
&C
) const {
880 llvm::PrettyStackTraceString
CrashInfo("Building compilation jobs");
881 bool SaveTemps
= C
.getArgs().hasArg(options::OPT_save_temps
);
882 bool UsePipes
= C
.getArgs().hasArg(options::OPT_pipe
);
884 // FIXME: Pipes are forcibly disabled until we support executing
886 if (!CCCPrintBindings
)
889 // -save-temps inhibits pipes.
890 if (SaveTemps
&& UsePipes
) {
891 Diag(clang::diag::warn_drv_pipe_ignored_with_save_temps
);
895 Arg
*FinalOutput
= C
.getArgs().getLastArg(options::OPT_o
);
897 // It is an error to provide a -o option if we are making multiple
900 unsigned NumOutputs
= 0;
901 for (ActionList::const_iterator it
= C
.getActions().begin(),
902 ie
= C
.getActions().end(); it
!= ie
; ++it
)
903 if ((*it
)->getType() != types::TY_Nothing
)
906 if (NumOutputs
> 1) {
907 Diag(clang::diag::err_drv_output_argument_with_multiple_files
);
912 for (ActionList::const_iterator it
= C
.getActions().begin(),
913 ie
= C
.getActions().end(); it
!= ie
; ++it
) {
916 // If we are linking an image for multiple archs then the linker
917 // wants -arch_multiple and -final_output <final image
918 // name>. Unfortunately, this doesn't fit in cleanly because we
919 // have to pass this information down.
921 // FIXME: This is a hack; find a cleaner way to integrate this
923 const char *LinkingOutput
= 0;
924 if (isa
<LipoJobAction
>(A
)) {
926 LinkingOutput
= FinalOutput
->getValue(C
.getArgs());
928 LinkingOutput
= DefaultImageName
.c_str();
932 BuildJobsForAction(C
, A
, &C
.getDefaultToolChain(),
933 /*CanAcceptPipe*/ true,
935 /*LinkingOutput*/ LinkingOutput
,
939 // If the user passed -Qunused-arguments or there were errors, don't
940 // warn about any unused arguments.
941 if (Diags
.getNumErrors() ||
942 C
.getArgs().hasArg(options::OPT_Qunused_arguments
))
946 (void) C
.getArgs().hasArg(options::OPT__HASH_HASH_HASH
);
948 for (ArgList::const_iterator it
= C
.getArgs().begin(), ie
= C
.getArgs().end();
952 // FIXME: It would be nice to be able to send the argument to the
953 // Diagnostic, so that extra values, position, and so on could be
955 if (!A
->isClaimed()) {
956 if (A
->getOption().hasNoArgumentUnused())
959 // Suppress the warning automatically if this is just a flag,
960 // and it is an instance of an argument we already claimed.
961 const Option
&Opt
= A
->getOption();
962 if (isa
<FlagOption
>(Opt
)) {
963 bool DuplicateClaimed
= false;
965 // FIXME: Use iterator.
966 for (ArgList::const_iterator it
= C
.getArgs().begin(),
967 ie
= C
.getArgs().end(); it
!= ie
; ++it
) {
968 if ((*it
)->isClaimed() && (*it
)->getOption().matches(Opt
.getId())) {
969 DuplicateClaimed
= true;
974 if (DuplicateClaimed
)
978 Diag(clang::diag::warn_drv_unused_argument
)
979 << A
->getAsString(C
.getArgs());
984 void Driver::BuildJobsForAction(Compilation
&C
,
989 const char *LinkingOutput
,
990 InputInfo
&Result
) const {
991 llvm::PrettyStackTraceString
CrashInfo("Building compilation jobs for action");
993 bool UsePipes
= C
.getArgs().hasArg(options::OPT_pipe
);
994 // FIXME: Pipes are forcibly disabled until we support executing
996 if (!CCCPrintBindings
)
999 if (const InputAction
*IA
= dyn_cast
<InputAction
>(A
)) {
1000 // FIXME: It would be nice to not claim this here; maybe the old
1001 // scheme of just using Args was better?
1002 const Arg
&Input
= IA
->getInputArg();
1004 if (isa
<PositionalArg
>(Input
)) {
1005 const char *Name
= Input
.getValue(C
.getArgs());
1006 Result
= InputInfo(Name
, A
->getType(), Name
);
1008 Result
= InputInfo(&Input
, A
->getType(), "");
1012 if (const BindArchAction
*BAA
= dyn_cast
<BindArchAction
>(A
)) {
1013 const char *ArchName
= BAA
->getArchName();
1016 Arch
= C
.getDefaultToolChain().getArchName();
1017 ArchName
= Arch
.c_str();
1019 BuildJobsForAction(C
,
1021 Host
->getToolChain(C
.getArgs(), ArchName
),
1029 const JobAction
*JA
= cast
<JobAction
>(A
);
1030 const Tool
&T
= TC
->SelectTool(C
, *JA
);
1032 // See if we should use an integrated preprocessor. We do so when we
1033 // have exactly one input, since this is the only use case we care
1034 // about (irrelevant since we don't support combine yet).
1035 bool UseIntegratedCPP
= false;
1036 const ActionList
*Inputs
= &A
->getInputs();
1037 if (Inputs
->size() == 1 && isa
<PreprocessJobAction
>(*Inputs
->begin())) {
1038 if (!C
.getArgs().hasArg(options::OPT_no_integrated_cpp
) &&
1039 !C
.getArgs().hasArg(options::OPT_traditional_cpp
) &&
1040 !C
.getArgs().hasArg(options::OPT_save_temps
) &&
1041 T
.hasIntegratedCPP()) {
1042 UseIntegratedCPP
= true;
1043 Inputs
= &(*Inputs
)[0]->getInputs();
1047 // Only use pipes when there is exactly one input.
1048 bool TryToUsePipeInput
= Inputs
->size() == 1 && T
.acceptsPipedInput();
1049 InputInfoList InputInfos
;
1050 for (ActionList::const_iterator it
= Inputs
->begin(), ie
= Inputs
->end();
1053 BuildJobsForAction(C
, *it
, TC
, TryToUsePipeInput
,
1054 /*AtTopLevel*/false,
1057 InputInfos
.push_back(II
);
1060 // Determine if we should output to a pipe.
1061 bool OutputToPipe
= false;
1062 if (CanAcceptPipe
&& T
.canPipeOutput()) {
1063 // Some actions default to writing to a pipe if they are the top
1064 // level phase and there was no user override.
1066 // FIXME: Is there a better way to handle this?
1068 if (isa
<PreprocessJobAction
>(A
) && !C
.getArgs().hasArg(options::OPT_o
))
1069 OutputToPipe
= true;
1070 } else if (UsePipes
)
1071 OutputToPipe
= true;
1074 // Figure out where to put the job (pipes).
1075 Job
*Dest
= &C
.getJobs();
1076 if (InputInfos
[0].isPipe()) {
1077 assert(TryToUsePipeInput
&& "Unrequested pipe!");
1078 assert(InputInfos
.size() == 1 && "Unexpected pipe with multiple inputs.");
1079 Dest
= &InputInfos
[0].getPipe();
1082 // Always use the first input as the base input.
1083 const char *BaseInput
= InputInfos
[0].getBaseInput();
1085 // Determine the place to write output to (nothing, pipe, or
1086 // filename) and where to put the new job.
1087 if (JA
->getType() == types::TY_Nothing
) {
1088 Result
= InputInfo(A
->getType(), BaseInput
);
1089 } else if (OutputToPipe
) {
1090 // Append to current piped job or create a new one as appropriate.
1091 PipedJob
*PJ
= dyn_cast
<PipedJob
>(Dest
);
1093 PJ
= new PipedJob();
1094 // FIXME: Temporary hack so that -ccc-print-bindings work until
1095 // we have pipe support. Please remove later.
1096 if (!CCCPrintBindings
)
1097 cast
<JobList
>(Dest
)->addJob(PJ
);
1100 Result
= InputInfo(PJ
, A
->getType(), BaseInput
);
1102 Result
= InputInfo(GetNamedOutputPath(C
, *JA
, BaseInput
, AtTopLevel
),
1103 A
->getType(), BaseInput
);
1106 if (CCCPrintBindings
) {
1107 llvm::errs() << "# \"" << T
.getToolChain().getTripleString() << '"'
1108 << " - \"" << T
.getName() << "\", inputs: [";
1109 for (unsigned i
= 0, e
= InputInfos
.size(); i
!= e
; ++i
) {
1110 llvm::errs() << InputInfos
[i
].getAsString();
1112 llvm::errs() << ", ";
1114 llvm::errs() << "], output: " << Result
.getAsString() << "\n";
1116 T
.ConstructJob(C
, *JA
, *Dest
, Result
, InputInfos
,
1117 C
.getArgsForToolChain(TC
), LinkingOutput
);
1121 const char *Driver::GetNamedOutputPath(Compilation
&C
,
1122 const JobAction
&JA
,
1123 const char *BaseInput
,
1124 bool AtTopLevel
) const {
1125 llvm::PrettyStackTraceString
CrashInfo("Computing output path");
1126 // Output to a user requested destination?
1128 if (Arg
*FinalOutput
= C
.getArgs().getLastArg(options::OPT_o
))
1129 return C
.addResultFile(FinalOutput
->getValue(C
.getArgs()));
1132 // Output to a temporary file?
1133 if (!AtTopLevel
&& !C
.getArgs().hasArg(options::OPT_save_temps
)) {
1134 std::string TmpName
=
1135 GetTemporaryPath(types::getTypeTempSuffix(JA
.getType()));
1136 return C
.addTempFile(C
.getArgs().MakeArgString(TmpName
.c_str()));
1139 llvm::sys::Path
BasePath(BaseInput
);
1140 std::string
BaseName(BasePath
.getLast());
1142 // Determine what the derived output name should be.
1143 const char *NamedOutput
;
1144 if (JA
.getType() == types::TY_Image
) {
1145 NamedOutput
= DefaultImageName
.c_str();
1147 const char *Suffix
= types::getTypeTempSuffix(JA
.getType());
1148 assert(Suffix
&& "All types used for output should have a suffix.");
1150 std::string::size_type End
= std::string::npos
;
1151 if (!types::appendSuffixForType(JA
.getType()))
1152 End
= BaseName
.rfind('.');
1153 std::string
Suffixed(BaseName
.substr(0, End
));
1156 NamedOutput
= C
.getArgs().MakeArgString(Suffixed
.c_str());
1159 // As an annoying special case, PCH generation doesn't strip the
1161 if (JA
.getType() == types::TY_PCH
) {
1162 BasePath
.eraseComponent();
1163 if (BasePath
.isEmpty())
1164 BasePath
= NamedOutput
;
1166 BasePath
.appendComponent(NamedOutput
);
1167 return C
.addResultFile(C
.getArgs().MakeArgString(BasePath
.c_str()));
1169 return C
.addResultFile(NamedOutput
);
1173 llvm::sys::Path
Driver::GetFilePath(const char *Name
,
1174 const ToolChain
&TC
) const {
1175 const ToolChain::path_list
&List
= TC
.getFilePaths();
1176 for (ToolChain::path_list::const_iterator
1177 it
= List
.begin(), ie
= List
.end(); it
!= ie
; ++it
) {
1178 llvm::sys::Path
P(*it
);
1179 P
.appendComponent(Name
);
1184 return llvm::sys::Path(Name
);
1187 llvm::sys::Path
Driver::GetProgramPath(const char *Name
,
1188 const ToolChain
&TC
,
1189 bool WantFile
) const {
1190 const ToolChain::path_list
&List
= TC
.getProgramPaths();
1191 for (ToolChain::path_list::const_iterator
1192 it
= List
.begin(), ie
= List
.end(); it
!= ie
; ++it
) {
1193 llvm::sys::Path
P(*it
);
1194 P
.appendComponent(Name
);
1195 if (WantFile
? P
.exists() : P
.canExecute())
1199 // If all else failed, search the path.
1200 llvm::sys::Path
P(llvm::sys::Program::FindProgramByName(Name
));
1204 return llvm::sys::Path(Name
);
1207 std::string
Driver::GetTemporaryPath(const char *Suffix
) const {
1208 // FIXME: This is lame; sys::Path should provide this function (in
1209 // particular, it should know how to find the temporary files dir).
1211 const char *TmpDir
= ::getenv("TMPDIR");
1213 TmpDir
= ::getenv("TEMP");
1215 TmpDir
= ::getenv("TMP");
1218 llvm::sys::Path
P(TmpDir
);
1219 P
.appendComponent("cc");
1220 if (P
.makeUnique(false, &Error
)) {
1221 Diag(clang::diag::err_drv_unable_to_make_temp
) << Error
;
1225 // FIXME: Grumble, makeUnique sometimes leaves the file around!?
1227 P
.eraseFromDisk(false, 0);
1229 P
.appendSuffix(Suffix
);
1230 return P
.toString();
1233 const HostInfo
*Driver::GetHostInfo(const char *TripleStr
) const {
1234 llvm::PrettyStackTraceString
CrashInfo("Constructing host");
1235 llvm::Triple
Triple(TripleStr
);
1237 // Normalize Arch a bit.
1239 // FIXME: We shouldn't need to do this once everything goes through the triple
1241 if (Triple
.getArchName() == "i686")
1242 Triple
.setArchName("i386");
1243 else if (Triple
.getArchName() == "amd64")
1244 Triple
.setArchName("x86_64");
1245 else if (Triple
.getArchName() == "ppc" ||
1246 Triple
.getArchName() == "Power Macintosh")
1247 Triple
.setArchName("powerpc");
1248 else if (Triple
.getArchName() == "ppc64")
1249 Triple
.setArchName("powerpc64");
1251 switch (Triple
.getOS()) {
1252 case llvm::Triple::Darwin
:
1253 return createDarwinHostInfo(*this, Triple
);
1254 case llvm::Triple::DragonFly
:
1255 return createDragonFlyHostInfo(*this, Triple
);
1256 case llvm::Triple::OpenBSD
:
1257 return createOpenBSDHostInfo(*this, Triple
);
1258 case llvm::Triple::FreeBSD
:
1259 return createFreeBSDHostInfo(*this, Triple
);
1260 case llvm::Triple::Linux
:
1261 return createLinuxHostInfo(*this, Triple
);
1263 return createUnknownHostInfo(*this, Triple
);
1267 bool Driver::ShouldUseClangCompiler(const Compilation
&C
, const JobAction
&JA
,
1268 const std::string
&ArchNameStr
) const {
1269 // FIXME: Remove this hack.
1270 const char *ArchName
= ArchNameStr
.c_str();
1271 if (ArchNameStr
== "powerpc")
1273 else if (ArchNameStr
== "powerpc64")
1276 // Check if user requested no clang, or clang doesn't understand
1277 // this type (we only handle single inputs for now).
1278 if (!CCCUseClang
|| JA
.size() != 1 ||
1279 !types::isAcceptedByClang((*JA
.begin())->getType()))
1282 // Otherwise make sure this is an action clang understands.
1283 if (isa
<PreprocessJobAction
>(JA
)) {
1284 if (!CCCUseClangCPP
) {
1285 Diag(clang::diag::warn_drv_not_using_clang_cpp
);
1288 } else if (!isa
<PrecompileJobAction
>(JA
) && !isa
<CompileJobAction
>(JA
))
1291 // Use clang for C++?
1292 if (!CCCUseClangCXX
&& types::isCXX((*JA
.begin())->getType())) {
1293 Diag(clang::diag::warn_drv_not_using_clang_cxx
);
1297 // Always use clang for precompiling, regardless of archs. PTH is
1298 // platform independent, and this allows the use of the static
1299 // analyzer on platforms we don't have full IRgen support for.
1300 if (isa
<PrecompileJobAction
>(JA
))
1303 // Finally, don't use clang if this isn't one of the user specified
1305 if (!CCCClangArchs
.empty() && !CCCClangArchs
.count(ArchName
)) {
1306 Diag(clang::diag::warn_drv_not_using_clang_arch
) << ArchName
;
1313 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and
1314 /// return the grouped values as integers. Numbers which are not
1315 /// provided are set to 0.
1317 /// \return True if the entire string was parsed (9.2), or all groups
1318 /// were parsed (10.3.5extrastuff).
1319 bool Driver::GetReleaseVersion(const char *Str
, unsigned &Major
,
1320 unsigned &Minor
, unsigned &Micro
,
1324 Major
= Minor
= Micro
= 0;
1329 Major
= (unsigned) strtol(Str
, &End
, 10);
1330 if (*Str
!= '\0' && *End
== '\0')
1336 Minor
= (unsigned) strtol(Str
, &End
, 10);
1337 if (*Str
!= '\0' && *End
== '\0')
1343 Micro
= (unsigned) strtol(Str
, &End
, 10);
1344 if (*Str
!= '\0' && *End
== '\0')