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