Coverage Report

Created: 2020-02-25 14:32

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Frontend/CompilerInvocation.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- CompilerInvocation.cpp ---------------------------------------------===//
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
#include "clang/Frontend/CompilerInvocation.h"
10
#include "TestModuleFileExtension.h"
11
#include "clang/Basic/Builtins.h"
12
#include "clang/Basic/CharInfo.h"
13
#include "clang/Basic/CodeGenOptions.h"
14
#include "clang/Basic/CommentOptions.h"
15
#include "clang/Basic/DebugInfoOptions.h"
16
#include "clang/Basic/Diagnostic.h"
17
#include "clang/Basic/DiagnosticOptions.h"
18
#include "clang/Basic/FileSystemOptions.h"
19
#include "clang/Basic/LLVM.h"
20
#include "clang/Basic/LangOptions.h"
21
#include "clang/Basic/LangStandard.h"
22
#include "clang/Basic/ObjCRuntime.h"
23
#include "clang/Basic/Sanitizers.h"
24
#include "clang/Basic/SourceLocation.h"
25
#include "clang/Basic/TargetOptions.h"
26
#include "clang/Basic/Version.h"
27
#include "clang/Basic/Visibility.h"
28
#include "clang/Basic/XRayInstr.h"
29
#include "clang/Config/config.h"
30
#include "clang/Driver/Driver.h"
31
#include "clang/Driver/DriverDiagnostic.h"
32
#include "clang/Driver/Options.h"
33
#include "clang/Frontend/CommandLineSourceLoc.h"
34
#include "clang/Frontend/DependencyOutputOptions.h"
35
#include "clang/Frontend/FrontendDiagnostic.h"
36
#include "clang/Frontend/FrontendOptions.h"
37
#include "clang/Frontend/FrontendPluginRegistry.h"
38
#include "clang/Frontend/MigratorOptions.h"
39
#include "clang/Frontend/PreprocessorOutputOptions.h"
40
#include "clang/Frontend/Utils.h"
41
#include "clang/Lex/HeaderSearchOptions.h"
42
#include "clang/Lex/PreprocessorOptions.h"
43
#include "clang/Sema/CodeCompleteOptions.h"
44
#include "clang/Serialization/ASTBitCodes.h"
45
#include "clang/Serialization/ModuleFileExtension.h"
46
#include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
47
#include "llvm/ADT/APInt.h"
48
#include "llvm/ADT/ArrayRef.h"
49
#include "llvm/ADT/CachedHashString.h"
50
#include "llvm/ADT/Hashing.h"
51
#include "llvm/ADT/None.h"
52
#include "llvm/ADT/Optional.h"
53
#include "llvm/ADT/SmallString.h"
54
#include "llvm/ADT/SmallVector.h"
55
#include "llvm/ADT/StringRef.h"
56
#include "llvm/ADT/StringSwitch.h"
57
#include "llvm/ADT/Triple.h"
58
#include "llvm/ADT/Twine.h"
59
#include "llvm/IR/DebugInfoMetadata.h"
60
#include "llvm/Linker/Linker.h"
61
#include "llvm/MC/MCTargetOptions.h"
62
#include "llvm/Option/Arg.h"
63
#include "llvm/Option/ArgList.h"
64
#include "llvm/Option/OptSpecifier.h"
65
#include "llvm/Option/OptTable.h"
66
#include "llvm/Option/Option.h"
67
#include "llvm/ProfileData/InstrProfReader.h"
68
#include "llvm/Support/CodeGen.h"
69
#include "llvm/Support/Compiler.h"
70
#include "llvm/Support/Error.h"
71
#include "llvm/Support/ErrorHandling.h"
72
#include "llvm/Support/ErrorOr.h"
73
#include "llvm/Support/FileSystem.h"
74
#include "llvm/Support/Host.h"
75
#include "llvm/Support/MathExtras.h"
76
#include "llvm/Support/MemoryBuffer.h"
77
#include "llvm/Support/Path.h"
78
#include "llvm/Support/Process.h"
79
#include "llvm/Support/Regex.h"
80
#include "llvm/Support/VersionTuple.h"
81
#include "llvm/Support/VirtualFileSystem.h"
82
#include "llvm/Support/raw_ostream.h"
83
#include "llvm/Target/TargetOptions.h"
84
#include <algorithm>
85
#include <atomic>
86
#include <cassert>
87
#include <cstddef>
88
#include <cstring>
89
#include <memory>
90
#include <string>
91
#include <tuple>
92
#include <utility>
93
#include <vector>
94
95
using namespace clang;
96
using namespace driver;
97
using namespace options;
98
using namespace llvm::opt;
99
100
//===----------------------------------------------------------------------===//
101
// Initialization.
102
//===----------------------------------------------------------------------===//
103
104
CompilerInvocationBase::CompilerInvocationBase()
105
    : LangOpts(new LangOptions()), TargetOpts(new TargetOptions()),
106
      DiagnosticOpts(new DiagnosticOptions()),
107
      HeaderSearchOpts(new HeaderSearchOptions()),
108
71.1k
      PreprocessorOpts(new PreprocessorOptions()) {}
109
110
CompilerInvocationBase::CompilerInvocationBase(const CompilerInvocationBase &X)
111
    : LangOpts(new LangOptions(*X.getLangOpts())),
112
      TargetOpts(new TargetOptions(X.getTargetOpts())),
113
      DiagnosticOpts(new DiagnosticOptions(X.getDiagnosticOpts())),
114
      HeaderSearchOpts(new HeaderSearchOptions(X.getHeaderSearchOpts())),
115
9.88k
      PreprocessorOpts(new PreprocessorOptions(X.getPreprocessorOpts())) {}
116
117
73.1k
CompilerInvocationBase::~CompilerInvocationBase() = default;
118
119
//===----------------------------------------------------------------------===//
120
// Deserialization (from args)
121
//===----------------------------------------------------------------------===//
122
123
static unsigned getOptimizationLevel(ArgList &Args, InputKind IK,
124
89.7k
                                     DiagnosticsEngine &Diags) {
125
89.7k
  unsigned DefaultOpt = llvm::CodeGenOpt::None;
126
89.7k
  if (IK.getLanguage() == Language::OpenCL && 
!Args.hasArg(OPT_cl_opt_disable)1.18k
)
127
1.17k
    DefaultOpt = llvm::CodeGenOpt::Default;
128
89.7k
129
89.7k
  if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
130
13.7k
    if (A->getOption().matches(options::OPT_O0))
131
11.8k
      return llvm::CodeGenOpt::None;
132
1.90k
133
1.90k
    if (A->getOption().matches(options::OPT_Ofast))
134
0
      return llvm::CodeGenOpt::Aggressive;
135
1.90k
136
1.90k
    assert(A->getOption().matches(options::OPT_O));
137
1.90k
138
1.90k
    StringRef S(A->getValue());
139
1.90k
    if (S == "s" || 
S == "z"1.78k
||
S.empty()1.75k
)
140
157
      return llvm::CodeGenOpt::Default;
141
1.75k
142
1.75k
    if (S == "g")
143
2
      return llvm::CodeGenOpt::Less;
144
1.74k
145
1.74k
    return getLastArgIntValue(Args, OPT_O, DefaultOpt, Diags);
146
1.74k
  }
147
75.9k
148
75.9k
  return DefaultOpt;
149
75.9k
}
150
151
89.7k
static unsigned getOptimizationLevelSize(ArgList &Args) {
152
89.7k
  if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
153
13.7k
    if (A->getOption().matches(options::OPT_O)) {
154
1.90k
      switch (A->getValue()[0]) {
155
1.75k
      default:
156
1.75k
        return 0;
157
119
      case 's':
158
119
        return 1;
159
38
      case 'z':
160
38
        return 2;
161
87.8k
      }
162
87.8k
    }
163
13.7k
  }
164
87.8k
  return 0;
165
87.8k
}
166
167
static void addDiagnosticArgs(ArgList &Args, OptSpecifier Group,
168
                              OptSpecifier GroupWithValue,
169
145k
                              std::vector<std::string> &Diagnostics) {
170
145k
  for (auto *A : Args.filtered(Group)) {
171
39.1k
    if (A->getOption().getKind() == Option::FlagClass) {
172
380
      // The argument is a pure flag (such as OPT_Wall or OPT_Wdeprecated). Add
173
380
      // its name (minus the "W" or "R" at the beginning) to the warning list.
174
380
      Diagnostics.push_back(
175
380
          std::string(A->getOption().getName().drop_front(1)));
176
38.7k
    } else if (A->getOption().matches(GroupWithValue)) {
177
76
      // This is -Wfoo= or -Rfoo=, where foo is the name of the diagnostic group.
178
76
      Diagnostics.push_back(
179
76
          std::string(A->getOption().getName().drop_front(1).rtrim("=-")));
180
38.6k
    } else {
181
38.6k
      // Otherwise, add its value (for OPT_W_Joined and similar).
182
38.6k
      for (const auto *Arg : A->getValues())
183
38.6k
        Diagnostics.emplace_back(Arg);
184
38.6k
    }
185
39.1k
  }
186
145k
}
187
188
// Parse the Static Analyzer configuration. If \p Diags is set to nullptr,
189
// it won't verify the input.
190
static void parseAnalyzerConfigs(AnalyzerOptions &AnOpts,
191
                                 DiagnosticsEngine *Diags);
192
193
static void getAllNoBuiltinFuncValues(ArgList &Args,
194
77.3k
                                      std::vector<std::string> &Funcs) {
195
77.3k
  SmallVector<const char *, 8> Values;
196
2.13M
  for (const auto &Arg : Args) {
197
2.13M
    const Option &O = Arg->getOption();
198
2.13M
    if (O.matches(options::OPT_fno_builtin_)) {
199
78
      const char *FuncName = Arg->getValue();
200
78
      if (Builtin::Context::isBuiltinFunc(FuncName))
201
78
        Values.push_back(FuncName);
202
78
    }
203
2.13M
  }
204
77.3k
  Funcs.insert(Funcs.end(), Values.begin(), Values.end());
205
77.3k
}
206
207
static bool ParseAnalyzerArgs(AnalyzerOptions &Opts, ArgList &Args,
208
44.9k
                              DiagnosticsEngine &Diags) {
209
44.9k
  bool Success = true;
210
44.9k
  if (Arg *A = Args.getLastArg(OPT_analyzer_store)) {
211
163
    StringRef Name = A->getValue();
212
163
    AnalysisStores Value = llvm::StringSwitch<AnalysisStores>(Name)
213
163
#define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN) \
214
163
      .Case(CMDFLAG, NAME##Model)
215
163
#include "clang/StaticAnalyzer/Core/Analyses.def"
216
163
      .Default(NumStores);
217
163
    if (Value == NumStores) {
218
0
      Diags.Report(diag::err_drv_invalid_value)
219
0
        << A->getAsString(Args) << Name;
220
0
      Success = false;
221
163
    } else {
222
163
      Opts.AnalysisStoreOpt = Value;
223
163
    }
224
163
  }
225
44.9k
226
44.9k
  if (Arg *A = Args.getLastArg(OPT_analyzer_constraints)) {
227
1.21k
    StringRef Name = A->getValue();
228
1.21k
    AnalysisConstraints Value = llvm::StringSwitch<AnalysisConstraints>(Name)
229
1.21k
#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) \
230
2.42k
      .Case(CMDFLAG, NAME##Model)
231
1.21k
#include "clang/StaticAnalyzer/Core/Analyses.def"
232
1.21k
      .Default(NumConstraints);
233
1.21k
    if (Value == NumConstraints) {
234
0
      Diags.Report(diag::err_drv_invalid_value)
235
0
        << A->getAsString(Args) << Name;
236
0
      Success = false;
237
1.21k
    } else {
238
1.21k
      Opts.AnalysisConstraintsOpt = Value;
239
1.21k
    }
240
1.21k
  }
241
44.9k
242
44.9k
  if (Arg *A = Args.getLastArg(OPT_analyzer_output)) {
243
213
    StringRef Name = A->getValue();
244
213
    AnalysisDiagClients Value = llvm::StringSwitch<AnalysisDiagClients>(Name)
245
213
#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN) \
246
1.49k
      .Case(CMDFLAG, PD_##NAME)
247
213
#include "clang/StaticAnalyzer/Core/Analyses.def"
248
213
      .Default(NUM_ANALYSIS_DIAG_CLIENTS);
249
213
    if (Value == NUM_ANALYSIS_DIAG_CLIENTS) {
250
0
      Diags.Report(diag::err_drv_invalid_value)
251
0
        << A->getAsString(Args) << Name;
252
0
      Success = false;
253
213
    } else {
254
213
      Opts.AnalysisDiagOpt = Value;
255
213
    }
256
213
  }
257
44.9k
258
44.9k
  if (Arg *A = Args.getLastArg(OPT_analyzer_purge)) {
259
1
    StringRef Name = A->getValue();
260
1
    AnalysisPurgeMode Value = llvm::StringSwitch<AnalysisPurgeMode>(Name)
261
1
#define ANALYSIS_PURGE(NAME, CMDFLAG, DESC) \
262
3
      .Case(CMDFLAG, NAME)
263
1
#include "clang/StaticAnalyzer/Core/Analyses.def"
264
1
      .Default(NumPurgeModes);
265
1
    if (Value == NumPurgeModes) {
266
0
      Diags.Report(diag::err_drv_invalid_value)
267
0
        << A->getAsString(Args) << Name;
268
0
      Success = false;
269
1
    } else {
270
1
      Opts.AnalysisPurgeOpt = Value;
271
1
    }
272
1
  }
273
44.9k
274
44.9k
  if (Arg *A = Args.getLastArg(OPT_analyzer_inlining_mode)) {
275
0
    StringRef Name = A->getValue();
276
0
    AnalysisInliningMode Value = llvm::StringSwitch<AnalysisInliningMode>(Name)
277
0
#define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC) \
278
0
      .Case(CMDFLAG, NAME)
279
0
#include "clang/StaticAnalyzer/Core/Analyses.def"
280
0
      .Default(NumInliningModes);
281
0
    if (Value == NumInliningModes) {
282
0
      Diags.Report(diag::err_drv_invalid_value)
283
0
        << A->getAsString(Args) << Name;
284
0
      Success = false;
285
0
    } else {
286
0
      Opts.InliningMode = Value;
287
0
    }
288
0
  }
289
44.9k
290
44.9k
  Opts.ShowCheckerHelp = Args.hasArg(OPT_analyzer_checker_help);
291
44.9k
  Opts.ShowCheckerHelpAlpha = Args.hasArg(OPT_analyzer_checker_help_alpha);
292
44.9k
  Opts.ShowCheckerHelpDeveloper =
293
44.9k
      Args.hasArg(OPT_analyzer_checker_help_developer);
294
44.9k
295
44.9k
  Opts.ShowCheckerOptionList = Args.hasArg(OPT_analyzer_checker_option_help);
296
44.9k
  Opts.ShowCheckerOptionAlphaList =
297
44.9k
      Args.hasArg(OPT_analyzer_checker_option_help_alpha);
298
44.9k
  Opts.ShowCheckerOptionDeveloperList =
299
44.9k
      Args.hasArg(OPT_analyzer_checker_option_help_developer);
300
44.9k
301
44.9k
  Opts.ShowConfigOptionsList = Args.hasArg(OPT_analyzer_config_help);
302
44.9k
  Opts.ShowEnabledCheckerList = Args.hasArg(OPT_analyzer_list_enabled_checkers);
303
44.9k
  Opts.ShouldEmitErrorsOnInvalidConfigValue =
304
44.9k
      /* negated */!llvm::StringSwitch<bool>(
305
44.9k
                   Args.getLastArgValue(OPT_analyzer_config_compatibility_mode))
306
44.9k
        .Case("true", true)
307
44.9k
        .Case("false", false)
308
44.9k
        .Default(false);
309
44.9k
  Opts.DisableAllCheckers = Args.hasArg(OPT_analyzer_disable_all_checks);
310
44.9k
311
44.9k
  Opts.visualizeExplodedGraphWithGraphViz =
312
44.9k
    Args.hasArg(OPT_analyzer_viz_egraph_graphviz);
313
44.9k
  Opts.DumpExplodedGraphTo =
314
44.9k
      std::string(Args.getLastArgValue(OPT_analyzer_dump_egraph));
315
44.9k
  Opts.NoRetryExhausted = Args.hasArg(OPT_analyzer_disable_retry_exhausted);
316
44.9k
  Opts.AnalyzerWerror = Args.hasArg(OPT_analyzer_werror);
317
44.9k
  Opts.AnalyzeAll = Args.hasArg(OPT_analyzer_opt_analyze_headers);
318
44.9k
  Opts.AnalyzerDisplayProgress = Args.hasArg(OPT_analyzer_display_progress);
319
44.9k
  Opts.AnalyzeNestedBlocks =
320
44.9k
    Args.hasArg(OPT_analyzer_opt_analyze_nested_blocks);
321
44.9k
  Opts.AnalyzeSpecificFunction =
322
44.9k
      std::string(Args.getLastArgValue(OPT_analyze_function));
323
44.9k
  Opts.UnoptimizedCFG = Args.hasArg(OPT_analysis_UnoptimizedCFG);
324
44.9k
  Opts.TrimGraph = Args.hasArg(OPT_trim_egraph);
325
44.9k
  Opts.maxBlockVisitOnPath =
326
44.9k
      getLastArgIntValue(Args, OPT_analyzer_max_loop, 4, Diags);
327
44.9k
  Opts.PrintStats = Args.hasArg(OPT_analyzer_stats);
328
44.9k
  Opts.InlineMaxStackDepth =
329
44.9k
      getLastArgIntValue(Args, OPT_analyzer_inline_max_stack_depth,
330
44.9k
                         Opts.InlineMaxStackDepth, Diags);
331
44.9k
332
44.9k
  Opts.CheckersAndPackages.clear();
333
44.9k
  for (const Arg *A :
334
44.9k
       Args.filtered(OPT_analyzer_checker, OPT_analyzer_disable_checker)) {
335
1.71k
    A->claim();
336
1.71k
    bool IsEnabled = A->getOption().getID() == OPT_analyzer_checker;
337
1.71k
    // We can have a list of comma separated checker names, e.g:
338
1.71k
    // '-analyzer-checker=cocoa,unix'
339
1.71k
    StringRef CheckerAndPackageList = A->getValue();
340
1.71k
    SmallVector<StringRef, 16> CheckersAndPackages;
341
1.71k
    CheckerAndPackageList.split(CheckersAndPackages, ",");
342
1.71k
    for (const StringRef &CheckerOrPackage : CheckersAndPackages)
343
2.53k
      Opts.CheckersAndPackages.emplace_back(std::string(CheckerOrPackage),
344
2.53k
                                            IsEnabled);
345
1.71k
  }
346
44.9k
347
44.9k
  // Go through the analyzer configuration options.
348
44.9k
  for (const auto *A : Args.filtered(OPT_analyzer_config)) {
349
487
350
487
    // We can have a list of comma separated config names, e.g:
351
487
    // '-analyzer-config key1=val1,key2=val2'
352
487
    StringRef configList = A->getValue();
353
487
    SmallVector<StringRef, 4> configVals;
354
487
    configList.split(configVals, ",");
355
512
    for (const auto &configVal : configVals) {
356
512
      StringRef key, val;
357
512
      std::tie(key, val) = configVal.split("=");
358
512
      if (val.empty()) {
359
0
        Diags.Report(SourceLocation(),
360
0
                     diag::err_analyzer_config_no_value) << configVal;
361
0
        Success = false;
362
0
        break;
363
0
      }
364
512
      if (val.find('=') != StringRef::npos) {
365
0
        Diags.Report(SourceLocation(),
366
0
                     diag::err_analyzer_config_multiple_values)
367
0
          << configVal;
368
0
        Success = false;
369
0
        break;
370
0
      }
371
512
372
512
      // TODO: Check checker options too, possibly in CheckerRegistry.
373
512
      // Leave unknown non-checker configs unclaimed.
374
512
      if (!key.contains(":") && 
Opts.isUnknownAnalyzerConfig(key)379
) {
375
10
        if (Opts.ShouldEmitErrorsOnInvalidConfigValue)
376
4
          Diags.Report(diag::err_analyzer_config_unknown) << key;
377
10
        continue;
378
10
      }
379
502
380
502
      A->claim();
381
502
      Opts.Config[key] = std::string(val);
382
502
    }
383
487
  }
384
44.9k
385
44.9k
  if (Opts.ShouldEmitErrorsOnInvalidConfigValue)
386
44.9k
    parseAnalyzerConfigs(Opts, &Diags);
387
19
  else
388
19
    parseAnalyzerConfigs(Opts, nullptr);
389
44.9k
390
44.9k
  llvm::raw_string_ostream os(Opts.FullCompilerInvocation);
391
2.15M
  for (unsigned i = 0; i < Args.getNumInputArgStrings(); 
++i2.11M
) {
392
2.11M
    if (i != 0)
393
2.06M
      os << " ";
394
2.11M
    os << Args.getArgString(i);
395
2.11M
  }
396
44.9k
  os.flush();
397
44.9k
398
44.9k
  return Success;
399
44.9k
}
400
401
static StringRef getStringOption(AnalyzerOptions::ConfigTable &Config,
402
2.51M
                                 StringRef OptionName, StringRef DefaultVal) {
403
2.51M
  return Config.insert({OptionName, std::string(DefaultVal)}).first->second;
404
2.51M
}
405
406
static void initOption(AnalyzerOptions::ConfigTable &Config,
407
                       DiagnosticsEngine *Diags,
408
                       StringRef &OptionField, StringRef Name,
409
359k
                       StringRef DefaultVal) {
410
359k
  // String options may be known to invalid (e.g. if the expected string is a
411
359k
  // file name, but the file does not exist), those will have to be checked in
412
359k
  // parseConfigs.
413
359k
  OptionField = getStringOption(Config, Name, DefaultVal);
414
359k
}
415
416
static void initOption(AnalyzerOptions::ConfigTable &Config,
417
                       DiagnosticsEngine *Diags,
418
1.75M
                       bool &OptionField, StringRef Name, bool DefaultVal) {
419
1.75M
  auto PossiblyInvalidVal = llvm::StringSwitch<Optional<bool>>(
420
1.75M
                 getStringOption(Config, Name, (DefaultVal ? 
"true"853k
:
"false"898k
)))
421
1.75M
      .Case("true", true)
422
1.75M
      .Case("false", false)
423
1.75M
      .Default(None);
424
1.75M
425
1.75M
  if (!PossiblyInvalidVal) {
426
4
    if (Diags)
427
2
      Diags->Report(diag::err_analyzer_config_invalid_input)
428
2
        << Name << "a boolean";
429
2
    else
430
2
      OptionField = DefaultVal;
431
4
  } else
432
1.75M
    OptionField = PossiblyInvalidVal.getValue();
433
1.75M
}
434
435
static void initOption(AnalyzerOptions::ConfigTable &Config,
436
                       DiagnosticsEngine *Diags,
437
                       unsigned &OptionField, StringRef Name,
438
404k
                       unsigned DefaultVal) {
439
404k
440
404k
  OptionField = DefaultVal;
441
404k
  bool HasFailed = getStringOption(Config, Name, std::to_string(DefaultVal))
442
404k
                     .getAsInteger(0, OptionField);
443
404k
  if (Diags && 
HasFailed404k
)
444
2
    Diags->Report(diag::err_analyzer_config_invalid_input)
445
2
      << Name << "an unsigned";
446
404k
}
447
448
static void parseAnalyzerConfigs(AnalyzerOptions &AnOpts,
449
44.9k
                                 DiagnosticsEngine *Diags) {
450
44.9k
  // TODO: There's no need to store the entire configtable, it'd be plenty
451
44.9k
  // enough tostore checker options.
452
44.9k
453
44.9k
#define ANALYZER_OPTION(TYPE, NAME, CMDFLAG, DESC, DEFAULT_VAL)                \
454
2.38M
  initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, DEFAULT_VAL);
455
44.9k
456
44.9k
#define ANALYZER_OPTION_DEPENDS_ON_USER_MODE(TYPE, NAME, CMDFLAG, DESC,        \
457
44.9k
                                           SHALLOW_VAL, DEEP_VAL)              \
458
134k
  switch (AnOpts.getUserMode()) {                                              \
459
6
  case UMK_Shallow:                                                            \
460
6
    initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, SHALLOW_VAL);       \
461
6
    break;                                                                     \
462
134k
  case UMK_Deep:                                                               \
463
134k
    initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, DEEP_VAL);          \
464
134k
    break;                                                                     \
465
134k
  }                                                                            \
466
44.9k
467
89.8k
#include 
"clang/StaticAnalyzer/Core/AnalyzerOptions.def"44.9k
468
89.8k
#undef ANALYZER_OPTION
469
89.8k
#undef ANALYZER_OPTION_DEPENDS_ON_USER_MODE
470
89.8k
471
89.8k
  // At this point, AnalyzerOptions is configured. Let's validate some options.
472
89.8k
473
89.8k
  // FIXME: Here we try to validate the silenced checkers or packages are valid.
474
89.8k
  // The current approach only validates the registered checkers which does not
475
89.8k
  // contain the runtime enabled checkers and optimally we would validate both.
476
89.8k
  
if (44.9k
!AnOpts.RawSilencedCheckersAndPackages.empty()44.9k
) {
477
5
    std::vector<StringRef> Checkers =
478
5
        AnOpts.getRegisteredCheckers(/*IncludeExperimental=*/true);
479
5
    std::vector<StringRef> Packages =
480
5
        AnOpts.getRegisteredPackages(/*IncludeExperimental=*/true);
481
5
482
5
    SmallVector<StringRef, 16> CheckersAndPackages;
483
5
    AnOpts.RawSilencedCheckersAndPackages.split(CheckersAndPackages, ";");
484
5
485
6
    for (const StringRef &CheckerOrPackage : CheckersAndPackages) {
486
6
      if (Diags) {
487
6
        bool IsChecker = CheckerOrPackage.contains('.');
488
6
        bool IsValidName =
489
6
            IsChecker
490
6
                ? 
llvm::find(Checkers, CheckerOrPackage) != Checkers.end()4
491
6
                : 
llvm::find(Packages, CheckerOrPackage) != Packages.end()2
;
492
6
493
6
        if (!IsValidName)
494
2
          Diags->Report(diag::err_unknown_analyzer_checker_or_package)
495
2
              << CheckerOrPackage;
496
6
      }
497
6
498
6
      AnOpts.SilencedCheckersAndPackages.emplace_back(CheckerOrPackage);
499
6
    }
500
5
  }
501
44.9k
502
44.9k
  if (!Diags)
503
20
    return;
504
44.9k
505
44.9k
  if (AnOpts.ShouldTrackConditionsDebug && 
!AnOpts.ShouldTrackConditions2
)
506
1
    Diags->Report(diag::err_analyzer_config_invalid_input)
507
1
        << "track-conditions-debug" << "'track-conditions' to also be enabled";
508
44.9k
509
44.9k
  if (!AnOpts.CTUDir.empty() && 
!llvm::sys::fs::is_directory(AnOpts.CTUDir)9
)
510
2
    Diags->Report(diag::err_analyzer_config_invalid_input) << "ctu-dir"
511
2
                                                           << "a filename";
512
44.9k
513
44.9k
  if (!AnOpts.ModelPath.empty() &&
514
44.9k
      
!llvm::sys::fs::is_directory(AnOpts.ModelPath)1
)
515
0
    Diags->Report(diag::err_analyzer_config_invalid_input) << "model-path"
516
0
                                                           << "a filename";
