blob: ad1546b0d1b9e955b2a1db7ae5b29378f123b137 [file] [log] [blame]
Daniel Dunbar544ecd12009-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 Dunbarb2da9332009-03-03 05:55:11 +000010// This is the entry point to the clang driver; it is a thin wrapper
11// for functionality in the Driver clang library.
Daniel Dunbar544ecd12009-03-02 19:59:07 +000012//
13//===----------------------------------------------------------------------===//
14
Jordan Rosea7d03842013-02-08 22:30:41 +000015#include "clang/Basic/CharInfo.h"
Douglas Gregor811db4e2012-10-23 22:26:28 +000016#include "clang/Basic/DiagnosticOptions.h"
Daniel Dunbar544ecd12009-03-02 19:59:07 +000017#include "clang/Driver/Compilation.h"
18#include "clang/Driver/Driver.h"
Richard Smith940a6d72012-12-25 21:56:27 +000019#include "clang/Driver/DriverDiagnostic.h"
Chandler Carruthcc0694c2012-12-04 09:25:21 +000020#include "clang/Driver/Options.h"
Chad Rosierd6f716a2012-03-13 20:09:56 +000021#include "clang/Frontend/CompilerInvocation.h"
Daniel Dunbar12ee3802010-02-25 03:23:43 +000022#include "clang/Frontend/TextDiagnosticPrinter.h"
Chad Rosierd6f716a2012-03-13 20:09:56 +000023#include "clang/Frontend/Utils.h"
Chris Lattnerce6c42f2011-03-23 04:04:01 +000024#include "llvm/ADT/ArrayRef.h"
Chandler Carruthcc0694c2012-12-04 09:25:21 +000025#include "llvm/ADT/OwningPtr.h"
Daniel Dunbard9b80c22009-03-18 02:11:26 +000026#include "llvm/ADT/SmallString.h"
Rafael Espindola77a067a2010-07-19 15:20:12 +000027#include "llvm/ADT/SmallVector.h"
Reid Kleckner898229a2013-06-14 17:17:23 +000028#include "llvm/Option/ArgList.h"
29#include "llvm/Option/OptTable.h"
30#include "llvm/Option/Option.h"
Rafael Espindola77a067a2010-07-19 15:20:12 +000031#include "llvm/Support/ErrorHandling.h"
Michael J. Spencer740857f2010-12-21 16:45:57 +000032#include "llvm/Support/FileSystem.h"
Chandler Carruthcc0694c2012-12-04 09:25:21 +000033#include "llvm/Support/Host.h"
Daniel Dunbar2608c542009-03-18 01:38:48 +000034#include "llvm/Support/ManagedStatic.h"
Rafael Espindola77a067a2010-07-19 15:20:12 +000035#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000036#include "llvm/Support/Path.h"
Chandler Carruthcc0694c2012-12-04 09:25:21 +000037#include "llvm/Support/PrettyStackTrace.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000038#include "llvm/Support/Program.h"
Chandler Carruthcc0694c2012-12-04 09:25:21 +000039#include "llvm/Support/Regex.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000040#include "llvm/Support/Signals.h"
Evan Cheng494eb062011-08-24 18:09:14 +000041#include "llvm/Support/TargetRegistry.h"
42#include "llvm/Support/TargetSelect.h"
Chandler Carruthcc0694c2012-12-04 09:25:21 +000043#include "llvm/Support/Timer.h"
44#include "llvm/Support/raw_ostream.h"
Michael J. Spencerf25faaa2010-12-09 17:36:38 +000045#include "llvm/Support/system_error.h"
Daniel Dunbarc0b3e952009-03-12 08:55:43 +000046using namespace clang;
Daniel Dunbarb2cd66b2009-03-04 20:49:20 +000047using namespace clang::driver;
Reid Kleckner898229a2013-06-14 17:17:23 +000048using namespace llvm::opt;
Daniel Dunbar544ecd12009-03-02 19:59:07 +000049
Rafael Espindola9678d272013-06-26 05:03:40 +000050std::string GetExecutablePath(const char *Argv0, bool CanonicalPrefixes) {
Rafael Espindola73d46372009-12-04 19:31:58 +000051 if (!CanonicalPrefixes)
Rafael Espindola9678d272013-06-26 05:03:40 +000052 return Argv0;
Rafael Espindola73d46372009-12-04 19:31:58 +000053
Daniel Dunbarda382a82009-03-18 20:25:53 +000054 // This just needs to be some symbol in the binary; C++ doesn't
55 // allow taking the address of ::main however.
56 void *P = (void*) (intptr_t) GetExecutablePath;
Rafael Espindola9678d272013-06-26 05:03:40 +000057 return llvm::sys::fs::getMainExecutable(Argv0, P);
Daniel Dunbarda382a82009-03-18 20:25:53 +000058}
59
Daniel Dunbarc3ccd182009-07-17 18:10:27 +000060static const char *SaveStringInSet(std::set<std::string> &SavedStrings,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000061 StringRef S) {
Daniel Dunbar3f4a2c22009-04-17 01:54:00 +000062 return SavedStrings.insert(S).first->c_str();
63}
64
65/// ApplyQAOverride - Apply a list of edits to the input argument lists.
66///
67/// The input string is a space separate list of edits to perform,
68/// they are applied in order to the input argument lists. Edits
69/// should be one of the following forms:
70///
Daniel Dunbar54091b82009-07-16 21:32:51 +000071/// '#': Silence information about the changes to the command line arguments.
72///
Daniel Dunbar3f4a2c22009-04-17 01:54:00 +000073/// '^': Add FOO as a new argument at the beginning of the command line.
74///
75/// '+': Add FOO as a new argument at the end of the command line.
76///
Daniel Dunbard2b20c12010-02-17 21:00:34 +000077/// 's/XXX/YYY/': Substitute the regular expression XXX with YYY in the command
78/// line.
Daniel Dunbar3f4a2c22009-04-17 01:54:00 +000079///
80/// 'xOPTION': Removes all instances of the literal argument OPTION.
81///
82/// 'XOPTION': Removes all instances of the literal argument OPTION,
83/// and the following argument.
84///
85/// 'Ox': Removes all flags matching 'O' or 'O[sz0-9]' and adds 'Ox'
86/// at the end of the command line.
Daniel Dunbar54091b82009-07-16 21:32:51 +000087///
88/// \param OS - The stream to write edit information to.
89/// \param Args - The vector of command line arguments.
90/// \param Edit - The override command to perform.
91/// \param SavedStrings - Set to use for storing string representations.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000092static void ApplyOneQAOverride(raw_ostream &OS,
93 SmallVectorImpl<const char*> &Args,
94 StringRef Edit,
Chris Lattner09f8cc82010-03-30 05:39:52 +000095 std::set<std::string> &SavedStrings) {
Daniel Dunbar3f4a2c22009-04-17 01:54:00 +000096 // This does not need to be efficient.
97
Daniel Dunbarc3ccd182009-07-17 18:10:27 +000098 if (Edit[0] == '^') {
99 const char *Str =
Daniel Dunbard2b20c12010-02-17 21:00:34 +0000100 SaveStringInSet(SavedStrings, Edit.substr(1));
Daniel Dunbarc3ccd182009-07-17 18:10:27 +0000101 OS << "### Adding argument " << Str << " at beginning\n";
102 Args.insert(Args.begin() + 1, Str);
103 } else if (Edit[0] == '+') {
104 const char *Str =
Daniel Dunbard2b20c12010-02-17 21:00:34 +0000105 SaveStringInSet(SavedStrings, Edit.substr(1));
Daniel Dunbarc3ccd182009-07-17 18:10:27 +0000106 OS << "### Adding argument " << Str << " at end\n";
107 Args.push_back(Str);
Daniel Dunbard2b20c12010-02-17 21:00:34 +0000108 } else if (Edit[0] == 's' && Edit[1] == '/' && Edit.endswith("/") &&
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000109 Edit.slice(2, Edit.size()-1).find('/') != StringRef::npos) {
110 StringRef MatchPattern = Edit.substr(2).split('/').first;
111 StringRef ReplPattern = Edit.substr(2).split('/').second;
Daniel Dunbard2b20c12010-02-17 21:00:34 +0000112 ReplPattern = ReplPattern.slice(0, ReplPattern.size()-1);
113
114 for (unsigned i = 1, e = Args.size(); i != e; ++i) {
115 std::string Repl = llvm::Regex(MatchPattern).sub(ReplPattern, Args[i]);
116
117 if (Repl != Args[i]) {
118 OS << "### Replacing '" << Args[i] << "' with '" << Repl << "'\n";
119 Args[i] = SaveStringInSet(SavedStrings, Repl);
120 }
121 }
Daniel Dunbarc3ccd182009-07-17 18:10:27 +0000122 } else if (Edit[0] == 'x' || Edit[0] == 'X') {
123 std::string Option = Edit.substr(1, std::string::npos);
124 for (unsigned i = 1; i < Args.size();) {
125 if (Option == Args[i]) {
126 OS << "### Deleting argument " << Args[i] << '\n';
127 Args.erase(Args.begin() + i);
128 if (Edit[0] == 'X') {
129 if (i < Args.size()) {
130 OS << "### Deleting argument " << Args[i] << '\n';
131 Args.erase(Args.begin() + i);
132 } else
133 OS << "### Invalid X edit, end of command line!\n";
134 }
135 } else
136 ++i;
137 }
138 } else if (Edit[0] == 'O') {
139 for (unsigned i = 1; i < Args.size();) {
140 const char *A = Args[i];
141 if (A[0] == '-' && A[1] == 'O' &&
142 (A[2] == '\0' ||
143 (A[3] == '\0' && (A[2] == 's' || A[2] == 'z' ||
144 ('0' <= A[2] && A[2] <= '9'))))) {
145 OS << "### Deleting argument " << Args[i] << '\n';
146 Args.erase(Args.begin() + i);
147 } else
148 ++i;
149 }
150 OS << "### Adding argument " << Edit << " at end\n";
Daniel Dunbard2b20c12010-02-17 21:00:34 +0000151 Args.push_back(SaveStringInSet(SavedStrings, '-' + Edit.str()));
Daniel Dunbarc3ccd182009-07-17 18:10:27 +0000152 } else {
153 OS << "### Unrecognized edit: " << Edit << "\n";
154 }
Daniel Dunbar3f4a2c22009-04-17 01:54:00 +0000155}
156
157/// ApplyQAOverride - Apply a comma separate list of edits to the
158/// input argument lists. See ApplyOneQAOverride.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000159static void ApplyQAOverride(SmallVectorImpl<const char*> &Args,
Chris Lattner09f8cc82010-03-30 05:39:52 +0000160 const char *OverrideStr,
161 std::set<std::string> &SavedStrings) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000162 raw_ostream *OS = &llvm::errs();
Daniel Dunbarc3ccd182009-07-17 18:10:27 +0000163
Daniel Dunbar54091b82009-07-16 21:32:51 +0000164 if (OverrideStr[0] == '#') {
165 ++OverrideStr;
166 OS = &llvm::nulls();
167 }
168
169 *OS << "### QA_OVERRIDE_GCC3_OPTIONS: " << OverrideStr << "\n";
Daniel Dunbar3f4a2c22009-04-17 01:54:00 +0000170
171 // This does not need to be efficient.
172
173 const char *S = OverrideStr;
174 while (*S) {
175 const char *End = ::strchr(S, ' ');
176 if (!End)
177 End = S + strlen(S);
178 if (End != S)
Daniel Dunbar54091b82009-07-16 21:32:51 +0000179 ApplyOneQAOverride(*OS, Args, std::string(S, End), SavedStrings);
Daniel Dunbar3f4a2c22009-04-17 01:54:00 +0000180 S = End;
181 if (*S != '\0')
182 ++S;
183 }
184}
185
Daniel Dunbar1c39f3c2009-11-30 07:18:13 +0000186extern int cc1_main(const char **ArgBegin, const char **ArgEnd,
Daniel Dunbar65ca1c62009-11-29 20:58:32 +0000187 const char *Argv0, void *MainAddr);
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000188extern int cc1as_main(const char **ArgBegin, const char **ArgEnd,
189 const char *Argv0, void *MainAddr);
Daniel Dunbar51cd8f02009-11-19 07:37:51 +0000190
Rafael Espindola77a067a2010-07-19 15:20:12 +0000191static void ExpandArgsFromBuf(const char *Arg,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000192 SmallVectorImpl<const char*> &ArgVector,
Rafael Espindola77a067a2010-07-19 15:20:12 +0000193 std::set<std::string> &SavedStrings) {
194 const char *FName = Arg + 1;
Dylan Noblesmith1cd10692012-02-13 12:32:21 +0000195 OwningPtr<llvm::MemoryBuffer> MemBuf;
Michael J. Spencerd9da7a12010-12-16 03:28:14 +0000196 if (llvm::MemoryBuffer::getFile(FName, MemBuf)) {
Rafael Espindola77a067a2010-07-19 15:20:12 +0000197 ArgVector.push_back(SaveStringInSet(SavedStrings, Arg));
198 return;
199 }
200
201 const char *Buf = MemBuf->getBufferStart();
202 char InQuote = ' ';
203 std::string CurArg;
204
205 for (const char *P = Buf; ; ++P) {
Jordan Rosea7d03842013-02-08 22:30:41 +0000206 if (*P == '\0' || (isWhitespace(*P) && InQuote == ' ')) {
Rafael Espindola77a067a2010-07-19 15:20:12 +0000207 if (!CurArg.empty()) {
208
209 if (CurArg[0] != '@') {
210 ArgVector.push_back(SaveStringInSet(SavedStrings, CurArg));
211 } else {
212 ExpandArgsFromBuf(CurArg.c_str(), ArgVector, SavedStrings);
213 }
214
215 CurArg = "";
216 }
217 if (*P == '\0')
218 break;
219 else
220 continue;
221 }
222
Jordan Rosea7d03842013-02-08 22:30:41 +0000223 if (isWhitespace(*P)) {
Rafael Espindola77a067a2010-07-19 15:20:12 +0000224 if (InQuote != ' ')
225 CurArg.push_back(*P);
226 continue;
227 }
228
229 if (*P == '"' || *P == '\'') {
230 if (InQuote == *P)
231 InQuote = ' ';
232 else if (InQuote == ' ')
233 InQuote = *P;
234 else
235 CurArg.push_back(*P);
236 continue;
237 }
238
239 if (*P == '\\') {
240 ++P;
241 if (*P != '\0')
242 CurArg.push_back(*P);
243 continue;
244 }
245 CurArg.push_back(*P);
246 }
Rafael Espindola77a067a2010-07-19 15:20:12 +0000247}
248
249static void ExpandArgv(int argc, const char **argv,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000250 SmallVectorImpl<const char*> &ArgVector,
Rafael Espindola77a067a2010-07-19 15:20:12 +0000251 std::set<std::string> &SavedStrings) {
252 for (int i = 0; i < argc; ++i) {
253 const char *Arg = argv[i];
254 if (Arg[0] != '@') {
255 ArgVector.push_back(SaveStringInSet(SavedStrings, std::string(Arg)));
256 continue;
257 }
258
259 ExpandArgsFromBuf(Arg, ArgVector, SavedStrings);
260 }
261}
262
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000263static void ParseProgName(SmallVectorImpl<const char *> &ArgVector,
Joerg Sonnenbergerf6ce2fb2011-03-16 20:15:43 +0000264 std::set<std::string> &SavedStrings,
265 Driver &TheDriver)
266{
267 // Try to infer frontend type and default target from the program name.
268
269 // suffixes[] contains the list of known driver suffixes.
270 // Suffixes are compared against the program name in order.
271 // If there is a match, the frontend type is updated as necessary (CPP/C++).
272 // If there is no match, a second round is done after stripping the last
273 // hyphen and everything following it. This allows using something like
274 // "clang++-2.9".
275
276 // If there is a match in either the first or second round,
277 // the function tries to identify a target as prefix. E.g.
278 // "x86_64-linux-clang" as interpreted as suffix "clang" with
279 // target prefix "x86_64-linux". If such a target prefix is found,
Sebastian Pop422377c2012-01-20 22:01:23 +0000280 // is gets added via -target as implicit first argument.
Joerg Sonnenbergerf6ce2fb2011-03-16 20:15:43 +0000281 static const struct {
282 const char *Suffix;
283 bool IsCXX;
284 bool IsCPP;
285 } suffixes [] = {
Chandler Carruth482942e2012-09-11 10:40:21 +0000286 { "clang", false, false },
287 { "clang++", true, false },
288 { "clang-c++", true, false },
289 { "clang-cc", false, false },
290 { "clang-cpp", false, true },
291 { "clang-g++", true, false },
292 { "clang-gcc", false, false },
293 { "cc", false, false },
294 { "cpp", false, true },
295 { "++", true, false },
Joerg Sonnenbergerf6ce2fb2011-03-16 20:15:43 +0000296 };
297 std::string ProgName(llvm::sys::path::stem(ArgVector[0]));
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000298 StringRef ProgNameRef(ProgName);
299 StringRef Prefix;
Joerg Sonnenbergerf6ce2fb2011-03-16 20:15:43 +0000300
301 for (int Components = 2; Components; --Components) {
302 bool FoundMatch = false;
303 size_t i;
304
305 for (i = 0; i < sizeof(suffixes) / sizeof(suffixes[0]); ++i) {
306 if (ProgNameRef.endswith(suffixes[i].Suffix)) {
307 FoundMatch = true;
Chandler Carruth482942e2012-09-11 10:40:21 +0000308 if (suffixes[i].IsCXX)
Joerg Sonnenbergerf6ce2fb2011-03-16 20:15:43 +0000309 TheDriver.CCCIsCXX = true;
310 if (suffixes[i].IsCPP)
311 TheDriver.CCCIsCPP = true;
312 break;
313 }
314 }
315
316 if (FoundMatch) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000317 StringRef::size_type LastComponent = ProgNameRef.rfind('-',
Joerg Sonnenbergerf6ce2fb2011-03-16 20:15:43 +0000318 ProgNameRef.size() - strlen(suffixes[i].Suffix));
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000319 if (LastComponent != StringRef::npos)
Joerg Sonnenbergerf6ce2fb2011-03-16 20:15:43 +0000320 Prefix = ProgNameRef.slice(0, LastComponent);
321 break;
322 }
323
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000324 StringRef::size_type LastComponent = ProgNameRef.rfind('-');
325 if (LastComponent == StringRef::npos)
Joerg Sonnenbergerf6ce2fb2011-03-16 20:15:43 +0000326 break;
327 ProgNameRef = ProgNameRef.slice(0, LastComponent);
328 }
329
330 if (Prefix.empty())
331 return;
332
333 std::string IgnoredError;
334 if (llvm::TargetRegistry::lookupTarget(Prefix, IgnoredError)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000335 SmallVectorImpl<const char *>::iterator it = ArgVector.begin();
Joerg Sonnenberger39ec1192011-07-07 16:57:26 +0000336 if (it != ArgVector.end())
337 ++it;
338 ArgVector.insert(it, SaveStringInSet(SavedStrings, Prefix));
339 ArgVector.insert(it,
Sebastian Pop422377c2012-01-20 22:01:23 +0000340 SaveStringInSet(SavedStrings, std::string("-target")));
Joerg Sonnenbergerf6ce2fb2011-03-16 20:15:43 +0000341 }
342}
343
Rafael Espindola77a067a2010-07-19 15:20:12 +0000344int main(int argc_, const char **argv_) {
Daniel Dunbar544ecd12009-03-02 19:59:07 +0000345 llvm::sys::PrintStackTraceOnErrorSignal();
Rafael Espindola77a067a2010-07-19 15:20:12 +0000346 llvm::PrettyStackTraceProgram X(argc_, argv_);
347
348 std::set<std::string> SavedStrings;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000349 SmallVector<const char*, 256> argv;
Rafael Espindola77a067a2010-07-19 15:20:12 +0000350
351 ExpandArgv(argc_, argv_, argv, SavedStrings);
Daniel Dunbar544ecd12009-03-02 19:59:07 +0000352
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000353 // Handle -cc1 integrated tools.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000354 if (argv.size() > 1 && StringRef(argv[1]).startswith("-cc1")) {
355 StringRef Tool = argv[1] + 4;
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000356
357 if (Tool == "")
Daniel Dunbar9d8416b2010-07-20 02:47:40 +0000358 return cc1_main(argv.data()+2, argv.data()+argv.size(), argv[0],
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000359 (void*) (intptr_t) GetExecutablePath);
360 if (Tool == "as")
Daniel Dunbar9d8416b2010-07-20 02:47:40 +0000361 return cc1as_main(argv.data()+2, argv.data()+argv.size(), argv[0],
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000362 (void*) (intptr_t) GetExecutablePath);
363
364 // Reject unknown tools.
365 llvm::errs() << "error: unknown integrated tool '" << Tool << "'\n";
366 return 1;
367 }
Daniel Dunbar1c39f3c2009-11-30 07:18:13 +0000368
Rafael Espindola73d46372009-12-04 19:31:58 +0000369 bool CanonicalPrefixes = true;
Rafael Espindola77a067a2010-07-19 15:20:12 +0000370 for (int i = 1, size = argv.size(); i < size; ++i) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000371 if (StringRef(argv[i]) == "-no-canonical-prefixes") {
Rafael Espindola73d46372009-12-04 19:31:58 +0000372 CanonicalPrefixes = false;
373 break;
374 }
375 }
376
Chad Rosier3e263e42013-02-21 18:56:55 +0000377 // Handle QA_OVERRIDE_GCC3_OPTIONS and CCC_ADD_ARGS, used for editing a
378 // command line behind the scenes.
379 if (const char *OverrideStr = ::getenv("QA_OVERRIDE_GCC3_OPTIONS")) {
380 // FIXME: Driver shouldn't take extra initial argument.
381 ApplyQAOverride(argv, OverrideStr, SavedStrings);
382 } else if (const char *Cur = ::getenv("CCC_ADD_ARGS")) {
383 // FIXME: Driver shouldn't take extra initial argument.
384 std::vector<const char*> ExtraArgs;
385
386 for (;;) {
387 const char *Next = strchr(Cur, ',');
388
389 if (Next) {
390 ExtraArgs.push_back(SaveStringInSet(SavedStrings,
391 std::string(Cur, Next)));
392 Cur = Next + 1;
393 } else {
394 if (*Cur != '\0')
395 ExtraArgs.push_back(SaveStringInSet(SavedStrings, Cur));
396 break;
397 }
398 }
399
400 argv.insert(&argv[1], ExtraArgs.begin(), ExtraArgs.end());
401 }
402
Rafael Espindola9678d272013-06-26 05:03:40 +0000403 std::string Path = GetExecutablePath(argv[0], CanonicalPrefixes);
Rafael Espindola73d46372009-12-04 19:31:58 +0000404
Douglas Gregor811db4e2012-10-23 22:26:28 +0000405 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions;
Chad Rosierd6f716a2012-03-13 20:09:56 +0000406 {
407 // Note that ParseDiagnosticArgs() uses the cc1 option table.
James Molloya3c85b82012-05-01 14:57:16 +0000408 OwningPtr<OptTable> CC1Opts(createDriverOptTable());
Chad Rosierd6f716a2012-03-13 20:09:56 +0000409 unsigned MissingArgIndex, MissingArgCount;
410 OwningPtr<InputArgList> Args(CC1Opts->ParseArgs(argv.begin()+1, argv.end(),
411 MissingArgIndex, MissingArgCount));
412 // We ignore MissingArgCount and the return value of ParseDiagnosticArgs.
413 // Any errors that would be diagnosed here will also be diagnosed later,
414 // when the DiagnosticsEngine actually exists.
Douglas Gregor811db4e2012-10-23 22:26:28 +0000415 (void) ParseDiagnosticArgs(*DiagOpts, *Args);
Chad Rosierd6f716a2012-03-13 20:09:56 +0000416 }
417 // Now we can create the DiagnosticsEngine with a properly-filled-out
418 // DiagnosticOptions instance.
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000419 TextDiagnosticPrinter *DiagClient
Douglas Gregor811db4e2012-10-23 22:26:28 +0000420 = new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts);
Rafael Espindola9678d272013-06-26 05:03:40 +0000421 DiagClient->setPrefix(llvm::sys::path::filename(Path));
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000422 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
Chad Rosierd6f716a2012-03-13 20:09:56 +0000423
Douglas Gregor811db4e2012-10-23 22:26:28 +0000424 DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagClient);
Chad Rosier5f15a352013-01-15 01:21:53 +0000425 ProcessWarningOptions(Diags, *DiagOpts, /*ReportDiags=*/false);
Daniel Dunbard9b80c22009-03-18 02:11:26 +0000426
Rafael Espindola9678d272013-06-26 05:03:40 +0000427 Driver TheDriver(Path, llvm::sys::getDefaultTargetTriple(), "a.out", Diags);
Daniel Dunbardae1d342009-04-01 19:08:46 +0000428
Daniel Dunbar88979912010-08-01 22:29:51 +0000429 // Attempt to find the original path used to invoke the driver, to determine
430 // the installed path. We do this manually, because we want to support that
431 // path being a symlink.
Michael J. Spencer740857f2010-12-21 16:45:57 +0000432 {
Dylan Noblesmithf1a13f22012-02-13 12:32:26 +0000433 SmallString<128> InstalledPath(argv[0]);
Daniel Dunbar88979912010-08-01 22:29:51 +0000434
Michael J. Spencer740857f2010-12-21 16:45:57 +0000435 // Do a PATH lookup, if there are no directory components.
436 if (llvm::sys::path::filename(InstalledPath) == InstalledPath) {
Rafael Espindola0725a7d2013-06-13 19:25:45 +0000437 std::string Tmp = llvm::sys::FindProgramByName(
Michael J. Spencer740857f2010-12-21 16:45:57 +0000438 llvm::sys::path::filename(InstalledPath.str()));
439 if (!Tmp.empty())
Rafael Espindola0725a7d2013-06-13 19:25:45 +0000440 InstalledPath = Tmp;
Michael J. Spencer740857f2010-12-21 16:45:57 +0000441 }
442 llvm::sys::fs::make_absolute(InstalledPath);
443 InstalledPath = llvm::sys::path::parent_path(InstalledPath);
444 bool exists;
445 if (!llvm::sys::fs::exists(InstalledPath.str(), exists) && exists)
446 TheDriver.setInstalledDir(InstalledPath);
Daniel Dunbar88979912010-08-01 22:29:51 +0000447 }
Daniel Dunbar88979912010-08-01 22:29:51 +0000448
Joerg Sonnenbergerf6ce2fb2011-03-16 20:15:43 +0000449 llvm::InitializeAllTargets();
450 ParseProgName(argv, SavedStrings, TheDriver);
Joerg Sonnenbergerb86f5f42011-03-06 23:31:01 +0000451
Daniel Dunbar6a8efa82010-03-20 08:01:59 +0000452 // Handle CC_PRINT_OPTIONS and CC_PRINT_OPTIONS_FILE.
453 TheDriver.CCPrintOptions = !!::getenv("CC_PRINT_OPTIONS");
454 if (TheDriver.CCPrintOptions)
455 TheDriver.CCPrintOptionsFilename = ::getenv("CC_PRINT_OPTIONS_FILE");
456
Daniel Dunbarac540b32011-02-02 21:11:35 +0000457 // Handle CC_PRINT_HEADERS and CC_PRINT_HEADERS_FILE.
458 TheDriver.CCPrintHeaders = !!::getenv("CC_PRINT_HEADERS");
459 if (TheDriver.CCPrintHeaders)
460 TheDriver.CCPrintHeadersFilename = ::getenv("CC_PRINT_HEADERS_FILE");
461
Daniel Dunbar529c03b2011-04-07 18:01:20 +0000462 // Handle CC_LOG_DIAGNOSTICS and CC_LOG_DIAGNOSTICS_FILE.
463 TheDriver.CCLogDiagnostics = !!::getenv("CC_LOG_DIAGNOSTICS");
464 if (TheDriver.CCLogDiagnostics)
465 TheDriver.CCLogDiagnosticsFilename = ::getenv("CC_LOG_DIAGNOSTICS_FILE");
466
Dylan Noblesmith1cd10692012-02-13 12:32:21 +0000467 OwningPtr<Compilation> C(TheDriver.BuildCompilation(argv));
Daniel Dunbar1acb0eb2009-03-21 00:40:53 +0000468 int Res = 0;
Chad Rosierdd60e092013-01-29 20:15:05 +0000469 SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
Daniel Dunbar1acb0eb2009-03-21 00:40:53 +0000470 if (C.get())
Chad Rosierdd60e092013-01-29 20:15:05 +0000471 Res = TheDriver.ExecuteCompilation(*C, FailingCommands);
Chad Rosierbe10f982011-08-02 17:58:04 +0000472
Chad Rosier681e4b82012-04-20 17:08:59 +0000473 // Force a crash to test the diagnostics.
Richard Smith940a6d72012-12-25 21:56:27 +0000474 if (::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH")) {
475 Diags.Report(diag::err_drv_force_crash) << "FORCE_CLANG_DIAGNOSTICS_CRASH";
Chad Rosierdd60e092013-01-29 20:15:05 +0000476 const Command *FailingCommand = 0;
477 FailingCommands.push_back(std::make_pair(-1, FailingCommand));
Richard Smith940a6d72012-12-25 21:56:27 +0000478 }
Chad Rosier681e4b82012-04-20 17:08:59 +0000479
Chad Rosierdd60e092013-01-29 20:15:05 +0000480 for (SmallVectorImpl< std::pair<int, const Command *> >::iterator it =
481 FailingCommands.begin(), ie = FailingCommands.end(); it != ie; ++it) {
482 int CommandRes = it->first;
483 const Command *FailingCommand = it->second;
484 if (!Res)
485 Res = CommandRes;
486
487 // If result status is < 0, then the driver command signalled an error.
488 // If result status is 70, then the driver command reported a fatal error.
489 // In these cases, generate additional diagnostic information if possible.
490 if (CommandRes < 0 || CommandRes == 70) {
491 TheDriver.generateCompilationDiagnostics(*C, FailingCommand);
Chad Rosierdd60e092013-01-29 20:15:05 +0000492 break;
493 }
494 }
Chad Rosierbe10f982011-08-02 17:58:04 +0000495
Chris Lattner09f8cc82010-03-30 05:39:52 +0000496 // If any timers were active but haven't been destroyed yet, print their
497 // results now. This happens in -disable-free mode.
498 llvm::TimerGroup::printAll(llvm::errs());
499
Daniel Dunbar2608c542009-03-18 01:38:48 +0000500 llvm::llvm_shutdown();
501
NAKAMURA Takumied5bbe92012-07-17 05:09:29 +0000502#ifdef _WIN32
503 // Exit status should not be negative on Win32, unless abnormal termination.
504 // Once abnormal termiation was caught, negative status should not be
505 // propagated.
506 if (Res < 0)
507 Res = 1;
508#endif
509
Chad Rosierdd60e092013-01-29 20:15:05 +0000510 // If we have multiple failing commands, we return the result of the first
511 // failing command.
Daniel Dunbar1acb0eb2009-03-21 00:40:53 +0000512 return Res;
Daniel Dunbar544ecd12009-03-02 19:59:07 +0000513}