blob: f63fc63fe8c83b02dec1864a82dd89a330660a24 [file] [log] [blame]
Daniel Dunbar63c4da92009-03-02 19:59:07 +00001//===--- Driver.cpp - Clang GCC Compatible Driver -----------------------*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Daniel Dunbar63c4da92009-03-02 19:59:07 +000010#include "clang/Driver/Driver.h"
Daniel Dunbar63c4da92009-03-02 19:59:07 +000011
Daniel Dunbardb62cc32009-03-12 07:58:46 +000012#include "clang/Driver/Action.h"
Daniel Dunbard6f0e372009-03-04 20:49:20 +000013#include "clang/Driver/Arg.h"
14#include "clang/Driver/ArgList.h"
15#include "clang/Driver/Compilation.h"
Daniel Dunbar93468492009-03-12 08:55:43 +000016#include "clang/Driver/DriverDiagnostic.h"
Daniel Dunbard25acaa2009-03-10 23:41:59 +000017#include "clang/Driver/HostInfo.h"
Daniel Dunbar7ce6add2009-03-16 06:56:51 +000018#include "clang/Driver/Job.h"
Daniel Dunbar7dc2a042009-03-05 06:38:47 +000019#include "clang/Driver/Option.h"
Daniel Dunbard6f0e372009-03-04 20:49:20 +000020#include "clang/Driver/Options.h"
Daniel Dunbar7ce6add2009-03-16 06:56:51 +000021#include "clang/Driver/Tool.h"
22#include "clang/Driver/ToolChain.h"
Daniel Dunbardb62cc32009-03-12 07:58:46 +000023#include "clang/Driver/Types.h"
Daniel Dunbar7dc2a042009-03-05 06:38:47 +000024
Daniel Dunbarb1873cd2009-03-13 20:33:35 +000025#include "llvm/ADT/StringSet.h"
Daniel Dunbar7dc2a042009-03-05 06:38:47 +000026#include "llvm/Support/raw_ostream.h"
Daniel Dunbardb62cc32009-03-12 07:58:46 +000027#include "llvm/System/Path.h"
Daniel Dunbar494646b2009-03-13 12:19:02 +000028
Daniel Dunbar7ce6add2009-03-16 06:56:51 +000029#include "InputInfo.h"
30
Daniel Dunbar494646b2009-03-13 12:19:02 +000031#include <map>
32
Daniel Dunbard6f0e372009-03-04 20:49:20 +000033using namespace clang::driver;
34
Daniel Dunbard25acaa2009-03-10 23:41:59 +000035Driver::Driver(const char *_Name, const char *_Dir,
Daniel Dunbar93468492009-03-12 08:55:43 +000036 const char *_DefaultHostTriple,
Daniel Dunbar7ce6add2009-03-16 06:56:51 +000037 const char *_DefaultImageName,
Daniel Dunbar93468492009-03-12 08:55:43 +000038 Diagnostic &_Diags)
39 : Opts(new OptTable()), Diags(_Diags),
Daniel Dunbard25acaa2009-03-10 23:41:59 +000040 Name(_Name), Dir(_Dir), DefaultHostTriple(_DefaultHostTriple),
Daniel Dunbar7ce6add2009-03-16 06:56:51 +000041 DefaultImageName(_DefaultImageName),
Daniel Dunbard25acaa2009-03-10 23:41:59 +000042 Host(0),
Daniel Dunbar07c9a1d2009-03-17 22:47:06 +000043 CCCIsCXX(false), CCCEcho(false), CCCPrintBindings(false),
Daniel Dunbar5a5ec5c2009-03-13 00:17:48 +000044 CCCNoClang(false), CCCNoClangCXX(false), CCCNoClangCPP(false),
45 SuppressMissingInputWarning(false)
Daniel Dunbarb282ced2009-03-10 20:52:46 +000046{
Daniel Dunbar63c4da92009-03-02 19:59:07 +000047}
48
49Driver::~Driver() {
Daniel Dunbard6f0e372009-03-04 20:49:20 +000050 delete Opts;
Daniel Dunbar2f8b37e2009-03-18 01:09:40 +000051 delete Host;
Daniel Dunbar63c4da92009-03-02 19:59:07 +000052}
53
Daniel Dunbar7dc2a042009-03-05 06:38:47 +000054ArgList *Driver::ParseArgStrings(const char **ArgBegin, const char **ArgEnd) {
55 ArgList *Args = new ArgList(ArgBegin, ArgEnd);
56
Daniel Dunbar85cb3592009-03-13 11:38:42 +000057 // FIXME: Handle '@' args (or at least error on them).
58
Daniel Dunbar7dc2a042009-03-05 06:38:47 +000059 unsigned Index = 0, End = ArgEnd - ArgBegin;
60 while (Index < End) {
Daniel Dunbarb043ebd2009-03-13 01:01:44 +000061 // gcc's handling of empty arguments doesn't make
62 // sense, but this is not a common use case. :)
63 //
64 // We just ignore them here (note that other things may
65 // still take them as arguments).
66 if (Args->getArgString(Index)[0] == '\0') {
67 ++Index;
68 continue;
69 }
70
Daniel Dunbar7dc2a042009-03-05 06:38:47 +000071 unsigned Prev = Index;
72 Arg *A = getOpts().ParseOneArg(*Args, Index, End);
Daniel Dunbardb62cc32009-03-12 07:58:46 +000073 if (A) {
74 if (A->getOption().isUnsupported()) {
Daniel Dunbard724e332009-03-12 09:13:48 +000075 Diag(clang::diag::err_drv_unsupported_opt) << A->getOption().getName();
Daniel Dunbardb62cc32009-03-12 07:58:46 +000076 continue;
77 }
78
Daniel Dunbar7dc2a042009-03-05 06:38:47 +000079 Args->append(A);
Daniel Dunbardb62cc32009-03-12 07:58:46 +000080 }
Daniel Dunbar7dc2a042009-03-05 06:38:47 +000081
82 assert(Index > Prev && "Parser failed to consume argument.");
Daniel Dunbarbb087552009-03-17 04:12:06 +000083 (void) Prev;
Daniel Dunbar7dc2a042009-03-05 06:38:47 +000084 }
85
86 return Args;
87}
88
Daniel Dunbar63c4da92009-03-02 19:59:07 +000089Compilation *Driver::BuildCompilation(int argc, const char **argv) {
Daniel Dunbarcc006892009-03-13 00:51:18 +000090 // FIXME: Handle environment options which effect driver behavior,
91 // somewhere (client?). GCC_EXEC_PREFIX, COMPILER_PATH,
92 // LIBRARY_PATH, LPATH, CC_PRINT_OPTIONS, QA_OVERRIDE_GCC3_OPTIONS.
93
94 // FIXME: What are we going to do with -V and -b?
95
96 // FIXME: Handle CCC_ADD_ARGS.
97
Daniel Dunbarb282ced2009-03-10 20:52:46 +000098 // FIXME: This stuff needs to go into the Compilation, not the
99 // driver.
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000100 bool CCCPrintOptions = false, CCCPrintActions = false;
Daniel Dunbar7dc2a042009-03-05 06:38:47 +0000101
Daniel Dunbarb282ced2009-03-10 20:52:46 +0000102 const char **Start = argv + 1, **End = argv + argc;
Daniel Dunbard25acaa2009-03-10 23:41:59 +0000103 const char *HostTriple = DefaultHostTriple.c_str();
Daniel Dunbarb282ced2009-03-10 20:52:46 +0000104
105 // Read -ccc args.
106 //
107 // FIXME: We need to figure out where this behavior should
108 // live. Most of it should be outside in the client; the parts that
109 // aren't should have proper options, either by introducing new ones
110 // or by overloading gcc ones like -V or -b.
111 for (; Start != End && memcmp(*Start, "-ccc-", 5) == 0; ++Start) {
112 const char *Opt = *Start + 5;
113
114 if (!strcmp(Opt, "print-options")) {
115 CCCPrintOptions = true;
116 } else if (!strcmp(Opt, "print-phases")) {
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000117 CCCPrintActions = true;
Daniel Dunbar07c9a1d2009-03-17 22:47:06 +0000118 } else if (!strcmp(Opt, "print-bindings")) {
119 CCCPrintBindings = true;
Daniel Dunbarb282ced2009-03-10 20:52:46 +0000120 } else if (!strcmp(Opt, "cxx")) {
121 CCCIsCXX = true;
122 } else if (!strcmp(Opt, "echo")) {
123 CCCEcho = true;
124
125 } else if (!strcmp(Opt, "no-clang")) {
126 CCCNoClang = true;
127 } else if (!strcmp(Opt, "no-clang-cxx")) {
128 CCCNoClangCXX = true;
129 } else if (!strcmp(Opt, "no-clang-cpp")) {
130 CCCNoClangCPP = true;
131 } else if (!strcmp(Opt, "clang-archs")) {
132 assert(Start+1 < End && "FIXME: -ccc- argument handling.");
133 const char *Cur = *++Start;
134
135 for (;;) {
136 const char *Next = strchr(Cur, ',');
137
138 if (Next) {
139 CCCClangArchs.insert(std::string(Cur, Next));
140 Cur = Next + 1;
141 } else {
142 CCCClangArchs.insert(std::string(Cur));
143 break;
144 }
145 }
146
Daniel Dunbard25acaa2009-03-10 23:41:59 +0000147 } else if (!strcmp(Opt, "host-triple")) {
Daniel Dunbarb282ced2009-03-10 20:52:46 +0000148 assert(Start+1 < End && "FIXME: -ccc- argument handling.");
Daniel Dunbard25acaa2009-03-10 23:41:59 +0000149 HostTriple = *++Start;
Daniel Dunbarb282ced2009-03-10 20:52:46 +0000150
151 } else {
152 // FIXME: Error handling.
153 llvm::errs() << "invalid option: " << *Start << "\n";
154 exit(1);
155 }
156 }
Daniel Dunbard25acaa2009-03-10 23:41:59 +0000157
Daniel Dunbarb282ced2009-03-10 20:52:46 +0000158 ArgList *Args = ParseArgStrings(Start, End);
159
Daniel Dunbar08966ca2009-03-17 20:45:45 +0000160 Host = GetHostInfo(HostTriple);
Daniel Dunbar43a36802009-03-17 21:29:52 +0000161 // FIXME: This shouldn't live inside Driver, the default tool chain
162 // is part of the compilation (it is arg dependent).
Daniel Dunbarcc006892009-03-13 00:51:18 +0000163 DefaultToolChain = Host->getToolChain(*Args);
164
Daniel Dunbarb282ced2009-03-10 20:52:46 +0000165 // FIXME: This behavior shouldn't be here.
166 if (CCCPrintOptions) {
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000167 PrintOptions(*Args);
Daniel Dunbar88c9eae2009-03-13 17:24:34 +0000168 return 0;
Daniel Dunbarb282ced2009-03-10 20:52:46 +0000169 }
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000170
Daniel Dunbarcc006892009-03-13 00:51:18 +0000171 if (!HandleImmediateArgs(*Args))
172 return 0;
173
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000174 // Construct the list of abstract actions to perform for this
175 // compilation.
Daniel Dunbara790d372009-03-12 18:24:49 +0000176 ActionList Actions;
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000177 if (Host->useDriverDriver())
178 BuildUniversalActions(*Args, Actions);
179 else
180 BuildActions(*Args, Actions);
181
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000182 if (CCCPrintActions) {
Daniel Dunbar494646b2009-03-13 12:19:02 +0000183 PrintActions(*Args, Actions);
Daniel Dunbar88c9eae2009-03-13 17:24:34 +0000184 return 0;
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000185 }
Daniel Dunbar88c9eae2009-03-13 17:24:34 +0000186
Daniel Dunbar9d625e12009-03-16 06:42:30 +0000187 // The compilation takes ownership of Args.
188 Compilation *C = new Compilation(*DefaultToolChain, Args);
189 BuildJobs(*C, Actions);
Daniel Dunbarc413f822009-03-15 01:38:15 +0000190
191 return C;
Daniel Dunbarb282ced2009-03-10 20:52:46 +0000192}
193
Daniel Dunbara790d372009-03-12 18:24:49 +0000194void Driver::PrintOptions(const ArgList &Args) const {
Daniel Dunbar7dc2a042009-03-05 06:38:47 +0000195 unsigned i = 0;
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000196 for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
Daniel Dunbar7dc2a042009-03-05 06:38:47 +0000197 it != ie; ++it, ++i) {
198 Arg *A = *it;
199 llvm::errs() << "Option " << i << " - "
200 << "Name: \"" << A->getOption().getName() << "\", "
201 << "Values: {";
202 for (unsigned j = 0; j < A->getNumValues(); ++j) {
203 if (j)
204 llvm::errs() << ", ";
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000205 llvm::errs() << '"' << A->getValue(Args, j) << '"';
Daniel Dunbar7dc2a042009-03-05 06:38:47 +0000206 }
207 llvm::errs() << "}\n";
Daniel Dunbar7dc2a042009-03-05 06:38:47 +0000208 }
Daniel Dunbar63c4da92009-03-02 19:59:07 +0000209}
Daniel Dunbard25acaa2009-03-10 23:41:59 +0000210
Daniel Dunbarcc006892009-03-13 00:51:18 +0000211void Driver::PrintVersion() const {
212 // FIXME: Get a reasonable version number.
213
214 // FIXME: The following handlers should use a callback mechanism, we
215 // don't know what the client would like to do.
216 llvm::outs() << "ccc version 1.0" << "\n";
217}
218
219bool Driver::HandleImmediateArgs(const ArgList &Args) {
220 // The order these options are handled in in gcc is all over the
221 // place, but we don't expect inconsistencies w.r.t. that to matter
222 // in practice.
223 if (Args.hasArg(options::OPT_v) ||
224 Args.hasArg(options::OPT__HASH_HASH_HASH)) {
225 PrintVersion();
226 SuppressMissingInputWarning = true;
227 }
228
229 // FIXME: The following handlers should use a callback mechanism, we
230 // don't know what the client would like to do.
231 if (Arg *A = Args.getLastArg(options::OPT_print_file_name_EQ)) {
232 llvm::outs() << GetFilePath(A->getValue(Args)).toString() << "\n";
233 return false;
234 }
235
236 if (Arg *A = Args.getLastArg(options::OPT_print_prog_name_EQ)) {
237 llvm::outs() << GetProgramPath(A->getValue(Args)).toString() << "\n";
238 return false;
239 }
240
Daniel Dunbarb043ebd2009-03-13 01:01:44 +0000241 if (Args.hasArg(options::OPT_print_libgcc_file_name)) {
Daniel Dunbarcc006892009-03-13 00:51:18 +0000242 llvm::outs() << GetProgramPath("libgcc.a").toString() << "\n";
243 return false;
244 }
245
246 return true;
247}
248
Daniel Dunbar494646b2009-03-13 12:19:02 +0000249static unsigned PrintActions1(const ArgList &Args,
250 Action *A,
251 std::map<Action*, unsigned> &Ids) {
252 if (Ids.count(A))
253 return Ids[A];
254
255 std::string str;
256 llvm::raw_string_ostream os(str);
257
258 os << Action::getClassName(A->getKind()) << ", ";
259 if (InputAction *IA = dyn_cast<InputAction>(A)) {
Daniel Dunbardd863aa2009-03-13 17:46:02 +0000260 os << "\"" << IA->getInputArg().getValue(Args) << "\"";
Daniel Dunbar494646b2009-03-13 12:19:02 +0000261 } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
262 os << "\"" << BIA->getArchName() << "\", "
263 << "{" << PrintActions1(Args, *BIA->begin(), Ids) << "}";
264 } else {
265 os << "{";
266 for (Action::iterator it = A->begin(), ie = A->end(); it != ie;) {
267 os << PrintActions1(Args, *it, Ids);
268 ++it;
269 if (it != ie)
270 os << ", ";
271 }
272 os << "}";
273 }
274
275 unsigned Id = Ids.size();
276 Ids[A] = Id;
Daniel Dunbar9dc28b82009-03-13 17:20:20 +0000277 llvm::errs() << Id << ": " << os.str() << ", "
Daniel Dunbar494646b2009-03-13 12:19:02 +0000278 << types::getTypeName(A->getType()) << "\n";
279
280 return Id;
281}
282
283void Driver::PrintActions(const ArgList &Args,
284 const ActionList &Actions) const {
285 std::map<Action*, unsigned> Ids;
286 for (ActionList::const_iterator it = Actions.begin(), ie = Actions.end();
Daniel Dunbar9dc28b82009-03-13 17:20:20 +0000287 it != ie; ++it)
Daniel Dunbar494646b2009-03-13 12:19:02 +0000288 PrintActions1(Args, *it, Ids);
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000289}
290
Daniel Dunbar47d762e2009-03-13 22:12:33 +0000291void Driver::BuildUniversalActions(ArgList &Args, ActionList &Actions) const {
Daniel Dunbarb1873cd2009-03-13 20:33:35 +0000292 // Collect the list of architectures. Duplicates are allowed, but
293 // should only be handled once (in the order seen).
294 llvm::StringSet<> ArchNames;
295 llvm::SmallVector<const char *, 4> Archs;
Daniel Dunbarfba157b2009-03-12 18:40:18 +0000296 for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
297 it != ie; ++it) {
298 Arg *A = *it;
299
300 if (A->getOption().getId() == options::OPT_arch) {
Daniel Dunbarb1873cd2009-03-13 20:33:35 +0000301 const char *Name = A->getValue(Args);
302
Daniel Dunbarfba157b2009-03-12 18:40:18 +0000303 // FIXME: We need to handle canonicalization of the specified
304 // arch?
305
Daniel Dunbarb1873cd2009-03-13 20:33:35 +0000306 if (ArchNames.insert(Name))
307 Archs.push_back(Name);
Daniel Dunbarfba157b2009-03-12 18:40:18 +0000308 }
309 }
310
311 // When there is no explicit arch for this platform, get one from
312 // the host so that -Xarch_ is handled correctly.
313 if (!Archs.size()) {
Daniel Dunbar43a36802009-03-17 21:29:52 +0000314 const char *Arch = DefaultToolChain->getArchName().c_str();
Daniel Dunbarb1873cd2009-03-13 20:33:35 +0000315 Archs.push_back(Arch);
Daniel Dunbarfba157b2009-03-12 18:40:18 +0000316 }
317
318 // FIXME: We killed off some others but these aren't yet detected in
319 // a functional manner. If we added information to jobs about which
320 // "auxiliary" files they wrote then we could detect the conflict
321 // these cause downstream.
322 if (Archs.size() > 1) {
323 // No recovery needed, the point of this is just to prevent
324 // overwriting the same files.
325 if (const Arg *A = Args.getLastArg(options::OPT_M_Group))
326 Diag(clang::diag::err_drv_invalid_opt_with_multiple_archs)
327 << A->getOption().getName();
328 if (const Arg *A = Args.getLastArg(options::OPT_save_temps))
329 Diag(clang::diag::err_drv_invalid_opt_with_multiple_archs)
330 << A->getOption().getName();
331 }
332
333 ActionList SingleActions;
334 BuildActions(Args, SingleActions);
335
336 // Add in arch binding and lipo (if necessary) for every top level
337 // action.
338 for (unsigned i = 0, e = SingleActions.size(); i != e; ++i) {
339 Action *Act = SingleActions[i];
340
341 // Make sure we can lipo this kind of output. If not (and it is an
342 // actual output) then we disallow, since we can't create an
343 // output file with the right name without overwriting it. We
344 // could remove this oddity by just changing the output names to
345 // include the arch, which would also fix
346 // -save-temps. Compatibility wins for now.
347
Daniel Dunbardd863aa2009-03-13 17:46:02 +0000348 if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
Daniel Dunbarfba157b2009-03-12 18:40:18 +0000349 Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
350 << types::getTypeName(Act->getType());
351
352 ActionList Inputs;
Daniel Dunbarb1873cd2009-03-13 20:33:35 +0000353 for (unsigned i = 0, e = Archs.size(); i != e; ++i )
354 Inputs.push_back(new BindArchAction(Act, Archs[i]));
Daniel Dunbarfba157b2009-03-12 18:40:18 +0000355
356 // Lipo if necessary, We do it this way because we need to set the
357 // arch flag so that -Xarch_ gets overwritten.
358 if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
359 Actions.append(Inputs.begin(), Inputs.end());
360 else
361 Actions.push_back(new LipoJobAction(Inputs, Act->getType()));
362 }
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000363}
364
Daniel Dunbar47d762e2009-03-13 22:12:33 +0000365void Driver::BuildActions(ArgList &Args, ActionList &Actions) const {
Daniel Dunbar207a56d2009-03-12 23:55:14 +0000366 // Start by constructing the list of inputs and their types.
367
Daniel Dunbar5cb75d62009-03-13 17:57:10 +0000368 // Track the current user specified (-x) input. We also explicitly
369 // track the argument used to set the type; we only want to claim
370 // the type when we actually use it, so we warn about unused -x
371 // arguments.
372 types::ID InputType = types::TY_Nothing;
373 Arg *InputTypeArg = 0;
374
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000375 llvm::SmallVector<std::pair<types::ID, const Arg*>, 16> Inputs;
376 for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
377 it != ie; ++it) {
378 Arg *A = *it;
379
380 if (isa<InputOption>(A->getOption())) {
381 const char *Value = A->getValue(Args);
382 types::ID Ty = types::TY_INVALID;
383
384 // Infer the input type if necessary.
Daniel Dunbar5cb75d62009-03-13 17:57:10 +0000385 if (InputType == types::TY_Nothing) {
386 // If there was an explicit arg for this, claim it.
387 if (InputTypeArg)
388 InputTypeArg->claim();
389
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000390 // stdin must be handled specially.
391 if (memcmp(Value, "-", 2) == 0) {
392 // If running with -E, treat as a C input (this changes the
393 // builtin macros, for example). This may be overridden by
394 // -ObjC below.
395 //
396 // Otherwise emit an error but still use a valid type to
397 // avoid spurious errors (e.g., no inputs).
Daniel Dunbare9c70fa2009-03-15 00:48:16 +0000398 if (!Args.hasArg(options::OPT_E, false))
Daniel Dunbard724e332009-03-12 09:13:48 +0000399 Diag(clang::diag::err_drv_unknown_stdin_type);
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000400 Ty = types::TY_C;
401 } else {
402 // Otherwise lookup by extension, and fallback to ObjectType
403 // if not found.
404 if (const char *Ext = strrchr(Value, '.'))
405 Ty = types::lookupTypeForExtension(Ext + 1);
406 if (Ty == types::TY_INVALID)
407 Ty = types::TY_Object;
408 }
409
410 // -ObjC and -ObjC++ override the default language, but only
411 // -for "source files". We just treat everything that isn't a
412 // -linker input as a source file.
413 //
414 // FIXME: Clean this up if we move the phase sequence into the
415 // type.
416 if (Ty != types::TY_Object) {
417 if (Args.hasArg(options::OPT_ObjC))
418 Ty = types::TY_ObjC;
419 else if (Args.hasArg(options::OPT_ObjCXX))
420 Ty = types::TY_ObjCXX;
421 }
422 } else {
423 assert(InputTypeArg && "InputType set w/o InputTypeArg");
424 InputTypeArg->claim();
425 Ty = InputType;
426 }
427
428 // Check that the file exists. It isn't clear this is worth
429 // doing, since the tool presumably does this anyway, and this
430 // just adds an extra stat to the equation, but this is gcc
431 // compatible.
Daniel Dunbar321c12d2009-03-15 01:40:22 +0000432 A->claim();
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000433 if (memcmp(Value, "-", 2) != 0 && !llvm::sys::Path(Value).exists())
Daniel Dunbard724e332009-03-12 09:13:48 +0000434 Diag(clang::diag::err_drv_no_such_file) << A->getValue(Args);
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000435 else
436 Inputs.push_back(std::make_pair(Ty, A));
437
438 } else if (A->getOption().isLinkerInput()) {
439 // Just treat as object type, we could make a special type for
440 // this if necessary.
Daniel Dunbar321c12d2009-03-15 01:40:22 +0000441 A->claim();
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000442 Inputs.push_back(std::make_pair(types::TY_Object, A));
443
444 } else if (A->getOption().getId() == options::OPT_x) {
445 InputTypeArg = A;
446 InputType = types::lookupTypeForTypeSpecifier(A->getValue(Args));
447
448 // Follow gcc behavior and treat as linker input for invalid -x
449 // options. Its not clear why we shouldn't just revert to
450 // unknown; but this isn't very important, we might as well be
451 // bug comatible.
452 if (!InputType) {
Daniel Dunbard724e332009-03-12 09:13:48 +0000453 Diag(clang::diag::err_drv_unknown_language) << A->getValue(Args);
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000454 InputType = types::TY_Object;
455 }
456 }
457 }
458
Daniel Dunbar5a5ec5c2009-03-13 00:17:48 +0000459 if (!SuppressMissingInputWarning && Inputs.empty()) {
Daniel Dunbar207a56d2009-03-12 23:55:14 +0000460 Diag(clang::diag::err_drv_no_input_files);
461 return;
462 }
463
464 // Determine which compilation mode we are in. We look for options
465 // which affect the phase, starting with the earliest phases, and
466 // record which option we used to determine the final phase.
Daniel Dunbar85cb3592009-03-13 11:38:42 +0000467 Arg *FinalPhaseArg = 0;
468 phases::ID FinalPhase;
Daniel Dunbar207a56d2009-03-12 23:55:14 +0000469
470 // -{E,M,MM} only run the preprocessor.
Daniel Dunbar85cb3592009-03-13 11:38:42 +0000471 if ((FinalPhaseArg = Args.getLastArg(options::OPT_E)) ||
472 (FinalPhaseArg = Args.getLastArg(options::OPT_M)) ||
473 (FinalPhaseArg = Args.getLastArg(options::OPT_MM))) {
474 FinalPhase = phases::Preprocess;
Daniel Dunbar207a56d2009-03-12 23:55:14 +0000475
Daniel Dunbare9c70fa2009-03-15 00:48:16 +0000476 // -{fsyntax-only,-analyze,emit-llvm,S} only run up to the compiler.
477 } else if ((FinalPhaseArg = Args.getLastArg(options::OPT_fsyntax_only)) ||
478 (FinalPhaseArg = Args.getLastArg(options::OPT__analyze)) ||
479 (FinalPhaseArg = Args.getLastArg(options::OPT_emit_llvm)) ||
Daniel Dunbar85cb3592009-03-13 11:38:42 +0000480 (FinalPhaseArg = Args.getLastArg(options::OPT_S))) {
481 FinalPhase = phases::Compile;
Daniel Dunbar207a56d2009-03-12 23:55:14 +0000482
483 // -c only runs up to the assembler.
Daniel Dunbar85cb3592009-03-13 11:38:42 +0000484 } else if ((FinalPhaseArg = Args.getLastArg(options::OPT_c))) {
485 FinalPhase = phases::Assemble;
Daniel Dunbar207a56d2009-03-12 23:55:14 +0000486
487 // Otherwise do everything.
488 } else
Daniel Dunbar85cb3592009-03-13 11:38:42 +0000489 FinalPhase = phases::Link;
Daniel Dunbar207a56d2009-03-12 23:55:14 +0000490
Daniel Dunbar207a56d2009-03-12 23:55:14 +0000491 // Reject -Z* at the top level, these options should never have been
492 // exposed by gcc.
493 if (Arg *A = Args.getLastArg(options::OPT_Z))
494 Diag(clang::diag::err_drv_use_of_Z_option) << A->getValue(Args);
495
Daniel Dunbar85cb3592009-03-13 11:38:42 +0000496 // Construct the actions to perform.
497 ActionList LinkerInputs;
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000498 for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
Daniel Dunbar85cb3592009-03-13 11:38:42 +0000499 types::ID InputType = Inputs[i].first;
500 const Arg *InputArg = Inputs[i].second;
501
502 unsigned NumSteps = types::getNumCompilationPhases(InputType);
503 assert(NumSteps && "Invalid number of steps!");
504
505 // If the first step comes after the final phase we are doing as
506 // part of this compilation, warn the user about it.
507 phases::ID InitialPhase = types::getCompilationPhase(InputType, 0);
508 if (InitialPhase > FinalPhase) {
509 Diag(clang::diag::warn_drv_input_file_unused)
510 << InputArg->getValue(Args)
511 << getPhaseName(InitialPhase)
512 << FinalPhaseArg->getOption().getName();
513 continue;
514 }
515
516 // Build the pipeline for this file.
517 Action *Current = new InputAction(*InputArg, InputType);
518 for (unsigned i = 0; i != NumSteps; ++i) {
519 phases::ID Phase = types::getCompilationPhase(InputType, i);
520
521 // We are done if this step is past what the user requested.
522 if (Phase > FinalPhase)
523 break;
524
525 // Queue linker inputs.
526 if (Phase == phases::Link) {
527 assert(i + 1 == NumSteps && "linking must be final compilation step.");
528 LinkerInputs.push_back(Current);
529 Current = 0;
530 break;
531 }
532
533 // Otherwise construct the appropriate action.
534 Current = ConstructPhaseAction(Args, Phase, Current);
535 if (Current->getType() == types::TY_Nothing)
536 break;
537 }
538
539 // If we ended with something, add to the output list.
540 if (Current)
541 Actions.push_back(Current);
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000542 }
Daniel Dunbar85cb3592009-03-13 11:38:42 +0000543
544 // Add a link action if necessary.
545 if (!LinkerInputs.empty())
546 Actions.push_back(new LinkJobAction(LinkerInputs, types::TY_Image));
547}
548
549Action *Driver::ConstructPhaseAction(const ArgList &Args, phases::ID Phase,
550 Action *Input) const {
551 // Build the appropriate action.
552 switch (Phase) {
553 case phases::Link: assert(0 && "link action invalid here.");
554 case phases::Preprocess: {
555 types::ID OutputTy = types::getPreprocessedType(Input->getType());
556 assert(OutputTy != types::TY_INVALID &&
557 "Cannot preprocess this input type!");
558 return new PreprocessJobAction(Input, OutputTy);
559 }
560 case phases::Precompile:
561 return new PrecompileJobAction(Input, types::TY_PCH);
562 case phases::Compile: {
563 if (Args.hasArg(options::OPT_fsyntax_only)) {
564 return new CompileJobAction(Input, types::TY_Nothing);
565 } else if (Args.hasArg(options::OPT__analyze)) {
566 return new AnalyzeJobAction(Input, types::TY_Plist);
567 } else if (Args.hasArg(options::OPT_emit_llvm)) {
568 types::ID Output =
569 Args.hasArg(options::OPT_S) ? types::TY_LLVMAsm : types::TY_LLVMBC;
570 return new CompileJobAction(Input, Output);
571 } else {
572 return new CompileJobAction(Input, types::TY_PP_Asm);
573 }
574 }
575 case phases::Assemble:
576 return new AssembleJobAction(Input, types::TY_Object);
577 }
578
579 assert(0 && "invalid phase in ConstructPhaseAction");
580 return 0;
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000581}
582
Daniel Dunbar7ce6add2009-03-16 06:56:51 +0000583void Driver::BuildJobs(Compilation &C, const ActionList &Actions) const {
584 bool SaveTemps = C.getArgs().hasArg(options::OPT_save_temps);
585 bool UsePipes = C.getArgs().hasArg(options::OPT_pipe);
586
587 // -save-temps inhibits pipes.
588 if (SaveTemps && UsePipes) {
589 Diag(clang::diag::warn_drv_pipe_ignored_with_save_temps);
590 UsePipes = true;
591 }
592
593 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
594
595 // It is an error to provide a -o option if we are making multiple
596 // output files.
597 if (FinalOutput) {
598 unsigned NumOutputs = 0;
599 for (ActionList::const_iterator it = Actions.begin(), ie = Actions.end();
600 it != ie; ++it)
601 if ((*it)->getType() != types::TY_Nothing)
602 ++NumOutputs;
603
604 if (NumOutputs > 1) {
605 Diag(clang::diag::err_drv_output_argument_with_multiple_files);
606 FinalOutput = 0;
607 }
608 }
609
610 for (ActionList::const_iterator it = Actions.begin(), ie = Actions.end();
611 it != ie; ++it) {
612 Action *A = *it;
613
614 // If we are linking an image for multiple archs then the linker
615 // wants -arch_multiple and -final_output <final image
616 // name>. Unfortunately, this doesn't fit in cleanly because we
617 // have to pass this information down.
618 //
619 // FIXME: This is a hack; find a cleaner way to integrate this
620 // into the process.
621 const char *LinkingOutput = 0;
622 if (isa<LinkJobAction>(A)) {
623 if (FinalOutput)
624 LinkingOutput = FinalOutput->getValue(C.getArgs());
625 else
626 LinkingOutput = DefaultImageName.c_str();
627 }
628
629 InputInfo II;
630 BuildJobsForAction(C,
631 A, DefaultToolChain,
632 /*CanAcceptPipe*/ true,
633 /*AtTopLevel*/ true,
634 /*LinkingOutput*/ LinkingOutput,
635 II);
636 }
Daniel Dunbar9d625e12009-03-16 06:42:30 +0000637
638 // If there were no errors, warn about any unused arguments.
639 for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end();
640 it != ie; ++it) {
641 Arg *A = *it;
642
643 // FIXME: It would be nice to be able to send the argument to the
644 // Diagnostic, so that extra values, position, and so on could be
645 // printed.
646 if (!A->isClaimed())
647 Diag(clang::diag::warn_drv_unused_argument)
648 << A->getOption().getName();
649 }
Daniel Dunbar47d762e2009-03-13 22:12:33 +0000650}
651
Daniel Dunbar7ce6add2009-03-16 06:56:51 +0000652void Driver::BuildJobsForAction(Compilation &C,
653 const Action *A,
654 const ToolChain *TC,
655 bool CanAcceptPipe,
656 bool AtTopLevel,
657 const char *LinkingOutput,
658 InputInfo &Result) const {
659 if (const InputAction *IA = dyn_cast<InputAction>(A)) {
660 const char *Name = IA->getInputArg().getValue(C.getArgs());
661 Result = InputInfo(Name, A->getType(), Name);
662 return;
663 }
664
665 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
666 const char *ArchName = BAA->getArchName();
667 BuildJobsForAction(C,
668 *BAA->begin(),
669 Host->getToolChain(C.getArgs(), ArchName),
670 CanAcceptPipe,
671 AtTopLevel,
672 LinkingOutput,
673 Result);
674 return;
675 }
676
677 const JobAction *JA = cast<JobAction>(A);
678 const Tool &T = TC->SelectTool(C, *JA);
679
680 // See if we should use an integrated preprocessor. We do so when we
681 // have exactly one input, since this is the only use case we care
682 // about (irrelevant since we don't support combine yet).
683 bool UseIntegratedCPP = false;
684 const ActionList *Inputs = &A->getInputs();
685 if (Inputs->size() == 1 && isa<PreprocessJobAction>(*Inputs->begin())) {
686 if (!C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
687 !C.getArgs().hasArg(options::OPT_traditional_cpp) &&
688 !C.getArgs().hasArg(options::OPT_save_temps) &&
689 T.hasIntegratedCPP()) {
690 UseIntegratedCPP = true;
691 Inputs = &(*Inputs)[0]->getInputs();
692 }
693 }
694
695 // Only use pipes when there is exactly one input.
696 bool TryToUsePipeInput = Inputs->size() == 1 && T.acceptsPipedInput();
697 llvm::SmallVector<InputInfo, 4> InputInfos;
698 for (ActionList::const_iterator it = Inputs->begin(), ie = Inputs->end();
699 it != ie; ++it) {
700 InputInfo II;
701 BuildJobsForAction(C, *it, TC, TryToUsePipeInput,
702 /*AtTopLevel*/false,
703 LinkingOutput,
704 II);
705 InputInfos.push_back(II);
706 }
707
708 // Determine if we should output to a pipe.
709 bool OutputToPipe = false;
710 if (CanAcceptPipe && T.canPipeOutput()) {
711 // Some actions default to writing to a pipe if they are the top
712 // level phase and there was no user override.
713 //
714 // FIXME: Is there a better way to handle this?
715 if (AtTopLevel) {
716 if (isa<PreprocessJobAction>(A) && !C.getArgs().hasArg(options::OPT_o))
717 OutputToPipe = true;
718 } else if (C.getArgs().hasArg(options::OPT_pipe))
719 OutputToPipe = true;
720 }
721
722 // Figure out where to put the job (pipes).
723 Job *Dest = &C.getJobs();
724 if (InputInfos[0].isPipe()) {
Daniel Dunbar01fb26a2009-03-17 17:53:55 +0000725 assert(TryToUsePipeInput && "Unrequested pipe!");
Daniel Dunbar7ce6add2009-03-16 06:56:51 +0000726 assert(InputInfos.size() == 1 && "Unexpected pipe with multiple inputs.");
727 Dest = &InputInfos[0].getPipe();
728 }
729
730 // Always use the first input as the base input.
731 const char *BaseInput = InputInfos[0].getBaseInput();
Daniel Dunbar01fb26a2009-03-17 17:53:55 +0000732
733 // Determine the place to write output to (nothing, pipe, or
734 // filename) and where to put the new job.
Daniel Dunbar01fb26a2009-03-17 17:53:55 +0000735 if (JA->getType() == types::TY_Nothing) {
Daniel Dunbar07c9a1d2009-03-17 22:47:06 +0000736 Result = InputInfo(A->getType(), BaseInput);
Daniel Dunbar01fb26a2009-03-17 17:53:55 +0000737 } else if (OutputToPipe) {
738 // Append to current piped job or create a new one as appropriate.
Daniel Dunbar07c9a1d2009-03-17 22:47:06 +0000739 PipedJob *PJ = dyn_cast<PipedJob>(Dest);
740 if (!PJ) {
741 PJ = new PipedJob();
742 cast<JobList>(Dest)->addJob(PJ);
Daniel Dunbar01fb26a2009-03-17 17:53:55 +0000743 }
Daniel Dunbar07c9a1d2009-03-17 22:47:06 +0000744 Result = InputInfo(PJ, A->getType(), BaseInput);
Daniel Dunbar01fb26a2009-03-17 17:53:55 +0000745 } else {
Daniel Dunbar07c9a1d2009-03-17 22:47:06 +0000746 Result = InputInfo(GetNamedOutputPath(C, *JA, BaseInput, AtTopLevel),
747 A->getType(), BaseInput);
Daniel Dunbar01fb26a2009-03-17 17:53:55 +0000748 }
749
Daniel Dunbar07c9a1d2009-03-17 22:47:06 +0000750 if (CCCPrintBindings) {
751 llvm::errs() << "bind - \"" << T.getName() << "\", inputs: [";
752 for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
753 llvm::errs() << InputInfos[i].getAsString();
754 if (i + 1 != e)
755 llvm::errs() << ", ";
756 }
757 llvm::errs() << "], output: " << Result.getAsString() << "\n";
758 } else {
759 assert(0 && "FIXME: Make the job.");
760 }
Daniel Dunbar7ce6add2009-03-16 06:56:51 +0000761}
762
Daniel Dunbar01fb26a2009-03-17 17:53:55 +0000763const char *Driver::GetNamedOutputPath(Compilation &C,
764 const JobAction &JA,
765 const char *BaseInput,
766 bool AtTopLevel) const {
767 // Output to a user requested destination?
768 if (AtTopLevel) {
769 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
770 return C.addResultFile(FinalOutput->getValue(C.getArgs()));
771 }
772
773 // Output to a temporary file?
774 if (!AtTopLevel && !C.getArgs().hasArg(options::OPT_save_temps)) {
775 // FIXME: Get temporary name.
776 std::string Name("/tmp/foo");
777 Name += '.';
778 Name += types::getTypeTempSuffix(JA.getType());
779 return C.addTempFile(C.getArgs().MakeArgString(Name.c_str()));
780 }
781
782 llvm::sys::Path BasePath(BaseInput);
783 std::string BaseName(BasePath.getBasename());
784
785 // Determine what the derived output name should be.
786 const char *NamedOutput;
787 if (JA.getType() == types::TY_Image) {
788 NamedOutput = DefaultImageName.c_str();
789 } else {
790 const char *Suffix = types::getTypeTempSuffix(JA.getType());
791 assert(Suffix && "All types used for output should have a suffix.");
792
793 std::string::size_type End = std::string::npos;
794 if (!types::appendSuffixForType(JA.getType()))
795 End = BaseName.rfind('.');
796 std::string Suffixed(BaseName.substr(0, End));
797 Suffixed += '.';
798 Suffixed += Suffix;
799 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
800 }
801
802 // As an annoying special case, PCH generation doesn't strip the
803 // pathname.
804 if (JA.getType() == types::TY_PCH) {
805 BasePath.eraseComponent();
806 BasePath.appendComponent(NamedOutput);
807 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()));
808 } else {
809 return C.addResultFile(NamedOutput);
810 }
811}
812
Daniel Dunbare1cef7d2009-03-16 05:25:36 +0000813llvm::sys::Path Driver::GetFilePath(const char *Name,
814 const ToolChain *TC) const {
Daniel Dunbarcc006892009-03-13 00:51:18 +0000815 // FIXME: Implement.
Daniel Dunbare1cef7d2009-03-16 05:25:36 +0000816 if (!TC) TC = DefaultToolChain;
817
Daniel Dunbarcc006892009-03-13 00:51:18 +0000818 return llvm::sys::Path(Name);
819}
820
Daniel Dunbare1cef7d2009-03-16 05:25:36 +0000821llvm::sys::Path Driver::GetProgramPath(const char *Name,
822 const ToolChain *TC) const {
Daniel Dunbarcc006892009-03-13 00:51:18 +0000823 // FIXME: Implement.
Daniel Dunbare1cef7d2009-03-16 05:25:36 +0000824 if (!TC) TC = DefaultToolChain;
825
Daniel Dunbarcc006892009-03-13 00:51:18 +0000826 return llvm::sys::Path(Name);
827}
828
Daniel Dunbar08966ca2009-03-17 20:45:45 +0000829const HostInfo *Driver::GetHostInfo(const char *Triple) const {
Daniel Dunbard25acaa2009-03-10 23:41:59 +0000830 // Dice into arch, platform, and OS. This matches
831 // arch,platform,os = '(.*?)-(.*?)-(.*?)'
832 // and missing fields are left empty.
833 std::string Arch, Platform, OS;
834
835 if (const char *ArchEnd = strchr(Triple, '-')) {
836 Arch = std::string(Triple, ArchEnd);
837
838 if (const char *PlatformEnd = strchr(ArchEnd+1, '-')) {
839 Platform = std::string(ArchEnd+1, PlatformEnd);
840 OS = PlatformEnd+1;
841 } else
842 Platform = ArchEnd+1;
843 } else
844 Arch = Triple;
845
Daniel Dunbar7424b8a2009-03-17 19:00:50 +0000846 // Normalize Arch a bit.
847 //
848 // FIXME: This is very incomplete.
849 if (Arch == "i686")
850 Arch = "i386";
851 else if (Arch == "amd64")
852 Arch = "x86_64";
853
Daniel Dunbar44119a12009-03-13 12:23:29 +0000854 if (memcmp(&OS[0], "darwin", 6) == 0)
Daniel Dunbar08966ca2009-03-17 20:45:45 +0000855 return createDarwinHostInfo(*this, Arch.c_str(), Platform.c_str(),
856 OS.c_str());
Daniel Dunbard25acaa2009-03-10 23:41:59 +0000857
Daniel Dunbar08966ca2009-03-17 20:45:45 +0000858 return createUnknownHostInfo(*this, Arch.c_str(), Platform.c_str(),
859 OS.c_str());
Daniel Dunbard25acaa2009-03-10 23:41:59 +0000860}