blob: 5f29195f519277d4198a7939795dc795034be0ba [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 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 Dunbar07c9a1d2009-03-17 22:47:06 +0000117 } else if (!strcmp(Opt, "print-bindings")) {
118 CCCPrintBindings = true;
Daniel Dunbarb282ced2009-03-10 20:52:46 +0000119 } else if (!strcmp(Opt, "cxx")) {
120 CCCIsCXX = true;
121 } else if (!strcmp(Opt, "echo")) {
122 CCCEcho = true;
123
124 } else if (!strcmp(Opt, "no-clang")) {
125 CCCNoClang = true;
126 } else if (!strcmp(Opt, "no-clang-cxx")) {
127 CCCNoClangCXX = true;
128 } else if (!strcmp(Opt, "no-clang-cpp")) {
129 CCCNoClangCPP = true;
130 } else if (!strcmp(Opt, "clang-archs")) {
131 assert(Start+1 < End && "FIXME: -ccc- argument handling.");
132 const char *Cur = *++Start;
133
134 for (;;) {
135 const char *Next = strchr(Cur, ',');
136
137 if (Next) {
138 CCCClangArchs.insert(std::string(Cur, Next));
139 Cur = Next + 1;
140 } else {
141 CCCClangArchs.insert(std::string(Cur));
142 break;
143 }
144 }
145
Daniel Dunbard25acaa2009-03-10 23:41:59 +0000146 } else if (!strcmp(Opt, "host-triple")) {
Daniel Dunbarb282ced2009-03-10 20:52:46 +0000147 assert(Start+1 < End && "FIXME: -ccc- argument handling.");
Daniel Dunbard25acaa2009-03-10 23:41:59 +0000148 HostTriple = *++Start;
Daniel Dunbarb282ced2009-03-10 20:52:46 +0000149
150 } else {
151 // FIXME: Error handling.
152 llvm::errs() << "invalid option: " << *Start << "\n";
153 exit(1);
154 }
155 }
Daniel Dunbard25acaa2009-03-10 23:41:59 +0000156
Daniel Dunbarb282ced2009-03-10 20:52:46 +0000157 ArgList *Args = ParseArgStrings(Start, End);
158
Daniel Dunbar08966ca2009-03-17 20:45:45 +0000159 Host = GetHostInfo(HostTriple);
Daniel Dunbar43a36802009-03-17 21:29:52 +0000160 // FIXME: This shouldn't live inside Driver, the default tool chain
161 // is part of the compilation (it is arg dependent).
Daniel Dunbarcc006892009-03-13 00:51:18 +0000162 DefaultToolChain = Host->getToolChain(*Args);
163
Daniel Dunbarb282ced2009-03-10 20:52:46 +0000164 // FIXME: This behavior shouldn't be here.
165 if (CCCPrintOptions) {
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000166 PrintOptions(*Args);
Daniel Dunbar88c9eae2009-03-13 17:24:34 +0000167 return 0;
Daniel Dunbarb282ced2009-03-10 20:52:46 +0000168 }
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000169
Daniel Dunbarcc006892009-03-13 00:51:18 +0000170 if (!HandleImmediateArgs(*Args))
171 return 0;
172
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000173 // Construct the list of abstract actions to perform for this
174 // compilation.
Daniel Dunbara790d372009-03-12 18:24:49 +0000175 ActionList Actions;
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000176 if (Host->useDriverDriver())
177 BuildUniversalActions(*Args, Actions);
178 else
179 BuildActions(*Args, Actions);
180
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000181 if (CCCPrintActions) {
Daniel Dunbar494646b2009-03-13 12:19:02 +0000182 PrintActions(*Args, Actions);
Daniel Dunbar88c9eae2009-03-13 17:24:34 +0000183 return 0;
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000184 }
Daniel Dunbar88c9eae2009-03-13 17:24:34 +0000185
Daniel Dunbar9d625e12009-03-16 06:42:30 +0000186 // The compilation takes ownership of Args.
187 Compilation *C = new Compilation(*DefaultToolChain, Args);
188 BuildJobs(*C, Actions);
Daniel Dunbarc413f822009-03-15 01:38:15 +0000189
190 return C;
Daniel Dunbarb282ced2009-03-10 20:52:46 +0000191}
192
Daniel Dunbara790d372009-03-12 18:24:49 +0000193void Driver::PrintOptions(const ArgList &Args) const {
Daniel Dunbar7dc2a042009-03-05 06:38:47 +0000194 unsigned i = 0;
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000195 for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
Daniel Dunbar7dc2a042009-03-05 06:38:47 +0000196 it != ie; ++it, ++i) {
197 Arg *A = *it;
198 llvm::errs() << "Option " << i << " - "
199 << "Name: \"" << A->getOption().getName() << "\", "
200 << "Values: {";
201 for (unsigned j = 0; j < A->getNumValues(); ++j) {
202 if (j)
203 llvm::errs() << ", ";
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000204 llvm::errs() << '"' << A->getValue(Args, j) << '"';
Daniel Dunbar7dc2a042009-03-05 06:38:47 +0000205 }
206 llvm::errs() << "}\n";
Daniel Dunbar7dc2a042009-03-05 06:38:47 +0000207 }
Daniel Dunbar63c4da92009-03-02 19:59:07 +0000208}
Daniel Dunbard25acaa2009-03-10 23:41:59 +0000209
Daniel Dunbarcc006892009-03-13 00:51:18 +0000210void Driver::PrintVersion() const {
211 // FIXME: Get a reasonable version number.
212
213 // FIXME: The following handlers should use a callback mechanism, we
214 // don't know what the client would like to do.
215 llvm::outs() << "ccc version 1.0" << "\n";
216}
217
218bool Driver::HandleImmediateArgs(const ArgList &Args) {
219 // The order these options are handled in in gcc is all over the
220 // place, but we don't expect inconsistencies w.r.t. that to matter
221 // in practice.
222 if (Args.hasArg(options::OPT_v) ||
223 Args.hasArg(options::OPT__HASH_HASH_HASH)) {
224 PrintVersion();
225 SuppressMissingInputWarning = true;
226 }
227
228 // FIXME: The following handlers should use a callback mechanism, we
229 // don't know what the client would like to do.
230 if (Arg *A = Args.getLastArg(options::OPT_print_file_name_EQ)) {
231 llvm::outs() << GetFilePath(A->getValue(Args)).toString() << "\n";
232 return false;
233 }
234
235 if (Arg *A = Args.getLastArg(options::OPT_print_prog_name_EQ)) {
236 llvm::outs() << GetProgramPath(A->getValue(Args)).toString() << "\n";
237 return false;
238 }
239
Daniel Dunbarb043ebd2009-03-13 01:01:44 +0000240 if (Args.hasArg(options::OPT_print_libgcc_file_name)) {
Daniel Dunbarcc006892009-03-13 00:51:18 +0000241 llvm::outs() << GetProgramPath("libgcc.a").toString() << "\n";
242 return false;
243 }
244
245 return true;
246}
247
Daniel Dunbar494646b2009-03-13 12:19:02 +0000248static unsigned PrintActions1(const ArgList &Args,
249 Action *A,
250 std::map<Action*, unsigned> &Ids) {
251 if (Ids.count(A))
252 return Ids[A];
253
254 std::string str;
255 llvm::raw_string_ostream os(str);
256
257 os << Action::getClassName(A->getKind()) << ", ";
258 if (InputAction *IA = dyn_cast<InputAction>(A)) {
Daniel Dunbardd863aa2009-03-13 17:46:02 +0000259 os << "\"" << IA->getInputArg().getValue(Args) << "\"";
Daniel Dunbar494646b2009-03-13 12:19:02 +0000260 } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
261 os << "\"" << BIA->getArchName() << "\", "
262 << "{" << PrintActions1(Args, *BIA->begin(), Ids) << "}";
263 } else {
264 os << "{";
265 for (Action::iterator it = A->begin(), ie = A->end(); it != ie;) {
266 os << PrintActions1(Args, *it, Ids);
267 ++it;
268 if (it != ie)
269 os << ", ";
270 }
271 os << "}";
272 }
273
274 unsigned Id = Ids.size();
275 Ids[A] = Id;
Daniel Dunbar9dc28b82009-03-13 17:20:20 +0000276 llvm::errs() << Id << ": " << os.str() << ", "
Daniel Dunbar494646b2009-03-13 12:19:02 +0000277 << types::getTypeName(A->getType()) << "\n";
278
279 return Id;
280}
281
282void Driver::PrintActions(const ArgList &Args,
283 const ActionList &Actions) const {
284 std::map<Action*, unsigned> Ids;
285 for (ActionList::const_iterator it = Actions.begin(), ie = Actions.end();
Daniel Dunbar9dc28b82009-03-13 17:20:20 +0000286 it != ie; ++it)
Daniel Dunbar494646b2009-03-13 12:19:02 +0000287 PrintActions1(Args, *it, Ids);
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000288}
289
Daniel Dunbar47d762e2009-03-13 22:12:33 +0000290void Driver::BuildUniversalActions(ArgList &Args, ActionList &Actions) const {
Daniel Dunbarb1873cd2009-03-13 20:33:35 +0000291 // Collect the list of architectures. Duplicates are allowed, but
292 // should only be handled once (in the order seen).
293 llvm::StringSet<> ArchNames;
294 llvm::SmallVector<const char *, 4> Archs;
Daniel Dunbarfba157b2009-03-12 18:40:18 +0000295 for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
296 it != ie; ++it) {
297 Arg *A = *it;
298
299 if (A->getOption().getId() == options::OPT_arch) {
Daniel Dunbarb1873cd2009-03-13 20:33:35 +0000300 const char *Name = A->getValue(Args);
301
Daniel Dunbarfba157b2009-03-12 18:40:18 +0000302 // FIXME: We need to handle canonicalization of the specified
303 // arch?
304
Daniel Dunbarb1873cd2009-03-13 20:33:35 +0000305 if (ArchNames.insert(Name))
306 Archs.push_back(Name);
Daniel Dunbarfba157b2009-03-12 18:40:18 +0000307 }
308 }
309
310 // When there is no explicit arch for this platform, get one from
311 // the host so that -Xarch_ is handled correctly.
312 if (!Archs.size()) {
Daniel Dunbar43a36802009-03-17 21:29:52 +0000313 const char *Arch = DefaultToolChain->getArchName().c_str();
Daniel Dunbarb1873cd2009-03-13 20:33:35 +0000314 Archs.push_back(Arch);
Daniel Dunbarfba157b2009-03-12 18:40:18 +0000315 }
316
317 // FIXME: We killed off some others but these aren't yet detected in
318 // a functional manner. If we added information to jobs about which
319 // "auxiliary" files they wrote then we could detect the conflict
320 // these cause downstream.
321 if (Archs.size() > 1) {
322 // No recovery needed, the point of this is just to prevent
323 // overwriting the same files.
324 if (const Arg *A = Args.getLastArg(options::OPT_M_Group))
325 Diag(clang::diag::err_drv_invalid_opt_with_multiple_archs)
326 << A->getOption().getName();
327 if (const Arg *A = Args.getLastArg(options::OPT_save_temps))
328 Diag(clang::diag::err_drv_invalid_opt_with_multiple_archs)
329 << A->getOption().getName();
330 }
331
332 ActionList SingleActions;
333 BuildActions(Args, SingleActions);
334
335 // Add in arch binding and lipo (if necessary) for every top level
336 // action.
337 for (unsigned i = 0, e = SingleActions.size(); i != e; ++i) {
338 Action *Act = SingleActions[i];
339
340 // Make sure we can lipo this kind of output. If not (and it is an
341 // actual output) then we disallow, since we can't create an
342 // output file with the right name without overwriting it. We
343 // could remove this oddity by just changing the output names to
344 // include the arch, which would also fix
345 // -save-temps. Compatibility wins for now.
346
Daniel Dunbardd863aa2009-03-13 17:46:02 +0000347 if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
Daniel Dunbarfba157b2009-03-12 18:40:18 +0000348 Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
349 << types::getTypeName(Act->getType());
350
351 ActionList Inputs;
Daniel Dunbarb1873cd2009-03-13 20:33:35 +0000352 for (unsigned i = 0, e = Archs.size(); i != e; ++i )
353 Inputs.push_back(new BindArchAction(Act, Archs[i]));
Daniel Dunbarfba157b2009-03-12 18:40:18 +0000354
355 // Lipo if necessary, We do it this way because we need to set the
356 // arch flag so that -Xarch_ gets overwritten.
357 if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
358 Actions.append(Inputs.begin(), Inputs.end());
359 else
360 Actions.push_back(new LipoJobAction(Inputs, Act->getType()));
361 }
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000362}
363
Daniel Dunbar47d762e2009-03-13 22:12:33 +0000364void Driver::BuildActions(ArgList &Args, ActionList &Actions) const {
Daniel Dunbar207a56d2009-03-12 23:55:14 +0000365 // Start by constructing the list of inputs and their types.
366
Daniel Dunbar5cb75d62009-03-13 17:57:10 +0000367 // Track the current user specified (-x) input. We also explicitly
368 // track the argument used to set the type; we only want to claim
369 // the type when we actually use it, so we warn about unused -x
370 // arguments.
371 types::ID InputType = types::TY_Nothing;
372 Arg *InputTypeArg = 0;
373
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000374 llvm::SmallVector<std::pair<types::ID, const Arg*>, 16> Inputs;
375 for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
376 it != ie; ++it) {
377 Arg *A = *it;
378
379 if (isa<InputOption>(A->getOption())) {
380 const char *Value = A->getValue(Args);
381 types::ID Ty = types::TY_INVALID;
382
383 // Infer the input type if necessary.
Daniel Dunbar5cb75d62009-03-13 17:57:10 +0000384 if (InputType == types::TY_Nothing) {
385 // If there was an explicit arg for this, claim it.
386 if (InputTypeArg)
387 InputTypeArg->claim();
388
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000389 // stdin must be handled specially.
390 if (memcmp(Value, "-", 2) == 0) {
391 // If running with -E, treat as a C input (this changes the
392 // builtin macros, for example). This may be overridden by
393 // -ObjC below.
394 //
395 // Otherwise emit an error but still use a valid type to
396 // avoid spurious errors (e.g., no inputs).
Daniel Dunbare9c70fa2009-03-15 00:48:16 +0000397 if (!Args.hasArg(options::OPT_E, false))
Daniel Dunbard724e332009-03-12 09:13:48 +0000398 Diag(clang::diag::err_drv_unknown_stdin_type);
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000399 Ty = types::TY_C;
400 } else {
401 // Otherwise lookup by extension, and fallback to ObjectType
402 // if not found.
403 if (const char *Ext = strrchr(Value, '.'))
404 Ty = types::lookupTypeForExtension(Ext + 1);
405 if (Ty == types::TY_INVALID)
406 Ty = types::TY_Object;
407 }
408
409 // -ObjC and -ObjC++ override the default language, but only
410 // -for "source files". We just treat everything that isn't a
411 // -linker input as a source file.
412 //
413 // FIXME: Clean this up if we move the phase sequence into the
414 // type.
415 if (Ty != types::TY_Object) {
416 if (Args.hasArg(options::OPT_ObjC))
417 Ty = types::TY_ObjC;
418 else if (Args.hasArg(options::OPT_ObjCXX))
419 Ty = types::TY_ObjCXX;
420 }
421 } else {
422 assert(InputTypeArg && "InputType set w/o InputTypeArg");
423 InputTypeArg->claim();
424 Ty = InputType;
425 }
426
427 // Check that the file exists. It isn't clear this is worth
428 // doing, since the tool presumably does this anyway, and this
429 // just adds an extra stat to the equation, but this is gcc
430 // compatible.
Daniel Dunbar321c12d2009-03-15 01:40:22 +0000431 A->claim();
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000432 if (memcmp(Value, "-", 2) != 0 && !llvm::sys::Path(Value).exists())
Daniel Dunbard724e332009-03-12 09:13:48 +0000433 Diag(clang::diag::err_drv_no_such_file) << A->getValue(Args);
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000434 else
435 Inputs.push_back(std::make_pair(Ty, A));
436
437 } else if (A->getOption().isLinkerInput()) {
438 // Just treat as object type, we could make a special type for
439 // this if necessary.
Daniel Dunbar321c12d2009-03-15 01:40:22 +0000440 A->claim();
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000441 Inputs.push_back(std::make_pair(types::TY_Object, A));
442
443 } else if (A->getOption().getId() == options::OPT_x) {
444 InputTypeArg = A;
445 InputType = types::lookupTypeForTypeSpecifier(A->getValue(Args));
446
447 // Follow gcc behavior and treat as linker input for invalid -x
448 // options. Its not clear why we shouldn't just revert to
449 // unknown; but this isn't very important, we might as well be
450 // bug comatible.
451 if (!InputType) {
Daniel Dunbard724e332009-03-12 09:13:48 +0000452 Diag(clang::diag::err_drv_unknown_language) << A->getValue(Args);
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000453 InputType = types::TY_Object;
454 }
455 }
456 }
457
Daniel Dunbar5a5ec5c2009-03-13 00:17:48 +0000458 if (!SuppressMissingInputWarning && Inputs.empty()) {
Daniel Dunbar207a56d2009-03-12 23:55:14 +0000459 Diag(clang::diag::err_drv_no_input_files);
460 return;
461 }
462
463 // Determine which compilation mode we are in. We look for options
464 // which affect the phase, starting with the earliest phases, and
465 // record which option we used to determine the final phase.
Daniel Dunbar85cb3592009-03-13 11:38:42 +0000466 Arg *FinalPhaseArg = 0;
467 phases::ID FinalPhase;
Daniel Dunbar207a56d2009-03-12 23:55:14 +0000468
469 // -{E,M,MM} only run the preprocessor.
Daniel Dunbar85cb3592009-03-13 11:38:42 +0000470 if ((FinalPhaseArg = Args.getLastArg(options::OPT_E)) ||
471 (FinalPhaseArg = Args.getLastArg(options::OPT_M)) ||
472 (FinalPhaseArg = Args.getLastArg(options::OPT_MM))) {
473 FinalPhase = phases::Preprocess;
Daniel Dunbar207a56d2009-03-12 23:55:14 +0000474
Daniel Dunbare9c70fa2009-03-15 00:48:16 +0000475 // -{fsyntax-only,-analyze,emit-llvm,S} only run up to the compiler.
476 } else if ((FinalPhaseArg = Args.getLastArg(options::OPT_fsyntax_only)) ||
477 (FinalPhaseArg = Args.getLastArg(options::OPT__analyze)) ||
478 (FinalPhaseArg = Args.getLastArg(options::OPT_emit_llvm)) ||
Daniel Dunbar85cb3592009-03-13 11:38:42 +0000479 (FinalPhaseArg = Args.getLastArg(options::OPT_S))) {
480 FinalPhase = phases::Compile;
Daniel Dunbar207a56d2009-03-12 23:55:14 +0000481
482 // -c only runs up to the assembler.
Daniel Dunbar85cb3592009-03-13 11:38:42 +0000483 } else if ((FinalPhaseArg = Args.getLastArg(options::OPT_c))) {
484 FinalPhase = phases::Assemble;
Daniel Dunbar207a56d2009-03-12 23:55:14 +0000485
486 // Otherwise do everything.
487 } else
Daniel Dunbar85cb3592009-03-13 11:38:42 +0000488 FinalPhase = phases::Link;
Daniel Dunbar207a56d2009-03-12 23:55:14 +0000489
Daniel Dunbar207a56d2009-03-12 23:55:14 +0000490 // Reject -Z* at the top level, these options should never have been
491 // exposed by gcc.
492 if (Arg *A = Args.getLastArg(options::OPT_Z))
493 Diag(clang::diag::err_drv_use_of_Z_option) << A->getValue(Args);
494
Daniel Dunbar85cb3592009-03-13 11:38:42 +0000495 // Construct the actions to perform.
496 ActionList LinkerInputs;
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000497 for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
Daniel Dunbar85cb3592009-03-13 11:38:42 +0000498 types::ID InputType = Inputs[i].first;
499 const Arg *InputArg = Inputs[i].second;
500
501 unsigned NumSteps = types::getNumCompilationPhases(InputType);
502 assert(NumSteps && "Invalid number of steps!");
503
504 // If the first step comes after the final phase we are doing as
505 // part of this compilation, warn the user about it.
506 phases::ID InitialPhase = types::getCompilationPhase(InputType, 0);
507 if (InitialPhase > FinalPhase) {
508 Diag(clang::diag::warn_drv_input_file_unused)
509 << InputArg->getValue(Args)
510 << getPhaseName(InitialPhase)
511 << FinalPhaseArg->getOption().getName();
512 continue;
513 }
514
515 // Build the pipeline for this file.
516 Action *Current = new InputAction(*InputArg, InputType);
517 for (unsigned i = 0; i != NumSteps; ++i) {
518 phases::ID Phase = types::getCompilationPhase(InputType, i);
519
520 // We are done if this step is past what the user requested.
521 if (Phase > FinalPhase)
522 break;
523
524 // Queue linker inputs.
525 if (Phase == phases::Link) {
526 assert(i + 1 == NumSteps && "linking must be final compilation step.");
527 LinkerInputs.push_back(Current);
528 Current = 0;
529 break;
530 }
531
532 // Otherwise construct the appropriate action.
533 Current = ConstructPhaseAction(Args, Phase, Current);
534 if (Current->getType() == types::TY_Nothing)
535 break;
536 }
537
538 // If we ended with something, add to the output list.
539 if (Current)
540 Actions.push_back(Current);
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000541 }
Daniel Dunbar85cb3592009-03-13 11:38:42 +0000542
543 // Add a link action if necessary.
544 if (!LinkerInputs.empty())
545 Actions.push_back(new LinkJobAction(LinkerInputs, types::TY_Image));
546}
547
548Action *Driver::ConstructPhaseAction(const ArgList &Args, phases::ID Phase,
549 Action *Input) const {
550 // Build the appropriate action.
551 switch (Phase) {
552 case phases::Link: assert(0 && "link action invalid here.");
553 case phases::Preprocess: {
554 types::ID OutputTy = types::getPreprocessedType(Input->getType());
555 assert(OutputTy != types::TY_INVALID &&
556 "Cannot preprocess this input type!");
557 return new PreprocessJobAction(Input, OutputTy);
558 }
559 case phases::Precompile:
560 return new PrecompileJobAction(Input, types::TY_PCH);
561 case phases::Compile: {
562 if (Args.hasArg(options::OPT_fsyntax_only)) {
563 return new CompileJobAction(Input, types::TY_Nothing);
564 } else if (Args.hasArg(options::OPT__analyze)) {
565 return new AnalyzeJobAction(Input, types::TY_Plist);
566 } else if (Args.hasArg(options::OPT_emit_llvm)) {
567 types::ID Output =
568 Args.hasArg(options::OPT_S) ? types::TY_LLVMAsm : types::TY_LLVMBC;
569 return new CompileJobAction(Input, Output);
570 } else {
571 return new CompileJobAction(Input, types::TY_PP_Asm);
572 }
573 }
574 case phases::Assemble:
575 return new AssembleJobAction(Input, types::TY_Object);
576 }
577
578 assert(0 && "invalid phase in ConstructPhaseAction");
579 return 0;
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000580}
581
Daniel Dunbar7ce6add2009-03-16 06:56:51 +0000582void Driver::BuildJobs(Compilation &C, const ActionList &Actions) const {
583 bool SaveTemps = C.getArgs().hasArg(options::OPT_save_temps);
584 bool UsePipes = C.getArgs().hasArg(options::OPT_pipe);
585
586 // -save-temps inhibits pipes.
587 if (SaveTemps && UsePipes) {
588 Diag(clang::diag::warn_drv_pipe_ignored_with_save_temps);
589 UsePipes = true;
590 }
591
592 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
593
594 // It is an error to provide a -o option if we are making multiple
595 // output files.
596 if (FinalOutput) {
597 unsigned NumOutputs = 0;
598 for (ActionList::const_iterator it = Actions.begin(), ie = Actions.end();
599 it != ie; ++it)
600 if ((*it)->getType() != types::TY_Nothing)
601 ++NumOutputs;
602
603 if (NumOutputs > 1) {
604 Diag(clang::diag::err_drv_output_argument_with_multiple_files);
605 FinalOutput = 0;
606 }
607 }
608
609 for (ActionList::const_iterator it = Actions.begin(), ie = Actions.end();
610 it != ie; ++it) {
611 Action *A = *it;
612
613 // If we are linking an image for multiple archs then the linker
614 // wants -arch_multiple and -final_output <final image
615 // name>. Unfortunately, this doesn't fit in cleanly because we
616 // have to pass this information down.
617 //
618 // FIXME: This is a hack; find a cleaner way to integrate this
619 // into the process.
620 const char *LinkingOutput = 0;
621 if (isa<LinkJobAction>(A)) {
622 if (FinalOutput)
623 LinkingOutput = FinalOutput->getValue(C.getArgs());
624 else
625 LinkingOutput = DefaultImageName.c_str();
626 }
627
628 InputInfo II;
629 BuildJobsForAction(C,
630 A, DefaultToolChain,
631 /*CanAcceptPipe*/ true,
632 /*AtTopLevel*/ true,
633 /*LinkingOutput*/ LinkingOutput,
634 II);
635 }
Daniel Dunbar9d625e12009-03-16 06:42:30 +0000636
637 // If there were no errors, warn about any unused arguments.
638 for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end();
639 it != ie; ++it) {
640 Arg *A = *it;
641
642 // FIXME: It would be nice to be able to send the argument to the
643 // Diagnostic, so that extra values, position, and so on could be
644 // printed.
645 if (!A->isClaimed())
646 Diag(clang::diag::warn_drv_unused_argument)
647 << A->getOption().getName();
648 }
Daniel Dunbar47d762e2009-03-13 22:12:33 +0000649}
650
Daniel Dunbar7ce6add2009-03-16 06:56:51 +0000651void Driver::BuildJobsForAction(Compilation &C,
652 const Action *A,
653 const ToolChain *TC,
654 bool CanAcceptPipe,
655 bool AtTopLevel,
656 const char *LinkingOutput,
657 InputInfo &Result) const {
658 if (const InputAction *IA = dyn_cast<InputAction>(A)) {
659 const char *Name = IA->getInputArg().getValue(C.getArgs());
660 Result = InputInfo(Name, A->getType(), Name);
661 return;
662 }
663
664 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
665 const char *ArchName = BAA->getArchName();
666 BuildJobsForAction(C,
667 *BAA->begin(),
668 Host->getToolChain(C.getArgs(), ArchName),
669 CanAcceptPipe,
670 AtTopLevel,
671 LinkingOutput,
672 Result);
673 return;
674 }
675
676 const JobAction *JA = cast<JobAction>(A);
677 const Tool &T = TC->SelectTool(C, *JA);
678
679 // See if we should use an integrated preprocessor. We do so when we
680 // have exactly one input, since this is the only use case we care
681 // about (irrelevant since we don't support combine yet).
682 bool UseIntegratedCPP = false;
683 const ActionList *Inputs = &A->getInputs();
684 if (Inputs->size() == 1 && isa<PreprocessJobAction>(*Inputs->begin())) {
685 if (!C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
686 !C.getArgs().hasArg(options::OPT_traditional_cpp) &&
687 !C.getArgs().hasArg(options::OPT_save_temps) &&
688 T.hasIntegratedCPP()) {
689 UseIntegratedCPP = true;
690 Inputs = &(*Inputs)[0]->getInputs();
691 }
692 }
693
694 // Only use pipes when there is exactly one input.
695 bool TryToUsePipeInput = Inputs->size() == 1 && T.acceptsPipedInput();
696 llvm::SmallVector<InputInfo, 4> InputInfos;
697 for (ActionList::const_iterator it = Inputs->begin(), ie = Inputs->end();
698 it != ie; ++it) {
699 InputInfo II;
700 BuildJobsForAction(C, *it, TC, TryToUsePipeInput,
701 /*AtTopLevel*/false,
702 LinkingOutput,
703 II);
704 InputInfos.push_back(II);
705 }
706
707 // Determine if we should output to a pipe.
708 bool OutputToPipe = false;
709 if (CanAcceptPipe && T.canPipeOutput()) {
710 // Some actions default to writing to a pipe if they are the top
711 // level phase and there was no user override.
712 //
713 // FIXME: Is there a better way to handle this?
714 if (AtTopLevel) {
715 if (isa<PreprocessJobAction>(A) && !C.getArgs().hasArg(options::OPT_o))
716 OutputToPipe = true;
717 } else if (C.getArgs().hasArg(options::OPT_pipe))
718 OutputToPipe = true;
719 }
720
721 // Figure out where to put the job (pipes).
722 Job *Dest = &C.getJobs();
723 if (InputInfos[0].isPipe()) {
Daniel Dunbar01fb26a2009-03-17 17:53:55 +0000724 assert(TryToUsePipeInput && "Unrequested pipe!");
Daniel Dunbar7ce6add2009-03-16 06:56:51 +0000725 assert(InputInfos.size() == 1 && "Unexpected pipe with multiple inputs.");
726 Dest = &InputInfos[0].getPipe();
727 }
728
729 // Always use the first input as the base input.
730 const char *BaseInput = InputInfos[0].getBaseInput();
Daniel Dunbar01fb26a2009-03-17 17:53:55 +0000731
732 // Determine the place to write output to (nothing, pipe, or
733 // filename) and where to put the new job.
Daniel Dunbar01fb26a2009-03-17 17:53:55 +0000734 if (JA->getType() == types::TY_Nothing) {
Daniel Dunbar07c9a1d2009-03-17 22:47:06 +0000735 Result = InputInfo(A->getType(), BaseInput);
Daniel Dunbar01fb26a2009-03-17 17:53:55 +0000736 } else if (OutputToPipe) {
737 // Append to current piped job or create a new one as appropriate.
Daniel Dunbar07c9a1d2009-03-17 22:47:06 +0000738 PipedJob *PJ = dyn_cast<PipedJob>(Dest);
739 if (!PJ) {
740 PJ = new PipedJob();
741 cast<JobList>(Dest)->addJob(PJ);
Daniel Dunbar01fb26a2009-03-17 17:53:55 +0000742 }
Daniel Dunbar07c9a1d2009-03-17 22:47:06 +0000743 Result = InputInfo(PJ, A->getType(), BaseInput);
Daniel Dunbar01fb26a2009-03-17 17:53:55 +0000744 } else {
Daniel Dunbar07c9a1d2009-03-17 22:47:06 +0000745 Result = InputInfo(GetNamedOutputPath(C, *JA, BaseInput, AtTopLevel),
746 A->getType(), BaseInput);
Daniel Dunbar01fb26a2009-03-17 17:53:55 +0000747 }
748
Daniel Dunbar07c9a1d2009-03-17 22:47:06 +0000749 if (CCCPrintBindings) {
750 llvm::errs() << "bind - \"" << T.getName() << "\", inputs: [";
751 for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
752 llvm::errs() << InputInfos[i].getAsString();
753 if (i + 1 != e)
754 llvm::errs() << ", ";
755 }
756 llvm::errs() << "], output: " << Result.getAsString() << "\n";
757 } else {
758 assert(0 && "FIXME: Make the job.");
759 }
Daniel Dunbar7ce6add2009-03-16 06:56:51 +0000760}
761
Daniel Dunbar01fb26a2009-03-17 17:53:55 +0000762const char *Driver::GetNamedOutputPath(Compilation &C,
763 const JobAction &JA,
764 const char *BaseInput,
765 bool AtTopLevel) const {
766 // Output to a user requested destination?
767 if (AtTopLevel) {
768 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
769 return C.addResultFile(FinalOutput->getValue(C.getArgs()));
770 }
771
772 // Output to a temporary file?
773 if (!AtTopLevel && !C.getArgs().hasArg(options::OPT_save_temps)) {
774 // FIXME: Get temporary name.
775 std::string Name("/tmp/foo");
776 Name += '.';
777 Name += types::getTypeTempSuffix(JA.getType());
778 return C.addTempFile(C.getArgs().MakeArgString(Name.c_str()));
779 }
780
781 llvm::sys::Path BasePath(BaseInput);
782 std::string BaseName(BasePath.getBasename());
783
784 // Determine what the derived output name should be.
785 const char *NamedOutput;
786 if (JA.getType() == types::TY_Image) {
787 NamedOutput = DefaultImageName.c_str();
788 } else {
789 const char *Suffix = types::getTypeTempSuffix(JA.getType());
790 assert(Suffix && "All types used for output should have a suffix.");
791
792 std::string::size_type End = std::string::npos;
793 if (!types::appendSuffixForType(JA.getType()))
794 End = BaseName.rfind('.');
795 std::string Suffixed(BaseName.substr(0, End));
796 Suffixed += '.';
797 Suffixed += Suffix;
798 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
799 }
800
801 // As an annoying special case, PCH generation doesn't strip the
802 // pathname.
803 if (JA.getType() == types::TY_PCH) {
804 BasePath.eraseComponent();
805 BasePath.appendComponent(NamedOutput);
806 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()));
807 } else {
808 return C.addResultFile(NamedOutput);
809 }
810}
811
Daniel Dunbare1cef7d2009-03-16 05:25:36 +0000812llvm::sys::Path Driver::GetFilePath(const char *Name,
813 const ToolChain *TC) const {
Daniel Dunbarcc006892009-03-13 00:51:18 +0000814 // FIXME: Implement.
Daniel Dunbare1cef7d2009-03-16 05:25:36 +0000815 if (!TC) TC = DefaultToolChain;
816
Daniel Dunbarcc006892009-03-13 00:51:18 +0000817 return llvm::sys::Path(Name);
818}
819
Daniel Dunbare1cef7d2009-03-16 05:25:36 +0000820llvm::sys::Path Driver::GetProgramPath(const char *Name,
821 const ToolChain *TC) const {
Daniel Dunbarcc006892009-03-13 00:51:18 +0000822 // FIXME: Implement.
Daniel Dunbare1cef7d2009-03-16 05:25:36 +0000823 if (!TC) TC = DefaultToolChain;
824
Daniel Dunbarcc006892009-03-13 00:51:18 +0000825 return llvm::sys::Path(Name);
826}
827
Daniel Dunbar08966ca2009-03-17 20:45:45 +0000828const HostInfo *Driver::GetHostInfo(const char *Triple) const {
Daniel Dunbard25acaa2009-03-10 23:41:59 +0000829 // Dice into arch, platform, and OS. This matches
830 // arch,platform,os = '(.*?)-(.*?)-(.*?)'
831 // and missing fields are left empty.
832 std::string Arch, Platform, OS;
833
834 if (const char *ArchEnd = strchr(Triple, '-')) {
835 Arch = std::string(Triple, ArchEnd);
836
837 if (const char *PlatformEnd = strchr(ArchEnd+1, '-')) {
838 Platform = std::string(ArchEnd+1, PlatformEnd);
839 OS = PlatformEnd+1;
840 } else
841 Platform = ArchEnd+1;
842 } else
843 Arch = Triple;
844
Daniel Dunbar7424b8a2009-03-17 19:00:50 +0000845 // Normalize Arch a bit.
846 //
847 // FIXME: This is very incomplete.
848 if (Arch == "i686")
849 Arch = "i386";
850 else if (Arch == "amd64")
851 Arch = "x86_64";
852
Daniel Dunbar44119a12009-03-13 12:23:29 +0000853 if (memcmp(&OS[0], "darwin", 6) == 0)
Daniel Dunbar08966ca2009-03-17 20:45:45 +0000854 return createDarwinHostInfo(*this, Arch.c_str(), Platform.c_str(),
855 OS.c_str());
Daniel Dunbard25acaa2009-03-10 23:41:59 +0000856
Daniel Dunbar08966ca2009-03-17 20:45:45 +0000857 return createUnknownHostInfo(*this, Arch.c_str(), Platform.c_str(),
858 OS.c_str());
Daniel Dunbard25acaa2009-03-10 23:41:59 +0000859}