blob: c104a6f40e20f90c51e23ef943deea81f2748a3b [file] [log] [blame]
//===- 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;
//===----------------------------------------------------------------------===//
// 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 const 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, [](const std::string FuncName) {
return Builtin::Context::isBuiltinFunc(FuncName);
});
Funcs.insert(Funcs.end(), Values.begin(), BuiltinEnd);
}
static void GenerateAnalyzerArgs(AnalyzerOptions &Opts,
SmallVectorImpl<const char *> &Args,
CompilerInvocation::StringAllocator SA) {
const AnalyzerOptions *AnalyzerOpts = &Opts;
#define ANALYZER_OPTION_WITH_MARSHALLING( \
PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
MERGER, EXTRACTOR, TABLE_INDEX) \
GENERATE_OPTION_WITH_MARSHALLING( \
Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \
IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
#include "clang/Driver/Options.inc"
#undef ANALYZER_OPTION_WITH_MARSHALLING
if (Opts.AnalysisStoreOpt != RegionStoreModel) {
switch (Opts.AnalysisStoreOpt) {
#define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN) \
case NAME##Model: \
GenerateArg(Args, OPT_analyzer_store, CMDFLAG, SA); \
break;
#include "clang/StaticAnalyzer/Core/Analyses.def"
default:
llvm_unreachable("Tried to generate unknown analysis store.");
}
}
if (Opts.AnalysisConstraintsOpt != RangeConstraintsModel) {
switch (Opts.AnalysisConstraintsOpt) {
#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) \
case NAME##Model: \
GenerateArg(Args, OPT_analyzer_constraints, CMDFLAG, SA); \
break;
#include "clang/StaticAnalyzer/Core/Analyses.def"
default:
llvm_unreachable("Tried to generate unknown analysis constraint.");
}
}
if (Opts.AnalysisDiagOpt != PD_HTML) {
switch (Opts.AnalysisDiagOpt) {
#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN) \
case PD_##NAME: \
GenerateArg(Args, OPT_analyzer_output, CMDFLAG, SA); \
break;
#include "clang/StaticAnalyzer/Core/Analyses.def"
default:
llvm_unreachable("Tried to generate unknown analysis diagnostic client.");
}
}
if (Opts.AnalysisPurgeOpt != PurgeStmt) {
switch (Opts.AnalysisPurgeOpt) {
#define ANALYSIS_PURGE(NAME, CMDFLAG, DESC) \
case NAME: \
GenerateArg(Args, OPT_analyzer_purge, CMDFLAG, SA); \
break;
#include "clang/StaticAnalyzer/Core/Analyses.def"
default:
llvm_unreachable("Tried to generate unknown analysis purge mode.");
}
}
if (Opts.InliningMode != NoRedundancy) {
switch (Opts.InliningMode) {
#define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC) \
case NAME: \
GenerateArg(Args, OPT_analyzer_inlining_mode, CMDFLAG, SA); \
break;
#include "clang/StaticAnalyzer/Core/Analyses.def"
default:
llvm_unreachable("Tried to generate unknown analysis inlining mode.");
}
}
for (const auto &CP : Opts.CheckersAndPackages) {
OptSpecifier Opt =
CP.second ? OPT_analyzer_checker : OPT_analyzer_disable_checker;
GenerateArg(Args, Opt, CP.first, SA);
}
AnalyzerOptions ConfigOpts;
parseAnalyzerConfigs(ConfigOpts, nullptr);
for (const auto &C : Opts.Config) {
// Don't generate anything that came from parseAnalyzerConfigs. It would be
// redundant and may not be valid on the command line.
auto Entry = ConfigOpts.Config.find(C.getKey());
if (Entry != ConfigOpts.Config.end() && Entry->getValue() == C.getValue())
continue;
GenerateArg(Args, OPT_analyzer_config, C.getKey() + "=" + C.getValue(), SA);
}
// Nothing to generate for FullCompilerInvocation.
}
static bool ParseAnalyzerArgs(AnalyzerOptions &Opts, ArgList &Args,
DiagnosticsEngine &Diags) {
unsigned NumErrorsBefore = Diags.getNumErrors();
AnalyzerOptions *AnalyzerOpts = &Opts;
#define ANALYZER_OPTION_WITH_MARSHALLING( \
PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
MERGER, EXTRACTOR, TABLE_INDEX) \
PARSE_OPTION_WITH_MARSHALLING( \
Args, Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \
IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
#include "clang/Driver/Options.inc"
#undef ANALYZER_OPTION_WITH_MARSHALLING
if (Arg *A = Args.getLastArg(OPT_analyzer_store)) {
StringRef Name = A->getValue();
AnalysisStores Value = llvm::StringSwitch<AnalysisStores>(Name)
#define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN) \
.Case(CMDFLAG, NAME##Model)
#include "clang/StaticAnalyzer/Core/Analyses.def"
.Default(NumStores);
if (Value == NumStores) {
Diags.Report(diag::err_drv_invalid_value)
<< A->getAsString(Args) << Name;
} else {
Opts.AnalysisStoreOpt = Value;
}
}
if (Arg *A = Args.getLastArg(OPT_analyzer_constraints)) {
StringRef Name = A->getValue();
AnalysisConstraints Value = llvm::StringSwitch<AnalysisConstraints>(Name)
#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) \
.Case(CMDFLAG, NAME##Model)
#include "clang/StaticAnalyzer/Core/Analyses.def"
.Default(NumConstraints);
if (Value == NumConstraints) {
Diags.Report(diag::err_drv_invalid_value)
<< A->getAsString(Args) << Name;
} else {
Opts.AnalysisConstraintsOpt = Value;
}
}
if (Arg *A = Args.getLastArg(OPT_analyzer_output)) {
StringRef Name = A->getValue();
AnalysisDiagClients Value = llvm::StringSwitch<AnalysisDiagClients>(Name)
#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN) \
.Case(CMDFLAG, PD_##NAME)
#include "clang/StaticAnalyzer/Core/Analyses.def"
.Default(NUM_ANALYSIS_DIAG_CLIENTS);
if (Value == NUM_ANALYSIS_DIAG_CLIENTS) {
Diags.Report(diag::err_drv_invalid_value)
<< A->getAsString(Args) << Name;
} else {
Opts.AnalysisDiagOpt = Value;
}
}
if (Arg *A = Args.getLastArg(OPT_analyzer_purge)) {
StringRef Name = A->getValue();
AnalysisPurgeMode Value = llvm::StringSwitch<AnalysisPurgeMode>(Name)
#define ANALYSIS_PURGE(NAME, CMDFLAG, DESC) \
.Case(CMDFLAG, NAME)
#include "clang/StaticAnalyzer/Core/Analyses.def"
.Default(NumPurgeModes);
if (Value == NumPurgeModes) {
Diags.Report(diag::err_drv_invalid_value)
<< A->getAsString(Args) << Name;
} else {
Opts.AnalysisPurgeOpt = Value;
}
}
if (Arg *A = Args.getLastArg(OPT_analyzer_inlining_mode)) {
StringRef Name = A->getValue();
AnalysisInliningMode Value = llvm::StringSwitch<AnalysisInliningMode>(Name)
#define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC) \
.Case(CMDFLAG, NAME)
#include "clang/StaticAnalyzer/Core/Analyses.def"
.Default(NumInliningModes);
if (Value == NumInliningModes) {
Diags.Report(diag::err_drv_invalid_value)
<< A->getAsString(Args) << Name;
} else {
Opts.InliningMode = Value;
}
}
Opts.CheckersAndPackages.clear();
for (const Arg *A :
Args.filtered(OPT_analyzer_checker, OPT_analyzer_disable_checker)) {
A->claim();
bool IsEnabled = A->getOption().getID() == OPT_analyzer_checker;
// We can have a list of comma separated checker names, e.g:
// '-analyzer-checker=cocoa,unix'
StringRef CheckerAndPackageList = A->getValue();
SmallVector<StringRef, 16> CheckersAndPackages;
CheckerAndPackageList.split(CheckersAndPackages, ",");
for (const StringRef &CheckerOrPackage : CheckersAndPackages)
Opts.CheckersAndPackages.emplace_back(std::string(CheckerOrPackage),
IsEnabled);
}
// Go through the analyzer configuration options.
for (const auto *A : Args.filtered(OPT_analyzer_config)) {
// We can have a list of comma separated config names, e.g:
// '-analyzer-config key1=val1,key2=val2'
StringRef configList = A->getValue();
SmallVector<StringRef, 4> configVals;
configList.split(configVals, ",");
for (const auto &configVal : configVals) {
StringRef key, val;
std::tie(key, val) = configVal.split("=");
if (val.empty()) {
Diags.Report(SourceLocation(),
diag::err_analyzer_config_no_value) << configVal;
break;
}
if (val.contains('=')) {
Diags.Report(SourceLocation(),
diag::err_analyzer_config_multiple_values)
<< configVal;
break;
}
// TODO: Check checker options too, possibly in CheckerRegistry.
// Leave unknown non-checker configs unclaimed.
if (!key.contains(":") && Opts.isUnknownAnalyzerConfig(key)) {
if (Opts.ShouldEmitErrorsOnInvalidConfigValue)
Diags.Report(diag::err_analyzer_config_unknown) << key;
continue;
}
A->claim();
Opts.Config[key] = std::string(val);
}
}
if (Opts.ShouldEmitErrorsOnInvalidConfigValue)
parseAnalyzerConfigs(Opts, &Diags);
else
parseAnalyzerConfigs(Opts, nullptr);
llvm::raw_string_ostream os(Opts.FullCompilerInvocation);
for (unsigned i = 0; i < Args.getNumInputArgStrings(); ++i) {
if (i != 0)
os << " ";
os << Args.getArgString(i);
}
os.flush();
return Diags.getNumErrors() == NumErrorsBefore;
}
static StringRef getStringOption(AnalyzerOptions::ConfigTable &Config,
StringRef OptionName, StringRef DefaultVal) {
return Config.insert({OptionName, std::string(DefaultVal)}).first->second;
}
static void initOption(AnalyzerOptions::ConfigTable &Config,
DiagnosticsEngine *Diags,
StringRef &OptionField, StringRef Name,
StringRef DefaultVal) {
// String options may be known to invalid (e.g. if the expected string is a
// file name, but the file does not exist), those will have to be checked in
// parseConfigs.
OptionField = getStringOption(Config, Name, DefaultVal);
}
static void initOption(AnalyzerOptions::ConfigTable &Config,
DiagnosticsEngine *Diags,
bool &OptionField, StringRef Name, bool DefaultVal) {
auto PossiblyInvalidVal = llvm::StringSwitch<Optional<bool>>(
getStringOption(Config, Name, (DefaultVal ? "true" : "false")))
.Case("true", true)
.Case("false", false)
.Default(None);
if (!PossiblyInvalidVal) {
if (Diags)
Diags->Report(diag::err_analyzer_config_invalid_input)
<< Name << "a boolean";
else
OptionField = DefaultVal;
} else
OptionField = PossiblyInvalidVal.getValue();
}
static void initOption(AnalyzerOptions::ConfigTable &Config,
DiagnosticsEngine *Diags,
unsigned &OptionField, StringRef Name,
unsigned DefaultVal) {
OptionField = DefaultVal;
bool HasFailed = getStringOption(Config, Name, std::to_string(DefaultVal))
.getAsInteger(0, OptionField);
if (Diags && HasFailed)
Diags->Report(diag::err_analyzer_config_invalid_input)
<< Name << "an unsigned";
}
static void parseAnalyzerConfigs(AnalyzerOptions &AnOpts,
DiagnosticsEngine *Diags) {
// TODO: There's no need to store the entire configtable, it'd be plenty
// enough tostore checker options.
#define ANALYZER_OPTION(TYPE, NAME, CMDFLAG, DESC, DEFAULT_VAL) \
initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, DEFAULT_VAL);
#define ANALYZER_OPTION_DEPENDS_ON_USER_MODE(TYPE, NAME, CMDFLAG, DESC, \
SHALLOW_VAL, DEEP_VAL) \
switch (AnOpts.getUserMode()) { \
case UMK_Shallow: \
initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, SHALLOW_VAL); \
break; \
case UMK_Deep: \
initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, DEEP_VAL); \
break; \
} \
#include "clang/StaticAnalyzer/Core/AnalyzerOptions.def"
#undef ANALYZER_OPTION
#undef ANALYZER_OPTION_DEPENDS_ON_USER_MODE
// At this point, AnalyzerOptions is configured. Let's validate some options.
// FIXME: Here we try to validate the silenced checkers or packages are valid.
// The current approach only validates the registered checkers which does not
// contain the runtime enabled checkers and optimally we would validate both.
if (!AnOpts.RawSilencedCheckersAndPackages.empty()) {
std::vector<StringRef> Checkers =
AnOpts.getRegisteredCheckers(/*IncludeExperimental=*/true);
std::vector<StringRef> Packages =
AnOpts.getRegisteredPackages(/*IncludeExperimental=*/true);
SmallVector<StringRef, 16> CheckersAndPackages;
AnOpts.RawSilencedCheckersAndPackages.split(CheckersAndPackages, ";");
for (const StringRef &CheckerOrPackage : CheckersAndPackages) {
if (Diags) {
bool IsChecker = CheckerOrPackage.contains('.');
bool IsValidName = IsChecker
? llvm::is_contained(Checkers, CheckerOrPackage)
: llvm::is_contained(Packages, CheckerOrPackage);
if (!IsValidName)
Diags->Report(diag::err_unknown_analyzer_checker_or_package)
<< CheckerOrPackage;
}
AnOpts.SilencedCheckersAndPackages.emplace_back(CheckerOrPackage);
}
}
if (!Diags)
return;
if (AnOpts.ShouldTrackConditionsDebug && !AnOpts.ShouldTrackConditions)
Diags->Report(diag::err_analyzer_config_invalid_input)
<< "track-conditions-debug" << "'track-conditions' to also be enabled";
if (!AnOpts.CTUDir.empty() && !llvm::sys::fs::is_directory(AnOpts.CTUDir))
Diags->Report(diag::err_analyzer_config_invalid_input) << "ctu-dir"
<< "a filename";
if (!AnOpts.ModelPath.empty() &&
!llvm::sys::fs::is_directory(AnOpts.ModelPath))
Diags->Report(diag::err_analyzer_config_invalid_input) << "model-path"
<< "a filename";
}
/// Generate a remark argument. This is an inverse of `ParseOptimizationRemark`.
static void
GenerateOptimizationRemark(SmallVectorImpl<const char *> &Args,
CompilerInvocation::StringAllocator SA,
OptSpecifier OptEQ, StringRef Name,
const CodeGenOptions::OptRemark &Remark) {
if (Remark.hasValidPattern()) {
GenerateArg(Args, OptEQ, Remark.Pattern, SA);
} else if (Remark.Kind == CodeGenOptions::RK_Enabled) {
GenerateArg(Args, OPT_R_Joined, Name, SA);
} else if (Remark.Kind == CodeGenOptions::RK_Disabled) {
GenerateArg(Args, OPT_R_Joined, StringRef("no-") + Name, SA);
}
}
/// Parse a remark command line argument. It may be missing, disabled/enabled by
/// '-R[no-]group' or specified with a regular expression by '-Rgroup=regexp'.
/// On top of that, it can be disabled/enabled globally by '-R[no-]everything'.
static CodeGenOptions::OptRemark
ParseOptimizationRemark(DiagnosticsEngine &Diags, ArgList &Args,
OptSpecifier OptEQ, StringRef Name) {
CodeGenOptions::OptRemark Result;
auto InitializeResultPattern = [&Diags, &Args, &Result](const Arg *A,
StringRef Pattern) {
Result.Pattern = Pattern.str();
std::string RegexError;
Result.Regex = std::make_shared<llvm::Regex>(Result.Pattern);
if (!Result.Regex->isValid(RegexError)) {
Diags.Report(diag::err_drv_optimization_remark_pattern)
<< RegexError << A->getAsString(Args);
return false;
}
return true;
};
for (Arg *A : Args) {
if (A->getOption().matches(OPT_R_Joined)) {
StringRef Value = A->getValue();
if (Value == Name)
Result.Kind = CodeGenOptions::RK_Enabled;
else if (Value == "everything")
Result.Kind = CodeGenOptions::RK_EnabledEverything;
else if (Value.split('-') == std::make_pair(StringRef("no"), Name))
Result.Kind = CodeGenOptions::RK_Disabled;
else if (Value == "no-everything")
Result.Kind = CodeGenOptions::RK_DisabledEverything;
else
continue;
if (Result.Kind == CodeGenOptions::RK_Disabled ||
Result.Kind == CodeGenOptions::RK_DisabledEverything) {
Result.Pattern = "";
Result.Regex = nullptr;
} else {
InitializeResultPattern(A, ".*");
}
} else if (A->getOption().matches(OptEQ)) {
Result.Kind = CodeGenOptions::RK_WithPattern;
if (!InitializeResultPattern(A, A->getValue()))
return CodeGenOptions::OptRemark();
}
}
return Result;
}
static bool parseDiagnosticLevelMask(StringRef FlagName,
const std::vector<std::string> &Levels,
DiagnosticsEngine &Diags,
DiagnosticLevelMask &M) {
bool Success = true;
for (const auto &Level : Levels) {
DiagnosticLevelMask const PM =
llvm::StringSwitch<DiagnosticLevelMask>(Level)
.Case("note", DiagnosticLevelMask::Note)
.Case("remark", DiagnosticLevelMask::Remark)
.Case("warning", DiagnosticLevelMask::Warning)
.Case("error", DiagnosticLevelMask::Error)
.Default(DiagnosticLevelMask::None);
if (PM == DiagnosticLevelMask::None) {
Success = false;
Diags.Report(diag::err_drv_invalid_value) << FlagName << Level;
}
M = M | PM;
}
return Success;
}
static void parseSanitizerKinds(StringRef FlagName,
const std::vector<std::string> &Sanitizers,
DiagnosticsEngine &Diags, SanitizerSet &S) {
for (const auto &Sanitizer : Sanitizers) {
SanitizerMask K = parseSanitizerValue(Sanitizer, /*AllowGroups=*/false);
if (K == SanitizerMask())
Diags.Report(diag::err_drv_invalid_value) << FlagName << Sanitizer;
else
S.set(K, true);
}
}
static SmallVector<StringRef, 4> serializeSanitizerKinds(SanitizerSet S) {
SmallVector<StringRef, 4> Values;
serializeSanitizerSet(S, Values);
return Values;
}
static void parseXRayInstrumentationBundle(StringRef FlagName, StringRef Bundle,
ArgList &Args, DiagnosticsEngine &D,
XRayInstrSet &S) {
llvm::SmallVector<StringRef, 2> BundleParts;
llvm::SplitString(Bundle, BundleParts, ",");
for (const auto &B : BundleParts) {
auto Mask = parseXRayInstrValue(B);
if (Mask == XRayInstrKind::None)
if (B != "none")
D.Report(diag::err_drv_invalid_value) << FlagName << Bundle;
else
S.Mask = Mask;
else if (Mask == XRayInstrKind::All)
S.Mask = Mask;
else
S.set(Mask, true);
}
}
static std::string serializeXRayInstrumentationBundle(const XRayInstrSet &S) {
llvm::SmallVector<StringRef, 2> BundleParts;
serializeXRayInstrValue(S, BundleParts);
std::string Buffer;
llvm::raw_string_ostream OS(Buffer);
llvm::interleave(BundleParts, OS, [&OS](StringRef Part) { OS << Part; }, ",");
return OS.str();
}
// Set the profile kind using fprofile-instrument-use-path.
static void setPGOUseInstrumentor(CodeGenOptions &Opts,
const Twine &ProfileName) {
auto ReaderOrErr = llvm::IndexedInstrProfReader::create(ProfileName);
// In error, return silently and let Clang PGOUse report the error message.
if (auto E = ReaderOrErr.takeError()) {
llvm::consumeError(std::move(E));
Opts.setProfileUse(CodeGenOptions::ProfileClangInstr);
return;
}
std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader =
std::move(ReaderOrErr.get());
if (PGOReader->isIRLevelProfile()) {
if (PGOReader->hasCSIRLevelProfile())
Opts.setProfileUse(CodeGenOptions::ProfileCSIRInstr);
else
Opts.setProfileUse(CodeGenOptions::ProfileIRInstr);
} else
Opts.setProfileUse(CodeGenOptions::ProfileClangInstr);
}
void CompilerInvocation::GenerateCodeGenArgs(
const CodeGenOptions &Opts, SmallVectorImpl<const char *> &Args,
StringAllocator SA, const llvm::Triple &T, const std::string &OutputFile,
const LangOptions *LangOpts) {
const CodeGenOptions &CodeGenOpts = Opts;
if (Opts.OptimizationLevel == 0)
GenerateArg(Args, OPT_O0, SA);
else
GenerateArg(Args, OPT_O, Twine(Opts.OptimizationLevel), SA);
#define CODEGEN_OPTION_WITH_MARSHALLING( \
PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
MERGER, EXTRACTOR, TABLE_INDEX) \
GENERATE_OPTION_WITH_MARSHALLING( \
Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \
IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
#include "clang/Driver/Options.inc"
#undef CODEGEN_OPTION_WITH_MARSHALLING
if (Opts.OptimizationLevel > 0) {
if (Opts.Inlining == CodeGenOptions::NormalInlining)
GenerateArg(Args, OPT_finline_functions, SA);
else if (Opts.Inlining == CodeGenOptions::OnlyHintInlining)
GenerateArg(Args, OPT_finline_hint_functions, SA);
else if (Opts.Inlining == CodeGenOptions::OnlyAlwaysInlining)
GenerateArg(Args, OPT_fno_inline, SA);
}
if (Opts.DirectAccessExternalData && LangOpts->PICLevel != 0)
GenerateArg(Args, OPT_fdirect_access_external_data, SA);
else if (!Opts.DirectAccessExternalData && LangOpts->PICLevel == 0)
GenerateArg(Args, OPT_fno_direct_access_external_data, SA);
Optional<StringRef> DebugInfoVal;
switch (Opts.DebugInfo) {
case codegenoptions::DebugLineTablesOnly:
DebugInfoVal = "line-tables-only";
break;
case codegenoptions::DebugDirectivesOnly:
DebugInfoVal = "line-directives-only";
break;
case codegenoptions::DebugInfoConstructor:
DebugInfoVal = "constructor";
break;
case codegenoptions::LimitedDebugInfo:
DebugInfoVal = "limited";
break;
case codegenoptions::FullDebugInfo:
DebugInfoVal = "standalone";
break;
case codegenoptions::UnusedTypeInfo:
DebugInfoVal = "unused-types";
break;
case codegenoptions::NoDebugInfo: // default value
DebugInfoVal = None;
break;
case codegenoptions::LocTrackingOnly: // implied value
DebugInfoVal = None;
break;
}
if (DebugInfoVal)
GenerateArg(Args, OPT_debug_info_kind_EQ, *DebugInfoVal, SA);
for (const auto &Prefix : Opts.DebugPrefixMap)
GenerateArg(Args, OPT_fdebug_prefix_map_EQ,
Prefix.first + "=" + Prefix.second, SA);
for (const auto &Prefix : Opts.CoveragePrefixMap)
GenerateArg(Args, OPT_fcoverage_prefix_map_EQ,
Prefix.first + "=" + Prefix.second, SA);
if (Opts.NewStructPathTBAA)
GenerateArg(Args, OPT_new_struct_path_tbaa, SA);
if (Opts.OptimizeSize == 1)
GenerateArg(Args, OPT_O, "s", SA);
else if (Opts.OptimizeSize == 2)
GenerateArg(Args, OPT_O, "z", SA);
// SimplifyLibCalls is set only in the absence of -fno-builtin and
// -ffreestanding. We'll consider that when generating them.
// NoBuiltinFuncs are generated by LangOptions.
if (Opts.UnrollLoops && Opts.OptimizationLevel <= 1)
GenerateArg(Args, OPT_funroll_loops, SA);
else if (!Opts.UnrollLoops && Opts.OptimizationLevel > 1)
GenerateArg(Args, OPT_fno_unroll_loops, SA);
if (!Opts.BinutilsVersion.empty())
GenerateArg(Args, OPT_fbinutils_version_EQ, Opts.BinutilsVersion, SA);
if (Opts.DebugNameTable ==
static_cast<unsigned>(llvm::DICompileUnit::DebugNameTableKind::GNU))
GenerateArg(Args, OPT_ggnu_pubnames, SA);
else if (Opts.DebugNameTable ==
static_cast<unsigned>(
llvm::DICompileUnit::DebugNameTableKind::Default))
GenerateArg(Args, OPT_gpubnames, SA);
auto TNK = Opts.getDebugSimpleTemplateNames();
if (TNK != codegenoptions::DebugTemplateNamesKind::Full) {
if (TNK == codegenoptions::DebugTemplateNamesKind::Simple)
GenerateArg(Args, OPT_gsimple_template_names_EQ, "simple", SA);
else if (TNK == codegenoptions::DebugTemplateNamesKind::Mangled)
GenerateArg(Args, OPT_gsimple_template_names_EQ, "mangled", SA);
}
// ProfileInstrumentUsePath is marshalled automatically, no need to generate
// it or PGOUseInstrumentor.
if (Opts.TimePasses) {
if (Opts.TimePassesPerRun)
GenerateArg(Args, OPT_ftime_report_EQ, "per-pass-run", SA);
else
GenerateArg(Args, OPT_ftime_report, SA);
}
if (Opts.PrepareForLTO && !Opts.PrepareForThinLTO)
GenerateArg(Args, OPT_flto_EQ, "full", SA);
if (Opts.PrepareForThinLTO)
GenerateArg(Args, OPT_flto_EQ, "thin", SA);
if (!Opts.ThinLTOIndexFile.empty())
GenerateArg(Args, OPT_fthinlto_index_EQ, Opts.ThinLTOIndexFile, SA);
if (Opts.SaveTempsFilePrefix == OutputFile)
GenerateArg(Args, OPT_save_temps_EQ, "obj", SA);
StringRef MemProfileBasename("memprof.profraw");
if (!Opts.MemoryProfileOutput.empty()) {
if (Opts.MemoryProfileOutput == MemProfileBasename) {
GenerateArg(Args, OPT_fmemory_profile, SA);
} else {
size_t ArgLength =
Opts.MemoryProfileOutput.size() - MemProfileBasename.size();
GenerateArg(Args, OPT_fmemory_profile_EQ,
Opts.MemoryProfileOutput.substr(0, ArgLength), SA);
}
}
if (memcmp(Opts.CoverageVersion, "408*", 4) != 0)
GenerateArg(Args, OPT_coverage_version_EQ,
StringRef(Opts.CoverageVersion, 4), SA);
// TODO: Check if we need to generate arguments stored in CmdArgs. (Namely
// '-fembed_bitcode', which does not map to any CompilerInvocation field and
// won't be generated.)
if (Opts.XRayInstrumentationBundle.Mask != XRayInstrKind::All) {
std::string InstrBundle =
serializeXRayInstrumentationBundle(Opts.XRayInstrumentationBundle);
if (!InstrBundle.empty())
GenerateArg(Args, OPT_fxray_instrumentation_bundle, InstrBundle, SA);
}
if (Opts.CFProtectionReturn && Opts.CFProtectionBranch)
GenerateArg(Args, OPT_fcf_protection_EQ, "full", SA);
else if (Opts.CFProtectionReturn)
GenerateArg(Args, OPT_fcf_protection_EQ, "return", SA);
else if (Opts.CFProtectionBranch)
GenerateArg(Args, OPT_fcf_protection_EQ, "branch", SA);
for (const auto &F : Opts.LinkBitcodeFiles) {
bool Builtint = F.LinkFlags == llvm::Linker::Flags::LinkOnlyNeeded &&
F.PropagateAttrs && F.Internalize;
GenerateArg(Args,
Builtint ? OPT_mlink_builtin_bitcode : OPT_mlink_bitcode_file,
F.Filename, SA);
}
// TODO: Consider removing marshalling annotations from f[no_]emulated_tls.
// That would make it easy to generate the option only **once** if it was
// explicitly set to non-default value.
if (Opts.ExplicitEmulatedTLS) {
GenerateArg(
Args, Opts.EmulatedTLS ? OPT_femulated_tls : OPT_fno_emulated_tls, SA);
}
if (Opts.FPDenormalMode != llvm::DenormalMode::getIEEE())
GenerateArg(Args, OPT_fdenormal_fp_math_EQ, Opts.FPDenormalMode.str(), SA);
if (Opts.FP32DenormalMode != llvm::DenormalMode::getIEEE())
GenerateArg(Args, OPT_fdenormal_fp_math_f32_EQ, Opts.FP32DenormalMode.str(),
SA);
if (Opts.StructReturnConvention == CodeGenOptions::SRCK_OnStack) {
OptSpecifier Opt =
T.isPPC32() ? OPT_maix_struct_return : OPT_fpcc_struct_return;
GenerateArg(Args, Opt, SA);
} else if (Opts.StructReturnConvention == CodeGenOptions::SRCK_InRegs) {
OptSpecifier Opt =
T.isPPC32() ? OPT_msvr4_struct_return : OPT_freg_struct_return;
GenerateArg(Args, Opt, SA);
}
if (Opts.EnableAIXExtendedAltivecABI)
GenerateArg(Args, OPT_mabi_EQ_vec_extabi, SA);
if (!Opts.OptRecordPasses.empty())
GenerateArg(Args, OPT_opt_record_passes, Opts.OptRecordPasses, SA);
if (!Opts.OptRecordFormat.empty())
GenerateArg(Args, OPT_opt_record_format, Opts.OptRecordFormat, SA);
GenerateOptimizationRemark(Args, SA, OPT_Rpass_EQ, "pass",
Opts.OptimizationRemark);
GenerateOptimizationRemark(Args, SA, OPT_Rpass_missed_EQ, "pass-missed",
Opts.OptimizationRemarkMissed);
GenerateOptimizationRemark(Args, SA, OPT_Rpass_analysis_EQ, "pass-analysis",
Opts.OptimizationRemarkAnalysis);
GenerateArg(Args, OPT_fdiagnostics_hotness_threshold_EQ,
Opts.DiagnosticsHotnessThreshold
? Twine(*Opts.DiagnosticsHotnessThreshold)
: "auto",
SA);
for (StringRef Sanitizer : serializeSanitizerKinds(Opts.SanitizeRecover))
GenerateArg(Args, OPT_fsanitize_recover_EQ, Sanitizer, SA);
for (StringRef Sanitizer : serializeSanitizerKinds(Opts.SanitizeTrap))
GenerateArg(Args, OPT_fsanitize_trap_EQ, Sanitizer, SA);
if (!Opts.EmitVersionIdentMetadata)
GenerateArg(Args, OPT_Qn, SA);
switch (Opts.FiniteLoops) {
case CodeGenOptions::FiniteLoopsKind::Language:
break;
case CodeGenOptions::FiniteLoopsKind::Always:
GenerateArg(Args, OPT_ffinite_loops, SA);
break;
case CodeGenOptions::FiniteLoopsKind::Never:
GenerateArg(Args, OPT_fno_finite_loops, SA);
break;
}
}
bool CompilerInvocation::ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args,
InputKind IK,
DiagnosticsEngine &Diags,
const llvm::Triple &T,
const std::string &OutputFile,
const LangOptions &LangOptsRef) {
unsigned NumErrorsBefore = Diags.getNumErrors();
unsigned OptimizationLevel = getOptimizationLevel(Args, IK, Diags);
// TODO: This could be done in Driver
unsigned MaxOptLevel = 3;
if (OptimizationLevel > MaxOptLevel) {
// If the optimization level is not supported, fall back on the default
// optimization
Diags.Report(diag::warn_drv_optimization_value)
<< Args.getLastArg(OPT_O)->getAsString(Args) << "-O" << MaxOptLevel;
OptimizationLevel = MaxOptLevel;
}
Opts.OptimizationLevel = OptimizationLevel;
// The key paths of codegen options defined in Options.td start with
// "CodeGenOpts.". Let's provide the expected variable name and type.
CodeGenOptions &CodeGenOpts = Opts;
// Some codegen options depend on language options. Let's provide the expected
// variable name and type.
const LangOptions *LangOpts = &LangOptsRef;
#define CODEGEN_OPTION_WITH_MARSHALLING( \
PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
MERGER, EXTRACTOR, TABLE_INDEX) \
PARSE_OPTION_WITH_MARSHALLING( \
Args, Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \
IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
#include "clang/Driver/Options.inc"
#undef CODEGEN_OPTION_WITH_MARSHALLING
// At O0 we want to fully disable inlining outside of cases marked with
// 'alwaysinline' that are required for correctness.
Opts.setInlining((Opts.OptimizationLevel == 0)
? CodeGenOptions::OnlyAlwaysInlining
: CodeGenOptions::NormalInlining);
// Explicit inlining flags can disable some or all inlining even at
// optimization levels above zero.
if (Arg *InlineArg = Args.getLastArg(
options::OPT_finline_functions, options::OPT_finline_hint_functions,
options::OPT_fno_inline_functions, options::OPT_fno_inline)) {
if (Opts.OptimizationLevel > 0) {
const Option &InlineOpt = InlineArg->getOption();
if (InlineOpt.matches(options::OPT_finline_functions))
Opts.setInlining(CodeGenOptions::NormalInlining);
else if (InlineOpt.matches(options::OPT_finline_hint_functions))
Opts.setInlining(CodeGenOptions::OnlyHintInlining);
else
Opts.setInlining(CodeGenOptions::OnlyAlwaysInlining);
}
}
// PIC defaults to -fno-direct-access-external-data while non-PIC defaults to
// -fdirect-access-external-data.
Opts.DirectAccessExternalData =
Args.hasArg(OPT_fdirect_access_external_data) ||
(!Args.hasArg(OPT_fno_direct_access_external_data) &&
LangOpts->PICLevel == 0);
if (Arg *A = Args.getLastArg(OPT_debug_info_kind_EQ)) {
unsigned Val =
llvm::StringSwitch<unsigned>(A->getValue())
.Case("line-tables-only", codegenoptions::DebugLineTablesOnly)
.Case("line-directives-only", codegenoptions::DebugDirectivesOnly)
.Case("constructor", codegenoptions::DebugInfoConstructor)
.Case("limited", codegenoptions::LimitedDebugInfo)
.Case("standalone", codegenoptions::FullDebugInfo)
.Case("unused-types", codegenoptions::UnusedTypeInfo)
.Default(~0U);
if (Val == ~0U)
Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
<< A->getValue();
else
Opts.setDebugInfo(static_cast<codegenoptions::DebugInfoKind>(Val));
}
// If -fuse-ctor-homing is set and limited debug info is already on, then use
// constructor homing, and vice versa for -fno-use-ctor-homing.
if (const Arg *A =
Args.getLastArg(OPT_fuse_ctor_homing, OPT_fno_use_ctor_homing)) {
if (A->getOption().matches(OPT_fuse_ctor_homing) &&
Opts.getDebugInfo() == codegenoptions::LimitedDebugInfo)
Opts.setDebugInfo(codegenoptions::DebugInfoConstructor);
if (A->getOption().matches(OPT_fno_use_ctor_homing) &&
Opts.getDebugInfo() == codegenoptions::DebugInfoConstructor)
Opts.setDebugInfo(codegenoptions::LimitedDebugInfo);
}
for (const auto &Arg : Args.getAllArgValues(OPT_fdebug_prefix_map_EQ)) {
auto Split = StringRef(Arg).split('=');
Opts.DebugPrefixMap.insert(
{std::string(Split.first), std::string(Split.second)});
}
for (const auto &Arg : Args.getAllArgValues(OPT_fcoverage_prefix_map_EQ)) {
auto Split = StringRef(Arg).split('=');
Opts.CoveragePrefixMap.insert(
{std::string(Split.first), std::string(Split.second)});
}
const llvm::Triple::ArchType DebugEntryValueArchs[] = {
llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::aarch64,
llvm::Triple::arm, llvm::Triple::armeb, llvm::Triple::mips,
llvm::Triple::mipsel, llvm::Triple::mips64, llvm::Triple::mips64el};
if (Opts.OptimizationLevel > 0 && Opts.hasReducedDebugInfo() &&
llvm::is_contained(DebugEntryValueArchs, T.getArch()))
Opts.EmitCallSiteInfo = true;
if (!Opts.EnableDIPreservationVerify && Opts.DIBugsReportFilePath.size()) {
Diags.Report(diag::warn_ignoring_verify_debuginfo_preserve_export)
<< Opts.DIBugsReportFilePath;
Opts.DIBugsReportFilePath = "";
}
Opts.NewStructPathTBAA = !Args.hasArg(OPT_no_struct_path_tbaa) &&
Args.hasArg(OPT_new_struct_path_tbaa);
Opts.OptimizeSize = getOptimizationLevelSize(Args);
Opts.SimplifyLibCalls = !LangOpts->NoBuiltin;
if (Opts.SimplifyLibCalls)
Opts.NoBuiltinFuncs = LangOpts->NoBuiltinFuncs;
Opts.UnrollLoops =
Args.hasFlag(OPT_funroll_loops, OPT_fno_unroll_loops,
(Opts.OptimizationLevel > 1));
Opts.BinutilsVersion =
std::string(Args.getLastArgValue(OPT_fbinutils_version_EQ));
Opts.DebugNameTable = static_cast<unsigned>(
Args.hasArg(OPT_ggnu_pubnames)
? llvm::DICompileUnit::DebugNameTableKind::GNU
: Args.hasArg(OPT_gpubnames)
? llvm::DICompileUnit::DebugNameTableKind::Default
: llvm::DICompileUnit::DebugNameTableKind::None);
if (const Arg *A = Args.getLastArg(OPT_gsimple_template_names_EQ)) {
StringRef Value = A->getValue();
if (Value != "simple" && Value != "mangled")
Diags.Report(diag::err_drv_unsupported_option_argument)
<< A->getOption().getName() << A->getValue();
Opts.setDebugSimpleTemplateNames(
StringRef(A->getValue()) == "simple"
? codegenoptions::DebugTemplateNamesKind::Simple
: codegenoptions::DebugTemplateNamesKind::Mangled);
}
if (!Opts.ProfileInstrumentUsePath.empty())
setPGOUseInstrumentor(Opts, Opts.ProfileInstrumentUsePath);
if (const Arg *A = Args.getLastArg(OPT_ftime_report, OPT_ftime_report_EQ)) {
Opts.TimePasses = true;
// -ftime-report= is only for new pass manager.
if (A->getOption().getID() == OPT_ftime_report_EQ) {
if (Opts.LegacyPassManager)
Diags.Report(diag::err_drv_argument_only_allowed_with)
<< A->getAsString(Args) << "-fno-legacy-pass-manager";
StringRef Val = A->getValue();
if (Val == "per-pass")
Opts.TimePassesPerRun = false;
else if (Val == "per-pass-run")
Opts.TimePassesPerRun = true;
else
Diags.Report(diag::err_drv_invalid_value)
<< A->getAsString(Args) << A->getValue();
}
}
Opts.PrepareForLTO = false;
Opts.PrepareForThinLTO = false;
if (Arg *A = Args.getLastArg(OPT_flto_EQ)) {
Opts.PrepareForLTO = true;
StringRef S = A->getValue();
if (S == "thin")
Opts.PrepareForThinLTO = true;
else if (S != "full")
Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << S;
}
if (Arg *A = Args.getLastArg(OPT_fthinlto_index_EQ)) {
if (IK.getLanguage() != Language::LLVM_IR)
Diags.Report(diag::err_drv_argument_only_allowed_with)
<< A->getAsString(Args) << "-x ir";
Opts.ThinLTOIndexFile =
std::string(Args.getLastArgValue(OPT_fthinlto_index_EQ));
}
if (Arg *A = Args.getLastArg(OPT_save_temps_EQ))
Opts.SaveTempsFilePrefix =
llvm::StringSwitch<std::string>(A->getValue())
.Case("obj", OutputFile)
.Default(llvm::sys::path::filename(OutputFile).str());
// The memory profile runtime appends the pid to make this name more unique.
const char *MemProfileBasename = "memprof.profraw";
if (Args.hasArg(OPT_fmemory_profile_EQ)) {
SmallString<128> Path(
std::string(Args.getLastArgValue(OPT_fmemory_profile_EQ)));
llvm::sys::path::append(Path, MemProfileBasename);
Opts.MemoryProfileOutput = std::string(Path);
} else if (Args.hasArg(OPT_fmemory_profile))
Opts.MemoryProfileOutput = MemProfileBasename;
memcpy(Opts.CoverageVersion, "408*", 4);
if (Opts.EmitGcovArcs || Opts.EmitGcovNotes) {
if (Args.hasArg(OPT_coverage_version_EQ)) {
StringRef CoverageVersion = Args.getLastArgValue(OPT_coverage_version_EQ);
if (CoverageVersion.size() != 4) {
Diags.Report(diag::err_drv_invalid_value)
<< Args.getLastArg(OPT_coverage_version_EQ)->getAsString(Args)
<< CoverageVersion;
} else {
memcpy(Opts.CoverageVersion, CoverageVersion.data(), 4);
}
}
}
// FIXME: For backend options that are not yet recorded as function
// attributes in the IR, keep track of them so we can embed them in a
// separate data section and use them when building the bitcode.
for (const auto &A : Args) {
// Do not encode output and input.
if (A->getOption().getID() == options::OPT_o ||
A->getOption().getID() == options::OPT_INPUT ||
A->getOption().getID() == options::OPT_x ||
A->getOption().getID() == options::OPT_fembed_bitcode ||
A->getOption().matches(options::OPT_W_Group))
continue;
ArgStringList ASL;
A->render(Args, ASL);
for (const auto &arg : ASL) {
StringRef ArgStr(arg);
Opts.CmdArgs.insert(Opts.CmdArgs.end(), ArgStr.begin(), ArgStr.end());
// using \00 to separate each commandline options.
Opts.CmdArgs.push_back('\0');
}
}
auto XRayInstrBundles =
Args.getAllArgValues(OPT_fxray_instrumentation_bundle);
if (XRayInstrBundles.empty())
Opts.XRayInstrumentationBundle.Mask = XRayInstrKind::All;
else
for (const auto &A : XRayInstrBundles)
parseXRayInstrumentationBundle("-fxray-instrumentation-bundle=", A, Args,
Diags, Opts.XRayInstrumentationBundle);
if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
StringRef Name = A->getValue();
if (Name == "full") {
Opts.CFProtectionReturn = 1;
Opts.CFProtectionBranch = 1;
} else if (Name == "return")
Opts.CFProtectionReturn = 1;
else if (Name == "branch")
Opts.CFProtectionBranch = 1;
else if (Name != "none")
Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
}
for (auto *A :
Args.filtered(OPT_mlink_bitcode_file, OPT_mlink_builtin_bitcode)) {
CodeGenOptions::BitcodeFileToLink F;
F.Filename = A->getValue();
if (A->getOption().matches(OPT_mlink_builtin_bitcode)) {
F.LinkFlags = llvm::Linker::Flags::LinkOnlyNeeded;
// When linking CUDA bitcode, propagate function attributes so that
// e.g. libdevice gets fast-math attrs if we're building with fast-math.
F.PropagateAttrs = true;
F.Internalize = true;
}
Opts.LinkBitcodeFiles.push_back(F);
}
if (Args.getLastArg(OPT_femulated_tls) ||
Args.getLastArg(OPT_fno_emulated_tls)) {
Opts.ExplicitEmulatedTLS = true;
}
if (Arg *A = Args.getLastArg(OPT_ftlsmodel_EQ)) {
if (T.isOSAIX()) {
StringRef Name = A->getValue();
if (Name != "global-dynamic")
Diags.Report(diag::err_aix_unsupported_tls_model) << Name;
}
}
if (Arg *A = Args.getLastArg(OPT_fdenormal_fp_math_EQ)) {
StringRef Val = A->getValue();
Opts.FPDenormalMode = llvm::parseDenormalFPAttribute(Val);
if (!Opts.FPDenormalMode.isValid())
Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
}
if (Arg *A = Args.getLastArg(OPT_fdenormal_fp_math_f32_EQ)) {
StringRef Val = A->getValue();
Opts.FP32DenormalMode = llvm::parseDenormalFPAttribute(Val);
if (!Opts.FP32DenormalMode.isValid())
Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
}
// X86_32 has -fppc-struct-return and -freg-struct-return.
// PPC32 has -maix-struct-return and -msvr4-struct-return.
if (Arg *A =
Args.getLastArg(OPT_fpcc_struct_return, OPT_freg_struct_return,
OPT_maix_struct_return, OPT_msvr4_struct_return)) {
// TODO: We might want to consider enabling these options on AIX in the
// future.
if (T.isOSAIX())
Diags.Report(diag::err_drv_unsupported_opt_for_target)
<< A->getSpelling() << T.str();
const Option &O = A->getOption();
if (O.matches(OPT_fpcc_struct_return) ||
O.matches(OPT_maix_struct_return)) {
Opts.setStructReturnConvention(CodeGenOptions::SRCK_OnStack);
} else {
assert(O.matches(OPT_freg_struct_return) ||
O.matches(OPT_msvr4_struct_return));
Opts.setStructReturnConvention(CodeGenOptions::SRCK_InRegs);
}
}
if (Arg *A =
Args.getLastArg(OPT_mabi_EQ_vec_default, OPT_mabi_EQ_vec_extabi)) {
if (!T.isOSAIX())
Diags.Report(diag::err_drv_unsupported_opt_for_target)
<< A->getSpelling() << T.str();
const Option &O = A->getOption();
Opts.EnableAIXExtendedAltivecABI = O.matches(OPT_mabi_EQ_vec_extabi);
}
bool NeedLocTracking = false;
if (!Opts.OptRecordFile.empty())
NeedLocTracking = true;
if (Arg *A = Args.getLastArg(OPT_opt_record_passes)) {
Opts.OptRecordPasses = A->getValue();
NeedLocTracking = true;
}
if (Arg *A = Args.getLastArg(OPT_opt_record_format)) {
Opts.OptRecordFormat = A->getValue();
NeedLocTracking = true;
}
Opts.OptimizationRemark =
ParseOptimizationRemark(Diags, Args, OPT_Rpass_EQ, "pass");
Opts.OptimizationRemarkMissed =
ParseOptimizationRemark(Diags, Args, OPT_Rpass_missed_EQ, "pass-missed");
Opts.OptimizationRemarkAnalysis = ParseOptimizationRemark(
Diags, Args, OPT_Rpass_analysis_EQ, "pass-analysis");
NeedLocTracking |= Opts.OptimizationRemark.hasValidPattern() ||
Opts.OptimizationRemarkMissed.hasValidPattern() ||
Opts.OptimizationRemarkAnalysis.hasValidPattern();
bool UsingSampleProfile = !Opts.SampleProfileFile.empty();
bool UsingProfile = UsingSampleProfile ||
(Opts.getProfileUse() != CodeGenOptions::ProfileNone);
if (Opts.DiagnosticsWithHotness && !UsingProfile &&
// An IR file will contain PGO as metadata
IK.getLanguage() != Language::LLVM_IR)
Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo)
<< "-fdiagnostics-show-hotness";
// Parse remarks hotness threshold. Valid value is either integer or 'auto'.
if (auto *arg =
Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
auto ResultOrErr =
llvm::remarks::parseHotnessThresholdOption(arg->getValue());
if (!ResultOrErr) {
Diags.Report(diag::err_drv_invalid_diagnotics_hotness_threshold)
<< "-fdiagnostics-hotness-threshold=";
} else {
Opts.DiagnosticsHotnessThreshold = *ResultOrErr;
if ((!Opts.DiagnosticsHotnessThreshold.hasValue() ||
Opts.DiagnosticsHotnessThreshold.getValue() > 0) &&
!UsingProfile)
Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo)
<< "-fdiagnostics-hotness-threshold=";
}
}
// If the user requested to use a sample profile for PGO, then the
// backend will need to track source location information so the profile
// can be incorporated into the IR.
if (UsingSampleProfile)
NeedLocTracking = true;
if (!Opts.StackUsageOutput.empty())
NeedLocTracking = true;
// If the user requested a flag that requires source locations available in
// the backend, make sure that the backend tracks source location information.
if (NeedLocTracking && Opts.getDebugInfo() == codegenoptions::NoDebugInfo)
Opts.setDebugInfo(codegenoptions::LocTrackingOnly);
// Parse -fsanitize-recover= arguments.
// FIXME: Report unrecoverable sanitizers incorrectly specified here.
parseSanitizerKinds("-fsanitize-recover=",
Args.getAllArgValues(OPT_fsanitize_recover_EQ), Diags,
Opts.SanitizeRecover);
parseSanitizerKinds("-fsanitize-trap=",
Args.getAllArgValues(OPT_fsanitize_trap_EQ), Diags,
Opts.SanitizeTrap);
Opts.EmitVersionIdentMetadata = Args.hasFlag(OPT_Qy, OPT_Qn, true);
if (Args.hasArg(options::OPT_ffinite_loops))
Opts.FiniteLoops = CodeGenOptions::FiniteLoopsKind::Always;
else if (Args.hasArg(options::OPT_fno_finite_loops))
Opts.FiniteLoops = CodeGenOptions::FiniteLoopsKind::Never;
Opts.EmitIEEENaNCompliantInsts =
Args.hasFlag(options::OPT_mamdgpu_ieee, options::OPT_mno_amdgpu_ieee);
if (!Opts.EmitIEEENaNCompliantInsts && !LangOptsRef.NoHonorNaNs)
Diags.Report(diag::err_drv_amdgpu_ieee_without_no_honor_nans);
return Diags.getNumErrors() == NumErrorsBefore;
}
static void
GenerateDependencyOutputArgs(const DependencyOutputOptions &Opts,
SmallVectorImpl<const char *> &Args,
CompilerInvocation::StringAllocator SA) {
const DependencyOutputOptions &DependencyOutputOpts = Opts;
#define DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING( \
PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
MERGER, EXTRACTOR, TABLE_INDEX) \
GENERATE_OPTION_WITH_MARSHALLING( \
Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \
IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
#include "clang/Driver/Options.inc"
#undef DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING
if (Opts.ShowIncludesDest != ShowIncludesDestination::None)
GenerateArg(Args, OPT_show_includes, SA);
for (const auto &Dep : Opts.ExtraDeps) {
switch (Dep.second) {
case EDK_SanitizeIgnorelist:
// Sanitizer ignorelist arguments are generated from LanguageOptions.
continue;
case EDK_ModuleFile:
// Module file arguments are generated from FrontendOptions and
// HeaderSearchOptions.
continue;
case EDK_ProfileList:
// Profile list arguments are generated from LanguageOptions via the
// marshalling infrastructure.
continue;
case EDK_DepFileEntry:
GenerateArg(Args, OPT_fdepfile_entry, Dep.first, SA);
break;
}
}
}
static bool ParseDependencyOutputArgs(DependencyOutputOptions &Opts,
ArgList &Args, DiagnosticsEngine &Diags,
frontend::ActionKind Action,
bool ShowLineMarkers) {
unsigned NumErrorsBefore = Diags.getNumErrors();
DependencyOutputOptions &DependencyOutputOpts = Opts;
#define DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING( \
PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
MERGER, EXTRACTOR, TABLE_INDEX) \
PARSE_OPTION_WITH_MARSHALLING( \
Args, Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \
IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
#include "clang/Driver/Options.inc"
#undef DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING
if (Args.hasArg(OPT_show_includes)) {
// Writing both /showIncludes and preprocessor output to stdout
// would produce interleaved output, so use stderr for /showIncludes.
// This behaves the same as cl.exe, when /E, /EP or /P are passed.
if (Action == frontend::PrintPreprocessedInput || !ShowLineMarkers)
Opts.ShowIncludesDest = ShowIncludesDestination::Stderr;
else
Opts.ShowIncludesDest = ShowIncludesDestination::Stdout;
} else {
Opts.ShowIncludesDest = ShowIncludesDestination::None;
}
// Add sanitizer ignorelists as extra dependencies.
// They won't be discovered by the regular preprocessor, so
// we let make / ninja to know about this implicit dependency.
if (!Args.hasArg(OPT_fno_sanitize_ignorelist)) {
for (const auto *A : Args.filtered(OPT_fsanitize_ignorelist_EQ)) {
StringRef Val = A->getValue();
if (!Val.contains('='))
Opts.ExtraDeps.emplace_back(std::string(Val), EDK_SanitizeIgnorelist);
}
if (Opts.IncludeSystemHeaders) {
for (const auto *A : Args.filtered(OPT_fsanitize_system_ignorelist_EQ)) {
StringRef Val = A->getValue();
if (!Val.contains('='))
Opts.ExtraDeps.emplace_back(std::string(Val), EDK_SanitizeIgnorelist);
}
}
}
// -fprofile-list= dependencies.
for (const auto &Filename : Args.getAllArgValues(OPT_fprofile_list_EQ))
Opts.ExtraDeps.emplace_back(Filename, EDK_ProfileList);
// Propagate the extra dependencies.
for (const auto *A : Args.filtered(OPT_fdepfile_entry))
Opts.ExtraDeps.emplace_back(A->getValue(), EDK_DepFileEntry);
// Only the -fmodule-file=<file> form.
for (const auto *A : Args.filtered(OPT_fmodule_file)) {
StringRef Val = A->getValue();
if (!Val.contains('='))
Opts.ExtraDeps.emplace_back(std::string(Val), EDK_ModuleFile);
}
return Diags.getNumErrors() == NumErrorsBefore;
}
static bool parseShowColorsArgs(const ArgList &Args, bool DefaultColor) {
// Color diagnostics default to auto ("on" if terminal supports) in the driver
// but default to off in cc1, needing an explicit OPT_fdiagnostics_color.
// Support both clang's -f[no-]color-diagnostics and gcc's
// -f[no-]diagnostics-colors[=never|always|auto].
enum {
Colors_On,
Colors_Off,
Colors_Auto
} ShowColors = DefaultColor ? Colors_Auto : Colors_Off;
for (auto *A : Args) {
const Option &O = A->getOption();
if (O.matches(options::OPT_fcolor_diagnostics) ||
O.matches(options::OPT_fdiagnostics_color)) {
ShowColors = Colors_On;
} else if (O.matches(options::OPT_fno_color_diagnostics) ||
O.matches(options::OPT_fno_diagnostics_color)) {
ShowColors = Colors_Off;
} else if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
StringRef Value(A->getValue());
if (Value == "always")
ShowColors = Colors_On;
else if (Value == "never")
ShowColors = Colors_Off;
else if (Value == "auto")
ShowColors = Colors_Auto;
}
}
return ShowColors == Colors_On ||
(ShowColors == Colors_Auto &&
llvm::sys::Process::StandardErrHasColors());
}
static bool checkVerifyPrefixes(const std::vector<std::string> &VerifyPrefixes,
DiagnosticsEngine &Diags) {
bool Success = true;
for (const auto &Prefix : VerifyPrefixes) {
// Every prefix must start with a letter and contain only alphanumeric
// characters, hyphens, and underscores.
auto BadChar = llvm::find_if(Prefix, [](char C) {
return !isAlphanumeric(C) && C != '-' && C != '_';
});
if (BadChar != Prefix.end() || !isLetter(Prefix[0])) {
Success = false;
Diags.Report(diag::err_drv_invalid_value) << "-verify=" << Prefix;
Diags.Report(diag::note_drv_verify_prefix_spelling);
}
}
return Success;
}
static void GenerateFileSystemArgs(const FileSystemOptions &Opts,
SmallVectorImpl<const char *> &Args,
CompilerInvocation::StringAllocator SA) {
const FileSystemOptions &FileSystemOpts = Opts;
#define FILE_SYSTEM_OPTION_WITH_MARSHALLING( \
PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
MERGER, EXTRACTOR, TABLE_INDEX) \
GENERATE_OPTION_WITH_MARSHALLING( \
Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \
IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
#include "clang/Driver/Options.inc"
#undef FILE_SYSTEM_OPTION_WITH_MARSHALLING
}
static bool ParseFileSystemArgs(FileSystemOptions &Opts, const ArgList &Args,
DiagnosticsEngine &Diags) {
unsigned NumErrorsBefore = Diags.getNumErrors();
FileSystemOptions &FileSystemOpts = Opts;
#define FILE_SYSTEM_OPTION_WITH_MARSHALLING( \
PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
MERGER, EXTRACTOR, TABLE_INDEX) \
PARSE_OPTION_WITH_MARSHALLING( \
Args, Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \
IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
#include "clang/Driver/Options.inc"
#undef FILE_SYSTEM_OPTION_WITH_MARSHALLING
return Diags.getNumErrors() == NumErrorsBefore;
}
static void GenerateMigratorArgs(const MigratorOptions &Opts,
SmallVectorImpl<const char *> &Args,
CompilerInvocation::StringAllocator SA) {
const MigratorOptions &MigratorOpts = Opts;
#define MIGRATOR_OPTION_WITH_MARSHALLING( \
PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
MERGER, EXTRACTOR, TABLE_INDEX) \
GENERATE_OPTION_WITH_MARSHALLING( \
Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \
IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
#include "clang/Driver/Options.inc"
#undef MIGRATOR_OPTION_WITH_MARSHALLING
}
static bool ParseMigratorArgs(MigratorOptions &Opts, const ArgList &Args,
DiagnosticsEngine &Diags) {
unsigned NumErrorsBefore = Diags.getNumErrors();
MigratorOptions &MigratorOpts = Opts;
#define MIGRATOR_OPTION_WITH_MARSHALLING( \
PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
MERGER, EXTRACTOR, TABLE_INDEX) \
PARSE_OPTION_WITH_MARSHALLING( \
Args, Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \
IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
#include "clang/Driver/Options.inc"
#undef MIGRATOR_OPTION_WITH_MARSHALLING
return Diags.getNumErrors() == NumErrorsBefore;
}
void CompilerInvocation::GenerateDiagnosticArgs(
const DiagnosticOptions &Opts, SmallVectorImpl<const char *> &Args,
StringAllocator SA, bool DefaultDiagColor) {
const DiagnosticOptions *DiagnosticOpts = &Opts;
#define DIAG_OPTION_WITH_MARSHALLING( \
PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
MERGER, EXTRACTOR, TABLE_INDEX) \
GENERATE_OPTION_WITH_MARSHALLING( \
Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \
IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
#include "clang/Driver/Options.inc"
#undef DIAG_OPTION_WITH_MARSHALLING
if (!Opts.DiagnosticSerializationFile.empty())
GenerateArg(Args, OPT_diagnostic_serialized_file,
Opts.DiagnosticSerializationFile, SA);
if (Opts.ShowColors)
GenerateArg(Args, OPT_fcolor_diagnostics, SA);
if (Opts.VerifyDiagnostics &&
llvm::is_contained(Opts.VerifyPrefixes, "expected"))
GenerateArg(Args, OPT_verify, SA);
for (const auto &Prefix : Opts.VerifyPrefixes)
if (Prefix != "expected")
GenerateArg(Args, OPT_verify_EQ, Prefix, SA);
DiagnosticLevelMask VIU = Opts.getVerifyIgnoreUnexpected();
if (VIU == DiagnosticLevelMask::None) {
// This is the default, don't generate anything.
} else if (VIU == DiagnosticLevelMask::All) {
GenerateArg(Args, OPT_verify_ignore_unexpected, SA);
} else {
if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Note) != 0)
GenerateArg(Args, OPT_verify_ignore_unexpected_EQ, "note", SA);
if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Remark) != 0)
GenerateArg(Args, OPT_verify_ignore_unexpected_EQ, "remark", SA);
if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Warning) != 0)
GenerateArg(Args, OPT_verify_ignore_unexpected_EQ, "warning", SA);
if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Error) != 0)
GenerateArg(Args, OPT_verify_ignore_unexpected_EQ, "error", SA);
}
for (const auto &Warning : Opts.Warnings) {
// This option is automatically generated from UndefPrefixes.
if (Warning == "undef-prefix")
continue;
Args.push_back(SA(StringRef("-W") + Warning));
}
for (const auto &Remark : Opts.Remarks) {
// These arguments are generated from OptimizationRemark fields of
// CodeGenOptions.
StringRef IgnoredRemarks[] = {"pass", "no-pass",
"pass-analysis", "no-pass-analysis",
"pass-missed", "no-pass-missed"};
if (llvm::is_contained(IgnoredRemarks, Remark))
continue;
Args.push_back(SA(StringRef("-R") + Remark));
}
}
std::unique_ptr<DiagnosticOptions>
clang::CreateAndPopulateDiagOpts(ArrayRef<const char *> Argv) {
auto DiagOpts = std::make_unique<DiagnosticOptions>();
unsigned MissingArgIndex, MissingArgCount;
InputArgList Args = getDriverOptTable().ParseArgs(
Argv.slice(1), MissingArgIndex, MissingArgCount);
// We ignore MissingArgCount and the return value of ParseDiagnosticArgs.
// Any errors that would be diagnosed here will also be diagnosed later,
// when the DiagnosticsEngine actually exists.
(void)ParseDiagnosticArgs(*DiagOpts, Args);
return DiagOpts;
}
bool clang::ParseDiagnosticArgs(DiagnosticOptions &Opts, ArgList &Args,
DiagnosticsEngine *Diags,
bool DefaultDiagColor) {
Optional<DiagnosticsEngine> IgnoringDiags;
if (!Diags) {
IgnoringDiags.emplace(new DiagnosticIDs(), new DiagnosticOptions(),
new IgnoringDiagConsumer());
Diags = &*IgnoringDiags;
}
unsigned NumErrorsBefore = Diags->getNumErrors();
// The key paths of diagnostic options defined in Options.td start with
// "DiagnosticOpts->". Let's provide the expected variable name and type.
DiagnosticOptions *DiagnosticOpts = &Opts;
#define DIAG_OPTION_WITH_MARSHALLING( \
PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
MERGER, EXTRACTOR, TABLE_INDEX) \
PARSE_OPTION_WITH_MARSHALLING( \
Args, *Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \
IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
#include "clang/Driver/Options.inc"
#undef DIAG_OPTION_WITH_MARSHALLING
llvm::sys::Process::UseANSIEscapeCodes(Opts.UseANSIEscapeCodes);
if (Arg *A =
Args.getLastArg(OPT_diagnostic_serialized_file, OPT__serialize_diags))
Opts.DiagnosticSerializationFile = A->getValue();
Opts.ShowColors = parseShowColorsArgs(Args, DefaultDiagColor);
Opts.VerifyDiagnostics = Args.hasArg(OPT_verify) || Args.hasArg(OPT_verify_EQ);
Opts.VerifyPrefixes = Args.getAllArgValues(OPT_verify_EQ);
if (Args.hasArg(OPT_verify))
Opts.VerifyPrefixes.push_back("expected");
// Keep VerifyPrefixes in its original order for the sake of diagnostics, and
// then sort it to prepare for fast lookup using std::binary_search.
if (!checkVerifyPrefixes(Opts.VerifyPrefixes, *Diags))
Opts.VerifyDiagnostics = false;
else
llvm::sort(Opts.VerifyPrefixes);
DiagnosticLevelMask DiagMask = DiagnosticLevelMask::None;
parseDiagnosticLevelMask(
"-verify-ignore-unexpected=",
Args.getAllArgValues(OPT_verify_ignore_unexpected_EQ), *Diags, DiagMask);
if (Args.hasArg(OPT_verify_ignore_unexpected))
DiagMask = DiagnosticLevelMask::All;
Opts.setVerifyIgnoreUnexpected(DiagMask);
if (Opts.TabStop == 0 || Opts.TabStop > DiagnosticOptions::MaxTabStop) {
Opts.TabStop = DiagnosticOptions::DefaultTabStop;
Diags->Report(diag::warn_ignoring_ftabstop_value)
<< Opts.TabStop << DiagnosticOptions::DefaultTabStop;
}
addDiagnosticArgs(Args, OPT_W_Group, OPT_W_value_Group, Opts.Warnings);
addDiagnosticArgs(Args, OPT_R_Group, OPT_R_value_Group, Opts.Remarks);
return Diags->getNumErrors() == NumErrorsBefore;
}
/// Parse the argument to the -ftest-module-file-extension
/// command-line argument.
///
/// \returns true on error, false on success.
static bool parseTestModuleFileExtensionArg(StringRef Arg,
std::string &BlockName,
unsigned &MajorVersion,
unsigned &MinorVersion,
bool &Hashed,
std::string &UserInfo) {
SmallVector<StringRef, 5> Args;
Arg.split(Args, ':', 5);
if (Args.size() < 5)
return true;
BlockName = std::string(Args[0]);
if (Args[1].getAsInteger(10, MajorVersion)) return true;
if (Args[2].getAsInteger(10, MinorVersion)) return true;
if (Args[3].getAsInteger(2, Hashed)) return true;
if (Args.size() > 4)
UserInfo = std::string(Args[4]);
return false;
}
/// Return a table that associates command line option specifiers with the
/// frontend action. Note: The pair {frontend::PluginAction, OPT_plugin} is
/// intentionally missing, as this case is handled separately from other
/// frontend options.
static const auto &getFrontendActionTable() {
static const std::pair<frontend::ActionKind, unsigned> Table[] = {
{frontend::ASTDeclList, OPT_ast_list},
{frontend::ASTDump, OPT_ast_dump_all_EQ},
{frontend::ASTDump, OPT_ast_dump_all},
{frontend::ASTDump, OPT_ast_dump_EQ},
{frontend::ASTDump, OPT_ast_dump},
{frontend::ASTDump, OPT_ast_dump_lookups},
{frontend::ASTDump, OPT_ast_dump_decl_types},
{frontend::ASTPrint, OPT_ast_print},
{frontend::ASTView, OPT_ast_view},
{frontend::DumpCompilerOptions, OPT_compiler_options_dump},
{frontend::DumpRawTokens, OPT_dump_raw_tokens},
{frontend::DumpTokens, OPT_dump_tokens},
{frontend::EmitAssembly, OPT_S},
{frontend::EmitBC, OPT_emit_llvm_bc},
{frontend::EmitHTML, OPT_emit_html},
{frontend::EmitLLVM, OPT_emit_llvm},
{frontend::EmitLLVMOnly, OPT_emit_llvm_only},
{frontend::EmitCodeGenOnly, OPT_emit_codegen_only},
{frontend::EmitCodeGenOnly, OPT_emit_codegen_only},
{frontend::EmitObj, OPT_emit_obj},
{frontend::FixIt, OPT_fixit_EQ},
{frontend::FixIt, OPT_fixit},
{frontend::GenerateModule, OPT_emit_module},
{frontend::GenerateModuleInterface, OPT_emit_module_interface},
{frontend::GenerateHeaderModule, OPT_emit_header_module},
{frontend::GeneratePCH, OPT_emit_pch},
{frontend::GenerateInterfaceStubs, OPT_emit_interface_stubs},
{frontend::InitOnly, OPT_init_only},
{frontend::ParseSyntaxOnly, OPT_fsyntax_only},
{frontend::ModuleFileInfo, OPT_module_file_info},
{frontend::VerifyPCH, OPT_verify_pch},
{frontend::PrintPreamble, OPT_print_preamble},
{frontend::PrintPreprocessedInput, OPT_E},
{frontend::TemplightDump, OPT_templight_dump},
{frontend::RewriteMacros, OPT_rewrite_macros},
{frontend::RewriteObjC, OPT_rewrite_objc},
{frontend::RewriteTest, OPT_rewrite_test},
{frontend::RunAnalysis, OPT_analyze},
{frontend::MigrateSource, OPT_migrate},
{frontend::RunPreprocessorOnly, OPT_Eonly},
{frontend::PrintDependencyDirectivesSourceMinimizerOutput,
OPT_print_dependency_directives_minimized_source},
};
return Table;
}
/// Maps command line option to frontend action.
static Optional<frontend::ActionKind> getFrontendAction(OptSpecifier &Opt) {
for (const auto &ActionOpt : getFrontendActionTable())
if (ActionOpt.second == Opt.getID())
return ActionOpt.first;
return None;
}
/// Maps frontend action to command line option.
static Optional<OptSpecifier>
getProgramActionOpt(frontend::ActionKind ProgramAction) {
for (const auto &ActionOpt : getFrontendActionTable())
if (ActionOpt.first == ProgramAction)
return OptSpecifier(ActionOpt.second);
return None;
}
static void GenerateFrontendArgs(const FrontendOptions &Opts,
SmallVectorImpl<const char *> &Args,
CompilerInvocation::StringAllocator SA,
bool IsHeader) {
const FrontendOptions &FrontendOpts = Opts;
#define FRONTEND_OPTION_WITH_MARSHALLING( \
PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
MERGER, EXTRACTOR, TABLE_INDEX) \
GENERATE_OPTION_WITH_MARSHALLING( \
Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \
IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
#include "clang/Driver/Options.inc"
#undef FRONTEND_OPTION_WITH_MARSHALLING
Optional<OptSpecifier> ProgramActionOpt =
getProgramActionOpt(Opts.ProgramAction);
// Generating a simple flag covers most frontend actions.
std::function<void()> GenerateProgramAction = [&]() {
GenerateArg(Args, *ProgramActionOpt, SA);
};
if (!ProgramActionOpt) {
// PluginAction is the only program action handled separately.
assert(Opts.ProgramAction == frontend::PluginAction &&
"Frontend action without option.");
GenerateProgramAction = [&]() {
GenerateArg(Args, OPT_plugin, Opts.ActionName, SA);
};
}
// FIXME: Simplify the complex 'AST dump' command line.
if (Opts.ProgramAction == frontend::ASTDump) {
GenerateProgramAction = [&]() {
// ASTDumpLookups, ASTDumpDeclTypes and ASTDumpFilter are generated via
// marshalling infrastructure.
if (Opts.ASTDumpFormat != ADOF_Default) {
StringRef Format;
switch (Opts.ASTDumpFormat) {
case ADOF_Default:
llvm_unreachable("Default AST dump format.");
case ADOF_JSON:
Format = "json";
break;
}
if (Opts.ASTDumpAll)
GenerateArg(Args, OPT_ast_dump_all_EQ, Format, SA);
if (Opts.ASTDumpDecls)
GenerateArg(Args, OPT_ast_dump_EQ, Format, SA);
} else {
if (Opts.ASTDumpAll)
GenerateArg(Args, OPT_ast_dump_all, SA);
if (Opts.ASTDumpDecls)
GenerateArg(Args, OPT_ast_dump, SA);
}
};
}
if (Opts.ProgramAction == frontend::FixIt && !Opts.FixItSuffix.empty()) {
GenerateProgramAction = [&]() {
GenerateArg(Args, OPT_fixit_EQ, Opts.FixItSuffix, SA);
};
}
GenerateProgramAction();
for (const auto &PluginArgs : Opts.PluginArgs) {
Option Opt = getDriverOptTable().getOption(OPT_plugin_arg);
const char *Spelling =
SA(Opt.getPrefix() + Opt.getName() + PluginArgs.first);
for (const auto &PluginArg : PluginArgs.second)
denormalizeString(Args, Spelling, SA, Opt.getKind(), 0, PluginArg);
}
for (const auto &