517
44.9k
}
518
519
44.9k
static bool ParseMigratorArgs(MigratorOptions &Opts, ArgList &Args) {
520
44.9k
  Opts.NoNSAllocReallocError = Args.hasArg(OPT_migrator_no_nsalloc_error);
521
44.9k
  Opts.NoFinalizeRemoval = Args.hasArg(OPT_migrator_no_finalize_removal);
522
44.9k
  return true;
523
44.9k
}
524
525
44.9k
static void ParseCommentArgs(CommentOptions &Opts, ArgList &Args) {
526
44.9k
  Opts.BlockCommandNames = Args.getAllArgValues(OPT_fcomment_block_commands);
527
44.9k
  Opts.ParseAllComments = Args.hasArg(OPT_fparse_all_comments);
528
44.9k
}
529
530
static llvm::Reloc::Model getRelocModel(ArgList &Args,
531
44.9k
                                        DiagnosticsEngine &Diags) {
532
44.9k
  if (Arg *A = Args.getLastArg(OPT_mrelocation_model)) {
533
18.9k
    StringRef Value = A->getValue();
534
18.9k
    auto RM = llvm::StringSwitch<llvm::Optional<llvm::Reloc::Model>>(Value)
535
18.9k
                  .Case("static", llvm::Reloc::Static)
536
18.9k
                  .Case("pic", llvm::Reloc::PIC_)
537
18.9k
                  .Case("ropi", llvm::Reloc::ROPI)
538
18.9k
                  .Case("rwpi", llvm::Reloc::RWPI)
539
18.9k
                  .Case("ropi-rwpi", llvm::Reloc::ROPI_RWPI)
540
18.9k
                  .Case("dynamic-no-pic", llvm::Reloc::DynamicNoPIC)
541
18.9k
                  .Default(None);
542
18.9k
    if (RM.hasValue())
543
18.9k
      return *RM;
544
1
    Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Value;
545
1
  }
546
44.9k
  
return llvm::Reloc::PIC_26.0k
;
547
44.9k
}
548
549
/// Create a new Regex instance out of the string value in \p RpassArg.
550
/// It returns a pointer to the newly generated Regex instance.
551
static std::shared_ptr<llvm::Regex>
552
GenerateOptimizationRemarkRegex(DiagnosticsEngine &Diags, ArgList &Args,
553
68
                                Arg *RpassArg) {
554
68
  StringRef Val = RpassArg->getValue();
555
68
  std::string RegexError;
556
68
  std::shared_ptr<llvm::Regex> Pattern = std::make_shared<llvm::Regex>(Val);
557
68
  if (!Pattern->isValid(RegexError)) {
558
0
    Diags.Report(diag::err_drv_optimization_remark_pattern)
559
0
        << RegexError << RpassArg->getAsString(Args);
560
0
    Pattern.reset();
561
0
  }
562
68
  return Pattern;
563
68
}
564
565
static bool parseDiagnosticLevelMask(StringRef FlagName,
566
                                     const std::vector<std::string> &Levels,
567
                                     DiagnosticsEngine *Diags,
568
72.5k
                                     DiagnosticLevelMask &M) {
569
72.5k
  bool Success = true;
570
72.5k
  for (const auto &Level : Levels) {
571
27
    DiagnosticLevelMask const PM =
572
27
      llvm::StringSwitch<DiagnosticLevelMask>(Level)
573
27
        .Case("note",    DiagnosticLevelMask::Note)
574
27
        .Case("remark",  DiagnosticLevelMask::Remark)
575
27
        .Case("warning", DiagnosticLevelMask::Warning)
576
27
        .Case("error",   DiagnosticLevelMask::Error)
577
27
        .Default(DiagnosticLevelMask::None);
578
27
    if (PM == DiagnosticLevelMask::None) {
579
1
      Success = false;
580
1
      if (Diags)
581
1
        Diags->Report(diag::err_drv_invalid_value) << FlagName << Level;
582
1
    }
583
27
    M = M | PM;
584
27
  }
585
72.5k
  return Success;
586
72.5k
}
587
588
static void parseSanitizerKinds(StringRef FlagName,
589
                                const std::vector<std::string> &Sanitizers,
590
134k
                                DiagnosticsEngine &Diags, SanitizerSet &S) {
591
134k
  for (const auto &Sanitizer : Sanitizers) {
592
1.25k
    SanitizerMask K = parseSanitizerValue(Sanitizer, /*AllowGroups=*/false);
593
1.25k
    if (K == SanitizerMask())
594
0
      Diags.Report(diag::err_drv_invalid_value) << FlagName << Sanitizer;
595
1.25k
    else
596
1.25k
      S.set(K, true);
597
1.25k
  }
598
134k
}
599
600
static void parseXRayInstrumentationBundle(StringRef FlagName, StringRef Bundle,
601
                                           ArgList &Args, DiagnosticsEngine &D,
602
20
                                           XRayInstrSet &S) {
603
20
  llvm::SmallVector<StringRef, 2> BundleParts;
604
20
  llvm::SplitString(Bundle, BundleParts, ",");
605
27
  for (const auto &B : BundleParts) {
606
27
    auto Mask = parseXRayInstrValue(B);
607
27
    if (Mask == XRayInstrKind::None)
608
1
      if (B != "none")
609
0
        D.Report(diag::err_drv_invalid_value) << FlagName << Bundle;
610
1
      else
611
1
        S.Mask = Mask;
612
26
    else if (Mask == XRayInstrKind::All)
613
3
      S.Mask = Mask;
614
23
    else
615
23
      S.set(Mask, true);
616
27
  }
617
20
}
618
619
// Set the profile kind for fprofile-instrument.
620
static void setPGOInstrumentor(CodeGenOptions &Opts, ArgList &Args,
621
44.9k
                               DiagnosticsEngine &Diags) {
622
44.9k
  Arg *A = Args.getLastArg(OPT_fprofile_instrument_EQ);
623
44.9k
  if (A == nullptr)
624
44.8k
    return;
625
111
  StringRef S = A->getValue();
626
111
  unsigned I = llvm::StringSwitch<unsigned>(S)
627
111
                   .Case("none", CodeGenOptions::ProfileNone)
628
111
                   .Case("clang", CodeGenOptions::ProfileClangInstr)
629
111
                   .Case("llvm", CodeGenOptions::ProfileIRInstr)
630
111
                   .Case("csllvm", CodeGenOptions::ProfileCSIRInstr)
631
111
                   .Default(~0U);
632
111
  if (I == ~0U) {
633
1
    Diags.Report(diag::err_drv_invalid_pgo_instrumentor) << A->getAsString(Args)
634
1
                                                         << S;
635
1
    return;
636
1
  }
637
110
  auto Instrumentor = static_cast<CodeGenOptions::ProfileInstrKind>(I);
638
110
  Opts.setProfileInstr(Instrumentor);
639
110
}
640
641
// Set the profile kind using fprofile-instrument-use-path.
642
static void setPGOUseInstrumentor(CodeGenOptions &Opts,
643
81
                                  const Twine &ProfileName) {
644
81
  auto ReaderOrErr = llvm::IndexedInstrProfReader::create(ProfileName);
645
81
  // In error, return silently and let Clang PGOUse report the error message.
646
81
  if (auto E = ReaderOrErr.takeError()) {
647
1
    llvm::consumeError(std::move(E));
648
1
    Opts.setProfileUse(CodeGenOptions::ProfileClangInstr);
649
1
    return;
650
1
  }
651
80
  std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader =
652
80
    std::move(ReaderOrErr.get());
653
80
  if (PGOReader->isIRLevelProfile()) {
654
30
    if (PGOReader->hasCSIRLevelProfile())
655
12
      Opts.setProfileUse(CodeGenOptions::ProfileCSIRInstr);
656
18
    else
657
18
      Opts.setProfileUse(CodeGenOptions::ProfileIRInstr);
658
30
  } else
659
50
    Opts.setProfileUse(CodeGenOptions::ProfileClangInstr);
660
80
}
661
662
static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK,
663
                             DiagnosticsEngine &Diags,
664
                             const TargetOptions &TargetOpts,
665
44.9k
                             const FrontendOptions &FrontendOpts) {
666
44.9k
  bool Success = true;
667
44.9k
  llvm::Triple Triple = llvm::Triple(TargetOpts.Triple);
668
44.9k
669
44.9k
  unsigned OptimizationLevel = getOptimizationLevel(Args, IK, Diags);
670
44.9k
  // TODO: This could be done in Driver
671
44.9k
  unsigned MaxOptLevel = 3;
672
44.9k
  if (OptimizationLevel > MaxOptLevel) {
673
4
    // If the optimization level is not supported, fall back on the default
674
4
    // optimization
675
4
    Diags.Report(diag::warn_drv_optimization_value)
676
4
        << Args.getLastArg(OPT_O)->getAsString(Args) << "-O" << MaxOptLevel;
677
4
    OptimizationLevel = MaxOptLevel;
678
4
  }
679
44.9k
  Opts.OptimizationLevel = OptimizationLevel;
680
44.9k
681
44.9k
  // At O0 we want to fully disable inlining outside of cases marked with
682
44.9k
  // 'alwaysinline' that are required for correctness.
683
44.9k
  Opts.setInlining((Opts.OptimizationLevel == 0)
684
44.9k
                       ? 
CodeGenOptions::OnlyAlwaysInlining43.4k
685
44.9k
                       : 
CodeGenOptions::NormalInlining1.44k
);
686
44.9k
  // Explicit inlining flags can disable some or all inlining even at
687
44.9k
  // optimization levels above zero.
688
44.9k
  if (Arg *InlineArg = Args.getLastArg(
689
20
          options::OPT_finline_functions, options::OPT_finline_hint_functions,
690
20
          options::OPT_fno_inline_functions, options::OPT_fno_inline)) {
691
20
    if (Opts.OptimizationLevel > 0) {
692
19
      const Option &InlineOpt = InlineArg->getOption();
693
19
      if (InlineOpt.matches(options::OPT_finline_functions))
694
4
        Opts.setInlining(CodeGenOptions::NormalInlining);
695
15
      else if (InlineOpt.matches(options::OPT_finline_hint_functions))
696
4
        Opts.setInlining(CodeGenOptions::OnlyHintInlining);
697
11
      else
698
11
        Opts.setInlining(CodeGenOptions::OnlyAlwaysInlining);
699
19
    }
700
20
  }
701
44.9k
702
44.9k
  Opts.ExperimentalNewPassManager = Args.hasFlag(
703
44.9k
      OPT_fexperimental_new_pass_manager, OPT_fno_experimental_new_pass_manager,
704
44.9k
      /* Default */ ENABLE_EXPERIMENTAL_NEW_PASS_MANAGER);
705
44.9k
706
44.9k
  Opts.DebugPassManager =
707
44.9k
      Args.hasFlag(OPT_fdebug_pass_manager, OPT_fno_debug_pass_manager,
708
44.9k
                   /* Default */ false);
709
44.9k
710
44.9k
  if (Arg *A = Args.getLastArg(OPT_fveclib)) {
711
1
    StringRef Name = A->getValue();
712
1
    if (Name == "Accelerate")
713
0
      Opts.setVecLib(CodeGenOptions::Accelerate);
714
1
    else if (Name == "MASSV")
715
0
      Opts.setVecLib(CodeGenOptions::MASSV);
716
1
    else if (Name == "SVML")
717
0
      Opts.setVecLib(CodeGenOptions::SVML);
718
1
    else if (Name == "none")
719
0
      Opts.setVecLib(CodeGenOptions::NoLibrary);
720
1
    else
721
1
      Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
722
1
  }
723
44.9k
724
44.9k
  if (Arg *A = Args.getLastArg(OPT_debug_info_kind_EQ)) {
725
6.27k
    unsigned Val =
726
6.27k
        llvm::StringSwitch<unsigned>(A->getValue())
727
6.27k
            .Case("line-tables-only", codegenoptions::DebugLineTablesOnly)
728
6.27k
            .Case("line-directives-only", codegenoptions::DebugDirectivesOnly)
729
6.27k
            .Case("constructor", codegenoptions::DebugInfoConstructor)
730
6.27k
            .Case("limited", codegenoptions::LimitedDebugInfo)
731
6.27k
            .Case("standalone", codegenoptions::FullDebugInfo)
732
6.27k
            .Default(~0U);
733
6.27k
    if (Val == ~0U)
734
1
      Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
735
1
                                                << A->getValue();
736
6.27k
    else
737
6.27k
      Opts.setDebugInfo(static_cast<codegenoptions::DebugInfoKind>(Val));
738
6.27k
  }
739
44.9k
  if (Arg *A = Args.getLastArg(OPT_debugger_tuning_EQ)) {
740
18.8k
    unsigned Val = llvm::StringSwitch<unsigned>(A->getValue())
741
18.8k
                       .Case("gdb", unsigned(llvm::DebuggerKind::GDB))
742
18.8k
                       .Case("lldb", unsigned(llvm::DebuggerKind::LLDB))
743
18.8k
                       .Case("sce", unsigned(llvm::DebuggerKind::SCE))
744
18.8k
                       .Default(~0U);
745
18.8k
    if (Val == ~0U)
746
1
      Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
747
1
                                                << A->getValue();
748
18.8k
    else
749
18.8k
      Opts.setDebuggerTuning(static_cast<llvm::DebuggerKind>(Val));
750
18.8k
  }
751
44.9k
  Opts.DwarfVersion = getLastArgIntValue(Args, OPT_dwarf_version_EQ, 0, Diags);
752
44.9k
  Opts.DebugColumnInfo = Args.hasArg(OPT_dwarf_column_info);
753
44.9k
  Opts.EmitCodeView = Args.hasArg(OPT_gcodeview);
754
44.9k
  Opts.CodeViewGHash = Args.hasArg(OPT_gcodeview_ghash);
755
44.9k
  Opts.MacroDebugInfo = Args.hasArg(OPT_debug_info_macro);
756
44.9k
  Opts.WholeProgramVTables = Args.hasArg(OPT_fwhole_program_vtables);
757
44.9k
  Opts.VirtualFunctionElimination =
758
44.9k
      Args.hasArg(OPT_fvirtual_function_elimination);
759
44.9k
  Opts.LTOVisibilityPublicStd = Args.hasArg(OPT_flto_visibility_public_std);
760
44.9k
  Opts.SplitDwarfFile = std::string(Args.getLastArgValue(OPT_split_dwarf_file));
761
44.9k
  Opts.SplitDwarfOutput =
762
44.9k
      std::string(Args.getLastArgValue(OPT_split_dwarf_output));
763
44.9k
  Opts.SplitDwarfInlining = !Args.hasArg(OPT_fno_split_dwarf_inlining);
764
44.9k
  Opts.DebugTypeExtRefs = Args.hasArg(OPT_dwarf_ext_refs);
765
44.9k
  Opts.DebugExplicitImport = Args.hasArg(OPT_dwarf_explicit_import);
766
44.9k
  Opts.DebugFwdTemplateParams = Args.hasArg(OPT_debug_forward_template_params);
767
44.9k
  Opts.EmbedSource = Args.hasArg(OPT_gembed_source);
768
44.9k
769
44.9k
  Opts.ForceDwarfFrameSection =
770
44.9k
      Args.hasFlag(OPT_fforce_dwarf_frame, OPT_fno_force_dwarf_frame, false);
771
44.9k
772
44.9k
  for (const auto &Arg : Args.getAllArgValues(OPT_fdebug_prefix_map_EQ)) {
773
12
    auto Split = StringRef(Arg).split('=');
774
12
    Opts.DebugPrefixMap.insert(
775
12
        {std::string(Split.first), std::string(Split.second)});
776
12
  }
777
44.9k
778
44.9k
  if (const Arg *A =
779
4
          Args.getLastArg(OPT_emit_llvm_uselists, OPT_no_emit_llvm_uselists))
780
4
    Opts.EmitLLVMUseLists = A->getOption().getID() == OPT_emit_llvm_uselists;
781
44.9k
782
44.9k
  Opts.DisableLLVMPasses = Args.hasArg(OPT_disable_llvm_passes);
783
44.9k
  Opts.DisableLifetimeMarkers = Args.hasArg(OPT_disable_lifetimemarkers);
784
44.9k
785
44.9k
  const llvm::Triple::ArchType DebugEntryValueArchs[] = {
786
44.9k
      llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::aarch64,
787
44.9k
      llvm::Triple::arm, llvm::Triple::armeb};
788
44.9k
789
44.9k
  llvm::Triple T(TargetOpts.Triple);
790
44.9k
  if (Opts.OptimizationLevel > 0 && 
Opts.hasReducedDebugInfo()1.44k
&&
791
44.9k
      
llvm::is_contained(DebugEntryValueArchs, T.getArch())180
)
792
176
    Opts.EnableDebugEntryValues = Args.hasArg(OPT_femit_debug_entry_values);
793
44.9k
794
44.9k
  Opts.DisableO0ImplyOptNone = Args.hasArg(OPT_disable_O0_optnone);
795
44.9k
  Opts.DisableRedZone = Args.hasArg(OPT_disable_red_zone);
796
44.9k
  Opts.IndirectTlsSegRefs = Args.hasArg(OPT_mno_tls_direct_seg_refs);
797
44.9k
  Opts.ForbidGuardVariables = Args.hasArg(OPT_fforbid_guard_variables);
798
44.9k
  Opts.UseRegisterSizedBitfieldAccess = Args.hasArg(
799
44.9k
    OPT_fuse_register_sized_bitfield_access);
800
44.9k
  Opts.RelaxedAliasing = Args.hasArg(OPT_relaxed_aliasing);
801
44.9k
  Opts.StructPathTBAA = !Args.hasArg(OPT_no_struct_path_tbaa);
802
44.9k
  Opts.NewStructPathTBAA = !Args.hasArg(OPT_no_struct_path_tbaa) &&
803
44.9k
                           
Args.hasArg(OPT_new_struct_path_tbaa)44.9k
;
804
44.9k
  Opts.FineGrainedBitfieldAccesses =
805
44.9k
      Args.hasFlag(OPT_ffine_grained_bitfield_accesses,
806
44.9k
                   OPT_fno_fine_grained_bitfield_accesses, false);
807
44.9k
  Opts.DwarfDebugFlags =
808
44.9k
      std::string(Args.getLastArgValue(OPT_dwarf_debug_flags));
809
44.9k
  Opts.RecordCommandLine =
810
44.9k
      std::string(Args.getLastArgValue(OPT_record_command_line));
811
44.9k
  Opts.MergeAllConstants = Args.hasArg(OPT_fmerge_all_constants);
812
44.9k
  Opts.NoCommon = Args.hasArg(OPT_fno_common);
813
44.9k
  Opts.NoInlineLineTables = Args.hasArg(OPT_gno_inline_line_tables);
814
44.9k
  Opts.NoImplicitFloat = Args.hasArg(OPT_no_implicit_float);
815
44.9k
  Opts.OptimizeSize = getOptimizationLevelSize(Args);
816
44.9k
  Opts.SimplifyLibCalls = !(Args.hasArg(OPT_fno_builtin) ||
817
44.9k
                            
Args.hasArg(OPT_ffreestanding)39.4k
);
818
44.9k
  if (Opts.SimplifyLibCalls)
819
38.7k
    getAllNoBuiltinFuncValues(Args, Opts.NoBuiltinFuncs);
820
44.9k
  Opts.UnrollLoops =
821
44.9k
      Args.hasFlag(OPT_funroll_loops, OPT_fno_unroll_loops,
822
44.9k
                   (Opts.OptimizationLevel > 1));
823
44.9k
  Opts.RerollLoops = Args.hasArg(OPT_freroll_loops);
824
44.9k
825
44.9k
  Opts.DisableIntegratedAS = Args.hasArg(OPT_fno_integrated_as);
826
44.9k
  Opts.Autolink = !Args.hasArg(OPT_fno_autolink);
827
44.9k
  Opts.SampleProfileFile =
828
44.9k
      std::string(Args.getLastArgValue(OPT_fprofile_sample_use_EQ));
829
44.9k
  Opts.DebugInfoForProfiling = Args.hasFlag(
830
44.9k
      OPT_fdebug_info_for_profiling, OPT_fno_debug_info_for_profiling, false);
831
44.9k
  Opts.DebugNameTable = static_cast<unsigned>(
832
44.9k
      Args.hasArg(OPT_ggnu_pubnames)
833
44.9k
          ? 
llvm::DICompileUnit::DebugNameTableKind::GNU4
834
44.9k
          : Args.hasArg(OPT_gpubnames)
835
44.9k
                ? 
llvm::DICompileUnit::DebugNameTableKind::Default1
836
44.9k
                : 
llvm::DICompileUnit::DebugNameTableKind::None44.9k
);
837
44.9k
  Opts.DebugRangesBaseAddress = Args.hasArg(OPT_fdebug_ranges_base_address);
838
44.9k
839
44.9k
  setPGOInstrumentor(Opts, Args, Diags);
840
44.9k
  Opts.InstrProfileOutput =
841
44.9k
      std::string(Args.getLastArgValue(OPT_fprofile_instrument_path_EQ));
842
44.9k
  Opts.ProfileInstrumentUsePath =
843
44.9k
      std::string(Args.getLastArgValue(OPT_fprofile_instrument_use_path_EQ));
844
44.9k
  if (!Opts.ProfileInstrumentUsePath.empty())
845
81
    setPGOUseInstrumentor(Opts, Opts.ProfileInstrumentUsePath);
846
44.9k
  Opts.ProfileRemappingFile =
847
44.9k
      std::string(Args.getLastArgValue(OPT_fprofile_remapping_file_EQ));
848
44.9k
  if (!Opts.ProfileRemappingFile.empty() && 
!Opts.ExperimentalNewPassManager3
) {
849
0
    Diags.Report(diag::err_drv_argument_only_allowed_with)
850
0
      << Args.getLastArg(OPT_fprofile_remapping_file_EQ)->getAsString(Args)
851
0
      << "-fexperimental-new-pass-manager";
852
0
  }
853
44.9k
854
44.9k
  Opts.CoverageMapping =
855
44.9k
      Args.hasFlag(OPT_fcoverage_mapping, OPT_fno_coverage_mapping, false);
856
44.9k
  Opts.DumpCoverageMapping = Args.hasArg(OPT_dump_coverage_mapping);
857
44.9k
  Opts.AsmVerbose = Args.hasArg(OPT_masm_verbose);
858
44.9k
  Opts.PreserveAsmComments = !Args.hasArg(OPT_fno_preserve_as_comments);
859
44.9k
  Opts.AssumeSaneOperatorNew = !Args.hasArg(OPT_fno_assume_sane_operator_new);
860
44.9k
  Opts.ObjCAutoRefCountExceptions = Args.hasArg(OPT_fobjc_arc_exceptions);
861
44.9k
  Opts.CXAAtExit = !Args.hasArg(OPT_fno_use_cxa_atexit);
862
44.9k
  Opts.RegisterGlobalDtorsWithAtExit =
863
44.9k
      Args.hasArg(OPT_fregister_global_dtors_with_atexit);
864
44.9k
  Opts.CXXCtorDtorAliases = Args.hasArg(OPT_mconstructor_aliases);
865
44.9k
  Opts.CodeModel = TargetOpts.CodeModel;
866
44.9k
  Opts.DebugPass = std::string(Args.getLastArgValue(OPT_mdebug_pass));
867
44.9k
868
44.9k
  // Handle -mframe-pointer option.
869
44.9k
  if (Arg *A = Args.getLastArg(OPT_mframe_pointer_EQ)) {
870
18.9k
    CodeGenOptions::FramePointerKind FP;
871
18.9k
    StringRef Name = A->getValue();
872
18.9k
    bool ValidFP = true;
873
18.9k
    if (Name == "none")
874
165
      FP = CodeGenOptions::FramePointerKind::None;
875
18.7k
    else if (Name == "non-leaf")
876
154
      FP = CodeGenOptions::FramePointerKind::NonLeaf;
877
18.6k
    else if (Name == "all")
878
18.6k
      FP = CodeGenOptions::FramePointerKind::All;
879
1
    else {
880
1
      Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
881
1
      Success = false;
882
1
      ValidFP = false;
883
1
    }
884
18.9k
    if (ValidFP)
885
18.9k
      Opts.setFramePointer(FP);
886
18.9k
  }
887
44.9k
888
44.9k
  Opts.DisableFree = Args.hasArg(OPT_disable_free);
889
44.9k
  Opts.DiscardValueNames = Args.hasArg(OPT_discard_value_names);
890
44.9k
  Opts.DisableTailCalls = Args.hasArg(OPT_mdisable_tail_calls);
891
44.9k
  Opts.NoEscapingBlockTailCalls =
892
44.9k
      Args.hasArg(OPT_fno_escaping_block_tail_calls);
893
44.9k
  Opts.FloatABI = std::string(Args.getLastArgValue(OPT_mfloat_abi));
894
44.9k
  Opts.LessPreciseFPMAD = Args.hasArg(OPT_cl_mad_enable) ||
895
44.9k
                          
Args.hasArg(OPT_cl_unsafe_math_optimizations)44.9k
||
896
44.9k
                          
Args.hasArg(OPT_cl_fast_relaxed_math)44.9k
;
897
44.9k
  Opts.LimitFloatPrecision =
898
44.9k
      std::string(Args.getLastArgValue(OPT_mlimit_float_precision));
899
44.9k
  Opts.NoInfsFPMath = (Args.hasArg(OPT_menable_no_infinities) ||
900
44.9k
                       
Args.hasArg(OPT_cl_finite_math_only)44.9k
||
901
44.9k
                       
Args.hasArg(OPT_cl_fast_relaxed_math)44.9k
);
902
44.9k
  Opts.NoNaNsFPMath = (Args.hasArg(OPT_menable_no_nans) ||
903
44.9k
                       
Args.hasArg(OPT_cl_unsafe_math_optimizations)44.9k
||
904
44.9k
                       
Args.hasArg(OPT_cl_finite_math_only)44.9k
||
905
44.9k
                       
Args.hasArg(OPT_cl_fast_relaxed_math)44.9k
);
906
44.9k
  Opts.NoSignedZeros = (Args.hasArg(OPT_fno_signed_zeros) ||
907
44.9k
                        
Args.hasArg(OPT_cl_no_signed_zeros)44.9k
||
908
44.9k
                        
Args.hasArg(OPT_cl_unsafe_math_optimizations)44.9k
||
909
44.9k
                        
Args.hasArg(OPT_cl_fast_relaxed_math)44.9k
);
910
44.9k
  Opts.Reassociate = Args.hasArg(OPT_mreassociate);
911
44.9k
  Opts.CorrectlyRoundedDivSqrt =
912
44.9k
      Args.hasArg(OPT_cl_fp32_correctly_rounded_divide_sqrt);
913
44.9k
  Opts.UniformWGSize =
914
44.9k
      Args.hasArg(OPT_cl_uniform_work_group_size);
915
44.9k
  Opts.Reciprocals = Args.getAllArgValues(OPT_mrecip_EQ);
916
44.9k
  Opts.ReciprocalMath = Args.hasArg(OPT_freciprocal_math);
917
44.9k
  Opts.NoTrappingMath = Args.hasArg(OPT_fno_trapping_math);
918
44.9k
  Opts.StrictFloatCastOverflow =
919
44.9k
      !Args.hasArg(OPT_fno_strict_float_cast_overflow);
920
44.9k
921
44.9k
  Opts.NoZeroInitializedInBSS = Args.hasArg(OPT_mno_zero_initialized_in_bss);
922
44.9k
  Opts.NumRegisterParameters = getLastArgIntValue(Args, OPT_mregparm, 0, Diags);
923
44.9k
  Opts.NoExecStack = Args.hasArg(OPT_mno_exec_stack);
924
44.9k
  Opts.FatalWarnings = Args.hasArg(OPT_massembler_fatal_warnings);
925
44.9k
  Opts.NoWarn = Args.hasArg(OPT_massembler_no_warn);
926
44.9k
  Opts.EnableSegmentedStacks = Args.hasArg(OPT_split_stacks);
927
44.9k
  Opts.RelaxAll = Args.hasArg(OPT_mrelax_all);
928
44.9k
  Opts.IncrementalLinkerCompatible =
929
44.9k
      Args.hasArg(OPT_mincremental_linker_compatible);
930
44.9k
  Opts.PIECopyRelocations =
931
44.9k
      Args.hasArg(OPT_mpie_copy_relocations);
932
44.9k
  Opts.NoPLT = Args.hasArg(OPT_fno_plt);
933
44.9k
  Opts.SaveTempLabels = Args.hasArg(OPT_msave_temp_labels);
934
44.9k
  Opts.NoDwarfDirectoryAsm = Args.hasArg(OPT_fno_dwarf_directory_asm);
935
44.9k
  Opts.SoftFloat = Args.hasArg(OPT_msoft_float);
936
44.9k
  Opts.StrictEnums = Args.hasArg(OPT_fstrict_enums);
937
44.9k
  Opts.StrictReturn = !Args.hasArg(OPT_fno_strict_return);
938
44.9k
  Opts.StrictVTablePointers = Args.hasArg(OPT_fstrict_vtable_pointers);
939
44.9k
  Opts.ForceEmitVTables = Args.hasArg(OPT_fforce_emit_vtables);
940
44.9k
  Opts.UnsafeFPMath = Args.hasArg(OPT_menable_unsafe_fp_math) ||
941
44.9k
                      
Args.hasArg(OPT_cl_unsafe_math_optimizations)44.9k
||
942
44.9k
                      
Args.hasArg(OPT_cl_fast_relaxed_math)44.9k
;
943
44.9k
  Opts.UnwindTables = Args.hasArg(OPT_munwind_tables);
944
44.9k
  Opts.RelocationModel = getRelocModel(Args, Diags);
945
44.9k
  Opts.ThreadModel =
946
44.9k
      std::string(Args.getLastArgValue(OPT_mthread_model, "posix"));
947
44.9k
  if (Opts.ThreadModel != "posix" && 
Opts.ThreadModel != "single"0
)
948
0
    Diags.Report(diag::err_drv_invalid_value)
949
0
        << Args.getLastArg(OPT_mthread_model)->getAsString(Args)
950
0
        << Opts.ThreadModel;
951
44.9k
  Opts.TrapFuncName = std::string(Args.getLastArgValue(OPT_ftrap_function_EQ));
952
44.9k
  Opts.UseInitArray = !Args.hasArg(OPT_fno_use_init_array);
953
44.9k
954
44.9k
  Opts.FunctionSections = Args.hasArg(OPT_ffunction_sections);
955
44.9k
  Opts.DataSections = Args.hasArg(OPT_fdata_sections);
956
44.9k
  Opts.StackSizeSection = Args.hasArg(OPT_fstack_size_section);
957
44.9k
  Opts.UniqueSectionNames = !Args.hasArg(OPT_fno_unique_section_names);
958
44.9k
959
44.9k
  Opts.MergeFunctions = Args.hasArg(OPT_fmerge_functions);
960
44.9k
961
44.9k
  Opts.NoUseJumpTables = Args.hasArg(OPT_fno_jump_tables);
962
44.9k
963
44.9k
  Opts.NullPointerIsValid = Args.hasArg(OPT_fno_delete_null_pointer_checks);
964
44.9k
965
44.9k
  Opts.ProfileSampleAccurate = Args.hasArg(OPT_fprofile_sample_accurate);
966
44.9k
967
44.9k
  Opts.PrepareForLTO = Args.hasArg(OPT_flto, OPT_flto_EQ);
968
44.9k
  Opts.PrepareForThinLTO = false;
969
44.9k
  if (Arg *A = Args.getLastArg(OPT_flto_EQ)) {
970
57
    StringRef S = A->getValue();
971
57
    if (S == "thin")
972
50
      Opts.PrepareForThinLTO = true;
973
7
    else if (S != "full")
974
1
      Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << S;
975
57
  }
976
44.9k
  Opts.LTOUnit = Args.hasFlag(OPT_flto_unit, OPT_fno_lto_unit, false);
977
44.9k
  Opts.EnableSplitLTOUnit = Args.hasArg(OPT_fsplit_lto_unit);
978
44.9k
  if (Arg *A = Args.getLastArg(OPT_fthinlto_index_EQ)) {
979
51
    if (IK.getLanguage() != Language::LLVM_IR)
980
1
      Diags.Report(diag::err_drv_argument_only_allowed_with)
981
1
          << A->getAsString(Args) << "-x ir";
982
51
    Opts.ThinLTOIndexFile =
983
51
        std::string(Args.getLastArgValue(OPT_fthinlto_index_EQ));
984
51
  }
985
44.9k
  if (Arg *A = Args.getLastArg(OPT_save_temps_EQ))
986
8
    Opts.SaveTempsFilePrefix =
987
8
        llvm::StringSwitch<std::string>(A->getValue())
988
8
            .Case("obj", FrontendOpts.OutputFile)
989
8
            .Default(llvm::sys::path::filename(FrontendOpts.OutputFile).str());
990
44.9k
991
44.9k
  Opts.ThinLinkBitcodeFile =
992
44.9k
      std::string(Args.getLastArgValue(OPT_fthin_link_bitcode_EQ));
993
44.9k
994
44.9k
  Opts.MSVolatile = Args.hasArg(OPT_fms_volatile);
995
44.9k
996
44.9k
  Opts.VectorizeLoop = Args.hasArg(OPT_vectorize_loops);
997
44.9k
  Opts.VectorizeSLP = Args.hasArg(OPT_vectorize_slp);
998
44.9k
999
44.9k
  Opts.PreferVectorWidth =
1000
44.9k
      std::string(Args.getLastArgValue(OPT_mprefer_vector_width_EQ));
1001
44.9k
1002
44.9k
  Opts.MainFileName = std::string(Args.getLastArgValue(OPT_main_file_name));
1003
44.9k
  Opts.VerifyModule = !Args.hasArg(OPT_disable_llvm_verifier);
1004
44.9k
1005
44.9k
  Opts.ControlFlowGuardNoChecks = Args.hasArg(OPT_cfguard_no_checks);
1006
44.9k
  Opts.ControlFlowGuard = Args.hasArg(OPT_cfguard);
1007
44.9k
1008
44.9k
  Opts.DisableGCov = Args.hasArg(OPT_test_coverage);
1009
44.9k
  Opts.EmitGcovArcs = Args.hasArg(OPT_femit_coverage_data);
1010
44.9k
  Opts.EmitGcovNotes = Args.hasArg(OPT_femit_coverage_notes);
1011
44.9k
  if (Opts.EmitGcovArcs || 
Opts.EmitGcovNotes44.9k
) {
1012
14
    Opts.CoverageDataFile =
1013
14
        std::string(Args.getLastArgValue(OPT_coverage_data_file));
1014
14
    Opts.CoverageNotesFile =
1015
14
        std::string(Args.getLastArgValue(OPT_coverage_notes_file));
1016
14
    Opts.CoverageExtraChecksum = Args.hasArg(OPT_coverage_cfg_checksum);
1017
14
    Opts.CoverageNoFunctionNamesInData =
1018
14
        Args.hasArg(OPT_coverage_no_function_names_in_data);
1019
14
    Opts.ProfileFilterFiles =
1020
14
        std::string(Args.getLastArgValue(OPT_fprofile_filter_files_EQ));
1021
14
    Opts.ProfileExcludeFiles =
1022
14
        std::string(Args.getLastArgValue(OPT_fprofile_exclude_files_EQ));
1023
14
    Opts.CoverageExitBlockBeforeBody =
1024
14
        Args.hasArg(OPT_coverage_exit_block_before_body);
1025
14
    if (Args.hasArg(OPT_coverage_version_EQ)) {
1026
0
      StringRef CoverageVersion = Args.getLastArgValue(OPT_coverage_version_EQ);
1027
0
      if (CoverageVersion.size() != 4) {
1028
0
        Diags.Report(diag::err_drv_invalid_value)
1029
0
            << Args.getLastArg(OPT_coverage_version_EQ)->getAsString(Args)
1030
0
            << CoverageVersion;
1031
0
      } else {
1032
0
        memcpy(Opts.CoverageVersion, CoverageVersion.data(), 4);
1033
0
      }
1034
0
    }
1035
14
  }
1036
44.9k
  // Handle -fembed-bitcode option.
1037
44.9k
  if (Arg *A = Args.getLastArg(OPT_fembed_bitcode_EQ)) {
1038
19
    StringRef Name = A->getValue();
1039
19
    unsigned Model = llvm::StringSwitch<unsigned>(Name)
1040
19
        .Case("off", CodeGenOptions::Embed_Off)
1041
19
        .Case("all", CodeGenOptions::Embed_All)
1042
19
        .Case("bitcode", CodeGenOptions::Embed_Bitcode)
1043
19
        .Case("marker", CodeGenOptions::Embed_Marker)
1044
19
        .Default(~0U);
1045
19
    if (Model == ~0U) {
1046
0
      Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
1047
0
      Success = false;
1048
0
    } else
1049
19
      Opts.setEmbedBitcode(
1050
19
          static_cast<CodeGenOptions::EmbedBitcodeKind>(Model));
1051
19
  }
1052
44.9k
  // FIXME: For backend options that are not yet recorded as function
1053
44.9k
  // attributes in the IR, keep track of them so we can embed them in a
1054
44.9k
  // separate data section and use them when building the bitcode.
1055
44.9k
  if (Opts.getEmbedBitcode() == CodeGenOptions::Embed_All) {
1056
91
    for (const auto &A : Args) {
1057
91
      // Do not encode output and input.
1058
91
      if (A->getOption().getID() == options::OPT_o ||
1059
91
          
A->getOption().getID() == options::OPT_INPUT80
||
1060
91
          
A->getOption().getID() == options::OPT_x69
||
1061
91
          
A->getOption().getID() == options::OPT_fembed_bitcode58
||
1062
91
          
(58
A->getOption().getGroup().isValid()58
&&
1063
58
           
A->getOption().getGroup().getID() == options::OPT_W_Group25
))
1064
33
        continue;
1065
58
      ArgStringList ASL;
1066
58
      A->render(Args, ASL);
1067
79
      for (const auto &arg : ASL) {
1068
79
        StringRef ArgStr(arg);
1069
79
        Opts.CmdArgs.insert(Opts.CmdArgs.end(), ArgStr.begin(), ArgStr.end());
1070
79
        // using \00 to separate each commandline options.
1071
79
        Opts.CmdArgs.push_back('\0');
1072
79
      }
1073
58
    }
1074
11
  }
1075
44.9k
1076
44.9k
  Opts.PreserveVec3Type = Args.hasArg(OPT_fpreserve_vec3_type);
1077
44.9k
  Opts.InstrumentFunctions = Args.hasArg(OPT_finstrument_functions);
1078
44.9k
  Opts.InstrumentFunctionsAfterInlining =
1079
44.9k
      Args.hasArg(OPT_finstrument_functions_after_inlining);
1080
44.9k
  Opts.InstrumentFunctionEntryBare =
1081
44.9k
      Args.hasArg(OPT_finstrument_function_entry_bare);
1082
44.9k
1083
44.9k
  Opts.XRayInstrumentFunctions =
1084
44.9k
      Args.hasArg(OPT_fxray_instrument);
1085
44.9k
  Opts.XRayAlwaysEmitCustomEvents =
1086
44.9k
      Args.hasArg(OPT_fxray_always_emit_customevents);
1087
44.9k
  Opts.XRayAlwaysEmitTypedEvents =
1088
44.9k
      Args.hasArg(OPT_fxray_always_emit_typedevents);
1089
44.9k
  Opts.XRayInstructionThreshold =
1090
44.9k
      getLastArgIntValue(Args, OPT_fxray_instruction_threshold_EQ, 200, Diags);
1091
44.9k
  Opts.XRayIgnoreLoops = Args.hasArg(OPT_fxray_ignore_loops);
1092
44.9k
1093
44.9k
  auto XRayInstrBundles =
1094
44.9k
      Args.getAllArgValues(OPT_fxray_instrumentation_bundle);
1095
44.9k
  if (XRayInstrBundles.empty())
1096
44.9k
    Opts.XRayInstrumentationBundle.Mask = XRayInstrKind::All;
1097
18
  else
1098
18
    for (const auto &A : XRayInstrBundles)
1099
20
      parseXRayInstrumentationBundle("-fxray-instrumentation-bundle=", A, Args,
1100
20
                                     Diags, Opts.XRayInstrumentationBundle);
1101
44.9k
1102
44.9k
  Opts.PatchableFunctionEntryCount =
1103
44.9k
      getLastArgIntValue(Args, OPT_fpatchable_function_entry_EQ, 0, Diags);
1104
44.9k
  Opts.PatchableFunctionEntryOffset = getLastArgIntValue(
1105
44.9k
      Args, OPT_fpatchable_function_entry_offset_EQ, 0, Diags);
1106
44.9k
  Opts.InstrumentForProfiling = Args.hasArg(OPT_pg);
1107
44.9k
  Opts.CallFEntry = Args.hasArg(OPT_mfentry);
1108
44.9k
  Opts.MNopMCount = Args.hasArg(OPT_mnop_mcount);
1109
44.9k
  Opts.RecordMCount = Args.hasArg(OPT_mrecord_mcount);
1110
44.9k
  Opts.PackedStack = Args.hasArg(OPT_mpacked_stack);
1111
44.9k
  Opts.EmitOpenCLArgMetadata = Args.hasArg(OPT_cl_kernel_arg_info);
1112
44.9k
1113
44.9k
  if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
1114
8
    StringRef Name = A->getValue();
1115
8
    if (Name == "full") {
1116
1
      Opts.CFProtectionReturn = 1;
1117
1
      Opts.CFProtectionBranch = 1;
1118
7
    } else if (Name == "return")
1119
1
      Opts.CFProtectionReturn = 1;
1120
6
    else if (Name == "branch")
1121
6
      Opts.CFProtectionBranch = 1;
1122
0
    else if (Name != "none") {
1123
0
      Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
1124
0
      Success = false;
1125
0
    }
1126
8
  }
