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