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