Coverage Report

Created: 2018-11-16 02:38

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/clang/tools/driver/driver.cpp
Line
Count
Source (jump to first uncovered line)
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/Driver/Driver.h"
16
#include "clang/Basic/DiagnosticOptions.h"
17
#include "clang/Driver/Compilation.h"
18
#include "clang/Driver/DriverDiagnostic.h"
19
#include "clang/Driver/Options.h"
20
#include "clang/Driver/ToolChain.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/SmallString.h"
28
#include "llvm/ADT/SmallVector.h"
29
#include "llvm/Option/ArgList.h"
30
#include "llvm/Option/OptTable.h"
31
#include "llvm/Option/Option.h"
32
#include "llvm/Support/CommandLine.h"
33
#include "llvm/Support/ErrorHandling.h"
34
#include "llvm/Support/FileSystem.h"
35
#include "llvm/Support/Host.h"
36
#include "llvm/Support/InitLLVM.h"
37
#include "llvm/Support/Path.h"
38
#include "llvm/Support/Process.h"
39
#include "llvm/Support/Program.h"
40
#include "llvm/Support/Regex.h"
41
#include "llvm/Support/Signals.h"
42
#include "llvm/Support/StringSaver.h"
43
#include "llvm/Support/TargetSelect.h"
44
#include "llvm/Support/Timer.h"
45
#include "llvm/Support/raw_ostream.h"
46
#include <memory>
47
#include <set>
48
#include <system_error>
49
using namespace clang;
50
using namespace clang::driver;
51
using namespace llvm::opt;
52
53
21.5k
std::string GetExecutablePath(const char *Argv0, bool CanonicalPrefixes) {
54
21.5k
  if (!CanonicalPrefixes) {
55
829
    SmallString<128> ExecutablePath(Argv0);
56
829
    // Do a PATH lookup if Argv0 isn't a valid path.
57
829
    if (!llvm::sys::fs::exists(ExecutablePath))
58
0
      if (llvm::ErrorOr<std::string> P =
59
0
              llvm::sys::findProgramByName(ExecutablePath))
60
0
        ExecutablePath = *P;
61
829
    return ExecutablePath.str();
62
829
  }
63
20.7k
64
20.7k
  // This just needs to be some symbol in the binary; C++ doesn't
65
20.7k
  // allow taking the address of ::main however.
66
20.7k
  void *P = (void*) (intptr_t) GetExecutablePath;
67
20.7k
  return llvm::sys::fs::getMainExecutable(Argv0, P);
68
20.7k
}
69
70
static const char *GetStableCStr(std::set<std::string> &SavedStrings,
71
7.46k
                                 StringRef S) {
72
7.46k
  return SavedStrings.insert(S).first->c_str();
73
7.46k
}
74
75
/// ApplyQAOverride - Apply a list of edits to the input argument lists.
76
///
77
/// The input string is a space separate list of edits to perform,
78
/// they are applied in order to the input argument lists. Edits
79
/// should be one of the following forms:
80
///
81
///  '#': Silence information about the changes to the command line arguments.
82
///
83
///  '^': Add FOO as a new argument at the beginning of the command line.
84
///
85
///  '+': Add FOO as a new argument at the end of the command line.
86
///
87
///  's/XXX/YYY/': Substitute the regular expression XXX with YYY in the command
88
///  line.
89
///
90
///  'xOPTION': Removes all instances of the literal argument OPTION.
91
///
92
///  'XOPTION': Removes all instances of the literal argument OPTION,
93
///  and the following argument.
94
///
95
///  'Ox': Removes all flags matching 'O' or 'O[sz0-9]' and adds 'Ox'
96
///  at the end of the command line.
97
///
98
/// \param OS - The stream to write edit information to.
99
/// \param Args - The vector of command line arguments.
100
/// \param Edit - The override command to perform.
101
/// \param SavedStrings - Set to use for storing string representations.
102
static void ApplyOneQAOverride(raw_ostream &OS,
103
                               SmallVectorImpl<const char*> &Args,
104
                               StringRef Edit,
105
14
                               std::set<std::string> &SavedStrings) {
106
14
  // This does not need to be efficient.
107
14
108
14
  if (Edit[0] == '^') {
109
1
    const char *Str =
110
1
      GetStableCStr(SavedStrings, Edit.substr(1));
111
1
    OS << "### Adding argument " << Str << " at beginning\n";
112
1
    Args.insert(Args.begin() + 1, Str);
113
13
  } else if (Edit[0] == '+') {
114
9
    const char *Str =
115
9
      GetStableCStr(SavedStrings, Edit.substr(1));
116
9
    OS << "### Adding argument " << Str << " at end\n";
117
9
    Args.push_back(Str);
118
9
  } else 
if (4
Edit[0] == 's'4
&&
Edit[1] == '/'0
&&
Edit.endswith("/")0
&&
119
4
             
Edit.slice(2, Edit.size()-1).find('/') != StringRef::npos0
) {
120
0
    StringRef MatchPattern = Edit.substr(2).split('/').first;
121
0
    StringRef ReplPattern = Edit.substr(2).split('/').second;
122
0
    ReplPattern = ReplPattern.slice(0, ReplPattern.size()-1);
123
0
124
0
    for (unsigned i = 1, e = Args.size(); i != e; ++i) {
125
0
      // Ignore end-of-line response file markers
126
0
      if (Args[i] == nullptr)
127
0
        continue;
128
0
      std::string Repl = llvm::Regex(MatchPattern).sub(ReplPattern, Args[i]);
129
0
130
0
      if (Repl != Args[i]) {
131
0
        OS << "### Replacing '" << Args[i] << "' with '" << Repl << "'\n";
132
0
        Args[i] = GetStableCStr(SavedStrings, Repl);
133
0
      }
134
0
    }
135
4
  } else if (Edit[0] == 'x' || 
Edit[0] == 'X'2
) {
136
3
    auto Option = Edit.substr(1);
137
34
    for (unsigned i = 1; i < Args.size();) {
138
31
      if (Option == Args[i]) {
139
4
        OS << "### Deleting argument " << Args[i] << '\n';
140
4
        Args.erase(Args.begin() + i);
141
4
        if (Edit[0] == 'X') {
142
1
          if (i < Args.size()) {
143
1
            OS << "### Deleting argument " << Args[i] << '\n';
144
1
            Args.erase(Args.begin() + i);
145
1
          } else
146
0
            OS << "### Invalid X edit, end of command line!\n";
147
1
        }
148
4
      } else
149
27
        ++i;
150
31
    }
151
3
  } else 
if (1
Edit[0] == 'O'1
) {
152
11
    for (unsigned i = 1; i < Args.size();) {
153
10
      const char *A = Args[i];
154
10
      // Ignore end-of-line response file markers
155
10
      if (A == nullptr)
156
0
        continue;
157
10
      if (A[0] == '-' && 
A[1] == 'O'8
&&
158
10
          
(7
A[2] == '\0'7
||
159
7
           
(6
A[3] == '\0'6
&&
(5
A[2] == 's'5
||
A[2] == 'z'4
||
160
6
                             
(3
'0' <= A[2]3
&&
A[2] <= '9'3
))))) {
161
6
        OS << "### Deleting argument " << Args[i] << '\n';
162
6
        Args.erase(Args.begin() + i);
163
6
      } else
164
4
        ++i;
165
10
    }
166
1
    OS << "### Adding argument " << Edit << " at end\n";
167
1
    Args.push_back(GetStableCStr(SavedStrings, '-' + Edit.str()));
168
1
  } else {
169
0
    OS << "### Unrecognized edit: " << Edit << "\n";
170
0
  }
171
14
}
172
173
/// ApplyQAOverride - Apply a comma separate list of edits to the
174
/// input argument lists. See ApplyOneQAOverride.
175
static void ApplyQAOverride(SmallVectorImpl<const char*> &Args,
176
                            const char *OverrideStr,
177
2
                            std::set<std::string> &SavedStrings) {
178
2
  raw_ostream *OS = &llvm::errs();
179
2
180
2
  if (OverrideStr[0] == '#') {
181
1
    ++OverrideStr;
182
1
    OS = &llvm::nulls();
183
1
  }
184
2
185
2
  *OS << "### CCC_OVERRIDE_OPTIONS: " << OverrideStr << "\n";
186
2
187
2
  // This does not need to be efficient.
188
2
189
2
  const char *S = OverrideStr;
190
17
  while (*S) {
191
15
    const char *End = ::strchr(S, ' ');
192
15
    if (!End)
193
1
      End = S + strlen(S);
194
15
    if (End != S)
195
14
      ApplyOneQAOverride(*OS, Args, std::string(S, End), SavedStrings);
196
15
    S = End;
197
15
    if (*S != '\0')
198
14
      ++S;
199
15
  }
200
2
}
201
202
extern int cc1_main(ArrayRef<const char *> Argv, const char *Argv0,
203
                    void *MainAddr);
