Coverage Report

Created: 2019-07-24 05:18

/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
22.1k
std::string GetExecutablePath(const char *Argv0, bool CanonicalPrefixes) {
53
22.1k
  if (!CanonicalPrefixes) {
54
908
    SmallString<128> ExecutablePath(Argv0);
55
908
    // Do a PATH lookup if Argv0 isn't a valid path.
56
908
    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
908
    return ExecutablePath.str();
61
908
  }
62
21.2k
63
21.2k
  // This just needs to be some symbol in the binary; C++ doesn't
64
21.2k
  // allow taking the address of ::main however.
65
21.2k
  void *P = (void*) (intptr_t) GetExecutablePath;
66
21.2k
  return llvm::sys::fs::getMainExecutable(Argv0, P);
67
21.2k
}
68
69
static const char *GetStableCStr(std::set<std::string> &SavedStrings,
70
7.49k
                                 StringRef S) {
71
7.49k
  return SavedStrings.insert(S).first->c_str();
72
7.49k
}
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
22.1k
                                    std::set<std::string> &SavedStrings) {
211
22.1k
  // Put target and mode arguments at the start of argument list so that
212
22.1k
  // arguments specified in command line could override them. Avoid putting
213
22.1k
  // them at index 0, as an option like '-cc1' must remain the first.
214
22.1k
  int InsertionPoint = 0;
215
22.1k
  if (ArgVector.size() > 0)
216
22.1k
    ++InsertionPoint;
217
22.1k
218
22.1k
  if (NameParts.DriverMode) {
219
7.47k
    // Add the mode flag to the arguments.
220
7.47k
    ArgVector.insert(ArgVector.begin() + InsertionPoint,
221
7.47k
                     GetStableCStr(SavedStrings, NameParts.DriverMode));
222
7.47k
  }
223
22.1k
224
22.1k
  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
22.1k
}
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
22.1k
static void SetBackdoorDriverOutputsFromEnvVars(Driver &TheDriver) {
242
22.1k
  // Handle CC_PRINT_OPTIONS and CC_PRINT_OPTIONS_FILE.
243
22.1k
  TheDriver.CCPrintOptions = !!::getenv("CC_PRINT_OPTIONS");
244
22.1k
  if (TheDriver.CCPrintOptions)
245
1
    TheDriver.CCPrintOptionsFilename = ::getenv("CC_PRINT_OPTIONS_FILE");
246
22.1k
247
22.1k
  // Handle CC_PRINT_HEADERS and CC_PRINT_HEADERS_FILE.
248
22.1k
  TheDriver.CCPrintHeaders = !!::getenv("CC_PRINT_HEADERS");
249
22.1k
  if (TheDriver.CCPrintHeaders)
250
1
    TheDriver.CCPrintHeadersFilename = ::getenv("CC_PRINT_HEADERS_FILE");
251
22.1k
252
22.1k
  // Handle CC_LOG_DIAGNOSTICS and CC_LOG_DIAGNOSTICS_FILE.
253
22.1k
  TheDriver.CCLogDiagnostics = !!::getenv("CC_LOG_DIAGNOSTICS");
254
22.1k
  if (TheDriver.CCLogDiagnostics)
255
3
    TheDriver.CCLogDiagnosticsFilename = ::getenv("CC_LOG_DIAGNOSTICS_FILE");
256
22.1k
}
257
258
static void FixupDiagPrefixExeName(TextDiagnosticPrinter *DiagClient,
259
22.1k
                                   const std::string &Path) {
260
22.1k
  // If the clang binary happens to be named cl.exe for compatibility reasons,
261
22.1k
  // use clang-cl.exe as the prefix to avoid confusion between clang and MSVC.
262
22.1k
  StringRef ExeBasename(llvm::sys::path::stem(Path));
263
22.1k
  if (ExeBasename.equals_lower("cl"))
264
0
    ExeBasename = "clang-cl";
265
22.1k
  DiagClient->setPrefix(ExeBasename);
266
22.1k
}
267
268
// This lets us create the DiagnosticsEngine with a properly-filled-out
269
// DiagnosticOptions instance.
270
static DiagnosticOptions *
271
22.1k
CreateAndPopulateDiagOpts(ArrayRef<const char *> argv) {
272
22.1k
  auto *DiagOpts = new DiagnosticOptions;
273
22.1k
  std::unique_ptr<OptTable> Opts(createDriverOptTable());
274
22.1k
  unsigned MissingArgIndex, MissingArgCount;
275
22.1k
  InputArgList Args =
276
22.1k
      Opts->ParseArgs(argv.slice(1), MissingArgIndex, MissingArgCount);
277
22.1k
  // We ignore MissingArgCount and the return value of ParseDiagnosticArgs.
278
22.1k
  // Any errors that would be diagnosed here will also be diagnosed later,
279
22.1k
  // when the DiagnosticsEngine actually exists.
280
22.1k
  (void)ParseDiagnosticArgs(*DiagOpts, Args);
281
22.1k
  return DiagOpts;
282
22.1k
}
283
284
static void SetInstallDir(SmallVectorImpl<const char *> &argv,
285
22.1k
                          Driver &TheDriver, bool CanonicalPrefixes) {
286
22.1k
  // Attempt to find the original path used to invoke the driver, to determine
287
22.1k
  // the installed path. We do this manually, because we want to support that
288
22.1k
  // path being a symlink.
289
22.1k
  SmallString<128> InstalledPath(argv[0]);
290
22.1k
291
22.1k
  // Do a PATH lookup, if there are no directory components.
292
22.1k
  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
22.1k
297
22.1k
  // FIXME: We don't actually canonicalize this, we just make it absolute.
298
22.1k
  if (CanonicalPrefixes)
299
21.2k
    llvm::sys::fs::make_absolute(InstalledPath);
300
22.1k
301
22.1k
  StringRef InstalledPathParent(llvm::sys::path::parent_path(InstalledPath));
302
22.1k
  if (llvm::sys::fs::exists(InstalledPathParent))
303
22.1k
    TheDriver.setInstalledDir(InstalledPathParent);
304
22.1k
}
305
306
37.9k
static int ExecuteCC1Tool(ArrayRef<const char *> argv, StringRef Tool) {
307
37.9k
  void *GetExecutablePathVP = (void *)(intptr_t) GetExecutablePath;
308
37.9k
  if (Tool == "")
309
37.1k
    return cc1_main(argv.slice(2), argv[0], GetExecutablePathVP);
310
760
  if (Tool == "as")
311
756
    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
60.0k
int main(int argc_, const char **argv_) {
322
60.0k
  llvm::InitLLVM X(argc_, argv_);
323
60.0k
  SmallVector<const char *, 256> argv(argv_, argv_ + argc_);
324
60.0k
325
60.0k
  if (llvm::sys::Process::FixupStandardFileDescriptors())
326
0
    return 1;
327
60.0k
328
60.0k
  llvm::InitializeAllTargets();
329
60.0k
  auto TargetAndMode = ToolChain::getTargetAndModeFromProgramName(argv[0]);
330
60.0k
331
60.0k
  llvm::BumpPtrAllocator A;
332
60.0k
  llvm::StringSaver Saver(A);
333
60.0k
334
60.0k
  // Parse response files using the GNU syntax, unless we're in CL mode. There
335
60.0k
  // are two ways to put clang in CL compatibility mode: argv[0] is either
336
60.0k
  // clang-cl or cl, or --driver-mode=cl is on the command line. The normal
337
60.0k
  // command line parsing can't happen until after response file parsing, so we
338
60.0k
  // have to manually search for a --driver-mode=cl argument the hard way.
339
60.0k
  // Finally, our -cc1 tools don't care which tokenization mode we use because
340
60.0k
  // response files written by clang will tokenize the same way in either mode.
341
60.0k
  bool ClangCLMode = false;
342
60.0k
  if (StringRef(TargetAndMode.DriverMode).equals("--driver-mode=cl") ||
343
2.04M
      
llvm::find_if(argv, [](const char *F) 60.0k
{
344
2.04M
        return F && strcmp(F, "--driver-mode=cl") == 0;
345
2.04M
      }) != argv.end()) {
346
497
    ClangCLMode = true;
347
497
  }
348
60.0k
  enum { Default, POSIX, Windows } RSPQuoting = Default;
349
2.04M
  for (const char *F : argv) {
350
2.04M
    if (strcmp(F, "--rsp-quoting=posix") == 0)
351
0
      RSPQuoting = POSIX;
352
2.04M
    else if (strcmp(F, "--rsp-quoting=windows") == 0)
353
2
      RSPQuoting = Windows;
354
2.04M
  }
355
60.0k
356
60.0k
  // Determines whether we want nullptr markers in argv to indicate response
357
60.0k
  // files end-of-lines. We only use this for the /LINK driver argument with
358
60.0k
  // clang-cl.exe on Windows.
359
60.0k
  bool MarkEOLs = ClangCLMode;
360
60.0k
361
60.0k
  llvm::cl::TokenizerCallback Tokenizer;
362
60.0k
  if (RSPQuoting == Windows || 
(60.0k
RSPQuoting == Default60.0k
&&
ClangCLMode60.0k
))
363
499
    Tokenizer = &llvm::cl::TokenizeWindowsCommandLine;
364
59.5k
  else
365
59.5k
    Tokenizer = &llvm::cl::TokenizeGNUCommandLine;
366
60.0k
367
60.0k
  if (MarkEOLs && 
argv.size() > 1497
&&
StringRef(argv[1]).startswith("-cc1")497
)
368
0
    MarkEOLs = false;
369
60.0k
  llvm::cl::ExpandResponseFiles(Saver, Tokenizer, argv, MarkEOLs);
370
60.0k
371
60.0k
  // Handle -cc1 integrated tools, even if -cc1 was expanded from a response
372
60.0k
  // file.
373
60.0k
  auto FirstArg = std::find_if(argv.begin() + 1, argv.end(),
374
60.0k
                               [](const char *A) { return A != nullptr; });
375
60.0k
  if (FirstArg != argv.end() && StringRef(*FirstArg).startswith("-cc1")) {
376
37.9k
    // If -cc1 came from a response file, remove the EOL sentinels.
377
37.9k
    if (MarkEOLs) {
378
0
      auto newEnd = std::remove(argv.begin(), argv.end(), nullptr);
379
0
      argv.resize(newEnd - argv.begin());
380
0
    }
381
37.9k
    return ExecuteCC1Tool(argv, argv[1] + 4);
382
37.9k
  }
383
22.1k
384
22.1k
  bool CanonicalPrefixes = true;
385
738k
  for (int i = 1, size = argv.size(); i < size; 
++i716k
) {
386
717k
    // Skip end-of-line response file markers
387
717k
    if (argv[i] == nullptr)
388
4
      continue;
389
717k
    if (StringRef(argv[i]) == "-no-canonical-prefixes") {
390
908
      CanonicalPrefixes = false;
391
908
      break;
392
908
    }
393
717k
  }
394
22.1k
395
22.1k
  // Handle CL and _CL_ which permits additional command line options to be
396
22.1k
  // prepended or appended.
397
22.1k
  if (ClangCLMode) {
398
497
    // Arguments in "CL" are prepended.
399
497
    llvm::Optional<std::string> OptCL = llvm::sys::Process::GetEnv("CL");
400
497
    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
497
    // Arguments in "_CL_" are appended.
408
497
    llvm::Optional<std::string> Opt_CL_ = llvm::sys::Process::GetEnv("_CL_");
409
497
    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
497
  }
417
22.1k
418
22.1k
  std::set<std::string> SavedStrings;
419
22.1k
  // Handle CCC_OVERRIDE_OPTIONS, used for editing a command line behind the
420
22.1k
  // scenes.
421
22.1k
  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
22.1k
426
22.1k
  std::string Path = GetExecutablePath(argv[0], CanonicalPrefixes);
427
22.1k
428
22.1k
  IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts =
429
22.1k
      CreateAndPopulateDiagOpts(argv);
430
22.1k
431
22.1k
  TextDiagnosticPrinter *DiagClient
432
22.1k
    = new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts);
433
22.1k
  FixupDiagPrefixExeName(DiagClient, Path);
434
22.1k
435
22.1k
  IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
436
22.1k
437
22.1k
  DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagClient);
