]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/tools/driver/driver.cpp
Merge OpenSSL 1.0.2g.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / tools / driver / driver.cpp
1 //===-- 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 //
10 // This is the entry point to the clang driver; it is a thin wrapper
11 // for functionality in the Driver clang library.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "clang/Basic/CharInfo.h"
16 #include "clang/Basic/DiagnosticOptions.h"
17 #include "clang/Driver/Compilation.h"
18 #include "clang/Driver/Driver.h"
19 #include "clang/Driver/DriverDiagnostic.h"
20 #include "clang/Driver/Options.h"
21 #include "clang/Frontend/ChainedDiagnosticConsumer.h"
22 #include "clang/Frontend/CompilerInvocation.h"
23 #include "clang/Frontend/SerializedDiagnosticPrinter.h"
24 #include "clang/Frontend/TextDiagnosticPrinter.h"
25 #include "clang/Frontend/Utils.h"
26 #include "llvm/ADT/ArrayRef.h"
27 #include "llvm/ADT/STLExtras.h"
28 #include "llvm/ADT/SmallString.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/Config/llvm-config.h"
31 #include "llvm/Option/ArgList.h"
32 #include "llvm/Option/OptTable.h"
33 #include "llvm/Option/Option.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/FileSystem.h"
37 #include "llvm/Support/Host.h"
38 #include "llvm/Support/ManagedStatic.h"
39 #include "llvm/Support/MemoryBuffer.h"
40 #include "llvm/Support/Path.h"
41 #include "llvm/Support/PrettyStackTrace.h"
42 #include "llvm/Support/Process.h"
43 #include "llvm/Support/Program.h"
44 #include "llvm/Support/Regex.h"
45 #include "llvm/Support/Signals.h"
46 #include "llvm/Support/StringSaver.h"
47 #include "llvm/Support/TargetRegistry.h"
48 #include "llvm/Support/TargetSelect.h"
49 #include "llvm/Support/Timer.h"
50 #include "llvm/Support/raw_ostream.h"
51 #include <memory>
52 #include <system_error>
53 using namespace clang;
54 using namespace clang::driver;
55 using namespace llvm::opt;
56
57 std::string GetExecutablePath(const char *Argv0, bool CanonicalPrefixes) {
58   if (!CanonicalPrefixes)
59     return Argv0;
60
61   // 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;
64   return llvm::sys::fs::getMainExecutable(Argv0, P);
65 }
66
67 static const char *GetStableCStr(std::set<std::string> &SavedStrings,
68                                  StringRef S) {
69   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 ///
78 ///  '#': Silence information about the changes to the command line arguments.
79 ///
80 ///  '^': 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 ///
84 ///  's/XXX/YYY/': Substitute the regular expression XXX with YYY in the command
85 ///  line.
86 ///
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.
94 ///
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.
99 static void ApplyOneQAOverride(raw_ostream &OS,
100                                SmallVectorImpl<const char*> &Args,
101                                StringRef Edit,
102                                std::set<std::string> &SavedStrings) {
103   // This does not need to be efficient.
104
105   if (Edit[0] == '^') {
106     const char *Str =
107       GetStableCStr(SavedStrings, Edit.substr(1));
108     OS << "### Adding argument " << Str << " at beginning\n";
109     Args.insert(Args.begin() + 1, Str);
110   } else if (Edit[0] == '+') {
111     const char *Str =
112       GetStableCStr(SavedStrings, Edit.substr(1));
113     OS << "### Adding argument " << Str << " at end\n";
114     Args.push_back(Str);
115   } else if (Edit[0] == 's' && Edit[1] == '/' && Edit.endswith("/") &&
116              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;
119     ReplPattern = ReplPattern.slice(0, ReplPattern.size()-1);
120
121     for (unsigned i = 1, e = Args.size(); i != e; ++i) {
122       // Ignore end-of-line response file markers
123       if (Args[i] == nullptr)
124         continue;
125       std::string Repl = llvm::Regex(MatchPattern).sub(ReplPattern, Args[i]);
126
127       if (Repl != Args[i]) {
128         OS << "### Replacing '" << Args[i] << "' with '" << Repl << "'\n";
129         Args[i] = GetStableCStr(SavedStrings, Repl);
130       }
131     }
132   } 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];
151       // Ignore end-of-line response file markers
152       if (A == nullptr)
153         continue;
154       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";
164     Args.push_back(GetStableCStr(SavedStrings, '-' + Edit.str()));
165   } else {
166     OS << "### Unrecognized edit: " << Edit << "\n";
167   }
168 }
169
170 /// ApplyQAOverride - Apply a comma separate list of edits to the
171 /// input argument lists. See ApplyOneQAOverride.
172 static void ApplyQAOverride(SmallVectorImpl<const char*> &Args,
173                             const char *OverrideStr,
174                             std::set<std::string> &SavedStrings) {
175   raw_ostream *OS = &llvm::errs();
176
177   if (OverrideStr[0] == '#') {
178     ++OverrideStr;
179     OS = &llvm::nulls();
180   }
181
182   *OS << "### CCC_OVERRIDE_OPTIONS: " << OverrideStr << "\n";
183
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)
192       ApplyOneQAOverride(*OS, Args, std::string(S, End), SavedStrings);
193     S = End;
194     if (*S != '\0')
195       ++S;
196   }
197 }
198
199 extern int cc1_main(ArrayRef<const char *> Argv, const char *Argv0,
200                     void *MainAddr);
201 extern int cc1as_main(ArrayRef<const char *> Argv, const char *Argv0,
202                       void *MainAddr);
203
204 struct DriverSuffix {
205   const char *Suffix;
206   const char *ModeFlag;
207 };
208
209 static 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++"},
226   };
227
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
234 static void ParseProgName(SmallVectorImpl<const char *> &ArgVector,
235                           std::set<std::string> &SavedStrings) {
236   // Try to infer frontend type and default target from the program name by
237   // comparing it against DriverSuffixes in order.
238
239   // If there is a match, the function tries to identify a target as prefix.
240   // E.g. "x86_64-linux-clang" as interpreted as suffix "clang" with target
241   // prefix "x86_64-linux". If such a target prefix is found, is gets added via
242   // -target as implicit first argument.
243
244   std::string ProgName =llvm::sys::path::stem(ArgVector[0]);
245 #ifdef LLVM_ON_WIN32
246   // Transform to lowercase for case insensitive file systems.
247   ProgName = StringRef(ProgName).lower();
248 #endif
249
250   StringRef ProgNameRef = ProgName;
251   const DriverSuffix *DS = FindDriverSuffix(ProgNameRef);
252
253   if (!DS) {
254     // Try again after stripping any trailing version number:
255     // clang++3.5 -> clang++
256     ProgNameRef = ProgNameRef.rtrim("0123456789.");
257     DS = FindDriverSuffix(ProgNameRef);
258   }
259
260   if (!DS) {
261     // Try again after stripping trailing -component.
262     // clang++-tot -> clang++
263     ProgNameRef = ProgNameRef.slice(0, ProgNameRef.rfind('-'));
264     DS = FindDriverSuffix(ProgNameRef);
265   }
266
267   if (DS) {
268     if (const char *Flag = DS->ModeFlag) {
269       // Add Flag to the arguments.
270       auto it = ArgVector.begin();
271       if (it != ArgVector.end())
272         ++it;
273       ArgVector.insert(it, Flag);
274     }
275
276     StringRef::size_type LastComponent = ProgNameRef.rfind(
277         '-', ProgNameRef.size() - strlen(DS->Suffix));
278     if (LastComponent == StringRef::npos)
279       return;
280
281     // Infer target from the prefix.
282     StringRef Prefix = ProgNameRef.slice(0, LastComponent);
283     std::string IgnoredError;
284     if (llvm::TargetRegistry::lookupTarget(Prefix, IgnoredError)) {
285       auto it = ArgVector.begin();
286       if (it != ArgVector.end())
287         ++it;
288       const char *arr[] = { "-target", GetStableCStr(SavedStrings, Prefix) };
289       ArgVector.insert(it, std::begin(arr), std::end(arr));
290     }
291   }
292 }
293
294 static void SetBackdoorDriverOutputsFromEnvVars(Driver &TheDriver) {
295   // Handle CC_PRINT_OPTIONS and CC_PRINT_OPTIONS_FILE.
296   TheDriver.CCPrintOptions = !!::getenv("CC_PRINT_OPTIONS");
297   if (TheDriver.CCPrintOptions)
298     TheDriver.CCPrintOptionsFilename = ::getenv("CC_PRINT_OPTIONS_FILE");
299
300   // Handle CC_PRINT_HEADERS and CC_PRINT_HEADERS_FILE.
301   TheDriver.CCPrintHeaders = !!::getenv("CC_PRINT_HEADERS");
302   if (TheDriver.CCPrintHeaders)
303     TheDriver.CCPrintHeadersFilename = ::getenv("CC_PRINT_HEADERS_FILE");
304
305   // Handle CC_LOG_DIAGNOSTICS and CC_LOG_DIAGNOSTICS_FILE.
306   TheDriver.CCLogDiagnostics = !!::getenv("CC_LOG_DIAGNOSTICS");
307   if (TheDriver.CCLogDiagnostics)
308     TheDriver.CCLogDiagnosticsFilename = ::getenv("CC_LOG_DIAGNOSTICS_FILE");
309 }
310
311 static void FixupDiagPrefixExeName(TextDiagnosticPrinter *DiagClient,
312                                    const std::string &Path) {
313   // If the clang binary happens to be named cl.exe for compatibility reasons,
314   // use clang-cl.exe as the prefix to avoid confusion between clang and MSVC.
315   StringRef ExeBasename(llvm::sys::path::filename(Path));
316   if (ExeBasename.equals_lower("cl.exe"))
317     ExeBasename = "clang-cl.exe";
318   DiagClient->setPrefix(ExeBasename);
319 }
320
321 // This lets us create the DiagnosticsEngine with a properly-filled-out
322 // DiagnosticOptions instance.
323 static DiagnosticOptions *
324 CreateAndPopulateDiagOpts(ArrayRef<const char *> argv) {
325   auto *DiagOpts = new DiagnosticOptions;
326   std::unique_ptr<OptTable> Opts(createDriverOptTable());
327   unsigned MissingArgIndex, MissingArgCount;
328   InputArgList Args =
329       Opts->ParseArgs(argv.slice(1), MissingArgIndex, MissingArgCount);
330   // We ignore MissingArgCount and the return value of ParseDiagnosticArgs.
331   // Any errors that would be diagnosed here will also be diagnosed later,
332   // when the DiagnosticsEngine actually exists.
333   (void)ParseDiagnosticArgs(*DiagOpts, Args);
334   return DiagOpts;
335 }
336
337 static void SetInstallDir(SmallVectorImpl<const char *> &argv,
338                           Driver &TheDriver) {
339   // Attempt to find the original path used to invoke the driver, to determine
340   // the installed path. We do this manually, because we want to support that
341   // path being a symlink.
342   SmallString<128> InstalledPath(argv[0]);
343
344   // Do a PATH lookup, if there are no directory components.
345   if (llvm::sys::path::filename(InstalledPath) == InstalledPath)
346     if (llvm::ErrorOr<std::string> Tmp = llvm::sys::findProgramByName(
347             llvm::sys::path::filename(InstalledPath.str())))
348       InstalledPath = *Tmp;
349   llvm::sys::fs::make_absolute(InstalledPath);
350   InstalledPath = llvm::sys::path::parent_path(InstalledPath);
351   if (llvm::sys::fs::exists(InstalledPath.c_str()))
352     TheDriver.setInstalledDir(InstalledPath);
353 }
354
355 static int ExecuteCC1Tool(ArrayRef<const char *> argv, StringRef Tool) {
356   void *GetExecutablePathVP = (void *)(intptr_t) GetExecutablePath;
357   if (Tool == "")
358     return cc1_main(argv.slice(2), argv[0], GetExecutablePathVP);
359   if (Tool == "as")
360     return cc1as_main(argv.slice(2), argv[0], GetExecutablePathVP);
361
362   // Reject unknown tools.
363   llvm::errs() << "error: unknown integrated tool '" << Tool << "'\n";
364   return 1;
365 }
366
367 int main(int argc_, const char **argv_) {
368   llvm::sys::PrintStackTraceOnErrorSignal();
369   llvm::PrettyStackTraceProgram X(argc_, argv_);
370
371   if (llvm::sys::Process::FixupStandardFileDescriptors())
372     return 1;
373
374   SmallVector<const char *, 256> argv;
375   llvm::SpecificBumpPtrAllocator<char> ArgAllocator;
376   std::error_code EC = llvm::sys::Process::GetArgumentVector(
377       argv, llvm::makeArrayRef(argv_, argc_), ArgAllocator);
378   if (EC) {
379     llvm::errs() << "error: couldn't get arguments: " << EC.message() << '\n';
380     return 1;
381   }
382
383   llvm::BumpPtrAllocator A;
384   llvm::BumpPtrStringSaver Saver(A);
385
386   // Determines whether we want nullptr markers in argv to indicate response
387   // files end-of-lines. We only use this for the /LINK driver argument.
388   bool MarkEOLs = true;
389   if (argv.size() > 1 && StringRef(argv[1]).startswith("-cc1"))
390     MarkEOLs = false;
391   llvm::cl::ExpandResponseFiles(Saver, llvm::cl::TokenizeGNUCommandLine, argv,
392                                 MarkEOLs);
393
394   // Handle -cc1 integrated tools, even if -cc1 was expanded from a response
395   // file.
396   auto FirstArg = std::find_if(argv.begin() + 1, argv.end(),
397                                [](const char *A) { return A != nullptr; });
398   if (FirstArg != argv.end() && StringRef(*FirstArg).startswith("-cc1")) {
399     // If -cc1 came from a response file, remove the EOL sentinels.
400     if (MarkEOLs) {
401       auto newEnd = std::remove(argv.begin(), argv.end(), nullptr);
402       argv.resize(newEnd - argv.begin());
403     }
404     return ExecuteCC1Tool(argv, argv[1] + 4);
405   }
406
407   bool CanonicalPrefixes = true;
408   for (int i = 1, size = argv.size(); i < size; ++i) {
409     // Skip end-of-line response file markers
410     if (argv[i] == nullptr)
411       continue;
412     if (StringRef(argv[i]) == "-no-canonical-prefixes") {
413       CanonicalPrefixes = false;
414       break;
415     }
416   }
417
418   std::set<std::string> SavedStrings;
419   // Handle CCC_OVERRIDE_OPTIONS, used for editing a command line behind the
420   // scenes.
421   if (const char *OverrideStr = ::getenv("CCC_OVERRIDE_OPTIONS")) {
422     // FIXME: Driver shouldn't take extra initial argument.
423     ApplyQAOverride(argv, OverrideStr, SavedStrings);
424   }
425
426   std::string Path = GetExecutablePath(argv[0], CanonicalPrefixes);
427
428   IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts =
429       CreateAndPopulateDiagOpts(argv);
430
431   TextDiagnosticPrinter *DiagClient
432     = new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts);
433   FixupDiagPrefixExeName(DiagClient, Path);
434
435   IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
436
437   DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagClient);
438
439   if (!DiagOpts->DiagnosticSerializationFile.empty()) {
440     auto SerializedConsumer =
441         clang::serialized_diags::create(DiagOpts->DiagnosticSerializationFile,
442                                         &*DiagOpts, /*MergeChildRecords=*/true);
443     Diags.setClient(new ChainedDiagnosticConsumer(
444         Diags.takeClient(), std::move(SerializedConsumer)));
445   }
446
447   ProcessWarningOptions(Diags, *DiagOpts, /*ReportDiags=*/false);
448
449   Driver TheDriver(Path, llvm::sys::getDefaultTargetTriple(), Diags);
450   SetInstallDir(argv, TheDriver);
451
452   llvm::InitializeAllTargets();
453   ParseProgName(argv, SavedStrings);
454
455   SetBackdoorDriverOutputsFromEnvVars(TheDriver);
456
457   std::unique_ptr<Compilation> C(TheDriver.BuildCompilation(argv));
458   int Res = 0;
459   SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
460   if (C.get())
461     Res = TheDriver.ExecuteCompilation(*C, FailingCommands);
462
463   // Force a crash to test the diagnostics.
464   if (::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH")) {
465     Diags.Report(diag::err_drv_force_crash) << "FORCE_CLANG_DIAGNOSTICS_CRASH";
466
467     // Pretend that every command failed.
468     FailingCommands.clear();
469     for (const auto &J : C->getJobs())
470       if (const Command *C = dyn_cast<Command>(&J))
471         FailingCommands.push_back(std::make_pair(-1, C));
472   }
473
474   for (const auto &P : FailingCommands) {
475     int CommandRes = P.first;
476     const Command *FailingCommand = P.second;
477     if (!Res)
478       Res = CommandRes;
479
480     // If result status is < 0, then the driver command signalled an error.
481     // If result status is 70, then the driver command reported a fatal error.
482     // On Windows, abort will return an exit code of 3.  In these cases,
483     // generate additional diagnostic information if possible.
484     bool DiagnoseCrash = CommandRes < 0 || CommandRes == 70;
485 #ifdef LLVM_ON_WIN32
486     DiagnoseCrash |= CommandRes == 3;
487 #endif
488     if (DiagnoseCrash) {
489       TheDriver.generateCompilationDiagnostics(*C, *FailingCommand);
490       break;
491     }
492   }
493
494   Diags.getClient()->finish();
495
496   // 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
500   llvm::llvm_shutdown();
501
502 #ifdef LLVM_ON_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
510   // If we have multiple failing commands, we return the result of the first
511   // failing command.
512   return Res;
513 }