xref: /llvm-project/clang/lib/Frontend/CompilerInvocation.cpp (revision dfb558b82d3f2ca228799b03d2be00b163d04ea5)
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/Utils.h"
42 #include "clang/Lex/HeaderSearchOptions.h"
43 #include "clang/Lex/PreprocessorOptions.h"
44 #include "clang/Sema/CodeCompleteOptions.h"
45 #include "clang/Serialization/ASTBitCodes.h"
46 #include "clang/Serialization/ModuleFileExtension.h"
47 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
48 #include "llvm/ADT/APInt.h"
49 #include "llvm/ADT/ArrayRef.h"
50 #include "llvm/ADT/CachedHashString.h"
51 #include "llvm/ADT/FloatingPointMode.h"
52 #include "llvm/ADT/Hashing.h"
53 #include "llvm/ADT/None.h"
54 #include "llvm/ADT/Optional.h"
55 #include "llvm/ADT/SmallString.h"
56 #include "llvm/ADT/SmallVector.h"
57 #include "llvm/ADT/StringRef.h"
58 #include "llvm/ADT/StringSwitch.h"
59 #include "llvm/ADT/Triple.h"
60 #include "llvm/ADT/Twine.h"
61 #include "llvm/Config/llvm-config.h"
62 #include "llvm/IR/DebugInfoMetadata.h"
63 #include "llvm/Linker/Linker.h"
64 #include "llvm/MC/MCTargetOptions.h"
65 #include "llvm/Option/Arg.h"
66 #include "llvm/Option/ArgList.h"
67 #include "llvm/Option/OptSpecifier.h"
68 #include "llvm/Option/OptTable.h"
69 #include "llvm/Option/Option.h"
70 #include "llvm/ProfileData/InstrProfReader.h"
71 #include "llvm/Remarks/HotnessThresholdParser.h"
72 #include "llvm/Support/CodeGen.h"
73 #include "llvm/Support/Compiler.h"
74 #include "llvm/Support/Error.h"
75 #include "llvm/Support/ErrorHandling.h"
76 #include "llvm/Support/ErrorOr.h"
77 #include "llvm/Support/FileSystem.h"
78 #include "llvm/Support/Host.h"
79 #include "llvm/Support/MathExtras.h"
80 #include "llvm/Support/MemoryBuffer.h"
81 #include "llvm/Support/Path.h"
82 #include "llvm/Support/Process.h"
83 #include "llvm/Support/Regex.h"
84 #include "llvm/Support/VersionTuple.h"
85 #include "llvm/Support/VirtualFileSystem.h"
86 #include "llvm/Support/raw_ostream.h"
87 #include "llvm/Target/TargetOptions.h"
88 #include <algorithm>
89 #include <atomic>
90 #include <cassert>
91 #include <cstddef>
92 #include <cstring>
93 #include <memory>
94 #include <string>
95 #include <tuple>
96 #include <type_traits>
97 #include <utility>
98 #include <vector>
99 
100 using namespace clang;
101 using namespace driver;
102 using namespace options;
103 using namespace llvm::opt;
104 
105 //===----------------------------------------------------------------------===//
106 // Initialization.
107 //===----------------------------------------------------------------------===//
108 
109 CompilerInvocationBase::CompilerInvocationBase()
110     : LangOpts(new LangOptions()), TargetOpts(new TargetOptions()),
111       DiagnosticOpts(new DiagnosticOptions()),
112       HeaderSearchOpts(new HeaderSearchOptions()),
113       PreprocessorOpts(new PreprocessorOptions()) {}
114 
115 CompilerInvocationBase::CompilerInvocationBase(const CompilerInvocationBase &X)
116     : LangOpts(new LangOptions(*X.getLangOpts())),
117       TargetOpts(new TargetOptions(X.getTargetOpts())),
118       DiagnosticOpts(new DiagnosticOptions(X.getDiagnosticOpts())),
119       HeaderSearchOpts(new HeaderSearchOptions(X.getHeaderSearchOpts())),
120       PreprocessorOpts(new PreprocessorOptions(X.getPreprocessorOpts())) {}
121 
122 CompilerInvocationBase::~CompilerInvocationBase() = default;
123 
124 //===----------------------------------------------------------------------===//
125 // Normalizers
126 //===----------------------------------------------------------------------===//
127 
128 #define SIMPLE_ENUM_VALUE_TABLE
129 #include "clang/Driver/Options.inc"
130 #undef SIMPLE_ENUM_VALUE_TABLE
131 
132 static llvm::Optional<bool>
133 normalizeSimpleFlag(OptSpecifier Opt, unsigned TableIndex, const ArgList &Args,
134                     DiagnosticsEngine &Diags, bool &Success) {
135   if (Args.hasArg(Opt))
136     return true;
137   return None;
138 }
139 
140 static Optional<bool> normalizeSimpleNegativeFlag(OptSpecifier Opt, unsigned,
141                                                   const ArgList &Args,
142                                                   DiagnosticsEngine &,
143                                                   bool &Success) {
144   if (Args.hasArg(Opt))
145     return false;
146   return None;
147 }
148 
149 /// The tblgen-erated code passes in a fifth parameter of an arbitrary type, but
150 /// denormalizeSimpleFlags never looks at it. Avoid bloating compile-time with
151 /// unnecessary template instantiations and just ignore it with a variadic
152 /// argument.
153 static void denormalizeSimpleFlag(SmallVectorImpl<const char *> &Args,
154                                   const char *Spelling,
155                                   CompilerInvocation::StringAllocator,
156                                   Option::OptionClass, unsigned, /*T*/...) {
157   Args.push_back(Spelling);
158 }
159 
160 template <typename T> static constexpr bool is_uint64_t_convertible() {
161   return !std::is_same<T, uint64_t>::value &&
162          llvm::is_integral_or_enum<T>::value;
163 }
164 
165 template <typename T,
166           std::enable_if_t<!is_uint64_t_convertible<T>(), bool> = false>
167 static auto makeFlagToValueNormalizer(T Value) {
168   return [Value](OptSpecifier Opt, unsigned, const ArgList &Args,
169                  DiagnosticsEngine &, bool &Success) -> Optional<T> {
170     if (Args.hasArg(Opt))
171       return Value;
172     return None;
173   };
174 }
175 
176 template <typename T,
177           std::enable_if_t<is_uint64_t_convertible<T>(), bool> = false>
178 static auto makeFlagToValueNormalizer(T Value) {
179   return makeFlagToValueNormalizer(uint64_t(Value));
180 }
181 
182 static auto makeBooleanOptionNormalizer(bool Value, bool OtherValue,
183                                         OptSpecifier OtherOpt) {
184   return [Value, OtherValue, OtherOpt](OptSpecifier Opt, unsigned,
185                                        const ArgList &Args, DiagnosticsEngine &,
186                                        bool &Success) -> Optional<bool> {
187     if (const Arg *A = Args.getLastArg(Opt, OtherOpt)) {
188       return A->getOption().matches(Opt) ? Value : OtherValue;
189     }
190     return None;
191   };
192 }
193 
194 static auto makeBooleanOptionDenormalizer(bool Value) {
195   return [Value](SmallVectorImpl<const char *> &Args, const char *Spelling,
196                  CompilerInvocation::StringAllocator, Option::OptionClass,
197                  unsigned, bool KeyPath) {
198     if (KeyPath == Value)
199       Args.push_back(Spelling);
200   };
201 }
202 
203 static void denormalizeStringImpl(SmallVectorImpl<const char *> &Args,
204                                   const char *Spelling,
205                                   CompilerInvocation::StringAllocator SA,
206                                   Option::OptionClass OptClass, unsigned,
207                                   Twine Value) {
208   switch (OptClass) {
209   case Option::SeparateClass:
210   case Option::JoinedOrSeparateClass:
211     Args.push_back(Spelling);
212     Args.push_back(SA(Value));
213     break;
214   case Option::JoinedClass:
215     Args.push_back(SA(Twine(Spelling) + Value));
216     break;
217   default:
218     llvm_unreachable("Cannot denormalize an option with option class "
219                      "incompatible with string denormalization.");
220   }
221 }
222 
223 template <typename T>
224 static void
225 denormalizeString(SmallVectorImpl<const char *> &Args, const char *Spelling,
226                   CompilerInvocation::StringAllocator SA,
227                   Option::OptionClass OptClass, unsigned TableIndex, T Value) {
228   denormalizeStringImpl(Args, Spelling, SA, OptClass, TableIndex, Twine(Value));
229 }
230 
231 static Optional<SimpleEnumValue>
232 findValueTableByName(const SimpleEnumValueTable &Table, StringRef Name) {
233   for (int I = 0, E = Table.Size; I != E; ++I)
234     if (Name == Table.Table[I].Name)
235       return Table.Table[I];
236 
237   return None;
238 }
239 
240 static Optional<SimpleEnumValue>
241 findValueTableByValue(const SimpleEnumValueTable &Table, unsigned Value) {
242   for (int I = 0, E = Table.Size; I != E; ++I)
243     if (Value == Table.Table[I].Value)
244       return Table.Table[I];
245 
246   return None;
247 }
248 
249 static llvm::Optional<unsigned>
250 normalizeSimpleEnum(OptSpecifier Opt, unsigned TableIndex, const ArgList &Args,
251                     DiagnosticsEngine &Diags, bool &Success) {
252   assert(TableIndex < SimpleEnumValueTablesSize);
253   const SimpleEnumValueTable &Table = SimpleEnumValueTables[TableIndex];
254 
255   auto *Arg = Args.getLastArg(Opt);
256   if (!Arg)
257     return None;
258 
259   StringRef ArgValue = Arg->getValue();
260   if (auto MaybeEnumVal = findValueTableByName(Table, ArgValue))
261     return MaybeEnumVal->Value;
262 
263   Success = false;
264   Diags.Report(diag::err_drv_invalid_value)
265       << Arg->getAsString(Args) << ArgValue;
266   return None;
267 }
268 
269 static void denormalizeSimpleEnumImpl(SmallVectorImpl<const char *> &Args,
270                                       const char *Spelling,
271                                       CompilerInvocation::StringAllocator SA,
272                                       Option::OptionClass OptClass,
273                                       unsigned TableIndex, unsigned Value) {
274   assert(TableIndex < SimpleEnumValueTablesSize);
275   const SimpleEnumValueTable &Table = SimpleEnumValueTables[TableIndex];
276   if (auto MaybeEnumVal = findValueTableByValue(Table, Value)) {
277     denormalizeString(Args, Spelling, SA, OptClass, TableIndex,
278                       MaybeEnumVal->Name);
279   } else {
280     llvm_unreachable("The simple enum value was not correctly defined in "
281                      "the tablegen option description");
282   }
283 }
284 
285 template <typename T>
286 static void denormalizeSimpleEnum(SmallVectorImpl<const char *> &Args,
287                                   const char *Spelling,
288                                   CompilerInvocation::StringAllocator SA,
289                                   Option::OptionClass OptClass,
290                                   unsigned TableIndex, T Value) {
291   return denormalizeSimpleEnumImpl(Args, Spelling, SA, OptClass, TableIndex,
292                                    static_cast<unsigned>(Value));
293 }
294 
295 static Optional<std::string> normalizeString(OptSpecifier Opt, int TableIndex,
296                                              const ArgList &Args,
297                                              DiagnosticsEngine &Diags,
298                                              bool &Success) {
299   auto *Arg = Args.getLastArg(Opt);
300   if (!Arg)
301     return None;
302   return std::string(Arg->getValue());
303 }
304 
305 template <typename IntTy>
306 static Optional<IntTy>
307 normalizeStringIntegral(OptSpecifier Opt, int, const ArgList &Args,
308                         DiagnosticsEngine &Diags, bool &Success) {
309   auto *Arg = Args.getLastArg(Opt);
310   if (!Arg)
311     return None;
312   IntTy Res;
313   if (StringRef(Arg->getValue()).getAsInteger(0, Res)) {
314     Success = false;
315     Diags.Report(diag::err_drv_invalid_int_value)
316         << Arg->getAsString(Args) << Arg->getValue();
317     return None;
318   }
319   return Res;
320 }
321 
322 static Optional<std::vector<std::string>>
323 normalizeStringVector(OptSpecifier Opt, int, const ArgList &Args,
324                       DiagnosticsEngine &, bool &Success) {
325   return Args.getAllArgValues(Opt);
326 }
327 
328 static void denormalizeStringVector(SmallVectorImpl<const char *> &Args,
329                                     const char *Spelling,
330                                     CompilerInvocation::StringAllocator SA,
331                                     Option::OptionClass OptClass,
332                                     unsigned TableIndex,
333                                     const std::vector<std::string> &Values) {
334   switch (OptClass) {
335   case Option::CommaJoinedClass: {
336     std::string CommaJoinedValue;
337     if (!Values.empty()) {
338       CommaJoinedValue.append(Values.front());
339       for (const std::string &Value : llvm::drop_begin(Values, 1)) {
340         CommaJoinedValue.append(",");
341         CommaJoinedValue.append(Value);
342       }
343     }
344     denormalizeString(Args, Spelling, SA, Option::OptionClass::JoinedClass,
345                       TableIndex, CommaJoinedValue);
346     break;
347   }
348   case Option::JoinedClass:
349   case Option::SeparateClass:
350   case Option::JoinedOrSeparateClass:
351     for (const std::string &Value : Values)
352       denormalizeString(Args, Spelling, SA, OptClass, TableIndex, Value);
353     break;
354   default:
355     llvm_unreachable("Cannot denormalize an option with option class "
356                      "incompatible with string vector denormalization.");
357   }
358 }
359 
360 static Optional<std::string> normalizeTriple(OptSpecifier Opt, int TableIndex,
361                                              const ArgList &Args,
362                                              DiagnosticsEngine &Diags,
363                                              bool &Success) {
364   auto *Arg = Args.getLastArg(Opt);
365   if (!Arg)
366     return None;
367   return llvm::Triple::normalize(Arg->getValue());
368 }
369 
370 template <typename T, typename U>
371 static T mergeForwardValue(T KeyPath, U Value) {
372   return static_cast<T>(Value);
373 }
374 
375 template <typename T, typename U> static T mergeMaskValue(T KeyPath, U Value) {
376   return KeyPath | Value;
377 }
378 
379 template <typename T> static T extractForwardValue(T KeyPath) {
380   return KeyPath;
381 }
382 
383 template <typename T, typename U, U Value>
384 static T extractMaskValue(T KeyPath) {
385   return KeyPath & Value;
386 }
387 
388 #define PARSE_OPTION_WITH_MARSHALLING(ARGS, DIAGS, SUCCESS, ID, FLAGS, PARAM,  \
389                                       SHOULD_PARSE, KEYPATH, DEFAULT_VALUE,    \
390                                       IMPLIED_CHECK, IMPLIED_VALUE,            \
391                                       NORMALIZER, MERGER, TABLE_INDEX)         \
392   if ((FLAGS)&options::CC1Option) {                                            \
393     KEYPATH = MERGER(KEYPATH, DEFAULT_VALUE);                                  \
394     if (IMPLIED_CHECK)                                                         \
395       KEYPATH = MERGER(KEYPATH, IMPLIED_VALUE);                                \
396     if (SHOULD_PARSE)                                                          \
397       if (auto MaybeValue =                                                    \
398               NORMALIZER(OPT_##ID, TABLE_INDEX, ARGS, DIAGS, SUCCESS))         \
399         KEYPATH =                                                              \
400             MERGER(KEYPATH, static_cast<decltype(KEYPATH)>(*MaybeValue));      \
401   }
402 
403 static const StringRef GetInputKindName(InputKind IK);
404 
405 static void FixupInvocation(CompilerInvocation &Invocation,
406                             DiagnosticsEngine &Diags, const InputArgList &Args,
407                             InputKind IK) {
408   LangOptions &LangOpts = *Invocation.getLangOpts();
409   CodeGenOptions &CodeGenOpts = Invocation.getCodeGenOpts();
410   TargetOptions &TargetOpts = Invocation.getTargetOpts();
411   FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
412   CodeGenOpts.XRayInstrumentFunctions = LangOpts.XRayInstrument;
413   CodeGenOpts.XRayAlwaysEmitCustomEvents = LangOpts.XRayAlwaysEmitCustomEvents;
414   CodeGenOpts.XRayAlwaysEmitTypedEvents = LangOpts.XRayAlwaysEmitTypedEvents;
415   CodeGenOpts.DisableFree = FrontendOpts.DisableFree;
416   FrontendOpts.GenerateGlobalModuleIndex = FrontendOpts.UseGlobalModuleIndex;
417 
418   LangOpts.ForceEmitVTables = CodeGenOpts.ForceEmitVTables;
419   LangOpts.SpeculativeLoadHardening = CodeGenOpts.SpeculativeLoadHardening;
420   LangOpts.CurrentModule = LangOpts.ModuleName;
421 
422   llvm::Triple T(TargetOpts.Triple);
423   llvm::Triple::ArchType Arch = T.getArch();
424 
425   CodeGenOpts.CodeModel = TargetOpts.CodeModel;
426 
427   if (LangOpts.getExceptionHandling() != llvm::ExceptionHandling::None &&
428       T.isWindowsMSVCEnvironment())
429     Diags.Report(diag::err_fe_invalid_exception_model)
430         << static_cast<unsigned>(LangOpts.getExceptionHandling()) << T.str();
431 
432   if (LangOpts.AppleKext && !LangOpts.CPlusPlus)
433     Diags.Report(diag::warn_c_kext);
434 
435   if (Args.hasArg(OPT_fconcepts_ts))
436     Diags.Report(diag::warn_fe_concepts_ts_flag);
437 
438   if (LangOpts.NewAlignOverride &&
439       !llvm::isPowerOf2_32(LangOpts.NewAlignOverride)) {
440     Arg *A = Args.getLastArg(OPT_fnew_alignment_EQ);
441     Diags.Report(diag::err_fe_invalid_alignment)
442         << A->getAsString(Args) << A->getValue();
443     LangOpts.NewAlignOverride = 0;
444   }
445 
446   if (Args.hasArg(OPT_fgnu89_inline) && LangOpts.CPlusPlus)
447     Diags.Report(diag::err_drv_argument_not_allowed_with)
448         << "-fgnu89-inline" << GetInputKindName(IK);
449 
450   if (Args.hasArg(OPT_fgpu_allow_device_init) && !LangOpts.HIP)
451     Diags.Report(diag::warn_ignored_hip_only_option)
452         << Args.getLastArg(OPT_fgpu_allow_device_init)->getAsString(Args);
453 
454   if (Args.hasArg(OPT_gpu_max_threads_per_block_EQ) && !LangOpts.HIP)
455     Diags.Report(diag::warn_ignored_hip_only_option)
456         << Args.getLastArg(OPT_gpu_max_threads_per_block_EQ)->getAsString(Args);
457 
458   // -cl-strict-aliasing needs to emit diagnostic in the case where CL > 1.0.
459   // This option should be deprecated for CL > 1.0 because
460   // this option was added for compatibility with OpenCL 1.0.
461   if (Args.getLastArg(OPT_cl_strict_aliasing) && LangOpts.OpenCLVersion > 100)
462     Diags.Report(diag::warn_option_invalid_ocl_version)
463         << LangOpts.getOpenCLVersionTuple().getAsString()
464         << Args.getLastArg(OPT_cl_strict_aliasing)->getAsString(Args);
465 
466   if (Arg *A = Args.getLastArg(OPT_fdefault_calling_conv_EQ)) {
467     auto DefaultCC = LangOpts.getDefaultCallingConv();
468 
469     bool emitError = (DefaultCC == LangOptions::DCC_FastCall ||
470                       DefaultCC == LangOptions::DCC_StdCall) &&
471                      Arch != llvm::Triple::x86;
472     emitError |= (DefaultCC == LangOptions::DCC_VectorCall ||
473                   DefaultCC == LangOptions::DCC_RegCall) &&
474                  !T.isX86();
475     if (emitError)
476       Diags.Report(diag::err_drv_argument_not_allowed_with)
477           << A->getSpelling() << T.getTriple();
478   }
479 
480   if (!CodeGenOpts.ProfileRemappingFile.empty() && CodeGenOpts.LegacyPassManager)
481     Diags.Report(diag::err_drv_argument_only_allowed_with)
482         << Args.getLastArg(OPT_fprofile_remapping_file_EQ)->getAsString(Args)
483         << "-fno-legacy-pass-manager";
484 }
485 
486 //===----------------------------------------------------------------------===//
487 // Deserialization (from args)
488 //===----------------------------------------------------------------------===//
489 
490 static unsigned getOptimizationLevel(ArgList &Args, InputKind IK,
491                                      DiagnosticsEngine &Diags) {
492   unsigned DefaultOpt = llvm::CodeGenOpt::None;
493   if (IK.getLanguage() == Language::OpenCL && !Args.hasArg(OPT_cl_opt_disable))
494     DefaultOpt = llvm::CodeGenOpt::Default;
495 
496   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
497     if (A->getOption().matches(options::OPT_O0))
498       return llvm::CodeGenOpt::None;
499 
500     if (A->getOption().matches(options::OPT_Ofast))
501       return llvm::CodeGenOpt::Aggressive;
502 
503     assert(A->getOption().matches(options::OPT_O));
504 
505     StringRef S(A->getValue());
506     if (S == "s" || S == "z")
507       return llvm::CodeGenOpt::Default;
508 
509     if (S == "g")
510       return llvm::CodeGenOpt::Less;
511 
512     return getLastArgIntValue(Args, OPT_O, DefaultOpt, Diags);
513   }
514 
515   return DefaultOpt;
516 }
517 
518 static unsigned getOptimizationLevelSize(ArgList &Args) {
519   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
520     if (A->getOption().matches(options::OPT_O)) {
521       switch (A->getValue()[0]) {
522       default:
523         return 0;
524       case 's':
525         return 1;
526       case 'z':
527         return 2;
528       }
529     }
530   }
531   return 0;
532 }
533 
534 static std::string GetOptName(llvm::opt::OptSpecifier OptSpecifier) {
535   static const OptTable &OptTable = getDriverOptTable();
536   return OptTable.getOption(OptSpecifier).getPrefixedName();
537 }
538 
539 static void addDiagnosticArgs(ArgList &Args, OptSpecifier Group,
540                               OptSpecifier GroupWithValue,
541                               std::vector<std::string> &Diagnostics) {
542   for (auto *A : Args.filtered(Group)) {
543     if (A->getOption().getKind() == Option::FlagClass) {
544       // The argument is a pure flag (such as OPT_Wall or OPT_Wdeprecated). Add
545       // its name (minus the "W" or "R" at the beginning) to the warning list.
546       Diagnostics.push_back(
547           std::string(A->getOption().getName().drop_front(1)));
548     } else if (A->getOption().matches(GroupWithValue)) {
549       // This is -Wfoo= or -Rfoo=, where foo is the name of the diagnostic group.
550       Diagnostics.push_back(
551           std::string(A->getOption().getName().drop_front(1).rtrim("=-")));
552     } else {
553       // Otherwise, add its value (for OPT_W_Joined and similar).
554       for (const auto *Arg : A->getValues())
555         Diagnostics.emplace_back(Arg);
556     }
557   }
558 }
559 
560 // Parse the Static Analyzer configuration. If \p Diags is set to nullptr,
561 // it won't verify the input.
562 static void parseAnalyzerConfigs(AnalyzerOptions &AnOpts,
563                                  DiagnosticsEngine *Diags);
564 
565 static void getAllNoBuiltinFuncValues(ArgList &Args,
566                                       std::vector<std::string> &Funcs) {
567   SmallVector<const char *, 8> Values;
568   for (const auto &Arg : Args) {
569     const Option &O = Arg->getOption();
570     if (O.matches(options::OPT_fno_builtin_)) {
571       const char *FuncName = Arg->getValue();
572       if (Builtin::Context::isBuiltinFunc(FuncName))
573         Values.push_back(FuncName);
574     }
575   }
576   Funcs.insert(Funcs.end(), Values.begin(), Values.end());
577 }
578 
579 static bool ParseAnalyzerArgs(AnalyzerOptions &Opts, ArgList &Args,
580                               DiagnosticsEngine &Diags) {
581   bool Success = true;
582   if (Arg *A = Args.getLastArg(OPT_analyzer_store)) {
583     StringRef Name = A->getValue();
584     AnalysisStores Value = llvm::StringSwitch<AnalysisStores>(Name)
585 #define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN) \
586       .Case(CMDFLAG, NAME##Model)
587 #include "clang/StaticAnalyzer/Core/Analyses.def"
588       .Default(NumStores);
589     if (Value == NumStores) {
590       Diags.Report(diag::err_drv_invalid_value)
591         << A->getAsString(Args) << Name;
592       Success = false;
593     } else {
594       Opts.AnalysisStoreOpt = Value;
595     }
596   }
597 
598   if (Arg *A = Args.getLastArg(OPT_analyzer_constraints)) {
599     StringRef Name = A->getValue();
600     AnalysisConstraints Value = llvm::StringSwitch<AnalysisConstraints>(Name)
601 #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) \
602       .Case(CMDFLAG, NAME##Model)
603 #include "clang/StaticAnalyzer/Core/Analyses.def"
604       .Default(NumConstraints);
605     if (Value == NumConstraints) {
606       Diags.Report(diag::err_drv_invalid_value)
607         << A->getAsString(Args) << Name;
608       Success = false;
609     } else {
610       Opts.AnalysisConstraintsOpt = Value;
611     }
612   }
613 
614   if (Arg *A = Args.getLastArg(OPT_analyzer_output)) {
615     StringRef Name = A->getValue();
616     AnalysisDiagClients Value = llvm::StringSwitch<AnalysisDiagClients>(Name)
617 #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN) \
618       .Case(CMDFLAG, PD_##NAME)
619 #include "clang/StaticAnalyzer/Core/Analyses.def"
620       .Default(NUM_ANALYSIS_DIAG_CLIENTS);
621     if (Value == NUM_ANALYSIS_DIAG_CLIENTS) {
622       Diags.Report(diag::err_drv_invalid_value)
623         << A->getAsString(Args) << Name;
624       Success = false;
625     } else {
626       Opts.AnalysisDiagOpt = Value;
627     }
628   }
629 
630   if (Arg *A = Args.getLastArg(OPT_analyzer_purge)) {
631     StringRef Name = A->getValue();
632     AnalysisPurgeMode Value = llvm::StringSwitch<AnalysisPurgeMode>(Name)
633 #define ANALYSIS_PURGE(NAME, CMDFLAG, DESC) \
634       .Case(CMDFLAG, NAME)
635 #include "clang/StaticAnalyzer/Core/Analyses.def"
636       .Default(NumPurgeModes);
637     if (Value == NumPurgeModes) {
638       Diags.Report(diag::err_drv_invalid_value)
639         << A->getAsString(Args) << Name;
640       Success = false;
641     } else {
642       Opts.AnalysisPurgeOpt = Value;
643     }
644   }
645 
646   if (Arg *A = Args.getLastArg(OPT_analyzer_inlining_mode)) {
647     StringRef Name = A->getValue();
648     AnalysisInliningMode Value = llvm::StringSwitch<AnalysisInliningMode>(Name)
649 #define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC) \
650       .Case(CMDFLAG, NAME)
651 #include "clang/StaticAnalyzer/Core/Analyses.def"
652       .Default(NumInliningModes);
653     if (Value == NumInliningModes) {
654       Diags.Report(diag::err_drv_invalid_value)
655         << A->getAsString(Args) << Name;
656       Success = false;
657     } else {
658       Opts.InliningMode = Value;
659     }
660   }
661 
662   Opts.CheckersAndPackages.clear();
663   for (const Arg *A :
664        Args.filtered(OPT_analyzer_checker, OPT_analyzer_disable_checker)) {
665     A->claim();
666     bool IsEnabled = A->getOption().getID() == OPT_analyzer_checker;
667     // We can have a list of comma separated checker names, e.g:
668     // '-analyzer-checker=cocoa,unix'
669     StringRef CheckerAndPackageList = A->getValue();
670     SmallVector<StringRef, 16> CheckersAndPackages;
671     CheckerAndPackageList.split(CheckersAndPackages, ",");
672     for (const StringRef &CheckerOrPackage : CheckersAndPackages)
673       Opts.CheckersAndPackages.emplace_back(std::string(CheckerOrPackage),
674                                             IsEnabled);
675   }
676 
677   // Go through the analyzer configuration options.
678   for (const auto *A : Args.filtered(OPT_analyzer_config)) {
679 
680     // We can have a list of comma separated config names, e.g:
681     // '-analyzer-config key1=val1,key2=val2'
682     StringRef configList = A->getValue();
683     SmallVector<StringRef, 4> configVals;
684     configList.split(configVals, ",");
685     for (const auto &configVal : configVals) {
686       StringRef key, val;
687       std::tie(key, val) = configVal.split("=");
688       if (val.empty()) {
689         Diags.Report(SourceLocation(),
690                      diag::err_analyzer_config_no_value) << configVal;
691         Success = false;
692         break;
693       }
694       if (val.find('=') != StringRef::npos) {
695         Diags.Report(SourceLocation(),
696                      diag::err_analyzer_config_multiple_values)
697           << configVal;
698         Success = false;
699         break;
700       }
701 
702       // TODO: Check checker options too, possibly in CheckerRegistry.
703       // Leave unknown non-checker configs unclaimed.
704       if (!key.contains(":") && Opts.isUnknownAnalyzerConfig(key)) {
705         if (Opts.ShouldEmitErrorsOnInvalidConfigValue)
706           Diags.Report(diag::err_analyzer_config_unknown) << key;
707         continue;
708       }
709 
710       A->claim();
711       Opts.Config[key] = std::string(val);
712     }
713   }
714 
715   if (Opts.ShouldEmitErrorsOnInvalidConfigValue)
716     parseAnalyzerConfigs(Opts, &Diags);
717   else
718     parseAnalyzerConfigs(Opts, nullptr);
719 
720   llvm::raw_string_ostream os(Opts.FullCompilerInvocation);
721   for (unsigned i = 0; i < Args.getNumInputArgStrings(); ++i) {
722     if (i != 0)
723       os << " ";
724     os << Args.getArgString(i);
725   }
726   os.flush();
727 
728   return Success;
729 }
730 
731 static StringRef getStringOption(AnalyzerOptions::ConfigTable &Config,
732                                  StringRef OptionName, StringRef DefaultVal) {
733   return Config.insert({OptionName, std::string(DefaultVal)}).first->second;
734 }
735 
736 static void initOption(AnalyzerOptions::ConfigTable &Config,
737                        DiagnosticsEngine *Diags,
738                        StringRef &OptionField, StringRef Name,
739                        StringRef DefaultVal) {
740   // String options may be known to invalid (e.g. if the expected string is a
741   // file name, but the file does not exist), those will have to be checked in
742   // parseConfigs.
743   OptionField = getStringOption(Config, Name, DefaultVal);
744 }
745 
746 static void initOption(AnalyzerOptions::ConfigTable &Config,
747                        DiagnosticsEngine *Diags,
748                        bool &OptionField, StringRef Name, bool DefaultVal) {
749   auto PossiblyInvalidVal = llvm::StringSwitch<Optional<bool>>(
750                  getStringOption(Config, Name, (DefaultVal ? "true" : "false")))
751       .Case("true", true)
752       .Case("false", false)
753       .Default(None);
754 
755   if (!PossiblyInvalidVal) {
756     if (Diags)
757       Diags->Report(diag::err_analyzer_config_invalid_input)
758         << Name << "a boolean";
759     else
760       OptionField = DefaultVal;
761   } else
762     OptionField = PossiblyInvalidVal.getValue();
763 }
764 
765 static void initOption(AnalyzerOptions::ConfigTable &Config,
766                        DiagnosticsEngine *Diags,
767                        unsigned &OptionField, StringRef Name,
768                        unsigned DefaultVal) {
769 
770   OptionField = DefaultVal;
771   bool HasFailed = getStringOption(Config, Name, std::to_string(DefaultVal))
772                      .getAsInteger(0, OptionField);
773   if (Diags && HasFailed)
774     Diags->Report(diag::err_analyzer_config_invalid_input)
775       << Name << "an unsigned";
776 }
777 
778 static void parseAnalyzerConfigs(AnalyzerOptions &AnOpts,
779                                  DiagnosticsEngine *Diags) {
780   // TODO: There's no need to store the entire configtable, it'd be plenty
781   // enough tostore checker options.
782 
783 #define ANALYZER_OPTION(TYPE, NAME, CMDFLAG, DESC, DEFAULT_VAL)                \
784   initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, DEFAULT_VAL);
785 
786 #define ANALYZER_OPTION_DEPENDS_ON_USER_MODE(TYPE, NAME, CMDFLAG, DESC,        \
787                                            SHALLOW_VAL, DEEP_VAL)              \
788   switch (AnOpts.getUserMode()) {                                              \
789   case UMK_Shallow:                                                            \
790     initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, SHALLOW_VAL);       \
791     break;                                                                     \
792   case UMK_Deep:                                                               \
793     initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, DEEP_VAL);          \
794     break;                                                                     \
795   }                                                                            \
796 
797 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.def"
798 #undef ANALYZER_OPTION
799 #undef ANALYZER_OPTION_DEPENDS_ON_USER_MODE
800 
801   // At this point, AnalyzerOptions is configured. Let's validate some options.
802 
803   // FIXME: Here we try to validate the silenced checkers or packages are valid.
804   // The current approach only validates the registered checkers which does not
805   // contain the runtime enabled checkers and optimally we would validate both.
806   if (!AnOpts.RawSilencedCheckersAndPackages.empty()) {
807     std::vector<StringRef> Checkers =
808         AnOpts.getRegisteredCheckers(/*IncludeExperimental=*/true);
809     std::vector<StringRef> Packages =
810         AnOpts.getRegisteredPackages(/*IncludeExperimental=*/true);
811 
812     SmallVector<StringRef, 16> CheckersAndPackages;
813     AnOpts.RawSilencedCheckersAndPackages.split(CheckersAndPackages, ";");
814 
815     for (const StringRef &CheckerOrPackage : CheckersAndPackages) {
816       if (Diags) {
817         bool IsChecker = CheckerOrPackage.contains('.');
818         bool IsValidName =
819             IsChecker
820                 ? llvm::find(Checkers, CheckerOrPackage) != Checkers.end()
821                 : llvm::find(Packages, CheckerOrPackage) != Packages.end();
822 
823         if (!IsValidName)
824           Diags->Report(diag::err_unknown_analyzer_checker_or_package)
825               << CheckerOrPackage;
826       }
827 
828       AnOpts.SilencedCheckersAndPackages.emplace_back(CheckerOrPackage);
829     }
830   }
831 
832   if (!Diags)
833     return;
834 
835   if (AnOpts.ShouldTrackConditionsDebug && !AnOpts.ShouldTrackConditions)
836     Diags->Report(diag::err_analyzer_config_invalid_input)
837         << "track-conditions-debug" << "'track-conditions' to also be enabled";
838 
839   if (!AnOpts.CTUDir.empty() && !llvm::sys::fs::is_directory(AnOpts.CTUDir))
840     Diags->Report(diag::err_analyzer_config_invalid_input) << "ctu-dir"
841                                                            << "a filename";
842 
843   if (!AnOpts.ModelPath.empty() &&
844       !llvm::sys::fs::is_directory(AnOpts.ModelPath))
845     Diags->Report(diag::err_analyzer_config_invalid_input) << "model-path"
846                                                            << "a filename";
847 }
848 
849 /// Create a new Regex instance out of the string value in \p RpassArg.
850 /// It returns a pointer to the newly generated Regex instance.
851 static std::shared_ptr<llvm::Regex>
852 GenerateOptimizationRemarkRegex(DiagnosticsEngine &Diags, ArgList &Args,
853                                 Arg *RpassArg) {
854   StringRef Val = RpassArg->getValue();
855   std::string RegexError;
856   std::shared_ptr<llvm::Regex> Pattern = std::make_shared<llvm::Regex>(Val);
857   if (!Pattern->isValid(RegexError)) {
858     Diags.Report(diag::err_drv_optimization_remark_pattern)
859         << RegexError << RpassArg->getAsString(Args);
860     Pattern.reset();
861   }
862   return Pattern;
863 }
864 
865 static bool parseDiagnosticLevelMask(StringRef FlagName,
866                                      const std::vector<std::string> &Levels,
867                                      DiagnosticsEngine &Diags,
868                                      DiagnosticLevelMask &M) {
869   bool Success = true;
870   for (const auto &Level : Levels) {
871     DiagnosticLevelMask const PM =
872       llvm::StringSwitch<DiagnosticLevelMask>(Level)
873         .Case("note",    DiagnosticLevelMask::Note)
874         .Case("remark",  DiagnosticLevelMask::Remark)
875         .Case("warning", DiagnosticLevelMask::Warning)
876         .Case("error",   DiagnosticLevelMask::Error)
877         .Default(DiagnosticLevelMask::None);
878     if (PM == DiagnosticLevelMask::None) {
879       Success = false;
880       Diags.Report(diag::err_drv_invalid_value) << FlagName << Level;
881     }
882     M = M | PM;
883   }
884   return Success;
885 }
886 
887 static void parseSanitizerKinds(StringRef FlagName,
888                                 const std::vector<std::string> &Sanitizers,
889                                 DiagnosticsEngine &Diags, SanitizerSet &S) {
890   for (const auto &Sanitizer : Sanitizers) {
891     SanitizerMask K = parseSanitizerValue(Sanitizer, /*AllowGroups=*/false);
892     if (K == SanitizerMask())
893       Diags.Report(diag::err_drv_invalid_value) << FlagName << Sanitizer;
894     else
895       S.set(K, true);
896   }
897 }
898 
899 static void parseXRayInstrumentationBundle(StringRef FlagName, StringRef Bundle,
900                                            ArgList &Args, DiagnosticsEngine &D,
901                                            XRayInstrSet &S) {
902   llvm::SmallVector<StringRef, 2> BundleParts;
903   llvm::SplitString(Bundle, BundleParts, ",");
904   for (const auto &B : BundleParts) {
905     auto Mask = parseXRayInstrValue(B);
906     if (Mask == XRayInstrKind::None)
907       if (B != "none")
908         D.Report(diag::err_drv_invalid_value) << FlagName << Bundle;
909       else
910         S.Mask = Mask;
911     else if (Mask == XRayInstrKind::All)
912       S.Mask = Mask;
913     else
914       S.set(Mask, true);
915   }
916 }
917 
918 // Set the profile kind using fprofile-instrument-use-path.
919 static void setPGOUseInstrumentor(CodeGenOptions &Opts,
920                                   const Twine &ProfileName) {
921   auto ReaderOrErr = llvm::IndexedInstrProfReader::create(ProfileName);
922   // In error, return silently and let Clang PGOUse report the error message.
923   if (auto E = ReaderOrErr.takeError()) {
924     llvm::consumeError(std::move(E));
925     Opts.setProfileUse(CodeGenOptions::ProfileClangInstr);
926     return;
927   }
928   std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader =
929     std::move(ReaderOrErr.get());
930   if (PGOReader->isIRLevelProfile()) {
931     if (PGOReader->hasCSIRLevelProfile())
932       Opts.setProfileUse(CodeGenOptions::ProfileCSIRInstr);
933     else
934       Opts.setProfileUse(CodeGenOptions::ProfileIRInstr);
935   } else
936     Opts.setProfileUse(CodeGenOptions::ProfileClangInstr);
937 }
938 
939 bool CompilerInvocation::ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args,
940                                           InputKind IK,
941                                           DiagnosticsEngine &Diags,
942                                           const llvm::Triple &T,
943                                           const std::string &OutputFile,
944                                           const LangOptions &LangOptsRef) {
945   bool Success = true;
946 
947   unsigned OptimizationLevel = getOptimizationLevel(Args, IK, Diags);
948   // TODO: This could be done in Driver
949   unsigned MaxOptLevel = 3;
950   if (OptimizationLevel > MaxOptLevel) {
951     // If the optimization level is not supported, fall back on the default
952     // optimization
953     Diags.Report(diag::warn_drv_optimization_value)
954         << Args.getLastArg(OPT_O)->getAsString(Args) << "-O" << MaxOptLevel;
955     OptimizationLevel = MaxOptLevel;
956   }
957   Opts.OptimizationLevel = OptimizationLevel;
958 
959   // The key paths of codegen options defined in Options.td start with
960   // "CodeGenOpts.". Let's provide the expected variable name and type.
961   CodeGenOptions &CodeGenOpts = Opts;
962   // Some codegen options depend on language options. Let's provide the expected
963   // variable name and type.
964   const LangOptions *LangOpts = &LangOptsRef;
965 
966 #define CODEGEN_OPTION_WITH_MARSHALLING(                                       \
967     PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,        \
968     HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
969     DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER,     \
970     MERGER, EXTRACTOR, TABLE_INDEX)                                            \
971   PARSE_OPTION_WITH_MARSHALLING(Args, Diags, Success, ID, FLAGS, PARAM,        \
972                                 SHOULD_PARSE, KEYPATH, DEFAULT_VALUE,          \
973                                 IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER,      \
974                                 MERGER, TABLE_INDEX)
975 #include "clang/Driver/Options.inc"
976 #undef CODEGEN_OPTION_WITH_MARSHALLING
977 
978   // At O0 we want to fully disable inlining outside of cases marked with
979   // 'alwaysinline' that are required for correctness.
980   Opts.setInlining((Opts.OptimizationLevel == 0)
981                        ? CodeGenOptions::OnlyAlwaysInlining
982                        : CodeGenOptions::NormalInlining);
983   // Explicit inlining flags can disable some or all inlining even at
984   // optimization levels above zero.
985   if (Arg *InlineArg = Args.getLastArg(
986           options::OPT_finline_functions, options::OPT_finline_hint_functions,
987           options::OPT_fno_inline_functions, options::OPT_fno_inline)) {
988     if (Opts.OptimizationLevel > 0) {
989       const Option &InlineOpt = InlineArg->getOption();
990       if (InlineOpt.matches(options::OPT_finline_functions))
991         Opts.setInlining(CodeGenOptions::NormalInlining);
992       else if (InlineOpt.matches(options::OPT_finline_hint_functions))
993         Opts.setInlining(CodeGenOptions::OnlyHintInlining);
994       else
995         Opts.setInlining(CodeGenOptions::OnlyAlwaysInlining);
996     }
997   }
998 
999   // PIC defaults to -fno-direct-access-external-data while non-PIC defaults to
1000   // -fdirect-access-external-data.
1001   Opts.DirectAccessExternalData =
1002       Args.hasArg(OPT_fdirect_access_external_data) ||
1003       (!Args.hasArg(OPT_fno_direct_access_external_data) &&
1004        getLastArgIntValue(Args, OPT_pic_level, 0, Diags) == 0);
1005 
1006   // If -fuse-ctor-homing is set and limited debug info is already on, then use
1007   // constructor homing.
1008   if (Args.getLastArg(OPT_fuse_ctor_homing))
1009     if (Opts.getDebugInfo() == codegenoptions::LimitedDebugInfo)
1010       Opts.setDebugInfo(codegenoptions::DebugInfoConstructor);
1011 
1012   for (const auto &Arg : Args.getAllArgValues(OPT_fdebug_prefix_map_EQ)) {
1013     auto Split = StringRef(Arg).split('=');
1014     Opts.DebugPrefixMap.insert(
1015         {std::string(Split.first), std::string(Split.second)});
1016   }
1017 
1018   for (const auto &Arg : Args.getAllArgValues(OPT_fprofile_prefix_map_EQ)) {
1019     auto Split = StringRef(Arg).split('=');
1020     Opts.ProfilePrefixMap.insert(
1021         {std::string(Split.first), std::string(Split.second)});
1022   }
1023 
1024   const llvm::Triple::ArchType DebugEntryValueArchs[] = {
1025       llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::aarch64,
1026       llvm::Triple::arm, llvm::Triple::armeb, llvm::Triple::mips,
1027       llvm::Triple::mipsel, llvm::Triple::mips64, llvm::Triple::mips64el};
1028 
1029   if (Opts.OptimizationLevel > 0 && Opts.hasReducedDebugInfo() &&
1030       llvm::is_contained(DebugEntryValueArchs, T.getArch()))
1031     Opts.EmitCallSiteInfo = true;
1032 
1033   Opts.NewStructPathTBAA = !Args.hasArg(OPT_no_struct_path_tbaa) &&
1034                            Args.hasArg(OPT_new_struct_path_tbaa);
1035   Opts.OptimizeSize = getOptimizationLevelSize(Args);
1036   Opts.SimplifyLibCalls = !(Args.hasArg(OPT_fno_builtin) ||
1037                             Args.hasArg(OPT_ffreestanding));
1038   if (Opts.SimplifyLibCalls)
1039     getAllNoBuiltinFuncValues(Args, Opts.NoBuiltinFuncs);
1040   Opts.UnrollLoops =
1041       Args.hasFlag(OPT_funroll_loops, OPT_fno_unroll_loops,
1042                    (Opts.OptimizationLevel > 1));
1043 
1044   Opts.BinutilsVersion =
1045       std::string(Args.getLastArgValue(OPT_fbinutils_version_EQ));
1046 
1047   Opts.DebugNameTable = static_cast<unsigned>(
1048       Args.hasArg(OPT_ggnu_pubnames)
1049           ? llvm::DICompileUnit::DebugNameTableKind::GNU
1050           : Args.hasArg(OPT_gpubnames)
1051                 ? llvm::DICompileUnit::DebugNameTableKind::Default
1052                 : llvm::DICompileUnit::DebugNameTableKind::None);
1053 
1054   if (!Opts.ProfileInstrumentUsePath.empty())
1055     setPGOUseInstrumentor(Opts, Opts.ProfileInstrumentUsePath);
1056 
1057   if (const Arg *A = Args.getLastArg(OPT_ftime_report, OPT_ftime_report_EQ)) {
1058     Opts.TimePasses = true;
1059 
1060     // -ftime-report= is only for new pass manager.
1061     if (A->getOption().getID() == OPT_ftime_report_EQ) {
1062       if (Opts.LegacyPassManager)
1063         Diags.Report(diag::err_drv_argument_only_allowed_with)
1064             << A->getAsString(Args) << "-fno-legacy-pass-manager";
1065 
1066       StringRef Val = A->getValue();
1067       if (Val == "per-pass")
1068         Opts.TimePassesPerRun = false;
1069       else if (Val == "per-pass-run")
1070         Opts.TimePassesPerRun = true;
1071       else
1072         Diags.Report(diag::err_drv_invalid_value)
1073             << A->getAsString(Args) << A->getValue();
1074     }
1075   }
1076 
1077   // Basic Block Sections implies Function Sections.
1078   Opts.FunctionSections =
1079       Args.hasArg(OPT_ffunction_sections) ||
1080       (Opts.BBSections != "none" && Opts.BBSections != "labels");
1081 
1082   Opts.PrepareForLTO = Args.hasArg(OPT_flto, OPT_flto_EQ);
1083   Opts.PrepareForThinLTO = false;
1084   if (Arg *A = Args.getLastArg(OPT_flto_EQ)) {
1085     StringRef S = A->getValue();
1086     if (S == "thin")
1087       Opts.PrepareForThinLTO = true;
1088     else if (S != "full")
1089       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << S;
1090   }
1091   if (Arg *A = Args.getLastArg(OPT_fthinlto_index_EQ)) {
1092     if (IK.getLanguage() != Language::LLVM_IR)
1093       Diags.Report(diag::err_drv_argument_only_allowed_with)
1094           << A->getAsString(Args) << "-x ir";
1095     Opts.ThinLTOIndexFile =
1096         std::string(Args.getLastArgValue(OPT_fthinlto_index_EQ));
1097   }
1098   if (Arg *A = Args.getLastArg(OPT_save_temps_EQ))
1099     Opts.SaveTempsFilePrefix =
1100         llvm::StringSwitch<std::string>(A->getValue())
1101             .Case("obj", OutputFile)
1102             .Default(llvm::sys::path::filename(OutputFile).str());
1103 
1104   // The memory profile runtime appends the pid to make this name more unique.
1105   const char *MemProfileBasename = "memprof.profraw";
1106   if (Args.hasArg(OPT_fmemory_profile_EQ)) {
1107     SmallString<128> Path(
1108         std::string(Args.getLastArgValue(OPT_fmemory_profile_EQ)));
1109     llvm::sys::path::append(Path, MemProfileBasename);
1110     Opts.MemoryProfileOutput = std::string(Path);
1111   } else if (Args.hasArg(OPT_fmemory_profile))
1112     Opts.MemoryProfileOutput = MemProfileBasename;
1113 
1114   if (Opts.EmitGcovArcs || Opts.EmitGcovNotes) {
1115     if (Args.hasArg(OPT_coverage_version_EQ)) {
1116       StringRef CoverageVersion = Args.getLastArgValue(OPT_coverage_version_EQ);
1117       if (CoverageVersion.size() != 4) {
1118         Diags.Report(diag::err_drv_invalid_value)
1119             << Args.getLastArg(OPT_coverage_version_EQ)->getAsString(Args)
1120             << CoverageVersion;
1121       } else {
1122         memcpy(Opts.CoverageVersion, CoverageVersion.data(), 4);
1123       }
1124     }
1125   }
1126   // FIXME: For backend options that are not yet recorded as function
1127   // attributes in the IR, keep track of them so we can embed them in a
1128   // separate data section and use them when building the bitcode.
1129   for (const auto &A : Args) {
1130     // Do not encode output and input.
1131     if (A->getOption().getID() == options::OPT_o ||
1132         A->getOption().getID() == options::OPT_INPUT ||
1133         A->getOption().getID() == options::OPT_x ||
1134         A->getOption().getID() == options::OPT_fembed_bitcode ||
1135         A->getOption().matches(options::OPT_W_Group))
1136       continue;
1137     ArgStringList ASL;
1138     A->render(Args, ASL);
1139     for (const auto &arg : ASL) {
1140       StringRef ArgStr(arg);
1141       Opts.CmdArgs.insert(Opts.CmdArgs.end(), ArgStr.begin(), ArgStr.end());
1142       // using \00 to separate each commandline options.
1143       Opts.CmdArgs.push_back('\0');
1144     }
1145   }
1146 
1147   auto XRayInstrBundles =
1148       Args.getAllArgValues(OPT_fxray_instrumentation_bundle);
1149   if (XRayInstrBundles.empty())
1150     Opts.XRayInstrumentationBundle.Mask = XRayInstrKind::All;
1151   else
1152     for (const auto &A : XRayInstrBundles)
1153       parseXRayInstrumentationBundle("-fxray-instrumentation-bundle=", A, Args,
1154                                      Diags, Opts.XRayInstrumentationBundle);
1155 
1156   if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
1157     StringRef Name = A->getValue();
1158     if (Name == "full") {
1159       Opts.CFProtectionReturn = 1;
1160       Opts.CFProtectionBranch = 1;
1161     } else if (Name == "return")
1162       Opts.CFProtectionReturn = 1;
1163     else if (Name == "branch")
1164       Opts.CFProtectionBranch = 1;
1165     else if (Name != "none") {
1166       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
1167       Success = false;
1168     }
1169   }
1170 
1171   for (auto *A :
1172        Args.filtered(OPT_mlink_bitcode_file, OPT_mlink_builtin_bitcode)) {
1173     CodeGenOptions::BitcodeFileToLink F;
1174     F.Filename = A->getValue();
1175     if (A->getOption().matches(OPT_mlink_builtin_bitcode)) {
1176       F.LinkFlags = llvm::Linker::Flags::LinkOnlyNeeded;
1177       // When linking CUDA bitcode, propagate function attributes so that
1178       // e.g. libdevice gets fast-math attrs if we're building with fast-math.
1179       F.PropagateAttrs = true;
1180       F.Internalize = true;
1181     }
1182     Opts.LinkBitcodeFiles.push_back(F);
1183   }
1184 
1185   if (Args.getLastArg(OPT_femulated_tls) ||
1186       Args.getLastArg(OPT_fno_emulated_tls)) {
1187     Opts.ExplicitEmulatedTLS = true;
1188   }
1189 
1190   if (Arg *A = Args.getLastArg(OPT_fdenormal_fp_math_EQ)) {
1191     StringRef Val = A->getValue();
1192     Opts.FPDenormalMode = llvm::parseDenormalFPAttribute(Val);
1193     if (!Opts.FPDenormalMode.isValid())
1194       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
1195   }
1196 
1197   if (Arg *A = Args.getLastArg(OPT_fdenormal_fp_math_f32_EQ)) {
1198     StringRef Val = A->getValue();
1199     Opts.FP32DenormalMode = llvm::parseDenormalFPAttribute(Val);
1200     if (!Opts.FP32DenormalMode.isValid())
1201       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
1202   }
1203 
1204   // X86_32 has -fppc-struct-return and -freg-struct-return.
1205   // PPC32 has -maix-struct-return and -msvr4-struct-return.
1206   if (Arg *A =
1207           Args.getLastArg(OPT_fpcc_struct_return, OPT_freg_struct_return,
1208                           OPT_maix_struct_return, OPT_msvr4_struct_return)) {
1209     // TODO: We might want to consider enabling these options on AIX in the
1210     // future.
1211     if (T.isOSAIX())
1212       Diags.Report(diag::err_drv_unsupported_opt_for_target)
1213           << A->getSpelling() << T.str();
1214 
1215     const Option &O = A->getOption();
1216     if (O.matches(OPT_fpcc_struct_return) ||
1217         O.matches(OPT_maix_struct_return)) {
1218       Opts.setStructReturnConvention(CodeGenOptions::SRCK_OnStack);
1219     } else {
1220       assert(O.matches(OPT_freg_struct_return) ||
1221              O.matches(OPT_msvr4_struct_return));
1222       Opts.setStructReturnConvention(CodeGenOptions::SRCK_InRegs);
1223     }
1224   }
1225 
1226   if (T.isOSAIX() && (Args.hasArg(OPT_mignore_xcoff_visibility) ||
1227                       !Args.hasArg(OPT_fvisibility)))
1228     Opts.IgnoreXCOFFVisibility = 1;
1229 
1230   if (Arg *A =
1231           Args.getLastArg(OPT_mabi_EQ_vec_default, OPT_mabi_EQ_vec_extabi)) {
1232     if (!T.isOSAIX())
1233       Diags.Report(diag::err_drv_unsupported_opt_for_target)
1234           << A->getSpelling() << T.str();
1235 
1236     const Option &O = A->getOption();
1237     if (O.matches(OPT_mabi_EQ_vec_default))
1238       Diags.Report(diag::err_aix_default_altivec_abi)
1239           << A->getSpelling() << T.str();
1240     else {
1241       assert(O.matches(OPT_mabi_EQ_vec_extabi));
1242       Opts.EnableAIXExtendedAltivecABI = 1;
1243     }
1244   }
1245 
1246   bool NeedLocTracking = false;
1247 
1248   if (!Opts.OptRecordFile.empty())
1249     NeedLocTracking = true;
1250 
1251   if (Arg *A = Args.getLastArg(OPT_opt_record_passes)) {
1252     Opts.OptRecordPasses = A->getValue();
1253     NeedLocTracking = true;
1254   }
1255 
1256   if (Arg *A = Args.getLastArg(OPT_opt_record_format)) {
1257     Opts.OptRecordFormat = A->getValue();
1258     NeedLocTracking = true;
1259   }
1260 
1261   if (Arg *A = Args.getLastArg(OPT_Rpass_EQ)) {
1262     Opts.OptimizationRemarkPattern =
1263         GenerateOptimizationRemarkRegex(Diags, Args, A);
1264     NeedLocTracking = true;
1265   }
1266 
1267   if (Arg *A = Args.getLastArg(OPT_Rpass_missed_EQ)) {
1268     Opts.OptimizationRemarkMissedPattern =
1269         GenerateOptimizationRemarkRegex(Diags, Args, A);
1270     NeedLocTracking = true;
1271   }
1272 
1273   if (Arg *A = Args.getLastArg(OPT_Rpass_analysis_EQ)) {
1274     Opts.OptimizationRemarkAnalysisPattern =
1275         GenerateOptimizationRemarkRegex(Diags, Args, A);
1276     NeedLocTracking = true;
1277   }
1278 
1279   bool UsingSampleProfile = !Opts.SampleProfileFile.empty();
1280   bool UsingProfile = UsingSampleProfile ||
1281       (Opts.getProfileUse() != CodeGenOptions::ProfileNone);
1282 
1283   if (Opts.DiagnosticsWithHotness && !UsingProfile &&
1284       // An IR file will contain PGO as metadata
1285       IK.getLanguage() != Language::LLVM_IR)
1286     Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo)
1287         << "-fdiagnostics-show-hotness";
1288 
1289   // Parse remarks hotness threshold. Valid value is either integer or 'auto'.
1290   if (auto *arg =
1291           Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
1292     auto ResultOrErr =
1293         llvm::remarks::parseHotnessThresholdOption(arg->getValue());
1294 
1295     if (!ResultOrErr) {
1296       Diags.Report(diag::err_drv_invalid_diagnotics_hotness_threshold)
1297           << "-fdiagnostics-hotness-threshold=";
1298     } else {
1299       Opts.DiagnosticsHotnessThreshold = *ResultOrErr;
1300       if ((!Opts.DiagnosticsHotnessThreshold.hasValue() ||
1301            Opts.DiagnosticsHotnessThreshold.getValue() > 0) &&
1302           !UsingProfile)
1303         Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo)
1304             << "-fdiagnostics-hotness-threshold=";
1305     }
1306   }
1307 
1308   // If the user requested to use a sample profile for PGO, then the
1309   // backend will need to track source location information so the profile
1310   // can be incorporated into the IR.
1311   if (UsingSampleProfile)
1312     NeedLocTracking = true;
1313 
1314   // If the user requested a flag that requires source locations available in
1315   // the backend, make sure that the backend tracks source location information.
1316   if (NeedLocTracking && Opts.getDebugInfo() == codegenoptions::NoDebugInfo)
1317     Opts.setDebugInfo(codegenoptions::LocTrackingOnly);
1318 
1319   // Parse -fsanitize-recover= arguments.
1320   // FIXME: Report unrecoverable sanitizers incorrectly specified here.
1321   parseSanitizerKinds("-fsanitize-recover=",
1322                       Args.getAllArgValues(OPT_fsanitize_recover_EQ), Diags,
1323                       Opts.SanitizeRecover);
1324   parseSanitizerKinds("-fsanitize-trap=",
1325                       Args.getAllArgValues(OPT_fsanitize_trap_EQ), Diags,
1326                       Opts.SanitizeTrap);
1327 
1328   Opts.EmitVersionIdentMetadata = Args.hasFlag(OPT_Qy, OPT_Qn, true);
1329 
1330   return Success;
1331 }
1332 
1333 static void ParseDependencyOutputArgs(DependencyOutputOptions &Opts,
1334                                       ArgList &Args) {
1335   if (Args.hasArg(OPT_show_includes)) {
1336     // Writing both /showIncludes and preprocessor output to stdout
1337     // would produce interleaved output, so use stderr for /showIncludes.
1338     // This behaves the same as cl.exe, when /E, /EP or /P are passed.
1339     if (Args.hasArg(options::OPT_E) || Args.hasArg(options::OPT_P))
1340       Opts.ShowIncludesDest = ShowIncludesDestination::Stderr;
1341     else
1342       Opts.ShowIncludesDest = ShowIncludesDestination::Stdout;
1343   } else {
1344     Opts.ShowIncludesDest = ShowIncludesDestination::None;
1345   }
1346   // Add sanitizer blacklists as extra dependencies.
1347   // They won't be discovered by the regular preprocessor, so
1348   // we let make / ninja to know about this implicit dependency.
1349   if (!Args.hasArg(OPT_fno_sanitize_blacklist)) {
1350     for (const auto *A : Args.filtered(OPT_fsanitize_blacklist)) {
1351       StringRef Val = A->getValue();
1352       if (Val.find('=') == StringRef::npos)
1353         Opts.ExtraDeps.push_back(std::string(Val));
1354     }
1355     if (Opts.IncludeSystemHeaders) {
1356       for (const auto *A : Args.filtered(OPT_fsanitize_system_blacklist)) {
1357         StringRef Val = A->getValue();
1358         if (Val.find('=') == StringRef::npos)
1359           Opts.ExtraDeps.push_back(std::string(Val));
1360       }
1361     }
1362   }
1363 
1364   // -fprofile-list= dependencies.
1365   for (const auto &Filename : Args.getAllArgValues(OPT_fprofile_list_EQ))
1366     Opts.ExtraDeps.push_back(Filename);
1367 
1368   // Propagate the extra dependencies.
1369   for (const auto *A : Args.filtered(OPT_fdepfile_entry)) {
1370     Opts.ExtraDeps.push_back(A->getValue());
1371   }
1372 
1373   // Only the -fmodule-file=<file> form.
1374   for (const auto *A : Args.filtered(OPT_fmodule_file)) {
1375     StringRef Val = A->getValue();
1376     if (Val.find('=') == StringRef::npos)
1377       Opts.ExtraDeps.push_back(std::string(Val));
1378   }
1379 }
1380 
1381 static bool parseShowColorsArgs(const ArgList &Args, bool DefaultColor) {
1382   // Color diagnostics default to auto ("on" if terminal supports) in the driver
1383   // but default to off in cc1, needing an explicit OPT_fdiagnostics_color.
1384   // Support both clang's -f[no-]color-diagnostics and gcc's
1385   // -f[no-]diagnostics-colors[=never|always|auto].
1386   enum {
1387     Colors_On,
1388     Colors_Off,
1389     Colors_Auto
1390   } ShowColors = DefaultColor ? Colors_Auto : Colors_Off;
1391   for (auto *A : Args) {
1392     const Option &O = A->getOption();
1393     if (O.matches(options::OPT_fcolor_diagnostics) ||
1394         O.matches(options::OPT_fdiagnostics_color)) {
1395       ShowColors = Colors_On;
1396     } else if (O.matches(options::OPT_fno_color_diagnostics) ||
1397                O.matches(options::OPT_fno_diagnostics_color)) {
1398       ShowColors = Colors_Off;
1399     } else if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
1400       StringRef Value(A->getValue());
1401       if (Value == "always")
1402         ShowColors = Colors_On;
1403       else if (Value == "never")
1404         ShowColors = Colors_Off;
1405       else if (Value == "auto")
1406         ShowColors = Colors_Auto;
1407     }
1408   }
1409   return ShowColors == Colors_On ||
1410          (ShowColors == Colors_Auto &&
1411           llvm::sys::Process::StandardErrHasColors());
1412 }
1413 
1414 static bool checkVerifyPrefixes(const std::vector<std::string> &VerifyPrefixes,
1415                                 DiagnosticsEngine &Diags) {
1416   bool Success = true;
1417   for (const auto &Prefix : VerifyPrefixes) {
1418     // Every prefix must start with a letter and contain only alphanumeric
1419     // characters, hyphens, and underscores.
1420     auto BadChar = llvm::find_if(Prefix, [](char C) {
1421       return !isAlphanumeric(C) && C != '-' && C != '_';
1422     });
1423     if (BadChar != Prefix.end() || !isLetter(Prefix[0])) {
1424       Success = false;
1425       Diags.Report(diag::err_drv_invalid_value) << "-verify=" << Prefix;
1426       Diags.Report(diag::note_drv_verify_prefix_spelling);
1427     }
1428   }
1429   return Success;
1430 }
1431 
1432 bool CompilerInvocation::parseSimpleArgs(const ArgList &Args,
1433                                          DiagnosticsEngine &Diags) {
1434   bool Success = true;
1435 
1436 #define OPTION_WITH_MARSHALLING(                                               \
1437     PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,        \
1438     HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
1439     DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER,     \
1440     MERGER, EXTRACTOR, TABLE_INDEX)                                            \
1441   PARSE_OPTION_WITH_MARSHALLING(Args, Diags, Success, ID, FLAGS, PARAM,        \
1442                                 SHOULD_PARSE, this->KEYPATH, DEFAULT_VALUE,    \
1443                                 IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER,      \
1444                                 MERGER, TABLE_INDEX)
1445 #include "clang/Driver/Options.inc"
1446 #undef OPTION_WITH_MARSHALLING
1447 
1448   return Success;
1449 }
1450 
1451 bool clang::ParseDiagnosticArgs(DiagnosticOptions &Opts, ArgList &Args,
1452                                 DiagnosticsEngine *Diags,
1453                                 bool DefaultDiagColor) {
1454   Optional<DiagnosticsEngine> IgnoringDiags;
1455   if (!Diags) {
1456     IgnoringDiags.emplace(new DiagnosticIDs(), new DiagnosticOptions(),
1457                           new IgnoringDiagConsumer());
1458     Diags = &*IgnoringDiags;
1459   }
1460 
1461   // The key paths of diagnostic options defined in Options.td start with
1462   // "DiagnosticOpts->". Let's provide the expected variable name and type.
1463   DiagnosticOptions *DiagnosticOpts = &Opts;
1464   bool Success = true;
1465 
1466 #define DIAG_OPTION_WITH_MARSHALLING(                                          \
1467     PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,        \
1468     HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
1469     DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER,     \
1470     MERGER, EXTRACTOR, TABLE_INDEX)                                            \
1471   PARSE_OPTION_WITH_MARSHALLING(Args, *Diags, Success, ID, FLAGS, PARAM,       \
1472                                 SHOULD_PARSE, KEYPATH, DEFAULT_VALUE,          \
1473                                 IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER,      \
1474                                 MERGER, TABLE_INDEX)
1475 #include "clang/Driver/Options.inc"
1476 #undef DIAG_OPTION_WITH_MARSHALLING
1477 
1478   llvm::sys::Process::UseANSIEscapeCodes(Opts.UseANSIEscapeCodes);
1479 
1480   if (Arg *A =
1481           Args.getLastArg(OPT_diagnostic_serialized_file, OPT__serialize_diags))
1482     Opts.DiagnosticSerializationFile = A->getValue();
1483   Opts.ShowColors = parseShowColorsArgs(Args, DefaultDiagColor);
1484 
1485   if (Args.getLastArgValue(OPT_fdiagnostics_format) == "msvc-fallback")
1486     Opts.CLFallbackMode = true;
1487 
1488   Opts.VerifyDiagnostics = Args.hasArg(OPT_verify) || Args.hasArg(OPT_verify_EQ);
1489   if (Args.hasArg(OPT_verify))
1490     Opts.VerifyPrefixes.push_back("expected");
1491   // Keep VerifyPrefixes in its original order for the sake of diagnostics, and
1492   // then sort it to prepare for fast lookup using std::binary_search.
1493   if (!checkVerifyPrefixes(Opts.VerifyPrefixes, *Diags)) {
1494     Opts.VerifyDiagnostics = false;
1495     Success = false;
1496   }
1497   else
1498     llvm::sort(Opts.VerifyPrefixes);
1499   DiagnosticLevelMask DiagMask = DiagnosticLevelMask::None;
1500   Success &= parseDiagnosticLevelMask("-verify-ignore-unexpected=",
1501     Args.getAllArgValues(OPT_verify_ignore_unexpected_EQ),
1502     *Diags, DiagMask);
1503   if (Args.hasArg(OPT_verify_ignore_unexpected))
1504     DiagMask = DiagnosticLevelMask::All;
1505   Opts.setVerifyIgnoreUnexpected(DiagMask);
1506   if (Opts.TabStop == 0 || Opts.TabStop > DiagnosticOptions::MaxTabStop) {
1507     Opts.TabStop = DiagnosticOptions::DefaultTabStop;
1508     Diags->Report(diag::warn_ignoring_ftabstop_value)
1509         << Opts.TabStop << DiagnosticOptions::DefaultTabStop;
1510   }
1511 
1512   addDiagnosticArgs(Args, OPT_W_Group, OPT_W_value_Group, Opts.Warnings);
1513   addDiagnosticArgs(Args, OPT_R_Group, OPT_R_value_Group, Opts.Remarks);
1514 
1515   return Success;
1516 }
1517 
1518 /// Parse the argument to the -ftest-module-file-extension
1519 /// command-line argument.
1520 ///
1521 /// \returns true on error, false on success.
1522 static bool parseTestModuleFileExtensionArg(StringRef Arg,
1523                                             std::string &BlockName,
1524                                             unsigned &MajorVersion,
1525                                             unsigned &MinorVersion,
1526                                             bool &Hashed,
1527                                             std::string &UserInfo) {
1528   SmallVector<StringRef, 5> Args;
1529   Arg.split(Args, ':', 5);
1530   if (Args.size() < 5)
1531     return true;
1532 
1533   BlockName = std::string(Args[0]);
1534   if (Args[1].getAsInteger(10, MajorVersion)) return true;
1535   if (Args[2].getAsInteger(10, MinorVersion)) return true;
1536   if (Args[3].getAsInteger(2, Hashed)) return true;
1537   if (Args.size() > 4)
1538     UserInfo = std::string(Args[4]);
1539   return false;
1540 }
1541 
1542 static InputKind ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args,
1543                                    DiagnosticsEngine &Diags,
1544                                    bool &IsHeaderFile) {
1545   Opts.ProgramAction = frontend::ParseSyntaxOnly;
1546   if (const Arg *A = Args.getLastArg(OPT_Action_Group)) {
1547     switch (A->getOption().getID()) {
1548     default:
1549       llvm_unreachable("Invalid option in group!");
1550     case OPT_ast_list:
1551       Opts.ProgramAction = frontend::ASTDeclList; break;
1552     case OPT_ast_dump_all_EQ:
1553     case OPT_ast_dump_EQ: {
1554       unsigned Val = llvm::StringSwitch<unsigned>(A->getValue())
1555                          .CaseLower("default", ADOF_Default)
1556                          .CaseLower("json", ADOF_JSON)
1557                          .Default(std::numeric_limits<unsigned>::max());
1558 
1559       if (Val != std::numeric_limits<unsigned>::max())
1560         Opts.ASTDumpFormat = static_cast<ASTDumpOutputFormat>(Val);
1561       else {
1562         Diags.Report(diag::err_drv_invalid_value)
1563             << A->getAsString(Args) << A->getValue();
1564         Opts.ASTDumpFormat = ADOF_Default;
1565       }
1566       LLVM_FALLTHROUGH;
1567     }
1568     case OPT_ast_dump:
1569     case OPT_ast_dump_all:
1570     case OPT_ast_dump_lookups:
1571     case OPT_ast_dump_decl_types:
1572       Opts.ProgramAction = frontend::ASTDump; break;
1573     case OPT_ast_print:
1574       Opts.ProgramAction = frontend::ASTPrint; break;
1575     case OPT_ast_view:
1576       Opts.ProgramAction = frontend::ASTView; break;
1577     case OPT_compiler_options_dump:
1578       Opts.ProgramAction = frontend::DumpCompilerOptions; break;
1579     case OPT_dump_raw_tokens:
1580       Opts.ProgramAction = frontend::DumpRawTokens; break;
1581     case OPT_dump_tokens:
1582       Opts.ProgramAction = frontend::DumpTokens; break;
1583     case OPT_S:
1584       Opts.ProgramAction = frontend::EmitAssembly; break;
1585     case OPT_emit_llvm_bc:
1586       Opts.ProgramAction = frontend::EmitBC; break;
1587     case OPT_emit_html:
1588       Opts.ProgramAction = frontend::EmitHTML; break;
1589     case OPT_emit_llvm:
1590       Opts.ProgramAction = frontend::EmitLLVM; break;
1591     case OPT_emit_llvm_only:
1592       Opts.ProgramAction = frontend::EmitLLVMOnly; break;
1593     case OPT_emit_codegen_only:
1594       Opts.ProgramAction = frontend::EmitCodeGenOnly; break;
1595     case OPT_emit_obj:
1596       Opts.ProgramAction = frontend::EmitObj; break;
1597     case OPT_fixit_EQ:
1598       Opts.FixItSuffix = A->getValue();
1599       LLVM_FALLTHROUGH;
1600     case OPT_fixit:
1601       Opts.ProgramAction = frontend::FixIt; break;
1602     case OPT_emit_module:
1603       Opts.ProgramAction = frontend::GenerateModule; break;
1604     case OPT_emit_module_interface:
1605       Opts.ProgramAction = frontend::GenerateModuleInterface; break;
1606     case OPT_emit_header_module:
1607       Opts.ProgramAction = frontend::GenerateHeaderModule; break;
1608     case OPT_emit_pch:
1609       Opts.ProgramAction = frontend::GeneratePCH; break;
1610     case OPT_emit_interface_stubs: {
1611       StringRef ArgStr =
1612           Args.hasArg(OPT_interface_stub_version_EQ)
1613               ? Args.getLastArgValue(OPT_interface_stub_version_EQ)
1614               : "experimental-ifs-v2";
1615       if (ArgStr == "experimental-yaml-elf-v1" ||
1616           ArgStr == "experimental-ifs-v1" ||
1617           ArgStr == "experimental-tapi-elf-v1") {
1618         std::string ErrorMessage =
1619             "Invalid interface stub format: " + ArgStr.str() +
1620             " is deprecated.";
1621         Diags.Report(diag::err_drv_invalid_value)
1622             << "Must specify a valid interface stub format type, ie: "
1623                "-interface-stub-version=experimental-ifs-v2"
1624             << ErrorMessage;
1625       } else if (!ArgStr.startswith("experimental-ifs-")) {
1626         std::string ErrorMessage =
1627             "Invalid interface stub format: " + ArgStr.str() + ".";
1628         Diags.Report(diag::err_drv_invalid_value)
1629             << "Must specify a valid interface stub format type, ie: "
1630                "-interface-stub-version=experimental-ifs-v2"
1631             << ErrorMessage;
1632       } else {
1633         Opts.ProgramAction = frontend::GenerateInterfaceStubs;
1634       }
1635       break;
1636     }
1637     case OPT_init_only:
1638       Opts.ProgramAction = frontend::InitOnly; break;
1639     case OPT_fsyntax_only:
1640       Opts.ProgramAction = frontend::ParseSyntaxOnly; break;
1641     case OPT_module_file_info:
1642       Opts.ProgramAction = frontend::ModuleFileInfo; break;
1643     case OPT_verify_pch:
1644       Opts.ProgramAction = frontend::VerifyPCH; break;
1645     case OPT_print_preamble:
1646       Opts.ProgramAction = frontend::PrintPreamble; break;
1647     case OPT_E:
1648       Opts.ProgramAction = frontend::PrintPreprocessedInput; break;
1649     case OPT_templight_dump:
1650       Opts.ProgramAction = frontend::TemplightDump; break;
1651     case OPT_rewrite_macros:
1652       Opts.ProgramAction = frontend::RewriteMacros; break;
1653     case OPT_rewrite_objc:
1654       Opts.ProgramAction = frontend::RewriteObjC; break;
1655     case OPT_rewrite_test:
1656       Opts.ProgramAction = frontend::RewriteTest; break;
1657     case OPT_analyze:
1658       Opts.ProgramAction = frontend::RunAnalysis; break;
1659     case OPT_migrate:
1660       Opts.ProgramAction = frontend::MigrateSource; break;
1661     case OPT_Eonly:
1662       Opts.ProgramAction = frontend::RunPreprocessorOnly; break;
1663     case OPT_print_dependency_directives_minimized_source:
1664       Opts.ProgramAction =
1665           frontend::PrintDependencyDirectivesSourceMinimizerOutput;
1666       break;
1667     }
1668   }
1669 
1670   if (const Arg* A = Args.getLastArg(OPT_plugin)) {
1671     Opts.Plugins.emplace_back(A->getValue(0));
1672     Opts.ProgramAction = frontend::PluginAction;
1673     Opts.ActionName = A->getValue();
1674   }
1675   for (const auto *AA : Args.filtered(OPT_plugin_arg))
1676     Opts.PluginArgs[AA->getValue(0)].emplace_back(AA->getValue(1));
1677 
1678   for (const std::string &Arg :
1679          Args.getAllArgValues(OPT_ftest_module_file_extension_EQ)) {
1680     std::string BlockName;
1681     unsigned MajorVersion;
1682     unsigned MinorVersion;
1683     bool Hashed;
1684     std::string UserInfo;
1685     if (parseTestModuleFileExtensionArg(Arg, BlockName, MajorVersion,
1686                                         MinorVersion, Hashed, UserInfo)) {
1687       Diags.Report(diag::err_test_module_file_extension_format) << Arg;
1688 
1689       continue;
1690     }
1691 
1692     // Add the testing module file extension.
1693     Opts.ModuleFileExtensions.push_back(
1694         std::make_shared<TestModuleFileExtension>(
1695             BlockName, MajorVersion, MinorVersion, Hashed, UserInfo));
1696   }
1697 
1698   if (const Arg *A = Args.getLastArg(OPT_code_completion_at)) {
1699     Opts.CodeCompletionAt =
1700       ParsedSourceLocation::FromString(A->getValue());
1701     if (Opts.CodeCompletionAt.FileName.empty())
1702       Diags.Report(diag::err_drv_invalid_value)
1703         << A->getAsString(Args) << A->getValue();
1704   }
1705 
1706   Opts.Plugins = Args.getAllArgValues(OPT_load);
1707   Opts.ASTDumpDecls = Args.hasArg(OPT_ast_dump, OPT_ast_dump_EQ);
1708   Opts.ASTDumpAll = Args.hasArg(OPT_ast_dump_all, OPT_ast_dump_all_EQ);
1709   // Only the -fmodule-file=<file> form.
1710   for (const auto *A : Args.filtered(OPT_fmodule_file)) {
1711     StringRef Val = A->getValue();
1712     if (Val.find('=') == StringRef::npos)
1713       Opts.ModuleFiles.push_back(std::string(Val));
1714   }
1715 
1716   if (Opts.ProgramAction != frontend::GenerateModule && Opts.IsSystemModule)
1717     Diags.Report(diag::err_drv_argument_only_allowed_with) << "-fsystem-module"
1718                                                            << "-emit-module";
1719 
1720   if (Args.hasArg(OPT_aux_target_cpu))
1721     Opts.AuxTargetCPU = std::string(Args.getLastArgValue(OPT_aux_target_cpu));
1722   if (Args.hasArg(OPT_aux_target_feature))
1723     Opts.AuxTargetFeatures = Args.getAllArgValues(OPT_aux_target_feature);
1724 
1725   if (Opts.ARCMTAction != FrontendOptions::ARCMT_None &&
1726       Opts.ObjCMTAction != FrontendOptions::ObjCMT_None) {
1727     Diags.Report(diag::err_drv_argument_not_allowed_with)
1728       << "ARC migration" << "ObjC migration";
1729   }
1730 
1731   InputKind DashX(Language::Unknown);
1732   if (const Arg *A = Args.getLastArg(OPT_x)) {
1733     StringRef XValue = A->getValue();
1734 
1735     // Parse suffixes: '<lang>(-header|[-module-map][-cpp-output])'.
1736     // FIXME: Supporting '<lang>-header-cpp-output' would be useful.
1737     bool Preprocessed = XValue.consume_back("-cpp-output");
1738     bool ModuleMap = XValue.consume_back("-module-map");
1739     IsHeaderFile = !Preprocessed && !ModuleMap &&
1740                    XValue != "precompiled-header" &&
1741                    XValue.consume_back("-header");
1742 
1743     // Principal languages.
1744     DashX = llvm::StringSwitch<InputKind>(XValue)
1745                 .Case("c", Language::C)
1746                 .Case("cl", Language::OpenCL)
1747                 .Case("cuda", Language::CUDA)
1748                 .Case("hip", Language::HIP)
1749                 .Case("c++", Language::CXX)
1750                 .Case("objective-c", Language::ObjC)
1751                 .Case("objective-c++", Language::ObjCXX)
1752                 .Case("renderscript", Language::RenderScript)
1753                 .Default(Language::Unknown);
1754 
1755     // "objc[++]-cpp-output" is an acceptable synonym for
1756     // "objective-c[++]-cpp-output".
1757     if (DashX.isUnknown() && Preprocessed && !IsHeaderFile && !ModuleMap)
1758       DashX = llvm::StringSwitch<InputKind>(XValue)
1759                   .Case("objc", Language::ObjC)
1760                   .Case("objc++", Language::ObjCXX)
1761                   .Default(Language::Unknown);
1762 
1763     // Some special cases cannot be combined with suffixes.
1764     if (DashX.isUnknown() && !Preprocessed && !ModuleMap && !IsHeaderFile)
1765       DashX = llvm::StringSwitch<InputKind>(XValue)
1766                   .Case("cpp-output", InputKind(Language::C).getPreprocessed())
1767                   .Case("assembler-with-cpp", Language::Asm)
1768                   .Cases("ast", "pcm", "precompiled-header",
1769                          InputKind(Language::Unknown, InputKind::Precompiled))
1770                   .Case("ir", Language::LLVM_IR)
1771                   .Default(Language::Unknown);
1772 
1773     if (DashX.isUnknown())
1774       Diags.Report(diag::err_drv_invalid_value)
1775         << A->getAsString(Args) << A->getValue();
1776 
1777     if (Preprocessed)
1778       DashX = DashX.getPreprocessed();
1779     if (ModuleMap)
1780       DashX = DashX.withFormat(InputKind::ModuleMap);
1781   }
1782 
1783   // '-' is the default input if none is given.
1784   std::vector<std::string> Inputs = Args.getAllArgValues(OPT_INPUT);
1785   Opts.Inputs.clear();
1786   if (Inputs.empty())
1787     Inputs.push_back("-");
1788   for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
1789     InputKind IK = DashX;
1790     if (IK.isUnknown()) {
1791       IK = FrontendOptions::getInputKindForExtension(
1792         StringRef(Inputs[i]).rsplit('.').second);
1793       // FIXME: Warn on this?
1794       if (IK.isUnknown())
1795         IK = Language::C;
1796       // FIXME: Remove this hack.
1797       if (i == 0)
1798         DashX = IK;
1799     }
1800 
1801     bool IsSystem = false;
1802 
1803     // The -emit-module action implicitly takes a module map.
1804     if (Opts.ProgramAction == frontend::GenerateModule &&
1805         IK.getFormat() == InputKind::Source) {
1806       IK = IK.withFormat(InputKind::ModuleMap);
1807       IsSystem = Opts.IsSystemModule;
1808     }
1809 
1810     Opts.Inputs.emplace_back(std::move(Inputs[i]), IK, IsSystem);
1811   }
1812 
1813   return DashX;
1814 }
1815 
1816 std::string CompilerInvocation::GetResourcesPath(const char *Argv0,
1817                                                  void *MainAddr) {
1818   std::string ClangExecutable =
1819       llvm::sys::fs::getMainExecutable(Argv0, MainAddr);
1820   return Driver::GetResourcesPath(ClangExecutable, CLANG_RESOURCE_DIR);
1821 }
1822 
1823 static void ParseHeaderSearchArgs(HeaderSearchOptions &Opts, ArgList &Args,
1824                                   const std::string &WorkingDir) {
1825   if (const Arg *A = Args.getLastArg(OPT_stdlib_EQ))
1826     Opts.UseLibcxx = (strcmp(A->getValue(), "libc++") == 0);
1827 
1828   // Canonicalize -fmodules-cache-path before storing it.
1829   SmallString<128> P(Args.getLastArgValue(OPT_fmodules_cache_path));
1830   if (!(P.empty() || llvm::sys::path::is_absolute(P))) {
1831     if (WorkingDir.empty())
1832       llvm::sys::fs::make_absolute(P);
1833     else
1834       llvm::sys::fs::make_absolute(WorkingDir, P);
1835   }
1836   llvm::sys::path::remove_dots(P);
1837   Opts.ModuleCachePath = std::string(P.str());
1838 
1839   // Only the -fmodule-file=<name>=<file> form.
1840   for (const auto *A : Args.filtered(OPT_fmodule_file)) {
1841     StringRef Val = A->getValue();
1842     if (Val.find('=') != StringRef::npos){
1843       auto Split = Val.split('=');
1844       Opts.PrebuiltModuleFiles.insert(
1845           {std::string(Split.first), std::string(Split.second)});
1846     }
1847   }
1848   for (const auto *A : Args.filtered(OPT_fprebuilt_module_path))
1849     Opts.AddPrebuiltModulePath(A->getValue());
1850 
1851   for (const auto *A : Args.filtered(OPT_fmodules_ignore_macro)) {
1852     StringRef MacroDef = A->getValue();
1853     Opts.ModulesIgnoreMacros.insert(
1854         llvm::CachedHashString(MacroDef.split('=').first));
1855   }
1856 
1857   // Add -I..., -F..., and -index-header-map options in order.
1858   bool IsIndexHeaderMap = false;
1859   bool IsSysrootSpecified =
1860       Args.hasArg(OPT__sysroot_EQ) || Args.hasArg(OPT_isysroot);
1861   for (const auto *A : Args.filtered(OPT_I, OPT_F, OPT_index_header_map)) {
1862     if (A->getOption().matches(OPT_index_header_map)) {
1863       // -index-header-map applies to the next -I or -F.
1864       IsIndexHeaderMap = true;
1865       continue;
1866     }
1867 
1868     frontend::IncludeDirGroup Group =
1869         IsIndexHeaderMap ? frontend::IndexHeaderMap : frontend::Angled;
1870 
1871     bool IsFramework = A->getOption().matches(OPT_F);
1872     std::string Path = A->getValue();
1873 
1874     if (IsSysrootSpecified && !IsFramework && A->getValue()[0] == '=') {
1875       SmallString<32> Buffer;
1876       llvm::sys::path::append(Buffer, Opts.Sysroot,
1877                               llvm::StringRef(A->getValue()).substr(1));
1878       Path = std::string(Buffer.str());
1879     }
1880 
1881     Opts.AddPath(Path, Group, IsFramework,
1882                  /*IgnoreSysroot*/ true);
1883     IsIndexHeaderMap = false;
1884   }
1885 
1886   // Add -iprefix/-iwithprefix/-iwithprefixbefore options.
1887   StringRef Prefix = ""; // FIXME: This isn't the correct default prefix.
1888   for (const auto *A :
1889        Args.filtered(OPT_iprefix, OPT_iwithprefix, OPT_iwithprefixbefore)) {
1890     if (A->getOption().matches(OPT_iprefix))
1891       Prefix = A->getValue();
1892     else if (A->getOption().matches(OPT_iwithprefix))
1893       Opts.AddPath(Prefix.str() + A->getValue(), frontend::After, false, true);
1894     else
1895       Opts.AddPath(Prefix.str() + A->getValue(), frontend::Angled, false, true);
1896   }
1897 
1898   for (const auto *A : Args.filtered(OPT_idirafter))
1899     Opts.AddPath(A->getValue(), frontend::After, false, true);
1900   for (const auto *A : Args.filtered(OPT_iquote))
1901     Opts.AddPath(A->getValue(), frontend::Quoted, false, true);
1902   for (const auto *A : Args.filtered(OPT_isystem, OPT_iwithsysroot))
1903     Opts.AddPath(A->getValue(), frontend::System, false,
1904                  !A->getOption().matches(OPT_iwithsysroot));
1905   for (const auto *A : Args.filtered(OPT_iframework))
1906     Opts.AddPath(A->getValue(), frontend::System, true, true);
1907   for (const auto *A : Args.filtered(OPT_iframeworkwithsysroot))
1908     Opts.AddPath(A->getValue(), frontend::System, /*IsFramework=*/true,
1909                  /*IgnoreSysRoot=*/false);
1910 
1911   // Add the paths for the various language specific isystem flags.
1912   for (const auto *A : Args.filtered(OPT_c_isystem))
1913     Opts.AddPath(A->getValue(), frontend::CSystem, false, true);
1914   for (const auto *A : Args.filtered(OPT_cxx_isystem))
1915     Opts.AddPath(A->getValue(), frontend::CXXSystem, false, true);
1916   for (const auto *A : Args.filtered(OPT_objc_isystem))
1917     Opts.AddPath(A->getValue(), frontend::ObjCSystem, false,true);
1918   for (const auto *A : Args.filtered(OPT_objcxx_isystem))
1919     Opts.AddPath(A->getValue(), frontend::ObjCXXSystem, false, true);
1920 
1921   // Add the internal paths from a driver that detects standard include paths.
1922   for (const auto *A :
1923        Args.filtered(OPT_internal_isystem, OPT_internal_externc_isystem)) {
1924     frontend::IncludeDirGroup Group = frontend::System;
1925     if (A->getOption().matches(OPT_internal_externc_isystem))
1926       Group = frontend::ExternCSystem;
1927     Opts.AddPath(A->getValue(), Group, false, true);
1928   }
1929 
1930   // Add the path prefixes which are implicitly treated as being system headers.
1931   for (const auto *A :
1932        Args.filtered(OPT_system_header_prefix, OPT_no_system_header_prefix))
1933     Opts.AddSystemHeaderPrefix(
1934         A->getValue(), A->getOption().matches(OPT_system_header_prefix));
1935 
1936   for (const auto *A : Args.filtered(OPT_ivfsoverlay))
1937     Opts.AddVFSOverlayFile(A->getValue());
1938 }
1939 
1940 void CompilerInvocation::setLangDefaults(LangOptions &Opts, InputKind IK,
1941                                          const llvm::Triple &T,
1942                                          std::vector<std::string> &Includes,
1943                                          LangStandard::Kind LangStd) {
1944   // Set some properties which depend solely on the input kind; it would be nice
1945   // to move these to the language standard, and have the driver resolve the
1946   // input kind + language standard.
1947   //
1948   // FIXME: Perhaps a better model would be for a single source file to have
1949   // multiple language standards (C / C++ std, ObjC std, OpenCL std, OpenMP std)
1950   // simultaneously active?
1951   if (IK.getLanguage() == Language::Asm) {
1952     Opts.AsmPreprocessor = 1;
1953   } else if (IK.isObjectiveC()) {
1954     Opts.ObjC = 1;
1955   }
1956 
1957   if (LangStd == LangStandard::lang_unspecified) {
1958     // Based on the base language, pick one.
1959     switch (IK.getLanguage()) {
1960     case Language::Unknown:
1961     case Language::LLVM_IR:
1962       llvm_unreachable("Invalid input kind!");
1963     case Language::OpenCL:
1964       LangStd = LangStandard::lang_opencl10;
1965       break;
1966     case Language::CUDA:
1967       LangStd = LangStandard::lang_cuda;
1968       break;
1969     case Language::Asm:
1970     case Language::C:
1971 #if defined(CLANG_DEFAULT_STD_C)
1972       LangStd = CLANG_DEFAULT_STD_C;
1973 #else
1974       // The PS4 uses C99 as the default C standard.
1975       if (T.isPS4())
1976         LangStd = LangStandard::lang_gnu99;
1977       else
1978         LangStd = LangStandard::lang_gnu17;
1979 #endif
1980       break;
1981     case Language::ObjC:
1982 #if defined(CLANG_DEFAULT_STD_C)
1983       LangStd = CLANG_DEFAULT_STD_C;
1984 #else
1985       LangStd = LangStandard::lang_gnu11;
1986 #endif
1987       break;
1988     case Language::CXX:
1989     case Language::ObjCXX:
1990 #if defined(CLANG_DEFAULT_STD_CXX)
1991       LangStd = CLANG_DEFAULT_STD_CXX;
1992 #else
1993       LangStd = LangStandard::lang_gnucxx14;
1994 #endif
1995       break;
1996     case Language::RenderScript:
1997       LangStd = LangStandard::lang_c99;
1998       break;
1999     case Language::HIP:
2000       LangStd = LangStandard::lang_hip;
2001       break;
2002     }
2003   }
2004 
2005   const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
2006   Opts.LangStd = LangStd;
2007   Opts.LineComment = Std.hasLineComments();
2008   Opts.C99 = Std.isC99();
2009   Opts.C11 = Std.isC11();
2010   Opts.C17 = Std.isC17();
2011   Opts.C2x = Std.isC2x();
2012   Opts.CPlusPlus = Std.isCPlusPlus();
2013   Opts.CPlusPlus11 = Std.isCPlusPlus11();
2014   Opts.CPlusPlus14 = Std.isCPlusPlus14();
2015   Opts.CPlusPlus17 = Std.isCPlusPlus17();
2016   Opts.CPlusPlus20 = Std.isCPlusPlus20();
2017   Opts.CPlusPlus2b = Std.isCPlusPlus2b();
2018   Opts.GNUMode = Std.isGNUMode();
2019   Opts.GNUCVersion = 0;
2020   Opts.HexFloats = Std.hasHexFloats();
2021   Opts.ImplicitInt = Std.hasImplicitInt();
2022 
2023   Opts.CPlusPlusModules = Opts.CPlusPlus20;
2024 
2025   // Set OpenCL Version.
2026   Opts.OpenCL = Std.isOpenCL();
2027   if (LangStd == LangStandard::lang_opencl10)
2028     Opts.OpenCLVersion = 100;
2029   else if (LangStd == LangStandard::lang_opencl11)
2030     Opts.OpenCLVersion = 110;
2031   else if (LangStd == LangStandard::lang_opencl12)
2032     Opts.OpenCLVersion = 120;
2033   else if (LangStd == LangStandard::lang_opencl20)
2034     Opts.OpenCLVersion = 200;
2035   else if (LangStd == LangStandard::lang_opencl30)
2036     Opts.OpenCLVersion = 300;
2037   else if (LangStd == LangStandard::lang_openclcpp)
2038     Opts.OpenCLCPlusPlusVersion = 100;
2039 
2040   // OpenCL has some additional defaults.
2041   if (Opts.OpenCL) {
2042     Opts.AltiVec = 0;
2043     Opts.ZVector = 0;
2044     Opts.setDefaultFPContractMode(LangOptions::FPM_On);
2045     Opts.OpenCLCPlusPlus = Opts.CPlusPlus;
2046 
2047     // Include default header file for OpenCL.
2048     if (Opts.IncludeDefaultHeader) {
2049       if (Opts.DeclareOpenCLBuiltins) {
2050         // Only include base header file for builtin types and constants.
2051         Includes.push_back("opencl-c-base.h");
2052       } else {
2053         Includes.push_back("opencl-c.h");
2054       }
2055     }
2056   }
2057 
2058   Opts.HIP = IK.getLanguage() == Language::HIP;
2059   Opts.CUDA = IK.getLanguage() == Language::CUDA || Opts.HIP;
2060   if (Opts.HIP) {
2061     // HIP toolchain does not support 'Fast' FPOpFusion in backends since it
2062     // fuses multiplication/addition instructions without contract flag from
2063     // device library functions in LLVM bitcode, which causes accuracy loss in
2064     // certain math functions, e.g. tan(-1e20) becomes -0.933 instead of 0.8446.
2065     // For device library functions in bitcode to work, 'Strict' or 'Standard'
2066     // FPOpFusion options in backends is needed. Therefore 'fast-honor-pragmas'
2067     // FP contract option is used to allow fuse across statements in frontend
2068     // whereas respecting contract flag in backend.
2069     Opts.setDefaultFPContractMode(LangOptions::FPM_FastHonorPragmas);
2070   } else if (Opts.CUDA) {
2071     // Allow fuse across statements disregarding pragmas.
2072     Opts.setDefaultFPContractMode(LangOptions::FPM_Fast);
2073   }
2074 
2075   Opts.RenderScript = IK.getLanguage() == Language::RenderScript;
2076 
2077   // OpenCL and C++ both have bool, true, false keywords.
2078   Opts.Bool = Opts.OpenCL || Opts.CPlusPlus;
2079 
2080   // OpenCL has half keyword
2081   Opts.Half = Opts.OpenCL;
2082 }
2083 
2084 /// Check if input file kind and language standard are compatible.
2085 static bool IsInputCompatibleWithStandard(InputKind IK,
2086                                           const LangStandard &S) {
2087   switch (IK.getLanguage()) {
2088   case Language::Unknown:
2089   case Language::LLVM_IR:
2090     llvm_unreachable("should not parse language flags for this input");
2091 
2092   case Language::C:
2093   case Language::ObjC:
2094   case Language::RenderScript:
2095     return S.getLanguage() == Language::C;
2096 
2097   case Language::OpenCL:
2098     return S.getLanguage() == Language::OpenCL;
2099 
2100   case Language::CXX:
2101   case Language::ObjCXX:
2102     return S.getLanguage() == Language::CXX;
2103 
2104   case Language::CUDA:
2105     // FIXME: What -std= values should be permitted for CUDA compilations?
2106     return S.getLanguage() == Language::CUDA ||
2107            S.getLanguage() == Language::CXX;
2108 
2109   case Language::HIP:
2110     return S.getLanguage() == Language::CXX || S.getLanguage() == Language::HIP;
2111 
2112   case Language::Asm:
2113     // Accept (and ignore) all -std= values.
2114     // FIXME: The -std= value is not ignored; it affects the tokenization
2115     // and preprocessing rules if we're preprocessing this asm input.
2116     return true;
2117   }
2118 
2119   llvm_unreachable("unexpected input language");
2120 }
2121 
2122 /// Get language name for given input kind.
2123 static const StringRef GetInputKindName(InputKind IK) {
2124   switch (IK.getLanguage()) {
2125   case Language::C:
2126     return "C";
2127   case Language::ObjC:
2128     return "Objective-C";
2129   case Language::CXX:
2130     return "C++";
2131   case Language::ObjCXX:
2132     return "Objective-C++";
2133   case Language::OpenCL:
2134     return "OpenCL";
2135   case Language::CUDA:
2136     return "CUDA";
2137   case Language::RenderScript:
2138     return "RenderScript";
2139   case Language::HIP:
2140     return "HIP";
2141 
2142   case Language::Asm:
2143     return "Asm";
2144   case Language::LLVM_IR:
2145     return "LLVM IR";
2146 
2147   case Language::Unknown:
2148     break;
2149   }
2150   llvm_unreachable("unknown input language");
2151 }
2152 
2153 static void GenerateLangArgs(const LangOptions &Opts,
2154                              SmallVectorImpl<const char *> &Args,
2155                              CompilerInvocation::StringAllocator SA) {
2156   if (Opts.IncludeDefaultHeader)
2157     Args.push_back(SA(GetOptName(OPT_finclude_default_header)));
2158   if (Opts.DeclareOpenCLBuiltins)
2159     Args.push_back(SA(GetOptName(OPT_fdeclare_opencl_builtins)));
2160 }
2161 
2162 void CompilerInvocation::ParseLangArgs(LangOptions &Opts, ArgList &Args,
2163                                        InputKind IK, const llvm::Triple &T,
2164                                        std::vector<std::string> &Includes,
2165                                        DiagnosticsEngine &Diags) {
2166   // FIXME: Cleanup per-file based stuff.
2167   LangStandard::Kind LangStd = LangStandard::lang_unspecified;
2168   if (const Arg *A = Args.getLastArg(OPT_std_EQ)) {
2169     LangStd = LangStandard::getLangKind(A->getValue());
2170     if (LangStd == LangStandard::lang_unspecified) {
2171       Diags.Report(diag::err_drv_invalid_value)
2172         << A->getAsString(Args) << A->getValue();
2173       // Report supported standards with short description.
2174       for (unsigned KindValue = 0;
2175            KindValue != LangStandard::lang_unspecified;
2176            ++KindValue) {
2177         const LangStandard &Std = LangStandard::getLangStandardForKind(
2178           static_cast<LangStandard::Kind>(KindValue));
2179         if (IsInputCompatibleWithStandard(IK, Std)) {
2180           auto Diag = Diags.Report(diag::note_drv_use_standard);
2181           Diag << Std.getName() << Std.getDescription();
2182           unsigned NumAliases = 0;
2183 #define LANGSTANDARD(id, name, lang, desc, features)
2184 #define LANGSTANDARD_ALIAS(id, alias) \
2185           if (KindValue == LangStandard::lang_##id) ++NumAliases;
2186 #define LANGSTANDARD_ALIAS_DEPR(id, alias)
2187 #include "clang/Basic/LangStandards.def"
2188           Diag << NumAliases;
2189 #define LANGSTANDARD(id, name, lang, desc, features)
2190 #define LANGSTANDARD_ALIAS(id, alias) \
2191           if (KindValue == LangStandard::lang_##id) Diag << alias;
2192 #define LANGSTANDARD_ALIAS_DEPR(id, alias)
2193 #include "clang/Basic/LangStandards.def"
2194         }
2195       }
2196     } else {
2197       // Valid standard, check to make sure language and standard are
2198       // compatible.
2199       const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
2200       if (!IsInputCompatibleWithStandard(IK, Std)) {
2201         Diags.Report(diag::err_drv_argument_not_allowed_with)
2202           << A->getAsString(Args) << GetInputKindName(IK);
2203       }
2204     }
2205   }
2206 
2207   // -cl-std only applies for OpenCL language standards.
2208   // Override the -std option in this case.
2209   if (const Arg *A = Args.getLastArg(OPT_cl_std_EQ)) {
2210     LangStandard::Kind OpenCLLangStd
2211       = llvm::StringSwitch<LangStandard::Kind>(A->getValue())
2212         .Cases("cl", "CL", LangStandard::lang_opencl10)
2213         .Cases("cl1.0", "CL1.0", LangStandard::lang_opencl10)
2214         .Cases("cl1.1", "CL1.1", LangStandard::lang_opencl11)
2215         .Cases("cl1.2", "CL1.2", LangStandard::lang_opencl12)
2216         .Cases("cl2.0", "CL2.0", LangStandard::lang_opencl20)
2217         .Cases("cl3.0", "CL3.0", LangStandard::lang_opencl30)
2218         .Cases("clc++", "CLC++", LangStandard::lang_openclcpp)
2219         .Default(LangStandard::lang_unspecified);
2220 
2221     if (OpenCLLangStd == LangStandard::lang_unspecified) {
2222       Diags.Report(diag::err_drv_invalid_value)
2223         << A->getAsString(Args) << A->getValue();
2224     }
2225     else
2226       LangStd = OpenCLLangStd;
2227   }
2228 
2229   // These need to be parsed now. They are used to set OpenCL defaults.
2230   Opts.IncludeDefaultHeader = Args.hasArg(OPT_finclude_default_header);
2231   Opts.DeclareOpenCLBuiltins = Args.hasArg(OPT_fdeclare_opencl_builtins);
2232 
2233   CompilerInvocation::setLangDefaults(Opts, IK, T, Includes, LangStd);
2234 
2235   // The key paths of codegen options defined in Options.td start with
2236   // "LangOpts->". Let's provide the expected variable name and type.
2237   LangOptions *LangOpts = &Opts;
2238   bool Success = true;
2239 
2240 #define LANG_OPTION_WITH_MARSHALLING(                                          \
2241     PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,        \
2242     HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
2243     DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER,     \
2244     MERGER, EXTRACTOR, TABLE_INDEX)                                            \
2245   PARSE_OPTION_WITH_MARSHALLING(Args, Diags, Success, ID, FLAGS, PARAM,        \
2246                                 SHOULD_PARSE, KEYPATH, DEFAULT_VALUE,          \
2247                                 IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER,      \
2248                                 MERGER, TABLE_INDEX)
2249 #include "clang/Driver/Options.inc"
2250 #undef LANG_OPTION_WITH_MARSHALLING
2251 
2252   if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
2253     StringRef Name = A->getValue();
2254     if (Name == "full" || Name == "branch") {
2255       Opts.CFProtectionBranch = 1;
2256     }
2257   }
2258 
2259   if (Opts.ObjC) {
2260     if (Arg *arg = Args.getLastArg(OPT_fobjc_runtime_EQ)) {
2261       StringRef value = arg->getValue();
2262       if (Opts.ObjCRuntime.tryParse(value))
2263         Diags.Report(diag::err_drv_unknown_objc_runtime) << value;
2264     }
2265 
2266     if (Args.hasArg(OPT_fobjc_gc_only))
2267       Opts.setGC(LangOptions::GCOnly);
2268     else if (Args.hasArg(OPT_fobjc_gc))
2269       Opts.setGC(LangOptions::HybridGC);
2270     else if (Args.hasArg(OPT_fobjc_arc)) {
2271       Opts.ObjCAutoRefCount = 1;
2272       if (!Opts.ObjCRuntime.allowsARC())
2273         Diags.Report(diag::err_arc_unsupported_on_runtime);
2274     }
2275 
2276     // ObjCWeakRuntime tracks whether the runtime supports __weak, not
2277     // whether the feature is actually enabled.  This is predominantly
2278     // determined by -fobjc-runtime, but we allow it to be overridden
2279     // from the command line for testing purposes.
2280     if (Args.hasArg(OPT_fobjc_runtime_has_weak))
2281       Opts.ObjCWeakRuntime = 1;
2282     else
2283       Opts.ObjCWeakRuntime = Opts.ObjCRuntime.allowsWeak();
2284 
2285     // ObjCWeak determines whether __weak is actually enabled.
2286     // Note that we allow -fno-objc-weak to disable this even in ARC mode.
2287     if (auto weakArg = Args.getLastArg(OPT_fobjc_weak, OPT_fno_objc_weak)) {
2288       if (!weakArg->getOption().matches(OPT_fobjc_weak)) {
2289         assert(!Opts.ObjCWeak);
2290       } else if (Opts.getGC() != LangOptions::NonGC) {
2291         Diags.Report(diag::err_objc_weak_with_gc);
2292       } else if (!Opts.ObjCWeakRuntime) {
2293         Diags.Report(diag::err_objc_weak_unsupported);
2294       } else {
2295         Opts.ObjCWeak = 1;
2296       }
2297     } else if (Opts.ObjCAutoRefCount) {
2298       Opts.ObjCWeak = Opts.ObjCWeakRuntime;
2299     }
2300 
2301     if (Args.hasArg(OPT_fobjc_subscripting_legacy_runtime))
2302       Opts.ObjCSubscriptingLegacyRuntime =
2303         (Opts.ObjCRuntime.getKind() == ObjCRuntime::FragileMacOSX);
2304   }
2305 
2306   if (Arg *A = Args.getLastArg(options::OPT_fgnuc_version_EQ)) {
2307     // Check that the version has 1 to 3 components and the minor and patch
2308     // versions fit in two decimal digits.
2309     VersionTuple GNUCVer;
2310     bool Invalid = GNUCVer.tryParse(A->getValue());
2311     unsigned Major = GNUCVer.getMajor();
2312     unsigned Minor = GNUCVer.getMinor().getValueOr(0);
2313     unsigned Patch = GNUCVer.getSubminor().getValueOr(0);
2314     if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) {
2315       Diags.Report(diag::err_drv_invalid_value)
2316           << A->getAsString(Args) << A->getValue();
2317     }
2318     Opts.GNUCVersion = Major * 100 * 100 + Minor * 100 + Patch;
2319   }
2320 
2321   if (Args.hasArg(OPT_ftrapv)) {
2322     Opts.setSignedOverflowBehavior(LangOptions::SOB_Trapping);
2323     // Set the handler, if one is specified.
2324     Opts.OverflowHandler =
2325         std::string(Args.getLastArgValue(OPT_ftrapv_handler));
2326   }
2327   else if (Args.hasArg(OPT_fwrapv))
2328     Opts.setSignedOverflowBehavior(LangOptions::SOB_Defined);
2329 
2330   Opts.MSCompatibilityVersion = 0;
2331   if (const Arg *A = Args.getLastArg(OPT_fms_compatibility_version)) {
2332     VersionTuple VT;
2333     if (VT.tryParse(A->getValue()))
2334       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
2335                                                 << A->getValue();
2336     Opts.MSCompatibilityVersion = VT.getMajor() * 10000000 +
2337                                   VT.getMinor().getValueOr(0) * 100000 +
2338                                   VT.getSubminor().getValueOr(0);
2339   }
2340 
2341   // Mimicking gcc's behavior, trigraphs are only enabled if -trigraphs
2342   // is specified, or -std is set to a conforming mode.
2343   // Trigraphs are disabled by default in c++1z onwards.
2344   // For z/OS, trigraphs are enabled by default (without regard to the above).
2345   Opts.Trigraphs =
2346       (!Opts.GNUMode && !Opts.MSVCCompat && !Opts.CPlusPlus17) || T.isOSzOS();
2347   Opts.Trigraphs =
2348       Args.hasFlag(OPT_ftrigraphs, OPT_fno_trigraphs, Opts.Trigraphs);
2349 
2350   Opts.Blocks = Args.hasArg(OPT_fblocks) || (Opts.OpenCL
2351     && Opts.OpenCLVersion == 200);
2352 
2353   Opts.ConvergentFunctions = Opts.OpenCL || (Opts.CUDA && Opts.CUDAIsDevice) ||
2354                              Opts.SYCLIsDevice ||
2355                              Args.hasArg(OPT_fconvergent_functions);
2356 
2357   Opts.NoBuiltin = Args.hasArg(OPT_fno_builtin) || Opts.Freestanding;
2358   if (!Opts.NoBuiltin)
2359     getAllNoBuiltinFuncValues(Args, Opts.NoBuiltinFuncs);
2360   Opts.LongDoubleSize = Args.hasArg(OPT_mlong_double_128)
2361                             ? 128
2362                             : Args.hasArg(OPT_mlong_double_64) ? 64 : 0;
2363   if (Opts.FastRelaxedMath)
2364     Opts.setDefaultFPContractMode(LangOptions::FPM_Fast);
2365   llvm::sort(Opts.ModuleFeatures);
2366 
2367   // -mrtd option
2368   if (Arg *A = Args.getLastArg(OPT_mrtd)) {
2369     if (Opts.getDefaultCallingConv() != LangOptions::DCC_None)
2370       Diags.Report(diag::err_drv_argument_not_allowed_with)
2371           << A->getSpelling() << "-fdefault-calling-conv";
2372     else {
2373       if (T.getArch() != llvm::Triple::x86)
2374         Diags.Report(diag::err_drv_argument_not_allowed_with)
2375             << A->getSpelling() << T.getTriple();
2376       else
2377         Opts.setDefaultCallingConv(LangOptions::DCC_StdCall);
2378     }
2379   }
2380 
2381   // Check if -fopenmp-simd is specified.
2382   bool IsSimdSpecified =
2383       Args.hasFlag(options::OPT_fopenmp_simd, options::OPT_fno_openmp_simd,
2384                    /*Default=*/false);
2385   Opts.OpenMPSimd = !Opts.OpenMP && IsSimdSpecified;
2386   Opts.OpenMPUseTLS =
2387       Opts.OpenMP && !Args.hasArg(options::OPT_fnoopenmp_use_tls);
2388   Opts.OpenMPIsDevice =
2389       Opts.OpenMP && Args.hasArg(options::OPT_fopenmp_is_device);
2390   Opts.OpenMPIRBuilder =
2391       Opts.OpenMP && Args.hasArg(options::OPT_fopenmp_enable_irbuilder);
2392   bool IsTargetSpecified =
2393       Opts.OpenMPIsDevice || Args.hasArg(options::OPT_fopenmp_targets_EQ);
2394 
2395   if (Opts.OpenMP || Opts.OpenMPSimd) {
2396     if (int Version = getLastArgIntValue(
2397             Args, OPT_fopenmp_version_EQ,
2398             (IsSimdSpecified || IsTargetSpecified) ? 50 : Opts.OpenMP, Diags))
2399       Opts.OpenMP = Version;
2400     // Provide diagnostic when a given target is not expected to be an OpenMP
2401     // device or host.
2402     if (!Opts.OpenMPIsDevice) {
2403       switch (T.getArch()) {
2404       default:
2405         break;
2406       // Add unsupported host targets here:
2407       case llvm::Triple::nvptx:
2408       case llvm::Triple::nvptx64:
2409         Diags.Report(diag::err_drv_omp_host_target_not_supported) << T.str();
2410         break;
2411       }
2412     }
2413   }
2414 
2415   // Set the flag to prevent the implementation from emitting device exception
2416   // handling code for those requiring so.
2417   if ((Opts.OpenMPIsDevice && (T.isNVPTX() || T.isAMDGCN())) ||
2418       Opts.OpenCLCPlusPlus) {
2419     Opts.Exceptions = 0;
2420     Opts.CXXExceptions = 0;
2421   }
2422   if (Opts.OpenMPIsDevice && T.isNVPTX()) {
2423     Opts.OpenMPCUDANumSMs =
2424         getLastArgIntValue(Args, options::OPT_fopenmp_cuda_number_of_sm_EQ,
2425                            Opts.OpenMPCUDANumSMs, Diags);
2426     Opts.OpenMPCUDABlocksPerSM =
2427         getLastArgIntValue(Args, options::OPT_fopenmp_cuda_blocks_per_sm_EQ,
2428                            Opts.OpenMPCUDABlocksPerSM, Diags);
2429     Opts.OpenMPCUDAReductionBufNum = getLastArgIntValue(
2430         Args, options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ,
2431         Opts.OpenMPCUDAReductionBufNum, Diags);
2432   }
2433 
2434   // Get the OpenMP target triples if any.
2435   if (Arg *A = Args.getLastArg(options::OPT_fopenmp_targets_EQ)) {
2436     enum ArchPtrSize { Arch16Bit, Arch32Bit, Arch64Bit };
2437     auto getArchPtrSize = [](const llvm::Triple &T) {
2438       if (T.isArch16Bit())
2439         return Arch16Bit;
2440       if (T.isArch32Bit())
2441         return Arch32Bit;
2442       assert(T.isArch64Bit() && "Expected 64-bit architecture");
2443       return Arch64Bit;
2444     };
2445 
2446     for (unsigned i = 0; i < A->getNumValues(); ++i) {
2447       llvm::Triple TT(A->getValue(i));
2448 
2449       if (TT.getArch() == llvm::Triple::UnknownArch ||
2450           !(TT.getArch() == llvm::Triple::aarch64 || TT.isPPC() ||
2451             TT.getArch() == llvm::Triple::nvptx ||
2452             TT.getArch() == llvm::Triple::nvptx64 ||
2453             TT.getArch() == llvm::Triple::amdgcn ||
2454             TT.getArch() == llvm::Triple::x86 ||
2455             TT.getArch() == llvm::Triple::x86_64))
2456         Diags.Report(diag::err_drv_invalid_omp_target) << A->getValue(i);
2457       else if (getArchPtrSize(T) != getArchPtrSize(TT))
2458         Diags.Report(diag::err_drv_incompatible_omp_arch)
2459             << A->getValue(i) << T.str();
2460       else
2461         Opts.OMPTargetTriples.push_back(TT);
2462     }
2463   }
2464 
2465   // Get OpenMP host file path if any and report if a non existent file is
2466   // found
2467   if (Arg *A = Args.getLastArg(options::OPT_fopenmp_host_ir_file_path)) {
2468     Opts.OMPHostIRFile = A->getValue();
2469     if (!llvm::sys::fs::exists(Opts.OMPHostIRFile))
2470       Diags.Report(diag::err_drv_omp_host_ir_file_not_found)
2471           << Opts.OMPHostIRFile;
2472   }
2473 
2474   // Set CUDA mode for OpenMP target NVPTX/AMDGCN if specified in options
2475   Opts.OpenMPCUDAMode = Opts.OpenMPIsDevice && (T.isNVPTX() || T.isAMDGCN()) &&
2476                         Args.hasArg(options::OPT_fopenmp_cuda_mode);
2477 
2478   // Set CUDA support for parallel execution of target regions for OpenMP target
2479   // NVPTX/AMDGCN if specified in options.
2480   Opts.OpenMPCUDATargetParallel =
2481       Opts.OpenMPIsDevice && (T.isNVPTX() || T.isAMDGCN()) &&
2482       Args.hasArg(options::OPT_fopenmp_cuda_parallel_target_regions);
2483 
2484   // Set CUDA mode for OpenMP target NVPTX/AMDGCN if specified in options
2485   Opts.OpenMPCUDAForceFullRuntime =
2486       Opts.OpenMPIsDevice && (T.isNVPTX() || T.isAMDGCN()) &&
2487       Args.hasArg(options::OPT_fopenmp_cuda_force_full_runtime);
2488 
2489   // FIXME: Eliminate this dependency.
2490   unsigned Opt = getOptimizationLevel(Args, IK, Diags),
2491        OptSize = getOptimizationLevelSize(Args);
2492   Opts.Optimize = Opt != 0;
2493   Opts.OptimizeSize = OptSize != 0;
2494 
2495   // This is the __NO_INLINE__ define, which just depends on things like the
2496   // optimization level and -fno-inline, not actually whether the backend has
2497   // inlining enabled.
2498   Opts.NoInlineDefine = !Opts.Optimize;
2499   if (Arg *InlineArg = Args.getLastArg(
2500           options::OPT_finline_functions, options::OPT_finline_hint_functions,
2501           options::OPT_fno_inline_functions, options::OPT_fno_inline))
2502     if (InlineArg->getOption().matches(options::OPT_fno_inline))
2503       Opts.NoInlineDefine = true;
2504 
2505   if (Arg *A = Args.getLastArg(OPT_ffp_contract)) {
2506     StringRef Val = A->getValue();
2507     if (Val == "fast")
2508       Opts.setDefaultFPContractMode(LangOptions::FPM_Fast);
2509     else if (Val == "on")
2510       Opts.setDefaultFPContractMode(LangOptions::FPM_On);
2511     else if (Val == "off")
2512       Opts.setDefaultFPContractMode(LangOptions::FPM_Off);
2513     else if (Val == "fast-honor-pragmas")
2514       Opts.setDefaultFPContractMode(LangOptions::FPM_FastHonorPragmas);
2515     else
2516       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
2517   }
2518 
2519   // Parse -fsanitize= arguments.
2520   parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ),
2521                       Diags, Opts.Sanitize);
2522   std::vector<std::string> systemBlacklists =
2523       Args.getAllArgValues(OPT_fsanitize_system_blacklist);
2524   Opts.SanitizerBlacklistFiles.insert(Opts.SanitizerBlacklistFiles.end(),
2525                                       systemBlacklists.begin(),
2526                                       systemBlacklists.end());
2527 
2528   if (Arg *A = Args.getLastArg(OPT_fclang_abi_compat_EQ)) {
2529     Opts.setClangABICompat(LangOptions::ClangABI::Latest);
2530 
2531     StringRef Ver = A->getValue();
2532     std::pair<StringRef, StringRef> VerParts = Ver.split('.');
2533     unsigned Major, Minor = 0;
2534 
2535     // Check the version number is valid: either 3.x (0 <= x <= 9) or
2536     // y or y.0 (4 <= y <= current version).
2537     if (!VerParts.first.startswith("0") &&
2538         !VerParts.first.getAsInteger(10, Major) &&
2539         3 <= Major && Major <= CLANG_VERSION_MAJOR &&
2540         (Major == 3 ? VerParts.second.size() == 1 &&
2541                       !VerParts.second.getAsInteger(10, Minor)
2542                     : VerParts.first.size() == Ver.size() ||
2543                       VerParts.second == "0")) {
2544       // Got a valid version number.
2545       if (Major == 3 && Minor <= 8)
2546         Opts.setClangABICompat(LangOptions::ClangABI::Ver3_8);
2547       else if (Major <= 4)
2548         Opts.setClangABICompat(LangOptions::ClangABI::Ver4);
2549       else if (Major <= 6)
2550         Opts.setClangABICompat(LangOptions::ClangABI::Ver6);
2551       else if (Major <= 7)
2552         Opts.setClangABICompat(LangOptions::ClangABI::Ver7);
2553       else if (Major <= 9)
2554         Opts.setClangABICompat(LangOptions::ClangABI::Ver9);
2555       else if (Major <= 11)
2556         Opts.setClangABICompat(LangOptions::ClangABI::Ver11);
2557     } else if (Ver != "latest") {
2558       Diags.Report(diag::err_drv_invalid_value)
2559           << A->getAsString(Args) << A->getValue();
2560     }
2561   }
2562 
2563   if (Arg *A = Args.getLastArg(OPT_msign_return_address_EQ)) {
2564     StringRef SignScope = A->getValue();
2565 
2566     if (SignScope.equals_lower("none"))
2567       Opts.setSignReturnAddressScope(
2568           LangOptions::SignReturnAddressScopeKind::None);
2569     else if (SignScope.equals_lower("all"))
2570       Opts.setSignReturnAddressScope(
2571           LangOptions::SignReturnAddressScopeKind::All);
2572     else if (SignScope.equals_lower("non-leaf"))
2573       Opts.setSignReturnAddressScope(
2574           LangOptions::SignReturnAddressScopeKind::NonLeaf);
2575     else
2576       Diags.Report(diag::err_drv_invalid_value)
2577           << A->getAsString(Args) << SignScope;
2578 
2579     if (Arg *A = Args.getLastArg(OPT_msign_return_address_key_EQ)) {
2580       StringRef SignKey = A->getValue();
2581       if (!SignScope.empty() && !SignKey.empty()) {
2582         if (SignKey.equals_lower("a_key"))
2583           Opts.setSignReturnAddressKey(
2584               LangOptions::SignReturnAddressKeyKind::AKey);
2585         else if (SignKey.equals_lower("b_key"))
2586           Opts.setSignReturnAddressKey(
2587               LangOptions::SignReturnAddressKeyKind::BKey);
2588         else
2589           Diags.Report(diag::err_drv_invalid_value)
2590               << A->getAsString(Args) << SignKey;
2591       }
2592     }
2593   }
2594 }
2595 
2596 static bool isStrictlyPreprocessorAction(frontend::ActionKind Action) {
2597   switch (Action) {
2598   case frontend::ASTDeclList:
2599   case frontend::ASTDump:
2600   case frontend::ASTPrint:
2601   case frontend::ASTView:
2602   case frontend::EmitAssembly:
2603   case frontend::EmitBC:
2604   case frontend::EmitHTML:
2605   case frontend::EmitLLVM:
2606   case frontend::EmitLLVMOnly:
2607   case frontend::EmitCodeGenOnly:
2608   case frontend::EmitObj:
2609   case frontend::FixIt:
2610   case frontend::GenerateModule:
2611   case frontend::GenerateModuleInterface:
2612   case frontend::GenerateHeaderModule:
2613   case frontend::GeneratePCH:
2614   case frontend::GenerateInterfaceStubs:
2615   case frontend::ParseSyntaxOnly:
2616   case frontend::ModuleFileInfo:
2617   case frontend::VerifyPCH:
2618   case frontend::PluginAction:
2619   case frontend::RewriteObjC:
2620   case frontend::RewriteTest:
2621   case frontend::RunAnalysis:
2622   case frontend::TemplightDump:
2623   case frontend::MigrateSource:
2624     return false;
2625 
2626   case frontend::DumpCompilerOptions:
2627   case frontend::DumpRawTokens:
2628   case frontend::DumpTokens:
2629   case frontend::InitOnly:
2630   case frontend::PrintPreamble:
2631   case frontend::PrintPreprocessedInput:
2632   case frontend::RewriteMacros:
2633   case frontend::RunPreprocessorOnly:
2634   case frontend::PrintDependencyDirectivesSourceMinimizerOutput:
2635     return true;
2636   }
2637   llvm_unreachable("invalid frontend action");
2638 }
2639 
2640 static void ParsePreprocessorArgs(PreprocessorOptions &Opts, ArgList &Args,
2641                                   DiagnosticsEngine &Diags,
2642                                   frontend::ActionKind Action) {
2643   Opts.PCHWithHdrStop = Args.hasArg(OPT_pch_through_hdrstop_create) ||
2644                         Args.hasArg(OPT_pch_through_hdrstop_use);
2645 
2646   for (const auto *A : Args.filtered(OPT_error_on_deserialized_pch_decl))
2647     Opts.DeserializedPCHDeclsToErrorOn.insert(A->getValue());
2648 
2649   for (const auto &A : Args.getAllArgValues(OPT_fmacro_prefix_map_EQ)) {
2650     auto Split = StringRef(A).split('=');
2651     Opts.MacroPrefixMap.insert(
2652         {std::string(Split.first), std::string(Split.second)});
2653   }
2654 
2655   if (const Arg *A = Args.getLastArg(OPT_preamble_bytes_EQ)) {
2656     StringRef Value(A->getValue());
2657     size_t Comma = Value.find(',');
2658     unsigned Bytes = 0;
2659     unsigned EndOfLine = 0;
2660 
2661     if (Comma == StringRef::npos ||
2662         Value.substr(0, Comma).getAsInteger(10, Bytes) ||
2663         Value.substr(Comma + 1).getAsInteger(10, EndOfLine))
2664       Diags.Report(diag::err_drv_preamble_format);
2665     else {
2666       Opts.PrecompiledPreambleBytes.first = Bytes;
2667       Opts.PrecompiledPreambleBytes.second = (EndOfLine != 0);
2668     }
2669   }
2670 
2671   // Add the __CET__ macro if a CFProtection option is set.
2672   if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
2673     StringRef Name = A->getValue();
2674     if (Name == "branch")
2675       Opts.addMacroDef("__CET__=1");
2676     else if (Name == "return")
2677       Opts.addMacroDef("__CET__=2");
2678     else if (Name == "full")
2679       Opts.addMacroDef("__CET__=3");
2680   }
2681 
2682   // Add macros from the command line.
2683   for (const auto *A : Args.filtered(OPT_D, OPT_U)) {
2684     if (A->getOption().matches(OPT_D))
2685       Opts.addMacroDef(A->getValue());
2686     else
2687       Opts.addMacroUndef(A->getValue());
2688   }
2689 
2690   // Add the ordered list of -includes.
2691   for (const auto *A : Args.filtered(OPT_include))
2692     Opts.Includes.emplace_back(A->getValue());
2693 
2694   for (const auto *A : Args.filtered(OPT_chain_include))
2695     Opts.ChainedIncludes.emplace_back(A->getValue());
2696 
2697   for (const auto *A : Args.filtered(OPT_remap_file)) {
2698     std::pair<StringRef, StringRef> Split = StringRef(A->getValue()).split(';');
2699 
2700     if (Split.second.empty()) {
2701       Diags.Report(diag::err_drv_invalid_remap_file) << A->getAsString(Args);
2702       continue;
2703     }
2704 
2705     Opts.addRemappedFile(Split.first, Split.second);
2706   }
2707 
2708   // Always avoid lexing editor placeholders when we're just running the
2709   // preprocessor as we never want to emit the
2710   // "editor placeholder in source file" error in PP only mode.
2711   if (isStrictlyPreprocessorAction(Action))
2712     Opts.LexEditorPlaceholders = false;
2713 }
2714 
2715 static void ParsePreprocessorOutputArgs(PreprocessorOutputOptions &Opts,
2716                                         ArgList &Args,
2717                                         frontend::ActionKind Action) {
2718   if (isStrictlyPreprocessorAction(Action))
2719     Opts.ShowCPP = !Args.hasArg(OPT_dM);
2720   else
2721     Opts.ShowCPP = 0;
2722 
2723   Opts.ShowMacros = Args.hasArg(OPT_dM) || Args.hasArg(OPT_dD);
2724 }
2725 
2726 static void ParseTargetArgs(TargetOptions &Opts, ArgList &Args,
2727                             DiagnosticsEngine &Diags) {
2728   if (Arg *A = Args.getLastArg(options::OPT_target_sdk_version_EQ)) {
2729     llvm::VersionTuple Version;
2730     if (Version.tryParse(A->getValue()))
2731       Diags.Report(diag::err_drv_invalid_value)
2732           << A->getAsString(Args) << A->getValue();
2733     else
2734       Opts.SDKVersion = Version;
2735   }
2736 }
2737 
2738 bool CompilerInvocation::CreateFromArgs(CompilerInvocation &Res,
2739                                         ArrayRef<const char *> CommandLineArgs,
2740                                         DiagnosticsEngine &Diags,
2741                                         const char *Argv0) {
2742   bool Success = true;
2743 
2744   // Parse the arguments.
2745   const OptTable &Opts = getDriverOptTable();
2746   const unsigned IncludedFlagsBitmask = options::CC1Option;
2747   unsigned MissingArgIndex, MissingArgCount;
2748   InputArgList Args = Opts.ParseArgs(CommandLineArgs, MissingArgIndex,
2749                                      MissingArgCount, IncludedFlagsBitmask);
2750   LangOptions &LangOpts = *Res.getLangOpts();
2751 
2752   // Check for missing argument error.
2753   if (MissingArgCount) {
2754     Diags.Report(diag::err_drv_missing_argument)
2755         << Args.getArgString(MissingArgIndex) << MissingArgCount;
2756     Success = false;
2757   }
2758 
2759   // Issue errors on unknown arguments.
2760   for (const auto *A : Args.filtered(OPT_UNKNOWN)) {
2761     auto ArgString = A->getAsString(Args);
2762     std::string Nearest;
2763     if (Opts.findNearest(ArgString, Nearest, IncludedFlagsBitmask) > 1)
2764       Diags.Report(diag::err_drv_unknown_argument) << ArgString;
2765     else
2766       Diags.Report(diag::err_drv_unknown_argument_with_suggestion)
2767           << ArgString << Nearest;
2768     Success = false;
2769   }
2770 
2771   Success &= Res.parseSimpleArgs(Args, Diags);
2772 
2773   Success &= ParseAnalyzerArgs(*Res.getAnalyzerOpts(), Args, Diags);
2774   ParseDependencyOutputArgs(Res.getDependencyOutputOpts(), Args);
2775   if (!Res.getDependencyOutputOpts().OutputFile.empty() &&
2776       Res.getDependencyOutputOpts().Targets.empty()) {
2777     Diags.Report(diag::err_fe_dependency_file_requires_MT);
2778     Success = false;
2779   }
2780   Success &= ParseDiagnosticArgs(Res.getDiagnosticOpts(), Args, &Diags,
2781                                  /*DefaultDiagColor=*/false);
2782   // FIXME: We shouldn't have to pass the DashX option around here
2783   InputKind DashX = ParseFrontendArgs(Res.getFrontendOpts(), Args, Diags,
2784                                       LangOpts.IsHeaderFile);
2785   ParseTargetArgs(Res.getTargetOpts(), Args, Diags);
2786   llvm::Triple T(Res.getTargetOpts().Triple);
2787   ParseHeaderSearchArgs(Res.getHeaderSearchOpts(), Args,
2788                         Res.getFileSystemOpts().WorkingDir);
2789   if (DashX.getFormat() == InputKind::Precompiled ||
2790       DashX.getLanguage() == Language::LLVM_IR) {
2791     // ObjCAAutoRefCount and Sanitize LangOpts are used to setup the
2792     // PassManager in BackendUtil.cpp. They need to be initializd no matter
2793     // what the input type is.
2794     if (Args.hasArg(OPT_fobjc_arc))
2795       LangOpts.ObjCAutoRefCount = 1;
2796     // PIClevel and PIELevel are needed during code generation and this should be
2797     // set regardless of the input type.
2798     LangOpts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags);
2799     LangOpts.PIE = Args.hasArg(OPT_pic_is_pie);
2800     parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ),
2801                         Diags, LangOpts.Sanitize);
2802   } else {
2803     // Other LangOpts are only initialized when the input is not AST or LLVM IR.
2804     // FIXME: Should we really be calling this for an Language::Asm input?
2805     ParseLangArgs(LangOpts, Args, DashX, T, Res.getPreprocessorOpts().Includes,
2806                   Diags);
2807     if (Res.getFrontendOpts().ProgramAction == frontend::RewriteObjC)
2808       LangOpts.ObjCExceptions = 1;
2809     if (T.isOSDarwin() && DashX.isPreprocessed()) {
2810       // Supress the darwin-specific 'stdlibcxx-not-found' diagnostic for
2811       // preprocessed input as we don't expect it to be used with -std=libc++
2812       // anyway.
2813       Res.getDiagnosticOpts().Warnings.push_back("no-stdlibcxx-not-found");
2814     }
2815   }
2816 
2817   if (LangOpts.CUDA) {
2818     // During CUDA device-side compilation, the aux triple is the
2819     // triple used for host compilation.
2820     if (LangOpts.CUDAIsDevice)
2821       Res.getTargetOpts().HostTriple = Res.getFrontendOpts().AuxTriple;
2822   }
2823 
2824   // Set the triple of the host for OpenMP device compile.
2825   if (LangOpts.OpenMPIsDevice)
2826     Res.getTargetOpts().HostTriple = Res.getFrontendOpts().AuxTriple;
2827 
2828   Success &= ParseCodeGenArgs(Res.getCodeGenOpts(), Args, DashX, Diags, T,
2829                               Res.getFrontendOpts().OutputFile, LangOpts);
2830 
2831   // FIXME: Override value name discarding when asan or msan is used because the
2832   // backend passes depend on the name of the alloca in order to print out
2833   // names.
2834   Res.getCodeGenOpts().DiscardValueNames &=
2835       !LangOpts.Sanitize.has(SanitizerKind::Address) &&
2836       !LangOpts.Sanitize.has(SanitizerKind::KernelAddress) &&
2837       !LangOpts.Sanitize.has(SanitizerKind::Memory) &&
2838       !LangOpts.Sanitize.has(SanitizerKind::KernelMemory);
2839 
2840   ParsePreprocessorArgs(Res.getPreprocessorOpts(), Args, Diags,
2841                         Res.getFrontendOpts().ProgramAction);
2842   ParsePreprocessorOutputArgs(Res.getPreprocessorOutputOpts(), Args,
2843                               Res.getFrontendOpts().ProgramAction);
2844 
2845   // Turn on -Wspir-compat for SPIR target.
2846   if (T.isSPIR())
2847     Res.getDiagnosticOpts().Warnings.push_back("spir-compat");
2848 
2849   // If sanitizer is enabled, disable OPT_ffine_grained_bitfield_accesses.
2850   if (Res.getCodeGenOpts().FineGrainedBitfieldAccesses &&
2851       !Res.getLangOpts()->Sanitize.empty()) {
2852     Res.getCodeGenOpts().FineGrainedBitfieldAccesses = false;
2853     Diags.Report(diag::warn_drv_fine_grained_bitfield_accesses_ignored);
2854   }
2855 
2856   // Store the command-line for using in the CodeView backend.
2857   Res.getCodeGenOpts().Argv0 = Argv0;
2858   Res.getCodeGenOpts().CommandLineArgs = CommandLineArgs;
2859 
2860   FixupInvocation(Res, Diags, Args, DashX);
2861 
2862   return Success;
2863 }
2864 
2865 std::string CompilerInvocation::getModuleHash() const {
2866   // Note: For QoI reasons, the things we use as a hash here should all be
2867   // dumped via the -module-info flag.
2868   using llvm::hash_code;
2869   using llvm::hash_value;
2870   using llvm::hash_combine;
2871   using llvm::hash_combine_range;
2872 
2873   // Start the signature with the compiler version.
2874   // FIXME: We'd rather use something more cryptographically sound than
2875   // CityHash, but this will do for now.
2876   hash_code code = hash_value(getClangFullRepositoryVersion());
2877 
2878   // Also include the serialization version, in case LLVM_APPEND_VC_REV is off
2879   // and getClangFullRepositoryVersion() doesn't include git revision.
2880   code = hash_combine(code, serialization::VERSION_MAJOR,
2881                       serialization::VERSION_MINOR);
2882 
2883   // Extend the signature with the language options
2884 #define LANGOPT(Name, Bits, Default, Description) \
2885    code = hash_combine(code, LangOpts->Name);
2886 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
2887   code = hash_combine(code, static_cast<unsigned>(LangOpts->get##Name()));
2888 #define BENIGN_LANGOPT(Name, Bits, Default, Description)
2889 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
2890 #include "clang/Basic/LangOptions.def"
2891 
2892   for (StringRef Feature : LangOpts->ModuleFeatures)
2893     code = hash_combine(code, Feature);
2894 
2895   code = hash_combine(code, LangOpts->ObjCRuntime);
2896   const auto &BCN = LangOpts->CommentOpts.BlockCommandNames;
2897   code = hash_combine(code, hash_combine_range(BCN.begin(), BCN.end()));
2898 
2899   // Extend the signature with the target options.
2900   code = hash_combine(code, TargetOpts->Triple, TargetOpts->CPU,
2901                       TargetOpts->TuneCPU, TargetOpts->ABI);
2902   for (const auto &FeatureAsWritten : TargetOpts->FeaturesAsWritten)
2903     code = hash_combine(code, FeatureAsWritten);
2904 
2905   // Extend the signature with preprocessor options.
2906   const PreprocessorOptions &ppOpts = getPreprocessorOpts();
2907   const HeaderSearchOptions &hsOpts = getHeaderSearchOpts();
2908   code = hash_combine(code, ppOpts.UsePredefines, ppOpts.DetailedRecord);
2909 
2910   for (const auto &I : getPreprocessorOpts().Macros) {
2911     // If we're supposed to ignore this macro for the purposes of modules,
2912     // don't put it into the hash.
2913     if (!hsOpts.ModulesIgnoreMacros.empty()) {
2914       // Check whether we're ignoring this macro.
2915       StringRef MacroDef = I.first;
2916       if (hsOpts.ModulesIgnoreMacros.count(
2917               llvm::CachedHashString(MacroDef.split('=').first)))
2918         continue;
2919     }
2920 
2921     code = hash_combine(code, I.first, I.second);
2922   }
2923 
2924   // Extend the signature with the sysroot and other header search options.
2925   code = hash_combine(code, hsOpts.Sysroot,
2926                       hsOpts.ModuleFormat,
2927                       hsOpts.UseDebugInfo,
2928                       hsOpts.UseBuiltinIncludes,
2929                       hsOpts.UseStandardSystemIncludes,
2930                       hsOpts.UseStandardCXXIncludes,
2931                       hsOpts.UseLibcxx,
2932                       hsOpts.ModulesValidateDiagnosticOptions);
2933   code = hash_combine(code, hsOpts.ResourceDir);
2934 
2935   if (hsOpts.ModulesStrictContextHash) {
2936     hash_code SHPC = hash_combine_range(hsOpts.SystemHeaderPrefixes.begin(),
2937                                         hsOpts.SystemHeaderPrefixes.end());
2938     hash_code UEC = hash_combine_range(hsOpts.UserEntries.begin(),
2939                                        hsOpts.UserEntries.end());
2940     code = hash_combine(code, hsOpts.SystemHeaderPrefixes.size(), SHPC,
2941                         hsOpts.UserEntries.size(), UEC);
2942 
2943     const DiagnosticOptions &diagOpts = getDiagnosticOpts();
2944     #define DIAGOPT(Name, Bits, Default) \
2945       code = hash_combine(code, diagOpts.Name);
2946     #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
2947       code = hash_combine(code, diagOpts.get##Name());
2948     #include "clang/Basic/DiagnosticOptions.def"
2949     #undef DIAGOPT
2950     #undef ENUM_DIAGOPT
2951   }
2952 
2953   // Extend the signature with the user build path.
2954   code = hash_combine(code, hsOpts.ModuleUserBuildPath);
2955 
2956   // Extend the signature with the module file extensions.
2957   const FrontendOptions &frontendOpts = getFrontendOpts();
2958   for (const auto &ext : frontendOpts.ModuleFileExtensions) {
2959     code = ext->hashExtension(code);
2960   }
2961 
2962   // When compiling with -gmodules, also hash -fdebug-prefix-map as it
2963   // affects the debug info in the PCM.
2964   if (getCodeGenOpts().DebugTypeExtRefs)
2965     for (const auto &KeyValue : getCodeGenOpts().DebugPrefixMap)
2966       code = hash_combine(code, KeyValue.first, KeyValue.second);
2967 
2968   // Extend the signature with the enabled sanitizers, if at least one is
2969   // enabled. Sanitizers which cannot affect AST generation aren't hashed.
2970   SanitizerSet SanHash = LangOpts->Sanitize;
2971   SanHash.clear(getPPTransparentSanitizers());
2972   if (!SanHash.empty())
2973     code = hash_combine(code, SanHash.Mask);
2974 
2975   return llvm::APInt(64, code).toString(36, /*Signed=*/false);
2976 }
2977 
2978 void CompilerInvocation::generateCC1CommandLine(
2979     SmallVectorImpl<const char *> &Args, StringAllocator SA) const {
2980   // Capture the extracted value as a lambda argument to avoid potential issues
2981   // with lifetime extension of the reference.
2982 #define GENERATE_OPTION_WITH_MARSHALLING(                                      \
2983     ARGS, STRING_ALLOCATOR, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH,       \
2984     DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR,      \
2985     TABLE_INDEX)                                                               \
2986   if ((FLAGS)&options::CC1Option) {                                            \
2987     [&](const auto &Extracted) {                                               \
2988       if (ALWAYS_EMIT ||                                                       \
2989           (Extracted !=                                                        \
2990            static_cast<decltype(KEYPATH)>((IMPLIED_CHECK) ? (IMPLIED_VALUE)    \
2991                                                           : (DEFAULT_VALUE)))) \
2992         DENORMALIZER(ARGS, SPELLING, STRING_ALLOCATOR, Option::KIND##Class,    \
2993                      TABLE_INDEX, Extracted);                                  \
2994     }(EXTRACTOR(KEYPATH));                                                     \
2995   }
2996 
2997 #define OPTION_WITH_MARSHALLING(                                               \
2998     PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,        \
2999     HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
3000     DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER,     \
3001     MERGER, EXTRACTOR, TABLE_INDEX)                                            \
3002   GENERATE_OPTION_WITH_MARSHALLING(Args, SA, KIND, FLAGS, SPELLING,            \
3003                                    ALWAYS_EMIT, this->KEYPATH, DEFAULT_VALUE,  \
3004                                    IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, \
3005                                    EXTRACTOR, TABLE_INDEX)
3006 
3007 #define DIAG_OPTION_WITH_MARSHALLING OPTION_WITH_MARSHALLING
3008 #define LANG_OPTION_WITH_MARSHALLING OPTION_WITH_MARSHALLING
3009 #define CODEGEN_OPTION_WITH_MARSHALLING OPTION_WITH_MARSHALLING
3010 
3011 #include "clang/Driver/Options.inc"
3012 
3013 #undef CODEGEN_OPTION_WITH_MARSHALLING
3014 #undef LANG_OPTION_WITH_MARSHALLING
3015 #undef DIAG_OPTION_WITH_MARSHALLING
3016 #undef OPTION_WITH_MARSHALLING
3017 #undef GENERATE_OPTION_WITH_MARSHALLING
3018 
3019   GenerateLangArgs(*LangOpts, Args, SA);
3020 }
3021 
3022 IntrusiveRefCntPtr<llvm::vfs::FileSystem>
3023 clang::createVFSFromCompilerInvocation(const CompilerInvocation &CI,
3024                                        DiagnosticsEngine &Diags) {
3025   return createVFSFromCompilerInvocation(CI, Diags,
3026                                          llvm::vfs::getRealFileSystem());
3027 }
3028 
3029 IntrusiveRefCntPtr<llvm::vfs::FileSystem>
3030 clang::createVFSFromCompilerInvocation(
3031     const CompilerInvocation &CI, DiagnosticsEngine &Diags,
3032     IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS) {
3033   if (CI.getHeaderSearchOpts().VFSOverlayFiles.empty())
3034     return BaseFS;
3035 
3036   IntrusiveRefCntPtr<llvm::vfs::FileSystem> Result = BaseFS;
3037   // earlier vfs files are on the bottom
3038   for (const auto &File : CI.getHeaderSearchOpts().VFSOverlayFiles) {
3039     llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer =
3040         Result->getBufferForFile(File);
3041     if (!Buffer) {
3042       Diags.Report(diag::err_missing_vfs_overlay_file) << File;
3043       continue;
3044     }
3045 
3046     IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS = llvm::vfs::getVFSFromYAML(
3047         std::move(Buffer.get()), /*DiagHandler*/ nullptr, File,
3048         /*DiagContext*/ nullptr, Result);
3049     if (!FS) {
3050       Diags.Report(diag::err_invalid_vfs_overlay) << File;
3051       continue;
3052     }
3053 
3054     Result = FS;
3055   }
3056   return Result;
3057 }
3058