blob: eeced7eab00780aa665de65c5b7ee60c3af049af [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"
Justin Bogner5a6a2fc2014-10-23 22:20:11 +000021#include "clang/Frontend/ChainedDiagnosticConsumer.h"
Chandler Carruth575bc3ba2015-01-14 11:23:58 +000022#include "clang/Frontend/CompilerInvocation.h"
Justin Bogner5a6a2fc2014-10-23 22:20:11 +000023#include "clang/Frontend/SerializedDiagnosticPrinter.h"
Daniel Dunbar12ee3802010-02-25 03:23:43 +000024#include "clang/Frontend/TextDiagnosticPrinter.h"
Chad Rosierd6f716a2012-03-13 20:09:56 +000025#include "clang/Frontend/Utils.h"
Chris Lattnerce6c42f2011-03-23 04:04:01 +000026#include "llvm/ADT/ArrayRef.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000027#include "llvm/ADT/STLExtras.h"
Daniel Dunbard9b80c22009-03-18 02:11:26 +000028#include "llvm/ADT/SmallString.h"
Rafael Espindola77a067a2010-07-19 15:20:12 +000029#include "llvm/ADT/SmallVector.h"
Alp Toker1d257e12014-06-04 03:28:55 +000030#include "llvm/Config/llvm-config.h"
Reid Kleckner898229a2013-06-14 17:17:23 +000031#include "llvm/Option/ArgList.h"
32#include "llvm/Option/OptTable.h"
33#include "llvm/Option/Option.h"
Reid Kleckner61b23b72013-07-18 20:00:53 +000034#include "llvm/Support/CommandLine.h"
Rafael Espindola77a067a2010-07-19 15:20:12 +000035#include "llvm/Support/ErrorHandling.h"
Michael J. Spencer740857f2010-12-21 16:45:57 +000036#include "llvm/Support/FileSystem.h"
Chandler Carruthcc0694c2012-12-04 09:25:21 +000037#include "llvm/Support/Host.h"
Daniel Dunbar2608c542009-03-18 01:38:48 +000038#include "llvm/Support/ManagedStatic.h"
Rafael Espindola77a067a2010-07-19 15:20:12 +000039#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000040#include "llvm/Support/Path.h"
Chandler Carruthcc0694c2012-12-04 09:25:21 +000041#include "llvm/Support/PrettyStackTrace.h"
David Majnemer3f8f8c92013-10-07 07:33:27 +000042#include "llvm/Support/Process.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000043#include "llvm/Support/Program.h"
Chandler Carruthcc0694c2012-12-04 09:25:21 +000044#include "llvm/Support/Regex.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000045#include "llvm/Support/Signals.h"
Rafael Espindola2b098e42015-06-13 12:50:07 +000046#include "llvm/Support/StringSaver.h"
Evan Cheng494eb062011-08-24 18:09:14 +000047#include "llvm/Support/TargetRegistry.h"
48#include "llvm/Support/TargetSelect.h"
Chandler Carruthcc0694c2012-12-04 09:25:21 +000049#include "llvm/Support/Timer.h"
50#include "llvm/Support/raw_ostream.h"
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000051#include <memory>
Rafael Espindola8a8e5542014-06-12 17:19:42 +000052#include <system_error>
Daniel Dunbarc0b3e952009-03-12 08:55:43 +000053using namespace clang;
Daniel Dunbarb2cd66b2009-03-04 20:49:20 +000054using namespace clang::driver;
Reid Kleckner898229a2013-06-14 17:17:23 +000055using namespace llvm::opt;
Daniel Dunbar544ecd12009-03-02 19:59:07 +000056
Rafael Espindola9678d272013-06-26 05:03:40 +000057std::string GetExecutablePath(const char *Argv0, bool CanonicalPrefixes) {
Rafael Espindola73d46372009-12-04 19:31:58 +000058 if (!CanonicalPrefixes)
Rafael Espindola9678d272013-06-26 05:03:40 +000059 return Argv0;
Rafael Espindola73d46372009-12-04 19:31:58 +000060
Daniel Dunbarda382a82009-03-18 20:25:53 +000061 // This just needs to be some symbol in the binary; C++ doesn't
62 // allow taking the address of ::main however.
63 void *P = (void*) (intptr_t) GetExecutablePath;
Rafael Espindola9678d272013-06-26 05:03:40 +000064 return llvm::sys::fs::getMainExecutable(Argv0, P);
Daniel Dunbarda382a82009-03-18 20:25:53 +000065}
66
Sean Silva6a9b0f92014-08-15 19:23:53 +000067static const char *GetStableCStr(std::set<std::string> &SavedStrings,
68 StringRef S) {
Daniel Dunbar3f4a2c22009-04-17 01:54:00 +000069 return SavedStrings.insert(S).first->c_str();
70}
71
72/// ApplyQAOverride - Apply a list of edits to the input argument lists.
73///
74/// The input string is a space separate list of edits to perform,
75/// they are applied in order to the input argument lists. Edits
76/// should be one of the following forms:
77///
Daniel Dunbar54091b82009-07-16 21:32:51 +000078/// '#': Silence information about the changes to the command line arguments.
79///
Daniel Dunbar3f4a2c22009-04-17 01:54:00 +000080/// '^': Add FOO as a new argument at the beginning of the command line.
81///
82/// '+': Add FOO as a new argument at the end of the command line.
83///
Daniel Dunbard2b20c12010-02-17 21:00:34 +000084/// 's/XXX/YYY/': Substitute the regular expression XXX with YYY in the command
85/// line.
Daniel Dunbar3f4a2c22009-04-17 01:54:00 +000086///
87/// 'xOPTION': Removes all instances of the literal argument OPTION.
88///
89/// 'XOPTION': Removes all instances of the literal argument OPTION,
90/// and the following argument.
91///
92/// 'Ox': Removes all flags matching 'O' or 'O[sz0-9]' and adds 'Ox'
93/// at the end of the command line.
Daniel Dunbar54091b82009-07-16 21:32:51 +000094///
95/// \param OS - The stream to write edit information to.
96/// \param Args - The vector of command line arguments.
97/// \param Edit - The override command to perform.
98/// \param SavedStrings - Set to use for storing string representations.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000099static void ApplyOneQAOverride(raw_ostream &OS,
100 SmallVectorImpl<const char*> &Args,
101 StringRef Edit,
Chris Lattner09f8cc82010-03-30 05:39:52 +0000102 std::set<std::string> &SavedStrings) {
Daniel Dunbar3f4a2c22009-04-17 01:54:00 +0000103 // This does not need to be efficient.
104
Daniel Dunbarc3ccd182009-07-17 18:10:27 +0000105 if (Edit[0] == '^') {
106 const char *Str =
Sean Silva6a9b0f92014-08-15 19:23:53 +0000107 GetStableCStr(SavedStrings, Edit.substr(1));
Daniel Dunbarc3ccd182009-07-17 18:10:27 +0000108 OS << "### Adding argument " << Str << " at beginning\n";
109 Args.insert(Args.begin() + 1, Str);
110 } else if (Edit[0] == '+') {
111 const char *Str =
Sean Silva6a9b0f92014-08-15 19:23:53 +0000112 GetStableCStr(SavedStrings, Edit.substr(1));
Daniel Dunbarc3ccd182009-07-17 18:10:27 +0000113 OS << "### Adding argument " << Str << " at end\n";
114 Args.push_back(Str);
Daniel Dunbard2b20c12010-02-17 21:00:34 +0000115 } else if (Edit[0] == 's' && Edit[1] == '/' && Edit.endswith("/") &&
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000116 Edit.slice(2, Edit.size()-1).find('/') != StringRef::npos) {
117 StringRef MatchPattern = Edit.substr(2).split('/').first;
118 StringRef ReplPattern = Edit.substr(2).split('/').second;
Daniel Dunbard2b20c12010-02-17 21:00:34 +0000119 ReplPattern = ReplPattern.slice(0, ReplPattern.size()-1);
120
121 for (unsigned i = 1, e = Args.size(); i != e; ++i) {
Reid Kleckneraf5fd6a2014-08-22 19:29:30 +0000122 // Ignore end-of-line response file markers
123 if (Args[i] == nullptr)
124 continue;
Daniel Dunbard2b20c12010-02-17 21:00:34 +0000125 std::string Repl = llvm::Regex(MatchPattern).sub(ReplPattern, Args[i]);
126
127 if (Repl != Args[i]) {
128 OS << "### Replacing '" << Args[i] << "' with '" << Repl << "'\n";
Sean Silva6a9b0f92014-08-15 19:23:53 +0000129 Args[i] = GetStableCStr(SavedStrings, Repl);
Daniel Dunbard2b20c12010-02-17 21:00:34 +0000130 }
131 }
Daniel Dunbarc3ccd182009-07-17 18:10:27 +0000132 } else if (Edit[0] == 'x' || Edit[0] == 'X') {
133 std::string Option = Edit.substr(1, std::string::npos);
134 for (unsigned i = 1; i < Args.size();) {
135 if (Option == Args[i]) {
136 OS << "### Deleting argument " << Args[i] << '\n';
137 Args.erase(Args.begin() + i);
138 if (Edit[0] == 'X') {
139 if (i < Args.size()) {
140 OS << "### Deleting argument " << Args[i] << '\n';
141 Args.erase(Args.begin() + i);
142 } else
143 OS << "### Invalid X edit, end of command line!\n";
144 }
145 } else
146 ++i;
147 }
148 } else if (Edit[0] == 'O') {
149 for (unsigned i = 1; i < Args.size();) {
150 const char *A = Args[i];
Reid Kleckneraf5fd6a2014-08-22 19:29:30 +0000151 // Ignore end-of-line response file markers
152 if (A == nullptr)
153 continue;
Daniel Dunbarc3ccd182009-07-17 18:10:27 +0000154 if (A[0] == '-' && A[1] == 'O' &&
155 (A[2] == '\0' ||
156 (A[3] == '\0' && (A[2] == 's' || A[2] == 'z' ||
157 ('0' <= A[2] && A[2] <= '9'))))) {
158 OS << "### Deleting argument " << Args[i] << '\n';
159 Args.erase(Args.begin() + i);
160 } else
161 ++i;
162 }
163 OS << "### Adding argument " << Edit << " at end\n";
Sean Silva6a9b0f92014-08-15 19:23:53 +0000164 Args.push_back(GetStableCStr(SavedStrings, '-' + Edit.str()));
Daniel Dunbarc3ccd182009-07-17 18:10:27 +0000165 } else {
166 OS << "### Unrecognized edit: " << Edit << "\n";
167 }
Daniel Dunbar3f4a2c22009-04-17 01:54:00 +0000168}
169
170/// ApplyQAOverride - Apply a comma separate list of edits to the
171/// input argument lists. See ApplyOneQAOverride.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000172static void ApplyQAOverride(SmallVectorImpl<const char*> &Args,
Chris Lattner09f8cc82010-03-30 05:39:52 +0000173 const char *OverrideStr,
174 std::set<std::string> &SavedStrings) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000175 raw_ostream *OS = &llvm::errs();
Daniel Dunbarc3ccd182009-07-17 18:10:27 +0000176
Daniel Dunbar54091b82009-07-16 21:32:51 +0000177 if (OverrideStr[0] == '#') {
178 ++OverrideStr;
179 OS = &llvm::nulls();
180 }
181
Bob Wilsona19fad72014-01-15 01:41:52 +0000182 *OS << "### CCC_OVERRIDE_OPTIONS: " << OverrideStr << "\n";
Daniel Dunbar3f4a2c22009-04-17 01:54:00 +0000183
184 // This does not need to be efficient.
185
186 const char *S = OverrideStr;
187 while (*S) {
188 const char *End = ::strchr(S, ' ');
189 if (!End)
190 End = S + strlen(S);
191 if (End != S)
Daniel Dunbar54091b82009-07-16 21:32:51 +0000192 ApplyOneQAOverride(*OS, Args, std::string(S, End), SavedStrings);
Daniel Dunbar3f4a2c22009-04-17 01:54:00 +0000193 S = End;
194 if (*S != '\0')
195 ++S;
196 }
197}
198
Sean Silva070cd2d2014-08-15 21:38:36 +0000199extern int cc1_main(ArrayRef<const char *> Argv, const char *Argv0,
200 void *MainAddr);
201extern int cc1as_main(ArrayRef<const char *> Argv, const char *Argv0,
202 void *MainAddr);
Daniel Dunbar51cd8f02009-11-19 07:37:51 +0000203
Hans Wennborg1a27e042014-10-17 17:07:59 +0000204struct DriverSuffix {
205 const char *Suffix;
206 const char *ModeFlag;
207};
Joerg Sonnenbergerf6ce2fb2011-03-16 20:15:43 +0000208
Hans Wennborg1a27e042014-10-17 17:07:59 +0000209static const DriverSuffix *FindDriverSuffix(StringRef ProgName) {
210 // A list of known driver suffixes. Suffixes are compared against the
211 // program name in order. If there is a match, the frontend type if updated as
212 // necessary by applying the ModeFlag.
213 static const DriverSuffix DriverSuffixes[] = {
214 {"clang", nullptr},
215 {"clang++", "--driver-mode=g++"},
216 {"clang-c++", "--driver-mode=g++"},
217 {"clang-cc", nullptr},
218 {"clang-cpp", "--driver-mode=cpp"},
219 {"clang-g++", "--driver-mode=g++"},
220 {"clang-gcc", nullptr},
221 {"clang-cl", "--driver-mode=cl"},
222 {"cc", nullptr},
223 {"cpp", "--driver-mode=cpp"},
224 {"cl", "--driver-mode=cl"},
225 {"++", "--driver-mode=g++"},
Joerg Sonnenbergerf6ce2fb2011-03-16 20:15:43 +0000226 };
Hans Wennborg1a27e042014-10-17 17:07:59 +0000227
228 for (size_t i = 0; i < llvm::array_lengthof(DriverSuffixes); ++i)
229 if (ProgName.endswith(DriverSuffixes[i].Suffix))
230 return &DriverSuffixes[i];
231 return nullptr;
232}
233
Reid Klecknere2d03442015-07-15 22:42:37 +0000234/// Normalize the program name from argv[0] by stripping the file extension if
235/// present and lower-casing the string on Windows.
236static std::string normalizeProgramName(const char *Argv0) {
237 std::string ProgName = llvm::sys::path::stem(Argv0);
238#ifdef LLVM_ON_WIN32
239 // Transform to lowercase for case insensitive file systems.
240 std::transform(ProgName.begin(), ProgName.end(), ProgName.begin(), ::tolower);
241#endif
242 return ProgName;
243}
244
245static const DriverSuffix *parseDriverSuffix(StringRef ProgName) {
Hans Wennborg1a27e042014-10-17 17:07:59 +0000246 // Try to infer frontend type and default target from the program name by
247 // comparing it against DriverSuffixes in order.
248
249 // If there is a match, the function tries to identify a target as prefix.
250 // E.g. "x86_64-linux-clang" as interpreted as suffix "clang" with target
251 // prefix "x86_64-linux". If such a target prefix is found, is gets added via
252 // -target as implicit first argument.
Reid Klecknere2d03442015-07-15 22:42:37 +0000253 const DriverSuffix *DS = FindDriverSuffix(ProgName);
Joerg Sonnenbergerf6ce2fb2011-03-16 20:15:43 +0000254
Hans Wennborg1a27e042014-10-17 17:07:59 +0000255 if (!DS) {
256 // Try again after stripping any trailing version number:
257 // clang++3.5 -> clang++
Reid Klecknere2d03442015-07-15 22:42:37 +0000258 ProgName = ProgName.rtrim("0123456789.");
259 DS = FindDriverSuffix(ProgName);
Joerg Sonnenbergerf6ce2fb2011-03-16 20:15:43 +0000260 }
261
Hans Wennborg1a27e042014-10-17 17:07:59 +0000262 if (!DS) {
263 // Try again after stripping trailing -component.
264 // clang++-tot -> clang++
Reid Klecknere2d03442015-07-15 22:42:37 +0000265 ProgName = ProgName.slice(0, ProgName.rfind('-'));
266 DS = FindDriverSuffix(ProgName);
267 }
268 return DS;
269}
270
271static void insertArgsFromProgramName(StringRef ProgName,
272 const DriverSuffix *DS,
273 SmallVectorImpl<const char *> &ArgVector,
274 std::set<std::string> &SavedStrings) {
275 if (!DS)
276 return;
277
278 if (const char *Flag = DS->ModeFlag) {
279 // Add Flag to the arguments.
280 auto it = ArgVector.begin();
281 if (it != ArgVector.end())
282 ++it;
283 ArgVector.insert(it, Flag);
Hans Wennborg1a27e042014-10-17 17:07:59 +0000284 }
Joerg Sonnenbergerf6ce2fb2011-03-16 20:15:43 +0000285
Reid Klecknere2d03442015-07-15 22:42:37 +0000286 StringRef::size_type LastComponent = ProgName.rfind(
287 '-', ProgName.size() - strlen(DS->Suffix));
288 if (LastComponent == StringRef::npos)
289 return;
Hans Wennborg1a27e042014-10-17 17:07:59 +0000290
Reid Klecknere2d03442015-07-15 22:42:37 +0000291 // Infer target from the prefix.
292 StringRef Prefix = ProgName.slice(0, LastComponent);
293 std::string IgnoredError;
294 if (llvm::TargetRegistry::lookupTarget(Prefix, IgnoredError)) {
295 auto it = ArgVector.begin();
296 if (it != ArgVector.end())
297 ++it;
298 const char *arr[] = { "-target", GetStableCStr(SavedStrings, Prefix) };
299 ArgVector.insert(it, std::begin(arr), std::end(arr));
Joerg Sonnenbergerf6ce2fb2011-03-16 20:15:43 +0000300 }
301}
302
David Majnemer3a4f9582015-08-10 18:16:32 +0000303static void getCLEnvVarOptions(std::string &EnvValue, llvm::StringSaver &Saver,
304 SmallVectorImpl<const char *> &Opts) {
305 llvm::cl::TokenizeWindowsCommandLine(EnvValue, Saver, Opts);
306 // The first instance of '#' should be replaced with '=' in each option.
307 for (const char *Opt : Opts)
308 if (char *NumberSignPtr = const_cast<char *>(::strchr(Opt, '#')))
309 *NumberSignPtr = '=';
310}
311
Sean Silva0ee846f2014-08-15 20:59:03 +0000312static void SetBackdoorDriverOutputsFromEnvVars(Driver &TheDriver) {
Sean Silva2103c382014-08-15 18:50:00 +0000313 // Handle CC_PRINT_OPTIONS and CC_PRINT_OPTIONS_FILE.
314 TheDriver.CCPrintOptions = !!::getenv("CC_PRINT_OPTIONS");
315 if (TheDriver.CCPrintOptions)
316 TheDriver.CCPrintOptionsFilename = ::getenv("CC_PRINT_OPTIONS_FILE");
317
318 // Handle CC_PRINT_HEADERS and CC_PRINT_HEADERS_FILE.
319 TheDriver.CCPrintHeaders = !!::getenv("CC_PRINT_HEADERS");
320 if (TheDriver.CCPrintHeaders)
321 TheDriver.CCPrintHeadersFilename = ::getenv("CC_PRINT_HEADERS_FILE");
322
323 // Handle CC_LOG_DIAGNOSTICS and CC_LOG_DIAGNOSTICS_FILE.
324 TheDriver.CCLogDiagnostics = !!::getenv("CC_LOG_DIAGNOSTICS");
325 if (TheDriver.CCLogDiagnostics)
326 TheDriver.CCLogDiagnosticsFilename = ::getenv("CC_LOG_DIAGNOSTICS_FILE");
327}
328
Sean Silva965bb992014-08-15 18:58:09 +0000329static void FixupDiagPrefixExeName(TextDiagnosticPrinter *DiagClient,
330 const std::string &Path) {
331 // If the clang binary happens to be named cl.exe for compatibility reasons,
332 // use clang-cl.exe as the prefix to avoid confusion between clang and MSVC.
333 StringRef ExeBasename(llvm::sys::path::filename(Path));
334 if (ExeBasename.equals_lower("cl.exe"))
335 ExeBasename = "clang-cl.exe";
336 DiagClient->setPrefix(ExeBasename);
337}
338
Sean Silva22b4a342014-08-15 18:58:12 +0000339// This lets us create the DiagnosticsEngine with a properly-filled-out
340// DiagnosticOptions instance.
341static DiagnosticOptions *
David Blaikie6d492ad2015-06-21 06:32:36 +0000342CreateAndPopulateDiagOpts(ArrayRef<const char *> argv) {
Sean Silva22b4a342014-08-15 18:58:12 +0000343 auto *DiagOpts = new DiagnosticOptions;
344 std::unique_ptr<OptTable> Opts(createDriverOptTable());
345 unsigned MissingArgIndex, MissingArgCount;
David Blaikie69a1d8c2015-06-22 22:07:27 +0000346 InputArgList Args =
347 Opts->ParseArgs(argv.slice(1), MissingArgIndex, MissingArgCount);
Sean Silva22b4a342014-08-15 18:58:12 +0000348 // We ignore MissingArgCount and the return value of ParseDiagnosticArgs.
349 // Any errors that would be diagnosed here will also be diagnosed later,
350 // when the DiagnosticsEngine actually exists.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000351 (void)ParseDiagnosticArgs(*DiagOpts, Args);
Sean Silva22b4a342014-08-15 18:58:12 +0000352 return DiagOpts;
353}
354
Sean Silvab5060472014-08-15 18:58:15 +0000355static void SetInstallDir(SmallVectorImpl<const char *> &argv,
Chandler Carruth9ade6a92015-08-05 17:07:33 +0000356 Driver &TheDriver, bool CanonicalPrefixes) {
Sean Silvab5060472014-08-15 18:58:15 +0000357 // Attempt to find the original path used to invoke the driver, to determine
358 // the installed path. We do this manually, because we want to support that
359 // path being a symlink.
360 SmallString<128> InstalledPath(argv[0]);
361
362 // Do a PATH lookup, if there are no directory components.
Michael J. Spencerb011d482014-11-07 21:30:32 +0000363 if (llvm::sys::path::filename(InstalledPath) == InstalledPath)
364 if (llvm::ErrorOr<std::string> Tmp = llvm::sys::findProgramByName(
365 llvm::sys::path::filename(InstalledPath.str())))
Michael J. Spencer04162ea2014-11-04 01:30:55 +0000366 InstalledPath = *Tmp;
Chandler Carruth9ade6a92015-08-05 17:07:33 +0000367
368 // FIXME: We don't actually canonicalize this, we just make it absolute.
369 if (CanonicalPrefixes)
370 llvm::sys::fs::make_absolute(InstalledPath);
371
Sean Silvab5060472014-08-15 18:58:15 +0000372 InstalledPath = llvm::sys::path::parent_path(InstalledPath);
Rafael Espindola611505f2014-09-11 18:10:13 +0000373 if (llvm::sys::fs::exists(InstalledPath.c_str()))
Sean Silvab5060472014-08-15 18:58:15 +0000374 TheDriver.setInstalledDir(InstalledPath);
375}
376
Sean Silva5d62c262014-08-15 21:40:51 +0000377static int ExecuteCC1Tool(ArrayRef<const char *> argv, StringRef Tool) {
Sean Silva070cd2d2014-08-15 21:38:36 +0000378 void *GetExecutablePathVP = (void *)(intptr_t) GetExecutablePath;
Sean Silva9a6bdf82014-08-15 19:23:47 +0000379 if (Tool == "")
Sean Silva070cd2d2014-08-15 21:38:36 +0000380 return cc1_main(argv.slice(2), argv[0], GetExecutablePathVP);
Sean Silva9a6bdf82014-08-15 19:23:47 +0000381 if (Tool == "as")
Sean Silva070cd2d2014-08-15 21:38:36 +0000382 return cc1as_main(argv.slice(2), argv[0], GetExecutablePathVP);
Sean Silva9a6bdf82014-08-15 19:23:47 +0000383
384 // Reject unknown tools.
385 llvm::errs() << "error: unknown integrated tool '" << Tool << "'\n";
386 return 1;
387}
388
Rafael Espindola77a067a2010-07-19 15:20:12 +0000389int main(int argc_, const char **argv_) {
Daniel Dunbar544ecd12009-03-02 19:59:07 +0000390 llvm::sys::PrintStackTraceOnErrorSignal();
Rafael Espindola77a067a2010-07-19 15:20:12 +0000391 llvm::PrettyStackTraceProgram X(argc_, argv_);
392
David Majnemer33498722014-10-06 23:52:23 +0000393 if (llvm::sys::Process::FixupStandardFileDescriptors())
394 return 1;
395
David Majnemer3f8f8c92013-10-07 07:33:27 +0000396 SmallVector<const char *, 256> argv;
397 llvm::SpecificBumpPtrAllocator<char> ArgAllocator;
Rafael Espindolac0809172014-06-12 14:02:15 +0000398 std::error_code EC = llvm::sys::Process::GetArgumentVector(
Craig Topper8c2a2a02014-08-30 16:55:39 +0000399 argv, llvm::makeArrayRef(argv_, argc_), ArgAllocator);
David Majnemer3f8f8c92013-10-07 07:33:27 +0000400 if (EC) {
401 llvm::errs() << "error: couldn't get arguments: " << EC.message() << '\n';
402 return 1;
403 }
404
Reid Klecknere2d03442015-07-15 22:42:37 +0000405 std::string ProgName = normalizeProgramName(argv[0]);
406 const DriverSuffix *DS = parseDriverSuffix(ProgName);
407
Rafael Espindola2b098e42015-06-13 12:50:07 +0000408 llvm::BumpPtrAllocator A;
409 llvm::BumpPtrStringSaver Saver(A);
Daniel Dunbar544ecd12009-03-02 19:59:07 +0000410
Reid Klecknere2d03442015-07-15 22:42:37 +0000411 // Parse response files using the GNU syntax, unless we're in CL mode. There
412 // are two ways to put clang in CL compatibility mode: argv[0] is either
413 // clang-cl or cl, or --driver-mode=cl is on the command line. The normal
414 // command line parsing can't happen until after response file parsing, so we
415 // have to manually search for a --driver-mode=cl argument the hard way.
416 // Finally, our -cc1 tools don't care which tokenization mode we use because
417 // response files written by clang will tokenize the same way in either mode.
418 llvm::cl::TokenizerCallback Tokenizer = &llvm::cl::TokenizeGNUCommandLine;
419 if ((DS && DS->ModeFlag && strcmp(DS->ModeFlag, "--driver-mode=cl") == 0) ||
420 std::find_if(argv.begin(), argv.end(), [](const char *F) {
421 return F && strcmp(F, "--driver-mode=cl") == 0;
422 }) != argv.end()) {
423 Tokenizer = &llvm::cl::TokenizeWindowsCommandLine;
424 }
425
Reid Kleckneraf5fd6a2014-08-22 19:29:30 +0000426 // Determines whether we want nullptr markers in argv to indicate response
427 // files end-of-lines. We only use this for the /LINK driver argument.
428 bool MarkEOLs = true;
Sean Silva9a6bdf82014-08-15 19:23:47 +0000429 if (argv.size() > 1 && StringRef(argv[1]).startswith("-cc1"))
Reid Kleckneraf5fd6a2014-08-22 19:29:30 +0000430 MarkEOLs = false;
Reid Klecknere2d03442015-07-15 22:42:37 +0000431 llvm::cl::ExpandResponseFiles(Saver, Tokenizer, argv, MarkEOLs);
Reid Kleckneraf5fd6a2014-08-22 19:29:30 +0000432
433 // Handle -cc1 integrated tools, even if -cc1 was expanded from a response
434 // file.
435 auto FirstArg = std::find_if(argv.begin() + 1, argv.end(),
436 [](const char *A) { return A != nullptr; });
437 if (FirstArg != argv.end() && StringRef(*FirstArg).startswith("-cc1")) {
438 // If -cc1 came from a response file, remove the EOL sentinels.
439 if (MarkEOLs) {
440 auto newEnd = std::remove(argv.begin(), argv.end(), nullptr);
441 argv.resize(newEnd - argv.begin());
442 }
Sean Silva5d62c262014-08-15 21:40:51 +0000443 return ExecuteCC1Tool(argv, argv[1] + 4);
Reid Kleckneraf5fd6a2014-08-22 19:29:30 +0000444 }
Daniel Dunbar1c39f3c2009-11-30 07:18:13 +0000445
Rafael Espindola73d46372009-12-04 19:31:58 +0000446 bool CanonicalPrefixes = true;
Rafael Espindola77a067a2010-07-19 15:20:12 +0000447 for (int i = 1, size = argv.size(); i < size; ++i) {
Reid Kleckneraf5fd6a2014-08-22 19:29:30 +0000448 // Skip end-of-line response file markers
449 if (argv[i] == nullptr)
450 continue;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000451 if (StringRef(argv[i]) == "-no-canonical-prefixes") {
Rafael Espindola73d46372009-12-04 19:31:58 +0000452 CanonicalPrefixes = false;
453 break;
454 }
455 }
456
David Majnemer3a4f9582015-08-10 18:16:32 +0000457 // Handle CL and _CL_ which permits additional command line options to be
458 // prepended or appended.
459 if (Tokenizer == &llvm::cl::TokenizeWindowsCommandLine) {
460 // Arguments in "CL" are prepended.
461 llvm::Optional<std::string> OptCL = llvm::sys::Process::GetEnv("CL");
462 if (OptCL.hasValue()) {
463 SmallVector<const char *, 8> PrependedOpts;
464 getCLEnvVarOptions(OptCL.getValue(), Saver, PrependedOpts);
465
466 // Insert right after the program name to prepend to the argument list.
467 argv.insert(argv.begin() + 1, PrependedOpts.begin(), PrependedOpts.end());
468 }
469 // Arguments in "_CL_" are appended.
470 llvm::Optional<std::string> Opt_CL_ = llvm::sys::Process::GetEnv("_CL_");
471 if (Opt_CL_.hasValue()) {
472 SmallVector<const char *, 8> AppendedOpts;
473 getCLEnvVarOptions(Opt_CL_.getValue(), Saver, AppendedOpts);
474
475 // Insert at the end of the argument list to append.
476 argv.append(AppendedOpts.begin(), AppendedOpts.end());
477 }
478 }
479
Rafael Espindola2b098e42015-06-13 12:50:07 +0000480 std::set<std::string> SavedStrings;
Bob Wilsona19fad72014-01-15 01:41:52 +0000481 // Handle CCC_OVERRIDE_OPTIONS, used for editing a command line behind the
Bob Wilson39265b92014-02-23 00:11:56 +0000482 // scenes.
Bob Wilsona19fad72014-01-15 01:41:52 +0000483 if (const char *OverrideStr = ::getenv("CCC_OVERRIDE_OPTIONS")) {
Chad Rosier3e263e42013-02-21 18:56:55 +0000484 // FIXME: Driver shouldn't take extra initial argument.
485 ApplyQAOverride(argv, OverrideStr, SavedStrings);
Chad Rosier3e263e42013-02-21 18:56:55 +0000486 }
487
Rafael Espindola9678d272013-06-26 05:03:40 +0000488 std::string Path = GetExecutablePath(argv[0], CanonicalPrefixes);
Rafael Espindola73d46372009-12-04 19:31:58 +0000489
Sean Silva22b4a342014-08-15 18:58:12 +0000490 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts =
491 CreateAndPopulateDiagOpts(argv);
492
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000493 TextDiagnosticPrinter *DiagClient
Douglas Gregor811db4e2012-10-23 22:26:28 +0000494 = new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts);
Sean Silva965bb992014-08-15 18:58:09 +0000495 FixupDiagPrefixExeName(DiagClient, Path);
Reid Klecknerdc74af12013-09-04 01:37:22 +0000496
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000497 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
Chad Rosierd6f716a2012-03-13 20:09:56 +0000498
Douglas Gregor811db4e2012-10-23 22:26:28 +0000499 DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagClient);
Justin Bogner5a6a2fc2014-10-23 22:20:11 +0000500
501 if (!DiagOpts->DiagnosticSerializationFile.empty()) {
502 auto SerializedConsumer =
503 clang::serialized_diags::create(DiagOpts->DiagnosticSerializationFile,
504 &*DiagOpts, /*MergeChildRecords=*/true);
505 Diags.setClient(new ChainedDiagnosticConsumer(
Alexander Kornienko41c247a2014-11-17 23:46:02 +0000506 Diags.takeClient(), std::move(SerializedConsumer)));
Justin Bogner5a6a2fc2014-10-23 22:20:11 +0000507 }
508
Chad Rosier5f15a352013-01-15 01:21:53 +0000509 ProcessWarningOptions(Diags, *DiagOpts, /*ReportDiags=*/false);
Daniel Dunbard9b80c22009-03-18 02:11:26 +0000510
Alp Toker1761f112014-05-15 22:26:36 +0000511 Driver TheDriver(Path, llvm::sys::getDefaultTargetTriple(), Diags);
Chandler Carruth9ade6a92015-08-05 17:07:33 +0000512 SetInstallDir(argv, TheDriver, CanonicalPrefixes);
Daniel Dunbar88979912010-08-01 22:29:51 +0000513
Joerg Sonnenbergerf6ce2fb2011-03-16 20:15:43 +0000514 llvm::InitializeAllTargets();
Reid Klecknere2d03442015-07-15 22:42:37 +0000515 insertArgsFromProgramName(ProgName, DS, argv, SavedStrings);
Joerg Sonnenbergerb86f5f42011-03-06 23:31:01 +0000516
Sean Silva0ee846f2014-08-15 20:59:03 +0000517 SetBackdoorDriverOutputsFromEnvVars(TheDriver);
Daniel Dunbar529c03b2011-04-07 18:01:20 +0000518
Ahmed Charlesb8984322014-03-07 20:03:18 +0000519 std::unique_ptr<Compilation> C(TheDriver.BuildCompilation(argv));
Daniel Dunbar1acb0eb2009-03-21 00:40:53 +0000520 int Res = 0;
Chad Rosierdd60e092013-01-29 20:15:05 +0000521 SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
Daniel Dunbar1acb0eb2009-03-21 00:40:53 +0000522 if (C.get())
Chad Rosierdd60e092013-01-29 20:15:05 +0000523 Res = TheDriver.ExecuteCompilation(*C, FailingCommands);
Chad Rosierbe10f982011-08-02 17:58:04 +0000524
Chad Rosier681e4b82012-04-20 17:08:59 +0000525 // Force a crash to test the diagnostics.
Richard Smith940a6d72012-12-25 21:56:27 +0000526 if (::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH")) {
527 Diags.Report(diag::err_drv_force_crash) << "FORCE_CLANG_DIAGNOSTICS_CRASH";
Justin Bognere1a33d12014-10-20 21:02:05 +0000528
529 // Pretend that every command failed.
530 FailingCommands.clear();
531 for (const auto &J : C->getJobs())
532 if (const Command *C = dyn_cast<Command>(&J))
533 FailingCommands.push_back(std::make_pair(-1, C));
Richard Smith940a6d72012-12-25 21:56:27 +0000534 }
Chad Rosier681e4b82012-04-20 17:08:59 +0000535
Sean Silvabbabefe2014-08-15 19:23:50 +0000536 for (const auto &P : FailingCommands) {
537 int CommandRes = P.first;
538 const Command *FailingCommand = P.second;
Chad Rosierdd60e092013-01-29 20:15:05 +0000539 if (!Res)
540 Res = CommandRes;
541
542 // If result status is < 0, then the driver command signalled an error.
543 // If result status is 70, then the driver command reported a fatal error.
Reid Kleckner3b5c6392014-07-07 20:23:27 +0000544 // On Windows, abort will return an exit code of 3. In these cases,
545 // generate additional diagnostic information if possible.
546 bool DiagnoseCrash = CommandRes < 0 || CommandRes == 70;
547#ifdef LLVM_ON_WIN32
548 DiagnoseCrash |= CommandRes == 3;
549#endif
550 if (DiagnoseCrash) {
Justin Bognere1a33d12014-10-20 21:02:05 +0000551 TheDriver.generateCompilationDiagnostics(*C, *FailingCommand);
Chad Rosierdd60e092013-01-29 20:15:05 +0000552 break;
553 }
554 }
Chad Rosierbe10f982011-08-02 17:58:04 +0000555
Justin Bogner5a6a2fc2014-10-23 22:20:11 +0000556 Diags.getClient()->finish();
557
Chris Lattner09f8cc82010-03-30 05:39:52 +0000558 // If any timers were active but haven't been destroyed yet, print their
559 // results now. This happens in -disable-free mode.
560 llvm::TimerGroup::printAll(llvm::errs());
Justin Bogner5a6a2fc2014-10-23 22:20:11 +0000561
Daniel Dunbar2608c542009-03-18 01:38:48 +0000562 llvm::llvm_shutdown();
563
Hans Wennborg501eadb2014-03-12 16:07:46 +0000564#ifdef LLVM_ON_WIN32
NAKAMURA Takumied5bbe92012-07-17 05:09:29 +0000565 // Exit status should not be negative on Win32, unless abnormal termination.
566 // Once abnormal termiation was caught, negative status should not be
567 // propagated.
568 if (Res < 0)
569 Res = 1;
570#endif
571
Chad Rosierdd60e092013-01-29 20:15:05 +0000572 // If we have multiple failing commands, we return the result of the first
573 // failing command.
Daniel Dunbar1acb0eb2009-03-21 00:40:53 +0000574 return Res;
Daniel Dunbar544ecd12009-03-02 19:59:07 +0000575}