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