10b57cec5SDimitry Andric //===- CompilerInvocation.cpp ---------------------------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric 
90b57cec5SDimitry Andric #include "clang/Frontend/CompilerInvocation.h"
100b57cec5SDimitry Andric #include "TestModuleFileExtension.h"
110b57cec5SDimitry Andric #include "clang/Basic/Builtins.h"
120b57cec5SDimitry Andric #include "clang/Basic/CharInfo.h"
130b57cec5SDimitry Andric #include "clang/Basic/CodeGenOptions.h"
140b57cec5SDimitry Andric #include "clang/Basic/CommentOptions.h"
150b57cec5SDimitry Andric #include "clang/Basic/DebugInfoOptions.h"
160b57cec5SDimitry Andric #include "clang/Basic/Diagnostic.h"
17af732203SDimitry Andric #include "clang/Basic/DiagnosticDriver.h"
180b57cec5SDimitry Andric #include "clang/Basic/DiagnosticOptions.h"
190b57cec5SDimitry Andric #include "clang/Basic/FileSystemOptions.h"
200b57cec5SDimitry Andric #include "clang/Basic/LLVM.h"
210b57cec5SDimitry Andric #include "clang/Basic/LangOptions.h"
22a7dea167SDimitry Andric #include "clang/Basic/LangStandard.h"
230b57cec5SDimitry Andric #include "clang/Basic/ObjCRuntime.h"
240b57cec5SDimitry Andric #include "clang/Basic/Sanitizers.h"
250b57cec5SDimitry Andric #include "clang/Basic/SourceLocation.h"
260b57cec5SDimitry Andric #include "clang/Basic/TargetOptions.h"
270b57cec5SDimitry Andric #include "clang/Basic/Version.h"
280b57cec5SDimitry Andric #include "clang/Basic/Visibility.h"
290b57cec5SDimitry Andric #include "clang/Basic/XRayInstr.h"
300b57cec5SDimitry Andric #include "clang/Config/config.h"
310b57cec5SDimitry Andric #include "clang/Driver/Driver.h"
320b57cec5SDimitry Andric #include "clang/Driver/DriverDiagnostic.h"
330b57cec5SDimitry Andric #include "clang/Driver/Options.h"
340b57cec5SDimitry Andric #include "clang/Frontend/CommandLineSourceLoc.h"
350b57cec5SDimitry Andric #include "clang/Frontend/DependencyOutputOptions.h"
360b57cec5SDimitry Andric #include "clang/Frontend/FrontendDiagnostic.h"
370b57cec5SDimitry Andric #include "clang/Frontend/FrontendOptions.h"
380b57cec5SDimitry Andric #include "clang/Frontend/FrontendPluginRegistry.h"
390b57cec5SDimitry Andric #include "clang/Frontend/MigratorOptions.h"
400b57cec5SDimitry Andric #include "clang/Frontend/PreprocessorOutputOptions.h"
415f7ddb14SDimitry Andric #include "clang/Frontend/TextDiagnosticBuffer.h"
420b57cec5SDimitry Andric #include "clang/Frontend/Utils.h"
430b57cec5SDimitry Andric #include "clang/Lex/HeaderSearchOptions.h"
440b57cec5SDimitry Andric #include "clang/Lex/PreprocessorOptions.h"
450b57cec5SDimitry Andric #include "clang/Sema/CodeCompleteOptions.h"
465ffd83dbSDimitry Andric #include "clang/Serialization/ASTBitCodes.h"
470b57cec5SDimitry Andric #include "clang/Serialization/ModuleFileExtension.h"
480b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
490b57cec5SDimitry Andric #include "llvm/ADT/APInt.h"
500b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h"
510b57cec5SDimitry Andric #include "llvm/ADT/CachedHashString.h"
525f7ddb14SDimitry Andric #include "llvm/ADT/DenseSet.h"
535ffd83dbSDimitry Andric #include "llvm/ADT/FloatingPointMode.h"
540b57cec5SDimitry Andric #include "llvm/ADT/Hashing.h"
550b57cec5SDimitry Andric #include "llvm/ADT/None.h"
560b57cec5SDimitry Andric #include "llvm/ADT/Optional.h"
575f7ddb14SDimitry Andric #include "llvm/ADT/STLExtras.h"
580b57cec5SDimitry Andric #include "llvm/ADT/SmallString.h"
590b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
600b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
610b57cec5SDimitry Andric #include "llvm/ADT/StringSwitch.h"
620b57cec5SDimitry Andric #include "llvm/ADT/Triple.h"
630b57cec5SDimitry Andric #include "llvm/ADT/Twine.h"
64af732203SDimitry Andric #include "llvm/Config/llvm-config.h"
650b57cec5SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
660b57cec5SDimitry Andric #include "llvm/Linker/Linker.h"
670b57cec5SDimitry Andric #include "llvm/MC/MCTargetOptions.h"
680b57cec5SDimitry Andric #include "llvm/Option/Arg.h"
690b57cec5SDimitry Andric #include "llvm/Option/ArgList.h"
700b57cec5SDimitry Andric #include "llvm/Option/OptSpecifier.h"
710b57cec5SDimitry Andric #include "llvm/Option/OptTable.h"
720b57cec5SDimitry Andric #include "llvm/Option/Option.h"
730b57cec5SDimitry Andric #include "llvm/ProfileData/InstrProfReader.h"
74af732203SDimitry Andric #include "llvm/Remarks/HotnessThresholdParser.h"
750b57cec5SDimitry Andric #include "llvm/Support/CodeGen.h"
760b57cec5SDimitry Andric #include "llvm/Support/Compiler.h"
770b57cec5SDimitry Andric #include "llvm/Support/Error.h"
780b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
790b57cec5SDimitry Andric #include "llvm/Support/ErrorOr.h"
800b57cec5SDimitry Andric #include "llvm/Support/FileSystem.h"
810b57cec5SDimitry Andric #include "llvm/Support/Host.h"
820b57cec5SDimitry Andric #include "llvm/Support/MathExtras.h"
830b57cec5SDimitry Andric #include "llvm/Support/MemoryBuffer.h"
840b57cec5SDimitry Andric #include "llvm/Support/Path.h"
850b57cec5SDimitry Andric #include "llvm/Support/Process.h"
860b57cec5SDimitry Andric #include "llvm/Support/Regex.h"
870b57cec5SDimitry Andric #include "llvm/Support/VersionTuple.h"
880b57cec5SDimitry Andric #include "llvm/Support/VirtualFileSystem.h"
890b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
900b57cec5SDimitry Andric #include "llvm/Target/TargetOptions.h"
910b57cec5SDimitry Andric #include <algorithm>
920b57cec5SDimitry Andric #include <atomic>
930b57cec5SDimitry Andric #include <cassert>
940b57cec5SDimitry Andric #include <cstddef>
950b57cec5SDimitry Andric #include <cstring>
960b57cec5SDimitry Andric #include <memory>
970b57cec5SDimitry Andric #include <string>
980b57cec5SDimitry Andric #include <tuple>
99af732203SDimitry Andric #include <type_traits>
1000b57cec5SDimitry Andric #include <utility>
1010b57cec5SDimitry Andric #include <vector>
1020b57cec5SDimitry Andric 
1030b57cec5SDimitry Andric using namespace clang;
1040b57cec5SDimitry Andric using namespace driver;
1050b57cec5SDimitry Andric using namespace options;
1060b57cec5SDimitry Andric using namespace llvm::opt;
1070b57cec5SDimitry Andric 
1080b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1090b57cec5SDimitry Andric // Initialization.
1100b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1110b57cec5SDimitry Andric 
CompilerInvocationRefBase()1125f7ddb14SDimitry Andric CompilerInvocationRefBase::CompilerInvocationRefBase()
1130b57cec5SDimitry Andric     : LangOpts(new LangOptions()), TargetOpts(new TargetOptions()),
1140b57cec5SDimitry Andric       DiagnosticOpts(new DiagnosticOptions()),
1150b57cec5SDimitry Andric       HeaderSearchOpts(new HeaderSearchOptions()),
1165f7ddb14SDimitry Andric       PreprocessorOpts(new PreprocessorOptions()),
1175f7ddb14SDimitry Andric       AnalyzerOpts(new AnalyzerOptions()) {}
1180b57cec5SDimitry Andric 
CompilerInvocationRefBase(const CompilerInvocationRefBase & X)1195f7ddb14SDimitry Andric CompilerInvocationRefBase::CompilerInvocationRefBase(
1205f7ddb14SDimitry Andric     const CompilerInvocationRefBase &X)
1210b57cec5SDimitry Andric     : LangOpts(new LangOptions(*X.getLangOpts())),
1220b57cec5SDimitry Andric       TargetOpts(new TargetOptions(X.getTargetOpts())),
1230b57cec5SDimitry Andric       DiagnosticOpts(new DiagnosticOptions(X.getDiagnosticOpts())),
1240b57cec5SDimitry Andric       HeaderSearchOpts(new HeaderSearchOptions(X.getHeaderSearchOpts())),
1255f7ddb14SDimitry Andric       PreprocessorOpts(new PreprocessorOptions(X.getPreprocessorOpts())),
1265f7ddb14SDimitry Andric       AnalyzerOpts(new AnalyzerOptions(*X.getAnalyzerOpts())) {}
1270b57cec5SDimitry Andric 
1285f7ddb14SDimitry Andric CompilerInvocationRefBase::CompilerInvocationRefBase(
1295f7ddb14SDimitry Andric     CompilerInvocationRefBase &&X) = default;
1305f7ddb14SDimitry Andric 
1315f7ddb14SDimitry Andric CompilerInvocationRefBase &
operator =(CompilerInvocationRefBase X)1325f7ddb14SDimitry Andric CompilerInvocationRefBase::operator=(CompilerInvocationRefBase X) {
1335f7ddb14SDimitry Andric   LangOpts.swap(X.LangOpts);
1345f7ddb14SDimitry Andric   TargetOpts.swap(X.TargetOpts);
1355f7ddb14SDimitry Andric   DiagnosticOpts.swap(X.DiagnosticOpts);
1365f7ddb14SDimitry Andric   HeaderSearchOpts.swap(X.HeaderSearchOpts);
1375f7ddb14SDimitry Andric   PreprocessorOpts.swap(X.PreprocessorOpts);
1385f7ddb14SDimitry Andric   AnalyzerOpts.swap(X.AnalyzerOpts);
1395f7ddb14SDimitry Andric   return *this;
1405f7ddb14SDimitry Andric }
1415f7ddb14SDimitry Andric 
1425f7ddb14SDimitry Andric CompilerInvocationRefBase &
1435f7ddb14SDimitry Andric CompilerInvocationRefBase::operator=(CompilerInvocationRefBase &&X) = default;
1445f7ddb14SDimitry Andric 
1455f7ddb14SDimitry Andric CompilerInvocationRefBase::~CompilerInvocationRefBase() = default;
1460b57cec5SDimitry Andric 
1470b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1485ffd83dbSDimitry Andric // Normalizers
1495ffd83dbSDimitry Andric //===----------------------------------------------------------------------===//
1505ffd83dbSDimitry Andric 
1515ffd83dbSDimitry Andric #define SIMPLE_ENUM_VALUE_TABLE
1525ffd83dbSDimitry Andric #include "clang/Driver/Options.inc"
1535ffd83dbSDimitry Andric #undef SIMPLE_ENUM_VALUE_TABLE
1545ffd83dbSDimitry Andric 
normalizeSimpleFlag(OptSpecifier Opt,unsigned TableIndex,const ArgList & Args,DiagnosticsEngine & Diags)1555f7ddb14SDimitry Andric static llvm::Optional<bool> normalizeSimpleFlag(OptSpecifier Opt,
1565f7ddb14SDimitry Andric                                                 unsigned TableIndex,
1575f7ddb14SDimitry Andric                                                 const ArgList &Args,
1585f7ddb14SDimitry Andric                                                 DiagnosticsEngine &Diags) {
159af732203SDimitry Andric   if (Args.hasArg(Opt))
160af732203SDimitry Andric     return true;
161af732203SDimitry Andric   return None;
162af732203SDimitry Andric }
163af732203SDimitry Andric 
normalizeSimpleNegativeFlag(OptSpecifier Opt,unsigned,const ArgList & Args,DiagnosticsEngine &)164af732203SDimitry Andric static Optional<bool> normalizeSimpleNegativeFlag(OptSpecifier Opt, unsigned,
1655ffd83dbSDimitry Andric                                                   const ArgList &Args,
1665f7ddb14SDimitry Andric                                                   DiagnosticsEngine &) {
167af732203SDimitry Andric   if (Args.hasArg(Opt))
168af732203SDimitry Andric     return false;
169af732203SDimitry Andric   return None;
170af732203SDimitry Andric }
171af732203SDimitry Andric 
172af732203SDimitry Andric /// The tblgen-erated code passes in a fifth parameter of an arbitrary type, but
173af732203SDimitry Andric /// denormalizeSimpleFlags never looks at it. Avoid bloating compile-time with
174af732203SDimitry Andric /// unnecessary template instantiations and just ignore it with a variadic
175af732203SDimitry Andric /// argument.
denormalizeSimpleFlag(SmallVectorImpl<const char * > & Args,const char * Spelling,CompilerInvocation::StringAllocator,Option::OptionClass,unsigned,...)176af732203SDimitry Andric static void denormalizeSimpleFlag(SmallVectorImpl<const char *> &Args,
177af732203SDimitry Andric                                   const char *Spelling,
178af732203SDimitry Andric                                   CompilerInvocation::StringAllocator,
179af732203SDimitry Andric                                   Option::OptionClass, unsigned, /*T*/...) {
180af732203SDimitry Andric   Args.push_back(Spelling);
181af732203SDimitry Andric }
182af732203SDimitry Andric 
is_uint64_t_convertible()183af732203SDimitry Andric template <typename T> static constexpr bool is_uint64_t_convertible() {
184af732203SDimitry Andric   return !std::is_same<T, uint64_t>::value &&
185af732203SDimitry Andric          llvm::is_integral_or_enum<T>::value;
186af732203SDimitry Andric }
187af732203SDimitry Andric 
188af732203SDimitry Andric template <typename T,
189af732203SDimitry Andric           std::enable_if_t<!is_uint64_t_convertible<T>(), bool> = false>
makeFlagToValueNormalizer(T Value)190af732203SDimitry Andric static auto makeFlagToValueNormalizer(T Value) {
191af732203SDimitry Andric   return [Value](OptSpecifier Opt, unsigned, const ArgList &Args,
1925f7ddb14SDimitry Andric                  DiagnosticsEngine &) -> Optional<T> {
193af732203SDimitry Andric     if (Args.hasArg(Opt))
194af732203SDimitry Andric       return Value;
195af732203SDimitry Andric     return None;
196af732203SDimitry Andric   };
197af732203SDimitry Andric }
198af732203SDimitry Andric 
199af732203SDimitry Andric template <typename T,
200af732203SDimitry Andric           std::enable_if_t<is_uint64_t_convertible<T>(), bool> = false>
makeFlagToValueNormalizer(T Value)201af732203SDimitry Andric static auto makeFlagToValueNormalizer(T Value) {
202af732203SDimitry Andric   return makeFlagToValueNormalizer(uint64_t(Value));
203af732203SDimitry Andric }
204af732203SDimitry Andric 
makeBooleanOptionNormalizer(bool Value,bool OtherValue,OptSpecifier OtherOpt)205af732203SDimitry Andric static auto makeBooleanOptionNormalizer(bool Value, bool OtherValue,
206af732203SDimitry Andric                                         OptSpecifier OtherOpt) {
207af732203SDimitry Andric   return [Value, OtherValue, OtherOpt](OptSpecifier Opt, unsigned,
2085f7ddb14SDimitry Andric                                        const ArgList &Args,
2095f7ddb14SDimitry Andric                                        DiagnosticsEngine &) -> Optional<bool> {
210af732203SDimitry Andric     if (const Arg *A = Args.getLastArg(Opt, OtherOpt)) {
211af732203SDimitry Andric       return A->getOption().matches(Opt) ? Value : OtherValue;
212af732203SDimitry Andric     }
213af732203SDimitry Andric     return None;
214af732203SDimitry Andric   };
215af732203SDimitry Andric }
216af732203SDimitry Andric 
makeBooleanOptionDenormalizer(bool Value)217af732203SDimitry Andric static auto makeBooleanOptionDenormalizer(bool Value) {
218af732203SDimitry Andric   return [Value](SmallVectorImpl<const char *> &Args, const char *Spelling,
219af732203SDimitry Andric                  CompilerInvocation::StringAllocator, Option::OptionClass,
220af732203SDimitry Andric                  unsigned, bool KeyPath) {
221af732203SDimitry Andric     if (KeyPath == Value)
222af732203SDimitry Andric       Args.push_back(Spelling);
223af732203SDimitry Andric   };
224af732203SDimitry Andric }
225af732203SDimitry Andric 
denormalizeStringImpl(SmallVectorImpl<const char * > & Args,const char * Spelling,CompilerInvocation::StringAllocator SA,Option::OptionClass OptClass,unsigned,const Twine & Value)226af732203SDimitry Andric static void denormalizeStringImpl(SmallVectorImpl<const char *> &Args,
227af732203SDimitry Andric                                   const char *Spelling,
228af732203SDimitry Andric                                   CompilerInvocation::StringAllocator SA,
229af732203SDimitry Andric                                   Option::OptionClass OptClass, unsigned,
2305f7ddb14SDimitry Andric                                   const Twine &Value) {
231af732203SDimitry Andric   switch (OptClass) {
232af732203SDimitry Andric   case Option::SeparateClass:
233af732203SDimitry Andric   case Option::JoinedOrSeparateClass:
2345f7ddb14SDimitry Andric   case Option::JoinedAndSeparateClass:
235af732203SDimitry Andric     Args.push_back(Spelling);
236af732203SDimitry Andric     Args.push_back(SA(Value));
237af732203SDimitry Andric     break;
238af732203SDimitry Andric   case Option::JoinedClass:
2395f7ddb14SDimitry Andric   case Option::CommaJoinedClass:
240af732203SDimitry Andric     Args.push_back(SA(Twine(Spelling) + Value));
241af732203SDimitry Andric     break;
242af732203SDimitry Andric   default:
243af732203SDimitry Andric     llvm_unreachable("Cannot denormalize an option with option class "
244af732203SDimitry Andric                      "incompatible with string denormalization.");
245af732203SDimitry Andric   }
246af732203SDimitry Andric }
247af732203SDimitry Andric 
248af732203SDimitry Andric template <typename T>
249af732203SDimitry Andric static void
denormalizeString(SmallVectorImpl<const char * > & Args,const char * Spelling,CompilerInvocation::StringAllocator SA,Option::OptionClass OptClass,unsigned TableIndex,T Value)250af732203SDimitry Andric denormalizeString(SmallVectorImpl<const char *> &Args, const char *Spelling,
251af732203SDimitry Andric                   CompilerInvocation::StringAllocator SA,
252af732203SDimitry Andric                   Option::OptionClass OptClass, unsigned TableIndex, T Value) {
253af732203SDimitry Andric   denormalizeStringImpl(Args, Spelling, SA, OptClass, TableIndex, Twine(Value));
254af732203SDimitry Andric }
255af732203SDimitry Andric 
256af732203SDimitry Andric static Optional<SimpleEnumValue>
findValueTableByName(const SimpleEnumValueTable & Table,StringRef Name)257af732203SDimitry Andric findValueTableByName(const SimpleEnumValueTable &Table, StringRef Name) {
258af732203SDimitry Andric   for (int I = 0, E = Table.Size; I != E; ++I)
259af732203SDimitry Andric     if (Name == Table.Table[I].Name)
260af732203SDimitry Andric       return Table.Table[I];
261af732203SDimitry Andric 
262af732203SDimitry Andric   return None;
263af732203SDimitry Andric }
264af732203SDimitry Andric 
265af732203SDimitry Andric static Optional<SimpleEnumValue>
findValueTableByValue(const SimpleEnumValueTable & Table,unsigned Value)266af732203SDimitry Andric findValueTableByValue(const SimpleEnumValueTable &Table, unsigned Value) {
267af732203SDimitry Andric   for (int I = 0, E = Table.Size; I != E; ++I)
268af732203SDimitry Andric     if (Value == Table.Table[I].Value)
269af732203SDimitry Andric       return Table.Table[I];
270af732203SDimitry Andric 
271af732203SDimitry Andric   return None;
272af732203SDimitry Andric }
273af732203SDimitry Andric 
normalizeSimpleEnum(OptSpecifier Opt,unsigned TableIndex,const ArgList & Args,DiagnosticsEngine & Diags)2745f7ddb14SDimitry Andric static llvm::Optional<unsigned> normalizeSimpleEnum(OptSpecifier Opt,
2755f7ddb14SDimitry Andric                                                     unsigned TableIndex,
2765f7ddb14SDimitry Andric                                                     const ArgList &Args,
2775f7ddb14SDimitry Andric                                                     DiagnosticsEngine &Diags) {
2785ffd83dbSDimitry Andric   assert(TableIndex < SimpleEnumValueTablesSize);
2795ffd83dbSDimitry Andric   const SimpleEnumValueTable &Table = SimpleEnumValueTables[TableIndex];
2805ffd83dbSDimitry Andric 
2815ffd83dbSDimitry Andric   auto *Arg = Args.getLastArg(Opt);
2825ffd83dbSDimitry Andric   if (!Arg)
2835ffd83dbSDimitry Andric     return None;
2845ffd83dbSDimitry Andric 
2855ffd83dbSDimitry Andric   StringRef ArgValue = Arg->getValue();
286af732203SDimitry Andric   if (auto MaybeEnumVal = findValueTableByName(Table, ArgValue))
287af732203SDimitry Andric     return MaybeEnumVal->Value;
2885ffd83dbSDimitry Andric 
2895ffd83dbSDimitry Andric   Diags.Report(diag::err_drv_invalid_value)
2905ffd83dbSDimitry Andric       << Arg->getAsString(Args) << ArgValue;
2915ffd83dbSDimitry Andric   return None;
2925ffd83dbSDimitry Andric }
2935ffd83dbSDimitry Andric 
denormalizeSimpleEnumImpl(SmallVectorImpl<const char * > & Args,const char * Spelling,CompilerInvocation::StringAllocator SA,Option::OptionClass OptClass,unsigned TableIndex,unsigned Value)294af732203SDimitry Andric static void denormalizeSimpleEnumImpl(SmallVectorImpl<const char *> &Args,
295af732203SDimitry Andric                                       const char *Spelling,
296af732203SDimitry Andric                                       CompilerInvocation::StringAllocator SA,
297af732203SDimitry Andric                                       Option::OptionClass OptClass,
2985ffd83dbSDimitry Andric                                       unsigned TableIndex, unsigned Value) {
2995ffd83dbSDimitry Andric   assert(TableIndex < SimpleEnumValueTablesSize);
3005ffd83dbSDimitry Andric   const SimpleEnumValueTable &Table = SimpleEnumValueTables[TableIndex];
301af732203SDimitry Andric   if (auto MaybeEnumVal = findValueTableByValue(Table, Value)) {
302af732203SDimitry Andric     denormalizeString(Args, Spelling, SA, OptClass, TableIndex,
303af732203SDimitry Andric                       MaybeEnumVal->Name);
304af732203SDimitry Andric   } else {
3055ffd83dbSDimitry Andric     llvm_unreachable("The simple enum value was not correctly defined in "
3065ffd83dbSDimitry Andric                      "the tablegen option description");
3075ffd83dbSDimitry Andric   }
308af732203SDimitry Andric }
3095ffd83dbSDimitry Andric 
310af732203SDimitry Andric template <typename T>
denormalizeSimpleEnum(SmallVectorImpl<const char * > & Args,const char * Spelling,CompilerInvocation::StringAllocator SA,Option::OptionClass OptClass,unsigned TableIndex,T Value)311af732203SDimitry Andric static void denormalizeSimpleEnum(SmallVectorImpl<const char *> &Args,
312af732203SDimitry Andric                                   const char *Spelling,
313af732203SDimitry Andric                                   CompilerInvocation::StringAllocator SA,
314af732203SDimitry Andric                                   Option::OptionClass OptClass,
315af732203SDimitry Andric                                   unsigned TableIndex, T Value) {
316af732203SDimitry Andric   return denormalizeSimpleEnumImpl(Args, Spelling, SA, OptClass, TableIndex,
317af732203SDimitry Andric                                    static_cast<unsigned>(Value));
318af732203SDimitry Andric }
319af732203SDimitry Andric 
normalizeString(OptSpecifier Opt,int TableIndex,const ArgList & Args,DiagnosticsEngine & Diags)320af732203SDimitry Andric static Optional<std::string> normalizeString(OptSpecifier Opt, int TableIndex,
321af732203SDimitry Andric                                              const ArgList &Args,
3225f7ddb14SDimitry Andric                                              DiagnosticsEngine &Diags) {
323af732203SDimitry Andric   auto *Arg = Args.getLastArg(Opt);
324af732203SDimitry Andric   if (!Arg)
325af732203SDimitry Andric     return None;
326af732203SDimitry Andric   return std::string(Arg->getValue());
327af732203SDimitry Andric }
328af732203SDimitry Andric 
329af732203SDimitry Andric template <typename IntTy>
normalizeStringIntegral(OptSpecifier Opt,int,const ArgList & Args,DiagnosticsEngine & Diags)3305f7ddb14SDimitry Andric static Optional<IntTy> normalizeStringIntegral(OptSpecifier Opt, int,
3315f7ddb14SDimitry Andric                                                const ArgList &Args,
3325f7ddb14SDimitry Andric                                                DiagnosticsEngine &Diags) {
333af732203SDimitry Andric   auto *Arg = Args.getLastArg(Opt);
334af732203SDimitry Andric   if (!Arg)
335af732203SDimitry Andric     return None;
336af732203SDimitry Andric   IntTy Res;
337af732203SDimitry Andric   if (StringRef(Arg->getValue()).getAsInteger(0, Res)) {
338af732203SDimitry Andric     Diags.Report(diag::err_drv_invalid_int_value)
339af732203SDimitry Andric         << Arg->getAsString(Args) << Arg->getValue();
340af732203SDimitry Andric     return None;
341af732203SDimitry Andric   }
342af732203SDimitry Andric   return Res;
343af732203SDimitry Andric }
344af732203SDimitry Andric 
345af732203SDimitry Andric static Optional<std::vector<std::string>>
normalizeStringVector(OptSpecifier Opt,int,const ArgList & Args,DiagnosticsEngine &)346af732203SDimitry Andric normalizeStringVector(OptSpecifier Opt, int, const ArgList &Args,
3475f7ddb14SDimitry Andric                       DiagnosticsEngine &) {
348af732203SDimitry Andric   return Args.getAllArgValues(Opt);
349af732203SDimitry Andric }
350af732203SDimitry Andric 
denormalizeStringVector(SmallVectorImpl<const char * > & Args,const char * Spelling,CompilerInvocation::StringAllocator SA,Option::OptionClass OptClass,unsigned TableIndex,const std::vector<std::string> & Values)351af732203SDimitry Andric static void denormalizeStringVector(SmallVectorImpl<const char *> &Args,
352af732203SDimitry Andric                                     const char *Spelling,
353af732203SDimitry Andric                                     CompilerInvocation::StringAllocator SA,
354af732203SDimitry Andric                                     Option::OptionClass OptClass,
3555ffd83dbSDimitry Andric                                     unsigned TableIndex,
356af732203SDimitry Andric                                     const std::vector<std::string> &Values) {
357af732203SDimitry Andric   switch (OptClass) {
358af732203SDimitry Andric   case Option::CommaJoinedClass: {
359af732203SDimitry Andric     std::string CommaJoinedValue;
360af732203SDimitry Andric     if (!Values.empty()) {
361af732203SDimitry Andric       CommaJoinedValue.append(Values.front());
362af732203SDimitry Andric       for (const std::string &Value : llvm::drop_begin(Values, 1)) {
363af732203SDimitry Andric         CommaJoinedValue.append(",");
364af732203SDimitry Andric         CommaJoinedValue.append(Value);
365af732203SDimitry Andric       }
366af732203SDimitry Andric     }
367af732203SDimitry Andric     denormalizeString(Args, Spelling, SA, Option::OptionClass::JoinedClass,
368af732203SDimitry Andric                       TableIndex, CommaJoinedValue);
369af732203SDimitry Andric     break;
370af732203SDimitry Andric   }
371af732203SDimitry Andric   case Option::JoinedClass:
372af732203SDimitry Andric   case Option::SeparateClass:
373af732203SDimitry Andric   case Option::JoinedOrSeparateClass:
374af732203SDimitry Andric     for (const std::string &Value : Values)
375af732203SDimitry Andric       denormalizeString(Args, Spelling, SA, OptClass, TableIndex, Value);
376af732203SDimitry Andric     break;
377af732203SDimitry Andric   default:
378af732203SDimitry Andric     llvm_unreachable("Cannot denormalize an option with option class "
379af732203SDimitry Andric                      "incompatible with string vector denormalization.");
380af732203SDimitry Andric   }
3815ffd83dbSDimitry Andric }
3825ffd83dbSDimitry Andric 
normalizeTriple(OptSpecifier Opt,int TableIndex,const ArgList & Args,DiagnosticsEngine & Diags)3835ffd83dbSDimitry Andric static Optional<std::string> normalizeTriple(OptSpecifier Opt, int TableIndex,
3845ffd83dbSDimitry Andric                                              const ArgList &Args,
3855f7ddb14SDimitry Andric                                              DiagnosticsEngine &Diags) {
3865ffd83dbSDimitry Andric   auto *Arg = Args.getLastArg(Opt);
3875ffd83dbSDimitry Andric   if (!Arg)
3885ffd83dbSDimitry Andric     return None;
3895ffd83dbSDimitry Andric   return llvm::Triple::normalize(Arg->getValue());
3905ffd83dbSDimitry Andric }
3915ffd83dbSDimitry Andric 
392af732203SDimitry Andric template <typename T, typename U>
mergeForwardValue(T KeyPath,U Value)393af732203SDimitry Andric static T mergeForwardValue(T KeyPath, U Value) {
394af732203SDimitry Andric   return static_cast<T>(Value);
395af732203SDimitry Andric }
396af732203SDimitry Andric 
mergeMaskValue(T KeyPath,U Value)397af732203SDimitry Andric template <typename T, typename U> static T mergeMaskValue(T KeyPath, U Value) {
398af732203SDimitry Andric   return KeyPath | Value;
399af732203SDimitry Andric }
400af732203SDimitry Andric 
extractForwardValue(T KeyPath)401af732203SDimitry Andric template <typename T> static T extractForwardValue(T KeyPath) {
402af732203SDimitry Andric   return KeyPath;
403af732203SDimitry Andric }
404af732203SDimitry Andric 
405af732203SDimitry Andric template <typename T, typename U, U Value>
extractMaskValue(T KeyPath)406af732203SDimitry Andric static T extractMaskValue(T KeyPath) {
4075f7ddb14SDimitry Andric   return ((KeyPath & Value) == Value) ? static_cast<T>(Value) : T();
408af732203SDimitry Andric }
409af732203SDimitry Andric 
4105f7ddb14SDimitry Andric #define PARSE_OPTION_WITH_MARSHALLING(                                         \
4115f7ddb14SDimitry Andric     ARGS, DIAGS, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE,       \
4125f7ddb14SDimitry Andric     IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)             \
413af732203SDimitry Andric   if ((FLAGS)&options::CC1Option) {                                            \
414af732203SDimitry Andric     KEYPATH = MERGER(KEYPATH, DEFAULT_VALUE);                                  \
415af732203SDimitry Andric     if (IMPLIED_CHECK)                                                         \
416af732203SDimitry Andric       KEYPATH = MERGER(KEYPATH, IMPLIED_VALUE);                                \
417af732203SDimitry Andric     if (SHOULD_PARSE)                                                          \
4185f7ddb14SDimitry Andric       if (auto MaybeValue = NORMALIZER(OPT_##ID, TABLE_INDEX, ARGS, DIAGS))    \
419af732203SDimitry Andric         KEYPATH =                                                              \
420af732203SDimitry Andric             MERGER(KEYPATH, static_cast<decltype(KEYPATH)>(*MaybeValue));      \
421af732203SDimitry Andric   }
422af732203SDimitry Andric 
4235f7ddb14SDimitry Andric // Capture the extracted value as a lambda argument to avoid potential issues
4245f7ddb14SDimitry Andric // with lifetime extension of the reference.
4255f7ddb14SDimitry Andric #define GENERATE_OPTION_WITH_MARSHALLING(                                      \
4265f7ddb14SDimitry Andric     ARGS, STRING_ALLOCATOR, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH,       \
4275f7ddb14SDimitry Andric     DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR,      \
4285f7ddb14SDimitry Andric     TABLE_INDEX)                                                               \
4295f7ddb14SDimitry Andric   if ((FLAGS)&options::CC1Option) {                                            \
4305f7ddb14SDimitry Andric     [&](const auto &Extracted) {                                               \
4315f7ddb14SDimitry Andric       if (ALWAYS_EMIT ||                                                       \
4325f7ddb14SDimitry Andric           (Extracted !=                                                        \
4335f7ddb14SDimitry Andric            static_cast<decltype(KEYPATH)>((IMPLIED_CHECK) ? (IMPLIED_VALUE)    \
4345f7ddb14SDimitry Andric                                                           : (DEFAULT_VALUE)))) \
4355f7ddb14SDimitry Andric         DENORMALIZER(ARGS, SPELLING, STRING_ALLOCATOR, Option::KIND##Class,    \
4365f7ddb14SDimitry Andric                      TABLE_INDEX, Extracted);                                  \
4375f7ddb14SDimitry Andric     }(EXTRACTOR(KEYPATH));                                                     \
4385f7ddb14SDimitry Andric   }
4395f7ddb14SDimitry Andric 
440af732203SDimitry Andric static const StringRef GetInputKindName(InputKind IK);
441af732203SDimitry Andric 
FixupInvocation(CompilerInvocation & Invocation,DiagnosticsEngine & Diags,const ArgList & Args,InputKind IK)4425f7ddb14SDimitry Andric static bool FixupInvocation(CompilerInvocation &Invocation,
4435f7ddb14SDimitry Andric                             DiagnosticsEngine &Diags, const ArgList &Args,
444af732203SDimitry Andric                             InputKind IK) {
4455f7ddb14SDimitry Andric   unsigned NumErrorsBefore = Diags.getNumErrors();
4465f7ddb14SDimitry Andric 
447af732203SDimitry Andric   LangOptions &LangOpts = *Invocation.getLangOpts();
448af732203SDimitry Andric   CodeGenOptions &CodeGenOpts = Invocation.getCodeGenOpts();
449af732203SDimitry Andric   TargetOptions &TargetOpts = Invocation.getTargetOpts();
450af732203SDimitry Andric   FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
451af732203SDimitry Andric   CodeGenOpts.XRayInstrumentFunctions = LangOpts.XRayInstrument;
452af732203SDimitry Andric   CodeGenOpts.XRayAlwaysEmitCustomEvents = LangOpts.XRayAlwaysEmitCustomEvents;
453af732203SDimitry Andric   CodeGenOpts.XRayAlwaysEmitTypedEvents = LangOpts.XRayAlwaysEmitTypedEvents;
454af732203SDimitry Andric   CodeGenOpts.DisableFree = FrontendOpts.DisableFree;
455af732203SDimitry Andric   FrontendOpts.GenerateGlobalModuleIndex = FrontendOpts.UseGlobalModuleIndex;
4565f7ddb14SDimitry Andric   LangOpts.SanitizeCoverage = CodeGenOpts.hasSanitizeCoverage();
457af732203SDimitry Andric   LangOpts.ForceEmitVTables = CodeGenOpts.ForceEmitVTables;
458af732203SDimitry Andric   LangOpts.SpeculativeLoadHardening = CodeGenOpts.SpeculativeLoadHardening;
459af732203SDimitry Andric   LangOpts.CurrentModule = LangOpts.ModuleName;
460af732203SDimitry Andric 
461af732203SDimitry Andric   llvm::Triple T(TargetOpts.Triple);
462af732203SDimitry Andric   llvm::Triple::ArchType Arch = T.getArch();
463af732203SDimitry Andric 
464af732203SDimitry Andric   CodeGenOpts.CodeModel = TargetOpts.CodeModel;
465af732203SDimitry Andric 
4665f7ddb14SDimitry Andric   if (LangOpts.getExceptionHandling() !=
4675f7ddb14SDimitry Andric           LangOptions::ExceptionHandlingKind::None &&
468af732203SDimitry Andric       T.isWindowsMSVCEnvironment())
469af732203SDimitry Andric     Diags.Report(diag::err_fe_invalid_exception_model)
470af732203SDimitry Andric         << static_cast<unsigned>(LangOpts.getExceptionHandling()) << T.str();
471af732203SDimitry Andric 
472af732203SDimitry Andric   if (LangOpts.AppleKext && !LangOpts.CPlusPlus)
473af732203SDimitry Andric     Diags.Report(diag::warn_c_kext);
474af732203SDimitry Andric 
4755f7ddb14SDimitry Andric   if (Args.hasArg(OPT_fconcepts_ts))
4765f7ddb14SDimitry Andric     Diags.Report(diag::warn_fe_concepts_ts_flag);
4775f7ddb14SDimitry Andric 
478af732203SDimitry Andric   if (LangOpts.NewAlignOverride &&
479af732203SDimitry Andric       !llvm::isPowerOf2_32(LangOpts.NewAlignOverride)) {
480af732203SDimitry Andric     Arg *A = Args.getLastArg(OPT_fnew_alignment_EQ);
481af732203SDimitry Andric     Diags.Report(diag::err_fe_invalid_alignment)
482af732203SDimitry Andric         << A->getAsString(Args) << A->getValue();
483af732203SDimitry Andric     LangOpts.NewAlignOverride = 0;
484af732203SDimitry Andric   }
485af732203SDimitry Andric 
4865f7ddb14SDimitry Andric   // Prevent the user from specifying both -fsycl-is-device and -fsycl-is-host.
4875f7ddb14SDimitry Andric   if (LangOpts.SYCLIsDevice && LangOpts.SYCLIsHost)
4885f7ddb14SDimitry Andric     Diags.Report(diag::err_drv_argument_not_allowed_with) << "-fsycl-is-device"
4895f7ddb14SDimitry Andric                                                           << "-fsycl-is-host";
4905f7ddb14SDimitry Andric 
491af732203SDimitry Andric   if (Args.hasArg(OPT_fgnu89_inline) && LangOpts.CPlusPlus)
492af732203SDimitry Andric     Diags.Report(diag::err_drv_argument_not_allowed_with)
493af732203SDimitry Andric         << "-fgnu89-inline" << GetInputKindName(IK);
494af732203SDimitry Andric 
495af732203SDimitry Andric   if (Args.hasArg(OPT_fgpu_allow_device_init) && !LangOpts.HIP)
496af732203SDimitry Andric     Diags.Report(diag::warn_ignored_hip_only_option)
497af732203SDimitry Andric         << Args.getLastArg(OPT_fgpu_allow_device_init)->getAsString(Args);
498af732203SDimitry Andric 
499af732203SDimitry Andric   if (Args.hasArg(OPT_gpu_max_threads_per_block_EQ) && !LangOpts.HIP)
500af732203SDimitry Andric     Diags.Report(diag::warn_ignored_hip_only_option)
501af732203SDimitry Andric         << Args.getLastArg(OPT_gpu_max_threads_per_block_EQ)->getAsString(Args);
502af732203SDimitry Andric 
503af732203SDimitry Andric   // -cl-strict-aliasing needs to emit diagnostic in the case where CL > 1.0.
504af732203SDimitry Andric   // This option should be deprecated for CL > 1.0 because
505af732203SDimitry Andric   // this option was added for compatibility with OpenCL 1.0.
506af732203SDimitry Andric   if (Args.getLastArg(OPT_cl_strict_aliasing) && LangOpts.OpenCLVersion > 100)
507af732203SDimitry Andric     Diags.Report(diag::warn_option_invalid_ocl_version)
508af732203SDimitry Andric         << LangOpts.getOpenCLVersionTuple().getAsString()
509af732203SDimitry Andric         << Args.getLastArg(OPT_cl_strict_aliasing)->getAsString(Args);
510af732203SDimitry Andric 
511af732203SDimitry Andric   if (Arg *A = Args.getLastArg(OPT_fdefault_calling_conv_EQ)) {
512af732203SDimitry Andric     auto DefaultCC = LangOpts.getDefaultCallingConv();
513af732203SDimitry Andric 
514af732203SDimitry Andric     bool emitError = (DefaultCC == LangOptions::DCC_FastCall ||
515af732203SDimitry Andric                       DefaultCC == LangOptions::DCC_StdCall) &&
516af732203SDimitry Andric                      Arch != llvm::Triple::x86;
517af732203SDimitry Andric     emitError |= (DefaultCC == LangOptions::DCC_VectorCall ||
518af732203SDimitry Andric                   DefaultCC == LangOptions::DCC_RegCall) &&
519af732203SDimitry Andric                  !T.isX86();
520af732203SDimitry Andric     if (emitError)
521af732203SDimitry Andric       Diags.Report(diag::err_drv_argument_not_allowed_with)
522af732203SDimitry Andric           << A->getSpelling() << T.getTriple();
523af732203SDimitry Andric   }
524af732203SDimitry Andric 
525af732203SDimitry Andric   if (!CodeGenOpts.ProfileRemappingFile.empty() && CodeGenOpts.LegacyPassManager)
526af732203SDimitry Andric     Diags.Report(diag::err_drv_argument_only_allowed_with)
527af732203SDimitry Andric         << Args.getLastArg(OPT_fprofile_remapping_file_EQ)->getAsString(Args)
528af732203SDimitry Andric         << "-fno-legacy-pass-manager";
5295f7ddb14SDimitry Andric 
5305f7ddb14SDimitry Andric   return Diags.getNumErrors() == NumErrorsBefore;
531af732203SDimitry Andric }
532af732203SDimitry Andric 
5335ffd83dbSDimitry Andric //===----------------------------------------------------------------------===//
5340b57cec5SDimitry Andric // Deserialization (from args)
5350b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
5360b57cec5SDimitry Andric 
getOptimizationLevel(ArgList & Args,InputKind IK,DiagnosticsEngine & Diags)5370b57cec5SDimitry Andric static unsigned getOptimizationLevel(ArgList &Args, InputKind IK,
5380b57cec5SDimitry Andric                                      DiagnosticsEngine &Diags) {
5390b57cec5SDimitry Andric   unsigned DefaultOpt = llvm::CodeGenOpt::None;
5405f7ddb14SDimitry Andric   if ((IK.getLanguage() == Language::OpenCL ||
5415f7ddb14SDimitry Andric        IK.getLanguage() == Language::OpenCLCXX) &&
5425f7ddb14SDimitry Andric       !Args.hasArg(OPT_cl_opt_disable))
5430b57cec5SDimitry Andric     DefaultOpt = llvm::CodeGenOpt::Default;
5440b57cec5SDimitry Andric 
5450b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
5460b57cec5SDimitry Andric     if (A->getOption().matches(options::OPT_O0))
5470b57cec5SDimitry Andric       return llvm::CodeGenOpt::None;
5480b57cec5SDimitry Andric 
5490b57cec5SDimitry Andric     if (A->getOption().matches(options::OPT_Ofast))
5500b57cec5SDimitry Andric       return llvm::CodeGenOpt::Aggressive;
5510b57cec5SDimitry Andric 
5520b57cec5SDimitry Andric     assert(A->getOption().matches(options::OPT_O));
5530b57cec5SDimitry Andric 
5540b57cec5SDimitry Andric     StringRef S(A->getValue());
5555ffd83dbSDimitry Andric     if (S == "s" || S == "z")
5560b57cec5SDimitry Andric       return llvm::CodeGenOpt::Default;
5570b57cec5SDimitry Andric 
5580b57cec5SDimitry Andric     if (S == "g")
5590b57cec5SDimitry Andric       return llvm::CodeGenOpt::Less;
5600b57cec5SDimitry Andric 
5610b57cec5SDimitry Andric     return getLastArgIntValue(Args, OPT_O, DefaultOpt, Diags);
5620b57cec5SDimitry Andric   }
5630b57cec5SDimitry Andric 
5640b57cec5SDimitry Andric   return DefaultOpt;
5650b57cec5SDimitry Andric }
5660b57cec5SDimitry Andric 
getOptimizationLevelSize(ArgList & Args)5670b57cec5SDimitry Andric static unsigned getOptimizationLevelSize(ArgList &Args) {
5680b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
5690b57cec5SDimitry Andric     if (A->getOption().matches(options::OPT_O)) {
5700b57cec5SDimitry Andric       switch (A->getValue()[0]) {
5710b57cec5SDimitry Andric       default:
5720b57cec5SDimitry Andric         return 0;
5730b57cec5SDimitry Andric       case 's':
5740b57cec5SDimitry Andric         return 1;
5750b57cec5SDimitry Andric       case 'z':
5760b57cec5SDimitry Andric         return 2;
5770b57cec5SDimitry Andric       }
5780b57cec5SDimitry Andric     }
5790b57cec5SDimitry Andric   }
5800b57cec5SDimitry Andric   return 0;
5810b57cec5SDimitry Andric }
5820b57cec5SDimitry Andric 
GenerateArg(SmallVectorImpl<const char * > & Args,llvm::opt::OptSpecifier OptSpecifier,CompilerInvocation::StringAllocator SA)5835f7ddb14SDimitry Andric static void GenerateArg(SmallVectorImpl<const char *> &Args,
5845f7ddb14SDimitry Andric                         llvm::opt::OptSpecifier OptSpecifier,
5855f7ddb14SDimitry Andric                         CompilerInvocation::StringAllocator SA) {
5865f7ddb14SDimitry Andric   Option Opt = getDriverOptTable().getOption(OptSpecifier);
5875f7ddb14SDimitry Andric   denormalizeSimpleFlag(Args, SA(Opt.getPrefix() + Opt.getName()), SA,
5885f7ddb14SDimitry Andric                         Option::OptionClass::FlagClass, 0);
5895f7ddb14SDimitry Andric }
5905f7ddb14SDimitry Andric 
GenerateArg(SmallVectorImpl<const char * > & Args,llvm::opt::OptSpecifier OptSpecifier,const Twine & Value,CompilerInvocation::StringAllocator SA)5915f7ddb14SDimitry Andric static void GenerateArg(SmallVectorImpl<const char *> &Args,
5925f7ddb14SDimitry Andric                         llvm::opt::OptSpecifier OptSpecifier,
5935f7ddb14SDimitry Andric                         const Twine &Value,
5945f7ddb14SDimitry Andric                         CompilerInvocation::StringAllocator SA) {
5955f7ddb14SDimitry Andric   Option Opt = getDriverOptTable().getOption(OptSpecifier);
5965f7ddb14SDimitry Andric   denormalizeString(Args, SA(Opt.getPrefix() + Opt.getName()), SA,
5975f7ddb14SDimitry Andric                     Opt.getKind(), 0, Value);
5985f7ddb14SDimitry Andric }
5995f7ddb14SDimitry Andric 
6005f7ddb14SDimitry Andric // Parse command line arguments into CompilerInvocation.
6015f7ddb14SDimitry Andric using ParseFn =
6025f7ddb14SDimitry Andric     llvm::function_ref<bool(CompilerInvocation &, ArrayRef<const char *>,
6035f7ddb14SDimitry Andric                             DiagnosticsEngine &, const char *)>;
6045f7ddb14SDimitry Andric 
6055f7ddb14SDimitry Andric // Generate command line arguments from CompilerInvocation.
6065f7ddb14SDimitry Andric using GenerateFn = llvm::function_ref<void(
6075f7ddb14SDimitry Andric     CompilerInvocation &, SmallVectorImpl<const char *> &,
6085f7ddb14SDimitry Andric     CompilerInvocation::StringAllocator)>;
6095f7ddb14SDimitry Andric 
6105f7ddb14SDimitry Andric // May perform round-trip of command line arguments. By default, the round-trip
6115f7ddb14SDimitry Andric // is enabled if CLANG_ROUND_TRIP_CC1_ARGS was defined during build. This can be
6125f7ddb14SDimitry Andric // overwritten at run-time via the "-round-trip-args" and "-no-round-trip-args"
6135f7ddb14SDimitry Andric // command line flags.
6145f7ddb14SDimitry Andric // During round-trip, the command line arguments are parsed into a dummy
6155f7ddb14SDimitry Andric // instance of CompilerInvocation which is used to generate the command line
6165f7ddb14SDimitry Andric // arguments again. The real CompilerInvocation instance is then created by
6175f7ddb14SDimitry Andric // 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)6185f7ddb14SDimitry Andric static bool RoundTrip(ParseFn Parse, GenerateFn Generate,
6195f7ddb14SDimitry Andric                       CompilerInvocation &RealInvocation,
6205f7ddb14SDimitry Andric                       CompilerInvocation &DummyInvocation,
6215f7ddb14SDimitry Andric                       ArrayRef<const char *> CommandLineArgs,
6225f7ddb14SDimitry Andric                       DiagnosticsEngine &Diags, const char *Argv0) {
6235f7ddb14SDimitry Andric   // FIXME: Switch to '#ifndef NDEBUG' when possible.
6245f7ddb14SDimitry Andric #ifdef CLANG_ROUND_TRIP_CC1_ARGS
6255f7ddb14SDimitry Andric   bool DoRoundTripDefault = true;
6265f7ddb14SDimitry Andric #else
6275f7ddb14SDimitry Andric   bool DoRoundTripDefault = false;
6285f7ddb14SDimitry Andric #endif
6295f7ddb14SDimitry Andric 
6305f7ddb14SDimitry Andric   bool DoRoundTrip = DoRoundTripDefault;
6315f7ddb14SDimitry Andric   for (const auto *Arg : CommandLineArgs) {
6325f7ddb14SDimitry Andric     if (Arg == StringRef("-round-trip-args"))
6335f7ddb14SDimitry Andric       DoRoundTrip = true;
6345f7ddb14SDimitry Andric     if (Arg == StringRef("-no-round-trip-args"))
6355f7ddb14SDimitry Andric       DoRoundTrip = false;
6365f7ddb14SDimitry Andric   }
6375f7ddb14SDimitry Andric 
6385f7ddb14SDimitry Andric   // If round-trip was not requested, simply run the parser with the real
6395f7ddb14SDimitry Andric   // invocation diagnostics.
6405f7ddb14SDimitry Andric   if (!DoRoundTrip)
6415f7ddb14SDimitry Andric     return Parse(RealInvocation, CommandLineArgs, Diags, Argv0);
6425f7ddb14SDimitry Andric 
6435f7ddb14SDimitry Andric   // Serializes quoted (and potentially escaped) arguments.
6445f7ddb14SDimitry Andric   auto SerializeArgs = [](ArrayRef<const char *> Args) {
6455f7ddb14SDimitry Andric     std::string Buffer;
6465f7ddb14SDimitry Andric     llvm::raw_string_ostream OS(Buffer);
6475f7ddb14SDimitry Andric     for (const char *Arg : Args) {
6485f7ddb14SDimitry Andric       llvm::sys::printArg(OS, Arg, /*Quote=*/true);
6495f7ddb14SDimitry Andric       OS << ' ';
6505f7ddb14SDimitry Andric     }
6515f7ddb14SDimitry Andric     OS.flush();
6525f7ddb14SDimitry Andric     return Buffer;
6535f7ddb14SDimitry Andric   };
6545f7ddb14SDimitry Andric 
6555f7ddb14SDimitry Andric   // Setup a dummy DiagnosticsEngine.
6565f7ddb14SDimitry Andric   DiagnosticsEngine DummyDiags(new DiagnosticIDs(), new DiagnosticOptions());
6575f7ddb14SDimitry Andric   DummyDiags.setClient(new TextDiagnosticBuffer());
6585f7ddb14SDimitry Andric 
6595f7ddb14SDimitry Andric   // Run the first parse on the original arguments with the dummy invocation and
6605f7ddb14SDimitry Andric   // diagnostics.
6615f7ddb14SDimitry Andric   if (!Parse(DummyInvocation, CommandLineArgs, DummyDiags, Argv0) ||
6625f7ddb14SDimitry Andric       DummyDiags.getNumWarnings() != 0) {
6635f7ddb14SDimitry Andric     // If the first parse did not succeed, it must be user mistake (invalid
6645f7ddb14SDimitry Andric     // command line arguments). We won't be able to generate arguments that
6655f7ddb14SDimitry Andric     // would reproduce the same result. Let's fail again with the real
6665f7ddb14SDimitry Andric     // invocation and diagnostics, so all side-effects of parsing are visible.
6675f7ddb14SDimitry Andric     unsigned NumWarningsBefore = Diags.getNumWarnings();
6685f7ddb14SDimitry Andric     auto Success = Parse(RealInvocation, CommandLineArgs, Diags, Argv0);
6695f7ddb14SDimitry Andric     if (!Success || Diags.getNumWarnings() != NumWarningsBefore)
6705f7ddb14SDimitry Andric       return Success;
6715f7ddb14SDimitry Andric 
6725f7ddb14SDimitry Andric     // Parse with original options and diagnostics succeeded even though it
6735f7ddb14SDimitry Andric     // shouldn't have. Something is off.
6745f7ddb14SDimitry Andric     Diags.Report(diag::err_cc1_round_trip_fail_then_ok);
6755f7ddb14SDimitry Andric     Diags.Report(diag::note_cc1_round_trip_original)
6765f7ddb14SDimitry Andric         << SerializeArgs(CommandLineArgs);
6775f7ddb14SDimitry Andric     return false;
6785f7ddb14SDimitry Andric   }
6795f7ddb14SDimitry Andric 
6805f7ddb14SDimitry Andric   // Setup string allocator.
6815f7ddb14SDimitry Andric   llvm::BumpPtrAllocator Alloc;
6825f7ddb14SDimitry Andric   llvm::StringSaver StringPool(Alloc);
6835f7ddb14SDimitry Andric   auto SA = [&StringPool](const Twine &Arg) {
6845f7ddb14SDimitry Andric     return StringPool.save(Arg).data();
6855f7ddb14SDimitry Andric   };
6865f7ddb14SDimitry Andric 
6875f7ddb14SDimitry Andric   // Generate arguments from the dummy invocation. If Generate is the
6885f7ddb14SDimitry Andric   // inverse of Parse, the newly generated arguments must have the same
6895f7ddb14SDimitry Andric   // semantics as the original.
6905f7ddb14SDimitry Andric   SmallVector<const char *> GeneratedArgs1;
6915f7ddb14SDimitry Andric   Generate(DummyInvocation, GeneratedArgs1, SA);
6925f7ddb14SDimitry Andric 
6935f7ddb14SDimitry Andric   // Run the second parse, now on the generated arguments, and with the real
6945f7ddb14SDimitry Andric   // invocation and diagnostics. The result is what we will end up using for the
6955f7ddb14SDimitry Andric   // rest of compilation, so if Generate is not inverse of Parse, something down
6965f7ddb14SDimitry Andric   // the line will break.
6975f7ddb14SDimitry Andric   bool Success2 = Parse(RealInvocation, GeneratedArgs1, Diags, Argv0);
6985f7ddb14SDimitry Andric 
6995f7ddb14SDimitry Andric   // The first parse on original arguments succeeded, but second parse of
7005f7ddb14SDimitry Andric   // generated arguments failed. Something must be wrong with the generator.
7015f7ddb14SDimitry Andric   if (!Success2) {
7025f7ddb14SDimitry Andric     Diags.Report(diag::err_cc1_round_trip_ok_then_fail);
7035f7ddb14SDimitry Andric     Diags.Report(diag::note_cc1_round_trip_generated)
7045f7ddb14SDimitry Andric         << 1 << SerializeArgs(GeneratedArgs1);
7055f7ddb14SDimitry Andric     return false;
7065f7ddb14SDimitry Andric   }
7075f7ddb14SDimitry Andric 
7085f7ddb14SDimitry Andric   // Generate arguments again, this time from the options we will end up using
7095f7ddb14SDimitry Andric   // for the rest of the compilation.
7105f7ddb14SDimitry Andric   SmallVector<const char *> GeneratedArgs2;
7115f7ddb14SDimitry Andric   Generate(RealInvocation, GeneratedArgs2, SA);
7125f7ddb14SDimitry Andric 
7135f7ddb14SDimitry Andric   // Compares two lists of generated arguments.
7145f7ddb14SDimitry Andric   auto Equal = [](const ArrayRef<const char *> A,
7155f7ddb14SDimitry Andric                   const ArrayRef<const char *> B) {
7165f7ddb14SDimitry Andric     return std::equal(A.begin(), A.end(), B.begin(), B.end(),
7175f7ddb14SDimitry Andric                       [](const char *AElem, const char *BElem) {
7185f7ddb14SDimitry Andric                         return StringRef(AElem) == StringRef(BElem);
7195f7ddb14SDimitry Andric                       });
7205f7ddb14SDimitry Andric   };
7215f7ddb14SDimitry Andric 
7225f7ddb14SDimitry Andric   // If we generated different arguments from what we assume are two
7235f7ddb14SDimitry Andric   // semantically equivalent CompilerInvocations, the Generate function may
7245f7ddb14SDimitry Andric   // be non-deterministic.
7255f7ddb14SDimitry Andric   if (!Equal(GeneratedArgs1, GeneratedArgs2)) {
7265f7ddb14SDimitry Andric     Diags.Report(diag::err_cc1_round_trip_mismatch);
7275f7ddb14SDimitry Andric     Diags.Report(diag::note_cc1_round_trip_generated)
7285f7ddb14SDimitry Andric         << 1 << SerializeArgs(GeneratedArgs1);
7295f7ddb14SDimitry Andric     Diags.Report(diag::note_cc1_round_trip_generated)
7305f7ddb14SDimitry Andric         << 2 << SerializeArgs(GeneratedArgs2);
7315f7ddb14SDimitry Andric     return false;
7325f7ddb14SDimitry Andric   }
7335f7ddb14SDimitry Andric 
7345f7ddb14SDimitry Andric   Diags.Report(diag::remark_cc1_round_trip_generated)
7355f7ddb14SDimitry Andric       << 1 << SerializeArgs(GeneratedArgs1);
7365f7ddb14SDimitry Andric   Diags.Report(diag::remark_cc1_round_trip_generated)
7375f7ddb14SDimitry Andric       << 2 << SerializeArgs(GeneratedArgs2);
7385f7ddb14SDimitry Andric 
7395f7ddb14SDimitry Andric   return Success2;
740af732203SDimitry Andric }
741af732203SDimitry Andric 
addDiagnosticArgs(ArgList & Args,OptSpecifier Group,OptSpecifier GroupWithValue,std::vector<std::string> & Diagnostics)7420b57cec5SDimitry Andric static void addDiagnosticArgs(ArgList &Args, OptSpecifier Group,
7430b57cec5SDimitry Andric                               OptSpecifier GroupWithValue,
7440b57cec5SDimitry Andric                               std::vector<std::string> &Diagnostics) {
7450b57cec5SDimitry Andric   for (auto *A : Args.filtered(Group)) {
7460b57cec5SDimitry Andric     if (A->getOption().getKind() == Option::FlagClass) {
7470b57cec5SDimitry Andric       // The argument is a pure flag (such as OPT_Wall or OPT_Wdeprecated). Add
7485f7ddb14SDimitry Andric       // its name (minus the "W" or "R" at the beginning) to the diagnostics.
7495ffd83dbSDimitry Andric       Diagnostics.push_back(
7505ffd83dbSDimitry Andric           std::string(A->getOption().getName().drop_front(1)));
7510b57cec5SDimitry Andric     } else if (A->getOption().matches(GroupWithValue)) {
7525f7ddb14SDimitry Andric       // This is -Wfoo= or -Rfoo=, where foo is the name of the diagnostic
7535f7ddb14SDimitry Andric       // group. Add only the group name to the diagnostics.
7545ffd83dbSDimitry Andric       Diagnostics.push_back(
7555ffd83dbSDimitry Andric           std::string(A->getOption().getName().drop_front(1).rtrim("=-")));
7560b57cec5SDimitry Andric     } else {
7570b57cec5SDimitry Andric       // Otherwise, add its value (for OPT_W_Joined and similar).
7585f7ddb14SDimitry Andric       Diagnostics.push_back(A->getValue());
7590b57cec5SDimitry Andric     }
7600b57cec5SDimitry Andric   }
7610b57cec5SDimitry Andric }
7620b57cec5SDimitry Andric 
7630b57cec5SDimitry Andric // Parse the Static Analyzer configuration. If \p Diags is set to nullptr,
7640b57cec5SDimitry Andric // it won't verify the input.
7650b57cec5SDimitry Andric static void parseAnalyzerConfigs(AnalyzerOptions &AnOpts,
7660b57cec5SDimitry Andric                                  DiagnosticsEngine *Diags);
7670b57cec5SDimitry Andric 
getAllNoBuiltinFuncValues(ArgList & Args,std::vector<std::string> & Funcs)7680b57cec5SDimitry Andric static void getAllNoBuiltinFuncValues(ArgList &Args,
7690b57cec5SDimitry Andric                                       std::vector<std::string> &Funcs) {
7705f7ddb14SDimitry Andric   std::vector<std::string> Values = Args.getAllArgValues(OPT_fno_builtin_);
7715f7ddb14SDimitry Andric   auto BuiltinEnd = llvm::partition(Values, [](const std::string FuncName) {
7725f7ddb14SDimitry Andric     return Builtin::Context::isBuiltinFunc(FuncName);
7735f7ddb14SDimitry Andric   });
7745f7ddb14SDimitry Andric   Funcs.insert(Funcs.end(), Values.begin(), BuiltinEnd);
7755f7ddb14SDimitry Andric }
7765f7ddb14SDimitry Andric 
GenerateAnalyzerArgs(AnalyzerOptions & Opts,SmallVectorImpl<const char * > & Args,CompilerInvocation::StringAllocator SA)7775f7ddb14SDimitry Andric static void GenerateAnalyzerArgs(AnalyzerOptions &Opts,
7785f7ddb14SDimitry Andric                                  SmallVectorImpl<const char *> &Args,
7795f7ddb14SDimitry Andric                                  CompilerInvocation::StringAllocator SA) {
7805f7ddb14SDimitry Andric   const AnalyzerOptions *AnalyzerOpts = &Opts;
7815f7ddb14SDimitry Andric 
7825f7ddb14SDimitry Andric #define ANALYZER_OPTION_WITH_MARSHALLING(                                      \
7835f7ddb14SDimitry Andric     PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,        \
7845f7ddb14SDimitry Andric     HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
7855f7ddb14SDimitry Andric     DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER,     \
7865f7ddb14SDimitry Andric     MERGER, EXTRACTOR, TABLE_INDEX)                                            \
7875f7ddb14SDimitry Andric   GENERATE_OPTION_WITH_MARSHALLING(                                            \
7885f7ddb14SDimitry Andric       Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE,    \
7895f7ddb14SDimitry Andric       IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
7905f7ddb14SDimitry Andric #include "clang/Driver/Options.inc"
7915f7ddb14SDimitry Andric #undef ANALYZER_OPTION_WITH_MARSHALLING
7925f7ddb14SDimitry Andric 
7935f7ddb14SDimitry Andric   if (Opts.AnalysisStoreOpt != RegionStoreModel) {
7945f7ddb14SDimitry Andric     switch (Opts.AnalysisStoreOpt) {
7955f7ddb14SDimitry Andric #define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN)                           \
7965f7ddb14SDimitry Andric   case NAME##Model:                                                            \
7975f7ddb14SDimitry Andric     GenerateArg(Args, OPT_analyzer_store, CMDFLAG, SA);                        \
7985f7ddb14SDimitry Andric     break;
7995f7ddb14SDimitry Andric #include "clang/StaticAnalyzer/Core/Analyses.def"
8005f7ddb14SDimitry Andric     default:
8015f7ddb14SDimitry Andric       llvm_unreachable("Tried to generate unknown analysis store.");
8020b57cec5SDimitry Andric     }
8030b57cec5SDimitry Andric   }
8045f7ddb14SDimitry Andric 
8055f7ddb14SDimitry Andric   if (Opts.AnalysisConstraintsOpt != RangeConstraintsModel) {
8065f7ddb14SDimitry Andric     switch (Opts.AnalysisConstraintsOpt) {
8075f7ddb14SDimitry Andric #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN)                     \
8085f7ddb14SDimitry Andric   case NAME##Model:                                                            \
8095f7ddb14SDimitry Andric     GenerateArg(Args, OPT_analyzer_constraints, CMDFLAG, SA);                  \
8105f7ddb14SDimitry Andric     break;
8115f7ddb14SDimitry Andric #include "clang/StaticAnalyzer/Core/Analyses.def"
8125f7ddb14SDimitry Andric     default:
8135f7ddb14SDimitry Andric       llvm_unreachable("Tried to generate unknown analysis constraint.");
8145f7ddb14SDimitry Andric     }
8155f7ddb14SDimitry Andric   }
8165f7ddb14SDimitry Andric 
8175f7ddb14SDimitry Andric   if (Opts.AnalysisDiagOpt != PD_HTML) {
8185f7ddb14SDimitry Andric     switch (Opts.AnalysisDiagOpt) {
8195f7ddb14SDimitry Andric #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN)                     \
8205f7ddb14SDimitry Andric   case PD_##NAME:                                                              \
8215f7ddb14SDimitry Andric     GenerateArg(Args, OPT_analyzer_output, CMDFLAG, SA);                       \
8225f7ddb14SDimitry Andric     break;
8235f7ddb14SDimitry Andric #include "clang/StaticAnalyzer/Core/Analyses.def"
8245f7ddb14SDimitry Andric     default:
8255f7ddb14SDimitry Andric       llvm_unreachable("Tried to generate unknown analysis diagnostic client.");
8265f7ddb14SDimitry Andric     }
8275f7ddb14SDimitry Andric   }
8285f7ddb14SDimitry Andric 
8295f7ddb14SDimitry Andric   if (Opts.AnalysisPurgeOpt != PurgeStmt) {
8305f7ddb14SDimitry Andric     switch (Opts.AnalysisPurgeOpt) {
8315f7ddb14SDimitry Andric #define ANALYSIS_PURGE(NAME, CMDFLAG, DESC)                                    \
8325f7ddb14SDimitry Andric   case NAME:                                                                   \
8335f7ddb14SDimitry Andric     GenerateArg(Args, OPT_analyzer_purge, CMDFLAG, SA);                        \
8345f7ddb14SDimitry Andric     break;
8355f7ddb14SDimitry Andric #include "clang/StaticAnalyzer/Core/Analyses.def"
8365f7ddb14SDimitry Andric     default:
8375f7ddb14SDimitry Andric       llvm_unreachable("Tried to generate unknown analysis purge mode.");
8385f7ddb14SDimitry Andric     }
8395f7ddb14SDimitry Andric   }
8405f7ddb14SDimitry Andric 
8415f7ddb14SDimitry Andric   if (Opts.InliningMode != NoRedundancy) {
8425f7ddb14SDimitry Andric     switch (Opts.InliningMode) {
8435f7ddb14SDimitry Andric #define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC)                            \
8445f7ddb14SDimitry Andric   case NAME:                                                                   \
8455f7ddb14SDimitry Andric     GenerateArg(Args, OPT_analyzer_inlining_mode, CMDFLAG, SA);                \
8465f7ddb14SDimitry Andric     break;
8475f7ddb14SDimitry Andric #include "clang/StaticAnalyzer/Core/Analyses.def"
8485f7ddb14SDimitry Andric     default:
8495f7ddb14SDimitry Andric       llvm_unreachable("Tried to generate unknown analysis inlining mode.");
8505f7ddb14SDimitry Andric     }
8515f7ddb14SDimitry Andric   }
8525f7ddb14SDimitry Andric 
8535f7ddb14SDimitry Andric   for (const auto &CP : Opts.CheckersAndPackages) {
8545f7ddb14SDimitry Andric     OptSpecifier Opt =
8555f7ddb14SDimitry Andric         CP.second ? OPT_analyzer_checker : OPT_analyzer_disable_checker;
8565f7ddb14SDimitry Andric     GenerateArg(Args, Opt, CP.first, SA);
8575f7ddb14SDimitry Andric   }
8585f7ddb14SDimitry Andric 
8595f7ddb14SDimitry Andric   AnalyzerOptions ConfigOpts;
8605f7ddb14SDimitry Andric   parseAnalyzerConfigs(ConfigOpts, nullptr);
8615f7ddb14SDimitry Andric 
8625f7ddb14SDimitry Andric   for (const auto &C : Opts.Config) {
8635f7ddb14SDimitry Andric     // Don't generate anything that came from parseAnalyzerConfigs. It would be
8645f7ddb14SDimitry Andric     // redundant and may not be valid on the command line.
8655f7ddb14SDimitry Andric     auto Entry = ConfigOpts.Config.find(C.getKey());
8665f7ddb14SDimitry Andric     if (Entry != ConfigOpts.Config.end() && Entry->getValue() == C.getValue())
8675f7ddb14SDimitry Andric       continue;
8685f7ddb14SDimitry Andric 
8695f7ddb14SDimitry Andric     GenerateArg(Args, OPT_analyzer_config, C.getKey() + "=" + C.getValue(), SA);
8705f7ddb14SDimitry Andric   }
8715f7ddb14SDimitry Andric 
8725f7ddb14SDimitry Andric   // Nothing to generate for FullCompilerInvocation.
8730b57cec5SDimitry Andric }
8740b57cec5SDimitry Andric 
ParseAnalyzerArgs(AnalyzerOptions & Opts,ArgList & Args,DiagnosticsEngine & Diags)8750b57cec5SDimitry Andric static bool ParseAnalyzerArgs(AnalyzerOptions &Opts, ArgList &Args,
8760b57cec5SDimitry Andric                               DiagnosticsEngine &Diags) {
8775f7ddb14SDimitry Andric   unsigned NumErrorsBefore = Diags.getNumErrors();
8785f7ddb14SDimitry Andric 
8795f7ddb14SDimitry Andric   AnalyzerOptions *AnalyzerOpts = &Opts;
8805f7ddb14SDimitry Andric 
8815f7ddb14SDimitry Andric #define ANALYZER_OPTION_WITH_MARSHALLING(                                      \
8825f7ddb14SDimitry Andric     PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,        \
8835f7ddb14SDimitry Andric     HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
8845f7ddb14SDimitry Andric     DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER,     \
8855f7ddb14SDimitry Andric     MERGER, EXTRACTOR, TABLE_INDEX)                                            \
8865f7ddb14SDimitry Andric   PARSE_OPTION_WITH_MARSHALLING(                                               \
8875f7ddb14SDimitry Andric       Args, Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE,     \
8885f7ddb14SDimitry Andric       IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
8895f7ddb14SDimitry Andric #include "clang/Driver/Options.inc"
8905f7ddb14SDimitry Andric #undef ANALYZER_OPTION_WITH_MARSHALLING
8915f7ddb14SDimitry Andric 
8920b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(OPT_analyzer_store)) {
8930b57cec5SDimitry Andric     StringRef Name = A->getValue();
8940b57cec5SDimitry Andric     AnalysisStores Value = llvm::StringSwitch<AnalysisStores>(Name)
8950b57cec5SDimitry Andric #define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN) \
8960b57cec5SDimitry Andric       .Case(CMDFLAG, NAME##Model)
8970b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/Analyses.def"
8980b57cec5SDimitry Andric       .Default(NumStores);
8990b57cec5SDimitry Andric     if (Value == NumStores) {
9000b57cec5SDimitry Andric       Diags.Report(diag::err_drv_invalid_value)
9010b57cec5SDimitry Andric         << A->getAsString(Args) << Name;
9020b57cec5SDimitry Andric     } else {
9030b57cec5SDimitry Andric       Opts.AnalysisStoreOpt = Value;
9040b57cec5SDimitry Andric     }
9050b57cec5SDimitry Andric   }
9060b57cec5SDimitry Andric 
9070b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(OPT_analyzer_constraints)) {
9080b57cec5SDimitry Andric     StringRef Name = A->getValue();
9090b57cec5SDimitry Andric     AnalysisConstraints Value = llvm::StringSwitch<AnalysisConstraints>(Name)
9100b57cec5SDimitry Andric #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) \
9110b57cec5SDimitry Andric       .Case(CMDFLAG, NAME##Model)
9120b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/Analyses.def"
9130b57cec5SDimitry Andric       .Default(NumConstraints);
9140b57cec5SDimitry Andric     if (Value == NumConstraints) {
9150b57cec5SDimitry Andric       Diags.Report(diag::err_drv_invalid_value)
9160b57cec5SDimitry Andric         << A->getAsString(Args) << Name;
9170b57cec5SDimitry Andric     } else {
9180b57cec5SDimitry Andric       Opts.AnalysisConstraintsOpt = Value;
9190b57cec5SDimitry Andric     }
9200b57cec5SDimitry Andric   }
9210b57cec5SDimitry Andric 
9220b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(OPT_analyzer_output)) {
9230b57cec5SDimitry Andric     StringRef Name = A->getValue();
9240b57cec5SDimitry Andric     AnalysisDiagClients Value = llvm::StringSwitch<AnalysisDiagClients>(Name)
9250b57cec5SDimitry Andric #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN) \
9260b57cec5SDimitry Andric       .Case(CMDFLAG, PD_##NAME)
9270b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/Analyses.def"
9280b57cec5SDimitry Andric       .Default(NUM_ANALYSIS_DIAG_CLIENTS);
9290b57cec5SDimitry Andric     if (Value == NUM_ANALYSIS_DIAG_CLIENTS) {
9300b57cec5SDimitry Andric       Diags.Report(diag::err_drv_invalid_value)
9310b57cec5SDimitry Andric         << A->getAsString(Args) << Name;
9320b57cec5SDimitry Andric     } else {
9330b57cec5SDimitry Andric       Opts.AnalysisDiagOpt = Value;
9340b57cec5SDimitry Andric     }
9350b57cec5SDimitry Andric   }
9360b57cec5SDimitry Andric 
9370b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(OPT_analyzer_purge)) {
9380b57cec5SDimitry Andric     StringRef Name = A->getValue();
9390b57cec5SDimitry Andric     AnalysisPurgeMode Value = llvm::StringSwitch<AnalysisPurgeMode>(Name)
9400b57cec5SDimitry Andric #define ANALYSIS_PURGE(NAME, CMDFLAG, DESC) \
9410b57cec5SDimitry Andric       .Case(CMDFLAG, NAME)
9420b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/Analyses.def"
9430b57cec5SDimitry Andric       .Default(NumPurgeModes);
9440b57cec5SDimitry Andric     if (Value == NumPurgeModes) {
9450b57cec5SDimitry Andric       Diags.Report(diag::err_drv_invalid_value)
9460b57cec5SDimitry Andric         << A->getAsString(Args) << Name;
9470b57cec5SDimitry Andric     } else {
9480b57cec5SDimitry Andric       Opts.AnalysisPurgeOpt = Value;
9490b57cec5SDimitry Andric     }
9500b57cec5SDimitry Andric   }
9510b57cec5SDimitry Andric 
9520b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(OPT_analyzer_inlining_mode)) {
9530b57cec5SDimitry Andric     StringRef Name = A->getValue();
9540b57cec5SDimitry Andric     AnalysisInliningMode Value = llvm::StringSwitch<AnalysisInliningMode>(Name)
9550b57cec5SDimitry Andric #define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC) \
9560b57cec5SDimitry Andric       .Case(CMDFLAG, NAME)
9570b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/Analyses.def"
9580b57cec5SDimitry Andric       .Default(NumInliningModes);
9590b57cec5SDimitry Andric     if (Value == NumInliningModes) {
9600b57cec5SDimitry Andric       Diags.Report(diag::err_drv_invalid_value)
9610b57cec5SDimitry Andric         << A->getAsString(Args) << Name;
9620b57cec5SDimitry Andric     } else {
9630b57cec5SDimitry Andric       Opts.InliningMode = Value;
9640b57cec5SDimitry Andric     }
9650b57cec5SDimitry Andric   }
9660b57cec5SDimitry Andric 
967a7dea167SDimitry Andric   Opts.CheckersAndPackages.clear();
9680b57cec5SDimitry Andric   for (const Arg *A :
9690b57cec5SDimitry Andric        Args.filtered(OPT_analyzer_checker, OPT_analyzer_disable_checker)) {
9700b57cec5SDimitry Andric     A->claim();
971a7dea167SDimitry Andric     bool IsEnabled = A->getOption().getID() == OPT_analyzer_checker;
9720b57cec5SDimitry Andric     // We can have a list of comma separated checker names, e.g:
9730b57cec5SDimitry Andric     // '-analyzer-checker=cocoa,unix'
974a7dea167SDimitry Andric     StringRef CheckerAndPackageList = A->getValue();
975a7dea167SDimitry Andric     SmallVector<StringRef, 16> CheckersAndPackages;
976a7dea167SDimitry Andric     CheckerAndPackageList.split(CheckersAndPackages, ",");
977480093f4SDimitry Andric     for (const StringRef &CheckerOrPackage : CheckersAndPackages)
9785ffd83dbSDimitry Andric       Opts.CheckersAndPackages.emplace_back(std::string(CheckerOrPackage),
9795ffd83dbSDimitry Andric                                             IsEnabled);
9800b57cec5SDimitry Andric   }
9810b57cec5SDimitry Andric 
9820b57cec5SDimitry Andric   // Go through the analyzer configuration options.
9830b57cec5SDimitry Andric   for (const auto *A : Args.filtered(OPT_analyzer_config)) {
9840b57cec5SDimitry Andric 
9850b57cec5SDimitry Andric     // We can have a list of comma separated config names, e.g:
9860b57cec5SDimitry Andric     // '-analyzer-config key1=val1,key2=val2'
9870b57cec5SDimitry Andric     StringRef configList = A->getValue();
9880b57cec5SDimitry Andric     SmallVector<StringRef, 4> configVals;
9890b57cec5SDimitry Andric     configList.split(configVals, ",");
9900b57cec5SDimitry Andric     for (const auto &configVal : configVals) {
9910b57cec5SDimitry Andric       StringRef key, val;
9920b57cec5SDimitry Andric       std::tie(key, val) = configVal.split("=");
9930b57cec5SDimitry Andric       if (val.empty()) {
9940b57cec5SDimitry Andric         Diags.Report(SourceLocation(),
9950b57cec5SDimitry Andric                      diag::err_analyzer_config_no_value) << configVal;
9960b57cec5SDimitry Andric         break;
9970b57cec5SDimitry Andric       }
9980b57cec5SDimitry Andric       if (val.find('=') != StringRef::npos) {
9990b57cec5SDimitry Andric         Diags.Report(SourceLocation(),
10000b57cec5SDimitry Andric                      diag::err_analyzer_config_multiple_values)
10010b57cec5SDimitry Andric           << configVal;
10020b57cec5SDimitry Andric         break;
10030b57cec5SDimitry Andric       }
10040b57cec5SDimitry Andric 
10050b57cec5SDimitry Andric       // TODO: Check checker options too, possibly in CheckerRegistry.
10060b57cec5SDimitry Andric       // Leave unknown non-checker configs unclaimed.
10070b57cec5SDimitry Andric       if (!key.contains(":") && Opts.isUnknownAnalyzerConfig(key)) {
10080b57cec5SDimitry Andric         if (Opts.ShouldEmitErrorsOnInvalidConfigValue)
10090b57cec5SDimitry Andric           Diags.Report(diag::err_analyzer_config_unknown) << key;
10100b57cec5SDimitry Andric         continue;
10110b57cec5SDimitry Andric       }
10120b57cec5SDimitry Andric 
10130b57cec5SDimitry Andric       A->claim();
10145ffd83dbSDimitry Andric       Opts.Config[key] = std::string(val);
10150b57cec5SDimitry Andric     }
10160b57cec5SDimitry Andric   }
10170b57cec5SDimitry Andric 
10180b57cec5SDimitry Andric   if (Opts.ShouldEmitErrorsOnInvalidConfigValue)
10190b57cec5SDimitry Andric     parseAnalyzerConfigs(Opts, &Diags);
10200b57cec5SDimitry Andric   else
10210b57cec5SDimitry Andric     parseAnalyzerConfigs(Opts, nullptr);
10220b57cec5SDimitry Andric 
10230b57cec5SDimitry Andric   llvm::raw_string_ostream os(Opts.FullCompilerInvocation);
10240b57cec5SDimitry Andric   for (unsigned i = 0; i < Args.getNumInputArgStrings(); ++i) {
10250b57cec5SDimitry Andric     if (i != 0)
10260b57cec5SDimitry Andric       os << " ";
10270b57cec5SDimitry Andric     os << Args.getArgString(i);
10280b57cec5SDimitry Andric   }
10290b57cec5SDimitry Andric   os.flush();
10300b57cec5SDimitry Andric 
10315f7ddb14SDimitry Andric   return Diags.getNumErrors() == NumErrorsBefore;
10320b57cec5SDimitry Andric }
10330b57cec5SDimitry Andric 
getStringOption(AnalyzerOptions::ConfigTable & Config,StringRef OptionName,StringRef DefaultVal)10340b57cec5SDimitry Andric static StringRef getStringOption(AnalyzerOptions::ConfigTable &Config,
10350b57cec5SDimitry Andric                                  StringRef OptionName, StringRef DefaultVal) {
10365ffd83dbSDimitry Andric   return Config.insert({OptionName, std::string(DefaultVal)}).first->second;
10370b57cec5SDimitry Andric }
10380b57cec5SDimitry Andric 
initOption(AnalyzerOptions::ConfigTable & Config,DiagnosticsEngine * Diags,StringRef & OptionField,StringRef Name,StringRef DefaultVal)10390b57cec5SDimitry Andric static void initOption(AnalyzerOptions::ConfigTable &Config,
10400b57cec5SDimitry Andric                        DiagnosticsEngine *Diags,
10410b57cec5SDimitry Andric                        StringRef &OptionField, StringRef Name,
10420b57cec5SDimitry Andric                        StringRef DefaultVal) {
10430b57cec5SDimitry Andric   // String options may be known to invalid (e.g. if the expected string is a
10440b57cec5SDimitry Andric   // file name, but the file does not exist), those will have to be checked in
10450b57cec5SDimitry Andric   // parseConfigs.
10460b57cec5SDimitry Andric   OptionField = getStringOption(Config, Name, DefaultVal);
10470b57cec5SDimitry Andric }
10480b57cec5SDimitry Andric 
initOption(AnalyzerOptions::ConfigTable & Config,DiagnosticsEngine * Diags,bool & OptionField,StringRef Name,bool DefaultVal)10490b57cec5SDimitry Andric static void initOption(AnalyzerOptions::ConfigTable &Config,
10500b57cec5SDimitry Andric                        DiagnosticsEngine *Diags,
10510b57cec5SDimitry Andric                        bool &OptionField, StringRef Name, bool DefaultVal) {
10520b57cec5SDimitry Andric   auto PossiblyInvalidVal = llvm::StringSwitch<Optional<bool>>(
10530b57cec5SDimitry Andric                  getStringOption(Config, Name, (DefaultVal ? "true" : "false")))
10540b57cec5SDimitry Andric       .Case("true", true)
10550b57cec5SDimitry Andric       .Case("false", false)
10560b57cec5SDimitry Andric       .Default(None);
10570b57cec5SDimitry Andric 
10580b57cec5SDimitry Andric   if (!PossiblyInvalidVal) {
10590b57cec5SDimitry Andric     if (Diags)
10600b57cec5SDimitry Andric       Diags->Report(diag::err_analyzer_config_invalid_input)
10610b57cec5SDimitry Andric         << Name << "a boolean";
10620b57cec5SDimitry Andric     else
10630b57cec5SDimitry Andric       OptionField = DefaultVal;
10640b57cec5SDimitry Andric   } else
10650b57cec5SDimitry Andric     OptionField = PossiblyInvalidVal.getValue();
10660b57cec5SDimitry Andric }
10670b57cec5SDimitry Andric 
initOption(AnalyzerOptions::ConfigTable & Config,DiagnosticsEngine * Diags,unsigned & OptionField,StringRef Name,unsigned DefaultVal)10680b57cec5SDimitry Andric static void initOption(AnalyzerOptions::ConfigTable &Config,
10690b57cec5SDimitry Andric                        DiagnosticsEngine *Diags,
10700b57cec5SDimitry Andric                        unsigned &OptionField, StringRef Name,
10710b57cec5SDimitry Andric                        unsigned DefaultVal) {
10720b57cec5SDimitry Andric 
10730b57cec5SDimitry Andric   OptionField = DefaultVal;
10740b57cec5SDimitry Andric   bool HasFailed = getStringOption(Config, Name, std::to_string(DefaultVal))
10750b57cec5SDimitry Andric                      .getAsInteger(0, OptionField);
10760b57cec5SDimitry Andric   if (Diags && HasFailed)
10770b57cec5SDimitry Andric     Diags->Report(diag::err_analyzer_config_invalid_input)
10780b57cec5SDimitry Andric       << Name << "an unsigned";
10790b57cec5SDimitry Andric }
10800b57cec5SDimitry Andric 
parseAnalyzerConfigs(AnalyzerOptions & AnOpts,DiagnosticsEngine * Diags)10810b57cec5SDimitry Andric static void parseAnalyzerConfigs(AnalyzerOptions &AnOpts,
10820b57cec5SDimitry Andric                                  DiagnosticsEngine *Diags) {
10830b57cec5SDimitry Andric   // TODO: There's no need to store the entire configtable, it'd be plenty
10840b57cec5SDimitry Andric   // enough tostore checker options.
10850b57cec5SDimitry Andric 
10860b57cec5SDimitry Andric #define ANALYZER_OPTION(TYPE, NAME, CMDFLAG, DESC, DEFAULT_VAL)                \
10870b57cec5SDimitry Andric   initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, DEFAULT_VAL);
10880b57cec5SDimitry Andric 
10890b57cec5SDimitry Andric #define ANALYZER_OPTION_DEPENDS_ON_USER_MODE(TYPE, NAME, CMDFLAG, DESC,        \
10900b57cec5SDimitry Andric                                            SHALLOW_VAL, DEEP_VAL)              \
10910b57cec5SDimitry Andric   switch (AnOpts.getUserMode()) {                                              \
10920b57cec5SDimitry Andric   case UMK_Shallow:                                                            \
10930b57cec5SDimitry Andric     initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, SHALLOW_VAL);       \
10940b57cec5SDimitry Andric     break;                                                                     \
10950b57cec5SDimitry Andric   case UMK_Deep:                                                               \
10960b57cec5SDimitry Andric     initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, DEEP_VAL);          \
10970b57cec5SDimitry Andric     break;                                                                     \
10980b57cec5SDimitry Andric   }                                                                            \
10990b57cec5SDimitry Andric 
11000b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/AnalyzerOptions.def"
11010b57cec5SDimitry Andric #undef ANALYZER_OPTION
11020b57cec5SDimitry Andric #undef ANALYZER_OPTION_DEPENDS_ON_USER_MODE
11030b57cec5SDimitry Andric 
11040b57cec5SDimitry Andric   // At this point, AnalyzerOptions is configured. Let's validate some options.
11050b57cec5SDimitry Andric 
1106a7dea167SDimitry Andric   // FIXME: Here we try to validate the silenced checkers or packages are valid.
1107a7dea167SDimitry Andric   // The current approach only validates the registered checkers which does not
1108a7dea167SDimitry Andric   // contain the runtime enabled checkers and optimally we would validate both.
1109a7dea167SDimitry Andric   if (!AnOpts.RawSilencedCheckersAndPackages.empty()) {
1110a7dea167SDimitry Andric     std::vector<StringRef> Checkers =
1111a7dea167SDimitry Andric         AnOpts.getRegisteredCheckers(/*IncludeExperimental=*/true);
1112a7dea167SDimitry Andric     std::vector<StringRef> Packages =
1113a7dea167SDimitry Andric         AnOpts.getRegisteredPackages(/*IncludeExperimental=*/true);
1114a7dea167SDimitry Andric 
1115a7dea167SDimitry Andric     SmallVector<StringRef, 16> CheckersAndPackages;
1116a7dea167SDimitry Andric     AnOpts.RawSilencedCheckersAndPackages.split(CheckersAndPackages, ";");
1117a7dea167SDimitry Andric 
1118480093f4SDimitry Andric     for (const StringRef &CheckerOrPackage : CheckersAndPackages) {
1119a7dea167SDimitry Andric       if (Diags) {
1120a7dea167SDimitry Andric         bool IsChecker = CheckerOrPackage.contains('.');
1121a7dea167SDimitry Andric         bool IsValidName =
1122a7dea167SDimitry Andric             IsChecker
1123a7dea167SDimitry Andric                 ? llvm::find(Checkers, CheckerOrPackage) != Checkers.end()
1124a7dea167SDimitry Andric                 : llvm::find(Packages, CheckerOrPackage) != Packages.end();
1125a7dea167SDimitry Andric 
1126a7dea167SDimitry Andric         if (!IsValidName)
1127a7dea167SDimitry Andric           Diags->Report(diag::err_unknown_analyzer_checker_or_package)
1128a7dea167SDimitry Andric               << CheckerOrPackage;
1129a7dea167SDimitry Andric       }
1130a7dea167SDimitry Andric 
1131a7dea167SDimitry Andric       AnOpts.SilencedCheckersAndPackages.emplace_back(CheckerOrPackage);
1132a7dea167SDimitry Andric     }
1133a7dea167SDimitry Andric   }
1134a7dea167SDimitry Andric 
11350b57cec5SDimitry Andric   if (!Diags)
11360b57cec5SDimitry Andric     return;
11370b57cec5SDimitry Andric 
11380b57cec5SDimitry Andric   if (AnOpts.ShouldTrackConditionsDebug && !AnOpts.ShouldTrackConditions)
11390b57cec5SDimitry Andric     Diags->Report(diag::err_analyzer_config_invalid_input)
11400b57cec5SDimitry Andric         << "track-conditions-debug" << "'track-conditions' to also be enabled";
11410b57cec5SDimitry Andric 
11420b57cec5SDimitry Andric   if (!AnOpts.CTUDir.empty() && !llvm::sys::fs::is_directory(AnOpts.CTUDir))
11430b57cec5SDimitry Andric     Diags->Report(diag::err_analyzer_config_invalid_input) << "ctu-dir"
11440b57cec5SDimitry Andric                                                            << "a filename";
11450b57cec5SDimitry Andric 
11460b57cec5SDimitry Andric   if (!AnOpts.ModelPath.empty() &&
11470b57cec5SDimitry Andric       !llvm::sys::fs::is_directory(AnOpts.ModelPath))
11480b57cec5SDimitry Andric     Diags->Report(diag::err_analyzer_config_invalid_input) << "model-path"
11490b57cec5SDimitry Andric                                                            << "a filename";
11500b57cec5SDimitry Andric }
11510b57cec5SDimitry Andric 
11525f7ddb14SDimitry Andric /// Generate a remark argument. This is an inverse of `ParseOptimizationRemark`.
11535f7ddb14SDimitry Andric static void
GenerateOptimizationRemark(SmallVectorImpl<const char * > & Args,CompilerInvocation::StringAllocator SA,OptSpecifier OptEQ,StringRef Name,const CodeGenOptions::OptRemark & Remark)11545f7ddb14SDimitry Andric GenerateOptimizationRemark(SmallVectorImpl<const char *> &Args,
11555f7ddb14SDimitry Andric                            CompilerInvocation::StringAllocator SA,
11565f7ddb14SDimitry Andric                            OptSpecifier OptEQ, StringRef Name,
11575f7ddb14SDimitry Andric                            const CodeGenOptions::OptRemark &Remark) {
11585f7ddb14SDimitry Andric   if (Remark.hasValidPattern()) {
11595f7ddb14SDimitry Andric     GenerateArg(Args, OptEQ, Remark.Pattern, SA);
11605f7ddb14SDimitry Andric   } else if (Remark.Kind == CodeGenOptions::RK_Enabled) {
11615f7ddb14SDimitry Andric     GenerateArg(Args, OPT_R_Joined, Name, SA);
11625f7ddb14SDimitry Andric   } else if (Remark.Kind == CodeGenOptions::RK_Disabled) {
11635f7ddb14SDimitry Andric     GenerateArg(Args, OPT_R_Joined, StringRef("no-") + Name, SA);
11640b57cec5SDimitry Andric   }
11655f7ddb14SDimitry Andric }
11665f7ddb14SDimitry Andric 
11675f7ddb14SDimitry Andric /// Parse a remark command line argument. It may be missing, disabled/enabled by
11685f7ddb14SDimitry Andric /// '-R[no-]group' or specified with a regular expression by '-Rgroup=regexp'.
11695f7ddb14SDimitry Andric /// On top of that, it can be disabled/enabled globally by '-R[no-]everything'.
11705f7ddb14SDimitry Andric static CodeGenOptions::OptRemark
ParseOptimizationRemark(DiagnosticsEngine & Diags,ArgList & Args,OptSpecifier OptEQ,StringRef Name)11715f7ddb14SDimitry Andric ParseOptimizationRemark(DiagnosticsEngine &Diags, ArgList &Args,
11725f7ddb14SDimitry Andric                         OptSpecifier OptEQ, StringRef Name) {
11735f7ddb14SDimitry Andric   CodeGenOptions::OptRemark Result;
11745f7ddb14SDimitry Andric 
11755f7ddb14SDimitry Andric   auto InitializeResultPattern = [&Diags, &Args, &Result](const Arg *A) {
11765f7ddb14SDimitry Andric     Result.Pattern = A->getValue();
11775f7ddb14SDimitry Andric 
11785f7ddb14SDimitry Andric     std::string RegexError;
11795f7ddb14SDimitry Andric     Result.Regex = std::make_shared<llvm::Regex>(Result.Pattern);
11805f7ddb14SDimitry Andric     if (!Result.Regex->isValid(RegexError)) {
11815f7ddb14SDimitry Andric       Diags.Report(diag::err_drv_optimization_remark_pattern)
11825f7ddb14SDimitry Andric           << RegexError << A->getAsString(Args);
11835f7ddb14SDimitry Andric       return false;
11845f7ddb14SDimitry Andric     }
11855f7ddb14SDimitry Andric 
11865f7ddb14SDimitry Andric     return true;
11875f7ddb14SDimitry Andric   };
11885f7ddb14SDimitry Andric 
11895f7ddb14SDimitry Andric   for (Arg *A : Args) {
11905f7ddb14SDimitry Andric     if (A->getOption().matches(OPT_R_Joined)) {
11915f7ddb14SDimitry Andric       StringRef Value = A->getValue();
11925f7ddb14SDimitry Andric 
11935f7ddb14SDimitry Andric       if (Value == Name)
11945f7ddb14SDimitry Andric         Result.Kind = CodeGenOptions::RK_Enabled;
11955f7ddb14SDimitry Andric       else if (Value == "everything")
11965f7ddb14SDimitry Andric         Result.Kind = CodeGenOptions::RK_EnabledEverything;
11975f7ddb14SDimitry Andric       else if (Value.split('-') == std::make_pair(StringRef("no"), Name))
11985f7ddb14SDimitry Andric         Result.Kind = CodeGenOptions::RK_Disabled;
11995f7ddb14SDimitry Andric       else if (Value == "no-everything")
12005f7ddb14SDimitry Andric         Result.Kind = CodeGenOptions::RK_DisabledEverything;
12015f7ddb14SDimitry Andric     } else if (A->getOption().matches(OptEQ)) {
12025f7ddb14SDimitry Andric       Result.Kind = CodeGenOptions::RK_WithPattern;
12035f7ddb14SDimitry Andric       if (!InitializeResultPattern(A))
12045f7ddb14SDimitry Andric         return CodeGenOptions::OptRemark();
12055f7ddb14SDimitry Andric     }
12065f7ddb14SDimitry Andric   }
12075f7ddb14SDimitry Andric 
12085f7ddb14SDimitry Andric   if (Result.Kind == CodeGenOptions::RK_Disabled ||
12095f7ddb14SDimitry Andric       Result.Kind == CodeGenOptions::RK_DisabledEverything) {
12105f7ddb14SDimitry Andric     Result.Pattern = "";
12115f7ddb14SDimitry Andric     Result.Regex = nullptr;
12125f7ddb14SDimitry Andric   }
12135f7ddb14SDimitry Andric 
12145f7ddb14SDimitry Andric   return Result;
12150b57cec5SDimitry Andric }
12160b57cec5SDimitry Andric 
parseDiagnosticLevelMask(StringRef FlagName,const std::vector<std::string> & Levels,DiagnosticsEngine & Diags,DiagnosticLevelMask & M)12170b57cec5SDimitry Andric static bool parseDiagnosticLevelMask(StringRef FlagName,
12180b57cec5SDimitry Andric                                      const std::vector<std::string> &Levels,
1219af732203SDimitry Andric                                      DiagnosticsEngine &Diags,
12200b57cec5SDimitry Andric                                      DiagnosticLevelMask &M) {
12210b57cec5SDimitry Andric   bool Success = true;
12220b57cec5SDimitry Andric   for (const auto &Level : Levels) {
12230b57cec5SDimitry Andric     DiagnosticLevelMask const PM =
12240b57cec5SDimitry Andric       llvm::StringSwitch<DiagnosticLevelMask>(Level)
12250b57cec5SDimitry Andric         .Case("note",    DiagnosticLevelMask::Note)
12260b57cec5SDimitry Andric         .Case("remark",  DiagnosticLevelMask::Remark)
12270b57cec5SDimitry Andric         .Case("warning", DiagnosticLevelMask::Warning)
12280b57cec5SDimitry Andric         .Case("error",   DiagnosticLevelMask::Error)
12290b57cec5SDimitry Andric         .Default(DiagnosticLevelMask::None);
12300b57cec5SDimitry Andric     if (PM == DiagnosticLevelMask::None) {
12310b57cec5SDimitry Andric       Success = false;
1232af732203SDimitry Andric       Diags.Report(diag::err_drv_invalid_value) << FlagName << Level;
12330b57cec5SDimitry Andric     }
12340b57cec5SDimitry Andric     M = M | PM;
12350b57cec5SDimitry Andric   }
12360b57cec5SDimitry Andric   return Success;
12370b57cec5SDimitry Andric }
12380b57cec5SDimitry Andric 
parseSanitizerKinds(StringRef FlagName,const std::vector<std::string> & Sanitizers,DiagnosticsEngine & Diags,SanitizerSet & S)12390b57cec5SDimitry Andric static void parseSanitizerKinds(StringRef FlagName,
12400b57cec5SDimitry Andric                                 const std::vector<std::string> &Sanitizers,
12410b57cec5SDimitry Andric                                 DiagnosticsEngine &Diags, SanitizerSet &S) {
12420b57cec5SDimitry Andric   for (const auto &Sanitizer : Sanitizers) {
12430b57cec5SDimitry Andric     SanitizerMask K = parseSanitizerValue(Sanitizer, /*AllowGroups=*/false);
12440b57cec5SDimitry Andric     if (K == SanitizerMask())
12450b57cec5SDimitry Andric       Diags.Report(diag::err_drv_invalid_value) << FlagName << Sanitizer;
12460b57cec5SDimitry Andric     else
12470b57cec5SDimitry Andric       S.set(K, true);
12480b57cec5SDimitry Andric   }
12490b57cec5SDimitry Andric }
12500b57cec5SDimitry Andric 
serializeSanitizerKinds(SanitizerSet S)12515f7ddb14SDimitry Andric static SmallVector<StringRef, 4> serializeSanitizerKinds(SanitizerSet S) {
12525f7ddb14SDimitry Andric   SmallVector<StringRef, 4> Values;
12535f7ddb14SDimitry Andric   serializeSanitizerSet(S, Values);
12545f7ddb14SDimitry Andric   return Values;
12555f7ddb14SDimitry Andric }
12565f7ddb14SDimitry Andric 
parseXRayInstrumentationBundle(StringRef FlagName,StringRef Bundle,ArgList & Args,DiagnosticsEngine & D,XRayInstrSet & S)12570b57cec5SDimitry Andric static void parseXRayInstrumentationBundle(StringRef FlagName, StringRef Bundle,
12580b57cec5SDimitry Andric                                            ArgList &Args, DiagnosticsEngine &D,
12590b57cec5SDimitry Andric                                            XRayInstrSet &S) {
12600b57cec5SDimitry Andric   llvm::SmallVector<StringRef, 2> BundleParts;
12610b57cec5SDimitry Andric   llvm::SplitString(Bundle, BundleParts, ",");
1262480093f4SDimitry Andric   for (const auto &B : BundleParts) {
12630b57cec5SDimitry Andric     auto Mask = parseXRayInstrValue(B);
12640b57cec5SDimitry Andric     if (Mask == XRayInstrKind::None)
12650b57cec5SDimitry Andric       if (B != "none")
12660b57cec5SDimitry Andric         D.Report(diag::err_drv_invalid_value) << FlagName << Bundle;
12670b57cec5SDimitry Andric       else
12680b57cec5SDimitry Andric         S.Mask = Mask;
12690b57cec5SDimitry Andric     else if (Mask == XRayInstrKind::All)
12700b57cec5SDimitry Andric       S.Mask = Mask;
12710b57cec5SDimitry Andric     else
12720b57cec5SDimitry Andric       S.set(Mask, true);
12730b57cec5SDimitry Andric   }
12740b57cec5SDimitry Andric }
12750b57cec5SDimitry Andric 
serializeXRayInstrumentationBundle(const XRayInstrSet & S)12765f7ddb14SDimitry Andric static std::string serializeXRayInstrumentationBundle(const XRayInstrSet &S) {
12775f7ddb14SDimitry Andric   llvm::SmallVector<StringRef, 2> BundleParts;
12785f7ddb14SDimitry Andric   serializeXRayInstrValue(S, BundleParts);
12795f7ddb14SDimitry Andric   std::string Buffer;
12805f7ddb14SDimitry Andric   llvm::raw_string_ostream OS(Buffer);
12815f7ddb14SDimitry Andric   llvm::interleave(BundleParts, OS, [&OS](StringRef Part) { OS << Part; }, ",");
12825f7ddb14SDimitry Andric   return OS.str();
12835f7ddb14SDimitry Andric }
12845f7ddb14SDimitry Andric 
12850b57cec5SDimitry Andric // Set the profile kind using fprofile-instrument-use-path.
setPGOUseInstrumentor(CodeGenOptions & Opts,const Twine & ProfileName)12860b57cec5SDimitry Andric static void setPGOUseInstrumentor(CodeGenOptions &Opts,
12870b57cec5SDimitry Andric                                   const Twine &ProfileName) {
12880b57cec5SDimitry Andric   auto ReaderOrErr = llvm::IndexedInstrProfReader::create(ProfileName);
12890b57cec5SDimitry Andric   // In error, return silently and let Clang PGOUse report the error message.
12900b57cec5SDimitry Andric   if (auto E = ReaderOrErr.takeError()) {
12910b57cec5SDimitry Andric     llvm::consumeError(std::move(E));
12920b57cec5SDimitry Andric     Opts.setProfileUse(CodeGenOptions::ProfileClangInstr);
12930b57cec5SDimitry Andric     return;
12940b57cec5SDimitry Andric   }
12950b57cec5SDimitry Andric   std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader =
12960b57cec5SDimitry Andric     std::move(ReaderOrErr.get());
12970b57cec5SDimitry Andric   if (PGOReader->isIRLevelProfile()) {
12980b57cec5SDimitry Andric     if (PGOReader->hasCSIRLevelProfile())
12990b57cec5SDimitry Andric       Opts.setProfileUse(CodeGenOptions::ProfileCSIRInstr);
13000b57cec5SDimitry Andric     else
13010b57cec5SDimitry Andric       Opts.setProfileUse(CodeGenOptions::ProfileIRInstr);
13020b57cec5SDimitry Andric   } else
13030b57cec5SDimitry Andric     Opts.setProfileUse(CodeGenOptions::ProfileClangInstr);
13040b57cec5SDimitry Andric }
13050b57cec5SDimitry Andric 
GenerateCodeGenArgs(const CodeGenOptions & Opts,SmallVectorImpl<const char * > & Args,StringAllocator SA,const llvm::Triple & T,const std::string & OutputFile,const LangOptions * LangOpts)13065f7ddb14SDimitry Andric void CompilerInvocation::GenerateCodeGenArgs(
13075f7ddb14SDimitry Andric     const CodeGenOptions &Opts, SmallVectorImpl<const char *> &Args,
13085f7ddb14SDimitry Andric     StringAllocator SA, const llvm::Triple &T, const std::string &OutputFile,
13095f7ddb14SDimitry Andric     const LangOptions *LangOpts) {
13105f7ddb14SDimitry Andric   const CodeGenOptions &CodeGenOpts = Opts;
13115f7ddb14SDimitry Andric 
13125f7ddb14SDimitry Andric   if (Opts.OptimizationLevel == 0)
13135f7ddb14SDimitry Andric     GenerateArg(Args, OPT_O0, SA);
13145f7ddb14SDimitry Andric   else
13155f7ddb14SDimitry Andric     GenerateArg(Args, OPT_O, Twine(Opts.OptimizationLevel), SA);
13165f7ddb14SDimitry Andric 
13175f7ddb14SDimitry Andric #define CODEGEN_OPTION_WITH_MARSHALLING(                                       \
13185f7ddb14SDimitry Andric     PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,        \
13195f7ddb14SDimitry Andric     HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
13205f7ddb14SDimitry Andric     DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER,     \
13215f7ddb14SDimitry Andric     MERGER, EXTRACTOR, TABLE_INDEX)                                            \
13225f7ddb14SDimitry Andric   GENERATE_OPTION_WITH_MARSHALLING(                                            \
13235f7ddb14SDimitry Andric       Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE,    \
13245f7ddb14SDimitry Andric       IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
13255f7ddb14SDimitry Andric #include "clang/Driver/Options.inc"
13265f7ddb14SDimitry Andric #undef CODEGEN_OPTION_WITH_MARSHALLING
13275f7ddb14SDimitry Andric 
13285f7ddb14SDimitry Andric   if (Opts.OptimizationLevel > 0) {
13295f7ddb14SDimitry Andric     if (Opts.Inlining == CodeGenOptions::NormalInlining)
13305f7ddb14SDimitry Andric       GenerateArg(Args, OPT_finline_functions, SA);
13315f7ddb14SDimitry Andric     else if (Opts.Inlining == CodeGenOptions::OnlyHintInlining)
13325f7ddb14SDimitry Andric       GenerateArg(Args, OPT_finline_hint_functions, SA);
13335f7ddb14SDimitry Andric     else if (Opts.Inlining == CodeGenOptions::OnlyAlwaysInlining)
13345f7ddb14SDimitry Andric       GenerateArg(Args, OPT_fno_inline, SA);
13355f7ddb14SDimitry Andric   }
13365f7ddb14SDimitry Andric 
13375f7ddb14SDimitry Andric   if (Opts.DirectAccessExternalData && LangOpts->PICLevel != 0)
13385f7ddb14SDimitry Andric     GenerateArg(Args, OPT_fdirect_access_external_data, SA);
13395f7ddb14SDimitry Andric   else if (!Opts.DirectAccessExternalData && LangOpts->PICLevel == 0)
13405f7ddb14SDimitry Andric     GenerateArg(Args, OPT_fno_direct_access_external_data, SA);
13415f7ddb14SDimitry Andric 
13425f7ddb14SDimitry Andric   Optional<StringRef> DebugInfoVal;
13435f7ddb14SDimitry Andric   switch (Opts.DebugInfo) {
13445f7ddb14SDimitry Andric   case codegenoptions::DebugLineTablesOnly:
13455f7ddb14SDimitry Andric     DebugInfoVal = "line-tables-only";
13465f7ddb14SDimitry Andric     break;
13475f7ddb14SDimitry Andric   case codegenoptions::DebugDirectivesOnly:
13485f7ddb14SDimitry Andric     DebugInfoVal = "line-directives-only";
13495f7ddb14SDimitry Andric     break;
13505f7ddb14SDimitry Andric   case codegenoptions::DebugInfoConstructor:
13515f7ddb14SDimitry Andric     DebugInfoVal = "constructor";
13525f7ddb14SDimitry Andric     break;
13535f7ddb14SDimitry Andric   case codegenoptions::LimitedDebugInfo:
13545f7ddb14SDimitry Andric     DebugInfoVal = "limited";
13555f7ddb14SDimitry Andric     break;
13565f7ddb14SDimitry Andric   case codegenoptions::FullDebugInfo:
13575f7ddb14SDimitry Andric     DebugInfoVal = "standalone";
13585f7ddb14SDimitry Andric     break;
13595f7ddb14SDimitry Andric   case codegenoptions::UnusedTypeInfo:
13605f7ddb14SDimitry Andric     DebugInfoVal = "unused-types";
13615f7ddb14SDimitry Andric     break;
13625f7ddb14SDimitry Andric   case codegenoptions::NoDebugInfo: // default value
13635f7ddb14SDimitry Andric     DebugInfoVal = None;
13645f7ddb14SDimitry Andric     break;
13655f7ddb14SDimitry Andric   case codegenoptions::LocTrackingOnly: // implied value
13665f7ddb14SDimitry Andric     DebugInfoVal = None;
13675f7ddb14SDimitry Andric     break;
13685f7ddb14SDimitry Andric   }
13695f7ddb14SDimitry Andric   if (DebugInfoVal)
13705f7ddb14SDimitry Andric     GenerateArg(Args, OPT_debug_info_kind_EQ, *DebugInfoVal, SA);
13715f7ddb14SDimitry Andric 
13725f7ddb14SDimitry Andric   for (const auto &Prefix : Opts.DebugPrefixMap)
13735f7ddb14SDimitry Andric     GenerateArg(Args, OPT_fdebug_prefix_map_EQ,
13745f7ddb14SDimitry Andric                 Prefix.first + "=" + Prefix.second, SA);
13755f7ddb14SDimitry Andric 
13765f7ddb14SDimitry Andric   for (const auto &Prefix : Opts.CoveragePrefixMap)
13775f7ddb14SDimitry Andric     GenerateArg(Args, OPT_fcoverage_prefix_map_EQ,
13785f7ddb14SDimitry Andric                 Prefix.first + "=" + Prefix.second, SA);
13795f7ddb14SDimitry Andric 
13805f7ddb14SDimitry Andric   if (Opts.NewStructPathTBAA)
13815f7ddb14SDimitry Andric     GenerateArg(Args, OPT_new_struct_path_tbaa, SA);
13825f7ddb14SDimitry Andric 
13835f7ddb14SDimitry Andric   if (Opts.OptimizeSize == 1)
13845f7ddb14SDimitry Andric     GenerateArg(Args, OPT_O, "s", SA);
13855f7ddb14SDimitry Andric   else if (Opts.OptimizeSize == 2)
13865f7ddb14SDimitry Andric     GenerateArg(Args, OPT_O, "z", SA);
13875f7ddb14SDimitry Andric 
13885f7ddb14SDimitry Andric   // SimplifyLibCalls is set only in the absence of -fno-builtin and
13895f7ddb14SDimitry Andric   // -ffreestanding. We'll consider that when generating them.
13905f7ddb14SDimitry Andric 
13915f7ddb14SDimitry Andric   // NoBuiltinFuncs are generated by LangOptions.
13925f7ddb14SDimitry Andric 
13935f7ddb14SDimitry Andric   if (Opts.UnrollLoops && Opts.OptimizationLevel <= 1)
13945f7ddb14SDimitry Andric     GenerateArg(Args, OPT_funroll_loops, SA);
13955f7ddb14SDimitry Andric   else if (!Opts.UnrollLoops && Opts.OptimizationLevel > 1)
13965f7ddb14SDimitry Andric     GenerateArg(Args, OPT_fno_unroll_loops, SA);
13975f7ddb14SDimitry Andric 
13985f7ddb14SDimitry Andric   if (!Opts.BinutilsVersion.empty())
13995f7ddb14SDimitry Andric     GenerateArg(Args, OPT_fbinutils_version_EQ, Opts.BinutilsVersion, SA);
14005f7ddb14SDimitry Andric 
14015f7ddb14SDimitry Andric   if (Opts.DebugNameTable ==
14025f7ddb14SDimitry Andric       static_cast<unsigned>(llvm::DICompileUnit::DebugNameTableKind::GNU))
14035f7ddb14SDimitry Andric     GenerateArg(Args, OPT_ggnu_pubnames, SA);
14045f7ddb14SDimitry Andric   else if (Opts.DebugNameTable ==
14055f7ddb14SDimitry Andric            static_cast<unsigned>(
14065f7ddb14SDimitry Andric                llvm::DICompileUnit::DebugNameTableKind::Default))
14075f7ddb14SDimitry Andric     GenerateArg(Args, OPT_gpubnames, SA);
14085f7ddb14SDimitry Andric 
14095f7ddb14SDimitry Andric   // ProfileInstrumentUsePath is marshalled automatically, no need to generate
14105f7ddb14SDimitry Andric   // it or PGOUseInstrumentor.
14115f7ddb14SDimitry Andric 
14125f7ddb14SDimitry Andric   if (Opts.TimePasses) {
14135f7ddb14SDimitry Andric     if (Opts.TimePassesPerRun)
14145f7ddb14SDimitry Andric       GenerateArg(Args, OPT_ftime_report_EQ, "per-pass-run", SA);
14155f7ddb14SDimitry Andric     else
14165f7ddb14SDimitry Andric       GenerateArg(Args, OPT_ftime_report, SA);
14175f7ddb14SDimitry Andric   }
14185f7ddb14SDimitry Andric 
14195f7ddb14SDimitry Andric   if (Opts.PrepareForLTO && !Opts.PrepareForThinLTO)
14205f7ddb14SDimitry Andric     GenerateArg(Args, OPT_flto, SA);
14215f7ddb14SDimitry Andric 
14225f7ddb14SDimitry Andric   if (Opts.PrepareForThinLTO)
14235f7ddb14SDimitry Andric     GenerateArg(Args, OPT_flto_EQ, "thin", SA);
14245f7ddb14SDimitry Andric 
14255f7ddb14SDimitry Andric   if (!Opts.ThinLTOIndexFile.empty())
14265f7ddb14SDimitry Andric     GenerateArg(Args, OPT_fthinlto_index_EQ, Opts.ThinLTOIndexFile, SA);
14275f7ddb14SDimitry Andric 
14285f7ddb14SDimitry Andric   if (Opts.SaveTempsFilePrefix == OutputFile)
14295f7ddb14SDimitry Andric     GenerateArg(Args, OPT_save_temps_EQ, "obj", SA);
14305f7ddb14SDimitry Andric 
14315f7ddb14SDimitry Andric   StringRef MemProfileBasename("memprof.profraw");
14325f7ddb14SDimitry Andric   if (!Opts.MemoryProfileOutput.empty()) {
14335f7ddb14SDimitry Andric     if (Opts.MemoryProfileOutput == MemProfileBasename) {
14345f7ddb14SDimitry Andric       GenerateArg(Args, OPT_fmemory_profile, SA);
14355f7ddb14SDimitry Andric     } else {
14365f7ddb14SDimitry Andric       size_t ArgLength =
14375f7ddb14SDimitry Andric           Opts.MemoryProfileOutput.size() - MemProfileBasename.size();
14385f7ddb14SDimitry Andric       GenerateArg(Args, OPT_fmemory_profile_EQ,
14395f7ddb14SDimitry Andric                   Opts.MemoryProfileOutput.substr(0, ArgLength), SA);
14405f7ddb14SDimitry Andric     }
14415f7ddb14SDimitry Andric   }
14425f7ddb14SDimitry Andric 
14435f7ddb14SDimitry Andric   if (memcmp(Opts.CoverageVersion, "408*", 4) != 0)
14445f7ddb14SDimitry Andric     GenerateArg(Args, OPT_coverage_version_EQ,
14455f7ddb14SDimitry Andric                 StringRef(Opts.CoverageVersion, 4), SA);
14465f7ddb14SDimitry Andric 
14475f7ddb14SDimitry Andric   // TODO: Check if we need to generate arguments stored in CmdArgs. (Namely
14485f7ddb14SDimitry Andric   //  '-fembed_bitcode', which does not map to any CompilerInvocation field and
14495f7ddb14SDimitry Andric   //  won't be generated.)
14505f7ddb14SDimitry Andric 
14515f7ddb14SDimitry Andric   if (Opts.XRayInstrumentationBundle.Mask != XRayInstrKind::All) {
14525f7ddb14SDimitry Andric     std::string InstrBundle =
14535f7ddb14SDimitry Andric         serializeXRayInstrumentationBundle(Opts.XRayInstrumentationBundle);
14545f7ddb14SDimitry Andric     if (!InstrBundle.empty())
14555f7ddb14SDimitry Andric       GenerateArg(Args, OPT_fxray_instrumentation_bundle, InstrBundle, SA);
14565f7ddb14SDimitry Andric   }
14575f7ddb14SDimitry Andric 
14585f7ddb14SDimitry Andric   if (Opts.CFProtectionReturn && Opts.CFProtectionBranch)
14595f7ddb14SDimitry Andric     GenerateArg(Args, OPT_fcf_protection_EQ, "full", SA);
14605f7ddb14SDimitry Andric   else if (Opts.CFProtectionReturn)
14615f7ddb14SDimitry Andric     GenerateArg(Args, OPT_fcf_protection_EQ, "return", SA);
14625f7ddb14SDimitry Andric   else if (Opts.CFProtectionBranch)
14635f7ddb14SDimitry Andric     GenerateArg(Args, OPT_fcf_protection_EQ, "branch", SA);
14645f7ddb14SDimitry Andric 
14655f7ddb14SDimitry Andric   for (const auto &F : Opts.LinkBitcodeFiles) {
14665f7ddb14SDimitry Andric     bool Builtint = F.LinkFlags == llvm::Linker::Flags::LinkOnlyNeeded &&
14675f7ddb14SDimitry Andric                     F.PropagateAttrs && F.Internalize;
14685f7ddb14SDimitry Andric     GenerateArg(Args,
14695f7ddb14SDimitry Andric                 Builtint ? OPT_mlink_builtin_bitcode : OPT_mlink_bitcode_file,
14705f7ddb14SDimitry Andric                 F.Filename, SA);
14715f7ddb14SDimitry Andric   }
14725f7ddb14SDimitry Andric 
14735f7ddb14SDimitry Andric   // TODO: Consider removing marshalling annotations from f[no_]emulated_tls.
14745f7ddb14SDimitry Andric   //  That would make it easy to generate the option only **once** if it was
14755f7ddb14SDimitry Andric   //  explicitly set to non-default value.
14765f7ddb14SDimitry Andric   if (Opts.ExplicitEmulatedTLS) {
14775f7ddb14SDimitry Andric     GenerateArg(
14785f7ddb14SDimitry Andric         Args, Opts.EmulatedTLS ? OPT_femulated_tls : OPT_fno_emulated_tls, SA);
14795f7ddb14SDimitry Andric   }
14805f7ddb14SDimitry Andric 
14815f7ddb14SDimitry Andric   if (Opts.FPDenormalMode != llvm::DenormalMode::getIEEE())
14825f7ddb14SDimitry Andric     GenerateArg(Args, OPT_fdenormal_fp_math_EQ, Opts.FPDenormalMode.str(), SA);
14835f7ddb14SDimitry Andric 
14845f7ddb14SDimitry Andric   if (Opts.FP32DenormalMode != llvm::DenormalMode::getIEEE())
14855f7ddb14SDimitry Andric     GenerateArg(Args, OPT_fdenormal_fp_math_f32_EQ, Opts.FP32DenormalMode.str(),
14865f7ddb14SDimitry Andric                 SA);
14875f7ddb14SDimitry Andric 
14885f7ddb14SDimitry Andric   if (Opts.StructReturnConvention == CodeGenOptions::SRCK_OnStack) {
14895f7ddb14SDimitry Andric     OptSpecifier Opt =
14905f7ddb14SDimitry Andric         T.isPPC32() ? OPT_maix_struct_return : OPT_fpcc_struct_return;
14915f7ddb14SDimitry Andric     GenerateArg(Args, Opt, SA);
14925f7ddb14SDimitry Andric   } else if (Opts.StructReturnConvention == CodeGenOptions::SRCK_InRegs) {
14935f7ddb14SDimitry Andric     OptSpecifier Opt =
14945f7ddb14SDimitry Andric         T.isPPC32() ? OPT_msvr4_struct_return : OPT_freg_struct_return;
14955f7ddb14SDimitry Andric     GenerateArg(Args, Opt, SA);
14965f7ddb14SDimitry Andric   }
14975f7ddb14SDimitry Andric 
14985f7ddb14SDimitry Andric   if (Opts.EnableAIXExtendedAltivecABI)
14995f7ddb14SDimitry Andric     GenerateArg(Args, OPT_mabi_EQ_vec_extabi, SA);
15005f7ddb14SDimitry Andric 
15015f7ddb14SDimitry Andric   if (!Opts.OptRecordPasses.empty())
15025f7ddb14SDimitry Andric     GenerateArg(Args, OPT_opt_record_passes, Opts.OptRecordPasses, SA);
15035f7ddb14SDimitry Andric 
15045f7ddb14SDimitry Andric   if (!Opts.OptRecordFormat.empty())
15055f7ddb14SDimitry Andric     GenerateArg(Args, OPT_opt_record_format, Opts.OptRecordFormat, SA);
15065f7ddb14SDimitry Andric 
15075f7ddb14SDimitry Andric   GenerateOptimizationRemark(Args, SA, OPT_Rpass_EQ, "pass",
15085f7ddb14SDimitry Andric                              Opts.OptimizationRemark);
15095f7ddb14SDimitry Andric 
15105f7ddb14SDimitry Andric   GenerateOptimizationRemark(Args, SA, OPT_Rpass_missed_EQ, "pass-missed",
15115f7ddb14SDimitry Andric                              Opts.OptimizationRemarkMissed);
15125f7ddb14SDimitry Andric 
15135f7ddb14SDimitry Andric   GenerateOptimizationRemark(Args, SA, OPT_Rpass_analysis_EQ, "pass-analysis",
15145f7ddb14SDimitry Andric                              Opts.OptimizationRemarkAnalysis);
15155f7ddb14SDimitry Andric 
15165f7ddb14SDimitry Andric   GenerateArg(Args, OPT_fdiagnostics_hotness_threshold_EQ,
15175f7ddb14SDimitry Andric               Opts.DiagnosticsHotnessThreshold
15185f7ddb14SDimitry Andric                   ? Twine(*Opts.DiagnosticsHotnessThreshold)
15195f7ddb14SDimitry Andric                   : "auto",
15205f7ddb14SDimitry Andric               SA);
15215f7ddb14SDimitry Andric 
15225f7ddb14SDimitry Andric   for (StringRef Sanitizer : serializeSanitizerKinds(Opts.SanitizeRecover))
15235f7ddb14SDimitry Andric     GenerateArg(Args, OPT_fsanitize_recover_EQ, Sanitizer, SA);
15245f7ddb14SDimitry Andric 
15255f7ddb14SDimitry Andric   for (StringRef Sanitizer : serializeSanitizerKinds(Opts.SanitizeTrap))
15265f7ddb14SDimitry Andric     GenerateArg(Args, OPT_fsanitize_trap_EQ, Sanitizer, SA);
15275f7ddb14SDimitry Andric 
15285f7ddb14SDimitry Andric   if (!Opts.EmitVersionIdentMetadata)
15295f7ddb14SDimitry Andric     GenerateArg(Args, OPT_Qn, SA);
15305f7ddb14SDimitry Andric 
15315f7ddb14SDimitry Andric   switch (Opts.FiniteLoops) {
15325f7ddb14SDimitry Andric   case CodeGenOptions::FiniteLoopsKind::Language:
15335f7ddb14SDimitry Andric     break;
15345f7ddb14SDimitry Andric   case CodeGenOptions::FiniteLoopsKind::Always:
15355f7ddb14SDimitry Andric     GenerateArg(Args, OPT_ffinite_loops, SA);
15365f7ddb14SDimitry Andric     break;
15375f7ddb14SDimitry Andric   case CodeGenOptions::FiniteLoopsKind::Never:
15385f7ddb14SDimitry Andric     GenerateArg(Args, OPT_fno_finite_loops, SA);
15395f7ddb14SDimitry Andric     break;
15405f7ddb14SDimitry Andric   }
15415f7ddb14SDimitry Andric }
15425f7ddb14SDimitry Andric 
ParseCodeGenArgs(CodeGenOptions & Opts,ArgList & Args,InputKind IK,DiagnosticsEngine & Diags,const llvm::Triple & T,const std::string & OutputFile,const LangOptions & LangOptsRef)1543af732203SDimitry Andric bool CompilerInvocation::ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args,
1544af732203SDimitry Andric                                           InputKind IK,
15450b57cec5SDimitry Andric                                           DiagnosticsEngine &Diags,
1546af732203SDimitry Andric                                           const llvm::Triple &T,
1547af732203SDimitry Andric                                           const std::string &OutputFile,
1548af732203SDimitry Andric                                           const LangOptions &LangOptsRef) {
15495f7ddb14SDimitry Andric   unsigned NumErrorsBefore = Diags.getNumErrors();
15500b57cec5SDimitry Andric 
15510b57cec5SDimitry Andric   unsigned OptimizationLevel = getOptimizationLevel(Args, IK, Diags);
15520b57cec5SDimitry Andric   // TODO: This could be done in Driver
15530b57cec5SDimitry Andric   unsigned MaxOptLevel = 3;
15540b57cec5SDimitry Andric   if (OptimizationLevel > MaxOptLevel) {
15550b57cec5SDimitry Andric     // If the optimization level is not supported, fall back on the default
15560b57cec5SDimitry Andric     // optimization
15570b57cec5SDimitry Andric     Diags.Report(diag::warn_drv_optimization_value)
15580b57cec5SDimitry Andric         << Args.getLastArg(OPT_O)->getAsString(Args) << "-O" << MaxOptLevel;
15590b57cec5SDimitry Andric     OptimizationLevel = MaxOptLevel;
15600b57cec5SDimitry Andric   }
15610b57cec5SDimitry Andric   Opts.OptimizationLevel = OptimizationLevel;
15620b57cec5SDimitry Andric 
1563af732203SDimitry Andric   // The key paths of codegen options defined in Options.td start with
1564af732203SDimitry Andric   // "CodeGenOpts.". Let's provide the expected variable name and type.
1565af732203SDimitry Andric   CodeGenOptions &CodeGenOpts = Opts;
1566af732203SDimitry Andric   // Some codegen options depend on language options. Let's provide the expected
1567af732203SDimitry Andric   // variable name and type.
1568af732203SDimitry Andric   const LangOptions *LangOpts = &LangOptsRef;
1569af732203SDimitry Andric 
1570af732203SDimitry Andric #define CODEGEN_OPTION_WITH_MARSHALLING(                                       \
1571af732203SDimitry Andric     PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,        \
1572af732203SDimitry Andric     HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
1573af732203SDimitry Andric     DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER,     \
1574af732203SDimitry Andric     MERGER, EXTRACTOR, TABLE_INDEX)                                            \
15755f7ddb14SDimitry Andric   PARSE_OPTION_WITH_MARSHALLING(                                               \
15765f7ddb14SDimitry Andric       Args, Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE,     \
15775f7ddb14SDimitry Andric       IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
1578af732203SDimitry Andric #include "clang/Driver/Options.inc"
1579af732203SDimitry Andric #undef CODEGEN_OPTION_WITH_MARSHALLING
1580af732203SDimitry Andric 
15810b57cec5SDimitry Andric   // At O0 we want to fully disable inlining outside of cases marked with
15820b57cec5SDimitry Andric   // 'alwaysinline' that are required for correctness.
15830b57cec5SDimitry Andric   Opts.setInlining((Opts.OptimizationLevel == 0)
15840b57cec5SDimitry Andric                        ? CodeGenOptions::OnlyAlwaysInlining
15850b57cec5SDimitry Andric                        : CodeGenOptions::NormalInlining);
15860b57cec5SDimitry Andric   // Explicit inlining flags can disable some or all inlining even at
15870b57cec5SDimitry Andric   // optimization levels above zero.
15880b57cec5SDimitry Andric   if (Arg *InlineArg = Args.getLastArg(
15890b57cec5SDimitry Andric           options::OPT_finline_functions, options::OPT_finline_hint_functions,
15900b57cec5SDimitry Andric           options::OPT_fno_inline_functions, options::OPT_fno_inline)) {
15910b57cec5SDimitry Andric     if (Opts.OptimizationLevel > 0) {
15920b57cec5SDimitry Andric       const Option &InlineOpt = InlineArg->getOption();
15930b57cec5SDimitry Andric       if (InlineOpt.matches(options::OPT_finline_functions))
15940b57cec5SDimitry Andric         Opts.setInlining(CodeGenOptions::NormalInlining);
15950b57cec5SDimitry Andric       else if (InlineOpt.matches(options::OPT_finline_hint_functions))
15960b57cec5SDimitry Andric         Opts.setInlining(CodeGenOptions::OnlyHintInlining);
15970b57cec5SDimitry Andric       else
15980b57cec5SDimitry Andric         Opts.setInlining(CodeGenOptions::OnlyAlwaysInlining);
15990b57cec5SDimitry Andric     }
16000b57cec5SDimitry Andric   }
16010b57cec5SDimitry Andric 
1602af732203SDimitry Andric   // PIC defaults to -fno-direct-access-external-data while non-PIC defaults to
1603af732203SDimitry Andric   // -fdirect-access-external-data.
1604af732203SDimitry Andric   Opts.DirectAccessExternalData =
1605af732203SDimitry Andric       Args.hasArg(OPT_fdirect_access_external_data) ||
1606af732203SDimitry Andric       (!Args.hasArg(OPT_fno_direct_access_external_data) &&
16075f7ddb14SDimitry Andric        LangOpts->PICLevel == 0);
16085f7ddb14SDimitry Andric 
16095f7ddb14SDimitry Andric   if (Arg *A = Args.getLastArg(OPT_debug_info_kind_EQ)) {
16105f7ddb14SDimitry Andric     unsigned Val =
16115f7ddb14SDimitry Andric         llvm::StringSwitch<unsigned>(A->getValue())
16125f7ddb14SDimitry Andric             .Case("line-tables-only", codegenoptions::DebugLineTablesOnly)
16135f7ddb14SDimitry Andric             .Case("line-directives-only", codegenoptions::DebugDirectivesOnly)
16145f7ddb14SDimitry Andric             .Case("constructor", codegenoptions::DebugInfoConstructor)
16155f7ddb14SDimitry Andric             .Case("limited", codegenoptions::LimitedDebugInfo)
16165f7ddb14SDimitry Andric             .Case("standalone", codegenoptions::FullDebugInfo)
16175f7ddb14SDimitry Andric             .Case("unused-types", codegenoptions::UnusedTypeInfo)
16185f7ddb14SDimitry Andric             .Default(~0U);
16195f7ddb14SDimitry Andric     if (Val == ~0U)
16205f7ddb14SDimitry Andric       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
16215f7ddb14SDimitry Andric                                                 << A->getValue();
16225f7ddb14SDimitry Andric     else
16235f7ddb14SDimitry Andric       Opts.setDebugInfo(static_cast<codegenoptions::DebugInfoKind>(Val));
16245f7ddb14SDimitry Andric   }
16250b57cec5SDimitry Andric 
1626af732203SDimitry Andric   // If -fuse-ctor-homing is set and limited debug info is already on, then use
16275f7ddb14SDimitry Andric   // constructor homing, and vice versa for -fno-use-ctor-homing.
16285f7ddb14SDimitry Andric   if (const Arg *A =
16295f7ddb14SDimitry Andric           Args.getLastArg(OPT_fuse_ctor_homing, OPT_fno_use_ctor_homing)) {
16305f7ddb14SDimitry Andric     if (A->getOption().matches(OPT_fuse_ctor_homing) &&
16315f7ddb14SDimitry Andric         Opts.getDebugInfo() == codegenoptions::LimitedDebugInfo)
1632af732203SDimitry Andric       Opts.setDebugInfo(codegenoptions::DebugInfoConstructor);
16335f7ddb14SDimitry Andric     if (A->getOption().matches(OPT_fno_use_ctor_homing) &&
16345f7ddb14SDimitry Andric         Opts.getDebugInfo() == codegenoptions::DebugInfoConstructor)
16355f7ddb14SDimitry Andric       Opts.setDebugInfo(codegenoptions::LimitedDebugInfo);
16365f7ddb14SDimitry Andric   }
16370b57cec5SDimitry Andric 
16385ffd83dbSDimitry Andric   for (const auto &Arg : Args.getAllArgValues(OPT_fdebug_prefix_map_EQ)) {
16395ffd83dbSDimitry Andric     auto Split = StringRef(Arg).split('=');
16405ffd83dbSDimitry Andric     Opts.DebugPrefixMap.insert(
16415ffd83dbSDimitry Andric         {std::string(Split.first), std::string(Split.second)});
16425ffd83dbSDimitry Andric   }
16430b57cec5SDimitry Andric 
16445f7ddb14SDimitry Andric   for (const auto &Arg : Args.getAllArgValues(OPT_fcoverage_prefix_map_EQ)) {
1645af732203SDimitry Andric     auto Split = StringRef(Arg).split('=');
16465f7ddb14SDimitry Andric     Opts.CoveragePrefixMap.insert(
1647af732203SDimitry Andric         {std::string(Split.first), std::string(Split.second)});
1648af732203SDimitry Andric   }
16490b57cec5SDimitry Andric 
1650a7dea167SDimitry Andric   const llvm::Triple::ArchType DebugEntryValueArchs[] = {
1651a7dea167SDimitry Andric       llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::aarch64,
16525ffd83dbSDimitry Andric       llvm::Triple::arm, llvm::Triple::armeb, llvm::Triple::mips,
16535ffd83dbSDimitry Andric       llvm::Triple::mipsel, llvm::Triple::mips64, llvm::Triple::mips64el};
1654a7dea167SDimitry Andric 
1655480093f4SDimitry Andric   if (Opts.OptimizationLevel > 0 && Opts.hasReducedDebugInfo() &&
1656a7dea167SDimitry Andric       llvm::is_contained(DebugEntryValueArchs, T.getArch()))
16575ffd83dbSDimitry Andric     Opts.EmitCallSiteInfo = true;
16580b57cec5SDimitry Andric 
16595f7ddb14SDimitry Andric   if (!Opts.EnableDIPreservationVerify && Opts.DIBugsReportFilePath.size()) {
16605f7ddb14SDimitry Andric     Diags.Report(diag::warn_ignoring_verify_debuginfo_preserve_export)
16615f7ddb14SDimitry Andric         << Opts.DIBugsReportFilePath;
16625f7ddb14SDimitry Andric     Opts.DIBugsReportFilePath = "";
16635f7ddb14SDimitry Andric   }
16645f7ddb14SDimitry Andric 
16650b57cec5SDimitry Andric   Opts.NewStructPathTBAA = !Args.hasArg(OPT_no_struct_path_tbaa) &&
16660b57cec5SDimitry Andric                            Args.hasArg(OPT_new_struct_path_tbaa);
16670b57cec5SDimitry Andric   Opts.OptimizeSize = getOptimizationLevelSize(Args);
16685f7ddb14SDimitry Andric   Opts.SimplifyLibCalls = !LangOpts->NoBuiltin;
16690b57cec5SDimitry Andric   if (Opts.SimplifyLibCalls)
16705f7ddb14SDimitry Andric     Opts.NoBuiltinFuncs = LangOpts->NoBuiltinFuncs;
16710b57cec5SDimitry Andric   Opts.UnrollLoops =
16720b57cec5SDimitry Andric       Args.hasFlag(OPT_funroll_loops, OPT_fno_unroll_loops,
16730b57cec5SDimitry Andric                    (Opts.OptimizationLevel > 1));
1674af732203SDimitry Andric   Opts.BinutilsVersion =
1675af732203SDimitry Andric       std::string(Args.getLastArgValue(OPT_fbinutils_version_EQ));
16760b57cec5SDimitry Andric 
16770b57cec5SDimitry Andric   Opts.DebugNameTable = static_cast<unsigned>(
16780b57cec5SDimitry Andric       Args.hasArg(OPT_ggnu_pubnames)
16790b57cec5SDimitry Andric           ? llvm::DICompileUnit::DebugNameTableKind::GNU
16800b57cec5SDimitry Andric           : Args.hasArg(OPT_gpubnames)
16810b57cec5SDimitry Andric                 ? llvm::DICompileUnit::DebugNameTableKind::Default
16820b57cec5SDimitry Andric                 : llvm::DICompileUnit::DebugNameTableKind::None);
16830b57cec5SDimitry Andric 
16840b57cec5SDimitry Andric   if (!Opts.ProfileInstrumentUsePath.empty())
16850b57cec5SDimitry Andric     setPGOUseInstrumentor(Opts, Opts.ProfileInstrumentUsePath);
1686af732203SDimitry Andric 
1687af732203SDimitry Andric   if (const Arg *A = Args.getLastArg(OPT_ftime_report, OPT_ftime_report_EQ)) {
1688af732203SDimitry Andric     Opts.TimePasses = true;
1689af732203SDimitry Andric 
1690af732203SDimitry Andric     // -ftime-report= is only for new pass manager.
1691af732203SDimitry Andric     if (A->getOption().getID() == OPT_ftime_report_EQ) {
1692af732203SDimitry Andric       if (Opts.LegacyPassManager)
16930b57cec5SDimitry Andric         Diags.Report(diag::err_drv_argument_only_allowed_with)
1694af732203SDimitry Andric             << A->getAsString(Args) << "-fno-legacy-pass-manager";
16950b57cec5SDimitry Andric 
1696af732203SDimitry Andric       StringRef Val = A->getValue();
1697af732203SDimitry Andric       if (Val == "per-pass")
1698af732203SDimitry Andric         Opts.TimePassesPerRun = false;
1699af732203SDimitry Andric       else if (Val == "per-pass-run")
1700af732203SDimitry Andric         Opts.TimePassesPerRun = true;
1701af732203SDimitry Andric       else
17020b57cec5SDimitry Andric         Diags.Report(diag::err_drv_invalid_value)
1703af732203SDimitry Andric             << A->getAsString(Args) << A->getValue();
1704af732203SDimitry Andric     }
1705af732203SDimitry Andric   }
17065ffd83dbSDimitry Andric 
17070b57cec5SDimitry Andric   Opts.PrepareForLTO = Args.hasArg(OPT_flto, OPT_flto_EQ);
17080b57cec5SDimitry Andric   Opts.PrepareForThinLTO = false;
17090b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(OPT_flto_EQ)) {
17100b57cec5SDimitry Andric     StringRef S = A->getValue();
17110b57cec5SDimitry Andric     if (S == "thin")
17120b57cec5SDimitry Andric       Opts.PrepareForThinLTO = true;
17130b57cec5SDimitry Andric     else if (S != "full")
17140b57cec5SDimitry Andric       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << S;
17150b57cec5SDimitry Andric   }
17160b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(OPT_fthinlto_index_EQ)) {
1717a7dea167SDimitry Andric     if (IK.getLanguage() != Language::LLVM_IR)
17180b57cec5SDimitry Andric       Diags.Report(diag::err_drv_argument_only_allowed_with)
17190b57cec5SDimitry Andric           << A->getAsString(Args) << "-x ir";
17205ffd83dbSDimitry Andric     Opts.ThinLTOIndexFile =
17215ffd83dbSDimitry Andric         std::string(Args.getLastArgValue(OPT_fthinlto_index_EQ));
17220b57cec5SDimitry Andric   }
17230b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(OPT_save_temps_EQ))
17240b57cec5SDimitry Andric     Opts.SaveTempsFilePrefix =
17250b57cec5SDimitry Andric         llvm::StringSwitch<std::string>(A->getValue())
1726af732203SDimitry Andric             .Case("obj", OutputFile)
1727af732203SDimitry Andric             .Default(llvm::sys::path::filename(OutputFile).str());
17280b57cec5SDimitry Andric 
1729af732203SDimitry Andric   // The memory profile runtime appends the pid to make this name more unique.
1730af732203SDimitry Andric   const char *MemProfileBasename = "memprof.profraw";
1731af732203SDimitry Andric   if (Args.hasArg(OPT_fmemory_profile_EQ)) {
1732af732203SDimitry Andric     SmallString<128> Path(
1733af732203SDimitry Andric         std::string(Args.getLastArgValue(OPT_fmemory_profile_EQ)));
1734af732203SDimitry Andric     llvm::sys::path::append(Path, MemProfileBasename);
1735af732203SDimitry Andric     Opts.MemoryProfileOutput = std::string(Path);
1736af732203SDimitry Andric   } else if (Args.hasArg(OPT_fmemory_profile))
1737af732203SDimitry Andric     Opts.MemoryProfileOutput = MemProfileBasename;
17380b57cec5SDimitry Andric 
17395f7ddb14SDimitry Andric   memcpy(Opts.CoverageVersion, "408*", 4);
17400b57cec5SDimitry Andric   if (Opts.EmitGcovArcs || Opts.EmitGcovNotes) {
17410b57cec5SDimitry Andric     if (Args.hasArg(OPT_coverage_version_EQ)) {
17420b57cec5SDimitry Andric       StringRef CoverageVersion = Args.getLastArgValue(OPT_coverage_version_EQ);
17430b57cec5SDimitry Andric       if (CoverageVersion.size() != 4) {
17440b57cec5SDimitry Andric         Diags.Report(diag::err_drv_invalid_value)
17450b57cec5SDimitry Andric             << Args.getLastArg(OPT_coverage_version_EQ)->getAsString(Args)
17460b57cec5SDimitry Andric             << CoverageVersion;
17470b57cec5SDimitry Andric       } else {
17480b57cec5SDimitry Andric         memcpy(Opts.CoverageVersion, CoverageVersion.data(), 4);
17490b57cec5SDimitry Andric       }
17500b57cec5SDimitry Andric     }
17510b57cec5SDimitry Andric   }
17520b57cec5SDimitry Andric   // FIXME: For backend options that are not yet recorded as function
17530b57cec5SDimitry Andric   // attributes in the IR, keep track of them so we can embed them in a
17540b57cec5SDimitry Andric   // separate data section and use them when building the bitcode.
17550b57cec5SDimitry Andric   for (const auto &A : Args) {
17560b57cec5SDimitry Andric     // Do not encode output and input.
17570b57cec5SDimitry Andric     if (A->getOption().getID() == options::OPT_o ||
17580b57cec5SDimitry Andric         A->getOption().getID() == options::OPT_INPUT ||
17590b57cec5SDimitry Andric         A->getOption().getID() == options::OPT_x ||
17600b57cec5SDimitry Andric         A->getOption().getID() == options::OPT_fembed_bitcode ||
17615ffd83dbSDimitry Andric         A->getOption().matches(options::OPT_W_Group))
17620b57cec5SDimitry Andric       continue;
17630b57cec5SDimitry Andric     ArgStringList ASL;
17640b57cec5SDimitry Andric     A->render(Args, ASL);
17650b57cec5SDimitry Andric     for (const auto &arg : ASL) {
17660b57cec5SDimitry Andric       StringRef ArgStr(arg);
17670b57cec5SDimitry Andric       Opts.CmdArgs.insert(Opts.CmdArgs.end(), ArgStr.begin(), ArgStr.end());
17680b57cec5SDimitry Andric       // using \00 to separate each commandline options.
17690b57cec5SDimitry Andric       Opts.CmdArgs.push_back('\0');
17700b57cec5SDimitry Andric     }
17710b57cec5SDimitry Andric   }
17720b57cec5SDimitry Andric 
17730b57cec5SDimitry Andric   auto XRayInstrBundles =
17740b57cec5SDimitry Andric       Args.getAllArgValues(OPT_fxray_instrumentation_bundle);
17750b57cec5SDimitry Andric   if (XRayInstrBundles.empty())
17760b57cec5SDimitry Andric     Opts.XRayInstrumentationBundle.Mask = XRayInstrKind::All;
17770b57cec5SDimitry Andric   else
17780b57cec5SDimitry Andric     for (const auto &A : XRayInstrBundles)
17790b57cec5SDimitry Andric       parseXRayInstrumentationBundle("-fxray-instrumentation-bundle=", A, Args,
17800b57cec5SDimitry Andric                                      Diags, Opts.XRayInstrumentationBundle);
17810b57cec5SDimitry Andric 
17820b57cec5SDimitry Andric   if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
17830b57cec5SDimitry Andric     StringRef Name = A->getValue();
17840b57cec5SDimitry Andric     if (Name == "full") {
17850b57cec5SDimitry Andric       Opts.CFProtectionReturn = 1;
17860b57cec5SDimitry Andric       Opts.CFProtectionBranch = 1;
17870b57cec5SDimitry Andric     } else if (Name == "return")
17880b57cec5SDimitry Andric       Opts.CFProtectionReturn = 1;
17890b57cec5SDimitry Andric     else if (Name == "branch")
17900b57cec5SDimitry Andric       Opts.CFProtectionBranch = 1;
17915f7ddb14SDimitry Andric     else if (Name != "none")
17920b57cec5SDimitry Andric       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
17930b57cec5SDimitry Andric   }
17940b57cec5SDimitry Andric 
17950b57cec5SDimitry Andric   for (auto *A :
17960b57cec5SDimitry Andric        Args.filtered(OPT_mlink_bitcode_file, OPT_mlink_builtin_bitcode)) {
17970b57cec5SDimitry Andric     CodeGenOptions::BitcodeFileToLink F;
17980b57cec5SDimitry Andric     F.Filename = A->getValue();
17990b57cec5SDimitry Andric     if (A->getOption().matches(OPT_mlink_builtin_bitcode)) {
18000b57cec5SDimitry Andric       F.LinkFlags = llvm::Linker::Flags::LinkOnlyNeeded;
18010b57cec5SDimitry Andric       // When linking CUDA bitcode, propagate function attributes so that
18020b57cec5SDimitry Andric       // e.g. libdevice gets fast-math attrs if we're building with fast-math.
18030b57cec5SDimitry Andric       F.PropagateAttrs = true;
18040b57cec5SDimitry Andric       F.Internalize = true;
18050b57cec5SDimitry Andric     }
18060b57cec5SDimitry Andric     Opts.LinkBitcodeFiles.push_back(F);
18070b57cec5SDimitry Andric   }
18080b57cec5SDimitry Andric 
18090b57cec5SDimitry Andric   if (Args.getLastArg(OPT_femulated_tls) ||
18100b57cec5SDimitry Andric       Args.getLastArg(OPT_fno_emulated_tls)) {
18110b57cec5SDimitry Andric     Opts.ExplicitEmulatedTLS = true;
18120b57cec5SDimitry Andric   }
18130b57cec5SDimitry Andric 
18145f7ddb14SDimitry Andric   if (Arg *A = Args.getLastArg(OPT_ftlsmodel_EQ)) {
18155f7ddb14SDimitry Andric     if (T.isOSAIX()) {
18165f7ddb14SDimitry Andric       StringRef Name = A->getValue();
18175f7ddb14SDimitry Andric       if (Name != "global-dynamic")
18185f7ddb14SDimitry Andric         Diags.Report(diag::err_aix_unsupported_tls_model) << Name;
18195f7ddb14SDimitry Andric     }
18205f7ddb14SDimitry Andric   }
18215f7ddb14SDimitry Andric 
18220b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(OPT_fdenormal_fp_math_EQ)) {
18230b57cec5SDimitry Andric     StringRef Val = A->getValue();
1824480093f4SDimitry Andric     Opts.FPDenormalMode = llvm::parseDenormalFPAttribute(Val);
18255ffd83dbSDimitry Andric     if (!Opts.FPDenormalMode.isValid())
18265ffd83dbSDimitry Andric       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
18275ffd83dbSDimitry Andric   }
18285ffd83dbSDimitry Andric 
18295ffd83dbSDimitry Andric   if (Arg *A = Args.getLastArg(OPT_fdenormal_fp_math_f32_EQ)) {
18305ffd83dbSDimitry Andric     StringRef Val = A->getValue();
18315ffd83dbSDimitry Andric     Opts.FP32DenormalMode = llvm::parseDenormalFPAttribute(Val);
18325ffd83dbSDimitry Andric     if (!Opts.FP32DenormalMode.isValid())
18330b57cec5SDimitry Andric       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
18340b57cec5SDimitry Andric   }
18350b57cec5SDimitry Andric 
1836e86cf8adSDimitry Andric   // X86_32 has -fppc-struct-return and -freg-struct-return.
1837e86cf8adSDimitry Andric   // PPC32 has -maix-struct-return and -msvr4-struct-return.
1838e86cf8adSDimitry Andric   if (Arg *A =
1839e86cf8adSDimitry Andric           Args.getLastArg(OPT_fpcc_struct_return, OPT_freg_struct_return,
1840e86cf8adSDimitry Andric                           OPT_maix_struct_return, OPT_msvr4_struct_return)) {
18415ffd83dbSDimitry Andric     // TODO: We might want to consider enabling these options on AIX in the
18425ffd83dbSDimitry Andric     // future.
18435ffd83dbSDimitry Andric     if (T.isOSAIX())
18445ffd83dbSDimitry Andric       Diags.Report(diag::err_drv_unsupported_opt_for_target)
18455ffd83dbSDimitry Andric           << A->getSpelling() << T.str();
18465ffd83dbSDimitry Andric 
1847e86cf8adSDimitry Andric     const Option &O = A->getOption();
1848e86cf8adSDimitry Andric     if (O.matches(OPT_fpcc_struct_return) ||
1849e86cf8adSDimitry Andric         O.matches(OPT_maix_struct_return)) {
18500b57cec5SDimitry Andric       Opts.setStructReturnConvention(CodeGenOptions::SRCK_OnStack);
18510b57cec5SDimitry Andric     } else {
1852e86cf8adSDimitry Andric       assert(O.matches(OPT_freg_struct_return) ||
1853e86cf8adSDimitry Andric              O.matches(OPT_msvr4_struct_return));
18540b57cec5SDimitry Andric       Opts.setStructReturnConvention(CodeGenOptions::SRCK_InRegs);
18550b57cec5SDimitry Andric     }
18560b57cec5SDimitry Andric   }
18570b57cec5SDimitry Andric 
1858af732203SDimitry Andric   if (Arg *A =
1859af732203SDimitry Andric           Args.getLastArg(OPT_mabi_EQ_vec_default, OPT_mabi_EQ_vec_extabi)) {
1860af732203SDimitry Andric     if (!T.isOSAIX())
1861af732203SDimitry Andric       Diags.Report(diag::err_drv_unsupported_opt_for_target)
1862af732203SDimitry Andric           << A->getSpelling() << T.str();
1863af732203SDimitry Andric 
1864af732203SDimitry Andric     const Option &O = A->getOption();
18655f7ddb14SDimitry Andric     Opts.EnableAIXExtendedAltivecABI = O.matches(OPT_mabi_EQ_vec_extabi);
1866af732203SDimitry Andric   }
1867af732203SDimitry Andric 
18680b57cec5SDimitry Andric   bool NeedLocTracking = false;
18690b57cec5SDimitry Andric 
18700b57cec5SDimitry Andric   if (!Opts.OptRecordFile.empty())
18710b57cec5SDimitry Andric     NeedLocTracking = true;
18720b57cec5SDimitry Andric 
18730b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(OPT_opt_record_passes)) {
18740b57cec5SDimitry Andric     Opts.OptRecordPasses = A->getValue();
18750b57cec5SDimitry Andric     NeedLocTracking = true;
18760b57cec5SDimitry Andric   }
18770b57cec5SDimitry Andric 
18780b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(OPT_opt_record_format)) {
18790b57cec5SDimitry Andric     Opts.OptRecordFormat = A->getValue();
18800b57cec5SDimitry Andric     NeedLocTracking = true;
18810b57cec5SDimitry Andric   }
18820b57cec5SDimitry Andric 
18835f7ddb14SDimitry Andric   Opts.OptimizationRemark =
18845f7ddb14SDimitry Andric       ParseOptimizationRemark(Diags, Args, OPT_Rpass_EQ, "pass");
18850b57cec5SDimitry Andric 
18865f7ddb14SDimitry Andric   Opts.OptimizationRemarkMissed =
18875f7ddb14SDimitry Andric       ParseOptimizationRemark(Diags, Args, OPT_Rpass_missed_EQ, "pass-missed");
18880b57cec5SDimitry Andric 
18895f7ddb14SDimitry Andric   Opts.OptimizationRemarkAnalysis = ParseOptimizationRemark(
18905f7ddb14SDimitry Andric       Diags, Args, OPT_Rpass_analysis_EQ, "pass-analysis");
18915f7ddb14SDimitry Andric 
18925f7ddb14SDimitry Andric   NeedLocTracking |= Opts.OptimizationRemark.hasValidPattern() ||
18935f7ddb14SDimitry Andric                      Opts.OptimizationRemarkMissed.hasValidPattern() ||
18945f7ddb14SDimitry Andric                      Opts.OptimizationRemarkAnalysis.hasValidPattern();
18950b57cec5SDimitry Andric 
18960b57cec5SDimitry Andric   bool UsingSampleProfile = !Opts.SampleProfileFile.empty();
18970b57cec5SDimitry Andric   bool UsingProfile = UsingSampleProfile ||
18980b57cec5SDimitry Andric       (Opts.getProfileUse() != CodeGenOptions::ProfileNone);
18990b57cec5SDimitry Andric 
19000b57cec5SDimitry Andric   if (Opts.DiagnosticsWithHotness && !UsingProfile &&
19010b57cec5SDimitry Andric       // An IR file will contain PGO as metadata
1902a7dea167SDimitry Andric       IK.getLanguage() != Language::LLVM_IR)
19030b57cec5SDimitry Andric     Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo)
19040b57cec5SDimitry Andric         << "-fdiagnostics-show-hotness";
19050b57cec5SDimitry Andric 
1906af732203SDimitry Andric   // Parse remarks hotness threshold. Valid value is either integer or 'auto'.
1907af732203SDimitry Andric   if (auto *arg =
1908af732203SDimitry Andric           Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
1909af732203SDimitry Andric     auto ResultOrErr =
1910af732203SDimitry Andric         llvm::remarks::parseHotnessThresholdOption(arg->getValue());
1911af732203SDimitry Andric 
1912af732203SDimitry Andric     if (!ResultOrErr) {
1913af732203SDimitry Andric       Diags.Report(diag::err_drv_invalid_diagnotics_hotness_threshold)
1914af732203SDimitry Andric           << "-fdiagnostics-hotness-threshold=";
1915af732203SDimitry Andric     } else {
1916af732203SDimitry Andric       Opts.DiagnosticsHotnessThreshold = *ResultOrErr;
1917af732203SDimitry Andric       if ((!Opts.DiagnosticsHotnessThreshold.hasValue() ||
1918af732203SDimitry Andric            Opts.DiagnosticsHotnessThreshold.getValue() > 0) &&
1919af732203SDimitry Andric           !UsingProfile)
19200b57cec5SDimitry Andric         Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo)
19210b57cec5SDimitry Andric             << "-fdiagnostics-hotness-threshold=";
1922af732203SDimitry Andric     }
1923af732203SDimitry Andric   }
19240b57cec5SDimitry Andric 
19250b57cec5SDimitry Andric   // If the user requested to use a sample profile for PGO, then the
19260b57cec5SDimitry Andric   // backend will need to track source location information so the profile
19270b57cec5SDimitry Andric   // can be incorporated into the IR.
19280b57cec5SDimitry Andric   if (UsingSampleProfile)
19290b57cec5SDimitry Andric     NeedLocTracking = true;
19300b57cec5SDimitry Andric 
19315f7ddb14SDimitry Andric   if (!Opts.StackUsageOutput.empty())
19325f7ddb14SDimitry Andric     NeedLocTracking = true;
19335f7ddb14SDimitry Andric 
19340b57cec5SDimitry Andric   // If the user requested a flag that requires source locations available in
19350b57cec5SDimitry Andric   // the backend, make sure that the backend tracks source location information.
19360b57cec5SDimitry Andric   if (NeedLocTracking && Opts.getDebugInfo() == codegenoptions::NoDebugInfo)
19370b57cec5SDimitry Andric     Opts.setDebugInfo(codegenoptions::LocTrackingOnly);
19380b57cec5SDimitry Andric 
19390b57cec5SDimitry Andric   // Parse -fsanitize-recover= arguments.
19400b57cec5SDimitry Andric   // FIXME: Report unrecoverable sanitizers incorrectly specified here.
19410b57cec5SDimitry Andric   parseSanitizerKinds("-fsanitize-recover=",
19420b57cec5SDimitry Andric                       Args.getAllArgValues(OPT_fsanitize_recover_EQ), Diags,
19430b57cec5SDimitry Andric                       Opts.SanitizeRecover);
19440b57cec5SDimitry Andric   parseSanitizerKinds("-fsanitize-trap=",
19450b57cec5SDimitry Andric                       Args.getAllArgValues(OPT_fsanitize_trap_EQ), Diags,
19460b57cec5SDimitry Andric                       Opts.SanitizeTrap);
19470b57cec5SDimitry Andric 
19480b57cec5SDimitry Andric   Opts.EmitVersionIdentMetadata = Args.hasFlag(OPT_Qy, OPT_Qn, true);
19490b57cec5SDimitry Andric 
1950af732203SDimitry Andric   if (Args.hasArg(options::OPT_ffinite_loops))
1951af732203SDimitry Andric     Opts.FiniteLoops = CodeGenOptions::FiniteLoopsKind::Always;
1952af732203SDimitry Andric   else if (Args.hasArg(options::OPT_fno_finite_loops))
1953af732203SDimitry Andric     Opts.FiniteLoops = CodeGenOptions::FiniteLoopsKind::Never;
19545f7ddb14SDimitry Andric 
19555f7ddb14SDimitry Andric   Opts.EmitIEEENaNCompliantInsts =
19565f7ddb14SDimitry Andric       Args.hasFlag(options::OPT_mamdgpu_ieee, options::OPT_mno_amdgpu_ieee);
19575f7ddb14SDimitry Andric   if (!Opts.EmitIEEENaNCompliantInsts && !LangOptsRef.NoHonorNaNs)
19585f7ddb14SDimitry Andric     Diags.Report(diag::err_drv_amdgpu_ieee_without_no_honor_nans);
19595f7ddb14SDimitry Andric 
19605f7ddb14SDimitry Andric   return Diags.getNumErrors() == NumErrorsBefore;
19610b57cec5SDimitry Andric }
19620b57cec5SDimitry Andric 
19635f7ddb14SDimitry Andric static void
GenerateDependencyOutputArgs(const DependencyOutputOptions & Opts,SmallVectorImpl<const char * > & Args,CompilerInvocation::StringAllocator SA)19645f7ddb14SDimitry Andric GenerateDependencyOutputArgs(const DependencyOutputOptions &Opts,
19655f7ddb14SDimitry Andric                              SmallVectorImpl<const char *> &Args,
19665f7ddb14SDimitry Andric                              CompilerInvocation::StringAllocator SA) {
19675f7ddb14SDimitry Andric   const DependencyOutputOptions &DependencyOutputOpts = Opts;
19685f7ddb14SDimitry Andric #define DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING(                             \
19695f7ddb14SDimitry Andric     PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,        \
19705f7ddb14SDimitry Andric     HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
19715f7ddb14SDimitry Andric     DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER,     \
19725f7ddb14SDimitry Andric     MERGER, EXTRACTOR, TABLE_INDEX)                                            \
19735f7ddb14SDimitry Andric   GENERATE_OPTION_WITH_MARSHALLING(                                            \
19745f7ddb14SDimitry Andric       Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE,    \
19755f7ddb14SDimitry Andric       IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
19765f7ddb14SDimitry Andric #include "clang/Driver/Options.inc"
19775f7ddb14SDimitry Andric #undef DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING
19785f7ddb14SDimitry Andric 
19795f7ddb14SDimitry Andric   if (Opts.ShowIncludesDest != ShowIncludesDestination::None)
19805f7ddb14SDimitry Andric     GenerateArg(Args, OPT_show_includes, SA);
19815f7ddb14SDimitry Andric 
19825f7ddb14SDimitry Andric   for (const auto &Dep : Opts.ExtraDeps) {
19835f7ddb14SDimitry Andric     switch (Dep.second) {
19845f7ddb14SDimitry Andric     case EDK_SanitizeIgnorelist:
19855f7ddb14SDimitry Andric       // Sanitizer ignorelist arguments are generated from LanguageOptions.
19865f7ddb14SDimitry Andric       continue;
19875f7ddb14SDimitry Andric     case EDK_ModuleFile:
19885f7ddb14SDimitry Andric       // Module file arguments are generated from FrontendOptions and
19895f7ddb14SDimitry Andric       // HeaderSearchOptions.
19905f7ddb14SDimitry Andric       continue;
19915f7ddb14SDimitry Andric     case EDK_ProfileList:
19925f7ddb14SDimitry Andric       // Profile list arguments are generated from LanguageOptions via the
19935f7ddb14SDimitry Andric       // marshalling infrastructure.
19945f7ddb14SDimitry Andric       continue;
19955f7ddb14SDimitry Andric     case EDK_DepFileEntry:
19965f7ddb14SDimitry Andric       GenerateArg(Args, OPT_fdepfile_entry, Dep.first, SA);
19975f7ddb14SDimitry Andric       break;
19985f7ddb14SDimitry Andric     }
19995f7ddb14SDimitry Andric   }
20005f7ddb14SDimitry Andric }
20015f7ddb14SDimitry Andric 
ParseDependencyOutputArgs(DependencyOutputOptions & Opts,ArgList & Args,DiagnosticsEngine & Diags,frontend::ActionKind Action,bool ShowLineMarkers)20025f7ddb14SDimitry Andric static bool ParseDependencyOutputArgs(DependencyOutputOptions &Opts,
20035f7ddb14SDimitry Andric                                       ArgList &Args, DiagnosticsEngine &Diags,
20045f7ddb14SDimitry Andric                                       frontend::ActionKind Action,
20055f7ddb14SDimitry Andric                                       bool ShowLineMarkers) {
20065f7ddb14SDimitry Andric   unsigned NumErrorsBefore = Diags.getNumErrors();
20075f7ddb14SDimitry Andric 
20085f7ddb14SDimitry Andric   DependencyOutputOptions &DependencyOutputOpts = Opts;
20095f7ddb14SDimitry Andric #define DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING(                             \
20105f7ddb14SDimitry Andric     PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,        \
20115f7ddb14SDimitry Andric     HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
20125f7ddb14SDimitry Andric     DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER,     \
20135f7ddb14SDimitry Andric     MERGER, EXTRACTOR, TABLE_INDEX)                                            \
20145f7ddb14SDimitry Andric   PARSE_OPTION_WITH_MARSHALLING(                                               \
20155f7ddb14SDimitry Andric       Args, Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE,     \
20165f7ddb14SDimitry Andric       IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
20175f7ddb14SDimitry Andric #include "clang/Driver/Options.inc"
20185f7ddb14SDimitry Andric #undef DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING
20195f7ddb14SDimitry Andric 
20200b57cec5SDimitry Andric   if (Args.hasArg(OPT_show_includes)) {
20210b57cec5SDimitry Andric     // Writing both /showIncludes and preprocessor output to stdout
20220b57cec5SDimitry Andric     // would produce interleaved output, so use stderr for /showIncludes.
20230b57cec5SDimitry Andric     // This behaves the same as cl.exe, when /E, /EP or /P are passed.
20245f7ddb14SDimitry Andric     if (Action == frontend::PrintPreprocessedInput || !ShowLineMarkers)
20250b57cec5SDimitry Andric       Opts.ShowIncludesDest = ShowIncludesDestination::Stderr;
20260b57cec5SDimitry Andric     else
20270b57cec5SDimitry Andric       Opts.ShowIncludesDest = ShowIncludesDestination::Stdout;
20280b57cec5SDimitry Andric   } else {
20290b57cec5SDimitry Andric     Opts.ShowIncludesDest = ShowIncludesDestination::None;
20300b57cec5SDimitry Andric   }
20315f7ddb14SDimitry Andric 
20325f7ddb14SDimitry Andric   // Add sanitizer ignorelists as extra dependencies.
20330b57cec5SDimitry Andric   // They won't be discovered by the regular preprocessor, so
20340b57cec5SDimitry Andric   // we let make / ninja to know about this implicit dependency.
20355f7ddb14SDimitry Andric   if (!Args.hasArg(OPT_fno_sanitize_ignorelist)) {
20365f7ddb14SDimitry Andric     for (const auto *A : Args.filtered(OPT_fsanitize_ignorelist_EQ)) {
2037480093f4SDimitry Andric       StringRef Val = A->getValue();
2038480093f4SDimitry Andric       if (Val.find('=') == StringRef::npos)
20395f7ddb14SDimitry Andric         Opts.ExtraDeps.emplace_back(std::string(Val), EDK_SanitizeIgnorelist);
2040480093f4SDimitry Andric     }
2041480093f4SDimitry Andric     if (Opts.IncludeSystemHeaders) {
20425f7ddb14SDimitry Andric       for (const auto *A : Args.filtered(OPT_fsanitize_system_ignorelist_EQ)) {
2043480093f4SDimitry Andric         StringRef Val = A->getValue();
2044480093f4SDimitry Andric         if (Val.find('=') == StringRef::npos)
20455f7ddb14SDimitry Andric           Opts.ExtraDeps.emplace_back(std::string(Val), EDK_SanitizeIgnorelist);
2046480093f4SDimitry Andric       }
2047480093f4SDimitry Andric     }
2048480093f4SDimitry Andric   }
2049480093f4SDimitry Andric 
2050af732203SDimitry Andric   // -fprofile-list= dependencies.
2051af732203SDimitry Andric   for (const auto &Filename : Args.getAllArgValues(OPT_fprofile_list_EQ))
20525f7ddb14SDimitry Andric     Opts.ExtraDeps.emplace_back(Filename, EDK_ProfileList);
2053af732203SDimitry Andric 
2054480093f4SDimitry Andric   // Propagate the extra dependencies.
20555f7ddb14SDimitry Andric   for (const auto *A : Args.filtered(OPT_fdepfile_entry))
20565f7ddb14SDimitry Andric     Opts.ExtraDeps.emplace_back(A->getValue(), EDK_DepFileEntry);
2057480093f4SDimitry Andric 
20580b57cec5SDimitry Andric   // Only the -fmodule-file=<file> form.
20590b57cec5SDimitry Andric   for (const auto *A : Args.filtered(OPT_fmodule_file)) {
20600b57cec5SDimitry Andric     StringRef Val = A->getValue();
20610b57cec5SDimitry Andric     if (Val.find('=') == StringRef::npos)
20625f7ddb14SDimitry Andric       Opts.ExtraDeps.emplace_back(std::string(Val), EDK_ModuleFile);
20630b57cec5SDimitry Andric   }
20645f7ddb14SDimitry Andric 
20655f7ddb14SDimitry Andric   return Diags.getNumErrors() == NumErrorsBefore;
20660b57cec5SDimitry Andric }
20670b57cec5SDimitry Andric 
parseShowColorsArgs(const ArgList & Args,bool DefaultColor)20680b57cec5SDimitry Andric static bool parseShowColorsArgs(const ArgList &Args, bool DefaultColor) {
20690b57cec5SDimitry Andric   // Color diagnostics default to auto ("on" if terminal supports) in the driver
20700b57cec5SDimitry Andric   // but default to off in cc1, needing an explicit OPT_fdiagnostics_color.
20710b57cec5SDimitry Andric   // Support both clang's -f[no-]color-diagnostics and gcc's
20720b57cec5SDimitry Andric   // -f[no-]diagnostics-colors[=never|always|auto].
20730b57cec5SDimitry Andric   enum {
20740b57cec5SDimitry Andric     Colors_On,
20750b57cec5SDimitry Andric     Colors_Off,
20760b57cec5SDimitry Andric     Colors_Auto
20770b57cec5SDimitry Andric   } ShowColors = DefaultColor ? Colors_Auto : Colors_Off;
20780b57cec5SDimitry Andric   for (auto *A : Args) {
20790b57cec5SDimitry Andric     const Option &O = A->getOption();
20800b57cec5SDimitry Andric     if (O.matches(options::OPT_fcolor_diagnostics) ||
20810b57cec5SDimitry Andric         O.matches(options::OPT_fdiagnostics_color)) {
20820b57cec5SDimitry Andric       ShowColors = Colors_On;
20830b57cec5SDimitry Andric     } else if (O.matches(options::OPT_fno_color_diagnostics) ||
20840b57cec5SDimitry Andric                O.matches(options::OPT_fno_diagnostics_color)) {
20850b57cec5SDimitry Andric       ShowColors = Colors_Off;
20860b57cec5SDimitry Andric     } else if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
20870b57cec5SDimitry Andric       StringRef Value(A->getValue());
20880b57cec5SDimitry Andric       if (Value == "always")
20890b57cec5SDimitry Andric         ShowColors = Colors_On;
20900b57cec5SDimitry Andric       else if (Value == "never")
20910b57cec5SDimitry Andric         ShowColors = Colors_Off;
20920b57cec5SDimitry Andric       else if (Value == "auto")
20930b57cec5SDimitry Andric         ShowColors = Colors_Auto;
20940b57cec5SDimitry Andric     }
20950b57cec5SDimitry Andric   }
20960b57cec5SDimitry Andric   return ShowColors == Colors_On ||
20970b57cec5SDimitry Andric          (ShowColors == Colors_Auto &&
20980b57cec5SDimitry Andric           llvm::sys::Process::StandardErrHasColors());
20990b57cec5SDimitry Andric }
21000b57cec5SDimitry Andric 
checkVerifyPrefixes(const std::vector<std::string> & VerifyPrefixes,DiagnosticsEngine & Diags)21010b57cec5SDimitry Andric static bool checkVerifyPrefixes(const std::vector<std::string> &VerifyPrefixes,
2102af732203SDimitry Andric                                 DiagnosticsEngine &Diags) {
21030b57cec5SDimitry Andric   bool Success = true;
21040b57cec5SDimitry Andric   for (const auto &Prefix : VerifyPrefixes) {
21050b57cec5SDimitry Andric     // Every prefix must start with a letter and contain only alphanumeric
21060b57cec5SDimitry Andric     // characters, hyphens, and underscores.
21070b57cec5SDimitry Andric     auto BadChar = llvm::find_if(Prefix, [](char C) {
21080b57cec5SDimitry Andric       return !isAlphanumeric(C) && C != '-' && C != '_';
21090b57cec5SDimitry Andric     });
21100b57cec5SDimitry Andric     if (BadChar != Prefix.end() || !isLetter(Prefix[0])) {
21110b57cec5SDimitry Andric       Success = false;
2112af732203SDimitry Andric       Diags.Report(diag::err_drv_invalid_value) << "-verify=" << Prefix;
2113af732203SDimitry Andric       Diags.Report(diag::note_drv_verify_prefix_spelling);
21140b57cec5SDimitry Andric     }
21150b57cec5SDimitry Andric   }
2116af732203SDimitry Andric   return Success;
21170b57cec5SDimitry Andric }
2118af732203SDimitry Andric 
GenerateFileSystemArgs(const FileSystemOptions & Opts,SmallVectorImpl<const char * > & Args,CompilerInvocation::StringAllocator SA)21195f7ddb14SDimitry Andric static void GenerateFileSystemArgs(const FileSystemOptions &Opts,
21205f7ddb14SDimitry Andric                                    SmallVectorImpl<const char *> &Args,
21215f7ddb14SDimitry Andric                                    CompilerInvocation::StringAllocator SA) {
21225f7ddb14SDimitry Andric   const FileSystemOptions &FileSystemOpts = Opts;
2123af732203SDimitry Andric 
21245f7ddb14SDimitry Andric #define FILE_SYSTEM_OPTION_WITH_MARSHALLING(                                   \
2125af732203SDimitry Andric     PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,        \
2126af732203SDimitry Andric     HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
2127af732203SDimitry Andric     DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER,     \
2128af732203SDimitry Andric     MERGER, EXTRACTOR, TABLE_INDEX)                                            \
21295f7ddb14SDimitry Andric   GENERATE_OPTION_WITH_MARSHALLING(                                            \
21305f7ddb14SDimitry Andric       Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE,    \
21315f7ddb14SDimitry Andric       IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
2132af732203SDimitry Andric #include "clang/Driver/Options.inc"
21335f7ddb14SDimitry Andric #undef FILE_SYSTEM_OPTION_WITH_MARSHALLING
21345f7ddb14SDimitry Andric }
2135af732203SDimitry Andric 
ParseFileSystemArgs(FileSystemOptions & Opts,const ArgList & Args,DiagnosticsEngine & Diags)21365f7ddb14SDimitry Andric static bool ParseFileSystemArgs(FileSystemOptions &Opts, const ArgList &Args,
21375f7ddb14SDimitry Andric                                 DiagnosticsEngine &Diags) {
21385f7ddb14SDimitry Andric   unsigned NumErrorsBefore = Diags.getNumErrors();
21395f7ddb14SDimitry Andric 
21405f7ddb14SDimitry Andric   FileSystemOptions &FileSystemOpts = Opts;
21415f7ddb14SDimitry Andric 
21425f7ddb14SDimitry Andric #define FILE_SYSTEM_OPTION_WITH_MARSHALLING(                                   \
21435f7ddb14SDimitry Andric     PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,        \
21445f7ddb14SDimitry Andric     HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
21455f7ddb14SDimitry Andric     DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER,     \
21465f7ddb14SDimitry Andric     MERGER, EXTRACTOR, TABLE_INDEX)                                            \
21475f7ddb14SDimitry Andric   PARSE_OPTION_WITH_MARSHALLING(                                               \
21485f7ddb14SDimitry Andric       Args, Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE,     \
21495f7ddb14SDimitry Andric       IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
21505f7ddb14SDimitry Andric #include "clang/Driver/Options.inc"
21515f7ddb14SDimitry Andric #undef FILE_SYSTEM_OPTION_WITH_MARSHALLING
21525f7ddb14SDimitry Andric 
21535f7ddb14SDimitry Andric   return Diags.getNumErrors() == NumErrorsBefore;
21545f7ddb14SDimitry Andric }
21555f7ddb14SDimitry Andric 
GenerateMigratorArgs(const MigratorOptions & Opts,SmallVectorImpl<const char * > & Args,CompilerInvocation::StringAllocator SA)21565f7ddb14SDimitry Andric static void GenerateMigratorArgs(const MigratorOptions &Opts,
21575f7ddb14SDimitry Andric                                  SmallVectorImpl<const char *> &Args,
21585f7ddb14SDimitry Andric                                  CompilerInvocation::StringAllocator SA) {
21595f7ddb14SDimitry Andric   const MigratorOptions &MigratorOpts = Opts;
21605f7ddb14SDimitry Andric #define MIGRATOR_OPTION_WITH_MARSHALLING(                                      \
21615f7ddb14SDimitry Andric     PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,        \
21625f7ddb14SDimitry Andric     HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
21635f7ddb14SDimitry Andric     DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER,     \
21645f7ddb14SDimitry Andric     MERGER, EXTRACTOR, TABLE_INDEX)                                            \
21655f7ddb14SDimitry Andric   GENERATE_OPTION_WITH_MARSHALLING(                                            \
21665f7ddb14SDimitry Andric       Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE,    \
21675f7ddb14SDimitry Andric       IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
21685f7ddb14SDimitry Andric #include "clang/Driver/Options.inc"
21695f7ddb14SDimitry Andric #undef MIGRATOR_OPTION_WITH_MARSHALLING
21705f7ddb14SDimitry Andric }
21715f7ddb14SDimitry Andric 
ParseMigratorArgs(MigratorOptions & Opts,const ArgList & Args,DiagnosticsEngine & Diags)21725f7ddb14SDimitry Andric static bool ParseMigratorArgs(MigratorOptions &Opts, const ArgList &Args,
21735f7ddb14SDimitry Andric                               DiagnosticsEngine &Diags) {
21745f7ddb14SDimitry Andric   unsigned NumErrorsBefore = Diags.getNumErrors();
21755f7ddb14SDimitry Andric 
21765f7ddb14SDimitry Andric   MigratorOptions &MigratorOpts = Opts;
21775f7ddb14SDimitry Andric 
21785f7ddb14SDimitry Andric #define MIGRATOR_OPTION_WITH_MARSHALLING(                                      \
21795f7ddb14SDimitry Andric     PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,        \
21805f7ddb14SDimitry Andric     HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
21815f7ddb14SDimitry Andric     DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER,     \
21825f7ddb14SDimitry Andric     MERGER, EXTRACTOR, TABLE_INDEX)                                            \
21835f7ddb14SDimitry Andric   PARSE_OPTION_WITH_MARSHALLING(                                               \
21845f7ddb14SDimitry Andric       Args, Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE,     \
21855f7ddb14SDimitry Andric       IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
21865f7ddb14SDimitry Andric #include "clang/Driver/Options.inc"
21875f7ddb14SDimitry Andric #undef MIGRATOR_OPTION_WITH_MARSHALLING
21885f7ddb14SDimitry Andric 
21895f7ddb14SDimitry Andric   return Diags.getNumErrors() == NumErrorsBefore;
21905f7ddb14SDimitry Andric }
21915f7ddb14SDimitry Andric 
GenerateDiagnosticArgs(const DiagnosticOptions & Opts,SmallVectorImpl<const char * > & Args,StringAllocator SA,bool DefaultDiagColor)21925f7ddb14SDimitry Andric void CompilerInvocation::GenerateDiagnosticArgs(
21935f7ddb14SDimitry Andric     const DiagnosticOptions &Opts, SmallVectorImpl<const char *> &Args,
21945f7ddb14SDimitry Andric     StringAllocator SA, bool DefaultDiagColor) {
21955f7ddb14SDimitry Andric   const DiagnosticOptions *DiagnosticOpts = &Opts;
21965f7ddb14SDimitry Andric #define DIAG_OPTION_WITH_MARSHALLING(                                          \
21975f7ddb14SDimitry Andric     PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,        \
21985f7ddb14SDimitry Andric     HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
21995f7ddb14SDimitry Andric     DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER,     \
22005f7ddb14SDimitry Andric     MERGER, EXTRACTOR, TABLE_INDEX)                                            \
22015f7ddb14SDimitry Andric   GENERATE_OPTION_WITH_MARSHALLING(                                            \
22025f7ddb14SDimitry Andric       Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE,    \
22035f7ddb14SDimitry Andric       IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
22045f7ddb14SDimitry Andric #include "clang/Driver/Options.inc"
22055f7ddb14SDimitry Andric #undef DIAG_OPTION_WITH_MARSHALLING
22065f7ddb14SDimitry Andric 
22075f7ddb14SDimitry Andric   if (!Opts.DiagnosticSerializationFile.empty())
22085f7ddb14SDimitry Andric     GenerateArg(Args, OPT_diagnostic_serialized_file,
22095f7ddb14SDimitry Andric                 Opts.DiagnosticSerializationFile, SA);
22105f7ddb14SDimitry Andric 
22115f7ddb14SDimitry Andric   if (Opts.ShowColors)
22125f7ddb14SDimitry Andric     GenerateArg(Args, OPT_fcolor_diagnostics, SA);
22135f7ddb14SDimitry Andric 
22145f7ddb14SDimitry Andric   if (Opts.VerifyDiagnostics &&
22155f7ddb14SDimitry Andric       llvm::is_contained(Opts.VerifyPrefixes, "expected"))
22165f7ddb14SDimitry Andric     GenerateArg(Args, OPT_verify, SA);
22175f7ddb14SDimitry Andric 
22185f7ddb14SDimitry Andric   for (const auto &Prefix : Opts.VerifyPrefixes)
22195f7ddb14SDimitry Andric     if (Prefix != "expected")
22205f7ddb14SDimitry Andric       GenerateArg(Args, OPT_verify_EQ, Prefix, SA);
22215f7ddb14SDimitry Andric 
22225f7ddb14SDimitry Andric   DiagnosticLevelMask VIU = Opts.getVerifyIgnoreUnexpected();
22235f7ddb14SDimitry Andric   if (VIU == DiagnosticLevelMask::None) {
22245f7ddb14SDimitry Andric     // This is the default, don't generate anything.
22255f7ddb14SDimitry Andric   } else if (VIU == DiagnosticLevelMask::All) {
22265f7ddb14SDimitry Andric     GenerateArg(Args, OPT_verify_ignore_unexpected, SA);
22275f7ddb14SDimitry Andric   } else {
22285f7ddb14SDimitry Andric     if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Note) != 0)
22295f7ddb14SDimitry Andric       GenerateArg(Args, OPT_verify_ignore_unexpected_EQ, "note", SA);
22305f7ddb14SDimitry Andric     if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Remark) != 0)
22315f7ddb14SDimitry Andric       GenerateArg(Args, OPT_verify_ignore_unexpected_EQ, "remark", SA);
22325f7ddb14SDimitry Andric     if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Warning) != 0)
22335f7ddb14SDimitry Andric       GenerateArg(Args, OPT_verify_ignore_unexpected_EQ, "warning", SA);
22345f7ddb14SDimitry Andric     if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Error) != 0)
22355f7ddb14SDimitry Andric       GenerateArg(Args, OPT_verify_ignore_unexpected_EQ, "error", SA);
22365f7ddb14SDimitry Andric   }
22375f7ddb14SDimitry Andric 
22385f7ddb14SDimitry Andric   for (const auto &Warning : Opts.Warnings) {
22395f7ddb14SDimitry Andric     // This option is automatically generated from UndefPrefixes.
22405f7ddb14SDimitry Andric     if (Warning == "undef-prefix")
22415f7ddb14SDimitry Andric       continue;
22425f7ddb14SDimitry Andric     Args.push_back(SA(StringRef("-W") + Warning));
22435f7ddb14SDimitry Andric   }
22445f7ddb14SDimitry Andric 
22455f7ddb14SDimitry Andric   for (const auto &Remark : Opts.Remarks) {
22465f7ddb14SDimitry Andric     // These arguments are generated from OptimizationRemark fields of
22475f7ddb14SDimitry Andric     // CodeGenOptions.
22485f7ddb14SDimitry Andric     StringRef IgnoredRemarks[] = {"pass",          "no-pass",
22495f7ddb14SDimitry Andric                                   "pass-analysis", "no-pass-analysis",
22505f7ddb14SDimitry Andric                                   "pass-missed",   "no-pass-missed"};
22515f7ddb14SDimitry Andric     if (llvm::is_contained(IgnoredRemarks, Remark))
22525f7ddb14SDimitry Andric       continue;
22535f7ddb14SDimitry Andric 
22545f7ddb14SDimitry Andric     Args.push_back(SA(StringRef("-R") + Remark));
22555f7ddb14SDimitry Andric   }
22560b57cec5SDimitry Andric }
22570b57cec5SDimitry Andric 
ParseDiagnosticArgs(DiagnosticOptions & Opts,ArgList & Args,DiagnosticsEngine * Diags,bool DefaultDiagColor)22580b57cec5SDimitry Andric bool clang::ParseDiagnosticArgs(DiagnosticOptions &Opts, ArgList &Args,
22590b57cec5SDimitry Andric                                 DiagnosticsEngine *Diags,
22605ffd83dbSDimitry Andric                                 bool DefaultDiagColor) {
2261af732203SDimitry Andric   Optional<DiagnosticsEngine> IgnoringDiags;
2262af732203SDimitry Andric   if (!Diags) {
2263af732203SDimitry Andric     IgnoringDiags.emplace(new DiagnosticIDs(), new DiagnosticOptions(),
2264af732203SDimitry Andric                           new IgnoringDiagConsumer());
2265af732203SDimitry Andric     Diags = &*IgnoringDiags;
2266af732203SDimitry Andric   }
2267af732203SDimitry Andric 
22685f7ddb14SDimitry Andric   unsigned NumErrorsBefore = Diags->getNumErrors();
22695f7ddb14SDimitry Andric 
2270af732203SDimitry Andric   // The key paths of diagnostic options defined in Options.td start with
2271af732203SDimitry Andric   // "DiagnosticOpts->". Let's provide the expected variable name and type.
2272af732203SDimitry Andric   DiagnosticOptions *DiagnosticOpts = &Opts;
22730b57cec5SDimitry Andric 
2274af732203SDimitry Andric #define DIAG_OPTION_WITH_MARSHALLING(                                          \
2275af732203SDimitry Andric     PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,        \
2276af732203SDimitry Andric     HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
2277af732203SDimitry Andric     DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER,     \
2278af732203SDimitry Andric     MERGER, EXTRACTOR, TABLE_INDEX)                                            \
22795f7ddb14SDimitry Andric   PARSE_OPTION_WITH_MARSHALLING(                                               \
22805f7ddb14SDimitry Andric       Args, *Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE,    \
22815f7ddb14SDimitry Andric       IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
2282af732203SDimitry Andric #include "clang/Driver/Options.inc"
2283af732203SDimitry Andric #undef DIAG_OPTION_WITH_MARSHALLING
2284af732203SDimitry Andric 
2285af732203SDimitry Andric   llvm::sys::Process::UseANSIEscapeCodes(Opts.UseANSIEscapeCodes);
2286af732203SDimitry Andric 
22870b57cec5SDimitry Andric   if (Arg *A =
22880b57cec5SDimitry Andric           Args.getLastArg(OPT_diagnostic_serialized_file, OPT__serialize_diags))
22890b57cec5SDimitry Andric     Opts.DiagnosticSerializationFile = A->getValue();
22900b57cec5SDimitry Andric   Opts.ShowColors = parseShowColorsArgs(Args, DefaultDiagColor);
22910b57cec5SDimitry Andric 
22920b57cec5SDimitry Andric   Opts.VerifyDiagnostics = Args.hasArg(OPT_verify) || Args.hasArg(OPT_verify_EQ);
22935f7ddb14SDimitry Andric   Opts.VerifyPrefixes = Args.getAllArgValues(OPT_verify_EQ);
22940b57cec5SDimitry Andric   if (Args.hasArg(OPT_verify))
22950b57cec5SDimitry Andric     Opts.VerifyPrefixes.push_back("expected");
22960b57cec5SDimitry Andric   // Keep VerifyPrefixes in its original order for the sake of diagnostics, and
22970b57cec5SDimitry Andric   // then sort it to prepare for fast lookup using std::binary_search.
22985f7ddb14SDimitry Andric   if (!checkVerifyPrefixes(Opts.VerifyPrefixes, *Diags))
22990b57cec5SDimitry Andric     Opts.VerifyDiagnostics = false;
23000b57cec5SDimitry Andric   else
23010b57cec5SDimitry Andric     llvm::sort(Opts.VerifyPrefixes);
23020b57cec5SDimitry Andric   DiagnosticLevelMask DiagMask = DiagnosticLevelMask::None;
23035f7ddb14SDimitry Andric   parseDiagnosticLevelMask(
23045f7ddb14SDimitry Andric       "-verify-ignore-unexpected=",
23055f7ddb14SDimitry Andric       Args.getAllArgValues(OPT_verify_ignore_unexpected_EQ), *Diags, DiagMask);
23060b57cec5SDimitry Andric   if (Args.hasArg(OPT_verify_ignore_unexpected))
23070b57cec5SDimitry Andric     DiagMask = DiagnosticLevelMask::All;
23080b57cec5SDimitry Andric   Opts.setVerifyIgnoreUnexpected(DiagMask);
23090b57cec5SDimitry Andric   if (Opts.TabStop == 0 || Opts.TabStop > DiagnosticOptions::MaxTabStop) {
23100b57cec5SDimitry Andric     Opts.TabStop = DiagnosticOptions::DefaultTabStop;
23110b57cec5SDimitry Andric     Diags->Report(diag::warn_ignoring_ftabstop_value)
23120b57cec5SDimitry Andric         << Opts.TabStop << DiagnosticOptions::DefaultTabStop;
23130b57cec5SDimitry Andric   }
23145ffd83dbSDimitry Andric 
23150b57cec5SDimitry Andric   addDiagnosticArgs(Args, OPT_W_Group, OPT_W_value_Group, Opts.Warnings);
23160b57cec5SDimitry Andric   addDiagnosticArgs(Args, OPT_R_Group, OPT_R_value_Group, Opts.Remarks);
23170b57cec5SDimitry Andric 
23185f7ddb14SDimitry Andric   return Diags->getNumErrors() == NumErrorsBefore;
23190b57cec5SDimitry Andric }
23200b57cec5SDimitry Andric 
23210b57cec5SDimitry Andric /// Parse the argument to the -ftest-module-file-extension
23220b57cec5SDimitry Andric /// command-line argument.
23230b57cec5SDimitry Andric ///
23240b57cec5SDimitry Andric /// \returns true on error, false on success.
parseTestModuleFileExtensionArg(StringRef Arg,std::string & BlockName,unsigned & MajorVersion,unsigned & MinorVersion,bool & Hashed,std::string & UserInfo)23250b57cec5SDimitry Andric static bool parseTestModuleFileExtensionArg(StringRef Arg,
23260b57cec5SDimitry Andric                                             std::string &BlockName,
23270b57cec5SDimitry Andric                                             unsigned &MajorVersion,
23280b57cec5SDimitry Andric                                             unsigned &MinorVersion,
23290b57cec5SDimitry Andric                                             bool &Hashed,
23300b57cec5SDimitry Andric                                             std::string &UserInfo) {
23310b57cec5SDimitry Andric   SmallVector<StringRef, 5> Args;
23320b57cec5SDimitry Andric   Arg.split(Args, ':', 5);
23330b57cec5SDimitry Andric   if (Args.size() < 5)
23340b57cec5SDimitry Andric     return true;
23350b57cec5SDimitry Andric 
23365ffd83dbSDimitry Andric   BlockName = std::string(Args[0]);
23370b57cec5SDimitry Andric   if (Args[1].getAsInteger(10, MajorVersion)) return true;
23380b57cec5SDimitry Andric   if (Args[2].getAsInteger(10, MinorVersion)) return true;
23390b57cec5SDimitry Andric   if (Args[3].getAsInteger(2, Hashed)) return true;
23400b57cec5SDimitry Andric   if (Args.size() > 4)
23415ffd83dbSDimitry Andric     UserInfo = std::string(Args[4]);
23420b57cec5SDimitry Andric   return false;
23430b57cec5SDimitry Andric }
23440b57cec5SDimitry Andric 
23455f7ddb14SDimitry Andric /// Return a table that associates command line option specifiers with the
23465f7ddb14SDimitry Andric /// frontend action. Note: The pair {frontend::PluginAction, OPT_plugin} is
23475f7ddb14SDimitry Andric /// intentionally missing, as this case is handled separately from other
23485f7ddb14SDimitry Andric /// frontend options.
getFrontendActionTable()23495f7ddb14SDimitry Andric static const auto &getFrontendActionTable() {
23505f7ddb14SDimitry Andric   static const std::pair<frontend::ActionKind, unsigned> Table[] = {
23515f7ddb14SDimitry Andric       {frontend::ASTDeclList, OPT_ast_list},
23525f7ddb14SDimitry Andric 
23535f7ddb14SDimitry Andric       {frontend::ASTDump, OPT_ast_dump_all_EQ},
23545f7ddb14SDimitry Andric       {frontend::ASTDump, OPT_ast_dump_all},
23555f7ddb14SDimitry Andric       {frontend::ASTDump, OPT_ast_dump_EQ},
23565f7ddb14SDimitry Andric       {frontend::ASTDump, OPT_ast_dump},
23575f7ddb14SDimitry Andric       {frontend::ASTDump, OPT_ast_dump_lookups},
23585f7ddb14SDimitry Andric       {frontend::ASTDump, OPT_ast_dump_decl_types},
23595f7ddb14SDimitry Andric 
23605f7ddb14SDimitry Andric       {frontend::ASTPrint, OPT_ast_print},
23615f7ddb14SDimitry Andric       {frontend::ASTView, OPT_ast_view},
23625f7ddb14SDimitry Andric       {frontend::DumpCompilerOptions, OPT_compiler_options_dump},
23635f7ddb14SDimitry Andric       {frontend::DumpRawTokens, OPT_dump_raw_tokens},
23645f7ddb14SDimitry Andric       {frontend::DumpTokens, OPT_dump_tokens},
23655f7ddb14SDimitry Andric       {frontend::EmitAssembly, OPT_S},
23665f7ddb14SDimitry Andric       {frontend::EmitBC, OPT_emit_llvm_bc},
23675f7ddb14SDimitry Andric       {frontend::EmitHTML, OPT_emit_html},
23685f7ddb14SDimitry Andric       {frontend::EmitLLVM, OPT_emit_llvm},
23695f7ddb14SDimitry Andric       {frontend::EmitLLVMOnly, OPT_emit_llvm_only},
23705f7ddb14SDimitry Andric       {frontend::EmitCodeGenOnly, OPT_emit_codegen_only},
23715f7ddb14SDimitry Andric       {frontend::EmitCodeGenOnly, OPT_emit_codegen_only},
23725f7ddb14SDimitry Andric       {frontend::EmitObj, OPT_emit_obj},
23735f7ddb14SDimitry Andric 
23745f7ddb14SDimitry Andric       {frontend::FixIt, OPT_fixit_EQ},
23755f7ddb14SDimitry Andric       {frontend::FixIt, OPT_fixit},
23765f7ddb14SDimitry Andric 
23775f7ddb14SDimitry Andric       {frontend::GenerateModule, OPT_emit_module},
23785f7ddb14SDimitry Andric       {frontend::GenerateModuleInterface, OPT_emit_module_interface},
23795f7ddb14SDimitry Andric       {frontend::GenerateHeaderModule, OPT_emit_header_module},
23805f7ddb14SDimitry Andric       {frontend::GeneratePCH, OPT_emit_pch},
23815f7ddb14SDimitry Andric       {frontend::GenerateInterfaceStubs, OPT_emit_interface_stubs},
23825f7ddb14SDimitry Andric       {frontend::InitOnly, OPT_init_only},
23835f7ddb14SDimitry Andric       {frontend::ParseSyntaxOnly, OPT_fsyntax_only},
23845f7ddb14SDimitry Andric       {frontend::ModuleFileInfo, OPT_module_file_info},
23855f7ddb14SDimitry Andric       {frontend::VerifyPCH, OPT_verify_pch},
23865f7ddb14SDimitry Andric       {frontend::PrintPreamble, OPT_print_preamble},
23875f7ddb14SDimitry Andric       {frontend::PrintPreprocessedInput, OPT_E},
23885f7ddb14SDimitry Andric       {frontend::TemplightDump, OPT_templight_dump},
23895f7ddb14SDimitry Andric       {frontend::RewriteMacros, OPT_rewrite_macros},
23905f7ddb14SDimitry Andric       {frontend::RewriteObjC, OPT_rewrite_objc},
23915f7ddb14SDimitry Andric       {frontend::RewriteTest, OPT_rewrite_test},
23925f7ddb14SDimitry Andric       {frontend::RunAnalysis, OPT_analyze},
23935f7ddb14SDimitry Andric       {frontend::MigrateSource, OPT_migrate},
23945f7ddb14SDimitry Andric       {frontend::RunPreprocessorOnly, OPT_Eonly},
23955f7ddb14SDimitry Andric       {frontend::PrintDependencyDirectivesSourceMinimizerOutput,
23965f7ddb14SDimitry Andric           OPT_print_dependency_directives_minimized_source},
23975f7ddb14SDimitry Andric   };
23985f7ddb14SDimitry Andric 
23995f7ddb14SDimitry Andric   return Table;
24005f7ddb14SDimitry Andric }
24015f7ddb14SDimitry Andric 
24025f7ddb14SDimitry Andric /// Maps command line option to frontend action.
getFrontendAction(OptSpecifier & Opt)24035f7ddb14SDimitry Andric static Optional<frontend::ActionKind> getFrontendAction(OptSpecifier &Opt) {
24045f7ddb14SDimitry Andric   for (const auto &ActionOpt : getFrontendActionTable())
24055f7ddb14SDimitry Andric     if (ActionOpt.second == Opt.getID())
24065f7ddb14SDimitry Andric       return ActionOpt.first;
24075f7ddb14SDimitry Andric 
24085f7ddb14SDimitry Andric   return None;
24095f7ddb14SDimitry Andric }
24105f7ddb14SDimitry Andric 
24115f7ddb14SDimitry Andric /// Maps frontend action to command line option.
24125f7ddb14SDimitry Andric static Optional<OptSpecifier>
getProgramActionOpt(frontend::ActionKind ProgramAction)24135f7ddb14SDimitry Andric getProgramActionOpt(frontend::ActionKind ProgramAction) {
24145f7ddb14SDimitry Andric   for (const auto &ActionOpt : getFrontendActionTable())
24155f7ddb14SDimitry Andric     if (ActionOpt.first == ProgramAction)
24165f7ddb14SDimitry Andric       return OptSpecifier(ActionOpt.second);
24175f7ddb14SDimitry Andric 
24185f7ddb14SDimitry Andric   return None;
24195f7ddb14SDimitry Andric }
24205f7ddb14SDimitry Andric 
GenerateFrontendArgs(const FrontendOptions & Opts,SmallVectorImpl<const char * > & Args,CompilerInvocation::StringAllocator SA,bool IsHeader)24215f7ddb14SDimitry Andric static void GenerateFrontendArgs(const FrontendOptions &Opts,
24225f7ddb14SDimitry Andric                                  SmallVectorImpl<const char *> &Args,
24235f7ddb14SDimitry Andric                                  CompilerInvocation::StringAllocator SA,
24245f7ddb14SDimitry Andric                                  bool IsHeader) {
24255f7ddb14SDimitry Andric   const FrontendOptions &FrontendOpts = Opts;
24265f7ddb14SDimitry Andric #define FRONTEND_OPTION_WITH_MARSHALLING(                                      \
24275f7ddb14SDimitry Andric     PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,        \
24285f7ddb14SDimitry Andric     HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
24295f7ddb14SDimitry Andric     DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER,     \
24305f7ddb14SDimitry Andric     MERGER, EXTRACTOR, TABLE_INDEX)                                            \
24315f7ddb14SDimitry Andric   GENERATE_OPTION_WITH_MARSHALLING(                                            \
24325f7ddb14SDimitry Andric       Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE,    \
24335f7ddb14SDimitry Andric       IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
24345f7ddb14SDimitry Andric #include "clang/Driver/Options.inc"
24355f7ddb14SDimitry Andric #undef FRONTEND_OPTION_WITH_MARSHALLING
24365f7ddb14SDimitry Andric 
24375f7ddb14SDimitry Andric   Optional<OptSpecifier> ProgramActionOpt =
24385f7ddb14SDimitry Andric       getProgramActionOpt(Opts.ProgramAction);
24395f7ddb14SDimitry Andric 
24405f7ddb14SDimitry Andric   // Generating a simple flag covers most frontend actions.
24415f7ddb14SDimitry Andric   std::function<void()> GenerateProgramAction = [&]() {
24425f7ddb14SDimitry Andric     GenerateArg(Args, *ProgramActionOpt, SA);
24435f7ddb14SDimitry Andric   };
24445f7ddb14SDimitry Andric 
24455f7ddb14SDimitry Andric   if (!ProgramActionOpt) {
24465f7ddb14SDimitry Andric     // PluginAction is the only program action handled separately.
24475f7ddb14SDimitry Andric     assert(Opts.ProgramAction == frontend::PluginAction &&
24485f7ddb14SDimitry Andric            "Frontend action without option.");
24495f7ddb14SDimitry Andric     GenerateProgramAction = [&]() {
24505f7ddb14SDimitry Andric       GenerateArg(Args, OPT_plugin, Opts.ActionName, SA);
24515f7ddb14SDimitry Andric     };
24525f7ddb14SDimitry Andric   }
24535f7ddb14SDimitry Andric 
24545f7ddb14SDimitry Andric   // FIXME: Simplify the complex 'AST dump' command line.
24555f7ddb14SDimitry Andric   if (Opts.ProgramAction == frontend::ASTDump) {
24565f7ddb14SDimitry Andric     GenerateProgramAction = [&]() {
24575f7ddb14SDimitry Andric       // ASTDumpLookups, ASTDumpDeclTypes and ASTDumpFilter are generated via
24585f7ddb14SDimitry Andric       // marshalling infrastructure.
24595f7ddb14SDimitry Andric 
24605f7ddb14SDimitry Andric       if (Opts.ASTDumpFormat != ADOF_Default) {
24615f7ddb14SDimitry Andric         StringRef Format;
24625f7ddb14SDimitry Andric         switch (Opts.ASTDumpFormat) {
24635f7ddb14SDimitry Andric         case ADOF_Default:
24645f7ddb14SDimitry Andric           llvm_unreachable("Default AST dump format.");
24655f7ddb14SDimitry Andric         case ADOF_JSON:
24665f7ddb14SDimitry Andric           Format = "json";
24675f7ddb14SDimitry Andric           break;
24685f7ddb14SDimitry Andric         }
24695f7ddb14SDimitry Andric 
24705f7ddb14SDimitry Andric         if (Opts.ASTDumpAll)
24715f7ddb14SDimitry Andric           GenerateArg(Args, OPT_ast_dump_all_EQ, Format, SA);
24725f7ddb14SDimitry Andric         if (Opts.ASTDumpDecls)
24735f7ddb14SDimitry Andric           GenerateArg(Args, OPT_ast_dump_EQ, Format, SA);
24745f7ddb14SDimitry Andric       } else {
24755f7ddb14SDimitry Andric         if (Opts.ASTDumpAll)
24765f7ddb14SDimitry Andric           GenerateArg(Args, OPT_ast_dump_all, SA);
24775f7ddb14SDimitry Andric         if (Opts.ASTDumpDecls)
24785f7ddb14SDimitry Andric           GenerateArg(Args, OPT_ast_dump, SA);
24795f7ddb14SDimitry Andric       }
24805f7ddb14SDimitry Andric     };
24815f7ddb14SDimitry Andric   }
24825f7ddb14SDimitry Andric 
24835f7ddb14SDimitry Andric   if (Opts.ProgramAction == frontend::FixIt && !Opts.FixItSuffix.empty()) {
24845f7ddb14SDimitry Andric     GenerateProgramAction = [&]() {
24855f7ddb14SDimitry Andric       GenerateArg(Args, OPT_fixit_EQ, Opts.FixItSuffix, SA);
24865f7ddb14SDimitry Andric     };
24875f7ddb14SDimitry Andric   }
24885f7ddb14SDimitry Andric 
24895f7ddb14SDimitry Andric   GenerateProgramAction();
24905f7ddb14SDimitry Andric 
24915f7ddb14SDimitry Andric   for (const auto &PluginArgs : Opts.PluginArgs) {
24925f7ddb14SDimitry Andric     Option Opt = getDriverOptTable().getOption(OPT_plugin_arg);
24935f7ddb14SDimitry Andric     const char *Spelling =
24945f7ddb14SDimitry Andric         SA(Opt.getPrefix() + Opt.getName() + PluginArgs.first);
24955f7ddb14SDimitry Andric     for (const auto &PluginArg : PluginArgs.second)
24965f7ddb14SDimitry Andric       denormalizeString(Args, Spelling, SA, Opt.getKind(), 0, PluginArg);
24975f7ddb14SDimitry Andric   }
24985f7ddb14SDimitry Andric 
24995f7ddb14SDimitry Andric   for (const auto &Ext : Opts.ModuleFileExtensions)
25005f7ddb14SDimitry Andric     if (auto *TestExt = dyn_cast_or_null<TestModuleFileExtension>(Ext.get()))
25015f7ddb14SDimitry Andric       GenerateArg(Args, OPT_ftest_module_file_extension_EQ, TestExt->str(), SA);
25025f7ddb14SDimitry Andric 
25035f7ddb14SDimitry Andric   if (!Opts.CodeCompletionAt.FileName.empty())
25045f7ddb14SDimitry Andric     GenerateArg(Args, OPT_code_completion_at, Opts.CodeCompletionAt.ToString(),
25055f7ddb14SDimitry Andric                 SA);
25065f7ddb14SDimitry Andric 
25075f7ddb14SDimitry Andric   for (const auto &Plugin : Opts.Plugins)
25085f7ddb14SDimitry Andric     GenerateArg(Args, OPT_load, Plugin, SA);
25095f7ddb14SDimitry Andric 
25105f7ddb14SDimitry Andric   // ASTDumpDecls and ASTDumpAll already handled with ProgramAction.
25115f7ddb14SDimitry Andric 
25125f7ddb14SDimitry Andric   for (const auto &ModuleFile : Opts.ModuleFiles)
25135f7ddb14SDimitry Andric     GenerateArg(Args, OPT_fmodule_file, ModuleFile, SA);
25145f7ddb14SDimitry Andric 
25155f7ddb14SDimitry Andric   if (Opts.AuxTargetCPU.hasValue())
25165f7ddb14SDimitry Andric     GenerateArg(Args, OPT_aux_target_cpu, *Opts.AuxTargetCPU, SA);
25175f7ddb14SDimitry Andric 
25185f7ddb14SDimitry Andric   if (Opts.AuxTargetFeatures.hasValue())
25195f7ddb14SDimitry Andric     for (const auto &Feature : *Opts.AuxTargetFeatures)
25205f7ddb14SDimitry Andric       GenerateArg(Args, OPT_aux_target_feature, Feature, SA);
25215f7ddb14SDimitry Andric 
25225f7ddb14SDimitry Andric   {
25235f7ddb14SDimitry Andric     StringRef Preprocessed = Opts.DashX.isPreprocessed() ? "-cpp-output" : "";
25245f7ddb14SDimitry Andric     StringRef ModuleMap =
25255f7ddb14SDimitry Andric         Opts.DashX.getFormat() == InputKind::ModuleMap ? "-module-map" : "";
25265f7ddb14SDimitry Andric     StringRef Header = IsHeader ? "-header" : "";
25275f7ddb14SDimitry Andric 
25285f7ddb14SDimitry Andric     StringRef Lang;
25295f7ddb14SDimitry Andric     switch (Opts.DashX.getLanguage()) {
25305f7ddb14SDimitry Andric     case Language::C:
25315f7ddb14SDimitry Andric       Lang = "c";
25325f7ddb14SDimitry Andric       break;
25335f7ddb14SDimitry Andric     case Language::OpenCL:
25345f7ddb14SDimitry Andric       Lang = "cl";
25355f7ddb14SDimitry Andric       break;
25365f7ddb14SDimitry Andric     case Language::OpenCLCXX:
25375f7ddb14SDimitry Andric       Lang = "clcpp";
25385f7ddb14SDimitry Andric       break;
25395f7ddb14SDimitry Andric     case Language::CUDA:
25405f7ddb14SDimitry Andric       Lang = "cuda";
25415f7ddb14SDimitry Andric       break;
25425f7ddb14SDimitry Andric     case Language::HIP:
25435f7ddb14SDimitry Andric       Lang = "hip";
25445f7ddb14SDimitry Andric       break;
25455f7ddb14SDimitry Andric     case Language::CXX:
25465f7ddb14SDimitry Andric       Lang = "c++";
25475f7ddb14SDimitry Andric       break;
25485f7ddb14SDimitry Andric     case Language::ObjC:
25495f7ddb14SDimitry Andric       Lang = "objective-c";
25505f7ddb14SDimitry Andric       break;
25515f7ddb14SDimitry Andric     case Language::ObjCXX:
25525f7ddb14SDimitry Andric       Lang = "objective-c++";
25535f7ddb14SDimitry Andric       break;
25545f7ddb14SDimitry Andric     case Language::RenderScript:
25555f7ddb14SDimitry Andric       Lang = "renderscript";
25565f7ddb14SDimitry Andric       break;
25575f7ddb14SDimitry Andric     case Language::Asm:
25585f7ddb14SDimitry Andric       Lang = "assembler-with-cpp";
25595f7ddb14SDimitry Andric       break;
25605f7ddb14SDimitry Andric     case Language::Unknown:
25615f7ddb14SDimitry Andric       assert(Opts.DashX.getFormat() == InputKind::Precompiled &&
25625f7ddb14SDimitry Andric              "Generating -x argument for unknown language (not precompiled).");
25635f7ddb14SDimitry Andric       Lang = "ast";
25645f7ddb14SDimitry Andric       break;
25655f7ddb14SDimitry Andric     case Language::LLVM_IR:
25665f7ddb14SDimitry Andric       Lang = "ir";
25675f7ddb14SDimitry Andric       break;
25685f7ddb14SDimitry Andric     }
25695f7ddb14SDimitry Andric 
25705f7ddb14SDimitry Andric     GenerateArg(Args, OPT_x, Lang + Header + ModuleMap + Preprocessed, SA);
25715f7ddb14SDimitry Andric   }
25725f7ddb14SDimitry Andric 
25735f7ddb14SDimitry Andric   // OPT_INPUT has a unique class, generate it directly.
25745f7ddb14SDimitry Andric   for (const auto &Input : Opts.Inputs)
25755f7ddb14SDimitry Andric     Args.push_back(SA(Input.getFile()));
25765f7ddb14SDimitry Andric }
25775f7ddb14SDimitry Andric 
ParseFrontendArgs(FrontendOptions & Opts,ArgList & Args,DiagnosticsEngine & Diags,bool & IsHeaderFile)25785f7ddb14SDimitry Andric static bool ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args,
25795f7ddb14SDimitry Andric                               DiagnosticsEngine &Diags, bool &IsHeaderFile) {
25805f7ddb14SDimitry Andric   unsigned NumErrorsBefore = Diags.getNumErrors();
25815f7ddb14SDimitry Andric 
25825f7ddb14SDimitry Andric   FrontendOptions &FrontendOpts = Opts;
25835f7ddb14SDimitry Andric 
25845f7ddb14SDimitry Andric #define FRONTEND_OPTION_WITH_MARSHALLING(                                      \
25855f7ddb14SDimitry Andric     PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,        \
25865f7ddb14SDimitry Andric     HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
25875f7ddb14SDimitry Andric     DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER,     \
25885f7ddb14SDimitry Andric     MERGER, EXTRACTOR, TABLE_INDEX)                                            \
25895f7ddb14SDimitry Andric   PARSE_OPTION_WITH_MARSHALLING(                                               \
25905f7ddb14SDimitry Andric       Args, Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE,     \
25915f7ddb14SDimitry Andric       IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
25925f7ddb14SDimitry Andric #include "clang/Driver/Options.inc"
25935f7ddb14SDimitry Andric #undef FRONTEND_OPTION_WITH_MARSHALLING
25945f7ddb14SDimitry Andric 
25950b57cec5SDimitry Andric   Opts.ProgramAction = frontend::ParseSyntaxOnly;
25960b57cec5SDimitry Andric   if (const Arg *A = Args.getLastArg(OPT_Action_Group)) {
25975f7ddb14SDimitry Andric     OptSpecifier Opt = OptSpecifier(A->getOption().getID());
25985f7ddb14SDimitry Andric     Optional<frontend::ActionKind> ProgramAction = getFrontendAction(Opt);
25995f7ddb14SDimitry Andric     assert(ProgramAction && "Option specifier not in Action_Group.");
26005f7ddb14SDimitry Andric 
26015f7ddb14SDimitry Andric     if (ProgramAction == frontend::ASTDump &&
26025f7ddb14SDimitry Andric         (Opt == OPT_ast_dump_all_EQ || Opt == OPT_ast_dump_EQ)) {
26030b57cec5SDimitry Andric       unsigned Val = llvm::StringSwitch<unsigned>(A->getValue())
26040b57cec5SDimitry Andric                          .CaseLower("default", ADOF_Default)
26050b57cec5SDimitry Andric                          .CaseLower("json", ADOF_JSON)
26060b57cec5SDimitry Andric                          .Default(std::numeric_limits<unsigned>::max());
26070b57cec5SDimitry Andric 
26080b57cec5SDimitry Andric       if (Val != std::numeric_limits<unsigned>::max())
26090b57cec5SDimitry Andric         Opts.ASTDumpFormat = static_cast<ASTDumpOutputFormat>(Val);
26100b57cec5SDimitry Andric       else {
26110b57cec5SDimitry Andric         Diags.Report(diag::err_drv_invalid_value)
26120b57cec5SDimitry Andric             << A->getAsString(Args) << A->getValue();
26130b57cec5SDimitry Andric         Opts.ASTDumpFormat = ADOF_Default;
26140b57cec5SDimitry Andric       }
26150b57cec5SDimitry Andric     }
26165f7ddb14SDimitry Andric 
26175f7ddb14SDimitry Andric     if (ProgramAction == frontend::FixIt && Opt == OPT_fixit_EQ)
26180b57cec5SDimitry Andric       Opts.FixItSuffix = A->getValue();
26195f7ddb14SDimitry Andric 
26205f7ddb14SDimitry Andric     if (ProgramAction == frontend::GenerateInterfaceStubs) {
2621a7dea167SDimitry Andric       StringRef ArgStr =
2622a7dea167SDimitry Andric           Args.hasArg(OPT_interface_stub_version_EQ)
2623a7dea167SDimitry Andric               ? Args.getLastArgValue(OPT_interface_stub_version_EQ)
26245f7ddb14SDimitry Andric               : "ifs-v1";
2625a7dea167SDimitry Andric       if (ArgStr == "experimental-yaml-elf-v1" ||
26265f7ddb14SDimitry Andric           ArgStr == "experimental-ifs-v1" || ArgStr == "experimental-ifs-v2" ||
2627a7dea167SDimitry Andric           ArgStr == "experimental-tapi-elf-v1") {
2628a7dea167SDimitry Andric         std::string ErrorMessage =
2629a7dea167SDimitry Andric             "Invalid interface stub format: " + ArgStr.str() +
2630a7dea167SDimitry Andric             " is deprecated.";
26310b57cec5SDimitry Andric         Diags.Report(diag::err_drv_invalid_value)
2632a7dea167SDimitry Andric             << "Must specify a valid interface stub format type, ie: "
26335f7ddb14SDimitry Andric                "-interface-stub-version=ifs-v1"
2634a7dea167SDimitry Andric             << ErrorMessage;
26355f7ddb14SDimitry Andric         ProgramAction = frontend::ParseSyntaxOnly;
26365f7ddb14SDimitry Andric       } else if (!ArgStr.startswith("ifs-")) {
2637a7dea167SDimitry Andric         std::string ErrorMessage =
2638a7dea167SDimitry Andric             "Invalid interface stub format: " + ArgStr.str() + ".";
2639a7dea167SDimitry Andric         Diags.Report(diag::err_drv_invalid_value)
2640a7dea167SDimitry Andric             << "Must specify a valid interface stub format type, ie: "
26415f7ddb14SDimitry Andric                "-interface-stub-version=ifs-v1"
2642a7dea167SDimitry Andric             << ErrorMessage;
26435f7ddb14SDimitry Andric         ProgramAction = frontend::ParseSyntaxOnly;
2644a7dea167SDimitry Andric       }
26450b57cec5SDimitry Andric     }
26465f7ddb14SDimitry Andric 
26475f7ddb14SDimitry Andric     Opts.ProgramAction = *ProgramAction;
26480b57cec5SDimitry Andric   }
26490b57cec5SDimitry Andric 
26500b57cec5SDimitry Andric   if (const Arg* A = Args.getLastArg(OPT_plugin)) {
26510b57cec5SDimitry Andric     Opts.Plugins.emplace_back(A->getValue(0));
26520b57cec5SDimitry Andric     Opts.ProgramAction = frontend::PluginAction;
26530b57cec5SDimitry Andric     Opts.ActionName = A->getValue();
26540b57cec5SDimitry Andric   }
26550b57cec5SDimitry Andric   for (const auto *AA : Args.filtered(OPT_plugin_arg))
26560b57cec5SDimitry Andric     Opts.PluginArgs[AA->getValue(0)].emplace_back(AA->getValue(1));
26570b57cec5SDimitry Andric 
26580b57cec5SDimitry Andric   for (const std::string &Arg :
26590b57cec5SDimitry Andric          Args.getAllArgValues(OPT_ftest_module_file_extension_EQ)) {
26600b57cec5SDimitry Andric     std::string BlockName;
26610b57cec5SDimitry Andric     unsigned MajorVersion;
26620b57cec5SDimitry Andric     unsigned MinorVersion;
26630b57cec5SDimitry Andric     bool Hashed;
26640b57cec5SDimitry Andric     std::string UserInfo;
26650b57cec5SDimitry Andric     if (parseTestModuleFileExtensionArg(Arg, BlockName, MajorVersion,
26660b57cec5SDimitry Andric                                         MinorVersion, Hashed, UserInfo)) {
26670b57cec5SDimitry Andric       Diags.Report(diag::err_test_module_file_extension_format) << Arg;
26680b57cec5SDimitry Andric 
26690b57cec5SDimitry Andric       continue;
26700b57cec5SDimitry Andric     }
26710b57cec5SDimitry Andric 
26720b57cec5SDimitry Andric     // Add the testing module file extension.
26730b57cec5SDimitry Andric     Opts.ModuleFileExtensions.push_back(
26740b57cec5SDimitry Andric         std::make_shared<TestModuleFileExtension>(
26750b57cec5SDimitry Andric             BlockName, MajorVersion, MinorVersion, Hashed, UserInfo));
26760b57cec5SDimitry Andric   }
26770b57cec5SDimitry Andric 
26780b57cec5SDimitry Andric   if (const Arg *A = Args.getLastArg(OPT_code_completion_at)) {
26790b57cec5SDimitry Andric     Opts.CodeCompletionAt =
26800b57cec5SDimitry Andric       ParsedSourceLocation::FromString(A->getValue());
26810b57cec5SDimitry Andric     if (Opts.CodeCompletionAt.FileName.empty())
26820b57cec5SDimitry Andric       Diags.Report(diag::err_drv_invalid_value)
26830b57cec5SDimitry Andric         << A->getAsString(Args) << A->getValue();
26840b57cec5SDimitry Andric   }
26850b57cec5SDimitry Andric 
26860b57cec5SDimitry Andric   Opts.Plugins = Args.getAllArgValues(OPT_load);
26870b57cec5SDimitry Andric   Opts.ASTDumpDecls = Args.hasArg(OPT_ast_dump, OPT_ast_dump_EQ);
26880b57cec5SDimitry Andric   Opts.ASTDumpAll = Args.hasArg(OPT_ast_dump_all, OPT_ast_dump_all_EQ);
26890b57cec5SDimitry Andric   // Only the -fmodule-file=<file> form.
26900b57cec5SDimitry Andric   for (const auto *A : Args.filtered(OPT_fmodule_file)) {
26910b57cec5SDimitry Andric     StringRef Val = A->getValue();
26920b57cec5SDimitry Andric     if (Val.find('=') == StringRef::npos)
26935ffd83dbSDimitry Andric       Opts.ModuleFiles.push_back(std::string(Val));
26940b57cec5SDimitry Andric   }
26955ffd83dbSDimitry Andric 
26965ffd83dbSDimitry Andric   if (Opts.ProgramAction != frontend::GenerateModule && Opts.IsSystemModule)
26975ffd83dbSDimitry Andric     Diags.Report(diag::err_drv_argument_only_allowed_with) << "-fsystem-module"
26985ffd83dbSDimitry Andric                                                            << "-emit-module";
26990b57cec5SDimitry Andric 
27005ffd83dbSDimitry Andric   if (Args.hasArg(OPT_aux_target_cpu))
27015ffd83dbSDimitry Andric     Opts.AuxTargetCPU = std::string(Args.getLastArgValue(OPT_aux_target_cpu));
27025ffd83dbSDimitry Andric   if (Args.hasArg(OPT_aux_target_feature))
27035ffd83dbSDimitry Andric     Opts.AuxTargetFeatures = Args.getAllArgValues(OPT_aux_target_feature);
27040b57cec5SDimitry Andric 
27050b57cec5SDimitry Andric   if (Opts.ARCMTAction != FrontendOptions::ARCMT_None &&
27060b57cec5SDimitry Andric       Opts.ObjCMTAction != FrontendOptions::ObjCMT_None) {
27070b57cec5SDimitry Andric     Diags.Report(diag::err_drv_argument_not_allowed_with)
27080b57cec5SDimitry Andric       << "ARC migration" << "ObjC migration";
27090b57cec5SDimitry Andric   }
27100b57cec5SDimitry Andric 
2711a7dea167SDimitry Andric   InputKind DashX(Language::Unknown);
27120b57cec5SDimitry Andric   if (const Arg *A = Args.getLastArg(OPT_x)) {
27130b57cec5SDimitry Andric     StringRef XValue = A->getValue();
27140b57cec5SDimitry Andric 
27150b57cec5SDimitry Andric     // Parse suffixes: '<lang>(-header|[-module-map][-cpp-output])'.
27160b57cec5SDimitry Andric     // FIXME: Supporting '<lang>-header-cpp-output' would be useful.
27170b57cec5SDimitry Andric     bool Preprocessed = XValue.consume_back("-cpp-output");
27180b57cec5SDimitry Andric     bool ModuleMap = XValue.consume_back("-module-map");
2719590d96feSDimitry Andric     IsHeaderFile = !Preprocessed && !ModuleMap &&
2720590d96feSDimitry Andric                    XValue != "precompiled-header" &&
2721590d96feSDimitry Andric                    XValue.consume_back("-header");
27220b57cec5SDimitry Andric 
27230b57cec5SDimitry Andric     // Principal languages.
27240b57cec5SDimitry Andric     DashX = llvm::StringSwitch<InputKind>(XValue)
2725a7dea167SDimitry Andric                 .Case("c", Language::C)
2726a7dea167SDimitry Andric                 .Case("cl", Language::OpenCL)
27275f7ddb14SDimitry Andric                 .Case("clcpp", Language::OpenCLCXX)
2728a7dea167SDimitry Andric                 .Case("cuda", Language::CUDA)
2729a7dea167SDimitry Andric                 .Case("hip", Language::HIP)
2730a7dea167SDimitry Andric                 .Case("c++", Language::CXX)
2731a7dea167SDimitry Andric                 .Case("objective-c", Language::ObjC)
2732a7dea167SDimitry Andric                 .Case("objective-c++", Language::ObjCXX)
2733a7dea167SDimitry Andric                 .Case("renderscript", Language::RenderScript)
2734a7dea167SDimitry Andric                 .Default(Language::Unknown);
27350b57cec5SDimitry Andric 
27360b57cec5SDimitry Andric     // "objc[++]-cpp-output" is an acceptable synonym for
27370b57cec5SDimitry Andric     // "objective-c[++]-cpp-output".
27380b57cec5SDimitry Andric     if (DashX.isUnknown() && Preprocessed && !IsHeaderFile && !ModuleMap)
27390b57cec5SDimitry Andric       DashX = llvm::StringSwitch<InputKind>(XValue)
2740a7dea167SDimitry Andric                   .Case("objc", Language::ObjC)
2741a7dea167SDimitry Andric                   .Case("objc++", Language::ObjCXX)
2742a7dea167SDimitry Andric                   .Default(Language::Unknown);
27430b57cec5SDimitry Andric 
27440b57cec5SDimitry Andric     // Some special cases cannot be combined with suffixes.
27450b57cec5SDimitry Andric     if (DashX.isUnknown() && !Preprocessed && !ModuleMap && !IsHeaderFile)
27460b57cec5SDimitry Andric       DashX = llvm::StringSwitch<InputKind>(XValue)
2747a7dea167SDimitry Andric                   .Case("cpp-output", InputKind(Language::C).getPreprocessed())
2748a7dea167SDimitry Andric                   .Case("assembler-with-cpp", Language::Asm)
2749590d96feSDimitry Andric                   .Cases("ast", "pcm", "precompiled-header",
2750a7dea167SDimitry Andric                          InputKind(Language::Unknown, InputKind::Precompiled))
2751a7dea167SDimitry Andric                   .Case("ir", Language::LLVM_IR)
2752a7dea167SDimitry Andric                   .Default(Language::Unknown);
27530b57cec5SDimitry Andric 
27540b57cec5SDimitry Andric     if (DashX.isUnknown())
27550b57cec5SDimitry Andric       Diags.Report(diag::err_drv_invalid_value)
27560b57cec5SDimitry Andric         << A->getAsString(Args) << A->getValue();
27570b57cec5SDimitry Andric 
27580b57cec5SDimitry Andric     if (Preprocessed)
27590b57cec5SDimitry Andric       DashX = DashX.getPreprocessed();
27600b57cec5SDimitry Andric     if (ModuleMap)
27610b57cec5SDimitry Andric       DashX = DashX.withFormat(InputKind::ModuleMap);
27620b57cec5SDimitry Andric   }
27630b57cec5SDimitry Andric 
27640b57cec5SDimitry Andric   // '-' is the default input if none is given.
27650b57cec5SDimitry Andric   std::vector<std::string> Inputs = Args.getAllArgValues(OPT_INPUT);
27660b57cec5SDimitry Andric   Opts.Inputs.clear();
27670b57cec5SDimitry Andric   if (Inputs.empty())
27680b57cec5SDimitry Andric     Inputs.push_back("-");
27690b57cec5SDimitry Andric   for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
27700b57cec5SDimitry Andric     InputKind IK = DashX;
27710b57cec5SDimitry Andric     if (IK.isUnknown()) {
27720b57cec5SDimitry Andric       IK = FrontendOptions::getInputKindForExtension(
27730b57cec5SDimitry Andric         StringRef(Inputs[i]).rsplit('.').second);
27740b57cec5SDimitry Andric       // FIXME: Warn on this?
27750b57cec5SDimitry Andric       if (IK.isUnknown())
2776a7dea167SDimitry Andric         IK = Language::C;
27770b57cec5SDimitry Andric       // FIXME: Remove this hack.
27780b57cec5SDimitry Andric       if (i == 0)
27790b57cec5SDimitry Andric         DashX = IK;
27800b57cec5SDimitry Andric     }
27810b57cec5SDimitry Andric 
27825ffd83dbSDimitry Andric     bool IsSystem = false;
27835ffd83dbSDimitry Andric 
27840b57cec5SDimitry Andric     // The -emit-module action implicitly takes a module map.
27850b57cec5SDimitry Andric     if (Opts.ProgramAction == frontend::GenerateModule &&
27865ffd83dbSDimitry Andric         IK.getFormat() == InputKind::Source) {
27870b57cec5SDimitry Andric       IK = IK.withFormat(InputKind::ModuleMap);
27885ffd83dbSDimitry Andric       IsSystem = Opts.IsSystemModule;
27895ffd83dbSDimitry Andric     }
27900b57cec5SDimitry Andric 
27915ffd83dbSDimitry Andric     Opts.Inputs.emplace_back(std::move(Inputs[i]), IK, IsSystem);
27920b57cec5SDimitry Andric   }
27930b57cec5SDimitry Andric 
27945f7ddb14SDimitry Andric   Opts.DashX = DashX;
27955f7ddb14SDimitry Andric 
27965f7ddb14SDimitry Andric   return Diags.getNumErrors() == NumErrorsBefore;
27970b57cec5SDimitry Andric }
27980b57cec5SDimitry Andric 
GetResourcesPath(const char * Argv0,void * MainAddr)27990b57cec5SDimitry Andric std::string CompilerInvocation::GetResourcesPath(const char *Argv0,
28000b57cec5SDimitry Andric                                                  void *MainAddr) {
28010b57cec5SDimitry Andric   std::string ClangExecutable =
28020b57cec5SDimitry Andric       llvm::sys::fs::getMainExecutable(Argv0, MainAddr);
28030b57cec5SDimitry Andric   return Driver::GetResourcesPath(ClangExecutable, CLANG_RESOURCE_DIR);
28040b57cec5SDimitry Andric }
28050b57cec5SDimitry Andric 
GenerateHeaderSearchArgs(HeaderSearchOptions & Opts,SmallVectorImpl<const char * > & Args,CompilerInvocation::StringAllocator SA)28065f7ddb14SDimitry Andric static void GenerateHeaderSearchArgs(HeaderSearchOptions &Opts,
28075f7ddb14SDimitry Andric                                      SmallVectorImpl<const char *> &Args,
28085f7ddb14SDimitry Andric                                      CompilerInvocation::StringAllocator SA) {
28095f7ddb14SDimitry Andric   const HeaderSearchOptions *HeaderSearchOpts = &Opts;
28105f7ddb14SDimitry Andric #define HEADER_SEARCH_OPTION_WITH_MARSHALLING(                                 \
28115f7ddb14SDimitry Andric     PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,        \
28125f7ddb14SDimitry Andric     HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
28135f7ddb14SDimitry Andric     DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER,     \
28145f7ddb14SDimitry Andric     MERGER, EXTRACTOR, TABLE_INDEX)                                            \
28155f7ddb14SDimitry Andric   GENERATE_OPTION_WITH_MARSHALLING(                                            \
28165f7ddb14SDimitry Andric       Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE,    \
28175f7ddb14SDimitry Andric       IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
28185f7ddb14SDimitry Andric #include "clang/Driver/Options.inc"
28195f7ddb14SDimitry Andric #undef HEADER_SEARCH_OPTION_WITH_MARSHALLING
28205f7ddb14SDimitry Andric 
28215f7ddb14SDimitry Andric   if (Opts.UseLibcxx)
28225f7ddb14SDimitry Andric     GenerateArg(Args, OPT_stdlib_EQ, "libc++", SA);
28235f7ddb14SDimitry Andric 
28245f7ddb14SDimitry Andric   if (!Opts.ModuleCachePath.empty())
28255f7ddb14SDimitry Andric     GenerateArg(Args, OPT_fmodules_cache_path, Opts.ModuleCachePath, SA);
28265f7ddb14SDimitry Andric 
28275f7ddb14SDimitry Andric   for (const auto &File : Opts.PrebuiltModuleFiles)
28285f7ddb14SDimitry Andric     GenerateArg(Args, OPT_fmodule_file, File.first + "=" + File.second, SA);
28295f7ddb14SDimitry Andric 
28305f7ddb14SDimitry Andric   for (const auto &Path : Opts.PrebuiltModulePaths)
28315f7ddb14SDimitry Andric     GenerateArg(Args, OPT_fprebuilt_module_path, Path, SA);
28325f7ddb14SDimitry Andric 
28335f7ddb14SDimitry Andric   for (const auto &Macro : Opts.ModulesIgnoreMacros)
28345f7ddb14SDimitry Andric     GenerateArg(Args, OPT_fmodules_ignore_macro, Macro.val(), SA);
28355f7ddb14SDimitry Andric 
28365f7ddb14SDimitry Andric   auto Matches = [](const HeaderSearchOptions::Entry &Entry,
28375f7ddb14SDimitry Andric                     llvm::ArrayRef<frontend::IncludeDirGroup> Groups,
28385f7ddb14SDimitry Andric                     llvm::Optional<bool> IsFramework,
28395f7ddb14SDimitry Andric                     llvm::Optional<bool> IgnoreSysRoot) {
28405f7ddb14SDimitry Andric     return llvm::find(Groups, Entry.Group) != Groups.end() &&
28415f7ddb14SDimitry Andric            (!IsFramework || (Entry.IsFramework == *IsFramework)) &&
28425f7ddb14SDimitry Andric            (!IgnoreSysRoot || (Entry.IgnoreSysRoot == *IgnoreSysRoot));
28435f7ddb14SDimitry Andric   };
28445f7ddb14SDimitry Andric 
28455f7ddb14SDimitry Andric   auto It = Opts.UserEntries.begin();
28465f7ddb14SDimitry Andric   auto End = Opts.UserEntries.end();
28475f7ddb14SDimitry Andric 
28485f7ddb14SDimitry Andric   // Add -I..., -F..., and -index-header-map options in order.
28495f7ddb14SDimitry Andric   for (; It < End &&
28505f7ddb14SDimitry Andric          Matches(*It, {frontend::IndexHeaderMap, frontend::Angled}, None, true);
28515f7ddb14SDimitry Andric        ++It) {
28525f7ddb14SDimitry Andric     OptSpecifier Opt = [It, Matches]() {
28535f7ddb14SDimitry Andric       if (Matches(*It, frontend::IndexHeaderMap, true, true))
28545f7ddb14SDimitry Andric         return OPT_F;
28555f7ddb14SDimitry Andric       if (Matches(*It, frontend::IndexHeaderMap, false, true))
28565f7ddb14SDimitry Andric         return OPT_I;
28575f7ddb14SDimitry Andric       if (Matches(*It, frontend::Angled, true, true))
28585f7ddb14SDimitry Andric         return OPT_F;
28595f7ddb14SDimitry Andric       if (Matches(*It, frontend::Angled, false, true))
28605f7ddb14SDimitry Andric         return OPT_I;
28615f7ddb14SDimitry Andric       llvm_unreachable("Unexpected HeaderSearchOptions::Entry.");
28625f7ddb14SDimitry Andric     }();
28635f7ddb14SDimitry Andric 
28645f7ddb14SDimitry Andric     if (It->Group == frontend::IndexHeaderMap)
28655f7ddb14SDimitry Andric       GenerateArg(Args, OPT_index_header_map, SA);
28665f7ddb14SDimitry Andric     GenerateArg(Args, Opt, It->Path, SA);
28675f7ddb14SDimitry Andric   };
28685f7ddb14SDimitry Andric 
28695f7ddb14SDimitry Andric   // Note: some paths that came from "[-iprefix=xx] -iwithprefixbefore=yy" may
28705f7ddb14SDimitry Andric   // have already been generated as "-I[xx]yy". If that's the case, their
28715f7ddb14SDimitry Andric   // position on command line was such that this has no semantic impact on
28725f7ddb14SDimitry Andric   // include paths.
28735f7ddb14SDimitry Andric   for (; It < End &&
28745f7ddb14SDimitry Andric          Matches(*It, {frontend::After, frontend::Angled}, false, true);
28755f7ddb14SDimitry Andric        ++It) {
28765f7ddb14SDimitry Andric     OptSpecifier Opt =
28775f7ddb14SDimitry Andric         It->Group == frontend::After ? OPT_iwithprefix : OPT_iwithprefixbefore;
28785f7ddb14SDimitry Andric     GenerateArg(Args, Opt, It->Path, SA);
28795f7ddb14SDimitry Andric   }
28805f7ddb14SDimitry Andric 
28815f7ddb14SDimitry Andric   // Note: Some paths that came from "-idirafter=xxyy" may have already been
28825f7ddb14SDimitry Andric   // generated as "-iwithprefix=xxyy". If that's the case, their position on
28835f7ddb14SDimitry Andric   // command line was such that this has no semantic impact on include paths.
28845f7ddb14SDimitry Andric   for (; It < End && Matches(*It, {frontend::After}, false, true); ++It)
28855f7ddb14SDimitry Andric     GenerateArg(Args, OPT_idirafter, It->Path, SA);
28865f7ddb14SDimitry Andric   for (; It < End && Matches(*It, {frontend::Quoted}, false, true); ++It)
28875f7ddb14SDimitry Andric     GenerateArg(Args, OPT_iquote, It->Path, SA);
28885f7ddb14SDimitry Andric   for (; It < End && Matches(*It, {frontend::System}, false, None); ++It)
28895f7ddb14SDimitry Andric     GenerateArg(Args, It->IgnoreSysRoot ? OPT_isystem : OPT_iwithsysroot,
28905f7ddb14SDimitry Andric                 It->Path, SA);
28915f7ddb14SDimitry Andric   for (; It < End && Matches(*It, {frontend::System}, true, true); ++It)
28925f7ddb14SDimitry Andric     GenerateArg(Args, OPT_iframework, It->Path, SA);
28935f7ddb14SDimitry Andric   for (; It < End && Matches(*It, {frontend::System}, true, false); ++It)
28945f7ddb14SDimitry Andric     GenerateArg(Args, OPT_iframeworkwithsysroot, It->Path, SA);
28955f7ddb14SDimitry Andric 
28965f7ddb14SDimitry Andric   // Add the paths for the various language specific isystem flags.
28975f7ddb14SDimitry Andric   for (; It < End && Matches(*It, {frontend::CSystem}, false, true); ++It)
28985f7ddb14SDimitry Andric     GenerateArg(Args, OPT_c_isystem, It->Path, SA);
28995f7ddb14SDimitry Andric   for (; It < End && Matches(*It, {frontend::CXXSystem}, false, true); ++It)
29005f7ddb14SDimitry Andric     GenerateArg(Args, OPT_cxx_isystem, It->Path, SA);
29015f7ddb14SDimitry Andric   for (; It < End && Matches(*It, {frontend::ObjCSystem}, false, true); ++It)
29025f7ddb14SDimitry Andric     GenerateArg(Args, OPT_objc_isystem, It->Path, SA);
29035f7ddb14SDimitry Andric   for (; It < End && Matches(*It, {frontend::ObjCXXSystem}, false, true); ++It)
29045f7ddb14SDimitry Andric     GenerateArg(Args, OPT_objcxx_isystem, It->Path, SA);
29055f7ddb14SDimitry Andric 
29065f7ddb14SDimitry Andric   // Add the internal paths from a driver that detects standard include paths.
29075f7ddb14SDimitry Andric   // Note: Some paths that came from "-internal-isystem" arguments may have
29085f7ddb14SDimitry Andric   // already been generated as "-isystem". If that's the case, their position on
29095f7ddb14SDimitry Andric   // command line was such that this has no semantic impact on include paths.
29105f7ddb14SDimitry Andric   for (; It < End &&
29115f7ddb14SDimitry Andric          Matches(*It, {frontend::System, frontend::ExternCSystem}, false, true);
29125f7ddb14SDimitry Andric        ++It) {
29135f7ddb14SDimitry Andric     OptSpecifier Opt = It->Group == frontend::System
29145f7ddb14SDimitry Andric                            ? OPT_internal_isystem
29155f7ddb14SDimitry Andric                            : OPT_internal_externc_isystem;
29165f7ddb14SDimitry Andric     GenerateArg(Args, Opt, It->Path, SA);
29175f7ddb14SDimitry Andric   }
29185f7ddb14SDimitry Andric 
29195f7ddb14SDimitry Andric   assert(It == End && "Unhandled HeaderSearchOption::Entry.");
29205f7ddb14SDimitry Andric 
29215f7ddb14SDimitry Andric   // Add the path prefixes which are implicitly treated as being system headers.
29225f7ddb14SDimitry Andric   for (const auto &P : Opts.SystemHeaderPrefixes) {
29235f7ddb14SDimitry Andric     OptSpecifier Opt = P.IsSystemHeader ? OPT_system_header_prefix
29245f7ddb14SDimitry Andric                                         : OPT_no_system_header_prefix;
29255f7ddb14SDimitry Andric     GenerateArg(Args, Opt, P.Prefix, SA);
29265f7ddb14SDimitry Andric   }
29275f7ddb14SDimitry Andric 
29285f7ddb14SDimitry Andric   for (const std::string &F : Opts.VFSOverlayFiles)
29295f7ddb14SDimitry Andric     GenerateArg(Args, OPT_ivfsoverlay, F, SA);
29305f7ddb14SDimitry Andric }
29315f7ddb14SDimitry Andric 
ParseHeaderSearchArgs(HeaderSearchOptions & Opts,ArgList & Args,DiagnosticsEngine & Diags,const std::string & WorkingDir)29325f7ddb14SDimitry Andric static bool ParseHeaderSearchArgs(HeaderSearchOptions &Opts, ArgList &Args,
29335f7ddb14SDimitry Andric                                   DiagnosticsEngine &Diags,
29340b57cec5SDimitry Andric                                   const std::string &WorkingDir) {
29355f7ddb14SDimitry Andric   unsigned NumErrorsBefore = Diags.getNumErrors();
29365f7ddb14SDimitry Andric 
29375f7ddb14SDimitry Andric   HeaderSearchOptions *HeaderSearchOpts = &Opts;
29385f7ddb14SDimitry Andric 
29395f7ddb14SDimitry Andric #define HEADER_SEARCH_OPTION_WITH_MARSHALLING(                                 \
29405f7ddb14SDimitry Andric     PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,        \
29415f7ddb14SDimitry Andric     HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
29425f7ddb14SDimitry Andric     DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER,     \
29435f7ddb14SDimitry Andric     MERGER, EXTRACTOR, TABLE_INDEX)                                            \
29445f7ddb14SDimitry Andric   PARSE_OPTION_WITH_MARSHALLING(                                               \
29455f7ddb14SDimitry Andric       Args, Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE,     \
29465f7ddb14SDimitry Andric       IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
29475f7ddb14SDimitry Andric #include "clang/Driver/Options.inc"
29485f7ddb14SDimitry Andric #undef HEADER_SEARCH_OPTION_WITH_MARSHALLING
29495f7ddb14SDimitry Andric 
29500b57cec5SDimitry Andric   if (const Arg *A = Args.getLastArg(OPT_stdlib_EQ))
29510b57cec5SDimitry Andric     Opts.UseLibcxx = (strcmp(A->getValue(), "libc++") == 0);
29520b57cec5SDimitry Andric 
29530b57cec5SDimitry Andric   // Canonicalize -fmodules-cache-path before storing it.
29540b57cec5SDimitry Andric   SmallString<128> P(Args.getLastArgValue(OPT_fmodules_cache_path));
29550b57cec5SDimitry Andric   if (!(P.empty() || llvm::sys::path::is_absolute(P))) {
29560b57cec5SDimitry Andric     if (WorkingDir.empty())
29570b57cec5SDimitry Andric       llvm::sys::fs::make_absolute(P);
29580b57cec5SDimitry Andric     else
29590b57cec5SDimitry Andric       llvm::sys::fs::make_absolute(WorkingDir, P);
29600b57cec5SDimitry Andric   }
29610b57cec5SDimitry Andric   llvm::sys::path::remove_dots(P);
29625ffd83dbSDimitry Andric   Opts.ModuleCachePath = std::string(P.str());
29630b57cec5SDimitry Andric 
29640b57cec5SDimitry Andric   // Only the -fmodule-file=<name>=<file> form.
29650b57cec5SDimitry Andric   for (const auto *A : Args.filtered(OPT_fmodule_file)) {
29660b57cec5SDimitry Andric     StringRef Val = A->getValue();
29675ffd83dbSDimitry Andric     if (Val.find('=') != StringRef::npos){
29685ffd83dbSDimitry Andric       auto Split = Val.split('=');
29695ffd83dbSDimitry Andric       Opts.PrebuiltModuleFiles.insert(
29705ffd83dbSDimitry Andric           {std::string(Split.first), std::string(Split.second)});
29715ffd83dbSDimitry Andric     }
29720b57cec5SDimitry Andric   }
29730b57cec5SDimitry Andric   for (const auto *A : Args.filtered(OPT_fprebuilt_module_path))
29740b57cec5SDimitry Andric     Opts.AddPrebuiltModulePath(A->getValue());
29750b57cec5SDimitry Andric 
29760b57cec5SDimitry Andric   for (const auto *A : Args.filtered(OPT_fmodules_ignore_macro)) {
29770b57cec5SDimitry Andric     StringRef MacroDef = A->getValue();
29780b57cec5SDimitry Andric     Opts.ModulesIgnoreMacros.insert(
29790b57cec5SDimitry Andric         llvm::CachedHashString(MacroDef.split('=').first));
29800b57cec5SDimitry Andric   }
29810b57cec5SDimitry Andric 
29820b57cec5SDimitry Andric   // Add -I..., -F..., and -index-header-map options in order.
29830b57cec5SDimitry Andric   bool IsIndexHeaderMap = false;
29840b57cec5SDimitry Andric   bool IsSysrootSpecified =
29850b57cec5SDimitry Andric       Args.hasArg(OPT__sysroot_EQ) || Args.hasArg(OPT_isysroot);
29860b57cec5SDimitry Andric   for (const auto *A : Args.filtered(OPT_I, OPT_F, OPT_index_header_map)) {
29870b57cec5SDimitry Andric     if (A->getOption().matches(OPT_index_header_map)) {
29880b57cec5SDimitry Andric       // -index-header-map applies to the next -I or -F.
29890b57cec5SDimitry Andric       IsIndexHeaderMap = true;
29900b57cec5SDimitry Andric       continue;
29910b57cec5SDimitry Andric     }
29920b57cec5SDimitry Andric 
29930b57cec5SDimitry Andric     frontend::IncludeDirGroup Group =
29940b57cec5SDimitry Andric         IsIndexHeaderMap ? frontend::IndexHeaderMap : frontend::Angled;
29950b57cec5SDimitry Andric 
29960b57cec5SDimitry Andric     bool IsFramework = A->getOption().matches(OPT_F);
29970b57cec5SDimitry Andric     std::string Path = A->getValue();
29980b57cec5SDimitry Andric 
29990b57cec5SDimitry Andric     if (IsSysrootSpecified && !IsFramework && A->getValue()[0] == '=') {
30000b57cec5SDimitry Andric       SmallString<32> Buffer;
30010b57cec5SDimitry Andric       llvm::sys::path::append(Buffer, Opts.Sysroot,
30020b57cec5SDimitry Andric                               llvm::StringRef(A->getValue()).substr(1));
30035ffd83dbSDimitry Andric       Path = std::string(Buffer.str());
30040b57cec5SDimitry Andric     }
30050b57cec5SDimitry Andric 
30060b57cec5SDimitry Andric     Opts.AddPath(Path, Group, IsFramework,
30070b57cec5SDimitry Andric                  /*IgnoreSysroot*/ true);
30080b57cec5SDimitry Andric     IsIndexHeaderMap = false;
30090b57cec5SDimitry Andric   }
30100b57cec5SDimitry Andric 
30110b57cec5SDimitry Andric   // Add -iprefix/-iwithprefix/-iwithprefixbefore options.
30120b57cec5SDimitry Andric   StringRef Prefix = ""; // FIXME: This isn't the correct default prefix.
30130b57cec5SDimitry Andric   for (const auto *A :
30140b57cec5SDimitry Andric        Args.filtered(OPT_iprefix, OPT_iwithprefix, OPT_iwithprefixbefore)) {
30150b57cec5SDimitry Andric     if (A->getOption().matches(OPT_iprefix))
30160b57cec5SDimitry Andric       Prefix = A->getValue();
30170b57cec5SDimitry Andric     else if (A->getOption().matches(OPT_iwithprefix))
30180b57cec5SDimitry Andric       Opts.AddPath(Prefix.str() + A->getValue(), frontend::After, false, true);
30190b57cec5SDimitry Andric     else
30200b57cec5SDimitry Andric       Opts.AddPath(Prefix.str() + A->getValue(), frontend::Angled, false, true);
30210b57cec5SDimitry Andric   }
30220b57cec5SDimitry Andric 
30230b57cec5SDimitry Andric   for (const auto *A : Args.filtered(OPT_idirafter))
30240b57cec5SDimitry Andric     Opts.AddPath(A->getValue(), frontend::After, false, true);
30250b57cec5SDimitry Andric   for (const auto *A : Args.filtered(OPT_iquote))
30260b57cec5SDimitry Andric     Opts.AddPath(A->getValue(), frontend::Quoted, false, true);
30270b57cec5SDimitry Andric   for (const auto *A : Args.filtered(OPT_isystem, OPT_iwithsysroot))
30280b57cec5SDimitry Andric     Opts.AddPath(A->getValue(), frontend::System, false,
30290b57cec5SDimitry Andric                  !A->getOption().matches(OPT_iwithsysroot));
30300b57cec5SDimitry Andric   for (const auto *A : Args.filtered(OPT_iframework))
30310b57cec5SDimitry Andric     Opts.AddPath(A->getValue(), frontend::System, true, true);
30320b57cec5SDimitry Andric   for (const auto *A : Args.filtered(OPT_iframeworkwithsysroot))
30330b57cec5SDimitry Andric     Opts.AddPath(A->getValue(), frontend::System, /*IsFramework=*/true,
30340b57cec5SDimitry Andric                  /*IgnoreSysRoot=*/false);
30350b57cec5SDimitry Andric 
30360b57cec5SDimitry Andric   // Add the paths for the various language specific isystem flags.
30370b57cec5SDimitry Andric   for (const auto *A : Args.filtered(OPT_c_isystem))
30380b57cec5SDimitry Andric     Opts.AddPath(A->getValue(), frontend::CSystem, false, true);
30390b57cec5SDimitry Andric   for (const auto *A : Args.filtered(OPT_cxx_isystem))
30400b57cec5SDimitry Andric     Opts.AddPath(A->getValue(), frontend::CXXSystem, false, true);
30410b57cec5SDimitry Andric   for (const auto *A : Args.filtered(OPT_objc_isystem))
30420b57cec5SDimitry Andric     Opts.AddPath(A->getValue(), frontend::ObjCSystem, false,true);
30430b57cec5SDimitry Andric   for (const auto *A : Args.filtered(OPT_objcxx_isystem))
30440b57cec5SDimitry Andric     Opts.AddPath(A->getValue(), frontend::ObjCXXSystem, false, true);
30450b57cec5SDimitry Andric 
30460b57cec5SDimitry Andric   // Add the internal paths from a driver that detects standard include paths.
30470b57cec5SDimitry Andric   for (const auto *A :
30480b57cec5SDimitry Andric        Args.filtered(OPT_internal_isystem, OPT_internal_externc_isystem)) {
30490b57cec5SDimitry Andric     frontend::IncludeDirGroup Group = frontend::System;
30500b57cec5SDimitry Andric     if (A->getOption().matches(OPT_internal_externc_isystem))
30510b57cec5SDimitry Andric       Group = frontend::ExternCSystem;
30520b57cec5SDimitry Andric     Opts.AddPath(A->getValue(), Group, false, true);
30530b57cec5SDimitry Andric   }
30540b57cec5SDimitry Andric 
30550b57cec5SDimitry Andric   // Add the path prefixes which are implicitly treated as being system headers.
30560b57cec5SDimitry Andric   for (const auto *A :
30570b57cec5SDimitry Andric        Args.filtered(OPT_system_header_prefix, OPT_no_system_header_prefix))
30580b57cec5SDimitry Andric     Opts.AddSystemHeaderPrefix(
30590b57cec5SDimitry Andric         A->getValue(), A->getOption().matches(OPT_system_header_prefix));
30600b57cec5SDimitry Andric 
30610b57cec5SDimitry Andric   for (const auto *A : Args.filtered(OPT_ivfsoverlay))
30620b57cec5SDimitry Andric     Opts.AddVFSOverlayFile(A->getValue());
30635f7ddb14SDimitry Andric 
30645f7ddb14SDimitry Andric   return Diags.getNumErrors() == NumErrorsBefore;
30650b57cec5SDimitry Andric }
30660b57cec5SDimitry Andric 
setLangDefaults(LangOptions & Opts,InputKind IK,const llvm::Triple & T,std::vector<std::string> & Includes,LangStandard::Kind LangStd)30670b57cec5SDimitry Andric void CompilerInvocation::setLangDefaults(LangOptions &Opts, InputKind IK,
30680b57cec5SDimitry Andric                                          const llvm::Triple &T,
3069af732203SDimitry Andric                                          std::vector<std::string> &Includes,
30700b57cec5SDimitry Andric                                          LangStandard::Kind LangStd) {
30710b57cec5SDimitry Andric   // Set some properties which depend solely on the input kind; it would be nice
30720b57cec5SDimitry Andric   // to move these to the language standard, and have the driver resolve the
30730b57cec5SDimitry Andric   // input kind + language standard.
30740b57cec5SDimitry Andric   //
30750b57cec5SDimitry Andric   // FIXME: Perhaps a better model would be for a single source file to have
30760b57cec5SDimitry Andric   // multiple language standards (C / C++ std, ObjC std, OpenCL std, OpenMP std)
30770b57cec5SDimitry Andric   // simultaneously active?
3078a7dea167SDimitry Andric   if (IK.getLanguage() == Language::Asm) {
30790b57cec5SDimitry Andric     Opts.AsmPreprocessor = 1;
30800b57cec5SDimitry Andric   } else if (IK.isObjectiveC()) {
30810b57cec5SDimitry Andric     Opts.ObjC = 1;
30820b57cec5SDimitry Andric   }
30830b57cec5SDimitry Andric 
30840b57cec5SDimitry Andric   if (LangStd == LangStandard::lang_unspecified) {
30850b57cec5SDimitry Andric     // Based on the base language, pick one.
30860b57cec5SDimitry Andric     switch (IK.getLanguage()) {
3087a7dea167SDimitry Andric     case Language::Unknown:
3088a7dea167SDimitry Andric     case Language::LLVM_IR:
30890b57cec5SDimitry Andric       llvm_unreachable("Invalid input kind!");
3090a7dea167SDimitry Andric     case Language::OpenCL:
30915f7ddb14SDimitry Andric       LangStd = LangStandard::lang_opencl12;
30925f7ddb14SDimitry Andric       break;
30935f7ddb14SDimitry Andric     case Language::OpenCLCXX:
30945f7ddb14SDimitry Andric       LangStd = LangStandard::lang_openclcpp;
30950b57cec5SDimitry Andric       break;
3096a7dea167SDimitry Andric     case Language::CUDA:
30970b57cec5SDimitry Andric       LangStd = LangStandard::lang_cuda;
30980b57cec5SDimitry Andric       break;
3099a7dea167SDimitry Andric     case Language::Asm:
3100a7dea167SDimitry Andric     case Language::C:
31010b57cec5SDimitry Andric #if defined(CLANG_DEFAULT_STD_C)
31020b57cec5SDimitry Andric       LangStd = CLANG_DEFAULT_STD_C;
31030b57cec5SDimitry Andric #else
31040b57cec5SDimitry Andric       // The PS4 uses C99 as the default C standard.
31050b57cec5SDimitry Andric       if (T.isPS4())
31060b57cec5SDimitry Andric         LangStd = LangStandard::lang_gnu99;
31070b57cec5SDimitry Andric       else
31085ffd83dbSDimitry Andric         LangStd = LangStandard::lang_gnu17;
31090b57cec5SDimitry Andric #endif
31100b57cec5SDimitry Andric       break;
3111a7dea167SDimitry Andric     case Language::ObjC:
31120b57cec5SDimitry Andric #if defined(CLANG_DEFAULT_STD_C)
31130b57cec5SDimitry Andric       LangStd = CLANG_DEFAULT_STD_C;
31140b57cec5SDimitry Andric #else
31150b57cec5SDimitry Andric       LangStd = LangStandard::lang_gnu11;
31160b57cec5SDimitry Andric #endif
31170b57cec5SDimitry Andric       break;
3118a7dea167SDimitry Andric     case Language::CXX:
3119a7dea167SDimitry Andric     case Language::ObjCXX:
31200b57cec5SDimitry Andric #if defined(CLANG_DEFAULT_STD_CXX)
31210b57cec5SDimitry Andric       LangStd = CLANG_DEFAULT_STD_CXX;
31220b57cec5SDimitry Andric #else
31230b57cec5SDimitry Andric       LangStd = LangStandard::lang_gnucxx14;
31240b57cec5SDimitry Andric #endif
31250b57cec5SDimitry Andric       break;
3126a7dea167SDimitry Andric     case Language::RenderScript:
31270b57cec5SDimitry Andric       LangStd = LangStandard::lang_c99;
31280b57cec5SDimitry Andric       break;
3129a7dea167SDimitry Andric     case Language::HIP:
31300b57cec5SDimitry Andric       LangStd = LangStandard::lang_hip;
31310b57cec5SDimitry Andric       break;
31320b57cec5SDimitry Andric     }
31330b57cec5SDimitry Andric   }
31340b57cec5SDimitry Andric 
31350b57cec5SDimitry Andric   const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
3136af732203SDimitry Andric   Opts.LangStd = LangStd;
31370b57cec5SDimitry Andric   Opts.LineComment = Std.hasLineComments();
31380b57cec5SDimitry Andric   Opts.C99 = Std.isC99();
31390b57cec5SDimitry Andric   Opts.C11 = Std.isC11();
31400b57cec5SDimitry Andric   Opts.C17 = Std.isC17();
31410b57cec5SDimitry Andric   Opts.C2x = Std.isC2x();
31420b57cec5SDimitry Andric   Opts.CPlusPlus = Std.isCPlusPlus();
31430b57cec5SDimitry Andric   Opts.CPlusPlus11 = Std.isCPlusPlus11();
31440b57cec5SDimitry Andric   Opts.CPlusPlus14 = Std.isCPlusPlus14();
31450b57cec5SDimitry Andric   Opts.CPlusPlus17 = Std.isCPlusPlus17();
31465ffd83dbSDimitry Andric   Opts.CPlusPlus20 = Std.isCPlusPlus20();
3147af732203SDimitry Andric   Opts.CPlusPlus2b = Std.isCPlusPlus2b();
31480b57cec5SDimitry Andric   Opts.GNUMode = Std.isGNUMode();
3149a7dea167SDimitry Andric   Opts.GNUCVersion = 0;
31500b57cec5SDimitry Andric   Opts.HexFloats = Std.hasHexFloats();
31510b57cec5SDimitry Andric   Opts.ImplicitInt = Std.hasImplicitInt();
31520b57cec5SDimitry Andric 
31535f7ddb14SDimitry Andric   Opts.CPlusPlusModules = Opts.CPlusPlus20;
31545f7ddb14SDimitry Andric 
31550b57cec5SDimitry Andric   // Set OpenCL Version.
31560b57cec5SDimitry Andric   Opts.OpenCL = Std.isOpenCL();
31570b57cec5SDimitry Andric   if (LangStd == LangStandard::lang_opencl10)
31580b57cec5SDimitry Andric     Opts.OpenCLVersion = 100;
31590b57cec5SDimitry Andric   else if (LangStd == LangStandard::lang_opencl11)
31600b57cec5SDimitry Andric     Opts.OpenCLVersion = 110;
31610b57cec5SDimitry Andric   else if (LangStd == LangStandard::lang_opencl12)
31620b57cec5SDimitry Andric     Opts.OpenCLVersion = 120;
31630b57cec5SDimitry Andric   else if (LangStd == LangStandard::lang_opencl20)
31640b57cec5SDimitry Andric     Opts.OpenCLVersion = 200;
3165af732203SDimitry Andric   else if (LangStd == LangStandard::lang_opencl30)
3166af732203SDimitry Andric     Opts.OpenCLVersion = 300;
31670b57cec5SDimitry Andric   else if (LangStd == LangStandard::lang_openclcpp)
31680b57cec5SDimitry Andric     Opts.OpenCLCPlusPlusVersion = 100;
31690b57cec5SDimitry Andric 
31700b57cec5SDimitry Andric   // OpenCL has some additional defaults.
31710b57cec5SDimitry Andric   if (Opts.OpenCL) {
31720b57cec5SDimitry Andric     Opts.AltiVec = 0;
31730b57cec5SDimitry Andric     Opts.ZVector = 0;
31745ffd83dbSDimitry Andric     Opts.setDefaultFPContractMode(LangOptions::FPM_On);
31750b57cec5SDimitry Andric     Opts.OpenCLCPlusPlus = Opts.CPlusPlus;
3176*2e2f8eacSDimitry Andric     Opts.OpenCLPipes = Opts.OpenCLCPlusPlus || Opts.OpenCLVersion == 200;
31775f7ddb14SDimitry Andric     Opts.OpenCLGenericAddressSpace =
31785f7ddb14SDimitry Andric         Opts.OpenCLCPlusPlus || Opts.OpenCLVersion == 200;
31790b57cec5SDimitry Andric 
31800b57cec5SDimitry Andric     // Include default header file for OpenCL.
31810b57cec5SDimitry Andric     if (Opts.IncludeDefaultHeader) {
31820b57cec5SDimitry Andric       if (Opts.DeclareOpenCLBuiltins) {
31830b57cec5SDimitry Andric         // Only include base header file for builtin types and constants.
3184af732203SDimitry Andric         Includes.push_back("opencl-c-base.h");
31850b57cec5SDimitry Andric       } else {
3186af732203SDimitry Andric         Includes.push_back("opencl-c.h");
31870b57cec5SDimitry Andric       }
31880b57cec5SDimitry Andric     }
31890b57cec5SDimitry Andric   }
31900b57cec5SDimitry Andric 
3191a7dea167SDimitry Andric   Opts.HIP = IK.getLanguage() == Language::HIP;
3192a7dea167SDimitry Andric   Opts.CUDA = IK.getLanguage() == Language::CUDA || Opts.HIP;
3193af732203SDimitry Andric   if (Opts.HIP) {
3194af732203SDimitry Andric     // HIP toolchain does not support 'Fast' FPOpFusion in backends since it
3195af732203SDimitry Andric     // fuses multiplication/addition instructions without contract flag from
3196af732203SDimitry Andric     // device library functions in LLVM bitcode, which causes accuracy loss in
3197af732203SDimitry Andric     // certain math functions, e.g. tan(-1e20) becomes -0.933 instead of 0.8446.
3198af732203SDimitry Andric     // For device library functions in bitcode to work, 'Strict' or 'Standard'
3199af732203SDimitry Andric     // FPOpFusion options in backends is needed. Therefore 'fast-honor-pragmas'
3200af732203SDimitry Andric     // FP contract option is used to allow fuse across statements in frontend
3201af732203SDimitry Andric     // whereas respecting contract flag in backend.
3202af732203SDimitry Andric     Opts.setDefaultFPContractMode(LangOptions::FPM_FastHonorPragmas);
3203af732203SDimitry Andric   } else if (Opts.CUDA) {
3204af732203SDimitry Andric     // Allow fuse across statements disregarding pragmas.
32055ffd83dbSDimitry Andric     Opts.setDefaultFPContractMode(LangOptions::FPM_Fast);
3206af732203SDimitry Andric   }
32070b57cec5SDimitry Andric 
3208a7dea167SDimitry Andric   Opts.RenderScript = IK.getLanguage() == Language::RenderScript;
32090b57cec5SDimitry Andric 
32100b57cec5SDimitry Andric   // OpenCL and C++ both have bool, true, false keywords.
32110b57cec5SDimitry Andric   Opts.Bool = Opts.OpenCL || Opts.CPlusPlus;
32120b57cec5SDimitry Andric 
32130b57cec5SDimitry Andric   // OpenCL has half keyword
32140b57cec5SDimitry Andric   Opts.Half = Opts.OpenCL;
32150b57cec5SDimitry Andric }
32160b57cec5SDimitry Andric 
32170b57cec5SDimitry Andric /// Check if input file kind and language standard are compatible.
IsInputCompatibleWithStandard(InputKind IK,const LangStandard & S)32180b57cec5SDimitry Andric static bool IsInputCompatibleWithStandard(InputKind IK,
32190b57cec5SDimitry Andric                                           const LangStandard &S) {
32200b57cec5SDimitry Andric   switch (IK.getLanguage()) {
3221a7dea167SDimitry Andric   case Language::Unknown:
3222a7dea167SDimitry Andric   case Language::LLVM_IR:
32230b57cec5SDimitry Andric     llvm_unreachable("should not parse language flags for this input");
32240b57cec5SDimitry Andric 
3225a7dea167SDimitry Andric   case Language::C:
3226a7dea167SDimitry Andric   case Language::ObjC:
3227a7dea167SDimitry Andric   case Language::RenderScript:
3228a7dea167SDimitry Andric     return S.getLanguage() == Language::C;
32290b57cec5SDimitry Andric 
3230a7dea167SDimitry Andric   case Language::OpenCL:
32315f7ddb14SDimitry Andric     return S.getLanguage() == Language::OpenCL ||
32325f7ddb14SDimitry Andric            S.getLanguage() == Language::OpenCLCXX;
32335f7ddb14SDimitry Andric 
32345f7ddb14SDimitry Andric   case Language::OpenCLCXX:
32355f7ddb14SDimitry Andric     return S.getLanguage() == Language::OpenCLCXX;
32360b57cec5SDimitry Andric 
3237a7dea167SDimitry Andric   case Language::CXX:
3238a7dea167SDimitry Andric   case Language::ObjCXX:
3239a7dea167SDimitry Andric     return S.getLanguage() == Language::CXX;
32400b57cec5SDimitry Andric 
3241a7dea167SDimitry Andric   case Language::CUDA:
32420b57cec5SDimitry Andric     // FIXME: What -std= values should be permitted for CUDA compilations?
3243a7dea167SDimitry Andric     return S.getLanguage() == Language::CUDA ||
3244a7dea167SDimitry Andric            S.getLanguage() == Language::CXX;
32450b57cec5SDimitry Andric 
3246a7dea167SDimitry Andric   case Language::HIP:
3247a7dea167SDimitry Andric     return S.getLanguage() == Language::CXX || S.getLanguage() == Language::HIP;
32480b57cec5SDimitry Andric 
3249a7dea167SDimitry Andric   case Language::Asm:
32500b57cec5SDimitry Andric     // Accept (and ignore) all -std= values.
32510b57cec5SDimitry Andric     // FIXME: The -std= value is not ignored; it affects the tokenization
32520b57cec5SDimitry Andric     // and preprocessing rules if we're preprocessing this asm input.
32530b57cec5SDimitry Andric     return true;
32540b57cec5SDimitry Andric   }
32550b57cec5SDimitry Andric 
32560b57cec5SDimitry Andric   llvm_unreachable("unexpected input language");
32570b57cec5SDimitry Andric }
32580b57cec5SDimitry Andric 
32590b57cec5SDimitry Andric /// Get language name for given input kind.
GetInputKindName(InputKind IK)32600b57cec5SDimitry Andric static const StringRef GetInputKindName(InputKind IK) {
32610b57cec5SDimitry Andric   switch (IK.getLanguage()) {
3262a7dea167SDimitry Andric   case Language::C:
32630b57cec5SDimitry Andric     return "C";
3264a7dea167SDimitry Andric   case Language::ObjC:
32650b57cec5SDimitry Andric     return "Objective-C";
3266a7dea167SDimitry Andric   case Language::CXX:
32670b57cec5SDimitry Andric     return "C++";
3268a7dea167SDimitry Andric   case Language::ObjCXX:
32690b57cec5SDimitry Andric     return "Objective-C++";
3270a7dea167SDimitry Andric   case Language::OpenCL:
32710b57cec5SDimitry Andric     return "OpenCL";
32725f7ddb14SDimitry Andric   case Language::OpenCLCXX:
32735f7ddb14SDimitry Andric     return "C++ for OpenCL";
3274a7dea167SDimitry Andric   case Language::CUDA:
32750b57cec5SDimitry Andric     return "CUDA";
3276a7dea167SDimitry Andric   case Language::RenderScript:
32770b57cec5SDimitry Andric     return "RenderScript";
3278a7dea167SDimitry Andric   case Language::HIP:
32790b57cec5SDimitry Andric     return "HIP";
32800b57cec5SDimitry Andric 
3281a7dea167SDimitry Andric   case Language::Asm:
32820b57cec5SDimitry Andric     return "Asm";
3283a7dea167SDimitry Andric   case Language::LLVM_IR:
32840b57cec5SDimitry Andric     return "LLVM IR";
32850b57cec5SDimitry Andric 
3286a7dea167SDimitry Andric   case Language::Unknown:
32870b57cec5SDimitry Andric     break;
32880b57cec5SDimitry Andric   }
32890b57cec5SDimitry Andric   llvm_unreachable("unknown input language");
32900b57cec5SDimitry Andric }
32910b57cec5SDimitry Andric 
GenerateLangArgs(const LangOptions & Opts,SmallVectorImpl<const char * > & Args,StringAllocator SA,const llvm::Triple & T,InputKind IK)32925f7ddb14SDimitry Andric void CompilerInvocation::GenerateLangArgs(const LangOptions &Opts,
3293af732203SDimitry Andric                                           SmallVectorImpl<const char *> &Args,
32945f7ddb14SDimitry Andric                                           StringAllocator SA,
32955f7ddb14SDimitry Andric                                           const llvm::Triple &T, InputKind IK) {
32965f7ddb14SDimitry Andric   if (IK.getFormat() == InputKind::Precompiled ||
32975f7ddb14SDimitry Andric       IK.getLanguage() == Language::LLVM_IR) {
32985f7ddb14SDimitry Andric     if (Opts.ObjCAutoRefCount)
32995f7ddb14SDimitry Andric       GenerateArg(Args, OPT_fobjc_arc, SA);
33005f7ddb14SDimitry Andric     if (Opts.PICLevel != 0)
33015f7ddb14SDimitry Andric       GenerateArg(Args, OPT_pic_level, Twine(Opts.PICLevel), SA);
33025f7ddb14SDimitry Andric     if (Opts.PIE)
33035f7ddb14SDimitry Andric       GenerateArg(Args, OPT_pic_is_pie, SA);
33045f7ddb14SDimitry Andric     for (StringRef Sanitizer : serializeSanitizerKinds(Opts.Sanitize))
33055f7ddb14SDimitry Andric       GenerateArg(Args, OPT_fsanitize_EQ, Sanitizer, SA);
33065f7ddb14SDimitry Andric 
33075f7ddb14SDimitry Andric     return;
3308af732203SDimitry Andric   }
3309af732203SDimitry Andric 
33105f7ddb14SDimitry Andric   OptSpecifier StdOpt;
33115f7ddb14SDimitry Andric   switch (Opts.LangStd) {
33125f7ddb14SDimitry Andric   case LangStandard::lang_opencl10:
33135f7ddb14SDimitry Andric   case LangStandard::lang_opencl11:
33145f7ddb14SDimitry Andric   case LangStandard::lang_opencl12:
33155f7ddb14SDimitry Andric   case LangStandard::lang_opencl20:
33165f7ddb14SDimitry Andric   case LangStandard::lang_opencl30:
33175f7ddb14SDimitry Andric   case LangStandard::lang_openclcpp:
33185f7ddb14SDimitry Andric     StdOpt = OPT_cl_std_EQ;
33195f7ddb14SDimitry Andric     break;
33205f7ddb14SDimitry Andric   default:
33215f7ddb14SDimitry Andric     StdOpt = OPT_std_EQ;
33225f7ddb14SDimitry Andric     break;
33235f7ddb14SDimitry Andric   }
33245f7ddb14SDimitry Andric 
33255f7ddb14SDimitry Andric   auto LangStandard = LangStandard::getLangStandardForKind(Opts.LangStd);
33265f7ddb14SDimitry Andric   GenerateArg(Args, StdOpt, LangStandard.getName(), SA);
33275f7ddb14SDimitry Andric 
33285f7ddb14SDimitry Andric   if (Opts.IncludeDefaultHeader)
33295f7ddb14SDimitry Andric     GenerateArg(Args, OPT_finclude_default_header, SA);
33305f7ddb14SDimitry Andric   if (Opts.DeclareOpenCLBuiltins)
33315f7ddb14SDimitry Andric     GenerateArg(Args, OPT_fdeclare_opencl_builtins, SA);
33325f7ddb14SDimitry Andric 
33335f7ddb14SDimitry Andric   const LangOptions *LangOpts = &Opts;
33345f7ddb14SDimitry Andric 
33355f7ddb14SDimitry Andric #define LANG_OPTION_WITH_MARSHALLING(                                          \
33365f7ddb14SDimitry Andric     PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,        \
33375f7ddb14SDimitry Andric     HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
33385f7ddb14SDimitry Andric     DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER,     \
33395f7ddb14SDimitry Andric     MERGER, EXTRACTOR, TABLE_INDEX)                                            \
33405f7ddb14SDimitry Andric   GENERATE_OPTION_WITH_MARSHALLING(                                            \
33415f7ddb14SDimitry Andric       Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE,    \
33425f7ddb14SDimitry Andric       IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
33435f7ddb14SDimitry Andric #include "clang/Driver/Options.inc"
33445f7ddb14SDimitry Andric #undef LANG_OPTION_WITH_MARSHALLING
33455f7ddb14SDimitry Andric 
33465f7ddb14SDimitry Andric   // The '-fcf-protection=' option is generated by CodeGenOpts generator.
33475f7ddb14SDimitry Andric 
33485f7ddb14SDimitry Andric   if (Opts.ObjC) {
33495f7ddb14SDimitry Andric     GenerateArg(Args, OPT_fobjc_runtime_EQ, Opts.ObjCRuntime.getAsString(), SA);
33505f7ddb14SDimitry Andric 
33515f7ddb14SDimitry Andric     if (Opts.GC == LangOptions::GCOnly)
33525f7ddb14SDimitry Andric       GenerateArg(Args, OPT_fobjc_gc_only, SA);
33535f7ddb14SDimitry Andric     else if (Opts.GC == LangOptions::HybridGC)
33545f7ddb14SDimitry Andric       GenerateArg(Args, OPT_fobjc_gc, SA);
33555f7ddb14SDimitry Andric     else if (Opts.ObjCAutoRefCount == 1)
33565f7ddb14SDimitry Andric       GenerateArg(Args, OPT_fobjc_arc, SA);
33575f7ddb14SDimitry Andric 
33585f7ddb14SDimitry Andric     if (Opts.ObjCWeakRuntime)
33595f7ddb14SDimitry Andric       GenerateArg(Args, OPT_fobjc_runtime_has_weak, SA);
33605f7ddb14SDimitry Andric 
33615f7ddb14SDimitry Andric     if (Opts.ObjCWeak)
33625f7ddb14SDimitry Andric       GenerateArg(Args, OPT_fobjc_weak, SA);
33635f7ddb14SDimitry Andric 
33645f7ddb14SDimitry Andric     if (Opts.ObjCSubscriptingLegacyRuntime)
33655f7ddb14SDimitry Andric       GenerateArg(Args, OPT_fobjc_subscripting_legacy_runtime, SA);
33665f7ddb14SDimitry Andric   }
33675f7ddb14SDimitry Andric 
33685f7ddb14SDimitry Andric   if (Opts.GNUCVersion != 0) {
33695f7ddb14SDimitry Andric     unsigned Major = Opts.GNUCVersion / 100 / 100;
33705f7ddb14SDimitry Andric     unsigned Minor = (Opts.GNUCVersion / 100) % 100;
33715f7ddb14SDimitry Andric     unsigned Patch = Opts.GNUCVersion % 100;
33725f7ddb14SDimitry Andric     GenerateArg(Args, OPT_fgnuc_version_EQ,
33735f7ddb14SDimitry Andric                 Twine(Major) + "." + Twine(Minor) + "." + Twine(Patch), SA);
33745f7ddb14SDimitry Andric   }
33755f7ddb14SDimitry Andric 
33765f7ddb14SDimitry Andric   if (Opts.IgnoreXCOFFVisibility)
33775f7ddb14SDimitry Andric     GenerateArg(Args, OPT_mignore_xcoff_visibility, SA);
33785f7ddb14SDimitry Andric 
33795f7ddb14SDimitry Andric   if (Opts.SignedOverflowBehavior == LangOptions::SOB_Trapping) {
33805f7ddb14SDimitry Andric     GenerateArg(Args, OPT_ftrapv, SA);
33815f7ddb14SDimitry Andric     GenerateArg(Args, OPT_ftrapv_handler, Opts.OverflowHandler, SA);
33825f7ddb14SDimitry Andric   } else if (Opts.SignedOverflowBehavior == LangOptions::SOB_Defined) {
33835f7ddb14SDimitry Andric     GenerateArg(Args, OPT_fwrapv, SA);
33845f7ddb14SDimitry Andric   }
33855f7ddb14SDimitry Andric 
33865f7ddb14SDimitry Andric   if (Opts.MSCompatibilityVersion != 0) {
33875f7ddb14SDimitry Andric     unsigned Major = Opts.MSCompatibilityVersion / 10000000;
33885f7ddb14SDimitry Andric     unsigned Minor = (Opts.MSCompatibilityVersion / 100000) % 100;
33895f7ddb14SDimitry Andric     unsigned Subminor = Opts.MSCompatibilityVersion % 100000;
33905f7ddb14SDimitry Andric     GenerateArg(Args, OPT_fms_compatibility_version,
33915f7ddb14SDimitry Andric                 Twine(Major) + "." + Twine(Minor) + "." + Twine(Subminor), SA);
33925f7ddb14SDimitry Andric   }
33935f7ddb14SDimitry Andric 
33945f7ddb14SDimitry Andric   if ((!Opts.GNUMode && !Opts.MSVCCompat && !Opts.CPlusPlus17) || T.isOSzOS()) {
33955f7ddb14SDimitry Andric     if (!Opts.Trigraphs)
33965f7ddb14SDimitry Andric       GenerateArg(Args, OPT_fno_trigraphs, SA);
33975f7ddb14SDimitry Andric   } else {
33985f7ddb14SDimitry Andric     if (Opts.Trigraphs)
33995f7ddb14SDimitry Andric       GenerateArg(Args, OPT_ftrigraphs, SA);
34005f7ddb14SDimitry Andric   }
34015f7ddb14SDimitry Andric 
34025f7ddb14SDimitry Andric   if (Opts.Blocks && !(Opts.OpenCL && Opts.OpenCLVersion == 200))
34035f7ddb14SDimitry Andric     GenerateArg(Args, OPT_fblocks, SA);
34045f7ddb14SDimitry Andric 
34055f7ddb14SDimitry Andric   if (Opts.ConvergentFunctions &&
34065f7ddb14SDimitry Andric       !(Opts.OpenCL || (Opts.CUDA && Opts.CUDAIsDevice) || Opts.SYCLIsDevice))
34075f7ddb14SDimitry Andric     GenerateArg(Args, OPT_fconvergent_functions, SA);
34085f7ddb14SDimitry Andric 
34095f7ddb14SDimitry Andric   if (Opts.NoBuiltin && !Opts.Freestanding)
34105f7ddb14SDimitry Andric     GenerateArg(Args, OPT_fno_builtin, SA);
34115f7ddb14SDimitry Andric 
34125f7ddb14SDimitry Andric   if (!Opts.NoBuiltin)
34135f7ddb14SDimitry Andric     for (const auto &Func : Opts.NoBuiltinFuncs)
34145f7ddb14SDimitry Andric       GenerateArg(Args, OPT_fno_builtin_, Func, SA);
34155f7ddb14SDimitry Andric 
34165f7ddb14SDimitry Andric   if (Opts.LongDoubleSize == 128)
34175f7ddb14SDimitry Andric     GenerateArg(Args, OPT_mlong_double_128, SA);
34185f7ddb14SDimitry Andric   else if (Opts.LongDoubleSize == 64)
34195f7ddb14SDimitry Andric     GenerateArg(Args, OPT_mlong_double_64, SA);
34205f7ddb14SDimitry Andric 
34215f7ddb14SDimitry Andric   // Not generating '-mrtd', it's just an alias for '-fdefault-calling-conv='.
34225f7ddb14SDimitry Andric 
34235f7ddb14SDimitry Andric   // OpenMP was requested via '-fopenmp', not implied by '-fopenmp-simd' or
34245f7ddb14SDimitry Andric   // '-fopenmp-targets='.
34255f7ddb14SDimitry Andric   if (Opts.OpenMP && !Opts.OpenMPSimd) {
34265f7ddb14SDimitry Andric     GenerateArg(Args, OPT_fopenmp, SA);
34275f7ddb14SDimitry Andric 
34285f7ddb14SDimitry Andric     if (Opts.OpenMP != 50)
34295f7ddb14SDimitry Andric       GenerateArg(Args, OPT_fopenmp_version_EQ, Twine(Opts.OpenMP), SA);
34305f7ddb14SDimitry Andric 
34315f7ddb14SDimitry Andric     if (!Opts.OpenMPUseTLS)
34325f7ddb14SDimitry Andric       GenerateArg(Args, OPT_fnoopenmp_use_tls, SA);
34335f7ddb14SDimitry Andric 
34345f7ddb14SDimitry Andric     if (Opts.OpenMPIsDevice)
34355f7ddb14SDimitry Andric       GenerateArg(Args, OPT_fopenmp_is_device, SA);
34365f7ddb14SDimitry Andric 
34375f7ddb14SDimitry Andric     if (Opts.OpenMPIRBuilder)
34385f7ddb14SDimitry Andric       GenerateArg(Args, OPT_fopenmp_enable_irbuilder, SA);
34395f7ddb14SDimitry Andric   }
34405f7ddb14SDimitry Andric 
34415f7ddb14SDimitry Andric   if (Opts.OpenMPSimd) {
34425f7ddb14SDimitry Andric     GenerateArg(Args, OPT_fopenmp_simd, SA);
34435f7ddb14SDimitry Andric 
34445f7ddb14SDimitry Andric     if (Opts.OpenMP != 50)
34455f7ddb14SDimitry Andric       GenerateArg(Args, OPT_fopenmp_version_EQ, Twine(Opts.OpenMP), SA);
34465f7ddb14SDimitry Andric   }
34475f7ddb14SDimitry Andric 
34485f7ddb14SDimitry Andric   if (Opts.OpenMPCUDANumSMs != 0)
34495f7ddb14SDimitry Andric     GenerateArg(Args, OPT_fopenmp_cuda_number_of_sm_EQ,
34505f7ddb14SDimitry Andric                 Twine(Opts.OpenMPCUDANumSMs), SA);
34515f7ddb14SDimitry Andric 
34525f7ddb14SDimitry Andric   if (Opts.OpenMPCUDABlocksPerSM != 0)
34535f7ddb14SDimitry Andric     GenerateArg(Args, OPT_fopenmp_cuda_blocks_per_sm_EQ,
34545f7ddb14SDimitry Andric                 Twine(Opts.OpenMPCUDABlocksPerSM), SA);
34555f7ddb14SDimitry Andric 
34565f7ddb14SDimitry Andric   if (Opts.OpenMPCUDAReductionBufNum != 1024)
34575f7ddb14SDimitry Andric     GenerateArg(Args, OPT_fopenmp_cuda_teams_reduction_recs_num_EQ,
34585f7ddb14SDimitry Andric                 Twine(Opts.OpenMPCUDAReductionBufNum), SA);
34595f7ddb14SDimitry Andric 
34605f7ddb14SDimitry Andric   if (!Opts.OMPTargetTriples.empty()) {
34615f7ddb14SDimitry Andric     std::string Targets;
34625f7ddb14SDimitry Andric     llvm::raw_string_ostream OS(Targets);
34635f7ddb14SDimitry Andric     llvm::interleave(
34645f7ddb14SDimitry Andric         Opts.OMPTargetTriples, OS,
34655f7ddb14SDimitry Andric         [&OS](const llvm::Triple &T) { OS << T.str(); }, ",");
34665f7ddb14SDimitry Andric     GenerateArg(Args, OPT_fopenmp_targets_EQ, OS.str(), SA);
34675f7ddb14SDimitry Andric   }
34685f7ddb14SDimitry Andric 
34695f7ddb14SDimitry Andric   if (!Opts.OMPHostIRFile.empty())
34705f7ddb14SDimitry Andric     GenerateArg(Args, OPT_fopenmp_host_ir_file_path, Opts.OMPHostIRFile, SA);
34715f7ddb14SDimitry Andric 
34725f7ddb14SDimitry Andric   if (Opts.OpenMPCUDAMode)
34735f7ddb14SDimitry Andric     GenerateArg(Args, OPT_fopenmp_cuda_mode, SA);
34745f7ddb14SDimitry Andric 
34755f7ddb14SDimitry Andric   if (Opts.OpenMPCUDAForceFullRuntime)
34765f7ddb14SDimitry Andric     GenerateArg(Args, OPT_fopenmp_cuda_force_full_runtime, SA);
34775f7ddb14SDimitry Andric 
34785f7ddb14SDimitry Andric   // The arguments used to set Optimize, OptimizeSize and NoInlineDefine are
34795f7ddb14SDimitry Andric   // generated from CodeGenOptions.
34805f7ddb14SDimitry Andric 
34815f7ddb14SDimitry Andric   if (Opts.DefaultFPContractMode == LangOptions::FPM_Fast)
34825f7ddb14SDimitry Andric     GenerateArg(Args, OPT_ffp_contract, "fast", SA);
34835f7ddb14SDimitry Andric   else if (Opts.DefaultFPContractMode == LangOptions::FPM_On)
34845f7ddb14SDimitry Andric     GenerateArg(Args, OPT_ffp_contract, "on", SA);
34855f7ddb14SDimitry Andric   else if (Opts.DefaultFPContractMode == LangOptions::FPM_Off)
34865f7ddb14SDimitry Andric     GenerateArg(Args, OPT_ffp_contract, "off", SA);
34875f7ddb14SDimitry Andric   else if (Opts.DefaultFPContractMode == LangOptions::FPM_FastHonorPragmas)
34885f7ddb14SDimitry Andric     GenerateArg(Args, OPT_ffp_contract, "fast-honor-pragmas", SA);
34895f7ddb14SDimitry Andric 
34905f7ddb14SDimitry Andric   for (StringRef Sanitizer : serializeSanitizerKinds(Opts.Sanitize))
34915f7ddb14SDimitry Andric     GenerateArg(Args, OPT_fsanitize_EQ, Sanitizer, SA);
34925f7ddb14SDimitry Andric 
34935f7ddb14SDimitry Andric   // Conflating '-fsanitize-system-ignorelist' and '-fsanitize-ignorelist'.
34945f7ddb14SDimitry Andric   for (const std::string &F : Opts.NoSanitizeFiles)
34955f7ddb14SDimitry Andric     GenerateArg(Args, OPT_fsanitize_ignorelist_EQ, F, SA);
34965f7ddb14SDimitry Andric 
34975f7ddb14SDimitry Andric   if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver3_8)
34985f7ddb14SDimitry Andric     GenerateArg(Args, OPT_fclang_abi_compat_EQ, "3.8", SA);
34995f7ddb14SDimitry Andric   else if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver4)
35005f7ddb14SDimitry Andric     GenerateArg(Args, OPT_fclang_abi_compat_EQ, "4.0", SA);
35015f7ddb14SDimitry Andric   else if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver6)
35025f7ddb14SDimitry Andric     GenerateArg(Args, OPT_fclang_abi_compat_EQ, "6.0", SA);
35035f7ddb14SDimitry Andric   else if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver7)
35045f7ddb14SDimitry Andric     GenerateArg(Args, OPT_fclang_abi_compat_EQ, "7.0", SA);
35055f7ddb14SDimitry Andric   else if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver9)
35065f7ddb14SDimitry Andric     GenerateArg(Args, OPT_fclang_abi_compat_EQ, "9.0", SA);
35075f7ddb14SDimitry Andric   else if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver11)
35085f7ddb14SDimitry Andric     GenerateArg(Args, OPT_fclang_abi_compat_EQ, "11.0", SA);
35095f7ddb14SDimitry Andric   else if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver12)
35105f7ddb14SDimitry Andric     GenerateArg(Args, OPT_fclang_abi_compat_EQ, "12.0", SA);
35115f7ddb14SDimitry Andric 
35125f7ddb14SDimitry Andric   if (Opts.getSignReturnAddressScope() ==
35135f7ddb14SDimitry Andric       LangOptions::SignReturnAddressScopeKind::All)
35145f7ddb14SDimitry Andric     GenerateArg(Args, OPT_msign_return_address_EQ, "all", SA);
35155f7ddb14SDimitry Andric   else if (Opts.getSignReturnAddressScope() ==
35165f7ddb14SDimitry Andric            LangOptions::SignReturnAddressScopeKind::NonLeaf)
35175f7ddb14SDimitry Andric     GenerateArg(Args, OPT_msign_return_address_EQ, "non-leaf", SA);
35185f7ddb14SDimitry Andric 
35195f7ddb14SDimitry Andric   if (Opts.getSignReturnAddressKey() ==
35205f7ddb14SDimitry Andric       LangOptions::SignReturnAddressKeyKind::BKey)
35215f7ddb14SDimitry Andric     GenerateArg(Args, OPT_msign_return_address_key_EQ, "b_key", SA);
35225f7ddb14SDimitry Andric 
35235f7ddb14SDimitry Andric   if (Opts.CXXABI)
35245f7ddb14SDimitry Andric     GenerateArg(Args, OPT_fcxx_abi_EQ, TargetCXXABI::getSpelling(*Opts.CXXABI),
35255f7ddb14SDimitry Andric                 SA);
35265f7ddb14SDimitry Andric 
35275f7ddb14SDimitry Andric   if (Opts.RelativeCXXABIVTables)
35285f7ddb14SDimitry Andric     GenerateArg(Args, OPT_fexperimental_relative_cxx_abi_vtables, SA);
35295f7ddb14SDimitry Andric   else
35305f7ddb14SDimitry Andric     GenerateArg(Args, OPT_fno_experimental_relative_cxx_abi_vtables, SA);
3531*2e2f8eacSDimitry Andric 
3532*2e2f8eacSDimitry Andric   for (const auto &MP : Opts.MacroPrefixMap)
3533*2e2f8eacSDimitry Andric     GenerateArg(Args, OPT_fmacro_prefix_map_EQ, MP.first + "=" + MP.second, SA);
35345f7ddb14SDimitry Andric }
35355f7ddb14SDimitry Andric 
ParseLangArgs(LangOptions & Opts,ArgList & Args,InputKind IK,const llvm::Triple & T,std::vector<std::string> & Includes,DiagnosticsEngine & Diags)35365f7ddb14SDimitry Andric bool CompilerInvocation::ParseLangArgs(LangOptions &Opts, ArgList &Args,
3537af732203SDimitry Andric                                        InputKind IK, const llvm::Triple &T,
3538af732203SDimitry Andric                                        std::vector<std::string> &Includes,
35390b57cec5SDimitry Andric                                        DiagnosticsEngine &Diags) {
35405f7ddb14SDimitry Andric   unsigned NumErrorsBefore = Diags.getNumErrors();
35415f7ddb14SDimitry Andric 
35425f7ddb14SDimitry Andric   if (IK.getFormat() == InputKind::Precompiled ||
35435f7ddb14SDimitry Andric       IK.getLanguage() == Language::LLVM_IR) {
35445f7ddb14SDimitry Andric     // ObjCAAutoRefCount and Sanitize LangOpts are used to setup the
35455f7ddb14SDimitry Andric     // PassManager in BackendUtil.cpp. They need to be initialized no matter
35465f7ddb14SDimitry Andric     // what the input type is.
35475f7ddb14SDimitry Andric     if (Args.hasArg(OPT_fobjc_arc))
35485f7ddb14SDimitry Andric       Opts.ObjCAutoRefCount = 1;
35495f7ddb14SDimitry Andric     // PICLevel and PIELevel are needed during code generation and this should
35505f7ddb14SDimitry Andric     // be set regardless of the input type.
35515f7ddb14SDimitry Andric     Opts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags);
35525f7ddb14SDimitry Andric     Opts.PIE = Args.hasArg(OPT_pic_is_pie);
35535f7ddb14SDimitry Andric     parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ),
35545f7ddb14SDimitry Andric                         Diags, Opts.Sanitize);
35555f7ddb14SDimitry Andric 
35565f7ddb14SDimitry Andric     return Diags.getNumErrors() == NumErrorsBefore;
35575f7ddb14SDimitry Andric   }
35585f7ddb14SDimitry Andric 
35595f7ddb14SDimitry Andric   // Other LangOpts are only initialized when the input is not AST or LLVM IR.
35605f7ddb14SDimitry Andric   // FIXME: Should we really be parsing this for an Language::Asm input?
35615f7ddb14SDimitry Andric 
35620b57cec5SDimitry Andric   // FIXME: Cleanup per-file based stuff.
35630b57cec5SDimitry Andric   LangStandard::Kind LangStd = LangStandard::lang_unspecified;
35640b57cec5SDimitry Andric   if (const Arg *A = Args.getLastArg(OPT_std_EQ)) {
3565a7dea167SDimitry Andric     LangStd = LangStandard::getLangKind(A->getValue());
35660b57cec5SDimitry Andric     if (LangStd == LangStandard::lang_unspecified) {
35670b57cec5SDimitry Andric       Diags.Report(diag::err_drv_invalid_value)
35680b57cec5SDimitry Andric         << A->getAsString(Args) << A->getValue();
35690b57cec5SDimitry Andric       // Report supported standards with short description.
35700b57cec5SDimitry Andric       for (unsigned KindValue = 0;
35710b57cec5SDimitry Andric            KindValue != LangStandard::lang_unspecified;
35720b57cec5SDimitry Andric            ++KindValue) {
35730b57cec5SDimitry Andric         const LangStandard &Std = LangStandard::getLangStandardForKind(
35740b57cec5SDimitry Andric           static_cast<LangStandard::Kind>(KindValue));
35750b57cec5SDimitry Andric         if (IsInputCompatibleWithStandard(IK, Std)) {
35760b57cec5SDimitry Andric           auto Diag = Diags.Report(diag::note_drv_use_standard);
35770b57cec5SDimitry Andric           Diag << Std.getName() << Std.getDescription();
35780b57cec5SDimitry Andric           unsigned NumAliases = 0;
35790b57cec5SDimitry Andric #define LANGSTANDARD(id, name, lang, desc, features)
35800b57cec5SDimitry Andric #define LANGSTANDARD_ALIAS(id, alias) \
35810b57cec5SDimitry Andric           if (KindValue == LangStandard::lang_##id) ++NumAliases;
35820b57cec5SDimitry Andric #define LANGSTANDARD_ALIAS_DEPR(id, alias)
3583a7dea167SDimitry Andric #include "clang/Basic/LangStandards.def"
35840b57cec5SDimitry Andric           Diag << NumAliases;
35850b57cec5SDimitry Andric #define LANGSTANDARD(id, name, lang, desc, features)
35860b57cec5SDimitry Andric #define LANGSTANDARD_ALIAS(id, alias) \
35870b57cec5SDimitry Andric           if (KindValue == LangStandard::lang_##id) Diag << alias;
35880b57cec5SDimitry Andric #define LANGSTANDARD_ALIAS_DEPR(id, alias)
3589a7dea167SDimitry Andric #include "clang/Basic/LangStandards.def"
35900b57cec5SDimitry Andric         }
35910b57cec5SDimitry Andric       }
35920b57cec5SDimitry Andric     } else {
35930b57cec5SDimitry Andric       // Valid standard, check to make sure language and standard are
35940b57cec5SDimitry Andric       // compatible.
35950b57cec5SDimitry Andric       const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
35960b57cec5SDimitry Andric       if (!IsInputCompatibleWithStandard(IK, Std)) {
35970b57cec5SDimitry Andric         Diags.Report(diag::err_drv_argument_not_allowed_with)
35980b57cec5SDimitry Andric           << A->getAsString(Args) << GetInputKindName(IK);
35990b57cec5SDimitry Andric       }
36000b57cec5SDimitry Andric     }
36010b57cec5SDimitry Andric   }
36020b57cec5SDimitry Andric 
36030b57cec5SDimitry Andric   // -cl-std only applies for OpenCL language standards.
36040b57cec5SDimitry Andric   // Override the -std option in this case.
36050b57cec5SDimitry Andric   if (const Arg *A = Args.getLastArg(OPT_cl_std_EQ)) {
36060b57cec5SDimitry Andric     LangStandard::Kind OpenCLLangStd
36070b57cec5SDimitry Andric       = llvm::StringSwitch<LangStandard::Kind>(A->getValue())
36080b57cec5SDimitry Andric         .Cases("cl", "CL", LangStandard::lang_opencl10)
3609af732203SDimitry Andric         .Cases("cl1.0", "CL1.0", LangStandard::lang_opencl10)
36100b57cec5SDimitry Andric         .Cases("cl1.1", "CL1.1", LangStandard::lang_opencl11)
36110b57cec5SDimitry Andric         .Cases("cl1.2", "CL1.2", LangStandard::lang_opencl12)
36120b57cec5SDimitry Andric         .Cases("cl2.0", "CL2.0", LangStandard::lang_opencl20)
3613af732203SDimitry Andric         .Cases("cl3.0", "CL3.0", LangStandard::lang_opencl30)
36140b57cec5SDimitry Andric         .Cases("clc++", "CLC++", LangStandard::lang_openclcpp)
36150b57cec5SDimitry Andric         .Default(LangStandard::lang_unspecified);
36160b57cec5SDimitry Andric 
36170b57cec5SDimitry Andric     if (OpenCLLangStd == LangStandard::lang_unspecified) {
36180b57cec5SDimitry Andric       Diags.Report(diag::err_drv_invalid_value)
36190b57cec5SDimitry Andric         << A->getAsString(Args) << A->getValue();
36200b57cec5SDimitry Andric     }
36210b57cec5SDimitry Andric     else
36220b57cec5SDimitry Andric       LangStd = OpenCLLangStd;
36230b57cec5SDimitry Andric   }
36240b57cec5SDimitry Andric 
3625af732203SDimitry Andric   // These need to be parsed now. They are used to set OpenCL defaults.
36260b57cec5SDimitry Andric   Opts.IncludeDefaultHeader = Args.hasArg(OPT_finclude_default_header);
36270b57cec5SDimitry Andric   Opts.DeclareOpenCLBuiltins = Args.hasArg(OPT_fdeclare_opencl_builtins);
36280b57cec5SDimitry Andric 
3629af732203SDimitry Andric   CompilerInvocation::setLangDefaults(Opts, IK, T, Includes, LangStd);
36300b57cec5SDimitry Andric 
3631af732203SDimitry Andric   // The key paths of codegen options defined in Options.td start with
3632af732203SDimitry Andric   // "LangOpts->". Let's provide the expected variable name and type.
3633af732203SDimitry Andric   LangOptions *LangOpts = &Opts;
3634af732203SDimitry Andric 
3635af732203SDimitry Andric #define LANG_OPTION_WITH_MARSHALLING(                                          \
3636af732203SDimitry Andric     PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,        \
3637af732203SDimitry Andric     HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
3638af732203SDimitry Andric     DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER,     \
3639af732203SDimitry Andric     MERGER, EXTRACTOR, TABLE_INDEX)                                            \
36405f7ddb14SDimitry Andric   PARSE_OPTION_WITH_MARSHALLING(                                               \
36415f7ddb14SDimitry Andric       Args, Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE,     \
36425f7ddb14SDimitry Andric       IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
3643af732203SDimitry Andric #include "clang/Driver/Options.inc"
3644af732203SDimitry Andric #undef LANG_OPTION_WITH_MARSHALLING
3645af732203SDimitry Andric 
3646af732203SDimitry Andric   if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
3647af732203SDimitry Andric     StringRef Name = A->getValue();
3648af732203SDimitry Andric     if (Name == "full" || Name == "branch") {
3649af732203SDimitry Andric       Opts.CFProtectionBranch = 1;
36500b57cec5SDimitry Andric     }
3651af732203SDimitry Andric   }
36520b57cec5SDimitry Andric 
36535f7ddb14SDimitry Andric   if ((Args.hasArg(OPT_fsycl_is_device) || Args.hasArg(OPT_fsycl_is_host)) &&
36545f7ddb14SDimitry Andric       !Args.hasArg(OPT_sycl_std_EQ)) {
36555f7ddb14SDimitry Andric     // If the user supplied -fsycl-is-device or -fsycl-is-host, but failed to
36565f7ddb14SDimitry Andric     // provide -sycl-std=, we want to default it to whatever the default SYCL
36575f7ddb14SDimitry Andric     // version is. I could not find a way to express this with the options
36585f7ddb14SDimitry Andric     // tablegen because we still want this value to be SYCL_None when the user
36595f7ddb14SDimitry Andric     // is not in device or host mode.
36605f7ddb14SDimitry Andric     Opts.setSYCLVersion(LangOptions::SYCL_Default);
36615f7ddb14SDimitry Andric   }
36620b57cec5SDimitry Andric 
36630b57cec5SDimitry Andric   if (Opts.ObjC) {
36640b57cec5SDimitry Andric     if (Arg *arg = Args.getLastArg(OPT_fobjc_runtime_EQ)) {
36650b57cec5SDimitry Andric       StringRef value = arg->getValue();
36660b57cec5SDimitry Andric       if (Opts.ObjCRuntime.tryParse(value))
36670b57cec5SDimitry Andric         Diags.Report(diag::err_drv_unknown_objc_runtime) << value;
36680b57cec5SDimitry Andric     }
36690b57cec5SDimitry Andric 
36700b57cec5SDimitry Andric     if (Args.hasArg(OPT_fobjc_gc_only))
36710b57cec5SDimitry Andric       Opts.setGC(LangOptions::GCOnly);
36720b57cec5SDimitry Andric     else if (Args.hasArg(OPT_fobjc_gc))
36730b57cec5SDimitry Andric       Opts.setGC(LangOptions::HybridGC);
36740b57cec5SDimitry Andric     else if (Args.hasArg(OPT_fobjc_arc)) {
36750b57cec5SDimitry Andric       Opts.ObjCAutoRefCount = 1;
36760b57cec5SDimitry Andric       if (!Opts.ObjCRuntime.allowsARC())
36770b57cec5SDimitry Andric         Diags.Report(diag::err_arc_unsupported_on_runtime);
36780b57cec5SDimitry Andric     }
36790b57cec5SDimitry Andric 
36800b57cec5SDimitry Andric     // ObjCWeakRuntime tracks whether the runtime supports __weak, not
36810b57cec5SDimitry Andric     // whether the feature is actually enabled.  This is predominantly
36820b57cec5SDimitry Andric     // determined by -fobjc-runtime, but we allow it to be overridden
36830b57cec5SDimitry Andric     // from the command line for testing purposes.
36840b57cec5SDimitry Andric     if (Args.hasArg(OPT_fobjc_runtime_has_weak))
36850b57cec5SDimitry Andric       Opts.ObjCWeakRuntime = 1;
36860b57cec5SDimitry Andric     else
36870b57cec5SDimitry Andric       Opts.ObjCWeakRuntime = Opts.ObjCRuntime.allowsWeak();
36880b57cec5SDimitry Andric 
36890b57cec5SDimitry Andric     // ObjCWeak determines whether __weak is actually enabled.
36900b57cec5SDimitry Andric     // Note that we allow -fno-objc-weak to disable this even in ARC mode.
36910b57cec5SDimitry Andric     if (auto weakArg = Args.getLastArg(OPT_fobjc_weak, OPT_fno_objc_weak)) {
36920b57cec5SDimitry Andric       if (!weakArg->getOption().matches(OPT_fobjc_weak)) {
36930b57cec5SDimitry Andric         assert(!Opts.ObjCWeak);
36940b57cec5SDimitry Andric       } else if (Opts.getGC() != LangOptions::NonGC) {
36950b57cec5SDimitry Andric         Diags.Report(diag::err_objc_weak_with_gc);
36960b57cec5SDimitry Andric       } else if (!Opts.ObjCWeakRuntime) {
36970b57cec5SDimitry Andric         Diags.Report(diag::err_objc_weak_unsupported);
36980b57cec5SDimitry Andric       } else {
36990b57cec5SDimitry Andric         Opts.ObjCWeak = 1;
37000b57cec5SDimitry Andric       }
37010b57cec5SDimitry Andric     } else if (Opts.ObjCAutoRefCount) {
37020b57cec5SDimitry Andric       Opts.ObjCWeak = Opts.ObjCWeakRuntime;
37030b57cec5SDimitry Andric     }
37040b57cec5SDimitry Andric 
37050b57cec5SDimitry Andric     if (Args.hasArg(OPT_fobjc_subscripting_legacy_runtime))
37060b57cec5SDimitry Andric       Opts.ObjCSubscriptingLegacyRuntime =
37070b57cec5SDimitry Andric         (Opts.ObjCRuntime.getKind() == ObjCRuntime::FragileMacOSX);
37080b57cec5SDimitry Andric   }
37090b57cec5SDimitry Andric 
3710a7dea167SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fgnuc_version_EQ)) {
3711a7dea167SDimitry Andric     // Check that the version has 1 to 3 components and the minor and patch
3712a7dea167SDimitry Andric     // versions fit in two decimal digits.
3713a7dea167SDimitry Andric     VersionTuple GNUCVer;
3714a7dea167SDimitry Andric     bool Invalid = GNUCVer.tryParse(A->getValue());
3715a7dea167SDimitry Andric     unsigned Major = GNUCVer.getMajor();
3716a7dea167SDimitry Andric     unsigned Minor = GNUCVer.getMinor().getValueOr(0);
3717a7dea167SDimitry Andric     unsigned Patch = GNUCVer.getSubminor().getValueOr(0);
3718a7dea167SDimitry Andric     if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) {
3719a7dea167SDimitry Andric       Diags.Report(diag::err_drv_invalid_value)
3720a7dea167SDimitry Andric           << A->getAsString(Args) << A->getValue();
3721a7dea167SDimitry Andric     }
3722a7dea167SDimitry Andric     Opts.GNUCVersion = Major * 100 * 100 + Minor * 100 + Patch;
3723a7dea167SDimitry Andric   }
3724a7dea167SDimitry Andric 
37255f7ddb14SDimitry Andric   // In AIX OS, the -mignore-xcoff-visibility is enable by default if there is
37265f7ddb14SDimitry Andric   // no -fvisibility=* option.
37275f7ddb14SDimitry Andric   // This is the reason why '-fvisibility' needs to be always generated:
37285f7ddb14SDimitry Andric   // its absence implies '-mignore-xcoff-visibility'.
37295f7ddb14SDimitry Andric   //
37305f7ddb14SDimitry Andric   // Suppose the original cc1 command line does contain '-fvisibility default':
37315f7ddb14SDimitry Andric   // '-mignore-xcoff-visibility' should not be implied.
37325f7ddb14SDimitry Andric   // * If '-fvisibility' is not generated (as most options with default values
37335f7ddb14SDimitry Andric   //   don't), its absence would imply '-mignore-xcoff-visibility'. This changes
37345f7ddb14SDimitry Andric   //   the command line semantics.
37355f7ddb14SDimitry Andric   // * If '-fvisibility' is generated regardless of its presence and value,
37365f7ddb14SDimitry Andric   //   '-mignore-xcoff-visibility' won't be implied and the command line
37375f7ddb14SDimitry Andric   //   semantics are kept intact.
37385f7ddb14SDimitry Andric   //
37395f7ddb14SDimitry Andric   // When the original cc1 command line does **not** contain '-fvisibility',
37405f7ddb14SDimitry Andric   // '-mignore-xcoff-visibility' is implied. The generated command line will
37415f7ddb14SDimitry Andric   // contain both '-fvisibility default' and '-mignore-xcoff-visibility' and
37425f7ddb14SDimitry Andric   // subsequent calls to `CreateFromArgs`/`generateCC1CommandLine` will always
37435f7ddb14SDimitry Andric   // produce the same arguments.
37445f7ddb14SDimitry Andric 
37455f7ddb14SDimitry Andric   if (T.isOSAIX() && (Args.hasArg(OPT_mignore_xcoff_visibility) ||
37465f7ddb14SDimitry Andric                       !Args.hasArg(OPT_fvisibility)))
37475f7ddb14SDimitry Andric     Opts.IgnoreXCOFFVisibility = 1;
37485f7ddb14SDimitry Andric 
37490b57cec5SDimitry Andric   if (Args.hasArg(OPT_ftrapv)) {
37500b57cec5SDimitry Andric     Opts.setSignedOverflowBehavior(LangOptions::SOB_Trapping);
37510b57cec5SDimitry Andric     // Set the handler, if one is specified.
37520b57cec5SDimitry Andric     Opts.OverflowHandler =
37535ffd83dbSDimitry Andric         std::string(Args.getLastArgValue(OPT_ftrapv_handler));
37540b57cec5SDimitry Andric   }
37550b57cec5SDimitry Andric   else if (Args.hasArg(OPT_fwrapv))
37560b57cec5SDimitry Andric     Opts.setSignedOverflowBehavior(LangOptions::SOB_Defined);
37570b57cec5SDimitry Andric 
37580b57cec5SDimitry Andric   Opts.MSCompatibilityVersion = 0;
37590b57cec5SDimitry Andric   if (const Arg *A = Args.getLastArg(OPT_fms_compatibility_version)) {
37600b57cec5SDimitry Andric     VersionTuple VT;
37610b57cec5SDimitry Andric     if (VT.tryParse(A->getValue()))
37620b57cec5SDimitry Andric       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
37630b57cec5SDimitry Andric                                                 << A->getValue();
37640b57cec5SDimitry Andric     Opts.MSCompatibilityVersion = VT.getMajor() * 10000000 +
37650b57cec5SDimitry Andric                                   VT.getMinor().getValueOr(0) * 100000 +
37660b57cec5SDimitry Andric                                   VT.getSubminor().getValueOr(0);
37670b57cec5SDimitry Andric   }
37680b57cec5SDimitry Andric 
37690b57cec5SDimitry Andric   // Mimicking gcc's behavior, trigraphs are only enabled if -trigraphs
37700b57cec5SDimitry Andric   // is specified, or -std is set to a conforming mode.
37710b57cec5SDimitry Andric   // Trigraphs are disabled by default in c++1z onwards.
3772af732203SDimitry Andric   // For z/OS, trigraphs are enabled by default (without regard to the above).
3773af732203SDimitry Andric   Opts.Trigraphs =
3774af732203SDimitry Andric       (!Opts.GNUMode && !Opts.MSVCCompat && !Opts.CPlusPlus17) || T.isOSzOS();
37750b57cec5SDimitry Andric   Opts.Trigraphs =
37760b57cec5SDimitry Andric       Args.hasFlag(OPT_ftrigraphs, OPT_fno_trigraphs, Opts.Trigraphs);
37770b57cec5SDimitry Andric 
37780b57cec5SDimitry Andric   Opts.Blocks = Args.hasArg(OPT_fblocks) || (Opts.OpenCL
37790b57cec5SDimitry Andric     && Opts.OpenCLVersion == 200);
37800b57cec5SDimitry Andric 
3781480093f4SDimitry Andric   Opts.ConvergentFunctions = Opts.OpenCL || (Opts.CUDA && Opts.CUDAIsDevice) ||
3782af732203SDimitry Andric                              Opts.SYCLIsDevice ||
3783480093f4SDimitry Andric                              Args.hasArg(OPT_fconvergent_functions);
3784480093f4SDimitry Andric 
37850b57cec5SDimitry Andric   Opts.NoBuiltin = Args.hasArg(OPT_fno_builtin) || Opts.Freestanding;
37860b57cec5SDimitry Andric   if (!Opts.NoBuiltin)
37870b57cec5SDimitry Andric     getAllNoBuiltinFuncValues(Args, Opts.NoBuiltinFuncs);
37880b57cec5SDimitry Andric   Opts.LongDoubleSize = Args.hasArg(OPT_mlong_double_128)
37890b57cec5SDimitry Andric                             ? 128
37900b57cec5SDimitry Andric                             : Args.hasArg(OPT_mlong_double_64) ? 64 : 0;
37915ffd83dbSDimitry Andric   if (Opts.FastRelaxedMath)
37925ffd83dbSDimitry Andric     Opts.setDefaultFPContractMode(LangOptions::FPM_Fast);
37930b57cec5SDimitry Andric   llvm::sort(Opts.ModuleFeatures);
3794af732203SDimitry Andric 
37950b57cec5SDimitry Andric   // -mrtd option
37960b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(OPT_mrtd)) {
37970b57cec5SDimitry Andric     if (Opts.getDefaultCallingConv() != LangOptions::DCC_None)
37980b57cec5SDimitry Andric       Diags.Report(diag::err_drv_argument_not_allowed_with)
37990b57cec5SDimitry Andric           << A->getSpelling() << "-fdefault-calling-conv";
38000b57cec5SDimitry Andric     else {
38010b57cec5SDimitry Andric       if (T.getArch() != llvm::Triple::x86)
38020b57cec5SDimitry Andric         Diags.Report(diag::err_drv_argument_not_allowed_with)
38030b57cec5SDimitry Andric             << A->getSpelling() << T.getTriple();
38040b57cec5SDimitry Andric       else
38050b57cec5SDimitry Andric         Opts.setDefaultCallingConv(LangOptions::DCC_StdCall);
38060b57cec5SDimitry Andric     }
38070b57cec5SDimitry Andric   }
38080b57cec5SDimitry Andric 
38095f7ddb14SDimitry Andric   // Check if -fopenmp is specified and set default version to 5.0.
38105f7ddb14SDimitry Andric   Opts.OpenMP = Args.hasArg(OPT_fopenmp) ? 50 : 0;
38110b57cec5SDimitry Andric   // Check if -fopenmp-simd is specified.
38120b57cec5SDimitry Andric   bool IsSimdSpecified =
38130b57cec5SDimitry Andric       Args.hasFlag(options::OPT_fopenmp_simd, options::OPT_fno_openmp_simd,
38140b57cec5SDimitry Andric                    /*Default=*/false);
38150b57cec5SDimitry Andric   Opts.OpenMPSimd = !Opts.OpenMP && IsSimdSpecified;
38160b57cec5SDimitry Andric   Opts.OpenMPUseTLS =
38170b57cec5SDimitry Andric       Opts.OpenMP && !Args.hasArg(options::OPT_fnoopenmp_use_tls);
38180b57cec5SDimitry Andric   Opts.OpenMPIsDevice =
38190b57cec5SDimitry Andric       Opts.OpenMP && Args.hasArg(options::OPT_fopenmp_is_device);
3820480093f4SDimitry Andric   Opts.OpenMPIRBuilder =
3821480093f4SDimitry Andric       Opts.OpenMP && Args.hasArg(options::OPT_fopenmp_enable_irbuilder);
38220b57cec5SDimitry Andric   bool IsTargetSpecified =
38230b57cec5SDimitry Andric       Opts.OpenMPIsDevice || Args.hasArg(options::OPT_fopenmp_targets_EQ);
38240b57cec5SDimitry Andric 
3825af732203SDimitry Andric   Opts.ConvergentFunctions = Opts.ConvergentFunctions || Opts.OpenMPIsDevice;
3826af732203SDimitry Andric 
38270b57cec5SDimitry Andric   if (Opts.OpenMP || Opts.OpenMPSimd) {
38280b57cec5SDimitry Andric     if (int Version = getLastArgIntValue(
38290b57cec5SDimitry Andric             Args, OPT_fopenmp_version_EQ,
38305ffd83dbSDimitry Andric             (IsSimdSpecified || IsTargetSpecified) ? 50 : Opts.OpenMP, Diags))
38310b57cec5SDimitry Andric       Opts.OpenMP = Version;
38320b57cec5SDimitry Andric     // Provide diagnostic when a given target is not expected to be an OpenMP
38330b57cec5SDimitry Andric     // device or host.
38340b57cec5SDimitry Andric     if (!Opts.OpenMPIsDevice) {
38350b57cec5SDimitry Andric       switch (T.getArch()) {
38360b57cec5SDimitry Andric       default:
38370b57cec5SDimitry Andric         break;
38380b57cec5SDimitry Andric       // Add unsupported host targets here:
38390b57cec5SDimitry Andric       case llvm::Triple::nvptx:
38400b57cec5SDimitry Andric       case llvm::Triple::nvptx64:
3841af732203SDimitry Andric         Diags.Report(diag::err_drv_omp_host_target_not_supported) << T.str();
38420b57cec5SDimitry Andric         break;
38430b57cec5SDimitry Andric       }
38440b57cec5SDimitry Andric     }
38450b57cec5SDimitry Andric   }
38460b57cec5SDimitry Andric 
38470b57cec5SDimitry Andric   // Set the flag to prevent the implementation from emitting device exception
38480b57cec5SDimitry Andric   // handling code for those requiring so.
38495ffd83dbSDimitry Andric   if ((Opts.OpenMPIsDevice && (T.isNVPTX() || T.isAMDGCN())) ||
38505ffd83dbSDimitry Andric       Opts.OpenCLCPlusPlus) {
38510b57cec5SDimitry Andric     Opts.Exceptions = 0;
38520b57cec5SDimitry Andric     Opts.CXXExceptions = 0;
38530b57cec5SDimitry Andric   }
38540b57cec5SDimitry Andric   if (Opts.OpenMPIsDevice && T.isNVPTX()) {
38550b57cec5SDimitry Andric     Opts.OpenMPCUDANumSMs =
38560b57cec5SDimitry Andric         getLastArgIntValue(Args, options::OPT_fopenmp_cuda_number_of_sm_EQ,
38570b57cec5SDimitry Andric                            Opts.OpenMPCUDANumSMs, Diags);
38580b57cec5SDimitry Andric     Opts.OpenMPCUDABlocksPerSM =
38590b57cec5SDimitry Andric         getLastArgIntValue(Args, options::OPT_fopenmp_cuda_blocks_per_sm_EQ,
38600b57cec5SDimitry Andric                            Opts.OpenMPCUDABlocksPerSM, Diags);
38610b57cec5SDimitry Andric     Opts.OpenMPCUDAReductionBufNum = getLastArgIntValue(
38620b57cec5SDimitry Andric         Args, options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ,
38630b57cec5SDimitry Andric         Opts.OpenMPCUDAReductionBufNum, Diags);
38640b57cec5SDimitry Andric   }
38650b57cec5SDimitry Andric 
38660b57cec5SDimitry Andric   // Get the OpenMP target triples if any.
38670b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fopenmp_targets_EQ)) {
3868af732203SDimitry Andric     enum ArchPtrSize { Arch16Bit, Arch32Bit, Arch64Bit };
3869af732203SDimitry Andric     auto getArchPtrSize = [](const llvm::Triple &T) {
3870af732203SDimitry Andric       if (T.isArch16Bit())
3871af732203SDimitry Andric         return Arch16Bit;
3872af732203SDimitry Andric       if (T.isArch32Bit())
3873af732203SDimitry Andric         return Arch32Bit;
3874af732203SDimitry Andric       assert(T.isArch64Bit() && "Expected 64-bit architecture");
3875af732203SDimitry Andric       return Arch64Bit;
3876af732203SDimitry Andric     };
38770b57cec5SDimitry Andric 
38780b57cec5SDimitry Andric     for (unsigned i = 0; i < A->getNumValues(); ++i) {
38790b57cec5SDimitry Andric       llvm::Triple TT(A->getValue(i));
38800b57cec5SDimitry Andric 
38810b57cec5SDimitry Andric       if (TT.getArch() == llvm::Triple::UnknownArch ||
3882af732203SDimitry Andric           !(TT.getArch() == llvm::Triple::aarch64 || TT.isPPC() ||
38830b57cec5SDimitry Andric             TT.getArch() == llvm::Triple::nvptx ||
38840b57cec5SDimitry Andric             TT.getArch() == llvm::Triple::nvptx64 ||
38855ffd83dbSDimitry Andric             TT.getArch() == llvm::Triple::amdgcn ||
38860b57cec5SDimitry Andric             TT.getArch() == llvm::Triple::x86 ||
38870b57cec5SDimitry Andric             TT.getArch() == llvm::Triple::x86_64))
38880b57cec5SDimitry Andric         Diags.Report(diag::err_drv_invalid_omp_target) << A->getValue(i);
3889af732203SDimitry Andric       else if (getArchPtrSize(T) != getArchPtrSize(TT))
3890af732203SDimitry Andric         Diags.Report(diag::err_drv_incompatible_omp_arch)
3891af732203SDimitry Andric             << A->getValue(i) << T.str();
38920b57cec5SDimitry Andric       else
38930b57cec5SDimitry Andric         Opts.OMPTargetTriples.push_back(TT);
38940b57cec5SDimitry Andric     }
38950b57cec5SDimitry Andric   }
38960b57cec5SDimitry Andric 
38970b57cec5SDimitry Andric   // Get OpenMP host file path if any and report if a non existent file is
38980b57cec5SDimitry Andric   // found
38990b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_fopenmp_host_ir_file_path)) {
39000b57cec5SDimitry Andric     Opts.OMPHostIRFile = A->getValue();
39010b57cec5SDimitry Andric     if (!llvm::sys::fs::exists(Opts.OMPHostIRFile))
39020b57cec5SDimitry Andric       Diags.Report(diag::err_drv_omp_host_ir_file_not_found)
39030b57cec5SDimitry Andric           << Opts.OMPHostIRFile;
39040b57cec5SDimitry Andric   }
39050b57cec5SDimitry Andric 
39065ffd83dbSDimitry Andric   // Set CUDA mode for OpenMP target NVPTX/AMDGCN if specified in options
39075ffd83dbSDimitry Andric   Opts.OpenMPCUDAMode = Opts.OpenMPIsDevice && (T.isNVPTX() || T.isAMDGCN()) &&
39080b57cec5SDimitry Andric                         Args.hasArg(options::OPT_fopenmp_cuda_mode);
39090b57cec5SDimitry Andric 
39105ffd83dbSDimitry Andric   // Set CUDA mode for OpenMP target NVPTX/AMDGCN if specified in options
39110b57cec5SDimitry Andric   Opts.OpenMPCUDAForceFullRuntime =
39125ffd83dbSDimitry Andric       Opts.OpenMPIsDevice && (T.isNVPTX() || T.isAMDGCN()) &&
39130b57cec5SDimitry Andric       Args.hasArg(options::OPT_fopenmp_cuda_force_full_runtime);
39140b57cec5SDimitry Andric 
39150b57cec5SDimitry Andric   // FIXME: Eliminate this dependency.
39160b57cec5SDimitry Andric   unsigned Opt = getOptimizationLevel(Args, IK, Diags),
39170b57cec5SDimitry Andric        OptSize = getOptimizationLevelSize(Args);
39180b57cec5SDimitry Andric   Opts.Optimize = Opt != 0;
39190b57cec5SDimitry Andric   Opts.OptimizeSize = OptSize != 0;
39200b57cec5SDimitry Andric 
39210b57cec5SDimitry Andric   // This is the __NO_INLINE__ define, which just depends on things like the
39220b57cec5SDimitry Andric   // optimization level and -fno-inline, not actually whether the backend has
39230b57cec5SDimitry Andric   // inlining enabled.
39240b57cec5SDimitry Andric   Opts.NoInlineDefine = !Opts.Optimize;
39250b57cec5SDimitry Andric   if (Arg *InlineArg = Args.getLastArg(
39260b57cec5SDimitry Andric           options::OPT_finline_functions, options::OPT_finline_hint_functions,
39270b57cec5SDimitry Andric           options::OPT_fno_inline_functions, options::OPT_fno_inline))
39280b57cec5SDimitry Andric     if (InlineArg->getOption().matches(options::OPT_fno_inline))
39290b57cec5SDimitry Andric       Opts.NoInlineDefine = true;
39300b57cec5SDimitry Andric 
39310b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(OPT_ffp_contract)) {
39320b57cec5SDimitry Andric     StringRef Val = A->getValue();
39330b57cec5SDimitry Andric     if (Val == "fast")
39345ffd83dbSDimitry Andric       Opts.setDefaultFPContractMode(LangOptions::FPM_Fast);
39350b57cec5SDimitry Andric     else if (Val == "on")
39365ffd83dbSDimitry Andric       Opts.setDefaultFPContractMode(LangOptions::FPM_On);
39370b57cec5SDimitry Andric     else if (Val == "off")
39385ffd83dbSDimitry Andric       Opts.setDefaultFPContractMode(LangOptions::FPM_Off);
3939af732203SDimitry Andric     else if (Val == "fast-honor-pragmas")
3940af732203SDimitry Andric       Opts.setDefaultFPContractMode(LangOptions::FPM_FastHonorPragmas);
39410b57cec5SDimitry Andric     else
39420b57cec5SDimitry Andric       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
39430b57cec5SDimitry Andric   }
39440b57cec5SDimitry Andric 
39450b57cec5SDimitry Andric   // Parse -fsanitize= arguments.
39460b57cec5SDimitry Andric   parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ),
39470b57cec5SDimitry Andric                       Diags, Opts.Sanitize);
39485f7ddb14SDimitry Andric   Opts.NoSanitizeFiles = Args.getAllArgValues(OPT_fsanitize_ignorelist_EQ);
39495f7ddb14SDimitry Andric   std::vector<std::string> systemIgnorelists =
39505f7ddb14SDimitry Andric       Args.getAllArgValues(OPT_fsanitize_system_ignorelist_EQ);
39515f7ddb14SDimitry Andric   Opts.NoSanitizeFiles.insert(Opts.NoSanitizeFiles.end(),
39525f7ddb14SDimitry Andric                               systemIgnorelists.begin(),
39535f7ddb14SDimitry Andric                               systemIgnorelists.end());
39540b57cec5SDimitry Andric 
39550b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(OPT_fclang_abi_compat_EQ)) {
39560b57cec5SDimitry Andric     Opts.setClangABICompat(LangOptions::ClangABI::Latest);
39570b57cec5SDimitry Andric 
39580b57cec5SDimitry Andric     StringRef Ver = A->getValue();
39590b57cec5SDimitry Andric     std::pair<StringRef, StringRef> VerParts = Ver.split('.');
39600b57cec5SDimitry Andric     unsigned Major, Minor = 0;
39610b57cec5SDimitry Andric 
39620b57cec5SDimitry Andric     // Check the version number is valid: either 3.x (0 <= x <= 9) or
39630b57cec5SDimitry Andric     // y or y.0 (4 <= y <= current version).
39640b57cec5SDimitry Andric     if (!VerParts.first.startswith("0") &&
39650b57cec5SDimitry Andric         !VerParts.first.getAsInteger(10, Major) &&
39660b57cec5SDimitry Andric         3 <= Major && Major <= CLANG_VERSION_MAJOR &&
39670b57cec5SDimitry Andric         (Major == 3 ? VerParts.second.size() == 1 &&
39680b57cec5SDimitry Andric                       !VerParts.second.getAsInteger(10, Minor)
39690b57cec5SDimitry Andric                     : VerParts.first.size() == Ver.size() ||
39700b57cec5SDimitry Andric                       VerParts.second == "0")) {
39710b57cec5SDimitry Andric       // Got a valid version number.
39720b57cec5SDimitry Andric       if (Major == 3 && Minor <= 8)
39730b57cec5SDimitry Andric         Opts.setClangABICompat(LangOptions::ClangABI::Ver3_8);
39740b57cec5SDimitry Andric       else if (Major <= 4)
39750b57cec5SDimitry Andric         Opts.setClangABICompat(LangOptions::ClangABI::Ver4);
39760b57cec5SDimitry Andric       else if (Major <= 6)
39770b57cec5SDimitry Andric         Opts.setClangABICompat(LangOptions::ClangABI::Ver6);
39780b57cec5SDimitry Andric       else if (Major <= 7)
39790b57cec5SDimitry Andric         Opts.setClangABICompat(LangOptions::ClangABI::Ver7);
3980a7dea167SDimitry Andric       else if (Major <= 9)
3981a7dea167SDimitry Andric         Opts.setClangABICompat(LangOptions::ClangABI::Ver9);
3982af732203SDimitry Andric       else if (Major <= 11)
3983af732203SDimitry Andric         Opts.setClangABICompat(LangOptions::ClangABI::Ver11);
39845f7ddb14SDimitry Andric       else if (Major <= 12)
39855f7ddb14SDimitry Andric         Opts.setClangABICompat(LangOptions::ClangABI::Ver12);
39860b57cec5SDimitry Andric     } else if (Ver != "latest") {
39870b57cec5SDimitry Andric       Diags.Report(diag::err_drv_invalid_value)
39880b57cec5SDimitry Andric           << A->getAsString(Args) << A->getValue();
39890b57cec5SDimitry Andric     }
39900b57cec5SDimitry Andric   }
39910b57cec5SDimitry Andric 
39925ffd83dbSDimitry Andric   if (Arg *A = Args.getLastArg(OPT_msign_return_address_EQ)) {
39935ffd83dbSDimitry Andric     StringRef SignScope = A->getValue();
39945ffd83dbSDimitry Andric 
39955f7ddb14SDimitry Andric     if (SignScope.equals_insensitive("none"))
39965ffd83dbSDimitry Andric       Opts.setSignReturnAddressScope(
39975ffd83dbSDimitry Andric           LangOptions::SignReturnAddressScopeKind::None);
39985f7ddb14SDimitry Andric     else if (SignScope.equals_insensitive("all"))
39995ffd83dbSDimitry Andric       Opts.setSignReturnAddressScope(
40005ffd83dbSDimitry Andric           LangOptions::SignReturnAddressScopeKind::All);
40015f7ddb14SDimitry Andric     else if (SignScope.equals_insensitive("non-leaf"))
40025ffd83dbSDimitry Andric       Opts.setSignReturnAddressScope(
40035ffd83dbSDimitry Andric           LangOptions::SignReturnAddressScopeKind::NonLeaf);
40045ffd83dbSDimitry Andric     else
40055ffd83dbSDimitry Andric       Diags.Report(diag::err_drv_invalid_value)
40065ffd83dbSDimitry Andric           << A->getAsString(Args) << SignScope;
40075ffd83dbSDimitry Andric 
40085ffd83dbSDimitry Andric     if (Arg *A = Args.getLastArg(OPT_msign_return_address_key_EQ)) {
40095ffd83dbSDimitry Andric       StringRef SignKey = A->getValue();
40105ffd83dbSDimitry Andric       if (!SignScope.empty() && !SignKey.empty()) {
40115f7ddb14SDimitry Andric         if (SignKey.equals_insensitive("a_key"))
40125ffd83dbSDimitry Andric           Opts.setSignReturnAddressKey(
40135ffd83dbSDimitry Andric               LangOptions::SignReturnAddressKeyKind::AKey);
40145f7ddb14SDimitry Andric         else if (SignKey.equals_insensitive("b_key"))
40155ffd83dbSDimitry Andric           Opts.setSignReturnAddressKey(
40165ffd83dbSDimitry Andric               LangOptions::SignReturnAddressKeyKind::BKey);
40175ffd83dbSDimitry Andric         else
40185ffd83dbSDimitry Andric           Diags.Report(diag::err_drv_invalid_value)
40195ffd83dbSDimitry Andric               << A->getAsString(Args) << SignKey;
40205ffd83dbSDimitry Andric       }
40215ffd83dbSDimitry Andric     }
40225ffd83dbSDimitry Andric   }
40235ffd83dbSDimitry Andric 
40245f7ddb14SDimitry Andric   // The value can be empty, which indicates the system default should be used.
40255f7ddb14SDimitry Andric   StringRef CXXABI = Args.getLastArgValue(OPT_fcxx_abi_EQ);
40265f7ddb14SDimitry Andric   if (!CXXABI.empty()) {
40275f7ddb14SDimitry Andric     if (!TargetCXXABI::isABI(CXXABI)) {
40285f7ddb14SDimitry Andric       Diags.Report(diag::err_invalid_cxx_abi) << CXXABI;
40295f7ddb14SDimitry Andric     } else {
40305f7ddb14SDimitry Andric       auto Kind = TargetCXXABI::getKind(CXXABI);
40315f7ddb14SDimitry Andric       if (!TargetCXXABI::isSupportedCXXABI(T, Kind))
40325f7ddb14SDimitry Andric         Diags.Report(diag::err_unsupported_cxx_abi) << CXXABI << T.str();
40335f7ddb14SDimitry Andric       else
40345f7ddb14SDimitry Andric         Opts.CXXABI = Kind;
40355f7ddb14SDimitry Andric     }
40365f7ddb14SDimitry Andric   }
40375f7ddb14SDimitry Andric 
40385f7ddb14SDimitry Andric   Opts.RelativeCXXABIVTables =
40395f7ddb14SDimitry Andric       Args.hasFlag(options::OPT_fexperimental_relative_cxx_abi_vtables,
40405f7ddb14SDimitry Andric                    options::OPT_fno_experimental_relative_cxx_abi_vtables,
40415f7ddb14SDimitry Andric                    TargetCXXABI::usesRelativeVTables(T));
40425f7ddb14SDimitry Andric 
4043*2e2f8eacSDimitry Andric   for (const auto &A : Args.getAllArgValues(OPT_fmacro_prefix_map_EQ)) {
4044*2e2f8eacSDimitry Andric     auto Split = StringRef(A).split('=');
4045*2e2f8eacSDimitry Andric     Opts.MacroPrefixMap.insert(
4046*2e2f8eacSDimitry Andric         {std::string(Split.first), std::string(Split.second)});
4047*2e2f8eacSDimitry Andric   }
4048*2e2f8eacSDimitry Andric 
40495f7ddb14SDimitry Andric   return Diags.getNumErrors() == NumErrorsBefore;
40500b57cec5SDimitry Andric }
40510b57cec5SDimitry Andric 
isStrictlyPreprocessorAction(frontend::ActionKind Action)40520b57cec5SDimitry Andric static bool isStrictlyPreprocessorAction(frontend::ActionKind Action) {
40530b57cec5SDimitry Andric   switch (Action) {
40540b57cec5SDimitry Andric   case frontend::ASTDeclList:
40550b57cec5SDimitry Andric   case frontend::ASTDump:
40560b57cec5SDimitry Andric   case frontend::ASTPrint:
40570b57cec5SDimitry Andric   case frontend::ASTView:
40580b57cec5SDimitry Andric   case frontend::EmitAssembly:
40590b57cec5SDimitry Andric   case frontend::EmitBC:
40600b57cec5SDimitry Andric   case frontend::EmitHTML:
40610b57cec5SDimitry Andric   case frontend::EmitLLVM:
40620b57cec5SDimitry Andric   case frontend::EmitLLVMOnly:
40630b57cec5SDimitry Andric   case frontend::EmitCodeGenOnly:
40640b57cec5SDimitry Andric   case frontend::EmitObj:
40650b57cec5SDimitry Andric   case frontend::FixIt:
40660b57cec5SDimitry Andric   case frontend::GenerateModule:
40670b57cec5SDimitry Andric   case frontend::GenerateModuleInterface:
40680b57cec5SDimitry Andric   case frontend::GenerateHeaderModule:
40690b57cec5SDimitry Andric   case frontend::GeneratePCH:
40705ffd83dbSDimitry Andric   case frontend::GenerateInterfaceStubs:
40710b57cec5SDimitry Andric   case frontend::ParseSyntaxOnly:
40720b57cec5SDimitry Andric   case frontend::ModuleFileInfo:
40730b57cec5SDimitry Andric   case frontend::VerifyPCH:
40740b57cec5SDimitry Andric   case frontend::PluginAction:
40750b57cec5SDimitry Andric   case frontend::RewriteObjC:
40760b57cec5SDimitry Andric   case frontend::RewriteTest:
40770b57cec5SDimitry Andric   case frontend::RunAnalysis:
40780b57cec5SDimitry Andric   case frontend::TemplightDump:
40790b57cec5SDimitry Andric   case frontend::MigrateSource:
40800b57cec5SDimitry Andric     return false;
40810b57cec5SDimitry Andric 
40820b57cec5SDimitry Andric   case frontend::DumpCompilerOptions:
40830b57cec5SDimitry Andric   case frontend::DumpRawTokens:
40840b57cec5SDimitry Andric   case frontend::DumpTokens:
40850b57cec5SDimitry Andric   case frontend::InitOnly:
40860b57cec5SDimitry Andric   case frontend::PrintPreamble:
40870b57cec5SDimitry Andric   case frontend::PrintPreprocessedInput:
40880b57cec5SDimitry Andric   case frontend::RewriteMacros:
40890b57cec5SDimitry Andric   case frontend::RunPreprocessorOnly:
40900b57cec5SDimitry Andric   case frontend::PrintDependencyDirectivesSourceMinimizerOutput:
40910b57cec5SDimitry Andric     return true;
40920b57cec5SDimitry Andric   }
40930b57cec5SDimitry Andric   llvm_unreachable("invalid frontend action");
40940b57cec5SDimitry Andric }
40950b57cec5SDimitry Andric 
GeneratePreprocessorArgs(PreprocessorOptions & Opts,SmallVectorImpl<const char * > & Args,CompilerInvocation::StringAllocator SA,const LangOptions & LangOpts,const FrontendOptions & FrontendOpts,const CodeGenOptions & CodeGenOpts)40965f7ddb14SDimitry Andric static void GeneratePreprocessorArgs(PreprocessorOptions &Opts,
40975f7ddb14SDimitry Andric                                      SmallVectorImpl<const char *> &Args,
40985f7ddb14SDimitry Andric                                      CompilerInvocation::StringAllocator SA,
40995f7ddb14SDimitry Andric                                      const LangOptions &LangOpts,
41005f7ddb14SDimitry Andric                                      const FrontendOptions &FrontendOpts,
41015f7ddb14SDimitry Andric                                      const CodeGenOptions &CodeGenOpts) {
41025f7ddb14SDimitry Andric   PreprocessorOptions *PreprocessorOpts = &Opts;
41035f7ddb14SDimitry Andric 
41045f7ddb14SDimitry Andric #define PREPROCESSOR_OPTION_WITH_MARSHALLING(                                  \
41055f7ddb14SDimitry Andric     PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,        \
41065f7ddb14SDimitry Andric     HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
41075f7ddb14SDimitry Andric     DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER,     \
41085f7ddb14SDimitry Andric     MERGER, EXTRACTOR, TABLE_INDEX)                                            \
41095f7ddb14SDimitry Andric   GENERATE_OPTION_WITH_MARSHALLING(                                            \
41105f7ddb14SDimitry Andric       Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE,    \
41115f7ddb14SDimitry Andric       IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
41125f7ddb14SDimitry Andric #include "clang/Driver/Options.inc"
41135f7ddb14SDimitry Andric #undef PREPROCESSOR_OPTION_WITH_MARSHALLING
41145f7ddb14SDimitry Andric 
41155f7ddb14SDimitry Andric   if (Opts.PCHWithHdrStop && !Opts.PCHWithHdrStopCreate)
41165f7ddb14SDimitry Andric     GenerateArg(Args, OPT_pch_through_hdrstop_use, SA);
41175f7ddb14SDimitry Andric 
41185f7ddb14SDimitry Andric   for (const auto &D : Opts.DeserializedPCHDeclsToErrorOn)
41195f7ddb14SDimitry Andric     GenerateArg(Args, OPT_error_on_deserialized_pch_decl, D, SA);
41205f7ddb14SDimitry Andric 
41215f7ddb14SDimitry Andric   if (Opts.PrecompiledPreambleBytes != std::make_pair(0u, false))
41225f7ddb14SDimitry Andric     GenerateArg(Args, OPT_preamble_bytes_EQ,
41235f7ddb14SDimitry Andric                 Twine(Opts.PrecompiledPreambleBytes.first) + "," +
41245f7ddb14SDimitry Andric                     (Opts.PrecompiledPreambleBytes.second ? "1" : "0"),
41255f7ddb14SDimitry Andric                 SA);
41265f7ddb14SDimitry Andric 
41275f7ddb14SDimitry Andric   for (const auto &M : Opts.Macros) {
41285f7ddb14SDimitry Andric     // Don't generate __CET__ macro definitions. They are implied by the
41295f7ddb14SDimitry Andric     // -fcf-protection option that is generated elsewhere.
41305f7ddb14SDimitry Andric     if (M.first == "__CET__=1" && !M.second &&
41315f7ddb14SDimitry Andric         !CodeGenOpts.CFProtectionReturn && CodeGenOpts.CFProtectionBranch)
41325f7ddb14SDimitry Andric       continue;
41335f7ddb14SDimitry Andric     if (M.first == "__CET__=2" && !M.second && CodeGenOpts.CFProtectionReturn &&
41345f7ddb14SDimitry Andric         !CodeGenOpts.CFProtectionBranch)
41355f7ddb14SDimitry Andric       continue;
41365f7ddb14SDimitry Andric     if (M.first == "__CET__=3" && !M.second && CodeGenOpts.CFProtectionReturn &&
41375f7ddb14SDimitry Andric         CodeGenOpts.CFProtectionBranch)
41385f7ddb14SDimitry Andric       continue;
41395f7ddb14SDimitry Andric 
41405f7ddb14SDimitry Andric     GenerateArg(Args, M.second ? OPT_U : OPT_D, M.first, SA);
41415f7ddb14SDimitry Andric   }
41425f7ddb14SDimitry Andric 
41435f7ddb14SDimitry Andric   for (const auto &I : Opts.Includes) {
41445f7ddb14SDimitry Andric     // Don't generate OpenCL includes. They are implied by other flags that are
41455f7ddb14SDimitry Andric     // generated elsewhere.
41465f7ddb14SDimitry Andric     if (LangOpts.OpenCL && LangOpts.IncludeDefaultHeader &&
41475f7ddb14SDimitry Andric         ((LangOpts.DeclareOpenCLBuiltins && I == "opencl-c-base.h") ||
41485f7ddb14SDimitry Andric          I == "opencl-c.h"))
41495f7ddb14SDimitry Andric       continue;
41505f7ddb14SDimitry Andric 
41515f7ddb14SDimitry Andric     GenerateArg(Args, OPT_include, I, SA);
41525f7ddb14SDimitry Andric   }
41535f7ddb14SDimitry Andric 
41545f7ddb14SDimitry Andric   for (const auto &CI : Opts.ChainedIncludes)
41555f7ddb14SDimitry Andric     GenerateArg(Args, OPT_chain_include, CI, SA);
41565f7ddb14SDimitry Andric 
41575f7ddb14SDimitry Andric   for (const auto &RF : Opts.RemappedFiles)
41585f7ddb14SDimitry Andric     GenerateArg(Args, OPT_remap_file, RF.first + ";" + RF.second, SA);
41595f7ddb14SDimitry Andric 
41605f7ddb14SDimitry Andric   // Don't handle LexEditorPlaceholders. It is implied by the action that is
41615f7ddb14SDimitry Andric   // generated elsewhere.
41625f7ddb14SDimitry Andric }
41635f7ddb14SDimitry Andric 
ParsePreprocessorArgs(PreprocessorOptions & Opts,ArgList & Args,DiagnosticsEngine & Diags,frontend::ActionKind Action,const FrontendOptions & FrontendOpts)41645f7ddb14SDimitry Andric static bool ParsePreprocessorArgs(PreprocessorOptions &Opts, ArgList &Args,
41650b57cec5SDimitry Andric                                   DiagnosticsEngine &Diags,
41665f7ddb14SDimitry Andric                                   frontend::ActionKind Action,
41675f7ddb14SDimitry Andric                                   const FrontendOptions &FrontendOpts) {
41685f7ddb14SDimitry Andric   unsigned NumErrorsBefore = Diags.getNumErrors();
41695f7ddb14SDimitry Andric 
41705f7ddb14SDimitry Andric   PreprocessorOptions *PreprocessorOpts = &Opts;
41715f7ddb14SDimitry Andric 
41725f7ddb14SDimitry Andric #define PREPROCESSOR_OPTION_WITH_MARSHALLING(                                  \
41735f7ddb14SDimitry Andric     PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,        \
41745f7ddb14SDimitry Andric     HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
41755f7ddb14SDimitry Andric     DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER,     \
41765f7ddb14SDimitry Andric     MERGER, EXTRACTOR, TABLE_INDEX)                                            \
41775f7ddb14SDimitry Andric   PARSE_OPTION_WITH_MARSHALLING(                                               \
41785f7ddb14SDimitry Andric       Args, Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE,     \
41795f7ddb14SDimitry Andric       IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
41805f7ddb14SDimitry Andric #include "clang/Driver/Options.inc"
41815f7ddb14SDimitry Andric #undef PREPROCESSOR_OPTION_WITH_MARSHALLING
41825f7ddb14SDimitry Andric 
41830b57cec5SDimitry Andric   Opts.PCHWithHdrStop = Args.hasArg(OPT_pch_through_hdrstop_create) ||
41840b57cec5SDimitry Andric                         Args.hasArg(OPT_pch_through_hdrstop_use);
41850b57cec5SDimitry Andric 
41860b57cec5SDimitry Andric   for (const auto *A : Args.filtered(OPT_error_on_deserialized_pch_decl))
41870b57cec5SDimitry Andric     Opts.DeserializedPCHDeclsToErrorOn.insert(A->getValue());
41880b57cec5SDimitry Andric 
41890b57cec5SDimitry Andric   if (const Arg *A = Args.getLastArg(OPT_preamble_bytes_EQ)) {
41900b57cec5SDimitry Andric     StringRef Value(A->getValue());
41910b57cec5SDimitry Andric     size_t Comma = Value.find(',');
41920b57cec5SDimitry Andric     unsigned Bytes = 0;
41930b57cec5SDimitry Andric     unsigned EndOfLine = 0;
41940b57cec5SDimitry Andric 
41950b57cec5SDimitry Andric     if (Comma == StringRef::npos ||
41960b57cec5SDimitry Andric         Value.substr(0, Comma).getAsInteger(10, Bytes) ||
41970b57cec5SDimitry Andric         Value.substr(Comma + 1).getAsInteger(10, EndOfLine))
41980b57cec5SDimitry Andric       Diags.Report(diag::err_drv_preamble_format);
41990b57cec5SDimitry Andric     else {
42000b57cec5SDimitry Andric       Opts.PrecompiledPreambleBytes.first = Bytes;
42010b57cec5SDimitry Andric       Opts.PrecompiledPreambleBytes.second = (EndOfLine != 0);
42020b57cec5SDimitry Andric     }
42030b57cec5SDimitry Andric   }
42040b57cec5SDimitry Andric 
42050b57cec5SDimitry Andric   // Add the __CET__ macro if a CFProtection option is set.
42060b57cec5SDimitry Andric   if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
42070b57cec5SDimitry Andric     StringRef Name = A->getValue();
42080b57cec5SDimitry Andric     if (Name == "branch")
42090b57cec5SDimitry Andric       Opts.addMacroDef("__CET__=1");
42100b57cec5SDimitry Andric     else if (Name == "return")
42110b57cec5SDimitry Andric       Opts.addMacroDef("__CET__=2");
42120b57cec5SDimitry Andric     else if (Name == "full")
42130b57cec5SDimitry Andric       Opts.addMacroDef("__CET__=3");
42140b57cec5SDimitry Andric   }
42150b57cec5SDimitry Andric 
42160b57cec5SDimitry Andric   // Add macros from the command line.
42170b57cec5SDimitry Andric   for (const auto *A : Args.filtered(OPT_D, OPT_U)) {
42180b57cec5SDimitry Andric     if (A->getOption().matches(OPT_D))
42190b57cec5SDimitry Andric       Opts.addMacroDef(A->getValue());
42200b57cec5SDimitry Andric     else
42210b57cec5SDimitry Andric       Opts.addMacroUndef(A->getValue());
42220b57cec5SDimitry Andric   }
42230b57cec5SDimitry Andric 
42240b57cec5SDimitry Andric   // Add the ordered list of -includes.
42250b57cec5SDimitry Andric   for (const auto *A : Args.filtered(OPT_include))
42260b57cec5SDimitry Andric     Opts.Includes.emplace_back(A->getValue());
42270b57cec5SDimitry Andric 
42280b57cec5SDimitry Andric   for (const auto *A : Args.filtered(OPT_chain_include))
42290b57cec5SDimitry Andric     Opts.ChainedIncludes.emplace_back(A->getValue());
42300b57cec5SDimitry Andric 
42310b57cec5SDimitry Andric   for (const auto *A : Args.filtered(OPT_remap_file)) {
42320b57cec5SDimitry Andric     std::pair<StringRef, StringRef> Split = StringRef(A->getValue()).split(';');
42330b57cec5SDimitry Andric 
42340b57cec5SDimitry Andric     if (Split.second.empty()) {
42350b57cec5SDimitry Andric       Diags.Report(diag::err_drv_invalid_remap_file) << A->getAsString(Args);
42360b57cec5SDimitry Andric       continue;
42370b57cec5SDimitry Andric     }
42380b57cec5SDimitry Andric 
42390b57cec5SDimitry Andric     Opts.addRemappedFile(Split.first, Split.second);
42400b57cec5SDimitry Andric   }
42410b57cec5SDimitry Andric 
42420b57cec5SDimitry Andric   // Always avoid lexing editor placeholders when we're just running the
42430b57cec5SDimitry Andric   // preprocessor as we never want to emit the
42440b57cec5SDimitry Andric   // "editor placeholder in source file" error in PP only mode.
42450b57cec5SDimitry Andric   if (isStrictlyPreprocessorAction(Action))
42460b57cec5SDimitry Andric     Opts.LexEditorPlaceholders = false;
42475f7ddb14SDimitry Andric 
42485f7ddb14SDimitry Andric   return Diags.getNumErrors() == NumErrorsBefore;
42490b57cec5SDimitry Andric }
42500b57cec5SDimitry Andric 
GeneratePreprocessorOutputArgs(const PreprocessorOutputOptions & Opts,SmallVectorImpl<const char * > & Args,CompilerInvocation::StringAllocator SA,frontend::ActionKind Action)42515f7ddb14SDimitry Andric static void GeneratePreprocessorOutputArgs(
42525f7ddb14SDimitry Andric     const PreprocessorOutputOptions &Opts, SmallVectorImpl<const char *> &Args,
42535f7ddb14SDimitry Andric     CompilerInvocation::StringAllocator SA, frontend::ActionKind Action) {
42545f7ddb14SDimitry Andric   const PreprocessorOutputOptions &PreprocessorOutputOpts = Opts;
42555f7ddb14SDimitry Andric 
42565f7ddb14SDimitry Andric #define PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING(                           \
42575f7ddb14SDimitry Andric     PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,        \
42585f7ddb14SDimitry Andric     HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
42595f7ddb14SDimitry Andric     DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER,     \
42605f7ddb14SDimitry Andric     MERGER, EXTRACTOR, TABLE_INDEX)                                            \
42615f7ddb14SDimitry Andric   GENERATE_OPTION_WITH_MARSHALLING(                                            \
42625f7ddb14SDimitry Andric       Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE,    \
42635f7ddb14SDimitry Andric       IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
42645f7ddb14SDimitry Andric #include "clang/Driver/Options.inc"
42655f7ddb14SDimitry Andric #undef PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING
42665f7ddb14SDimitry Andric 
42675f7ddb14SDimitry Andric   bool Generate_dM = isStrictlyPreprocessorAction(Action) && !Opts.ShowCPP;
42685f7ddb14SDimitry Andric   if (Generate_dM)
42695f7ddb14SDimitry Andric     GenerateArg(Args, OPT_dM, SA);
42705f7ddb14SDimitry Andric   if (!Generate_dM && Opts.ShowMacros)
42715f7ddb14SDimitry Andric     GenerateArg(Args, OPT_dD, SA);
42725f7ddb14SDimitry Andric }
42735f7ddb14SDimitry Andric 
ParsePreprocessorOutputArgs(PreprocessorOutputOptions & Opts,ArgList & Args,DiagnosticsEngine & Diags,frontend::ActionKind Action)42745f7ddb14SDimitry Andric static bool ParsePreprocessorOutputArgs(PreprocessorOutputOptions &Opts,
42755f7ddb14SDimitry Andric                                         ArgList &Args, DiagnosticsEngine &Diags,
42760b57cec5SDimitry Andric                                         frontend::ActionKind Action) {
42775f7ddb14SDimitry Andric   unsigned NumErrorsBefore = Diags.getNumErrors();
42780b57cec5SDimitry Andric 
42795f7ddb14SDimitry Andric   PreprocessorOutputOptions &PreprocessorOutputOpts = Opts;
42805f7ddb14SDimitry Andric 
42815f7ddb14SDimitry Andric #define PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING(                           \
42825f7ddb14SDimitry Andric     PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,        \
42835f7ddb14SDimitry Andric     HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
42845f7ddb14SDimitry Andric     DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER,     \
42855f7ddb14SDimitry Andric     MERGER, EXTRACTOR, TABLE_INDEX)                                            \
42865f7ddb14SDimitry Andric   PARSE_OPTION_WITH_MARSHALLING(                                               \
42875f7ddb14SDimitry Andric       Args, Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE,     \
42885f7ddb14SDimitry Andric       IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
42895f7ddb14SDimitry Andric #include "clang/Driver/Options.inc"
42905f7ddb14SDimitry Andric #undef PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING
42915f7ddb14SDimitry Andric 
42925f7ddb14SDimitry Andric   Opts.ShowCPP = isStrictlyPreprocessorAction(Action) && !Args.hasArg(OPT_dM);
42930b57cec5SDimitry Andric   Opts.ShowMacros = Args.hasArg(OPT_dM) || Args.hasArg(OPT_dD);
42945f7ddb14SDimitry Andric 
42955f7ddb14SDimitry Andric   return Diags.getNumErrors() == NumErrorsBefore;
42960b57cec5SDimitry Andric }
42970b57cec5SDimitry Andric 
GenerateTargetArgs(const TargetOptions & Opts,SmallVectorImpl<const char * > & Args,CompilerInvocation::StringAllocator SA)42985f7ddb14SDimitry Andric static void GenerateTargetArgs(const TargetOptions &Opts,
42995f7ddb14SDimitry Andric                                SmallVectorImpl<const char *> &Args,
43005f7ddb14SDimitry Andric                                CompilerInvocation::StringAllocator SA) {
43015f7ddb14SDimitry Andric   const TargetOptions *TargetOpts = &Opts;
43025f7ddb14SDimitry Andric #define TARGET_OPTION_WITH_MARSHALLING(                                        \
43035f7ddb14SDimitry Andric     PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,        \
43045f7ddb14SDimitry Andric     HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
43055f7ddb14SDimitry Andric     DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER,     \
43065f7ddb14SDimitry Andric     MERGER, EXTRACTOR, TABLE_INDEX)                                            \
43075f7ddb14SDimitry Andric   GENERATE_OPTION_WITH_MARSHALLING(                                            \
43085f7ddb14SDimitry Andric       Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE,    \
43095f7ddb14SDimitry Andric       IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
43105f7ddb14SDimitry Andric #include "clang/Driver/Options.inc"
43115f7ddb14SDimitry Andric #undef TARGET_OPTION_WITH_MARSHALLING
43125f7ddb14SDimitry Andric 
43135f7ddb14SDimitry Andric   if (!Opts.SDKVersion.empty())
43145f7ddb14SDimitry Andric     GenerateArg(Args, OPT_target_sdk_version_EQ, Opts.SDKVersion.getAsString(),
43155f7ddb14SDimitry Andric                 SA);
43165f7ddb14SDimitry Andric }
43175f7ddb14SDimitry Andric 
ParseTargetArgs(TargetOptions & Opts,ArgList & Args,DiagnosticsEngine & Diags)43185f7ddb14SDimitry Andric static bool ParseTargetArgs(TargetOptions &Opts, ArgList &Args,
43190b57cec5SDimitry Andric                             DiagnosticsEngine &Diags) {
43205f7ddb14SDimitry Andric   unsigned NumErrorsBefore = Diags.getNumErrors();
43215f7ddb14SDimitry Andric 
43225f7ddb14SDimitry Andric   TargetOptions *TargetOpts = &Opts;
43235f7ddb14SDimitry Andric 
43245f7ddb14SDimitry Andric #define TARGET_OPTION_WITH_MARSHALLING(                                        \
43255f7ddb14SDimitry Andric     PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,        \
43265f7ddb14SDimitry Andric     HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
43275f7ddb14SDimitry Andric     DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER,     \
43285f7ddb14SDimitry Andric     MERGER, EXTRACTOR, TABLE_INDEX)                                            \
43295f7ddb14SDimitry Andric   PARSE_OPTION_WITH_MARSHALLING(                                               \
43305f7ddb14SDimitry Andric       Args, Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE,     \
43315f7ddb14SDimitry Andric       IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
43325f7ddb14SDimitry Andric #include "clang/Driver/Options.inc"
43335f7ddb14SDimitry Andric #undef TARGET_OPTION_WITH_MARSHALLING
43345f7ddb14SDimitry Andric 
43350b57cec5SDimitry Andric   if (Arg *A = Args.getLastArg(options::OPT_target_sdk_version_EQ)) {
43360b57cec5SDimitry Andric     llvm::VersionTuple Version;
43370b57cec5SDimitry Andric     if (Version.tryParse(A->getValue()))
43380b57cec5SDimitry Andric       Diags.Report(diag::err_drv_invalid_value)
43390b57cec5SDimitry Andric           << A->getAsString(Args) << A->getValue();
43400b57cec5SDimitry Andric     else
43410b57cec5SDimitry Andric       Opts.SDKVersion = Version;
43420b57cec5SDimitry Andric   }
43435f7ddb14SDimitry Andric 
43445f7ddb14SDimitry Andric   return Diags.getNumErrors() == NumErrorsBefore;
43450b57cec5SDimitry Andric }
43460b57cec5SDimitry Andric 
CreateFromArgsImpl(CompilerInvocation & Res,ArrayRef<const char * > CommandLineArgs,DiagnosticsEngine & Diags,const char * Argv0)43475f7ddb14SDimitry Andric bool CompilerInvocation::CreateFromArgsImpl(
43485f7ddb14SDimitry Andric     CompilerInvocation &Res, ArrayRef<const char *> CommandLineArgs,
43495f7ddb14SDimitry Andric     DiagnosticsEngine &Diags, const char *Argv0) {
43505f7ddb14SDimitry Andric   unsigned NumErrorsBefore = Diags.getNumErrors();
43510b57cec5SDimitry Andric 
43520b57cec5SDimitry Andric   // Parse the arguments.
4353a7dea167SDimitry Andric   const OptTable &Opts = getDriverOptTable();
43540b57cec5SDimitry Andric   const unsigned IncludedFlagsBitmask = options::CC1Option;
43550b57cec5SDimitry Andric   unsigned MissingArgIndex, MissingArgCount;
4356a7dea167SDimitry Andric   InputArgList Args = Opts.ParseArgs(CommandLineArgs, MissingArgIndex,
43570b57cec5SDimitry Andric                                      MissingArgCount, IncludedFlagsBitmask);
43580b57cec5SDimitry Andric   LangOptions &LangOpts = *Res.getLangOpts();
43590b57cec5SDimitry Andric 
43600b57cec5SDimitry Andric   // Check for missing argument error.
43615f7ddb14SDimitry Andric   if (MissingArgCount)
43620b57cec5SDimitry Andric     Diags.Report(diag::err_drv_missing_argument)
43630b57cec5SDimitry Andric         << Args.getArgString(MissingArgIndex) << MissingArgCount;
43640b57cec5SDimitry Andric 
43650b57cec5SDimitry Andric   // Issue errors on unknown arguments.
43660b57cec5SDimitry Andric   for (const auto *A : Args.filtered(OPT_UNKNOWN)) {
43670b57cec5SDimitry Andric     auto ArgString = A->getAsString(Args);
43680b57cec5SDimitry Andric     std::string Nearest;
4369a7dea167SDimitry Andric     if (Opts.findNearest(ArgString, Nearest, IncludedFlagsBitmask) > 1)
43700b57cec5SDimitry Andric       Diags.Report(diag::err_drv_unknown_argument) << ArgString;
43710b57cec5SDimitry Andric     else
43720b57cec5SDimitry Andric       Diags.Report(diag::err_drv_unknown_argument_with_suggestion)
43730b57cec5SDimitry Andric           << ArgString << Nearest;
43740b57cec5SDimitry Andric   }
43750b57cec5SDimitry Andric 
43765f7ddb14SDimitry Andric   ParseFileSystemArgs(Res.getFileSystemOpts(), Args, Diags);
43775f7ddb14SDimitry Andric   ParseMigratorArgs(Res.getMigratorOpts(), Args, Diags);
43785f7ddb14SDimitry Andric   ParseAnalyzerArgs(*Res.getAnalyzerOpts(), Args, Diags);
43795f7ddb14SDimitry Andric   ParseDiagnosticArgs(Res.getDiagnosticOpts(), Args, &Diags,
43805ffd83dbSDimitry Andric                       /*DefaultDiagColor=*/false);
43815f7ddb14SDimitry Andric   ParseFrontendArgs(Res.getFrontendOpts(), Args, Diags, LangOpts.IsHeaderFile);
43820b57cec5SDimitry Andric   // FIXME: We shouldn't have to pass the DashX option around here
43835f7ddb14SDimitry Andric   InputKind DashX = Res.getFrontendOpts().DashX;
43840b57cec5SDimitry Andric   ParseTargetArgs(Res.getTargetOpts(), Args, Diags);
4385af732203SDimitry Andric   llvm::Triple T(Res.getTargetOpts().Triple);
43865f7ddb14SDimitry Andric   ParseHeaderSearchArgs(Res.getHeaderSearchOpts(), Args, Diags,
43870b57cec5SDimitry Andric                         Res.getFileSystemOpts().WorkingDir);
43885f7ddb14SDimitry Andric 
4389af732203SDimitry Andric   ParseLangArgs(LangOpts, Args, DashX, T, Res.getPreprocessorOpts().Includes,
4390af732203SDimitry Andric                 Diags);
43910b57cec5SDimitry Andric   if (Res.getFrontendOpts().ProgramAction == frontend::RewriteObjC)
43920b57cec5SDimitry Andric     LangOpts.ObjCExceptions = 1;
43930b57cec5SDimitry Andric 
43940b57cec5SDimitry Andric   if (LangOpts.CUDA) {
43950b57cec5SDimitry Andric     // During CUDA device-side compilation, the aux triple is the
43960b57cec5SDimitry Andric     // triple used for host compilation.
43970b57cec5SDimitry Andric     if (LangOpts.CUDAIsDevice)
43980b57cec5SDimitry Andric       Res.getTargetOpts().HostTriple = Res.getFrontendOpts().AuxTriple;
43990b57cec5SDimitry Andric   }
44000b57cec5SDimitry Andric 
44010b57cec5SDimitry Andric   // Set the triple of the host for OpenMP device compile.
44020b57cec5SDimitry Andric   if (LangOpts.OpenMPIsDevice)
44030b57cec5SDimitry Andric     Res.getTargetOpts().HostTriple = Res.getFrontendOpts().AuxTriple;
44040b57cec5SDimitry Andric 
44055f7ddb14SDimitry Andric   ParseCodeGenArgs(Res.getCodeGenOpts(), Args, DashX, Diags, T,
4406af732203SDimitry Andric                    Res.getFrontendOpts().OutputFile, LangOpts);
4407af732203SDimitry Andric 
44080b57cec5SDimitry Andric   // FIXME: Override value name discarding when asan or msan is used because the
44090b57cec5SDimitry Andric   // backend passes depend on the name of the alloca in order to print out
44100b57cec5SDimitry Andric   // names.
44110b57cec5SDimitry Andric   Res.getCodeGenOpts().DiscardValueNames &=
44120b57cec5SDimitry Andric       !LangOpts.Sanitize.has(SanitizerKind::Address) &&
44130b57cec5SDimitry Andric       !LangOpts.Sanitize.has(SanitizerKind::KernelAddress) &&
44140b57cec5SDimitry Andric       !LangOpts.Sanitize.has(SanitizerKind::Memory) &&
44150b57cec5SDimitry Andric       !LangOpts.Sanitize.has(SanitizerKind::KernelMemory);
44160b57cec5SDimitry Andric 
44170b57cec5SDimitry Andric   ParsePreprocessorArgs(Res.getPreprocessorOpts(), Args, Diags,
44185f7ddb14SDimitry Andric                         Res.getFrontendOpts().ProgramAction,
44195f7ddb14SDimitry Andric                         Res.getFrontendOpts());
44205f7ddb14SDimitry Andric   ParsePreprocessorOutputArgs(Res.getPreprocessorOutputOpts(), Args, Diags,
44210b57cec5SDimitry Andric                               Res.getFrontendOpts().ProgramAction);
44220b57cec5SDimitry Andric 
44235f7ddb14SDimitry Andric   ParseDependencyOutputArgs(Res.getDependencyOutputOpts(), Args, Diags,
44245f7ddb14SDimitry Andric                             Res.getFrontendOpts().ProgramAction,
44255f7ddb14SDimitry Andric                             Res.getPreprocessorOutputOpts().ShowLineMarkers);
44265f7ddb14SDimitry Andric   if (!Res.getDependencyOutputOpts().OutputFile.empty() &&
44275f7ddb14SDimitry Andric       Res.getDependencyOutputOpts().Targets.empty())
44285f7ddb14SDimitry Andric     Diags.Report(diag::err_fe_dependency_file_requires_MT);
44290b57cec5SDimitry Andric 
44300b57cec5SDimitry Andric   // If sanitizer is enabled, disable OPT_ffine_grained_bitfield_accesses.
44310b57cec5SDimitry Andric   if (Res.getCodeGenOpts().FineGrainedBitfieldAccesses &&
44320b57cec5SDimitry Andric       !Res.getLangOpts()->Sanitize.empty()) {
44330b57cec5SDimitry Andric     Res.getCodeGenOpts().FineGrainedBitfieldAccesses = false;
44340b57cec5SDimitry Andric     Diags.Report(diag::warn_drv_fine_grained_bitfield_accesses_ignored);
44350b57cec5SDimitry Andric   }
44365ffd83dbSDimitry Andric 
44375ffd83dbSDimitry Andric   // Store the command-line for using in the CodeView backend.
44385ffd83dbSDimitry Andric   Res.getCodeGenOpts().Argv0 = Argv0;
44395ffd83dbSDimitry Andric   Res.getCodeGenOpts().CommandLineArgs = CommandLineArgs;
44405ffd83dbSDimitry Andric 
4441af732203SDimitry Andric   FixupInvocation(Res, Diags, Args, DashX);
4442af732203SDimitry Andric 
44435f7ddb14SDimitry Andric   return Diags.getNumErrors() == NumErrorsBefore;
44445f7ddb14SDimitry Andric }
44455f7ddb14SDimitry Andric 
CreateFromArgs(CompilerInvocation & Invocation,ArrayRef<const char * > CommandLineArgs,DiagnosticsEngine & Diags,const char * Argv0)44465f7ddb14SDimitry Andric bool CompilerInvocation::CreateFromArgs(CompilerInvocation &Invocation,
44475f7ddb14SDimitry Andric                                         ArrayRef<const char *> CommandLineArgs,
44485f7ddb14SDimitry Andric                                         DiagnosticsEngine &Diags,
44495f7ddb14SDimitry Andric                                         const char *Argv0) {
44505f7ddb14SDimitry Andric   CompilerInvocation DummyInvocation;
44515f7ddb14SDimitry Andric 
44525f7ddb14SDimitry Andric   return RoundTrip(
44535f7ddb14SDimitry Andric       [](CompilerInvocation &Invocation, ArrayRef<const char *> CommandLineArgs,
44545f7ddb14SDimitry Andric          DiagnosticsEngine &Diags, const char *Argv0) {
44555f7ddb14SDimitry Andric         return CreateFromArgsImpl(Invocation, CommandLineArgs, Diags, Argv0);
44565f7ddb14SDimitry Andric       },
44575f7ddb14SDimitry Andric       [](CompilerInvocation &Invocation, SmallVectorImpl<const char *> &Args,
44585f7ddb14SDimitry Andric          StringAllocator SA) { Invocation.generateCC1CommandLine(Args, SA); },
44595f7ddb14SDimitry Andric       Invocation, DummyInvocation, CommandLineArgs, Diags, Argv0);
44600b57cec5SDimitry Andric }
44610b57cec5SDimitry Andric 
getModuleHash() const44620b57cec5SDimitry Andric std::string CompilerInvocation::getModuleHash() const {
44630b57cec5SDimitry Andric   // Note: For QoI reasons, the things we use as a hash here should all be
44640b57cec5SDimitry Andric   // dumped via the -module-info flag.
44650b57cec5SDimitry Andric   using llvm::hash_code;
44660b57cec5SDimitry Andric   using llvm::hash_value;
44670b57cec5SDimitry Andric   using llvm::hash_combine;
4468a7dea167SDimitry Andric   using llvm::hash_combine_range;
44690b57cec5SDimitry Andric 
44700b57cec5SDimitry Andric   // Start the signature with the compiler version.
44710b57cec5SDimitry Andric   // FIXME: We'd rather use something more cryptographically sound than
44720b57cec5SDimitry Andric   // CityHash, but this will do for now.
44730b57cec5SDimitry Andric   hash_code code = hash_value(getClangFullRepositoryVersion());
44740b57cec5SDimitry Andric 
44755ffd83dbSDimitry Andric   // Also include the serialization version, in case LLVM_APPEND_VC_REV is off
44765ffd83dbSDimitry Andric   // and getClangFullRepositoryVersion() doesn't include git revision.
44775ffd83dbSDimitry Andric   code = hash_combine(code, serialization::VERSION_MAJOR,
44785ffd83dbSDimitry Andric                       serialization::VERSION_MINOR);
44795ffd83dbSDimitry Andric 
44800b57cec5SDimitry Andric   // Extend the signature with the language options
44810b57cec5SDimitry Andric #define LANGOPT(Name, Bits, Default, Description) \
44820b57cec5SDimitry Andric    code = hash_combine(code, LangOpts->Name);
44830b57cec5SDimitry Andric #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
44840b57cec5SDimitry Andric   code = hash_combine(code, static_cast<unsigned>(LangOpts->get##Name()));
44850b57cec5SDimitry Andric #define BENIGN_LANGOPT(Name, Bits, Default, Description)
44860b57cec5SDimitry Andric #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
44870b57cec5SDimitry Andric #include "clang/Basic/LangOptions.def"
44880b57cec5SDimitry Andric 
44890b57cec5SDimitry Andric   for (StringRef Feature : LangOpts->ModuleFeatures)
44900b57cec5SDimitry Andric     code = hash_combine(code, Feature);
44910b57cec5SDimitry Andric 
44925ffd83dbSDimitry Andric   code = hash_combine(code, LangOpts->ObjCRuntime);
44935ffd83dbSDimitry Andric   const auto &BCN = LangOpts->CommentOpts.BlockCommandNames;
44945ffd83dbSDimitry Andric   code = hash_combine(code, hash_combine_range(BCN.begin(), BCN.end()));
44955ffd83dbSDimitry Andric 
44960b57cec5SDimitry Andric   // Extend the signature with the target options.
44970b57cec5SDimitry Andric   code = hash_combine(code, TargetOpts->Triple, TargetOpts->CPU,
4498af732203SDimitry Andric                       TargetOpts->TuneCPU, TargetOpts->ABI);
44990b57cec5SDimitry Andric   for (const auto &FeatureAsWritten : TargetOpts->FeaturesAsWritten)
45000b57cec5SDimitry Andric     code = hash_combine(code, FeatureAsWritten);
45010b57cec5SDimitry Andric 
45020b57cec5SDimitry Andric   // Extend the signature with preprocessor options.
45030b57cec5SDimitry Andric   const PreprocessorOptions &ppOpts = getPreprocessorOpts();
45040b57cec5SDimitry Andric   const HeaderSearchOptions &hsOpts = getHeaderSearchOpts();
45050b57cec5SDimitry Andric   code = hash_combine(code, ppOpts.UsePredefines, ppOpts.DetailedRecord);
45060b57cec5SDimitry Andric 
45070b57cec5SDimitry Andric   for (const auto &I : getPreprocessorOpts().Macros) {
45080b57cec5SDimitry Andric     // If we're supposed to ignore this macro for the purposes of modules,
45090b57cec5SDimitry Andric     // don't put it into the hash.
45100b57cec5SDimitry Andric     if (!hsOpts.ModulesIgnoreMacros.empty()) {
45110b57cec5SDimitry Andric       // Check whether we're ignoring this macro.
45120b57cec5SDimitry Andric       StringRef MacroDef = I.first;
45130b57cec5SDimitry Andric       if (hsOpts.ModulesIgnoreMacros.count(
45140b57cec5SDimitry Andric               llvm::CachedHashString(MacroDef.split('=').first)))
45150b57cec5SDimitry Andric         continue;
45160b57cec5SDimitry Andric     }
45170b57cec5SDimitry Andric 
45180b57cec5SDimitry Andric     code = hash_combine(code, I.first, I.second);
45190b57cec5SDimitry Andric   }
45200b57cec5SDimitry Andric 
45210b57cec5SDimitry Andric   // Extend the signature with the sysroot and other header search options.
45220b57cec5SDimitry Andric   code = hash_combine(code, hsOpts.Sysroot,
45230b57cec5SDimitry Andric                       hsOpts.ModuleFormat,
45240b57cec5SDimitry Andric                       hsOpts.UseDebugInfo,
45250b57cec5SDimitry Andric                       hsOpts.UseBuiltinIncludes,
45260b57cec5SDimitry Andric                       hsOpts.UseStandardSystemIncludes,
45270b57cec5SDimitry Andric                       hsOpts.UseStandardCXXIncludes,
45280b57cec5SDimitry Andric                       hsOpts.UseLibcxx,
45290b57cec5SDimitry Andric                       hsOpts.ModulesValidateDiagnosticOptions);
45300b57cec5SDimitry Andric   code = hash_combine(code, hsOpts.ResourceDir);
45310b57cec5SDimitry Andric 
4532a7dea167SDimitry Andric   if (hsOpts.ModulesStrictContextHash) {
4533a7dea167SDimitry Andric     hash_code SHPC = hash_combine_range(hsOpts.SystemHeaderPrefixes.begin(),
4534a7dea167SDimitry Andric                                         hsOpts.SystemHeaderPrefixes.end());
4535a7dea167SDimitry Andric     hash_code UEC = hash_combine_range(hsOpts.UserEntries.begin(),
4536a7dea167SDimitry Andric                                        hsOpts.UserEntries.end());
4537a7dea167SDimitry Andric     code = hash_combine(code, hsOpts.SystemHeaderPrefixes.size(), SHPC,
4538a7dea167SDimitry Andric                         hsOpts.UserEntries.size(), UEC);
4539a7dea167SDimitry Andric 
4540a7dea167SDimitry Andric     const DiagnosticOptions &diagOpts = getDiagnosticOpts();
4541a7dea167SDimitry Andric     #define DIAGOPT(Name, Bits, Default) \
4542a7dea167SDimitry Andric       code = hash_combine(code, diagOpts.Name);
4543a7dea167SDimitry Andric     #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
4544a7dea167SDimitry Andric       code = hash_combine(code, diagOpts.get##Name());
4545a7dea167SDimitry Andric     #include "clang/Basic/DiagnosticOptions.def"
4546a7dea167SDimitry Andric     #undef DIAGOPT
4547a7dea167SDimitry Andric     #undef ENUM_DIAGOPT
4548a7dea167SDimitry Andric   }
4549a7dea167SDimitry Andric 
45500b57cec5SDimitry Andric   // Extend the signature with the user build path.
45510b57cec5SDimitry Andric   code = hash_combine(code, hsOpts.ModuleUserBuildPath);
45520b57cec5SDimitry Andric 
45530b57cec5SDimitry Andric   // Extend the signature with the module file extensions.
45540b57cec5SDimitry Andric   const FrontendOptions &frontendOpts = getFrontendOpts();
45550b57cec5SDimitry Andric   for (const auto &ext : frontendOpts.ModuleFileExtensions) {
45560b57cec5SDimitry Andric     code = ext->hashExtension(code);
45570b57cec5SDimitry Andric   }
45580b57cec5SDimitry Andric 
45590b57cec5SDimitry Andric   // When compiling with -gmodules, also hash -fdebug-prefix-map as it
45600b57cec5SDimitry Andric   // affects the debug info in the PCM.
45610b57cec5SDimitry Andric   if (getCodeGenOpts().DebugTypeExtRefs)
45620b57cec5SDimitry Andric     for (const auto &KeyValue : getCodeGenOpts().DebugPrefixMap)
45630b57cec5SDimitry Andric       code = hash_combine(code, KeyValue.first, KeyValue.second);
45640b57cec5SDimitry Andric 
45650b57cec5SDimitry Andric   // Extend the signature with the enabled sanitizers, if at least one is
45660b57cec5SDimitry Andric   // enabled. Sanitizers which cannot affect AST generation aren't hashed.
45670b57cec5SDimitry Andric   SanitizerSet SanHash = LangOpts->Sanitize;
45680b57cec5SDimitry Andric   SanHash.clear(getPPTransparentSanitizers());
45690b57cec5SDimitry Andric   if (!SanHash.empty())
45700b57cec5SDimitry Andric     code = hash_combine(code, SanHash.Mask);
45710b57cec5SDimitry Andric 
45725f7ddb14SDimitry Andric   return toString(llvm::APInt(64, code), 36, /*Signed=*/false);
45730b57cec5SDimitry Andric }
45740b57cec5SDimitry Andric 
generateCC1CommandLine(SmallVectorImpl<const char * > & Args,StringAllocator SA) const45755ffd83dbSDimitry Andric void CompilerInvocation::generateCC1CommandLine(
45765ffd83dbSDimitry Andric     SmallVectorImpl<const char *> &Args, StringAllocator SA) const {
45775f7ddb14SDimitry Andric   llvm::Triple T(TargetOpts->Triple);
45785ffd83dbSDimitry Andric 
45795f7ddb14SDimitry Andric   GenerateFileSystemArgs(FileSystemOpts, Args, SA);
45805f7ddb14SDimitry Andric   GenerateMigratorArgs(MigratorOpts, Args, SA);
45815f7ddb14SDimitry Andric   GenerateAnalyzerArgs(*AnalyzerOpts, Args, SA);
45825f7ddb14SDimitry Andric   GenerateDiagnosticArgs(*DiagnosticOpts, Args, SA, false);
45835f7ddb14SDimitry Andric   GenerateFrontendArgs(FrontendOpts, Args, SA, LangOpts->IsHeaderFile);
45845f7ddb14SDimitry Andric   GenerateTargetArgs(*TargetOpts, Args, SA);
45855f7ddb14SDimitry Andric   GenerateHeaderSearchArgs(*HeaderSearchOpts, Args, SA);
45865f7ddb14SDimitry Andric   GenerateLangArgs(*LangOpts, Args, SA, T, FrontendOpts.DashX);
45875f7ddb14SDimitry Andric   GenerateCodeGenArgs(CodeGenOpts, Args, SA, T, FrontendOpts.OutputFile,
45885f7ddb14SDimitry Andric                       &*LangOpts);
45895f7ddb14SDimitry Andric   GeneratePreprocessorArgs(*PreprocessorOpts, Args, SA, *LangOpts, FrontendOpts,
45905f7ddb14SDimitry Andric                            CodeGenOpts);
45915f7ddb14SDimitry Andric   GeneratePreprocessorOutputArgs(PreprocessorOutputOpts, Args, SA,
45925f7ddb14SDimitry Andric                                  FrontendOpts.ProgramAction);
45935f7ddb14SDimitry Andric   GenerateDependencyOutputArgs(DependencyOutputOpts, Args, SA);
45945ffd83dbSDimitry Andric }
45955ffd83dbSDimitry Andric 
45960b57cec5SDimitry Andric IntrusiveRefCntPtr<llvm::vfs::FileSystem>
createVFSFromCompilerInvocation(const CompilerInvocation & CI,DiagnosticsEngine & Diags)4597af732203SDimitry Andric clang::createVFSFromCompilerInvocation(const CompilerInvocation &CI,
45980b57cec5SDimitry Andric                                        DiagnosticsEngine &Diags) {
45990b57cec5SDimitry Andric   return createVFSFromCompilerInvocation(CI, Diags,
46000b57cec5SDimitry Andric                                          llvm::vfs::getRealFileSystem());
46010b57cec5SDimitry Andric }
46020b57cec5SDimitry Andric 
4603af732203SDimitry Andric IntrusiveRefCntPtr<llvm::vfs::FileSystem>
createVFSFromCompilerInvocation(const CompilerInvocation & CI,DiagnosticsEngine & Diags,IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS)4604af732203SDimitry Andric clang::createVFSFromCompilerInvocation(
46050b57cec5SDimitry Andric     const CompilerInvocation &CI, DiagnosticsEngine &Diags,
46060b57cec5SDimitry Andric     IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS) {
46070b57cec5SDimitry Andric   if (CI.getHeaderSearchOpts().VFSOverlayFiles.empty())
46080b57cec5SDimitry Andric     return BaseFS;
46090b57cec5SDimitry Andric 
46100b57cec5SDimitry Andric   IntrusiveRefCntPtr<llvm::vfs::FileSystem> Result = BaseFS;
46110b57cec5SDimitry Andric   // earlier vfs files are on the bottom
46120b57cec5SDimitry Andric   for (const auto &File : CI.getHeaderSearchOpts().VFSOverlayFiles) {
46130b57cec5SDimitry Andric     llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer =
46140b57cec5SDimitry Andric         Result->getBufferForFile(File);
46150b57cec5SDimitry Andric     if (!Buffer) {
46160b57cec5SDimitry Andric       Diags.Report(diag::err_missing_vfs_overlay_file) << File;
46170b57cec5SDimitry Andric       continue;
46180b57cec5SDimitry Andric     }
46190b57cec5SDimitry Andric 
46200b57cec5SDimitry Andric     IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS = llvm::vfs::getVFSFromYAML(
46210b57cec5SDimitry Andric         std::move(Buffer.get()), /*DiagHandler*/ nullptr, File,
46220b57cec5SDimitry Andric         /*DiagContext*/ nullptr, Result);
46230b57cec5SDimitry Andric     if (!FS) {
46240b57cec5SDimitry Andric       Diags.Report(diag::err_invalid_vfs_overlay) << File;
46250b57cec5SDimitry Andric       continue;
46260b57cec5SDimitry Andric     }
46270b57cec5SDimitry Andric 
46280b57cec5SDimitry Andric     Result = FS;
46290b57cec5SDimitry Andric   }
46300b57cec5SDimitry Andric   return Result;
46310b57cec5SDimitry Andric }
4632