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