//===- CompilerInvocation.cpp ---------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "clang/Frontend/CompilerInvocation.h"
#include "TestModuleFileExtension.h"
#include "clang/Basic/Builtins.h"
#include "clang/Basic/CharInfo.h"
#include "clang/Basic/CodeGenOptions.h"
#include "clang/Basic/CommentOptions.h"
#include "clang/Basic/DebugInfoOptions.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/DiagnosticDriver.h"
#include "clang/Basic/DiagnosticOptions.h"
#include "clang/Basic/FileSystemOptions.h"
#include "clang/Basic/LLVM.h"
#include "clang/Basic/LangOptions.h"
#include "clang/Basic/LangStandard.h"
#include "clang/Basic/ObjCRuntime.h"
#include "clang/Basic/Sanitizers.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Basic/TargetOptions.h"
#include "clang/Basic/Version.h"
#include "clang/Basic/Visibility.h"
#include "clang/Basic/XRayInstr.h"
#include "clang/Config/config.h"
#include "clang/Driver/Driver.h"
#include "clang/Driver/DriverDiagnostic.h"
#include "clang/Driver/Options.h"
#include "clang/Frontend/CommandLineSourceLoc.h"
#include "clang/Frontend/DependencyOutputOptions.h"
#include "clang/Frontend/FrontendDiagnostic.h"
#include "clang/Frontend/FrontendOptions.h"
#include "clang/Frontend/FrontendPluginRegistry.h"
#include "clang/Frontend/MigratorOptions.h"
#include "clang/Frontend/PreprocessorOutputOptions.h"
#include "clang/Frontend/TextDiagnosticBuffer.h"
#include "clang/Frontend/Utils.h"
#include "clang/Lex/HeaderSearchOptions.h"
#include "clang/Lex/PreprocessorOptions.h"
#include "clang/Sema/CodeCompleteOptions.h"
#include "clang/Serialization/ASTBitCodes.h"
#include "clang/Serialization/ModuleFileExtension.h"
#include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/CachedHashString.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/FloatingPointMode.h"
#include "llvm/ADT/Hashing.h"
#include "llvm/ADT/None.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/ADT/Triple.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Config/llvm-config.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/Linker/Linker.h"
#include "llvm/MC/MCTargetOptions.h"
#include "llvm/Option/Arg.h"
#include "llvm/Option/ArgList.h"
#include "llvm/Option/OptSpecifier.h"
#include "llvm/Option/OptTable.h"
#include "llvm/Option/Option.h"
#include "llvm/ProfileData/InstrProfReader.h"
#include "llvm/Remarks/HotnessThresholdParser.h"
#include "llvm/Support/CodeGen.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/ErrorOr.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/HashBuilder.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Process.h"
#include "llvm/Support/Regex.h"
#include "llvm/Support/VersionTuple.h"
#include "llvm/Support/VirtualFileSystem.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetOptions.h"
#include <algorithm>
#include <atomic>
#include <cassert>
#include <cstddef>
#include <cstring>
#include <memory>
#include <string>
#include <tuple>
#include <type_traits>
#include <utility>
#include <vector>
using namespace clang;
using namespace driver;
using namespace options;
using namespace llvm::opt;
//===----------------------------------------------------------------------===//
// Helpers.
//===----------------------------------------------------------------------===//
// Parse misexpect tolerance argument value.
// Valid option values are integers in the range [0, 100)
inline Expected<Optional<uint64_t>> parseToleranceOption(StringRef Arg) {
int64_t Val;
if (Arg.getAsInteger(10, Val))
return llvm::createStringError(llvm::inconvertibleErrorCode(),
"Not an integer: %s", Arg.data());
return Val;
}
//===----------------------------------------------------------------------===//
// Initialization.
//===----------------------------------------------------------------------===//
CompilerInvocationRefBase::CompilerInvocationRefBase()
: LangOpts(new LangOptions()), TargetOpts(new TargetOptions()),
DiagnosticOpts(new DiagnosticOptions()),
HeaderSearchOpts(new HeaderSearchOptions()),
PreprocessorOpts(new PreprocessorOptions()),
AnalyzerOpts(new AnalyzerOptions()) {}
CompilerInvocationRefBase::CompilerInvocationRefBase(
const CompilerInvocationRefBase &X)
: LangOpts(new LangOptions(*X.getLangOpts())),
TargetOpts(new TargetOptions(X.getTargetOpts())),
DiagnosticOpts(new DiagnosticOptions(X.getDiagnosticOpts())),
HeaderSearchOpts(new HeaderSearchOptions(X.getHeaderSearchOpts())),
PreprocessorOpts(new PreprocessorOptions(X.getPreprocessorOpts())),
AnalyzerOpts(new AnalyzerOptions(*X.getAnalyzerOpts())) {}
CompilerInvocationRefBase::CompilerInvocationRefBase(
CompilerInvocationRefBase &&X) = default;
CompilerInvocationRefBase &
CompilerInvocationRefBase::operator=(CompilerInvocationRefBase X) {
LangOpts.swap(X.LangOpts);
TargetOpts.swap(X.TargetOpts);
DiagnosticOpts.swap(X.DiagnosticOpts);
HeaderSearchOpts.swap(X.HeaderSearchOpts);
PreprocessorOpts.swap(X.PreprocessorOpts);
AnalyzerOpts.swap(X.AnalyzerOpts);
return *this;
}
CompilerInvocationRefBase &
CompilerInvocationRefBase::operator=(CompilerInvocationRefBase &&X) = default;
CompilerInvocationRefBase::~CompilerInvocationRefBase() = default;
//===----------------------------------------------------------------------===//
// Normalizers
//===----------------------------------------------------------------------===//
#define SIMPLE_ENUM_VALUE_TABLE
#include "clang/Driver/Options.inc"
#undef SIMPLE_ENUM_VALUE_TABLE
static llvm::Optional<bool> normalizeSimpleFlag(OptSpecifier Opt,
unsigned TableIndex,
const ArgList &Args,
DiagnosticsEngine &Diags) {
if (Args.hasArg(Opt))
return true;
return None;
}
static Optional<bool> normalizeSimpleNegativeFlag(OptSpecifier Opt, unsigned,
const ArgList &Args,
DiagnosticsEngine &) {
if (Args.hasArg(Opt))
return false;
return None;
}
/// The tblgen-erated code passes in a fifth parameter of an arbitrary type, but
/// denormalizeSimpleFlags never looks at it. Avoid bloating compile-time with
/// unnecessary template instantiations and just ignore it with a variadic
/// argument.
static void denormalizeSimpleFlag(SmallVectorImpl<const char *> &Args,
const char *Spelling,
CompilerInvocation::StringAllocator,
Option::OptionClass, unsigned, /*T*/...) {
Args.push_back(Spelling);
}
template <typename T> static constexpr bool is_uint64_t_convertible() {
return !std::is_same<T, uint64_t>::value &&
llvm::is_integral_or_enum<T>::value;
}
template <typename T,
std::enable_if_t<!is_uint64_t_convertible<T>(), bool> = false>
static auto makeFlagToValueNormalizer(T Value) {
return [Value](OptSpecifier Opt, unsigned, const ArgList &Args,
DiagnosticsEngine &) -> Optional<T> {
if (Args.hasArg(Opt))
return Value;
return None;
};
}
template <typename T,
std::enable_if_t<is_uint64_t_convertible<T>(), bool> = false>
static auto makeFlagToValueNormalizer(T Value) {
return makeFlagToValueNormalizer(uint64_t(Value));
}
static auto makeBooleanOptionNormalizer(bool Value, bool OtherValue,
OptSpecifier OtherOpt) {
return [Value, OtherValue, OtherOpt](OptSpecifier Opt, unsigned,
const ArgList &Args,
DiagnosticsEngine &) -> Optional<bool> {
if (const Arg *A = Args.getLastArg(Opt, OtherOpt)) {
return A->getOption().matches(Opt) ? Value : OtherValue;
}
return None;
};
}
static auto makeBooleanOptionDenormalizer(bool Value) {
return [Value](SmallVectorImpl<const char *> &Args, const char *Spelling,
CompilerInvocation::StringAllocator, Option::OptionClass,
unsigned, bool KeyPath) {
if (KeyPath == Value)
Args.push_back(Spelling);
};
}
static void denormalizeStringImpl(SmallVectorImpl<const char *> &Args,
const char *Spelling,
CompilerInvocation::StringAllocator SA,
Option::OptionClass OptClass, unsigned,
const Twine &Value) {
switch (OptClass) {
case Option::SeparateClass:
case Option::JoinedOrSeparateClass:
case Option::JoinedAndSeparateClass:
Args.push_back(Spelling);
Args.push_back(SA(Value));
break;
case Option::JoinedClass:
case Option::CommaJoinedClass:
Args.push_back(SA(Twine(Spelling) + Value));
break;
default:
llvm_unreachable("Cannot denormalize an option with option class "
"incompatible with string denormalization.");
}
}
template <typename T>
static void
denormalizeString(SmallVectorImpl<const char *> &Args, const char *Spelling,
CompilerInvocation::StringAllocator SA,
Option::OptionClass OptClass, unsigned TableIndex, T Value) {
denormalizeStringImpl(Args, Spelling, SA, OptClass, TableIndex, Twine(Value));
}
static Optional<SimpleEnumValue>
findValueTableByName(const SimpleEnumValueTable &Table, StringRef Name) {
for (int I = 0, E = Table.Size; I != E; ++I)
if (Name == Table.Table[I].Name)
return Table.Table[I];
return None;
}
static Optional<SimpleEnumValue>
findValueTableByValue(const SimpleEnumValueTable &Table, unsigned Value) {
for (int I = 0, E = Table.Size; I != E; ++I)
if (Value == Table.Table[I].Value)
return Table.Table[I];
return None;
}
static llvm::Optional<unsigned> normalizeSimpleEnum(OptSpecifier Opt,
unsigned TableIndex,
const ArgList &Args,
DiagnosticsEngine &Diags) {
assert(TableIndex < SimpleEnumValueTablesSize);
const SimpleEnumValueTable &Table = SimpleEnumValueTables[TableIndex];
auto *Arg = Args.getLastArg(Opt);
if (!Arg)
return None;
StringRef ArgValue = Arg->getValue();
if (auto MaybeEnumVal = findValueTableByName(Table, ArgValue))
return MaybeEnumVal->Value;
Diags.Report(diag::err_drv_invalid_value)
<< Arg->getAsString(Args) << ArgValue;
return None;
}
static void denormalizeSimpleEnumImpl(SmallVectorImpl<const char *> &Args,
const char *Spelling,
CompilerInvocation::StringAllocator SA,
Option::OptionClass OptClass,
unsigned TableIndex, unsigned Value) {
assert(TableIndex < SimpleEnumValueTablesSize);
const SimpleEnumValueTable &Table = SimpleEnumValueTables[TableIndex];
if (auto MaybeEnumVal = findValueTableByValue(Table, Value)) {
denormalizeString(Args, Spelling, SA, OptClass, TableIndex,
MaybeEnumVal->Name);
} else {
llvm_unreachable("The simple enum value was not correctly defined in "
"the tablegen option description");
}
}
template <typename T>
static void denormalizeSimpleEnum(SmallVectorImpl<const char *> &Args,
const char *Spelling,
CompilerInvocation::StringAllocator SA,
Option::OptionClass OptClass,
unsigned TableIndex, T Value) {
return denormalizeSimpleEnumImpl(Args, Spelling, SA, OptClass, TableIndex,
static_cast<unsigned>(Value));
}
static Optional<std::string> normalizeString(OptSpecifier Opt, int TableIndex,
const ArgList &Args,
DiagnosticsEngine &Diags) {
auto *Arg = Args.getLastArg(Opt);
if (!Arg)
return None;
return std::string(Arg->getValue());
}
template <typename IntTy>
static Optional<IntTy> normalizeStringIntegral(OptSpecifier Opt, int,
const ArgList &Args,
DiagnosticsEngine &Diags) {
auto *Arg = Args.getLastArg(Opt);
if (!Arg)
return None;
IntTy Res;
if (StringRef(Arg->getValue()).getAsInteger(0, Res)) {
Diags.Report(diag::err_drv_invalid_int_value)
<< Arg->getAsString(Args) << Arg->getValue();
return None;
}
return Res;
}
static Optional<std::vector<std::string>>
normalizeStringVector(OptSpecifier Opt, int, const ArgList &Args,
DiagnosticsEngine &) {
return Args.getAllArgValues(Opt);
}
static void denormalizeStringVector(SmallVectorImpl<const char *> &Args,
const char *Spelling,
CompilerInvocation::StringAllocator SA,
Option::OptionClass OptClass,
unsigned TableIndex,
const std::vector<std::string> &Values) {
switch (OptClass) {
case Option::CommaJoinedClass: {
std::string CommaJoinedValue;
if (!Values.empty()) {
CommaJoinedValue.append(Values.front());
for (const std::string &Value : llvm::drop_begin(Values, 1)) {
CommaJoinedValue.append(",");
CommaJoinedValue.append(Value);
}
}
denormalizeString(Args, Spelling, SA, Option::OptionClass::JoinedClass,
TableIndex, CommaJoinedValue);
break;
}
case Option::JoinedClass:
case Option::SeparateClass:
case Option::JoinedOrSeparateClass:
for (const std::string &Value : Values)
denormalizeString(Args, Spelling, SA, OptClass, TableIndex, Value);
break;
default:
llvm_unreachable("Cannot denormalize an option with option class "
"incompatible with string vector denormalization.");
}
}
static Optional<std::string> normalizeTriple(OptSpecifier Opt, int TableIndex,
const ArgList &Args,
DiagnosticsEngine &Diags) {
auto *Arg = Args.getLastArg(Opt);
if (!Arg)
return None;
return llvm::Triple::normalize(Arg->getValue());
}
template <typename T, typename U>
static T mergeForwardValue(T KeyPath, U Value) {
return static_cast<T>(Value);
}
template <typename T, typename U> static T mergeMaskValue(T KeyPath, U Value) {
return KeyPath | Value;
}
template <typename T> static T extractForwardValue(T KeyPath) {
return KeyPath;
}
template <typename T, typename U, U Value>
static T extractMaskValue(T KeyPath) {
return ((KeyPath & Value) == Value) ? static_cast<T>(Value) : T();
}
#define PARSE_OPTION_WITH_MARSHALLING( \
ARGS, DIAGS, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \
IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX) \
if ((FLAGS)&options::CC1Option) { \
KEYPATH = MERGER(KEYPATH, DEFAULT_VALUE); \
if (IMPLIED_CHECK) \
KEYPATH = MERGER(KEYPATH, IMPLIED_VALUE); \
if (SHOULD_PARSE) \
if (auto MaybeValue = NORMALIZER(OPT_##ID, TABLE_INDEX, ARGS, DIAGS)) \
KEYPATH = \
MERGER(KEYPATH, static_cast<decltype(KEYPATH)>(*MaybeValue)); \
}
// Capture the extracted value as a lambda argument to avoid potential issues
// with lifetime extension of the reference.
#define GENERATE_OPTION_WITH_MARSHALLING( \
ARGS, STRING_ALLOCATOR, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, \
DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, \
TABLE_INDEX) \
if ((FLAGS)&options::CC1Option) { \
[&](const auto &Extracted) { \
if (ALWAYS_EMIT || \
(Extracted != \
static_cast<decltype(KEYPATH)>((IMPLIED_CHECK) ? (IMPLIED_VALUE) \
: (DEFAULT_VALUE)))) \
DENORMALIZER(ARGS, SPELLING, STRING_ALLOCATOR, Option::KIND##Class, \
TABLE_INDEX, Extracted); \
}(EXTRACTOR(KEYPATH)); \
}
static StringRef GetInputKindName(InputKind IK);
static bool FixupInvocation(CompilerInvocation &Invocation,
DiagnosticsEngine &Diags, const ArgList &Args,
InputKind IK) {
unsigned NumErrorsBefore = Diags.getNumErrors();
LangOptions &LangOpts = *Invocation.getLangOpts();
CodeGenOptions &CodeGenOpts = Invocation.getCodeGenOpts();
TargetOptions &TargetOpts = Invocation.getTargetOpts();
FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
CodeGenOpts.XRayInstrumentFunctions = LangOpts.XRayInstrument;
CodeGenOpts.XRayAlwaysEmitCustomEvents = LangOpts.XRayAlwaysEmitCustomEvents;
CodeGenOpts.XRayAlwaysEmitTypedEvents = LangOpts.XRayAlwaysEmitTypedEvents;
CodeGenOpts.DisableFree = FrontendOpts.DisableFree;
FrontendOpts.GenerateGlobalModuleIndex = FrontendOpts.UseGlobalModuleIndex;
if (FrontendOpts.ShowStats)
CodeGenOpts.ClearASTBeforeBackend = false;
LangOpts.SanitizeCoverage = CodeGenOpts.hasSanitizeCoverage();
LangOpts.ForceEmitVTables = CodeGenOpts.ForceEmitVTables;
LangOpts.SpeculativeLoadHardening = CodeGenOpts.SpeculativeLoadHardening;
LangOpts.CurrentModule = LangOpts.ModuleName;
llvm::Triple T(TargetOpts.Triple);
llvm::Triple::ArchType Arch = T.getArch();
CodeGenOpts.CodeModel = TargetOpts.CodeModel;
if (LangOpts.getExceptionHandling() !=
LangOptions::ExceptionHandlingKind::None &&
T.isWindowsMSVCEnvironment())
Diags.Report(diag::err_fe_invalid_exception_model)
<< static_cast<unsigned>(LangOpts.getExceptionHandling()) << T.str();
if (LangOpts.AppleKext && !LangOpts.CPlusPlus)
Diags.Report(diag::warn_c_kext);
if (Args.hasArg(OPT_fconcepts_ts))
Diags.Report(diag::warn_fe_concepts_ts_flag);
if (LangOpts.NewAlignOverride &&
!llvm::isPowerOf2_32(LangOpts.NewAlignOverride)) {
Arg *A = Args.getLastArg(OPT_fnew_alignment_EQ);
Diags.Report(diag::err_fe_invalid_alignment)
<< A->getAsString(Args) << A->getValue();
LangOpts.NewAlignOverride = 0;
}
// Prevent the user from specifying both -fsycl-is-device and -fsycl-is-host.
if (LangOpts.SYCLIsDevice && LangOpts.SYCLIsHost)
Diags.Report(diag::err_drv_argument_not_allowed_with) << "-fsycl-is-device"
<< "-fsycl-is-host";
if (Args.hasArg(OPT_fgnu89_inline) && LangOpts.CPlusPlus)
Diags.Report(diag::err_drv_argument_not_allowed_with)
<< "-fgnu89-inline" << GetInputKindName(IK);
if (Args.hasArg(OPT_fgpu_allow_device_init) && !LangOpts.HIP)
Diags.Report(diag::warn_ignored_hip_only_option)
<< Args.getLastArg(OPT_fgpu_allow_device_init)->getAsString(Args);
if (Args.hasArg(OPT_gpu_max_threads_per_block_EQ) && !LangOpts.HIP)
Diags.Report(diag::warn_ignored_hip_only_option)
<< Args.getLastArg(OPT_gpu_max_threads_per_block_EQ)->getAsString(Args);
// -cl-strict-aliasing needs to emit diagnostic in the case where CL > 1.0.
// This option should be deprecated for CL > 1.0 because
// this option was added for compatibility with OpenCL 1.0.
if (Args.getLastArg(OPT_cl_strict_aliasing) &&
(LangOpts.getOpenCLCompatibleVersion() > 100))
Diags.Report(diag::warn_option_invalid_ocl_version)
<< LangOpts.getOpenCLVersionString()
<< Args.getLastArg(OPT_cl_strict_aliasing)->getAsString(Args);
if (Arg *A = Args.getLastArg(OPT_fdefault_calling_conv_EQ)) {
auto DefaultCC = LangOpts.getDefaultCallingConv();
bool emitError = (DefaultCC == LangOptions::DCC_FastCall ||
DefaultCC == LangOptions::DCC_StdCall) &&
Arch != llvm::Triple::x86;
emitError |= (DefaultCC == LangOptions::DCC_VectorCall ||
DefaultCC == LangOptions::DCC_RegCall) &&
!T.isX86();
if (emitError)
Diags.Report(diag::err_drv_argument_not_allowed_with)
<< A->getSpelling() << T.getTriple();
}
if (!CodeGenOpts.ProfileRemappingFile.empty() && CodeGenOpts.LegacyPassManager)
Diags.Report(diag::err_drv_argument_only_allowed_with)
<< Args.getLastArg(OPT_fprofile_remapping_file_EQ)->getAsString(Args)
<< "-fno-legacy-pass-manager";
return Diags.getNumErrors() == NumErrorsBefore;
}
//===----------------------------------------------------------------------===//
// Deserialization (from args)
//===----------------------------------------------------------------------===//
static unsigned getOptimizationLevel(ArgList &Args, InputKind IK,
DiagnosticsEngine &Diags) {
unsigned DefaultOpt = llvm::CodeGenOpt::None;
if ((IK.getLanguage() == Language::OpenCL ||
IK.getLanguage() == Language::OpenCLCXX) &&
!Args.hasArg(OPT_cl_opt_disable))
DefaultOpt = llvm::CodeGenOpt::Default;
if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
if (A->getOption().matches(options::OPT_O0))
return llvm::CodeGenOpt::None;
if (A->getOption().matches(options::OPT_Ofast))
return llvm::CodeGenOpt::Aggressive;
assert(A->getOption().matches(options::OPT_O));
StringRef S(A->getValue());
if (S == "s" || S == "z")
return llvm::CodeGenOpt::Default;
if (S == "g")
return llvm::CodeGenOpt::Less;
return getLastArgIntValue(Args, OPT_O, DefaultOpt, Diags);
}
return DefaultOpt;
}
static unsigned getOptimizationLevelSize(ArgList &Args) {
if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
if (A->getOption().matches(options::OPT_O)) {
switch (A->getValue()[0]) {
default:
return 0;
case 's':
return 1;
case 'z':
return 2;
}
}
}
return 0;
}
static void GenerateArg(SmallVectorImpl<const char *> &Args,
llvm::opt::OptSpecifier OptSpecifier,
CompilerInvocation::StringAllocator SA) {
Option Opt = getDriverOptTable().getOption(OptSpecifier);
denormalizeSimpleFlag(Args, SA(Opt.getPrefix() + Opt.getName()), SA,
Option::OptionClass::FlagClass, 0);
}
static void GenerateArg(SmallVectorImpl<const char *> &Args,
llvm::opt::OptSpecifier OptSpecifier,
const Twine &Value,
CompilerInvocation::StringAllocator SA) {
Option Opt = getDriverOptTable().getOption(OptSpecifier);
denormalizeString(Args, SA(Opt.getPrefix() + Opt.getName()), SA,
Opt.getKind(), 0, Value);
}
// Parse command line arguments into CompilerInvocation.
using ParseFn =
llvm::function_ref<bool(CompilerInvocation &, ArrayRef<const char *>,
DiagnosticsEngine &, const char *)>;
// Generate command line arguments from CompilerInvocation.
using GenerateFn = llvm::function_ref<void(
CompilerInvocation &, SmallVectorImpl<const char *> &,
CompilerInvocation::StringAllocator)>;
// May perform round-trip of command line arguments. By default, the round-trip
// is enabled in assert builds. This can be overwritten at run-time via the
// "-round-trip-args" and "-no-round-trip-args" command line flags.
// During round-trip, the command line arguments are parsed into a dummy
// instance of CompilerInvocation which is used to generate the command line
// arguments again. The real CompilerInvocation instance is then created by
// parsing the generated arguments, not the original ones.
static bool RoundTrip(ParseFn Parse, GenerateFn Generate,
CompilerInvocation &RealInvocation,
CompilerInvocation &DummyInvocation,
ArrayRef<const char *> CommandLineArgs,
DiagnosticsEngine &Diags, const char *Argv0) {
#ifndef NDEBUG
bool DoRoundTripDefault = true;
#else
bool DoRoundTripDefault = false;
#endif
bool DoRoundTrip = DoRoundTripDefault;
for (const auto *Arg : CommandLineArgs) {
if (Arg == StringRef("-round-trip-args"))
DoRoundTrip = true;
if (Arg == StringRef("-no-round-trip-args"))
DoRoundTrip = false;
}
// If round-trip was not requested, simply run the parser with the real
// invocation diagnostics.
if (!DoRoundTrip)
return Parse(RealInvocation, CommandLineArgs, Diags, Argv0);
// Serializes quoted (and potentially escaped) arguments.
auto SerializeArgs = [](ArrayRef<const char *> Args) {
std::string Buffer;
llvm::raw_string_ostream OS(Buffer);
for (const char *Arg : Args) {
llvm::sys::printArg(OS, Arg, /*Quote=*/true);
OS << ' ';
}
OS.flush();
return Buffer;
};
// Setup a dummy DiagnosticsEngine.
DiagnosticsEngine DummyDiags(new DiagnosticIDs(), new DiagnosticOptions());
DummyDiags.setClient(new TextDiagnosticBuffer());
// Run the first parse on the original arguments with the dummy invocation and
// diagnostics.
if (!Parse(DummyInvocation, CommandLineArgs, DummyDiags, Argv0) ||
DummyDiags.getNumWarnings() != 0) {
// If the first parse did not succeed, it must be user mistake (invalid
// command line arguments). We won't be able to generate arguments that
// would reproduce the same result. Let's fail again with the real
// invocation and diagnostics, so all side-effects of parsing are visible.
unsigned NumWarningsBefore = Diags.getNumWarnings();
auto Success = Parse(RealInvocation, CommandLineArgs, Diags, Argv0);
if (!Success || Diags.getNumWarnings() != NumWarningsBefore)
return Success;
// Parse with original options and diagnostics succeeded even though it
// shouldn't have. Something is off.
Diags.Report(diag::err_cc1_round_trip_fail_then_ok);
Diags.Report(diag::note_cc1_round_trip_original)
<< SerializeArgs(CommandLineArgs);
return false;
}
// Setup string allocator.
llvm::BumpPtrAllocator Alloc;
llvm::StringSaver StringPool(Alloc);
auto SA = [&StringPool](const Twine &Arg) {
return StringPool.save(Arg).data();
};
// Generate arguments from the dummy invocation. If Generate is the
// inverse of Parse, the newly generated arguments must have the same
// semantics as the original.
SmallVector<const char *> GeneratedArgs1;
Generate(DummyInvocation, GeneratedArgs1, SA);
// Run the second parse, now on the generated arguments, and with the real
// invocation and diagnostics. The result is what we will end up using for the
// rest of compilation, so if Generate is not inverse of Parse, something down
// the line will break.
bool Success2 = Parse(RealInvocation, GeneratedArgs1, Diags, Argv0);
// The first parse on original arguments succeeded, but second parse of
// generated arguments failed. Something must be wrong with the generator.
if (!Success2) {
Diags.Report(diag::err_cc1_round_trip_ok_then_fail);
Diags.Report(diag::note_cc1_round_trip_generated)
<< 1 << SerializeArgs(GeneratedArgs1);
return false;
}
// Generate arguments again, this time from the options we will end up using
// for the rest of the compilation.
SmallVector<const char *> GeneratedArgs2;
Generate(RealInvocation, GeneratedArgs2, SA);
// Compares two lists of generated arguments.
auto Equal = [](const ArrayRef<const char *> A,
const ArrayRef<const char *> B) {
return std::equal(A.begin(), A.end(), B.begin(), B.end(),
[](const char *AElem, const char *BElem) {
return StringRef(AElem) == StringRef(BElem);
});
};
// If we generated different arguments from what we assume are two
// semantically equivalent CompilerInvocations, the Generate function may
// be non-deterministic.
if (!Equal(GeneratedArgs1, GeneratedArgs2)) {
Diags.Report(diag::err_cc1_round_trip_mismatch);
Diags.Report(diag::note_cc1_round_trip_generated)
<< 1 << SerializeArgs(GeneratedArgs1);
Diags.Report(diag::note_cc1_round_trip_generated)
<< 2 << SerializeArgs(GeneratedArgs2);
return false;
}
Diags.Report(diag::remark_cc1_round_trip_generated)
<< 1 << SerializeArgs(GeneratedArgs1);
Diags.Report(diag::remark_cc1_round_trip_generated)
<< 2 << SerializeArgs(GeneratedArgs2);
return Success2;
}
static void addDiagnosticArgs(ArgList &Args, OptSpecifier Group,
OptSpecifier GroupWithValue,
std::vector<std::string> &Diagnostics) {
for (auto *A : Args.filtered(Group)) {
if (A->getOption().getKind() == Option::FlagClass) {
// The argument is a pure flag (such as OPT_Wall or OPT_Wdeprecated). Add
// its name (minus the "W" or "R" at the beginning) to the diagnostics.
Diagnostics.push_back(
std::string(A->getOption().getName().drop_front(1)));
} else if (A->getOption().matches(GroupWithValue)) {
// This is -Wfoo= or -Rfoo=, where foo is the name of the diagnostic
// group. Add only the group name to the diagnostics.
Diagnostics.push_back(
std::string(A->getOption().getName().drop_front(1).rtrim("=-")));
} else {
// Otherwise, add its value (for OPT_W_Joined and similar).
Diagnostics.push_back(A->getValue());
}
}
}
// Parse the Static Analyzer configuration. If \p Diags is set to nullptr,
// it won't verify the input.
static void parseAnalyzerConfigs(AnalyzerOptions &AnOpts,
DiagnosticsEngine *Diags);
static void getAllNoBuiltinFuncValues(ArgList &Args,
std::vector<std::string> &Funcs) {
std::vector<std::string> Values = Args.getAllArgValues(OPT_fno_builtin_);
auto BuiltinEnd = llvm::partition(Values, Builtin::Context::isBuiltinFunc);
Funcs.insert(Funcs.end(), Values.begin(), BuiltinEnd);
}
static void GenerateAnalyzerArgs(AnalyzerOptions &Opts,
SmallVectorImpl<const char *> &Args,
CompilerInvocation::StringAllocator SA) {
const AnalyzerOptions *AnalyzerOpts = &Opts;
|