blob: 5afcefe68d32e0890fdbc64e5a45167bdac9058d [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
Daniel Dunbar365c02f2009-03-10 20:52:46 +0000112 // FIXME: This stuff needs to go into the Compilation, not the
113 // driver.
Daniel Dunbar53ec5522009-03-12 07:58:46 +0000114 bool CCCPrintOptions = false, CCCPrintActions = false;
Daniel Dunbar06482622009-03-05 06:38:47 +0000115
Daniel Dunbar365c02f2009-03-10 20:52:46 +0000116 const char **Start = argv + 1, **End = argv + argc;
Daniel Dunbardd98e2c2009-03-10 23:41:59 +0000117 const char *HostTriple = DefaultHostTriple.c_str();
Daniel Dunbar365c02f2009-03-10 20:52:46 +0000118
119 // Read -ccc args.
120 //
121 // FIXME: We need to figure out where this behavior should
122 // live. Most of it should be outside in the client; the parts that
123 // aren't should have proper options, either by introducing new ones
124 // or by overloading gcc ones like -V or -b.
125 for (; Start != End && memcmp(*Start, "-ccc-", 5) == 0; ++Start) {
126 const char *Opt = *Start + 5;
127
128 if (!strcmp(Opt, "print-options")) {
129 CCCPrintOptions = true;
130 } else if (!strcmp(Opt, "print-phases")) {
Daniel Dunbar53ec5522009-03-12 07:58:46 +0000131 CCCPrintActions = true;
Daniel Dunbar5c3c1d72009-03-17 22:47:06 +0000132 } else if (!strcmp(Opt, "print-bindings")) {
133 CCCPrintBindings = true;
Daniel Dunbar365c02f2009-03-10 20:52:46 +0000134 } else if (!strcmp(Opt, "cxx")) {
135 CCCIsCXX = true;
136 } else if (!strcmp(Opt, "echo")) {
137 CCCEcho = true;
138
Daniel Dunbar78d8a082009-04-01 23:34:41 +0000139 } else if (!strcmp(Opt, "gcc-name")) {
140 assert(Start+1 < End && "FIXME: -ccc- argument handling.");
141 CCCGenericGCCName = *++Start;
142
Daniel Dunbar0f99d2e2009-03-24 19:02:31 +0000143 } else if (!strcmp(Opt, "clang-cxx")) {
144 CCCUseClangCXX = true;
Daniel Dunbar365c02f2009-03-10 20:52:46 +0000145 } else if (!strcmp(Opt, "no-clang")) {
Daniel Dunbar0f99d2e2009-03-24 19:02:31 +0000146 CCCUseClang = false;
Daniel Dunbar365c02f2009-03-10 20:52:46 +0000147 } else if (!strcmp(Opt, "no-clang-cpp")) {
Daniel Dunbar0f99d2e2009-03-24 19:02:31 +0000148 CCCUseClangCPP = false;
Daniel Dunbar365c02f2009-03-10 20:52:46 +0000149 } else if (!strcmp(Opt, "clang-archs")) {
150 assert(Start+1 < End && "FIXME: -ccc- argument handling.");
151 const char *Cur = *++Start;
152
Daniel Dunbar0f99d2e2009-03-24 19:02:31 +0000153 CCCClangArchs.clear();
Daniel Dunbar365c02f2009-03-10 20:52:46 +0000154 for (;;) {
155 const char *Next = strchr(Cur, ',');
156
157 if (Next) {
Daniel Dunbar0f99d2e2009-03-24 19:02:31 +0000158 if (Cur != Next)
159 CCCClangArchs.insert(std::string(Cur, Next));
Daniel Dunbar365c02f2009-03-10 20:52:46 +0000160 Cur = Next + 1;
161 } else {
Daniel Dunbar0f99d2e2009-03-24 19:02:31 +0000162 if (*Cur != '\0')
163 CCCClangArchs.insert(std::string(Cur));
Daniel Dunbar365c02f2009-03-10 20:52:46 +0000164 break;
165 }
166 }
167
Daniel Dunbardd98e2c2009-03-10 23:41:59 +0000168 } else if (!strcmp(Opt, "host-triple")) {
Daniel Dunbar365c02f2009-03-10 20:52:46 +0000169 assert(Start+1 < End && "FIXME: -ccc- argument handling.");
Daniel Dunbardd98e2c2009-03-10 23:41:59 +0000170 HostTriple = *++Start;
Daniel Dunbar365c02f2009-03-10 20:52:46 +0000171
172 } else {
173 // FIXME: Error handling.
174 llvm::errs() << "invalid option: " << *Start << "\n";
175 exit(1);
176 }
177 }
Daniel Dunbardd98e2c2009-03-10 23:41:59 +0000178
Daniel Dunbarf3cad362009-03-25 04:13:45 +0000179 InputArgList *Args = ParseArgStrings(Start, End);
Daniel Dunbar365c02f2009-03-10 20:52:46 +0000180
Daniel Dunbare5049522009-03-17 20:45:45 +0000181 Host = GetHostInfo(HostTriple);
Daniel Dunbarcb881672009-03-13 00:51:18 +0000182
Daniel Dunbar586dc232009-03-16 06:42:30 +0000183 // The compilation takes ownership of Args.
Daniel Dunbare530ad42009-03-18 22:16:03 +0000184 Compilation *C = new Compilation(*this, *Host->getToolChain(*Args), Args);
Daniel Dunbar21549232009-03-18 02:55:38 +0000185
186 // FIXME: This behavior shouldn't be here.
187 if (CCCPrintOptions) {
188 PrintOptions(C->getArgs());
189 return C;
190 }
191
192 if (!HandleImmediateArgs(*C))
193 return C;
194
195 // Construct the list of abstract actions to perform for this
196 // compilation. We avoid passing a Compilation here simply to
197 // enforce the abstraction that pipelining is not host or toolchain
198 // dependent (other than the driver driver test).
199 if (Host->useDriverDriver())
200 BuildUniversalActions(C->getArgs(), C->getActions());
201 else
202 BuildActions(C->getArgs(), C->getActions());
203
204 if (CCCPrintActions) {
Daniel Dunbar10ffa9a2009-03-18 03:13:20 +0000205 PrintActions(*C);
Daniel Dunbar21549232009-03-18 02:55:38 +0000206 return C;
207 }
208
209 BuildJobs(*C);
Daniel Dunbar8d2554a2009-03-15 01:38:15 +0000210
211 return C;
Daniel Dunbar365c02f2009-03-10 20:52:46 +0000212}
213
Daniel Dunbard65bddc2009-03-12 18:24:49 +0000214void Driver::PrintOptions(const ArgList &Args) const {
Daniel Dunbar06482622009-03-05 06:38:47 +0000215 unsigned i = 0;
Daniel Dunbar53ec5522009-03-12 07:58:46 +0000216 for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
Daniel Dunbar06482622009-03-05 06:38:47 +0000217 it != ie; ++it, ++i) {
218 Arg *A = *it;
219 llvm::errs() << "Option " << i << " - "
220 << "Name: \"" << A->getOption().getName() << "\", "
221 << "Values: {";
222 for (unsigned j = 0; j < A->getNumValues(); ++j) {
223 if (j)
224 llvm::errs() << ", ";
Daniel Dunbar53ec5522009-03-12 07:58:46 +0000225 llvm::errs() << '"' << A->getValue(Args, j) << '"';
Daniel Dunbar06482622009-03-05 06:38:47 +0000226 }
227 llvm::errs() << "}\n";
Daniel Dunbar06482622009-03-05 06:38:47 +0000228 }
Daniel Dunbar3ede8d02009-03-02 19:59:07 +0000229}
Daniel Dunbardd98e2c2009-03-10 23:41:59 +0000230
Daniel Dunbar91e28af2009-03-31 21:38:17 +0000231static std::string getOptionHelpName(const OptTable &Opts, options::ID Id) {
232 std::string Name = Opts.getOptionName(Id);
233
234 // Add metavar, if used.
235 switch (Opts.getOptionKind(Id)) {
236 case Option::GroupClass: case Option::InputClass: case Option::UnknownClass:
237 assert(0 && "Invalid option with help text.");
238
239 case Option::MultiArgClass: case Option::JoinedAndSeparateClass:
240 assert(0 && "Cannot print metavar for this kind of option.");
241
242 case Option::FlagClass:
243 break;
244
245 case Option::SeparateClass: case Option::JoinedOrSeparateClass:
246 Name += ' ';
247 // FALLTHROUGH
248 case Option::JoinedClass: case Option::CommaJoinedClass:
249 Name += Opts.getOptionMetaVar(Id);
250 break;
251 }
252
253 return Name;
254}
255
Daniel Dunbarc35d71f2009-04-15 16:34:29 +0000256void Driver::PrintHelp(bool ShowHidden) const {
Daniel Dunbar91e28af2009-03-31 21:38:17 +0000257 llvm::raw_ostream &OS = llvm::outs();
258
259 OS << "OVERVIEW: clang \"gcc-compatible\" driver\n";
260 OS << '\n';
261 OS << "USAGE: " << Name << " [options] <input files>\n";
262 OS << '\n';
263 OS << "OPTIONS:\n";
264
265 // Render help text into (option, help) pairs.
266 std::vector< std::pair<std::string, const char*> > OptionHelp;
267
268 for (unsigned i = options::OPT_INPUT, e = options::LastOption; i != e; ++i) {
269 options::ID Id = (options::ID) i;
270 if (const char *Text = getOpts().getOptionHelpText(Id))
271 OptionHelp.push_back(std::make_pair(getOptionHelpName(getOpts(), Id),
272 Text));
273 }
274
Daniel Dunbarc35d71f2009-04-15 16:34:29 +0000275 if (ShowHidden) {
276 OptionHelp.push_back(std::make_pair("\nDRIVER OPTIONS:",""));
277 OptionHelp.push_back(std::make_pair("-ccc-cxx",
278 "Act as a C++ driver"));
279 OptionHelp.push_back(std::make_pair("-ccc-gcc-name",
280 "Name for native GCC compiler"));
281 OptionHelp.push_back(std::make_pair("-ccc-clang-cxx",
282 "Use the clang compiler for C++"));
283 OptionHelp.push_back(std::make_pair("-ccc-no-clang",
284 "Never use the clang compiler"));
285 OptionHelp.push_back(std::make_pair("-ccc-no-clang-cpp",
286 "Never use the clang preprocessor"));
287 OptionHelp.push_back(std::make_pair("-ccc-clang-archs",
288 "Comma separate list of architectures "
289 "to use the clang compiler for"));
290
291 OptionHelp.push_back(std::make_pair("\nDEBUG/DEVELOPMENT OPTIONS:",""));
292 OptionHelp.push_back(std::make_pair("-ccc-host-triple",
293 "Simulate running on the given target"));
294 OptionHelp.push_back(std::make_pair("-ccc-print-options",
295 "Dump parsed command line arguments"));
296 OptionHelp.push_back(std::make_pair("-ccc-print-phases",
297 "Dump list of actions to perform"));
298 OptionHelp.push_back(std::make_pair("-ccc-print-bindings",
299 "Show bindings of tools to actions"));
300 OptionHelp.push_back(std::make_pair("CCC_ADD_ARGS",
301 "(ENVIRONMENT VARIABLE) Comma separated list of "
302 "arguments to prepend to the command line"));
303 }
304
Daniel Dunbar91e28af2009-03-31 21:38:17 +0000305 // Find the maximum option length.
306 unsigned OptionFieldWidth = 0;
307 for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
Daniel Dunbarc35d71f2009-04-15 16:34:29 +0000308 // Skip titles.
309 if (!OptionHelp[i].second)
310 continue;
311
Daniel Dunbar91e28af2009-03-31 21:38:17 +0000312 // Limit the amount of padding we are willing to give up for
313 // alignment.
314 unsigned Length = OptionHelp[i].first.size();
315 if (Length <= 23)
316 OptionFieldWidth = std::max(OptionFieldWidth, Length);
317 }
318
319 for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
320 const std::string &Option = OptionHelp[i].first;
321 OS << " " << Option;
322 for (int j = Option.length(), e = OptionFieldWidth; j < e; ++j)
323 OS << ' ';
324 OS << ' ' << OptionHelp[i].second << '\n';
325 }
326
327 OS.flush();
328}
329
Daniel Dunbar70c8db12009-03-26 16:09:13 +0000330void Driver::PrintVersion(const Compilation &C) const {
Mike Stump5d023c32009-03-18 14:00:02 +0000331 static char buf[] = "$URL$";
332 char *zap = strstr(buf, "/lib/Driver");
333 if (zap)
334 *zap = 0;
335 zap = strstr(buf, "/clang/tools/clang");
336 if (zap)
337 *zap = 0;
Mike Stumpe70295b2009-03-18 15:19:35 +0000338 const char *vers = buf+6;
Mike Stump8944c382009-03-18 18:45:55 +0000339 // FIXME: Add cmake support and remove #ifdef
340#ifdef SVN_REVISION
341 const char *revision = SVN_REVISION;
342#else
343 const char *revision = "";
344#endif
Daniel Dunbarcb881672009-03-13 00:51:18 +0000345 // FIXME: The following handlers should use a callback mechanism, we
346 // don't know what the client would like to do.
Daniel Dunbare06dc212009-04-04 05:17:38 +0000347
348 // FIXME: Do not hardcode clang version.
Mike Stumpd227fe72009-03-18 21:19:11 +0000349 llvm::errs() << "clang version 1.0 (" << vers << " " << revision << ")" << "\n";
Daniel Dunbar70c8db12009-03-26 16:09:13 +0000350
351 const ToolChain &TC = C.getDefaultToolChain();
Daniel Dunbarcd8e4c42009-03-30 06:36:42 +0000352 llvm::errs() << "Target: " << TC.getTripleString() << '\n';
Daniel Dunbarcb881672009-03-13 00:51:18 +0000353}
354
Daniel Dunbar21549232009-03-18 02:55:38 +0000355bool Driver::HandleImmediateArgs(const Compilation &C) {
Daniel Dunbarcb881672009-03-13 00:51:18 +0000356 // The order these options are handled in in gcc is all over the
357 // place, but we don't expect inconsistencies w.r.t. that to matter
358 // in practice.
Daniel Dunbar91e28af2009-03-31 21:38:17 +0000359
Daniel Dunbare06dc212009-04-04 05:17:38 +0000360 if (C.getArgs().hasArg(options::OPT_dumpversion)) {
361 // FIXME: Do not hardcode clang version.
362 llvm::outs() << "1.0\n";
363 return false;
364 }
365
Daniel Dunbarc35d71f2009-04-15 16:34:29 +0000366 if (C.getArgs().hasArg(options::OPT__help) ||
367 C.getArgs().hasArg(options::OPT__help_hidden)) {
368 PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
Daniel Dunbar91e28af2009-03-31 21:38:17 +0000369 return false;
370 }
371
Daniel Dunbar6cc73de2009-04-02 15:05:41 +0000372 if (C.getArgs().hasArg(options::OPT__version)) {
373 PrintVersion(C);
374 return false;
375 }
376
Daniel Dunbar21549232009-03-18 02:55:38 +0000377 if (C.getArgs().hasArg(options::OPT_v) ||
378 C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
Daniel Dunbar70c8db12009-03-26 16:09:13 +0000379 PrintVersion(C);
Daniel Dunbarcb881672009-03-13 00:51:18 +0000380 SuppressMissingInputWarning = true;
381 }
382
Daniel Dunbar21549232009-03-18 02:55:38 +0000383 const ToolChain &TC = C.getDefaultToolChain();
Daniel Dunbarca3459e2009-03-20 04:37:21 +0000384 if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
385 llvm::outs() << "programs: =";
386 for (ToolChain::path_list::const_iterator it = TC.getProgramPaths().begin(),
387 ie = TC.getProgramPaths().end(); it != ie; ++it) {
388 if (it != TC.getProgramPaths().begin())
389 llvm::outs() << ':';
390 llvm::outs() << *it;
391 }
392 llvm::outs() << "\n";
393 llvm::outs() << "libraries: =";
394 for (ToolChain::path_list::const_iterator it = TC.getFilePaths().begin(),
395 ie = TC.getFilePaths().end(); it != ie; ++it) {
396 if (it != TC.getFilePaths().begin())
397 llvm::outs() << ':';
398 llvm::outs() << *it;
399 }
400 llvm::outs() << "\n";
Daniel Dunbar91e28af2009-03-31 21:38:17 +0000401 return false;
Daniel Dunbarca3459e2009-03-20 04:37:21 +0000402 }
403
Daniel Dunbarcb881672009-03-13 00:51:18 +0000404 // FIXME: The following handlers should use a callback mechanism, we
405 // don't know what the client would like to do.
Daniel Dunbar21549232009-03-18 02:55:38 +0000406 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
407 llvm::outs() << GetFilePath(A->getValue(C.getArgs()), TC).toString()
408 << "\n";
Daniel Dunbarcb881672009-03-13 00:51:18 +0000409 return false;
410 }
411
Daniel Dunbar21549232009-03-18 02:55:38 +0000412 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
413 llvm::outs() << GetProgramPath(A->getValue(C.getArgs()), TC).toString()
414 << "\n";
Daniel Dunbarcb881672009-03-13 00:51:18 +0000415 return false;
416 }
417
Daniel Dunbar21549232009-03-18 02:55:38 +0000418 if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
Daniel Dunbar08c65e02009-03-27 14:26:33 +0000419 llvm::outs() << GetFilePath("libgcc.a", TC).toString() << "\n";
Daniel Dunbarcb881672009-03-13 00:51:18 +0000420 return false;
421 }
422
423 return true;
424}
425
Daniel Dunbar10ffa9a2009-03-18 03:13:20 +0000426static unsigned PrintActions1(const Compilation &C,
Daniel Dunbarba102132009-03-13 12:19:02 +0000427 Action *A,
428 std::map<Action*, unsigned> &Ids) {
429 if (Ids.count(A))
430 return Ids[A];
431
432 std::string str;
433 llvm::raw_string_ostream os(str);
434
435 os << Action::getClassName(A->getKind()) << ", ";
436 if (InputAction *IA = dyn_cast<InputAction>(A)) {
Daniel Dunbar10ffa9a2009-03-18 03:13:20 +0000437 os << "\"" << IA->getInputArg().getValue(C.getArgs()) << "\"";
Daniel Dunbarba102132009-03-13 12:19:02 +0000438 } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
Daniel Dunbar10ffa9a2009-03-18 03:13:20 +0000439 os << '"' << (BIA->getArchName() ? BIA->getArchName() :
440 C.getDefaultToolChain().getArchName()) << '"'
441 << ", {" << PrintActions1(C, *BIA->begin(), Ids) << "}";
Daniel Dunbarba102132009-03-13 12:19:02 +0000442 } else {
443 os << "{";
444 for (Action::iterator it = A->begin(), ie = A->end(); it != ie;) {
Daniel Dunbar10ffa9a2009-03-18 03:13:20 +0000445 os << PrintActions1(C, *it, Ids);
Daniel Dunbarba102132009-03-13 12:19:02 +0000446 ++it;
447 if (it != ie)
448 os << ", ";
449 }
450 os << "}";
451 }
452
453 unsigned Id = Ids.size();
454 Ids[A] = Id;
Daniel Dunbarb269c322009-03-13 17:20:20 +0000455 llvm::errs() << Id << ": " << os.str() << ", "
Daniel Dunbarba102132009-03-13 12:19:02 +0000456 << types::getTypeName(A->getType()) << "\n";
457
458 return Id;
459}
460
Daniel Dunbar10ffa9a2009-03-18 03:13:20 +0000461void Driver::PrintActions(const Compilation &C) const {
Daniel Dunbarba102132009-03-13 12:19:02 +0000462 std::map<Action*, unsigned> Ids;
Daniel Dunbar10ffa9a2009-03-18 03:13:20 +0000463 for (ActionList::const_iterator it = C.getActions().begin(),
464 ie = C.getActions().end(); it != ie; ++it)
465 PrintActions1(C, *it, Ids);
Daniel Dunbar53ec5522009-03-12 07:58:46 +0000466}
467
Daniel Dunbar21549232009-03-18 02:55:38 +0000468void Driver::BuildUniversalActions(const ArgList &Args,
469 ActionList &Actions) const {
Daniel Dunbar8f25c792009-03-18 01:38:48 +0000470 llvm::PrettyStackTraceString CrashInfo("Building actions for universal build");
Daniel Dunbar13689542009-03-13 20:33:35 +0000471 // Collect the list of architectures. Duplicates are allowed, but
472 // should only be handled once (in the order seen).
473 llvm::StringSet<> ArchNames;
474 llvm::SmallVector<const char *, 4> Archs;
Daniel Dunbar2fe63e62009-03-12 18:40:18 +0000475 for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
476 it != ie; ++it) {
477 Arg *A = *it;
478
479 if (A->getOption().getId() == options::OPT_arch) {
Daniel Dunbar13689542009-03-13 20:33:35 +0000480 const char *Name = A->getValue(Args);
481
Daniel Dunbar2fe63e62009-03-12 18:40:18 +0000482 // FIXME: We need to handle canonicalization of the specified
483 // arch?
484
Daniel Dunbar75877192009-03-19 07:55:12 +0000485 A->claim();
Daniel Dunbar13689542009-03-13 20:33:35 +0000486 if (ArchNames.insert(Name))
487 Archs.push_back(Name);
Daniel Dunbar2fe63e62009-03-12 18:40:18 +0000488 }
489 }
490
Daniel Dunbar10ffa9a2009-03-18 03:13:20 +0000491 // When there is no explicit arch for this platform, make sure we
492 // still bind the architecture (to the default) so that -Xarch_ is
493 // handled correctly.
494 if (!Archs.size())
495 Archs.push_back(0);
Daniel Dunbar2fe63e62009-03-12 18:40:18 +0000496
497 // FIXME: We killed off some others but these aren't yet detected in
498 // a functional manner. If we added information to jobs about which
499 // "auxiliary" files they wrote then we could detect the conflict
500 // these cause downstream.
501 if (Archs.size() > 1) {
502 // No recovery needed, the point of this is just to prevent
503 // overwriting the same files.
Daniel Dunbar2fe63e62009-03-12 18:40:18 +0000504 if (const Arg *A = Args.getLastArg(options::OPT_save_temps))
505 Diag(clang::diag::err_drv_invalid_opt_with_multiple_archs)
Daniel Dunbar38dd3d52009-03-20 06:14:23 +0000506 << A->getAsString(Args);
Daniel Dunbar2fe63e62009-03-12 18:40:18 +0000507 }
508
509 ActionList SingleActions;
510 BuildActions(Args, SingleActions);
511
512 // Add in arch binding and lipo (if necessary) for every top level
513 // action.
514 for (unsigned i = 0, e = SingleActions.size(); i != e; ++i) {
515 Action *Act = SingleActions[i];
516
517 // Make sure we can lipo this kind of output. If not (and it is an
518 // actual output) then we disallow, since we can't create an
519 // output file with the right name without overwriting it. We
520 // could remove this oddity by just changing the output names to
521 // include the arch, which would also fix
522 // -save-temps. Compatibility wins for now.
523
Daniel Dunbar3dbd6c52009-03-13 17:46:02 +0000524 if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
Daniel Dunbar2fe63e62009-03-12 18:40:18 +0000525 Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
526 << types::getTypeName(Act->getType());
527
528 ActionList Inputs;
Daniel Dunbar75877192009-03-19 07:55:12 +0000529 for (unsigned i = 0, e = Archs.size(); i != e; ++i)
Daniel Dunbar13689542009-03-13 20:33:35 +0000530 Inputs.push_back(new BindArchAction(Act, Archs[i]));
Daniel Dunbar2fe63e62009-03-12 18:40:18 +0000531
532 // Lipo if necessary, We do it this way because we need to set the
533 // arch flag so that -Xarch_ gets overwritten.
534 if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
535 Actions.append(Inputs.begin(), Inputs.end());
536 else
537 Actions.push_back(new LipoJobAction(Inputs, Act->getType()));
538 }
Daniel Dunbar53ec5522009-03-12 07:58:46 +0000539}
540
Daniel Dunbar21549232009-03-18 02:55:38 +0000541void Driver::BuildActions(const ArgList &Args, ActionList &Actions) const {
Daniel Dunbar8f25c792009-03-18 01:38:48 +0000542 llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
Daniel Dunbaraf61c712009-03-12 23:55:14 +0000543 // Start by constructing the list of inputs and their types.
544
Daniel Dunbar83dd21f2009-03-13 17:57:10 +0000545 // Track the current user specified (-x) input. We also explicitly
546 // track the argument used to set the type; we only want to claim
547 // the type when we actually use it, so we warn about unused -x
548 // arguments.
549 types::ID InputType = types::TY_Nothing;
550 Arg *InputTypeArg = 0;
551
Daniel Dunbar53ec5522009-03-12 07:58:46 +0000552 llvm::SmallVector<std::pair<types::ID, const Arg*>, 16> Inputs;
553 for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
554 it != ie; ++it) {
555 Arg *A = *it;
556
557 if (isa<InputOption>(A->getOption())) {
558 const char *Value = A->getValue(Args);
559 types::ID Ty = types::TY_INVALID;
560
561 // Infer the input type if necessary.
Daniel Dunbar83dd21f2009-03-13 17:57:10 +0000562 if (InputType == types::TY_Nothing) {
563 // If there was an explicit arg for this, claim it.
564 if (InputTypeArg)
565 InputTypeArg->claim();
566
Daniel Dunbar53ec5522009-03-12 07:58:46 +0000567 // stdin must be handled specially.
568 if (memcmp(Value, "-", 2) == 0) {
569 // If running with -E, treat as a C input (this changes the
570 // builtin macros, for example). This may be overridden by
571 // -ObjC below.
572 //
573 // Otherwise emit an error but still use a valid type to
574 // avoid spurious errors (e.g., no inputs).
Daniel Dunbar8022fd42009-03-15 00:48:16 +0000575 if (!Args.hasArg(options::OPT_E, false))
Daniel Dunbarb897f5d2009-03-12 09:13:48 +0000576 Diag(clang::diag::err_drv_unknown_stdin_type);
Daniel Dunbar53ec5522009-03-12 07:58:46 +0000577 Ty = types::TY_C;
578 } else {
579 // Otherwise lookup by extension, and fallback to ObjectType
Daniel Dunbare33bea42009-03-20 23:39:23 +0000580 // if not found. We use a host hook here because Darwin at
581 // least has its own idea of what .s is.
Daniel Dunbar53ec5522009-03-12 07:58:46 +0000582 if (const char *Ext = strrchr(Value, '.'))
Daniel Dunbare33bea42009-03-20 23:39:23 +0000583 Ty = Host->lookupTypeForExtension(Ext + 1);
584
Daniel Dunbar53ec5522009-03-12 07:58:46 +0000585 if (Ty == types::TY_INVALID)
586 Ty = types::TY_Object;
587 }
588
589 // -ObjC and -ObjC++ override the default language, but only
590 // -for "source files". We just treat everything that isn't a
591 // -linker input as a source file.
592 //
593 // FIXME: Clean this up if we move the phase sequence into the
594 // type.
595 if (Ty != types::TY_Object) {
596 if (Args.hasArg(options::OPT_ObjC))
597 Ty = types::TY_ObjC;
598 else if (Args.hasArg(options::OPT_ObjCXX))
599 Ty = types::TY_ObjCXX;
600 }
601 } else {
602 assert(InputTypeArg && "InputType set w/o InputTypeArg");
603 InputTypeArg->claim();
604 Ty = InputType;
605 }
606
607 // Check that the file exists. It isn't clear this is worth
608 // doing, since the tool presumably does this anyway, and this
609 // just adds an extra stat to the equation, but this is gcc
610 // compatible.
611 if (memcmp(Value, "-", 2) != 0 && !llvm::sys::Path(Value).exists())
Daniel Dunbarb897f5d2009-03-12 09:13:48 +0000612 Diag(clang::diag::err_drv_no_such_file) << A->getValue(Args);
Daniel Dunbar53ec5522009-03-12 07:58:46 +0000613 else
614 Inputs.push_back(std::make_pair(Ty, A));
615
616 } else if (A->getOption().isLinkerInput()) {
617 // Just treat as object type, we could make a special type for
618 // this if necessary.
619 Inputs.push_back(std::make_pair(types::TY_Object, A));
620
621 } else if (A->getOption().getId() == options::OPT_x) {
622 InputTypeArg = A;
623 InputType = types::lookupTypeForTypeSpecifier(A->getValue(Args));
624
625 // Follow gcc behavior and treat as linker input for invalid -x
626 // options. Its not clear why we shouldn't just revert to
627 // unknown; but this isn't very important, we might as well be
628 // bug comatible.
629 if (!InputType) {
Daniel Dunbarb897f5d2009-03-12 09:13:48 +0000630 Diag(clang::diag::err_drv_unknown_language) << A->getValue(Args);
Daniel Dunbar53ec5522009-03-12 07:58:46 +0000631 InputType = types::TY_Object;
632 }
633 }
634 }
635
Daniel Dunbar8b1604e2009-03-13 00:17:48 +0000636 if (!SuppressMissingInputWarning && Inputs.empty()) {
Daniel Dunbaraf61c712009-03-12 23:55:14 +0000637 Diag(clang::diag::err_drv_no_input_files);
638 return;
639 }
640
641 // Determine which compilation mode we are in. We look for options
642 // which affect the phase, starting with the earliest phases, and
643 // record which option we used to determine the final phase.
Daniel Dunbarad2a9af2009-03-13 11:38:42 +0000644 Arg *FinalPhaseArg = 0;
645 phases::ID FinalPhase;
Daniel Dunbaraf61c712009-03-12 23:55:14 +0000646
647 // -{E,M,MM} only run the preprocessor.
Daniel Dunbarad2a9af2009-03-13 11:38:42 +0000648 if ((FinalPhaseArg = Args.getLastArg(options::OPT_E)) ||
649 (FinalPhaseArg = Args.getLastArg(options::OPT_M)) ||
650 (FinalPhaseArg = Args.getLastArg(options::OPT_MM))) {
651 FinalPhase = phases::Preprocess;
Daniel Dunbaraf61c712009-03-12 23:55:14 +0000652
Daniel Dunbar8022fd42009-03-15 00:48:16 +0000653 // -{fsyntax-only,-analyze,emit-llvm,S} only run up to the compiler.
654 } else if ((FinalPhaseArg = Args.getLastArg(options::OPT_fsyntax_only)) ||
655 (FinalPhaseArg = Args.getLastArg(options::OPT__analyze)) ||
Daniel Dunbarad2a9af2009-03-13 11:38:42 +0000656 (FinalPhaseArg = Args.getLastArg(options::OPT_S))) {
657 FinalPhase = phases::Compile;
Daniel Dunbaraf61c712009-03-12 23:55:14 +0000658
659 // -c only runs up to the assembler.
Daniel Dunbarad2a9af2009-03-13 11:38:42 +0000660 } else if ((FinalPhaseArg = Args.getLastArg(options::OPT_c))) {
661 FinalPhase = phases::Assemble;
Daniel Dunbaraf61c712009-03-12 23:55:14 +0000662
663 // Otherwise do everything.
664 } else
Daniel Dunbarad2a9af2009-03-13 11:38:42 +0000665 FinalPhase = phases::Link;
Daniel Dunbaraf61c712009-03-12 23:55:14 +0000666
Daniel Dunbaraf61c712009-03-12 23:55:14 +0000667 // Reject -Z* at the top level, these options should never have been
668 // exposed by gcc.
Daniel Dunbard7b88c22009-03-26 16:12:09 +0000669 if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
Daniel Dunbar38dd3d52009-03-20 06:14:23 +0000670 Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
Daniel Dunbaraf61c712009-03-12 23:55:14 +0000671
Daniel Dunbarad2a9af2009-03-13 11:38:42 +0000672 // Construct the actions to perform.
673 ActionList LinkerInputs;
Daniel Dunbar53ec5522009-03-12 07:58:46 +0000674 for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
Daniel Dunbarad2a9af2009-03-13 11:38:42 +0000675 types::ID InputType = Inputs[i].first;
676 const Arg *InputArg = Inputs[i].second;
677
678 unsigned NumSteps = types::getNumCompilationPhases(InputType);
679 assert(NumSteps && "Invalid number of steps!");
680
681 // If the first step comes after the final phase we are doing as
682 // part of this compilation, warn the user about it.
683 phases::ID InitialPhase = types::getCompilationPhase(InputType, 0);
684 if (InitialPhase > FinalPhase) {
Daniel Dunbar05494a72009-03-19 07:57:08 +0000685 // Claim here to avoid the more general unused warning.
686 InputArg->claim();
Daniel Dunbarad2a9af2009-03-13 11:38:42 +0000687 Diag(clang::diag::warn_drv_input_file_unused)
Daniel Dunbar38dd3d52009-03-20 06:14:23 +0000688 << InputArg->getAsString(Args)
Daniel Dunbarad2a9af2009-03-13 11:38:42 +0000689 << getPhaseName(InitialPhase)
690 << FinalPhaseArg->getOption().getName();
691 continue;
692 }
693
694 // Build the pipeline for this file.
695 Action *Current = new InputAction(*InputArg, InputType);
696 for (unsigned i = 0; i != NumSteps; ++i) {
697 phases::ID Phase = types::getCompilationPhase(InputType, i);
698
699 // We are done if this step is past what the user requested.
700 if (Phase > FinalPhase)
701 break;
702
703 // Queue linker inputs.
704 if (Phase == phases::Link) {
705 assert(i + 1 == NumSteps && "linking must be final compilation step.");
706 LinkerInputs.push_back(Current);
707 Current = 0;
708 break;
709 }
710
Daniel Dunbar337a6272009-03-24 20:17:30 +0000711 // Some types skip the assembler phase (e.g., llvm-bc), but we
712 // can't encode this in the steps because the intermediate type
713 // depends on arguments. Just special case here.
714 if (Phase == phases::Assemble && Current->getType() != types::TY_PP_Asm)
715 continue;
716
Daniel Dunbarad2a9af2009-03-13 11:38:42 +0000717 // Otherwise construct the appropriate action.
718 Current = ConstructPhaseAction(Args, Phase, Current);
719 if (Current->getType() == types::TY_Nothing)
720 break;
721 }
722
723 // If we ended with something, add to the output list.
724 if (Current)
725 Actions.push_back(Current);
Daniel Dunbar53ec5522009-03-12 07:58:46 +0000726 }
Daniel Dunbarad2a9af2009-03-13 11:38:42 +0000727
728 // Add a link action if necessary.
729 if (!LinkerInputs.empty())
730 Actions.push_back(new LinkJobAction(LinkerInputs, types::TY_Image));
731}
732
733Action *Driver::ConstructPhaseAction(const ArgList &Args, phases::ID Phase,
734 Action *Input) const {
Daniel Dunbar8f25c792009-03-18 01:38:48 +0000735 llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
Daniel Dunbarad2a9af2009-03-13 11:38:42 +0000736 // Build the appropriate action.
737 switch (Phase) {
738 case phases::Link: assert(0 && "link action invalid here.");
739 case phases::Preprocess: {
Daniel Dunbarcd8e4c42009-03-30 06:36:42 +0000740 types::ID OutputTy;
741 // -{M, MM} alter the output type.
742 if (Args.hasArg(options::OPT_M) || Args.hasArg(options::OPT_MM)) {
743 OutputTy = types::TY_Dependencies;
744 } else {
745 OutputTy = types::getPreprocessedType(Input->getType());
746 assert(OutputTy != types::TY_INVALID &&
747 "Cannot preprocess this input type!");
748 }
Daniel Dunbarad2a9af2009-03-13 11:38:42 +0000749 return new PreprocessJobAction(Input, OutputTy);
750 }
751 case phases::Precompile:
752 return new PrecompileJobAction(Input, types::TY_PCH);
753 case phases::Compile: {
754 if (Args.hasArg(options::OPT_fsyntax_only)) {
755 return new CompileJobAction(Input, types::TY_Nothing);
756 } else if (Args.hasArg(options::OPT__analyze)) {
757 return new AnalyzeJobAction(Input, types::TY_Plist);
Daniel Dunbar337a6272009-03-24 20:17:30 +0000758 } else if (Args.hasArg(options::OPT_emit_llvm) ||
759 Args.hasArg(options::OPT_flto) ||
760 Args.hasArg(options::OPT_O4)) {
Daniel Dunbarad2a9af2009-03-13 11:38:42 +0000761 types::ID Output =
762 Args.hasArg(options::OPT_S) ? types::TY_LLVMAsm : types::TY_LLVMBC;
763 return new CompileJobAction(Input, Output);
764 } else {
765 return new CompileJobAction(Input, types::TY_PP_Asm);
766 }
767 }
768 case phases::Assemble:
769 return new AssembleJobAction(Input, types::TY_Object);
770 }
771
772 assert(0 && "invalid phase in ConstructPhaseAction");
773 return 0;
Daniel Dunbar53ec5522009-03-12 07:58:46 +0000774}
775
Daniel Dunbar21549232009-03-18 02:55:38 +0000776void Driver::BuildJobs(Compilation &C) const {
Daniel Dunbar8f25c792009-03-18 01:38:48 +0000777 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
Daniel Dunbarf353c8c2009-03-16 06:56:51 +0000778 bool SaveTemps = C.getArgs().hasArg(options::OPT_save_temps);
779 bool UsePipes = C.getArgs().hasArg(options::OPT_pipe);
Daniel Dunbar60ccc762009-03-18 23:18:19 +0000780
781 // FIXME: Pipes are forcibly disabled until we support executing
782 // them.
783 if (!CCCPrintBindings)
784 UsePipes = false;
Daniel Dunbarf353c8c2009-03-16 06:56:51 +0000785
786 // -save-temps inhibits pipes.
787 if (SaveTemps && UsePipes) {
788 Diag(clang::diag::warn_drv_pipe_ignored_with_save_temps);
789 UsePipes = true;
790 }
791
792 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
793
794 // It is an error to provide a -o option if we are making multiple
795 // output files.
796 if (FinalOutput) {
797 unsigned NumOutputs = 0;
Daniel Dunbar21549232009-03-18 02:55:38 +0000798 for (ActionList::const_iterator it = C.getActions().begin(),
799 ie = C.getActions().end(); it != ie; ++it)
Daniel Dunbarf353c8c2009-03-16 06:56:51 +0000800 if ((*it)->getType() != types::TY_Nothing)
801 ++NumOutputs;
802
803 if (NumOutputs > 1) {
804 Diag(clang::diag::err_drv_output_argument_with_multiple_files);
805 FinalOutput = 0;
806 }
807 }
808
Daniel Dunbar21549232009-03-18 02:55:38 +0000809 for (ActionList::const_iterator it = C.getActions().begin(),
810 ie = C.getActions().end(); it != ie; ++it) {
Daniel Dunbarf353c8c2009-03-16 06:56:51 +0000811 Action *A = *it;
812
813 // If we are linking an image for multiple archs then the linker
814 // wants -arch_multiple and -final_output <final image
815 // name>. Unfortunately, this doesn't fit in cleanly because we
816 // have to pass this information down.
817 //
818 // FIXME: This is a hack; find a cleaner way to integrate this
819 // into the process.
820 const char *LinkingOutput = 0;
Daniel Dunbard7b88c22009-03-26 16:12:09 +0000821 if (isa<LipoJobAction>(A)) {
Daniel Dunbarf353c8c2009-03-16 06:56:51 +0000822 if (FinalOutput)
823 LinkingOutput = FinalOutput->getValue(C.getArgs());
824 else
825 LinkingOutput = DefaultImageName.c_str();
826 }
827
828 InputInfo II;
Daniel Dunbar10ffa9a2009-03-18 03:13:20 +0000829 BuildJobsForAction(C, A, &C.getDefaultToolChain(),
Daniel Dunbarf353c8c2009-03-16 06:56:51 +0000830 /*CanAcceptPipe*/ true,
831 /*AtTopLevel*/ true,
832 /*LinkingOutput*/ LinkingOutput,
833 II);
834 }
Daniel Dunbar586dc232009-03-16 06:42:30 +0000835
Daniel Dunbarbf4a6762009-04-03 22:09:23 +0000836 // If the user passed -Qunused-arguments or there were errors, don't
837 // warn about any unused arguments.
Daniel Dunbar1e23f5f2009-04-07 19:04:18 +0000838 if (Diags.getNumErrors() ||
839 C.getArgs().hasArg(options::OPT_Qunused_arguments))
Daniel Dunbaraf2e4ba2009-03-18 18:03:46 +0000840 return;
841
Daniel Dunbara2094e72009-03-29 22:24:54 +0000842 // Claim -### here.
843 (void) C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
844
Daniel Dunbar586dc232009-03-16 06:42:30 +0000845 for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end();
846 it != ie; ++it) {
847 Arg *A = *it;
Daniel Dunbaraf2e4ba2009-03-18 18:03:46 +0000848
Daniel Dunbar586dc232009-03-16 06:42:30 +0000849 // FIXME: It would be nice to be able to send the argument to the
850 // Diagnostic, so that extra values, position, and so on could be
851 // printed.
Daniel Dunbar4f53b292009-04-04 00:52:26 +0000852 if (!A->isClaimed()) {
Daniel Dunbar1e23f5f2009-04-07 19:04:18 +0000853 if (A->getOption().hasNoArgumentUnused())
854 continue;
855
Daniel Dunbar4f53b292009-04-04 00:52:26 +0000856 // Suppress the warning automatically if this is just a flag,
857 // and it is an instance of an argument we already claimed.
858 const Option &Opt = A->getOption();
859 if (isa<FlagOption>(Opt)) {
860 bool DuplicateClaimed = false;
861
862 // FIXME: Use iterator.
863 for (ArgList::const_iterator it = C.getArgs().begin(),
864 ie = C.getArgs().end(); it != ie; ++it) {
865 if ((*it)->isClaimed() && (*it)->getOption().matches(Opt.getId())) {
866 DuplicateClaimed = true;
867 break;
868 }
869 }
870
871 if (DuplicateClaimed)
872 continue;
873 }
874
Daniel Dunbar586dc232009-03-16 06:42:30 +0000875 Diag(clang::diag::warn_drv_unused_argument)
Daniel Dunbar38dd3d52009-03-20 06:14:23 +0000876 << A->getAsString(C.getArgs());
Daniel Dunbar4f53b292009-04-04 00:52:26 +0000877 }
Daniel Dunbar586dc232009-03-16 06:42:30 +0000878 }
Daniel Dunbar57b704d2009-03-13 22:12:33 +0000879}
880
Daniel Dunbarf353c8c2009-03-16 06:56:51 +0000881void Driver::BuildJobsForAction(Compilation &C,
882 const Action *A,
883 const ToolChain *TC,
884 bool CanAcceptPipe,
885 bool AtTopLevel,
886 const char *LinkingOutput,
887 InputInfo &Result) const {
Daniel Dunbar8f25c792009-03-18 01:38:48 +0000888 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs for action");
Daniel Dunbar60ccc762009-03-18 23:18:19 +0000889
890 bool UsePipes = C.getArgs().hasArg(options::OPT_pipe);
891 // FIXME: Pipes are forcibly disabled until we support executing
892 // them.
893 if (!CCCPrintBindings)
894 UsePipes = false;
895
Daniel Dunbarf353c8c2009-03-16 06:56:51 +0000896 if (const InputAction *IA = dyn_cast<InputAction>(A)) {
Daniel Dunbar115a7922009-03-19 07:29:38 +0000897 // FIXME: It would be nice to not claim this here; maybe the old
898 // scheme of just using Args was better?
899 const Arg &Input = IA->getInputArg();
900 Input.claim();
901 if (isa<PositionalArg>(Input)) {
902 const char *Name = Input.getValue(C.getArgs());
903 Result = InputInfo(Name, A->getType(), Name);
904 } else
905 Result = InputInfo(&Input, A->getType(), "");
Daniel Dunbarf353c8c2009-03-16 06:56:51 +0000906 return;
907 }
908
909 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
910 const char *ArchName = BAA->getArchName();
Daniel Dunbar10ffa9a2009-03-18 03:13:20 +0000911 if (!ArchName)
912 ArchName = C.getDefaultToolChain().getArchName().c_str();
Daniel Dunbarf353c8c2009-03-16 06:56:51 +0000913 BuildJobsForAction(C,
914 *BAA->begin(),
915 Host->getToolChain(C.getArgs(), ArchName),
916 CanAcceptPipe,
917 AtTopLevel,
918 LinkingOutput,
919 Result);
920 return;
921 }
922
923 const JobAction *JA = cast<JobAction>(A);
924 const Tool &T = TC->SelectTool(C, *JA);
925
926 // See if we should use an integrated preprocessor. We do so when we
927 // have exactly one input, since this is the only use case we care
928 // about (irrelevant since we don't support combine yet).
929 bool UseIntegratedCPP = false;
930 const ActionList *Inputs = &A->getInputs();
931 if (Inputs->size() == 1 && isa<PreprocessJobAction>(*Inputs->begin())) {
932 if (!C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
933 !C.getArgs().hasArg(options::OPT_traditional_cpp) &&
934 !C.getArgs().hasArg(options::OPT_save_temps) &&
935 T.hasIntegratedCPP()) {
936 UseIntegratedCPP = true;
937 Inputs = &(*Inputs)[0]->getInputs();
938 }
939 }
940
941 // Only use pipes when there is exactly one input.
942 bool TryToUsePipeInput = Inputs->size() == 1 && T.acceptsPipedInput();
Daniel Dunbar47ac7d22009-03-18 06:00:36 +0000943 InputInfoList InputInfos;
Daniel Dunbarf353c8c2009-03-16 06:56:51 +0000944 for (ActionList::const_iterator it = Inputs->begin(), ie = Inputs->end();
945 it != ie; ++it) {
946 InputInfo II;
947 BuildJobsForAction(C, *it, TC, TryToUsePipeInput,
948 /*AtTopLevel*/false,
949 LinkingOutput,
950 II);
951 InputInfos.push_back(II);
952 }
953
954 // Determine if we should output to a pipe.
955 bool OutputToPipe = false;
956 if (CanAcceptPipe && T.canPipeOutput()) {
957 // Some actions default to writing to a pipe if they are the top
958 // level phase and there was no user override.
959 //
960 // FIXME: Is there a better way to handle this?
961 if (AtTopLevel) {
962 if (isa<PreprocessJobAction>(A) && !C.getArgs().hasArg(options::OPT_o))
963 OutputToPipe = true;
Daniel Dunbar60ccc762009-03-18 23:18:19 +0000964 } else if (UsePipes)
Daniel Dunbarf353c8c2009-03-16 06:56:51 +0000965 OutputToPipe = true;
966 }
967
968 // Figure out where to put the job (pipes).
969 Job *Dest = &C.getJobs();
970 if (InputInfos[0].isPipe()) {
Daniel Dunbar441d0602009-03-17 17:53:55 +0000971 assert(TryToUsePipeInput && "Unrequested pipe!");
Daniel Dunbarf353c8c2009-03-16 06:56:51 +0000972 assert(InputInfos.size() == 1 && "Unexpected pipe with multiple inputs.");
973 Dest = &InputInfos[0].getPipe();
974 }
975
976 // Always use the first input as the base input.
977 const char *BaseInput = InputInfos[0].getBaseInput();
Daniel Dunbar441d0602009-03-17 17:53:55 +0000978
979 // Determine the place to write output to (nothing, pipe, or
980 // filename) and where to put the new job.
Daniel Dunbar441d0602009-03-17 17:53:55 +0000981 if (JA->getType() == types::TY_Nothing) {
Daniel Dunbar5c3c1d72009-03-17 22:47:06 +0000982 Result = InputInfo(A->getType(), BaseInput);
Daniel Dunbar441d0602009-03-17 17:53:55 +0000983 } else if (OutputToPipe) {
984 // Append to current piped job or create a new one as appropriate.
Daniel Dunbar5c3c1d72009-03-17 22:47:06 +0000985 PipedJob *PJ = dyn_cast<PipedJob>(Dest);
986 if (!PJ) {
987 PJ = new PipedJob();
Daniel Dunbarb7b61b22009-03-20 00:11:04 +0000988 // FIXME: Temporary hack so that -ccc-print-bindings work until
989 // we have pipe support. Please remove later.
990 if (!CCCPrintBindings)
991 cast<JobList>(Dest)->addJob(PJ);
Daniel Dunbar871adcf2009-03-18 07:06:02 +0000992 Dest = PJ;
Daniel Dunbar441d0602009-03-17 17:53:55 +0000993 }
Daniel Dunbar5c3c1d72009-03-17 22:47:06 +0000994 Result = InputInfo(PJ, A->getType(), BaseInput);
Daniel Dunbar441d0602009-03-17 17:53:55 +0000995 } else {
Daniel Dunbar5c3c1d72009-03-17 22:47:06 +0000996 Result = InputInfo(GetNamedOutputPath(C, *JA, BaseInput, AtTopLevel),
997 A->getType(), BaseInput);
Daniel Dunbar441d0602009-03-17 17:53:55 +0000998 }
999
Daniel Dunbar5c3c1d72009-03-17 22:47:06 +00001000 if (CCCPrintBindings) {
Daniel Dunbarcd8e4c42009-03-30 06:36:42 +00001001 llvm::errs() << "# \"" << T.getToolChain().getTripleString() << '"'
1002 << " - \"" << T.getName() << "\", inputs: [";
Daniel Dunbar5c3c1d72009-03-17 22:47:06 +00001003 for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
1004 llvm::errs() << InputInfos[i].getAsString();
1005 if (i + 1 != e)
1006 llvm::errs() << ", ";
1007 }
1008 llvm::errs() << "], output: " << Result.getAsString() << "\n";
1009 } else {
Daniel Dunbarf3cad362009-03-25 04:13:45 +00001010 T.ConstructJob(C, *JA, *Dest, Result, InputInfos,
1011 C.getArgsForToolChain(TC), LinkingOutput);
Daniel Dunbar5c3c1d72009-03-17 22:47:06 +00001012 }
Daniel Dunbarf353c8c2009-03-16 06:56:51 +00001013}
1014
Daniel Dunbar441d0602009-03-17 17:53:55 +00001015const char *Driver::GetNamedOutputPath(Compilation &C,
1016 const JobAction &JA,
1017 const char *BaseInput,
1018 bool AtTopLevel) const {
Daniel Dunbar8f25c792009-03-18 01:38:48 +00001019 llvm::PrettyStackTraceString CrashInfo("Computing output path");
Daniel Dunbar441d0602009-03-17 17:53:55 +00001020 // Output to a user requested destination?
1021 if (AtTopLevel) {
1022 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
1023 return C.addResultFile(FinalOutput->getValue(C.getArgs()));
1024 }
1025
1026 // Output to a temporary file?
1027 if (!AtTopLevel && !C.getArgs().hasArg(options::OPT_save_temps)) {
Daniel Dunbar214399e2009-03-18 19:34:39 +00001028 std::string TmpName =
1029 GetTemporaryPath(types::getTypeTempSuffix(JA.getType()));
1030 return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()));
Daniel Dunbar441d0602009-03-17 17:53:55 +00001031 }
1032
1033 llvm::sys::Path BasePath(BaseInput);
Daniel Dunbar5796bf42009-03-18 02:00:31 +00001034 std::string BaseName(BasePath.getLast());
Daniel Dunbar441d0602009-03-17 17:53:55 +00001035
1036 // Determine what the derived output name should be.
1037 const char *NamedOutput;
1038 if (JA.getType() == types::TY_Image) {
1039 NamedOutput = DefaultImageName.c_str();
1040 } else {
1041 const char *Suffix = types::getTypeTempSuffix(JA.getType());
1042 assert(Suffix && "All types used for output should have a suffix.");
1043
1044 std::string::size_type End = std::string::npos;
1045 if (!types::appendSuffixForType(JA.getType()))
1046 End = BaseName.rfind('.');
1047 std::string Suffixed(BaseName.substr(0, End));
1048 Suffixed += '.';
1049 Suffixed += Suffix;
1050 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
1051 }
1052
1053 // As an annoying special case, PCH generation doesn't strip the
1054 // pathname.
1055 if (JA.getType() == types::TY_PCH) {
1056 BasePath.eraseComponent();
Daniel Dunbar56c55942009-03-18 09:58:30 +00001057 if (BasePath.isEmpty())
1058 BasePath = NamedOutput;
1059 else
1060 BasePath.appendComponent(NamedOutput);
Daniel Dunbar441d0602009-03-17 17:53:55 +00001061 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()));
1062 } else {
1063 return C.addResultFile(NamedOutput);
1064 }
1065}
1066
Daniel Dunbar2ba38ba2009-03-16 05:25:36 +00001067llvm::sys::Path Driver::GetFilePath(const char *Name,
Daniel Dunbar21549232009-03-18 02:55:38 +00001068 const ToolChain &TC) const {
Daniel Dunbar0edefeb2009-03-18 20:26:19 +00001069 const ToolChain::path_list &List = TC.getFilePaths();
1070 for (ToolChain::path_list::const_iterator
1071 it = List.begin(), ie = List.end(); it != ie; ++it) {
1072 llvm::sys::Path P(*it);
1073 P.appendComponent(Name);
1074 if (P.exists())
1075 return P;
1076 }
1077
Daniel Dunbarcb881672009-03-13 00:51:18 +00001078 return llvm::sys::Path(Name);
1079}
1080
Daniel Dunbar2ba38ba2009-03-16 05:25:36 +00001081llvm::sys::Path Driver::GetProgramPath(const char *Name,
Mike Stump950bedd2009-03-27 00:40:20 +00001082 const ToolChain &TC,
1083 bool WantFile) const {
Daniel Dunbar0edefeb2009-03-18 20:26:19 +00001084 const ToolChain::path_list &List = TC.getProgramPaths();
1085 for (ToolChain::path_list::const_iterator
1086 it = List.begin(), ie = List.end(); it != ie; ++it) {
1087 llvm::sys::Path P(*it);
1088 P.appendComponent(Name);
Mike Stump950bedd2009-03-27 00:40:20 +00001089 if (WantFile ? P.exists() : P.canExecute())
Daniel Dunbar0edefeb2009-03-18 20:26:19 +00001090 return P;
1091 }
1092
Daniel Dunbarc50b00d2009-03-23 16:15:50 +00001093 // If all else failed, search the path.
1094 llvm::sys::Path P(llvm::sys::Program::FindProgramByName(Name));
Daniel Dunbar632f50e2009-03-18 21:34:08 +00001095 if (!P.empty())
1096 return P;
1097
Daniel Dunbarcb881672009-03-13 00:51:18 +00001098 return llvm::sys::Path(Name);
1099}
1100
Daniel Dunbar214399e2009-03-18 19:34:39 +00001101std::string Driver::GetTemporaryPath(const char *Suffix) const {
1102 // FIXME: This is lame; sys::Path should provide this function (in
1103 // particular, it should know how to find the temporary files dir).
1104 std::string Error;
1105 llvm::sys::Path P("/tmp/cc");
1106 if (P.makeUnique(false, &Error)) {
1107 Diag(clang::diag::err_drv_unable_to_make_temp) << Error;
1108 return "";
1109 }
1110
Daniel Dunbar84603bc2009-03-18 23:08:52 +00001111 // FIXME: Grumble, makeUnique sometimes leaves the file around!?
1112 // PR3837.
1113 P.eraseFromDisk(false, 0);
1114
Daniel Dunbar214399e2009-03-18 19:34:39 +00001115 P.appendSuffix(Suffix);
1116 return P.toString();
1117}
1118
Daniel Dunbare5049522009-03-17 20:45:45 +00001119const HostInfo *Driver::GetHostInfo(const char *Triple) const {
Daniel Dunbar8f25c792009-03-18 01:38:48 +00001120 llvm::PrettyStackTraceString CrashInfo("Constructing host");
Daniel Dunbardd98e2c2009-03-10 23:41:59 +00001121 // Dice into arch, platform, and OS. This matches
1122 // arch,platform,os = '(.*?)-(.*?)-(.*?)'
1123 // and missing fields are left empty.
1124 std::string Arch, Platform, OS;
1125
1126 if (const char *ArchEnd = strchr(Triple, '-')) {
1127 Arch = std::string(Triple, ArchEnd);
1128
1129 if (const char *PlatformEnd = strchr(ArchEnd+1, '-')) {
1130 Platform = std::string(ArchEnd+1, PlatformEnd);
1131 OS = PlatformEnd+1;
1132 } else
1133 Platform = ArchEnd+1;
1134 } else
1135 Arch = Triple;
1136
Daniel Dunbar1fd6c4b2009-03-17 19:00:50 +00001137 // Normalize Arch a bit.
1138 //
1139 // FIXME: This is very incomplete.
1140 if (Arch == "i686")
1141 Arch = "i386";
1142 else if (Arch == "amd64")
1143 Arch = "x86_64";
Daniel Dunbarbf54a062009-04-01 20:33:11 +00001144 else if (Arch == "ppc" || Arch == "Power Macintosh")
1145 Arch = "powerpc";
1146 else if (Arch == "ppc64")
1147 Arch = "powerpc64";
Daniel Dunbar1fd6c4b2009-03-17 19:00:50 +00001148
Daniel Dunbara88162c2009-03-13 12:23:29 +00001149 if (memcmp(&OS[0], "darwin", 6) == 0)
Daniel Dunbare5049522009-03-17 20:45:45 +00001150 return createDarwinHostInfo(*this, Arch.c_str(), Platform.c_str(),
1151 OS.c_str());
Daniel Dunbar75358d22009-03-30 21:06:03 +00001152 if (memcmp(&OS[0], "freebsd", 7) == 0)
1153 return createFreeBSDHostInfo(*this, Arch.c_str(), Platform.c_str(),
1154 OS.c_str());
Daniel Dunbardd98e2c2009-03-10 23:41:59 +00001155
Daniel Dunbare5049522009-03-17 20:45:45 +00001156 return createUnknownHostInfo(*this, Arch.c_str(), Platform.c_str(),
1157 OS.c_str());
Daniel Dunbardd98e2c2009-03-10 23:41:59 +00001158}
Daniel Dunbaraf80e1f2009-03-24 18:57:02 +00001159
1160bool Driver::ShouldUseClangCompiler(const Compilation &C, const JobAction &JA,
Daniel Dunbarbf54a062009-04-01 20:33:11 +00001161 const std::string &ArchNameStr) const {
1162 // FIXME: Remove this hack.
1163 const char *ArchName = ArchNameStr.c_str();
1164 if (ArchNameStr == "powerpc")
1165 ArchName = "ppc";
1166 else if (ArchNameStr == "powerpc64")
1167 ArchName = "ppc64";
1168
Daniel Dunbaraf80e1f2009-03-24 18:57:02 +00001169 // Check if user requested no clang, or clang doesn't understand
1170 // this type (we only handle single inputs for now).
Daniel Dunbar0f99d2e2009-03-24 19:02:31 +00001171 if (!CCCUseClang || JA.size() != 1 ||
Daniel Dunbaraf80e1f2009-03-24 18:57:02 +00001172 !types::isAcceptedByClang((*JA.begin())->getType()))
1173 return false;
1174
Daniel Dunbar0f99d2e2009-03-24 19:02:31 +00001175 // Otherwise make sure this is an action clang understands.
Daniel Dunbaraf80e1f2009-03-24 18:57:02 +00001176 if (isa<PreprocessJobAction>(JA)) {
Daniel Dunbar6256d362009-03-24 19:14:56 +00001177 if (!CCCUseClangCPP) {
1178 Diag(clang::diag::warn_drv_not_using_clang_cpp);
Daniel Dunbaraf80e1f2009-03-24 18:57:02 +00001179 return false;
Daniel Dunbar6256d362009-03-24 19:14:56 +00001180 }
Daniel Dunbaraf80e1f2009-03-24 18:57:02 +00001181 } else if (!isa<PrecompileJobAction>(JA) && !isa<CompileJobAction>(JA))
1182 return false;
1183
Daniel Dunbar0f99d2e2009-03-24 19:02:31 +00001184 // Use clang for C++?
Daniel Dunbar6256d362009-03-24 19:14:56 +00001185 if (!CCCUseClangCXX && types::isCXX((*JA.begin())->getType())) {
1186 Diag(clang::diag::warn_drv_not_using_clang_cxx);
Daniel Dunbaraf80e1f2009-03-24 18:57:02 +00001187 return false;
Daniel Dunbar6256d362009-03-24 19:14:56 +00001188 }
Daniel Dunbaraf80e1f2009-03-24 18:57:02 +00001189
Daniel Dunbarfec26bd2009-04-16 23:10:13 +00001190 // Always use clang for precompiling, regardless of archs. PTH is
1191 // platform independent, and this allows the use of the static
1192 // analyzer on platforms we don't have full IRgen support for.
1193 if (isa<PrecompileJobAction>(JA))
1194 return true;
1195
Daniel Dunbaraf80e1f2009-03-24 18:57:02 +00001196 // Finally, don't use clang if this isn't one of the user specified
1197 // archs to build.
Daniel Dunbar6256d362009-03-24 19:14:56 +00001198 if (!CCCClangArchs.empty() && !CCCClangArchs.count(ArchName)) {
1199 Diag(clang::diag::warn_drv_not_using_clang_arch) << ArchName;
Daniel Dunbaraf80e1f2009-03-24 18:57:02 +00001200 return false;
Daniel Dunbar6256d362009-03-24 19:14:56 +00001201 }
Daniel Dunbaraf80e1f2009-03-24 18:57:02 +00001202
1203 return true;
1204}
Daniel Dunbard73fe9b2009-03-26 15:58:36 +00001205
1206/// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and
1207/// return the grouped values as integers. Numbers which are not
1208/// provided are set to 0.
1209///
1210/// \return True if the entire string was parsed (9.2), or all groups
1211/// were parsed (10.3.5extrastuff).
1212bool Driver::GetReleaseVersion(const char *Str, unsigned &Major,
1213 unsigned &Minor, unsigned &Micro,
1214 bool &HadExtra) {
1215 HadExtra = false;
1216
1217 Major = Minor = Micro = 0;
1218 if (*Str == '\0')
1219 return true;
1220
1221 char *End;
1222 Major = (unsigned) strtol(Str, &End, 10);
1223 if (*Str != '\0' && *End == '\0')
1224 return true;
1225 if (*End != '.')
1226 return false;
1227
1228 Str = End+1;
1229 Minor = (unsigned) strtol(Str, &End, 10);
1230 if (*Str != '\0' && *End == '\0')
1231 return true;
1232 if (*End != '.')
1233 return false;
1234
1235 Str = End+1;
1236 Micro = (unsigned) strtol(Str, &End, 10);
1237 if (*Str != '\0' && *End == '\0')
1238 return true;
1239 if (Str == End)
1240 return false;
1241 HadExtra = true;
1242 return true;
1243}