29 #include "clang/Config/config.h"
48 #include "llvm/ADT/APInt.h"
49 #include "llvm/ADT/ArrayRef.h"
50 #include "llvm/ADT/CachedHashString.h"
51 #include "llvm/ADT/FloatingPointMode.h"
52 #include "llvm/ADT/Hashing.h"
53 #include "llvm/ADT/STLExtras.h"
54 #include "llvm/ADT/SmallString.h"
55 #include "llvm/ADT/SmallVector.h"
56 #include "llvm/ADT/StringRef.h"
57 #include "llvm/ADT/StringSwitch.h"
58 #include "llvm/ADT/Twine.h"
59 #include "llvm/Config/llvm-config.h"
60 #include "llvm/Frontend/Debug/Options.h"
61 #include "llvm/IR/DebugInfoMetadata.h"
62 #include "llvm/Linker/Linker.h"
63 #include "llvm/MC/MCTargetOptions.h"
64 #include "llvm/Option/Arg.h"
65 #include "llvm/Option/ArgList.h"
66 #include "llvm/Option/OptSpecifier.h"
67 #include "llvm/Option/OptTable.h"
68 #include "llvm/Option/Option.h"
69 #include "llvm/ProfileData/InstrProfReader.h"
70 #include "llvm/Remarks/HotnessThresholdParser.h"
71 #include "llvm/Support/CodeGen.h"
72 #include "llvm/Support/Compiler.h"
73 #include "llvm/Support/Error.h"
74 #include "llvm/Support/ErrorHandling.h"
75 #include "llvm/Support/ErrorOr.h"
76 #include "llvm/Support/FileSystem.h"
77 #include "llvm/Support/HashBuilder.h"
78 #include "llvm/Support/MathExtras.h"
79 #include "llvm/Support/MemoryBuffer.h"
80 #include "llvm/Support/Path.h"
81 #include "llvm/Support/Process.h"
82 #include "llvm/Support/Regex.h"
83 #include "llvm/Support/VersionTuple.h"
84 #include "llvm/Support/VirtualFileSystem.h"
85 #include "llvm/Support/raw_ostream.h"
86 #include "llvm/Target/TargetOptions.h"
87 #include "llvm/TargetParser/Host.h"
88 #include "llvm/TargetParser/Triple.h"
101 #include <type_traits>
105 using namespace clang;
106 using namespace driver;
107 using namespace options;
118 if (Arg.getAsInteger(10, Val))
119 return llvm::createStringError(llvm::inconvertibleErrorCode(),
120 "Not an integer: %s", Arg.data());
129 template <
class T> std::shared_ptr<T> make_shared_copy(
const T &
X) {
130 return std::make_shared<T>(
X);
135 return llvm::makeIntrusiveRefCnt<T>(
X);
157 LangOpts = make_shared_copy(
X.getLangOpts());
160 HSOpts = make_shared_copy(
X.getHeaderSearchOpts());
161 PPOpts = make_shared_copy(
X.getPreprocessorOpts());
166 FSOpts = make_shared_copy(
X.getFileSystemOpts());
206 template <
typename T>
207 T &ensureOwned(std::shared_ptr<T> &
Storage) {
213 template <
typename T>
234 return ensureOwned(
HSOpts);
238 return ensureOwned(
PPOpts);
258 return ensureOwned(
FSOpts);
280 #define SIMPLE_ENUM_VALUE_TABLE
281 #include "clang/Driver/Options.inc"
282 #undef SIMPLE_ENUM_VALUE_TABLE
288 if (Args.hasArg(Opt))
297 if (Args.hasArg(Opt))
307 const Twine &Spelling, Option::OptionClass,
313 return !std::is_same_v<T, uint64_t> && llvm::is_integral_or_enum<T>::value;
316 template <
typename T,
317 std::enable_if_t<!is_uint64_t_convertible<T>(),
bool> =
false>
319 return [
Value](OptSpecifier Opt,
unsigned,
const ArgList &Args,
321 if (Args.hasArg(Opt))
327 template <
typename T,
328 std::enable_if_t<is_uint64_t_convertible<T>(),
bool> =
false>
334 OptSpecifier OtherOpt) {
335 return [
Value, OtherValue,
336 OtherOpt](OptSpecifier Opt,
unsigned,
const ArgList &Args,
338 if (
const Arg *A = Args.getLastArg(Opt, OtherOpt)) {
339 return A->getOption().matches(Opt) ?
Value : OtherValue;
347 Option::OptionClass,
unsigned,
bool KeyPath) {
348 if (KeyPath ==
Value)
354 const Twine &Spelling,
355 Option::OptionClass OptClass,
unsigned,
356 const Twine &
Value) {
358 case Option::SeparateClass:
359 case Option::JoinedOrSeparateClass:
360 case Option::JoinedAndSeparateClass:
364 case Option::JoinedClass:
365 case Option::CommaJoinedClass:
366 Consumer(Spelling +
Value);
369 llvm_unreachable(
"Cannot denormalize an option with option class "
370 "incompatible with string denormalization.");
374 template <
typename T>
376 Option::OptionClass OptClass,
unsigned TableIndex,
381 static std::optional<SimpleEnumValue>
383 for (
int I = 0, E = Table.Size; I != E; ++I)
384 if (Name == Table.Table[I].Name)
385 return Table.Table[I];
390 static std::optional<SimpleEnumValue>
392 for (
int I = 0, E = Table.Size; I != E; ++I)
394 return Table.Table[I];
403 assert(TableIndex < SimpleEnumValueTablesSize);
404 const SimpleEnumValueTable &Table = SimpleEnumValueTables[TableIndex];
406 auto *Arg = Args.getLastArg(Opt);
410 StringRef ArgValue = Arg->getValue();
412 return MaybeEnumVal->Value;
414 Diags.
Report(diag::err_drv_invalid_value)
415 << Arg->getAsString(Args) << ArgValue;
420 const Twine &Spelling,
421 Option::OptionClass OptClass,
422 unsigned TableIndex,
unsigned Value) {
423 assert(TableIndex < SimpleEnumValueTablesSize);
424 const SimpleEnumValueTable &Table = SimpleEnumValueTables[TableIndex];
429 llvm_unreachable(
"The simple enum value was not correctly defined in "
430 "the tablegen option description");
434 template <
typename T>
436 const Twine &Spelling,
437 Option::OptionClass OptClass,
438 unsigned TableIndex,
T Value) {
440 static_cast<unsigned>(
Value));
447 auto *Arg = Args.getLastArg(Opt);
450 return std::string(Arg->getValue());
453 template <
typename IntTy>
457 auto *Arg = Args.getLastArg(Opt);
461 if (StringRef(Arg->getValue()).getAsInteger(0, Res)) {
462 Diags.
Report(diag::err_drv_invalid_int_value)
463 << Arg->getAsString(Args) << Arg->getValue();
469 static std::optional<std::vector<std::string>>
472 return Args.getAllArgValues(Opt);
476 const Twine &Spelling,
477 Option::OptionClass OptClass,
479 const std::vector<std::string> &Values) {
481 case Option::CommaJoinedClass: {
482 std::string CommaJoinedValue;
483 if (!Values.empty()) {
484 CommaJoinedValue.append(Values.front());
485 for (
const std::string &
Value : llvm::drop_begin(Values, 1)) {
486 CommaJoinedValue.append(
",");
487 CommaJoinedValue.append(
Value);
491 TableIndex, CommaJoinedValue);
494 case Option::JoinedClass:
495 case Option::SeparateClass:
496 case Option::JoinedOrSeparateClass:
497 for (
const std::string &
Value : Values)
501 llvm_unreachable(
"Cannot denormalize an option with option class "
502 "incompatible with string vector denormalization.");
510 auto *Arg = Args.getLastArg(Opt);
516 template <
typename T,
typename U>
518 return static_cast<T>(
Value);
522 return KeyPath |
Value;
529 template <
typename T,
typename U, U Value>
534 #define PARSE_OPTION_WITH_MARSHALLING( \
535 ARGS, DIAGS, PREFIX_TYPE, SPELLING, ID, KIND, GROUP, ALIAS, ALIASARGS, \
536 FLAGS, VISIBILITY, PARAM, HELPTEXT, HELPTEXTSFORVARIANTS, METAVAR, VALUES, \
537 SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, IMPLIED_CHECK, \
538 IMPLIED_VALUE, NORMALIZER, DENORMALIZER, MERGER, EXTRACTOR, TABLE_INDEX) \
539 if ((VISIBILITY) & options::CC1Option) { \
540 KEYPATH = MERGER(KEYPATH, DEFAULT_VALUE); \
542 KEYPATH = MERGER(KEYPATH, IMPLIED_VALUE); \
544 if (auto MaybeValue = NORMALIZER(OPT_##ID, TABLE_INDEX, ARGS, DIAGS)) \
546 MERGER(KEYPATH, static_cast<decltype(KEYPATH)>(*MaybeValue)); \
551 #define GENERATE_OPTION_WITH_MARSHALLING( \
552 CONSUMER, PREFIX_TYPE, SPELLING, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, \
553 VISIBILITY, PARAM, HELPTEXT, HELPTEXTSFORVARIANTS, METAVAR, VALUES, \
554 SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, IMPLIED_CHECK, \
555 IMPLIED_VALUE, NORMALIZER, DENORMALIZER, MERGER, EXTRACTOR, TABLE_INDEX) \
556 if ((VISIBILITY) & options::CC1Option) { \
557 [&](const auto &Extracted) { \
560 static_cast<decltype(KEYPATH)>((IMPLIED_CHECK) ? (IMPLIED_VALUE) \
561 : (DEFAULT_VALUE)))) \
562 DENORMALIZER(CONSUMER, SPELLING, Option::KIND##Class, TABLE_INDEX, \
564 }(EXTRACTOR(KEYPATH)); \
578 CodeGenOpts.XRayInstrumentFunctions = LangOpts.XRayInstrument;
579 CodeGenOpts.XRayAlwaysEmitCustomEvents = LangOpts.XRayAlwaysEmitCustomEvents;
580 CodeGenOpts.XRayAlwaysEmitTypedEvents = LangOpts.XRayAlwaysEmitTypedEvents;
581 CodeGenOpts.DisableFree = FrontendOpts.
DisableFree;
584 CodeGenOpts.ClearASTBeforeBackend =
false;
586 LangOpts.ForceEmitVTables = CodeGenOpts.ForceEmitVTables;
587 LangOpts.SpeculativeLoadHardening = CodeGenOpts.SpeculativeLoadHardening;
590 llvm::Triple
T(TargetOpts.
Triple);
591 llvm::Triple::ArchType Arch =
T.getArch();
596 if (LangOpts.getExceptionHandling() !=
598 T.isWindowsMSVCEnvironment())
599 Diags.
Report(diag::err_fe_invalid_exception_model)
600 <<
static_cast<unsigned>(LangOpts.getExceptionHandling()) <<
T.str();
602 if (LangOpts.AppleKext && !LangOpts.CPlusPlus)
603 Diags.
Report(diag::warn_c_kext);
605 if (LangOpts.NewAlignOverride &&
606 !llvm::isPowerOf2_32(LangOpts.NewAlignOverride)) {
607 Arg *A = Args.getLastArg(OPT_fnew_alignment_EQ);
608 Diags.
Report(diag::err_fe_invalid_alignment)
609 << A->getAsString(Args) << A->getValue();
610 LangOpts.NewAlignOverride = 0;
614 if (LangOpts.SYCLIsDevice && LangOpts.SYCLIsHost)
615 Diags.
Report(diag::err_drv_argument_not_allowed_with) <<
"-fsycl-is-device"
620 if (LangOpts.SYCLEnableIntHeaderDiags && !LangOpts.SYCLIsHost)
621 Diags.
Report(diag::err_opt_not_valid_without_opt)
622 <<
"-fsycl-enable-int-header-diags"
625 if (Args.hasArg(OPT_fgnu89_inline) && LangOpts.CPlusPlus)
626 Diags.
Report(diag::err_drv_argument_not_allowed_with)
629 if (Args.hasArg(OPT_hlsl_entrypoint) && !LangOpts.HLSL)
630 Diags.
Report(diag::err_drv_argument_not_allowed_with)
633 if (Args.hasArg(OPT_fgpu_allow_device_init) && !LangOpts.HIP)
634 Diags.
Report(diag::warn_ignored_hip_only_option)
635 << Args.getLastArg(OPT_fgpu_allow_device_init)->getAsString(Args);
637 if (Args.hasArg(OPT_gpu_max_threads_per_block_EQ) && !LangOpts.HIP)
638 Diags.
Report(diag::warn_ignored_hip_only_option)
639 << Args.getLastArg(OPT_gpu_max_threads_per_block_EQ)->getAsString(Args);
648 if (Args.hasArg(OPT_ffp_eval_method_EQ)) {
649 if (LangOpts.ApproxFunc)
650 Diags.
Report(diag::err_incompatible_fp_eval_method_options) << 0;
651 if (LangOpts.AllowFPReassoc)
652 Diags.
Report(diag::err_incompatible_fp_eval_method_options) << 1;
653 if (LangOpts.AllowRecip)
654 Diags.
Report(diag::err_incompatible_fp_eval_method_options) << 2;
660 if (Args.getLastArg(OPT_cl_strict_aliasing) &&
662 Diags.
Report(diag::warn_option_invalid_ocl_version)
664 << Args.getLastArg(OPT_cl_strict_aliasing)->getAsString(Args);
666 if (Arg *A = Args.getLastArg(OPT_fdefault_calling_conv_EQ)) {
667 auto DefaultCC = LangOpts.getDefaultCallingConv();
671 Arch != llvm::Triple::x86;
677 Diags.
Report(diag::err_drv_argument_not_allowed_with)
678 << A->getSpelling() <<
T.getTriple();
690 unsigned DefaultOpt = 0;
693 !Args.hasArg(OPT_cl_opt_disable))
696 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
697 if (A->getOption().matches(options::OPT_O0))
700 if (A->getOption().matches(options::OPT_Ofast))
703 assert(A->getOption().matches(options::OPT_O));
705 StringRef S(A->getValue());
706 if (S ==
"s" || S ==
"z")
719 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
720 if (A->getOption().matches(options::OPT_O)) {
721 switch (A->getValue()[0]) {
735 llvm::opt::OptSpecifier OptSpecifier) {
738 Option::OptionClass::FlagClass, 0);
742 llvm::opt::OptSpecifier OptSpecifier,
743 const Twine &
Value) {
781 bool CheckAgainstOriginalInvocation =
false,
782 bool ForceRoundTrip =
false) {
784 bool DoRoundTripDefault =
true;
786 bool DoRoundTripDefault =
false;
789 bool DoRoundTrip = DoRoundTripDefault;
790 if (ForceRoundTrip) {
793 for (
const auto *Arg : CommandLineArgs) {
794 if (Arg == StringRef(
"-round-trip-args"))
796 if (Arg == StringRef(
"-no-round-trip-args"))
804 return Parse(RealInvocation, CommandLineArgs, Diags, Argv0);
809 llvm::raw_string_ostream OS(Buffer);
810 for (
const char *Arg : Args) {
811 llvm::sys::printArg(OS, Arg,
true);
824 if (!Parse(DummyInvocation, CommandLineArgs, DummyDiags, Argv0) ||
831 auto Success = Parse(RealInvocation, CommandLineArgs, Diags, Argv0);
837 Diags.
Report(diag::err_cc1_round_trip_fail_then_ok);
838 Diags.
Report(diag::note_cc1_round_trip_original)
839 << SerializeArgs(CommandLineArgs);
844 llvm::BumpPtrAllocator Alloc;
845 llvm::StringSaver StringPool(Alloc);
846 auto SA = [&StringPool](
const Twine &Arg) {
847 return StringPool.save(Arg).data();
854 Generate(DummyInvocation, GeneratedArgs, SA);
860 bool Success2 = Parse(RealInvocation, GeneratedArgs, Diags, Argv0);
865 Diags.
Report(diag::err_cc1_round_trip_ok_then_fail);
866 Diags.
Report(diag::note_cc1_round_trip_generated)
867 << 1 << SerializeArgs(GeneratedArgs);
872 if (CheckAgainstOriginalInvocation)
874 ComparisonArgs.assign(CommandLineArgs.begin(), CommandLineArgs.end());
878 Generate(RealInvocation, ComparisonArgs, SA);
883 return std::equal(A.begin(), A.end(), B.begin(), B.end(),
884 [](
const char *AElem,
const char *BElem) {
885 return StringRef(AElem) == StringRef(BElem);
892 if (!
Equal(GeneratedArgs, ComparisonArgs)) {
893 Diags.
Report(diag::err_cc1_round_trip_mismatch);
894 Diags.
Report(diag::note_cc1_round_trip_generated)
895 << 1 << SerializeArgs(GeneratedArgs);
896 Diags.
Report(diag::note_cc1_round_trip_generated)
897 << 2 << SerializeArgs(ComparisonArgs);
901 Diags.
Report(diag::remark_cc1_round_trip_generated)
902 << 1 << SerializeArgs(GeneratedArgs);
903 Diags.
Report(diag::remark_cc1_round_trip_generated)
904 << 2 << SerializeArgs(ComparisonArgs);
916 return CreateFromArgsImpl(Invocation, CommandLineArgs, Diags, Argv0);
920 Args.push_back(
"-cc1");
923 DummyInvocation1, DummyInvocation2, Args, Diags, Argv0,
928 OptSpecifier GroupWithValue,
929 std::vector<std::string> &Diagnostics) {
930 for (
auto *A : Args.filtered(
Group)) {
931 if (A->getOption().getKind() == Option::FlagClass) {
934 Diagnostics.push_back(
935 std::string(A->getOption().getName().drop_front(1)));
936 }
else if (A->getOption().matches(GroupWithValue)) {
939 Diagnostics.push_back(
940 std::string(A->getOption().getName().drop_front(1).rtrim(
"=-")));
943 Diagnostics.push_back(A->getValue());
954 std::vector<std::string> &Funcs) {
955 std::vector<std::string> Values = Args.getAllArgValues(OPT_fno_builtin_);
957 Funcs.insert(Funcs.end(), Values.begin(), BuiltinEnd);
964 #define ANALYZER_OPTION_WITH_MARSHALLING(...) \
965 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
966 #include "clang/Driver/Options.inc"
967 #undef ANALYZER_OPTION_WITH_MARSHALLING
971 #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) \
973 GenerateArg(Consumer, OPT_analyzer_constraints, CMDFLAG); \
975 #include "clang/StaticAnalyzer/Core/Analyses.def"
977 llvm_unreachable(
"Tried to generate unknown analysis constraint.");
983 #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN) \
985 GenerateArg(Consumer, OPT_analyzer_output, CMDFLAG); \
987 #include "clang/StaticAnalyzer/Core/Analyses.def"
989 llvm_unreachable(
"Tried to generate unknown analysis diagnostic client.");
995 #define ANALYSIS_PURGE(NAME, CMDFLAG, DESC) \
997 GenerateArg(Consumer, OPT_analyzer_purge, CMDFLAG); \
999 #include "clang/StaticAnalyzer/Core/Analyses.def"
1001 llvm_unreachable(
"Tried to generate unknown analysis purge mode.");
1007 #define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC) \
1009 GenerateArg(Consumer, OPT_analyzer_inlining_mode, CMDFLAG); \
1011 #include "clang/StaticAnalyzer/Core/Analyses.def"
1013 llvm_unreachable(
"Tried to generate unknown analysis inlining mode.");
1019 CP.second ? OPT_analyzer_checker : OPT_analyzer_disable_checker;
1028 for (
const auto &C : Opts.
Config)
1029 SortedConfigOpts.emplace_back(C.getKey(), C.getValue());
1030 llvm::sort(SortedConfigOpts, llvm::less_first());
1032 for (
const auto &[Key,
Value] : SortedConfigOpts) {
1035 auto Entry = ConfigOpts.
Config.find(Key);
1036 if (Entry != ConfigOpts.
Config.end() && Entry->getValue() ==
Value)
1051 #define ANALYZER_OPTION_WITH_MARSHALLING(...) \
1052 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
1053 #include "clang/Driver/Options.inc"
1054 #undef ANALYZER_OPTION_WITH_MARSHALLING
1056 if (Arg *A = Args.getLastArg(OPT_analyzer_constraints)) {
1057 StringRef Name = A->getValue();
1059 #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) \
1060 .Case(CMDFLAG, NAME##Model)
1061 #include "clang/StaticAnalyzer/Core/Analyses.def"
1064 Diags.
Report(diag::err_drv_invalid_value)
1065 << A->getAsString(Args) << Name;
1067 #ifndef LLVM_WITH_Z3
1068 if (
Value == AnalysisConstraints::Z3ConstraintsModel) {
1069 Diags.
Report(diag::err_analyzer_not_built_with_z3);
1076 if (Arg *A = Args.getLastArg(OPT_analyzer_output)) {
1077 StringRef Name = A->getValue();
1079 #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN) \
1080 .Case(CMDFLAG, PD_##NAME)
1081 #include "clang/StaticAnalyzer/Core/Analyses.def"
1084 Diags.
Report(diag::err_drv_invalid_value)
1085 << A->getAsString(Args) << Name;
1091 if (Arg *A = Args.getLastArg(OPT_analyzer_purge)) {
1092 StringRef Name = A->getValue();
1094 #define ANALYSIS_PURGE(NAME, CMDFLAG, DESC) \
1095 .Case(CMDFLAG, NAME)
1096 #include "clang/StaticAnalyzer/Core/Analyses.def"
1099 Diags.
Report(diag::err_drv_invalid_value)
1100 << A->getAsString(Args) << Name;
1106 if (Arg *A = Args.getLastArg(OPT_analyzer_inlining_mode)) {
1107 StringRef Name = A->getValue();
1109 #define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC) \
1110 .Case(CMDFLAG, NAME)
1111 #include "clang/StaticAnalyzer/Core/Analyses.def"
1114 Diags.
Report(diag::err_drv_invalid_value)
1115 << A->getAsString(Args) << Name;
1123 Args.filtered(OPT_analyzer_checker, OPT_analyzer_disable_checker)) {
1125 bool IsEnabled = A->getOption().getID() == OPT_analyzer_checker;
1128 StringRef CheckerAndPackageList = A->getValue();
1130 CheckerAndPackageList.split(CheckersAndPackages,
",");
1131 for (
const StringRef &CheckerOrPackage : CheckersAndPackages)
1137 for (
const auto *A : Args.filtered(OPT_analyzer_config)) {
1141 StringRef configList = A->getValue();
1143 configList.split(configVals,
",");
1144 for (
const auto &configVal : configVals) {
1146 std::tie(key, val) = configVal.split(
"=");
1149 diag::err_analyzer_config_no_value) << configVal;
1152 if (val.contains(
'=')) {
1154 diag::err_analyzer_config_multiple_values)
1163 Diags.
Report(diag::err_analyzer_config_unknown) << key;
1168 Opts.
Config[key] = std::string(val);
1178 for (
unsigned i = 0; i < Args.getNumInputArgStrings(); ++i) {
1181 os << Args.getArgString(i);
1189 StringRef OptionName, StringRef DefaultVal) {
1190 return Config.insert({OptionName, std::string(DefaultVal)}).first->second;
1195 StringRef &OptionField, StringRef Name,
1196 StringRef DefaultVal) {
1205 bool &OptionField, StringRef Name,
bool DefaultVal) {
1206 auto PossiblyInvalidVal =
1207 llvm::StringSwitch<std::optional<bool>>(
1210 .Case(
"false",
false)
1211 .Default(std::nullopt);
1213 if (!PossiblyInvalidVal) {
1215 Diags->
Report(diag::err_analyzer_config_invalid_input)
1216 << Name <<
"a boolean";
1218 OptionField = DefaultVal;
1220 OptionField = *PossiblyInvalidVal;
1225 unsigned &OptionField, StringRef Name,
1226 unsigned DefaultVal) {
1228 OptionField = DefaultVal;
1229 bool HasFailed =
getStringOption(Config, Name, std::to_string(DefaultVal))
1230 .getAsInteger(0, OptionField);
1231 if (Diags && HasFailed)
1232 Diags->
Report(diag::err_analyzer_config_invalid_input)
1233 << Name <<
"an unsigned";
1241 #define ANALYZER_OPTION(TYPE, NAME, CMDFLAG, DESC, DEFAULT_VAL) \
1242 initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, DEFAULT_VAL);
1243 #define ANALYZER_OPTION_DEPENDS_ON_USER_MODE(...)
1244 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.def"
1246 assert(AnOpts.UserMode ==
"shallow" || AnOpts.UserMode ==
"deep");
1247 const bool InShallowMode = AnOpts.UserMode ==
"shallow";
1249 #define ANALYZER_OPTION(...)
1250 #define ANALYZER_OPTION_DEPENDS_ON_USER_MODE(TYPE, NAME, CMDFLAG, DESC, \
1251 SHALLOW_VAL, DEEP_VAL) \
1252 initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, \
1253 InShallowMode ? SHALLOW_VAL : DEEP_VAL);
1254 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.def"
1261 if (!AnOpts.RawSilencedCheckersAndPackages.empty()) {
1262 std::vector<StringRef> Checkers =
1264 std::vector<StringRef> Packages =
1268 AnOpts.RawSilencedCheckersAndPackages.split(CheckersAndPackages,
";");
1270 for (
const StringRef &CheckerOrPackage : CheckersAndPackages) {
1272 bool IsChecker = CheckerOrPackage.contains(
'.');
1273 bool IsValidName = IsChecker
1274 ? llvm::is_contained(Checkers, CheckerOrPackage)
1275 : llvm::is_contained(Packages, CheckerOrPackage);
1278 Diags->
Report(diag::err_unknown_analyzer_checker_or_package)
1279 << CheckerOrPackage;
1289 if (AnOpts.ShouldTrackConditionsDebug && !AnOpts.ShouldTrackConditions)
1290 Diags->
Report(diag::err_analyzer_config_invalid_input)
1291 <<
"track-conditions-debug" <<
"'track-conditions' to also be enabled";
1293 if (!AnOpts.CTUDir.empty() && !llvm::sys::fs::is_directory(AnOpts.CTUDir))
1294 Diags->
Report(diag::err_analyzer_config_invalid_input) <<
"ctu-dir"
1297 if (!AnOpts.ModelPath.empty() &&
1298 !llvm::sys::fs::is_directory(AnOpts.ModelPath))
1299 Diags->
Report(diag::err_analyzer_config_invalid_input) <<
"model-path"
1308 if (Remark.hasValidPattern()) {
1313 GenerateArg(Consumer, OPT_R_Joined, StringRef(
"no-") + Name);
1322 OptSpecifier OptEQ, StringRef Name) {
1325 auto InitializeResultPattern = [&Diags, &Args, &Result](
const Arg *A,
1326 StringRef Pattern) {
1327 Result.Pattern = Pattern.str();
1329 std::string RegexError;
1330 Result.Regex = std::make_shared<llvm::Regex>(Result.Pattern);
1331 if (!Result.Regex->isValid(RegexError)) {
1332 Diags.
Report(diag::err_drv_optimization_remark_pattern)
1333 << RegexError << A->getAsString(Args);
1340 for (Arg *A : Args) {
1341 if (A->getOption().matches(OPT_R_Joined)) {
1342 StringRef
Value = A->getValue();
1346 else if (
Value ==
"everything")
1348 else if (
Value.split(
'-') == std::make_pair(StringRef(
"no"), Name))
1350 else if (
Value ==
"no-everything")
1357 Result.Pattern =
"";
1358 Result.Regex =
nullptr;
1360 InitializeResultPattern(A,
".*");
1362 }
else if (A->getOption().matches(OptEQ)) {
1364 if (!InitializeResultPattern(A, A->getValue()))
1373 const std::vector<std::string> &Levels,
1376 bool Success =
true;
1377 for (
const auto &
Level : Levels) {
1379 llvm::StringSwitch<DiagnosticLevelMask>(
Level)
1387 Diags.
Report(diag::err_drv_invalid_value) << FlagName <<
Level;
1395 const std::vector<std::string> &Sanitizers,
1397 for (
const auto &Sanitizer : Sanitizers) {
1400 Diags.
Report(diag::err_drv_invalid_value) << FlagName << Sanitizer;
1416 llvm::SplitString(Bundle, BundleParts,
",");
1417 for (
const auto &B : BundleParts) {
1421 D.
Report(diag::err_drv_invalid_value) << FlagName << Bundle;
1435 llvm::raw_string_ostream OS(Buffer);
1436 llvm::interleave(BundleParts, OS, [&OS](StringRef Part) { OS << Part; },
",");
1442 const Twine &ProfileName,
1443 llvm::vfs::FileSystem &FS,
1446 if (
auto E = ReaderOrErr.takeError()) {
1448 "Error in reading profile %0: %1");
1449 llvm::handleAllErrors(std::move(E), [&](
const llvm::ErrorInfoBase &EI) {
1450 Diags.
Report(DiagID) << ProfileName.str() << EI.message();
1454 std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader =
1455 std::move(ReaderOrErr.get());
1459 if (PGOReader->isIRLevelProfile() || PGOReader->hasMemoryProfile()) {
1460 if (PGOReader->hasCSIRLevelProfile())
1468 void CompilerInvocationBase::GenerateCodeGenArgs(
const CodeGenOptions &Opts,
1470 const llvm::Triple &
T,
1471 const std::string &OutputFile,
1475 if (Opts.OptimizationLevel == 0)
1478 GenerateArg(Consumer, OPT_O, Twine(Opts.OptimizationLevel));
1480 #define CODEGEN_OPTION_WITH_MARSHALLING(...) \
1481 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
1482 #include "clang/Driver/Options.inc"
1483 #undef CODEGEN_OPTION_WITH_MARSHALLING
1485 if (Opts.OptimizationLevel > 0) {
1489 GenerateArg(Consumer, OPT_finline_hint_functions);
1494 if (Opts.DirectAccessExternalData &&
LangOpts->PICLevel != 0)
1495 GenerateArg(Consumer, OPT_fdirect_access_external_data);
1496 else if (!Opts.DirectAccessExternalData &&
LangOpts->PICLevel == 0)
1497 GenerateArg(Consumer, OPT_fno_direct_access_external_data);
1499 std::optional<StringRef> DebugInfoVal;
1500 switch (Opts.DebugInfo) {
1501 case llvm::codegenoptions::DebugLineTablesOnly:
1502 DebugInfoVal =
"line-tables-only";
1504 case llvm::codegenoptions::DebugDirectivesOnly:
1505 DebugInfoVal =
"line-directives-only";
1507 case llvm::codegenoptions::DebugInfoConstructor:
1508 DebugInfoVal =
"constructor";
1510 case llvm::codegenoptions::LimitedDebugInfo:
1511 DebugInfoVal =
"limited";
1513 case llvm::codegenoptions::FullDebugInfo:
1514 DebugInfoVal =
"standalone";
1516 case llvm::codegenoptions::UnusedTypeInfo:
1517 DebugInfoVal =
"unused-types";
1519 case llvm::codegenoptions::NoDebugInfo:
1520 DebugInfoVal = std::nullopt;
1522 case llvm::codegenoptions::LocTrackingOnly:
1523 DebugInfoVal = std::nullopt;
1527 GenerateArg(Consumer, OPT_debug_info_kind_EQ, *DebugInfoVal);
1531 Prefix.first +
"=" + Prefix.second);
1534 GenerateArg(Consumer, OPT_fcoverage_prefix_map_EQ,
1535 Prefix.first +
"=" + Prefix.second);
1537 if (Opts.NewStructPathTBAA)
1540 if (Opts.OptimizeSize == 1)
1542 else if (Opts.OptimizeSize == 2)
1550 if (Opts.UnrollLoops && Opts.OptimizationLevel <= 1)
1552 else if (!Opts.UnrollLoops && Opts.OptimizationLevel > 1)
1558 if (Opts.DebugNameTable ==
1559 static_cast<unsigned>(llvm::DICompileUnit::DebugNameTableKind::GNU))
1561 else if (Opts.DebugNameTable ==
1562 static_cast<unsigned>(
1563 llvm::DICompileUnit::DebugNameTableKind::Default))
1566 if (Opts.DebugTemplateAlias)
1569 auto TNK = Opts.getDebugSimpleTemplateNames();
1570 if (TNK != llvm::codegenoptions::DebugTemplateNamesKind::Full) {
1571 if (TNK == llvm::codegenoptions::DebugTemplateNamesKind::Simple)
1572 GenerateArg(Consumer, OPT_gsimple_template_names_EQ,
"simple");
1573 else if (TNK == llvm::codegenoptions::DebugTemplateNamesKind::Mangled)
1574 GenerateArg(Consumer, OPT_gsimple_template_names_EQ,
"mangled");
1579 if (Opts.TimePasses) {
1580 if (Opts.TimePassesPerRun)
1581 GenerateArg(Consumer, OPT_ftime_report_EQ,
"per-pass-run");
1586 if (Opts.PrepareForLTO && !Opts.PrepareForThinLTO)
1589 if (Opts.PrepareForThinLTO)
1598 StringRef MemProfileBasename(
"memprof.profraw");
1619 std::string InstrBundle =
1621 if (!InstrBundle.empty())
1622 GenerateArg(Consumer, OPT_fxray_instrumentation_bundle, InstrBundle);
1625 if (Opts.CFProtectionReturn && Opts.CFProtectionBranch)
1626 GenerateArg(Consumer, OPT_fcf_protection_EQ,
"full");
1627 else if (Opts.CFProtectionReturn)
1628 GenerateArg(Consumer, OPT_fcf_protection_EQ,
"return");
1629 else if (Opts.CFProtectionBranch)
1630 GenerateArg(Consumer, OPT_fcf_protection_EQ,
"branch");
1632 if (Opts.FunctionReturnThunks)
1633 GenerateArg(Consumer, OPT_mfunction_return_EQ,
"thunk-extern");
1636 bool Builtint = F.LinkFlags == llvm::Linker::Flags::LinkOnlyNeeded &&
1637 F.PropagateAttrs && F.Internalize;
1639 Builtint ? OPT_mlink_builtin_bitcode : OPT_mlink_bitcode_file,
1643 if (Opts.EmulatedTLS)
1651 GenerateArg(Consumer, OPT_fdenormal_fp_math_f32_EQ,
1656 T.isPPC32() ? OPT_maix_struct_return : OPT_fpcc_struct_return;
1660 T.isPPC32() ? OPT_msvr4_struct_return : OPT_freg_struct_return;
1664 if (Opts.EnableAIXExtendedAltivecABI)
1667 if (Opts.XCOFFReadOnlyPointers)
1685 GenerateArg(Consumer, OPT_fdiagnostics_hotness_threshold_EQ,
1690 GenerateArg(Consumer, OPT_fdiagnostics_misexpect_tolerance_EQ,
1694 GenerateArg(Consumer, OPT_fsanitize_recover_EQ, Sanitizer);
1697 GenerateArg(Consumer, OPT_fsanitize_trap_EQ, Sanitizer);
1699 if (!Opts.EmitVersionIdentMetadata)
1702 switch (Opts.FiniteLoops) {
1705 case CodeGenOptions::FiniteLoopsKind::Always:
1708 case CodeGenOptions::FiniteLoopsKind::Never:
1714 bool CompilerInvocation::ParseCodeGenArgs(
CodeGenOptions &Opts, ArgList &Args,
1717 const llvm::Triple &
T,
1718 const std::string &OutputFile,
1724 unsigned MaxOptLevel = 3;
1725 if (OptimizationLevel > MaxOptLevel) {
1728 Diags.
Report(diag::warn_drv_optimization_value)
1729 << Args.getLastArg(OPT_O)->getAsString(Args) <<
"-O" << MaxOptLevel;
1730 OptimizationLevel = MaxOptLevel;
1732 Opts.OptimizationLevel = OptimizationLevel;
1741 #define CODEGEN_OPTION_WITH_MARSHALLING(...) \
1742 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
1743 #include "clang/Driver/Options.inc"
1744 #undef CODEGEN_OPTION_WITH_MARSHALLING
1748 if (Opts.OptimizationLevel == 0) {
1750 }
else if (
const Arg *A = Args.getLastArg(options::OPT_finline_functions,
1751 options::OPT_finline_hint_functions,
1752 options::OPT_fno_inline_functions,
1753 options::OPT_fno_inline)) {
1756 if (A->getOption().matches(options::OPT_finline_functions))
1758 else if (A->getOption().matches(options::OPT_finline_hint_functions))
1768 Opts.DirectAccessExternalData =
1769 Args.hasArg(OPT_fdirect_access_external_data) ||
1770 (!Args.hasArg(OPT_fno_direct_access_external_data) &&
1773 if (Arg *A = Args.getLastArg(OPT_debug_info_kind_EQ)) {
1775 llvm::StringSwitch<unsigned>(A->getValue())
1776 .Case(
"line-tables-only", llvm::codegenoptions::DebugLineTablesOnly)
1777 .Case(
"line-directives-only",
1778 llvm::codegenoptions::DebugDirectivesOnly)
1779 .Case(
"constructor", llvm::codegenoptions::DebugInfoConstructor)
1780 .Case(
"limited", llvm::codegenoptions::LimitedDebugInfo)
1781 .Case(
"standalone", llvm::codegenoptions::FullDebugInfo)
1782 .Case(
"unused-types", llvm::codegenoptions::UnusedTypeInfo)
1785 Diags.
Report(diag::err_drv_invalid_value) << A->getAsString(Args)
1788 Opts.setDebugInfo(
static_cast<llvm::codegenoptions::DebugInfoKind
>(Val));
1794 Args.getLastArg(OPT_fuse_ctor_homing, OPT_fno_use_ctor_homing)) {
1795 if (A->getOption().matches(OPT_fuse_ctor_homing) &&
1796 Opts.getDebugInfo() == llvm::codegenoptions::LimitedDebugInfo)
1797 Opts.setDebugInfo(llvm::codegenoptions::DebugInfoConstructor);
1798 if (A->getOption().matches(OPT_fno_use_ctor_homing) &&
1799 Opts.getDebugInfo() == llvm::codegenoptions::DebugInfoConstructor)
1800 Opts.setDebugInfo(llvm::codegenoptions::LimitedDebugInfo);
1803 for (
const auto &Arg : Args.getAllArgValues(OPT_fdebug_prefix_map_EQ)) {
1804 auto Split = StringRef(Arg).split(
'=');
1808 for (
const auto &Arg : Args.getAllArgValues(OPT_fcoverage_prefix_map_EQ)) {
1809 auto Split = StringRef(Arg).split(
'=');
1813 const llvm::Triple::ArchType DebugEntryValueArchs[] = {
1814 llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::aarch64,
1815 llvm::Triple::arm, llvm::Triple::armeb, llvm::Triple::mips,
1816 llvm::Triple::mipsel, llvm::Triple::mips64, llvm::Triple::mips64el};
1819 llvm::is_contained(DebugEntryValueArchs,
T.getArch()))
1820 Opts.EmitCallSiteInfo =
true;
1823 Diags.
Report(diag::warn_ignoring_verify_debuginfo_preserve_export)
1828 Opts.NewStructPathTBAA = !Args.hasArg(OPT_no_struct_path_tbaa) &&
1829 Args.hasArg(OPT_new_struct_path_tbaa);
1831 Opts.SimplifyLibCalls = !
LangOpts->NoBuiltin;
1832 if (Opts.SimplifyLibCalls)
1835 Args.hasFlag(OPT_funroll_loops, OPT_fno_unroll_loops,
1836 (Opts.OptimizationLevel > 1));
1838 std::string(Args.getLastArgValue(OPT_fbinutils_version_EQ));
1840 Opts.DebugTemplateAlias = Args.hasArg(OPT_gtemplate_alias);
1842 Opts.DebugNameTable =
static_cast<unsigned>(
1843 Args.hasArg(OPT_ggnu_pubnames)
1844 ? llvm::DICompileUnit::DebugNameTableKind::GNU
1845 : Args.hasArg(OPT_gpubnames)
1846 ? llvm::DICompileUnit::DebugNameTableKind::Default
1848 if (
const Arg *A = Args.getLastArg(OPT_gsimple_template_names_EQ)) {
1849 StringRef
Value = A->getValue();
1851 Diags.
Report(diag::err_drv_unsupported_option_argument)
1852 << A->getSpelling() << A->getValue();
1853 Opts.setDebugSimpleTemplateNames(
1854 StringRef(A->getValue()) ==
"simple"
1855 ? llvm::codegenoptions::DebugTemplateNamesKind::Simple
1856 : llvm::codegenoptions::DebugTemplateNamesKind::Mangled);
1859 if (
const Arg *A = Args.getLastArg(OPT_ftime_report, OPT_ftime_report_EQ)) {
1860 Opts.TimePasses =
true;
1863 if (A->getOption().getID() == OPT_ftime_report_EQ) {
1864 StringRef Val = A->getValue();
1865 if (Val ==
"per-pass")
1866 Opts.TimePassesPerRun =
false;
1867 else if (Val ==
"per-pass-run")
1868 Opts.TimePassesPerRun =
true;
1870 Diags.
Report(diag::err_drv_invalid_value)
1871 << A->getAsString(Args) << A->getValue();
1875 Opts.PrepareForLTO =
false;
1876 Opts.PrepareForThinLTO =
false;
1877 if (Arg *A = Args.getLastArg(OPT_flto_EQ)) {
1878 Opts.PrepareForLTO =
true;
1879 StringRef S = A->getValue();
1881 Opts.PrepareForThinLTO =
true;
1882 else if (S !=
"full")
1883 Diags.
Report(diag::err_drv_invalid_value) << A->getAsString(Args) << S;
1884 if (Args.hasArg(OPT_funified_lto))
1885 Opts.PrepareForThinLTO =
true;
1887 if (Arg *A = Args.getLastArg(OPT_fthinlto_index_EQ)) {
1889 Diags.
Report(diag::err_drv_argument_only_allowed_with)
1890 << A->getAsString(Args) <<
"-x ir";
1892 std::string(Args.getLastArgValue(OPT_fthinlto_index_EQ));
1894 if (Arg *A = Args.getLastArg(OPT_save_temps_EQ))
1896 llvm::StringSwitch<std::string>(A->getValue())
1897 .Case(
"obj", OutputFile)
1898 .Default(llvm::sys::path::filename(OutputFile).str());
1901 const char *MemProfileBasename =
"memprof.profraw";
1902 if (Args.hasArg(OPT_fmemory_profile_EQ)) {
1904 std::string(Args.getLastArgValue(OPT_fmemory_profile_EQ)));
1905 llvm::sys::path::append(Path, MemProfileBasename);
1907 }
else if (Args.hasArg(OPT_fmemory_profile))
1912 if (Args.hasArg(OPT_coverage_version_EQ)) {
1913 StringRef CoverageVersion = Args.getLastArgValue(OPT_coverage_version_EQ);
1914 if (CoverageVersion.size() != 4) {
1915 Diags.
Report(diag::err_drv_invalid_value)
1916 << Args.getLastArg(OPT_coverage_version_EQ)->getAsString(Args)
1926 for (
const auto &A : Args) {
1928 if (A->getOption().getID() == options::OPT_o ||
1929 A->getOption().getID() == options::OPT_INPUT ||
1930 A->getOption().getID() == options::OPT_x ||
1931 A->getOption().getID() == options::OPT_fembed_bitcode ||
1932 A->getOption().matches(options::OPT_W_Group))
1935 A->render(Args, ASL);
1936 for (
const auto &
arg : ASL) {
1937 StringRef ArgStr(
arg);
1938 Opts.
CmdArgs.insert(Opts.
CmdArgs.end(), ArgStr.begin(), ArgStr.end());
1944 auto XRayInstrBundles =
1945 Args.getAllArgValues(OPT_fxray_instrumentation_bundle);
1946 if (XRayInstrBundles.empty())
1949 for (
const auto &A : XRayInstrBundles)
1953 if (
const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
1954 StringRef Name = A->getValue();
1955 if (Name ==
"full") {
1956 Opts.CFProtectionReturn = 1;
1957 Opts.CFProtectionBranch = 1;
1958 }
else if (Name ==
"return")
1959 Opts.CFProtectionReturn = 1;
1960 else if (Name ==
"branch")
1961 Opts.CFProtectionBranch = 1;
1962 else if (Name !=
"none")
1963 Diags.
Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
1966 if (
const Arg *A = Args.getLastArg(OPT_mfunction_return_EQ)) {
1967 auto Val = llvm::StringSwitch<llvm::FunctionReturnThunksKind>(A->getValue())
1968 .Case(
"keep", llvm::FunctionReturnThunksKind::Keep)
1969 .Case(
"thunk-extern", llvm::FunctionReturnThunksKind::Extern)
1970 .Default(llvm::FunctionReturnThunksKind::Invalid);
1973 Diags.
Report(diag::err_drv_argument_not_allowed_with)
1974 << A->getSpelling() <<
T.getTriple();
1975 else if (Val == llvm::FunctionReturnThunksKind::Invalid)
1976 Diags.
Report(diag::err_drv_invalid_value)
1977 << A->getAsString(Args) << A->getValue();
1978 else if (Val == llvm::FunctionReturnThunksKind::Extern &&
1979 Args.getLastArgValue(OPT_mcmodel_EQ) ==
"large")
1980 Diags.
Report(diag::err_drv_argument_not_allowed_with)
1981 << A->getAsString(Args)
1982 << Args.getLastArg(OPT_mcmodel_EQ)->getAsString(Args);
1984 Opts.FunctionReturnThunks =
static_cast<unsigned>(Val);
1988 Args.filtered(OPT_mlink_bitcode_file, OPT_mlink_builtin_bitcode)) {
1991 if (A->getOption().matches(OPT_mlink_builtin_bitcode)) {
1992 F.
LinkFlags = llvm::Linker::Flags::LinkOnlyNeeded;
2001 if (Arg *A = Args.getLastArg(OPT_fdenormal_fp_math_EQ)) {
2002 StringRef Val = A->getValue();
2006 Diags.
Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
2009 if (Arg *A = Args.getLastArg(OPT_fdenormal_fp_math_f32_EQ)) {
2010 StringRef Val = A->getValue();
2013 Diags.
Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
2019 Args.getLastArg(OPT_fpcc_struct_return, OPT_freg_struct_return,
2020 OPT_maix_struct_return, OPT_msvr4_struct_return)) {
2024 Diags.
Report(diag::err_drv_unsupported_opt_for_target)
2025 << A->getSpelling() <<
T.str();
2027 const Option &O = A->getOption();
2028 if (O.matches(OPT_fpcc_struct_return) ||
2029 O.matches(OPT_maix_struct_return)) {
2032 assert(O.matches(OPT_freg_struct_return) ||
2033 O.matches(OPT_msvr4_struct_return));
2038 if (Arg *A = Args.getLastArg(OPT_fsycl_instrument_device_code)) {
2039 if (!
T.isSPIROrSPIRV())
2040 Diags.
Report(diag::err_drv_unsupported_opt_for_target)
2041 << A->getSpelling() <<
T.str();
2042 Opts.SPIRITTAnnotations =
true;
2045 if (Arg *A = Args.getLastArg(OPT_mxcoff_roptr)) {
2047 Diags.
Report(diag::err_drv_unsupported_opt_for_target)
2048 << A->getSpelling() <<
T.str();
2058 if (!Args.hasFlag(OPT_fdata_sections, OPT_fno_data_sections,
false))
2059 Diags.
Report(diag::err_roptr_requires_data_sections);
2061 Opts.XCOFFReadOnlyPointers =
true;
2064 if (Arg *A = Args.getLastArg(OPT_mabi_EQ_quadword_atomics)) {
2065 if (!
T.isOSAIX() ||
T.isPPC32())
2066 Diags.
Report(diag::err_drv_unsupported_opt_for_target)
2067 << A->getSpelling() <<
T.str();
2070 bool NeedLocTracking =
false;
2075 NeedLocTracking =
true;
2077 if (Arg *A = Args.getLastArg(OPT_opt_record_passes)) {
2079 NeedLocTracking =
true;
2082 if (Arg *A = Args.getLastArg(OPT_opt_record_format)) {
2084 NeedLocTracking =
true;
2094 Diags, Args, OPT_Rpass_analysis_EQ,
"pass-analysis");
2104 if (Opts.DiagnosticsWithHotness && !UsingProfile &&
2107 Diags.
Report(diag::warn_drv_diagnostics_hotness_requires_pgo)
2108 <<
"-fdiagnostics-show-hotness";
2112 Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
2114 llvm::remarks::parseHotnessThresholdOption(
arg->getValue());
2117 Diags.
Report(diag::err_drv_invalid_diagnotics_hotness_threshold)
2118 <<
"-fdiagnostics-hotness-threshold=";
2124 Diags.
Report(diag::warn_drv_diagnostics_hotness_requires_pgo)
2125 <<
"-fdiagnostics-hotness-threshold=";
2130 Args.getLastArg(options::OPT_fdiagnostics_misexpect_tolerance_EQ)) {
2134 Diags.
Report(diag::err_drv_invalid_diagnotics_misexpect_tolerance)
2135 <<
"-fdiagnostics-misexpect-tolerance=";
2141 Diags.
Report(diag::warn_drv_diagnostics_misexpect_requires_pgo)
2142 <<
"-fdiagnostics-misexpect-tolerance=";
2149 if (UsingSampleProfile)
2150 NeedLocTracking =
true;
2153 NeedLocTracking =
true;
2157 if (NeedLocTracking &&
2158 Opts.getDebugInfo() == llvm::codegenoptions::NoDebugInfo)
2159 Opts.setDebugInfo(llvm::codegenoptions::LocTrackingOnly);
2164 Args.getAllArgValues(OPT_fsanitize_recover_EQ), Diags,
2167 Args.getAllArgValues(OPT_fsanitize_trap_EQ), Diags,
2170 Opts.EmitVersionIdentMetadata = Args.hasFlag(OPT_Qy, OPT_Qn,
true);
2172 if (Args.hasArg(options::OPT_ffinite_loops))
2173 Opts.FiniteLoops = CodeGenOptions::FiniteLoopsKind::Always;
2174 else if (Args.hasArg(options::OPT_fno_finite_loops))
2175 Opts.FiniteLoops = CodeGenOptions::FiniteLoopsKind::Never;
2177 Opts.EmitIEEENaNCompliantInsts = Args.hasFlag(
2178 options::OPT_mamdgpu_ieee, options::OPT_mno_amdgpu_ieee,
true);
2179 if (!Opts.EmitIEEENaNCompliantInsts && !LangOptsRef.NoHonorNaNs)
2180 Diags.
Report(diag::err_drv_amdgpu_ieee_without_no_honor_nans);
2188 #define DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING(...) \
2189 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
2190 #include "clang/Driver/Options.inc"
2191 #undef DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING
2196 for (
const auto &Dep : Opts.
ExtraDeps) {
2197 switch (Dep.second) {
2210 GenerateArg(Consumer, OPT_fdepfile_entry, Dep.first);
2219 bool ShowLineMarkers) {
2223 #define DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING(...) \
2224 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
2225 #include "clang/Driver/Options.inc"
2226 #undef DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING
2228 if (Args.hasArg(OPT_show_includes)) {
2243 if (!Args.hasArg(OPT_fno_sanitize_ignorelist)) {
2244 for (
const auto *A : Args.filtered(OPT_fsanitize_ignorelist_EQ)) {
2245 StringRef Val = A->getValue();
2246 if (!Val.contains(
'='))
2250 for (
const auto *A : Args.filtered(OPT_fsanitize_system_ignorelist_EQ)) {
2251 StringRef Val = A->getValue();
2252 if (!Val.contains(
'='))
2259 for (
const auto &
Filename : Args.getAllArgValues(OPT_fprofile_list_EQ))
2263 for (
const auto *A : Args.filtered(OPT_fdepfile_entry))
2267 for (
const auto *A : Args.filtered(OPT_fmodule_file)) {
2268 StringRef Val = A->getValue();
2269 if (!Val.contains(
'='))
2279 Diags.
Report(diag::err_drv_print_header_env_var_combination_cc1)
2280 << Args.getLastArg(OPT_header_include_format_EQ)->getValue()
2281 << Args.getLastArg(OPT_header_include_filtering_EQ)->getValue();
2295 }
ShowColors = DefaultColor ? Colors_Auto : Colors_Off;
2296 for (
auto *A : Args) {
2297 const Option &O = A->getOption();
2298 if (O.matches(options::OPT_fcolor_diagnostics)) {
2300 }
else if (O.matches(options::OPT_fno_color_diagnostics)) {
2302 }
else if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
2303 StringRef
Value(A->getValue());
2304 if (
Value ==
"always")
2306 else if (
Value ==
"never")
2308 else if (
Value ==
"auto")
2314 llvm::sys::Process::StandardErrHasColors());
2319 bool Success =
true;
2320 for (
const auto &Prefix : VerifyPrefixes) {
2323 auto BadChar = llvm::find_if(Prefix, [](
char C) {
2326 if (BadChar != Prefix.end() || !
isLetter(Prefix[0])) {
2328 Diags.
Report(diag::err_drv_invalid_value) <<
"-verify=" << Prefix;
2329 Diags.
Report(diag::note_drv_verify_prefix_spelling);
2339 #define FILE_SYSTEM_OPTION_WITH_MARSHALLING(...) \
2340 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
2341 #include "clang/Driver/Options.inc"
2342 #undef FILE_SYSTEM_OPTION_WITH_MARSHALLING
2351 #define FILE_SYSTEM_OPTION_WITH_MARSHALLING(...) \
2352 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
2353 #include "clang/Driver/Options.inc"
2354 #undef FILE_SYSTEM_OPTION_WITH_MARSHALLING
2362 #define MIGRATOR_OPTION_WITH_MARSHALLING(...) \
2363 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
2364 #include "clang/Driver/Options.inc"
2365 #undef MIGRATOR_OPTION_WITH_MARSHALLING
2374 #define MIGRATOR_OPTION_WITH_MARSHALLING(...) \
2375 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
2376 #include "clang/Driver/Options.inc"
2377 #undef MIGRATOR_OPTION_WITH_MARSHALLING
2382 void CompilerInvocationBase::GenerateDiagnosticArgs(
2384 bool DefaultDiagColor) {
2386 #define DIAG_OPTION_WITH_MARSHALLING(...) \
2387 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
2388 #include "clang/Driver/Options.inc"
2389 #undef DIAG_OPTION_WITH_MARSHALLING
2392 GenerateArg(Consumer, OPT_diagnostic_serialized_file,
2395 if (Opts.ShowColors)
2398 if (Opts.VerifyDiagnostics &&
2403 if (Prefix !=
"expected")
2410 GenerateArg(Consumer, OPT_verify_ignore_unexpected);
2413 GenerateArg(Consumer, OPT_verify_ignore_unexpected_EQ,
"note");
2415 GenerateArg(Consumer, OPT_verify_ignore_unexpected_EQ,
"remark");
2417 GenerateArg(Consumer, OPT_verify_ignore_unexpected_EQ,
"warning");
2419 GenerateArg(Consumer, OPT_verify_ignore_unexpected_EQ,
"error");
2422 for (
const auto &Warning : Opts.
Warnings) {
2424 if (Warning ==
"undef-prefix")
2426 Consumer(StringRef(
"-W") + Warning);
2429 for (
const auto &Remark : Opts.
Remarks) {
2432 StringRef IgnoredRemarks[] = {
"pass",
"no-pass",
2433 "pass-analysis",
"no-pass-analysis",
2434 "pass-missed",
"no-pass-missed"};
2435 if (llvm::is_contained(IgnoredRemarks, Remark))
2438 Consumer(StringRef(
"-R") + Remark);
2442 std::unique_ptr<DiagnosticOptions>
2444 auto DiagOpts = std::make_unique<DiagnosticOptions>();
2445 unsigned MissingArgIndex, MissingArgCount;
2447 Argv.slice(1), MissingArgIndex, MissingArgCount);
2450 if (std::optional<std::string> NoColor =
2451 llvm::sys::Process::GetEnv(
"NO_COLOR");
2452 NoColor && !NoColor->empty()) {
2467 bool DefaultDiagColor) {
2468 std::optional<DiagnosticsEngine> IgnoringDiags;
2472 Diags = &*IgnoringDiags;
2481 #define DIAG_OPTION_WITH_MARSHALLING(...) \
2482 PARSE_OPTION_WITH_MARSHALLING(Args, *Diags, __VA_ARGS__)
2483 #include "clang/Driver/Options.inc"
2484 #undef DIAG_OPTION_WITH_MARSHALLING
2486 llvm::sys::Process::UseANSIEscapeCodes(Opts.UseANSIEscapeCodes);
2489 Args.getLastArg(OPT_diagnostic_serialized_file, OPT__serialize_diags))
2493 Opts.VerifyDiagnostics = Args.hasArg(OPT_verify) || Args.hasArg(OPT_verify_EQ);
2495 if (Args.hasArg(OPT_verify))
2500 Opts.VerifyDiagnostics =
false;
2505 "-verify-ignore-unexpected=",
2506 Args.getAllArgValues(OPT_verify_ignore_unexpected_EQ), *Diags, DiagMask);
2507 if (Args.hasArg(OPT_verify_ignore_unexpected))
2509 Opts.setVerifyIgnoreUnexpected(DiagMask);
2511 Diags->
Report(diag::warn_ignoring_ftabstop_value)
2527 std::string &BlockName,
2528 unsigned &MajorVersion,
2529 unsigned &MinorVersion,
2531 std::string &UserInfo) {
2533 Arg.split(Args,
':', 5);
2534 if (Args.size() < 5)
2537 BlockName = std::string(Args[0]);
2538 if (Args[1].getAsInteger(10, MajorVersion))
return true;
2539 if (Args[2].getAsInteger(10, MinorVersion))
return true;
2540 if (Args[3].getAsInteger(2, Hashed))
return true;
2541 if (Args.size() > 4)
2542 UserInfo = std::string(Args[4]);
2551 static const std::pair<frontend::ActionKind, unsigned> Table[] = {
2582 OPT_emit_reduced_module_interface},
2600 OPT_print_dependency_directives_minimized_source},
2607 static std::optional<frontend::ActionKind>
2610 if (ActionOpt.second == Opt.getID())
2611 return ActionOpt.first;
2613 return std::nullopt;
2617 static std::optional<OptSpecifier>
2620 if (ActionOpt.first == ProgramAction)
2621 return OptSpecifier(ActionOpt.second);
2623 return std::nullopt;
2629 #define FRONTEND_OPTION_WITH_MARSHALLING(...) \
2630 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
2631 #include "clang/Driver/Options.inc"
2632 #undef FRONTEND_OPTION_WITH_MARSHALLING
2634 std::optional<OptSpecifier> ProgramActionOpt =
2638 std::function<void()> GenerateProgramAction = [&]() {
2642 if (!ProgramActionOpt) {
2645 "Frontend action without option.");
2646 GenerateProgramAction = [&]() {
2653 GenerateProgramAction = [&]() {
2661 llvm_unreachable(
"Default AST dump format.");
2668 GenerateArg(Consumer, OPT_ast_dump_all_EQ, Format);
2681 GenerateProgramAction = [&]() {
2686 GenerateProgramAction();
2688 for (
const auto &PluginArgs : Opts.
PluginArgs) {
2690 for (
const auto &PluginArg : PluginArgs.second)
2692 Opt.getPrefix() + Opt.getName() + PluginArgs.first,
2693 Opt.getKind(), 0, PluginArg);
2697 if (
auto *TestExt = dyn_cast_or_null<TestModuleFileExtension>(Ext.get()))
2698 GenerateArg(Consumer, OPT_ftest_module_file_extension_EQ, TestExt->str());
2704 for (
const auto &Plugin : Opts.
Plugins)
2710 GenerateArg(Consumer, OPT_fmodule_file, ModuleFile);
2717 GenerateArg(Consumer, OPT_aux_target_feature, Feature);
2723 StringRef HeaderUnit =
"";
2728 HeaderUnit =
"-user";
2731 HeaderUnit =
"-system";
2734 HeaderUnit =
"-header-unit";
2737 StringRef Header = IsHeader ?
"-header" :
"";
2760 Lang =
"objective-c";
2763 Lang =
"objective-c++";
2766 Lang =
"renderscript";
2769 Lang =
"assembler-with-cpp";
2773 "Generating -x argument for unknown language (not precompiled).");
2792 for (
const auto &Input : Opts.
Inputs)
2793 Consumer(Input.getFile());
2802 #define FRONTEND_OPTION_WITH_MARSHALLING(...) \
2803 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
2804 #include "clang/Driver/Options.inc"
2805 #undef FRONTEND_OPTION_WITH_MARSHALLING
2808 if (
const Arg *A = Args.getLastArg(OPT_Action_Group)) {
2809 OptSpecifier Opt = OptSpecifier(A->getOption().getID());
2811 assert(ProgramAction &&
"Option specifier not in Action_Group.");
2814 (Opt == OPT_ast_dump_all_EQ || Opt == OPT_ast_dump_EQ)) {
2815 unsigned Val = llvm::StringSwitch<unsigned>(A->getValue())
2823 Diags.
Report(diag::err_drv_invalid_value)
2824 << A->getAsString(Args) << A->getValue();
2834 Args.hasArg(OPT_interface_stub_version_EQ)
2835 ? Args.getLastArgValue(OPT_interface_stub_version_EQ)
2837 if (ArgStr ==
"experimental-yaml-elf-v1" ||
2838 ArgStr ==
"experimental-ifs-v1" || ArgStr ==
"experimental-ifs-v2" ||
2839 ArgStr ==
"experimental-tapi-elf-v1") {
2840 std::string ErrorMessage =
2841 "Invalid interface stub format: " + ArgStr.str() +
2843 Diags.
Report(diag::err_drv_invalid_value)
2844 <<
"Must specify a valid interface stub format type, ie: "
2845 "-interface-stub-version=ifs-v1"
2848 }
else if (!ArgStr.starts_with(
"ifs-")) {
2849 std::string ErrorMessage =
2850 "Invalid interface stub format: " + ArgStr.str() +
".";
2851 Diags.
Report(diag::err_drv_invalid_value)
2852 <<
"Must specify a valid interface stub format type, ie: "
2853 "-interface-stub-version=ifs-v1"
2868 if (!A->getSpelling().starts_with(
"-ast-dump")) {
2869 const Arg *SavedAction =
nullptr;
2870 for (
const Arg *AA :
2871 Args.filtered(OPT_Action_Group, OPT_main_file_name)) {
2872 if (AA->getOption().matches(OPT_main_file_name)) {
2873 SavedAction =
nullptr;
2874 }
else if (!SavedAction) {
2877 if (!A->getOption().matches(OPT_ast_dump_EQ))
2878 Diags.
Report(diag::err_fe_invalid_multiple_actions)
2879 << SavedAction->getSpelling() << A->getSpelling();
2886 if (
const Arg* A = Args.getLastArg(OPT_plugin)) {
2887 Opts.
Plugins.emplace_back(A->getValue(0));
2891 for (
const auto *AA : Args.filtered(OPT_plugin_arg))
2892 Opts.
PluginArgs[AA->getValue(0)].emplace_back(AA->getValue(1));
2894 for (
const std::string &Arg :
2895 Args.getAllArgValues(OPT_ftest_module_file_extension_EQ)) {
2896 std::string BlockName;
2897 unsigned MajorVersion;
2898 unsigned MinorVersion;
2900 std::string UserInfo;
2902 MinorVersion, Hashed, UserInfo)) {
2903 Diags.
Report(diag::err_test_module_file_extension_format) << Arg;
2910 std::make_shared<TestModuleFileExtension>(
2911 BlockName, MajorVersion, MinorVersion, Hashed, UserInfo));
2914 if (
const Arg *A = Args.getLastArg(OPT_code_completion_at)) {
2918 Diags.
Report(diag::err_drv_invalid_value)
2919 << A->getAsString(Args) << A->getValue();
2922 Opts.
Plugins = Args.getAllArgValues(OPT_load);
2923 Opts.
ASTDumpDecls = Args.hasArg(OPT_ast_dump, OPT_ast_dump_EQ);
2924 Opts.
ASTDumpAll = Args.hasArg(OPT_ast_dump_all, OPT_ast_dump_all_EQ);
2926 for (
const auto *A : Args.filtered(OPT_fmodule_file)) {
2927 StringRef Val = A->getValue();
2928 if (!Val.contains(
'='))
2933 Diags.
Report(diag::err_drv_argument_only_allowed_with) <<
"-fsystem-module"
2935 if (Args.hasArg(OPT_fclangir) || Args.hasArg(OPT_emit_cir))
2938 if (Args.hasArg(OPT_aux_target_cpu))
2939 Opts.
AuxTargetCPU = std::string(Args.getLastArgValue(OPT_aux_target_cpu));
2940 if (Args.hasArg(OPT_aux_target_feature))
2945 Diags.
Report(diag::err_drv_argument_not_allowed_with)
2946 <<
"ARC migration" <<
"ObjC migration";
2950 if (
const Arg *A = Args.getLastArg(OPT_x)) {
2951 StringRef XValue = A->getValue();
2956 bool Preprocessed = XValue.consume_back(
"-cpp-output");
2957 bool ModuleMap = XValue.consume_back(
"-module-map");
2960 XValue !=
"precompiled-header" && XValue.consume_back(
"-header");
2966 if (IsHeader || Preprocessed) {
2967 if (XValue.consume_back(
"-header-unit"))
2969 else if (XValue.consume_back(
"-system"))
2971 else if (XValue.consume_back(
"-user"))
2981 DashX = llvm::StringSwitch<InputKind>(XValue)
2998 DashX = llvm::StringSwitch<InputKind>(XValue)
3006 DashX = llvm::StringSwitch<InputKind>(XValue)
3009 .Cases(
"ast",
"pcm",
"precompiled-header",
3016 Diags.
Report(diag::err_drv_invalid_value)
3017 << A->getAsString(Args) << A->getValue();
3032 std::vector<std::string> Inputs = Args.getAllArgValues(OPT_INPUT);
3035 Inputs.push_back(
"-");
3039 Diags.
Report(diag::err_drv_header_unit_extra_inputs) << Inputs[1];
3041 for (
unsigned i = 0, e = Inputs.size(); i != e; ++i) {
3045 StringRef(Inputs[i]).rsplit(
'.').second);
3054 bool IsSystem =
false;
3063 Opts.
Inputs.emplace_back(std::move(Inputs[i]), IK, IsSystem);
3073 std::string ClangExecutable =
3074 llvm::sys::fs::getMainExecutable(Argv0, MainAddr);
3075 return Driver::GetResourcesPath(ClangExecutable, CLANG_RESOURCE_DIR);
3081 #define HEADER_SEARCH_OPTION_WITH_MARSHALLING(...) \
3082 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
3083 #include "clang/Driver/Options.inc"
3084 #undef HEADER_SEARCH_OPTION_WITH_MARSHALLING
3096 GenerateArg(Consumer, OPT_fprebuilt_module_path, Path);
3099 GenerateArg(Consumer, OPT_fmodules_ignore_macro, Macro.val());
3103 std::optional<bool> IsFramework,
3104 std::optional<bool> IgnoreSysRoot) {
3105 return llvm::is_contained(Groups, Entry.
Group) &&
3106 (!IsFramework || (Entry.
IsFramework == *IsFramework)) &&
3107 (!IgnoreSysRoot || (Entry.
IgnoreSysRoot == *IgnoreSysRoot));
3115 std::nullopt,
true);
3117 OptSpecifier Opt = [It, Matches]() {
3126 llvm_unreachable(
"Unexpected HeaderSearchOptions::Entry.");
3142 It->Group ==
frontend::After ? OPT_iwithprefix : OPT_iwithprefixbefore;
3155 GenerateArg(Consumer, It->IgnoreSysRoot ? OPT_isystem : OPT_iwithsysroot,
3160 GenerateArg(Consumer, OPT_iframeworkwithsysroot, It->Path);
3168 GenerateArg(Consumer, OPT_objc_isystem, It->Path);
3170 GenerateArg(Consumer, OPT_objcxx_isystem, It->Path);
3180 ? OPT_internal_isystem
3181 : OPT_internal_externc_isystem;
3185 assert(It ==
End &&
"Unhandled HeaderSearchOption::Entry.");
3189 OptSpecifier Opt =
P.IsSystemHeader ? OPT_system_header_prefix
3190 : OPT_no_system_header_prefix;
3200 const std::string &WorkingDir) {
3205 #define HEADER_SEARCH_OPTION_WITH_MARSHALLING(...) \
3206 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
3207 #include "clang/Driver/Options.inc"
3208 #undef HEADER_SEARCH_OPTION_WITH_MARSHALLING
3210 if (
const Arg *A = Args.getLastArg(OPT_stdlib_EQ))
3211 Opts.
UseLibcxx = (strcmp(A->getValue(),
"libc++") == 0);
3215 if (!(
P.empty() || llvm::sys::path::is_absolute(
P))) {
3216 if (WorkingDir.empty())
3217 llvm::sys::fs::make_absolute(
P);
3219 llvm::sys::fs::make_absolute(WorkingDir,
P);
3221 llvm::sys::path::remove_dots(
P);
3225 for (
const auto *A : Args.filtered(OPT_fmodule_file)) {
3226 StringRef Val = A->getValue();
3227 if (Val.contains(
'=')) {
3228 auto Split = Val.split(
'=');
3230 std::string(Split.first), std::string(Split.second));
3233 for (
const auto *A : Args.filtered(OPT_fprebuilt_module_path))
3236 for (
const auto *A : Args.filtered(OPT_fmodules_ignore_macro)) {
3237 StringRef MacroDef = A->getValue();
3239 llvm::CachedHashString(MacroDef.split(
'=').first));
3243 bool IsIndexHeaderMap =
false;
3244 bool IsSysrootSpecified =
3245 Args.hasArg(OPT__sysroot_EQ) || Args.hasArg(OPT_isysroot);
3249 auto PrefixHeaderPath = [IsSysrootSpecified,
3250 &Opts](
const llvm::opt::Arg *A,
3251 bool IsFramework =
false) -> std::string {
3252 assert(A->getNumValues() &&
"Unexpected empty search path flag!");
3253 if (IsSysrootSpecified && !IsFramework && A->getValue()[0] ==
'=') {
3255 llvm::sys::path::append(Buffer, Opts.
Sysroot,
3256 llvm::StringRef(A->getValue()).substr(1));
3257 return std::string(Buffer);
3259 return A->getValue();
3262 for (
const auto *A : Args.filtered(OPT_I, OPT_F, OPT_index_header_map)) {
3263 if (A->getOption().matches(OPT_index_header_map)) {
3265 IsIndexHeaderMap =
true;
3272 bool IsFramework = A->getOption().matches(OPT_F);
3273 Opts.
AddPath(PrefixHeaderPath(A, IsFramework),
Group, IsFramework,
3275 IsIndexHeaderMap =
false;
3279 StringRef Prefix =
"";
3280 for (
const auto *A :
3281 Args.filtered(OPT_iprefix, OPT_iwithprefix, OPT_iwithprefixbefore)) {
3282 if (A->getOption().matches(OPT_iprefix))
3283 Prefix = A->getValue();
3284 else if (A->getOption().matches(OPT_iwithprefix))
3290 for (
const auto *A : Args.filtered(OPT_idirafter))
3292 for (
const auto *A : Args.filtered(OPT_iquote))
3295 for (
const auto *A : Args.filtered(OPT_isystem, OPT_iwithsysroot)) {
3296 if (A->getOption().matches(OPT_iwithsysroot)) {
3303 for (
const auto *A : Args.filtered(OPT_iframework))
3305 for (
const auto *A : Args.filtered(OPT_iframeworkwithsysroot))
3310 for (
const auto *A : Args.filtered(OPT_c_isystem))
3312 for (
const auto *A : Args.filtered(OPT_cxx_isystem))
3314 for (
const auto *A : Args.filtered(OPT_objc_isystem))
3316 for (
const auto *A : Args.filtered(OPT_objcxx_isystem))
3320 for (
const auto *A :
3321 Args.filtered(OPT_internal_isystem, OPT_internal_externc_isystem)) {
3323 if (A->getOption().matches(OPT_internal_externc_isystem))
3329 for (
const auto *A :
3330 Args.filtered(OPT_system_header_prefix, OPT_no_system_header_prefix))
3332 A->getValue(), A->getOption().matches(OPT_system_header_prefix));
3334 for (
const auto *A : Args.filtered(OPT_ivfsoverlay, OPT_vfsoverlay))
3343 GenerateArg(Consumer, OPT_fapinotes_swift_version,
3347 GenerateArg(Consumer, OPT_iapinotes_modules, Path);
3352 if (
const Arg *A = Args.getLastArg(OPT_fapinotes_swift_version)) {
3354 diags.
Report(diag::err_drv_invalid_value)
3355 << A->getAsString(Args) << A->getValue();
3357 for (
const Arg *A : Args.filtered(OPT_iapinotes_modules))
3363 if (Opts.PointerAuthIntrinsics)
3365 if (Opts.PointerAuthCalls)
3367 if (Opts.PointerAuthReturns)
3369 if (Opts.PointerAuthAuthTraps)
3371 if (Opts.PointerAuthVTPtrAddressDiscrimination)
3372 GenerateArg(Consumer, OPT_fptrauth_vtable_pointer_address_discrimination);
3373 if (Opts.PointerAuthVTPtrTypeDiscrimination)
3374 GenerateArg(Consumer, OPT_fptrauth_vtable_pointer_type_discrimination);
3375 if (Opts.PointerAuthInitFini)
3381 Opts.PointerAuthIntrinsics = Args.hasArg(OPT_fptrauth_intrinsics);
3382 Opts.PointerAuthCalls = Args.hasArg(OPT_fptrauth_calls);
3383 Opts.PointerAuthReturns = Args.hasArg(OPT_fptrauth_returns);
3384 Opts.PointerAuthAuthTraps = Args.hasArg(OPT_fptrauth_auth_traps);
3385 Opts.PointerAuthVTPtrAddressDiscrimination =
3386 Args.hasArg(OPT_fptrauth_vtable_pointer_address_discrimination);
3387 Opts.PointerAuthVTPtrTypeDiscrimination =
3388 Args.hasArg(OPT_fptrauth_vtable_pointer_type_discrimination);
3389 Opts.PointerAuthInitFini = Args.hasArg(OPT_fptrauth_init_fini);
3399 llvm_unreachable(
"should not parse language flags for this input");
3435 llvm_unreachable(
"unexpected input language");
3444 return "Objective-C";
3448 return "Objective-C++";
3452 return "C++ for OpenCL";
3456 return "RenderScript";
3473 llvm_unreachable(
"unknown input language");
3476 void CompilerInvocationBase::GenerateLangArgs(
const LangOptions &Opts,
3478 const llvm::Triple &
T,
3483 if (Opts.ObjCAutoRefCount)
3485 if (Opts.PICLevel != 0)
3486 GenerateArg(Consumer, OPT_pic_level, Twine(Opts.PICLevel));
3490 GenerateArg(Consumer, OPT_fsanitize_EQ, Sanitizer);
3497 OptSpecifier StdOpt;
3499 case LangStandard::lang_opencl10:
3500 case LangStandard::lang_opencl11:
3501 case LangStandard::lang_opencl12:
3502 case LangStandard::lang_opencl20:
3503 case LangStandard::lang_opencl30:
3504 case LangStandard::lang_openclcpp10:
3505 case LangStandard::lang_openclcpp2021:
3506 StdOpt = OPT_cl_std_EQ;
3509 StdOpt = OPT_std_EQ;
3516 if (Opts.IncludeDefaultHeader)
3517 GenerateArg(Consumer, OPT_finclude_default_header);
3518 if (Opts.DeclareOpenCLBuiltins)
3519 GenerateArg(Consumer, OPT_fdeclare_opencl_builtins);
3523 #define LANG_OPTION_WITH_MARSHALLING(...) \
3524 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
3525 #include "clang/Driver/Options.inc"
3526 #undef LANG_OPTION_WITH_MARSHALLING
3532 GenerateArg(Consumer, OPT_ffp_builtin_accuracy_EQ,
3533 (F.second +
":" + F.first));
3544 else if (Opts.ObjCAutoRefCount == 1)
3547 if (Opts.ObjCWeakRuntime)
3548 GenerateArg(Consumer, OPT_fobjc_runtime_has_weak);
3553 if (Opts.ObjCSubscriptingLegacyRuntime)
3554 GenerateArg(Consumer, OPT_fobjc_subscripting_legacy_runtime);
3557 if (Opts.GNUCVersion != 0) {
3558 unsigned Major = Opts.GNUCVersion / 100 / 100;
3559 unsigned Minor = (Opts.GNUCVersion / 100) % 100;
3560 unsigned Patch = Opts.GNUCVersion % 100;
3562 Twine(Major) +
"." + Twine(Minor) +
"." + Twine(Patch));
3565 if (Opts.IgnoreXCOFFVisibility)
3566 GenerateArg(Consumer, OPT_mignore_xcoff_visibility);
3575 if (Opts.MSCompatibilityVersion != 0) {
3576 unsigned Major = Opts.MSCompatibilityVersion / 10000000;
3577 unsigned Minor = (Opts.MSCompatibilityVersion / 100000) % 100;
3578 unsigned Subminor = Opts.MSCompatibilityVersion % 100000;
3579 GenerateArg(Consumer, OPT_fms_compatibility_version,
3580 Twine(Major) +
"." + Twine(Minor) +
"." + Twine(Subminor));
3583 if ((!Opts.GNUMode && !Opts.MSVCCompat && !Opts.CPlusPlus17 && !Opts.C23) ||
3585 if (!Opts.Trigraphs)
3592 if (Opts.Blocks && !(Opts.OpenCL && Opts.OpenCLVersion == 200))
3595 if (Opts.ConvergentFunctions &&
3596 !(Opts.OpenCL || (Opts.CUDA && Opts.CUDAIsDevice) || Opts.SYCLIsDevice ||
3600 if (Opts.NoBuiltin && !Opts.Freestanding)
3603 if (!Opts.NoBuiltin)
3607 if (Opts.LongDoubleSize == 128)
3609 else if (Opts.LongDoubleSize == 64)
3611 else if (Opts.LongDoubleSize == 80)
3618 if (Opts.OpenMP && !Opts.OpenMPSimd) {
3621 if (Opts.OpenMP != 51)
3622 GenerateArg(Consumer, OPT_fopenmp_version_EQ, Twine(Opts.OpenMP));
3624 if (!Opts.OpenMPUseTLS)
3627 if (Opts.OpenMPIsTargetDevice)
3628 GenerateArg(Consumer, OPT_fopenmp_is_target_device);
3630 if (Opts.OpenMPIRBuilder)
3631 GenerateArg(Consumer, OPT_fopenmp_enable_irbuilder);
3634 if (Opts.OpenMPSimd) {
3637 if (Opts.OpenMP != 51)
3638 GenerateArg(Consumer, OPT_fopenmp_version_EQ, Twine(Opts.OpenMP));
3641 if (Opts.OpenMPThreadSubscription)
3642 GenerateArg(Consumer, OPT_fopenmp_assume_threads_oversubscription);
3644 if (Opts.OpenMPTeamSubscription)
3645 GenerateArg(Consumer, OPT_fopenmp_assume_teams_oversubscription);
3647 if (Opts.OpenMPTargetDebug != 0)
3648 GenerateArg(Consumer, OPT_fopenmp_target_debug_EQ,
3649 Twine(Opts.OpenMPTargetDebug));
3651 if (Opts.OpenMPCUDANumSMs != 0)
3652 GenerateArg(Consumer, OPT_fopenmp_cuda_number_of_sm_EQ,
3653 Twine(Opts.OpenMPCUDANumSMs));
3655 if (Opts.OpenMPCUDABlocksPerSM != 0)
3656 GenerateArg(Consumer, OPT_fopenmp_cuda_blocks_per_sm_EQ,
3657 Twine(Opts.OpenMPCUDABlocksPerSM));
3659 if (Opts.OpenMPCUDAReductionBufNum != 1024)
3660 GenerateArg(Consumer, OPT_fopenmp_cuda_teams_reduction_recs_num_EQ,
3661 Twine(Opts.OpenMPCUDAReductionBufNum));
3664 std::string Targets;
3665 llvm::raw_string_ostream OS(Targets);
3668 [&OS](
const llvm::Triple &
T) { OS << T.str(); },
",");
3669 GenerateArg(Consumer, OPT_fopenmp_targets_EQ, OS.str());
3675 if (Opts.OpenMPCUDAMode)
3695 GenerateArg(Consumer, OPT_ffp_contract,
"fast-honor-pragmas");
3698 GenerateArg(Consumer, OPT_fsanitize_EQ, Sanitizer);
3702 GenerateArg(Consumer, OPT_fsanitize_ignorelist_EQ, F);
3704 switch (Opts.getClangABICompat()) {
3706 GenerateArg(Consumer, OPT_fclang_abi_compat_EQ,
"3.8");
3709 GenerateArg(Consumer, OPT_fclang_abi_compat_EQ,
"4.0");
3712 GenerateArg(Consumer, OPT_fclang_abi_compat_EQ,
"6.0");
3715 GenerateArg(Consumer, OPT_fclang_abi_compat_EQ,
"7.0");
3718 GenerateArg(Consumer, OPT_fclang_abi_compat_EQ,
"9.0");
3721 GenerateArg(Consumer, OPT_fclang_abi_compat_EQ,
"11.0");
3724 GenerateArg(Consumer, OPT_fclang_abi_compat_EQ,
"12.0");
3727 GenerateArg(Consumer, OPT_fclang_abi_compat_EQ,
"14.0");
3730 GenerateArg(Consumer, OPT_fclang_abi_compat_EQ,
"15.0");
3733 GenerateArg(Consumer, OPT_fclang_abi_compat_EQ,
"17.0");
3736 GenerateArg(Consumer, OPT_fclang_abi_compat_EQ,
"18.0");
3742 if (Opts.getSignReturnAddressScope() ==
3744 GenerateArg(Consumer, OPT_msign_return_address_EQ,
"all");
3745 else if (Opts.getSignReturnAddressScope() ==
3747 GenerateArg(Consumer, OPT_msign_return_address_EQ,
"non-leaf");
3749 if (Opts.getSignReturnAddressKey() ==
3751 GenerateArg(Consumer, OPT_msign_return_address_key_EQ,
"b_key");
3757 if (Opts.RelativeCXXABIVTables)
3758 GenerateArg(Consumer, OPT_fexperimental_relative_cxx_abi_vtables);
3760 GenerateArg(Consumer, OPT_fno_experimental_relative_cxx_abi_vtables);
3762 switch (Opts.getDefaultSubGroupSizeType()) {
3764 GenerateArg(Consumer, OPT_fsycl_default_sub_group_size,
"automatic");
3767 GenerateArg(Consumer, OPT_fsycl_default_sub_group_size,
"primary");
3770 GenerateArg(Consumer, OPT_fsycl_default_sub_group_size,
3771 Twine(Opts.DefaultSubGroupSize));
3778 switch (Opts.SYCLVersion) {
3796 GenerateArg(Consumer, OPT_fmacro_prefix_map_EQ, MP.first +
"=" + MP.second);
3801 if (!Opts.GPURelocatableDeviceCode)
3807 if (!llvm::StringSwitch<bool>(ValElement)
3808 .Case(
"default",
true)
3811 .Case(
"medium",
true)
3815 Diags.
Report(diag::err_drv_unsupported_option_argument)
3816 <<
"-ffp-accuracy" << ValElement;
3820 StringRef ValElement, StringRef Opt1,
3821 StringRef Opt2,
const std::string Func) {
3822 Diags.
Report(diag::warn_drv_fp_accuracy_override) << Opt1 << Opt2 <<
Func;
3825 void CompilerInvocation::ParseFpAccuracyArgs(
LangOptions &Opts, ArgList &Args,
3827 for (StringRef Values : Args.getAllArgValues(OPT_ffp_builtin_accuracy_EQ)) {
3828 if (Opts.MathErrno) {
3829 Diags.
Report(diag::err_drv_incompatible_fp_accuracy_options);
3832 Values.split(ValuesArr,
' ');
3833 for (
const auto &Val : ValuesArr) {
3835 Val.split(ValElement,
':');
3837 if (ValElement.size() == 1) {
3845 ValuesArr[0], F.first);
3846 F.second = ValElement[0];
3850 if (ValElement.size() == 2) {
3852 ValElement[1].split(FuncList,
',');
3853 for (StringRef FuncName : FuncList) {
3854 if (FuncName.front() ==
'[')
3855 FuncName = FuncName.drop_front(1);
3856 if (FuncName.back() ==
']')
3857 FuncName = FuncName.drop_back(1);
3861 if (ValElement[0] !=
"default") {
3868 ValuesArr[0], FuncMap->first.c_str());
3869 FuncMap->second = ValElement[0].str();
3872 {FuncName.str(), ValElement[0].str()});
3882 bool CompilerInvocation::ParseLangArgs(
LangOptions &Opts, ArgList &Args,
3884 std::vector<std::string> &Includes,
3894 if (Args.hasArg(OPT_fobjc_arc))
3895 Opts.ObjCAutoRefCount = 1;
3899 Opts.PIE = Args.hasArg(OPT_pic_is_pie);
3905 if (Args.hasArg(OPT_opt_record_file))
3907 std::string(Args.getLastArgValue(OPT_opt_record_file));
3917 if (
const Arg *A = Args.getLastArg(OPT_std_EQ)) {
3920 Diags.
Report(diag::err_drv_invalid_value)
3921 << A->getAsString(Args) << A->getValue();
3923 for (
unsigned KindValue = 0;
3929 auto Diag = Diags.
Report(diag::note_drv_use_standard);
3930 Diag <<
Std.getName() <<
Std.getDescription();
3931 unsigned NumAliases = 0;
3932 #define LANGSTANDARD(id, name, lang, desc, features)
3933 #define LANGSTANDARD_ALIAS(id, alias) \
3934 if (KindValue == LangStandard::lang_##id) ++NumAliases;
3935 #define LANGSTANDARD_ALIAS_DEPR(id, alias)
3936 #include "clang/Basic/LangStandards.def"
3938 #define LANGSTANDARD(id, name, lang, desc, features)
3939 #define LANGSTANDARD_ALIAS(id, alias) \
3940 if (KindValue == LangStandard::lang_##id) Diag << alias;
3941 #define LANGSTANDARD_ALIAS_DEPR(id, alias)
3942 #include "clang/Basic/LangStandards.def"
3950 Diags.
Report(diag::err_drv_argument_not_allowed_with)
3958 if (
const Arg *A = Args.getLastArg(OPT_cl_std_EQ)) {
3960 = llvm::StringSwitch<LangStandard::Kind>(A->getValue())
3961 .Cases(
"cl",
"CL", LangStandard::lang_opencl10)
3962 .Cases(
"cl1.0",
"CL1.0", LangStandard::lang_opencl10)
3963 .Cases(
"cl1.1",
"CL1.1", LangStandard::lang_opencl11)
3964 .Cases(
"cl1.2",
"CL1.2", LangStandard::lang_opencl12)
3965 .Cases(
"cl2.0",
"CL2.0", LangStandard::lang_opencl20)
3966 .Cases(
"cl3.0",
"CL3.0", LangStandard::lang_opencl30)
3967 .Cases(
"clc++",
"CLC++", LangStandard::lang_openclcpp10)
3968 .Cases(
"clc++1.0",
"CLC++1.0", LangStandard::lang_openclcpp10)
3969 .Cases(
"clc++2021",
"CLC++2021", LangStandard::lang_openclcpp2021)
3973 Diags.
Report(diag::err_drv_invalid_value)
3974 << A->getAsString(Args) << A->getValue();
3977 LangStd = OpenCLLangStd;
3982 if (Args.hasArg(OPT_fsycl_is_device) || Args.hasArg(OPT_fsycl_is_host)) {
3983 if (
const Arg *A = Args.getLastArg(OPT_sycl_std_EQ)) {
3984 Opts.setSYCLVersion(
3985 llvm::StringSwitch<LangOptions::SYCLMajorVersion>(A->getValue())
3987 .Cases(
"2017",
"121",
"1.2.1",
"sycl-1.2.1",
3992 Diags.
Report(diag::err_drv_invalid_value)
3993 << A->getAsString(Args) << A->getValue();
4003 if (
const Arg *A = Args.getLastArg(OPT_fsycl_default_sub_group_size)) {
4004 StringRef
Value = A->getValue();
4005 Opts.setDefaultSubGroupSizeType(
4006 llvm::StringSwitch<LangOptions::SubGroupSizeType>(
Value)
4011 if (Opts.getDefaultSubGroupSizeType() ==
4014 if (!
Value.getAsInteger(10, IntResult)) {
4015 Opts.DefaultSubGroupSize = IntResult;
4017 Diags.
Report(diag::err_drv_invalid_value)
4018 << A->getAsString(Args) << A->getValue();
4025 Opts.IncludeDefaultHeader = Args.hasArg(OPT_finclude_default_header);
4026 Opts.DeclareOpenCLBuiltins = Args.hasArg(OPT_fdeclare_opencl_builtins);
4034 #define LANG_OPTION_WITH_MARSHALLING(...) \
4035 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
4036 #include "clang/Driver/Options.inc"
4037 #undef LANG_OPTION_WITH_MARSHALLING
4039 ParseFpAccuracyArgs(Opts, Args, Diags);
4041 if (
const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
4042 StringRef Name = A->getValue();
4043 if (Name ==
"full" || Name ==
"branch") {
4044 Opts.CFProtectionBranch = 1;
4049 if (Arg *
arg = Args.getLastArg(OPT_fobjc_runtime_EQ)) {
4050 StringRef value =
arg->getValue();
4052 Diags.
Report(diag::err_drv_unknown_objc_runtime) << value;
4055 if (Args.hasArg(OPT_fobjc_gc_only))
4057 else if (Args.hasArg(OPT_fobjc_gc))
4059 else if (Args.hasArg(OPT_fobjc_arc)) {
4060 Opts.ObjCAutoRefCount = 1;
4062 Diags.
Report(diag::err_arc_unsupported_on_runtime);
4069 if (Args.hasArg(OPT_fobjc_runtime_has_weak))
4070 Opts.ObjCWeakRuntime = 1;
4076 if (
auto weakArg = Args.getLastArg(OPT_fobjc_weak, OPT_fno_objc_weak)) {
4077 if (!weakArg->getOption().matches(OPT_fobjc_weak)) {
4078 assert(!Opts.ObjCWeak);
4080 Diags.
Report(diag::err_objc_weak_with_gc);
4081 }
else if (!Opts.ObjCWeakRuntime) {
4082 Diags.
Report(diag::err_objc_weak_unsupported);
4086 }
else if (Opts.ObjCAutoRefCount) {
4087 Opts.ObjCWeak = Opts.ObjCWeakRuntime;
4090 if (Args.hasArg(OPT_fobjc_subscripting_legacy_runtime))
4091 Opts.ObjCSubscriptingLegacyRuntime =
4095 if (Arg *A = Args.getLastArg(options::OPT_fgnuc_version_EQ)) {
4098 VersionTuple GNUCVer;
4099 bool Invalid = GNUCVer.tryParse(A->getValue());
4100 unsigned Major = GNUCVer.getMajor();
4101 unsigned Minor = GNUCVer.getMinor().value_or(0);
4102 unsigned Patch = GNUCVer.getSubminor().value_or(0);
4103 if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) {
4104 Diags.
Report(diag::err_drv_invalid_value)
4105 << A->getAsString(Args) << A->getValue();
4107 Opts.GNUCVersion = Major * 100 * 100 + Minor * 100 + Patch;
4110 if (
T.isOSAIX() && (Args.hasArg(OPT_mignore_xcoff_visibility)))
4111 Opts.IgnoreXCOFFVisibility = 1;
4113 if (Args.hasArg(OPT_ftrapv)) {
4117 std::string(Args.getLastArgValue(OPT_ftrapv_handler));
4119 else if (Args.hasArg(OPT_fwrapv))
4122 Opts.MSCompatibilityVersion = 0;
4123 if (
const Arg *A = Args.getLastArg(OPT_fms_compatibility_version)) {
4125 if (VT.tryParse(A->getValue()))
4126 Diags.
Report(diag::err_drv_invalid_value) << A->getAsString(Args)
4128 Opts.MSCompatibilityVersion = VT.getMajor() * 10000000 +
4129 VT.getMinor().value_or(0) * 100000 +
4130 VT.getSubminor().value_or(0);
4138 (!Opts.GNUMode && !Opts.MSVCCompat && !Opts.CPlusPlus17 && !Opts.C23) ||
4141 Args.hasFlag(OPT_ftrigraphs, OPT_fno_trigraphs, Opts.Trigraphs);
4143 Opts.Blocks = Args.hasArg(OPT_fblocks) || (Opts.OpenCL
4144 && Opts.OpenCLVersion == 200);
4146 Opts.ConvergentFunctions = Args.hasArg(OPT_fconvergent_functions) ||
4147 Opts.OpenCL || (Opts.CUDA && Opts.CUDAIsDevice) ||
4148 Opts.SYCLIsDevice || Opts.HLSL;
4150 Opts.NoBuiltin = Args.hasArg(OPT_fno_builtin) || Opts.Freestanding;
4151 if (!Opts.NoBuiltin)
4153 if (Arg *A = Args.getLastArg(options::OPT_LongDouble_Group)) {
4154 if (A->getOption().matches(options::OPT_mlong_double_64))
4155 Opts.LongDoubleSize = 64;
4156 else if (A->getOption().matches(options::OPT_mlong_double_80))
4157 Opts.LongDoubleSize = 80;
4158 else if (A->getOption().matches(options::OPT_mlong_double_128))
4159 Opts.LongDoubleSize = 128;
4161 Opts.LongDoubleSize = 0;
4163 if (Opts.FastRelaxedMath || Opts.CLUnsafeMath)
4169 if (Arg *A = Args.getLastArg(OPT_mrtd)) {
4171 Diags.
Report(diag::err_drv_argument_not_allowed_with)
4172 << A->getSpelling() <<
"-fdefault-calling-conv";
4174 switch (
T.getArch()) {
4175 case llvm::Triple::x86:
4178 case llvm::Triple::m68k:
4182 Diags.
Report(diag::err_drv_argument_not_allowed_with)
4183 << A->getSpelling() <<
T.getTriple();
4188 Opts.OpenCLForceVectorABI = Args.hasArg(OPT_fopencl_force_vector_abi);
4191 Opts.OpenMP = Args.hasArg(OPT_fopenmp) ? 51 : 0;
4193 bool IsSimdSpecified =
4194 Args.hasFlag(options::OPT_fopenmp_simd, options::OPT_fno_openmp_simd,
4196 Opts.OpenMPSimd = !Opts.OpenMP && IsSimdSpecified;
4198 Opts.OpenMP && !Args.hasArg(options::OPT_fnoopenmp_use_tls);
4199 Opts.OpenMPIsTargetDevice =
4200 Opts.OpenMP && Args.hasArg(options::OPT_fopenmp_is_target_device);
4201 Opts.OpenMPIRBuilder =
4202 Opts.OpenMP && Args.hasArg(options::OPT_fopenmp_enable_irbuilder);
4203 bool IsTargetSpecified =
4204 Opts.OpenMPIsTargetDevice || Args.hasArg(options::OPT_fopenmp_targets_EQ);
4206 Opts.ConvergentFunctions =
4207 Opts.ConvergentFunctions || Opts.OpenMPIsTargetDevice;
4209 if (Opts.OpenMP || Opts.OpenMPSimd) {
4211 Args, OPT_fopenmp_version_EQ,
4212 (IsSimdSpecified || IsTargetSpecified) ? 51 : Opts.OpenMP, Diags))
4213 Opts.OpenMP = Version;
4216 if (!Opts.OpenMPIsTargetDevice) {
4217 switch (
T.getArch()) {
4221 case llvm::Triple::nvptx:
4222 case llvm::Triple::nvptx64:
4223 Diags.
Report(diag::err_drv_omp_host_target_not_supported) <<
T.str();
4231 if ((Opts.OpenMPIsTargetDevice && (
T.isNVPTX() ||
T.isAMDGCN())) ||
4232 Opts.OpenCLCPlusPlus) {
4234 Opts.Exceptions = 0;
4235 Opts.CXXExceptions = 0;
4237 if (Opts.OpenMPIsTargetDevice &&
T.isNVPTX()) {
4238 Opts.OpenMPCUDANumSMs =
4240 Opts.OpenMPCUDANumSMs, Diags);
4241 Opts.OpenMPCUDABlocksPerSM =
4243 Opts.OpenMPCUDABlocksPerSM, Diags);
4245 Args, options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ,
4246 Opts.OpenMPCUDAReductionBufNum, Diags);
4251 if (Opts.OpenMPIsTargetDevice && (Args.hasArg(OPT_fopenmp_target_debug) ||
4252 Args.hasArg(OPT_fopenmp_target_debug_EQ))) {
4254 Args, OPT_fopenmp_target_debug_EQ, Opts.OpenMPTargetDebug, Diags);
4255 if (!Opts.OpenMPTargetDebug && Args.hasArg(OPT_fopenmp_target_debug))
4256 Opts.OpenMPTargetDebug = 1;
4259 if (Opts.OpenMPIsTargetDevice) {
4260 if (Args.hasArg(OPT_fopenmp_assume_teams_oversubscription))
4261 Opts.OpenMPTeamSubscription =
true;
4262 if (Args.hasArg(OPT_fopenmp_assume_threads_oversubscription))
4263 Opts.OpenMPThreadSubscription =
true;
4267 if (Arg *A = Args.getLastArg(options::OPT_fopenmp_targets_EQ)) {
4268 enum ArchPtrSize { Arch16Bit, Arch32Bit, Arch64Bit };
4269 auto getArchPtrSize = [](
const llvm::Triple &
T) {
4270 if (
T.isArch16Bit())
4272 if (
T.isArch32Bit())
4274 assert(
T.isArch64Bit() &&
"Expected 64-bit architecture");
4278 for (
unsigned i = 0; i < A->getNumValues(); ++i) {
4279 llvm::Triple TT(A->getValue(i));
4281 if (TT.getArch() == llvm::Triple::UnknownArch ||
4282 !(TT.getArch() == llvm::Triple::aarch64 || TT.isPPC() ||
4283 TT.getArch() == llvm::Triple::systemz ||
4284 TT.getArch() == llvm::Triple::nvptx ||
4285 TT.getArch() == llvm::Triple::nvptx64 ||
4286 TT.getArch() == llvm::Triple::amdgcn ||
4287 TT.getArch() == llvm::Triple::x86 ||
4288 TT.getArch() == llvm::Triple::x86_64))
4289 Diags.
Report(diag::err_drv_invalid_omp_target) << A->getValue(i);
4290 else if (getArchPtrSize(
T) != getArchPtrSize(TT))
4291 Diags.
Report(diag::err_drv_incompatible_omp_arch)
4292 << A->getValue(i) <<
T.str();
4300 if (Arg *A = Args.getLastArg(options::OPT_fopenmp_host_ir_file_path)) {
4303 Diags.
Report(diag::err_drv_omp_host_ir_file_not_found)
4308 Opts.OpenMPCUDAMode = Opts.OpenMPIsTargetDevice &&
4309 (
T.isNVPTX() ||
T.isAMDGCN()) &&
4310 Args.hasArg(options::OPT_fopenmp_cuda_mode);
4313 if (Args.hasArg(options::OPT_fopenacc)) {
4314 Opts.OpenACC =
true;
4316 if (Arg *A = Args.getLastArg(options::OPT_openacc_macro_override))
4323 Opts.Optimize = Opt != 0;
4324 Opts.OptimizeSize = OptSize != 0;
4329 Opts.NoInlineDefine = !Opts.Optimize;
4330 if (Arg *InlineArg = Args.getLastArg(
4331 options::OPT_finline_functions, options::OPT_finline_hint_functions,
4332 options::OPT_fno_inline_functions, options::OPT_fno_inline))
4333 if (InlineArg->getOption().matches(options::OPT_fno_inline))
4334 Opts.NoInlineDefine =
true;
4336 if (Arg *A = Args.getLastArg(OPT_ffp_contract)) {
4337 StringRef Val = A->getValue();
4340 else if (Val ==
"on")
4342 else if (Val ==
"off")
4344 else if (Val ==
"fast-honor-pragmas")
4347 Diags.
Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
4353 Opts.
NoSanitizeFiles = Args.getAllArgValues(OPT_fsanitize_ignorelist_EQ);
4354 std::vector<std::string> systemIgnorelists =
4355 Args.getAllArgValues(OPT_fsanitize_system_ignorelist_EQ);
4357 systemIgnorelists.begin(),
4358 systemIgnorelists.end());
4360 if (Arg *A = Args.getLastArg(OPT_fclang_abi_compat_EQ)) {
4363 StringRef Ver = A->getValue();
4364 std::pair<StringRef, StringRef> VerParts = Ver.split(
'.');
4365 unsigned Major, Minor = 0;
4369 if (!VerParts.first.starts_with(
"0") &&
4370 !VerParts.first.getAsInteger(10, Major) && 3 <= Major &&
4371 Major <= CLANG_VERSION_MAJOR &&
4373 ? VerParts.second.size() == 1 &&
4374 !VerParts.second.getAsInteger(10, Minor)
4375 : VerParts.first.size() == Ver.size() || VerParts.second ==
"0")) {
4377 if (Major == 3 && Minor <= 8)
4379 else if (Major <= 4)
4381 else if (Major <= 6)
4383 else if (Major <= 7)
4385 else if (Major <= 9)
4387 else if (Major <= 11)
4389 else if (Major <= 12)
4391 else if (Major <= 14)
4393 else if (Major <= 15)
4395 else if (Major <= 17)
4397 else if (Major <= 18)
4399 }
else if (Ver !=
"latest") {
4400 Diags.
Report(diag::err_drv_invalid_value)
4401 << A->getAsString(Args) << A->getValue();
4405 if (Arg *A = Args.getLastArg(OPT_msign_return_address_EQ)) {
4406 StringRef SignScope = A->getValue();
4408 if (SignScope.equals_insensitive(
"none"))
4409 Opts.setSignReturnAddressScope(
4411 else if (SignScope.equals_insensitive(
"all"))
4412 Opts.setSignReturnAddressScope(
4414 else if (SignScope.equals_insensitive(
"non-leaf"))
4415 Opts.setSignReturnAddressScope(
4418 Diags.
Report(diag::err_drv_invalid_value)
4419 << A->getAsString(Args) << SignScope;
4421 if (Arg *A = Args.getLastArg(OPT_msign_return_address_key_EQ)) {
4422 StringRef SignKey = A->getValue();
4423 if (!SignScope.empty() && !SignKey.empty()) {
4424 if (SignKey ==
"a_key")
4425 Opts.setSignReturnAddressKey(
4427 else if (SignKey ==
"b_key")
4428 Opts.setSignReturnAddressKey(
4431 Diags.
Report(diag::err_drv_invalid_value)
4432 << A->getAsString(Args) << SignKey;
4438 StringRef
CXXABI = Args.getLastArgValue(OPT_fcxx_abi_EQ);
4445 Diags.
Report(diag::err_unsupported_cxx_abi) <<
CXXABI <<
T.str();
4451 Opts.RelativeCXXABIVTables =
4452 Args.hasFlag(options::OPT_fexperimental_relative_cxx_abi_vtables,
4453 options::OPT_fno_experimental_relative_cxx_abi_vtables,
4457 bool HasRTTI = !Args.hasArg(options::OPT_fno_rtti);
4458 Opts.OmitVTableRTTI =
4459 Args.hasFlag(options::OPT_fexperimental_omit_vtable_rtti,
4460 options::OPT_fno_experimental_omit_vtable_rtti,
false);
4461 if (Opts.OmitVTableRTTI && HasRTTI)
4462 Diags.
Report(diag::err_drv_using_omit_rtti_component_without_no_rtti);
4464 for (
const auto &A : Args.getAllArgValues(OPT_fmacro_prefix_map_EQ)) {
4465 auto Split = StringRef(A).split(
'=');
4467 {std::string(
Split.first), std::string(
Split.second)});
4471 !Args.getLastArg(OPT_fno_file_reproducible) &&
4472 (Args.getLastArg(OPT_ffile_compilation_dir_EQ) ||
4473 Args.getLastArg(OPT_fmacro_prefix_map_EQ) ||
4474 Args.getLastArg(OPT_ffile_reproducible));
4477 if (Arg *A = Args.getLastArg(options::OPT_mvscale_min_EQ)) {
4479 if (StringRef(A->getValue()).getAsInteger(10, VScaleMin) || VScaleMin == 0)
4480 Diags.
Report(diag::err_cc1_unbounded_vscale_min);
4483 if (
const Arg *A = Args.getLastArg(OPT_frandomize_layout_seed_file_EQ)) {
4484 std::ifstream SeedFile(A->getValue(0));
4486 if (!SeedFile.is_open())
4487 Diags.
Report(diag::err_drv_cannot_open_randomize_layout_seed_file)
4493 if (
const Arg *A = Args.getLastArg(OPT_frandomize_layout_seed_EQ))
4500 if (
T.isDXIL() ||
T.isSPIRVLogical()) {
4502 enum { OS, Environment };
4504 int ExpectedOS =
T.isSPIRVLogical() ? VulkanEnv : ShaderModel;
4506 if (
T.getOSName().empty()) {
4507 Diags.
Report(diag::err_drv_hlsl_bad_shader_required_in_target)
4508 << ExpectedOS << OS <<
T.str();
4509 }
else if (
T.getEnvironmentName().empty()) {
4510 Diags.
Report(diag::err_drv_hlsl_bad_shader_required_in_target)
4512 }
else if (!
T.isShaderStageEnvironment()) {
4513 Diags.
Report(diag::err_drv_hlsl_bad_shader_unsupported)
4518 if (!
T.isShaderModelOS() ||
T.getOSVersion() == VersionTuple(0)) {
4519 Diags.
Report(diag::err_drv_hlsl_bad_shader_unsupported)
4520 << ShaderModel <<
T.getOSName() <<
T.str();
4525 if (Args.getLastArg(OPT_fnative_half_type)) {
4528 if (!(Opts.
LangStd >= LangStandard::lang_hlsl2018 &&
4529 T.getOSVersion() >= VersionTuple(6, 2)))
4530 Diags.
Report(diag::err_drv_hlsl_16bit_types_unsupported)
4531 <<
"-enable-16bit-types" <<
true <<
Std.getName()
4532 <<
T.getOSVersion().getAsString();
4534 }
else if (
T.isSPIRVLogical()) {
4535 if (!
T.isVulkanOS() ||
T.getVulkanVersion() == VersionTuple(0)) {
4536 Diags.
Report(diag::err_drv_hlsl_bad_shader_unsupported)
4537 << VulkanEnv <<
T.getOSName() <<
T.str();
4539 if (Args.getLastArg(OPT_fnative_half_type)) {
4542 if (!(Opts.
LangStd >= LangStandard::lang_hlsl2018))
4543 Diags.
Report(diag::err_drv_hlsl_16bit_types_unsupported)
4544 <<
"-fnative-half-type" <<
false <<
Std.getName();
4547 llvm_unreachable(
"expected DXIL or SPIR-V target");
4550 Diags.
Report(diag::err_drv_hlsl_unsupported_target) <<
T.str();
4554 if (Args.hasArg(OPT_fsycl_is_device) || Args.hasArg(OPT_fsycl_is_host))
4555 Opts.GPURelocatableDeviceCode = Args.hasFlag(
4556 options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,
true);
4605 llvm_unreachable(
"invalid frontend action");
4615 #define PREPROCESSOR_OPTION_WITH_MARSHALLING(...) \
4616 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
4617 #include "clang/Driver/Options.inc"
4618 #undef PREPROCESSOR_OPTION_WITH_MARSHALLING
4621 GenerateArg(Consumer, OPT_pch_through_hdrstop_use);
4624 GenerateArg(Consumer, OPT_error_on_deserialized_pch_decl, D);
4631 for (
const auto &M : Opts.
Macros) {
4634 if (M.first ==
"__CET__=1" && !M.second &&
4635 !CodeGenOpts.CFProtectionReturn && CodeGenOpts.CFProtectionBranch)
4637 if (M.first ==
"__CET__=2" && !M.second && CodeGenOpts.CFProtectionReturn &&
4638 !CodeGenOpts.CFProtectionBranch)
4640 if (M.first ==
"__CET__=3" && !M.second && CodeGenOpts.CFProtectionReturn &&
4641 CodeGenOpts.CFProtectionBranch)
4644 GenerateArg(Consumer, M.second ? OPT_U : OPT_D, M.first);
4647 for (
const auto &I : Opts.
Includes) {
4650 if (LangOpts.OpenCL && LangOpts.IncludeDefaultHeader &&
4651 ((LangOpts.DeclareOpenCLBuiltins && I ==
"opencl-c-base.h") ||
4656 if (LangOpts.HLSL && I ==
"hlsl.h")
4666 GenerateArg(Consumer, OPT_remap_file, RF.first +
";" + RF.second);
4672 GenerateArg(Consumer, OPT_fdefine_target_os_macros);
4686 #define PREPROCESSOR_OPTION_WITH_MARSHALLING(...) \
4687 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
4688 #include "clang/Driver/Options.inc"
4689 #undef PREPROCESSOR_OPTION_WITH_MARSHALLING
4691 Opts.
PCHWithHdrStop = Args.hasArg(OPT_pch_through_hdrstop_create) ||
4692 Args.hasArg(OPT_pch_through_hdrstop_use);
4694 for (
const auto *A : Args.filtered(OPT_error_on_deserialized_pch_decl))
4697 if (
const Arg *A = Args.getLastArg(OPT_preamble_bytes_EQ)) {
4698 StringRef
Value(A->getValue());
4699 size_t Comma =
Value.find(
',');
4701 unsigned EndOfLine = 0;
4703 if (Comma == StringRef::npos ||
4704 Value.substr(0, Comma).getAsInteger(10, Bytes) ||
4705 Value.substr(Comma + 1).getAsInteger(10, EndOfLine))
4706 Diags.
Report(diag::err_drv_preamble_format);
4714 if (
const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
4715 StringRef Name = A->getValue();
4716 if (Name ==
"branch")
4718 else if (Name ==
"return")
4720 else if (Name ==
"full")
4725 for (
const auto *A : Args.filtered(OPT_D, OPT_U)) {
4726 if (A->getOption().matches(OPT_D))
4733 for (
const auto *A : Args.filtered(OPT_include))
4734 Opts.
Includes.emplace_back(A->getValue());
4736 for (
const auto *A : Args.filtered(OPT_chain_include))
4739 for (
const auto *A : Args.filtered(OPT_remap_file)) {
4740 std::pair<StringRef, StringRef> Split = StringRef(A->getValue()).split(
';');
4742 if (Split.second.empty()) {
4743 Diags.
Report(diag::err_drv_invalid_remap_file) << A->getAsString(Args);
4750 if (
const Arg *A = Args.getLastArg(OPT_source_date_epoch)) {
4751 StringRef Epoch = A->getValue();
4758 if (Epoch.getAsInteger(10,
V) ||
V > MaxTimestamp) {
4759 Diags.
Report(diag::err_fe_invalid_source_date_epoch)
4760 << Epoch << MaxTimestamp;
4773 Args.hasFlag(OPT_fdefine_target_os_macros,
4785 #define PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING(...) \
4786 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
4787 #include "clang/Driver/Options.inc"
4788 #undef PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING
4806 #define PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING(...) \
4807 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
4808 #include "clang/Driver/Options.inc"
4809 #undef PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING
4812 Opts.
ShowMacros = Args.hasArg(OPT_dM) || Args.hasArg(OPT_dD);
4821 #define TARGET_OPTION_WITH_MARSHALLING(...) \
4822 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
4823 #include "clang/Driver/Options.inc"
4824 #undef TARGET_OPTION_WITH_MARSHALLING
4830 GenerateArg(Consumer, OPT_darwin_target_variant_sdk_version_EQ,
4840 #define TARGET_OPTION_WITH_MARSHALLING(...) \
4841 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
4842 #include "clang/Driver/Options.inc"
4843 #undef TARGET_OPTION_WITH_MARSHALLING
4845 if (Arg *A = Args.getLastArg(options::OPT_target_sdk_version_EQ)) {
4846 llvm::VersionTuple Version;
4847 if (Version.tryParse(A->getValue()))
4848 Diags.
Report(diag::err_drv_invalid_value)
4849 << A->getAsString(Args) << A->getValue();
4854 Args.getLastArg(options::OPT_darwin_target_variant_sdk_version_EQ)) {
4855 llvm::VersionTuple Version;
4856 if (Version.tryParse(A->getValue()))
4857 Diags.
Report(diag::err_drv_invalid_value)
4858 << A->getAsString(Args) << A->getValue();
4867 if (HeaderName.empty())
4871 HeaderName, llvm::sys::fs::CD_OpenAlways, llvm::sys::fs::OF_None);
4873 llvm::sys::fs::closeFile(*FT);
4878 <<
" when opening " << HeaderName <<
"\n";
4882 bool CompilerInvocation::CreateFromArgsImpl(
4890 unsigned MissingArgIndex, MissingArgCount;
4891 InputArgList Args = Opts.ParseArgs(CommandLineArgs, MissingArgIndex,
4892 MissingArgCount, VisibilityMask);
4896 if (MissingArgCount)
4897 Diags.
Report(diag::err_drv_missing_argument)
4898 << Args.getArgString(MissingArgIndex) << MissingArgCount;
4901 for (
const auto *A : Args.filtered(OPT_UNKNOWN)) {
4902 auto ArgString = A->getAsString(Args);
4903 std::string Nearest;
4904 if (Opts.findNearest(ArgString, Nearest, VisibilityMask) > 1)
4905 Diags.
Report(diag::err_drv_unknown_argument) << ArgString;
4907 Diags.
Report(diag::err_drv_unknown_argument_with_suggestion)
4908 << ArgString << Nearest;
4933 if (Warning ==
"misexpect" &&
4965 !
LangOpts.Sanitize.has(SanitizerKind::Address) &&
4966 !
LangOpts.Sanitize.has(SanitizerKind::KernelAddress) &&
4967 !
LangOpts.Sanitize.has(SanitizerKind::Memory) &&
4968 !
LangOpts.Sanitize.has(SanitizerKind::KernelMemory);
4981 Diags.
Report(diag::err_fe_dependency_file_requires_MT);
4987 Diags.
Report(diag::warn_drv_fine_grained_bitfield_accesses_ignored);
5001 Diags, llvm::vfs::getRealFileSystem());
5015 const char *Argv0) {
5021 return CreateFromArgsImpl(Invocation, CommandLineArgs, Diags, Argv0);
5025 Args.push_back(
"-cc1");
5028 Invocation, DummyInvocation, CommandLineArgs, Diags, Argv0);
5033 llvm::HashBuilder<llvm::MD5, llvm::endianness::native> HBuilder;
5046 #define LANGOPT(Name, Bits, Default, Description) HBuilder.add(LangOpts->Name);
5047 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
5048 HBuilder.add(static_cast<unsigned>(LangOpts->get##Name()));
5049 #define BENIGN_LANGOPT(Name, Bits, Default, Description)
5050 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
5051 #include "clang/Basic/LangOptions.def"
5056 HBuilder.addRange(
getLangOpts().CommentOpts.BlockCommandNames);
5073 StringRef MacroDef = Macro.first;
5075 llvm::CachedHashString(MacroDef.split(
'=').first)))
5079 HBuilder.add(Macro);
5095 #define DIAGOPT(Name, Bits, Default) HBuilder.add(diagOpts.Name);
5096 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
5097 HBuilder.add(diagOpts.get##Name());
5098 #include "clang/Basic/DiagnosticOptions.def"
5108 ext->hashExtension(HBuilder);
5115 HBuilder.add(*Minor);
5116 if (
auto Subminor =
APINotesOpts.SwiftVersion.getSubminor())
5117 HBuilder.add(*Subminor);
5119 HBuilder.add(*Build);
5129 #define DEBUGOPT(Name, Bits, Default) HBuilder.add(CodeGenOpts->Name);
5130 #define VALUE_DEBUGOPT(Name, Bits, Default) HBuilder.add(CodeGenOpts->Name);
5131 #define ENUM_DEBUGOPT(Name, Type, Bits, Default) \
5132 HBuilder.add(static_cast<unsigned>(CodeGenOpts->get##Name()));
5133 #define BENIGN_DEBUGOPT(Name, Bits, Default)
5134 #define BENIGN_VALUE_DEBUGOPT(Name, Bits, Default)
5135 #define BENIGN_ENUM_DEBUGOPT(Name, Type, Bits, Default)
5136 #include "clang/Basic/DebugOptions.def"
5143 if (!SanHash.
empty())
5144 HBuilder.add(SanHash.
Mask);
5146 llvm::MD5::MD5Result Result;
5147 HBuilder.getHasher().final(Result);
5148 uint64_t Hash = Result.high() ^ Result.low();
5177 std::vector<std::string> Args{
"-cc1"};
5179 [&Args](
const Twine &Arg) { Args.push_back(Arg.str()); });
5205 llvm::vfs::getRealFileSystem());
5213 Diags, std::move(BaseFS));
5219 if (VFSOverlayFiles.empty())
5224 for (
const auto &
File : VFSOverlayFiles) {
5225 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer =
5226 Result->getBufferForFile(
File);
5228 Diags.
Report(diag::err_missing_vfs_overlay_file) <<
File;
5233 std::move(Buffer.get()),
nullptr,
File,
5236 Diags.
Report(diag::err_invalid_vfs_overlay) <<
File;
Defines the Diagnostic-related interfaces.
Defines enum values for all the target-independent builtin functions.
static void getAllNoBuiltinFuncValues(ArgList &Args, std::vector< std::string > &Funcs)
static T extractMaskValue(T KeyPath)
static std::optional< std::string > normalizeString(OptSpecifier Opt, int TableIndex, const ArgList &Args, DiagnosticsEngine &Diags)
static T mergeMaskValue(T KeyPath, U Value)
static auto makeBooleanOptionNormalizer(bool Value, bool OtherValue, OptSpecifier OtherOpt)
static void parseXRayInstrumentationBundle(StringRef FlagName, StringRef Bundle, ArgList &Args, DiagnosticsEngine &D, XRayInstrSet &S)
static unsigned getOptimizationLevelSize(ArgList &Args)
static void GenerateFrontendArgs(const FrontendOptions &Opts, ArgumentConsumer Consumer, bool IsHeader)
static std::optional< std::vector< std::string > > normalizeStringVector(OptSpecifier Opt, int, const ArgList &Args, DiagnosticsEngine &)
static bool ParseTargetArgs(TargetOptions &Opts, ArgList &Args, DiagnosticsEngine &Diags)
static auto makeFlagToValueNormalizer(T Value)
static void denormalizeStringVector(ArgumentConsumer Consumer, const Twine &Spelling, Option::OptionClass OptClass, unsigned TableIndex, const std::vector< std::string > &Values)
static CodeGenOptions::OptRemark ParseOptimizationRemark(DiagnosticsEngine &Diags, ArgList &Args, OptSpecifier OptEQ, StringRef Name)
Parse a remark command line argument.
static bool ParseFileSystemArgs(FileSystemOptions &Opts, const ArgList &Args, DiagnosticsEngine &Diags)
static constexpr bool is_uint64_t_convertible()
static Expected< std::optional< uint32_t > > parseToleranceOption(StringRef Arg)
static void GeneratePointerAuthArgs(const LangOptions &Opts, ArgumentConsumer Consumer)
static void diagnoseFPAccuracyHasVal(DiagnosticsEngine &Diags, StringRef ValElement, StringRef Opt1, StringRef Opt2, const std::string Func)
static bool parseDiagnosticLevelMask(StringRef FlagName, const std::vector< std::string > &Levels, DiagnosticsEngine &Diags, DiagnosticLevelMask &M)
CompilerInvocation::ArgumentConsumer ArgumentConsumer
static void GenerateArg(ArgumentConsumer Consumer, llvm::opt::OptSpecifier OptSpecifier)
static void addDiagnosticArgs(ArgList &Args, OptSpecifier Group, OptSpecifier GroupWithValue, std::vector< std::string > &Diagnostics)
static bool ParseAnalyzerArgs(AnalyzerOptions &Opts, ArgList &Args, DiagnosticsEngine &Diags)
static void ParsePointerAuthArgs(LangOptions &Opts, ArgList &Args, DiagnosticsEngine &Diags)
static void parseAnalyzerConfigs(AnalyzerOptions &AnOpts, DiagnosticsEngine *Diags)
static void denormalizeSimpleEnum(ArgumentConsumer Consumer, const Twine &Spelling, Option::OptionClass OptClass, unsigned TableIndex, T Value)
static bool ParsePreprocessorArgs(PreprocessorOptions &Opts, ArgList &Args, DiagnosticsEngine &Diags, frontend::ActionKind Action, const FrontendOptions &FrontendOpts)
static StringRef GetInputKindName(InputKind IK)
Get language name for given input kind.
static void initOption(AnalyzerOptions::ConfigTable &Config, DiagnosticsEngine *Diags, StringRef &OptionField, StringRef Name, StringRef DefaultVal)
static void denormalizeString(ArgumentConsumer Consumer, const Twine &Spelling, Option::OptionClass OptClass, unsigned TableIndex, T Value)
llvm::function_ref< bool(CompilerInvocation &, ArrayRef< const char * >, DiagnosticsEngine &, const char *)> ParseFn
llvm::function_ref< void(CompilerInvocation &, SmallVectorImpl< const char * > &, CompilerInvocation::StringAllocator)> GenerateFn
static std::optional< std::string > normalizeTriple(OptSpecifier Opt, int TableIndex, const ArgList &Args, DiagnosticsEngine &Diags)
static void GenerateMigratorArgs(const MigratorOptions &Opts, ArgumentConsumer Consumer)
static void GenerateTargetArgs(const TargetOptions &Opts, ArgumentConsumer Consumer)
static bool checkVerifyPrefixes(const std::vector< std::string > &VerifyPrefixes, DiagnosticsEngine &Diags)
static std::optional< unsigned > normalizeSimpleEnum(OptSpecifier Opt, unsigned TableIndex, const ArgList &Args, DiagnosticsEngine &Diags)
static void denormalizeSimpleFlag(ArgumentConsumer Consumer, const Twine &Spelling, Option::OptionClass, unsigned,...)
The tblgen-erated code passes in a fifth parameter of an arbitrary type, but denormalizeSimpleFlags n...
static SmallVector< StringRef, 4 > serializeSanitizerKinds(SanitizerSet S)
static std::optional< OptSpecifier > getProgramActionOpt(frontend::ActionKind ProgramAction)
Maps frontend action to command line option.
static void GenerateAPINotesArgs(const APINotesOptions &Opts, ArgumentConsumer Consumer)
static void GenerateFileSystemArgs(const FileSystemOptions &Opts, ArgumentConsumer Consumer)
static bool IsInputCompatibleWithStandard(InputKind IK, const LangStandard &S)
Check if input file kind and language standard are compatible.
static void denormalizeStringImpl(ArgumentConsumer Consumer, const Twine &Spelling, Option::OptionClass OptClass, unsigned, const Twine &Value)
static std::optional< IntTy > normalizeStringIntegral(OptSpecifier Opt, int, const ArgList &Args, DiagnosticsEngine &Diags)
static void setPGOUseInstrumentor(CodeGenOptions &Opts, const Twine &ProfileName, llvm::vfs::FileSystem &FS, DiagnosticsEngine &Diags)
static void denormalizeSimpleEnumImpl(ArgumentConsumer Consumer, const Twine &Spelling, Option::OptionClass OptClass, unsigned TableIndex, unsigned Value)
static void GeneratePreprocessorArgs(const PreprocessorOptions &Opts, ArgumentConsumer Consumer, const LangOptions &LangOpts, const FrontendOptions &FrontendOpts, const CodeGenOptions &CodeGenOpts)
static bool ParseHeaderSearchArgs(HeaderSearchOptions &Opts, ArgList &Args, DiagnosticsEngine &Diags, const std::string &WorkingDir)
static bool ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args, DiagnosticsEngine &Diags, bool &IsHeaderFile)
static auto makeBooleanOptionDenormalizer(bool Value)
static const auto & getFrontendActionTable()
Return a table that associates command line option specifiers with the frontend action.
static void GeneratePreprocessorOutputArgs(const PreprocessorOutputOptions &Opts, ArgumentConsumer Consumer, frontend::ActionKind Action)
static bool isStrictlyPreprocessorAction(frontend::ActionKind Action)
static std::string serializeXRayInstrumentationBundle(const XRayInstrSet &S)
static std::optional< frontend::ActionKind > getFrontendAction(OptSpecifier &Opt)
Maps command line option to frontend action.
static bool ParseMigratorArgs(MigratorOptions &Opts, const ArgList &Args, DiagnosticsEngine &Diags)
static std::optional< bool > normalizeSimpleNegativeFlag(OptSpecifier Opt, unsigned, const ArgList &Args, DiagnosticsEngine &)
static void checkFPAccuracyIsValid(StringRef ValElement, DiagnosticsEngine &Diags)
static bool parseShowColorsArgs(const ArgList &Args, bool DefaultColor)
static std::optional< bool > normalizeSimpleFlag(OptSpecifier Opt, unsigned TableIndex, const ArgList &Args, DiagnosticsEngine &Diags)
static T mergeForwardValue(T KeyPath, U Value)
static std::optional< SimpleEnumValue > findValueTableByName(const SimpleEnumValueTable &Table, StringRef Name)
static void ParseAPINotesArgs(APINotesOptions &Opts, ArgList &Args, DiagnosticsEngine &diags)
static bool ParseDependencyOutputArgs(DependencyOutputOptions &Opts, ArgList &Args, DiagnosticsEngine &Diags, frontend::ActionKind Action, bool ShowLineMarkers)
static void GenerateAnalyzerArgs(const AnalyzerOptions &Opts, ArgumentConsumer Consumer)
static void GenerateOptimizationRemark(ArgumentConsumer Consumer, OptSpecifier OptEQ, StringRef Name, const CodeGenOptions::OptRemark &Remark)
Generate a remark argument. This is an inverse of ParseOptimizationRemark.
static bool ParsePreprocessorOutputArgs(PreprocessorOutputOptions &Opts, ArgList &Args, DiagnosticsEngine &Diags, frontend::ActionKind Action)
static bool RoundTrip(ParseFn Parse, GenerateFn Generate, CompilerInvocation &RealInvocation, CompilerInvocation &DummyInvocation, ArrayRef< const char * > CommandLineArgs, DiagnosticsEngine &Diags, const char *Argv0, bool CheckAgainstOriginalInvocation=false, bool ForceRoundTrip=false)
May perform round-trip of command line arguments.
static T extractForwardValue(T KeyPath)
static unsigned getOptimizationLevel(ArgList &Args, InputKind IK, DiagnosticsEngine &Diags)
static void CreateEmptyFile(StringRef HeaderName)
static bool parseTestModuleFileExtensionArg(StringRef Arg, std::string &BlockName, unsigned &MajorVersion, unsigned &MinorVersion, bool &Hashed, std::string &UserInfo)
Parse the argument to the -ftest-module-file-extension command-line argument.
static std::optional< SimpleEnumValue > findValueTableByValue(const SimpleEnumValueTable &Table, unsigned Value)
static void GenerateDependencyOutputArgs(const DependencyOutputOptions &Opts, ArgumentConsumer Consumer)
static StringRef getStringOption(AnalyzerOptions::ConfigTable &Config, StringRef OptionName, StringRef DefaultVal)
static bool FixupInvocation(CompilerInvocation &Invocation, DiagnosticsEngine &Diags, const ArgList &Args, InputKind IK)
static void parseSanitizerKinds(StringRef FlagName, const std::vector< std::string > &Sanitizers, DiagnosticsEngine &Diags, SanitizerSet &S)
static void GenerateHeaderSearchArgs(const HeaderSearchOptions &Opts, ArgumentConsumer Consumer)
Defines the clang::FileSystemOptions interface.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
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.
Defines types useful for describing an Objective-C runtime.
static bool IsHeaderFile(const std::string &Filename)
Defines the clang::SanitizerKind enum.
Defines the clang::SourceLocation class and associated facilities.
#define CXXABI(Name, Str)
Defines the clang::TargetOptions class.
Defines version macros and version-related utility functions for Clang.
Defines the clang::Visibility enumeration and various utility functions.
Defines the clang::XRayInstrKind enum.
__DEVICE__ void * memcpy(void *__a, const void *__b, size_t __c)
__DEVICE__ int max(int __a, int __b)
Tracks various options which control how API notes are found and handled.
llvm::VersionTuple SwiftVersion
The Swift version which should be used for API notes.
std::vector< std::string > ModuleSearchPaths
The set of search paths where we API notes can be found for particular modules.
Stores options for the analyzer from the command line.
static std::vector< StringRef > getRegisteredPackages(bool IncludeExperimental=false)
Retrieves the list of packages generated from Checkers.td.
std::vector< std::pair< std::string, bool > > CheckersAndPackages
Pairs of checker/package name and enable/disable.
std::vector< std::string > SilencedCheckersAndPackages
Vector of checker/package names which will not emit warnings.
AnalysisDiagClients AnalysisDiagOpt
AnalysisConstraints AnalysisConstraintsOpt
ConfigTable Config
A key-value table of use-specified configuration values.
unsigned ShouldEmitErrorsOnInvalidConfigValue
AnalysisPurgeMode AnalysisPurgeOpt
bool isUnknownAnalyzerConfig(llvm::StringRef Name)
static std::vector< StringRef > getRegisteredCheckers(bool IncludeExperimental=false)
Retrieves the list of checkers generated from Checkers.td.
llvm::StringMap< std::string > ConfigTable
std::string FullCompilerInvocation
Store full compiler invocation for reproducible instructions in the generated report.
AnalysisInliningMode InliningMode
The mode of function selection used during inlining.
static bool isBuiltinFunc(llvm::StringRef Name)
Returns true if this is a libc/libm function without the '__builtin_' prefix.
Implements C++ ABI-specific semantic analysis functions.
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
llvm::SmallVector< std::pair< std::string, std::string >, 0 > CoveragePrefixMap
Prefix replacement map for source-based code coverage to remap source file paths in coverage mapping.
llvm::SmallVector< std::pair< std::string, std::string >, 0 > DebugPrefixMap
std::string OptRecordFile
The name of the file to which the backend should save YAML optimization records.
std::string BinutilsVersion
std::vector< BitcodeFileToLink > LinkBitcodeFiles
The files specified here are linked in to the module before optimizations.
std::optional< uint64_t > DiagnosticsHotnessThreshold
The minimum hotness value a diagnostic needs in order to be included in optimization diagnostics.
char CoverageVersion[4]
The version string to put into coverage files.
llvm::DenormalMode FPDenormalMode
The floating-point denormal mode to use.
std::string CoverageNotesFile
The filename with path we use for coverage notes files.
std::string ProfileInstrumentUsePath
Name of the profile file to use as input for -fprofile-instr-use.
std::string SampleProfileFile
Name of the profile file to use with -fprofile-sample-use.
uint64_t LargeDataThreshold
The code model-specific large data threshold to use (-mlarge-data-threshold).
std::string MemoryProfileOutput
Name of the profile file to use as output for with -fmemory-profile.
std::string CodeModel
The code model to use (-mcmodel).
std::string CoverageDataFile
The filename with path we use for coverage data files.
std::optional< uint32_t > DiagnosticsMisExpectTolerance
The maximum percentage profiling weights can deviate from the expected values in order to be included...
std::string StackUsageOutput
Name of the stack usage file (i.e., .su file) if user passes -fstack-usage.
std::string OptRecordPasses
The regex that filters the passes that should be saved to the optimization records.
std::string SaveTempsFilePrefix
Prefix to use for -save-temps output.
XRayInstrSet XRayInstrumentationBundle
Set of XRay instrumentation kinds to emit.
bool hasSanitizeCoverage() const
llvm::DenormalMode FP32DenormalMode
The floating-point denormal mode to use, for float.
SanitizerSet SanitizeTrap
Set of sanitizer checks that trap rather than diagnose.
SanitizerSet SanitizeRecover
Set of sanitizer checks that are non-fatal (i.e.
bool hasReducedDebugInfo() const
Check if type and variable info should be emitted.
OptRemark OptimizationRemark
Selected optimizations for which we should enable optimization remarks.
std::string ThinLTOIndexFile
Name of the function summary index file to use for ThinLTO function importing.
const char * Argv0
Executable and command-line used to create a given CompilerInvocation.
std::vector< std::string > NoBuiltinFuncs
A list of all -fno-builtin-* function names (e.g., memset).
std::vector< uint8_t > CmdArgs
List of backend command-line options for -fembed-bitcode.
OptRemark OptimizationRemarkAnalysis
Selected optimizations for which we should enable optimization analyses.
std::vector< std::string > CommandLineArgs
void resetNonModularOptions(StringRef ModuleFormat)
Reset all of the options that are not considered when building a module.
std::string OptRecordFormat
The format used for serializing remarks (default: YAML)
std::string DIBugsReportFilePath
The file to use for dumping bug report by Debugify for original debug info.
OptRemark OptimizationRemarkMissed
Selected optimizations for which we should enable missed optimization remarks.
The base class of CompilerInvocation.
const MigratorOptions & getMigratorOpts() const
const PreprocessorOptions & getPreprocessorOpts() const
std::shared_ptr< MigratorOptions > MigratorOpts
const AnalyzerOptions & getAnalyzerOpts() const
std::shared_ptr< PreprocessorOutputOptions > PreprocessorOutputOpts
Options controlling preprocessed output.
const PreprocessorOutputOptions & getPreprocessorOutputOpts() const
std::shared_ptr< APINotesOptions > APINotesOpts
Options controlling API notes.
const HeaderSearchOptions & getHeaderSearchOpts() const
std::shared_ptr< TargetOptions > TargetOpts
Options controlling the target.
const DiagnosticOptions & getDiagnosticOpts() const
llvm::function_ref< const char *(const Twine &)> StringAllocator
Command line generation.
std::shared_ptr< PreprocessorOptions > PPOpts
Options controlling the preprocessor (aside from #include handling).
const TargetOptions & getTargetOpts() const
const APINotesOptions & getAPINotesOpts() const
std::vector< std::string > getCC1CommandLine() const
Generate cc1-compatible command line arguments from this instance, wrapping the result as a std::vect...
const DependencyOutputOptions & getDependencyOutputOpts() const
std::shared_ptr< FileSystemOptions > FSOpts
Options controlling file system operations.
const FrontendOptions & getFrontendOpts() const
void generateCC1CommandLine(llvm::SmallVectorImpl< const char * > &Args, StringAllocator SA) const
Generate cc1-compatible command line arguments from this instance.
const CodeGenOptions & getCodeGenOpts() const
CompilerInvocationBase & deep_copy_assign(const CompilerInvocationBase &X)
const LangOptions & getLangOpts() const
Const getters.
AnalyzerOptionsRef AnalyzerOpts
Options controlling the static analyzer.
IntrusiveRefCntPtr< DiagnosticOptions > DiagnosticOpts
Options controlling the diagnostic engine.
const FileSystemOptions & getFileSystemOpts() const
CompilerInvocationBase & shallow_copy_assign(const CompilerInvocationBase &X)
std::shared_ptr< CodeGenOptions > CodeGenOpts
Options controlling IRgen and the backend.
std::shared_ptr< LangOptions > LangOpts
Options controlling the language variant.
std::shared_ptr< HeaderSearchOptions > HSOpts
Options controlling the #include directive.
std::shared_ptr< FrontendOptions > FrontendOpts
Options controlling the frontend itself.
llvm::function_ref< void(const Twine &)> ArgumentConsumer
std::shared_ptr< DependencyOutputOptions > DependencyOutputOpts
Options controlling dependency output.
Helper class for holding the data necessary to invoke the compiler.
void clearImplicitModuleBuildOptions()
Disable implicit modules and canonicalize options that are only used by implicit modules.
PreprocessorOutputOptions & getPreprocessorOutputOpts()
AnalyzerOptions & getAnalyzerOpts()
static std::string GetResourcesPath(const char *Argv0, void *MainAddr)
Get the directory where the compiler headers reside, relative to the compiler binary (found by the pa...
static bool CreateFromArgs(CompilerInvocation &Res, ArrayRef< const char * > CommandLineArgs, DiagnosticsEngine &Diags, const char *Argv0=nullptr)
Create a compiler invocation from a list of input options.
MigratorOptions & getMigratorOpts()
PreprocessorOptions & getPreprocessorOpts()
APINotesOptions & getAPINotesOpts()
CodeGenOptions & getCodeGenOpts()
DiagnosticOptions & getDiagnosticOpts()
static bool checkCC1RoundTrip(ArrayRef< const char * > Args, DiagnosticsEngine &Diags, const char *Argv0=nullptr)
Check that Args can be parsed and re-serialized without change, emiting diagnostics for any differenc...
CompilerInvocation()=default
void resetNonModularOptions()
Reset all of the options that are not considered when building a module.
FileSystemOptions & getFileSystemOpts()
std::string getModuleHash() const
Retrieve a module hash string that is suitable for uniquely identifying the conditions under which th...
TargetOptions & getTargetOpts()
LangOptions & getLangOpts()
Mutable getters.
CompilerInvocation & operator=(const CompilerInvocation &X)
HeaderSearchOptions & getHeaderSearchOpts()
std::shared_ptr< LangOptions > LangOpts
Base class internals.
DependencyOutputOptions & getDependencyOutputOpts()
FrontendOptions & getFrontendOpts()
Same as CompilerInvocation, but with copy-on-write optimization.
FrontendOptions & getMutFrontendOpts()
LangOptions & getMutLangOpts()
Mutable getters.
HeaderSearchOptions & getMutHeaderSearchOpts()
MigratorOptions & getMutMigratorOpts()
PreprocessorOptions & getMutPreprocessorOpts()
APINotesOptions & getMutAPINotesOpts()
PreprocessorOutputOptions & getMutPreprocessorOutputOpts()
CodeGenOptions & getMutCodeGenOpts()
TargetOptions & getMutTargetOpts()
FileSystemOptions & getMutFileSystemOpts()
AnalyzerOptions & getMutAnalyzerOpts()
DiagnosticOptions & getMutDiagnosticOpts()
DependencyOutputOptions & getMutDependencyOutputOpts()
Kind
Lists the kind of concrete classes of Decl.
DependencyOutputOptions - Options for controlling the compiler dependency file generation.
ShowIncludesDestination ShowIncludesDest
Destination of cl.exe style /showIncludes info.
HeaderIncludeFormatKind HeaderIncludeFormat
The format of header information.
std::string OutputFile
The file to write dependency output to.
HeaderIncludeFilteringKind HeaderIncludeFiltering
Determine whether header information should be filtered.
std::vector< std::string > Targets
A list of names to use as the targets in the dependency file; this list must contain at least one ent...
std::vector< std::pair< std::string, ExtraDepKind > > ExtraDeps
A list of extra dependencies (filename and kind) to be used for every target.
unsigned IncludeSystemHeaders
Include system header dependencies.
Used for handling and querying diagnostic IDs.
Options for controlling the compiler diagnostics engine.
std::vector< std::string > Remarks
The list of -R...
std::vector< std::string > Warnings
The list of -W...
std::vector< std::string > VerifyPrefixes
The prefixes for comment directives sought by -verify ("expected" by default).
std::string DiagnosticSerializationFile
The file to serialize diagnostics to (non-appending).
Concrete class used by the front-end to report problems and issues.
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
void setClient(DiagnosticConsumer *client, bool ShouldOwnClient=true)
Set the diagnostic client associated with this diagnostic object.
unsigned getNumErrors() const
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
unsigned getNumWarnings() const
Keeps track of options that affect how file operations are performed.
std::string WorkingDir
If set, paths are resolved as if the working directory was set to the value of WorkingDir.
FrontendOptions - Options for controlling the behavior of the frontend.
InputKind DashX
The input kind, either specified via -x argument or deduced from the input file name.
std::vector< std::string > ModuleFiles
The list of additional prebuilt module files to load before processing the input.
std::map< std::string, std::vector< std::string > > PluginArgs
Args to pass to the plugins.
unsigned IsSystemModule
When using -emit-module, treat the modulemap as a system module.
unsigned UseClangIRPipeline
Use Clang IR pipeline to emit code.
ASTDumpOutputFormat ASTDumpFormat
Specifies the output format of the AST.
std::optional< std::string > AuxTargetCPU
Auxiliary target CPU for CUDA/HIP compilation.
std::string OutputFile
The output file, if any.
unsigned ShowStats
Show frontend performance metrics and statistics.
std::string ActionName
The name of the action to run when using a plugin action.
enum clang::FrontendOptions::@198 ARCMTAction
std::vector< std::shared_ptr< ModuleFileExtension > > ModuleFileExtensions
The list of module file extensions.
ParsedSourceLocation CodeCompletionAt
If given, enable code completion at the provided location.
std::string FixItSuffix
If given, the new suffix for fix-it rewritten files.
static InputKind getInputKindForExtension(StringRef Extension)
getInputKindForExtension - Return the appropriate input kind for a file extension.
std::vector< std::string > Plugins
The list of plugins to load.
unsigned ASTDumpAll
Whether we deserialize all decls when forming AST dumps.
unsigned GenerateGlobalModuleIndex
Whether we can generate the global module index if needed.
unsigned DisableFree
Disable memory freeing on exit.
SmallVector< FrontendInputFile, 0 > Inputs
The input files and their types.
frontend::ActionKind ProgramAction
The frontend action to perform.
std::optional< std::vector< std::string > > AuxTargetFeatures
Auxiliary target features for CUDA/HIP compilation.
std::string AuxTriple
Auxiliary triple for CUDA/HIP compilation.
unsigned UseGlobalModuleIndex
Whether we can use the global module index if available.
unsigned ASTDumpDecls
Whether we include declaration dumps in AST dumps.
A diagnostic client that ignores all diagnostics.
@ None
No signing for any function.
@ NonLeaf
Sign the return address of functions that spill LR.
@ All
Sign the return address of all functions,.
@ BKey
Return address signing uses APIB key.
@ AKey
Return address signing uses APIA key.
@ Ver6
Attempt to be ABI-compatible with code generated by Clang 6.0.x (SVN r321711).
@ Ver18
Attempt to be ABI-compatible with code generated by Clang 18.0.x.
@ Ver4
Attempt to be ABI-compatible with code generated by Clang 4.0.x (SVN r291814).
@ Ver14
Attempt to be ABI-compatible with code generated by Clang 14.0.x.
@ Ver11
Attempt to be ABI-compatible with code generated by Clang 11.0.x (git 2e10b7a39b93).
@ Ver15
Attempt to be ABI-compatible with code generated by Clang 15.0.x.
@ Ver17
Attempt to be ABI-compatible with code generated by Clang 17.0.x.
@ Ver7
Attempt to be ABI-compatible with code generated by Clang 7.0.x (SVN r338536).
@ Latest
Conform to the underlying platform's C and C++ ABIs as closely as we can.
@ Ver3_8
Attempt to be ABI-compatible with code generated by Clang 3.8.x (SVN r257626).
@ Ver12
Attempt to be ABI-compatible with code generated by Clang 12.0.x (git 8e464dd76bef).
@ Ver9
Attempt to be ABI-compatible with code generated by Clang 9.0.x (SVN r351319).
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
void resetNonModularOptions()
Reset all of the options that are not considered when building a module.
std::optional< TargetCXXABI::Kind > CXXABI
C++ ABI to compile with, if specified by the frontend through -fc++-abi=.
std::string FPAccuracyVal
std::vector< std::string > NoBuiltinFuncs
A list of all -fno-builtin-* function names (e.g., memset).
std::string ModuleName
The module currently being compiled as specified by -fmodule-name.
clang::ObjCRuntime ObjCRuntime
std::string getOpenCLVersionString() const
Return the OpenCL C or C++ for OpenCL language name and version as a string.
SanitizerSet Sanitize
Set of enabled sanitizers.
bool UseTargetPathSeparator
Indicates whether to use target's platform-specific file separator when FILE macro is used and when c...
static void setLangDefaults(LangOptions &Opts, Language Lang, 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...
std::string OptRecordFile
The name of the file to which the backend should save YAML optimization records.
std::string OMPHostIRFile
Name of the IR file that contains the result of the OpenMP target host code generation.
std::string OverflowHandler
The name of the handler function to be called when -ftrapv is specified.
std::string RandstructSeed
The seed used by the randomize structure layout feature.
std::map< std::string, std::string, std::greater< std::string > > MacroPrefixMap
A prefix map for FILE, BASE_FILE and __builtin_FILE().
LangStandard::Kind LangStd
The used language standard.
FPAccuracyFuncMapTy FPAccuracyFuncMap
std::string OpenACCMacroOverride
unsigned getOpenCLCompatibleVersion() const
Return the OpenCL version that kernel language is compatible with.
bool SanitizeCoverage
Is at least one coverage instrumentation type enabled.
std::vector< llvm::Triple > OMPTargetTriples
Triples of the OpenMP targets that the host code codegen should take into account in order to generat...
std::vector< std::string > NoSanitizeFiles
Paths to files specifying which objects (files, functions, variables) should not be instrumented.
std::string CurrentModule
The name of the current module, of which the main source file is a part.
std::vector< std::string > ModuleFeatures
The names of any features to enable in module 'requires' decls in addition to the hard-coded list in ...
The basic abstraction for the target Objective-C runtime.
bool allowsWeak() const
Does this runtime allow the use of __weak?
bool tryParse(StringRef input)
Try to parse an Objective-C runtime specification from the given string.
std::string getAsString() const
bool allowsARC() const
Does this runtime allow ARC at all?
@ FragileMacOSX
'macosx-fragile' is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the fragil...
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
std::vector< std::pair< std::string, std::string > > RemappedFiles
The set of file remappings, which take existing files on the system (the first part of each pair) and...
bool PCHWithHdrStopCreate
When true, we are creating a PCH or creating the PCH object while expecting a #pragma hdrstop to sepa...
std::vector< std::string > Includes
std::pair< unsigned, bool > PrecompiledPreambleBytes
If non-zero, the implicit PCH include is actually a precompiled preamble that covers this number of b...
bool LexEditorPlaceholders
When enabled, the preprocessor will construct editor placeholder tokens.
void resetNonModularOptions()
Reset any options that are not considered when building a module.
void addMacroUndef(StringRef Name)
std::set< std::string > DeserializedPCHDeclsToErrorOn
This is a set of names for decls that we do not want to be deserialized, and we emit an error if they...
void addMacroDef(StringRef Name)
bool DefineTargetOSMacros
Indicates whether to predefine target OS macros.
bool DetailedRecord
Whether we should maintain a detailed record of all macro definitions and expansions.
std::vector< std::string > ChainedIncludes
Headers that will be converted to chained PCHs in memory.
bool PCHWithHdrStop
When true, we are creating or using a PCH where a #pragma hdrstop is expected to indicate the beginni...
std::optional< uint64_t > SourceDateEpoch
If set, the UNIX timestamp specified by SOURCE_DATE_EPOCH.
bool UsePredefines
Initialize the preprocessor with the compiler and target specific predefines.
void addRemappedFile(StringRef From, StringRef To)
std::vector< std::pair< std::string, bool > > Macros
PreprocessorOutputOptions - Options for controlling the C preprocessor output (e.g....
unsigned ShowMacros
Print macro definitions.
unsigned ShowCPP
Print normal preprocessed output.
unsigned ShowLineMarkers
Show #line markers.
unsigned DirectivesOnly
Process directives but do not expand macros.
Encodes a location in the source.
static bool isSupportedCXXABI(const llvm::Triple &T, Kind Kind)
static bool usesRelativeVTables(const llvm::Triple &T)
static bool isABI(StringRef Name)
static const auto & getSpelling(Kind ABIKind)
Options for controlling the target.
std::string Triple
The name of the target triple to compile for.
llvm::VersionTuple SDKVersion
The version of the SDK which was used during the compilation.
uint64_t LargeDataThreshold
llvm::VersionTuple DarwinTargetVariantSDKVersion
The version of the darwin target variant SDK which was used during the compilation.
std::string HostTriple
When compiling for the device side, contains the triple used to compile for the host.
Action - Represent an abstract compilation step to perform.
constexpr XRayInstrMask None
constexpr XRayInstrMask All
const llvm::opt::OptTable & getDriverOptTable()
IncludeDirGroup
IncludeDirGroup - Identifies the group an include Entry belongs to, representing its relative positiv...
@ CXXSystem
Like System, but only used for C++.
@ Angled
Paths for '#include <>' added by '-I'.
@ CSystem
Like System, but only used for C.
@ System
Like Angled, but marks system directories.
@ Quoted
'#include ""' paths, added by 'gcc -iquote'.
@ ExternCSystem
Like System, but headers are implicitly wrapped in extern "C".
@ ObjCSystem
Like System, but only used for ObjC.
@ IndexHeaderMap
Like Angled, but marks header maps used when building frameworks.
@ ObjCXXSystem
Like System, but only used for ObjC++.
@ After
Like System, but searched after the system directories.
@ GenerateHeaderUnit
Generate a C++20 header unit module from a header file.
@ VerifyPCH
Load and verify that a PCH file is usable.
@ PrintPreprocessedInput
-E mode.
@ RewriteTest
Rewriter playground.
@ ParseSyntaxOnly
Parse and perform semantic analysis.
@ TemplightDump
Dump template instantiations.
@ GenerateModuleInterface
Generate pre-compiled module from a standard C++ module interface unit.
@ EmitLLVM
Emit a .ll file.
@ PrintPreamble
Print the "preamble" of the input file.
@ MigrateSource
Run migrator.
@ InitOnly
Only execute frontend initialization.
@ ASTView
Parse ASTs and view them in Graphviz.
@ PluginAction
Run a plugin action,.
@ DumpRawTokens
Dump out raw tokens.
@ PrintDependencyDirectivesSourceMinimizerOutput
Print the output of the dependency directives source minimizer.
@ RewriteObjC
ObjC->C Rewriter.
@ RunPreprocessorOnly
Just lex, no output.
@ ModuleFileInfo
Dump information about a module file.
@ EmitCIR
Emit a .cir file.
@ DumpCompilerOptions
Dump the compiler configuration.
@ RunAnalysis
Run one or more source code analyses.
@ ASTPrint
Parse ASTs and print them.
@ GenerateReducedModuleInterface
Generate reduced module interface for a standard C++ module interface unit.
@ GenerateInterfaceStubs
Generate Interface Stub Files.
@ ASTDump
Parse ASTs and dump them.
@ DumpTokens
Dump out preprocessed tokens.
@ FixIt
Parse and apply any fixits to the source.
@ EmitAssembly
Emit a .s file.
@ EmitCodeGenOnly
Generate machine code, but don't emit anything.
@ RewriteMacros
Expand macros but not #includes.
@ EmitHTML
Translate input source into HTML.
@ GeneratePCH
Generate pre-compiled header.
@ EmitLLVMOnly
Generate LLVM IR, but do not emit anything.
@ GenerateModule
Generate pre-compiled module from a module map.
@ ASTDeclList
Parse ASTs and list Decl nodes.
const unsigned VERSION_MINOR
AST file minor version number supported by this version of Clang.
const unsigned VERSION_MAJOR
AST file major version number supported by this version of Clang.
std::unique_ptr< DiagnosticConsumer > create(StringRef OutputFile, DiagnosticOptions *Diags, bool MergeChildRecords=false)
Returns a DiagnosticConsumer that serializes diagnostics to a bitcode file.
std::string toString(const til::SExpr *E)
The JSON file list parser is used to communicate input to InstallAPI.
ASTDumpOutputFormat
Used to specify the format for printing AST dump information.
SanitizerMask getPPTransparentSanitizers()
Return the sanitizers which do not affect preprocessing.
IntrusiveRefCntPtr< llvm::vfs::FileSystem > createVFSFromOverlayFiles(ArrayRef< std::string > VFSOverlayFiles, DiagnosticsEngine &Diags, IntrusiveRefCntPtr< llvm::vfs::FileSystem > BaseFS)
DiagnosticLevelMask
A bitmask representing the diagnostic levels used by VerifyDiagnosticConsumer.
std::unique_ptr< DiagnosticOptions > CreateAndPopulateDiagOpts(ArrayRef< const char * > Argv)
AnalysisConstraints
AnalysisConstraints - Set of available constraint models.
@ HIFIL_Only_Direct_System
void serializeSanitizerSet(SanitizerSet Set, SmallVectorImpl< StringRef > &Values)
Serialize a SanitizerSet into values for -fsanitize= or -fno-sanitize=.
LLVM_READONLY bool isLetter(unsigned char c)
Return true if this character is an ASCII letter: [a-zA-Z].
LLVM_READONLY bool isAlphanumeric(unsigned char c)
Return true if this character is an ASCII letter or digit: [a-zA-Z0-9].
Language
The language for the input, used to select and validate the language standard and possible actions.
@ C
Languages that the frontend can parse and compile.
@ CIR
LLVM IR & CIR: we accept these so that we can run the optimizer on them, and compile them to assembly...
@ Asm
Assembly: we accept this only so that we can preprocess it.
XRayInstrMask parseXRayInstrValue(StringRef Value)
Parses a command line argument into a mask.
IntrusiveRefCntPtr< llvm::vfs::FileSystem > createVFSFromCompilerInvocation(const CompilerInvocation &CI, DiagnosticsEngine &Diags)
void serializeXRayInstrValue(XRayInstrSet Set, SmallVectorImpl< StringRef > &Values)
Serializes a set into a list of command line arguments.
AnalysisPurgeMode
AnalysisPurgeModes - Set of available strategies for dead symbol removal.
ShaderStage
Shader programs run in specific pipeline stages.
SanitizerMask parseSanitizerValue(StringRef Value, bool AllowGroups)
Parse a single value from a -fsanitize= or -fno-sanitize= value list.
const FunctionProtoType * T
AnalysisDiagClients
AnalysisDiagClients - Set of available diagnostic clients for rendering analysis results.
@ NUM_ANALYSIS_DIAG_CLIENTS
std::string getClangFullRepositoryVersion()
Retrieves the full repository version that is an amalgamation of the information in getClangRepositor...
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.
bool ParseDiagnosticArgs(DiagnosticOptions &Opts, llvm::opt::ArgList &Args, DiagnosticsEngine *Diags=nullptr, bool DefaultDiagColor=true)
Fill out Opts based on the options given in Args.
AnalysisInliningMode
AnalysisInlineFunctionSelection - Set of inlining function selection heuristics.
Visibility
Describes the different kinds of visibility that a declaration may have.
Diagnostic wrappers for TextAPI types for error reporting.
__DEVICE__ _Tp arg(const std::complex< _Tp > &__c)
float __ovld __cnfn normalize(float)
Returns a vector in the same direction as p but with a length of 1.
bool Internalize
If true, we use LLVM module internalizer.
bool PropagateAttrs
If true, we set attributes functions in the bitcode library according to our CodeGenOptions,...
std::string Filename
The filename of the bitcode file to link in.
unsigned LinkFlags
Bitwise combination of llvm::Linker::Flags, passed to the LLVM linker.
Dummy tag type whose instance can be passed into the constructor to prevent creation of the reference...
LangStandard - Information about the properties of a particular language standard.
const char * getName() const
getName - Get the name of this standard.
static const LangStandard & getLangStandardForKind(Kind K)
static Kind getLangKind(StringRef Name)
static ParsedSourceLocation FromString(StringRef Str)
Construct a parsed source location from a string; the Filename is empty on error.
std::string ToString() const
Serialize ParsedSourceLocation back to a string.
void clear(SanitizerMask K=SanitizerKind::All)
Disable the sanitizers specified in K.
bool empty() const
Returns true if no sanitizers are enabled.
SanitizerMask Mask
Bitmask of enabled sanitizers.