blob: c2df48cbc1afd91698f832d1b832feeb0783cd51 [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 Dunbarb282ced2009-03-10 20:52:46 +000043 CCCIsCXX(false), CCCEcho(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 Dunbar63c4da92009-03-02 19:59:07 +000051}
52
Daniel Dunbar7dc2a042009-03-05 06:38:47 +000053ArgList *Driver::ParseArgStrings(const char **ArgBegin, const char **ArgEnd) {
54 ArgList *Args = new ArgList(ArgBegin, ArgEnd);
55
Daniel Dunbar85cb3592009-03-13 11:38:42 +000056 // FIXME: Handle '@' args (or at least error on them).
57
Daniel Dunbar7dc2a042009-03-05 06:38:47 +000058 unsigned Index = 0, End = ArgEnd - ArgBegin;
59 while (Index < End) {
Daniel Dunbarb043ebd2009-03-13 01:01:44 +000060 // gcc's handling of empty arguments doesn't make
61 // sense, but this is not a common use case. :)
62 //
63 // We just ignore them here (note that other things may
64 // still take them as arguments).
65 if (Args->getArgString(Index)[0] == '\0') {
66 ++Index;
67 continue;
68 }
69
Daniel Dunbar7dc2a042009-03-05 06:38:47 +000070 unsigned Prev = Index;
71 Arg *A = getOpts().ParseOneArg(*Args, Index, End);
Daniel Dunbardb62cc32009-03-12 07:58:46 +000072 if (A) {
73 if (A->getOption().isUnsupported()) {
Daniel Dunbard724e332009-03-12 09:13:48 +000074 Diag(clang::diag::err_drv_unsupported_opt) << A->getOption().getName();
Daniel Dunbardb62cc32009-03-12 07:58:46 +000075 continue;
76 }
77
Daniel Dunbar7dc2a042009-03-05 06:38:47 +000078 Args->append(A);
Daniel Dunbardb62cc32009-03-12 07:58:46 +000079 }
Daniel Dunbar7dc2a042009-03-05 06:38:47 +000080
81 assert(Index > Prev && "Parser failed to consume argument.");
Daniel Dunbarbb087552009-03-17 04:12:06 +000082 (void) Prev;
Daniel Dunbar7dc2a042009-03-05 06:38:47 +000083 }
84
85 return Args;
86}
87
Daniel Dunbar63c4da92009-03-02 19:59:07 +000088Compilation *Driver::BuildCompilation(int argc, const char **argv) {
Daniel Dunbarcc006892009-03-13 00:51:18 +000089 // FIXME: Handle environment options which effect driver behavior,
90 // somewhere (client?). GCC_EXEC_PREFIX, COMPILER_PATH,
91 // LIBRARY_PATH, LPATH, CC_PRINT_OPTIONS, QA_OVERRIDE_GCC3_OPTIONS.
92
93 // FIXME: What are we going to do with -V and -b?
94
95 // FIXME: Handle CCC_ADD_ARGS.
96
Daniel Dunbarb282ced2009-03-10 20:52:46 +000097 // FIXME: This stuff needs to go into the Compilation, not the
98 // driver.
Daniel Dunbardb62cc32009-03-12 07:58:46 +000099 bool CCCPrintOptions = false, CCCPrintActions = false;
Daniel Dunbar7dc2a042009-03-05 06:38:47 +0000100
Daniel Dunbarb282ced2009-03-10 20:52:46 +0000101 const char **Start = argv + 1, **End = argv + argc;
Daniel Dunbard25acaa2009-03-10 23:41:59 +0000102 const char *HostTriple = DefaultHostTriple.c_str();
Daniel Dunbarb282ced2009-03-10 20:52:46 +0000103
104 // Read -ccc args.
105 //
106 // FIXME: We need to figure out where this behavior should
107 // live. Most of it should be outside in the client; the parts that
108 // aren't should have proper options, either by introducing new ones
109 // or by overloading gcc ones like -V or -b.
110 for (; Start != End && memcmp(*Start, "-ccc-", 5) == 0; ++Start) {
111 const char *Opt = *Start + 5;
112
113 if (!strcmp(Opt, "print-options")) {
114 CCCPrintOptions = true;
115 } else if (!strcmp(Opt, "print-phases")) {
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000116 CCCPrintActions = true;
Daniel Dunbarb282ced2009-03-10 20:52:46 +0000117 } else if (!strcmp(Opt, "cxx")) {
118 CCCIsCXX = true;
119 } else if (!strcmp(Opt, "echo")) {
120 CCCEcho = true;
121
122 } else if (!strcmp(Opt, "no-clang")) {
123 CCCNoClang = true;
124 } else if (!strcmp(Opt, "no-clang-cxx")) {
125 CCCNoClangCXX = true;
126 } else if (!strcmp(Opt, "no-clang-cpp")) {
127 CCCNoClangCPP = true;
128 } else if (!strcmp(Opt, "clang-archs")) {
129 assert(Start+1 < End && "FIXME: -ccc- argument handling.");
130 const char *Cur = *++Start;
131
132 for (;;) {
133 const char *Next = strchr(Cur, ',');
134
135 if (Next) {
136 CCCClangArchs.insert(std::string(Cur, Next));
137 Cur = Next + 1;
138 } else {
139 CCCClangArchs.insert(std::string(Cur));
140 break;
141 }
142 }
143
Daniel Dunbard25acaa2009-03-10 23:41:59 +0000144 } else if (!strcmp(Opt, "host-triple")) {
Daniel Dunbarb282ced2009-03-10 20:52:46 +0000145 assert(Start+1 < End && "FIXME: -ccc- argument handling.");
Daniel Dunbard25acaa2009-03-10 23:41:59 +0000146 HostTriple = *++Start;
Daniel Dunbarb282ced2009-03-10 20:52:46 +0000147
148 } else {
149 // FIXME: Error handling.
150 llvm::errs() << "invalid option: " << *Start << "\n";
151 exit(1);
152 }
153 }
Daniel Dunbard25acaa2009-03-10 23:41:59 +0000154
Daniel Dunbarb282ced2009-03-10 20:52:46 +0000155 ArgList *Args = ParseArgStrings(Start, End);
156
Daniel Dunbar08966ca2009-03-17 20:45:45 +0000157 Host = GetHostInfo(HostTriple);
Daniel Dunbar43a36802009-03-17 21:29:52 +0000158 // FIXME: This shouldn't live inside Driver, the default tool chain
159 // is part of the compilation (it is arg dependent).
Daniel Dunbarcc006892009-03-13 00:51:18 +0000160 DefaultToolChain = Host->getToolChain(*Args);
161
Daniel Dunbarb282ced2009-03-10 20:52:46 +0000162 // FIXME: This behavior shouldn't be here.
163 if (CCCPrintOptions) {
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000164 PrintOptions(*Args);
Daniel Dunbar88c9eae2009-03-13 17:24:34 +0000165 return 0;
Daniel Dunbarb282ced2009-03-10 20:52:46 +0000166 }
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000167
Daniel Dunbarcc006892009-03-13 00:51:18 +0000168 if (!HandleImmediateArgs(*Args))
169 return 0;
170
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000171 // Construct the list of abstract actions to perform for this
172 // compilation.
Daniel Dunbara790d372009-03-12 18:24:49 +0000173 ActionList Actions;
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000174 if (Host->useDriverDriver())
175 BuildUniversalActions(*Args, Actions);
176 else
177 BuildActions(*Args, Actions);
178
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000179 if (CCCPrintActions) {
Daniel Dunbar494646b2009-03-13 12:19:02 +0000180 PrintActions(*Args, Actions);
Daniel Dunbar88c9eae2009-03-13 17:24:34 +0000181 return 0;
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000182 }
Daniel Dunbar88c9eae2009-03-13 17:24:34 +0000183
Daniel Dunbar9d625e12009-03-16 06:42:30 +0000184 // The compilation takes ownership of Args.
185 Compilation *C = new Compilation(*DefaultToolChain, Args);
186 BuildJobs(*C, Actions);
Daniel Dunbarc413f822009-03-15 01:38:15 +0000187
188 return C;
Daniel Dunbarb282ced2009-03-10 20:52:46 +0000189}
190
Daniel Dunbara790d372009-03-12 18:24:49 +0000191void Driver::PrintOptions(const ArgList &Args) const {
Daniel Dunbar7dc2a042009-03-05 06:38:47 +0000192 unsigned i = 0;
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000193 for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
Daniel Dunbar7dc2a042009-03-05 06:38:47 +0000194 it != ie; ++it, ++i) {
195 Arg *A = *it;
196 llvm::errs() << "Option " << i << " - "
197 << "Name: \"" << A->getOption().getName() << "\", "
198 << "Values: {";
199 for (unsigned j = 0; j < A->getNumValues(); ++j) {
200 if (j)
201 llvm::errs() << ", ";
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000202 llvm::errs() << '"' << A->getValue(Args, j) << '"';
Daniel Dunbar7dc2a042009-03-05 06:38:47 +0000203 }
204 llvm::errs() << "}\n";
Daniel Dunbar7dc2a042009-03-05 06:38:47 +0000205 }
Daniel Dunbar63c4da92009-03-02 19:59:07 +0000206}
Daniel Dunbard25acaa2009-03-10 23:41:59 +0000207
Daniel Dunbarcc006892009-03-13 00:51:18 +0000208void Driver::PrintVersion() const {
209 // FIXME: Get a reasonable version number.
210
211 // FIXME: The following handlers should use a callback mechanism, we
212 // don't know what the client would like to do.
213 llvm::outs() << "ccc version 1.0" << "\n";
214}
215
216bool Driver::HandleImmediateArgs(const ArgList &Args) {
217 // The order these options are handled in in gcc is all over the
218 // place, but we don't expect inconsistencies w.r.t. that to matter
219 // in practice.
220 if (Args.hasArg(options::OPT_v) ||
221 Args.hasArg(options::OPT__HASH_HASH_HASH)) {
222 PrintVersion();
223 SuppressMissingInputWarning = true;
224 }
225
226 // FIXME: The following handlers should use a callback mechanism, we
227 // don't know what the client would like to do.
228 if (Arg *A = Args.getLastArg(options::OPT_print_file_name_EQ)) {
229 llvm::outs() << GetFilePath(A->getValue(Args)).toString() << "\n";
230 return false;
231 }
232
233 if (Arg *A = Args.getLastArg(options::OPT_print_prog_name_EQ)) {
234 llvm::outs() << GetProgramPath(A->getValue(Args)).toString() << "\n";
235 return false;
236 }
237
Daniel Dunbarb043ebd2009-03-13 01:01:44 +0000238 if (Args.hasArg(options::OPT_print_libgcc_file_name)) {
Daniel Dunbarcc006892009-03-13 00:51:18 +0000239 llvm::outs() << GetProgramPath("libgcc.a").toString() << "\n";
240 return false;
241 }
242
243 return true;
244}
245
Daniel Dunbar494646b2009-03-13 12:19:02 +0000246static unsigned PrintActions1(const ArgList &Args,
247 Action *A,
248 std::map<Action*, unsigned> &Ids) {
249 if (Ids.count(A))
250 return Ids[A];
251
252 std::string str;
253 llvm::raw_string_ostream os(str);
254
255 os << Action::getClassName(A->getKind()) << ", ";
256 if (InputAction *IA = dyn_cast<InputAction>(A)) {
Daniel Dunbardd863aa2009-03-13 17:46:02 +0000257 os << "\"" << IA->getInputArg().getValue(Args) << "\"";
Daniel Dunbar494646b2009-03-13 12:19:02 +0000258 } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
259 os << "\"" << BIA->getArchName() << "\", "
260 << "{" << PrintActions1(Args, *BIA->begin(), Ids) << "}";
261 } else {
262 os << "{";
263 for (Action::iterator it = A->begin(), ie = A->end(); it != ie;) {
264 os << PrintActions1(Args, *it, Ids);
265 ++it;
266 if (it != ie)
267 os << ", ";
268 }
269 os << "}";
270 }
271
272 unsigned Id = Ids.size();
273 Ids[A] = Id;
Daniel Dunbar9dc28b82009-03-13 17:20:20 +0000274 llvm::errs() << Id << ": " << os.str() << ", "
Daniel Dunbar494646b2009-03-13 12:19:02 +0000275 << types::getTypeName(A->getType()) << "\n";
276
277 return Id;
278}
279
280void Driver::PrintActions(const ArgList &Args,
281 const ActionList &Actions) const {
282 std::map<Action*, unsigned> Ids;
283 for (ActionList::const_iterator it = Actions.begin(), ie = Actions.end();
Daniel Dunbar9dc28b82009-03-13 17:20:20 +0000284 it != ie; ++it)
Daniel Dunbar494646b2009-03-13 12:19:02 +0000285 PrintActions1(Args, *it, Ids);
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000286}
287
Daniel Dunbar47d762e2009-03-13 22:12:33 +0000288void Driver::BuildUniversalActions(ArgList &Args, ActionList &Actions) const {
Daniel Dunbarb1873cd2009-03-13 20:33:35 +0000289 // Collect the list of architectures. Duplicates are allowed, but
290 // should only be handled once (in the order seen).
291 llvm::StringSet<> ArchNames;
292 llvm::SmallVector<const char *, 4> Archs;
Daniel Dunbarfba157b2009-03-12 18:40:18 +0000293 for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
294 it != ie; ++it) {
295 Arg *A = *it;
296
297 if (A->getOption().getId() == options::OPT_arch) {
Daniel Dunbarb1873cd2009-03-13 20:33:35 +0000298 const char *Name = A->getValue(Args);
299
Daniel Dunbarfba157b2009-03-12 18:40:18 +0000300 // FIXME: We need to handle canonicalization of the specified
301 // arch?
302
Daniel Dunbarb1873cd2009-03-13 20:33:35 +0000303 if (ArchNames.insert(Name))
304 Archs.push_back(Name);
Daniel Dunbarfba157b2009-03-12 18:40:18 +0000305 }
306 }
307
308 // When there is no explicit arch for this platform, get one from
309 // the host so that -Xarch_ is handled correctly.
310 if (!Archs.size()) {
Daniel Dunbar43a36802009-03-17 21:29:52 +0000311 const char *Arch = DefaultToolChain->getArchName().c_str();
Daniel Dunbarb1873cd2009-03-13 20:33:35 +0000312 Archs.push_back(Arch);
Daniel Dunbarfba157b2009-03-12 18:40:18 +0000313 }
314
315 // FIXME: We killed off some others but these aren't yet detected in
316 // a functional manner. If we added information to jobs about which
317 // "auxiliary" files they wrote then we could detect the conflict
318 // these cause downstream.
319 if (Archs.size() > 1) {
320 // No recovery needed, the point of this is just to prevent
321 // overwriting the same files.
322 if (const Arg *A = Args.getLastArg(options::OPT_M_Group))
323 Diag(clang::diag::err_drv_invalid_opt_with_multiple_archs)
324 << A->getOption().getName();
325 if (const Arg *A = Args.getLastArg(options::OPT_save_temps))
326 Diag(clang::diag::err_drv_invalid_opt_with_multiple_archs)
327 << A->getOption().getName();
328 }
329
330 ActionList SingleActions;
331 BuildActions(Args, SingleActions);
332
333 // Add in arch binding and lipo (if necessary) for every top level
334 // action.
335 for (unsigned i = 0, e = SingleActions.size(); i != e; ++i) {
336 Action *Act = SingleActions[i];
337
338 // Make sure we can lipo this kind of output. If not (and it is an
339 // actual output) then we disallow, since we can't create an
340 // output file with the right name without overwriting it. We
341 // could remove this oddity by just changing the output names to
342 // include the arch, which would also fix
343 // -save-temps. Compatibility wins for now.
344
Daniel Dunbardd863aa2009-03-13 17:46:02 +0000345 if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
Daniel Dunbarfba157b2009-03-12 18:40:18 +0000346 Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
347 << types::getTypeName(Act->getType());
348
349 ActionList Inputs;
Daniel Dunbarb1873cd2009-03-13 20:33:35 +0000350 for (unsigned i = 0, e = Archs.size(); i != e; ++i )
351 Inputs.push_back(new BindArchAction(Act, Archs[i]));
Daniel Dunbarfba157b2009-03-12 18:40:18 +0000352
353 // Lipo if necessary, We do it this way because we need to set the
354 // arch flag so that -Xarch_ gets overwritten.
355 if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
356 Actions.append(Inputs.begin(), Inputs.end());
357 else
358 Actions.push_back(new LipoJobAction(Inputs, Act->getType()));
359 }
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000360}
361
Daniel Dunbar47d762e2009-03-13 22:12:33 +0000362void Driver::BuildActions(ArgList &Args, ActionList &Actions) const {
Daniel Dunbar207a56d2009-03-12 23:55:14 +0000363 // Start by constructing the list of inputs and their types.
364
Daniel Dunbar5cb75d62009-03-13 17:57:10 +0000365 // Track the current user specified (-x) input. We also explicitly
366 // track the argument used to set the type; we only want to claim
367 // the type when we actually use it, so we warn about unused -x
368 // arguments.
369 types::ID InputType = types::TY_Nothing;
370 Arg *InputTypeArg = 0;
371
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000372 llvm::SmallVector<std::pair<types::ID, const Arg*>, 16> Inputs;
373 for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
374 it != ie; ++it) {
375 Arg *A = *it;
376
377 if (isa<InputOption>(A->getOption())) {
378 const char *Value = A->getValue(Args);
379 types::ID Ty = types::TY_INVALID;
380
381 // Infer the input type if necessary.
Daniel Dunbar5cb75d62009-03-13 17:57:10 +0000382 if (InputType == types::TY_Nothing) {
383 // If there was an explicit arg for this, claim it.
384 if (InputTypeArg)
385 InputTypeArg->claim();
386
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000387 // stdin must be handled specially.
388 if (memcmp(Value, "-", 2) == 0) {
389 // If running with -E, treat as a C input (this changes the
390 // builtin macros, for example). This may be overridden by
391 // -ObjC below.
392 //
393 // Otherwise emit an error but still use a valid type to
394 // avoid spurious errors (e.g., no inputs).
Daniel Dunbare9c70fa2009-03-15 00:48:16 +0000395 if (!Args.hasArg(options::OPT_E, false))
Daniel Dunbard724e332009-03-12 09:13:48 +0000396 Diag(clang::diag::err_drv_unknown_stdin_type);
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000397 Ty = types::TY_C;
398 } else {
399 // Otherwise lookup by extension, and fallback to ObjectType
400 // if not found.
401 if (const char *Ext = strrchr(Value, '.'))
402 Ty = types::lookupTypeForExtension(Ext + 1);
403 if (Ty == types::TY_INVALID)
404 Ty = types::TY_Object;
405 }
406
407 // -ObjC and -ObjC++ override the default language, but only
408 // -for "source files". We just treat everything that isn't a
409 // -linker input as a source file.
410 //
411 // FIXME: Clean this up if we move the phase sequence into the
412 // type.
413 if (Ty != types::TY_Object) {
414 if (Args.hasArg(options::OPT_ObjC))
415 Ty = types::TY_ObjC;
416 else if (Args.hasArg(options::OPT_ObjCXX))
417 Ty = types::TY_ObjCXX;
418 }
419 } else {
420 assert(InputTypeArg && "InputType set w/o InputTypeArg");
421 InputTypeArg->claim();
422 Ty = InputType;
423 }
424
425 // Check that the file exists. It isn't clear this is worth
426 // doing, since the tool presumably does this anyway, and this
427 // just adds an extra stat to the equation, but this is gcc
428 // compatible.
Daniel Dunbar321c12d2009-03-15 01:40:22 +0000429 A->claim();
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000430 if (memcmp(Value, "-", 2) != 0 && !llvm::sys::Path(Value).exists())
Daniel Dunbard724e332009-03-12 09:13:48 +0000431 Diag(clang::diag::err_drv_no_such_file) << A->getValue(Args);
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000432 else
433 Inputs.push_back(std::make_pair(Ty, A));
434
435 } else if (A->getOption().isLinkerInput()) {
436 // Just treat as object type, we could make a special type for
437 // this if necessary.
Daniel Dunbar321c12d2009-03-15 01:40:22 +0000438 A->claim();
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000439 Inputs.push_back(std::make_pair(types::TY_Object, A));
440
441 } else if (A->getOption().getId() == options::OPT_x) {
442 InputTypeArg = A;
443 InputType = types::lookupTypeForTypeSpecifier(A->getValue(Args));
444
445 // Follow gcc behavior and treat as linker input for invalid -x
446 // options. Its not clear why we shouldn't just revert to
447 // unknown; but this isn't very important, we might as well be
448 // bug comatible.
449 if (!InputType) {
Daniel Dunbard724e332009-03-12 09:13:48 +0000450 Diag(clang::diag::err_drv_unknown_language) << A->getValue(Args);
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000451 InputType = types::TY_Object;
452 }
453 }
454 }
455
Daniel Dunbar5a5ec5c2009-03-13 00:17:48 +0000456 if (!SuppressMissingInputWarning && Inputs.empty()) {
Daniel Dunbar207a56d2009-03-12 23:55:14 +0000457 Diag(clang::diag::err_drv_no_input_files);
458 return;
459 }
460
461 // Determine which compilation mode we are in. We look for options
462 // which affect the phase, starting with the earliest phases, and
463 // record which option we used to determine the final phase.
Daniel Dunbar85cb3592009-03-13 11:38:42 +0000464 Arg *FinalPhaseArg = 0;
465 phases::ID FinalPhase;
Daniel Dunbar207a56d2009-03-12 23:55:14 +0000466
467 // -{E,M,MM} only run the preprocessor.
Daniel Dunbar85cb3592009-03-13 11:38:42 +0000468 if ((FinalPhaseArg = Args.getLastArg(options::OPT_E)) ||
469 (FinalPhaseArg = Args.getLastArg(options::OPT_M)) ||
470 (FinalPhaseArg = Args.getLastArg(options::OPT_MM))) {
471 FinalPhase = phases::Preprocess;
Daniel Dunbar207a56d2009-03-12 23:55:14 +0000472
Daniel Dunbare9c70fa2009-03-15 00:48:16 +0000473 // -{fsyntax-only,-analyze,emit-llvm,S} only run up to the compiler.
474 } else if ((FinalPhaseArg = Args.getLastArg(options::OPT_fsyntax_only)) ||
475 (FinalPhaseArg = Args.getLastArg(options::OPT__analyze)) ||
476 (FinalPhaseArg = Args.getLastArg(options::OPT_emit_llvm)) ||
Daniel Dunbar85cb3592009-03-13 11:38:42 +0000477 (FinalPhaseArg = Args.getLastArg(options::OPT_S))) {
478 FinalPhase = phases::Compile;
Daniel Dunbar207a56d2009-03-12 23:55:14 +0000479
480 // -c only runs up to the assembler.
Daniel Dunbar85cb3592009-03-13 11:38:42 +0000481 } else if ((FinalPhaseArg = Args.getLastArg(options::OPT_c))) {
482 FinalPhase = phases::Assemble;
Daniel Dunbar207a56d2009-03-12 23:55:14 +0000483
484 // Otherwise do everything.
485 } else
Daniel Dunbar85cb3592009-03-13 11:38:42 +0000486 FinalPhase = phases::Link;
Daniel Dunbar207a56d2009-03-12 23:55:14 +0000487
Daniel Dunbar207a56d2009-03-12 23:55:14 +0000488 // Reject -Z* at the top level, these options should never have been
489 // exposed by gcc.
490 if (Arg *A = Args.getLastArg(options::OPT_Z))
491 Diag(clang::diag::err_drv_use_of_Z_option) << A->getValue(Args);
492
Daniel Dunbar85cb3592009-03-13 11:38:42 +0000493 // Construct the actions to perform.
494 ActionList LinkerInputs;
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000495 for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
Daniel Dunbar85cb3592009-03-13 11:38:42 +0000496 types::ID InputType = Inputs[i].first;
497 const Arg *InputArg = Inputs[i].second;
498
499 unsigned NumSteps = types::getNumCompilationPhases(InputType);
500 assert(NumSteps && "Invalid number of steps!");
501
502 // If the first step comes after the final phase we are doing as
503 // part of this compilation, warn the user about it.
504 phases::ID InitialPhase = types::getCompilationPhase(InputType, 0);
505 if (InitialPhase > FinalPhase) {
506 Diag(clang::diag::warn_drv_input_file_unused)
507 << InputArg->getValue(Args)
508 << getPhaseName(InitialPhase)
509 << FinalPhaseArg->getOption().getName();
510 continue;
511 }
512
513 // Build the pipeline for this file.
514 Action *Current = new InputAction(*InputArg, InputType);
515 for (unsigned i = 0; i != NumSteps; ++i) {
516 phases::ID Phase = types::getCompilationPhase(InputType, i);
517
518 // We are done if this step is past what the user requested.
519 if (Phase > FinalPhase)
520 break;
521
522 // Queue linker inputs.
523 if (Phase == phases::Link) {
524 assert(i + 1 == NumSteps && "linking must be final compilation step.");
525 LinkerInputs.push_back(Current);
526 Current = 0;
527 break;
528 }
529
530 // Otherwise construct the appropriate action.
531 Current = ConstructPhaseAction(Args, Phase, Current);
532 if (Current->getType() == types::TY_Nothing)
533 break;
534 }
535
536 // If we ended with something, add to the output list.
537 if (Current)
538 Actions.push_back(Current);
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000539 }
Daniel Dunbar85cb3592009-03-13 11:38:42 +0000540
541 // Add a link action if necessary.
542 if (!LinkerInputs.empty())
543 Actions.push_back(new LinkJobAction(LinkerInputs, types::TY_Image));
544}
545
546Action *Driver::ConstructPhaseAction(const ArgList &Args, phases::ID Phase,
547 Action *Input) const {
548 // Build the appropriate action.
549 switch (Phase) {
550 case phases::Link: assert(0 && "link action invalid here.");
551 case phases::Preprocess: {
552 types::ID OutputTy = types::getPreprocessedType(Input->getType());
553 assert(OutputTy != types::TY_INVALID &&
554 "Cannot preprocess this input type!");
555 return new PreprocessJobAction(Input, OutputTy);
556 }
557 case phases::Precompile:
558 return new PrecompileJobAction(Input, types::TY_PCH);
559 case phases::Compile: {
560 if (Args.hasArg(options::OPT_fsyntax_only)) {
561 return new CompileJobAction(Input, types::TY_Nothing);
562 } else if (Args.hasArg(options::OPT__analyze)) {
563 return new AnalyzeJobAction(Input, types::TY_Plist);
564 } else if (Args.hasArg(options::OPT_emit_llvm)) {
565 types::ID Output =
566 Args.hasArg(options::OPT_S) ? types::TY_LLVMAsm : types::TY_LLVMBC;
567 return new CompileJobAction(Input, Output);
568 } else {
569 return new CompileJobAction(Input, types::TY_PP_Asm);
570 }
571 }
572 case phases::Assemble:
573 return new AssembleJobAction(Input, types::TY_Object);
574 }
575
576 assert(0 && "invalid phase in ConstructPhaseAction");
577 return 0;
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000578}
579
Daniel Dunbar7ce6add2009-03-16 06:56:51 +0000580void Driver::BuildJobs(Compilation &C, const ActionList &Actions) const {
581 bool SaveTemps = C.getArgs().hasArg(options::OPT_save_temps);
582 bool UsePipes = C.getArgs().hasArg(options::OPT_pipe);
583
584 // -save-temps inhibits pipes.
585 if (SaveTemps && UsePipes) {
586 Diag(clang::diag::warn_drv_pipe_ignored_with_save_temps);
587 UsePipes = true;
588 }
589
590 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
591
592 // It is an error to provide a -o option if we are making multiple
593 // output files.
594 if (FinalOutput) {
595 unsigned NumOutputs = 0;
596 for (ActionList::const_iterator it = Actions.begin(), ie = Actions.end();
597 it != ie; ++it)
598 if ((*it)->getType() != types::TY_Nothing)
599 ++NumOutputs;
600
601 if (NumOutputs > 1) {
602 Diag(clang::diag::err_drv_output_argument_with_multiple_files);
603 FinalOutput = 0;
604 }
605 }
606
607 for (ActionList::const_iterator it = Actions.begin(), ie = Actions.end();
608 it != ie; ++it) {
609 Action *A = *it;
610
611 // If we are linking an image for multiple archs then the linker
612 // wants -arch_multiple and -final_output <final image
613 // name>. Unfortunately, this doesn't fit in cleanly because we
614 // have to pass this information down.
615 //
616 // FIXME: This is a hack; find a cleaner way to integrate this
617 // into the process.
618 const char *LinkingOutput = 0;
619 if (isa<LinkJobAction>(A)) {
620 if (FinalOutput)
621 LinkingOutput = FinalOutput->getValue(C.getArgs());
622 else
623 LinkingOutput = DefaultImageName.c_str();
624 }
625
626 InputInfo II;
627 BuildJobsForAction(C,
628 A, DefaultToolChain,
629 /*CanAcceptPipe*/ true,
630 /*AtTopLevel*/ true,
631 /*LinkingOutput*/ LinkingOutput,
632 II);
633 }
Daniel Dunbar9d625e12009-03-16 06:42:30 +0000634
635 // If there were no errors, warn about any unused arguments.
636 for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end();
637 it != ie; ++it) {
638 Arg *A = *it;
639
640 // FIXME: It would be nice to be able to send the argument to the
641 // Diagnostic, so that extra values, position, and so on could be
642 // printed.
643 if (!A->isClaimed())
644 Diag(clang::diag::warn_drv_unused_argument)
645 << A->getOption().getName();
646 }
Daniel Dunbar47d762e2009-03-13 22:12:33 +0000647}
648
Daniel Dunbar7ce6add2009-03-16 06:56:51 +0000649void Driver::BuildJobsForAction(Compilation &C,
650 const Action *A,
651 const ToolChain *TC,
652 bool CanAcceptPipe,
653 bool AtTopLevel,
654 const char *LinkingOutput,
655 InputInfo &Result) const {
656 if (const InputAction *IA = dyn_cast<InputAction>(A)) {
657 const char *Name = IA->getInputArg().getValue(C.getArgs());
658 Result = InputInfo(Name, A->getType(), Name);
659 return;
660 }
661
662 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
663 const char *ArchName = BAA->getArchName();
664 BuildJobsForAction(C,
665 *BAA->begin(),
666 Host->getToolChain(C.getArgs(), ArchName),
667 CanAcceptPipe,
668 AtTopLevel,
669 LinkingOutput,
670 Result);
671 return;
672 }
673
674 const JobAction *JA = cast<JobAction>(A);
675 const Tool &T = TC->SelectTool(C, *JA);
676
677 // See if we should use an integrated preprocessor. We do so when we
678 // have exactly one input, since this is the only use case we care
679 // about (irrelevant since we don't support combine yet).
680 bool UseIntegratedCPP = false;
681 const ActionList *Inputs = &A->getInputs();
682 if (Inputs->size() == 1 && isa<PreprocessJobAction>(*Inputs->begin())) {
683 if (!C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
684 !C.getArgs().hasArg(options::OPT_traditional_cpp) &&
685 !C.getArgs().hasArg(options::OPT_save_temps) &&
686 T.hasIntegratedCPP()) {
687 UseIntegratedCPP = true;
688 Inputs = &(*Inputs)[0]->getInputs();
689 }
690 }
691
692 // Only use pipes when there is exactly one input.
693 bool TryToUsePipeInput = Inputs->size() == 1 && T.acceptsPipedInput();
694 llvm::SmallVector<InputInfo, 4> InputInfos;
695 for (ActionList::const_iterator it = Inputs->begin(), ie = Inputs->end();
696 it != ie; ++it) {
697 InputInfo II;
698 BuildJobsForAction(C, *it, TC, TryToUsePipeInput,
699 /*AtTopLevel*/false,
700 LinkingOutput,
701 II);
702 InputInfos.push_back(II);
703 }
704
705 // Determine if we should output to a pipe.
706 bool OutputToPipe = false;
707 if (CanAcceptPipe && T.canPipeOutput()) {
708 // Some actions default to writing to a pipe if they are the top
709 // level phase and there was no user override.
710 //
711 // FIXME: Is there a better way to handle this?
712 if (AtTopLevel) {
713 if (isa<PreprocessJobAction>(A) && !C.getArgs().hasArg(options::OPT_o))
714 OutputToPipe = true;
715 } else if (C.getArgs().hasArg(options::OPT_pipe))
716 OutputToPipe = true;
717 }
718
719 // Figure out where to put the job (pipes).
720 Job *Dest = &C.getJobs();
721 if (InputInfos[0].isPipe()) {
Daniel Dunbar01fb26a2009-03-17 17:53:55 +0000722 assert(TryToUsePipeInput && "Unrequested pipe!");
Daniel Dunbar7ce6add2009-03-16 06:56:51 +0000723 assert(InputInfos.size() == 1 && "Unexpected pipe with multiple inputs.");
724 Dest = &InputInfos[0].getPipe();
725 }
726
727 // Always use the first input as the base input.
728 const char *BaseInput = InputInfos[0].getBaseInput();
Daniel Dunbar01fb26a2009-03-17 17:53:55 +0000729
730 // Determine the place to write output to (nothing, pipe, or
731 // filename) and where to put the new job.
732 PipedJob *OutputJob = 0;
733 const char *Output = 0;
734 if (JA->getType() == types::TY_Nothing) {
735 ;
736 } else if (OutputToPipe) {
737 // Append to current piped job or create a new one as appropriate.
738 if (PipedJob *PJ = dyn_cast<PipedJob>(Dest)) {
739 OutputJob = PJ;
740 Dest = OutputJob;
741 } else {
742 OutputJob = new PipedJob();
743 cast<JobList>(Dest)->addJob(OutputJob);
744 Dest = OutputJob;
745 }
746 } else {
747 Output = GetNamedOutputPath(C, *JA, BaseInput, AtTopLevel);
748 }
749
Daniel Dunbar7ce6add2009-03-16 06:56:51 +0000750 // FIXME: Make the job.
751
752 Result = InputInfo(Output, A->getType(), BaseInput);
753}
754
Daniel Dunbar01fb26a2009-03-17 17:53:55 +0000755const char *Driver::GetNamedOutputPath(Compilation &C,
756 const JobAction &JA,
757 const char *BaseInput,
758 bool AtTopLevel) const {
759 // Output to a user requested destination?
760 if (AtTopLevel) {
761 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
762 return C.addResultFile(FinalOutput->getValue(C.getArgs()));
763 }
764
765 // Output to a temporary file?
766 if (!AtTopLevel && !C.getArgs().hasArg(options::OPT_save_temps)) {
767 // FIXME: Get temporary name.
768 std::string Name("/tmp/foo");
769 Name += '.';
770 Name += types::getTypeTempSuffix(JA.getType());
771 return C.addTempFile(C.getArgs().MakeArgString(Name.c_str()));
772 }
773
774 llvm::sys::Path BasePath(BaseInput);
775 std::string BaseName(BasePath.getBasename());
776
777 // Determine what the derived output name should be.
778 const char *NamedOutput;
779 if (JA.getType() == types::TY_Image) {
780 NamedOutput = DefaultImageName.c_str();
781 } else {
782 const char *Suffix = types::getTypeTempSuffix(JA.getType());
783 assert(Suffix && "All types used for output should have a suffix.");
784
785 std::string::size_type End = std::string::npos;
786 if (!types::appendSuffixForType(JA.getType()))
787 End = BaseName.rfind('.');
788 std::string Suffixed(BaseName.substr(0, End));
789 Suffixed += '.';
790 Suffixed += Suffix;
791 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
792 }
793
794 // As an annoying special case, PCH generation doesn't strip the
795 // pathname.
796 if (JA.getType() == types::TY_PCH) {
797 BasePath.eraseComponent();
798 BasePath.appendComponent(NamedOutput);
799 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()));
800 } else {
801 return C.addResultFile(NamedOutput);
802 }
803}
804
Daniel Dunbare1cef7d2009-03-16 05:25:36 +0000805llvm::sys::Path Driver::GetFilePath(const char *Name,
806 const ToolChain *TC) const {
Daniel Dunbarcc006892009-03-13 00:51:18 +0000807 // FIXME: Implement.
Daniel Dunbare1cef7d2009-03-16 05:25:36 +0000808 if (!TC) TC = DefaultToolChain;
809
Daniel Dunbarcc006892009-03-13 00:51:18 +0000810 return llvm::sys::Path(Name);
811}
812
Daniel Dunbare1cef7d2009-03-16 05:25:36 +0000813llvm::sys::Path Driver::GetProgramPath(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 Dunbar08966ca2009-03-17 20:45:45 +0000821const HostInfo *Driver::GetHostInfo(const char *Triple) const {
Daniel Dunbard25acaa2009-03-10 23:41:59 +0000822 // Dice into arch, platform, and OS. This matches
823 // arch,platform,os = '(.*?)-(.*?)-(.*?)'
824 // and missing fields are left empty.
825 std::string Arch, Platform, OS;
826
827 if (const char *ArchEnd = strchr(Triple, '-')) {
828 Arch = std::string(Triple, ArchEnd);
829
830 if (const char *PlatformEnd = strchr(ArchEnd+1, '-')) {
831 Platform = std::string(ArchEnd+1, PlatformEnd);
832 OS = PlatformEnd+1;
833 } else
834 Platform = ArchEnd+1;
835 } else
836 Arch = Triple;
837
Daniel Dunbar7424b8a2009-03-17 19:00:50 +0000838 // Normalize Arch a bit.
839 //
840 // FIXME: This is very incomplete.
841 if (Arch == "i686")
842 Arch = "i386";
843 else if (Arch == "amd64")
844 Arch = "x86_64";
845
Daniel Dunbar44119a12009-03-13 12:23:29 +0000846 if (memcmp(&OS[0], "darwin", 6) == 0)
Daniel Dunbar08966ca2009-03-17 20:45:45 +0000847 return createDarwinHostInfo(*this, Arch.c_str(), Platform.c_str(),
848 OS.c_str());
Daniel Dunbard25acaa2009-03-10 23:41:59 +0000849
Daniel Dunbar08966ca2009-03-17 20:45:45 +0000850 return createUnknownHostInfo(*this, Arch.c_str(), Platform.c_str(),
851 OS.c_str());
Daniel Dunbard25acaa2009-03-10 23:41:59 +0000852}