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