blob: 7890e72de63c40cfbab323c1399d9ddc161eacce [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 Dunbar632f50e2009-03-18 21:34:08 +000029#include "llvm/System/Program.h"
Daniel Dunbarba102132009-03-13 12:19:02 +000030
Daniel Dunbarf353c8c2009-03-16 06:56:51 +000031#include "InputInfo.h"
32
Daniel Dunbarba102132009-03-13 12:19:02 +000033#include <map>
34
Daniel Dunbar1b3bb6e2009-03-04 20:49:20 +000035using namespace clang::driver;
Chris Lattner92b36992009-03-26 05:56:24 +000036using namespace clang;
Daniel Dunbar1b3bb6e2009-03-04 20:49:20 +000037
Daniel Dunbardd98e2c2009-03-10 23:41:59 +000038Driver::Driver(const char *_Name, const char *_Dir,
Daniel Dunbar4ad4b3e2009-03-12 08:55:43 +000039 const char *_DefaultHostTriple,
Daniel Dunbarf353c8c2009-03-16 06:56:51 +000040 const char *_DefaultImageName,
Daniel Dunbar4ad4b3e2009-03-12 08:55:43 +000041 Diagnostic &_Diags)
42 : Opts(new OptTable()), Diags(_Diags),
Daniel Dunbardd98e2c2009-03-10 23:41:59 +000043 Name(_Name), Dir(_Dir), DefaultHostTriple(_DefaultHostTriple),
Daniel Dunbarf353c8c2009-03-16 06:56:51 +000044 DefaultImageName(_DefaultImageName),
Daniel Dunbardd98e2c2009-03-10 23:41:59 +000045 Host(0),
Daniel Dunbar5c3c1d72009-03-17 22:47:06 +000046 CCCIsCXX(false), CCCEcho(false), CCCPrintBindings(false),
Daniel Dunbar78d8a082009-04-01 23:34:41 +000047 CCCGenericGCCName("gcc"), CCCUseClang(true), CCCUseClangCXX(false),
48 CCCUseClangCPP(true),
Daniel Dunbar8b1604e2009-03-13 00:17:48 +000049 SuppressMissingInputWarning(false)
Daniel Dunbar365c02f2009-03-10 20:52:46 +000050{
Daniel Dunbar0f99d2e2009-03-24 19:02:31 +000051 // Only use clang on i386 and x86_64 by default.
52 CCCClangArchs.insert("i386");
53 CCCClangArchs.insert("x86_64");
Daniel Dunbar3ede8d02009-03-02 19:59:07 +000054}
55
56Driver::~Driver() {
Daniel Dunbar1b3bb6e2009-03-04 20:49:20 +000057 delete Opts;
Daniel Dunbar7e4534d2009-03-18 01:09:40 +000058 delete Host;
Daniel Dunbar3ede8d02009-03-02 19:59:07 +000059}
60
Daniel Dunbarf3cad362009-03-25 04:13:45 +000061InputArgList *Driver::ParseArgStrings(const char **ArgBegin,
62 const char **ArgEnd) {
Daniel Dunbar8f25c792009-03-18 01:38:48 +000063 llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
Daniel Dunbarf3cad362009-03-25 04:13:45 +000064 InputArgList *Args = new InputArgList(ArgBegin, ArgEnd);
Daniel Dunbar06482622009-03-05 06:38:47 +000065
Daniel Dunbarad2a9af2009-03-13 11:38:42 +000066 // FIXME: Handle '@' args (or at least error on them).
67
Daniel Dunbar06482622009-03-05 06:38:47 +000068 unsigned Index = 0, End = ArgEnd - ArgBegin;
69 while (Index < End) {
Daniel Dunbar41393402009-03-13 01:01:44 +000070 // gcc's handling of empty arguments doesn't make
71 // sense, but this is not a common use case. :)
72 //
73 // We just ignore them here (note that other things may
74 // still take them as arguments).
75 if (Args->getArgString(Index)[0] == '\0') {
76 ++Index;
77 continue;
78 }
79
Daniel Dunbar06482622009-03-05 06:38:47 +000080 unsigned Prev = Index;
Daniel Dunbarb0c4df52009-03-22 23:26:43 +000081 Arg *A = getOpts().ParseOneArg(*Args, Index);
82 assert(Index > Prev && "Parser failed to consume argument.");
Daniel Dunbar53ec5522009-03-12 07:58:46 +000083
Daniel Dunbarb0c4df52009-03-22 23:26:43 +000084 // Check for missing argument error.
85 if (!A) {
86 assert(Index >= End && "Unexpected parser error.");
87 Diag(clang::diag::err_drv_missing_argument)
88 << Args->getArgString(Prev)
89 << (Index - Prev - 1);
90 break;
Daniel Dunbar53ec5522009-03-12 07:58:46 +000091 }
Daniel Dunbar06482622009-03-05 06:38:47 +000092
Daniel Dunbarb0c4df52009-03-22 23:26:43 +000093 if (A->getOption().isUnsupported()) {
94 Diag(clang::diag::err_drv_unsupported_opt) << A->getAsString(*Args);
95 continue;
96 }
97 Args->append(A);
Daniel Dunbar06482622009-03-05 06:38:47 +000098 }
99
100 return Args;
101}
102
Daniel Dunbar3ede8d02009-03-02 19:59:07 +0000103Compilation *Driver::BuildCompilation(int argc, const char **argv) {
Daniel Dunbar8f25c792009-03-18 01:38:48 +0000104 llvm::PrettyStackTraceString CrashInfo("Compilation construction");
105
Daniel Dunbarcb881672009-03-13 00:51:18 +0000106 // FIXME: Handle environment options which effect driver behavior,
107 // somewhere (client?). GCC_EXEC_PREFIX, COMPILER_PATH,
108 // LIBRARY_PATH, LPATH, CC_PRINT_OPTIONS, QA_OVERRIDE_GCC3_OPTIONS.
109
110 // FIXME: What are we going to do with -V and -b?
111
112 // FIXME: Handle CCC_ADD_ARGS.
113
Daniel Dunbar365c02f2009-03-10 20:52:46 +0000114 // FIXME: This stuff needs to go into the Compilation, not the
115 // driver.
Daniel Dunbar53ec5522009-03-12 07:58:46 +0000116 bool CCCPrintOptions = false, CCCPrintActions = false;
Daniel Dunbar06482622009-03-05 06:38:47 +0000117
Daniel Dunbar365c02f2009-03-10 20:52:46 +0000118 const char **Start = argv + 1, **End = argv + argc;
Daniel Dunbardd98e2c2009-03-10 23:41:59 +0000119 const char *HostTriple = DefaultHostTriple.c_str();
Daniel Dunbar365c02f2009-03-10 20:52:46 +0000120
121 // Read -ccc args.
122 //
123 // FIXME: We need to figure out where this behavior should
124 // live. Most of it should be outside in the client; the parts that
125 // aren't should have proper options, either by introducing new ones
126 // or by overloading gcc ones like -V or -b.
127 for (; Start != End && memcmp(*Start, "-ccc-", 5) == 0; ++Start) {
128 const char *Opt = *Start + 5;
129
130 if (!strcmp(Opt, "print-options")) {
131 CCCPrintOptions = true;
132 } else if (!strcmp(Opt, "print-phases")) {
Daniel Dunbar53ec5522009-03-12 07:58:46 +0000133 CCCPrintActions = true;
Daniel Dunbar5c3c1d72009-03-17 22:47:06 +0000134 } else if (!strcmp(Opt, "print-bindings")) {
135 CCCPrintBindings = true;
Daniel Dunbar365c02f2009-03-10 20:52:46 +0000136 } else if (!strcmp(Opt, "cxx")) {
137 CCCIsCXX = true;
138 } else if (!strcmp(Opt, "echo")) {
139 CCCEcho = true;
140
Daniel Dunbar78d8a082009-04-01 23:34:41 +0000141 } else if (!strcmp(Opt, "gcc-name")) {
142 assert(Start+1 < End && "FIXME: -ccc- argument handling.");
143 CCCGenericGCCName = *++Start;
144
Daniel Dunbar0f99d2e2009-03-24 19:02:31 +0000145 } else if (!strcmp(Opt, "clang-cxx")) {
146 CCCUseClangCXX = true;
Daniel Dunbar365c02f2009-03-10 20:52:46 +0000147 } else if (!strcmp(Opt, "no-clang")) {
Daniel Dunbar0f99d2e2009-03-24 19:02:31 +0000148 CCCUseClang = false;
Daniel Dunbar365c02f2009-03-10 20:52:46 +0000149 } else if (!strcmp(Opt, "no-clang-cpp")) {
Daniel Dunbar0f99d2e2009-03-24 19:02:31 +0000150 CCCUseClangCPP = false;
Daniel Dunbar365c02f2009-03-10 20:52:46 +0000151 } else if (!strcmp(Opt, "clang-archs")) {
152 assert(Start+1 < End && "FIXME: -ccc- argument handling.");
153 const char *Cur = *++Start;
154
Daniel Dunbar0f99d2e2009-03-24 19:02:31 +0000155 CCCClangArchs.clear();
Daniel Dunbar365c02f2009-03-10 20:52:46 +0000156 for (;;) {
157 const char *Next = strchr(Cur, ',');
158
159 if (Next) {
Daniel Dunbar0f99d2e2009-03-24 19:02:31 +0000160 if (Cur != Next)
161 CCCClangArchs.insert(std::string(Cur, Next));
Daniel Dunbar365c02f2009-03-10 20:52:46 +0000162 Cur = Next + 1;
163 } else {
Daniel Dunbar0f99d2e2009-03-24 19:02:31 +0000164 if (*Cur != '\0')
165 CCCClangArchs.insert(std::string(Cur));
Daniel Dunbar365c02f2009-03-10 20:52:46 +0000166 break;
167 }
168 }
169
Daniel Dunbardd98e2c2009-03-10 23:41:59 +0000170 } else if (!strcmp(Opt, "host-triple")) {
Daniel Dunbar365c02f2009-03-10 20:52:46 +0000171 assert(Start+1 < End && "FIXME: -ccc- argument handling.");
Daniel Dunbardd98e2c2009-03-10 23:41:59 +0000172 HostTriple = *++Start;
Daniel Dunbar365c02f2009-03-10 20:52:46 +0000173
174 } else {
175 // FIXME: Error handling.
176 llvm::errs() << "invalid option: " << *Start << "\n";
177 exit(1);
178 }
179 }
Daniel Dunbardd98e2c2009-03-10 23:41:59 +0000180
Daniel Dunbarf3cad362009-03-25 04:13:45 +0000181 InputArgList *Args = ParseArgStrings(Start, End);
Daniel Dunbar365c02f2009-03-10 20:52:46 +0000182
Daniel Dunbare5049522009-03-17 20:45:45 +0000183 Host = GetHostInfo(HostTriple);
Daniel Dunbarcb881672009-03-13 00:51:18 +0000184
Daniel Dunbar586dc232009-03-16 06:42:30 +0000185 // The compilation takes ownership of Args.
Daniel Dunbare530ad42009-03-18 22:16:03 +0000186 Compilation *C = new Compilation(*this, *Host->getToolChain(*Args), Args);
Daniel Dunbar21549232009-03-18 02:55:38 +0000187
188 // FIXME: This behavior shouldn't be here.
189 if (CCCPrintOptions) {
190 PrintOptions(C->getArgs());
191 return C;
192 }
193
194 if (!HandleImmediateArgs(*C))
195 return C;
196
197 // Construct the list of abstract actions to perform for this
198 // compilation. We avoid passing a Compilation here simply to
199 // enforce the abstraction that pipelining is not host or toolchain
200 // dependent (other than the driver driver test).
201 if (Host->useDriverDriver())
202 BuildUniversalActions(C->getArgs(), C->getActions());
203 else
204 BuildActions(C->getArgs(), C->getActions());
205
206 if (CCCPrintActions) {
Daniel Dunbar10ffa9a2009-03-18 03:13:20 +0000207 PrintActions(*C);
Daniel Dunbar21549232009-03-18 02:55:38 +0000208 return C;
209 }
210
211 BuildJobs(*C);
Daniel Dunbar8d2554a2009-03-15 01:38:15 +0000212
213 return C;
Daniel Dunbar365c02f2009-03-10 20:52:46 +0000214}
215
Daniel Dunbard65bddc2009-03-12 18:24:49 +0000216void Driver::PrintOptions(const ArgList &Args) const {
Daniel Dunbar06482622009-03-05 06:38:47 +0000217 unsigned i = 0;
Daniel Dunbar53ec5522009-03-12 07:58:46 +0000218 for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
Daniel Dunbar06482622009-03-05 06:38:47 +0000219 it != ie; ++it, ++i) {
220 Arg *A = *it;
221 llvm::errs() << "Option " << i << " - "
222 << "Name: \"" << A->getOption().getName() << "\", "
223 << "Values: {";
224 for (unsigned j = 0; j < A->getNumValues(); ++j) {
225 if (j)
226 llvm::errs() << ", ";
Daniel Dunbar53ec5522009-03-12 07:58:46 +0000227 llvm::errs() << '"' << A->getValue(Args, j) << '"';
Daniel Dunbar06482622009-03-05 06:38:47 +0000228 }
229 llvm::errs() << "}\n";
Daniel Dunbar06482622009-03-05 06:38:47 +0000230 }
Daniel Dunbar3ede8d02009-03-02 19:59:07 +0000231}
Daniel Dunbardd98e2c2009-03-10 23:41:59 +0000232
Daniel Dunbar91e28af2009-03-31 21:38:17 +0000233static std::string getOptionHelpName(const OptTable &Opts, options::ID Id) {
234 std::string Name = Opts.getOptionName(Id);
235
236 // Add metavar, if used.
237 switch (Opts.getOptionKind(Id)) {
238 case Option::GroupClass: case Option::InputClass: case Option::UnknownClass:
239 assert(0 && "Invalid option with help text.");
240
241 case Option::MultiArgClass: case Option::JoinedAndSeparateClass:
242 assert(0 && "Cannot print metavar for this kind of option.");
243
244 case Option::FlagClass:
245 break;
246
247 case Option::SeparateClass: case Option::JoinedOrSeparateClass:
248 Name += ' ';
249 // FALLTHROUGH
250 case Option::JoinedClass: case Option::CommaJoinedClass:
251 Name += Opts.getOptionMetaVar(Id);
252 break;
253 }
254
255 return Name;
256}
257
258void Driver::PrintHelp() const {
259 llvm::raw_ostream &OS = llvm::outs();
260
261 OS << "OVERVIEW: clang \"gcc-compatible\" driver\n";
262 OS << '\n';
263 OS << "USAGE: " << Name << " [options] <input files>\n";
264 OS << '\n';
265 OS << "OPTIONS:\n";
266
267 // Render help text into (option, help) pairs.
268 std::vector< std::pair<std::string, const char*> > OptionHelp;
269
270 for (unsigned i = options::OPT_INPUT, e = options::LastOption; i != e; ++i) {
271 options::ID Id = (options::ID) i;
272 if (const char *Text = getOpts().getOptionHelpText(Id))
273 OptionHelp.push_back(std::make_pair(getOptionHelpName(getOpts(), Id),
274 Text));
275 }
276
277 // Find the maximum option length.
278 unsigned OptionFieldWidth = 0;
279 for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
280 // Limit the amount of padding we are willing to give up for
281 // alignment.
282 unsigned Length = OptionHelp[i].first.size();
283 if (Length <= 23)
284 OptionFieldWidth = std::max(OptionFieldWidth, Length);
285 }
286
287 for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
288 const std::string &Option = OptionHelp[i].first;
289 OS << " " << Option;
290 for (int j = Option.length(), e = OptionFieldWidth; j < e; ++j)
291 OS << ' ';
292 OS << ' ' << OptionHelp[i].second << '\n';
293 }
294
295 OS.flush();
296}
297
Daniel Dunbar70c8db12009-03-26 16:09:13 +0000298void Driver::PrintVersion(const Compilation &C) const {
Mike Stump5d023c32009-03-18 14:00:02 +0000299 static char buf[] = "$URL$";
300 char *zap = strstr(buf, "/lib/Driver");
301 if (zap)
302 *zap = 0;
303 zap = strstr(buf, "/clang/tools/clang");
304 if (zap)
305 *zap = 0;
Mike Stumpe70295b2009-03-18 15:19:35 +0000306 const char *vers = buf+6;
Mike Stump8944c382009-03-18 18:45:55 +0000307 // FIXME: Add cmake support and remove #ifdef
308#ifdef SVN_REVISION
309 const char *revision = SVN_REVISION;
310#else
311 const char *revision = "";
312#endif
Daniel Dunbarcb881672009-03-13 00:51:18 +0000313 // FIXME: The following handlers should use a callback mechanism, we
314 // don't know what the client would like to do.
Mike Stumpd227fe72009-03-18 21:19:11 +0000315 llvm::errs() << "clang version 1.0 (" << vers << " " << revision << ")" << "\n";
Daniel Dunbar70c8db12009-03-26 16:09:13 +0000316
317 const ToolChain &TC = C.getDefaultToolChain();
Daniel Dunbarcd8e4c42009-03-30 06:36:42 +0000318 llvm::errs() << "Target: " << TC.getTripleString() << '\n';
Daniel Dunbarcb881672009-03-13 00:51:18 +0000319}
320
Daniel Dunbar21549232009-03-18 02:55:38 +0000321bool Driver::HandleImmediateArgs(const Compilation &C) {
Daniel Dunbarcb881672009-03-13 00:51:18 +0000322 // The order these options are handled in in gcc is all over the
323 // place, but we don't expect inconsistencies w.r.t. that to matter
324 // in practice.
Daniel Dunbar91e28af2009-03-31 21:38:17 +0000325
326 if (C.getArgs().hasArg(options::OPT__help)) {
327 PrintHelp();
328 return false;
329 }
330
Daniel Dunbar6cc73de2009-04-02 15:05:41 +0000331 if (C.getArgs().hasArg(options::OPT__version)) {
332 PrintVersion(C);
333 return false;
334 }
335
Daniel Dunbar21549232009-03-18 02:55:38 +0000336 if (C.getArgs().hasArg(options::OPT_v) ||
337 C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
Daniel Dunbar70c8db12009-03-26 16:09:13 +0000338 PrintVersion(C);
Daniel Dunbarcb881672009-03-13 00:51:18 +0000339 SuppressMissingInputWarning = true;
340 }
341
Daniel Dunbar21549232009-03-18 02:55:38 +0000342 const ToolChain &TC = C.getDefaultToolChain();
Daniel Dunbarca3459e2009-03-20 04:37:21 +0000343 if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
344 llvm::outs() << "programs: =";
345 for (ToolChain::path_list::const_iterator it = TC.getProgramPaths().begin(),
346 ie = TC.getProgramPaths().end(); it != ie; ++it) {
347 if (it != TC.getProgramPaths().begin())
348 llvm::outs() << ':';
349 llvm::outs() << *it;
350 }
351 llvm::outs() << "\n";
352 llvm::outs() << "libraries: =";
353 for (ToolChain::path_list::const_iterator it = TC.getFilePaths().begin(),
354 ie = TC.getFilePaths().end(); it != ie; ++it) {
355 if (it != TC.getFilePaths().begin())
356 llvm::outs() << ':';
357 llvm::outs() << *it;
358 }
359 llvm::outs() << "\n";
Daniel Dunbar91e28af2009-03-31 21:38:17 +0000360 return false;
Daniel Dunbarca3459e2009-03-20 04:37:21 +0000361 }
362
Daniel Dunbarcb881672009-03-13 00:51:18 +0000363 // FIXME: The following handlers should use a callback mechanism, we
364 // don't know what the client would like to do.
Daniel Dunbar21549232009-03-18 02:55:38 +0000365 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
366 llvm::outs() << GetFilePath(A->getValue(C.getArgs()), TC).toString()
367 << "\n";
Daniel Dunbarcb881672009-03-13 00:51:18 +0000368 return false;
369 }
370
Daniel Dunbar21549232009-03-18 02:55:38 +0000371 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
372 llvm::outs() << GetProgramPath(A->getValue(C.getArgs()), TC).toString()
373 << "\n";
Daniel Dunbarcb881672009-03-13 00:51:18 +0000374 return false;
375 }
376
Daniel Dunbar21549232009-03-18 02:55:38 +0000377 if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
Daniel Dunbar08c65e02009-03-27 14:26:33 +0000378 llvm::outs() << GetFilePath("libgcc.a", TC).toString() << "\n";
Daniel Dunbarcb881672009-03-13 00:51:18 +0000379 return false;
380 }
381
382 return true;
383}
384
Daniel Dunbar10ffa9a2009-03-18 03:13:20 +0000385static unsigned PrintActions1(const Compilation &C,
Daniel Dunbarba102132009-03-13 12:19:02 +0000386 Action *A,
387 std::map<Action*, unsigned> &Ids) {
388 if (Ids.count(A))
389 return Ids[A];
390
391 std::string str;
392 llvm::raw_string_ostream os(str);
393
394 os << Action::getClassName(A->getKind()) << ", ";
395 if (InputAction *IA = dyn_cast<InputAction>(A)) {
Daniel Dunbar10ffa9a2009-03-18 03:13:20 +0000396 os << "\"" << IA->getInputArg().getValue(C.getArgs()) << "\"";
Daniel Dunbarba102132009-03-13 12:19:02 +0000397 } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
Daniel Dunbar10ffa9a2009-03-18 03:13:20 +0000398 os << '"' << (BIA->getArchName() ? BIA->getArchName() :
399 C.getDefaultToolChain().getArchName()) << '"'
400 << ", {" << PrintActions1(C, *BIA->begin(), Ids) << "}";
Daniel Dunbarba102132009-03-13 12:19:02 +0000401 } else {
402 os << "{";
403 for (Action::iterator it = A->begin(), ie = A->end(); it != ie;) {
Daniel Dunbar10ffa9a2009-03-18 03:13:20 +0000404 os << PrintActions1(C, *it, Ids);
Daniel Dunbarba102132009-03-13 12:19:02 +0000405 ++it;
406 if (it != ie)
407 os << ", ";
408 }
409 os << "}";
410 }
411
412 unsigned Id = Ids.size();
413 Ids[A] = Id;
Daniel Dunbarb269c322009-03-13 17:20:20 +0000414 llvm::errs() << Id << ": " << os.str() << ", "
Daniel Dunbarba102132009-03-13 12:19:02 +0000415 << types::getTypeName(A->getType()) << "\n";
416
417 return Id;
418}
419
Daniel Dunbar10ffa9a2009-03-18 03:13:20 +0000420void Driver::PrintActions(const Compilation &C) const {
Daniel Dunbarba102132009-03-13 12:19:02 +0000421 std::map<Action*, unsigned> Ids;
Daniel Dunbar10ffa9a2009-03-18 03:13:20 +0000422 for (ActionList::const_iterator it = C.getActions().begin(),
423 ie = C.getActions().end(); it != ie; ++it)
424 PrintActions1(C, *it, Ids);
Daniel Dunbar53ec5522009-03-12 07:58:46 +0000425}
426
Daniel Dunbar21549232009-03-18 02:55:38 +0000427void Driver::BuildUniversalActions(const ArgList &Args,
428 ActionList &Actions) const {
Daniel Dunbar8f25c792009-03-18 01:38:48 +0000429 llvm::PrettyStackTraceString CrashInfo("Building actions for universal build");
Daniel Dunbar13689542009-03-13 20:33:35 +0000430 // Collect the list of architectures. Duplicates are allowed, but
431 // should only be handled once (in the order seen).
432 llvm::StringSet<> ArchNames;
433 llvm::SmallVector<const char *, 4> Archs;
Daniel Dunbar2fe63e62009-03-12 18:40:18 +0000434 for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
435 it != ie; ++it) {
436 Arg *A = *it;
437
438 if (A->getOption().getId() == options::OPT_arch) {
Daniel Dunbar13689542009-03-13 20:33:35 +0000439 const char *Name = A->getValue(Args);
440
Daniel Dunbar2fe63e62009-03-12 18:40:18 +0000441 // FIXME: We need to handle canonicalization of the specified
442 // arch?
443
Daniel Dunbar75877192009-03-19 07:55:12 +0000444 A->claim();
Daniel Dunbar13689542009-03-13 20:33:35 +0000445 if (ArchNames.insert(Name))
446 Archs.push_back(Name);
Daniel Dunbar2fe63e62009-03-12 18:40:18 +0000447 }
448 }
449
Daniel Dunbar10ffa9a2009-03-18 03:13:20 +0000450 // When there is no explicit arch for this platform, make sure we
451 // still bind the architecture (to the default) so that -Xarch_ is
452 // handled correctly.
453 if (!Archs.size())
454 Archs.push_back(0);
Daniel Dunbar2fe63e62009-03-12 18:40:18 +0000455
456 // FIXME: We killed off some others but these aren't yet detected in
457 // a functional manner. If we added information to jobs about which
458 // "auxiliary" files they wrote then we could detect the conflict
459 // these cause downstream.
460 if (Archs.size() > 1) {
461 // No recovery needed, the point of this is just to prevent
462 // overwriting the same files.
Daniel Dunbar2fe63e62009-03-12 18:40:18 +0000463 if (const Arg *A = Args.getLastArg(options::OPT_save_temps))
464 Diag(clang::diag::err_drv_invalid_opt_with_multiple_archs)
Daniel Dunbar38dd3d52009-03-20 06:14:23 +0000465 << A->getAsString(Args);
Daniel Dunbar2fe63e62009-03-12 18:40:18 +0000466 }
467
468 ActionList SingleActions;
469 BuildActions(Args, SingleActions);
470
471 // Add in arch binding and lipo (if necessary) for every top level
472 // action.
473 for (unsigned i = 0, e = SingleActions.size(); i != e; ++i) {
474 Action *Act = SingleActions[i];
475
476 // Make sure we can lipo this kind of output. If not (and it is an
477 // actual output) then we disallow, since we can't create an
478 // output file with the right name without overwriting it. We
479 // could remove this oddity by just changing the output names to
480 // include the arch, which would also fix
481 // -save-temps. Compatibility wins for now.
482
Daniel Dunbar3dbd6c52009-03-13 17:46:02 +0000483 if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
Daniel Dunbar2fe63e62009-03-12 18:40:18 +0000484 Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
485 << types::getTypeName(Act->getType());
486
487 ActionList Inputs;
Daniel Dunbar75877192009-03-19 07:55:12 +0000488 for (unsigned i = 0, e = Archs.size(); i != e; ++i)
Daniel Dunbar13689542009-03-13 20:33:35 +0000489 Inputs.push_back(new BindArchAction(Act, Archs[i]));
Daniel Dunbar2fe63e62009-03-12 18:40:18 +0000490
491 // Lipo if necessary, We do it this way because we need to set the
492 // arch flag so that -Xarch_ gets overwritten.
493 if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
494 Actions.append(Inputs.begin(), Inputs.end());
495 else
496 Actions.push_back(new LipoJobAction(Inputs, Act->getType()));
497 }
Daniel Dunbar53ec5522009-03-12 07:58:46 +0000498}
499
Daniel Dunbar21549232009-03-18 02:55:38 +0000500void Driver::BuildActions(const ArgList &Args, ActionList &Actions) const {
Daniel Dunbar8f25c792009-03-18 01:38:48 +0000501 llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
Daniel Dunbaraf61c712009-03-12 23:55:14 +0000502 // Start by constructing the list of inputs and their types.
503
Daniel Dunbar83dd21f2009-03-13 17:57:10 +0000504 // Track the current user specified (-x) input. We also explicitly
505 // track the argument used to set the type; we only want to claim
506 // the type when we actually use it, so we warn about unused -x
507 // arguments.
508 types::ID InputType = types::TY_Nothing;
509 Arg *InputTypeArg = 0;
510
Daniel Dunbar53ec5522009-03-12 07:58:46 +0000511 llvm::SmallVector<std::pair<types::ID, const Arg*>, 16> Inputs;
512 for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
513 it != ie; ++it) {
514 Arg *A = *it;
515
516 if (isa<InputOption>(A->getOption())) {
517 const char *Value = A->getValue(Args);
518 types::ID Ty = types::TY_INVALID;
519
520 // Infer the input type if necessary.
Daniel Dunbar83dd21f2009-03-13 17:57:10 +0000521 if (InputType == types::TY_Nothing) {
522 // If there was an explicit arg for this, claim it.
523 if (InputTypeArg)
524 InputTypeArg->claim();
525
Daniel Dunbar53ec5522009-03-12 07:58:46 +0000526 // stdin must be handled specially.
527 if (memcmp(Value, "-", 2) == 0) {
528 // If running with -E, treat as a C input (this changes the
529 // builtin macros, for example). This may be overridden by
530 // -ObjC below.
531 //
532 // Otherwise emit an error but still use a valid type to
533 // avoid spurious errors (e.g., no inputs).
Daniel Dunbar8022fd42009-03-15 00:48:16 +0000534 if (!Args.hasArg(options::OPT_E, false))
Daniel Dunbarb897f5d2009-03-12 09:13:48 +0000535 Diag(clang::diag::err_drv_unknown_stdin_type);
Daniel Dunbar53ec5522009-03-12 07:58:46 +0000536 Ty = types::TY_C;
537 } else {
538 // Otherwise lookup by extension, and fallback to ObjectType
Daniel Dunbare33bea42009-03-20 23:39:23 +0000539 // if not found. We use a host hook here because Darwin at
540 // least has its own idea of what .s is.
Daniel Dunbar53ec5522009-03-12 07:58:46 +0000541 if (const char *Ext = strrchr(Value, '.'))
Daniel Dunbare33bea42009-03-20 23:39:23 +0000542 Ty = Host->lookupTypeForExtension(Ext + 1);
543
Daniel Dunbar53ec5522009-03-12 07:58:46 +0000544 if (Ty == types::TY_INVALID)
545 Ty = types::TY_Object;
546 }
547
548 // -ObjC and -ObjC++ override the default language, but only
549 // -for "source files". We just treat everything that isn't a
550 // -linker input as a source file.
551 //
552 // FIXME: Clean this up if we move the phase sequence into the
553 // type.
554 if (Ty != types::TY_Object) {
555 if (Args.hasArg(options::OPT_ObjC))
556 Ty = types::TY_ObjC;
557 else if (Args.hasArg(options::OPT_ObjCXX))
558 Ty = types::TY_ObjCXX;
559 }
560 } else {
561 assert(InputTypeArg && "InputType set w/o InputTypeArg");
562 InputTypeArg->claim();
563 Ty = InputType;
564 }
565
566 // Check that the file exists. It isn't clear this is worth
567 // doing, since the tool presumably does this anyway, and this
568 // just adds an extra stat to the equation, but this is gcc
569 // compatible.
570 if (memcmp(Value, "-", 2) != 0 && !llvm::sys::Path(Value).exists())
Daniel Dunbarb897f5d2009-03-12 09:13:48 +0000571 Diag(clang::diag::err_drv_no_such_file) << A->getValue(Args);
Daniel Dunbar53ec5522009-03-12 07:58:46 +0000572 else
573 Inputs.push_back(std::make_pair(Ty, A));
574
575 } else if (A->getOption().isLinkerInput()) {
576 // Just treat as object type, we could make a special type for
577 // this if necessary.
578 Inputs.push_back(std::make_pair(types::TY_Object, A));
579
580 } else if (A->getOption().getId() == options::OPT_x) {
581 InputTypeArg = A;
582 InputType = types::lookupTypeForTypeSpecifier(A->getValue(Args));
583
584 // Follow gcc behavior and treat as linker input for invalid -x
585 // options. Its not clear why we shouldn't just revert to
586 // unknown; but this isn't very important, we might as well be
587 // bug comatible.
588 if (!InputType) {
Daniel Dunbarb897f5d2009-03-12 09:13:48 +0000589 Diag(clang::diag::err_drv_unknown_language) << A->getValue(Args);
Daniel Dunbar53ec5522009-03-12 07:58:46 +0000590 InputType = types::TY_Object;
591 }
592 }
593 }
594
Daniel Dunbar8b1604e2009-03-13 00:17:48 +0000595 if (!SuppressMissingInputWarning && Inputs.empty()) {
Daniel Dunbaraf61c712009-03-12 23:55:14 +0000596 Diag(clang::diag::err_drv_no_input_files);
597 return;
598 }
599
600 // Determine which compilation mode we are in. We look for options
601 // which affect the phase, starting with the earliest phases, and
602 // record which option we used to determine the final phase.
Daniel Dunbarad2a9af2009-03-13 11:38:42 +0000603 Arg *FinalPhaseArg = 0;
604 phases::ID FinalPhase;
Daniel Dunbaraf61c712009-03-12 23:55:14 +0000605
606 // -{E,M,MM} only run the preprocessor.
Daniel Dunbarad2a9af2009-03-13 11:38:42 +0000607 if ((FinalPhaseArg = Args.getLastArg(options::OPT_E)) ||
608 (FinalPhaseArg = Args.getLastArg(options::OPT_M)) ||
609 (FinalPhaseArg = Args.getLastArg(options::OPT_MM))) {
610 FinalPhase = phases::Preprocess;
Daniel Dunbaraf61c712009-03-12 23:55:14 +0000611
Daniel Dunbar8022fd42009-03-15 00:48:16 +0000612 // -{fsyntax-only,-analyze,emit-llvm,S} only run up to the compiler.
613 } else if ((FinalPhaseArg = Args.getLastArg(options::OPT_fsyntax_only)) ||
614 (FinalPhaseArg = Args.getLastArg(options::OPT__analyze)) ||
Daniel Dunbarad2a9af2009-03-13 11:38:42 +0000615 (FinalPhaseArg = Args.getLastArg(options::OPT_S))) {
616 FinalPhase = phases::Compile;
Daniel Dunbaraf61c712009-03-12 23:55:14 +0000617
618 // -c only runs up to the assembler.
Daniel Dunbarad2a9af2009-03-13 11:38:42 +0000619 } else if ((FinalPhaseArg = Args.getLastArg(options::OPT_c))) {
620 FinalPhase = phases::Assemble;
Daniel Dunbaraf61c712009-03-12 23:55:14 +0000621
622 // Otherwise do everything.
623 } else
Daniel Dunbarad2a9af2009-03-13 11:38:42 +0000624 FinalPhase = phases::Link;
Daniel Dunbaraf61c712009-03-12 23:55:14 +0000625
Daniel Dunbaraf61c712009-03-12 23:55:14 +0000626 // Reject -Z* at the top level, these options should never have been
627 // exposed by gcc.
Daniel Dunbard7b88c22009-03-26 16:12:09 +0000628 if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
Daniel Dunbar38dd3d52009-03-20 06:14:23 +0000629 Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
Daniel Dunbaraf61c712009-03-12 23:55:14 +0000630
Daniel Dunbarad2a9af2009-03-13 11:38:42 +0000631 // Construct the actions to perform.
632 ActionList LinkerInputs;
Daniel Dunbar53ec5522009-03-12 07:58:46 +0000633 for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
Daniel Dunbarad2a9af2009-03-13 11:38:42 +0000634 types::ID InputType = Inputs[i].first;
635 const Arg *InputArg = Inputs[i].second;
636
637 unsigned NumSteps = types::getNumCompilationPhases(InputType);
638 assert(NumSteps && "Invalid number of steps!");
639
640 // If the first step comes after the final phase we are doing as
641 // part of this compilation, warn the user about it.
642 phases::ID InitialPhase = types::getCompilationPhase(InputType, 0);
643 if (InitialPhase > FinalPhase) {
Daniel Dunbar05494a72009-03-19 07:57:08 +0000644 // Claim here to avoid the more general unused warning.
645 InputArg->claim();
Daniel Dunbarad2a9af2009-03-13 11:38:42 +0000646 Diag(clang::diag::warn_drv_input_file_unused)
Daniel Dunbar38dd3d52009-03-20 06:14:23 +0000647 << InputArg->getAsString(Args)
Daniel Dunbarad2a9af2009-03-13 11:38:42 +0000648 << getPhaseName(InitialPhase)
649 << FinalPhaseArg->getOption().getName();
650 continue;
651 }
652
653 // Build the pipeline for this file.
654 Action *Current = new InputAction(*InputArg, InputType);
655 for (unsigned i = 0; i != NumSteps; ++i) {
656 phases::ID Phase = types::getCompilationPhase(InputType, i);
657
658 // We are done if this step is past what the user requested.
659 if (Phase > FinalPhase)
660 break;
661
662 // Queue linker inputs.
663 if (Phase == phases::Link) {
664 assert(i + 1 == NumSteps && "linking must be final compilation step.");
665 LinkerInputs.push_back(Current);
666 Current = 0;
667 break;
668 }
669
Daniel Dunbar337a6272009-03-24 20:17:30 +0000670 // Some types skip the assembler phase (e.g., llvm-bc), but we
671 // can't encode this in the steps because the intermediate type
672 // depends on arguments. Just special case here.
673 if (Phase == phases::Assemble && Current->getType() != types::TY_PP_Asm)
674 continue;
675
Daniel Dunbarad2a9af2009-03-13 11:38:42 +0000676 // Otherwise construct the appropriate action.
677 Current = ConstructPhaseAction(Args, Phase, Current);
678 if (Current->getType() == types::TY_Nothing)
679 break;
680 }
681
682 // If we ended with something, add to the output list.
683 if (Current)
684 Actions.push_back(Current);
Daniel Dunbar53ec5522009-03-12 07:58:46 +0000685 }
Daniel Dunbarad2a9af2009-03-13 11:38:42 +0000686
687 // Add a link action if necessary.
688 if (!LinkerInputs.empty())
689 Actions.push_back(new LinkJobAction(LinkerInputs, types::TY_Image));
690}
691
692Action *Driver::ConstructPhaseAction(const ArgList &Args, phases::ID Phase,
693 Action *Input) const {
Daniel Dunbar8f25c792009-03-18 01:38:48 +0000694 llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
Daniel Dunbarad2a9af2009-03-13 11:38:42 +0000695 // Build the appropriate action.
696 switch (Phase) {
697 case phases::Link: assert(0 && "link action invalid here.");
698 case phases::Preprocess: {
Daniel Dunbarcd8e4c42009-03-30 06:36:42 +0000699 types::ID OutputTy;
700 // -{M, MM} alter the output type.
701 if (Args.hasArg(options::OPT_M) || Args.hasArg(options::OPT_MM)) {
702 OutputTy = types::TY_Dependencies;
703 } else {
704 OutputTy = types::getPreprocessedType(Input->getType());
705 assert(OutputTy != types::TY_INVALID &&
706 "Cannot preprocess this input type!");
707 }
Daniel Dunbarad2a9af2009-03-13 11:38:42 +0000708 return new PreprocessJobAction(Input, OutputTy);
709 }
710 case phases::Precompile:
711 return new PrecompileJobAction(Input, types::TY_PCH);
712 case phases::Compile: {
713 if (Args.hasArg(options::OPT_fsyntax_only)) {
714 return new CompileJobAction(Input, types::TY_Nothing);
715 } else if (Args.hasArg(options::OPT__analyze)) {
716 return new AnalyzeJobAction(Input, types::TY_Plist);
Daniel Dunbar337a6272009-03-24 20:17:30 +0000717 } else if (Args.hasArg(options::OPT_emit_llvm) ||
718 Args.hasArg(options::OPT_flto) ||
719 Args.hasArg(options::OPT_O4)) {
Daniel Dunbarad2a9af2009-03-13 11:38:42 +0000720 types::ID Output =
721 Args.hasArg(options::OPT_S) ? types::TY_LLVMAsm : types::TY_LLVMBC;
722 return new CompileJobAction(Input, Output);
723 } else {
724 return new CompileJobAction(Input, types::TY_PP_Asm);
725 }
726 }
727 case phases::Assemble:
728 return new AssembleJobAction(Input, types::TY_Object);
729 }
730
731 assert(0 && "invalid phase in ConstructPhaseAction");
732 return 0;
Daniel Dunbar53ec5522009-03-12 07:58:46 +0000733}
734
Daniel Dunbar21549232009-03-18 02:55:38 +0000735void Driver::BuildJobs(Compilation &C) const {
Daniel Dunbar8f25c792009-03-18 01:38:48 +0000736 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
Daniel Dunbarf353c8c2009-03-16 06:56:51 +0000737 bool SaveTemps = C.getArgs().hasArg(options::OPT_save_temps);
738 bool UsePipes = C.getArgs().hasArg(options::OPT_pipe);
Daniel Dunbar60ccc762009-03-18 23:18:19 +0000739
740 // FIXME: Pipes are forcibly disabled until we support executing
741 // them.
742 if (!CCCPrintBindings)
743 UsePipes = false;
Daniel Dunbarf353c8c2009-03-16 06:56:51 +0000744
745 // -save-temps inhibits pipes.
746 if (SaveTemps && UsePipes) {
747 Diag(clang::diag::warn_drv_pipe_ignored_with_save_temps);
748 UsePipes = true;
749 }
750
751 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
752
753 // It is an error to provide a -o option if we are making multiple
754 // output files.
755 if (FinalOutput) {
756 unsigned NumOutputs = 0;
Daniel Dunbar21549232009-03-18 02:55:38 +0000757 for (ActionList::const_iterator it = C.getActions().begin(),
758 ie = C.getActions().end(); it != ie; ++it)
Daniel Dunbarf353c8c2009-03-16 06:56:51 +0000759 if ((*it)->getType() != types::TY_Nothing)
760 ++NumOutputs;
761
762 if (NumOutputs > 1) {
763 Diag(clang::diag::err_drv_output_argument_with_multiple_files);
764 FinalOutput = 0;
765 }
766 }
767
Daniel Dunbar21549232009-03-18 02:55:38 +0000768 for (ActionList::const_iterator it = C.getActions().begin(),
769 ie = C.getActions().end(); it != ie; ++it) {
Daniel Dunbarf353c8c2009-03-16 06:56:51 +0000770 Action *A = *it;
771
772 // If we are linking an image for multiple archs then the linker
773 // wants -arch_multiple and -final_output <final image
774 // name>. Unfortunately, this doesn't fit in cleanly because we
775 // have to pass this information down.
776 //
777 // FIXME: This is a hack; find a cleaner way to integrate this
778 // into the process.
779 const char *LinkingOutput = 0;
Daniel Dunbard7b88c22009-03-26 16:12:09 +0000780 if (isa<LipoJobAction>(A)) {
Daniel Dunbarf353c8c2009-03-16 06:56:51 +0000781 if (FinalOutput)
782 LinkingOutput = FinalOutput->getValue(C.getArgs());
783 else
784 LinkingOutput = DefaultImageName.c_str();
785 }
786
787 InputInfo II;
Daniel Dunbar10ffa9a2009-03-18 03:13:20 +0000788 BuildJobsForAction(C, A, &C.getDefaultToolChain(),
Daniel Dunbarf353c8c2009-03-16 06:56:51 +0000789 /*CanAcceptPipe*/ true,
790 /*AtTopLevel*/ true,
791 /*LinkingOutput*/ LinkingOutput,
792 II);
793 }
Daniel Dunbar586dc232009-03-16 06:42:30 +0000794
Daniel Dunbarbf4a6762009-04-03 22:09:23 +0000795 // If the user passed -Qunused-arguments or there were errors, don't
796 // warn about any unused arguments.
797 if (Diags.getNumErrors() || C.getArgs().hasArg(options::OPT_Qunused_arguments))
Daniel Dunbaraf2e4ba2009-03-18 18:03:46 +0000798 return;
799
Daniel Dunbara2094e72009-03-29 22:24:54 +0000800 // Claim -### here.
801 (void) C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
802
Daniel Dunbar586dc232009-03-16 06:42:30 +0000803 for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end();
804 it != ie; ++it) {
805 Arg *A = *it;
Daniel Dunbaraf2e4ba2009-03-18 18:03:46 +0000806
Daniel Dunbar586dc232009-03-16 06:42:30 +0000807 // FIXME: It would be nice to be able to send the argument to the
808 // Diagnostic, so that extra values, position, and so on could be
809 // printed.
810 if (!A->isClaimed())
811 Diag(clang::diag::warn_drv_unused_argument)
Daniel Dunbar38dd3d52009-03-20 06:14:23 +0000812 << A->getAsString(C.getArgs());
Daniel Dunbar586dc232009-03-16 06:42:30 +0000813 }
Daniel Dunbar57b704d2009-03-13 22:12:33 +0000814}
815
Daniel Dunbarf353c8c2009-03-16 06:56:51 +0000816void Driver::BuildJobsForAction(Compilation &C,
817 const Action *A,
818 const ToolChain *TC,
819 bool CanAcceptPipe,
820 bool AtTopLevel,
821 const char *LinkingOutput,
822 InputInfo &Result) const {
Daniel Dunbar8f25c792009-03-18 01:38:48 +0000823 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs for action");
Daniel Dunbar60ccc762009-03-18 23:18:19 +0000824
825 bool UsePipes = C.getArgs().hasArg(options::OPT_pipe);
826 // FIXME: Pipes are forcibly disabled until we support executing
827 // them.
828 if (!CCCPrintBindings)
829 UsePipes = false;
830
Daniel Dunbarf353c8c2009-03-16 06:56:51 +0000831 if (const InputAction *IA = dyn_cast<InputAction>(A)) {
Daniel Dunbar115a7922009-03-19 07:29:38 +0000832 // FIXME: It would be nice to not claim this here; maybe the old
833 // scheme of just using Args was better?
834 const Arg &Input = IA->getInputArg();
835 Input.claim();
836 if (isa<PositionalArg>(Input)) {
837 const char *Name = Input.getValue(C.getArgs());
838 Result = InputInfo(Name, A->getType(), Name);
839 } else
840 Result = InputInfo(&Input, A->getType(), "");
Daniel Dunbarf353c8c2009-03-16 06:56:51 +0000841 return;
842 }
843
844 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
845 const char *ArchName = BAA->getArchName();
Daniel Dunbar10ffa9a2009-03-18 03:13:20 +0000846 if (!ArchName)
847 ArchName = C.getDefaultToolChain().getArchName().c_str();
Daniel Dunbarf353c8c2009-03-16 06:56:51 +0000848 BuildJobsForAction(C,
849 *BAA->begin(),
850 Host->getToolChain(C.getArgs(), ArchName),
851 CanAcceptPipe,
852 AtTopLevel,
853 LinkingOutput,
854 Result);
855 return;
856 }
857
858 const JobAction *JA = cast<JobAction>(A);
859 const Tool &T = TC->SelectTool(C, *JA);
860
861 // See if we should use an integrated preprocessor. We do so when we
862 // have exactly one input, since this is the only use case we care
863 // about (irrelevant since we don't support combine yet).
864 bool UseIntegratedCPP = false;
865 const ActionList *Inputs = &A->getInputs();
866 if (Inputs->size() == 1 && isa<PreprocessJobAction>(*Inputs->begin())) {
867 if (!C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
868 !C.getArgs().hasArg(options::OPT_traditional_cpp) &&
869 !C.getArgs().hasArg(options::OPT_save_temps) &&
870 T.hasIntegratedCPP()) {
871 UseIntegratedCPP = true;
872 Inputs = &(*Inputs)[0]->getInputs();
873 }
874 }
875
876 // Only use pipes when there is exactly one input.
877 bool TryToUsePipeInput = Inputs->size() == 1 && T.acceptsPipedInput();
Daniel Dunbar47ac7d22009-03-18 06:00:36 +0000878 InputInfoList InputInfos;
Daniel Dunbarf353c8c2009-03-16 06:56:51 +0000879 for (ActionList::const_iterator it = Inputs->begin(), ie = Inputs->end();
880 it != ie; ++it) {
881 InputInfo II;
882 BuildJobsForAction(C, *it, TC, TryToUsePipeInput,
883 /*AtTopLevel*/false,
884 LinkingOutput,
885 II);
886 InputInfos.push_back(II);
887 }
888
889 // Determine if we should output to a pipe.
890 bool OutputToPipe = false;
891 if (CanAcceptPipe && T.canPipeOutput()) {
892 // Some actions default to writing to a pipe if they are the top
893 // level phase and there was no user override.
894 //
895 // FIXME: Is there a better way to handle this?
896 if (AtTopLevel) {
897 if (isa<PreprocessJobAction>(A) && !C.getArgs().hasArg(options::OPT_o))
898 OutputToPipe = true;
Daniel Dunbar60ccc762009-03-18 23:18:19 +0000899 } else if (UsePipes)
Daniel Dunbarf353c8c2009-03-16 06:56:51 +0000900 OutputToPipe = true;
901 }
902
903 // Figure out where to put the job (pipes).
904 Job *Dest = &C.getJobs();
905 if (InputInfos[0].isPipe()) {
Daniel Dunbar441d0602009-03-17 17:53:55 +0000906 assert(TryToUsePipeInput && "Unrequested pipe!");
Daniel Dunbarf353c8c2009-03-16 06:56:51 +0000907 assert(InputInfos.size() == 1 && "Unexpected pipe with multiple inputs.");
908 Dest = &InputInfos[0].getPipe();
909 }
910
911 // Always use the first input as the base input.
912 const char *BaseInput = InputInfos[0].getBaseInput();
Daniel Dunbar441d0602009-03-17 17:53:55 +0000913
914 // Determine the place to write output to (nothing, pipe, or
915 // filename) and where to put the new job.
Daniel Dunbar441d0602009-03-17 17:53:55 +0000916 if (JA->getType() == types::TY_Nothing) {
Daniel Dunbar5c3c1d72009-03-17 22:47:06 +0000917 Result = InputInfo(A->getType(), BaseInput);
Daniel Dunbar441d0602009-03-17 17:53:55 +0000918 } else if (OutputToPipe) {
919 // Append to current piped job or create a new one as appropriate.
Daniel Dunbar5c3c1d72009-03-17 22:47:06 +0000920 PipedJob *PJ = dyn_cast<PipedJob>(Dest);
921 if (!PJ) {
922 PJ = new PipedJob();
Daniel Dunbarb7b61b22009-03-20 00:11:04 +0000923 // FIXME: Temporary hack so that -ccc-print-bindings work until
924 // we have pipe support. Please remove later.
925 if (!CCCPrintBindings)
926 cast<JobList>(Dest)->addJob(PJ);
Daniel Dunbar871adcf2009-03-18 07:06:02 +0000927 Dest = PJ;
Daniel Dunbar441d0602009-03-17 17:53:55 +0000928 }
Daniel Dunbar5c3c1d72009-03-17 22:47:06 +0000929 Result = InputInfo(PJ, A->getType(), BaseInput);
Daniel Dunbar441d0602009-03-17 17:53:55 +0000930 } else {
Daniel Dunbar5c3c1d72009-03-17 22:47:06 +0000931 Result = InputInfo(GetNamedOutputPath(C, *JA, BaseInput, AtTopLevel),
932 A->getType(), BaseInput);
Daniel Dunbar441d0602009-03-17 17:53:55 +0000933 }
934
Daniel Dunbar5c3c1d72009-03-17 22:47:06 +0000935 if (CCCPrintBindings) {
Daniel Dunbarcd8e4c42009-03-30 06:36:42 +0000936 llvm::errs() << "# \"" << T.getToolChain().getTripleString() << '"'
937 << " - \"" << T.getName() << "\", inputs: [";
Daniel Dunbar5c3c1d72009-03-17 22:47:06 +0000938 for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
939 llvm::errs() << InputInfos[i].getAsString();
940 if (i + 1 != e)
941 llvm::errs() << ", ";
942 }
943 llvm::errs() << "], output: " << Result.getAsString() << "\n";
944 } else {
Daniel Dunbarf3cad362009-03-25 04:13:45 +0000945 T.ConstructJob(C, *JA, *Dest, Result, InputInfos,
946 C.getArgsForToolChain(TC), LinkingOutput);
Daniel Dunbar5c3c1d72009-03-17 22:47:06 +0000947 }
Daniel Dunbarf353c8c2009-03-16 06:56:51 +0000948}
949
Daniel Dunbar441d0602009-03-17 17:53:55 +0000950const char *Driver::GetNamedOutputPath(Compilation &C,
951 const JobAction &JA,
952 const char *BaseInput,
953 bool AtTopLevel) const {
Daniel Dunbar8f25c792009-03-18 01:38:48 +0000954 llvm::PrettyStackTraceString CrashInfo("Computing output path");
Daniel Dunbar441d0602009-03-17 17:53:55 +0000955 // Output to a user requested destination?
956 if (AtTopLevel) {
957 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
958 return C.addResultFile(FinalOutput->getValue(C.getArgs()));
959 }
960
961 // Output to a temporary file?
962 if (!AtTopLevel && !C.getArgs().hasArg(options::OPT_save_temps)) {
Daniel Dunbar214399e2009-03-18 19:34:39 +0000963 std::string TmpName =
964 GetTemporaryPath(types::getTypeTempSuffix(JA.getType()));
965 return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()));
Daniel Dunbar441d0602009-03-17 17:53:55 +0000966 }
967
968 llvm::sys::Path BasePath(BaseInput);
Daniel Dunbar5796bf42009-03-18 02:00:31 +0000969 std::string BaseName(BasePath.getLast());
Daniel Dunbar441d0602009-03-17 17:53:55 +0000970
971 // Determine what the derived output name should be.
972 const char *NamedOutput;
973 if (JA.getType() == types::TY_Image) {
974 NamedOutput = DefaultImageName.c_str();
975 } else {
976 const char *Suffix = types::getTypeTempSuffix(JA.getType());
977 assert(Suffix && "All types used for output should have a suffix.");
978
979 std::string::size_type End = std::string::npos;
980 if (!types::appendSuffixForType(JA.getType()))
981 End = BaseName.rfind('.');
982 std::string Suffixed(BaseName.substr(0, End));
983 Suffixed += '.';
984 Suffixed += Suffix;
985 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
986 }
987
988 // As an annoying special case, PCH generation doesn't strip the
989 // pathname.
990 if (JA.getType() == types::TY_PCH) {
991 BasePath.eraseComponent();
Daniel Dunbar56c55942009-03-18 09:58:30 +0000992 if (BasePath.isEmpty())
993 BasePath = NamedOutput;
994 else
995 BasePath.appendComponent(NamedOutput);
Daniel Dunbar441d0602009-03-17 17:53:55 +0000996 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()));
997 } else {
998 return C.addResultFile(NamedOutput);
999 }
1000}
1001
Daniel Dunbar2ba38ba2009-03-16 05:25:36 +00001002llvm::sys::Path Driver::GetFilePath(const char *Name,
Daniel Dunbar21549232009-03-18 02:55:38 +00001003 const ToolChain &TC) const {
Daniel Dunbar0edefeb2009-03-18 20:26:19 +00001004 const ToolChain::path_list &List = TC.getFilePaths();
1005 for (ToolChain::path_list::const_iterator
1006 it = List.begin(), ie = List.end(); it != ie; ++it) {
1007 llvm::sys::Path P(*it);
1008 P.appendComponent(Name);
1009 if (P.exists())
1010 return P;
1011 }
1012
Daniel Dunbarcb881672009-03-13 00:51:18 +00001013 return llvm::sys::Path(Name);
1014}
1015
Daniel Dunbar2ba38ba2009-03-16 05:25:36 +00001016llvm::sys::Path Driver::GetProgramPath(const char *Name,
Mike Stump950bedd2009-03-27 00:40:20 +00001017 const ToolChain &TC,
1018 bool WantFile) const {
Daniel Dunbar0edefeb2009-03-18 20:26:19 +00001019 const ToolChain::path_list &List = TC.getProgramPaths();
1020 for (ToolChain::path_list::const_iterator
1021 it = List.begin(), ie = List.end(); it != ie; ++it) {
1022 llvm::sys::Path P(*it);
1023 P.appendComponent(Name);
Mike Stump950bedd2009-03-27 00:40:20 +00001024 if (WantFile ? P.exists() : P.canExecute())
Daniel Dunbar0edefeb2009-03-18 20:26:19 +00001025 return P;
1026 }
1027
Daniel Dunbarc50b00d2009-03-23 16:15:50 +00001028 // If all else failed, search the path.
1029 llvm::sys::Path P(llvm::sys::Program::FindProgramByName(Name));
Daniel Dunbar632f50e2009-03-18 21:34:08 +00001030 if (!P.empty())
1031 return P;
1032
Daniel Dunbarcb881672009-03-13 00:51:18 +00001033 return llvm::sys::Path(Name);
1034}
1035
Daniel Dunbar214399e2009-03-18 19:34:39 +00001036std::string Driver::GetTemporaryPath(const char *Suffix) const {
1037 // FIXME: This is lame; sys::Path should provide this function (in
1038 // particular, it should know how to find the temporary files dir).
1039 std::string Error;
1040 llvm::sys::Path P("/tmp/cc");
1041 if (P.makeUnique(false, &Error)) {
1042 Diag(clang::diag::err_drv_unable_to_make_temp) << Error;
1043 return "";
1044 }
1045
Daniel Dunbar84603bc2009-03-18 23:08:52 +00001046 // FIXME: Grumble, makeUnique sometimes leaves the file around!?
1047 // PR3837.
1048 P.eraseFromDisk(false, 0);
1049
Daniel Dunbar214399e2009-03-18 19:34:39 +00001050 P.appendSuffix(Suffix);
1051 return P.toString();
1052}
1053
Daniel Dunbare5049522009-03-17 20:45:45 +00001054const HostInfo *Driver::GetHostInfo(const char *Triple) const {
Daniel Dunbar8f25c792009-03-18 01:38:48 +00001055 llvm::PrettyStackTraceString CrashInfo("Constructing host");
Daniel Dunbardd98e2c2009-03-10 23:41:59 +00001056 // Dice into arch, platform, and OS. This matches
1057 // arch,platform,os = '(.*?)-(.*?)-(.*?)'
1058 // and missing fields are left empty.
1059 std::string Arch, Platform, OS;
1060
1061 if (const char *ArchEnd = strchr(Triple, '-')) {
1062 Arch = std::string(Triple, ArchEnd);
1063
1064 if (const char *PlatformEnd = strchr(ArchEnd+1, '-')) {
1065 Platform = std::string(ArchEnd+1, PlatformEnd);
1066 OS = PlatformEnd+1;
1067 } else
1068 Platform = ArchEnd+1;
1069 } else
1070 Arch = Triple;
1071
Daniel Dunbar1fd6c4b2009-03-17 19:00:50 +00001072 // Normalize Arch a bit.
1073 //
1074 // FIXME: This is very incomplete.
1075 if (Arch == "i686")
1076 Arch = "i386";
1077 else if (Arch == "amd64")
1078 Arch = "x86_64";
Daniel Dunbarbf54a062009-04-01 20:33:11 +00001079 else if (Arch == "ppc" || Arch == "Power Macintosh")
1080 Arch = "powerpc";
1081 else if (Arch == "ppc64")
1082 Arch = "powerpc64";
Daniel Dunbar1fd6c4b2009-03-17 19:00:50 +00001083
Daniel Dunbara88162c2009-03-13 12:23:29 +00001084 if (memcmp(&OS[0], "darwin", 6) == 0)
Daniel Dunbare5049522009-03-17 20:45:45 +00001085 return createDarwinHostInfo(*this, Arch.c_str(), Platform.c_str(),
1086 OS.c_str());
Daniel Dunbar75358d22009-03-30 21:06:03 +00001087 if (memcmp(&OS[0], "freebsd", 7) == 0)
1088 return createFreeBSDHostInfo(*this, Arch.c_str(), Platform.c_str(),
1089 OS.c_str());
Daniel Dunbardd98e2c2009-03-10 23:41:59 +00001090
Daniel Dunbare5049522009-03-17 20:45:45 +00001091 return createUnknownHostInfo(*this, Arch.c_str(), Platform.c_str(),
1092 OS.c_str());
Daniel Dunbardd98e2c2009-03-10 23:41:59 +00001093}
Daniel Dunbaraf80e1f2009-03-24 18:57:02 +00001094
1095bool Driver::ShouldUseClangCompiler(const Compilation &C, const JobAction &JA,
Daniel Dunbarbf54a062009-04-01 20:33:11 +00001096 const std::string &ArchNameStr) const {
1097 // FIXME: Remove this hack.
1098 const char *ArchName = ArchNameStr.c_str();
1099 if (ArchNameStr == "powerpc")
1100 ArchName = "ppc";
1101 else if (ArchNameStr == "powerpc64")
1102 ArchName = "ppc64";
1103
Daniel Dunbaraf80e1f2009-03-24 18:57:02 +00001104 // Check if user requested no clang, or clang doesn't understand
1105 // this type (we only handle single inputs for now).
Daniel Dunbar0f99d2e2009-03-24 19:02:31 +00001106 if (!CCCUseClang || JA.size() != 1 ||
Daniel Dunbaraf80e1f2009-03-24 18:57:02 +00001107 !types::isAcceptedByClang((*JA.begin())->getType()))
1108 return false;
1109
Daniel Dunbar0f99d2e2009-03-24 19:02:31 +00001110 // Otherwise make sure this is an action clang understands.
Daniel Dunbaraf80e1f2009-03-24 18:57:02 +00001111 if (isa<PreprocessJobAction>(JA)) {
Daniel Dunbar6256d362009-03-24 19:14:56 +00001112 if (!CCCUseClangCPP) {
1113 Diag(clang::diag::warn_drv_not_using_clang_cpp);
Daniel Dunbaraf80e1f2009-03-24 18:57:02 +00001114 return false;
Daniel Dunbar6256d362009-03-24 19:14:56 +00001115 }
Daniel Dunbaraf80e1f2009-03-24 18:57:02 +00001116 } else if (!isa<PrecompileJobAction>(JA) && !isa<CompileJobAction>(JA))
1117 return false;
1118
Daniel Dunbar0f99d2e2009-03-24 19:02:31 +00001119 // Use clang for C++?
Daniel Dunbar6256d362009-03-24 19:14:56 +00001120 if (!CCCUseClangCXX && types::isCXX((*JA.begin())->getType())) {
1121 Diag(clang::diag::warn_drv_not_using_clang_cxx);
Daniel Dunbaraf80e1f2009-03-24 18:57:02 +00001122 return false;
Daniel Dunbar6256d362009-03-24 19:14:56 +00001123 }
Daniel Dunbaraf80e1f2009-03-24 18:57:02 +00001124
1125 // Finally, don't use clang if this isn't one of the user specified
1126 // archs to build.
Daniel Dunbar6256d362009-03-24 19:14:56 +00001127 if (!CCCClangArchs.empty() && !CCCClangArchs.count(ArchName)) {
1128 Diag(clang::diag::warn_drv_not_using_clang_arch) << ArchName;
Daniel Dunbaraf80e1f2009-03-24 18:57:02 +00001129 return false;
Daniel Dunbar6256d362009-03-24 19:14:56 +00001130 }
Daniel Dunbaraf80e1f2009-03-24 18:57:02 +00001131
1132 return true;
1133}
Daniel Dunbard73fe9b2009-03-26 15:58:36 +00001134
1135/// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and
1136/// return the grouped values as integers. Numbers which are not
1137/// provided are set to 0.
1138///
1139/// \return True if the entire string was parsed (9.2), or all groups
1140/// were parsed (10.3.5extrastuff).
1141bool Driver::GetReleaseVersion(const char *Str, unsigned &Major,
1142 unsigned &Minor, unsigned &Micro,
1143 bool &HadExtra) {
1144 HadExtra = false;
1145
1146 Major = Minor = Micro = 0;
1147 if (*Str == '\0')
1148 return true;
1149
1150 char *End;
1151 Major = (unsigned) strtol(Str, &End, 10);
1152 if (*Str != '\0' && *End == '\0')
1153 return true;
1154 if (*End != '.')
1155 return false;
1156
1157 Str = End+1;
1158 Minor = (unsigned) strtol(Str, &End, 10);
1159 if (*Str != '\0' && *End == '\0')
1160 return true;
1161 if (*End != '.')
1162 return false;
1163
1164 Str = End+1;
1165 Micro = (unsigned) strtol(Str, &End, 10);
1166 if (*Str != '\0' && *End == '\0')
1167 return true;
1168 if (Str == End)
1169 return false;
1170 HadExtra = true;
1171 return true;
1172}