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