1//===-- CommandLine.cpp - Command line parser implementation --------------===// 3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4// See https://llvm.org/LICENSE.txt for license information. 5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 7//===----------------------------------------------------------------------===// 9// This class implements a command line argument processor that is useful when 10// creating a tool. It provides a simple, minimalistic interface that is easily 11// extensible and supports nonlocal (library) command line options. 13// Note that rather than trying to figure out what this code does, you could try 14// reading the library documentation located in docs/CommandLine.html 16//===----------------------------------------------------------------------===// 31#include "llvm/Config/config.h" 50#define DEBUG_TYPE "commandline" 52//===----------------------------------------------------------------------===// 53// Template instantiations and anchors. 78// Pin the vtables to this file. 79void GenericOptionValue::anchor() {}
82void Option::anchor() {}
97//===----------------------------------------------------------------------===// 106size_t Len = ArgName.
size();
114for (
size_tI = 0;
I < Pad; ++
I) {
121// Option predicates... 142OS <<
argPrefix(Arg.ArgName, Arg.Pad) << Arg.ArgName;
146classCommandLineParser {
148// Globals for name and overview of program. Program name is not a string to 149// avoid static ctor/dtor issues. 150 std::string ProgramName;
153// This collects additional help to be printed. 154 std::vector<StringRef> MoreHelp;
156// This collects Options added with the cl::DefaultOption flag. Since they can 157// be overridden, they are not added to the appropriate SubCommands until 158// ParseCommandLineOptions actually runs. 161// This collects the different option categories that have been registered. 164// This collects the different subcommands that have been registered. 173bool LongOptionsUseDoubleDash =
false);
176if (Opt.
Subs.empty()) {
181for (
auto *SC : RegisteredSubCommands)
186for (
auto *SC : Opt.
Subs) {
188"SubCommand::getAll() should not be used with other subcommands");
196if (!
SC->OptionsMap.insert(std::make_pair(
Name, &Opt)).second) {
197errs() << ProgramName <<
": CommandLine Error: Option '" <<
Name 198 <<
"' registered more than once!\n";
209bool HadErrors =
false;
211// If it's a DefaultOption, check to make sure it isn't already there. 212if (
O->isDefaultOption() &&
SC->OptionsMap.contains(
O->ArgStr))
215// Add argument to the argument map! 216if (!
SC->OptionsMap.insert(std::make_pair(
O->ArgStr, O)).second) {
217errs() << ProgramName <<
": CommandLine Error: Option '" <<
O->ArgStr
218 <<
"' registered more than once!\n";
223// Remember information about positional options. 225SC->PositionalOpts.push_back(O);
226elseif (
O->getMiscFlags() &
cl::Sink)
// Remember sink options 227SC->SinkOpts.push_back(O);
229if (
SC->ConsumeAfterOpt) {
230O->error(
"Cannot specify more than one option with cl::ConsumeAfter!");
233SC->ConsumeAfterOpt =
O;
236// Fail hard if there were errors. These are strictly unrecoverable and 237// indicate serious issues such as conflicting option names or an 239// linked LLVM distribution. 244void addOption(
Option *O,
bool ProcessDefaultOption =
false) {
245if (!ProcessDefaultOption &&
O->isDefaultOption()) {
249 forEachSubCommand(*O, [&](
SubCommand &SC) { addOption(O, &SC); });
254O->getExtraOptionNames(OptionNames);
260for (
autoName : OptionNames) {
262if (
I !=
End &&
I->getValue() == O)
285void removeOption(
Option *O) {
286 forEachSubCommand(*O, [&](
SubCommand &SC) { removeOption(O, &SC); });
294bool hasOptions()
const{
295for (
constauto *S : RegisteredSubCommands) {
302bool hasNamedSubCommands()
const{
303for (
constauto *S : RegisteredSubCommands)
304if (!S->getName().empty())
309SubCommand *getActiveSubCommand() {
return ActiveSubCommand; }
313if (!Sub.
OptionsMap.insert(std::make_pair(NewName, O)).second) {
314errs() << ProgramName <<
": CommandLine Error: Option '" <<
O->ArgStr
315 <<
"' registered more than once!\n";
322 forEachSubCommand(*O,
323 [&](
SubCommand &SC) { updateArgStr(O, NewName, &SC); });
326void printOptionValues();
333"Duplicate option categories");
341return (!
sub->getName().empty()) &&
344"Duplicate subcommands");
345 RegisteredSubCommands.insert(
sub);
347// For all options that have been registered for all subcommands, add the 348// option to this subcommand now. 350"SubCommand::getAll() should not be registered");
353if ((
O->isPositional() ||
O->isSink() ||
O->isConsumeAfter()) ||
357 addLiteralOption(*O,
sub, E.first());
362 RegisteredSubCommands.erase(
sub);
367returnmake_range(RegisteredSubCommands.begin(),
368 RegisteredSubCommands.end());
372 ActiveSubCommand =
nullptr;
377 RegisteredOptionCategories.
clear();
380 RegisteredSubCommands.clear();
386 DefaultOptions.
clear();
394bool LongOptionsUseDoubleDash,
bool HaveDoubleDash) {
396if (Opt && LongOptionsUseDoubleDash && !HaveDoubleDash && !
isGrouping(Opt))
407template <
typename T, T TrueVal, T FalseVal>
409if (Arg ==
"" || Arg ==
"true" || Arg ==
"TRUE" || Arg ==
"True" ||
415if (Arg ==
"false" || Arg ==
"FALSE" || Arg ==
"False" || Arg ==
"0") {
419return O.error(
"'" + Arg +
420"' is invalid value for boolean argument! Try 0 or 1");
433 FullyInitialized =
true;
449// Maintain backward compatibility by replacing the default GeneralCategory 450// if it's still set. Otherwise, just add the new one. The GeneralCategory 451// must be explicitly added if you want multiple categories that include it. 465void OptionCategory::registerCategory() {
469// A special subcommand representing no subcommand. It is particularly important 470// that this ManagedStatic uses constant initailization and not dynamic 471// initialization because it is referenced from cl::opt constructors, which run 472// dynamically in an arbitrary order. 476// A special subcommand that can be used to put an option into all subcommands. 499SubCommand::operator
bool()
const{
503//===----------------------------------------------------------------------===// 504// Basic, shared command line option processing machinery. 507/// LookupOption - Lookup the option specified by the specified option on the 508/// command line. If there is a value specified (after an equal sign) return 509/// that as well. This assumes that leading dashes have already been stripped. 517size_t EqualPos = Arg.
find(
'=');
519// If we have an equals sign, remember the value. 521// Look up the option. 525// If the argument before the = is a valid option name and the option allows 526// non-prefix form (ie is not AlwaysPrefix), we match. If not, signal match 527// failure by returning nullptr. 537 Arg = Arg.
substr(0, EqualPos);
542 std::string &NearestString) {
545// Find a subcommand with the edit distance == 1. 547for (
auto *S : RegisteredSubCommands) {
549"SubCommand::getAll() is not expected in RegisteredSubCommands");
550if (S->getName().empty())
553if (S->getName() ==
Name)
556if (!NearestMatch && S->getName().edit_distance(
Name) < 2)
561 NearestString = NearestMatch->
getName();
566/// LookupNearestOption - Lookup the closest match to the option specified by 567/// the specified option on the command line. If there is a value specified 568/// (after an equal sign) return that as well. This assumes that leading dashes 569/// have already been stripped. 572 std::string &NearestString) {
577// Split on any equal sign. 578 std::pair<StringRef, StringRef> SplitArg = Arg.
split(
'=');
579StringRef &
LHS = SplitArg.first;
// LHS == Arg when no '=' is present. 582// Find the closest match. 584unsigned BestDistance = 0;
586 ie = OptionsMap.
end();
589// Do not suggest really hidden options (not shown in any help). 594 O->getExtraOptionNames(OptionNames);
600for (
constauto &
Name : OptionNames) {
602 Flag,
/*AllowReplacements=*/true,
/*MaxEditDistance=*/BestDistance);
603if (!Best || Distance < BestDistance) {
605 BestDistance = Distance;
606if (
RHS.empty() || !PermitValue)
607 NearestString = std::string(
Name);
617/// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence() 618/// that does special handling of cl::CommaSeparated options. 621bool MultiArg =
false) {
622// Check to see if this option accepts a comma separated list of values. If 623// it does, we have to split up the value into multiple values. 629// Process the portion before the comma. 632// Erase the portion before the comma, AND the comma. 633 Val = Val.
substr(Pos + 1);
634// Check for another comma. 644/// ProvideOption - For Value, this differentiates between an empty value ("") 645/// and a null value (StringRef()). The later is accepted for arguments that 646/// don't allow a value (-foo) the former is rejected (-foo=). 649constchar *
const *argv,
int &i) {
650// Is this a multi-argument option? 653// Enforce value requirements 656if (!
Value.data()) {
// No value specified? 657// If no other argument or the option only supports prefix form, we 658// cannot look at the next argument. 660return Handler->
error(
"requires a value!");
661// Steal the next argument, like for '-o filename' 662assert(argv &&
"null check");
667if (NumAdditionalVals > 0)
668return Handler->
error(
"multi-valued option specified" 669" with ValueDisallowed modifier!");
679// If this isn't a multi-arg option, just run the handler. 680if (NumAdditionalVals == 0)
683// If it is, run the handle several times. 693while (NumAdditionalVals > 0) {
695return Handler->
error(
"not enough values!");
696assert(argv &&
"null check");
712// getOptionPred - Check to see if there are any options that satisfy the 713// specified predicate with names that are the prefixes in Name. This is 714// checked by progressively stripping characters off of the name, checking to 715// see if there options that satisfy the predicate. If we find one, return it, 716// otherwise return null. 719bool (*Pred)(
constOption *),
722if (OMI != OptionsMap.
end() && !Pred(OMI->getValue()))
723 OMI = OptionsMap.
end();
725// Loop while we haven't found an option and Name still has at least two 726// characters in it (so that the next iteration will not be the empty 728while (OMI == OptionsMap.
end() &&
Name.size() > 1) {
729Name =
Name.substr(0,
Name.size() - 1);
// Chop off the last character. 731if (OMI != OptionsMap.
end() && !Pred(OMI->getValue()))
732 OMI = OptionsMap.
end();
735if (OMI != OptionsMap.
end() && Pred(OMI->second)) {
737return OMI->second;
// Found one! 739returnnullptr;
// No option found! 742/// HandlePrefixedOrGroupedOption - The specified argument string (which started 743/// with at least one '-') does not fully match an available option. Check to 744/// see if this is a prefix or grouped option. If so, split arg into output an 745/// Arg/Value pair and return the Option to parse it with. 765// cl::Prefix options do not preserve '=' when used separately. 766// The behavior for them with grouped options should be the same. 773if (MaybeValue[0] ==
'=') {
778// This must be a grouped option. 781// Grouping options inside a group can't have values. 783 ErrorParsing |= PGOpt->
error(
"may not occur within a group!");
787// Because the value for the option is not required, we don't need to pass 792// Get the next grouping option. 797// We could not find a grouping option in the remainder of Arg. 812returnC ==
' ' ||
C ==
'\t' ||
C ==
'\r' ||
C ==
'\n';
825for (
size_tI = 0, E = Src.size();
I != E; ++
I) {
826// Consume runs of whitespace. 829// Mark the end of lines in response files. 830if (MarkEOLs && Src[
I] ==
'\n')
840// Backslash escapes the next character. 841if (
I + 1 < E &&
C ==
'\\') {
842 ++
I;
// Skip the escape. 847// Consume a quoted string. 850while (
I != E && Src[
I] !=
C) {
851// Backslash escapes the next character. 852if (Src[
I] ==
'\\' &&
I + 1 != E)
862// End the token if this is whitespace. 866// Mark the end of lines in response files. 867if (MarkEOLs &&
C ==
'\n')
873// This is a normal character. Append it. 877// Append the last token after hitting EOF with no whitespace. 882/// Backslashes are interpreted in a rather complicated way in the Windows-style 883/// command line, because backslashes are used both to separate path and to 884/// escape double quote. This method consumes runs of backslashes as well as the 885/// following double quote if it's escaped. 887/// * If an even number of backslashes is followed by a double quote, one 888/// backslash is output for every pair of backslashes, and the last double 889/// quote remains unconsumed. The double quote will later be interpreted as 890/// the start or end of a quoted string in the main loop outside of this 893/// * If an odd number of backslashes is followed by a double quote, one 894/// backslash is output for every pair of backslashes, and a double quote is 895/// output for the last pair of backslash-double quote. The double quote is 896/// consumed in this case. 898/// * Otherwise, backslashes are interpreted literally. 900size_t E = Src.size();
901int BackslashCount = 0;
902// Skip the backslashes. 906 }
while (
I != E && Src[
I] ==
'\\');
908bool FollowedByDoubleQuote = (
I != E && Src[
I] ==
'"');
909if (FollowedByDoubleQuote) {
910 Token.
append(BackslashCount / 2,
'\\');
911if (BackslashCount % 2 == 0)
916 Token.
append(BackslashCount,
'\\');
920// Windows treats whitespace, double quotes, and backslashes specially, except 921// when parsing the first token of a full command line, in which case 922// backslashes are not special. 930// Windows tokenization implementation. The implementation is designed to be 931// inlined and specialized for the two user entry points. 934bool AlwaysCopy,
function_ref<
void()> MarkEOL,
bool InitialCommandName) {
937// Sometimes, this function will be handling a full command line including an 938// executable pathname at the start. In that situation, the initial pathname 939// needs different handling from the following arguments, because when 940// CreateProcess or cmd.exe scans the pathname, it doesn't treat \ as 941// escaping the quote character, whereas when libc scans the rest of the 942// command line, it does. 943bool CommandName = InitialCommandName;
945// Try to do as much work inside the state machine as possible. 946enum {
INIT, UNQUOTED, QUOTED } State =
INIT;
948for (
size_tI = 0, E = Src.size();
I < E; ++
I) {
951assert(Token.
empty() &&
"token should be empty in initial state");
952// Eat whitespace before a token. 958// Stop if this was trailing whitespace. 971// No special characters: slice out the substring and start the next 972// token. Copy the string if the caller asks us to. 973 AddToken(AlwaysCopy ? Saver.
save(NormalChars) : NormalChars);
974if (
I < E && Src[
I] ==
'\n') {
976 CommandName = InitialCommandName;
980 }
elseif (Src[
I] ==
'\"') {
981 Token += NormalChars;
983 }
elseif (Src[
I] ==
'\\') {
984assert(!CommandName &&
"or else we'd have treated it as a normal char");
985 Token += NormalChars;
996// Whitespace means the end of the token. If we are in this state, the 997// token must have contained a special character, so we must copy the 999 AddToken(Saver.
save(Token.
str()));
1002 CommandName = InitialCommandName;
1008 }
elseif (Src[
I] ==
'\"') {
1010 }
elseif (Src[
I] ==
'\\' && !CommandName) {
1019if (
I < (E - 1) && Src[
I + 1] ==
'"') {
1020// Consecutive double-quotes inside a quoted string implies one 1025// Otherwise, end the quoted portion and return to the unquoted state. 1028 }
elseif (Src[
I] ==
'\\' && !CommandName) {
1038 AddToken(Saver.
save(Token.
str()));
1050/*AlwaysCopy=*/true, OnEOL,
false);
1056auto OnEOL = []() {};
1070/*AlwaysCopy=*/true, OnEOL,
true);
1076for (
constchar *Cur = Source.begin(); Cur != Source.end();) {
1078// Check for comment line. 1085while (Cur != Source.end() && *Cur !=
'\n')
1089// Find end of the current line. 1090constchar *Start = Cur;
1091for (
constchar *
End = Source.end(); Cur !=
End; ++Cur) {
1096 (*Cur ==
'\r' && (Cur + 1 !=
End) && Cur[1] ==
'\n')) {
1097 Line.append(Start, Cur - 1);
1103 }
elseif (*Cur ==
'\n')
1107 Line.append(Start, Cur);
1112// It is called byte order marker but the UTF-8 BOM is actually not affected 1113// by the host system's endianness. 1115return (S.
size() >= 3 && S[0] ==
'\xef' && S[1] ==
'\xbb' && S[2] ==
'\xbf');
1118// Substitute <CFGDIR> with the file's base path. 1129 TokenPos = ArgString.
find(Token, StartPos)) {
1130// Token may appear more than once per arg (e.g. comma-separated linker 1131// args). Support by using path-append on any subsequent appearances. 1133if (ResponseFile.
empty())
1137 ResponseFile.
append(BasePath);
1138 StartPos = TokenPos + Token.
size();
1141if (!ResponseFile.
empty()) {
1142// Path-append the remaining arg substring if at least one token appeared. 1144if (!Remaining.
empty())
1150// FName must be an absolute path. 1151Error ExpansionContext::expandResponseFile(
1159"': " +
EC.message());
1164// If we have a UTF-16 byte order mark, convert to UTF-8 for parsing. 1166 std::string UTF8Buf;
1170"Could not convert UTF16 to UTF8");
1173// If we see UTF-8 BOM sequence at the beginning of a file, we shall remove 1174// these bytes before parsing. 1175// Reference: http://en.wikipedia.org/wiki/UTF-8#Byte_order_mark 1177 Str =
StringRef(BufRef.data() + 3, BufRef.size() - 3);
1179// Tokenize the contents into NewArgv. 1180 Tokenizer(Str, Saver, NewArgv, MarkEOLs);
1182// Expanded file content may require additional transformations, like using 1183// absolute paths instead of relative in '@file' constructs or expanding 1185if (!RelativeNames && !InConfigFile)
1189for (
constchar *&Arg : NewArgv) {
1193// Substitute <CFGDIR> with the file's base path. 1197// Discover the case, when argument should be transformed into '@file' and 1198// evaluate 'file' for it. 1201bool ConfigInclusion =
false;
1202if (ArgStr.consume_front(
"@")) {
1206 }
elseif (ArgStr.consume_front(
"--config=")) {
1208 ConfigInclusion =
true;
1213// Update expansion construct. 1220 std::make_error_code(std::errc::no_such_file_or_directory),
1221"cannot not find configuration file: " + FileName);
1222 ResponseFile.
append(FilePath);
1224 ResponseFile.
append(BasePath);
1232/// Expand response files on a command line recursively using the given 1233/// StringSaver and tokenization strategy. 1236structResponseFileRecord {
1241// To detect recursive response files, we maintain a stack of files and the 1242// position of the last argument in the file. This position is updated 1243// dynamically as we recursively expand files. 1246// Push a dummy entry that represents the initial command line, removing 1247// the need to check for an empty list. 1250// Don't cache Argv.size() because it can change. 1251for (
unsignedI = 0;
I != Argv.
size();) {
1252while (
I == FileStack.
back().End) {
1253// Passing the end of a file's argument list, so we can remove it from the 1258constchar *Arg = Argv[
I];
1259// Check if it is an EOL marker 1270constchar *FName = Arg + 1;
1271// Note that CurrentDir is only used for top-level rsp files, the rest will 1272// always have an absolute path deduced from the containing file. 1275if (CurrentDir.
empty()) {
1280 CWD.getError(),
Twine(
"cannot get absolute path for: ") + FName);
1283 CurrDir = CurrentDir;
1286 FName = CurrDir.
c_str();
1290if (!Res || !Res->exists()) {
1291 std::error_code EC = Res.
getError();
1293// If the specified file does not exist, leave '@file' unexpanded, as 1303"': " + EC.message());
1308 [FileStatus,
this](
const ResponseFileRecord &RFile) ->
ErrorOr<bool> {
1311returnRHS.getError();
1315// Check for recursive response files. 1320 R.getError(),
Twine(
"recursive expansion of: '") +
F.File +
"'");
1323Twine(
"cannot open file: ") +
F.File);
1327// Replace this response file argument with the tokenization of its 1328// contents. Nested response files are expanded in subsequent iterations. 1330if (
Error Err = expandResponseFile(FName, ExpandedArgv))
1333for (ResponseFileRecord &
Record : FileStack) {
1334// Increase the end of all active records by the number of newly expanded 1335// arguments, minus the response file itself. 1339 FileStack.push_back({FName,
I + ExpandedArgv.
size()});
1344// If successful, the top of the file stack will mark the end of the Argv 1345// stream. A failure here indicates a bug in the stack popping logic above. 1346// Note that FileStack may have more than one element at this point because we 1347// don't have a chance to pop the stack when encountering recursive files at 1348// the end of the stream, so seeing that doesn't indicate a bug. 1361// The environment variable specifies initial options. 1364 Tokenize(*EnvValue, Saver, NewArgv,
/*MarkEOLs=*/false);
1366// Command line options can override the environment variable. 1367 NewArgv.
append(Argv + 1, Argv + Argc);
1387 : Saver(
A), Tokenizer(
T), FS(vfs::getRealFileSystem().
get()) {}
1398// If file name contains directory separator, treat it as a path to 1399// configuration file. 1401 CfgFilePath = FileName;
1404if (!FileExists(CfgFilePath))
1410// Look for the file in search directories. 1417if (FileExists(CfgFilePath)) {
1432return make_error<StringError>(
1433 EC,
Twine(
"cannot get absolute path for " + CfgFile));
1434 CfgFile = AbsPath.
str();
1437 RelativeNames =
true;
1438if (
Error Err = expandResponseFile(CfgFile, Argv))
1447bool LongOptionsUseDoubleDash) {
1454// Parse options from environment variable. 1456if (std::optional<std::string> EnvValue =
1461// Append options from command line. 1462for (
intI = 1;
I < argc; ++
I)
1464int NewArgc =
static_cast<int>(NewArgv.
size());
1466// Parse all options. 1467returnGlobalParser->ParseCommandLineOptions(NewArgc, &NewArgv[0], Overview,
1468 Errs, LongOptionsUseDoubleDash);
1471/// Reset all options at least once, so that we can parse different options. 1472void CommandLineParser::ResetAllOptionOccurrences() {
1473// Reset all option values to look like they have never been seen before. 1474// Options might be reset twice (they can be reference in both OptionsMap 1475// and one of the other members), but that does not harm. 1476for (
auto *SC : RegisteredSubCommands) {
1477for (
auto &O : SC->OptionsMap)
1479for (
Option *O : SC->PositionalOpts)
1481for (
Option *O : SC->SinkOpts)
1483if (SC->ConsumeAfterOpt)
1484 SC->ConsumeAfterOpt->reset();
1488bool CommandLineParser::ParseCommandLineOptions(
int argc,
1489constchar *
const *argv,
1492bool LongOptionsUseDoubleDash) {
1493assert(hasOptions() &&
"No options specified!");
1495 ProgramOverview = Overview;
1496bool IgnoreErrors = Errs;
1499bool ErrorParsing =
false;
1501// Expand response files. 1510if (
Error Err = ECtx.expandResponseFiles(newArgv)) {
1511 *Errs <<
toString(std::move(Err)) <<
'\n';
1515 argc =
static_cast<int>(newArgv.size());
1517// Copy the program name into ProgName, making sure not to overflow it. 1520// Check out the positional arguments to collect information about them. 1521unsigned NumPositionalRequired = 0;
1523// Determine whether or not there are an unlimited number of positionals 1524bool HasUnlimitedPositionals =
false;
1528 std::string NearestSubCommandString;
1529bool MaybeNamedSubCommand =
1530 argc >= 2 && argv[FirstArg][0] !=
'-' && hasNamedSubCommands();
1531if (MaybeNamedSubCommand) {
1532// If the first argument specifies a valid subcommand, start processing 1533// options from the second argument. 1535 LookupSubCommand(
StringRef(argv[FirstArg]), NearestSubCommandString);
1544auto &SinkOpts = ChosenSubCommand->
SinkOpts;
1545auto &OptionsMap = ChosenSubCommand->
OptionsMap;
1547for (
auto *O: DefaultOptions) {
1551if (ConsumeAfterOpt) {
1552assert(PositionalOpts.size() > 0 &&
1553"Cannot specify cl::ConsumeAfter without a positional argument!");
1555if (!PositionalOpts.empty()) {
1557// Calculate how many positional values are _required_. 1558bool UnboundedFound =
false;
1559for (
size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
1560Option *Opt = PositionalOpts[i];
1562 ++NumPositionalRequired;
1563elseif (ConsumeAfterOpt) {
1564// ConsumeAfter cannot be combined with "optional" positional options 1565// unless there is only one positional argument... 1566if (PositionalOpts.size() > 1) {
1568 Opt->
error(
"error - this positional option will never be matched, " 1569"because it does not Require a value, and a " 1570"cl::ConsumeAfter option is active!");
1573 }
elseif (UnboundedFound && !Opt->
hasArgStr()) {
1574// This option does not "require" a value... Make sure this option is 1575// not specified after an option that eats all extra arguments, or this 1576// one will never get any! 1579 Opt->
error(
"error - option can never match, because " 1580"another positional argument will match an " 1581"unbounded number of values, and this option" 1582" does not require a value!");
1583 *Errs << ProgramName <<
": CommandLine Error: Option '" << Opt->
ArgStr 1584 <<
"' is all messed up!\n";
1585 *Errs << PositionalOpts.size();
1590 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
1593// PositionalVals - A vector of "positional" arguments we accumulate into 1594// the process at the end. 1598// If the program has named positional arguments, and the name has been run 1599// across, keep track of which positional argument was named. Otherwise put 1600// the positional args into the PositionalVals list... 1601Option *ActivePositionalArg =
nullptr;
1603// Loop over all of the arguments... processing them. 1604bool DashDashFound =
false;
// Have we read '--'? 1605for (
int i = FirstArg; i < argc; ++i) {
1607 std::string NearestHandlerString;
1610bool HaveDoubleDash =
false;
1612// Check to see if this is a positional argument. This argument is 1613// considered to be positional if it doesn't start with '-', if it is "-" 1614// itself, or if we have seen "--" already. 1616if (argv[i][0] !=
'-' || argv[i][1] == 0 || DashDashFound) {
1617// Positional argument! 1618if (ActivePositionalArg) {
1620continue;
// We are done! 1623if (!PositionalOpts.empty()) {
1626// All of the positional arguments have been fulfulled, give the rest to 1627// the consume after option... if it's specified... 1629if (PositionalVals.
size() >= NumPositionalRequired && ConsumeAfterOpt) {
1630for (++i; i < argc; ++i)
1632break;
// Handle outside of the argument processing loop... 1635// Delay processing positional arguments until the end... 1638 }
elseif (argv[i][0] ==
'-' && argv[i][1] ==
'-' && argv[i][2] == 0 &&
1640 DashDashFound =
true;
// This is the mythical "--"? 1641continue;
// Don't try to process it as an argument itself. 1642 }
elseif (ActivePositionalArg &&
1644// If there is a positional argument eating options, check to see if this 1645// option is another positional argument. If so, treat it as an argument, 1646// otherwise feed it to the eating positional. 1650 HaveDoubleDash =
true;
1652 Handler = LookupLongOption(*ChosenSubCommand, ArgName,
Value,
1653 LongOptionsUseDoubleDash, HaveDoubleDash);
1656continue;
// We are done! 1658 }
else {
// We start with a '-', must be an argument. 1662 HaveDoubleDash =
true;
1664 Handler = LookupLongOption(*ChosenSubCommand, ArgName,
Value,
1665 LongOptionsUseDoubleDash, HaveDoubleDash);
1667// If Handler is not found in a specialized subcommand, look up handler 1668// in the top-level subcommand. 1669// cl::opt without cl::sub belongs to top-level subcommand. 1672 LongOptionsUseDoubleDash, HaveDoubleDash);
1674// Check to see if this "option" is really a prefixed or grouped argument. 1675if (!Handler && !(LongOptionsUseDoubleDash && HaveDoubleDash))
1679// Otherwise, look for the closest available option to report to the user 1680// in the upcoming error. 1681if (!Handler && SinkOpts.empty())
1686if (!SinkOpts.empty()) {
1687for (
Option *SinkOpt : SinkOpts)
1688 SinkOpt->addOccurrence(i,
"",
StringRef(argv[i]));
1692auto ReportUnknownArgument = [&](
bool IsArg,
1694 *Errs << ProgramName <<
": Unknown " 1695 << (IsArg ?
"command line argument" :
"subcommand") <<
" '" 1696 << argv[i] <<
"'. Try: '" << argv[0] <<
" --help'\n";
1698if (NearestArgumentName.empty())
1701 *Errs << ProgramName <<
": Did you mean '";
1703 *Errs << PrintArg(NearestArgumentName, 0);
1705 *Errs << NearestArgumentName;
1709if (i > 1 || !MaybeNamedSubCommand)
1710 ReportUnknownArgument(
/*IsArg=*/true, NearestHandlerString);
1712 ReportUnknownArgument(
/*IsArg=*/false, NearestSubCommandString);
1718// If this is a named positional argument, just remember that it is the 1722 Handler->
error(
"This argument does not take a value.\n" 1723"\tInstead, it consumes any positional arguments until " 1724"the next recognized option.", *Errs);
1727 ActivePositionalArg = Handler;
1733// Check and handle positional arguments now... 1734if (NumPositionalRequired > PositionalVals.
size()) {
1735 *Errs << ProgramName
1736 <<
": Not enough positional command line arguments specified!\n" 1737 <<
"Must specify at least " << NumPositionalRequired
1738 <<
" positional argument" << (NumPositionalRequired > 1 ?
"s" :
"")
1739 <<
": See: " << argv[0] <<
" --help\n";
1742 }
elseif (!HasUnlimitedPositionals &&
1743 PositionalVals.
size() > PositionalOpts.size()) {
1744 *Errs << ProgramName <<
": Too many positional arguments specified!\n" 1745 <<
"Can specify at most " << PositionalOpts.size()
1746 <<
" positional arguments: See: " << argv[0] <<
" --help\n";
1749 }
elseif (!ConsumeAfterOpt) {
1750// Positional args have already been handled if ConsumeAfter is specified. 1751unsigned ValNo = 0, NumVals =
static_cast<unsigned>(PositionalVals.
size());
1752for (
Option *Opt : PositionalOpts) {
1755 PositionalVals[ValNo].second);
1757 --NumPositionalRequired;
// We fulfilled our duty... 1760// If we _can_ give this option more arguments, do so now, as long as we 1761// do not give it values that others need. 'Done' controls whether the 1762// option even _WANTS_ any more. 1765while (NumVals - ValNo > NumPositionalRequired && !
Done) {
1768Done =
true;
// Optional arguments want _at most_ one value 1771casecl::OneOrMore:
// One or more will take all they can get... 1773 PositionalVals[ValNo].second);
1778"positional argument processing!");
1783assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.
size());
1785for (
Option *Opt : PositionalOpts)
1788 Opt, PositionalVals[ValNo].first, PositionalVals[ValNo].second);
1792// Handle the case where there is just one positional option, and it's 1793// optional. In this case, we want to give JUST THE FIRST option to the 1794// positional option and keep the rest for the consume after. The above 1795// loop would have assigned no values to positional options in this case. 1797if (PositionalOpts.size() == 1 && ValNo == 0 && !PositionalVals.
empty()) {
1799 PositionalVals[ValNo].first,
1800 PositionalVals[ValNo].second);
1804// Handle over all of the rest of the arguments to the 1805// cl::ConsumeAfter command line option... 1806for (; ValNo != PositionalVals.
size(); ++ValNo)
1809 PositionalVals[ValNo].second);
1812// Loop over args and make sure all required args are specified! 1813for (
constauto &Opt : OptionsMap) {
1818 Opt.second->
error(
"must be specified at least once!");
1827// Now that we know if -debug is specified, we can use it. 1828// Note that if ReadResponseFiles == true, this must be done before the 1829// memory allocated for the expanded command line is free()d below. 1831for (
int i = 0; i < argc; ++i)
dbgs() << argv[i] <<
' ';
1834// Free all of the memory allocated to the map. Command line options may only 1835// be processed once! 1838// If we had an error processing our arguments, don't let the program execute 1847//===----------------------------------------------------------------------===// 1848// Option Base class implementation 1855 Errs <<
HelpStr;
// Be nice for positional arguments 1857 Errs <<
GlobalParser->ProgramName <<
": for the " << PrintArg(ArgName, 0);
1859 Errs <<
" option: " << Message <<
"\n";
1866 NumOccurrences++;
// Increment the number of times we have been seen 1868return handleOccurrence(pos, ArgName,
Value);
1871// getValueStr - Get the value description string, using "DefaultMsg" if nothing 1872// has been specified yet. 1875if (O.ValueStr.empty())
1880//===----------------------------------------------------------------------===// 1881// cl::alias class implementation 1884// Return the width of the option tag for printing... 1885size_t alias::getOptionWidth()
const{
1890size_t FirstLineIndentedBy) {
1891assert(Indent >= FirstLineIndentedBy);
1892 std::pair<StringRef, StringRef> Split =
HelpStr.
split(
'\n');
1895while (!Split.second.empty()) {
1896 Split = Split.second.split(
'\n');
1902size_t FirstLineIndentedBy) {
1904assert(BaseIndent >= FirstLineIndentedBy);
1905 std::pair<StringRef, StringRef> Split =
HelpStr.
split(
'\n');
1906outs().
indent(BaseIndent - FirstLineIndentedBy)
1908while (!Split.second.empty()) {
1909 Split = Split.second.split(
'\n');
1910outs().
indent(BaseIndent + ValHelpPrefix.
size()) << Split.first <<
"\n";
1914// Print out the option for the alias. 1915void alias::printOptionInfo(
size_t GlobalWidth)
const{
1920//===----------------------------------------------------------------------===// 1921// Parser Implementation code... 1924// basic_parser implementation 1927// Return the width of the option tag for printing... 1931if (!ValName.empty()) {
1932size_t FormattingLen = 3;
1941// printOptionInfo - Print out information about this option. The 1942// to-be-maintained width is specified. 1945size_t GlobalWidth)
const{
1946outs() << PrintArg(O.ArgStr);
1949if (!ValName.empty()) {
1964size_t GlobalWidth)
const{
1965outs() << PrintArg(O.ArgStr);
1969// parser<bool> implementation 1973return parseBool<bool, true, false>(O, ArgName, Arg,
Value);
1976// parser<boolOrDefault> implementation 1980return parseBool<boolOrDefault, BOU_TRUE, BOU_FALSE>(O, ArgName, Arg,
Value);
1983// parser<int> implementation 1988return O.error(
"'" + Arg +
"' value invalid for integer argument!");
1992// parser<long> implementation 1997returnO.error(
"'" + Arg +
"' value invalid for long argument!");
2001// parser<long long> implementation 2006returnO.error(
"'" + Arg +
"' value invalid for llong argument!");
2010// parser<unsigned> implementation 2016returnO.error(
"'" + Arg +
"' value invalid for uint argument!");
2020// parser<unsigned long> implementation 2023unsignedlong &
Value) {
2026returnO.error(
"'" + Arg +
"' value invalid for ulong argument!");
2030// parser<unsigned long long> implementation 2034unsignedlonglong &
Value) {
2037returnO.error(
"'" + Arg +
"' value invalid for ullong argument!");
2041// parser<double>/parser<float> implementation 2044if (to_float(Arg,
Value))
2046return O.error(
"'" + Arg +
"' value invalid for floating point argument!");
2063// generic_parser_base implementation 2066// findOption - Return the option number corresponding to the specified 2067// argument string. If the option is not found, getNumOptions() is returned. 2072for (
unsigned i = 0; i != e; ++i) {
2089 !Description.
empty();
2092// Return the width of the option tag for printing... 2113// printOptionInfo - Print out information about this option. The 2114// to-be-maintained width is specified. 2117size_t GlobalWidth)
const{
2119// When the value is optional, first print a line just describing the 2120// option without values. 2124outs() << PrintArg(O.ArgStr);
2143if (OptionName.
empty()) {
2148if (!Description.
empty())
2154if (!O.HelpStr.empty())
2155outs() <<
" " << O.HelpStr <<
'\n';
2164staticconstsize_tMaxOptWidth = 8;
// arbitrary spacing for printOptionDiff 2166// printGenericOptionDiff - Print the value of this option and it's default. 2168// "Generic" options have each value mapped to a name. 2172outs() <<
" " << PrintArg(O.ArgStr);
2176for (
unsigned i = 0; i != NumOpts; ++i) {
2184for (
unsigned j = 0; j != NumOpts; ++j) {
2193outs() <<
"= *unknown option value*\n";
2196// printOptionDiff - Specializations for printing basic value types. 2198#define PRINT_OPT_DIFF(T) \ 2199 void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D, \ 2200 size_t GlobalWidth) const { \ 2201 printOptionName(O, GlobalWidth); \ 2204 raw_string_ostream SS(Str); \ 2207 outs() << "= " << Str; \
2208 size_t NumSpaces = \
2209 MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0; \
2210 outs().indent(NumSpaces) << " (default: "; \
2212 outs() << D.getValue(); \
2214 outs() << "*no default*"; \
2232size_t GlobalWidth)
const{
2233 printOptionName(O, GlobalWidth);
2238outs() <<
D.getValue();
2240outs() <<
"*no default*";
2244// Print a placeholder for options that don't yet support printOptionDiff(). 2246size_t GlobalWidth)
const{
2248outs() <<
"= *cannot print option value*\n";
2251//===----------------------------------------------------------------------===// 2252// -help and -help-hidden option implementation 2256const std::pair<const char *, Option *> *RHS) {
2257return strcmp(
LHS->first,
RHS->first);
2261const std::pair<const char *, SubCommand *> *RHS) {
2262return strcmp(
LHS->first,
RHS->first);
2265// Copy Options into a vector so we can sort them as we like. 2273// Ignore really-hidden options. 2277// Unless showhidden is set, ignore hidden flags. 2278if (
I->second->getOptionHiddenFlag() ==
Hidden && !ShowHidden)
2281// If we've already seen this option, don't add it to the list again. 2282if (!OptionSet.
insert(
I->second).second)
2286 std::pair<const char *, Option *>(
I->getKey().data(),
I->second));
2289// Sort the options list alphabetically. 2296for (
auto *S : SubMap) {
2297if (S->getName().empty())
2299 Subs.push_back(std::make_pair(S->getName().data(), S));
2308constbool ShowHidden;
2310 StrOptionPairVector;
2312 StrSubCommandPairVector;
2313// Print the options. Opts is assumed to be alphabetically sorted. 2314virtualvoid printOptions(StrOptionPairVector &Opts,
size_t MaxArgLen) {
2315for (
size_t i = 0, e = Opts.size(); i != e; ++i)
2316 Opts[i].second->printOptionInfo(MaxArgLen);
2319void printSubCommands(StrSubCommandPairVector &Subs,
size_t MaxSubLen) {
2320for (
constauto &S : Subs) {
2321outs() <<
" " << S.first;
2322if (!S.second->getDescription().empty()) {
2324outs() <<
" - " << S.second->getDescription();
2331explicit HelpPrinter(
bool showHidden) : ShowHidden(showHidden) {}
2332virtual ~HelpPrinter() =
default;
2334// Invoke the printer. 2335void operator=(
boolValue) {
2340// Halt the program since help information was printed 2350 StrOptionPairVector Opts;
2351sortOpts(OptionsMap, Opts, ShowHidden);
2353 StrSubCommandPairVector Subs;
2362outs() <<
" [subcommand]";
2363outs() <<
" [options]";
2373for (
auto *Opt : PositionalOpts) {
2379// Print the consume after option info if it exists... 2381outs() <<
" " << ConsumeAfterOpt->HelpStr;
2384// Compute the maximum subcommand length... 2385size_t MaxSubLen = 0;
2386for (
size_t i = 0, e = Subs.size(); i != e; ++i)
2387 MaxSubLen = std::max(MaxSubLen, strlen(Subs[i].first));
2390outs() <<
"SUBCOMMANDS:\n\n";
2391 printSubCommands(Subs, MaxSubLen);
2394 <<
" <subcommand> --help\" to get more help on a specific " 2400// Compute the maximum argument length... 2401size_t MaxArgLen = 0;
2402for (
size_t i = 0, e = Opts.size(); i != e; ++i)
2403 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
2405outs() <<
"OPTIONS:\n";
2406 printOptions(Opts, MaxArgLen);
2408// Print any extra help the user has declared. 2415classCategorizedHelpPrinter :
public HelpPrinter {
2417explicit CategorizedHelpPrinter(
bool showHidden) : HelpPrinter(showHidden) {}
2419// Helper function for printOptions(). 2420// It shall return a negative value if A's name should be lexicographically 2421// ordered before B's name. It returns a value greater than zero if B's name 2422// should be ordered before A's name, and it returns 0 otherwise. 2425return (*A)->getName().compare((*B)->getName());
2428// Make sure we inherit our base class's operator=() 2429usingHelpPrinter::operator=;
2432void printOptions(StrOptionPairVector &Opts,
size_t MaxArgLen)
override{
2433 std::vector<OptionCategory *> SortedCategories;
2436// Collect registered option categories into vector in preparation for 2439 SortedCategories.push_back(Category);
2441// Sort the different option categories alphabetically. 2442assert(SortedCategories.size() > 0 &&
"No option categories registered!");
2444 OptionCategoryCompare);
2446// Walk through pre-sorted options and assign into categories. 2447// Because the options are already alphabetically sorted the 2448// options within categories will also be alphabetically sorted. 2449for (
size_tI = 0,
E = Opts.size();
I !=
E; ++
I) {
2453"Option has an unregistered category");
2454 CategorizedOptions[Cat].push_back(Opt);
2460// Hide empty categories for --help, but show for --help-hidden. 2461constauto &CategoryOptions = CategorizedOptions[Category];
2462if (CategoryOptions.empty())
2465// Print category information. 2469// Check if description is set. 2475// Loop over the options in the category and print. 2476for (
constOption *Opt : CategoryOptions)
2482// This wraps the Uncategorizing and Categorizing printers and decides 2483// at run time which should be invoked. 2484classHelpPrinterWrapper {
2486 HelpPrinter &UncategorizedPrinter;
2487 CategorizedHelpPrinter &CategorizedPrinter;
2490explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
2491 CategorizedHelpPrinter &CategorizedPrinter)
2492 : UncategorizedPrinter(UncategorizedPrinter),
2493 CategorizedPrinter(CategorizedPrinter) {}
2495// Invoke the printer. 2496void operator=(
boolValue);
2499}
// End anonymous namespace 2501#if defined(__GNUC__) 2502// GCC and GCC-compatible compilers define __OPTIMIZE__ when optimizations are 2504# if defined(__OPTIMIZE__) 2505# define LLVM_IS_DEBUG_BUILD 0 2507# define LLVM_IS_DEBUG_BUILD 1 2509#elif defined(_MSC_VER) 2510// MSVC doesn't have a predefined macro indicating if optimizations are enabled. 2511// Use _DEBUG instead. This macro actually corresponds to the choice between 2512// debug and release CRTs, but it is a reasonable proxy. 2514# define LLVM_IS_DEBUG_BUILD 1 2516# define LLVM_IS_DEBUG_BUILD 0 2519// Otherwise, for an unknown compiler, assume this is an optimized build. 2520# define LLVM_IS_DEBUG_BUILD 0 2524classVersionPrinter {
2526voidprint(std::vector<VersionPrinterTy> ExtraPrinters = {}) {
2528#ifdef PACKAGE_VENDOR 2529OS << PACKAGE_VENDOR <<
" ";
2531OS <<
"LLVM (http://llvm.org/):\n ";
2533OS << PACKAGE_NAME <<
" version " << PACKAGE_VERSION <<
"\n ";
2534#if LLVM_IS_DEBUG_BUILD 2537OS <<
"Optimized build";
2540OS <<
" with assertions";
2544// Iterate over any registered extra printers and call them to add further 2546if (!ExtraPrinters.empty()) {
2547for (
constauto &
I : ExtraPrinters)
2551void operator=(
bool OptionWasSpecified);
2554structCommandLineCommonOptions {
2555// Declare the four HelpPrinter instances that are used to print out help, or 2556// help-hidden as an uncategorized list or in categories. 2557 HelpPrinter UncategorizedNormalPrinter{
false};
2558 HelpPrinter UncategorizedHiddenPrinter{
true};
2559 CategorizedHelpPrinter CategorizedNormalPrinter{
false};
2560 CategorizedHelpPrinter CategorizedHiddenPrinter{
true};
2561// Declare HelpPrinter wrappers that will decide whether or not to invoke 2562// a categorizing help printer 2563 HelpPrinterWrapper WrappedNormalPrinter{UncategorizedNormalPrinter,
2564 CategorizedNormalPrinter};
2565 HelpPrinterWrapper WrappedHiddenPrinter{UncategorizedHiddenPrinter,
2566 CategorizedHiddenPrinter};
2567// Define a category for generic options that all tools should have. 2570// Define uncategorized help printers. 2571// --help-list is hidden by default because if Option categories are being 2572// used then --help behaves the same as --help-list. 2576"Display list of available options (--help-list-hidden for more)"),
2585cl::desc(
"Display list of all available options"),
2592// Define uncategorized/categorized help printers. These printers change their 2593// behaviour at runtime depending on whether one or more Option categories 2594// have been declared. 2597cl::desc(
"Display available options (--help-hidden for more)"),
2608cl::desc(
"Display all available options"),
2617cl::desc(
"Print non-default options after command line parsing"),
2625cl::desc(
"Print all option values after command line parsing"),
2633 std::vector<VersionPrinterTy> ExtraVersionPrinters;
2635// Define the --version option that prints out the LLVM version for the tool 2636 VersionPrinter VersionPrinterInstance;
2639"version",
cl::desc(
"Display the version of this program"),
2643}
// End anonymous namespace 2645// Lazy-initialized global instance of options controlling the command-line 2646// parser and general handling. 2663// Initialise the general option category. 2665return GeneralCategory;
2668void VersionPrinter::operator=(
bool OptionWasSpecified) {
2669if (!OptionWasSpecified)
2681void HelpPrinterWrapper::operator=(
boolValue) {
2685// Decide which printer to invoke. If more than one option category is 2686// registered then it is useful to show the categorized help instead of 2687// uncategorized help. 2688if (
GlobalParser->RegisteredOptionCategories.size() > 1) {
2689// unhide --help-list option so user can have uncategorized output if they 2693 CategorizedPrinter =
true;
// Invoke categorized printer 2695 UncategorizedPrinter =
true;
// Invoke uncategorized printer 2698// Print the value of each option. 2701void CommandLineParser::printOptionValues() {
2708// Compute the maximum argument length... 2709size_t MaxArgLen = 0;
2710for (
size_t i = 0, e = Opts.
size(); i != e; ++i)
2711 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
2713for (
size_t i = 0, e = Opts.
size(); i != e; ++i)
2714 Opts[i].second->printOptionValue(MaxArgLen,
CommonOptions->PrintAllOptions);
2717// Utility function for printing the help message. 2719if (!
Hidden && !Categorized)
2721elseif (!
Hidden && Categorized)
2723elseif (
Hidden && !Categorized)
2731// Placeholder to ensure the array always has elements, since it's an 2732// error to have a zero-sized array. Slice this off before returning. 2734// Actual compiler build config feature list: 2735#if LLVM_IS_DEBUG_BUILD 2741#ifdef EXPENSIVE_CHECKS 2744#if __has_feature(address_sanitizer) 2747#if __has_feature(dataflow_sanitizer) 2750#if __has_feature(hwaddress_sanitizer) 2753#if __has_feature(memory_sanitizer) 2756#if __has_feature(thread_sanitizer) 2759#if __has_feature(undefined_behavior_sanitizer) 2766// Utility function for printing the build config. 2768#if LLVM_VERSION_PRINTER_SHOW_BUILD_CONFIG 2769OS <<
"Build config: ";
2775/// Utility function for printing version number. 2792assert(Subs.contains(&Sub));
2804bool Unrelated =
true;
2805for (
auto &Cat :
I.second->Categories) {
2806if (Cat == &Category || Cat == &
CommonOptions->GenericCategory)
2818bool Unrelated =
true;
2819for (
auto &Cat :
I.second->Categories) {
2835constchar *Overview) {
This file defines the StringMap class.
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
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 bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos, StringRef ArgName, StringRef Value, bool MultiArg=false)
CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence() that does special handling ...
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 isPrefixedOrGrouping(const Option *O)
static bool shouldPrintOption(StringRef Name, StringRef Description, const Option &O)
static ManagedStatic< SubCommand > AllSubCommands
static Option * HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value, bool &ErrorParsing, const StringMap< Option * > &OptionsMap)
HandlePrefixedOrGroupedOption - The specified argument string (which started with at least one '-') d...
static bool parseDouble(Option &O, StringRef Arg, double &Value)
static bool parseBool(Option &O, StringRef ArgName, StringRef Arg, T &Value)
static const size_t DefaultPad
static StringRef EmptyOption
static bool hasUTF8ByteOrderMark(ArrayRef< char > S)
static ManagedStatic< CommandLineParser > GlobalParser
static void ExpandBasePaths(StringRef BasePath, StringSaver &Saver, const char *&Arg)
static SmallString< 8 > argPrefix(StringRef ArgName, size_t Pad=DefaultPad)
static StringRef ArgHelpPrefix
static bool isWindowsSpecialCharInCommandName(char C)
static Option * getOptionPred(StringRef Name, size_t &Length, bool(*Pred)(const Option *), const StringMap< Option * > &OptionsMap)
static StringRef getValueStr(const Option &O, StringRef DefaultMsg)
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 tokenizeWindowsCommandLineImpl(StringRef Src, StringSaver &Saver, function_ref< void(StringRef)> AddToken, bool AlwaysCopy, function_ref< void()> MarkEOL, bool InitialCommandName)
static bool isWhitespace(char C)
static LLVM_REQUIRE_CONSTANT_INITIALIZATION ManagedStatic< SubCommand > TopLevelSubCommand
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 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 Option * LookupNearestOption(StringRef Arg, const StringMap< Option * > &OptionsMap, std::string &NearestString)
LookupNearestOption - Lookup the closest match to the option specified by the specified option on the...
static bool EatsUnboundedNumberOfValues(const Option *O)
static int OptNameCompare(const std::pair< const char *, Option * > *LHS, const std::pair< const char *, Option * > *RHS)
static void sortOpts(StringMap< Option * > &OptMap, SmallVectorImpl< std::pair< const char *, Option * > > &Opts, bool ShowHidden)
static StringRef ArgPrefix
static bool isWindowsSpecialChar(char C)
static bool isGrouping(const Option *O)
#define LLVM_REQUIRE_CONSTANT_INITIALIZATION
LLVM_REQUIRE_CONSTANT_INITIALIZATION - Apply this to globals to ensure that they are constant initial...
static void Help(ArrayRef< StringRef > 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 ...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the SmallPtrSet class.
This file defines the SmallString class.
This file contains some functions that are useful when dealing with strings.
Defines the virtual file system interface vfs::FileSystem.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
ArrayRef< T > drop_front(size_t N=1) const
Drop the first N elements of the array.
size_t size() const
size - Get the array size.
Allocate memory in an ever growing pool, as if by bump-pointer.
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...
This interface provides simple read-only access to a block of memory, and provides simple methods for...
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...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
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)
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...
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
iterator find(StringRef Key)
size_type count(StringRef Key) const
count - Return 1 if the element is in the map, 0 otherwise.
StringRef - 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.
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
empty - Check if the string is empty.
unsigned edit_distance(StringRef Other, bool AllowReplacements=true, unsigned MaxEditDistance=0) const
Determine the edit distance between this string and another string.
constexpr size_t size() const
size - Get the string size.
constexpr const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
bool consume_front(StringRef Prefix)
Returns true if this StringRef has the given prefix and removes that prefix.
size_t find(char C, size_t From=0) const
Search for the first character C in the string.
static constexpr size_t npos
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.
bool findConfigFile(StringRef FileName, SmallVectorImpl< char > &FilePath)
Looks for the specified configuration file.
ExpansionContext(BumpPtrAllocator &A, TokenizerCallback T)
Error expandResponseFiles(SmallVectorImpl< const char * > &Argv)
Expands constructs "@file" in the provided array of arguments recursively.
Error readConfigFile(StringRef CfgFile, SmallVectorImpl< const char * > &Argv)
Reads command line options from the given configuration file.
StringRef getDescription() const
StringRef getName() const
SmallPtrSet< SubCommand *, 1 > Subs
int getNumOccurrences() const
enum ValueExpected getValueExpectedFlag() const
void addCategory(OptionCategory &C)
virtual bool addOccurrence(unsigned pos, StringRef ArgName, StringRef Value, bool MultiArg=false)
void setMiscFlag(enum MiscFlags M)
enum FormattingFlags getFormattingFlag() const
virtual void printOptionInfo(size_t GlobalWidth) const =0
enum NumOccurrencesFlag getNumOccurrencesFlag() const
SmallVector< OptionCategory *, 1 > Categories
bool error(const Twine &Message, StringRef ArgName=StringRef(), raw_ostream &Errs=llvm::errs())
void setArgStr(StringRef S)
bool isDefaultOption() const
unsigned getMiscFlags() const
virtual void setDefault()=0
static void printEnumValHelpStr(StringRef HelpStr, size_t Indent, size_t FirstLineIndentedBy)
unsigned getNumAdditionalVals() const
void removeArgument()
Unregisters this option from the CommandLine system.
static void printHelpStr(StringRef HelpStr, size_t Indent, size_t FirstLineIndentedBy)
StringRef getName() const
SmallVector< Option *, 4 > SinkOpts
static SubCommand & getTopLevel()
void unregisterSubCommand()
static SubCommand & getAll()
void registerSubCommand()
SmallVector< Option *, 4 > PositionalOpts
StringMap< Option * > OptionsMap
StringRef getDescription() const
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 printOptionDiff(const Option &O, const AnyOptionValue &V, const AnyOptionValue &Default, size_t GlobalWidth) const
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.
static std::optional< std::string > GetEnv(StringRef name)
virtual llvm::ErrorOr< std::string > getCurrentWorkingDirectory() const =0
Get the working directory of this file system.
virtual std::error_code makeAbsolute(SmallVectorImpl< char > &Path) const
Make Path an absolute path.
llvm::ErrorOr< std::unique_ptr< llvm::MemoryBuffer > > getBufferForFile(const Twine &Name, int64_t FileSize=-1, bool RequiresNullTerminator=true, bool IsVolatile=false, bool IsText=true)
This is a convenience method that opens a file, gets its content and then closes the file.
virtual llvm::ErrorOr< Status > status(const Twine &Path)=0
Get the status of the entry at Path, if one exists.
The result of a status operation.
bool equivalent(const Status &Other) const
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.
@ C
The default llvm calling convention, compatible with C.
@ SC
CHAIN = SC CHAIN, Imm128 - System call.
constexpr size_t NameSize
std::function< void(raw_ostream &)> VersionPrinterTy
void(*)(StringRef Source, StringSaver &Saver, SmallVectorImpl< const char * > &NewArgv, bool MarkEOLs) TokenizerCallback
String tokenization function type.
void PrintVersionMessage()
Utility function for printing version number.
bool ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer, SmallVectorImpl< const char * > &Argv)
A convenience helper which supports the typical use case of expansion function call.
bool expandResponseFiles(int Argc, const char *const *Argv, const char *EnvVar, SmallVectorImpl< const char * > &NewArgv)
A convenience helper which concatenates the options specified by the environment variable EnvVar and ...
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.
OptionCategory & getGeneralCategory()
void ResetAllOptionOccurrences()
Reset all command line options to a state that looks as if they have never appeared on the command li...
void SetVersionPrinter(VersionPrinterTy func)
===------------------------------------------------------------------—===// Override the default (LLV...
void tokenizeConfigFile(StringRef Source, StringSaver &Saver, SmallVectorImpl< const char * > &NewArgv, bool MarkEOLs=false)
Tokenizes content of configuration file.
StringMap< Option * > & getRegisteredOptions(SubCommand &Sub=SubCommand::getTopLevel())
Use this to get a StringMap to all registered named options (e.g.
void ResetCommandLineParser()
Reset the command line parser back to its initial state.
bool ParseCommandLineOptions(int argc, const char *const *argv, StringRef Overview="", raw_ostream *Errs=nullptr, const char *EnvVar=nullptr, bool LongOptionsUseDoubleDash=false)
iterator_range< typename SmallPtrSet< SubCommand *, 4 >::iterator > getRegisteredSubcommands()
Use this to get all registered SubCommands from the provided parser.
void AddLiteralOption(Option &O, StringRef Name)
Adds a new option for parsing and provides the option it refers to.
void TokenizeWindowsCommandLineNoCopy(StringRef Source, StringSaver &Saver, SmallVectorImpl< StringRef > &NewArgv)
Tokenizes a Windows command line while attempting to avoid copies.
void printBuildConfig(raw_ostream &OS)
Prints the compiler build configuration.
bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i)
Parses Arg into the option handler Handler.
initializer< Ty > init(const Ty &Val)
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)
void HideUnrelatedOptions(cl::OptionCategory &Category, SubCommand &Sub=SubCommand::getTopLevel())
Mark all options not part of this category as cl::ReallyHidden.
void AddExtraVersionPrinter(VersionPrinterTy func)
===------------------------------------------------------------------—===// Add an extra printer to u...
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...
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.
void TokenizeGNUCommandLine(StringRef Source, StringSaver &Saver, SmallVectorImpl< const char * > &NewArgv, bool MarkEOLs=false)
Tokenizes a command line that can contain escapes and quotes.
StringRef parent_path(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get parent path.
bool has_parent_path(const Twine &path, Style style=Style::native)
Has parent path?
bool is_relative(const Twine &path, Style style=Style::native)
Is path relative?
StringRef filename(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get filename.
bool is_absolute(const Twine &path, Style style=Style::native)
Is path absolute?
void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
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.
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 interleaveComma(const Container &c, StreamT &os, UnaryFunctor each_fn)
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.
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr)
@ no_such_file_or_directory
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
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 initTypeSizeOptions()
void initStatisticOptions()
raw_ostream & nulls()
This returns a reference to a raw_ostream which simply discards output.
raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
void initRandomSeedOptions()
void initGraphWriterOptions()
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
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.
const char * toString(DWARFSectionKind Kind)
void array_pod_sort(IteratorTy Start, IteratorTy End)
array_pod_sort - This sorts an array with the specified start and end extent.
@ Default
The result values are uniform if and only if all operands are uniform.
extrahelp(StringRef help)