1127
44.9k
1128
44.9k
  if (const Arg *A = Args.getLastArg(OPT_compress_debug_sections,
1129
1
                                     OPT_compress_debug_sections_EQ)) {
1130
1
    if (A->getOption().getID() == OPT_compress_debug_sections) {
1131
0
      // TODO: be more clever about the compression type auto-detection
1132
0
      Opts.setCompressDebugSections(llvm::DebugCompressionType::GNU);
1133
1
    } else {
1134
1
      auto DCT = llvm::StringSwitch<llvm::DebugCompressionType>(A->getValue())
1135
1
                     .Case("none", llvm::DebugCompressionType::None)
1136
1
                     .Case("zlib", llvm::DebugCompressionType::Z)
1137
1
                     .Case("zlib-gnu", llvm::DebugCompressionType::GNU)
1138
1
                     .Default(llvm::DebugCompressionType::None);
1139
1
      Opts.setCompressDebugSections(DCT);
1140
1
    }
1141
1
  }
1142
44.9k
1143
44.9k
  Opts.RelaxELFRelocations = Args.hasArg(OPT_mrelax_relocations);
1144
44.9k
  Opts.DebugCompilationDir =
1145
44.9k
      std::string(Args.getLastArgValue(OPT_fdebug_compilation_dir));
1146
44.9k
  for (auto *A :
1147
44.9k
       Args.filtered(OPT_mlink_bitcode_file, OPT_mlink_builtin_bitcode)) {
1148
14
    CodeGenOptions::BitcodeFileToLink F;
1149
14
    F.Filename = A->getValue();
1150
14
    if (A->getOption().matches(OPT_mlink_builtin_bitcode)) {
1151
8
      F.LinkFlags = llvm::Linker::Flags::LinkOnlyNeeded;
1152
8
      // When linking CUDA bitcode, propagate function attributes so that
1153
8
      // e.g. libdevice gets fast-math attrs if we're building with fast-math.
1154
8
      F.PropagateAttrs = true;
1155
8
      F.Internalize = true;
1156
8
    }
1157
14
    Opts.LinkBitcodeFiles.push_back(F);
1158
14
  }
1159
44.9k
  Opts.SanitizeCoverageType =
1160
44.9k
      getLastArgIntValue(Args, OPT_fsanitize_coverage_type, 0, Diags);
1161
44.9k
  Opts.SanitizeCoverageIndirectCalls =
1162
44.9k
      Args.hasArg(OPT_fsanitize_coverage_indirect_calls);
1163
44.9k
  Opts.SanitizeCoverageTraceBB = Args.hasArg(OPT_fsanitize_coverage_trace_bb);
1164
44.9k
  Opts.SanitizeCoverageTraceCmp = Args.hasArg(OPT_fsanitize_coverage_trace_cmp);
1165
44.9k
  Opts.SanitizeCoverageTraceDiv = Args.hasArg(OPT_fsanitize_coverage_trace_div);
1166
44.9k
  Opts.SanitizeCoverageTraceGep = Args.hasArg(OPT_fsanitize_coverage_trace_gep);
1167
44.9k
  Opts.SanitizeCoverage8bitCounters =
1168
44.9k
      Args.hasArg(OPT_fsanitize_coverage_8bit_counters);
1169
44.9k
  Opts.SanitizeCoverageTracePC = Args.hasArg(OPT_fsanitize_coverage_trace_pc);
1170
44.9k
  Opts.SanitizeCoverageTracePCGuard =
1171
44.9k
      Args.hasArg(OPT_fsanitize_coverage_trace_pc_guard);
1172
44.9k
  Opts.SanitizeCoverageNoPrune = Args.hasArg(OPT_fsanitize_coverage_no_prune);
1173
44.9k
  Opts.SanitizeCoverageInline8bitCounters =
1174
44.9k
      Args.hasArg(OPT_fsanitize_coverage_inline_8bit_counters);
1175
44.9k
  Opts.SanitizeCoveragePCTable = Args.hasArg(OPT_fsanitize_coverage_pc_table);
1176
44.9k
  Opts.SanitizeCoverageStackDepth =
1177
44.9k
      Args.hasArg(OPT_fsanitize_coverage_stack_depth);
1178
44.9k
  Opts.SanitizeMemoryTrackOrigins =
1179
44.9k
      getLastArgIntValue(Args, OPT_fsanitize_memory_track_origins_EQ, 0, Diags);
1180
44.9k
  Opts.SanitizeMemoryUseAfterDtor =
1181
44.9k
      Args.hasFlag(OPT_fsanitize_memory_use_after_dtor,
1182
44.9k
                   OPT_fno_sanitize_memory_use_after_dtor,
1183
44.9k
                   false);
1184
44.9k
  Opts.SanitizeMinimalRuntime = Args.hasArg(OPT_fsanitize_minimal_runtime);
1185
44.9k
  Opts.SanitizeCfiCrossDso = Args.hasArg(OPT_fsanitize_cfi_cross_dso);
1186
44.9k
  Opts.SanitizeCfiICallGeneralizePointers =
1187
44.9k
      Args.hasArg(OPT_fsanitize_cfi_icall_generalize_pointers);
1188
44.9k
  Opts.SanitizeCfiCanonicalJumpTables =
1189
44.9k
      Args.hasArg(OPT_fsanitize_cfi_canonical_jump_tables);
1190
44.9k
  Opts.SanitizeStats = Args.hasArg(OPT_fsanitize_stats);
1191
44.9k
  if (Arg *A = Args.getLastArg(
1192
1
          OPT_fsanitize_address_poison_custom_array_cookie,
1193
1
          OPT_fno_sanitize_address_poison_custom_array_cookie)) {
1194
1
    Opts.SanitizeAddressPoisonCustomArrayCookie =
1195
1
        A->getOption().getID() ==
1196
1
        OPT_fsanitize_address_poison_custom_array_cookie;
1197
1
  }
1198
44.9k
  if (Arg *A = Args.getLastArg(OPT_fsanitize_address_use_after_scope,
1199
27
                               OPT_fno_sanitize_address_use_after_scope)) {
1200
27
    Opts.SanitizeAddressUseAfterScope =
1201
27
        A->getOption().getID() == OPT_fsanitize_address_use_after_scope;
1202
27
  }
1203
44.9k
  Opts.SanitizeAddressGlobalsDeadStripping =
1204
44.9k
      Args.hasArg(OPT_fsanitize_address_globals_dead_stripping);
1205
44.9k
  if (Arg *A = Args.getLastArg(OPT_fsanitize_address_use_odr_indicator,
1206
5
                               OPT_fno_sanitize_address_use_odr_indicator)) {
1207
5
    Opts.SanitizeAddressUseOdrIndicator =
1208
5
        A->getOption().getID() == OPT_fsanitize_address_use_odr_indicator;
1209
5
  }
1210
44.9k
  Opts.SSPBufferSize =
1211
44.9k
      getLastArgIntValue(Args, OPT_stack_protector_buffer_size, 8, Diags);
1212
44.9k
  Opts.StackRealignment = Args.hasArg(OPT_mstackrealign);
1213
44.9k
  if (Arg *A = Args.getLastArg(OPT_mstack_alignment)) {
1214
1
    StringRef Val = A->getValue();
1215
1
    unsigned StackAlignment = Opts.StackAlignment;
1216
1
    Val.getAsInteger(10, StackAlignment);
1217
1
    Opts.StackAlignment = StackAlignment;
1218
1
  }
1219
44.9k
1220
44.9k
  if (Arg *A = Args.getLastArg(OPT_mstack_probe_size)) {
1221
2
    StringRef Val = A->getValue();
1222
2
    unsigned StackProbeSize = Opts.StackProbeSize;
1223
2
    Val.getAsInteger(0, StackProbeSize);
1224
2
    Opts.StackProbeSize = StackProbeSize;
1225
2
  }
1226
44.9k
1227
44.9k
  Opts.NoStackArgProbe = Args.hasArg(OPT_mno_stack_arg_probe);
1228
44.9k
1229
44.9k
  Opts.StackClashProtector = Args.hasArg(OPT_fstack_clash_protection);
1230
44.9k
1231
44.9k
  if (Arg *A = Args.getLastArg(OPT_fobjc_dispatch_method_EQ)) {
1232
15
    StringRef Name = A->getValue();
1233
15
    unsigned Method = llvm::StringSwitch<unsigned>(Name)
1234
15
      .Case("legacy", CodeGenOptions::Legacy)
1235
15
      .Case("non-legacy", CodeGenOptions::NonLegacy)
1236
15
      .Case("mixed", CodeGenOptions::Mixed)
1237
15
      .Default(~0U);
1238
15
    if (Method == ~0U) {
1239
0
      Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
1240
0
      Success = false;
1241
15
    } else {
1242
15
      Opts.setObjCDispatchMethod(
1243
15
        static_cast<CodeGenOptions::ObjCDispatchMethodKind>(Method));
1244
15
    }
1245
15
  }
1246
44.9k
1247
44.9k
1248
44.9k
  if (Args.hasArg(OPT_fno_objc_convert_messages_to_runtime_calls))
1249
1
    Opts.ObjCConvertMessagesToRuntimeCalls = 0;
1250
44.9k
1251
44.9k
  if (Args.getLastArg(OPT_femulated_tls) ||
1252
44.9k
      
Args.getLastArg(OPT_fno_emulated_tls)44.9k
) {
1253
3
    Opts.ExplicitEmulatedTLS = true;
1254
3
    Opts.EmulatedTLS =
1255
3
        Args.hasFlag(OPT_femulated_tls, OPT_fno_emulated_tls, false);
1256
3
  }
1257
44.9k
1258
44.9k
  if (Arg *A = Args.getLastArg(OPT_ftlsmodel_EQ)) {
1259
5
    StringRef Name = A->getValue();
1260
5
    unsigned Model = llvm::StringSwitch<unsigned>(Name)
1261
5
        .Case("global-dynamic", CodeGenOptions::GeneralDynamicTLSModel)
1262
5
        .Case("local-dynamic", CodeGenOptions::LocalDynamicTLSModel)
1263
5
        .Case("initial-exec", CodeGenOptions::InitialExecTLSModel)
1264
5
        .Case("local-exec", CodeGenOptions::LocalExecTLSModel)
1265
5
        .Default(~0U);
1266
5
    if (Model == ~0U) {
1267
0
      Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
1268
0
      Success = false;
1269
5
    } else {
1270
5
      Opts.setDefaultTLSModel(static_cast<CodeGenOptions::TLSModel>(Model));
1271
5
    }
1272
5
  }
1273
44.9k
1274
44.9k
  Opts.TLSSize = getLastArgIntValue(Args, OPT_mtls_size_EQ, 0, Diags);
1275
44.9k
1276
44.9k
  if (Arg *A = Args.getLastArg(OPT_fdenormal_fp_math_EQ)) {
1277
633
    StringRef Val = A->getValue();
1278
633
    Opts.FPDenormalMode = llvm::parseDenormalFPAttribute(Val);
1279
633
    if (!Opts.FPDenormalMode.isValid())
1280
0
      Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
1281
633
  }
1282
44.9k
1283
44.9k
  if (Arg *A = Args.getLastArg(OPT_fdenormal_fp_math_f32_EQ)) {
1284
637
    StringRef Val = A->getValue();
1285
637
    Opts.FP32DenormalMode = llvm::parseDenormalFPAttribute(Val);
1286
637
    if (!Opts.FP32DenormalMode.isValid())
1287
0
      Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
1288
637
  }
1289
44.9k
1290
44.9k
  if (Arg *A = Args.getLastArg(OPT_fpcc_struct_return, OPT_freg_struct_return)) {
1291
6
    if (A->getOption().matches(OPT_fpcc_struct_return)) {
1292
3
      Opts.setStructReturnConvention(CodeGenOptions::SRCK_OnStack);
1293
3
    } else {
1294
3
      assert(A->getOption().matches(OPT_freg_struct_return));
1295
3
      Opts.setStructReturnConvention(CodeGenOptions::SRCK_InRegs);
1296
3
    }
1297
6
  }
1298
44.9k
1299
44.9k
  Opts.DependentLibraries = Args.getAllArgValues(OPT_dependent_lib);
1300
44.9k
  Opts.LinkerOptions = Args.getAllArgValues(OPT_linker_option);
1301
44.9k
  bool NeedLocTracking = false;
1302
44.9k
1303
44.9k
  Opts.OptRecordFile = std::string(Args.getLastArgValue(OPT_opt_record_file));
1304
44.9k
  if (!Opts.OptRecordFile.empty())
1305
11
    NeedLocTracking = true;
1306
44.9k
1307
44.9k
  if (Arg *A = Args.getLastArg(OPT_opt_record_passes)) {
1308
3
    Opts.OptRecordPasses = A->getValue();
1309
3
    NeedLocTracking = true;
1310
3
  }
1311
44.9k
1312
44.9k
  if (Arg *A = Args.getLastArg(OPT_opt_record_format)) {
1313
4
    Opts.OptRecordFormat = A->getValue();
1314
4
    NeedLocTracking = true;
1315
4
  }
1316
44.9k
1317
44.9k
  if (Arg *A = Args.getLastArg(OPT_Rpass_EQ)) {
1318
32
    Opts.OptimizationRemarkPattern =
1319
32
        GenerateOptimizationRemarkRegex(Diags, Args, A);
1320
32
    NeedLocTracking = true;
1321
32
  }
1322
44.9k
1323
44.9k
  if (Arg *A = Args.getLastArg(OPT_Rpass_missed_EQ)) {
1324
14
    Opts.OptimizationRemarkMissedPattern =
1325
14
        GenerateOptimizationRemarkRegex(Diags, Args, A);
1326
14
    NeedLocTracking = true;
1327
14
  }
1328
44.9k
1329
44.9k
  if (Arg *A = Args.getLastArg(OPT_Rpass_analysis_EQ)) {
1330
22
    Opts.OptimizationRemarkAnalysisPattern =
1331
22
        GenerateOptimizationRemarkRegex(Diags, Args, A);
1332
22
    NeedLocTracking = true;
1333
22
  }
1334
44.9k
1335
44.9k
  Opts.DiagnosticsWithHotness =
1336
44.9k
      Args.hasArg(options::OPT_fdiagnostics_show_hotness);
1337
44.9k
  bool UsingSampleProfile = !Opts.SampleProfileFile.empty();
1338
44.9k
  bool UsingProfile = UsingSampleProfile ||
1339
44.9k
      
(Opts.getProfileUse() != CodeGenOptions::ProfileNone)44.9k
;
1340
44.9k
1341
44.9k
  if (Opts.DiagnosticsWithHotness && 
!UsingProfile14
&&
1342
44.9k
      // An IR file will contain PGO as metadata
1343
44.9k
      
IK.getLanguage() != Language::LLVM_IR4
)
1344
2
    Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo)
1345
2
        << "-fdiagnostics-show-hotness";
1346
44.9k
1347
44.9k
  Opts.DiagnosticsHotnessThreshold = getLastArgUInt64Value(
1348
44.9k
      Args, options::OPT_fdiagnostics_hotness_threshold_EQ, 0);
1349
44.9k
  if (Opts.DiagnosticsHotnessThreshold > 0 && 
!UsingProfile8
)
1350
2
    Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo)
1351
2
        << "-fdiagnostics-hotness-threshold=";
1352
44.9k
1353
44.9k
  // If the user requested to use a sample profile for PGO, then the
1354
44.9k
  // backend will need to track source location information so the profile
1355
44.9k
  // can be incorporated into the IR.
1356
44.9k
  if (UsingSampleProfile)
1357
12
    NeedLocTracking = true;
1358
44.9k
1359
44.9k
  // If the user requested a flag that requires source locations available in
1360
44.9k
  // the backend, make sure that the backend tracks source location information.
1361
44.9k
  if (NeedLocTracking && 
Opts.getDebugInfo() == codegenoptions::NoDebugInfo57
)
1362
52
    Opts.setDebugInfo(codegenoptions::LocTrackingOnly);
1363
44.9k
1364
44.9k
  Opts.RewriteMapFiles = Args.getAllArgValues(OPT_frewrite_map_file);
1365
44.9k
1366
44.9k
  // Parse -fsanitize-recover= arguments.
1367
44.9k
  // FIXME: Report unrecoverable sanitizers incorrectly specified here.
1368
44.9k
  parseSanitizerKinds("-fsanitize-recover=",
1369
44.9k
                      Args.getAllArgValues(OPT_fsanitize_recover_EQ), Diags,
1370
44.9k
                      Opts.SanitizeRecover);
1371
44.9k
  parseSanitizerKinds("-fsanitize-trap=",
1372
44.9k
                      Args.getAllArgValues(OPT_fsanitize_trap_EQ), Diags,
1373
44.9k
                      Opts.SanitizeTrap);
1374
44.9k
1375
44.9k
  Opts.CudaGpuBinaryFileName =
1376
44.9k
      std::string(Args.getLastArgValue(OPT_fcuda_include_gpubinary));
1377
44.9k
1378
44.9k
  Opts.Backchain = Args.hasArg(OPT_mbackchain);
1379
44.9k
1380
44.9k
  Opts.EmitCheckPathComponentsToStrip = getLastArgIntValue(
1381
44.9k
      Args, OPT_fsanitize_undefined_strip_path_components_EQ, 0, Diags);
1382
44.9k
1383
44.9k
  Opts.EmitVersionIdentMetadata = Args.hasFlag(OPT_Qy, OPT_Qn, true);
1384
44.9k
1385
44.9k
  Opts.Addrsig = Args.hasArg(OPT_faddrsig);
1386
44.9k
1387
44.9k
  if (Arg *A = Args.getLastArg(OPT_msign_return_address_EQ)) {
1388
21
    StringRef SignScope = A->getValue();
1389
21
1390
21
    if (SignScope.equals_lower("none"))
1391
5
      Opts.setSignReturnAddress(CodeGenOptions::SignReturnAddressScope::None);
1392
16
    else if (SignScope.equals_lower("all"))
1393
9
      Opts.setSignReturnAddress(CodeGenOptions::SignReturnAddressScope::All);
1394
7
    else if (SignScope.equals_lower("non-leaf"))
1395
7
      Opts.setSignReturnAddress(
1396
7
          CodeGenOptions::SignReturnAddressScope::NonLeaf);
1397
0
    else
1398
0
      Diags.Report(diag::err_drv_invalid_value)
1399
0
          << A->getAsString(Args) << SignScope;
1400
21
1401
21
    if (Arg *A = Args.getLastArg(OPT_msign_return_address_key_EQ)) {
1402
21
      StringRef SignKey = A->getValue();
1403
21
      if (!SignScope.empty() && !SignKey.empty()) {
1404
21
        if (SignKey.equals_lower("a_key"))
1405
16
          Opts.setSignReturnAddressKey(
1406
16
              CodeGenOptions::SignReturnAddressKeyValue::AKey);
1407
5
        else if (SignKey.equals_lower("b_key"))
1408
5
          Opts.setSignReturnAddressKey(
1409
5
              CodeGenOptions::SignReturnAddressKeyValue::BKey);
1410
0
        else
1411
0
          Diags.Report(diag::err_drv_invalid_value)
1412
0
              << A->getAsString(Args) << SignKey;
1413
21
      }
1414
21
    }
1415
21
  }
1416
44.9k
1417
44.9k
  Opts.BranchTargetEnforcement = Args.hasArg(OPT_mbranch_target_enforce);
1418
44.9k
1419
44.9k
  Opts.KeepStaticConsts = Args.hasArg(OPT_fkeep_static_consts);
1420
44.9k
1421
44.9k
  Opts.SpeculativeLoadHardening = Args.hasArg(OPT_mspeculative_load_hardening);
1422
44.9k
1423
44.9k
  Opts.DefaultFunctionAttrs = Args.getAllArgValues(OPT_default_function_attr);
1424
44.9k
1425
44.9k
  Opts.PassPlugins = Args.getAllArgValues(OPT_fpass_plugin_EQ);
1426
44.9k
1427
44.9k
  Opts.SymbolPartition =
1428
44.9k
      std::string(Args.getLastArgValue(OPT_fsymbol_partition_EQ));
1429
44.9k
1430
44.9k
  Opts.ForceAAPCSBitfieldLoad = Args.hasArg(OPT_ForceAAPCSBitfieldLoad);
1431
44.9k
  return Success;
