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