438
22.1k
439
22.1k
  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
22.1k
447
22.1k
  ProcessWarningOptions(Diags, *DiagOpts, /*ReportDiags=*/false);
448
22.1k
449
22.1k
  Driver TheDriver(Path, llvm::sys::getDefaultTargetTriple(), Diags);
450
22.1k
  SetInstallDir(argv, TheDriver, CanonicalPrefixes);
451
22.1k
  TheDriver.setTargetAndMode(TargetAndMode);
452
22.1k
453
22.1k
  insertTargetAndModeArgs(TargetAndMode, argv, SavedStrings);
454
22.1k
455
22.1k
  SetBackdoorDriverOutputsFromEnvVars(TheDriver);
456
22.1k
457
22.1k
  std::unique_ptr<Compilation> C(TheDriver.BuildCompilation(argv));
458
22.1k
  int Res = 1;
459
22.1k
  if (C && !C->containsError()) {
460
22.1k
    SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
461
22.1k
    Res = TheDriver.ExecuteCompilation(*C, FailingCommands);
462
22.1k
463
22.1k
    // Force a crash to test the diagnostics.
464
22.1k
    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
22.1k
475
22.1k
    for (const auto &P : FailingCommands) {
476
219
      int CommandRes = P.first;
477
219
      const Command *FailingCommand = P.second;
478
219
      if (!Res)
479
218
        Res = CommandRes;
480
219
481
219
      // If result status is < 0, then the driver command signalled an error.
482
219
      // If result status is 70, then the driver command reported a fatal error.
483
219
      // On Windows, abort will return an exit code of 3.  In these cases,
484
219
      // generate additional diagnostic information if possible.
485
219
      bool DiagnoseCrash = CommandRes < 0 || 
CommandRes == 70199
;
486
#ifdef _WIN32
487
      DiagnoseCrash |= CommandRes == 3;
488
#endif
489
219
      if (DiagnoseCrash) {
490
20
        TheDriver.generateCompilationDiagnostics(*C, *FailingCommand);
491
20
        break;
492
20
      }
493
219
    }
494
22.1k
  }
495
22.1k
496
22.1k
  Diags.getClient()->finish();
497
22.1k
498
22.1k
  // If any timers were active but haven't been destroyed yet, print their
499
22.1k
  // results now.  This happens in -disable-free mode.
500
22.1k
  llvm::TimerGroup::printAll(llvm::errs());
501
22.1k
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
22.1k
  // If we have multiple failing commands, we return the result of the first
511
22.1k
  // failing command.
512
22.1k
  return Res;
513
22.1k
}