clang  16.0.0git
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"
20 #include "clang/Basic/LLVM.h"
24 #include "clang/Basic/Sanitizers.h"
27 #include "clang/Basic/Version.h"
28 #include "clang/Basic/Visibility.h"
29 #include "clang/Basic/XRayInstr.h"
30 #include "clang/Config/config.h"
31 #include "clang/Driver/Driver.h"
33 #include "clang/Driver/Options.h"
42 #include "clang/Frontend/Utils.h"
49 #include "llvm/ADT/APInt.h"
50 #include "llvm/ADT/ArrayRef.h"
51 #include "llvm/ADT/CachedHashString.h"
52 #include "llvm/ADT/DenseSet.h"
53 #include "llvm/ADT/FloatingPointMode.h"
54 #include "llvm/ADT/Hashing.h"
55 #include "llvm/ADT/None.h"
56 #include "llvm/ADT/Optional.h"
57 #include "llvm/ADT/STLExtras.h"
58 #include "llvm/ADT/SmallString.h"
59 #include "llvm/ADT/SmallVector.h"
60 #include "llvm/ADT/StringRef.h"
61 #include "llvm/ADT/StringSwitch.h"
62 #include "llvm/ADT/Triple.h"
63 #include "llvm/ADT/Twine.h"
64 #include "llvm/Config/llvm-config.h"
65 #include "llvm/IR/DebugInfoMetadata.h"
66 #include "llvm/Linker/Linker.h"
67 #include "llvm/MC/MCTargetOptions.h"
68 #include "llvm/Option/Arg.h"
69 #include "llvm/Option/ArgList.h"
70 #include "llvm/Option/OptSpecifier.h"
71 #include "llvm/Option/OptTable.h"
72 #include "llvm/Option/Option.h"
73 #include "llvm/ProfileData/InstrProfReader.h"
74 #include "llvm/Remarks/HotnessThresholdParser.h"
75 #include "llvm/Support/CodeGen.h"
76 #include "llvm/Support/Compiler.h"
77 #include "llvm/Support/Error.h"
78 #include "llvm/Support/ErrorHandling.h"
79 #include "llvm/Support/ErrorOr.h"
80 #include "llvm/Support/FileSystem.h"
81 #include "llvm/Support/HashBuilder.h"
82 #include "llvm/Support/Host.h"
83 #include "llvm/Support/MathExtras.h"
84 #include "llvm/Support/MemoryBuffer.h"
85 #include "llvm/Support/Path.h"
86 #include "llvm/Support/Process.h"
87 #include "llvm/Support/Regex.h"
88 #include "llvm/Support/VersionTuple.h"
89 #include "llvm/Support/VirtualFileSystem.h"
90 #include "llvm/Support/raw_ostream.h"
91 #include "llvm/Target/TargetOptions.h"
92 #include <algorithm>
93 #include <atomic>
94 #include <cassert>
95 #include <cstddef>
96 #include <cstring>
97 #include <ctime>
98 #include <fstream>
99 #include <limits>
100 #include <memory>
101 #include <string>
102 #include <tuple>
103 #include <type_traits>
104 #include <utility>
105 #include <vector>
106 
107 using namespace clang;
108 using namespace driver;
109 using namespace options;
110 using namespace llvm::opt;
111 
112 //===----------------------------------------------------------------------===//
113 // Helpers.
114 //===----------------------------------------------------------------------===//
115 
116 // Parse misexpect tolerance argument value.
117 // Valid option values are integers in the range [0, 100)
119  uint32_t Val;
120  if (Arg.getAsInteger(10, Val))
121  return llvm::createStringError(llvm::inconvertibleErrorCode(),
122  "Not an integer: %s", Arg.data());
123  return Val;
124 }
125 
126 //===----------------------------------------------------------------------===//
127 // Initialization.
128 //===----------------------------------------------------------------------===//
129 
131  : LangOpts(new LangOptions()), TargetOpts(new TargetOptions()),
132  DiagnosticOpts(new DiagnosticOptions()),
133  HeaderSearchOpts(new HeaderSearchOptions()),
134  PreprocessorOpts(new PreprocessorOptions()),
135  AnalyzerOpts(new AnalyzerOptions()) {}
136 
139  : LangOpts(new LangOptions(*X.getLangOpts())),
140  TargetOpts(new TargetOptions(X.getTargetOpts())),
141  DiagnosticOpts(new DiagnosticOptions(X.getDiagnosticOpts())),
142  HeaderSearchOpts(new HeaderSearchOptions(X.getHeaderSearchOpts())),
143  PreprocessorOpts(new PreprocessorOptions(X.getPreprocessorOpts())),
144  AnalyzerOpts(new AnalyzerOptions(*X.getAnalyzerOpts())) {}
145 
147  CompilerInvocationRefBase &&X) = default;
148 
151  LangOpts.swap(X.LangOpts);
152  TargetOpts.swap(X.TargetOpts);
153  DiagnosticOpts.swap(X.DiagnosticOpts);
154  HeaderSearchOpts.swap(X.HeaderSearchOpts);
155  PreprocessorOpts.swap(X.PreprocessorOpts);
156  AnalyzerOpts.swap(X.AnalyzerOpts);
157  return *this;
158 }
159 
162 
164 
165 //===----------------------------------------------------------------------===//
166 // Normalizers
167 //===----------------------------------------------------------------------===//
168 
169 #define SIMPLE_ENUM_VALUE_TABLE
170 #include "clang/Driver/Options.inc"
171 #undef SIMPLE_ENUM_VALUE_TABLE
172 
174  unsigned TableIndex,
175  const ArgList &Args,
176  DiagnosticsEngine &Diags) {
177  if (Args.hasArg(Opt))
178  return true;
179  return None;
180 }
181 
182 static Optional<bool> normalizeSimpleNegativeFlag(OptSpecifier Opt, unsigned,
183  const ArgList &Args,
184  DiagnosticsEngine &) {
185  if (Args.hasArg(Opt))
186  return false;
187  return None;
188 }
189 
190 /// The tblgen-erated code passes in a fifth parameter of an arbitrary type, but
191 /// denormalizeSimpleFlags never looks at it. Avoid bloating compile-time with
192 /// unnecessary template instantiations and just ignore it with a variadic
193 /// argument.
195  const char *Spelling,
197  Option::OptionClass, unsigned, /*T*/...) {
198  Args.push_back(Spelling);
199 }
200 
201 template <typename T> static constexpr bool is_uint64_t_convertible() {
202  return !std::is_same_v<T, uint64_t> && llvm::is_integral_or_enum<T>::value;
203 }
204 
205 template <typename T,
206  std::enable_if_t<!is_uint64_t_convertible<T>(), bool> = false>
208  return [Value](OptSpecifier Opt, unsigned, const ArgList &Args,
210  if (Args.hasArg(Opt))
211  return Value;
212  return None;
213  };
214 }
215 
216 template <typename T,
217  std::enable_if_t<is_uint64_t_convertible<T>(), bool> = false>
218 static auto makeFlagToValueNormalizer(T Value) {
220 }
221 
222 static auto makeBooleanOptionNormalizer(bool Value, bool OtherValue,
223  OptSpecifier OtherOpt) {
224  return [Value, OtherValue, OtherOpt](OptSpecifier Opt, unsigned,
225  const ArgList &Args,
227  if (const Arg *A = Args.getLastArg(Opt, OtherOpt)) {
228  return A->getOption().matches(Opt) ? Value : OtherValue;
229  }
230  return None;
231  };
232 }
233 
235  return [Value](SmallVectorImpl<const char *> &Args, const char *Spelling,
236  CompilerInvocation::StringAllocator, Option::OptionClass,
237  unsigned, bool KeyPath) {
238  if (KeyPath == Value)
239  Args.push_back(Spelling);
240  };
241 }
242 
244  const char *Spelling,
246  Option::OptionClass OptClass, unsigned,
247  const Twine &Value) {
248  switch (OptClass) {
249  case Option::SeparateClass:
250  case Option::JoinedOrSeparateClass:
251  case Option::JoinedAndSeparateClass:
252  Args.push_back(Spelling);
253  Args.push_back(SA(Value));
254  break;
255  case Option::JoinedClass:
256  case Option::CommaJoinedClass:
257  Args.push_back(SA(Twine(Spelling) + Value));
258  break;
259  default:
260  llvm_unreachable("Cannot denormalize an option with option class "
261  "incompatible with string denormalization.");
262  }
263 }
264 
265 template <typename T>
266 static void
269  Option::OptionClass OptClass, unsigned TableIndex, T Value) {
270  denormalizeStringImpl(Args, Spelling, SA, OptClass, TableIndex, Twine(Value));
271 }
272 
274 findValueTableByName(const SimpleEnumValueTable &Table, StringRef Name) {
275  for (int I = 0, E = Table.Size; I != E; ++I)
276  if (Name == Table.Table[I].Name)
277  return Table.Table[I];
278 
279  return None;
280 }
281 
283 findValueTableByValue(const SimpleEnumValueTable &Table, unsigned Value) {
284  for (int I = 0, E = Table.Size; I != E; ++I)
285  if (Value == Table.Table[I].Value)
286  return Table.Table[I];
287 
288  return None;
289 }
290 
292  unsigned TableIndex,
293  const ArgList &Args,
294  DiagnosticsEngine &Diags) {
295  assert(TableIndex < SimpleEnumValueTablesSize);
296  const SimpleEnumValueTable &Table = SimpleEnumValueTables[TableIndex];
297 
298  auto *Arg = Args.getLastArg(Opt);
299  if (!Arg)
300  return None;
301 
302  StringRef ArgValue = Arg->getValue();
303  if (auto MaybeEnumVal = findValueTableByName(Table, ArgValue))
304  return MaybeEnumVal->Value;
305 
306  Diags.Report(diag::err_drv_invalid_value)
307  << Arg->getAsString(Args) << ArgValue;
308  return None;
309 }
310 
312  const char *Spelling,
314  Option::OptionClass OptClass,
315  unsigned TableIndex, unsigned Value) {
316  assert(TableIndex < SimpleEnumValueTablesSize);
317  const SimpleEnumValueTable &Table = SimpleEnumValueTables[TableIndex];
318  if (auto MaybeEnumVal = findValueTableByValue(Table, Value)) {
319  denormalizeString(Args, Spelling, SA, OptClass, TableIndex,
320  MaybeEnumVal->Name);
321  } else {
322  llvm_unreachable("The simple enum value was not correctly defined in "
323  "the tablegen option description");
324  }
325 }
326 
327 template <typename T>
329  const char *Spelling,
331  Option::OptionClass OptClass,
332  unsigned TableIndex, T Value) {
333  return denormalizeSimpleEnumImpl(Args, Spelling, SA, OptClass, TableIndex,
334  static_cast<unsigned>(Value));
335 }
336 
337 static Optional<std::string> normalizeString(OptSpecifier Opt, int TableIndex,
338  const ArgList &Args,
339  DiagnosticsEngine &Diags) {
340  auto *Arg = Args.getLastArg(Opt);
341  if (!Arg)
342  return None;
343  return std::string(Arg->getValue());
344 }
345 
346 template <typename IntTy>
347 static Optional<IntTy> normalizeStringIntegral(OptSpecifier Opt, int,
348  const ArgList &Args,
349  DiagnosticsEngine &Diags) {
350  auto *Arg = Args.getLastArg(Opt);
351  if (!Arg)
352  return None;
353  IntTy Res;
354  if (StringRef(Arg->getValue()).getAsInteger(0, Res)) {
355  Diags.Report(diag::err_drv_invalid_int_value)
356  << Arg->getAsString(Args) << Arg->getValue();
357  return None;
358  }
359  return Res;
360 }
361 
363 normalizeStringVector(OptSpecifier Opt, int, const ArgList &Args,
364  DiagnosticsEngine &) {
365  return Args.getAllArgValues(Opt);
366 }
367 
369  const char *Spelling,
371  Option::OptionClass OptClass,
372  unsigned TableIndex,
373  const std::vector<std::string> &Values) {
374  switch (OptClass) {
375  case Option::CommaJoinedClass: {
376  std::string CommaJoinedValue;
377  if (!Values.empty()) {
378  CommaJoinedValue.append(Values.front());
379  for (const std::string &Value : llvm::drop_begin(Values, 1)) {
380  CommaJoinedValue.append(",");
381  CommaJoinedValue.append(Value);
382  }
383  }
384  denormalizeString(Args, Spelling, SA, Option::OptionClass::JoinedClass,
385  TableIndex, CommaJoinedValue);
386  break;
387  }
388  case Option::JoinedClass:
389  case Option::SeparateClass:
390  case Option::JoinedOrSeparateClass:
391  for (const std::string &Value : Values)
392  denormalizeString(Args, Spelling, SA, OptClass, TableIndex, Value);
393  break;
394  default:
395  llvm_unreachable("Cannot denormalize an option with option class "
396  "incompatible with string vector denormalization.");
397  }
398 }
399 
400 static Optional<std::string> normalizeTriple(OptSpecifier Opt, int TableIndex,
401  const ArgList &Args,
402  DiagnosticsEngine &Diags) {
403  auto *Arg = Args.getLastArg(Opt);
404  if (!Arg)
405  return None;
406  return llvm::Triple::normalize(Arg->getValue());
407 }
408 
409 template <typename T, typename U>
410 static T mergeForwardValue(T KeyPath, U Value) {
411  return static_cast<T>(Value);
412 }
413 
414 template <typename T, typename U> static T mergeMaskValue(T KeyPath, U Value) {
415  return KeyPath | Value;
416 }
417 
418 template <typename T> static T extractForwardValue(T KeyPath) {
419  return KeyPath;
420 }
421 
422 template <typename T, typename U, U Value>
423 static T extractMaskValue(T KeyPath) {
424  return ((KeyPath & Value) == Value) ? static_cast<T>(Value) : T();
425 }
426 
427 #define PARSE_OPTION_WITH_MARSHALLING( \
428  ARGS, DIAGS, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \
429  IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX) \
430  if ((FLAGS)&options::CC1Option) { \
431  KEYPATH = MERGER(KEYPATH, DEFAULT_VALUE); \
432  if (IMPLIED_CHECK) \
433  KEYPATH = MERGER(KEYPATH, IMPLIED_VALUE); \
434  if (SHOULD_PARSE) \
435  if (auto MaybeValue = NORMALIZER(OPT_##ID, TABLE_INDEX, ARGS, DIAGS)) \
436  KEYPATH = \
437  MERGER(KEYPATH, static_cast<decltype(KEYPATH)>(*MaybeValue)); \
438  }
439 
440 // Capture the extracted value as a lambda argument to avoid potential issues
441 // with lifetime extension of the reference.
442 #define GENERATE_OPTION_WITH_MARSHALLING( \
443  ARGS, STRING_ALLOCATOR, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, \
444  DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, \
445  TABLE_INDEX) \
446  if ((FLAGS)&options::CC1Option) { \
447  [&](const auto &Extracted) { \
448  if (ALWAYS_EMIT || \
449  (Extracted != \
450  static_cast<decltype(KEYPATH)>((IMPLIED_CHECK) ? (IMPLIED_VALUE) \
451  : (DEFAULT_VALUE)))) \
452  DENORMALIZER(ARGS, SPELLING, STRING_ALLOCATOR, Option::KIND##Class, \
453  TABLE_INDEX, Extracted); \
454  }(EXTRACTOR(KEYPATH)); \
455  }
456 
457 static StringRef GetInputKindName(InputKind IK);
458 
459 static bool FixupInvocation(CompilerInvocation &Invocation,
460  DiagnosticsEngine &Diags, const ArgList &Args,
461  InputKind IK) {
462  unsigned NumErrorsBefore = Diags.getNumErrors();
463 
464  LangOptions &LangOpts = *Invocation.getLangOpts();
465  CodeGenOptions &CodeGenOpts = Invocation.getCodeGenOpts();
466  TargetOptions &TargetOpts = Invocation.getTargetOpts();
467  FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
468  CodeGenOpts.XRayInstrumentFunctions = LangOpts.XRayInstrument;
469  CodeGenOpts.XRayAlwaysEmitCustomEvents = LangOpts.XRayAlwaysEmitCustomEvents;
470  CodeGenOpts.XRayAlwaysEmitTypedEvents = LangOpts.XRayAlwaysEmitTypedEvents;
471  CodeGenOpts.DisableFree = FrontendOpts.DisableFree;
472  FrontendOpts.GenerateGlobalModuleIndex = FrontendOpts.UseGlobalModuleIndex;
473  if (FrontendOpts.ShowStats)
474  CodeGenOpts.ClearASTBeforeBackend = false;
475  LangOpts.SanitizeCoverage = CodeGenOpts.hasSanitizeCoverage();
476  LangOpts.ForceEmitVTables = CodeGenOpts.ForceEmitVTables;
477  LangOpts.SpeculativeLoadHardening = CodeGenOpts.SpeculativeLoadHardening;
478  LangOpts.CurrentModule = LangOpts.ModuleName;
479 
480  llvm::Triple T(TargetOpts.Triple);
481  llvm::Triple::ArchType Arch = T.getArch();
482 
483  CodeGenOpts.CodeModel = TargetOpts.CodeModel;
484 
485  if (LangOpts.getExceptionHandling() !=
487  T.isWindowsMSVCEnvironment())
488  Diags.Report(diag::err_fe_invalid_exception_model)
489  << static_cast<unsigned>(LangOpts.getExceptionHandling()) << T.str();
490 
491  if (LangOpts.AppleKext && !LangOpts.CPlusPlus)
492  Diags.Report(diag::warn_c_kext);
493 
494  if (LangOpts.NewAlignOverride &&
495  !llvm::isPowerOf2_32(LangOpts.NewAlignOverride)) {
496  Arg *A = Args.getLastArg(OPT_fnew_alignment_EQ);
497  Diags.Report(diag::err_fe_invalid_alignment)
498  << A->getAsString(Args) << A->getValue();
499  LangOpts.NewAlignOverride = 0;
500  }
501 
502  // Prevent the user from specifying both -fsycl-is-device and -fsycl-is-host.
503  if (LangOpts.SYCLIsDevice && LangOpts.SYCLIsHost)
504  Diags.Report(diag::err_drv_argument_not_allowed_with) << "-fsycl-is-device"
505  << "-fsycl-is-host";
506 
507  if (Args.hasArg(OPT_fgnu89_inline) && LangOpts.CPlusPlus)
508  Diags.Report(diag::err_drv_argument_not_allowed_with)
509  << "-fgnu89-inline" << GetInputKindName(IK);
510 
511  if (Args.hasArg(OPT_hlsl_entrypoint) && !LangOpts.HLSL)
512  Diags.Report(diag::err_drv_argument_not_allowed_with)
513  << "-hlsl-entry" << GetInputKindName(IK);
514 
515  if (Args.hasArg(OPT_fgpu_allow_device_init) && !LangOpts.HIP)
516  Diags.Report(diag::warn_ignored_hip_only_option)
517  << Args.getLastArg(OPT_fgpu_allow_device_init)->getAsString(Args);
518 
519  if (Args.hasArg(OPT_gpu_max_threads_per_block_EQ) && !LangOpts.HIP)
520  Diags.Report(diag::warn_ignored_hip_only_option)
521  << Args.getLastArg(OPT_gpu_max_threads_per_block_EQ)->getAsString(Args);
522 
523  // When these options are used, the compiler is allowed to apply
524  // optimizations that may affect the final result. For example
525  // (x+y)+z is transformed to x+(y+z) but may not give the same
526  // final result; it's not value safe.
527  // Another example can be to simplify x/x to 1.0 but x could be 0.0, INF
528  // or NaN. Final result may then differ. An error is issued when the eval
529  // method is set with one of these options.
530  if (Args.hasArg(OPT_ffp_eval_method_EQ)) {
531  if (LangOpts.ApproxFunc)
532  Diags.Report(diag::err_incompatible_fp_eval_method_options) << 0;
533  if (LangOpts.AllowFPReassoc)
534  Diags.Report(diag::err_incompatible_fp_eval_method_options) << 1;
535  if (LangOpts.AllowRecip)
536  Diags.Report(diag::err_incompatible_fp_eval_method_options) << 2;
537  }
538 
539  // -cl-strict-aliasing needs to emit diagnostic in the case where CL > 1.0.
540  // This option should be deprecated for CL > 1.0 because
541  // this option was added for compatibility with OpenCL 1.0.
542  if (Args.getLastArg(OPT_cl_strict_aliasing) &&
543  (LangOpts.getOpenCLCompatibleVersion() > 100))
544  Diags.Report(diag::warn_option_invalid_ocl_version)
545  << LangOpts.getOpenCLVersionString()
546  << Args.getLastArg(OPT_cl_strict_aliasing)->getAsString(Args);
547 
548  if (Arg *A = Args.getLastArg(OPT_fdefault_calling_conv_EQ)) {
549  auto DefaultCC = LangOpts.getDefaultCallingConv();
550 
551  bool emitError = (DefaultCC == LangOptions::DCC_FastCall ||
552  DefaultCC == LangOptions::DCC_StdCall) &&
553  Arch != llvm::Triple::x86;
554  emitError |= (DefaultCC == LangOptions::DCC_VectorCall ||
555  DefaultCC == LangOptions::DCC_RegCall) &&
556  !T.isX86();
557  if (emitError)
558  Diags.Report(diag::err_drv_argument_not_allowed_with)
559  << A->getSpelling() << T.getTriple();
560  }
561 
562  return Diags.getNumErrors() == NumErrorsBefore;
563 }
564 
565 //===----------------------------------------------------------------------===//
566 // Deserialization (from args)
567 //===----------------------------------------------------------------------===//
568 
569 static unsigned getOptimizationLevel(ArgList &Args, InputKind IK,
570  DiagnosticsEngine &Diags) {
571  unsigned DefaultOpt = llvm::CodeGenOpt::None;
572  if ((IK.getLanguage() == Language::OpenCL ||
573  IK.getLanguage() == Language::OpenCLCXX) &&
574  !Args.hasArg(OPT_cl_opt_disable))
575  DefaultOpt = llvm::CodeGenOpt::Default;
576 
577  if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
578  if (A->getOption().matches(options::OPT_O0))
579  return llvm::CodeGenOpt::None;
580 
581  if (A->getOption().matches(options::OPT_Ofast))
582  return llvm::CodeGenOpt::Aggressive;
583 
584  assert(A->getOption().matches(options::OPT_O));
585 
586  StringRef S(A->getValue());
587  if (S == "s" || S == "z")
588  return llvm::CodeGenOpt::Default;
589 
590  if (S == "g")
591  return llvm::CodeGenOpt::Less;
592 
593  return getLastArgIntValue(Args, OPT_O, DefaultOpt, Diags);
594  }
595 
596  return DefaultOpt;
597 }
598 
599 static unsigned getOptimizationLevelSize(ArgList &Args) {
600  if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
601  if (A->getOption().matches(options::OPT_O)) {
602  switch (A->getValue()[0]) {
603  default:
604  return 0;
605  case 's':
606  return 1;
607  case 'z':
608  return 2;
609  }
610  }
611  }
612  return 0;
613 }
614 
616  llvm::opt::OptSpecifier OptSpecifier,
618  Option Opt = getDriverOptTable().getOption(OptSpecifier);
619  denormalizeSimpleFlag(Args, SA(Opt.getPrefix() + Opt.getName()), SA,
620  Option::OptionClass::FlagClass, 0);
621 }
622 
624  llvm::opt::OptSpecifier OptSpecifier,
625  const Twine &Value,
627  Option Opt = getDriverOptTable().getOption(OptSpecifier);
628  denormalizeString(Args, SA(Opt.getPrefix() + Opt.getName()), SA,
629  Opt.getKind(), 0, Value);
630 }
631 
632 // Parse command line arguments into CompilerInvocation.
633 using ParseFn =
634  llvm::function_ref<bool(CompilerInvocation &, ArrayRef<const char *>,
635  DiagnosticsEngine &, const char *)>;
636 
637 // Generate command line arguments from CompilerInvocation.
638 using GenerateFn = llvm::function_ref<void(
641 
642 // May perform round-trip of command line arguments. By default, the round-trip
643 // is enabled in assert builds. This can be overwritten at run-time via the
644 // "-round-trip-args" and "-no-round-trip-args" command line flags.
645 // During round-trip, the command line arguments are parsed into a dummy
646 // instance of CompilerInvocation which is used to generate the command line
647 // arguments again. The real CompilerInvocation instance is then created by
648 // parsing the generated arguments, not the original ones.
649 static bool RoundTrip(ParseFn Parse, GenerateFn Generate,
650  CompilerInvocation &RealInvocation,
651  CompilerInvocation &DummyInvocation,
652  ArrayRef<const char *> CommandLineArgs,
653  DiagnosticsEngine &Diags, const char *Argv0) {
654 #ifndef NDEBUG
655  bool DoRoundTripDefault = true;
656 #else
657  bool DoRoundTripDefault = false;
658 #endif
659 
660  bool DoRoundTrip = DoRoundTripDefault;
661  for (const auto *Arg : CommandLineArgs) {
662  if (Arg == StringRef("-round-trip-args"))
663  DoRoundTrip = true;
664  if (Arg == StringRef("-no-round-trip-args"))
665  DoRoundTrip = false;
666  }
667 
668  // If round-trip was not requested, simply run the parser with the real
669  // invocation diagnostics.
670  if (!DoRoundTrip)
671  return Parse(RealInvocation, CommandLineArgs, Diags, Argv0);
672 
673  // Serializes quoted (and potentially escaped) arguments.
674  auto SerializeArgs = [](ArrayRef<const char *> Args) {
675  std::string Buffer;
676  llvm::raw_string_ostream OS(Buffer);
677  for (const char *Arg : Args) {
678  llvm::sys::printArg(OS, Arg, /*Quote=*/true);
679  OS << ' ';
680  }
681  OS.flush();
682  return Buffer;
683  };
684 
685  // Setup a dummy DiagnosticsEngine.
686  DiagnosticsEngine DummyDiags(new DiagnosticIDs(), new DiagnosticOptions());
687  DummyDiags.setClient(new TextDiagnosticBuffer());
688 
689  // Run the first parse on the original arguments with the dummy invocation and
690  // diagnostics.
691  if (!Parse(DummyInvocation, CommandLineArgs, DummyDiags, Argv0) ||
692  DummyDiags.getNumWarnings() != 0) {
693  // If the first parse did not succeed, it must be user mistake (invalid
694  // command line arguments). We won't be able to generate arguments that
695  // would reproduce the same result. Let's fail again with the real
696  // invocation and diagnostics, so all side-effects of parsing are visible.
697  unsigned NumWarningsBefore = Diags.getNumWarnings();
698  auto Success = Parse(RealInvocation, CommandLineArgs, Diags, Argv0);
699  if (!Success || Diags.getNumWarnings() != NumWarningsBefore)
700  return Success;
701 
702  // Parse with original options and diagnostics succeeded even though it
703  // shouldn't have. Something is off.
704  Diags.Report(diag::err_cc1_round_trip_fail_then_ok);
705  Diags.Report(diag::note_cc1_round_trip_original)
706  << SerializeArgs(CommandLineArgs);
707  return false;
708  }
709 
710  // Setup string allocator.
711  llvm::BumpPtrAllocator Alloc;
712  llvm::StringSaver StringPool(Alloc);
713  auto SA = [&StringPool](const Twine &Arg) {
714  return StringPool.save(Arg).data();
715  };
716 
717  // Generate arguments from the dummy invocation. If Generate is the
718  // inverse of Parse, the newly generated arguments must have the same
719  // semantics as the original.
720  SmallVector<const char *> GeneratedArgs1;
721  Generate(DummyInvocation, GeneratedArgs1, SA);
722 
723  // Run the second parse, now on the generated arguments, and with the real
724  // invocation and diagnostics. The result is what we will end up using for the
725  // rest of compilation, so if Generate is not inverse of Parse, something down
726  // the line will break.
727  bool Success2 = Parse(RealInvocation, GeneratedArgs1, Diags, Argv0);
728 
729  // The first parse on original arguments succeeded, but second parse of
730  // generated arguments failed. Something must be wrong with the generator.
731  if (!Success2) {
732  Diags.Report(diag::err_cc1_round_trip_ok_then_fail);
733  Diags.Report(diag::note_cc1_round_trip_generated)
734  << 1 << SerializeArgs(GeneratedArgs1);
735  return false;
736  }
737 
738  // Generate arguments again, this time from the options we will end up using
739  // for the rest of the compilation.
740  SmallVector<const char *> GeneratedArgs2;
741  Generate(RealInvocation, GeneratedArgs2, SA);
742 
743  // Compares two lists of generated arguments.
744  auto Equal = [](const ArrayRef<const char *> A,
745  const ArrayRef<const char *> B) {
746  return std::equal(A.begin(), A.end(), B.begin(), B.end(),
747  [](const char *AElem, const char *BElem) {
748  return StringRef(AElem) == StringRef(BElem);
749  });
750  };
751 
752  // If we generated different arguments from what we assume are two
753  // semantically equivalent CompilerInvocations, the Generate function may
754  // be non-deterministic.
755  if (!Equal(GeneratedArgs1, GeneratedArgs2)) {
756  Diags.Report(diag::err_cc1_round_trip_mismatch);
757  Diags.Report(diag::note_cc1_round_trip_generated)
758  << 1 << SerializeArgs(GeneratedArgs1);
759  Diags.Report(diag::note_cc1_round_trip_generated)
760  << 2 << SerializeArgs(GeneratedArgs2);
761  return false;
762  }
763 
764  Diags.Report(diag::remark_cc1_round_trip_generated)
765  << 1 << SerializeArgs(GeneratedArgs1);
766  Diags.Report(diag::remark_cc1_round_trip_generated)
767  << 2 << SerializeArgs(GeneratedArgs2);
768 
769  return Success2;
770 }
771 
772 static void addDiagnosticArgs(ArgList &Args, OptSpecifier Group,
773  OptSpecifier GroupWithValue,
774  std::vector<std::string> &Diagnostics) {
775  for (auto *A : Args.filtered(Group)) {
776  if (A->getOption().getKind() == Option::FlagClass) {
777  // The argument is a pure flag (such as OPT_Wall or OPT_Wdeprecated). Add
778  // its name (minus the "W" or "R" at the beginning) to the diagnostics.
779  Diagnostics.push_back(
780  std::string(A->getOption().getName().drop_front(1)));
781  } else if (A->getOption().matches(GroupWithValue)) {
782  // This is -Wfoo= or -Rfoo=, where foo is the name of the diagnostic
783  // group. Add only the group name to the diagnostics.
784  Diagnostics.push_back(
785  std::string(A->getOption().getName().drop_front(1).rtrim("=-")));
786  } else {
787  // Otherwise, add its value (for OPT_W_Joined and similar).
788  Diagnostics.push_back(A->getValue());
789  }
790  }
791 }
792 
793 // Parse the Static Analyzer configuration. If \p Diags is set to nullptr,
794 // it won't verify the input.
795 static void parseAnalyzerConfigs(AnalyzerOptions &AnOpts,
796  DiagnosticsEngine *Diags);
797 
798 static void getAllNoBuiltinFuncValues(ArgList &Args,
799  std::vector<std::string> &Funcs) {
800  std::vector<std::string> Values = Args.getAllArgValues(OPT_fno_builtin_);
801  auto BuiltinEnd = llvm::partition(Values, Builtin::Context::isBuiltinFunc);
802  Funcs.insert(Funcs.end(), Values.begin(), BuiltinEnd);
803 }
804 
808  const AnalyzerOptions *AnalyzerOpts = &Opts;
809 
810 #define ANALYZER_OPTION_WITH_MARSHALLING( \
811  PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
812  HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
813  DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
814  MERGER, EXTRACTOR, TABLE_INDEX) \
815  GENERATE_OPTION_WITH_MARSHALLING( \
816  Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \
817  IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
818 #include "clang/Driver/Options.inc"
819 #undef ANALYZER_OPTION_WITH_MARSHALLING
820 
821  if (Opts.AnalysisConstraintsOpt != RangeConstraintsModel) {
822  switch (Opts.AnalysisConstraintsOpt) {
823 #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) \
824  case NAME##Model: \
825  GenerateArg(Args, OPT_analyzer_constraints, CMDFLAG, SA); \
826  break;
827 #include "clang/StaticAnalyzer/Core/Analyses.def"
828  default:
829  llvm_unreachable("Tried to generate unknown analysis constraint.");
830  }
831  }
832 
833  if (Opts.AnalysisDiagOpt != PD_HTML) {
834  switch (Opts.AnalysisDiagOpt) {
835 #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN) \
836  case PD_##NAME: \
837  GenerateArg(Args, OPT_analyzer_output, CMDFLAG, SA); \
838  break;
839 #include "clang/StaticAnalyzer/Core/Analyses.def"
840  default:
841  llvm_unreachable("Tried to generate unknown analysis diagnostic client.");
842  }
843  }
844 
845  if (Opts.AnalysisPurgeOpt != PurgeStmt) {
846  switch (Opts.AnalysisPurgeOpt) {
847 #define ANALYSIS_PURGE(NAME, CMDFLAG, DESC) \
848  case NAME: \
849  GenerateArg(Args, OPT_analyzer_purge, CMDFLAG, SA); \
850  break;
851 #include "clang/StaticAnalyzer/Core/Analyses.def"
852  default:
853  llvm_unreachable("Tried to generate unknown analysis purge mode.");
854  }
855  }
856 
857  if (Opts.InliningMode != NoRedundancy) {
858  switch (Opts.InliningMode) {
859 #define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC) \
860  case NAME: \
861  GenerateArg(Args, OPT_analyzer_inlining_mode, CMDFLAG, SA); \
862  break;
863 #include "clang/StaticAnalyzer/Core/Analyses.def"
864  default:
865  llvm_unreachable("Tried to generate unknown analysis inlining mode.");
866  }
867  }
868 
869  for (const auto &CP : Opts.CheckersAndPackages) {
870  OptSpecifier Opt =
871  CP.second ? OPT_analyzer_checker : OPT_analyzer_disable_checker;
872  GenerateArg(Args, Opt, CP.first, SA);
873  }
874 
875  AnalyzerOptions ConfigOpts;
876  parseAnalyzerConfigs(ConfigOpts, nullptr);
877 
878  for (const auto &C : Opts.Config) {
879  // Don't generate anything that came from parseAnalyzerConfigs. It would be
880  // redundant and may not be valid on the command line.
881  auto Entry = ConfigOpts.Config.find(C.getKey());
882  if (Entry != ConfigOpts.Config.end() && Entry->getValue() == C.getValue())
883  continue;
884 
885  GenerateArg(Args, OPT_analyzer_config, C.getKey() + "=" + C.getValue(), SA);
886  }
887 
888  // Nothing to generate for FullCompilerInvocation.
889 }
890 
891 static bool ParseAnalyzerArgs(AnalyzerOptions &Opts, ArgList &Args,
892  DiagnosticsEngine &Diags) {
893  unsigned NumErrorsBefore = Diags.getNumErrors();
894 
895  AnalyzerOptions *AnalyzerOpts = &Opts;
896 
897 #define ANALYZER_OPTION_WITH_MARSHALLING( \
898  PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
899  HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
900  DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
901  MERGER, EXTRACTOR, TABLE_INDEX) \
902  PARSE_OPTION_WITH_MARSHALLING( \
903  Args, Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \
904  IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
905 #include "clang/Driver/Options.inc"
906 #undef ANALYZER_OPTION_WITH_MARSHALLING
907 
908  if (Arg *A = Args.getLastArg(OPT_analyzer_constraints)) {
909  StringRef Name = A->getValue();
910  AnalysisConstraints Value = llvm::StringSwitch<AnalysisConstraints>(Name)
911 #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) \
912  .Case(CMDFLAG, NAME##Model)
913 #include "clang/StaticAnalyzer/Core/Analyses.def"
914  .Default(NumConstraints);
915  if (Value == NumConstraints) {
916  Diags.Report(diag::err_drv_invalid_value)
917  << A->getAsString(Args) << Name;
918  } else {
919 #ifndef LLVM_WITH_Z3
920  if (Value == AnalysisConstraints::Z3ConstraintsModel) {
921  Diags.Report(diag::err_analyzer_not_built_with_z3);
922  }
923 #endif // LLVM_WITH_Z3
925  }
926  }
927 
928  if (Arg *A = Args.getLastArg(OPT_analyzer_output)) {
929  StringRef Name = A->getValue();
930  AnalysisDiagClients Value = llvm::StringSwitch<AnalysisDiagClients>(Name)
931 #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN) \
932  .Case(CMDFLAG, PD_##NAME)
933 #include "clang/StaticAnalyzer/Core/Analyses.def"
934  .Default(NUM_ANALYSIS_DIAG_CLIENTS);
936  Diags.Report(diag::err_drv_invalid_value)
937  << A->getAsString(Args) << Name;
938  } else {
939  Opts.AnalysisDiagOpt = Value;
940  }
941  }
942 
943  if (Arg *A = Args.getLastArg(OPT_analyzer_purge)) {
944  StringRef Name = A->getValue();
945  AnalysisPurgeMode Value = llvm::StringSwitch<AnalysisPurgeMode>(Name)
946 #define ANALYSIS_PURGE(NAME, CMDFLAG, DESC) \
947  .Case(CMDFLAG, NAME)
948 #include "clang/StaticAnalyzer/Core/Analyses.def"
949  .Default(NumPurgeModes);
950  if (Value == NumPurgeModes) {
951  Diags.Report(diag::err_drv_invalid_value)
952  << A->getAsString(Args) << Name;
953  } else {
954  Opts.AnalysisPurgeOpt = Value;
955  }
956  }
957 
958  if (Arg *A = Args.getLastArg(OPT_analyzer_inlining_mode)) {
959  StringRef Name = A->getValue();
960  AnalysisInliningMode Value = llvm::StringSwitch<AnalysisInliningMode>(Name)
961 #define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC) \
962  .Case(CMDFLAG, NAME)
963 #include "clang/StaticAnalyzer/Core/Analyses.def"
964  .Default(NumInliningModes);
965  if (Value == NumInliningModes) {
966  Diags.Report(diag::err_drv_invalid_value)
967  << A->getAsString(Args) << Name;
968  } else {
969  Opts.InliningMode = Value;
970  }
971  }
972 
973  Opts.CheckersAndPackages.clear();
974  for (const Arg *A :
975  Args.filtered(OPT_analyzer_checker, OPT_analyzer_disable_checker)) {
976  A->claim();
977  bool IsEnabled = A->getOption().getID() == OPT_analyzer_checker;
978  // We can have a list of comma separated checker names, e.g:
979  // '-analyzer-checker=cocoa,unix'
980  StringRef CheckerAndPackageList = A->getValue();
981  SmallVector<StringRef, 16> CheckersAndPackages;
982  CheckerAndPackageList.split(CheckersAndPackages, ",");
983  for (const StringRef &CheckerOrPackage : CheckersAndPackages)
984  Opts.CheckersAndPackages.emplace_back(std::string(CheckerOrPackage),
985  IsEnabled);
986  }
987 
988  // Go through the analyzer configuration options.
989  for (const auto *A : Args.filtered(OPT_analyzer_config)) {
990 
991  // We can have a list of comma separated config names, e.g:
992  // '-analyzer-config key1=val1,key2=val2'
993  StringRef configList = A->getValue();
994  SmallVector<StringRef, 4> configVals;
995  configList.split(configVals, ",");
996  for (const auto &configVal : configVals) {
997  StringRef key, val;
998  std::tie(key, val) = configVal.split("=");
999  if (val.empty()) {
1000  Diags.Report(SourceLocation(),
1001  diag::err_analyzer_config_no_value) << configVal;
1002  break;
1003  }
1004  if (val.contains('=')) {
1005  Diags.Report(SourceLocation(),
1006  diag::err_analyzer_config_multiple_values)
1007  << configVal;
1008  break;
1009  }
1010 
1011  // TODO: Check checker options too, possibly in CheckerRegistry.
1012  // Leave unknown non-checker configs unclaimed.
1013  if (!key.contains(":") && Opts.isUnknownAnalyzerConfig(key)) {
1015  Diags.Report(diag::err_analyzer_config_unknown) << key;
1016  continue;
1017  }
1018 
1019  A->claim();
1020  Opts.Config[key] = std::string(val);
1021 
1022  // FIXME: Remove this hunk after clang-17 released.
1023  constexpr auto SingleFAM =
1024  "consider-single-element-arrays-as-flexible-array-members";
1025  if (key == SingleFAM) {
1026  Diags.Report(diag::warn_analyzer_deprecated_option_with_alternative)
1027  << SingleFAM << "clang-17"
1028  << "-fstrict-flex-arrays=<N>";
1029  }
1030  }
1031  }
1032 
1034  parseAnalyzerConfigs(Opts, &Diags);
1035  else
1036  parseAnalyzerConfigs(Opts, nullptr);
1037 
1038  llvm::raw_string_ostream os(Opts.FullCompilerInvocation);
1039  for (unsigned i = 0; i < Args.getNumInputArgStrings(); ++i) {
1040  if (i != 0)
1041  os << " ";
1042  os << Args.getArgString(i);
1043  }
1044  os.flush();
1045 
1046  return Diags.getNumErrors() == NumErrorsBefore;
1047 }
1048 
1050  StringRef OptionName, StringRef DefaultVal) {
1051  return Config.insert({OptionName, std::string(DefaultVal)}).first->second;
1052 }
1053 
1055  DiagnosticsEngine *Diags,
1056  StringRef &OptionField, StringRef Name,
1057  StringRef DefaultVal) {
1058  // String options may be known to invalid (e.g. if the expected string is a
1059  // file name, but the file does not exist), those will have to be checked in
1060  // parseConfigs.
1061  OptionField = getStringOption(Config, Name, DefaultVal);
1062 }
1063 
1065  DiagnosticsEngine *Diags,
1066  bool &OptionField, StringRef Name, bool DefaultVal) {
1067  auto PossiblyInvalidVal = llvm::StringSwitch<Optional<bool>>(
1068  getStringOption(Config, Name, (DefaultVal ? "true" : "false")))
1069  .Case("true", true)
1070  .Case("false", false)
1071  .Default(None);
1072 
1073  if (!PossiblyInvalidVal) {
1074  if (Diags)
1075  Diags->Report(diag::err_analyzer_config_invalid_input)
1076  << Name << "a boolean";
1077  else
1078  OptionField = DefaultVal;
1079  } else
1080  OptionField = *PossiblyInvalidVal;
1081 }
1082 
1084  DiagnosticsEngine *Diags,
1085  unsigned &OptionField, StringRef Name,
1086  unsigned DefaultVal) {
1087 
1088  OptionField = DefaultVal;
1089  bool HasFailed = getStringOption(Config, Name, std::to_string(DefaultVal))
1090  .getAsInteger(0, OptionField);
1091  if (Diags && HasFailed)
1092  Diags->Report(diag::err_analyzer_config_invalid_input)
1093  << Name << "an unsigned";
1094 }
1095 
1097  DiagnosticsEngine *Diags) {
1098  // TODO: There's no need to store the entire configtable, it'd be plenty
1099  // enough to store checker options.
1100 
1101 #define ANALYZER_OPTION(TYPE, NAME, CMDFLAG, DESC, DEFAULT_VAL) \
1102  initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, DEFAULT_VAL);
1103 #define ANALYZER_OPTION_DEPENDS_ON_USER_MODE(...)
1104 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.def"
1105 
1106  assert(AnOpts.UserMode == "shallow" || AnOpts.UserMode == "deep");
1107  const bool InShallowMode = AnOpts.UserMode == "shallow";
1108 
1109 #define ANALYZER_OPTION(...)
1110 #define ANALYZER_OPTION_DEPENDS_ON_USER_MODE(TYPE, NAME, CMDFLAG, DESC, \
1111  SHALLOW_VAL, DEEP_VAL) \
1112  initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, \
1113  InShallowMode ? SHALLOW_VAL : DEEP_VAL);
1114 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.def"
1115 
1116  // At this point, AnalyzerOptions is configured. Let's validate some options.
1117 
1118  // FIXME: Here we try to validate the silenced checkers or packages are valid.
1119  // The current approach only validates the registered checkers which does not
1120  // contain the runtime enabled checkers and optimally we would validate both.
1121  if (!AnOpts.RawSilencedCheckersAndPackages.empty()) {
1122  std::vector<StringRef> Checkers =
1123  AnOpts.getRegisteredCheckers(/*IncludeExperimental=*/true);
1124  std::vector<StringRef> Packages =
1125  AnOpts.getRegisteredPackages(/*IncludeExperimental=*/true);
1126 
1127  SmallVector<StringRef, 16> CheckersAndPackages;
1128  AnOpts.RawSilencedCheckersAndPackages.split(CheckersAndPackages, ";");
1129 
1130  for (const StringRef &CheckerOrPackage : CheckersAndPackages) {
1131  if (Diags) {
1132  bool IsChecker = CheckerOrPackage.contains('.');
1133  bool IsValidName = IsChecker
1134  ? llvm::is_contained(Checkers, CheckerOrPackage)
1135  : llvm::is_contained(Packages, CheckerOrPackage);
1136 
1137  if (!IsValidName)
1138  Diags->Report(diag::err_unknown_analyzer_checker_or_package)
1139  << CheckerOrPackage;
1140  }
1141 
1142  AnOpts.SilencedCheckersAndPackages.emplace_back(CheckerOrPackage);
1143  }
1144  }
1145 
1146  if (!Diags)
1147  return;
1148 
1149  if (AnOpts.ShouldTrackConditionsDebug && !AnOpts.ShouldTrackConditions)
1150  Diags->Report(diag::err_analyzer_config_invalid_input)
1151  << "track-conditions-debug" << "'track-conditions' to also be enabled";
1152 
1153  if (!AnOpts.CTUDir.empty() && !llvm::sys::fs::is_directory(AnOpts.CTUDir))
1154  Diags->Report(diag::err_analyzer_config_invalid_input) << "ctu-dir"
1155  << "a filename";
1156 
1157  if (!AnOpts.ModelPath.empty() &&
1158  !llvm::sys::fs::is_directory(AnOpts.ModelPath))
1159  Diags->Report(diag::err_analyzer_config_invalid_input) << "model-path"
1160  << "a filename";
1161 }
1162 
1163 /// Generate a remark argument. This is an inverse of `ParseOptimizationRemark`.
1164 static void
1167  OptSpecifier OptEQ, StringRef Name,
1168  const CodeGenOptions::OptRemark &Remark) {
1169  if (Remark.hasValidPattern()) {
1170  GenerateArg(Args, OptEQ, Remark.Pattern, SA);
1171  } else if (Remark.Kind == CodeGenOptions::RK_Enabled) {
1172  GenerateArg(Args, OPT_R_Joined, Name, SA);
1173  } else if (Remark.Kind == CodeGenOptions::RK_Disabled) {
1174  GenerateArg(Args, OPT_R_Joined, StringRef("no-") + Name, SA);
1175  }
1176 }
1177 
1178 /// Parse a remark command line argument. It may be missing, disabled/enabled by
1179 /// '-R[no-]group' or specified with a regular expression by '-Rgroup=regexp'.
1180 /// On top of that, it can be disabled/enabled globally by '-R[no-]everything'.
1183  OptSpecifier OptEQ, StringRef Name) {
1185 
1186  auto InitializeResultPattern = [&Diags, &Args, &Result](const Arg *A,
1187  StringRef Pattern) {
1188  Result.Pattern = Pattern.str();
1189 
1190  std::string RegexError;
1191  Result.Regex = std::make_shared<llvm::Regex>(Result.Pattern);
1192  if (!Result.Regex->isValid(RegexError)) {
1193  Diags.Report(diag::err_drv_optimization_remark_pattern)
1194  << RegexError << A->getAsString(Args);
1195  return false;
1196  }
1197 
1198  return true;
1199  };
1200 
1201  for (Arg *A : Args) {
1202  if (A->getOption().matches(OPT_R_Joined)) {
1203  StringRef Value = A->getValue();
1204 
1205  if (Value == Name)
1207  else if (Value == "everything")
1209  else if (Value.split('-') == std::make_pair(StringRef("no"), Name))
1211  else if (Value == "no-everything")
1213  else
1214  continue;
1215 
1216  if (Result.Kind == CodeGenOptions::RK_Disabled ||
1218  Result.Pattern = "";
1219  Result.Regex = nullptr;
1220  } else {
1221  InitializeResultPattern(A, ".*");
1222  }
1223  } else if (A->getOption().matches(OptEQ)) {
1225  if (!InitializeResultPattern(A, A->getValue()))
1226  return CodeGenOptions::OptRemark();
1227  }
1228  }
1229 
1230  return Result;
1231 }
1232 
1233 static bool parseDiagnosticLevelMask(StringRef FlagName,
1234  const std::vector<std::string> &Levels,
1235  DiagnosticsEngine &Diags,
1236  DiagnosticLevelMask &M) {
1237  bool Success = true;
1238  for (const auto &Level : Levels) {
1239  DiagnosticLevelMask const PM =
1240  llvm::StringSwitch<DiagnosticLevelMask>(Level)
1241  .Case("note", DiagnosticLevelMask::Note)
1242  .Case("remark", DiagnosticLevelMask::Remark)
1243  .Case("warning", DiagnosticLevelMask::Warning)
1244  .Case("error", DiagnosticLevelMask::Error)
1245  .Default(DiagnosticLevelMask::None);
1246  if (PM == DiagnosticLevelMask::None) {
1247  Success = false;
1248  Diags.Report(diag::err_drv_invalid_value) << FlagName << Level;
1249  }
1250  M = M | PM;
1251  }
1252  return Success;
1253 }
1254 
1255 static void parseSanitizerKinds(StringRef FlagName,
1256  const std::vector<std::string> &Sanitizers,
1257  DiagnosticsEngine &Diags, SanitizerSet &S) {
1258  for (const auto &Sanitizer : Sanitizers) {
1259  SanitizerMask K = parseSanitizerValue(Sanitizer, /*AllowGroups=*/false);
1260  if (K == SanitizerMask())
1261  Diags.Report(diag::err_drv_invalid_value) << FlagName << Sanitizer;
1262  else
1263  S.set(K, true);
1264  }
1265 }
1266 
1267 static SmallVector<StringRef, 4> serializeSanitizerKinds(SanitizerSet S) {
1268  SmallVector<StringRef, 4> Values;
1269  serializeSanitizerSet(S, Values);
1270  return Values;
1271 }
1272 
1273 static void parseXRayInstrumentationBundle(StringRef FlagName, StringRef Bundle,
1274  ArgList &Args, DiagnosticsEngine &D,
1275  XRayInstrSet &S) {
1276  llvm::SmallVector<StringRef, 2> BundleParts;
1277  llvm::SplitString(Bundle, BundleParts, ",");
1278  for (const auto &B : BundleParts) {
1279  auto Mask = parseXRayInstrValue(B);
1280  if (Mask == XRayInstrKind::None)
1281  if (B != "none")
1282  D.Report(diag::err_drv_invalid_value) << FlagName << Bundle;
1283  else
1284  S.Mask = Mask;
1285  else if (Mask == XRayInstrKind::All)
1286  S.Mask = Mask;
1287  else
1288  S.set(Mask, true);
1289  }
1290 }
1291 
1293  llvm::SmallVector<StringRef, 2> BundleParts;
1294  serializeXRayInstrValue(S, BundleParts);
1295  std::string Buffer;
1296  llvm::raw_string_ostream OS(Buffer);
1297  llvm::interleave(BundleParts, OS, [&OS](StringRef Part) { OS << Part; }, ",");
1298  return Buffer;
1299 }
1300 
1301 // Set the profile kind using fprofile-instrument-use-path.
1303  const Twine &ProfileName,
1304  DiagnosticsEngine &Diags) {
1305  auto ReaderOrErr = llvm::IndexedInstrProfReader::create(ProfileName);
1306  if (auto E = ReaderOrErr.takeError()) {
1307  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1308  "Error in reading profile %0: %1");
1309  llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
1310  Diags.Report(DiagID) << ProfileName.str() << EI.message();
1311  });
1312  return;
1313  }
1314  std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader =
1315  std::move(ReaderOrErr.get());
1316  // Currently memprof profiles are only added at the IR level. Mark the profile
1317  // type as IR in that case as well and the subsequent matching needs to detect
1318  // which is available (might be one or both).
1319  if (PGOReader->isIRLevelProfile() || PGOReader->hasMemoryProfile()) {
1320  if (PGOReader->hasCSIRLevelProfile())
1321  Opts.setProfileUse(CodeGenOptions::ProfileCSIRInstr);
1322  else
1323  Opts.setProfileUse(CodeGenOptions::ProfileIRInstr);
1324  } else
1325  Opts.setProfileUse(CodeGenOptions::ProfileClangInstr);
1326 }
1327 
1328 void CompilerInvocation::GenerateCodeGenArgs(
1329  const CodeGenOptions &Opts, SmallVectorImpl<const char *> &Args,
1330  StringAllocator SA, const llvm::Triple &T, const std::string &OutputFile,
1331  const LangOptions *LangOpts) {
1332  const CodeGenOptions &CodeGenOpts = Opts;
1333 
1334  if (Opts.OptimizationLevel == 0)
1335  GenerateArg(Args, OPT_O0, SA);
1336  else
1337  GenerateArg(Args, OPT_O, Twine(Opts.OptimizationLevel), SA);
1338 
1339 #define CODEGEN_OPTION_WITH_MARSHALLING( \
1340  PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
1341  HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
1342  DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
1343  MERGER, EXTRACTOR, TABLE_INDEX) \
1344  GENERATE_OPTION_WITH_MARSHALLING( \
1345  Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \
1346  IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
1347 #include "clang/Driver/Options.inc"
1348 #undef CODEGEN_OPTION_WITH_MARSHALLING
1349 
1350  if (Opts.OptimizationLevel > 0) {
1351  if (Opts.Inlining == CodeGenOptions::NormalInlining)
1352  GenerateArg(Args, OPT_finline_functions, SA);
1353  else if (Opts.Inlining == CodeGenOptions::OnlyHintInlining)
1354  GenerateArg(Args, OPT_finline_hint_functions, SA);
1355  else if (Opts.Inlining == CodeGenOptions::OnlyAlwaysInlining)
1356  GenerateArg(Args, OPT_fno_inline, SA);
1357  }
1358 
1359  if (Opts.DirectAccessExternalData && LangOpts->PICLevel != 0)
1360  GenerateArg(Args, OPT_fdirect_access_external_data, SA);
1361  else if (!Opts.DirectAccessExternalData && LangOpts->PICLevel == 0)
1362  GenerateArg(Args, OPT_fno_direct_access_external_data, SA);
1363 
1364  Optional<StringRef> DebugInfoVal;
1365  switch (Opts.DebugInfo) {
1367  DebugInfoVal = "line-tables-only";
1368  break;
1370  DebugInfoVal = "line-directives-only";
1371  break;
1373  DebugInfoVal = "constructor";
1374  break;
1376  DebugInfoVal = "limited";
1377  break;
1379  DebugInfoVal = "standalone";
1380  break;
1382  DebugInfoVal = "unused-types";
1383  break;
1384  case codegenoptions::NoDebugInfo: // default value
1385  DebugInfoVal = None;
1386  break;
1387  case codegenoptions::LocTrackingOnly: // implied value
1388  DebugInfoVal = None;
1389  break;
1390  }
1391  if (DebugInfoVal)
1392  GenerateArg(Args, OPT_debug_info_kind_EQ, *DebugInfoVal, SA);
1393 
1394  for (const auto &Prefix : Opts.DebugPrefixMap)
1395  GenerateArg(Args, OPT_fdebug_prefix_map_EQ,
1396  Prefix.first + "=" + Prefix.second, SA);
1397 
1398  for (const auto &Prefix : Opts.CoveragePrefixMap)
1399  GenerateArg(Args, OPT_fcoverage_prefix_map_EQ,
1400  Prefix.first + "=" + Prefix.second, SA);
1401 
1402  if (Opts.NewStructPathTBAA)
1403  GenerateArg(Args, OPT_new_struct_path_tbaa, SA);
1404 
1405  if (Opts.OptimizeSize == 1)
1406  GenerateArg(Args, OPT_O, "s", SA);
1407  else if (Opts.OptimizeSize == 2)
1408  GenerateArg(Args, OPT_O, "z", SA);
1409 
1410  // SimplifyLibCalls is set only in the absence of -fno-builtin and
1411  // -ffreestanding. We'll consider that when generating them.
1412 
1413  // NoBuiltinFuncs are generated by LangOptions.
1414 
1415  if (Opts.UnrollLoops && Opts.OptimizationLevel <= 1)
1416  GenerateArg(Args, OPT_funroll_loops, SA);
1417  else if (!Opts.UnrollLoops && Opts.OptimizationLevel > 1)
1418  GenerateArg(Args, OPT_fno_unroll_loops, SA);
1419 
1420  if (!Opts.BinutilsVersion.empty())
1421  GenerateArg(Args, OPT_fbinutils_version_EQ, Opts.BinutilsVersion, SA);
1422 
1423  if (Opts.DebugNameTable ==
1424  static_cast<unsigned>(llvm::DICompileUnit::DebugNameTableKind::GNU))
1425  GenerateArg(Args, OPT_ggnu_pubnames, SA);
1426  else if (Opts.DebugNameTable ==
1427  static_cast<unsigned>(
1428  llvm::DICompileUnit::DebugNameTableKind::Default))
1429  GenerateArg(Args, OPT_gpubnames, SA);
1430 
1431  auto TNK = Opts.getDebugSimpleTemplateNames();
1434  GenerateArg(Args, OPT_gsimple_template_names_EQ, "simple", SA);
1436  GenerateArg(Args, OPT_gsimple_template_names_EQ, "mangled", SA);
1437  }
1438  // ProfileInstrumentUsePath is marshalled automatically, no need to generate
1439  // it or PGOUseInstrumentor.
1440 
1441  if (Opts.TimePasses) {
1442  if (Opts.TimePassesPerRun)
1443  GenerateArg(Args, OPT_ftime_report_EQ, "per-pass-run", SA);
1444  else
1445  GenerateArg(Args, OPT_ftime_report, SA);
1446  }
1447 
1448  if (Opts.PrepareForLTO && !Opts.PrepareForThinLTO)
1449  GenerateArg(Args, OPT_flto_EQ, "full", SA);
1450 
1451  if (Opts.PrepareForThinLTO)
1452  GenerateArg(Args, OPT_flto_EQ, "thin", SA);
1453 
1454  if (!Opts.ThinLTOIndexFile.empty())
1455  GenerateArg(Args, OPT_fthinlto_index_EQ, Opts.ThinLTOIndexFile, SA);
1456 
1457  if (Opts.SaveTempsFilePrefix == OutputFile)
1458  GenerateArg(Args, OPT_save_temps_EQ, "obj", SA);
1459 
1460  StringRef MemProfileBasename("memprof.profraw");
1461  if (!Opts.MemoryProfileOutput.empty()) {
1462  if (Opts.MemoryProfileOutput == MemProfileBasename) {
1463  GenerateArg(Args, OPT_fmemory_profile, SA);
1464  } else {
1465  size_t ArgLength =
1466  Opts.MemoryProfileOutput.size() - MemProfileBasename.size();
1467  GenerateArg(Args, OPT_fmemory_profile_EQ,
1468  Opts.MemoryProfileOutput.substr(0, ArgLength), SA);
1469  }
1470  }
1471 
1472  if (memcmp(Opts.CoverageVersion, "408*", 4) != 0)
1473  GenerateArg(Args, OPT_coverage_version_EQ,
1474  StringRef(Opts.CoverageVersion, 4), SA);
1475 
1476  // TODO: Check if we need to generate arguments stored in CmdArgs. (Namely
1477  // '-fembed_bitcode', which does not map to any CompilerInvocation field and
1478  // won't be generated.)
1479 
1481  std::string InstrBundle =
1483  if (!InstrBundle.empty())
1484  GenerateArg(Args, OPT_fxray_instrumentation_bundle, InstrBundle, SA);
1485  }
1486 
1487  if (Opts.CFProtectionReturn && Opts.CFProtectionBranch)
1488  GenerateArg(Args, OPT_fcf_protection_EQ, "full", SA);
1489  else if (Opts.CFProtectionReturn)
1490  GenerateArg(Args, OPT_fcf_protection_EQ, "return", SA);
1491  else if (Opts.CFProtectionBranch)
1492  GenerateArg(Args, OPT_fcf_protection_EQ, "branch", SA);
1493 
1494  if (Opts.IBTSeal)
1495  GenerateArg(Args, OPT_mibt_seal, SA);
1496 
1497  if (Opts.FunctionReturnThunks)
1498  GenerateArg(Args, OPT_mfunction_return_EQ, "thunk-extern", SA);
1499 
1500  for (const auto &F : Opts.LinkBitcodeFiles) {
1501  bool Builtint = F.LinkFlags == llvm::Linker::Flags::LinkOnlyNeeded &&
1502  F.PropagateAttrs && F.Internalize;
1503  GenerateArg(Args,
1504  Builtint ? OPT_mlink_builtin_bitcode : OPT_mlink_bitcode_file,
1505  F.Filename, SA);
1506  }
1507 
1508  GenerateArg(
1509  Args, Opts.EmulatedTLS ? OPT_femulated_tls : OPT_fno_emulated_tls, SA);
1510 
1511  if (Opts.FPDenormalMode != llvm::DenormalMode::getIEEE())
1512  GenerateArg(Args, OPT_fdenormal_fp_math_EQ, Opts.FPDenormalMode.str(), SA);
1513 
1514  if ((Opts.FPDenormalMode != Opts.FP32DenormalMode) ||
1515  (Opts.FP32DenormalMode != llvm::DenormalMode::getIEEE()))
1516  GenerateArg(Args, OPT_fdenormal_fp_math_f32_EQ, Opts.FP32DenormalMode.str(),
1517  SA);
1518 
1519  if (Opts.StructReturnConvention == CodeGenOptions::SRCK_OnStack) {
1520  OptSpecifier Opt =
1521  T.isPPC32() ? OPT_maix_struct_return : OPT_fpcc_struct_return;
1522  GenerateArg(Args, Opt, SA);
1523  } else if (Opts.StructReturnConvention == CodeGenOptions::SRCK_InRegs) {
1524  OptSpecifier Opt =
1525  T.isPPC32() ? OPT_msvr4_struct_return : OPT_freg_struct_return;
1526  GenerateArg(Args, Opt, SA);
1527  }
1528 
1529  if (Opts.EnableAIXExtendedAltivecABI)
1530  GenerateArg(Args, OPT_mabi_EQ_vec_extabi, SA);
1531 
1532  if (!Opts.OptRecordPasses.empty())
1533  GenerateArg(Args, OPT_opt_record_passes, Opts.OptRecordPasses, SA);
1534 
1535  if (!Opts.OptRecordFormat.empty())
1536  GenerateArg(Args, OPT_opt_record_format, Opts.OptRecordFormat, SA);
1537 
1538  GenerateOptimizationRemark(Args, SA, OPT_Rpass_EQ, "pass",
1539  Opts.OptimizationRemark);
1540 
1541  GenerateOptimizationRemark(Args, SA, OPT_Rpass_missed_EQ, "pass-missed",
1543 
1544  GenerateOptimizationRemark(Args, SA, OPT_Rpass_analysis_EQ, "pass-analysis",
1546 
1547  GenerateArg(Args, OPT_fdiagnostics_hotness_threshold_EQ,
1549  ? Twine(*Opts.DiagnosticsHotnessThreshold)
1550  : "auto",
1551  SA);
1552 
1553  GenerateArg(Args, OPT_fdiagnostics_misexpect_tolerance_EQ,
1554  Twine(*Opts.DiagnosticsMisExpectTolerance), SA);
1555 
1556  for (StringRef Sanitizer : serializeSanitizerKinds(Opts.SanitizeRecover))
1557  GenerateArg(Args, OPT_fsanitize_recover_EQ, Sanitizer, SA);
1558 
1559  for (StringRef Sanitizer : serializeSanitizerKinds(Opts.SanitizeTrap))
1560  GenerateArg(Args, OPT_fsanitize_trap_EQ, Sanitizer, SA);
1561 
1562  if (!Opts.EmitVersionIdentMetadata)
1563  GenerateArg(Args, OPT_Qn, SA);
1564 
1565  switch (Opts.FiniteLoops) {
1567  break;
1568  case CodeGenOptions::FiniteLoopsKind::Always:
1569  GenerateArg(Args, OPT_ffinite_loops, SA);
1570  break;
1571  case CodeGenOptions::FiniteLoopsKind::Never:
1572  GenerateArg(Args, OPT_fno_finite_loops, SA);
1573  break;
1574  }
1575 }
1576 
1577 bool CompilerInvocation::ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args,
1578  InputKind IK,
1579  DiagnosticsEngine &Diags,
1580  const llvm::Triple &T,
1581  const std::string &OutputFile,
1582  const LangOptions &LangOptsRef) {
1583  unsigned NumErrorsBefore = Diags.getNumErrors();
1584 
1585  unsigned OptimizationLevel = getOptimizationLevel(Args, IK, Diags);
1586  // TODO: This could be done in Driver
1587  unsigned MaxOptLevel = 3;
1588  if (OptimizationLevel > MaxOptLevel) {
1589  // If the optimization level is not supported, fall back on the default
1590  // optimization
1591  Diags.Report(diag::warn_drv_optimization_value)
1592  << Args.getLastArg(OPT_O)->getAsString(Args) << "-O" << MaxOptLevel;
1593  OptimizationLevel = MaxOptLevel;
1594  }
1595  Opts.OptimizationLevel = OptimizationLevel;
1596 
1597  // The key paths of codegen options defined in Options.td start with
1598  // "CodeGenOpts.". Let's provide the expected variable name and type.
1599  CodeGenOptions &CodeGenOpts = Opts;
1600  // Some codegen options depend on language options. Let's provide the expected
1601  // variable name and type.
1602  const LangOptions *LangOpts = &LangOptsRef;
1603 
1604 #define CODEGEN_OPTION_WITH_MARSHALLING( \
1605  PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
1606  HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
1607  DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
1608  MERGER, EXTRACTOR, TABLE_INDEX) \
1609  PARSE_OPTION_WITH_MARSHALLING( \
1610  Args, Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \
1611  IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
1612 #include "clang/Driver/Options.inc"
1613 #undef CODEGEN_OPTION_WITH_MARSHALLING
1614 
1615  // At O0 we want to fully disable inlining outside of cases marked with
1616  // 'alwaysinline' that are required for correctness.
1617  if (Opts.OptimizationLevel == 0) {
1618  Opts.setInlining(CodeGenOptions::OnlyAlwaysInlining);
1619  } else if (const Arg *A = Args.getLastArg(options::OPT_finline_functions,
1620  options::OPT_finline_hint_functions,
1621  options::OPT_fno_inline_functions,
1622  options::OPT_fno_inline)) {
1623  // Explicit inlining flags can disable some or all inlining even at
1624  // optimization levels above zero.
1625  if (A->getOption().matches(options::OPT_finline_functions))
1626  Opts.setInlining(CodeGenOptions::NormalInlining);
1627  else if (A->getOption().matches(options::OPT_finline_hint_functions))
1628  Opts.setInlining(CodeGenOptions::OnlyHintInlining);
1629  else
1630  Opts.setInlining(CodeGenOptions::OnlyAlwaysInlining);
1631  } else {
1632  Opts.setInlining(CodeGenOptions::NormalInlining);
1633  }
1634 
1635  // PIC defaults to -fno-direct-access-external-data while non-PIC defaults to
1636  // -fdirect-access-external-data.
1637  Opts.DirectAccessExternalData =
1638  Args.hasArg(OPT_fdirect_access_external_data) ||
1639  (!Args.hasArg(OPT_fno_direct_access_external_data) &&
1640  LangOpts->PICLevel == 0);
1641 
1642  if (Arg *A = Args.getLastArg(OPT_debug_info_kind_EQ)) {
1643  unsigned Val =
1644  llvm::StringSwitch<unsigned>(A->getValue())
1645  .Case("line-tables-only", codegenoptions::DebugLineTablesOnly)
1646  .Case("line-directives-only", codegenoptions::DebugDirectivesOnly)
1647  .Case("constructor", codegenoptions::DebugInfoConstructor)
1648  .Case("limited", codegenoptions::LimitedDebugInfo)
1649  .Case("standalone", codegenoptions::FullDebugInfo)
1650  .Case("unused-types", codegenoptions::UnusedTypeInfo)
1651  .Default(~0U);
1652  if (Val == ~0U)
1653  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
1654  << A->getValue();
1655  else
1656  Opts.setDebugInfo(static_cast<codegenoptions::DebugInfoKind>(Val));
1657  }
1658 
1659  // If -fuse-ctor-homing is set and limited debug info is already on, then use
1660  // constructor homing, and vice versa for -fno-use-ctor-homing.
1661  if (const Arg *A =
1662  Args.getLastArg(OPT_fuse_ctor_homing, OPT_fno_use_ctor_homing)) {
1663  if (A->getOption().matches(OPT_fuse_ctor_homing) &&
1664  Opts.getDebugInfo() == codegenoptions::LimitedDebugInfo)
1665  Opts.setDebugInfo(codegenoptions::DebugInfoConstructor);
1666  if (A->getOption().matches(OPT_fno_use_ctor_homing) &&
1667  Opts.getDebugInfo() == codegenoptions::DebugInfoConstructor)
1668  Opts.setDebugInfo(codegenoptions::LimitedDebugInfo);
1669  }
1670 
1671  for (const auto &Arg : Args.getAllArgValues(OPT_fdebug_prefix_map_EQ)) {
1672  auto Split = StringRef(Arg).split('=');
1673  Opts.DebugPrefixMap.insert(
1674  {std::string(Split.first), std::string(Split.second)});
1675  }
1676 
1677  for (const auto &Arg : Args.getAllArgValues(OPT_fcoverage_prefix_map_EQ)) {
1678  auto Split = StringRef(Arg).split('=');
1679  Opts.CoveragePrefixMap.insert(
1680  {std::string(Split.first), std::string(Split.second)});
1681  }
1682 
1683  const llvm::Triple::ArchType DebugEntryValueArchs[] = {
1684  llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::aarch64,
1685  llvm::Triple::arm, llvm::Triple::armeb, llvm::Triple::mips,
1686  llvm::Triple::mipsel, llvm::Triple::mips64, llvm::Triple::mips64el};
1687 
1688  if (Opts.OptimizationLevel > 0 && Opts.hasReducedDebugInfo() &&
1689  llvm::is_contained(DebugEntryValueArchs, T.getArch()))
1690  Opts.EmitCallSiteInfo = true;
1691 
1692  if (!Opts.EnableDIPreservationVerify && Opts.DIBugsReportFilePath.size()) {
1693  Diags.Report(diag::warn_ignoring_verify_debuginfo_preserve_export)
1694  << Opts.DIBugsReportFilePath;
1695  Opts.DIBugsReportFilePath = "";
1696  }
1697 
1698  Opts.NewStructPathTBAA = !Args.hasArg(OPT_no_struct_path_tbaa) &&
1699  Args.hasArg(OPT_new_struct_path_tbaa);
1700  Opts.OptimizeSize = getOptimizationLevelSize(Args);
1701  Opts.SimplifyLibCalls = !LangOpts->NoBuiltin;
1702  if (Opts.SimplifyLibCalls)
1703  Opts.NoBuiltinFuncs = LangOpts->NoBuiltinFuncs;
1704  Opts.UnrollLoops =
1705  Args.hasFlag(OPT_funroll_loops, OPT_fno_unroll_loops,
1706  (Opts.OptimizationLevel > 1));
1707  Opts.BinutilsVersion =
1708  std::string(Args.getLastArgValue(OPT_fbinutils_version_EQ));
1709 
1710  Opts.DebugNameTable = static_cast<unsigned>(
1711  Args.hasArg(OPT_ggnu_pubnames)
1712  ? llvm::DICompileUnit::DebugNameTableKind::GNU
1713  : Args.hasArg(OPT_gpubnames)
1714  ? llvm::DICompileUnit::DebugNameTableKind::Default
1716  if (const Arg *A = Args.getLastArg(OPT_gsimple_template_names_EQ)) {
1717  StringRef Value = A->getValue();
1718  if (Value != "simple" && Value != "mangled")
1719  Diags.Report(diag::err_drv_unsupported_option_argument)
1720  << A->getSpelling() << A->getValue();
1721  Opts.setDebugSimpleTemplateNames(
1722  StringRef(A->getValue()) == "simple"
1725  }
1726 
1727  if (!Opts.ProfileInstrumentUsePath.empty())
1729 
1730  if (const Arg *A = Args.getLastArg(OPT_ftime_report, OPT_ftime_report_EQ)) {
1731  Opts.TimePasses = true;
1732 
1733  // -ftime-report= is only for new pass manager.
1734  if (A->getOption().getID() == OPT_ftime_report_EQ) {
1735  StringRef Val = A->getValue();
1736  if (Val == "per-pass")
1737  Opts.TimePassesPerRun = false;
1738  else if (Val == "per-pass-run")
1739  Opts.TimePassesPerRun = true;
1740  else
1741  Diags.Report(diag::err_drv_invalid_value)
1742  << A->getAsString(Args) << A->getValue();
1743  }
1744  }
1745 
1746  Opts.PrepareForLTO = false;
1747  Opts.PrepareForThinLTO = false;
1748  if (Arg *A = Args.getLastArg(OPT_flto_EQ)) {
1749  Opts.PrepareForLTO = true;
1750  StringRef S = A->getValue();
1751  if (S == "thin")
1752  Opts.PrepareForThinLTO = true;
1753  else if (S != "full")
1754  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << S;
1755  }
1756  if (Arg *A = Args.getLastArg(OPT_fthinlto_index_EQ)) {
1757  if (IK.getLanguage() != Language::LLVM_IR)
1758  Diags.Report(diag::err_drv_argument_only_allowed_with)
1759  << A->getAsString(Args) << "-x ir";
1760  Opts.ThinLTOIndexFile =
1761  std::string(Args.getLastArgValue(OPT_fthinlto_index_EQ));
1762  }
1763  if (Arg *A = Args.getLastArg(OPT_save_temps_EQ))
1764  Opts.SaveTempsFilePrefix =
1765  llvm::StringSwitch<std::string>(A->getValue())
1766  .Case("obj", OutputFile)
1767  .Default(llvm::sys::path::filename(OutputFile).str());
1768 
1769  // The memory profile runtime appends the pid to make this name more unique.
1770  const char *MemProfileBasename = "memprof.profraw";
1771  if (Args.hasArg(OPT_fmemory_profile_EQ)) {
1772  SmallString<128> Path(
1773  std::string(Args.getLastArgValue(OPT_fmemory_profile_EQ)));
1774  llvm::sys::path::append(Path, MemProfileBasename);
1775  Opts.MemoryProfileOutput = std::string(Path);
1776  } else if (Args.hasArg(OPT_fmemory_profile))
1777  Opts.MemoryProfileOutput = MemProfileBasename;
1778 
1779  memcpy(Opts.CoverageVersion, "408*", 4);
1780  if (Opts.EmitGcovArcs || Opts.EmitGcovNotes) {
1781  if (Args.hasArg(OPT_coverage_version_EQ)) {
1782  StringRef CoverageVersion = Args.getLastArgValue(OPT_coverage_version_EQ);
1783  if (CoverageVersion.size() != 4) {
1784  Diags.Report(diag::err_drv_invalid_value)
1785  << Args.getLastArg(OPT_coverage_version_EQ)->getAsString(Args)
1786  << CoverageVersion;
1787  } else {
1788  memcpy(Opts.CoverageVersion, CoverageVersion.data(), 4);
1789  }
1790  }
1791  }
1792  // FIXME: For backend options that are not yet recorded as function
1793  // attributes in the IR, keep track of them so we can embed them in a
1794  // separate data section and use them when building the bitcode.
1795  for (const auto &A : Args) {
1796  // Do not encode output and input.
1797  if (A->getOption().getID() == options::OPT_o ||
1798  A->getOption().getID() == options::OPT_INPUT ||
1799  A->getOption().getID() == options::OPT_x ||
1800  A->getOption().getID() == options::OPT_fembed_bitcode ||
1801  A->getOption().matches(options::OPT_W_Group))
1802  continue;
1803  ArgStringList ASL;
1804  A->render(Args, ASL);
1805  for (const auto &arg : ASL) {
1806  StringRef ArgStr(arg);
1807  Opts.CmdArgs.insert(Opts.CmdArgs.end(), ArgStr.begin(), ArgStr.end());
1808  // using \00 to separate each commandline options.
1809  Opts.CmdArgs.push_back('\0');
1810  }
1811  }
1812 
1813  auto XRayInstrBundles =
1814  Args.getAllArgValues(OPT_fxray_instrumentation_bundle);
1815  if (XRayInstrBundles.empty())
1817  else
1818  for (const auto &A : XRayInstrBundles)
1819  parseXRayInstrumentationBundle("-fxray-instrumentation-bundle=", A, Args,
1820  Diags, Opts.XRayInstrumentationBundle);
1821 
1822  if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
1823  StringRef Name = A->getValue();
1824  if (Name == "full") {
1825  Opts.CFProtectionReturn = 1;
1826  Opts.CFProtectionBranch = 1;
1827  } else if (Name == "return")
1828  Opts.CFProtectionReturn = 1;
1829  else if (Name == "branch")
1830  Opts.CFProtectionBranch = 1;
1831  else if (Name != "none")
1832  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
1833  }
1834 
1835  if (const Arg *A = Args.getLastArg(OPT_mfunction_return_EQ)) {
1836  auto Val = llvm::StringSwitch<llvm::FunctionReturnThunksKind>(A->getValue())
1837  .Case("keep", llvm::FunctionReturnThunksKind::Keep)
1838  .Case("thunk-extern", llvm::FunctionReturnThunksKind::Extern)
1840  // SystemZ might want to add support for "expolines."
1841  if (!T.isX86())
1842  Diags.Report(diag::err_drv_argument_not_allowed_with)
1843  << A->getSpelling() << T.getTriple();
1845  Diags.Report(diag::err_drv_invalid_value)
1846  << A->getAsString(Args) << A->getValue();
1847  else if (Val == llvm::FunctionReturnThunksKind::Extern &&
1848  Args.getLastArgValue(OPT_mcmodel_EQ).equals("large"))
1849  Diags.Report(diag::err_drv_argument_not_allowed_with)
1850  << A->getAsString(Args)
1851  << Args.getLastArg(OPT_mcmodel_EQ)->getAsString(Args);
1852  else
1853  Opts.FunctionReturnThunks = static_cast<unsigned>(Val);
1854  }
1855 
1856  if (Opts.PrepareForLTO && Args.hasArg(OPT_mibt_seal))
1857  Opts.IBTSeal = 1;
1858 
1859  for (auto *A :
1860  Args.filtered(OPT_mlink_bitcode_file, OPT_mlink_builtin_bitcode)) {
1862  F.Filename = A->getValue();
1863  if (A->getOption().matches(OPT_mlink_builtin_bitcode)) {
1864  F.LinkFlags = llvm::Linker::Flags::LinkOnlyNeeded;
1865  // When linking CUDA bitcode, propagate function attributes so that
1866  // e.g. libdevice gets fast-math attrs if we're building with fast-math.
1867  F.PropagateAttrs = true;
1868  F.Internalize = true;
1869  }
1870  Opts.LinkBitcodeFiles.push_back(F);
1871  }
1872 
1873  if (!Args.getLastArg(OPT_femulated_tls) &&
1874  !Args.getLastArg(OPT_fno_emulated_tls)) {
1875  Opts.EmulatedTLS = T.hasDefaultEmulatedTLS();
1876  }
1877 
1878  if (Arg *A = Args.getLastArg(OPT_ftlsmodel_EQ)) {
1879  if (T.isOSAIX()) {
1880  StringRef Name = A->getValue();
1881  if (Name != "global-dynamic")
1882  Diags.Report(diag::err_aix_unsupported_tls_model) << Name;
1883  }
1884  }
1885 
1886  if (Arg *A = Args.getLastArg(OPT_fdenormal_fp_math_EQ)) {
1887  StringRef Val = A->getValue();
1888  Opts.FPDenormalMode = llvm::parseDenormalFPAttribute(Val);
1889  Opts.FP32DenormalMode = Opts.FPDenormalMode;
1890  if (!Opts.FPDenormalMode.isValid())
1891  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
1892  }
1893 
1894  if (Arg *A = Args.getLastArg(OPT_fdenormal_fp_math_f32_EQ)) {
1895  StringRef Val = A->getValue();
1896  Opts.FP32DenormalMode = llvm::parseDenormalFPAttribute(Val);
1897  if (!Opts.FP32DenormalMode.isValid())
1898  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
1899  }
1900 
1901  // X86_32 has -fppc-struct-return and -freg-struct-return.
1902  // PPC32 has -maix-struct-return and -msvr4-struct-return.
1903  if (Arg *A =
1904  Args.getLastArg(OPT_fpcc_struct_return, OPT_freg_struct_return,
1905  OPT_maix_struct_return, OPT_msvr4_struct_return)) {
1906  // TODO: We might want to consider enabling these options on AIX in the
1907  // future.
1908  if (T.isOSAIX())
1909  Diags.Report(diag::err_drv_unsupported_opt_for_target)
1910  << A->getSpelling() << T.str();
1911 
1912  const Option &O = A->getOption();
1913  if (O.matches(OPT_fpcc_struct_return) ||
1914  O.matches(OPT_maix_struct_return)) {
1915  Opts.setStructReturnConvention(CodeGenOptions::SRCK_OnStack);
1916  } else {
1917  assert(O.matches(OPT_freg_struct_return) ||
1918  O.matches(OPT_msvr4_struct_return));
1919  Opts.setStructReturnConvention(CodeGenOptions::SRCK_InRegs);
1920  }
1921  }
1922 
1923  if (Arg *A =
1924  Args.getLastArg(OPT_mabi_EQ_vec_default, OPT_mabi_EQ_vec_extabi)) {
1925  if (!T.isOSAIX())
1926  Diags.Report(diag::err_drv_unsupported_opt_for_target)
1927  << A->getSpelling() << T.str();
1928 
1929  const Option &O = A->getOption();
1930  Opts.EnableAIXExtendedAltivecABI = O.matches(OPT_mabi_EQ_vec_extabi);
1931  }
1932 
1933  if (Arg *A = Args.getLastArg(OPT_mabi_EQ_quadword_atomics)) {
1934  if (!T.isOSAIX() || T.isPPC32())
1935  Diags.Report(diag::err_drv_unsupported_opt_for_target)
1936  << A->getSpelling() << T.str();
1937  }
1938 
1939  bool NeedLocTracking = false;
1940 
1941  if (!Opts.OptRecordFile.empty())
1942  NeedLocTracking = true;
1943 
1944  if (Arg *A = Args.getLastArg(OPT_opt_record_passes)) {
1945  Opts.OptRecordPasses = A->getValue();
1946  NeedLocTracking = true;
1947  }
1948 
1949  if (Arg *A = Args.getLastArg(OPT_opt_record_format)) {
1950  Opts.OptRecordFormat = A->getValue();
1951  NeedLocTracking = true;
1952  }
1953 
1954  Opts.OptimizationRemark =
1955  ParseOptimizationRemark(Diags, Args, OPT_Rpass_EQ, "pass");
1956 
1958  ParseOptimizationRemark(Diags, Args, OPT_Rpass_missed_EQ, "pass-missed");
1959 
1961  Diags, Args, OPT_Rpass_analysis_EQ, "pass-analysis");
1962 
1963  NeedLocTracking |= Opts.OptimizationRemark.hasValidPattern() ||
1966 
1967  bool UsingSampleProfile = !Opts.SampleProfileFile.empty();
1968  bool UsingProfile = UsingSampleProfile ||
1969  (Opts.getProfileUse() != CodeGenOptions::ProfileNone);
1970 
1971  if (Opts.DiagnosticsWithHotness && !UsingProfile &&
1972  // An IR file will contain PGO as metadata
1974  Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo)
1975  << "-fdiagnostics-show-hotness";
1976 
1977  // Parse remarks hotness threshold. Valid value is either integer or 'auto'.
1978  if (auto *arg =
1979  Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
1980  auto ResultOrErr =
1981  llvm::remarks::parseHotnessThresholdOption(arg->getValue());
1982 
1983  if (!ResultOrErr) {
1984  Diags.Report(diag::err_drv_invalid_diagnotics_hotness_threshold)
1985  << "-fdiagnostics-hotness-threshold=";
1986  } else {
1987  Opts.DiagnosticsHotnessThreshold = *ResultOrErr;
1988  if ((!Opts.DiagnosticsHotnessThreshold ||
1989  Opts.DiagnosticsHotnessThreshold.value() > 0) &&
1990  !UsingProfile)
1991  Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo)
1992  << "-fdiagnostics-hotness-threshold=";
1993  }
1994  }
1995 
1996  if (auto *arg =
1997  Args.getLastArg(options::OPT_fdiagnostics_misexpect_tolerance_EQ)) {
1998  auto ResultOrErr = parseToleranceOption(arg->getValue());
1999 
2000  if (!ResultOrErr) {
2001  Diags.Report(diag::err_drv_invalid_diagnotics_misexpect_tolerance)
2002  << "-fdiagnostics-misexpect-tolerance=";
2003  } else {
2004  Opts.DiagnosticsMisExpectTolerance = *ResultOrErr;
2005  if ((!Opts.DiagnosticsMisExpectTolerance ||
2006  Opts.DiagnosticsMisExpectTolerance.value() > 0) &&
2007  !UsingProfile)
2008  Diags.Report(diag::warn_drv_diagnostics_misexpect_requires_pgo)
2009  << "-fdiagnostics-misexpect-tolerance=";
2010  }
2011  }
2012 
2013  // If the user requested to use a sample profile for PGO, then the
2014  // backend will need to track source location information so the profile
2015  // can be incorporated into the IR.
2016  if (UsingSampleProfile)
2017  NeedLocTracking = true;
2018 
2019  if (!Opts.StackUsageOutput.empty())
2020  NeedLocTracking = true;
2021 
2022  // If the user requested a flag that requires source locations available in
2023  // the backend, make sure that the backend tracks source location information.
2024  if (NeedLocTracking && Opts.getDebugInfo() == codegenoptions::NoDebugInfo)
2025  Opts.setDebugInfo(codegenoptions::LocTrackingOnly);
2026 
2027  // Parse -fsanitize-recover= arguments.
2028  // FIXME: Report unrecoverable sanitizers incorrectly specified here.
2029  parseSanitizerKinds("-fsanitize-recover=",
2030  Args.getAllArgValues(OPT_fsanitize_recover_EQ), Diags,
2031  Opts.SanitizeRecover);
2032  parseSanitizerKinds("-fsanitize-trap=",
2033  Args.getAllArgValues(OPT_fsanitize_trap_EQ), Diags,
2034  Opts.SanitizeTrap);
2035 
2036  Opts.EmitVersionIdentMetadata = Args.hasFlag(OPT_Qy, OPT_Qn, true);
2037 
2038  if (Args.hasArg(options::OPT_ffinite_loops))
2039  Opts.FiniteLoops = CodeGenOptions::FiniteLoopsKind::Always;
2040  else if (Args.hasArg(options::OPT_fno_finite_loops))
2041  Opts.FiniteLoops = CodeGenOptions::FiniteLoopsKind::Never;
2042 
2043  Opts.EmitIEEENaNCompliantInsts = Args.hasFlag(
2044  options::OPT_mamdgpu_ieee, options::OPT_mno_amdgpu_ieee, true);
2045  if (!Opts.EmitIEEENaNCompliantInsts && !LangOptsRef.NoHonorNaNs)
2046  Diags.Report(diag::err_drv_amdgpu_ieee_without_no_honor_nans);
2047 
2048  return Diags.getNumErrors() == NumErrorsBefore;
2049 }
2050 
2051 static void
2055  const DependencyOutputOptions &DependencyOutputOpts = Opts;
2056 #define DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING( \
2057  PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
2058  HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
2059  DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
2060  MERGER, EXTRACTOR, TABLE_INDEX) \
2061  GENERATE_OPTION_WITH_MARSHALLING( \
2062  Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \
2063  IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
2064 #include "clang/Driver/Options.inc"
2065 #undef DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING
2066 
2068  GenerateArg(Args, OPT_show_includes, SA);
2069 
2070  for (const auto &Dep : Opts.ExtraDeps) {
2071  switch (Dep.second) {
2073  // Sanitizer ignorelist arguments are generated from LanguageOptions.
2074  continue;
2075  case EDK_ModuleFile:
2076  // Module file arguments are generated from FrontendOptions and
2077  // HeaderSearchOptions.
2078  continue;
2079  case EDK_ProfileList:
2080  // Profile list arguments are generated from LanguageOptions via the
2081  // marshalling infrastructure.
2082  continue;
2083  case EDK_DepFileEntry:
2084  GenerateArg(Args, OPT_fdepfile_entry, Dep.first, SA);
2085  break;
2086  }
2087  }
2088 }
2089 
2091  ArgList &Args, DiagnosticsEngine &Diags,
2093  bool ShowLineMarkers) {
2094  unsigned NumErrorsBefore = Diags.getNumErrors();
2095 
2096  DependencyOutputOptions &DependencyOutputOpts = Opts;
2097 #define DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING( \
2098  PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
2099  HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
2100  DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
2101  MERGER, EXTRACTOR, TABLE_INDEX) \
2102  PARSE_OPTION_WITH_MARSHALLING( \
2103  Args, Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \
2104  IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
2105 #include "clang/Driver/Options.inc"
2106 #undef DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING
2107 
2108  if (Args.hasArg(OPT_show_includes)) {
2109  // Writing both /showIncludes and preprocessor output to stdout
2110  // would produce interleaved output, so use stderr for /showIncludes.
2111  // This behaves the same as cl.exe, when /E, /EP or /P are passed.
2112  if (Action == frontend::PrintPreprocessedInput || !ShowLineMarkers)
2114  else
2116  } else {
2118  }
2119 
2120  // Add sanitizer ignorelists as extra dependencies.
2121  // They won't be discovered by the regular preprocessor, so
2122  // we let make / ninja to know about this implicit dependency.
2123  if (!Args.hasArg(OPT_fno_sanitize_ignorelist)) {
2124  for (const auto *A : Args.filtered(OPT_fsanitize_ignorelist_EQ)) {
2125  StringRef Val = A->getValue();
2126  if (!Val.contains('='))
2127  Opts.ExtraDeps.emplace_back(std::string(Val), EDK_SanitizeIgnorelist);
2128  }
2129  if (Opts.IncludeSystemHeaders) {
2130  for (const auto *A : Args.filtered(OPT_fsanitize_system_ignorelist_EQ)) {
2131  StringRef Val = A->getValue();
2132  if (!Val.contains('='))
2133  Opts.ExtraDeps.emplace_back(std::string(Val), EDK_SanitizeIgnorelist);
2134  }
2135  }
2136  }
2137 
2138  // -fprofile-list= dependencies.
2139  for (const auto &Filename : Args.getAllArgValues(OPT_fprofile_list_EQ))
2140  Opts.ExtraDeps.emplace_back(Filename, EDK_ProfileList);
2141 
2142  // Propagate the extra dependencies.
2143  for (const auto *A : Args.filtered(OPT_fdepfile_entry))
2144  Opts.ExtraDeps.emplace_back(A->getValue(), EDK_DepFileEntry);
2145 
2146  // Only the -fmodule-file=<file> form.
2147  for (const auto *A : Args.filtered(OPT_fmodule_file)) {
2148  StringRef Val = A->getValue();
2149  if (!Val.contains('='))
2150  Opts.ExtraDeps.emplace_back(std::string(Val), EDK_ModuleFile);
2151  }
2152 
2153  return Diags.getNumErrors() == NumErrorsBefore;
2154 }
2155 
2156 static bool parseShowColorsArgs(const ArgList &Args, bool DefaultColor) {
2157  // Color diagnostics default to auto ("on" if terminal supports) in the driver
2158  // but default to off in cc1, needing an explicit OPT_fdiagnostics_color.
2159  // Support both clang's -f[no-]color-diagnostics and gcc's
2160  // -f[no-]diagnostics-colors[=never|always|auto].
2161  enum {
2162  Colors_On,
2163  Colors_Off,
2164  Colors_Auto
2165  } ShowColors = DefaultColor ? Colors_Auto : Colors_Off;
2166  for (auto *A : Args) {
2167  const Option &O = A->getOption();
2168  if (O.matches(options::OPT_fcolor_diagnostics)) {
2169  ShowColors = Colors_On;
2170  } else if (O.matches(options::OPT_fno_color_diagnostics)) {
2171  ShowColors = Colors_Off;
2172  } else if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
2173  StringRef Value(A->getValue());
2174  if (Value == "always")
2175  ShowColors = Colors_On;
2176  else if (Value == "never")
2177  ShowColors = Colors_Off;
2178  else if (Value == "auto")
2179  ShowColors = Colors_Auto;
2180  }
2181  }
2182  return ShowColors == Colors_On ||
2183  (ShowColors == Colors_Auto &&
2184  llvm::sys::Process::StandardErrHasColors());
2185 }
2186 
2187 static bool checkVerifyPrefixes(const std::vector<std::string> &VerifyPrefixes,
2188  DiagnosticsEngine &Diags) {
2189  bool Success = true;
2190  for (const auto &Prefix : VerifyPrefixes) {
2191  // Every prefix must start with a letter and contain only alphanumeric
2192  // characters, hyphens, and underscores.
2193  auto BadChar = llvm::find_if(Prefix, [](char C) {
2194  return !isAlphanumeric(C) && C != '-' && C != '_';
2195  });
2196  if (BadChar != Prefix.end() || !isLetter(Prefix[0])) {
2197  Success = false;
2198  Diags.Report(diag::err_drv_invalid_value) << "-verify=" << Prefix;
2199  Diags.Report(diag::note_drv_verify_prefix_spelling);
2200  }
2201  }
2202  return Success;
2203 }
2204 
2208  const FileSystemOptions &FileSystemOpts = Opts;
2209 
2210 #define FILE_SYSTEM_OPTION_WITH_MARSHALLING( \
2211  PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
2212  HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
2213  DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
2214  MERGER, EXTRACTOR, TABLE_INDEX) \
2215  GENERATE_OPTION_WITH_MARSHALLING( \
2216  Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \
2217  IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
2218 #include "clang/Driver/Options.inc"
2219 #undef FILE_SYSTEM_OPTION_WITH_MARSHALLING
2220 }
2221 
2222 static bool ParseFileSystemArgs(FileSystemOptions &Opts, const ArgList &Args,
2223  DiagnosticsEngine &Diags) {
2224  unsigned NumErrorsBefore = Diags.getNumErrors();
2225 
2226  FileSystemOptions &FileSystemOpts = Opts;
2227 
2228 #define FILE_SYSTEM_OPTION_WITH_MARSHALLING( \
2229  PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
2230  HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
2231  DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
2232  MERGER, EXTRACTOR, TABLE_INDEX) \
2233  PARSE_OPTION_WITH_MARSHALLING( \
2234  Args, Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \
2235  IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
2236 #include "clang/Driver/Options.inc"
2237 #undef FILE_SYSTEM_OPTION_WITH_MARSHALLING
2238 
2239  return Diags.getNumErrors() == NumErrorsBefore;
2240 }
2241 
2242 static void GenerateMigratorArgs(const MigratorOptions &Opts,
2245  const MigratorOptions &MigratorOpts = Opts;
2246 #define MIGRATOR_OPTION_WITH_MARSHALLING( \
2247  PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
2248  HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
2249  DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
2250  MERGER, EXTRACTOR, TABLE_INDEX) \
2251  GENERATE_OPTION_WITH_MARSHALLING( \
2252  Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \
2253  IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
2254 #include "clang/Driver/Options.inc"
2255 #undef MIGRATOR_OPTION_WITH_MARSHALLING
2256 }
2257 
2258 static bool ParseMigratorArgs(MigratorOptions &Opts, const ArgList &Args,
2259  DiagnosticsEngine &Diags) {
2260  unsigned NumErrorsBefore = Diags.getNumErrors();
2261 
2262  MigratorOptions &MigratorOpts = Opts;
2263 
2264 #define MIGRATOR_OPTION_WITH_MARSHALLING( \
2265  PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
2266  HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
2267  DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
2268  MERGER, EXTRACTOR, TABLE_INDEX) \
2269  PARSE_OPTION_WITH_MARSHALLING( \
2270  Args, Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \
2271  IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
2272 #include "clang/Driver/Options.inc"
2273 #undef MIGRATOR_OPTION_WITH_MARSHALLING
2274 
2275  return Diags.getNumErrors() == NumErrorsBefore;
2276 }
2277 
2278 void CompilerInvocation::GenerateDiagnosticArgs(
2280  StringAllocator SA, bool DefaultDiagColor) {
2281  const DiagnosticOptions *DiagnosticOpts = &Opts;
2282 #define DIAG_OPTION_WITH_MARSHALLING( \
2283  PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
2284  HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
2285  DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
2286  MERGER, EXTRACTOR, TABLE_INDEX) \
2287  GENERATE_OPTION_WITH_MARSHALLING( \
2288  Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \
2289  IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
2290 #include "clang/Driver/Options.inc"
2291 #undef DIAG_OPTION_WITH_MARSHALLING
2292 
2293  if (!Opts.DiagnosticSerializationFile.empty())
2294  GenerateArg(Args, OPT_diagnostic_serialized_file,
2295  Opts.DiagnosticSerializationFile, SA);
2296 
2297  if (Opts.ShowColors)
2298  GenerateArg(Args, OPT_fcolor_diagnostics, SA);
2299 
2300  if (Opts.VerifyDiagnostics &&
2301  llvm::is_contained(Opts.VerifyPrefixes, "expected"))
2302  GenerateArg(Args, OPT_verify, SA);
2303 
2304  for (const auto &Prefix : Opts.VerifyPrefixes)
2305  if (Prefix != "expected")
2306  GenerateArg(Args, OPT_verify_EQ, Prefix, SA);
2307 
2308  DiagnosticLevelMask VIU = Opts.getVerifyIgnoreUnexpected();
2309  if (VIU == DiagnosticLevelMask::None) {
2310  // This is the default, don't generate anything.
2311  } else if (VIU == DiagnosticLevelMask::All) {
2312  GenerateArg(Args, OPT_verify_ignore_unexpected, SA);
2313  } else {
2314  if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Note) != 0)
2315  GenerateArg(Args, OPT_verify_ignore_unexpected_EQ, "note", SA);
2316  if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Remark) != 0)
2317  GenerateArg(Args, OPT_verify_ignore_unexpected_EQ, "remark", SA);
2318  if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Warning) != 0)
2319  GenerateArg(Args, OPT_verify_ignore_unexpected_EQ, "warning", SA);
2320  if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Error) != 0)
2321  GenerateArg(Args, OPT_verify_ignore_unexpected_EQ, "error", SA);
2322  }
2323 
2324  for (const auto &Warning : Opts.Warnings) {
2325  // This option is automatically generated from UndefPrefixes.
2326  if (Warning == "undef-prefix")
2327  continue;
2328  Args.push_back(SA(StringRef("-W") + Warning));
2329  }
2330 
2331  for (const auto &Remark : Opts.Remarks) {
2332  // These arguments are generated from OptimizationRemark fields of
2333  // CodeGenOptions.
2334  StringRef IgnoredRemarks[] = {"pass", "no-pass",
2335  "pass-analysis", "no-pass-analysis",
2336  "pass-missed", "no-pass-missed"};
2337  if (llvm::is_contained(IgnoredRemarks, Remark))
2338  continue;
2339 
2340  Args.push_back(SA(StringRef("-R") + Remark));
2341  }
2342 }
2343 
2344 std::unique_ptr<DiagnosticOptions>
2346  auto DiagOpts = std::make_unique<DiagnosticOptions>();
2347  unsigned MissingArgIndex, MissingArgCount;
2348  InputArgList Args = getDriverOptTable().ParseArgs(
2349  Argv.slice(1), MissingArgIndex, MissingArgCount);
2350  // We ignore MissingArgCount and the return value of ParseDiagnosticArgs.
2351  // Any errors that would be diagnosed here will also be diagnosed later,
2352  // when the DiagnosticsEngine actually exists.
2353  (void)ParseDiagnosticArgs(*DiagOpts, Args);
2354  return DiagOpts;
2355 }
2356 
2357 bool clang::ParseDiagnosticArgs(DiagnosticOptions &Opts, ArgList &Args,
2358  DiagnosticsEngine *Diags,
2359  bool DefaultDiagColor) {
2360  Optional<DiagnosticsEngine> IgnoringDiags;
2361  if (!Diags) {
2362  IgnoringDiags.emplace(new DiagnosticIDs(), new DiagnosticOptions(),
2363  new IgnoringDiagConsumer());
2364  Diags = &*IgnoringDiags;
2365  }
2366 
2367  unsigned NumErrorsBefore = Diags->getNumErrors();
2368 
2369  // The key paths of diagnostic options defined in Options.td start with
2370  // "DiagnosticOpts->". Let's provide the expected variable name and type.
2371  DiagnosticOptions *DiagnosticOpts = &Opts;
2372 
2373 #define DIAG_OPTION_WITH_MARSHALLING( \
2374  PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
2375  HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
2376  DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
2377  MERGER, EXTRACTOR, TABLE_INDEX) \
2378  PARSE_OPTION_WITH_MARSHALLING( \
2379  Args, *Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \
2380  IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
2381 #include "clang/Driver/Options.inc"
2382 #undef DIAG_OPTION_WITH_MARSHALLING
2383 
2384  llvm::sys::Process::UseANSIEscapeCodes(Opts.UseANSIEscapeCodes);
2385 
2386  if (Arg *A =
2387  Args.getLastArg(OPT_diagnostic_serialized_file, OPT__serialize_diags))
2388  Opts.DiagnosticSerializationFile = A->getValue();
2389  Opts.ShowColors = parseShowColorsArgs(Args, DefaultDiagColor);
2390 
2391  Opts.VerifyDiagnostics = Args.hasArg(OPT_verify) || Args.hasArg(OPT_verify_EQ);
2392  Opts.VerifyPrefixes = Args.getAllArgValues(OPT_verify_EQ);
2393  if (Args.hasArg(OPT_verify))
2394  Opts.VerifyPrefixes.push_back("expected");
2395  // Keep VerifyPrefixes in its original order for the sake of diagnostics, and
2396  // then sort it to prepare for fast lookup using std::binary_search.
2397  if (!checkVerifyPrefixes(Opts.VerifyPrefixes, *Diags))
2398  Opts.VerifyDiagnostics = false;
2399  else
2400  llvm::sort(Opts.VerifyPrefixes);
2403  "-verify-ignore-unexpected=",
2404  Args.getAllArgValues(OPT_verify_ignore_unexpected_EQ), *Diags, DiagMask);
2405  if (Args.hasArg(OPT_verify_ignore_unexpected))
2406  DiagMask = DiagnosticLevelMask::All;
2407  Opts.setVerifyIgnoreUnexpected(DiagMask);
2408  if (Opts.TabStop == 0 || Opts.TabStop > DiagnosticOptions::MaxTabStop) {
2409  Opts.TabStop = DiagnosticOptions::DefaultTabStop;
2410  Diags->Report(diag::warn_ignoring_ftabstop_value)
2411  << Opts.TabStop << DiagnosticOptions::DefaultTabStop;
2412  }
2413 
2414  addDiagnosticArgs(Args, OPT_W_Group, OPT_W_value_Group, Opts.Warnings);
2415  addDiagnosticArgs(Args, OPT_R_Group, OPT_R_value_Group, Opts.Remarks);
2416 
2417  return Diags->getNumErrors() == NumErrorsBefore;
2418 }
2419 
2420 /// Parse the argument to the -ftest-module-file-extension
2421 /// command-line argument.
2422 ///
2423 /// \returns true on error, false on success.
2424 static bool parseTestModuleFileExtensionArg(StringRef Arg,
2425  std::string &BlockName,
2426  unsigned &MajorVersion,
2427  unsigned &MinorVersion,
2428  bool &Hashed,
2429  std::string &UserInfo) {
2430  SmallVector<StringRef, 5> Args;
2431  Arg.split(Args, ':', 5);
2432  if (Args.size() < 5)
2433  return true;
2434 
2435  BlockName = std::string(Args[0]);
2436  if (Args[1].getAsInteger(10, MajorVersion)) return true;
2437  if (Args[2].getAsInteger(10, MinorVersion)) return true;
2438  if (Args[3].getAsInteger(2, Hashed)) return true;
2439  if (Args.size() > 4)
2440  UserInfo = std::string(Args[4]);
2441  return false;
2442 }
2443 
2444 /// Return a table that associates command line option specifiers with the
2445 /// frontend action. Note: The pair {frontend::PluginAction, OPT_plugin} is
2446 /// intentionally missing, as this case is handled separately from other
2447 /// frontend options.
2448 static const auto &getFrontendActionTable() {
2449  static const std::pair<frontend::ActionKind, unsigned> Table[] = {
2450  {frontend::ASTDeclList, OPT_ast_list},
2451 
2452  {frontend::ASTDump, OPT_ast_dump_all_EQ},
2453  {frontend::ASTDump, OPT_ast_dump_all},
2454  {frontend::ASTDump, OPT_ast_dump_EQ},
2455  {frontend::ASTDump, OPT_ast_dump},
2456  {frontend::ASTDump, OPT_ast_dump_lookups},
2457  {frontend::ASTDump, OPT_ast_dump_decl_types},
2458 
2459  {frontend::ASTPrint, OPT_ast_print},
2460  {frontend::ASTView, OPT_ast_view},
2461  {frontend::DumpCompilerOptions, OPT_compiler_options_dump},
2462  {frontend::DumpRawTokens, OPT_dump_raw_tokens},
2463  {frontend::DumpTokens, OPT_dump_tokens},
2464  {frontend::EmitAssembly, OPT_S},
2465  {frontend::EmitBC, OPT_emit_llvm_bc},
2466  {frontend::EmitHTML, OPT_emit_html},
2467  {frontend::EmitLLVM, OPT_emit_llvm},
2468  {frontend::EmitLLVMOnly, OPT_emit_llvm_only},
2469  {frontend::EmitCodeGenOnly, OPT_emit_codegen_only},
2470  {frontend::EmitObj, OPT_emit_obj},
2471  {frontend::ExtractAPI, OPT_extract_api},
2472 
2473  {frontend::FixIt, OPT_fixit_EQ},
2474  {frontend::FixIt, OPT_fixit},
2475 
2476  {frontend::GenerateModule, OPT_emit_module},
2477  {frontend::GenerateModuleInterface, OPT_emit_module_interface},
2478  {frontend::GenerateHeaderUnit, OPT_emit_header_unit},
2479  {frontend::GeneratePCH, OPT_emit_pch},
2480  {frontend::GenerateInterfaceStubs, OPT_emit_interface_stubs},
2481  {frontend::InitOnly, OPT_init_only},
2482  {frontend::ParseSyntaxOnly, OPT_fsyntax_only},
2483  {frontend::ModuleFileInfo, OPT_module_file_info},
2484  {frontend::VerifyPCH, OPT_verify_pch},
2485  {frontend::PrintPreamble, OPT_print_preamble},
2487  {frontend::TemplightDump, OPT_templight_dump},
2488  {frontend::RewriteMacros, OPT_rewrite_macros},
2489  {frontend::RewriteObjC, OPT_rewrite_objc},
2490  {frontend::RewriteTest, OPT_rewrite_test},
2491  {frontend::RunAnalysis, OPT_analyze},
2492  {frontend::MigrateSource, OPT_migrate},
2493  {frontend::RunPreprocessorOnly, OPT_Eonly},
2495  OPT_print_dependency_directives_minimized_source},
2496  };
2497 
2498  return Table;
2499 }
2500 
2501 /// Maps command line option to frontend action.
2503  for (const auto &ActionOpt : getFrontendActionTable())
2504  if (ActionOpt.second == Opt.getID())
2505  return ActionOpt.first;
2506 
2507  return None;
2508 }
2509 
2510 /// Maps frontend action to command line option.
2513  for (const auto &ActionOpt : getFrontendActionTable())
2514  if (ActionOpt.first == ProgramAction)
2515  return OptSpecifier(ActionOpt.second);
2516 
2517  return None;
2518 }
2519 
2520 static void GenerateFrontendArgs(const FrontendOptions &Opts,
2523  bool IsHeader) {
2524  const FrontendOptions &FrontendOpts = Opts;
2525 #define FRONTEND_OPTION_WITH_MARSHALLING( \
2526  PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
2527  HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
2528  DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
2529  MERGER, EXTRACTOR, TABLE_INDEX) \
2530  GENERATE_OPTION_WITH_MARSHALLING( \
2531  Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \
2532  IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
2533 #include "clang/Driver/Options.inc"
2534 #undef FRONTEND_OPTION_WITH_MARSHALLING
2535 
2536  Optional<OptSpecifier> ProgramActionOpt =
2538 
2539  // Generating a simple flag covers most frontend actions.
2540  std::function<void()> GenerateProgramAction = [&]() {
2541  GenerateArg(Args, *ProgramActionOpt, SA);
2542  };
2543 
2544  if (!ProgramActionOpt) {
2545  // PluginAction is the only program action handled separately.
2546  assert(Opts.ProgramAction == frontend::PluginAction &&
2547  "Frontend action without option.");
2548  GenerateProgramAction = [&]() {
2549  GenerateArg(Args, OPT_plugin, Opts.ActionName, SA);
2550  };
2551  }
2552 
2553  // FIXME: Simplify the complex 'AST dump' command line.
2554  if (Opts.ProgramAction == frontend::ASTDump) {
2555  GenerateProgramAction = [&]() {
2556  // ASTDumpLookups, ASTDumpDeclTypes and ASTDumpFilter are generated via
2557  // marshalling infrastructure.
2558 
2559  if (Opts.ASTDumpFormat != ADOF_Default) {
2560  StringRef Format;
2561  switch (Opts.ASTDumpFormat) {
2562  case ADOF_Default:
2563  llvm_unreachable("Default AST dump format.");
2564  case ADOF_JSON:
2565  Format = "json";
2566  break;
2567  }
2568 
2569  if (Opts.ASTDumpAll)
2570  GenerateArg(Args, OPT_ast_dump_all_EQ, Format, SA);
2571  if (Opts.ASTDumpDecls)
2572  GenerateArg(Args, OPT_ast_dump_EQ, Format, SA);
2573  } else {
2574  if (Opts.ASTDumpAll)
2575  GenerateArg(Args, OPT_ast_dump_all, SA);
2576  if (Opts.ASTDumpDecls)
2577  GenerateArg(Args, OPT_ast_dump, SA);
2578  }
2579  };
2580  }
2581 
2582  if (Opts.ProgramAction == frontend::FixIt && !Opts.FixItSuffix.empty()) {
2583  GenerateProgramAction = [&]() {
2584  GenerateArg(Args, OPT_fixit_EQ, Opts.FixItSuffix, SA);
2585  };
2586  }
2587 
2588  GenerateProgramAction();
2589 
2590  for (const auto &PluginArgs : Opts.PluginArgs) {
2591  Option Opt = getDriverOptTable().getOption(OPT_plugin_arg);
2592  const char *Spelling =
2593  SA(Opt.getPrefix() + Opt.getName() + PluginArgs.first);
2594  for (const auto &PluginArg : PluginArgs.second)
2595  denormalizeString(Args, Spelling, SA, Opt.getKind(), 0, PluginArg);
2596  }
2597 
2598  for (const auto &Ext : Opts.ModuleFileExtensions)
2599  if (auto *TestExt = dyn_cast_or_null<TestModuleFileExtension>(Ext.get()))
2600  GenerateArg(Args, OPT_ftest_module_file_extension_EQ, TestExt->str(), SA);
2601 
2602  if (!Opts.CodeCompletionAt.FileName.empty())
2603  GenerateArg(Args, OPT_code_completion_at, Opts.CodeCompletionAt.ToString(),
2604  SA);
2605 
2606  for (const auto &Plugin : Opts.Plugins)
2607  GenerateArg(Args, OPT_load, Plugin, SA);
2608 
2609  // ASTDumpDecls and ASTDumpAll already handled with ProgramAction.
2610 
2611  for (const auto &ModuleFile : Opts.ModuleFiles)
2612  GenerateArg(Args, OPT_fmodule_file, ModuleFile, SA);
2613 
2614  if (Opts.AuxTargetCPU)
2615  GenerateArg(Args, OPT_aux_target_cpu, *Opts.AuxTargetCPU, SA);
2616 
2617  if (Opts.AuxTargetFeatures)
2618  for (const auto &Feature : *Opts.AuxTargetFeatures)
2619  GenerateArg(Args, OPT_aux_target_feature, Feature, SA);
2620 
2621  {
2622  StringRef Preprocessed = Opts.DashX.isPreprocessed() ? "-cpp-output" : "";
2623  StringRef ModuleMap =
2624  Opts.DashX.getFormat() == InputKind::ModuleMap ? "-module-map" : "";
2625  StringRef HeaderUnit = "";
2626  switch (Opts.DashX.getHeaderUnitKind()) {
2628  break;
2630  HeaderUnit = "-user";
2631  break;
2633  HeaderUnit = "-system";
2634  break;
2636  HeaderUnit = "-header-unit";
2637  break;
2638  }
2639  StringRef Header = IsHeader ? "-header" : "";
2640 
2641  StringRef Lang;
2642  switch (Opts.DashX.getLanguage()) {
2643  case Language::C:
2644  Lang = "c";
2645  break;
2646  case Language::OpenCL:
2647  Lang = "cl";
2648  break;
2649  case Language::OpenCLCXX:
2650  Lang = "clcpp";
2651  break;
2652  case Language::CUDA:
2653  Lang = "cuda";
2654  break;
2655  case Language::HIP:
2656  Lang = "hip";
2657  break;
2658  case Language::CXX:
2659  Lang = "c++";
2660  break;
2661  case Language::ObjC:
2662  Lang = "objective-c";
2663  break;
2664  case Language::ObjCXX:
2665  Lang = "objective-c++";
2666  break;
2668  Lang = "renderscript";
2669  break;
2670  case Language::Asm:
2671  Lang = "assembler-with-cpp";
2672  break;
2673  case Language::Unknown:
2674  assert(Opts.DashX.getFormat() == InputKind::Precompiled &&
2675  "Generating -x argument for unknown language (not precompiled).");
2676  Lang = "ast";
2677  break;
2678  case Language::LLVM_IR:
2679  Lang = "ir";
2680  break;
2681  case Language::HLSL:
2682  Lang = "hlsl";
2683  break;
2684  }
2685 
2686  GenerateArg(Args, OPT_x,
2687  Lang + HeaderUnit + Header + ModuleMap + Preprocessed, SA);
2688  }
2689 
2690  // OPT_INPUT has a unique class, generate it directly.
2691  for (const auto &Input : Opts.Inputs)
2692  Args.push_back(SA(Input.getFile()));
2693 }
2694 
2695 static bool ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args,
2696  DiagnosticsEngine &Diags, bool &IsHeaderFile) {
2697  unsigned NumErrorsBefore = Diags.getNumErrors();
2698 
2699  FrontendOptions &FrontendOpts = Opts;
2700 
2701 #define FRONTEND_OPTION_WITH_MARSHALLING( \
2702  PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
2703  HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
2704  DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
2705  MERGER, EXTRACTOR, TABLE_INDEX) \
2706  PARSE_OPTION_WITH_MARSHALLING( \
2707  Args, Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \
2708  IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
2709 #include "clang/Driver/Options.inc"
2710 #undef FRONTEND_OPTION_WITH_MARSHALLING
2711 
2713  if (const Arg *A = Args.getLastArg(OPT_Action_Group)) {
2714  OptSpecifier Opt = OptSpecifier(A->getOption().getID());
2716  assert(ProgramAction && "Option specifier not in Action_Group.");
2717 
2718  if (ProgramAction == frontend::ASTDump &&
2719  (Opt == OPT_ast_dump_all_EQ || Opt == OPT_ast_dump_EQ)) {
2720  unsigned Val = llvm::StringSwitch<unsigned>(A->getValue())
2721  .CaseLower("default", ADOF_Default)
2722  .CaseLower("json", ADOF_JSON)
2724 
2726  Opts.ASTDumpFormat = static_cast<ASTDumpOutputFormat>(Val);
2727  else {
2728  Diags.Report(diag::err_drv_invalid_value)
2729  << A->getAsString(Args) << A->getValue();
2730  Opts.ASTDumpFormat = ADOF_Default;
2731  }
2732  }
2733 
2734  if (ProgramAction == frontend::FixIt && Opt == OPT_fixit_EQ)
2735  Opts.FixItSuffix = A->getValue();
2736 
2737  if (ProgramAction == frontend::GenerateInterfaceStubs) {
2738  StringRef ArgStr =
2739  Args.hasArg(OPT_interface_stub_version_EQ)
2740  ? Args.getLastArgValue(OPT_interface_stub_version_EQ)
2741  : "ifs-v1";
2742  if (ArgStr == "experimental-yaml-elf-v1" ||
2743  ArgStr == "experimental-ifs-v1" || ArgStr == "experimental-ifs-v2" ||
2744  ArgStr == "experimental-tapi-elf-v1") {
2745  std::string ErrorMessage =
2746  "Invalid interface stub format: " + ArgStr.str() +
2747  " is deprecated.";
2748  Diags.Report(diag::err_drv_invalid_value)
2749  << "Must specify a valid interface stub format type, ie: "
2750  "-interface-stub-version=ifs-v1"
2751  << ErrorMessage;
2752  ProgramAction = frontend::ParseSyntaxOnly;
2753  } else if (!ArgStr.startswith("ifs-")) {
2754  std::string ErrorMessage =
2755  "Invalid interface stub format: " + ArgStr.str() + ".";
2756  Diags.Report(diag::err_drv_invalid_value)
2757  << "Must specify a valid interface stub format type, ie: "
2758  "-interface-stub-version=ifs-v1"
2759  << ErrorMessage;
2760  ProgramAction = frontend::ParseSyntaxOnly;
2761  }
2762  }
2763 
2764  Opts.ProgramAction = *ProgramAction;
2765  }
2766 
2767  if (const Arg* A = Args.getLastArg(OPT_plugin)) {
2768  Opts.Plugins.emplace_back(A->getValue(0));
2770  Opts.ActionName = A->getValue();
2771  }
2772  for (const auto *AA : Args.filtered(OPT_plugin_arg))
2773  Opts.PluginArgs[AA->getValue(0)].emplace_back(AA->getValue(1));
2774 
2775  for (const std::string &Arg :
2776  Args.getAllArgValues(OPT_ftest_module_file_extension_EQ)) {
2777  std::string BlockName;
2778  unsigned MajorVersion;
2779  unsigned MinorVersion;
2780  bool Hashed;
2781  std::string UserInfo;
2782  if (parseTestModuleFileExtensionArg(Arg, BlockName, MajorVersion,
2783  MinorVersion, Hashed, UserInfo)) {
2784  Diags.Report(diag::err_test_module_file_extension_format) << Arg;
2785 
2786  continue;
2787  }
2788 
2789  // Add the testing module file extension.
2790  Opts.ModuleFileExtensions.push_back(
2791  std::make_shared<TestModuleFileExtension>(
2792  BlockName, MajorVersion, MinorVersion, Hashed, UserInfo));
2793  }
2794 
2795  if (const Arg *A = Args.getLastArg(OPT_code_completion_at)) {
2796  Opts.CodeCompletionAt =
2797  ParsedSourceLocation::FromString(A->getValue());
2798  if (Opts.CodeCompletionAt.FileName.empty())
2799  Diags.Report(diag::err_drv_invalid_value)
2800  << A->getAsString(Args) << A->getValue();
2801  }
2802 
2803  Opts.Plugins = Args.getAllArgValues(OPT_load);
2804  Opts.ASTDumpDecls = Args.hasArg(OPT_ast_dump, OPT_ast_dump_EQ);
2805  Opts.ASTDumpAll = Args.hasArg(OPT_ast_dump_all, OPT_ast_dump_all_EQ);
2806  // Only the -fmodule-file=<file> form.
2807  for (const auto *A : Args.filtered(OPT_fmodule_file)) {
2808  StringRef Val = A->getValue();
2809  if (!Val.contains('='))
2810  Opts.ModuleFiles.push_back(std::string(Val));
2811  }
2812 
2814  Diags.Report(diag::err_drv_argument_only_allowed_with) << "-fsystem-module"
2815  << "-emit-module";
2816 
2817  if (Args.hasArg(OPT_aux_target_cpu))
2818  Opts.AuxTargetCPU = std::string(Args.getLastArgValue(OPT_aux_target_cpu));
2819  if (Args.hasArg(OPT_aux_target_feature))
2820  Opts.AuxTargetFeatures = Args.getAllArgValues(OPT_aux_target_feature);
2821 
2824  Diags.Report(diag::err_drv_argument_not_allowed_with)
2825  << "ARC migration" << "ObjC migration";
2826  }
2827 
2829  if (const Arg *A = Args.getLastArg(OPT_x)) {
2830  StringRef XValue = A->getValue();
2831 
2832  // Parse suffixes:
2833  // '<lang>(-[{header-unit,user,system}-]header|[-module-map][-cpp-output])'.
2834  // FIXME: Supporting '<lang>-header-cpp-output' would be useful.
2835  bool Preprocessed = XValue.consume_back("-cpp-output");
2836  bool ModuleMap = XValue.consume_back("-module-map");
2837  // Detect and consume the header indicator.
2838  bool IsHeader =
2839  XValue != "precompiled-header" && XValue.consume_back("-header");
2840 
2841  // If we have c++-{user,system}-header, that indicates a header unit input
2842  // likewise, if the user put -fmodule-header together with a header with an
2843  // absolute path (header-unit-header).
2845  if (IsHeader || Preprocessed) {
2846  if (XValue.consume_back("-header-unit"))
2848  else if (XValue.consume_back("-system"))
2850  else if (XValue.consume_back("-user"))
2852  }
2853 
2854  // The value set by this processing is an un-preprocessed source which is
2855  // not intended to be a module map or header unit.
2856  IsHeaderFile = IsHeader && !Preprocessed && !ModuleMap &&
2858 
2859  // Principal languages.
2860  DashX = llvm::StringSwitch<InputKind>(XValue)
2861  .Case("c", Language::C)
2862  .Case("cl", Language::OpenCL)
2863  .Case("clcpp", Language::OpenCLCXX)
2864  .Case("cuda", Language::CUDA)
2865  .Case("hip", Language::HIP)
2866  .Case("c++", Language::CXX)
2867  .Case("objective-c", Language::ObjC)
2868  .Case("objective-c++", Language::ObjCXX)
2869  .Case("renderscript", Language::RenderScript)
2870  .Case("hlsl", Language::HLSL)
2871  .Default(Language::Unknown);
2872 
2873  // "objc[++]-cpp-output" is an acceptable synonym for
2874  // "objective-c[++]-cpp-output".
2875  if (DashX.isUnknown() && Preprocessed && !IsHeaderFile && !ModuleMap &&
2877  DashX = llvm::StringSwitch<InputKind>(XValue)
2878  .Case("objc", Language::ObjC)
2879  .Case("objc++", Language::ObjCXX)
2880  .Default(Language::Unknown);
2881 
2882  // Some special cases cannot be combined with suffixes.
2883  if (DashX.isUnknown() && !Preprocessed && !IsHeaderFile && !ModuleMap &&
2885  DashX = llvm::StringSwitch<InputKind>(XValue)
2886  .Case("cpp-output", InputKind(Language::C).getPreprocessed())
2887  .Case("assembler-with-cpp", Language::Asm)
2888  .Cases("ast", "pcm", "precompiled-header",
2890  .Case("ir", Language::LLVM_IR)
2891  .Default(Language::Unknown);
2892 
2893  if (DashX.isUnknown())
2894  Diags.Report(diag::err_drv_invalid_value)
2895  << A->getAsString(Args) << A->getValue();
2896 
2897  if (Preprocessed)
2898  DashX = DashX.getPreprocessed();
2899  // A regular header is considered mutually exclusive with a header unit.
2900  if (HUK != InputKind::HeaderUnit_None) {
2901  DashX = DashX.withHeaderUnit(HUK);
2902  IsHeaderFile = true;
2903  } else if (IsHeaderFile)
2904  DashX = DashX.getHeader();
2905  if (ModuleMap)
2906  DashX = DashX.withFormat(InputKind::ModuleMap);
2907  }
2908 
2909  // '-' is the default input if none is given.
2910  std::vector<std::string> Inputs = Args.getAllArgValues(OPT_INPUT);
2911  Opts.Inputs.clear();
2912  if (Inputs.empty())
2913  Inputs.push_back("-");
2914 
2916  Inputs.size() > 1)
2917  Diags.Report(diag::err_drv_header_unit_extra_inputs) << Inputs[1];
2918 
2919  for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
2920  InputKind IK = DashX;
2921  if (IK.isUnknown()) {
2923  StringRef(Inputs[i]).rsplit('.').second);
2924  // FIXME: Warn on this?
2925  if (IK.isUnknown())
2926  IK = Language::C;
2927  // FIXME: Remove this hack.
2928  if (i == 0)
2929  DashX = IK;
2930  }
2931 
2932  bool IsSystem = false;
2933 
2934  // The -emit-module action implicitly takes a module map.
2936  IK.getFormat() == InputKind::Source) {
2938  IsSystem = Opts.IsSystemModule;
2939  }
2940 
2941  Opts.Inputs.emplace_back(std::move(Inputs[i]), IK, IsSystem);
2942  }
2943 
2944  Opts.DashX = DashX;
2945 
2946  return Diags.getNumErrors() == NumErrorsBefore;
2947 }
2948 
2950  void *MainAddr) {
2951  std::string ClangExecutable =
2952  llvm::sys::fs::getMainExecutable(Argv0, MainAddr);
2953  return Driver::GetResourcesPath(ClangExecutable, CLANG_RESOURCE_DIR);
2954 }
2955 
2959  const HeaderSearchOptions *HeaderSearchOpts = &Opts;
2960 #define HEADER_SEARCH_OPTION_WITH_MARSHALLING( \
2961  PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
2962  HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
2963  DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
2964  MERGER, EXTRACTOR, TABLE_INDEX) \
2965  GENERATE_OPTION_WITH_MARSHALLING( \
2966  Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \
2967  IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
2968 #include "clang/Driver/Options.inc"
2969 #undef HEADER_SEARCH_OPTION_WITH_MARSHALLING
2970 
2971  if (Opts.UseLibcxx)
2972  GenerateArg(Args, OPT_stdlib_EQ, "libc++", SA);
2973 
2974  if (!Opts.ModuleCachePath.empty())
2975  GenerateArg(Args, OPT_fmodules_cache_path, Opts.ModuleCachePath, SA);
2976 
2977  for (const auto &File : Opts.PrebuiltModuleFiles)
2978  GenerateArg(Args, OPT_fmodule_file, File.first + "=" + File.second, SA);
2979 
2980  for (const auto &Path : Opts.PrebuiltModulePaths)
2981  GenerateArg(Args, OPT_fprebuilt_module_path, Path, SA);
2982 
2983  for (const auto &Macro : Opts.ModulesIgnoreMacros)
2984  GenerateArg(Args, OPT_fmodules_ignore_macro, Macro.val(), SA);
2985 
2986  auto Matches = [](const HeaderSearchOptions::Entry &Entry,
2988  llvm::Optional<bool> IsFramework,
2989  llvm::Optional<bool> IgnoreSysRoot) {
2990  return llvm::is_contained(Groups, Entry.Group) &&
2991  (!IsFramework || (Entry.IsFramework == *IsFramework)) &&
2992  (!IgnoreSysRoot || (Entry.IgnoreSysRoot == *IgnoreSysRoot));
2993  };
2994 
2995  auto It = Opts.UserEntries.begin();
2996  auto End = Opts.UserEntries.end();
2997 
2998  // Add -I..., -F..., and -index-header-map options in order.
2999  for (; It < End &&
3000  Matches(*It, {frontend::IndexHeaderMap, frontend::Angled}, None, true);
3001  ++It) {
3002  OptSpecifier Opt = [It, Matches]() {
3003  if (Matches(*It, frontend::IndexHeaderMap, true, true))
3004  return OPT_F;
3005  if (Matches(*It, frontend::IndexHeaderMap, false, true))
3006  return OPT_I;
3007  if (Matches(*It, frontend::Angled, true, true))
3008  return OPT_F;
3009  if (Matches(*It, frontend::Angled, false, true))
3010  return OPT_I;
3011  llvm_unreachable("Unexpected HeaderSearchOptions::Entry.");
3012  }();
3013 
3014  if (It->Group == frontend::IndexHeaderMap)
3015  GenerateArg(Args, OPT_index_header_map, SA);
3016  GenerateArg(Args, Opt, It->Path, SA);
3017  };
3018 
3019  // Note: some paths that came from "[-iprefix=xx] -iwithprefixbefore=yy" may
3020  // have already been generated as "-I[xx]yy". If that's the case, their
3021  // position on command line was such that this has no semantic impact on
3022  // include paths.
3023  for (; It < End &&
3024  Matches(*It, {frontend::After, frontend::Angled}, false, true);
3025  ++It) {
3026  OptSpecifier Opt =
3027  It->Group == frontend::After ? OPT_iwithprefix : OPT_iwithprefixbefore;
3028  GenerateArg(Args, Opt, It->Path, SA);
3029  }
3030 
3031  // Note: Some paths that came from "-idirafter=xxyy" may have already been
3032  // generated as "-iwithprefix=xxyy". If that's the case, their position on
3033  // command line was such that this has no semantic impact on include paths.
3034  for (; It < End && Matches(*It, {frontend::After}, false, true); ++It)
3035  GenerateArg(Args, OPT_idirafter, It->Path, SA);
3036  for (; It < End && Matches(*It, {frontend::Quoted}, false, true); ++It)
3037  GenerateArg(Args, OPT_iquote, It->Path, SA);
3038  for (; It < End && Matches(*It, {frontend::System}, false, None); ++It)
3039  GenerateArg(Args, It->IgnoreSysRoot ? OPT_isystem : OPT_iwithsysroot,
3040  It->Path, SA);
3041  for (; It < End && Matches(*It, {frontend::System}, true, true); ++It)
3042  GenerateArg(Args, OPT_iframework, It->Path, SA);
3043  for (; It < End && Matches(*It, {frontend::System}, true, false); ++It)
3044  GenerateArg(Args, OPT_iframeworkwithsysroot, It->Path, SA);
3045 
3046  // Add the paths for the various language specific isystem flags.
3047  for (; It < End && Matches(*It, {frontend::CSystem}, false, true); ++It)
3048  GenerateArg(Args, OPT_c_isystem, It->Path, SA);
3049  for (; It < End && Matches(*It, {frontend::CXXSystem}, false, true); ++It)
3050  GenerateArg(Args, OPT_cxx_isystem, It->Path, SA);
3051  for (; It < End && Matches(*It, {frontend::ObjCSystem}, false, true); ++It)
3052  GenerateArg(Args, OPT_objc_isystem, It->Path, SA);
3053  for (; It < End && Matches(*It, {frontend::ObjCXXSystem}, false, true); ++It)
3054  GenerateArg(Args, OPT_objcxx_isystem, It->Path, SA);
3055 
3056  // Add the internal paths from a driver that detects standard include paths.
3057  // Note: Some paths that came from "-internal-isystem" arguments may have
3058  // already been generated as "-isystem". If that's the case, their position on
3059  // command line was such that this has no semantic impact on include paths.
3060  for (; It < End &&
3061  Matches(*It, {frontend::System, frontend::ExternCSystem}, false, true);
3062  ++It) {
3063  OptSpecifier Opt = It->Group == frontend::System
3064  ? OPT_internal_isystem
3065  : OPT_internal_externc_isystem;
3066  GenerateArg(Args, Opt, It->Path, SA);
3067  }
3068 
3069  assert(It == End && "Unhandled HeaderSearchOption::Entry.");
3070 
3071  // Add the path prefixes which are implicitly treated as being system headers.
3072  for (const auto &P : Opts.SystemHeaderPrefixes) {
3073  OptSpecifier Opt = P.IsSystemHeader ? OPT_system_header_prefix
3074  : OPT_no_system_header_prefix;
3075  GenerateArg(Args, Opt, P.Prefix, SA);
3076  }
3077 
3078  for (const std::string &F : Opts.VFSOverlayFiles)
3079  GenerateArg(Args, OPT_ivfsoverlay, F, SA);
3080 }
3081 
3082 static bool ParseHeaderSearchArgs(HeaderSearchOptions &Opts, ArgList &Args,
3083  DiagnosticsEngine &Diags,
3084  const std::string &WorkingDir) {
3085  unsigned NumErrorsBefore = Diags.getNumErrors();
3086 
3087  HeaderSearchOptions *HeaderSearchOpts = &Opts;
3088 
3089 #define HEADER_SEARCH_OPTION_WITH_MARSHALLING( \
3090  PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
3091  HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
3092  DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
3093  MERGER, EXTRACTOR, TABLE_INDEX) \
3094  PARSE_OPTION_WITH_MARSHALLING( \
3095  Args, Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \
3096  IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
3097 #include "clang/Driver/Options.inc"
3098 #undef HEADER_SEARCH_OPTION_WITH_MARSHALLING
3099 
3100  if (const Arg *A = Args.getLastArg(OPT_stdlib_EQ))
3101  Opts.UseLibcxx = (strcmp(A->getValue(), "libc++") == 0);
3102 
3103  // Canonicalize -fmodules-cache-path before storing it.
3104  SmallString<128> P(Args.getLastArgValue(OPT_fmodules_cache_path));
3105  if (!(P.empty() || llvm::sys::path::is_absolute(P))) {
3106  if (WorkingDir.empty())
3107  llvm::sys::fs::make_absolute(P);
3108  else
3109  llvm::sys::fs::make_absolute(WorkingDir, P);
3110  }
3111  llvm::sys::path::remove_dots(P);
3112  Opts.ModuleCachePath = std::string(P.str());
3113 
3114  // Only the -fmodule-file=<name>=<file> form.
3115  for (const auto *A : Args.filtered(OPT_fmodule_file)) {
3116  StringRef Val = A->getValue();
3117  if (Val.contains('=')) {
3118  auto Split = Val.split('=');
3119  Opts.PrebuiltModuleFiles.insert(
3120  {std::string(Split.first), std::string(Split.second)});
3121  }
3122  }
3123  for (const auto *A : Args.filtered(OPT_fprebuilt_module_path))
3124  Opts.AddPrebuiltModulePath(A->getValue());
3125 
3126  for (const auto *A : Args.filtered(OPT_fmodules_ignore_macro)) {
3127  StringRef MacroDef = A->getValue();
3128  Opts.ModulesIgnoreMacros.insert(
3129  llvm::CachedHashString(MacroDef.split('=').first));
3130  }
3131 
3132  // Add -I..., -F..., and -index-header-map options in order.
3133  bool IsIndexHeaderMap = false;
3134  bool IsSysrootSpecified =
3135  Args.hasArg(OPT__sysroot_EQ) || Args.hasArg(OPT_isysroot);
3136  for (const auto *A : Args.filtered(OPT_I, OPT_F, OPT_index_header_map)) {
3137  if (A->getOption().matches(OPT_index_header_map)) {
3138  // -index-header-map applies to the next -I or -F.
3139  IsIndexHeaderMap = true;
3140  continue;
3141  }
3142 
3144  IsIndexHeaderMap ? frontend::IndexHeaderMap : frontend::Angled;
3145 
3146  bool IsFramework = A->getOption().matches(OPT_F);
3147  std::string Path = A->getValue();
3148 
3149  if (IsSysrootSpecified && !IsFramework && A->getValue()[0] == '=') {
3150  SmallString<32> Buffer;
3151  llvm::sys::path::append(Buffer, Opts.Sysroot,
3152  llvm::StringRef(A->getValue()).substr(1));
3153  Path = std::string(Buffer.str());
3154  }
3155 
3156  Opts.AddPath(Path, Group, IsFramework,
3157  /*IgnoreSysroot*/ true);
3158  IsIndexHeaderMap = false;
3159  }
3160 
3161  // Add -iprefix/-iwithprefix/-iwithprefixbefore options.
3162  StringRef Prefix = ""; // FIXME: This isn't the correct default prefix.
3163  for (const auto *A :
3164  Args.filtered(OPT_iprefix, OPT_iwithprefix, OPT_iwithprefixbefore)) {
3165  if (A->getOption().matches(OPT_iprefix))
3166  Prefix = A->getValue();
3167  else if (A->getOption().matches(OPT_iwithprefix))
3168  Opts.AddPath(Prefix.str() + A->getValue(), frontend::After, false, true);
3169  else
3170  Opts.AddPath(Prefix.str() + A->getValue(), frontend::Angled, false, true);
3171  }
3172 
3173  for (const auto *A : Args.filtered(OPT_idirafter))
3174  Opts.AddPath(A->getValue(), frontend::After, false, true);
3175  for (const auto *A : Args.filtered(OPT_iquote))
3176  Opts.AddPath(A->getValue(), frontend::Quoted, false, true);
3177  for (const auto *A : Args.filtered(OPT_isystem, OPT_iwithsysroot))
3178  Opts.AddPath(A->getValue(), frontend::System, false,
3179  !A->getOption().matches(OPT_iwithsysroot));
3180  for (const auto *A : Args.filtered(OPT_iframework))
3181  Opts.AddPath(A->getValue(), frontend::System, true, true);
3182  for (const auto *A : Args.filtered(OPT_iframeworkwithsysroot))
3183  Opts.AddPath(A->getValue(), frontend::System, /*IsFramework=*/true,
3184  /*IgnoreSysRoot=*/false);
3185 
3186  // Add the paths for the various language specific isystem flags.
3187  for (const auto *A : Args.filtered(OPT_c_isystem))
3188  Opts.AddPath(A->getValue(), frontend::CSystem, false, true);
3189  for (const auto *A : Args.filtered(OPT_cxx_isystem))
3190  Opts.AddPath(A->getValue(), frontend::CXXSystem, false, true);
3191  for (const auto *A : Args.filtered(OPT_objc_isystem))
3192  Opts.AddPath(A->getValue(), frontend::ObjCSystem, false,true);
3193  for (const auto *A : Args.filtered(OPT_objcxx_isystem))
3194  Opts.AddPath(A->getValue(), frontend::ObjCXXSystem, false, true);
3195 
3196  // Add the internal paths from a driver that detects standard include paths.
3197  for (const auto *A :
3198  Args.filtered(OPT_internal_isystem, OPT_internal_externc_isystem)) {
3200  if (A->getOption().matches(OPT_internal_externc_isystem))
3202  Opts.AddPath(A->getValue(), Group, false, true);
3203  }
3204 
3205  // Add the path prefixes which are implicitly treated as being system headers.
3206  for (const auto *A :
3207  Args.filtered(OPT_system_header_prefix, OPT_no_system_header_prefix))
3208  Opts.AddSystemHeaderPrefix(
3209  A->getValue(), A->getOption().matches(OPT_system_header_prefix));
3210 
3211  for (const auto *A : Args.filtered(OPT_ivfsoverlay))
3212  Opts.AddVFSOverlayFile(A->getValue());
3213 
3214  return Diags.getNumErrors() == NumErrorsBefore;
3215 }
3216 
3217 /// Check if input file kind and language standard are compatible.
3219  const LangStandard &S) {
3220  switch (IK.getLanguage()) {
3221  case Language::Unknown:
3222  case Language::LLVM_IR:
3223  llvm_unreachable("should not parse language flags for this input");
3224 
3225  case Language::C:
3226  case Language::ObjC:
3228  return S.getLanguage() == Language::C;
3229 
3230  case Language::OpenCL:
3231  return S.getLanguage() == Language::OpenCL ||
3232  S.getLanguage() == Language::OpenCLCXX;
3233 
3234  case Language::OpenCLCXX:
3235  return S.getLanguage() == Language::OpenCLCXX;
3236 
3237  case Language::CXX:
3238  case Language::ObjCXX:
3239  return S.getLanguage() == Language::CXX;
3240 
3241  case Language::CUDA:
3242  // FIXME: What -std= values should be permitted for CUDA compilations?
3243  return S.getLanguage() == Language::CUDA ||
3244  S.getLanguage() == Language::CXX;
3245 
3246  case Language::HIP:
3247  return S.getLanguage() == Language::CXX || S.getLanguage() == Language::HIP;
3248 
3249  case Language::Asm:
3250  // Accept (and ignore) all -std= values.
3251  // FIXME: The -std= value is not ignored; it affects the tokenization
3252  // and preprocessing rules if we're preprocessing this asm input.
3253  return true;
3254 
3255  case Language::HLSL:
3256  return S.getLanguage() == Language::HLSL;
3257  }
3258 
3259  llvm_unreachable("unexpected input language");
3260 }
3261 
3262 /// Get language name for given input kind.
3263 static StringRef GetInputKindName(InputKind IK) {
3264  switch (IK.getLanguage()) {
3265  case Language::C:
3266  return "C";
3267  case Language::ObjC:
3268  return "Objective-C";
3269  case Language::CXX:
3270  return "C++";
3271  case Language::ObjCXX:
3272  return "Objective-C++";
3273  case Language::OpenCL:
3274  return "OpenCL";
3275  case Language::OpenCLCXX:
3276  return "C++ for OpenCL";
3277  case Language::CUDA:
3278  return "CUDA";
3280  return "RenderScript";
3281  case Language::HIP:
3282  return "HIP";
3283 
3284  case Language::Asm:
3285  return "Asm";
3286  case Language::LLVM_IR:
3287  return "LLVM IR";
3288 
3289  case Language::HLSL:
3290  return "HLSL";
3291 
3292  case Language::Unknown:
3293  break;
3294  }
3295  llvm_unreachable("unknown input language");
3296 }
3297 
3298 void CompilerInvocation::GenerateLangArgs(const LangOptions &Opts,
3300  StringAllocator SA,
3301  const llvm::Triple &T, InputKind IK) {
3302  if (IK.getFormat() == InputKind::Precompiled ||
3303  IK.getLanguage() == Language::LLVM_IR) {
3304  if (Opts.ObjCAutoRefCount)
3305  GenerateArg(Args, OPT_fobjc_arc, SA);
3306  if (Opts.PICLevel != 0)
3307  GenerateArg(Args, OPT_pic_level, Twine(Opts.PICLevel), SA);
3308  if (Opts.PIE)
3309  GenerateArg(Args, OPT_pic_is_pie, SA);
3310  for (StringRef Sanitizer : serializeSanitizerKinds(Opts.Sanitize))
3311  GenerateArg(Args, OPT_fsanitize_EQ, Sanitizer, SA);
3312 
3313  return;
3314  }
3315 
3316  OptSpecifier StdOpt;
3317  switch (Opts.LangStd) {
3318  case LangStandard::lang_opencl10:
3319  case LangStandard::lang_opencl11:
3320  case LangStandard::lang_opencl12:
3321  case LangStandard::lang_opencl20:
3322  case LangStandard::lang_opencl30:
3323  case LangStandard::lang_openclcpp10:
3324  case LangStandard::lang_openclcpp2021:
3325  StdOpt = OPT_cl_std_EQ;
3326  break;
3327  default:
3328  StdOpt = OPT_std_EQ;
3329  break;
3330  }
3331 
3333  GenerateArg(Args, StdOpt, LangStandard.getName(), SA);
3334 
3335  if (Opts.IncludeDefaultHeader)
3336  GenerateArg(Args, OPT_finclude_default_header, SA);
3337  if (Opts.DeclareOpenCLBuiltins)
3338  GenerateArg(Args, OPT_fdeclare_opencl_builtins, SA);
3339 
3340  const LangOptions *LangOpts = &Opts;
3341 
3342 #define LANG_OPTION_WITH_MARSHALLING( \
3343  PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
3344  HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
3345  DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
3346  MERGER, EXTRACTOR, TABLE_INDEX) \
3347  GENERATE_OPTION_WITH_MARSHALLING( \
3348  Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \
3349  IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
3350 #include "clang/Driver/Options.inc"
3351 #undef LANG_OPTION_WITH_MARSHALLING
3352 
3353  // The '-fcf-protection=' option is generated by CodeGenOpts generator.
3354 
3355  if (Opts.ObjC) {
3356  GenerateArg(Args, OPT_fobjc_runtime_EQ, Opts.ObjCRuntime.getAsString(), SA);
3357 
3358  if (Opts.GC == LangOptions::GCOnly)
3359  GenerateArg(Args, OPT_fobjc_gc_only, SA);
3360  else if (Opts.GC == LangOptions::HybridGC)
3361  GenerateArg(Args, OPT_fobjc_gc, SA);
3362  else if (Opts.ObjCAutoRefCount == 1)
3363  GenerateArg(Args, OPT_fobjc_arc, SA);
3364 
3365  if (Opts.ObjCWeakRuntime)
3366  GenerateArg(Args, OPT_fobjc_runtime_has_weak, SA);
3367 
3368  if (Opts.ObjCWeak)
3369  GenerateArg(Args, OPT_fobjc_weak, SA);
3370 
3371  if (Opts.ObjCSubscriptingLegacyRuntime)
3372  GenerateArg(Args, OPT_fobjc_subscripting_legacy_runtime, SA);
3373  }
3374 
3375  if (Opts.GNUCVersion != 0) {
3376  unsigned Major = Opts.GNUCVersion / 100 / 100;
3377  unsigned Minor = (Opts.GNUCVersion / 100) % 100;
3378  unsigned Patch = Opts.GNUCVersion % 100;
3379  GenerateArg(Args, OPT_fgnuc_version_EQ,
3380  Twine(Major) + "." + Twine(Minor) + "." + Twine(Patch), SA);
3381  }
3382 
3383  if (Opts.IgnoreXCOFFVisibility)
3384  GenerateArg(Args, OPT_mignore_xcoff_visibility, SA);
3385 
3386  if (Opts.SignedOverflowBehavior == LangOptions::SOB_Trapping) {
3387  GenerateArg(Args, OPT_ftrapv, SA);
3388  GenerateArg(Args, OPT_ftrapv_handler, Opts.OverflowHandler, SA);
3389  } else if (Opts.SignedOverflowBehavior == LangOptions::SOB_Defined) {
3390  GenerateArg(Args, OPT_fwrapv, SA);
3391  }
3392 
3393  if (Opts.MSCompatibilityVersion != 0) {
3394  unsigned Major = Opts.MSCompatibilityVersion / 10000000;
3395  unsigned Minor = (Opts.MSCompatibilityVersion / 100000) % 100;
3396  unsigned Subminor = Opts.MSCompatibilityVersion % 100000;
3397  GenerateArg(Args, OPT_fms_compatibility_version,
3398  Twine(Major) + "." + Twine(Minor) + "." + Twine(Subminor), SA);
3399  }
3400 
3401  if ((!Opts.GNUMode && !Opts.MSVCCompat && !Opts.CPlusPlus17) || T.isOSzOS()) {
3402  if (!Opts.Trigraphs)
3403  GenerateArg(Args, OPT_fno_trigraphs, SA);
3404  } else {
3405  if (Opts.Trigraphs)
3406  GenerateArg(Args, OPT_ftrigraphs, SA);
3407  }
3408 
3409  if (Opts.Blocks && !(Opts.OpenCL && Opts.OpenCLVersion == 200))
3410  GenerateArg(Args, OPT_fblocks, SA);
3411 
3412  if (Opts.ConvergentFunctions &&
3413  !(Opts.OpenCL || (Opts.CUDA && Opts.CUDAIsDevice) || Opts.SYCLIsDevice))
3414  GenerateArg(Args, OPT_fconvergent_functions, SA);
3415 
3416  if (Opts.NoBuiltin && !Opts.Freestanding)
3417  GenerateArg(Args, OPT_fno_builtin, SA);
3418 
3419  if (!Opts.NoBuiltin)
3420  for (const auto &Func : Opts.NoBuiltinFuncs)
3421  GenerateArg(Args, OPT_fno_builtin_, Func, SA);
3422 
3423  if (Opts.LongDoubleSize == 128)
3424  GenerateArg(Args, OPT_mlong_double_128, SA);
3425  else if (Opts.LongDoubleSize == 64)
3426  GenerateArg(Args, OPT_mlong_double_64, SA);
3427  else if (Opts.LongDoubleSize == 80)
3428  GenerateArg(Args, OPT_mlong_double_80, SA);
3429 
3430  // Not generating '-mrtd', it's just an alias for '-fdefault-calling-conv='.
3431 
3432  // OpenMP was requested via '-fopenmp', not implied by '-fopenmp-simd' or
3433  // '-fopenmp-targets='.
3434  if (Opts.OpenMP && !Opts.OpenMPSimd) {
3435  GenerateArg(Args, OPT_fopenmp, SA);
3436 
3437  if (Opts.OpenMP != 50)
3438  GenerateArg(Args, OPT_fopenmp_version_EQ, Twine(Opts.OpenMP), SA);
3439 
3440  if (!Opts.OpenMPUseTLS)
3441  GenerateArg(Args, OPT_fnoopenmp_use_tls, SA);
3442 
3443  if (Opts.OpenMPIsDevice)
3444  GenerateArg(Args, OPT_fopenmp_is_device, SA);
3445 
3446  if (Opts.OpenMPIRBuilder)
3447  GenerateArg(Args, OPT_fopenmp_enable_irbuilder, SA);
3448  }
3449 
3450  if (Opts.OpenMPSimd) {
3451  GenerateArg(Args, OPT_fopenmp_simd, SA);
3452 
3453  if (Opts.OpenMP != 50)
3454  GenerateArg(Args, OPT_fopenmp_version_EQ, Twine(Opts.OpenMP), SA);
3455  }
3456 
3457  if (Opts.OpenMPThreadSubscription)
3458  GenerateArg(Args, OPT_fopenmp_assume_threads_oversubscription, SA);
3459 
3460  if (Opts.OpenMPTeamSubscription)
3461  GenerateArg(Args, OPT_fopenmp_assume_teams_oversubscription, SA);
3462 
3463  if (Opts.OpenMPTargetDebug != 0)
3464  GenerateArg(Args, OPT_fopenmp_target_debug_EQ,
3465  Twine(Opts.OpenMPTargetDebug), SA);
3466 
3467  if (Opts.OpenMPCUDANumSMs != 0)
3468  GenerateArg(Args, OPT_fopenmp_cuda_number_of_sm_EQ,
3469  Twine(Opts.OpenMPCUDANumSMs), SA);
3470 
3471  if (Opts.OpenMPCUDABlocksPerSM != 0)
3472  GenerateArg(Args, OPT_fopenmp_cuda_blocks_per_sm_EQ,
3473  Twine(Opts.OpenMPCUDABlocksPerSM), SA);
3474 
3475  if (Opts.OpenMPCUDAReductionBufNum != 1024)
3476  GenerateArg(Args, OPT_fopenmp_cuda_teams_reduction_recs_num_EQ,
3477  Twine(Opts.OpenMPCUDAReductionBufNum), SA);
3478 
3479  if (!Opts.OMPTargetTriples.empty()) {
3480  std::string Targets;
3481  llvm::raw_string_ostream OS(Targets);
3482  llvm::interleave(
3483  Opts.OMPTargetTriples, OS,
3484  [&OS](const llvm::Triple &T) { OS << T.str(); }, ",");
3485  GenerateArg(Args, OPT_fopenmp_targets_EQ, OS.str(), SA);
3486  }
3487 
3488  if (!Opts.OMPHostIRFile.empty())
3489  GenerateArg(Args, OPT_fopenmp_host_ir_file_path, Opts.OMPHostIRFile, SA);
3490 
3491  if (Opts.OpenMPCUDAMode)
3492  GenerateArg(Args, OPT_fopenmp_cuda_mode, SA);
3493 
3494  // The arguments used to set Optimize, OptimizeSize and NoInlineDefine are
3495  // generated from CodeGenOptions.
3496 
3497  if (Opts.DefaultFPContractMode == LangOptions::FPM_Fast)
3498  GenerateArg(Args, OPT_ffp_contract, "fast", SA);
3499  else if (Opts.DefaultFPContractMode == LangOptions::FPM_On)
3500  GenerateArg(Args, OPT_ffp_contract, "on", SA);
3501  else if (Opts.DefaultFPContractMode == LangOptions::FPM_Off)
3502  GenerateArg(Args, OPT_ffp_contract, "off", SA);
3503  else if (Opts.DefaultFPContractMode == LangOptions::FPM_FastHonorPragmas)
3504  GenerateArg(Args, OPT_ffp_contract, "fast-honor-pragmas", SA);
3505 
3506  for (StringRef Sanitizer : serializeSanitizerKinds(Opts.Sanitize))
3507  GenerateArg(Args, OPT_fsanitize_EQ, Sanitizer, SA);
3508 
3509  // Conflating '-fsanitize-system-ignorelist' and '-fsanitize-ignorelist'.
3510  for (const std::string &F : Opts.NoSanitizeFiles)
3511  GenerateArg(Args, OPT_fsanitize_ignorelist_EQ, F, SA);
3512 
3513  if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver3_8)
3514  GenerateArg(Args, OPT_fclang_abi_compat_EQ, "3.8", SA);
3515  else if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver4)
3516  GenerateArg(Args, OPT_fclang_abi_compat_EQ, "4.0", SA);
3517  else if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver6)
3518  GenerateArg(Args, OPT_fclang_abi_compat_EQ, "6.0", SA);
3519  else if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver7)
3520  GenerateArg(Args, OPT_fclang_abi_compat_EQ, "7.0", SA);
3521  else if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver9)
3522  GenerateArg(Args, OPT_fclang_abi_compat_EQ, "9.0", SA);
3523  else if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver11)
3524  GenerateArg(Args, OPT_fclang_abi_compat_EQ, "11.0", SA);
3525  else if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver12)
3526  GenerateArg(Args, OPT_fclang_abi_compat_EQ, "12.0", SA);
3527  else if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver14)
3528  GenerateArg(Args, OPT_fclang_abi_compat_EQ, "14.0", SA);
3529  else if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver15)
3530  GenerateArg(Args, OPT_fclang_abi_compat_EQ, "15.0", SA);
3531 
3532  if (Opts.getSignReturnAddressScope() ==
3534  GenerateArg(Args, OPT_msign_return_address_EQ, "all", SA);
3535  else if (Opts.getSignReturnAddressScope() ==
3537  GenerateArg(Args, OPT_msign_return_address_EQ, "non-leaf", SA);
3538 
3539  if (Opts.getSignReturnAddressKey() ==
3541  GenerateArg(Args, OPT_msign_return_address_key_EQ, "b_key", SA);
3542 
3543  if (Opts.CXXABI)
3544  GenerateArg(Args, OPT_fcxx_abi_EQ, TargetCXXABI::getSpelling(*Opts.CXXABI),
3545  SA);
3546 
3547  if (Opts.RelativeCXXABIVTables)
3548  GenerateArg(Args, OPT_fexperimental_relative_cxx_abi_vtables, SA);
3549  else
3550  GenerateArg(Args, OPT_fno_experimental_relative_cxx_abi_vtables, SA);
3551 
3552  if (Opts.UseTargetPathSeparator)
3553  GenerateArg(Args, OPT_ffile_reproducible, SA);
3554  else
3555  GenerateArg(Args, OPT_fno_file_reproducible, SA);
3556 
3557  for (const auto &MP : Opts.MacroPrefixMap)
3558  GenerateArg(Args, OPT_fmacro_prefix_map_EQ, MP.first + "=" + MP.second, SA);
3559 
3560  if (!Opts.RandstructSeed.empty())
3561  GenerateArg(Args, OPT_frandomize_layout_seed_EQ, Opts.RandstructSeed, SA);
3562 }
3563 
3564 bool CompilerInvocation::ParseLangArgs(LangOptions &Opts, ArgList &Args,
3565  InputKind IK, const llvm::Triple &T,
3566  std::vector<std::string> &Includes,
3567  DiagnosticsEngine &Diags) {
3568  unsigned NumErrorsBefore = Diags.getNumErrors();
3569 
3570  if (IK.getFormat() == InputKind::Precompiled ||
3571  IK.getLanguage() == Language::LLVM_IR) {
3572  // ObjCAAutoRefCount and Sanitize LangOpts are used to setup the
3573  // PassManager in BackendUtil.cpp. They need to be initialized no matter
3574  // what the input type is.
3575  if (Args.hasArg(OPT_fobjc_arc))
3576  Opts.ObjCAutoRefCount = 1;
3577  // PICLevel and PIELevel are needed during code generation and this should
3578  // be set regardless of the input type.
3579  Opts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags);
3580  Opts.PIE = Args.hasArg(OPT_pic_is_pie);
3581  parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ),
3582  Diags, Opts.Sanitize);
3583 
3584  return Diags.getNumErrors() == NumErrorsBefore;
3585  }
3586 
3587  // Other LangOpts are only initialized when the input is not AST or LLVM IR.
3588  // FIXME: Should we really be parsing this for an Language::Asm input?
3589 
3590  // FIXME: Cleanup per-file based stuff.
3592  if (const Arg *A = Args.getLastArg(OPT_std_EQ)) {
3593  LangStd = LangStandard::getLangKind(A->getValue());
3594  if (LangStd == LangStandard::lang_unspecified) {
3595  Diags.Report(diag::err_drv_invalid_value)
3596  << A->getAsString(Args) << A->getValue();
3597  // Report supported standards with short description.
3598  for (unsigned KindValue = 0;
3599  KindValue != LangStandard::lang_unspecified;
3600  ++KindValue) {
3602  static_cast<LangStandard::Kind>(KindValue));
3604  auto Diag = Diags.Report(diag::note_drv_use_standard);
3605  Diag << Std.getName() << Std.getDescription();
3606  unsigned NumAliases = 0;
3607 #define LANGSTANDARD(id, name, lang, desc, features)
3608 #define LANGSTANDARD_ALIAS(id, alias) \
3609  if (KindValue == LangStandard::lang_##id) ++NumAliases;
3610 #define LANGSTANDARD_ALIAS_DEPR(id, alias)
3611 #include "clang/Basic/LangStandards.def"
3612  Diag << NumAliases;
3613 #define LANGSTANDARD(id, name, lang, desc, features)
3614 #define LANGSTANDARD_ALIAS(id, alias) \
3615  if (KindValue == LangStandard::lang_##id) Diag << alias;
3616 #define LANGSTANDARD_ALIAS_DEPR(id, alias)
3617 #include "clang/Basic/LangStandards.def"
3618  }
3619  }
3620  } else {
3621  // Valid standard, check to make sure language and standard are
3622  // compatible.
3624  if (!IsInputCompatibleWithStandard(IK, Std)) {
3625  Diags.Report(diag::err_drv_argument_not_allowed_with)
3626  << A->getAsString(Args) << GetInputKindName(IK);
3627  }
3628  }
3629  }
3630 
3631  // -cl-std only applies for OpenCL language standards.
3632  // Override the -std option in this case.
3633  if (const Arg *A = Args.getLastArg(OPT_cl_std_EQ)) {
3634  LangStandard::Kind OpenCLLangStd
3635  = llvm::StringSwitch<LangStandard::Kind>(A->getValue())
3636  .Cases("cl", "CL", LangStandard::lang_opencl10)
3637  .Cases("cl1.0", "CL1.0", LangStandard::lang_opencl10)
3638  .Cases("cl1.1", "CL1.1", LangStandard::lang_opencl11)
3639  .Cases("cl1.2", "CL1.2", LangStandard::lang_opencl12)
3640  .Cases("cl2.0", "CL2.0", LangStandard::lang_opencl20)
3641  .Cases("cl3.0", "CL3.0", LangStandard::lang_opencl30)
3642  .Cases("clc++", "CLC++", LangStandard::lang_openclcpp10)
3643  .Cases("clc++1.0", "CLC++1.0", LangStandard::lang_openclcpp10)
3644  .Cases("clc++2021", "CLC++2021", LangStandard::lang_openclcpp2021)
3646 
3647  if (OpenCLLangStd == LangStandard::lang_unspecified) {
3648  Diags.Report(diag::err_drv_invalid_value)
3649  << A->getAsString(Args) << A->getValue();
3650  }
3651  else
3652  LangStd = OpenCLLangStd;
3653  }
3654 
3655  // These need to be parsed now. They are used to set OpenCL defaults.
3656  Opts.IncludeDefaultHeader = Args.hasArg(OPT_finclude_default_header);
3657  Opts.DeclareOpenCLBuiltins = Args.hasArg(OPT_fdeclare_opencl_builtins);
3658 
3659  LangOptions::setLangDefaults(Opts, IK.getLanguage(), T, Includes, LangStd);
3660 
3661  // The key paths of codegen options defined in Options.td start with
3662  // "LangOpts->". Let's provide the expected variable name and type.
3663  LangOptions *LangOpts = &Opts;
3664 
3665 #define LANG_OPTION_WITH_MARSHALLING( \
3666  PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
3667  HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
3668  DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
3669  MERGER, EXTRACTOR, TABLE_INDEX) \
3670  PARSE_OPTION_WITH_MARSHALLING( \
3671  Args, Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \
3672  IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
3673 #include "clang/Driver/Options.inc"
3674 #undef LANG_OPTION_WITH_MARSHALLING
3675 
3676  if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
3677  StringRef Name = A->getValue();
3678  if (Name == "full" || Name == "branch") {
3679  Opts.CFProtectionBranch = 1;
3680  }
3681  }
3682 
3683  if ((Args.hasArg(OPT_fsycl_is_device) || Args.hasArg(OPT_fsycl_is_host)) &&
3684  !Args.hasArg(OPT_sycl_std_EQ)) {
3685  // If the user supplied -fsycl-is-device or -fsycl-is-host, but failed to
3686  // provide -sycl-std=, we want to default it to whatever the default SYCL
3687  // version is. I could not find a way to express this with the options
3688  // tablegen because we still want this value to be SYCL_None when the user
3689  // is not in device or host mode.
3690  Opts.setSYCLVersion(LangOptions::SYCL_Default);
3691  }
3692 
3693  if (Opts.ObjC) {
3694  if (Arg *arg = Args.getLastArg(OPT_fobjc_runtime_EQ)) {
3695  StringRef value = arg->getValue();
3696  if (Opts.ObjCRuntime.tryParse(value))
3697  Diags.Report(diag::err_drv_unknown_objc_runtime) << value;
3698  }
3699 
3700  if (Args.hasArg(OPT_fobjc_gc_only))
3701  Opts.setGC(LangOptions::GCOnly);
3702  else if (Args.hasArg(OPT_fobjc_gc))
3703  Opts.setGC(LangOptions::HybridGC);
3704  else if (Args.hasArg(OPT_fobjc_arc)) {
3705  Opts.ObjCAutoRefCount = 1;
3706  if (!Opts.ObjCRuntime.allowsARC())
3707  Diags.Report(diag::err_arc_unsupported_on_runtime);
3708  }
3709 
3710  // ObjCWeakRuntime tracks whether the runtime supports __weak, not
3711  // whether the feature is actually enabled. This is predominantly
3712  // determined by -fobjc-runtime, but we allow it to be overridden
3713  // from the command line for testing purposes.
3714  if (Args.hasArg(OPT_fobjc_runtime_has_weak))
3715  Opts.ObjCWeakRuntime = 1;
3716  else
3717  Opts.ObjCWeakRuntime = Opts.ObjCRuntime.allowsWeak();
3718 
3719  // ObjCWeak determines whether __weak is actually enabled.
3720  // Note that we allow -fno-objc-weak to disable this even in ARC mode.
3721  if (auto weakArg = Args.getLastArg(OPT_fobjc_weak, OPT_fno_objc_weak)) {
3722  if (!weakArg->getOption().matches(OPT_fobjc_weak)) {
3723  assert(!Opts.ObjCWeak);
3724  } else if (Opts.getGC() != LangOptions::NonGC) {
3725  Diags.Report(diag::err_objc_weak_with_gc);
3726  } else if (!Opts.ObjCWeakRuntime) {
3727  Diags.Report(diag::err_objc_weak_unsupported);
3728  } else {
3729  Opts.ObjCWeak = 1;
3730  }
3731  } else if (Opts.ObjCAutoRefCount) {
3732  Opts.ObjCWeak = Opts.ObjCWeakRuntime;
3733  }
3734 
3735  if (Args.hasArg(OPT_fobjc_subscripting_legacy_runtime))
3736  Opts.ObjCSubscriptingLegacyRuntime =
3738  }
3739 
3740  if (Arg *A = Args.getLastArg(options::OPT_fgnuc_version_EQ)) {
3741  // Check that the version has 1 to 3 components and the minor and patch
3742  // versions fit in two decimal digits.
3743  VersionTuple GNUCVer;
3744  bool Invalid = GNUCVer.tryParse(A->getValue());
3745  unsigned Major = GNUCVer.getMajor();
3746  unsigned Minor = GNUCVer.getMinor().value_or(0);
3747  unsigned Patch = GNUCVer.getSubminor().value_or(0);
3748  if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) {
3749  Diags.Report(diag::err_drv_invalid_value)
3750  << A->getAsString(Args) << A->getValue();
3751  }
3752  Opts.GNUCVersion = Major * 100 * 100 + Minor * 100 + Patch;
3753  }
3754 
3755  if (T.isOSAIX() && (Args.hasArg(OPT_mignore_xcoff_visibility)))
3756  Opts.IgnoreXCOFFVisibility = 1;
3757 
3758  if (Args.hasArg(OPT_ftrapv)) {
3759  Opts.setSignedOverflowBehavior(LangOptions::SOB_Trapping);
3760  // Set the handler, if one is specified.
3761  Opts.OverflowHandler =
3762  std::string(Args.getLastArgValue(OPT_ftrapv_handler));
3763  }
3764  else if (Args.hasArg(OPT_fwrapv))
3765  Opts.setSignedOverflowBehavior(LangOptions::SOB_Defined);
3766 
3767  Opts.MSCompatibilityVersion = 0;
3768  if (const Arg *A = Args.getLastArg(OPT_fms_compatibility_version)) {
3769  VersionTuple VT;
3770  if (VT.tryParse(A->getValue()))
3771  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
3772  << A->getValue();
3773  Opts.MSCompatibilityVersion = VT.getMajor() * 10000000 +
3774  VT.getMinor().value_or(0) * 100000 +
3775  VT.getSubminor().value_or(0);
3776  }
3777 
3778  // Mimicking gcc's behavior, trigraphs are only enabled if -trigraphs
3779  // is specified, or -std is set to a conforming mode.
3780  // Trigraphs are disabled by default in c++1z onwards.
3781  // For z/OS, trigraphs are enabled by default (without regard to the above).
3782  Opts.Trigraphs =
3783  (!Opts.GNUMode && !Opts.MSVCCompat && !Opts.CPlusPlus17) || T.isOSzOS();
3784  Opts.Trigraphs =
3785  Args.hasFlag(OPT_ftrigraphs, OPT_fno_trigraphs, Opts.Trigraphs);
3786 
3787  Opts.Blocks = Args.hasArg(OPT_fblocks) || (Opts.OpenCL
3788  && Opts.OpenCLVersion == 200);
3789 
3790  Opts.ConvergentFunctions = Opts.OpenCL || (Opts.CUDA && Opts.CUDAIsDevice) ||
3791  Opts.SYCLIsDevice ||
3792  Args.hasArg(OPT_fconvergent_functions);
3793 
3794  Opts.NoBuiltin = Args.hasArg(OPT_fno_builtin) || Opts.Freestanding;
3795  if (!Opts.NoBuiltin)
3797  if (Arg *A = Args.getLastArg(options::OPT_LongDouble_Group)) {
3798  if (A->getOption().matches(options::OPT_mlong_double_64))
3799  Opts.LongDoubleSize = 64;
3800  else if (A->getOption().matches(options::OPT_mlong_double_80))
3801  Opts.LongDoubleSize = 80;
3802  else if (A->getOption().matches(options::OPT_mlong_double_128))
3803  Opts.LongDoubleSize = 128;
3804  else
3805  Opts.LongDoubleSize = 0;
3806  }
3807  if (Opts.FastRelaxedMath || Opts.CLUnsafeMath)
3808  Opts.setDefaultFPContractMode(LangOptions::FPM_Fast);
3809 
3810  llvm::sort(Opts.ModuleFeatures);
3811 
3812  // -mrtd option
3813  if (Arg *A = Args.getLastArg(OPT_mrtd)) {
3814  if (Opts.getDefaultCallingConv() != LangOptions::DCC_None)
3815  Diags.Report(diag::err_drv_argument_not_allowed_with)
3816  << A->getSpelling() << "-fdefault-calling-conv";
3817  else {
3818  if (T.getArch() != llvm::Triple::x86)
3819  Diags.Report(diag::err_drv_argument_not_allowed_with)
3820  << A->getSpelling() << T.getTriple();
3821  else
3822  Opts.setDefaultCallingConv(LangOptions::DCC_StdCall);
3823  }
3824  }
3825 
3826  // Check if -fopenmp is specified and set default version to 5.0.
3827  Opts.OpenMP = Args.hasArg(OPT_fopenmp) ? 50 : 0;
3828  // Check if -fopenmp-simd is specified.
3829  bool IsSimdSpecified =
3830  Args.hasFlag(options::OPT_fopenmp_simd, options::OPT_fno_openmp_simd,
3831  /*Default=*/false);
3832  Opts.OpenMPSimd = !Opts.OpenMP && IsSimdSpecified;
3833  Opts.OpenMPUseTLS =
3834  Opts.OpenMP && !Args.hasArg(options::OPT_fnoopenmp_use_tls);
3835  Opts.OpenMPIsDevice =
3836  Opts.OpenMP && Args.hasArg(options::OPT_fopenmp_is_device);
3837  Opts.OpenMPIRBuilder =
3838  Opts.OpenMP && Args.hasArg(options::OPT_fopenmp_enable_irbuilder);
3839  bool IsTargetSpecified =
3840  Opts.OpenMPIsDevice || Args.hasArg(options::OPT_fopenmp_targets_EQ);
3841 
3842  Opts.ConvergentFunctions = Opts.ConvergentFunctions || Opts.OpenMPIsDevice;
3843 
3844  if (Opts.OpenMP || Opts.OpenMPSimd) {
3845  if (int Version = getLastArgIntValue(
3846  Args, OPT_fopenmp_version_EQ,
3847  (IsSimdSpecified || IsTargetSpecified) ? 50 : Opts.OpenMP, Diags))
3848  Opts.OpenMP = Version;
3849  // Provide diagnostic when a given target is not expected to be an OpenMP
3850  // device or host.
3851  if (!Opts.OpenMPIsDevice) {
3852  switch (T.getArch()) {
3853  default:
3854  break;
3855  // Add unsupported host targets here:
3856  case llvm::Triple::nvptx:
3857  case llvm::Triple::nvptx64:
3858  Diags.Report(diag::err_drv_omp_host_target_not_supported) << T.str();
3859  break;
3860  }
3861  }
3862  }
3863 
3864  // Set the flag to prevent the implementation from emitting device exception
3865  // handling code for those requiring so.
3866  if ((Opts.OpenMPIsDevice && (T.isNVPTX() || T.isAMDGCN())) ||
3867  Opts.OpenCLCPlusPlus) {
3868 
3869  Opts.Exceptions = 0;
3870  Opts.CXXExceptions = 0;
3871  }
3872  if (Opts.OpenMPIsDevice && T.isNVPTX()) {
3873  Opts.OpenMPCUDANumSMs =
3874  getLastArgIntValue(Args, options::OPT_fopenmp_cuda_number_of_sm_EQ,
3875  Opts.OpenMPCUDANumSMs, Diags);
3876  Opts.OpenMPCUDABlocksPerSM =
3877  getLastArgIntValue(Args, options::OPT_fopenmp_cuda_blocks_per_sm_EQ,
3878  Opts.OpenMPCUDABlocksPerSM, Diags);
3879  Opts.OpenMPCUDAReductionBufNum = getLastArgIntValue(
3880  Args, options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ,
3881  Opts.OpenMPCUDAReductionBufNum, Diags);
3882  }
3883 
3884  // Set the value of the debugging flag used in the new offloading device RTL.
3885  // Set either by a specific value or to a default if not specified.
3886  if (Opts.OpenMPIsDevice && (Args.hasArg(OPT_fopenmp_target_debug) ||
3887  Args.hasArg(OPT_fopenmp_target_debug_EQ))) {
3888  Opts.OpenMPTargetDebug = getLastArgIntValue(
3889  Args, OPT_fopenmp_target_debug_EQ, Opts.OpenMPTargetDebug, Diags);
3890  if (!Opts.OpenMPTargetDebug && Args.hasArg(OPT_fopenmp_target_debug))
3891  Opts.OpenMPTargetDebug = 1;
3892  }
3893 
3894  if (Opts.OpenMPIsDevice) {
3895  if (Args.hasArg(OPT_fopenmp_assume_teams_oversubscription))
3896  Opts.OpenMPTeamSubscription = true;
3897  if (Args.hasArg(OPT_fopenmp_assume_threads_oversubscription))
3898  Opts.OpenMPThreadSubscription = true;
3899  }
3900 
3901  // Get the OpenMP target triples if any.
3902  if (Arg *A = Args.getLastArg(options::OPT_fopenmp_targets_EQ)) {
3903  enum ArchPtrSize { Arch16Bit, Arch32Bit, Arch64Bit };
3904  auto getArchPtrSize = [](const llvm::Triple &T) {
3905  if (T.isArch16Bit())
3906  return Arch16Bit;
3907  if (T.isArch32Bit())
3908  return Arch32Bit;
3909  assert(T.isArch64Bit() && "Expected 64-bit architecture");
3910  return Arch64Bit;
3911  };
3912 
3913  for (unsigned i = 0; i < A->getNumValues(); ++i) {
3914  llvm::Triple TT(A->getValue(i));
3915 
3916  if (TT.getArch() == llvm::Triple::UnknownArch ||
3917  !(TT.getArch() == llvm::Triple::aarch64 || TT.isPPC() ||
3918  TT.getArch() == llvm::Triple::nvptx ||
3919  TT.getArch() == llvm::Triple::nvptx64 ||
3920  TT.getArch() == llvm::Triple::amdgcn ||
3921  TT.getArch() == llvm::Triple::x86 ||
3922  TT.getArch() == llvm::Triple::x86_64))
3923  Diags.Report(diag::err_drv_invalid_omp_target) << A->getValue(i);
3924  else if (getArchPtrSize(T) != getArchPtrSize(TT))
3925  Diags.Report(diag::err_drv_incompatible_omp_arch)
3926  << A->getValue(i) << T.str();
3927  else
3928  Opts.OMPTargetTriples.push_back(TT);
3929  }
3930  }
3931 
3932  // Get OpenMP host file path if any and report if a non existent file is
3933  // found
3934  if (Arg *A = Args.getLastArg(options::OPT_fopenmp_host_ir_file_path)) {
3935  Opts.OMPHostIRFile = A->getValue();
3936  if (!llvm::sys::fs::exists(Opts.OMPHostIRFile))
3937  Diags.Report(diag::err_drv_omp_host_ir_file_not_found)
3938  << Opts.OMPHostIRFile;
3939  }
3940 
3941  // Set CUDA mode for OpenMP target NVPTX/AMDGCN if specified in options
3942  Opts.OpenMPCUDAMode = Opts.OpenMPIsDevice && (T.isNVPTX() || T.isAMDGCN()) &&
3943  Args.hasArg(options::OPT_fopenmp_cuda_mode);
3944 
3945  // FIXME: Eliminate this dependency.
3946  unsigned Opt = getOptimizationLevel(Args, IK, Diags),
3947  OptSize = getOptimizationLevelSize(Args);
3948  Opts.Optimize = Opt != 0;
3949  Opts.OptimizeSize = OptSize != 0;
3950 
3951  // This is the __NO_INLINE__ define, which just depends on things like the
3952  // optimization level and -fno-inline, not actually whether the backend has
3953  // inlining enabled.
3954  Opts.NoInlineDefine = !Opts.Optimize;
3955  if (Arg *InlineArg = Args.getLastArg(
3956  options::OPT_finline_functions, options::OPT_finline_hint_functions,
3957  options::OPT_fno_inline_functions, options::OPT_fno_inline))
3958  if (InlineArg->getOption().matches(options::OPT_fno_inline))
3959  Opts.NoInlineDefine = true;
3960 
3961  if (Arg *A = Args.getLastArg(OPT_ffp_contract)) {
3962  StringRef Val = A->getValue();
3963  if (Val == "fast")
3964  Opts.setDefaultFPContractMode(LangOptions::FPM_Fast);
3965  else if (Val == "on")
3966  Opts.setDefaultFPContractMode(LangOptions::FPM_On);
3967  else if (Val == "off")
3968  Opts.setDefaultFPContractMode(LangOptions::FPM_Off);
3969  else if (Val == "fast-honor-pragmas")
3970  Opts.setDefaultFPContractMode(LangOptions::FPM_FastHonorPragmas);
3971  else
3972  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
3973  }
3974 
3975  // Parse -fsanitize= arguments.
3976  parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ),
3977  Diags, Opts.Sanitize);
3978  Opts.NoSanitizeFiles = Args.getAllArgValues(OPT_fsanitize_ignorelist_EQ);
3979  std::vector<std::string> systemIgnorelists =
3980  Args.getAllArgValues(OPT_fsanitize_system_ignorelist_EQ);
3981  Opts.NoSanitizeFiles.insert(Opts.NoSanitizeFiles.end(),
3982  systemIgnorelists.begin(),
3983  systemIgnorelists.end());
3984 
3985  if (Arg *A = Args.getLastArg(OPT_fclang_abi_compat_EQ)) {
3986  Opts.setClangABICompat(LangOptions::ClangABI::Latest);
3987 
3988  StringRef Ver = A->getValue();
3989  std::pair<StringRef, StringRef> VerParts = Ver.split('.');
3990  unsigned Major, Minor = 0;
3991 
3992  // Check the version number is valid: either 3.x (0 <= x <= 9) or
3993  // y or y.0 (4 <= y <= current version).
3994  if (!VerParts.first.startswith("0") &&
3995  !VerParts.first.getAsInteger(10, Major) &&
3996  3 <= Major && Major <= CLANG_VERSION_MAJOR &&
3997  (Major == 3 ? VerParts.second.size() == 1 &&
3998  !VerParts.second.getAsInteger(10, Minor)
3999  : VerParts.first.size() == Ver.size() ||
4000  VerParts.second == "0")) {
4001  // Got a valid version number.
4002  if (Major == 3 && Minor <= 8)
4003  Opts.setClangABICompat(LangOptions::ClangABI::Ver3_8);
4004  else if (Major <= 4)
4005  Opts.setClangABICompat(LangOptions::ClangABI::Ver4);
4006  else if (Major <= 6)
4007  Opts.setClangABICompat(LangOptions::ClangABI::Ver6);
4008  else if (Major <= 7)
4009  Opts.setClangABICompat(LangOptions::ClangABI::Ver7);
4010  else if (Major <= 9)
4011  Opts.setClangABICompat(LangOptions::ClangABI::Ver9);
4012  else if (Major <= 11)
4013  Opts.setClangABICompat(LangOptions::ClangABI::Ver11);
4014  else if (Major <= 12)
4015  Opts.setClangABICompat(LangOptions::ClangABI::Ver12);
4016  else if (Major <= 14)
4017  Opts.setClangABICompat(LangOptions::ClangABI::Ver14);
4018  else if (Major <= 15)
4019  Opts.setClangABICompat(LangOptions::ClangABI::Ver15);
4020  } else if (Ver != "latest") {
4021  Diags.Report(diag::err_drv_invalid_value)
4022  << A->getAsString(Args) << A->getValue();
4023  }
4024  }
4025 
4026  if (Arg *A = Args.getLastArg(OPT_msign_return_address_EQ)) {
4027  StringRef SignScope = A->getValue();
4028 
4029  if (SignScope.equals_insensitive("none"))
4030  Opts.setSignReturnAddressScope(
4032  else if (SignScope.equals_insensitive("all"))
4033  Opts.setSignReturnAddressScope(
4035  else if (SignScope.equals_insensitive("non-leaf"))
4036  Opts.setSignReturnAddressScope(
4038  else
4039  Diags.Report(diag::err_drv_invalid_value)
4040  << A->getAsString(Args) << SignScope;
4041 
4042  if (Arg *A = Args.getLastArg(OPT_msign_return_address_key_EQ)) {
4043  StringRef SignKey = A->getValue();
4044  if (!SignScope.empty() && !SignKey.empty()) {
4045  if (SignKey.equals_insensitive("a_key"))
4046  Opts.setSignReturnAddressKey(
4048  else if (SignKey.equals_insensitive("b_key"))
4049  Opts.setSignReturnAddressKey(
4051  else
4052  Diags.Report(diag::err_drv_invalid_value)
4053  << A->getAsString(Args) << SignKey;
4054  }
4055  }
4056  }
4057 
4058  // The value can be empty, which indicates the system default should be used.
4059  StringRef CXXABI = Args.getLastArgValue(OPT_fcxx_abi_EQ);
4060  if (!CXXABI.empty()) {
4061  if (!TargetCXXABI::isABI(CXXABI)) {
4062  Diags.Report(diag::err_invalid_cxx_abi) << CXXABI;
4063  } else {
4066  Diags.Report(diag::err_unsupported_cxx_abi) << CXXABI << T.str();
4067  else
4068  Opts.CXXABI = Kind;
4069  }
4070  }
4071 
4072  Opts.RelativeCXXABIVTables =
4073  Args.hasFlag(options::OPT_fexperimental_relative_cxx_abi_vtables,
4074  options::OPT_fno_experimental_relative_cxx_abi_vtables,
4076 
4077  for (const auto &A : Args.getAllArgValues(OPT_fmacro_prefix_map_EQ)) {
4078  auto Split = StringRef(A).split('=');
4079  Opts.MacroPrefixMap.insert(
4080  {std::string(Split.first), std::string(Split.second)});
4081  }
4082 
4083  Opts.UseTargetPathSeparator =
4084  !Args.getLastArg(OPT_fno_file_reproducible) &&
4085  (Args.getLastArg(OPT_ffile_compilation_dir_EQ) ||
4086  Args.getLastArg(OPT_fmacro_prefix_map_EQ) ||
4087  Args.getLastArg(OPT_ffile_reproducible));
4088 
4089  // Error if -mvscale-min is unbounded.
4090  if (Arg *A = Args.getLastArg(options::OPT_mvscale_min_EQ)) {
4091  unsigned VScaleMin;
4092  if (StringRef(A->getValue()).getAsInteger(10, VScaleMin) || VScaleMin == 0)
4093  Diags.Report(diag::err_cc1_unbounded_vscale_min);
4094  }
4095 
4096  if (const Arg *A = Args.getLastArg(OPT_frandomize_layout_seed_file_EQ)) {
4097  std::ifstream SeedFile(A->getValue(0));
4098 
4099  if (!SeedFile.is_open())
4100  Diags.Report(diag::err_drv_cannot_open_randomize_layout_seed_file)
4101  << A->getValue(0);
4102 
4103  std::getline(SeedFile, Opts.RandstructSeed);
4104  }
4105 
4106  if (const Arg *A = Args.getLastArg(OPT_frandomize_layout_seed_EQ))
4107  Opts.RandstructSeed = A->getValue(0);
4108 
4109  // Validate options for HLSL
4110  if (Opts.HLSL) {
4111  bool SupportedTarget = T.getArch() == llvm::Triple::dxil &&
4112  T.getOS() == llvm::Triple::ShaderModel;
4113  if (!SupportedTarget)
4114  Diags.Report(diag::err_drv_hlsl_unsupported_target) << T.str();
4115  }
4116 
4117  return Diags.getNumErrors() == NumErrorsBefore;
4118 }
4119 
4121  switch (Action) {
4122  case frontend::ASTDeclList:
4123  case frontend::ASTDump:
4124  case frontend::ASTPrint:
4125  case frontend::ASTView:
4127  case frontend::EmitBC:
4128  case frontend::EmitHTML:
4129  case frontend::EmitLLVM:
4132  case frontend::EmitObj:
4133  case frontend::ExtractAPI:
4134  case frontend::FixIt:
4138  case frontend::GeneratePCH:
4142  case frontend::VerifyPCH:
4144  case frontend::RewriteObjC:
4145  case frontend::RewriteTest:
4146  case frontend::RunAnalysis:
4149  return false;
4150 
4153  case frontend::DumpTokens:
4154  case frontend::InitOnly:
4160  return true;
4161  }
4162  llvm_unreachable("invalid frontend action");
4163 }
4164 
4168  const LangOptions &LangOpts,
4169  const FrontendOptions &FrontendOpts,
4170  const CodeGenOptions &CodeGenOpts) {
4171  PreprocessorOptions *PreprocessorOpts = &Opts;
4172 
4173 #define PREPROCESSOR_OPTION_WITH_MARSHALLING( \
4174  PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
4175  HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
4176  DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
4177  MERGER, EXTRACTOR, TABLE_INDEX) \
4178  GENERATE_OPTION_WITH_MARSHALLING( \
4179  Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \
4180  IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
4181 #include "clang/Driver/Options.inc"
4182 #undef PREPROCESSOR_OPTION_WITH_MARSHALLING
4183 
4184  if (Opts.PCHWithHdrStop && !Opts.PCHWithHdrStopCreate)
4185  GenerateArg(Args, OPT_pch_through_hdrstop_use, SA);
4186 
4187  for (const auto &D : Opts.DeserializedPCHDeclsToErrorOn)
4188  GenerateArg(Args, OPT_error_on_deserialized_pch_decl, D, SA);
4189 
4190  if (Opts.PrecompiledPreambleBytes != std::make_pair(0u, false))
4191  GenerateArg(Args, OPT_preamble_bytes_EQ,
4192  Twine(Opts.PrecompiledPreambleBytes.first) + "," +
4193  (Opts.PrecompiledPreambleBytes.second ? "1" : "0"),
4194  SA);
4195 
4196  for (const auto &M : Opts.Macros) {
4197  // Don't generate __CET__ macro definitions. They are implied by the
4198  // -fcf-protection option that is generated elsewhere.
4199  if (M.first == "__CET__=1" && !M.second &&
4200  !CodeGenOpts.CFProtectionReturn && CodeGenOpts.CFProtectionBranch)
4201  continue;
4202  if (M.first == "__CET__=2" && !M.second && CodeGenOpts.CFProtectionReturn &&
4203  !CodeGenOpts.CFProtectionBranch)
4204  continue;
4205  if (M.first == "__CET__=3" && !M.second && CodeGenOpts.CFProtectionReturn &&
4206  CodeGenOpts.CFProtectionBranch)
4207  continue;
4208 
4209  GenerateArg(Args, M.second ? OPT_U : OPT_D, M.first, SA);
4210  }
4211 
4212  for (const auto &I : Opts.Includes) {
4213  // Don't generate OpenCL includes. They are implied by other flags that are
4214  // generated elsewhere.
4215  if (LangOpts.OpenCL && LangOpts.IncludeDefaultHeader &&
4216  ((LangOpts.DeclareOpenCLBuiltins && I == "opencl-c-base.h") ||
4217  I == "opencl-c.h"))
4218  continue;
4219  // Don't generate HLSL includes. They are implied by other flags that are
4220  // generated elsewhere.
4221  if (LangOpts.HLSL && I == "hlsl.h")
4222  continue;
4223 
4224  GenerateArg(Args, OPT_include, I, SA);
4225  }
4226 
4227  for (const auto &CI : Opts.ChainedIncludes)
4228  GenerateArg(Args, OPT_chain_include, CI, SA);
4229 
4230  for (const auto &RF : Opts.RemappedFiles)
4231  GenerateArg(Args, OPT_remap_file, RF.first + ";" + RF.second, SA);
4232 
4233  if (Opts.SourceDateEpoch)
4234  GenerateArg(Args, OPT_source_date_epoch, Twine(*Opts.SourceDateEpoch), SA);
4235 
4236  // Don't handle LexEditorPlaceholders. It is implied by the action that is
4237  // generated elsewhere.
4238 }
4239 
4240 static bool ParsePreprocessorArgs(PreprocessorOptions &Opts, ArgList &Args,
4241  DiagnosticsEngine &Diags,
4243  const FrontendOptions &FrontendOpts) {
4244  unsigned NumErrorsBefore = Diags.getNumErrors();
4245 
4246  PreprocessorOptions *PreprocessorOpts = &Opts;
4247 
4248 #define PREPROCESSOR_OPTION_WITH_MARSHALLING( \
4249  PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
4250  HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
4251  DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
4252  MERGER, EXTRACTOR, TABLE_INDEX) \
4253  PARSE_OPTION_WITH_MARSHALLING( \
4254  Args, Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \
4255  IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
4256 #include "clang/Driver/Options.inc"
4257 #undef PREPROCESSOR_OPTION_WITH_MARSHALLING
4258 
4259  Opts.PCHWithHdrStop = Args.hasArg(OPT_pch_through_hdrstop_create) ||
4260  Args.hasArg(OPT_pch_through_hdrstop_use);
4261 
4262  for (const auto *A : Args.filtered(OPT_error_on_deserialized_pch_decl))
4263  Opts.DeserializedPCHDeclsToErrorOn.insert(A->getValue());
4264 
4265  if (const Arg *A = Args.getLastArg(OPT_preamble_bytes_EQ)) {
4266  StringRef Value(A->getValue());
4267  size_t Comma = Value.find(',');
4268  unsigned Bytes = 0;
4269  unsigned EndOfLine = 0;
4270 
4271  if (Comma == StringRef::npos ||
4272  Value.substr(0, Comma).getAsInteger(10, Bytes) ||
4273  Value.substr(Comma + 1).getAsInteger(10, EndOfLine))
4274  Diags.Report(diag::err_drv_preamble_format);
4275  else {
4276  Opts.PrecompiledPreambleBytes.first = Bytes;
4277  Opts.PrecompiledPreambleBytes.second = (EndOfLine != 0);
4278  }
4279  }
4280 
4281  // Add the __CET__ macro if a CFProtection option is set.
4282  if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
4283  StringRef Name = A->getValue();
4284  if (Name == "branch")
4285  Opts.addMacroDef("__CET__=1");
4286  else if (Name == "return")
4287  Opts.addMacroDef("__CET__=2");
4288  else if (Name == "full")
4289  Opts.addMacroDef("__CET__=3");
4290  }
4291 
4292  // Add macros from the command line.
4293  for (const auto *A : Args.filtered(OPT_D, OPT_U)) {
4294  if (A->getOption().matches(OPT_D))
4295  Opts.addMacroDef(A->getValue());
4296  else
4297  Opts.addMacroUndef(A->getValue());
4298  }
4299 
4300  // Add the ordered list of -includes.
4301  for (const auto *A : Args.filtered(OPT_include))
4302  Opts.Includes.emplace_back(A->getValue());
4303 
4304  for (const auto *A : Args.filtered(OPT_chain_include))
4305  Opts.ChainedIncludes.emplace_back(A->getValue());
4306 
4307  for (const auto *A : Args.filtered(OPT_remap_file)) {
4308  std::pair<StringRef, StringRef> Split = StringRef(A->getValue()).split(';');
4309 
4310  if (Split.second.empty()) {
4311  Diags.Report(diag::err_drv_invalid_remap_file) << A->getAsString(Args);
4312  continue;
4313  }
4314 
4315  Opts.addRemappedFile(Split.first, Split.second);
4316  }
4317 
4318  if (const Arg *A = Args.getLastArg(OPT_source_date_epoch)) {
4319  StringRef Epoch = A->getValue();
4320  // SOURCE_DATE_EPOCH, if specified, must be a non-negative decimal integer.
4321  // On time64 systems, pick 253402300799 (the UNIX timestamp of
4322  // 9999-12-31T23:59:59Z) as the upper bound.
4323  const uint64_t MaxTimestamp =
4324  std::min<uint64_t>(std::numeric_limits<time_t>::max(), 253402300799);
4325  uint64_t V;
4326  if (Epoch.getAsInteger(10, V) || V > MaxTimestamp) {
4327  Diags.Report(diag::err_fe_invalid_source_date_epoch)
4328  << Epoch << MaxTimestamp;
4329  } else {
4330  Opts.SourceDateEpoch = V;
4331  }
4332  }
4333 
4334  // Always avoid lexing editor placeholders when we're just running the
4335  // preprocessor as we never want to emit the
4336  // "editor placeholder in source file" error in PP only mode.
4338  Opts.LexEditorPlaceholders = false;
4339 
4340  return Diags.getNumErrors() == NumErrorsBefore;
4341 }
4342 
4346  const PreprocessorOutputOptions &PreprocessorOutputOpts = Opts;
4347 
4348 #define PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING( \
4349  PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
4350  HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
4351  DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
4352  MERGER, EXTRACTOR, TABLE_INDEX) \
4353  GENERATE_OPTION_WITH_MARSHALLING( \
4354  Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \
4355  IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
4356 #include "clang/Driver/Options.inc"
4357 #undef PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING
4358 
4359  bool Generate_dM = isStrictlyPreprocessorAction(Action) && !Opts.ShowCPP;
4360  if (Generate_dM)
4361  GenerateArg(Args, OPT_dM, SA);
4362  if (!Generate_dM && Opts.ShowMacros)
4363  GenerateArg(Args, OPT_dD, SA);
4364  if (Opts.DirectivesOnly)
4365  GenerateArg(Args, OPT_fdirectives_only, SA);
4366 }
4367 
4369  ArgList &Args, DiagnosticsEngine &Diags,
4371  unsigned NumErrorsBefore = Diags.getNumErrors();
4372 
4373  PreprocessorOutputOptions &PreprocessorOutputOpts = Opts;
4374 
4375 #define PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING( \
4376  PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
4377  HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
4378  DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
4379  MERGER, EXTRACTOR, TABLE_INDEX) \
4380  PARSE_OPTION_WITH_MARSHALLING( \
4381  Args, Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \
4382  IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
4383 #include "clang/Driver/Options.inc"
4384 #undef PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING
4385 
4386  Opts.ShowCPP = isStrictlyPreprocessorAction(Action) && !Args.hasArg(OPT_dM);
4387  Opts.ShowMacros = Args.hasArg(OPT_dM) || Args.hasArg(OPT_dD);
4388  Opts.DirectivesOnly = Args.hasArg(OPT_fdirectives_only);
4389 
4390  return Diags.getNumErrors() == NumErrorsBefore;
4391 }
4392 
4393 static void GenerateTargetArgs(const TargetOptions &Opts,
4396  const TargetOptions *TargetOpts = &Opts;
4397 #define TARGET_OPTION_WITH_MARSHALLING( \
4398  PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
4399  HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
4400  DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
4401  MERGER, EXTRACTOR, TABLE_INDEX) \
4402  GENERATE_OPTION_WITH_MARSHALLING( \
4403  Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \
4404  IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
4405 #include "clang/Driver/Options.inc"
4406 #undef TARGET_OPTION_WITH_MARSHALLING
4407 
4408  if (!Opts.SDKVersion.empty())
4409  GenerateArg(Args, OPT_target_sdk_version_EQ, Opts.SDKVersion.getAsString(),
4410  SA);
4411  if (!Opts.DarwinTargetVariantSDKVersion.empty())
4412  GenerateArg(Args, OPT_darwin_target_variant_sdk_version_EQ,
4413  Opts.DarwinTargetVariantSDKVersion.getAsString(), SA);
4414 }
4415 
4416 static bool ParseTargetArgs(TargetOptions &Opts, ArgList &Args,
4417  DiagnosticsEngine &Diags) {
4418  unsigned NumErrorsBefore = Diags.getNumErrors();
4419 
4420  TargetOptions *TargetOpts = &Opts;
4421 
4422 #define TARGET_OPTION_WITH_MARSHALLING( \
4423  PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
4424  HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
4425  DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
4426  MERGER, EXTRACTOR, TABLE_INDEX) \
4427  PARSE_OPTION_WITH_MARSHALLING( \
4428  Args, Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \
4429  IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
4430 #include "clang/Driver/Options.inc"
4431 #undef TARGET_OPTION_WITH_MARSHALLING
4432 
4433  if (Arg *A = Args.getLastArg(options::OPT_target_sdk_version_EQ)) {
4434  llvm::VersionTuple Version;
4435  if (Version.tryParse(A->getValue()))
4436  Diags.Report(diag::err_drv_invalid_value)
4437  << A->getAsString(Args) << A->getValue();
4438  else
4439  Opts.SDKVersion = Version;
4440  }
4441  if (Arg *A =
4442  Args.getLastArg(options::OPT_darwin_target_variant_sdk_version_EQ)) {
4443  llvm::VersionTuple Version;
4444  if (Version.tryParse(A->getValue()))
4445  Diags.Report(diag::err_drv_invalid_value)
4446  << A->getAsString(Args) << A->getValue();
4447  else
4448  Opts.DarwinTargetVariantSDKVersion = Version;
4449  }
4450 
4451  return Diags.getNumErrors() == NumErrorsBefore;
4452 }
4453 
4454 bool CompilerInvocation::CreateFromArgsImpl(
4455  CompilerInvocation &Res, ArrayRef<const char *> CommandLineArgs,
4456  DiagnosticsEngine &Diags, const char *Argv0) {
4457  unsigned NumErrorsBefore = Diags.getNumErrors();
4458 
4459  // Parse the arguments.
4460  const OptTable &Opts = getDriverOptTable();
4461  const unsigned IncludedFlagsBitmask = options::CC1Option;
4462  unsigned MissingArgIndex, MissingArgCount;
4463  InputArgList Args = Opts.ParseArgs(CommandLineArgs, MissingArgIndex,
4464  MissingArgCount, IncludedFlagsBitmask);
4465  LangOptions &LangOpts = *Res.getLangOpts();
4466 
4467  // Check for missing argument error.
4468  if (MissingArgCount)
4469  Diags.Report(diag::err_drv_missing_argument)
4470  << Args.getArgString(MissingArgIndex) << MissingArgCount;
4471 
4472  // Issue errors on unknown arguments.
4473  for (const auto *A : Args.filtered(OPT_UNKNOWN)) {
4474  auto ArgString = A->getAsString(Args);
4475  std::string Nearest;
4476  if (Opts.findNearest(ArgString, Nearest, IncludedFlagsBitmask) > 1)
4477  Diags.Report(diag::err_drv_unknown_argument) << ArgString;
4478  else
4479  Diags.Report(diag::err_drv_unknown_argument_with_suggestion)
4480  << ArgString << Nearest;
4481  }
4482 
4483  ParseFileSystemArgs(Res.getFileSystemOpts(), Args, Diags);
4484  ParseMigratorArgs(Res.getMigratorOpts(), Args, Diags);
4485  ParseAnalyzerArgs(*Res.getAnalyzerOpts(), Args, Diags);
4486  ParseDiagnosticArgs(Res.getDiagnosticOpts(), Args, &Diags,
4487  /*DefaultDiagColor=*/false);
4488  ParseFrontendArgs(Res.getFrontendOpts(), Args, Diags, LangOpts.IsHeaderFile);
4489  // FIXME: We shouldn't have to pass the DashX option around here
4490  InputKind DashX = Res.getFrontendOpts().DashX;
4491  ParseTargetArgs(Res.getTargetOpts(), Args, Diags);
4492  llvm::Triple T(Res.getTargetOpts().Triple);
4493  ParseHeaderSearchArgs(Res.getHeaderSearchOpts(), Args, Diags,
4495 
4496  ParseLangArgs(LangOpts, Args, DashX, T, Res.getPreprocessorOpts().Includes,
4497  Diags);
4499  LangOpts.ObjCExceptions = 1;
4500 
4501  for (auto Warning : Res.getDiagnosticOpts().Warnings) {
4502  if (Warning == "misexpect" &&
4503  !Diags.isIgnored(diag::warn_profile_data_misexpect, SourceLocation())) {
4504  Res.getCodeGenOpts().MisExpect = true;
4505  }
4506  }
4507 
4508  if (LangOpts.CUDA) {
4509  // During CUDA device-side compilation, the aux triple is the
4510  // triple used for host compilation.
4511  if (LangOpts.CUDAIsDevice)
4513  }
4514 
4515  // Set the triple of the host for OpenMP device compile.
4516  if (LangOpts.OpenMPIsDevice)
4518 
4519  ParseCodeGenArgs(Res.getCodeGenOpts(), Args, DashX, Diags, T,
4521 
4522  // FIXME: Override value name discarding when asan or msan is used because the
4523  // backend passes depend on the name of the alloca in order to print out
4524  // names.
4525  Res.getCodeGenOpts().DiscardValueNames &=
4526  !LangOpts.Sanitize.has(SanitizerKind::Address) &&
4527  !LangOpts.Sanitize.has(SanitizerKind::KernelAddress) &&
4528  !LangOpts.Sanitize.has(SanitizerKind::Memory) &&
4529  !LangOpts.Sanitize.has(SanitizerKind::KernelMemory);
4530 
4531  ParsePreprocessorArgs(Res.getPreprocessorOpts(), Args, Diags,
4533  Res.getFrontendOpts());
4536 
4540  if (!Res.getDependencyOutputOpts().OutputFile.empty() &&
4541  Res.getDependencyOutputOpts().Targets.empty())
4542  Diags.Report(diag::err_fe_dependency_file_requires_MT);
4543 
4544  // If sanitizer is enabled, disable OPT_ffine_grained_bitfield_accesses.
4545  if (Res.getCodeGenOpts().FineGrainedBitfieldAccesses &&
4546  !Res.getLangOpts()->Sanitize.empty()) {
4547  Res.getCodeGenOpts().FineGrainedBitfieldAccesses = false;
4548  Diags.Report(diag::warn_drv_fine_grained_bitfield_accesses_ignored);
4549  }
4550 
4551  // Store the command-line for using in the CodeView backend.
4552  if (Res.getCodeGenOpts().CodeViewCommandLine) {
4553  Res.getCodeGenOpts().Argv0 = Argv0;
4554  append_range(Res.getCodeGenOpts().CommandLineArgs, CommandLineArgs);
4555  }
4556 
4557  FixupInvocation(Res, Diags, Args, DashX);
4558 
4559  return Diags.getNumErrors() == NumErrorsBefore;
4560 }
4561 
4563  ArrayRef<const char *> CommandLineArgs,
4564  DiagnosticsEngine &Diags,
4565  const char *Argv0) {
4566  CompilerInvocation DummyInvocation;
4567 
4568  return RoundTrip(
4569  [](CompilerInvocation &Invocation, ArrayRef<const char *> CommandLineArgs,
4570  DiagnosticsEngine &Diags, const char *Argv0) {
4571  return CreateFromArgsImpl(Invocation, CommandLineArgs, Diags, Argv0);
4572  },
4573  [](CompilerInvocation &Invocation, SmallVectorImpl<const char *> &Args,
4574  StringAllocator SA) {
4575  Args.push_back("-cc1");
4576  Invocation.generateCC1CommandLine(Args, SA);
4577  },
4578  Invocation, DummyInvocation, CommandLineArgs, Diags, Argv0);
4579 }
4580 
4582  // FIXME: Consider using SHA1 instead of MD5.
4583  llvm::HashBuilder<llvm::MD5, llvm::support::endianness::native> HBuilder;
4584 
4585  // Note: For QoI reasons, the things we use as a hash here should all be
4586  // dumped via the -module-info flag.
4587 
4588  // Start the signature with the compiler version.
4589  HBuilder.add(getClangFullRepositoryVersion());
4590 
4591  // Also include the serialization version, in case LLVM_APPEND_VC_REV is off
4592  // and getClangFullRepositoryVersion() doesn't include git revision.
4594 
4595  // Extend the signature with the language options
4596 #define LANGOPT(Name, Bits, Default, Description) HBuilder.add(LangOpts->Name);
4597 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4598  HBuilder.add(static_cast<unsigned>(LangOpts->get##Name()));
4599 #define BENIGN_LANGOPT(Name, Bits, Default, Description)
4600 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
4601 #include "clang/Basic/LangOptions.def"
4602 
4603  HBuilder.addRange(LangOpts->ModuleFeatures);
4604 
4605  HBuilder.add(LangOpts->ObjCRuntime);
4606  HBuilder.addRange(LangOpts->CommentOpts.BlockCommandNames);
4607 
4608  // Extend the signature with the target options.
4609  HBuilder.add(TargetOpts->Triple, TargetOpts->CPU, TargetOpts->TuneCPU,
4610  TargetOpts->ABI);
4611  HBuilder.addRange(TargetOpts->FeaturesAsWritten);
4612 
4613  // Extend the signature with preprocessor options.
4614  const PreprocessorOptions &ppOpts = getPreprocessorOpts();
4615  HBuilder.add(ppOpts.UsePredefines, ppOpts.DetailedRecord);
4616 
4617  const HeaderSearchOptions &hsOpts = getHeaderSearchOpts();
4618  for (const auto &Macro : getPreprocessorOpts().Macros) {
4619  // If we're supposed to ignore this macro for the purposes of modules,
4620  // don't put it into the hash.
4621  if (!hsOpts.ModulesIgnoreMacros.empty()) {
4622  // Check whether we're ignoring this macro.
4623  StringRef MacroDef = Macro.first;
4624  if (hsOpts.ModulesIgnoreMacros.count(
4625  llvm::CachedHashString(MacroDef.split('=').first)))
4626  continue;
4627  }
4628 
4629  HBuilder.add(Macro);
4630  }
4631 
4632  // Extend the signature with the sysroot and other header search options.
4633  HBuilder.add(hsOpts.Sysroot, hsOpts.ModuleFormat, hsOpts.UseDebugInfo,
4635  hsOpts.UseStandardCXXIncludes, hsOpts.UseLibcxx,
4637  HBuilder.add(hsOpts.ResourceDir);
4638 
4639  if (hsOpts.ModulesStrictContextHash) {
4640  HBuilder.addRange(hsOpts.SystemHeaderPrefixes);
4641  HBuilder.addRange(hsOpts.UserEntries);
4642 
4643  const DiagnosticOptions &diagOpts = getDiagnosticOpts();
4644 #define DIAGOPT(Name, Bits, Default) HBuilder.add(diagOpts.Name);
4645 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
4646  HBuilder.add(diagOpts.get##Name());
4647 #include "clang/Basic/DiagnosticOptions.def"
4648 #undef DIAGOPT
4649 #undef ENUM_DIAGOPT
4650  }
4651 
4652  // Extend the signature with the user build path.
4653  HBuilder.add(hsOpts.ModuleUserBuildPath);
4654 
4655  // Extend the signature with the module file extensions.
4656  for (const auto &ext : getFrontendOpts().ModuleFileExtensions)
4657  ext->hashExtension(HBuilder);
4658 
4659  // When compiling with -gmodules, also hash -fdebug-prefix-map as it
4660  // affects the debug info in the PCM.
4661  if (getCodeGenOpts().DebugTypeExtRefs)
4662  HBuilder.addRange(getCodeGenOpts().DebugPrefixMap);
4663 
4664  // Extend the signature with the enabled sanitizers, if at least one is
4665  // enabled. Sanitizers which cannot affect AST generation aren't hashed.
4666  SanitizerSet SanHash = LangOpts->Sanitize;
4667  SanHash.clear(getPPTransparentSanitizers());
4668  if (!SanHash.empty())
4669  HBuilder.add(SanHash.Mask);
4670 
4671  llvm::MD5::MD5Result Result;
4672  HBuilder.getHasher().final(Result);
4673  uint64_t Hash = Result.high() ^ Result.low();
4674  return toString(llvm::APInt(64, Hash), 36, /*Signed=*/false);
4675 }
4676 
4679  llvm::Triple T(TargetOpts->Triple);
4680 
4683  GenerateAnalyzerArgs(*AnalyzerOpts, Args, SA);
4684  GenerateDiagnosticArgs(*DiagnosticOpts, Args, SA, false);
4685  GenerateFrontendArgs(FrontendOpts, Args, SA, LangOpts->IsHeaderFile);
4686  GenerateTargetArgs(*TargetOpts, Args, SA);
4688  GenerateLangArgs(*LangOpts, Args, SA, T, FrontendOpts.DashX);
4689  GenerateCodeGenArgs(CodeGenOpts, Args, SA, T, FrontendOpts.OutputFile,
4690  &*LangOpts);
4692  CodeGenOpts);
4696 }
4697 
4698 std::vector<std::string> CompilerInvocation::getCC1CommandLine() const {
4699  // Set up string allocator.
4700  llvm::BumpPtrAllocator Alloc;
4701  llvm::StringSaver Strings(Alloc);
4702  auto SA = [&Strings](const Twine &Arg) { return Strings.save(Arg).data(); };
4703 
4704  // Synthesize full command line from the CompilerInvocation, including "-cc1".
4705  SmallVector<const char *, 32> Args{"-cc1"};
4706  generateCC1CommandLine(Args, SA);
4707 
4708  // Convert arguments to the return type.
4709  return std::vector<std::string>{Args.begin(), Args.end()};
4710 }
4711 
4715 }
4716 
4718  getLangOpts()->ImplicitModules = false;
4723  // The specific values we canonicalize to for pruning don't affect behaviour,
4724  /// so use the default values so they may be dropped from the command-line.
4725  getHeaderSearchOpts().ModuleCachePruneInterval = 7 * 24 * 60 * 60;
4726  getHeaderSearchOpts().ModuleCachePruneAfter = 31 * 24 * 60 * 60;
4727 }
4728 
4731  DiagnosticsEngine &Diags) {
4732  return createVFSFromCompilerInvocation(CI, Diags,
4733  llvm::vfs::getRealFileSystem());
4734 }
4735 
4738  const CompilerInvocation &CI, DiagnosticsEngine &Diags,
4740  if (CI.getHeaderSearchOpts().VFSOverlayFiles.empty())
4741  return BaseFS;
4742 
4744  // earlier vfs files are on the bottom
4745  for (const auto &File : CI.getHeaderSearchOpts().VFSOverlayFiles) {
4746  llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer =
4747  Result->getBufferForFile(File);
4748  if (!Buffer) {
4749  Diags.Report(diag::err_missing_vfs_overlay_file) << File;
4750  continue;
4751  }
4752 
4753  IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS = llvm::vfs::getVFSFromYAML(
4754  std::move(Buffer.get()), /*DiagHandler*/ nullptr, File,
4755  /*DiagContext*/ nullptr, Result);
4756  if (!FS) {
4757  Diags.Report(diag::err_invalid_vfs_overlay) << File;
4758  continue;
4759  }
4760 
4761  Result = FS;
4762  }
4763  return Result;
4764 }
clang::CodeGenOptions::BinutilsVersion
std::string BinutilsVersion
Definition: CodeGenOptions.h:131
clang::InputKind::HeaderUnitKind
HeaderUnitKind
Definition: FrontendOptions.h:167
clang::CompilerInvocationValueBase::FileSystemOpts
FileSystemOptions FileSystemOpts
Options controlling file system operations.
Definition: CompilerInvocation.h:147
clang::TargetOptions::HostTriple
std::string HostTriple
When compiling for the device side, contains the triple used to compile for the host.
Definition: TargetOptions.h:33
clang::Language::CUDA
@ CUDA
clang::LangOptions::DCC_FastCall
@ DCC_FastCall
Definition: LangOptions.h:132
clang::DependencyOutputOptions
DependencyOutputOptions - Options for controlling the compiler dependency file generation.
Definition: DependencyOutputOptions.h:33
clang::CodeGenOptions::Argv0
const char * Argv0
Executable and command-line used to create a given CompilerInvocation.
Definition: CodeGenOptions.h:413
normalizeSimpleEnum
static llvm::Optional< unsigned > normalizeSimpleEnum(OptSpecifier Opt, unsigned TableIndex, const ArgList &Args, DiagnosticsEngine &Diags)
Definition: CompilerInvocation.cpp:291
Builtins.h
clang::LangOptions::CurrentModule
std::string CurrentModule
The name of the current module, of which the main source file is a part.
Definition: LangOptions.h:434
AnalyzerOptions.h
clang::InputKind::HeaderUnit_User
@ HeaderUnit_User
Definition: FrontendOptions.h:169
max
__DEVICE__ int max(int __a, int __b)
Definition: __clang_cuda_math.h:196
clang::CompilerInvocationRefBase::getTargetOpts
TargetOptions & getTargetOpts()
Definition: CompilerInvocation.h:107
clang::CodeGenOptions::CoveragePrefixMap
std::map< std::string, std::string > CoveragePrefixMap
Definition: CodeGenOptions.h:190
ParseOptimizationRemark
static CodeGenOptions::OptRemark ParseOptimizationRemark(DiagnosticsEngine &Diags, ArgList &Args, OptSpecifier OptEQ, StringRef Name)
Parse a remark command line argument.
Definition: CompilerInvocation.cpp:1182
clang::CodeGenOptions::DiagnosticsMisExpectTolerance
Optional< uint32_t > DiagnosticsMisExpectTolerance
The maximum percentage profiling weights can deviate from the expected values in order to be included...
Definition: CodeGenOptions.h:433
FrontendPluginRegistry.h
is_uint64_t_convertible
static constexpr bool is_uint64_t_convertible()
Definition: CompilerInvocation.cpp:201
Visibility.h
clang::LangOptions::ExceptionHandlingKind::None
@ None
clang::AnalyzerOptions::getRegisteredPackages
static std::vector< StringRef > getRegisteredPackages(bool IncludeExperimental=false)
Retrieves the list of packages generated from Checkers.td.
Definition: AnalyzerOptions.h:421
clang::CompilerInvocationValueBase::getCodeGenOpts
CodeGenOptions & getCodeGenOpts()
Definition: CompilerInvocation.h:159
clang::Builtin::Context::isBuiltinFunc
static bool isBuiltinFunc(llvm::StringRef Name)
Returns true if this is a libc/libm function without the '__builtin_' prefix.
Definition: Builtins.cpp:51
clang::interp::APInt
llvm::APInt APInt
Definition: Integral.h:27
clang::ParsedSourceLocation::FromString
static ParsedSourceLocation FromString(StringRef Str)
Construct a parsed source location from a string; the Filename is empty on error.
Definition: CommandLineSourceLoc.h:32
ObjCRuntime.h
clang::frontend::EmitAssembly
@ EmitAssembly
Emit a .s file.
Definition: FrontendOptions.h:58
denormalizeStringVector
static void denormalizeStringVector(SmallVectorImpl< const char * > &Args, const char *Spelling, CompilerInvocation::StringAllocator SA, Option::OptionClass OptClass, unsigned TableIndex, const std::vector< std::string > &Values)
Definition: CompilerInvocation.cpp:368
clang::DiagnosticOptions::DiagnosticSerializationFile
std::string DiagnosticSerializationFile
The file to serialize diagnostics to (non-appending).
Definition: DiagnosticOptions.h:107
TestModuleFileExtension.h
clang::LangOptions::getOpenCLCompatibleVersion
unsigned getOpenCLCompatibleVersion() const
Return the OpenCL version that kernel language is compatible with.
Definition: LangOptions.cpp:55
clang::for
for(unsigned I=0, E=TL.getNumArgs();I !=E;++I)
Definition: RecursiveASTVisitor.h:1384
clang::DeclaratorContext::File
@ File
Driver.h
string
string(SUBSTRING ${CMAKE_CURRENT_BINARY_DIR} 0 ${PATH_LIB_START} PATH_HEAD) string(SUBSTRING $
Definition: CMakeLists.txt:22
clang::DiagnosticsEngine::setClient
void setClient(DiagnosticConsumer *client, bool ShouldOwnClient=true)
Set the diagnostic client associated with this diagnostic object.
Definition: Diagnostic.cpp:112
clang::PreprocessorOptions
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
Definition: PreprocessorOptions.h:65
addDiagnosticArgs
static void addDiagnosticArgs(ArgList &Args, OptSpecifier Group, OptSpecifier GroupWithValue, std::vector< std::string > &Diagnostics)
Definition: CompilerInvocation.cpp:772
clang::getLastArgIntValue
int getLastArgIntValue(const llvm::opt::ArgList &Args, llvm::opt::OptSpecifier Id, int Default, DiagnosticsEngine *Diags=nullptr, unsigned Base=0)
Return the value of the last argument as an integer, or a default.
clang::AnalyzerOptions::AnalysisConstraintsOpt
AnalysisConstraints AnalysisConstraintsOpt
Definition: AnalyzerOptions.h:195
clang::frontend::RewriteTest
@ RewriteTest
Rewriter playground.
Definition: FrontendOptions.h:127
clang::CompilerInvocationRefBase::TargetOpts
std::shared_ptr< TargetOptions > TargetOpts
Options controlling the target.
Definition: CompilerInvocation.h:83
clang::FrontendOptions::ARCMT_None
@ ARCMT_None
Definition: FrontendOptions.h:356
clang::DependencyOutputOptions::ExtraDeps
std::vector< std::pair< std::string, ExtraDepKind > > ExtraDeps
A list of extra dependencies (filename and kind) to be used for every target.
Definition: DependencyOutputOptions.h:68
makeFlagToValueNormalizer
static auto makeFlagToValueNormalizer(T Value)
Definition: CompilerInvocation.cpp:207
normalizeSimpleNegativeFlag
static Optional< bool > normalizeSimpleNegativeFlag(OptSpecifier Opt, unsigned, const ArgList &Args, DiagnosticsEngine &)
Definition: CompilerInvocation.cpp:182
clang::XRayInstrSet::Mask
XRayInstrMask Mask
Definition: XRayInstr.h:65
clang::CodeGenOptions::SanitizeRecover
SanitizerSet SanitizeRecover
Set of sanitizer checks that are non-fatal (i.e.
Definition: CodeGenOptions.h:356
clang::FrontendOptions::ProgramAction
frontend::ActionKind ProgramAction
The frontend action to perform.
Definition: FrontendOptions.h:445
clang::LangOptions::ClangABI::Latest
@ Latest
Conform to the underlying platform's C and C++ ABIs as closely as we can.
getFrontendAction
static Optional< frontend::ActionKind > getFrontendAction(OptSpecifier &Opt)
Maps command line option to frontend action.
Definition: CompilerInvocation.cpp:2502
clang::ParseDiagnosticArgs
bool ParseDiagnosticArgs(DiagnosticOptions &Opts, llvm::opt::ArgList &Args, DiagnosticsEngine *Diags=nullptr, bool DefaultDiagColor=true)
Fill out Opts based on the options given in Args.
Diag
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.
Definition: LiteralSupport.cpp:79
clang::HeaderSearchOptions::BuildSessionTimestamp
uint64_t BuildSessionTimestamp
The time in seconds when the build session started.
Definition: HeaderSearchOptions.h:178
clang::CodeGenOptions::OptimizationRemarkAnalysis
OptRemark OptimizationRemarkAnalysis
Selected optimizations for which we should enable optimization analyses.
Definition: CodeGenOptions.h:349
clang::FrontendOptions::ShowStats
unsigned ShowStats
Show frontend performance metrics and statistics.
Definition: FrontendOptions.h:278
clang::CompilerInvocationRefBase::CompilerInvocationRefBase
CompilerInvocationRefBase()
Definition: CompilerInvocation.cpp:130
clang::HeaderSearchOptions::Entry::IgnoreSysRoot
unsigned IgnoreSysRoot
IgnoreSysRoot - This is false if an absolute path should be treated relative to the sysroot,...
Definition: HeaderSearchOptions.h:78
clang::DiagnosticLevelMask::Error
@ Error
clang::driver::tools::DwarfFissionKind::Split
@ Split
clang::ObjCRuntime::getKind
Kind getKind() const
Definition: ObjCRuntime.h:77
llvm::SmallVector< StringRef, 16 >
mergeMaskValue
static T mergeMaskValue(T KeyPath, U Value)
Definition: CompilerInvocation.cpp:414
GenerateArg
static void GenerateArg(SmallVectorImpl< const char * > &Args, llvm::opt::OptSpecifier OptSpecifier, CompilerInvocation::StringAllocator SA)
Definition: CompilerInvocation.cpp:615
clang::if
if(T->getSizeExpr()) TRY_TO(TraverseStmt(T -> getSizeExpr()))
Definition: RecursiveASTVisitor.h:1081
clang::SourceLocation
Encodes a location in the source.
Definition: SourceLocation.h:86
clang::LangOptions::OverflowHandler
std::string OverflowHandler
The name of the handler function to be called when -ftrapv is specified.
Definition: LangOptions.h:424
clang::LangOptions::ClangABI::Ver11
@ Ver11
Attempt to be ABI-compatible with code generated by Clang 11.0.x (git 2e10b7a39b93).
getOptimizationLevelSize
static unsigned getOptimizationLevelSize(ArgList &Args)
Definition: CompilerInvocation.cpp:599
clang::PreprocessorOptions::SourceDateEpoch
Optional< uint64_t > SourceDateEpoch
If set, the UNIX timestamp specified by SOURCE_DATE_EPOCH.
Definition: PreprocessorOptions.h:224
clang::DiagnosticsEngine::isIgnored
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:911
clang::driver::Action
Action - Represent an abstract compilation step to perform.
Definition: Action.h:47
clang::CodeGenOptions::CommandLineArgs
std::vector< std::string > CommandLineArgs
Definition: CodeGenOptions.h:414
clang::FrontendOptions::PluginArgs
std::map< std::string, std::vector< std::string > > PluginArgs
Args to pass to the plugins.
Definition: FrontendOptions.h:459
GenerateFileSystemArgs
static void GenerateFileSystemArgs(const FileSystemOptions &Opts, SmallVectorImpl< const char * > &Args, CompilerInvocation::StringAllocator SA)
Definition: CompilerInvocation.cpp:2205
parseShowColorsArgs
static bool parseShowColorsArgs(const ArgList &Args, bool DefaultColor)
Definition: CompilerInvocation.cpp:2156
clang::frontend::ModuleFileInfo
@ ModuleFileInfo
Dump information about a module file.
Definition: FrontendOptions.h:103
clang::CodeGenOptions::hasSanitizeCoverage
bool hasSanitizeCoverage() const
Definition: CodeGenOptions.h:492
clang::HeaderSearchOptions::UseStandardSystemIncludes
unsigned UseStandardSystemIncludes
Include the system standard include search directories.
Definition: HeaderSearchOptions.h:191
parseToleranceOption
Expected< Optional< uint32_t > > parseToleranceOption(StringRef Arg)
Definition: CompilerInvocation.cpp:118
clang::codegenoptions::DebugTemplateNamesKind::Simple
@ Simple
clang::codegenoptions::UnusedTypeInfo
@ UnusedTypeInfo
Generate debug info for types that may be unused in the source (-fno-eliminate-unused-debug-types).
Definition: DebugInfoOptions.h:54
clang::frontend::RunPreprocessorOnly
@ RunPreprocessorOnly
Just lex, no output.
Definition: FrontendOptions.h:139
Filename
StringRef Filename
Definition: Format.cpp:2715
clang::DiagnosticsEngine
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:192
clang::Language::OpenCLCXX
@ OpenCLCXX
GetInputKindName
static StringRef GetInputKindName(InputKind IK)
Get language name for given input kind.
Definition: CompilerInvocation.cpp:3263
clang::CodeGenOptions::DIBugsReportFilePath
std::string DIBugsReportFilePath
The file to use for dumping bug report by Debugify for original debug info.
Definition: CodeGenOptions.h:197
clang::CodeGenOptions::SampleProfileFile
std::string SampleProfileFile
Name of the profile file to use with -fprofile-sample-use.
Definition: CodeGenOptions.h:257
memcpy
__DEVICE__ void * memcpy(void *__a, const void *__b, size_t __c)
Definition: __clang_cuda_device_functions.h:1549
clang::CodeGenOptions::SaveTempsFilePrefix
std::string SaveTempsFilePrefix
Prefix to use for -save-temps output.
Definition: CodeGenOptions.h:279
getAllNoBuiltinFuncValues
static void getAllNoBuiltinFuncValues(ArgList &Args, std::vector< std::string > &Funcs)
Definition: CompilerInvocation.cpp:798
clang::LangOptions::CXXABI
llvm::Optional< TargetCXXABI::Kind > CXXABI
C++ ABI to compile with, if specified by the frontend through -fc++-abi=.
Definition: LangOptions.h:467
clang::LangOptions::FPM_On
@ FPM_On
Definition: LangOptions.h:259
clang::LangOptions::SignReturnAddressScopeKind::NonLeaf
@ NonLeaf
Sign the return address of functions that spill LR.
clang::PreprocessorOutputOptions::ShowCPP
unsigned ShowCPP
Print normal preprocessed output.
Definition: PreprocessorOutputOptions.h:18
ParseDependencyOutputArgs
static bool ParseDependencyOutputArgs(DependencyOutputOptions &Opts, ArgList &Args, DiagnosticsEngine &Diags, frontend::ActionKind Action, bool ShowLineMarkers)
Definition: CompilerInvocation.cpp:2090
checkVerifyPrefixes
static bool checkVerifyPrefixes(const std::vector< std::string > &VerifyPrefixes, DiagnosticsEngine &Diags)
Definition: CompilerInvocation.cpp:2187
clang::LangOptions::SignReturnAddressScopeKind::None
@ None
No signing for any function.
clang::InputKind::withHeaderUnit
InputKind withHeaderUnit(HeaderUnitKind HU) const
Definition: FrontendOptions.h:206
clang::codegenoptions::NoDebugInfo
@ NoDebugInfo
Don't generate debug info.
Definition: DebugInfoOptions.h:22
clang::FrontendOptions::ObjCMT_None
@ ObjCMT_None
Definition: FrontendOptions.h:363
clang::codegenoptions::DebugTemplateNamesKind::Mangled
@ Mangled
llvm::Optional< bool >
clang::CompilerInvocationRefBase::getHeaderSearchOpts
HeaderSearchOptions & getHeaderSearchOpts()
Definition: CompilerInvocation.h:112
denormalizeSimpleFlag
static void denormalizeSimpleFlag(SmallVectorImpl< const char * > &Args, const char *Spelling, CompilerInvocation::StringAllocator, Option::OptionClass, unsigned,...)
The tblgen-erated code passes in a fifth parameter of an arbitrary type, but denormalizeSimpleFlags n...
Definition: CompilerInvocation.cpp:194
clang::driver::options::CC1Option
@ CC1Option
Definition: Options.h:31
clang::serialization::VERSION_MAJOR
const unsigned VERSION_MAJOR
AST file major version number supported by this version of Clang.
Definition: ASTBitCodes.h:44
findValueTableByValue
static Optional< SimpleEnumValue > findValueTableByValue(const SimpleEnumValueTable &Table, unsigned Value)
Definition: CompilerInvocation.cpp:283
clang::CodeGenOptions::CodeModel
std::string CodeModel
The code model to use (-mcmodel).
Definition: CodeGenOptions.h:153
clang::frontend::ASTDump
@ ASTDump
Parse ASTs and dump them.
Definition: FrontendOptions.h:40
ParseFrontendArgs
static bool ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args, DiagnosticsEngine &Diags, bool &IsHeaderFile)
Definition: CompilerInvocation.cpp:2695
clang::LangOptions::GCOnly
@ GCOnly
Definition: LangOptions.h:86
clang::tooling::X
static ToolExecutorPluginRegistry::Add< AllTUsToolExecutorPlugin > X("all-TUs", "Runs FrontendActions on all TUs in the compilation database. " "Tool results are stored in memory.")
llvm::Expected
Definition: LLVM.h:41
clang::LangOptions::DCC_None
@ DCC_None
Definition: LangOptions.h:130
clang::PreprocessorOptions::DetailedRecord
bool DetailedRecord
Whether we should maintain a detailed record of all macro definitions and expansions.
Definition: PreprocessorOptions.h:77
clang::diag::Group
Group
Definition: DiagnosticCategories.h:23
ParseMigratorArgs
static bool ParseMigratorArgs(MigratorOptions &Opts, const ArgList &Args, DiagnosticsEngine &Diags)
Definition: CompilerInvocation.cpp:2258
GenerateMigratorArgs
static void GenerateMigratorArgs(const MigratorOptions &Opts, SmallVectorImpl< const char * > &Args, CompilerInvocation::StringAllocator SA)
Definition: CompilerInvocation.cpp:2242
clang::Language::Asm
@ Asm
Assembly: we accept this only so that we can preprocess it.
clang::LangOptions::getOpenCLVersionString
std::string getOpenCLVersionString() const
Return the OpenCL C or C++ for OpenCL language name and version as a string.
Definition: LangOptions.cpp:71
clang::FileSystemOptions::WorkingDir
std::string WorkingDir
If set, paths are resolved as if the working directory was set to the value of WorkingDir.
Definition: FileSystemOptions.h:26
clang::LangOptions::MacroPrefixMap
std::map< std::string, std::string, std::greater< std::string > > MacroPrefixMap
A prefix map for FILE, BASE_FILE and __builtin_FILE().
Definition: LangOptions.h:449
clang::InputKind
The kind of a file that we've been handed as an input.
Definition: FrontendOptions.h:148
clang::frontend::CSystem
@ CSystem
Like System, but only used for C.
Definition: HeaderSearchOptions.h:49
clang::PreprocessorOutputOptions::ShowLineMarkers
unsigned ShowLineMarkers
Show #line markers.
Definition: PreprocessorOutputOptions.h:20
clang::frontend::VerifyPCH
@ VerifyPCH
Load and verify that a PCH file is usable.
Definition: FrontendOptions.h:106
clang::AnalyzerOptions::AnalysisPurgeOpt
AnalysisPurgeMode AnalysisPurgeOpt
Definition: AnalyzerOptions.h:197
clang::CompilerInvocationRefBase::LangOpts
std::shared_ptr< LangOptions > LangOpts
Options controlling the language variant.
Definition: CompilerInvocation.h:80
End
SourceLocation End
Definition: USRLocFinder.cpp:167
clang::frontend::PluginAction
@ PluginAction
Run a plugin action,.
Definition: FrontendOptions.h:112
clang::HeaderSearchOptions::ModulesValidateDiagnosticOptions
unsigned ModulesValidateDiagnosticOptions
Definition: HeaderSearchOptions.h:217
clang::frontend::RewriteObjC
@ RewriteObjC
ObjC->C Rewriter.
Definition: FrontendOptions.h:124
clang::CompilerInvocation::resetNonModularOptions
void resetNonModularOptions()
Reset all of the options that are not considered when building a module.
Definition: CompilerInvocation.cpp:4712
clang::InputKind::Source
@ Source
Definition: FrontendOptions.h:159
clang::FrontendOptions::AuxTargetFeatures
Optional< std::vector< std::string > > AuxTargetFeatures
Auxiliary target features for CUDA/HIP compilation.
Definition: FrontendOptions.h:498
clang::codegenoptions::DebugInfoConstructor
@ DebugInfoConstructor
Limit generated debug info for classes to reduce size.
Definition: DebugInfoOptions.h:41
GenerateAnalyzerArgs
static void GenerateAnalyzerArgs(AnalyzerOptions &Opts, SmallVectorImpl< const char * > &Args, CompilerInvocation::StringAllocator SA)
Definition: CompilerInvocation.cpp:805
CompilerInvocation.h
clang::XRayInstrSet
Definition: XRayInstr.h:47
clang::PreprocessorOptions::Includes
std::vector< std::string > Includes
Definition: PreprocessorOptions.h:68
clang::ObjCRuntime::allowsWeak
bool allowsWeak() const
Does this runtime allow the use of __weak?
Definition: ObjCRuntime.h:283
PreprocessorOutputOptions.h
extractMaskValue
static T extractMaskValue(T KeyPath)
Definition: CompilerInvocation.cpp:423
clang::frontend::IndexHeaderMap
@ IndexHeaderMap
Like Angled, but marks header maps used when building frameworks.
Definition: HeaderSearchOptions.h:40
clang::codegenoptions::DebugDirectivesOnly
@ DebugDirectivesOnly
Emit only debug directives with the line numbers data.
Definition: DebugInfoOptions.h:31
clang::CompilerInvocationValueBase::CodeGenOpts
CodeGenOptions CodeGenOpts
Options controlling IRgen and the backend.
Definition: CompilerInvocation.h:141
getStringOption
static StringRef getStringOption(AnalyzerOptions::ConfigTable &Config, StringRef OptionName, StringRef DefaultVal)
Definition: CompilerInvocation.cpp:1049
clang::FrontendOptions::Inputs
SmallVector< FrontendInputFile, 0 > Inputs
The input files and their types.
Definition: FrontendOptions.h:426
clang::LangOptions::SignReturnAddressKeyKind::AKey
@ AKey
Return address signing uses APIA key.
clang::ParsedSourceLocation::FileName
std::string FileName
Definition: CommandLineSourceLoc.h:25
clang::HeaderSearchOptions::UseDebugInfo
unsigned UseDebugInfo
Whether the module includes debug information (-gmodules).
Definition: HeaderSearchOptions.h:215
clang::frontend::ObjCSystem
@ ObjCSystem
Like System, but only used for ObjC.
Definition: HeaderSearchOptions.h:55
clang::CodeGenOptions::SRCK_OnStack
@ SRCK_OnStack
Definition: CodeGenOptions.h:81
clang::frontend::GeneratePCH
@ GeneratePCH
Generate pre-compiled header.
Definition: FrontendOptions.h:94
isStrictlyPreprocessorAction
static bool isStrictlyPreprocessorAction(frontend::ActionKind Action)
Definition: CompilerInvocation.cpp:4120
clang::FileSystemOptions
Keeps track of options that affect how file operations are performed.
Definition: FileSystemOptions.h:22
clang::SanitizerSet::Mask
SanitizerMask Mask
Bitmask of enabled sanitizers.
Definition: Sanitizers.h:176
clang::PreprocessorOptions::PCHWithHdrStopCreate
bool PCHWithHdrStopCreate
When true, we are creating a PCH or creating the PCH object while expecting a #pragma hdrstop to sepa...
Definition: PreprocessorOptions.h:87
clang::LangStandard::Kind
Kind
Definition: LangStandard.h:69
clang::getPPTransparentSanitizers
SanitizerMask getPPTransparentSanitizers()
Return the sanitizers which do not affect preprocessing.
Definition: Sanitizers.h:192
CodeGenOptions.h
U
clang::ObjCRuntime::FragileMacOSX
@ FragileMacOSX
'macosx-fragile' is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the fragil...
Definition: ObjCRuntime.h:40
clang::CodeGenOptions::NoBuiltinFuncs
std::vector< std::string > NoBuiltinFuncs
A list of all -fno-builtin-* function names (e.g., memset).
Definition: CodeGenOptions.h:365
clang::frontend::ASTView
@ ASTView
Parse ASTs and view them in Graphviz.
Definition: FrontendOptions.h:46
clang::frontend::ExternCSystem
@ ExternCSystem
Like System, but headers are implicitly wrapped in extern "C".
Definition: HeaderSearchOptions.h:46
clang::LangOptions::SanitizeCoverage
bool SanitizeCoverage
Is at least one coverage instrumentation type enabled.
Definition: LangOptions.h:387
clang::AnalyzerOptions::ConfigTable
llvm::StringMap< std::string > ConfigTable
Definition: AnalyzerOptions.h:152
clang::XRayInstrKind::All
constexpr XRayInstrMask All
Definition: XRayInstr.h:43
normalizeStringIntegral
static Optional< IntTy > normalizeStringIntegral(OptSpecifier Opt, int, const ArgList &Args, DiagnosticsEngine &Diags)
Definition: CompilerInvocation.cpp:347
clang::LangStandard::getLangKind
static Kind getLangKind(StringRef Name)
Definition: LangStandards.cpp:31
getProgramActionOpt
static Optional< OptSpecifier > getProgramActionOpt(frontend::ActionKind ProgramAction)
Maps frontend action to command line option.
Definition: CompilerInvocation.cpp:2512
V
#define V(N, I)
Definition: ASTContext.h:3235
clang::FrontendOptions::AuxTargetCPU
Optional< std::string > AuxTargetCPU
Auxiliary target CPU for CUDA/HIP compilation.
Definition: FrontendOptions.h:495
clang::LangOptions::SOB_Trapping
@ SOB_Trapping
Definition: LangOptions.h:102
initOption
static void initOption(AnalyzerOptions::ConfigTable &Config, DiagnosticsEngine *Diags, StringRef &OptionField, StringRef Name, StringRef DefaultVal)
Definition: CompilerInvocation.cpp:1054
clang::FrontendOptions::ASTDumpFormat
ASTDumpOutputFormat ASTDumpFormat
Specifies the output format of the AST.
Definition: FrontendOptions.h:353
clang::LangOptions::ClangABI::Ver12
@ Ver12
Attempt to be ABI-compatible with code generated by Clang 12.0.x (git 8e464dd76bef).
clang::frontend::System
@ System
Like Angled, but marks system directories.
Definition: HeaderSearchOptions.h:43
clang::frontend::ASTPrint
@ ASTPrint
Parse ASTs and print them.
Definition: FrontendOptions.h:43
clang::CompilerInvocationRefBase
The base class of CompilerInvocation with reference semantics.
Definition: CompilerInvocation.h:77
clang::Decl::Kind
Kind
Lists the kind of concrete classes of Decl.
Definition: DeclBase.h:86
clang::Language::RenderScript
@ RenderScript
clang::HeaderSearchOptions::Entry::IsFramework
unsigned IsFramework
Definition: HeaderSearchOptions.h:73
clang::FrontendOptions::ASTDumpDecls
unsigned ASTDumpDecls
Whether we include declaration dumps in AST dumps.
Definition: FrontendOptions.h:315
denormalizeSimpleEnum
static void denormalizeSimpleEnum(SmallVectorImpl< const char * > &Args, const char *Spelling, CompilerInvocation::StringAllocator SA, Option::OptionClass OptClass, unsigned TableIndex, T Value)
Definition: CompilerInvocation.cpp:328
normalizeStringVector
static Optional< std::vector< std::string > > normalizeStringVector(OptSpecifier Opt, int, const ArgList &Args, DiagnosticsEngine &)
Definition: CompilerInvocation.cpp:363
clang::EDK_ModuleFile
@ EDK_ModuleFile
Definition: DependencyOutputOptions.h:27
clang::CodeGenOptions::RK_DisabledEverything
@ RK_DisabledEverything
Definition: CodeGenOptions.h:309
clang::HeaderSearchOptions::ModuleCachePruneAfter
unsigned ModuleCachePruneAfter
The time (in seconds) after which an unused module file will be considered unused and will,...
Definition: HeaderSearchOptions.h:172
clang::frontend::RunAnalysis
@ RunAnalysis
Run one or more source code analyses.
Definition: FrontendOptions.h:130
clang::HeaderSearchOptions::ModulesStrictContextHash
unsigned ModulesStrictContextHash
Whether we should include all things that could impact the module in the hash.
Definition: HeaderSearchOptions.h:226
DiagnosticDriver.h
clang::CompilerInvocationRefBase::PreprocessorOpts
std::shared_ptr< PreprocessorOptions > PreprocessorOpts
Options controlling the preprocessor (aside from #include handling).
Definition: CompilerInvocation.h:92
makeBooleanOptionNormalizer
static auto makeBooleanOptionNormalizer(bool Value, bool OtherValue, OptSpecifier OtherOpt)
Definition: CompilerInvocation.cpp:222
clang::CompilerInvocationValueBase::getFrontendOpts
FrontendOptions & getFrontendOpts()
Definition: CompilerInvocation.h:176
clang::AnalysisDiagClients
AnalysisDiagClients
AnalysisDiagClients - Set of available diagnostic clients for rendering analysis results.
Definition: AnalyzerOptions.h:44
clang::SanitizerSet
Definition: Sanitizers.h:153
clang::driver::getDriverOptTable
const llvm::opt::OptTable & getDriverOptTable()
Definition: DriverOptions.cpp:42
clang::codegenoptions::LocTrackingOnly
@ LocTrackingOnly
Emit location information but do not generate debug info in the output.
Definition: DebugInfoOptions.h:28
clang::LangStandard::getName
const char * getName() const
getName - Get the name of this standard.
Definition: LangStandard.h:83
Options.h
GeneratePreprocessorOutputArgs
static void GeneratePreprocessorOutputArgs(const PreprocessorOutputOptions &Opts, SmallVectorImpl< const char * > &Args, CompilerInvocation::StringAllocator SA, frontend::ActionKind Action)
Definition: CompilerInvocation.cpp:4343
clang::frontend::ObjCXXSystem
@ ObjCXXSystem
Like System, but only used for ObjC++.
Definition: HeaderSearchOptions.h:58
clang::LangOptions::ObjCRuntime
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:414
clang::frontend::EmitObj
@ EmitObj
Emit a .o file.
Definition: FrontendOptions.h:76
clang::PreprocessorOutputOptions
PreprocessorOutputOptions - Options for controlling the C preprocessor output (e.g....
Definition: PreprocessorOutputOptions.h:16
clang::FrontendOptions::getInputKindForExtension
static InputKind getInputKindForExtension(StringRef Extension)
getInputKindForExtension - Return the appropriate input kind for a file extension.
Definition: FrontendOptions.cpp:15
HeaderSearchOptions.h
clang::frontend::ActionKind
ActionKind
Definition: FrontendOptions.h:35
CodeCompleteOptions.h
clang::LangOptions::OMPTargetTriples
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:453
clang::CodeGenOptions::CmdArgs
std::vector< uint8_t > CmdArgs
List of backend command-line options for -fembed-bitcode.
Definition: CodeGenOptions.h:362
clang::CodeGenOptions::DebugPrefixMap
std::map< std::string, std::string > DebugPrefixMap
Definition: CodeGenOptions.h:189
clang::CodeGenOptions::ProfileNone
@ ProfileNone
Definition: CodeGenOptions.h:86
FrontendOptions.h
clang::FrontendOptions::OutputFile
std::string OutputFile
The output file, if any.
Definition: FrontendOptions.h:433
hlsl::uint64_t
unsigned long uint64_t
Definition: hlsl_basic_types.h:25
clang::XRayInstrKind::None
constexpr XRayInstrMask None
Definition: XRayInstr.h:38
clang::CodeGenOptions::MemoryProfileOutput
std::string MemoryProfileOutput
Name of the profile file to use as output for with -fmemory-profile.
Definition: CodeGenOptions.h:260
clang::FrontendOptions::AuxTriple
std::string AuxTriple
Auxiliary triple for CUDA/HIP compilation.
Definition: FrontendOptions.h:492
clang::TargetCXXABI::getKind
Kind getKind() const
Definition: TargetCXXABI.h:82
clang::ObjCRuntime::allowsARC
bool allowsARC() const
Does this runtime allow ARC at all?
Definition: ObjCRuntime.h:142
clang::HeaderSearchOptions::Sysroot
std::string Sysroot
If non-empty, the directory to use as a "virtual system root" for include paths.
Definition: HeaderSearchOptions.h:100
clang::threadSafety::sx::toString
std::string toString(const til::SExpr *E)
Definition: ThreadSafetyCommon.h:91
clang::CompilerInvocationRefBase::HeaderSearchOpts
std::shared_ptr< HeaderSearchOptions > HeaderSearchOpts
Options controlling the #include directive.
Definition: CompilerInvocation.h:89
clang::PreprocessorOptions::ChainedIncludes
std::vector< std::string > ChainedIncludes
Headers that will be converted to chained PCHs in memory.
Definition: PreprocessorOptions.h:100
clang::frontend::ParseSyntaxOnly
@ ParseSyntaxOnly
Parse and perform semantic analysis.
Definition: FrontendOptions.h:109
clang::AnalyzerOptions::InliningMode
AnalysisInliningMode InliningMode
The mode of function selection used during inlining.
Definition: AnalyzerOptions.h:250
Version.h
LangOptions.h
llvm::opt
Definition: DiagnosticOptions.h:19
Std
LangStandard::Kind Std
Definition: InterpolatingCompilationDatabase.cpp:133
Diagnostic.h
DriverDiagnostic.h
clang::ASTDumpOutputFormat
ASTDumpOutputFormat
Used to specify the format for printing AST dump information.
Definition: ASTDumperUtils.h:21
clang::FrontendOptions
FrontendOptions - Options for controlling the behavior of the frontend.
Definition: FrontendOptions.h:265
clang::CompilerInvocationValueBase::DependencyOutputOpts
DependencyOutputOptions DependencyOutputOpts
Options controlling dependency output.
Definition: CompilerInvocation.h:144
clang::DiagnosticsEngine::Error
@ Error
Definition: Diagnostic.h:200
Utils.h
clang::isLetter
LLVM_READONLY bool isLetter(unsigned char c)
Return true if this character is an ASCII letter: [a-zA-Z].
Definition: CharInfo.h:117
clang::frontend::ASTDeclList
@ ASTDeclList
Parse ASTs and list Decl nodes.
Definition: FrontendOptions.h:37
ParseFileSystemArgs
static bool ParseFileSystemArgs(FileSystemOptions &Opts, const ArgList &Args, DiagnosticsEngine &Diags)
Definition: CompilerInvocation.cpp:2222
clang::CodeGenOptions::OptimizationRemarkMissed
OptRemark OptimizationRemarkMissed
Selected optimizations for which we should enable missed optimization remarks.
Definition: CodeGenOptions.h:342
clang::InputKind::isUnknown
bool isUnknown() const
Is the input kind fully-unknown?
Definition: FrontendOptions.h:189
clang::InputKind::HeaderUnit_Abs
@ HeaderUnit_Abs
Definition: FrontendOptions.h:171
clang::AnalyzerOptions::AnalysisDiagOpt
AnalysisDiagClients AnalysisDiagOpt
Definition: AnalyzerOptions.h:196
clang::CompilerInvocationRefBase::AnalyzerOpts
AnalyzerOptionsRef AnalyzerOpts
Options controlling the static analyzer.
Definition: CompilerInvocation.h:95
clang::InputKind::getHeader
InputKind getHeader() const
Definition: FrontendOptions.h:201
clang::frontend::DumpRawTokens
@ DumpRawTokens
Dump out raw tokens.
Definition: FrontendOptions.h:52
clang::CodeGenOptions::ProfileClangInstr
@ ProfileClangInstr
Definition: CodeGenOptions.h:87
clang::LangOptions::ModuleFeatures
std::vector< std::string > ModuleFeatures
The names of any features to enable in module 'requires' decls in addition to the hard-coded list in ...
Definition: LangOptions.h:440
clang::InputKind::getLanguage
Language getLanguage() const
Definition: FrontendOptions.h:179
clang::frontend::EmitLLVM
@ EmitLLVM
Emit a .ll file.
Definition: FrontendOptions.h:67
clang::PreprocessorOutputOptions::DirectivesOnly
unsigned DirectivesOnly
Process directives but do not expand macros.
Definition: PreprocessorOutputOptions.h:28
DependencyOutputOptions.h
clang::DependencyOutputOptions::ShowIncludesDest
ShowIncludesDestination ShowIncludesDest
Destination of cl.exe style /showIncludes info.
Definition: DependencyOutputOptions.h:48
clang::HeaderSearchOptions::ModuleFormat
std::string ModuleFormat
The module/pch container format.
Definition: HeaderSearchOptions.h:125
clang::InputKind::Precompiled
@ Precompiled
Definition: FrontendOptions.h:161
clang::LangOptions::NoBuiltinFuncs
std::vector< std::string > NoBuiltinFuncs
A list of all -fno-builtin-* function names (e.g., memset).
Definition: LangOptions.h:446
clang::FrontendOptions::ASTDumpAll
unsigned ASTDumpAll
Whether we deserialize all decls when forming AST dumps.
Definition: FrontendOptions.h:318
clang::InputKind::getPreprocessed
InputKind getPreprocessed() const
Definition: FrontendOptions.h:196
clang::CodeGenOptions::OptRemark
Optimization remark with an optional regular expression pattern.
Definition: CodeGenOptions.h:314
llvm::SmallString< 128 >
clang::FrontendOptions::ObjCMTAction
unsigned ObjCMTAction
Definition: FrontendOptions.h:415
bool
#define bool
Definition: stdbool.h:20
clang::Language::C
@ C
Languages that the frontend can parse and compile.
clang::CodeGenOptions::OptRecordFormat
std::string OptRecordFormat
The format used for serializing remarks (default: YAML)
Definition: CodeGenOptions.h:298
clang::CompilerInvocationRefBase::getLangOpts
LangOptions * getLangOpts()
Definition: CompilerInvocation.h:104
clang::frontend::Quoted
@ Quoted
'#include ""' paths, added by 'gcc -iquote'.
Definition: HeaderSearchOptions.h:34
TextDiagnosticBuffer.h
clang::frontend::PrintDependencyDirectivesSourceMinimizerOutput
@ PrintDependencyDirectivesSourceMinimizerOutput
Print the output of the dependency directives source minimizer.
Definition: FrontendOptions.h:142
clang::getClangFullRepositoryVersion
std::string getClangFullRepositoryVersion()
Retrieves the full repository version that is an amalgamation of the information in getClangRepositor...
Definition: Version.cpp:60
clang::TargetCXXABI::isABI
static bool isABI(StringRef Name)
Definition: TargetCXXABI.h:63
clang::DiagnosticOptions::DefaultTabStop
@ DefaultTabStop
Definition: DiagnosticOptions.h:81
clang::LangOptions::SYCL_Default
@ SYCL_Default
Definition: LangOptions.h:160
clang::PreprocessorOptions::UsePredefines
bool UsePredefines
Initialize the preprocessor with the compiler and target specific predefines.
Definition: PreprocessorOptions.h:73
GenerateTargetArgs
static void GenerateTargetArgs(const TargetOptions &Opts, SmallVectorImpl< const char * > &Args, CompilerInvocation::StringAllocator SA)
Definition: CompilerInvocation.cpp:4393
clang::frontend::EmitHTML
@ EmitHTML
Translate input source into HTML.
Definition: FrontendOptions.h:64
clang::CXXABI
Implements C++ ABI-specific semantic analysis functions.
Definition: CXXABI.h:29
clang::FrontendOptions::DashX
InputKind DashX
The input kind, either specified via -x argument or deduced from the input file name.
Definition: FrontendOptions.h:423
clang::HeaderSearchOptions::UseLibcxx
unsigned UseLibcxx
Use libc++ instead of the default libstdc++.
Definition: HeaderSearchOptions.h:197
clang::DiagnosticsEngine::getNumWarnings
unsigned getNumWarnings() const
Definition: Diagnostic.h:853
clang::HeaderSearchOptions::PrebuiltModulePaths
std::vector< std::string > PrebuiltModulePaths
The directories used to load prebuilt module files.
Definition: HeaderSearchOptions.h:122
clang::frontend::RewriteMacros
@ RewriteMacros
Expand macros but not #includes.
Definition: FrontendOptions.h:121
clang::AnalysisConstraints
AnalysisConstraints
AnalysisConstraints - Set of available constraint models.
Definition: AnalyzerOptions.h:36
clang::LangOptions::HybridGC
@ HybridGC
Definition: LangOptions.h:86
clang::FrontendOptions::UseGlobalModuleIndex
unsigned UseGlobalModuleIndex
Whether we can use the global module index if available.
Definition: FrontendOptions.h:309
CXXABI
#define CXXABI(Name, Str)
Definition: TargetCXXABI.h:32
clang::LangOptions::DCC_VectorCall
@ DCC_VectorCall
Definition: LangOptions.h:134
denormalizeString
static void denormalizeString(SmallVectorImpl< const char * > &Args, const char *Spelling, CompilerInvocation::StringAllocator SA, Option::OptionClass OptClass, unsigned TableIndex, T Value)
Definition: CompilerInvocation.cpp:267
clang::AnalyzerOptions::getRegisteredCheckers
static std::vector< StringRef > getRegisteredCheckers(bool IncludeExperimental=false)
Retrieves the list of checkers generated from Checkers.td.
Definition: AnalyzerOptions.h:402
clang::HeaderSearchOptions::UseStandardCXXIncludes
unsigned UseStandardCXXIncludes
Include the system standard C++ library include search directories.
Definition: HeaderSearchOptions.h:194
clang::CompilerInvocation::generateCC1CommandLine
void generateCC1CommandLine(llvm::SmallVectorImpl< const char * > &Args, StringAllocator SA) const
Generate cc1-compatible command line arguments from this instance.
Definition: CompilerInvocation.cpp:4677
clang::LangOptions::ClangABI::Ver4
@ Ver4
Attempt to be ABI-compatible with code generated by Clang 4.0.x (SVN r291814).
clang::CompilerInvocationRefBase::~CompilerInvocationRefBase
~CompilerInvocationRefBase()
clang::CompilerInvocationRefBase::getAnalyzerOpts
AnalyzerOptionsRef getAnalyzerOpts() const
Definition: CompilerInvocation.h:132
clang::CodeGenOptions
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
Definition: CodeGenOptions.h:49