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