xref: /llvm-project/clang/lib/Frontend/CompilerInvocation.cpp (revision d1c8a151df830c6c727f0bb7d33774bd3eb96824)
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/TextDiagnosticBuffer.h"
42 #include "clang/Frontend/Utils.h"
43 #include "clang/Lex/HeaderSearchOptions.h"
44 #include "clang/Lex/PreprocessorOptions.h"
45 #include "clang/Sema/CodeCompleteOptions.h"
46 #include "clang/Serialization/ASTBitCodes.h"
47 #include "clang/Serialization/ModuleFileExtension.h"
48 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
49 #include "llvm/ADT/APInt.h"
50 #include "llvm/ADT/ArrayRef.h"
51 #include "llvm/ADT/CachedHashString.h"
52 #include "llvm/ADT/DenseSet.h"
53 #include "llvm/ADT/FloatingPointMode.h"
54 #include "llvm/ADT/Hashing.h"
55 #include "llvm/ADT/None.h"
56 #include "llvm/ADT/Optional.h"
57 #include "llvm/ADT/STLExtras.h"
58 #include "llvm/ADT/SmallString.h"
59 #include "llvm/ADT/SmallVector.h"
60 #include "llvm/ADT/StringRef.h"
61 #include "llvm/ADT/StringSwitch.h"
62 #include "llvm/ADT/Triple.h"
63 #include "llvm/ADT/Twine.h"
64 #include "llvm/Config/llvm-config.h"
65 #include "llvm/IR/DebugInfoMetadata.h"
66 #include "llvm/Linker/Linker.h"
67 #include "llvm/MC/MCTargetOptions.h"
68 #include "llvm/Option/Arg.h"
69 #include "llvm/Option/ArgList.h"
70 #include "llvm/Option/OptSpecifier.h"
71 #include "llvm/Option/OptTable.h"
72 #include "llvm/Option/Option.h"
73 #include "llvm/ProfileData/InstrProfReader.h"
74 #include "llvm/Remarks/HotnessThresholdParser.h"
75 #include "llvm/Support/CodeGen.h"
76 #include "llvm/Support/Compiler.h"
77 #include "llvm/Support/Error.h"
78 #include "llvm/Support/ErrorHandling.h"
79 #include "llvm/Support/ErrorOr.h"
80 #include "llvm/Support/FileSystem.h"
81 #include "llvm/Support/Host.h"
82 #include "llvm/Support/MathExtras.h"
83 #include "llvm/Support/MemoryBuffer.h"
84 #include "llvm/Support/Path.h"
85 #include "llvm/Support/Process.h"
86 #include "llvm/Support/Regex.h"
87 #include "llvm/Support/VersionTuple.h"
88 #include "llvm/Support/VirtualFileSystem.h"
89 #include "llvm/Support/raw_ostream.h"
90 #include "llvm/Target/TargetOptions.h"
91 #include <algorithm>
92 #include <atomic>
93 #include <cassert>
94 #include <cstddef>
95 #include <cstring>
96 #include <memory>
97 #include <string>
98 #include <tuple>
99 #include <type_traits>
100 #include <utility>
101 #include <vector>
102 
103 using namespace clang;
104 using namespace driver;
105 using namespace options;
106 using namespace llvm::opt;
107 
108 //===----------------------------------------------------------------------===//
109 // Initialization.
110 //===----------------------------------------------------------------------===//
111 
112 CompilerInvocationBase::CompilerInvocationBase()
113     : LangOpts(new LangOptions()), TargetOpts(new TargetOptions()),
114       DiagnosticOpts(new DiagnosticOptions()),
115       HeaderSearchOpts(new HeaderSearchOptions()),
116       PreprocessorOpts(new PreprocessorOptions()) {}
117 
118 CompilerInvocationBase::CompilerInvocationBase(const CompilerInvocationBase &X)
119     : LangOpts(new LangOptions(*X.getLangOpts())),
120       TargetOpts(new TargetOptions(X.getTargetOpts())),
121       DiagnosticOpts(new DiagnosticOptions(X.getDiagnosticOpts())),
122       HeaderSearchOpts(new HeaderSearchOptions(X.getHeaderSearchOpts())),
123       PreprocessorOpts(new PreprocessorOptions(X.getPreprocessorOpts())) {}
124 
125 CompilerInvocationBase::~CompilerInvocationBase() = default;
126 
127 //===----------------------------------------------------------------------===//
128 // Normalizers
129 //===----------------------------------------------------------------------===//
130 
131 #define SIMPLE_ENUM_VALUE_TABLE
132 #include "clang/Driver/Options.inc"
133 #undef SIMPLE_ENUM_VALUE_TABLE
134 
135 static llvm::Optional<bool>
136 normalizeSimpleFlag(OptSpecifier Opt, unsigned TableIndex, const ArgList &Args,
137                     DiagnosticsEngine &Diags, bool &Success) {
138   if (Args.hasArg(Opt))
139     return true;
140   return None;
141 }
142 
143 static Optional<bool> normalizeSimpleNegativeFlag(OptSpecifier Opt, unsigned,
144                                                   const ArgList &Args,
145                                                   DiagnosticsEngine &,
146                                                   bool &Success) {
147   if (Args.hasArg(Opt))
148     return false;
149   return None;
150 }
151 
152 /// The tblgen-erated code passes in a fifth parameter of an arbitrary type, but
153 /// denormalizeSimpleFlags never looks at it. Avoid bloating compile-time with
154 /// unnecessary template instantiations and just ignore it with a variadic
155 /// argument.
156 static void denormalizeSimpleFlag(SmallVectorImpl<const char *> &Args,
157                                   const char *Spelling,
158                                   CompilerInvocation::StringAllocator,
159                                   Option::OptionClass, unsigned, /*T*/...) {
160   Args.push_back(Spelling);
161 }
162 
163 template <typename T> static constexpr bool is_uint64_t_convertible() {
164   return !std::is_same<T, uint64_t>::value &&
165          llvm::is_integral_or_enum<T>::value;
166 }
167 
168 template <typename T,
169           std::enable_if_t<!is_uint64_t_convertible<T>(), bool> = false>
170 static auto makeFlagToValueNormalizer(T Value) {
171   return [Value](OptSpecifier Opt, unsigned, const ArgList &Args,
172                  DiagnosticsEngine &, bool &Success) -> Optional<T> {
173     if (Args.hasArg(Opt))
174       return Value;
175     return None;
176   };
177 }
178 
179 template <typename T,
180           std::enable_if_t<is_uint64_t_convertible<T>(), bool> = false>
181 static auto makeFlagToValueNormalizer(T Value) {
182   return makeFlagToValueNormalizer(uint64_t(Value));
183 }
184 
185 static auto makeBooleanOptionNormalizer(bool Value, bool OtherValue,
186                                         OptSpecifier OtherOpt) {
187   return [Value, OtherValue, OtherOpt](OptSpecifier Opt, unsigned,
188                                        const ArgList &Args, DiagnosticsEngine &,
189                                        bool &Success) -> Optional<bool> {
190     if (const Arg *A = Args.getLastArg(Opt, OtherOpt)) {
191       return A->getOption().matches(Opt) ? Value : OtherValue;
192     }
193     return None;
194   };
195 }
196 
197 static auto makeBooleanOptionDenormalizer(bool Value) {
198   return [Value](SmallVectorImpl<const char *> &Args, const char *Spelling,
199                  CompilerInvocation::StringAllocator, Option::OptionClass,
200                  unsigned, bool KeyPath) {
201     if (KeyPath == Value)
202       Args.push_back(Spelling);
203   };
204 }
205 
206 static void denormalizeStringImpl(SmallVectorImpl<const char *> &Args,
207                                   const char *Spelling,
208                                   CompilerInvocation::StringAllocator SA,
209                                   Option::OptionClass OptClass, unsigned,
210                                   const Twine &Value) {
211   switch (OptClass) {
212   case Option::SeparateClass:
213   case Option::JoinedOrSeparateClass:
214     Args.push_back(Spelling);
215     Args.push_back(SA(Value));
216     break;
217   case Option::JoinedClass:
218   case Option::CommaJoinedClass:
219     Args.push_back(SA(Twine(Spelling) + Value));
220     break;
221   default:
222     llvm_unreachable("Cannot denormalize an option with option class "
223                      "incompatible with string denormalization.");
224   }
225 }
226 
227 template <typename T>
228 static void
229 denormalizeString(SmallVectorImpl<const char *> &Args, const char *Spelling,
230                   CompilerInvocation::StringAllocator SA,
231                   Option::OptionClass OptClass, unsigned TableIndex, T Value) {
232   denormalizeStringImpl(Args, Spelling, SA, OptClass, TableIndex, Twine(Value));
233 }
234 
235 static Optional<SimpleEnumValue>
236 findValueTableByName(const SimpleEnumValueTable &Table, StringRef Name) {
237   for (int I = 0, E = Table.Size; I != E; ++I)
238     if (Name == Table.Table[I].Name)
239       return Table.Table[I];
240 
241   return None;
242 }
243 
244 static Optional<SimpleEnumValue>
245 findValueTableByValue(const SimpleEnumValueTable &Table, unsigned Value) {
246   for (int I = 0, E = Table.Size; I != E; ++I)
247     if (Value == Table.Table[I].Value)
248       return Table.Table[I];
249 
250   return None;
251 }
252 
253 static llvm::Optional<unsigned>
254 normalizeSimpleEnum(OptSpecifier Opt, unsigned TableIndex, const ArgList &Args,
255                     DiagnosticsEngine &Diags, bool &Success) {
256   assert(TableIndex < SimpleEnumValueTablesSize);
257   const SimpleEnumValueTable &Table = SimpleEnumValueTables[TableIndex];
258 
259   auto *Arg = Args.getLastArg(Opt);
260   if (!Arg)
261     return None;
262 
263   StringRef ArgValue = Arg->getValue();
264   if (auto MaybeEnumVal = findValueTableByName(Table, ArgValue))
265     return MaybeEnumVal->Value;
266 
267   Success = false;
268   Diags.Report(diag::err_drv_invalid_value)
269       << Arg->getAsString(Args) << ArgValue;
270   return None;
271 }
272 
273 static void denormalizeSimpleEnumImpl(SmallVectorImpl<const char *> &Args,
274                                       const char *Spelling,
275                                       CompilerInvocation::StringAllocator SA,
276                                       Option::OptionClass OptClass,
277                                       unsigned TableIndex, unsigned Value) {
278   assert(TableIndex < SimpleEnumValueTablesSize);
279   const SimpleEnumValueTable &Table = SimpleEnumValueTables[TableIndex];
280   if (auto MaybeEnumVal = findValueTableByValue(Table, Value)) {
281     denormalizeString(Args, Spelling, SA, OptClass, TableIndex,
282                       MaybeEnumVal->Name);
283   } else {
284     llvm_unreachable("The simple enum value was not correctly defined in "
285                      "the tablegen option description");
286   }
287 }
288 
289 template <typename T>
290 static void denormalizeSimpleEnum(SmallVectorImpl<const char *> &Args,
291                                   const char *Spelling,
292                                   CompilerInvocation::StringAllocator SA,
293                                   Option::OptionClass OptClass,
294                                   unsigned TableIndex, T Value) {
295   return denormalizeSimpleEnumImpl(Args, Spelling, SA, OptClass, TableIndex,
296                                    static_cast<unsigned>(Value));
297 }
298 
299 static Optional<std::string> normalizeString(OptSpecifier Opt, int TableIndex,
300                                              const ArgList &Args,
301                                              DiagnosticsEngine &Diags,
302                                              bool &Success) {
303   auto *Arg = Args.getLastArg(Opt);
304   if (!Arg)
305     return None;
306   return std::string(Arg->getValue());
307 }
308 
309 template <typename IntTy>
310 static Optional<IntTy>
311 normalizeStringIntegral(OptSpecifier Opt, int, const ArgList &Args,
312                         DiagnosticsEngine &Diags, bool &Success) {
313   auto *Arg = Args.getLastArg(Opt);
314   if (!Arg)
315     return None;
316   IntTy Res;
317   if (StringRef(Arg->getValue()).getAsInteger(0, Res)) {
318     Success = false;
319     Diags.Report(diag::err_drv_invalid_int_value)
320         << Arg->getAsString(Args) << Arg->getValue();
321     return None;
322   }
323   return Res;
324 }
325 
326 static Optional<std::vector<std::string>>
327 normalizeStringVector(OptSpecifier Opt, int, const ArgList &Args,
328                       DiagnosticsEngine &, bool &Success) {
329   return Args.getAllArgValues(Opt);
330 }
331 
332 static void denormalizeStringVector(SmallVectorImpl<const char *> &Args,
333                                     const char *Spelling,
334                                     CompilerInvocation::StringAllocator SA,
335                                     Option::OptionClass OptClass,
336                                     unsigned TableIndex,
337                                     const std::vector<std::string> &Values) {
338   switch (OptClass) {
339   case Option::CommaJoinedClass: {
340     std::string CommaJoinedValue;
341     if (!Values.empty()) {
342       CommaJoinedValue.append(Values.front());
343       for (const std::string &Value : llvm::drop_begin(Values, 1)) {
344         CommaJoinedValue.append(",");
345         CommaJoinedValue.append(Value);
346       }
347     }
348     denormalizeString(Args, Spelling, SA, Option::OptionClass::JoinedClass,
349                       TableIndex, CommaJoinedValue);
350     break;
351   }
352   case Option::JoinedClass:
353   case Option::SeparateClass:
354   case Option::JoinedOrSeparateClass:
355     for (const std::string &Value : Values)
356       denormalizeString(Args, Spelling, SA, OptClass, TableIndex, Value);
357     break;
358   default:
359     llvm_unreachable("Cannot denormalize an option with option class "
360                      "incompatible with string vector denormalization.");
361   }
362 }
363 
364 static Optional<std::string> normalizeTriple(OptSpecifier Opt, int TableIndex,
365                                              const ArgList &Args,
366                                              DiagnosticsEngine &Diags,
367                                              bool &Success) {
368   auto *Arg = Args.getLastArg(Opt);
369   if (!Arg)
370     return None;
371   return llvm::Triple::normalize(Arg->getValue());
372 }
373 
374 template <typename T, typename U>
375 static T mergeForwardValue(T KeyPath, U Value) {
376   return static_cast<T>(Value);
377 }
378 
379 template <typename T, typename U> static T mergeMaskValue(T KeyPath, U Value) {
380   return KeyPath | Value;
381 }
382 
383 template <typename T> static T extractForwardValue(T KeyPath) {
384   return KeyPath;
385 }
386 
387 template <typename T, typename U, U Value>
388 static T extractMaskValue(T KeyPath) {
389   return ((KeyPath & Value) == Value) ? static_cast<T>(Value) : T();
390 }
391 
392 #define PARSE_OPTION_WITH_MARSHALLING(ARGS, DIAGS, SUCCESS, ID, FLAGS, PARAM,  \
393                                       SHOULD_PARSE, KEYPATH, DEFAULT_VALUE,    \
394                                       IMPLIED_CHECK, IMPLIED_VALUE,            \
395                                       NORMALIZER, MERGER, TABLE_INDEX)         \
396   if ((FLAGS)&options::CC1Option) {                                            \
397     KEYPATH = MERGER(KEYPATH, DEFAULT_VALUE);                                  \
398     if (IMPLIED_CHECK)                                                         \
399       KEYPATH = MERGER(KEYPATH, IMPLIED_VALUE);                                \
400     if (SHOULD_PARSE)                                                          \
401       if (auto MaybeValue =                                                    \
402               NORMALIZER(OPT_##ID, TABLE_INDEX, ARGS, DIAGS, SUCCESS))         \
403         KEYPATH =                                                              \
404             MERGER(KEYPATH, static_cast<decltype(KEYPATH)>(*MaybeValue));      \
405   }
406 
407 // Capture the extracted value as a lambda argument to avoid potential issues
408 // with lifetime extension of the reference.
409 #define GENERATE_OPTION_WITH_MARSHALLING(                                      \
410     ARGS, STRING_ALLOCATOR, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH,       \
411     DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR,      \
412     TABLE_INDEX)                                                               \
413   if ((FLAGS)&options::CC1Option) {                                            \
414     [&](const auto &Extracted) {                                               \
415       if (ALWAYS_EMIT ||                                                       \
416           (Extracted !=                                                        \
417            static_cast<decltype(KEYPATH)>((IMPLIED_CHECK) ? (IMPLIED_VALUE)    \
418                                                           : (DEFAULT_VALUE)))) \
419         DENORMALIZER(ARGS, SPELLING, STRING_ALLOCATOR, Option::KIND##Class,    \
420                      TABLE_INDEX, Extracted);                                  \
421     }(EXTRACTOR(KEYPATH));                                                     \
422   }
423 
424 static const StringRef GetInputKindName(InputKind IK);
425 
426 static bool FixupInvocation(CompilerInvocation &Invocation,
427                             DiagnosticsEngine &Diags, const ArgList &Args,
428                             InputKind IK) {
429   unsigned NumErrorsBefore = Diags.getNumErrors();
430 
431   LangOptions &LangOpts = *Invocation.getLangOpts();
432   CodeGenOptions &CodeGenOpts = Invocation.getCodeGenOpts();
433   TargetOptions &TargetOpts = Invocation.getTargetOpts();
434   FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
435   CodeGenOpts.XRayInstrumentFunctions = LangOpts.XRayInstrument;
436   CodeGenOpts.XRayAlwaysEmitCustomEvents = LangOpts.XRayAlwaysEmitCustomEvents;
437   CodeGenOpts.XRayAlwaysEmitTypedEvents = LangOpts.XRayAlwaysEmitTypedEvents;
438   CodeGenOpts.DisableFree = FrontendOpts.DisableFree;
439   FrontendOpts.GenerateGlobalModuleIndex = FrontendOpts.UseGlobalModuleIndex;
440 
441   LangOpts.ForceEmitVTables = CodeGenOpts.ForceEmitVTables;
442   LangOpts.SpeculativeLoadHardening = CodeGenOpts.SpeculativeLoadHardening;
443   LangOpts.CurrentModule = LangOpts.ModuleName;
444 
445   llvm::Triple T(TargetOpts.Triple);
446   llvm::Triple::ArchType Arch = T.getArch();
447 
448   CodeGenOpts.CodeModel = TargetOpts.CodeModel;
449 
450   if (LangOpts.getExceptionHandling() != llvm::ExceptionHandling::None &&
451       T.isWindowsMSVCEnvironment())
452     Diags.Report(diag::err_fe_invalid_exception_model)
453         << static_cast<unsigned>(LangOpts.getExceptionHandling()) << T.str();
454 
455   if (LangOpts.AppleKext && !LangOpts.CPlusPlus)
456     Diags.Report(diag::warn_c_kext);
457 
458   if (Args.hasArg(OPT_fconcepts_ts))
459     Diags.Report(diag::warn_fe_concepts_ts_flag);
460 
461   if (LangOpts.NewAlignOverride &&
462       !llvm::isPowerOf2_32(LangOpts.NewAlignOverride)) {
463     Arg *A = Args.getLastArg(OPT_fnew_alignment_EQ);
464     Diags.Report(diag::err_fe_invalid_alignment)
465         << A->getAsString(Args) << A->getValue();
466     LangOpts.NewAlignOverride = 0;
467   }
468 
469   // Prevent the user from specifying both -fsycl-is-device and -fsycl-is-host.
470   if (LangOpts.SYCLIsDevice && LangOpts.SYCLIsHost)
471     Diags.Report(diag::err_drv_argument_not_allowed_with) << "-fsycl-is-device"
472                                                           << "-fsycl-is-host";
473 
474   if (Args.hasArg(OPT_fgnu89_inline) && LangOpts.CPlusPlus)
475     Diags.Report(diag::err_drv_argument_not_allowed_with)
476         << "-fgnu89-inline" << GetInputKindName(IK);
477 
478   if (Args.hasArg(OPT_fgpu_allow_device_init) && !LangOpts.HIP)
479     Diags.Report(diag::warn_ignored_hip_only_option)
480         << Args.getLastArg(OPT_fgpu_allow_device_init)->getAsString(Args);
481 
482   if (Args.hasArg(OPT_gpu_max_threads_per_block_EQ) && !LangOpts.HIP)
483     Diags.Report(diag::warn_ignored_hip_only_option)
484         << Args.getLastArg(OPT_gpu_max_threads_per_block_EQ)->getAsString(Args);
485 
486   // -cl-strict-aliasing needs to emit diagnostic in the case where CL > 1.0.
487   // This option should be deprecated for CL > 1.0 because
488   // this option was added for compatibility with OpenCL 1.0.
489   if (Args.getLastArg(OPT_cl_strict_aliasing) && LangOpts.OpenCLVersion > 100)
490     Diags.Report(diag::warn_option_invalid_ocl_version)
491         << LangOpts.getOpenCLVersionTuple().getAsString()
492         << Args.getLastArg(OPT_cl_strict_aliasing)->getAsString(Args);
493 
494   if (Arg *A = Args.getLastArg(OPT_fdefault_calling_conv_EQ)) {
495     auto DefaultCC = LangOpts.getDefaultCallingConv();
496 
497     bool emitError = (DefaultCC == LangOptions::DCC_FastCall ||
498                       DefaultCC == LangOptions::DCC_StdCall) &&
499                      Arch != llvm::Triple::x86;
500     emitError |= (DefaultCC == LangOptions::DCC_VectorCall ||
501                   DefaultCC == LangOptions::DCC_RegCall) &&
502                  !T.isX86();
503     if (emitError)
504       Diags.Report(diag::err_drv_argument_not_allowed_with)
505           << A->getSpelling() << T.getTriple();
506   }
507 
508   if (!CodeGenOpts.ProfileRemappingFile.empty() && CodeGenOpts.LegacyPassManager)
509     Diags.Report(diag::err_drv_argument_only_allowed_with)
510         << Args.getLastArg(OPT_fprofile_remapping_file_EQ)->getAsString(Args)
511         << "-fno-legacy-pass-manager";
512 
513   return Diags.getNumErrors() == NumErrorsBefore;
514 }
515 
516 //===----------------------------------------------------------------------===//
517 // Deserialization (from args)
518 //===----------------------------------------------------------------------===//
519 
520 static unsigned getOptimizationLevel(ArgList &Args, InputKind IK,
521                                      DiagnosticsEngine &Diags) {
522   unsigned DefaultOpt = llvm::CodeGenOpt::None;
523   if ((IK.getLanguage() == Language::OpenCL ||
524        IK.getLanguage() == Language::OpenCLCXX) &&
525       !Args.hasArg(OPT_cl_opt_disable))
526     DefaultOpt = llvm::CodeGenOpt::Default;
527 
528   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
529     if (A->getOption().matches(options::OPT_O0))
530       return llvm::CodeGenOpt::None;
531 
532     if (A->getOption().matches(options::OPT_Ofast))
533       return llvm::CodeGenOpt::Aggressive;
534 
535     assert(A->getOption().matches(options::OPT_O));
536 
537     StringRef S(A->getValue());
538     if (S == "s" || S == "z")
539       return llvm::CodeGenOpt::Default;
540 
541     if (S == "g")
542       return llvm::CodeGenOpt::Less;
543 
544     return getLastArgIntValue(Args, OPT_O, DefaultOpt, Diags);
545   }
546 
547   return DefaultOpt;
548 }
549 
550 static unsigned getOptimizationLevelSize(ArgList &Args) {
551   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
552     if (A->getOption().matches(options::OPT_O)) {
553       switch (A->getValue()[0]) {
554       default:
555         return 0;
556       case 's':
557         return 1;
558       case 'z':
559         return 2;
560       }
561     }
562   }
563   return 0;
564 }
565 
566 static void GenerateArg(SmallVectorImpl<const char *> &Args,
567                         llvm::opt::OptSpecifier OptSpecifier,
568                         CompilerInvocation::StringAllocator SA) {
569   Option Opt = getDriverOptTable().getOption(OptSpecifier);
570   denormalizeSimpleFlag(Args, SA(Opt.getPrefix() + Opt.getName()), SA,
571                         Option::OptionClass::FlagClass, 0);
572 }
573 
574 static void GenerateArg(SmallVectorImpl<const char *> &Args,
575                         llvm::opt::OptSpecifier OptSpecifier,
576                         const Twine &Value,
577                         CompilerInvocation::StringAllocator SA) {
578   Option Opt = getDriverOptTable().getOption(OptSpecifier);
579   denormalizeString(Args, SA(Opt.getPrefix() + Opt.getName()), SA,
580                     Opt.getKind(), 0, Value);
581 }
582 
583 // Parse command line arguments into CompilerInvocation.
584 using ParseFn =
585     llvm::function_ref<bool(CompilerInvocation &, ArrayRef<const char *>,
586                             DiagnosticsEngine &, const char *)>;
587 
588 // Generate command line arguments from CompilerInvocation.
589 using GenerateFn = llvm::function_ref<void(
590     CompilerInvocation &, SmallVectorImpl<const char *> &,
591     CompilerInvocation::StringAllocator)>;
592 
593 // May perform round-trip of command line arguments. By default, the round-trip
594 // is enabled if CLANG_ROUND_TRIP_CC1_ARGS was defined during build. This can be
595 // overwritten at run-time via the "-round-trip-args" and "-no-round-trip-args"
596 // command line flags.
597 // During round-trip, the command line arguments are parsed into a dummy
598 // instance of CompilerInvocation which is used to generate the command line
599 // arguments again. The real CompilerInvocation instance is then created by
600 // parsing the generated arguments, not the original ones.
601 static bool RoundTrip(ParseFn Parse, GenerateFn Generate,
602                       CompilerInvocation &RealInvocation,
603                       CompilerInvocation &DummyInvocation,
604                       ArrayRef<const char *> CommandLineArgs,
605                       DiagnosticsEngine &Diags, const char *Argv0) {
606   // FIXME: Switch to '#ifndef NDEBUG' when possible.
607 #ifdef CLANG_ROUND_TRIP_CC1_ARGS
608   bool DoRoundTripDefault = true;
609 #else
610   bool DoRoundTripDefault = false;
611 #endif
612 
613   bool DoRoundTrip = DoRoundTripDefault;
614   for (const auto *Arg : CommandLineArgs) {
615     if (Arg == StringRef("-round-trip-args"))
616       DoRoundTrip = true;
617     if (Arg == StringRef("-no-round-trip-args"))
618       DoRoundTrip = false;
619   }
620 
621   // If round-trip was not requested, simply run the parser with the real
622   // invocation diagnostics.
623   if (!DoRoundTrip)
624     return Parse(RealInvocation, CommandLineArgs, Diags, Argv0);
625 
626   // Serializes quoted (and potentially escaped) arguments.
627   auto SerializeArgs = [](ArrayRef<const char *> Args) {
628     std::string Buffer;
629     llvm::raw_string_ostream OS(Buffer);
630     for (const char *Arg : Args) {
631       llvm::sys::printArg(OS, Arg, /*Quote=*/true);
632       OS << ' ';
633     }
634     OS.flush();
635     return Buffer;
636   };
637 
638   // Setup a dummy DiagnosticsEngine.
639   DiagnosticsEngine DummyDiags(new DiagnosticIDs(), new DiagnosticOptions());
640   DummyDiags.setClient(new TextDiagnosticBuffer());
641 
642   // Run the first parse on the original arguments with the dummy invocation and
643   // diagnostics.
644   if (!Parse(DummyInvocation, CommandLineArgs, DummyDiags, Argv0) ||
645       DummyDiags.getNumWarnings() != 0) {
646     // If the first parse did not succeed, it must be user mistake (invalid
647     // command line arguments). We won't be able to generate arguments that
648     // would reproduce the same result. Let's fail again with the real
649     // invocation and diagnostics, so all side-effects of parsing are visible.
650     unsigned NumWarningsBefore = Diags.getNumWarnings();
651     auto Success = Parse(RealInvocation, CommandLineArgs, Diags, Argv0);
652     if (!Success || Diags.getNumWarnings() != NumWarningsBefore)
653       return Success;
654 
655     // Parse with original options and diagnostics succeeded even though it
656     // shouldn't have. Something is off.
657     Diags.Report(diag::err_cc1_round_trip_fail_then_ok);
658     Diags.Report(diag::note_cc1_round_trip_original)
659         << SerializeArgs(CommandLineArgs);
660     return false;
661   }
662 
663   // Setup string allocator.
664   llvm::BumpPtrAllocator Alloc;
665   llvm::StringSaver StringPool(Alloc);
666   auto SA = [&StringPool](const Twine &Arg) {
667     return StringPool.save(Arg).data();
668   };
669 
670   // Generate arguments from the dummy invocation. If Generate is the
671   // inverse of Parse, the newly generated arguments must have the same
672   // semantics as the original.
673   SmallVector<const char *> GeneratedArgs1;
674   Generate(DummyInvocation, GeneratedArgs1, SA);
675 
676   // Run the second parse, now on the generated arguments, and with the real
677   // invocation and diagnostics. The result is what we will end up using for the
678   // rest of compilation, so if Generate is not inverse of Parse, something down
679   // the line will break.
680   bool Success2 = Parse(RealInvocation, GeneratedArgs1, Diags, Argv0);
681 
682   // The first parse on original arguments succeeded, but second parse of
683   // generated arguments failed. Something must be wrong with the generator.
684   if (!Success2) {
685     Diags.Report(diag::err_cc1_round_trip_ok_then_fail);
686     Diags.Report(diag::note_cc1_round_trip_generated)
687         << 1 << SerializeArgs(GeneratedArgs1);
688     return false;
689   }
690 
691   // Generate arguments again, this time from the options we will end up using
692   // for the rest of the compilation.
693   SmallVector<const char *> GeneratedArgs2;
694   Generate(RealInvocation, GeneratedArgs2, SA);
695 
696   // Compares two lists of generated arguments.
697   auto Equal = [](const ArrayRef<const char *> A,
698                   const ArrayRef<const char *> B) {
699     return std::equal(A.begin(), A.end(), B.begin(), B.end(),
700                       [](const char *AElem, const char *BElem) {
701                         return StringRef(AElem) == StringRef(BElem);
702                       });
703   };
704 
705   // If we generated different arguments from what we assume are two
706   // semantically equivalent CompilerInvocations, the Generate function may
707   // be non-deterministic.
708   if (!Equal(GeneratedArgs1, GeneratedArgs2)) {
709     Diags.Report(diag::err_cc1_round_trip_mismatch);
710     Diags.Report(diag::note_cc1_round_trip_generated)
711         << 1 << SerializeArgs(GeneratedArgs1);
712     Diags.Report(diag::note_cc1_round_trip_generated)
713         << 2 << SerializeArgs(GeneratedArgs2);
714     return false;
715   }
716 
717   Diags.Report(diag::remark_cc1_round_trip_generated)
718       << 1 << SerializeArgs(GeneratedArgs1);
719   Diags.Report(diag::remark_cc1_round_trip_generated)
720       << 2 << SerializeArgs(GeneratedArgs2);
721 
722   return Success2;
723 }
724 
725 static void addDiagnosticArgs(ArgList &Args, OptSpecifier Group,
726                               OptSpecifier GroupWithValue,
727                               std::vector<std::string> &Diagnostics) {
728   for (auto *A : Args.filtered(Group)) {
729     if (A->getOption().getKind() == Option::FlagClass) {
730       // The argument is a pure flag (such as OPT_Wall or OPT_Wdeprecated). Add
731       // its name (minus the "W" or "R" at the beginning) to the diagnostics.
732       Diagnostics.push_back(
733           std::string(A->getOption().getName().drop_front(1)));
734     } else if (A->getOption().matches(GroupWithValue)) {
735       // This is -Wfoo= or -Rfoo=, where foo is the name of the diagnostic
736       // group. Add only the group name to the diagnostics.
737       Diagnostics.push_back(
738           std::string(A->getOption().getName().drop_front(1).rtrim("=-")));
739     } else {
740       // Otherwise, add its value (for OPT_W_Joined and similar).
741       Diagnostics.push_back(A->getValue());
742     }
743   }
744 }
745 
746 // Parse the Static Analyzer configuration. If \p Diags is set to nullptr,
747 // it won't verify the input.
748 static void parseAnalyzerConfigs(AnalyzerOptions &AnOpts,
749                                  DiagnosticsEngine *Diags);
750 
751 static void getAllNoBuiltinFuncValues(ArgList &Args,
752                                       std::vector<std::string> &Funcs) {
753   std::vector<std::string> Values = Args.getAllArgValues(OPT_fno_builtin_);
754   auto BuiltinEnd = llvm::partition(Values, [](const std::string FuncName) {
755     return Builtin::Context::isBuiltinFunc(FuncName);
756   });
757   Funcs.insert(Funcs.end(), Values.begin(), BuiltinEnd);
758 }
759 
760 static void GenerateAnalyzerArgs(AnalyzerOptions &Opts,
761                                  SmallVectorImpl<const char *> &Args,
762                                  CompilerInvocation::StringAllocator SA) {
763   const AnalyzerOptions *AnalyzerOpts = &Opts;
764 
765 #define ANALYZER_OPTION_WITH_MARSHALLING(                                      \
766     PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,        \
767     HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
768     DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER,     \
769     MERGER, EXTRACTOR, TABLE_INDEX)                                            \
770   GENERATE_OPTION_WITH_MARSHALLING(                                            \
771       Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE,    \
772       IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
773 #include "clang/Driver/Options.inc"
774 #undef ANALYZER_OPTION_WITH_MARSHALLING
775 
776   if (Opts.AnalysisStoreOpt != RegionStoreModel) {
777     switch (Opts.AnalysisStoreOpt) {
778 #define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN)                           \
779   case NAME##Model:                                                            \
780     GenerateArg(Args, OPT_analyzer_store, CMDFLAG, SA);                        \
781     break;
782 #include "clang/StaticAnalyzer/Core/Analyses.def"
783     default:
784       llvm_unreachable("Tried to generate unknown analysis store.");
785     }
786   }
787 
788   if (Opts.AnalysisConstraintsOpt != RangeConstraintsModel) {
789     switch (Opts.AnalysisConstraintsOpt) {
790 #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN)                     \
791   case NAME##Model:                                                            \
792     GenerateArg(Args, OPT_analyzer_constraints, CMDFLAG, SA);                  \
793     break;
794 #include "clang/StaticAnalyzer/Core/Analyses.def"
795     default:
796       llvm_unreachable("Tried to generate unknown analysis constraint.");
797     }
798   }
799 
800   if (Opts.AnalysisDiagOpt != PD_HTML) {
801     switch (Opts.AnalysisDiagOpt) {
802 #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN)                     \
803   case PD_##NAME:                                                              \
804     GenerateArg(Args, OPT_analyzer_output, CMDFLAG, SA);                       \
805     break;
806 #include "clang/StaticAnalyzer/Core/Analyses.def"
807     default:
808       llvm_unreachable("Tried to generate unknown analysis diagnostic client.");
809     }
810   }
811 
812   if (Opts.AnalysisPurgeOpt != PurgeStmt) {
813     switch (Opts.AnalysisPurgeOpt) {
814 #define ANALYSIS_PURGE(NAME, CMDFLAG, DESC)                                    \
815   case NAME:                                                                   \
816     GenerateArg(Args, OPT_analyzer_purge, CMDFLAG, SA);                        \
817     break;
818 #include "clang/StaticAnalyzer/Core/Analyses.def"
819     default:
820       llvm_unreachable("Tried to generate unknown analysis purge mode.");
821     }
822   }
823 
824   if (Opts.InliningMode != NoRedundancy) {
825     switch (Opts.InliningMode) {
826 #define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC)                            \
827   case NAME:                                                                   \
828     GenerateArg(Args, OPT_analyzer_inlining_mode, CMDFLAG, SA);                \
829     break;
830 #include "clang/StaticAnalyzer/Core/Analyses.def"
831     default:
832       llvm_unreachable("Tried to generate unknown analysis inlining mode.");
833     }
834   }
835 
836   for (const auto &CP : Opts.CheckersAndPackages) {
837     OptSpecifier Opt =
838         CP.second ? OPT_analyzer_checker : OPT_analyzer_disable_checker;
839     GenerateArg(Args, Opt, CP.first, SA);
840   }
841 
842   AnalyzerOptions ConfigOpts;
843   parseAnalyzerConfigs(ConfigOpts, nullptr);
844 
845   for (const auto &C : Opts.Config) {
846     // Don't generate anything that came from parseAnalyzerConfigs. It would be
847     // redundant and may not be valid on the command line.
848     auto Entry = ConfigOpts.Config.find(C.getKey());
849     if (Entry != ConfigOpts.Config.end() && Entry->getValue() == C.getValue())
850       continue;
851 
852     GenerateArg(Args, OPT_analyzer_config, C.getKey() + "=" + C.getValue(), SA);
853   }
854 
855   // Nothing to generate for FullCompilerInvocation.
856 }
857 
858 static bool ParseAnalyzerArgs(AnalyzerOptions &Opts, ArgList &Args,
859                               DiagnosticsEngine &Diags) {
860   AnalyzerOptions *AnalyzerOpts = &Opts;
861   bool Success = true;
862 
863 #define ANALYZER_OPTION_WITH_MARSHALLING(                                      \
864     PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,        \
865     HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
866     DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER,     \
867     MERGER, EXTRACTOR, TABLE_INDEX)                                            \
868   PARSE_OPTION_WITH_MARSHALLING(Args, Diags, Success, ID, FLAGS, PARAM,        \
869                                 SHOULD_PARSE, KEYPATH, DEFAULT_VALUE,          \
870                                 IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER,      \
871                                 MERGER, TABLE_INDEX)
872 #include "clang/Driver/Options.inc"
873 #undef ANALYZER_OPTION_WITH_MARSHALLING
874 
875   if (Arg *A = Args.getLastArg(OPT_analyzer_store)) {
876     StringRef Name = A->getValue();
877     AnalysisStores Value = llvm::StringSwitch<AnalysisStores>(Name)
878 #define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN) \
879       .Case(CMDFLAG, NAME##Model)
880 #include "clang/StaticAnalyzer/Core/Analyses.def"
881       .Default(NumStores);
882     if (Value == NumStores) {
883       Diags.Report(diag::err_drv_invalid_value)
884         << A->getAsString(Args) << Name;
885       Success = false;
886     } else {
887       Opts.AnalysisStoreOpt = Value;
888     }
889   }
890 
891   if (Arg *A = Args.getLastArg(OPT_analyzer_constraints)) {
892     StringRef Name = A->getValue();
893     AnalysisConstraints Value = llvm::StringSwitch<AnalysisConstraints>(Name)
894 #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) \
895       .Case(CMDFLAG, NAME##Model)
896 #include "clang/StaticAnalyzer/Core/Analyses.def"
897       .Default(NumConstraints);
898     if (Value == NumConstraints) {
899       Diags.Report(diag::err_drv_invalid_value)
900         << A->getAsString(Args) << Name;
901       Success = false;
902     } else {
903       Opts.AnalysisConstraintsOpt = Value;
904     }
905   }
906 
907   if (Arg *A = Args.getLastArg(OPT_analyzer_output)) {
908     StringRef Name = A->getValue();
909     AnalysisDiagClients Value = llvm::StringSwitch<AnalysisDiagClients>(Name)
910 #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN) \
911       .Case(CMDFLAG, PD_##NAME)
912 #include "clang/StaticAnalyzer/Core/Analyses.def"
913       .Default(NUM_ANALYSIS_DIAG_CLIENTS);
914     if (Value == NUM_ANALYSIS_DIAG_CLIENTS) {
915       Diags.Report(diag::err_drv_invalid_value)
916         << A->getAsString(Args) << Name;
917       Success = false;
918     } else {
919       Opts.AnalysisDiagOpt = Value;
920     }
921   }
922 
923   if (Arg *A = Args.getLastArg(OPT_analyzer_purge)) {
924     StringRef Name = A->getValue();
925     AnalysisPurgeMode Value = llvm::StringSwitch<AnalysisPurgeMode>(Name)
926 #define ANALYSIS_PURGE(NAME, CMDFLAG, DESC) \
927       .Case(CMDFLAG, NAME)
928 #include "clang/StaticAnalyzer/Core/Analyses.def"
929       .Default(NumPurgeModes);
930     if (Value == NumPurgeModes) {
931       Diags.Report(diag::err_drv_invalid_value)
932         << A->getAsString(Args) << Name;
933       Success = false;
934     } else {
935       Opts.AnalysisPurgeOpt = Value;
936     }
937   }
938 
939   if (Arg *A = Args.getLastArg(OPT_analyzer_inlining_mode)) {
940     StringRef Name = A->getValue();
941     AnalysisInliningMode Value = llvm::StringSwitch<AnalysisInliningMode>(Name)
942 #define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC) \
943       .Case(CMDFLAG, NAME)
944 #include "clang/StaticAnalyzer/Core/Analyses.def"
945       .Default(NumInliningModes);
946     if (Value == NumInliningModes) {
947       Diags.Report(diag::err_drv_invalid_value)
948         << A->getAsString(Args) << Name;
949       Success = false;
950     } else {
951       Opts.InliningMode = Value;
952     }
953   }
954 
955   Opts.CheckersAndPackages.clear();
956   for (const Arg *A :
957        Args.filtered(OPT_analyzer_checker, OPT_analyzer_disable_checker)) {
958     A->claim();
959     bool IsEnabled = A->getOption().getID() == OPT_analyzer_checker;
960     // We can have a list of comma separated checker names, e.g:
961     // '-analyzer-checker=cocoa,unix'
962     StringRef CheckerAndPackageList = A->getValue();
963     SmallVector<StringRef, 16> CheckersAndPackages;
964     CheckerAndPackageList.split(CheckersAndPackages, ",");
965     for (const StringRef &CheckerOrPackage : CheckersAndPackages)
966       Opts.CheckersAndPackages.emplace_back(std::string(CheckerOrPackage),
967                                             IsEnabled);
968   }
969 
970   // Go through the analyzer configuration options.
971   for (const auto *A : Args.filtered(OPT_analyzer_config)) {
972 
973     // We can have a list of comma separated config names, e.g:
974     // '-analyzer-config key1=val1,key2=val2'
975     StringRef configList = A->getValue();
976     SmallVector<StringRef, 4> configVals;
977     configList.split(configVals, ",");
978     for (const auto &configVal : configVals) {
979       StringRef key, val;
980       std::tie(key, val) = configVal.split("=");
981       if (val.empty()) {
982         Diags.Report(SourceLocation(),
983                      diag::err_analyzer_config_no_value) << configVal;
984         Success = false;
985         break;
986       }
987       if (val.find('=') != StringRef::npos) {
988         Diags.Report(SourceLocation(),
989                      diag::err_analyzer_config_multiple_values)
990           << configVal;
991         Success = false;
992         break;
993       }
994 
995       // TODO: Check checker options too, possibly in CheckerRegistry.
996       // Leave unknown non-checker configs unclaimed.
997       if (!key.contains(":") && Opts.isUnknownAnalyzerConfig(key)) {
998         if (Opts.ShouldEmitErrorsOnInvalidConfigValue) {
999           Diags.Report(diag::err_analyzer_config_unknown) << key;
1000           Success = false;
1001         }
1002         continue;
1003       }
1004 
1005       A->claim();
1006       Opts.Config[key] = std::string(val);
1007     }
1008   }
1009 
1010   if (Opts.ShouldEmitErrorsOnInvalidConfigValue)
1011     parseAnalyzerConfigs(Opts, &Diags);
1012   else
1013     parseAnalyzerConfigs(Opts, nullptr);
1014 
1015   llvm::raw_string_ostream os(Opts.FullCompilerInvocation);
1016   for (unsigned i = 0; i < Args.getNumInputArgStrings(); ++i) {
1017     if (i != 0)
1018       os << " ";
1019     os << Args.getArgString(i);
1020   }
1021   os.flush();
1022 
1023   return Success;
1024 }
1025 
1026 static StringRef getStringOption(AnalyzerOptions::ConfigTable &Config,
1027                                  StringRef OptionName, StringRef DefaultVal) {
1028   return Config.insert({OptionName, std::string(DefaultVal)}).first->second;
1029 }
1030 
1031 static void initOption(AnalyzerOptions::ConfigTable &Config,
1032                        DiagnosticsEngine *Diags,
1033                        StringRef &OptionField, StringRef Name,
1034                        StringRef DefaultVal) {
1035   // String options may be known to invalid (e.g. if the expected string is a
1036   // file name, but the file does not exist), those will have to be checked in
1037   // parseConfigs.
1038   OptionField = getStringOption(Config, Name, DefaultVal);
1039 }
1040 
1041 static void initOption(AnalyzerOptions::ConfigTable &Config,
1042                        DiagnosticsEngine *Diags,
1043                        bool &OptionField, StringRef Name, bool DefaultVal) {
1044   auto PossiblyInvalidVal = llvm::StringSwitch<Optional<bool>>(
1045                  getStringOption(Config, Name, (DefaultVal ? "true" : "false")))
1046       .Case("true", true)
1047       .Case("false", false)
1048       .Default(None);
1049 
1050   if (!PossiblyInvalidVal) {
1051     if (Diags)
1052       Diags->Report(diag::err_analyzer_config_invalid_input)
1053         << Name << "a boolean";
1054     else
1055       OptionField = DefaultVal;
1056   } else
1057     OptionField = PossiblyInvalidVal.getValue();
1058 }
1059 
1060 static void initOption(AnalyzerOptions::ConfigTable &Config,
1061                        DiagnosticsEngine *Diags,
1062                        unsigned &OptionField, StringRef Name,
1063                        unsigned DefaultVal) {
1064 
1065   OptionField = DefaultVal;
1066   bool HasFailed = getStringOption(Config, Name, std::to_string(DefaultVal))
1067                      .getAsInteger(0, OptionField);
1068   if (Diags && HasFailed)
1069     Diags->Report(diag::err_analyzer_config_invalid_input)
1070       << Name << "an unsigned";
1071 }
1072 
1073 static void parseAnalyzerConfigs(AnalyzerOptions &AnOpts,
1074                                  DiagnosticsEngine *Diags) {
1075   // TODO: There's no need to store the entire configtable, it'd be plenty
1076   // enough tostore checker options.
1077 
1078 #define ANALYZER_OPTION(TYPE, NAME, CMDFLAG, DESC, DEFAULT_VAL)                \
1079   initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, DEFAULT_VAL);
1080 
1081 #define ANALYZER_OPTION_DEPENDS_ON_USER_MODE(TYPE, NAME, CMDFLAG, DESC,        \
1082                                            SHALLOW_VAL, DEEP_VAL)              \
1083   switch (AnOpts.getUserMode()) {                                              \
1084   case UMK_Shallow:                                                            \
1085     initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, SHALLOW_VAL);       \
1086     break;                                                                     \
1087   case UMK_Deep:                                                               \
1088     initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, DEEP_VAL);          \
1089     break;                                                                     \
1090   }                                                                            \
1091 
1092 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.def"
1093 #undef ANALYZER_OPTION
1094 #undef ANALYZER_OPTION_DEPENDS_ON_USER_MODE
1095 
1096   // At this point, AnalyzerOptions is configured. Let's validate some options.
1097 
1098   // FIXME: Here we try to validate the silenced checkers or packages are valid.
1099   // The current approach only validates the registered checkers which does not
1100   // contain the runtime enabled checkers and optimally we would validate both.
1101   if (!AnOpts.RawSilencedCheckersAndPackages.empty()) {
1102     std::vector<StringRef> Checkers =
1103         AnOpts.getRegisteredCheckers(/*IncludeExperimental=*/true);
1104     std::vector<StringRef> Packages =
1105         AnOpts.getRegisteredPackages(/*IncludeExperimental=*/true);
1106 
1107     SmallVector<StringRef, 16> CheckersAndPackages;
1108     AnOpts.RawSilencedCheckersAndPackages.split(CheckersAndPackages, ";");
1109 
1110     for (const StringRef &CheckerOrPackage : CheckersAndPackages) {
1111       if (Diags) {
1112         bool IsChecker = CheckerOrPackage.contains('.');
1113         bool IsValidName =
1114             IsChecker
1115                 ? llvm::find(Checkers, CheckerOrPackage) != Checkers.end()
1116                 : llvm::find(Packages, CheckerOrPackage) != Packages.end();
1117 
1118         if (!IsValidName)
1119           Diags->Report(diag::err_unknown_analyzer_checker_or_package)
1120               << CheckerOrPackage;
1121       }
1122 
1123       AnOpts.SilencedCheckersAndPackages.emplace_back(CheckerOrPackage);
1124     }
1125   }
1126 
1127   if (!Diags)
1128     return;
1129 
1130   if (AnOpts.ShouldTrackConditionsDebug && !AnOpts.ShouldTrackConditions)
1131     Diags->Report(diag::err_analyzer_config_invalid_input)
1132         << "track-conditions-debug" << "'track-conditions' to also be enabled";
1133 
1134   if (!AnOpts.CTUDir.empty() && !llvm::sys::fs::is_directory(AnOpts.CTUDir))
1135     Diags->Report(diag::err_analyzer_config_invalid_input) << "ctu-dir"
1136                                                            << "a filename";
1137 
1138   if (!AnOpts.ModelPath.empty() &&
1139       !llvm::sys::fs::is_directory(AnOpts.ModelPath))
1140     Diags->Report(diag::err_analyzer_config_invalid_input) << "model-path"
1141                                                            << "a filename";
1142 }
1143 
1144 /// Generate a remark argument. This is an inverse of `ParseOptimizationRemark`.
1145 static void
1146 GenerateOptimizationRemark(SmallVectorImpl<const char *> &Args,
1147                            CompilerInvocation::StringAllocator SA,
1148                            OptSpecifier OptEQ, StringRef Name,
1149                            const CodeGenOptions::OptRemark &Remark) {
1150   if (Remark.hasValidPattern()) {
1151     GenerateArg(Args, OptEQ, Remark.Pattern, SA);
1152   } else if (Remark.Kind == CodeGenOptions::RK_Enabled) {
1153     GenerateArg(Args, OPT_R_Joined, Name, SA);
1154   } else if (Remark.Kind == CodeGenOptions::RK_Disabled) {
1155     GenerateArg(Args, OPT_R_Joined, StringRef("no-") + Name, SA);
1156   }
1157 }
1158 
1159 /// Parse a remark command line argument. It may be missing, disabled/enabled by
1160 /// '-R[no-]group' or specified with a regular expression by '-Rgroup=regexp'.
1161 /// On top of that, it can be disabled/enabled globally by '-R[no-]everything'.
1162 static CodeGenOptions::OptRemark
1163 ParseOptimizationRemark(DiagnosticsEngine &Diags, ArgList &Args,
1164                         OptSpecifier OptEQ, StringRef Name) {
1165   CodeGenOptions::OptRemark Result;
1166 
1167   auto InitializeResultPattern = [&Diags, &Args, &Result](const Arg *A) {
1168     Result.Pattern = A->getValue();
1169 
1170     std::string RegexError;
1171     Result.Regex = std::make_shared<llvm::Regex>(Result.Pattern);
1172     if (!Result.Regex->isValid(RegexError)) {
1173       Diags.Report(diag::err_drv_optimization_remark_pattern)
1174           << RegexError << A->getAsString(Args);
1175       return false;
1176     }
1177 
1178     return true;
1179   };
1180 
1181   for (Arg *A : Args) {
1182     if (A->getOption().matches(OPT_R_Joined)) {
1183       StringRef Value = A->getValue();
1184 
1185       if (Value == Name)
1186         Result.Kind = CodeGenOptions::RK_Enabled;
1187       else if (Value == "everything")
1188         Result.Kind = CodeGenOptions::RK_EnabledEverything;
1189       else if (Value.split('-') == std::make_pair(StringRef("no"), Name))
1190         Result.Kind = CodeGenOptions::RK_Disabled;
1191       else if (Value == "no-everything")
1192         Result.Kind = CodeGenOptions::RK_DisabledEverything;
1193     } else if (A->getOption().matches(OptEQ)) {
1194       Result.Kind = CodeGenOptions::RK_WithPattern;
1195       if (!InitializeResultPattern(A))
1196         return CodeGenOptions::OptRemark();
1197     }
1198   }
1199 
1200   if (Result.Kind == CodeGenOptions::RK_Disabled ||
1201       Result.Kind == CodeGenOptions::RK_DisabledEverything) {
1202     Result.Pattern = "";
1203     Result.Regex = nullptr;
1204   }
1205 
1206   return Result;
1207 }
1208 
1209 static bool parseDiagnosticLevelMask(StringRef FlagName,
1210                                      const std::vector<std::string> &Levels,
1211                                      DiagnosticsEngine &Diags,
1212                                      DiagnosticLevelMask &M) {
1213   bool Success = true;
1214   for (const auto &Level : Levels) {
1215     DiagnosticLevelMask const PM =
1216       llvm::StringSwitch<DiagnosticLevelMask>(Level)
1217         .Case("note",    DiagnosticLevelMask::Note)
1218         .Case("remark",  DiagnosticLevelMask::Remark)
1219         .Case("warning", DiagnosticLevelMask::Warning)
1220         .Case("error",   DiagnosticLevelMask::Error)
1221         .Default(DiagnosticLevelMask::None);
1222     if (PM == DiagnosticLevelMask::None) {
1223       Success = false;
1224       Diags.Report(diag::err_drv_invalid_value) << FlagName << Level;
1225     }
1226     M = M | PM;
1227   }
1228   return Success;
1229 }
1230 
1231 static void parseSanitizerKinds(StringRef FlagName,
1232                                 const std::vector<std::string> &Sanitizers,
1233                                 DiagnosticsEngine &Diags, SanitizerSet &S) {
1234   for (const auto &Sanitizer : Sanitizers) {
1235     SanitizerMask K = parseSanitizerValue(Sanitizer, /*AllowGroups=*/false);
1236     if (K == SanitizerMask())
1237       Diags.Report(diag::err_drv_invalid_value) << FlagName << Sanitizer;
1238     else
1239       S.set(K, true);
1240   }
1241 }
1242 
1243 static SmallVector<StringRef, 4> serializeSanitizerKinds(SanitizerSet S) {
1244   SmallVector<StringRef, 4> Values;
1245   serializeSanitizerSet(S, Values);
1246   return Values;
1247 }
1248 
1249 static void parseXRayInstrumentationBundle(StringRef FlagName, StringRef Bundle,
1250                                            ArgList &Args, DiagnosticsEngine &D,
1251                                            XRayInstrSet &S) {
1252   llvm::SmallVector<StringRef, 2> BundleParts;
1253   llvm::SplitString(Bundle, BundleParts, ",");
1254   for (const auto &B : BundleParts) {
1255     auto Mask = parseXRayInstrValue(B);
1256     if (Mask == XRayInstrKind::None)
1257       if (B != "none")
1258         D.Report(diag::err_drv_invalid_value) << FlagName << Bundle;
1259       else
1260         S.Mask = Mask;
1261     else if (Mask == XRayInstrKind::All)
1262       S.Mask = Mask;
1263     else
1264       S.set(Mask, true);
1265   }
1266 }
1267 
1268 static std::string serializeXRayInstrumentationBundle(const XRayInstrSet &S) {
1269   llvm::SmallVector<StringRef, 2> BundleParts;
1270   serializeXRayInstrValue(S, BundleParts);
1271   std::string Buffer;
1272   llvm::raw_string_ostream OS(Buffer);
1273   llvm::interleave(BundleParts, OS, [&OS](StringRef Part) { OS << Part; }, ",");
1274   return OS.str();
1275 }
1276 
1277 // Set the profile kind using fprofile-instrument-use-path.
1278 static void setPGOUseInstrumentor(CodeGenOptions &Opts,
1279                                   const Twine &ProfileName) {
1280   auto ReaderOrErr = llvm::IndexedInstrProfReader::create(ProfileName);
1281   // In error, return silently and let Clang PGOUse report the error message.
1282   if (auto E = ReaderOrErr.takeError()) {
1283     llvm::consumeError(std::move(E));
1284     Opts.setProfileUse(CodeGenOptions::ProfileClangInstr);
1285     return;
1286   }
1287   std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader =
1288     std::move(ReaderOrErr.get());
1289   if (PGOReader->isIRLevelProfile()) {
1290     if (PGOReader->hasCSIRLevelProfile())
1291       Opts.setProfileUse(CodeGenOptions::ProfileCSIRInstr);
1292     else
1293       Opts.setProfileUse(CodeGenOptions::ProfileIRInstr);
1294   } else
1295     Opts.setProfileUse(CodeGenOptions::ProfileClangInstr);
1296 }
1297 
1298 void CompilerInvocation::GenerateCodeGenArgs(
1299     const CodeGenOptions &Opts, SmallVectorImpl<const char *> &Args,
1300     StringAllocator SA, const llvm::Triple &T, const std::string &OutputFile,
1301     const LangOptions *LangOpts) {
1302   const CodeGenOptions &CodeGenOpts = Opts;
1303 
1304   if (Opts.OptimizationLevel == 0)
1305     GenerateArg(Args, OPT_O0, SA);
1306   else
1307     GenerateArg(Args, OPT_O, Twine(Opts.OptimizationLevel), SA);
1308 
1309 #define CODEGEN_OPTION_WITH_MARSHALLING(                                       \
1310     PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,        \
1311     HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
1312     DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER,     \
1313     MERGER, EXTRACTOR, TABLE_INDEX)                                            \
1314   GENERATE_OPTION_WITH_MARSHALLING(                                            \
1315       Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE,    \
1316       IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
1317 #include "clang/Driver/Options.inc"
1318 #undef CODEGEN_OPTION_WITH_MARSHALLING
1319 
1320   if (Opts.OptimizationLevel > 0) {
1321     if (Opts.Inlining == CodeGenOptions::NormalInlining)
1322       GenerateArg(Args, OPT_finline_functions, SA);
1323     else if (Opts.Inlining == CodeGenOptions::OnlyHintInlining)
1324       GenerateArg(Args, OPT_finline_hint_functions, SA);
1325     else if (Opts.Inlining == CodeGenOptions::OnlyAlwaysInlining)
1326       GenerateArg(Args, OPT_fno_inline, SA);
1327   }
1328 
1329   if (Opts.DirectAccessExternalData && LangOpts->PICLevel != 0)
1330     GenerateArg(Args, OPT_fdirect_access_external_data, SA);
1331   else if (!Opts.DirectAccessExternalData && LangOpts->PICLevel == 0)
1332     GenerateArg(Args, OPT_fno_direct_access_external_data, SA);
1333 
1334   Optional<StringRef> DebugInfoVal;
1335   switch (Opts.DebugInfo) {
1336   case codegenoptions::DebugLineTablesOnly:
1337     DebugInfoVal = "line-tables-only";
1338     break;
1339   case codegenoptions::DebugDirectivesOnly:
1340     DebugInfoVal = "line-directives-only";
1341     break;
1342   case codegenoptions::DebugInfoConstructor:
1343     DebugInfoVal = "constructor";
1344     break;
1345   case codegenoptions::LimitedDebugInfo:
1346     DebugInfoVal = "limited";
1347     break;
1348   case codegenoptions::FullDebugInfo:
1349     DebugInfoVal = "standalone";
1350     break;
1351   case codegenoptions::UnusedTypeInfo:
1352     DebugInfoVal = "unused-types";
1353     break;
1354   case codegenoptions::NoDebugInfo: // default value
1355     DebugInfoVal = None;
1356     break;
1357   case codegenoptions::LocTrackingOnly: // implied value
1358     DebugInfoVal = None;
1359     break;
1360   }
1361   if (DebugInfoVal)
1362     GenerateArg(Args, OPT_debug_info_kind_EQ, *DebugInfoVal, SA);
1363 
1364   if (Opts.DebugInfo == codegenoptions::DebugInfoConstructor)
1365     GenerateArg(Args, OPT_fuse_ctor_homing, SA);
1366 
1367   for (const auto &Prefix : Opts.DebugPrefixMap)
1368     GenerateArg(Args, OPT_fdebug_prefix_map_EQ,
1369                 Prefix.first + "=" + Prefix.second, SA);
1370 
1371   for (const auto &Prefix : Opts.CoveragePrefixMap)
1372     GenerateArg(Args, OPT_fcoverage_prefix_map_EQ,
1373                 Prefix.first + "=" + Prefix.second, SA);
1374 
1375   if (Opts.NewStructPathTBAA)
1376     GenerateArg(Args, OPT_new_struct_path_tbaa, SA);
1377 
1378   if (Opts.OptimizeSize == 1)
1379     GenerateArg(Args, OPT_O, "s", SA);
1380   else if (Opts.OptimizeSize == 2)
1381     GenerateArg(Args, OPT_O, "z", SA);
1382 
1383   // SimplifyLibCalls is set only in the absence of -fno-builtin and
1384   // -ffreestanding. We'll consider that when generating them.
1385 
1386   // NoBuiltinFuncs are generated by LangOptions.
1387 
1388   if (Opts.UnrollLoops && Opts.OptimizationLevel <= 1)
1389     GenerateArg(Args, OPT_funroll_loops, SA);
1390   else if (!Opts.UnrollLoops && Opts.OptimizationLevel > 1)
1391     GenerateArg(Args, OPT_fno_unroll_loops, SA);
1392 
1393   if (!Opts.BinutilsVersion.empty())
1394     GenerateArg(Args, OPT_fbinutils_version_EQ, Opts.BinutilsVersion, SA);
1395 
1396   if (Opts.DebugNameTable ==
1397       static_cast<unsigned>(llvm::DICompileUnit::DebugNameTableKind::GNU))
1398     GenerateArg(Args, OPT_ggnu_pubnames, SA);
1399   else if (Opts.DebugNameTable ==
1400            static_cast<unsigned>(
1401                llvm::DICompileUnit::DebugNameTableKind::Default))
1402     GenerateArg(Args, OPT_gpubnames, SA);
1403 
1404   // ProfileInstrumentUsePath is marshalled automatically, no need to generate
1405   // it or PGOUseInstrumentor.
1406 
1407   if (Opts.TimePasses) {
1408     if (Opts.TimePassesPerRun)
1409       GenerateArg(Args, OPT_ftime_report_EQ, "per-pass-run", SA);
1410     else
1411       GenerateArg(Args, OPT_ftime_report, SA);
1412   }
1413 
1414   if (Opts.PrepareForLTO && !Opts.PrepareForThinLTO)
1415     GenerateArg(Args, OPT_flto, SA);
1416 
1417   if (Opts.PrepareForThinLTO)
1418     GenerateArg(Args, OPT_flto_EQ, "thin", SA);
1419 
1420   if (!Opts.ThinLTOIndexFile.empty())
1421     GenerateArg(Args, OPT_fthinlto_index_EQ, Opts.ThinLTOIndexFile, SA);
1422 
1423   if (Opts.SaveTempsFilePrefix == OutputFile)
1424     GenerateArg(Args, OPT_save_temps_EQ, "obj", SA);
1425 
1426   StringRef MemProfileBasename("memprof.profraw");
1427   if (!Opts.MemoryProfileOutput.empty()) {
1428     if (Opts.MemoryProfileOutput == MemProfileBasename) {
1429       GenerateArg(Args, OPT_fmemory_profile, SA);
1430     } else {
1431       size_t ArgLength =
1432           Opts.MemoryProfileOutput.size() - MemProfileBasename.size();
1433       GenerateArg(Args, OPT_fmemory_profile_EQ,
1434                   Opts.MemoryProfileOutput.substr(0, ArgLength), SA);
1435     }
1436   }
1437 
1438   if (memcmp(Opts.CoverageVersion, "408*", 4) != 0)
1439     GenerateArg(Args, OPT_coverage_version_EQ,
1440                 StringRef(Opts.CoverageVersion, 4), SA);
1441 
1442   // TODO: Check if we need to generate arguments stored in CmdArgs. (Namely
1443   //  '-fembed_bitcode', which does not map to any CompilerInvocation field and
1444   //  won't be generated.)
1445 
1446   if (Opts.XRayInstrumentationBundle.Mask != XRayInstrKind::All) {
1447     std::string InstrBundle =
1448         serializeXRayInstrumentationBundle(Opts.XRayInstrumentationBundle);
1449     if (!InstrBundle.empty())
1450       GenerateArg(Args, OPT_fxray_instrumentation_bundle, InstrBundle, SA);
1451   }
1452 
1453   if (Opts.CFProtectionReturn && Opts.CFProtectionBranch)
1454     GenerateArg(Args, OPT_fcf_protection_EQ, "full", SA);
1455   else if (Opts.CFProtectionReturn)
1456     GenerateArg(Args, OPT_fcf_protection_EQ, "return", SA);
1457   else if (Opts.CFProtectionBranch)
1458     GenerateArg(Args, OPT_fcf_protection_EQ, "branch", SA);
1459 
1460   for (const auto &F : Opts.LinkBitcodeFiles) {
1461     bool Builtint = F.LinkFlags == llvm::Linker::Flags::LinkOnlyNeeded &&
1462                     F.PropagateAttrs && F.Internalize;
1463     GenerateArg(Args,
1464                 Builtint ? OPT_mlink_builtin_bitcode : OPT_mlink_bitcode_file,
1465                 F.Filename, SA);
1466   }
1467 
1468   // TODO: Consider removing marshalling annotations from f[no_]emulated_tls.
1469   //  That would make it easy to generate the option only **once** if it was
1470   //  explicitly set to non-default value.
1471   if (Opts.ExplicitEmulatedTLS) {
1472     GenerateArg(
1473         Args, Opts.EmulatedTLS ? OPT_femulated_tls : OPT_fno_emulated_tls, SA);
1474   }
1475 
1476   if (Opts.FPDenormalMode != llvm::DenormalMode::getIEEE())
1477     GenerateArg(Args, OPT_fdenormal_fp_math_EQ, Opts.FPDenormalMode.str(), SA);
1478 
1479   if (Opts.FP32DenormalMode != llvm::DenormalMode::getIEEE())
1480     GenerateArg(Args, OPT_fdenormal_fp_math_f32_EQ, Opts.FP32DenormalMode.str(),
1481                 SA);
1482 
1483   if (Opts.StructReturnConvention == CodeGenOptions::SRCK_OnStack) {
1484     OptSpecifier Opt =
1485         T.isPPC32() ? OPT_maix_struct_return : OPT_fpcc_struct_return;
1486     GenerateArg(Args, Opt, SA);
1487   } else if (Opts.StructReturnConvention == CodeGenOptions::SRCK_InRegs) {
1488     OptSpecifier Opt =
1489         T.isPPC32() ? OPT_msvr4_struct_return : OPT_freg_struct_return;
1490     GenerateArg(Args, Opt, SA);
1491   }
1492 
1493   if (Opts.EnableAIXExtendedAltivecABI)
1494     GenerateArg(Args, OPT_mabi_EQ_vec_extabi, SA);
1495 
1496   if (!Opts.OptRecordPasses.empty())
1497     GenerateArg(Args, OPT_opt_record_passes, Opts.OptRecordPasses, SA);
1498 
1499   if (!Opts.OptRecordFormat.empty())
1500     GenerateArg(Args, OPT_opt_record_format, Opts.OptRecordFormat, SA);
1501 
1502   GenerateOptimizationRemark(Args, SA, OPT_Rpass_EQ, "pass",
1503                              Opts.OptimizationRemark);
1504 
1505   GenerateOptimizationRemark(Args, SA, OPT_Rpass_missed_EQ, "pass-missed",
1506                              Opts.OptimizationRemarkMissed);
1507 
1508   GenerateOptimizationRemark(Args, SA, OPT_Rpass_analysis_EQ, "pass-analysis",
1509                              Opts.OptimizationRemarkAnalysis);
1510 
1511   GenerateArg(Args, OPT_fdiagnostics_hotness_threshold_EQ,
1512               Opts.DiagnosticsHotnessThreshold
1513                   ? Twine(*Opts.DiagnosticsHotnessThreshold)
1514                   : "auto",
1515               SA);
1516 
1517   for (StringRef Sanitizer : serializeSanitizerKinds(Opts.SanitizeRecover))
1518     GenerateArg(Args, OPT_fsanitize_recover_EQ, Sanitizer, SA);
1519 
1520   for (StringRef Sanitizer : serializeSanitizerKinds(Opts.SanitizeTrap))
1521     GenerateArg(Args, OPT_fsanitize_trap_EQ, Sanitizer, SA);
1522 
1523   if (!Opts.EmitVersionIdentMetadata)
1524     GenerateArg(Args, OPT_Qn, SA);
1525 
1526   switch (Opts.FiniteLoops) {
1527   case CodeGenOptions::FiniteLoopsKind::Language:
1528     break;
1529   case CodeGenOptions::FiniteLoopsKind::Always:
1530     GenerateArg(Args, OPT_ffinite_loops, SA);
1531     break;
1532   case CodeGenOptions::FiniteLoopsKind::Never:
1533     GenerateArg(Args, OPT_fno_finite_loops, SA);
1534     break;
1535   }
1536 }
1537 
1538 bool CompilerInvocation::ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args,
1539                                           InputKind IK,
1540                                           DiagnosticsEngine &Diags,
1541                                           const llvm::Triple &T,
1542                                           const std::string &OutputFile,
1543                                           const LangOptions &LangOptsRef) {
1544   unsigned NumErrorsBefore = Diags.getNumErrors();
1545 
1546   bool Success = true;
1547 
1548   unsigned OptimizationLevel = getOptimizationLevel(Args, IK, Diags);
1549   // TODO: This could be done in Driver
1550   unsigned MaxOptLevel = 3;
1551   if (OptimizationLevel > MaxOptLevel) {
1552     // If the optimization level is not supported, fall back on the default
1553     // optimization
1554     Diags.Report(diag::warn_drv_optimization_value)
1555         << Args.getLastArg(OPT_O)->getAsString(Args) << "-O" << MaxOptLevel;
1556     OptimizationLevel = MaxOptLevel;
1557   }
1558   Opts.OptimizationLevel = OptimizationLevel;
1559 
1560   // The key paths of codegen options defined in Options.td start with
1561   // "CodeGenOpts.". Let's provide the expected variable name and type.
1562   CodeGenOptions &CodeGenOpts = Opts;
1563   // Some codegen options depend on language options. Let's provide the expected
1564   // variable name and type.
1565   const LangOptions *LangOpts = &LangOptsRef;
1566 
1567 #define CODEGEN_OPTION_WITH_MARSHALLING(                                       \
1568     PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,        \
1569     HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
1570     DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER,     \
1571     MERGER, EXTRACTOR, TABLE_INDEX)                                            \
1572   PARSE_OPTION_WITH_MARSHALLING(Args, Diags, Success, ID, FLAGS, PARAM,        \
1573                                 SHOULD_PARSE, KEYPATH, DEFAULT_VALUE,          \
1574                                 IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER,      \
1575                                 MERGER, TABLE_INDEX)
1576 #include "clang/Driver/Options.inc"
1577 #undef CODEGEN_OPTION_WITH_MARSHALLING
1578 
1579   // At O0 we want to fully disable inlining outside of cases marked with
1580   // 'alwaysinline' that are required for correctness.
1581   Opts.setInlining((Opts.OptimizationLevel == 0)
1582                        ? CodeGenOptions::OnlyAlwaysInlining
1583                        : CodeGenOptions::NormalInlining);
1584   // Explicit inlining flags can disable some or all inlining even at
1585   // optimization levels above zero.
1586   if (Arg *InlineArg = Args.getLastArg(
1587           options::OPT_finline_functions, options::OPT_finline_hint_functions,
1588           options::OPT_fno_inline_functions, options::OPT_fno_inline)) {
1589     if (Opts.OptimizationLevel > 0) {
1590       const Option &InlineOpt = InlineArg->getOption();
1591       if (InlineOpt.matches(options::OPT_finline_functions))
1592         Opts.setInlining(CodeGenOptions::NormalInlining);
1593       else if (InlineOpt.matches(options::OPT_finline_hint_functions))
1594         Opts.setInlining(CodeGenOptions::OnlyHintInlining);
1595       else
1596         Opts.setInlining(CodeGenOptions::OnlyAlwaysInlining);
1597     }
1598   }
1599 
1600   // PIC defaults to -fno-direct-access-external-data while non-PIC defaults to
1601   // -fdirect-access-external-data.
1602   Opts.DirectAccessExternalData =
1603       Args.hasArg(OPT_fdirect_access_external_data) ||
1604       (!Args.hasArg(OPT_fno_direct_access_external_data) &&
1605        LangOpts->PICLevel == 0);
1606 
1607   if (Arg *A = Args.getLastArg(OPT_debug_info_kind_EQ)) {
1608     unsigned Val =
1609         llvm::StringSwitch<unsigned>(A->getValue())
1610             .Case("line-tables-only", codegenoptions::DebugLineTablesOnly)
1611             .Case("line-directives-only", codegenoptions::DebugDirectivesOnly)
1612             .Case("constructor", codegenoptions::DebugInfoConstructor)
1613             .Case("limited", codegenoptions::LimitedDebugInfo)
1614             .Case("standalone", codegenoptions::FullDebugInfo)
1615             .Case("unused-types", codegenoptions::UnusedTypeInfo)
1616             .Default(~0U);
1617     if (Val == ~0U)
1618       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
1619                                                 << A->getValue();
1620     else
1621       Opts.setDebugInfo(static_cast<codegenoptions::DebugInfoKind>(Val));
1622   }
1623 
1624   // If -fuse-ctor-homing is set and limited debug info is already on, then use
1625   // constructor homing.
1626   if (Args.getLastArg(OPT_fuse_ctor_homing))
1627     if (Opts.getDebugInfo() == codegenoptions::LimitedDebugInfo)
1628       Opts.setDebugInfo(codegenoptions::DebugInfoConstructor);
1629 
1630   for (const auto &Arg : Args.getAllArgValues(OPT_fdebug_prefix_map_EQ)) {
1631     auto Split = StringRef(Arg).split('=');
1632     Opts.DebugPrefixMap.insert(
1633         {std::string(Split.first), std::string(Split.second)});
1634   }
1635 
1636   for (const auto &Arg : Args.getAllArgValues(OPT_fcoverage_prefix_map_EQ)) {
1637     auto Split = StringRef(Arg).split('=');
1638     Opts.CoveragePrefixMap.insert(
1639         {std::string(Split.first), std::string(Split.second)});
1640   }
1641 
1642   const llvm::Triple::ArchType DebugEntryValueArchs[] = {
1643       llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::aarch64,
1644       llvm::Triple::arm, llvm::Triple::armeb, llvm::Triple::mips,
1645       llvm::Triple::mipsel, llvm::Triple::mips64, llvm::Triple::mips64el};
1646 
1647   if (Opts.OptimizationLevel > 0 && Opts.hasReducedDebugInfo() &&
1648       llvm::is_contained(DebugEntryValueArchs, T.getArch()))
1649     Opts.EmitCallSiteInfo = true;
1650 
1651   Opts.NewStructPathTBAA = !Args.hasArg(OPT_no_struct_path_tbaa) &&
1652                            Args.hasArg(OPT_new_struct_path_tbaa);
1653   Opts.OptimizeSize = getOptimizationLevelSize(Args);
1654   Opts.SimplifyLibCalls = !LangOpts->NoBuiltin;
1655   if (Opts.SimplifyLibCalls)
1656     Opts.NoBuiltinFuncs = LangOpts->NoBuiltinFuncs;
1657   Opts.UnrollLoops =
1658       Args.hasFlag(OPT_funroll_loops, OPT_fno_unroll_loops,
1659                    (Opts.OptimizationLevel > 1));
1660   Opts.BinutilsVersion =
1661       std::string(Args.getLastArgValue(OPT_fbinutils_version_EQ));
1662 
1663   Opts.DebugNameTable = static_cast<unsigned>(
1664       Args.hasArg(OPT_ggnu_pubnames)
1665           ? llvm::DICompileUnit::DebugNameTableKind::GNU
1666           : Args.hasArg(OPT_gpubnames)
1667                 ? llvm::DICompileUnit::DebugNameTableKind::Default
1668                 : llvm::DICompileUnit::DebugNameTableKind::None);
1669 
1670   if (!Opts.ProfileInstrumentUsePath.empty())
1671     setPGOUseInstrumentor(Opts, Opts.ProfileInstrumentUsePath);
1672 
1673   if (const Arg *A = Args.getLastArg(OPT_ftime_report, OPT_ftime_report_EQ)) {
1674     Opts.TimePasses = true;
1675 
1676     // -ftime-report= is only for new pass manager.
1677     if (A->getOption().getID() == OPT_ftime_report_EQ) {
1678       if (Opts.LegacyPassManager)
1679         Diags.Report(diag::err_drv_argument_only_allowed_with)
1680             << A->getAsString(Args) << "-fno-legacy-pass-manager";
1681 
1682       StringRef Val = A->getValue();
1683       if (Val == "per-pass")
1684         Opts.TimePassesPerRun = false;
1685       else if (Val == "per-pass-run")
1686         Opts.TimePassesPerRun = true;
1687       else
1688         Diags.Report(diag::err_drv_invalid_value)
1689             << A->getAsString(Args) << A->getValue();
1690     }
1691   }
1692 
1693   Opts.PrepareForLTO = Args.hasArg(OPT_flto, OPT_flto_EQ);
1694   Opts.PrepareForThinLTO = false;
1695   if (Arg *A = Args.getLastArg(OPT_flto_EQ)) {
1696     StringRef S = A->getValue();
1697     if (S == "thin")
1698       Opts.PrepareForThinLTO = true;
1699     else if (S != "full")
1700       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << S;
1701   }
1702   if (Arg *A = Args.getLastArg(OPT_fthinlto_index_EQ)) {
1703     if (IK.getLanguage() != Language::LLVM_IR)
1704       Diags.Report(diag::err_drv_argument_only_allowed_with)
1705           << A->getAsString(Args) << "-x ir";
1706     Opts.ThinLTOIndexFile =
1707         std::string(Args.getLastArgValue(OPT_fthinlto_index_EQ));
1708   }
1709   if (Arg *A = Args.getLastArg(OPT_save_temps_EQ))
1710     Opts.SaveTempsFilePrefix =
1711         llvm::StringSwitch<std::string>(A->getValue())
1712             .Case("obj", OutputFile)
1713             .Default(llvm::sys::path::filename(OutputFile).str());
1714 
1715   // The memory profile runtime appends the pid to make this name more unique.
1716   const char *MemProfileBasename = "memprof.profraw";
1717   if (Args.hasArg(OPT_fmemory_profile_EQ)) {
1718     SmallString<128> Path(
1719         std::string(Args.getLastArgValue(OPT_fmemory_profile_EQ)));
1720     llvm::sys::path::append(Path, MemProfileBasename);
1721     Opts.MemoryProfileOutput = std::string(Path);
1722   } else if (Args.hasArg(OPT_fmemory_profile))
1723     Opts.MemoryProfileOutput = MemProfileBasename;
1724 
1725   memcpy(Opts.CoverageVersion, "408*", 4);
1726   if (Opts.EmitGcovArcs || Opts.EmitGcovNotes) {
1727     if (Args.hasArg(OPT_coverage_version_EQ)) {
1728       StringRef CoverageVersion = Args.getLastArgValue(OPT_coverage_version_EQ);
1729       if (CoverageVersion.size() != 4) {
1730         Diags.Report(diag::err_drv_invalid_value)
1731             << Args.getLastArg(OPT_coverage_version_EQ)->getAsString(Args)
1732             << CoverageVersion;
1733       } else {
1734         memcpy(Opts.CoverageVersion, CoverageVersion.data(), 4);
1735       }
1736     }
1737   }
1738   // FIXME: For backend options that are not yet recorded as function
1739   // attributes in the IR, keep track of them so we can embed them in a
1740   // separate data section and use them when building the bitcode.
1741   for (const auto &A : Args) {
1742     // Do not encode output and input.
1743     if (A->getOption().getID() == options::OPT_o ||
1744         A->getOption().getID() == options::OPT_INPUT ||
1745         A->getOption().getID() == options::OPT_x ||
1746         A->getOption().getID() == options::OPT_fembed_bitcode ||
1747         A->getOption().matches(options::OPT_W_Group))
1748       continue;
1749     ArgStringList ASL;
1750     A->render(Args, ASL);
1751     for (const auto &arg : ASL) {
1752       StringRef ArgStr(arg);
1753       Opts.CmdArgs.insert(Opts.CmdArgs.end(), ArgStr.begin(), ArgStr.end());
1754       // using \00 to separate each commandline options.
1755       Opts.CmdArgs.push_back('\0');
1756     }
1757   }
1758 
1759   auto XRayInstrBundles =
1760       Args.getAllArgValues(OPT_fxray_instrumentation_bundle);
1761   if (XRayInstrBundles.empty())
1762     Opts.XRayInstrumentationBundle.Mask = XRayInstrKind::All;
1763   else
1764     for (const auto &A : XRayInstrBundles)
1765       parseXRayInstrumentationBundle("-fxray-instrumentation-bundle=", A, Args,
1766                                      Diags, Opts.XRayInstrumentationBundle);
1767 
1768   if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
1769     StringRef Name = A->getValue();
1770     if (Name == "full") {
1771       Opts.CFProtectionReturn = 1;
1772       Opts.CFProtectionBranch = 1;
1773     } else if (Name == "return")
1774       Opts.CFProtectionReturn = 1;
1775     else if (Name == "branch")
1776       Opts.CFProtectionBranch = 1;
1777     else if (Name != "none") {
1778       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
1779       Success = false;
1780     }
1781   }
1782 
1783   for (auto *A :
1784        Args.filtered(OPT_mlink_bitcode_file, OPT_mlink_builtin_bitcode)) {
1785     CodeGenOptions::BitcodeFileToLink F;
1786     F.Filename = A->getValue();
1787     if (A->getOption().matches(OPT_mlink_builtin_bitcode)) {
1788       F.LinkFlags = llvm::Linker::Flags::LinkOnlyNeeded;
1789       // When linking CUDA bitcode, propagate function attributes so that
1790       // e.g. libdevice gets fast-math attrs if we're building with fast-math.
1791       F.PropagateAttrs = true;
1792       F.Internalize = true;
1793     }
1794     Opts.LinkBitcodeFiles.push_back(F);
1795   }
1796 
1797   if (Args.getLastArg(OPT_femulated_tls) ||
1798       Args.getLastArg(OPT_fno_emulated_tls)) {
1799     Opts.ExplicitEmulatedTLS = true;
1800   }
1801 
1802   if (Arg *A = Args.getLastArg(OPT_fdenormal_fp_math_EQ)) {
1803     StringRef Val = A->getValue();
1804     Opts.FPDenormalMode = llvm::parseDenormalFPAttribute(Val);
1805     if (!Opts.FPDenormalMode.isValid())
1806       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
1807   }
1808 
1809   if (Arg *A = Args.getLastArg(OPT_fdenormal_fp_math_f32_EQ)) {
1810     StringRef Val = A->getValue();
1811     Opts.FP32DenormalMode = llvm::parseDenormalFPAttribute(Val);
1812     if (!Opts.FP32DenormalMode.isValid())
1813       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
1814   }
1815 
1816   // X86_32 has -fppc-struct-return and -freg-struct-return.
1817   // PPC32 has -maix-struct-return and -msvr4-struct-return.
1818   if (Arg *A =
1819           Args.getLastArg(OPT_fpcc_struct_return, OPT_freg_struct_return,
1820                           OPT_maix_struct_return, OPT_msvr4_struct_return)) {
1821     // TODO: We might want to consider enabling these options on AIX in the
1822     // future.
1823     if (T.isOSAIX())
1824       Diags.Report(diag::err_drv_unsupported_opt_for_target)
1825           << A->getSpelling() << T.str();
1826 
1827     const Option &O = A->getOption();
1828     if (O.matches(OPT_fpcc_struct_return) ||
1829         O.matches(OPT_maix_struct_return)) {
1830       Opts.setStructReturnConvention(CodeGenOptions::SRCK_OnStack);
1831     } else {
1832       assert(O.matches(OPT_freg_struct_return) ||
1833              O.matches(OPT_msvr4_struct_return));
1834       Opts.setStructReturnConvention(CodeGenOptions::SRCK_InRegs);
1835     }
1836   }
1837 
1838   if (Arg *A =
1839           Args.getLastArg(OPT_mabi_EQ_vec_default, OPT_mabi_EQ_vec_extabi)) {
1840     if (!T.isOSAIX())
1841       Diags.Report(diag::err_drv_unsupported_opt_for_target)
1842           << A->getSpelling() << T.str();
1843 
1844     const Option &O = A->getOption();
1845     if (O.matches(OPT_mabi_EQ_vec_default))
1846       Diags.Report(diag::err_aix_default_altivec_abi)
1847           << A->getSpelling() << T.str();
1848     else {
1849       assert(O.matches(OPT_mabi_EQ_vec_extabi));
1850       Opts.EnableAIXExtendedAltivecABI = 1;
1851     }
1852   }
1853 
1854   bool NeedLocTracking = false;
1855 
1856   if (!Opts.OptRecordFile.empty())
1857     NeedLocTracking = true;
1858 
1859   if (Arg *A = Args.getLastArg(OPT_opt_record_passes)) {
1860     Opts.OptRecordPasses = A->getValue();
1861     NeedLocTracking = true;
1862   }
1863 
1864   if (Arg *A = Args.getLastArg(OPT_opt_record_format)) {
1865     Opts.OptRecordFormat = A->getValue();
1866     NeedLocTracking = true;
1867   }
1868 
1869   Opts.OptimizationRemark =
1870       ParseOptimizationRemark(Diags, Args, OPT_Rpass_EQ, "pass");
1871 
1872   Opts.OptimizationRemarkMissed =
1873       ParseOptimizationRemark(Diags, Args, OPT_Rpass_missed_EQ, "pass-missed");
1874 
1875   Opts.OptimizationRemarkAnalysis = ParseOptimizationRemark(
1876       Diags, Args, OPT_Rpass_analysis_EQ, "pass-analysis");
1877 
1878   NeedLocTracking |= Opts.OptimizationRemark.hasValidPattern() ||
1879                      Opts.OptimizationRemarkMissed.hasValidPattern() ||
1880                      Opts.OptimizationRemarkAnalysis.hasValidPattern();
1881 
1882   bool UsingSampleProfile = !Opts.SampleProfileFile.empty();
1883   bool UsingProfile = UsingSampleProfile ||
1884       (Opts.getProfileUse() != CodeGenOptions::ProfileNone);
1885 
1886   if (Opts.DiagnosticsWithHotness && !UsingProfile &&
1887       // An IR file will contain PGO as metadata
1888       IK.getLanguage() != Language::LLVM_IR)
1889     Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo)
1890         << "-fdiagnostics-show-hotness";
1891 
1892   // Parse remarks hotness threshold. Valid value is either integer or 'auto'.
1893   if (auto *arg =
1894           Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
1895     auto ResultOrErr =
1896         llvm::remarks::parseHotnessThresholdOption(arg->getValue());
1897 
1898     if (!ResultOrErr) {
1899       Diags.Report(diag::err_drv_invalid_diagnotics_hotness_threshold)
1900           << "-fdiagnostics-hotness-threshold=";
1901     } else {
1902       Opts.DiagnosticsHotnessThreshold = *ResultOrErr;
1903       if ((!Opts.DiagnosticsHotnessThreshold.hasValue() ||
1904            Opts.DiagnosticsHotnessThreshold.getValue() > 0) &&
1905           !UsingProfile)
1906         Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo)
1907             << "-fdiagnostics-hotness-threshold=";
1908     }
1909   }
1910 
1911   // If the user requested to use a sample profile for PGO, then the
1912   // backend will need to track source location information so the profile
1913   // can be incorporated into the IR.
1914   if (UsingSampleProfile)
1915     NeedLocTracking = true;
1916 
1917   // If the user requested a flag that requires source locations available in
1918   // the backend, make sure that the backend tracks source location information.
1919   if (NeedLocTracking && Opts.getDebugInfo() == codegenoptions::NoDebugInfo)
1920     Opts.setDebugInfo(codegenoptions::LocTrackingOnly);
1921 
1922   // Parse -fsanitize-recover= arguments.
1923   // FIXME: Report unrecoverable sanitizers incorrectly specified here.
1924   parseSanitizerKinds("-fsanitize-recover=",
1925                       Args.getAllArgValues(OPT_fsanitize_recover_EQ), Diags,
1926                       Opts.SanitizeRecover);
1927   parseSanitizerKinds("-fsanitize-trap=",
1928                       Args.getAllArgValues(OPT_fsanitize_trap_EQ), Diags,
1929                       Opts.SanitizeTrap);
1930 
1931   Opts.EmitVersionIdentMetadata = Args.hasFlag(OPT_Qy, OPT_Qn, true);
1932 
1933   if (Args.hasArg(options::OPT_ffinite_loops))
1934     Opts.FiniteLoops = CodeGenOptions::FiniteLoopsKind::Always;
1935   else if (Args.hasArg(options::OPT_fno_finite_loops))
1936     Opts.FiniteLoops = CodeGenOptions::FiniteLoopsKind::Never;
1937 
1938   return Success && Diags.getNumErrors() == NumErrorsBefore;
1939 }
1940 
1941 static void
1942 GenerateDependencyOutputArgs(const DependencyOutputOptions &Opts,
1943                              SmallVectorImpl<const char *> &Args,
1944                              CompilerInvocation::StringAllocator SA) {
1945   const DependencyOutputOptions &DependencyOutputOpts = Opts;
1946 #define DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING(                             \
1947     PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,        \
1948     HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
1949     DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER,     \
1950     MERGER, EXTRACTOR, TABLE_INDEX)                                            \
1951   GENERATE_OPTION_WITH_MARSHALLING(                                            \
1952       Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE,    \
1953       IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
1954 #include "clang/Driver/Options.inc"
1955 #undef DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING
1956 
1957   if (Opts.ShowIncludesDest != ShowIncludesDestination::None)
1958     GenerateArg(Args, OPT_show_includes, SA);
1959 
1960   for (const auto &Dep : Opts.ExtraDeps) {
1961     switch (Dep.second) {
1962     case EDK_SanitizeBlacklist:
1963       // Sanitizer blacklist arguments are generated from LanguageOptions.
1964       continue;
1965     case EDK_ModuleFile:
1966       // Module file arguments are generated from FrontendOptions and
1967       // HeaderSearchOptions.
1968       continue;
1969     case EDK_ProfileList:
1970       // Profile list arguments are generated from LanguageOptions via the
1971       // marshalling infrastructure.
1972       continue;
1973     case EDK_DepFileEntry:
1974       GenerateArg(Args, OPT_fdepfile_entry, Dep.first, SA);
1975       break;
1976     }
1977   }
1978 }
1979 
1980 static bool ParseDependencyOutputArgs(DependencyOutputOptions &Opts,
1981                                       ArgList &Args, DiagnosticsEngine &Diags,
1982                                       frontend::ActionKind Action,
1983                                       bool ShowLineMarkers) {
1984   unsigned NumErrorsBefore = Diags.getNumErrors();
1985   bool Success = true;
1986 
1987   DependencyOutputOptions &DependencyOutputOpts = Opts;
1988 #define DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING(                             \
1989     PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,        \
1990     HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
1991     DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER,     \
1992     MERGER, EXTRACTOR, TABLE_INDEX)                                            \
1993   PARSE_OPTION_WITH_MARSHALLING(Args, Diags, Success, ID, FLAGS, PARAM,        \
1994                                 SHOULD_PARSE, KEYPATH, DEFAULT_VALUE,          \
1995                                 IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER,      \
1996                                 MERGER, TABLE_INDEX)
1997 #include "clang/Driver/Options.inc"
1998 #undef DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING
1999 
2000   if (Args.hasArg(OPT_show_includes)) {
2001     // Writing both /showIncludes and preprocessor output to stdout
2002     // would produce interleaved output, so use stderr for /showIncludes.
2003     // This behaves the same as cl.exe, when /E, /EP or /P are passed.
2004     if (Action == frontend::PrintPreprocessedInput || !ShowLineMarkers)
2005       Opts.ShowIncludesDest = ShowIncludesDestination::Stderr;
2006     else
2007       Opts.ShowIncludesDest = ShowIncludesDestination::Stdout;
2008   } else {
2009     Opts.ShowIncludesDest = ShowIncludesDestination::None;
2010   }
2011 
2012   // Add sanitizer blacklists as extra dependencies.
2013   // They won't be discovered by the regular preprocessor, so
2014   // we let make / ninja to know about this implicit dependency.
2015   if (!Args.hasArg(OPT_fno_sanitize_blacklist)) {
2016     for (const auto *A : Args.filtered(OPT_fsanitize_blacklist)) {
2017       StringRef Val = A->getValue();
2018       if (Val.find('=') == StringRef::npos)
2019         Opts.ExtraDeps.emplace_back(std::string(Val), EDK_SanitizeBlacklist);
2020     }
2021     if (Opts.IncludeSystemHeaders) {
2022       for (const auto *A : Args.filtered(OPT_fsanitize_system_blacklist)) {
2023         StringRef Val = A->getValue();
2024         if (Val.find('=') == StringRef::npos)
2025           Opts.ExtraDeps.emplace_back(std::string(Val), EDK_SanitizeBlacklist);
2026       }
2027     }
2028   }
2029 
2030   // -fprofile-list= dependencies.
2031   for (const auto &Filename : Args.getAllArgValues(OPT_fprofile_list_EQ))
2032     Opts.ExtraDeps.emplace_back(Filename, EDK_ProfileList);
2033 
2034   // Propagate the extra dependencies.
2035   for (const auto *A : Args.filtered(OPT_fdepfile_entry))
2036     Opts.ExtraDeps.emplace_back(A->getValue(), EDK_DepFileEntry);
2037 
2038   // Only the -fmodule-file=<file> form.
2039   for (const auto *A : Args.filtered(OPT_fmodule_file)) {
2040     StringRef Val = A->getValue();
2041     if (Val.find('=') == StringRef::npos)
2042       Opts.ExtraDeps.emplace_back(std::string(Val), EDK_ModuleFile);
2043   }
2044 
2045   return Success && Diags.getNumErrors() == NumErrorsBefore;
2046 }
2047 
2048 static bool parseShowColorsArgs(const ArgList &Args, bool DefaultColor) {
2049   // Color diagnostics default to auto ("on" if terminal supports) in the driver
2050   // but default to off in cc1, needing an explicit OPT_fdiagnostics_color.
2051   // Support both clang's -f[no-]color-diagnostics and gcc's
2052   // -f[no-]diagnostics-colors[=never|always|auto].
2053   enum {
2054     Colors_On,
2055     Colors_Off,
2056     Colors_Auto
2057   } ShowColors = DefaultColor ? Colors_Auto : Colors_Off;
2058   for (auto *A : Args) {
2059     const Option &O = A->getOption();
2060     if (O.matches(options::OPT_fcolor_diagnostics) ||
2061         O.matches(options::OPT_fdiagnostics_color)) {
2062       ShowColors = Colors_On;
2063     } else if (O.matches(options::OPT_fno_color_diagnostics) ||
2064                O.matches(options::OPT_fno_diagnostics_color)) {
2065       ShowColors = Colors_Off;
2066     } else if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
2067       StringRef Value(A->getValue());
2068       if (Value == "always")
2069         ShowColors = Colors_On;
2070       else if (Value == "never")
2071         ShowColors = Colors_Off;
2072       else if (Value == "auto")
2073         ShowColors = Colors_Auto;
2074     }
2075   }
2076   return ShowColors == Colors_On ||
2077          (ShowColors == Colors_Auto &&
2078           llvm::sys::Process::StandardErrHasColors());
2079 }
2080 
2081 static bool checkVerifyPrefixes(const std::vector<std::string> &VerifyPrefixes,
2082                                 DiagnosticsEngine &Diags) {
2083   bool Success = true;
2084   for (const auto &Prefix : VerifyPrefixes) {
2085     // Every prefix must start with a letter and contain only alphanumeric
2086     // characters, hyphens, and underscores.
2087     auto BadChar = llvm::find_if(Prefix, [](char C) {
2088       return !isAlphanumeric(C) && C != '-' && C != '_';
2089     });
2090     if (BadChar != Prefix.end() || !isLetter(Prefix[0])) {
2091       Success = false;
2092       Diags.Report(diag::err_drv_invalid_value) << "-verify=" << Prefix;
2093       Diags.Report(diag::note_drv_verify_prefix_spelling);
2094     }
2095   }
2096   return Success;
2097 }
2098 
2099 static void GenerateFileSystemArgs(const FileSystemOptions &Opts,
2100                                    SmallVectorImpl<const char *> &Args,
2101                                    CompilerInvocation::StringAllocator SA) {
2102   const FileSystemOptions &FileSystemOpts = Opts;
2103 
2104 #define FILE_SYSTEM_OPTION_WITH_MARSHALLING(                                   \
2105     PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,        \
2106     HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
2107     DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER,     \
2108     MERGER, EXTRACTOR, TABLE_INDEX)                                            \
2109   GENERATE_OPTION_WITH_MARSHALLING(                                            \
2110       Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE,    \
2111       IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
2112 #include "clang/Driver/Options.inc"
2113 #undef FILE_SYSTEM_OPTION_WITH_MARSHALLING
2114 }
2115 
2116 static bool ParseFileSystemArgs(FileSystemOptions &Opts, const ArgList &Args,
2117                                 DiagnosticsEngine &Diags) {
2118   FileSystemOptions &FileSystemOpts = Opts;
2119   bool Success = true;
2120 
2121 #define FILE_SYSTEM_OPTION_WITH_MARSHALLING(                                   \
2122     PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,        \
2123     HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
2124     DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER,     \
2125     MERGER, EXTRACTOR, TABLE_INDEX)                                            \
2126   PARSE_OPTION_WITH_MARSHALLING(Args, Diags, Success, ID, FLAGS, PARAM,        \
2127                                 SHOULD_PARSE, KEYPATH, DEFAULT_VALUE,          \
2128                                 IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER,      \
2129                                 MERGER, TABLE_INDEX)
2130 #include "clang/Driver/Options.inc"
2131 #undef FILE_SYSTEM_OPTION_WITH_MARSHALLING
2132 
2133   return Success;
2134 }
2135 
2136 static void GenerateMigratorArgs(const MigratorOptions &Opts,
2137                                  SmallVectorImpl<const char *> &Args,
2138                                  CompilerInvocation::StringAllocator SA) {
2139   const MigratorOptions &MigratorOpts = Opts;
2140 
2141 #define MIGRATOR_OPTION_WITH_MARSHALLING(                                      \
2142     PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,        \
2143     HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
2144     DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER,     \
2145     MERGER, EXTRACTOR, TABLE_INDEX)                                            \
2146   GENERATE_OPTION_WITH_MARSHALLING(                                            \
2147       Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE,    \
2148       IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
2149 #include "clang/Driver/Options.inc"
2150 #undef MIGRATOR_OPTION_WITH_MARSHALLING
2151 }
2152 
2153 static bool ParseMigratorArgs(MigratorOptions &Opts, const ArgList &Args,
2154                               DiagnosticsEngine &Diags) {
2155   MigratorOptions &MigratorOpts = Opts;
2156   bool Success = true;
2157 
2158 #define MIGRATOR_OPTION_WITH_MARSHALLING(                                      \
2159     PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,        \
2160     HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
2161     DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER,     \
2162     MERGER, EXTRACTOR, TABLE_INDEX)                                            \
2163   PARSE_OPTION_WITH_MARSHALLING(Args, Diags, Success, ID, FLAGS, PARAM,        \
2164                                 SHOULD_PARSE, KEYPATH, DEFAULT_VALUE,          \
2165                                 IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER,      \
2166                                 MERGER, TABLE_INDEX)
2167 #include "clang/Driver/Options.inc"
2168 #undef MIGRATOR_OPTION_WITH_MARSHALLING
2169 
2170   return Success;
2171 }
2172 
2173 void CompilerInvocation::GenerateDiagnosticArgs(
2174     const DiagnosticOptions &Opts, SmallVectorImpl<const char *> &Args,
2175     StringAllocator SA, bool DefaultDiagColor) {
2176   const DiagnosticOptions *DiagnosticOpts = &Opts;
2177 #define DIAG_OPTION_WITH_MARSHALLING(                                          \
2178     PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,        \
2179     HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
2180     DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER,     \
2181     MERGER, EXTRACTOR, TABLE_INDEX)                                            \
2182   GENERATE_OPTION_WITH_MARSHALLING(                                            \
2183       Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE,    \
2184       IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
2185 #include "clang/Driver/Options.inc"
2186 #undef DIAG_OPTION_WITH_MARSHALLING
2187 
2188   if (!Opts.DiagnosticSerializationFile.empty())
2189     GenerateArg(Args, OPT_diagnostic_serialized_file,
2190                 Opts.DiagnosticSerializationFile, SA);
2191 
2192   if (Opts.ShowColors)
2193     GenerateArg(Args, OPT_fcolor_diagnostics, SA);
2194 
2195   if (Opts.VerifyDiagnostics &&
2196       llvm::is_contained(Opts.VerifyPrefixes, "expected"))
2197     GenerateArg(Args, OPT_verify, SA);
2198 
2199   for (const auto &Prefix : Opts.VerifyPrefixes)
2200     if (Prefix != "expected")
2201       GenerateArg(Args, OPT_verify_EQ, Prefix, SA);
2202 
2203   DiagnosticLevelMask VIU = Opts.getVerifyIgnoreUnexpected();
2204   if (VIU == DiagnosticLevelMask::None) {
2205     // This is the default, don't generate anything.
2206   } else if (VIU == DiagnosticLevelMask::All) {
2207     GenerateArg(Args, OPT_verify_ignore_unexpected, SA);
2208   } else {
2209     if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Note) != 0)
2210       GenerateArg(Args, OPT_verify_ignore_unexpected_EQ, "note", SA);
2211     if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Remark) != 0)
2212       GenerateArg(Args, OPT_verify_ignore_unexpected_EQ, "remark", SA);
2213     if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Warning) != 0)
2214       GenerateArg(Args, OPT_verify_ignore_unexpected_EQ, "warning", SA);
2215     if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Error) != 0)
2216       GenerateArg(Args, OPT_verify_ignore_unexpected_EQ, "error", SA);
2217   }
2218 
2219   for (const auto &Warning : Opts.Warnings) {
2220     // This option is automatically generated from UndefPrefixes.
2221     if (Warning == "undef-prefix")
2222       continue;
2223     Args.push_back(SA(StringRef("-W") + Warning));
2224   }
2225 
2226   for (const auto &Remark : Opts.Remarks) {
2227     // These arguments are generated from OptimizationRemark fields of
2228     // CodeGenOptions.
2229     StringRef IgnoredRemarks[] = {"pass",          "no-pass",
2230                                   "pass-analysis", "no-pass-analysis",
2231                                   "pass-missed",   "no-pass-missed"};
2232     if (llvm::is_contained(IgnoredRemarks, Remark))
2233       continue;
2234 
2235     Args.push_back(SA(StringRef("-R") + Remark));
2236   }
2237 }
2238 
2239 bool clang::ParseDiagnosticArgs(DiagnosticOptions &Opts, ArgList &Args,
2240                                 DiagnosticsEngine *Diags,
2241                                 bool DefaultDiagColor) {
2242   Optional<DiagnosticsEngine> IgnoringDiags;
2243   if (!Diags) {
2244     IgnoringDiags.emplace(new DiagnosticIDs(), new DiagnosticOptions(),
2245                           new IgnoringDiagConsumer());
2246     Diags = &*IgnoringDiags;
2247   }
2248 
2249   // The key paths of diagnostic options defined in Options.td start with
2250   // "DiagnosticOpts->". Let's provide the expected variable name and type.
2251   DiagnosticOptions *DiagnosticOpts = &Opts;
2252   bool Success = true;
2253 
2254 #define DIAG_OPTION_WITH_MARSHALLING(                                          \
2255     PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,        \
2256     HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
2257     DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER,     \
2258     MERGER, EXTRACTOR, TABLE_INDEX)                                            \
2259   PARSE_OPTION_WITH_MARSHALLING(Args, *Diags, Success, ID, FLAGS, PARAM,       \
2260                                 SHOULD_PARSE, KEYPATH, DEFAULT_VALUE,          \
2261                                 IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER,      \
2262                                 MERGER, TABLE_INDEX)
2263 #include "clang/Driver/Options.inc"
2264 #undef DIAG_OPTION_WITH_MARSHALLING
2265 
2266   llvm::sys::Process::UseANSIEscapeCodes(Opts.UseANSIEscapeCodes);
2267 
2268   if (Arg *A =
2269           Args.getLastArg(OPT_diagnostic_serialized_file, OPT__serialize_diags))
2270     Opts.DiagnosticSerializationFile = A->getValue();
2271   Opts.ShowColors = parseShowColorsArgs(Args, DefaultDiagColor);
2272 
2273   Opts.VerifyDiagnostics = Args.hasArg(OPT_verify) || Args.hasArg(OPT_verify_EQ);
2274   Opts.VerifyPrefixes = Args.getAllArgValues(OPT_verify_EQ);
2275   if (Args.hasArg(OPT_verify))
2276     Opts.VerifyPrefixes.push_back("expected");
2277   // Keep VerifyPrefixes in its original order for the sake of diagnostics, and
2278   // then sort it to prepare for fast lookup using std::binary_search.
2279   if (!checkVerifyPrefixes(Opts.VerifyPrefixes, *Diags)) {
2280     Opts.VerifyDiagnostics = false;
2281     Success = false;
2282   }
2283   else
2284     llvm::sort(Opts.VerifyPrefixes);
2285   DiagnosticLevelMask DiagMask = DiagnosticLevelMask::None;
2286   Success &= parseDiagnosticLevelMask("-verify-ignore-unexpected=",
2287     Args.getAllArgValues(OPT_verify_ignore_unexpected_EQ),
2288     *Diags, DiagMask);
2289   if (Args.hasArg(OPT_verify_ignore_unexpected))
2290     DiagMask = DiagnosticLevelMask::All;
2291   Opts.setVerifyIgnoreUnexpected(DiagMask);
2292   if (Opts.TabStop == 0 || Opts.TabStop > DiagnosticOptions::MaxTabStop) {
2293     Opts.TabStop = DiagnosticOptions::DefaultTabStop;
2294     Diags->Report(diag::warn_ignoring_ftabstop_value)
2295         << Opts.TabStop << DiagnosticOptions::DefaultTabStop;
2296   }
2297 
2298   addDiagnosticArgs(Args, OPT_W_Group, OPT_W_value_Group, Opts.Warnings);
2299   addDiagnosticArgs(Args, OPT_R_Group, OPT_R_value_Group, Opts.Remarks);
2300 
2301   return Success;
2302 }
2303 
2304 /// Parse the argument to the -ftest-module-file-extension
2305 /// command-line argument.
2306 ///
2307 /// \returns true on error, false on success.
2308 static bool parseTestModuleFileExtensionArg(StringRef Arg,
2309                                             std::string &BlockName,
2310                                             unsigned &MajorVersion,
2311                                             unsigned &MinorVersion,
2312                                             bool &Hashed,
2313                                             std::string &UserInfo) {
2314   SmallVector<StringRef, 5> Args;
2315   Arg.split(Args, ':', 5);
2316   if (Args.size() < 5)
2317     return true;
2318 
2319   BlockName = std::string(Args[0]);
2320   if (Args[1].getAsInteger(10, MajorVersion)) return true;
2321   if (Args[2].getAsInteger(10, MinorVersion)) return true;
2322   if (Args[3].getAsInteger(2, Hashed)) return true;
2323   if (Args.size() > 4)
2324     UserInfo = std::string(Args[4]);
2325   return false;
2326 }
2327 
2328 /// Return a table that associates command line option specifiers with the
2329 /// frontend action. Note: The pair {frontend::PluginAction, OPT_plugin} is
2330 /// intentionally missing, as this case is handled separately from other
2331 /// frontend options.
2332 static const auto &getFrontendActionTable() {
2333   static const std::pair<frontend::ActionKind, unsigned> Table[] = {
2334       {frontend::ASTDeclList, OPT_ast_list},
2335 
2336       {frontend::ASTDump, OPT_ast_dump_all_EQ},
2337       {frontend::ASTDump, OPT_ast_dump_all},
2338       {frontend::ASTDump, OPT_ast_dump_EQ},
2339       {frontend::ASTDump, OPT_ast_dump},
2340       {frontend::ASTDump, OPT_ast_dump_lookups},
2341       {frontend::ASTDump, OPT_ast_dump_decl_types},
2342 
2343       {frontend::ASTPrint, OPT_ast_print},
2344       {frontend::ASTView, OPT_ast_view},
2345       {frontend::DumpCompilerOptions, OPT_compiler_options_dump},
2346       {frontend::DumpRawTokens, OPT_dump_raw_tokens},
2347       {frontend::DumpTokens, OPT_dump_tokens},
2348       {frontend::EmitAssembly, OPT_S},
2349       {frontend::EmitBC, OPT_emit_llvm_bc},
2350       {frontend::EmitHTML, OPT_emit_html},
2351       {frontend::EmitLLVM, OPT_emit_llvm},
2352       {frontend::EmitLLVMOnly, OPT_emit_llvm_only},
2353       {frontend::EmitCodeGenOnly, OPT_emit_codegen_only},
2354       {frontend::EmitCodeGenOnly, OPT_emit_codegen_only},
2355       {frontend::EmitObj, OPT_emit_obj},
2356 
2357       {frontend::FixIt, OPT_fixit_EQ},
2358       {frontend::FixIt, OPT_fixit},
2359 
2360       {frontend::GenerateModule, OPT_emit_module},
2361       {frontend::GenerateModuleInterface, OPT_emit_module_interface},
2362       {frontend::GenerateHeaderModule, OPT_emit_header_module},
2363       {frontend::GeneratePCH, OPT_emit_pch},
2364       {frontend::GenerateInterfaceStubs, OPT_emit_interface_stubs},
2365       {frontend::InitOnly, OPT_init_only},
2366       {frontend::ParseSyntaxOnly, OPT_fsyntax_only},
2367       {frontend::ModuleFileInfo, OPT_module_file_info},
2368       {frontend::VerifyPCH, OPT_verify_pch},
2369       {frontend::PrintPreamble, OPT_print_preamble},
2370       {frontend::PrintPreprocessedInput, OPT_E},
2371       {frontend::TemplightDump, OPT_templight_dump},
2372       {frontend::RewriteMacros, OPT_rewrite_macros},
2373       {frontend::RewriteObjC, OPT_rewrite_objc},
2374       {frontend::RewriteTest, OPT_rewrite_test},
2375       {frontend::RunAnalysis, OPT_analyze},
2376       {frontend::MigrateSource, OPT_migrate},
2377       {frontend::RunPreprocessorOnly, OPT_Eonly},
2378       {frontend::PrintDependencyDirectivesSourceMinimizerOutput,
2379           OPT_print_dependency_directives_minimized_source},
2380   };
2381 
2382   return Table;
2383 }
2384 
2385 /// Maps command line option to frontend action.
2386 static Optional<frontend::ActionKind> getFrontendAction(OptSpecifier &Opt) {
2387   for (const auto &ActionOpt : getFrontendActionTable())
2388     if (ActionOpt.second == Opt.getID())
2389       return ActionOpt.first;
2390 
2391   return None;
2392 }
2393 
2394 /// Maps frontend action to command line option.
2395 static Optional<OptSpecifier>
2396 getProgramActionOpt(frontend::ActionKind ProgramAction) {
2397   for (const auto &ActionOpt : getFrontendActionTable())
2398     if (ActionOpt.first == ProgramAction)
2399       return OptSpecifier(ActionOpt.second);
2400 
2401   return None;
2402 }
2403 
2404 static void GenerateFrontendArgs(const FrontendOptions &Opts,
2405                                  SmallVectorImpl<const char *> &Args,
2406                                  CompilerInvocation::StringAllocator SA,
2407                                  bool IsHeader) {
2408   const FrontendOptions &FrontendOpts = Opts;
2409 #define FRONTEND_OPTION_WITH_MARSHALLING(                                      \
2410     PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,        \
2411     HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
2412     DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER,     \
2413     MERGER, EXTRACTOR, TABLE_INDEX)                                            \
2414   GENERATE_OPTION_WITH_MARSHALLING(                                            \
2415       Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE,    \
2416       IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
2417 #include "clang/Driver/Options.inc"
2418 #undef FRONTEND_OPTION_WITH_MARSHALLING
2419 
2420   Optional<OptSpecifier> ProgramActionOpt =
2421       getProgramActionOpt(Opts.ProgramAction);
2422 
2423   // Generating a simple flag covers most frontend actions.
2424   std::function<void()> GenerateProgramAction = [&]() {
2425     GenerateArg(Args, *ProgramActionOpt, SA);
2426   };
2427 
2428   if (!ProgramActionOpt) {
2429     // PluginAction is the only program action handled separately.
2430     assert(Opts.ProgramAction == frontend::PluginAction &&
2431            "Frontend action without option.");
2432     GenerateProgramAction = [&]() {
2433       GenerateArg(Args, OPT_plugin, Opts.ActionName, SA);
2434     };
2435   }
2436 
2437   // FIXME: Simplify the complex 'AST dump' command line.
2438   if (Opts.ProgramAction == frontend::ASTDump) {
2439     GenerateProgramAction = [&]() {
2440       // ASTDumpLookups, ASTDumpDeclTypes and ASTDumpFilter are generated via
2441       // marshalling infrastructure.
2442 
2443       if (Opts.ASTDumpFormat != ADOF_Default) {
2444         StringRef Format;
2445         switch (Opts.ASTDumpFormat) {
2446         case ADOF_Default:
2447           llvm_unreachable("Default AST dump format.");
2448         case ADOF_JSON:
2449           Format = "json";
2450           break;
2451         }
2452 
2453         if (Opts.ASTDumpAll)
2454           GenerateArg(Args, OPT_ast_dump_all_EQ, Format, SA);
2455         if (Opts.ASTDumpDecls)
2456           GenerateArg(Args, OPT_ast_dump_EQ, Format, SA);
2457       } else {
2458         if (Opts.ASTDumpAll)
2459           GenerateArg(Args, OPT_ast_dump_all, SA);
2460         if (Opts.ASTDumpDecls)
2461           GenerateArg(Args, OPT_ast_dump, SA);
2462       }
2463     };
2464   }
2465 
2466   if (Opts.ProgramAction == frontend::FixIt && !Opts.FixItSuffix.empty()) {
2467     GenerateProgramAction = [&]() {
2468       GenerateArg(Args, OPT_fixit_EQ, Opts.FixItSuffix, SA);
2469     };
2470   }
2471 
2472   GenerateProgramAction();
2473 
2474   for (const auto &PluginArgs : Opts.PluginArgs)
2475     for (const auto &PluginArg : PluginArgs.second)
2476       GenerateArg(Args, OPT_plugin_arg, PluginArgs.first + PluginArg, SA);
2477 
2478   for (const auto &Ext : Opts.ModuleFileExtensions)
2479     if (auto *TestExt = dyn_cast_or_null<TestModuleFileExtension>(Ext.get()))
2480       GenerateArg(Args, OPT_ftest_module_file_extension_EQ, TestExt->str(), SA);
2481 
2482   if (!Opts.CodeCompletionAt.FileName.empty())
2483     GenerateArg(Args, OPT_code_completion_at, Opts.CodeCompletionAt.ToString(),
2484                 SA);
2485 
2486   for (const auto &Plugin : Opts.Plugins)
2487     GenerateArg(Args, OPT_load, Plugin, SA);
2488 
2489   // ASTDumpDecls and ASTDumpAll already handled with ProgramAction.
2490 
2491   for (const auto &ModuleFile : Opts.ModuleFiles)
2492     GenerateArg(Args, OPT_fmodule_file, ModuleFile, SA);
2493 
2494   if (Opts.AuxTargetCPU.hasValue())
2495     GenerateArg(Args, OPT_aux_target_cpu, *Opts.AuxTargetCPU, SA);
2496 
2497   if (Opts.AuxTargetFeatures.hasValue())
2498     for (const auto &Feature : *Opts.AuxTargetFeatures)
2499       GenerateArg(Args, OPT_aux_target_feature, Feature, SA);
2500 
2501   {
2502     StringRef Preprocessed = Opts.DashX.isPreprocessed() ? "-cpp-output" : "";
2503     StringRef ModuleMap =
2504         Opts.DashX.getFormat() == InputKind::ModuleMap ? "-module-map" : "";
2505     StringRef Header = IsHeader ? "-header" : "";
2506 
2507     StringRef Lang;
2508     switch (Opts.DashX.getLanguage()) {
2509     case Language::C:
2510       Lang = "c";
2511       break;
2512     case Language::OpenCL:
2513       Lang = "cl";
2514       break;
2515     case Language::OpenCLCXX:
2516       Lang = "clcpp";
2517       break;
2518     case Language::CUDA:
2519       Lang = "cuda";
2520       break;
2521     case Language::HIP:
2522       Lang = "hip";
2523       break;
2524     case Language::CXX:
2525       Lang = "c++";
2526       break;
2527     case Language::ObjC:
2528       Lang = "objective-c";
2529       break;
2530     case Language::ObjCXX:
2531       Lang = "objective-c++";
2532       break;
2533     case Language::RenderScript:
2534       Lang = "renderscript";
2535       break;
2536     case Language::Asm:
2537       Lang = "assembler-with-cpp";
2538       break;
2539     case Language::Unknown:
2540       assert(Opts.DashX.getFormat() == InputKind::Precompiled &&
2541              "Generating -x argument for unknown language (not precompiled).");
2542       Lang = "ast";
2543       break;
2544     case Language::LLVM_IR:
2545       Lang = "ir";
2546       break;
2547     }
2548 
2549     GenerateArg(Args, OPT_x, Lang + Header + ModuleMap + Preprocessed, SA);
2550   }
2551 
2552   // OPT_INPUT has a unique class, generate it directly.
2553   for (const auto &Input : Opts.Inputs)
2554     Args.push_back(SA(Input.getFile()));
2555 }
2556 
2557 static bool ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args,
2558                               DiagnosticsEngine &Diags, bool &IsHeaderFile) {
2559   FrontendOptions &FrontendOpts = Opts;
2560   bool Success = true;
2561   unsigned NumErrorsBefore = Diags.getNumErrors();
2562 #define FRONTEND_OPTION_WITH_MARSHALLING(                                      \
2563     PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,        \
2564     HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
2565     DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER,     \
2566     MERGER, EXTRACTOR, TABLE_INDEX)                                            \
2567   PARSE_OPTION_WITH_MARSHALLING(Args, Diags, Success, ID, FLAGS, PARAM,        \
2568                                 SHOULD_PARSE, KEYPATH, DEFAULT_VALUE,          \
2569                                 IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER,      \
2570                                 MERGER, TABLE_INDEX)
2571 #include "clang/Driver/Options.inc"
2572 #undef FRONTEND_OPTION_WITH_MARSHALLING
2573 
2574   Opts.ProgramAction = frontend::ParseSyntaxOnly;
2575   if (const Arg *A = Args.getLastArg(OPT_Action_Group)) {
2576     OptSpecifier Opt = OptSpecifier(A->getOption().getID());
2577     Optional<frontend::ActionKind> ProgramAction = getFrontendAction(Opt);
2578     assert(ProgramAction && "Option specifier not in Action_Group.");
2579 
2580     if (ProgramAction == frontend::ASTDump &&
2581         (Opt == OPT_ast_dump_all_EQ || Opt == OPT_ast_dump_EQ)) {
2582       unsigned Val = llvm::StringSwitch<unsigned>(A->getValue())
2583                          .CaseLower("default", ADOF_Default)
2584                          .CaseLower("json", ADOF_JSON)
2585                          .Default(std::numeric_limits<unsigned>::max());
2586 
2587       if (Val != std::numeric_limits<unsigned>::max())
2588         Opts.ASTDumpFormat = static_cast<ASTDumpOutputFormat>(Val);
2589       else {
2590         Diags.Report(diag::err_drv_invalid_value)
2591             << A->getAsString(Args) << A->getValue();
2592         Opts.ASTDumpFormat = ADOF_Default;
2593       }
2594     }
2595 
2596     if (ProgramAction == frontend::FixIt && Opt == OPT_fixit_EQ)
2597       Opts.FixItSuffix = A->getValue();
2598 
2599     if (ProgramAction == frontend::GenerateInterfaceStubs) {
2600       StringRef ArgStr =
2601           Args.hasArg(OPT_interface_stub_version_EQ)
2602               ? Args.getLastArgValue(OPT_interface_stub_version_EQ)
2603               : "experimental-ifs-v2";
2604       if (ArgStr == "experimental-yaml-elf-v1" ||
2605           ArgStr == "experimental-ifs-v1" ||
2606           ArgStr == "experimental-tapi-elf-v1") {
2607         std::string ErrorMessage =
2608             "Invalid interface stub format: " + ArgStr.str() +
2609             " is deprecated.";
2610         Diags.Report(diag::err_drv_invalid_value)
2611             << "Must specify a valid interface stub format type, ie: "
2612                "-interface-stub-version=experimental-ifs-v2"
2613             << ErrorMessage;
2614         ProgramAction = frontend::ParseSyntaxOnly;
2615       } else if (!ArgStr.startswith("experimental-ifs-")) {
2616         std::string ErrorMessage =
2617             "Invalid interface stub format: " + ArgStr.str() + ".";
2618         Diags.Report(diag::err_drv_invalid_value)
2619             << "Must specify a valid interface stub format type, ie: "
2620                "-interface-stub-version=experimental-ifs-v2"
2621             << ErrorMessage;
2622         ProgramAction = frontend::ParseSyntaxOnly;
2623       }
2624     }
2625 
2626     Opts.ProgramAction = *ProgramAction;
2627   }
2628 
2629   if (const Arg* A = Args.getLastArg(OPT_plugin)) {
2630     Opts.Plugins.emplace_back(A->getValue(0));
2631     Opts.ProgramAction = frontend::PluginAction;
2632     Opts.ActionName = A->getValue();
2633   }
2634   for (const auto *AA : Args.filtered(OPT_plugin_arg))
2635     Opts.PluginArgs[AA->getValue(0)].emplace_back(AA->getValue(1));
2636 
2637   for (const std::string &Arg :
2638          Args.getAllArgValues(OPT_ftest_module_file_extension_EQ)) {
2639     std::string BlockName;
2640     unsigned MajorVersion;
2641     unsigned MinorVersion;
2642     bool Hashed;
2643     std::string UserInfo;
2644     if (parseTestModuleFileExtensionArg(Arg, BlockName, MajorVersion,
2645                                         MinorVersion, Hashed, UserInfo)) {
2646       Diags.Report(diag::err_test_module_file_extension_format) << Arg;
2647 
2648       continue;
2649     }
2650 
2651     // Add the testing module file extension.
2652     Opts.ModuleFileExtensions.push_back(
2653         std::make_shared<TestModuleFileExtension>(
2654             BlockName, MajorVersion, MinorVersion, Hashed, UserInfo));
2655   }
2656 
2657   if (const Arg *A = Args.getLastArg(OPT_code_completion_at)) {
2658     Opts.CodeCompletionAt =
2659       ParsedSourceLocation::FromString(A->getValue());
2660     if (Opts.CodeCompletionAt.FileName.empty())
2661       Diags.Report(diag::err_drv_invalid_value)
2662         << A->getAsString(Args) << A->getValue();
2663   }
2664 
2665   Opts.Plugins = Args.getAllArgValues(OPT_load);
2666   Opts.ASTDumpDecls = Args.hasArg(OPT_ast_dump, OPT_ast_dump_EQ);
2667   Opts.ASTDumpAll = Args.hasArg(OPT_ast_dump_all, OPT_ast_dump_all_EQ);
2668   // Only the -fmodule-file=<file> form.
2669   for (const auto *A : Args.filtered(OPT_fmodule_file)) {
2670     StringRef Val = A->getValue();
2671     if (Val.find('=') == StringRef::npos)
2672       Opts.ModuleFiles.push_back(std::string(Val));
2673   }
2674 
2675   if (Opts.ProgramAction != frontend::GenerateModule && Opts.IsSystemModule)
2676     Diags.Report(diag::err_drv_argument_only_allowed_with) << "-fsystem-module"
2677                                                            << "-emit-module";
2678 
2679   if (Args.hasArg(OPT_aux_target_cpu))
2680     Opts.AuxTargetCPU = std::string(Args.getLastArgValue(OPT_aux_target_cpu));
2681   if (Args.hasArg(OPT_aux_target_feature))
2682     Opts.AuxTargetFeatures = Args.getAllArgValues(OPT_aux_target_feature);
2683 
2684   if (Opts.ARCMTAction != FrontendOptions::ARCMT_None &&
2685       Opts.ObjCMTAction != FrontendOptions::ObjCMT_None) {
2686     Diags.Report(diag::err_drv_argument_not_allowed_with)
2687       << "ARC migration" << "ObjC migration";
2688   }
2689 
2690   InputKind DashX(Language::Unknown);
2691   if (const Arg *A = Args.getLastArg(OPT_x)) {
2692     StringRef XValue = A->getValue();
2693 
2694     // Parse suffixes: '<lang>(-header|[-module-map][-cpp-output])'.
2695     // FIXME: Supporting '<lang>-header-cpp-output' would be useful.
2696     bool Preprocessed = XValue.consume_back("-cpp-output");
2697     bool ModuleMap = XValue.consume_back("-module-map");
2698     IsHeaderFile = !Preprocessed && !ModuleMap &&
2699                    XValue != "precompiled-header" &&
2700                    XValue.consume_back("-header");
2701 
2702     // Principal languages.
2703     DashX = llvm::StringSwitch<InputKind>(XValue)
2704                 .Case("c", Language::C)
2705                 .Case("cl", Language::OpenCL)
2706                 .Case("clcpp", Language::OpenCLCXX)
2707                 .Case("cuda", Language::CUDA)
2708                 .Case("hip", Language::HIP)
2709                 .Case("c++", Language::CXX)
2710                 .Case("objective-c", Language::ObjC)
2711                 .Case("objective-c++", Language::ObjCXX)
2712                 .Case("renderscript", Language::RenderScript)
2713                 .Default(Language::Unknown);
2714 
2715     // "objc[++]-cpp-output" is an acceptable synonym for
2716     // "objective-c[++]-cpp-output".
2717     if (DashX.isUnknown() && Preprocessed && !IsHeaderFile && !ModuleMap)
2718       DashX = llvm::StringSwitch<InputKind>(XValue)
2719                   .Case("objc", Language::ObjC)
2720                   .Case("objc++", Language::ObjCXX)
2721                   .Default(Language::Unknown);
2722 
2723     // Some special cases cannot be combined with suffixes.
2724     if (DashX.isUnknown() && !Preprocessed && !ModuleMap && !IsHeaderFile)
2725       DashX = llvm::StringSwitch<InputKind>(XValue)
2726                   .Case("cpp-output", InputKind(Language::C).getPreprocessed())
2727                   .Case("assembler-with-cpp", Language::Asm)
2728                   .Cases("ast", "pcm", "precompiled-header",
2729                          InputKind(Language::Unknown, InputKind::Precompiled))
2730                   .Case("ir", Language::LLVM_IR)
2731                   .Default(Language::Unknown);
2732 
2733     if (DashX.isUnknown())
2734       Diags.Report(diag::err_drv_invalid_value)
2735         << A->getAsString(Args) << A->getValue();
2736 
2737     if (Preprocessed)
2738       DashX = DashX.getPreprocessed();
2739     if (ModuleMap)
2740       DashX = DashX.withFormat(InputKind::ModuleMap);
2741   }
2742 
2743   // '-' is the default input if none is given.
2744   std::vector<std::string> Inputs = Args.getAllArgValues(OPT_INPUT);
2745   Opts.Inputs.clear();
2746   if (Inputs.empty())
2747     Inputs.push_back("-");
2748   for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
2749     InputKind IK = DashX;
2750     if (IK.isUnknown()) {
2751       IK = FrontendOptions::getInputKindForExtension(
2752         StringRef(Inputs[i]).rsplit('.').second);
2753       // FIXME: Warn on this?
2754       if (IK.isUnknown())
2755         IK = Language::C;
2756       // FIXME: Remove this hack.
2757       if (i == 0)
2758         DashX = IK;
2759     }
2760 
2761     bool IsSystem = false;
2762 
2763     // The -emit-module action implicitly takes a module map.
2764     if (Opts.ProgramAction == frontend::GenerateModule &&
2765         IK.getFormat() == InputKind::Source) {
2766       IK = IK.withFormat(InputKind::ModuleMap);
2767       IsSystem = Opts.IsSystemModule;
2768     }
2769 
2770     Opts.Inputs.emplace_back(std::move(Inputs[i]), IK, IsSystem);
2771   }
2772 
2773   Opts.DashX = DashX;
2774 
2775   return Diags.getNumErrors() == NumErrorsBefore;
2776 }
2777 
2778 std::string CompilerInvocation::GetResourcesPath(const char *Argv0,
2779                                                  void *MainAddr) {
2780   std::string ClangExecutable =
2781       llvm::sys::fs::getMainExecutable(Argv0, MainAddr);
2782   return Driver::GetResourcesPath(ClangExecutable, CLANG_RESOURCE_DIR);
2783 }
2784 
2785 static void GenerateHeaderSearchArgs(HeaderSearchOptions &Opts,
2786                                      SmallVectorImpl<const char *> &Args,
2787                                      CompilerInvocation::StringAllocator SA) {
2788   const HeaderSearchOptions *HeaderSearchOpts = &Opts;
2789 #define HEADER_SEARCH_OPTION_WITH_MARSHALLING(                                 \
2790     PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,        \
2791     HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
2792     DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER,     \
2793     MERGER, EXTRACTOR, TABLE_INDEX)                                            \
2794   GENERATE_OPTION_WITH_MARSHALLING(                                            \
2795       Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE,    \
2796       IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
2797 #include "clang/Driver/Options.inc"
2798 #undef HEADER_SEARCH_OPTION_WITH_MARSHALLING
2799 
2800   if (Opts.UseLibcxx)
2801     GenerateArg(Args, OPT_stdlib_EQ, "libc++", SA);
2802 
2803   if (!Opts.ModuleCachePath.empty())
2804     GenerateArg(Args, OPT_fmodules_cache_path, Opts.ModuleCachePath, SA);
2805 
2806   for (const auto &File : Opts.PrebuiltModuleFiles)
2807     GenerateArg(Args, OPT_fmodule_file, File.first + "=" + File.second, SA);
2808 
2809   for (const auto &Path : Opts.PrebuiltModulePaths)
2810     GenerateArg(Args, OPT_fprebuilt_module_path, Path, SA);
2811 
2812   for (const auto &Macro : Opts.ModulesIgnoreMacros)
2813     GenerateArg(Args, OPT_fmodules_ignore_macro, Macro.val(), SA);
2814 
2815   auto Matches = [](const HeaderSearchOptions::Entry &Entry,
2816                     llvm::ArrayRef<frontend::IncludeDirGroup> Groups,
2817                     llvm::Optional<bool> IsFramework,
2818                     llvm::Optional<bool> IgnoreSysRoot) {
2819     return llvm::find(Groups, Entry.Group) != Groups.end() &&
2820            (!IsFramework || (Entry.IsFramework == *IsFramework)) &&
2821            (!IgnoreSysRoot || (Entry.IgnoreSysRoot == *IgnoreSysRoot));
2822   };
2823 
2824   auto It = Opts.UserEntries.begin();
2825   auto End = Opts.UserEntries.end();
2826 
2827   // Add -I..., -F..., and -index-header-map options in order.
2828   for (; It < End &&
2829          Matches(*It, {frontend::IndexHeaderMap, frontend::Angled}, None, true);
2830        ++It) {
2831     OptSpecifier Opt = [It, Matches]() {
2832       if (Matches(*It, frontend::IndexHeaderMap, true, true))
2833         return OPT_F;
2834       if (Matches(*It, frontend::IndexHeaderMap, false, true))
2835         return OPT_I;
2836       if (Matches(*It, frontend::Angled, true, true))
2837         return OPT_F;
2838       if (Matches(*It, frontend::Angled, false, true))
2839         return OPT_I;
2840       llvm_unreachable("Unexpected HeaderSearchOptions::Entry.");
2841     }();
2842 
2843     if (It->Group == frontend::IndexHeaderMap)
2844       GenerateArg(Args, OPT_index_header_map, SA);
2845     GenerateArg(Args, Opt, It->Path, SA);
2846   };
2847 
2848   // Note: some paths that came from "[-iprefix=xx] -iwithprefixbefore=yy" may
2849   // have already been generated as "-I[xx]yy". If that's the case, their
2850   // position on command line was such that this has no semantic impact on
2851   // include paths.
2852   for (; It < End &&
2853          Matches(*It, {frontend::After, frontend::Angled}, false, true);
2854        ++It) {
2855     OptSpecifier Opt =
2856         It->Group == frontend::After ? OPT_iwithprefix : OPT_iwithprefixbefore;
2857     GenerateArg(Args, Opt, It->Path, SA);
2858   }
2859 
2860   // Note: Some paths that came from "-idirafter=xxyy" may have already been
2861   // generated as "-iwithprefix=xxyy". If that's the case, their position on
2862   // command line was such that this has no semantic impact on include paths.
2863   for (; It < End && Matches(*It, {frontend::After}, false, true); ++It)
2864     GenerateArg(Args, OPT_idirafter, It->Path, SA);
2865   for (; It < End && Matches(*It, {frontend::Quoted}, false, true); ++It)
2866     GenerateArg(Args, OPT_iquote, It->Path, SA);
2867   for (; It < End && Matches(*It, {frontend::System}, false, None); ++It)
2868     GenerateArg(Args, It->IgnoreSysRoot ? OPT_isystem : OPT_iwithsysroot,
2869                 It->Path, SA);
2870   for (; It < End && Matches(*It, {frontend::System}, true, true); ++It)
2871     GenerateArg(Args, OPT_iframework, It->Path, SA);
2872   for (; It < End && Matches(*It, {frontend::System}, true, false); ++It)
2873     GenerateArg(Args, OPT_iframeworkwithsysroot, It->Path, SA);
2874 
2875   // Add the paths for the various language specific isystem flags.
2876   for (; It < End && Matches(*It, {frontend::CSystem}, false, true); ++It)
2877     GenerateArg(Args, OPT_c_isystem, It->Path, SA);
2878   for (; It < End && Matches(*It, {frontend::CXXSystem}, false, true); ++It)
2879     GenerateArg(Args, OPT_cxx_isystem, It->Path, SA);
2880   for (; It < End && Matches(*It, {frontend::ObjCSystem}, false, true); ++It)
2881     GenerateArg(Args, OPT_objc_isystem, It->Path, SA);
2882   for (; It < End && Matches(*It, {frontend::ObjCXXSystem}, false, true); ++It)
2883     GenerateArg(Args, OPT_objcxx_isystem, It->Path, SA);
2884 
2885   // Add the internal paths from a driver that detects standard include paths.
2886   // Note: Some paths that came from "-internal-isystem" arguments may have
2887   // already been generated as "-isystem". If that's the case, their position on
2888   // command line was such that this has no semantic impact on include paths.
2889   for (; It < End &&
2890          Matches(*It, {frontend::System, frontend::ExternCSystem}, false, true);
2891        ++It) {
2892     OptSpecifier Opt = It->Group == frontend::System
2893                            ? OPT_internal_isystem
2894                            : OPT_internal_externc_isystem;
2895     GenerateArg(Args, Opt, It->Path, SA);
2896   }
2897 
2898   assert(It == End && "Unhandled HeaderSearchOption::Entry.");
2899 
2900   // Add the path prefixes which are implicitly treated as being system headers.
2901   for (const auto &P : Opts.SystemHeaderPrefixes) {
2902     OptSpecifier Opt = P.IsSystemHeader ? OPT_system_header_prefix
2903                                         : OPT_no_system_header_prefix;
2904     GenerateArg(Args, Opt, P.Prefix, SA);
2905   }
2906 
2907   for (const std::string &F : Opts.VFSOverlayFiles)
2908     GenerateArg(Args, OPT_ivfsoverlay, F, SA);
2909 }
2910 
2911 static bool ParseHeaderSearchArgs(HeaderSearchOptions &Opts, ArgList &Args,
2912                                   DiagnosticsEngine &Diags,
2913                                   const std::string &WorkingDir) {
2914   HeaderSearchOptions *HeaderSearchOpts = &Opts;
2915   bool Success = true;
2916 
2917 #define HEADER_SEARCH_OPTION_WITH_MARSHALLING(                                 \
2918     PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,        \
2919     HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
2920     DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER,     \
2921     MERGER, EXTRACTOR, TABLE_INDEX)                                            \
2922   PARSE_OPTION_WITH_MARSHALLING(Args, Diags, Success, ID, FLAGS, PARAM,        \
2923                                 SHOULD_PARSE, KEYPATH, DEFAULT_VALUE,          \
2924                                 IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER,      \
2925                                 MERGER, TABLE_INDEX)
2926 #include "clang/Driver/Options.inc"
2927 #undef HEADER_SEARCH_OPTION_WITH_MARSHALLING
2928 
2929   if (const Arg *A = Args.getLastArg(OPT_stdlib_EQ))
2930     Opts.UseLibcxx = (strcmp(A->getValue(), "libc++") == 0);
2931 
2932   // Canonicalize -fmodules-cache-path before storing it.
2933   SmallString<128> P(Args.getLastArgValue(OPT_fmodules_cache_path));
2934   if (!(P.empty() || llvm::sys::path::is_absolute(P))) {
2935     if (WorkingDir.empty())
2936       llvm::sys::fs::make_absolute(P);
2937     else
2938       llvm::sys::fs::make_absolute(WorkingDir, P);
2939   }
2940   llvm::sys::path::remove_dots(P);
2941   Opts.ModuleCachePath = std::string(P.str());
2942 
2943   // Only the -fmodule-file=<name>=<file> form.
2944   for (const auto *A : Args.filtered(OPT_fmodule_file)) {
2945     StringRef Val = A->getValue();
2946     if (Val.find('=') != StringRef::npos){
2947       auto Split = Val.split('=');
2948       Opts.PrebuiltModuleFiles.insert(
2949           {std::string(Split.first), std::string(Split.second)});
2950     }
2951   }
2952   for (const auto *A : Args.filtered(OPT_fprebuilt_module_path))
2953     Opts.AddPrebuiltModulePath(A->getValue());
2954 
2955   for (const auto *A : Args.filtered(OPT_fmodules_ignore_macro)) {
2956     StringRef MacroDef = A->getValue();
2957     Opts.ModulesIgnoreMacros.insert(
2958         llvm::CachedHashString(MacroDef.split('=').first));
2959   }
2960 
2961   // Add -I..., -F..., and -index-header-map options in order.
2962   bool IsIndexHeaderMap = false;
2963   bool IsSysrootSpecified =
2964       Args.hasArg(OPT__sysroot_EQ) || Args.hasArg(OPT_isysroot);
2965   for (const auto *A : Args.filtered(OPT_I, OPT_F, OPT_index_header_map)) {
2966     if (A->getOption().matches(OPT_index_header_map)) {
2967       // -index-header-map applies to the next -I or -F.
2968       IsIndexHeaderMap = true;
2969       continue;
2970     }
2971 
2972     frontend::IncludeDirGroup Group =
2973         IsIndexHeaderMap ? frontend::IndexHeaderMap : frontend::Angled;
2974 
2975     bool IsFramework = A->getOption().matches(OPT_F);
2976     std::string Path = A->getValue();
2977 
2978     if (IsSysrootSpecified && !IsFramework && A->getValue()[0] == '=') {
2979       SmallString<32> Buffer;
2980       llvm::sys::path::append(Buffer, Opts.Sysroot,
2981                               llvm::StringRef(A->getValue()).substr(1));
2982       Path = std::string(Buffer.str());
2983     }
2984 
2985     Opts.AddPath(Path, Group, IsFramework,
2986                  /*IgnoreSysroot*/ true);
2987     IsIndexHeaderMap = false;
2988   }
2989 
2990   // Add -iprefix/-iwithprefix/-iwithprefixbefore options.
2991   StringRef Prefix = ""; // FIXME: This isn't the correct default prefix.
2992   for (const auto *A :
2993        Args.filtered(OPT_iprefix, OPT_iwithprefix, OPT_iwithprefixbefore)) {
2994     if (A->getOption().matches(OPT_iprefix))
2995       Prefix = A->getValue();
2996     else if (A->getOption().matches(OPT_iwithprefix))
2997       Opts.AddPath(Prefix.str() + A->getValue(), frontend::After, false, true);
2998     else
2999       Opts.AddPath(Prefix.str() + A->getValue(), frontend::Angled, false, true);
3000   }
3001 
3002   for (const auto *A : Args.filtered(OPT_idirafter))
3003     Opts.AddPath(A->getValue(), frontend::After, false, true);
3004   for (const auto *A : Args.filtered(OPT_iquote))
3005     Opts.AddPath(A->getValue(), frontend::Quoted, false, true);
3006   for (const auto *A : Args.filtered(OPT_isystem, OPT_iwithsysroot))
3007     Opts.AddPath(A->getValue(), frontend::System, false,
3008                  !A->getOption().matches(OPT_iwithsysroot));
3009   for (const auto *A : Args.filtered(OPT_iframework))
3010     Opts.AddPath(A->getValue(), frontend::System, true, true);
3011   for (const auto *A : Args.filtered(OPT_iframeworkwithsysroot))
3012     Opts.AddPath(A->getValue(), frontend::System, /*IsFramework=*/true,
3013                  /*IgnoreSysRoot=*/false);
3014 
3015   // Add the paths for the various language specific isystem flags.
3016   for (const auto *A : Args.filtered(OPT_c_isystem))
3017     Opts.AddPath(A->getValue(), frontend::CSystem, false, true);
3018   for (const auto *A : Args.filtered(OPT_cxx_isystem))
3019     Opts.AddPath(A->getValue(), frontend::CXXSystem, false, true);
3020   for (const auto *A : Args.filtered(OPT_objc_isystem))
3021     Opts.AddPath(A->getValue(), frontend::ObjCSystem, false,true);
3022   for (const auto *A : Args.filtered(OPT_objcxx_isystem))
3023     Opts.AddPath(A->getValue(), frontend::ObjCXXSystem, false, true);
3024 
3025   // Add the internal paths from a driver that detects standard include paths.
3026   for (const auto *A :
3027        Args.filtered(OPT_internal_isystem, OPT_internal_externc_isystem)) {
3028     frontend::IncludeDirGroup Group = frontend::System;
3029     if (A->getOption().matches(OPT_internal_externc_isystem))
3030       Group = frontend::ExternCSystem;
3031     Opts.AddPath(A->getValue(), Group, false, true);
3032   }
3033 
3034   // Add the path prefixes which are implicitly treated as being system headers.
3035   for (const auto *A :
3036        Args.filtered(OPT_system_header_prefix, OPT_no_system_header_prefix))
3037     Opts.AddSystemHeaderPrefix(
3038         A->getValue(), A->getOption().matches(OPT_system_header_prefix));
3039 
3040   for (const auto *A : Args.filtered(OPT_ivfsoverlay))
3041     Opts.AddVFSOverlayFile(A->getValue());
3042 
3043   return Success;
3044 }
3045 
3046 void CompilerInvocation::setLangDefaults(LangOptions &Opts, InputKind IK,
3047                                          const llvm::Triple &T,
3048                                          std::vector<std::string> &Includes,
3049                                          LangStandard::Kind LangStd) {
3050   // Set some properties which depend solely on the input kind; it would be nice
3051   // to move these to the language standard, and have the driver resolve the
3052   // input kind + language standard.
3053   //
3054   // FIXME: Perhaps a better model would be for a single source file to have
3055   // multiple language standards (C / C++ std, ObjC std, OpenCL std, OpenMP std)
3056   // simultaneously active?
3057   if (IK.getLanguage() == Language::Asm) {
3058     Opts.AsmPreprocessor = 1;
3059   } else if (IK.isObjectiveC()) {
3060     Opts.ObjC = 1;
3061   }
3062 
3063   if (LangStd == LangStandard::lang_unspecified) {
3064     // Based on the base language, pick one.
3065     switch (IK.getLanguage()) {
3066     case Language::Unknown:
3067     case Language::LLVM_IR:
3068       llvm_unreachable("Invalid input kind!");
3069     case Language::OpenCL:
3070       LangStd = LangStandard::lang_opencl10;
3071       break;
3072     case Language::OpenCLCXX:
3073       LangStd = LangStandard::lang_openclcpp;
3074       break;
3075     case Language::CUDA:
3076       LangStd = LangStandard::lang_cuda;
3077       break;
3078     case Language::Asm:
3079     case Language::C:
3080 #if defined(CLANG_DEFAULT_STD_C)
3081       LangStd = CLANG_DEFAULT_STD_C;
3082 #else
3083       // The PS4 uses C99 as the default C standard.
3084       if (T.isPS4())
3085         LangStd = LangStandard::lang_gnu99;
3086       else
3087         LangStd = LangStandard::lang_gnu17;
3088 #endif
3089       break;
3090     case Language::ObjC:
3091 #if defined(CLANG_DEFAULT_STD_C)
3092       LangStd = CLANG_DEFAULT_STD_C;
3093 #else
3094       LangStd = LangStandard::lang_gnu11;
3095 #endif
3096       break;
3097     case Language::CXX:
3098     case Language::ObjCXX:
3099 #if defined(CLANG_DEFAULT_STD_CXX)
3100       LangStd = CLANG_DEFAULT_STD_CXX;
3101 #else
3102       LangStd = LangStandard::lang_gnucxx14;
3103 #endif
3104       break;
3105     case Language::RenderScript:
3106       LangStd = LangStandard::lang_c99;
3107       break;
3108     case Language::HIP:
3109       LangStd = LangStandard::lang_hip;
3110       break;
3111     }
3112   }
3113 
3114   const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
3115   Opts.LangStd = LangStd;
3116   Opts.LineComment = Std.hasLineComments();
3117   Opts.C99 = Std.isC99();
3118   Opts.C11 = Std.isC11();
3119   Opts.C17 = Std.isC17();
3120   Opts.C2x = Std.isC2x();
3121   Opts.CPlusPlus = Std.isCPlusPlus();
3122   Opts.CPlusPlus11 = Std.isCPlusPlus11();
3123   Opts.CPlusPlus14 = Std.isCPlusPlus14();
3124   Opts.CPlusPlus17 = Std.isCPlusPlus17();
3125   Opts.CPlusPlus20 = Std.isCPlusPlus20();
3126   Opts.CPlusPlus2b = Std.isCPlusPlus2b();
3127   Opts.GNUMode = Std.isGNUMode();
3128   Opts.GNUCVersion = 0;
3129   Opts.HexFloats = Std.hasHexFloats();
3130   Opts.ImplicitInt = Std.hasImplicitInt();
3131 
3132   Opts.CPlusPlusModules = Opts.CPlusPlus20;
3133 
3134   // Set OpenCL Version.
3135   Opts.OpenCL = Std.isOpenCL();
3136   if (LangStd == LangStandard::lang_opencl10)
3137     Opts.OpenCLVersion = 100;
3138   else if (LangStd == LangStandard::lang_opencl11)
3139     Opts.OpenCLVersion = 110;
3140   else if (LangStd == LangStandard::lang_opencl12)
3141     Opts.OpenCLVersion = 120;
3142   else if (LangStd == LangStandard::lang_opencl20)
3143     Opts.OpenCLVersion = 200;
3144   else if (LangStd == LangStandard::lang_opencl30)
3145     Opts.OpenCLVersion = 300;
3146   else if (LangStd == LangStandard::lang_openclcpp)
3147     Opts.OpenCLCPlusPlusVersion = 100;
3148 
3149   // OpenCL has some additional defaults.
3150   if (Opts.OpenCL) {
3151     Opts.AltiVec = 0;
3152     Opts.ZVector = 0;
3153     Opts.setDefaultFPContractMode(LangOptions::FPM_On);
3154     Opts.OpenCLCPlusPlus = Opts.CPlusPlus;
3155     Opts.OpenCLPipe = Opts.OpenCLCPlusPlus || Opts.OpenCLVersion == 200;
3156     Opts.OpenCLGenericAddressSpace =
3157         Opts.OpenCLCPlusPlus || Opts.OpenCLVersion == 200;
3158 
3159     // Include default header file for OpenCL.
3160     if (Opts.IncludeDefaultHeader) {
3161       if (Opts.DeclareOpenCLBuiltins) {
3162         // Only include base header file for builtin types and constants.
3163         Includes.push_back("opencl-c-base.h");
3164       } else {
3165         Includes.push_back("opencl-c.h");
3166       }
3167     }
3168   }
3169 
3170   Opts.HIP = IK.getLanguage() == Language::HIP;
3171   Opts.CUDA = IK.getLanguage() == Language::CUDA || Opts.HIP;
3172   if (Opts.HIP) {
3173     // HIP toolchain does not support 'Fast' FPOpFusion in backends since it
3174     // fuses multiplication/addition instructions without contract flag from
3175     // device library functions in LLVM bitcode, which causes accuracy loss in
3176     // certain math functions, e.g. tan(-1e20) becomes -0.933 instead of 0.8446.
3177     // For device library functions in bitcode to work, 'Strict' or 'Standard'
3178     // FPOpFusion options in backends is needed. Therefore 'fast-honor-pragmas'
3179     // FP contract option is used to allow fuse across statements in frontend
3180     // whereas respecting contract flag in backend.
3181     Opts.setDefaultFPContractMode(LangOptions::FPM_FastHonorPragmas);
3182   } else if (Opts.CUDA) {
3183     // Allow fuse across statements disregarding pragmas.
3184     Opts.setDefaultFPContractMode(LangOptions::FPM_Fast);
3185   }
3186 
3187   Opts.RenderScript = IK.getLanguage() == Language::RenderScript;
3188 
3189   // OpenCL and C++ both have bool, true, false keywords.
3190   Opts.Bool = Opts.OpenCL || Opts.CPlusPlus;
3191 
3192   // OpenCL has half keyword
3193   Opts.Half = Opts.OpenCL;
3194 }
3195 
3196 /// Check if input file kind and language standard are compatible.
3197 static bool IsInputCompatibleWithStandard(InputKind IK,
3198                                           const LangStandard &S) {
3199   switch (IK.getLanguage()) {
3200   case Language::Unknown:
3201   case Language::LLVM_IR:
3202     llvm_unreachable("should not parse language flags for this input");
3203 
3204   case Language::C:
3205   case Language::ObjC:
3206   case Language::RenderScript:
3207     return S.getLanguage() == Language::C;
3208 
3209   case Language::OpenCL:
3210     return S.getLanguage() == Language::OpenCL ||
3211            S.getLanguage() == Language::OpenCLCXX;
3212 
3213   case Language::OpenCLCXX:
3214     return S.getLanguage() == Language::OpenCLCXX;
3215 
3216   case Language::CXX:
3217   case Language::ObjCXX:
3218     return S.getLanguage() == Language::CXX;
3219 
3220   case Language::CUDA:
3221     // FIXME: What -std= values should be permitted for CUDA compilations?
3222     return S.getLanguage() == Language::CUDA ||
3223            S.getLanguage() == Language::CXX;
3224 
3225   case Language::HIP:
3226     return S.getLanguage() == Language::CXX || S.getLanguage() == Language::HIP;
3227 
3228   case Language::Asm:
3229     // Accept (and ignore) all -std= values.
3230     // FIXME: The -std= value is not ignored; it affects the tokenization
3231     // and preprocessing rules if we're preprocessing this asm input.
3232     return true;
3233   }
3234 
3235   llvm_unreachable("unexpected input language");
3236 }
3237 
3238 /// Get language name for given input kind.
3239 static const StringRef GetInputKindName(InputKind IK) {
3240   switch (IK.getLanguage()) {
3241   case Language::C:
3242     return "C";
3243   case Language::ObjC:
3244     return "Objective-C";
3245   case Language::CXX:
3246     return "C++";
3247   case Language::ObjCXX:
3248     return "Objective-C++";
3249   case Language::OpenCL:
3250     return "OpenCL";
3251   case Language::OpenCLCXX:
3252     return "C++ for OpenCL";
3253   case Language::CUDA:
3254     return "CUDA";
3255   case Language::RenderScript:
3256     return "RenderScript";
3257   case Language::HIP:
3258     return "HIP";
3259 
3260   case Language::Asm:
3261     return "Asm";
3262   case Language::LLVM_IR:
3263     return "LLVM IR";
3264 
3265   case Language::Unknown:
3266     break;
3267   }
3268   llvm_unreachable("unknown input language");
3269 }
3270 
3271 void CompilerInvocation::GenerateLangArgs(const LangOptions &Opts,
3272                                           SmallVectorImpl<const char *> &Args,
3273                                           StringAllocator SA,
3274                                           const llvm::Triple &T) {
3275   OptSpecifier StdOpt;
3276   switch (Opts.LangStd) {
3277   case LangStandard::lang_opencl10:
3278   case LangStandard::lang_opencl11:
3279   case LangStandard::lang_opencl12:
3280   case LangStandard::lang_opencl20:
3281   case LangStandard::lang_opencl30:
3282   case LangStandard::lang_openclcpp:
3283     StdOpt = OPT_cl_std_EQ;
3284     break;
3285   default:
3286     StdOpt = OPT_std_EQ;
3287     break;
3288   }
3289 
3290   auto LangStandard = LangStandard::getLangStandardForKind(Opts.LangStd);
3291   GenerateArg(Args, StdOpt, LangStandard.getName(), SA);
3292 
3293   if (Opts.IncludeDefaultHeader)
3294     GenerateArg(Args, OPT_finclude_default_header, SA);
3295   if (Opts.DeclareOpenCLBuiltins)
3296     GenerateArg(Args, OPT_fdeclare_opencl_builtins, SA);
3297 
3298   const LangOptions *LangOpts = &Opts;
3299 
3300 #define LANG_OPTION_WITH_MARSHALLING(                                          \
3301     PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,        \
3302     HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
3303     DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER,     \
3304     MERGER, EXTRACTOR, TABLE_INDEX)                                            \
3305   GENERATE_OPTION_WITH_MARSHALLING(                                            \
3306       Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE,    \
3307       IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
3308 #include "clang/Driver/Options.inc"
3309 #undef LANG_OPTION_WITH_MARSHALLING
3310 
3311   // The '-fcf-protection=' option is generated by CodeGenOpts generator.
3312 
3313   if (Opts.ObjC) {
3314     GenerateArg(Args, OPT_fobjc_runtime_EQ, Opts.ObjCRuntime.getAsString(), SA);
3315 
3316     if (Opts.GC == LangOptions::GCOnly)
3317       GenerateArg(Args, OPT_fobjc_gc_only, SA);
3318     else if (Opts.GC == LangOptions::HybridGC)
3319       GenerateArg(Args, OPT_fobjc_gc, SA);
3320     else if (Opts.ObjCAutoRefCount == 1)
3321       GenerateArg(Args, OPT_fobjc_arc, SA);
3322 
3323     if (Opts.ObjCWeakRuntime)
3324       GenerateArg(Args, OPT_fobjc_runtime_has_weak, SA);
3325 
3326     if (Opts.ObjCWeak)
3327       GenerateArg(Args, OPT_fobjc_weak, SA);
3328 
3329     if (Opts.ObjCSubscriptingLegacyRuntime)
3330       GenerateArg(Args, OPT_fobjc_subscripting_legacy_runtime, SA);
3331   }
3332 
3333   if (Opts.GNUCVersion != 0) {
3334     unsigned Major = Opts.GNUCVersion / 100 / 100;
3335     unsigned Minor = (Opts.GNUCVersion / 100) % 100;
3336     unsigned Patch = Opts.GNUCVersion % 100;
3337     GenerateArg(Args, OPT_fgnuc_version_EQ,
3338                 Twine(Major) + "." + Twine(Minor) + "." + Twine(Patch), SA);
3339   }
3340 
3341   if (Opts.IgnoreXCOFFVisibility)
3342     GenerateArg(Args, OPT_mignore_xcoff_visibility, SA);
3343 
3344   if (Opts.SignedOverflowBehavior == LangOptions::SOB_Trapping) {
3345     GenerateArg(Args, OPT_ftrapv, SA);
3346     GenerateArg(Args, OPT_ftrapv_handler, Opts.OverflowHandler, SA);
3347   } else if (Opts.SignedOverflowBehavior == LangOptions::SOB_Defined) {
3348     GenerateArg(Args, OPT_fwrapv, SA);
3349   }
3350 
3351   if (Opts.MSCompatibilityVersion != 0) {
3352     unsigned Major = Opts.MSCompatibilityVersion / 10000000;
3353     unsigned Minor = (Opts.MSCompatibilityVersion / 100000) % 100;
3354     unsigned Subminor = Opts.MSCompatibilityVersion % 100000;
3355     GenerateArg(Args, OPT_fms_compatibility_version,
3356                 Twine(Major) + "." + Twine(Minor) + "." + Twine(Subminor), SA);
3357   }
3358 
3359   if ((!Opts.GNUMode && !Opts.MSVCCompat && !Opts.CPlusPlus17) || T.isOSzOS()) {
3360     if (!Opts.Trigraphs)
3361       GenerateArg(Args, OPT_fno_trigraphs, SA);
3362   } else {
3363     if (Opts.Trigraphs)
3364       GenerateArg(Args, OPT_ftrigraphs, SA);
3365   }
3366 
3367   if (Opts.Blocks && !(Opts.OpenCL && Opts.OpenCLVersion == 200))
3368     GenerateArg(Args, OPT_fblocks, SA);
3369 
3370   if (Opts.ConvergentFunctions &&
3371       !(Opts.OpenCL || (Opts.CUDA && Opts.CUDAIsDevice) || Opts.SYCLIsDevice))
3372     GenerateArg(Args, OPT_fconvergent_functions, SA);
3373 
3374   if (Opts.NoBuiltin && !Opts.Freestanding)
3375     GenerateArg(Args, OPT_fno_builtin, SA);
3376 
3377   if (!Opts.NoBuiltin)
3378     for (const auto &Func : Opts.NoBuiltinFuncs)
3379       GenerateArg(Args, OPT_fno_builtin_, Func, SA);
3380 
3381   if (Opts.LongDoubleSize == 128)
3382     GenerateArg(Args, OPT_mlong_double_128, SA);
3383   else if (Opts.LongDoubleSize == 64)
3384     GenerateArg(Args, OPT_mlong_double_64, SA);
3385 
3386   // Not generating '-mrtd', it's just an alias for '-fdefault-calling-conv='.
3387 
3388   // OpenMP was requested via '-fopenmp', not implied by '-fopenmp-simd' or
3389   // '-fopenmp-targets='.
3390   if (Opts.OpenMP && !Opts.OpenMPSimd) {
3391     GenerateArg(Args, OPT_fopenmp, SA);
3392 
3393     if (Opts.OpenMP != 50)
3394       GenerateArg(Args, OPT_fopenmp_version_EQ, Twine(Opts.OpenMP), SA);
3395 
3396     if (!Opts.OpenMPUseTLS)
3397       GenerateArg(Args, OPT_fnoopenmp_use_tls, SA);
3398 
3399     if (Opts.OpenMPIsDevice)
3400       GenerateArg(Args, OPT_fopenmp_is_device, SA);
3401 
3402     if (Opts.OpenMPIRBuilder)
3403       GenerateArg(Args, OPT_fopenmp_enable_irbuilder, SA);
3404   }
3405 
3406   if (Opts.OpenMPSimd) {
3407     GenerateArg(Args, OPT_fopenmp_simd, SA);
3408 
3409     if (Opts.OpenMP != 50)
3410       GenerateArg(Args, OPT_fopenmp_version_EQ, Twine(Opts.OpenMP), SA);
3411   }
3412 
3413   if (Opts.OpenMPCUDANumSMs != 0)
3414     GenerateArg(Args, OPT_fopenmp_cuda_number_of_sm_EQ,
3415                 Twine(Opts.OpenMPCUDANumSMs), SA);
3416 
3417   if (Opts.OpenMPCUDABlocksPerSM != 0)
3418     GenerateArg(Args, OPT_fopenmp_cuda_blocks_per_sm_EQ,
3419                 Twine(Opts.OpenMPCUDABlocksPerSM), SA);
3420 
3421   if (Opts.OpenMPCUDAReductionBufNum != 1024)
3422     GenerateArg(Args, OPT_fopenmp_cuda_teams_reduction_recs_num_EQ,
3423                 Twine(Opts.OpenMPCUDAReductionBufNum), SA);
3424 
3425   if (!Opts.OMPTargetTriples.empty()) {
3426     std::string Targets;
3427     llvm::raw_string_ostream OS(Targets);
3428     llvm::interleave(
3429         Opts.OMPTargetTriples, OS,
3430         [&OS](const llvm::Triple &T) { OS << T.str(); }, ",");
3431     GenerateArg(Args, OPT_fopenmp_targets_EQ, OS.str(), SA);
3432   }
3433 
3434   if (!Opts.OMPHostIRFile.empty())
3435     GenerateArg(Args, OPT_fopenmp_host_ir_file_path, Opts.OMPHostIRFile, SA);
3436 
3437   if (Opts.OpenMPCUDAMode)
3438     GenerateArg(Args, OPT_fopenmp_cuda_mode, SA);
3439 
3440   if (Opts.OpenMPCUDATargetParallel)
3441     GenerateArg(Args, OPT_fopenmp_cuda_parallel_target_regions, SA);
3442 
3443   if (Opts.OpenMPCUDAForceFullRuntime)
3444     GenerateArg(Args, OPT_fopenmp_cuda_force_full_runtime, SA);
3445 
3446   // The arguments used to set Optimize, OptimizeSize and NoInlineDefine are
3447   // generated from CodeGenOptions.
3448 
3449   if (Opts.DefaultFPContractMode == LangOptions::FPM_Fast)
3450     GenerateArg(Args, OPT_ffp_contract, "fast", SA);
3451   else if (Opts.DefaultFPContractMode == LangOptions::FPM_On)
3452     GenerateArg(Args, OPT_ffp_contract, "on", SA);
3453   else if (Opts.DefaultFPContractMode == LangOptions::FPM_Off)
3454     GenerateArg(Args, OPT_ffp_contract, "off", SA);
3455   else if (Opts.DefaultFPContractMode == LangOptions::FPM_FastHonorPragmas)
3456     GenerateArg(Args, OPT_ffp_contract, "fast-honor-pragmas", SA);
3457 
3458   for (StringRef Sanitizer : serializeSanitizerKinds(Opts.Sanitize))
3459     GenerateArg(Args, OPT_fsanitize_EQ, Sanitizer, SA);
3460 
3461   // Conflating '-fsanitize-system-blacklist' and '-fsanitize-blacklist'.
3462   for (const std::string &F : Opts.NoSanitizeFiles)
3463     GenerateArg(Args, OPT_fsanitize_blacklist, F, SA);
3464 
3465   if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver3_8)
3466     GenerateArg(Args, OPT_fclang_abi_compat_EQ, "3.8", SA);
3467   else if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver4)
3468     GenerateArg(Args, OPT_fclang_abi_compat_EQ, "4.0", SA);
3469   else if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver6)
3470     GenerateArg(Args, OPT_fclang_abi_compat_EQ, "6.0", SA);
3471   else if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver7)
3472     GenerateArg(Args, OPT_fclang_abi_compat_EQ, "7.0", SA);
3473   else if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver9)
3474     GenerateArg(Args, OPT_fclang_abi_compat_EQ, "9.0", SA);
3475   else if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver11)
3476     GenerateArg(Args, OPT_fclang_abi_compat_EQ, "11.0", SA);
3477 
3478   if (Opts.getSignReturnAddressScope() ==
3479       LangOptions::SignReturnAddressScopeKind::All)
3480     GenerateArg(Args, OPT_msign_return_address_EQ, "all", SA);
3481   else if (Opts.getSignReturnAddressScope() ==
3482            LangOptions::SignReturnAddressScopeKind::NonLeaf)
3483     GenerateArg(Args, OPT_msign_return_address_EQ, "non-leaf", SA);
3484 
3485   if (Opts.getSignReturnAddressKey() ==
3486       LangOptions::SignReturnAddressKeyKind::BKey)
3487     GenerateArg(Args, OPT_msign_return_address_key_EQ, "b_key", SA);
3488 }
3489 
3490 bool CompilerInvocation::ParseLangArgs(LangOptions &Opts, ArgList &Args,
3491                                        InputKind IK, const llvm::Triple &T,
3492                                        std::vector<std::string> &Includes,
3493                                        DiagnosticsEngine &Diags) {
3494   unsigned NumErrorsBefore = Diags.getNumErrors();
3495 
3496   // FIXME: Cleanup per-file based stuff.
3497   LangStandard::Kind LangStd = LangStandard::lang_unspecified;
3498   if (const Arg *A = Args.getLastArg(OPT_std_EQ)) {
3499     LangStd = LangStandard::getLangKind(A->getValue());
3500     if (LangStd == LangStandard::lang_unspecified) {
3501       Diags.Report(diag::err_drv_invalid_value)
3502         << A->getAsString(Args) << A->getValue();
3503       // Report supported standards with short description.
3504       for (unsigned KindValue = 0;
3505            KindValue != LangStandard::lang_unspecified;
3506            ++KindValue) {
3507         const LangStandard &Std = LangStandard::getLangStandardForKind(
3508           static_cast<LangStandard::Kind>(KindValue));
3509         if (IsInputCompatibleWithStandard(IK, Std)) {
3510           auto Diag = Diags.Report(diag::note_drv_use_standard);
3511           Diag << Std.getName() << Std.getDescription();
3512           unsigned NumAliases = 0;
3513 #define LANGSTANDARD(id, name, lang, desc, features)
3514 #define LANGSTANDARD_ALIAS(id, alias) \
3515           if (KindValue == LangStandard::lang_##id) ++NumAliases;
3516 #define LANGSTANDARD_ALIAS_DEPR(id, alias)
3517 #include "clang/Basic/LangStandards.def"
3518           Diag << NumAliases;
3519 #define LANGSTANDARD(id, name, lang, desc, features)
3520 #define LANGSTANDARD_ALIAS(id, alias) \
3521           if (KindValue == LangStandard::lang_##id) Diag << alias;
3522 #define LANGSTANDARD_ALIAS_DEPR(id, alias)
3523 #include "clang/Basic/LangStandards.def"
3524         }
3525       }
3526     } else {
3527       // Valid standard, check to make sure language and standard are
3528       // compatible.
3529       const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
3530       if (!IsInputCompatibleWithStandard(IK, Std)) {
3531         Diags.Report(diag::err_drv_argument_not_allowed_with)
3532           << A->getAsString(Args) << GetInputKindName(IK);
3533       }
3534     }
3535   }
3536 
3537   // -cl-std only applies for OpenCL language standards.
3538   // Override the -std option in this case.
3539   if (const Arg *A = Args.getLastArg(OPT_cl_std_EQ)) {
3540     LangStandard::Kind OpenCLLangStd
3541       = llvm::StringSwitch<LangStandard::Kind>(A->getValue())
3542         .Cases("cl", "CL", LangStandard::lang_opencl10)
3543         .Cases("cl1.0", "CL1.0", LangStandard::lang_opencl10)
3544         .Cases("cl1.1", "CL1.1", LangStandard::lang_opencl11)
3545         .Cases("cl1.2", "CL1.2", LangStandard::lang_opencl12)
3546         .Cases("cl2.0", "CL2.0", LangStandard::lang_opencl20)
3547         .Cases("cl3.0", "CL3.0", LangStandard::lang_opencl30)
3548         .Cases("clc++", "CLC++", LangStandard::lang_openclcpp)
3549         .Default(LangStandard::lang_unspecified);
3550 
3551     if (OpenCLLangStd == LangStandard::lang_unspecified) {
3552       Diags.Report(diag::err_drv_invalid_value)
3553         << A->getAsString(Args) << A->getValue();
3554     }
3555     else
3556       LangStd = OpenCLLangStd;
3557   }
3558 
3559   // These need to be parsed now. They are used to set OpenCL defaults.
3560   Opts.IncludeDefaultHeader = Args.hasArg(OPT_finclude_default_header);
3561   Opts.DeclareOpenCLBuiltins = Args.hasArg(OPT_fdeclare_opencl_builtins);
3562 
3563   CompilerInvocation::setLangDefaults(Opts, IK, T, Includes, LangStd);
3564 
3565   // The key paths of codegen options defined in Options.td start with
3566   // "LangOpts->". Let's provide the expected variable name and type.
3567   LangOptions *LangOpts = &Opts;
3568   bool Success = true;
3569 
3570 #define LANG_OPTION_WITH_MARSHALLING(                                          \
3571     PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,        \
3572     HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
3573     DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER,     \
3574     MERGER, EXTRACTOR, TABLE_INDEX)                                            \
3575   PARSE_OPTION_WITH_MARSHALLING(Args, Diags, Success, ID, FLAGS, PARAM,        \
3576                                 SHOULD_PARSE, KEYPATH, DEFAULT_VALUE,          \
3577                                 IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER,      \
3578                                 MERGER, TABLE_INDEX)
3579 #include "clang/Driver/Options.inc"
3580 #undef LANG_OPTION_WITH_MARSHALLING
3581 
3582   if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
3583     StringRef Name = A->getValue();
3584     if (Name == "full" || Name == "branch") {
3585       Opts.CFProtectionBranch = 1;
3586     }
3587   }
3588 
3589   if (Opts.ObjC) {
3590     if (Arg *arg = Args.getLastArg(OPT_fobjc_runtime_EQ)) {
3591       StringRef value = arg->getValue();
3592       if (Opts.ObjCRuntime.tryParse(value))
3593         Diags.Report(diag::err_drv_unknown_objc_runtime) << value;
3594     }
3595 
3596     if (Args.hasArg(OPT_fobjc_gc_only))
3597       Opts.setGC(LangOptions::GCOnly);
3598     else if (Args.hasArg(OPT_fobjc_gc))
3599       Opts.setGC(LangOptions::HybridGC);
3600     else if (Args.hasArg(OPT_fobjc_arc)) {
3601       Opts.ObjCAutoRefCount = 1;
3602       if (!Opts.ObjCRuntime.allowsARC())
3603         Diags.Report(diag::err_arc_unsupported_on_runtime);
3604     }
3605 
3606     // ObjCWeakRuntime tracks whether the runtime supports __weak, not
3607     // whether the feature is actually enabled.  This is predominantly
3608     // determined by -fobjc-runtime, but we allow it to be overridden
3609     // from the command line for testing purposes.
3610     if (Args.hasArg(OPT_fobjc_runtime_has_weak))
3611       Opts.ObjCWeakRuntime = 1;
3612     else
3613       Opts.ObjCWeakRuntime = Opts.ObjCRuntime.allowsWeak();
3614 
3615     // ObjCWeak determines whether __weak is actually enabled.
3616     // Note that we allow -fno-objc-weak to disable this even in ARC mode.
3617     if (auto weakArg = Args.getLastArg(OPT_fobjc_weak, OPT_fno_objc_weak)) {
3618       if (!weakArg->getOption().matches(OPT_fobjc_weak)) {
3619         assert(!Opts.ObjCWeak);
3620       } else if (Opts.getGC() != LangOptions::NonGC) {
3621         Diags.Report(diag::err_objc_weak_with_gc);
3622       } else if (!Opts.ObjCWeakRuntime) {
3623         Diags.Report(diag::err_objc_weak_unsupported);
3624       } else {
3625         Opts.ObjCWeak = 1;
3626       }
3627     } else if (Opts.ObjCAutoRefCount) {
3628       Opts.ObjCWeak = Opts.ObjCWeakRuntime;
3629     }
3630 
3631     if (Args.hasArg(OPT_fobjc_subscripting_legacy_runtime))
3632       Opts.ObjCSubscriptingLegacyRuntime =
3633         (Opts.ObjCRuntime.getKind() == ObjCRuntime::FragileMacOSX);
3634   }
3635 
3636   if (Arg *A = Args.getLastArg(options::OPT_fgnuc_version_EQ)) {
3637     // Check that the version has 1 to 3 components and the minor and patch
3638     // versions fit in two decimal digits.
3639     VersionTuple GNUCVer;
3640     bool Invalid = GNUCVer.tryParse(A->getValue());
3641     unsigned Major = GNUCVer.getMajor();
3642     unsigned Minor = GNUCVer.getMinor().getValueOr(0);
3643     unsigned Patch = GNUCVer.getSubminor().getValueOr(0);
3644     if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) {
3645       Diags.Report(diag::err_drv_invalid_value)
3646           << A->getAsString(Args) << A->getValue();
3647     }
3648     Opts.GNUCVersion = Major * 100 * 100 + Minor * 100 + Patch;
3649   }
3650 
3651   // In AIX OS, the -mignore-xcoff-visibility is enable by default if there is
3652   // no -fvisibility=* option.
3653   // This is the reason why '-fvisibility' needs to be always generated:
3654   // its absence implies '-mignore-xcoff-visibility'.
3655   //
3656   // Suppose the original cc1 command line does contain '-fvisibility default':
3657   // '-mignore-xcoff-visibility' should not be implied.
3658   // * If '-fvisibility' is not generated (as most options with default values
3659   //   don't), its absence would imply '-mignore-xcoff-visibility'. This changes
3660   //   the command line semantics.
3661   // * If '-fvisibility' is generated regardless of its presence and value,
3662   //   '-mignore-xcoff-visibility' won't be implied and the command line
3663   //   semantics are kept intact.
3664   //
3665   // When the original cc1 command line does **not** contain '-fvisibility',
3666   // '-mignore-xcoff-visibility' is implied. The generated command line will
3667   // contain both '-fvisibility default' and '-mignore-xcoff-visibility' and
3668   // subsequent calls to `CreateFromArgs`/`generateCC1CommandLine` will always
3669   // produce the same arguments.
3670 
3671   if (T.isOSAIX() && (Args.hasArg(OPT_mignore_xcoff_visibility) ||
3672                       !Args.hasArg(OPT_fvisibility)))
3673     Opts.IgnoreXCOFFVisibility = 1;
3674 
3675   if (Args.hasArg(OPT_ftrapv)) {
3676     Opts.setSignedOverflowBehavior(LangOptions::SOB_Trapping);
3677     // Set the handler, if one is specified.
3678     Opts.OverflowHandler =
3679         std::string(Args.getLastArgValue(OPT_ftrapv_handler));
3680   }
3681   else if (Args.hasArg(OPT_fwrapv))
3682     Opts.setSignedOverflowBehavior(LangOptions::SOB_Defined);
3683 
3684   Opts.MSCompatibilityVersion = 0;
3685   if (const Arg *A = Args.getLastArg(OPT_fms_compatibility_version)) {
3686     VersionTuple VT;
3687     if (VT.tryParse(A->getValue()))
3688       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
3689                                                 << A->getValue();
3690     Opts.MSCompatibilityVersion = VT.getMajor() * 10000000 +
3691                                   VT.getMinor().getValueOr(0) * 100000 +
3692                                   VT.getSubminor().getValueOr(0);
3693   }
3694 
3695   // Mimicking gcc's behavior, trigraphs are only enabled if -trigraphs
3696   // is specified, or -std is set to a conforming mode.
3697   // Trigraphs are disabled by default in c++1z onwards.
3698   // For z/OS, trigraphs are enabled by default (without regard to the above).
3699   Opts.Trigraphs =
3700       (!Opts.GNUMode && !Opts.MSVCCompat && !Opts.CPlusPlus17) || T.isOSzOS();
3701   Opts.Trigraphs =
3702       Args.hasFlag(OPT_ftrigraphs, OPT_fno_trigraphs, Opts.Trigraphs);
3703 
3704   Opts.Blocks = Args.hasArg(OPT_fblocks) || (Opts.OpenCL
3705     && Opts.OpenCLVersion == 200);
3706 
3707   Opts.ConvergentFunctions = Opts.OpenCL || (Opts.CUDA && Opts.CUDAIsDevice) ||
3708                              Opts.SYCLIsDevice ||
3709                              Args.hasArg(OPT_fconvergent_functions);
3710 
3711   Opts.NoBuiltin = Args.hasArg(OPT_fno_builtin) || Opts.Freestanding;
3712   if (!Opts.NoBuiltin)
3713     getAllNoBuiltinFuncValues(Args, Opts.NoBuiltinFuncs);
3714   Opts.LongDoubleSize = Args.hasArg(OPT_mlong_double_128)
3715                             ? 128
3716                             : Args.hasArg(OPT_mlong_double_64) ? 64 : 0;
3717   if (Opts.FastRelaxedMath)
3718     Opts.setDefaultFPContractMode(LangOptions::FPM_Fast);
3719   llvm::sort(Opts.ModuleFeatures);
3720 
3721   // -mrtd option
3722   if (Arg *A = Args.getLastArg(OPT_mrtd)) {
3723     if (Opts.getDefaultCallingConv() != LangOptions::DCC_None)
3724       Diags.Report(diag::err_drv_argument_not_allowed_with)
3725           << A->getSpelling() << "-fdefault-calling-conv";
3726     else {
3727       if (T.getArch() != llvm::Triple::x86)
3728         Diags.Report(diag::err_drv_argument_not_allowed_with)
3729             << A->getSpelling() << T.getTriple();
3730       else
3731         Opts.setDefaultCallingConv(LangOptions::DCC_StdCall);
3732     }
3733   }
3734 
3735   // Check if -fopenmp is specified and set default version to 5.0.
3736   Opts.OpenMP = Args.hasArg(OPT_fopenmp) ? 50 : 0;
3737   // Check if -fopenmp-simd is specified.
3738   bool IsSimdSpecified =
3739       Args.hasFlag(options::OPT_fopenmp_simd, options::OPT_fno_openmp_simd,
3740                    /*Default=*/false);
3741   Opts.OpenMPSimd = !Opts.OpenMP && IsSimdSpecified;
3742   Opts.OpenMPUseTLS =
3743       Opts.OpenMP && !Args.hasArg(options::OPT_fnoopenmp_use_tls);
3744   Opts.OpenMPIsDevice =
3745       Opts.OpenMP && Args.hasArg(options::OPT_fopenmp_is_device);
3746   Opts.OpenMPIRBuilder =
3747       Opts.OpenMP && Args.hasArg(options::OPT_fopenmp_enable_irbuilder);
3748   bool IsTargetSpecified =
3749       Opts.OpenMPIsDevice || Args.hasArg(options::OPT_fopenmp_targets_EQ);
3750 
3751   Opts.ConvergentFunctions = Opts.ConvergentFunctions || Opts.OpenMPIsDevice;
3752 
3753   if (Opts.OpenMP || Opts.OpenMPSimd) {
3754     if (int Version = getLastArgIntValue(
3755             Args, OPT_fopenmp_version_EQ,
3756             (IsSimdSpecified || IsTargetSpecified) ? 50 : Opts.OpenMP, Diags))
3757       Opts.OpenMP = Version;
3758     // Provide diagnostic when a given target is not expected to be an OpenMP
3759     // device or host.
3760     if (!Opts.OpenMPIsDevice) {
3761       switch (T.getArch()) {
3762       default:
3763         break;
3764       // Add unsupported host targets here:
3765       case llvm::Triple::nvptx:
3766       case llvm::Triple::nvptx64:
3767         Diags.Report(diag::err_drv_omp_host_target_not_supported) << T.str();
3768         break;
3769       }
3770     }
3771   }
3772 
3773   // Set the flag to prevent the implementation from emitting device exception
3774   // handling code for those requiring so.
3775   if ((Opts.OpenMPIsDevice && (T.isNVPTX() || T.isAMDGCN())) ||
3776       Opts.OpenCLCPlusPlus) {
3777     Opts.Exceptions = 0;
3778     Opts.CXXExceptions = 0;
3779   }
3780   if (Opts.OpenMPIsDevice && T.isNVPTX()) {
3781     Opts.OpenMPCUDANumSMs =
3782         getLastArgIntValue(Args, options::OPT_fopenmp_cuda_number_of_sm_EQ,
3783                            Opts.OpenMPCUDANumSMs, Diags);
3784     Opts.OpenMPCUDABlocksPerSM =
3785         getLastArgIntValue(Args, options::OPT_fopenmp_cuda_blocks_per_sm_EQ,
3786                            Opts.OpenMPCUDABlocksPerSM, Diags);
3787     Opts.OpenMPCUDAReductionBufNum = getLastArgIntValue(
3788         Args, options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ,
3789         Opts.OpenMPCUDAReductionBufNum, Diags);
3790   }
3791 
3792   // Get the OpenMP target triples if any.
3793   if (Arg *A = Args.getLastArg(options::OPT_fopenmp_targets_EQ)) {
3794     enum ArchPtrSize { Arch16Bit, Arch32Bit, Arch64Bit };
3795     auto getArchPtrSize = [](const llvm::Triple &T) {
3796       if (T.isArch16Bit())
3797         return Arch16Bit;
3798       if (T.isArch32Bit())
3799         return Arch32Bit;
3800       assert(T.isArch64Bit() && "Expected 64-bit architecture");
3801       return Arch64Bit;
3802     };
3803 
3804     for (unsigned i = 0; i < A->getNumValues(); ++i) {
3805       llvm::Triple TT(A->getValue(i));
3806 
3807       if (TT.getArch() == llvm::Triple::UnknownArch ||
3808           !(TT.getArch() == llvm::Triple::aarch64 || TT.isPPC() ||
3809             TT.getArch() == llvm::Triple::nvptx ||
3810             TT.getArch() == llvm::Triple::nvptx64 ||
3811             TT.getArch() == llvm::Triple::amdgcn ||
3812             TT.getArch() == llvm::Triple::x86 ||
3813             TT.getArch() == llvm::Triple::x86_64))
3814         Diags.Report(diag::err_drv_invalid_omp_target) << A->getValue(i);
3815       else if (getArchPtrSize(T) != getArchPtrSize(TT))
3816         Diags.Report(diag::err_drv_incompatible_omp_arch)
3817             << A->getValue(i) << T.str();
3818       else
3819         Opts.OMPTargetTriples.push_back(TT);
3820     }
3821   }
3822 
3823   // Get OpenMP host file path if any and report if a non existent file is
3824   // found
3825   if (Arg *A = Args.getLastArg(options::OPT_fopenmp_host_ir_file_path)) {
3826     Opts.OMPHostIRFile = A->getValue();
3827     if (!llvm::sys::fs::exists(Opts.OMPHostIRFile))
3828       Diags.Report(diag::err_drv_omp_host_ir_file_not_found)
3829           << Opts.OMPHostIRFile;
3830   }
3831 
3832   // Set CUDA mode for OpenMP target NVPTX/AMDGCN if specified in options
3833   Opts.OpenMPCUDAMode = Opts.OpenMPIsDevice && (T.isNVPTX() || T.isAMDGCN()) &&
3834                         Args.hasArg(options::OPT_fopenmp_cuda_mode);
3835 
3836   // Set CUDA support for parallel execution of target regions for OpenMP target
3837   // NVPTX/AMDGCN if specified in options.
3838   Opts.OpenMPCUDATargetParallel =
3839       Opts.OpenMPIsDevice && (T.isNVPTX() || T.isAMDGCN()) &&
3840       Args.hasArg(options::OPT_fopenmp_cuda_parallel_target_regions);
3841 
3842   // Set CUDA mode for OpenMP target NVPTX/AMDGCN if specified in options
3843   Opts.OpenMPCUDAForceFullRuntime =
3844       Opts.OpenMPIsDevice && (T.isNVPTX() || T.isAMDGCN()) &&
3845       Args.hasArg(options::OPT_fopenmp_cuda_force_full_runtime);
3846 
3847   // FIXME: Eliminate this dependency.
3848   unsigned Opt = getOptimizationLevel(Args, IK, Diags),
3849        OptSize = getOptimizationLevelSize(Args);
3850   Opts.Optimize = Opt != 0;
3851   Opts.OptimizeSize = OptSize != 0;
3852 
3853   // This is the __NO_INLINE__ define, which just depends on things like the
3854   // optimization level and -fno-inline, not actually whether the backend has
3855   // inlining enabled.
3856   Opts.NoInlineDefine = !Opts.Optimize;
3857   if (Arg *InlineArg = Args.getLastArg(
3858           options::OPT_finline_functions, options::OPT_finline_hint_functions,
3859           options::OPT_fno_inline_functions, options::OPT_fno_inline))
3860     if (InlineArg->getOption().matches(options::OPT_fno_inline))
3861       Opts.NoInlineDefine = true;
3862 
3863   if (Arg *A = Args.getLastArg(OPT_ffp_contract)) {
3864     StringRef Val = A->getValue();
3865     if (Val == "fast")
3866       Opts.setDefaultFPContractMode(LangOptions::FPM_Fast);
3867     else if (Val == "on")
3868       Opts.setDefaultFPContractMode(LangOptions::FPM_On);
3869     else if (Val == "off")
3870       Opts.setDefaultFPContractMode(LangOptions::FPM_Off);
3871     else if (Val == "fast-honor-pragmas")
3872       Opts.setDefaultFPContractMode(LangOptions::FPM_FastHonorPragmas);
3873     else
3874       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
3875   }
3876 
3877   // Parse -fsanitize= arguments.
3878   parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ),
3879                       Diags, Opts.Sanitize);
3880   Opts.NoSanitizeFiles = Args.getAllArgValues(OPT_fsanitize_blacklist);
3881   std::vector<std::string> systemBlacklists =
3882       Args.getAllArgValues(OPT_fsanitize_system_blacklist);
3883   Opts.NoSanitizeFiles.insert(Opts.NoSanitizeFiles.end(),
3884                               systemBlacklists.begin(), systemBlacklists.end());
3885 
3886   if (Arg *A = Args.getLastArg(OPT_fclang_abi_compat_EQ)) {
3887     Opts.setClangABICompat(LangOptions::ClangABI::Latest);
3888 
3889     StringRef Ver = A->getValue();
3890     std::pair<StringRef, StringRef> VerParts = Ver.split('.');
3891     unsigned Major, Minor = 0;
3892 
3893     // Check the version number is valid: either 3.x (0 <= x <= 9) or
3894     // y or y.0 (4 <= y <= current version).
3895     if (!VerParts.first.startswith("0") &&
3896         !VerParts.first.getAsInteger(10, Major) &&
3897         3 <= Major && Major <= CLANG_VERSION_MAJOR &&
3898         (Major == 3 ? VerParts.second.size() == 1 &&
3899                       !VerParts.second.getAsInteger(10, Minor)
3900                     : VerParts.first.size() == Ver.size() ||
3901                       VerParts.second == "0")) {
3902       // Got a valid version number.
3903       if (Major == 3 && Minor <= 8)
3904         Opts.setClangABICompat(LangOptions::ClangABI::Ver3_8);
3905       else if (Major <= 4)
3906         Opts.setClangABICompat(LangOptions::ClangABI::Ver4);
3907       else if (Major <= 6)
3908         Opts.setClangABICompat(LangOptions::ClangABI::Ver6);
3909       else if (Major <= 7)
3910         Opts.setClangABICompat(LangOptions::ClangABI::Ver7);
3911       else if (Major <= 9)
3912         Opts.setClangABICompat(LangOptions::ClangABI::Ver9);
3913       else if (Major <= 11)
3914         Opts.setClangABICompat(LangOptions::ClangABI::Ver11);
3915     } else if (Ver != "latest") {
3916       Diags.Report(diag::err_drv_invalid_value)
3917           << A->getAsString(Args) << A->getValue();
3918     }
3919   }
3920 
3921   if (Arg *A = Args.getLastArg(OPT_msign_return_address_EQ)) {
3922     StringRef SignScope = A->getValue();
3923 
3924     if (SignScope.equals_lower("none"))
3925       Opts.setSignReturnAddressScope(
3926           LangOptions::SignReturnAddressScopeKind::None);
3927     else if (SignScope.equals_lower("all"))
3928       Opts.setSignReturnAddressScope(
3929           LangOptions::SignReturnAddressScopeKind::All);
3930     else if (SignScope.equals_lower("non-leaf"))
3931       Opts.setSignReturnAddressScope(
3932           LangOptions::SignReturnAddressScopeKind::NonLeaf);
3933     else
3934       Diags.Report(diag::err_drv_invalid_value)
3935           << A->getAsString(Args) << SignScope;
3936 
3937     if (Arg *A = Args.getLastArg(OPT_msign_return_address_key_EQ)) {
3938       StringRef SignKey = A->getValue();
3939       if (!SignScope.empty() && !SignKey.empty()) {
3940         if (SignKey.equals_lower("a_key"))
3941           Opts.setSignReturnAddressKey(
3942               LangOptions::SignReturnAddressKeyKind::AKey);
3943         else if (SignKey.equals_lower("b_key"))
3944           Opts.setSignReturnAddressKey(
3945               LangOptions::SignReturnAddressKeyKind::BKey);
3946         else
3947           Diags.Report(diag::err_drv_invalid_value)
3948               << A->getAsString(Args) << SignKey;
3949       }
3950     }
3951   }
3952 
3953   return Success && Diags.getNumErrors() == NumErrorsBefore;
3954 }
3955 
3956 static bool isStrictlyPreprocessorAction(frontend::ActionKind Action) {
3957   switch (Action) {
3958   case frontend::ASTDeclList:
3959   case frontend::ASTDump:
3960   case frontend::ASTPrint:
3961   case frontend::ASTView:
3962   case frontend::EmitAssembly:
3963   case frontend::EmitBC:
3964   case frontend::EmitHTML:
3965   case frontend::EmitLLVM:
3966   case frontend::EmitLLVMOnly:
3967   case frontend::EmitCodeGenOnly:
3968   case frontend::EmitObj:
3969   case frontend::FixIt:
3970   case frontend::GenerateModule:
3971   case frontend::GenerateModuleInterface:
3972   case frontend::GenerateHeaderModule:
3973   case frontend::GeneratePCH:
3974   case frontend::GenerateInterfaceStubs:
3975   case frontend::ParseSyntaxOnly:
3976   case frontend::ModuleFileInfo:
3977   case frontend::VerifyPCH:
3978   case frontend::PluginAction:
3979   case frontend::RewriteObjC:
3980   case frontend::RewriteTest:
3981   case frontend::RunAnalysis:
3982   case frontend::TemplightDump:
3983   case frontend::MigrateSource:
3984     return false;
3985 
3986   case frontend::DumpCompilerOptions:
3987   case frontend::DumpRawTokens:
3988   case frontend::DumpTokens:
3989   case frontend::InitOnly:
3990   case frontend::PrintPreamble:
3991   case frontend::PrintPreprocessedInput:
3992   case frontend::RewriteMacros:
3993   case frontend::RunPreprocessorOnly:
3994   case frontend::PrintDependencyDirectivesSourceMinimizerOutput:
3995     return true;
3996   }
3997   llvm_unreachable("invalid frontend action");
3998 }
3999 
4000 static void GeneratePreprocessorArgs(PreprocessorOptions &Opts,
4001                                      SmallVectorImpl<const char *> &Args,
4002                                      CompilerInvocation::StringAllocator SA,
4003                                      const LangOptions &LangOpts,
4004                                      const FrontendOptions &FrontendOpts,
4005                                      const CodeGenOptions &CodeGenOpts) {
4006   PreprocessorOptions *PreprocessorOpts = &Opts;
4007 
4008 #define PREPROCESSOR_OPTION_WITH_MARSHALLING(                                  \
4009     PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,        \
4010     HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
4011     DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER,     \
4012     MERGER, EXTRACTOR, TABLE_INDEX)                                            \
4013   GENERATE_OPTION_WITH_MARSHALLING(                                            \
4014       Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE,    \
4015       IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
4016 #include "clang/Driver/Options.inc"
4017 #undef PREPROCESSOR_OPTION_WITH_MARSHALLING
4018 
4019   if (Opts.PCHWithHdrStop && !Opts.PCHWithHdrStopCreate)
4020     GenerateArg(Args, OPT_pch_through_hdrstop_use, SA);
4021 
4022   for (const auto &D : Opts.DeserializedPCHDeclsToErrorOn)
4023     GenerateArg(Args, OPT_error_on_deserialized_pch_decl, D, SA);
4024 
4025   for (const auto &MP : Opts.MacroPrefixMap)
4026     GenerateArg(Args, OPT_fmacro_prefix_map_EQ, MP.first + "=" + MP.second, SA);
4027 
4028   if (Opts.PrecompiledPreambleBytes != std::make_pair(0u, false))
4029     GenerateArg(Args, OPT_preamble_bytes_EQ,
4030                 Twine(Opts.PrecompiledPreambleBytes.first) + "," +
4031                     (Opts.PrecompiledPreambleBytes.second ? "1" : "0"),
4032                 SA);
4033 
4034   for (const auto &M : Opts.Macros) {
4035     // Don't generate __CET__ macro definitions. They are implied by the
4036     // -fcf-protection option that is generated elsewhere.
4037     if (M.first == "__CET__=1" && !M.second &&
4038         !CodeGenOpts.CFProtectionReturn && CodeGenOpts.CFProtectionBranch)
4039       continue;
4040     if (M.first == "__CET__=2" && !M.second && CodeGenOpts.CFProtectionReturn &&
4041         !CodeGenOpts.CFProtectionBranch)
4042       continue;
4043     if (M.first == "__CET__=3" && !M.second && CodeGenOpts.CFProtectionReturn &&
4044         CodeGenOpts.CFProtectionBranch)
4045       continue;
4046 
4047     GenerateArg(Args, M.second ? OPT_U : OPT_D, M.first, SA);
4048   }
4049 
4050   for (const auto &I : Opts.Includes) {
4051     // Don't generate OpenCL includes. They are implied by other flags that are
4052     // generated elsewhere.
4053     if (LangOpts.OpenCL && LangOpts.IncludeDefaultHeader &&
4054         ((LangOpts.DeclareOpenCLBuiltins && I == "opencl-c-base.h") ||
4055          I == "opencl-c.h"))
4056       continue;
4057 
4058     GenerateArg(Args, OPT_include, I, SA);
4059   }
4060 
4061   for (const auto &CI : Opts.ChainedIncludes)
4062     GenerateArg(Args, OPT_chain_include, CI, SA);
4063 
4064   for (const auto &RF : Opts.RemappedFiles)
4065     GenerateArg(Args, OPT_remap_file, RF.first + ";" + RF.second, SA);
4066 
4067   // Don't handle LexEditorPlaceholders. It is implied by the action that is
4068   // generated elsewhere.
4069 }
4070 
4071 static bool ParsePreprocessorArgs(PreprocessorOptions &Opts, ArgList &Args,
4072                                   DiagnosticsEngine &Diags,
4073                                   frontend::ActionKind Action,
4074                                   const FrontendOptions &FrontendOpts) {
4075   PreprocessorOptions *PreprocessorOpts = &Opts;
4076   bool Success = true;
4077 
4078 #define PREPROCESSOR_OPTION_WITH_MARSHALLING(                                  \
4079     PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,        \
4080     HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
4081     DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER,     \
4082     MERGER, EXTRACTOR, TABLE_INDEX)                                            \
4083   PARSE_OPTION_WITH_MARSHALLING(Args, Diags, Success, ID, FLAGS, PARAM,        \
4084                                 SHOULD_PARSE, KEYPATH, DEFAULT_VALUE,          \
4085                                 IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER,      \
4086                                 MERGER, TABLE_INDEX)
4087 #include "clang/Driver/Options.inc"
4088 #undef PREPROCESSOR_OPTION_WITH_MARSHALLING
4089 
4090   Opts.PCHWithHdrStop = Args.hasArg(OPT_pch_through_hdrstop_create) ||
4091                         Args.hasArg(OPT_pch_through_hdrstop_use);
4092 
4093   for (const auto *A : Args.filtered(OPT_error_on_deserialized_pch_decl))
4094     Opts.DeserializedPCHDeclsToErrorOn.insert(A->getValue());
4095 
4096   for (const auto &A : Args.getAllArgValues(OPT_fmacro_prefix_map_EQ)) {
4097     auto Split = StringRef(A).split('=');
4098     Opts.MacroPrefixMap.insert(
4099         {std::string(Split.first), std::string(Split.second)});
4100   }
4101 
4102   if (const Arg *A = Args.getLastArg(OPT_preamble_bytes_EQ)) {
4103     StringRef Value(A->getValue());
4104     size_t Comma = Value.find(',');
4105     unsigned Bytes = 0;
4106     unsigned EndOfLine = 0;
4107 
4108     if (Comma == StringRef::npos ||
4109         Value.substr(0, Comma).getAsInteger(10, Bytes) ||
4110         Value.substr(Comma + 1).getAsInteger(10, EndOfLine))
4111       Diags.Report(diag::err_drv_preamble_format);
4112     else {
4113       Opts.PrecompiledPreambleBytes.first = Bytes;
4114       Opts.PrecompiledPreambleBytes.second = (EndOfLine != 0);
4115     }
4116   }
4117 
4118   // Add the __CET__ macro if a CFProtection option is set.
4119   if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
4120     StringRef Name = A->getValue();
4121     if (Name == "branch")
4122       Opts.addMacroDef("__CET__=1");
4123     else if (Name == "return")
4124       Opts.addMacroDef("__CET__=2");
4125     else if (Name == "full")
4126       Opts.addMacroDef("__CET__=3");
4127   }
4128 
4129   // Add macros from the command line.
4130   for (const auto *A : Args.filtered(OPT_D, OPT_U)) {
4131     if (A->getOption().matches(OPT_D))
4132       Opts.addMacroDef(A->getValue());
4133     else
4134       Opts.addMacroUndef(A->getValue());
4135   }
4136 
4137   // Add the ordered list of -includes.
4138   for (const auto *A : Args.filtered(OPT_include))
4139     Opts.Includes.emplace_back(A->getValue());
4140 
4141   for (const auto *A : Args.filtered(OPT_chain_include))
4142     Opts.ChainedIncludes.emplace_back(A->getValue());
4143 
4144   for (const auto *A : Args.filtered(OPT_remap_file)) {
4145     std::pair<StringRef, StringRef> Split = StringRef(A->getValue()).split(';');
4146 
4147     if (Split.second.empty()) {
4148       Diags.Report(diag::err_drv_invalid_remap_file) << A->getAsString(Args);
4149       continue;
4150     }
4151 
4152     Opts.addRemappedFile(Split.first, Split.second);
4153   }
4154 
4155   // Always avoid lexing editor placeholders when we're just running the
4156   // preprocessor as we never want to emit the
4157   // "editor placeholder in source file" error in PP only mode.
4158   if (isStrictlyPreprocessorAction(Action))
4159     Opts.LexEditorPlaceholders = false;
4160 
4161   return Success;
4162 }
4163 
4164 static void GeneratePreprocessorOutputArgs(
4165     const PreprocessorOutputOptions &Opts, SmallVectorImpl<const char *> &Args,
4166     CompilerInvocation::StringAllocator SA, frontend::ActionKind Action) {
4167   const PreprocessorOutputOptions &PreprocessorOutputOpts = Opts;
4168 
4169 #define PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING(                           \
4170     PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,        \
4171     HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
4172     DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER,     \
4173     MERGER, EXTRACTOR, TABLE_INDEX)                                            \
4174   GENERATE_OPTION_WITH_MARSHALLING(                                            \
4175       Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE,    \
4176       IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
4177 #include "clang/Driver/Options.inc"
4178 #undef PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING
4179 
4180   bool Generate_dM = isStrictlyPreprocessorAction(Action) && !Opts.ShowCPP;
4181   if (Generate_dM)
4182     GenerateArg(Args, OPT_dM, SA);
4183   if (!Generate_dM && Opts.ShowMacros)
4184     GenerateArg(Args, OPT_dD, SA);
4185 }
4186 
4187 static bool ParsePreprocessorOutputArgs(PreprocessorOutputOptions &Opts,
4188                                         ArgList &Args, DiagnosticsEngine &Diags,
4189                                         frontend::ActionKind Action) {
4190   PreprocessorOutputOptions &PreprocessorOutputOpts = Opts;
4191   unsigned NumErrorsBefore = Diags.getNumErrors();
4192   bool Success = true;
4193 
4194 #define PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING(                           \
4195     PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,        \
4196     HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
4197     DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER,     \
4198     MERGER, EXTRACTOR, TABLE_INDEX)                                            \
4199   PARSE_OPTION_WITH_MARSHALLING(Args, Diags, Success, ID, FLAGS, PARAM,        \
4200                                 SHOULD_PARSE, KEYPATH, DEFAULT_VALUE,          \
4201                                 IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER,      \
4202                                 MERGER, TABLE_INDEX)
4203 #include "clang/Driver/Options.inc"
4204 #undef PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING
4205 
4206   Opts.ShowCPP = isStrictlyPreprocessorAction(Action) && !Args.hasArg(OPT_dM);
4207   Opts.ShowMacros = Args.hasArg(OPT_dM) || Args.hasArg(OPT_dD);
4208 
4209   return Success && Diags.getNumErrors() == NumErrorsBefore;
4210 }
4211 
4212 static void GenerateTargetArgs(const TargetOptions &Opts,
4213                                SmallVectorImpl<const char *> &Args,
4214                                CompilerInvocation::StringAllocator SA) {
4215   const TargetOptions *TargetOpts = &Opts;
4216 #define TARGET_OPTION_WITH_MARSHALLING(                                        \
4217     PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,        \
4218     HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
4219     DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER,     \
4220     MERGER, EXTRACTOR, TABLE_INDEX)                                            \
4221   GENERATE_OPTION_WITH_MARSHALLING(                                            \
4222       Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE,    \
4223       IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
4224 #include "clang/Driver/Options.inc"
4225 #undef TARGET_OPTION_WITH_MARSHALLING
4226 
4227   if (!Opts.SDKVersion.empty())
4228     GenerateArg(Args, OPT_target_sdk_version_EQ, Opts.SDKVersion.getAsString(),
4229                 SA);
4230 }
4231 
4232 static bool ParseTargetArgs(TargetOptions &Opts, ArgList &Args,
4233                             DiagnosticsEngine &Diags) {
4234   TargetOptions *TargetOpts = &Opts;
4235   unsigned NumErrorsBefore = Diags.getNumErrors();
4236   bool Success = true;
4237 
4238 #define TARGET_OPTION_WITH_MARSHALLING(                                        \
4239     PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,        \
4240     HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
4241     DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER,     \
4242     MERGER, EXTRACTOR, TABLE_INDEX)                                            \
4243   PARSE_OPTION_WITH_MARSHALLING(Args, Diags, Success, ID, FLAGS, PARAM,        \
4244                                 SHOULD_PARSE, KEYPATH, DEFAULT_VALUE,          \
4245                                 IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER,      \
4246                                 MERGER, TABLE_INDEX)
4247 #include "clang/Driver/Options.inc"
4248 #undef TARGET_OPTION_WITH_MARSHALLING
4249 
4250   if (Arg *A = Args.getLastArg(options::OPT_target_sdk_version_EQ)) {
4251     llvm::VersionTuple Version;
4252     if (Version.tryParse(A->getValue()))
4253       Diags.Report(diag::err_drv_invalid_value)
4254           << A->getAsString(Args) << A->getValue();
4255     else
4256       Opts.SDKVersion = Version;
4257   }
4258 
4259   return Success && Diags.getNumErrors() == NumErrorsBefore;
4260 }
4261 
4262 bool CompilerInvocation::CreateFromArgsImpl(
4263     CompilerInvocation &Res, ArrayRef<const char *> CommandLineArgs,
4264     DiagnosticsEngine &Diags, const char *Argv0) {
4265   bool Success = true;
4266 
4267   // Parse the arguments.
4268   const OptTable &Opts = getDriverOptTable();
4269   const unsigned IncludedFlagsBitmask = options::CC1Option;
4270   unsigned MissingArgIndex, MissingArgCount;
4271   InputArgList Args = Opts.ParseArgs(CommandLineArgs, MissingArgIndex,
4272                                      MissingArgCount, IncludedFlagsBitmask);
4273   LangOptions &LangOpts = *Res.getLangOpts();
4274 
4275   // Check for missing argument error.
4276   if (MissingArgCount) {
4277     Diags.Report(diag::err_drv_missing_argument)
4278         << Args.getArgString(MissingArgIndex) << MissingArgCount;
4279     Success = false;
4280   }
4281 
4282   // Issue errors on unknown arguments.
4283   for (const auto *A : Args.filtered(OPT_UNKNOWN)) {
4284     auto ArgString = A->getAsString(Args);
4285     std::string Nearest;
4286     if (Opts.findNearest(ArgString, Nearest, IncludedFlagsBitmask) > 1)
4287       Diags.Report(diag::err_drv_unknown_argument) << ArgString;
4288     else
4289       Diags.Report(diag::err_drv_unknown_argument_with_suggestion)
4290           << ArgString << Nearest;
4291     Success = false;
4292   }
4293 
4294   Success &= ParseFileSystemArgs(Res.getFileSystemOpts(), Args, Diags);
4295   Success &= ParseMigratorArgs(Res.getMigratorOpts(), Args, Diags);
4296   Success &= ParseAnalyzerArgs(*Res.getAnalyzerOpts(), Args, Diags);
4297   Success &= ParseDiagnosticArgs(Res.getDiagnosticOpts(), Args, &Diags,
4298                                  /*DefaultDiagColor=*/false);
4299   Success &= ParseFrontendArgs(Res.getFrontendOpts(), Args, Diags,
4300                                LangOpts.IsHeaderFile);
4301   // FIXME: We shouldn't have to pass the DashX option around here
4302   InputKind DashX = Res.getFrontendOpts().DashX;
4303   Success &= ParseTargetArgs(Res.getTargetOpts(), Args, Diags);
4304   llvm::Triple T(Res.getTargetOpts().Triple);
4305   ParseHeaderSearchArgs(Res.getHeaderSearchOpts(), Args, Diags,
4306                         Res.getFileSystemOpts().WorkingDir);
4307   if (DashX.getFormat() == InputKind::Precompiled ||
4308       DashX.getLanguage() == Language::LLVM_IR) {
4309     // ObjCAAutoRefCount and Sanitize LangOpts are used to setup the
4310     // PassManager in BackendUtil.cpp. They need to be initializd no matter
4311     // what the input type is.
4312     if (Args.hasArg(OPT_fobjc_arc))
4313       LangOpts.ObjCAutoRefCount = 1;
4314     // PIClevel and PIELevel are needed during code generation and this should be
4315     // set regardless of the input type.
4316     LangOpts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags);
4317     LangOpts.PIE = Args.hasArg(OPT_pic_is_pie);
4318     parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ),
4319                         Diags, LangOpts.Sanitize);
4320   } else {
4321     // Other LangOpts are only initialized when the input is not AST or LLVM IR.
4322     // FIXME: Should we really be calling this for an Language::Asm input?
4323     Success &= ParseLangArgs(LangOpts, Args, DashX, T,
4324                              Res.getPreprocessorOpts().Includes, Diags);
4325     if (Res.getFrontendOpts().ProgramAction == frontend::RewriteObjC)
4326       LangOpts.ObjCExceptions = 1;
4327   }
4328 
4329   if (LangOpts.CUDA) {
4330     // During CUDA device-side compilation, the aux triple is the
4331     // triple used for host compilation.
4332     if (LangOpts.CUDAIsDevice)
4333       Res.getTargetOpts().HostTriple = Res.getFrontendOpts().AuxTriple;
4334   }
4335 
4336   // Set the triple of the host for OpenMP device compile.
4337   if (LangOpts.OpenMPIsDevice)
4338     Res.getTargetOpts().HostTriple = Res.getFrontendOpts().AuxTriple;
4339 
4340   Success &= ParseCodeGenArgs(Res.getCodeGenOpts(), Args, DashX, Diags, T,
4341                               Res.getFrontendOpts().OutputFile, LangOpts);
4342 
4343   // FIXME: Override value name discarding when asan or msan is used because the
4344   // backend passes depend on the name of the alloca in order to print out
4345   // names.
4346   Res.getCodeGenOpts().DiscardValueNames &=
4347       !LangOpts.Sanitize.has(SanitizerKind::Address) &&
4348       !LangOpts.Sanitize.has(SanitizerKind::KernelAddress) &&
4349       !LangOpts.Sanitize.has(SanitizerKind::Memory) &&
4350       !LangOpts.Sanitize.has(SanitizerKind::KernelMemory);
4351 
4352   ParsePreprocessorArgs(Res.getPreprocessorOpts(), Args, Diags,
4353                         Res.getFrontendOpts().ProgramAction,
4354                         Res.getFrontendOpts());
4355   ParsePreprocessorOutputArgs(Res.getPreprocessorOutputOpts(), Args, Diags,
4356                               Res.getFrontendOpts().ProgramAction);
4357 
4358   ParseDependencyOutputArgs(Res.getDependencyOutputOpts(), Args, Diags,
4359                             Res.getFrontendOpts().ProgramAction,
4360                             Res.getPreprocessorOutputOpts().ShowLineMarkers);
4361   if (!Res.getDependencyOutputOpts().OutputFile.empty() &&
4362       Res.getDependencyOutputOpts().Targets.empty()) {
4363     Diags.Report(diag::err_fe_dependency_file_requires_MT);
4364     Success = false;
4365   }
4366 
4367   // If sanitizer is enabled, disable OPT_ffine_grained_bitfield_accesses.
4368   if (Res.getCodeGenOpts().FineGrainedBitfieldAccesses &&
4369       !Res.getLangOpts()->Sanitize.empty()) {
4370     Res.getCodeGenOpts().FineGrainedBitfieldAccesses = false;
4371     Diags.Report(diag::warn_drv_fine_grained_bitfield_accesses_ignored);
4372   }
4373 
4374   // Store the command-line for using in the CodeView backend.
4375   Res.getCodeGenOpts().Argv0 = Argv0;
4376   Res.getCodeGenOpts().CommandLineArgs = CommandLineArgs;
4377 
4378   Success &= FixupInvocation(Res, Diags, Args, DashX);
4379 
4380   return Success;
4381 }
4382 
4383 bool CompilerInvocation::CreateFromArgs(CompilerInvocation &Invocation,
4384                                         ArrayRef<const char *> CommandLineArgs,
4385                                         DiagnosticsEngine &Diags,
4386                                         const char *Argv0) {
4387   CompilerInvocation DummyInvocation;
4388 
4389   return RoundTrip(
4390       [](CompilerInvocation &Invocation, ArrayRef<const char *> CommandLineArgs,
4391          DiagnosticsEngine &Diags, const char *Argv0) {
4392         return CreateFromArgsImpl(Invocation, CommandLineArgs, Diags, Argv0);
4393       },
4394       [](CompilerInvocation &Invocation, SmallVectorImpl<const char *> &Args,
4395          StringAllocator SA) { Invocation.generateCC1CommandLine(Args, SA); },
4396       Invocation, DummyInvocation, CommandLineArgs, Diags, Argv0);
4397 }
4398 
4399 std::string CompilerInvocation::getModuleHash() const {
4400   // Note: For QoI reasons, the things we use as a hash here should all be
4401   // dumped via the -module-info flag.
4402   using llvm::hash_code;
4403   using llvm::hash_value;
4404   using llvm::hash_combine;
4405   using llvm::hash_combine_range;
4406 
4407   // Start the signature with the compiler version.
4408   // FIXME: We'd rather use something more cryptographically sound than
4409   // CityHash, but this will do for now.
4410   hash_code code = hash_value(getClangFullRepositoryVersion());
4411 
4412   // Also include the serialization version, in case LLVM_APPEND_VC_REV is off
4413   // and getClangFullRepositoryVersion() doesn't include git revision.
4414   code = hash_combine(code, serialization::VERSION_MAJOR,
4415                       serialization::VERSION_MINOR);
4416 
4417   // Extend the signature with the language options
4418 #define LANGOPT(Name, Bits, Default, Description) \
4419    code = hash_combine(code, LangOpts->Name);
4420 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4421   code = hash_combine(code, static_cast<unsigned>(LangOpts->get##Name()));
4422 #define BENIGN_LANGOPT(Name, Bits, Default, Description)
4423 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
4424 #include "clang/Basic/LangOptions.def"
4425 
4426   for (StringRef Feature : LangOpts->ModuleFeatures)
4427     code = hash_combine(code, Feature);
4428 
4429   code = hash_combine(code, LangOpts->ObjCRuntime);
4430   const auto &BCN = LangOpts->CommentOpts.BlockCommandNames;
4431   code = hash_combine(code, hash_combine_range(BCN.begin(), BCN.end()));
4432 
4433   // Extend the signature with the target options.
4434   code = hash_combine(code, TargetOpts->Triple, TargetOpts->CPU,
4435                       TargetOpts->TuneCPU, TargetOpts->ABI);
4436   for (const auto &FeatureAsWritten : TargetOpts->FeaturesAsWritten)
4437     code = hash_combine(code, FeatureAsWritten);
4438 
4439   // Extend the signature with preprocessor options.
4440   const PreprocessorOptions &ppOpts = getPreprocessorOpts();
4441   const HeaderSearchOptions &hsOpts = getHeaderSearchOpts();
4442   code = hash_combine(code, ppOpts.UsePredefines, ppOpts.DetailedRecord);
4443 
4444   for (const auto &I : getPreprocessorOpts().Macros) {
4445     // If we're supposed to ignore this macro for the purposes of modules,
4446     // don't put it into the hash.
4447     if (!hsOpts.ModulesIgnoreMacros.empty()) {
4448       // Check whether we're ignoring this macro.
4449       StringRef MacroDef = I.first;
4450       if (hsOpts.ModulesIgnoreMacros.count(
4451               llvm::CachedHashString(MacroDef.split('=').first)))
4452         continue;
4453     }
4454 
4455     code = hash_combine(code, I.first, I.second);
4456   }
4457 
4458   // Extend the signature with the sysroot and other header search options.
4459   code = hash_combine(code, hsOpts.Sysroot,
4460                       hsOpts.ModuleFormat,
4461                       hsOpts.UseDebugInfo,
4462                       hsOpts.UseBuiltinIncludes,
4463                       hsOpts.UseStandardSystemIncludes,
4464                       hsOpts.UseStandardCXXIncludes,
4465                       hsOpts.UseLibcxx,
4466                       hsOpts.ModulesValidateDiagnosticOptions);
4467   code = hash_combine(code, hsOpts.ResourceDir);
4468 
4469   if (hsOpts.ModulesStrictContextHash) {
4470     hash_code SHPC = hash_combine_range(hsOpts.SystemHeaderPrefixes.begin(),
4471                                         hsOpts.SystemHeaderPrefixes.end());
4472     hash_code UEC = hash_combine_range(hsOpts.UserEntries.begin(),
4473                                        hsOpts.UserEntries.end());
4474     code = hash_combine(code, hsOpts.SystemHeaderPrefixes.size(), SHPC,
4475                         hsOpts.UserEntries.size(), UEC);
4476 
4477     const DiagnosticOptions &diagOpts = getDiagnosticOpts();
4478     #define DIAGOPT(Name, Bits, Default) \
4479       code = hash_combine(code, diagOpts.Name);
4480     #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
4481       code = hash_combine(code, diagOpts.get##Name());
4482     #include "clang/Basic/DiagnosticOptions.def"
4483     #undef DIAGOPT
4484     #undef ENUM_DIAGOPT
4485   }
4486 
4487   // Extend the signature with the user build path.
4488   code = hash_combine(code, hsOpts.ModuleUserBuildPath);
4489 
4490   // Extend the signature with the module file extensions.
4491   const FrontendOptions &frontendOpts = getFrontendOpts();
4492   for (const auto &ext : frontendOpts.ModuleFileExtensions) {
4493     code = ext->hashExtension(code);
4494   }
4495 
4496   // When compiling with -gmodules, also hash -fdebug-prefix-map as it
4497   // affects the debug info in the PCM.
4498   if (getCodeGenOpts().DebugTypeExtRefs)
4499     for (const auto &KeyValue : getCodeGenOpts().DebugPrefixMap)
4500       code = hash_combine(code, KeyValue.first, KeyValue.second);
4501 
4502   // Extend the signature with the enabled sanitizers, if at least one is
4503   // enabled. Sanitizers which cannot affect AST generation aren't hashed.
4504   SanitizerSet SanHash = LangOpts->Sanitize;
4505   SanHash.clear(getPPTransparentSanitizers());
4506   if (!SanHash.empty())
4507     code = hash_combine(code, SanHash.Mask);
4508 
4509   return llvm::APInt(64, code).toString(36, /*Signed=*/false);
4510 }
4511 
4512 void CompilerInvocation::generateCC1CommandLine(
4513     SmallVectorImpl<const char *> &Args, StringAllocator SA) const {
4514   llvm::Triple T(TargetOpts->Triple);
4515 
4516   GenerateFileSystemArgs(FileSystemOpts, Args, SA);
4517   GenerateMigratorArgs(MigratorOpts, Args, SA);
4518   GenerateAnalyzerArgs(*AnalyzerOpts, Args, SA);
4519   GenerateDiagnosticArgs(*DiagnosticOpts, Args, SA, false);
4520   GenerateFrontendArgs(FrontendOpts, Args, SA, LangOpts->IsHeaderFile);
4521   GenerateTargetArgs(*TargetOpts, Args, SA);
4522   GenerateHeaderSearchArgs(*HeaderSearchOpts, Args, SA);
4523 
4524   InputKind DashX = FrontendOpts.DashX;
4525   if (DashX.getFormat() == InputKind::Precompiled ||
4526       DashX.getLanguage() == Language::LLVM_IR) {
4527     if (LangOpts->ObjCAutoRefCount)
4528       GenerateArg(Args, OPT_fobjc_arc, SA);
4529     if (LangOpts->PICLevel != 0)
4530       GenerateArg(Args, OPT_pic_level, Twine(LangOpts->PICLevel), SA);
4531     if (LangOpts->PIE)
4532       GenerateArg(Args, OPT_pic_is_pie, SA);
4533     for (StringRef Sanitizer : serializeSanitizerKinds(LangOpts->Sanitize))
4534       GenerateArg(Args, OPT_fsanitize_EQ, Sanitizer, SA);
4535   } else {
4536     // FIXME: Move this whole condition into GenerateLangArgs. (And do the same
4537     // for ParseLangArgs).
4538     GenerateLangArgs(*LangOpts, Args, SA, T);
4539   }
4540 
4541   GenerateCodeGenArgs(CodeGenOpts, Args, SA, T, FrontendOpts.OutputFile,
4542                       &*LangOpts);
4543   GeneratePreprocessorArgs(*PreprocessorOpts, Args, SA, *LangOpts, FrontendOpts,
4544                            CodeGenOpts);
4545   GeneratePreprocessorOutputArgs(PreprocessorOutputOpts, Args, SA,
4546                                  FrontendOpts.ProgramAction);
4547   GenerateDependencyOutputArgs(DependencyOutputOpts, Args, SA);
4548 }
4549 
4550 IntrusiveRefCntPtr<llvm::vfs::FileSystem>
4551 clang::createVFSFromCompilerInvocation(const CompilerInvocation &CI,
4552                                        DiagnosticsEngine &Diags) {
4553   return createVFSFromCompilerInvocation(CI, Diags,
4554                                          llvm::vfs::getRealFileSystem());
4555 }
4556 
4557 IntrusiveRefCntPtr<llvm::vfs::FileSystem>
4558 clang::createVFSFromCompilerInvocation(
4559     const CompilerInvocation &CI, DiagnosticsEngine &Diags,
4560     IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS) {
4561   if (CI.getHeaderSearchOpts().VFSOverlayFiles.empty())
4562     return BaseFS;
4563 
4564   IntrusiveRefCntPtr<llvm::vfs::FileSystem> Result = BaseFS;
4565   // earlier vfs files are on the bottom
4566   for (const auto &File : CI.getHeaderSearchOpts().VFSOverlayFiles) {
4567     llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer =
4568         Result->getBufferForFile(File);
4569     if (!Buffer) {
4570       Diags.Report(diag::err_missing_vfs_overlay_file) << File;
4571       continue;
4572     }
4573 
4574     IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS = llvm::vfs::getVFSFromYAML(
4575         std::move(Buffer.get()), /*DiagHandler*/ nullptr, File,
4576         /*DiagContext*/ nullptr, Result);
4577     if (!FS) {
4578       Diags.Report(diag::err_invalid_vfs_overlay) << File;
4579       continue;
4580     }
4581 
4582     Result = FS;
4583   }
4584   return Result;
4585 }
4586