Coverage Report

Created: 2019-02-15 18:59

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