blob: 6d81db1f2ac5cb222ce1f49ec5ce084a473308b6 [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"
Craig Topper93b402d2013-07-15 04:28:48 +000028#include "llvm/ADT/STLExtras.h"
Reid Kleckner898229a2013-06-14 17:17:23 +000029#include "llvm/Option/ArgList.h"
30#include "llvm/Option/OptTable.h"
31#include "llvm/Option/Option.h"
Rafael Espindola77a067a2010-07-19 15:20:12 +000032#include "llvm/Support/ErrorHandling.h"
Michael J. Spencer740857f2010-12-21 16:45:57 +000033#include "llvm/Support/FileSystem.h"
Chandler Carruthcc0694c2012-12-04 09:25:21 +000034#include "llvm/Support/Host.h"
Daniel Dunbar2608c542009-03-18 01:38:48 +000035#include "llvm/Support/ManagedStatic.h"
Rafael Espindola77a067a2010-07-19 15:20:12 +000036#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000037#include "llvm/Support/Path.h"
Chandler Carruthcc0694c2012-12-04 09:25:21 +000038#include "llvm/Support/PrettyStackTrace.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000039#include "llvm/Support/Program.h"
Chandler Carruthcc0694c2012-12-04 09:25:21 +000040#include "llvm/Support/Regex.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000041#include "llvm/Support/Signals.h"
Evan Cheng494eb062011-08-24 18:09:14 +000042#include "llvm/Support/TargetRegistry.h"
43#include "llvm/Support/TargetSelect.h"
Chandler Carruthcc0694c2012-12-04 09:25:21 +000044#include "llvm/Support/Timer.h"
45#include "llvm/Support/raw_ostream.h"
Michael J. Spencerf25faaa2010-12-09 17:36:38 +000046#include "llvm/Support/system_error.h"
Daniel Dunbarc0b3e952009-03-12 08:55:43 +000047using namespace clang;
Daniel Dunbarb2cd66b2009-03-04 20:49:20 +000048using namespace clang::driver;
Reid Kleckner898229a2013-06-14 17:17:23 +000049using namespace llvm::opt;
Daniel Dunbar544ecd12009-03-02 19:59:07 +000050
Rafael Espindola9678d272013-06-26 05:03:40 +000051std::string GetExecutablePath(const char *Argv0, bool CanonicalPrefixes) {
Rafael Espindola73d46372009-12-04 19:31:58 +000052 if (!CanonicalPrefixes)
Rafael Espindola9678d272013-06-26 05:03:40 +000053 return Argv0;
Rafael Espindola73d46372009-12-04 19:31:58 +000054
Daniel Dunbarda382a82009-03-18 20:25:53 +000055 // This just needs to be some symbol in the binary; C++ doesn't
56 // allow taking the address of ::main however.
57 void *P = (void*) (intptr_t) GetExecutablePath;
Rafael Espindola9678d272013-06-26 05:03:40 +000058 return llvm::sys::fs::getMainExecutable(Argv0, P);
Daniel Dunbarda382a82009-03-18 20:25:53 +000059}
60
Daniel Dunbarc3ccd182009-07-17 18:10:27 +000061static const char *SaveStringInSet(std::set<std::string> &SavedStrings,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000062 StringRef S) {
Daniel Dunbar3f4a2c22009-04-17 01:54:00 +000063 return SavedStrings.insert(S).first->c_str();
64}
65
66/// ApplyQAOverride - Apply a list of edits to the input argument lists.
67///
68/// The input string is a space separate list of edits to perform,
69/// they are applied in order to the input argument lists. Edits
70/// should be one of the following forms:
71///
Daniel Dunbar54091b82009-07-16 21:32:51 +000072/// '#': Silence information about the changes to the command line arguments.
73///
Daniel Dunbar3f4a2c22009-04-17 01:54:00 +000074/// '^': Add FOO as a new argument at the beginning of the command line.
75///
76/// '+': Add FOO as a new argument at the end of the command line.
77///
Daniel Dunbard2b20c12010-02-17 21:00:34 +000078/// 's/XXX/YYY/': Substitute the regular expression XXX with YYY in the command
79/// line.
Daniel Dunbar3f4a2c22009-04-17 01:54:00 +000080///
81/// 'xOPTION': Removes all instances of the literal argument OPTION.
82///
83/// 'XOPTION': Removes all instances of the literal argument OPTION,
84/// and the following argument.
85///
86/// 'Ox': Removes all flags matching 'O' or 'O[sz0-9]' and adds 'Ox'
87/// at the end of the command line.
Daniel Dunbar54091b82009-07-16 21:32:51 +000088///
89/// \param OS - The stream to write edit information to.
90/// \param Args - The vector of command line arguments.
91/// \param Edit - The override command to perform.
92/// \param SavedStrings - Set to use for storing string representations.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000093static void ApplyOneQAOverride(raw_ostream &OS,
94 SmallVectorImpl<const char*> &Args,
95 StringRef Edit,
Chris Lattner09f8cc82010-03-30 05:39:52 +000096 std::set<std::string> &SavedStrings) {
Daniel Dunbar3f4a2c22009-04-17 01:54:00 +000097 // This does not need to be efficient.
98
Daniel Dunbarc3ccd182009-07-17 18:10:27 +000099 if (Edit[0] == '^') {
100 const char *Str =
Daniel Dunbard2b20c12010-02-17 21:00:34 +0000101 SaveStringInSet(SavedStrings, Edit.substr(1));
Daniel Dunbarc3ccd182009-07-17 18:10:27 +0000102 OS << "### Adding argument " << Str << " at beginning\n";
103 Args.insert(Args.begin() + 1, Str);
104 } else if (Edit[0] == '+') {
105 const char *Str =
Daniel Dunbard2b20c12010-02-17 21:00:34 +0000106 SaveStringInSet(SavedStrings, Edit.substr(1));
Daniel Dunbarc3ccd182009-07-17 18:10:27 +0000107 OS << "### Adding argument " << Str << " at end\n";
108 Args.push_back(Str);
Daniel Dunbard2b20c12010-02-17 21:00:34 +0000109 } else if (Edit[0] == 's' && Edit[1] == '/' && Edit.endswith("/") &&
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000110 Edit.slice(2, Edit.size()-1).find('/') != StringRef::npos) {
111 StringRef MatchPattern = Edit.substr(2).split('/').first;
112 StringRef ReplPattern = Edit.substr(2).split('/').second;
Daniel Dunbard2b20c12010-02-17 21:00:34 +0000113 ReplPattern = ReplPattern.slice(0, ReplPattern.size()-1);
114
115 for (unsigned i = 1, e = Args.size(); i != e; ++i) {
116 std::string Repl = llvm::Regex(MatchPattern).sub(ReplPattern, Args[i]);
117
118 if (Repl != Args[i]) {
119 OS << "### Replacing '" << Args[i] << "' with '" << Repl << "'\n";
120 Args[i] = SaveStringInSet(SavedStrings, Repl);
121 }
122 }
Daniel Dunbarc3ccd182009-07-17 18:10:27 +0000123 } else if (Edit[0] == 'x' || Edit[0] == 'X') {
124 std::string Option = Edit.substr(1, std::string::npos);
125 for (unsigned i = 1; i < Args.size();) {
126 if (Option == Args[i]) {
127 OS << "### Deleting argument " << Args[i] << '\n';
128 Args.erase(Args.begin() + i);
129 if (Edit[0] == 'X') {
130 if (i < Args.size()) {
131 OS << "### Deleting argument " << Args[i] << '\n';
132 Args.erase(Args.begin() + i);
133 } else
134 OS << "### Invalid X edit, end of command line!\n";
135 }
136 } else
137 ++i;
138 }
139 } else if (Edit[0] == 'O') {
140 for (unsigned i = 1; i < Args.size();) {
141 const char *A = Args[i];
142 if (A[0] == '-' && A[1] == 'O' &&
143 (A[2] == '\0' ||
144 (A[3] == '\0' && (A[2] == 's' || A[2] == 'z' ||
145 ('0' <= A[2] && A[2] <= '9'))))) {
146 OS << "### Deleting argument " << Args[i] << '\n';
147 Args.erase(Args.begin() + i);
148 } else
149 ++i;
150 }
151 OS << "### Adding argument " << Edit << " at end\n";
Daniel Dunbard2b20c12010-02-17 21:00:34 +0000152 Args.push_back(SaveStringInSet(SavedStrings, '-' + Edit.str()));
Daniel Dunbarc3ccd182009-07-17 18:10:27 +0000153 } else {
154 OS << "### Unrecognized edit: " << Edit << "\n";
155 }
Daniel Dunbar3f4a2c22009-04-17 01:54:00 +0000156}
157
158/// ApplyQAOverride - Apply a comma separate list of edits to the
159/// input argument lists. See ApplyOneQAOverride.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000160static void ApplyQAOverride(SmallVectorImpl<const char*> &Args,
Chris Lattner09f8cc82010-03-30 05:39:52 +0000161 const char *OverrideStr,
162 std::set<std::string> &SavedStrings) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000163 raw_ostream *OS = &llvm::errs();
Daniel Dunbarc3ccd182009-07-17 18:10:27 +0000164
Daniel Dunbar54091b82009-07-16 21:32:51 +0000165 if (OverrideStr[0] == '#') {
166 ++OverrideStr;
167 OS = &llvm::nulls();
168 }
169
170 *OS << "### QA_OVERRIDE_GCC3_OPTIONS: " << OverrideStr << "\n";
Daniel Dunbar3f4a2c22009-04-17 01:54:00 +0000171
172 // This does not need to be efficient.
173
174 const char *S = OverrideStr;
175 while (*S) {
176 const char *End = ::strchr(S, ' ');
177 if (!End)
178 End = S + strlen(S);
179 if (End != S)
Daniel Dunbar54091b82009-07-16 21:32:51 +0000180 ApplyOneQAOverride(*OS, Args, std::string(S, End), SavedStrings);
Daniel Dunbar3f4a2c22009-04-17 01:54:00 +0000181 S = End;
182 if (*S != '\0')
183 ++S;
184 }
185}
186
Daniel Dunbar1c39f3c2009-11-30 07:18:13 +0000187extern int cc1_main(const char **ArgBegin, const char **ArgEnd,
Daniel Dunbar65ca1c62009-11-29 20:58:32 +0000188 const char *Argv0, void *MainAddr);
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000189extern int cc1as_main(const char **ArgBegin, const char **ArgEnd,
190 const char *Argv0, void *MainAddr);
Daniel Dunbar51cd8f02009-11-19 07:37:51 +0000191
Rafael Espindola77a067a2010-07-19 15:20:12 +0000192static void ExpandArgsFromBuf(const char *Arg,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000193 SmallVectorImpl<const char*> &ArgVector,
Rafael Espindola77a067a2010-07-19 15:20:12 +0000194 std::set<std::string> &SavedStrings) {
195 const char *FName = Arg + 1;
Dylan Noblesmith1cd10692012-02-13 12:32:21 +0000196 OwningPtr<llvm::MemoryBuffer> MemBuf;
Michael J. Spencerd9da7a12010-12-16 03:28:14 +0000197 if (llvm::MemoryBuffer::getFile(FName, MemBuf)) {
Rafael Espindola77a067a2010-07-19 15:20:12 +0000198 ArgVector.push_back(SaveStringInSet(SavedStrings, Arg));
199 return;
200 }
201
202 const char *Buf = MemBuf->getBufferStart();
203 char InQuote = ' ';
204 std::string CurArg;
205
206 for (const char *P = Buf; ; ++P) {
Jordan Rosea7d03842013-02-08 22:30:41 +0000207 if (*P == '\0' || (isWhitespace(*P) && InQuote == ' ')) {
Rafael Espindola77a067a2010-07-19 15:20:12 +0000208 if (!CurArg.empty()) {
209
210 if (CurArg[0] != '@') {
211 ArgVector.push_back(SaveStringInSet(SavedStrings, CurArg));
212 } else {
213 ExpandArgsFromBuf(CurArg.c_str(), ArgVector, SavedStrings);
214 }
215
216 CurArg = "";
217 }
218 if (*P == '\0')
219 break;
220 else
221 continue;
222 }
223
Jordan Rosea7d03842013-02-08 22:30:41 +0000224 if (isWhitespace(*P)) {
Rafael Espindola77a067a2010-07-19 15:20:12 +0000225 if (InQuote != ' ')
226 CurArg.push_back(*P);
227 continue;
228 }
229
230 if (*P == '"' || *P == '\'') {
231 if (InQuote == *P)
232 InQuote = ' ';
233 else if (InQuote == ' ')
234 InQuote = *P;
235 else
236 CurArg.push_back(*P);
237 continue;
238 }
239
240 if (*P == '\\') {
241 ++P;
242 if (*P != '\0')
243 CurArg.push_back(*P);
244 continue;
245 }
246 CurArg.push_back(*P);
247 }
Rafael Espindola77a067a2010-07-19 15:20:12 +0000248}
249
250static void ExpandArgv(int argc, const char **argv,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000251 SmallVectorImpl<const char*> &ArgVector,
Rafael Espindola77a067a2010-07-19 15:20:12 +0000252 std::set<std::string> &SavedStrings) {
253 for (int i = 0; i < argc; ++i) {
254 const char *Arg = argv[i];
255 if (Arg[0] != '@') {
256 ArgVector.push_back(SaveStringInSet(SavedStrings, std::string(Arg)));
257 continue;
258 }
259
260 ExpandArgsFromBuf(Arg, ArgVector, SavedStrings);
261 }
262}
263
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000264static void ParseProgName(SmallVectorImpl<const char *> &ArgVector,
Joerg Sonnenbergerf6ce2fb2011-03-16 20:15:43 +0000265 std::set<std::string> &SavedStrings,
266 Driver &TheDriver)
267{
268 // Try to infer frontend type and default target from the program name.
269
270 // suffixes[] contains the list of known driver suffixes.
271 // Suffixes are compared against the program name in order.
272 // If there is a match, the frontend type is updated as necessary (CPP/C++).
273 // If there is no match, a second round is done after stripping the last
274 // hyphen and everything following it. This allows using something like
275 // "clang++-2.9".
276
277 // If there is a match in either the first or second round,
278 // the function tries to identify a target as prefix. E.g.
279 // "x86_64-linux-clang" as interpreted as suffix "clang" with
280 // target prefix "x86_64-linux". If such a target prefix is found,
Sebastian Pop422377c2012-01-20 22:01:23 +0000281 // is gets added via -target as implicit first argument.
Joerg Sonnenbergerf6ce2fb2011-03-16 20:15:43 +0000282 static const struct {
283 const char *Suffix;
284 bool IsCXX;
285 bool IsCPP;
286 } suffixes [] = {
Chandler Carruth482942e2012-09-11 10:40:21 +0000287 { "clang", false, false },
288 { "clang++", true, false },
289 { "clang-c++", true, false },
290 { "clang-cc", false, false },
291 { "clang-cpp", false, true },
292 { "clang-g++", true, false },
293 { "clang-gcc", false, false },
294 { "cc", false, false },
295 { "cpp", false, true },
296 { "++", true, false },
Joerg Sonnenbergerf6ce2fb2011-03-16 20:15:43 +0000297 };
298 std::string ProgName(llvm::sys::path::stem(ArgVector[0]));
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000299 StringRef ProgNameRef(ProgName);
300 StringRef Prefix;
Joerg Sonnenbergerf6ce2fb2011-03-16 20:15:43 +0000301
302 for (int Components = 2; Components; --Components) {
303 bool FoundMatch = false;
304 size_t i;
305
Craig Topper93b402d2013-07-15 04:28:48 +0000306 for (i = 0; i < llvm::array_lengthof(suffixes); ++i) {
Joerg Sonnenbergerf6ce2fb2011-03-16 20:15:43 +0000307 if (ProgNameRef.endswith(suffixes[i].Suffix)) {
308 FoundMatch = true;
Chandler Carruth482942e2012-09-11 10:40:21 +0000309 if (suffixes[i].IsCXX)
Joerg Sonnenbergerf6ce2fb2011-03-16 20:15:43 +0000310 TheDriver.CCCIsCXX = true;
311 if (suffixes[i].IsCPP)
312 TheDriver.CCCIsCPP = true;
313 break;
314 }
315 }
316
317 if (FoundMatch) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000318 StringRef::size_type LastComponent = ProgNameRef.rfind('-',
Joerg Sonnenbergerf6ce2fb2011-03-16 20:15:43 +0000319 ProgNameRef.size() - strlen(suffixes[i].Suffix));
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000320 if (LastComponent != StringRef::npos)
Joerg Sonnenbergerf6ce2fb2011-03-16 20:15:43 +0000321 Prefix = ProgNameRef.slice(0, LastComponent);
322 break;
323 }
324
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000325 StringRef::size_type LastComponent = ProgNameRef.rfind('-');
326 if (LastComponent == StringRef::npos)
Joerg Sonnenbergerf6ce2fb2011-03-16 20:15:43 +0000327 break;
328 ProgNameRef = ProgNameRef.slice(0, LastComponent);
329 }
330
331 if (Prefix.empty())
332 return;
333
334 std::string IgnoredError;
335 if (llvm::TargetRegistry::lookupTarget(Prefix, IgnoredError)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000336 SmallVectorImpl<const char *>::iterator it = ArgVector.begin();
Joerg Sonnenberger39ec1192011-07-07 16:57:26 +0000337 if (it != ArgVector.end())
338 ++it;
339 ArgVector.insert(it, SaveStringInSet(SavedStrings, Prefix));
340 ArgVector.insert(it,
Sebastian Pop422377c2012-01-20 22:01:23 +0000341 SaveStringInSet(SavedStrings, std::string("-target")));
Joerg Sonnenbergerf6ce2fb2011-03-16 20:15:43 +0000342 }
343}
344
Rafael Espindola77a067a2010-07-19 15:20:12 +0000345int main(int argc_, const char **argv_) {
Daniel Dunbar544ecd12009-03-02 19:59:07 +0000346 llvm::sys::PrintStackTraceOnErrorSignal();
Rafael Espindola77a067a2010-07-19 15:20:12 +0000347 llvm::PrettyStackTraceProgram X(argc_, argv_);
348
349 std::set<std::string> SavedStrings;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000350 SmallVector<const char*, 256> argv;
Rafael Espindola77a067a2010-07-19 15:20:12 +0000351
352 ExpandArgv(argc_, argv_, argv, SavedStrings);
Daniel Dunbar544ecd12009-03-02 19:59:07 +0000353
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000354 // Handle -cc1 integrated tools.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000355 if (argv.size() > 1 && StringRef(argv[1]).startswith("-cc1")) {
356 StringRef Tool = argv[1] + 4;
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000357
358 if (Tool == "")
Daniel Dunbar9d8416b2010-07-20 02:47:40 +0000359 return cc1_main(argv.data()+2, argv.data()+argv.size(), argv[0],
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000360 (void*) (intptr_t) GetExecutablePath);
361 if (Tool == "as")
Daniel Dunbar9d8416b2010-07-20 02:47:40 +0000362 return cc1as_main(argv.data()+2, argv.data()+argv.size(), argv[0],
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000363 (void*) (intptr_t) GetExecutablePath);
364
365 // Reject unknown tools.
366 llvm::errs() << "error: unknown integrated tool '" << Tool << "'\n";
367 return 1;
368 }
Daniel Dunbar1c39f3c2009-11-30 07:18:13 +0000369
Rafael Espindola73d46372009-12-04 19:31:58 +0000370 bool CanonicalPrefixes = true;
Rafael Espindola77a067a2010-07-19 15:20:12 +0000371 for (int i = 1, size = argv.size(); i < size; ++i) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000372 if (StringRef(argv[i]) == "-no-canonical-prefixes") {
Rafael Espindola73d46372009-12-04 19:31:58 +0000373 CanonicalPrefixes = false;
374 break;
375 }
376 }
377
Chad Rosier3e263e42013-02-21 18:56:55 +0000378 // Handle QA_OVERRIDE_GCC3_OPTIONS and CCC_ADD_ARGS, used for editing a
379 // command line behind the scenes.
380 if (const char *OverrideStr = ::getenv("QA_OVERRIDE_GCC3_OPTIONS")) {
381 // FIXME: Driver shouldn't take extra initial argument.
382 ApplyQAOverride(argv, OverrideStr, SavedStrings);
383 } else if (const char *Cur = ::getenv("CCC_ADD_ARGS")) {
384 // FIXME: Driver shouldn't take extra initial argument.
385 std::vector<const char*> ExtraArgs;
386
387 for (;;) {
388 const char *Next = strchr(Cur, ',');
389
390 if (Next) {
391 ExtraArgs.push_back(SaveStringInSet(SavedStrings,
392 std::string(Cur, Next)));
393 Cur = Next + 1;
394 } else {
395 if (*Cur != '\0')
396 ExtraArgs.push_back(SaveStringInSet(SavedStrings, Cur));
397 break;
398 }
399 }
400
401 argv.insert(&argv[1], ExtraArgs.begin(), ExtraArgs.end());
402 }
403
Rafael Espindola9678d272013-06-26 05:03:40 +0000404 std::string Path = GetExecutablePath(argv[0], CanonicalPrefixes);
Rafael Espindola73d46372009-12-04 19:31:58 +0000405
Douglas Gregor811db4e2012-10-23 22:26:28 +0000406 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions;
Chad Rosierd6f716a2012-03-13 20:09:56 +0000407 {
408 // Note that ParseDiagnosticArgs() uses the cc1 option table.
James Molloya3c85b82012-05-01 14:57:16 +0000409 OwningPtr<OptTable> CC1Opts(createDriverOptTable());
Chad Rosierd6f716a2012-03-13 20:09:56 +0000410 unsigned MissingArgIndex, MissingArgCount;
411 OwningPtr<InputArgList> Args(CC1Opts->ParseArgs(argv.begin()+1, argv.end(),
412 MissingArgIndex, MissingArgCount));
413 // We ignore MissingArgCount and the return value of ParseDiagnosticArgs.
414 // Any errors that would be diagnosed here will also be diagnosed later,
415 // when the DiagnosticsEngine actually exists.
Douglas Gregor811db4e2012-10-23 22:26:28 +0000416 (void) ParseDiagnosticArgs(*DiagOpts, *Args);
Chad Rosierd6f716a2012-03-13 20:09:56 +0000417 }
418 // Now we can create the DiagnosticsEngine with a properly-filled-out
419 // DiagnosticOptions instance.
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000420 TextDiagnosticPrinter *DiagClient
Douglas Gregor811db4e2012-10-23 22:26:28 +0000421 = new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts);
Rafael Espindola9678d272013-06-26 05:03:40 +0000422 DiagClient->setPrefix(llvm::sys::path::filename(Path));
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000423 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
Chad Rosierd6f716a2012-03-13 20:09:56 +0000424
Douglas Gregor811db4e2012-10-23 22:26:28 +0000425 DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagClient);
Chad Rosier5f15a352013-01-15 01:21:53 +0000426 ProcessWarningOptions(Diags, *DiagOpts, /*ReportDiags=*/false);
Daniel Dunbard9b80c22009-03-18 02:11:26 +0000427
Rafael Espindola9678d272013-06-26 05:03:40 +0000428 Driver TheDriver(Path, llvm::sys::getDefaultTargetTriple(), "a.out", Diags);
Daniel Dunbardae1d342009-04-01 19:08:46 +0000429
Daniel Dunbar88979912010-08-01 22:29:51 +0000430 // Attempt to find the original path used to invoke the driver, to determine
431 // the installed path. We do this manually, because we want to support that
432 // path being a symlink.
Michael J. Spencer740857f2010-12-21 16:45:57 +0000433 {
Dylan Noblesmithf1a13f22012-02-13 12:32:26 +0000434 SmallString<128> InstalledPath(argv[0]);
Daniel Dunbar88979912010-08-01 22:29:51 +0000435
Michael J. Spencer740857f2010-12-21 16:45:57 +0000436 // Do a PATH lookup, if there are no directory components.
437 if (llvm::sys::path::filename(InstalledPath) == InstalledPath) {
Rafael Espindola0725a7d2013-06-13 19:25:45 +0000438 std::string Tmp = llvm::sys::FindProgramByName(
Michael J. Spencer740857f2010-12-21 16:45:57 +0000439 llvm::sys::path::filename(InstalledPath.str()));
440 if (!Tmp.empty())
Rafael Espindola0725a7d2013-06-13 19:25:45 +0000441 InstalledPath = Tmp;
Michael J. Spencer740857f2010-12-21 16:45:57 +0000442 }
443 llvm::sys::fs::make_absolute(InstalledPath);
444 InstalledPath = llvm::sys::path::parent_path(InstalledPath);
445 bool exists;
446 if (!llvm::sys::fs::exists(InstalledPath.str(), exists) && exists)
447 TheDriver.setInstalledDir(InstalledPath);
Daniel Dunbar88979912010-08-01 22:29:51 +0000448 }
Daniel Dunbar88979912010-08-01 22:29:51 +0000449
Joerg Sonnenbergerf6ce2fb2011-03-16 20:15:43 +0000450 llvm::InitializeAllTargets();
451 ParseProgName(argv, SavedStrings, TheDriver);
Joerg Sonnenbergerb86f5f42011-03-06 23:31:01 +0000452
Daniel Dunbar6a8efa82010-03-20 08:01:59 +0000453 // Handle CC_PRINT_OPTIONS and CC_PRINT_OPTIONS_FILE.
454 TheDriver.CCPrintOptions = !!::getenv("CC_PRINT_OPTIONS");
455 if (TheDriver.CCPrintOptions)
456 TheDriver.CCPrintOptionsFilename = ::getenv("CC_PRINT_OPTIONS_FILE");
457
Daniel Dunbarac540b32011-02-02 21:11:35 +0000458 // Handle CC_PRINT_HEADERS and CC_PRINT_HEADERS_FILE.
459 TheDriver.CCPrintHeaders = !!::getenv("CC_PRINT_HEADERS");
460 if (TheDriver.CCPrintHeaders)
461 TheDriver.CCPrintHeadersFilename = ::getenv("CC_PRINT_HEADERS_FILE");
462
Daniel Dunbar529c03b2011-04-07 18:01:20 +0000463 // Handle CC_LOG_DIAGNOSTICS and CC_LOG_DIAGNOSTICS_FILE.
464 TheDriver.CCLogDiagnostics = !!::getenv("CC_LOG_DIAGNOSTICS");
465 if (TheDriver.CCLogDiagnostics)
466 TheDriver.CCLogDiagnosticsFilename = ::getenv("CC_LOG_DIAGNOSTICS_FILE");
467
Dylan Noblesmith1cd10692012-02-13 12:32:21 +0000468 OwningPtr<Compilation> C(TheDriver.BuildCompilation(argv));
Daniel Dunbar1acb0eb2009-03-21 00:40:53 +0000469 int Res = 0;
Chad Rosierdd60e092013-01-29 20:15:05 +0000470 SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
Daniel Dunbar1acb0eb2009-03-21 00:40:53 +0000471 if (C.get())
Chad Rosierdd60e092013-01-29 20:15:05 +0000472 Res = TheDriver.ExecuteCompilation(*C, FailingCommands);
Chad Rosierbe10f982011-08-02 17:58:04 +0000473
Chad Rosier681e4b82012-04-20 17:08:59 +0000474 // Force a crash to test the diagnostics.
Richard Smith940a6d72012-12-25 21:56:27 +0000475 if (::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH")) {
476 Diags.Report(diag::err_drv_force_crash) << "FORCE_CLANG_DIAGNOSTICS_CRASH";
Chad Rosierdd60e092013-01-29 20:15:05 +0000477 const Command *FailingCommand = 0;
478 FailingCommands.push_back(std::make_pair(-1, FailingCommand));
Richard Smith940a6d72012-12-25 21:56:27 +0000479 }
Chad Rosier681e4b82012-04-20 17:08:59 +0000480
Chad Rosierdd60e092013-01-29 20:15:05 +0000481 for (SmallVectorImpl< std::pair<int, const Command *> >::iterator it =
482 FailingCommands.begin(), ie = FailingCommands.end(); it != ie; ++it) {
483 int CommandRes = it->first;
484 const Command *FailingCommand = it->second;
485 if (!Res)
486 Res = CommandRes;
487
488 // If result status is < 0, then the driver command signalled an error.
489 // If result status is 70, then the driver command reported a fatal error.
490 // In these cases, generate additional diagnostic information if possible.
491 if (CommandRes < 0 || CommandRes == 70) {
492 TheDriver.generateCompilationDiagnostics(*C, FailingCommand);
Chad Rosierdd60e092013-01-29 20:15:05 +0000493 break;
494 }
495 }
Chad Rosierbe10f982011-08-02 17:58:04 +0000496
Chris Lattner09f8cc82010-03-30 05:39:52 +0000497 // If any timers were active but haven't been destroyed yet, print their
498 // results now. This happens in -disable-free mode.
499 llvm::TimerGroup::printAll(llvm::errs());
500
Daniel Dunbar2608c542009-03-18 01:38:48 +0000501 llvm::llvm_shutdown();
502
NAKAMURA Takumied5bbe92012-07-17 05:09:29 +0000503#ifdef _WIN32
504 // Exit status should not be negative on Win32, unless abnormal termination.
505 // Once abnormal termiation was caught, negative status should not be
506 // propagated.
507 if (Res < 0)
508 Res = 1;
509#endif
510
Chad Rosierdd60e092013-01-29 20:15:05 +0000511 // If we have multiple failing commands, we return the result of the first
512 // failing command.
Daniel Dunbar1acb0eb2009-03-21 00:40:53 +0000513 return Res;
Daniel Dunbar544ecd12009-03-02 19:59:07 +0000514}