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