blob: e281a89e5019f365c7b8af1dbd191741f4e37265 [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 Carruth5553d0d2014-01-07 11:51:46 +000025#include "llvm/ADT/STLExtras.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"
Alp Toker1d257e12014-06-04 03:28:55 +000028#include "llvm/Config/llvm-config.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"
Reid Kleckner61b23b72013-07-18 20:00:53 +000032#include "llvm/Support/CommandLine.h"
Rafael Espindola77a067a2010-07-19 15:20:12 +000033#include "llvm/Support/ErrorHandling.h"
Michael J. Spencer740857f2010-12-21 16:45:57 +000034#include "llvm/Support/FileSystem.h"
Chandler Carruthcc0694c2012-12-04 09:25:21 +000035#include "llvm/Support/Host.h"
Daniel Dunbar2608c542009-03-18 01:38:48 +000036#include "llvm/Support/ManagedStatic.h"
Rafael Espindola77a067a2010-07-19 15:20:12 +000037#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000038#include "llvm/Support/Path.h"
Chandler Carruthcc0694c2012-12-04 09:25:21 +000039#include "llvm/Support/PrettyStackTrace.h"
David Majnemer3f8f8c92013-10-07 07:33:27 +000040#include "llvm/Support/Process.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000041#include "llvm/Support/Program.h"
Chandler Carruthcc0694c2012-12-04 09:25:21 +000042#include "llvm/Support/Regex.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000043#include "llvm/Support/Signals.h"
Evan Cheng494eb062011-08-24 18:09:14 +000044#include "llvm/Support/TargetRegistry.h"
45#include "llvm/Support/TargetSelect.h"
Chandler Carruthcc0694c2012-12-04 09:25:21 +000046#include "llvm/Support/Timer.h"
47#include "llvm/Support/raw_ostream.h"
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000048#include <memory>
Rafael Espindola8a8e5542014-06-12 17:19:42 +000049#include <system_error>
Daniel Dunbarc0b3e952009-03-12 08:55:43 +000050using namespace clang;
Daniel Dunbarb2cd66b2009-03-04 20:49:20 +000051using namespace clang::driver;
Reid Kleckner898229a2013-06-14 17:17:23 +000052using namespace llvm::opt;
Daniel Dunbar544ecd12009-03-02 19:59:07 +000053
Rafael Espindola9678d272013-06-26 05:03:40 +000054std::string GetExecutablePath(const char *Argv0, bool CanonicalPrefixes) {
Rafael Espindola73d46372009-12-04 19:31:58 +000055 if (!CanonicalPrefixes)
Rafael Espindola9678d272013-06-26 05:03:40 +000056 return Argv0;
Rafael Espindola73d46372009-12-04 19:31:58 +000057
Daniel Dunbarda382a82009-03-18 20:25:53 +000058 // This just needs to be some symbol in the binary; C++ doesn't
59 // allow taking the address of ::main however.
60 void *P = (void*) (intptr_t) GetExecutablePath;
Rafael Espindola9678d272013-06-26 05:03:40 +000061 return llvm::sys::fs::getMainExecutable(Argv0, P);
Daniel Dunbarda382a82009-03-18 20:25:53 +000062}
63
Sean Silva6a9b0f92014-08-15 19:23:53 +000064static const char *GetStableCStr(std::set<std::string> &SavedStrings,
65 StringRef S) {
Daniel Dunbar3f4a2c22009-04-17 01:54:00 +000066 return SavedStrings.insert(S).first->c_str();
67}
68
69/// ApplyQAOverride - Apply a list of edits to the input argument lists.
70///
71/// The input string is a space separate list of edits to perform,
72/// they are applied in order to the input argument lists. Edits
73/// should be one of the following forms:
74///
Daniel Dunbar54091b82009-07-16 21:32:51 +000075/// '#': Silence information about the changes to the command line arguments.
76///
Daniel Dunbar3f4a2c22009-04-17 01:54:00 +000077/// '^': Add FOO as a new argument at the beginning of the command line.
78///
79/// '+': Add FOO as a new argument at the end of the command line.
80///
Daniel Dunbard2b20c12010-02-17 21:00:34 +000081/// 's/XXX/YYY/': Substitute the regular expression XXX with YYY in the command
82/// line.
Daniel Dunbar3f4a2c22009-04-17 01:54:00 +000083///
84/// 'xOPTION': Removes all instances of the literal argument OPTION.
85///
86/// 'XOPTION': Removes all instances of the literal argument OPTION,
87/// and the following argument.
88///
89/// 'Ox': Removes all flags matching 'O' or 'O[sz0-9]' and adds 'Ox'
90/// at the end of the command line.
Daniel Dunbar54091b82009-07-16 21:32:51 +000091///
92/// \param OS - The stream to write edit information to.
93/// \param Args - The vector of command line arguments.
94/// \param Edit - The override command to perform.
95/// \param SavedStrings - Set to use for storing string representations.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000096static void ApplyOneQAOverride(raw_ostream &OS,
97 SmallVectorImpl<const char*> &Args,
98 StringRef Edit,
Chris Lattner09f8cc82010-03-30 05:39:52 +000099 std::set<std::string> &SavedStrings) {
Daniel Dunbar3f4a2c22009-04-17 01:54:00 +0000100 // This does not need to be efficient.
101
Daniel Dunbarc3ccd182009-07-17 18:10:27 +0000102 if (Edit[0] == '^') {
103 const char *Str =
Sean Silva6a9b0f92014-08-15 19:23:53 +0000104 GetStableCStr(SavedStrings, Edit.substr(1));
Daniel Dunbarc3ccd182009-07-17 18:10:27 +0000105 OS << "### Adding argument " << Str << " at beginning\n";
106 Args.insert(Args.begin() + 1, Str);
107 } else if (Edit[0] == '+') {
108 const char *Str =
Sean Silva6a9b0f92014-08-15 19:23:53 +0000109 GetStableCStr(SavedStrings, Edit.substr(1));
Daniel Dunbarc3ccd182009-07-17 18:10:27 +0000110 OS << "### Adding argument " << Str << " at end\n";
111 Args.push_back(Str);
Daniel Dunbard2b20c12010-02-17 21:00:34 +0000112 } else if (Edit[0] == 's' && Edit[1] == '/' && Edit.endswith("/") &&
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000113 Edit.slice(2, Edit.size()-1).find('/') != StringRef::npos) {
114 StringRef MatchPattern = Edit.substr(2).split('/').first;
115 StringRef ReplPattern = Edit.substr(2).split('/').second;
Daniel Dunbard2b20c12010-02-17 21:00:34 +0000116 ReplPattern = ReplPattern.slice(0, ReplPattern.size()-1);
117
118 for (unsigned i = 1, e = Args.size(); i != e; ++i) {
Reid Kleckneraf5fd6a2014-08-22 19:29:30 +0000119 // Ignore end-of-line response file markers
120 if (Args[i] == nullptr)
121 continue;
Daniel Dunbard2b20c12010-02-17 21:00:34 +0000122 std::string Repl = llvm::Regex(MatchPattern).sub(ReplPattern, Args[i]);
123
124 if (Repl != Args[i]) {
125 OS << "### Replacing '" << Args[i] << "' with '" << Repl << "'\n";
Sean Silva6a9b0f92014-08-15 19:23:53 +0000126 Args[i] = GetStableCStr(SavedStrings, Repl);
Daniel Dunbard2b20c12010-02-17 21:00:34 +0000127 }
128 }
Daniel Dunbarc3ccd182009-07-17 18:10:27 +0000129 } else if (Edit[0] == 'x' || Edit[0] == 'X') {
130 std::string Option = Edit.substr(1, std::string::npos);
131 for (unsigned i = 1; i < Args.size();) {
132 if (Option == Args[i]) {
133 OS << "### Deleting argument " << Args[i] << '\n';
134 Args.erase(Args.begin() + i);
135 if (Edit[0] == 'X') {
136 if (i < Args.size()) {
137 OS << "### Deleting argument " << Args[i] << '\n';
138 Args.erase(Args.begin() + i);
139 } else
140 OS << "### Invalid X edit, end of command line!\n";
141 }
142 } else
143 ++i;
144 }
145 } else if (Edit[0] == 'O') {
146 for (unsigned i = 1; i < Args.size();) {
147 const char *A = Args[i];
Reid Kleckneraf5fd6a2014-08-22 19:29:30 +0000148 // Ignore end-of-line response file markers
149 if (A == nullptr)
150 continue;
Daniel Dunbarc3ccd182009-07-17 18:10:27 +0000151 if (A[0] == '-' && A[1] == 'O' &&
152 (A[2] == '\0' ||
153 (A[3] == '\0' && (A[2] == 's' || A[2] == 'z' ||
154 ('0' <= A[2] && A[2] <= '9'))))) {
155 OS << "### Deleting argument " << Args[i] << '\n';
156 Args.erase(Args.begin() + i);
157 } else
158 ++i;
159 }
160 OS << "### Adding argument " << Edit << " at end\n";
Sean Silva6a9b0f92014-08-15 19:23:53 +0000161 Args.push_back(GetStableCStr(SavedStrings, '-' + Edit.str()));
Daniel Dunbarc3ccd182009-07-17 18:10:27 +0000162 } else {
163 OS << "### Unrecognized edit: " << Edit << "\n";
164 }
Daniel Dunbar3f4a2c22009-04-17 01:54:00 +0000165}
166
167/// ApplyQAOverride - Apply a comma separate list of edits to the
168/// input argument lists. See ApplyOneQAOverride.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000169static void ApplyQAOverride(SmallVectorImpl<const char*> &Args,
Chris Lattner09f8cc82010-03-30 05:39:52 +0000170 const char *OverrideStr,
171 std::set<std::string> &SavedStrings) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000172 raw_ostream *OS = &llvm::errs();
Daniel Dunbarc3ccd182009-07-17 18:10:27 +0000173
Daniel Dunbar54091b82009-07-16 21:32:51 +0000174 if (OverrideStr[0] == '#') {
175 ++OverrideStr;
176 OS = &llvm::nulls();
177 }
178
Bob Wilsona19fad72014-01-15 01:41:52 +0000179 *OS << "### CCC_OVERRIDE_OPTIONS: " << OverrideStr << "\n";
Daniel Dunbar3f4a2c22009-04-17 01:54:00 +0000180
181 // This does not need to be efficient.
182
183 const char *S = OverrideStr;
184 while (*S) {
185 const char *End = ::strchr(S, ' ');
186 if (!End)
187 End = S + strlen(S);
188 if (End != S)
Daniel Dunbar54091b82009-07-16 21:32:51 +0000189 ApplyOneQAOverride(*OS, Args, std::string(S, End), SavedStrings);
Daniel Dunbar3f4a2c22009-04-17 01:54:00 +0000190 S = End;
191 if (*S != '\0')
192 ++S;
193 }
194}
195
Sean Silva070cd2d2014-08-15 21:38:36 +0000196extern int cc1_main(ArrayRef<const char *> Argv, const char *Argv0,
197 void *MainAddr);
198extern int cc1as_main(ArrayRef<const char *> Argv, const char *Argv0,
199 void *MainAddr);
Daniel Dunbar51cd8f02009-11-19 07:37:51 +0000200
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000201static void ParseProgName(SmallVectorImpl<const char *> &ArgVector,
Joerg Sonnenbergerf6ce2fb2011-03-16 20:15:43 +0000202 std::set<std::string> &SavedStrings,
203 Driver &TheDriver)
204{
205 // Try to infer frontend type and default target from the program name.
206
207 // suffixes[] contains the list of known driver suffixes.
208 // Suffixes are compared against the program name in order.
209 // If there is a match, the frontend type is updated as necessary (CPP/C++).
210 // If there is no match, a second round is done after stripping the last
211 // hyphen and everything following it. This allows using something like
212 // "clang++-2.9".
213
214 // If there is a match in either the first or second round,
215 // the function tries to identify a target as prefix. E.g.
216 // "x86_64-linux-clang" as interpreted as suffix "clang" with
217 // target prefix "x86_64-linux". If such a target prefix is found,
Sebastian Pop422377c2012-01-20 22:01:23 +0000218 // is gets added via -target as implicit first argument.
Joerg Sonnenbergerf6ce2fb2011-03-16 20:15:43 +0000219 static const struct {
220 const char *Suffix;
Hans Wennborg70850d82013-07-18 20:29:38 +0000221 const char *ModeFlag;
Joerg Sonnenbergerf6ce2fb2011-03-16 20:15:43 +0000222 } suffixes [] = {
Craig Topper69186e72014-06-08 08:38:04 +0000223 { "clang", nullptr },
Hans Wennborg70850d82013-07-18 20:29:38 +0000224 { "clang++", "--driver-mode=g++" },
225 { "clang-c++", "--driver-mode=g++" },
Craig Topper69186e72014-06-08 08:38:04 +0000226 { "clang-cc", nullptr },
Hans Wennborg70850d82013-07-18 20:29:38 +0000227 { "clang-cpp", "--driver-mode=cpp" },
228 { "clang-g++", "--driver-mode=g++" },
Craig Topper69186e72014-06-08 08:38:04 +0000229 { "clang-gcc", nullptr },
Hans Wennborge4b031c2013-07-19 20:33:20 +0000230 { "clang-cl", "--driver-mode=cl" },
Craig Topper69186e72014-06-08 08:38:04 +0000231 { "cc", nullptr },
Hans Wennborg70850d82013-07-18 20:29:38 +0000232 { "cpp", "--driver-mode=cpp" },
Hans Wennborge4b031c2013-07-19 20:33:20 +0000233 { "cl" , "--driver-mode=cl" },
Hans Wennborg70850d82013-07-18 20:29:38 +0000234 { "++", "--driver-mode=g++" },
Joerg Sonnenbergerf6ce2fb2011-03-16 20:15:43 +0000235 };
236 std::string ProgName(llvm::sys::path::stem(ArgVector[0]));
Hans Wennborg501eadb2014-03-12 16:07:46 +0000237#ifdef LLVM_ON_WIN32
Hans Wennborgae1c5a82014-03-11 23:42:29 +0000238 // Transform to lowercase for case insensitive file systems.
Hans Wennborgbcbc89c2013-08-20 21:47:50 +0000239 std::transform(ProgName.begin(), ProgName.end(), ProgName.begin(),
240 toLowercase);
Hans Wennborgae1c5a82014-03-11 23:42:29 +0000241#endif
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000242 StringRef ProgNameRef(ProgName);
243 StringRef Prefix;
Joerg Sonnenbergerf6ce2fb2011-03-16 20:15:43 +0000244
245 for (int Components = 2; Components; --Components) {
246 bool FoundMatch = false;
247 size_t i;
248
Craig Topper28700722013-07-15 05:44:18 +0000249 for (i = 0; i < sizeof(suffixes) / sizeof(suffixes[0]); ++i) {
Joerg Sonnenbergerf6ce2fb2011-03-16 20:15:43 +0000250 if (ProgNameRef.endswith(suffixes[i].Suffix)) {
251 FoundMatch = true;
Hans Wennborg70850d82013-07-18 20:29:38 +0000252 SmallVectorImpl<const char *>::iterator it = ArgVector.begin();
253 if (it != ArgVector.end())
254 ++it;
255 if (suffixes[i].ModeFlag)
256 ArgVector.insert(it, suffixes[i].ModeFlag);
Joerg Sonnenbergerf6ce2fb2011-03-16 20:15:43 +0000257 break;
258 }
259 }
260
261 if (FoundMatch) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000262 StringRef::size_type LastComponent = ProgNameRef.rfind('-',
Joerg Sonnenbergerf6ce2fb2011-03-16 20:15:43 +0000263 ProgNameRef.size() - strlen(suffixes[i].Suffix));
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000264 if (LastComponent != StringRef::npos)
Joerg Sonnenbergerf6ce2fb2011-03-16 20:15:43 +0000265 Prefix = ProgNameRef.slice(0, LastComponent);
266 break;
267 }
268
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000269 StringRef::size_type LastComponent = ProgNameRef.rfind('-');
270 if (LastComponent == StringRef::npos)
Joerg Sonnenbergerf6ce2fb2011-03-16 20:15:43 +0000271 break;
272 ProgNameRef = ProgNameRef.slice(0, LastComponent);
273 }
274
275 if (Prefix.empty())
276 return;
277
278 std::string IgnoredError;
279 if (llvm::TargetRegistry::lookupTarget(Prefix, IgnoredError)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000280 SmallVectorImpl<const char *>::iterator it = ArgVector.begin();
Joerg Sonnenberger39ec1192011-07-07 16:57:26 +0000281 if (it != ArgVector.end())
282 ++it;
Eli Friedmana617d092013-08-20 22:01:43 +0000283 const char* Strings[] =
Sean Silva6a9b0f92014-08-15 19:23:53 +0000284 { GetStableCStr(SavedStrings, std::string("-target")),
285 GetStableCStr(SavedStrings, Prefix) };
Eli Friedmana617d092013-08-20 22:01:43 +0000286 ArgVector.insert(it, Strings, Strings + llvm::array_lengthof(Strings));
Joerg Sonnenbergerf6ce2fb2011-03-16 20:15:43 +0000287 }
288}
289
Sean Silvabcd500e2014-08-15 23:39:12 +0000290namespace {
291 class StringSetSaver : public llvm::cl::StringSaver {
292 public:
293 StringSetSaver(std::set<std::string> &Storage) : Storage(Storage) {}
294 const char *SaveString(const char *Str) override {
295 return GetStableCStr(Storage, Str);
296 }
297 private:
298 std::set<std::string> &Storage;
299 };
300}
301
Sean Silva0ee846f2014-08-15 20:59:03 +0000302static void SetBackdoorDriverOutputsFromEnvVars(Driver &TheDriver) {
Sean Silva2103c382014-08-15 18:50:00 +0000303 // Handle CC_PRINT_OPTIONS and CC_PRINT_OPTIONS_FILE.
304 TheDriver.CCPrintOptions = !!::getenv("CC_PRINT_OPTIONS");
305 if (TheDriver.CCPrintOptions)
306 TheDriver.CCPrintOptionsFilename = ::getenv("CC_PRINT_OPTIONS_FILE");
307
308 // Handle CC_PRINT_HEADERS and CC_PRINT_HEADERS_FILE.
309 TheDriver.CCPrintHeaders = !!::getenv("CC_PRINT_HEADERS");
310 if (TheDriver.CCPrintHeaders)
311 TheDriver.CCPrintHeadersFilename = ::getenv("CC_PRINT_HEADERS_FILE");
312
313 // Handle CC_LOG_DIAGNOSTICS and CC_LOG_DIAGNOSTICS_FILE.
314 TheDriver.CCLogDiagnostics = !!::getenv("CC_LOG_DIAGNOSTICS");
315 if (TheDriver.CCLogDiagnostics)
316 TheDriver.CCLogDiagnosticsFilename = ::getenv("CC_LOG_DIAGNOSTICS_FILE");
317}
318
Sean Silva965bb992014-08-15 18:58:09 +0000319static void FixupDiagPrefixExeName(TextDiagnosticPrinter *DiagClient,
320 const std::string &Path) {
321 // If the clang binary happens to be named cl.exe for compatibility reasons,
322 // use clang-cl.exe as the prefix to avoid confusion between clang and MSVC.
323 StringRef ExeBasename(llvm::sys::path::filename(Path));
324 if (ExeBasename.equals_lower("cl.exe"))
325 ExeBasename = "clang-cl.exe";
326 DiagClient->setPrefix(ExeBasename);
327}
328
Sean Silva22b4a342014-08-15 18:58:12 +0000329// This lets us create the DiagnosticsEngine with a properly-filled-out
330// DiagnosticOptions instance.
331static DiagnosticOptions *
332CreateAndPopulateDiagOpts(SmallVectorImpl<const char *> &argv) {
333 auto *DiagOpts = new DiagnosticOptions;
334 std::unique_ptr<OptTable> Opts(createDriverOptTable());
335 unsigned MissingArgIndex, MissingArgCount;
336 std::unique_ptr<InputArgList> Args(Opts->ParseArgs(
337 argv.begin() + 1, argv.end(), MissingArgIndex, MissingArgCount));
338 // We ignore MissingArgCount and the return value of ParseDiagnosticArgs.
339 // Any errors that would be diagnosed here will also be diagnosed later,
340 // when the DiagnosticsEngine actually exists.
341 (void) ParseDiagnosticArgs(*DiagOpts, *Args);
342 return DiagOpts;
343}
344
Sean Silvab5060472014-08-15 18:58:15 +0000345static void SetInstallDir(SmallVectorImpl<const char *> &argv,
346 Driver &TheDriver) {
347 // Attempt to find the original path used to invoke the driver, to determine
348 // the installed path. We do this manually, because we want to support that
349 // path being a symlink.
350 SmallString<128> InstalledPath(argv[0]);
351
352 // Do a PATH lookup, if there are no directory components.
353 if (llvm::sys::path::filename(InstalledPath) == InstalledPath) {
354 std::string Tmp = llvm::sys::FindProgramByName(
355 llvm::sys::path::filename(InstalledPath.str()));
356 if (!Tmp.empty())
357 InstalledPath = Tmp;
358 }
359 llvm::sys::fs::make_absolute(InstalledPath);
360 InstalledPath = llvm::sys::path::parent_path(InstalledPath);
361 bool exists;
362 if (!llvm::sys::fs::exists(InstalledPath.str(), exists) && exists)
363 TheDriver.setInstalledDir(InstalledPath);
364}
365
Sean Silva5d62c262014-08-15 21:40:51 +0000366static int ExecuteCC1Tool(ArrayRef<const char *> argv, StringRef Tool) {
Sean Silva070cd2d2014-08-15 21:38:36 +0000367 void *GetExecutablePathVP = (void *)(intptr_t) GetExecutablePath;
Sean Silva9a6bdf82014-08-15 19:23:47 +0000368 if (Tool == "")
Sean Silva070cd2d2014-08-15 21:38:36 +0000369 return cc1_main(argv.slice(2), argv[0], GetExecutablePathVP);
Sean Silva9a6bdf82014-08-15 19:23:47 +0000370 if (Tool == "as")
Sean Silva070cd2d2014-08-15 21:38:36 +0000371 return cc1as_main(argv.slice(2), argv[0], GetExecutablePathVP);
Sean Silva9a6bdf82014-08-15 19:23:47 +0000372
373 // Reject unknown tools.
374 llvm::errs() << "error: unknown integrated tool '" << Tool << "'\n";
375 return 1;
376}
377
Rafael Espindola77a067a2010-07-19 15:20:12 +0000378int main(int argc_, const char **argv_) {
Daniel Dunbar544ecd12009-03-02 19:59:07 +0000379 llvm::sys::PrintStackTraceOnErrorSignal();
Rafael Espindola77a067a2010-07-19 15:20:12 +0000380 llvm::PrettyStackTraceProgram X(argc_, argv_);
381
David Majnemer3f8f8c92013-10-07 07:33:27 +0000382 SmallVector<const char *, 256> argv;
383 llvm::SpecificBumpPtrAllocator<char> ArgAllocator;
Rafael Espindolac0809172014-06-12 14:02:15 +0000384 std::error_code EC = llvm::sys::Process::GetArgumentVector(
Craig Topper8c2a2a02014-08-30 16:55:39 +0000385 argv, llvm::makeArrayRef(argv_, argc_), ArgAllocator);
David Majnemer3f8f8c92013-10-07 07:33:27 +0000386 if (EC) {
387 llvm::errs() << "error: couldn't get arguments: " << EC.message() << '\n';
388 return 1;
389 }
390
Rafael Espindola77a067a2010-07-19 15:20:12 +0000391 std::set<std::string> SavedStrings;
Sean Silvabcd500e2014-08-15 23:39:12 +0000392 StringSetSaver Saver(SavedStrings);
Daniel Dunbar544ecd12009-03-02 19:59:07 +0000393
Reid Kleckneraf5fd6a2014-08-22 19:29:30 +0000394 // Determines whether we want nullptr markers in argv to indicate response
395 // files end-of-lines. We only use this for the /LINK driver argument.
396 bool MarkEOLs = true;
Sean Silva9a6bdf82014-08-15 19:23:47 +0000397 if (argv.size() > 1 && StringRef(argv[1]).startswith("-cc1"))
Reid Kleckneraf5fd6a2014-08-22 19:29:30 +0000398 MarkEOLs = false;
399 llvm::cl::ExpandResponseFiles(Saver, llvm::cl::TokenizeGNUCommandLine, argv,
400 MarkEOLs);
401
402 // Handle -cc1 integrated tools, even if -cc1 was expanded from a response
403 // file.
404 auto FirstArg = std::find_if(argv.begin() + 1, argv.end(),
405 [](const char *A) { return A != nullptr; });
406 if (FirstArg != argv.end() && StringRef(*FirstArg).startswith("-cc1")) {
407 // If -cc1 came from a response file, remove the EOL sentinels.
408 if (MarkEOLs) {
409 auto newEnd = std::remove(argv.begin(), argv.end(), nullptr);
410 argv.resize(newEnd - argv.begin());
411 }
Sean Silva5d62c262014-08-15 21:40:51 +0000412 return ExecuteCC1Tool(argv, argv[1] + 4);
Reid Kleckneraf5fd6a2014-08-22 19:29:30 +0000413 }
Daniel Dunbar1c39f3c2009-11-30 07:18:13 +0000414
Rafael Espindola73d46372009-12-04 19:31:58 +0000415 bool CanonicalPrefixes = true;
Rafael Espindola77a067a2010-07-19 15:20:12 +0000416 for (int i = 1, size = argv.size(); i < size; ++i) {
Reid Kleckneraf5fd6a2014-08-22 19:29:30 +0000417 // Skip end-of-line response file markers
418 if (argv[i] == nullptr)
419 continue;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000420 if (StringRef(argv[i]) == "-no-canonical-prefixes") {
Rafael Espindola73d46372009-12-04 19:31:58 +0000421 CanonicalPrefixes = false;
422 break;
423 }
424 }
425
Bob Wilsona19fad72014-01-15 01:41:52 +0000426 // Handle CCC_OVERRIDE_OPTIONS, used for editing a command line behind the
Bob Wilson39265b92014-02-23 00:11:56 +0000427 // scenes.
Bob Wilsona19fad72014-01-15 01:41:52 +0000428 if (const char *OverrideStr = ::getenv("CCC_OVERRIDE_OPTIONS")) {
Chad Rosier3e263e42013-02-21 18:56:55 +0000429 // FIXME: Driver shouldn't take extra initial argument.
430 ApplyQAOverride(argv, OverrideStr, SavedStrings);
Chad Rosier3e263e42013-02-21 18:56:55 +0000431 }
432
Rafael Espindola9678d272013-06-26 05:03:40 +0000433 std::string Path = GetExecutablePath(argv[0], CanonicalPrefixes);
Rafael Espindola73d46372009-12-04 19:31:58 +0000434
Sean Silva22b4a342014-08-15 18:58:12 +0000435 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts =
436 CreateAndPopulateDiagOpts(argv);
437
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000438 TextDiagnosticPrinter *DiagClient
Douglas Gregor811db4e2012-10-23 22:26:28 +0000439 = new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts);
Sean Silva965bb992014-08-15 18:58:09 +0000440 FixupDiagPrefixExeName(DiagClient, Path);
Reid Klecknerdc74af12013-09-04 01:37:22 +0000441
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000442 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
Chad Rosierd6f716a2012-03-13 20:09:56 +0000443
Douglas Gregor811db4e2012-10-23 22:26:28 +0000444 DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagClient);
Chad Rosier5f15a352013-01-15 01:21:53 +0000445 ProcessWarningOptions(Diags, *DiagOpts, /*ReportDiags=*/false);
Daniel Dunbard9b80c22009-03-18 02:11:26 +0000446
Alp Toker1761f112014-05-15 22:26:36 +0000447 Driver TheDriver(Path, llvm::sys::getDefaultTargetTriple(), Diags);
Sean Silvab5060472014-08-15 18:58:15 +0000448 SetInstallDir(argv, TheDriver);
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
Sean Silva0ee846f2014-08-15 20:59:03 +0000453 SetBackdoorDriverOutputsFromEnvVars(TheDriver);
Daniel Dunbar529c03b2011-04-07 18:01:20 +0000454
Ahmed Charlesb8984322014-03-07 20:03:18 +0000455 std::unique_ptr<Compilation> C(TheDriver.BuildCompilation(argv));
Daniel Dunbar1acb0eb2009-03-21 00:40:53 +0000456 int Res = 0;
Chad Rosierdd60e092013-01-29 20:15:05 +0000457 SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
Daniel Dunbar1acb0eb2009-03-21 00:40:53 +0000458 if (C.get())
Chad Rosierdd60e092013-01-29 20:15:05 +0000459 Res = TheDriver.ExecuteCompilation(*C, FailingCommands);
Chad Rosierbe10f982011-08-02 17:58:04 +0000460
Chad Rosier681e4b82012-04-20 17:08:59 +0000461 // Force a crash to test the diagnostics.
Richard Smith940a6d72012-12-25 21:56:27 +0000462 if (::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH")) {
463 Diags.Report(diag::err_drv_force_crash) << "FORCE_CLANG_DIAGNOSTICS_CRASH";
Craig Topper69186e72014-06-08 08:38:04 +0000464 const Command *FailingCommand = nullptr;
Chad Rosierdd60e092013-01-29 20:15:05 +0000465 FailingCommands.push_back(std::make_pair(-1, FailingCommand));
Richard Smith940a6d72012-12-25 21:56:27 +0000466 }
Chad Rosier681e4b82012-04-20 17:08:59 +0000467
Sean Silvabbabefe2014-08-15 19:23:50 +0000468 for (const auto &P : FailingCommands) {
469 int CommandRes = P.first;
470 const Command *FailingCommand = P.second;
Chad Rosierdd60e092013-01-29 20:15:05 +0000471 if (!Res)
472 Res = CommandRes;
473
474 // If result status is < 0, then the driver command signalled an error.
475 // If result status is 70, then the driver command reported a fatal error.
Reid Kleckner3b5c6392014-07-07 20:23:27 +0000476 // On Windows, abort will return an exit code of 3. In these cases,
477 // generate additional diagnostic information if possible.
478 bool DiagnoseCrash = CommandRes < 0 || CommandRes == 70;
479#ifdef LLVM_ON_WIN32
480 DiagnoseCrash |= CommandRes == 3;
481#endif
482 if (DiagnoseCrash) {
Chad Rosierdd60e092013-01-29 20:15:05 +0000483 TheDriver.generateCompilationDiagnostics(*C, FailingCommand);
Chad Rosierdd60e092013-01-29 20:15:05 +0000484 break;
485 }
486 }
Chad Rosierbe10f982011-08-02 17:58:04 +0000487
Chris Lattner09f8cc82010-03-30 05:39:52 +0000488 // If any timers were active but haven't been destroyed yet, print their
489 // results now. This happens in -disable-free mode.
490 llvm::TimerGroup::printAll(llvm::errs());
491
Daniel Dunbar2608c542009-03-18 01:38:48 +0000492 llvm::llvm_shutdown();
493
Hans Wennborg501eadb2014-03-12 16:07:46 +0000494#ifdef LLVM_ON_WIN32
NAKAMURA Takumied5bbe92012-07-17 05:09:29 +0000495 // Exit status should not be negative on Win32, unless abnormal termination.
496 // Once abnormal termiation was caught, negative status should not be
497 // propagated.
498 if (Res < 0)
499 Res = 1;
500#endif
501
Chad Rosierdd60e092013-01-29 20:15:05 +0000502 // If we have multiple failing commands, we return the result of the first
503 // failing command.
Daniel Dunbar1acb0eb2009-03-21 00:40:53 +0000504 return Res;
Daniel Dunbar544ecd12009-03-02 19:59:07 +0000505}