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