clang 24.0.0git
CompilerInvocation.cpp
Go to the documentation of this file.
1//===- CompilerInvocation.cpp ---------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
20#include "clang/Basic/LLVM.h"
27#include "clang/Basic/Version.h"
29#include "clang/Config/config.h"
44#include "llvm/ADT/APInt.h"
45#include "llvm/ADT/ArrayRef.h"
46#include "llvm/ADT/CachedHashString.h"
47#include "llvm/ADT/FloatingPointMode.h"
48#include "llvm/ADT/STLExtras.h"
49#include "llvm/ADT/SmallVector.h"
50#include "llvm/ADT/StringRef.h"
51#include "llvm/ADT/StringSwitch.h"
52#include "llvm/ADT/Twine.h"
53#include "llvm/Config/llvm-config.h"
54#include "llvm/Frontend/Debug/Options.h"
55#include "llvm/IR/DebugInfoMetadata.h"
56#include "llvm/Linker/Linker.h"
57#include "llvm/MC/MCTargetOptions.h"
58#include "llvm/Option/Arg.h"
59#include "llvm/Option/ArgList.h"
60#include "llvm/Option/OptSpecifier.h"
61#include "llvm/Option/OptTable.h"
62#include "llvm/Option/Option.h"
63#include "llvm/ProfileData/InstrProfReader.h"
64#include "llvm/Remarks/HotnessThresholdParser.h"
65#include "llvm/Support/CodeGen.h"
66#include "llvm/Support/Compiler.h"
67#include "llvm/Support/Error.h"
68#include "llvm/Support/ErrorHandling.h"
69#include "llvm/Support/ErrorOr.h"
70#include "llvm/Support/FileSystem.h"
71#include "llvm/Support/HashBuilder.h"
72#include "llvm/Support/MathExtras.h"
73#include "llvm/Support/MemoryBuffer.h"
74#include "llvm/Support/Path.h"
75#include "llvm/Support/Process.h"
76#include "llvm/Support/Regex.h"
77#include "llvm/Support/VersionTuple.h"
78#include "llvm/Support/VirtualFileSystem.h"
79#include "llvm/Support/raw_ostream.h"
80#include "llvm/Target/TargetOptions.h"
81#include "llvm/TargetParser/Host.h"
82#include "llvm/TargetParser/Triple.h"
83#include <algorithm>
84#include <cassert>
85#include <cstddef>
86#include <cstring>
87#include <ctime>
88#include <fstream>
89#include <limits>
90#include <memory>
91#include <optional>
92#include <string>
93#include <tuple>
94#include <type_traits>
95#include <utility>
96#include <vector>
97
98using namespace clang;
99using namespace options;
100using namespace llvm::opt;
101
102//===----------------------------------------------------------------------===//
103// Helpers.
104//===----------------------------------------------------------------------===//
105
106// Parse misexpect tolerance argument value.
107// Valid option values are integers in the range [0, 100)
109 uint32_t Val;
110 if (Arg.getAsInteger(10, Val))
111 return llvm::createStringError(llvm::inconvertibleErrorCode(),
112 "Not an integer: %s", Arg.data());
113 return Val;
114}
115
116//===----------------------------------------------------------------------===//
117// Initialization.
118//===----------------------------------------------------------------------===//
119
120template <class T> std::shared_ptr<T> make_shared_copy(const T &X) {
121 return std::make_shared<T>(X);
122}
123
125 : LangOpts(std::make_shared<LangOptions>()),
126 TargetOpts(std::make_shared<TargetOptions>()),
127 DiagnosticOpts(std::make_shared<DiagnosticOptions>()),
128 HSOpts(std::make_shared<HeaderSearchOptions>()),
129 PPOpts(std::make_shared<PreprocessorOptions>()),
130 AnalyzerOpts(std::make_shared<AnalyzerOptions>()),
131 MigratorOpts(std::make_shared<MigratorOptions>()),
132 APINotesOpts(std::make_shared<APINotesOptions>()),
133 CodeGenOpts(std::make_shared<CodeGenOptions>()),
134 FSOpts(std::make_shared<FileSystemOptions>()),
135 FrontendOpts(std::make_shared<FrontendOptions>()),
138 SSAFOpts(std::make_shared<ssaf::SSAFOptions>()) {}
139
142 if (this != &X) {
143 LangOpts = make_shared_copy(X.getLangOpts());
144 TargetOpts = make_shared_copy(X.getTargetOpts());
145 DiagnosticOpts = make_shared_copy(X.getDiagnosticOpts());
146 HSOpts = make_shared_copy(X.getHeaderSearchOpts());
147 PPOpts = make_shared_copy(X.getPreprocessorOpts());
148 AnalyzerOpts = make_shared_copy(X.getAnalyzerOpts());
149 MigratorOpts = make_shared_copy(X.getMigratorOpts());
150 APINotesOpts = make_shared_copy(X.getAPINotesOpts());
151 CodeGenOpts = make_shared_copy(X.getCodeGenOpts());
152 FSOpts = make_shared_copy(X.getFileSystemOpts());
153 FrontendOpts = make_shared_copy(X.getFrontendOpts());
154 DependencyOutputOpts = make_shared_copy(X.getDependencyOutputOpts());
155 PreprocessorOutputOpts = make_shared_copy(X.getPreprocessorOutputOpts());
156 SSAFOpts = make_shared_copy(X.getSSAFOpts());
157 }
158 return *this;
159}
160
163 if (this != &X) {
164 LangOpts = X.LangOpts;
165 TargetOpts = X.TargetOpts;
166 DiagnosticOpts = X.DiagnosticOpts;
167 HSOpts = X.HSOpts;
168 PPOpts = X.PPOpts;
169 AnalyzerOpts = X.AnalyzerOpts;
170 MigratorOpts = X.MigratorOpts;
171 APINotesOpts = X.APINotesOpts;
172 CodeGenOpts = X.CodeGenOpts;
173 FSOpts = X.FSOpts;
174 FrontendOpts = X.FrontendOpts;
175 DependencyOutputOpts = X.DependencyOutputOpts;
176 PreprocessorOutputOpts = X.PreprocessorOutputOpts;
177 SSAFOpts = X.SSAFOpts;
178 }
179 return *this;
180}
181
186
192
193template <typename T>
194T &ensureOwned(std::shared_ptr<T> &Storage) {
195 if (Storage.use_count() > 1)
196 Storage = std::make_shared<T>(*Storage);
197 return *Storage;
198}
199
203
207
211
215
219
223
227
231
235
239
243
247
251
256
257//===----------------------------------------------------------------------===//
258// Normalizers
259//===----------------------------------------------------------------------===//
260
262
263static llvm::StringRef lookupStrInTable(unsigned Offset) {
264 return getDriverOptTable().getStrTable()[Offset];
265}
266
267#define SIMPLE_ENUM_VALUE_TABLE
268#include "clang/Options/Options.inc"
269#undef SIMPLE_ENUM_VALUE_TABLE
270
271static std::optional<bool> normalizeSimpleFlag(OptSpecifier Opt,
272 unsigned TableIndex,
273 const ArgList &Args,
274 DiagnosticsEngine &Diags) {
275 if (Args.hasArg(Opt))
276 return true;
277 return std::nullopt;
278}
279
280static std::optional<bool> normalizeSimpleNegativeFlag(OptSpecifier Opt,
281 unsigned,
282 const ArgList &Args,
284 if (Args.hasArg(Opt))
285 return false;
286 return std::nullopt;
287}
288
289/// The tblgen-erated code passes in a fifth parameter of an arbitrary type, but
290/// denormalizeSimpleFlags never looks at it. Avoid bloating compile-time with
291/// unnecessary template instantiations and just ignore it with a variadic
292/// argument.
294 unsigned SpellingOffset, Option::OptionClass,
295 unsigned, /*T*/...) {
296 Consumer(lookupStrInTable(SpellingOffset));
297}
299 const Twine &Spelling, Option::OptionClass,
300 unsigned, /*T*/...) {
301 Consumer(Spelling);
302}
303
304template <typename T> static constexpr bool is_uint64_t_convertible() {
305 return !std::is_same_v<T, uint64_t> && llvm::is_integral_or_enum<T>::value;
306}
307
308template <typename T,
309 std::enable_if_t<!is_uint64_t_convertible<T>(), bool> = false>
311 return [Value](OptSpecifier Opt, unsigned, const ArgList &Args,
312 DiagnosticsEngine &) -> std::optional<T> {
313 if (Args.hasArg(Opt))
314 return Value;
315 return std::nullopt;
316 };
317}
318
319template <typename T,
320 std::enable_if_t<is_uint64_t_convertible<T>(), bool> = false>
324
325static auto makeBooleanOptionNormalizer(bool Value, bool OtherValue,
326 OptSpecifier OtherOpt) {
327 return [Value, OtherValue,
328 OtherOpt](OptSpecifier Opt, unsigned, const ArgList &Args,
329 DiagnosticsEngine &) -> std::optional<bool> {
330 if (const Arg *A = Args.getLastArg(Opt, OtherOpt)) {
331 return A->getOption().matches(Opt) ? Value : OtherValue;
332 }
333 return std::nullopt;
334 };
335}
336
338 return [Value](ArgumentConsumer Consumer, unsigned SpellingOffset,
339 Option::OptionClass, unsigned, bool KeyPath) {
340 if (KeyPath == Value)
341 Consumer(lookupStrInTable(SpellingOffset));
342 };
343}
344
346 const Twine &Spelling,
347 Option::OptionClass OptClass, unsigned,
348 const Twine &Value) {
349 switch (OptClass) {
350 case Option::SeparateClass:
351 case Option::SeparateOrEqClass:
352 case Option::JoinedOrSeparateClass:
353 case Option::JoinedAndSeparateClass:
354 Consumer(Spelling);
355 Consumer(Value);
356 break;
357 case Option::JoinedClass:
358 case Option::CommaJoinedClass:
359 Consumer(Spelling + Value);
360 break;
361 default:
362 llvm_unreachable("Cannot denormalize an option with option class "
363 "incompatible with string denormalization.");
364 }
365}
366
367template <typename T>
368static void
369denormalizeString(ArgumentConsumer Consumer, unsigned SpellingOffset,
370 Option::OptionClass OptClass, unsigned TableIndex, T Value) {
371 denormalizeStringImpl(Consumer, lookupStrInTable(SpellingOffset), OptClass,
372 TableIndex, Twine(Value));
373}
374
375template <typename T>
376static void denormalizeString(ArgumentConsumer Consumer, const Twine &Spelling,
377 Option::OptionClass OptClass, unsigned TableIndex,
378 T Value) {
379 denormalizeStringImpl(Consumer, Spelling, OptClass, TableIndex, Twine(Value));
380}
381
382static std::optional<SimpleEnumValue>
383findValueTableByName(const SimpleEnumValueTable &Table, StringRef Name) {
384 for (int I = 0, E = Table.Size; I != E; ++I)
385 if (Name == Table.Table[I].Name)
386 return Table.Table[I];
387
388 return std::nullopt;
389}
390
391static std::optional<SimpleEnumValue>
392findValueTableByValue(const SimpleEnumValueTable &Table, unsigned Value) {
393 for (int I = 0, E = Table.Size; I != E; ++I)
394 if (Value == Table.Table[I].Value)
395 return Table.Table[I];
396
397 return std::nullopt;
398}
399
400static std::optional<unsigned> normalizeSimpleEnum(OptSpecifier Opt,
401 unsigned TableIndex,
402 const ArgList &Args,
403 DiagnosticsEngine &Diags) {
404 assert(TableIndex < SimpleEnumValueTablesSize);
405 const SimpleEnumValueTable &Table = SimpleEnumValueTables[TableIndex];
406
407 auto *Arg = Args.getLastArg(Opt);
408 if (!Arg)
409 return std::nullopt;
410
411 StringRef ArgValue = Arg->getValue();
412 if (auto MaybeEnumVal = findValueTableByName(Table, ArgValue))
413 return MaybeEnumVal->Value;
414
415 Diags.Report(diag::err_drv_invalid_value)
416 << Arg->getAsString(Args) << ArgValue;
417 return std::nullopt;
418}
419
421 unsigned SpellingOffset,
422 Option::OptionClass OptClass,
423 unsigned TableIndex, unsigned Value) {
424 assert(TableIndex < SimpleEnumValueTablesSize);
425 const SimpleEnumValueTable &Table = SimpleEnumValueTables[TableIndex];
426 if (auto MaybeEnumVal = findValueTableByValue(Table, Value)) {
427 denormalizeString(Consumer, lookupStrInTable(SpellingOffset), OptClass,
428 TableIndex, MaybeEnumVal->Name);
429 } else {
430 llvm_unreachable("The simple enum value was not correctly defined in "
431 "the tablegen option description");
432 }
433}
434
435template <typename T>
437 unsigned SpellingOffset,
438 Option::OptionClass OptClass,
439 unsigned TableIndex, T Value) {
440 return denormalizeSimpleEnumImpl(Consumer, SpellingOffset, OptClass,
441 TableIndex, static_cast<unsigned>(Value));
442}
443
444static std::optional<std::string> normalizeString(OptSpecifier Opt,
445 int TableIndex,
446 const ArgList &Args,
447 DiagnosticsEngine &Diags) {
448 auto *Arg = Args.getLastArg(Opt);
449 if (!Arg)
450 return std::nullopt;
451 return std::string(Arg->getValue());
452}
453
454template <typename IntTy>
455static std::optional<IntTy> normalizeStringIntegral(OptSpecifier Opt, int,
456 const ArgList &Args,
457 DiagnosticsEngine &Diags) {
458 auto *Arg = Args.getLastArg(Opt);
459 if (!Arg)
460 return std::nullopt;
461 IntTy Res;
462 if (StringRef(Arg->getValue()).getAsInteger(0, Res)) {
463 Diags.Report(diag::err_drv_invalid_int_value)
464 << Arg->getAsString(Args) << Arg->getValue();
465 return std::nullopt;
466 }
467 return Res;
468}
469
470static std::optional<std::vector<std::string>>
471normalizeStringVector(OptSpecifier Opt, int, const ArgList &Args,
473 return Args.getAllArgValues(Opt);
474}
475
477 unsigned SpellingOffset,
478 Option::OptionClass OptClass,
479 unsigned TableIndex,
480 const std::vector<std::string> &Values) {
481 switch (OptClass) {
482 case Option::CommaJoinedClass: {
483 std::string CommaJoinedValue;
484 if (!Values.empty()) {
485 CommaJoinedValue.append(Values.front());
486 for (const std::string &Value : llvm::drop_begin(Values, 1)) {
487 CommaJoinedValue.append(",");
488 CommaJoinedValue.append(Value);
489 }
490 }
491 denormalizeString(Consumer, SpellingOffset,
492 Option::OptionClass::JoinedClass, TableIndex,
493 CommaJoinedValue);
494 break;
495 }
496 case Option::JoinedClass:
497 case Option::SeparateClass:
498 case Option::SeparateOrEqClass:
499 case Option::JoinedOrSeparateClass:
500 for (const std::string &Value : Values)
501 denormalizeString(Consumer, SpellingOffset, OptClass, TableIndex, Value);
502 break;
503 default:
504 llvm_unreachable("Cannot denormalize an option with option class "
505 "incompatible with string vector denormalization.");
506 }
507}
508
509static std::optional<std::string> normalizeTriple(OptSpecifier Opt,
510 int TableIndex,
511 const ArgList &Args,
512 DiagnosticsEngine &Diags) {
513 auto *Arg = Args.getLastArg(Opt);
514 if (!Arg)
515 return std::nullopt;
516 return llvm::Triple::normalize(Arg->getValue());
517}
518
519#define PARSE_OPTION_WITH_MARSHALLING( \
520 ARGS, DIAGS, PREFIX_TYPE, SPELLING_OFFSET, ID, KIND, GROUP, ALIAS, \
521 ALIASARGS, FLAGS, VISIBILITY, PARAM, HELPTEXT, HELPTEXTSFORVARIANTS, \
522 METAVAR, VALUES, SUBCOMMANDIDS_OFFSET, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
523 DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
524 TABLE_INDEX) \
525 if ((VISIBILITY) & options::CC1Option) { \
526 KEYPATH = static_cast<decltype(KEYPATH)>(DEFAULT_VALUE); \
527 if (IMPLIED_CHECK) \
528 KEYPATH = static_cast<decltype(KEYPATH)>(IMPLIED_VALUE); \
529 if (SHOULD_PARSE) \
530 if (auto MaybeValue = NORMALIZER(OPT_##ID, TABLE_INDEX, ARGS, DIAGS)) \
531 KEYPATH = static_cast<decltype(KEYPATH)>(*MaybeValue); \
532 }
533
534#define GENERATE_OPTION_WITH_MARSHALLING( \
535 CONSUMER, PREFIX_TYPE, SPELLING_OFFSET, ID, KIND, GROUP, ALIAS, ALIASARGS, \
536 FLAGS, VISIBILITY, PARAM, HELPTEXT, HELPTEXTSFORVARIANTS, METAVAR, VALUES, \
537 SUBCOMMANDIDS_OFFSET, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \
538 IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, TABLE_INDEX) \
539 if ((VISIBILITY) & options::CC1Option) { \
540 if (ALWAYS_EMIT || (KEYPATH != static_cast<decltype(KEYPATH)>( \
541 ((IMPLIED_CHECK) ? (IMPLIED_VALUE) \
542 : (DEFAULT_VALUE))))) \
543 DENORMALIZER(CONSUMER, SPELLING_OFFSET, Option::KIND##Class, \
544 TABLE_INDEX, KEYPATH); \
545 }
546
547static StringRef GetInputKindName(InputKind IK);
548
549static bool FixupInvocation(CompilerInvocation &Invocation,
550 DiagnosticsEngine &Diags, const ArgList &Args,
551 InputKind IK) {
552 unsigned NumErrorsBefore = Diags.getNumErrors();
553
554 LangOptions &LangOpts = Invocation.getLangOpts();
555 CodeGenOptions &CodeGenOpts = Invocation.getCodeGenOpts();
556 TargetOptions &TargetOpts = Invocation.getTargetOpts();
557 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
558 CodeGenOpts.XRayInstrumentFunctions = LangOpts.XRayInstrument;
559 CodeGenOpts.XRayAlwaysEmitCustomEvents = LangOpts.XRayAlwaysEmitCustomEvents;
560 CodeGenOpts.XRayAlwaysEmitTypedEvents = LangOpts.XRayAlwaysEmitTypedEvents;
561 CodeGenOpts.DisableFree = FrontendOpts.DisableFree;
562 FrontendOpts.GenerateGlobalModuleIndex = FrontendOpts.UseGlobalModuleIndex;
563 if (FrontendOpts.ShowStats)
564 CodeGenOpts.ClearASTBeforeBackend = false;
565 LangOpts.SanitizeCoverage = CodeGenOpts.hasSanitizeCoverage();
566 LangOpts.ForceEmitVTables = CodeGenOpts.ForceEmitVTables;
567 LangOpts.SpeculativeLoadHardening = CodeGenOpts.SpeculativeLoadHardening;
568 LangOpts.CurrentModule = LangOpts.ModuleName;
569
570 llvm::Triple T(TargetOpts.Triple);
571 llvm::Triple::ArchType Arch = T.getArch();
572
573 CodeGenOpts.CodeModel = TargetOpts.CodeModel;
574 CodeGenOpts.LargeDataThreshold = TargetOpts.LargeDataThreshold;
575
576 if (CodeGenOpts.getExceptionHandling() !=
578 T.isWindowsMSVCEnvironment())
579 Diags.Report(diag::err_fe_invalid_exception_model)
580 << static_cast<unsigned>(CodeGenOpts.getExceptionHandling()) << T.str();
581
582 if (T.isWasm() &&
583 (CodeGenOpts.hasSjLjExceptions() || CodeGenOpts.hasSEHExceptions() ||
584 CodeGenOpts.hasDWARFExceptions()))
585 Diags.Report(diag::err_fe_invalid_exception_model)
586 << static_cast<unsigned>(CodeGenOpts.getExceptionHandling()) << T.str();
587
588 if (LangOpts.AppleKext && !LangOpts.CPlusPlus)
589 Diags.Report(diag::warn_c_kext);
590
591 if (LangOpts.NewAlignOverride &&
592 !llvm::isPowerOf2_32(LangOpts.NewAlignOverride)) {
593 Arg *A = Args.getLastArg(OPT_fnew_alignment_EQ);
594 Diags.Report(diag::err_fe_invalid_alignment)
595 << A->getAsString(Args) << A->getValue();
596 LangOpts.NewAlignOverride = 0;
597 }
598
599 // The -f[no-]raw-string-literals option is only valid in C and in C++
600 // standards before C++11.
601 if (LangOpts.CPlusPlus11) {
602 if (Args.hasArg(OPT_fraw_string_literals, OPT_fno_raw_string_literals)) {
603 Args.claimAllArgs(OPT_fraw_string_literals, OPT_fno_raw_string_literals);
604 Diags.Report(diag::warn_drv_fraw_string_literals_in_cxx11)
605 << bool(LangOpts.RawStringLiterals);
606 }
607
608 // Do not allow disabling raw string literals in C++11 or later.
609 LangOpts.RawStringLiterals = true;
610 }
611
612 if (Args.hasArg(OPT_freflection) && !LangOpts.CPlusPlus26) {
613 Diags.Report(diag::err_drv_reflection_requires_cxx26)
614 << Args.getLastArg(options::OPT_freflection)->getAsString(Args);
615 }
616
617 LangOpts.NamedLoops =
618 Args.hasFlag(OPT_fnamed_loops, OPT_fno_named_loops, LangOpts.C2y);
619
620 // Prevent the user from specifying both -fsycl-is-device and -fsycl-is-host.
621 if (LangOpts.SYCLIsDevice && LangOpts.SYCLIsHost)
622 Diags.Report(diag::err_drv_argument_not_allowed_with) << "-fsycl-is-device"
623 << "-fsycl-is-host";
624
625 // SYCL requires C++; reject C inputs on both device and host.
626 if ((LangOpts.SYCLIsDevice || LangOpts.SYCLIsHost) && !LangOpts.CPlusPlus)
627 Diags.Report(diag::err_drv_argument_not_allowed_with)
628 << GetInputKindName(IK) << "-fsycl";
629
630 if (Args.hasArg(OPT_fgnu89_inline) && LangOpts.CPlusPlus)
631 Diags.Report(diag::err_drv_argument_not_allowed_with)
632 << "-fgnu89-inline" << GetInputKindName(IK);
633
634 if (Args.hasArg(OPT_hlsl_entrypoint) && !LangOpts.HLSL)
635 Diags.Report(diag::err_drv_argument_not_allowed_with)
636 << "-hlsl-entry" << GetInputKindName(IK);
637
638 if (Args.hasArg(OPT_fdx_rootsignature_version) && !LangOpts.HLSL)
639 Diags.Report(diag::err_drv_argument_not_allowed_with)
640 << "-fdx-rootsignature-version" << GetInputKindName(IK);
641
642 if (Args.hasArg(OPT_fdx_rootsignature_define) && !LangOpts.HLSL)
643 Diags.Report(diag::err_drv_argument_not_allowed_with)
644 << "-fdx-rootsignature-define" << GetInputKindName(IK);
645
646 if (Args.hasArg(OPT_fdx_semantic_signature_packing_mode_EQ) && !LangOpts.HLSL)
647 Diags.Report(diag::err_drv_argument_not_allowed_with)
648 << "-fdx-semantic-signature-packing-mode" << GetInputKindName(IK);
649
650 if (Args.hasArg(OPT_fgpu_allow_device_init) && !LangOpts.HIP)
651 Diags.Report(diag::warn_ignored_hip_only_option)
652 << Args.getLastArg(OPT_fgpu_allow_device_init)->getAsString(Args);
653
654 if (Args.hasArg(OPT_gpu_max_threads_per_block_EQ) && !LangOpts.HIP)
655 Diags.Report(diag::warn_ignored_hip_only_option)
656 << Args.getLastArg(OPT_gpu_max_threads_per_block_EQ)->getAsString(Args);
657
658 // HLSL invocations should always have -Wconversion, -Wvector-conversion, and
659 // -Wmatrix-conversion by default.
660 if (LangOpts.HLSL) {
661 auto &Warnings = Invocation.getDiagnosticOpts().Warnings;
662 if (!llvm::is_contained(Warnings, "conversion"))
663 Warnings.insert(Warnings.begin(), "conversion");
664 if (!llvm::is_contained(Warnings, "vector-conversion"))
665 Warnings.insert(Warnings.begin(), "vector-conversion");
666 if (!llvm::is_contained(Warnings, "matrix-conversion"))
667 Warnings.insert(Warnings.begin(), "matrix-conversion");
668
669 // HLSL booleans in memory are i32; any non-zero value is true.
670 // Use icmp-ne rather than truncation to avoid InstCombine rewriting
671 // trunc i32 to i1 into an illegal wide <N x i1> bitcast (issue #140824).
672 if (Args.hasArg(OPT_load_bool_from_mem) &&
673 CodeGenOpts.getLoadBoolFromMem() !=
675 Diags.Report(diag::warn_hlsl_bool_from_mem)
676 << Args.getLastArg(OPT_load_bool_from_mem)->getValue();
677 CodeGenOpts.setLoadBoolFromMem(CodeGenOptions::BoolFromMem::NonZero);
678 }
679
680 // When these options are used, the compiler is allowed to apply
681 // optimizations that may affect the final result. For example
682 // (x+y)+z is transformed to x+(y+z) but may not give the same
683 // final result; it's not value safe.
684 // Another example can be to simplify x/x to 1.0 but x could be 0.0, INF
685 // or NaN. Final result may then differ. An error is issued when the eval
686 // method is set with one of these options.
687 if (Args.hasArg(OPT_ffp_eval_method_EQ)) {
688 if (LangOpts.ApproxFunc)
689 Diags.Report(diag::err_incompatible_fp_eval_method_options) << 0;
690 if (LangOpts.AllowFPReassoc)
691 Diags.Report(diag::err_incompatible_fp_eval_method_options) << 1;
692 if (LangOpts.AllowRecip)
693 Diags.Report(diag::err_incompatible_fp_eval_method_options) << 2;
694 }
695
696 // -cl-strict-aliasing needs to emit diagnostic in the case where CL > 1.0.
697 // This option should be deprecated for CL > 1.0 because
698 // this option was added for compatibility with OpenCL 1.0.
699 if (Args.getLastArg(OPT_cl_strict_aliasing) &&
700 (LangOpts.getOpenCLCompatibleVersion() > 100))
701 Diags.Report(diag::warn_option_invalid_ocl_version)
702 << LangOpts.getOpenCLVersionString()
703 << Args.getLastArg(OPT_cl_strict_aliasing)->getAsString(Args);
704
705 if (Arg *A = Args.getLastArg(OPT_fdefault_calling_conv_EQ)) {
706 auto DefaultCC = LangOpts.getDefaultCallingConv();
707
708 bool emitError = (DefaultCC == LangOptions::DCC_FastCall ||
709 DefaultCC == LangOptions::DCC_StdCall) &&
710 Arch != llvm::Triple::x86;
711 emitError |= (DefaultCC == LangOptions::DCC_VectorCall ||
712 DefaultCC == LangOptions::DCC_RegCall) &&
713 !T.isX86();
714 emitError |= DefaultCC == LangOptions::DCC_RtdCall && Arch != llvm::Triple::m68k;
715 if (emitError)
716 Diags.Report(diag::err_drv_argument_not_allowed_with)
717 << A->getSpelling() << T.getTriple();
718 }
719
720 return Diags.getNumErrors() == NumErrorsBefore;
721}
722
723//===----------------------------------------------------------------------===//
724// Deserialization (from args)
725//===----------------------------------------------------------------------===//
726
727static void GenerateArg(ArgumentConsumer Consumer,
728 llvm::opt::OptSpecifier OptSpecifier) {
729 Option Opt = getDriverOptTable().getOption(OptSpecifier);
730 denormalizeSimpleFlag(Consumer, Opt.getPrefixedName(),
731 Option::OptionClass::FlagClass, 0);
732}
733
734static void GenerateArg(ArgumentConsumer Consumer,
735 llvm::opt::OptSpecifier OptSpecifier,
736 const Twine &Value) {
737 Option Opt = getDriverOptTable().getOption(OptSpecifier);
738 denormalizeString(Consumer, Opt.getPrefixedName(), Opt.getKind(), 0, Value);
739}
740
741// Parse command line arguments into CompilerInvocation.
742using ParseFn =
743 llvm::function_ref<bool(CompilerInvocation &, ArrayRef<const char *>,
744 DiagnosticsEngine &, const char *)>;
745
746// Generate command line arguments from CompilerInvocation.
747using GenerateFn = llvm::function_ref<void(
750
751/// May perform round-trip of command line arguments. By default, the round-trip
752/// is enabled in assert builds. This can be overwritten at run-time via the
753/// "-round-trip-args" and "-no-round-trip-args" command line flags, or via the
754/// ForceRoundTrip parameter.
755///
756/// During round-trip, the command line arguments are parsed into a dummy
757/// CompilerInvocation, which is used to generate the command line arguments
758/// again. The real CompilerInvocation is then created by parsing the generated
759/// arguments, not the original ones. This (in combination with tests covering
760/// argument behavior) ensures the generated command line is complete (doesn't
761/// drop/mangle any arguments).
762///
763/// Finally, we check the command line that was used to create the real
764/// CompilerInvocation instance. By default, we compare it to the command line
765/// the real CompilerInvocation generates. This checks whether the generator is
766/// deterministic. If \p CheckAgainstOriginalInvocation is enabled, we instead
767/// compare it to the original command line to verify the original command-line
768/// was canonical and can round-trip exactly.
769static bool RoundTrip(ParseFn Parse, GenerateFn Generate,
770 CompilerInvocation &RealInvocation,
771 CompilerInvocation &DummyInvocation,
772 ArrayRef<const char *> CommandLineArgs,
773 DiagnosticsEngine &Diags, const char *Argv0,
774 bool CheckAgainstOriginalInvocation = false,
775 bool ForceRoundTrip = false) {
776#ifndef NDEBUG
777 bool DoRoundTripDefault = true;
778#else
779 bool DoRoundTripDefault = false;
780#endif
781
782 bool DoRoundTrip = DoRoundTripDefault;
783 if (ForceRoundTrip) {
784 DoRoundTrip = true;
785 } else {
786 for (const auto *Arg : CommandLineArgs) {
787 if (Arg == StringRef("-round-trip-args"))
788 DoRoundTrip = true;
789 if (Arg == StringRef("-no-round-trip-args"))
790 DoRoundTrip = false;
791 }
792 }
793
794 // If round-trip was not requested, simply run the parser with the real
795 // invocation diagnostics.
796 if (!DoRoundTrip)
797 return Parse(RealInvocation, CommandLineArgs, Diags, Argv0);
798
799 // Serializes quoted (and potentially escaped) arguments.
800 auto SerializeArgs = [](ArrayRef<const char *> Args) {
801 std::string Buffer;
802 llvm::raw_string_ostream OS(Buffer);
803 for (const char *Arg : Args) {
804 llvm::sys::printArg(OS, Arg, /*Quote=*/true);
805 OS << ' ';
806 }
807 return Buffer;
808 };
809
810 // Setup a dummy DiagnosticsEngine.
811 DiagnosticOptions DummyDiagOpts;
812 DiagnosticsEngine DummyDiags(DiagnosticIDs::create(), DummyDiagOpts);
813 DummyDiags.setClient(new TextDiagnosticBuffer());
814
815 // Run the first parse on the original arguments with the dummy invocation and
816 // diagnostics.
817 if (!Parse(DummyInvocation, CommandLineArgs, DummyDiags, Argv0) ||
818 DummyDiags.getNumWarnings() != 0) {
819 // If the first parse did not succeed, it must be user mistake (invalid
820 // command line arguments). We won't be able to generate arguments that
821 // would reproduce the same result. Let's fail again with the real
822 // invocation and diagnostics, so all side-effects of parsing are visible.
823 unsigned NumWarningsBefore = Diags.getNumWarnings();
824 auto Success = Parse(RealInvocation, CommandLineArgs, Diags, Argv0);
825 if (!Success || Diags.getNumWarnings() != NumWarningsBefore)
826 return Success;
827
828 // Parse with original options and diagnostics succeeded even though it
829 // shouldn't have. Something is off.
830 Diags.Report(diag::err_cc1_round_trip_fail_then_ok);
831 Diags.Report(diag::note_cc1_round_trip_original)
832 << SerializeArgs(CommandLineArgs);
833 return false;
834 }
835
836 // Setup string allocator.
837 llvm::BumpPtrAllocator Alloc;
838 llvm::StringSaver StringPool(Alloc);
839 auto SA = [&StringPool](const Twine &Arg) {
840 return StringPool.save(Arg).data();
841 };
842
843 // Generate arguments from the dummy invocation. If Generate is the
844 // inverse of Parse, the newly generated arguments must have the same
845 // semantics as the original.
846 SmallVector<const char *> GeneratedArgs;
847 Generate(DummyInvocation, GeneratedArgs, SA);
848
849 // Run the second parse, now on the generated arguments, and with the real
850 // invocation and diagnostics. The result is what we will end up using for the
851 // rest of compilation, so if Generate is not inverse of Parse, something down
852 // the line will break.
853 bool Success2 = Parse(RealInvocation, GeneratedArgs, Diags, Argv0);
854
855 // The first parse on original arguments succeeded, but second parse of
856 // generated arguments failed. Something must be wrong with the generator.
857 if (!Success2) {
858 Diags.Report(diag::err_cc1_round_trip_ok_then_fail);
859 Diags.Report(diag::note_cc1_round_trip_generated)
860 << 1 << SerializeArgs(GeneratedArgs);
861 return false;
862 }
863
864 SmallVector<const char *> ComparisonArgs;
865 if (CheckAgainstOriginalInvocation)
866 // Compare against original arguments.
867 ComparisonArgs.assign(CommandLineArgs.begin(), CommandLineArgs.end());
868 else
869 // Generate arguments again, this time from the options we will end up using
870 // for the rest of the compilation.
871 Generate(RealInvocation, ComparisonArgs, SA);
872
873 // Compares two lists of arguments.
874 auto Equal = [](const ArrayRef<const char *> A,
875 const ArrayRef<const char *> B) {
876 return llvm::equal(A, B, [](const char *AElem, const char *BElem) {
877 return StringRef(AElem) == StringRef(BElem);
878 });
879 };
880
881 // If we generated different arguments from what we assume are two
882 // semantically equivalent CompilerInvocations, the Generate function may
883 // be non-deterministic.
884 if (!Equal(GeneratedArgs, ComparisonArgs)) {
885 Diags.Report(diag::err_cc1_round_trip_mismatch);
886 Diags.Report(diag::note_cc1_round_trip_generated)
887 << 1 << SerializeArgs(GeneratedArgs);
888 Diags.Report(diag::note_cc1_round_trip_generated)
889 << 2 << SerializeArgs(ComparisonArgs);
890 return false;
891 }
892
893 Diags.Report(diag::remark_cc1_round_trip_generated)
894 << 1 << SerializeArgs(GeneratedArgs);
895 Diags.Report(diag::remark_cc1_round_trip_generated)
896 << 2 << SerializeArgs(ComparisonArgs);
897
898 return Success2;
899}
900
902 DiagnosticsEngine &Diags,
903 const char *Argv0) {
904 CompilerInvocation DummyInvocation1, DummyInvocation2;
905 return RoundTrip(
906 [](CompilerInvocation &Invocation, ArrayRef<const char *> CommandLineArgs,
907 DiagnosticsEngine &Diags, const char *Argv0) {
908 return CreateFromArgsImpl(Invocation, CommandLineArgs, Diags, Argv0);
909 },
911 StringAllocator SA) {
912 Args.push_back("-cc1");
913 Invocation.generateCC1CommandLine(Args, SA);
914 },
915 DummyInvocation1, DummyInvocation2, Args, Diags, Argv0,
916 /*CheckAgainstOriginalInvocation=*/true, /*ForceRoundTrip=*/true);
917}
918
919static void addDiagnosticArgs(ArgList &Args, OptSpecifier Group,
920 OptSpecifier GroupWithValue,
921 std::vector<std::string> &Diagnostics) {
922 for (auto *A : Args.filtered(Group)) {
923 if (A->getOption().getKind() == Option::FlagClass) {
924 // The argument is a pure flag (such as OPT_Wall or OPT_Wdeprecated). Add
925 // its name (minus the "W" or "R" at the beginning) to the diagnostics.
926 Diagnostics.push_back(
927 std::string(A->getOption().getName().drop_front(1)));
928 } else if (A->getOption().matches(GroupWithValue)) {
929 // This is -Wfoo= or -Rfoo=, where foo is the name of the diagnostic
930 // group. Add only the group name to the diagnostics.
931 Diagnostics.push_back(
932 std::string(A->getOption().getName().drop_front(1).rtrim("=-")));
933 } else {
934 // Otherwise, add its value (for OPT_W_Joined and similar).
935 Diagnostics.push_back(A->getValue());
936 }
937 }
938}
939
940// Parse the Static Analyzer configuration. If \p Diags is set to nullptr,
941// it won't verify the input.
942static void parseAnalyzerConfigs(AnalyzerOptions &AnOpts,
943 DiagnosticsEngine *Diags);
944
945static void getAllNoBuiltinFuncValues(ArgList &Args,
946 std::vector<std::string> &Funcs) {
947 std::vector<std::string> Values = Args.getAllArgValues(OPT_fno_builtin_);
948 auto BuiltinEnd = llvm::partition(Values, Builtin::Context::isBuiltinFunc);
949 Funcs.insert(Funcs.end(), Values.begin(), BuiltinEnd);
950}
951
952static void GenerateAnalyzerArgs(const AnalyzerOptions &Opts,
953 ArgumentConsumer Consumer) {
954 const AnalyzerOptions *AnalyzerOpts = &Opts;
955
956#define ANALYZER_OPTION_WITH_MARSHALLING(...) \
957 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
958#include "clang/Options/Options.inc"
959#undef ANALYZER_OPTION_WITH_MARSHALLING
960
961 if (Opts.AnalysisConstraintsOpt != RangeConstraintsModel) {
962 switch (Opts.AnalysisConstraintsOpt) {
963#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) \
964 case NAME##Model: \
965 GenerateArg(Consumer, OPT_analyzer_constraints, CMDFLAG); \
966 break;
967#include "clang/StaticAnalyzer/Core/Analyses.def"
968 default:
969 llvm_unreachable("Tried to generate unknown analysis constraint.");
970 }
971 }
972
973 if (Opts.AnalysisDiagOpt != PD_HTML) {
974 switch (Opts.AnalysisDiagOpt) {
975#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN) \
976 case PD_##NAME: \
977 GenerateArg(Consumer, OPT_analyzer_output, CMDFLAG); \
978 break;
979#include "clang/StaticAnalyzer/Core/Analyses.def"
980 default:
981 llvm_unreachable("Tried to generate unknown analysis diagnostic client.");
982 }
983 }
984
985 if (Opts.AnalysisPurgeOpt != PurgeStmt) {
986 switch (Opts.AnalysisPurgeOpt) {
987#define ANALYSIS_PURGE(NAME, CMDFLAG, DESC) \
988 case NAME: \
989 GenerateArg(Consumer, OPT_analyzer_purge, CMDFLAG); \
990 break;
991#include "clang/StaticAnalyzer/Core/Analyses.def"
992 default:
993 llvm_unreachable("Tried to generate unknown analysis purge mode.");
994 }
995 }
996
997 if (Opts.InliningMode != NoRedundancy) {
998 switch (Opts.InliningMode) {
999#define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC) \
1000 case NAME: \
1001 GenerateArg(Consumer, OPT_analyzer_inlining_mode, CMDFLAG); \
1002 break;
1003#include "clang/StaticAnalyzer/Core/Analyses.def"
1004 default:
1005 llvm_unreachable("Tried to generate unknown analysis inlining mode.");
1006 }
1007 }
1008
1009 for (const auto &CP : Opts.CheckersAndPackages) {
1010 OptSpecifier Opt =
1011 CP.second ? OPT_analyzer_checker : OPT_analyzer_disable_checker;
1012 GenerateArg(Consumer, Opt, CP.first);
1013 }
1014
1015 AnalyzerOptions ConfigOpts;
1016 parseAnalyzerConfigs(ConfigOpts, nullptr);
1017
1018 // Sort options by key to avoid relying on StringMap iteration order.
1020 for (const auto &C : Opts.Config)
1021 SortedConfigOpts.emplace_back(C.getKey(), C.getValue());
1022 llvm::sort(SortedConfigOpts, llvm::less_first());
1023
1024 for (const auto &[Key, Value] : SortedConfigOpts) {
1025 // Don't generate anything that came from parseAnalyzerConfigs. It would be
1026 // redundant and may not be valid on the command line.
1027 auto Entry = ConfigOpts.Config.find(Key);
1028 if (Entry != ConfigOpts.Config.end() && Entry->getValue() == Value)
1029 continue;
1030
1031 GenerateArg(Consumer, OPT_analyzer_config, Key + "=" + Value);
1032 }
1033
1034 // Nothing to generate for FullCompilerInvocation.
1035}
1036
1037static void GenerateSSAFArgs(const ssaf::SSAFOptions &Opts,
1038 ArgumentConsumer Consumer) {
1039 const ssaf::SSAFOptions *SSAFOpts = &Opts;
1040
1041#define SSAF_OPTION_WITH_MARSHALLING(...) \
1042 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
1043#include "clang/Options/Options.inc"
1044#undef SSAF_OPTION_WITH_MARSHALLING
1045}
1046
1047static bool ParseSSAFArgs(ssaf::SSAFOptions &Opts, ArgList &Args,
1048 DiagnosticsEngine &Diags) {
1049 unsigned NumErrorsBefore = Diags.getNumErrors();
1050
1051 ssaf::SSAFOptions *SSAFOpts = &Opts;
1052
1053#define SSAF_OPTION_WITH_MARSHALLING(...) \
1054 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
1055#include "clang/Options/Options.inc"
1056#undef SSAF_OPTION_WITH_MARSHALLING
1057
1058 return Diags.getNumErrors() == NumErrorsBefore;
1059}
1060
1061static bool ParseAnalyzerArgs(AnalyzerOptions &Opts, ArgList &Args,
1062 DiagnosticsEngine &Diags) {
1063 unsigned NumErrorsBefore = Diags.getNumErrors();
1064
1065 AnalyzerOptions *AnalyzerOpts = &Opts;
1066
1067#define ANALYZER_OPTION_WITH_MARSHALLING(...) \
1068 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
1069#include "clang/Options/Options.inc"
1070#undef ANALYZER_OPTION_WITH_MARSHALLING
1071
1072 if (Arg *A = Args.getLastArg(OPT_analyzer_constraints)) {
1073 StringRef Name = A->getValue();
1074 AnalysisConstraints Value = llvm::StringSwitch<AnalysisConstraints>(Name)
1075#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) \
1076 .Case(CMDFLAG, NAME##Model)
1077#include "clang/StaticAnalyzer/Core/Analyses.def"
1078 .Default(NumConstraints);
1079 if (Value == NumConstraints) {
1080 Diags.Report(diag::err_drv_invalid_value)
1081 << A->getAsString(Args) << Name;
1082 } else {
1083#ifndef LLVM_WITH_Z3
1084 if (Value == AnalysisConstraints::Z3ConstraintsModel) {
1085 Diags.Report(diag::err_analyzer_not_built_with_z3);
1086 }
1087#endif // LLVM_WITH_Z3
1089 }
1090 }
1091
1092 if (Arg *A = Args.getLastArg(OPT_analyzer_output)) {
1093 StringRef Name = A->getValue();
1094 AnalysisDiagClients Value = llvm::StringSwitch<AnalysisDiagClients>(Name)
1095#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN) \
1096 .Case(CMDFLAG, PD_##NAME)
1097#include "clang/StaticAnalyzer/Core/Analyses.def"
1098 .Default(NUM_ANALYSIS_DIAG_CLIENTS);
1100 Diags.Report(diag::err_drv_invalid_value)
1101 << A->getAsString(Args) << Name;
1102 } else {
1103 Opts.AnalysisDiagOpt = Value;
1104 }
1105 }
1106
1107 if (Arg *A = Args.getLastArg(OPT_analyzer_purge)) {
1108 StringRef Name = A->getValue();
1109 AnalysisPurgeMode Value = llvm::StringSwitch<AnalysisPurgeMode>(Name)
1110#define ANALYSIS_PURGE(NAME, CMDFLAG, DESC) \
1111 .Case(CMDFLAG, NAME)
1112#include "clang/StaticAnalyzer/Core/Analyses.def"
1113 .Default(NumPurgeModes);
1114 if (Value == NumPurgeModes) {
1115 Diags.Report(diag::err_drv_invalid_value)
1116 << A->getAsString(Args) << Name;
1117 } else {
1118 Opts.AnalysisPurgeOpt = Value;
1119 }
1120 }
1121
1122 if (Arg *A = Args.getLastArg(OPT_analyzer_inlining_mode)) {
1123 StringRef Name = A->getValue();
1124 AnalysisInliningMode Value = llvm::StringSwitch<AnalysisInliningMode>(Name)
1125#define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC) \
1126 .Case(CMDFLAG, NAME)
1127#include "clang/StaticAnalyzer/Core/Analyses.def"
1128 .Default(NumInliningModes);
1129 if (Value == NumInliningModes) {
1130 Diags.Report(diag::err_drv_invalid_value)
1131 << A->getAsString(Args) << Name;
1132 } else {
1133 Opts.InliningMode = Value;
1134 }
1135 }
1136
1137 Opts.CheckersAndPackages.clear();
1138 for (const Arg *A :
1139 Args.filtered(OPT_analyzer_checker, OPT_analyzer_disable_checker)) {
1140 A->claim();
1141 bool IsEnabled = A->getOption().getID() == OPT_analyzer_checker;
1142 // We can have a list of comma separated checker names, e.g:
1143 // '-analyzer-checker=cocoa,unix'
1144 StringRef CheckerAndPackageList = A->getValue();
1145 SmallVector<StringRef, 16> CheckersAndPackages;
1146 CheckerAndPackageList.split(CheckersAndPackages, ",");
1147 for (const StringRef &CheckerOrPackage : CheckersAndPackages)
1148 Opts.CheckersAndPackages.emplace_back(std::string(CheckerOrPackage),
1149 IsEnabled);
1150 }
1151
1152 // Go through the analyzer configuration options.
1153 for (const auto *A : Args.filtered(OPT_analyzer_config)) {
1154
1155 // We can have a list of comma separated config names, e.g:
1156 // '-analyzer-config key1=val1,key2=val2'
1157 StringRef configList = A->getValue();
1158 SmallVector<StringRef, 4> configVals;
1159 configList.split(configVals, ",");
1160 for (const auto &configVal : configVals) {
1161 StringRef key, val;
1162 std::tie(key, val) = configVal.split("=");
1163 if (val.empty()) {
1164 Diags.Report(SourceLocation(),
1165 diag::err_analyzer_config_no_value) << configVal;
1166 break;
1167 }
1168 if (val.contains('=')) {
1169 Diags.Report(SourceLocation(),
1170 diag::err_analyzer_config_multiple_values)
1171 << configVal;
1172 break;
1173 }
1174
1175 // TODO: Check checker options too, possibly in CheckerRegistry.
1176 // Leave unknown non-checker configs unclaimed.
1177 if (!key.contains(":") && Opts.isUnknownAnalyzerConfig(key)) {
1179 Diags.Report(diag::err_analyzer_config_unknown) << key;
1180 continue;
1181 }
1182
1183 A->claim();
1184 Opts.Config[key] = std::string(val);
1185 }
1186 }
1187
1189 parseAnalyzerConfigs(Opts, &Diags);
1190 else
1191 parseAnalyzerConfigs(Opts, nullptr);
1192
1193 llvm::raw_string_ostream os(Opts.FullCompilerInvocation);
1194 for (unsigned i = 0; i < Args.getNumInputArgStrings(); ++i) {
1195 if (i != 0)
1196 os << " ";
1197 os << Args.getArgString(i);
1198 }
1199
1200 return Diags.getNumErrors() == NumErrorsBefore;
1201}
1202
1204 StringRef OptionName, StringRef DefaultVal) {
1205 return Config.insert({OptionName, std::string(DefaultVal)}).first->second;
1206}
1207
1209 DiagnosticsEngine *Diags,
1210 StringRef &OptionField, StringRef Name,
1211 StringRef DefaultVal) {
1212 // String options may be known to invalid (e.g. if the expected string is a
1213 // file name, but the file does not exist), those will have to be checked in
1214 // parseConfigs.
1215 OptionField = getStringOption(Config, Name, DefaultVal);
1216}
1217
1219 DiagnosticsEngine *Diags,
1220 bool &OptionField, StringRef Name, bool DefaultVal) {
1221 auto PossiblyInvalidVal =
1222 llvm::StringSwitch<std::optional<bool>>(
1223 getStringOption(Config, Name, (DefaultVal ? "true" : "false")))
1224 .Case("true", true)
1225 .Case("false", false)
1226 .Default(std::nullopt);
1227
1228 if (!PossiblyInvalidVal) {
1229 if (Diags)
1230 Diags->Report(diag::err_analyzer_config_invalid_input)
1231 << Name << "a boolean";
1232 else
1233 OptionField = DefaultVal;
1234 } else
1235 OptionField = *PossiblyInvalidVal;
1236}
1237
1239 DiagnosticsEngine *Diags,
1240 unsigned &OptionField, StringRef Name,
1241 unsigned DefaultVal) {
1242
1243 OptionField = DefaultVal;
1244 bool HasFailed = getStringOption(Config, Name, std::to_string(DefaultVal))
1245 .getAsInteger(0, OptionField);
1246 if (Diags && HasFailed)
1247 Diags->Report(diag::err_analyzer_config_invalid_input)
1248 << Name << "an unsigned";
1249}
1250
1252 DiagnosticsEngine *Diags,
1253 PositiveAnalyzerOption &OptionField, StringRef Name,
1254 unsigned DefaultVal) {
1255 auto Parsed = PositiveAnalyzerOption::create(
1256 getStringOption(Config, Name, std::to_string(DefaultVal)));
1257 if (Parsed.has_value()) {
1258 OptionField = Parsed.value();
1259 return;
1260 }
1261 if (Diags && !Parsed.has_value())
1262 Diags->Report(diag::err_analyzer_config_invalid_input)
1263 << Name << "a positive";
1264
1265 OptionField = DefaultVal;
1266}
1267
1269 DiagnosticsEngine *Diags) {
1270 // TODO: There's no need to store the entire configtable, it'd be plenty
1271 // enough to store checker options.
1272
1273#define ANALYZER_OPTION(TYPE, NAME, CMDFLAG, DESC, DEFAULT_VAL) \
1274 initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, DEFAULT_VAL);
1275#define ANALYZER_OPTION_DEPENDS_ON_USER_MODE(...)
1276#include "clang/StaticAnalyzer/Core/AnalyzerOptions.def"
1277
1278 assert(AnOpts.UserMode == "shallow" || AnOpts.UserMode == "deep");
1279 const bool InShallowMode = AnOpts.UserMode == "shallow";
1280
1281#define ANALYZER_OPTION(...)
1282#define ANALYZER_OPTION_DEPENDS_ON_USER_MODE(TYPE, NAME, CMDFLAG, DESC, \
1283 SHALLOW_VAL, DEEP_VAL) \
1284 initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, \
1285 InShallowMode ? SHALLOW_VAL : DEEP_VAL);
1286#include "clang/StaticAnalyzer/Core/AnalyzerOptions.def"
1287
1288 // At this point, AnalyzerOptions is configured. Let's validate some options.
1289
1290 // FIXME: Here we try to validate the silenced checkers or packages are valid.
1291 // The current approach only validates the registered checkers which does not
1292 // contain the runtime enabled checkers and optimally we would validate both.
1293 if (!AnOpts.RawSilencedCheckersAndPackages.empty()) {
1294 std::vector<StringRef> Checkers =
1295 AnOpts.getRegisteredCheckers(/*IncludeExperimental=*/true);
1296 std::vector<StringRef> Packages =
1297 AnOpts.getRegisteredPackages(/*IncludeExperimental=*/true);
1298
1299 SmallVector<StringRef, 16> CheckersAndPackages;
1300 AnOpts.RawSilencedCheckersAndPackages.split(CheckersAndPackages, ";");
1301
1302 for (const StringRef &CheckerOrPackage : CheckersAndPackages) {
1303 if (Diags) {
1304 bool IsChecker = CheckerOrPackage.contains('.');
1305 bool IsValidName = IsChecker
1306 ? llvm::is_contained(Checkers, CheckerOrPackage)
1307 : llvm::is_contained(Packages, CheckerOrPackage);
1308
1309 if (!IsValidName)
1310 Diags->Report(diag::err_unknown_analyzer_checker_or_package)
1311 << CheckerOrPackage;
1312 }
1313
1314 AnOpts.SilencedCheckersAndPackages.emplace_back(CheckerOrPackage);
1315 }
1316 }
1317
1318 if (!Diags)
1319 return;
1320
1321 if (AnOpts.ShouldTrackConditionsDebug && !AnOpts.ShouldTrackConditions)
1322 Diags->Report(diag::err_analyzer_config_invalid_input)
1323 << "track-conditions-debug" << "'track-conditions' to also be enabled";
1324}
1325
1326/// Generate a remark argument. This is an inverse of `ParseOptimizationRemark`.
1327static void
1329 StringRef Name,
1331 if (Remark.hasValidPattern()) {
1332 GenerateArg(Consumer, OptEQ, Remark.Pattern);
1333 } else if (Remark.Kind == CodeGenOptions::RK_Enabled) {
1334 GenerateArg(Consumer, OPT_R_Joined, Name);
1335 } else if (Remark.Kind == CodeGenOptions::RK_Disabled) {
1336 GenerateArg(Consumer, OPT_R_Joined, StringRef("no-") + Name);
1337 }
1338}
1339
1340/// Parse a remark command line argument. It may be missing, disabled/enabled by
1341/// '-R[no-]group' or specified with a regular expression by '-Rgroup=regexp'.
1342/// On top of that, it can be disabled/enabled globally by '-R[no-]everything'.
1345 OptSpecifier OptEQ, StringRef Name) {
1347
1348 auto InitializeResultPattern = [&Diags, &Args, &Result](const Arg *A,
1349 StringRef Pattern) {
1350 Result.Pattern = Pattern.str();
1351
1352 std::string RegexError;
1353 Result.Regex = std::make_shared<llvm::Regex>(Result.Pattern);
1354 if (!Result.Regex->isValid(RegexError)) {
1355 Diags.Report(diag::err_drv_optimization_remark_pattern)
1356 << RegexError << A->getAsString(Args);
1357 return false;
1358 }
1359
1360 return true;
1361 };
1362
1363 for (Arg *A : Args) {
1364 if (A->getOption().matches(OPT_R_Joined)) {
1365 StringRef Value = A->getValue();
1366
1367 if (Value == Name)
1369 else if (Value == "everything")
1371 else if (Value.split('-') == std::make_pair(StringRef("no"), Name))
1373 else if (Value == "no-everything")
1375 else
1376 continue;
1377
1378 if (Result.Kind == CodeGenOptions::RK_Disabled ||
1380 Result.Pattern = "";
1381 Result.Regex = nullptr;
1382 } else {
1383 InitializeResultPattern(A, ".*");
1384 }
1385 } else if (A->getOption().matches(OptEQ)) {
1387 if (!InitializeResultPattern(A, A->getValue()))
1389 }
1390 }
1391
1392 return Result;
1393}
1394
1395static bool parseDiagnosticLevelMask(StringRef FlagName,
1396 const std::vector<std::string> &Levels,
1397 DiagnosticsEngine &Diags,
1399 bool Success = true;
1400 for (const auto &Level : Levels) {
1401 DiagnosticLevelMask const PM =
1402 llvm::StringSwitch<DiagnosticLevelMask>(Level)
1403 .Case("note", DiagnosticLevelMask::Note)
1404 .Case("remark", DiagnosticLevelMask::Remark)
1405 .Case("warning", DiagnosticLevelMask::Warning)
1406 .Case("error", DiagnosticLevelMask::Error)
1407 .Default(DiagnosticLevelMask::None);
1408 if (PM == DiagnosticLevelMask::None) {
1409 Success = false;
1410 Diags.Report(diag::err_drv_invalid_value) << FlagName << Level;
1411 }
1412 M = M | PM;
1413 }
1414 return Success;
1415}
1416
1417static void parseSanitizerKinds(StringRef FlagName,
1418 const std::vector<std::string> &Sanitizers,
1419 DiagnosticsEngine &Diags, SanitizerSet &S) {
1420 for (const auto &Sanitizer : Sanitizers) {
1421 SanitizerMask K = parseSanitizerValue(Sanitizer, /*AllowGroups=*/false);
1422 if (K == SanitizerMask())
1423 Diags.Report(diag::err_drv_invalid_value) << FlagName << Sanitizer;
1424 else
1425 S.set(K, true);
1426 }
1427}
1428
1434
1437 const std::vector<std::string> &Sanitizers,
1438 DiagnosticsEngine &Diags) {
1439 SanitizerMaskCutoffs Cutoffs;
1440 for (const auto &Sanitizer : Sanitizers) {
1441 if (!parseSanitizerWeightedValue(Sanitizer, /*AllowGroups=*/false, Cutoffs))
1442 Diags.Report(diag::err_drv_invalid_value) << FlagName << Sanitizer;
1443 }
1444 return Cutoffs;
1445}
1446
1447static void parseXRayInstrumentationBundle(StringRef FlagName, StringRef Bundle,
1448 ArgList &Args, DiagnosticsEngine &D,
1449 XRayInstrSet &S) {
1451 llvm::SplitString(Bundle, BundleParts, ",");
1452 for (const auto &B : BundleParts) {
1453 auto Mask = parseXRayInstrValue(B);
1454 if (Mask == XRayInstrKind::None)
1455 if (B != "none")
1456 D.Report(diag::err_drv_invalid_value) << FlagName << Bundle;
1457 else
1458 S.Mask = Mask;
1459 else if (Mask == XRayInstrKind::All)
1460 S.Mask = Mask;
1461 else
1462 S.set(Mask, true);
1463 }
1464}
1465
1468 serializeXRayInstrValue(S, BundleParts);
1469 std::string Buffer;
1470 llvm::raw_string_ostream OS(Buffer);
1471 llvm::interleave(BundleParts, OS, [&OS](StringRef Part) { OS << Part; }, ",");
1472 return Buffer;
1473}
1474
1477 const llvm::Triple &Triple) {
1478 assert(Triple.getArch() == llvm::Triple::aarch64);
1479 if (LangOpts.PointerAuthCalls) {
1480 using Key = PointerAuthSchema::ARM8_3Key;
1481 using Discrimination = PointerAuthSchema::Discrimination;
1482 // If you change anything here, be sure to update <ptrauth.h>.
1484 Key::ASIA, false,
1485 LangOpts.PointerAuthFunctionTypeDiscrimination ? Discrimination::Type
1486 : Discrimination::None);
1487
1489 Key::ASDA, LangOpts.PointerAuthVTPtrAddressDiscrimination,
1490 LangOpts.PointerAuthVTPtrTypeDiscrimination ? Discrimination::Type
1491 : Discrimination::None);
1492
1493 if (LangOpts.PointerAuthTypeInfoVTPtrDiscrimination)
1495 PointerAuthSchema(Key::ASDA, true, Discrimination::Constant,
1497 else
1499 PointerAuthSchema(Key::ASDA, false, Discrimination::None);
1500
1501 if (LangOpts.PointerAuthVTTVTPtrDiscrimination)
1503 Key::ASDA, LangOpts.PointerAuthVTPtrAddressDiscrimination,
1504 LangOpts.PointerAuthVTPtrTypeDiscrimination ? Discrimination::Type
1505 : Discrimination::None);
1506 else
1508 PointerAuthSchema(Key::ASDA, false, Discrimination::None);
1509
1511 PointerAuthSchema(Key::ASIA, true, Discrimination::Decl);
1513 PointerAuthSchema(Key::ASIA, false, Discrimination::Type);
1514
1516 PointerAuthSchema(Key::ASIA, true, Discrimination::None);
1518 PointerAuthSchema(Key::ASIA, true, Discrimination::None);
1520 PointerAuthSchema(Key::ASIA, true, Discrimination::None);
1521 if (LangOpts.PointerAuthBlockDescriptorPointers)
1523 PointerAuthSchema(Key::ASDA, true, Discrimination::Constant,
1525
1527 PointerAuthSchema(Key::ASIA, true, Discrimination::None);
1529 PointerAuthSchema(Key::ASDA, true, Discrimination::Constant,
1531 if (LangOpts.PointerAuthObjcIsa) {
1532 Opts.ObjCIsaPointers =
1533 PointerAuthSchema(Key::ASDA, true, Discrimination::Constant,
1535 Opts.ObjCSuperPointers =
1536 PointerAuthSchema(Key::ASDA, true, Discrimination::Constant,
1538 }
1539
1540 if (LangOpts.PointerAuthObjcClassROPointers)
1541 Opts.ObjCClassROPointers =
1542 PointerAuthSchema(Key::ASDA, true, Discrimination::Constant,
1544 }
1545 Opts.ReturnAddresses = LangOpts.PointerAuthReturns;
1546 Opts.AuthTraps = LangOpts.PointerAuthAuthTraps;
1547 Opts.IndirectGotos = LangOpts.PointerAuthIndirectGotos;
1548 Opts.AArch64JumpTableHardening = LangOpts.AArch64JumpTableHardening;
1549}
1550
1552 const LangOptions &LangOpts,
1553 const llvm::Triple &Triple,
1554 DiagnosticsEngine &Diags) {
1555 if (!LangOpts.PointerAuthCalls && !LangOpts.PointerAuthReturns &&
1556 !LangOpts.PointerAuthAuthTraps && !LangOpts.PointerAuthIndirectGotos &&
1557 !LangOpts.AArch64JumpTableHardening)
1558 return;
1559
1561}
1562
1563void CompilerInvocationBase::GenerateCodeGenArgs(const CodeGenOptions &Opts,
1564 ArgumentConsumer Consumer,
1565 const llvm::Triple &T,
1566 const std::string &OutputFile,
1567 const LangOptions *LangOpts) {
1568 const CodeGenOptions &CodeGenOpts = Opts;
1569
1570 if (Opts.OptimizationLevel == 0)
1571 GenerateArg(Consumer, OPT_O0);
1572 else
1573 GenerateArg(Consumer, OPT_O, Twine(Opts.OptimizationLevel));
1574
1575#define CODEGEN_OPTION_WITH_MARSHALLING(...) \
1576 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
1577#include "clang/Options/Options.inc"
1578#undef CODEGEN_OPTION_WITH_MARSHALLING
1579
1580 if (Opts.OptimizationLevel > 0) {
1581 if (Opts.Inlining == CodeGenOptions::NormalInlining)
1582 GenerateArg(Consumer, OPT_finline_functions);
1583 else if (Opts.Inlining == CodeGenOptions::OnlyHintInlining)
1584 GenerateArg(Consumer, OPT_finline_hint_functions);
1585 else if (Opts.Inlining == CodeGenOptions::OnlyAlwaysInlining)
1586 GenerateArg(Consumer, OPT_fno_inline);
1587 }
1588
1589 if (Opts.DirectAccessExternalData && LangOpts->PICLevel != 0)
1590 GenerateArg(Consumer, OPT_fdirect_access_external_data);
1591 else if (!Opts.DirectAccessExternalData && LangOpts->PICLevel == 0)
1592 GenerateArg(Consumer, OPT_fno_direct_access_external_data);
1593
1594 std::optional<StringRef> DebugInfoVal;
1595 switch (Opts.DebugInfo) {
1596 case llvm::codegenoptions::DebugLineTablesOnly:
1597 DebugInfoVal = "line-tables-only";
1598 break;
1599 case llvm::codegenoptions::DebugDirectivesOnly:
1600 DebugInfoVal = "line-directives-only";
1601 break;
1602 case llvm::codegenoptions::DebugInfoConstructor:
1603 DebugInfoVal = "constructor";
1604 break;
1605 case llvm::codegenoptions::LimitedDebugInfo:
1606 DebugInfoVal = "limited";
1607 break;
1608 case llvm::codegenoptions::FullDebugInfo:
1609 DebugInfoVal = "standalone";
1610 break;
1611 case llvm::codegenoptions::UnusedTypeInfo:
1612 DebugInfoVal = "unused-types";
1613 break;
1614 case llvm::codegenoptions::NoDebugInfo: // default value
1615 DebugInfoVal = std::nullopt;
1616 break;
1617 case llvm::codegenoptions::LocTrackingOnly: // implied value
1618 DebugInfoVal = std::nullopt;
1619 break;
1620 }
1621 if (DebugInfoVal)
1622 GenerateArg(Consumer, OPT_debug_info_kind_EQ, *DebugInfoVal);
1623
1624 for (const auto &Prefix : Opts.DebugPrefixMap)
1625 GenerateArg(Consumer, OPT_fdebug_prefix_map_EQ,
1626 Prefix.first + "=" + Prefix.second);
1627
1628 for (const auto &Prefix : Opts.CoveragePrefixMap)
1629 GenerateArg(Consumer, OPT_fcoverage_prefix_map_EQ,
1630 Prefix.first + "=" + Prefix.second);
1631
1632 if (Opts.NewStructPathTBAA)
1633 GenerateArg(Consumer, OPT_new_struct_path_tbaa);
1634
1635 if (Opts.OptimizeSize == 1)
1636 GenerateArg(Consumer, OPT_O, "s");
1637 else if (Opts.OptimizeSize == 2)
1638 GenerateArg(Consumer, OPT_O, "z");
1639
1640 // SimplifyLibCalls is set only in the absence of -fno-builtin and
1641 // -ffreestanding. We'll consider that when generating them.
1642
1643 // NoBuiltinFuncs are generated by LangOptions.
1644
1645 if (Opts.UnrollLoops && Opts.OptimizationLevel <= 1)
1646 GenerateArg(Consumer, OPT_funroll_loops);
1647 else if (!Opts.UnrollLoops && Opts.OptimizationLevel > 1)
1648 GenerateArg(Consumer, OPT_fno_unroll_loops);
1649
1650 if (Opts.InterchangeLoops)
1651 GenerateArg(Consumer, OPT_floop_interchange);
1652 else
1653 GenerateArg(Consumer, OPT_fno_loop_interchange);
1654
1655 if (Opts.FuseLoops)
1656 GenerateArg(Consumer, OPT_fexperimental_loop_fusion);
1657
1658 if (!Opts.BinutilsVersion.empty())
1659 GenerateArg(Consumer, OPT_fbinutils_version_EQ, Opts.BinutilsVersion);
1660
1661 if (Opts.DebugNameTable ==
1662 static_cast<unsigned>(llvm::DICompileUnit::DebugNameTableKind::GNU))
1663 GenerateArg(Consumer, OPT_ggnu_pubnames);
1664 else if (Opts.DebugNameTable ==
1665 static_cast<unsigned>(
1666 llvm::DICompileUnit::DebugNameTableKind::Default))
1667 GenerateArg(Consumer, OPT_gpubnames);
1668
1669 if (Opts.DebugTemplateAlias)
1670 GenerateArg(Consumer, OPT_gtemplate_alias);
1671
1672 auto TNK = Opts.getDebugSimpleTemplateNames();
1673 if (TNK != llvm::codegenoptions::DebugTemplateNamesKind::Full) {
1674 if (TNK == llvm::codegenoptions::DebugTemplateNamesKind::Simple)
1675 GenerateArg(Consumer, OPT_gsimple_template_names_EQ, "simple");
1676 else if (TNK == llvm::codegenoptions::DebugTemplateNamesKind::Mangled)
1677 GenerateArg(Consumer, OPT_gsimple_template_names_EQ, "mangled");
1678 }
1679 // ProfileInstrumentUsePath is marshalled automatically, no need to generate
1680 // it or PGOUseInstrumentor.
1681
1682 if (Opts.TimePasses) {
1683 if (Opts.TimePassesPerRun)
1684 GenerateArg(Consumer, OPT_ftime_report_EQ, "per-pass-run");
1685 else
1686 GenerateArg(Consumer, OPT_ftime_report);
1687
1688 if (Opts.TimePassesJson)
1689 GenerateArg(Consumer, OPT_ftime_report_json);
1690 }
1691
1692 if (Opts.PrepareForLTO && !Opts.PrepareForThinLTO)
1693 GenerateArg(Consumer, OPT_flto_EQ, "full");
1694
1695 if (Opts.PrepareForThinLTO)
1696 GenerateArg(Consumer, OPT_flto_EQ, "thin");
1697
1698 if (!Opts.ThinLTOIndexFile.empty())
1699 GenerateArg(Consumer, OPT_fthinlto_index_EQ, Opts.ThinLTOIndexFile);
1700
1701 if (Opts.SaveTempsFilePrefix == OutputFile)
1702 GenerateArg(Consumer, OPT_save_temps_EQ, "obj");
1703
1704 if (!Opts.SaveDynDbgTempsFilePrefix.empty())
1705 GenerateArg(Consumer, OPT_save_dynamic_debugging_temps);
1706
1707 StringRef MemProfileBasename("memprof.profraw");
1708 if (!Opts.MemoryProfileOutput.empty()) {
1709 if (Opts.MemoryProfileOutput == MemProfileBasename) {
1710 GenerateArg(Consumer, OPT_fmemory_profile);
1711 } else {
1712 size_t ArgLength =
1713 Opts.MemoryProfileOutput.size() - MemProfileBasename.size();
1714 GenerateArg(Consumer, OPT_fmemory_profile_EQ,
1715 Opts.MemoryProfileOutput.substr(0, ArgLength));
1716 }
1717 }
1718
1719 if (memcmp(Opts.CoverageVersion, "0000", 4))
1720 GenerateArg(Consumer, OPT_coverage_version_EQ,
1721 StringRef(Opts.CoverageVersion, 4));
1722
1723 // TODO: Check if we need to generate arguments stored in CmdArgs. (Namely
1724 // '-fembed_bitcode', which does not map to any CompilerInvocation field and
1725 // won't be generated.)
1726
1728 std::string InstrBundle =
1730 if (!InstrBundle.empty())
1731 GenerateArg(Consumer, OPT_fxray_instrumentation_bundle, InstrBundle);
1732 }
1733
1734 if (Opts.CFProtectionReturn && Opts.CFProtectionBranch)
1735 GenerateArg(Consumer, OPT_fcf_protection_EQ, "full");
1736 else if (Opts.CFProtectionReturn)
1737 GenerateArg(Consumer, OPT_fcf_protection_EQ, "return");
1738 else if (Opts.CFProtectionBranch)
1739 GenerateArg(Consumer, OPT_fcf_protection_EQ, "branch");
1740
1741 if (Opts.CFProtectionBranch) {
1742 switch (Opts.getCFBranchLabelScheme()) {
1744 break;
1745#define CF_BRANCH_LABEL_SCHEME(Kind, FlagVal) \
1746 case CFBranchLabelSchemeKind::Kind: \
1747 GenerateArg(Consumer, OPT_mcf_branch_label_scheme_EQ, #FlagVal); \
1748 break;
1749#include "clang/Basic/CFProtectionOptions.def"
1750 }
1751 }
1752
1753 if (Opts.FunctionReturnThunks)
1754 GenerateArg(Consumer, OPT_mfunction_return_EQ, "thunk-extern");
1755
1756 for (const auto &F : Opts.LinkBitcodeFiles) {
1757 bool Builtint = F.LinkFlags == llvm::Linker::Flags::LinkOnlyNeeded &&
1758 F.PropagateAttrs && F.Internalize;
1759 GenerateArg(Consumer,
1760 Builtint ? OPT_mlink_builtin_bitcode : OPT_mlink_bitcode_file,
1761 F.Filename);
1762 }
1763
1764 if (Opts.EmulatedTLS)
1765 GenerateArg(Consumer, OPT_femulated_tls);
1766
1767 if (Opts.FPDenormalMode != llvm::DenormalMode::getIEEE())
1768 GenerateArg(Consumer, OPT_fdenormal_fp_math_EQ, Opts.FPDenormalMode.str());
1769
1770 if ((Opts.FPDenormalMode != Opts.FP32DenormalMode) ||
1771 (Opts.FP32DenormalMode != llvm::DenormalMode::getIEEE()))
1772 GenerateArg(Consumer, OPT_fdenormal_fp_math_f32_EQ,
1773 Opts.FP32DenormalMode.str());
1774
1775 if (Opts.StructReturnConvention == CodeGenOptions::SRCK_OnStack) {
1776 OptSpecifier Opt =
1777 T.isPPC32() ? OPT_maix_struct_return : OPT_fpcc_struct_return;
1778 GenerateArg(Consumer, Opt);
1779 } else if (Opts.StructReturnConvention == CodeGenOptions::SRCK_InRegs) {
1780 OptSpecifier Opt =
1781 T.isPPC32() ? OPT_msvr4_struct_return : OPT_freg_struct_return;
1782 GenerateArg(Consumer, Opt);
1783 }
1784
1785 if (Opts.XCOFFReadOnlyPointers)
1786 GenerateArg(Consumer, OPT_mxcoff_roptr);
1787
1788 if (!Opts.OptRecordPasses.empty())
1789 GenerateArg(Consumer, OPT_opt_record_passes, Opts.OptRecordPasses);
1790
1791 if (!Opts.OptRecordFormat.empty())
1792 GenerateArg(Consumer, OPT_opt_record_format, Opts.OptRecordFormat);
1793
1794 GenerateOptimizationRemark(Consumer, OPT_Rpass_EQ, "pass",
1795 Opts.OptimizationRemark);
1796
1797 GenerateOptimizationRemark(Consumer, OPT_Rpass_missed_EQ, "pass-missed",
1799
1800 GenerateOptimizationRemark(Consumer, OPT_Rpass_analysis_EQ, "pass-analysis",
1802
1803 GenerateArg(Consumer, OPT_fdiagnostics_hotness_threshold_EQ,
1805 ? Twine(*Opts.DiagnosticsHotnessThreshold)
1806 : "auto");
1807
1808 GenerateArg(Consumer, OPT_fdiagnostics_misexpect_tolerance_EQ,
1809 Twine(*Opts.DiagnosticsMisExpectTolerance));
1810
1811 for (StringRef Sanitizer : serializeSanitizerKinds(Opts.SanitizeRecover))
1812 GenerateArg(Consumer, OPT_fsanitize_recover_EQ, Sanitizer);
1813
1814 for (StringRef Sanitizer : serializeSanitizerKinds(Opts.SanitizeTrap))
1815 GenerateArg(Consumer, OPT_fsanitize_trap_EQ, Sanitizer);
1816
1817 for (StringRef Sanitizer :
1819 GenerateArg(Consumer, OPT_fsanitize_merge_handlers_EQ, Sanitizer);
1820
1821 SmallVector<std::string, 4> Values;
1823 for (std::string Sanitizer : Values)
1824 GenerateArg(Consumer, OPT_fsanitize_skip_hot_cutoff_EQ, Sanitizer);
1825
1827 GenerateArg(Consumer, OPT_fallow_runtime_check_skip_hot_cutoff_EQ,
1828 std::to_string(*Opts.AllowRuntimeCheckSkipHotCutoff));
1829 }
1830
1831 for (StringRef Sanitizer :
1833 GenerateArg(Consumer, OPT_fsanitize_annotate_debug_info_EQ, Sanitizer);
1834
1835 if (!Opts.EmitVersionIdentMetadata)
1836 GenerateArg(Consumer, OPT_Qn);
1837
1838 switch (Opts.FiniteLoops) {
1840 break;
1842 GenerateArg(Consumer, OPT_ffinite_loops);
1843 break;
1845 GenerateArg(Consumer, OPT_fno_finite_loops);
1846 break;
1847 }
1848
1849 if (Opts.StaticClosure)
1850 GenerateArg(Consumer, OPT_static_libclosure);
1851}
1852
1853bool CompilerInvocation::ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args,
1854 InputKind IK,
1855 DiagnosticsEngine &Diags,
1856 const llvm::Triple &T,
1857 const std::string &OutputFile,
1858 const LangOptions &LangOptsRef) {
1859 unsigned NumErrorsBefore = Diags.getNumErrors();
1860
1861 Opts.OptimizationLevel = getOptimizationLevel(Args, IK, Diags);
1862
1863 // The key paths of codegen options defined in Options.td start with
1864 // "CodeGenOpts.". Let's provide the expected variable name and type.
1865 CodeGenOptions &CodeGenOpts = Opts;
1866 // Some codegen options depend on language options. Let's provide the expected
1867 // variable name and type.
1868 const LangOptions *LangOpts = &LangOptsRef;
1869
1870#define CODEGEN_OPTION_WITH_MARSHALLING(...) \
1871 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
1872#include "clang/Options/Options.inc"
1873#undef CODEGEN_OPTION_WITH_MARSHALLING
1874
1875 // At O0 we want to fully disable inlining outside of cases marked with
1876 // 'alwaysinline' that are required for correctness.
1877 if (Opts.OptimizationLevel == 0) {
1878 Opts.setInlining(CodeGenOptions::OnlyAlwaysInlining);
1879 } else if (const Arg *A = Args.getLastArg(options::OPT_finline_functions,
1880 options::OPT_finline_hint_functions,
1881 options::OPT_fno_inline_functions,
1882 options::OPT_fno_inline)) {
1883 // Explicit inlining flags can disable some or all inlining even at
1884 // optimization levels above zero.
1885 if (A->getOption().matches(options::OPT_finline_functions))
1886 Opts.setInlining(CodeGenOptions::NormalInlining);
1887 else if (A->getOption().matches(options::OPT_finline_hint_functions))
1888 Opts.setInlining(CodeGenOptions::OnlyHintInlining);
1889 else
1890 Opts.setInlining(CodeGenOptions::OnlyAlwaysInlining);
1891 } else {
1892 Opts.setInlining(CodeGenOptions::NormalInlining);
1893 }
1894
1895 // PIC defaults to -fno-direct-access-external-data while non-PIC defaults to
1896 // -fdirect-access-external-data.
1897 Opts.DirectAccessExternalData =
1898 Args.hasArg(OPT_fdirect_access_external_data) ||
1899 (!Args.hasArg(OPT_fno_direct_access_external_data) &&
1900 LangOpts->PICLevel == 0);
1901
1902 if (Arg *A = Args.getLastArg(OPT_debug_info_kind_EQ)) {
1903 unsigned Val =
1904 llvm::StringSwitch<unsigned>(A->getValue())
1905 .Case("line-tables-only", llvm::codegenoptions::DebugLineTablesOnly)
1906 .Case("line-directives-only",
1907 llvm::codegenoptions::DebugDirectivesOnly)
1908 .Case("constructor", llvm::codegenoptions::DebugInfoConstructor)
1909 .Case("limited", llvm::codegenoptions::LimitedDebugInfo)
1910 .Case("standalone", llvm::codegenoptions::FullDebugInfo)
1911 .Case("unused-types", llvm::codegenoptions::UnusedTypeInfo)
1912 .Default(~0U);
1913 if (Val == ~0U)
1914 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
1915 << A->getValue();
1916 else
1917 Opts.setDebugInfo(static_cast<llvm::codegenoptions::DebugInfoKind>(Val));
1918 }
1919
1920 // If -fuse-ctor-homing is set and limited debug info is already on, then use
1921 // constructor homing, and vice versa for -fno-use-ctor-homing.
1922 if (const Arg *A =
1923 Args.getLastArg(OPT_fuse_ctor_homing, OPT_fno_use_ctor_homing)) {
1924 if (A->getOption().matches(OPT_fuse_ctor_homing) &&
1925 Opts.getDebugInfo() == llvm::codegenoptions::LimitedDebugInfo)
1926 Opts.setDebugInfo(llvm::codegenoptions::DebugInfoConstructor);
1927 if (A->getOption().matches(OPT_fno_use_ctor_homing) &&
1928 Opts.getDebugInfo() == llvm::codegenoptions::DebugInfoConstructor)
1929 Opts.setDebugInfo(llvm::codegenoptions::LimitedDebugInfo);
1930 }
1931
1932 for (const auto &Arg : Args.getAllArgValues(OPT_fdebug_prefix_map_EQ)) {
1933 auto Split = StringRef(Arg).split('=');
1934 Opts.DebugPrefixMap.emplace_back(Split.first, Split.second);
1935 }
1936
1937 for (const auto &Arg : Args.getAllArgValues(OPT_fcoverage_prefix_map_EQ)) {
1938 auto Split = StringRef(Arg).split('=');
1939 Opts.CoveragePrefixMap.emplace_back(Split.first, Split.second);
1940 }
1941
1942 if (Opts.OptimizationLevel > 0 && Opts.hasReducedDebugInfo() &&
1943 T.supportsDebugEntryValues())
1944 Opts.EmitCallSiteInfo = true;
1945
1946 if (!Opts.EnableDIPreservationVerify && Opts.DIBugsReportFilePath.size()) {
1947 Diags.Report(diag::warn_ignoring_verify_debuginfo_preserve_export)
1948 << Opts.DIBugsReportFilePath;
1949 Opts.DIBugsReportFilePath = "";
1950 }
1951
1952 Opts.NewStructPathTBAA = !Args.hasArg(OPT_no_struct_path_tbaa) &&
1953 Args.hasArg(OPT_new_struct_path_tbaa);
1954 Opts.OptimizeSize = getOptimizationLevelSize(Args);
1955 Opts.SimplifyLibCalls = !LangOpts->NoBuiltin;
1956 if (Opts.SimplifyLibCalls)
1957 Opts.NoBuiltinFuncs = LangOpts->NoBuiltinFuncs;
1958 Opts.UnrollLoops =
1959 Args.hasFlag(OPT_funroll_loops, OPT_fno_unroll_loops,
1960 (Opts.OptimizationLevel > 1));
1961 // Match the LLVM pipeline default (PipelineTuningOptions::LoopInterchange),
1962 // which enables the pass whenever the optimization pipeline runs.
1963 Opts.InterchangeLoops =
1964 Args.hasFlag(OPT_floop_interchange, OPT_fno_loop_interchange, true);
1965 Opts.FuseLoops = Args.hasFlag(OPT_fexperimental_loop_fusion,
1966 OPT_fno_experimental_loop_fusion, false);
1967 Opts.BinutilsVersion =
1968 std::string(Args.getLastArgValue(OPT_fbinutils_version_EQ));
1969
1970 Opts.DebugTemplateAlias = Args.hasArg(OPT_gtemplate_alias);
1971
1972 Opts.DebugNameTable = static_cast<unsigned>(
1973 Args.hasArg(OPT_ggnu_pubnames)
1974 ? llvm::DICompileUnit::DebugNameTableKind::GNU
1975 : Args.hasArg(OPT_gpubnames)
1976 ? llvm::DICompileUnit::DebugNameTableKind::Default
1977 : llvm::DICompileUnit::DebugNameTableKind::None);
1978 if (const Arg *A = Args.getLastArg(OPT_gsimple_template_names_EQ)) {
1979 StringRef Value = A->getValue();
1980 if (Value != "simple" && Value != "mangled")
1981 Diags.Report(diag::err_drv_unsupported_option_argument)
1982 << A->getSpelling() << A->getValue();
1983 Opts.setDebugSimpleTemplateNames(
1984 StringRef(A->getValue()) == "simple"
1985 ? llvm::codegenoptions::DebugTemplateNamesKind::Simple
1986 : llvm::codegenoptions::DebugTemplateNamesKind::Mangled);
1987 }
1988
1989 if (Args.hasArg(OPT_ftime_report, OPT_ftime_report_EQ, OPT_ftime_report_json,
1990 OPT_stats_file_timers)) {
1991 Opts.TimePasses = true;
1992
1993 // -ftime-report= is only for new pass manager.
1994 if (const Arg *EQ = Args.getLastArg(OPT_ftime_report_EQ)) {
1995 StringRef Val = EQ->getValue();
1996 if (Val == "per-pass")
1997 Opts.TimePassesPerRun = false;
1998 else if (Val == "per-pass-run")
1999 Opts.TimePassesPerRun = true;
2000 else
2001 Diags.Report(diag::err_drv_invalid_value)
2002 << EQ->getAsString(Args) << EQ->getValue();
2003 }
2004
2005 if (Args.getLastArg(OPT_ftime_report_json))
2006 Opts.TimePassesJson = true;
2007 }
2008
2009 Opts.PrepareForLTO = false;
2010 Opts.PrepareForThinLTO = false;
2011 if (Arg *A = Args.getLastArg(OPT_flto_EQ)) {
2012 Opts.PrepareForLTO = true;
2013 StringRef S = A->getValue();
2014 if (S == "thin")
2015 Opts.PrepareForThinLTO = true;
2016 else if (S != "full")
2017 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << S;
2018 if (Args.hasArg(OPT_funified_lto))
2019 Opts.PrepareForThinLTO = true;
2020 }
2021 if (Arg *A = Args.getLastArg(OPT_fthinlto_index_EQ)) {
2022 if (IK.getLanguage() != Language::LLVM_IR)
2023 Diags.Report(diag::err_drv_argument_only_allowed_with)
2024 << A->getAsString(Args) << "-x ir";
2025 Opts.ThinLTOIndexFile =
2026 std::string(Args.getLastArgValue(OPT_fthinlto_index_EQ));
2027 }
2028 if (Arg *A = Args.getLastArg(OPT_save_temps_EQ))
2029 Opts.SaveTempsFilePrefix =
2030 llvm::StringSwitch<std::string>(A->getValue())
2031 .Case("obj", OutputFile)
2032 .Default(llvm::sys::path::filename(OutputFile).str());
2033
2034 if (Args.getLastArg(OPT_save_dynamic_debugging_temps))
2035 Opts.SaveDynDbgTempsFilePrefix = OutputFile;
2036
2037 // The memory profile runtime appends the pid to make this name more unique.
2038 const char *MemProfileBasename = "memprof.profraw";
2039 if (Args.hasArg(OPT_fmemory_profile_EQ)) {
2040 SmallString<128> Path(Args.getLastArgValue(OPT_fmemory_profile_EQ));
2041 llvm::sys::path::append(Path, MemProfileBasename);
2042 Opts.MemoryProfileOutput = std::string(Path);
2043 } else if (Args.hasArg(OPT_fmemory_profile))
2044 Opts.MemoryProfileOutput = MemProfileBasename;
2045
2046 if (Opts.CoverageNotesFile.size() || Opts.CoverageDataFile.size()) {
2047 if (Args.hasArg(OPT_coverage_version_EQ)) {
2048 StringRef CoverageVersion = Args.getLastArgValue(OPT_coverage_version_EQ);
2049 if (CoverageVersion.size() != 4) {
2050 Diags.Report(diag::err_drv_invalid_value)
2051 << Args.getLastArg(OPT_coverage_version_EQ)->getAsString(Args)
2052 << CoverageVersion;
2053 } else {
2054 memcpy(Opts.CoverageVersion, CoverageVersion.data(), 4);
2055 }
2056 }
2057 }
2058 // FIXME: For backend options that are not yet recorded as function
2059 // attributes in the IR, keep track of them so we can embed them in a
2060 // separate data section and use them when building the bitcode.
2061 for (const auto &A : Args) {
2062 // Do not encode output and input.
2063 if (A->getOption().getID() == options::OPT_o ||
2064 A->getOption().getID() == options::OPT_INPUT ||
2065 A->getOption().getID() == options::OPT_x ||
2066 A->getOption().getID() == options::OPT_fembed_bitcode ||
2067 A->getOption().matches(options::OPT_W_Group))
2068 continue;
2069 ArgStringList ASL;
2070 A->render(Args, ASL);
2071 for (const auto &arg : ASL) {
2072 StringRef ArgStr(arg);
2073 llvm::append_range(Opts.CmdArgs, ArgStr);
2074 // using \00 to separate each commandline options.
2075 Opts.CmdArgs.push_back('\0');
2076 }
2077 }
2078
2079 auto XRayInstrBundles =
2080 Args.getAllArgValues(OPT_fxray_instrumentation_bundle);
2081 if (XRayInstrBundles.empty())
2083 else
2084 for (const auto &A : XRayInstrBundles)
2085 parseXRayInstrumentationBundle("-fxray-instrumentation-bundle=", A, Args,
2086 Diags, Opts.XRayInstrumentationBundle);
2087
2088 if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
2089 StringRef Name = A->getValue();
2090 if (Name == "full") {
2091 Opts.CFProtectionReturn = 1;
2092 Opts.CFProtectionBranch = 1;
2093 } else if (Name == "return")
2094 Opts.CFProtectionReturn = 1;
2095 else if (Name == "branch")
2096 Opts.CFProtectionBranch = 1;
2097 else if (Name != "none")
2098 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
2099 }
2100
2101 if (Opts.CFProtectionBranch && T.isRISCV()) {
2102 if (const Arg *A = Args.getLastArg(OPT_mcf_branch_label_scheme_EQ)) {
2103 const auto Scheme =
2104 llvm::StringSwitch<CFBranchLabelSchemeKind>(A->getValue())
2105#define CF_BRANCH_LABEL_SCHEME(Kind, FlagVal) \
2106 .Case(#FlagVal, CFBranchLabelSchemeKind::Kind)
2107#include "clang/Basic/CFProtectionOptions.def"
2110 Opts.setCFBranchLabelScheme(Scheme);
2111 else
2112 Diags.Report(diag::err_drv_invalid_value)
2113 << A->getAsString(Args) << A->getValue();
2114 }
2115 }
2116
2117 if (const Arg *A = Args.getLastArg(OPT_mfunction_return_EQ)) {
2118 auto Val = llvm::StringSwitch<llvm::FunctionReturnThunksKind>(A->getValue())
2119 .Case("keep", llvm::FunctionReturnThunksKind::Keep)
2120 .Case("thunk-extern", llvm::FunctionReturnThunksKind::Extern)
2121 .Default(llvm::FunctionReturnThunksKind::Invalid);
2122 // SystemZ might want to add support for "expolines."
2123 if (!T.isX86())
2124 Diags.Report(diag::err_drv_argument_not_allowed_with)
2125 << A->getSpelling() << T.getTriple();
2126 else if (Val == llvm::FunctionReturnThunksKind::Invalid)
2127 Diags.Report(diag::err_drv_invalid_value)
2128 << A->getAsString(Args) << A->getValue();
2129 else if (Val == llvm::FunctionReturnThunksKind::Extern &&
2130 Args.getLastArgValue(OPT_mcmodel_EQ) == "large")
2131 Diags.Report(diag::err_drv_argument_not_allowed_with)
2132 << A->getAsString(Args)
2133 << Args.getLastArg(OPT_mcmodel_EQ)->getAsString(Args);
2134 else
2135 Opts.FunctionReturnThunks = static_cast<unsigned>(Val);
2136 }
2137
2138 for (auto *A :
2139 Args.filtered(OPT_mlink_bitcode_file, OPT_mlink_builtin_bitcode)) {
2140 CodeGenOptions::BitcodeFileToLink F;
2141 F.Filename = A->getValue();
2142 if (A->getOption().matches(OPT_mlink_builtin_bitcode)) {
2143 F.LinkFlags = llvm::Linker::Flags::LinkOnlyNeeded;
2144 // When linking CUDA bitcode, propagate function attributes so that
2145 // e.g. libdevice gets fast-math attrs if we're building with fast-math.
2146 F.PropagateAttrs = true;
2147 F.Internalize = true;
2148 }
2149 Opts.LinkBitcodeFiles.push_back(F);
2150 }
2151
2152 if (Arg *A = Args.getLastArg(OPT_fdenormal_fp_math_EQ)) {
2153 StringRef Val = A->getValue();
2154 Opts.FPDenormalMode = llvm::parseDenormalFPAttribute(Val);
2155 Opts.FP32DenormalMode = Opts.FPDenormalMode;
2156 if (!Opts.FPDenormalMode.isValid())
2157 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
2158 }
2159
2160 if (Arg *A = Args.getLastArg(OPT_fdenormal_fp_math_f32_EQ)) {
2161 StringRef Val = A->getValue();
2162 Opts.FP32DenormalMode = llvm::parseDenormalFPAttribute(Val);
2163 if (!Opts.FP32DenormalMode.isValid())
2164 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
2165 }
2166
2167 // X86_32 has -fppc-struct-return and -freg-struct-return.
2168 // PPC32 has -maix-struct-return and -msvr4-struct-return.
2169 if (Arg *A =
2170 Args.getLastArg(OPT_fpcc_struct_return, OPT_freg_struct_return,
2171 OPT_maix_struct_return, OPT_msvr4_struct_return)) {
2172 // TODO: We might want to consider enabling these options on AIX in the
2173 // future.
2174 if (T.isOSAIX())
2175 Diags.Report(diag::err_drv_unsupported_opt_for_target)
2176 << A->getSpelling() << T.str();
2177
2178 const Option &O = A->getOption();
2179 if (O.matches(OPT_fpcc_struct_return) ||
2180 O.matches(OPT_maix_struct_return)) {
2181 Opts.setStructReturnConvention(CodeGenOptions::SRCK_OnStack);
2182 } else {
2183 assert(O.matches(OPT_freg_struct_return) ||
2184 O.matches(OPT_msvr4_struct_return));
2185 Opts.setStructReturnConvention(CodeGenOptions::SRCK_InRegs);
2186 }
2187 }
2188
2189 if (Arg *A = Args.getLastArg(OPT_mxcoff_roptr)) {
2190 if (!T.isOSAIX())
2191 Diags.Report(diag::err_drv_unsupported_opt_for_target)
2192 << A->getSpelling() << T.str();
2193
2194 // Since the storage mapping class is specified per csect,
2195 // without using data sections, it is less effective to use read-only
2196 // pointers. Using read-only pointers may cause other RO variables in the
2197 // same csect to become RW when the linker acts upon `-bforceimprw`;
2198 // therefore, we require that separate data sections
2199 // are used when `-mxcoff-roptr` is in effect. We respect the setting of
2200 // data-sections since we have not found reasons to do otherwise that
2201 // overcome the user surprise of not respecting the setting.
2202 if (!Args.hasFlag(OPT_fdata_sections, OPT_fno_data_sections, false))
2203 Diags.Report(diag::err_roptr_requires_data_sections);
2204
2205 Opts.XCOFFReadOnlyPointers = true;
2206 }
2207
2208 if (Arg *A = Args.getLastArg(OPT_mabi_EQ_quadword_atomics)) {
2209 if (!T.isOSAIX() || T.isPPC32())
2210 Diags.Report(diag::err_drv_unsupported_opt_for_target)
2211 << A->getSpelling() << T.str();
2212 }
2213
2214 bool NeedLocTracking = false;
2215
2216 if (!Opts.OptRecordFile.empty())
2217 NeedLocTracking = true;
2218
2219 if (Arg *A = Args.getLastArg(OPT_opt_record_passes)) {
2220 Opts.OptRecordPasses = A->getValue();
2221 NeedLocTracking = true;
2222 }
2223
2224 if (Arg *A = Args.getLastArg(OPT_opt_record_format)) {
2225 Opts.OptRecordFormat = A->getValue();
2226 NeedLocTracking = true;
2227 }
2228
2229 Opts.OptimizationRemark =
2230 ParseOptimizationRemark(Diags, Args, OPT_Rpass_EQ, "pass");
2231
2233 ParseOptimizationRemark(Diags, Args, OPT_Rpass_missed_EQ, "pass-missed");
2234
2236 Diags, Args, OPT_Rpass_analysis_EQ, "pass-analysis");
2237
2238 NeedLocTracking |= Opts.OptimizationRemark.hasValidPattern() ||
2241
2242 bool UsingSampleProfile = !Opts.SampleProfileFile.empty();
2243 bool UsingProfile =
2244 UsingSampleProfile || !Opts.ProfileInstrumentUsePath.empty();
2245
2246 if (Opts.DiagnosticsWithHotness && !UsingProfile &&
2247 // An IR file will contain PGO as metadata
2249 Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo)
2250 << "-fdiagnostics-show-hotness";
2251
2252 // Parse remarks hotness threshold. Valid value is either integer or 'auto'.
2253 if (auto *arg =
2254 Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
2255 auto ResultOrErr =
2256 llvm::remarks::parseHotnessThresholdOption(arg->getValue());
2257
2258 if (!ResultOrErr) {
2259 Diags.Report(diag::err_drv_invalid_diagnotics_hotness_threshold)
2260 << "-fdiagnostics-hotness-threshold=";
2261 } else {
2262 Opts.DiagnosticsHotnessThreshold = *ResultOrErr;
2263 if ((!Opts.DiagnosticsHotnessThreshold ||
2264 *Opts.DiagnosticsHotnessThreshold > 0) &&
2265 !UsingProfile)
2266 Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo)
2267 << "-fdiagnostics-hotness-threshold=";
2268 }
2269 }
2270
2271 if (auto *arg =
2272 Args.getLastArg(options::OPT_fdiagnostics_misexpect_tolerance_EQ)) {
2273 auto ResultOrErr = parseToleranceOption(arg->getValue());
2274
2275 if (!ResultOrErr) {
2276 Diags.Report(diag::err_drv_invalid_diagnotics_misexpect_tolerance)
2277 << "-fdiagnostics-misexpect-tolerance=";
2278 } else {
2279 Opts.DiagnosticsMisExpectTolerance = *ResultOrErr;
2280 if ((!Opts.DiagnosticsMisExpectTolerance ||
2281 *Opts.DiagnosticsMisExpectTolerance > 0) &&
2282 !UsingProfile)
2283 Diags.Report(diag::warn_drv_diagnostics_misexpect_requires_pgo)
2284 << "-fdiagnostics-misexpect-tolerance=";
2285 }
2286 }
2287
2288 // If the user requested to use a sample profile for PGO, then the
2289 // backend will need to track source location information so the profile
2290 // can be incorporated into the IR.
2291 if (UsingSampleProfile)
2292 NeedLocTracking = true;
2293
2294 if (!Opts.StackUsageFile.empty())
2295 NeedLocTracking = true;
2296
2297 // If the user requested a flag that requires source locations available in
2298 // the backend, make sure that the backend tracks source location information.
2299 if (NeedLocTracking &&
2300 Opts.getDebugInfo() == llvm::codegenoptions::NoDebugInfo)
2301 Opts.setDebugInfo(llvm::codegenoptions::LocTrackingOnly);
2302
2303 // Parse -fsanitize-recover= arguments.
2304 // FIXME: Report unrecoverable sanitizers incorrectly specified here.
2305 parseSanitizerKinds("-fsanitize-recover=",
2306 Args.getAllArgValues(OPT_fsanitize_recover_EQ), Diags,
2307 Opts.SanitizeRecover);
2308 parseSanitizerKinds("-fsanitize-trap=",
2309 Args.getAllArgValues(OPT_fsanitize_trap_EQ), Diags,
2310 Opts.SanitizeTrap);
2311 parseSanitizerKinds("-fsanitize-merge=",
2312 Args.getAllArgValues(OPT_fsanitize_merge_handlers_EQ),
2313 Diags, Opts.SanitizeMergeHandlers);
2314
2315 // Parse -fsanitize-skip-hot-cutoff= arguments.
2317 "-fsanitize-skip-hot-cutoff=",
2318 Args.getAllArgValues(OPT_fsanitize_skip_hot_cutoff_EQ), Diags);
2319
2321 "-fsanitize-annotate-debug-info=",
2322 Args.getAllArgValues(OPT_fsanitize_annotate_debug_info_EQ), Diags,
2324
2325 if (StringRef V =
2326 Args.getLastArgValue(OPT_fallow_runtime_check_skip_hot_cutoff_EQ);
2327 !V.empty()) {
2328 double A;
2329 if (V.getAsDouble(A) || A < 0.0 || A > 1.0) {
2330 Diags.Report(diag::err_drv_invalid_value)
2331 << "-fallow-runtime-check-skip-hot-cutoff=" << V;
2332 } else {
2334 }
2335 }
2336
2337 Opts.EmitVersionIdentMetadata = Args.hasFlag(OPT_Qy, OPT_Qn, true);
2338
2339 if (!LangOpts->CUDAIsDevice)
2341
2342 if (Args.hasArg(options::OPT_ffinite_loops))
2343 Opts.FiniteLoops = CodeGenOptions::FiniteLoopsKind::Always;
2344 else if (Args.hasArg(options::OPT_fno_finite_loops))
2345 Opts.FiniteLoops = CodeGenOptions::FiniteLoopsKind::Never;
2346
2347 Opts.EmitIEEENaNCompliantInsts = Args.hasFlag(
2348 options::OPT_mamdgpu_ieee, options::OPT_mno_amdgpu_ieee, true);
2349 if (!Opts.EmitIEEENaNCompliantInsts && !LangOptsRef.NoHonorNaNs)
2350 Diags.Report(diag::err_drv_amdgpu_ieee_without_no_honor_nans);
2351
2352 Opts.StaticClosure = Args.hasArg(options::OPT_static_libclosure);
2353
2354 if (!Opts.HLSLRecordCommandLine.empty()) {
2355 auto ParsedArgs =
2357 if (!ParsedArgs)
2358 Diags.Report(diag::err_drv_invalid_escaped_command_line)
2359 << llvm::toString(ParsedArgs.takeError());
2360 else
2361 Opts.HLSLParsedCommandLine = std::move(*ParsedArgs);
2362 }
2363
2364 return Diags.getNumErrors() == NumErrorsBefore;
2365}
2366
2368 ArgumentConsumer Consumer) {
2369 const DependencyOutputOptions &DependencyOutputOpts = Opts;
2370#define DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING(...) \
2371 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
2372#include "clang/Options/Options.inc"
2373#undef DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING
2374
2376 GenerateArg(Consumer, OPT_show_includes);
2377
2378 for (const auto &Dep : Opts.ExtraDeps) {
2379 switch (Dep.second) {
2381 // Sanitizer ignorelist arguments are generated from LanguageOptions.
2382 continue;
2383 case EDK_ModuleFile:
2384 // Module file arguments are generated from FrontendOptions and
2385 // HeaderSearchOptions.
2386 continue;
2387 case EDK_ProfileList:
2388 // Profile list arguments are generated from LanguageOptions via the
2389 // marshalling infrastructure.
2390 continue;
2391 case EDK_DepFileEntry:
2392 GenerateArg(Consumer, OPT_fdepfile_entry, Dep.first);
2393 break;
2394 }
2395 }
2396}
2397
2399 ArgList &Args, DiagnosticsEngine &Diags,
2400 frontend::ActionKind Action,
2401 bool ShowLineMarkers) {
2402 unsigned NumErrorsBefore = Diags.getNumErrors();
2403
2404 DependencyOutputOptions &DependencyOutputOpts = Opts;
2405#define DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING(...) \
2406 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
2407#include "clang/Options/Options.inc"
2408#undef DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING
2409
2410 if (Args.hasArg(OPT_show_includes)) {
2411 // Writing both /showIncludes and preprocessor output to stdout
2412 // would produce interleaved output, so use stderr for /showIncludes.
2413 // This behaves the same as cl.exe, when /E, /EP or /P are passed.
2414 if (Action == frontend::PrintPreprocessedInput || !ShowLineMarkers)
2416 else
2418 } else {
2420 }
2421
2422 // Add sanitizer ignorelists as extra dependencies.
2423 // They won't be discovered by the regular preprocessor, so
2424 // we let make / ninja to know about this implicit dependency.
2425 if (!Args.hasArg(OPT_fno_sanitize_ignorelist)) {
2426 for (const auto *A : Args.filtered(OPT_fsanitize_ignorelist_EQ)) {
2427 StringRef Val = A->getValue();
2428 if (!Val.contains('='))
2429 Opts.ExtraDeps.emplace_back(std::string(Val), EDK_SanitizeIgnorelist);
2430 }
2431 if (Opts.IncludeSystemHeaders) {
2432 for (const auto *A : Args.filtered(OPT_fsanitize_system_ignorelist_EQ)) {
2433 StringRef Val = A->getValue();
2434 if (!Val.contains('='))
2435 Opts.ExtraDeps.emplace_back(std::string(Val), EDK_SanitizeIgnorelist);
2436 }
2437 }
2438 }
2439
2440 // -fprofile-list= dependencies.
2441 for (const auto &Filename : Args.getAllArgValues(OPT_fprofile_list_EQ))
2442 Opts.ExtraDeps.emplace_back(Filename, EDK_ProfileList);
2443
2444 // Propagate the extra dependencies.
2445 for (const auto *A : Args.filtered(OPT_fdepfile_entry))
2446 Opts.ExtraDeps.emplace_back(A->getValue(), EDK_DepFileEntry);
2447
2448 // Only the -fmodule-file=<file> form.
2449 for (const auto *A : Args.filtered(OPT_fmodule_file)) {
2450 StringRef Val = A->getValue();
2451 if (!Val.contains('='))
2452 Opts.ExtraDeps.emplace_back(std::string(Val), EDK_ModuleFile);
2453 }
2454
2455 // Check for invalid combinations of header-include-format
2456 // and header-include-filtering.
2457 if (Opts.HeaderIncludeFormat == HIFMT_Textual &&
2459 if (Args.hasArg(OPT_header_include_format_EQ))
2460 Diags.Report(diag::err_drv_print_header_cc1_invalid_combination)
2463 else
2464 Diags.Report(diag::err_drv_print_header_cc1_invalid_filtering)
2466 } else if (Opts.HeaderIncludeFormat == HIFMT_JSON &&
2468 if (Args.hasArg(OPT_header_include_filtering_EQ))
2469 Diags.Report(diag::err_drv_print_header_cc1_invalid_combination)
2472 else
2473 Diags.Report(diag::err_drv_print_header_cc1_invalid_format)
2475 }
2476
2477 return Diags.getNumErrors() == NumErrorsBefore;
2478}
2479
2480static ShowColorsKind parseShowColorsMode(const ArgList &Args,
2481 bool DefaultColor) {
2482 // Color diagnostics default to auto ("on" if terminal supports) in the driver
2483 // but default to off in cc1, needing an explicit OPT_fdiagnostics_color.
2484 // Support both clang's -f[no-]color-diagnostics and gcc's
2485 // -f[no-]diagnostics-colors[=never|always|auto].
2486 ShowColorsKind Mode =
2488 for (auto *A : Args) {
2489 const Option &O = A->getOption();
2490 if (O.matches(options::OPT_fcolor_diagnostics)) {
2491 Mode = ShowColorsKind::On;
2492 } else if (O.matches(options::OPT_fno_color_diagnostics)) {
2493 Mode = ShowColorsKind::Off;
2494 } else if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
2495 StringRef Value(A->getValue());
2496 if (Value == "always")
2497 Mode = ShowColorsKind::On;
2498 else if (Value == "never")
2499 Mode = ShowColorsKind::Off;
2500 else if (Value == "auto")
2501 Mode = ShowColorsKind::Auto;
2502 }
2503 }
2504 return Mode;
2505}
2506
2507static bool checkVerifyPrefixes(const std::vector<std::string> &VerifyPrefixes,
2508 DiagnosticsEngine &Diags) {
2509 bool Success = true;
2510 for (const auto &Prefix : VerifyPrefixes) {
2511 // Every prefix must start with a letter and contain only alphanumeric
2512 // characters, hyphens, and underscores.
2513 auto BadChar = llvm::find_if(Prefix, [](char C) {
2514 return !isAlphanumeric(C) && C != '-' && C != '_';
2515 });
2516 if (BadChar != Prefix.end() || !isLetter(Prefix[0])) {
2517 Success = false;
2518 Diags.Report(diag::err_drv_invalid_value) << "-verify=" << Prefix;
2519 Diags.Report(diag::note_drv_verify_prefix_spelling);
2520 }
2521 }
2522 return Success;
2523}
2524
2526 ArgumentConsumer Consumer) {
2527 const FileSystemOptions &FileSystemOpts = Opts;
2528
2529#define FILE_SYSTEM_OPTION_WITH_MARSHALLING(...) \
2530 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
2531#include "clang/Options/Options.inc"
2532#undef FILE_SYSTEM_OPTION_WITH_MARSHALLING
2533}
2534
2535static bool ParseFileSystemArgs(FileSystemOptions &Opts, const ArgList &Args,
2536 DiagnosticsEngine &Diags) {
2537 unsigned NumErrorsBefore = Diags.getNumErrors();
2538
2539 FileSystemOptions &FileSystemOpts = Opts;
2540
2541#define FILE_SYSTEM_OPTION_WITH_MARSHALLING(...) \
2542 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
2543#include "clang/Options/Options.inc"
2544#undef FILE_SYSTEM_OPTION_WITH_MARSHALLING
2545
2546 return Diags.getNumErrors() == NumErrorsBefore;
2547}
2548
2550 ArgumentConsumer Consumer) {
2551 const MigratorOptions &MigratorOpts = Opts;
2552#define MIGRATOR_OPTION_WITH_MARSHALLING(...) \
2553 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
2554#include "clang/Options/Options.inc"
2555#undef MIGRATOR_OPTION_WITH_MARSHALLING
2556}
2557
2558static bool ParseMigratorArgs(MigratorOptions &Opts, const ArgList &Args,
2559 DiagnosticsEngine &Diags) {
2560 unsigned NumErrorsBefore = Diags.getNumErrors();
2561
2562 MigratorOptions &MigratorOpts = Opts;
2563
2564#define MIGRATOR_OPTION_WITH_MARSHALLING(...) \
2565 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
2566#include "clang/Options/Options.inc"
2567#undef MIGRATOR_OPTION_WITH_MARSHALLING
2568
2569 return Diags.getNumErrors() == NumErrorsBefore;
2570}
2571
2572void CompilerInvocationBase::GenerateDiagnosticArgs(
2573 const DiagnosticOptions &Opts, ArgumentConsumer Consumer,
2574 bool DefaultDiagColor) {
2575 const DiagnosticOptions *DiagnosticOpts = &Opts;
2576#define DIAG_OPTION_WITH_MARSHALLING(...) \
2577 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
2578#include "clang/Options/Options.inc"
2579#undef DIAG_OPTION_WITH_MARSHALLING
2580
2581 if (!Opts.DiagnosticSerializationFile.empty())
2582 GenerateArg(Consumer, OPT_diagnostic_serialized_file,
2584
2585 switch (Opts.getShowColors()) {
2586 case ShowColorsKind::On:
2587 GenerateArg(Consumer, OPT_fcolor_diagnostics);
2588 break;
2590 GenerateArg(Consumer, OPT_fno_color_diagnostics);
2591 break;
2593 break;
2594 }
2595
2596 if (Opts.VerifyDiagnostics &&
2597 llvm::is_contained(Opts.VerifyPrefixes, "expected"))
2598 GenerateArg(Consumer, OPT_verify);
2599
2600 for (const auto &Prefix : Opts.VerifyPrefixes)
2601 if (Prefix != "expected")
2602 GenerateArg(Consumer, OPT_verify_EQ, Prefix);
2603
2604 if (Opts.VerifyDirectives) {
2605 GenerateArg(Consumer, OPT_verify_directives);
2606 }
2607
2608 DiagnosticLevelMask VIU = Opts.getVerifyIgnoreUnexpected();
2609 if (VIU == DiagnosticLevelMask::None) {
2610 // This is the default, don't generate anything.
2611 } else if (VIU == DiagnosticLevelMask::All) {
2612 GenerateArg(Consumer, OPT_verify_ignore_unexpected);
2613 } else {
2614 if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Note) != 0)
2615 GenerateArg(Consumer, OPT_verify_ignore_unexpected_EQ, "note");
2616 if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Remark) != 0)
2617 GenerateArg(Consumer, OPT_verify_ignore_unexpected_EQ, "remark");
2618 if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Warning) != 0)
2619 GenerateArg(Consumer, OPT_verify_ignore_unexpected_EQ, "warning");
2620 if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Error) != 0)
2621 GenerateArg(Consumer, OPT_verify_ignore_unexpected_EQ, "error");
2622 }
2623
2624 for (const auto &Warning : Opts.Warnings) {
2625 // This option is automatically generated from UndefPrefixes.
2626 if (Warning == "undef-prefix")
2627 continue;
2628 // This option is automatically generated from CheckConstexprFunctionBodies.
2629 if (Warning == "invalid-constexpr" || Warning == "no-invalid-constexpr")
2630 continue;
2631 Consumer(StringRef("-W") + Warning);
2632 }
2633
2634 for (const auto &Remark : Opts.Remarks) {
2635 // These arguments are generated from OptimizationRemark fields of
2636 // CodeGenOptions.
2637 StringRef IgnoredRemarks[] = {"pass", "no-pass",
2638 "pass-analysis", "no-pass-analysis",
2639 "pass-missed", "no-pass-missed"};
2640 if (llvm::is_contained(IgnoredRemarks, Remark))
2641 continue;
2642
2643 Consumer(StringRef("-R") + Remark);
2644 }
2645
2646 if (!Opts.DiagnosticSuppressionMappingsFile.empty()) {
2647 GenerateArg(Consumer, OPT_warning_suppression_mappings_EQ,
2649 }
2650}
2651
2652std::unique_ptr<DiagnosticOptions>
2654 auto DiagOpts = std::make_unique<DiagnosticOptions>();
2655 unsigned MissingArgIndex, MissingArgCount;
2656 InputArgList Args = getDriverOptTable().ParseArgs(
2657 Argv.slice(1), MissingArgIndex, MissingArgCount);
2658
2659 bool ShowColors = true;
2660 if (std::optional<std::string> NoColor =
2661 llvm::sys::Process::GetEnv("NO_COLOR");
2662 NoColor && !NoColor->empty()) {
2663 // If the user set the NO_COLOR environment variable, we'll honor that
2664 // unless the command line overrides it.
2665 ShowColors = false;
2666 }
2667
2668 // We ignore MissingArgCount and the return value of ParseDiagnosticArgs.
2669 // Any errors that would be diagnosed here will also be diagnosed later,
2670 // when the DiagnosticsEngine actually exists.
2671 (void)ParseDiagnosticArgs(*DiagOpts, Args, /*Diags=*/nullptr, ShowColors);
2672 return DiagOpts;
2673}
2674
2675bool clang::ParseDiagnosticArgs(DiagnosticOptions &Opts, ArgList &Args,
2676 DiagnosticsEngine *Diags,
2677 bool DefaultDiagColor) {
2678 std::optional<DiagnosticOptions> IgnoringDiagOpts;
2679 std::optional<DiagnosticsEngine> IgnoringDiags;
2680 if (!Diags) {
2681 IgnoringDiagOpts.emplace();
2682 IgnoringDiags.emplace(DiagnosticIDs::create(), *IgnoringDiagOpts,
2683 new IgnoringDiagConsumer());
2684 Diags = &*IgnoringDiags;
2685 }
2686
2687 unsigned NumErrorsBefore = Diags->getNumErrors();
2688
2689 // The key paths of diagnostic options defined in Options.td start with
2690 // "DiagnosticOpts->". Let's provide the expected variable name and type.
2691 DiagnosticOptions *DiagnosticOpts = &Opts;
2692
2693#define DIAG_OPTION_WITH_MARSHALLING(...) \
2694 PARSE_OPTION_WITH_MARSHALLING(Args, *Diags, __VA_ARGS__)
2695#include "clang/Options/Options.inc"
2696#undef DIAG_OPTION_WITH_MARSHALLING
2697
2698 llvm::sys::Process::UseANSIEscapeCodes(Opts.UseANSIEscapeCodes);
2699
2700 if (Arg *A =
2701 Args.getLastArg(OPT_diagnostic_serialized_file, OPT__serialize_diags))
2702 Opts.DiagnosticSerializationFile = A->getValue();
2703 Opts.setShowColors(parseShowColorsMode(Args, DefaultDiagColor));
2704
2705 Opts.VerifyDiagnostics = Args.hasArg(OPT_verify) || Args.hasArg(OPT_verify_EQ);
2706 Opts.VerifyDirectives = Args.hasArg(OPT_verify_directives);
2707 Opts.VerifyPrefixes = Args.getAllArgValues(OPT_verify_EQ);
2708 if (Args.hasArg(OPT_verify))
2709 Opts.VerifyPrefixes.push_back("expected");
2710 // Keep VerifyPrefixes in its original order for the sake of diagnostics, and
2711 // then sort it to prepare for fast lookup using std::binary_search.
2712 if (!checkVerifyPrefixes(Opts.VerifyPrefixes, *Diags))
2713 Opts.VerifyDiagnostics = false;
2714 else
2715 llvm::sort(Opts.VerifyPrefixes);
2718 "-verify-ignore-unexpected=",
2719 Args.getAllArgValues(OPT_verify_ignore_unexpected_EQ), *Diags, DiagMask);
2720 if (Args.hasArg(OPT_verify_ignore_unexpected))
2721 DiagMask = DiagnosticLevelMask::All;
2722 Opts.setVerifyIgnoreUnexpected(DiagMask);
2723 if (Opts.TabStop == 0 || Opts.TabStop > DiagnosticOptions::MaxTabStop) {
2724 Diags->Report(diag::warn_ignoring_ftabstop_value)
2725 << Opts.TabStop << DiagnosticOptions::DefaultTabStop;
2726 Opts.TabStop = DiagnosticOptions::DefaultTabStop;
2727 }
2728
2729 if (const Arg *A = Args.getLastArg(OPT_warning_suppression_mappings_EQ))
2730 Opts.DiagnosticSuppressionMappingsFile = A->getValue();
2731
2732 addDiagnosticArgs(Args, OPT_W_Group, OPT_W_value_Group, Opts.Warnings);
2733 addDiagnosticArgs(Args, OPT_R_Group, OPT_R_value_Group, Opts.Remarks);
2734
2735 return Diags->getNumErrors() == NumErrorsBefore;
2736}
2737
2738unsigned clang::getOptimizationLevel(const ArgList &Args, InputKind IK,
2739 DiagnosticsEngine &Diags) {
2740 unsigned DefaultOpt = 0;
2741 if ((IK.getLanguage() == Language::OpenCL ||
2743 !Args.hasArg(OPT_cl_opt_disable))
2744 DefaultOpt = 2;
2745
2746 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
2747 if (A->getOption().matches(options::OPT_O0))
2748 return 0;
2749
2750 if (A->getOption().matches(options::OPT_Ofast) ||
2751 A->getOption().matches(options::OPT_O4))
2752 return 3;
2753
2754 assert(A->getOption().matches(options::OPT_O));
2755
2756 StringRef S(A->getValue());
2757 if (S == "s" || S == "z")
2758 return 2;
2759
2760 if (S == "g")
2761 return 1;
2762
2763 DefaultOpt = getLastArgIntValue(Args, OPT_O, DefaultOpt, Diags);
2764 }
2765
2766 unsigned MaxOptLevel = 3;
2767 if (DefaultOpt > MaxOptLevel) {
2768 // If the optimization level is not supported, fall back on the default
2769 // optimization
2770 Diags.Report(diag::warn_drv_optimization_value)
2771 << Args.getLastArg(OPT_O)->getAsString(Args) << "-O" << MaxOptLevel;
2772 DefaultOpt = MaxOptLevel;
2773 }
2774
2775 return DefaultOpt;
2776}
2777
2778unsigned clang::getOptimizationLevelSize(const ArgList &Args) {
2779 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
2780 if (A->getOption().matches(options::OPT_O)) {
2781 switch (A->getValue()[0]) {
2782 default:
2783 return 0;
2784 case 's':
2785 return 1;
2786 case 'z':
2787 return 2;
2788 }
2789 }
2790 }
2791 return 0;
2792}
2793
2794/// Parse the argument to the -ftest-module-file-extension
2795/// command-line argument.
2796///
2797/// \returns true on error, false on success.
2798static bool parseTestModuleFileExtensionArg(StringRef Arg,
2799 std::string &BlockName,
2800 unsigned &MajorVersion,
2801 unsigned &MinorVersion,
2802 bool &Hashed,
2803 std::string &UserInfo) {
2805 Arg.split(Args, ':', 5);
2806 if (Args.size() < 5)
2807 return true;
2808
2809 BlockName = std::string(Args[0]);
2810 if (Args[1].getAsInteger(10, MajorVersion)) return true;
2811 if (Args[2].getAsInteger(10, MinorVersion)) return true;
2812 if (Args[3].getAsInteger(2, Hashed)) return true;
2813 if (Args.size() > 4)
2814 UserInfo = std::string(Args[4]);
2815 return false;
2816}
2817
2818/// Return a table that associates command line option specifiers with the
2819/// frontend action. Note: The pair {frontend::PluginAction, OPT_plugin} is
2820/// intentionally missing, as this case is handled separately from other
2821/// frontend options.
2822static const auto &getFrontendActionTable() {
2823 static const std::pair<frontend::ActionKind, unsigned> Table[] = {
2824 {frontend::ASTDeclList, OPT_ast_list},
2825
2826 {frontend::ASTDump, OPT_ast_dump_all_EQ},
2827 {frontend::ASTDump, OPT_ast_dump_all},
2828 {frontend::ASTDump, OPT_ast_dump_EQ},
2829 {frontend::ASTDump, OPT_ast_dump},
2830 {frontend::ASTDump, OPT_ast_dump_lookups},
2831 {frontend::ASTDump, OPT_ast_dump_decl_types},
2832
2833 {frontend::ASTPrint, OPT_ast_print},
2834 {frontend::ASTView, OPT_ast_view},
2835 {frontend::DumpCompilerOptions, OPT_compiler_options_dump},
2836 {frontend::DumpRawTokens, OPT_dump_raw_tokens},
2837 {frontend::DumpTokens, OPT_dump_tokens},
2838 {frontend::EmitAssembly, OPT_S},
2839 {frontend::EmitBC, OPT_emit_llvm_bc},
2840 {frontend::EmitCIR, OPT_emit_cir},
2841 {frontend::EmitCIR, OPT_emit_cir_EQ},
2842 {frontend::EmitCIRBC, OPT_emit_cir_bc},
2843 {frontend::EmitHTML, OPT_emit_html},
2844 {frontend::EmitLLVM, OPT_emit_llvm},
2845 {frontend::EmitLLVMOnly, OPT_emit_llvm_only},
2846 {frontend::EmitCodeGenOnly, OPT_emit_codegen_only},
2847 {frontend::EmitObj, OPT_emit_obj},
2848 {frontend::ExtractAPI, OPT_extract_api},
2849
2850 {frontend::FixIt, OPT_fixit_EQ},
2851 {frontend::FixIt, OPT_fixit},
2852
2853 {frontend::GenerateModule, OPT_emit_module},
2854 {frontend::GenerateModuleInterface, OPT_emit_module_interface},
2856 OPT_emit_reduced_module_interface},
2857 {frontend::GenerateHeaderUnit, OPT_emit_header_unit},
2858 {frontend::GeneratePCH, OPT_emit_pch},
2859 {frontend::GenerateInterfaceStubs, OPT_emit_interface_stubs},
2860 {frontend::InitOnly, OPT_init_only},
2861 {frontend::ParseSyntaxOnly, OPT_fsyntax_only},
2862 {frontend::ModuleFileInfo, OPT_module_file_info},
2863 {frontend::VerifyPCH, OPT_verify_pch},
2864 {frontend::PrintPreamble, OPT_print_preamble},
2866 {frontend::RewriteMacros, OPT_rewrite_macros},
2867 {frontend::RewriteObjC, OPT_rewrite_objc},
2868 {frontend::RewriteTest, OPT_rewrite_test},
2869 {frontend::RunAnalysis, OPT_analyze},
2870 {frontend::RunPreprocessorOnly, OPT_Eonly},
2872 OPT_print_dependency_directives_minimized_source},
2873 };
2874
2875 return Table;
2876}
2877
2878/// Maps command line option to frontend action.
2879static std::optional<frontend::ActionKind>
2880getFrontendAction(OptSpecifier &Opt) {
2881 for (const auto &ActionOpt : getFrontendActionTable())
2882 if (ActionOpt.second == Opt.getID())
2883 return ActionOpt.first;
2884
2885 return std::nullopt;
2886}
2887
2888/// Maps frontend action to command line option.
2889static std::optional<OptSpecifier>
2891 for (const auto &ActionOpt : getFrontendActionTable())
2892 if (ActionOpt.first == ProgramAction)
2893 return OptSpecifier(ActionOpt.second);
2894
2895 return std::nullopt;
2896}
2897
2899 ArgumentConsumer Consumer, bool IsHeader) {
2900 const FrontendOptions &FrontendOpts = Opts;
2901#define FRONTEND_OPTION_WITH_MARSHALLING(...) \
2902 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
2903#include "clang/Options/Options.inc"
2904#undef FRONTEND_OPTION_WITH_MARSHALLING
2905
2906 std::optional<OptSpecifier> ProgramActionOpt =
2908
2909 // Generating a simple flag covers most frontend actions.
2910 std::function<void()> GenerateProgramAction = [&]() {
2911 GenerateArg(Consumer, *ProgramActionOpt);
2912 };
2913
2914 if (!ProgramActionOpt) {
2915 // PluginAction is the only program action handled separately.
2916 assert(Opts.ProgramAction == frontend::PluginAction &&
2917 "Frontend action without option.");
2918 GenerateProgramAction = [&]() {
2919 GenerateArg(Consumer, OPT_plugin, Opts.ActionName);
2920 };
2921 }
2922
2923 // FIXME: Simplify the complex 'AST dump' command line.
2924 if (Opts.ProgramAction == frontend::ASTDump) {
2925 GenerateProgramAction = [&]() {
2926 // ASTDumpLookups, ASTDumpDeclTypes and ASTDumpFilter are generated via
2927 // marshalling infrastructure.
2928
2929 if (Opts.ASTDumpFormat != ADOF_Default) {
2930 StringRef Format;
2931 switch (Opts.ASTDumpFormat) {
2932 case ADOF_Default:
2933 llvm_unreachable("Default AST dump format.");
2934 case ADOF_JSON:
2935 Format = "json";
2936 break;
2937 }
2938
2939 if (Opts.ASTDumpAll)
2940 GenerateArg(Consumer, OPT_ast_dump_all_EQ, Format);
2941 if (Opts.ASTDumpDecls)
2942 GenerateArg(Consumer, OPT_ast_dump_EQ, Format);
2943 } else {
2944 if (Opts.ASTDumpAll)
2945 GenerateArg(Consumer, OPT_ast_dump_all);
2946 if (Opts.ASTDumpDecls)
2947 GenerateArg(Consumer, OPT_ast_dump);
2948 }
2949 };
2950 }
2951
2952 if (Opts.ProgramAction == frontend::FixIt && !Opts.FixItSuffix.empty()) {
2953 GenerateProgramAction = [&]() {
2954 GenerateArg(Consumer, OPT_fixit_EQ, Opts.FixItSuffix);
2955 };
2956 }
2957
2958 GenerateProgramAction();
2959
2960 for (const auto &PluginArgs : Opts.PluginArgs) {
2961 Option Opt = getDriverOptTable().getOption(OPT_plugin_arg);
2962 for (const auto &PluginArg : PluginArgs.second)
2963 denormalizeString(Consumer,
2964 Opt.getPrefix() + Opt.getName() + PluginArgs.first,
2965 Opt.getKind(), 0, PluginArg);
2966 }
2967
2968 for (const auto &Ext : Opts.ModuleFileExtensions)
2969 if (auto *TestExt = dyn_cast_or_null<TestModuleFileExtension>(Ext.get()))
2970 GenerateArg(Consumer, OPT_ftest_module_file_extension_EQ, TestExt->str());
2971
2972 if (!Opts.CodeCompletionAt.FileName.empty())
2973 GenerateArg(Consumer, OPT_code_completion_at,
2974 Opts.CodeCompletionAt.ToString());
2975
2976 for (const auto &Plugin : Opts.Plugins)
2977 GenerateArg(Consumer, OPT_load, Plugin);
2978
2979 // ASTDumpDecls and ASTDumpAll already handled with ProgramAction.
2980
2981 for (const auto &ModuleFile : Opts.ModuleFiles)
2982 GenerateArg(Consumer, OPT_fmodule_file, ModuleFile);
2983
2984 if (Opts.AuxTargetCPU)
2985 GenerateArg(Consumer, OPT_aux_target_cpu, *Opts.AuxTargetCPU);
2986
2987 if (Opts.AuxTargetFeatures)
2988 for (const auto &Feature : *Opts.AuxTargetFeatures)
2989 GenerateArg(Consumer, OPT_aux_target_feature, Feature);
2990
2991 {
2992 StringRef Preprocessed = Opts.DashX.isPreprocessed() ? "-cpp-output" : "";
2993 StringRef ModuleMap =
2994 Opts.DashX.getFormat() == InputKind::ModuleMap ? "-module-map" : "";
2995 StringRef HeaderUnit = "";
2996 switch (Opts.DashX.getHeaderUnitKind()) {
2998 break;
3000 HeaderUnit = "-user";
3001 break;
3003 HeaderUnit = "-system";
3004 break;
3006 HeaderUnit = "-header-unit";
3007 break;
3008 }
3009 StringRef Header = IsHeader ? "-header" : "";
3010
3011 StringRef Lang;
3012 switch (Opts.DashX.getLanguage()) {
3013 case Language::C:
3014 Lang = "c";
3015 break;
3016 case Language::OpenCL:
3017 Lang = "cl";
3018 break;
3020 Lang = "clcpp";
3021 break;
3022 case Language::CUDA:
3023 Lang = "cuda";
3024 break;
3025 case Language::HIP:
3026 Lang = "hip";
3027 break;
3028 case Language::CXX:
3029 Lang = "c++";
3030 break;
3031 case Language::ObjC:
3032 Lang = "objective-c";
3033 break;
3034 case Language::ObjCXX:
3035 Lang = "objective-c++";
3036 break;
3037 case Language::Asm:
3038 Lang = "assembler-with-cpp";
3039 break;
3040 case Language::Unknown:
3041 assert(Opts.DashX.getFormat() == InputKind::Precompiled &&
3042 "Generating -x argument for unknown language (not precompiled).");
3043 Lang = "ast";
3044 break;
3045 case Language::LLVM_IR:
3046 Lang = "ir";
3047 break;
3048 case Language::HLSL:
3049 Lang = "hlsl";
3050 break;
3051 case Language::CIR:
3052 Lang = "cir";
3053 break;
3054 }
3055
3056 GenerateArg(Consumer, OPT_x,
3057 Lang + HeaderUnit + Header + ModuleMap + Preprocessed);
3058 }
3059
3060 // OPT_INPUT has a unique class, generate it directly.
3061 for (const auto &Input : Opts.Inputs)
3062 Consumer(Input.getFile());
3063}
3064
3065static bool ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args,
3066 DiagnosticsEngine &Diags, bool &IsHeaderFile) {
3067 unsigned NumErrorsBefore = Diags.getNumErrors();
3068
3069 FrontendOptions &FrontendOpts = Opts;
3070
3071#define FRONTEND_OPTION_WITH_MARSHALLING(...) \
3072 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
3073#include "clang/Options/Options.inc"
3074#undef FRONTEND_OPTION_WITH_MARSHALLING
3075
3077 if (const Arg *A = Args.getLastArg(OPT_Action_Group)) {
3078 OptSpecifier Opt = OptSpecifier(A->getOption().getID());
3079 std::optional<frontend::ActionKind> ProgramAction = getFrontendAction(Opt);
3080 assert(ProgramAction && "Option specifier not in Action_Group.");
3081
3082 if (ProgramAction == frontend::ASTDump &&
3083 (Opt == OPT_ast_dump_all_EQ || Opt == OPT_ast_dump_EQ)) {
3084 unsigned Val = llvm::StringSwitch<unsigned>(A->getValue())
3085 .CaseLower("default", ADOF_Default)
3086 .CaseLower("json", ADOF_JSON)
3087 .Default(std::numeric_limits<unsigned>::max());
3088
3089 if (Val != std::numeric_limits<unsigned>::max())
3090 Opts.ASTDumpFormat = static_cast<ASTDumpOutputFormat>(Val);
3091 else {
3092 Diags.Report(diag::err_drv_invalid_value)
3093 << A->getAsString(Args) << A->getValue();
3095 }
3096 }
3097
3098 if (Opt == OPT_emit_cir_EQ) {
3099 std::optional<bool> DisablePasses =
3100 llvm::StringSwitch<std::optional<bool>>(A->getValue())
3101 .Case("pristine", true)
3102 .Default(std::nullopt);
3103 if (DisablePasses)
3104 Opts.ClangIRDisablePasses = *DisablePasses;
3105 else
3106 Diags.Report(diag::err_drv_invalid_value)
3107 << A->getAsString(Args) << A->getValue();
3108 }
3109
3110 if (ProgramAction == frontend::FixIt && Opt == OPT_fixit_EQ)
3111 Opts.FixItSuffix = A->getValue();
3112
3113 if (ProgramAction == frontend::GenerateInterfaceStubs) {
3114 StringRef ArgStr =
3115 Args.hasArg(OPT_interface_stub_version_EQ)
3116 ? Args.getLastArgValue(OPT_interface_stub_version_EQ)
3117 : "ifs-v1";
3118 if (ArgStr == "experimental-yaml-elf-v1" ||
3119 ArgStr == "experimental-ifs-v1" || ArgStr == "experimental-ifs-v2" ||
3120 ArgStr == "experimental-tapi-elf-v1") {
3121 std::string ErrorMessage =
3122 "Invalid interface stub format: " + ArgStr.str() +
3123 " is deprecated.";
3124 Diags.Report(diag::err_drv_invalid_value)
3125 << "Must specify a valid interface stub format type, ie: "
3126 "-interface-stub-version=ifs-v1"
3127 << ErrorMessage;
3128 ProgramAction = frontend::ParseSyntaxOnly;
3129 } else if (!ArgStr.starts_with("ifs-")) {
3130 std::string ErrorMessage =
3131 "Invalid interface stub format: " + ArgStr.str() + ".";
3132 Diags.Report(diag::err_drv_invalid_value)
3133 << "Must specify a valid interface stub format type, ie: "
3134 "-interface-stub-version=ifs-v1"
3135 << ErrorMessage;
3136 ProgramAction = frontend::ParseSyntaxOnly;
3137 }
3138 }
3139
3140 Opts.ProgramAction = *ProgramAction;
3141
3142 // Catch common mistakes when multiple actions are specified for cc1 (e.g.
3143 // -S -emit-llvm means -emit-llvm while -emit-llvm -S means -S). However, to
3144 // support driver `-c -Xclang ACTION` (-cc1 -emit-llvm file -main-file-name
3145 // X ACTION), we suppress the error when the two actions are separated by
3146 // -main-file-name.
3147 //
3148 // As an exception, accept composable -ast-dump*.
3149 if (!A->getSpelling().starts_with("-ast-dump")) {
3150 const Arg *SavedAction = nullptr;
3151 for (const Arg *AA :
3152 Args.filtered(OPT_Action_Group, OPT_main_file_name)) {
3153 if (AA->getOption().matches(OPT_main_file_name)) {
3154 SavedAction = nullptr;
3155 } else if (!SavedAction) {
3156 SavedAction = AA;
3157 } else {
3158 if (!A->getOption().matches(OPT_ast_dump_EQ))
3159 Diags.Report(diag::err_fe_invalid_multiple_actions)
3160 << SavedAction->getSpelling() << A->getSpelling();
3161 break;
3162 }
3163 }
3164 }
3165 }
3166
3167 if (const Arg* A = Args.getLastArg(OPT_plugin)) {
3168 Opts.Plugins.emplace_back(A->getValue(0));
3170 Opts.ActionName = A->getValue();
3171 }
3172 for (const auto *AA : Args.filtered(OPT_plugin_arg))
3173 Opts.PluginArgs[AA->getValue(0)].emplace_back(AA->getValue(1));
3174
3175 for (const std::string &Arg :
3176 Args.getAllArgValues(OPT_ftest_module_file_extension_EQ)) {
3177 std::string BlockName;
3178 unsigned MajorVersion;
3179 unsigned MinorVersion;
3180 bool Hashed;
3181 std::string UserInfo;
3182 if (parseTestModuleFileExtensionArg(Arg, BlockName, MajorVersion,
3183 MinorVersion, Hashed, UserInfo)) {
3184 Diags.Report(diag::err_test_module_file_extension_format) << Arg;
3185
3186 continue;
3187 }
3188
3189 // Add the testing module file extension.
3190 Opts.ModuleFileExtensions.push_back(
3191 std::make_shared<TestModuleFileExtension>(
3192 BlockName, MajorVersion, MinorVersion, Hashed, UserInfo));
3193 }
3194
3195 if (const Arg *A = Args.getLastArg(OPT_code_completion_at)) {
3196 Opts.CodeCompletionAt =
3197 ParsedSourceLocation::FromString(A->getValue());
3198 if (Opts.CodeCompletionAt.FileName.empty()) {
3199 Diags.Report(diag::err_drv_invalid_value)
3200 << A->getAsString(Args) << A->getValue();
3201 Diags.Report(diag::note_command_line_code_loc_requirement);
3202 }
3203 }
3204
3205 Opts.Plugins = Args.getAllArgValues(OPT_load);
3206 Opts.ASTDumpDecls = Args.hasArg(OPT_ast_dump, OPT_ast_dump_EQ);
3207 Opts.ASTDumpAll = Args.hasArg(OPT_ast_dump_all, OPT_ast_dump_all_EQ);
3208 // Only the -fmodule-file=<file> form.
3209 for (const auto *A : Args.filtered(OPT_fmodule_file)) {
3210 StringRef Val = A->getValue();
3211 if (!Val.contains('='))
3212 Opts.ModuleFiles.push_back(std::string(Val));
3213 }
3214
3216 Diags.Report(diag::err_drv_argument_only_allowed_with) << "-fsystem-module"
3217 << "-emit-module";
3218 if (Args.hasArg(OPT_emit_cir, OPT_emit_cir_EQ, OPT_emit_cir_bc))
3219 Opts.UseClangIRPipeline = true;
3220
3221#if CLANG_ENABLE_CIR
3222 if (Args.hasArg(OPT_clangir_disable_passes))
3223 Opts.ClangIRDisablePasses = true;
3224
3225 if (Args.hasArg(OPT_clangir_disable_verifier))
3226 Opts.ClangIRDisableCIRVerifier = true;
3227
3228 if (Args.hasArg(OPT_clangir_lib_opt) || Args.hasArg(OPT_clangir_lib_opt_EQ))
3229 Opts.ClangIRLibOptEnabled = true;
3230#endif // CLANG_ENABLE_CIR
3231
3232 if (Args.hasArg(OPT_aux_target_cpu))
3233 Opts.AuxTargetCPU = std::string(Args.getLastArgValue(OPT_aux_target_cpu));
3234 if (Args.hasArg(OPT_aux_target_feature))
3235 Opts.AuxTargetFeatures = Args.getAllArgValues(OPT_aux_target_feature);
3236
3238 if (const Arg *A = Args.getLastArg(OPT_x)) {
3239 StringRef XValue = A->getValue();
3240
3241 // Parse suffixes:
3242 // '<lang>(-[{header-unit,user,system}-]header|[-module-map][-cpp-output])'.
3243 // FIXME: Supporting '<lang>-header-cpp-output' would be useful.
3244 bool Preprocessed = XValue.consume_back("-cpp-output");
3245 bool ModuleMap = XValue.consume_back("-module-map");
3246 // Detect and consume the header indicator.
3247 bool IsHeader =
3248 XValue != "precompiled-header" && XValue.consume_back("-header");
3249
3250 // If we have c++-{user,system}-header, that indicates a header unit input
3251 // likewise, if the user put -fmodule-header together with a header with an
3252 // absolute path (header-unit-header).
3254 if (IsHeader || Preprocessed) {
3255 if (XValue.consume_back("-header-unit"))
3257 else if (XValue.consume_back("-system"))
3259 else if (XValue.consume_back("-user"))
3261 }
3262
3263 // The value set by this processing is an un-preprocessed source which is
3264 // not intended to be a module map or header unit.
3265 IsHeaderFile = IsHeader && !Preprocessed && !ModuleMap &&
3267
3268 // Principal languages.
3269 DashX = llvm::StringSwitch<InputKind>(XValue)
3270 .Case("c", Language::C)
3271 .Case("cl", Language::OpenCL)
3272 .Case("clcpp", Language::OpenCLCXX)
3273 .Case("cuda", Language::CUDA)
3274 .Case("hip", Language::HIP)
3275 .Case("c++", Language::CXX)
3276 .Case("objective-c", Language::ObjC)
3277 .Case("objective-c++", Language::ObjCXX)
3278 .Case("hlsl", Language::HLSL)
3279 .Default(Language::Unknown);
3280
3281 // "objc[++]-cpp-output" is an acceptable synonym for
3282 // "objective-c[++]-cpp-output".
3283 if (DashX.isUnknown() && Preprocessed && !IsHeaderFile && !ModuleMap &&
3285 DashX = llvm::StringSwitch<InputKind>(XValue)
3286 .Case("objc", Language::ObjC)
3287 .Case("objc++", Language::ObjCXX)
3288 .Default(Language::Unknown);
3289
3290 // Some special cases cannot be combined with suffixes.
3291 if (DashX.isUnknown() && !Preprocessed && !IsHeaderFile && !ModuleMap &&
3293 DashX = llvm::StringSwitch<InputKind>(XValue)
3294 .Case("cpp-output", InputKind(Language::C).getPreprocessed())
3295 .Case("assembler-with-cpp", Language::Asm)
3296 .Cases({"ast", "pcm", "precompiled-header"},
3298 .Case("ir", Language::LLVM_IR)
3299 .Case("cir", Language::CIR)
3300 .Default(Language::Unknown);
3301
3302 if (DashX.isUnknown())
3303 Diags.Report(diag::err_drv_invalid_value)
3304 << A->getAsString(Args) << A->getValue();
3305
3306 if (Preprocessed)
3307 DashX = DashX.getPreprocessed();
3308 // A regular header is considered mutually exclusive with a header unit.
3309 if (HUK != InputKind::HeaderUnit_None) {
3310 DashX = DashX.withHeaderUnit(HUK);
3311 IsHeaderFile = true;
3312 } else if (IsHeaderFile)
3313 DashX = DashX.getHeader();
3314 if (ModuleMap)
3315 DashX = DashX.withFormat(InputKind::ModuleMap);
3316 }
3317
3318 // '-' is the default input if none is given.
3319 std::vector<std::string> Inputs = Args.getAllArgValues(OPT_INPUT);
3320 Opts.Inputs.clear();
3321 if (Inputs.empty())
3322 Inputs.push_back("-");
3323
3325 Inputs.size() > 1)
3326 Diags.Report(diag::err_drv_header_unit_extra_inputs) << Inputs[1];
3327
3328 for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
3329 InputKind IK = DashX;
3330 if (IK.isUnknown()) {
3332 StringRef(Inputs[i]).rsplit('.').second);
3333 // FIXME: Warn on this?
3334 if (IK.isUnknown())
3335 IK = Language::C;
3336 // FIXME: Remove this hack.
3337 if (i == 0)
3338 DashX = IK;
3339 }
3340
3341 bool IsSystem = false;
3342
3343 // The -emit-module action implicitly takes a module map.
3345 IK.getFormat() == InputKind::Source) {
3347 IsSystem = Opts.IsSystemModule;
3348 }
3349
3350 Opts.Inputs.emplace_back(std::move(Inputs[i]), IK, IsSystem);
3351 }
3352
3353 Opts.DashX = DashX;
3354
3355 // CIR is a source-level frontend pipeline. When the input is already LLVM IR
3356 // (e.g. during the backend phase of OpenMP offloading), the standard LLVM
3357 // backend should be used instead.
3358 if (Opts.UseClangIRPipeline && DashX.getLanguage() == Language::LLVM_IR)
3359 Opts.UseClangIRPipeline = false;
3360
3361 // Conversely, ClangIR input can only be consumed by the CIR pipeline, so it
3362 // implies -fclangir, and is an error if that pipeline is not built in.
3363 if (DashX.getLanguage() == Language::CIR) {
3364#if CLANG_ENABLE_CIR
3365 Opts.UseClangIRPipeline = true;
3366#else
3367 Diags.Report(diag::err_fe_cir_not_built);
3368#endif
3369 }
3370
3371 return Diags.getNumErrors() == NumErrorsBefore;
3372}
3373
3375 ArgumentConsumer Consumer) {
3376 const HeaderSearchOptions *HeaderSearchOpts = &Opts;
3377#define HEADER_SEARCH_OPTION_WITH_MARSHALLING(...) \
3378 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
3379#include "clang/Options/Options.inc"
3380#undef HEADER_SEARCH_OPTION_WITH_MARSHALLING
3381
3382 if (Opts.UseLibcxx)
3383 GenerateArg(Consumer, OPT_stdlib_EQ, "libc++");
3384
3385 for (const auto &File : Opts.PrebuiltModuleFiles)
3386 GenerateArg(Consumer, OPT_fmodule_file, File.first + "=" + File.second);
3387
3388 for (const auto &Path : Opts.PrebuiltModulePaths)
3389 GenerateArg(Consumer, OPT_fprebuilt_module_path, Path);
3390
3391 for (const auto &Macro : Opts.ModulesIgnoreMacros)
3392 GenerateArg(Consumer, OPT_fmodules_ignore_macro, Macro.val());
3393
3394 for (const auto &Path : Opts.ModulesIgnoreSearchPaths)
3395 GenerateArg(Consumer, OPT_fmodules_ignore_search_path, Path.val());
3396
3397 auto Matches = [](const HeaderSearchOptions::Entry &Entry,
3399 std::optional<bool> IsFramework,
3400 std::optional<bool> IgnoreSysRoot) {
3401 return llvm::is_contained(Groups, Entry.Group) &&
3402 (!IsFramework || (Entry.IsFramework == *IsFramework)) &&
3403 (!IgnoreSysRoot || (Entry.IgnoreSysRoot == *IgnoreSysRoot));
3404 };
3405
3406 auto It = Opts.UserEntries.begin();
3407 auto End = Opts.UserEntries.end();
3408
3409 // Add -I... and -F... options in order.
3410 for (; It < End && Matches(*It, {frontend::Angled}, std::nullopt, true);
3411 ++It) {
3412 OptSpecifier Opt = [It, Matches]() {
3413 if (Matches(*It, frontend::Angled, true, true))
3414 return OPT_F;
3415 if (Matches(*It, frontend::Angled, false, true))
3416 return OPT_I;
3417 llvm_unreachable("Unexpected HeaderSearchOptions::Entry.");
3418 }();
3419
3420 GenerateArg(Consumer, Opt, It->Path);
3421 }
3422
3423 // Note: some paths that came from "[-iprefix=xx] -iwithprefixbefore=yy" may
3424 // have already been generated as "-I[xx]yy". If that's the case, their
3425 // position on command line was such that this has no semantic impact on
3426 // include paths.
3427 for (; It < End &&
3428 Matches(*It, {frontend::After, frontend::Angled}, false, true);
3429 ++It) {
3430 OptSpecifier Opt =
3431 It->Group == frontend::After ? OPT_iwithprefix : OPT_iwithprefixbefore;
3432 GenerateArg(Consumer, Opt, It->Path);
3433 }
3434
3435 // Note: Some paths that came from "-idirafter=xxyy" may have already been
3436 // generated as "-iwithprefix=xxyy". If that's the case, their position on
3437 // command line was such that this has no semantic impact on include paths.
3438 for (; It < End && Matches(*It, {frontend::After}, false, true); ++It)
3439 GenerateArg(Consumer, OPT_idirafter, It->Path);
3440 for (; It < End && Matches(*It, {frontend::Quoted}, false, true); ++It)
3441 GenerateArg(Consumer, OPT_iquote, It->Path);
3442 for (; It < End && Matches(*It, {frontend::System}, false, std::nullopt);
3443 ++It)
3444 GenerateArg(Consumer, It->IgnoreSysRoot ? OPT_isystem : OPT_iwithsysroot,
3445 It->Path);
3446 for (; It < End && Matches(*It, {frontend::System}, true, true); ++It)
3447 GenerateArg(Consumer, OPT_iframework, It->Path);
3448 for (; It < End && Matches(*It, {frontend::System}, true, false); ++It)
3449 GenerateArg(Consumer, OPT_iframeworkwithsysroot, It->Path);
3450
3451 // Add the paths for the various language specific isystem flags.
3452 for (; It < End && Matches(*It, {frontend::CSystem}, false, true); ++It)
3453 GenerateArg(Consumer, OPT_c_isystem, It->Path);
3454 for (; It < End && Matches(*It, {frontend::CXXSystem}, false, true); ++It)
3455 GenerateArg(Consumer, OPT_cxx_isystem, It->Path);
3456 for (; It < End && Matches(*It, {frontend::ObjCSystem}, false, true); ++It)
3457 GenerateArg(Consumer, OPT_objc_isystem, It->Path);
3458 for (; It < End && Matches(*It, {frontend::ObjCXXSystem}, false, true); ++It)
3459 GenerateArg(Consumer, OPT_objcxx_isystem, It->Path);
3460
3461 // Add the internal paths from a driver that detects standard include paths.
3462 // Note: Some paths that came from "-internal-isystem" arguments may have
3463 // already been generated as "-isystem". If that's the case, their position on
3464 // command line was such that this has no semantic impact on include paths.
3465 for (; It < End &&
3466 Matches(*It, {frontend::System, frontend::ExternCSystem}, false, true);
3467 ++It) {
3468 OptSpecifier Opt = It->Group == frontend::System
3469 ? OPT_internal_isystem
3470 : OPT_internal_externc_isystem;
3471 GenerateArg(Consumer, Opt, It->Path);
3472 }
3473 for (; It < End && Matches(*It, {frontend::System}, true, true); ++It)
3474 GenerateArg(Consumer, OPT_internal_iframework, It->Path);
3475
3476 assert(It == End && "Unhandled HeaderSearchOption::Entry.");
3477
3478 // Add the path prefixes which are implicitly treated as being system headers.
3479 for (const auto &P : Opts.SystemHeaderPrefixes) {
3480 OptSpecifier Opt = P.IsSystemHeader ? OPT_system_header_prefix
3481 : OPT_no_system_header_prefix;
3482 GenerateArg(Consumer, Opt, P.Prefix);
3483 }
3484
3485 for (const std::string &F : Opts.VFSOverlayFiles)
3486 GenerateArg(Consumer, OPT_ivfsoverlay, F);
3487}
3488
3489static bool ParseHeaderSearchArgs(HeaderSearchOptions &Opts, ArgList &Args,
3490 DiagnosticsEngine &Diags) {
3491 unsigned NumErrorsBefore = Diags.getNumErrors();
3492
3493 HeaderSearchOptions *HeaderSearchOpts = &Opts;
3494
3495#define HEADER_SEARCH_OPTION_WITH_MARSHALLING(...) \
3496 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
3497#include "clang/Options/Options.inc"
3498#undef HEADER_SEARCH_OPTION_WITH_MARSHALLING
3499
3500 if (const Arg *A = Args.getLastArg(OPT_stdlib_EQ))
3501 Opts.UseLibcxx = (strcmp(A->getValue(), "libc++") == 0);
3502
3503 // Only the -fmodule-file=<name>=<file> form.
3504 for (const auto *A : Args.filtered(OPT_fmodule_file)) {
3505 StringRef Val = A->getValue();
3506 if (Val.contains('=')) {
3507 auto Split = Val.split('=');
3508 Opts.PrebuiltModuleFiles.insert_or_assign(
3509 std::string(Split.first), std::string(Split.second));
3510 }
3511 }
3512 for (const auto *A : Args.filtered(OPT_fprebuilt_module_path))
3513 Opts.AddPrebuiltModulePath(A->getValue());
3514
3515 for (const auto *A : Args.filtered(OPT_fmodules_ignore_macro)) {
3516 StringRef MacroDef = A->getValue();
3517 Opts.ModulesIgnoreMacros.insert(
3518 llvm::CachedHashString(MacroDef.split('=').first));
3519 }
3520
3521 for (const auto *A : Args.filtered(OPT_fmodules_ignore_search_path))
3522 Opts.ModulesIgnoreSearchPaths.insert(llvm::CachedHashString(A->getValue()));
3523
3524 // Add -I... and -F... options in order.
3525 bool IsSysrootSpecified =
3526 Args.hasArg(OPT__sysroot_EQ) || Args.hasArg(OPT_isysroot);
3527
3528 // Expand a leading `=` to the sysroot if one was passed (and it's not a
3529 // framework flag).
3530 auto PrefixHeaderPath = [IsSysrootSpecified,
3531 &Opts](const llvm::opt::Arg *A,
3532 bool IsFramework = false) -> std::string {
3533 assert(A->getNumValues() && "Unexpected empty search path flag!");
3534 if (IsSysrootSpecified && !IsFramework && A->getValue()[0] == '=') {
3535 SmallString<32> Buffer;
3536 llvm::sys::path::append(Buffer, Opts.Sysroot,
3537 llvm::StringRef(A->getValue()).substr(1));
3538 return std::string(Buffer);
3539 }
3540 return A->getValue();
3541 };
3542
3543 for (const auto *A : Args.filtered(OPT_I, OPT_F)) {
3544 bool IsFramework = A->getOption().matches(OPT_F);
3545 Opts.AddPath(PrefixHeaderPath(A, IsFramework), frontend::Angled,
3546 IsFramework, /*IgnoreSysroot=*/true);
3547 }
3548
3549 // Add -iprefix/-iwithprefix/-iwithprefixbefore options.
3550 StringRef Prefix = ""; // FIXME: This isn't the correct default prefix.
3551 for (const auto *A :
3552 Args.filtered(OPT_iprefix, OPT_iwithprefix, OPT_iwithprefixbefore)) {
3553 if (A->getOption().matches(OPT_iprefix))
3554 Prefix = A->getValue();
3555 else if (A->getOption().matches(OPT_iwithprefix))
3556 Opts.AddPath(Prefix.str() + A->getValue(), frontend::After, false, true);
3557 else
3558 Opts.AddPath(Prefix.str() + A->getValue(), frontend::Angled, false, true);
3559 }
3560
3561 for (const auto *A : Args.filtered(OPT_idirafter))
3562 Opts.AddPath(PrefixHeaderPath(A), frontend::After, false, true);
3563 for (const auto *A : Args.filtered(OPT_iquote))
3564 Opts.AddPath(PrefixHeaderPath(A), frontend::Quoted, false, true);
3565
3566 for (const auto *A : Args.filtered(OPT_isystem, OPT_iwithsysroot)) {
3567 if (A->getOption().matches(OPT_iwithsysroot)) {
3568 Opts.AddPath(A->getValue(), frontend::System, false,
3569 /*IgnoreSysRoot=*/false);
3570 continue;
3571 }
3572 Opts.AddPath(PrefixHeaderPath(A), frontend::System, false, true);
3573 }
3574 for (const auto *A : Args.filtered(OPT_iframework))
3575 Opts.AddPath(A->getValue(), frontend::System, true, true);
3576 for (const auto *A : Args.filtered(OPT_iframeworkwithsysroot))
3577 Opts.AddPath(A->getValue(), frontend::System, /*IsFramework=*/true,
3578 /*IgnoreSysRoot=*/false);
3579
3580 // Add the paths for the various language specific isystem flags.
3581 for (const auto *A : Args.filtered(OPT_c_isystem))
3582 Opts.AddPath(A->getValue(), frontend::CSystem, false, true);
3583 for (const auto *A : Args.filtered(OPT_cxx_isystem))
3584 Opts.AddPath(A->getValue(), frontend::CXXSystem, false, true);
3585 for (const auto *A : Args.filtered(OPT_objc_isystem))
3586 Opts.AddPath(A->getValue(), frontend::ObjCSystem, false,true);
3587 for (const auto *A : Args.filtered(OPT_objcxx_isystem))
3588 Opts.AddPath(A->getValue(), frontend::ObjCXXSystem, false, true);
3589
3590 // Add the internal paths from a driver that detects standard include paths.
3591 for (const auto *A :
3592 Args.filtered(OPT_internal_isystem, OPT_internal_externc_isystem)) {
3594 if (A->getOption().matches(OPT_internal_externc_isystem))
3596 Opts.AddPath(A->getValue(), Group, false, true);
3597 }
3598 for (const auto *A : Args.filtered(OPT_internal_iframework))
3599 Opts.AddPath(A->getValue(), frontend::System, true, true);
3600
3601 // Add the path prefixes which are implicitly treated as being system headers.
3602 for (const auto *A :
3603 Args.filtered(OPT_system_header_prefix, OPT_no_system_header_prefix))
3605 A->getValue(), A->getOption().matches(OPT_system_header_prefix));
3606
3607 for (const auto *A : Args.filtered(OPT_ivfsoverlay, OPT_vfsoverlay))
3608 Opts.AddVFSOverlayFile(A->getValue());
3609
3610 return Diags.getNumErrors() == NumErrorsBefore;
3611}
3612
3614 ArgumentConsumer Consumer) {
3615 if (!Opts.SwiftVersion.empty())
3616 GenerateArg(Consumer, OPT_fapinotes_swift_version,
3617 Opts.SwiftVersion.getAsString());
3618
3619 for (const auto &Path : Opts.ModuleSearchPaths)
3620 GenerateArg(Consumer, OPT_iapinotes_modules, Path);
3621}
3622
3623static void ParseAPINotesArgs(APINotesOptions &Opts, ArgList &Args,
3624 DiagnosticsEngine &diags) {
3625 if (const Arg *A = Args.getLastArg(OPT_fapinotes_swift_version)) {
3626 if (Opts.SwiftVersion.tryParse(A->getValue()))
3627 diags.Report(diag::err_drv_invalid_value)
3628 << A->getAsString(Args) << A->getValue();
3629 }
3630 for (const Arg *A : Args.filtered(OPT_iapinotes_modules))
3631 Opts.ModuleSearchPaths.push_back(A->getValue());
3632}
3633
3634static void GeneratePointerAuthArgs(const LangOptions &Opts,
3635 ArgumentConsumer Consumer) {
3636 if (Opts.PointerAuthIntrinsics)
3637 GenerateArg(Consumer, OPT_fptrauth_intrinsics);
3638 if (Opts.PointerAuthCalls)
3639 GenerateArg(Consumer, OPT_fptrauth_calls);
3640 if (Opts.PointerAuthReturns)
3641 GenerateArg(Consumer, OPT_fptrauth_returns);
3642 if (Opts.PointerAuthIndirectGotos)
3643 GenerateArg(Consumer, OPT_fptrauth_indirect_gotos);
3644 if (Opts.PointerAuthAuthTraps)
3645 GenerateArg(Consumer, OPT_fptrauth_auth_traps);
3646 if (Opts.PointerAuthVTPtrAddressDiscrimination)
3647 GenerateArg(Consumer, OPT_fptrauth_vtable_pointer_address_discrimination);
3648 if (Opts.PointerAuthVTPtrTypeDiscrimination)
3649 GenerateArg(Consumer, OPT_fptrauth_vtable_pointer_type_discrimination);
3650 if (Opts.PointerAuthVTTVTPtrDiscrimination)
3651 GenerateArg(Consumer, OPT_fptrauth_vtt_vtable_pointer_discrimination);
3652 if (Opts.PointerAuthTypeInfoVTPtrDiscrimination)
3653 GenerateArg(Consumer, OPT_fptrauth_type_info_vtable_pointer_discrimination);
3654 if (Opts.PointerAuthFunctionTypeDiscrimination)
3655 GenerateArg(Consumer, OPT_fptrauth_function_pointer_type_discrimination);
3656 if (Opts.PointerAuthInitFini)
3657 GenerateArg(Consumer, OPT_fptrauth_init_fini);
3658 if (Opts.PointerAuthInitFiniAddressDiscrimination)
3659 GenerateArg(Consumer, OPT_fptrauth_init_fini_address_discrimination);
3660 if (Opts.PointerAuthELFGOT)
3661 GenerateArg(Consumer, OPT_fptrauth_elf_got);
3662 if (Opts.AArch64JumpTableHardening)
3663 GenerateArg(Consumer, OPT_faarch64_jump_table_hardening);
3664 if (Opts.PointerAuthObjcIsa)
3665 GenerateArg(Consumer, OPT_fptrauth_objc_isa);
3666 if (Opts.PointerAuthObjcInterfaceSel)
3667 GenerateArg(Consumer, OPT_fptrauth_objc_interface_sel);
3668 if (Opts.PointerAuthObjcClassROPointers)
3669 GenerateArg(Consumer, OPT_fptrauth_objc_class_ro);
3670 if (Opts.PointerAuthBlockDescriptorPointers)
3671 GenerateArg(Consumer, OPT_fptrauth_block_descriptor_pointers);
3672}
3673
3674static void ParsePointerAuthArgs(LangOptions &Opts, ArgList &Args,
3675 DiagnosticsEngine &Diags) {
3676 Opts.PointerAuthIntrinsics = Args.hasArg(OPT_fptrauth_intrinsics);
3677 Opts.PointerAuthCalls = Args.hasArg(OPT_fptrauth_calls);
3678 Opts.PointerAuthReturns = Args.hasArg(OPT_fptrauth_returns);
3679 Opts.PointerAuthIndirectGotos = Args.hasArg(OPT_fptrauth_indirect_gotos);
3680 Opts.PointerAuthAuthTraps = Args.hasArg(OPT_fptrauth_auth_traps);
3681 Opts.PointerAuthVTPtrAddressDiscrimination =
3682 Args.hasArg(OPT_fptrauth_vtable_pointer_address_discrimination);
3683 Opts.PointerAuthVTPtrTypeDiscrimination =
3684 Args.hasArg(OPT_fptrauth_vtable_pointer_type_discrimination);
3685 Opts.PointerAuthVTTVTPtrDiscrimination =
3686 Args.hasArg(OPT_fptrauth_vtt_vtable_pointer_discrimination);
3687 Opts.PointerAuthTypeInfoVTPtrDiscrimination =
3688 Args.hasArg(OPT_fptrauth_type_info_vtable_pointer_discrimination);
3689 Opts.PointerAuthFunctionTypeDiscrimination =
3690 Args.hasArg(OPT_fptrauth_function_pointer_type_discrimination);
3691 Opts.PointerAuthInitFini = Args.hasArg(OPT_fptrauth_init_fini);
3692 Opts.PointerAuthInitFiniAddressDiscrimination =
3693 Args.hasArg(OPT_fptrauth_init_fini_address_discrimination);
3694 Opts.PointerAuthELFGOT = Args.hasArg(OPT_fptrauth_elf_got);
3695 Opts.AArch64JumpTableHardening =
3696 Args.hasArg(OPT_faarch64_jump_table_hardening);
3697 Opts.PointerAuthBlockDescriptorPointers =
3698 Args.hasArg(OPT_fptrauth_block_descriptor_pointers);
3699 Opts.PointerAuthObjcIsa = Args.hasArg(OPT_fptrauth_objc_isa);
3700 Opts.PointerAuthObjcClassROPointers = Args.hasArg(OPT_fptrauth_objc_class_ro);
3701 Opts.PointerAuthObjcInterfaceSel =
3702 Args.hasArg(OPT_fptrauth_objc_interface_sel);
3703
3704 if (Opts.PointerAuthObjcInterfaceSel)
3705 Opts.PointerAuthObjcInterfaceSelKey =
3706 static_cast<unsigned>(PointerAuthSchema::ARM8_3Key::ASDB);
3707}
3708
3709/// Check if input file kind and language standard are compatible.
3711 const LangStandard &S) {
3712 switch (IK.getLanguage()) {
3713 case Language::Unknown:
3714 case Language::LLVM_IR:
3715 case Language::CIR:
3716 llvm_unreachable("should not parse language flags for this input");
3717
3718 case Language::C:
3719 case Language::ObjC:
3720 return S.getLanguage() == Language::C;
3721
3722 case Language::OpenCL:
3723 return S.getLanguage() == Language::OpenCL ||
3725
3727 return S.getLanguage() == Language::OpenCLCXX;
3728
3729 case Language::CXX:
3730 case Language::ObjCXX:
3731 return S.getLanguage() == Language::CXX;
3732
3733 case Language::CUDA:
3734 // FIXME: What -std= values should be permitted for CUDA compilations?
3735 return S.getLanguage() == Language::CUDA ||
3737
3738 case Language::HIP:
3739 return S.getLanguage() == Language::CXX || S.getLanguage() == Language::HIP;
3740
3741 case Language::Asm:
3742 // Accept (and ignore) all -std= values.
3743 // FIXME: The -std= value is not ignored; it affects the tokenization
3744 // and preprocessing rules if we're preprocessing this asm input.
3745 return true;
3746
3747 case Language::HLSL:
3748 return S.getLanguage() == Language::HLSL;
3749 }
3750
3751 llvm_unreachable("unexpected input language");
3752}
3753
3754/// Get language name for given input kind.
3755static StringRef GetInputKindName(InputKind IK) {
3756 switch (IK.getLanguage()) {
3757 case Language::C:
3758 return "C";
3759 case Language::ObjC:
3760 return "Objective-C";
3761 case Language::CXX:
3762 return "C++";
3763 case Language::ObjCXX:
3764 return "Objective-C++";
3765 case Language::OpenCL:
3766 return "OpenCL";
3768 return "C++ for OpenCL";
3769 case Language::CUDA:
3770 return "CUDA";
3771 case Language::HIP:
3772 return "HIP";
3773
3774 case Language::Asm:
3775 return "Asm";
3776 case Language::LLVM_IR:
3777 return "LLVM IR";
3778 case Language::CIR:
3779 return "Clang IR";
3780
3781 case Language::HLSL:
3782 return "HLSL";
3783
3784 case Language::Unknown:
3785 break;
3786 }
3787 llvm_unreachable("unknown input language");
3788}
3789
3790void CompilerInvocationBase::GenerateLangArgs(const LangOptions &Opts,
3791 ArgumentConsumer Consumer,
3792 const llvm::Triple &T,
3793 InputKind IK) {
3794 if (IK.getFormat() == InputKind::Precompiled ||
3796 IK.getLanguage() == Language::CIR) {
3797 if (Opts.ObjCAutoRefCount)
3798 GenerateArg(Consumer, OPT_fobjc_arc);
3799 if (Opts.PICLevel != 0)
3800 GenerateArg(Consumer, OPT_pic_level, Twine(Opts.PICLevel));
3801 if (Opts.PIE)
3802 GenerateArg(Consumer, OPT_pic_is_pie);
3803 for (StringRef Sanitizer : serializeSanitizerKinds(Opts.Sanitize))
3804 GenerateArg(Consumer, OPT_fsanitize_EQ, Sanitizer);
3805 for (StringRef Sanitizer :
3807 GenerateArg(Consumer, OPT_fsanitize_ignore_for_ubsan_feature_EQ,
3808 Sanitizer);
3809
3810 return;
3811 }
3812
3813 OptSpecifier StdOpt;
3814 switch (Opts.LangStd) {
3815 case LangStandard::lang_opencl10:
3816 case LangStandard::lang_opencl11:
3817 case LangStandard::lang_opencl12:
3818 case LangStandard::lang_opencl20:
3819 case LangStandard::lang_opencl30:
3820 case LangStandard::lang_openclcpp10:
3821 case LangStandard::lang_openclcpp2021:
3822 StdOpt = OPT_cl_std_EQ;
3823 break;
3824 default:
3825 StdOpt = OPT_std_EQ;
3826 break;
3827 }
3828
3829 auto LangStandard = LangStandard::getLangStandardForKind(Opts.LangStd);
3830 GenerateArg(Consumer, StdOpt, LangStandard.getName());
3831
3832 if (Opts.IncludeDefaultHeader)
3833 GenerateArg(Consumer, OPT_finclude_default_header);
3834 if (Opts.DeclareOpenCLBuiltins)
3835 GenerateArg(Consumer, OPT_fdeclare_opencl_builtins);
3836
3837 const LangOptions *LangOpts = &Opts;
3838
3839#define LANG_OPTION_WITH_MARSHALLING(...) \
3840 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
3841#include "clang/Options/Options.inc"
3842#undef LANG_OPTION_WITH_MARSHALLING
3843
3844 // The '-fcf-protection=' option is generated by CodeGenOpts generator.
3845
3846 if (Opts.ObjC) {
3847 GenerateArg(Consumer, OPT_fobjc_runtime_EQ, Opts.ObjCRuntime.getAsString());
3848
3849 if (Opts.GC == LangOptions::GCOnly)
3850 GenerateArg(Consumer, OPT_fobjc_gc_only);
3851 else if (Opts.GC == LangOptions::HybridGC)
3852 GenerateArg(Consumer, OPT_fobjc_gc);
3853 else if (Opts.ObjCAutoRefCount == 1)
3854 GenerateArg(Consumer, OPT_fobjc_arc);
3855
3856 if (Opts.ObjCWeakRuntime)
3857 GenerateArg(Consumer, OPT_fobjc_runtime_has_weak);
3858
3859 if (Opts.ObjCWeak)
3860 GenerateArg(Consumer, OPT_fobjc_weak);
3861
3862 if (Opts.ObjCSubscriptingLegacyRuntime)
3863 GenerateArg(Consumer, OPT_fobjc_subscripting_legacy_runtime);
3864 }
3865
3866 if (Opts.GNUCVersion != 0) {
3867 unsigned Major = Opts.GNUCVersion / 100 / 100;
3868 unsigned Minor = (Opts.GNUCVersion / 100) % 100;
3869 unsigned Patch = Opts.GNUCVersion % 100;
3870 GenerateArg(Consumer, OPT_fgnuc_version_EQ,
3871 Twine(Major) + "." + Twine(Minor) + "." + Twine(Patch));
3872 }
3873
3874 if (Opts.IgnoreXCOFFVisibility)
3875 GenerateArg(Consumer, OPT_mignore_xcoff_visibility);
3876
3877 if (Opts.SignedOverflowBehavior == LangOptions::SOB_Trapping) {
3878 GenerateArg(Consumer, OPT_ftrapv);
3879 GenerateArg(Consumer, OPT_ftrapv_handler, Opts.OverflowHandler);
3880 } else if (Opts.SignedOverflowBehavior == LangOptions::SOB_Defined) {
3881 if (!Opts.MSVCCompat)
3882 GenerateArg(Consumer, OPT_fwrapv);
3883 } else if (Opts.MSVCCompat) {
3884 GenerateArg(Consumer, OPT_fno_wrapv);
3885 }
3886 if (Opts.PointerOverflowDefined)
3887 GenerateArg(Consumer, OPT_fwrapv_pointer);
3888
3889 if (Opts.MSCompatibilityVersion != 0) {
3890 unsigned Major = Opts.MSCompatibilityVersion / 10000000;
3891 unsigned Minor = (Opts.MSCompatibilityVersion / 100000) % 100;
3892 unsigned Subminor = Opts.MSCompatibilityVersion % 100000;
3893 GenerateArg(Consumer, OPT_fms_compatibility_version,
3894 Twine(Major) + "." + Twine(Minor) + "." + Twine(Subminor));
3895 }
3896
3897 if ((!Opts.GNUMode && !Opts.MSVCCompat && !Opts.CPlusPlus17 && !Opts.C23) ||
3898 T.isOSzOS()) {
3899 if (!Opts.Trigraphs)
3900 GenerateArg(Consumer, OPT_fno_trigraphs);
3901 } else {
3902 if (Opts.Trigraphs)
3903 GenerateArg(Consumer, OPT_ftrigraphs);
3904 }
3905
3906 if (T.isOSzOS() && !Opts.ZOSExt)
3907 GenerateArg(Consumer, OPT_fno_zos_extensions);
3908 else if (Opts.ZOSExt)
3909 GenerateArg(Consumer, OPT_fzos_extensions);
3910
3911 if (Opts.Blocks && !(Opts.OpenCL && Opts.OpenCLVersion == 200))
3912 GenerateArg(Consumer, OPT_fblocks);
3913
3914 if (Opts.ConvergentFunctions)
3915 GenerateArg(Consumer, OPT_fconvergent_functions);
3916 else
3917 GenerateArg(Consumer, OPT_fno_convergent_functions);
3918
3919 if (Opts.NoBuiltin && !Opts.Freestanding)
3920 GenerateArg(Consumer, OPT_fno_builtin);
3921
3922 if (!Opts.NoBuiltin)
3923 for (const auto &Func : Opts.NoBuiltinFuncs)
3924 GenerateArg(Consumer, OPT_fno_builtin_, Func);
3925
3926 if (Opts.LongDoubleSize == 128)
3927 GenerateArg(Consumer, OPT_mlong_double_128);
3928 else if (Opts.LongDoubleSize == 64)
3929 GenerateArg(Consumer, OPT_mlong_double_64);
3930 else if (Opts.LongDoubleSize == 80)
3931 GenerateArg(Consumer, OPT_mlong_double_80);
3932
3933 // Not generating '-mrtd', it's just an alias for '-fdefault-calling-conv='.
3934
3935 // OpenMP was requested via '-fopenmp', not implied by '-fopenmp-simd' or
3936 // '-fopenmp-targets='.
3937 if (Opts.OpenMP && !Opts.OpenMPSimd) {
3938 GenerateArg(Consumer, OPT_fopenmp);
3939
3940 if (Opts.OpenMP != 51)
3941 GenerateArg(Consumer, OPT_fopenmp_version_EQ, Twine(Opts.OpenMP));
3942
3943 if (!Opts.OpenMPUseTLS)
3944 GenerateArg(Consumer, OPT_fnoopenmp_use_tls);
3945
3946 if (Opts.OpenMPIsTargetDevice)
3947 GenerateArg(Consumer, OPT_fopenmp_is_target_device);
3948
3949 if (Opts.OpenMPIRBuilder)
3950 GenerateArg(Consumer, OPT_fopenmp_enable_irbuilder);
3951 }
3952
3953 if (Opts.OpenMPSimd) {
3954 GenerateArg(Consumer, OPT_fopenmp_simd);
3955
3956 if (Opts.OpenMP != 51)
3957 GenerateArg(Consumer, OPT_fopenmp_version_EQ, Twine(Opts.OpenMP));
3958 }
3959
3960 if (Opts.OpenMPThreadSubscription)
3961 GenerateArg(Consumer, OPT_fopenmp_assume_threads_oversubscription);
3962
3963 if (Opts.OpenMPTeamSubscription)
3964 GenerateArg(Consumer, OPT_fopenmp_assume_teams_oversubscription);
3965
3966 if (Opts.OpenMPTargetDebug != 0)
3967 GenerateArg(Consumer, OPT_fopenmp_target_debug_EQ,
3968 Twine(Opts.OpenMPTargetDebug));
3969
3970 if (Opts.OpenMPCUDANumSMs != 0)
3971 GenerateArg(Consumer, OPT_fopenmp_cuda_number_of_sm_EQ,
3972 Twine(Opts.OpenMPCUDANumSMs));
3973
3974 if (Opts.OpenMPCUDABlocksPerSM != 0)
3975 GenerateArg(Consumer, OPT_fopenmp_cuda_blocks_per_sm_EQ,
3976 Twine(Opts.OpenMPCUDABlocksPerSM));
3977
3978 if (!Opts.OMPTargetTriples.empty()) {
3979 std::string Targets;
3980 llvm::raw_string_ostream OS(Targets);
3981 llvm::interleave(
3982 Opts.OMPTargetTriples, OS,
3983 [&OS](const llvm::Triple &T) { OS << T.str(); }, ",");
3984 GenerateArg(Consumer, OPT_offload_targets_EQ, Targets);
3985 }
3986
3987 if (Opts.OpenMPCUDAMode)
3988 GenerateArg(Consumer, OPT_fopenmp_cuda_mode);
3989
3990 if (Opts.OpenACC)
3991 GenerateArg(Consumer, OPT_fopenacc);
3992
3993 // The arguments used to set Optimize, OptimizeSize and NoInlineDefine are
3994 // generated from CodeGenOptions.
3995
3996 if (Opts.DefaultFPContractMode == LangOptions::FPM_Fast)
3997 GenerateArg(Consumer, OPT_ffp_contract, "fast");
3998 else if (Opts.DefaultFPContractMode == LangOptions::FPM_On)
3999 GenerateArg(Consumer, OPT_ffp_contract, "on");
4000 else if (Opts.DefaultFPContractMode == LangOptions::FPM_Off)
4001 GenerateArg(Consumer, OPT_ffp_contract, "off");
4002 else if (Opts.DefaultFPContractMode == LangOptions::FPM_FastHonorPragmas)
4003 GenerateArg(Consumer, OPT_ffp_contract, "fast-honor-pragmas");
4004
4005 for (StringRef Sanitizer : serializeSanitizerKinds(Opts.Sanitize))
4006 GenerateArg(Consumer, OPT_fsanitize_EQ, Sanitizer);
4007 for (StringRef Sanitizer :
4009 GenerateArg(Consumer, OPT_fsanitize_ignore_for_ubsan_feature_EQ, Sanitizer);
4010
4011 // Conflating '-fsanitize-system-ignorelist' and '-fsanitize-ignorelist'.
4012 for (const std::string &F : Opts.NoSanitizeFiles)
4013 GenerateArg(Consumer, OPT_fsanitize_ignorelist_EQ, F);
4014
4015 switch (Opts.getClangABICompat()) {
4016#define ABI_VER_MAJOR_MINOR(Major, Minor) \
4017 case LangOptions::ClangABI::Ver##Major##_##Minor: \
4018 GenerateArg(Consumer, OPT_fclang_abi_compat_EQ, #Major "." #Minor); \
4019 break;
4020#define ABI_VER_MAJOR(Major) \
4021 case LangOptions::ClangABI::Ver##Major: \
4022 GenerateArg(Consumer, OPT_fclang_abi_compat_EQ, #Major ".0"); \
4023 break;
4024#define ABI_VER_LATEST(Latest) \
4025 case LangOptions::ClangABI::Latest: \
4026 break;
4027#include "clang/Basic/ABIVersions.def"
4028 }
4029
4030 if (Opts.getSignReturnAddressScope() ==
4032 GenerateArg(Consumer, OPT_msign_return_address_EQ, "all");
4033 else if (Opts.getSignReturnAddressScope() ==
4035 GenerateArg(Consumer, OPT_msign_return_address_EQ, "non-leaf");
4036
4037 if (Opts.getSignReturnAddressKey() ==
4039 GenerateArg(Consumer, OPT_msign_return_address_key_EQ, "b_key");
4040
4041 if (Opts.CXXABI)
4042 GenerateArg(Consumer, OPT_fcxx_abi_EQ,
4044
4045 if (Opts.RelativeCXXABIVTables)
4046 GenerateArg(Consumer, OPT_fexperimental_relative_cxx_abi_vtables);
4047 else
4048 GenerateArg(Consumer, OPT_fno_experimental_relative_cxx_abi_vtables);
4049
4050 if (Opts.UseTargetPathSeparator)
4051 GenerateArg(Consumer, OPT_ffile_reproducible);
4052 else
4053 GenerateArg(Consumer, OPT_fno_file_reproducible);
4054
4055 for (const auto &MP : Opts.MacroPrefixMap)
4056 GenerateArg(Consumer, OPT_fmacro_prefix_map_EQ, MP.first + "=" + MP.second);
4057
4058 if (!Opts.RandstructSeed.empty())
4059 GenerateArg(Consumer, OPT_frandomize_layout_seed_EQ, Opts.RandstructSeed);
4060
4061 if (Opts.AllocTokenMax)
4062 GenerateArg(Consumer, OPT_falloc_token_max_EQ,
4063 std::to_string(*Opts.AllocTokenMax));
4064
4065 if (Opts.AllocTokenMode) {
4066 StringRef S = llvm::getAllocTokenModeAsString(*Opts.AllocTokenMode);
4067 GenerateArg(Consumer, OPT_falloc_token_mode_EQ, S);
4068 }
4069 // Generate args for matrix types.
4070 if (Opts.MatrixTypes) {
4071 if (Opts.getDefaultMatrixMemoryLayout() ==
4073 GenerateArg(Consumer, OPT_fmatrix_memory_layout_EQ, "column-major");
4074 if (Opts.getDefaultMatrixMemoryLayout() ==
4076 GenerateArg(Consumer, OPT_fmatrix_memory_layout_EQ, "row-major");
4077 }
4078}
4079
4080bool CompilerInvocation::ParseLangArgs(LangOptions &Opts, ArgList &Args,
4081 InputKind IK, const llvm::Triple &T,
4082 std::vector<std::string> &Includes,
4083 DiagnosticsEngine &Diags) {
4084 unsigned NumErrorsBefore = Diags.getNumErrors();
4085
4086 if (IK.getFormat() == InputKind::Precompiled ||
4088 IK.getLanguage() == Language::CIR) {
4089 // ObjCAAutoRefCount and Sanitize LangOpts are used to setup the
4090 // PassManager in BackendUtil.cpp. They need to be initialized no matter
4091 // what the input type is.
4092 if (Args.hasArg(OPT_fobjc_arc))
4093 Opts.ObjCAutoRefCount = 1;
4094 // PICLevel and PIELevel are needed during code generation and this should
4095 // be set regardless of the input type.
4096 Opts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags);
4097 Opts.PIE = Args.hasArg(OPT_pic_is_pie);
4098 parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ),
4099 Diags, Opts.Sanitize);
4101 "-fsanitize-ignore-for-ubsan-feature=",
4102 Args.getAllArgValues(OPT_fsanitize_ignore_for_ubsan_feature_EQ), Diags,
4104
4105 return Diags.getNumErrors() == NumErrorsBefore;
4106 }
4107
4108 // Other LangOpts are only initialized when the input is not AST or LLVM IR.
4109 // FIXME: Should we really be parsing this for an Language::Asm input?
4110
4111 // FIXME: Cleanup per-file based stuff.
4113 if (const Arg *A = Args.getLastArg(OPT_std_EQ)) {
4114 LangStd = LangStandard::getLangKind(A->getValue());
4115 if (LangStd == LangStandard::lang_unspecified) {
4116 Diags.Report(diag::err_drv_invalid_value)
4117 << A->getAsString(Args) << A->getValue();
4118 // Report supported standards with short description.
4119 for (unsigned KindValue = 0;
4120 KindValue != LangStandard::lang_unspecified;
4121 ++KindValue) {
4122 const LangStandard &Std = LangStandard::getLangStandardForKind(
4123 static_cast<LangStandard::Kind>(KindValue));
4124 if (IsInputCompatibleWithStandard(IK, Std)) {
4125 auto Diag = Diags.Report(diag::note_drv_use_standard);
4126 Diag << Std.getName() << Std.getDescription();
4127 unsigned NumAliases = 0;
4128#define LANGSTANDARD(id, name, lang, desc, features, version)
4129#define LANGSTANDARD_ALIAS(id, alias) \
4130 if (KindValue == LangStandard::lang_##id) ++NumAliases;
4131#define LANGSTANDARD_ALIAS_DEPR(id, alias)
4132#include "clang/Basic/LangStandards.def"
4133 Diag << NumAliases;
4134#define LANGSTANDARD(id, name, lang, desc, features, version)
4135#define LANGSTANDARD_ALIAS(id, alias) \
4136 if (KindValue == LangStandard::lang_##id) Diag << alias;
4137#define LANGSTANDARD_ALIAS_DEPR(id, alias)
4138#include "clang/Basic/LangStandards.def"
4139 }
4140 }
4141 } else {
4142 // Valid standard, check to make sure language and standard are
4143 // compatible.
4144 const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
4145 if (!IsInputCompatibleWithStandard(IK, Std)) {
4146 Diags.Report(diag::err_drv_argument_not_allowed_with)
4147 << A->getAsString(Args) << GetInputKindName(IK);
4148 }
4149 }
4150 }
4151
4152 // -cl-std only applies for OpenCL language standards.
4153 // Override the -std option in this case.
4154 if (const Arg *A = Args.getLastArg(OPT_cl_std_EQ)) {
4155 LangStandard::Kind OpenCLLangStd =
4156 llvm::StringSwitch<LangStandard::Kind>(A->getValue())
4157 .Cases({"cl", "CL"}, LangStandard::lang_opencl10)
4158 .Cases({"cl1.0", "CL1.0"}, LangStandard::lang_opencl10)
4159 .Cases({"cl1.1", "CL1.1"}, LangStandard::lang_opencl11)
4160 .Cases({"cl1.2", "CL1.2"}, LangStandard::lang_opencl12)
4161 .Cases({"cl2.0", "CL2.0"}, LangStandard::lang_opencl20)
4162 .Cases({"cl3.0", "CL3.0"}, LangStandard::lang_opencl30)
4163 .Cases({"cl3.1", "CL3.1"}, LangStandard::lang_opencl31)
4164 .Cases({"clc++", "CLC++"}, LangStandard::lang_openclcpp10)
4165 .Cases({"clc++1.0", "CLC++1.0"}, LangStandard::lang_openclcpp10)
4166 .Cases({"clc++2021", "CLC++2021"}, LangStandard::lang_openclcpp2021)
4168
4169 if (OpenCLLangStd == LangStandard::lang_unspecified) {
4170 Diags.Report(diag::err_drv_invalid_value)
4171 << A->getAsString(Args) << A->getValue();
4172 }
4173 else
4174 LangStd = OpenCLLangStd;
4175 }
4176
4177 // These need to be parsed now. They are used to set OpenCL defaults.
4178 Opts.IncludeDefaultHeader = Args.hasArg(OPT_finclude_default_header);
4179 Opts.DeclareOpenCLBuiltins = Args.hasArg(OPT_fdeclare_opencl_builtins);
4180
4181 LangOptions::setLangDefaults(Opts, IK.getLanguage(), T, Includes, LangStd);
4182
4183 // The key paths of codegen options defined in Options.td start with
4184 // "LangOpts->". Let's provide the expected variable name and type.
4185 LangOptions *LangOpts = &Opts;
4186
4187#define LANG_OPTION_WITH_MARSHALLING(...) \
4188 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
4189#include "clang/Options/Options.inc"
4190#undef LANG_OPTION_WITH_MARSHALLING
4191
4192 // "Modules semantics" (e.g. cross-translation-unit declaration merging) are
4193 // needed for both Clang (header) modules and C++20 modules, so enable them
4194 // for either.
4195 Opts.Modules = Opts.ClangModules || Opts.CPlusPlusModules;
4196
4197 if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
4198 StringRef Name = A->getValue();
4199 if (Name == "full") {
4200 Opts.CFProtectionBranch = 1;
4201 Opts.CFProtectionReturn = 1;
4202 } else if (Name == "branch") {
4203 Opts.CFProtectionBranch = 1;
4204 } else if (Name == "return") {
4205 Opts.CFProtectionReturn = 1;
4206 }
4207 }
4208
4209 if (Opts.CFProtectionBranch) {
4210 if (const Arg *A = Args.getLastArg(OPT_mcf_branch_label_scheme_EQ)) {
4211 const auto Scheme =
4212 llvm::StringSwitch<CFBranchLabelSchemeKind>(A->getValue())
4213#define CF_BRANCH_LABEL_SCHEME(Kind, FlagVal) \
4214 .Case(#FlagVal, CFBranchLabelSchemeKind::Kind)
4215#include "clang/Basic/CFProtectionOptions.def"
4217 Opts.setCFBranchLabelScheme(Scheme);
4218 }
4219 }
4220
4221 if ((Args.hasArg(OPT_fsycl_is_device) || Args.hasArg(OPT_fsycl_is_host)) &&
4222 !Args.hasArg(OPT_sycl_std_EQ)) {
4223 // If the user supplied -fsycl-is-device or -fsycl-is-host, but failed to
4224 // provide -sycl-std=, we want to default it to whatever the default SYCL
4225 // version is. I could not find a way to express this with the options
4226 // tablegen because we still want this value to be SYCL_None when the user
4227 // is not in device or host mode.
4228 Opts.setSYCLVersion(LangOptions::SYCL_Default);
4229 }
4230
4231 if (Opts.ObjC) {
4232 if (Arg *arg = Args.getLastArg(OPT_fobjc_runtime_EQ)) {
4233 StringRef value = arg->getValue();
4234 if (Opts.ObjCRuntime.tryParse(value))
4235 Diags.Report(diag::err_drv_unknown_objc_runtime) << value;
4236 }
4237
4238 if (Args.hasArg(OPT_fobjc_gc_only))
4239 Opts.setGC(LangOptions::GCOnly);
4240 else if (Args.hasArg(OPT_fobjc_gc))
4241 Opts.setGC(LangOptions::HybridGC);
4242 else if (Args.hasArg(OPT_fobjc_arc)) {
4243 Opts.ObjCAutoRefCount = 1;
4244 if (!Opts.ObjCRuntime.allowsARC())
4245 Diags.Report(diag::err_arc_unsupported_on_runtime);
4246 }
4247
4248 // ObjCWeakRuntime tracks whether the runtime supports __weak, not
4249 // whether the feature is actually enabled. This is predominantly
4250 // determined by -fobjc-runtime, but we allow it to be overridden
4251 // from the command line for testing purposes.
4252 if (Args.hasArg(OPT_fobjc_runtime_has_weak))
4253 Opts.ObjCWeakRuntime = 1;
4254 else
4255 Opts.ObjCWeakRuntime = Opts.ObjCRuntime.allowsWeak();
4256
4257 // ObjCWeak determines whether __weak is actually enabled.
4258 // Note that we allow -fno-objc-weak to disable this even in ARC mode.
4259 if (auto weakArg = Args.getLastArg(OPT_fobjc_weak, OPT_fno_objc_weak)) {
4260 if (!weakArg->getOption().matches(OPT_fobjc_weak)) {
4261 assert(!Opts.ObjCWeak);
4262 } else if (Opts.getGC() != LangOptions::NonGC) {
4263 Diags.Report(diag::err_objc_weak_with_gc);
4264 } else if (!Opts.ObjCWeakRuntime) {
4265 Diags.Report(diag::err_objc_weak_unsupported);
4266 } else {
4267 Opts.ObjCWeak = 1;
4268 }
4269 } else if (Opts.ObjCAutoRefCount) {
4270 Opts.ObjCWeak = Opts.ObjCWeakRuntime;
4271 }
4272
4273 if (Args.hasArg(OPT_fobjc_subscripting_legacy_runtime))
4274 Opts.ObjCSubscriptingLegacyRuntime =
4276 }
4277
4278 if (Arg *A = Args.getLastArg(options::OPT_fgnuc_version_EQ)) {
4279 // Check that the version has 1 to 3 components and the minor and patch
4280 // versions fit in two decimal digits.
4281 VersionTuple GNUCVer;
4282 bool Invalid = GNUCVer.tryParse(A->getValue());
4283 unsigned Major = GNUCVer.getMajor();
4284 unsigned Minor = GNUCVer.getMinor().value_or(0);
4285 unsigned Patch = GNUCVer.getSubminor().value_or(0);
4286 if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) {
4287 Diags.Report(diag::err_drv_invalid_value)
4288 << A->getAsString(Args) << A->getValue();
4289 }
4290 Opts.GNUCVersion = Major * 100 * 100 + Minor * 100 + Patch;
4291 }
4292
4293 if (T.isOSAIX() && (Args.hasArg(OPT_mignore_xcoff_visibility)))
4294 Opts.IgnoreXCOFFVisibility = 1;
4295
4296 if (Args.hasArg(OPT_ftrapv)) {
4297 Opts.setSignedOverflowBehavior(LangOptions::SOB_Trapping);
4298 // Set the handler, if one is specified.
4299 Opts.OverflowHandler =
4300 std::string(Args.getLastArgValue(OPT_ftrapv_handler));
4301 } else if (Args.hasFlag(OPT_fwrapv, OPT_fno_wrapv, Opts.MSVCCompat)) {
4302 Opts.setSignedOverflowBehavior(LangOptions::SOB_Defined);
4303 }
4304 if (Args.hasArg(OPT_fwrapv_pointer))
4305 Opts.PointerOverflowDefined = true;
4306
4307 Opts.MSCompatibilityVersion = 0;
4308 if (const Arg *A = Args.getLastArg(OPT_fms_compatibility_version)) {
4309 VersionTuple VT;
4310 if (VT.tryParse(A->getValue()))
4311 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
4312 << A->getValue();
4313 Opts.MSCompatibilityVersion = VT.getMajor() * 10000000 +
4314 VT.getMinor().value_or(0) * 100000 +
4315 VT.getSubminor().value_or(0);
4316 }
4317
4318 // Mimicking gcc's behavior, trigraphs are only enabled if -trigraphs
4319 // is specified, or -std is set to a conforming mode.
4320 // Trigraphs are disabled by default in C++17 and C23 onwards.
4321 // For z/OS, trigraphs are enabled by default (without regard to the above).
4322 Opts.Trigraphs =
4323 (!Opts.GNUMode && !Opts.MSVCCompat && !Opts.CPlusPlus17 && !Opts.C23) ||
4324 T.isOSzOS();
4325 Opts.Trigraphs =
4326 Args.hasFlag(OPT_ftrigraphs, OPT_fno_trigraphs, Opts.Trigraphs);
4327
4328 Opts.ZOSExt =
4329 Args.hasFlag(OPT_fzos_extensions, OPT_fno_zos_extensions, T.isOSzOS());
4330
4331 Opts.Blocks = Args.hasArg(OPT_fblocks) || (Opts.OpenCL
4332 && Opts.OpenCLVersion == 200);
4333
4334 bool HasConvergentOperations = Opts.isTargetDevice() || Opts.OpenCL ||
4335 Opts.HLSL || T.isAMDGPU() || T.isNVPTX();
4336 Opts.ConvergentFunctions =
4337 Args.hasFlag(OPT_fconvergent_functions, OPT_fno_convergent_functions,
4338 HasConvergentOperations);
4339
4340 Opts.NoBuiltin = Args.hasArg(OPT_fno_builtin) || Opts.Freestanding;
4341 if (!Opts.NoBuiltin)
4343 if (Arg *A = Args.getLastArg(options::OPT_LongDouble_Group)) {
4344 if (A->getOption().matches(options::OPT_mlong_double_64))
4345 Opts.LongDoubleSize = 64;
4346 else if (A->getOption().matches(options::OPT_mlong_double_80))
4347 Opts.LongDoubleSize = 80;
4348 else if (A->getOption().matches(options::OPT_mlong_double_128))
4349 Opts.LongDoubleSize = 128;
4350 else
4351 Opts.LongDoubleSize = 0;
4352 }
4353 if (Opts.FastRelaxedMath || Opts.CLUnsafeMath)
4354 Opts.setDefaultFPContractMode(LangOptions::FPM_Fast);
4355
4356 llvm::sort(Opts.ModuleFeatures);
4357
4358 // -mrtd option
4359 if (Arg *A = Args.getLastArg(OPT_mrtd)) {
4360 if (Opts.getDefaultCallingConv() != LangOptions::DCC_None)
4361 Diags.Report(diag::err_drv_argument_not_allowed_with)
4362 << A->getSpelling() << "-fdefault-calling-conv";
4363 else {
4364 switch (T.getArch()) {
4365 case llvm::Triple::x86:
4366 Opts.setDefaultCallingConv(LangOptions::DCC_StdCall);
4367 break;
4368 case llvm::Triple::m68k:
4369 Opts.setDefaultCallingConv(LangOptions::DCC_RtdCall);
4370 break;
4371 default:
4372 Diags.Report(diag::err_drv_argument_not_allowed_with)
4373 << A->getSpelling() << T.getTriple();
4374 }
4375 }
4376 }
4377
4378 // Check if -fopenmp is specified and set default version to 5.1.
4379 Opts.OpenMP = Args.hasArg(OPT_fopenmp) ? 51 : 0;
4380 // Check if -fopenmp-simd is specified.
4381 bool IsSimdSpecified =
4382 Args.hasFlag(options::OPT_fopenmp_simd, options::OPT_fno_openmp_simd,
4383 /*Default=*/false);
4384 Opts.OpenMPSimd = !Opts.OpenMP && IsSimdSpecified;
4385 Opts.OpenMPUseTLS =
4386 Opts.OpenMP && !Args.hasArg(options::OPT_fnoopenmp_use_tls);
4387 Opts.OpenMPIsTargetDevice =
4388 Opts.OpenMP && Args.hasArg(options::OPT_fopenmp_is_target_device);
4389 Opts.OpenMPIRBuilder =
4390 Opts.OpenMP && Args.hasArg(options::OPT_fopenmp_enable_irbuilder);
4391 bool IsTargetSpecified =
4392 Opts.OpenMPIsTargetDevice || Args.hasArg(options::OPT_offload_targets_EQ);
4393
4394 if (Opts.OpenMP || Opts.OpenMPSimd) {
4395 if (int Version = getLastArgIntValue(
4396 Args, OPT_fopenmp_version_EQ,
4397 (IsSimdSpecified || IsTargetSpecified) ? 51 : Opts.OpenMP, Diags))
4398 Opts.OpenMP = Version;
4399 // Provide diagnostic when a given target is not expected to be an OpenMP
4400 // device or host.
4401 if (!Opts.OpenMPIsTargetDevice) {
4402 switch (T.getArch()) {
4403 default:
4404 break;
4405 // Add unsupported host targets here:
4406 case llvm::Triple::nvptx:
4407 case llvm::Triple::nvptx64:
4408 Diags.Report(diag::err_drv_omp_host_target_not_supported) << T.str();
4409 break;
4410 }
4411 }
4412 }
4413
4414 // Set the flag to prevent the implementation from emitting device exception
4415 // handling code for those requiring so.
4416 if ((Opts.OpenMPIsTargetDevice && T.isGPU()) || Opts.OpenCLCPlusPlus) {
4417
4418 Opts.Exceptions = 0;
4419 Opts.CXXExceptions = 0;
4420 }
4421 if (Opts.OpenMPIsTargetDevice && T.isNVPTX()) {
4422 Opts.OpenMPCUDANumSMs =
4423 getLastArgIntValue(Args, options::OPT_fopenmp_cuda_number_of_sm_EQ,
4424 Opts.OpenMPCUDANumSMs, Diags);
4425 Opts.OpenMPCUDABlocksPerSM =
4426 getLastArgIntValue(Args, options::OPT_fopenmp_cuda_blocks_per_sm_EQ,
4427 Opts.OpenMPCUDABlocksPerSM, Diags);
4428 }
4429
4430 // Set the value of the debugging flag used in the new offloading device RTL.
4431 // Set either by a specific value or to a default if not specified.
4432 if (Opts.OpenMPIsTargetDevice && (Args.hasArg(OPT_fopenmp_target_debug) ||
4433 Args.hasArg(OPT_fopenmp_target_debug_EQ))) {
4434 Opts.OpenMPTargetDebug = getLastArgIntValue(
4435 Args, OPT_fopenmp_target_debug_EQ, Opts.OpenMPTargetDebug, Diags);
4436 if (!Opts.OpenMPTargetDebug && Args.hasArg(OPT_fopenmp_target_debug))
4437 Opts.OpenMPTargetDebug = 1;
4438 }
4439
4440 if (Opts.OpenMPIsTargetDevice) {
4441 if (Args.hasArg(OPT_fopenmp_assume_teams_oversubscription))
4442 Opts.OpenMPTeamSubscription = true;
4443 if (Args.hasArg(OPT_fopenmp_assume_threads_oversubscription))
4444 Opts.OpenMPThreadSubscription = true;
4445 }
4446
4447 // Get the OpenMP target triples if any.
4448 if (Arg *A = Args.getLastArg(options::OPT_offload_targets_EQ)) {
4449 enum ArchPtrSize { Arch16Bit, Arch32Bit, Arch64Bit };
4450 auto getArchPtrSize = [](const llvm::Triple &T) {
4451 if (T.isArch16Bit())
4452 return Arch16Bit;
4453 if (T.isArch32Bit())
4454 return Arch32Bit;
4455 assert(T.isArch64Bit() && "Expected 64-bit architecture");
4456 return Arch64Bit;
4457 };
4458
4459 for (unsigned i = 0; i < A->getNumValues(); ++i) {
4460 llvm::Triple TT(A->getValue(i));
4461
4462 if (TT.getArch() == llvm::Triple::UnknownArch ||
4463 !(TT.getArch() == llvm::Triple::aarch64 || TT.isPPC() ||
4464 TT.getArch() == llvm::Triple::spirv64 ||
4465 TT.getArch() == llvm::Triple::systemz ||
4466 TT.getArch() == llvm::Triple::loongarch64 ||
4467 TT.getArch() == llvm::Triple::nvptx ||
4468 TT.getArch() == llvm::Triple::nvptx64 || TT.isAMDGCN() ||
4469 TT.getArch() == llvm::Triple::x86 ||
4470 TT.getArch() == llvm::Triple::x86_64))
4471 Diags.Report(diag::err_drv_invalid_omp_target) << A->getValue(i);
4472 else if (getArchPtrSize(T) != getArchPtrSize(TT))
4473 Diags.Report(diag::err_drv_incompatible_omp_arch)
4474 << A->getValue(i) << T.str();
4475 else
4476 Opts.OMPTargetTriples.push_back(TT);
4477 }
4478 }
4479
4480 // Set CUDA mode for OpenMP target NVPTX/AMDGCN if specified in options
4481 Opts.OpenMPCUDAMode = Opts.OpenMPIsTargetDevice &&
4482 (T.isNVPTX() || T.isAMDGCN()) &&
4483 Args.hasArg(options::OPT_fopenmp_cuda_mode);
4484
4485 // OpenACC Configuration.
4486 if (Args.hasArg(options::OPT_fopenacc))
4487 Opts.OpenACC = true;
4488
4489 if (Arg *A = Args.getLastArg(OPT_ffp_contract)) {
4490 StringRef Val = A->getValue();
4491 if (Val == "fast")
4492 Opts.setDefaultFPContractMode(LangOptions::FPM_Fast);
4493 else if (Val == "on")
4494 Opts.setDefaultFPContractMode(LangOptions::FPM_On);
4495 else if (Val == "off")
4496 Opts.setDefaultFPContractMode(LangOptions::FPM_Off);
4497 else if (Val == "fast-honor-pragmas")
4498 Opts.setDefaultFPContractMode(LangOptions::FPM_FastHonorPragmas);
4499 else
4500 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
4501 }
4502
4503 if (auto *A =
4504 Args.getLastArg(OPT_fsanitize_undefined_ignore_overflow_pattern_EQ)) {
4505 for (int i = 0, n = A->getNumValues(); i != n; ++i) {
4507 llvm::StringSwitch<unsigned>(A->getValue(i))
4508 .Case("none", LangOptionsBase::None)
4509 .Case("all", LangOptionsBase::All)
4510 .Case("add-unsigned-overflow-test",
4512 .Case("add-signed-overflow-test",
4514 .Case("negated-unsigned-const", LangOptionsBase::NegUnsignedConst)
4515 .Case("unsigned-post-decr-while",
4517 .Default(0);
4518 }
4519 }
4520
4521 // Parse -fsanitize= arguments.
4522 parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ),
4523 Diags, Opts.Sanitize);
4525 "-fsanitize-ignore-for-ubsan-feature=",
4526 Args.getAllArgValues(OPT_fsanitize_ignore_for_ubsan_feature_EQ), Diags,
4528 Opts.NoSanitizeFiles = Args.getAllArgValues(OPT_fsanitize_ignorelist_EQ);
4529 std::vector<std::string> systemIgnorelists =
4530 Args.getAllArgValues(OPT_fsanitize_system_ignorelist_EQ);
4531 Opts.NoSanitizeFiles.insert(Opts.NoSanitizeFiles.end(),
4532 systemIgnorelists.begin(),
4533 systemIgnorelists.end());
4534
4535 if (Arg *A = Args.getLastArg(OPT_fclang_abi_compat_EQ)) {
4536 Opts.setClangABICompat(LangOptions::ClangABI::Latest);
4537
4538 StringRef Ver = A->getValue();
4539 std::pair<StringRef, StringRef> VerParts = Ver.split('.');
4540 int Major, Minor = 0;
4541
4542 // Check the version number is valid: either 3.x (0 <= x <= 9) or
4543 // y or y.0 (4 <= y <= current version).
4544 if (!VerParts.first.starts_with("0") &&
4545 !VerParts.first.getAsInteger(10, Major) && 3 <= Major &&
4546 Major <= MAX_CLANG_ABI_COMPAT_VERSION &&
4547 (Major == 3
4548 ? VerParts.second.size() == 1 &&
4549 !VerParts.second.getAsInteger(10, Minor)
4550 : VerParts.first.size() == Ver.size() || VerParts.second == "0")) {
4551 // Got a valid version number.
4552#define ABI_VER_MAJOR_MINOR(Major_, Minor_) \
4553 if (std::tuple(Major, Minor) <= std::tuple(Major_, Minor_)) \
4554 Opts.setClangABICompat(LangOptions::ClangABI::Ver##Major_##_##Minor_); \
4555 else
4556#define ABI_VER_MAJOR(Major_) \
4557 if (Major <= Major_) \
4558 Opts.setClangABICompat(LangOptions::ClangABI::Ver##Major_); \
4559 else
4560#define ABI_VER_LATEST(Latest) \
4561 { /* Equivalent to latest version - do nothing */ \
4562 }
4563#include "clang/Basic/ABIVersions.def"
4564 } else if (Ver != "latest") {
4565 Diags.Report(diag::err_drv_invalid_value)
4566 << A->getAsString(Args) << A->getValue();
4567 }
4568 }
4569
4570 if (Arg *A = Args.getLastArg(OPT_msign_return_address_EQ)) {
4571 StringRef SignScope = A->getValue();
4572
4573 if (SignScope.equals_insensitive("none"))
4574 Opts.setSignReturnAddressScope(
4576 else if (SignScope.equals_insensitive("all"))
4577 Opts.setSignReturnAddressScope(
4579 else if (SignScope.equals_insensitive("non-leaf"))
4580 Opts.setSignReturnAddressScope(
4582 else
4583 Diags.Report(diag::err_drv_invalid_value)
4584 << A->getAsString(Args) << SignScope;
4585
4586 if (Arg *A = Args.getLastArg(OPT_msign_return_address_key_EQ)) {
4587 StringRef SignKey = A->getValue();
4588 if (!SignScope.empty() && !SignKey.empty()) {
4589 if (SignKey == "a_key")
4590 Opts.setSignReturnAddressKey(
4592 else if (SignKey == "b_key")
4593 Opts.setSignReturnAddressKey(
4595 else
4596 Diags.Report(diag::err_drv_invalid_value)
4597 << A->getAsString(Args) << SignKey;
4598 }
4599 }
4600 }
4601
4602 // The value can be empty, which indicates the system default should be used.
4603 StringRef CXXABI = Args.getLastArgValue(OPT_fcxx_abi_EQ);
4604 if (!CXXABI.empty()) {
4606 Diags.Report(diag::err_invalid_cxx_abi) << CXXABI;
4607 } else {
4609 if (!TargetCXXABI::isSupportedCXXABI(T, Kind))
4610 Diags.Report(diag::err_unsupported_cxx_abi) << CXXABI << T.str();
4611 else
4612 Opts.CXXABI = Kind;
4613 }
4614 }
4615
4616 Opts.RelativeCXXABIVTables =
4617 Args.hasFlag(options::OPT_fexperimental_relative_cxx_abi_vtables,
4618 options::OPT_fno_experimental_relative_cxx_abi_vtables,
4620
4621 // RTTI is on by default.
4622 bool HasRTTI = !Args.hasArg(options::OPT_fno_rtti);
4623 Opts.OmitVTableRTTI =
4624 Args.hasFlag(options::OPT_fexperimental_omit_vtable_rtti,
4625 options::OPT_fno_experimental_omit_vtable_rtti, false);
4626 if (Opts.OmitVTableRTTI && HasRTTI)
4627 Diags.Report(diag::err_drv_using_omit_rtti_component_without_no_rtti);
4628
4629 for (const auto &A : Args.getAllArgValues(OPT_fmacro_prefix_map_EQ)) {
4630 auto Split = StringRef(A).split('=');
4631 Opts.MacroPrefixMap.insert(
4632 {std::string(Split.first), std::string(Split.second)});
4633 }
4634
4636 !Args.getLastArg(OPT_fno_file_reproducible) &&
4637 (Args.getLastArg(OPT_ffile_compilation_dir_EQ) ||
4638 Args.getLastArg(OPT_fmacro_prefix_map_EQ) ||
4639 Args.getLastArg(OPT_ffile_reproducible));
4640
4641 // Error if -mvscale-min is unbounded.
4642 if (Arg *A = Args.getLastArg(options::OPT_mvscale_min_EQ)) {
4643 unsigned VScaleMin;
4644 if (StringRef(A->getValue()).getAsInteger(10, VScaleMin) || VScaleMin == 0)
4645 Diags.Report(diag::err_cc1_unbounded_vscale_min);
4646 }
4647 if (Arg *A = Args.getLastArg(options::OPT_mvscale_streaming_min_EQ)) {
4648 unsigned VScaleMin;
4649 if (StringRef(A->getValue()).getAsInteger(10, VScaleMin) || VScaleMin == 0)
4650 Diags.Report(diag::err_cc1_unbounded_vscale_min);
4651 }
4652
4653 if (const Arg *A = Args.getLastArg(OPT_frandomize_layout_seed_file_EQ)) {
4654 std::ifstream SeedFile(A->getValue(0));
4655
4656 if (!SeedFile.is_open())
4657 Diags.Report(diag::err_drv_cannot_open_randomize_layout_seed_file)
4658 << A->getValue(0);
4659
4660 std::getline(SeedFile, Opts.RandstructSeed);
4661 }
4662
4663 if (const Arg *A = Args.getLastArg(OPT_frandomize_layout_seed_EQ))
4664 Opts.RandstructSeed = A->getValue(0);
4665
4666 if (const auto *Arg = Args.getLastArg(options::OPT_falloc_token_max_EQ)) {
4667 StringRef S = Arg->getValue();
4668 uint64_t Value = 0;
4669 if (S.getAsInteger(0, Value))
4670 Diags.Report(diag::err_drv_invalid_value) << Arg->getAsString(Args) << S;
4671 else
4672 Opts.AllocTokenMax = Value;
4673 }
4674
4675 if (const auto *Arg = Args.getLastArg(options::OPT_falloc_token_mode_EQ)) {
4676 StringRef S = Arg->getValue();
4677 if (auto Mode = getAllocTokenModeFromString(S))
4678 Opts.AllocTokenMode = Mode;
4679 else
4680 Diags.Report(diag::err_drv_invalid_value) << Arg->getAsString(Args) << S;
4681 }
4682
4683 // Enable options for matrix types.
4684 if (Opts.MatrixTypes) {
4685 if (const Arg *A = Args.getLastArg(OPT_fmatrix_memory_layout_EQ)) {
4686 StringRef ClangValue = A->getValue();
4687 if (ClangValue == "row-major")
4688 Opts.setDefaultMatrixMemoryLayout(
4690 else
4691 Opts.setDefaultMatrixMemoryLayout(
4693
4694 for (Arg *A : Args.filtered(options::OPT_mllvm)) {
4695 StringRef OptValue = A->getValue();
4696 if (OptValue.consume_front("-matrix-default-layout=") &&
4697 ClangValue != OptValue)
4698 Diags.Report(diag::err_conflicting_matrix_layout_flags)
4699 << ClangValue << OptValue;
4700 }
4701 }
4702 }
4703
4704 // Validate options for HLSL
4705 if (Opts.HLSL) {
4706 // TODO: Revisit restricting SPIR-V to logical once we've figured out how to
4707 // handle PhysicalStorageBuffer64 memory model
4708 if (T.isDXIL() || T.isSPIRVLogical()) {
4709 enum { ShaderModel, VulkanEnv, ShaderStage };
4710 enum { OS, Environment };
4711
4712 int ExpectedOS = T.isSPIRVLogical() ? VulkanEnv : ShaderModel;
4713
4714 if (T.getOSName().empty()) {
4715 Diags.Report(diag::err_drv_hlsl_bad_shader_required_in_target)
4716 << ExpectedOS << OS << T.str();
4717 } else if (T.getEnvironmentName().empty()) {
4718 Diags.Report(diag::err_drv_hlsl_bad_shader_required_in_target)
4719 << ShaderStage << Environment << T.str();
4720 } else if (!T.isShaderStageEnvironment()) {
4721 Diags.Report(diag::err_drv_hlsl_bad_shader_unsupported)
4722 << ShaderStage << T.getEnvironmentName() << T.str();
4723 }
4724
4725 if (T.isDXIL()) {
4726 if (!T.isShaderModelOS() || T.getOSVersion() == VersionTuple(0)) {
4727 Diags.Report(diag::err_drv_hlsl_bad_shader_unsupported)
4728 << ShaderModel << T.getOSName() << T.str();
4729 }
4730 // Validate that if fnative-half-type is given, that
4731 // the language standard is at least hlsl2018, and that
4732 // the target shader model is at least 6.2.
4733 if (Args.getLastArg(OPT_fnative_half_type) ||
4734 Args.getLastArg(OPT_fnative_int16_type)) {
4735 const LangStandard &Std =
4737 if (!(Opts.LangStd >= LangStandard::lang_hlsl2018 &&
4738 T.getOSVersion() >= VersionTuple(6, 2)))
4739 Diags.Report(diag::err_drv_hlsl_16bit_types_unsupported)
4740 << "-enable-16bit-types" << true << Std.getName()
4741 << T.getOSVersion().getAsString();
4742 }
4743 } else if (T.isSPIRVLogical()) {
4744 if (!T.isVulkanOS() || T.getVulkanVersion() == VersionTuple(0)) {
4745 Diags.Report(diag::err_drv_hlsl_bad_shader_unsupported)
4746 << VulkanEnv << T.getOSName() << T.str();
4747 }
4748 if (Args.getLastArg(OPT_fnative_half_type) ||
4749 Args.getLastArg(OPT_fnative_int16_type)) {
4750 const char *Str = Args.getLastArg(OPT_fnative_half_type)
4751 ? "-fnative-half-type"
4752 : "-fnative-int16-type";
4753 const LangStandard &Std =
4755 if (!(Opts.LangStd >= LangStandard::lang_hlsl2018))
4756 Diags.Report(diag::err_drv_hlsl_16bit_types_unsupported)
4757 << Str << false << Std.getName();
4758 }
4759 } else {
4760 llvm_unreachable("expected DXIL or SPIR-V target");
4761 }
4762 } else
4763 Diags.Report(diag::err_drv_hlsl_unsupported_target) << T.str();
4764
4765 if (Opts.LangStd < LangStandard::lang_hlsl2021) {
4766 const LangStandard &Requested =
4768 const LangStandard &Recommended =
4769 LangStandard::getLangStandardForKind(LangStandard::lang_hlsl202x);
4770 Diags.Report(diag::warn_hlsl_langstd_minimal)
4771 << Requested.getName() << Recommended.getName();
4772 }
4773 }
4774
4775 return Diags.getNumErrors() == NumErrorsBefore;
4776}
4777
4779 switch (Action) {
4781 case frontend::ASTDump:
4782 case frontend::ASTPrint:
4783 case frontend::ASTView:
4785 case frontend::EmitBC:
4786 case frontend::EmitCIR:
4788 case frontend::EmitHTML:
4789 case frontend::EmitLLVM:
4792 case frontend::EmitObj:
4794 case frontend::FixIt:
4808 return false;
4809
4813 case frontend::InitOnly:
4819 return true;
4820 }
4821 llvm_unreachable("invalid frontend action");
4822}
4823
4868
4870 ArgumentConsumer Consumer,
4871 const LangOptions &LangOpts,
4872 const FrontendOptions &FrontendOpts,
4873 const CodeGenOptions &CodeGenOpts) {
4874 const PreprocessorOptions *PreprocessorOpts = &Opts;
4875
4876#define PREPROCESSOR_OPTION_WITH_MARSHALLING(...) \
4877 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
4878#include "clang/Options/Options.inc"
4879#undef PREPROCESSOR_OPTION_WITH_MARSHALLING
4880
4881 if (Opts.PCHWithHdrStop && !Opts.PCHWithHdrStopCreate)
4882 GenerateArg(Consumer, OPT_pch_through_hdrstop_use);
4883
4884 for (const auto &D : Opts.DeserializedPCHDeclsToErrorOn)
4885 GenerateArg(Consumer, OPT_error_on_deserialized_pch_decl, D);
4886
4887 if (Opts.PrecompiledPreambleBytes != std::make_pair(0u, false))
4888 GenerateArg(Consumer, OPT_preamble_bytes_EQ,
4889 Twine(Opts.PrecompiledPreambleBytes.first) + "," +
4890 (Opts.PrecompiledPreambleBytes.second ? "1" : "0"));
4891
4892 for (const auto &M : Opts.Macros) {
4893 // Don't generate __CET__ macro definitions. They are implied by the
4894 // -fcf-protection option that is generated elsewhere.
4895 if (M.first == "__CET__=1" && !M.second &&
4896 !CodeGenOpts.CFProtectionReturn && CodeGenOpts.CFProtectionBranch)
4897 continue;
4898 if (M.first == "__CET__=2" && !M.second && CodeGenOpts.CFProtectionReturn &&
4899 !CodeGenOpts.CFProtectionBranch)
4900 continue;
4901 if (M.first == "__CET__=3" && !M.second && CodeGenOpts.CFProtectionReturn &&
4902 CodeGenOpts.CFProtectionBranch)
4903 continue;
4904
4905 GenerateArg(Consumer, M.second ? OPT_U : OPT_D, M.first);
4906 }
4907
4908 for (const auto &I : Opts.Includes) {
4909 // Don't generate OpenCL includes. They are implied by other flags that are
4910 // generated elsewhere.
4911 if (LangOpts.OpenCL && LangOpts.IncludeDefaultHeader &&
4912 ((LangOpts.DeclareOpenCLBuiltins && I == "opencl-c-base.h") ||
4913 I == "opencl-c.h"))
4914 continue;
4915 // Don't generate HLSL includes. They are implied by other flags that are
4916 // generated elsewhere.
4917 if (LangOpts.HLSL && I == "hlsl.h")
4918 continue;
4919
4920 GenerateArg(Consumer, OPT_include, I);
4921 }
4922
4923 for (const auto &CI : Opts.ChainedIncludes)
4924 GenerateArg(Consumer, OPT_chain_include, CI);
4925
4926 for (const auto &RF : Opts.RemappedFiles)
4927 GenerateArg(Consumer, OPT_remap_file, RF.first + ";" + RF.second);
4928
4929 if (Opts.SourceDateEpoch)
4930 GenerateArg(Consumer, OPT_source_date_epoch, Twine(*Opts.SourceDateEpoch));
4931
4932 if (Opts.DefineTargetOSMacros)
4933 GenerateArg(Consumer, OPT_fdefine_target_os_macros);
4934
4935 for (const auto &EmbedEntry : Opts.EmbedEntries)
4936 GenerateArg(Consumer, OPT_embed_dir_EQ, EmbedEntry);
4937
4938 // Don't handle LexEditorPlaceholders. It is implied by the action that is
4939 // generated elsewhere.
4940}
4941
4942static bool ParsePreprocessorArgs(PreprocessorOptions &Opts, ArgList &Args,
4943 DiagnosticsEngine &Diags,
4944 frontend::ActionKind Action,
4945 const FrontendOptions &FrontendOpts) {
4946 unsigned NumErrorsBefore = Diags.getNumErrors();
4947
4948 PreprocessorOptions *PreprocessorOpts = &Opts;
4949
4950#define PREPROCESSOR_OPTION_WITH_MARSHALLING(...) \
4951 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
4952#include "clang/Options/Options.inc"
4953#undef PREPROCESSOR_OPTION_WITH_MARSHALLING
4954
4955 Opts.PCHWithHdrStop = Args.hasArg(OPT_pch_through_hdrstop_create) ||
4956 Args.hasArg(OPT_pch_through_hdrstop_use);
4957
4958 for (const auto *A : Args.filtered(OPT_error_on_deserialized_pch_decl))
4959 Opts.DeserializedPCHDeclsToErrorOn.insert(A->getValue());
4960
4961 if (const Arg *A = Args.getLastArg(OPT_preamble_bytes_EQ)) {
4962 StringRef Value(A->getValue());
4963 size_t Comma = Value.find(',');
4964 unsigned Bytes = 0;
4965 unsigned EndOfLine = 0;
4966
4967 if (Comma == StringRef::npos ||
4968 Value.substr(0, Comma).getAsInteger(10, Bytes) ||
4969 Value.substr(Comma + 1).getAsInteger(10, EndOfLine))
4970 Diags.Report(diag::err_drv_preamble_format);
4971 else {
4972 Opts.PrecompiledPreambleBytes.first = Bytes;
4973 Opts.PrecompiledPreambleBytes.second = (EndOfLine != 0);
4974 }
4975 }
4976
4977 // Add macros from the command line.
4978 for (const auto *A : Args.filtered(OPT_D, OPT_U)) {
4979 if (A->getOption().matches(OPT_D))
4980 Opts.addMacroDef(A->getValue());
4981 else
4982 Opts.addMacroUndef(A->getValue());
4983 }
4984
4985 // Add the ordered list of -includes.
4986 for (const auto *A : Args.filtered(OPT_include))
4987 Opts.Includes.emplace_back(A->getValue());
4988
4989 for (const auto *A : Args.filtered(OPT_chain_include))
4990 Opts.ChainedIncludes.emplace_back(A->getValue());
4991
4992 for (const auto *A : Args.filtered(OPT_remap_file)) {
4993 std::pair<StringRef, StringRef> Split = StringRef(A->getValue()).split(';');
4994
4995 if (Split.second.empty()) {
4996 Diags.Report(diag::err_drv_invalid_remap_file) << A->getAsString(Args);
4997 continue;
4998 }
4999
5000 Opts.addRemappedFile(Split.first, Split.second);
5001 }
5002
5003 if (const Arg *A = Args.getLastArg(OPT_source_date_epoch)) {
5004 StringRef Epoch = A->getValue();
5005 // SOURCE_DATE_EPOCH, if specified, must be a non-negative decimal integer.
5006 // On time64 systems, pick 253402300799 (the UNIX timestamp of
5007 // 9999-12-31T23:59:59Z) as the upper bound.
5008 const uint64_t MaxTimestamp =
5009 std::min<uint64_t>(std::numeric_limits<time_t>::max(), 253402300799);
5010 uint64_t V;
5011 if (Epoch.getAsInteger(10, V) || V > MaxTimestamp) {
5012 Diags.Report(diag::err_fe_invalid_source_date_epoch)
5013 << Epoch << MaxTimestamp;
5014 } else {
5015 Opts.SourceDateEpoch = V;
5016 }
5017 }
5018
5019 for (const auto *A : Args.filtered(OPT_embed_dir_EQ)) {
5020 StringRef Val = A->getValue();
5021 Opts.EmbedEntries.push_back(std::string(Val));
5022 }
5023
5024 // Always avoid lexing editor placeholders when we're just running the
5025 // preprocessor as we never want to emit the
5026 // "editor placeholder in source file" error in PP only mode.
5027 if (isStrictlyPreprocessorAction(Action))
5028 Opts.LexEditorPlaceholders = false;
5029
5031 Args.hasFlag(OPT_fdefine_target_os_macros,
5032 OPT_fno_define_target_os_macros, Opts.DefineTargetOSMacros);
5033
5034 return Diags.getNumErrors() == NumErrorsBefore;
5035}
5036
5037static void
5039 ArgumentConsumer Consumer,
5040 frontend::ActionKind Action) {
5041 const PreprocessorOutputOptions &PreprocessorOutputOpts = Opts;
5042
5043#define PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING(...) \
5044 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
5045#include "clang/Options/Options.inc"
5046#undef PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING
5047
5048 bool Generate_dM = isStrictlyPreprocessorAction(Action) && !Opts.ShowCPP;
5049 if (Generate_dM)
5050 GenerateArg(Consumer, OPT_dM);
5051 if (!Generate_dM && Opts.ShowMacros)
5052 GenerateArg(Consumer, OPT_dD);
5053 if (Opts.DirectivesOnly)
5054 GenerateArg(Consumer, OPT_fdirectives_only);
5055}
5056
5058 ArgList &Args, DiagnosticsEngine &Diags,
5059 frontend::ActionKind Action) {
5060 unsigned NumErrorsBefore = Diags.getNumErrors();
5061
5062 PreprocessorOutputOptions &PreprocessorOutputOpts = Opts;
5063
5064#define PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING(...) \
5065 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
5066#include "clang/Options/Options.inc"
5067#undef PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING
5068
5069 Opts.ShowCPP = isStrictlyPreprocessorAction(Action) && !Args.hasArg(OPT_dM);
5070 Opts.ShowMacros = Args.hasArg(OPT_dM) || Args.hasArg(OPT_dD);
5071 Opts.DirectivesOnly = Args.hasArg(OPT_fdirectives_only);
5072
5073 return Diags.getNumErrors() == NumErrorsBefore;
5074}
5075
5076static void GenerateTargetArgs(const TargetOptions &Opts,
5077 ArgumentConsumer Consumer) {
5078 const TargetOptions *TargetOpts = &Opts;
5079#define TARGET_OPTION_WITH_MARSHALLING(...) \
5080 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
5081#include "clang/Options/Options.inc"
5082#undef TARGET_OPTION_WITH_MARSHALLING
5083
5084 if (!Opts.SDKVersion.empty())
5085 GenerateArg(Consumer, OPT_target_sdk_version_EQ,
5086 Opts.SDKVersion.getAsString());
5087 if (!Opts.DarwinTargetVariantSDKVersion.empty())
5088 GenerateArg(Consumer, OPT_darwin_target_variant_sdk_version_EQ,
5089 Opts.DarwinTargetVariantSDKVersion.getAsString());
5090
5091 // Generate AMDGPU xnack and sramecc flags.
5093 GenerateArg(Consumer, OPT_mxnack);
5095 GenerateArg(Consumer, OPT_mno_xnack);
5096
5098 GenerateArg(Consumer, OPT_msramecc);
5099 else if (Opts.AMDGPUSramEccState ==
5101 GenerateArg(Consumer, OPT_mno_sramecc);
5102}
5103
5104static bool ParseTargetArgs(TargetOptions &Opts, ArgList &Args,
5105 DiagnosticsEngine &Diags) {
5106 unsigned NumErrorsBefore = Diags.getNumErrors();
5107
5108 TargetOptions *TargetOpts = &Opts;
5109
5110#define TARGET_OPTION_WITH_MARSHALLING(...) \
5111 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
5112#include "clang/Options/Options.inc"
5113#undef TARGET_OPTION_WITH_MARSHALLING
5114
5115 if (Arg *A = Args.getLastArg(options::OPT_target_sdk_version_EQ)) {
5116 llvm::VersionTuple Version;
5117 if (Version.tryParse(A->getValue()))
5118 Diags.Report(diag::err_drv_invalid_value)
5119 << A->getAsString(Args) << A->getValue();
5120 else
5121 Opts.SDKVersion = Version;
5122 }
5123 if (Arg *A =
5124 Args.getLastArg(options::OPT_darwin_target_variant_sdk_version_EQ)) {
5125 llvm::VersionTuple Version;
5126 if (Version.tryParse(A->getValue()))
5127 Diags.Report(diag::err_drv_invalid_value)
5128 << A->getAsString(Args) << A->getValue();
5129 else
5130 Opts.DarwinTargetVariantSDKVersion = Version;
5131 }
5132
5133 if (Arg *A = Args.getLastArg(options::OPT_mxnack, options::OPT_mno_xnack)) {
5134 bool IsEnabled = A->getOption().matches(options::OPT_mxnack);
5135 Opts.AMDGPUXnackState = IsEnabled
5138 }
5139
5140 if (Arg *A =
5141 Args.getLastArg(options::OPT_msramecc, options::OPT_mno_sramecc)) {
5142 bool IsEnabled = A->getOption().matches(options::OPT_msramecc);
5143 Opts.AMDGPUSramEccState = IsEnabled
5146 }
5147
5148 return Diags.getNumErrors() == NumErrorsBefore;
5149}
5150
5151bool CompilerInvocation::CreateFromArgsImpl(
5152 CompilerInvocation &Res, ArrayRef<const char *> CommandLineArgs,
5153 DiagnosticsEngine &Diags, const char *Argv0) {
5154 unsigned NumErrorsBefore = Diags.getNumErrors();
5155
5156 // Parse the arguments.
5157 const OptTable &Opts = getDriverOptTable();
5158 llvm::opt::Visibility VisibilityMask(options::CC1Option);
5159 unsigned MissingArgIndex, MissingArgCount;
5160 InputArgList Args = Opts.ParseArgs(CommandLineArgs, MissingArgIndex,
5161 MissingArgCount, VisibilityMask);
5162 LangOptions &LangOpts = Res.getLangOpts();
5163
5164 // Check for missing argument error.
5165 if (MissingArgCount)
5166 Diags.Report(diag::err_drv_missing_argument)
5167 << Args.getArgString(MissingArgIndex) << MissingArgCount;
5168
5169 // Issue errors on unknown arguments.
5170 for (const auto *A : Args.filtered(OPT_UNKNOWN)) {
5171 auto ArgString = A->getAsString(Args);
5172 std::string Nearest;
5173 if (Opts.findNearest(ArgString, Nearest, VisibilityMask) > 1)
5174 Diags.Report(diag::err_drv_unknown_argument) << ArgString;
5175 else
5176 Diags.Report(diag::err_drv_unknown_argument_with_suggestion)
5177 << ArgString << Nearest;
5178 }
5179
5180 ParseFileSystemArgs(Res.getFileSystemOpts(), Args, Diags);
5181 ParseMigratorArgs(Res.getMigratorOpts(), Args, Diags);
5182 ParseAnalyzerArgs(Res.getAnalyzerOpts(), Args, Diags);
5183 ParseSSAFArgs(Res.getSSAFOpts(), Args, Diags);
5184 ParseDiagnosticArgs(Res.getDiagnosticOpts(), Args, &Diags);
5185 ParseFrontendArgs(Res.getFrontendOpts(), Args, Diags, LangOpts.IsHeaderFile);
5186 // FIXME: We shouldn't have to pass the DashX option around here
5187 InputKind DashX = Res.getFrontendOpts().DashX;
5188 ParseTargetArgs(Res.getTargetOpts(), Args, Diags);
5189 llvm::Triple T(Res.getTargetOpts().Triple);
5190 ParseHeaderSearchArgs(Res.getHeaderSearchOpts(), Args, Diags);
5191 if (Res.getFrontendOpts().GenReducedBMI ||
5198 }
5199 ParseAPINotesArgs(Res.getAPINotesOpts(), Args, Diags);
5200
5201 ParsePointerAuthArgs(LangOpts, Args, Diags);
5202
5203 ParseLangArgs(LangOpts, Args, DashX, T, Res.getPreprocessorOpts().Includes,
5204 Diags);
5206 LangOpts.ObjCExceptions = 1;
5207
5208 for (auto Warning : Res.getDiagnosticOpts().Warnings) {
5209 if (Warning == "misexpect" &&
5210 !Diags.isIgnored(diag::warn_profile_data_misexpect, SourceLocation())) {
5211 Res.getCodeGenOpts().MisExpect = true;
5212 }
5213 }
5214
5215 if (LangOpts.CUDA) {
5216 // During CUDA device-side compilation, the aux triple is the
5217 // triple used for host compilation.
5218 if (LangOpts.CUDAIsDevice)
5220 }
5221
5222 if (LangOpts.OpenACC && !Res.getFrontendOpts().UseClangIRPipeline &&
5224 Diags.Report(diag::warn_drv_openacc_without_cir);
5225
5226 // Set the triple of the host for OpenMP device compile.
5227 if (LangOpts.OpenMPIsTargetDevice)
5229
5230 // Set the default and host triples for SYCL device compilation.
5231 if (LangOpts.SYCLIsDevice) {
5232 if (!Args.hasArg(options::OPT_triple))
5233 Res.getTargetOpts().Triple = "spirv64-unknown-unknown";
5235 }
5236
5237 ParseCodeGenArgs(Res.getCodeGenOpts(), Args, DashX, Diags, T,
5239
5240 // FIXME: Override value name discarding when asan or msan is used because the
5241 // backend passes depend on the name of the alloca in order to print out
5242 // names.
5243 Res.getCodeGenOpts().DiscardValueNames &=
5244 !LangOpts.Sanitize.has(SanitizerKind::Address) &&
5245 !LangOpts.Sanitize.has(SanitizerKind::KernelAddress) &&
5246 !LangOpts.Sanitize.has(SanitizerKind::Memory) &&
5247 !LangOpts.Sanitize.has(SanitizerKind::KernelMemory);
5248
5249 ParsePreprocessorArgs(Res.getPreprocessorOpts(), Args, Diags,
5251 Res.getFrontendOpts());
5254
5258 if (!Res.getDependencyOutputOpts().OutputFile.empty() &&
5259 Res.getDependencyOutputOpts().Targets.empty())
5260 Diags.Report(diag::err_fe_dependency_file_requires_MT);
5261
5262 // If sanitizer is enabled, disable OPT_ffine_grained_bitfield_accesses.
5263 if (Res.getCodeGenOpts().FineGrainedBitfieldAccesses &&
5264 !Res.getLangOpts().Sanitize.empty()) {
5265 Res.getCodeGenOpts().FineGrainedBitfieldAccesses = false;
5266 Diags.Report(diag::warn_drv_fine_grained_bitfield_accesses_ignored);
5267 }
5268
5269 // Store the command-line for using in the CodeView backend.
5270 if (Res.getCodeGenOpts().CodeViewCommandLine) {
5271 Res.getCodeGenOpts().Argv0 = Argv0;
5272 append_range(Res.getCodeGenOpts().CommandLineArgs, CommandLineArgs);
5273 }
5274
5275 if (!Res.getCodeGenOpts().ProfileInstrumentUsePath.empty() &&
5276 Res.getCodeGenOpts().getProfileUse() ==
5277 llvm::driver::ProfileInstrKind::ProfileNone)
5278 Diags.Report(diag::err_drv_profile_instrument_use_path_with_no_kind);
5279
5280 llvm::TimeTraceCompression TimeTraceCompress =
5282 if (TimeTraceCompress == llvm::TimeTraceCompression::Infer &&
5283 !Res.getFrontendOpts().TimeTracePath.empty())
5284 TimeTraceCompress = llvm::inferTimeTraceCompressionFromPath(
5286 if (TimeTraceCompress == llvm::TimeTraceCompression::Zstd &&
5287 !llvm::compression::zstd::isAvailable())
5288 Diags.Report(diag::err_drv_time_trace_compression_unavailable) << "zstd";
5289
5290 FixupInvocation(Res, Diags, Args, DashX);
5291
5292 return Diags.getNumErrors() == NumErrorsBefore;
5293}
5294
5296 ArrayRef<const char *> CommandLineArgs,
5297 DiagnosticsEngine &Diags,
5298 const char *Argv0) {
5299 CompilerInvocation DummyInvocation;
5300
5301 return RoundTrip(
5302 [](CompilerInvocation &Invocation, ArrayRef<const char *> CommandLineArgs,
5303 DiagnosticsEngine &Diags, const char *Argv0) {
5304 return CreateFromArgsImpl(Invocation, CommandLineArgs, Diags, Argv0);
5305 },
5307 StringAllocator SA) {
5308 Args.push_back("-cc1");
5309 Invocation.generateCC1CommandLine(Args, SA);
5310 },
5311 Invocation, DummyInvocation, CommandLineArgs, Diags, Argv0);
5312}
5313
5315 // FIXME: Consider using SHA1 instead of MD5.
5316 llvm::HashBuilder<llvm::MD5, llvm::endianness::native> HBuilder;
5317
5318 // Note: For QoI reasons, the things we use as a hash here should all be
5319 // dumped via the -module-info flag.
5320
5321 // Start the signature with the compiler version.
5322 HBuilder.add(getClangFullRepositoryVersion());
5323
5324 // Also include the serialization version, in case LLVM_APPEND_VC_REV is off
5325 // and getClangFullRepositoryVersion() doesn't include git revision.
5327
5328 // Extend the signature with the language options
5329 const unsigned LanguageOptionValues[] = {
5330#define HASH_LANGOPT_Benign(Value)
5331#define HASH_LANGOPT_Compatible(Value) Value,
5332#define HASH_LANGOPT_NotCompatible(Value) Value,
5333#define LANGOPT(Name, Bits, Default, Compatibility, Description) \
5334 HASH_LANGOPT_##Compatibility(LangOpts->Name)
5335#define ENUM_LANGOPT(Name, Type, Bits, Default, Compatibility, Description) \
5336 HASH_LANGOPT_##Compatibility(static_cast<unsigned>(LangOpts->get##Name()))
5337#include "clang/Basic/LangOptions.def"
5338 };
5339#undef HASH_LANGOPT_Benign
5340#undef HASH_LANGOPT_Compatible
5341#undef HASH_LANGOPT_NotCompatible
5342 // addRangeElements preserves the HBuilder.add sequence and excludes the
5343 // LanguageOptionValues element count.
5344 HBuilder.addRangeElements(LanguageOptionValues);
5345
5346 HBuilder.addRange(getLangOpts().ModuleFeatures);
5347
5348 HBuilder.add(getLangOpts().ObjCRuntime);
5349 HBuilder.addRange(getLangOpts().CommentOpts.BlockCommandNames);
5350 HBuilder.add(getLangOpts().CommentOpts.RetainCommentsFromSystemHeaders);
5351
5352 // Extend the signature with the target options.
5353 HBuilder.add(getTargetOpts().Triple, getTargetOpts().CPU,
5354 getTargetOpts().TuneCPU, getTargetOpts().ABI);
5355 HBuilder.addRange(getTargetOpts().FeaturesAsWritten);
5356
5357 // Extend the signature with preprocessor options.
5358 const PreprocessorOptions &ppOpts = getPreprocessorOpts();
5359 HBuilder.add(ppOpts.UsePredefines, ppOpts.DetailedRecord);
5360
5361 const HeaderSearchOptions &hsOpts = getHeaderSearchOpts();
5362 for (const auto &Macro : getPreprocessorOpts().Macros) {
5363 // If we're supposed to ignore this macro for the purposes of modules,
5364 // don't put it into the hash.
5365 if (!hsOpts.ModulesIgnoreMacros.empty()) {
5366 // Check whether we're ignoring this macro.
5367 StringRef MacroDef = Macro.first;
5368 if (hsOpts.ModulesIgnoreMacros.count(
5369 llvm::CachedHashString(MacroDef.split('=').first)))
5370 continue;
5371 }
5372
5373 HBuilder.add(Macro);
5374 }
5375
5376 // Extend the signature with the sysroot and other header search options.
5377 HBuilder.add(hsOpts.Sysroot, hsOpts.ModuleFormat, hsOpts.UseDebugInfo,
5379 hsOpts.UseStandardCXXIncludes, hsOpts.UseLibcxx,
5381 HBuilder.add(hsOpts.ResourceDir);
5382
5383 if (hsOpts.ModulesStrictContextHash) {
5384 HBuilder.addRange(hsOpts.SystemHeaderPrefixes);
5385
5386 for (const auto &UserEntry : hsOpts.UserEntries) {
5387 // If we're supposed to ignore this search path for the purposes of
5388 // modules, don't put it into the hash.
5389 if (!hsOpts.ModulesIgnoreSearchPaths.empty()) {
5390 // Check whether we're ignoring this search path.
5391 StringRef Path = UserEntry.Path;
5392 if (hsOpts.ModulesIgnoreSearchPaths.count(llvm::CachedHashString(Path)))
5393 continue;
5394 }
5395
5396 HBuilder.add(UserEntry);
5397 }
5398
5399 HBuilder.addRange(getFrontendOpts().ModuleMapFiles);
5400
5401 HBuilder.addRange(hsOpts.VFSOverlayFiles);
5402
5403 const DiagnosticOptions &diagOpts = getDiagnosticOpts();
5404#define DIAGOPT(Name, Bits, Default) HBuilder.add(diagOpts.Name);
5405#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
5406 HBuilder.add(diagOpts.get##Name());
5407#include "clang/Basic/DiagnosticOptions.def"
5408#undef DIAGOPT
5409#undef ENUM_DIAGOPT
5410 }
5411
5412 // Extend the signature with the user build path.
5413 HBuilder.add(hsOpts.ModuleUserBuildPath);
5414
5415 // Extend the signature with the module file extensions.
5416 for (const auto &ext : getFrontendOpts().ModuleFileExtensions)
5417 ext->hashExtension(HBuilder);
5418
5419 // Extend the signature with the Swift version for API notes.
5421 if (!APINotesOpts.SwiftVersion.empty()) {
5422 HBuilder.add(APINotesOpts.SwiftVersion.getMajor());
5423 if (auto Minor = APINotesOpts.SwiftVersion.getMinor())
5424 HBuilder.add(*Minor);
5425 if (auto Subminor = APINotesOpts.SwiftVersion.getSubminor())
5426 HBuilder.add(*Subminor);
5427 if (auto Build = APINotesOpts.SwiftVersion.getBuild())
5428 HBuilder.add(*Build);
5429 }
5430
5431 // Extend the signature with affecting codegen options.
5432 {
5434#define CODEGENOPT(Name, Bits, Default, Compatibility) \
5435 if constexpr (CK::Compatibility != CK::Benign) \
5436 HBuilder.add(CodeGenOpts->Name);
5437#define ENUM_CODEGENOPT(Name, Type, Bits, Default, Compatibility) \
5438 if constexpr (CK::Compatibility != CK::Benign) \
5439 HBuilder.add(static_cast<unsigned>(CodeGenOpts->get##Name()));
5440#define DEBUGOPT(Name, Bits, Default, Compatibility)
5441#define VALUE_DEBUGOPT(Name, Bits, Default, Compatibility)
5442#define ENUM_DEBUGOPT(Name, Type, Bits, Default, Compatibility)
5443#include "clang/Basic/CodeGenOptions.def"
5444 }
5445
5446 // When compiling with -gmodules, also hash -fdebug-prefix-map as it
5447 // affects the debug info in the PCM.
5448 if (getCodeGenOpts().DebugTypeExtRefs)
5449 HBuilder.addRange(getCodeGenOpts().DebugPrefixMap);
5450
5451 // Extend the signature with the affecting debug options.
5452 if (getHeaderSearchOpts().ModuleFormat == "obj") {
5453 // FIXME: Replace with C++20 `using enum CodeGenOptions::CompatibilityKind`.
5455#define DEBUGOPT(Name, Bits, Default, Compatibility) \
5456 if constexpr (CK::Compatibility != CK::Benign) \
5457 HBuilder.add(CodeGenOpts->Name);
5458#define VALUE_DEBUGOPT(Name, Bits, Default, Compatibility) \
5459 if constexpr (CK::Compatibility != CK::Benign) \
5460 HBuilder.add(CodeGenOpts->Name);
5461#define ENUM_DEBUGOPT(Name, Type, Bits, Default, Compatibility) \
5462 if constexpr (CK::Compatibility != CK::Benign) \
5463 HBuilder.add(static_cast<unsigned>(CodeGenOpts->get##Name()));
5464#include "clang/Basic/DebugOptions.def"
5465 }
5466
5467 // Extend the signature with the enabled sanitizers, if at least one is
5468 // enabled. Sanitizers which cannot affect AST generation aren't hashed.
5469 SanitizerSet SanHash = getLangOpts().Sanitize;
5471 if (!SanHash.empty())
5472 HBuilder.add(SanHash.Mask);
5473
5474 llvm::MD5::MD5Result Result;
5475 HBuilder.getHasher().final(Result);
5476 uint64_t Hash = Result.high() ^ Result.low();
5477 return toString(llvm::APInt(64, Hash), 36, /*Signed=*/false);
5478}
5479
5481 llvm::function_ref<VisitMutResult(StringRef, std::string &)> Cb) {
5482 std::string NewValue;
5483
5484#define RETURN_IF(OPTS, PATH) \
5485 do { \
5486 VisitMutResult Res = Cb(PATH, NewValue); \
5487 if (Res.Replace) { \
5488 (void)ensureOwned(OPTS); \
5489 PATH.clear(); \
5490 std::swap(PATH, NewValue); \
5491 } \
5492 if (Res.Terminate) \
5493 return; \
5494 } while (0)
5495
5496#define RETURN_IF_MANY(OPTS, PATHS) \
5497 do { \
5498 for (unsigned I = 0, E = PATHS.size(); I != E; ++I) \
5499 RETURN_IF(OPTS, PATHS[I]); \
5500 } while (0)
5501
5502 // Header search paths.
5503 RETURN_IF(HSOpts, HSOpts->Sysroot);
5504 for (auto &Entry : HSOpts->UserEntries)
5505 if (Entry.IgnoreSysRoot)
5506 RETURN_IF(HSOpts, Entry.Path);
5507 RETURN_IF(HSOpts, HSOpts->ResourceDir);
5508 RETURN_IF(HSOpts, HSOpts->ModuleCachePath);
5509 RETURN_IF(HSOpts, HSOpts->ModuleUserBuildPath);
5510 for (auto &[Name, File] : HSOpts->PrebuiltModuleFiles)
5512 RETURN_IF_MANY(HSOpts, HSOpts->PrebuiltModulePaths);
5513 RETURN_IF_MANY(HSOpts, HSOpts->VFSOverlayFiles);
5514
5515 // Preprocessor options.
5516 RETURN_IF_MANY(PPOpts, PPOpts->MacroIncludes);
5517 RETURN_IF_MANY(PPOpts, PPOpts->Includes);
5518 RETURN_IF(PPOpts, PPOpts->ImplicitPCHInclude);
5519
5520 // Frontend options.
5521 for (auto &Input : FrontendOpts->Inputs) {
5522 if (Input.isBuffer())
5523 continue;
5524
5525 RETURN_IF(FrontendOpts, Input.File);
5526 }
5527 // TODO: Also report output files such as FrontendOpts->OutputFile;
5528 RETURN_IF(FrontendOpts, FrontendOpts->CodeCompletionAt.FileName);
5529 RETURN_IF_MANY(FrontendOpts, FrontendOpts->ModuleMapFiles);
5531 RETURN_IF_MANY(FrontendOpts, FrontendOpts->ModulesEmbedFiles);
5532 RETURN_IF_MANY(FrontendOpts, FrontendOpts->ASTMergeFiles);
5533 RETURN_IF(FrontendOpts, FrontendOpts->OverrideRecordLayoutsFile);
5534 RETURN_IF(FrontendOpts, FrontendOpts->StatsFile);
5535
5536 // Filesystem options.
5537 RETURN_IF(FSOpts, FSOpts->WorkingDir);
5538
5539 // Codegen options.
5540 RETURN_IF(CodeGenOpts, CodeGenOpts->DebugCompilationDir);
5541 RETURN_IF(CodeGenOpts, CodeGenOpts->CoverageCompilationDir);
5542
5543 // Sanitizer options.
5544 RETURN_IF_MANY(LangOpts, LangOpts->NoSanitizeFiles);
5545
5546 // Coverage mappings.
5547 RETURN_IF(CodeGenOpts, CodeGenOpts->ProfileInstrumentUsePath);
5548 RETURN_IF(CodeGenOpts, CodeGenOpts->SampleProfileFile);
5549 RETURN_IF(CodeGenOpts, CodeGenOpts->ProfileRemappingFile);
5550
5551 // Dependency output options.
5552 for (auto &ExtraDep : DependencyOutputOpts->ExtraDeps)
5553 RETURN_IF(DependencyOutputOpts, ExtraDep.first);
5554}
5555
5557 llvm::function_ref<VisitConstResult(StringRef)> Cb) const {
5558 // The const_cast here is OK, because our callback never tries to modify.
5559 return const_cast<CowCompilerInvocation *>(this)->visitMutPaths(
5560 [&Cb](StringRef Path, std::string &) { return Cb(Path); });
5561}
5562
5564 ArgumentConsumer Consumer) const {
5565 llvm::Triple T(getTargetOpts().Triple);
5566
5570 GenerateSSAFArgs(getSSAFOpts(), Consumer);
5571 GenerateDiagnosticArgs(getDiagnosticOpts(), Consumer,
5572 /*DefaultDiagColor=*/false);
5573 GenerateFrontendArgs(getFrontendOpts(), Consumer, getLangOpts().IsHeaderFile);
5574 GenerateTargetArgs(getTargetOpts(), Consumer);
5578 GenerateLangArgs(getLangOpts(), Consumer, T, getFrontendOpts().DashX);
5579 GenerateCodeGenArgs(getCodeGenOpts(), Consumer, T,
5580 getFrontendOpts().OutputFile, &getLangOpts());
5584 getFrontendOpts().ProgramAction);
5586}
5587
5588std::vector<std::string> CompilerInvocationBase::getCC1CommandLine() const {
5589 std::vector<std::string> Args{"-cc1"};
5591 [&Args](const Twine &Arg) { Args.push_back(Arg.str()); });
5592 return Args;
5593}
5594
5600
5602 getLangOpts().ImplicitModules = false;
5608 // The specific values we canonicalize to for pruning don't affect behaviour,
5609 /// so use the default values so they may be dropped from the command-line.
5610 getHeaderSearchOpts().ModuleCachePruneInterval = 7 * 24 * 60 * 60;
5611 getHeaderSearchOpts().ModuleCachePruneAfter = 31 * 24 * 60 * 60;
5612}
5613
5616 DiagnosticsEngine &Diags) {
5617 return createVFSFromCompilerInvocation(CI, Diags,
5618 llvm::vfs::getRealFileSystem());
5619}
5620
5628
5630 ArrayRef<std::string> VFSOverlayFiles, DiagnosticsEngine &Diags,
5632 if (VFSOverlayFiles.empty())
5633 return BaseFS;
5634
5636 // earlier vfs files are on the bottom
5637 for (const auto &File : VFSOverlayFiles) {
5638 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer =
5639 Result->getBufferForFile(File);
5640 if (!Buffer) {
5641 Diags.Report(diag::err_missing_vfs_overlay_file) << File;
5642 continue;
5643 }
5644
5645 IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS = llvm::vfs::getVFSFromYAML(
5646 std::move(Buffer.get()), /*DiagHandler*/ nullptr, File,
5647 /*DiagContext*/ nullptr, Result);
5648 if (!FS) {
5649 Diags.Report(diag::err_invalid_vfs_overlay) << File;
5650 continue;
5651 }
5652
5653 Result = FS;
5654 }
5655 return Result;
5656}
#define V(N, I)
Defines the Diagnostic-related interfaces.
Defines enum values for all the target-independent builtin functions.
Defines the clang::CommentOptions interface.
static void getAllNoBuiltinFuncValues(ArgList &Args, std::vector< std::string > &Funcs)
static std::optional< IntTy > normalizeStringIntegral(OptSpecifier Opt, int, const ArgList &Args, DiagnosticsEngine &Diags)
static std::optional< std::string > normalizeString(OptSpecifier Opt, int TableIndex, const ArgList &Args, DiagnosticsEngine &Diags)
static auto makeBooleanOptionNormalizer(bool Value, bool OtherValue, OptSpecifier OtherOpt)
static void parsePointerAuthOptions(PointerAuthOptions &Opts, const LangOptions &LangOpts, const llvm::Triple &Triple, DiagnosticsEngine &Diags)
static void denormalizeString(ArgumentConsumer Consumer, unsigned SpellingOffset, Option::OptionClass OptClass, unsigned TableIndex, T Value)
static SmallVector< StringRef, 4 > serializeSanitizerKinds(SanitizerSet S)
static void parseXRayInstrumentationBundle(StringRef FlagName, StringRef Bundle, ArgList &Args, DiagnosticsEngine &D, XRayInstrSet &S)
static void GenerateFrontendArgs(const FrontendOptions &Opts, ArgumentConsumer Consumer, bool IsHeader)
static std::optional< SimpleEnumValue > findValueTableByValue(const SimpleEnumValueTable &Table, unsigned Value)
static void GenerateSSAFArgs(const ssaf::SSAFOptions &Opts, ArgumentConsumer Consumer)
static bool ParseTargetArgs(TargetOptions &Opts, ArgList &Args, DiagnosticsEngine &Diags)
static auto makeFlagToValueNormalizer(T Value)
#define RETURN_IF_MANY(OPTS, PATHS)
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 void GeneratePointerAuthArgs(const LangOptions &Opts, ArgumentConsumer Consumer)
static std::optional< SimpleEnumValue > findValueTableByName(const SimpleEnumValueTable &Table, StringRef Name)
static std::optional< OptSpecifier > getProgramActionOpt(frontend::ActionKind ProgramAction)
Maps frontend action to command line option.
static bool parseDiagnosticLevelMask(StringRef FlagName, const std::vector< std::string > &Levels, DiagnosticsEngine &Diags, DiagnosticLevelMask &M)
static std::optional< bool > normalizeSimpleFlag(OptSpecifier Opt, unsigned TableIndex, const ArgList &Args, DiagnosticsEngine &Diags)
CompilerInvocation::ArgumentConsumer ArgumentConsumer
static void denormalizeSimpleEnumImpl(ArgumentConsumer Consumer, unsigned SpellingOffset, Option::OptionClass OptClass, unsigned TableIndex, unsigned Value)
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 denormalizeSimpleFlag(ArgumentConsumer Consumer, unsigned SpellingOffset, Option::OptionClass, unsigned,...)
The tblgen-erated code passes in a fifth parameter of an arbitrary type, but denormalizeSimpleFlags n...
static bool ParsePreprocessorArgs(PreprocessorOptions &Opts, ArgList &Args, DiagnosticsEngine &Diags, frontend::ActionKind Action, const FrontendOptions &FrontendOpts)
static std::optional< unsigned > normalizeSimpleEnum(OptSpecifier Opt, unsigned TableIndex, const ArgList &Args, DiagnosticsEngine &Diags)
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)
#define RETURN_IF(OPTS, PATH)
static std::optional< std::string > normalizeTriple(OptSpecifier Opt, int TableIndex, const ArgList &Args, DiagnosticsEngine &Diags)
T & ensureOwned(std::shared_ptr< T > &Storage)
static void GenerateMigratorArgs(const MigratorOptions &Opts, ArgumentConsumer Consumer)
static const auto & getFrontendActionTable()
Return a table that associates command line option specifiers with the frontend action.
static void GenerateTargetArgs(const TargetOptions &Opts, ArgumentConsumer Consumer)
static std::optional< frontend::ActionKind > getFrontendAction(OptSpecifier &Opt)
Maps command line option to frontend action.
static bool checkVerifyPrefixes(const std::vector< std::string > &VerifyPrefixes, DiagnosticsEngine &Diags)
static SanitizerMaskCutoffs parseSanitizerWeightedKinds(StringRef FlagName, const std::vector< std::string > &Sanitizers, DiagnosticsEngine &Diags)
static ShowColorsKind parseShowColorsMode(const ArgList &Args, bool DefaultColor)
static void GenerateAPINotesArgs(const APINotesOptions &Opts, ArgumentConsumer Consumer)
static bool isCodeGenAction(frontend::ActionKind Action)
static std::optional< bool > normalizeSimpleNegativeFlag(OptSpecifier Opt, unsigned, const ArgList &Args, DiagnosticsEngine &)
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 llvm::StringRef lookupStrInTable(unsigned Offset)
static bool ParseSSAFArgs(ssaf::SSAFOptions &Opts, ArgList &Args, DiagnosticsEngine &Diags)
static void GeneratePreprocessorArgs(const PreprocessorOptions &Opts, ArgumentConsumer Consumer, const LangOptions &LangOpts, const FrontendOptions &FrontendOpts, const CodeGenOptions &CodeGenOpts)
static bool ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args, DiagnosticsEngine &Diags, bool &IsHeaderFile)
static auto makeBooleanOptionDenormalizer(bool Value)
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 bool ParseMigratorArgs(MigratorOptions &Opts, const ArgList &Args, DiagnosticsEngine &Diags)
static void ParseAPINotesArgs(APINotesOptions &Opts, ArgList &Args, DiagnosticsEngine &diags)
static void denormalizeStringVector(ArgumentConsumer Consumer, unsigned SpellingOffset, Option::OptionClass OptClass, unsigned TableIndex, const std::vector< std::string > &Values)
static bool ParseDependencyOutputArgs(DependencyOutputOptions &Opts, ArgList &Args, DiagnosticsEngine &Diags, frontend::ActionKind Action, bool ShowLineMarkers)
static Expected< std::optional< uint32_t > > parseToleranceOption(StringRef Arg)
static std::optional< std::vector< std::string > > normalizeStringVector(OptSpecifier Opt, int, const ArgList &Args, DiagnosticsEngine &)
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)
llvm::function_ref< void( CompilerInvocation &, SmallVectorImpl< const char * > &, CompilerInvocation::StringAllocator)> GenerateFn
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 void denormalizeSimpleEnum(ArgumentConsumer Consumer, unsigned SpellingOffset, Option::OptionClass OptClass, unsigned TableIndex, T Value)
std::shared_ptr< T > make_shared_copy(const T &X)
llvm::function_ref< bool(CompilerInvocation &, ArrayRef< const char * >, DiagnosticsEngine &, const char *)> ParseFn
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 bool ParseHeaderSearchArgs(HeaderSearchOptions &Opts, ArgList &Args, DiagnosticsEngine &Diags)
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.
Result
Implement __builtin_bit_cast and related operations.
#define X(type, name)
Definition Value.h:97
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 std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
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::XRayInstrKind enum.
__DEVICE__ void * memcpy(void *__a, const void *__b, size_t __c)
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.
Definition Builtins.cpp:139
CompatibilityKind
For ASTs produced with different option value, signifies their level of compatibility.
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.
SanitizerSet SanitizeMergeHandlers
Set of sanitizer checks that can merge handlers (smaller code size at the expense of debuggability).
std::string StackUsageFile
Name of the stack usage file (i.e., .su file) if user passes -fstack-usage.
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.
bool hasDWARFExceptions() const
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.
std::string HLSLRecordCommandLine
The string containing the commandline for the dx.source.args metadata, if non-empty.
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 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
SanitizerSet SanitizeAnnotateDebugInfo
Set of sanitizer checks, for which the instrumentation will be annotated with extra debug info.
PointerAuthOptions PointerAuth
Configuration for pointer-signing.
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.
llvm::SmallVector< llvm::SmallString< 8 > > HLSLParsedCommandLine
The vector contains parsed commandline for the dx.source.args metadata, if parsing was successful.
bool hasSjLjExceptions() const
SanitizerMaskCutoffs SanitizeSkipHotCutoffs
Set of thresholds in a range [0.0, 1.0]: the top hottest code responsible for the given fraction of P...
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::optional< double > AllowRuntimeCheckSkipHotCutoff
std::vector< std::string > CommandLineArgs
bool hasSEHExceptions() const
void resetNonModularOptions(StringRef ModuleFormat)
Reset all of the options that are not considered when building a module.
@ NonZero
Convert in-memory bools to i1 by checking if any bit is set to 1.
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.
std::string SaveDynDbgTempsFilePrefix
Prefix to use for -save-dynamic-debugging-temps output.
The base class of CompilerInvocation.
std::shared_ptr< DiagnosticOptions > DiagnosticOpts
Options controlling the diagnostic engine.
std::shared_ptr< AnalyzerOptions > AnalyzerOpts
Options controlling the static analyzer.
std::shared_ptr< MigratorOptions > MigratorOpts
std::shared_ptr< PreprocessorOutputOptions > PreprocessorOutputOpts
Options controlling preprocessed output.
std::shared_ptr< APINotesOptions > APINotesOpts
Options controlling API notes.
std::shared_ptr< TargetOptions > TargetOpts
Options controlling the target.
const FrontendOptions & getFrontendOpts() const
std::shared_ptr< ssaf::SSAFOptions > SSAFOpts
Options controlling the Scalable Static Analysis Framework (SSAF).
const CodeGenOptions & getCodeGenOpts() const
llvm::function_ref< const char *(const Twine &)> StringAllocator
Command line generation.
const FileSystemOptions & getFileSystemOpts() const
std::shared_ptr< PreprocessorOptions > PPOpts
Options controlling the preprocessor (aside from #include handling).
const PreprocessorOutputOptions & getPreprocessorOutputOpts() const
const ssaf::SSAFOptions & getSSAFOpts() const
std::vector< std::string > getCC1CommandLine() const
Generate cc1-compatible command line arguments from this instance, wrapping the result as a std::vect...
std::shared_ptr< FileSystemOptions > FSOpts
Options controlling file system operations.
const AnalyzerOptions & getAnalyzerOpts() const
const MigratorOptions & getMigratorOpts() const
void generateCC1CommandLine(llvm::SmallVectorImpl< const char * > &Args, StringAllocator SA) const
Generate cc1-compatible command line arguments from this instance.
CompilerInvocationBase & deep_copy_assign(const CompilerInvocationBase &X)
const DependencyOutputOptions & getDependencyOutputOpts() const
CompilerInvocationBase & shallow_copy_assign(const CompilerInvocationBase &X)
const TargetOptions & getTargetOpts() const
std::shared_ptr< CodeGenOptions > CodeGenOpts
Options controlling IRgen and the backend.
std::shared_ptr< LangOptions > LangOpts
Options controlling the language variant.
const APINotesOptions & getAPINotesOpts() const
const HeaderSearchOptions & getHeaderSearchOpts() const
std::shared_ptr< HeaderSearchOptions > HSOpts
Options controlling the #include directive.
const PreprocessorOptions & getPreprocessorOpts() const
const DiagnosticOptions & getDiagnosticOpts() const
const LangOptions & getLangOpts() const
Const getters.
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.
PreprocessorOptions & getPreprocessorOpts()
void clearImplicitModuleBuildOptions()
Disable implicit modules and canonicalize options that are only used by implicit modules.
MigratorOptions & getMigratorOpts()
AnalyzerOptions & getAnalyzerOpts()
APINotesOptions & getAPINotesOpts()
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.
ssaf::SSAFOptions & getSSAFOpts()
LangOptions & getLangOpts()
Mutable getters.
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...
DependencyOutputOptions & getDependencyOutputOpts()
void resetNonModularOptions()
Reset all of the options that are not considered when building a module.
FrontendOptions & getFrontendOpts()
FileSystemOptions & getFileSystemOpts()
CompilerInvocation & operator=(const CompilerInvocation &X)
static void setDefaultPointerAuthOptions(PointerAuthOptions &Opts, const LangOptions &LangOpts, const llvm::Triple &Triple)
Populate Opts with the default set of pointer authentication-related options given LangOpts and Tripl...
CodeGenOptions & getCodeGenOpts()
std::string computeContextHash() const
Compute the context hash - a string that uniquely identifies compiler settings.
HeaderSearchOptions & getHeaderSearchOpts()
DiagnosticOptions & getDiagnosticOpts()
PreprocessorOutputOptions & getPreprocessorOutputOpts()
Same as CompilerInvocation, but with copy-on-write optimization.
LangOptions & getMutLangOpts()
Mutable getters.
HeaderSearchOptions & getMutHeaderSearchOpts()
PreprocessorOptions & getMutPreprocessorOpts()
PreprocessorOutputOptions & getMutPreprocessorOutputOpts()
FileSystemOptions & getMutFileSystemOpts()
void visitMutPaths(llvm::function_ref< VisitMutResult(StringRef, std::string &)> Cb)
Visits paths stored in the invocation, allowing the callback to mutate them via the out-param.
DiagnosticOptions & getMutDiagnosticOpts()
DependencyOutputOptions & getMutDependencyOutputOpts()
void visitPaths(llvm::function_ref< VisitConstResult(StringRef)> Cb) const
Visits paths stored in the invocation.
ssaf::SSAFOptions & getMutSSAFOpts()
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.
static llvm::IntrusiveRefCntPtr< DiagnosticIDs > create()
Options for controlling the compiler diagnostics engine.
std::string DiagnosticSuppressionMappingsFile
Path for the file that defines diagnostic suppression mappings.
std::vector< std::string > Remarks
The list of -R... options used to alter the diagnostic mappings, with the prefixes removed.
std::vector< std::string > Warnings
The list of -W... options used to alter the diagnostic mappings, with the prefixes removed.
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.
Definition Diagnostic.h:240
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
void setClient(DiagnosticConsumer *client, bool ShouldOwnClient=true)
Set the diagnostic client associated with this diagnostic object.
unsigned getNumErrors() const
Definition Diagnostic.h:937
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
unsigned getNumWarnings() const
Definition Diagnostic.h:938
Keeps track of options that affect how file operations are performed.
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.
unsigned ClangIRDisablePasses
Disable Clang IR specific (CIR) passes.
llvm::TimeTraceCompression TimeTraceCompress
Compression mode for -ftime-trace output.
std::map< std::string, std::vector< std::string > > PluginArgs
Args to pass to the plugins.
unsigned ClangIRDisableCIRVerifier
Disable Clang IR (CIR) verifier.
unsigned IsSystemModule
When using -emit-module, treat the modulemap as a system module.
unsigned ClangIRLibOptEnabled
Enable ClangIR library optimization.
std::string TimeTracePath
Path which stores the output files for -ftime-trace.
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.
unsigned GenReducedBMI
Whether to generate reduced BMI for C++20 named modules.
std::string ActionName
The name of the action to run when using a plugin action.
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/SYCL compilation.
unsigned UseGlobalModuleIndex
Whether we can use the global module index if available.
unsigned ASTDumpDecls
Whether we include declaration dumps in AST dumps.
HeaderSearchOptions - Helper class for storing options related to the initialization of the HeaderSea...
unsigned ModulesStrictContextHash
Whether we should include all things that could impact the module in the hash.
void AddPath(StringRef Path, frontend::IncludeDirGroup Group, bool IsFramework, bool IgnoreSysRoot)
AddPath - Add the Path path to the specified Group list.
unsigned ModuleCachePruneInterval
The interval (in seconds) between pruning operations.
std::map< std::string, std::string, std::less<> > PrebuiltModuleFiles
The mapping of module names to prebuilt module files.
uint64_t BuildSessionTimestamp
The time in seconds when the build session started.
std::vector< std::string > PrebuiltModulePaths
The directories used to load prebuilt module files.
unsigned ModulesSkipHeaderSearchPaths
Whether to entirely skip writing header search paths.
unsigned ImplicitModuleMaps
Implicit module maps.
void AddSystemHeaderPrefix(StringRef Prefix, bool IsSystemHeader)
AddSystemHeaderPrefix - Override whether #include directives naming a path starting with Prefix shoul...
std::vector< SystemHeaderPrefix > SystemHeaderPrefixes
User-specified system header prefixes.
std::string ModuleFormat
The module/pch container format.
std::string Sysroot
If non-empty, the directory to use as a "virtual system root" for include paths.
unsigned ModulesSkipDiagnosticOptions
Whether to entirely skip writing diagnostic options.
llvm::SmallSetVector< llvm::CachedHashString, 16 > ModulesIgnoreMacros
The set of macro names that should be ignored by implicitly-built modules.
std::string ModuleCachePath
The directory used for the module cache.
std::string ModuleUserBuildPath
The directory used for a user build.
std::vector< std::string > VFSOverlayFiles
The set of user-provided virtual filesystem overlay files.
unsigned UseLibcxx
Use libc++ instead of the default libstdc++.
unsigned UseBuiltinIncludes
Include the compiler builtin includes.
unsigned UseStandardCXXIncludes
Include the system standard C++ library include search directories.
unsigned UseDebugInfo
Whether the module includes debug information (-gmodules).
std::vector< Entry > UserEntries
User specified include entries.
std::string ResourceDir
The directory which holds the compiler resource files (builtin includes, etc.).
void AddPrebuiltModulePath(StringRef Name)
unsigned UseStandardSystemIncludes
Include the system standard include search directories.
void AddVFSOverlayFile(StringRef Name)
llvm::SmallSetVector< llvm::CachedHashString, 16 > ModulesIgnoreSearchPaths
The set of header search paths that should be ignored by implicitly-built modules.
unsigned ModulesValidateOncePerBuildSession
If true, skip verifying input files used by modules if the module was already verified during this bu...
unsigned ModulesValidateDirectoryDependencies
Whether to treat an implicitly built module as out of date when a directory it depends on the listing...
unsigned ModuleCachePruneAfter
The time (in seconds) after which an unused module file will be considered unused and will,...
A diagnostic client that ignores all diagnostics.
The kind of a file that we've been handed as an input.
bool isPreprocessed() const
InputKind withHeaderUnit(HeaderUnitKind HU) const
bool isUnknown() const
Is the input kind fully-unknown?
InputKind getPreprocessed() const
Format getFormat() const
HeaderUnitKind getHeaderUnitKind() const
InputKind getHeader() const
InputKind withFormat(Format F) const
Language getLanguage() const
@ 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.
@ None
Don't exclude any overflow patterns from sanitizers.
@ AddUnsignedOverflowTest
if (a + b < a)
@ All
Exclude all overflow patterns (below)
@ AddSignedOverflowTest
if (a + b < a)
@ PostDecrInWhile
while (count–)
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
SanitizerSet UBSanFeatureIgnoredSanitize
Set of (UBSan) sanitizers that when enabled do not cause __has_feature(undefined_behavior_sanitizer) ...
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::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.
unsigned OverflowPatternExclusionMask
Which overflow patterns should be excluded from sanitizer instrumentation.
SanitizerSet Sanitize
Set of enabled sanitizers.
std::optional< llvm::AllocTokenMode > AllocTokenMode
The allocation token mode.
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 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().
bool isTargetDevice() const
True when compiling for an offloading target device.
std::optional< uint64_t > AllocTokenMax
Maximum number of allocation tokens (0 = target SIZE_MAX), nullopt if none set (use target SIZE_MAX).
LangStandard::Kind LangStd
The used language standard.
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.
Definition ObjCRuntime.h:28
bool allowsWeak() const
Does this runtime allow the use of __weak?
Kind getKind() const
Definition ObjCRuntime.h:77
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...
Definition ObjCRuntime.h:40
Discrimination
Forms of extra discrimination.
ARM8_3Key
Hardware pointer-signing keys in ARM8.3.
static constexpr std::optional< PositiveAnalyzerOption > create(unsigned Val)
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 separ...
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...
std::vector< std::string > EmbedEntries
User specified embed entries.
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 beginnin...
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 const auto & getSpelling(Kind ABIKind)
static bool usesRelativeVTables(const llvm::Triple &T)
static bool isABI(StringRef Name)
Kind getKind() const
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.
AMDGPUFeatureState AMDGPUSramEccState
AMDGPU sramecc setting from -msramecc/-mno-sramecc.
llvm::VersionTuple DarwinTargetVariantSDKVersion
The version of the darwin target variant SDK which was used during the compilation.
AMDGPUFeatureState AMDGPUXnackState
AMDGPU xnack setting from -mxnack/-mno-xnack.
std::string HostTriple
When compiling for the device side, contains the triple used to compile for the host.
@ Enabled
Feature explicitly enabled.
@ Disabled
Feature explicitly disabled.
Value()=default
constexpr XRayInstrMask None
Definition XRayInstr.h:38
constexpr XRayInstrMask All
Definition XRayInstr.h:43
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
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.
@ 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.
@ EmitBC
Emit a .bc file.
@ 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.
@ InitOnly
Only execute frontend initialization.
@ ASTView
Parse ASTs and view them in Graphviz.
@ PluginAction
Run a plugin action,.
@ EmitObj
Emit a .o file.
@ 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.
@ EmitCIRBC
Emit a .cirbc file (ClangIR bytecode).
@ 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.
bool EQ(InterpState &S, CodePtr OpPC)
Definition Interp.h:1451
const unsigned VERSION_MINOR
AST file minor version number supported by this version of Clang.
Definition ASTBitCodes.h:57
const unsigned VERSION_MAJOR
AST file major version number supported by this version of Clang.
Definition ASTBitCodes.h:47
Top level wrappers for InstallAPI frontend operations.
ASTDumpOutputFormat
Used to specify the format for printing AST dump information.
bool ParseDiagnosticArgs(DiagnosticOptions &Opts, llvm::opt::ArgList &Args, DiagnosticsEngine *Diags=nullptr, bool DefaultDiagColor=true)
Fill out Opts based on the options given in Args.
SanitizerMask getPPTransparentSanitizers()
Return the sanitizers which do not affect preprocessing.
Definition Sanitizers.h:230
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.
const char * headerIncludeFormatKindToString(HeaderIncludeFormatKind K)
std::unique_ptr< DiagnosticOptions > CreateAndPopulateDiagOpts(ArrayRef< const char * > Argv)
constexpr uint16_t BlockDescriptorConstantDiscriminator
Constant discriminator to be used with block descriptor pointers.
constexpr uint16_t IsaPointerConstantDiscriminator
Constant discriminator to be used with objective-c isa pointers.
const char * headerIncludeFilteringKindToString(HeaderIncludeFilteringKind K)
AnalysisConstraints
AnalysisConstraints - Set of available constraint models.
@ Success
Annotation was successful.
Definition Parser.h:65
@ Parse
Parse the block; this code is always used.
Definition Parser.h:137
constexpr uint16_t SuperPointerConstantDiscriminator
Constant discriminator to be used with objective-c superclass pointers.
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].
Definition CharInfo.h:132
LLVM_READONLY bool isAlphanumeric(unsigned char c)
Return true if this character is an ASCII letter or digit: [a-zA-Z0-9].
Definition CharInfo.h:138
constexpr uint16_t MethodListPointerConstantDiscriminator
Constant discriminator to be used with method list pointers.
constexpr uint16_t ClassROConstantDiscriminator
Constant discriminator to be used with objective-c class_ro_t pointers.
@ 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.
@ Default
Set to the current date and time.
bool parseSanitizerWeightedValue(StringRef Value, bool AllowGroups, SanitizerMaskCutoffs &Cutoffs)
Parse a single weighted value (e.g., 'undefined=0.05') from a -fsanitize= or -fno-sanitize= value lis...
@ Result
The result type of a method or function.
Definition TypeBase.h:906
unsigned getOptimizationLevel(const llvm::opt::ArgList &Args, InputKind IK, DiagnosticsEngine &Diags)
XRayInstrMask parseXRayInstrValue(StringRef Value)
Parses a command line argument into a mask.
Definition XRayInstr.cpp:19
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.
Definition XRayInstr.cpp:34
unsigned getOptimizationLevelSize(const llvm::opt::ArgList &Args)
AnalysisPurgeMode
AnalysisPurgeModes - Set of available strategies for dead symbol removal.
llvm::Expected< llvm::SmallVector< llvm::SmallString< 8 > > > parseEscapedCommandLine(const char *CommandLine)
Parse a space-separated command line with escaped spaces and backslashes.
void serializeSanitizerMaskCutoffs(const SanitizerMaskCutoffs &Cutoffs, SmallVectorImpl< std::string > &Values)
Serialize a SanitizerMaskCutoffs into command line arguments.
ShowColorsKind
Controls whether to show colors in diagnostic output.
@ Auto
Emit colors only if the output stream is detected to support them.
@ On
Always emit colors regardless of the output stream.
@ Off
Never emit colors regardless of the output stream.
ShaderStage
Shader programs run in specific pipeline stages.
Definition LangOptions.h:45
constexpr uint16_t StdTypeInfoVTablePointerConstantDiscrimination
Constant discriminator for std::type_info vtable pointers: 0xB1EA/45546 The value is ptrauth_string_d...
SanitizerMask parseSanitizerValue(StringRef Value, bool AllowGroups)
Parse a single value from a -fsanitize= or -fno-sanitize= value list.
const llvm::opt::OptTable & getDriverOptTable()
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...
Definition Version.cpp:68
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.
AnalysisInliningMode
AnalysisInlineFunctionSelection - Set of inlining function selection heuristics.
@ NumInliningModes
@ HIFMT_Textual
int const char * function
Definition c++config.h:31
__DEVICE__ _Tp arg(const std::complex< _Tp > &__c)
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 unsigned
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 uint64_t
Optimization remark with an optional regular expression pattern.
bool hasValidPattern() const
Returns true iff the optimization remark holds a valid regular expression.
Dummy tag type whose instance can be passed into the constructor to prevent creation of the reference...
unsigned IgnoreSysRoot
IgnoreSysRoot - This is false if an absolute path should be treated relative to the sysroot,...
LangStandard - Information about the properties of a particular language standard.
clang::Language getLanguage() const
Get the language that this standard describes.
const char * getDescription() const
getDescription - Get the description of this standard.
static const LangStandard & getLangStandardForKind(Kind K)
const char * getName() const
getName - Get the name of this standard.
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.
PointerAuthSchema BlockDescriptorPointers
The ABI for pointers to block descriptors.
PointerAuthSchema BlockHelperFunctionPointers
The ABI for block object copy/destroy function pointers.
PointerAuthSchema CXXVTablePointers
The ABI for C++ virtual table pointers (the pointer to the table itself) as installed in an actual cl...
PointerAuthSchema BlockInvocationFunctionPointers
The ABI for block invocation function pointers.
PointerAuthSchema BlockByrefHelperFunctionPointers
The ABI for __block variable copy/destroy function pointers.
PointerAuthSchema CXXVTTVTablePointers
The ABI for C++ virtual table pointers as installed in a VTT.
bool ReturnAddresses
Should return addresses be authenticated?
PointerAuthSchema CXXTypeInfoVTablePointer
TypeInfo has external ABI requirements and is emitted without actually having parsed the libcxx defin...
bool AArch64JumpTableHardening
Use hardened lowering for jump-table dispatch?
PointerAuthSchema ObjCMethodListPointer
The ABI for a reference to an Objective-C method list in _class_ro_t.
PointerAuthSchema FunctionPointers
The ABI for C function pointers.
PointerAuthSchema ObjCSuperPointers
The ABI for Objective-C superclass pointers.
bool AuthTraps
Do authentication failures cause a trap?
PointerAuthSchema CXXMemberFunctionPointers
The ABI for C++ member function pointers.
PointerAuthSchema CXXVirtualVariadicFunctionPointers
The ABI for variadic C++ virtual function pointers.
PointerAuthSchema ObjCMethodListFunctionPointers
The ABI for Objective-C method lists.
PointerAuthSchema ObjCClassROPointers
The ABI for Objective-C class_ro_t pointers.
PointerAuthSchema CXXVirtualFunctionPointers
The ABI for most C++ virtual function pointers, i.e. v-table entries.
PointerAuthSchema ObjCIsaPointers
The ABI for Objective-C isa pointers.
bool IndirectGotos
Do indirect goto label addresses need to be authenticated?
void clear(SanitizerMask K=SanitizerKind::All)
Disable the sanitizers specified in K.
Definition Sanitizers.h:195
void set(SanitizerMask K, bool Value)
Enable or disable a certain (single) sanitizer.
Definition Sanitizers.h:187
bool empty() const
Returns true if no sanitizers are enabled.
Definition Sanitizers.h:198
SanitizerMask Mask
Bitmask of enabled sanitizers.
Definition Sanitizers.h:201
XRayInstrMask Mask
Definition XRayInstr.h:65
void set(XRayInstrMask K, bool Value)
Definition XRayInstr.h:55