31#include "llvm/Config/config.h"
53#define DEBUG_TYPE "commandline"
74#if !(defined(LLVM_ENABLE_LLVM_EXPORT_ANNOTATIONS) && defined(_MSC_VER))
91void GenericOptionValue::anchor() {}
92void OptionValue<boolOrDefault>::anchor() {}
93void OptionValue<std::string>::anchor() {}
94void Option::anchor() {}
129 size_t Len = ArgName.
size();
137 for (
size_t I = 0;
I < Pad; ++
I) {
157 OS <<
argPrefix(Arg.ArgName, Arg.Pad) << Arg.ArgName;
161class CommandLineParser {
165 std::string ProgramName;
169 std::vector<StringRef> MoreHelp;
181 size_t NumIndexedLibraries = 0;
202 if (Opt.
Subs.empty()) {
207 for (
auto *SC : RegisteredSubCommands)
212 for (
auto *SC : Opt.
Subs) {
214 "SubCommand::getAll() should not be used with other subcommands");
223 errs() << ProgramName <<
": CommandLine Error: Option '" << Name
224 <<
"' registered more than once!\n";
231 Opt, [&](
SubCommand &SC) { addLiteralOption(Opt, &SC, Name); });
235 bool HadErrors =
false;
236 if (O->hasArgStr()) {
241 (RegisteredSubCommands.
contains(SC) &&
242 (LibraryIndex.
contains(O->ArgStr) ||
244 errs() << ProgramName <<
": CommandLine Error: Option '" << O->ArgStr
245 <<
"' registered more than once!\n";
255 O->error(
"Cannot specify more than one option with cl::ConsumeAfter!");
269 void addOption(
Option *O) {
270 forEachSubCommand(*O, [&](
SubCommand &SC) { addOption(O, &SC); });
275 O->getExtraOptionNames(OptionNames);
280 for (
auto Name : OptionNames) {
281 auto I =
Sub.OptionsMap.find(Name);
284 if (
I !=
Sub.OptionsMap.end() &&
I->second == O)
285 Sub.OptionsMap.erase(
I);
289 for (
auto *Opt =
Sub.PositionalOpts.begin();
290 Opt !=
Sub.PositionalOpts.end(); ++Opt) {
292 Sub.PositionalOpts.erase(Opt);
296 else if (O ==
Sub.ConsumeAfterOpt)
297 Sub.ConsumeAfterOpt =
nullptr;
300 void removeOption(
Option *O) {
301 forEachSubCommand(*O, [&](
SubCommand &SC) { removeOption(O, &SC); });
305 return (!
Sub.OptionsMap.empty() || !
Sub.PositionalOpts.empty() ||
306 nullptr !=
Sub.ConsumeAfterOpt);
309 bool hasOptions()
const {
310 for (
const auto *S : RegisteredSubCommands) {
314 return !Libraries.
empty();
317 bool hasNamedSubCommands()
const {
318 for (
const auto *S : RegisteredSubCommands)
319 if (!S->getName().empty())
324 SubCommand *getActiveSubCommand() {
return ActiveSubCommand; }
328 if (!
Sub.OptionsMap.insert(std::make_pair(NewName, O)).second) {
329 errs() << ProgramName <<
": CommandLine Error: Option '" << O->ArgStr
330 <<
"' registered more than once!\n";
333 Sub.OptionsMap.erase(O->ArgStr);
337 forEachSubCommand(*O,
338 [&](
SubCommand &SC) { updateArgStr(O, NewName, &SC); });
341 void printOptionValues();
347 bool HadErrors =
false;
351 auto [It, Inserted] = Index.try_emplace(Name, L);
352 if (Inserted ? !
Other.contains(Name) &&
359 errs() << ProgramName <<
": CommandLine Error: Option '" << Name
360 <<
"' registered more than once!\n";
368 void indexLibraryOptions() {
369 indexLibraries(
ArrayRef(Libraries).drop_front(NumIndexedLibraries),
370 LibraryIndex, ToolIndex);
371 NumIndexedLibraries = Libraries.
size();
379 indexLibraries(ToolOptions, ToolIndex, LibraryIndex);
384 indexLibraryOptions();
387 return ToolIndex.
lookup(Name);
393 return cat->getName() == Category->getName();
395 "Duplicate option categories");
403 return (!
sub->getName().empty()) &&
404 (
Sub->getName() ==
sub->getName());
406 "Duplicate subcommands");
412 "SubCommand::getAll() should not be registered");
415 if (O->isPositional() || O->isConsumeAfter() || O->hasArgStr())
418 addLiteralOption(*O,
sub,
E.first);
429 RegisteredSubCommands.
end());
433 ActiveSubCommand =
nullptr;
438 RegisteredOptionCategories.
clear();
441 RegisteredSubCommands.
clear();
443 LibraryIndex.
clear();
444 NumIndexedLibraries = 0;
469 return *GlobalParser;
481 const char *
Saved[2];
482 unsigned NumArgs = std::min<size_t>(Args.size(), 2);
483 for (
unsigned J = 0; J != NumArgs; ++J)
493template <
typename T, T TrueVal, T FalseVal>
497 if (!Arg.
data() || Arg ==
"true" || Arg ==
"1") {
502 if (Arg ==
"false" || Arg ==
"0") {
506 return O.error(
"'" + Arg +
507 "' is invalid value for boolean argument! Try 0 or 1");
519 : NumOccurrences(0), Occurrences(OccurrencesFlag), Value(0),
521 FullyInitialized(
false), Position(0) {
527 FullyInitialized =
true;
533 if (FullyInitialized)
555void OptionCategory::registerCategory() {
566 return *TopLevelSubCommand;
572 return *AllSubCommands;
590SubCommand::operator
bool()
const {
608 size_t EqualPos = Arg.
find(
'=');
613 return Sub.OptionsMap.lookup(Arg);
619 auto I =
Sub.OptionsMap.find(Arg.
substr(0, EqualPos));
620 if (
I ==
Sub.OptionsMap.end())
628 Arg = Arg.
substr(0, EqualPos);
633 std::string &NearestString) {
638 for (
auto *S : RegisteredSubCommands) {
640 "SubCommand::getAll() is not expected in RegisteredSubCommands");
641 if (S->getName().empty())
644 if (S->getName() == Name)
647 if (!NearestMatch && S->getName().edit_distance(Name) < 2)
652 NearestString = NearestMatch->
getName();
663 std::string &NearestString) {
669 std::pair<StringRef, StringRef> SplitArg = Arg.
split(
'=');
675 unsigned BestDistance = 0;
676 for (
const auto &[
_, O] : OptionsMap) {
682 O->getExtraOptionNames(OptionNames);
688 for (
const auto &Name : OptionNames) {
690 Flag,
true, BestDistance);
691 if (!Best || Distance < BestDistance) {
693 BestDistance = Distance;
694 if (
RHS.empty() || !PermitValue)
695 NearestString = std::string(Name);
697 NearestString = (
Twine(Name) +
"=" +
RHS).str();
720 Val = Val.
substr(Pos + 1);
736 const char *
const *argv,
int &i) {
744 return Handler->
error(
"requires a value!");
746 assert(argv &&
"null check");
771 for (; !Name.empty(); Name = Name.drop_back()) {
773 if (O && (O->getFormattingFlag() ==
cl::Prefix ||
818 return C ==
' ' ||
C ==
'\t' ||
C ==
'\r' ||
C ==
'\n';
825static bool isQuote(
char C) {
return C ==
'\"' ||
C ==
'\''; }
831 bool InToken =
false;
832 for (
size_t I = 0, E = Src.size();
I != E; ++
I) {
837 if (MarkEOLs && Src[
I] ==
'\n')
849 if (
I + 1 < E &&
C ==
'\\') {
858 while (
I != E && Src[
I] !=
C) {
860 if (Src[
I] ==
'\\' &&
I + 1 != E)
874 if (MarkEOLs &&
C ==
'\n')
908 size_t E = Src.size();
909 int BackslashCount = 0;
914 }
while (
I !=
E && Src[
I] ==
'\\');
916 bool FollowedByDoubleQuote = (
I !=
E && Src[
I] ==
'"');
917 if (FollowedByDoubleQuote) {
918 Token.
append(BackslashCount / 2,
'\\');
919 if (BackslashCount % 2 == 0)
924 Token.
append(BackslashCount,
'\\');
942 bool AlwaysCopy,
function_ref<
void()> MarkEOL,
bool InitialCommandName) {
951 bool CommandName = InitialCommandName;
954 enum {
INIT, UNQUOTED, QUOTED } State =
INIT;
956 for (
size_t I = 0,
E = Src.size();
I <
E; ++
I) {
959 assert(Token.
empty() &&
"token should be empty in initial state");
981 AddToken(AlwaysCopy ? Saver.
save(NormalChars) : NormalChars);
982 if (
I <
E && Src[
I] ==
'\n') {
984 CommandName = InitialCommandName;
988 }
else if (Src[
I] ==
'\"') {
989 Token += NormalChars;
991 }
else if (Src[
I] ==
'\\') {
992 assert(!CommandName &&
"or else we'd have treated it as a normal char");
993 Token += NormalChars;
1007 AddToken(Saver.
save(Token.
str()));
1009 if (Src[
I] ==
'\n') {
1010 CommandName = InitialCommandName;
1013 CommandName =
false;
1016 }
else if (Src[
I] ==
'\"') {
1018 }
else if (Src[
I] ==
'\\' && !CommandName) {
1026 if (Src[
I] ==
'\"') {
1027 if (
I < (
E - 1) && Src[
I + 1] ==
'"') {
1036 }
else if (Src[
I] ==
'\\' && !CommandName) {
1046 AddToken(Saver.
save(Token.
str()));
1053 auto OnEOL = [&]() {
1058 true, OnEOL,
false);
1064 auto OnEOL = []() {};
1073 auto OnEOL = [&]() {
1084 for (
const char *Cur = Source.begin(); Cur != Source.end();) {
1093 while (Cur != Source.end() && *Cur !=
'\n')
1101 const char *Start = Cur;
1102 const char *LineEnd =
nullptr;
1104 bool AtTokenStart =
true;
1105 for (
const char *
End = Source.end(); Cur !=
End; ++Cur) {
1108 if (Cur + 1 !=
End) {
1111 (*Cur ==
'\r' && (Cur + 1 !=
End) && Cur[1] ==
'\n')) {
1112 Line.append(Start, Cur - 1);
1120 AtTokenStart =
false;
1130 }
else if (
C ==
'#' && AtTokenStart) {
1132 while (Cur !=
End && *Cur !=
'\n')
1139 Line.append(Start, LineEnd ? LineEnd : Cur);
1147 return (S.
size() >= 3 && S[0] ==
'\xef' && S[1] ==
'\xbb' && S[2] ==
'\xbf');
1161 TokenPos = ArgString.
find(Token, StartPos)) {
1165 if (ResponseFile.
empty())
1169 ResponseFile.
append(BasePath);
1170 StartPos = TokenPos + Token.
size();
1173 if (!ResponseFile.
empty()) {
1176 if (!Remaining.
empty())
1183Error ExpansionContext::expandResponseFile(
1184 StringRef FName, SmallVectorImpl<const char *> &NewArgv) {
1186 llvm::ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
1187 FS->getBufferForFile(FName);
1191 "': " +
EC.message());
1193 MemoryBuffer &MemBuf = *MemBufOrErr.
get();
1198 std::string UTF8Buf;
1202 "Could not convert UTF16 to UTF8");
1203 Str = StringRef(UTF8Buf);
1209 Str = StringRef(BufRef.data() + 3, BufRef.size() - 3);
1212 Tokenizer(Str, Saver, NewArgv, MarkEOLs);
1217 if (!RelativeNames && !InConfigFile)
1221 for (
const char *&Arg : NewArgv) {
1231 StringRef ArgStr(Arg);
1233 bool ConfigInclusion =
false;
1234 if (ArgStr.consume_front(
"@")) {
1238 }
else if (ArgStr.consume_front(
"--config=")) {
1240 ConfigInclusion =
true;
1246 SmallString<128> ResponseFile;
1249 SmallString<128> FilePath;
1252 std::make_error_code(std::errc::no_such_file_or_directory),
1253 "cannot not find configuration file: " + FileName);
1254 ResponseFile.
append(FilePath);
1256 ResponseFile.
append(BasePath);
1259 Arg = Saver.save(ResponseFile.
str()).
data();
1268 struct ResponseFileRecord {
1283 for (
unsigned I = 0;
I != Argv.
size();) {
1284 while (
I == FileStack.
back().End) {
1290 const char *Arg = Argv[
I];
1292 if (Arg ==
nullptr) {
1297 if (Arg[0] !=
'@') {
1302 const char *FName = Arg + 1;
1307 if (CurrentDir.empty()) {
1308 if (
auto CWD = FS->getCurrentWorkingDirectory()) {
1312 CWD.getError(),
Twine(
"cannot get absolute path for: ") + FName);
1315 CurrDir = CurrentDir;
1318 FName = CurrDir.
c_str();
1322 if (!Res || !Res->exists()) {
1323 std::error_code EC = Res.
getError();
1324 if (!InConfigFile) {
1335 "': " + EC.message());
1340 [FileStatus,
this](
const ResponseFileRecord &RFile) ->
ErrorOr<bool> {
1352 R.getError(),
Twine(
"recursive expansion of: '") +
F.File +
"'");
1355 Twine(
"cannot open file: ") +
F.File);
1362 if (
Error Err = expandResponseFile(FName, ExpandedArgv))
1365 for (ResponseFileRecord &
Record : FileStack) {
1396 Tokenize(*EnvValue, Saver, NewArgv,
false);
1399 NewArgv.
append(Argv + 1, Argv + Argc);
1420 : Saver(
A), Tokenizer(
T), FS(FS ? FS :
vfs::getRealFileSystem().
get()) {}
1426 auto Status = FS->status(Path);
1434 CfgFilePath = FileName;
1437 if (!FileExists(CfgFilePath))
1444 for (
const StringRef &Dir : SearchDirs) {
1450 if (FileExists(CfgFilePath)) {
1464 if (std::error_code EC = FS->makeAbsolute(AbsPath))
1466 EC,
Twine(
"cannot get absolute path for " + CfgFile));
1467 CfgFile = AbsPath.
str();
1469 InConfigFile =
true;
1470 RelativeNames =
true;
1471 if (
Error Err = expandResponseFile(CfgFile, Argv))
1484 StringSaver Saver(
A);
1489 if (std::optional<std::string> EnvValue =
1496 int NewArgc =
static_cast<int>(NewArgv.
size());
1500 NewArgc, &NewArgv[0], Overview, Errs, VFS,
Context, ToolOptions);
1524 EnvVar, ToolOptions);
1528void CommandLineParser::ResetAllOptionOccurrences() {
1532 for (
auto *SC : RegisteredSubCommands) {
1536 Opts.
reserve(SC->OptionsMap.size());
1537 for (
auto &O : SC->OptionsMap)
1541 for (
Option *O : SC->PositionalOpts)
1543 if (SC->ConsumeAfterOpt)
1544 SC->ConsumeAfterOpt->reset();
1549 LibraryArgAlloc.Reset();
1552bool CommandLineParser::ParseCommandLineOptions(
1556 assert((hasOptions() || !Tools.
empty()) &&
"No options specified!");
1558 ProgramOverview = Overview;
1559 bool IgnoreErrors = Errs;
1564 bool ErrorParsing =
false;
1575 if (
Error Err = ECtx.expandResponseFiles(newArgv)) {
1576 *Errs <<
toString(std::move(Err)) <<
'\n';
1580 argc =
static_cast<int>(newArgv.size());
1584 setToolOptions(Tools);
1585 indexLibraryOptions();
1588 unsigned NumPositionalRequired = 0;
1591 bool HasUnlimitedPositionals =
false;
1595 std::string NearestSubCommandString;
1596 bool MaybeNamedSubCommand =
1597 argc >= 2 && argv[FirstArg][0] !=
'-' && hasNamedSubCommands();
1598 if (MaybeNamedSubCommand) {
1602 LookupSubCommand(
StringRef(argv[FirstArg]), NearestSubCommandString);
1608 assert(ChosenSubCommand);
1611 auto &OptionsMap = ChosenSubCommand->
OptionsMap;
1613 if (ConsumeAfterOpt) {
1614 assert(PositionalOpts.size() > 0 &&
1615 "Cannot specify cl::ConsumeAfter without a positional argument!");
1617 if (!PositionalOpts.empty()) {
1620 bool UnboundedFound =
false;
1621 for (
size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
1622 Option *Opt = PositionalOpts[i];
1624 ++NumPositionalRequired;
1625 else if (ConsumeAfterOpt) {
1628 if (PositionalOpts.size() > 1) {
1630 Opt->
error(
"error - this positional option will never be matched, "
1631 "because it does not Require a value, and a "
1632 "cl::ConsumeAfter option is active!");
1633 ErrorParsing =
true;
1635 }
else if (UnboundedFound && !Opt->
hasArgStr()) {
1641 Opt->
error(
"error - option can never match, because "
1642 "another positional argument will match an "
1643 "unbounded number of values, and this option"
1644 " does not require a value!");
1645 *Errs << ProgramName <<
": CommandLine Error: Option '" << Opt->
ArgStr
1646 <<
"' is all messed up!\n";
1647 *Errs << PositionalOpts.size();
1648 ErrorParsing =
true;
1652 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
1663 Option *ActivePositionalArg =
nullptr;
1666 bool DashDashFound =
false;
1667 for (
int i = FirstArg; i < argc; ++i) {
1668 Option *Handler =
nullptr;
1669 std::string NearestHandlerString;
1671 StringRef ArgName =
"";
1677 if (argv[i][0] !=
'-' || argv[i][1] == 0 || DashDashFound) {
1679 if (ActivePositionalArg) {
1684 if (!PositionalOpts.empty()) {
1685 PositionalVals.
push_back(std::make_pair(StringRef(argv[i]), i));
1690 if (PositionalVals.
size() >= NumPositionalRequired && ConsumeAfterOpt) {
1691 for (++i; i < argc; ++i)
1692 PositionalVals.
push_back(std::make_pair(StringRef(argv[i]), i));
1699 }
else if (argv[i][0] ==
'-' && argv[i][1] ==
'-' && argv[i][2] == 0 &&
1701 DashDashFound =
true;
1703 }
else if (ActivePositionalArg &&
1708 ArgName = StringRef(argv[i] + 1);
1712 Handler = LookupOption(*ChosenSubCommand, ArgName,
Value);
1718 ArgName = StringRef(argv[i] + 1);
1722 Handler = LookupOption(*ChosenSubCommand, ArgName,
Value);
1732 lookupLibraryOption(ArgName.
split(
'=').first)) {
1733 ArrayRef<const char *> Rest(argv + i, argc - i);
1739 *Errs << ProgramName <<
": " <<
toString(std::move(
E)) <<
'\n';
1740 ErrorParsing =
true;
1758 auto ReportUnknownArgument = [&](
bool IsArg,
1759 StringRef NearestArgumentName) {
1760 *Errs << ProgramName <<
": Unknown "
1761 << (IsArg ?
"command line argument" :
"subcommand") <<
" '"
1762 << argv[i] <<
"'. Try: '" << argv[0] <<
" --help'\n";
1764 if (NearestArgumentName.empty())
1767 *Errs << ProgramName <<
": Did you mean '";
1769 *Errs << PrintArg(NearestArgumentName, 0);
1771 *Errs << NearestArgumentName;
1775 if (i > 1 || !MaybeNamedSubCommand)
1776 ReportUnknownArgument(
true, NearestHandlerString);
1778 ReportUnknownArgument(
false, NearestSubCommandString);
1780 ErrorParsing =
true;
1788 Handler->
error(
"This argument does not take a value.\n"
1789 "\tInstead, it consumes any positional arguments until "
1790 "the next recognized option.", *Errs);
1791 ErrorParsing =
true;
1793 ActivePositionalArg = Handler;
1800 if (NumPositionalRequired > PositionalVals.
size()) {
1801 *Errs << ProgramName
1802 <<
": Not enough positional command line arguments specified!\n"
1803 <<
"Must specify at least " << NumPositionalRequired
1804 <<
" positional argument" << (NumPositionalRequired > 1 ?
"s" :
"")
1805 <<
": See: " << argv[0] <<
" --help\n";
1807 ErrorParsing =
true;
1808 }
else if (!HasUnlimitedPositionals &&
1809 PositionalVals.
size() > PositionalOpts.size()) {
1810 *Errs << ProgramName <<
": Too many positional arguments specified!\n"
1811 <<
"Can specify at most " << PositionalOpts.size()
1812 <<
" positional arguments: See: " << argv[0] <<
" --help\n";
1813 ErrorParsing =
true;
1815 }
else if (!ConsumeAfterOpt) {
1817 unsigned ValNo = 0, NumVals =
static_cast<unsigned>(PositionalVals.
size());
1818 for (
Option *Opt : PositionalOpts) {
1821 PositionalVals[ValNo].second);
1823 --NumPositionalRequired;
1831 while (NumVals - ValNo > NumPositionalRequired && !
Done) {
1839 PositionalVals[ValNo].second);
1844 "positional argument processing!");
1849 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.
size());
1851 for (
Option *Opt : PositionalOpts)
1854 Opt, PositionalVals[ValNo].first, PositionalVals[ValNo].second);
1863 if (PositionalOpts.size() == 1 && ValNo == 0 && !PositionalVals.
empty()) {
1865 PositionalVals[ValNo].first,
1866 PositionalVals[ValNo].second);
1872 for (; ValNo != PositionalVals.
size(); ++ValNo)
1875 PositionalVals[ValNo].second);
1879 for (
const auto &Opt : OptionsMap) {
1884 Opt.second->
error(
"must be specified at least once!");
1885 ErrorParsing =
true;
1897 for (
int i = 0; i < argc; ++i)
dbgs() << argv[i] <<
' ';
1918 if (!ArgName.
data())
1920 if (ArgName.
empty())
1923 Errs <<
globalParser().ProgramName <<
": for the " << PrintArg(ArgName, 0);
1925 Errs <<
" option: " << Message <<
"\n";
1931 return handleOccurrence(pos, ArgName, Value);
1938 if (O.ValueStr.empty())
1953 size_t FirstLineIndentedBy) {
1954 assert(Indent >= FirstLineIndentedBy);
1955 std::pair<StringRef, StringRef> Split =
HelpStr.split(
'\n');
1958 while (!Split.second.empty()) {
1959 Split = Split.second.split(
'\n');
1960 outs().
indent(Indent) << Split.first <<
"\n";
1965 size_t FirstLineIndentedBy) {
1967 assert(BaseIndent >= FirstLineIndentedBy);
1968 std::pair<StringRef, StringRef> Split =
HelpStr.split(
'\n');
1969 outs().
indent(BaseIndent - FirstLineIndentedBy)
1971 while (!Split.second.empty()) {
1972 Split = Split.second.split(
'\n');
1973 outs().
indent(BaseIndent + ValHelpPrefix.
size()) << Split.first <<
"\n";
1978void alias::printOptionInfo(
size_t GlobalWidth)
const {
1994 if (!ValName.empty()) {
1995 size_t FormattingLen = 3;
2008 size_t GlobalWidth)
const {
2009 outs() << PrintArg(O.ArgStr);
2012 if (!ValName.empty()) {
2018 outs() << (O.ArgStr.size() == 1 ?
" <" :
"=<") <<
getValueStr(O, ValName)
2027 size_t GlobalWidth)
const {
2028 outs() << PrintArg(O.ArgStr);
2029 outs().
indent(GlobalWidth - O.ArgStr.size());
2049template <
typename FixedOrScalableQuantityT>
2052 FixedOrScalableQuantityT &
Value) {
2053 using ScalarTy =
typename FixedOrScalableQuantityT::ScalarTy;
2059 Value = FixedOrScalableQuantityT::getFixed(MinValue);
2065 return O.error(
"'" + Arg +
"' value invalid for " + ValueKind +
2068 Remainder = Remainder.
ltrim();
2070 return O.error(
"'" + Arg +
"' value invalid for " + ValueKind +
2073 Remainder = Remainder.
ltrim();
2075 return O.error(
"'" + Arg +
"' value invalid for " + ValueKind +
2078 Value = FixedOrScalableQuantityT::getScalable(MinValue);
2087 return O.error(
"'" + Arg +
"' value invalid for integer argument!");
2096 return O.error(
"'" + Arg +
"' value invalid for long argument!");
2105 return O.error(
"'" + Arg +
"' value invalid for llong argument!");
2115 return O.error(
"'" + Arg +
"' value invalid for uint argument!");
2122 unsigned long &
Value) {
2125 return O.error(
"'" + Arg +
"' value invalid for ulong argument!");
2133 unsigned long long &
Value) {
2136 return O.error(
"'" + Arg +
"' value invalid for ullong argument!");
2143 ElementCount &
Value) {
2152 return O.error(
"'" + Arg +
"' value invalid for floating point argument!");
2178 for (
unsigned i = 0; i != e; ++i) {
2194 return O.getValueExpectedFlag() !=
ValueOptional || !Name.empty() ||
2195 !Description.
empty();
2200 if (O.hasArgStr()) {
2212 size_t BaseSize = 0;
2223 size_t GlobalWidth)
const {
2224 if (O.hasArgStr()) {
2230 outs() << PrintArg(O.ArgStr);
2249 if (OptionName.
empty()) {
2254 if (!Description.
empty())
2260 if (!O.HelpStr.empty())
2261 outs() <<
" " << O.HelpStr <<
'\n';
2278 outs() <<
" " << PrintArg(O.ArgStr);
2279 outs().
indent(GlobalWidth - O.ArgStr.size());
2282 for (
unsigned i = 0; i != NumOpts; ++i) {
2290 for (
unsigned j = 0; j != NumOpts; ++j) {
2299 outs() <<
"= *unknown option value*\n";
2307 return OS << static_cast<int>(V);
2312#define PRINT_OPT_DIFF(T) \
2313 void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D, \
2314 size_t GlobalWidth) const { \
2315 printOptionName(O, GlobalWidth); \
2318 raw_string_ostream SS(Str); \
2321 outs() << "= " << Str; \
2322 size_t NumSpaces = \
2323 MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0; \
2324 outs().indent(NumSpaces) << " (default: "; \
2326 outs() << D.getValue(); \
2328 outs() << "*no default*"; \
2347 size_t GlobalWidth)
const {
2348 printOptionName(O, GlobalWidth);
2349 outs() <<
"= " <<
V;
2353 outs() <<
D.getValue();
2355 outs() <<
"*no default*";
2360 const Option &O, std::optional<StringRef>
V,
2361 const OptionValue<std::optional<std::string>> &
D,
2362 size_t GlobalWidth)
const {
2363 printOptionName(O, GlobalWidth);
2364 outs() <<
"= " <<
V;
2365 size_t VSize =
V.has_value() ?
V.value().size() : 0;
2368 if (
D.hasValue() &&
D.getValue().has_value())
2369 outs() <<
D.getValue();
2371 outs() <<
"*no value*";
2377 size_t GlobalWidth)
const {
2379 outs() <<
"= *cannot print option value*\n";
2387 const std::pair<const char *, Option *> *
RHS) {
2388 return strcmp(
LHS->first,
RHS->first);
2392 const std::pair<const char *, SubCommand *> *
RHS) {
2393 return strcmp(
LHS->first,
RHS->first);
2402 for (
auto I = OptMap.
begin(),
E = OptMap.
end();
I !=
E; ++
I) {
2408 if (
I->second->getOptionHiddenFlag() ==
Hidden && !ShowHidden)
2412 if (!OptionSet.
insert(
I->second).second)
2416 std::pair<const char *, Option *>(
I->first.data(),
I->second));
2426 for (
auto *S : SubMap) {
2427 if (S->getName().empty())
2429 Subs.push_back(std::make_pair(S->getName().data(), S));
2438 const bool ShowHidden;
2439 using StrOptionPairVector =
2441 using StrSubCommandPairVector =
2444 virtual void printOptions(StrOptionPairVector &Opts,
size_t MaxArgLen) {
2445 for (
const auto &Opt : Opts)
2449 void printSubCommands(StrSubCommandPairVector &Subs,
size_t MaxSubLen) {
2450 for (
const auto &S : Subs) {
2451 outs() <<
" " << S.first;
2452 if (!S.second->getDescription().empty()) {
2454 outs() <<
" - " << S.second->getDescription();
2461 explicit HelpPrinter(
bool showHidden) : ShowHidden(showHidden) {}
2462 virtual ~HelpPrinter() =
default;
2465 void operator=(
bool Value) {
2476 auto &OptionsMap =
Sub->OptionsMap;
2477 auto &PositionalOpts =
Sub->PositionalOpts;
2478 auto &ConsumeAfterOpt =
Sub->ConsumeAfterOpt;
2480 StrOptionPairVector Opts;
2481 sortOpts(OptionsMap, Opts, ShowHidden);
2483 StrSubCommandPairVector Subs;
2492 outs() <<
" [subcommand]";
2493 outs() <<
" [options]";
2495 if (!
Sub->getDescription().empty()) {
2496 outs() <<
"SUBCOMMAND '" <<
Sub->getName()
2497 <<
"': " <<
Sub->getDescription() <<
"\n\n";
2503 for (
auto *Opt : PositionalOpts) {
2510 if (ConsumeAfterOpt)
2511 outs() <<
" " << ConsumeAfterOpt->HelpStr;
2515 size_t MaxSubLen = 0;
2516 for (
const auto &
Sub : Subs)
2517 MaxSubLen = std::max(MaxSubLen, strlen(
Sub.first));
2520 outs() <<
"SUBCOMMANDS:\n\n";
2521 printSubCommands(Subs, MaxSubLen);
2524 <<
" <subcommand> --help\" to get more help on a specific "
2531 size_t MaxArgLen = 0;
2532 for (
const auto &Opt : Opts)
2540 [&](StringRef Spelling, StringRef MetaVar, StringRef
Help) {
2545 for (
const auto &[Name,
Help] : LibraryOpts)
2548 outs() <<
"OPTIONS:\n";
2549 printOptions(Opts, MaxArgLen);
2551 if (!LibraryOpts.empty())
2552 outs() <<
"\nLibrary options:\n\n";
2553 for (
const auto &[Name,
Help] : LibraryOpts) {
2554 outs() << PrintArg(Name);
2565class CategorizedHelpPrinter :
public HelpPrinter {
2567 explicit CategorizedHelpPrinter(
bool showHidden) : HelpPrinter(showHidden) {}
2573 static int OptionCategoryCompare(OptionCategory *
const *
A,
2574 OptionCategory *
const *
B) {
2575 return (*A)->getName().compare((*B)->getName());
2579 using HelpPrinter::operator=;
2582 void printOptions(StrOptionPairVector &Opts,
size_t MaxArgLen)
override {
2583 std::vector<OptionCategory *> SortedCategories;
2584 DenseMap<OptionCategory *, std::vector<Option *>> CategorizedOptions;
2592 assert(SortedCategories.size() > 0 &&
"No option categories registered!");
2594 OptionCategoryCompare);
2599 for (
const auto &
I : Opts) {
2600 Option *Opt =
I.second;
2601 for (OptionCategory *Cat : Opt->
Categories) {
2603 "Option has an unregistered category");
2604 CategorizedOptions[Cat].push_back(Opt);
2609 for (OptionCategory *Category : SortedCategories) {
2611 const auto &CategoryOptions = CategorizedOptions[Category];
2612 if (CategoryOptions.empty())
2617 outs() << Category->getName() <<
":\n";
2620 if (!Category->getDescription().empty())
2621 outs() << Category->getDescription() <<
"\n\n";
2626 for (
const Option *Opt : CategoryOptions)
2634class HelpPrinterWrapper {
2636 HelpPrinter &UncategorizedPrinter;
2637 CategorizedHelpPrinter &CategorizedPrinter;
2640 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
2641 CategorizedHelpPrinter &CategorizedPrinter)
2642 : UncategorizedPrinter(UncategorizedPrinter),
2643 CategorizedPrinter(CategorizedPrinter) {}
2646 void operator=(
bool Value);
2651#if defined(__GNUC__)
2654# if defined(__OPTIMIZE__)
2655# define LLVM_IS_DEBUG_BUILD 0
2657# define LLVM_IS_DEBUG_BUILD 1
2659#elif defined(_MSC_VER)
2664# define LLVM_IS_DEBUG_BUILD 1
2666# define LLVM_IS_DEBUG_BUILD 0
2670# define LLVM_IS_DEBUG_BUILD 0
2674class VersionPrinter {
2676 void print(
const std::vector<VersionPrinterTy> &ExtraPrinters) {
2678#ifdef PACKAGE_VENDOR
2679 OS << PACKAGE_VENDOR <<
" ";
2681 OS <<
"LLVM (http://llvm.org/):\n ";
2683 OS << PACKAGE_NAME <<
" version " << PACKAGE_VERSION <<
"\n ";
2684#if LLVM_IS_DEBUG_BUILD
2685 OS <<
"DEBUG build";
2687 OS <<
"Optimized build";
2690 OS <<
" with assertions";
2696 if (!ExtraPrinters.empty()) {
2697 for (
const auto &
I : ExtraPrinters)
2701 void operator=(
bool OptionWasSpecified);
2704struct CommandLineCommonOptions {
2707 HelpPrinter UncategorizedNormalPrinter{
false};
2708 HelpPrinter UncategorizedHiddenPrinter{
true};
2709 CategorizedHelpPrinter CategorizedNormalPrinter{
false};
2710 CategorizedHelpPrinter CategorizedHiddenPrinter{
true};
2713 HelpPrinterWrapper WrappedNormalPrinter{UncategorizedNormalPrinter,
2714 CategorizedNormalPrinter};
2715 HelpPrinterWrapper WrappedHiddenPrinter{UncategorizedHiddenPrinter,
2716 CategorizedHiddenPrinter};
2726 "Display list of available options (--help-list-hidden for more)"),
2735 cl::desc(
"Display list of all available options"),
2747 cl::desc(
"Display available options (--help-hidden for more)"),
2757 cl::desc(
"Display all available options"),
2766 cl::desc(
"Print non-default options after command line parsing"),
2773 "print-all-options",
2774 cl::desc(
"Print all option values after command line parsing"),
2782 std::vector<VersionPrinterTy> ExtraVersionPrinters;
2785 VersionPrinter VersionPrinterInstance;
2788 "version",
cl::desc(
"Display the version of this program"),
2813 return GeneralCategory;
2816void VersionPrinter::operator=(
bool OptionWasSpecified) {
2817 if (!OptionWasSpecified)
2829void HelpPrinterWrapper::operator=(
bool Value) {
2836 if (
globalParser().RegisteredOptionCategories.size() > 1) {
2841 CategorizedPrinter =
true;
2843 UncategorizedPrinter =
true;
2850void CommandLineParser::printOptionValues() {
2855 sortOpts(ActiveSubCommand->OptionsMap, Opts,
true);
2858 size_t MaxArgLen = 0;
2859 for (
const auto &Opt : Opts)
2862 for (
const auto &Opt : Opts)
2868 if (!
Hidden && !Categorized)
2870 else if (!
Hidden && Categorized)
2872 else if (
Hidden && !Categorized)
2884#if LLVM_IS_DEBUG_BUILD
2890#ifdef EXPENSIVE_CHECKS
2891 "+expensive-checks",
2893#if __has_feature(address_sanitizer)
2896#if __has_feature(dataflow_sanitizer)
2899#if __has_feature(hwaddress_sanitizer)
2902#if __has_feature(memory_sanitizer)
2905#if __has_feature(thread_sanitizer)
2908#if __has_feature(undefined_behavior_sanitizer)
2911#ifdef LLVM_INTEGRATED_CRT_ALLOC
2912 "+alloc:" LLVM_INTEGRATED_CRT_ALLOC,
2920#if LLVM_VERSION_PRINTER_SHOW_BUILD_CONFIG
2921 OS <<
"Build config: ";
2945 return Sub.OptionsMap;
2955 for (
auto &
I :
Sub.OptionsMap) {
2956 bool Unrelated =
true;
2957 for (
auto &Cat :
I.second->Categories) {
2958 if (Cat == &Category || Cat == &
CommonOptions->GenericCategory)
2969 for (
auto &
I :
Sub.OptionsMap) {
2970 bool Unrelated =
true;
2971 for (
auto &Cat :
I.second->Categories) {
2993 for (
size_t I = 0,
E = Args.size();
I !=
E;) {
2997 cantFail(Context ? Context->parse(L, Rest,
N)
3008 SavedLibraries.clear();
3014 unsigned &Consumed) {
3015 auto [It, Inserted] = Values.try_emplace(L.getDefault());
3017 It->second = L.copyDefault(Alloc);
3020 SavedLibraries.resize(SavedArgs.size(), &L);
3034 const char *Overview,
3037 size_t Begin =
C.args().size();
3043 C.argLibraries().drop_front(Begin),
nullptr);
3049 const char *Overview) {
3054 const char *Overview,
3055 char **ErrorMessage) {
3056 *ErrorMessage =
nullptr;
3060 *ErrorMessage = strdup(Err.c_str());
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the StringMap class.
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static StringRef OptionPrefix
static bool RequiresValue(const Option *O)
static int SubNameCompare(const std::pair< const char *, SubCommand * > *LHS, const std::pair< const char *, SubCommand * > *RHS)
static size_t argPlusPrefixesSize(StringRef ArgName, size_t Pad=DefaultPad)
static bool shouldPrintOption(StringRef Name, StringRef Description, const Option &O)
static bool parseDouble(Option &O, StringRef Arg, double &Value)
static CommandLineParser & globalParser()
static bool parseBool(Option &O, StringRef ArgName, StringRef Arg, T &Value)
static const size_t DefaultPad
static StringRef EmptyOption
static void replayLibraryArgs(ArrayRef< const char * > Args, ArrayRef< const LibraryOptions * > Libraries, LibraryOptionsContext *Context)
static bool parseCommandLineOptionsImpl(LibraryOptionsContext *Context, ArrayRef< const char * > Args, StringRef Overview, raw_ostream *Errs, vfs::FileSystem *VFS, const char *EnvVar, ArrayRef< const LibraryOptions * > ToolOptions={})
static bool hasUTF8ByteOrderMark(ArrayRef< char > S)
static void ExpandBasePaths(StringRef BasePath, StringSaver &Saver, const char *&Arg)
static SmallString< 8 > argPrefix(StringRef ArgName, size_t Pad=DefaultPad)
static Error parseLibraryOption(const LibraryOptions &L, void *Opts, ArrayRef< const char * > Args, unsigned &Consumed, BumpPtrAllocator &Alloc, SmallVectorImpl< const char * > *Record=nullptr)
static StringRef ArgHelpPrefix
void opt_unsigned_anchor()
static bool isWindowsSpecialCharInCommandName(char C)
static StringRef getValueStr(const Option &O, StringRef DefaultMsg)
static Option * HandlePrefixedOption(StringRef &Arg, StringRef &Value, const OptionsMapTy &OptionsMap)
The specified argument string (which started with at least one '-') does not fully match an available...
static size_t getOptionPrefixesSize()
static bool ProvideOption(Option *Handler, StringRef ArgName, StringRef Value, int argc, const char *const *argv, int &i)
ProvideOption - For Value, this differentiates between an empty value ("") and a null value (StringRe...
static bool isQuote(char C)
static ManagedStatic< CommandLineCommonOptions > CommonOptions
static void initCommonOptions()
static void sortOpts(OptionsMapTy &OptMap, SmallVectorImpl< std::pair< const char *, Option * > > &Opts, bool ShowHidden)
DenseMap< StringRef, Option * > OptionsMapTy
static void tokenizeWindowsCommandLineImpl(StringRef Src, StringSaver &Saver, function_ref< void(StringRef)> AddToken, bool AlwaysCopy, function_ref< void()> MarkEOL, bool InitialCommandName)
static Option * findPrefixOption(StringRef Name, size_t &Length, const OptionsMapTy &OptionsMap)
static bool isWhitespace(char C)
static bool parseFixedOrScalableQuantity(Option &O, StringRef Arg, StringRef ValueKind, FixedOrScalableQuantityT &Value)
static size_t parseBackslash(StringRef Src, size_t I, SmallString< 128 > &Token)
Backslashes are interpreted in a rather complicated way in the Windows-style command line,...
static StringRef ArgPrefixLong
static bool llvmParseCommandLineOptionsImpl(int argc, const char *const *argv, const char *Overview, raw_ostream *Errs)
static void sortSubCommands(const SmallPtrSetImpl< SubCommand * > &SubMap, SmallVectorImpl< std::pair< const char *, SubCommand * > > &Subs)
#define PRINT_OPT_DIFF(T)
static bool isWhitespaceOrNull(char C)
static const size_t MaxOptWidth
static bool EatsUnboundedNumberOfValues(const Option *O)
static int OptNameCompare(const std::pair< const char *, Option * > *LHS, const std::pair< const char *, Option * > *RHS)
static Option * LookupNearestOption(StringRef Arg, const OptionsMapTy &OptionsMap, std::string &NearestString)
LookupNearestOption - Lookup the closest match to the option specified by the specified option on the...
static StringRef ArgPrefix
static bool isWindowsSpecialChar(char C)
static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos, StringRef ArgName, StringRef Value)
CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence() that does special handling ...
#define LLVM_EXPORT_TEMPLATE
Fixup Statepoint Caller Saved
static void Help(StringTable CPUNames, ArrayRef< SubtargetFeatureKV > FeatTable)
Display help for feature and mcpu choices.
Provides a library for accessing information about this process and other processes on the operating ...
This file defines the SmallPtrSet class.
This file defines the SmallString class.
Defines the virtual file system interface vfs::FileSystem.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
Get the array size.
bool empty() const
Check if the array is empty.
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Represents either an error or a value T.
std::error_code getError() const
Lightweight error class with error context and mandatory checking.
static ErrorSuccess success()
Create a success value.
ManagedStatic - This transparently changes the behavior of global statics to be lazily constructed on...
size_t getBufferSize() const
const char * getBufferEnd() const
const char * getBufferStart() const
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
bool erase(PtrType Ptr)
Remove pointer from the set.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
void assign(StringRef RHS)
Assign from a StringRef.
void append(StringRef RHS)
Append from a StringRef.
StringRef str() const
Explicit conversion to StringRef.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void assign(size_type NumElts, ValueParamT Elt)
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
iterator erase(const_iterator CI)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
iterator insert(iterator I, T &&Elt)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
A wrapper around a string literal that serves as a proxy for constructing global tables of StringRefs...
Represent a constant reference to a string, i.e.
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
static constexpr size_t npos
bool getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
constexpr bool empty() const
Check if the string is empty.
StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
LLVM_ABI unsigned edit_distance(StringRef Other, bool AllowReplacements=true, unsigned MaxEditDistance=0) const
Determine the edit distance between this string and another string.
StringRef slice(size_t Start, size_t End) const
Return a reference to the substring from [Start, End).
constexpr size_t size() const
Get the string size.
constexpr const char * data() const
Get a pointer to the start of the string (which may not be null terminated).
StringRef ltrim(char Char) const
Return string with consecutive Char characters starting from the the left removed.
size_t find(char C, size_t From=0) const
Search for the first character C in the string.
StringRef trim(char Char) const
Return string with consecutive Char characters starting from the left and right removed.
bool consume_front(char Prefix)
Returns true if this StringRef has the given prefix and removes that prefix.
Saves strings in the provided stable storage and returns a StringRef with a stable character pointer.
BumpPtrAllocator & getAllocator() const
StringRef save(const char *S)
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
LLVM Value Representation.
Contains options that control response file expansion.
LLVM_ABI ExpansionContext(BumpPtrAllocator &A, TokenizerCallback T, vfs::FileSystem *FS=nullptr)
LLVM_ABI bool findConfigFile(StringRef FileName, SmallVectorImpl< char > &FilePath)
Looks for the specified configuration file.
LLVM_ABI Error expandResponseFiles(SmallVectorImpl< const char * > &Argv)
Expands constructs "@file" in the provided array of arguments recursively.
LLVM_ABI Error readConfigFile(StringRef CfgFile, SmallVectorImpl< const char * > &Argv)
Reads command line options from the given configuration file.
Error parse(const LibraryOptions &L, ArrayRef< const char * > Args, unsigned &Consumed)
void assign(const LibraryOptionsContext &Other)
The options of a library that declares them in TableGen rather than as cl::opt (see llvm/Option/Libra...
SmallPtrSet< SubCommand *, 1 > Subs
int getNumOccurrences() const
enum ValueExpected getValueExpectedFlag() const
void addCategory(OptionCategory &C)
enum FormattingFlags getFormattingFlag() const
virtual void printOptionInfo(size_t GlobalWidth) const =0
enum NumOccurrencesFlag getNumOccurrencesFlag() const
virtual bool addOccurrence(unsigned pos, StringRef ArgName, StringRef Value)
SmallVector< OptionCategory *, 1 > Categories
bool error(const Twine &Message, StringRef ArgName=StringRef(), raw_ostream &Errs=llvm::errs())
void setArgStr(StringRef S)
unsigned getMiscFlags() const
virtual void setDefault()=0
virtual void printOptionValue(size_t GlobalWidth, bool Force) const =0
static void printEnumValHelpStr(StringRef HelpStr, size_t Indent, size_t FirstLineIndentedBy)
void removeArgument()
Unregisters this option from the CommandLine system.
static void printHelpStr(StringRef HelpStr, size_t Indent, size_t FirstLineIndentedBy)
virtual size_t getOptionWidth() const =0
Option(enum NumOccurrencesFlag OccurrencesFlag, enum OptionHidden Hidden)
StringRef getName() const
SubCommand(StringRef Name, StringRef Description="")
static LLVM_ABI SubCommand & getTopLevel()
LLVM_ABI void unregisterSubCommand()
static LLVM_ABI SubCommand & getAll()
DenseMap< StringRef, Option * > OptionsMap
LLVM_ABI void registerSubCommand()
SmallVector< Option *, 4 > PositionalOpts
void printOptionInfo(const Option &O, size_t GlobalWidth) const
virtual StringRef getValueName() const
void printOptionNoValue(const Option &O, size_t GlobalWidth) const
size_t getOptionWidth(const Option &O) const
void printOptionName(const Option &O, size_t GlobalWidth) const
virtual size_t getOptionWidth(const Option &O) const
virtual StringRef getDescription(unsigned N) const =0
virtual const GenericOptionValue & getOptionValue(unsigned N) const =0
virtual unsigned getNumOptions() const =0
virtual StringRef getOption(unsigned N) const =0
void printGenericOptionDiff(const Option &O, const GenericOptionValue &V, const GenericOptionValue &Default, size_t GlobalWidth) const
virtual void printOptionInfo(const Option &O, size_t GlobalWidth) const
unsigned findOption(StringRef Name)
bool parse(Option &O, StringRef ArgName, StringRef Arg, DataType &V)
An efficient, type-erasing, non-owning reference to a callable.
A range adaptor for a pair of iterators.
This class implements an extremely fast bulk output stream that can only output to a stream.
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
A raw_ostream that writes to an SmallVector or SmallString.
static LLVM_ABI std::optional< std::string > GetEnv(StringRef name)
The virtual file system interface.
The result of a status operation.
LLVM_ABI bool equivalent(const Status &Other) const
LLVM_C_ABI LLVMBool LLVMParseCommandLineOptionsWithError(int argc, const char *const *argv, const char *Overview, char **ErrorMessage)
Like LLVMParseCommandLineOptions() but returns non-zero and sets *ErrorMessage on error.
LLVM_C_ABI void LLVMParseCommandLineOptions(int argc, const char *const *argv, const char *Overview)
This function parses the given arguments using the LLVM command line parser.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr size_t NameSize
This namespace contains all of the command line option processing machinery.
LLVM_ABI iterator_range< SmallPtrSet< SubCommand *, 4 >::iterator > getRegisteredSubcommands()
Use this to get all registered SubCommands from the provided parser.
LLVM_ABI void PrintVersionMessage()
Utility function for printing version number.
LLVM_ABI bool ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer, SmallVectorImpl< const char * > &Argv)
A convenience helper which supports the typical use case of expansion function call.
LLVM_ABI LibraryOptionsContext & getCAPILibraryOptions()
LLVM_ABI void TokenizeWindowsCommandLine(StringRef Source, StringSaver &Saver, SmallVectorImpl< const char * > &NewArgv, bool MarkEOLs=false)
Tokenizes a string of Windows command line arguments, which may contain quotes and escaped quotes.
LLVM_ABI OptionCategory & getGeneralCategory()
LLVM_ABI void addLibraryOptions(const LibraryOptions &L)
Makes ParseCommandLineOptions recognize L's options.
LLVM_ABI void ResetAllOptionOccurrences()
Reset all command line options to a state that looks as if they have never appeared on the command li...
LLVM_ABI void SetVersionPrinter(VersionPrinterTy func)
===------------------------------------------------------------------—===// Override the default (LLV...
LLVM_ABI void tokenizeConfigFile(StringRef Source, StringSaver &Saver, SmallVectorImpl< const char * > &NewArgv, bool MarkEOLs=false)
Tokenizes content of configuration file.
LLVM_ABI DenseMap< StringRef, Option * > & getRegisteredOptions(SubCommand &Sub=SubCommand::getTopLevel())
Use this to get a map of all registered named options (e.g.
LLVM_ABI bool expandResponseFiles(int Argc, const char *const *Argv, const char *EnvVar, StringSaver &Saver, SmallVectorImpl< const char * > &NewArgv)
A convenience helper which concatenates the options specified by the environment variable EnvVar and ...
LLVM_ABI void ResetCommandLineParser()
Reset the command line parser back to its initial state.
LLVM_ABI void PrintOptionValues()
LLVM_ABI void AddLiteralOption(Option &O, StringRef Name)
Adds a new option for parsing and provides the option it refers to.
void printOptionDiff(const Option &O, const generic_parser_base &P, const DT &V, const OptionValue< DT > &Default, size_t GlobalWidth)
LLVM_ABI void TokenizeWindowsCommandLineNoCopy(StringRef Source, StringSaver &Saver, SmallVectorImpl< StringRef > &NewArgv)
Tokenizes a Windows command line while attempting to avoid copies.
LLVM_ABI void printBuildConfig(raw_ostream &OS)
Prints the compiler build configuration.
void(*)(StringRef Source, StringSaver &Saver, SmallVectorImpl< const char * > &NewArgv, bool MarkEOLs) TokenizerCallback
String tokenization function type.
LLVM_ABI bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i)
Parses Arg into the option handler Handler.
static raw_ostream & operator<<(raw_ostream &OS, boolOrDefault V)
initializer< Ty > init(const Ty &Val)
std::function< void(raw_ostream &)> VersionPrinterTy
LLVM_ABI bool parseCommandLineOptions(LibraryOptionsContext &Context, ArrayRef< const char * > Args, StringRef Overview="", raw_ostream *Errs=nullptr, vfs::FileSystem *VFS=nullptr, const char *EnvVar=nullptr)
LLVM_ABI ArrayRef< StringRef > getCompilerBuildConfig()
An array of optional enabled settings in the LLVM build configuration, which may be of interest to co...
LocationClass< Ty > location(Ty &L)
LLVM_ABI bool ParseCommandLineOptions(int argc, const char *const *argv, StringRef Overview="", raw_ostream *Errs=nullptr, vfs::FileSystem *VFS=nullptr, const char *EnvVar=nullptr)
LLVM_ABI void HideUnrelatedOptions(cl::OptionCategory &Category, SubCommand &Sub=SubCommand::getTopLevel())
Mark all options not part of this category as cl::ReallyHidden.
LLVM_ABI void AddExtraVersionPrinter(VersionPrinterTy func)
===------------------------------------------------------------------—===// Add an extra printer to u...
LLVM_ABI void PrintHelpMessage(bool Hidden=false, bool Categorized=false)
This function just prints the help message, exactly the same way as if the -help or -help-hidden opti...
LLVM_ABI void TokenizeWindowsCommandLineFull(StringRef Source, StringSaver &Saver, SmallVectorImpl< const char * > &NewArgv, bool MarkEOLs=false)
Tokenizes a Windows full command line, including command name at the start.
LLVM_ABI void TokenizeGNUCommandLine(StringRef Source, StringSaver &Saver, SmallVectorImpl< const char * > &NewArgv, bool MarkEOLs=false)
Tokenizes a command line that can contain escapes and quotes.
LLVM_ABI StringRef parent_path(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get parent path.
LLVM_ABI bool has_parent_path(const Twine &path, Style style=Style::native)
Has parent path?
LLVM_ABI bool is_relative(const Twine &path, Style style=Style::native)
Is path relative?
LLVM_ABI StringRef filename(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get filename.
LLVM_ABI bool is_absolute(const Twine &path, Style style=Style::native)
Is path absolute?
LLVM_ABI void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
LLVM_ABI IntrusiveRefCntPtr< FileSystem > getRealFileSystem()
Gets an vfs::FileSystem for the 'real' file system, as seen by the operating system.
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
void initWithColorOptions()
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
LLVM_ABI raw_fd_ostream & outs()
This returns a reference to a raw_fd_ostream for standard output.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
void interleaveComma(const Container &c, StreamT &os, UnaryFunctor each_fn)
LLVM_ABI bool hasUTF16ByteOrderMark(ArrayRef< char > SrcBytes)
Returns true if a blob of text starts with a UTF-16 big or little endian byte order mark.
void initDebugCounterOptions()
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
detail::concat_range< ValueT, RangeTs... > concat(RangeTs &&...Ranges)
Returns a concatenated range across two or more ranges.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
bool to_float(const Twine &T, float &Num)
@ no_such_file_or_directory
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
void sort(IteratorTy Start, IteratorTy End)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
LLVM_ABI bool convertUTF16ToUTF8String(ArrayRef< char > SrcBytes, std::string &Out)
Converts a stream of raw bytes assumed to be UTF16 into a UTF8 std::string.
void initSignalsOptions()
void initStatisticOptions()
LLVM_ABI raw_ostream & nulls()
This returns a reference to a raw_ostream which simply discards output.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
void initRandomSeedOptions()
@ Sub
Subtraction of integers.
void initGraphWriterOptions()
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
ArrayRef(const T &OneElt) -> ArrayRef< T >
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
void array_pod_sort(IteratorTy Start, IteratorTy End)
array_pod_sort - This sorts an array with the specified start and end extent.
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
@ End
Run the machine verifier once, at the end of the pipeline.