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