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.LTOVisibilityPublicStd = Args.hasArg(OPT_flto_visibility_public_std);
762  Opts.SplitDwarfFile = Args.getLastArgValue(OPT_split_dwarf_file);
763  Opts.SplitDwarfOutput = Args.getLastArgValue(OPT_split_dwarf_output);
764  Opts.SplitDwarfInlining = !Args.hasArg(OPT_fno_split_dwarf_inlining);
765  Opts.DebugTypeExtRefs = Args.hasArg(OPT_dwarf_ext_refs);
766  Opts.DebugExplicitImport = Args.hasArg(OPT_dwarf_explicit_import);
767  Opts.DebugFwdTemplateParams = Args.hasArg(OPT_debug_forward_template_params);
768  Opts.EmbedSource = Args.hasArg(OPT_gembed_source);
769 
770  for (const auto &Arg : Args.getAllArgValues(OPT_fdebug_prefix_map_EQ))
771  Opts.DebugPrefixMap.insert(StringRef(Arg).split('='));
772 
773  if (const Arg *A =
774  Args.getLastArg(OPT_emit_llvm_uselists, OPT_no_emit_llvm_uselists))
775  Opts.EmitLLVMUseLists = A->getOption().getID() == OPT_emit_llvm_uselists;
776 
777  Opts.DisableLLVMPasses = Args.hasArg(OPT_disable_llvm_passes);
778  Opts.DisableLifetimeMarkers = Args.hasArg(OPT_disable_lifetimemarkers);
779 
780  llvm::Triple T(TargetOpts.Triple);
781  llvm::Triple::ArchType Arch = T.getArch();
782  if (Opts.OptimizationLevel > 0 &&
783  (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64))
784  Opts.EnableDebugEntryValues = Args.hasArg(OPT_femit_debug_entry_values);
785 
786  Opts.DisableO0ImplyOptNone = Args.hasArg(OPT_disable_O0_optnone);
787  Opts.DisableRedZone = Args.hasArg(OPT_disable_red_zone);
788  Opts.IndirectTlsSegRefs = Args.hasArg(OPT_mno_tls_direct_seg_refs);
789  Opts.ForbidGuardVariables = Args.hasArg(OPT_fforbid_guard_variables);
790  Opts.UseRegisterSizedBitfieldAccess = Args.hasArg(
791  OPT_fuse_register_sized_bitfield_access);
792  Opts.RelaxedAliasing = Args.hasArg(OPT_relaxed_aliasing);
793  Opts.StructPathTBAA = !Args.hasArg(OPT_no_struct_path_tbaa);
794  Opts.NewStructPathTBAA = !Args.hasArg(OPT_no_struct_path_tbaa) &&
795  Args.hasArg(OPT_new_struct_path_tbaa);
796  Opts.FineGrainedBitfieldAccesses =
797  Args.hasFlag(OPT_ffine_grained_bitfield_accesses,
798  OPT_fno_fine_grained_bitfield_accesses, false);
799  Opts.DwarfDebugFlags = Args.getLastArgValue(OPT_dwarf_debug_flags);
800  Opts.RecordCommandLine = Args.getLastArgValue(OPT_record_command_line);
801  Opts.MergeAllConstants = Args.hasArg(OPT_fmerge_all_constants);
802  Opts.NoCommon = Args.hasArg(OPT_fno_common);
803  Opts.NoImplicitFloat = Args.hasArg(OPT_no_implicit_float);
804  Opts.OptimizeSize = getOptimizationLevelSize(Args);
805  Opts.SimplifyLibCalls = !(Args.hasArg(OPT_fno_builtin) ||
806  Args.hasArg(OPT_ffreestanding));
807  if (Opts.SimplifyLibCalls)
809  Opts.UnrollLoops =
810  Args.hasFlag(OPT_funroll_loops, OPT_fno_unroll_loops,
811  (Opts.OptimizationLevel > 1));
812  Opts.RerollLoops = Args.hasArg(OPT_freroll_loops);
813 
814  Opts.DisableIntegratedAS = Args.hasArg(OPT_fno_integrated_as);
815  Opts.Autolink = !Args.hasArg(OPT_fno_autolink);
816  Opts.SampleProfileFile = Args.getLastArgValue(OPT_fprofile_sample_use_EQ);
817  Opts.DebugInfoForProfiling = Args.hasFlag(
818  OPT_fdebug_info_for_profiling, OPT_fno_debug_info_for_profiling, false);
819  Opts.DebugNameTable = static_cast<unsigned>(
820  Args.hasArg(OPT_ggnu_pubnames)
821  ? llvm::DICompileUnit::DebugNameTableKind::GNU
822  : Args.hasArg(OPT_gpubnames)
823  ? llvm::DICompileUnit::DebugNameTableKind::Default
825  Opts.DebugRangesBaseAddress = Args.hasArg(OPT_fdebug_ranges_base_address);
826 
827  setPGOInstrumentor(Opts, Args, Diags);
828  Opts.InstrProfileOutput =
829  Args.getLastArgValue(OPT_fprofile_instrument_path_EQ);
831  Args.getLastArgValue(OPT_fprofile_instrument_use_path_EQ);
832  if (!Opts.ProfileInstrumentUsePath.empty())
834  Opts.ProfileRemappingFile =
835  Args.getLastArgValue(OPT_fprofile_remapping_file_EQ);
836  if (!Opts.ProfileRemappingFile.empty() && !Opts.ExperimentalNewPassManager) {
837  Diags.Report(diag::err_drv_argument_only_allowed_with)
838  << Args.getLastArg(OPT_fprofile_remapping_file_EQ)->getAsString(Args)
839  << "-fexperimental-new-pass-manager";
840  }
841 
842  Opts.CoverageMapping =
843  Args.hasFlag(OPT_fcoverage_mapping, OPT_fno_coverage_mapping, false);
844  Opts.DumpCoverageMapping = Args.hasArg(OPT_dump_coverage_mapping);
845  Opts.AsmVerbose = Args.hasArg(OPT_masm_verbose);
846  Opts.PreserveAsmComments = !Args.hasArg(OPT_fno_preserve_as_comments);
847  Opts.AssumeSaneOperatorNew = !Args.hasArg(OPT_fno_assume_sane_operator_new);
848  Opts.ObjCAutoRefCountExceptions = Args.hasArg(OPT_fobjc_arc_exceptions);
849  Opts.CXAAtExit = !Args.hasArg(OPT_fno_use_cxa_atexit);
850  Opts.RegisterGlobalDtorsWithAtExit =
851  Args.hasArg(OPT_fregister_global_dtors_with_atexit);
852  Opts.CXXCtorDtorAliases = Args.hasArg(OPT_mconstructor_aliases);
853  Opts.CodeModel = TargetOpts.CodeModel;
854  Opts.DebugPass = Args.getLastArgValue(OPT_mdebug_pass);
855 
856  // Handle -mframe-pointer option.
857  if (Arg *A = Args.getLastArg(OPT_mframe_pointer_EQ)) {
859  StringRef Name = A->getValue();
860  bool ValidFP = true;
861  if (Name == "none")
863  else if (Name == "non-leaf")
865  else if (Name == "all")
867  else {
868  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
869  Success = false;
870  ValidFP = false;
871  }
872  if (ValidFP)
873  Opts.setFramePointer(FP);
874  }
875 
876  // -pg may override -mframe-pointer
877  // TODO: This should be merged into getFramePointerKind in Clang.cpp.
878  if (Args.hasArg(OPT_pg))
879  Opts.setFramePointer(CodeGenOptions::FramePointerKind::All);
880 
881  Opts.DisableFree = Args.hasArg(OPT_disable_free);
882  Opts.DiscardValueNames = Args.hasArg(OPT_discard_value_names);
883  Opts.DisableTailCalls = Args.hasArg(OPT_mdisable_tail_calls);
884  Opts.NoEscapingBlockTailCalls =
885  Args.hasArg(OPT_fno_escaping_block_tail_calls);
886  Opts.FloatABI = Args.getLastArgValue(OPT_mfloat_abi);
887  Opts.LessPreciseFPMAD = Args.hasArg(OPT_cl_mad_enable) ||
888  Args.hasArg(OPT_cl_unsafe_math_optimizations) ||
889  Args.hasArg(OPT_cl_fast_relaxed_math);
890  Opts.LimitFloatPrecision = Args.getLastArgValue(OPT_mlimit_float_precision);
891  Opts.NoInfsFPMath = (Args.hasArg(OPT_menable_no_infinities) ||
892  Args.hasArg(OPT_cl_finite_math_only) ||
893  Args.hasArg(OPT_cl_fast_relaxed_math));
894  Opts.NoNaNsFPMath = (Args.hasArg(OPT_menable_no_nans) ||
895  Args.hasArg(OPT_cl_unsafe_math_optimizations) ||
896  Args.hasArg(OPT_cl_finite_math_only) ||
897  Args.hasArg(OPT_cl_fast_relaxed_math));
898  Opts.NoSignedZeros = (Args.hasArg(OPT_fno_signed_zeros) ||
899  Args.hasArg(OPT_cl_no_signed_zeros) ||
900  Args.hasArg(OPT_cl_unsafe_math_optimizations) ||
901  Args.hasArg(OPT_cl_fast_relaxed_math));
902  Opts.Reassociate = Args.hasArg(OPT_mreassociate);
903  Opts.FlushDenorm = Args.hasArg(OPT_cl_denorms_are_zero) ||
904  (Args.hasArg(OPT_fcuda_is_device) &&
905  Args.hasArg(OPT_fcuda_flush_denormals_to_zero));
906  Opts.CorrectlyRoundedDivSqrt =
907  Args.hasArg(OPT_cl_fp32_correctly_rounded_divide_sqrt);
908  Opts.UniformWGSize =
909  Args.hasArg(OPT_cl_uniform_work_group_size);
910  Opts.Reciprocals = Args.getAllArgValues(OPT_mrecip_EQ);
911  Opts.ReciprocalMath = Args.hasArg(OPT_freciprocal_math);
912  Opts.NoTrappingMath = Args.hasArg(OPT_fno_trapping_math);
913  Opts.StrictFloatCastOverflow =
914  !Args.hasArg(OPT_fno_strict_float_cast_overflow);
915 
916  Opts.NoZeroInitializedInBSS = Args.hasArg(OPT_mno_zero_initialized_in_bss);
917  Opts.NumRegisterParameters = getLastArgIntValue(Args, OPT_mregparm, 0, Diags);
918  Opts.NoExecStack = Args.hasArg(OPT_mno_exec_stack);
919  Opts.FatalWarnings = Args.hasArg(OPT_massembler_fatal_warnings);
920  Opts.NoWarn = Args.hasArg(OPT_massembler_no_warn);
921  Opts.EnableSegmentedStacks = Args.hasArg(OPT_split_stacks);
922  Opts.RelaxAll = Args.hasArg(OPT_mrelax_all);
923  Opts.IncrementalLinkerCompatible =
924  Args.hasArg(OPT_mincremental_linker_compatible);
925  Opts.PIECopyRelocations =
926  Args.hasArg(OPT_mpie_copy_relocations);
927  Opts.NoPLT = Args.hasArg(OPT_fno_plt);
928  Opts.SaveTempLabels = Args.hasArg(OPT_msave_temp_labels);
929  Opts.NoDwarfDirectoryAsm = Args.hasArg(OPT_fno_dwarf_directory_asm);
930  Opts.SoftFloat = Args.hasArg(OPT_msoft_float);
931  Opts.StrictEnums = Args.hasArg(OPT_fstrict_enums);
932  Opts.StrictReturn = !Args.hasArg(OPT_fno_strict_return);
933  Opts.StrictVTablePointers = Args.hasArg(OPT_fstrict_vtable_pointers);
934  Opts.ForceEmitVTables = Args.hasArg(OPT_fforce_emit_vtables);
935  Opts.UnsafeFPMath = Args.hasArg(OPT_menable_unsafe_fp_math) ||
936  Args.hasArg(OPT_cl_unsafe_math_optimizations) ||
937  Args.hasArg(OPT_cl_fast_relaxed_math);
938  Opts.UnwindTables = Args.hasArg(OPT_munwind_tables);
939  Opts.RelocationModel = getRelocModel(Args, Diags);
940  Opts.ThreadModel = Args.getLastArgValue(OPT_mthread_model, "posix");
941  if (Opts.ThreadModel != "posix" && Opts.ThreadModel != "single")
942  Diags.Report(diag::err_drv_invalid_value)
943  << Args.getLastArg(OPT_mthread_model)->getAsString(Args)
944  << Opts.ThreadModel;
945  Opts.TrapFuncName = Args.getLastArgValue(OPT_ftrap_function_EQ);
946  Opts.UseInitArray = Args.hasArg(OPT_fuse_init_array);
947 
948  Opts.FunctionSections = Args.hasFlag(OPT_ffunction_sections,
949  OPT_fno_function_sections, false);
950  Opts.DataSections = Args.hasFlag(OPT_fdata_sections,
951  OPT_fno_data_sections, false);
952  Opts.StackSizeSection =
953  Args.hasFlag(OPT_fstack_size_section, OPT_fno_stack_size_section, false);
954  Opts.UniqueSectionNames = Args.hasFlag(OPT_funique_section_names,
955  OPT_fno_unique_section_names, true);
956 
957  Opts.MergeFunctions = Args.hasArg(OPT_fmerge_functions);
958 
959  Opts.NoUseJumpTables = Args.hasArg(OPT_fno_jump_tables);
960 
961  Opts.NullPointerIsValid = Args.hasArg(OPT_fno_delete_null_pointer_checks);
962 
963  Opts.ProfileSampleAccurate = Args.hasArg(OPT_fprofile_sample_accurate);
964 
965  Opts.PrepareForLTO = Args.hasArg(OPT_flto, OPT_flto_EQ);
966  Opts.PrepareForThinLTO = false;
967  if (Arg *A = Args.getLastArg(OPT_flto_EQ)) {
968  StringRef S = A->getValue();
969  if (S == "thin")
970  Opts.PrepareForThinLTO = true;
971  else if (S != "full")
972  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << S;
973  }
974  Opts.LTOUnit = Args.hasFlag(OPT_flto_unit, OPT_fno_lto_unit, false);
975  Opts.EnableSplitLTOUnit = Args.hasArg(OPT_fsplit_lto_unit);
976  if (Arg *A = Args.getLastArg(OPT_fthinlto_index_EQ)) {
977  if (IK.getLanguage() != Language::LLVM_IR)
978  Diags.Report(diag::err_drv_argument_only_allowed_with)
979  << A->getAsString(Args) << "-x ir";
980  Opts.ThinLTOIndexFile = Args.getLastArgValue(OPT_fthinlto_index_EQ);
981  }
982  if (Arg *A = Args.getLastArg(OPT_save_temps_EQ))
983  Opts.SaveTempsFilePrefix =
984  llvm::StringSwitch<std::string>(A->getValue())
985  .Case("obj", FrontendOpts.OutputFile)
986  .Default(llvm::sys::path::filename(FrontendOpts.OutputFile).str());
987 
988  Opts.ThinLinkBitcodeFile = Args.getLastArgValue(OPT_fthin_link_bitcode_EQ);
989 
990  Opts.MSVolatile = Args.hasArg(OPT_fms_volatile);
991 
992  Opts.VectorizeLoop = Args.hasArg(OPT_vectorize_loops);
993  Opts.VectorizeSLP = Args.hasArg(OPT_vectorize_slp);
994 
995  Opts.PreferVectorWidth = Args.getLastArgValue(OPT_mprefer_vector_width_EQ);
996 
997  Opts.MainFileName = Args.getLastArgValue(OPT_main_file_name);
998  Opts.VerifyModule = !Args.hasArg(OPT_disable_llvm_verifier);
999 
1000  Opts.ControlFlowGuard = Args.hasArg(OPT_cfguard);
1001 
1002  Opts.DisableGCov = Args.hasArg(OPT_test_coverage);
1003  Opts.EmitGcovArcs = Args.hasArg(OPT_femit_coverage_data);
1004  Opts.EmitGcovNotes = Args.hasArg(OPT_femit_coverage_notes);
1005  if (Opts.EmitGcovArcs || Opts.EmitGcovNotes) {
1006  Opts.CoverageDataFile = Args.getLastArgValue(OPT_coverage_data_file);
1007  Opts.CoverageNotesFile = Args.getLastArgValue(OPT_coverage_notes_file);
1008  Opts.CoverageExtraChecksum = Args.hasArg(OPT_coverage_cfg_checksum);
1009  Opts.CoverageNoFunctionNamesInData =
1010  Args.hasArg(OPT_coverage_no_function_names_in_data);
1011  Opts.ProfileFilterFiles =
1012  Args.getLastArgValue(OPT_fprofile_filter_files_EQ);
1013  Opts.ProfileExcludeFiles =
1014  Args.getLastArgValue(OPT_fprofile_exclude_files_EQ);
1015  Opts.CoverageExitBlockBeforeBody =
1016  Args.hasArg(OPT_coverage_exit_block_before_body);
1017  if (Args.hasArg(OPT_coverage_version_EQ)) {
1018  StringRef CoverageVersion = Args.getLastArgValue(OPT_coverage_version_EQ);
1019  if (CoverageVersion.size() != 4) {
1020  Diags.Report(diag::err_drv_invalid_value)
1021  << Args.getLastArg(OPT_coverage_version_EQ)->getAsString(Args)
1022  << CoverageVersion;
1023  } else {
1024  memcpy(Opts.CoverageVersion, CoverageVersion.data(), 4);
1025  }
1026  }
1027  }
1028  // Handle -fembed-bitcode option.
1029  if (Arg *A = Args.getLastArg(OPT_fembed_bitcode_EQ)) {
1030  StringRef Name = A->getValue();
1031  unsigned Model = llvm::StringSwitch<unsigned>(Name)
1032  .Case("off", CodeGenOptions::Embed_Off)
1033  .Case("all", CodeGenOptions::Embed_All)
1034  .Case("bitcode", CodeGenOptions::Embed_Bitcode)
1035  .Case("marker", CodeGenOptions::Embed_Marker)
1036  .Default(~0U);
1037  if (Model == ~0U) {
1038  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
1039  Success = false;
1040  } else
1041  Opts.setEmbedBitcode(
1042  static_cast<CodeGenOptions::EmbedBitcodeKind>(Model));
1043  }
1044  // FIXME: For backend options that are not yet recorded as function
1045  // attributes in the IR, keep track of them so we can embed them in a
1046  // separate data section and use them when building the bitcode.
1047  if (Opts.getEmbedBitcode() == CodeGenOptions::Embed_All) {
1048  for (const auto &A : Args) {
1049  // Do not encode output and input.
1050  if (A->getOption().getID() == options::OPT_o ||
1051  A->getOption().getID() == options::OPT_INPUT ||
1052  A->getOption().getID() == options::OPT_x ||
1053  A->getOption().getID() == options::OPT_fembed_bitcode ||
1054  (A->getOption().getGroup().isValid() &&
1055  A->getOption().getGroup().getID() == options::OPT_W_Group))
1056  continue;
1057  ArgStringList ASL;
1058  A->render(Args, ASL);
1059  for (const auto &arg : ASL) {
1060  StringRef ArgStr(arg);
1061  Opts.CmdArgs.insert(Opts.CmdArgs.end(), ArgStr.begin(), ArgStr.end());
1062  // using \00 to separate each commandline options.
1063  Opts.CmdArgs.push_back('\0');
1064  }
1065  }
1066  }
1067 
1068  Opts.PreserveVec3Type = Args.hasArg(OPT_fpreserve_vec3_type);
1069  Opts.InstrumentFunctions = Args.hasArg(OPT_finstrument_functions);
1070  Opts.InstrumentFunctionsAfterInlining =
1071  Args.hasArg(OPT_finstrument_functions_after_inlining);
1072  Opts.InstrumentFunctionEntryBare =
1073  Args.hasArg(OPT_finstrument_function_entry_bare);
1074 
1075  Opts.XRayInstrumentFunctions =
1076  Args.hasArg(OPT_fxray_instrument);
1077  Opts.XRayAlwaysEmitCustomEvents =
1078  Args.hasArg(OPT_fxray_always_emit_customevents);
1079  Opts.XRayAlwaysEmitTypedEvents =
1080  Args.hasArg(OPT_fxray_always_emit_typedevents);
1081  Opts.XRayInstructionThreshold =
1082  getLastArgIntValue(Args, OPT_fxray_instruction_threshold_EQ, 200, Diags);
1083 
1084  auto XRayInstrBundles =
1085  Args.getAllArgValues(OPT_fxray_instrumentation_bundle);
1086  if (XRayInstrBundles.empty())
1088  else
1089  for (const auto &A : XRayInstrBundles)
1090  parseXRayInstrumentationBundle("-fxray-instrumentation-bundle=", A, Args,
1091  Diags, Opts.XRayInstrumentationBundle);
1092 
1093  Opts.InstrumentForProfiling = Args.hasArg(OPT_pg);
1094  Opts.CallFEntry = Args.hasArg(OPT_mfentry);
1095  Opts.EmitOpenCLArgMetadata = Args.hasArg(OPT_cl_kernel_arg_info);
1096 
1097  if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
1098  StringRef Name = A->getValue();
1099  if (Name == "full") {
1100  Opts.CFProtectionReturn = 1;
1101  Opts.CFProtectionBranch = 1;
1102  } else if (Name == "return")
1103  Opts.CFProtectionReturn = 1;
1104  else if (Name == "branch")
1105  Opts.CFProtectionBranch = 1;
1106  else if (Name != "none") {
1107  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
1108  Success = false;
1109  }
1110  }
1111 
1112  if (const Arg *A = Args.getLastArg(OPT_compress_debug_sections,
1113  OPT_compress_debug_sections_EQ)) {
1114  if (A->getOption().getID() == OPT_compress_debug_sections) {
1115  // TODO: be more clever about the compression type auto-detection
1116  Opts.setCompressDebugSections(llvm::DebugCompressionType::GNU);
1117  } else {
1118  auto DCT = llvm::StringSwitch<llvm::DebugCompressionType>(A->getValue())
1119  .Case("none", llvm::DebugCompressionType::None)
1120  .Case("zlib", llvm::DebugCompressionType::Z)
1121  .Case("zlib-gnu", llvm::DebugCompressionType::GNU)
1123  Opts.setCompressDebugSections(DCT);
1124  }
1125  }
1126 
1127  Opts.RelaxELFRelocations = Args.hasArg(OPT_mrelax_relocations);
1128  Opts.DebugCompilationDir = Args.getLastArgValue(OPT_fdebug_compilation_dir);
1129  for (auto *A :
1130  Args.filtered(OPT_mlink_bitcode_file, OPT_mlink_builtin_bitcode)) {
1132  F.Filename = A->getValue();
1133  if (A->getOption().matches(OPT_mlink_builtin_bitcode)) {
1134  F.LinkFlags = llvm::Linker::Flags::LinkOnlyNeeded;
1135  // When linking CUDA bitcode, propagate function attributes so that
1136  // e.g. libdevice gets fast-math attrs if we're building with fast-math.
1137  F.PropagateAttrs = true;
1138  F.Internalize = true;
1139  }
1140  Opts.LinkBitcodeFiles.push_back(F);
1141  }
1142  Opts.SanitizeCoverageType =
1143  getLastArgIntValue(Args, OPT_fsanitize_coverage_type, 0, Diags);
1144  Opts.SanitizeCoverageIndirectCalls =
1145  Args.hasArg(OPT_fsanitize_coverage_indirect_calls);
1146  Opts.SanitizeCoverageTraceBB = Args.hasArg(OPT_fsanitize_coverage_trace_bb);
1147  Opts.SanitizeCoverageTraceCmp = Args.hasArg(OPT_fsanitize_coverage_trace_cmp);
1148  Opts.SanitizeCoverageTraceDiv = Args.hasArg(OPT_fsanitize_coverage_trace_div);
1149  Opts.SanitizeCoverageTraceGep = Args.hasArg(OPT_fsanitize_coverage_trace_gep);
1150  Opts.SanitizeCoverage8bitCounters =
1151  Args.hasArg(OPT_fsanitize_coverage_8bit_counters);
1152  Opts.SanitizeCoverageTracePC = Args.hasArg(OPT_fsanitize_coverage_trace_pc);
1153  Opts.SanitizeCoverageTracePCGuard =
1154  Args.hasArg(OPT_fsanitize_coverage_trace_pc_guard);
1155  Opts.SanitizeCoverageNoPrune = Args.hasArg(OPT_fsanitize_coverage_no_prune);
1156  Opts.SanitizeCoverageInline8bitCounters =
1157  Args.hasArg(OPT_fsanitize_coverage_inline_8bit_counters);
1158  Opts.SanitizeCoveragePCTable = Args.hasArg(OPT_fsanitize_coverage_pc_table);
1159  Opts.SanitizeCoverageStackDepth =
1160  Args.hasArg(OPT_fsanitize_coverage_stack_depth);
1161  Opts.SanitizeMemoryTrackOrigins =
1162  getLastArgIntValue(Args, OPT_fsanitize_memory_track_origins_EQ, 0, Diags);
1163  Opts.SanitizeMemoryUseAfterDtor =
1164  Args.hasFlag(OPT_fsanitize_memory_use_after_dtor,
1165  OPT_fno_sanitize_memory_use_after_dtor,
1166  false);
1167  Opts.SanitizeMinimalRuntime = Args.hasArg(OPT_fsanitize_minimal_runtime);
1168  Opts.SanitizeCfiCrossDso = Args.hasArg(OPT_fsanitize_cfi_cross_dso);
1169  Opts.SanitizeCfiICallGeneralizePointers =
1170  Args.hasArg(OPT_fsanitize_cfi_icall_generalize_pointers);
1171  Opts.SanitizeCfiCanonicalJumpTables =
1172  Args.hasArg(OPT_fsanitize_cfi_canonical_jump_tables);
1173  Opts.SanitizeStats = Args.hasArg(OPT_fsanitize_stats);
1174  if (Arg *A = Args.getLastArg(
1175  OPT_fsanitize_address_poison_custom_array_cookie,
1176  OPT_fno_sanitize_address_poison_custom_array_cookie)) {
1177  Opts.SanitizeAddressPoisonCustomArrayCookie =
1178  A->getOption().getID() ==
1179  OPT_fsanitize_address_poison_custom_array_cookie;
1180  }
1181  if (Arg *A = Args.getLastArg(OPT_fsanitize_address_use_after_scope,
1182  OPT_fno_sanitize_address_use_after_scope)) {
1183  Opts.SanitizeAddressUseAfterScope =
1184  A->getOption().getID() == OPT_fsanitize_address_use_after_scope;
1185  }
1186  Opts.SanitizeAddressGlobalsDeadStripping =
1187  Args.hasArg(OPT_fsanitize_address_globals_dead_stripping);
1188  if (Arg *A = Args.getLastArg(OPT_fsanitize_address_use_odr_indicator,
1189  OPT_fno_sanitize_address_use_odr_indicator)) {
1190  Opts.SanitizeAddressUseOdrIndicator =
1191  A->getOption().getID() == OPT_fsanitize_address_use_odr_indicator;
1192  }
1193  Opts.SSPBufferSize =
1194  getLastArgIntValue(Args, OPT_stack_protector_buffer_size, 8, Diags);
1195  Opts.StackRealignment = Args.hasArg(OPT_mstackrealign);
1196  if (Arg *A = Args.getLastArg(OPT_mstack_alignment)) {
1197  StringRef Val = A->getValue();
1198  unsigned StackAlignment = Opts.StackAlignment;
1199  Val.getAsInteger(10, StackAlignment);
1200  Opts.StackAlignment = StackAlignment;
1201  }
1202 
1203  if (Arg *A = Args.getLastArg(OPT_mstack_probe_size)) {
1204  StringRef Val = A->getValue();
1205  unsigned StackProbeSize = Opts.StackProbeSize;
1206  Val.getAsInteger(0, StackProbeSize);
1207  Opts.StackProbeSize = StackProbeSize;
1208  }
1209 
1210  Opts.NoStackArgProbe = Args.hasArg(OPT_mno_stack_arg_probe);
1211 
1212  if (Arg *A = Args.getLastArg(OPT_fobjc_dispatch_method_EQ)) {
1213  StringRef Name = A->getValue();
1214  unsigned Method = llvm::StringSwitch<unsigned>(Name)
1215  .Case("legacy", CodeGenOptions::Legacy)
1216  .Case("non-legacy", CodeGenOptions::NonLegacy)
1217  .Case("mixed", CodeGenOptions::Mixed)
1218  .Default(~0U);
1219  if (Method == ~0U) {
1220  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
1221  Success = false;
1222  } else {
1223  Opts.setObjCDispatchMethod(
1224  static_cast<CodeGenOptions::ObjCDispatchMethodKind>(Method));
1225  }
1226  }
1227 
1228 
1229  if (Args.hasArg(OPT_fno_objc_convert_messages_to_runtime_calls))
1230  Opts.ObjCConvertMessagesToRuntimeCalls = 0;
1231 
1232  if (Args.getLastArg(OPT_femulated_tls) ||
1233  Args.getLastArg(OPT_fno_emulated_tls)) {
1234  Opts.ExplicitEmulatedTLS = true;
1235  Opts.EmulatedTLS =
1236  Args.hasFlag(OPT_femulated_tls, OPT_fno_emulated_tls, false);
1237  }
1238 
1239  if (Arg *A = Args.getLastArg(OPT_ftlsmodel_EQ)) {
1240  StringRef Name = A->getValue();
1241  unsigned Model = llvm::StringSwitch<unsigned>(Name)
1242  .Case("global-dynamic", CodeGenOptions::GeneralDynamicTLSModel)
1243  .Case("local-dynamic", CodeGenOptions::LocalDynamicTLSModel)
1244  .Case("initial-exec", CodeGenOptions::InitialExecTLSModel)
1245  .Case("local-exec", CodeGenOptions::LocalExecTLSModel)
1246  .Default(~0U);
1247  if (Model == ~0U) {
1248  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
1249  Success = false;
1250  } else {
1251  Opts.setDefaultTLSModel(static_cast<CodeGenOptions::TLSModel>(Model));
1252  }
1253  }
1254 
1255  if (Arg *A = Args.getLastArg(OPT_fdenormal_fp_math_EQ)) {
1256  StringRef Val = A->getValue();
1257  if (Val == "ieee")
1258  Opts.FPDenormalMode = "ieee";
1259  else if (Val == "preserve-sign")
1260  Opts.FPDenormalMode = "preserve-sign";
1261  else if (Val == "positive-zero")
1262  Opts.FPDenormalMode = "positive-zero";
1263  else
1264  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
1265  }
1266 
1267  if (Arg *A = Args.getLastArg(OPT_fpcc_struct_return, OPT_freg_struct_return)) {
1268  if (A->getOption().matches(OPT_fpcc_struct_return)) {
1269  Opts.setStructReturnConvention(CodeGenOptions::SRCK_OnStack);
1270  } else {
1271  assert(A->getOption().matches(OPT_freg_struct_return));
1272  Opts.setStructReturnConvention(CodeGenOptions::SRCK_InRegs);
1273  }
1274  }
1275 
1276  Opts.DependentLibraries = Args.getAllArgValues(OPT_dependent_lib);
1277  Opts.LinkerOptions = Args.getAllArgValues(OPT_linker_option);
1278  bool NeedLocTracking = false;
1279 
1280  Opts.OptRecordFile = Args.getLastArgValue(OPT_opt_record_file);
1281  if (!Opts.OptRecordFile.empty())
1282  NeedLocTracking = true;
1283 
1284  if (Arg *A = Args.getLastArg(OPT_opt_record_passes)) {
1285  Opts.OptRecordPasses = A->getValue();
1286  NeedLocTracking = true;
1287  }
1288 
1289  if (Arg *A = Args.getLastArg(OPT_opt_record_format)) {
1290  Opts.OptRecordFormat = A->getValue();
1291  NeedLocTracking = true;
1292  }
1293 
1294  if (Arg *A = Args.getLastArg(OPT_Rpass_EQ)) {
1296  GenerateOptimizationRemarkRegex(Diags, Args, A);
1297  NeedLocTracking = true;
1298  }
1299 
1300  if (Arg *A = Args.getLastArg(OPT_Rpass_missed_EQ)) {
1302  GenerateOptimizationRemarkRegex(Diags, Args, A);
1303  NeedLocTracking = true;
1304  }
1305 
1306  if (Arg *A = Args.getLastArg(OPT_Rpass_analysis_EQ)) {
1308  GenerateOptimizationRemarkRegex(Diags, Args, A);
1309  NeedLocTracking = true;
1310  }
1311 
1312  Opts.DiagnosticsWithHotness =
1313  Args.hasArg(options::OPT_fdiagnostics_show_hotness);
1314  bool UsingSampleProfile = !Opts.SampleProfileFile.empty();
1315  bool UsingProfile = UsingSampleProfile ||
1316  (Opts.getProfileUse() != CodeGenOptions::ProfileNone);
1317 
1318  if (Opts.DiagnosticsWithHotness && !UsingProfile &&
1319  // An IR file will contain PGO as metadata
1321  Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo)
1322  << "-fdiagnostics-show-hotness";
1323 
1324  Opts.DiagnosticsHotnessThreshold = getLastArgUInt64Value(
1325  Args, options::OPT_fdiagnostics_hotness_threshold_EQ, 0);
1326  if (Opts.DiagnosticsHotnessThreshold > 0 && !UsingProfile)
1327  Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo)
1328  << "-fdiagnostics-hotness-threshold=";
1329 
1330  // If the user requested to use a sample profile for PGO, then the
1331  // backend will need to track source location information so the profile
1332  // can be incorporated into the IR.
1333  if (UsingSampleProfile)
1334  NeedLocTracking = true;
1335 
1336  // If the user requested a flag that requires source locations available in
1337  // the backend, make sure that the backend tracks source location information.
1338  if (NeedLocTracking && Opts.getDebugInfo() == codegenoptions::NoDebugInfo)
1339  Opts.setDebugInfo(codegenoptions::LocTrackingOnly);
1340 
1341  Opts.RewriteMapFiles = Args.getAllArgValues(OPT_frewrite_map_file);
1342 
1343  // Parse -fsanitize-recover= arguments.
1344  // FIXME: Report unrecoverable sanitizers incorrectly specified here.
1345  parseSanitizerKinds("-fsanitize-recover=",
1346  Args.getAllArgValues(OPT_fsanitize_recover_EQ), Diags,
1347  Opts.SanitizeRecover);
1348  parseSanitizerKinds("-fsanitize-trap=",
1349  Args.getAllArgValues(OPT_fsanitize_trap_EQ), Diags,
1350  Opts.SanitizeTrap);
1351 
1352  Opts.CudaGpuBinaryFileName =
1353  Args.getLastArgValue(OPT_fcuda_include_gpubinary);
1354 
1355  Opts.Backchain = Args.hasArg(OPT_mbackchain);
1356 
1357  Opts.EmitCheckPathComponentsToStrip = getLastArgIntValue(
1358  Args, OPT_fsanitize_undefined_strip_path_components_EQ, 0, Diags);
1359 
1360  Opts.EmitVersionIdentMetadata = Args.hasFlag(OPT_Qy, OPT_Qn, true);
1361 
1362  Opts.Addrsig = Args.hasArg(OPT_faddrsig);
1363 
1364  if (Arg *A = Args.getLastArg(OPT_msign_return_address_EQ)) {
1365  StringRef SignScope = A->getValue();
1366 
1367  if (SignScope.equals_lower("none"))
1368  Opts.setSignReturnAddress(CodeGenOptions::SignReturnAddressScope::None);
1369  else if (SignScope.equals_lower("all"))
1370  Opts.setSignReturnAddress(CodeGenOptions::SignReturnAddressScope::All);
1371  else if (SignScope.equals_lower("non-leaf"))
1372  Opts.setSignReturnAddress(
1373  CodeGenOptions::SignReturnAddressScope::NonLeaf);
1374  else
1375  Diags.Report(diag::err_drv_invalid_value)
1376  << A->getAsString(Args) << SignScope;
1377 
1378  if (Arg *A = Args.getLastArg(OPT_msign_return_address_key_EQ)) {
1379  StringRef SignKey = A->getValue();
1380  if (!SignScope.empty() && !SignKey.empty()) {
1381  if (SignKey.equals_lower("a_key"))
1382  Opts.setSignReturnAddressKey(
1383  CodeGenOptions::SignReturnAddressKeyValue::AKey);
1384  else if (SignKey.equals_lower("b_key"))
1385  Opts.setSignReturnAddressKey(
1386  CodeGenOptions::SignReturnAddressKeyValue::BKey);
1387  else
1388  Diags.Report(diag::err_drv_invalid_value)
1389  << A->getAsString(Args) << SignKey;
1390  }
1391  }
1392  }
1393 
1394  Opts.BranchTargetEnforcement = Args.hasArg(OPT_mbranch_target_enforce);
1395 
1396  Opts.KeepStaticConsts = Args.hasArg(OPT_fkeep_static_consts);
1397 
1398  Opts.SpeculativeLoadHardening = Args.hasArg(OPT_mspeculative_load_hardening);
1399 
1400  Opts.DefaultFunctionAttrs = Args.getAllArgValues(OPT_default_function_attr);
1401 
1402  Opts.PassPlugins = Args.getAllArgValues(OPT_fpass_plugin_EQ);
1403 
1404  Opts.SymbolPartition = Args.getLastArgValue(OPT_fsymbol_partition_EQ);
1405 
1406  return Success;
1407 }
1408 
1410  ArgList &Args) {
1411  Opts.OutputFile = Args.getLastArgValue(OPT_dependency_file);
1412  Opts.Targets = Args.getAllArgValues(OPT_MT);
1413  Opts.IncludeSystemHeaders = Args.hasArg(OPT_sys_header_deps);
1414  Opts.IncludeModuleFiles = Args.hasArg(OPT_module_file_deps);
1415  Opts.UsePhonyTargets = Args.hasArg(OPT_MP);
1416  Opts.ShowHeaderIncludes = Args.hasArg(OPT_H);
1417  Opts.HeaderIncludeOutputFile = Args.getLastArgValue(OPT_header_include_file);
1418  Opts.AddMissingHeaderDeps = Args.hasArg(OPT_MG);
1419  if (Args.hasArg(OPT_show_includes)) {
1420  // Writing both /showIncludes and preprocessor output to stdout
1421  // would produce interleaved output, so use stderr for /showIncludes.
1422  // This behaves the same as cl.exe, when /E, /EP or /P are passed.
1423  if (Args.hasArg(options::OPT_E) || Args.hasArg(options::OPT_P))
1425  else
1427  } else {
1429  }
1430  Opts.DOTOutputFile = Args.getLastArgValue(OPT_dependency_dot);
1432  Args.getLastArgValue(OPT_module_dependency_dir);
1433  if (Args.hasArg(OPT_MV))
1435  // Add sanitizer blacklists as extra dependencies.
1436  // They won't be discovered by the regular preprocessor, so
1437  // we let make / ninja to know about this implicit dependency.
1438  Opts.ExtraDeps = Args.getAllArgValues(OPT_fdepfile_entry);
1439  // Only the -fmodule-file=<file> form.
1440  for (const auto *A : Args.filtered(OPT_fmodule_file)) {
1441  StringRef Val = A->getValue();
1442  if (Val.find('=') == StringRef::npos)
1443  Opts.ExtraDeps.push_back(Val);
1444  }
1445 }
1446 
1447 static bool parseShowColorsArgs(const ArgList &Args, bool DefaultColor) {
1448  // Color diagnostics default to auto ("on" if terminal supports) in the driver
1449  // but default to off in cc1, needing an explicit OPT_fdiagnostics_color.
1450  // Support both clang's -f[no-]color-diagnostics and gcc's
1451  // -f[no-]diagnostics-colors[=never|always|auto].
1452  enum {
1453  Colors_On,
1454  Colors_Off,
1455  Colors_Auto
1456  } ShowColors = DefaultColor ? Colors_Auto : Colors_Off;
1457  for (auto *A : Args) {
1458  const Option &O = A->getOption();
1459  if (O.matches(options::OPT_fcolor_diagnostics) ||
1460  O.matches(options::OPT_fdiagnostics_color)) {
1461  ShowColors = Colors_On;
1462  } else if (O.matches(options::OPT_fno_color_diagnostics) ||
1463  O.matches(options::OPT_fno_diagnostics_color)) {
1464  ShowColors = Colors_Off;
1465  } else if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
1466  StringRef Value(A->getValue());
1467  if (Value == "always")
1468  ShowColors = Colors_On;
1469  else if (Value == "never")
1470  ShowColors = Colors_Off;
1471  else if (Value == "auto")
1472  ShowColors = Colors_Auto;
1473  }
1474  }
1475  return ShowColors == Colors_On ||
1476  (ShowColors == Colors_Auto &&
1477  llvm::sys::Process::StandardErrHasColors());
1478 }
1479 
1480 static bool checkVerifyPrefixes(const std::vector<std::string> &VerifyPrefixes,
1481  DiagnosticsEngine *Diags) {
1482  bool Success = true;
1483  for (const auto &Prefix : VerifyPrefixes) {
1484  // Every prefix must start with a letter and contain only alphanumeric
1485  // characters, hyphens, and underscores.
1486  auto BadChar = llvm::find_if(Prefix, [](char C) {
1487  return !isAlphanumeric(C) && C != '-' && C != '_';
1488  });
1489  if (BadChar != Prefix.end() || !isLetter(Prefix[0])) {
1490  Success = false;
1491  if (Diags) {
1492  Diags->Report(diag::err_drv_invalid_value) << "-verify=" << Prefix;
1493  Diags->Report(diag::note_drv_verify_prefix_spelling);
1494  }
1495  }
1496  }
1497  return Success;
1498 }
1499 
1500 bool clang::ParseDiagnosticArgs(DiagnosticOptions &Opts, ArgList &Args,
1501  DiagnosticsEngine *Diags,
1502  bool DefaultDiagColor, bool DefaultShowOpt) {
1503  bool Success = true;
1504 
1505  Opts.DiagnosticLogFile = Args.getLastArgValue(OPT_diagnostic_log_file);
1506  if (Arg *A =
1507  Args.getLastArg(OPT_diagnostic_serialized_file, OPT__serialize_diags))
1508  Opts.DiagnosticSerializationFile = A->getValue();
1509  Opts.IgnoreWarnings = Args.hasArg(OPT_w);
1510  Opts.NoRewriteMacros = Args.hasArg(OPT_Wno_rewrite_macros);
1511  Opts.Pedantic = Args.hasArg(OPT_pedantic);
1512  Opts.PedanticErrors = Args.hasArg(OPT_pedantic_errors);
1513  Opts.ShowCarets = !Args.hasArg(OPT_fno_caret_diagnostics);
1514  Opts.ShowColors = parseShowColorsArgs(Args, DefaultDiagColor);
1515  Opts.ShowColumn = Args.hasFlag(OPT_fshow_column,
1516  OPT_fno_show_column,
1517  /*Default=*/true);
1518  Opts.ShowFixits = !Args.hasArg(OPT_fno_diagnostics_fixit_info);
1519  Opts.ShowLocation = !Args.hasArg(OPT_fno_show_source_location);
1520  Opts.AbsolutePath = Args.hasArg(OPT_fdiagnostics_absolute_paths);
1521  Opts.ShowOptionNames =
1522  Args.hasFlag(OPT_fdiagnostics_show_option,
1523  OPT_fno_diagnostics_show_option, DefaultShowOpt);
1524 
1525  llvm::sys::Process::UseANSIEscapeCodes(Args.hasArg(OPT_fansi_escape_codes));
1526 
1527  // Default behavior is to not to show note include stacks.
1528  Opts.ShowNoteIncludeStack = false;
1529  if (Arg *A = Args.getLastArg(OPT_fdiagnostics_show_note_include_stack,
1530  OPT_fno_diagnostics_show_note_include_stack))
1531  if (A->getOption().matches(OPT_fdiagnostics_show_note_include_stack))
1532  Opts.ShowNoteIncludeStack = true;
1533 
1534  StringRef ShowOverloads =
1535  Args.getLastArgValue(OPT_fshow_overloads_EQ, "all");
1536  if (ShowOverloads == "best")
1537  Opts.setShowOverloads(Ovl_Best);
1538  else if (ShowOverloads == "all")
1539  Opts.setShowOverloads(Ovl_All);
1540  else {
1541  Success = false;
1542  if (Diags)
1543  Diags->Report(diag::err_drv_invalid_value)
1544  << Args.getLastArg(OPT_fshow_overloads_EQ)->getAsString(Args)
1545  << ShowOverloads;
1546  }
1547 
1548  StringRef ShowCategory =
1549  Args.getLastArgValue(OPT_fdiagnostics_show_category, "none");
1550  if (ShowCategory == "none")
1551  Opts.ShowCategories = 0;
1552  else if (ShowCategory == "id")
1553  Opts.ShowCategories = 1;
1554  else if (ShowCategory == "name")
1555  Opts.ShowCategories = 2;
1556  else {
1557  Success = false;
1558  if (Diags)
1559  Diags->Report(diag::err_drv_invalid_value)
1560  << Args.getLastArg(OPT_fdiagnostics_show_category)->getAsString(Args)
1561  << ShowCategory;
1562  }
1563 
1564  StringRef Format =
1565  Args.getLastArgValue(OPT_fdiagnostics_format, "clang");
1566  if (Format == "clang")
1567  Opts.setFormat(DiagnosticOptions::Clang);
1568  else if (Format == "msvc")
1569  Opts.setFormat(DiagnosticOptions::MSVC);
1570  else if (Format == "msvc-fallback") {
1571  Opts.setFormat(DiagnosticOptions::MSVC);
1572  Opts.CLFallbackMode = true;
1573  } else if (Format == "vi")
1574  Opts.setFormat(DiagnosticOptions::Vi);
1575  else {
1576  Success = false;
1577  if (Diags)
1578  Diags->Report(diag::err_drv_invalid_value)
1579  << Args.getLastArg(OPT_fdiagnostics_format)->getAsString(Args)
1580  << Format;
1581  }
1582 
1583  Opts.ShowSourceRanges = Args.hasArg(OPT_fdiagnostics_print_source_range_info);
1584  Opts.ShowParseableFixits = Args.hasArg(OPT_fdiagnostics_parseable_fixits);
1585  Opts.ShowPresumedLoc = !Args.hasArg(OPT_fno_diagnostics_use_presumed_location);
1586  Opts.VerifyDiagnostics = Args.hasArg(OPT_verify) || Args.hasArg(OPT_verify_EQ);
1587  Opts.VerifyPrefixes = Args.getAllArgValues(OPT_verify_EQ);
1588  if (Args.hasArg(OPT_verify))
1589  Opts.VerifyPrefixes.push_back("expected");
1590  // Keep VerifyPrefixes in its original order for the sake of diagnostics, and
1591  // then sort it to prepare for fast lookup using std::binary_search.
1592  if (!checkVerifyPrefixes(Opts.VerifyPrefixes, Diags)) {
1593  Opts.VerifyDiagnostics = false;
1594  Success = false;
1595  }
1596  else
1597  llvm::sort(Opts.VerifyPrefixes);
1599  Success &= parseDiagnosticLevelMask("-verify-ignore-unexpected=",
1600  Args.getAllArgValues(OPT_verify_ignore_unexpected_EQ),
1601  Diags, DiagMask);
1602  if (Args.hasArg(OPT_verify_ignore_unexpected))
1603  DiagMask = DiagnosticLevelMask::All;
1604  Opts.setVerifyIgnoreUnexpected(DiagMask);
1605  Opts.ElideType = !Args.hasArg(OPT_fno_elide_type);
1606  Opts.ShowTemplateTree = Args.hasArg(OPT_fdiagnostics_show_template_tree);
1607  Opts.ErrorLimit = getLastArgIntValue(Args, OPT_ferror_limit, 0, Diags);
1608  Opts.MacroBacktraceLimit =
1609  getLastArgIntValue(Args, OPT_fmacro_backtrace_limit,
1611  Opts.TemplateBacktraceLimit = getLastArgIntValue(
1612  Args, OPT_ftemplate_backtrace_limit,
1614  Opts.ConstexprBacktraceLimit = getLastArgIntValue(
1615  Args, OPT_fconstexpr_backtrace_limit,
1617  Opts.SpellCheckingLimit = getLastArgIntValue(
1618  Args, OPT_fspell_checking_limit,
1620  Opts.SnippetLineLimit = getLastArgIntValue(
1621  Args, OPT_fcaret_diagnostics_max_lines,
1623  Opts.TabStop = getLastArgIntValue(Args, OPT_ftabstop,
1625  if (Opts.TabStop == 0 || Opts.TabStop > DiagnosticOptions::MaxTabStop) {
1626  Opts.TabStop = DiagnosticOptions::DefaultTabStop;
1627  if (Diags)
1628  Diags->Report(diag::warn_ignoring_ftabstop_value)
1629  << Opts.TabStop << DiagnosticOptions::DefaultTabStop;
1630  }
1631  Opts.MessageLength = getLastArgIntValue(Args, OPT_fmessage_length, 0, Diags);
1632  addDiagnosticArgs(Args, OPT_W_Group, OPT_W_value_Group, Opts.Warnings);
1633  addDiagnosticArgs(Args, OPT_R_Group, OPT_R_value_Group, Opts.Remarks);
1634 
1635  return Success;
1636 }
1637 
1638 static void ParseFileSystemArgs(FileSystemOptions &Opts, ArgList &Args) {
1639  Opts.WorkingDir = Args.getLastArgValue(OPT_working_directory);
1640 }
1641 
1642 /// Parse the argument to the -ftest-module-file-extension
1643 /// command-line argument.
1644 ///
1645 /// \returns true on error, false on success.
1646 static bool parseTestModuleFileExtensionArg(StringRef Arg,
1647  std::string &BlockName,
1648  unsigned &MajorVersion,
1649  unsigned &MinorVersion,
1650  bool &Hashed,
1651  std::string &UserInfo) {
1653  Arg.split(Args, ':', 5);
1654  if (Args.size() < 5)
1655  return true;
1656 
1657  BlockName = Args[0];
1658  if (Args[1].getAsInteger(10, MajorVersion)) return true;
1659  if (Args[2].getAsInteger(10, MinorVersion)) return true;
1660  if (Args[3].getAsInteger(2, Hashed)) return true;
1661  if (Args.size() > 4)
1662  UserInfo = Args[4];
1663  return false;
1664 }
1665 
1666 static InputKind ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args,
1667  DiagnosticsEngine &Diags,
1668  bool &IsHeaderFile) {
1670  if (const Arg *A = Args.getLastArg(OPT_Action_Group)) {
1671  switch (A->getOption().getID()) {
1672  default:
1673  llvm_unreachable("Invalid option in group!");
1674  case OPT_ast_list:
1675  Opts.ProgramAction = frontend::ASTDeclList; break;
1676  case OPT_ast_dump_all_EQ:
1677  case OPT_ast_dump_EQ: {
1678  unsigned Val = llvm::StringSwitch<unsigned>(A->getValue())
1679  .CaseLower("default", ADOF_Default)
1680  .CaseLower("json", ADOF_JSON)
1682 
1684  Opts.ASTDumpFormat = static_cast<ASTDumpOutputFormat>(Val);
1685  else {
1686  Diags.Report(diag::err_drv_invalid_value)
1687  << A->getAsString(Args) << A->getValue();
1688  Opts.ASTDumpFormat = ADOF_Default;
1689  }
1690  LLVM_FALLTHROUGH;
1691  }
1692  case OPT_ast_dump:
1693  case OPT_ast_dump_all:
1694  case OPT_ast_dump_lookups:
1695  Opts.ProgramAction = frontend::ASTDump; break;
1696  case OPT_ast_print:
1697  Opts.ProgramAction = frontend::ASTPrint; break;
1698  case OPT_ast_view:
1699  Opts.ProgramAction = frontend::ASTView; break;
1700  case OPT_compiler_options_dump:
1702  case OPT_dump_raw_tokens:
1703  Opts.ProgramAction = frontend::DumpRawTokens; break;
1704  case OPT_dump_tokens:
1705  Opts.ProgramAction = frontend::DumpTokens; break;
1706  case OPT_S:
1707  Opts.ProgramAction = frontend::EmitAssembly; break;
1708  case OPT_emit_llvm_bc:
1709  Opts.ProgramAction = frontend::EmitBC; break;
1710  case OPT_emit_html:
1711  Opts.ProgramAction = frontend::EmitHTML; break;
1712  case OPT_emit_llvm:
1713  Opts.ProgramAction = frontend::EmitLLVM; break;
1714  case OPT_emit_llvm_only:
1715  Opts.ProgramAction = frontend::EmitLLVMOnly; break;
1716  case OPT_emit_codegen_only:
1718  case OPT_emit_obj:
1719  Opts.ProgramAction = frontend::EmitObj; break;
1720  case OPT_fixit_EQ:
1721  Opts.FixItSuffix = A->getValue();
1722  LLVM_FALLTHROUGH;
1723  case OPT_fixit:
1724  Opts.ProgramAction = frontend::FixIt; break;
1725  case OPT_emit_module:
1727  case OPT_emit_module_interface:
1729  case OPT_emit_header_module:
1731  case OPT_emit_pch:
1732  Opts.ProgramAction = frontend::GeneratePCH; break;
1733  case OPT_emit_iterface_stubs: {
1734  StringRef ArgStr =
1735  Args.hasArg(OPT_iterface_stub_version_EQ)
1736  ? Args.getLastArgValue(OPT_iterface_stub_version_EQ)
1737  : "";
1738  llvm::Optional<frontend::ActionKind> ProgramAction =
1739  llvm::StringSwitch<llvm::Optional<frontend::ActionKind>>(ArgStr)
1740  .Case("experimental-ifs-v1", frontend::GenerateInterfaceIfsExpV1)
1741  .Default(llvm::None);
1742  if (!ProgramAction) {
1743  std::string ErrorMessage =
1744  "Invalid interface stub format: " + ArgStr.str() +
1745  ((ArgStr == "experimental-yaml-elf-v1" ||
1746  ArgStr == "experimental-tapi-elf-v1")
1747  ? " is deprecated."
1748  : ".");
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 {
1754  Opts.ProgramAction = *ProgramAction;
1755  }
1756  break;
1757  }
1758  case OPT_init_only:
1759  Opts.ProgramAction = frontend::InitOnly; break;
1760  case OPT_fsyntax_only:
1762  case OPT_module_file_info:
1764  case OPT_verify_pch:
1765  Opts.ProgramAction = frontend::VerifyPCH; break;
1766  case OPT_print_preamble:
1767  Opts.ProgramAction = frontend::PrintPreamble; break;
1768  case OPT_E:
1770  case OPT_templight_dump:
1771  Opts.ProgramAction = frontend::TemplightDump; break;
1772  case OPT_rewrite_macros:
1773  Opts.ProgramAction = frontend::RewriteMacros; break;
1774  case OPT_rewrite_objc:
1775  Opts.ProgramAction = frontend::RewriteObjC; break;
1776  case OPT_rewrite_test:
1777  Opts.ProgramAction = frontend::RewriteTest; break;
1778  case OPT_analyze:
1779  Opts.ProgramAction = frontend::RunAnalysis; break;
1780  case OPT_migrate:
1781  Opts.ProgramAction = frontend::MigrateSource; break;
1782  case OPT_Eonly:
1784  case OPT_print_dependency_directives_minimized_source:
1785  Opts.ProgramAction =
1787  break;
1788  }
1789  }
1790 
1791  if (const Arg* A = Args.getLastArg(OPT_plugin)) {
1792  Opts.Plugins.emplace_back(A->getValue(0));
1794  Opts.ActionName = A->getValue();
1795  }
1796  Opts.AddPluginActions = Args.getAllArgValues(OPT_add_plugin);
1797  for (const auto *AA : Args.filtered(OPT_plugin_arg))
1798  Opts.PluginArgs[AA->getValue(0)].emplace_back(AA->getValue(1));
1799 
1800  for (const std::string &Arg :
1801  Args.getAllArgValues(OPT_ftest_module_file_extension_EQ)) {
1802  std::string BlockName;
1803  unsigned MajorVersion;
1804  unsigned MinorVersion;
1805  bool Hashed;
1806  std::string UserInfo;
1807  if (parseTestModuleFileExtensionArg(Arg, BlockName, MajorVersion,
1808  MinorVersion, Hashed, UserInfo)) {
1809  Diags.Report(diag::err_test_module_file_extension_format) << Arg;
1810 
1811  continue;
1812  }
1813 
1814  // Add the testing module file extension.
1815  Opts.ModuleFileExtensions.push_back(
1816  std::make_shared<TestModuleFileExtension>(
1817  BlockName, MajorVersion, MinorVersion, Hashed, UserInfo));
1818  }
1819 
1820  if (const Arg *A = Args.getLastArg(OPT_code_completion_at)) {
1821  Opts.CodeCompletionAt =
1822  ParsedSourceLocation::FromString(A->getValue());
1823  if (Opts.CodeCompletionAt.FileName.empty())
1824  Diags.Report(diag::err_drv_invalid_value)
1825  << A->getAsString(Args) << A->getValue();
1826  }
1827  Opts.DisableFree = Args.hasArg(OPT_disable_free);
1828 
1829  Opts.OutputFile = Args.getLastArgValue(OPT_o);
1830  Opts.Plugins = Args.getAllArgValues(OPT_load);
1831  Opts.RelocatablePCH = Args.hasArg(OPT_relocatable_pch);
1832  Opts.ShowHelp = Args.hasArg(OPT_help);
1833  Opts.ShowStats = Args.hasArg(OPT_print_stats);
1834  Opts.ShowTimers = Args.hasArg(OPT_ftime_report);
1835  Opts.PrintSupportedCPUs = Args.hasArg(OPT_print_supported_cpus);
1836  Opts.TimeTrace = Args.hasArg(OPT_ftime_trace);
1838  Args, OPT_ftime_trace_granularity_EQ, Opts.TimeTraceGranularity, Diags);
1839  Opts.ShowVersion = Args.hasArg(OPT_version);
1840  Opts.ASTMergeFiles = Args.getAllArgValues(OPT_ast_merge);
1841  Opts.LLVMArgs = Args.getAllArgValues(OPT_mllvm);
1842  Opts.FixWhatYouCan = Args.hasArg(OPT_fix_what_you_can);
1843  Opts.FixOnlyWarnings = Args.hasArg(OPT_fix_only_warnings);
1844  Opts.FixAndRecompile = Args.hasArg(OPT_fixit_recompile);
1845  Opts.FixToTemporaries = Args.hasArg(OPT_fixit_to_temp);
1846  Opts.ASTDumpDecls = Args.hasArg(OPT_ast_dump, OPT_ast_dump_EQ);
1847  Opts.ASTDumpAll = Args.hasArg(OPT_ast_dump_all, OPT_ast_dump_all_EQ);
1848  Opts.ASTDumpFilter = Args.getLastArgValue(OPT_ast_dump_filter);
1849  Opts.ASTDumpLookups = Args.hasArg(OPT_ast_dump_lookups);
1850  Opts.UseGlobalModuleIndex = !Args.hasArg(OPT_fno_modules_global_index);
1852  Opts.ModuleMapFiles = Args.getAllArgValues(OPT_fmodule_map_file);
1853  // Only the -fmodule-file=<file> form.
1854  for (const auto *A : Args.filtered(OPT_fmodule_file)) {
1855  StringRef Val = A->getValue();
1856  if (Val.find('=') == StringRef::npos)
1857  Opts.ModuleFiles.push_back(Val);
1858  }
1859  Opts.ModulesEmbedFiles = Args.getAllArgValues(OPT_fmodules_embed_file_EQ);
1860  Opts.ModulesEmbedAllFiles = Args.hasArg(OPT_fmodules_embed_all_files);
1861  Opts.IncludeTimestamps = !Args.hasArg(OPT_fno_pch_timestamp);
1862 
1864  = Args.hasArg(OPT_code_completion_macros);
1866  = Args.hasArg(OPT_code_completion_patterns);
1868  = !Args.hasArg(OPT_no_code_completion_globals);
1870  = !Args.hasArg(OPT_no_code_completion_ns_level_decls);
1872  = Args.hasArg(OPT_code_completion_brief_comments);
1874  = Args.hasArg(OPT_code_completion_with_fixits);
1875 
1877  = Args.getLastArgValue(OPT_foverride_record_layout_EQ);
1878  Opts.AuxTriple = Args.getLastArgValue(OPT_aux_triple);
1879  Opts.StatsFile = Args.getLastArgValue(OPT_stats_file);
1880 
1881  if (const Arg *A = Args.getLastArg(OPT_arcmt_check,
1882  OPT_arcmt_modify,
1883  OPT_arcmt_migrate)) {
1884  switch (A->getOption().getID()) {
1885  default:
1886  llvm_unreachable("missed a case");
1887  case OPT_arcmt_check:
1889  break;
1890  case OPT_arcmt_modify:
1892  break;
1893  case OPT_arcmt_migrate:
1895  break;
1896  }
1897  }
1898  Opts.MTMigrateDir = Args.getLastArgValue(OPT_mt_migrate_directory);
1900  = Args.getLastArgValue(OPT_arcmt_migrate_report_output);
1902  = Args.hasArg(OPT_arcmt_migrate_emit_arc_errors);
1903 
1904  if (Args.hasArg(OPT_objcmt_migrate_literals))
1906  if (Args.hasArg(OPT_objcmt_migrate_subscripting))
1908  if (Args.hasArg(OPT_objcmt_migrate_property_dot_syntax))
1910  if (Args.hasArg(OPT_objcmt_migrate_property))
1912  if (Args.hasArg(OPT_objcmt_migrate_readonly_property))
1914  if (Args.hasArg(OPT_objcmt_migrate_readwrite_property))
1916  if (Args.hasArg(OPT_objcmt_migrate_annotation))
1918  if (Args.hasArg(OPT_objcmt_returns_innerpointer_property))
1920  if (Args.hasArg(OPT_objcmt_migrate_instancetype))
1922  if (Args.hasArg(OPT_objcmt_migrate_nsmacros))
1924  if (Args.hasArg(OPT_objcmt_migrate_protocol_conformance))
1926  if (Args.hasArg(OPT_objcmt_atomic_property))
1928  if (Args.hasArg(OPT_objcmt_ns_nonatomic_iosonly))
1930  if (Args.hasArg(OPT_objcmt_migrate_designated_init))
1932  if (Args.hasArg(OPT_objcmt_migrate_all))
1934 
1935  Opts.ObjCMTWhiteListPath = Args.getLastArgValue(OPT_objcmt_whitelist_dir_path);
1936 
1939  Diags.Report(diag::err_drv_argument_not_allowed_with)
1940  << "ARC migration" << "ObjC migration";
1941  }
1942 
1944  if (const Arg *A = Args.getLastArg(OPT_x)) {
1945  StringRef XValue = A->getValue();
1946 
1947  // Parse suffixes: '<lang>(-header|[-module-map][-cpp-output])'.
1948  // FIXME: Supporting '<lang>-header-cpp-output' would be useful.
1949  bool Preprocessed = XValue.consume_back("-cpp-output");
1950  bool ModuleMap = XValue.consume_back("-module-map");
1951  IsHeaderFile =
1952  !Preprocessed && !ModuleMap && XValue.consume_back("-header");
1953 
1954  // Principal languages.
1955  DashX = llvm::StringSwitch<InputKind>(XValue)
1956  .Case("c", Language::C)
1957  .Case("cl", Language::OpenCL)
1958  .Case("cuda", Language::CUDA)
1959  .Case("hip", Language::HIP)
1960  .Case("c++", Language::CXX)
1961  .Case("objective-c", Language::ObjC)
1962  .Case("objective-c++", Language::ObjCXX)
1963  .Case("renderscript", Language::RenderScript)
1964  .Default(Language::Unknown);
1965 
1966  // "objc[++]-cpp-output" is an acceptable synonym for
1967  // "objective-c[++]-cpp-output".
1968  if (DashX.isUnknown() && Preprocessed && !IsHeaderFile && !ModuleMap)
1969  DashX = llvm::StringSwitch<InputKind>(XValue)
1970  .Case("objc", Language::ObjC)
1971  .Case("objc++", Language::ObjCXX)
1972  .Default(Language::Unknown);
1973 
1974  // Some special cases cannot be combined with suffixes.
1975  if (DashX.isUnknown() && !Preprocessed && !ModuleMap && !IsHeaderFile)
1976  DashX = llvm::StringSwitch<InputKind>(XValue)
1977  .Case("cpp-output", InputKind(Language::C).getPreprocessed())
1978  .Case("assembler-with-cpp", Language::Asm)
1979  .Cases("ast", "pcm",
1981  .Case("ir", Language::LLVM_IR)
1982  .Default(Language::Unknown);
1983 
1984  if (DashX.isUnknown())
1985  Diags.Report(diag::err_drv_invalid_value)
1986  << A->getAsString(Args) << A->getValue();
1987 
1988  if (Preprocessed)
1989  DashX = DashX.getPreprocessed();
1990  if (ModuleMap)
1991  DashX = DashX.withFormat(InputKind::ModuleMap);
1992  }
1993 
1994  // '-' is the default input if none is given.
1995  std::vector<std::string> Inputs = Args.getAllArgValues(OPT_INPUT);
1996  Opts.Inputs.clear();
1997  if (Inputs.empty())
1998  Inputs.push_back("-");
1999  for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
2000  InputKind IK = DashX;
2001  if (IK.isUnknown()) {
2003  StringRef(Inputs[i]).rsplit('.').second);
2004  // FIXME: Warn on this?
2005  if (IK.isUnknown())
2006  IK = Language::C;
2007  // FIXME: Remove this hack.
2008  if (i == 0)
2009  DashX = IK;
2010  }
2011 
2012  // The -emit-module action implicitly takes a module map.
2014  IK.getFormat() == InputKind::Source)
2016 
2017  Opts.Inputs.emplace_back(std::move(Inputs[i]), IK);
2018  }
2019 
2020  return DashX;
2021 }
2022 
2023 std::string CompilerInvocation::GetResourcesPath(const char *Argv0,
2024  void *MainAddr) {
2025  std::string ClangExecutable =
2026  llvm::sys::fs::getMainExecutable(Argv0, MainAddr);
2027  return Driver::GetResourcesPath(ClangExecutable, CLANG_RESOURCE_DIR);
2028 }
2029 
2030 static void ParseHeaderSearchArgs(HeaderSearchOptions &Opts, ArgList &Args,
2031  const std::string &WorkingDir) {
2032  Opts.Sysroot = Args.getLastArgValue(OPT_isysroot, "/");
2033  Opts.Verbose = Args.hasArg(OPT_v);
2034  Opts.UseBuiltinIncludes = !Args.hasArg(OPT_nobuiltininc);
2035  Opts.UseStandardSystemIncludes = !Args.hasArg(OPT_nostdsysteminc);
2036  Opts.UseStandardCXXIncludes = !Args.hasArg(OPT_nostdincxx);
2037  if (const Arg *A = Args.getLastArg(OPT_stdlib_EQ))
2038  Opts.UseLibcxx = (strcmp(A->getValue(), "libc++") == 0);
2039  Opts.ResourceDir = Args.getLastArgValue(OPT_resource_dir);
2040 
2041  // Canonicalize -fmodules-cache-path before storing it.
2042  SmallString<128> P(Args.getLastArgValue(OPT_fmodules_cache_path));
2043  if (!(P.empty() || llvm::sys::path::is_absolute(P))) {
2044  if (WorkingDir.empty())
2045  llvm::sys::fs::make_absolute(P);
2046  else
2047  llvm::sys::fs::make_absolute(WorkingDir, P);
2048  }
2049  llvm::sys::path::remove_dots(P);
2050  Opts.ModuleCachePath = P.str();
2051 
2052  Opts.ModuleUserBuildPath = Args.getLastArgValue(OPT_fmodules_user_build_path);
2053  // Only the -fmodule-file=<name>=<file> form.
2054  for (const auto *A : Args.filtered(OPT_fmodule_file)) {
2055  StringRef Val = A->getValue();
2056  if (Val.find('=') != StringRef::npos)
2057  Opts.PrebuiltModuleFiles.insert(Val.split('='));
2058  }
2059  for (const auto *A : Args.filtered(OPT_fprebuilt_module_path))
2060  Opts.AddPrebuiltModulePath(A->getValue());
2061  Opts.DisableModuleHash = Args.hasArg(OPT_fdisable_module_hash);
2062  Opts.ModulesHashContent = Args.hasArg(OPT_fmodules_hash_content);
2064  !Args.hasArg(OPT_fmodules_disable_diagnostic_validation);
2065  Opts.ImplicitModuleMaps = Args.hasArg(OPT_fimplicit_module_maps);
2066  Opts.ModuleMapFileHomeIsCwd = Args.hasArg(OPT_fmodule_map_file_home_is_cwd);
2068  getLastArgIntValue(Args, OPT_fmodules_prune_interval, 7 * 24 * 60 * 60);
2069  Opts.ModuleCachePruneAfter =
2070  getLastArgIntValue(Args, OPT_fmodules_prune_after, 31 * 24 * 60 * 60);
2072  Args.hasArg(OPT_fmodules_validate_once_per_build_session);
2073  Opts.BuildSessionTimestamp =
2074  getLastArgUInt64Value(Args, OPT_fbuild_session_timestamp, 0);
2076  Args.hasArg(OPT_fmodules_validate_system_headers);
2077  if (const Arg *A = Args.getLastArg(OPT_fmodule_format_EQ))
2078  Opts.ModuleFormat = A->getValue();
2079 
2080  for (const auto *A : Args.filtered(OPT_fmodules_ignore_macro)) {
2081  StringRef MacroDef = A->getValue();
2082  Opts.ModulesIgnoreMacros.insert(
2083  llvm::CachedHashString(MacroDef.split('=').first));
2084  }
2085 
2086  // Add -I..., -F..., and -index-header-map options in order.
2087  bool IsIndexHeaderMap = false;
2088  bool IsSysrootSpecified =
2089  Args.hasArg(OPT__sysroot_EQ) || Args.hasArg(OPT_isysroot);
2090  for (const auto *A : Args.filtered(OPT_I, OPT_F, OPT_index_header_map)) {
2091  if (A->getOption().matches(OPT_index_header_map)) {
2092  // -index-header-map applies to the next -I or -F.
2093  IsIndexHeaderMap = true;
2094  continue;
2095  }
2096 
2098  IsIndexHeaderMap ? frontend::IndexHeaderMap : frontend::Angled;
2099 
2100  bool IsFramework = A->getOption().matches(OPT_F);
2101  std::string Path = A->getValue();
2102 
2103  if (IsSysrootSpecified && !IsFramework && A->getValue()[0] == '=') {
2104  SmallString<32> Buffer;
2105  llvm::sys::path::append(Buffer, Opts.Sysroot,
2106  llvm::StringRef(A->getValue()).substr(1));
2107  Path = Buffer.str();
2108  }
2109 
2110  Opts.AddPath(Path, Group, IsFramework,
2111  /*IgnoreSysroot*/ true);
2112  IsIndexHeaderMap = false;
2113  }
2114 
2115  // Add -iprefix/-iwithprefix/-iwithprefixbefore options.
2116  StringRef Prefix = ""; // FIXME: This isn't the correct default prefix.
2117  for (const auto *A :
2118  Args.filtered(OPT_iprefix, OPT_iwithprefix, OPT_iwithprefixbefore)) {
2119  if (A->getOption().matches(OPT_iprefix))
2120  Prefix = A->getValue();
2121  else if (A->getOption().matches(OPT_iwithprefix))
2122  Opts.AddPath(Prefix.str() + A->getValue(), frontend::After, false, true);
2123  else
2124  Opts.AddPath(Prefix.str() + A->getValue(), frontend::Angled, false, true);
2125  }
2126 
2127  for (const auto *A : Args.filtered(OPT_idirafter))
2128  Opts.AddPath(A->getValue(), frontend::After, false, true);
2129  for (const auto *A : Args.filtered(OPT_iquote))
2130  Opts.AddPath(A->getValue(), frontend::Quoted, false, true);
2131  for (const auto *A : Args.filtered(OPT_isystem, OPT_iwithsysroot))
2132  Opts.AddPath(A->getValue(), frontend::System, false,
2133  !A->getOption().matches(OPT_iwithsysroot));
2134  for (const auto *A : Args.filtered(OPT_iframework))
2135  Opts.AddPath(A->getValue(), frontend::System, true, true);
2136  for (const auto *A : Args.filtered(OPT_iframeworkwithsysroot))
2137  Opts.AddPath(A->getValue(), frontend::System, /*IsFramework=*/true,
2138  /*IgnoreSysRoot=*/false);
2139 
2140  // Add the paths for the various language specific isystem flags.
2141  for (const auto *A : Args.filtered(OPT_c_isystem))
2142  Opts.AddPath(A->getValue(), frontend::CSystem, false, true);
2143  for (const auto *A : Args.filtered(OPT_cxx_isystem))
2144  Opts.AddPath(A->getValue(), frontend::CXXSystem, false, true);
2145  for (const auto *A : Args.filtered(OPT_objc_isystem))
2146  Opts.AddPath(A->getValue(), frontend::ObjCSystem, false,true);
2147  for (const auto *A : Args.filtered(OPT_objcxx_isystem))
2148  Opts.AddPath(A->getValue(), frontend::ObjCXXSystem, false, true);
2149 
2150  // Add the internal paths from a driver that detects standard include paths.
2151  for (const auto *A :
2152  Args.filtered(OPT_internal_isystem, OPT_internal_externc_isystem)) {
2154  if (A->getOption().matches(OPT_internal_externc_isystem))
2155  Group = frontend::ExternCSystem;
2156  Opts.AddPath(A->getValue(), Group, false, true);
2157  }
2158 
2159  // Add the path prefixes which are implicitly treated as being system headers.
2160  for (const auto *A :
2161  Args.filtered(OPT_system_header_prefix, OPT_no_system_header_prefix))
2162  Opts.AddSystemHeaderPrefix(
2163  A->getValue(), A->getOption().matches(OPT_system_header_prefix));
2164 
2165  for (const auto *A : Args.filtered(OPT_ivfsoverlay))
2166  Opts.AddVFSOverlayFile(A->getValue());
2167 }
2168 
2170  const llvm::Triple &T,
2171  PreprocessorOptions &PPOpts,
2172  LangStandard::Kind LangStd) {
2173  // Set some properties which depend solely on the input kind; it would be nice
2174  // to move these to the language standard, and have the driver resolve the
2175  // input kind + language standard.
2176  //
2177  // FIXME: Perhaps a better model would be for a single source file to have
2178  // multiple language standards (C / C++ std, ObjC std, OpenCL std, OpenMP std)
2179  // simultaneously active?
2180  if (IK.getLanguage() == Language::Asm) {
2181  Opts.AsmPreprocessor = 1;
2182  } else if (IK.isObjectiveC()) {
2183  Opts.ObjC = 1;
2184  }
2185 
2186  if (LangStd == LangStandard::lang_unspecified) {
2187  // Based on the base language, pick one.
2188  switch (IK.getLanguage()) {
2189  case Language::Unknown:
2190  case Language::LLVM_IR:
2191  llvm_unreachable("Invalid input kind!");
2192  case Language::OpenCL:
2193  LangStd = LangStandard::lang_opencl10;
2194  break;
2195  case Language::CUDA:
2196  LangStd = LangStandard::lang_cuda;
2197  break;
2198  case Language::Asm:
2199  case Language::C:
2200 #if defined(CLANG_DEFAULT_STD_C)
2201  LangStd = CLANG_DEFAULT_STD_C;
2202 #else
2203  // The PS4 uses C99 as the default C standard.
2204  if (T.isPS4())
2205  LangStd = LangStandard::lang_gnu99;
2206  else
2207  LangStd = LangStandard::lang_gnu11;
2208 #endif
2209  break;
2210  case Language::ObjC:
2211 #if defined(CLANG_DEFAULT_STD_C)
2212  LangStd = CLANG_DEFAULT_STD_C;
2213 #else
2214  LangStd = LangStandard::lang_gnu11;
2215 #endif
2216  break;
2217  case Language::CXX:
2218  case Language::ObjCXX:
2219 #if defined(CLANG_DEFAULT_STD_CXX)
2220  LangStd = CLANG_DEFAULT_STD_CXX;
2221 #else
2222  LangStd = LangStandard::lang_gnucxx14;
2223 #endif
2224  break;
2226  LangStd = LangStandard::lang_c99;
2227  break;
2228  case Language::HIP:
2229  LangStd = LangStandard::lang_hip;
2230  break;
2231  }
2232  }
2233 
2235  Opts.LineComment = Std.hasLineComments();
2236  Opts.C99 = Std.isC99();
2237  Opts.C11 = Std.isC11();
2238  Opts.C17 = Std.isC17();
2239  Opts.C2x = Std.isC2x();
2240  Opts.CPlusPlus = Std.isCPlusPlus();
2241  Opts.CPlusPlus11 = Std.isCPlusPlus11();
2242  Opts.CPlusPlus14 = Std.isCPlusPlus14();
2243  Opts.CPlusPlus17 = Std.isCPlusPlus17();
2244  Opts.CPlusPlus2a = Std.isCPlusPlus2a();
2245  Opts.Digraphs = Std.hasDigraphs();
2246  Opts.GNUMode = Std.isGNUMode();
2247  Opts.GNUInline = !Opts.C99 && !Opts.CPlusPlus;
2248  Opts.HexFloats = Std.hasHexFloats();
2249  Opts.ImplicitInt = Std.hasImplicitInt();
2250 
2251  // Set OpenCL Version.
2252  Opts.OpenCL = Std.isOpenCL();
2253  if (LangStd == LangStandard::lang_opencl10)
2254  Opts.OpenCLVersion = 100;
2255  else if (LangStd == LangStandard::lang_opencl11)
2256  Opts.OpenCLVersion = 110;
2257  else if (LangStd == LangStandard::lang_opencl12)
2258  Opts.OpenCLVersion = 120;
2259  else if (LangStd == LangStandard::lang_opencl20)
2260  Opts.OpenCLVersion = 200;
2261  else if (LangStd == LangStandard::lang_openclcpp)
2262  Opts.OpenCLCPlusPlusVersion = 100;
2263 
2264  // OpenCL has some additional defaults.
2265  if (Opts.OpenCL) {
2266  Opts.AltiVec = 0;
2267  Opts.ZVector = 0;
2268  Opts.setLaxVectorConversions(LangOptions::LaxVectorConversionKind::None);
2269  Opts.setDefaultFPContractMode(LangOptions::FPC_On);
2270  Opts.NativeHalfType = 1;
2271  Opts.NativeHalfArgsAndReturns = 1;
2272  Opts.OpenCLCPlusPlus = Opts.CPlusPlus;
2273 
2274  // Include default header file for OpenCL.
2275  if (Opts.IncludeDefaultHeader) {
2276  if (Opts.DeclareOpenCLBuiltins) {
2277  // Only include base header file for builtin types and constants.
2278  PPOpts.Includes.push_back("opencl-c-base.h");
2279  } else {
2280  PPOpts.Includes.push_back("opencl-c.h");
2281  }
2282  }
2283  }
2284 
2285  Opts.HIP = IK.getLanguage() == Language::HIP;
2286  Opts.CUDA = IK.getLanguage() == Language::CUDA || Opts.HIP;
2287  if (Opts.CUDA)
2288  // Set default FP_CONTRACT to FAST.
2289  Opts.setDefaultFPContractMode(LangOptions::FPC_Fast);
2290 
2291  Opts.RenderScript = IK.getLanguage() == Language::RenderScript;
2292  if (Opts.RenderScript) {
2293  Opts.NativeHalfType = 1;
2294  Opts.NativeHalfArgsAndReturns = 1;
2295  }
2296 
2297  // OpenCL and C++ both have bool, true, false keywords.
2298  Opts.Bool = Opts.OpenCL || Opts.CPlusPlus;
2299 
2300  // OpenCL has half keyword
2301  Opts.Half = Opts.OpenCL;
2302 
2303  // C++ has wchar_t keyword.
2304  Opts.WChar = Opts.CPlusPlus;
2305 
2306  Opts.GNUKeywords = Opts.GNUMode;
2307  Opts.CXXOperatorNames = Opts.CPlusPlus;
2308 
2309  Opts.AlignedAllocation = Opts.CPlusPlus17;
2310 
2311  Opts.DollarIdents = !Opts.AsmPreprocessor;
2312 
2313  // Enable [[]] attributes in C++11 and C2x by default.
2314  Opts.DoubleSquareBracketAttributes = Opts.CPlusPlus11 || Opts.C2x;
2315 }
2316 
2317 /// Attempt to parse a visibility value out of the given argument.
2318 static Visibility parseVisibility(Arg *arg, ArgList &args,
2319  DiagnosticsEngine &diags) {
2320  StringRef value = arg->getValue();
2321  if (value == "default") {
2322  return DefaultVisibility;
2323  } else if (value == "hidden" || value == "internal") {
2324  return HiddenVisibility;
2325  } else if (value == "protected") {
2326  // FIXME: diagnose if target does not support protected visibility
2327  return ProtectedVisibility;
2328  }
2329 
2330  diags.Report(diag::err_drv_invalid_value)
2331  << arg->getAsString(args) << value;
2332  return DefaultVisibility;
2333 }
2334 
2335 /// Check if input file kind and language standard are compatible.
2337  const LangStandard &S) {
2338  switch (IK.getLanguage()) {
2339  case Language::Unknown:
2340  case Language::LLVM_IR:
2341  llvm_unreachable("should not parse language flags for this input");
2342 
2343  case Language::C:
2344  case Language::ObjC:
2346  return S.getLanguage() == Language::C;
2347 
2348  case Language::OpenCL:
2349  return S.getLanguage() == Language::OpenCL;
2350 
2351  case Language::CXX:
2352  case Language::ObjCXX:
2353  return S.getLanguage() == Language::CXX;
2354 
2355  case Language::CUDA:
2356  // FIXME: What -std= values should be permitted for CUDA compilations?
2357  return S.getLanguage() == Language::CUDA ||
2358  S.getLanguage() == Language::CXX;
2359 
2360  case Language::HIP:
2361  return S.getLanguage() == Language::CXX || S.getLanguage() == Language::HIP;
2362 
2363  case Language::Asm:
2364  // Accept (and ignore) all -std= values.
2365  // FIXME: The -std= value is not ignored; it affects the tokenization
2366  // and preprocessing rules if we're preprocessing this asm input.
2367  return true;
2368  }
2369 
2370  llvm_unreachable("unexpected input language");
2371 }
2372 
2373 /// Get language name for given input kind.
2374 static const StringRef GetInputKindName(InputKind IK) {
2375  switch (IK.getLanguage()) {
2376  case Language::C:
2377  return "C";
2378  case Language::ObjC:
2379  return "Objective-C";
2380  case Language::CXX:
2381  return "C++";
2382  case Language::ObjCXX:
2383  return "Objective-C++";
2384  case Language::OpenCL:
2385  return "OpenCL";
2386  case Language::CUDA:
2387  return "CUDA";
2389  return "RenderScript";
2390  case Language::HIP:
2391  return "HIP";
2392 
2393  case Language::Asm:
2394  return "Asm";
2395  case Language::LLVM_IR:
2396  return "LLVM IR";
2397 
2398  case Language::Unknown:
2399  break;
2400  }
2401  llvm_unreachable("unknown input language");
2402 }
2403 
2404 static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK,
2405  const TargetOptions &TargetOpts,
2406  PreprocessorOptions &PPOpts,
2407  DiagnosticsEngine &Diags) {
2408  // FIXME: Cleanup per-file based stuff.
2410  if (const Arg *A = Args.getLastArg(OPT_std_EQ)) {
2411  LangStd = LangStandard::getLangKind(A->getValue());
2412  if (LangStd == LangStandard::lang_unspecified) {
2413  Diags.Report(diag::err_drv_invalid_value)
2414  << A->getAsString(Args) << A->getValue();
2415  // Report supported standards with short description.
2416  for (unsigned KindValue = 0;
2417  KindValue != LangStandard::lang_unspecified;
2418  ++KindValue) {
2420  static_cast<LangStandard::Kind>(KindValue));
2421  if (IsInputCompatibleWithStandard(IK, Std)) {
2422  auto Diag = Diags.Report(diag::note_drv_use_standard);
2423  Diag << Std.getName() << Std.getDescription();
2424  unsigned NumAliases = 0;
2425 #define LANGSTANDARD(id, name, lang, desc, features)
2426 #define LANGSTANDARD_ALIAS(id, alias) \
2427  if (KindValue == LangStandard::lang_##id) ++NumAliases;
2428 #define LANGSTANDARD_ALIAS_DEPR(id, alias)
2429 #include "clang/Basic/LangStandards.def"
2430  Diag << NumAliases;
2431 #define LANGSTANDARD(id, name, lang, desc, features)
2432 #define LANGSTANDARD_ALIAS(id, alias) \
2433  if (KindValue == LangStandard::lang_##id) Diag << alias;
2434 #define LANGSTANDARD_ALIAS_DEPR(id, alias)
2435 #include "clang/Basic/LangStandards.def"
2436  }
2437  }
2438  } else {
2439  // Valid standard, check to make sure language and standard are
2440  // compatible.
2442  if (!IsInputCompatibleWithStandard(IK, Std)) {
2443  Diags.Report(diag::err_drv_argument_not_allowed_with)
2444  << A->getAsString(Args) << GetInputKindName(IK);
2445  }
2446  }
2447  }
2448 
2449  if (Args.hasArg(OPT_fno_dllexport_inlines))
2450  Opts.DllExportInlines = false;
2451 
2452  if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
2453  StringRef Name = A->getValue();
2454  if (Name == "full" || Name == "branch") {
2455  Opts.CFProtectionBranch = 1;
2456  }
2457  }
2458  // -cl-std only applies for OpenCL language standards.
2459  // Override the -std option in this case.
2460  if (const Arg *A = Args.getLastArg(OPT_cl_std_EQ)) {
2461  LangStandard::Kind OpenCLLangStd
2462  = llvm::StringSwitch<LangStandard::Kind>(A->getValue())
2463  .Cases("cl", "CL", LangStandard::lang_opencl10)
2464  .Cases("cl1.1", "CL1.1", LangStandard::lang_opencl11)
2465  .Cases("cl1.2", "CL1.2", LangStandard::lang_opencl12)
2466  .Cases("cl2.0", "CL2.0", LangStandard::lang_opencl20)
2467  .Cases("clc++", "CLC++", LangStandard::lang_openclcpp)
2469 
2470  if (OpenCLLangStd == LangStandard::lang_unspecified) {
2471  Diags.Report(diag::err_drv_invalid_value)
2472  << A->getAsString(Args) << A->getValue();
2473  }
2474  else
2475  LangStd = OpenCLLangStd;
2476  }
2477 
2478  Opts.IncludeDefaultHeader = Args.hasArg(OPT_finclude_default_header);
2479  Opts.DeclareOpenCLBuiltins = Args.hasArg(OPT_fdeclare_opencl_builtins);
2480 
2481  llvm::Triple T(TargetOpts.Triple);
2482  CompilerInvocation::setLangDefaults(Opts, IK, T, PPOpts, LangStd);
2483 
2484  // -cl-strict-aliasing needs to emit diagnostic in the case where CL > 1.0.
2485  // This option should be deprecated for CL > 1.0 because
2486  // this option was added for compatibility with OpenCL 1.0.
2487  if (Args.getLastArg(OPT_cl_strict_aliasing)
2488  && Opts.OpenCLVersion > 100) {
2489  Diags.Report(diag::warn_option_invalid_ocl_version)
2490  << Opts.getOpenCLVersionTuple().getAsString()
2491  << Args.getLastArg(OPT_cl_strict_aliasing)->getAsString(Args);
2492  }
2493 
2494  // We abuse '-f[no-]gnu-keywords' to force overriding all GNU-extension
2495  // keywords. This behavior is provided by GCC's poorly named '-fasm' flag,
2496  // while a subset (the non-C++ GNU keywords) is provided by GCC's
2497  // '-fgnu-keywords'. Clang conflates the two for simplicity under the single
2498  // name, as it doesn't seem a useful distinction.
2499  Opts.GNUKeywords = Args.hasFlag(OPT_fgnu_keywords, OPT_fno_gnu_keywords,
2500  Opts.GNUKeywords);
2501 
2502  Opts.Digraphs = Args.hasFlag(OPT_fdigraphs, OPT_fno_digraphs, Opts.Digraphs);
2503 
2504  if (Args.hasArg(OPT_fno_operator_names))
2505  Opts.CXXOperatorNames = 0;
2506 
2507  if (Args.hasArg(OPT_fcuda_is_device))
2508  Opts.CUDAIsDevice = 1;
2509 
2510  if (Args.hasArg(OPT_fcuda_allow_variadic_functions))
2511  Opts.CUDAAllowVariadicFunctions = 1;
2512 
2513  if (Args.hasArg(OPT_fno_cuda_host_device_constexpr))
2514  Opts.CUDAHostDeviceConstexpr = 0;
2515 
2516  if (Opts.CUDAIsDevice && Args.hasArg(OPT_fcuda_approx_transcendentals))
2517  Opts.CUDADeviceApproxTranscendentals = 1;
2518 
2519  Opts.GPURelocatableDeviceCode = Args.hasArg(OPT_fgpu_rdc);
2520 
2521  if (Opts.ObjC) {
2522  if (Arg *arg = Args.getLastArg(OPT_fobjc_runtime_EQ)) {
2523  StringRef value = arg->getValue();
2524  if (Opts.ObjCRuntime.tryParse(value))
2525  Diags.Report(diag::err_drv_unknown_objc_runtime) << value;
2526  }
2527 
2528  if (Args.hasArg(OPT_fobjc_gc_only))
2529  Opts.setGC(LangOptions::GCOnly);
2530  else if (Args.hasArg(OPT_fobjc_gc))
2531  Opts.setGC(LangOptions::HybridGC);
2532  else if (Args.hasArg(OPT_fobjc_arc)) {
2533  Opts.ObjCAutoRefCount = 1;
2534  if (!Opts.ObjCRuntime.allowsARC())
2535  Diags.Report(diag::err_arc_unsupported_on_runtime);
2536  }
2537 
2538  // ObjCWeakRuntime tracks whether the runtime supports __weak, not
2539  // whether the feature is actually enabled. This is predominantly
2540  // determined by -fobjc-runtime, but we allow it to be overridden
2541  // from the command line for testing purposes.
2542  if (Args.hasArg(OPT_fobjc_runtime_has_weak))
2543  Opts.ObjCWeakRuntime = 1;
2544  else
2545  Opts.ObjCWeakRuntime = Opts.ObjCRuntime.allowsWeak();
2546 
2547  // ObjCWeak determines whether __weak is actually enabled.
2548  // Note that we allow -fno-objc-weak to disable this even in ARC mode.
2549  if (auto weakArg = Args.getLastArg(OPT_fobjc_weak, OPT_fno_objc_weak)) {
2550  if (!weakArg->getOption().matches(OPT_fobjc_weak)) {
2551  assert(!Opts.ObjCWeak);
2552  } else if (Opts.getGC() != LangOptions::NonGC) {
2553  Diags.Report(diag::err_objc_weak_with_gc);
2554  } else if (!Opts.ObjCWeakRuntime) {
2555  Diags.Report(diag::err_objc_weak_unsupported);
2556  } else {
2557  Opts.ObjCWeak = 1;
2558  }
2559  } else if (Opts.ObjCAutoRefCount) {
2560  Opts.ObjCWeak = Opts.ObjCWeakRuntime;
2561  }
2562 
2563  if (Args.hasArg(OPT_fno_objc_infer_related_result_type))
2564  Opts.ObjCInferRelatedResultType = 0;
2565 
2566  if (Args.hasArg(OPT_fobjc_subscripting_legacy_runtime))
2567  Opts.ObjCSubscriptingLegacyRuntime =
2569  }
2570 
2571  if (Args.hasArg(OPT_fgnu89_inline)) {
2572  if (Opts.CPlusPlus)
2573  Diags.Report(diag::err_drv_argument_not_allowed_with)
2574  << "-fgnu89-inline" << GetInputKindName(IK);
2575  else
2576  Opts.GNUInline = 1;
2577  }
2578 
2579  if (Args.hasArg(OPT_fapple_kext)) {
2580  if (!Opts.CPlusPlus)
2581  Diags.Report(diag::warn_c_kext);
2582  else
2583  Opts.AppleKext = 1;
2584  }
2585 
2586  if (Args.hasArg(OPT_print_ivar_layout))
2587  Opts.ObjCGCBitmapPrint = 1;
2588 
2589  if (Args.hasArg(OPT_fno_constant_cfstrings))
2590  Opts.NoConstantCFStrings = 1;
2591  if (const auto *A = Args.getLastArg(OPT_fcf_runtime_abi_EQ))
2592  Opts.CFRuntime =
2593  llvm::StringSwitch<LangOptions::CoreFoundationABI>(A->getValue())
2594  .Cases("unspecified", "standalone", "objc",
2596  .Cases("swift", "swift-5.0",
2598  .Case("swift-4.2", LangOptions::CoreFoundationABI::Swift4_2)
2599  .Case("swift-4.1", LangOptions::CoreFoundationABI::Swift4_1)
2601 
2602  if (Args.hasArg(OPT_fzvector))
2603  Opts.ZVector = 1;
2604 
2605  if (Args.hasArg(OPT_pthread))
2606  Opts.POSIXThreads = 1;
2607 
2608  // The value-visibility mode defaults to "default".
2609  if (Arg *visOpt = Args.getLastArg(OPT_fvisibility)) {
2610  Opts.setValueVisibilityMode(parseVisibility(visOpt, Args, Diags));
2611  } else {
2612  Opts.setValueVisibilityMode(DefaultVisibility);
2613  }
2614 
2615  // The type-visibility mode defaults to the value-visibility mode.
2616  if (Arg *typeVisOpt = Args.getLastArg(OPT_ftype_visibility)) {
2617  Opts.setTypeVisibilityMode(parseVisibility(typeVisOpt, Args, Diags));
2618  } else {
2619  Opts.setTypeVisibilityMode(Opts.getValueVisibilityMode());
2620  }
2621 
2622  if (Args.hasArg(OPT_fvisibility_inlines_hidden))
2623  Opts.InlineVisibilityHidden = 1;
2624 
2625  if (Args.hasArg(OPT_fvisibility_global_new_delete_hidden))
2626  Opts.GlobalAllocationFunctionVisibilityHidden = 1;
2627 
2628  if (Args.hasArg(OPT_fapply_global_visibility_to_externs))
2629  Opts.SetVisibilityForExternDecls = 1;
2630 
2631  if (Args.hasArg(OPT_ftrapv)) {
2632  Opts.setSignedOverflowBehavior(LangOptions::SOB_Trapping);
2633  // Set the handler, if one is specified.
2634  Opts.OverflowHandler =
2635  Args.getLastArgValue(OPT_ftrapv_handler);
2636  }
2637  else if (Args.hasArg(OPT_fwrapv))
2638  Opts.setSignedOverflowBehavior(LangOptions::SOB_Defined);
2639 
2640  Opts.MSVCCompat = Args.hasArg(OPT_fms_compatibility);
2641  Opts.MicrosoftExt = Opts.MSVCCompat || Args.hasArg(OPT_fms_extensions);
2642  Opts.AsmBlocks = Args.hasArg(OPT_fasm_blocks) || Opts.MicrosoftExt;
2643  Opts.MSCompatibilityVersion = 0;
2644  if (const Arg *A = Args.getLastArg(OPT_fms_compatibility_version)) {
2645  VersionTuple VT;
2646  if (VT.tryParse(A->getValue()))
2647  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
2648  << A->getValue();
2649  Opts.MSCompatibilityVersion = VT.getMajor() * 10000000 +
2650  VT.getMinor().getValueOr(0) * 100000 +
2651  VT.getSubminor().getValueOr(0);
2652  }
2653 
2654  // Mimicking gcc's behavior, trigraphs are only enabled if -trigraphs
2655  // is specified, or -std is set to a conforming mode.
2656  // Trigraphs are disabled by default in c++1z onwards.
2657  Opts.Trigraphs = !Opts.GNUMode && !Opts.MSVCCompat && !Opts.CPlusPlus17;
2658  Opts.Trigraphs =
2659  Args.hasFlag(OPT_ftrigraphs, OPT_fno_trigraphs, Opts.Trigraphs);
2660 
2661  Opts.DollarIdents = Args.hasFlag(OPT_fdollars_in_identifiers,
2662  OPT_fno_dollars_in_identifiers,
2663  Opts.DollarIdents);
2664  Opts.PascalStrings = Args.hasArg(OPT_fpascal_strings);
2665  Opts.VtorDispMode = getLastArgIntValue(Args, OPT_vtordisp_mode_EQ, 1, Diags);
2666  Opts.Borland = Args.hasArg(OPT_fborland_extensions);
2667  Opts.WritableStrings = Args.hasArg(OPT_fwritable_strings);
2668  Opts.ConstStrings = Args.hasFlag(OPT_fconst_strings, OPT_fno_const_strings,
2669  Opts.ConstStrings);
2670  if (Arg *A = Args.getLastArg(OPT_flax_vector_conversions_EQ)) {
2671  using LaxKind = LangOptions::LaxVectorConversionKind;
2672  if (auto Kind = llvm::StringSwitch<Optional<LaxKind>>(A->getValue())
2673  .Case("none", LaxKind::None)
2674  .Case("integer", LaxKind::Integer)
2675  .Case("all", LaxKind::All)
2676  .Default(llvm::None))
2677  Opts.setLaxVectorConversions(*Kind);
2678  else
2679  Diags.Report(diag::err_drv_invalid_value)
2680  << A->getAsString(Args) << A->getValue();
2681  }
2682  if (Args.hasArg(OPT_fno_threadsafe_statics))
2683  Opts.ThreadsafeStatics = 0;
2684  Opts.Exceptions = Args.hasArg(OPT_fexceptions);
2685  Opts.ObjCExceptions = Args.hasArg(OPT_fobjc_exceptions);
2686  Opts.CXXExceptions = Args.hasArg(OPT_fcxx_exceptions);
2687 
2688  // -ffixed-point
2689  Opts.FixedPoint =
2690  Args.hasFlag(OPT_ffixed_point, OPT_fno_fixed_point, /*Default=*/false) &&
2691  !Opts.CPlusPlus;
2692  Opts.PaddingOnUnsignedFixedPoint =
2693  Args.hasFlag(OPT_fpadding_on_unsigned_fixed_point,
2694  OPT_fno_padding_on_unsigned_fixed_point,
2695  /*Default=*/false) &&
2696  Opts.FixedPoint;
2697 
2698  // Handle exception personalities
2699  Arg *A = Args.getLastArg(
2700  options::OPT_fsjlj_exceptions, options::OPT_fseh_exceptions,
2701  options::OPT_fdwarf_exceptions, options::OPT_fwasm_exceptions);
2702  if (A) {
2703  const Option &Opt = A->getOption();
2704  llvm::Triple T(TargetOpts.Triple);
2705  if (T.isWindowsMSVCEnvironment())
2706  Diags.Report(diag::err_fe_invalid_exception_model)
2707  << Opt.getName() << T.str();
2708 
2709  Opts.SjLjExceptions = Opt.matches(options::OPT_fsjlj_exceptions);
2710  Opts.SEHExceptions = Opt.matches(options::OPT_fseh_exceptions);
2711  Opts.DWARFExceptions = Opt.matches(options::OPT_fdwarf_exceptions);
2712  Opts.WasmExceptions = Opt.matches(options::OPT_fwasm_exceptions);
2713  }
2714 
2715  Opts.ExternCNoUnwind = Args.hasArg(OPT_fexternc_nounwind);
2716  Opts.TraditionalCPP = Args.hasArg(OPT_traditional_cpp);
2717 
2718  Opts.RTTI = Opts.CPlusPlus && !Args.hasArg(OPT_fno_rtti);
2719  Opts.RTTIData = Opts.RTTI && !Args.hasArg(OPT_fno_rtti_data);
2720  Opts.Blocks = Args.hasArg(OPT_fblocks) || (Opts.OpenCL
2721  && Opts.OpenCLVersion == 200);
2722  Opts.BlocksRuntimeOptional = Args.hasArg(OPT_fblocks_runtime_optional);
2723  Opts.Coroutines = Opts.CPlusPlus2a || Args.hasArg(OPT_fcoroutines_ts);
2724 
2725  Opts.DoubleSquareBracketAttributes =
2726  Args.hasFlag(OPT_fdouble_square_bracket_attributes,
2727  OPT_fno_double_square_bracket_attributes,
2728  Opts.DoubleSquareBracketAttributes);
2729 
2730  Opts.CPlusPlusModules = Opts.CPlusPlus2a;
2731  Opts.ModulesTS = Args.hasArg(OPT_fmodules_ts);
2732  Opts.Modules =
2733  Args.hasArg(OPT_fmodules) || Opts.ModulesTS || Opts.CPlusPlusModules;
2734  Opts.ModulesStrictDeclUse = Args.hasArg(OPT_fmodules_strict_decluse);
2735  Opts.ModulesDeclUse =
2736  Args.hasArg(OPT_fmodules_decluse) || Opts.ModulesStrictDeclUse;
2737  // FIXME: We only need this in C++ modules / Modules TS if we might textually
2738  // enter a different module (eg, when building a header unit).
2739  Opts.ModulesLocalVisibility =
2740  Args.hasArg(OPT_fmodules_local_submodule_visibility) || Opts.ModulesTS ||
2741  Opts.CPlusPlusModules;
2742  Opts.ModulesCodegen = Args.hasArg(OPT_fmodules_codegen);
2743  Opts.ModulesDebugInfo = Args.hasArg(OPT_fmodules_debuginfo);
2744  Opts.ModulesSearchAll = Opts.Modules &&
2745  !Args.hasArg(OPT_fno_modules_search_all) &&
2746  Args.hasArg(OPT_fmodules_search_all);
2747  Opts.ModulesErrorRecovery = !Args.hasArg(OPT_fno_modules_error_recovery);
2748  Opts.ImplicitModules = !Args.hasArg(OPT_fno_implicit_modules);
2749  Opts.CharIsSigned = Opts.OpenCL || !Args.hasArg(OPT_fno_signed_char);
2750  Opts.WChar = Opts.CPlusPlus && !Args.hasArg(OPT_fno_wchar);
2751  Opts.Char8 = Args.hasFlag(OPT_fchar8__t, OPT_fno_char8__t, Opts.CPlusPlus2a);
2752  if (const Arg *A = Args.getLastArg(OPT_fwchar_type_EQ)) {
2753  Opts.WCharSize = llvm::StringSwitch<unsigned>(A->getValue())
2754  .Case("char", 1)
2755  .Case("short", 2)
2756  .Case("int", 4)
2757  .Default(0);
2758  if (Opts.WCharSize == 0)
2759  Diags.Report(diag::err_fe_invalid_wchar_type) << A->getValue();
2760  }
2761  Opts.WCharIsSigned = Args.hasFlag(OPT_fsigned_wchar, OPT_fno_signed_wchar, true);
2762  Opts.ShortEnums = Args.hasArg(OPT_fshort_enums);
2763  Opts.Freestanding = Args.hasArg(OPT_ffreestanding);
2764  Opts.NoBuiltin = Args.hasArg(OPT_fno_builtin) || Opts.Freestanding;
2765  if (!Opts.NoBuiltin)
2767  Opts.NoMathBuiltin = Args.hasArg(OPT_fno_math_builtin);
2768  Opts.RelaxedTemplateTemplateArgs =
2769  Args.hasArg(OPT_frelaxed_template_template_args);
2770  Opts.SizedDeallocation = Args.hasArg(OPT_fsized_deallocation);
2771  Opts.AlignedAllocation =
2772  Args.hasFlag(OPT_faligned_allocation, OPT_fno_aligned_allocation,
2773  Opts.AlignedAllocation);
2774  Opts.AlignedAllocationUnavailable =
2775  Opts.AlignedAllocation && Args.hasArg(OPT_aligned_alloc_unavailable);
2776  Opts.NewAlignOverride =
2777  getLastArgIntValue(Args, OPT_fnew_alignment_EQ, 0, Diags);
2778  if (Opts.NewAlignOverride && !llvm::isPowerOf2_32(Opts.NewAlignOverride)) {
2779  Arg *A = Args.getLastArg(OPT_fnew_alignment_EQ);
2780  Diags.Report(diag::err_fe_invalid_alignment) << A->getAsString(Args)
2781  << A->getValue();
2782  Opts.NewAlignOverride = 0;
2783  }
2784  Opts.ConceptsTS = Args.hasArg(OPT_fconcepts_ts);
2785  Opts.HeinousExtensions = Args.hasArg(OPT_fheinous_gnu_extensions);
2786  Opts.AccessControl = !Args.hasArg(OPT_fno_access_control);
2787  Opts.ElideConstructors = !Args.hasArg(OPT_fno_elide_constructors);
2788  Opts.MathErrno = !Opts.OpenCL && Args.hasArg(OPT_fmath_errno);
2789  Opts.InstantiationDepth =
2790  getLastArgIntValue(Args, OPT_ftemplate_depth, 1024, Diags);
2791  Opts.ArrowDepth =
2792  getLastArgIntValue(Args, OPT_foperator_arrow_depth, 256, Diags);
2793  Opts.ConstexprCallDepth =
2794  getLastArgIntValue(Args, OPT_fconstexpr_depth, 512, Diags);
2795  Opts.ConstexprStepLimit =
2796  getLastArgIntValue(Args, OPT_fconstexpr_steps, 1048576, Diags);
2797  Opts.EnableNewConstInterp =
2798  Args.hasArg(OPT_fexperimental_new_constant_interpreter);
2799  Opts.ForceNewConstInterp =
2800  Args.hasArg(OPT_fforce_experimental_new_constant_interpreter);
2801  Opts.BracketDepth = getLastArgIntValue(Args, OPT_fbracket_depth, 256, Diags);
2802  Opts.DelayedTemplateParsing = Args.hasArg(OPT_fdelayed_template_parsing);
2803  Opts.NumLargeByValueCopy =
2804  getLastArgIntValue(Args, OPT_Wlarge_by_value_copy_EQ, 0, Diags);
2805  Opts.MSBitfields = Args.hasArg(OPT_mms_bitfields);
2807  Args.getLastArgValue(OPT_fconstant_string_class);
2808  Opts.ObjCDefaultSynthProperties =
2809  !Args.hasArg(OPT_disable_objc_default_synthesize_properties);
2810  Opts.EncodeExtendedBlockSig =
2811  Args.hasArg(OPT_fencode_extended_block_signature);
2812  Opts.EmitAllDecls = Args.hasArg(OPT_femit_all_decls);
2813  Opts.PackStruct = getLastArgIntValue(Args, OPT_fpack_struct_EQ, 0, Diags);
2814  Opts.MaxTypeAlign = getLastArgIntValue(Args, OPT_fmax_type_align_EQ, 0, Diags);
2815  Opts.AlignDouble = Args.hasArg(OPT_malign_double);
2816  Opts.LongDoubleSize = Args.hasArg(OPT_mlong_double_128)
2817  ? 128
2818  : Args.hasArg(OPT_mlong_double_64) ? 64 : 0;
2819  Opts.PPCIEEELongDouble = Args.hasArg(OPT_mabi_EQ_ieeelongdouble);
2820  Opts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags);
2821  Opts.ROPI = Args.hasArg(OPT_fropi);
2822  Opts.RWPI = Args.hasArg(OPT_frwpi);
2823  Opts.PIE = Args.hasArg(OPT_pic_is_pie);
2824  Opts.Static = Args.hasArg(OPT_static_define);
2825  Opts.DumpRecordLayoutsSimple = Args.hasArg(OPT_fdump_record_layouts_simple);
2826  Opts.DumpRecordLayouts = Opts.DumpRecordLayoutsSimple
2827  || Args.hasArg(OPT_fdump_record_layouts);
2828  Opts.DumpVTableLayouts = Args.hasArg(OPT_fdump_vtable_layouts);
2829  Opts.SpellChecking = !Args.hasArg(OPT_fno_spell_checking);
2830  Opts.NoBitFieldTypeAlign = Args.hasArg(OPT_fno_bitfield_type_align);
2831  Opts.SinglePrecisionConstants = Args.hasArg(OPT_cl_single_precision_constant);
2832  Opts.FastRelaxedMath = Args.hasArg(OPT_cl_fast_relaxed_math);
2833  Opts.HexagonQdsp6Compat = Args.hasArg(OPT_mqdsp6_compat);
2834  Opts.FakeAddressSpaceMap = Args.hasArg(OPT_ffake_address_space_map);
2835  Opts.ParseUnknownAnytype = Args.hasArg(OPT_funknown_anytype);
2836  Opts.DebuggerSupport = Args.hasArg(OPT_fdebugger_support);
2837  Opts.DebuggerCastResultToId = Args.hasArg(OPT_fdebugger_cast_result_to_id);
2838  Opts.DebuggerObjCLiteral = Args.hasArg(OPT_fdebugger_objc_literal);
2839  Opts.ApplePragmaPack = Args.hasArg(OPT_fapple_pragma_pack);
2840  Opts.ModuleName = Args.getLastArgValue(OPT_fmodule_name_EQ);
2841  Opts.CurrentModule = Opts.ModuleName;
2842  Opts.AppExt = Args.hasArg(OPT_fapplication_extension);
2843  Opts.ModuleFeatures = Args.getAllArgValues(OPT_fmodule_feature);
2844  llvm::sort(Opts.ModuleFeatures);
2845  Opts.NativeHalfType |= Args.hasArg(OPT_fnative_half_type);
2846  Opts.NativeHalfArgsAndReturns |= Args.hasArg(OPT_fnative_half_arguments_and_returns);
2847  // Enable HalfArgsAndReturns if present in Args or if NativeHalfArgsAndReturns
2848  // is enabled.
2849  Opts.HalfArgsAndReturns = Args.hasArg(OPT_fallow_half_arguments_and_returns)
2850  | Opts.NativeHalfArgsAndReturns;
2851  Opts.GNUAsm = !Args.hasArg(OPT_fno_gnu_inline_asm);
2852  Opts.Cmse = Args.hasArg(OPT_mcmse); // Armv8-M Security Extensions
2853 
2854  // __declspec is enabled by default for the PS4 by the driver, and also
2855  // enabled for Microsoft Extensions or Borland Extensions, here.
2856  //
2857  // FIXME: __declspec is also currently enabled for CUDA, but isn't really a
2858  // CUDA extension. However, it is required for supporting
2859  // __clang_cuda_builtin_vars.h, which uses __declspec(property). Once that has
2860  // been rewritten in terms of something more generic, remove the Opts.CUDA
2861  // term here.
2862  Opts.DeclSpecKeyword =
2863  Args.hasFlag(OPT_fdeclspec, OPT_fno_declspec,
2864  (Opts.MicrosoftExt || Opts.Borland || Opts.CUDA));
2865 
2866  if (Arg *A = Args.getLastArg(OPT_faddress_space_map_mangling_EQ)) {
2867  switch (llvm::StringSwitch<unsigned>(A->getValue())
2868  .Case("target", LangOptions::ASMM_Target)
2869  .Case("no", LangOptions::ASMM_Off)
2870  .Case("yes", LangOptions::ASMM_On)
2871  .Default(255)) {
2872  default:
2873  Diags.Report(diag::err_drv_invalid_value)
2874  << "-faddress-space-map-mangling=" << A->getValue();
2875  break;
2877  Opts.setAddressSpaceMapMangling(LangOptions::ASMM_Target);
2878  break;
2879  case LangOptions::ASMM_On:
2880  Opts.setAddressSpaceMapMangling(LangOptions::ASMM_On);
2881  break;
2882  case LangOptions::ASMM_Off:
2883  Opts.setAddressSpaceMapMangling(LangOptions::ASMM_Off);
2884  break;
2885  }
2886  }
2887 
2888  if (Arg *A = Args.getLastArg(OPT_fms_memptr_rep_EQ)) {
2890  llvm::StringSwitch<LangOptions::PragmaMSPointersToMembersKind>(
2891  A->getValue())
2892  .Case("single",
2894  .Case("multiple",
2896  .Case("virtual",
2898  .Default(LangOptions::PPTMK_BestCase);
2899  if (InheritanceModel == LangOptions::PPTMK_BestCase)
2900  Diags.Report(diag::err_drv_invalid_value)
2901  << "-fms-memptr-rep=" << A->getValue();
2902 
2903  Opts.setMSPointerToMemberRepresentationMethod(InheritanceModel);
2904  }
2905 
2906  // Check for MS default calling conventions being specified.
2907  if (Arg *A = Args.getLastArg(OPT_fdefault_calling_conv_EQ)) {
2909  llvm::StringSwitch<LangOptions::DefaultCallingConvention>(A->getValue())
2910  .Case("cdecl", LangOptions::DCC_CDecl)
2911  .Case("fastcall", LangOptions::DCC_FastCall)
2912  .Case("stdcall", LangOptions::DCC_StdCall)
2913  .Case("vectorcall", LangOptions::DCC_VectorCall)
2914  .Case("regcall", LangOptions::DCC_RegCall)
2915  .Default(LangOptions::DCC_None);
2916  if (DefaultCC == LangOptions::DCC_None)
2917  Diags.Report(diag::err_drv_invalid_value)
2918  << "-fdefault-calling-conv=" << A->getValue();
2919 
2920  llvm::Triple T(TargetOpts.Triple);
2921  llvm::Triple::ArchType Arch = T.getArch();
2922  bool emitError = (DefaultCC == LangOptions::DCC_FastCall ||
2923  DefaultCC == LangOptions::DCC_StdCall) &&
2924  Arch != llvm::Triple::x86;
2925  emitError |= (DefaultCC == LangOptions::DCC_VectorCall ||
2926  DefaultCC == LangOptions::DCC_RegCall) &&
2927  !(Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64);
2928  if (emitError)
2929  Diags.Report(diag::err_drv_argument_not_allowed_with)
2930  << A->getSpelling() << T.getTriple();
2931  else
2932  Opts.setDefaultCallingConv(DefaultCC);
2933  }
2934 
2935  // -mrtd option
2936  if (Arg *A = Args.getLastArg(OPT_mrtd)) {
2937  if (Opts.getDefaultCallingConv() != LangOptions::DCC_None)
2938  Diags.Report(diag::err_drv_argument_not_allowed_with)
2939  << A->getSpelling() << "-fdefault-calling-conv";
2940  else {
2941  llvm::Triple T(TargetOpts.Triple);
2942  if (T.getArch() != llvm::Triple::x86)
2943  Diags.Report(diag::err_drv_argument_not_allowed_with)
2944  << A->getSpelling() << T.getTriple();
2945  else
2946  Opts.setDefaultCallingConv(LangOptions::DCC_StdCall);
2947  }
2948  }
2949 
2950  // Check if -fopenmp is specified and set default version to 4.5.
2951  Opts.OpenMP = Args.hasArg(options::OPT_fopenmp) ? 45 : 0;
2952  // Check if -fopenmp-simd is specified.
2953  bool IsSimdSpecified =
2954  Args.hasFlag(options::OPT_fopenmp_simd, options::OPT_fno_openmp_simd,
2955  /*Default=*/false);
2956  Opts.OpenMPSimd = !Opts.OpenMP && IsSimdSpecified;
2957  Opts.OpenMPUseTLS =
2958  Opts.OpenMP && !Args.hasArg(options::OPT_fnoopenmp_use_tls);
2959  Opts.OpenMPIsDevice =
2960  Opts.OpenMP && Args.hasArg(options::OPT_fopenmp_is_device);
2961  bool IsTargetSpecified =
2962  Opts.OpenMPIsDevice || Args.hasArg(options::OPT_fopenmp_targets_EQ);
2963 
2964  if (Opts.OpenMP || Opts.OpenMPSimd) {
2965  if (int Version = getLastArgIntValue(
2966  Args, OPT_fopenmp_version_EQ,
2967  (IsSimdSpecified || IsTargetSpecified) ? 45 : Opts.OpenMP, Diags))
2968  Opts.OpenMP = Version;
2969  else if (IsSimdSpecified || IsTargetSpecified)
2970  Opts.OpenMP = 45;
2971  // Provide diagnostic when a given target is not expected to be an OpenMP
2972  // device or host.
2973  if (!Opts.OpenMPIsDevice) {
2974  switch (T.getArch()) {
2975  default:
2976  break;
2977  // Add unsupported host targets here:
2978  case llvm::Triple::nvptx:
2979  case llvm::Triple::nvptx64:
2980  Diags.Report(diag::err_drv_omp_host_target_not_supported)
2981  << TargetOpts.Triple;
2982  break;
2983  }
2984  }
2985  }
2986 
2987  // Set the flag to prevent the implementation from emitting device exception
2988  // handling code for those requiring so.
2989  if ((Opts.OpenMPIsDevice && T.isNVPTX()) || Opts.OpenCLCPlusPlus) {
2990  Opts.Exceptions = 0;
2991  Opts.CXXExceptions = 0;
2992  }
2993  if (Opts.OpenMPIsDevice && T.isNVPTX()) {
2994  Opts.OpenMPCUDANumSMs =
2995  getLastArgIntValue(Args, options::OPT_fopenmp_cuda_number_of_sm_EQ,
2996  Opts.OpenMPCUDANumSMs, Diags);
2997  Opts.OpenMPCUDABlocksPerSM =
2998  getLastArgIntValue(Args, options::OPT_fopenmp_cuda_blocks_per_sm_EQ,
2999  Opts.OpenMPCUDABlocksPerSM, Diags);
3000  Opts.OpenMPCUDAReductionBufNum = getLastArgIntValue(
3001  Args, options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ,
3002  Opts.OpenMPCUDAReductionBufNum, Diags);
3003  }
3004 
3005  // Prevent auto-widening the representation of loop counters during an
3006  // OpenMP collapse clause.
3007  Opts.OpenMPOptimisticCollapse =
3008  Args.hasArg(options::OPT_fopenmp_optimistic_collapse) ? 1 : 0;
3009 
3010  // Get the OpenMP target triples if any.
3011  if (Arg *A = Args.getLastArg(options::OPT_fopenmp_targets_EQ)) {
3012 
3013  for (unsigned i = 0; i < A->getNumValues(); ++i) {
3014  llvm::Triple TT(A->getValue(i));
3015 
3016  if (TT.getArch() == llvm::Triple::UnknownArch ||
3017  !(TT.getArch() == llvm::Triple::ppc ||
3018  TT.getArch() == llvm::Triple::ppc64 ||
3019  TT.getArch() == llvm::Triple::ppc64le ||
3020  TT.getArch() == llvm::Triple::nvptx ||
3021  TT.getArch() == llvm::Triple::nvptx64 ||
3022  TT.getArch() == llvm::Triple::x86 ||
3023  TT.getArch() == llvm::Triple::x86_64))
3024  Diags.Report(diag::err_drv_invalid_omp_target) << A->getValue(i);
3025  else
3026  Opts.OMPTargetTriples.push_back(TT);
3027  }
3028  }
3029 
3030  // Get OpenMP host file path if any and report if a non existent file is
3031  // found
3032  if (Arg *A = Args.getLastArg(options::OPT_fopenmp_host_ir_file_path)) {
3033  Opts.OMPHostIRFile = A->getValue();
3034  if (!llvm::sys::fs::exists(Opts.OMPHostIRFile))
3035  Diags.Report(diag::err_drv_omp_host_ir_file_not_found)
3036  << Opts.OMPHostIRFile;
3037  }
3038 
3039  Opts.SYCLIsDevice = Args.hasArg(options::OPT_fsycl_is_device);
3040 
3041  // Set CUDA mode for OpenMP target NVPTX if specified in options
3042  Opts.OpenMPCUDAMode = Opts.OpenMPIsDevice && T.isNVPTX() &&
3043  Args.hasArg(options::OPT_fopenmp_cuda_mode);
3044 
3045  // Set CUDA mode for OpenMP target NVPTX if specified in options
3046  Opts.OpenMPCUDAForceFullRuntime =
3047  Opts.OpenMPIsDevice && T.isNVPTX() &&
3048  Args.hasArg(options::OPT_fopenmp_cuda_force_full_runtime);
3049 
3050  // Record whether the __DEPRECATED define was requested.
3051  Opts.Deprecated = Args.hasFlag(OPT_fdeprecated_macro,
3052  OPT_fno_deprecated_macro,
3053  Opts.Deprecated);
3054 
3055  // FIXME: Eliminate this dependency.
3056  unsigned Opt = getOptimizationLevel(Args, IK, Diags),
3057  OptSize = getOptimizationLevelSize(Args);
3058  Opts.Optimize = Opt != 0;
3059  Opts.OptimizeSize = OptSize != 0;
3060 
3061  // This is the __NO_INLINE__ define, which just depends on things like the
3062  // optimization level and -fno-inline, not actually whether the backend has
3063  // inlining enabled.
3064  Opts.NoInlineDefine = !Opts.Optimize;
3065  if (Arg *InlineArg = Args.getLastArg(
3066  options::OPT_finline_functions, options::OPT_finline_hint_functions,
3067  options::OPT_fno_inline_functions, options::OPT_fno_inline))
3068  if (InlineArg->getOption().matches(options::OPT_fno_inline))
3069  Opts.NoInlineDefine = true;
3070 
3071  Opts.FastMath = Args.hasArg(OPT_ffast_math) ||
3072  Args.hasArg(OPT_cl_fast_relaxed_math);
3073  Opts.FiniteMathOnly = Args.hasArg(OPT_ffinite_math_only) ||
3074  Args.hasArg(OPT_cl_finite_math_only) ||
3075  Args.hasArg(OPT_cl_fast_relaxed_math);
3076  Opts.UnsafeFPMath = Args.hasArg(OPT_menable_unsafe_fp_math) ||
3077  Args.hasArg(OPT_cl_unsafe_math_optimizations) ||
3078  Args.hasArg(OPT_cl_fast_relaxed_math);
3079 
3080  if (Arg *A = Args.getLastArg(OPT_ffp_contract)) {
3081  StringRef Val = A->getValue();
3082  if (Val == "fast")
3083  Opts.setDefaultFPContractMode(LangOptions::FPC_Fast);
3084  else if (Val == "on")
3085  Opts.setDefaultFPContractMode(LangOptions::FPC_On);
3086  else if (Val == "off")
3087  Opts.setDefaultFPContractMode(LangOptions::FPC_Off);
3088  else
3089  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
3090  }
3091 
3092  Opts.RetainCommentsFromSystemHeaders =
3093  Args.hasArg(OPT_fretain_comments_from_system_headers);
3094 
3095  unsigned SSP = getLastArgIntValue(Args, OPT_stack_protector, 0, Diags);
3096  switch (SSP) {
3097  default:
3098  Diags.Report(diag::err_drv_invalid_value)
3099  << Args.getLastArg(OPT_stack_protector)->getAsString(Args) << SSP;
3100  break;
3101  case 0: Opts.setStackProtector(LangOptions::SSPOff); break;
3102  case 1: Opts.setStackProtector(LangOptions::SSPOn); break;
3103  case 2: Opts.setStackProtector(LangOptions::SSPStrong); break;
3104  case 3: Opts.setStackProtector(LangOptions::SSPReq); break;
3105  }
3106 
3107  if (Arg *A = Args.getLastArg(OPT_ftrivial_auto_var_init)) {
3108  StringRef Val = A->getValue();
3109  if (Val == "uninitialized")
3110  Opts.setTrivialAutoVarInit(
3112  else if (Val == "zero")
3113  Opts.setTrivialAutoVarInit(LangOptions::TrivialAutoVarInitKind::Zero);
3114  else if (Val == "pattern")
3115  Opts.setTrivialAutoVarInit(LangOptions::TrivialAutoVarInitKind::Pattern);
3116  else
3117  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
3118  }
3119 
3120  // Parse -fsanitize= arguments.
3121  parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ),
3122  Diags, Opts.Sanitize);
3123  // -fsanitize-address-field-padding=N has to be a LangOpt, parse it here.
3124  Opts.SanitizeAddressFieldPadding =
3125  getLastArgIntValue(Args, OPT_fsanitize_address_field_padding, 0, Diags);
3126  Opts.SanitizerBlacklistFiles = Args.getAllArgValues(OPT_fsanitize_blacklist);
3127 
3128  // -fxray-instrument
3129  Opts.XRayInstrument =
3130  Args.hasFlag(OPT_fxray_instrument, OPT_fnoxray_instrument, false);
3131 
3132  // -fxray-always-emit-customevents
3133  Opts.XRayAlwaysEmitCustomEvents =
3134  Args.hasFlag(OPT_fxray_always_emit_customevents,
3135  OPT_fnoxray_always_emit_customevents, false);
3136 
3137  // -fxray-always-emit-typedevents
3138  Opts.XRayAlwaysEmitTypedEvents =
3139  Args.hasFlag(OPT_fxray_always_emit_typedevents,
3140  OPT_fnoxray_always_emit_customevents, false);
3141 
3142  // -fxray-{always,never}-instrument= filenames.
3144  Args.getAllArgValues(OPT_fxray_always_instrument);
3146  Args.getAllArgValues(OPT_fxray_never_instrument);
3147  Opts.XRayAttrListFiles = Args.getAllArgValues(OPT_fxray_attr_list);
3148 
3149  // -fforce-emit-vtables
3150  Opts.ForceEmitVTables = Args.hasArg(OPT_fforce_emit_vtables);
3151 
3152  // -fallow-editor-placeholders
3153  Opts.AllowEditorPlaceholders = Args.hasArg(OPT_fallow_editor_placeholders);
3154 
3155  Opts.RegisterStaticDestructors = !Args.hasArg(OPT_fno_cxx_static_destructors);
3156 
3157  if (Arg *A = Args.getLastArg(OPT_fclang_abi_compat_EQ)) {
3158  Opts.setClangABICompat(LangOptions::ClangABI::Latest);
3159 
3160  StringRef Ver = A->getValue();
3161  std::pair<StringRef, StringRef> VerParts = Ver.split('.');
3162  unsigned Major, Minor = 0;
3163 
3164  // Check the version number is valid: either 3.x (0 <= x <= 9) or
3165  // y or y.0 (4 <= y <= current version).
3166  if (!VerParts.first.startswith("0") &&
3167  !VerParts.first.getAsInteger(10, Major) &&
3168  3 <= Major && Major <= CLANG_VERSION_MAJOR &&
3169  (Major == 3 ? VerParts.second.size() == 1 &&
3170  !VerParts.second.getAsInteger(10, Minor)
3171  : VerParts.first.size() == Ver.size() ||
3172  VerParts.second == "0")) {
3173  // Got a valid version number.
3174  if (Major == 3 && Minor <= 8)
3175  Opts.setClangABICompat(LangOptions::ClangABI::Ver3_8);
3176  else if (Major <= 4)
3177  Opts.setClangABICompat(LangOptions::ClangABI::Ver4);
3178  else if (Major <= 6)
3179  Opts.setClangABICompat(LangOptions::ClangABI::Ver6);
3180  else if (Major <= 7)
3181  Opts.setClangABICompat(LangOptions::ClangABI::Ver7);
3182  else if (Major <= 9)
3183  Opts.setClangABICompat(LangOptions::ClangABI::Ver9);
3184  } else if (Ver != "latest") {
3185  Diags.Report(diag::err_drv_invalid_value)
3186  << A->getAsString(Args) << A->getValue();
3187  }
3188  }
3189 
3190  Opts.CompleteMemberPointers = Args.hasArg(OPT_fcomplete_member_pointers);
3191  Opts.BuildingPCHWithObjectFile = Args.hasArg(OPT_building_pch_with_obj);
3192 }
3193 
3195  switch (Action) {
3196  case frontend::ASTDeclList:
3197  case frontend::ASTDump:
3198  case frontend::ASTPrint:
3199  case frontend::ASTView:
3201  case frontend::EmitBC:
3202  case frontend::EmitHTML:
3203  case frontend::EmitLLVM:
3206  case frontend::EmitObj:
3207  case frontend::FixIt:
3211  case frontend::GeneratePCH:
3215  case frontend::VerifyPCH:
3217  case frontend::RewriteObjC:
3218  case frontend::RewriteTest:
3219  case frontend::RunAnalysis:
3222  return false;
3223 
3226  case frontend::DumpTokens:
3227  case frontend::InitOnly:
3233  return true;
3234  }
3235  llvm_unreachable("invalid frontend action");
3236 }
3237 
3238 static void ParsePreprocessorArgs(PreprocessorOptions &Opts, ArgList &Args,
3239  DiagnosticsEngine &Diags,
3241  Opts.ImplicitPCHInclude = Args.getLastArgValue(OPT_include_pch);
3242  Opts.PCHWithHdrStop = Args.hasArg(OPT_pch_through_hdrstop_create) ||
3243  Args.hasArg(OPT_pch_through_hdrstop_use);
3244  Opts.PCHWithHdrStopCreate = Args.hasArg(OPT_pch_through_hdrstop_create);
3245  Opts.PCHThroughHeader = Args.getLastArgValue(OPT_pch_through_header_EQ);
3246  Opts.UsePredefines = !Args.hasArg(OPT_undef);
3247  Opts.DetailedRecord = Args.hasArg(OPT_detailed_preprocessing_record);
3248  Opts.DisablePCHValidation = Args.hasArg(OPT_fno_validate_pch);
3249  Opts.AllowPCHWithCompilerErrors = Args.hasArg(OPT_fallow_pch_with_errors);
3250 
3251  Opts.DumpDeserializedPCHDecls = Args.hasArg(OPT_dump_deserialized_pch_decls);
3252  for (const auto *A : Args.filtered(OPT_error_on_deserialized_pch_decl))
3253  Opts.DeserializedPCHDeclsToErrorOn.insert(A->getValue());
3254 
3255  if (const Arg *A = Args.getLastArg(OPT_preamble_bytes_EQ)) {
3256  StringRef Value(A->getValue());
3257  size_t Comma = Value.find(',');
3258  unsigned Bytes = 0;
3259  unsigned EndOfLine = 0;
3260 
3261  if (Comma == StringRef::npos ||
3262  Value.substr(0, Comma).getAsInteger(10, Bytes) ||
3263  Value.substr(Comma + 1).getAsInteger(10, EndOfLine))
3264  Diags.Report(diag::err_drv_preamble_format);
3265  else {
3266  Opts.PrecompiledPreambleBytes.first = Bytes;
3267  Opts.PrecompiledPreambleBytes.second = (EndOfLine != 0);
3268  }
3269  }
3270 
3271  // Add the __CET__ macro if a CFProtection option is set.
3272  if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
3273  StringRef Name = A->getValue();
3274  if (Name == "branch")
3275  Opts.addMacroDef("__CET__=1");
3276  else if (Name == "return")
3277  Opts.addMacroDef("__CET__=2");
3278  else if (Name == "full")
3279  Opts.addMacroDef("__CET__=3");
3280  }
3281 
3282  // Add macros from the command line.
3283  for (const auto *A : Args.filtered(OPT_D, OPT_U)) {
3284  if (A->getOption().matches(OPT_D))
3285  Opts.addMacroDef(A->getValue());
3286  else
3287  Opts.addMacroUndef(A->getValue());
3288  }
3289 
3290  Opts.MacroIncludes = Args.getAllArgValues(OPT_imacros);
3291 
3292  // Add the ordered list of -includes.
3293  for (const auto *A : Args.filtered(OPT_include))
3294  Opts.Includes.emplace_back(A->getValue());
3295 
3296  for (const auto *A : Args.filtered(OPT_chain_include))
3297  Opts.ChainedIncludes.emplace_back(A->getValue());
3298 
3299  for (const auto *A : Args.filtered(OPT_remap_file)) {
3300  std::pair<StringRef, StringRef> Split = StringRef(A->getValue()).split(';');
3301 
3302  if (Split.second.empty()) {
3303  Diags.Report(diag::err_drv_invalid_remap_file) << A->getAsString(Args);
3304  continue;
3305  }
3306 
3307  Opts.addRemappedFile(Split.first, Split.second);
3308  }
3309 
3310  if (Arg *A = Args.getLastArg(OPT_fobjc_arc_cxxlib_EQ)) {
3311  StringRef Name = A->getValue();
3312  unsigned Library = llvm::StringSwitch<unsigned>(Name)
3313  .Case("libc++", ARCXX_libcxx)
3314  .Case("libstdc++", ARCXX_libstdcxx)
3315  .Case("none", ARCXX_nolib)
3316  .Default(~0U);
3317  if (Library == ~0U)
3318  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
3319  else
3321  }
3322 
3323  // Always avoid lexing editor placeholders when we're just running the
3324  // preprocessor as we never want to emit the
3325  // "editor placeholder in source file" error in PP only mode.
3326  if (isStrictlyPreprocessorAction(Action))
3327  Opts.LexEditorPlaceholders = false;
3328 }
3329 
3331  ArgList &Args,
3333  if (isStrictlyPreprocessorAction(Action))
3334  Opts.ShowCPP = !Args.hasArg(OPT_dM);
3335  else
3336  Opts.ShowCPP = 0;
3337 
3338  Opts.ShowComments = Args.hasArg(OPT_C);
3339  Opts.ShowLineMarkers = !Args.hasArg(OPT_P);
3340  Opts.ShowMacroComments = Args.hasArg(OPT_CC);
3341  Opts.ShowMacros = Args.hasArg(OPT_dM) || Args.hasArg(OPT_dD);
3342  Opts.ShowIncludeDirectives = Args.hasArg(OPT_dI);
3343  Opts.RewriteIncludes = Args.hasArg(OPT_frewrite_includes);
3344  Opts.RewriteImports = Args.hasArg(OPT_frewrite_imports);
3345  Opts.UseLineDirectives = Args.hasArg(OPT_fuse_line_directives);
3346 }
3347 
3348 static void ParseTargetArgs(TargetOptions &Opts, ArgList &Args,
3349  DiagnosticsEngine &Diags) {
3350  Opts.CodeModel = getCodeModel(Args, Diags);
3351  Opts.ABI = Args.getLastArgValue(OPT_target_abi);
3352  if (Arg *A = Args.getLastArg(OPT_meabi)) {
3353  StringRef Value = A->getValue();
3354  llvm::EABI EABIVersion = llvm::StringSwitch<llvm::EABI>(Value)
3355  .Case("default", llvm::EABI::Default)
3356  .Case("4", llvm::EABI::EABI4)
3357  .Case("5", llvm::EABI::EABI5)
3358  .Case("gnu", llvm::EABI::GNU)
3359  .Default(llvm::EABI::Unknown);
3360  if (EABIVersion == llvm::EABI::Unknown)
3361  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
3362  << Value;
3363  else
3364  Opts.EABIVersion = EABIVersion;
3365  }
3366  Opts.CPU = Args.getLastArgValue(OPT_target_cpu);
3367  Opts.FPMath = Args.getLastArgValue(OPT_mfpmath);
3368  Opts.FeaturesAsWritten = Args.getAllArgValues(OPT_target_feature);
3369  Opts.LinkerVersion = Args.getLastArgValue(OPT_target_linker_version);
3370  Opts.Triple = Args.getLastArgValue(OPT_triple);
3371  // Use the default target triple if unspecified.
3372  if (Opts.Triple.empty())
3373  Opts.Triple = llvm::sys::getDefaultTargetTriple();
3374  Opts.Triple = llvm::Triple::normalize(Opts.Triple);
3375  Opts.OpenCLExtensionsAsWritten = Args.getAllArgValues(OPT_cl_ext_EQ);
3376  Opts.ForceEnableInt128 = Args.hasArg(OPT_fforce_enable_int128);
3377  Opts.NVPTXUseShortPointers = Args.hasFlag(
3378  options::OPT_fcuda_short_ptr, options::OPT_fno_cuda_short_ptr, false);
3379  if (Arg *A = Args.getLastArg(options::OPT_target_sdk_version_EQ)) {
3380  llvm::VersionTuple Version;
3381  if (Version.tryParse(A->getValue()))
3382  Diags.Report(diag::err_drv_invalid_value)
3383  << A->getAsString(Args) << A->getValue();
3384  else
3385  Opts.SDKVersion = Version;
3386  }
3387 }
3388 
3390  ArrayRef<const char *> CommandLineArgs,
3391  DiagnosticsEngine &Diags) {
3392  bool Success = true;
3393 
3394  // Parse the arguments.
3395  const OptTable &Opts = getDriverOptTable();
3396  const unsigned IncludedFlagsBitmask = options::CC1Option;
3397  unsigned MissingArgIndex, MissingArgCount;
3398  InputArgList Args = Opts.ParseArgs(CommandLineArgs, MissingArgIndex,
3399  MissingArgCount, IncludedFlagsBitmask);
3400  LangOptions &LangOpts = *Res.getLangOpts();
3401 
3402  // Check for missing argument error.
3403  if (MissingArgCount) {
3404  Diags.Report(diag::err_drv_missing_argument)
3405  << Args.getArgString(MissingArgIndex) << MissingArgCount;
3406  Success = false;
3407  }
3408 
3409  // Issue errors on unknown arguments.
3410  for (const auto *A : Args.filtered(OPT_UNKNOWN)) {
3411  auto ArgString = A->getAsString(Args);
3412  std::string Nearest;
3413  if (Opts.findNearest(ArgString, Nearest, IncludedFlagsBitmask) > 1)
3414  Diags.Report(diag::err_drv_unknown_argument) << ArgString;
3415  else
3416  Diags.Report(diag::err_drv_unknown_argument_with_suggestion)
3417  << ArgString << Nearest;
3418  Success = false;
3419  }
3420 
3421  Success &= ParseAnalyzerArgs(*Res.getAnalyzerOpts(), Args, Diags);
3422  Success &= ParseMigratorArgs(Res.getMigratorOpts(), Args);
3424  if (!Res.getDependencyOutputOpts().OutputFile.empty() &&
3425  Res.getDependencyOutputOpts().Targets.empty()) {
3426  Diags.Report(diag::err_fe_dependency_file_requires_MT);
3427  Success = false;
3428  }
3429  Success &=
3430  ParseDiagnosticArgs(Res.getDiagnosticOpts(), Args, &Diags,
3431  false /*DefaultDiagColor*/, false /*DefaultShowOpt*/);
3432  ParseCommentArgs(LangOpts.CommentOpts, Args);
3434  // FIXME: We shouldn't have to pass the DashX option around here
3435  InputKind DashX = ParseFrontendArgs(Res.getFrontendOpts(), Args, Diags,
3436  LangOpts.IsHeaderFile);
3437  ParseTargetArgs(Res.getTargetOpts(), Args, Diags);
3438  Success &= ParseCodeGenArgs(Res.getCodeGenOpts(), Args, DashX, Diags,
3439  Res.getTargetOpts(), Res.getFrontendOpts());
3442  llvm::Triple T(Res.getTargetOpts().Triple);
3443  if (DashX.getFormat() == InputKind::Precompiled ||
3444  DashX.getLanguage() == Language::LLVM_IR) {
3445  // ObjCAAutoRefCount and Sanitize LangOpts are used to setup the
3446  // PassManager in BackendUtil.cpp. They need to be initializd no matter
3447  // what the input type is.
3448  if (Args.hasArg(OPT_fobjc_arc))
3449  LangOpts.ObjCAutoRefCount = 1;
3450  // PIClevel and PIELevel are needed during code generation and this should be
3451  // set regardless of the input type.
3452  LangOpts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags);
3453  LangOpts.PIE = Args.hasArg(OPT_pic_is_pie);
3454  parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ),
3455  Diags, LangOpts.Sanitize);
3456  } else {
3457  // Other LangOpts are only initialized when the input is not AST or LLVM IR.
3458  // FIXME: Should we really be calling this for an Language::Asm input?
3459  ParseLangArgs(LangOpts, Args, DashX, Res.getTargetOpts(),
3460  Res.getPreprocessorOpts(), Diags);
3462  LangOpts.ObjCExceptions = 1;
3463  if (T.isOSDarwin() && DashX.isPreprocessed()) {
3464  // Supress the darwin-specific 'stdlibcxx-not-found' diagnostic for
3465  // preprocessed input as we don't expect it to be used with -std=libc++
3466  // anyway.
3467  Res.getDiagnosticOpts().Warnings.push_back("no-stdlibcxx-not-found");
3468  }
3469  }
3470 
3471  if (Diags.isIgnored(diag::warn_profile_data_misexpect, SourceLocation()))
3472  Res.FrontendOpts.LLVMArgs.push_back("-pgo-warn-misexpect");
3473 
3474  LangOpts.FunctionAlignment =
3475  getLastArgIntValue(Args, OPT_function_alignment, 0, Diags);
3476 
3477  if (LangOpts.CUDA) {
3478  // During CUDA device-side compilation, the aux triple is the
3479  // triple used for host compilation.
3480  if (LangOpts.CUDAIsDevice)
3482  }
3483 
3484  // Set the triple of the host for OpenMP device compile.
3485  if (LangOpts.OpenMPIsDevice)
3487 
3488  // FIXME: Override value name discarding when asan or msan is used because the
3489  // backend passes depend on the name of the alloca in order to print out
3490  // names.
3491  Res.getCodeGenOpts().DiscardValueNames &=
3492  !LangOpts.Sanitize.has(SanitizerKind::Address) &&
3493  !LangOpts.Sanitize.has(SanitizerKind::KernelAddress) &&
3494  !LangOpts.Sanitize.has(SanitizerKind::Memory) &&
3495  !LangOpts.Sanitize.has(SanitizerKind::KernelMemory);
3496 
3497  ParsePreprocessorArgs(Res.getPreprocessorOpts(), Args, Diags,
3501 
3502  // Turn on -Wspir-compat for SPIR target.
3503  if (T.isSPIR())
3504  Res.getDiagnosticOpts().Warnings.push_back("spir-compat");
3505 
3506  // If sanitizer is enabled, disable OPT_ffine_grained_bitfield_accesses.
3507  if (Res.getCodeGenOpts().FineGrainedBitfieldAccesses &&
3508  !Res.getLangOpts()->Sanitize.empty()) {
3509  Res.getCodeGenOpts().FineGrainedBitfieldAccesses = false;
3510  Diags.Report(diag::warn_drv_fine_grained_bitfield_accesses_ignored);
3511  }
3512  return Success;
3513 }
3514 
3516  // Note: For QoI reasons, the things we use as a hash here should all be
3517  // dumped via the -module-info flag.
3518  using llvm::hash_code;
3519  using llvm::hash_value;
3520  using llvm::hash_combine;
3521 
3522  // Start the signature with the compiler version.
3523  // FIXME: We'd rather use something more cryptographically sound than
3524  // CityHash, but this will do for now.
3525  hash_code code = hash_value(getClangFullRepositoryVersion());
3526 
3527  // Extend the signature with the language options
3528 #define LANGOPT(Name, Bits, Default, Description) \
3529  code = hash_combine(code, LangOpts->Name);
3530 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
3531  code = hash_combine(code, static_cast<unsigned>(LangOpts->get##Name()));
3532 #define BENIGN_LANGOPT(Name, Bits, Default, Description)
3533 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
3534 #include "clang/Basic/LangOptions.def"
3535 
3536  for (StringRef Feature : LangOpts->ModuleFeatures)
3537  code = hash_combine(code, Feature);
3538 
3539  // Extend the signature with the target options.
3540  code = hash_combine(code, TargetOpts->Triple, TargetOpts->CPU,
3541  TargetOpts->ABI);
3542  for (const auto &FeatureAsWritten : TargetOpts->FeaturesAsWritten)
3543  code = hash_combine(code, FeatureAsWritten);
3544 
3545  // Extend the signature with preprocessor options.
3546  const PreprocessorOptions &ppOpts = getPreprocessorOpts();
3547  const HeaderSearchOptions &hsOpts = getHeaderSearchOpts();
3548  code = hash_combine(code, ppOpts.UsePredefines, ppOpts.DetailedRecord);
3549 
3550  for (const auto &I : getPreprocessorOpts().Macros) {
3551  // If we're supposed to ignore this macro for the purposes of modules,
3552  // don't put it into the hash.
3553  if (!hsOpts.ModulesIgnoreMacros.empty()) {
3554  // Check whether we're ignoring this macro.
3555  StringRef MacroDef = I.first;
3556  if (hsOpts.ModulesIgnoreMacros.count(
3557  llvm::CachedHashString(MacroDef.split('=').first)))
3558  continue;
3559  }
3560 
3561  code = hash_combine(code, I.first, I.second);
3562  }
3563 
3564  // Extend the signature with the sysroot and other header search options.
3565  code = hash_combine(code, hsOpts.Sysroot,
3566  hsOpts.ModuleFormat,
3567  hsOpts.UseDebugInfo,
3568  hsOpts.UseBuiltinIncludes,
3570  hsOpts.UseStandardCXXIncludes,
3571  hsOpts.UseLibcxx,
3573  code = hash_combine(code, hsOpts.ResourceDir);
3574 
3575  // Extend the signature with the user build path.
3576  code = hash_combine(code, hsOpts.ModuleUserBuildPath);
3577 
3578  // Extend the signature with the module file extensions.
3579  const FrontendOptions &frontendOpts = getFrontendOpts();
3580  for (const auto &ext : frontendOpts.ModuleFileExtensions) {
3581  code = ext->hashExtension(code);
3582  }
3583 
3584  // When compiling with -gmodules, also hash -fdebug-prefix-map as it
3585  // affects the debug info in the PCM.
3586  if (getCodeGenOpts().DebugTypeExtRefs)
3587  for (const auto &KeyValue : getCodeGenOpts().DebugPrefixMap)
3588  code = hash_combine(code, KeyValue.first, KeyValue.second);
3589 
3590  // Extend the signature with the enabled sanitizers, if at least one is
3591  // enabled. Sanitizers which cannot affect AST generation aren't hashed.
3592  SanitizerSet SanHash = LangOpts->Sanitize;
3593  SanHash.clear(getPPTransparentSanitizers());
3594  if (!SanHash.empty())
3595  code = hash_combine(code, SanHash.Mask);
3596 
3597  return llvm::APInt(64, code).toString(36, /*Signed=*/false);
3598 }
3599 
3600 template<typename IntTy>
3601 static IntTy getLastArgIntValueImpl(const ArgList &Args, OptSpecifier Id,
3602  IntTy Default,
3603  DiagnosticsEngine *Diags) {
3604  IntTy Res = Default;
3605  if (Arg *A = Args.getLastArg(Id)) {
3606  if (StringRef(A->getValue()).getAsInteger(10, Res)) {
3607  if (Diags)
3608  Diags->Report(diag::err_drv_invalid_int_value) << A->getAsString(Args)
3609  << A->getValue();
3610  }
3611  }
3612  return Res;
3613 }
3614 
3615 namespace clang {
3616 
3617 // Declared in clang/Frontend/Utils.h.
3618 int getLastArgIntValue(const ArgList &Args, OptSpecifier Id, int Default,
3619  DiagnosticsEngine *Diags) {
3620  return getLastArgIntValueImpl<int>(Args, Id, Default, Diags);
3621 }
3622 
3623 uint64_t getLastArgUInt64Value(const ArgList &Args, OptSpecifier Id,
3624  uint64_t Default,
3625  DiagnosticsEngine *Diags) {
3626  return getLastArgIntValueImpl<uint64_t>(Args, Id, Default, Diags);
3627 }
3628 
3631  DiagnosticsEngine &Diags) {
3632  return createVFSFromCompilerInvocation(CI, Diags,
3633  llvm::vfs::getRealFileSystem());
3634 }
3635 
3637  const CompilerInvocation &CI, DiagnosticsEngine &Diags,
3639  if (CI.getHeaderSearchOpts().VFSOverlayFiles.empty())
3640  return BaseFS;
3641 
3643  // earlier vfs files are on the bottom
3644  for (const auto &File : CI.getHeaderSearchOpts().VFSOverlayFiles) {
3645  llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer =
3646  Result->getBufferForFile(File);
3647  if (!Buffer) {
3648  Diags.Report(diag::err_missing_vfs_overlay_file) << File;
3649  continue;
3650  }
3651 
3652  IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS = llvm::vfs::getVFSFromYAML(
3653  std::move(Buffer.get()), /*DiagHandler*/ nullptr, File,
3654  /*DiagContext*/ nullptr, Result);
3655  if (!FS) {
3656  Diags.Report(diag::err_invalid_vfs_overlay) << File;
3657  continue;
3658  }
3659 
3660  Result = FS;
3661  }
3662  return Result;
3663 }
3664 
3665 } // 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 converting setter/getter expressions to property-dot syntx.
Enable migration to modern ObjC readonly 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)
Enable inferring NS_DESIGNATED_INITIALIZER for ObjC methods.
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.
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.
Enable migration to add conforming protocols.
bool hasDigraphs() const
hasDigraphs - Language supports digraphs.
Definition: LangStandard.h:115
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
use NS_NONATOMIC_IOSONLY for property &#39;atomic&#39; attribute
#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.
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.
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::string SplitDwarfOutput
Output filename for the split debug info, not used in the skeleton CU.
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.
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.).
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
Enable migration to modern ObjC readwrite property.
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.
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.
Enable migration to modern ObjC literals.
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.
Enable migration of ObjC methods to &#39;instancetype&#39;.
enum clang::FrontendOptions::@192 ARCMTAction
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 subscripting.
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.
Enable annotation of ObjCMethods of all kinds.
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.
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
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()
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
Enable migration to modern ObjC property.
Enable migration to NS_ENUM/NS_OPTIONS macros.
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.
prefer &#39;atomic&#39; property over &#39;nonatomic&#39;.
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
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:14579
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
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...
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
annotate property with NS_RETURNS_INNER_POINTER
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
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.