1432
44.9k
}
1433
1434
static void ParseDependencyOutputArgs(DependencyOutputOptions &Opts,
1435
44.9k
                                      ArgList &Args) {
1436
44.9k
  Opts.OutputFile = std::string(Args.getLastArgValue(OPT_dependency_file));
1437
44.9k
  Opts.Targets = Args.getAllArgValues(OPT_MT);
1438
44.9k
  Opts.IncludeSystemHeaders = Args.hasArg(OPT_sys_header_deps);
1439
44.9k
  Opts.IncludeModuleFiles = Args.hasArg(OPT_module_file_deps);
1440
44.9k
  Opts.UsePhonyTargets = Args.hasArg(OPT_MP);
1441
44.9k
  Opts.ShowHeaderIncludes = Args.hasArg(OPT_H);
1442
44.9k
  Opts.HeaderIncludeOutputFile =
1443
44.9k
      std::string(Args.getLastArgValue(OPT_header_include_file));
1444
44.9k
  Opts.AddMissingHeaderDeps = Args.hasArg(OPT_MG);
1445
44.9k
  if (Args.hasArg(OPT_show_includes)) {
1446
10
    // Writing both /showIncludes and preprocessor output to stdout
1447
10
    // would produce interleaved output, so use stderr for /showIncludes.
1448
10
    // This behaves the same as cl.exe, when /E, /EP or /P are passed.
1449
10
    if (Args.hasArg(options::OPT_E) || 
Args.hasArg(options::OPT_P)9
)
1450
1
      Opts.ShowIncludesDest = ShowIncludesDestination::Stderr;
1451
9
    else
1452
9
      Opts.ShowIncludesDest = ShowIncludesDestination::Stdout;
1453
44.9k
  } else {
1454
44.9k
    Opts.ShowIncludesDest = ShowIncludesDestination::None;
1455
44.9k
  }
1456
44.9k
  Opts.DOTOutputFile = std::string(Args.getLastArgValue(OPT_dependency_dot));
1457
44.9k
  Opts.ModuleDependencyOutputDir =
1458
44.9k
      std::string(Args.getLastArgValue(OPT_module_dependency_dir));
1459
44.9k
  if (Args.hasArg(OPT_MV))
1460
1
    Opts.OutputFormat = DependencyOutputFormat::NMake;
1461
44.9k
  // Add sanitizer blacklists as extra dependencies.
1462
44.9k
  // They won't be discovered by the regular preprocessor, so
1463
44.9k
  // we let make / ninja to know about this implicit dependency.
1464
44.9k
  if (
!Args.hasArg(OPT_fno_sanitize_blacklist)44.9k
) {
1465
44.9k
    for (const auto *A : Args.filtered(OPT_fsanitize_blacklist)) {
1466
29
      StringRef Val = A->getValue();
1467
29
      if (Val.find('=') == StringRef::npos)
1468
29
        Opts.ExtraDeps.push_back(std::string(Val));
1469
29
    }
1470
44.9k
    if (Opts.IncludeSystemHeaders) {
1471
2.84k
      for (const auto *A : Args.filtered(OPT_fsanitize_system_blacklist)) {
1472
3
        StringRef Val = A->getValue();
1473
3
        if (Val.find('=') == StringRef::npos)
1474
3
          Opts.ExtraDeps.push_back(std::string(Val));
1475
3
      }
1476
2.84k
    }
1477
44.9k
  }
1478
44.9k
1479
44.9k
  // Propagate the extra dependencies.
1480
44.9k
  for (const auto *A : Args.filtered(OPT_fdepfile_entry)) {
1481
4
    Opts.ExtraDeps.push_back(A->getValue());
1482
4
  }
1483
44.9k
1484
44.9k
  // Only the -fmodule-file=<file> form.
1485
44.9k
  for (const auto *A : Args.filtered(OPT_fmodule_file)) {
1486
406
    StringRef Val = A->getValue();
1487
406
    if (Val.find('=') == StringRef::npos)
1488
395
      Opts.ExtraDeps.push_back(std::string(Val));
1489
406
  }
1490
44.9k
}
1491
1492
72.5k
static bool parseShowColorsArgs(const ArgList &Args, bool DefaultColor) {
1493
72.5k
  // Color diagnostics default to auto ("on" if terminal supports) in the driver
1494
72.5k
  // but default to off in cc1, needing an explicit OPT_fdiagnostics_color.
1495
72.5k
  // Support both clang's -f[no-]color-diagnostics and gcc's
1496
72.5k
  // -f[no-]diagnostics-colors[=never|always|auto].
1497
72.5k
  enum {
1498
72.5k
    Colors_On,
1499
72.5k
    Colors_Off,
1500
72.5k
    Colors_Auto
1501
72.5k
  } ShowColors = DefaultColor ? 
Colors_Auto27.6k
:
Colors_Off44.9k
;
1502
1.89M
  for (auto *A : Args) {
1503
1.89M
    const Option &O = A->getOption();
1504
1.89M
    if (O.matches(options::OPT_fcolor_diagnostics) ||
1505
1.89M
        
O.matches(options::OPT_fdiagnostics_color)1.89M
) {
1506
20
      ShowColors = Colors_On;
1507
1.89M
    } else if (O.matches(options::OPT_fno_color_diagnostics) ||
1508
1.89M
               
O.matches(options::OPT_fno_diagnostics_color)1.89M
) {
1509
12
      ShowColors = Colors_Off;
1510
1.89M
    } else if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
1511
6
      StringRef Value(A->getValue());
1512
6
      if (Value == "always")
1513
2
        ShowColors = Colors_On;
1514
4
      else if (Value == "never")
1515
1
        ShowColors = Colors_Off;
1516
3
      else if (Value == "auto")
1517
2
        ShowColors = Colors_Auto;
1518
6
    }
1519
1.89M
  }
1520
72.5k
  return ShowColors == Colors_On ||
1521
72.5k
         
(72.5k
ShowColors == Colors_Auto72.5k
&&
1522
72.5k
          
llvm::sys::Process::StandardErrHasColors()27.6k
);
1523
72.5k
}
1524
1525
static bool checkVerifyPrefixes(const std::vector<std::string> &VerifyPrefixes,
1526
72.5k
                                DiagnosticsEngine *Diags) {
1527
72.5k
  bool Success = true;
1528
72.5k
  for (const auto &Prefix : VerifyPrefixes) {
1529
14.5k
    // Every prefix must start with a letter and contain only alphanumeric
1530
14.5k
    // characters, hyphens, and underscores.
1531
114k
    auto BadChar = llvm::find_if(Prefix, [](char C) {
1532
114k
      return !isAlphanumeric(C) && 
C != '-'54
&&
C != '_'5
;
1533
114k
    });
1534
14.5k
    if (BadChar != Prefix.end() || 
!isLetter(Prefix[0])14.5k
) {
1535
6
      Success = false;
1536
6
      if (Diags) {
1537
6
        Diags->Report(diag::err_drv_invalid_value) << "-verify=" << Prefix;
1538
6
        Diags->Report(diag::note_drv_verify_prefix_spelling);
1539
6
      }
1540
6
    }
1541
14.5k
  }
1542
72.5k
  return Success;
1543
72.5k
}
1544
1545
bool clang::ParseDiagnosticArgs(DiagnosticOptions &Opts, ArgList &Args,
1546
                                DiagnosticsEngine *Diags,
1547
72.5k
                                bool DefaultDiagColor, bool DefaultShowOpt) {
1548
72.5k
  bool Success = true;
1549
72.5k
1550
72.5k
  Opts.DiagnosticLogFile =
1551
72.5k
      std::string(Args.getLastArgValue(OPT_diagnostic_log_file));
1552
72.5k
  if (Arg *A =
1553
26
          Args.getLastArg(OPT_diagnostic_serialized_file, OPT__serialize_diags))
1554
26
    Opts.DiagnosticSerializationFile = A->getValue();
1555
72.5k
  Opts.IgnoreWarnings = Args.hasArg(OPT_w);
1556
72.5k
  Opts.NoRewriteMacros = Args.hasArg(OPT_Wno_rewrite_macros);
1557
72.5k
  Opts.Pedantic = Args.hasArg(OPT_pedantic);
1558
72.5k
  Opts.PedanticErrors = Args.hasArg(OPT_pedantic_errors);
1559
72.5k
  Opts.ShowCarets = !Args.hasArg(OPT_fno_caret_diagnostics);
1560
72.5k
  Opts.ShowColors = parseShowColorsArgs(Args, DefaultDiagColor);
1561
72.5k
  Opts.ShowColumn = !Args.hasArg(OPT_fno_show_column);
1562
72.5k
  Opts.ShowFixits = !Args.hasArg(OPT_fno_diagnostics_fixit_info);
1563
72.5k
  Opts.ShowLocation = !Args.hasArg(OPT_fno_show_source_location);
1564
72.5k
  Opts.AbsolutePath = Args.hasArg(OPT_fdiagnostics_absolute_paths);
1565
72.5k
  Opts.ShowOptionNames =
1566
72.5k
      Args.hasFlag(OPT_fdiagnostics_show_option,
1567
72.5k
                   OPT_fno_diagnostics_show_option, DefaultShowOpt);
1568
72.5k
1569
72.5k
  llvm::sys::Process::UseANSIEscapeCodes(Args.hasArg(OPT_fansi_escape_codes));
1570
72.5k
1571
72.5k
  // Default behavior is to not to show note include stacks.
1572
72.5k
  Opts.ShowNoteIncludeStack = false;
1573
72.5k
  if (Arg *A = Args.getLastArg(OPT_fdiagnostics_show_note_include_stack,
1574
8
                               OPT_fno_diagnostics_show_note_include_stack))
1575
8
    if (A->getOption().matches(OPT_fdiagnostics_show_note_include_stack))
1576
6
      Opts.ShowNoteIncludeStack = true;
1577
72.5k
1578
72.5k
  StringRef ShowOverloads =
1579
72.5k
    Args.getLastArgValue(OPT_fshow_overloads_EQ, "all");
1580
72.5k
  if (ShowOverloads == "best")
1581
6
    Opts.setShowOverloads(Ovl_Best);
1582
72.5k
  else if (ShowOverloads == "all")
1583
72.5k
    Opts.setShowOverloads(Ovl_All);
1584
18.4E
  else {
1585
18.4E
    Success = false;
1586
18.4E
    if (Diags)
1587
0
      Diags->Report(diag::err_drv_invalid_value)
1588
0
      << Args.getLastArg(OPT_fshow_overloads_EQ)->getAsString(Args)
1589
0
      << ShowOverloads;
1590
18.4E
  }
1591
72.5k
1592
72.5k
  StringRef ShowCategory =
1593
72.5k
    Args.getLastArgValue(OPT_fdiagnostics_show_category, "none");
1594
72.5k
  if (ShowCategory == "none")
1595
72.5k
    Opts.ShowCategories = 0;
1596
2
  else if (ShowCategory == "id")
1597
1
    Opts.ShowCategories = 1;
1598
1
  else if (ShowCategory == "name")
1599
2
    Opts.ShowCategories = 2;
1600
18.4E
  else {
1601
18.4E
    Success = false;
1602
18.4E
    if (Diags)
1603
0
      Diags->Report(diag::err_drv_invalid_value)
1604
0
      << Args.getLastArg(OPT_fdiagnostics_show_category)->getAsString(Args)
1605
0
      << ShowCategory;
1606
18.4E
  }
1607
72.5k
1608
72.5k
  StringRef Format =
1609
72.5k
    Args.getLastArgValue(OPT_fdiagnostics_format, "clang");
1610
72.5k
  if (Format == "clang")
1611
72.4k
    Opts.setFormat(DiagnosticOptions::Clang);
1612
53
  else if (Format == "msvc")
1613
48
    Opts.setFormat(DiagnosticOptions::MSVC);
1614
5
  else if (Format == "msvc-fallback") {
1615
5
    Opts.setFormat(DiagnosticOptions::MSVC);
1616
5
    Opts.CLFallbackMode = true;
1617
5
  } else 
if (0
Format == "vi"0
)
1618
2
    Opts.setFormat(DiagnosticOptions::Vi);
1619
18.4E
  else {
1620
18.4E
    Success = false;
1621
18.4E
    if (Diags)
1622
0
      Diags->Report(diag::err_drv_invalid_value)
1623
0
      << Args.getLastArg(OPT_fdiagnostics_format)->getAsString(Args)
1624
0
      << Format;
1625
18.4E
  }
1626
72.5k
1627
72.5k
  Opts.ShowSourceRanges = Args.hasArg(OPT_fdiagnostics_print_source_range_info);
1628
72.5k
  Opts.ShowParseableFixits = Args.hasArg(OPT_fdiagnostics_parseable_fixits);
1629
72.5k
  Opts.ShowPresumedLoc = !Args.hasArg(OPT_fno_diagnostics_use_presumed_location);
1630
72.5k
  Opts.VerifyDiagnostics = Args.hasArg(OPT_verify) || 
Args.hasArg(OPT_verify_EQ)59.0k
;
1631
72.5k
  Opts.VerifyPrefixes = Args.getAllArgValues(OPT_verify_EQ);
1632
72.5k
  if (Args.hasArg(OPT_verify))
1633
13.4k
    Opts.VerifyPrefixes.push_back("expected");
1634
72.5k
  // Keep VerifyPrefixes in its original order for the sake of diagnostics, and
1635
72.5k
  // then sort it to prepare for fast lookup using std::binary_search.
1636
72.5k
  if (!checkVerifyPrefixes(Opts.VerifyPrefixes, Diags)) {
1637
2
    Opts.VerifyDiagnostics = false;
1638
2
    Success = false;
1639
2
  }
1640
72.5k
  else
1641
72.5k
    llvm::sort(Opts.VerifyPrefixes);
1642
72.5k
  DiagnosticLevelMask DiagMask = DiagnosticLevelMask::None;
1643
72.5k
  Success &= parseDiagnosticLevelMask("-verify-ignore-unexpected=",
1644
72.5k
    Args.getAllArgValues(OPT_verify_ignore_unexpected_EQ),
1645
72.5k
    Diags, DiagMask);
1646
72.5k
  if (Args.hasArg(OPT_verify_ignore_unexpected))
1647
3
    DiagMask = DiagnosticLevelMask::All;
1648
72.5k
  Opts.setVerifyIgnoreUnexpected(DiagMask);
1649
72.5k
  Opts.ElideType = !Args.hasArg(OPT_fno_elide_type);
1650
72.5k
  Opts.ShowTemplateTree = Args.hasArg(OPT_fdiagnostics_show_template_tree);
1651
72.5k
  Opts.ErrorLimit = getLastArgIntValue(Args, OPT_ferror_limit, 0, Diags);
1652
72.5k
  Opts.MacroBacktraceLimit =
1653
72.5k
      getLastArgIntValue(Args, OPT_fmacro_backtrace_limit,
1654
72.5k
                         DiagnosticOptions::DefaultMacroBacktraceLimit, Diags);
1655
72.5k
  Opts.TemplateBacktraceLimit = getLastArgIntValue(
1656
72.5k
      Args, OPT_ftemplate_backtrace_limit,
1657
72.5k
      DiagnosticOptions::DefaultTemplateBacktraceLimit, Diags);
1658
72.5k
  Opts.ConstexprBacktraceLimit = getLastArgIntValue(
1659
72.5k
      Args, OPT_fconstexpr_backtrace_limit,
1660
72.5k
      DiagnosticOptions::DefaultConstexprBacktraceLimit, Diags);
1661
72.5k
  Opts.SpellCheckingLimit = getLastArgIntValue(
1662
72.5k
      Args, OPT_fspell_checking_limit,
1663
72.5k
      DiagnosticOptions::DefaultSpellCheckingLimit, Diags);
1664
72.5k
  Opts.SnippetLineLimit = getLastArgIntValue(
1665
72.5k
      Args, OPT_fcaret_diagnostics_max_lines,
1666
72.5k
      DiagnosticOptions::DefaultSnippetLineLimit, Diags);
1667
72.5k
  Opts.TabStop = getLastArgIntValue(Args, OPT_ftabstop,
1668
72.5k
                                    DiagnosticOptions::DefaultTabStop, Diags);
1669
72.5k
  if (Opts.TabStop == 0 || Opts.TabStop > DiagnosticOptions::MaxTabStop) {
1670
0
    Opts.TabStop = DiagnosticOptions::DefaultTabStop;
1671
0
    if (Diags)
1672
0
      Diags->Report(diag::warn_ignoring_ftabstop_value)
1673
0
      << Opts.TabStop << DiagnosticOptions::DefaultTabStop;
1674
0
  }
1675
72.5k
  Opts.MessageLength = getLastArgIntValue(Args, OPT_fmessage_length, 0, Diags);
1676
72.5k
  addDiagnosticArgs(Args, OPT_W_Group, OPT_W_value_Group, Opts.Warnings);
1677
72.5k
  addDiagnosticArgs(Args, OPT_R_Group, OPT_R_value_Group, Opts.Remarks);
1678
72.5k
1679
72.5k
  return Success;
1680
72.5k
}
1681
1682
44.9k
static void ParseFileSystemArgs(FileSystemOptions &Opts, ArgList &Args) {
1683
44.9k
  Opts.WorkingDir = std::string(Args.getLastArgValue(OPT_working_directory));
1684
44.9k
}
1685
1686
/// Parse the argument to the -ftest-module-file-extension
1687
/// command-line argument.
1688
///
1689
/// \returns true on error, false on success.
1690
static bool parseTestModuleFileExtensionArg(StringRef Arg,
1691
                                            std::string &BlockName,
1692
                                            unsigned &MajorVersion,
1693
                                            unsigned &MinorVersion,
1694
                                            bool &Hashed,
1695
16
                                            std::string &UserInfo) {
1696
16
  SmallVector<StringRef, 5> Args;
1697
16
  Arg.split(Args, ':', 5);
1698
16
  if (Args.size() < 5)
1699
0
    return true;
1700
16
1701
16
  BlockName = std::string(Args[0]);
1702
16
  if (Args[1].getAsInteger(10, MajorVersion)) 
return true0
;
1703
16
  if (Args[2].getAsInteger(10, MinorVersion)) 
return true0
;
1704
16
  if (Args[3].getAsInteger(2, Hashed)) 
return true0
;
1705
16
  if (Args.size() > 4)
1706
16
    UserInfo = std::string(Args[4]);
1707
16
  return false;
1708
16
}
1709
1710
static InputKind ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args,
1711
                                   DiagnosticsEngine &Diags,
