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