204
extern int cc1as_main(ArrayRef<const char *> Argv, const char *Argv0,
205
                      void *MainAddr);
206
extern int cc1gen_reproducer_main(ArrayRef<const char *> Argv,
207
                                  const char *Argv0, void *MainAddr);
208
209
static void insertTargetAndModeArgs(const ParsedClangName &NameParts,
210
                                    SmallVectorImpl<const char *> &ArgVector,
211
21.5k
                                    std::set<std::string> &SavedStrings) {
212
21.5k
  // Put target and mode arguments at the start of argument list so that
213
21.5k
  // arguments specified in command line could override them. Avoid putting
214
21.5k
  // them at index 0, as an option like '-cc1' must remain the first.
215
21.5k
  int InsertionPoint = 0;
216
21.5k
  if (ArgVector.size() > 0)
217
21.5k
    ++InsertionPoint;
218
21.5k
219
21.5k
  if (NameParts.DriverMode) {
220
7.44k
    // Add the mode flag to the arguments.
221
7.44k
    ArgVector.insert(ArgVector.begin() + InsertionPoint,
222
7.44k
                     GetStableCStr(SavedStrings, NameParts.DriverMode));
223
7.44k
  }
224
21.5k
225
21.5k
  if (NameParts.TargetIsValid) {
226
10
    const char *arr[] = {"-target", GetStableCStr(SavedStrings,
227
10
                                                  NameParts.TargetPrefix)};
228
10
    ArgVector.insert(ArgVector.begin() + InsertionPoint,
229
10
                     std::begin(arr), std::end(arr));
230
10
  }
231
21.5k
}
232
233
static void getCLEnvVarOptions(std::string &EnvValue, llvm::StringSaver &Saver,
234
3
                               SmallVectorImpl<const char *> &Opts) {
235
3
  llvm::cl::TokenizeWindowsCommandLine(EnvValue, Saver, Opts);
236
3
  // The first instance of '#' should be replaced with '=' in each option.
237
3
  for (const char *Opt : Opts)
238
5
    if (char *NumberSignPtr = const_cast<char *>(::strchr(Opt, '#')))
239
0
      *NumberSignPtr = '=';
240
3
}
241
242
21.5k
static void SetBackdoorDriverOutputsFromEnvVars(Driver &TheDriver) {
243
21.5k
  // Handle CC_PRINT_OPTIONS and CC_PRINT_OPTIONS_FILE.
244
21.5k
  TheDriver.CCPrintOptions = !!::getenv("CC_PRINT_OPTIONS");
245
21.5k
  if (TheDriver.CCPrintOptions)
246
1
    TheDriver.CCPrintOptionsFilename = ::getenv("CC_PRINT_OPTIONS_FILE");
247
21.5k
248
21.5k
  // Handle CC_PRINT_HEADERS and CC_PRINT_HEADERS_FILE.
249
21.5k
  TheDriver.CCPrintHeaders = !!::getenv("CC_PRINT_HEADERS");
250
21.5k
  if (TheDriver.CCPrintHeaders)
251
1
    TheDriver.CCPrintHeadersFilename = ::getenv("CC_PRINT_HEADERS_FILE");
252
21.5k
253
21.5k
  // Handle CC_LOG_DIAGNOSTICS and CC_LOG_DIAGNOSTICS_FILE.
254
21.5k
  TheDriver.CCLogDiagnostics = !!::getenv("CC_LOG_DIAGNOSTICS");
255
21.5k
  if (TheDriver.CCLogDiagnostics)
256
3
    TheDriver.CCLogDiagnosticsFilename = ::getenv("CC_LOG_DIAGNOSTICS_FILE");
257
21.5k
}
258
259
static void FixupDiagPrefixExeName(TextDiagnosticPrinter *DiagClient,
260
21.5k
                                   const std::string &Path) {
261
21.5k
  // If the clang binary happens to be named cl.exe for compatibility reasons,
262
21.5k
  // use clang-cl.exe as the prefix to avoid confusion between clang and MSVC.
263
21.5k
  StringRef ExeBasename(llvm::sys::path::stem(Path));
264
21.5k
  if (ExeBasename.equals_lower("cl"))
265
0
    ExeBasename = "clang-cl";
266
21.5k
  DiagClient->setPrefix(ExeBasename);
267
21.5k
}
268
269
// This lets us create the DiagnosticsEngine with a properly-filled-out
270
// DiagnosticOptions instance.
271
static DiagnosticOptions *
272
21.5k
CreateAndPopulateDiagOpts(ArrayRef<const char *> argv) {
273
21.5k
  auto *DiagOpts = new DiagnosticOptions;
274
21.5k
  std::unique_ptr<OptTable> Opts(createDriverOptTable());
275
21.5k
  unsigned MissingArgIndex, MissingArgCount;
276
21.5k
  InputArgList Args =
277
21.5k
      Opts->ParseArgs(argv.slice(1), MissingArgIndex, MissingArgCount);
278
21.5k
  // We ignore MissingArgCount and the return value of ParseDiagnosticArgs.
279
21.5k
  // Any errors that would be diagnosed here will also be diagnosed later,
280
21.5k
  // when the DiagnosticsEngine actually exists.
281
21.5k
  (void)ParseDiagnosticArgs(*DiagOpts, Args);
282
21.5k
  return DiagOpts;
283
21.5k
}
284
285
static void SetInstallDir(SmallVectorImpl<const char *> &argv,
286
21.5k
                          Driver &TheDriver, bool CanonicalPrefixes) {
287
21.5k
  // Attempt to find the original path used to invoke the driver, to determine
288
21.5k
  // the installed path. We do this manually, because we want to support that
289
21.5k
  // path being a symlink.
290
21.5k
  SmallString<128> InstalledPath(argv[0]);
291
21.5k
292
21.5k
  // Do a PATH lookup, if there are no directory components.
293
21.5k
  if (llvm::sys::path::filename(InstalledPath) == InstalledPath)
294
0
    if (llvm::ErrorOr<std::string> Tmp = llvm::sys::findProgramByName(
295
0
            llvm::sys::path::filename(InstalledPath.str())))
296
0
      InstalledPath = *Tmp;
297
21.5k
298
21.5k
  // FIXME: We don't actually canonicalize this, we just make it absolute.
299
21.5k
  if (CanonicalPrefixes)
300
20.7k
    llvm::sys::fs::make_absolute(InstalledPath);
301
21.5k
302
21.5k
  StringRef InstalledPathParent(llvm::sys::path::parent_path(InstalledPath));
303
21.5k
  if (llvm::sys::fs::exists(InstalledPathParent))
304
21.5k
    TheDriver.setInstalledDir(InstalledPathParent);
305
21.5k
}
306
307
36.5k
static int ExecuteCC1Tool(ArrayRef<const char *> argv, StringRef Tool) {
308
36.5k
  void *GetExecutablePathVP = (void *)(intptr_t) GetExecutablePath;
309
36.5k
  if (Tool == "")
310
35.8k
    return cc1_main(argv.slice(2), argv[0], GetExecutablePathVP);
311
772
  if (Tool == "as")
312
768
    return cc1as_main(argv.slice(2), argv[0], GetExecutablePathVP);
313
4
  if (Tool == "gen-reproducer")
314
3
    return cc1gen_reproducer_main(argv.slice(2), argv[0], GetExecutablePathVP);
315
1
316
1
  // Reject unknown tools.
317
1
  llvm::errs() << "error: unknown integrated tool '" << Tool << "'. "
318
1
               << "Valid tools include '-cc1' and '-cc1as'.\n";
319
1
  return 1;
320
1
}
321
322
58.1k
int main(int argc_, const char **argv_) {
323
58.1k
  llvm::InitLLVM X(argc_, argv_);
324
58.1k
  SmallVector<const char *, 256> argv(argv_, argv_ + argc_);
325
58.1k
326
58.1k
  if (llvm::sys::Process::FixupStandardFileDescriptors())
327
0
    return 1;
328
58.1k
329
58.1k
  llvm::InitializeAllTargets();
330
58.1k
  auto TargetAndMode = ToolChain::getTargetAndModeFromProgramName(argv[0]);
331
58.1k
332
58.1k
  llvm::BumpPtrAllocator A;
333
58.1k
  llvm::StringSaver Saver(A);
334
58.1k
335
58.1k
  // Parse response files using the GNU syntax, unless we're in CL mode. There
336
58.1k
  // are two ways to put clang in CL compatibility mode: argv[0] is either
337
58.1k
  // clang-cl or cl, or --driver-mode=cl is on the command line. The normal
338
58.1k
  // command line parsing can't happen until after response file parsing, so we
339
58.1k
  // have to manually search for a --driver-mode=cl argument the hard way.
340
58.1k
  // Finally, our -cc1 tools don't care which tokenization mode we use because
341
58.1k
  // response files written by clang will tokenize the same way in either mode.
342
58.1k
  bool ClangCLMode = false;
343
58.1k
  if (StringRef(TargetAndMode.DriverMode).equals("--driver-mode=cl") ||
344
1.90M
      
std::find_if(argv.begin(), argv.end(), [](const char *F) 58.1k
{
345
1.90M
        return F && strcmp(F, "--driver-mode=cl") == 0;
346
1.90M
      }) != argv.end()) {
347
475
    ClangCLMode = true;
348
475
  }
349
58.1k
  enum { Default, POSIX, Windows } RSPQuoting = Default;
350
1.90M
  for (const char *F : argv) {
351
1.90M
    if (strcmp(F, "--rsp-quoting=posix") == 0)
352
0
      RSPQuoting = POSIX;
353
1.90M
    else if (strcmp(F, "--rsp-quoting=windows") == 0)
354
2
      RSPQuoting = Windows;
355
1.90M
  }
356
58.1k
357
58.1k
  // Determines whether we want nullptr markers in argv to indicate response
358
58.1k
  // files end-of-lines. We only use this for the /LINK driver argument with
359
58.1k
  // clang-cl.exe on Windows.
360
58.1k
  bool MarkEOLs = ClangCLMode;
361
58.1k
362
58.1k
  llvm::cl::TokenizerCallback Tokenizer;
363
58.1k
  if (RSPQuoting == Windows || 
(58.1k
RSPQuoting == Default58.1k
&&
ClangCLMode58.1k
))
364
477
    Tokenizer = &llvm::cl::TokenizeWindowsCommandLine;
365
57.6k
  else
366
57.6k
    Tokenizer = &llvm::cl::TokenizeGNUCommandLine;
367
58.1k
368
58.1k
  if (MarkEOLs && 
argv.size() > 1475
&&
StringRef(argv[1]).startswith("-cc1")475
)
369
0
    MarkEOLs = false;
370
58.1k
  llvm::cl::ExpandResponseFiles(Saver, Tokenizer, argv, MarkEOLs);
371
58.1k
372
58.1k
  // Handle -cc1 integrated tools, even if -cc1 was expanded from a response
373
58.1k
  // file.
374
58.1k
  auto FirstArg = std::find_if(argv.begin() + 1, argv.end(),
375
58.1k
                               [](const char *A) { return A != nullptr; });
376
58.1k
  if (FirstArg != argv.end() && StringRef(*FirstArg).startswith("-cc1")) {
377
36.5k
    // If -cc1 came from a response file, remove the EOL sentinels.
378
36.5k
    if (MarkEOLs) {
379
0
      auto newEnd = std::remove(argv.begin(), argv.end(), nullptr);
380
0
      argv.resize(newEnd - argv.begin());
381
0
    }
382
36.5k
    return ExecuteCC1Tool(argv, argv[1] + 4);
383
36.5k
  }
384
21.5k
385
21.5k
  bool CanonicalPrefixes = true;
386
727k
  for (int i = 1, size = argv.size(); i < size; 
++i706k
) {
387
706k
    // Skip end-of-line response file markers
388
706k
    if (argv[i] == nullptr)
389
4
      continue;
390
706k
    if (StringRef(argv[i]) == "-no-canonical-prefixes") {
391
829
      CanonicalPrefixes = false;
392
829
      break;
393
829
    }
394
706k
  }
395
21.5k
396
21.5k
  // Handle CL and _CL_ which permits additional command line options to be
397
21.5k
  // prepended or appended.
398
21.5k
  if (ClangCLMode) {
399
475
    // Arguments in "CL" are prepended.
400
475
    llvm::Optional<std::string> OptCL = llvm::sys::Process::GetEnv("CL");
401
475
    if (OptCL.hasValue()) {
402
2
      SmallVector<const char *, 8> PrependedOpts;
403
2
      getCLEnvVarOptions(OptCL.getValue(), Saver, PrependedOpts);
404
2
405
2
      // Insert right after the program name to prepend to the argument list.
406
2
      argv.insert(argv.begin() + 1, PrependedOpts.begin(), PrependedOpts.end());
407
2
    }
408
475
    // Arguments in "_CL_" are appended.
409
475
    llvm::Optional<std::string> Opt_CL_ = llvm::sys::Process::GetEnv("_CL_");
410
475
    if (Opt_CL_.hasValue()) {
411
1
      SmallVector<const char *, 8> AppendedOpts;
412
1
      getCLEnvVarOptions(Opt_CL_.getValue(), Saver, AppendedOpts);
413
1
414
1
      // Insert at the end of the argument list to append.
415
1
      argv.append(AppendedOpts.begin(), AppendedOpts.end());
416
1
    }
417
475
  }
418
21.5k
419
21.5k
  std::set<std::string> SavedStrings;
420
21.5k
  // Handle CCC_OVERRIDE_OPTIONS, used for editing a command line behind the
421
21.5k
  // scenes.
422
21.5k
  if (const char *OverrideStr = ::getenv("CCC_OVERRIDE_OPTIONS")) {
423
2
    // FIXME: Driver shouldn't take extra initial argument.
424
2
    ApplyQAOverride(argv, OverrideStr, SavedStrings);
425
2
  }
426
21.5k
427
21.5k
  std::string Path = GetExecutablePath(argv[0], CanonicalPrefixes);
428
21.5k
429
21.5k
  IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts =
430
21.5k
      CreateAndPopulateDiagOpts(argv);
431
21.5k
432
21.5k
  TextDiagnosticPrinter *DiagClient
433
21.5k
    = new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts);