1712
44.9k
                                   bool &IsHeaderFile) {
1713
44.9k
  Opts.ProgramAction = frontend::ParseSyntaxOnly;
1714
44.9k
  if (const Arg *A = Args.getLastArg(OPT_Action_Group)) {
1715
40.9k
    switch (A->getOption().getID()) {
1716
0
    default:
1717
0
      llvm_unreachable("Invalid option in group!");
1718
0
    case OPT_ast_list:
1719
0
      Opts.ProgramAction = frontend::ASTDeclList; break;
1720
29
    case OPT_ast_dump_all_EQ:
1721
29
    case OPT_ast_dump_EQ: {
1722
29
      unsigned Val = llvm::StringSwitch<unsigned>(A->getValue())
1723
29
                         .CaseLower("default", ADOF_Default)
1724
29
                         .CaseLower("json", ADOF_JSON)
1725
29
                         .Default(std::numeric_limits<unsigned>::max());
1726
29
1727
29
      if (Val != std::numeric_limits<unsigned>::max())
1728
29
        Opts.ASTDumpFormat = static_cast<ASTDumpOutputFormat>(Val);
1729
0
      else {
1730
0
        Diags.Report(diag::err_drv_invalid_value)
1731
0
            << A->getAsString(Args) << A->getValue();
1732
0
        Opts.ASTDumpFormat = ADOF_Default;
1733
0
      }
1734
29
      LLVM_FALLTHROUGH;
1735
29
    }
1736
220
    case OPT_ast_dump:
1737
220
    case OPT_ast_dump_all:
1738
220
    case OPT_ast_dump_lookups:
1739
220
      Opts.ProgramAction = frontend::ASTDump; break;
1740
476
    case OPT_ast_print:
1741
476
      Opts.ProgramAction = frontend::ASTPrint; break;
1742
220
    case OPT_ast_view:
1743
0
      Opts.ProgramAction = frontend::ASTView; break;
1744
220
    case OPT_compiler_options_dump:
1745
3
      Opts.ProgramAction = frontend::DumpCompilerOptions; break;
1746
220
    case OPT_dump_raw_tokens:
1747
0
      Opts.ProgramAction = frontend::DumpRawTokens; break;
1748
220
    case OPT_dump_tokens:
1749
3
      Opts.ProgramAction = frontend::DumpTokens; break;
1750
309
    case OPT_S:
1751
309
      Opts.ProgramAction = frontend::EmitAssembly; break;
1752
420
    case OPT_emit_llvm_bc:
1753
420
      Opts.ProgramAction = frontend::EmitBC; break;
1754
220
    case OPT_emit_html:
1755
3
      Opts.ProgramAction = frontend::EmitHTML; break;
1756
10.1k
    case OPT_emit_llvm:
1757
10.1k
      Opts.ProgramAction = frontend::EmitLLVM; break;
1758
221
    case OPT_emit_llvm_only:
1759
221
      Opts.ProgramAction = frontend::EmitLLVMOnly; break;
1760
220
    case OPT_emit_codegen_only:
1761
3
      Opts.ProgramAction = frontend::EmitCodeGenOnly; break;
1762
3.18k
    case OPT_emit_obj:
1763
3.18k
      Opts.ProgramAction = frontend::EmitObj; break;
1764
220
    case OPT_fixit_EQ:
1765
1
      Opts.FixItSuffix = A->getValue();
1766
1
      LLVM_FALLTHROUGH;
1767
63
    case OPT_fixit:
1768
63
      Opts.ProgramAction = frontend::FixIt; break;
1769
193
    case OPT_emit_module:
1770
193
      Opts.ProgramAction = frontend::GenerateModule; break;
1771
49
    case OPT_emit_module_interface:
1772
49
      Opts.ProgramAction = frontend::GenerateModuleInterface; break;
1773
6
    case OPT_emit_header_module:
1774
6
      Opts.ProgramAction = frontend::GenerateHeaderModule; break;
1775
2.30k
    case OPT_emit_pch:
1776
2.30k
      Opts.ProgramAction = frontend::GeneratePCH; break;
1777
71
    case OPT_emit_interface_stubs: {
1778
71
      StringRef ArgStr =
1779
71
          Args.hasArg(OPT_interface_stub_version_EQ)
1780
71
              ? 
Args.getLastArgValue(OPT_interface_stub_version_EQ)23
1781
71
              : 
"experimental-ifs-v1"48
;
1782
71
      if (ArgStr == "experimental-yaml-elf-v1" ||
1783
71
          
ArgStr == "experimental-tapi-elf-v1"69
) {
1784
4
        std::string ErrorMessage =
1785
4
            "Invalid interface stub format: " + ArgStr.str() +
1786
4
            " is deprecated.";
1787
4
        Diags.Report(diag::err_drv_invalid_value)
1788
4
            << "Must specify a valid interface stub format type, ie: "
1789
4
               "-interface-stub-version=experimental-ifs-v1"
1790
4
            << ErrorMessage;
1791
67
      } else if (ArgStr != "experimental-ifs-v1") {
1792
2
        std::string ErrorMessage =
1793
2
            "Invalid interface stub format: " + ArgStr.str() + ".";
1794
2
        Diags.Report(diag::err_drv_invalid_value)
1795
2
            << "Must specify a valid interface stub format type, ie: "
1796
2
               "-interface-stub-version=experimental-ifs-v1"
1797
2
            << ErrorMessage;
1798
65
      } else {
1799
65
        Opts.ProgramAction = frontend::GenerateInterfaceIfsExpV1;
1800
65
      }
1801
71
      break;
1802
1
    }
1803
1
    case OPT_init_only:
1804
0
      Opts.ProgramAction = frontend::InitOnly; break;
1805
17.1k
    case OPT_fsyntax_only:
1806
17.1k
      Opts.ProgramAction = frontend::ParseSyntaxOnly; break;
1807
5
    case OPT_module_file_info:
1808
5
      Opts.ProgramAction = frontend::ModuleFileInfo; break;
1809
7
    case OPT_verify_pch:
1810
7
      Opts.ProgramAction = frontend::VerifyPCH; break;
1811
2
    case OPT_print_preamble:
1812
2
      Opts.ProgramAction = frontend::PrintPreamble; break;
1813
1.85k
    case OPT_E:
1814
1.85k
      Opts.ProgramAction = frontend::PrintPreprocessedInput; break;
1815
11
    case OPT_templight_dump:
1816
11
      Opts.ProgramAction = frontend::TemplightDump; break;
1817
1
    case OPT_rewrite_macros:
1818
1
      Opts.ProgramAction = frontend::RewriteMacros; break;
1819
164
    case OPT_rewrite_objc:
1820
164
      Opts.ProgramAction = frontend::RewriteObjC; break;
1821
1
    case OPT_rewrite_test:
1822
0
      Opts.ProgramAction = frontend::RewriteTest; break;
1823
1.26k
    case OPT_analyze:
1824
1.26k
      Opts.ProgramAction = frontend::RunAnalysis; break;
1825
8
    case OPT_migrate:
1826
8
      Opts.ProgramAction = frontend::MigrateSource; break;
1827
2.83k
    case OPT_Eonly:
1828
2.83k
      Opts.ProgramAction = frontend::RunPreprocessorOnly; break;
1829
7
    case OPT_print_dependency_directives_minimized_source:
1830
7
      Opts.ProgramAction =
1831
7
          frontend::PrintDependencyDirectivesSourceMinimizerOutput;
1832
7
      break;
1833
44.9k
    }
1834
44.9k
  }
1835
44.9k
1836
44.9k
  if (const Arg* A = Args.getLastArg(OPT_plugin)) {
1837
1
    Opts.Plugins.emplace_back(A->getValue(0));
1838
1
    Opts.ProgramAction = frontend::PluginAction;
1839
1
    Opts.ActionName = A->getValue();
1840
1
  }
1841
44.9k
  Opts.AddPluginActions = Args.getAllArgValues(OPT_add_plugin);
1842
44.9k
  for (const auto *AA : Args.filtered(OPT_plugin_arg))
1843
0
    Opts.PluginArgs[AA->getValue(0)].emplace_back(AA->getValue(1));
1844
44.9k
1845
44.9k
  for (const std::string &Arg :
1846
44.9k
         Args.getAllArgValues(OPT_ftest_module_file_extension_EQ)) {
1847
16
    std::string BlockName;
1848
16
    unsigned MajorVersion;
1849
16
    unsigned MinorVersion;
1850
16
    bool Hashed;
1851
16
    std::string UserInfo;
1852
16
    if (parseTestModuleFileExtensionArg(Arg, BlockName, MajorVersion,
1853
16
                                        MinorVersion, Hashed, UserInfo)) {
1854
0
      Diags.Report(diag::err_test_module_file_extension_format) << Arg;
1855
0
1856
0
      continue;
1857
0
    }
1858
16
1859
16
    // Add the testing module file extension.
1860
16
    Opts.ModuleFileExtensions.push_back(
1861
16
        std::make_shared<TestModuleFileExtension>(
1862
16
            BlockName, MajorVersion, MinorVersion, Hashed, UserInfo));
1863
16
  }
1864
44.9k
1865
44.9k
  if (const Arg *A = Args.getLastArg(OPT_code_completion_at)) {
1866
246
    Opts.CodeCompletionAt =
1867
246
      ParsedSourceLocation::FromString(A->getValue());
1868
246
    if (Opts.CodeCompletionAt.FileName.empty())
1869
0
      Diags.Report(diag::err_drv_invalid_value)
1870
0
        << A->getAsString(Args) << A->getValue();
1871
246
  }
1872
44.9k
  Opts.DisableFree = Args.hasArg(OPT_disable_free);
1873
44.9k
1874
44.9k
  Opts.OutputFile = std::string(Args.getLastArgValue(OPT_o));
1875
44.9k
  Opts.Plugins = Args.getAllArgValues(OPT_load);
1876
44.9k
  Opts.RelocatablePCH = Args.hasArg(OPT_relocatable_pch);
1877
44.9k
  Opts.ShowHelp = Args.hasArg(OPT_help);
1878
44.9k
  Opts.ShowStats = Args.hasArg(OPT_print_stats);
1879
44.9k
  Opts.ShowTimers = Args.hasArg(OPT_ftime_report);
1880
44.9k
  Opts.PrintSupportedCPUs = Args.hasArg(OPT_print_supported_cpus);
1881
44.9k
  Opts.TimeTrace = Args.hasArg(OPT_ftime_trace);
1882
44.9k
  Opts.TimeTraceGranularity = getLastArgIntValue(
1883
44.9k
      Args, OPT_ftime_trace_granularity_EQ, Opts.TimeTraceGranularity, Diags);
1884
44.9k
  Opts.ShowVersion = Args.hasArg(OPT_version);
1885
44.9k
  Opts.ASTMergeFiles = Args.getAllArgValues(OPT_ast_merge);
1886
44.9k
  Opts.LLVMArgs = Args.getAllArgValues(OPT_mllvm);
1887
44.9k
  Opts.FixWhatYouCan = Args.hasArg(OPT_fix_what_you_can);
1888
44.9k
  Opts.FixOnlyWarnings = Args.hasArg(OPT_fix_only_warnings);
1889
44.9k
  Opts.FixAndRecompile = Args.hasArg(OPT_fixit_recompile);
1890
44.9k
  Opts.FixToTemporaries = Args.hasArg(OPT_fixit_to_temp);
1891
44.9k
  Opts.ASTDumpDecls = Args.hasArg(OPT_ast_dump, OPT_ast_dump_EQ);
1892
44.9k
  Opts.ASTDumpAll = Args.hasArg(OPT_ast_dump_all, OPT_ast_dump_all_EQ);
1893
44.9k
  Opts.ASTDumpFilter = std::string(Args.getLastArgValue(OPT_ast_dump_filter));
1894
44.9k
  Opts.ASTDumpLookups = Args.hasArg(OPT_ast_dump_lookups);
1895
44.9k
  Opts.UseGlobalModuleIndex = !Args.hasArg(OPT_fno_modules_global_index);
1896
44.9k
  Opts.GenerateGlobalModuleIndex = Opts.UseGlobalModuleIndex;
1897
44.9k
  Opts.ModuleMapFiles = Args.getAllArgValues(OPT_fmodule_map_file);
1898
44.9k
  // Only the -fmodule-file=<file> form.
1899
44.9k
  for (const auto *A : Args.filtered(OPT_fmodule_file)) {
1900
406
    StringRef Val = A->getValue();
1901
406
    if (Val.find('=') == StringRef::npos)
1902
395
      Opts.ModuleFiles.push_back(std::string(Val));
1903
406
  }
1904
44.9k
  Opts.ModulesEmbedFiles = Args.getAllArgValues(OPT_fmodules_embed_file_EQ);
1905
44.9k
  Opts.ModulesEmbedAllFiles = Args.hasArg(OPT_fmodules_embed_all_files);
1906
44.9k
  Opts.IncludeTimestamps = !Args.hasArg(OPT_fno_pch_timestamp);
1907
44.9k
  Opts.UseTemporary = !Args.hasArg(OPT_fno_temp_file);
1908
44.9k
1909
44.9k
  Opts.CodeCompleteOpts.IncludeMacros
1910
44.9k
    = Args.hasArg(OPT_code_completion_macros);
1911
44.9k
  Opts.CodeCompleteOpts.IncludeCodePatterns
1912
44.9k
    = Args.hasArg(OPT_code_completion_patterns);
1913
44.9k
  Opts.CodeCompleteOpts.IncludeGlobals
1914
44.9k
    = !Args.hasArg(OPT_no_code_completion_globals);
1915
44.9k
  Opts.CodeCompleteOpts.IncludeNamespaceLevelDecls
1916
44.9k
    = !Args.hasArg(OPT_no_code_completion_ns_level_decls);
1917
44.9k
  Opts.CodeCompleteOpts.IncludeBriefComments
1918
44.9k
    = Args.hasArg(OPT_code_completion_brief_comments);
1919
44.9k
  Opts.CodeCompleteOpts.IncludeFixIts
1920
44.9k
    = Args.hasArg(OPT_code_completion_with_fixits);
1921
44.9k
1922
44.9k
  Opts.OverrideRecordLayoutsFile =
1923
44.9k
      std::string(Args.getLastArgValue(OPT_foverride_record_layout_EQ));
1924
44.9k
  Opts.AuxTriple = std::string(Args.getLastArgValue(OPT_aux_triple));
1925
44.9k
  if (Args.hasArg(OPT_aux_target_cpu))
1926
23
    Opts.AuxTargetCPU = std::string(Args.getLastArgValue(OPT_aux_target_cpu));
1927
44.9k
  if (Args.hasArg(OPT_aux_target_feature))
1928
1
    Opts.AuxTargetFeatures = Args.getAllArgValues(OPT_aux_target_feature);
1929
44.9k
  Opts.StatsFile = std::string(Args.getLastArgValue(OPT_stats_file));
1930
44.9k
1931
44.9k
  if (const Arg *A = Args.getLastArg(OPT_arcmt_check,
1932
25
                                     OPT_arcmt_modify,
1933
25
                                     OPT_arcmt_migrate)) {
1934
25
    switch (A->getOption().getID()) {
1935
0
    default:
1936
0
      llvm_unreachable("missed a case");
1937
15
    case OPT_arcmt_check:
1938
15
      Opts.ARCMTAction = FrontendOptions::ARCMT_Check;
1939
15
      break;
1940
2
    case OPT_arcmt_modify:
1941
2
      Opts.ARCMTAction = FrontendOptions::ARCMT_Modify;
1942
2
      break;
1943
8
    case OPT_arcmt_migrate:
1944
8
      Opts.ARCMTAction = FrontendOptions::ARCMT_Migrate;
1945
8
      break;
1946
44.9k
    }
1947
44.9k
  }
1948
44.9k
  Opts.MTMigrateDir =
1949
44.9k
      std::string(Args.getLastArgValue(OPT_mt_migrate_directory));
1950
44.9k
  Opts.ARCMTMigrateReportOut =
1951
44.9k
      std::string(Args.getLastArgValue(OPT_arcmt_migrate_report_output));
1952
44.9k
  Opts.ARCMTMigrateEmitARCErrors
1953
44.9k
    = Args.hasArg(OPT_arcmt_migrate_emit_arc_errors);
1954
44.9k
1955
44.9k
  if (Args.hasArg(OPT_objcmt_migrate_literals))
1956
7
    Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Literals;
1957
44.9k
  if (Args.hasArg(OPT_objcmt_migrate_subscripting))
1958
9
    Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Subscripting;
1959
44.9k
  if (Args.hasArg(OPT_objcmt_migrate_property_dot_syntax))
1960
1
    Opts.ObjCMTAction |= FrontendOptions::ObjCMT_PropertyDotSyntax;
1961
44.9k
  if (Args.hasArg(OPT_objcmt_migrate_property))
1962
0
    Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Property;
1963
44.9k
  if (Args.hasArg(OPT_objcmt_migrate_readonly_property))
1964
4
    Opts.ObjCMTAction |= FrontendOptions::ObjCMT_ReadonlyProperty;
1965
44.9k
  if (Args.hasArg(OPT_objcmt_migrate_readwrite_property))
1966
11
    Opts.ObjCMTAction |= FrontendOptions::ObjCMT_ReadwriteProperty;
1967
44.9k
  if (Args.hasArg(OPT_objcmt_migrate_annotation))
1968
2
    Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Annotation;
1969
44.9k
  if (Args.hasArg(OPT_objcmt_returns_innerpointer_property))
1970
1
    Opts.ObjCMTAction |= FrontendOptions::ObjCMT_ReturnsInnerPointerProperty;
1971
44.9k
  if (Args.hasArg(OPT_objcmt_migrate_instancetype))
1972
9
    Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Instancetype;
1973
44.9k
  if (Args.hasArg(OPT_objcmt_migrate_nsmacros))
1974
5
    Opts.ObjCMTAction |= FrontendOptions::ObjCMT_NsMacros;
1975
44.9k
  if (Args.hasArg(OPT_objcmt_migrate_protocol_conformance))
1976
1
    Opts.ObjCMTAction |= FrontendOptions::ObjCMT_ProtocolConformance;
1977
44.9k
  if (Args.hasArg(OPT_objcmt_atomic_property))
1978
2
    Opts.ObjCMTAction |= FrontendOptions::ObjCMT_AtomicProperty;
1979
44.9k
  if (Args.hasArg(OPT_objcmt_ns_nonatomic_iosonly))
1980
1
    Opts.ObjCMTAction |= FrontendOptions::ObjCMT_NsAtomicIOSOnlyProperty;
1981
44.9k
  if (Args.hasArg(OPT_objcmt_migrate_designated_init))
1982
3
    Opts.ObjCMTAction |= FrontendOptions::ObjCMT_DesignatedInitializer;
1983
44.9k
  if (Args.hasArg(OPT_objcmt_migrate_all))
1984
1
    Opts.ObjCMTAction |= FrontendOptions::ObjCMT_MigrateDecls;
1985
44.9k
1986
44.9k
  Opts.ObjCMTWhiteListPath =
1987
44.9k
      std::string(Args.getLastArgValue(OPT_objcmt_whitelist_dir_path));
1988
44.9k
1989
44.9k
  if (Opts.ARCMTAction != FrontendOptions::ARCMT_None &&
1990
44.9k
      
Opts.ObjCMTAction != FrontendOptions::ObjCMT_None25
) {
1991
0
    Diags.Report(diag::err_drv_argument_not_allowed_with)
1992
0
      << "ARC migration" << "ObjC migration";
1993
0
  }
1994
44.9k
1995
44.9k
  InputKind DashX(Language::Unknown);
1996
44.9k
  if (const Arg *A = Args.getLastArg(OPT_x)) {
1997
27.1k
    StringRef XValue = A->getValue();
1998
27.1k
1999
27.1k
    // Parse suffixes: '<lang>(-header|[-module-map][-cpp-output])'.
2000
27.1k
    // FIXME: Supporting '<lang>-header-cpp-output' would be useful.
2001
27.1k
    bool Preprocessed = XValue.consume_back("-cpp-output");
2002
27.1k
    bool ModuleMap = XValue.consume_back("-module-map");
2003
27.1k
    IsHeaderFile =
2004
27.1k
        !Preprocessed && 
!ModuleMap27.1k
&&
XValue.consume_back("-header")27.1k
;
2005
27.1k
2006
27.1k
    // Principal languages.
2007
27.1k
    DashX = llvm::StringSwitch<InputKind>(XValue)
2008
27.1k
                .Case("c", Language::C)
2009
27.1k
                .Case("cl", Language::OpenCL)
2010
27.1k
                .Case("cuda", Language::CUDA)
2011
27.1k
                .Case("hip", Language::HIP)
2012
27.1k
                .Case("c++", Language::CXX)
2013
27.1k
                .Case("objective-c", Language::ObjC)
2014
27.1k
                .Case("objective-c++", Language::ObjCXX)
2015
27.1k
                .Case("renderscript", Language::RenderScript)
2016
27.1k
                .Default(Language::Unknown);
2017
27.1k
2018
27.1k
    // "objc[++]-cpp-output" is an acceptable synonym for
2019
27.1k
    // "objective-c[++]-cpp-output".
2020
27.1k
    if (DashX.isUnknown() && 
Preprocessed134
&&
!IsHeaderFile2
&&
!ModuleMap2
)
2021
2
      DashX = llvm::StringSwitch<InputKind>(XValue)
2022
2
                  .Case("objc", Language::ObjC)
2023
2
                  .Case("objc++", Language::ObjCXX)
2024
2
                  .Default(Language::Unknown);
2025
27.1k
2026
27.1k
    // Some special cases cannot be combined with suffixes.
2027
27.1k
    if (DashX.isUnknown() && 
!Preprocessed132
&&
!ModuleMap132
&&
!IsHeaderFile132
)
2028
132
      DashX = llvm::StringSwitch<InputKind>(XValue)
2029
132
                  .Case("cpp-output", InputKind(Language::C).getPreprocessed())
2030
132
                  .Case("assembler-with-cpp", Language::Asm)
2031
132
                  .Cases("ast", "pcm",
2032
132
                         InputKind(Language::Unknown, InputKind::Precompiled))
2033
132
                  .Case("ir", Language::LLVM_IR)
2034
132
                  .Default(Language::Unknown);
2035
27.1k
2036
27.1k
    if (DashX.isUnknown())
2037
0
      Diags.Report(diag::err_drv_invalid_value)
2038
0
        << A->getAsString(Args) << A->getValue();
2039
27.1k
2040
27.1k
    if (Preprocessed)
2041
20
      DashX = DashX.getPreprocessed();
2042
27.1k
    if (ModuleMap)
2043
26
      DashX = DashX.withFormat(InputKind::ModuleMap);
2044
27.1k
  }
2045
44.9k
2046
44.9k
  // '-' is the default input if none is given.
2047
44.9k
  std::vector<std::string> Inputs = Args.getAllArgValues(OPT_INPUT);
2048
44.9k
  Opts.Inputs.clear();
2049
44.9k
  if (Inputs.empty())
2050
665
    Inputs.push_back("-");
2051
89.8k
  for (unsigned i = 0, e = Inputs.size(); i != e; 
++i44.9k
) {
2052
44.9k
    InputKind IK = DashX;
2053
44.9k
    if (IK.isUnknown()) {
2054
17.7k
      IK = FrontendOptions::getInputKindForExtension(
2055
17.7k
        StringRef(Inputs[i]).rsplit('.').second);
2056
17.7k
      // FIXME: Warn on this?
2057
17.7k
      if (IK.isUnknown())
2058
660
        IK = Language::C;
2059
17.7k
      // FIXME: Remove this hack.
2060
17.7k
      if (i == 0)
2061
17.7k
        DashX = IK;
2062
17.7k
    }
2063
44.9k
2064
44.9k
    // The -emit-module action implicitly takes a module map.
2065
44.9k
    if (Opts.ProgramAction == frontend::GenerateModule &&
2066
44.9k
        
IK.getFormat() == InputKind::Source193
)
2067
178
      IK = IK.withFormat(InputKind::ModuleMap);
2068
44.9k
2069
44.9k
    Opts.Inputs.emplace_back(std::move(Inputs[i]), IK);
2070
44.9k
  }
2071
44.9k
2072
44.9k
  return DashX;
2073
44.9k
}
2074
2075
std::string CompilerInvocation::GetResourcesPath(const char *Argv0,
2076
26.2k
                                                 void *MainAddr) {
2077
26.2k
  std::string ClangExecutable =
2078
26.2k
      llvm::sys::fs::getMainExecutable(Argv0, MainAddr);
2079
26.2k
  return Driver::GetResourcesPath(ClangExecutable, CLANG_RESOURCE_DIR);
2080
26.2k
}
2081
2082
static void ParseHeaderSearchArgs(HeaderSearchOptions &Opts, ArgList &Args,
2083
44.9k
                                  const std::string &WorkingDir) {
2084
44.9k
  Opts.Sysroot = std::string(Args.getLastArgValue(OPT_isysroot, "/"));
2085
44.9k
  Opts.Verbose = Args.hasArg(OPT_v);
2086
44.9k
  Opts.UseBuiltinIncludes = !Args.hasArg(OPT_nobuiltininc);
2087
44.9k
  Opts.UseStandardSystemIncludes = !Args.hasArg(OPT_nostdsysteminc);
2088
44.9k
  Opts.UseStandardCXXIncludes = !Args.hasArg(OPT_nostdincxx);
2089
44.9k
  if (const Arg *A = Args.getLastArg(OPT_stdlib_EQ))
2090
11.6k
    Opts.UseLibcxx = (strcmp(A->getValue(), "libc++") == 0);
2091
44.9k
  Opts.ResourceDir = std::string(Args.getLastArgValue(OPT_resource_dir));
2092
44.9k
2093
44.9k
  // Canonicalize -fmodules-cache-path before storing it.
2094
44.9k
  SmallString<128> P(Args.getLastArgValue(OPT_fmodules_cache_path));
2095
44.9k
  if (!(P.empty() || 
llvm::sys::path::is_absolute(P)3.78k
)) {
2096
5
    if (WorkingDir.empty())
2097
4
      llvm::sys::fs::make_absolute(P);
2098
1
    else
2099
1
      llvm::sys::fs::make_absolute(WorkingDir, P);
2100
5
  }
2101
44.9k
  llvm::sys::path::remove_dots(P);
2102
44.9k
  Opts.ModuleCachePath = std::string(P.str());
2103
44.9k
2104
44.9k
  Opts.ModuleUserBuildPath =
2105
44.9k
      std::string(Args.getLastArgValue(OPT_fmodules_user_build_path));
2106
44.9k
  // Only the -fmodule-file=<name>=<file> form.
2107
44.9k
  for (const auto *A : Args.filtered(OPT_fmodule_file)) {
2108
406
    StringRef Val = A->getValue();
2109
406
    if (Val.find('=') != StringRef::npos){
2110
11
      auto Split = Val.split('=');
2111
11
      Opts.PrebuiltModuleFiles.insert(
2112
11
          {std::string(Split.first), std::string(Split.second)});
2113
11
    }
2114
406
  }
2115
44.9k
  for (const auto *A : Args.filtered(OPT_fprebuilt_module_path))
2116
6
    Opts.AddPrebuiltModulePath(A->getValue());
2117
44.9k
  Opts.DisableModuleHash = Args.hasArg(OPT_fdisable_module_hash);
2118
44.9k
  Opts.ModulesHashContent = Args.hasArg(OPT_fmodules_hash_content);
2119
44.9k
  Opts.ModulesStrictContextHash = Args.hasArg(OPT_fmodules_strict_context_hash);
2120
44.9k
  Opts.ModulesValidateDiagnosticOptions =
2121
44.9k
      !Args.hasArg(OPT_fmodules_disable_diagnostic_validation);
2122
44.9k
  Opts.ImplicitModuleMaps = Args.hasArg(OPT_fimplicit_module_maps);
2123
44.9k
  Opts.ModuleMapFileHomeIsCwd = Args.hasArg(OPT_fmodule_map_file_home_is_cwd);
2124
44.9k
  Opts.ModuleCachePruneInterval =
2125
44.9k
      getLastArgIntValue(Args, OPT_fmodules_prune_interval, 7 * 24 * 60 * 60);
2126
44.9k
  Opts.ModuleCachePruneAfter =
2127
44.9k
      getLastArgIntValue(Args, OPT_fmodules_prune_after, 31 * 24 * 60 * 60);
2128
44.9k
  Opts.ModulesValidateOncePerBuildSession =
2129
44.9k
      Args.hasArg(OPT_fmodules_validate_once_per_build_session);
2130
44.9k
  Opts.BuildSessionTimestamp =
2131
44.9k
      getLastArgUInt64Value(Args, OPT_fbuild_session_timestamp, 0);
2132
44.9k
  Opts.ModulesValidateSystemHeaders =
2133
44.9k
      Args.hasArg(OPT_fmodules_validate_system_headers);
2134
44.9k
  Opts.ValidateASTInputFilesContent =
2135
44.9k
      Args.hasArg(OPT_fvalidate_ast_input_files_content);
2136
44.9k
  if (const Arg *A = Args.getLastArg(OPT_fmodule_format_EQ))
2137
1.58k
    Opts.ModuleFormat = A->getValue();
2138
44.9k
2139
44.9k
  for (const auto *A : Args.filtered(OPT_fmodules_ignore_macro)) {
2140
25
    StringRef MacroDef = A->getValue();
2141
25
    Opts.ModulesIgnoreMacros.insert(
2142
25
        llvm::CachedHashString(MacroDef.split('=').first));
2143
25
  }
2144
44.9k
2145
44.9k
  // Add -I..., -F..., and -index-header-map options in order.
2146
44.9k
  bool IsIndexHeaderMap = false;
2147
44.9k
  bool IsSysrootSpecified =
2148
44.9k
      
Args.hasArg(OPT__sysroot_EQ)44.9k
|| Args.hasArg(OPT_isysroot);
2149
44.9k
  for (const auto *A : Args.filtered(OPT_I, OPT_F, OPT_index_header_map)) {
2150
18.2k
    if (A->getOption().matches(OPT_index_header_map)) {
2151
0
      // -index-header-map applies to the next -I or -F.
2152
0
      IsIndexHeaderMap = true;
2153
0
      continue;
2154
0
    }
2155
18.2k
2156
18.2k
    frontend::IncludeDirGroup Group =
2157
18.2k
        IsIndexHeaderMap ? 
frontend::IndexHeaderMap0
: frontend::Angled;
2158
18.2k
2159
18.2k
    bool IsFramework = A->getOption().matches(OPT_F);
2160
18.2k
    std::string Path = A->getValue();
2161
18.2k
2162
18.2k
    if (IsSysrootSpecified && 
!IsFramework16.9k
&&
A->getValue()[0] == '='16.9k
) {
2163
4
      SmallString<32> Buffer;
2164
4
      llvm::sys::path::append(Buffer, Opts.Sysroot,
2165
4
                              llvm::StringRef(A->getValue()).substr(1));
2166
4
      Path = std::string(Buffer.str());
2167
4
    }
2168
18.2k
2169
18.2k
    Opts.AddPath(Path, Group, IsFramework,
2170
18.2k
                 /*IgnoreSysroot*/ true);
2171
18.2k
    IsIndexHeaderMap = false;
2172
18.2k
  }
2173
44.9k
2174
44.9k
  // Add -iprefix/-iwithprefix/-iwithprefixbefore options.
2175
44.9k
  StringRef Prefix = ""; // FIXME: This isn't the correct default prefix.
2176
44.9k
  for (const auto *A :
2177
44.9k
       Args.filtered(OPT_iprefix, OPT_iwithprefix, OPT_iwithprefixbefore)) {
2178
32
    if (A->getOption().matches(OPT_iprefix))
2179
11
      Prefix = A->getValue();
2180
21
    else if (A->getOption().matches(OPT_iwithprefix))
2181
11
      Opts.AddPath(Prefix.str() + A->getValue(), frontend::After, false, true);
2182
10
    else
2183
10
      Opts.AddPath(Prefix.str() + A->getValue(), frontend::Angled, false, true);
2184
32
  }
2185
44.9k
2186
44.9k
  for (const auto *A : Args.filtered(OPT_idirafter))
2187
10
    Opts.AddPath(A->getValue(), frontend::After, false, true);
2188
44.9k
  for (const auto *A : Args.filtered(OPT_iquote))
2189
39
    Opts.AddPath(A->getValue(), frontend::Quoted, false, true);
2190
44.9k
  for (const auto *A : Args.filtered(OPT_isystem, OPT_iwithsysroot))
2191
137
    Opts.AddPath(A->getValue(), frontend::System, false,
2192
137
                 !A->getOption().matches(OPT_iwithsysroot));
2193
44.9k
  for (const auto *A : Args.filtered(OPT_iframework))
2194
7
    Opts.AddPath(A->getValue(), frontend::System, true, true);
2195
44.9k
  for (const auto *A : Args.filtered(OPT_iframeworkwithsysroot))
2196
1
    Opts.AddPath(A->getValue(), frontend::System, /*IsFramework=*/true,
2197
1
                 /*IgnoreSysRoot=*/false);
2198
44.9k
2199
44.9k
  // Add the paths for the various language specific isystem flags.
2200
44.9k
  for (const auto *A : Args.filtered(OPT_c_isystem))
2201
2
    Opts.AddPath(A->getValue(), frontend::CSystem, false, true);
2202
44.9k
  for (const auto *A : Args.filtered(OPT_cxx_isystem))
2203
4
    Opts.AddPath(A->getValue(), frontend::CXXSystem, false, true);
2204
44.9k
  for (const auto *A : Args.filtered(OPT_objc_isystem))
2205
3
    Opts.AddPath(A->getValue(), frontend::ObjCSystem, false,true);
2206
44.9k
  for (const auto *A : Args.filtered(OPT_objcxx_isystem))
2207
2
    Opts.AddPath(A->getValue(), frontend::ObjCXXSystem, false, true);
2208
44.9k
2209
44.9k
  // Add the internal paths from a driver that detects standard include paths.
2210
44.9k
  for (const auto *A :
2211
98.6k
       Args.filtered(OPT_internal_isystem, OPT_internal_externc_isystem)) {
2212
98.6k
    frontend::IncludeDirGroup Group = frontend::System;
2213
98.6k
    if (A->getOption().matches(OPT_internal_externc_isystem))
2214
16.7k
      Group = frontend::ExternCSystem;
2215
98.6k
    Opts.AddPath(A->getValue(), Group, false, true);
2216
98.6k
  }
2217
44.9k
2218
44.9k
  // Add the path prefixes which are implicitly treated as being system headers.
2219
44.9k
  for (const auto *A :
2220
44.9k
       Args.filtered(OPT_system_header_prefix, OPT_no_system_header_prefix))
2221
4
    Opts.AddSystemHeaderPrefix(
2222
4
        A->getValue(), A->getOption().matches(OPT_system_header_prefix));
2223
44.9k
2224
44.9k
  for (const auto *A : Args.filtered(OPT_ivfsoverlay))
2225
70
    Opts.AddVFSOverlayFile(A->getValue());
2226
44.9k
}
2227
2228
void CompilerInvocation::setLangDefaults(LangOptions &Opts, InputKind IK,
2229
                                         const llvm::Triple &T,
2230
                                         PreprocessorOptions &PPOpts,
2231
44.7k
                                         LangStandard::Kind LangStd) {
2232
44.7k
  // Set some properties which depend solely on the input kind; it would be nice
2233
44.7k
  // to move these to the language standard, and have the driver resolve the
2234
44.7k
  // input kind + language standard.
2235
44.7k
  //
2236
44.7k
  // FIXME: Perhaps a better model would be for a single source file to have
2237
44.7k
  // multiple language standards (C / C++ std, ObjC std, OpenCL std, OpenMP std)
2238
44.7k
  // simultaneously active?
2239
44.7k
  if (IK.getLanguage() == Language::Asm) {
2240
28
    Opts.AsmPreprocessor = 1;
2241
44.7k
  } else if (IK.isObjectiveC()) {
2242
5.64k
    Opts.ObjC = 1;
2243
5.64k
  }
2244
44.7k
2245
44.7k
  if (LangStd == LangStandard::lang_unspecified) {
2246
23.6k
    // Based on the base language, pick one.
2247
23.6k
    switch (IK.getLanguage()) {
2248
0
    case Language::Unknown:
2249
0
    case Language::LLVM_IR:
2250
0
      llvm_unreachable("Invalid input kind!");
2251
286
    case Language::OpenCL:
2252
286
      LangStd = LangStandard::lang_opencl10;
2253
286
      break;
2254
186
    case Language::CUDA:
2255
186
      LangStd = LangStandard::lang_cuda;
2256
186
      break;
2257
9.23k
    case Language::Asm:
2258
9.23k
    case Language::C:
2259
#if defined(CLANG_DEFAULT_STD_C)
2260
      LangStd = CLANG_DEFAULT_STD_C;
2261
#else
2262
      // The PS4 uses C99 as the default C standard.
2263
9.23k
      if (T.isPS4())
2264
15
        LangStd = LangStandard::lang_gnu99;
2265
9.21k
      else
2266
9.21k
        LangStd = LangStandard::lang_gnu11;
2267
9.23k
#endif
2268
9.23k
      break;
2269
9.23k
    case Language::ObjC:
2270
#if defined(CLANG_DEFAULT_STD_C)
2271
      LangStd = CLANG_DEFAULT_STD_C;
2272
#else
2273
      LangStd = LangStandard::lang_gnu11;
2274
3.54k
#endif
2275
3.54k
      break;
2276
10.3k
    case Language::CXX:
2277
10.3k
    case Language::ObjCXX:
2278
#if defined(CLANG_DEFAULT_STD_CXX)
2279
      LangStd = CLANG_DEFAULT_STD_CXX;
2280
#else
2281
      LangStd = LangStandard::lang_gnucxx14;
2282
10.3k
#endif
2283
10.3k
      break;
2284
10.3k
    case Language::RenderScript:
2285
4
      LangStd = LangStandard::lang_c99;
2286
4
      break;
2287
10.3k
    case Language::HIP:
2288
33
      LangStd = LangStandard::lang_hip;
2289
33
      break;
2290
44.7k
    }
2291
44.7k
  }
2292
44.7k
2293
44.7k
  const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
2294
44.7k
  Opts.LineComment = Std.hasLineComments();
2295
44.7k
  Opts.C99 = Std.isC99();
2296
44.7k
  Opts.C11 = Std.isC11();
2297
44.7k
  Opts.C17 = Std.isC17();
2298
44.7k
  Opts.C2x = Std.isC2x();
2299
44.7k
  Opts.CPlusPlus = Std.isCPlusPlus();
2300
44.7k
  Opts.CPlusPlus11 = Std.isCPlusPlus11();
2301
44.7k
  Opts.CPlusPlus14 = Std.isCPlusPlus14();
2302
44.7k
  Opts.CPlusPlus17 = Std.isCPlusPlus17();
2303
44.7k
  Opts.CPlusPlus2a = Std.isCPlusPlus2a();
2304
44.7k
  Opts.Digraphs = Std.hasDigraphs();
2305
44.7k
  Opts.GNUMode = Std.isGNUMode();
2306
44.7k
  Opts.GNUInline = !Opts.C99 && 
!Opts.CPlusPlus30.8k
;
2307
44.7k
  Opts.GNUCVersion = 0;
2308
44.7k
  Opts.HexFloats = Std.hasHexFloats();
2309
44.7k
  Opts.ImplicitInt = Std.hasImplicitInt();
2310
44.7k
2311
44.7k
  // Set OpenCL Version.
2312
44.7k
  Opts.OpenCL = Std.isOpenCL();
2313
44.7k
  if (LangStd == LangStandard::lang_opencl10)
2314
304
    Opts.OpenCLVersion = 100;
2315
44.4k
  else if (LangStd == LangStandard::lang_opencl11)
2316
25
    Opts.OpenCLVersion = 110;
2317
44.4k
  else if (LangStd == LangStandard::lang_opencl12)
2318
64
    Opts.OpenCLVersion = 120;
2319
44.3k
  else if (LangStd == LangStandard::lang_opencl20)
2320
151
    Opts.OpenCLVersion = 200;
2321
44.2k
  else if (LangStd == LangStandard::lang_openclcpp)
2322
64
    Opts.OpenCLCPlusPlusVersion = 100;
2323
44.7k
2324
44.7k
  // OpenCL has some additional defaults.
2325
44.7k
  if (Opts.OpenCL) {
2326
608
    Opts.AltiVec = 0;
2327
608
    Opts.ZVector = 0;
2328
608
    Opts.setLaxVectorConversions(LangOptions::LaxVectorConversionKind::None);
2329
608
    Opts.setDefaultFPContractMode(LangOptions::FPC_On);
2330
608
    Opts.NativeHalfType = 1;
2331
608
    Opts.NativeHalfArgsAndReturns = 1;
2332
608
    Opts.OpenCLCPlusPlus = Opts.CPlusPlus;
2333
608
2334
608
    // Include default header file for OpenCL.
2335
608
    if (Opts.IncludeDefaultHeader) {
2336
23
      if (Opts.DeclareOpenCLBuiltins) {
2337
5
        // Only include base header file for builtin types and constants.
2338
5
        PPOpts.Includes.push_back("opencl-c-base.h");
2339
18
      } else {
2340
18
        PPOpts.Includes.push_back("opencl-c.h");
2341
18
      }
2342
23
    }
2343
608
  }
2344
44.7k
2345
44.7k
  Opts.HIP = IK.getLanguage() == Language::HIP;
2346
44.7k
  Opts.CUDA = IK.getLanguage() == Language::CUDA || 
Opts.HIP44.5k
;
2347
44.7k
  if (Opts.CUDA)
2348
292
    // Set default FP_CONTRACT to FAST.
2349
292
    Opts.setDefaultFPContractMode(LangOptions::FPC_Fast);
2350
44.7k
2351
44.7k
  Opts.RenderScript = IK.getLanguage() == Language::RenderScript;
2352
44.7k
  if (Opts.RenderScript) {
2353
4
    Opts.NativeHalfType = 1;
2354
4
    Opts.NativeHalfArgsAndReturns = 1;
2355
4
  }
2356
44.7k
2357
44.7k
  // OpenCL and C++ both have bool, true, false keywords.
2358
44.7k
  Opts.Bool = Opts.OpenCL || 
Opts.CPlusPlus44.1k
;
2359
44.7k
2360
44.7k
  // OpenCL has half keyword
2361
44.7k
  Opts.Half = Opts.OpenCL;
2362
44.7k
2363
44.7k
  // C++ has wchar_t keyword.
2364
44.7k
  Opts.WChar = Opts.CPlusPlus;
2365
44.7k
2366
44.7k
  Opts.GNUKeywords = Opts.GNUMode;
2367
44.7k
  Opts.CXXOperatorNames = Opts.CPlusPlus;
2368
44.7k
2369
44.7k
  Opts.AlignedAllocation = Opts.CPlusPlus17;
2370
44.7k
2371
44.7k
  Opts.DollarIdents = !Opts.AsmPreprocessor;
2372
44.7k
2373
44.7k
  // Enable [[]] attributes in C++11 and C2x by default.
2374
44.7k
  Opts.DoubleSquareBracketAttributes = Opts.CPlusPlus11 || 
Opts.C2x18.0k
;
2375
44.7k
}
2376
2377
/// Attempt to parse a visibility value out of the given argument.
2378
static Visibility parseVisibility(Arg *arg, ArgList &args,
2379
133
                                  DiagnosticsEngine &diags) {
2380
133
  StringRef value = arg->getValue();
2381
133
  if (value == "default") {
2382
22
    return DefaultVisibility;
2383
111
  } else if (value == "hidden" || 
value == "internal"6
) {
2384
106
    return HiddenVisibility;
2385
106
  } else 
if (5
value == "protected"5
) {
2386
5
    // FIXME: diagnose if target does not support protected visibility
2387
5
    return ProtectedVisibility;
2388
5
  }
2389
0
2390
0
  diags.Report(diag::err_drv_invalid_value)
2391
0
    << arg->getAsString(args) << value;
2392
0
  return DefaultVisibility;
2393
0
}
2394
2395
/// Check if input file kind and language standard are compatible.
2396
static bool IsInputCompatibleWithStandard(InputKind IK,
2397
21.0k
                                          const LangStandard &S) {
2398
21.0k
  switch (IK.getLanguage()) {
2399
0
  case Language::Unknown:
2400
0
  case Language::LLVM_IR:
2401
0
    llvm_unreachable("should not parse language flags for this input");
2402
0
2403
844
  case Language::C:
2404
844
  case Language::ObjC:
2405
844
  case Language::RenderScript:
2406
844
    return S.getLanguage() == Language::C;
2407
844
2408
844
  case Language::OpenCL:
2409
32
    return S.getLanguage() == Language::OpenCL;
2410
844
2411
20.0k
  case Language::CXX:
2412
20.0k
  case Language::ObjCXX:
2413
20.0k
    return S.getLanguage() == Language::CXX;
2414
20.0k
2415
20.0k
  case Language::CUDA:
2416
94
    // FIXME: What -std= values should be permitted for CUDA compilations?
2417
94
    return S.getLanguage() == Language::CUDA ||
2418
94
           
S.getLanguage() == Language::CXX93
;
2419
20.0k
2420
20.0k
  case Language::HIP:
2421
7
    return S.getLanguage() == Language::CXX || 
S.getLanguage() == Language::HIP0
;
2422
20.0k
2423
20.0k
  case Language::Asm:
2424
1
    // Accept (and ignore) all -std= values.
2425
1
    // FIXME: The -std= value is not ignored; it affects the tokenization
2426
1
    // and preprocessing rules if we're preprocessing this asm input.
2427
1
    return true;
2428
0
  }
2429
0
2430
0
  llvm_unreachable("unexpected input language");
2431
0
}
2432
2433
/// Get language name for given input kind.
2434
4
static const StringRef GetInputKindName(InputKind IK) {
2435
4
  switch (IK.getLanguage()) {
2436
1
  case Language::C:
2437
1
    return "C";
2438
0
  case Language::ObjC:
2439
0
    return "Objective-C";
2440
1
  case Language::CXX:
2441
1
    return "C++";
2442
1
  case Language::ObjCXX:
2443
1
    return "Objective-C++";
2444
1
  case Language::OpenCL:
2445
1
    return "OpenCL";
2446
0
  case Language::CUDA:
2447
0
    return "CUDA";
2448
0
  case Language::RenderScript:
2449
0
    return "RenderScript";
2450
0
  case Language::HIP:
2451
0
    return "HIP";
2452
0
2453
0
  case Language::Asm:
2454
0
    return "Asm";
2455
0
  case Language::LLVM_IR:
2456
0
    return "LLVM IR";
2457
0
2458
0
  case Language::Unknown:
2459
0
    break;
2460
0
  }
2461
0
  llvm_unreachable("unknown input language");
2462
0
}
2463
2464
static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK,
2465
                          const TargetOptions &TargetOpts,
