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