blob: 84f3428c62846c0287d119244e7059ec3e6237c3 [file] [log] [blame]
Daniel Dunbar3ede8d02009-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 Dunbar3ede8d02009-03-02 19:59:07 +000010#include "clang/Driver/Driver.h"
Daniel Dunbar3ede8d02009-03-02 19:59:07 +000011
Daniel Dunbar53ec5522009-03-12 07:58:46 +000012#include "clang/Driver/Action.h"
Daniel Dunbar1b3bb6e2009-03-04 20:49:20 +000013#include "clang/Driver/Arg.h"
14#include "clang/Driver/ArgList.h"
15#include "clang/Driver/Compilation.h"
Daniel Dunbar4ad4b3e2009-03-12 08:55:43 +000016#include "clang/Driver/DriverDiagnostic.h"
Daniel Dunbardd98e2c2009-03-10 23:41:59 +000017#include "clang/Driver/HostInfo.h"
Daniel Dunbarf353c8c2009-03-16 06:56:51 +000018#include "clang/Driver/Job.h"
Daniel Dunbar06482622009-03-05 06:38:47 +000019#include "clang/Driver/Option.h"
Daniel Dunbar1b3bb6e2009-03-04 20:49:20 +000020#include "clang/Driver/Options.h"
Daniel Dunbarf353c8c2009-03-16 06:56:51 +000021#include "clang/Driver/Tool.h"
22#include "clang/Driver/ToolChain.h"
Daniel Dunbar53ec5522009-03-12 07:58:46 +000023#include "clang/Driver/Types.h"
Daniel Dunbar06482622009-03-05 06:38:47 +000024
Daniel Dunbar13689542009-03-13 20:33:35 +000025#include "llvm/ADT/StringSet.h"
Daniel Dunbar8f25c792009-03-18 01:38:48 +000026#include "llvm/Support/PrettyStackTrace.h"
Daniel Dunbar06482622009-03-05 06:38:47 +000027#include "llvm/Support/raw_ostream.h"
Daniel Dunbar53ec5522009-03-12 07:58:46 +000028#include "llvm/System/Path.h"
Daniel Dunbarba102132009-03-13 12:19:02 +000029
Daniel Dunbarf353c8c2009-03-16 06:56:51 +000030#include "InputInfo.h"
31
Daniel Dunbarba102132009-03-13 12:19:02 +000032#include <map>
33
Daniel Dunbar1b3bb6e2009-03-04 20:49:20 +000034using namespace clang::driver;
35
Daniel Dunbardd98e2c2009-03-10 23:41:59 +000036Driver::Driver(const char *_Name, const char *_Dir,
Daniel Dunbar4ad4b3e2009-03-12 08:55:43 +000037 const char *_DefaultHostTriple,
Daniel Dunbarf353c8c2009-03-16 06:56:51 +000038 const char *_DefaultImageName,
Daniel Dunbar4ad4b3e2009-03-12 08:55:43 +000039 Diagnostic &_Diags)
40 : Opts(new OptTable()), Diags(_Diags),
Daniel Dunbardd98e2c2009-03-10 23:41:59 +000041 Name(_Name), Dir(_Dir), DefaultHostTriple(_DefaultHostTriple),
Daniel Dunbarf353c8c2009-03-16 06:56:51 +000042 DefaultImageName(_DefaultImageName),
Daniel Dunbardd98e2c2009-03-10 23:41:59 +000043 Host(0),
Daniel Dunbar5c3c1d72009-03-17 22:47:06 +000044 CCCIsCXX(false), CCCEcho(false), CCCPrintBindings(false),
Daniel Dunbar8b1604e2009-03-13 00:17:48 +000045 CCCNoClang(false), CCCNoClangCXX(false), CCCNoClangCPP(false),
46 SuppressMissingInputWarning(false)
Daniel Dunbar365c02f2009-03-10 20:52:46 +000047{
Daniel Dunbar3ede8d02009-03-02 19:59:07 +000048}
49
50Driver::~Driver() {
Daniel Dunbar1b3bb6e2009-03-04 20:49:20 +000051 delete Opts;
Daniel Dunbar7e4534d2009-03-18 01:09:40 +000052 delete Host;
Daniel Dunbar3ede8d02009-03-02 19:59:07 +000053}
54
Daniel Dunbar06482622009-03-05 06:38:47 +000055ArgList *Driver::ParseArgStrings(const char **ArgBegin, const char **ArgEnd) {
Daniel Dunbar8f25c792009-03-18 01:38:48 +000056 llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
Daniel Dunbar06482622009-03-05 06:38:47 +000057 ArgList *Args = new ArgList(ArgBegin, ArgEnd);
58
Daniel Dunbarad2a9af2009-03-13 11:38:42 +000059 // FIXME: Handle '@' args (or at least error on them).
60
Daniel Dunbar06482622009-03-05 06:38:47 +000061 unsigned Index = 0, End = ArgEnd - ArgBegin;
62 while (Index < End) {
Daniel Dunbar41393402009-03-13 01:01:44 +000063 // gcc's handling of empty arguments doesn't make
64 // sense, but this is not a common use case. :)
65 //
66 // We just ignore them here (note that other things may
67 // still take them as arguments).
68 if (Args->getArgString(Index)[0] == '\0') {
69 ++Index;
70 continue;
71 }
72
Daniel Dunbar06482622009-03-05 06:38:47 +000073 unsigned Prev = Index;
74 Arg *A = getOpts().ParseOneArg(*Args, Index, End);
Daniel Dunbar53ec5522009-03-12 07:58:46 +000075 if (A) {
76 if (A->getOption().isUnsupported()) {
Daniel Dunbarb897f5d2009-03-12 09:13:48 +000077 Diag(clang::diag::err_drv_unsupported_opt) << A->getOption().getName();
Daniel Dunbar53ec5522009-03-12 07:58:46 +000078 continue;
79 }
80
Daniel Dunbar06482622009-03-05 06:38:47 +000081 Args->append(A);
Daniel Dunbar53ec5522009-03-12 07:58:46 +000082 }
Daniel Dunbar06482622009-03-05 06:38:47 +000083
84 assert(Index > Prev && "Parser failed to consume argument.");
Daniel Dunbar70c16842009-03-17 04:12:06 +000085 (void) Prev;
Daniel Dunbar06482622009-03-05 06:38:47 +000086 }
87
88 return Args;
89}
90
Daniel Dunbar3ede8d02009-03-02 19:59:07 +000091Compilation *Driver::BuildCompilation(int argc, const char **argv) {
Daniel Dunbar8f25c792009-03-18 01:38:48 +000092 llvm::PrettyStackTraceString CrashInfo("Compilation construction");
93
Daniel Dunbarcb881672009-03-13 00:51:18 +000094 // FIXME: Handle environment options which effect driver behavior,
95 // somewhere (client?). GCC_EXEC_PREFIX, COMPILER_PATH,
96 // LIBRARY_PATH, LPATH, CC_PRINT_OPTIONS, QA_OVERRIDE_GCC3_OPTIONS.
97
98 // FIXME: What are we going to do with -V and -b?
99
100 // FIXME: Handle CCC_ADD_ARGS.
101
Daniel Dunbar365c02f2009-03-10 20:52:46 +0000102 // FIXME: This stuff needs to go into the Compilation, not the
103 // driver.
Daniel Dunbar53ec5522009-03-12 07:58:46 +0000104 bool CCCPrintOptions = false, CCCPrintActions = false;
Daniel Dunbar06482622009-03-05 06:38:47 +0000105
Daniel Dunbar365c02f2009-03-10 20:52:46 +0000106 const char **Start = argv + 1, **End = argv + argc;
Daniel Dunbardd98e2c2009-03-10 23:41:59 +0000107 const char *HostTriple = DefaultHostTriple.c_str();
Daniel Dunbar365c02f2009-03-10 20:52:46 +0000108
109 // Read -ccc args.
110 //
111 // FIXME: We need to figure out where this behavior should
112 // live. Most of it should be outside in the client; the parts that
113 // aren't should have proper options, either by introducing new ones
114 // or by overloading gcc ones like -V or -b.
115 for (; Start != End && memcmp(*Start, "-ccc-", 5) == 0; ++Start) {
116 const char *Opt = *Start + 5;
117
118 if (!strcmp(Opt, "print-options")) {
119 CCCPrintOptions = true;
120 } else if (!strcmp(Opt, "print-phases")) {
Daniel Dunbar53ec5522009-03-12 07:58:46 +0000121 CCCPrintActions = true;
Daniel Dunbar5c3c1d72009-03-17 22:47:06 +0000122 } else if (!strcmp(Opt, "print-bindings")) {
123 CCCPrintBindings = true;
Daniel Dunbar365c02f2009-03-10 20:52:46 +0000124 } else if (!strcmp(Opt, "cxx")) {
125 CCCIsCXX = true;
126 } else if (!strcmp(Opt, "echo")) {
127 CCCEcho = true;
128
129 } else if (!strcmp(Opt, "no-clang")) {
130 CCCNoClang = true;
131 } else if (!strcmp(Opt, "no-clang-cxx")) {
132 CCCNoClangCXX = true;
133 } else if (!strcmp(Opt, "no-clang-cpp")) {
134 CCCNoClangCPP = true;
135 } else if (!strcmp(Opt, "clang-archs")) {
136 assert(Start+1 < End && "FIXME: -ccc- argument handling.");
137 const char *Cur = *++Start;
138
139 for (;;) {
140 const char *Next = strchr(Cur, ',');
141
142 if (Next) {
143 CCCClangArchs.insert(std::string(Cur, Next));
144 Cur = Next + 1;
145 } else {
146 CCCClangArchs.insert(std::string(Cur));
147 break;
148 }
149 }
150
Daniel Dunbardd98e2c2009-03-10 23:41:59 +0000151 } else if (!strcmp(Opt, "host-triple")) {
Daniel Dunbar365c02f2009-03-10 20:52:46 +0000152 assert(Start+1 < End && "FIXME: -ccc- argument handling.");
Daniel Dunbardd98e2c2009-03-10 23:41:59 +0000153 HostTriple = *++Start;
Daniel Dunbar365c02f2009-03-10 20:52:46 +0000154
155 } else {
156 // FIXME: Error handling.
157 llvm::errs() << "invalid option: " << *Start << "\n";
158 exit(1);
159 }
160 }
Daniel Dunbardd98e2c2009-03-10 23:41:59 +0000161
Daniel Dunbar365c02f2009-03-10 20:52:46 +0000162 ArgList *Args = ParseArgStrings(Start, End);
163
Daniel Dunbare5049522009-03-17 20:45:45 +0000164 Host = GetHostInfo(HostTriple);
Daniel Dunbarcb881672009-03-13 00:51:18 +0000165
Daniel Dunbar586dc232009-03-16 06:42:30 +0000166 // The compilation takes ownership of Args.
Daniel Dunbar10ffa9a2009-03-18 03:13:20 +0000167 Compilation *C = new Compilation(*Host->getToolChain(*Args), Args);
Daniel Dunbar21549232009-03-18 02:55:38 +0000168
169 // FIXME: This behavior shouldn't be here.
170 if (CCCPrintOptions) {
171 PrintOptions(C->getArgs());
172 return C;
173 }
174
175 if (!HandleImmediateArgs(*C))
176 return C;
177
178 // Construct the list of abstract actions to perform for this
179 // compilation. We avoid passing a Compilation here simply to
180 // enforce the abstraction that pipelining is not host or toolchain
181 // dependent (other than the driver driver test).
182 if (Host->useDriverDriver())
183 BuildUniversalActions(C->getArgs(), C->getActions());
184 else
185 BuildActions(C->getArgs(), C->getActions());
186
187 if (CCCPrintActions) {
Daniel Dunbar10ffa9a2009-03-18 03:13:20 +0000188 PrintActions(*C);
Daniel Dunbar21549232009-03-18 02:55:38 +0000189 return C;
190 }
191
192 BuildJobs(*C);
Daniel Dunbar8d2554a2009-03-15 01:38:15 +0000193
194 return C;
Daniel Dunbar365c02f2009-03-10 20:52:46 +0000195}
196
Daniel Dunbard65bddc2009-03-12 18:24:49 +0000197void Driver::PrintOptions(const ArgList &Args) const {
Daniel Dunbar06482622009-03-05 06:38:47 +0000198 unsigned i = 0;
Daniel Dunbar53ec5522009-03-12 07:58:46 +0000199 for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
Daniel Dunbar06482622009-03-05 06:38:47 +0000200 it != ie; ++it, ++i) {
201 Arg *A = *it;
202 llvm::errs() << "Option " << i << " - "
203 << "Name: \"" << A->getOption().getName() << "\", "
204 << "Values: {";
205 for (unsigned j = 0; j < A->getNumValues(); ++j) {
206 if (j)
207 llvm::errs() << ", ";
Daniel Dunbar53ec5522009-03-12 07:58:46 +0000208 llvm::errs() << '"' << A->getValue(Args, j) << '"';
Daniel Dunbar06482622009-03-05 06:38:47 +0000209 }
210 llvm::errs() << "}\n";
Daniel Dunbar06482622009-03-05 06:38:47 +0000211 }
Daniel Dunbar3ede8d02009-03-02 19:59:07 +0000212}
Daniel Dunbardd98e2c2009-03-10 23:41:59 +0000213
Daniel Dunbarcb881672009-03-13 00:51:18 +0000214void Driver::PrintVersion() const {
215 // FIXME: Get a reasonable version number.
216
217 // FIXME: The following handlers should use a callback mechanism, we
218 // don't know what the client would like to do.
219 llvm::outs() << "ccc version 1.0" << "\n";
220}
221
Daniel Dunbar21549232009-03-18 02:55:38 +0000222bool Driver::HandleImmediateArgs(const Compilation &C) {
Daniel Dunbarcb881672009-03-13 00:51:18 +0000223 // The order these options are handled in in gcc is all over the
224 // place, but we don't expect inconsistencies w.r.t. that to matter
225 // in practice.
Daniel Dunbar21549232009-03-18 02:55:38 +0000226 if (C.getArgs().hasArg(options::OPT_v) ||
227 C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
Daniel Dunbarcb881672009-03-13 00:51:18 +0000228 PrintVersion();
229 SuppressMissingInputWarning = true;
230 }
231
Daniel Dunbar21549232009-03-18 02:55:38 +0000232 const ToolChain &TC = C.getDefaultToolChain();
Daniel Dunbarcb881672009-03-13 00:51:18 +0000233 // FIXME: The following handlers should use a callback mechanism, we
234 // don't know what the client would like to do.
Daniel Dunbar21549232009-03-18 02:55:38 +0000235 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
236 llvm::outs() << GetFilePath(A->getValue(C.getArgs()), TC).toString()
237 << "\n";
Daniel Dunbarcb881672009-03-13 00:51:18 +0000238 return false;
239 }
240
Daniel Dunbar21549232009-03-18 02:55:38 +0000241 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
242 llvm::outs() << GetProgramPath(A->getValue(C.getArgs()), TC).toString()
243 << "\n";
Daniel Dunbarcb881672009-03-13 00:51:18 +0000244 return false;
245 }
246
Daniel Dunbar21549232009-03-18 02:55:38 +0000247 if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
248 llvm::outs() << GetProgramPath("libgcc.a", TC).toString() << "\n";
Daniel Dunbarcb881672009-03-13 00:51:18 +0000249 return false;
250 }
251
252 return true;
253}
254
Daniel Dunbar10ffa9a2009-03-18 03:13:20 +0000255static unsigned PrintActions1(const Compilation &C,
Daniel Dunbarba102132009-03-13 12:19:02 +0000256 Action *A,
257 std::map<Action*, unsigned> &Ids) {
258 if (Ids.count(A))
259 return Ids[A];
260
261 std::string str;
262 llvm::raw_string_ostream os(str);
263
264 os << Action::getClassName(A->getKind()) << ", ";
265 if (InputAction *IA = dyn_cast<InputAction>(A)) {
Daniel Dunbar10ffa9a2009-03-18 03:13:20 +0000266 os << "\"" << IA->getInputArg().getValue(C.getArgs()) << "\"";
Daniel Dunbarba102132009-03-13 12:19:02 +0000267 } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
Daniel Dunbar10ffa9a2009-03-18 03:13:20 +0000268 os << '"' << (BIA->getArchName() ? BIA->getArchName() :
269 C.getDefaultToolChain().getArchName()) << '"'
270 << ", {" << PrintActions1(C, *BIA->begin(), Ids) << "}";
Daniel Dunbarba102132009-03-13 12:19:02 +0000271 } else {
272 os << "{";
273 for (Action::iterator it = A->begin(), ie = A->end(); it != ie;) {
Daniel Dunbar10ffa9a2009-03-18 03:13:20 +0000274 os << PrintActions1(C, *it, Ids);
Daniel Dunbarba102132009-03-13 12:19:02 +0000275 ++it;
276 if (it != ie)
277 os << ", ";
278 }
279 os << "}";
280 }
281
282 unsigned Id = Ids.size();
283 Ids[A] = Id;
Daniel Dunbarb269c322009-03-13 17:20:20 +0000284 llvm::errs() << Id << ": " << os.str() << ", "
Daniel Dunbarba102132009-03-13 12:19:02 +0000285 << types::getTypeName(A->getType()) << "\n";
286
287 return Id;
288}
289
Daniel Dunbar10ffa9a2009-03-18 03:13:20 +0000290void Driver::PrintActions(const Compilation &C) const {
Daniel Dunbarba102132009-03-13 12:19:02 +0000291 std::map<Action*, unsigned> Ids;
Daniel Dunbar10ffa9a2009-03-18 03:13:20 +0000292 for (ActionList::const_iterator it = C.getActions().begin(),
293 ie = C.getActions().end(); it != ie; ++it)
294 PrintActions1(C, *it, Ids);
Daniel Dunbar53ec5522009-03-12 07:58:46 +0000295}
296
Daniel Dunbar21549232009-03-18 02:55:38 +0000297void Driver::BuildUniversalActions(const ArgList &Args,
298 ActionList &Actions) const {
Daniel Dunbar8f25c792009-03-18 01:38:48 +0000299 llvm::PrettyStackTraceString CrashInfo("Building actions for universal build");
Daniel Dunbar13689542009-03-13 20:33:35 +0000300 // Collect the list of architectures. Duplicates are allowed, but
301 // should only be handled once (in the order seen).
302 llvm::StringSet<> ArchNames;
303 llvm::SmallVector<const char *, 4> Archs;
Daniel Dunbar2fe63e62009-03-12 18:40:18 +0000304 for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
305 it != ie; ++it) {
306 Arg *A = *it;
307
308 if (A->getOption().getId() == options::OPT_arch) {
Daniel Dunbar13689542009-03-13 20:33:35 +0000309 const char *Name = A->getValue(Args);
310
Daniel Dunbar2fe63e62009-03-12 18:40:18 +0000311 // FIXME: We need to handle canonicalization of the specified
312 // arch?
313
Daniel Dunbar13689542009-03-13 20:33:35 +0000314 if (ArchNames.insert(Name))
315 Archs.push_back(Name);
Daniel Dunbar2fe63e62009-03-12 18:40:18 +0000316 }
317 }
318
Daniel Dunbar10ffa9a2009-03-18 03:13:20 +0000319 // When there is no explicit arch for this platform, make sure we
320 // still bind the architecture (to the default) so that -Xarch_ is
321 // handled correctly.
322 if (!Archs.size())
323 Archs.push_back(0);
Daniel Dunbar2fe63e62009-03-12 18:40:18 +0000324
325 // FIXME: We killed off some others but these aren't yet detected in
326 // a functional manner. If we added information to jobs about which
327 // "auxiliary" files they wrote then we could detect the conflict
328 // these cause downstream.
329 if (Archs.size() > 1) {
330 // No recovery needed, the point of this is just to prevent
331 // overwriting the same files.
332 if (const Arg *A = Args.getLastArg(options::OPT_M_Group))
333 Diag(clang::diag::err_drv_invalid_opt_with_multiple_archs)
334 << A->getOption().getName();
335 if (const Arg *A = Args.getLastArg(options::OPT_save_temps))
336 Diag(clang::diag::err_drv_invalid_opt_with_multiple_archs)
337 << A->getOption().getName();
338 }
339
340 ActionList SingleActions;
341 BuildActions(Args, SingleActions);
342
343 // Add in arch binding and lipo (if necessary) for every top level
344 // action.
345 for (unsigned i = 0, e = SingleActions.size(); i != e; ++i) {
346 Action *Act = SingleActions[i];
347
348 // Make sure we can lipo this kind of output. If not (and it is an
349 // actual output) then we disallow, since we can't create an
350 // output file with the right name without overwriting it. We
351 // could remove this oddity by just changing the output names to
352 // include the arch, which would also fix
353 // -save-temps. Compatibility wins for now.
354
Daniel Dunbar3dbd6c52009-03-13 17:46:02 +0000355 if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
Daniel Dunbar2fe63e62009-03-12 18:40:18 +0000356 Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
357 << types::getTypeName(Act->getType());
358
359 ActionList Inputs;
Daniel Dunbar13689542009-03-13 20:33:35 +0000360 for (unsigned i = 0, e = Archs.size(); i != e; ++i )
361 Inputs.push_back(new BindArchAction(Act, Archs[i]));
Daniel Dunbar2fe63e62009-03-12 18:40:18 +0000362
363 // Lipo if necessary, We do it this way because we need to set the
364 // arch flag so that -Xarch_ gets overwritten.
365 if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
366 Actions.append(Inputs.begin(), Inputs.end());
367 else
368 Actions.push_back(new LipoJobAction(Inputs, Act->getType()));
369 }
Daniel Dunbar53ec5522009-03-12 07:58:46 +0000370}
371
Daniel Dunbar21549232009-03-18 02:55:38 +0000372void Driver::BuildActions(const ArgList &Args, ActionList &Actions) const {
Daniel Dunbar8f25c792009-03-18 01:38:48 +0000373 llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
Daniel Dunbaraf61c712009-03-12 23:55:14 +0000374 // Start by constructing the list of inputs and their types.
375
Daniel Dunbar83dd21f2009-03-13 17:57:10 +0000376 // Track the current user specified (-x) input. We also explicitly
377 // track the argument used to set the type; we only want to claim
378 // the type when we actually use it, so we warn about unused -x
379 // arguments.
380 types::ID InputType = types::TY_Nothing;
381 Arg *InputTypeArg = 0;
382
Daniel Dunbar53ec5522009-03-12 07:58:46 +0000383 llvm::SmallVector<std::pair<types::ID, const Arg*>, 16> Inputs;
384 for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
385 it != ie; ++it) {
386 Arg *A = *it;
387
388 if (isa<InputOption>(A->getOption())) {
389 const char *Value = A->getValue(Args);
390 types::ID Ty = types::TY_INVALID;
391
392 // Infer the input type if necessary.
Daniel Dunbar83dd21f2009-03-13 17:57:10 +0000393 if (InputType == types::TY_Nothing) {
394 // If there was an explicit arg for this, claim it.
395 if (InputTypeArg)
396 InputTypeArg->claim();
397
Daniel Dunbar53ec5522009-03-12 07:58:46 +0000398 // stdin must be handled specially.
399 if (memcmp(Value, "-", 2) == 0) {
400 // If running with -E, treat as a C input (this changes the
401 // builtin macros, for example). This may be overridden by
402 // -ObjC below.
403 //
404 // Otherwise emit an error but still use a valid type to
405 // avoid spurious errors (e.g., no inputs).
Daniel Dunbar8022fd42009-03-15 00:48:16 +0000406 if (!Args.hasArg(options::OPT_E, false))
Daniel Dunbarb897f5d2009-03-12 09:13:48 +0000407 Diag(clang::diag::err_drv_unknown_stdin_type);
Daniel Dunbar53ec5522009-03-12 07:58:46 +0000408 Ty = types::TY_C;
409 } else {
410 // Otherwise lookup by extension, and fallback to ObjectType
411 // if not found.
412 if (const char *Ext = strrchr(Value, '.'))
413 Ty = types::lookupTypeForExtension(Ext + 1);
414 if (Ty == types::TY_INVALID)
415 Ty = types::TY_Object;
416 }
417
418 // -ObjC and -ObjC++ override the default language, but only
419 // -for "source files". We just treat everything that isn't a
420 // -linker input as a source file.
421 //
422 // FIXME: Clean this up if we move the phase sequence into the
423 // type.
424 if (Ty != types::TY_Object) {
425 if (Args.hasArg(options::OPT_ObjC))
426 Ty = types::TY_ObjC;
427 else if (Args.hasArg(options::OPT_ObjCXX))
428 Ty = types::TY_ObjCXX;
429 }
430 } else {
431 assert(InputTypeArg && "InputType set w/o InputTypeArg");
432 InputTypeArg->claim();
433 Ty = InputType;
434 }
435
436 // Check that the file exists. It isn't clear this is worth
437 // doing, since the tool presumably does this anyway, and this
438 // just adds an extra stat to the equation, but this is gcc
439 // compatible.
Daniel Dunbar411f2e42009-03-15 01:40:22 +0000440 A->claim();
Daniel Dunbar53ec5522009-03-12 07:58:46 +0000441 if (memcmp(Value, "-", 2) != 0 && !llvm::sys::Path(Value).exists())
Daniel Dunbarb897f5d2009-03-12 09:13:48 +0000442 Diag(clang::diag::err_drv_no_such_file) << A->getValue(Args);
Daniel Dunbar53ec5522009-03-12 07:58:46 +0000443 else
444 Inputs.push_back(std::make_pair(Ty, A));
445
446 } else if (A->getOption().isLinkerInput()) {
447 // Just treat as object type, we could make a special type for
448 // this if necessary.
Daniel Dunbar411f2e42009-03-15 01:40:22 +0000449 A->claim();
Daniel Dunbar53ec5522009-03-12 07:58:46 +0000450 Inputs.push_back(std::make_pair(types::TY_Object, A));
451
452 } else if (A->getOption().getId() == options::OPT_x) {
453 InputTypeArg = A;
454 InputType = types::lookupTypeForTypeSpecifier(A->getValue(Args));
455
456 // Follow gcc behavior and treat as linker input for invalid -x
457 // options. Its not clear why we shouldn't just revert to
458 // unknown; but this isn't very important, we might as well be
459 // bug comatible.
460 if (!InputType) {
Daniel Dunbarb897f5d2009-03-12 09:13:48 +0000461 Diag(clang::diag::err_drv_unknown_language) << A->getValue(Args);
Daniel Dunbar53ec5522009-03-12 07:58:46 +0000462 InputType = types::TY_Object;
463 }
464 }
465 }
466
Daniel Dunbar8b1604e2009-03-13 00:17:48 +0000467 if (!SuppressMissingInputWarning && Inputs.empty()) {
Daniel Dunbaraf61c712009-03-12 23:55:14 +0000468 Diag(clang::diag::err_drv_no_input_files);
469 return;
470 }
471
472 // Determine which compilation mode we are in. We look for options
473 // which affect the phase, starting with the earliest phases, and
474 // record which option we used to determine the final phase.
Daniel Dunbarad2a9af2009-03-13 11:38:42 +0000475 Arg *FinalPhaseArg = 0;
476 phases::ID FinalPhase;
Daniel Dunbaraf61c712009-03-12 23:55:14 +0000477
478 // -{E,M,MM} only run the preprocessor.
Daniel Dunbarad2a9af2009-03-13 11:38:42 +0000479 if ((FinalPhaseArg = Args.getLastArg(options::OPT_E)) ||
480 (FinalPhaseArg = Args.getLastArg(options::OPT_M)) ||
481 (FinalPhaseArg = Args.getLastArg(options::OPT_MM))) {
482 FinalPhase = phases::Preprocess;
Daniel Dunbaraf61c712009-03-12 23:55:14 +0000483
Daniel Dunbar8022fd42009-03-15 00:48:16 +0000484 // -{fsyntax-only,-analyze,emit-llvm,S} only run up to the compiler.
485 } else if ((FinalPhaseArg = Args.getLastArg(options::OPT_fsyntax_only)) ||
486 (FinalPhaseArg = Args.getLastArg(options::OPT__analyze)) ||
487 (FinalPhaseArg = Args.getLastArg(options::OPT_emit_llvm)) ||
Daniel Dunbarad2a9af2009-03-13 11:38:42 +0000488 (FinalPhaseArg = Args.getLastArg(options::OPT_S))) {
489 FinalPhase = phases::Compile;
Daniel Dunbaraf61c712009-03-12 23:55:14 +0000490
491 // -c only runs up to the assembler.
Daniel Dunbarad2a9af2009-03-13 11:38:42 +0000492 } else if ((FinalPhaseArg = Args.getLastArg(options::OPT_c))) {
493 FinalPhase = phases::Assemble;
Daniel Dunbaraf61c712009-03-12 23:55:14 +0000494
495 // Otherwise do everything.
496 } else
Daniel Dunbarad2a9af2009-03-13 11:38:42 +0000497 FinalPhase = phases::Link;
Daniel Dunbaraf61c712009-03-12 23:55:14 +0000498
Daniel Dunbaraf61c712009-03-12 23:55:14 +0000499 // Reject -Z* at the top level, these options should never have been
500 // exposed by gcc.
501 if (Arg *A = Args.getLastArg(options::OPT_Z))
502 Diag(clang::diag::err_drv_use_of_Z_option) << A->getValue(Args);
503
Daniel Dunbarad2a9af2009-03-13 11:38:42 +0000504 // Construct the actions to perform.
505 ActionList LinkerInputs;
Daniel Dunbar53ec5522009-03-12 07:58:46 +0000506 for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
Daniel Dunbarad2a9af2009-03-13 11:38:42 +0000507 types::ID InputType = Inputs[i].first;
508 const Arg *InputArg = Inputs[i].second;
509
510 unsigned NumSteps = types::getNumCompilationPhases(InputType);
511 assert(NumSteps && "Invalid number of steps!");
512
513 // If the first step comes after the final phase we are doing as
514 // part of this compilation, warn the user about it.
515 phases::ID InitialPhase = types::getCompilationPhase(InputType, 0);
516 if (InitialPhase > FinalPhase) {
517 Diag(clang::diag::warn_drv_input_file_unused)
518 << InputArg->getValue(Args)
519 << getPhaseName(InitialPhase)
520 << FinalPhaseArg->getOption().getName();
521 continue;
522 }
523
524 // Build the pipeline for this file.
525 Action *Current = new InputAction(*InputArg, InputType);
526 for (unsigned i = 0; i != NumSteps; ++i) {
527 phases::ID Phase = types::getCompilationPhase(InputType, i);
528
529 // We are done if this step is past what the user requested.
530 if (Phase > FinalPhase)
531 break;
532
533 // Queue linker inputs.
534 if (Phase == phases::Link) {
535 assert(i + 1 == NumSteps && "linking must be final compilation step.");
536 LinkerInputs.push_back(Current);
537 Current = 0;
538 break;
539 }
540
541 // Otherwise construct the appropriate action.
542 Current = ConstructPhaseAction(Args, Phase, Current);
543 if (Current->getType() == types::TY_Nothing)
544 break;
545 }
546
547 // If we ended with something, add to the output list.
548 if (Current)
549 Actions.push_back(Current);
Daniel Dunbar53ec5522009-03-12 07:58:46 +0000550 }
Daniel Dunbarad2a9af2009-03-13 11:38:42 +0000551
552 // Add a link action if necessary.
553 if (!LinkerInputs.empty())
554 Actions.push_back(new LinkJobAction(LinkerInputs, types::TY_Image));
555}
556
557Action *Driver::ConstructPhaseAction(const ArgList &Args, phases::ID Phase,
558 Action *Input) const {
Daniel Dunbar8f25c792009-03-18 01:38:48 +0000559 llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
Daniel Dunbarad2a9af2009-03-13 11:38:42 +0000560 // Build the appropriate action.
561 switch (Phase) {
562 case phases::Link: assert(0 && "link action invalid here.");
563 case phases::Preprocess: {
564 types::ID OutputTy = types::getPreprocessedType(Input->getType());
565 assert(OutputTy != types::TY_INVALID &&
566 "Cannot preprocess this input type!");
567 return new PreprocessJobAction(Input, OutputTy);
568 }
569 case phases::Precompile:
570 return new PrecompileJobAction(Input, types::TY_PCH);
571 case phases::Compile: {
572 if (Args.hasArg(options::OPT_fsyntax_only)) {
573 return new CompileJobAction(Input, types::TY_Nothing);
574 } else if (Args.hasArg(options::OPT__analyze)) {
575 return new AnalyzeJobAction(Input, types::TY_Plist);
576 } else if (Args.hasArg(options::OPT_emit_llvm)) {
577 types::ID Output =
578 Args.hasArg(options::OPT_S) ? types::TY_LLVMAsm : types::TY_LLVMBC;
579 return new CompileJobAction(Input, Output);
580 } else {
581 return new CompileJobAction(Input, types::TY_PP_Asm);
582 }
583 }
584 case phases::Assemble:
585 return new AssembleJobAction(Input, types::TY_Object);
586 }
587
588 assert(0 && "invalid phase in ConstructPhaseAction");
589 return 0;
Daniel Dunbar53ec5522009-03-12 07:58:46 +0000590}
591
Daniel Dunbar21549232009-03-18 02:55:38 +0000592void Driver::BuildJobs(Compilation &C) const {
Daniel Dunbar8f25c792009-03-18 01:38:48 +0000593 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
Daniel Dunbarf353c8c2009-03-16 06:56:51 +0000594 bool SaveTemps = C.getArgs().hasArg(options::OPT_save_temps);
595 bool UsePipes = C.getArgs().hasArg(options::OPT_pipe);
596
597 // -save-temps inhibits pipes.
598 if (SaveTemps && UsePipes) {
599 Diag(clang::diag::warn_drv_pipe_ignored_with_save_temps);
600 UsePipes = true;
601 }
602
603 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
604
605 // It is an error to provide a -o option if we are making multiple
606 // output files.
607 if (FinalOutput) {
608 unsigned NumOutputs = 0;
Daniel Dunbar21549232009-03-18 02:55:38 +0000609 for (ActionList::const_iterator it = C.getActions().begin(),
610 ie = C.getActions().end(); it != ie; ++it)
Daniel Dunbarf353c8c2009-03-16 06:56:51 +0000611 if ((*it)->getType() != types::TY_Nothing)
612 ++NumOutputs;
613
614 if (NumOutputs > 1) {
615 Diag(clang::diag::err_drv_output_argument_with_multiple_files);
616 FinalOutput = 0;
617 }
618 }
619
Daniel Dunbar21549232009-03-18 02:55:38 +0000620 for (ActionList::const_iterator it = C.getActions().begin(),
621 ie = C.getActions().end(); it != ie; ++it) {
Daniel Dunbarf353c8c2009-03-16 06:56:51 +0000622 Action *A = *it;
623
624 // If we are linking an image for multiple archs then the linker
625 // wants -arch_multiple and -final_output <final image
626 // name>. Unfortunately, this doesn't fit in cleanly because we
627 // have to pass this information down.
628 //
629 // FIXME: This is a hack; find a cleaner way to integrate this
630 // into the process.
631 const char *LinkingOutput = 0;
632 if (isa<LinkJobAction>(A)) {
633 if (FinalOutput)
634 LinkingOutput = FinalOutput->getValue(C.getArgs());
635 else
636 LinkingOutput = DefaultImageName.c_str();
637 }
638
639 InputInfo II;
Daniel Dunbar10ffa9a2009-03-18 03:13:20 +0000640 BuildJobsForAction(C, A, &C.getDefaultToolChain(),
Daniel Dunbarf353c8c2009-03-16 06:56:51 +0000641 /*CanAcceptPipe*/ true,
642 /*AtTopLevel*/ true,
643 /*LinkingOutput*/ LinkingOutput,
644 II);
645 }
Daniel Dunbar586dc232009-03-16 06:42:30 +0000646
647 // If there were no errors, warn about any unused arguments.
648 for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end();
649 it != ie; ++it) {
650 Arg *A = *it;
651
652 // FIXME: It would be nice to be able to send the argument to the
653 // Diagnostic, so that extra values, position, and so on could be
654 // printed.
655 if (!A->isClaimed())
656 Diag(clang::diag::warn_drv_unused_argument)
657 << A->getOption().getName();
658 }
Daniel Dunbar57b704d2009-03-13 22:12:33 +0000659}
660
Daniel Dunbarf353c8c2009-03-16 06:56:51 +0000661void Driver::BuildJobsForAction(Compilation &C,
662 const Action *A,
663 const ToolChain *TC,
664 bool CanAcceptPipe,
665 bool AtTopLevel,
666 const char *LinkingOutput,
667 InputInfo &Result) const {
Daniel Dunbar8f25c792009-03-18 01:38:48 +0000668 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs for action");
Daniel Dunbarf353c8c2009-03-16 06:56:51 +0000669 if (const InputAction *IA = dyn_cast<InputAction>(A)) {
670 const char *Name = IA->getInputArg().getValue(C.getArgs());
671 Result = InputInfo(Name, A->getType(), Name);
672 return;
673 }
674
675 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
676 const char *ArchName = BAA->getArchName();
Daniel Dunbar10ffa9a2009-03-18 03:13:20 +0000677 if (!ArchName)
678 ArchName = C.getDefaultToolChain().getArchName().c_str();
Daniel Dunbarf353c8c2009-03-16 06:56:51 +0000679 BuildJobsForAction(C,
680 *BAA->begin(),
681 Host->getToolChain(C.getArgs(), ArchName),
682 CanAcceptPipe,
683 AtTopLevel,
684 LinkingOutput,
685 Result);
686 return;
687 }
688
689 const JobAction *JA = cast<JobAction>(A);
690 const Tool &T = TC->SelectTool(C, *JA);
691
692 // See if we should use an integrated preprocessor. We do so when we
693 // have exactly one input, since this is the only use case we care
694 // about (irrelevant since we don't support combine yet).
695 bool UseIntegratedCPP = false;
696 const ActionList *Inputs = &A->getInputs();
697 if (Inputs->size() == 1 && isa<PreprocessJobAction>(*Inputs->begin())) {
698 if (!C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
699 !C.getArgs().hasArg(options::OPT_traditional_cpp) &&
700 !C.getArgs().hasArg(options::OPT_save_temps) &&
701 T.hasIntegratedCPP()) {
702 UseIntegratedCPP = true;
703 Inputs = &(*Inputs)[0]->getInputs();
704 }
705 }
706
707 // Only use pipes when there is exactly one input.
708 bool TryToUsePipeInput = Inputs->size() == 1 && T.acceptsPipedInput();
709 llvm::SmallVector<InputInfo, 4> InputInfos;
710 for (ActionList::const_iterator it = Inputs->begin(), ie = Inputs->end();
711 it != ie; ++it) {
712 InputInfo II;
713 BuildJobsForAction(C, *it, TC, TryToUsePipeInput,
714 /*AtTopLevel*/false,
715 LinkingOutput,
716 II);
717 InputInfos.push_back(II);
718 }
719
720 // Determine if we should output to a pipe.
721 bool OutputToPipe = false;
722 if (CanAcceptPipe && T.canPipeOutput()) {
723 // Some actions default to writing to a pipe if they are the top
724 // level phase and there was no user override.
725 //
726 // FIXME: Is there a better way to handle this?
727 if (AtTopLevel) {
728 if (isa<PreprocessJobAction>(A) && !C.getArgs().hasArg(options::OPT_o))
729 OutputToPipe = true;
730 } else if (C.getArgs().hasArg(options::OPT_pipe))
731 OutputToPipe = true;
732 }
733
734 // Figure out where to put the job (pipes).
735 Job *Dest = &C.getJobs();
736 if (InputInfos[0].isPipe()) {
Daniel Dunbar441d0602009-03-17 17:53:55 +0000737 assert(TryToUsePipeInput && "Unrequested pipe!");
Daniel Dunbarf353c8c2009-03-16 06:56:51 +0000738 assert(InputInfos.size() == 1 && "Unexpected pipe with multiple inputs.");
739 Dest = &InputInfos[0].getPipe();
740 }
741
742 // Always use the first input as the base input.
743 const char *BaseInput = InputInfos[0].getBaseInput();
Daniel Dunbar441d0602009-03-17 17:53:55 +0000744
745 // Determine the place to write output to (nothing, pipe, or
746 // filename) and where to put the new job.
Daniel Dunbar441d0602009-03-17 17:53:55 +0000747 if (JA->getType() == types::TY_Nothing) {
Daniel Dunbar5c3c1d72009-03-17 22:47:06 +0000748 Result = InputInfo(A->getType(), BaseInput);
Daniel Dunbar441d0602009-03-17 17:53:55 +0000749 } else if (OutputToPipe) {
750 // Append to current piped job or create a new one as appropriate.
Daniel Dunbar5c3c1d72009-03-17 22:47:06 +0000751 PipedJob *PJ = dyn_cast<PipedJob>(Dest);
752 if (!PJ) {
753 PJ = new PipedJob();
754 cast<JobList>(Dest)->addJob(PJ);
Daniel Dunbar441d0602009-03-17 17:53:55 +0000755 }
Daniel Dunbar5c3c1d72009-03-17 22:47:06 +0000756 Result = InputInfo(PJ, A->getType(), BaseInput);
Daniel Dunbar441d0602009-03-17 17:53:55 +0000757 } else {
Daniel Dunbar5c3c1d72009-03-17 22:47:06 +0000758 Result = InputInfo(GetNamedOutputPath(C, *JA, BaseInput, AtTopLevel),
759 A->getType(), BaseInput);
Daniel Dunbar441d0602009-03-17 17:53:55 +0000760 }
761
Daniel Dunbar5c3c1d72009-03-17 22:47:06 +0000762 if (CCCPrintBindings) {
763 llvm::errs() << "bind - \"" << T.getName() << "\", inputs: [";
764 for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
765 llvm::errs() << InputInfos[i].getAsString();
766 if (i + 1 != e)
767 llvm::errs() << ", ";
768 }
769 llvm::errs() << "], output: " << Result.getAsString() << "\n";
770 } else {
771 assert(0 && "FIXME: Make the job.");
772 }
Daniel Dunbarf353c8c2009-03-16 06:56:51 +0000773}
774
Daniel Dunbar441d0602009-03-17 17:53:55 +0000775const char *Driver::GetNamedOutputPath(Compilation &C,
776 const JobAction &JA,
777 const char *BaseInput,
778 bool AtTopLevel) const {
Daniel Dunbar8f25c792009-03-18 01:38:48 +0000779 llvm::PrettyStackTraceString CrashInfo("Computing output path");
Daniel Dunbar441d0602009-03-17 17:53:55 +0000780 // Output to a user requested destination?
781 if (AtTopLevel) {
782 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
783 return C.addResultFile(FinalOutput->getValue(C.getArgs()));
784 }
785
786 // Output to a temporary file?
787 if (!AtTopLevel && !C.getArgs().hasArg(options::OPT_save_temps)) {
788 // FIXME: Get temporary name.
789 std::string Name("/tmp/foo");
790 Name += '.';
791 Name += types::getTypeTempSuffix(JA.getType());
792 return C.addTempFile(C.getArgs().MakeArgString(Name.c_str()));
793 }
794
795 llvm::sys::Path BasePath(BaseInput);
Daniel Dunbar5796bf42009-03-18 02:00:31 +0000796 std::string BaseName(BasePath.getLast());
Daniel Dunbar441d0602009-03-17 17:53:55 +0000797
798 // Determine what the derived output name should be.
799 const char *NamedOutput;
800 if (JA.getType() == types::TY_Image) {
801 NamedOutput = DefaultImageName.c_str();
802 } else {
803 const char *Suffix = types::getTypeTempSuffix(JA.getType());
804 assert(Suffix && "All types used for output should have a suffix.");
805
806 std::string::size_type End = std::string::npos;
807 if (!types::appendSuffixForType(JA.getType()))
808 End = BaseName.rfind('.');
809 std::string Suffixed(BaseName.substr(0, End));
810 Suffixed += '.';
811 Suffixed += Suffix;
812 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
813 }
814
815 // As an annoying special case, PCH generation doesn't strip the
816 // pathname.
817 if (JA.getType() == types::TY_PCH) {
818 BasePath.eraseComponent();
819 BasePath.appendComponent(NamedOutput);
820 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()));
821 } else {
822 return C.addResultFile(NamedOutput);
823 }
824}
825
Daniel Dunbar2ba38ba2009-03-16 05:25:36 +0000826llvm::sys::Path Driver::GetFilePath(const char *Name,
Daniel Dunbar21549232009-03-18 02:55:38 +0000827 const ToolChain &TC) const {
Daniel Dunbarcb881672009-03-13 00:51:18 +0000828 // FIXME: Implement.
829 return llvm::sys::Path(Name);
830}
831
Daniel Dunbar2ba38ba2009-03-16 05:25:36 +0000832llvm::sys::Path Driver::GetProgramPath(const char *Name,
Daniel Dunbar21549232009-03-18 02:55:38 +0000833 const ToolChain &TC) const {
Daniel Dunbarcb881672009-03-13 00:51:18 +0000834 // FIXME: Implement.
835 return llvm::sys::Path(Name);
836}
837
Daniel Dunbare5049522009-03-17 20:45:45 +0000838const HostInfo *Driver::GetHostInfo(const char *Triple) const {
Daniel Dunbar8f25c792009-03-18 01:38:48 +0000839 llvm::PrettyStackTraceString CrashInfo("Constructing host");
Daniel Dunbardd98e2c2009-03-10 23:41:59 +0000840 // Dice into arch, platform, and OS. This matches
841 // arch,platform,os = '(.*?)-(.*?)-(.*?)'
842 // and missing fields are left empty.
843 std::string Arch, Platform, OS;
844
845 if (const char *ArchEnd = strchr(Triple, '-')) {
846 Arch = std::string(Triple, ArchEnd);
847
848 if (const char *PlatformEnd = strchr(ArchEnd+1, '-')) {
849 Platform = std::string(ArchEnd+1, PlatformEnd);
850 OS = PlatformEnd+1;
851 } else
852 Platform = ArchEnd+1;
853 } else
854 Arch = Triple;
855
Daniel Dunbar1fd6c4b2009-03-17 19:00:50 +0000856 // Normalize Arch a bit.
857 //
858 // FIXME: This is very incomplete.
859 if (Arch == "i686")
860 Arch = "i386";
861 else if (Arch == "amd64")
862 Arch = "x86_64";
863
Daniel Dunbara88162c2009-03-13 12:23:29 +0000864 if (memcmp(&OS[0], "darwin", 6) == 0)
Daniel Dunbare5049522009-03-17 20:45:45 +0000865 return createDarwinHostInfo(*this, Arch.c_str(), Platform.c_str(),
866 OS.c_str());
Daniel Dunbardd98e2c2009-03-10 23:41:59 +0000867
Daniel Dunbare5049522009-03-17 20:45:45 +0000868 return createUnknownHostInfo(*this, Arch.c_str(), Platform.c_str(),
869 OS.c_str());
Daniel Dunbardd98e2c2009-03-10 23:41:59 +0000870}