2466
                          PreprocessorOptions &PPOpts,
2467
44.7k
                          DiagnosticsEngine &Diags) {
2468
44.7k
  // FIXME: Cleanup per-file based stuff.
2469
44.7k
  LangStandard::Kind LangStd = LangStandard::lang_unspecified;
2470
44.7k
  if (const Arg *A = Args.getLastArg(OPT_std_EQ)) {
2471
20.8k
    LangStd = LangStandard::getLangKind(A->getValue());
2472
20.8k
    if (LangStd == LangStandard::lang_unspecified) {
2473
8
      Diags.Report(diag::err_drv_invalid_value)
2474
8
        << A->getAsString(Args) << A->getValue();
2475
8
      // Report supported standards with short description.
2476
8
      for (unsigned KindValue = 0;
2477
232
           KindValue != LangStandard::lang_unspecified;
2478
224
           ++KindValue) {
2479
224
        const LangStandard &Std = LangStandard::getLangStandardForKind(
2480
224
          static_cast<LangStandard::Kind>(KindValue));
2481
224
        if (IsInputCompatibleWithStandard(IK, Std)) {
2482
80
          auto Diag = Diags.Report(diag::note_drv_use_standard);
2483
80
          Diag << Std.getName() << Std.getDescription();
2484
80
          unsigned NumAliases = 0;
2485
80
#define LANGSTANDARD(id, name, lang, desc, features)
2486
80
#define LANGSTANDARD_ALIAS(id, alias) \
2487
880
          if (KindValue == LangStandard::lang_##id) 
++NumAliases42
;
2488
80
#define LANGSTANDARD_ALIAS_DEPR(id, alias)
2489
80
#include "clang/Basic/LangStandards.def"
2490
80
          Diag << NumAliases;
2491
80
#define LANGSTANDARD(id, name, lang, desc, features)
2492
80
#define LANGSTANDARD_ALIAS(id, alias) \
2493
880
          if (KindValue == LangStandard::lang_##id) 
Diag << alias42
;
2494
80
#define LANGSTANDARD_ALIAS_DEPR(id, alias)
2495
80
#include "clang/Basic/LangStandards.def"
2496
80
        }
2497
224
      }
2498
20.8k
    } else {
2499
20.8k
      // Valid standard, check to make sure language and standard are
2500
20.8k
      // compatible.
2501
20.8k
      const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
2502
20.8k
      if (!IsInputCompatibleWithStandard(IK, Std)) {
2503
2
        Diags.Report(diag::err_drv_argument_not_allowed_with)
2504
2
          << A->getAsString(Args) << GetInputKindName(IK);
2505
2
      }
2506
20.8k
    }
2507
20.8k
  }
2508
44.7k
2509
44.7k
  if (Args.hasArg(OPT_fno_dllexport_inlines))
2510
1
    Opts.DllExportInlines = false;
2511
44.7k
2512
44.7k
  if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
2513
8
    StringRef Name = A->getValue();
2514
8
    if (Name == "full" || 
Name == "branch"7
) {
2515
7
      Opts.CFProtectionBranch = 1;
2516
7
    }
2517
8
  }
2518
44.7k
  // -cl-std only applies for OpenCL language standards.
2519
44.7k
  // Override the -std option in this case.
2520
44.7k
  if (const Arg *A = Args.getLastArg(OPT_cl_std_EQ)) {
2521
322
    LangStandard::Kind OpenCLLangStd
2522
322
      = llvm::StringSwitch<LangStandard::Kind>(A->getValue())
2523
322
        .Cases("cl", "CL", LangStandard::lang_opencl10)
2524
322
        .Cases("cl1.1", "CL1.1", LangStandard::lang_opencl11)
2525
322
        .Cases("cl1.2", "CL1.2", LangStandard::lang_opencl12)
2526
322
        .Cases("cl2.0", "CL2.0", LangStandard::lang_opencl20)
2527
322
        .Cases("clc++", "CLC++", LangStandard::lang_openclcpp)
2528
322
        .Default(LangStandard::lang_unspecified);
2529
322
2530
322
    if (OpenCLLangStd == LangStandard::lang_unspecified) {
2531
3
      Diags.Report(diag::err_drv_invalid_value)
2532
3
        << A->getAsString(Args) << A->getValue();
2533
3
    }
2534
319
    else
2535
319
      LangStd = OpenCLLangStd;
2536
322
  }
2537
44.7k
2538
44.7k
  Opts.IncludeDefaultHeader = Args.hasArg(OPT_finclude_default_header);
2539
44.7k
  Opts.DeclareOpenCLBuiltins = Args.hasArg(OPT_fdeclare_opencl_builtins);
2540
44.7k
2541
44.7k
  llvm::Triple T(TargetOpts.Triple);
2542
44.7k
  CompilerInvocation::setLangDefaults(Opts, IK, T, PPOpts, LangStd);
2543
44.7k
2544
44.7k
  // -cl-strict-aliasing needs to emit diagnostic in the case where CL > 1.0.
2545
44.7k
  // This option should be deprecated for CL > 1.0 because
2546
44.7k
  // this option was added for compatibility with OpenCL 1.0.
2547
44.7k
  if (Args.getLastArg(OPT_cl_strict_aliasing)
2548
44.7k
       && 
Opts.OpenCLVersion > 1004
) {
2549
3
    Diags.Report(diag::warn_option_invalid_ocl_version)
2550
3
        << Opts.getOpenCLVersionTuple().getAsString()
2551
3
        << Args.getLastArg(OPT_cl_strict_aliasing)->getAsString(Args);
2552
3
  }
2553
44.7k
2554
44.7k
  // We abuse '-f[no-]gnu-keywords' to force overriding all GNU-extension
2555
44.7k
  // keywords. This behavior is provided by GCC's poorly named '-fasm' flag,
2556
44.7k
  // while a subset (the non-C++ GNU keywords) is provided by GCC's
2557
44.7k
  // '-fgnu-keywords'. Clang conflates the two for simplicity under the single
2558
44.7k
  // name, as it doesn't seem a useful distinction.
2559
44.7k
  Opts.GNUKeywords = Args.hasFlag(OPT_fgnu_keywords, OPT_fno_gnu_keywords,
2560
44.7k
                                  Opts.GNUKeywords);
2561
44.7k
2562
44.7k
  Opts.Digraphs = Args.hasFlag(OPT_fdigraphs, OPT_fno_digraphs, Opts.Digraphs);
2563
44.7k
2564
44.7k
  if (Args.hasArg(OPT_fno_operator_names))
2565
1
    Opts.CXXOperatorNames = 0;
2566
44.7k
2567
44.7k
  if (Args.hasArg(OPT_fcuda_is_device))
2568
155
    Opts.CUDAIsDevice = 1;
2569
44.7k
2570
44.7k
  if (Args.hasArg(OPT_fcuda_allow_variadic_functions))
2571
4
    Opts.CUDAAllowVariadicFunctions = 1;
2572
44.7k
2573
44.7k
  if (Args.hasArg(OPT_fno_cuda_host_device_constexpr))
2574
2
    Opts.CUDAHostDeviceConstexpr = 0;
2575
44.7k
2576
44.7k
  if (Opts.CUDAIsDevice && 
Args.hasArg(OPT_fcuda_approx_transcendentals)155
)
2577
1
    Opts.CUDADeviceApproxTranscendentals = 1;
2578
44.7k
2579
44.7k
  Opts.GPURelocatableDeviceCode = Args.hasArg(OPT_fgpu_rdc);
2580
44.7k
  if (Args.hasArg(OPT_fgpu_allow_device_init)) {
2581
1
    if (Opts.HIP)
2582
1
      Opts.GPUAllowDeviceInit = 1;
2583
0
    else
2584
0
      Diags.Report(diag::warn_ignored_hip_only_option)
2585
0
          << Args.getLastArg(OPT_fgpu_allow_device_init)->getAsString(Args);
2586
1
  }
2587
44.7k
  Opts.HIPUseNewLaunchAPI = Args.hasArg(OPT_fhip_new_launch_api);
2588
44.7k
  if (Opts.HIP)
2589
40
    Opts.GPUMaxThreadsPerBlock = getLastArgIntValue(
2590
40
        Args, OPT_gpu_max_threads_per_block_EQ, Opts.GPUMaxThreadsPerBlock);
2591
44.7k
  else if (Args.hasArg(OPT_gpu_max_threads_per_block_EQ))
2592
0
    Diags.Report(diag::warn_ignored_hip_only_option)
2593
0
        << Args.getLastArg(OPT_gpu_max_threads_per_block_EQ)->getAsString(Args);
2594
44.7k
2595
44.7k
  if (Opts.ObjC) {
2596
5.64k
    if (Arg *arg = Args.getLastArg(OPT_fobjc_runtime_EQ)) {
2597
3.15k
      StringRef value = arg->getValue();
2598
3.15k
      if (Opts.ObjCRuntime.tryParse(value))
2599
0
        Diags.Report(diag::err_drv_unknown_objc_runtime) << value;
2600
3.15k
    }
2601
5.64k
2602
5.64k
    if (Args.hasArg(OPT_fobjc_gc_only))
2603
20
      Opts.setGC(LangOptions::GCOnly);
2604
5.62k
    else if (Args.hasArg(OPT_fobjc_gc))
2605
83
      Opts.setGC(LangOptions::HybridGC);
2606
5.53k
    else if (Args.hasArg(OPT_fobjc_arc)) {
2607
1.57k
      Opts.ObjCAutoRefCount = 1;
2608
1.57k
      if (!Opts.ObjCRuntime.allowsARC())
2609
8
        Diags.Report(diag::err_arc_unsupported_on_runtime);
2610
1.57k
    }
2611
5.64k
2612
5.64k
    // ObjCWeakRuntime tracks whether the runtime supports __weak, not
2613
5.64k
    // whether the feature is actually enabled.  This is predominantly
2614
5.64k
    // determined by -fobjc-runtime, but we allow it to be overridden
2615
5.64k
    // from the command line for testing purposes.
2616
5.64k
    if (Args.hasArg(OPT_fobjc_runtime_has_weak))
2617
138
      Opts.ObjCWeakRuntime = 1;
2618
5.50k
    else
2619
5.50k
      Opts.ObjCWeakRuntime = Opts.ObjCRuntime.allowsWeak();
2620
5.64k
2621
5.64k
    // ObjCWeak determines whether __weak is actually enabled.
2622
5.64k
    // Note that we allow -fno-objc-weak to disable this even in ARC mode.
2623
5.64k
    if (auto weakArg = Args.getLastArg(OPT_fobjc_weak, OPT_fno_objc_weak)) {
2624
22
      if (!weakArg->getOption().matches(OPT_fobjc_weak)) {
2625
0
        assert(!Opts.ObjCWeak);
2626
22
      } else if (Opts.getGC() != LangOptions::NonGC) {
2627
0
        Diags.Report(diag::err_objc_weak_with_gc);
2628
22
      } else if (!Opts.ObjCWeakRuntime) {
2629
0
        Diags.Report(diag::err_objc_weak_unsupported);
2630
22
      } else {
2631
22
        Opts.ObjCWeak = 1;
2632
22
      }
2633
5.62k
    } else if (Opts.ObjCAutoRefCount) {
2634
1.56k
      Opts.ObjCWeak = Opts.ObjCWeakRuntime;
2635
1.56k
    }
2636
5.64k
2637
5.64k
    if (Args.hasArg(OPT_fno_objc_infer_related_result_type))
2638
7
      Opts.ObjCInferRelatedResultType = 0;
2639
5.64k
2640
5.64k
    if (Args.hasArg(OPT_fobjc_subscripting_legacy_runtime))
2641
9
      Opts.ObjCSubscriptingLegacyRuntime =
2642
9
        (Opts.ObjCRuntime.getKind() == ObjCRuntime::FragileMacOSX);
2643
5.64k
  }
2644
44.7k
2645
44.7k
  if (Arg *A = Args.getLastArg(options::OPT_fgnuc_version_EQ)) {
2646
16.6k
    // Check that the version has 1 to 3 components and the minor and patch
2647
16.6k
    // versions fit in two decimal digits.
2648
16.6k
    VersionTuple GNUCVer;
2649
16.6k
    bool Invalid = GNUCVer.tryParse(A->getValue());
2650
16.6k
    unsigned Major = GNUCVer.getMajor();
2651
16.6k
    unsigned Minor = GNUCVer.getMinor().getValueOr(0);
2652
16.6k
    unsigned Patch = GNUCVer.getSubminor().getValueOr(0);
2653
16.6k
    if (
Invalid16.6k
|| GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) {
2654
0
      Diags.Report(diag::err_drv_invalid_value)
2655
0
          << A->getAsString(Args) << A->getValue();
2656
0
    }
2657
16.6k
    Opts.GNUCVersion = Major * 100 * 100 + Minor * 100 + Patch;
2658
16.6k
  }
2659
44.7k
2660
44.7k
  if (Args.hasArg(OPT_fgnu89_inline)) {
2661
4
    if (Opts.CPlusPlus)
2662
2
      Diags.Report(diag::err_drv_argument_not_allowed_with)
2663
2
        << "-fgnu89-inline" << GetInputKindName(IK);
2664
2
    else
2665
2
      Opts.GNUInline = 1;
2666
4
  }
2667
44.7k
2668
44.7k
  if (Args.hasArg(OPT_fapple_kext)) {
2669
11
    if (!Opts.CPlusPlus)
2670
0
      Diags.Report(diag::warn_c_kext);
2671
11
    else
2672
11
      Opts.AppleKext = 1;
2673
11
  }
2674
44.7k
2675
44.7k
  if (Args.hasArg(OPT_print_ivar_layout))
2676
10
    Opts.ObjCGCBitmapPrint = 1;
2677
44.7k
2678
44.7k
  if (Args.hasArg(OPT_fno_constant_cfstrings))
2679
5
    Opts.NoConstantCFStrings = 1;
2680
44.7k
  if (const auto *A = Args.getLastArg(OPT_fcf_runtime_abi_EQ))
2681
30
    Opts.CFRuntime =
2682
30
        llvm::StringSwitch<LangOptions::CoreFoundationABI>(A->getValue())
2683
30
            .Cases("unspecified", "standalone", "objc",
2684
30
                   LangOptions::CoreFoundationABI::ObjectiveC)
2685
30
            .Cases("swift", "swift-5.0",
2686
30
                   LangOptions::CoreFoundationABI::Swift5_0)
2687
30
            .Case("swift-4.2", LangOptions::CoreFoundationABI::Swift4_2)
2688
30
            .Case("swift-4.1", LangOptions::CoreFoundationABI::Swift4_1)
2689
30
            .Default(LangOptions::CoreFoundationABI::ObjectiveC);
2690
44.7k
2691
44.7k
  if (Args.hasArg(OPT_fzvector))
2692
25
    Opts.ZVector = 1;
2693
44.7k
2694
44.7k
  if (Args.hasArg(OPT_pthread))
2695
10
    Opts.POSIXThreads = 1;
2696
44.7k
2697
44.7k
  // The value-visibility mode defaults to "default".
2698
44.7k
  if (Arg *visOpt = Args.getLastArg(OPT_fvisibility)) {
2699
132
    Opts.setValueVisibilityMode(parseVisibility(visOpt, Args, Diags));
2700
44.6k
  } else {
2701
44.6k
    Opts.setValueVisibilityMode(DefaultVisibility);
2702
44.6k
  }
2703
44.7k
2704
44.7k
  // The type-visibility mode defaults to the value-visibility mode.
2705
44.7k
  if (Arg *typeVisOpt = Args.getLastArg(OPT_ftype_visibility)) {
2706
1
    Opts.setTypeVisibilityMode(parseVisibility(typeVisOpt, Args, Diags));
2707
44.7k
  } else {
2708
44.7k
    Opts.setTypeVisibilityMode(Opts.getValueVisibilityMode());
2709
44.7k
  }
2710
44.7k
2711
44.7k
  if (Args.hasArg(OPT_fvisibility_inlines_hidden))
2712
5
    Opts.InlineVisibilityHidden = 1;
2713
44.7k
2714
44.7k
  if (Args.hasArg(OPT_fvisibility_global_new_delete_hidden))
2715
0
    Opts.GlobalAllocationFunctionVisibilityHidden = 1;
2716
44.7k
2717
44.7k
  if (Args.hasArg(OPT_fapply_global_visibility_to_externs))
2718
16
    Opts.SetVisibilityForExternDecls = 1;
2719
44.7k
2720
44.7k
  if (Args.hasArg(OPT_ftrapv)) {
2721
8
    Opts.setSignedOverflowBehavior(LangOptions::SOB_Trapping);
2722
8
    // Set the handler, if one is specified.
2723
8
    Opts.OverflowHandler =
2724
8
        std::string(Args.getLastArgValue(OPT_ftrapv_handler));
2725
8
  }
2726
44.7k
  else if (Args.hasArg(OPT_fwrapv))
2727
3
    Opts.setSignedOverflowBehavior(LangOptions::SOB_Defined);
2728
44.7k
2729
44.7k
  Opts.MSVCCompat = Args.hasArg(OPT_fms_compatibility);
2730
44.7k
  Opts.MicrosoftExt = Opts.MSVCCompat || 
Args.hasArg(OPT_fms_extensions)42.2k
;
2731
44.7k
  Opts.AsmBlocks = Args.hasArg(OPT_fasm_blocks) || 
Opts.MicrosoftExt44.7k
;
2732
44.7k
  Opts.MSCompatibilityVersion = 0;
2733
44.7k
  if (const Arg *A = Args.getLastArg(OPT_fms_compatibility_version)) {
2734
183
    VersionTuple VT;
2735
183
    if (VT.tryParse(A->getValue()))
2736
0
      Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
2737
0
                                                << A->getValue();
2738
183
    Opts.MSCompatibilityVersion = VT.getMajor() * 10000000 +
2739
183
                                  VT.getMinor().getValueOr(0) * 100000 +
2740
183
                                  VT.getSubminor().getValueOr(0);
2741
183
  }
2742
44.7k
2743
44.7k
  // Mimicking gcc's behavior, trigraphs are only enabled if -trigraphs
2744
44.7k
  // is specified, or -std is set to a conforming mode.
2745
44.7k
  // Trigraphs are disabled by default in c++1z onwards.
2746
44.7k
  Opts.Trigraphs = !Opts.GNUMode && 
!Opts.MSVCCompat21.2k
&&
!Opts.CPlusPlus1718.9k
;
2747
44.7k
  Opts.Trigraphs =
2748
44.7k
      Args.hasFlag(OPT_ftrigraphs, OPT_fno_trigraphs, Opts.Trigraphs);
2749
44.7k
2750
44.7k
  Opts.DollarIdents = Args.hasFlag(OPT_fdollars_in_identifiers,
2751
44.7k
                                   OPT_fno_dollars_in_identifiers,
2752
44.7k
                                   Opts.DollarIdents);
2753
44.7k
  Opts.PascalStrings = Args.hasArg(OPT_fpascal_strings);
2754
44.7k
  Opts.setVtorDispMode(
2755
44.7k
      MSVtorDispMode(getLastArgIntValue(Args, OPT_vtordisp_mode_EQ, 1, Diags)));
2756
44.7k
  Opts.Borland = Args.hasArg(OPT_fborland_extensions);
2757
44.7k
  Opts.WritableStrings = Args.hasArg(OPT_fwritable_strings);
2758
44.7k
  Opts.ConstStrings = Args.hasFlag(OPT_fconst_strings, OPT_fno_const_strings,
2759
44.7k
                                   Opts.ConstStrings);
2760
44.7k
  if (Arg *A = Args.getLastArg(OPT_flax_vector_conversions_EQ)) {
2761
115
    using LaxKind = LangOptions::LaxVectorConversionKind;
2762
115
    if (auto Kind = llvm::StringSwitch<Optional<LaxKind>>(A->getValue())
2763
115
                        .Case("none", LaxKind::None)
2764
115
                        .Case("integer", LaxKind::Integer)
2765
115
                        .Case("all", LaxKind::All)
2766
115
                        .Default(llvm::None))
2767
115
      Opts.setLaxVectorConversions(*Kind);
2768
0
    else
2769
0
      Diags.Report(diag::err_drv_invalid_value)
2770
0
          << A->getAsString(Args) << A->getValue();
2771
115
  }
2772
44.7k
  if (Args.hasArg(OPT_fno_threadsafe_statics))
2773
33
    Opts.ThreadsafeStatics = 0;
2774
44.7k
  Opts.Exceptions = Args.hasArg(OPT_fexceptions);
2775
44.7k
  Opts.IgnoreExceptions = Args.hasArg(OPT_fignore_exceptions);
2776
44.7k
  Opts.ObjCExceptions = Args.hasArg(OPT_fobjc_exceptions);
2777
44.7k
  Opts.CXXExceptions = Args.hasArg(OPT_fcxx_exceptions);
2778
44.7k
2779
44.7k
  // -ffixed-point
2780
44.7k
  Opts.FixedPoint =
2781
44.7k
      Args.hasFlag(OPT_ffixed_point, OPT_fno_fixed_point, /*Default=*/false) &&
2782
44.7k
      
!Opts.CPlusPlus23
;
2783
44.7k
  Opts.PaddingOnUnsignedFixedPoint =
2784
44.7k
      Args.hasFlag(OPT_fpadding_on_unsigned_fixed_point,
2785
44.7k
                   OPT_fno_padding_on_unsigned_fixed_point,
2786
44.7k
                   /*Default=*/false) &&
2787
44.7k
      
Opts.FixedPoint7
;
2788
44.7k
2789
44.7k
  // Handle exception personalities
2790
44.7k
  Arg *A = Args.getLastArg(
2791
44.7k
      options::OPT_fsjlj_exceptions, options::OPT_fseh_exceptions,
2792
44.7k
      options::OPT_fdwarf_exceptions, options::OPT_fwasm_exceptions);
2793
44.7k
  if (A) {
2794
98
    const Option &Opt = A->getOption();
2795
98
    llvm::Triple T(TargetOpts.Triple);
2796
98
    if (T.isWindowsMSVCEnvironment())
2797
6
      Diags.Report(diag::err_fe_invalid_exception_model)
2798
6
          << Opt.getName() << T.str();
2799
98
2800
98
    Opts.SjLjExceptions = Opt.matches(options::OPT_fsjlj_exceptions);
2801
98
    Opts.SEHExceptions = Opt.matches(options::OPT_fseh_exceptions);
2802
98
    Opts.DWARFExceptions = Opt.matches(options::OPT_fdwarf_exceptions);
2803
98
    Opts.WasmExceptions = Opt.matches(options::OPT_fwasm_exceptions);
2804
98
  }
2805
44.7k
2806
44.7k
  Opts.ExternCNoUnwind = Args.hasArg(OPT_fexternc_nounwind);
2807
44.7k
  Opts.TraditionalCPP = Args.hasArg(OPT_traditional_cpp);
2808
44.7k
2809
44.7k
  Opts.RTTI = Opts.CPlusPlus && 
!Args.hasArg(OPT_fno_rtti)30.7k
;
2810
44.7k
  Opts.RTTIData = Opts.RTTI && 
!Args.hasArg(OPT_fno_rtti_data)30.6k
;
2811
44.7k
  Opts.Blocks = Args.hasArg(OPT_fblocks) || 
(28.1k
Opts.OpenCL28.1k
2812
28.1k
    && 
Opts.OpenCLVersion == 200594
);
2813
44.7k
  Opts.BlocksRuntimeOptional = Args.hasArg(OPT_fblocks_runtime_optional);
2814
44.7k
  Opts.Coroutines = Opts.CPlusPlus2a || 
Args.hasArg(OPT_fcoroutines_ts)44.4k
;
2815
44.7k
2816
44.7k
  Opts.ConvergentFunctions = Opts.OpenCL || 
(44.1k
Opts.CUDA44.1k
&&
Opts.CUDAIsDevice292
) ||
2817
44.7k
    
Args.hasArg(OPT_fconvergent_functions)44.0k
;
2818
44.7k
2819
44.7k
  Opts.DoubleSquareBracketAttributes =
2820
44.7k
      Args.hasFlag(OPT_fdouble_square_bracket_attributes,
2821
44.7k
                   OPT_fno_double_square_bracket_attributes,
2822
44.7k
                   Opts.DoubleSquareBracketAttributes);
2823
44.7k
2824
44.7k
  Opts.CPlusPlusModules = Opts.CPlusPlus2a;
2825
44.7k
  Opts.ModulesTS = Args.hasArg(OPT_fmodules_ts);
2826
44.7k
  Opts.Modules =
2827
44.7k
      Args.hasArg(OPT_fmodules) || 
Opts.ModulesTS40.7k
||
Opts.CPlusPlusModules40.6k
;
2828
44.7k
  Opts.ModulesStrictDeclUse = Args.hasArg(OPT_fmodules_strict_decluse);
2829
44.7k
  Opts.ModulesDeclUse =
2830
44.7k
      Args.hasArg(OPT_fmodules_decluse) || 
Opts.ModulesStrictDeclUse44.7k
;
2831
44.7k
  // FIXME: We only need this in C++ modules / Modules TS if we might textually
2832
44.7k
  // enter a different module (eg, when building a header unit).
2833
44.7k
  Opts.ModulesLocalVisibility =
2834
44.7k
      Args.hasArg(OPT_fmodules_local_submodule_visibility) || 
Opts.ModulesTS44.7k
||
2835
44.7k
      
Opts.CPlusPlusModules44.5k
;
2836
44.7k
  Opts.ModulesCodegen = Args.hasArg(OPT_fmodules_codegen);
2837
44.7k
  Opts.ModulesDebugInfo = Args.hasArg(OPT_fmodules_debuginfo);
2838
44.7k
  Opts.ModulesSearchAll = Opts.Modules &&
2839
44.7k
    
!Args.hasArg(OPT_fno_modules_search_all)4.47k
&&
2840
44.7k
    
Args.hasArg(OPT_fmodules_search_all)4.47k
;
2841
44.7k
  Opts.ModulesErrorRecovery = !Args.hasArg(OPT_fno_modules_error_recovery);
2842
44.7k
  Opts.ImplicitModules = !Args.hasArg(OPT_fno_implicit_modules);
2843
44.7k
  Opts.CharIsSigned = Opts.OpenCL || 
!Args.hasArg(OPT_fno_signed_char)44.1k
;
2844
44.7k
  Opts.WChar = Opts.CPlusPlus && 
!Args.hasArg(OPT_fno_wchar)30.7k
;
2845
44.7k
  Opts.Char8 = Args.hasFlag(OPT_fchar8__t, OPT_fno_char8__t, Opts.CPlusPlus2a);
2846
44.7k
  if (const Arg *A = Args.getLastArg(OPT_fwchar_type_EQ)) {
2847
35
    Opts.WCharSize = llvm::StringSwitch<unsigned>(A->getValue())
2848
35
                         .Case("char", 1)
2849
35
                         .Case("short", 2)
2850
35
                         .Case("int", 4)
2851
35
                         .Default(0);
2852
35
    if (Opts.WCharSize == 0)
2853
0
      Diags.Report(diag::err_fe_invalid_wchar_type) << A->getValue();
2854
35
  }
2855
44.7k
  Opts.WCharIsSigned = Args.hasFlag(OPT_fsigned_wchar, OPT_fno_signed_wchar, true);
2856
44.7k
  Opts.ShortEnums = Args.hasArg(OPT_fshort_enums);
2857
44.7k
  Opts.Freestanding = Args.hasArg(OPT_ffreestanding);
2858
44.7k
  Opts.NoBuiltin = Args.hasArg(OPT_fno_builtin) || 
Opts.Freestanding39.2k
;
2859
44.7k
  if (!Opts.NoBuiltin)
2860
38.6k
    getAllNoBuiltinFuncValues(Args, Opts.NoBuiltinFuncs);
2861
44.7k
  Opts.NoMathBuiltin = Args.hasArg(OPT_fno_math_builtin);
2862
44.7k
  Opts.RelaxedTemplateTemplateArgs =
2863
44.7k
      Args.hasArg(OPT_frelaxed_template_template_args);
2864
44.7k
  Opts.SizedDeallocation = Args.hasArg(OPT_fsized_deallocation);
2865
44.7k
  Opts.AlignedAllocation =
2866
44.7k
      Args.hasFlag(OPT_faligned_allocation, OPT_fno_aligned_allocation,
2867
44.7k
                   Opts.AlignedAllocation);
2868
44.7k
  Opts.AlignedAllocationUnavailable =
2869
44.7k
      Opts.AlignedAllocation && 
Args.hasArg(OPT_aligned_alloc_unavailable)1.09k
;
2870
44.7k
  Opts.NewAlignOverride =
2871
44.7k
      getLastArgIntValue(Args, OPT_fnew_alignment_EQ, 0, Diags);
2872
44.7k
  if (Opts.NewAlignOverride && 
!llvm::isPowerOf2_32(Opts.NewAlignOverride)2
) {
2873
0
    Arg *A = Args.getLastArg(OPT_fnew_alignment_EQ);
2874
0
    Diags.Report(diag::err_fe_invalid_alignment) << A->getAsString(Args)
2875
0
                                                 << A->getValue();
2876
0
    Opts.NewAlignOverride = 0;
2877
0
  }
2878
44.7k
  Opts.ConceptSatisfactionCaching =
2879
44.7k
      !Args.hasArg(OPT_fno_concept_satisfaction_caching);
2880
44.7k
  if (Args.hasArg(OPT_fconcepts_ts))
2881
0
    Diags.Report(diag::warn_fe_concepts_ts_flag);
2882
44.7k
  Opts.HeinousExtensions = Args.hasArg(OPT_fheinous_gnu_extensions);
2883
44.7k
  Opts.AccessControl = !Args.hasArg(OPT_fno_access_control);
2884
44.7k
  Opts.ElideConstructors = !Args.hasArg(OPT_fno_elide_constructors);
2885
44.7k
  Opts.MathErrno = !Opts.OpenCL && 
Args.hasArg(OPT_fmath_errno)44.1k
;
2886
44.7k
  Opts.InstantiationDepth =
2887
44.7k
      getLastArgIntValue(Args, OPT_ftemplate_depth, 1024, Diags);
2888
44.7k
  Opts.ArrowDepth =
2889
44.7k
      getLastArgIntValue(Args, OPT_foperator_arrow_depth, 256, Diags);
2890
44.7k
  Opts.ConstexprCallDepth =
2891
44.7k
      getLastArgIntValue(Args, OPT_fconstexpr_depth, 512, Diags);
2892
44.7k
  Opts.ConstexprStepLimit =
2893
44.7k
      getLastArgIntValue(Args, OPT_fconstexpr_steps, 1048576, Diags);
2894
44.7k
  Opts.EnableNewConstInterp =
2895
44.7k
      Args.hasArg(OPT_fexperimental_new_constant_interpreter);
2896
44.7k
  Opts.BracketDepth = getLastArgIntValue(Args, OPT_fbracket_depth, 256, Diags);
2897
44.7k
  Opts.DelayedTemplateParsing = Args.hasArg(OPT_fdelayed_template_parsing);
2898
44.7k
  Opts.NumLargeByValueCopy =
2899
44.7k
      getLastArgIntValue(Args, OPT_Wlarge_by_value_copy_EQ, 0, Diags);
2900
44.7k
  Opts.MSBitfields = Args.hasArg(OPT_mms_bitfields);
2901
44.7k
  Opts.ObjCConstantStringClass =
2902
44.7k
      std::string(Args.getLastArgValue(OPT_fconstant_string_class));
2903
44.7k
  Opts.ObjCDefaultSynthProperties =
2904
44.7k
    !Args.hasArg(OPT_disable_objc_default_synthesize_properties);
2905
44.7k
  Opts.EncodeExtendedBlockSig =
2906
44.7k
    Args.hasArg(OPT_fencode_extended_block_signature);
2907
44.7k
  Opts.EmitAllDecls = Args.hasArg(OPT_femit_all_decls);
2908
44.7k
  Opts.PackStruct = getLastArgIntValue(Args, OPT_fpack_struct_EQ, 0, Diags);
2909
44.7k
  Opts.MaxTypeAlign = getLastArgIntValue(Args, OPT_fmax_type_align_EQ, 0, Diags);
2910
44.7k
  Opts.AlignDouble = Args.hasArg(OPT_malign_double);
2911
44.7k
  Opts.LongDoubleSize = Args.hasArg(OPT_mlong_double_128)
2912
44.7k
                            ? 
1286
2913
44.7k
                            : 
Args.hasArg(OPT_mlong_double_64) 44.7k
?
647
:
044.7k
;
2914
44.7k
  Opts.PPCIEEELongDouble = Args.hasArg(OPT_mabi_EQ_ieeelongdouble);
2915
44.7k
  Opts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags);
2916
44.7k
  Opts.ROPI = Args.hasArg(OPT_fropi);
2917
44.7k
  Opts.RWPI = Args.hasArg(OPT_frwpi);
2918
44.7k
  Opts.PIE = Args.hasArg(OPT_pic_is_pie);
2919
44.7k
  Opts.Static = Args.hasArg(OPT_static_define);
2920
44.7k
  Opts.DumpRecordLayoutsSimple = Args.hasArg(OPT_fdump_record_layouts_simple);
2921
44.7k
  Opts.DumpRecordLayouts = Opts.DumpRecordLayoutsSimple
2922
44.7k
                        || 
Args.hasArg(OPT_fdump_record_layouts)44.7k
;
2923
44.7k
  Opts.DumpVTableLayouts = Args.hasArg(OPT_fdump_vtable_layouts);
2924
44.7k
  Opts.SpellChecking = !Args.hasArg(OPT_fno_spell_checking);
2925
44.7k
  Opts.NoBitFieldTypeAlign = Args.hasArg(OPT_fno_bitfield_type_align);
2926
44.7k
  Opts.SinglePrecisionConstants = Args.hasArg(OPT_cl_single_precision_constant);
2927
44.7k
  Opts.FastRelaxedMath = Args.hasArg(OPT_cl_fast_relaxed_math);
2928
44.7k
  Opts.HexagonQdsp6Compat = Args.hasArg(OPT_mqdsp6_compat);
2929
44.7k
  Opts.FakeAddressSpaceMap = Args.hasArg(OPT_ffake_address_space_map);
2930
44.7k
  Opts.ParseUnknownAnytype = Args.hasArg(OPT_funknown_anytype);
2931
44.7k
  Opts.DebuggerSupport = Args.hasArg(OPT_fdebugger_support);
2932
44.7k
  Opts.DebuggerCastResultToId = Args.hasArg(OPT_fdebugger_cast_result_to_id);
2933
44.7k
  Opts.DebuggerObjCLiteral = Args.hasArg(OPT_fdebugger_objc_literal);
2934
44.7k
  Opts.ApplePragmaPack = Args.hasArg(OPT_fapple_pragma_pack);
2935
44.7k
  Opts.ModuleName = std::string(Args.getLastArgValue(OPT_fmodule_name_EQ));
2936
44.7k
  Opts.CurrentModule = Opts.ModuleName;
2937
44.7k
  Opts.AppExt = Args.hasArg(OPT_fapplication_extension);
2938
44.7k
  Opts.ModuleFeatures = Args.getAllArgValues(OPT_fmodule_feature);
2939
44.7k
  llvm::sort(Opts.ModuleFeatures);
2940
44.7k
  Opts.NativeHalfType |= Args.hasArg(OPT_fnative_half_type);
2941
44.7k
  Opts.NativeHalfArgsAndReturns |= Args.hasArg(OPT_fnative_half_arguments_and_returns);
2942
44.7k
  // Enable HalfArgsAndReturns if present in Args or if NativeHalfArgsAndReturns
2943
44.7k
  // is enabled.
2944
44.7k
  Opts.HalfArgsAndReturns = Args.hasArg(OPT_fallow_half_arguments_and_returns)
2945
44.7k
                            | Opts.NativeHalfArgsAndReturns;
2946
44.7k
  Opts.GNUAsm = !Args.hasArg(OPT_fno_gnu_inline_asm);
2947
44.7k
  Opts.Cmse = Args.hasArg(OPT_mcmse); // Armv8-M Security Extensions
2948
44.7k
2949
44.7k
  // __declspec is enabled by default for the PS4 by the driver, and also
2950
44.7k
  // enabled for Microsoft Extensions or Borland Extensions, here.
2951
44.7k
  //
2952
44.7k
  // FIXME: __declspec is also currently enabled for CUDA, but isn't really a
2953
44.7k
  // CUDA extension. However, it is required for supporting
2954
44.7k
  // __clang_cuda_builtin_vars.h, which uses __declspec(property). Once that has
2955
44.7k
  // been rewritten in terms of something more generic, remove the Opts.CUDA
2956
44.7k
  // term here.
2957
44.7k
  Opts.DeclSpecKeyword =
2958
44.7k
      Args.hasFlag(OPT_fdeclspec, OPT_fno_declspec,
2959
44.7k
                   (Opts.MicrosoftExt || 
Opts.Borland41.6k
||
Opts.CUDA41.6k
));
2960
44.7k
2961
44.7k
  if (Arg *A = Args.getLastArg(OPT_faddress_space_map_mangling_EQ)) {
2962
5
    switch (llvm::StringSwitch<unsigned>(A->getValue())
2963
5
      .Case("target", LangOptions::ASMM_Target)
2964
5
      .Case("no", LangOptions::ASMM_Off)
2965
5
      .Case("yes", LangOptions::ASMM_On)
2966
5
      .Default(255)) {
2967
0
    default:
2968
0
      Diags.Report(diag::err_drv_invalid_value)
2969
0
        << "-faddress-space-map-mangling=" << A->getValue();
2970
0
      break;
2971
0
    case LangOptions::ASMM_Target:
2972
0
      Opts.setAddressSpaceMapMangling(LangOptions::ASMM_Target);
2973
0
      break;
2974
2
    case LangOptions::ASMM_On:
2975
2
      Opts.setAddressSpaceMapMangling(LangOptions::ASMM_On);
2976
2
      break;
2977
3
    case LangOptions::ASMM_Off:
2978
3
      Opts.setAddressSpaceMapMangling(LangOptions::ASMM_Off);
2979
3
      break;
2980
44.7k
    }
2981
44.7k
  }
2982
44.7k
2983
44.7k
  if (Arg *A = Args.getLastArg(OPT_fms_memptr_rep_EQ)) {
2984
1
    LangOptions::PragmaMSPointersToMembersKind InheritanceModel =
2985
1
        llvm::StringSwitch<LangOptions::PragmaMSPointersToMembersKind>(
2986
1
            A->getValue())
2987
1
            .Case("single",
2988
1
                  LangOptions::PPTMK_FullGeneralitySingleInheritance)
2989
1
            .Case("multiple",
2990
1
                  LangOptions::PPTMK_FullGeneralityMultipleInheritance)
2991
1
            .Case("virtual",
2992
1
                  LangOptions::PPTMK_FullGeneralityVirtualInheritance)
2993
1
            .Default(LangOptions::PPTMK_BestCase);
2994
1
    if (InheritanceModel == LangOptions::PPTMK_BestCase)
2995
0
      Diags.Report(diag::err_drv_invalid_value)
2996
0
          << "-fms-memptr-rep=" << A->getValue();
2997
1
2998
1
    Opts.setMSPointerToMemberRepresentationMethod(InheritanceModel);
2999
1
  }
3000
44.7k
3001
44.7k
  // Check for MS default calling conventions being specified.
3002
44.7k
  if (Arg *A = Args.getLastArg(OPT_fdefault_calling_conv_EQ)) {
3003
8
    LangOptions::DefaultCallingConvention DefaultCC =
3004
8
        llvm::StringSwitch<LangOptions::DefaultCallingConvention>(A->getValue())
3005
8
            .Case("cdecl", LangOptions::DCC_CDecl)
3006
8
            .Case("fastcall", LangOptions::DCC_FastCall)
3007
8
            .Case("stdcall", LangOptions::DCC_StdCall)
3008
8
            .Case("vectorcall", LangOptions::DCC_VectorCall)
3009
8
            .Case("regcall", LangOptions::DCC_RegCall)
3010
8
            .Default(LangOptions::DCC_None);
3011
8
    if (DefaultCC == LangOptions::DCC_None)
3012
0
      Diags.Report(diag::err_drv_invalid_value)
3013
0
          << "-fdefault-calling-conv=" << A->getValue();
3014
8
3015
8
    llvm::Triple T(TargetOpts.Triple);
3016
8
    llvm::Triple::ArchType Arch = T.getArch();
3017
8
    bool emitError = (DefaultCC == LangOptions::DCC_FastCall ||
3018
8
                      
DefaultCC == LangOptions::DCC_StdCall7
) &&
3019
8
                     
Arch != llvm::Triple::x863
;
3020
8
    emitError |= (DefaultCC == LangOptions::DCC_VectorCall ||
3021
8
                  
DefaultCC == LangOptions::DCC_RegCall5
) &&
3022
8
                 
!T.isX86()4
;
3023
8
    if (emitError)
3024
0
      Diags.Report(diag::err_drv_argument_not_allowed_with)
3025
0
          << A->getSpelling() << T.getTriple();
3026
8
    else
3027
8
      Opts.setDefaultCallingConv(DefaultCC);
3028
8
  }
3029
44.7k
3030
44.7k
  Opts.SemanticInterposition = Args.hasArg(OPT_fsemantic_interposition);
3031
44.7k
3032
44.7k
  // -mrtd option
3033
44.7k
  if (Arg *A = Args.getLastArg(OPT_mrtd)) {
3034
5
    if (Opts.getDefaultCallingConv() != LangOptions::DCC_None)
3035
0
      Diags.Report(diag::err_drv_argument_not_allowed_with)
3036
0
          << A->getSpelling() << "-fdefault-calling-conv";
3037
5
    else {
3038
5
      llvm::Triple T(TargetOpts.Triple);
3039
5
      if (T.getArch() != llvm::Triple::x86)
3040
0
        Diags.Report(diag::err_drv_argument_not_allowed_with)
3041
0
            << A->getSpelling() << T.getTriple();
3042
5
      else
3043
5
        Opts.setDefaultCallingConv(LangOptions::DCC_StdCall);
3044
5
    }
3045
5
  }
3046
44.7k
3047
44.7k
  // Check if -fopenmp is specified and set default version to 4.5.
3048
44.7k
  Opts.OpenMP = Args.hasArg(options::OPT_fopenmp) ? 
454.57k
:
040.2k
;
3049
44.7k
  // Check if -fopenmp-simd is specified.
3050
44.7k
  bool IsSimdSpecified =
3051
44.7k
      Args.hasFlag(options::OPT_fopenmp_simd, options::OPT_fno_openmp_simd,
3052
44.7k
                   /*Default=*/false);
3053
44.7k
  Opts.OpenMPSimd = !Opts.OpenMP && 
IsSimdSpecified40.2k
;
3054
44.7k
  Opts.OpenMPUseTLS =
3055
44.7k
      Opts.OpenMP && 
!Args.hasArg(options::OPT_fnoopenmp_use_tls)4.57k
;
3056
44.7k
  Opts.OpenMPIsDevice =
3057
44.7k
      Opts.OpenMP && 
Args.hasArg(options::OPT_fopenmp_is_device)4.57k
;
3058
44.7k
  Opts.OpenMPIRBuilder =
3059
44.7k
      Opts.OpenMP && 
Args.hasArg(options::OPT_fopenmp_enable_irbuilder)4.57k
;
3060
44.7k
  bool IsTargetSpecified =
3061
44.7k
      Opts.OpenMPIsDevice || 
Args.hasArg(options::OPT_fopenmp_targets_EQ)44.2k
;
3062
44.7k
3063
44.7k
  if (Opts.OpenMP || 
Opts.OpenMPSimd40.2k
) {
3064
8.52k
    if (int Version = getLastArgIntValue(
3065
8.52k
            Args, OPT_fopenmp_version_EQ,
3066
8.52k
            (IsSimdSpecified || IsTargetSpecified) ? 45 : Opts.OpenMP, Diags))
3067
8.52k
      Opts.OpenMP = Version;
3068
2
    else if (IsSimdSpecified || 
IsTargetSpecified1
)
3069
1
      Opts.OpenMP = 45;
3070
8.52k
    // Provide diagnostic when a given target is not expected to be an OpenMP
3071
8.52k
    // device or host.
3072
8.52k
    if (!Opts.OpenMPIsDevice) {
3073
8.00k
      switch (T.getArch()) {
3074
8.00k
      default:
3075
8.00k
        break;
3076
0
      // Add unsupported host targets here:
3077
2
      case llvm::Triple::nvptx:
3078
2
      case llvm::Triple::nvptx64:
3079
2
        Diags.Report(diag::err_drv_omp_host_target_not_supported)
3080
2
            << TargetOpts.Triple;
3081
2
        break;
3082
44.7k
      }
3083
44.7k
    }
3084
8.52k
  }
3085
44.7k
3086
44.7k
  // Set the flag to prevent the implementation from emitting device exception
3087
44.7k
  // handling code for those requiring so.
3088
44.7k
  if ((Opts.OpenMPIsDevice && 
T.isNVPTX()521
) ||
Opts.OpenCLCPlusPlus44.6k
) {
3089
195
    Opts.Exceptions = 0;
3090
195
    Opts.CXXExceptions = 0;
3091
195
  }
3092
44.7k
  if (Opts.OpenMPIsDevice && 
T.isNVPTX()521
) {
3093
131
    Opts.OpenMPCUDANumSMs =
3094
131
        getLastArgIntValue(Args, options::OPT_fopenmp_cuda_number_of_sm_EQ,
3095
131
                           Opts.OpenMPCUDANumSMs, Diags);
3096
131
    Opts.OpenMPCUDABlocksPerSM =
3097
131
        getLastArgIntValue(Args, options::OPT_fopenmp_cuda_blocks_per_sm_EQ,
3098
131
                           Opts.OpenMPCUDABlocksPerSM, Diags);
3099
131
    Opts.OpenMPCUDAReductionBufNum = getLastArgIntValue(
3100
131
        Args, options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ,
3101
131
        Opts.OpenMPCUDAReductionBufNum, Diags);
3102
131
  }
3103
44.7k
3104
44.7k
  // Prevent auto-widening the representation of loop counters during an
3105
44.7k
  // OpenMP collapse clause.
3106
44.7k
  Opts.OpenMPOptimisticCollapse =
3107
44.7k
      Args.hasArg(options::OPT_fopenmp_optimistic_collapse) ? 
11
:
044.7k
;
3108
44.7k
3109
44.7k
  // Get the OpenMP target triples if any.
3110
44.7k
  if (Arg *A = Args.getLastArg(options::OPT_fopenmp_targets_EQ)) {
3111
4.73k
3112
9.46k
    for (unsigned i = 0; i < A->getNumValues(); 
++i4.73k
) {
3113
4.73k
      llvm::Triple TT(A->getValue(i));
3114
4.73k
3115
4.73k
      if (TT.getArch() == llvm::Triple::UnknownArch ||
3116
4.73k
          
!(4.73k
TT.getArch() == llvm::Triple::aarch644.73k
||
3117
4.73k
            
TT.getArch() == llvm::Triple::ppc4.73k
||
3118
4.73k
            
TT.getArch() == llvm::Triple::ppc644.73k
||
3119
4.73k
            
TT.getArch() == llvm::Triple::ppc64le4.73k
||
3120
4.73k
            
TT.getArch() == llvm::Triple::nvptx2.31k
||
3121
4.73k
            
TT.getArch() == llvm::Triple::nvptx642.23k
||
3122
4.73k
            
TT.getArch() == llvm::Triple::x862.10k
||
3123
4.73k
            
TT.getArch() == llvm::Triple::x86_646
))
3124
3
        Diags.Report(diag::err_drv_invalid_omp_target) << A->getValue(i);
3125
4.73k
      else
3126
4.73k
        Opts.OMPTargetTriples.push_back(TT);
3127
4.73k
    }
3128
4.73k
  }
3129
44.7k
3130
44.7k
  // Get OpenMP host file path if any and report if a non existent file is
3131
44.7k
  // found
3132
44.7k
  if (Arg *A = Args.getLastArg(options::OPT_fopenmp_host_ir_file_path)) {
3133
889
    Opts.OMPHostIRFile = A->getValue();
3134
889
    if (!llvm::sys::fs::exists(Opts.OMPHostIRFile))
3135
1
      Diags.Report(diag::err_drv_omp_host_ir_file_not_found)
3136
1
          << Opts.OMPHostIRFile;
3137
889
  }
3138
44.7k
3139
44.7k
  Opts.SYCLIsDevice = Args.hasArg(options::OPT_fsycl_is_device);
3140
44.7k
3141
44.7k
  // Set CUDA mode for OpenMP target NVPTX if specified in options
3142
44.7k
  Opts.OpenMPCUDAMode = Opts.OpenMPIsDevice && 
T.isNVPTX()521
&&
3143
44.7k
                        
Args.hasArg(options::OPT_fopenmp_cuda_mode)131
;
3144
44.7k
3145
44.7k
  // Set CUDA mode for OpenMP target NVPTX if specified in options
3146
44.7k
  Opts.OpenMPCUDAForceFullRuntime =
3147
44.7k
      Opts.OpenMPIsDevice && 
T.isNVPTX()521
&&
3148
44.7k
      
Args.hasArg(options::OPT_fopenmp_cuda_force_full_runtime)131
;
3149
44.7k
3150
44.7k
  // Record whether the __DEPRECATED define was requested.
3151
44.7k
  Opts.Deprecated = Args.hasFlag(OPT_fdeprecated_macro,
3152
44.7k
                                 OPT_fno_deprecated_macro,
3153
44.7k
                                 Opts.Deprecated);
3154
44.7k
3155
44.7k
  // FIXME: Eliminate this dependency.
3156
44.7k
  unsigned Opt = getOptimizationLevel(Args, IK, Diags),
3157
44.7k
       OptSize = getOptimizationLevelSize(Args);
3158
44.7k
  Opts.Optimize = Opt != 0;
3159
44.7k
  Opts.OptimizeSize = OptSize != 0;
3160
44.7k
3161
44.7k
  // This is the __NO_INLINE__ define, which just depends on things like the
3162
44.7k
  // optimization level and -fno-inline, not actually whether the backend has
3163
44.7k
  // inlining enabled.
3164
44.7k
  Opts.NoInlineDefine = !Opts.Optimize;
3165
44.7k
  if (Arg *InlineArg = Args.getLastArg(
3166
20
          options::OPT_finline_functions, options::OPT_finline_hint_functions,
3167
20
          options::OPT_fno_inline_functions, options::OPT_fno_inline))
3168
20
    if (InlineArg->getOption().matches(options::OPT_fno_inline))
3169
9
      Opts.NoInlineDefine = true;
3170
44.7k
3171
44.7k
  Opts.FastMath = Args.hasArg(OPT_ffast_math) ||
3172
44.7k
      
Args.hasArg(OPT_cl_fast_relaxed_math)44.7k
;
3173
44.7k
  Opts.FiniteMathOnly = Args.hasArg(OPT_ffinite_math_only) ||
3174
44.7k
      
Args.hasArg(OPT_cl_finite_math_only)44.7k
||
3175
44.7k
      
Args.hasArg(OPT_cl_fast_relaxed_math)44.7k
;
3176
44.7k
  Opts.UnsafeFPMath = Args.hasArg(OPT_menable_unsafe_fp_math) ||
3177
44.7k
                      
Args.hasArg(OPT_cl_unsafe_math_optimizations)44.7k
||
3178
44.7k
                      
Args.hasArg(OPT_cl_fast_relaxed_math)44.7k
;
3179
44.7k
3180
44.7k
  if (Arg *A = Args.getLastArg(OPT_ffp_contract)) {
3181
24
    StringRef Val = A->getValue();
3182
24
    if (Val == "fast")
3183
22
      Opts.setDefaultFPContractMode(LangOptions::FPC_Fast);
3184
2
    else if (Val == "on")
3185
1
      Opts.setDefaultFPContractMode(LangOptions::FPC_On);
3186
1
    else if (Val == "off")
3187
1
      Opts.setDefaultFPContractMode(LangOptions::FPC_Off);
3188
0
    else
3189
0
      Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
3190
24
  }
3191
44.7k
3192
44.7k
  LangOptions::FPRoundingModeKind FPRM = LangOptions::FPR_ToNearest;
3193
44.7k
  if (Args.hasArg(OPT_frounding_math)) {
3194
8
    FPRM = LangOptions::FPR_Dynamic;
3195
8
  }
3196
44.7k
  Opts.setFPRoundingMode(FPRM);
3197
44.7k
3198
44.7k
  if (Args.hasArg(OPT_ftrapping_math)) {
3199
3
    Opts.setFPExceptionMode(LangOptions::FPE_Strict);
3200
3
  }
3201
44.7k
3202
44.7k
  if (Args.hasArg(OPT_fno_trapping_math)) {
3203
6
    Opts.setFPExceptionMode(LangOptions::FPE_Ignore);
3204
6
  }
3205
44.7k
3206
44.7k
  LangOptions::FPExceptionModeKind FPEB = LangOptions::FPE_Ignore;
3207
44.7k
  if (Arg *A = Args.getLastArg(OPT_ffp_exception_behavior_EQ)) {
3208
43
    StringRef Val = A->getValue();
3209
43
    if (Val.equals("ignore"))
3210
8
      FPEB = LangOptions::FPE_Ignore;
3211
35
    else if (Val.equals("maytrap"))
3212
6
      FPEB = LangOptions::FPE_MayTrap;
3213
29
    else if (Val.equals("strict"))
3214
29
      FPEB = LangOptions::FPE_Strict;
3215
0
    else
3216
0
      Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
3217
43
  }
3218
44.7k
  Opts.setFPExceptionMode(FPEB);
3219
44.7k
3220
44.7k
  Opts.RetainCommentsFromSystemHeaders =
3221
44.7k
      Args.hasArg(OPT_fretain_comments_from_system_headers);
3222
44.7k
3223
44.7k
  unsigned SSP = getLastArgIntValue(Args, OPT_stack_protector, 0, Diags);
3224
44.7k
  switch (SSP) {
3225
0
  default:
3226
0
    Diags.Report(diag::err_drv_invalid_value)
3227
0
      << Args.getLastArg(OPT_stack_protector)->getAsString(Args) << SSP;
3228
0
    break;
3229
29.2k
  case 0: Opts.setStackProtector(LangOptions::SSPOff); break;
3230
15.4k
  case 1: Opts.setStackProtector(LangOptions::SSPOn);  break;
3231
52
  case 2: Opts.setStackProtector(LangOptions::SSPStrong); break;
3232
2
  case 3: Opts.setStackProtector(LangOptions::SSPReq); break;
3233
44.7k
  }
3234
44.7k
3235
44.7k
  if (Arg *A = Args.getLastArg(OPT_ftrivial_auto_var_init)) {
3236
14
    StringRef Val = A->getValue();
3237
14
    if (Val == "uninitialized")
3238
0
      Opts.setTrivialAutoVarInit(
3239
0
          LangOptions::TrivialAutoVarInitKind::Uninitialized);
3240
14
    else if (Val == "zero")
3241
6
      Opts.setTrivialAutoVarInit(LangOptions::TrivialAutoVarInitKind::Zero);
3242
8
    else if (Val == "pattern")
3243
8
      Opts.setTrivialAutoVarInit(LangOptions::TrivialAutoVarInitKind::Pattern);
3244
0
    else
3245
0
      Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
3246
14
  }
3247
44.7k
3248
44.7k
  // Parse -fsanitize= arguments.
3249
44.7k
  parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ),
