[clang][modules] Don't prevent translation of FW_Private includes when explicitly...
[llvm-project.git] / clang / lib / Frontend / CompilerInvocation.cpp
blobfd6c250efeda2a8d57cb9caaba0f0865ea07a40c
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 //===----------------------------------------------------------------------===//
9 #include "clang/Frontend/CompilerInvocation.h"
10 #include "TestModuleFileExtension.h"
11 #include "clang/Basic/Builtins.h"
12 #include "clang/Basic/CharInfo.h"
13 #include "clang/Basic/CodeGenOptions.h"
14 #include "clang/Basic/CommentOptions.h"
15 #include "clang/Basic/Diagnostic.h"
16 #include "clang/Basic/DiagnosticDriver.h"
17 #include "clang/Basic/DiagnosticOptions.h"
18 #include "clang/Basic/FileSystemOptions.h"
19 #include "clang/Basic/LLVM.h"
20 #include "clang/Basic/LangOptions.h"
21 #include "clang/Basic/LangStandard.h"
22 #include "clang/Basic/ObjCRuntime.h"
23 #include "clang/Basic/Sanitizers.h"
24 #include "clang/Basic/SourceLocation.h"
25 #include "clang/Basic/TargetOptions.h"
26 #include "clang/Basic/Version.h"
27 #include "clang/Basic/Visibility.h"
28 #include "clang/Basic/XRayInstr.h"
29 #include "clang/Config/config.h"
30 #include "clang/Driver/Driver.h"
31 #include "clang/Driver/DriverDiagnostic.h"
32 #include "clang/Driver/Options.h"
33 #include "clang/Frontend/CommandLineSourceLoc.h"
34 #include "clang/Frontend/DependencyOutputOptions.h"
35 #include "clang/Frontend/FrontendDiagnostic.h"
36 #include "clang/Frontend/FrontendOptions.h"
37 #include "clang/Frontend/FrontendPluginRegistry.h"
38 #include "clang/Frontend/MigratorOptions.h"
39 #include "clang/Frontend/PreprocessorOutputOptions.h"
40 #include "clang/Frontend/TextDiagnosticBuffer.h"
41 #include "clang/Frontend/Utils.h"
42 #include "clang/Lex/HeaderSearchOptions.h"
43 #include "clang/Lex/PreprocessorOptions.h"
44 #include "clang/Sema/CodeCompleteOptions.h"
45 #include "clang/Serialization/ASTBitCodes.h"
46 #include "clang/Serialization/ModuleFileExtension.h"
47 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
48 #include "llvm/ADT/APInt.h"
49 #include "llvm/ADT/ArrayRef.h"
50 #include "llvm/ADT/CachedHashString.h"
51 #include "llvm/ADT/DenseSet.h"
52 #include "llvm/ADT/FloatingPointMode.h"
53 #include "llvm/ADT/Hashing.h"
54 #include "llvm/ADT/STLExtras.h"
55 #include "llvm/ADT/SmallString.h"
56 #include "llvm/ADT/SmallVector.h"
57 #include "llvm/ADT/StringRef.h"
58 #include "llvm/ADT/StringSwitch.h"
59 #include "llvm/ADT/Twine.h"
60 #include "llvm/Config/llvm-config.h"
61 #include "llvm/Frontend/Debug/Options.h"
62 #include "llvm/IR/DebugInfoMetadata.h"
63 #include "llvm/Linker/Linker.h"
64 #include "llvm/MC/MCTargetOptions.h"
65 #include "llvm/Option/Arg.h"
66 #include "llvm/Option/ArgList.h"
67 #include "llvm/Option/OptSpecifier.h"
68 #include "llvm/Option/OptTable.h"
69 #include "llvm/Option/Option.h"
70 #include "llvm/ProfileData/InstrProfReader.h"
71 #include "llvm/Remarks/HotnessThresholdParser.h"
72 #include "llvm/Support/CodeGen.h"
73 #include "llvm/Support/Compiler.h"
74 #include "llvm/Support/Error.h"
75 #include "llvm/Support/ErrorHandling.h"
76 #include "llvm/Support/ErrorOr.h"
77 #include "llvm/Support/FileSystem.h"
78 #include "llvm/Support/HashBuilder.h"
79 #include "llvm/Support/MathExtras.h"
80 #include "llvm/Support/MemoryBuffer.h"
81 #include "llvm/Support/Path.h"
82 #include "llvm/Support/Process.h"
83 #include "llvm/Support/Regex.h"
84 #include "llvm/Support/VersionTuple.h"
85 #include "llvm/Support/VirtualFileSystem.h"
86 #include "llvm/Support/raw_ostream.h"
87 #include "llvm/Target/TargetOptions.h"
88 #include "llvm/TargetParser/Host.h"
89 #include "llvm/TargetParser/Triple.h"
90 #include <algorithm>
91 #include <atomic>
92 #include <cassert>
93 #include <cstddef>
94 #include <cstring>
95 #include <ctime>
96 #include <fstream>
97 #include <limits>
98 #include <memory>
99 #include <optional>
100 #include <string>
101 #include <tuple>
102 #include <type_traits>
103 #include <utility>
104 #include <vector>
106 using namespace clang;
107 using namespace driver;
108 using namespace options;
109 using namespace llvm::opt;
111 //===----------------------------------------------------------------------===//
112 // Helpers.
113 //===----------------------------------------------------------------------===//
115 // Parse misexpect tolerance argument value.
116 // Valid option values are integers in the range [0, 100)
117 static Expected<std::optional<uint32_t>> parseToleranceOption(StringRef Arg) {
118 uint32_t Val;
119 if (Arg.getAsInteger(10, Val))
120 return llvm::createStringError(llvm::inconvertibleErrorCode(),
121 "Not an integer: %s", Arg.data());
122 return Val;
125 //===----------------------------------------------------------------------===//
126 // Initialization.
127 //===----------------------------------------------------------------------===//
129 namespace {
130 template <class T> std::shared_ptr<T> make_shared_copy(const T &X) {
131 return std::make_shared<T>(X);
134 template <class T>
135 llvm::IntrusiveRefCntPtr<T> makeIntrusiveRefCntCopy(const T &X) {
136 return llvm::makeIntrusiveRefCnt<T>(X);
138 } // namespace
140 CompilerInvocationBase::CompilerInvocationBase()
141 : LangOpts(std::make_shared<LangOptions>()),
142 TargetOpts(std::make_shared<TargetOptions>()),
143 DiagnosticOpts(llvm::makeIntrusiveRefCnt<DiagnosticOptions>()),
144 HSOpts(std::make_shared<HeaderSearchOptions>()),
145 PPOpts(std::make_shared<PreprocessorOptions>()),
146 AnalyzerOpts(llvm::makeIntrusiveRefCnt<AnalyzerOptions>()),
147 MigratorOpts(std::make_shared<MigratorOptions>()),
148 CodeGenOpts(std::make_shared<CodeGenOptions>()),
149 FSOpts(std::make_shared<FileSystemOptions>()),
150 FrontendOpts(std::make_shared<FrontendOptions>()),
151 DependencyOutputOpts(std::make_shared<DependencyOutputOptions>()),
152 PreprocessorOutputOpts(std::make_shared<PreprocessorOutputOptions>()) {}
154 CompilerInvocationBase &
155 CompilerInvocationBase::deep_copy_assign(const CompilerInvocationBase &X) {
156 if (this != &X) {
157 LangOpts = make_shared_copy(X.getLangOpts());
158 TargetOpts = make_shared_copy(X.getTargetOpts());
159 DiagnosticOpts = makeIntrusiveRefCntCopy(X.getDiagnosticOpts());
160 HSOpts = make_shared_copy(X.getHeaderSearchOpts());
161 PPOpts = make_shared_copy(X.getPreprocessorOpts());
162 AnalyzerOpts = makeIntrusiveRefCntCopy(X.getAnalyzerOpts());
163 MigratorOpts = make_shared_copy(X.getMigratorOpts());
164 CodeGenOpts = make_shared_copy(X.getCodeGenOpts());
165 FSOpts = make_shared_copy(X.getFileSystemOpts());
166 FrontendOpts = make_shared_copy(X.getFrontendOpts());
167 DependencyOutputOpts = make_shared_copy(X.getDependencyOutputOpts());
168 PreprocessorOutputOpts = make_shared_copy(X.getPreprocessorOutputOpts());
170 return *this;
173 CompilerInvocationBase &
174 CompilerInvocationBase::shallow_copy_assign(const CompilerInvocationBase &X) {
175 if (this != &X) {
176 LangOpts = X.LangOpts;
177 TargetOpts = X.TargetOpts;
178 DiagnosticOpts = X.DiagnosticOpts;
179 HSOpts = X.HSOpts;
180 PPOpts = X.PPOpts;
181 AnalyzerOpts = X.AnalyzerOpts;
182 MigratorOpts = X.MigratorOpts;
183 CodeGenOpts = X.CodeGenOpts;
184 FSOpts = X.FSOpts;
185 FrontendOpts = X.FrontendOpts;
186 DependencyOutputOpts = X.DependencyOutputOpts;
187 PreprocessorOutputOpts = X.PreprocessorOutputOpts;
189 return *this;
192 namespace {
193 template <typename T>
194 T &ensureOwned(std::shared_ptr<T> &Storage) {
195 if (Storage.use_count() > 1)
196 Storage = std::make_shared<T>(*Storage);
197 return *Storage;
200 template <typename T>
201 T &ensureOwned(llvm::IntrusiveRefCntPtr<T> &Storage) {
202 if (Storage.useCount() > 1)
203 Storage = llvm::makeIntrusiveRefCnt<T>(*Storage);
204 return *Storage;
206 } // namespace
208 LangOptions &CowCompilerInvocation::getMutLangOpts() {
209 return ensureOwned(LangOpts);
212 TargetOptions &CowCompilerInvocation::getMutTargetOpts() {
213 return ensureOwned(TargetOpts);
216 DiagnosticOptions &CowCompilerInvocation::getMutDiagnosticOpts() {
217 return ensureOwned(DiagnosticOpts);
220 HeaderSearchOptions &CowCompilerInvocation::getMutHeaderSearchOpts() {
221 return ensureOwned(HSOpts);
224 PreprocessorOptions &CowCompilerInvocation::getMutPreprocessorOpts() {
225 return ensureOwned(PPOpts);
228 AnalyzerOptions &CowCompilerInvocation::getMutAnalyzerOpts() {
229 return ensureOwned(AnalyzerOpts);
232 MigratorOptions &CowCompilerInvocation::getMutMigratorOpts() {
233 return ensureOwned(MigratorOpts);
236 CodeGenOptions &CowCompilerInvocation::getMutCodeGenOpts() {
237 return ensureOwned(CodeGenOpts);
240 FileSystemOptions &CowCompilerInvocation::getMutFileSystemOpts() {
241 return ensureOwned(FSOpts);
244 FrontendOptions &CowCompilerInvocation::getMutFrontendOpts() {
245 return ensureOwned(FrontendOpts);
248 DependencyOutputOptions &CowCompilerInvocation::getMutDependencyOutputOpts() {
249 return ensureOwned(DependencyOutputOpts);
252 PreprocessorOutputOptions &
253 CowCompilerInvocation::getMutPreprocessorOutputOpts() {
254 return ensureOwned(PreprocessorOutputOpts);
257 //===----------------------------------------------------------------------===//
258 // Normalizers
259 //===----------------------------------------------------------------------===//
261 using ArgumentConsumer = CompilerInvocation::ArgumentConsumer;
263 #define SIMPLE_ENUM_VALUE_TABLE
264 #include "clang/Driver/Options.inc"
265 #undef SIMPLE_ENUM_VALUE_TABLE
267 static std::optional<bool> normalizeSimpleFlag(OptSpecifier Opt,
268 unsigned TableIndex,
269 const ArgList &Args,
270 DiagnosticsEngine &Diags) {
271 if (Args.hasArg(Opt))
272 return true;
273 return std::nullopt;
276 static std::optional<bool> normalizeSimpleNegativeFlag(OptSpecifier Opt,
277 unsigned,
278 const ArgList &Args,
279 DiagnosticsEngine &) {
280 if (Args.hasArg(Opt))
281 return false;
282 return std::nullopt;
285 /// The tblgen-erated code passes in a fifth parameter of an arbitrary type, but
286 /// denormalizeSimpleFlags never looks at it. Avoid bloating compile-time with
287 /// unnecessary template instantiations and just ignore it with a variadic
288 /// argument.
289 static void denormalizeSimpleFlag(ArgumentConsumer Consumer,
290 const Twine &Spelling, Option::OptionClass,
291 unsigned, /*T*/...) {
292 Consumer(Spelling);
295 template <typename T> static constexpr bool is_uint64_t_convertible() {
296 return !std::is_same_v<T, uint64_t> && llvm::is_integral_or_enum<T>::value;
299 template <typename T,
300 std::enable_if_t<!is_uint64_t_convertible<T>(), bool> = false>
301 static auto makeFlagToValueNormalizer(T Value) {
302 return [Value](OptSpecifier Opt, unsigned, const ArgList &Args,
303 DiagnosticsEngine &) -> std::optional<T> {
304 if (Args.hasArg(Opt))
305 return Value;
306 return std::nullopt;
310 template <typename T,
311 std::enable_if_t<is_uint64_t_convertible<T>(), bool> = false>
312 static auto makeFlagToValueNormalizer(T Value) {
313 return makeFlagToValueNormalizer(uint64_t(Value));
316 static auto makeBooleanOptionNormalizer(bool Value, bool OtherValue,
317 OptSpecifier OtherOpt) {
318 return [Value, OtherValue,
319 OtherOpt](OptSpecifier Opt, unsigned, const ArgList &Args,
320 DiagnosticsEngine &) -> std::optional<bool> {
321 if (const Arg *A = Args.getLastArg(Opt, OtherOpt)) {
322 return A->getOption().matches(Opt) ? Value : OtherValue;
324 return std::nullopt;
328 static auto makeBooleanOptionDenormalizer(bool Value) {
329 return [Value](ArgumentConsumer Consumer, const Twine &Spelling,
330 Option::OptionClass, unsigned, bool KeyPath) {
331 if (KeyPath == Value)
332 Consumer(Spelling);
336 static void denormalizeStringImpl(ArgumentConsumer Consumer,
337 const Twine &Spelling,
338 Option::OptionClass OptClass, unsigned,
339 const Twine &Value) {
340 switch (OptClass) {
341 case Option::SeparateClass:
342 case Option::JoinedOrSeparateClass:
343 case Option::JoinedAndSeparateClass:
344 Consumer(Spelling);
345 Consumer(Value);
346 break;
347 case Option::JoinedClass:
348 case Option::CommaJoinedClass:
349 Consumer(Spelling + Value);
350 break;
351 default:
352 llvm_unreachable("Cannot denormalize an option with option class "
353 "incompatible with string denormalization.");
357 template <typename T>
358 static void denormalizeString(ArgumentConsumer Consumer, const Twine &Spelling,
359 Option::OptionClass OptClass, unsigned TableIndex,
360 T Value) {
361 denormalizeStringImpl(Consumer, Spelling, OptClass, TableIndex, Twine(Value));
364 static std::optional<SimpleEnumValue>
365 findValueTableByName(const SimpleEnumValueTable &Table, StringRef Name) {
366 for (int I = 0, E = Table.Size; I != E; ++I)
367 if (Name == Table.Table[I].Name)
368 return Table.Table[I];
370 return std::nullopt;
373 static std::optional<SimpleEnumValue>
374 findValueTableByValue(const SimpleEnumValueTable &Table, unsigned Value) {
375 for (int I = 0, E = Table.Size; I != E; ++I)
376 if (Value == Table.Table[I].Value)
377 return Table.Table[I];
379 return std::nullopt;
382 static std::optional<unsigned> normalizeSimpleEnum(OptSpecifier Opt,
383 unsigned TableIndex,
384 const ArgList &Args,
385 DiagnosticsEngine &Diags) {
386 assert(TableIndex < SimpleEnumValueTablesSize);
387 const SimpleEnumValueTable &Table = SimpleEnumValueTables[TableIndex];
389 auto *Arg = Args.getLastArg(Opt);
390 if (!Arg)
391 return std::nullopt;
393 StringRef ArgValue = Arg->getValue();
394 if (auto MaybeEnumVal = findValueTableByName(Table, ArgValue))
395 return MaybeEnumVal->Value;
397 Diags.Report(diag::err_drv_invalid_value)
398 << Arg->getAsString(Args) << ArgValue;
399 return std::nullopt;
402 static void denormalizeSimpleEnumImpl(ArgumentConsumer Consumer,
403 const Twine &Spelling,
404 Option::OptionClass OptClass,
405 unsigned TableIndex, unsigned Value) {
406 assert(TableIndex < SimpleEnumValueTablesSize);
407 const SimpleEnumValueTable &Table = SimpleEnumValueTables[TableIndex];
408 if (auto MaybeEnumVal = findValueTableByValue(Table, Value)) {
409 denormalizeString(Consumer, Spelling, OptClass, TableIndex,
410 MaybeEnumVal->Name);
411 } else {
412 llvm_unreachable("The simple enum value was not correctly defined in "
413 "the tablegen option description");
417 template <typename T>
418 static void denormalizeSimpleEnum(ArgumentConsumer Consumer,
419 const Twine &Spelling,
420 Option::OptionClass OptClass,
421 unsigned TableIndex, T Value) {
422 return denormalizeSimpleEnumImpl(Consumer, Spelling, OptClass, TableIndex,
423 static_cast<unsigned>(Value));
426 static std::optional<std::string> normalizeString(OptSpecifier Opt,
427 int TableIndex,
428 const ArgList &Args,
429 DiagnosticsEngine &Diags) {
430 auto *Arg = Args.getLastArg(Opt);
431 if (!Arg)
432 return std::nullopt;
433 return std::string(Arg->getValue());
436 template <typename IntTy>
437 static std::optional<IntTy> normalizeStringIntegral(OptSpecifier Opt, int,
438 const ArgList &Args,
439 DiagnosticsEngine &Diags) {
440 auto *Arg = Args.getLastArg(Opt);
441 if (!Arg)
442 return std::nullopt;
443 IntTy Res;
444 if (StringRef(Arg->getValue()).getAsInteger(0, Res)) {
445 Diags.Report(diag::err_drv_invalid_int_value)
446 << Arg->getAsString(Args) << Arg->getValue();
447 return std::nullopt;
449 return Res;
452 static std::optional<std::vector<std::string>>
453 normalizeStringVector(OptSpecifier Opt, int, const ArgList &Args,
454 DiagnosticsEngine &) {
455 return Args.getAllArgValues(Opt);
458 static void denormalizeStringVector(ArgumentConsumer Consumer,
459 const Twine &Spelling,
460 Option::OptionClass OptClass,
461 unsigned TableIndex,
462 const std::vector<std::string> &Values) {
463 switch (OptClass) {
464 case Option::CommaJoinedClass: {
465 std::string CommaJoinedValue;
466 if (!Values.empty()) {
467 CommaJoinedValue.append(Values.front());
468 for (const std::string &Value : llvm::drop_begin(Values, 1)) {
469 CommaJoinedValue.append(",");
470 CommaJoinedValue.append(Value);
473 denormalizeString(Consumer, Spelling, Option::OptionClass::JoinedClass,
474 TableIndex, CommaJoinedValue);
475 break;
477 case Option::JoinedClass:
478 case Option::SeparateClass:
479 case Option::JoinedOrSeparateClass:
480 for (const std::string &Value : Values)
481 denormalizeString(Consumer, Spelling, OptClass, TableIndex, Value);
482 break;
483 default:
484 llvm_unreachable("Cannot denormalize an option with option class "
485 "incompatible with string vector denormalization.");
489 static std::optional<std::string> normalizeTriple(OptSpecifier Opt,
490 int TableIndex,
491 const ArgList &Args,
492 DiagnosticsEngine &Diags) {
493 auto *Arg = Args.getLastArg(Opt);
494 if (!Arg)
495 return std::nullopt;
496 return llvm::Triple::normalize(Arg->getValue());
499 template <typename T, typename U>
500 static T mergeForwardValue(T KeyPath, U Value) {
501 return static_cast<T>(Value);
504 template <typename T, typename U> static T mergeMaskValue(T KeyPath, U Value) {
505 return KeyPath | Value;
508 template <typename T> static T extractForwardValue(T KeyPath) {
509 return KeyPath;
512 template <typename T, typename U, U Value>
513 static T extractMaskValue(T KeyPath) {
514 return ((KeyPath & Value) == Value) ? static_cast<T>(Value) : T();
517 #define PARSE_OPTION_WITH_MARSHALLING( \
518 ARGS, DIAGS, PREFIX_TYPE, SPELLING, ID, KIND, GROUP, ALIAS, ALIASARGS, \
519 FLAGS, VISIBILITY, PARAM, HELPTEXT, METAVAR, VALUES, SHOULD_PARSE, \
520 ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, \
521 NORMALIZER, DENORMALIZER, MERGER, EXTRACTOR, TABLE_INDEX) \
522 if ((VISIBILITY)&options::CC1Option) { \
523 KEYPATH = MERGER(KEYPATH, DEFAULT_VALUE); \
524 if (IMPLIED_CHECK) \
525 KEYPATH = MERGER(KEYPATH, IMPLIED_VALUE); \
526 if (SHOULD_PARSE) \
527 if (auto MaybeValue = NORMALIZER(OPT_##ID, TABLE_INDEX, ARGS, DIAGS)) \
528 KEYPATH = \
529 MERGER(KEYPATH, static_cast<decltype(KEYPATH)>(*MaybeValue)); \
532 // Capture the extracted value as a lambda argument to avoid potential issues
533 // with lifetime extension of the reference.
534 #define GENERATE_OPTION_WITH_MARSHALLING( \
535 CONSUMER, PREFIX_TYPE, SPELLING, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, \
536 VISIBILITY, PARAM, HELPTEXT, METAVAR, VALUES, SHOULD_PARSE, ALWAYS_EMIT, \
537 KEYPATH, DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, \
538 DENORMALIZER, MERGER, EXTRACTOR, TABLE_INDEX) \
539 if ((VISIBILITY)&options::CC1Option) { \
540 [&](const auto &Extracted) { \
541 if (ALWAYS_EMIT || \
542 (Extracted != \
543 static_cast<decltype(KEYPATH)>((IMPLIED_CHECK) ? (IMPLIED_VALUE) \
544 : (DEFAULT_VALUE)))) \
545 DENORMALIZER(CONSUMER, SPELLING, Option::KIND##Class, TABLE_INDEX, \
546 Extracted); \
547 }(EXTRACTOR(KEYPATH)); \
550 static StringRef GetInputKindName(InputKind IK);
552 static bool FixupInvocation(CompilerInvocation &Invocation,
553 DiagnosticsEngine &Diags, const ArgList &Args,
554 InputKind IK) {
555 unsigned NumErrorsBefore = Diags.getNumErrors();
557 LangOptions &LangOpts = Invocation.getLangOpts();
558 CodeGenOptions &CodeGenOpts = Invocation.getCodeGenOpts();
559 TargetOptions &TargetOpts = Invocation.getTargetOpts();
560 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
561 CodeGenOpts.XRayInstrumentFunctions = LangOpts.XRayInstrument;
562 CodeGenOpts.XRayAlwaysEmitCustomEvents = LangOpts.XRayAlwaysEmitCustomEvents;
563 CodeGenOpts.XRayAlwaysEmitTypedEvents = LangOpts.XRayAlwaysEmitTypedEvents;
564 CodeGenOpts.DisableFree = FrontendOpts.DisableFree;
565 FrontendOpts.GenerateGlobalModuleIndex = FrontendOpts.UseGlobalModuleIndex;
566 if (FrontendOpts.ShowStats)
567 CodeGenOpts.ClearASTBeforeBackend = false;
568 LangOpts.SanitizeCoverage = CodeGenOpts.hasSanitizeCoverage();
569 LangOpts.ForceEmitVTables = CodeGenOpts.ForceEmitVTables;
570 LangOpts.SpeculativeLoadHardening = CodeGenOpts.SpeculativeLoadHardening;
571 LangOpts.CurrentModule = LangOpts.ModuleName;
573 llvm::Triple T(TargetOpts.Triple);
574 llvm::Triple::ArchType Arch = T.getArch();
576 CodeGenOpts.CodeModel = TargetOpts.CodeModel;
577 CodeGenOpts.LargeDataThreshold = TargetOpts.LargeDataThreshold;
579 if (LangOpts.getExceptionHandling() !=
580 LangOptions::ExceptionHandlingKind::None &&
581 T.isWindowsMSVCEnvironment())
582 Diags.Report(diag::err_fe_invalid_exception_model)
583 << static_cast<unsigned>(LangOpts.getExceptionHandling()) << T.str();
585 if (LangOpts.AppleKext && !LangOpts.CPlusPlus)
586 Diags.Report(diag::warn_c_kext);
588 if (LangOpts.NewAlignOverride &&
589 !llvm::isPowerOf2_32(LangOpts.NewAlignOverride)) {
590 Arg *A = Args.getLastArg(OPT_fnew_alignment_EQ);
591 Diags.Report(diag::err_fe_invalid_alignment)
592 << A->getAsString(Args) << A->getValue();
593 LangOpts.NewAlignOverride = 0;
596 // Prevent the user from specifying both -fsycl-is-device and -fsycl-is-host.
597 if (LangOpts.SYCLIsDevice && LangOpts.SYCLIsHost)
598 Diags.Report(diag::err_drv_argument_not_allowed_with) << "-fsycl-is-device"
599 << "-fsycl-is-host";
601 if (Args.hasArg(OPT_fgnu89_inline) && LangOpts.CPlusPlus)
602 Diags.Report(diag::err_drv_argument_not_allowed_with)
603 << "-fgnu89-inline" << GetInputKindName(IK);
605 if (Args.hasArg(OPT_hlsl_entrypoint) && !LangOpts.HLSL)
606 Diags.Report(diag::err_drv_argument_not_allowed_with)
607 << "-hlsl-entry" << GetInputKindName(IK);
609 if (Args.hasArg(OPT_fgpu_allow_device_init) && !LangOpts.HIP)
610 Diags.Report(diag::warn_ignored_hip_only_option)
611 << Args.getLastArg(OPT_fgpu_allow_device_init)->getAsString(Args);
613 if (Args.hasArg(OPT_gpu_max_threads_per_block_EQ) && !LangOpts.HIP)
614 Diags.Report(diag::warn_ignored_hip_only_option)
615 << Args.getLastArg(OPT_gpu_max_threads_per_block_EQ)->getAsString(Args);
617 // When these options are used, the compiler is allowed to apply
618 // optimizations that may affect the final result. For example
619 // (x+y)+z is transformed to x+(y+z) but may not give the same
620 // final result; it's not value safe.
621 // Another example can be to simplify x/x to 1.0 but x could be 0.0, INF
622 // or NaN. Final result may then differ. An error is issued when the eval
623 // method is set with one of these options.
624 if (Args.hasArg(OPT_ffp_eval_method_EQ)) {
625 if (LangOpts.ApproxFunc)
626 Diags.Report(diag::err_incompatible_fp_eval_method_options) << 0;
627 if (LangOpts.AllowFPReassoc)
628 Diags.Report(diag::err_incompatible_fp_eval_method_options) << 1;
629 if (LangOpts.AllowRecip)
630 Diags.Report(diag::err_incompatible_fp_eval_method_options) << 2;
633 // -cl-strict-aliasing needs to emit diagnostic in the case where CL > 1.0.
634 // This option should be deprecated for CL > 1.0 because
635 // this option was added for compatibility with OpenCL 1.0.
636 if (Args.getLastArg(OPT_cl_strict_aliasing) &&
637 (LangOpts.getOpenCLCompatibleVersion() > 100))
638 Diags.Report(diag::warn_option_invalid_ocl_version)
639 << LangOpts.getOpenCLVersionString()
640 << Args.getLastArg(OPT_cl_strict_aliasing)->getAsString(Args);
642 if (Arg *A = Args.getLastArg(OPT_fdefault_calling_conv_EQ)) {
643 auto DefaultCC = LangOpts.getDefaultCallingConv();
645 bool emitError = (DefaultCC == LangOptions::DCC_FastCall ||
646 DefaultCC == LangOptions::DCC_StdCall) &&
647 Arch != llvm::Triple::x86;
648 emitError |= (DefaultCC == LangOptions::DCC_VectorCall ||
649 DefaultCC == LangOptions::DCC_RegCall) &&
650 !T.isX86();
651 emitError |= DefaultCC == LangOptions::DCC_RtdCall && Arch != llvm::Triple::m68k;
652 if (emitError)
653 Diags.Report(diag::err_drv_argument_not_allowed_with)
654 << A->getSpelling() << T.getTriple();
657 return Diags.getNumErrors() == NumErrorsBefore;
660 //===----------------------------------------------------------------------===//
661 // Deserialization (from args)
662 //===----------------------------------------------------------------------===//
664 static unsigned getOptimizationLevel(ArgList &Args, InputKind IK,
665 DiagnosticsEngine &Diags) {
666 unsigned DefaultOpt = 0;
667 if ((IK.getLanguage() == Language::OpenCL ||
668 IK.getLanguage() == Language::OpenCLCXX) &&
669 !Args.hasArg(OPT_cl_opt_disable))
670 DefaultOpt = 2;
672 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
673 if (A->getOption().matches(options::OPT_O0))
674 return 0;
676 if (A->getOption().matches(options::OPT_Ofast))
677 return 3;
679 assert(A->getOption().matches(options::OPT_O));
681 StringRef S(A->getValue());
682 if (S == "s" || S == "z")
683 return 2;
685 if (S == "g")
686 return 1;
688 return getLastArgIntValue(Args, OPT_O, DefaultOpt, Diags);
691 return DefaultOpt;
694 static unsigned getOptimizationLevelSize(ArgList &Args) {
695 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
696 if (A->getOption().matches(options::OPT_O)) {
697 switch (A->getValue()[0]) {
698 default:
699 return 0;
700 case 's':
701 return 1;
702 case 'z':
703 return 2;
707 return 0;
710 static void GenerateArg(ArgumentConsumer Consumer,
711 llvm::opt::OptSpecifier OptSpecifier) {
712 Option Opt = getDriverOptTable().getOption(OptSpecifier);
713 denormalizeSimpleFlag(Consumer, Opt.getPrefixedName(),
714 Option::OptionClass::FlagClass, 0);
717 static void GenerateArg(ArgumentConsumer Consumer,
718 llvm::opt::OptSpecifier OptSpecifier,
719 const Twine &Value) {
720 Option Opt = getDriverOptTable().getOption(OptSpecifier);
721 denormalizeString(Consumer, Opt.getPrefixedName(), Opt.getKind(), 0, Value);
724 // Parse command line arguments into CompilerInvocation.
725 using ParseFn =
726 llvm::function_ref<bool(CompilerInvocation &, ArrayRef<const char *>,
727 DiagnosticsEngine &, const char *)>;
729 // Generate command line arguments from CompilerInvocation.
730 using GenerateFn = llvm::function_ref<void(
731 CompilerInvocation &, SmallVectorImpl<const char *> &,
732 CompilerInvocation::StringAllocator)>;
734 /// May perform round-trip of command line arguments. By default, the round-trip
735 /// is enabled in assert builds. This can be overwritten at run-time via the
736 /// "-round-trip-args" and "-no-round-trip-args" command line flags, or via the
737 /// ForceRoundTrip parameter.
739 /// During round-trip, the command line arguments are parsed into a dummy
740 /// CompilerInvocation, which is used to generate the command line arguments
741 /// again. The real CompilerInvocation is then created by parsing the generated
742 /// arguments, not the original ones. This (in combination with tests covering
743 /// argument behavior) ensures the generated command line is complete (doesn't
744 /// drop/mangle any arguments).
746 /// Finally, we check the command line that was used to create the real
747 /// CompilerInvocation instance. By default, we compare it to the command line
748 /// the real CompilerInvocation generates. This checks whether the generator is
749 /// deterministic. If \p CheckAgainstOriginalInvocation is enabled, we instead
750 /// compare it to the original command line to verify the original command-line
751 /// was canonical and can round-trip exactly.
752 static bool RoundTrip(ParseFn Parse, GenerateFn Generate,
753 CompilerInvocation &RealInvocation,
754 CompilerInvocation &DummyInvocation,
755 ArrayRef<const char *> CommandLineArgs,
756 DiagnosticsEngine &Diags, const char *Argv0,
757 bool CheckAgainstOriginalInvocation = false,
758 bool ForceRoundTrip = false) {
759 #ifndef NDEBUG
760 bool DoRoundTripDefault = true;
761 #else
762 bool DoRoundTripDefault = false;
763 #endif
765 bool DoRoundTrip = DoRoundTripDefault;
766 if (ForceRoundTrip) {
767 DoRoundTrip = true;
768 } else {
769 for (const auto *Arg : CommandLineArgs) {
770 if (Arg == StringRef("-round-trip-args"))
771 DoRoundTrip = true;
772 if (Arg == StringRef("-no-round-trip-args"))
773 DoRoundTrip = false;
777 // If round-trip was not requested, simply run the parser with the real
778 // invocation diagnostics.
779 if (!DoRoundTrip)
780 return Parse(RealInvocation, CommandLineArgs, Diags, Argv0);
782 // Serializes quoted (and potentially escaped) arguments.
783 auto SerializeArgs = [](ArrayRef<const char *> Args) {
784 std::string Buffer;
785 llvm::raw_string_ostream OS(Buffer);
786 for (const char *Arg : Args) {
787 llvm::sys::printArg(OS, Arg, /*Quote=*/true);
788 OS << ' ';
790 OS.flush();
791 return Buffer;
794 // Setup a dummy DiagnosticsEngine.
795 DiagnosticsEngine DummyDiags(new DiagnosticIDs(), new DiagnosticOptions());
796 DummyDiags.setClient(new TextDiagnosticBuffer());
798 // Run the first parse on the original arguments with the dummy invocation and
799 // diagnostics.
800 if (!Parse(DummyInvocation, CommandLineArgs, DummyDiags, Argv0) ||
801 DummyDiags.getNumWarnings() != 0) {
802 // If the first parse did not succeed, it must be user mistake (invalid
803 // command line arguments). We won't be able to generate arguments that
804 // would reproduce the same result. Let's fail again with the real
805 // invocation and diagnostics, so all side-effects of parsing are visible.
806 unsigned NumWarningsBefore = Diags.getNumWarnings();
807 auto Success = Parse(RealInvocation, CommandLineArgs, Diags, Argv0);
808 if (!Success || Diags.getNumWarnings() != NumWarningsBefore)
809 return Success;
811 // Parse with original options and diagnostics succeeded even though it
812 // shouldn't have. Something is off.
813 Diags.Report(diag::err_cc1_round_trip_fail_then_ok);
814 Diags.Report(diag::note_cc1_round_trip_original)
815 << SerializeArgs(CommandLineArgs);
816 return false;
819 // Setup string allocator.
820 llvm::BumpPtrAllocator Alloc;
821 llvm::StringSaver StringPool(Alloc);
822 auto SA = [&StringPool](const Twine &Arg) {
823 return StringPool.save(Arg).data();
826 // Generate arguments from the dummy invocation. If Generate is the
827 // inverse of Parse, the newly generated arguments must have the same
828 // semantics as the original.
829 SmallVector<const char *> GeneratedArgs;
830 Generate(DummyInvocation, GeneratedArgs, SA);
832 // Run the second parse, now on the generated arguments, and with the real
833 // invocation and diagnostics. The result is what we will end up using for the
834 // rest of compilation, so if Generate is not inverse of Parse, something down
835 // the line will break.
836 bool Success2 = Parse(RealInvocation, GeneratedArgs, Diags, Argv0);
838 // The first parse on original arguments succeeded, but second parse of
839 // generated arguments failed. Something must be wrong with the generator.
840 if (!Success2) {
841 Diags.Report(diag::err_cc1_round_trip_ok_then_fail);
842 Diags.Report(diag::note_cc1_round_trip_generated)
843 << 1 << SerializeArgs(GeneratedArgs);
844 return false;
847 SmallVector<const char *> ComparisonArgs;
848 if (CheckAgainstOriginalInvocation)
849 // Compare against original arguments.
850 ComparisonArgs.assign(CommandLineArgs.begin(), CommandLineArgs.end());
851 else
852 // Generate arguments again, this time from the options we will end up using
853 // for the rest of the compilation.
854 Generate(RealInvocation, ComparisonArgs, SA);
856 // Compares two lists of arguments.
857 auto Equal = [](const ArrayRef<const char *> A,
858 const ArrayRef<const char *> B) {
859 return std::equal(A.begin(), A.end(), B.begin(), B.end(),
860 [](const char *AElem, const char *BElem) {
861 return StringRef(AElem) == StringRef(BElem);
865 // If we generated different arguments from what we assume are two
866 // semantically equivalent CompilerInvocations, the Generate function may
867 // be non-deterministic.
868 if (!Equal(GeneratedArgs, ComparisonArgs)) {
869 Diags.Report(diag::err_cc1_round_trip_mismatch);
870 Diags.Report(diag::note_cc1_round_trip_generated)
871 << 1 << SerializeArgs(GeneratedArgs);
872 Diags.Report(diag::note_cc1_round_trip_generated)
873 << 2 << SerializeArgs(ComparisonArgs);
874 return false;
877 Diags.Report(diag::remark_cc1_round_trip_generated)
878 << 1 << SerializeArgs(GeneratedArgs);
879 Diags.Report(diag::remark_cc1_round_trip_generated)
880 << 2 << SerializeArgs(ComparisonArgs);
882 return Success2;
885 bool CompilerInvocation::checkCC1RoundTrip(ArrayRef<const char *> Args,
886 DiagnosticsEngine &Diags,
887 const char *Argv0) {
888 CompilerInvocation DummyInvocation1, DummyInvocation2;
889 return RoundTrip(
890 [](CompilerInvocation &Invocation, ArrayRef<const char *> CommandLineArgs,
891 DiagnosticsEngine &Diags, const char *Argv0) {
892 return CreateFromArgsImpl(Invocation, CommandLineArgs, Diags, Argv0);
894 [](CompilerInvocation &Invocation, SmallVectorImpl<const char *> &Args,
895 StringAllocator SA) {
896 Args.push_back("-cc1");
897 Invocation.generateCC1CommandLine(Args, SA);
899 DummyInvocation1, DummyInvocation2, Args, Diags, Argv0,
900 /*CheckAgainstOriginalInvocation=*/true, /*ForceRoundTrip=*/true);
903 static void addDiagnosticArgs(ArgList &Args, OptSpecifier Group,
904 OptSpecifier GroupWithValue,
905 std::vector<std::string> &Diagnostics) {
906 for (auto *A : Args.filtered(Group)) {
907 if (A->getOption().getKind() == Option::FlagClass) {
908 // The argument is a pure flag (such as OPT_Wall or OPT_Wdeprecated). Add
909 // its name (minus the "W" or "R" at the beginning) to the diagnostics.
910 Diagnostics.push_back(
911 std::string(A->getOption().getName().drop_front(1)));
912 } else if (A->getOption().matches(GroupWithValue)) {
913 // This is -Wfoo= or -Rfoo=, where foo is the name of the diagnostic
914 // group. Add only the group name to the diagnostics.
915 Diagnostics.push_back(
916 std::string(A->getOption().getName().drop_front(1).rtrim("=-")));
917 } else {
918 // Otherwise, add its value (for OPT_W_Joined and similar).
919 Diagnostics.push_back(A->getValue());
924 // Parse the Static Analyzer configuration. If \p Diags is set to nullptr,
925 // it won't verify the input.
926 static void parseAnalyzerConfigs(AnalyzerOptions &AnOpts,
927 DiagnosticsEngine *Diags);
929 static void getAllNoBuiltinFuncValues(ArgList &Args,
930 std::vector<std::string> &Funcs) {
931 std::vector<std::string> Values = Args.getAllArgValues(OPT_fno_builtin_);
932 auto BuiltinEnd = llvm::partition(Values, Builtin::Context::isBuiltinFunc);
933 Funcs.insert(Funcs.end(), Values.begin(), BuiltinEnd);
936 static void GenerateAnalyzerArgs(const AnalyzerOptions &Opts,
937 ArgumentConsumer Consumer) {
938 const AnalyzerOptions *AnalyzerOpts = &Opts;
940 #define ANALYZER_OPTION_WITH_MARSHALLING(...) \
941 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
942 #include "clang/Driver/Options.inc"
943 #undef ANALYZER_OPTION_WITH_MARSHALLING
945 if (Opts.AnalysisConstraintsOpt != RangeConstraintsModel) {
946 switch (Opts.AnalysisConstraintsOpt) {
947 #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) \
948 case NAME##Model: \
949 GenerateArg(Consumer, OPT_analyzer_constraints, CMDFLAG); \
950 break;
951 #include "clang/StaticAnalyzer/Core/Analyses.def"
952 default:
953 llvm_unreachable("Tried to generate unknown analysis constraint.");
957 if (Opts.AnalysisDiagOpt != PD_HTML) {
958 switch (Opts.AnalysisDiagOpt) {
959 #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN) \
960 case PD_##NAME: \
961 GenerateArg(Consumer, OPT_analyzer_output, CMDFLAG); \
962 break;
963 #include "clang/StaticAnalyzer/Core/Analyses.def"
964 default:
965 llvm_unreachable("Tried to generate unknown analysis diagnostic client.");
969 if (Opts.AnalysisPurgeOpt != PurgeStmt) {
970 switch (Opts.AnalysisPurgeOpt) {
971 #define ANALYSIS_PURGE(NAME, CMDFLAG, DESC) \
972 case NAME: \
973 GenerateArg(Consumer, OPT_analyzer_purge, CMDFLAG); \
974 break;
975 #include "clang/StaticAnalyzer/Core/Analyses.def"
976 default:
977 llvm_unreachable("Tried to generate unknown analysis purge mode.");
981 if (Opts.InliningMode != NoRedundancy) {
982 switch (Opts.InliningMode) {
983 #define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC) \
984 case NAME: \
985 GenerateArg(Consumer, OPT_analyzer_inlining_mode, CMDFLAG); \
986 break;
987 #include "clang/StaticAnalyzer/Core/Analyses.def"
988 default:
989 llvm_unreachable("Tried to generate unknown analysis inlining mode.");
993 for (const auto &CP : Opts.CheckersAndPackages) {
994 OptSpecifier Opt =
995 CP.second ? OPT_analyzer_checker : OPT_analyzer_disable_checker;
996 GenerateArg(Consumer, Opt, CP.first);
999 AnalyzerOptions ConfigOpts;
1000 parseAnalyzerConfigs(ConfigOpts, nullptr);
1002 // Sort options by key to avoid relying on StringMap iteration order.
1003 SmallVector<std::pair<StringRef, StringRef>, 4> SortedConfigOpts;
1004 for (const auto &C : Opts.Config)
1005 SortedConfigOpts.emplace_back(C.getKey(), C.getValue());
1006 llvm::sort(SortedConfigOpts, llvm::less_first());
1008 for (const auto &[Key, Value] : SortedConfigOpts) {
1009 // Don't generate anything that came from parseAnalyzerConfigs. It would be
1010 // redundant and may not be valid on the command line.
1011 auto Entry = ConfigOpts.Config.find(Key);
1012 if (Entry != ConfigOpts.Config.end() && Entry->getValue() == Value)
1013 continue;
1015 GenerateArg(Consumer, OPT_analyzer_config, Key + "=" + Value);
1018 // Nothing to generate for FullCompilerInvocation.
1021 static bool ParseAnalyzerArgs(AnalyzerOptions &Opts, ArgList &Args,
1022 DiagnosticsEngine &Diags) {
1023 unsigned NumErrorsBefore = Diags.getNumErrors();
1025 AnalyzerOptions *AnalyzerOpts = &Opts;
1027 #define ANALYZER_OPTION_WITH_MARSHALLING(...) \
1028 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
1029 #include "clang/Driver/Options.inc"
1030 #undef ANALYZER_OPTION_WITH_MARSHALLING
1032 if (Arg *A = Args.getLastArg(OPT_analyzer_constraints)) {
1033 StringRef Name = A->getValue();
1034 AnalysisConstraints Value = llvm::StringSwitch<AnalysisConstraints>(Name)
1035 #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) \
1036 .Case(CMDFLAG, NAME##Model)
1037 #include "clang/StaticAnalyzer/Core/Analyses.def"
1038 .Default(NumConstraints);
1039 if (Value == NumConstraints) {
1040 Diags.Report(diag::err_drv_invalid_value)
1041 << A->getAsString(Args) << Name;
1042 } else {
1043 #ifndef LLVM_WITH_Z3
1044 if (Value == AnalysisConstraints::Z3ConstraintsModel) {
1045 Diags.Report(diag::err_analyzer_not_built_with_z3);
1047 #endif // LLVM_WITH_Z3
1048 Opts.AnalysisConstraintsOpt = Value;
1052 if (Arg *A = Args.getLastArg(OPT_analyzer_output)) {
1053 StringRef Name = A->getValue();
1054 AnalysisDiagClients Value = llvm::StringSwitch<AnalysisDiagClients>(Name)
1055 #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN) \
1056 .Case(CMDFLAG, PD_##NAME)
1057 #include "clang/StaticAnalyzer/Core/Analyses.def"
1058 .Default(NUM_ANALYSIS_DIAG_CLIENTS);
1059 if (Value == NUM_ANALYSIS_DIAG_CLIENTS) {
1060 Diags.Report(diag::err_drv_invalid_value)
1061 << A->getAsString(Args) << Name;
1062 } else {
1063 Opts.AnalysisDiagOpt = Value;
1067 if (Arg *A = Args.getLastArg(OPT_analyzer_purge)) {
1068 StringRef Name = A->getValue();
1069 AnalysisPurgeMode Value = llvm::StringSwitch<AnalysisPurgeMode>(Name)
1070 #define ANALYSIS_PURGE(NAME, CMDFLAG, DESC) \
1071 .Case(CMDFLAG, NAME)
1072 #include "clang/StaticAnalyzer/Core/Analyses.def"
1073 .Default(NumPurgeModes);
1074 if (Value == NumPurgeModes) {
1075 Diags.Report(diag::err_drv_invalid_value)
1076 << A->getAsString(Args) << Name;
1077 } else {
1078 Opts.AnalysisPurgeOpt = Value;
1082 if (Arg *A = Args.getLastArg(OPT_analyzer_inlining_mode)) {
1083 StringRef Name = A->getValue();
1084 AnalysisInliningMode Value = llvm::StringSwitch<AnalysisInliningMode>(Name)
1085 #define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC) \
1086 .Case(CMDFLAG, NAME)
1087 #include "clang/StaticAnalyzer/Core/Analyses.def"
1088 .Default(NumInliningModes);
1089 if (Value == NumInliningModes) {
1090 Diags.Report(diag::err_drv_invalid_value)
1091 << A->getAsString(Args) << Name;
1092 } else {
1093 Opts.InliningMode = Value;
1097 Opts.CheckersAndPackages.clear();
1098 for (const Arg *A :
1099 Args.filtered(OPT_analyzer_checker, OPT_analyzer_disable_checker)) {
1100 A->claim();
1101 bool IsEnabled = A->getOption().getID() == OPT_analyzer_checker;
1102 // We can have a list of comma separated checker names, e.g:
1103 // '-analyzer-checker=cocoa,unix'
1104 StringRef CheckerAndPackageList = A->getValue();
1105 SmallVector<StringRef, 16> CheckersAndPackages;
1106 CheckerAndPackageList.split(CheckersAndPackages, ",");
1107 for (const StringRef &CheckerOrPackage : CheckersAndPackages)
1108 Opts.CheckersAndPackages.emplace_back(std::string(CheckerOrPackage),
1109 IsEnabled);
1112 // Go through the analyzer configuration options.
1113 for (const auto *A : Args.filtered(OPT_analyzer_config)) {
1115 // We can have a list of comma separated config names, e.g:
1116 // '-analyzer-config key1=val1,key2=val2'
1117 StringRef configList = A->getValue();
1118 SmallVector<StringRef, 4> configVals;
1119 configList.split(configVals, ",");
1120 for (const auto &configVal : configVals) {
1121 StringRef key, val;
1122 std::tie(key, val) = configVal.split("=");
1123 if (val.empty()) {
1124 Diags.Report(SourceLocation(),
1125 diag::err_analyzer_config_no_value) << configVal;
1126 break;
1128 if (val.contains('=')) {
1129 Diags.Report(SourceLocation(),
1130 diag::err_analyzer_config_multiple_values)
1131 << configVal;
1132 break;
1135 // TODO: Check checker options too, possibly in CheckerRegistry.
1136 // Leave unknown non-checker configs unclaimed.
1137 if (!key.contains(":") && Opts.isUnknownAnalyzerConfig(key)) {
1138 if (Opts.ShouldEmitErrorsOnInvalidConfigValue)
1139 Diags.Report(diag::err_analyzer_config_unknown) << key;
1140 continue;
1143 A->claim();
1144 Opts.Config[key] = std::string(val);
1148 if (Opts.ShouldEmitErrorsOnInvalidConfigValue)
1149 parseAnalyzerConfigs(Opts, &Diags);
1150 else
1151 parseAnalyzerConfigs(Opts, nullptr);
1153 llvm::raw_string_ostream os(Opts.FullCompilerInvocation);
1154 for (unsigned i = 0; i < Args.getNumInputArgStrings(); ++i) {
1155 if (i != 0)
1156 os << " ";
1157 os << Args.getArgString(i);
1159 os.flush();
1161 return Diags.getNumErrors() == NumErrorsBefore;
1164 static StringRef getStringOption(AnalyzerOptions::ConfigTable &Config,
1165 StringRef OptionName, StringRef DefaultVal) {
1166 return Config.insert({OptionName, std::string(DefaultVal)}).first->second;
1169 static void initOption(AnalyzerOptions::ConfigTable &Config,
1170 DiagnosticsEngine *Diags,
1171 StringRef &OptionField, StringRef Name,
1172 StringRef DefaultVal) {
1173 // String options may be known to invalid (e.g. if the expected string is a
1174 // file name, but the file does not exist), those will have to be checked in
1175 // parseConfigs.
1176 OptionField = getStringOption(Config, Name, DefaultVal);
1179 static void initOption(AnalyzerOptions::ConfigTable &Config,
1180 DiagnosticsEngine *Diags,
1181 bool &OptionField, StringRef Name, bool DefaultVal) {
1182 auto PossiblyInvalidVal =
1183 llvm::StringSwitch<std::optional<bool>>(
1184 getStringOption(Config, Name, (DefaultVal ? "true" : "false")))
1185 .Case("true", true)
1186 .Case("false", false)
1187 .Default(std::nullopt);
1189 if (!PossiblyInvalidVal) {
1190 if (Diags)
1191 Diags->Report(diag::err_analyzer_config_invalid_input)
1192 << Name << "a boolean";
1193 else
1194 OptionField = DefaultVal;
1195 } else
1196 OptionField = *PossiblyInvalidVal;
1199 static void initOption(AnalyzerOptions::ConfigTable &Config,
1200 DiagnosticsEngine *Diags,
1201 unsigned &OptionField, StringRef Name,
1202 unsigned DefaultVal) {
1204 OptionField = DefaultVal;
1205 bool HasFailed = getStringOption(Config, Name, std::to_string(DefaultVal))
1206 .getAsInteger(0, OptionField);
1207 if (Diags && HasFailed)
1208 Diags->Report(diag::err_analyzer_config_invalid_input)
1209 << Name << "an unsigned";
1212 static void parseAnalyzerConfigs(AnalyzerOptions &AnOpts,
1213 DiagnosticsEngine *Diags) {
1214 // TODO: There's no need to store the entire configtable, it'd be plenty
1215 // enough to store checker options.
1217 #define ANALYZER_OPTION(TYPE, NAME, CMDFLAG, DESC, DEFAULT_VAL) \
1218 initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, DEFAULT_VAL);
1219 #define ANALYZER_OPTION_DEPENDS_ON_USER_MODE(...)
1220 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.def"
1222 assert(AnOpts.UserMode == "shallow" || AnOpts.UserMode == "deep");
1223 const bool InShallowMode = AnOpts.UserMode == "shallow";
1225 #define ANALYZER_OPTION(...)
1226 #define ANALYZER_OPTION_DEPENDS_ON_USER_MODE(TYPE, NAME, CMDFLAG, DESC, \
1227 SHALLOW_VAL, DEEP_VAL) \
1228 initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, \
1229 InShallowMode ? SHALLOW_VAL : DEEP_VAL);
1230 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.def"
1232 // At this point, AnalyzerOptions is configured. Let's validate some options.
1234 // FIXME: Here we try to validate the silenced checkers or packages are valid.
1235 // The current approach only validates the registered checkers which does not
1236 // contain the runtime enabled checkers and optimally we would validate both.
1237 if (!AnOpts.RawSilencedCheckersAndPackages.empty()) {
1238 std::vector<StringRef> Checkers =
1239 AnOpts.getRegisteredCheckers(/*IncludeExperimental=*/true);
1240 std::vector<StringRef> Packages =
1241 AnOpts.getRegisteredPackages(/*IncludeExperimental=*/true);
1243 SmallVector<StringRef, 16> CheckersAndPackages;
1244 AnOpts.RawSilencedCheckersAndPackages.split(CheckersAndPackages, ";");
1246 for (const StringRef &CheckerOrPackage : CheckersAndPackages) {
1247 if (Diags) {
1248 bool IsChecker = CheckerOrPackage.contains('.');
1249 bool IsValidName = IsChecker
1250 ? llvm::is_contained(Checkers, CheckerOrPackage)
1251 : llvm::is_contained(Packages, CheckerOrPackage);
1253 if (!IsValidName)
1254 Diags->Report(diag::err_unknown_analyzer_checker_or_package)
1255 << CheckerOrPackage;
1258 AnOpts.SilencedCheckersAndPackages.emplace_back(CheckerOrPackage);
1262 if (!Diags)
1263 return;
1265 if (AnOpts.ShouldTrackConditionsDebug && !AnOpts.ShouldTrackConditions)
1266 Diags->Report(diag::err_analyzer_config_invalid_input)
1267 << "track-conditions-debug" << "'track-conditions' to also be enabled";
1269 if (!AnOpts.CTUDir.empty() && !llvm::sys::fs::is_directory(AnOpts.CTUDir))
1270 Diags->Report(diag::err_analyzer_config_invalid_input) << "ctu-dir"
1271 << "a filename";
1273 if (!AnOpts.ModelPath.empty() &&
1274 !llvm::sys::fs::is_directory(AnOpts.ModelPath))
1275 Diags->Report(diag::err_analyzer_config_invalid_input) << "model-path"
1276 << "a filename";
1279 /// Generate a remark argument. This is an inverse of `ParseOptimizationRemark`.
1280 static void
1281 GenerateOptimizationRemark(ArgumentConsumer Consumer, OptSpecifier OptEQ,
1282 StringRef Name,
1283 const CodeGenOptions::OptRemark &Remark) {
1284 if (Remark.hasValidPattern()) {
1285 GenerateArg(Consumer, OptEQ, Remark.Pattern);
1286 } else if (Remark.Kind == CodeGenOptions::RK_Enabled) {
1287 GenerateArg(Consumer, OPT_R_Joined, Name);
1288 } else if (Remark.Kind == CodeGenOptions::RK_Disabled) {
1289 GenerateArg(Consumer, OPT_R_Joined, StringRef("no-") + Name);
1293 /// Parse a remark command line argument. It may be missing, disabled/enabled by
1294 /// '-R[no-]group' or specified with a regular expression by '-Rgroup=regexp'.
1295 /// On top of that, it can be disabled/enabled globally by '-R[no-]everything'.
1296 static CodeGenOptions::OptRemark
1297 ParseOptimizationRemark(DiagnosticsEngine &Diags, ArgList &Args,
1298 OptSpecifier OptEQ, StringRef Name) {
1299 CodeGenOptions::OptRemark Result;
1301 auto InitializeResultPattern = [&Diags, &Args, &Result](const Arg *A,
1302 StringRef Pattern) {
1303 Result.Pattern = Pattern.str();
1305 std::string RegexError;
1306 Result.Regex = std::make_shared<llvm::Regex>(Result.Pattern);
1307 if (!Result.Regex->isValid(RegexError)) {
1308 Diags.Report(diag::err_drv_optimization_remark_pattern)
1309 << RegexError << A->getAsString(Args);
1310 return false;
1313 return true;
1316 for (Arg *A : Args) {
1317 if (A->getOption().matches(OPT_R_Joined)) {
1318 StringRef Value = A->getValue();
1320 if (Value == Name)
1321 Result.Kind = CodeGenOptions::RK_Enabled;
1322 else if (Value == "everything")
1323 Result.Kind = CodeGenOptions::RK_EnabledEverything;
1324 else if (Value.split('-') == std::make_pair(StringRef("no"), Name))
1325 Result.Kind = CodeGenOptions::RK_Disabled;
1326 else if (Value == "no-everything")
1327 Result.Kind = CodeGenOptions::RK_DisabledEverything;
1328 else
1329 continue;
1331 if (Result.Kind == CodeGenOptions::RK_Disabled ||
1332 Result.Kind == CodeGenOptions::RK_DisabledEverything) {
1333 Result.Pattern = "";
1334 Result.Regex = nullptr;
1335 } else {
1336 InitializeResultPattern(A, ".*");
1338 } else if (A->getOption().matches(OptEQ)) {
1339 Result.Kind = CodeGenOptions::RK_WithPattern;
1340 if (!InitializeResultPattern(A, A->getValue()))
1341 return CodeGenOptions::OptRemark();
1345 return Result;
1348 static bool parseDiagnosticLevelMask(StringRef FlagName,
1349 const std::vector<std::string> &Levels,
1350 DiagnosticsEngine &Diags,
1351 DiagnosticLevelMask &M) {
1352 bool Success = true;
1353 for (const auto &Level : Levels) {
1354 DiagnosticLevelMask const PM =
1355 llvm::StringSwitch<DiagnosticLevelMask>(Level)
1356 .Case("note", DiagnosticLevelMask::Note)
1357 .Case("remark", DiagnosticLevelMask::Remark)
1358 .Case("warning", DiagnosticLevelMask::Warning)
1359 .Case("error", DiagnosticLevelMask::Error)
1360 .Default(DiagnosticLevelMask::None);
1361 if (PM == DiagnosticLevelMask::None) {
1362 Success = false;
1363 Diags.Report(diag::err_drv_invalid_value) << FlagName << Level;
1365 M = M | PM;
1367 return Success;
1370 static void parseSanitizerKinds(StringRef FlagName,
1371 const std::vector<std::string> &Sanitizers,
1372 DiagnosticsEngine &Diags, SanitizerSet &S) {
1373 for (const auto &Sanitizer : Sanitizers) {
1374 SanitizerMask K = parseSanitizerValue(Sanitizer, /*AllowGroups=*/false);
1375 if (K == SanitizerMask())
1376 Diags.Report(diag::err_drv_invalid_value) << FlagName << Sanitizer;
1377 else
1378 S.set(K, true);
1382 static SmallVector<StringRef, 4> serializeSanitizerKinds(SanitizerSet S) {
1383 SmallVector<StringRef, 4> Values;
1384 serializeSanitizerSet(S, Values);
1385 return Values;
1388 static void parseXRayInstrumentationBundle(StringRef FlagName, StringRef Bundle,
1389 ArgList &Args, DiagnosticsEngine &D,
1390 XRayInstrSet &S) {
1391 llvm::SmallVector<StringRef, 2> BundleParts;
1392 llvm::SplitString(Bundle, BundleParts, ",");
1393 for (const auto &B : BundleParts) {
1394 auto Mask = parseXRayInstrValue(B);
1395 if (Mask == XRayInstrKind::None)
1396 if (B != "none")
1397 D.Report(diag::err_drv_invalid_value) << FlagName << Bundle;
1398 else
1399 S.Mask = Mask;
1400 else if (Mask == XRayInstrKind::All)
1401 S.Mask = Mask;
1402 else
1403 S.set(Mask, true);
1407 static std::string serializeXRayInstrumentationBundle(const XRayInstrSet &S) {
1408 llvm::SmallVector<StringRef, 2> BundleParts;
1409 serializeXRayInstrValue(S, BundleParts);
1410 std::string Buffer;
1411 llvm::raw_string_ostream OS(Buffer);
1412 llvm::interleave(BundleParts, OS, [&OS](StringRef Part) { OS << Part; }, ",");
1413 return Buffer;
1416 // Set the profile kind using fprofile-instrument-use-path.
1417 static void setPGOUseInstrumentor(CodeGenOptions &Opts,
1418 const Twine &ProfileName,
1419 llvm::vfs::FileSystem &FS,
1420 DiagnosticsEngine &Diags) {
1421 auto ReaderOrErr = llvm::IndexedInstrProfReader::create(ProfileName, FS);
1422 if (auto E = ReaderOrErr.takeError()) {
1423 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1424 "Error in reading profile %0: %1");
1425 llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
1426 Diags.Report(DiagID) << ProfileName.str() << EI.message();
1428 return;
1430 std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader =
1431 std::move(ReaderOrErr.get());
1432 // Currently memprof profiles are only added at the IR level. Mark the profile
1433 // type as IR in that case as well and the subsequent matching needs to detect
1434 // which is available (might be one or both).
1435 if (PGOReader->isIRLevelProfile() || PGOReader->hasMemoryProfile()) {
1436 if (PGOReader->hasCSIRLevelProfile())
1437 Opts.setProfileUse(CodeGenOptions::ProfileCSIRInstr);
1438 else
1439 Opts.setProfileUse(CodeGenOptions::ProfileIRInstr);
1440 } else
1441 Opts.setProfileUse(CodeGenOptions::ProfileClangInstr);
1444 void CompilerInvocationBase::GenerateCodeGenArgs(const CodeGenOptions &Opts,
1445 ArgumentConsumer Consumer,
1446 const llvm::Triple &T,
1447 const std::string &OutputFile,
1448 const LangOptions *LangOpts) {
1449 const CodeGenOptions &CodeGenOpts = Opts;
1451 if (Opts.OptimizationLevel == 0)
1452 GenerateArg(Consumer, OPT_O0);
1453 else
1454 GenerateArg(Consumer, OPT_O, Twine(Opts.OptimizationLevel));
1456 #define CODEGEN_OPTION_WITH_MARSHALLING(...) \
1457 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
1458 #include "clang/Driver/Options.inc"
1459 #undef CODEGEN_OPTION_WITH_MARSHALLING
1461 if (Opts.OptimizationLevel > 0) {
1462 if (Opts.Inlining == CodeGenOptions::NormalInlining)
1463 GenerateArg(Consumer, OPT_finline_functions);
1464 else if (Opts.Inlining == CodeGenOptions::OnlyHintInlining)
1465 GenerateArg(Consumer, OPT_finline_hint_functions);
1466 else if (Opts.Inlining == CodeGenOptions::OnlyAlwaysInlining)
1467 GenerateArg(Consumer, OPT_fno_inline);
1470 if (Opts.DirectAccessExternalData && LangOpts->PICLevel != 0)
1471 GenerateArg(Consumer, OPT_fdirect_access_external_data);
1472 else if (!Opts.DirectAccessExternalData && LangOpts->PICLevel == 0)
1473 GenerateArg(Consumer, OPT_fno_direct_access_external_data);
1475 std::optional<StringRef> DebugInfoVal;
1476 switch (Opts.DebugInfo) {
1477 case llvm::codegenoptions::DebugLineTablesOnly:
1478 DebugInfoVal = "line-tables-only";
1479 break;
1480 case llvm::codegenoptions::DebugDirectivesOnly:
1481 DebugInfoVal = "line-directives-only";
1482 break;
1483 case llvm::codegenoptions::DebugInfoConstructor:
1484 DebugInfoVal = "constructor";
1485 break;
1486 case llvm::codegenoptions::LimitedDebugInfo:
1487 DebugInfoVal = "limited";
1488 break;
1489 case llvm::codegenoptions::FullDebugInfo:
1490 DebugInfoVal = "standalone";
1491 break;
1492 case llvm::codegenoptions::UnusedTypeInfo:
1493 DebugInfoVal = "unused-types";
1494 break;
1495 case llvm::codegenoptions::NoDebugInfo: // default value
1496 DebugInfoVal = std::nullopt;
1497 break;
1498 case llvm::codegenoptions::LocTrackingOnly: // implied value
1499 DebugInfoVal = std::nullopt;
1500 break;
1502 if (DebugInfoVal)
1503 GenerateArg(Consumer, OPT_debug_info_kind_EQ, *DebugInfoVal);
1505 for (const auto &Prefix : Opts.DebugPrefixMap)
1506 GenerateArg(Consumer, OPT_fdebug_prefix_map_EQ,
1507 Prefix.first + "=" + Prefix.second);
1509 for (const auto &Prefix : Opts.CoveragePrefixMap)
1510 GenerateArg(Consumer, OPT_fcoverage_prefix_map_EQ,
1511 Prefix.first + "=" + Prefix.second);
1513 if (Opts.NewStructPathTBAA)
1514 GenerateArg(Consumer, OPT_new_struct_path_tbaa);
1516 if (Opts.OptimizeSize == 1)
1517 GenerateArg(Consumer, OPT_O, "s");
1518 else if (Opts.OptimizeSize == 2)
1519 GenerateArg(Consumer, OPT_O, "z");
1521 // SimplifyLibCalls is set only in the absence of -fno-builtin and
1522 // -ffreestanding. We'll consider that when generating them.
1524 // NoBuiltinFuncs are generated by LangOptions.
1526 if (Opts.UnrollLoops && Opts.OptimizationLevel <= 1)
1527 GenerateArg(Consumer, OPT_funroll_loops);
1528 else if (!Opts.UnrollLoops && Opts.OptimizationLevel > 1)
1529 GenerateArg(Consumer, OPT_fno_unroll_loops);
1531 if (!Opts.BinutilsVersion.empty())
1532 GenerateArg(Consumer, OPT_fbinutils_version_EQ, Opts.BinutilsVersion);
1534 if (Opts.DebugNameTable ==
1535 static_cast<unsigned>(llvm::DICompileUnit::DebugNameTableKind::GNU))
1536 GenerateArg(Consumer, OPT_ggnu_pubnames);
1537 else if (Opts.DebugNameTable ==
1538 static_cast<unsigned>(
1539 llvm::DICompileUnit::DebugNameTableKind::Default))
1540 GenerateArg(Consumer, OPT_gpubnames);
1542 auto TNK = Opts.getDebugSimpleTemplateNames();
1543 if (TNK != llvm::codegenoptions::DebugTemplateNamesKind::Full) {
1544 if (TNK == llvm::codegenoptions::DebugTemplateNamesKind::Simple)
1545 GenerateArg(Consumer, OPT_gsimple_template_names_EQ, "simple");
1546 else if (TNK == llvm::codegenoptions::DebugTemplateNamesKind::Mangled)
1547 GenerateArg(Consumer, OPT_gsimple_template_names_EQ, "mangled");
1549 // ProfileInstrumentUsePath is marshalled automatically, no need to generate
1550 // it or PGOUseInstrumentor.
1552 if (Opts.TimePasses) {
1553 if (Opts.TimePassesPerRun)
1554 GenerateArg(Consumer, OPT_ftime_report_EQ, "per-pass-run");
1555 else
1556 GenerateArg(Consumer, OPT_ftime_report);
1559 if (Opts.PrepareForLTO && !Opts.PrepareForThinLTO)
1560 GenerateArg(Consumer, OPT_flto_EQ, "full");
1562 if (Opts.PrepareForThinLTO)
1563 GenerateArg(Consumer, OPT_flto_EQ, "thin");
1565 if (!Opts.ThinLTOIndexFile.empty())
1566 GenerateArg(Consumer, OPT_fthinlto_index_EQ, Opts.ThinLTOIndexFile);
1568 if (Opts.SaveTempsFilePrefix == OutputFile)
1569 GenerateArg(Consumer, OPT_save_temps_EQ, "obj");
1571 StringRef MemProfileBasename("memprof.profraw");
1572 if (!Opts.MemoryProfileOutput.empty()) {
1573 if (Opts.MemoryProfileOutput == MemProfileBasename) {
1574 GenerateArg(Consumer, OPT_fmemory_profile);
1575 } else {
1576 size_t ArgLength =
1577 Opts.MemoryProfileOutput.size() - MemProfileBasename.size();
1578 GenerateArg(Consumer, OPT_fmemory_profile_EQ,
1579 Opts.MemoryProfileOutput.substr(0, ArgLength));
1583 if (memcmp(Opts.CoverageVersion, "408*", 4) != 0)
1584 GenerateArg(Consumer, OPT_coverage_version_EQ,
1585 StringRef(Opts.CoverageVersion, 4));
1587 // TODO: Check if we need to generate arguments stored in CmdArgs. (Namely
1588 // '-fembed_bitcode', which does not map to any CompilerInvocation field and
1589 // won't be generated.)
1591 if (Opts.XRayInstrumentationBundle.Mask != XRayInstrKind::All) {
1592 std::string InstrBundle =
1593 serializeXRayInstrumentationBundle(Opts.XRayInstrumentationBundle);
1594 if (!InstrBundle.empty())
1595 GenerateArg(Consumer, OPT_fxray_instrumentation_bundle, InstrBundle);
1598 if (Opts.CFProtectionReturn && Opts.CFProtectionBranch)
1599 GenerateArg(Consumer, OPT_fcf_protection_EQ, "full");
1600 else if (Opts.CFProtectionReturn)
1601 GenerateArg(Consumer, OPT_fcf_protection_EQ, "return");
1602 else if (Opts.CFProtectionBranch)
1603 GenerateArg(Consumer, OPT_fcf_protection_EQ, "branch");
1605 if (Opts.FunctionReturnThunks)
1606 GenerateArg(Consumer, OPT_mfunction_return_EQ, "thunk-extern");
1608 for (const auto &F : Opts.LinkBitcodeFiles) {
1609 bool Builtint = F.LinkFlags == llvm::Linker::Flags::LinkOnlyNeeded &&
1610 F.PropagateAttrs && F.Internalize;
1611 GenerateArg(Consumer,
1612 Builtint ? OPT_mlink_builtin_bitcode : OPT_mlink_bitcode_file,
1613 F.Filename);
1616 if (Opts.EmulatedTLS)
1617 GenerateArg(Consumer, OPT_femulated_tls);
1619 if (Opts.FPDenormalMode != llvm::DenormalMode::getIEEE())
1620 GenerateArg(Consumer, OPT_fdenormal_fp_math_EQ, Opts.FPDenormalMode.str());
1622 if ((Opts.FPDenormalMode != Opts.FP32DenormalMode) ||
1623 (Opts.FP32DenormalMode != llvm::DenormalMode::getIEEE()))
1624 GenerateArg(Consumer, OPT_fdenormal_fp_math_f32_EQ,
1625 Opts.FP32DenormalMode.str());
1627 if (Opts.StructReturnConvention == CodeGenOptions::SRCK_OnStack) {
1628 OptSpecifier Opt =
1629 T.isPPC32() ? OPT_maix_struct_return : OPT_fpcc_struct_return;
1630 GenerateArg(Consumer, Opt);
1631 } else if (Opts.StructReturnConvention == CodeGenOptions::SRCK_InRegs) {
1632 OptSpecifier Opt =
1633 T.isPPC32() ? OPT_msvr4_struct_return : OPT_freg_struct_return;
1634 GenerateArg(Consumer, Opt);
1637 if (Opts.EnableAIXExtendedAltivecABI)
1638 GenerateArg(Consumer, OPT_mabi_EQ_vec_extabi);
1640 if (Opts.XCOFFReadOnlyPointers)
1641 GenerateArg(Consumer, OPT_mxcoff_roptr);
1643 if (!Opts.OptRecordPasses.empty())
1644 GenerateArg(Consumer, OPT_opt_record_passes, Opts.OptRecordPasses);
1646 if (!Opts.OptRecordFormat.empty())
1647 GenerateArg(Consumer, OPT_opt_record_format, Opts.OptRecordFormat);
1649 GenerateOptimizationRemark(Consumer, OPT_Rpass_EQ, "pass",
1650 Opts.OptimizationRemark);
1652 GenerateOptimizationRemark(Consumer, OPT_Rpass_missed_EQ, "pass-missed",
1653 Opts.OptimizationRemarkMissed);
1655 GenerateOptimizationRemark(Consumer, OPT_Rpass_analysis_EQ, "pass-analysis",
1656 Opts.OptimizationRemarkAnalysis);
1658 GenerateArg(Consumer, OPT_fdiagnostics_hotness_threshold_EQ,
1659 Opts.DiagnosticsHotnessThreshold
1660 ? Twine(*Opts.DiagnosticsHotnessThreshold)
1661 : "auto");
1663 GenerateArg(Consumer, OPT_fdiagnostics_misexpect_tolerance_EQ,
1664 Twine(*Opts.DiagnosticsMisExpectTolerance));
1666 for (StringRef Sanitizer : serializeSanitizerKinds(Opts.SanitizeRecover))
1667 GenerateArg(Consumer, OPT_fsanitize_recover_EQ, Sanitizer);
1669 for (StringRef Sanitizer : serializeSanitizerKinds(Opts.SanitizeTrap))
1670 GenerateArg(Consumer, OPT_fsanitize_trap_EQ, Sanitizer);
1672 if (!Opts.EmitVersionIdentMetadata)
1673 GenerateArg(Consumer, OPT_Qn);
1675 switch (Opts.FiniteLoops) {
1676 case CodeGenOptions::FiniteLoopsKind::Language:
1677 break;
1678 case CodeGenOptions::FiniteLoopsKind::Always:
1679 GenerateArg(Consumer, OPT_ffinite_loops);
1680 break;
1681 case CodeGenOptions::FiniteLoopsKind::Never:
1682 GenerateArg(Consumer, OPT_fno_finite_loops);
1683 break;
1687 bool CompilerInvocation::ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args,
1688 InputKind IK,
1689 DiagnosticsEngine &Diags,
1690 const llvm::Triple &T,
1691 const std::string &OutputFile,
1692 const LangOptions &LangOptsRef) {
1693 unsigned NumErrorsBefore = Diags.getNumErrors();
1695 unsigned OptimizationLevel = getOptimizationLevel(Args, IK, Diags);
1696 // TODO: This could be done in Driver
1697 unsigned MaxOptLevel = 3;
1698 if (OptimizationLevel > MaxOptLevel) {
1699 // If the optimization level is not supported, fall back on the default
1700 // optimization
1701 Diags.Report(diag::warn_drv_optimization_value)
1702 << Args.getLastArg(OPT_O)->getAsString(Args) << "-O" << MaxOptLevel;
1703 OptimizationLevel = MaxOptLevel;
1705 Opts.OptimizationLevel = OptimizationLevel;
1707 // The key paths of codegen options defined in Options.td start with
1708 // "CodeGenOpts.". Let's provide the expected variable name and type.
1709 CodeGenOptions &CodeGenOpts = Opts;
1710 // Some codegen options depend on language options. Let's provide the expected
1711 // variable name and type.
1712 const LangOptions *LangOpts = &LangOptsRef;
1714 #define CODEGEN_OPTION_WITH_MARSHALLING(...) \
1715 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
1716 #include "clang/Driver/Options.inc"
1717 #undef CODEGEN_OPTION_WITH_MARSHALLING
1719 // At O0 we want to fully disable inlining outside of cases marked with
1720 // 'alwaysinline' that are required for correctness.
1721 if (Opts.OptimizationLevel == 0) {
1722 Opts.setInlining(CodeGenOptions::OnlyAlwaysInlining);
1723 } else if (const Arg *A = Args.getLastArg(options::OPT_finline_functions,
1724 options::OPT_finline_hint_functions,
1725 options::OPT_fno_inline_functions,
1726 options::OPT_fno_inline)) {
1727 // Explicit inlining flags can disable some or all inlining even at
1728 // optimization levels above zero.
1729 if (A->getOption().matches(options::OPT_finline_functions))
1730 Opts.setInlining(CodeGenOptions::NormalInlining);
1731 else if (A->getOption().matches(options::OPT_finline_hint_functions))
1732 Opts.setInlining(CodeGenOptions::OnlyHintInlining);
1733 else
1734 Opts.setInlining(CodeGenOptions::OnlyAlwaysInlining);
1735 } else {
1736 Opts.setInlining(CodeGenOptions::NormalInlining);
1739 // PIC defaults to -fno-direct-access-external-data while non-PIC defaults to
1740 // -fdirect-access-external-data.
1741 Opts.DirectAccessExternalData =
1742 Args.hasArg(OPT_fdirect_access_external_data) ||
1743 (!Args.hasArg(OPT_fno_direct_access_external_data) &&
1744 LangOpts->PICLevel == 0);
1746 if (Arg *A = Args.getLastArg(OPT_debug_info_kind_EQ)) {
1747 unsigned Val =
1748 llvm::StringSwitch<unsigned>(A->getValue())
1749 .Case("line-tables-only", llvm::codegenoptions::DebugLineTablesOnly)
1750 .Case("line-directives-only",
1751 llvm::codegenoptions::DebugDirectivesOnly)
1752 .Case("constructor", llvm::codegenoptions::DebugInfoConstructor)
1753 .Case("limited", llvm::codegenoptions::LimitedDebugInfo)
1754 .Case("standalone", llvm::codegenoptions::FullDebugInfo)
1755 .Case("unused-types", llvm::codegenoptions::UnusedTypeInfo)
1756 .Default(~0U);
1757 if (Val == ~0U)
1758 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
1759 << A->getValue();
1760 else
1761 Opts.setDebugInfo(static_cast<llvm::codegenoptions::DebugInfoKind>(Val));
1764 // If -fuse-ctor-homing is set and limited debug info is already on, then use
1765 // constructor homing, and vice versa for -fno-use-ctor-homing.
1766 if (const Arg *A =
1767 Args.getLastArg(OPT_fuse_ctor_homing, OPT_fno_use_ctor_homing)) {
1768 if (A->getOption().matches(OPT_fuse_ctor_homing) &&
1769 Opts.getDebugInfo() == llvm::codegenoptions::LimitedDebugInfo)
1770 Opts.setDebugInfo(llvm::codegenoptions::DebugInfoConstructor);
1771 if (A->getOption().matches(OPT_fno_use_ctor_homing) &&
1772 Opts.getDebugInfo() == llvm::codegenoptions::DebugInfoConstructor)
1773 Opts.setDebugInfo(llvm::codegenoptions::LimitedDebugInfo);
1776 for (const auto &Arg : Args.getAllArgValues(OPT_fdebug_prefix_map_EQ)) {
1777 auto Split = StringRef(Arg).split('=');
1778 Opts.DebugPrefixMap.emplace_back(Split.first, Split.second);
1781 for (const auto &Arg : Args.getAllArgValues(OPT_fcoverage_prefix_map_EQ)) {
1782 auto Split = StringRef(Arg).split('=');
1783 Opts.CoveragePrefixMap.emplace_back(Split.first, Split.second);
1786 const llvm::Triple::ArchType DebugEntryValueArchs[] = {
1787 llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::aarch64,
1788 llvm::Triple::arm, llvm::Triple::armeb, llvm::Triple::mips,
1789 llvm::Triple::mipsel, llvm::Triple::mips64, llvm::Triple::mips64el};
1791 if (Opts.OptimizationLevel > 0 && Opts.hasReducedDebugInfo() &&
1792 llvm::is_contained(DebugEntryValueArchs, T.getArch()))
1793 Opts.EmitCallSiteInfo = true;
1795 if (!Opts.EnableDIPreservationVerify && Opts.DIBugsReportFilePath.size()) {
1796 Diags.Report(diag::warn_ignoring_verify_debuginfo_preserve_export)
1797 << Opts.DIBugsReportFilePath;
1798 Opts.DIBugsReportFilePath = "";
1801 Opts.NewStructPathTBAA = !Args.hasArg(OPT_no_struct_path_tbaa) &&
1802 Args.hasArg(OPT_new_struct_path_tbaa);
1803 Opts.OptimizeSize = getOptimizationLevelSize(Args);
1804 Opts.SimplifyLibCalls = !LangOpts->NoBuiltin;
1805 if (Opts.SimplifyLibCalls)
1806 Opts.NoBuiltinFuncs = LangOpts->NoBuiltinFuncs;
1807 Opts.UnrollLoops =
1808 Args.hasFlag(OPT_funroll_loops, OPT_fno_unroll_loops,
1809 (Opts.OptimizationLevel > 1));
1810 Opts.BinutilsVersion =
1811 std::string(Args.getLastArgValue(OPT_fbinutils_version_EQ));
1813 Opts.DebugNameTable = static_cast<unsigned>(
1814 Args.hasArg(OPT_ggnu_pubnames)
1815 ? llvm::DICompileUnit::DebugNameTableKind::GNU
1816 : Args.hasArg(OPT_gpubnames)
1817 ? llvm::DICompileUnit::DebugNameTableKind::Default
1818 : llvm::DICompileUnit::DebugNameTableKind::None);
1819 if (const Arg *A = Args.getLastArg(OPT_gsimple_template_names_EQ)) {
1820 StringRef Value = A->getValue();
1821 if (Value != "simple" && Value != "mangled")
1822 Diags.Report(diag::err_drv_unsupported_option_argument)
1823 << A->getSpelling() << A->getValue();
1824 Opts.setDebugSimpleTemplateNames(
1825 StringRef(A->getValue()) == "simple"
1826 ? llvm::codegenoptions::DebugTemplateNamesKind::Simple
1827 : llvm::codegenoptions::DebugTemplateNamesKind::Mangled);
1830 if (const Arg *A = Args.getLastArg(OPT_ftime_report, OPT_ftime_report_EQ)) {
1831 Opts.TimePasses = true;
1833 // -ftime-report= is only for new pass manager.
1834 if (A->getOption().getID() == OPT_ftime_report_EQ) {
1835 StringRef Val = A->getValue();
1836 if (Val == "per-pass")
1837 Opts.TimePassesPerRun = false;
1838 else if (Val == "per-pass-run")
1839 Opts.TimePassesPerRun = true;
1840 else
1841 Diags.Report(diag::err_drv_invalid_value)
1842 << A->getAsString(Args) << A->getValue();
1846 Opts.PrepareForLTO = false;
1847 Opts.PrepareForThinLTO = false;
1848 if (Arg *A = Args.getLastArg(OPT_flto_EQ)) {
1849 Opts.PrepareForLTO = true;
1850 StringRef S = A->getValue();
1851 if (S == "thin")
1852 Opts.PrepareForThinLTO = true;
1853 else if (S != "full")
1854 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << S;
1855 if (Args.hasArg(OPT_funified_lto))
1856 Opts.PrepareForThinLTO = true;
1858 if (Arg *A = Args.getLastArg(OPT_fthinlto_index_EQ)) {
1859 if (IK.getLanguage() != Language::LLVM_IR)
1860 Diags.Report(diag::err_drv_argument_only_allowed_with)
1861 << A->getAsString(Args) << "-x ir";
1862 Opts.ThinLTOIndexFile =
1863 std::string(Args.getLastArgValue(OPT_fthinlto_index_EQ));
1865 if (Arg *A = Args.getLastArg(OPT_save_temps_EQ))
1866 Opts.SaveTempsFilePrefix =
1867 llvm::StringSwitch<std::string>(A->getValue())
1868 .Case("obj", OutputFile)
1869 .Default(llvm::sys::path::filename(OutputFile).str());
1871 // The memory profile runtime appends the pid to make this name more unique.
1872 const char *MemProfileBasename = "memprof.profraw";
1873 if (Args.hasArg(OPT_fmemory_profile_EQ)) {
1874 SmallString<128> Path(
1875 std::string(Args.getLastArgValue(OPT_fmemory_profile_EQ)));
1876 llvm::sys::path::append(Path, MemProfileBasename);
1877 Opts.MemoryProfileOutput = std::string(Path);
1878 } else if (Args.hasArg(OPT_fmemory_profile))
1879 Opts.MemoryProfileOutput = MemProfileBasename;
1881 memcpy(Opts.CoverageVersion, "408*", 4);
1882 if (Opts.CoverageNotesFile.size() || Opts.CoverageDataFile.size()) {
1883 if (Args.hasArg(OPT_coverage_version_EQ)) {
1884 StringRef CoverageVersion = Args.getLastArgValue(OPT_coverage_version_EQ);
1885 if (CoverageVersion.size() != 4) {
1886 Diags.Report(diag::err_drv_invalid_value)
1887 << Args.getLastArg(OPT_coverage_version_EQ)->getAsString(Args)
1888 << CoverageVersion;
1889 } else {
1890 memcpy(Opts.CoverageVersion, CoverageVersion.data(), 4);
1894 // FIXME: For backend options that are not yet recorded as function
1895 // attributes in the IR, keep track of them so we can embed them in a
1896 // separate data section and use them when building the bitcode.
1897 for (const auto &A : Args) {
1898 // Do not encode output and input.
1899 if (A->getOption().getID() == options::OPT_o ||
1900 A->getOption().getID() == options::OPT_INPUT ||
1901 A->getOption().getID() == options::OPT_x ||
1902 A->getOption().getID() == options::OPT_fembed_bitcode ||
1903 A->getOption().matches(options::OPT_W_Group))
1904 continue;
1905 ArgStringList ASL;
1906 A->render(Args, ASL);
1907 for (const auto &arg : ASL) {
1908 StringRef ArgStr(arg);
1909 Opts.CmdArgs.insert(Opts.CmdArgs.end(), ArgStr.begin(), ArgStr.end());
1910 // using \00 to separate each commandline options.
1911 Opts.CmdArgs.push_back('\0');
1915 auto XRayInstrBundles =
1916 Args.getAllArgValues(OPT_fxray_instrumentation_bundle);
1917 if (XRayInstrBundles.empty())
1918 Opts.XRayInstrumentationBundle.Mask = XRayInstrKind::All;
1919 else
1920 for (const auto &A : XRayInstrBundles)
1921 parseXRayInstrumentationBundle("-fxray-instrumentation-bundle=", A, Args,
1922 Diags, Opts.XRayInstrumentationBundle);
1924 if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
1925 StringRef Name = A->getValue();
1926 if (Name == "full") {
1927 Opts.CFProtectionReturn = 1;
1928 Opts.CFProtectionBranch = 1;
1929 } else if (Name == "return")
1930 Opts.CFProtectionReturn = 1;
1931 else if (Name == "branch")
1932 Opts.CFProtectionBranch = 1;
1933 else if (Name != "none")
1934 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
1937 if (const Arg *A = Args.getLastArg(OPT_mfunction_return_EQ)) {
1938 auto Val = llvm::StringSwitch<llvm::FunctionReturnThunksKind>(A->getValue())
1939 .Case("keep", llvm::FunctionReturnThunksKind::Keep)
1940 .Case("thunk-extern", llvm::FunctionReturnThunksKind::Extern)
1941 .Default(llvm::FunctionReturnThunksKind::Invalid);
1942 // SystemZ might want to add support for "expolines."
1943 if (!T.isX86())
1944 Diags.Report(diag::err_drv_argument_not_allowed_with)
1945 << A->getSpelling() << T.getTriple();
1946 else if (Val == llvm::FunctionReturnThunksKind::Invalid)
1947 Diags.Report(diag::err_drv_invalid_value)
1948 << A->getAsString(Args) << A->getValue();
1949 else if (Val == llvm::FunctionReturnThunksKind::Extern &&
1950 Args.getLastArgValue(OPT_mcmodel_EQ).equals("large"))
1951 Diags.Report(diag::err_drv_argument_not_allowed_with)
1952 << A->getAsString(Args)
1953 << Args.getLastArg(OPT_mcmodel_EQ)->getAsString(Args);
1954 else
1955 Opts.FunctionReturnThunks = static_cast<unsigned>(Val);
1958 for (auto *A :
1959 Args.filtered(OPT_mlink_bitcode_file, OPT_mlink_builtin_bitcode)) {
1960 CodeGenOptions::BitcodeFileToLink F;
1961 F.Filename = A->getValue();
1962 if (A->getOption().matches(OPT_mlink_builtin_bitcode)) {
1963 F.LinkFlags = llvm::Linker::Flags::LinkOnlyNeeded;
1964 // When linking CUDA bitcode, propagate function attributes so that
1965 // e.g. libdevice gets fast-math attrs if we're building with fast-math.
1966 F.PropagateAttrs = true;
1967 F.Internalize = true;
1969 Opts.LinkBitcodeFiles.push_back(F);
1972 if (Arg *A = Args.getLastArg(OPT_ftlsmodel_EQ)) {
1973 if (T.isOSAIX()) {
1974 StringRef Name = A->getValue();
1975 if (Name == "local-dynamic")
1976 Diags.Report(diag::err_aix_unsupported_tls_model) << Name;
1980 if (Arg *A = Args.getLastArg(OPT_fdenormal_fp_math_EQ)) {
1981 StringRef Val = A->getValue();
1982 Opts.FPDenormalMode = llvm::parseDenormalFPAttribute(Val);
1983 Opts.FP32DenormalMode = Opts.FPDenormalMode;
1984 if (!Opts.FPDenormalMode.isValid())
1985 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
1988 if (Arg *A = Args.getLastArg(OPT_fdenormal_fp_math_f32_EQ)) {
1989 StringRef Val = A->getValue();
1990 Opts.FP32DenormalMode = llvm::parseDenormalFPAttribute(Val);
1991 if (!Opts.FP32DenormalMode.isValid())
1992 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
1995 // X86_32 has -fppc-struct-return and -freg-struct-return.
1996 // PPC32 has -maix-struct-return and -msvr4-struct-return.
1997 if (Arg *A =
1998 Args.getLastArg(OPT_fpcc_struct_return, OPT_freg_struct_return,
1999 OPT_maix_struct_return, OPT_msvr4_struct_return)) {
2000 // TODO: We might want to consider enabling these options on AIX in the
2001 // future.
2002 if (T.isOSAIX())
2003 Diags.Report(diag::err_drv_unsupported_opt_for_target)
2004 << A->getSpelling() << T.str();
2006 const Option &O = A->getOption();
2007 if (O.matches(OPT_fpcc_struct_return) ||
2008 O.matches(OPT_maix_struct_return)) {
2009 Opts.setStructReturnConvention(CodeGenOptions::SRCK_OnStack);
2010 } else {
2011 assert(O.matches(OPT_freg_struct_return) ||
2012 O.matches(OPT_msvr4_struct_return));
2013 Opts.setStructReturnConvention(CodeGenOptions::SRCK_InRegs);
2017 if (Arg *A = Args.getLastArg(OPT_mxcoff_roptr)) {
2018 if (!T.isOSAIX())
2019 Diags.Report(diag::err_drv_unsupported_opt_for_target)
2020 << A->getSpelling() << T.str();
2022 // Since the storage mapping class is specified per csect,
2023 // without using data sections, it is less effective to use read-only
2024 // pointers. Using read-only pointers may cause other RO variables in the
2025 // same csect to become RW when the linker acts upon `-bforceimprw`;
2026 // therefore, we require that separate data sections
2027 // are used when `-mxcoff-roptr` is in effect. We respect the setting of
2028 // data-sections since we have not found reasons to do otherwise that
2029 // overcome the user surprise of not respecting the setting.
2030 if (!Args.hasFlag(OPT_fdata_sections, OPT_fno_data_sections, false))
2031 Diags.Report(diag::err_roptr_requires_data_sections);
2033 Opts.XCOFFReadOnlyPointers = true;
2036 if (Arg *A = Args.getLastArg(OPT_mabi_EQ_quadword_atomics)) {
2037 if (!T.isOSAIX() || T.isPPC32())
2038 Diags.Report(diag::err_drv_unsupported_opt_for_target)
2039 << A->getSpelling() << T.str();
2042 bool NeedLocTracking = false;
2044 if (!Opts.OptRecordFile.empty())
2045 NeedLocTracking = true;
2047 if (Arg *A = Args.getLastArg(OPT_opt_record_passes)) {
2048 Opts.OptRecordPasses = A->getValue();
2049 NeedLocTracking = true;
2052 if (Arg *A = Args.getLastArg(OPT_opt_record_format)) {
2053 Opts.OptRecordFormat = A->getValue();
2054 NeedLocTracking = true;
2057 Opts.OptimizationRemark =
2058 ParseOptimizationRemark(Diags, Args, OPT_Rpass_EQ, "pass");
2060 Opts.OptimizationRemarkMissed =
2061 ParseOptimizationRemark(Diags, Args, OPT_Rpass_missed_EQ, "pass-missed");
2063 Opts.OptimizationRemarkAnalysis = ParseOptimizationRemark(
2064 Diags, Args, OPT_Rpass_analysis_EQ, "pass-analysis");
2066 NeedLocTracking |= Opts.OptimizationRemark.hasValidPattern() ||
2067 Opts.OptimizationRemarkMissed.hasValidPattern() ||
2068 Opts.OptimizationRemarkAnalysis.hasValidPattern();
2070 bool UsingSampleProfile = !Opts.SampleProfileFile.empty();
2071 bool UsingProfile =
2072 UsingSampleProfile || !Opts.ProfileInstrumentUsePath.empty();
2074 if (Opts.DiagnosticsWithHotness && !UsingProfile &&
2075 // An IR file will contain PGO as metadata
2076 IK.getLanguage() != Language::LLVM_IR)
2077 Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo)
2078 << "-fdiagnostics-show-hotness";
2080 // Parse remarks hotness threshold. Valid value is either integer or 'auto'.
2081 if (auto *arg =
2082 Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
2083 auto ResultOrErr =
2084 llvm::remarks::parseHotnessThresholdOption(arg->getValue());
2086 if (!ResultOrErr) {
2087 Diags.Report(diag::err_drv_invalid_diagnotics_hotness_threshold)
2088 << "-fdiagnostics-hotness-threshold=";
2089 } else {
2090 Opts.DiagnosticsHotnessThreshold = *ResultOrErr;
2091 if ((!Opts.DiagnosticsHotnessThreshold ||
2092 *Opts.DiagnosticsHotnessThreshold > 0) &&
2093 !UsingProfile)
2094 Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo)
2095 << "-fdiagnostics-hotness-threshold=";
2099 if (auto *arg =
2100 Args.getLastArg(options::OPT_fdiagnostics_misexpect_tolerance_EQ)) {
2101 auto ResultOrErr = parseToleranceOption(arg->getValue());
2103 if (!ResultOrErr) {
2104 Diags.Report(diag::err_drv_invalid_diagnotics_misexpect_tolerance)
2105 << "-fdiagnostics-misexpect-tolerance=";
2106 } else {
2107 Opts.DiagnosticsMisExpectTolerance = *ResultOrErr;
2108 if ((!Opts.DiagnosticsMisExpectTolerance ||
2109 *Opts.DiagnosticsMisExpectTolerance > 0) &&
2110 !UsingProfile)
2111 Diags.Report(diag::warn_drv_diagnostics_misexpect_requires_pgo)
2112 << "-fdiagnostics-misexpect-tolerance=";
2116 // If the user requested to use a sample profile for PGO, then the
2117 // backend will need to track source location information so the profile
2118 // can be incorporated into the IR.
2119 if (UsingSampleProfile)
2120 NeedLocTracking = true;
2122 if (!Opts.StackUsageOutput.empty())
2123 NeedLocTracking = true;
2125 // If the user requested a flag that requires source locations available in
2126 // the backend, make sure that the backend tracks source location information.
2127 if (NeedLocTracking &&
2128 Opts.getDebugInfo() == llvm::codegenoptions::NoDebugInfo)
2129 Opts.setDebugInfo(llvm::codegenoptions::LocTrackingOnly);
2131 // Parse -fsanitize-recover= arguments.
2132 // FIXME: Report unrecoverable sanitizers incorrectly specified here.
2133 parseSanitizerKinds("-fsanitize-recover=",
2134 Args.getAllArgValues(OPT_fsanitize_recover_EQ), Diags,
2135 Opts.SanitizeRecover);
2136 parseSanitizerKinds("-fsanitize-trap=",
2137 Args.getAllArgValues(OPT_fsanitize_trap_EQ), Diags,
2138 Opts.SanitizeTrap);
2140 Opts.EmitVersionIdentMetadata = Args.hasFlag(OPT_Qy, OPT_Qn, true);
2142 if (Args.hasArg(options::OPT_ffinite_loops))
2143 Opts.FiniteLoops = CodeGenOptions::FiniteLoopsKind::Always;
2144 else if (Args.hasArg(options::OPT_fno_finite_loops))
2145 Opts.FiniteLoops = CodeGenOptions::FiniteLoopsKind::Never;
2147 Opts.EmitIEEENaNCompliantInsts = Args.hasFlag(
2148 options::OPT_mamdgpu_ieee, options::OPT_mno_amdgpu_ieee, true);
2149 if (!Opts.EmitIEEENaNCompliantInsts && !LangOptsRef.NoHonorNaNs)
2150 Diags.Report(diag::err_drv_amdgpu_ieee_without_no_honor_nans);
2152 return Diags.getNumErrors() == NumErrorsBefore;
2155 static void GenerateDependencyOutputArgs(const DependencyOutputOptions &Opts,
2156 ArgumentConsumer Consumer) {
2157 const DependencyOutputOptions &DependencyOutputOpts = Opts;
2158 #define DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING(...) \
2159 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
2160 #include "clang/Driver/Options.inc"
2161 #undef DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING
2163 if (Opts.ShowIncludesDest != ShowIncludesDestination::None)
2164 GenerateArg(Consumer, OPT_show_includes);
2166 for (const auto &Dep : Opts.ExtraDeps) {
2167 switch (Dep.second) {
2168 case EDK_SanitizeIgnorelist:
2169 // Sanitizer ignorelist arguments are generated from LanguageOptions.
2170 continue;
2171 case EDK_ModuleFile:
2172 // Module file arguments are generated from FrontendOptions and
2173 // HeaderSearchOptions.
2174 continue;
2175 case EDK_ProfileList:
2176 // Profile list arguments are generated from LanguageOptions via the
2177 // marshalling infrastructure.
2178 continue;
2179 case EDK_DepFileEntry:
2180 GenerateArg(Consumer, OPT_fdepfile_entry, Dep.first);
2181 break;
2186 static bool ParseDependencyOutputArgs(DependencyOutputOptions &Opts,
2187 ArgList &Args, DiagnosticsEngine &Diags,
2188 frontend::ActionKind Action,
2189 bool ShowLineMarkers) {
2190 unsigned NumErrorsBefore = Diags.getNumErrors();
2192 DependencyOutputOptions &DependencyOutputOpts = Opts;
2193 #define DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING(...) \
2194 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
2195 #include "clang/Driver/Options.inc"
2196 #undef DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING
2198 if (Args.hasArg(OPT_show_includes)) {
2199 // Writing both /showIncludes and preprocessor output to stdout
2200 // would produce interleaved output, so use stderr for /showIncludes.
2201 // This behaves the same as cl.exe, when /E, /EP or /P are passed.
2202 if (Action == frontend::PrintPreprocessedInput || !ShowLineMarkers)
2203 Opts.ShowIncludesDest = ShowIncludesDestination::Stderr;
2204 else
2205 Opts.ShowIncludesDest = ShowIncludesDestination::Stdout;
2206 } else {
2207 Opts.ShowIncludesDest = ShowIncludesDestination::None;
2210 // Add sanitizer ignorelists as extra dependencies.
2211 // They won't be discovered by the regular preprocessor, so
2212 // we let make / ninja to know about this implicit dependency.
2213 if (!Args.hasArg(OPT_fno_sanitize_ignorelist)) {
2214 for (const auto *A : Args.filtered(OPT_fsanitize_ignorelist_EQ)) {
2215 StringRef Val = A->getValue();
2216 if (!Val.contains('='))
2217 Opts.ExtraDeps.emplace_back(std::string(Val), EDK_SanitizeIgnorelist);
2219 if (Opts.IncludeSystemHeaders) {
2220 for (const auto *A : Args.filtered(OPT_fsanitize_system_ignorelist_EQ)) {
2221 StringRef Val = A->getValue();
2222 if (!Val.contains('='))
2223 Opts.ExtraDeps.emplace_back(std::string(Val), EDK_SanitizeIgnorelist);
2228 // -fprofile-list= dependencies.
2229 for (const auto &Filename : Args.getAllArgValues(OPT_fprofile_list_EQ))
2230 Opts.ExtraDeps.emplace_back(Filename, EDK_ProfileList);
2232 // Propagate the extra dependencies.
2233 for (const auto *A : Args.filtered(OPT_fdepfile_entry))
2234 Opts.ExtraDeps.emplace_back(A->getValue(), EDK_DepFileEntry);
2236 // Only the -fmodule-file=<file> form.
2237 for (const auto *A : Args.filtered(OPT_fmodule_file)) {
2238 StringRef Val = A->getValue();
2239 if (!Val.contains('='))
2240 Opts.ExtraDeps.emplace_back(std::string(Val), EDK_ModuleFile);
2243 // Check for invalid combinations of header-include-format
2244 // and header-include-filtering.
2245 if ((Opts.HeaderIncludeFormat == HIFMT_Textual &&
2246 Opts.HeaderIncludeFiltering != HIFIL_None) ||
2247 (Opts.HeaderIncludeFormat == HIFMT_JSON &&
2248 Opts.HeaderIncludeFiltering != HIFIL_Only_Direct_System))
2249 Diags.Report(diag::err_drv_print_header_env_var_combination_cc1)
2250 << Args.getLastArg(OPT_header_include_format_EQ)->getValue()
2251 << Args.getLastArg(OPT_header_include_filtering_EQ)->getValue();
2253 return Diags.getNumErrors() == NumErrorsBefore;
2256 static bool parseShowColorsArgs(const ArgList &Args, bool DefaultColor) {
2257 // Color diagnostics default to auto ("on" if terminal supports) in the driver
2258 // but default to off in cc1, needing an explicit OPT_fdiagnostics_color.
2259 // Support both clang's -f[no-]color-diagnostics and gcc's
2260 // -f[no-]diagnostics-colors[=never|always|auto].
2261 enum {
2262 Colors_On,
2263 Colors_Off,
2264 Colors_Auto
2265 } ShowColors = DefaultColor ? Colors_Auto : Colors_Off;
2266 for (auto *A : Args) {
2267 const Option &O = A->getOption();
2268 if (O.matches(options::OPT_fcolor_diagnostics)) {
2269 ShowColors = Colors_On;
2270 } else if (O.matches(options::OPT_fno_color_diagnostics)) {
2271 ShowColors = Colors_Off;
2272 } else if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
2273 StringRef Value(A->getValue());
2274 if (Value == "always")
2275 ShowColors = Colors_On;
2276 else if (Value == "never")
2277 ShowColors = Colors_Off;
2278 else if (Value == "auto")
2279 ShowColors = Colors_Auto;
2282 return ShowColors == Colors_On ||
2283 (ShowColors == Colors_Auto &&
2284 llvm::sys::Process::StandardErrHasColors());
2287 static bool checkVerifyPrefixes(const std::vector<std::string> &VerifyPrefixes,
2288 DiagnosticsEngine &Diags) {
2289 bool Success = true;
2290 for (const auto &Prefix : VerifyPrefixes) {
2291 // Every prefix must start with a letter and contain only alphanumeric
2292 // characters, hyphens, and underscores.
2293 auto BadChar = llvm::find_if(Prefix, [](char C) {
2294 return !isAlphanumeric(C) && C != '-' && C != '_';
2296 if (BadChar != Prefix.end() || !isLetter(Prefix[0])) {
2297 Success = false;
2298 Diags.Report(diag::err_drv_invalid_value) << "-verify=" << Prefix;
2299 Diags.Report(diag::note_drv_verify_prefix_spelling);
2302 return Success;
2305 static void GenerateFileSystemArgs(const FileSystemOptions &Opts,
2306 ArgumentConsumer Consumer) {
2307 const FileSystemOptions &FileSystemOpts = Opts;
2309 #define FILE_SYSTEM_OPTION_WITH_MARSHALLING(...) \
2310 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
2311 #include "clang/Driver/Options.inc"
2312 #undef FILE_SYSTEM_OPTION_WITH_MARSHALLING
2315 static bool ParseFileSystemArgs(FileSystemOptions &Opts, const ArgList &Args,
2316 DiagnosticsEngine &Diags) {
2317 unsigned NumErrorsBefore = Diags.getNumErrors();
2319 FileSystemOptions &FileSystemOpts = Opts;
2321 #define FILE_SYSTEM_OPTION_WITH_MARSHALLING(...) \
2322 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
2323 #include "clang/Driver/Options.inc"
2324 #undef FILE_SYSTEM_OPTION_WITH_MARSHALLING
2326 return Diags.getNumErrors() == NumErrorsBefore;
2329 static void GenerateMigratorArgs(const MigratorOptions &Opts,
2330 ArgumentConsumer Consumer) {
2331 const MigratorOptions &MigratorOpts = Opts;
2332 #define MIGRATOR_OPTION_WITH_MARSHALLING(...) \
2333 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
2334 #include "clang/Driver/Options.inc"
2335 #undef MIGRATOR_OPTION_WITH_MARSHALLING
2338 static bool ParseMigratorArgs(MigratorOptions &Opts, const ArgList &Args,
2339 DiagnosticsEngine &Diags) {
2340 unsigned NumErrorsBefore = Diags.getNumErrors();
2342 MigratorOptions &MigratorOpts = Opts;
2344 #define MIGRATOR_OPTION_WITH_MARSHALLING(...) \
2345 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
2346 #include "clang/Driver/Options.inc"
2347 #undef MIGRATOR_OPTION_WITH_MARSHALLING
2349 return Diags.getNumErrors() == NumErrorsBefore;
2352 void CompilerInvocationBase::GenerateDiagnosticArgs(
2353 const DiagnosticOptions &Opts, ArgumentConsumer Consumer,
2354 bool DefaultDiagColor) {
2355 const DiagnosticOptions *DiagnosticOpts = &Opts;
2356 #define DIAG_OPTION_WITH_MARSHALLING(...) \
2357 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
2358 #include "clang/Driver/Options.inc"
2359 #undef DIAG_OPTION_WITH_MARSHALLING
2361 if (!Opts.DiagnosticSerializationFile.empty())
2362 GenerateArg(Consumer, OPT_diagnostic_serialized_file,
2363 Opts.DiagnosticSerializationFile);
2365 if (Opts.ShowColors)
2366 GenerateArg(Consumer, OPT_fcolor_diagnostics);
2368 if (Opts.VerifyDiagnostics &&
2369 llvm::is_contained(Opts.VerifyPrefixes, "expected"))
2370 GenerateArg(Consumer, OPT_verify);
2372 for (const auto &Prefix : Opts.VerifyPrefixes)
2373 if (Prefix != "expected")
2374 GenerateArg(Consumer, OPT_verify_EQ, Prefix);
2376 DiagnosticLevelMask VIU = Opts.getVerifyIgnoreUnexpected();
2377 if (VIU == DiagnosticLevelMask::None) {
2378 // This is the default, don't generate anything.
2379 } else if (VIU == DiagnosticLevelMask::All) {
2380 GenerateArg(Consumer, OPT_verify_ignore_unexpected);
2381 } else {
2382 if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Note) != 0)
2383 GenerateArg(Consumer, OPT_verify_ignore_unexpected_EQ, "note");
2384 if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Remark) != 0)
2385 GenerateArg(Consumer, OPT_verify_ignore_unexpected_EQ, "remark");
2386 if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Warning) != 0)
2387 GenerateArg(Consumer, OPT_verify_ignore_unexpected_EQ, "warning");
2388 if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Error) != 0)
2389 GenerateArg(Consumer, OPT_verify_ignore_unexpected_EQ, "error");
2392 for (const auto &Warning : Opts.Warnings) {
2393 // This option is automatically generated from UndefPrefixes.
2394 if (Warning == "undef-prefix")
2395 continue;
2396 Consumer(StringRef("-W") + Warning);
2399 for (const auto &Remark : Opts.Remarks) {
2400 // These arguments are generated from OptimizationRemark fields of
2401 // CodeGenOptions.
2402 StringRef IgnoredRemarks[] = {"pass", "no-pass",
2403 "pass-analysis", "no-pass-analysis",
2404 "pass-missed", "no-pass-missed"};
2405 if (llvm::is_contained(IgnoredRemarks, Remark))
2406 continue;
2408 Consumer(StringRef("-R") + Remark);
2412 std::unique_ptr<DiagnosticOptions>
2413 clang::CreateAndPopulateDiagOpts(ArrayRef<const char *> Argv) {
2414 auto DiagOpts = std::make_unique<DiagnosticOptions>();
2415 unsigned MissingArgIndex, MissingArgCount;
2416 InputArgList Args = getDriverOptTable().ParseArgs(
2417 Argv.slice(1), MissingArgIndex, MissingArgCount);
2419 bool ShowColors = true;
2420 if (std::optional<std::string> NoColor =
2421 llvm::sys::Process::GetEnv("NO_COLOR");
2422 NoColor && !NoColor->empty()) {
2423 // If the user set the NO_COLOR environment variable, we'll honor that
2424 // unless the command line overrides it.
2425 ShowColors = false;
2428 // We ignore MissingArgCount and the return value of ParseDiagnosticArgs.
2429 // Any errors that would be diagnosed here will also be diagnosed later,
2430 // when the DiagnosticsEngine actually exists.
2431 (void)ParseDiagnosticArgs(*DiagOpts, Args, /*Diags=*/nullptr, ShowColors);
2432 return DiagOpts;
2435 bool clang::ParseDiagnosticArgs(DiagnosticOptions &Opts, ArgList &Args,
2436 DiagnosticsEngine *Diags,
2437 bool DefaultDiagColor) {
2438 std::optional<DiagnosticsEngine> IgnoringDiags;
2439 if (!Diags) {
2440 IgnoringDiags.emplace(new DiagnosticIDs(), new DiagnosticOptions(),
2441 new IgnoringDiagConsumer());
2442 Diags = &*IgnoringDiags;
2445 unsigned NumErrorsBefore = Diags->getNumErrors();
2447 // The key paths of diagnostic options defined in Options.td start with
2448 // "DiagnosticOpts->". Let's provide the expected variable name and type.
2449 DiagnosticOptions *DiagnosticOpts = &Opts;
2451 #define DIAG_OPTION_WITH_MARSHALLING(...) \
2452 PARSE_OPTION_WITH_MARSHALLING(Args, *Diags, __VA_ARGS__)
2453 #include "clang/Driver/Options.inc"
2454 #undef DIAG_OPTION_WITH_MARSHALLING
2456 llvm::sys::Process::UseANSIEscapeCodes(Opts.UseANSIEscapeCodes);
2458 if (Arg *A =
2459 Args.getLastArg(OPT_diagnostic_serialized_file, OPT__serialize_diags))
2460 Opts.DiagnosticSerializationFile = A->getValue();
2461 Opts.ShowColors = parseShowColorsArgs(Args, DefaultDiagColor);
2463 Opts.VerifyDiagnostics = Args.hasArg(OPT_verify) || Args.hasArg(OPT_verify_EQ);
2464 Opts.VerifyPrefixes = Args.getAllArgValues(OPT_verify_EQ);
2465 if (Args.hasArg(OPT_verify))
2466 Opts.VerifyPrefixes.push_back("expected");
2467 // Keep VerifyPrefixes in its original order for the sake of diagnostics, and
2468 // then sort it to prepare for fast lookup using std::binary_search.
2469 if (!checkVerifyPrefixes(Opts.VerifyPrefixes, *Diags))
2470 Opts.VerifyDiagnostics = false;
2471 else
2472 llvm::sort(Opts.VerifyPrefixes);
2473 DiagnosticLevelMask DiagMask = DiagnosticLevelMask::None;
2474 parseDiagnosticLevelMask(
2475 "-verify-ignore-unexpected=",
2476 Args.getAllArgValues(OPT_verify_ignore_unexpected_EQ), *Diags, DiagMask);
2477 if (Args.hasArg(OPT_verify_ignore_unexpected))
2478 DiagMask = DiagnosticLevelMask::All;
2479 Opts.setVerifyIgnoreUnexpected(DiagMask);
2480 if (Opts.TabStop == 0 || Opts.TabStop > DiagnosticOptions::MaxTabStop) {
2481 Diags->Report(diag::warn_ignoring_ftabstop_value)
2482 << Opts.TabStop << DiagnosticOptions::DefaultTabStop;
2483 Opts.TabStop = DiagnosticOptions::DefaultTabStop;
2486 addDiagnosticArgs(Args, OPT_W_Group, OPT_W_value_Group, Opts.Warnings);
2487 addDiagnosticArgs(Args, OPT_R_Group, OPT_R_value_Group, Opts.Remarks);
2489 return Diags->getNumErrors() == NumErrorsBefore;
2492 /// Parse the argument to the -ftest-module-file-extension
2493 /// command-line argument.
2495 /// \returns true on error, false on success.
2496 static bool parseTestModuleFileExtensionArg(StringRef Arg,
2497 std::string &BlockName,
2498 unsigned &MajorVersion,
2499 unsigned &MinorVersion,
2500 bool &Hashed,
2501 std::string &UserInfo) {
2502 SmallVector<StringRef, 5> Args;
2503 Arg.split(Args, ':', 5);
2504 if (Args.size() < 5)
2505 return true;
2507 BlockName = std::string(Args[0]);
2508 if (Args[1].getAsInteger(10, MajorVersion)) return true;
2509 if (Args[2].getAsInteger(10, MinorVersion)) return true;
2510 if (Args[3].getAsInteger(2, Hashed)) return true;
2511 if (Args.size() > 4)
2512 UserInfo = std::string(Args[4]);
2513 return false;
2516 /// Return a table that associates command line option specifiers with the
2517 /// frontend action. Note: The pair {frontend::PluginAction, OPT_plugin} is
2518 /// intentionally missing, as this case is handled separately from other
2519 /// frontend options.
2520 static const auto &getFrontendActionTable() {
2521 static const std::pair<frontend::ActionKind, unsigned> Table[] = {
2522 {frontend::ASTDeclList, OPT_ast_list},
2524 {frontend::ASTDump, OPT_ast_dump_all_EQ},
2525 {frontend::ASTDump, OPT_ast_dump_all},
2526 {frontend::ASTDump, OPT_ast_dump_EQ},
2527 {frontend::ASTDump, OPT_ast_dump},
2528 {frontend::ASTDump, OPT_ast_dump_lookups},
2529 {frontend::ASTDump, OPT_ast_dump_decl_types},
2531 {frontend::ASTPrint, OPT_ast_print},
2532 {frontend::ASTView, OPT_ast_view},
2533 {frontend::DumpCompilerOptions, OPT_compiler_options_dump},
2534 {frontend::DumpRawTokens, OPT_dump_raw_tokens},
2535 {frontend::DumpTokens, OPT_dump_tokens},
2536 {frontend::EmitAssembly, OPT_S},
2537 {frontend::EmitBC, OPT_emit_llvm_bc},
2538 {frontend::EmitHTML, OPT_emit_html},
2539 {frontend::EmitLLVM, OPT_emit_llvm},
2540 {frontend::EmitLLVMOnly, OPT_emit_llvm_only},
2541 {frontend::EmitCodeGenOnly, OPT_emit_codegen_only},
2542 {frontend::EmitObj, OPT_emit_obj},
2543 {frontend::ExtractAPI, OPT_extract_api},
2545 {frontend::FixIt, OPT_fixit_EQ},
2546 {frontend::FixIt, OPT_fixit},
2548 {frontend::GenerateModule, OPT_emit_module},
2549 {frontend::GenerateModuleInterface, OPT_emit_module_interface},
2550 {frontend::GenerateHeaderUnit, OPT_emit_header_unit},
2551 {frontend::GeneratePCH, OPT_emit_pch},
2552 {frontend::GenerateInterfaceStubs, OPT_emit_interface_stubs},
2553 {frontend::InitOnly, OPT_init_only},
2554 {frontend::ParseSyntaxOnly, OPT_fsyntax_only},
2555 {frontend::ModuleFileInfo, OPT_module_file_info},
2556 {frontend::VerifyPCH, OPT_verify_pch},
2557 {frontend::PrintPreamble, OPT_print_preamble},
2558 {frontend::PrintPreprocessedInput, OPT_E},
2559 {frontend::TemplightDump, OPT_templight_dump},
2560 {frontend::RewriteMacros, OPT_rewrite_macros},
2561 {frontend::RewriteObjC, OPT_rewrite_objc},
2562 {frontend::RewriteTest, OPT_rewrite_test},
2563 {frontend::RunAnalysis, OPT_analyze},
2564 {frontend::MigrateSource, OPT_migrate},
2565 {frontend::RunPreprocessorOnly, OPT_Eonly},
2566 {frontend::PrintDependencyDirectivesSourceMinimizerOutput,
2567 OPT_print_dependency_directives_minimized_source},
2570 return Table;
2573 /// Maps command line option to frontend action.
2574 static std::optional<frontend::ActionKind>
2575 getFrontendAction(OptSpecifier &Opt) {
2576 for (const auto &ActionOpt : getFrontendActionTable())
2577 if (ActionOpt.second == Opt.getID())
2578 return ActionOpt.first;
2580 return std::nullopt;
2583 /// Maps frontend action to command line option.
2584 static std::optional<OptSpecifier>
2585 getProgramActionOpt(frontend::ActionKind ProgramAction) {
2586 for (const auto &ActionOpt : getFrontendActionTable())
2587 if (ActionOpt.first == ProgramAction)
2588 return OptSpecifier(ActionOpt.second);
2590 return std::nullopt;
2593 static void GenerateFrontendArgs(const FrontendOptions &Opts,
2594 ArgumentConsumer Consumer, bool IsHeader) {
2595 const FrontendOptions &FrontendOpts = Opts;
2596 #define FRONTEND_OPTION_WITH_MARSHALLING(...) \
2597 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
2598 #include "clang/Driver/Options.inc"
2599 #undef FRONTEND_OPTION_WITH_MARSHALLING
2601 std::optional<OptSpecifier> ProgramActionOpt =
2602 getProgramActionOpt(Opts.ProgramAction);
2604 // Generating a simple flag covers most frontend actions.
2605 std::function<void()> GenerateProgramAction = [&]() {
2606 GenerateArg(Consumer, *ProgramActionOpt);
2609 if (!ProgramActionOpt) {
2610 // PluginAction is the only program action handled separately.
2611 assert(Opts.ProgramAction == frontend::PluginAction &&
2612 "Frontend action without option.");
2613 GenerateProgramAction = [&]() {
2614 GenerateArg(Consumer, OPT_plugin, Opts.ActionName);
2618 // FIXME: Simplify the complex 'AST dump' command line.
2619 if (Opts.ProgramAction == frontend::ASTDump) {
2620 GenerateProgramAction = [&]() {
2621 // ASTDumpLookups, ASTDumpDeclTypes and ASTDumpFilter are generated via
2622 // marshalling infrastructure.
2624 if (Opts.ASTDumpFormat != ADOF_Default) {
2625 StringRef Format;
2626 switch (Opts.ASTDumpFormat) {
2627 case ADOF_Default:
2628 llvm_unreachable("Default AST dump format.");
2629 case ADOF_JSON:
2630 Format = "json";
2631 break;
2634 if (Opts.ASTDumpAll)
2635 GenerateArg(Consumer, OPT_ast_dump_all_EQ, Format);
2636 if (Opts.ASTDumpDecls)
2637 GenerateArg(Consumer, OPT_ast_dump_EQ, Format);
2638 } else {
2639 if (Opts.ASTDumpAll)
2640 GenerateArg(Consumer, OPT_ast_dump_all);
2641 if (Opts.ASTDumpDecls)
2642 GenerateArg(Consumer, OPT_ast_dump);
2647 if (Opts.ProgramAction == frontend::FixIt && !Opts.FixItSuffix.empty()) {
2648 GenerateProgramAction = [&]() {
2649 GenerateArg(Consumer, OPT_fixit_EQ, Opts.FixItSuffix);
2653 GenerateProgramAction();
2655 for (const auto &PluginArgs : Opts.PluginArgs) {
2656 Option Opt = getDriverOptTable().getOption(OPT_plugin_arg);
2657 for (const auto &PluginArg : PluginArgs.second)
2658 denormalizeString(Consumer,
2659 Opt.getPrefix() + Opt.getName() + PluginArgs.first,
2660 Opt.getKind(), 0, PluginArg);
2663 for (const auto &Ext : Opts.ModuleFileExtensions)
2664 if (auto *TestExt = dyn_cast_or_null<TestModuleFileExtension>(Ext.get()))
2665 GenerateArg(Consumer, OPT_ftest_module_file_extension_EQ, TestExt->str());
2667 if (!Opts.CodeCompletionAt.FileName.empty())
2668 GenerateArg(Consumer, OPT_code_completion_at,
2669 Opts.CodeCompletionAt.ToString());
2671 for (const auto &Plugin : Opts.Plugins)
2672 GenerateArg(Consumer, OPT_load, Plugin);
2674 // ASTDumpDecls and ASTDumpAll already handled with ProgramAction.
2676 for (const auto &ModuleFile : Opts.ModuleFiles)
2677 GenerateArg(Consumer, OPT_fmodule_file, ModuleFile);
2679 if (Opts.AuxTargetCPU)
2680 GenerateArg(Consumer, OPT_aux_target_cpu, *Opts.AuxTargetCPU);
2682 if (Opts.AuxTargetFeatures)
2683 for (const auto &Feature : *Opts.AuxTargetFeatures)
2684 GenerateArg(Consumer, OPT_aux_target_feature, Feature);
2687 StringRef Preprocessed = Opts.DashX.isPreprocessed() ? "-cpp-output" : "";
2688 StringRef ModuleMap =
2689 Opts.DashX.getFormat() == InputKind::ModuleMap ? "-module-map" : "";
2690 StringRef HeaderUnit = "";
2691 switch (Opts.DashX.getHeaderUnitKind()) {
2692 case InputKind::HeaderUnit_None:
2693 break;
2694 case InputKind::HeaderUnit_User:
2695 HeaderUnit = "-user";
2696 break;
2697 case InputKind::HeaderUnit_System:
2698 HeaderUnit = "-system";
2699 break;
2700 case InputKind::HeaderUnit_Abs:
2701 HeaderUnit = "-header-unit";
2702 break;
2704 StringRef Header = IsHeader ? "-header" : "";
2706 StringRef Lang;
2707 switch (Opts.DashX.getLanguage()) {
2708 case Language::C:
2709 Lang = "c";
2710 break;
2711 case Language::OpenCL:
2712 Lang = "cl";
2713 break;
2714 case Language::OpenCLCXX:
2715 Lang = "clcpp";
2716 break;
2717 case Language::CUDA:
2718 Lang = "cuda";
2719 break;
2720 case Language::HIP:
2721 Lang = "hip";
2722 break;
2723 case Language::CXX:
2724 Lang = "c++";
2725 break;
2726 case Language::ObjC:
2727 Lang = "objective-c";
2728 break;
2729 case Language::ObjCXX:
2730 Lang = "objective-c++";
2731 break;
2732 case Language::RenderScript:
2733 Lang = "renderscript";
2734 break;
2735 case Language::Asm:
2736 Lang = "assembler-with-cpp";
2737 break;
2738 case Language::Unknown:
2739 assert(Opts.DashX.getFormat() == InputKind::Precompiled &&
2740 "Generating -x argument for unknown language (not precompiled).");
2741 Lang = "ast";
2742 break;
2743 case Language::LLVM_IR:
2744 Lang = "ir";
2745 break;
2746 case Language::HLSL:
2747 Lang = "hlsl";
2748 break;
2751 GenerateArg(Consumer, OPT_x,
2752 Lang + HeaderUnit + Header + ModuleMap + Preprocessed);
2755 // OPT_INPUT has a unique class, generate it directly.
2756 for (const auto &Input : Opts.Inputs)
2757 Consumer(Input.getFile());
2760 static bool ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args,
2761 DiagnosticsEngine &Diags, bool &IsHeaderFile) {
2762 unsigned NumErrorsBefore = Diags.getNumErrors();
2764 FrontendOptions &FrontendOpts = Opts;
2766 #define FRONTEND_OPTION_WITH_MARSHALLING(...) \
2767 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
2768 #include "clang/Driver/Options.inc"
2769 #undef FRONTEND_OPTION_WITH_MARSHALLING
2771 Opts.ProgramAction = frontend::ParseSyntaxOnly;
2772 if (const Arg *A = Args.getLastArg(OPT_Action_Group)) {
2773 OptSpecifier Opt = OptSpecifier(A->getOption().getID());
2774 std::optional<frontend::ActionKind> ProgramAction = getFrontendAction(Opt);
2775 assert(ProgramAction && "Option specifier not in Action_Group.");
2777 if (ProgramAction == frontend::ASTDump &&
2778 (Opt == OPT_ast_dump_all_EQ || Opt == OPT_ast_dump_EQ)) {
2779 unsigned Val = llvm::StringSwitch<unsigned>(A->getValue())
2780 .CaseLower("default", ADOF_Default)
2781 .CaseLower("json", ADOF_JSON)
2782 .Default(std::numeric_limits<unsigned>::max());
2784 if (Val != std::numeric_limits<unsigned>::max())
2785 Opts.ASTDumpFormat = static_cast<ASTDumpOutputFormat>(Val);
2786 else {
2787 Diags.Report(diag::err_drv_invalid_value)
2788 << A->getAsString(Args) << A->getValue();
2789 Opts.ASTDumpFormat = ADOF_Default;
2793 if (ProgramAction == frontend::FixIt && Opt == OPT_fixit_EQ)
2794 Opts.FixItSuffix = A->getValue();
2796 if (ProgramAction == frontend::GenerateInterfaceStubs) {
2797 StringRef ArgStr =
2798 Args.hasArg(OPT_interface_stub_version_EQ)
2799 ? Args.getLastArgValue(OPT_interface_stub_version_EQ)
2800 : "ifs-v1";
2801 if (ArgStr == "experimental-yaml-elf-v1" ||
2802 ArgStr == "experimental-ifs-v1" || ArgStr == "experimental-ifs-v2" ||
2803 ArgStr == "experimental-tapi-elf-v1") {
2804 std::string ErrorMessage =
2805 "Invalid interface stub format: " + ArgStr.str() +
2806 " is deprecated.";
2807 Diags.Report(diag::err_drv_invalid_value)
2808 << "Must specify a valid interface stub format type, ie: "
2809 "-interface-stub-version=ifs-v1"
2810 << ErrorMessage;
2811 ProgramAction = frontend::ParseSyntaxOnly;
2812 } else if (!ArgStr.startswith("ifs-")) {
2813 std::string ErrorMessage =
2814 "Invalid interface stub format: " + ArgStr.str() + ".";
2815 Diags.Report(diag::err_drv_invalid_value)
2816 << "Must specify a valid interface stub format type, ie: "
2817 "-interface-stub-version=ifs-v1"
2818 << ErrorMessage;
2819 ProgramAction = frontend::ParseSyntaxOnly;
2823 Opts.ProgramAction = *ProgramAction;
2826 if (const Arg* A = Args.getLastArg(OPT_plugin)) {
2827 Opts.Plugins.emplace_back(A->getValue(0));
2828 Opts.ProgramAction = frontend::PluginAction;
2829 Opts.ActionName = A->getValue();
2831 for (const auto *AA : Args.filtered(OPT_plugin_arg))
2832 Opts.PluginArgs[AA->getValue(0)].emplace_back(AA->getValue(1));
2834 for (const std::string &Arg :
2835 Args.getAllArgValues(OPT_ftest_module_file_extension_EQ)) {
2836 std::string BlockName;
2837 unsigned MajorVersion;
2838 unsigned MinorVersion;
2839 bool Hashed;
2840 std::string UserInfo;
2841 if (parseTestModuleFileExtensionArg(Arg, BlockName, MajorVersion,
2842 MinorVersion, Hashed, UserInfo)) {
2843 Diags.Report(diag::err_test_module_file_extension_format) << Arg;
2845 continue;
2848 // Add the testing module file extension.
2849 Opts.ModuleFileExtensions.push_back(
2850 std::make_shared<TestModuleFileExtension>(
2851 BlockName, MajorVersion, MinorVersion, Hashed, UserInfo));
2854 if (const Arg *A = Args.getLastArg(OPT_code_completion_at)) {
2855 Opts.CodeCompletionAt =
2856 ParsedSourceLocation::FromString(A->getValue());
2857 if (Opts.CodeCompletionAt.FileName.empty())
2858 Diags.Report(diag::err_drv_invalid_value)
2859 << A->getAsString(Args) << A->getValue();
2862 Opts.Plugins = Args.getAllArgValues(OPT_load);
2863 Opts.ASTDumpDecls = Args.hasArg(OPT_ast_dump, OPT_ast_dump_EQ);
2864 Opts.ASTDumpAll = Args.hasArg(OPT_ast_dump_all, OPT_ast_dump_all_EQ);
2865 // Only the -fmodule-file=<file> form.
2866 for (const auto *A : Args.filtered(OPT_fmodule_file)) {
2867 StringRef Val = A->getValue();
2868 if (!Val.contains('='))
2869 Opts.ModuleFiles.push_back(std::string(Val));
2872 if (Opts.ProgramAction != frontend::GenerateModule && Opts.IsSystemModule)
2873 Diags.Report(diag::err_drv_argument_only_allowed_with) << "-fsystem-module"
2874 << "-emit-module";
2876 if (Args.hasArg(OPT_aux_target_cpu))
2877 Opts.AuxTargetCPU = std::string(Args.getLastArgValue(OPT_aux_target_cpu));
2878 if (Args.hasArg(OPT_aux_target_feature))
2879 Opts.AuxTargetFeatures = Args.getAllArgValues(OPT_aux_target_feature);
2881 if (Opts.ARCMTAction != FrontendOptions::ARCMT_None &&
2882 Opts.ObjCMTAction != FrontendOptions::ObjCMT_None) {
2883 Diags.Report(diag::err_drv_argument_not_allowed_with)
2884 << "ARC migration" << "ObjC migration";
2887 InputKind DashX(Language::Unknown);
2888 if (const Arg *A = Args.getLastArg(OPT_x)) {
2889 StringRef XValue = A->getValue();
2891 // Parse suffixes:
2892 // '<lang>(-[{header-unit,user,system}-]header|[-module-map][-cpp-output])'.
2893 // FIXME: Supporting '<lang>-header-cpp-output' would be useful.
2894 bool Preprocessed = XValue.consume_back("-cpp-output");
2895 bool ModuleMap = XValue.consume_back("-module-map");
2896 // Detect and consume the header indicator.
2897 bool IsHeader =
2898 XValue != "precompiled-header" && XValue.consume_back("-header");
2900 // If we have c++-{user,system}-header, that indicates a header unit input
2901 // likewise, if the user put -fmodule-header together with a header with an
2902 // absolute path (header-unit-header).
2903 InputKind::HeaderUnitKind HUK = InputKind::HeaderUnit_None;
2904 if (IsHeader || Preprocessed) {
2905 if (XValue.consume_back("-header-unit"))
2906 HUK = InputKind::HeaderUnit_Abs;
2907 else if (XValue.consume_back("-system"))
2908 HUK = InputKind::HeaderUnit_System;
2909 else if (XValue.consume_back("-user"))
2910 HUK = InputKind::HeaderUnit_User;
2913 // The value set by this processing is an un-preprocessed source which is
2914 // not intended to be a module map or header unit.
2915 IsHeaderFile = IsHeader && !Preprocessed && !ModuleMap &&
2916 HUK == InputKind::HeaderUnit_None;
2918 // Principal languages.
2919 DashX = llvm::StringSwitch<InputKind>(XValue)
2920 .Case("c", Language::C)
2921 .Case("cl", Language::OpenCL)
2922 .Case("clcpp", Language::OpenCLCXX)
2923 .Case("cuda", Language::CUDA)
2924 .Case("hip", Language::HIP)
2925 .Case("c++", Language::CXX)
2926 .Case("objective-c", Language::ObjC)
2927 .Case("objective-c++", Language::ObjCXX)
2928 .Case("renderscript", Language::RenderScript)
2929 .Case("hlsl", Language::HLSL)
2930 .Default(Language::Unknown);
2932 // "objc[++]-cpp-output" is an acceptable synonym for
2933 // "objective-c[++]-cpp-output".
2934 if (DashX.isUnknown() && Preprocessed && !IsHeaderFile && !ModuleMap &&
2935 HUK == InputKind::HeaderUnit_None)
2936 DashX = llvm::StringSwitch<InputKind>(XValue)
2937 .Case("objc", Language::ObjC)
2938 .Case("objc++", Language::ObjCXX)
2939 .Default(Language::Unknown);
2941 // Some special cases cannot be combined with suffixes.
2942 if (DashX.isUnknown() && !Preprocessed && !IsHeaderFile && !ModuleMap &&
2943 HUK == InputKind::HeaderUnit_None)
2944 DashX = llvm::StringSwitch<InputKind>(XValue)
2945 .Case("cpp-output", InputKind(Language::C).getPreprocessed())
2946 .Case("assembler-with-cpp", Language::Asm)
2947 .Cases("ast", "pcm", "precompiled-header",
2948 InputKind(Language::Unknown, InputKind::Precompiled))
2949 .Case("ir", Language::LLVM_IR)
2950 .Default(Language::Unknown);
2952 if (DashX.isUnknown())
2953 Diags.Report(diag::err_drv_invalid_value)
2954 << A->getAsString(Args) << A->getValue();
2956 if (Preprocessed)
2957 DashX = DashX.getPreprocessed();
2958 // A regular header is considered mutually exclusive with a header unit.
2959 if (HUK != InputKind::HeaderUnit_None) {
2960 DashX = DashX.withHeaderUnit(HUK);
2961 IsHeaderFile = true;
2962 } else if (IsHeaderFile)
2963 DashX = DashX.getHeader();
2964 if (ModuleMap)
2965 DashX = DashX.withFormat(InputKind::ModuleMap);
2968 // '-' is the default input if none is given.
2969 std::vector<std::string> Inputs = Args.getAllArgValues(OPT_INPUT);
2970 Opts.Inputs.clear();
2971 if (Inputs.empty())
2972 Inputs.push_back("-");
2974 if (DashX.getHeaderUnitKind() != InputKind::HeaderUnit_None &&
2975 Inputs.size() > 1)
2976 Diags.Report(diag::err_drv_header_unit_extra_inputs) << Inputs[1];
2978 for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
2979 InputKind IK = DashX;
2980 if (IK.isUnknown()) {
2981 IK = FrontendOptions::getInputKindForExtension(
2982 StringRef(Inputs[i]).rsplit('.').second);
2983 // FIXME: Warn on this?
2984 if (IK.isUnknown())
2985 IK = Language::C;
2986 // FIXME: Remove this hack.
2987 if (i == 0)
2988 DashX = IK;
2991 bool IsSystem = false;
2993 // The -emit-module action implicitly takes a module map.
2994 if (Opts.ProgramAction == frontend::GenerateModule &&
2995 IK.getFormat() == InputKind::Source) {
2996 IK = IK.withFormat(InputKind::ModuleMap);
2997 IsSystem = Opts.IsSystemModule;
3000 Opts.Inputs.emplace_back(std::move(Inputs[i]), IK, IsSystem);
3003 Opts.DashX = DashX;
3005 return Diags.getNumErrors() == NumErrorsBefore;
3008 std::string CompilerInvocation::GetResourcesPath(const char *Argv0,
3009 void *MainAddr) {
3010 std::string ClangExecutable =
3011 llvm::sys::fs::getMainExecutable(Argv0, MainAddr);
3012 return Driver::GetResourcesPath(ClangExecutable, CLANG_RESOURCE_DIR);
3015 static void GenerateHeaderSearchArgs(const HeaderSearchOptions &Opts,
3016 ArgumentConsumer Consumer) {
3017 const HeaderSearchOptions *HeaderSearchOpts = &Opts;
3018 #define HEADER_SEARCH_OPTION_WITH_MARSHALLING(...) \
3019 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
3020 #include "clang/Driver/Options.inc"
3021 #undef HEADER_SEARCH_OPTION_WITH_MARSHALLING
3023 if (Opts.UseLibcxx)
3024 GenerateArg(Consumer, OPT_stdlib_EQ, "libc++");
3026 if (!Opts.ModuleCachePath.empty())
3027 GenerateArg(Consumer, OPT_fmodules_cache_path, Opts.ModuleCachePath);
3029 for (const auto &File : Opts.PrebuiltModuleFiles)
3030 GenerateArg(Consumer, OPT_fmodule_file, File.first + "=" + File.second);
3032 for (const auto &Path : Opts.PrebuiltModulePaths)
3033 GenerateArg(Consumer, OPT_fprebuilt_module_path, Path);
3035 for (const auto &Macro : Opts.ModulesIgnoreMacros)
3036 GenerateArg(Consumer, OPT_fmodules_ignore_macro, Macro.val());
3038 auto Matches = [](const HeaderSearchOptions::Entry &Entry,
3039 llvm::ArrayRef<frontend::IncludeDirGroup> Groups,
3040 std::optional<bool> IsFramework,
3041 std::optional<bool> IgnoreSysRoot) {
3042 return llvm::is_contained(Groups, Entry.Group) &&
3043 (!IsFramework || (Entry.IsFramework == *IsFramework)) &&
3044 (!IgnoreSysRoot || (Entry.IgnoreSysRoot == *IgnoreSysRoot));
3047 auto It = Opts.UserEntries.begin();
3048 auto End = Opts.UserEntries.end();
3050 // Add -I..., -F..., and -index-header-map options in order.
3051 for (; It < End && Matches(*It, {frontend::IndexHeaderMap, frontend::Angled},
3052 std::nullopt, true);
3053 ++It) {
3054 OptSpecifier Opt = [It, Matches]() {
3055 if (Matches(*It, frontend::IndexHeaderMap, true, true))
3056 return OPT_F;
3057 if (Matches(*It, frontend::IndexHeaderMap, false, true))
3058 return OPT_I;
3059 if (Matches(*It, frontend::Angled, true, true))
3060 return OPT_F;
3061 if (Matches(*It, frontend::Angled, false, true))
3062 return OPT_I;
3063 llvm_unreachable("Unexpected HeaderSearchOptions::Entry.");
3064 }();
3066 if (It->Group == frontend::IndexHeaderMap)
3067 GenerateArg(Consumer, OPT_index_header_map);
3068 GenerateArg(Consumer, Opt, It->Path);
3071 // Note: some paths that came from "[-iprefix=xx] -iwithprefixbefore=yy" may
3072 // have already been generated as "-I[xx]yy". If that's the case, their
3073 // position on command line was such that this has no semantic impact on
3074 // include paths.
3075 for (; It < End &&
3076 Matches(*It, {frontend::After, frontend::Angled}, false, true);
3077 ++It) {
3078 OptSpecifier Opt =
3079 It->Group == frontend::After ? OPT_iwithprefix : OPT_iwithprefixbefore;
3080 GenerateArg(Consumer, Opt, It->Path);
3083 // Note: Some paths that came from "-idirafter=xxyy" may have already been
3084 // generated as "-iwithprefix=xxyy". If that's the case, their position on
3085 // command line was such that this has no semantic impact on include paths.
3086 for (; It < End && Matches(*It, {frontend::After}, false, true); ++It)
3087 GenerateArg(Consumer, OPT_idirafter, It->Path);
3088 for (; It < End && Matches(*It, {frontend::Quoted}, false, true); ++It)
3089 GenerateArg(Consumer, OPT_iquote, It->Path);
3090 for (; It < End && Matches(*It, {frontend::System}, false, std::nullopt);
3091 ++It)
3092 GenerateArg(Consumer, It->IgnoreSysRoot ? OPT_isystem : OPT_iwithsysroot,
3093 It->Path);
3094 for (; It < End && Matches(*It, {frontend::System}, true, true); ++It)
3095 GenerateArg(Consumer, OPT_iframework, It->Path);
3096 for (; It < End && Matches(*It, {frontend::System}, true, false); ++It)
3097 GenerateArg(Consumer, OPT_iframeworkwithsysroot, It->Path);
3099 // Add the paths for the various language specific isystem flags.
3100 for (; It < End && Matches(*It, {frontend::CSystem}, false, true); ++It)
3101 GenerateArg(Consumer, OPT_c_isystem, It->Path);
3102 for (; It < End && Matches(*It, {frontend::CXXSystem}, false, true); ++It)
3103 GenerateArg(Consumer, OPT_cxx_isystem, It->Path);
3104 for (; It < End && Matches(*It, {frontend::ObjCSystem}, false, true); ++It)
3105 GenerateArg(Consumer, OPT_objc_isystem, It->Path);
3106 for (; It < End && Matches(*It, {frontend::ObjCXXSystem}, false, true); ++It)
3107 GenerateArg(Consumer, OPT_objcxx_isystem, It->Path);
3109 // Add the internal paths from a driver that detects standard include paths.
3110 // Note: Some paths that came from "-internal-isystem" arguments may have
3111 // already been generated as "-isystem". If that's the case, their position on
3112 // command line was such that this has no semantic impact on include paths.
3113 for (; It < End &&
3114 Matches(*It, {frontend::System, frontend::ExternCSystem}, false, true);
3115 ++It) {
3116 OptSpecifier Opt = It->Group == frontend::System
3117 ? OPT_internal_isystem
3118 : OPT_internal_externc_isystem;
3119 GenerateArg(Consumer, Opt, It->Path);
3122 assert(It == End && "Unhandled HeaderSearchOption::Entry.");
3124 // Add the path prefixes which are implicitly treated as being system headers.
3125 for (const auto &P : Opts.SystemHeaderPrefixes) {
3126 OptSpecifier Opt = P.IsSystemHeader ? OPT_system_header_prefix
3127 : OPT_no_system_header_prefix;
3128 GenerateArg(Consumer, Opt, P.Prefix);
3131 for (const std::string &F : Opts.VFSOverlayFiles)
3132 GenerateArg(Consumer, OPT_ivfsoverlay, F);
3135 static bool ParseHeaderSearchArgs(HeaderSearchOptions &Opts, ArgList &Args,
3136 DiagnosticsEngine &Diags,
3137 const std::string &WorkingDir) {
3138 unsigned NumErrorsBefore = Diags.getNumErrors();
3140 HeaderSearchOptions *HeaderSearchOpts = &Opts;
3142 #define HEADER_SEARCH_OPTION_WITH_MARSHALLING(...) \
3143 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
3144 #include "clang/Driver/Options.inc"
3145 #undef HEADER_SEARCH_OPTION_WITH_MARSHALLING
3147 if (const Arg *A = Args.getLastArg(OPT_stdlib_EQ))
3148 Opts.UseLibcxx = (strcmp(A->getValue(), "libc++") == 0);
3150 // Canonicalize -fmodules-cache-path before storing it.
3151 SmallString<128> P(Args.getLastArgValue(OPT_fmodules_cache_path));
3152 if (!(P.empty() || llvm::sys::path::is_absolute(P))) {
3153 if (WorkingDir.empty())
3154 llvm::sys::fs::make_absolute(P);
3155 else
3156 llvm::sys::fs::make_absolute(WorkingDir, P);
3158 llvm::sys::path::remove_dots(P);
3159 Opts.ModuleCachePath = std::string(P.str());
3161 // Only the -fmodule-file=<name>=<file> form.
3162 for (const auto *A : Args.filtered(OPT_fmodule_file)) {
3163 StringRef Val = A->getValue();
3164 if (Val.contains('=')) {
3165 auto Split = Val.split('=');
3166 Opts.PrebuiltModuleFiles.insert_or_assign(
3167 std::string(Split.first), std::string(Split.second));
3170 for (const auto *A : Args.filtered(OPT_fprebuilt_module_path))
3171 Opts.AddPrebuiltModulePath(A->getValue());
3173 for (const auto *A : Args.filtered(OPT_fmodules_ignore_macro)) {
3174 StringRef MacroDef = A->getValue();
3175 Opts.ModulesIgnoreMacros.insert(
3176 llvm::CachedHashString(MacroDef.split('=').first));
3179 // Add -I..., -F..., and -index-header-map options in order.
3180 bool IsIndexHeaderMap = false;
3181 bool IsSysrootSpecified =
3182 Args.hasArg(OPT__sysroot_EQ) || Args.hasArg(OPT_isysroot);
3183 for (const auto *A : Args.filtered(OPT_I, OPT_F, OPT_index_header_map)) {
3184 if (A->getOption().matches(OPT_index_header_map)) {
3185 // -index-header-map applies to the next -I or -F.
3186 IsIndexHeaderMap = true;
3187 continue;
3190 frontend::IncludeDirGroup Group =
3191 IsIndexHeaderMap ? frontend::IndexHeaderMap : frontend::Angled;
3193 bool IsFramework = A->getOption().matches(OPT_F);
3194 std::string Path = A->getValue();
3196 if (IsSysrootSpecified && !IsFramework && A->getValue()[0] == '=') {
3197 SmallString<32> Buffer;
3198 llvm::sys::path::append(Buffer, Opts.Sysroot,
3199 llvm::StringRef(A->getValue()).substr(1));
3200 Path = std::string(Buffer.str());
3203 Opts.AddPath(Path, Group, IsFramework,
3204 /*IgnoreSysroot*/ true);
3205 IsIndexHeaderMap = false;
3208 // Add -iprefix/-iwithprefix/-iwithprefixbefore options.
3209 StringRef Prefix = ""; // FIXME: This isn't the correct default prefix.
3210 for (const auto *A :
3211 Args.filtered(OPT_iprefix, OPT_iwithprefix, OPT_iwithprefixbefore)) {
3212 if (A->getOption().matches(OPT_iprefix))
3213 Prefix = A->getValue();
3214 else if (A->getOption().matches(OPT_iwithprefix))
3215 Opts.AddPath(Prefix.str() + A->getValue(), frontend::After, false, true);
3216 else
3217 Opts.AddPath(Prefix.str() + A->getValue(), frontend::Angled, false, true);
3220 for (const auto *A : Args.filtered(OPT_idirafter))
3221 Opts.AddPath(A->getValue(), frontend::After, false, true);
3222 for (const auto *A : Args.filtered(OPT_iquote))
3223 Opts.AddPath(A->getValue(), frontend::Quoted, false, true);
3224 for (const auto *A : Args.filtered(OPT_isystem, OPT_iwithsysroot))
3225 Opts.AddPath(A->getValue(), frontend::System, false,
3226 !A->getOption().matches(OPT_iwithsysroot));
3227 for (const auto *A : Args.filtered(OPT_iframework))
3228 Opts.AddPath(A->getValue(), frontend::System, true, true);
3229 for (const auto *A : Args.filtered(OPT_iframeworkwithsysroot))
3230 Opts.AddPath(A->getValue(), frontend::System, /*IsFramework=*/true,
3231 /*IgnoreSysRoot=*/false);
3233 // Add the paths for the various language specific isystem flags.
3234 for (const auto *A : Args.filtered(OPT_c_isystem))
3235 Opts.AddPath(A->getValue(), frontend::CSystem, false, true);
3236 for (const auto *A : Args.filtered(OPT_cxx_isystem))
3237 Opts.AddPath(A->getValue(), frontend::CXXSystem, false, true);
3238 for (const auto *A : Args.filtered(OPT_objc_isystem))
3239 Opts.AddPath(A->getValue(), frontend::ObjCSystem, false,true);
3240 for (const auto *A : Args.filtered(OPT_objcxx_isystem))
3241 Opts.AddPath(A->getValue(), frontend::ObjCXXSystem, false, true);
3243 // Add the internal paths from a driver that detects standard include paths.
3244 for (const auto *A :
3245 Args.filtered(OPT_internal_isystem, OPT_internal_externc_isystem)) {
3246 frontend::IncludeDirGroup Group = frontend::System;
3247 if (A->getOption().matches(OPT_internal_externc_isystem))
3248 Group = frontend::ExternCSystem;
3249 Opts.AddPath(A->getValue(), Group, false, true);
3252 // Add the path prefixes which are implicitly treated as being system headers.
3253 for (const auto *A :
3254 Args.filtered(OPT_system_header_prefix, OPT_no_system_header_prefix))
3255 Opts.AddSystemHeaderPrefix(
3256 A->getValue(), A->getOption().matches(OPT_system_header_prefix));
3258 for (const auto *A : Args.filtered(OPT_ivfsoverlay, OPT_vfsoverlay))
3259 Opts.AddVFSOverlayFile(A->getValue());
3261 return Diags.getNumErrors() == NumErrorsBefore;
3264 /// Check if input file kind and language standard are compatible.
3265 static bool IsInputCompatibleWithStandard(InputKind IK,
3266 const LangStandard &S) {
3267 switch (IK.getLanguage()) {
3268 case Language::Unknown:
3269 case Language::LLVM_IR:
3270 llvm_unreachable("should not parse language flags for this input");
3272 case Language::C:
3273 case Language::ObjC:
3274 case Language::RenderScript:
3275 return S.getLanguage() == Language::C;
3277 case Language::OpenCL:
3278 return S.getLanguage() == Language::OpenCL ||
3279 S.getLanguage() == Language::OpenCLCXX;
3281 case Language::OpenCLCXX:
3282 return S.getLanguage() == Language::OpenCLCXX;
3284 case Language::CXX:
3285 case Language::ObjCXX:
3286 return S.getLanguage() == Language::CXX;
3288 case Language::CUDA:
3289 // FIXME: What -std= values should be permitted for CUDA compilations?
3290 return S.getLanguage() == Language::CUDA ||
3291 S.getLanguage() == Language::CXX;
3293 case Language::HIP:
3294 return S.getLanguage() == Language::CXX || S.getLanguage() == Language::HIP;
3296 case Language::Asm:
3297 // Accept (and ignore) all -std= values.
3298 // FIXME: The -std= value is not ignored; it affects the tokenization
3299 // and preprocessing rules if we're preprocessing this asm input.
3300 return true;
3302 case Language::HLSL:
3303 return S.getLanguage() == Language::HLSL;
3306 llvm_unreachable("unexpected input language");
3309 /// Get language name for given input kind.
3310 static StringRef GetInputKindName(InputKind IK) {
3311 switch (IK.getLanguage()) {
3312 case Language::C:
3313 return "C";
3314 case Language::ObjC:
3315 return "Objective-C";
3316 case Language::CXX:
3317 return "C++";
3318 case Language::ObjCXX:
3319 return "Objective-C++";
3320 case Language::OpenCL:
3321 return "OpenCL";
3322 case Language::OpenCLCXX:
3323 return "C++ for OpenCL";
3324 case Language::CUDA:
3325 return "CUDA";
3326 case Language::RenderScript:
3327 return "RenderScript";
3328 case Language::HIP:
3329 return "HIP";
3331 case Language::Asm:
3332 return "Asm";
3333 case Language::LLVM_IR:
3334 return "LLVM IR";
3336 case Language::HLSL:
3337 return "HLSL";
3339 case Language::Unknown:
3340 break;
3342 llvm_unreachable("unknown input language");
3345 void CompilerInvocationBase::GenerateLangArgs(const LangOptions &Opts,
3346 ArgumentConsumer Consumer,
3347 const llvm::Triple &T,
3348 InputKind IK) {
3349 if (IK.getFormat() == InputKind::Precompiled ||
3350 IK.getLanguage() == Language::LLVM_IR) {
3351 if (Opts.ObjCAutoRefCount)
3352 GenerateArg(Consumer, OPT_fobjc_arc);
3353 if (Opts.PICLevel != 0)
3354 GenerateArg(Consumer, OPT_pic_level, Twine(Opts.PICLevel));
3355 if (Opts.PIE)
3356 GenerateArg(Consumer, OPT_pic_is_pie);
3357 for (StringRef Sanitizer : serializeSanitizerKinds(Opts.Sanitize))
3358 GenerateArg(Consumer, OPT_fsanitize_EQ, Sanitizer);
3360 return;
3363 OptSpecifier StdOpt;
3364 switch (Opts.LangStd) {
3365 case LangStandard::lang_opencl10:
3366 case LangStandard::lang_opencl11:
3367 case LangStandard::lang_opencl12:
3368 case LangStandard::lang_opencl20:
3369 case LangStandard::lang_opencl30:
3370 case LangStandard::lang_openclcpp10:
3371 case LangStandard::lang_openclcpp2021:
3372 StdOpt = OPT_cl_std_EQ;
3373 break;
3374 default:
3375 StdOpt = OPT_std_EQ;
3376 break;
3379 auto LangStandard = LangStandard::getLangStandardForKind(Opts.LangStd);
3380 GenerateArg(Consumer, StdOpt, LangStandard.getName());
3382 if (Opts.IncludeDefaultHeader)
3383 GenerateArg(Consumer, OPT_finclude_default_header);
3384 if (Opts.DeclareOpenCLBuiltins)
3385 GenerateArg(Consumer, OPT_fdeclare_opencl_builtins);
3387 const LangOptions *LangOpts = &Opts;
3389 #define LANG_OPTION_WITH_MARSHALLING(...) \
3390 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
3391 #include "clang/Driver/Options.inc"
3392 #undef LANG_OPTION_WITH_MARSHALLING
3394 // The '-fcf-protection=' option is generated by CodeGenOpts generator.
3396 if (Opts.ObjC) {
3397 GenerateArg(Consumer, OPT_fobjc_runtime_EQ, Opts.ObjCRuntime.getAsString());
3399 if (Opts.GC == LangOptions::GCOnly)
3400 GenerateArg(Consumer, OPT_fobjc_gc_only);
3401 else if (Opts.GC == LangOptions::HybridGC)
3402 GenerateArg(Consumer, OPT_fobjc_gc);
3403 else if (Opts.ObjCAutoRefCount == 1)
3404 GenerateArg(Consumer, OPT_fobjc_arc);
3406 if (Opts.ObjCWeakRuntime)
3407 GenerateArg(Consumer, OPT_fobjc_runtime_has_weak);
3409 if (Opts.ObjCWeak)
3410 GenerateArg(Consumer, OPT_fobjc_weak);
3412 if (Opts.ObjCSubscriptingLegacyRuntime)
3413 GenerateArg(Consumer, OPT_fobjc_subscripting_legacy_runtime);
3416 if (Opts.GNUCVersion != 0) {
3417 unsigned Major = Opts.GNUCVersion / 100 / 100;
3418 unsigned Minor = (Opts.GNUCVersion / 100) % 100;
3419 unsigned Patch = Opts.GNUCVersion % 100;
3420 GenerateArg(Consumer, OPT_fgnuc_version_EQ,
3421 Twine(Major) + "." + Twine(Minor) + "." + Twine(Patch));
3424 if (Opts.IgnoreXCOFFVisibility)
3425 GenerateArg(Consumer, OPT_mignore_xcoff_visibility);
3427 if (Opts.SignedOverflowBehavior == LangOptions::SOB_Trapping) {
3428 GenerateArg(Consumer, OPT_ftrapv);
3429 GenerateArg(Consumer, OPT_ftrapv_handler, Opts.OverflowHandler);
3430 } else if (Opts.SignedOverflowBehavior == LangOptions::SOB_Defined) {
3431 GenerateArg(Consumer, OPT_fwrapv);
3434 if (Opts.MSCompatibilityVersion != 0) {
3435 unsigned Major = Opts.MSCompatibilityVersion / 10000000;
3436 unsigned Minor = (Opts.MSCompatibilityVersion / 100000) % 100;
3437 unsigned Subminor = Opts.MSCompatibilityVersion % 100000;
3438 GenerateArg(Consumer, OPT_fms_compatibility_version,
3439 Twine(Major) + "." + Twine(Minor) + "." + Twine(Subminor));
3442 if ((!Opts.GNUMode && !Opts.MSVCCompat && !Opts.CPlusPlus17) || T.isOSzOS()) {
3443 if (!Opts.Trigraphs)
3444 GenerateArg(Consumer, OPT_fno_trigraphs);
3445 } else {
3446 if (Opts.Trigraphs)
3447 GenerateArg(Consumer, OPT_ftrigraphs);
3450 if (Opts.Blocks && !(Opts.OpenCL && Opts.OpenCLVersion == 200))
3451 GenerateArg(Consumer, OPT_fblocks);
3453 if (Opts.ConvergentFunctions &&
3454 !(Opts.OpenCL || (Opts.CUDA && Opts.CUDAIsDevice) || Opts.SYCLIsDevice))
3455 GenerateArg(Consumer, OPT_fconvergent_functions);
3457 if (Opts.NoBuiltin && !Opts.Freestanding)
3458 GenerateArg(Consumer, OPT_fno_builtin);
3460 if (!Opts.NoBuiltin)
3461 for (const auto &Func : Opts.NoBuiltinFuncs)
3462 GenerateArg(Consumer, OPT_fno_builtin_, Func);
3464 if (Opts.LongDoubleSize == 128)
3465 GenerateArg(Consumer, OPT_mlong_double_128);
3466 else if (Opts.LongDoubleSize == 64)
3467 GenerateArg(Consumer, OPT_mlong_double_64);
3468 else if (Opts.LongDoubleSize == 80)
3469 GenerateArg(Consumer, OPT_mlong_double_80);
3471 // Not generating '-mrtd', it's just an alias for '-fdefault-calling-conv='.
3473 // OpenMP was requested via '-fopenmp', not implied by '-fopenmp-simd' or
3474 // '-fopenmp-targets='.
3475 if (Opts.OpenMP && !Opts.OpenMPSimd) {
3476 GenerateArg(Consumer, OPT_fopenmp);
3478 if (Opts.OpenMP != 51)
3479 GenerateArg(Consumer, OPT_fopenmp_version_EQ, Twine(Opts.OpenMP));
3481 if (!Opts.OpenMPUseTLS)
3482 GenerateArg(Consumer, OPT_fnoopenmp_use_tls);
3484 if (Opts.OpenMPIsTargetDevice)
3485 GenerateArg(Consumer, OPT_fopenmp_is_target_device);
3487 if (Opts.OpenMPIRBuilder)
3488 GenerateArg(Consumer, OPT_fopenmp_enable_irbuilder);
3491 if (Opts.OpenMPSimd) {
3492 GenerateArg(Consumer, OPT_fopenmp_simd);
3494 if (Opts.OpenMP != 51)
3495 GenerateArg(Consumer, OPT_fopenmp_version_EQ, Twine(Opts.OpenMP));
3498 if (Opts.OpenMPThreadSubscription)
3499 GenerateArg(Consumer, OPT_fopenmp_assume_threads_oversubscription);
3501 if (Opts.OpenMPTeamSubscription)
3502 GenerateArg(Consumer, OPT_fopenmp_assume_teams_oversubscription);
3504 if (Opts.OpenMPTargetDebug != 0)
3505 GenerateArg(Consumer, OPT_fopenmp_target_debug_EQ,
3506 Twine(Opts.OpenMPTargetDebug));
3508 if (Opts.OpenMPCUDANumSMs != 0)
3509 GenerateArg(Consumer, OPT_fopenmp_cuda_number_of_sm_EQ,
3510 Twine(Opts.OpenMPCUDANumSMs));
3512 if (Opts.OpenMPCUDABlocksPerSM != 0)
3513 GenerateArg(Consumer, OPT_fopenmp_cuda_blocks_per_sm_EQ,
3514 Twine(Opts.OpenMPCUDABlocksPerSM));
3516 if (Opts.OpenMPCUDAReductionBufNum != 1024)
3517 GenerateArg(Consumer, OPT_fopenmp_cuda_teams_reduction_recs_num_EQ,
3518 Twine(Opts.OpenMPCUDAReductionBufNum));
3520 if (!Opts.OMPTargetTriples.empty()) {
3521 std::string Targets;
3522 llvm::raw_string_ostream OS(Targets);
3523 llvm::interleave(
3524 Opts.OMPTargetTriples, OS,
3525 [&OS](const llvm::Triple &T) { OS << T.str(); }, ",");
3526 GenerateArg(Consumer, OPT_fopenmp_targets_EQ, OS.str());
3529 if (!Opts.OMPHostIRFile.empty())
3530 GenerateArg(Consumer, OPT_fopenmp_host_ir_file_path, Opts.OMPHostIRFile);
3532 if (Opts.OpenMPCUDAMode)
3533 GenerateArg(Consumer, OPT_fopenmp_cuda_mode);
3535 // The arguments used to set Optimize, OptimizeSize and NoInlineDefine are
3536 // generated from CodeGenOptions.
3538 if (Opts.DefaultFPContractMode == LangOptions::FPM_Fast)
3539 GenerateArg(Consumer, OPT_ffp_contract, "fast");
3540 else if (Opts.DefaultFPContractMode == LangOptions::FPM_On)
3541 GenerateArg(Consumer, OPT_ffp_contract, "on");
3542 else if (Opts.DefaultFPContractMode == LangOptions::FPM_Off)
3543 GenerateArg(Consumer, OPT_ffp_contract, "off");
3544 else if (Opts.DefaultFPContractMode == LangOptions::FPM_FastHonorPragmas)
3545 GenerateArg(Consumer, OPT_ffp_contract, "fast-honor-pragmas");
3547 for (StringRef Sanitizer : serializeSanitizerKinds(Opts.Sanitize))
3548 GenerateArg(Consumer, OPT_fsanitize_EQ, Sanitizer);
3550 // Conflating '-fsanitize-system-ignorelist' and '-fsanitize-ignorelist'.
3551 for (const std::string &F : Opts.NoSanitizeFiles)
3552 GenerateArg(Consumer, OPT_fsanitize_ignorelist_EQ, F);
3554 switch (Opts.getClangABICompat()) {
3555 case LangOptions::ClangABI::Ver3_8:
3556 GenerateArg(Consumer, OPT_fclang_abi_compat_EQ, "3.8");
3557 break;
3558 case LangOptions::ClangABI::Ver4:
3559 GenerateArg(Consumer, OPT_fclang_abi_compat_EQ, "4.0");
3560 break;
3561 case LangOptions::ClangABI::Ver6:
3562 GenerateArg(Consumer, OPT_fclang_abi_compat_EQ, "6.0");
3563 break;
3564 case LangOptions::ClangABI::Ver7:
3565 GenerateArg(Consumer, OPT_fclang_abi_compat_EQ, "7.0");
3566 break;
3567 case LangOptions::ClangABI::Ver9:
3568 GenerateArg(Consumer, OPT_fclang_abi_compat_EQ, "9.0");
3569 break;
3570 case LangOptions::ClangABI::Ver11:
3571 GenerateArg(Consumer, OPT_fclang_abi_compat_EQ, "11.0");
3572 break;
3573 case LangOptions::ClangABI::Ver12:
3574 GenerateArg(Consumer, OPT_fclang_abi_compat_EQ, "12.0");
3575 break;
3576 case LangOptions::ClangABI::Ver14:
3577 GenerateArg(Consumer, OPT_fclang_abi_compat_EQ, "14.0");
3578 break;
3579 case LangOptions::ClangABI::Ver15:
3580 GenerateArg(Consumer, OPT_fclang_abi_compat_EQ, "15.0");
3581 break;
3582 case LangOptions::ClangABI::Ver17:
3583 GenerateArg(Consumer, OPT_fclang_abi_compat_EQ, "17.0");
3584 break;
3585 case LangOptions::ClangABI::Latest:
3586 break;
3589 if (Opts.getSignReturnAddressScope() ==
3590 LangOptions::SignReturnAddressScopeKind::All)
3591 GenerateArg(Consumer, OPT_msign_return_address_EQ, "all");
3592 else if (Opts.getSignReturnAddressScope() ==
3593 LangOptions::SignReturnAddressScopeKind::NonLeaf)
3594 GenerateArg(Consumer, OPT_msign_return_address_EQ, "non-leaf");
3596 if (Opts.getSignReturnAddressKey() ==
3597 LangOptions::SignReturnAddressKeyKind::BKey)
3598 GenerateArg(Consumer, OPT_msign_return_address_key_EQ, "b_key");
3600 if (Opts.CXXABI)
3601 GenerateArg(Consumer, OPT_fcxx_abi_EQ,
3602 TargetCXXABI::getSpelling(*Opts.CXXABI));
3604 if (Opts.RelativeCXXABIVTables)
3605 GenerateArg(Consumer, OPT_fexperimental_relative_cxx_abi_vtables);
3606 else
3607 GenerateArg(Consumer, OPT_fno_experimental_relative_cxx_abi_vtables);
3609 if (Opts.UseTargetPathSeparator)
3610 GenerateArg(Consumer, OPT_ffile_reproducible);
3611 else
3612 GenerateArg(Consumer, OPT_fno_file_reproducible);
3614 for (const auto &MP : Opts.MacroPrefixMap)
3615 GenerateArg(Consumer, OPT_fmacro_prefix_map_EQ, MP.first + "=" + MP.second);
3617 if (!Opts.RandstructSeed.empty())
3618 GenerateArg(Consumer, OPT_frandomize_layout_seed_EQ, Opts.RandstructSeed);
3621 bool CompilerInvocation::ParseLangArgs(LangOptions &Opts, ArgList &Args,
3622 InputKind IK, const llvm::Triple &T,
3623 std::vector<std::string> &Includes,
3624 DiagnosticsEngine &Diags) {
3625 unsigned NumErrorsBefore = Diags.getNumErrors();
3627 if (IK.getFormat() == InputKind::Precompiled ||
3628 IK.getLanguage() == Language::LLVM_IR) {
3629 // ObjCAAutoRefCount and Sanitize LangOpts are used to setup the
3630 // PassManager in BackendUtil.cpp. They need to be initialized no matter
3631 // what the input type is.
3632 if (Args.hasArg(OPT_fobjc_arc))
3633 Opts.ObjCAutoRefCount = 1;
3634 // PICLevel and PIELevel are needed during code generation and this should
3635 // be set regardless of the input type.
3636 Opts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags);
3637 Opts.PIE = Args.hasArg(OPT_pic_is_pie);
3638 parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ),
3639 Diags, Opts.Sanitize);
3641 return Diags.getNumErrors() == NumErrorsBefore;
3644 // Other LangOpts are only initialized when the input is not AST or LLVM IR.
3645 // FIXME: Should we really be parsing this for an Language::Asm input?
3647 // FIXME: Cleanup per-file based stuff.
3648 LangStandard::Kind LangStd = LangStandard::lang_unspecified;
3649 if (const Arg *A = Args.getLastArg(OPT_std_EQ)) {
3650 LangStd = LangStandard::getLangKind(A->getValue());
3651 if (LangStd == LangStandard::lang_unspecified) {
3652 Diags.Report(diag::err_drv_invalid_value)
3653 << A->getAsString(Args) << A->getValue();
3654 // Report supported standards with short description.
3655 for (unsigned KindValue = 0;
3656 KindValue != LangStandard::lang_unspecified;
3657 ++KindValue) {
3658 const LangStandard &Std = LangStandard::getLangStandardForKind(
3659 static_cast<LangStandard::Kind>(KindValue));
3660 if (IsInputCompatibleWithStandard(IK, Std)) {
3661 auto Diag = Diags.Report(diag::note_drv_use_standard);
3662 Diag << Std.getName() << Std.getDescription();
3663 unsigned NumAliases = 0;
3664 #define LANGSTANDARD(id, name, lang, desc, features)
3665 #define LANGSTANDARD_ALIAS(id, alias) \
3666 if (KindValue == LangStandard::lang_##id) ++NumAliases;
3667 #define LANGSTANDARD_ALIAS_DEPR(id, alias)
3668 #include "clang/Basic/LangStandards.def"
3669 Diag << NumAliases;
3670 #define LANGSTANDARD(id, name, lang, desc, features)
3671 #define LANGSTANDARD_ALIAS(id, alias) \
3672 if (KindValue == LangStandard::lang_##id) Diag << alias;
3673 #define LANGSTANDARD_ALIAS_DEPR(id, alias)
3674 #include "clang/Basic/LangStandards.def"
3677 } else {
3678 // Valid standard, check to make sure language and standard are
3679 // compatible.
3680 const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
3681 if (!IsInputCompatibleWithStandard(IK, Std)) {
3682 Diags.Report(diag::err_drv_argument_not_allowed_with)
3683 << A->getAsString(Args) << GetInputKindName(IK);
3688 // -cl-std only applies for OpenCL language standards.
3689 // Override the -std option in this case.
3690 if (const Arg *A = Args.getLastArg(OPT_cl_std_EQ)) {
3691 LangStandard::Kind OpenCLLangStd
3692 = llvm::StringSwitch<LangStandard::Kind>(A->getValue())
3693 .Cases("cl", "CL", LangStandard::lang_opencl10)
3694 .Cases("cl1.0", "CL1.0", LangStandard::lang_opencl10)
3695 .Cases("cl1.1", "CL1.1", LangStandard::lang_opencl11)
3696 .Cases("cl1.2", "CL1.2", LangStandard::lang_opencl12)
3697 .Cases("cl2.0", "CL2.0", LangStandard::lang_opencl20)
3698 .Cases("cl3.0", "CL3.0", LangStandard::lang_opencl30)
3699 .Cases("clc++", "CLC++", LangStandard::lang_openclcpp10)
3700 .Cases("clc++1.0", "CLC++1.0", LangStandard::lang_openclcpp10)
3701 .Cases("clc++2021", "CLC++2021", LangStandard::lang_openclcpp2021)
3702 .Default(LangStandard::lang_unspecified);
3704 if (OpenCLLangStd == LangStandard::lang_unspecified) {
3705 Diags.Report(diag::err_drv_invalid_value)
3706 << A->getAsString(Args) << A->getValue();
3708 else
3709 LangStd = OpenCLLangStd;
3712 // These need to be parsed now. They are used to set OpenCL defaults.
3713 Opts.IncludeDefaultHeader = Args.hasArg(OPT_finclude_default_header);
3714 Opts.DeclareOpenCLBuiltins = Args.hasArg(OPT_fdeclare_opencl_builtins);
3716 LangOptions::setLangDefaults(Opts, IK.getLanguage(), T, Includes, LangStd);
3718 // The key paths of codegen options defined in Options.td start with
3719 // "LangOpts->". Let's provide the expected variable name and type.
3720 LangOptions *LangOpts = &Opts;
3722 #define LANG_OPTION_WITH_MARSHALLING(...) \
3723 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
3724 #include "clang/Driver/Options.inc"
3725 #undef LANG_OPTION_WITH_MARSHALLING
3727 if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
3728 StringRef Name = A->getValue();
3729 if (Name == "full" || Name == "branch") {
3730 Opts.CFProtectionBranch = 1;
3734 if ((Args.hasArg(OPT_fsycl_is_device) || Args.hasArg(OPT_fsycl_is_host)) &&
3735 !Args.hasArg(OPT_sycl_std_EQ)) {
3736 // If the user supplied -fsycl-is-device or -fsycl-is-host, but failed to
3737 // provide -sycl-std=, we want to default it to whatever the default SYCL
3738 // version is. I could not find a way to express this with the options
3739 // tablegen because we still want this value to be SYCL_None when the user
3740 // is not in device or host mode.
3741 Opts.setSYCLVersion(LangOptions::SYCL_Default);
3744 if (Opts.ObjC) {
3745 if (Arg *arg = Args.getLastArg(OPT_fobjc_runtime_EQ)) {
3746 StringRef value = arg->getValue();
3747 if (Opts.ObjCRuntime.tryParse(value))
3748 Diags.Report(diag::err_drv_unknown_objc_runtime) << value;
3751 if (Args.hasArg(OPT_fobjc_gc_only))
3752 Opts.setGC(LangOptions::GCOnly);
3753 else if (Args.hasArg(OPT_fobjc_gc))
3754 Opts.setGC(LangOptions::HybridGC);
3755 else if (Args.hasArg(OPT_fobjc_arc)) {
3756 Opts.ObjCAutoRefCount = 1;
3757 if (!Opts.ObjCRuntime.allowsARC())
3758 Diags.Report(diag::err_arc_unsupported_on_runtime);
3761 // ObjCWeakRuntime tracks whether the runtime supports __weak, not
3762 // whether the feature is actually enabled. This is predominantly
3763 // determined by -fobjc-runtime, but we allow it to be overridden
3764 // from the command line for testing purposes.
3765 if (Args.hasArg(OPT_fobjc_runtime_has_weak))
3766 Opts.ObjCWeakRuntime = 1;
3767 else
3768 Opts.ObjCWeakRuntime = Opts.ObjCRuntime.allowsWeak();
3770 // ObjCWeak determines whether __weak is actually enabled.
3771 // Note that we allow -fno-objc-weak to disable this even in ARC mode.
3772 if (auto weakArg = Args.getLastArg(OPT_fobjc_weak, OPT_fno_objc_weak)) {
3773 if (!weakArg->getOption().matches(OPT_fobjc_weak)) {
3774 assert(!Opts.ObjCWeak);
3775 } else if (Opts.getGC() != LangOptions::NonGC) {
3776 Diags.Report(diag::err_objc_weak_with_gc);
3777 } else if (!Opts.ObjCWeakRuntime) {
3778 Diags.Report(diag::err_objc_weak_unsupported);
3779 } else {
3780 Opts.ObjCWeak = 1;
3782 } else if (Opts.ObjCAutoRefCount) {
3783 Opts.ObjCWeak = Opts.ObjCWeakRuntime;
3786 if (Args.hasArg(OPT_fobjc_subscripting_legacy_runtime))
3787 Opts.ObjCSubscriptingLegacyRuntime =
3788 (Opts.ObjCRuntime.getKind() == ObjCRuntime::FragileMacOSX);
3791 if (Arg *A = Args.getLastArg(options::OPT_fgnuc_version_EQ)) {
3792 // Check that the version has 1 to 3 components and the minor and patch
3793 // versions fit in two decimal digits.
3794 VersionTuple GNUCVer;
3795 bool Invalid = GNUCVer.tryParse(A->getValue());
3796 unsigned Major = GNUCVer.getMajor();
3797 unsigned Minor = GNUCVer.getMinor().value_or(0);
3798 unsigned Patch = GNUCVer.getSubminor().value_or(0);
3799 if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) {
3800 Diags.Report(diag::err_drv_invalid_value)
3801 << A->getAsString(Args) << A->getValue();
3803 Opts.GNUCVersion = Major * 100 * 100 + Minor * 100 + Patch;
3806 if (T.isOSAIX() && (Args.hasArg(OPT_mignore_xcoff_visibility)))
3807 Opts.IgnoreXCOFFVisibility = 1;
3809 if (Args.hasArg(OPT_ftrapv)) {
3810 Opts.setSignedOverflowBehavior(LangOptions::SOB_Trapping);
3811 // Set the handler, if one is specified.
3812 Opts.OverflowHandler =
3813 std::string(Args.getLastArgValue(OPT_ftrapv_handler));
3815 else if (Args.hasArg(OPT_fwrapv))
3816 Opts.setSignedOverflowBehavior(LangOptions::SOB_Defined);
3818 Opts.MSCompatibilityVersion = 0;
3819 if (const Arg *A = Args.getLastArg(OPT_fms_compatibility_version)) {
3820 VersionTuple VT;
3821 if (VT.tryParse(A->getValue()))
3822 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
3823 << A->getValue();
3824 Opts.MSCompatibilityVersion = VT.getMajor() * 10000000 +
3825 VT.getMinor().value_or(0) * 100000 +
3826 VT.getSubminor().value_or(0);
3829 // Mimicking gcc's behavior, trigraphs are only enabled if -trigraphs
3830 // is specified, or -std is set to a conforming mode.
3831 // Trigraphs are disabled by default in c++1z onwards.
3832 // For z/OS, trigraphs are enabled by default (without regard to the above).
3833 Opts.Trigraphs =
3834 (!Opts.GNUMode && !Opts.MSVCCompat && !Opts.CPlusPlus17) || T.isOSzOS();
3835 Opts.Trigraphs =
3836 Args.hasFlag(OPT_ftrigraphs, OPT_fno_trigraphs, Opts.Trigraphs);
3838 Opts.Blocks = Args.hasArg(OPT_fblocks) || (Opts.OpenCL
3839 && Opts.OpenCLVersion == 200);
3841 Opts.ConvergentFunctions = Args.hasArg(OPT_fconvergent_functions) ||
3842 Opts.OpenCL || (Opts.CUDA && Opts.CUDAIsDevice) ||
3843 Opts.SYCLIsDevice;
3845 Opts.NoBuiltin = Args.hasArg(OPT_fno_builtin) || Opts.Freestanding;
3846 if (!Opts.NoBuiltin)
3847 getAllNoBuiltinFuncValues(Args, Opts.NoBuiltinFuncs);
3848 if (Arg *A = Args.getLastArg(options::OPT_LongDouble_Group)) {
3849 if (A->getOption().matches(options::OPT_mlong_double_64))
3850 Opts.LongDoubleSize = 64;
3851 else if (A->getOption().matches(options::OPT_mlong_double_80))
3852 Opts.LongDoubleSize = 80;
3853 else if (A->getOption().matches(options::OPT_mlong_double_128))
3854 Opts.LongDoubleSize = 128;
3855 else
3856 Opts.LongDoubleSize = 0;
3858 if (Opts.FastRelaxedMath || Opts.CLUnsafeMath)
3859 Opts.setDefaultFPContractMode(LangOptions::FPM_Fast);
3861 llvm::sort(Opts.ModuleFeatures);
3863 // -mrtd option
3864 if (Arg *A = Args.getLastArg(OPT_mrtd)) {
3865 if (Opts.getDefaultCallingConv() != LangOptions::DCC_None)
3866 Diags.Report(diag::err_drv_argument_not_allowed_with)
3867 << A->getSpelling() << "-fdefault-calling-conv";
3868 else {
3869 switch (T.getArch()) {
3870 case llvm::Triple::x86:
3871 Opts.setDefaultCallingConv(LangOptions::DCC_StdCall);
3872 break;
3873 case llvm::Triple::m68k:
3874 Opts.setDefaultCallingConv(LangOptions::DCC_RtdCall);
3875 break;
3876 default:
3877 Diags.Report(diag::err_drv_argument_not_allowed_with)
3878 << A->getSpelling() << T.getTriple();
3883 // Check if -fopenmp is specified and set default version to 5.0.
3884 Opts.OpenMP = Args.hasArg(OPT_fopenmp) ? 51 : 0;
3885 // Check if -fopenmp-simd is specified.
3886 bool IsSimdSpecified =
3887 Args.hasFlag(options::OPT_fopenmp_simd, options::OPT_fno_openmp_simd,
3888 /*Default=*/false);
3889 Opts.OpenMPSimd = !Opts.OpenMP && IsSimdSpecified;
3890 Opts.OpenMPUseTLS =
3891 Opts.OpenMP && !Args.hasArg(options::OPT_fnoopenmp_use_tls);
3892 Opts.OpenMPIsTargetDevice =
3893 Opts.OpenMP && Args.hasArg(options::OPT_fopenmp_is_target_device);
3894 Opts.OpenMPIRBuilder =
3895 Opts.OpenMP && Args.hasArg(options::OPT_fopenmp_enable_irbuilder);
3896 bool IsTargetSpecified =
3897 Opts.OpenMPIsTargetDevice || Args.hasArg(options::OPT_fopenmp_targets_EQ);
3899 Opts.ConvergentFunctions =
3900 Opts.ConvergentFunctions || Opts.OpenMPIsTargetDevice;
3902 if (Opts.OpenMP || Opts.OpenMPSimd) {
3903 if (int Version = getLastArgIntValue(
3904 Args, OPT_fopenmp_version_EQ,
3905 (IsSimdSpecified || IsTargetSpecified) ? 51 : Opts.OpenMP, Diags))
3906 Opts.OpenMP = Version;
3907 // Provide diagnostic when a given target is not expected to be an OpenMP
3908 // device or host.
3909 if (!Opts.OpenMPIsTargetDevice) {
3910 switch (T.getArch()) {
3911 default:
3912 break;
3913 // Add unsupported host targets here:
3914 case llvm::Triple::nvptx:
3915 case llvm::Triple::nvptx64:
3916 Diags.Report(diag::err_drv_omp_host_target_not_supported) << T.str();
3917 break;
3922 // Set the flag to prevent the implementation from emitting device exception
3923 // handling code for those requiring so.
3924 if ((Opts.OpenMPIsTargetDevice && (T.isNVPTX() || T.isAMDGCN())) ||
3925 Opts.OpenCLCPlusPlus) {
3927 Opts.Exceptions = 0;
3928 Opts.CXXExceptions = 0;
3930 if (Opts.OpenMPIsTargetDevice && T.isNVPTX()) {
3931 Opts.OpenMPCUDANumSMs =
3932 getLastArgIntValue(Args, options::OPT_fopenmp_cuda_number_of_sm_EQ,
3933 Opts.OpenMPCUDANumSMs, Diags);
3934 Opts.OpenMPCUDABlocksPerSM =
3935 getLastArgIntValue(Args, options::OPT_fopenmp_cuda_blocks_per_sm_EQ,
3936 Opts.OpenMPCUDABlocksPerSM, Diags);
3937 Opts.OpenMPCUDAReductionBufNum = getLastArgIntValue(
3938 Args, options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ,
3939 Opts.OpenMPCUDAReductionBufNum, Diags);
3942 // Set the value of the debugging flag used in the new offloading device RTL.
3943 // Set either by a specific value or to a default if not specified.
3944 if (Opts.OpenMPIsTargetDevice && (Args.hasArg(OPT_fopenmp_target_debug) ||
3945 Args.hasArg(OPT_fopenmp_target_debug_EQ))) {
3946 Opts.OpenMPTargetDebug = getLastArgIntValue(
3947 Args, OPT_fopenmp_target_debug_EQ, Opts.OpenMPTargetDebug, Diags);
3948 if (!Opts.OpenMPTargetDebug && Args.hasArg(OPT_fopenmp_target_debug))
3949 Opts.OpenMPTargetDebug = 1;
3952 if (Opts.OpenMPIsTargetDevice) {
3953 if (Args.hasArg(OPT_fopenmp_assume_teams_oversubscription))
3954 Opts.OpenMPTeamSubscription = true;
3955 if (Args.hasArg(OPT_fopenmp_assume_threads_oversubscription))
3956 Opts.OpenMPThreadSubscription = true;
3959 // Get the OpenMP target triples if any.
3960 if (Arg *A = Args.getLastArg(options::OPT_fopenmp_targets_EQ)) {
3961 enum ArchPtrSize { Arch16Bit, Arch32Bit, Arch64Bit };
3962 auto getArchPtrSize = [](const llvm::Triple &T) {
3963 if (T.isArch16Bit())
3964 return Arch16Bit;
3965 if (T.isArch32Bit())
3966 return Arch32Bit;
3967 assert(T.isArch64Bit() && "Expected 64-bit architecture");
3968 return Arch64Bit;
3971 for (unsigned i = 0; i < A->getNumValues(); ++i) {
3972 llvm::Triple TT(A->getValue(i));
3974 if (TT.getArch() == llvm::Triple::UnknownArch ||
3975 !(TT.getArch() == llvm::Triple::aarch64 || TT.isPPC() ||
3976 TT.getArch() == llvm::Triple::nvptx ||
3977 TT.getArch() == llvm::Triple::nvptx64 ||
3978 TT.getArch() == llvm::Triple::amdgcn ||
3979 TT.getArch() == llvm::Triple::x86 ||
3980 TT.getArch() == llvm::Triple::x86_64))
3981 Diags.Report(diag::err_drv_invalid_omp_target) << A->getValue(i);
3982 else if (getArchPtrSize(T) != getArchPtrSize(TT))
3983 Diags.Report(diag::err_drv_incompatible_omp_arch)
3984 << A->getValue(i) << T.str();
3985 else
3986 Opts.OMPTargetTriples.push_back(TT);
3990 // Get OpenMP host file path if any and report if a non existent file is
3991 // found
3992 if (Arg *A = Args.getLastArg(options::OPT_fopenmp_host_ir_file_path)) {
3993 Opts.OMPHostIRFile = A->getValue();
3994 if (!llvm::sys::fs::exists(Opts.OMPHostIRFile))
3995 Diags.Report(diag::err_drv_omp_host_ir_file_not_found)
3996 << Opts.OMPHostIRFile;
3999 // Set CUDA mode for OpenMP target NVPTX/AMDGCN if specified in options
4000 Opts.OpenMPCUDAMode = Opts.OpenMPIsTargetDevice &&
4001 (T.isNVPTX() || T.isAMDGCN()) &&
4002 Args.hasArg(options::OPT_fopenmp_cuda_mode);
4004 // FIXME: Eliminate this dependency.
4005 unsigned Opt = getOptimizationLevel(Args, IK, Diags),
4006 OptSize = getOptimizationLevelSize(Args);
4007 Opts.Optimize = Opt != 0;
4008 Opts.OptimizeSize = OptSize != 0;
4010 // This is the __NO_INLINE__ define, which just depends on things like the
4011 // optimization level and -fno-inline, not actually whether the backend has
4012 // inlining enabled.
4013 Opts.NoInlineDefine = !Opts.Optimize;
4014 if (Arg *InlineArg = Args.getLastArg(
4015 options::OPT_finline_functions, options::OPT_finline_hint_functions,
4016 options::OPT_fno_inline_functions, options::OPT_fno_inline))
4017 if (InlineArg->getOption().matches(options::OPT_fno_inline))
4018 Opts.NoInlineDefine = true;
4020 if (Arg *A = Args.getLastArg(OPT_ffp_contract)) {
4021 StringRef Val = A->getValue();
4022 if (Val == "fast")
4023 Opts.setDefaultFPContractMode(LangOptions::FPM_Fast);
4024 else if (Val == "on")
4025 Opts.setDefaultFPContractMode(LangOptions::FPM_On);
4026 else if (Val == "off")
4027 Opts.setDefaultFPContractMode(LangOptions::FPM_Off);
4028 else if (Val == "fast-honor-pragmas")
4029 Opts.setDefaultFPContractMode(LangOptions::FPM_FastHonorPragmas);
4030 else
4031 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
4034 // Parse -fsanitize= arguments.
4035 parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ),
4036 Diags, Opts.Sanitize);
4037 Opts.NoSanitizeFiles = Args.getAllArgValues(OPT_fsanitize_ignorelist_EQ);
4038 std::vector<std::string> systemIgnorelists =
4039 Args.getAllArgValues(OPT_fsanitize_system_ignorelist_EQ);
4040 Opts.NoSanitizeFiles.insert(Opts.NoSanitizeFiles.end(),
4041 systemIgnorelists.begin(),
4042 systemIgnorelists.end());
4044 if (Arg *A = Args.getLastArg(OPT_fclang_abi_compat_EQ)) {
4045 Opts.setClangABICompat(LangOptions::ClangABI::Latest);
4047 StringRef Ver = A->getValue();
4048 std::pair<StringRef, StringRef> VerParts = Ver.split('.');
4049 unsigned Major, Minor = 0;
4051 // Check the version number is valid: either 3.x (0 <= x <= 9) or
4052 // y or y.0 (4 <= y <= current version).
4053 if (!VerParts.first.startswith("0") &&
4054 !VerParts.first.getAsInteger(10, Major) &&
4055 3 <= Major && Major <= CLANG_VERSION_MAJOR &&
4056 (Major == 3 ? VerParts.second.size() == 1 &&
4057 !VerParts.second.getAsInteger(10, Minor)
4058 : VerParts.first.size() == Ver.size() ||
4059 VerParts.second == "0")) {
4060 // Got a valid version number.
4061 if (Major == 3 && Minor <= 8)
4062 Opts.setClangABICompat(LangOptions::ClangABI::Ver3_8);
4063 else if (Major <= 4)
4064 Opts.setClangABICompat(LangOptions::ClangABI::Ver4);
4065 else if (Major <= 6)
4066 Opts.setClangABICompat(LangOptions::ClangABI::Ver6);
4067 else if (Major <= 7)
4068 Opts.setClangABICompat(LangOptions::ClangABI::Ver7);
4069 else if (Major <= 9)
4070 Opts.setClangABICompat(LangOptions::ClangABI::Ver9);
4071 else if (Major <= 11)
4072 Opts.setClangABICompat(LangOptions::ClangABI::Ver11);
4073 else if (Major <= 12)
4074 Opts.setClangABICompat(LangOptions::ClangABI::Ver12);
4075 else if (Major <= 14)
4076 Opts.setClangABICompat(LangOptions::ClangABI::Ver14);
4077 else if (Major <= 15)
4078 Opts.setClangABICompat(LangOptions::ClangABI::Ver15);
4079 else if (Major <= 17)
4080 Opts.setClangABICompat(LangOptions::ClangABI::Ver17);
4081 } else if (Ver != "latest") {
4082 Diags.Report(diag::err_drv_invalid_value)
4083 << A->getAsString(Args) << A->getValue();
4087 if (Arg *A = Args.getLastArg(OPT_msign_return_address_EQ)) {
4088 StringRef SignScope = A->getValue();
4090 if (SignScope.equals_insensitive("none"))
4091 Opts.setSignReturnAddressScope(
4092 LangOptions::SignReturnAddressScopeKind::None);
4093 else if (SignScope.equals_insensitive("all"))
4094 Opts.setSignReturnAddressScope(
4095 LangOptions::SignReturnAddressScopeKind::All);
4096 else if (SignScope.equals_insensitive("non-leaf"))
4097 Opts.setSignReturnAddressScope(
4098 LangOptions::SignReturnAddressScopeKind::NonLeaf);
4099 else
4100 Diags.Report(diag::err_drv_invalid_value)
4101 << A->getAsString(Args) << SignScope;
4103 if (Arg *A = Args.getLastArg(OPT_msign_return_address_key_EQ)) {
4104 StringRef SignKey = A->getValue();
4105 if (!SignScope.empty() && !SignKey.empty()) {
4106 if (SignKey.equals_insensitive("a_key"))
4107 Opts.setSignReturnAddressKey(
4108 LangOptions::SignReturnAddressKeyKind::AKey);
4109 else if (SignKey.equals_insensitive("b_key"))
4110 Opts.setSignReturnAddressKey(
4111 LangOptions::SignReturnAddressKeyKind::BKey);
4112 else
4113 Diags.Report(diag::err_drv_invalid_value)
4114 << A->getAsString(Args) << SignKey;
4119 // The value can be empty, which indicates the system default should be used.
4120 StringRef CXXABI = Args.getLastArgValue(OPT_fcxx_abi_EQ);
4121 if (!CXXABI.empty()) {
4122 if (!TargetCXXABI::isABI(CXXABI)) {
4123 Diags.Report(diag::err_invalid_cxx_abi) << CXXABI;
4124 } else {
4125 auto Kind = TargetCXXABI::getKind(CXXABI);
4126 if (!TargetCXXABI::isSupportedCXXABI(T, Kind))
4127 Diags.Report(diag::err_unsupported_cxx_abi) << CXXABI << T.str();
4128 else
4129 Opts.CXXABI = Kind;
4133 Opts.RelativeCXXABIVTables =
4134 Args.hasFlag(options::OPT_fexperimental_relative_cxx_abi_vtables,
4135 options::OPT_fno_experimental_relative_cxx_abi_vtables,
4136 TargetCXXABI::usesRelativeVTables(T));
4138 // RTTI is on by default.
4139 bool HasRTTI = Args.hasFlag(options::OPT_frtti, options::OPT_fno_rtti, true);
4140 Opts.OmitVTableRTTI =
4141 Args.hasFlag(options::OPT_fexperimental_omit_vtable_rtti,
4142 options::OPT_fno_experimental_omit_vtable_rtti, false);
4143 if (Opts.OmitVTableRTTI && HasRTTI)
4144 Diags.Report(diag::err_drv_using_omit_rtti_component_without_no_rtti);
4146 for (const auto &A : Args.getAllArgValues(OPT_fmacro_prefix_map_EQ)) {
4147 auto Split = StringRef(A).split('=');
4148 Opts.MacroPrefixMap.insert(
4149 {std::string(Split.first), std::string(Split.second)});
4152 Opts.UseTargetPathSeparator =
4153 !Args.getLastArg(OPT_fno_file_reproducible) &&
4154 (Args.getLastArg(OPT_ffile_compilation_dir_EQ) ||
4155 Args.getLastArg(OPT_fmacro_prefix_map_EQ) ||
4156 Args.getLastArg(OPT_ffile_reproducible));
4158 // Error if -mvscale-min is unbounded.
4159 if (Arg *A = Args.getLastArg(options::OPT_mvscale_min_EQ)) {
4160 unsigned VScaleMin;
4161 if (StringRef(A->getValue()).getAsInteger(10, VScaleMin) || VScaleMin == 0)
4162 Diags.Report(diag::err_cc1_unbounded_vscale_min);
4165 if (const Arg *A = Args.getLastArg(OPT_frandomize_layout_seed_file_EQ)) {
4166 std::ifstream SeedFile(A->getValue(0));
4168 if (!SeedFile.is_open())
4169 Diags.Report(diag::err_drv_cannot_open_randomize_layout_seed_file)
4170 << A->getValue(0);
4172 std::getline(SeedFile, Opts.RandstructSeed);
4175 if (const Arg *A = Args.getLastArg(OPT_frandomize_layout_seed_EQ))
4176 Opts.RandstructSeed = A->getValue(0);
4178 // Validate options for HLSL
4179 if (Opts.HLSL) {
4180 // TODO: Revisit restricting SPIR-V to logical once we've figured out how to
4181 // handle PhysicalStorageBuffer64 memory model
4182 if (T.isDXIL() || T.isSPIRVLogical()) {
4183 enum { ShaderModel, ShaderStage };
4184 if (T.getOSName().empty()) {
4185 Diags.Report(diag::err_drv_hlsl_bad_shader_required_in_target)
4186 << ShaderModel << T.str();
4187 } else if (!T.isShaderModelOS() || T.getOSVersion() == VersionTuple(0)) {
4188 Diags.Report(diag::err_drv_hlsl_bad_shader_unsupported)
4189 << ShaderModel << T.getOSName() << T.str();
4190 } else if (T.getEnvironmentName().empty()) {
4191 Diags.Report(diag::err_drv_hlsl_bad_shader_required_in_target)
4192 << ShaderStage << T.str();
4193 } else if (!T.isShaderStageEnvironment()) {
4194 Diags.Report(diag::err_drv_hlsl_bad_shader_unsupported)
4195 << ShaderStage << T.getEnvironmentName() << T.str();
4197 } else
4198 Diags.Report(diag::err_drv_hlsl_unsupported_target) << T.str();
4201 return Diags.getNumErrors() == NumErrorsBefore;
4204 static bool isStrictlyPreprocessorAction(frontend::ActionKind Action) {
4205 switch (Action) {
4206 case frontend::ASTDeclList:
4207 case frontend::ASTDump:
4208 case frontend::ASTPrint:
4209 case frontend::ASTView:
4210 case frontend::EmitAssembly:
4211 case frontend::EmitBC:
4212 case frontend::EmitHTML:
4213 case frontend::EmitLLVM:
4214 case frontend::EmitLLVMOnly:
4215 case frontend::EmitCodeGenOnly:
4216 case frontend::EmitObj:
4217 case frontend::ExtractAPI:
4218 case frontend::FixIt:
4219 case frontend::GenerateModule:
4220 case frontend::GenerateModuleInterface:
4221 case frontend::GenerateHeaderUnit:
4222 case frontend::GeneratePCH:
4223 case frontend::GenerateInterfaceStubs:
4224 case frontend::ParseSyntaxOnly:
4225 case frontend::ModuleFileInfo:
4226 case frontend::VerifyPCH:
4227 case frontend::PluginAction:
4228 case frontend::RewriteObjC:
4229 case frontend::RewriteTest:
4230 case frontend::RunAnalysis:
4231 case frontend::TemplightDump:
4232 case frontend::MigrateSource:
4233 return false;
4235 case frontend::DumpCompilerOptions:
4236 case frontend::DumpRawTokens:
4237 case frontend::DumpTokens:
4238 case frontend::InitOnly:
4239 case frontend::PrintPreamble:
4240 case frontend::PrintPreprocessedInput:
4241 case frontend::RewriteMacros:
4242 case frontend::RunPreprocessorOnly:
4243 case frontend::PrintDependencyDirectivesSourceMinimizerOutput:
4244 return true;
4246 llvm_unreachable("invalid frontend action");
4249 static void GeneratePreprocessorArgs(const PreprocessorOptions &Opts,
4250 ArgumentConsumer Consumer,
4251 const LangOptions &LangOpts,
4252 const FrontendOptions &FrontendOpts,
4253 const CodeGenOptions &CodeGenOpts) {
4254 const PreprocessorOptions *PreprocessorOpts = &Opts;
4256 #define PREPROCESSOR_OPTION_WITH_MARSHALLING(...) \
4257 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
4258 #include "clang/Driver/Options.inc"
4259 #undef PREPROCESSOR_OPTION_WITH_MARSHALLING
4261 if (Opts.PCHWithHdrStop && !Opts.PCHWithHdrStopCreate)
4262 GenerateArg(Consumer, OPT_pch_through_hdrstop_use);
4264 for (const auto &D : Opts.DeserializedPCHDeclsToErrorOn)
4265 GenerateArg(Consumer, OPT_error_on_deserialized_pch_decl, D);
4267 if (Opts.PrecompiledPreambleBytes != std::make_pair(0u, false))
4268 GenerateArg(Consumer, OPT_preamble_bytes_EQ,
4269 Twine(Opts.PrecompiledPreambleBytes.first) + "," +
4270 (Opts.PrecompiledPreambleBytes.second ? "1" : "0"));
4272 for (const auto &M : Opts.Macros) {
4273 // Don't generate __CET__ macro definitions. They are implied by the
4274 // -fcf-protection option that is generated elsewhere.
4275 if (M.first == "__CET__=1" && !M.second &&
4276 !CodeGenOpts.CFProtectionReturn && CodeGenOpts.CFProtectionBranch)
4277 continue;
4278 if (M.first == "__CET__=2" && !M.second && CodeGenOpts.CFProtectionReturn &&
4279 !CodeGenOpts.CFProtectionBranch)
4280 continue;
4281 if (M.first == "__CET__=3" && !M.second && CodeGenOpts.CFProtectionReturn &&
4282 CodeGenOpts.CFProtectionBranch)
4283 continue;
4285 GenerateArg(Consumer, M.second ? OPT_U : OPT_D, M.first);
4288 for (const auto &I : Opts.Includes) {
4289 // Don't generate OpenCL includes. They are implied by other flags that are
4290 // generated elsewhere.
4291 if (LangOpts.OpenCL && LangOpts.IncludeDefaultHeader &&
4292 ((LangOpts.DeclareOpenCLBuiltins && I == "opencl-c-base.h") ||
4293 I == "opencl-c.h"))
4294 continue;
4295 // Don't generate HLSL includes. They are implied by other flags that are
4296 // generated elsewhere.
4297 if (LangOpts.HLSL && I == "hlsl.h")
4298 continue;
4300 GenerateArg(Consumer, OPT_include, I);
4303 for (const auto &CI : Opts.ChainedIncludes)
4304 GenerateArg(Consumer, OPT_chain_include, CI);
4306 for (const auto &RF : Opts.RemappedFiles)
4307 GenerateArg(Consumer, OPT_remap_file, RF.first + ";" + RF.second);
4309 if (Opts.SourceDateEpoch)
4310 GenerateArg(Consumer, OPT_source_date_epoch, Twine(*Opts.SourceDateEpoch));
4312 // Don't handle LexEditorPlaceholders. It is implied by the action that is
4313 // generated elsewhere.
4316 static bool ParsePreprocessorArgs(PreprocessorOptions &Opts, ArgList &Args,
4317 DiagnosticsEngine &Diags,
4318 frontend::ActionKind Action,
4319 const FrontendOptions &FrontendOpts) {
4320 unsigned NumErrorsBefore = Diags.getNumErrors();
4322 PreprocessorOptions *PreprocessorOpts = &Opts;
4324 #define PREPROCESSOR_OPTION_WITH_MARSHALLING(...) \
4325 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
4326 #include "clang/Driver/Options.inc"
4327 #undef PREPROCESSOR_OPTION_WITH_MARSHALLING
4329 Opts.PCHWithHdrStop = Args.hasArg(OPT_pch_through_hdrstop_create) ||
4330 Args.hasArg(OPT_pch_through_hdrstop_use);
4332 for (const auto *A : Args.filtered(OPT_error_on_deserialized_pch_decl))
4333 Opts.DeserializedPCHDeclsToErrorOn.insert(A->getValue());
4335 if (const Arg *A = Args.getLastArg(OPT_preamble_bytes_EQ)) {
4336 StringRef Value(A->getValue());
4337 size_t Comma = Value.find(',');
4338 unsigned Bytes = 0;
4339 unsigned EndOfLine = 0;
4341 if (Comma == StringRef::npos ||
4342 Value.substr(0, Comma).getAsInteger(10, Bytes) ||
4343 Value.substr(Comma + 1).getAsInteger(10, EndOfLine))
4344 Diags.Report(diag::err_drv_preamble_format);
4345 else {
4346 Opts.PrecompiledPreambleBytes.first = Bytes;
4347 Opts.PrecompiledPreambleBytes.second = (EndOfLine != 0);
4351 // Add the __CET__ macro if a CFProtection option is set.
4352 if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
4353 StringRef Name = A->getValue();
4354 if (Name == "branch")
4355 Opts.addMacroDef("__CET__=1");
4356 else if (Name == "return")
4357 Opts.addMacroDef("__CET__=2");
4358 else if (Name == "full")
4359 Opts.addMacroDef("__CET__=3");
4362 // Add macros from the command line.
4363 for (const auto *A : Args.filtered(OPT_D, OPT_U)) {
4364 if (A->getOption().matches(OPT_D))
4365 Opts.addMacroDef(A->getValue());
4366 else
4367 Opts.addMacroUndef(A->getValue());
4370 // Add the ordered list of -includes.
4371 for (const auto *A : Args.filtered(OPT_include))
4372 Opts.Includes.emplace_back(A->getValue());
4374 for (const auto *A : Args.filtered(OPT_chain_include))
4375 Opts.ChainedIncludes.emplace_back(A->getValue());
4377 for (const auto *A : Args.filtered(OPT_remap_file)) {
4378 std::pair<StringRef, StringRef> Split = StringRef(A->getValue()).split(';');
4380 if (Split.second.empty()) {
4381 Diags.Report(diag::err_drv_invalid_remap_file) << A->getAsString(Args);
4382 continue;
4385 Opts.addRemappedFile(Split.first, Split.second);
4388 if (const Arg *A = Args.getLastArg(OPT_source_date_epoch)) {
4389 StringRef Epoch = A->getValue();
4390 // SOURCE_DATE_EPOCH, if specified, must be a non-negative decimal integer.
4391 // On time64 systems, pick 253402300799 (the UNIX timestamp of
4392 // 9999-12-31T23:59:59Z) as the upper bound.
4393 const uint64_t MaxTimestamp =
4394 std::min<uint64_t>(std::numeric_limits<time_t>::max(), 253402300799);
4395 uint64_t V;
4396 if (Epoch.getAsInteger(10, V) || V > MaxTimestamp) {
4397 Diags.Report(diag::err_fe_invalid_source_date_epoch)
4398 << Epoch << MaxTimestamp;
4399 } else {
4400 Opts.SourceDateEpoch = V;
4404 // Always avoid lexing editor placeholders when we're just running the
4405 // preprocessor as we never want to emit the
4406 // "editor placeholder in source file" error in PP only mode.
4407 if (isStrictlyPreprocessorAction(Action))
4408 Opts.LexEditorPlaceholders = false;
4410 return Diags.getNumErrors() == NumErrorsBefore;
4413 static void
4414 GeneratePreprocessorOutputArgs(const PreprocessorOutputOptions &Opts,
4415 ArgumentConsumer Consumer,
4416 frontend::ActionKind Action) {
4417 const PreprocessorOutputOptions &PreprocessorOutputOpts = Opts;
4419 #define PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING(...) \
4420 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
4421 #include "clang/Driver/Options.inc"
4422 #undef PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING
4424 bool Generate_dM = isStrictlyPreprocessorAction(Action) && !Opts.ShowCPP;
4425 if (Generate_dM)
4426 GenerateArg(Consumer, OPT_dM);
4427 if (!Generate_dM && Opts.ShowMacros)
4428 GenerateArg(Consumer, OPT_dD);
4429 if (Opts.DirectivesOnly)
4430 GenerateArg(Consumer, OPT_fdirectives_only);
4433 static bool ParsePreprocessorOutputArgs(PreprocessorOutputOptions &Opts,
4434 ArgList &Args, DiagnosticsEngine &Diags,
4435 frontend::ActionKind Action) {
4436 unsigned NumErrorsBefore = Diags.getNumErrors();
4438 PreprocessorOutputOptions &PreprocessorOutputOpts = Opts;
4440 #define PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING(...) \
4441 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
4442 #include "clang/Driver/Options.inc"
4443 #undef PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING
4445 Opts.ShowCPP = isStrictlyPreprocessorAction(Action) && !Args.hasArg(OPT_dM);
4446 Opts.ShowMacros = Args.hasArg(OPT_dM) || Args.hasArg(OPT_dD);
4447 Opts.DirectivesOnly = Args.hasArg(OPT_fdirectives_only);
4449 return Diags.getNumErrors() == NumErrorsBefore;
4452 static void GenerateTargetArgs(const TargetOptions &Opts,
4453 ArgumentConsumer Consumer) {
4454 const TargetOptions *TargetOpts = &Opts;
4455 #define TARGET_OPTION_WITH_MARSHALLING(...) \
4456 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
4457 #include "clang/Driver/Options.inc"
4458 #undef TARGET_OPTION_WITH_MARSHALLING
4460 if (!Opts.SDKVersion.empty())
4461 GenerateArg(Consumer, OPT_target_sdk_version_EQ,
4462 Opts.SDKVersion.getAsString());
4463 if (!Opts.DarwinTargetVariantSDKVersion.empty())
4464 GenerateArg(Consumer, OPT_darwin_target_variant_sdk_version_EQ,
4465 Opts.DarwinTargetVariantSDKVersion.getAsString());
4468 static bool ParseTargetArgs(TargetOptions &Opts, ArgList &Args,
4469 DiagnosticsEngine &Diags) {
4470 unsigned NumErrorsBefore = Diags.getNumErrors();
4472 TargetOptions *TargetOpts = &Opts;
4474 #define TARGET_OPTION_WITH_MARSHALLING(...) \
4475 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
4476 #include "clang/Driver/Options.inc"
4477 #undef TARGET_OPTION_WITH_MARSHALLING
4479 if (Arg *A = Args.getLastArg(options::OPT_target_sdk_version_EQ)) {
4480 llvm::VersionTuple Version;
4481 if (Version.tryParse(A->getValue()))
4482 Diags.Report(diag::err_drv_invalid_value)
4483 << A->getAsString(Args) << A->getValue();
4484 else
4485 Opts.SDKVersion = Version;
4487 if (Arg *A =
4488 Args.getLastArg(options::OPT_darwin_target_variant_sdk_version_EQ)) {
4489 llvm::VersionTuple Version;
4490 if (Version.tryParse(A->getValue()))
4491 Diags.Report(diag::err_drv_invalid_value)
4492 << A->getAsString(Args) << A->getValue();
4493 else
4494 Opts.DarwinTargetVariantSDKVersion = Version;
4497 return Diags.getNumErrors() == NumErrorsBefore;
4500 bool CompilerInvocation::CreateFromArgsImpl(
4501 CompilerInvocation &Res, ArrayRef<const char *> CommandLineArgs,
4502 DiagnosticsEngine &Diags, const char *Argv0) {
4503 unsigned NumErrorsBefore = Diags.getNumErrors();
4505 // Parse the arguments.
4506 const OptTable &Opts = getDriverOptTable();
4507 llvm::opt::Visibility VisibilityMask(options::CC1Option);
4508 unsigned MissingArgIndex, MissingArgCount;
4509 InputArgList Args = Opts.ParseArgs(CommandLineArgs, MissingArgIndex,
4510 MissingArgCount, VisibilityMask);
4511 LangOptions &LangOpts = Res.getLangOpts();
4513 // Check for missing argument error.
4514 if (MissingArgCount)
4515 Diags.Report(diag::err_drv_missing_argument)
4516 << Args.getArgString(MissingArgIndex) << MissingArgCount;
4518 // Issue errors on unknown arguments.
4519 for (const auto *A : Args.filtered(OPT_UNKNOWN)) {
4520 auto ArgString = A->getAsString(Args);
4521 std::string Nearest;
4522 if (Opts.findNearest(ArgString, Nearest, VisibilityMask) > 1)
4523 Diags.Report(diag::err_drv_unknown_argument) << ArgString;
4524 else
4525 Diags.Report(diag::err_drv_unknown_argument_with_suggestion)
4526 << ArgString << Nearest;
4529 ParseFileSystemArgs(Res.getFileSystemOpts(), Args, Diags);
4530 ParseMigratorArgs(Res.getMigratorOpts(), Args, Diags);
4531 ParseAnalyzerArgs(Res.getAnalyzerOpts(), Args, Diags);
4532 ParseDiagnosticArgs(Res.getDiagnosticOpts(), Args, &Diags,
4533 /*DefaultDiagColor=*/false);
4534 ParseFrontendArgs(Res.getFrontendOpts(), Args, Diags, LangOpts.IsHeaderFile);
4535 // FIXME: We shouldn't have to pass the DashX option around here
4536 InputKind DashX = Res.getFrontendOpts().DashX;
4537 ParseTargetArgs(Res.getTargetOpts(), Args, Diags);
4538 llvm::Triple T(Res.getTargetOpts().Triple);
4539 ParseHeaderSearchArgs(Res.getHeaderSearchOpts(), Args, Diags,
4540 Res.getFileSystemOpts().WorkingDir);
4542 ParseLangArgs(LangOpts, Args, DashX, T, Res.getPreprocessorOpts().Includes,
4543 Diags);
4544 if (Res.getFrontendOpts().ProgramAction == frontend::RewriteObjC)
4545 LangOpts.ObjCExceptions = 1;
4547 for (auto Warning : Res.getDiagnosticOpts().Warnings) {
4548 if (Warning == "misexpect" &&
4549 !Diags.isIgnored(diag::warn_profile_data_misexpect, SourceLocation())) {
4550 Res.getCodeGenOpts().MisExpect = true;
4554 if (LangOpts.CUDA) {
4555 // During CUDA device-side compilation, the aux triple is the
4556 // triple used for host compilation.
4557 if (LangOpts.CUDAIsDevice)
4558 Res.getTargetOpts().HostTriple = Res.getFrontendOpts().AuxTriple;
4561 // Set the triple of the host for OpenMP device compile.
4562 if (LangOpts.OpenMPIsTargetDevice)
4563 Res.getTargetOpts().HostTriple = Res.getFrontendOpts().AuxTriple;
4565 ParseCodeGenArgs(Res.getCodeGenOpts(), Args, DashX, Diags, T,
4566 Res.getFrontendOpts().OutputFile, LangOpts);
4568 // FIXME: Override value name discarding when asan or msan is used because the
4569 // backend passes depend on the name of the alloca in order to print out
4570 // names.
4571 Res.getCodeGenOpts().DiscardValueNames &=
4572 !LangOpts.Sanitize.has(SanitizerKind::Address) &&
4573 !LangOpts.Sanitize.has(SanitizerKind::KernelAddress) &&
4574 !LangOpts.Sanitize.has(SanitizerKind::Memory) &&
4575 !LangOpts.Sanitize.has(SanitizerKind::KernelMemory);
4577 ParsePreprocessorArgs(Res.getPreprocessorOpts(), Args, Diags,
4578 Res.getFrontendOpts().ProgramAction,
4579 Res.getFrontendOpts());
4580 ParsePreprocessorOutputArgs(Res.getPreprocessorOutputOpts(), Args, Diags,
4581 Res.getFrontendOpts().ProgramAction);
4583 ParseDependencyOutputArgs(Res.getDependencyOutputOpts(), Args, Diags,
4584 Res.getFrontendOpts().ProgramAction,
4585 Res.getPreprocessorOutputOpts().ShowLineMarkers);
4586 if (!Res.getDependencyOutputOpts().OutputFile.empty() &&
4587 Res.getDependencyOutputOpts().Targets.empty())
4588 Diags.Report(diag::err_fe_dependency_file_requires_MT);
4590 // If sanitizer is enabled, disable OPT_ffine_grained_bitfield_accesses.
4591 if (Res.getCodeGenOpts().FineGrainedBitfieldAccesses &&
4592 !Res.getLangOpts().Sanitize.empty()) {
4593 Res.getCodeGenOpts().FineGrainedBitfieldAccesses = false;
4594 Diags.Report(diag::warn_drv_fine_grained_bitfield_accesses_ignored);
4597 // Store the command-line for using in the CodeView backend.
4598 if (Res.getCodeGenOpts().CodeViewCommandLine) {
4599 Res.getCodeGenOpts().Argv0 = Argv0;
4600 append_range(Res.getCodeGenOpts().CommandLineArgs, CommandLineArgs);
4603 // Set PGOOptions. Need to create a temporary VFS to read the profile
4604 // to determine the PGO type.
4605 if (!Res.getCodeGenOpts().ProfileInstrumentUsePath.empty()) {
4606 auto FS =
4607 createVFSFromOverlayFiles(Res.getHeaderSearchOpts().VFSOverlayFiles,
4608 Diags, llvm::vfs::getRealFileSystem());
4609 setPGOUseInstrumentor(Res.getCodeGenOpts(),
4610 Res.getCodeGenOpts().ProfileInstrumentUsePath, *FS,
4611 Diags);
4614 FixupInvocation(Res, Diags, Args, DashX);
4616 return Diags.getNumErrors() == NumErrorsBefore;
4619 bool CompilerInvocation::CreateFromArgs(CompilerInvocation &Invocation,
4620 ArrayRef<const char *> CommandLineArgs,
4621 DiagnosticsEngine &Diags,
4622 const char *Argv0) {
4623 CompilerInvocation DummyInvocation;
4625 return RoundTrip(
4626 [](CompilerInvocation &Invocation, ArrayRef<const char *> CommandLineArgs,
4627 DiagnosticsEngine &Diags, const char *Argv0) {
4628 return CreateFromArgsImpl(Invocation, CommandLineArgs, Diags, Argv0);
4630 [](CompilerInvocation &Invocation, SmallVectorImpl<const char *> &Args,
4631 StringAllocator SA) {
4632 Args.push_back("-cc1");
4633 Invocation.generateCC1CommandLine(Args, SA);
4635 Invocation, DummyInvocation, CommandLineArgs, Diags, Argv0);
4638 std::string CompilerInvocation::getModuleHash() const {
4639 // FIXME: Consider using SHA1 instead of MD5.
4640 llvm::HashBuilder<llvm::MD5, llvm::endianness::native> HBuilder;
4642 // Note: For QoI reasons, the things we use as a hash here should all be
4643 // dumped via the -module-info flag.
4645 // Start the signature with the compiler version.
4646 HBuilder.add(getClangFullRepositoryVersion());
4648 // Also include the serialization version, in case LLVM_APPEND_VC_REV is off
4649 // and getClangFullRepositoryVersion() doesn't include git revision.
4650 HBuilder.add(serialization::VERSION_MAJOR, serialization::VERSION_MINOR);
4652 // Extend the signature with the language options
4653 #define LANGOPT(Name, Bits, Default, Description) HBuilder.add(LangOpts->Name);
4654 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4655 HBuilder.add(static_cast<unsigned>(LangOpts->get##Name()));
4656 #define BENIGN_LANGOPT(Name, Bits, Default, Description)
4657 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
4658 #include "clang/Basic/LangOptions.def"
4660 HBuilder.addRange(getLangOpts().ModuleFeatures);
4662 HBuilder.add(getLangOpts().ObjCRuntime);
4663 HBuilder.addRange(getLangOpts().CommentOpts.BlockCommandNames);
4665 // Extend the signature with the target options.
4666 HBuilder.add(getTargetOpts().Triple, getTargetOpts().CPU,
4667 getTargetOpts().TuneCPU, getTargetOpts().ABI);
4668 HBuilder.addRange(getTargetOpts().FeaturesAsWritten);
4670 // Extend the signature with preprocessor options.
4671 const PreprocessorOptions &ppOpts = getPreprocessorOpts();
4672 HBuilder.add(ppOpts.UsePredefines, ppOpts.DetailedRecord);
4674 const HeaderSearchOptions &hsOpts = getHeaderSearchOpts();
4675 for (const auto &Macro : getPreprocessorOpts().Macros) {
4676 // If we're supposed to ignore this macro for the purposes of modules,
4677 // don't put it into the hash.
4678 if (!hsOpts.ModulesIgnoreMacros.empty()) {
4679 // Check whether we're ignoring this macro.
4680 StringRef MacroDef = Macro.first;
4681 if (hsOpts.ModulesIgnoreMacros.count(
4682 llvm::CachedHashString(MacroDef.split('=').first)))
4683 continue;
4686 HBuilder.add(Macro);
4689 // Extend the signature with the sysroot and other header search options.
4690 HBuilder.add(hsOpts.Sysroot, hsOpts.ModuleFormat, hsOpts.UseDebugInfo,
4691 hsOpts.UseBuiltinIncludes, hsOpts.UseStandardSystemIncludes,
4692 hsOpts.UseStandardCXXIncludes, hsOpts.UseLibcxx,
4693 hsOpts.ModulesValidateDiagnosticOptions);
4694 HBuilder.add(hsOpts.ResourceDir);
4696 if (hsOpts.ModulesStrictContextHash) {
4697 HBuilder.addRange(hsOpts.SystemHeaderPrefixes);
4698 HBuilder.addRange(hsOpts.UserEntries);
4700 const DiagnosticOptions &diagOpts = getDiagnosticOpts();
4701 #define DIAGOPT(Name, Bits, Default) HBuilder.add(diagOpts.Name);
4702 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
4703 HBuilder.add(diagOpts.get##Name());
4704 #include "clang/Basic/DiagnosticOptions.def"
4705 #undef DIAGOPT
4706 #undef ENUM_DIAGOPT
4709 // Extend the signature with the user build path.
4710 HBuilder.add(hsOpts.ModuleUserBuildPath);
4712 // Extend the signature with the module file extensions.
4713 for (const auto &ext : getFrontendOpts().ModuleFileExtensions)
4714 ext->hashExtension(HBuilder);
4716 // When compiling with -gmodules, also hash -fdebug-prefix-map as it
4717 // affects the debug info in the PCM.
4718 if (getCodeGenOpts().DebugTypeExtRefs)
4719 HBuilder.addRange(getCodeGenOpts().DebugPrefixMap);
4721 // Extend the signature with the enabled sanitizers, if at least one is
4722 // enabled. Sanitizers which cannot affect AST generation aren't hashed.
4723 SanitizerSet SanHash = getLangOpts().Sanitize;
4724 SanHash.clear(getPPTransparentSanitizers());
4725 if (!SanHash.empty())
4726 HBuilder.add(SanHash.Mask);
4728 llvm::MD5::MD5Result Result;
4729 HBuilder.getHasher().final(Result);
4730 uint64_t Hash = Result.high() ^ Result.low();
4731 return toString(llvm::APInt(64, Hash), 36, /*Signed=*/false);
4734 void CompilerInvocationBase::generateCC1CommandLine(
4735 ArgumentConsumer Consumer) const {
4736 llvm::Triple T(getTargetOpts().Triple);
4738 GenerateFileSystemArgs(getFileSystemOpts(), Consumer);
4739 GenerateMigratorArgs(getMigratorOpts(), Consumer);
4740 GenerateAnalyzerArgs(getAnalyzerOpts(), Consumer);
4741 GenerateDiagnosticArgs(getDiagnosticOpts(), Consumer,
4742 /*DefaultDiagColor=*/false);
4743 GenerateFrontendArgs(getFrontendOpts(), Consumer, getLangOpts().IsHeaderFile);
4744 GenerateTargetArgs(getTargetOpts(), Consumer);
4745 GenerateHeaderSearchArgs(getHeaderSearchOpts(), Consumer);
4746 GenerateLangArgs(getLangOpts(), Consumer, T, getFrontendOpts().DashX);
4747 GenerateCodeGenArgs(getCodeGenOpts(), Consumer, T,
4748 getFrontendOpts().OutputFile, &getLangOpts());
4749 GeneratePreprocessorArgs(getPreprocessorOpts(), Consumer, getLangOpts(),
4750 getFrontendOpts(), getCodeGenOpts());
4751 GeneratePreprocessorOutputArgs(getPreprocessorOutputOpts(), Consumer,
4752 getFrontendOpts().ProgramAction);
4753 GenerateDependencyOutputArgs(getDependencyOutputOpts(), Consumer);
4756 std::vector<std::string> CompilerInvocationBase::getCC1CommandLine() const {
4757 std::vector<std::string> Args{"-cc1"};
4758 generateCC1CommandLine(
4759 [&Args](const Twine &Arg) { Args.push_back(Arg.str()); });
4760 return Args;
4763 void CompilerInvocation::resetNonModularOptions() {
4764 getLangOpts().resetNonModularOptions();
4765 getPreprocessorOpts().resetNonModularOptions();
4768 void CompilerInvocation::clearImplicitModuleBuildOptions() {
4769 getLangOpts().ImplicitModules = false;
4770 getHeaderSearchOpts().ImplicitModuleMaps = false;
4771 getHeaderSearchOpts().ModuleCachePath.clear();
4772 getHeaderSearchOpts().ModulesValidateOncePerBuildSession = false;
4773 getHeaderSearchOpts().BuildSessionTimestamp = 0;
4774 // The specific values we canonicalize to for pruning don't affect behaviour,
4775 /// so use the default values so they may be dropped from the command-line.
4776 getHeaderSearchOpts().ModuleCachePruneInterval = 7 * 24 * 60 * 60;
4777 getHeaderSearchOpts().ModuleCachePruneAfter = 31 * 24 * 60 * 60;
4780 IntrusiveRefCntPtr<llvm::vfs::FileSystem>
4781 clang::createVFSFromCompilerInvocation(const CompilerInvocation &CI,
4782 DiagnosticsEngine &Diags) {
4783 return createVFSFromCompilerInvocation(CI, Diags,
4784 llvm::vfs::getRealFileSystem());
4787 IntrusiveRefCntPtr<llvm::vfs::FileSystem>
4788 clang::createVFSFromCompilerInvocation(
4789 const CompilerInvocation &CI, DiagnosticsEngine &Diags,
4790 IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS) {
4791 return createVFSFromOverlayFiles(CI.getHeaderSearchOpts().VFSOverlayFiles,
4792 Diags, std::move(BaseFS));
4795 IntrusiveRefCntPtr<llvm::vfs::FileSystem> clang::createVFSFromOverlayFiles(
4796 ArrayRef<std::string> VFSOverlayFiles, DiagnosticsEngine &Diags,
4797 IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS) {
4798 if (VFSOverlayFiles.empty())
4799 return BaseFS;
4801 IntrusiveRefCntPtr<llvm::vfs::FileSystem> Result = BaseFS;
4802 // earlier vfs files are on the bottom
4803 for (const auto &File : VFSOverlayFiles) {
4804 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer =
4805 Result->getBufferForFile(File);
4806 if (!Buffer) {
4807 Diags.Report(diag::err_missing_vfs_overlay_file) << File;
4808 continue;
4811 IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS = llvm::vfs::getVFSFromYAML(
4812 std::move(Buffer.get()), /*DiagHandler*/ nullptr, File,
4813 /*DiagContext*/ nullptr, Result);
4814 if (!FS) {
4815 Diags.Report(diag::err_invalid_vfs_overlay) << File;
4816 continue;
4819 Result = FS;
4821 return Result;