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