3250
44.7k
                      Diags, Opts.Sanitize);
3251
44.7k
  // -fsanitize-address-field-padding=N has to be a LangOpt, parse it here.
3252
44.7k
  Opts.SanitizeAddressFieldPadding =
3253
44.7k
      getLastArgIntValue(Args, OPT_fsanitize_address_field_padding, 0, Diags);
3254
44.7k
  Opts.SanitizerBlacklistFiles = Args.getAllArgValues(OPT_fsanitize_blacklist);
3255
44.7k
  std::vector<std::string> systemBlacklists =
3256
44.7k
      Args.getAllArgValues(OPT_fsanitize_system_blacklist);
3257
44.7k
  Opts.SanitizerBlacklistFiles.insert(Opts.SanitizerBlacklistFiles.end(),
3258
44.7k
                                      systemBlacklists.begin(),
3259
44.7k
                                      systemBlacklists.end());
3260
44.7k
3261
44.7k
  // -fxray-instrument
3262
44.7k
  Opts.XRayInstrument = Args.hasArg(OPT_fxray_instrument);
3263
44.7k
  Opts.XRayAlwaysEmitCustomEvents =
3264
44.7k
      Args.hasArg(OPT_fxray_always_emit_customevents);
3265
44.7k
  Opts.XRayAlwaysEmitTypedEvents =
3266
44.7k
      Args.hasArg(OPT_fxray_always_emit_typedevents);
3267
44.7k
3268
44.7k
  // -fxray-{always,never}-instrument= filenames.
3269
44.7k
  Opts.XRayAlwaysInstrumentFiles =
3270
44.7k
      Args.getAllArgValues(OPT_fxray_always_instrument);
3271
44.7k
  Opts.XRayNeverInstrumentFiles =
3272
44.7k
      Args.getAllArgValues(OPT_fxray_never_instrument);
3273
44.7k
  Opts.XRayAttrListFiles = Args.getAllArgValues(OPT_fxray_attr_list);
3274
44.7k
3275
44.7k
  // -fforce-emit-vtables
3276
44.7k
  Opts.ForceEmitVTables = Args.hasArg(OPT_fforce_emit_vtables);
3277
44.7k
3278
44.7k
  // -fallow-editor-placeholders
3279
44.7k
  Opts.AllowEditorPlaceholders = Args.hasArg(OPT_fallow_editor_placeholders);
3280
44.7k
3281
44.7k
  Opts.RegisterStaticDestructors = !Args.hasArg(OPT_fno_cxx_static_destructors);
3282
44.7k
3283
44.7k
  if (Arg *A = Args.getLastArg(OPT_fclang_abi_compat_EQ)) {
3284
34
    Opts.setClangABICompat(LangOptions::ClangABI::Latest);
3285
34
3286
34
    StringRef Ver = A->getValue();
3287
34
    std::pair<StringRef, StringRef> VerParts = Ver.split('.');
3288
34
    unsigned Major, Minor = 0;
3289
34
3290
34
    // Check the version number is valid: either 3.x (0 <= x <= 9) or
3291
34
    // y or y.0 (4 <= y <= current version).
3292
34
    if (!VerParts.first.startswith("0") &&
3293
34
        
!VerParts.first.getAsInteger(10, Major)33
&&
3294
34
        
3 <= Major30
&&
Major <= 29
CLANG_VERSION_MAJOR29
&&
3295
34
        
(Major == 3 28
?
VerParts.second.size() == 16
&&
3296
6
                      
!VerParts.second.getAsInteger(10, Minor)5
3297
28
                    : 
VerParts.first.size() == Ver.size()22
||
3298
24
                      
VerParts.second == "0"12
)) {
3299
24
      // Got a valid version number.
3300
24
      if (Major == 3 && 
Minor <= 85
)
3301
3
        Opts.setClangABICompat(LangOptions::ClangABI::Ver3_8);
3302
21
      else if (Major <= 4)
3303
9
        Opts.setClangABICompat(LangOptions::ClangABI::Ver4);
3304
12
      else if (Major <= 6)
3305
5
        Opts.setClangABICompat(LangOptions::ClangABI::Ver6);
3306
7
      else if (Major <= 7)
3307
4
        Opts.setClangABICompat(LangOptions::ClangABI::Ver7);
3308
3
      else if (Major <= 9)
3309
3
        Opts.setClangABICompat(LangOptions::ClangABI::Ver9);
3310
24
    } else 
if (10
Ver != "latest"10
) {
3311
8
      Diags.Report(diag::err_drv_invalid_value)
3312
8
          << A->getAsString(Args) << A->getValue();
3313
8
    }
3314
34
  }
