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   }
1061 
1062   if (Opts.ShouldEmitErrorsOnInvalidConfigValue)
1063     parseAnalyzerConfigs(Opts, &Diags);
1064   else
1065     parseAnalyzerConfigs(Opts, nullptr);
1066 
1067   llvm::raw_string_ostream os(Opts.FullCompilerInvocation);
1068   for (unsigned i = 0; i < Args.getNumInputArgStrings(); ++i) {
1069     if (i != 0)
1070       os << " ";
1071     os << Args.getArgString(i);
1072   }
1073   os.flush();
1074 
1075   return Diags.getNumErrors() == NumErrorsBefore;
1076 }
1077 
1078 static StringRef getStringOption(AnalyzerOptions::ConfigTable &Config,
1079                                  StringRef OptionName, StringRef DefaultVal) {
1080   return Config.insert({OptionName, std::string(DefaultVal)}).first->second;
1081 }
1082 
1083 static void initOption(AnalyzerOptions::ConfigTable &Config,
1084                        DiagnosticsEngine *Diags,
1085                        StringRef &OptionField, StringRef Name,
1086                        StringRef DefaultVal) {
1087   // String options may be known to invalid (e.g. if the expected string is a
1088   // file name, but the file does not exist), those will have to be checked in
1089   // parseConfigs.
1090   OptionField = getStringOption(Config, Name, DefaultVal);
1091 }
1092 
1093 static void initOption(AnalyzerOptions::ConfigTable &Config,
1094                        DiagnosticsEngine *Diags,
1095                        bool &OptionField, StringRef Name, bool DefaultVal) {
1096   auto PossiblyInvalidVal =
1097       llvm::StringSwitch<std::optional<bool>>(
1098           getStringOption(Config, Name, (DefaultVal ? "true" : "false")))
1099           .Case("true", true)
1100           .Case("false", false)
1101           .Default(std::nullopt);
1102 
1103   if (!PossiblyInvalidVal) {
1104     if (Diags)
1105       Diags->Report(diag::err_analyzer_config_invalid_input)
1106         << Name << "a boolean";
1107     else
1108       OptionField = DefaultVal;
1109   } else
1110     OptionField = *PossiblyInvalidVal;
1111 }
1112 
1113 static void initOption(AnalyzerOptions::ConfigTable &Config,
1114                        DiagnosticsEngine *Diags,
1115                        unsigned &OptionField, StringRef Name,
1116                        unsigned DefaultVal) {
1117 
1118   OptionField = DefaultVal;
1119   bool HasFailed = getStringOption(Config, Name, std::to_string(DefaultVal))
1120                      .getAsInteger(0, OptionField);
1121   if (Diags && HasFailed)
1122     Diags->Report(diag::err_analyzer_config_invalid_input)
1123       << Name << "an unsigned";
1124 }
1125 
1126 static void parseAnalyzerConfigs(AnalyzerOptions &AnOpts,
1127                                  DiagnosticsEngine *Diags) {
1128   // TODO: There's no need to store the entire configtable, it'd be plenty
1129   // enough to store checker options.
1130 
1131 #define ANALYZER_OPTION(TYPE, NAME, CMDFLAG, DESC, DEFAULT_VAL)                \
1132   initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, DEFAULT_VAL);
1133 #define ANALYZER_OPTION_DEPENDS_ON_USER_MODE(...)
1134 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.def"
1135 
1136   assert(AnOpts.UserMode == "shallow" || AnOpts.UserMode == "deep");
1137   const bool InShallowMode = AnOpts.UserMode == "shallow";
1138 
1139 #define ANALYZER_OPTION(...)
1140 #define ANALYZER_OPTION_DEPENDS_ON_USER_MODE(TYPE, NAME, CMDFLAG, DESC,        \
1141                                              SHALLOW_VAL, DEEP_VAL)            \
1142   initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG,                       \
1143              InShallowMode ? SHALLOW_VAL : DEEP_VAL);
1144 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.def"
1145 
1146   // At this point, AnalyzerOptions is configured. Let's validate some options.
1147 
1148   // FIXME: Here we try to validate the silenced checkers or packages are valid.
1149   // The current approach only validates the registered checkers which does not
1150   // contain the runtime enabled checkers and optimally we would validate both.
1151   if (!AnOpts.RawSilencedCheckersAndPackages.empty()) {
1152     std::vector<StringRef> Checkers =
1153         AnOpts.getRegisteredCheckers(/*IncludeExperimental=*/true);
1154     std::vector<StringRef> Packages =
1155         AnOpts.getRegisteredPackages(/*IncludeExperimental=*/true);
1156 
1157     SmallVector<StringRef, 16> CheckersAndPackages;
1158     AnOpts.RawSilencedCheckersAndPackages.split(CheckersAndPackages, ";");
1159 
1160     for (const StringRef &CheckerOrPackage : CheckersAndPackages) {
1161       if (Diags) {
1162         bool IsChecker = CheckerOrPackage.contains('.');
1163         bool IsValidName = IsChecker
1164                                ? llvm::is_contained(Checkers, CheckerOrPackage)
1165                                : llvm::is_contained(Packages, CheckerOrPackage);
1166 
1167         if (!IsValidName)
1168           Diags->Report(diag::err_unknown_analyzer_checker_or_package)
1169               << CheckerOrPackage;
1170       }
1171 
1172       AnOpts.SilencedCheckersAndPackages.emplace_back(CheckerOrPackage);
1173     }
1174   }
1175 
1176   if (!Diags)
1177     return;
1178 
1179   if (AnOpts.ShouldTrackConditionsDebug && !AnOpts.ShouldTrackConditions)
1180     Diags->Report(diag::err_analyzer_config_invalid_input)
1181         << "track-conditions-debug" << "'track-conditions' to also be enabled";
1182 
1183   if (!AnOpts.CTUDir.empty() && !llvm::sys::fs::is_directory(AnOpts.CTUDir))
1184     Diags->Report(diag::err_analyzer_config_invalid_input) << "ctu-dir"
1185                                                            << "a filename";
1186 
1187   if (!AnOpts.ModelPath.empty() &&
1188       !llvm::sys::fs::is_directory(AnOpts.ModelPath))
1189     Diags->Report(diag::err_analyzer_config_invalid_input) << "model-path"
1190                                                            << "a filename";
1191 }
1192 
1193 /// Generate a remark argument. This is an inverse of `ParseOptimizationRemark`.
1194 static void
1195 GenerateOptimizationRemark(SmallVectorImpl<const char *> &Args,
1196                            CompilerInvocation::StringAllocator SA,
1197                            OptSpecifier OptEQ, StringRef Name,
1198                            const CodeGenOptions::OptRemark &Remark) {
1199   if (Remark.hasValidPattern()) {
1200     GenerateArg(Args, OptEQ, Remark.Pattern, SA);
1201   } else if (Remark.Kind == CodeGenOptions::RK_Enabled) {
1202     GenerateArg(Args, OPT_R_Joined, Name, SA);
1203   } else if (Remark.Kind == CodeGenOptions::RK_Disabled) {
1204     GenerateArg(Args, OPT_R_Joined, StringRef("no-") + Name, SA);
1205   }
1206 }
1207 
1208 /// Parse a remark command line argument. It may be missing, disabled/enabled by
1209 /// '-R[no-]group' or specified with a regular expression by '-Rgroup=regexp'.
1210 /// On top of that, it can be disabled/enabled globally by '-R[no-]everything'.
1211 static CodeGenOptions::OptRemark
1212 ParseOptimizationRemark(DiagnosticsEngine &Diags, ArgList &Args,
1213                         OptSpecifier OptEQ, StringRef Name) {
1214   CodeGenOptions::OptRemark Result;
1215 
1216   auto InitializeResultPattern = [&Diags, &Args, &Result](const Arg *A,
1217                                                           StringRef Pattern) {
1218     Result.Pattern = Pattern.str();
1219 
1220     std::string RegexError;
1221     Result.Regex = std::make_shared<llvm::Regex>(Result.Pattern);
1222     if (!Result.Regex->isValid(RegexError)) {
1223       Diags.Report(diag::err_drv_optimization_remark_pattern)
1224           << RegexError << A->getAsString(Args);
1225       return false;
1226     }
1227 
1228     return true;
1229   };
1230 
1231   for (Arg *A : Args) {
1232     if (A->getOption().matches(OPT_R_Joined)) {
1233       StringRef Value = A->getValue();
1234 
1235       if (Value == Name)
1236         Result.Kind = CodeGenOptions::RK_Enabled;
1237       else if (Value == "everything")
1238         Result.Kind = CodeGenOptions::RK_EnabledEverything;
1239       else if (Value.split('-') == std::make_pair(StringRef("no"), Name))
1240         Result.Kind = CodeGenOptions::RK_Disabled;
1241       else if (Value == "no-everything")
1242         Result.Kind = CodeGenOptions::RK_DisabledEverything;
1243       else
1244         continue;
1245 
1246       if (Result.Kind == CodeGenOptions::RK_Disabled ||
1247           Result.Kind == CodeGenOptions::RK_DisabledEverything) {
1248         Result.Pattern = "";
1249         Result.Regex = nullptr;
1250       } else {
1251         InitializeResultPattern(A, ".*");
1252       }
1253     } else if (A->getOption().matches(OptEQ)) {
1254       Result.Kind = CodeGenOptions::RK_WithPattern;
1255       if (!InitializeResultPattern(A, A->getValue()))
1256         return CodeGenOptions::OptRemark();
1257     }
1258   }
1259 
1260   return Result;
1261 }
1262 
1263 static bool parseDiagnosticLevelMask(StringRef FlagName,
1264                                      const std::vector<std::string> &Levels,
1265                                      DiagnosticsEngine &Diags,
1266                                      DiagnosticLevelMask &M) {
1267   bool Success = true;
1268   for (const auto &Level : Levels) {
1269     DiagnosticLevelMask const PM =
1270       llvm::StringSwitch<DiagnosticLevelMask>(Level)
1271         .Case("note",    DiagnosticLevelMask::Note)
1272         .Case("remark",  DiagnosticLevelMask::Remark)
1273         .Case("warning", DiagnosticLevelMask::Warning)
1274         .Case("error",   DiagnosticLevelMask::Error)
1275         .Default(DiagnosticLevelMask::None);
1276     if (PM == DiagnosticLevelMask::None) {
1277       Success = false;
1278       Diags.Report(diag::err_drv_invalid_value) << FlagName << Level;
1279     }
1280     M = M | PM;
1281   }
1282   return Success;
1283 }
1284 
1285 static void parseSanitizerKinds(StringRef FlagName,
1286                                 const std::vector<std::string> &Sanitizers,
1287                                 DiagnosticsEngine &Diags, SanitizerSet &S) {
1288   for (const auto &Sanitizer : Sanitizers) {
1289     SanitizerMask K = parseSanitizerValue(Sanitizer, /*AllowGroups=*/false);
1290     if (K == SanitizerMask())
1291       Diags.Report(diag::err_drv_invalid_value) << FlagName << Sanitizer;
1292     else
1293       S.set(K, true);
1294   }
1295 }
1296 
1297 static SmallVector<StringRef, 4> serializeSanitizerKinds(SanitizerSet S) {
1298   SmallVector<StringRef, 4> Values;
1299   serializeSanitizerSet(S, Values);
1300   return Values;
1301 }
1302 
1303 static void parseXRayInstrumentationBundle(StringRef FlagName, StringRef Bundle,
1304                                            ArgList &Args, DiagnosticsEngine &D,
1305                                            XRayInstrSet &S) {
1306   llvm::SmallVector<StringRef, 2> BundleParts;
1307   llvm::SplitString(Bundle, BundleParts, ",");
1308   for (const auto &B : BundleParts) {
1309     auto Mask = parseXRayInstrValue(B);
1310     if (Mask == XRayInstrKind::None)
1311       if (B != "none")
1312         D.Report(diag::err_drv_invalid_value) << FlagName << Bundle;
1313       else
1314         S.Mask = Mask;
1315     else if (Mask == XRayInstrKind::All)
1316       S.Mask = Mask;
1317     else
1318       S.set(Mask, true);
1319   }
1320 }
1321 
1322 static std::string serializeXRayInstrumentationBundle(const XRayInstrSet &S) {
1323   llvm::SmallVector<StringRef, 2> BundleParts;
1324   serializeXRayInstrValue(S, BundleParts);
1325   std::string Buffer;
1326   llvm::raw_string_ostream OS(Buffer);
1327   llvm::interleave(BundleParts, OS, [&OS](StringRef Part) { OS << Part; }, ",");
1328   return Buffer;
1329 }
1330 
1331 // Set the profile kind using fprofile-instrument-use-path.
1332 static void setPGOUseInstrumentor(CodeGenOptions &Opts,
1333                                   const Twine &ProfileName,
1334                                   llvm::vfs::FileSystem &FS,
1335                                   DiagnosticsEngine &Diags) {
1336   auto ReaderOrErr = llvm::IndexedInstrProfReader::create(ProfileName, FS);
1337   if (auto E = ReaderOrErr.takeError()) {
1338     unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1339                                             "Error in reading profile %0: %1");
1340     llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
1341       Diags.Report(DiagID) << ProfileName.str() << EI.message();
1342     });
1343     return;
1344   }
1345   std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader =
1346     std::move(ReaderOrErr.get());
1347   // Currently memprof profiles are only added at the IR level. Mark the profile
1348   // type as IR in that case as well and the subsequent matching needs to detect
1349   // which is available (might be one or both).
1350   if (PGOReader->isIRLevelProfile() || PGOReader->hasMemoryProfile()) {
1351     if (PGOReader->hasCSIRLevelProfile())
1352       Opts.setProfileUse(CodeGenOptions::ProfileCSIRInstr);
1353     else
1354       Opts.setProfileUse(CodeGenOptions::ProfileIRInstr);
1355   } else
1356     Opts.setProfileUse(CodeGenOptions::ProfileClangInstr);
1357 }
1358 
1359 void CompilerInvocation::GenerateCodeGenArgs(
1360     const CodeGenOptions &Opts, SmallVectorImpl<const char *> &Args,
1361     StringAllocator SA, const llvm::Triple &T, const std::string &OutputFile,
1362     const LangOptions *LangOpts) {
1363   const CodeGenOptions &CodeGenOpts = Opts;
1364 
1365   if (Opts.OptimizationLevel == 0)
1366     GenerateArg(Args, OPT_O0, SA);
1367   else
1368     GenerateArg(Args, OPT_O, Twine(Opts.OptimizationLevel), SA);
1369 
1370 #define CODEGEN_OPTION_WITH_MARSHALLING(...)                                   \
1371   GENERATE_OPTION_WITH_MARSHALLING(Args, SA, __VA_ARGS__)
1372 #include "clang/Driver/Options.inc"
1373 #undef CODEGEN_OPTION_WITH_MARSHALLING
1374 
1375   if (Opts.OptimizationLevel > 0) {
1376     if (Opts.Inlining == CodeGenOptions::NormalInlining)
1377       GenerateArg(Args, OPT_finline_functions, SA);
1378     else if (Opts.Inlining == CodeGenOptions::OnlyHintInlining)
1379       GenerateArg(Args, OPT_finline_hint_functions, SA);
1380     else if (Opts.Inlining == CodeGenOptions::OnlyAlwaysInlining)
1381       GenerateArg(Args, OPT_fno_inline, SA);
1382   }
1383 
1384   if (Opts.DirectAccessExternalData && LangOpts->PICLevel != 0)
1385     GenerateArg(Args, OPT_fdirect_access_external_data, SA);
1386   else if (!Opts.DirectAccessExternalData && LangOpts->PICLevel == 0)
1387     GenerateArg(Args, OPT_fno_direct_access_external_data, SA);
1388 
1389   std::optional<StringRef> DebugInfoVal;
1390   switch (Opts.DebugInfo) {
1391   case llvm::codegenoptions::DebugLineTablesOnly:
1392     DebugInfoVal = "line-tables-only";
1393     break;
1394   case llvm::codegenoptions::DebugDirectivesOnly:
1395     DebugInfoVal = "line-directives-only";
1396     break;
1397   case llvm::codegenoptions::DebugInfoConstructor:
1398     DebugInfoVal = "constructor";
1399     break;
1400   case llvm::codegenoptions::LimitedDebugInfo:
1401     DebugInfoVal = "limited";
1402     break;
1403   case llvm::codegenoptions::FullDebugInfo:
1404     DebugInfoVal = "standalone";
1405     break;
1406   case llvm::codegenoptions::UnusedTypeInfo:
1407     DebugInfoVal = "unused-types";
1408     break;
1409   case llvm::codegenoptions::NoDebugInfo: // default value
1410     DebugInfoVal = std::nullopt;
1411     break;
1412   case llvm::codegenoptions::LocTrackingOnly: // implied value
1413     DebugInfoVal = std::nullopt;
1414     break;
1415   }
1416   if (DebugInfoVal)
1417     GenerateArg(Args, OPT_debug_info_kind_EQ, *DebugInfoVal, SA);
1418 
1419   for (const auto &Prefix : Opts.DebugPrefixMap)
1420     GenerateArg(Args, OPT_fdebug_prefix_map_EQ,
1421                 Prefix.first + "=" + Prefix.second, SA);
1422 
1423   for (const auto &Prefix : Opts.CoveragePrefixMap)
1424     GenerateArg(Args, OPT_fcoverage_prefix_map_EQ,
1425                 Prefix.first + "=" + Prefix.second, SA);
1426 
1427   if (Opts.NewStructPathTBAA)
1428     GenerateArg(Args, OPT_new_struct_path_tbaa, SA);
1429 
1430   if (Opts.OptimizeSize == 1)
1431     GenerateArg(Args, OPT_O, "s", SA);
1432   else if (Opts.OptimizeSize == 2)
1433     GenerateArg(Args, OPT_O, "z", SA);
1434 
1435   // SimplifyLibCalls is set only in the absence of -fno-builtin and
1436   // -ffreestanding. We'll consider that when generating them.
1437 
1438   // NoBuiltinFuncs are generated by LangOptions.
1439 
1440   if (Opts.UnrollLoops && Opts.OptimizationLevel <= 1)
1441     GenerateArg(Args, OPT_funroll_loops, SA);
1442   else if (!Opts.UnrollLoops && Opts.OptimizationLevel > 1)
1443     GenerateArg(Args, OPT_fno_unroll_loops, SA);
1444 
1445   if (!Opts.BinutilsVersion.empty())
1446     GenerateArg(Args, OPT_fbinutils_version_EQ, Opts.BinutilsVersion, SA);
1447 
1448   if (Opts.DebugNameTable ==
1449       static_cast<unsigned>(llvm::DICompileUnit::DebugNameTableKind::GNU))
1450     GenerateArg(Args, OPT_ggnu_pubnames, SA);
1451   else if (Opts.DebugNameTable ==
1452            static_cast<unsigned>(
1453                llvm::DICompileUnit::DebugNameTableKind::Default))
1454     GenerateArg(Args, OPT_gpubnames, SA);
1455 
1456   auto TNK = Opts.getDebugSimpleTemplateNames();
1457   if (TNK != llvm::codegenoptions::DebugTemplateNamesKind::Full) {
1458     if (TNK == llvm::codegenoptions::DebugTemplateNamesKind::Simple)
1459       GenerateArg(Args, OPT_gsimple_template_names_EQ, "simple", SA);
1460     else if (TNK == llvm::codegenoptions::DebugTemplateNamesKind::Mangled)
1461       GenerateArg(Args, OPT_gsimple_template_names_EQ, "mangled", SA);
1462   }
1463   // ProfileInstrumentUsePath is marshalled automatically, no need to generate
1464   // it or PGOUseInstrumentor.
1465 
1466   if (Opts.TimePasses) {
1467     if (Opts.TimePassesPerRun)
1468       GenerateArg(Args, OPT_ftime_report_EQ, "per-pass-run", SA);
1469     else
1470       GenerateArg(Args, OPT_ftime_report, SA);
1471   }
1472 
1473   if (Opts.PrepareForLTO && !Opts.PrepareForThinLTO)
1474     GenerateArg(Args, OPT_flto_EQ, "full", SA);
1475 
1476   if (Opts.PrepareForThinLTO)
1477     GenerateArg(Args, OPT_flto_EQ, "thin", SA);
1478 
1479   if (!Opts.ThinLTOIndexFile.empty())
1480     GenerateArg(Args, OPT_fthinlto_index_EQ, Opts.ThinLTOIndexFile, SA);
1481 
1482   if (Opts.SaveTempsFilePrefix == OutputFile)
1483     GenerateArg(Args, OPT_save_temps_EQ, "obj", SA);
1484 
1485   StringRef MemProfileBasename("memprof.profraw");
1486   if (!Opts.MemoryProfileOutput.empty()) {
1487     if (Opts.MemoryProfileOutput == MemProfileBasename) {
1488       GenerateArg(Args, OPT_fmemory_profile, SA);
1489     } else {
1490       size_t ArgLength =
1491           Opts.MemoryProfileOutput.size() - MemProfileBasename.size();
1492       GenerateArg(Args, OPT_fmemory_profile_EQ,
1493                   Opts.MemoryProfileOutput.substr(0, ArgLength), SA);
1494     }
1495   }
1496 
1497   if (memcmp(Opts.CoverageVersion, "408*", 4) != 0)
1498     GenerateArg(Args, OPT_coverage_version_EQ,
1499                 StringRef(Opts.CoverageVersion, 4), SA);
1500 
1501   // TODO: Check if we need to generate arguments stored in CmdArgs. (Namely
1502   //  '-fembed_bitcode', which does not map to any CompilerInvocation field and
1503   //  won't be generated.)
1504 
1505   if (Opts.XRayInstrumentationBundle.Mask != XRayInstrKind::All) {
1506     std::string InstrBundle =
1507         serializeXRayInstrumentationBundle(Opts.XRayInstrumentationBundle);
1508     if (!InstrBundle.empty())
1509       GenerateArg(Args, OPT_fxray_instrumentation_bundle, InstrBundle, SA);
1510   }
1511 
1512   if (Opts.CFProtectionReturn && Opts.CFProtectionBranch)
1513     GenerateArg(Args, OPT_fcf_protection_EQ, "full", SA);
1514   else if (Opts.CFProtectionReturn)
1515     GenerateArg(Args, OPT_fcf_protection_EQ, "return", SA);
1516   else if (Opts.CFProtectionBranch)
1517     GenerateArg(Args, OPT_fcf_protection_EQ, "branch", SA);
1518 
1519   if (Opts.FunctionReturnThunks)
1520     GenerateArg(Args, OPT_mfunction_return_EQ, "thunk-extern", SA);
1521 
1522   for (const auto &F : Opts.LinkBitcodeFiles) {
1523     bool Builtint = F.LinkFlags == llvm::Linker::Flags::LinkOnlyNeeded &&
1524                     F.PropagateAttrs && F.Internalize;
1525     GenerateArg(Args,
1526                 Builtint ? OPT_mlink_builtin_bitcode : OPT_mlink_bitcode_file,
1527                 F.Filename, SA);
1528   }
1529 
1530   if (Opts.EmulatedTLS)
1531     GenerateArg(Args, OPT_femulated_tls, SA);
1532 
1533   if (Opts.FPDenormalMode != llvm::DenormalMode::getIEEE())
1534     GenerateArg(Args, OPT_fdenormal_fp_math_EQ, Opts.FPDenormalMode.str(), SA);
1535 
1536   if ((Opts.FPDenormalMode != Opts.FP32DenormalMode) ||
1537       (Opts.FP32DenormalMode != llvm::DenormalMode::getIEEE()))
1538     GenerateArg(Args, OPT_fdenormal_fp_math_f32_EQ, Opts.FP32DenormalMode.str(),
1539                 SA);
1540 
1541   if (Opts.StructReturnConvention == CodeGenOptions::SRCK_OnStack) {
1542     OptSpecifier Opt =
1543         T.isPPC32() ? OPT_maix_struct_return : OPT_fpcc_struct_return;
1544     GenerateArg(Args, Opt, SA);
1545   } else if (Opts.StructReturnConvention == CodeGenOptions::SRCK_InRegs) {
1546     OptSpecifier Opt =
1547         T.isPPC32() ? OPT_msvr4_struct_return : OPT_freg_struct_return;
1548     GenerateArg(Args, Opt, SA);
1549   }
1550 
1551   if (Opts.EnableAIXExtendedAltivecABI)
1552     GenerateArg(Args, OPT_mabi_EQ_vec_extabi, SA);
1553 
1554   if (Opts.XCOFFReadOnlyPointers)
1555     GenerateArg(Args, OPT_mxcoff_roptr, SA);
1556 
1557   if (!Opts.OptRecordPasses.empty())
1558     GenerateArg(Args, OPT_opt_record_passes, Opts.OptRecordPasses, SA);
1559 
1560   if (!Opts.OptRecordFormat.empty())
1561     GenerateArg(Args, OPT_opt_record_format, Opts.OptRecordFormat, SA);
1562 
1563   GenerateOptimizationRemark(Args, SA, OPT_Rpass_EQ, "pass",
1564                              Opts.OptimizationRemark);
1565 
1566   GenerateOptimizationRemark(Args, SA, OPT_Rpass_missed_EQ, "pass-missed",
1567                              Opts.OptimizationRemarkMissed);
1568 
1569   GenerateOptimizationRemark(Args, SA, OPT_Rpass_analysis_EQ, "pass-analysis",
1570                              Opts.OptimizationRemarkAnalysis);
1571 
1572   GenerateArg(Args, OPT_fdiagnostics_hotness_threshold_EQ,
1573               Opts.DiagnosticsHotnessThreshold
1574                   ? Twine(*Opts.DiagnosticsHotnessThreshold)
1575                   : "auto",
1576               SA);
1577 
1578   GenerateArg(Args, OPT_fdiagnostics_misexpect_tolerance_EQ,
1579               Twine(*Opts.DiagnosticsMisExpectTolerance), SA);
1580 
1581   for (StringRef Sanitizer : serializeSanitizerKinds(Opts.SanitizeRecover))
1582     GenerateArg(Args, OPT_fsanitize_recover_EQ, Sanitizer, SA);
1583 
1584   for (StringRef Sanitizer : serializeSanitizerKinds(Opts.SanitizeTrap))
1585     GenerateArg(Args, OPT_fsanitize_trap_EQ, Sanitizer, SA);
1586 
1587   if (!Opts.EmitVersionIdentMetadata)
1588     GenerateArg(Args, OPT_Qn, SA);
1589 
1590   switch (Opts.FiniteLoops) {
1591   case CodeGenOptions::FiniteLoopsKind::Language:
1592     break;
1593   case CodeGenOptions::FiniteLoopsKind::Always:
1594     GenerateArg(Args, OPT_ffinite_loops, SA);
1595     break;
1596   case CodeGenOptions::FiniteLoopsKind::Never:
1597     GenerateArg(Args, OPT_fno_finite_loops, SA);
1598     break;
1599   }
1600 }
1601 
1602 bool CompilerInvocation::ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args,
1603                                           InputKind IK,
1604                                           DiagnosticsEngine &Diags,
1605                                           const llvm::Triple &T,
1606                                           const std::string &OutputFile,
1607                                           const LangOptions &LangOptsRef) {
1608   unsigned NumErrorsBefore = Diags.getNumErrors();
1609 
1610   unsigned OptimizationLevel = getOptimizationLevel(Args, IK, Diags);
1611   // TODO: This could be done in Driver
1612   unsigned MaxOptLevel = 3;
1613   if (OptimizationLevel > MaxOptLevel) {
1614     // If the optimization level is not supported, fall back on the default
1615     // optimization
1616     Diags.Report(diag::warn_drv_optimization_value)
1617         << Args.getLastArg(OPT_O)->getAsString(Args) << "-O" << MaxOptLevel;
1618     OptimizationLevel = MaxOptLevel;
1619   }
1620   Opts.OptimizationLevel = OptimizationLevel;
1621 
1622   // The key paths of codegen options defined in Options.td start with
1623   // "CodeGenOpts.". Let's provide the expected variable name and type.
1624   CodeGenOptions &CodeGenOpts = Opts;
1625   // Some codegen options depend on language options. Let's provide the expected
1626   // variable name and type.
1627   const LangOptions *LangOpts = &LangOptsRef;
1628 
1629 #define CODEGEN_OPTION_WITH_MARSHALLING(...)                                   \
1630   PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
1631 #include "clang/Driver/Options.inc"
1632 #undef CODEGEN_OPTION_WITH_MARSHALLING
1633 
1634   // At O0 we want to fully disable inlining outside of cases marked with
1635   // 'alwaysinline' that are required for correctness.
1636   if (Opts.OptimizationLevel == 0) {
1637     Opts.setInlining(CodeGenOptions::OnlyAlwaysInlining);
1638   } else if (const Arg *A = Args.getLastArg(options::OPT_finline_functions,
1639                                             options::OPT_finline_hint_functions,
1640                                             options::OPT_fno_inline_functions,
1641                                             options::OPT_fno_inline)) {
1642     // Explicit inlining flags can disable some or all inlining even at
1643     // optimization levels above zero.
1644     if (A->getOption().matches(options::OPT_finline_functions))
1645       Opts.setInlining(CodeGenOptions::NormalInlining);
1646     else if (A->getOption().matches(options::OPT_finline_hint_functions))
1647       Opts.setInlining(CodeGenOptions::OnlyHintInlining);
1648     else
1649       Opts.setInlining(CodeGenOptions::OnlyAlwaysInlining);
1650   } else {
1651     Opts.setInlining(CodeGenOptions::NormalInlining);
1652   }
1653 
1654   // PIC defaults to -fno-direct-access-external-data while non-PIC defaults to
1655   // -fdirect-access-external-data.
1656   Opts.DirectAccessExternalData =
1657       Args.hasArg(OPT_fdirect_access_external_data) ||
1658       (!Args.hasArg(OPT_fno_direct_access_external_data) &&
1659        LangOpts->PICLevel == 0);
1660 
1661   if (Arg *A = Args.getLastArg(OPT_debug_info_kind_EQ)) {
1662     unsigned Val =
1663         llvm::StringSwitch<unsigned>(A->getValue())
1664             .Case("line-tables-only", llvm::codegenoptions::DebugLineTablesOnly)
1665             .Case("line-directives-only",
1666                   llvm::codegenoptions::DebugDirectivesOnly)
1667             .Case("constructor", llvm::codegenoptions::DebugInfoConstructor)
1668             .Case("limited", llvm::codegenoptions::LimitedDebugInfo)
1669             .Case("standalone", llvm::codegenoptions::FullDebugInfo)
1670             .Case("unused-types", llvm::codegenoptions::UnusedTypeInfo)
1671             .Default(~0U);
1672     if (Val == ~0U)
1673       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
1674                                                 << A->getValue();
1675     else
1676       Opts.setDebugInfo(static_cast<llvm::codegenoptions::DebugInfoKind>(Val));
1677   }
1678 
1679   // If -fuse-ctor-homing is set and limited debug info is already on, then use
1680   // constructor homing, and vice versa for -fno-use-ctor-homing.
1681   if (const Arg *A =
1682           Args.getLastArg(OPT_fuse_ctor_homing, OPT_fno_use_ctor_homing)) {
1683     if (A->getOption().matches(OPT_fuse_ctor_homing) &&
1684         Opts.getDebugInfo() == llvm::codegenoptions::LimitedDebugInfo)
1685       Opts.setDebugInfo(llvm::codegenoptions::DebugInfoConstructor);
1686     if (A->getOption().matches(OPT_fno_use_ctor_homing) &&
1687         Opts.getDebugInfo() == llvm::codegenoptions::DebugInfoConstructor)
1688       Opts.setDebugInfo(llvm::codegenoptions::LimitedDebugInfo);
1689   }
1690 
1691   for (const auto &Arg : Args.getAllArgValues(OPT_fdebug_prefix_map_EQ)) {
1692     auto Split = StringRef(Arg).split('=');
1693     Opts.DebugPrefixMap.emplace_back(Split.first, Split.second);
1694   }
1695 
1696   for (const auto &Arg : Args.getAllArgValues(OPT_fcoverage_prefix_map_EQ)) {
1697     auto Split = StringRef(Arg).split('=');
1698     Opts.CoveragePrefixMap.emplace_back(Split.first, Split.second);
1699   }
1700 
1701   const llvm::Triple::ArchType DebugEntryValueArchs[] = {
1702       llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::aarch64,
1703       llvm::Triple::arm, llvm::Triple::armeb, llvm::Triple::mips,
1704       llvm::Triple::mipsel, llvm::Triple::mips64, llvm::Triple::mips64el};
1705 
1706   if (Opts.OptimizationLevel > 0 && Opts.hasReducedDebugInfo() &&
1707       llvm::is_contained(DebugEntryValueArchs, T.getArch()))
1708     Opts.EmitCallSiteInfo = true;
1709 
1710   if (!Opts.EnableDIPreservationVerify && Opts.DIBugsReportFilePath.size()) {
1711     Diags.Report(diag::warn_ignoring_verify_debuginfo_preserve_export)
1712         << Opts.DIBugsReportFilePath;
1713     Opts.DIBugsReportFilePath = "";
1714   }
1715 
1716   Opts.NewStructPathTBAA = !Args.hasArg(OPT_no_struct_path_tbaa) &&
1717                            Args.hasArg(OPT_new_struct_path_tbaa);
1718   Opts.OptimizeSize = getOptimizationLevelSize(Args);
1719   Opts.SimplifyLibCalls = !LangOpts->NoBuiltin;
1720   if (Opts.SimplifyLibCalls)
1721     Opts.NoBuiltinFuncs = LangOpts->NoBuiltinFuncs;
1722   Opts.UnrollLoops =
1723       Args.hasFlag(OPT_funroll_loops, OPT_fno_unroll_loops,
1724                    (Opts.OptimizationLevel > 1));
1725   Opts.BinutilsVersion =
1726       std::string(Args.getLastArgValue(OPT_fbinutils_version_EQ));
1727 
1728   Opts.DebugNameTable = static_cast<unsigned>(
1729       Args.hasArg(OPT_ggnu_pubnames)
1730           ? llvm::DICompileUnit::DebugNameTableKind::GNU
1731           : Args.hasArg(OPT_gpubnames)
1732                 ? llvm::DICompileUnit::DebugNameTableKind::Default
1733                 : llvm::DICompileUnit::DebugNameTableKind::None);
1734   if (const Arg *A = Args.getLastArg(OPT_gsimple_template_names_EQ)) {
1735     StringRef Value = A->getValue();
1736     if (Value != "simple" && Value != "mangled")
1737       Diags.Report(diag::err_drv_unsupported_option_argument)
1738           << A->getSpelling() << A->getValue();
1739     Opts.setDebugSimpleTemplateNames(
1740         StringRef(A->getValue()) == "simple"
1741             ? llvm::codegenoptions::DebugTemplateNamesKind::Simple
1742             : llvm::codegenoptions::DebugTemplateNamesKind::Mangled);
1743   }
1744 
1745   if (const Arg *A = Args.getLastArg(OPT_ftime_report, OPT_ftime_report_EQ)) {
1746     Opts.TimePasses = true;
1747 
1748     // -ftime-report= is only for new pass manager.
1749     if (A->getOption().getID() == OPT_ftime_report_EQ) {
1750       StringRef Val = A->getValue();
1751       if (Val == "per-pass")
1752         Opts.TimePassesPerRun = false;
1753       else if (Val == "per-pass-run")
1754         Opts.TimePassesPerRun = true;
1755       else
1756         Diags.Report(diag::err_drv_invalid_value)
1757             << A->getAsString(Args) << A->getValue();
1758     }
1759   }
1760 
1761   Opts.PrepareForLTO = false;
1762   Opts.PrepareForThinLTO = false;
1763   if (Arg *A = Args.getLastArg(OPT_flto_EQ)) {
1764     Opts.PrepareForLTO = true;
1765     StringRef S = A->getValue();
1766     if (S == "thin")
1767       Opts.PrepareForThinLTO = true;
1768     else if (S != "full")
1769       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << S;
1770     if (Args.hasArg(OPT_funified_lto))
1771       Opts.PrepareForThinLTO = true;
1772   }
1773   if (Arg *A = Args.getLastArg(OPT_fthinlto_index_EQ)) {
1774     if (IK.getLanguage() != Language::LLVM_IR)
1775       Diags.Report(diag::err_drv_argument_only_allowed_with)
1776           << A->getAsString(Args) << "-x ir";
1777     Opts.ThinLTOIndexFile =
1778         std::string(Args.getLastArgValue(OPT_fthinlto_index_EQ));
1779   }
1780   if (Arg *A = Args.getLastArg(OPT_save_temps_EQ))
1781     Opts.SaveTempsFilePrefix =
1782         llvm::StringSwitch<std::string>(A->getValue())
1783             .Case("obj", OutputFile)
1784             .Default(llvm::sys::path::filename(OutputFile).str());
1785 
1786   // The memory profile runtime appends the pid to make this name more unique.
1787   const char *MemProfileBasename = "memprof.profraw";
1788   if (Args.hasArg(OPT_fmemory_profile_EQ)) {
1789     SmallString<128> Path(
1790         std::string(Args.getLastArgValue(OPT_fmemory_profile_EQ)));
1791     llvm::sys::path::append(Path, MemProfileBasename);
1792     Opts.MemoryProfileOutput = std::string(Path);
1793   } else if (Args.hasArg(OPT_fmemory_profile))
1794     Opts.MemoryProfileOutput = MemProfileBasename;
1795 
1796   memcpy(Opts.CoverageVersion, "408*", 4);
1797   if (Opts.CoverageNotesFile.size() || Opts.CoverageDataFile.size()) {
1798     if (Args.hasArg(OPT_coverage_version_EQ)) {
1799       StringRef CoverageVersion = Args.getLastArgValue(OPT_coverage_version_EQ);
1800       if (CoverageVersion.size() != 4) {
1801         Diags.Report(diag::err_drv_invalid_value)
1802             << Args.getLastArg(OPT_coverage_version_EQ)->getAsString(Args)
1803             << CoverageVersion;
1804       } else {
1805         memcpy(Opts.CoverageVersion, CoverageVersion.data(), 4);
1806       }
1807     }
1808   }
1809   // FIXME: For backend options that are not yet recorded as function
1810   // attributes in the IR, keep track of them so we can embed them in a
1811   // separate data section and use them when building the bitcode.
1812   for (const auto &A : Args) {
1813     // Do not encode output and input.
1814     if (A->getOption().getID() == options::OPT_o ||
1815         A->getOption().getID() == options::OPT_INPUT ||
1816         A->getOption().getID() == options::OPT_x ||
1817         A->getOption().getID() == options::OPT_fembed_bitcode ||
1818         A->getOption().matches(options::OPT_W_Group))
1819       continue;
1820     ArgStringList ASL;
1821     A->render(Args, ASL);
1822     for (const auto &arg : ASL) {
1823       StringRef ArgStr(arg);
1824       Opts.CmdArgs.insert(Opts.CmdArgs.end(), ArgStr.begin(), ArgStr.end());
1825       // using \00 to separate each commandline options.
1826       Opts.CmdArgs.push_back('\0');
1827     }
1828   }
1829 
1830   auto XRayInstrBundles =
1831       Args.getAllArgValues(OPT_fxray_instrumentation_bundle);
1832   if (XRayInstrBundles.empty())
1833     Opts.XRayInstrumentationBundle.Mask = XRayInstrKind::All;
1834   else
1835     for (const auto &A : XRayInstrBundles)
1836       parseXRayInstrumentationBundle("-fxray-instrumentation-bundle=", A, Args,
1837                                      Diags, Opts.XRayInstrumentationBundle);
1838 
1839   if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
1840     StringRef Name = A->getValue();
1841     if (Name == "full") {
1842       Opts.CFProtectionReturn = 1;
1843       Opts.CFProtectionBranch = 1;
1844     } else if (Name == "return")
1845       Opts.CFProtectionReturn = 1;
1846     else if (Name == "branch")
1847       Opts.CFProtectionBranch = 1;
1848     else if (Name != "none")
1849       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
1850   }
1851 
1852   if (const Arg *A = Args.getLastArg(OPT_mfunction_return_EQ)) {
1853     auto Val = llvm::StringSwitch<llvm::FunctionReturnThunksKind>(A->getValue())
1854                    .Case("keep", llvm::FunctionReturnThunksKind::Keep)
1855                    .Case("thunk-extern", llvm::FunctionReturnThunksKind::Extern)
1856                    .Default(llvm::FunctionReturnThunksKind::Invalid);
1857     // SystemZ might want to add support for "expolines."
1858     if (!T.isX86())
1859       Diags.Report(diag::err_drv_argument_not_allowed_with)
1860           << A->getSpelling() << T.getTriple();
1861     else if (Val == llvm::FunctionReturnThunksKind::Invalid)
1862       Diags.Report(diag::err_drv_invalid_value)
1863           << A->getAsString(Args) << A->getValue();
1864     else if (Val == llvm::FunctionReturnThunksKind::Extern &&
1865              Args.getLastArgValue(OPT_mcmodel_EQ).equals("large"))
1866       Diags.Report(diag::err_drv_argument_not_allowed_with)
1867           << A->getAsString(Args)
1868           << Args.getLastArg(OPT_mcmodel_EQ)->getAsString(Args);
1869     else
1870       Opts.FunctionReturnThunks = static_cast<unsigned>(Val);
1871   }
1872 
1873   for (auto *A :
1874        Args.filtered(OPT_mlink_bitcode_file, OPT_mlink_builtin_bitcode)) {
1875     CodeGenOptions::BitcodeFileToLink F;
1876     F.Filename = A->getValue();
1877     if (A->getOption().matches(OPT_mlink_builtin_bitcode)) {
1878       F.LinkFlags = llvm::Linker::Flags::LinkOnlyNeeded;
1879       // When linking CUDA bitcode, propagate function attributes so that
1880       // e.g. libdevice gets fast-math attrs if we're building with fast-math.
1881       F.PropagateAttrs = true;
1882       F.Internalize = true;
1883     }
1884     Opts.LinkBitcodeFiles.push_back(F);
1885   }
1886 
1887   if (Arg *A = Args.getLastArg(OPT_ftlsmodel_EQ)) {
1888     if (T.isOSAIX()) {
1889       StringRef Name = A->getValue();
1890       if (Name != "global-dynamic" && Name != "local-exec")
1891         Diags.Report(diag::err_aix_unsupported_tls_model) << Name;
1892     }
1893   }
1894 
1895   if (Arg *A = Args.getLastArg(OPT_fdenormal_fp_math_EQ)) {
1896     StringRef Val = A->getValue();
1897     Opts.FPDenormalMode = llvm::parseDenormalFPAttribute(Val);
1898     Opts.FP32DenormalMode = Opts.FPDenormalMode;
1899     if (!Opts.FPDenormalMode.isValid())
1900       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
1901   }
1902 
1903   if (Arg *A = Args.getLastArg(OPT_fdenormal_fp_math_f32_EQ)) {
1904     StringRef Val = A->getValue();
1905     Opts.FP32DenormalMode = llvm::parseDenormalFPAttribute(Val);
1906     if (!Opts.FP32DenormalMode.isValid())
1907       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
1908   }
1909 
1910   // X86_32 has -fppc-struct-return and -freg-struct-return.
1911   // PPC32 has -maix-struct-return and -msvr4-struct-return.
1912   if (Arg *A =
1913           Args.getLastArg(OPT_fpcc_struct_return, OPT_freg_struct_return,
1914                           OPT_maix_struct_return, OPT_msvr4_struct_return)) {
1915     // TODO: We might want to consider enabling these options on AIX in the
1916     // future.
1917     if (T.isOSAIX())
1918       Diags.Report(diag::err_drv_unsupported_opt_for_target)
1919           << A->getSpelling() << T.str();
1920 
1921     const Option &O = A->getOption();
1922     if (O.matches(OPT_fpcc_struct_return) ||
1923         O.matches(OPT_maix_struct_return)) {
1924       Opts.setStructReturnConvention(CodeGenOptions::SRCK_OnStack);
1925     } else {
1926       assert(O.matches(OPT_freg_struct_return) ||
1927              O.matches(OPT_msvr4_struct_return));
1928       Opts.setStructReturnConvention(CodeGenOptions::SRCK_InRegs);
1929     }
1930   }
1931 
1932   if (Arg *A = Args.getLastArg(OPT_mxcoff_roptr)) {
1933     if (!T.isOSAIX())
1934       Diags.Report(diag::err_drv_unsupported_opt_for_target)
1935           << A->getSpelling() << T.str();
1936 
1937     // Since the storage mapping class is specified per csect,
1938     // without using data sections, it is less effective to use read-only
1939     // pointers. Using read-only pointers may cause other RO variables in the
1940     // same csect to become RW when the linker acts upon `-bforceimprw`;
1941     // therefore, we require that separate data sections
1942     // are used when `-mxcoff-roptr` is in effect. We respect the setting of
1943     // data-sections since we have not found reasons to do otherwise that
1944     // overcome the user surprise of not respecting the setting.
1945     if (!Args.hasFlag(OPT_fdata_sections, OPT_fno_data_sections, false))
1946       Diags.Report(diag::err_roptr_requires_data_sections);
1947 
1948     Opts.XCOFFReadOnlyPointers = true;
1949   }
1950 
1951   if (Arg *A = Args.getLastArg(OPT_mabi_EQ_quadword_atomics)) {
1952     if (!T.isOSAIX() || T.isPPC32())
1953       Diags.Report(diag::err_drv_unsupported_opt_for_target)
1954         << A->getSpelling() << T.str();
1955   }
1956 
1957   bool NeedLocTracking = false;
1958 
1959   if (!Opts.OptRecordFile.empty())
1960     NeedLocTracking = true;
1961 
1962   if (Arg *A = Args.getLastArg(OPT_opt_record_passes)) {
1963     Opts.OptRecordPasses = A->getValue();
1964     NeedLocTracking = true;
1965   }
1966 
1967   if (Arg *A = Args.getLastArg(OPT_opt_record_format)) {
1968     Opts.OptRecordFormat = A->getValue();
1969     NeedLocTracking = true;
1970   }
1971 
1972   Opts.OptimizationRemark =
1973       ParseOptimizationRemark(Diags, Args, OPT_Rpass_EQ, "pass");
1974 
1975   Opts.OptimizationRemarkMissed =
1976       ParseOptimizationRemark(Diags, Args, OPT_Rpass_missed_EQ, "pass-missed");
1977 
1978   Opts.OptimizationRemarkAnalysis = ParseOptimizationRemark(
1979       Diags, Args, OPT_Rpass_analysis_EQ, "pass-analysis");
1980 
1981   NeedLocTracking |= Opts.OptimizationRemark.hasValidPattern() ||
1982                      Opts.OptimizationRemarkMissed.hasValidPattern() ||
1983                      Opts.OptimizationRemarkAnalysis.hasValidPattern();
1984 
1985   bool UsingSampleProfile = !Opts.SampleProfileFile.empty();
1986   bool UsingProfile =
1987       UsingSampleProfile || !Opts.ProfileInstrumentUsePath.empty();
1988 
1989   if (Opts.DiagnosticsWithHotness && !UsingProfile &&
1990       // An IR file will contain PGO as metadata
1991       IK.getLanguage() != Language::LLVM_IR)
1992     Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo)
1993         << "-fdiagnostics-show-hotness";
1994 
1995   // Parse remarks hotness threshold. Valid value is either integer or 'auto'.
1996   if (auto *arg =
1997           Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
1998     auto ResultOrErr =
1999         llvm::remarks::parseHotnessThresholdOption(arg->getValue());
2000 
2001     if (!ResultOrErr) {
2002       Diags.Report(diag::err_drv_invalid_diagnotics_hotness_threshold)
2003           << "-fdiagnostics-hotness-threshold=";
2004     } else {
2005       Opts.DiagnosticsHotnessThreshold = *ResultOrErr;
2006       if ((!Opts.DiagnosticsHotnessThreshold ||
2007            *Opts.DiagnosticsHotnessThreshold > 0) &&
2008           !UsingProfile)
2009         Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo)
2010             << "-fdiagnostics-hotness-threshold=";
2011     }
2012   }
2013 
2014   if (auto *arg =
2015           Args.getLastArg(options::OPT_fdiagnostics_misexpect_tolerance_EQ)) {
2016     auto ResultOrErr = parseToleranceOption(arg->getValue());
2017 
2018     if (!ResultOrErr) {
2019       Diags.Report(diag::err_drv_invalid_diagnotics_misexpect_tolerance)
2020           << "-fdiagnostics-misexpect-tolerance=";
2021     } else {
2022       Opts.DiagnosticsMisExpectTolerance = *ResultOrErr;
2023       if ((!Opts.DiagnosticsMisExpectTolerance ||
2024            *Opts.DiagnosticsMisExpectTolerance > 0) &&
2025           !UsingProfile)
2026         Diags.Report(diag::warn_drv_diagnostics_misexpect_requires_pgo)
2027             << "-fdiagnostics-misexpect-tolerance=";
2028     }
2029   }
2030 
2031   // If the user requested to use a sample profile for PGO, then the
2032   // backend will need to track source location information so the profile
2033   // can be incorporated into the IR.
2034   if (UsingSampleProfile)
2035     NeedLocTracking = true;
2036 
2037   if (!Opts.StackUsageOutput.empty())
2038     NeedLocTracking = true;
2039 
2040   // If the user requested a flag that requires source locations available in
2041   // the backend, make sure that the backend tracks source location information.
2042   if (NeedLocTracking &&
2043       Opts.getDebugInfo() == llvm::codegenoptions::NoDebugInfo)
2044     Opts.setDebugInfo(llvm::codegenoptions::LocTrackingOnly);
2045 
2046   // Parse -fsanitize-recover= arguments.
2047   // FIXME: Report unrecoverable sanitizers incorrectly specified here.
2048   parseSanitizerKinds("-fsanitize-recover=",
2049                       Args.getAllArgValues(OPT_fsanitize_recover_EQ), Diags,
2050                       Opts.SanitizeRecover);
2051   parseSanitizerKinds("-fsanitize-trap=",
2052                       Args.getAllArgValues(OPT_fsanitize_trap_EQ), Diags,
2053                       Opts.SanitizeTrap);
2054 
2055   Opts.EmitVersionIdentMetadata = Args.hasFlag(OPT_Qy, OPT_Qn, true);
2056 
2057   if (Args.hasArg(options::OPT_ffinite_loops))
2058     Opts.FiniteLoops = CodeGenOptions::FiniteLoopsKind::Always;
2059   else if (Args.hasArg(options::OPT_fno_finite_loops))
2060     Opts.FiniteLoops = CodeGenOptions::FiniteLoopsKind::Never;
2061 
2062   Opts.EmitIEEENaNCompliantInsts = Args.hasFlag(
2063       options::OPT_mamdgpu_ieee, options::OPT_mno_amdgpu_ieee, true);
2064   if (!Opts.EmitIEEENaNCompliantInsts && !LangOptsRef.NoHonorNaNs)
2065     Diags.Report(diag::err_drv_amdgpu_ieee_without_no_honor_nans);
2066 
2067   return Diags.getNumErrors() == NumErrorsBefore;
2068 }
2069 
2070 static void
2071 GenerateDependencyOutputArgs(const DependencyOutputOptions &Opts,
2072                              SmallVectorImpl<const char *> &Args,
2073                              CompilerInvocation::StringAllocator SA) {
2074   const DependencyOutputOptions &DependencyOutputOpts = Opts;
2075 #define DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING(...)                         \
2076   GENERATE_OPTION_WITH_MARSHALLING(Args, SA, __VA_ARGS__)
2077 #include "clang/Driver/Options.inc"
2078 #undef DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING
2079 
2080   if (Opts.ShowIncludesDest != ShowIncludesDestination::None)
2081     GenerateArg(Args, OPT_show_includes, SA);
2082 
2083   for (const auto &Dep : Opts.ExtraDeps) {
2084     switch (Dep.second) {
2085     case EDK_SanitizeIgnorelist:
2086       // Sanitizer ignorelist arguments are generated from LanguageOptions.
2087       continue;
2088     case EDK_ModuleFile:
2089       // Module file arguments are generated from FrontendOptions and
2090       // HeaderSearchOptions.
2091       continue;
2092     case EDK_ProfileList:
2093       // Profile list arguments are generated from LanguageOptions via the
2094       // marshalling infrastructure.
2095       continue;
2096     case EDK_DepFileEntry:
2097       GenerateArg(Args, OPT_fdepfile_entry, Dep.first, SA);
2098       break;
2099     }
2100   }
2101 }
2102 
2103 static bool ParseDependencyOutputArgs(DependencyOutputOptions &Opts,
2104                                       ArgList &Args, DiagnosticsEngine &Diags,
2105                                       frontend::ActionKind Action,
2106                                       bool ShowLineMarkers) {
2107   unsigned NumErrorsBefore = Diags.getNumErrors();
2108 
2109   DependencyOutputOptions &DependencyOutputOpts = Opts;
2110 #define DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING(...)                         \
2111   PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
2112 #include "clang/Driver/Options.inc"
2113 #undef DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING
2114 
2115   if (Args.hasArg(OPT_show_includes)) {
2116     // Writing both /showIncludes and preprocessor output to stdout
2117     // would produce interleaved output, so use stderr for /showIncludes.
2118     // This behaves the same as cl.exe, when /E, /EP or /P are passed.
2119     if (Action == frontend::PrintPreprocessedInput || !ShowLineMarkers)
2120       Opts.ShowIncludesDest = ShowIncludesDestination::Stderr;
2121     else
2122       Opts.ShowIncludesDest = ShowIncludesDestination::Stdout;
2123   } else {
2124     Opts.ShowIncludesDest = ShowIncludesDestination::None;
2125   }
2126 
2127   // Add sanitizer ignorelists as extra dependencies.
2128   // They won't be discovered by the regular preprocessor, so
2129   // we let make / ninja to know about this implicit dependency.
2130   if (!Args.hasArg(OPT_fno_sanitize_ignorelist)) {
2131     for (const auto *A : Args.filtered(OPT_fsanitize_ignorelist_EQ)) {
2132       StringRef Val = A->getValue();
2133       if (!Val.contains('='))
2134         Opts.ExtraDeps.emplace_back(std::string(Val), EDK_SanitizeIgnorelist);
2135     }
2136     if (Opts.IncludeSystemHeaders) {
2137       for (const auto *A : Args.filtered(OPT_fsanitize_system_ignorelist_EQ)) {
2138         StringRef Val = A->getValue();
2139         if (!Val.contains('='))
2140           Opts.ExtraDeps.emplace_back(std::string(Val), EDK_SanitizeIgnorelist);
2141       }
2142     }
2143   }
2144 
2145   // -fprofile-list= dependencies.
2146   for (const auto &Filename : Args.getAllArgValues(OPT_fprofile_list_EQ))
2147     Opts.ExtraDeps.emplace_back(Filename, EDK_ProfileList);
2148 
2149   // Propagate the extra dependencies.
2150   for (const auto *A : Args.filtered(OPT_fdepfile_entry))
2151     Opts.ExtraDeps.emplace_back(A->getValue(), EDK_DepFileEntry);
2152 
2153   // Only the -fmodule-file=<file> form.
2154   for (const auto *A : Args.filtered(OPT_fmodule_file)) {
2155     StringRef Val = A->getValue();
2156     if (!Val.contains('='))
2157       Opts.ExtraDeps.emplace_back(std::string(Val), EDK_ModuleFile);
2158   }
2159 
2160   // Check for invalid combinations of header-include-format
2161   // and header-include-filtering.
2162   if ((Opts.HeaderIncludeFormat == HIFMT_Textual &&
2163        Opts.HeaderIncludeFiltering != HIFIL_None) ||
2164       (Opts.HeaderIncludeFormat == HIFMT_JSON &&
2165        Opts.HeaderIncludeFiltering != HIFIL_Only_Direct_System))
2166     Diags.Report(diag::err_drv_print_header_env_var_combination_cc1)
2167         << Args.getLastArg(OPT_header_include_format_EQ)->getValue()
2168         << Args.getLastArg(OPT_header_include_filtering_EQ)->getValue();
2169 
2170   return Diags.getNumErrors() == NumErrorsBefore;
2171 }
2172 
2173 static bool parseShowColorsArgs(const ArgList &Args, bool DefaultColor) {
2174   // Color diagnostics default to auto ("on" if terminal supports) in the driver
2175   // but default to off in cc1, needing an explicit OPT_fdiagnostics_color.
2176   // Support both clang's -f[no-]color-diagnostics and gcc's
2177   // -f[no-]diagnostics-colors[=never|always|auto].
2178   enum {
2179     Colors_On,
2180     Colors_Off,
2181     Colors_Auto
2182   } ShowColors = DefaultColor ? Colors_Auto : Colors_Off;
2183   for (auto *A : Args) {
2184     const Option &O = A->getOption();
2185     if (O.matches(options::OPT_fcolor_diagnostics)) {
2186       ShowColors = Colors_On;
2187     } else if (O.matches(options::OPT_fno_color_diagnostics)) {
2188       ShowColors = Colors_Off;
2189     } else if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
2190       StringRef Value(A->getValue());
2191       if (Value == "always")
2192         ShowColors = Colors_On;
2193       else if (Value == "never")
2194         ShowColors = Colors_Off;
2195       else if (Value == "auto")
2196         ShowColors = Colors_Auto;
2197     }
2198   }
2199   return ShowColors == Colors_On ||
2200          (ShowColors == Colors_Auto &&
2201           llvm::sys::Process::StandardErrHasColors());
2202 }
2203 
2204 static bool checkVerifyPrefixes(const std::vector<std::string> &VerifyPrefixes,
2205                                 DiagnosticsEngine &Diags) {
2206   bool Success = true;
2207   for (const auto &Prefix : VerifyPrefixes) {
2208     // Every prefix must start with a letter and contain only alphanumeric
2209     // characters, hyphens, and underscores.
2210     auto BadChar = llvm::find_if(Prefix, [](char C) {
2211       return !isAlphanumeric(C) && C != '-' && C != '_';
2212     });
2213     if (BadChar != Prefix.end() || !isLetter(Prefix[0])) {
2214       Success = false;
2215       Diags.Report(diag::err_drv_invalid_value) << "-verify=" << Prefix;
2216       Diags.Report(diag::note_drv_verify_prefix_spelling);
2217     }
2218   }
2219   return Success;
2220 }
2221 
2222 static void GenerateFileSystemArgs(const FileSystemOptions &Opts,
2223                                    SmallVectorImpl<const char *> &Args,
2224                                    CompilerInvocation::StringAllocator SA) {
2225   const FileSystemOptions &FileSystemOpts = Opts;
2226 
2227 #define FILE_SYSTEM_OPTION_WITH_MARSHALLING(...)                               \
2228   GENERATE_OPTION_WITH_MARSHALLING(Args, SA, __VA_ARGS__)
2229 #include "clang/Driver/Options.inc"
2230 #undef FILE_SYSTEM_OPTION_WITH_MARSHALLING
2231 }
2232 
2233 static bool ParseFileSystemArgs(FileSystemOptions &Opts, const ArgList &Args,
2234                                 DiagnosticsEngine &Diags) {
2235   unsigned NumErrorsBefore = Diags.getNumErrors();
2236 
2237   FileSystemOptions &FileSystemOpts = Opts;
2238 
2239 #define FILE_SYSTEM_OPTION_WITH_MARSHALLING(...)                               \
2240   PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
2241 #include "clang/Driver/Options.inc"
2242 #undef FILE_SYSTEM_OPTION_WITH_MARSHALLING
2243 
2244   return Diags.getNumErrors() == NumErrorsBefore;
2245 }
2246 
2247 static void GenerateMigratorArgs(const MigratorOptions &Opts,
2248                                  SmallVectorImpl<const char *> &Args,
2249                                  CompilerInvocation::StringAllocator SA) {
2250   const MigratorOptions &MigratorOpts = Opts;
2251 #define MIGRATOR_OPTION_WITH_MARSHALLING(...)                                  \
2252   GENERATE_OPTION_WITH_MARSHALLING(Args, SA, __VA_ARGS__)
2253 #include "clang/Driver/Options.inc"
2254 #undef MIGRATOR_OPTION_WITH_MARSHALLING
2255 }
2256 
2257 static bool ParseMigratorArgs(MigratorOptions &Opts, const ArgList &Args,
2258                               DiagnosticsEngine &Diags) {
2259   unsigned NumErrorsBefore = Diags.getNumErrors();
2260 
2261   MigratorOptions &MigratorOpts = Opts;
2262 
2263 #define MIGRATOR_OPTION_WITH_MARSHALLING(...)                                  \
2264   PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
2265 #include "clang/Driver/Options.inc"
2266 #undef MIGRATOR_OPTION_WITH_MARSHALLING
2267 
2268   return Diags.getNumErrors() == NumErrorsBefore;
2269 }
2270 
2271 void CompilerInvocation::GenerateDiagnosticArgs(
2272     const DiagnosticOptions &Opts, SmallVectorImpl<const char *> &Args,
2273     StringAllocator SA, bool DefaultDiagColor) {
2274   const DiagnosticOptions *DiagnosticOpts = &Opts;
2275 #define DIAG_OPTION_WITH_MARSHALLING(...)                                      \
2276   GENERATE_OPTION_WITH_MARSHALLING(Args, SA, __VA_ARGS__)
2277 #include "clang/Driver/Options.inc"
2278 #undef DIAG_OPTION_WITH_MARSHALLING
2279 
2280   if (!Opts.DiagnosticSerializationFile.empty())
2281     GenerateArg(Args, OPT_diagnostic_serialized_file,
2282                 Opts.DiagnosticSerializationFile, SA);
2283 
2284   if (Opts.ShowColors)
2285     GenerateArg(Args, OPT_fcolor_diagnostics, SA);
2286 
2287   if (Opts.VerifyDiagnostics &&
2288       llvm::is_contained(Opts.VerifyPrefixes, "expected"))
2289     GenerateArg(Args, OPT_verify, SA);
2290 
2291   for (const auto &Prefix : Opts.VerifyPrefixes)
2292     if (Prefix != "expected")
2293       GenerateArg(Args, OPT_verify_EQ, Prefix, SA);
2294 
2295   DiagnosticLevelMask VIU = Opts.getVerifyIgnoreUnexpected();
2296   if (VIU == DiagnosticLevelMask::None) {
2297     // This is the default, don't generate anything.
2298   } else if (VIU == DiagnosticLevelMask::All) {
2299     GenerateArg(Args, OPT_verify_ignore_unexpected, SA);
2300   } else {
2301     if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Note) != 0)
2302       GenerateArg(Args, OPT_verify_ignore_unexpected_EQ, "note", SA);
2303     if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Remark) != 0)
2304       GenerateArg(Args, OPT_verify_ignore_unexpected_EQ, "remark", SA);
2305     if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Warning) != 0)
2306       GenerateArg(Args, OPT_verify_ignore_unexpected_EQ, "warning", SA);
2307     if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Error) != 0)
2308       GenerateArg(Args, OPT_verify_ignore_unexpected_EQ, "error", SA);
2309   }
2310 
2311   for (const auto &Warning : Opts.Warnings) {
2312     // This option is automatically generated from UndefPrefixes.
2313     if (Warning == "undef-prefix")
2314       continue;
2315     Args.push_back(SA(StringRef("-W") + Warning));
2316   }
2317 
2318   for (const auto &Remark : Opts.Remarks) {
2319     // These arguments are generated from OptimizationRemark fields of
2320     // CodeGenOptions.
2321     StringRef IgnoredRemarks[] = {"pass",          "no-pass",
2322                                   "pass-analysis", "no-pass-analysis",
2323                                   "pass-missed",   "no-pass-missed"};
2324     if (llvm::is_contained(IgnoredRemarks, Remark))
2325       continue;
2326 
2327     Args.push_back(SA(StringRef("-R") + Remark));
2328   }
2329 }
2330 
2331 std::unique_ptr<DiagnosticOptions>
2332 clang::CreateAndPopulateDiagOpts(ArrayRef<const char *> Argv) {
2333   auto DiagOpts = std::make_unique<DiagnosticOptions>();
2334   unsigned MissingArgIndex, MissingArgCount;
2335   InputArgList Args = getDriverOptTable().ParseArgs(
2336       Argv.slice(1), MissingArgIndex, MissingArgCount);
2337 
2338   bool ShowColors = true;
2339   if (std::optional<std::string> NoColor =
2340           llvm::sys::Process::GetEnv("NO_COLOR");
2341       NoColor && !NoColor->empty()) {
2342     // If the user set the NO_COLOR environment variable, we'll honor that
2343     // unless the command line overrides it.
2344     ShowColors = false;
2345   }
2346 
2347   // We ignore MissingArgCount and the return value of ParseDiagnosticArgs.
2348   // Any errors that would be diagnosed here will also be diagnosed later,
2349   // when the DiagnosticsEngine actually exists.
2350   (void)ParseDiagnosticArgs(*DiagOpts, Args, /*Diags=*/nullptr, ShowColors);
2351   return DiagOpts;
2352 }
2353 
2354 bool clang::ParseDiagnosticArgs(DiagnosticOptions &Opts, ArgList &Args,
2355                                 DiagnosticsEngine *Diags,
2356                                 bool DefaultDiagColor) {
2357   std::optional<DiagnosticsEngine> IgnoringDiags;
2358   if (!Diags) {
2359     IgnoringDiags.emplace(new DiagnosticIDs(), new DiagnosticOptions(),
2360                           new IgnoringDiagConsumer());
2361     Diags = &*IgnoringDiags;
2362   }
2363 
2364   unsigned NumErrorsBefore = Diags->getNumErrors();
2365 
2366   // The key paths of diagnostic options defined in Options.td start with
2367   // "DiagnosticOpts->". Let's provide the expected variable name and type.
2368   DiagnosticOptions *DiagnosticOpts = &Opts;
2369 
2370 #define DIAG_OPTION_WITH_MARSHALLING(...)                                      \
2371   PARSE_OPTION_WITH_MARSHALLING(Args, *Diags, __VA_ARGS__)
2372 #include "clang/Driver/Options.inc"
2373 #undef DIAG_OPTION_WITH_MARSHALLING
2374 
2375   llvm::sys::Process::UseANSIEscapeCodes(Opts.UseANSIEscapeCodes);
2376 
2377   if (Arg *A =
2378           Args.getLastArg(OPT_diagnostic_serialized_file, OPT__serialize_diags))
2379     Opts.DiagnosticSerializationFile = A->getValue();
2380   Opts.ShowColors = parseShowColorsArgs(Args, DefaultDiagColor);
2381 
2382   Opts.VerifyDiagnostics = Args.hasArg(OPT_verify) || Args.hasArg(OPT_verify_EQ);
2383   Opts.VerifyPrefixes = Args.getAllArgValues(OPT_verify_EQ);
2384   if (Args.hasArg(OPT_verify))
2385     Opts.VerifyPrefixes.push_back("expected");
2386   // Keep VerifyPrefixes in its original order for the sake of diagnostics, and
2387   // then sort it to prepare for fast lookup using std::binary_search.
2388   if (!checkVerifyPrefixes(Opts.VerifyPrefixes, *Diags))
2389     Opts.VerifyDiagnostics = false;
2390   else
2391     llvm::sort(Opts.VerifyPrefixes);
2392   DiagnosticLevelMask DiagMask = DiagnosticLevelMask::None;
2393   parseDiagnosticLevelMask(
2394       "-verify-ignore-unexpected=",
2395       Args.getAllArgValues(OPT_verify_ignore_unexpected_EQ), *Diags, DiagMask);
2396   if (Args.hasArg(OPT_verify_ignore_unexpected))
2397     DiagMask = DiagnosticLevelMask::All;
2398   Opts.setVerifyIgnoreUnexpected(DiagMask);
2399   if (Opts.TabStop == 0 || Opts.TabStop > DiagnosticOptions::MaxTabStop) {
2400     Diags->Report(diag::warn_ignoring_ftabstop_value)
2401         << Opts.TabStop << DiagnosticOptions::DefaultTabStop;
2402     Opts.TabStop = DiagnosticOptions::DefaultTabStop;
2403   }
2404 
2405   addDiagnosticArgs(Args, OPT_W_Group, OPT_W_value_Group, Opts.Warnings);
2406   addDiagnosticArgs(Args, OPT_R_Group, OPT_R_value_Group, Opts.Remarks);
2407 
2408   return Diags->getNumErrors() == NumErrorsBefore;
2409 }
2410 
2411 /// Parse the argument to the -ftest-module-file-extension
2412 /// command-line argument.
2413 ///
2414 /// \returns true on error, false on success.
2415 static bool parseTestModuleFileExtensionArg(StringRef Arg,
2416                                             std::string &BlockName,
2417                                             unsigned &MajorVersion,
2418                                             unsigned &MinorVersion,
2419                                             bool &Hashed,
2420                                             std::string &UserInfo) {
2421   SmallVector<StringRef, 5> Args;
2422   Arg.split(Args, ':', 5);
2423   if (Args.size() < 5)
2424     return true;
2425 
2426   BlockName = std::string(Args[0]);
2427   if (Args[1].getAsInteger(10, MajorVersion)) return true;
2428   if (Args[2].getAsInteger(10, MinorVersion)) return true;
2429   if (Args[3].getAsInteger(2, Hashed)) return true;
2430   if (Args.size() > 4)
2431     UserInfo = std::string(Args[4]);
2432   return false;
2433 }
2434 
2435 /// Return a table that associates command line option specifiers with the
2436 /// frontend action. Note: The pair {frontend::PluginAction, OPT_plugin} is
2437 /// intentionally missing, as this case is handled separately from other
2438 /// frontend options.
2439 static const auto &getFrontendActionTable() {
2440   static const std::pair<frontend::ActionKind, unsigned> Table[] = {
2441       {frontend::ASTDeclList, OPT_ast_list},
2442 
2443       {frontend::ASTDump, OPT_ast_dump_all_EQ},
2444       {frontend::ASTDump, OPT_ast_dump_all},
2445       {frontend::ASTDump, OPT_ast_dump_EQ},
2446       {frontend::ASTDump, OPT_ast_dump},
2447       {frontend::ASTDump, OPT_ast_dump_lookups},
2448       {frontend::ASTDump, OPT_ast_dump_decl_types},
2449 
2450       {frontend::ASTPrint, OPT_ast_print},
2451       {frontend::ASTView, OPT_ast_view},
2452       {frontend::DumpCompilerOptions, OPT_compiler_options_dump},
2453       {frontend::DumpRawTokens, OPT_dump_raw_tokens},
2454       {frontend::DumpTokens, OPT_dump_tokens},
2455       {frontend::EmitAssembly, OPT_S},
2456       {frontend::EmitBC, OPT_emit_llvm_bc},
2457       {frontend::EmitHTML, OPT_emit_html},
2458       {frontend::EmitLLVM, OPT_emit_llvm},
2459       {frontend::EmitLLVMOnly, OPT_emit_llvm_only},
2460       {frontend::EmitCodeGenOnly, OPT_emit_codegen_only},
2461       {frontend::EmitObj, OPT_emit_obj},
2462       {frontend::ExtractAPI, OPT_extract_api},
2463 
2464       {frontend::FixIt, OPT_fixit_EQ},
2465       {frontend::FixIt, OPT_fixit},
2466 
2467       {frontend::GenerateModule, OPT_emit_module},
2468       {frontend::GenerateModuleInterface, OPT_emit_module_interface},
2469       {frontend::GenerateHeaderUnit, OPT_emit_header_unit},
2470       {frontend::GeneratePCH, OPT_emit_pch},
2471       {frontend::GenerateInterfaceStubs, OPT_emit_interface_stubs},
2472       {frontend::InitOnly, OPT_init_only},
2473       {frontend::ParseSyntaxOnly, OPT_fsyntax_only},
2474       {frontend::ModuleFileInfo, OPT_module_file_info},
2475       {frontend::VerifyPCH, OPT_verify_pch},
2476       {frontend::PrintPreamble, OPT_print_preamble},
2477       {frontend::PrintPreprocessedInput, OPT_E},
2478       {frontend::TemplightDump, OPT_templight_dump},
2479       {frontend::RewriteMacros, OPT_rewrite_macros},
2480       {frontend::RewriteObjC, OPT_rewrite_objc},
2481       {frontend::RewriteTest, OPT_rewrite_test},
2482       {frontend::RunAnalysis, OPT_analyze},
2483       {frontend::MigrateSource, OPT_migrate},
2484       {frontend::RunPreprocessorOnly, OPT_Eonly},
2485       {frontend::PrintDependencyDirectivesSourceMinimizerOutput,
2486        OPT_print_dependency_directives_minimized_source},
2487   };
2488 
2489   return Table;
2490 }
2491 
2492 /// Maps command line option to frontend action.
2493 static std::optional<frontend::ActionKind>
2494 getFrontendAction(OptSpecifier &Opt) {
2495   for (const auto &ActionOpt : getFrontendActionTable())
2496     if (ActionOpt.second == Opt.getID())
2497       return ActionOpt.first;
2498 
2499   return std::nullopt;
2500 }
2501 
2502 /// Maps frontend action to command line option.
2503 static std::optional<OptSpecifier>
2504 getProgramActionOpt(frontend::ActionKind ProgramAction) {
2505   for (const auto &ActionOpt : getFrontendActionTable())
2506     if (ActionOpt.first == ProgramAction)
2507       return OptSpecifier(ActionOpt.second);
2508 
2509   return std::nullopt;
2510 }
2511 
2512 static void GenerateFrontendArgs(const FrontendOptions &Opts,
2513                                  SmallVectorImpl<const char *> &Args,
2514                                  CompilerInvocation::StringAllocator SA,
2515                                  bool IsHeader) {
2516   const FrontendOptions &FrontendOpts = Opts;
2517 #define FRONTEND_OPTION_WITH_MARSHALLING(...)                                  \
2518   GENERATE_OPTION_WITH_MARSHALLING(Args, SA, __VA_ARGS__)
2519 #include "clang/Driver/Options.inc"
2520 #undef FRONTEND_OPTION_WITH_MARSHALLING
2521 
2522   std::optional<OptSpecifier> ProgramActionOpt =
2523       getProgramActionOpt(Opts.ProgramAction);
2524 
2525   // Generating a simple flag covers most frontend actions.
2526   std::function<void()> GenerateProgramAction = [&]() {
2527     GenerateArg(Args, *ProgramActionOpt, SA);
2528   };
2529 
2530   if (!ProgramActionOpt) {
2531     // PluginAction is the only program action handled separately.
2532     assert(Opts.ProgramAction == frontend::PluginAction &&
2533            "Frontend action without option.");
2534     GenerateProgramAction = [&]() {
2535       GenerateArg(Args, OPT_plugin, Opts.ActionName, SA);
2536     };
2537   }
2538 
2539   // FIXME: Simplify the complex 'AST dump' command line.
2540   if (Opts.ProgramAction == frontend::ASTDump) {
2541     GenerateProgramAction = [&]() {
2542       // ASTDumpLookups, ASTDumpDeclTypes and ASTDumpFilter are generated via
2543       // marshalling infrastructure.
2544 
2545       if (Opts.ASTDumpFormat != ADOF_Default) {
2546         StringRef Format;
2547         switch (Opts.ASTDumpFormat) {
2548         case ADOF_Default:
2549           llvm_unreachable("Default AST dump format.");
2550         case ADOF_JSON:
2551           Format = "json";
2552           break;
2553         }
2554 
2555         if (Opts.ASTDumpAll)
2556           GenerateArg(Args, OPT_ast_dump_all_EQ, Format, SA);
2557         if (Opts.ASTDumpDecls)
2558           GenerateArg(Args, OPT_ast_dump_EQ, Format, SA);
2559       } else {
2560         if (Opts.ASTDumpAll)
2561           GenerateArg(Args, OPT_ast_dump_all, SA);
2562         if (Opts.ASTDumpDecls)
2563           GenerateArg(Args, OPT_ast_dump, SA);
2564       }
2565     };
2566   }
2567 
2568   if (Opts.ProgramAction == frontend::FixIt && !Opts.FixItSuffix.empty()) {
2569     GenerateProgramAction = [&]() {
2570       GenerateArg(Args, OPT_fixit_EQ, Opts.FixItSuffix, SA);
2571     };
2572   }
2573 
2574   GenerateProgramAction();
2575 
2576   for (const auto &PluginArgs : Opts.PluginArgs) {
2577     Option Opt = getDriverOptTable().getOption(OPT_plugin_arg);
2578     const char *Spelling =
2579         SA(Opt.getPrefix() + Opt.getName() + PluginArgs.first);
2580     for (const auto &PluginArg : PluginArgs.second)
2581       denormalizeString(Args, Spelling, SA, Opt.getKind(), 0, PluginArg);
2582   }
2583 
2584   for (const auto &Ext : Opts.ModuleFileExtensions)
2585     if (auto *TestExt = dyn_cast_or_null<TestModuleFileExtension>(Ext.get()))
2586       GenerateArg(Args, OPT_ftest_module_file_extension_EQ, TestExt->str(), SA);
2587 
2588   if (!Opts.CodeCompletionAt.FileName.empty())
2589     GenerateArg(Args, OPT_code_completion_at, Opts.CodeCompletionAt.ToString(),
2590                 SA);
2591 
2592   for (const auto &Plugin : Opts.Plugins)
2593     GenerateArg(Args, OPT_load, Plugin, SA);
2594 
2595   // ASTDumpDecls and ASTDumpAll already handled with ProgramAction.
2596 
2597   for (const auto &ModuleFile : Opts.ModuleFiles)
2598     GenerateArg(Args, OPT_fmodule_file, ModuleFile, SA);
2599 
2600   if (Opts.AuxTargetCPU)
2601     GenerateArg(Args, OPT_aux_target_cpu, *Opts.AuxTargetCPU, SA);
2602 
2603   if (Opts.AuxTargetFeatures)
2604     for (const auto &Feature : *Opts.AuxTargetFeatures)
2605       GenerateArg(Args, OPT_aux_target_feature, Feature, SA);
2606 
2607   {
2608     StringRef Preprocessed = Opts.DashX.isPreprocessed() ? "-cpp-output" : "";
2609     StringRef ModuleMap =
2610         Opts.DashX.getFormat() == InputKind::ModuleMap ? "-module-map" : "";
2611     StringRef HeaderUnit = "";
2612     switch (Opts.DashX.getHeaderUnitKind()) {
2613     case InputKind::HeaderUnit_None:
2614       break;
2615     case InputKind::HeaderUnit_User:
2616       HeaderUnit = "-user";
2617       break;
2618     case InputKind::HeaderUnit_System:
2619       HeaderUnit = "-system";
2620       break;
2621     case InputKind::HeaderUnit_Abs:
2622       HeaderUnit = "-header-unit";
2623       break;
2624     }
2625     StringRef Header = IsHeader ? "-header" : "";
2626 
2627     StringRef Lang;
2628     switch (Opts.DashX.getLanguage()) {
2629     case Language::C:
2630       Lang = "c";
2631       break;
2632     case Language::OpenCL:
2633       Lang = "cl";
2634       break;
2635     case Language::OpenCLCXX:
2636       Lang = "clcpp";
2637       break;
2638     case Language::CUDA:
2639       Lang = "cuda";
2640       break;
2641     case Language::HIP:
2642       Lang = "hip";
2643       break;
2644     case Language::CXX:
2645       Lang = "c++";
2646       break;
2647     case Language::ObjC:
2648       Lang = "objective-c";
2649       break;
2650     case Language::ObjCXX:
2651       Lang = "objective-c++";
2652       break;
2653     case Language::RenderScript:
2654       Lang = "renderscript";
2655       break;
2656     case Language::Asm:
2657       Lang = "assembler-with-cpp";
2658       break;
2659     case Language::Unknown:
2660       assert(Opts.DashX.getFormat() == InputKind::Precompiled &&
2661              "Generating -x argument for unknown language (not precompiled).");
2662       Lang = "ast";
2663       break;
2664     case Language::LLVM_IR:
2665       Lang = "ir";
2666       break;
2667     case Language::HLSL:
2668       Lang = "hlsl";
2669       break;
2670     }
2671 
2672     GenerateArg(Args, OPT_x,
2673                 Lang + HeaderUnit + Header + ModuleMap + Preprocessed, SA);
2674   }
2675 
2676   // OPT_INPUT has a unique class, generate it directly.
2677   for (const auto &Input : Opts.Inputs)
2678     Args.push_back(SA(Input.getFile()));
2679 }
2680 
2681 static bool ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args,
2682                               DiagnosticsEngine &Diags, bool &IsHeaderFile) {
2683   unsigned NumErrorsBefore = Diags.getNumErrors();
2684 
2685   FrontendOptions &FrontendOpts = Opts;
2686 
2687 #define FRONTEND_OPTION_WITH_MARSHALLING(...)                                  \
2688   PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
2689 #include "clang/Driver/Options.inc"
2690 #undef FRONTEND_OPTION_WITH_MARSHALLING
2691 
2692   Opts.ProgramAction = frontend::ParseSyntaxOnly;
2693   if (const Arg *A = Args.getLastArg(OPT_Action_Group)) {
2694     OptSpecifier Opt = OptSpecifier(A->getOption().getID());
2695     std::optional<frontend::ActionKind> ProgramAction = getFrontendAction(Opt);
2696     assert(ProgramAction && "Option specifier not in Action_Group.");
2697 
2698     if (ProgramAction == frontend::ASTDump &&
2699         (Opt == OPT_ast_dump_all_EQ || Opt == OPT_ast_dump_EQ)) {
2700       unsigned Val = llvm::StringSwitch<unsigned>(A->getValue())
2701                          .CaseLower("default", ADOF_Default)
2702                          .CaseLower("json", ADOF_JSON)
2703                          .Default(std::numeric_limits<unsigned>::max());
2704 
2705       if (Val != std::numeric_limits<unsigned>::max())
2706         Opts.ASTDumpFormat = static_cast<ASTDumpOutputFormat>(Val);
2707       else {
2708         Diags.Report(diag::err_drv_invalid_value)
2709             << A->getAsString(Args) << A->getValue();
2710         Opts.ASTDumpFormat = ADOF_Default;
2711       }
2712     }
2713 
2714     if (ProgramAction == frontend::FixIt && Opt == OPT_fixit_EQ)
2715       Opts.FixItSuffix = A->getValue();
2716 
2717     if (ProgramAction == frontend::GenerateInterfaceStubs) {
2718       StringRef ArgStr =
2719           Args.hasArg(OPT_interface_stub_version_EQ)
2720               ? Args.getLastArgValue(OPT_interface_stub_version_EQ)
2721               : "ifs-v1";
2722       if (ArgStr == "experimental-yaml-elf-v1" ||
2723           ArgStr == "experimental-ifs-v1" || ArgStr == "experimental-ifs-v2" ||
2724           ArgStr == "experimental-tapi-elf-v1") {
2725         std::string ErrorMessage =
2726             "Invalid interface stub format: " + ArgStr.str() +
2727             " is deprecated.";
2728         Diags.Report(diag::err_drv_invalid_value)
2729             << "Must specify a valid interface stub format type, ie: "
2730                "-interface-stub-version=ifs-v1"
2731             << ErrorMessage;
2732         ProgramAction = frontend::ParseSyntaxOnly;
2733       } else if (!ArgStr.startswith("ifs-")) {
2734         std::string ErrorMessage =
2735             "Invalid interface stub format: " + ArgStr.str() + ".";
2736         Diags.Report(diag::err_drv_invalid_value)
2737             << "Must specify a valid interface stub format type, ie: "
2738                "-interface-stub-version=ifs-v1"
2739             << ErrorMessage;
2740         ProgramAction = frontend::ParseSyntaxOnly;
2741       }
2742     }
2743 
2744     Opts.ProgramAction = *ProgramAction;
2745   }
2746 
2747   if (const Arg* A = Args.getLastArg(OPT_plugin)) {
2748     Opts.Plugins.emplace_back(A->getValue(0));
2749     Opts.ProgramAction = frontend::PluginAction;
2750     Opts.ActionName = A->getValue();
2751   }
2752   for (const auto *AA : Args.filtered(OPT_plugin_arg))
2753     Opts.PluginArgs[AA->getValue(0)].emplace_back(AA->getValue(1));
2754 
2755   for (const std::string &Arg :
2756          Args.getAllArgValues(OPT_ftest_module_file_extension_EQ)) {
2757     std::string BlockName;
2758     unsigned MajorVersion;
2759     unsigned MinorVersion;
2760     bool Hashed;
2761     std::string UserInfo;
2762     if (parseTestModuleFileExtensionArg(Arg, BlockName, MajorVersion,
2763                                         MinorVersion, Hashed, UserInfo)) {
2764       Diags.Report(diag::err_test_module_file_extension_format) << Arg;
2765 
2766       continue;
2767     }
2768 
2769     // Add the testing module file extension.
2770     Opts.ModuleFileExtensions.push_back(
2771         std::make_shared<TestModuleFileExtension>(
2772             BlockName, MajorVersion, MinorVersion, Hashed, UserInfo));
2773   }
2774 
2775   if (const Arg *A = Args.getLastArg(OPT_code_completion_at)) {
2776     Opts.CodeCompletionAt =
2777       ParsedSourceLocation::FromString(A->getValue());
2778     if (Opts.CodeCompletionAt.FileName.empty())
2779       Diags.Report(diag::err_drv_invalid_value)
2780         << A->getAsString(Args) << A->getValue();
2781   }
2782 
2783   Opts.Plugins = Args.getAllArgValues(OPT_load);
2784   Opts.ASTDumpDecls = Args.hasArg(OPT_ast_dump, OPT_ast_dump_EQ);
2785   Opts.ASTDumpAll = Args.hasArg(OPT_ast_dump_all, OPT_ast_dump_all_EQ);
2786   // Only the -fmodule-file=<file> form.
2787   for (const auto *A : Args.filtered(OPT_fmodule_file)) {
2788     StringRef Val = A->getValue();
2789     if (!Val.contains('='))
2790       Opts.ModuleFiles.push_back(std::string(Val));
2791   }
2792 
2793   if (Opts.ProgramAction != frontend::GenerateModule && Opts.IsSystemModule)
2794     Diags.Report(diag::err_drv_argument_only_allowed_with) << "-fsystem-module"
2795                                                            << "-emit-module";
2796 
2797   if (Args.hasArg(OPT_aux_target_cpu))
2798     Opts.AuxTargetCPU = std::string(Args.getLastArgValue(OPT_aux_target_cpu));
2799   if (Args.hasArg(OPT_aux_target_feature))
2800     Opts.AuxTargetFeatures = Args.getAllArgValues(OPT_aux_target_feature);
2801 
2802   if (Opts.ARCMTAction != FrontendOptions::ARCMT_None &&
2803       Opts.ObjCMTAction != FrontendOptions::ObjCMT_None) {
2804     Diags.Report(diag::err_drv_argument_not_allowed_with)
2805       << "ARC migration" << "ObjC migration";
2806   }
2807 
2808   InputKind DashX(Language::Unknown);
2809   if (const Arg *A = Args.getLastArg(OPT_x)) {
2810     StringRef XValue = A->getValue();
2811 
2812     // Parse suffixes:
2813     // '<lang>(-[{header-unit,user,system}-]header|[-module-map][-cpp-output])'.
2814     // FIXME: Supporting '<lang>-header-cpp-output' would be useful.
2815     bool Preprocessed = XValue.consume_back("-cpp-output");
2816     bool ModuleMap = XValue.consume_back("-module-map");
2817     // Detect and consume the header indicator.
2818     bool IsHeader =
2819         XValue != "precompiled-header" && XValue.consume_back("-header");
2820 
2821     // If we have c++-{user,system}-header, that indicates a header unit input
2822     // likewise, if the user put -fmodule-header together with a header with an
2823     // absolute path (header-unit-header).
2824     InputKind::HeaderUnitKind HUK = InputKind::HeaderUnit_None;
2825     if (IsHeader || Preprocessed) {
2826       if (XValue.consume_back("-header-unit"))
2827         HUK = InputKind::HeaderUnit_Abs;
2828       else if (XValue.consume_back("-system"))
2829         HUK = InputKind::HeaderUnit_System;
2830       else if (XValue.consume_back("-user"))
2831         HUK = InputKind::HeaderUnit_User;
2832     }
2833 
2834     // The value set by this processing is an un-preprocessed source which is
2835     // not intended to be a module map or header unit.
2836     IsHeaderFile = IsHeader && !Preprocessed && !ModuleMap &&
2837                    HUK == InputKind::HeaderUnit_None;
2838 
2839     // Principal languages.
2840     DashX = llvm::StringSwitch<InputKind>(XValue)
2841                 .Case("c", Language::C)
2842                 .Case("cl", Language::OpenCL)
2843                 .Case("clcpp", Language::OpenCLCXX)
2844                 .Case("cuda", Language::CUDA)
2845                 .Case("hip", Language::HIP)
2846                 .Case("c++", Language::CXX)
2847                 .Case("objective-c", Language::ObjC)
2848                 .Case("objective-c++", Language::ObjCXX)
2849                 .Case("renderscript", Language::RenderScript)
2850                 .Case("hlsl", Language::HLSL)
2851                 .Default(Language::Unknown);
2852 
2853     // "objc[++]-cpp-output" is an acceptable synonym for
2854     // "objective-c[++]-cpp-output".
2855     if (DashX.isUnknown() && Preprocessed && !IsHeaderFile && !ModuleMap &&
2856         HUK == InputKind::HeaderUnit_None)
2857       DashX = llvm::StringSwitch<InputKind>(XValue)
2858                   .Case("objc", Language::ObjC)
2859                   .Case("objc++", Language::ObjCXX)
2860                   .Default(Language::Unknown);
2861 
2862     // Some special cases cannot be combined with suffixes.
2863     if (DashX.isUnknown() && !Preprocessed && !IsHeaderFile && !ModuleMap &&
2864         HUK == InputKind::HeaderUnit_None)
2865       DashX = llvm::StringSwitch<InputKind>(XValue)
2866                   .Case("cpp-output", InputKind(Language::C).getPreprocessed())
2867                   .Case("assembler-with-cpp", Language::Asm)
2868                   .Cases("ast", "pcm", "precompiled-header",
2869                          InputKind(Language::Unknown, InputKind::Precompiled))
2870                   .Case("ir", Language::LLVM_IR)
2871                   .Default(Language::Unknown);
2872 
2873     if (DashX.isUnknown())
2874       Diags.Report(diag::err_drv_invalid_value)
2875         << A->getAsString(Args) << A->getValue();
2876 
2877     if (Preprocessed)
2878       DashX = DashX.getPreprocessed();
2879     // A regular header is considered mutually exclusive with a header unit.
2880     if (HUK != InputKind::HeaderUnit_None) {
2881       DashX = DashX.withHeaderUnit(HUK);
2882       IsHeaderFile = true;
2883     } else if (IsHeaderFile)
2884       DashX = DashX.getHeader();
2885     if (ModuleMap)
2886       DashX = DashX.withFormat(InputKind::ModuleMap);
2887   }
2888 
2889   // '-' is the default input if none is given.
2890   std::vector<std::string> Inputs = Args.getAllArgValues(OPT_INPUT);
2891   Opts.Inputs.clear();
2892   if (Inputs.empty())
2893     Inputs.push_back("-");
2894 
2895   if (DashX.getHeaderUnitKind() != InputKind::HeaderUnit_None &&
2896       Inputs.size() > 1)
2897     Diags.Report(diag::err_drv_header_unit_extra_inputs) << Inputs[1];
2898 
2899   for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
2900     InputKind IK = DashX;
2901     if (IK.isUnknown()) {
2902       IK = FrontendOptions::getInputKindForExtension(
2903         StringRef(Inputs[i]).rsplit('.').second);
2904       // FIXME: Warn on this?
2905       if (IK.isUnknown())
2906         IK = Language::C;
2907       // FIXME: Remove this hack.
2908       if (i == 0)
2909         DashX = IK;
2910     }
2911 
2912     bool IsSystem = false;
2913 
2914     // The -emit-module action implicitly takes a module map.
2915     if (Opts.ProgramAction == frontend::GenerateModule &&
2916         IK.getFormat() == InputKind::Source) {
2917       IK = IK.withFormat(InputKind::ModuleMap);
2918       IsSystem = Opts.IsSystemModule;
2919     }
2920 
2921     Opts.Inputs.emplace_back(std::move(Inputs[i]), IK, IsSystem);
2922   }
2923 
2924   Opts.DashX = DashX;
2925 
2926   return Diags.getNumErrors() == NumErrorsBefore;
2927 }
2928 
2929 std::string CompilerInvocation::GetResourcesPath(const char *Argv0,
2930                                                  void *MainAddr) {
2931   std::string ClangExecutable =
2932       llvm::sys::fs::getMainExecutable(Argv0, MainAddr);
2933   return Driver::GetResourcesPath(ClangExecutable, CLANG_RESOURCE_DIR);
2934 }
2935 
2936 static void GenerateHeaderSearchArgs(HeaderSearchOptions &Opts,
2937                                      SmallVectorImpl<const char *> &Args,
2938                                      CompilerInvocation::StringAllocator SA) {
2939   const HeaderSearchOptions *HeaderSearchOpts = &Opts;
2940 #define HEADER_SEARCH_OPTION_WITH_MARSHALLING(...)                             \
2941   GENERATE_OPTION_WITH_MARSHALLING(Args, SA, __VA_ARGS__)
2942 #include "clang/Driver/Options.inc"
2943 #undef HEADER_SEARCH_OPTION_WITH_MARSHALLING
2944 
2945   if (Opts.UseLibcxx)
2946     GenerateArg(Args, OPT_stdlib_EQ, "libc++", SA);
2947 
2948   if (!Opts.ModuleCachePath.empty())
2949     GenerateArg(Args, OPT_fmodules_cache_path, Opts.ModuleCachePath, SA);
2950 
2951   for (const auto &File : Opts.PrebuiltModuleFiles)
2952     GenerateArg(Args, OPT_fmodule_file, File.first + "=" + File.second, SA);
2953 
2954   for (const auto &Path : Opts.PrebuiltModulePaths)
2955     GenerateArg(Args, OPT_fprebuilt_module_path, Path, SA);
2956 
2957   for (const auto &Macro : Opts.ModulesIgnoreMacros)
2958     GenerateArg(Args, OPT_fmodules_ignore_macro, Macro.val(), SA);
2959 
2960   auto Matches = [](const HeaderSearchOptions::Entry &Entry,
2961                     llvm::ArrayRef<frontend::IncludeDirGroup> Groups,
2962                     std::optional<bool> IsFramework,
2963                     std::optional<bool> IgnoreSysRoot) {
2964     return llvm::is_contained(Groups, Entry.Group) &&
2965            (!IsFramework || (Entry.IsFramework == *IsFramework)) &&
2966            (!IgnoreSysRoot || (Entry.IgnoreSysRoot == *IgnoreSysRoot));
2967   };
2968 
2969   auto It = Opts.UserEntries.begin();
2970   auto End = Opts.UserEntries.end();
2971 
2972   // Add -I..., -F..., and -index-header-map options in order.
2973   for (; It < End && Matches(*It, {frontend::IndexHeaderMap, frontend::Angled},
2974                              std::nullopt, true);
2975        ++It) {
2976     OptSpecifier Opt = [It, Matches]() {
2977       if (Matches(*It, frontend::IndexHeaderMap, true, true))
2978         return OPT_F;
2979       if (Matches(*It, frontend::IndexHeaderMap, false, true))
2980         return OPT_I;
2981       if (Matches(*It, frontend::Angled, true, true))
2982         return OPT_F;
2983       if (Matches(*It, frontend::Angled, false, true))
2984         return OPT_I;
2985       llvm_unreachable("Unexpected HeaderSearchOptions::Entry.");
2986     }();
2987 
2988     if (It->Group == frontend::IndexHeaderMap)
2989       GenerateArg(Args, OPT_index_header_map, SA);
2990     GenerateArg(Args, Opt, It->Path, SA);
2991   };
2992 
2993   // Note: some paths that came from "[-iprefix=xx] -iwithprefixbefore=yy" may
2994   // have already been generated as "-I[xx]yy". If that's the case, their
2995   // position on command line was such that this has no semantic impact on
2996   // include paths.
2997   for (; It < End &&
2998          Matches(*It, {frontend::After, frontend::Angled}, false, true);
2999        ++It) {
3000     OptSpecifier Opt =
3001         It->Group == frontend::After ? OPT_iwithprefix : OPT_iwithprefixbefore;
3002     GenerateArg(Args, Opt, It->Path, SA);
3003   }
3004 
3005   // Note: Some paths that came from "-idirafter=xxyy" may have already been
3006   // generated as "-iwithprefix=xxyy". If that's the case, their position on
3007   // command line was such that this has no semantic impact on include paths.
3008   for (; It < End && Matches(*It, {frontend::After}, false, true); ++It)
3009     GenerateArg(Args, OPT_idirafter, It->Path, SA);
3010   for (; It < End && Matches(*It, {frontend::Quoted}, false, true); ++It)
3011     GenerateArg(Args, OPT_iquote, It->Path, SA);
3012   for (; It < End && Matches(*It, {frontend::System}, false, std::nullopt);
3013        ++It)
3014     GenerateArg(Args, It->IgnoreSysRoot ? OPT_isystem : OPT_iwithsysroot,
3015                 It->Path, SA);
3016   for (; It < End && Matches(*It, {frontend::System}, true, true); ++It)
3017     GenerateArg(Args, OPT_iframework, It->Path, SA);
3018   for (; It < End && Matches(*It, {frontend::System}, true, false); ++It)
3019     GenerateArg(Args, OPT_iframeworkwithsysroot, It->Path, SA);
3020 
3021   // Add the paths for the various language specific isystem flags.
3022   for (; It < End && Matches(*It, {frontend::CSystem}, false, true); ++It)
3023     GenerateArg(Args, OPT_c_isystem, It->Path, SA);
3024   for (; It < End && Matches(*It, {frontend::CXXSystem}, false, true); ++It)
3025     GenerateArg(Args, OPT_cxx_isystem, It->Path, SA);
3026   for (; It < End && Matches(*It, {frontend::ObjCSystem}, false, true); ++It)
3027     GenerateArg(Args, OPT_objc_isystem, It->Path, SA);
3028   for (; It < End && Matches(*It, {frontend::ObjCXXSystem}, false, true); ++It)
3029     GenerateArg(Args, OPT_objcxx_isystem, It->Path, SA);
3030 
3031   // Add the internal paths from a driver that detects standard include paths.
3032   // Note: Some paths that came from "-internal-isystem" arguments may have
3033   // already been generated as "-isystem". If that's the case, their position on
3034   // command line was such that this has no semantic impact on include paths.
3035   for (; It < End &&
3036          Matches(*It, {frontend::System, frontend::ExternCSystem}, false, true);
3037        ++It) {
3038     OptSpecifier Opt = It->Group == frontend::System
3039                            ? OPT_internal_isystem
3040                            : OPT_internal_externc_isystem;
3041     GenerateArg(Args, Opt, It->Path, SA);
3042   }
3043 
3044   assert(It == End && "Unhandled HeaderSearchOption::Entry.");
3045 
3046   // Add the path prefixes which are implicitly treated as being system headers.
3047   for (const auto &P : Opts.SystemHeaderPrefixes) {
3048     OptSpecifier Opt = P.IsSystemHeader ? OPT_system_header_prefix
3049                                         : OPT_no_system_header_prefix;
3050     GenerateArg(Args, Opt, P.Prefix, SA);
3051   }
3052 
3053   for (const std::string &F : Opts.VFSOverlayFiles)
3054     GenerateArg(Args, OPT_ivfsoverlay, F, SA);
3055 }
3056 
3057 static bool ParseHeaderSearchArgs(HeaderSearchOptions &Opts, ArgList &Args,
3058                                   DiagnosticsEngine &Diags,
3059                                   const std::string &WorkingDir) {
3060   unsigned NumErrorsBefore = Diags.getNumErrors();
3061 
3062   HeaderSearchOptions *HeaderSearchOpts = &Opts;
3063 
3064 #define HEADER_SEARCH_OPTION_WITH_MARSHALLING(...)                             \
3065   PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
3066 #include "clang/Driver/Options.inc"
3067 #undef HEADER_SEARCH_OPTION_WITH_MARSHALLING
3068 
3069   if (const Arg *A = Args.getLastArg(OPT_stdlib_EQ))
3070     Opts.UseLibcxx = (strcmp(A->getValue(), "libc++") == 0);
3071 
3072   // Canonicalize -fmodules-cache-path before storing it.
3073   SmallString<128> P(Args.getLastArgValue(OPT_fmodules_cache_path));
3074   if (!(P.empty() || llvm::sys::path::is_absolute(P))) {
3075     if (WorkingDir.empty())
3076       llvm::sys::fs::make_absolute(P);
3077     else
3078       llvm::sys::fs::make_absolute(WorkingDir, P);
3079   }
3080   llvm::sys::path::remove_dots(P);
3081   Opts.ModuleCachePath = std::string(P.str());
3082 
3083   // Only the -fmodule-file=<name>=<file> form.
3084   for (const auto *A : Args.filtered(OPT_fmodule_file)) {
3085     StringRef Val = A->getValue();
3086     if (Val.contains('=')) {
3087       auto Split = Val.split('=');
3088       Opts.PrebuiltModuleFiles.insert(
3089           {std::string(Split.first), std::string(Split.second)});
3090     }
3091   }
3092   for (const auto *A : Args.filtered(OPT_fprebuilt_module_path))
3093     Opts.AddPrebuiltModulePath(A->getValue());
3094 
3095   for (const auto *A : Args.filtered(OPT_fmodules_ignore_macro)) {
3096     StringRef MacroDef = A->getValue();
3097     Opts.ModulesIgnoreMacros.insert(
3098         llvm::CachedHashString(MacroDef.split('=').first));
3099   }
3100 
3101   // Add -I..., -F..., and -index-header-map options in order.
3102   bool IsIndexHeaderMap = false;
3103   bool IsSysrootSpecified =
3104       Args.hasArg(OPT__sysroot_EQ) || Args.hasArg(OPT_isysroot);
3105   for (const auto *A : Args.filtered(OPT_I, OPT_F, OPT_index_header_map)) {
3106     if (A->getOption().matches(OPT_index_header_map)) {
3107       // -index-header-map applies to the next -I or -F.
3108       IsIndexHeaderMap = true;
3109       continue;
3110     }
3111 
3112     frontend::IncludeDirGroup Group =
3113         IsIndexHeaderMap ? frontend::IndexHeaderMap : frontend::Angled;
3114 
3115     bool IsFramework = A->getOption().matches(OPT_F);
3116     std::string Path = A->getValue();
3117 
3118     if (IsSysrootSpecified && !IsFramework && A->getValue()[0] == '=') {
3119       SmallString<32> Buffer;
3120       llvm::sys::path::append(Buffer, Opts.Sysroot,
3121                               llvm::StringRef(A->getValue()).substr(1));
3122       Path = std::string(Buffer.str());
3123     }
3124 
3125     Opts.AddPath(Path, Group, IsFramework,
3126                  /*IgnoreSysroot*/ true);
3127     IsIndexHeaderMap = false;
3128   }
3129 
3130   // Add -iprefix/-iwithprefix/-iwithprefixbefore options.
3131   StringRef Prefix = ""; // FIXME: This isn't the correct default prefix.
3132   for (const auto *A :
3133        Args.filtered(OPT_iprefix, OPT_iwithprefix, OPT_iwithprefixbefore)) {
3134     if (A->getOption().matches(OPT_iprefix))
3135       Prefix = A->getValue();
3136     else if (A->getOption().matches(OPT_iwithprefix))
3137       Opts.AddPath(Prefix.str() + A->getValue(), frontend::After, false, true);
3138     else
3139       Opts.AddPath(Prefix.str() + A->getValue(), frontend::Angled, false, true);
3140   }
3141 
3142   for (const auto *A : Args.filtered(OPT_idirafter))
3143     Opts.AddPath(A->getValue(), frontend::After, false, true);
3144   for (const auto *A : Args.filtered(OPT_iquote))
3145     Opts.AddPath(A->getValue(), frontend::Quoted, false, true);
3146   for (const auto *A : Args.filtered(OPT_isystem, OPT_iwithsysroot))
3147     Opts.AddPath(A->getValue(), frontend::System, false,
3148                  !A->getOption().matches(OPT_iwithsysroot));
3149   for (const auto *A : Args.filtered(OPT_iframework))
3150     Opts.AddPath(A->getValue(), frontend::System, true, true);
3151   for (const auto *A : Args.filtered(OPT_iframeworkwithsysroot))
3152     Opts.AddPath(A->getValue(), frontend::System, /*IsFramework=*/true,
3153                  /*IgnoreSysRoot=*/false);
3154 
3155   // Add the paths for the various language specific isystem flags.
3156   for (const auto *A : Args.filtered(OPT_c_isystem))
3157     Opts.AddPath(A->getValue(), frontend::CSystem, false, true);
3158   for (const auto *A : Args.filtered(OPT_cxx_isystem))
3159     Opts.AddPath(A->getValue(), frontend::CXXSystem, false, true);
3160   for (const auto *A : Args.filtered(OPT_objc_isystem))
3161     Opts.AddPath(A->getValue(), frontend::ObjCSystem, false,true);
3162   for (const auto *A : Args.filtered(OPT_objcxx_isystem))
3163     Opts.AddPath(A->getValue(), frontend::ObjCXXSystem, false, true);
3164 
3165   // Add the internal paths from a driver that detects standard include paths.
3166   for (const auto *A :
3167        Args.filtered(OPT_internal_isystem, OPT_internal_externc_isystem)) {
3168     frontend::IncludeDirGroup Group = frontend::System;
3169     if (A->getOption().matches(OPT_internal_externc_isystem))
3170       Group = frontend::ExternCSystem;
3171     Opts.AddPath(A->getValue(), Group, false, true);
3172   }
3173 
3174   // Add the path prefixes which are implicitly treated as being system headers.
3175   for (const auto *A :
3176        Args.filtered(OPT_system_header_prefix, OPT_no_system_header_prefix))
3177     Opts.AddSystemHeaderPrefix(
3178         A->getValue(), A->getOption().matches(OPT_system_header_prefix));
3179 
3180   for (const auto *A : Args.filtered(OPT_ivfsoverlay, OPT_vfsoverlay))
3181     Opts.AddVFSOverlayFile(A->getValue());
3182 
3183   return Diags.getNumErrors() == NumErrorsBefore;
3184 }
3185 
3186 /// Check if input file kind and language standard are compatible.
3187 static bool IsInputCompatibleWithStandard(InputKind IK,
3188                                           const LangStandard &S) {
3189   switch (IK.getLanguage()) {
3190   case Language::Unknown:
3191   case Language::LLVM_IR:
3192     llvm_unreachable("should not parse language flags for this input");
3193 
3194   case Language::C:
3195   case Language::ObjC:
3196   case Language::RenderScript:
3197     return S.getLanguage() == Language::C;
3198 
3199   case Language::OpenCL:
3200     return S.getLanguage() == Language::OpenCL ||
3201            S.getLanguage() == Language::OpenCLCXX;
3202 
3203   case Language::OpenCLCXX:
3204     return S.getLanguage() == Language::OpenCLCXX;
3205 
3206   case Language::CXX:
3207   case Language::ObjCXX:
3208     return S.getLanguage() == Language::CXX;
3209 
3210   case Language::CUDA:
3211     // FIXME: What -std= values should be permitted for CUDA compilations?
3212     return S.getLanguage() == Language::CUDA ||
3213            S.getLanguage() == Language::CXX;
3214 
3215   case Language::HIP:
3216     return S.getLanguage() == Language::CXX || S.getLanguage() == Language::HIP;
3217 
3218   case Language::Asm:
3219     // Accept (and ignore) all -std= values.
3220     // FIXME: The -std= value is not ignored; it affects the tokenization
3221     // and preprocessing rules if we're preprocessing this asm input.
3222     return true;
3223 
3224   case Language::HLSL:
3225     return S.getLanguage() == Language::HLSL;
3226   }
3227 
3228   llvm_unreachable("unexpected input language");
3229 }
3230 
3231 /// Get language name for given input kind.
3232 static StringRef GetInputKindName(InputKind IK) {
3233   switch (IK.getLanguage()) {
3234   case Language::C:
3235     return "C";
3236   case Language::ObjC:
3237     return "Objective-C";
3238   case Language::CXX:
3239     return "C++";
3240   case Language::ObjCXX:
3241     return "Objective-C++";
3242   case Language::OpenCL:
3243     return "OpenCL";
3244   case Language::OpenCLCXX:
3245     return "C++ for OpenCL";
3246   case Language::CUDA:
3247     return "CUDA";
3248   case Language::RenderScript:
3249     return "RenderScript";
3250   case Language::HIP:
3251     return "HIP";
3252 
3253   case Language::Asm:
3254     return "Asm";
3255   case Language::LLVM_IR:
3256     return "LLVM IR";
3257 
3258   case Language::HLSL:
3259     return "HLSL";
3260 
3261   case Language::Unknown:
3262     break;
3263   }
3264   llvm_unreachable("unknown input language");
3265 }
3266 
3267 void CompilerInvocation::GenerateLangArgs(const LangOptions &Opts,
3268                                           SmallVectorImpl<const char *> &Args,
3269                                           StringAllocator SA,
3270                                           const llvm::Triple &T, InputKind IK) {
3271   if (IK.getFormat() == InputKind::Precompiled ||
3272       IK.getLanguage() == Language::LLVM_IR) {
3273     if (Opts.ObjCAutoRefCount)
3274       GenerateArg(Args, OPT_fobjc_arc, SA);
3275     if (Opts.PICLevel != 0)
3276       GenerateArg(Args, OPT_pic_level, Twine(Opts.PICLevel), SA);
3277     if (Opts.PIE)
3278       GenerateArg(Args, OPT_pic_is_pie, SA);
3279     for (StringRef Sanitizer : serializeSanitizerKinds(Opts.Sanitize))
3280       GenerateArg(Args, OPT_fsanitize_EQ, Sanitizer, SA);
3281 
3282     return;
3283   }
3284 
3285   OptSpecifier StdOpt;
3286   switch (Opts.LangStd) {
3287   case LangStandard::lang_opencl10:
3288   case LangStandard::lang_opencl11:
3289   case LangStandard::lang_opencl12:
3290   case LangStandard::lang_opencl20:
3291   case LangStandard::lang_opencl30:
3292   case LangStandard::lang_openclcpp10:
3293   case LangStandard::lang_openclcpp2021:
3294     StdOpt = OPT_cl_std_EQ;
3295     break;
3296   default:
3297     StdOpt = OPT_std_EQ;
3298     break;
3299   }
3300 
3301   auto LangStandard = LangStandard::getLangStandardForKind(Opts.LangStd);
3302   GenerateArg(Args, StdOpt, LangStandard.getName(), SA);
3303 
3304   if (Opts.IncludeDefaultHeader)
3305     GenerateArg(Args, OPT_finclude_default_header, SA);
3306   if (Opts.DeclareOpenCLBuiltins)
3307     GenerateArg(Args, OPT_fdeclare_opencl_builtins, SA);
3308 
3309   const LangOptions *LangOpts = &Opts;
3310 
3311 #define LANG_OPTION_WITH_MARSHALLING(...)                                      \
3312   GENERATE_OPTION_WITH_MARSHALLING(Args, SA, __VA_ARGS__)
3313 #include "clang/Driver/Options.inc"
3314 #undef LANG_OPTION_WITH_MARSHALLING
3315 
3316   // The '-fcf-protection=' option is generated by CodeGenOpts generator.
3317 
3318   if (Opts.ObjC) {
3319     GenerateArg(Args, OPT_fobjc_runtime_EQ, Opts.ObjCRuntime.getAsString(), SA);
3320 
3321     if (Opts.GC == LangOptions::GCOnly)
3322       GenerateArg(Args, OPT_fobjc_gc_only, SA);
3323     else if (Opts.GC == LangOptions::HybridGC)
3324       GenerateArg(Args, OPT_fobjc_gc, SA);
3325     else if (Opts.ObjCAutoRefCount == 1)
3326       GenerateArg(Args, OPT_fobjc_arc, SA);
3327 
3328     if (Opts.ObjCWeakRuntime)
3329       GenerateArg(Args, OPT_fobjc_runtime_has_weak, SA);
3330 
3331     if (Opts.ObjCWeak)
3332       GenerateArg(Args, OPT_fobjc_weak, SA);
3333 
3334     if (Opts.ObjCSubscriptingLegacyRuntime)
3335       GenerateArg(Args, OPT_fobjc_subscripting_legacy_runtime, SA);
3336   }
3337 
3338   if (Opts.GNUCVersion != 0) {
3339     unsigned Major = Opts.GNUCVersion / 100 / 100;
3340     unsigned Minor = (Opts.GNUCVersion / 100) % 100;
3341     unsigned Patch = Opts.GNUCVersion % 100;
3342     GenerateArg(Args, OPT_fgnuc_version_EQ,
3343                 Twine(Major) + "." + Twine(Minor) + "." + Twine(Patch), SA);
3344   }
3345 
3346   if (Opts.IgnoreXCOFFVisibility)
3347     GenerateArg(Args, OPT_mignore_xcoff_visibility, SA);
3348 
3349   if (Opts.SignedOverflowBehavior == LangOptions::SOB_Trapping) {
3350     GenerateArg(Args, OPT_ftrapv, SA);
3351     GenerateArg(Args, OPT_ftrapv_handler, Opts.OverflowHandler, SA);
3352   } else if (Opts.SignedOverflowBehavior == LangOptions::SOB_Defined) {
3353     GenerateArg(Args, OPT_fwrapv, SA);
3354   }
3355 
3356   if (Opts.MSCompatibilityVersion != 0) {
3357     unsigned Major = Opts.MSCompatibilityVersion / 10000000;
3358     unsigned Minor = (Opts.MSCompatibilityVersion / 100000) % 100;
3359     unsigned Subminor = Opts.MSCompatibilityVersion % 100000;
3360     GenerateArg(Args, OPT_fms_compatibility_version,
3361                 Twine(Major) + "." + Twine(Minor) + "." + Twine(Subminor), SA);
3362   }
3363 
3364   if ((!Opts.GNUMode && !Opts.MSVCCompat && !Opts.CPlusPlus17) || T.isOSzOS()) {
3365     if (!Opts.Trigraphs)
3366       GenerateArg(Args, OPT_fno_trigraphs, SA);
3367   } else {
3368     if (Opts.Trigraphs)
3369       GenerateArg(Args, OPT_ftrigraphs, SA);
3370   }
3371 
3372   if (Opts.Blocks && !(Opts.OpenCL && Opts.OpenCLVersion == 200))
3373     GenerateArg(Args, OPT_fblocks, SA);
3374 
3375   if (Opts.ConvergentFunctions &&
3376       !(Opts.OpenCL || (Opts.CUDA && Opts.CUDAIsDevice) || Opts.SYCLIsDevice))
3377     GenerateArg(Args, OPT_fconvergent_functions, SA);
3378 
3379   if (Opts.NoBuiltin && !Opts.Freestanding)
3380     GenerateArg(Args, OPT_fno_builtin, SA);
3381 
3382   if (!Opts.NoBuiltin)
3383     for (const auto &Func : Opts.NoBuiltinFuncs)
3384       GenerateArg(Args, OPT_fno_builtin_, Func, SA);
3385 
3386   if (Opts.LongDoubleSize == 128)
3387     GenerateArg(Args, OPT_mlong_double_128, SA);
3388   else if (Opts.LongDoubleSize == 64)
3389     GenerateArg(Args, OPT_mlong_double_64, SA);
3390   else if (Opts.LongDoubleSize == 80)
3391     GenerateArg(Args, OPT_mlong_double_80, SA);
3392 
3393   // Not generating '-mrtd', it's just an alias for '-fdefault-calling-conv='.
3394 
3395   // OpenMP was requested via '-fopenmp', not implied by '-fopenmp-simd' or
3396   // '-fopenmp-targets='.
3397   if (Opts.OpenMP && !Opts.OpenMPSimd) {
3398     GenerateArg(Args, OPT_fopenmp, SA);
3399 
3400     if (Opts.OpenMP != 51)
3401       GenerateArg(Args, OPT_fopenmp_version_EQ, Twine(Opts.OpenMP), SA);
3402 
3403     if (!Opts.OpenMPUseTLS)
3404       GenerateArg(Args, OPT_fnoopenmp_use_tls, SA);
3405 
3406     if (Opts.OpenMPIsTargetDevice)
3407       GenerateArg(Args, OPT_fopenmp_is_target_device, SA);
3408 
3409     if (Opts.OpenMPIRBuilder)
3410       GenerateArg(Args, OPT_fopenmp_enable_irbuilder, SA);
3411   }
3412 
3413   if (Opts.OpenMPSimd) {
3414     GenerateArg(Args, OPT_fopenmp_simd, SA);
3415 
3416     if (Opts.OpenMP != 51)
3417       GenerateArg(Args, OPT_fopenmp_version_EQ, Twine(Opts.OpenMP), SA);
3418   }
3419 
3420   if (Opts.OpenMPThreadSubscription)
3421     GenerateArg(Args, OPT_fopenmp_assume_threads_oversubscription, SA);
3422 
3423   if (Opts.OpenMPTeamSubscription)
3424     GenerateArg(Args, OPT_fopenmp_assume_teams_oversubscription, SA);
3425 
3426   if (Opts.OpenMPTargetDebug != 0)
3427     GenerateArg(Args, OPT_fopenmp_target_debug_EQ,
3428                 Twine(Opts.OpenMPTargetDebug), SA);
3429 
3430   if (Opts.OpenMPCUDANumSMs != 0)
3431     GenerateArg(Args, OPT_fopenmp_cuda_number_of_sm_EQ,
3432                 Twine(Opts.OpenMPCUDANumSMs), SA);
3433 
3434   if (Opts.OpenMPCUDABlocksPerSM != 0)
3435     GenerateArg(Args, OPT_fopenmp_cuda_blocks_per_sm_EQ,
3436                 Twine(Opts.OpenMPCUDABlocksPerSM), SA);
3437 
3438   if (Opts.OpenMPCUDAReductionBufNum != 1024)
3439     GenerateArg(Args, OPT_fopenmp_cuda_teams_reduction_recs_num_EQ,
3440                 Twine(Opts.OpenMPCUDAReductionBufNum), SA);
3441 
3442   if (!Opts.OMPTargetTriples.empty()) {
3443     std::string Targets;
3444     llvm::raw_string_ostream OS(Targets);
3445     llvm::interleave(
3446         Opts.OMPTargetTriples, OS,
3447         [&OS](const llvm::Triple &T) { OS << T.str(); }, ",");
3448     GenerateArg(Args, OPT_fopenmp_targets_EQ, OS.str(), SA);
3449   }
3450 
3451   if (!Opts.OMPHostIRFile.empty())
3452     GenerateArg(Args, OPT_fopenmp_host_ir_file_path, Opts.OMPHostIRFile, SA);
3453 
3454   if (Opts.OpenMPCUDAMode)
3455     GenerateArg(Args, OPT_fopenmp_cuda_mode, SA);
3456 
3457   // The arguments used to set Optimize, OptimizeSize and NoInlineDefine are
3458   // generated from CodeGenOptions.
3459 
3460   if (Opts.DefaultFPContractMode == LangOptions::FPM_Fast)
3461     GenerateArg(Args, OPT_ffp_contract, "fast", SA);
3462   else if (Opts.DefaultFPContractMode == LangOptions::FPM_On)
3463     GenerateArg(Args, OPT_ffp_contract, "on", SA);
3464   else if (Opts.DefaultFPContractMode == LangOptions::FPM_Off)
3465     GenerateArg(Args, OPT_ffp_contract, "off", SA);
3466   else if (Opts.DefaultFPContractMode == LangOptions::FPM_FastHonorPragmas)
3467     GenerateArg(Args, OPT_ffp_contract, "fast-honor-pragmas", SA);
3468 
3469   for (StringRef Sanitizer : serializeSanitizerKinds(Opts.Sanitize))
3470     GenerateArg(Args, OPT_fsanitize_EQ, Sanitizer, SA);
3471 
3472   // Conflating '-fsanitize-system-ignorelist' and '-fsanitize-ignorelist'.
3473   for (const std::string &F : Opts.NoSanitizeFiles)
3474     GenerateArg(Args, OPT_fsanitize_ignorelist_EQ, F, SA);
3475 
3476   if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver3_8)
3477     GenerateArg(Args, OPT_fclang_abi_compat_EQ, "3.8", SA);
3478   else if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver4)
3479     GenerateArg(Args, OPT_fclang_abi_compat_EQ, "4.0", SA);
3480   else if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver6)
3481     GenerateArg(Args, OPT_fclang_abi_compat_EQ, "6.0", SA);
3482   else if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver7)
3483     GenerateArg(Args, OPT_fclang_abi_compat_EQ, "7.0", SA);
3484   else if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver9)
3485     GenerateArg(Args, OPT_fclang_abi_compat_EQ, "9.0", SA);
3486   else if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver11)
3487     GenerateArg(Args, OPT_fclang_abi_compat_EQ, "11.0", SA);
3488   else if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver12)
3489     GenerateArg(Args, OPT_fclang_abi_compat_EQ, "12.0", SA);
3490   else if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver14)
3491     GenerateArg(Args, OPT_fclang_abi_compat_EQ, "14.0", SA);
3492   else if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver15)
3493     GenerateArg(Args, OPT_fclang_abi_compat_EQ, "15.0", SA);
3494 
3495   if (Opts.getSignReturnAddressScope() ==
3496       LangOptions::SignReturnAddressScopeKind::All)
3497     GenerateArg(Args, OPT_msign_return_address_EQ, "all", SA);
3498   else if (Opts.getSignReturnAddressScope() ==
3499            LangOptions::SignReturnAddressScopeKind::NonLeaf)
3500     GenerateArg(Args, OPT_msign_return_address_EQ, "non-leaf", SA);
3501 
3502   if (Opts.getSignReturnAddressKey() ==
3503       LangOptions::SignReturnAddressKeyKind::BKey)
3504     GenerateArg(Args, OPT_msign_return_address_key_EQ, "b_key", SA);
3505 
3506   if (Opts.CXXABI)
3507     GenerateArg(Args, OPT_fcxx_abi_EQ, TargetCXXABI::getSpelling(*Opts.CXXABI),
3508                 SA);
3509 
3510   if (Opts.RelativeCXXABIVTables)
3511     GenerateArg(Args, OPT_fexperimental_relative_cxx_abi_vtables, SA);
3512   else
3513     GenerateArg(Args, OPT_fno_experimental_relative_cxx_abi_vtables, SA);
3514 
3515   if (Opts.UseTargetPathSeparator)
3516     GenerateArg(Args, OPT_ffile_reproducible, SA);
3517   else
3518     GenerateArg(Args, OPT_fno_file_reproducible, SA);
3519 
3520   for (const auto &MP : Opts.MacroPrefixMap)
3521     GenerateArg(Args, OPT_fmacro_prefix_map_EQ, MP.first + "=" + MP.second, SA);
3522 
3523   if (!Opts.RandstructSeed.empty())
3524     GenerateArg(Args, OPT_frandomize_layout_seed_EQ, Opts.RandstructSeed, SA);
3525 }
3526 
3527 bool CompilerInvocation::ParseLangArgs(LangOptions &Opts, ArgList &Args,
3528                                        InputKind IK, const llvm::Triple &T,
3529                                        std::vector<std::string> &Includes,
3530                                        DiagnosticsEngine &Diags) {
3531   unsigned NumErrorsBefore = Diags.getNumErrors();
3532 
3533   if (IK.getFormat() == InputKind::Precompiled ||
3534       IK.getLanguage() == Language::LLVM_IR) {
3535     // ObjCAAutoRefCount and Sanitize LangOpts are used to setup the
3536     // PassManager in BackendUtil.cpp. They need to be initialized no matter
3537     // what the input type is.
3538     if (Args.hasArg(OPT_fobjc_arc))
3539       Opts.ObjCAutoRefCount = 1;
3540     // PICLevel and PIELevel are needed during code generation and this should
3541     // be set regardless of the input type.
3542     Opts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags);
3543     Opts.PIE = Args.hasArg(OPT_pic_is_pie);
3544     parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ),
3545                         Diags, Opts.Sanitize);
3546 
3547     return Diags.getNumErrors() == NumErrorsBefore;
3548   }
3549 
3550   // Other LangOpts are only initialized when the input is not AST or LLVM IR.
3551   // FIXME: Should we really be parsing this for an Language::Asm input?
3552 
3553   // FIXME: Cleanup per-file based stuff.
3554   LangStandard::Kind LangStd = LangStandard::lang_unspecified;
3555   if (const Arg *A = Args.getLastArg(OPT_std_EQ)) {
3556     LangStd = LangStandard::getLangKind(A->getValue());
3557     if (LangStd == LangStandard::lang_unspecified) {
3558       Diags.Report(diag::err_drv_invalid_value)
3559         << A->getAsString(Args) << A->getValue();
3560       // Report supported standards with short description.
3561       for (unsigned KindValue = 0;
3562            KindValue != LangStandard::lang_unspecified;
3563            ++KindValue) {
3564         const LangStandard &Std = LangStandard::getLangStandardForKind(
3565           static_cast<LangStandard::Kind>(KindValue));
3566         if (IsInputCompatibleWithStandard(IK, Std)) {
3567           auto Diag = Diags.Report(diag::note_drv_use_standard);
3568           Diag << Std.getName() << Std.getDescription();
3569           unsigned NumAliases = 0;
3570 #define LANGSTANDARD(id, name, lang, desc, features)
3571 #define LANGSTANDARD_ALIAS(id, alias) \
3572           if (KindValue == LangStandard::lang_##id) ++NumAliases;
3573 #define LANGSTANDARD_ALIAS_DEPR(id, alias)
3574 #include "clang/Basic/LangStandards.def"
3575           Diag << NumAliases;
3576 #define LANGSTANDARD(id, name, lang, desc, features)
3577 #define LANGSTANDARD_ALIAS(id, alias) \
3578           if (KindValue == LangStandard::lang_##id) Diag << alias;
3579 #define LANGSTANDARD_ALIAS_DEPR(id, alias)
3580 #include "clang/Basic/LangStandards.def"
3581         }
3582       }
3583     } else {
3584       // Valid standard, check to make sure language and standard are
3585       // compatible.
3586       const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
3587       if (!IsInputCompatibleWithStandard(IK, Std)) {
3588         Diags.Report(diag::err_drv_argument_not_allowed_with)
3589           << A->getAsString(Args) << GetInputKindName(IK);
3590       }
3591     }
3592   }
3593 
3594   // -cl-std only applies for OpenCL language standards.
3595   // Override the -std option in this case.
3596   if (const Arg *A = Args.getLastArg(OPT_cl_std_EQ)) {
3597     LangStandard::Kind OpenCLLangStd
3598       = llvm::StringSwitch<LangStandard::Kind>(A->getValue())
3599         .Cases("cl", "CL", LangStandard::lang_opencl10)
3600         .Cases("cl1.0", "CL1.0", LangStandard::lang_opencl10)
3601         .Cases("cl1.1", "CL1.1", LangStandard::lang_opencl11)
3602         .Cases("cl1.2", "CL1.2", LangStandard::lang_opencl12)
3603         .Cases("cl2.0", "CL2.0", LangStandard::lang_opencl20)
3604         .Cases("cl3.0", "CL3.0", LangStandard::lang_opencl30)
3605         .Cases("clc++", "CLC++", LangStandard::lang_openclcpp10)
3606         .Cases("clc++1.0", "CLC++1.0", LangStandard::lang_openclcpp10)
3607         .Cases("clc++2021", "CLC++2021", LangStandard::lang_openclcpp2021)
3608         .Default(LangStandard::lang_unspecified);
3609 
3610     if (OpenCLLangStd == LangStandard::lang_unspecified) {
3611       Diags.Report(diag::err_drv_invalid_value)
3612         << A->getAsString(Args) << A->getValue();
3613     }
3614     else
3615       LangStd = OpenCLLangStd;
3616   }
3617 
3618   // These need to be parsed now. They are used to set OpenCL defaults.
3619   Opts.IncludeDefaultHeader = Args.hasArg(OPT_finclude_default_header);
3620   Opts.DeclareOpenCLBuiltins = Args.hasArg(OPT_fdeclare_opencl_builtins);
3621 
3622   LangOptions::setLangDefaults(Opts, IK.getLanguage(), T, Includes, LangStd);
3623 
3624   // The key paths of codegen options defined in Options.td start with
3625   // "LangOpts->". Let's provide the expected variable name and type.
3626   LangOptions *LangOpts = &Opts;
3627 
3628 #define LANG_OPTION_WITH_MARSHALLING(...)                                      \
3629   PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
3630 #include "clang/Driver/Options.inc"
3631 #undef LANG_OPTION_WITH_MARSHALLING
3632 
3633   if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
3634     StringRef Name = A->getValue();
3635     if (Name == "full" || Name == "branch") {
3636       Opts.CFProtectionBranch = 1;
3637     }
3638   }
3639 
3640   if ((Args.hasArg(OPT_fsycl_is_device) || Args.hasArg(OPT_fsycl_is_host)) &&
3641       !Args.hasArg(OPT_sycl_std_EQ)) {
3642     // If the user supplied -fsycl-is-device or -fsycl-is-host, but failed to
3643     // provide -sycl-std=, we want to default it to whatever the default SYCL
3644     // version is. I could not find a way to express this with the options
3645     // tablegen because we still want this value to be SYCL_None when the user
3646     // is not in device or host mode.
3647     Opts.setSYCLVersion(LangOptions::SYCL_Default);
3648   }
3649 
3650   if (Opts.ObjC) {
3651     if (Arg *arg = Args.getLastArg(OPT_fobjc_runtime_EQ)) {
3652       StringRef value = arg->getValue();
3653       if (Opts.ObjCRuntime.tryParse(value))
3654         Diags.Report(diag::err_drv_unknown_objc_runtime) << value;
3655     }
3656 
3657     if (Args.hasArg(OPT_fobjc_gc_only))
3658       Opts.setGC(LangOptions::GCOnly);
3659     else if (Args.hasArg(OPT_fobjc_gc))
3660       Opts.setGC(LangOptions::HybridGC);
3661     else if (Args.hasArg(OPT_fobjc_arc)) {
3662       Opts.ObjCAutoRefCount = 1;
3663       if (!Opts.ObjCRuntime.allowsARC())
3664         Diags.Report(diag::err_arc_unsupported_on_runtime);
3665     }
3666 
3667     // ObjCWeakRuntime tracks whether the runtime supports __weak, not
3668     // whether the feature is actually enabled.  This is predominantly
3669     // determined by -fobjc-runtime, but we allow it to be overridden
3670     // from the command line for testing purposes.
3671     if (Args.hasArg(OPT_fobjc_runtime_has_weak))
3672       Opts.ObjCWeakRuntime = 1;
3673     else
3674       Opts.ObjCWeakRuntime = Opts.ObjCRuntime.allowsWeak();
3675 
3676     // ObjCWeak determines whether __weak is actually enabled.
3677     // Note that we allow -fno-objc-weak to disable this even in ARC mode.
3678     if (auto weakArg = Args.getLastArg(OPT_fobjc_weak, OPT_fno_objc_weak)) {
3679       if (!weakArg->getOption().matches(OPT_fobjc_weak)) {
3680         assert(!Opts.ObjCWeak);
3681       } else if (Opts.getGC() != LangOptions::NonGC) {
3682         Diags.Report(diag::err_objc_weak_with_gc);
3683       } else if (!Opts.ObjCWeakRuntime) {
3684         Diags.Report(diag::err_objc_weak_unsupported);
3685       } else {
3686         Opts.ObjCWeak = 1;
3687       }
3688     } else if (Opts.ObjCAutoRefCount) {
3689       Opts.ObjCWeak = Opts.ObjCWeakRuntime;
3690     }
3691 
3692     if (Args.hasArg(OPT_fobjc_subscripting_legacy_runtime))
3693       Opts.ObjCSubscriptingLegacyRuntime =
3694         (Opts.ObjCRuntime.getKind() == ObjCRuntime::FragileMacOSX);
3695   }
3696 
3697   if (Arg *A = Args.getLastArg(options::OPT_fgnuc_version_EQ)) {
3698     // Check that the version has 1 to 3 components and the minor and patch
3699     // versions fit in two decimal digits.
3700     VersionTuple GNUCVer;
3701     bool Invalid = GNUCVer.tryParse(A->getValue());
3702     unsigned Major = GNUCVer.getMajor();
3703     unsigned Minor = GNUCVer.getMinor().value_or(0);
3704     unsigned Patch = GNUCVer.getSubminor().value_or(0);
3705     if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) {
3706       Diags.Report(diag::err_drv_invalid_value)
3707           << A->getAsString(Args) << A->getValue();
3708     }
3709     Opts.GNUCVersion = Major * 100 * 100 + Minor * 100 + Patch;
3710   }
3711 
3712   if (T.isOSAIX() && (Args.hasArg(OPT_mignore_xcoff_visibility)))
3713     Opts.IgnoreXCOFFVisibility = 1;
3714 
3715   if (Args.hasArg(OPT_ftrapv)) {
3716     Opts.setSignedOverflowBehavior(LangOptions::SOB_Trapping);
3717     // Set the handler, if one is specified.
3718     Opts.OverflowHandler =
3719         std::string(Args.getLastArgValue(OPT_ftrapv_handler));
3720   }
3721   else if (Args.hasArg(OPT_fwrapv))
3722     Opts.setSignedOverflowBehavior(LangOptions::SOB_Defined);
3723 
3724   Opts.MSCompatibilityVersion = 0;
3725   if (const Arg *A = Args.getLastArg(OPT_fms_compatibility_version)) {
3726     VersionTuple VT;
3727     if (VT.tryParse(A->getValue()))
3728       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
3729                                                 << A->getValue();
3730     Opts.MSCompatibilityVersion = VT.getMajor() * 10000000 +
3731                                   VT.getMinor().value_or(0) * 100000 +
3732                                   VT.getSubminor().value_or(0);
3733   }
3734 
3735   // Mimicking gcc's behavior, trigraphs are only enabled if -trigraphs
3736   // is specified, or -std is set to a conforming mode.
3737   // Trigraphs are disabled by default in c++1z onwards.
3738   // For z/OS, trigraphs are enabled by default (without regard to the above).
3739   Opts.Trigraphs =
3740       (!Opts.GNUMode && !Opts.MSVCCompat && !Opts.CPlusPlus17) || T.isOSzOS();
3741   Opts.Trigraphs =
3742       Args.hasFlag(OPT_ftrigraphs, OPT_fno_trigraphs, Opts.Trigraphs);
3743 
3744   Opts.Blocks = Args.hasArg(OPT_fblocks) || (Opts.OpenCL
3745     && Opts.OpenCLVersion == 200);
3746 
3747   Opts.ConvergentFunctions = Args.hasArg(OPT_fconvergent_functions) ||
3748                              Opts.OpenCL || (Opts.CUDA && Opts.CUDAIsDevice) ||
3749                              Opts.SYCLIsDevice;
3750 
3751   Opts.NoBuiltin = Args.hasArg(OPT_fno_builtin) || Opts.Freestanding;
3752   if (!Opts.NoBuiltin)
3753     getAllNoBuiltinFuncValues(Args, Opts.NoBuiltinFuncs);
3754   if (Arg *A = Args.getLastArg(options::OPT_LongDouble_Group)) {
3755     if (A->getOption().matches(options::OPT_mlong_double_64))
3756       Opts.LongDoubleSize = 64;
3757     else if (A->getOption().matches(options::OPT_mlong_double_80))
3758       Opts.LongDoubleSize = 80;
3759     else if (A->getOption().matches(options::OPT_mlong_double_128))
3760       Opts.LongDoubleSize = 128;
3761     else
3762       Opts.LongDoubleSize = 0;
3763   }
3764   if (Opts.FastRelaxedMath || Opts.CLUnsafeMath)
3765     Opts.setDefaultFPContractMode(LangOptions::FPM_Fast);
3766 
3767   llvm::sort(Opts.ModuleFeatures);
3768 
3769   // -mrtd option
3770   if (Arg *A = Args.getLastArg(OPT_mrtd)) {
3771     if (Opts.getDefaultCallingConv() != LangOptions::DCC_None)
3772       Diags.Report(diag::err_drv_argument_not_allowed_with)
3773           << A->getSpelling() << "-fdefault-calling-conv";
3774     else {
3775       if (T.getArch() != llvm::Triple::x86)
3776         Diags.Report(diag::err_drv_argument_not_allowed_with)
3777             << A->getSpelling() << T.getTriple();
3778       else
3779         Opts.setDefaultCallingConv(LangOptions::DCC_StdCall);
3780     }
3781   }
3782 
3783   // Check if -fopenmp is specified and set default version to 5.0.
3784   Opts.OpenMP = Args.hasArg(OPT_fopenmp) ? 51 : 0;
3785   // Check if -fopenmp-simd is specified.
3786   bool IsSimdSpecified =
3787       Args.hasFlag(options::OPT_fopenmp_simd, options::OPT_fno_openmp_simd,
3788                    /*Default=*/false);
3789   Opts.OpenMPSimd = !Opts.OpenMP && IsSimdSpecified;
3790   Opts.OpenMPUseTLS =
3791       Opts.OpenMP && !Args.hasArg(options::OPT_fnoopenmp_use_tls);
3792   Opts.OpenMPIsTargetDevice =
3793       Opts.OpenMP && Args.hasArg(options::OPT_fopenmp_is_target_device);
3794   Opts.OpenMPIRBuilder =
3795       Opts.OpenMP && Args.hasArg(options::OPT_fopenmp_enable_irbuilder);
3796   bool IsTargetSpecified =
3797       Opts.OpenMPIsTargetDevice || Args.hasArg(options::OPT_fopenmp_targets_EQ);
3798 
3799   Opts.ConvergentFunctions =
3800       Opts.ConvergentFunctions || Opts.OpenMPIsTargetDevice;
3801 
3802   if (Opts.OpenMP || Opts.OpenMPSimd) {
3803     if (int Version = getLastArgIntValue(
3804             Args, OPT_fopenmp_version_EQ,
3805             (IsSimdSpecified || IsTargetSpecified) ? 51 : Opts.OpenMP, Diags))
3806       Opts.OpenMP = Version;
3807     // Provide diagnostic when a given target is not expected to be an OpenMP
3808     // device or host.
3809     if (!Opts.OpenMPIsTargetDevice) {
3810       switch (T.getArch()) {
3811       default:
3812         break;
3813       // Add unsupported host targets here:
3814       case llvm::Triple::nvptx:
3815       case llvm::Triple::nvptx64:
3816         Diags.Report(diag::err_drv_omp_host_target_not_supported) << T.str();
3817         break;
3818       }
3819     }
3820   }
3821 
3822   // Set the flag to prevent the implementation from emitting device exception
3823   // handling code for those requiring so.
3824   if ((Opts.OpenMPIsTargetDevice && (T.isNVPTX() || T.isAMDGCN())) ||
3825       Opts.OpenCLCPlusPlus) {
3826 
3827     Opts.Exceptions = 0;
3828     Opts.CXXExceptions = 0;
3829   }
3830   if (Opts.OpenMPIsTargetDevice && T.isNVPTX()) {
3831     Opts.OpenMPCUDANumSMs =
3832         getLastArgIntValue(Args, options::OPT_fopenmp_cuda_number_of_sm_EQ,
3833                            Opts.OpenMPCUDANumSMs, Diags);
3834     Opts.OpenMPCUDABlocksPerSM =
3835         getLastArgIntValue(Args, options::OPT_fopenmp_cuda_blocks_per_sm_EQ,
3836                            Opts.OpenMPCUDABlocksPerSM, Diags);
3837     Opts.OpenMPCUDAReductionBufNum = getLastArgIntValue(
3838         Args, options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ,
3839         Opts.OpenMPCUDAReductionBufNum, Diags);
3840   }
3841 
3842   // Set the value of the debugging flag used in the new offloading device RTL.
3843   // Set either by a specific value or to a default if not specified.
3844   if (Opts.OpenMPIsTargetDevice && (Args.hasArg(OPT_fopenmp_target_debug) ||
3845                                     Args.hasArg(OPT_fopenmp_target_debug_EQ))) {
3846     Opts.OpenMPTargetDebug = getLastArgIntValue(
3847         Args, OPT_fopenmp_target_debug_EQ, Opts.OpenMPTargetDebug, Diags);
3848     if (!Opts.OpenMPTargetDebug && Args.hasArg(OPT_fopenmp_target_debug))
3849       Opts.OpenMPTargetDebug = 1;
3850   }
3851 
3852   if (Opts.OpenMPIsTargetDevice) {
3853     if (Args.hasArg(OPT_fopenmp_assume_teams_oversubscription))
3854       Opts.OpenMPTeamSubscription = true;
3855     if (Args.hasArg(OPT_fopenmp_assume_threads_oversubscription))
3856       Opts.OpenMPThreadSubscription = true;
3857   }
3858 
3859   // Get the OpenMP target triples if any.
3860   if (Arg *A = Args.getLastArg(options::OPT_fopenmp_targets_EQ)) {
3861     enum ArchPtrSize { Arch16Bit, Arch32Bit, Arch64Bit };
3862     auto getArchPtrSize = [](const llvm::Triple &T) {
3863       if (T.isArch16Bit())
3864         return Arch16Bit;
3865       if (T.isArch32Bit())
3866         return Arch32Bit;
3867       assert(T.isArch64Bit() && "Expected 64-bit architecture");
3868       return Arch64Bit;
3869     };
3870 
3871     for (unsigned i = 0; i < A->getNumValues(); ++i) {
3872       llvm::Triple TT(A->getValue(i));
3873 
3874       if (TT.getArch() == llvm::Triple::UnknownArch ||
3875           !(TT.getArch() == llvm::Triple::aarch64 || TT.isPPC() ||
3876             TT.getArch() == llvm::Triple::nvptx ||
3877             TT.getArch() == llvm::Triple::nvptx64 ||
3878             TT.getArch() == llvm::Triple::amdgcn ||
3879             TT.getArch() == llvm::Triple::x86 ||
3880             TT.getArch() == llvm::Triple::x86_64))
3881         Diags.Report(diag::err_drv_invalid_omp_target) << A->getValue(i);
3882       else if (getArchPtrSize(T) != getArchPtrSize(TT))
3883         Diags.Report(diag::err_drv_incompatible_omp_arch)
3884             << A->getValue(i) << T.str();
3885       else
3886         Opts.OMPTargetTriples.push_back(TT);
3887     }
3888   }
3889 
3890   // Get OpenMP host file path if any and report if a non existent file is
3891   // found
3892   if (Arg *A = Args.getLastArg(options::OPT_fopenmp_host_ir_file_path)) {
3893     Opts.OMPHostIRFile = A->getValue();
3894     if (!llvm::sys::fs::exists(Opts.OMPHostIRFile))
3895       Diags.Report(diag::err_drv_omp_host_ir_file_not_found)
3896           << Opts.OMPHostIRFile;
3897   }
3898 
3899   // Set CUDA mode for OpenMP target NVPTX/AMDGCN if specified in options
3900   Opts.OpenMPCUDAMode = Opts.OpenMPIsTargetDevice &&
3901                         (T.isNVPTX() || T.isAMDGCN()) &&
3902                         Args.hasArg(options::OPT_fopenmp_cuda_mode);
3903 
3904   // FIXME: Eliminate this dependency.
3905   unsigned Opt = getOptimizationLevel(Args, IK, Diags),
3906        OptSize = getOptimizationLevelSize(Args);
3907   Opts.Optimize = Opt != 0;
3908   Opts.OptimizeSize = OptSize != 0;
3909 
3910   // This is the __NO_INLINE__ define, which just depends on things like the
3911   // optimization level and -fno-inline, not actually whether the backend has
3912   // inlining enabled.
3913   Opts.NoInlineDefine = !Opts.Optimize;
3914   if (Arg *InlineArg = Args.getLastArg(
3915           options::OPT_finline_functions, options::OPT_finline_hint_functions,
3916           options::OPT_fno_inline_functions, options::OPT_fno_inline))
3917     if (InlineArg->getOption().matches(options::OPT_fno_inline))
3918       Opts.NoInlineDefine = true;
3919 
3920   if (Arg *A = Args.getLastArg(OPT_ffp_contract)) {
3921     StringRef Val = A->getValue();
3922     if (Val == "fast")
3923       Opts.setDefaultFPContractMode(LangOptions::FPM_Fast);
3924     else if (Val == "on")
3925       Opts.setDefaultFPContractMode(LangOptions::FPM_On);
3926     else if (Val == "off")
3927       Opts.setDefaultFPContractMode(LangOptions::FPM_Off);
3928     else if (Val == "fast-honor-pragmas")
3929       Opts.setDefaultFPContractMode(LangOptions::FPM_FastHonorPragmas);
3930     else
3931       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
3932   }
3933 
3934   // Parse -fsanitize= arguments.
3935   parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ),
3936                       Diags, Opts.Sanitize);
3937   Opts.NoSanitizeFiles = Args.getAllArgValues(OPT_fsanitize_ignorelist_EQ);
3938   std::vector<std::string> systemIgnorelists =
3939       Args.getAllArgValues(OPT_fsanitize_system_ignorelist_EQ);
3940   Opts.NoSanitizeFiles.insert(Opts.NoSanitizeFiles.end(),
3941                               systemIgnorelists.begin(),
3942                               systemIgnorelists.end());
3943 
3944   if (Arg *A = Args.getLastArg(OPT_fclang_abi_compat_EQ)) {
3945     Opts.setClangABICompat(LangOptions::ClangABI::Latest);
3946 
3947     StringRef Ver = A->getValue();
3948     std::pair<StringRef, StringRef> VerParts = Ver.split('.');
3949     unsigned Major, Minor = 0;
3950 
3951     // Check the version number is valid: either 3.x (0 <= x <= 9) or
3952     // y or y.0 (4 <= y <= current version).
3953     if (!VerParts.first.startswith("0") &&
3954         !VerParts.first.getAsInteger(10, Major) &&
3955         3 <= Major && Major <= CLANG_VERSION_MAJOR &&
3956         (Major == 3 ? VerParts.second.size() == 1 &&
3957                       !VerParts.second.getAsInteger(10, Minor)
3958                     : VerParts.first.size() == Ver.size() ||
3959                       VerParts.second == "0")) {
3960       // Got a valid version number.
3961       if (Major == 3 && Minor <= 8)
3962         Opts.setClangABICompat(LangOptions::ClangABI::Ver3_8);
3963       else if (Major <= 4)
3964         Opts.setClangABICompat(LangOptions::ClangABI::Ver4);
3965       else if (Major <= 6)
3966         Opts.setClangABICompat(LangOptions::ClangABI::Ver6);
3967       else if (Major <= 7)
3968         Opts.setClangABICompat(LangOptions::ClangABI::Ver7);
3969       else if (Major <= 9)
3970         Opts.setClangABICompat(LangOptions::ClangABI::Ver9);
3971       else if (Major <= 11)
3972         Opts.setClangABICompat(LangOptions::ClangABI::Ver11);
3973       else if (Major <= 12)
3974         Opts.setClangABICompat(LangOptions::ClangABI::Ver12);
3975       else if (Major <= 14)
3976         Opts.setClangABICompat(LangOptions::ClangABI::Ver14);
3977       else if (Major <= 15)
3978         Opts.setClangABICompat(LangOptions::ClangABI::Ver15);
3979     } else if (Ver != "latest") {
3980       Diags.Report(diag::err_drv_invalid_value)
3981           << A->getAsString(Args) << A->getValue();
3982     }
3983   }
3984 
3985   if (Arg *A = Args.getLastArg(OPT_msign_return_address_EQ)) {
3986     StringRef SignScope = A->getValue();
3987 
3988     if (SignScope.equals_insensitive("none"))
3989       Opts.setSignReturnAddressScope(
3990           LangOptions::SignReturnAddressScopeKind::None);
3991     else if (SignScope.equals_insensitive("all"))
3992       Opts.setSignReturnAddressScope(
3993           LangOptions::SignReturnAddressScopeKind::All);
3994     else if (SignScope.equals_insensitive("non-leaf"))
3995       Opts.setSignReturnAddressScope(
3996           LangOptions::SignReturnAddressScopeKind::NonLeaf);
3997     else
3998       Diags.Report(diag::err_drv_invalid_value)
3999           << A->getAsString(Args) << SignScope;
4000 
4001     if (Arg *A = Args.getLastArg(OPT_msign_return_address_key_EQ)) {
4002       StringRef SignKey = A->getValue();
4003       if (!SignScope.empty() && !SignKey.empty()) {
4004         if (SignKey.equals_insensitive("a_key"))
4005           Opts.setSignReturnAddressKey(
4006               LangOptions::SignReturnAddressKeyKind::AKey);
4007         else if (SignKey.equals_insensitive("b_key"))
4008           Opts.setSignReturnAddressKey(
4009               LangOptions::SignReturnAddressKeyKind::BKey);
4010         else
4011           Diags.Report(diag::err_drv_invalid_value)
4012               << A->getAsString(Args) << SignKey;
4013       }
4014     }
4015   }
4016 
4017   // The value can be empty, which indicates the system default should be used.
4018   StringRef CXXABI = Args.getLastArgValue(OPT_fcxx_abi_EQ);
4019   if (!CXXABI.empty()) {
4020     if (!TargetCXXABI::isABI(CXXABI)) {
4021       Diags.Report(diag::err_invalid_cxx_abi) << CXXABI;
4022     } else {
4023       auto Kind = TargetCXXABI::getKind(CXXABI);
4024       if (!TargetCXXABI::isSupportedCXXABI(T, Kind))
4025         Diags.Report(diag::err_unsupported_cxx_abi) << CXXABI << T.str();
4026       else
4027         Opts.CXXABI = Kind;
4028     }
4029   }
4030 
4031   Opts.RelativeCXXABIVTables =
4032       Args.hasFlag(options::OPT_fexperimental_relative_cxx_abi_vtables,
4033                    options::OPT_fno_experimental_relative_cxx_abi_vtables,
4034                    TargetCXXABI::usesRelativeVTables(T));
4035 
4036   for (const auto &A : Args.getAllArgValues(OPT_fmacro_prefix_map_EQ)) {
4037     auto Split = StringRef(A).split('=');
4038     Opts.MacroPrefixMap.insert(
4039         {std::string(Split.first), std::string(Split.second)});
4040   }
4041 
4042   Opts.UseTargetPathSeparator =
4043       !Args.getLastArg(OPT_fno_file_reproducible) &&
4044       (Args.getLastArg(OPT_ffile_compilation_dir_EQ) ||
4045        Args.getLastArg(OPT_fmacro_prefix_map_EQ) ||
4046        Args.getLastArg(OPT_ffile_reproducible));
4047 
4048   // Error if -mvscale-min is unbounded.
4049   if (Arg *A = Args.getLastArg(options::OPT_mvscale_min_EQ)) {
4050     unsigned VScaleMin;
4051     if (StringRef(A->getValue()).getAsInteger(10, VScaleMin) || VScaleMin == 0)
4052       Diags.Report(diag::err_cc1_unbounded_vscale_min);
4053   }
4054 
4055   if (const Arg *A = Args.getLastArg(OPT_frandomize_layout_seed_file_EQ)) {
4056     std::ifstream SeedFile(A->getValue(0));
4057 
4058     if (!SeedFile.is_open())
4059       Diags.Report(diag::err_drv_cannot_open_randomize_layout_seed_file)
4060           << A->getValue(0);
4061 
4062     std::getline(SeedFile, Opts.RandstructSeed);
4063   }
4064 
4065   if (const Arg *A = Args.getLastArg(OPT_frandomize_layout_seed_EQ))
4066     Opts.RandstructSeed = A->getValue(0);
4067 
4068   // Validate options for HLSL
4069   if (Opts.HLSL) {
4070     bool SupportedTarget = T.getArch() == llvm::Triple::dxil &&
4071                            T.getOS() == llvm::Triple::ShaderModel;
4072     if (!SupportedTarget)
4073       Diags.Report(diag::err_drv_hlsl_unsupported_target) << T.str();
4074   }
4075 
4076   return Diags.getNumErrors() == NumErrorsBefore;
4077 }
4078 
4079 static bool isStrictlyPreprocessorAction(frontend::ActionKind Action) {
4080   switch (Action) {
4081   case frontend::ASTDeclList:
4082   case frontend::ASTDump:
4083   case frontend::ASTPrint:
4084   case frontend::ASTView:
4085   case frontend::EmitAssembly:
4086   case frontend::EmitBC:
4087   case frontend::EmitHTML:
4088   case frontend::EmitLLVM:
4089   case frontend::EmitLLVMOnly:
4090   case frontend::EmitCodeGenOnly:
4091   case frontend::EmitObj:
4092   case frontend::ExtractAPI:
4093   case frontend::FixIt:
4094   case frontend::GenerateModule:
4095   case frontend::GenerateModuleInterface:
4096   case frontend::GenerateHeaderUnit:
4097   case frontend::GeneratePCH:
4098   case frontend::GenerateInterfaceStubs:
4099   case frontend::ParseSyntaxOnly:
4100   case frontend::ModuleFileInfo:
4101   case frontend::VerifyPCH:
4102   case frontend::PluginAction:
4103   case frontend::RewriteObjC:
4104   case frontend::RewriteTest:
4105   case frontend::RunAnalysis:
4106   case frontend::TemplightDump:
4107   case frontend::MigrateSource:
4108     return false;
4109 
4110   case frontend::DumpCompilerOptions:
4111   case frontend::DumpRawTokens:
4112   case frontend::DumpTokens:
4113   case frontend::InitOnly:
4114   case frontend::PrintPreamble:
4115   case frontend::PrintPreprocessedInput:
4116   case frontend::RewriteMacros:
4117   case frontend::RunPreprocessorOnly:
4118   case frontend::PrintDependencyDirectivesSourceMinimizerOutput:
4119     return true;
4120   }
4121   llvm_unreachable("invalid frontend action");
4122 }
4123 
4124 static void GeneratePreprocessorArgs(PreprocessorOptions &Opts,
4125                                      SmallVectorImpl<const char *> &Args,
4126                                      CompilerInvocation::StringAllocator SA,
4127                                      const LangOptions &LangOpts,
4128                                      const FrontendOptions &FrontendOpts,
4129                                      const CodeGenOptions &CodeGenOpts) {
4130   PreprocessorOptions *PreprocessorOpts = &Opts;
4131 
4132 #define PREPROCESSOR_OPTION_WITH_MARSHALLING(...)                              \
4133   GENERATE_OPTION_WITH_MARSHALLING(Args, SA, __VA_ARGS__)
4134 #include "clang/Driver/Options.inc"
4135 #undef PREPROCESSOR_OPTION_WITH_MARSHALLING
4136 
4137   if (Opts.PCHWithHdrStop && !Opts.PCHWithHdrStopCreate)
4138     GenerateArg(Args, OPT_pch_through_hdrstop_use, SA);
4139 
4140   for (const auto &D : Opts.DeserializedPCHDeclsToErrorOn)
4141     GenerateArg(Args, OPT_error_on_deserialized_pch_decl, D, SA);
4142 
4143   if (Opts.PrecompiledPreambleBytes != std::make_pair(0u, false))
4144     GenerateArg(Args, OPT_preamble_bytes_EQ,
4145                 Twine(Opts.PrecompiledPreambleBytes.first) + "," +
4146                     (Opts.PrecompiledPreambleBytes.second ? "1" : "0"),
4147                 SA);
4148 
4149   for (const auto &M : Opts.Macros) {
4150     // Don't generate __CET__ macro definitions. They are implied by the
4151     // -fcf-protection option that is generated elsewhere.
4152     if (M.first == "__CET__=1" && !M.second &&
4153         !CodeGenOpts.CFProtectionReturn && CodeGenOpts.CFProtectionBranch)
4154       continue;
4155     if (M.first == "__CET__=2" && !M.second && CodeGenOpts.CFProtectionReturn &&
4156         !CodeGenOpts.CFProtectionBranch)
4157       continue;
4158     if (M.first == "__CET__=3" && !M.second && CodeGenOpts.CFProtectionReturn &&
4159         CodeGenOpts.CFProtectionBranch)
4160       continue;
4161 
4162     GenerateArg(Args, M.second ? OPT_U : OPT_D, M.first, SA);
4163   }
4164 
4165   for (const auto &I : Opts.Includes) {
4166     // Don't generate OpenCL includes. They are implied by other flags that are
4167     // generated elsewhere.
4168     if (LangOpts.OpenCL && LangOpts.IncludeDefaultHeader &&
4169         ((LangOpts.DeclareOpenCLBuiltins && I == "opencl-c-base.h") ||
4170          I == "opencl-c.h"))
4171       continue;
4172     // Don't generate HLSL includes. They are implied by other flags that are
4173     // generated elsewhere.
4174     if (LangOpts.HLSL && I == "hlsl.h")
4175       continue;
4176 
4177     GenerateArg(Args, OPT_include, I, SA);
4178   }
4179 
4180   for (const auto &CI : Opts.ChainedIncludes)
4181     GenerateArg(Args, OPT_chain_include, CI, SA);
4182 
4183   for (const auto &RF : Opts.RemappedFiles)
4184     GenerateArg(Args, OPT_remap_file, RF.first + ";" + RF.second, SA);
4185 
4186   if (Opts.SourceDateEpoch)
4187     GenerateArg(Args, OPT_source_date_epoch, Twine(*Opts.SourceDateEpoch), SA);
4188 
4189   // Don't handle LexEditorPlaceholders. It is implied by the action that is
4190   // generated elsewhere.
4191 }
4192 
4193 static bool ParsePreprocessorArgs(PreprocessorOptions &Opts, ArgList &Args,
4194                                   DiagnosticsEngine &Diags,
4195                                   frontend::ActionKind Action,
4196                                   const FrontendOptions &FrontendOpts) {
4197   unsigned NumErrorsBefore = Diags.getNumErrors();
4198 
4199   PreprocessorOptions *PreprocessorOpts = &Opts;
4200 
4201 #define PREPROCESSOR_OPTION_WITH_MARSHALLING(...)                              \
4202   PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
4203 #include "clang/Driver/Options.inc"
4204 #undef PREPROCESSOR_OPTION_WITH_MARSHALLING
4205 
4206   Opts.PCHWithHdrStop = Args.hasArg(OPT_pch_through_hdrstop_create) ||
4207                         Args.hasArg(OPT_pch_through_hdrstop_use);
4208 
4209   for (const auto *A : Args.filtered(OPT_error_on_deserialized_pch_decl))
4210     Opts.DeserializedPCHDeclsToErrorOn.insert(A->getValue());
4211 
4212   if (const Arg *A = Args.getLastArg(OPT_preamble_bytes_EQ)) {
4213     StringRef Value(A->getValue());
4214     size_t Comma = Value.find(',');
4215     unsigned Bytes = 0;
4216     unsigned EndOfLine = 0;
4217 
4218     if (Comma == StringRef::npos ||
4219         Value.substr(0, Comma).getAsInteger(10, Bytes) ||
4220         Value.substr(Comma + 1).getAsInteger(10, EndOfLine))
4221       Diags.Report(diag::err_drv_preamble_format);
4222     else {
4223       Opts.PrecompiledPreambleBytes.first = Bytes;
4224       Opts.PrecompiledPreambleBytes.second = (EndOfLine != 0);
4225     }
4226   }
4227 
4228   // Add the __CET__ macro if a CFProtection option is set.
4229   if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
4230     StringRef Name = A->getValue();
4231     if (Name == "branch")
4232       Opts.addMacroDef("__CET__=1");
4233     else if (Name == "return")
4234       Opts.addMacroDef("__CET__=2");
4235     else if (Name == "full")
4236       Opts.addMacroDef("__CET__=3");
4237   }
4238 
4239   // Add macros from the command line.
4240   for (const auto *A : Args.filtered(OPT_D, OPT_U)) {
4241     if (A->getOption().matches(OPT_D))
4242       Opts.addMacroDef(A->getValue());
4243     else
4244       Opts.addMacroUndef(A->getValue());
4245   }
4246 
4247   // Add the ordered list of -includes.
4248   for (const auto *A : Args.filtered(OPT_include))
4249     Opts.Includes.emplace_back(A->getValue());
4250 
4251   for (const auto *A : Args.filtered(OPT_chain_include))
4252     Opts.ChainedIncludes.emplace_back(A->getValue());
4253 
4254   for (const auto *A : Args.filtered(OPT_remap_file)) {
4255     std::pair<StringRef, StringRef> Split = StringRef(A->getValue()).split(';');
4256 
4257     if (Split.second.empty()) {
4258       Diags.Report(diag::err_drv_invalid_remap_file) << A->getAsString(Args);
4259       continue;
4260     }
4261 
4262     Opts.addRemappedFile(Split.first, Split.second);
4263   }
4264 
4265   if (const Arg *A = Args.getLastArg(OPT_source_date_epoch)) {
4266     StringRef Epoch = A->getValue();
4267     // SOURCE_DATE_EPOCH, if specified, must be a non-negative decimal integer.
4268     // On time64 systems, pick 253402300799 (the UNIX timestamp of
4269     // 9999-12-31T23:59:59Z) as the upper bound.
4270     const uint64_t MaxTimestamp =
4271         std::min<uint64_t>(std::numeric_limits<time_t>::max(), 253402300799);
4272     uint64_t V;
4273     if (Epoch.getAsInteger(10, V) || V > MaxTimestamp) {
4274       Diags.Report(diag::err_fe_invalid_source_date_epoch)
4275           << Epoch << MaxTimestamp;
4276     } else {
4277       Opts.SourceDateEpoch = V;
4278     }
4279   }
4280 
4281   // Always avoid lexing editor placeholders when we're just running the
4282   // preprocessor as we never want to emit the
4283   // "editor placeholder in source file" error in PP only mode.
4284   if (isStrictlyPreprocessorAction(Action))
4285     Opts.LexEditorPlaceholders = false;
4286 
4287   return Diags.getNumErrors() == NumErrorsBefore;
4288 }
4289 
4290 static void GeneratePreprocessorOutputArgs(
4291     const PreprocessorOutputOptions &Opts, SmallVectorImpl<const char *> &Args,
4292     CompilerInvocation::StringAllocator SA, frontend::ActionKind Action) {
4293   const PreprocessorOutputOptions &PreprocessorOutputOpts = Opts;
4294 
4295 #define PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING(...)                       \
4296   GENERATE_OPTION_WITH_MARSHALLING(Args, SA, __VA_ARGS__)
4297 #include "clang/Driver/Options.inc"
4298 #undef PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING
4299 
4300   bool Generate_dM = isStrictlyPreprocessorAction(Action) && !Opts.ShowCPP;
4301   if (Generate_dM)
4302     GenerateArg(Args, OPT_dM, SA);
4303   if (!Generate_dM && Opts.ShowMacros)
4304     GenerateArg(Args, OPT_dD, SA);
4305   if (Opts.DirectivesOnly)
4306     GenerateArg(Args, OPT_fdirectives_only, SA);
4307 }
4308 
4309 static bool ParsePreprocessorOutputArgs(PreprocessorOutputOptions &Opts,
4310                                         ArgList &Args, DiagnosticsEngine &Diags,
4311                                         frontend::ActionKind Action) {
4312   unsigned NumErrorsBefore = Diags.getNumErrors();
4313 
4314   PreprocessorOutputOptions &PreprocessorOutputOpts = Opts;
4315 
4316 #define PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING(...)                       \
4317   PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
4318 #include "clang/Driver/Options.inc"
4319 #undef PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING
4320 
4321   Opts.ShowCPP = isStrictlyPreprocessorAction(Action) && !Args.hasArg(OPT_dM);
4322   Opts.ShowMacros = Args.hasArg(OPT_dM) || Args.hasArg(OPT_dD);
4323   Opts.DirectivesOnly = Args.hasArg(OPT_fdirectives_only);
4324 
4325   return Diags.getNumErrors() == NumErrorsBefore;
4326 }
4327 
4328 static void GenerateTargetArgs(const TargetOptions &Opts,
4329                                SmallVectorImpl<const char *> &Args,
4330                                CompilerInvocation::StringAllocator SA) {
4331   const TargetOptions *TargetOpts = &Opts;
4332 #define TARGET_OPTION_WITH_MARSHALLING(...)                                    \
4333   GENERATE_OPTION_WITH_MARSHALLING(Args, SA, __VA_ARGS__)
4334 #include "clang/Driver/Options.inc"
4335 #undef TARGET_OPTION_WITH_MARSHALLING
4336 
4337   if (!Opts.SDKVersion.empty())
4338     GenerateArg(Args, OPT_target_sdk_version_EQ, Opts.SDKVersion.getAsString(),
4339                 SA);
4340   if (!Opts.DarwinTargetVariantSDKVersion.empty())
4341     GenerateArg(Args, OPT_darwin_target_variant_sdk_version_EQ,
4342                 Opts.DarwinTargetVariantSDKVersion.getAsString(), SA);
4343 }
4344 
4345 static bool ParseTargetArgs(TargetOptions &Opts, ArgList &Args,
4346                             DiagnosticsEngine &Diags) {
4347   unsigned NumErrorsBefore = Diags.getNumErrors();
4348 
4349   TargetOptions *TargetOpts = &Opts;
4350 
4351 #define TARGET_OPTION_WITH_MARSHALLING(...)                                    \
4352   PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
4353 #include "clang/Driver/Options.inc"
4354 #undef TARGET_OPTION_WITH_MARSHALLING
4355 
4356   if (Arg *A = Args.getLastArg(options::OPT_target_sdk_version_EQ)) {
4357     llvm::VersionTuple Version;
4358     if (Version.tryParse(A->getValue()))
4359       Diags.Report(diag::err_drv_invalid_value)
4360           << A->getAsString(Args) << A->getValue();
4361     else
4362       Opts.SDKVersion = Version;
4363   }
4364   if (Arg *A =
4365           Args.getLastArg(options::OPT_darwin_target_variant_sdk_version_EQ)) {
4366     llvm::VersionTuple Version;
4367     if (Version.tryParse(A->getValue()))
4368       Diags.Report(diag::err_drv_invalid_value)
4369           << A->getAsString(Args) << A->getValue();
4370     else
4371       Opts.DarwinTargetVariantSDKVersion = Version;
4372   }
4373 
4374   return Diags.getNumErrors() == NumErrorsBefore;
4375 }
4376 
4377 bool CompilerInvocation::CreateFromArgsImpl(
4378     CompilerInvocation &Res, ArrayRef<const char *> CommandLineArgs,
4379     DiagnosticsEngine &Diags, const char *Argv0) {
4380   unsigned NumErrorsBefore = Diags.getNumErrors();
4381 
4382   // Parse the arguments.
4383   const OptTable &Opts = getDriverOptTable();
4384   const unsigned IncludedFlagsBitmask = options::CC1Option;
4385   unsigned MissingArgIndex, MissingArgCount;
4386   InputArgList Args = Opts.ParseArgs(CommandLineArgs, MissingArgIndex,
4387                                      MissingArgCount, IncludedFlagsBitmask);
4388   LangOptions &LangOpts = *Res.getLangOpts();
4389 
4390   // Check for missing argument error.
4391   if (MissingArgCount)
4392     Diags.Report(diag::err_drv_missing_argument)
4393         << Args.getArgString(MissingArgIndex) << MissingArgCount;
4394 
4395   // Issue errors on unknown arguments.
4396   for (const auto *A : Args.filtered(OPT_UNKNOWN)) {
4397     auto ArgString = A->getAsString(Args);
4398     std::string Nearest;
4399     if (Opts.findNearest(ArgString, Nearest, IncludedFlagsBitmask) > 1)
4400       Diags.Report(diag::err_drv_unknown_argument) << ArgString;
4401     else
4402       Diags.Report(diag::err_drv_unknown_argument_with_suggestion)
4403           << ArgString << Nearest;
4404   }
4405 
4406   ParseFileSystemArgs(Res.getFileSystemOpts(), Args, Diags);
4407   ParseMigratorArgs(Res.getMigratorOpts(), Args, Diags);
4408   ParseAnalyzerArgs(*Res.getAnalyzerOpts(), Args, Diags);
4409   ParseDiagnosticArgs(Res.getDiagnosticOpts(), Args, &Diags,
4410                       /*DefaultDiagColor=*/false);
4411   ParseFrontendArgs(Res.getFrontendOpts(), Args, Diags, LangOpts.IsHeaderFile);
4412   // FIXME: We shouldn't have to pass the DashX option around here
4413   InputKind DashX = Res.getFrontendOpts().DashX;
4414   ParseTargetArgs(Res.getTargetOpts(), Args, Diags);
4415   llvm::Triple T(Res.getTargetOpts().Triple);
4416   ParseHeaderSearchArgs(Res.getHeaderSearchOpts(), Args, Diags,
4417                         Res.getFileSystemOpts().WorkingDir);
4418 
4419   ParseLangArgs(LangOpts, Args, DashX, T, Res.getPreprocessorOpts().Includes,
4420                 Diags);
4421   if (Res.getFrontendOpts().ProgramAction == frontend::RewriteObjC)
4422     LangOpts.ObjCExceptions = 1;
4423 
4424   for (auto Warning : Res.getDiagnosticOpts().Warnings) {
4425     if (Warning == "misexpect" &&
4426         !Diags.isIgnored(diag::warn_profile_data_misexpect, SourceLocation())) {
4427       Res.getCodeGenOpts().MisExpect = true;
4428     }
4429   }
4430 
4431   if (LangOpts.CUDA) {
4432     // During CUDA device-side compilation, the aux triple is the
4433     // triple used for host compilation.
4434     if (LangOpts.CUDAIsDevice)
4435       Res.getTargetOpts().HostTriple = Res.getFrontendOpts().AuxTriple;
4436   }
4437 
4438   // Set the triple of the host for OpenMP device compile.
4439   if (LangOpts.OpenMPIsTargetDevice)
4440     Res.getTargetOpts().HostTriple = Res.getFrontendOpts().AuxTriple;
4441 
4442   ParseCodeGenArgs(Res.getCodeGenOpts(), Args, DashX, Diags, T,
4443                    Res.getFrontendOpts().OutputFile, LangOpts);
4444 
4445   // FIXME: Override value name discarding when asan or msan is used because the
4446   // backend passes depend on the name of the alloca in order to print out
4447   // names.
4448   Res.getCodeGenOpts().DiscardValueNames &=
4449       !LangOpts.Sanitize.has(SanitizerKind::Address) &&
4450       !LangOpts.Sanitize.has(SanitizerKind::KernelAddress) &&
4451       !LangOpts.Sanitize.has(SanitizerKind::Memory) &&
4452       !LangOpts.Sanitize.has(SanitizerKind::KernelMemory);
4453 
4454   ParsePreprocessorArgs(Res.getPreprocessorOpts(), Args, Diags,
4455                         Res.getFrontendOpts().ProgramAction,
4456                         Res.getFrontendOpts());
4457   ParsePreprocessorOutputArgs(Res.getPreprocessorOutputOpts(), Args, Diags,
4458                               Res.getFrontendOpts().ProgramAction);
4459 
4460   ParseDependencyOutputArgs(Res.getDependencyOutputOpts(), Args, Diags,
4461                             Res.getFrontendOpts().ProgramAction,
4462                             Res.getPreprocessorOutputOpts().ShowLineMarkers);
4463   if (!Res.getDependencyOutputOpts().OutputFile.empty() &&
4464       Res.getDependencyOutputOpts().Targets.empty())
4465     Diags.Report(diag::err_fe_dependency_file_requires_MT);
4466 
4467   // If sanitizer is enabled, disable OPT_ffine_grained_bitfield_accesses.
4468   if (Res.getCodeGenOpts().FineGrainedBitfieldAccesses &&
4469       !Res.getLangOpts()->Sanitize.empty()) {
4470     Res.getCodeGenOpts().FineGrainedBitfieldAccesses = false;
4471     Diags.Report(diag::warn_drv_fine_grained_bitfield_accesses_ignored);
4472   }
4473 
4474   // Store the command-line for using in the CodeView backend.
4475   if (Res.getCodeGenOpts().CodeViewCommandLine) {
4476     Res.getCodeGenOpts().Argv0 = Argv0;
4477     append_range(Res.getCodeGenOpts().CommandLineArgs, CommandLineArgs);
4478   }
4479 
4480   // Set PGOOptions. Need to create a temporary VFS to read the profile
4481   // to determine the PGO type.
4482   if (!Res.getCodeGenOpts().ProfileInstrumentUsePath.empty()) {
4483     auto FS =
4484         createVFSFromOverlayFiles(Res.getHeaderSearchOpts().VFSOverlayFiles,
4485                                   Diags, llvm::vfs::getRealFileSystem());
4486     setPGOUseInstrumentor(Res.getCodeGenOpts(),
4487                           Res.getCodeGenOpts().ProfileInstrumentUsePath, *FS,
4488                           Diags);
4489   }
4490 
4491   FixupInvocation(Res, Diags, Args, DashX);
4492 
4493   return Diags.getNumErrors() == NumErrorsBefore;
4494 }
4495 
4496 bool CompilerInvocation::CreateFromArgs(CompilerInvocation &Invocation,
4497                                         ArrayRef<const char *> CommandLineArgs,
4498                                         DiagnosticsEngine &Diags,
4499                                         const char *Argv0) {
4500   CompilerInvocation DummyInvocation;
4501 
4502   return RoundTrip(
4503       [](CompilerInvocation &Invocation, ArrayRef<const char *> CommandLineArgs,
4504          DiagnosticsEngine &Diags, const char *Argv0) {
4505         return CreateFromArgsImpl(Invocation, CommandLineArgs, Diags, Argv0);
4506       },
4507       [](CompilerInvocation &Invocation, SmallVectorImpl<const char *> &Args,
4508          StringAllocator SA) {
4509         Args.push_back("-cc1");
4510         Invocation.generateCC1CommandLine(Args, SA);
4511       },
4512       Invocation, DummyInvocation, CommandLineArgs, Diags, Argv0);
4513 }
4514 
4515 std::string CompilerInvocation::getModuleHash() const {
4516   // FIXME: Consider using SHA1 instead of MD5.
4517   llvm::HashBuilder<llvm::MD5, llvm::support::endianness::native> HBuilder;
4518 
4519   // Note: For QoI reasons, the things we use as a hash here should all be
4520   // dumped via the -module-info flag.
4521 
4522   // Start the signature with the compiler version.
4523   HBuilder.add(getClangFullRepositoryVersion());
4524 
4525   // Also include the serialization version, in case LLVM_APPEND_VC_REV is off
4526   // and getClangFullRepositoryVersion() doesn't include git revision.
4527   HBuilder.add(serialization::VERSION_MAJOR, serialization::VERSION_MINOR);
4528 
4529   // Extend the signature with the language options
4530 #define LANGOPT(Name, Bits, Default, Description) HBuilder.add(LangOpts->Name);
4531 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description)                   \
4532   HBuilder.add(static_cast<unsigned>(LangOpts->get##Name()));
4533 #define BENIGN_LANGOPT(Name, Bits, Default, Description)
4534 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
4535 #include "clang/Basic/LangOptions.def"
4536 
4537   HBuilder.addRange(LangOpts->ModuleFeatures);
4538 
4539   HBuilder.add(LangOpts->ObjCRuntime);
4540   HBuilder.addRange(LangOpts->CommentOpts.BlockCommandNames);
4541 
4542   // Extend the signature with the target options.
4543   HBuilder.add(TargetOpts->Triple, TargetOpts->CPU, TargetOpts->TuneCPU,
4544                TargetOpts->ABI);
4545   HBuilder.addRange(TargetOpts->FeaturesAsWritten);
4546 
4547   // Extend the signature with preprocessor options.
4548   const PreprocessorOptions &ppOpts = getPreprocessorOpts();
4549   HBuilder.add(ppOpts.UsePredefines, ppOpts.DetailedRecord);
4550 
4551   const HeaderSearchOptions &hsOpts = getHeaderSearchOpts();
4552   for (const auto &Macro : getPreprocessorOpts().Macros) {
4553     // If we're supposed to ignore this macro for the purposes of modules,
4554     // don't put it into the hash.
4555     if (!hsOpts.ModulesIgnoreMacros.empty()) {
4556       // Check whether we're ignoring this macro.
4557       StringRef MacroDef = Macro.first;
4558       if (hsOpts.ModulesIgnoreMacros.count(
4559               llvm::CachedHashString(MacroDef.split('=').first)))
4560         continue;
4561     }
4562 
4563     HBuilder.add(Macro);
4564   }
4565 
4566   // Extend the signature with the sysroot and other header search options.
4567   HBuilder.add(hsOpts.Sysroot, hsOpts.ModuleFormat, hsOpts.UseDebugInfo,
4568                hsOpts.UseBuiltinIncludes, hsOpts.UseStandardSystemIncludes,
4569                hsOpts.UseStandardCXXIncludes, hsOpts.UseLibcxx,
4570                hsOpts.ModulesValidateDiagnosticOptions);
4571   HBuilder.add(hsOpts.ResourceDir);
4572 
4573   if (hsOpts.ModulesStrictContextHash) {
4574     HBuilder.addRange(hsOpts.SystemHeaderPrefixes);
4575     HBuilder.addRange(hsOpts.UserEntries);
4576 
4577     const DiagnosticOptions &diagOpts = getDiagnosticOpts();
4578 #define DIAGOPT(Name, Bits, Default) HBuilder.add(diagOpts.Name);
4579 #define ENUM_DIAGOPT(Name, Type, Bits, Default)                                \
4580   HBuilder.add(diagOpts.get##Name());
4581 #include "clang/Basic/DiagnosticOptions.def"
4582 #undef DIAGOPT
4583 #undef ENUM_DIAGOPT
4584   }
4585 
4586   // Extend the signature with the user build path.
4587   HBuilder.add(hsOpts.ModuleUserBuildPath);
4588 
4589   // Extend the signature with the module file extensions.
4590   for (const auto &ext : getFrontendOpts().ModuleFileExtensions)
4591     ext->hashExtension(HBuilder);
4592 
4593   // When compiling with -gmodules, also hash -fdebug-prefix-map as it
4594   // affects the debug info in the PCM.
4595   if (getCodeGenOpts().DebugTypeExtRefs)
4596     HBuilder.addRange(getCodeGenOpts().DebugPrefixMap);
4597 
4598   // Extend the signature with the enabled sanitizers, if at least one is
4599   // enabled. Sanitizers which cannot affect AST generation aren't hashed.
4600   SanitizerSet SanHash = LangOpts->Sanitize;
4601   SanHash.clear(getPPTransparentSanitizers());
4602   if (!SanHash.empty())
4603     HBuilder.add(SanHash.Mask);
4604 
4605   llvm::MD5::MD5Result Result;
4606   HBuilder.getHasher().final(Result);
4607   uint64_t Hash = Result.high() ^ Result.low();
4608   return toString(llvm::APInt(64, Hash), 36, /*Signed=*/false);
4609 }
4610 
4611 void CompilerInvocation::generateCC1CommandLine(
4612     SmallVectorImpl<const char *> &Args, StringAllocator SA) const {
4613   llvm::Triple T(TargetOpts->Triple);
4614 
4615   GenerateFileSystemArgs(FileSystemOpts, Args, SA);
4616   GenerateMigratorArgs(MigratorOpts, Args, SA);
4617   GenerateAnalyzerArgs(*AnalyzerOpts, Args, SA);
4618   GenerateDiagnosticArgs(*DiagnosticOpts, Args, SA, false);
4619   GenerateFrontendArgs(FrontendOpts, Args, SA, LangOpts->IsHeaderFile);
4620   GenerateTargetArgs(*TargetOpts, Args, SA);
4621   GenerateHeaderSearchArgs(*HeaderSearchOpts, Args, SA);
4622   GenerateLangArgs(*LangOpts, Args, SA, T, FrontendOpts.DashX);
4623   GenerateCodeGenArgs(CodeGenOpts, Args, SA, T, FrontendOpts.OutputFile,
4624                       &*LangOpts);
4625   GeneratePreprocessorArgs(*PreprocessorOpts, Args, SA, *LangOpts, FrontendOpts,
4626                            CodeGenOpts);
4627   GeneratePreprocessorOutputArgs(PreprocessorOutputOpts, Args, SA,
4628                                  FrontendOpts.ProgramAction);
4629   GenerateDependencyOutputArgs(DependencyOutputOpts, Args, SA);
4630 }
4631 
4632 std::vector<std::string> CompilerInvocation::getCC1CommandLine() const {
4633   // Set up string allocator.
4634   llvm::BumpPtrAllocator Alloc;
4635   llvm::StringSaver Strings(Alloc);
4636   auto SA = [&Strings](const Twine &Arg) { return Strings.save(Arg).data(); };
4637 
4638   // Synthesize full command line from the CompilerInvocation, including "-cc1".
4639   SmallVector<const char *, 32> Args{"-cc1"};
4640   generateCC1CommandLine(Args, SA);
4641 
4642   // Convert arguments to the return type.
4643   return std::vector<std::string>{Args.begin(), Args.end()};
4644 }
4645 
4646 void CompilerInvocation::resetNonModularOptions() {
4647   getLangOpts()->resetNonModularOptions();
4648   getPreprocessorOpts().resetNonModularOptions();
4649 }
4650 
4651 void CompilerInvocation::clearImplicitModuleBuildOptions() {
4652   getLangOpts()->ImplicitModules = false;
4653   getHeaderSearchOpts().ImplicitModuleMaps = false;
4654   getHeaderSearchOpts().ModuleCachePath.clear();
4655   getHeaderSearchOpts().ModulesValidateOncePerBuildSession = false;
4656   getHeaderSearchOpts().BuildSessionTimestamp = 0;
4657   // The specific values we canonicalize to for pruning don't affect behaviour,
4658   /// so use the default values so they may be dropped from the command-line.
4659   getHeaderSearchOpts().ModuleCachePruneInterval = 7 * 24 * 60 * 60;
4660   getHeaderSearchOpts().ModuleCachePruneAfter = 31 * 24 * 60 * 60;
4661 }
4662 
4663 IntrusiveRefCntPtr<llvm::vfs::FileSystem>
4664 clang::createVFSFromCompilerInvocation(const CompilerInvocation &CI,
4665                                        DiagnosticsEngine &Diags) {
4666   return createVFSFromCompilerInvocation(CI, Diags,
4667                                          llvm::vfs::getRealFileSystem());
4668 }
4669 
4670 IntrusiveRefCntPtr<llvm::vfs::FileSystem>
4671 clang::createVFSFromCompilerInvocation(
4672     const CompilerInvocation &CI, DiagnosticsEngine &Diags,
4673     IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS) {
4674   return createVFSFromOverlayFiles(CI.getHeaderSearchOpts().VFSOverlayFiles,
4675                                    Diags, std::move(BaseFS));
4676 }
4677 
4678 IntrusiveRefCntPtr<llvm::vfs::FileSystem> clang::createVFSFromOverlayFiles(
4679     ArrayRef<std::string> VFSOverlayFiles, DiagnosticsEngine &Diags,
4680     IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS) {
4681   if (VFSOverlayFiles.empty())
4682     return BaseFS;
4683 
4684   IntrusiveRefCntPtr<llvm::vfs::FileSystem> Result = BaseFS;
4685   // earlier vfs files are on the bottom
4686   for (const auto &File : VFSOverlayFiles) {
4687     llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer =
4688         Result->getBufferForFile(File);
4689     if (!Buffer) {
4690       Diags.Report(diag::err_missing_vfs_overlay_file) << File;
4691       continue;
4692     }
4693 
4694     IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS = llvm::vfs::getVFSFromYAML(
4695         std::move(Buffer.get()), /*DiagHandler*/ nullptr, File,
4696         /*DiagContext*/ nullptr, Result);
4697     if (!FS) {
4698       Diags.Report(diag::err_invalid_vfs_overlay) << File;
4699       continue;
4700     }
4701 
4702     Result = FS;
4703   }
4704   return Result;
4705 }
4706