434
21.5k
  FixupDiagPrefixExeName(DiagClient, Path);
435
21.5k
436
21.5k
  IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
437
21.5k
438
21.5k
  DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagClient);
439
21.5k
440
21.5k
  if (!DiagOpts->DiagnosticSerializationFile.empty()) {
441
11
    auto SerializedConsumer =
442
11
        clang::serialized_diags::create(DiagOpts->DiagnosticSerializationFile,
443
11
                                        &*DiagOpts, /*MergeChildRecords=*/true);
444
11
    Diags.setClient(new ChainedDiagnosticConsumer(
445
11
        Diags.takeClient(), std::move(SerializedConsumer)));
446
11
  }
447
21.5k
448
21.5k
  ProcessWarningOptions(Diags, *DiagOpts, /*ReportDiags=*/false);
449
21.5k
450
21.5k
  Driver TheDriver(Path, llvm::sys::getDefaultTargetTriple(), Diags);
451
21.5k
  SetInstallDir(argv, TheDriver, CanonicalPrefixes);
452
21.5k
  TheDriver.setTargetAndMode(TargetAndMode);
453
21.5k
454
21.5k
  insertTargetAndModeArgs(TargetAndMode, argv, SavedStrings);
455
21.5k
456
21.5k
  SetBackdoorDriverOutputsFromEnvVars(TheDriver);