3315
44.7k
3316
44.7k
  Opts.CompleteMemberPointers = Args.hasArg(OPT_fcomplete_member_pointers);
3317
44.7k
  Opts.BuildingPCHWithObjectFile = Args.hasArg(OPT_building_pch_with_obj);
3318
44.7k
3319
44.7k
  Opts.MaxTokens = getLastArgIntValue(Args, OPT_fmax_tokens_EQ, 0, Diags);
3320
44.7k
}
3321
3322
89.8k
static bool isStrictlyPreprocessorAction(frontend::ActionKind Action) {
3323
89.8k
  switch (Action) {
3324
80.4k
  case frontend::ASTDeclList:
3325
80.4k
  case frontend::ASTDump:
3326
80.4k
  case frontend::ASTPrint:
3327
80.4k
  case frontend::ASTView:
3328
80.4k
  case frontend::EmitAssembly:
3329
80.4k
  case frontend::EmitBC:
3330
80.4k
  case frontend::EmitHTML:
3331
80.4k
  case frontend::EmitLLVM:
3332
80.4k
  case frontend::EmitLLVMOnly:
3333
80.4k
  case frontend::EmitCodeGenOnly:
3334
80.4k
  case frontend::EmitObj:
3335
80.4k
  case frontend::FixIt:
3336
80.4k
  case frontend::GenerateModule:
3337
80.4k
  case frontend::GenerateModuleInterface:
3338
80.4k
  case frontend::GenerateHeaderModule:
3339
80.4k
  case frontend::GeneratePCH:
3340
80.4k
  case frontend::GenerateInterfaceIfsExpV1:
3341
80.4k
  case frontend::ParseSyntaxOnly:
3342
80.4k
  case frontend::ModuleFileInfo:
3343
80.4k
  case frontend::VerifyPCH:
3344
80.4k
  case frontend::PluginAction:
3345
80.4k
  case frontend::RewriteObjC:
3346
80.4k
  case frontend::RewriteTest:
3347
80.4k
  case frontend::RunAnalysis:
3348
80.4k
  case frontend::TemplightDump:
3349
80.4k
  case frontend::MigrateSource:
3350
80.4k
    return false;
3351
80.4k
3352
80.4k
  case frontend::DumpCompilerOptions:
3353
9.40k
  case frontend::DumpRawTokens:
3354
9.40k
  case frontend::DumpTokens:
3355
9.40k
  case frontend::InitOnly:
3356
9.40k
  case frontend::PrintPreamble:
3357
9.40k
  case frontend::PrintPreprocessedInput:
3358
9.40k
  case frontend::RewriteMacros:
3359
9.40k
  case frontend::RunPreprocessorOnly:
3360
9.40k
  case frontend::PrintDependencyDirectivesSourceMinimizerOutput:
3361
9.40k
    return true;
3362
0
  }
3363
0
  llvm_unreachable("invalid frontend action");
3364
0
}
3365
3366
static void ParsePreprocessorArgs(PreprocessorOptions &Opts, ArgList &Args,
3367
                                  DiagnosticsEngine &Diags,
3368
44.9k
                                  frontend::ActionKind Action) {
3369
44.9k
  Opts.ImplicitPCHInclude = std::string(Args.getLastArgValue(OPT_include_pch));
3370
44.9k
  Opts.PCHWithHdrStop = Args.hasArg(OPT_pch_through_hdrstop_create) ||
3371
44.9k
                        
Args.hasArg(OPT_pch_through_hdrstop_use)44.9k
;
3372
44.9k
  Opts.PCHWithHdrStopCreate = Args.hasArg(OPT_pch_through_hdrstop_create);
3373
44.9k
  Opts.PCHThroughHeader =
3374
44.9k
      std::string(Args.getLastArgValue(OPT_pch_through_header_EQ));
3375
44.9k
  Opts.UsePredefines = !Args.hasArg(OPT_undef);
3376
44.9k
  Opts.DetailedRecord = Args.hasArg(OPT_detailed_preprocessing_record);
3377
44.9k
  Opts.DisablePCHValidation = Args.hasArg(OPT_fno_validate_pch);
3378
44.9k
  Opts.AllowPCHWithCompilerErrors = Args.hasArg(OPT_fallow_pch_with_errors);
3379
44.9k
3380
44.9k
  Opts.DumpDeserializedPCHDecls = Args.hasArg(OPT_dump_deserialized_pch_decls);
3381
44.9k
  for (const auto *A : Args.filtered(OPT_error_on_deserialized_pch_decl))
3382
63
    Opts.DeserializedPCHDeclsToErrorOn.insert(A->getValue());
3383
44.9k
3384
44.9k
  for (const auto &A : Args.getAllArgValues(OPT_fmacro_prefix_map_EQ)) {
3385
5
    auto Split = StringRef(A).split('=');
3386
5
    Opts.MacroPrefixMap.insert(
3387
5
        {std::string(Split.first), std::string(Split.second)});
3388
5
  }
3389
44.9k
3390
44.9k
  if (const Arg *A = Args.getLastArg(OPT_preamble_bytes_EQ)) {
3391
1
    StringRef Value(A->getValue());
3392
1
    size_t Comma = Value.find(',');
3393
1
    unsigned Bytes = 0;
3394
1
    unsigned EndOfLine = 0;
3395
1
3396
1
    if (Comma == StringRef::npos ||
3397
1
        Value.substr(0, Comma).getAsInteger(10, Bytes) ||
3398
1
        Value.substr(Comma + 1).getAsInteger(10, EndOfLine))
3399
0
      Diags.Report(diag::err_drv_preamble_format);
3400
1
    else {
3401
1
      Opts.PrecompiledPreambleBytes.first = Bytes;
3402
1
      Opts.PrecompiledPreambleBytes.second = (EndOfLine != 0);
3403
1
    }
3404
1
  }
3405
44.9k
3406
44.9k
  // Add the __CET__ macro if a CFProtection option is set.
3407
44.9k
  if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
3408
8
    StringRef Name = A->getValue();
3409
8
    if (Name == "branch")
3410
6
      Opts.addMacroDef("__CET__=1");
3411
2
    else if (Name == "return")
3412
1
      Opts.addMacroDef("__CET__=2");
3413
1
    else if (Name == "full")
3414
1
      Opts.addMacroDef("__CET__=3");
3415
8
  }
3416
44.9k
3417
44.9k
  // Add macros from the command line.
3418
309k
  for (const auto *A : Args.filtered(OPT_D, OPT_U)) {
3419
309k
    if (A->getOption().matches(OPT_D))
3420
309k
      Opts.addMacroDef(A->getValue());
3421
44
    else
3422
44
      Opts.addMacroUndef(A->getValue());
3423
309k
  }
3424
44.9k
3425
44.9k
  Opts.MacroIncludes = Args.getAllArgValues(OPT_imacros);
3426
44.9k
3427
44.9k
  // Add the ordered list of -includes.
3428
44.9k
  for (const auto *A : Args.filtered(OPT_include))
3429
5.78k
    Opts.Includes.emplace_back(A->getValue());
3430
44.9k
3431
44.9k
  for (const auto *A : Args.filtered(OPT_chain_include))
3432
51
    Opts.ChainedIncludes.emplace_back(A->getValue());
3433
44.9k
3434
44.9k
  for (const auto *A : Args.filtered(OPT_remap_file)) {
3435
5
    std::pair<StringRef, StringRef> Split = StringRef(A->getValue()).split(';');
3436
5
3437
5
    if (Split.second.empty()) {
3438
0
      Diags.Report(diag::err_drv_invalid_remap_file) << A->getAsString(Args);
3439
0
      continue;
3440
0
    }
3441
5
3442
5
    Opts.addRemappedFile(Split.first, Split.second);
3443
5
  }
3444
44.9k
3445
44.9k
  if (Arg *A = Args.getLastArg(OPT_fobjc_arc_cxxlib_EQ)) {
3446
1.16k
    StringRef Name = A->getValue();
3447
1.16k
    unsigned Library = llvm::StringSwitch<unsigned>(Name)
3448
1.16k
      .Case("libc++", ARCXX_libcxx)
3449
1.16k
      .Case("libstdc++", ARCXX_libstdcxx)
3450
1.16k
      .Case("none", ARCXX_nolib)
3451
1.16k
      .Default(~0U);
3452
1.16k
    if (Library == ~0U)
3453
0
      Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
3454
1.16k
    else
3455
1.16k
      Opts.ObjCXXARCStandardLibrary = (ObjCXXARCStandardLibraryKind)Library;
3456
1.16k
  }
3457
44.9k
3458
44.9k
  // Always avoid lexing editor placeholders when we're just running the
3459
44.9k
  // preprocessor as we never want to emit the
3460
44.9k
  // "editor placeholder in source file" error in PP only mode.
3461
44.9k
  if (isStrictlyPreprocessorAction(Action))
3462
4.70k
    Opts.LexEditorPlaceholders = false;
3463
44.9k
3464
44.9k
  Opts.SetUpStaticAnalyzer = Args.hasArg(OPT_setup_static_analyzer);
3465
44.9k
  Opts.DisablePragmaDebugCrash = Args.hasArg(OPT_disable_pragma_debug_crash);
3466
44.9k
}
3467
3468
static void ParsePreprocessorOutputArgs(PreprocessorOutputOptions &Opts,
3469
                                        ArgList &Args,
3470
44.9k
                                        frontend::ActionKind Action) {
3471
44.9k
  if (isStrictlyPreprocessorAction(Action))
3472
4.70k
    Opts.ShowCPP = !Args.hasArg(OPT_dM);
3473
40.2k
  else
3474
40.2k
    Opts.ShowCPP = 0;
3475
44.9k
3476
44.9k
  Opts.ShowComments = Args.hasArg(OPT_C);
3477
44.9k
  Opts.ShowLineMarkers = !Args.hasArg(OPT_P);
3478
44.9k
  Opts.ShowMacroComments = Args.hasArg(OPT_CC);
3479
44.9k
  Opts.ShowMacros = Args.hasArg(OPT_dM) || 
Args.hasArg(OPT_dD)43.6k
;
3480
44.9k
  Opts.ShowIncludeDirectives = Args.hasArg(OPT_dI);
3481
44.9k
  Opts.RewriteIncludes = Args.hasArg(OPT_frewrite_includes);
3482
44.9k
  Opts.RewriteImports = Args.hasArg(OPT_frewrite_imports);
3483
44.9k
  Opts.UseLineDirectives = Args.hasArg(OPT_fuse_line_directives);
3484
44.9k
}
3485
3486
static void ParseTargetArgs(TargetOptions &Opts, ArgList &Args,
3487
44.9k
                            DiagnosticsEngine &Diags) {
3488
44.9k
  Opts.CodeModel = std::string(Args.getLastArgValue(OPT_mcmodel_EQ, "default"));
3489
44.9k
  Opts.ABI = std::string(Args.getLastArgValue(OPT_target_abi));
3490
44.9k
  if (Arg *A = Args.getLastArg(OPT_meabi)) {
3491
29
    StringRef Value = A->getValue();
3492
29
    llvm::EABI EABIVersion = llvm::StringSwitch<llvm::EABI>(Value)
3493
29
                                 .Case("default", llvm::EABI::Default)
3494
29
                                 .Case("4", llvm::EABI::EABI4)
3495
29
                                 .Case("5", llvm::EABI::EABI5)
3496
29
                                 .Case("gnu", llvm::EABI::GNU)
3497
29
                                 .Default(llvm::EABI::Unknown);
3498
29
    if (EABIVersion == llvm::EABI::Unknown)
3499
1
      Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
3500
1
                                                << Value;
3501
28
    else
3502
28
      Opts.EABIVersion = EABIVersion;
3503
29
  }
3504
44.9k
  Opts.CPU = std::string(Args.getLastArgValue(OPT_target_cpu));
3505
44.9k
  Opts.FPMath = std::string(Args.getLastArgValue(OPT_mfpmath));
3506
44.9k
  Opts.FeaturesAsWritten = Args.getAllArgValues(OPT_target_feature);
3507
44.9k
  Opts.LinkerVersion =
3508
44.9k
      std::string(Args.getLastArgValue(OPT_target_linker_version));
3509
44.9k
  Opts.Triple = std::string(Args.getLastArgValue(OPT_triple));
3510
44.9k
  // Use the default target triple if unspecified.
3511
44.9k
  if (Opts.Triple.empty())
3512
11.8k
    Opts.Triple = llvm::sys::getDefaultTargetTriple();
3513
44.9k
  Opts.Triple = llvm::Triple::normalize(Opts.Triple);
3514
44.9k
  Opts.OpenCLExtensionsAsWritten = Args.getAllArgValues(OPT_cl_ext_EQ);
3515
44.9k
  Opts.ForceEnableInt128 = Args.hasArg(OPT_fforce_enable_int128);
3516
44.9k
  Opts.NVPTXUseShortPointers = Args.hasFlag(
3517
44.9k
      options::OPT_fcuda_short_ptr, options::OPT_fno_cuda_short_ptr, false);
3518
44.9k
  if (Arg *A = Args.getLastArg(options::OPT_target_sdk_version_EQ)) {
3519
8.54k
    llvm::VersionTuple Version;
3520
8.54k
    if (Version.tryParse(A->getValue()))
3521
0
      Diags.Report(diag::err_drv_invalid_value)
3522
0
          << A->getAsString(Args) << A->getValue();
3523
8.54k
    else
3524
8.54k
      Opts.SDKVersion = Version;
3525
8.54k
  }
3526
44.9k
}
3527
3528
bool CompilerInvocation::CreateFromArgs(CompilerInvocation &Res,
3529
                                        ArrayRef<const char *> CommandLineArgs,
3530
44.9k
                                        DiagnosticsEngine &Diags) {
3531
44.9k
  bool Success = true;
3532
44.9k
3533
44.9k
  // Parse the arguments.
3534
44.9k
  const OptTable &Opts = getDriverOptTable();
3535
44.9k
  const unsigned IncludedFlagsBitmask = options::CC1Option;
3536
44.9k
  unsigned MissingArgIndex, MissingArgCount;
3537
44.9k
  InputArgList Args = Opts.ParseArgs(CommandLineArgs, MissingArgIndex,
3538
44.9k
                                     MissingArgCount, IncludedFlagsBitmask);
3539
44.9k
  LangOptions &LangOpts = *Res.getLangOpts();
3540
44.9k
3541
44.9k
  // Check for missing argument error.
3542
44.9k
  if (MissingArgCount) {
3543
0
    Diags.Report(diag::err_drv_missing_argument)
3544
0
        << Args.getArgString(MissingArgIndex) << MissingArgCount;
3545
0
    Success = false;
3546
0
  }
3547
44.9k
3548
44.9k
  // Issue errors on unknown arguments.
3549
44.9k
  for (const auto *A : Args.filtered(OPT_UNKNOWN)) {
3550
9
    auto ArgString = A->getAsString(Args);
3551
9
    std::string Nearest;
3552
9
    if (Opts.findNearest(ArgString, Nearest, IncludedFlagsBitmask) > 1)
3553
7
      Diags.Report(diag::err_drv_unknown_argument) << ArgString;
3554
2
    else
3555
2
      Diags.Report(diag::err_drv_unknown_argument_with_suggestion)
3556
2
          << ArgString << Nearest;
3557
9
    Success = false;
3558
9
  }
3559
44.9k
3560
44.9k
  Success &= ParseAnalyzerArgs(*Res.getAnalyzerOpts(), Args, Diags);
3561
44.9k
  Success &= ParseMigratorArgs(Res.getMigratorOpts(), Args);
3562
44.9k
  ParseDependencyOutputArgs(Res.getDependencyOutputOpts(), Args);
3563
44.9k
  if (!Res.getDependencyOutputOpts().OutputFile.empty() &&
3564
44.9k
      
Res.getDependencyOutputOpts().Targets.empty()2.85k
) {
3565
0
    Diags.Report(diag::err_fe_dependency_file_requires_MT);
3566
0
    Success = false;
3567
0
  }
3568
44.9k
  Success &=
3569
44.9k
      ParseDiagnosticArgs(Res.getDiagnosticOpts(), Args, &Diags,
3570
44.9k
                          false /*DefaultDiagColor*/, false /*DefaultShowOpt*/);
3571
44.9k
  ParseCommentArgs(LangOpts.CommentOpts, Args);
3572
44.9k
  ParseFileSystemArgs(Res.getFileSystemOpts(), Args);
3573
44.9k
  // FIXME: We shouldn't have to pass the DashX option around here
3574
44.9k
  InputKind DashX = ParseFrontendArgs(Res.getFrontendOpts(), Args, Diags,
3575
44.9k
                                      LangOpts.IsHeaderFile);
3576
44.9k
  ParseTargetArgs(Res.getTargetOpts(), Args, Diags);
3577
44.9k
  Success &= ParseCodeGenArgs(Res.getCodeGenOpts(), Args, DashX, Diags,
3578
44.9k
                              Res.getTargetOpts(), Res.getFrontendOpts());
3579
44.9k
  ParseHeaderSearchArgs(Res.getHeaderSearchOpts(), Args,
3580
44.9k
                        Res.getFileSystemOpts().WorkingDir);
3581
44.9k
  llvm::Triple T(Res.getTargetOpts().Triple);
3582
44.9k
  if (DashX.getFormat() == InputKind::Precompiled ||
3583
44.9k
      
DashX.getLanguage() == Language::LLVM_IR44.8k
) {
3584
141
    // ObjCAAutoRefCount and Sanitize LangOpts are used to setup the
3585
141
    // PassManager in BackendUtil.cpp. They need to be initializd no matter
3586
141
    // what the input type is.
3587
141
    if (Args.hasArg(OPT_fobjc_arc))
3588
1
      LangOpts.ObjCAutoRefCount = 1;
3589
141
    // PIClevel and PIELevel are needed during code generation and this should be
3590
141
    // set regardless of the input type.
3591
141
    LangOpts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags);
3592
141
    LangOpts.PIE = Args.hasArg(OPT_pic_is_pie);
3593
141
    parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ),
3594
141
                        Diags, LangOpts.Sanitize);
3595
44.7k
  } else {
3596
44.7k
    // Other LangOpts are only initialized when the input is not AST or LLVM IR.
3597
44.7k
    // FIXME: Should we really be calling this for an Language::Asm input?
3598
44.7k
    ParseLangArgs(LangOpts, Args, DashX, Res.getTargetOpts(),
3599
44.7k
                  Res.getPreprocessorOpts(), Diags);
3600
44.7k
    if (Res.getFrontendOpts().ProgramAction == frontend::RewriteObjC)
3601
164
      LangOpts.ObjCExceptions = 1;
3602
44.7k
    if (T.isOSDarwin() && 
DashX.isPreprocessed()30.8k
) {
3603
20
      // Supress the darwin-specific 'stdlibcxx-not-found' diagnostic for
3604
20
      // preprocessed input as we don't expect it to be used with -std=libc++
3605
20
      // anyway.
3606
20
      Res.getDiagnosticOpts().Warnings.push_back("no-stdlibcxx-not-found");
3607
20
    }
3608
44.7k
  }
3609
44.9k
3610
44.9k
  if (Diags.isIgnored(diag::warn_profile_data_misexpect, SourceLocation()))
3611
44.9k
    Res.FrontendOpts.LLVMArgs.push_back("-pgo-warn-misexpect");
3612
44.9k
3613
44.9k
  LangOpts.FunctionAlignment =
3614
44.9k
      getLastArgIntValue(Args, OPT_function_alignment, 0, Diags);
3615
44.9k
3616
44.9k
  if (LangOpts.CUDA) {
3617
292
    // During CUDA device-side compilation, the aux triple is the
3618
292
    // triple used for host compilation.
3619
292
    if (LangOpts.CUDAIsDevice)
3620
155
      Res.getTargetOpts().HostTriple = Res.getFrontendOpts().AuxTriple;
3621
292
  }
3622
44.9k
3623
44.9k
  // Set the triple of the host for OpenMP device compile.
3624
44.9k
  if (LangOpts.OpenMPIsDevice)
3625
521
    Res.getTargetOpts().HostTriple = Res.getFrontendOpts().AuxTriple;
3626
44.9k
3627
44.9k
  // FIXME: Override value name discarding when asan or msan is used because the
3628
44.9k
  // backend passes depend on the name of the alloca in order to print out
3629
44.9k
  // names.
3630
44.9k
  Res.getCodeGenOpts().DiscardValueNames &=
3631
44.9k
      !LangOpts.Sanitize.has(SanitizerKind::Address) &&
3632
44.9k
      
!LangOpts.Sanitize.has(SanitizerKind::KernelAddress)44.8k
&&
3633
44.9k
      
!LangOpts.Sanitize.has(SanitizerKind::Memory)44.8k
&&
3634
44.9k
      
!LangOpts.Sanitize.has(SanitizerKind::KernelMemory)44.8k
;
3635
44.9k
3636
44.9k
  ParsePreprocessorArgs(Res.getPreprocessorOpts(), Args, Diags,
3637
44.9k
                        Res.getFrontendOpts().ProgramAction);
3638
44.9k
  ParsePreprocessorOutputArgs(Res.getPreprocessorOutputOpts(), Args,
3639
44.9k
                              Res.getFrontendOpts().ProgramAction);
3640
44.9k
3641
44.9k
  // Turn on -Wspir-compat for SPIR target.
3642
44.9k
  if (T.isSPIR())
3643
177
    Res.getDiagnosticOpts().Warnings.push_back("spir-compat");
3644
44.9k
3645
44.9k
  // If sanitizer is enabled, disable OPT_ffine_grained_bitfield_accesses.
3646
44.9k
  if (Res.getCodeGenOpts().FineGrainedBitfieldAccesses &&
3647
44.9k
      
!Res.getLangOpts()->Sanitize.empty()3
) {
3648
1
    Res.getCodeGenOpts().FineGrainedBitfieldAccesses = false;
3649
1
    Diags.Report(diag::warn_drv_fine_grained_bitfield_accesses_ignored);
3650
1
  }
3651
44.9k
  return Success;
3652
44.9k
}
3653
3654
9.01k
std::string CompilerInvocation::getModuleHash() const {
3655
9.01k
  // Note: For QoI reasons, the things we use as a hash here should all be
3656
9.01k
  // dumped via the -module-info flag.
3657
9.01k
  using llvm::hash_code;
3658
9.01k
  using llvm::hash_value;
3659
9.01k
  using llvm::hash_combine;
3660
9.01k
  using llvm::hash_combine_range;
3661
9.01k
3662
9.01k
  // Start the signature with the compiler version.
3663
9.01k
  // FIXME: We'd rather use something more cryptographically sound than
3664
9.01k
  // CityHash, but this will do for now.
3665
9.01k
  hash_code code = hash_value(getClangFullRepositoryVersion());
3666
9.01k
3667
9.01k
  // Also include the serialization version, in case LLVM_APPEND_VC_REV is off
3668
9.01k
  // and getClangFullRepositoryVersion() doesn't include git revision.
3669
9.01k
  code = hash_combine(code, serialization::VERSION_MAJOR,
3670
9.01k
                      serialization::VERSION_MINOR);
3671
9.01k
3672
9.01k
  // Extend the signature with the language options
3673
9.01k
#define LANGOPT(Name, Bits, Default, Description) \
3674
1.36M
   code = hash_combine(code, LangOpts->Name);
3675
9.01k
#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
3676
135k
  code = hash_combine(code, static_cast<unsigned>(LangOpts->get##Name()));
3677
9.01k
#define BENIGN_LANGOPT(Name, Bits, Default, Description)
3678
9.01k
#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
3679
9.01k
#include "clang/Basic/LangOptions.def"
3680
9.01k
3681
9.01k
  for (StringRef Feature : LangOpts->ModuleFeatures)
3682
40
    code = hash_combine(code, Feature);
3683
9.01k
3684
9.01k
  // Extend the signature with the target options.
3685
9.01k
  code = hash_combine(code, TargetOpts->Triple, TargetOpts->CPU,
3686
9.01k
                      TargetOpts->ABI);
3687
9.01k
  for (const auto &FeatureAsWritten : TargetOpts->FeaturesAsWritten)
3688
4
    code = hash_combine(code, FeatureAsWritten);
3689
9.01k
3690
9.01k
  // Extend the signature with preprocessor options.
3691
9.01k
  const PreprocessorOptions &ppOpts = getPreprocessorOpts();
3692
9.01k
  const HeaderSearchOptions &hsOpts = getHeaderSearchOpts();
3693
9.01k
  code = hash_combine(code, ppOpts.UsePredefines, ppOpts.DetailedRecord);
3694
9.01k
3695
9.01k
  for (const auto &I : getPreprocessorOpts().Macros) {
3696
6.27k
    // If we're supposed to ignore this macro for the purposes of modules,
3697
6.27k
    // don't put it into the hash.
3698
6.27k
    if (!hsOpts.ModulesIgnoreMacros.empty()) {
3699
41
      // Check whether we're ignoring this macro.
3700
41
      StringRef MacroDef = I.first;
3701
41
      if (hsOpts.ModulesIgnoreMacros.count(
3702
41
              llvm::CachedHashString(MacroDef.split('=').first)))
3703
33
        continue;
3704
6.23k
    }
3705
6.23k
3706
6.23k
    code = hash_combine(code, I.first, I.second);
3707
6.23k
  }
3708
9.01k
3709
9.01k
  // Extend the signature with the sysroot and other header search options.
3710
9.01k
  code = hash_combine(code, hsOpts.Sysroot,
3711
9.01k
                      hsOpts.ModuleFormat,
3712
9.01k
                      hsOpts.UseDebugInfo,
3713
9.01k
                      hsOpts.UseBuiltinIncludes,
3714
9.01k
                      hsOpts.UseStandardSystemIncludes,
3715
9.01k
                      hsOpts.UseStandardCXXIncludes,
3716
9.01k
                      hsOpts.UseLibcxx,
3717
9.01k
                      hsOpts.ModulesValidateDiagnosticOptions);
3718
9.01k
  code = hash_combine(code, hsOpts.ResourceDir);
3719
9.01k
3720
9.01k
  if (hsOpts.ModulesStrictContextHash) {
3721
73
    hash_code SHPC = hash_combine_range(hsOpts.SystemHeaderPrefixes.begin(),
3722
73
                                        hsOpts.SystemHeaderPrefixes.end());
3723
73
    hash_code UEC = hash_combine_range(hsOpts.UserEntries.begin(),
3724
73
                                       hsOpts.UserEntries.end());
3725
73
    code = hash_combine(code, hsOpts.SystemHeaderPrefixes.size(), SHPC,
3726
73
                        hsOpts.UserEntries.size(), UEC);
3727
73
3728
73
    const DiagnosticOptions &diagOpts = getDiagnosticOpts();
3729
73
    #define DIAGOPT(Name, Bits, Default) \
3730
2.11k
      code = hash_combine(code, diagOpts.Name);
3731
73
    #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
3732
219
      code = hash_combine(code, diagOpts.get##Name());
3733
73
    #include "clang/Basic/DiagnosticOptions.def"
3734
73
    #undef DIAGOPT
3735
73
    #undef ENUM_DIAGOPT
3736
73
  }
3737
9.01k
3738
9.01k
  // Extend the signature with the user build path.
3739
9.01k
  code = hash_combine(code, hsOpts.ModuleUserBuildPath);
3740
9.01k
3741
9.01k
  // Extend the signature with the module file extensions.
3742
9.01k
  const FrontendOptions &frontendOpts = getFrontendOpts();
3743
9.01k
  for (const auto &ext : frontendOpts.ModuleFileExtensions) {
3744
42
    code = ext->hashExtension(code);
3745
42
  }
3746
9.01k
3747
9.01k
  // When compiling with -gmodules, also hash -fdebug-prefix-map as it
3748
9.01k
  // affects the debug info in the PCM.
3749
9.01k
  if (getCodeGenOpts().DebugTypeExtRefs)
3750
2.43k
    for (const auto &KeyValue : getCodeGenOpts().DebugPrefixMap)
3751
0
      code = hash_combine(code, KeyValue.first, KeyValue.second);
3752
9.01k
3753
9.01k
  // Extend the signature with the enabled sanitizers, if at least one is
3754
9.01k
  // enabled. Sanitizers which cannot affect AST generation aren't hashed.
3755
9.01k
  SanitizerSet SanHash = LangOpts->Sanitize;
3756
9.01k
  SanHash.clear(getPPTransparentSanitizers());
3757
9.01k
  if (!SanHash.empty())
3758
5
    code = hash_combine(code, SanHash.Mask);
3759
9.01k
3760
9.01k
  return llvm::APInt(64, code).toString(36, /*Signed=*/false);
3761
9.01k
}
3762
3763
namespace clang {
3764
3765
IntrusiveRefCntPtr<llvm::vfs::FileSystem>
3766
createVFSFromCompilerInvocation(const CompilerInvocation &CI,
3767
33.6k
                                DiagnosticsEngine &Diags) {
3768
33.6k
  return createVFSFromCompilerInvocation(CI, Diags,
3769
33.6k
                                         llvm::vfs::getRealFileSystem());
3770
33.6k
}
3771
3772
IntrusiveRefCntPtr<llvm::vfs::FileSystem> createVFSFromCompilerInvocation(
3773
    const CompilerInvocation &CI, DiagnosticsEngine &Diags,
3774
34.7k
    IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS) {
3775
34.7k
  if (CI.getHeaderSearchOpts().VFSOverlayFiles.empty())
3776
34.7k
    return BaseFS;
3777
65
3778
65
  IntrusiveRefCntPtr<llvm::vfs::FileSystem> Result = BaseFS;
3779
65
  // earlier vfs files are on the bottom
3780
70
  for (const auto &File : CI.getHeaderSearchOpts().VFSOverlayFiles) {
3781
70
    llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer =
3782
70
        Result->getBufferForFile(File);
3783
70
    if (!Buffer) {
3784
3
      Diags.Report(diag::err_missing_vfs_overlay_file) << File;
3785
3
      continue;
3786
3
    }
3787
67
3788
67
    IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS = llvm::vfs::getVFSFromYAML(
3789
67
        std::move(Buffer.get()), /*DiagHandler*/ nullptr, File,
3790
67
        /*DiagContext*/ nullptr, Result);
3791
67
    if (!FS) {
3792
4
      Diags.Report(diag::err_invalid_vfs_overlay) << File;
3793
4
      continue;
3794
4
    }
3795
63
3796
63
    Result = FS;
3797
63
  }
3798
65
  return Result;
3799
65
}
3800
3801
} // namespace clang