457
21.5k
458
21.5k
  std::unique_ptr<Compilation> C(TheDriver.BuildCompilation(argv));
459
21.5k
  int Res = 1;
460
21.5k
  if (C && !C->containsError()) {
461
21.4k
    SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
462
21.4k
    Res = TheDriver.ExecuteCompilation(*C, FailingCommands);
463
21.4k
464
21.4k
    // Force a crash to test the diagnostics.
465
21.4k
    if (TheDriver.GenReproducer) {
466
14
      Diags.Report(diag::err_drv_force_crash)
467
14
        << !::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH");
468
14
469
14
      // Pretend that every command failed.
470
14
      FailingCommands.clear();
471
14
      for (const auto &J : C->getJobs())
472
14
        if (const Command *C = dyn_cast<Command>(&J))
473
14
          FailingCommands.push_back(std::make_pair(-1, C));
474
14
    }
475
21.4k
476
21.4k
    for (const auto &P : FailingCommands) {
477
197
      int CommandRes = P.first;
478
197
      const Command *FailingCommand = P.second;
479
197
      if (!Res)
480
196
        Res = CommandRes;
481
197
482
197
      // If result status is < 0, then the driver command signalled an error.
483
197
      // If result status is 70, then the driver command reported a fatal error.
484
197
      // On Windows, abort will return an exit code of 3.  In these cases,
485
197
      // generate additional diagnostic information if possible.
486
197
      bool DiagnoseCrash = CommandRes < 0 || 
CommandRes == 70177
;
487
#ifdef _WIN32
488
      DiagnoseCrash |= CommandRes == 3;
489
#endif
490
197
      if (DiagnoseCrash) {
491
20
        TheDriver.generateCompilationDiagnostics(*C, *FailingCommand);
492
20
        break;
493
20
      }
494
197
    }
495
21.4k
  }
496
21.5k
497
21.5k
  Diags.getClient()->finish();
498
21.5k
499
21.5k
  // If any timers were active but haven't been destroyed yet, print their
500
21.5k
  // results now.  This happens in -disable-free mode.
501
21.5k
  llvm::TimerGroup::printAll(llvm::errs());
502
21.5k
503
#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
511
21.5k
  // If we have multiple failing commands, we return the result of the first
512
21.5k
  // failing command.
513
21.5k
  return Res;
514
21.5k
}