31#include "llvm/Config/config.h"
52#define DEBUG_TYPE "commandline"
73#if !(defined(LLVM_ENABLE_LLVM_EXPORT_ANNOTATIONS) && defined(_MSC_VER))
90void GenericOptionValue::anchor() {}
91void OptionValue<boolOrDefault>::anchor() {}
92void OptionValue<std::string>::anchor() {}
93void Option::anchor() {}
128 size_t Len = ArgName.
size();
136 for (
size_t I = 0;
I < Pad; ++
I) {
165 OS <<
argPrefix(Arg.ArgName, Arg.Pad) << Arg.ArgName;
169class CommandLineParser {
173 std::string ProgramName;
177 std::vector<StringRef> MoreHelp;
197 bool LongOptionsUseDoubleDash =
false);
200 if (Opt.
Subs.empty()) {
205 for (
auto *SC : RegisteredSubCommands)
210 for (
auto *SC : Opt.
Subs) {
212 "SubCommand::getAll() should not be used with other subcommands");
221 errs() << ProgramName <<
": CommandLine Error: Option '" << Name
222 <<
"' registered more than once!\n";
229 Opt, [&](
SubCommand &SC) { addLiteralOption(Opt, &SC, Name); });
233 bool HadErrors =
false;
234 if (O->hasArgStr()) {
241 errs() << ProgramName <<
": CommandLine Error: Option '" << O->ArgStr
242 <<
"' registered more than once!\n";
250 else if (O->getMiscFlags() &
cl::Sink)
254 O->error(
"Cannot specify more than one option with cl::ConsumeAfter!");
268 void addOption(
Option *O,
bool ProcessDefaultOption =
false) {
269 if (!ProcessDefaultOption && O->isDefaultOption()) {
273 forEachSubCommand(*O, [&](
SubCommand &SC) { addOption(O, &SC); });
278 O->getExtraOptionNames(OptionNames);
283 for (
auto Name : OptionNames) {
284 auto I =
Sub.OptionsMap.find(Name);
287 if (
I !=
Sub.OptionsMap.end() &&
I->second == O)
288 Sub.OptionsMap.erase(
I);
292 for (
auto *Opt =
Sub.PositionalOpts.begin();
293 Opt !=
Sub.PositionalOpts.end(); ++Opt) {
295 Sub.PositionalOpts.erase(Opt);
299 else if (O->getMiscFlags() &
cl::Sink)
300 for (
auto *Opt =
Sub.SinkOpts.begin(); Opt !=
Sub.SinkOpts.end(); ++Opt) {
302 Sub.SinkOpts.erase(Opt);
306 else if (O ==
Sub.ConsumeAfterOpt)
307 Sub.ConsumeAfterOpt =
nullptr;
310 void removeOption(
Option *O) {
311 forEachSubCommand(*O, [&](
SubCommand &SC) { removeOption(O, &SC); });
315 return (!
Sub.OptionsMap.empty() || !
Sub.PositionalOpts.empty() ||
316 nullptr !=
Sub.ConsumeAfterOpt);
319 bool hasOptions()
const {
320 for (
const auto *S : RegisteredSubCommands) {
327 bool hasNamedSubCommands()
const {
328 for (
const auto *S : RegisteredSubCommands)
329 if (!S->getName().empty())
334 SubCommand *getActiveSubCommand() {
return ActiveSubCommand; }
338 if (!
Sub.OptionsMap.insert(std::make_pair(NewName, O)).second) {
339 errs() << ProgramName <<
": CommandLine Error: Option '" << O->ArgStr
340 <<
"' registered more than once!\n";
343 Sub.OptionsMap.erase(O->ArgStr);
347 forEachSubCommand(*O,
348 [&](
SubCommand &SC) { updateArgStr(O, NewName, &SC); });
351 void printOptionValues();
358 "Duplicate option categories");
366 return (!
sub->getName().empty()) &&
367 (
Sub->getName() ==
sub->getName());
369 "Duplicate subcommands");
375 "SubCommand::getAll() should not be registered");
378 if ((O->isPositional() || O->isSink() || O->isConsumeAfter()) ||
382 addLiteralOption(*O,
sub,
E.first);
393 RegisteredSubCommands.
end());
397 ActiveSubCommand =
nullptr;
402 RegisteredOptionCategories.
clear();
405 RegisteredSubCommands.
clear();
411 DefaultOptions.
clear();
419 bool LongOptionsUseDoubleDash,
bool HaveDoubleDash) {
421 if (Opt && LongOptionsUseDoubleDash && !HaveDoubleDash && !
isGrouping(Opt))
437 return *GlobalParser;
440template <
typename T, T TrueVal, T FalseVal>
442 if (Arg ==
"" || Arg ==
"true" || Arg ==
"TRUE" || Arg ==
"True" ||
448 if (Arg ==
"false" || Arg ==
"FALSE" || Arg ==
"False" || Arg ==
"0") {
452 return O.error(
"'" + Arg +
453 "' is invalid value for boolean argument! Try 0 or 1");
465 : NumOccurrences(0), Occurrences(OccurrencesFlag), Value(0),
467 FullyInitialized(
false), Position(0), AdditionalVals(0) {
473 FullyInitialized =
true;
479 if (FullyInitialized)
505void OptionCategory::registerCategory() {
516 return *TopLevelSubCommand;
522 return *AllSubCommands;
541SubCommand::operator
bool()
const {
559 size_t EqualPos = Arg.
find(
'=');
564 return Sub.OptionsMap.lookup(Arg);
570 auto I =
Sub.OptionsMap.find(Arg.
substr(0, EqualPos));
571 if (
I ==
Sub.OptionsMap.end())
579 Arg = Arg.
substr(0, EqualPos);
584 std::string &NearestString) {
589 for (
auto *S : RegisteredSubCommands) {
591 "SubCommand::getAll() is not expected in RegisteredSubCommands");
592 if (S->getName().empty())
595 if (S->getName() == Name)
598 if (!NearestMatch && S->getName().edit_distance(Name) < 2)
603 NearestString = NearestMatch->
getName();
614 std::string &NearestString) {
620 std::pair<StringRef, StringRef> SplitArg = Arg.
split(
'=');
626 unsigned BestDistance = 0;
627 for (
const auto &[
_, O] : OptionsMap) {
633 O->getExtraOptionNames(OptionNames);
639 for (
const auto &Name : OptionNames) {
641 Flag,
true, BestDistance);
642 if (!Best || Distance < BestDistance) {
644 BestDistance = Distance;
645 if (
RHS.empty() || !PermitValue)
646 NearestString = std::string(Name);
648 NearestString = (
Twine(Name) +
"=" +
RHS).str();
660 bool MultiArg =
false) {
672 Val = Val.
substr(Pos + 1);
688 const char *
const *argv,
int &i) {
699 return Handler->
error(
"requires a value!");
701 assert(argv &&
"null check");
706 if (NumAdditionalVals > 0)
707 return Handler->
error(
"multi-valued option specified"
708 " with ValueDisallowed modifier!");
719 if (NumAdditionalVals == 0)
723 bool MultiArg =
false;
732 while (NumAdditionalVals > 0) {
734 return Handler->
error(
"not enough values!");
735 assert(argv &&
"null check");
758 bool (*Pred)(
const Option *),
760 auto OMI = OptionsMap.
find(Name);
761 if (OMI != OptionsMap.
end() && !Pred(OMI->second))
762 OMI = OptionsMap.
end();
767 while (OMI == OptionsMap.
end() && Name.size() > 1) {
768 Name = Name.drop_back();
769 OMI = OptionsMap.
find(Name);
770 if (OMI != OptionsMap.
end() && !Pred(OMI->second))
771 OMI = OptionsMap.
end();
774 if (OMI != OptionsMap.
end() && Pred(OMI->second)) {
801 assert(OptionsMap.
count(Arg) && OptionsMap.
find(Arg)->second == PGOpt);
811 if (MaybeValue[0] ==
'=') {
821 ErrorParsing |= PGOpt->
error(
"may not occur within a group!");
850 return C ==
' ' ||
C ==
'\t' ||
C ==
'\r' ||
C ==
'\n';
857static bool isQuote(
char C) {
return C ==
'\"' ||
C ==
'\''; }
863 bool InToken =
false;
864 for (
size_t I = 0, E = Src.size();
I != E; ++
I) {
869 if (MarkEOLs && Src[
I] ==
'\n')
881 if (
I + 1 < E &&
C ==
'\\') {
890 while (
I != E && Src[
I] !=
C) {
892 if (Src[
I] ==
'\\' &&
I + 1 != E)
906 if (MarkEOLs &&
C ==
'\n')
940 size_t E = Src.size();
941 int BackslashCount = 0;
946 }
while (
I !=
E && Src[
I] ==
'\\');
948 bool FollowedByDoubleQuote = (
I !=
E && Src[
I] ==
'"');
949 if (FollowedByDoubleQuote) {
950 Token.
append(BackslashCount / 2,
'\\');
951 if (BackslashCount % 2 == 0)
956 Token.
append(BackslashCount,
'\\');
974 bool AlwaysCopy,
function_ref<
void()> MarkEOL,
bool InitialCommandName) {
983 bool CommandName = InitialCommandName;
986 enum {
INIT, UNQUOTED, QUOTED } State =
INIT;
988 for (
size_t I = 0,
E = Src.size();
I <
E; ++
I) {
991 assert(Token.
empty() &&
"token should be empty in initial state");
1013 AddToken(AlwaysCopy ? Saver.
save(NormalChars) : NormalChars);
1014 if (
I <
E && Src[
I] ==
'\n') {
1016 CommandName = InitialCommandName;
1018 CommandName =
false;
1020 }
else if (Src[
I] ==
'\"') {
1021 Token += NormalChars;
1023 }
else if (Src[
I] ==
'\\') {
1024 assert(!CommandName &&
"or else we'd have treated it as a normal char");
1025 Token += NormalChars;
1039 AddToken(Saver.
save(Token.
str()));
1041 if (Src[
I] ==
'\n') {
1042 CommandName = InitialCommandName;
1045 CommandName =
false;
1048 }
else if (Src[
I] ==
'\"') {
1050 }
else if (Src[
I] ==
'\\' && !CommandName) {
1058 if (Src[
I] ==
'\"') {
1059 if (
I < (
E - 1) && Src[
I + 1] ==
'"') {
1068 }
else if (Src[
I] ==
'\\' && !CommandName) {
1078 AddToken(Saver.
save(Token.
str()));
1085 auto OnEOL = [&]() {
1090 true, OnEOL,
false);
1096 auto OnEOL = []() {};
1105 auto OnEOL = [&]() {
1116 for (
const char *Cur = Source.begin(); Cur != Source.end();) {
1125 while (Cur != Source.end() && *Cur !=
'\n')
1130 const char *Start = Cur;
1131 for (
const char *End = Source.end(); Cur != End; ++Cur) {
1133 if (Cur + 1 != End) {
1136 (*Cur ==
'\r' && (Cur + 1 != End) && Cur[1] ==
'\n')) {
1137 Line.append(Start, Cur - 1);
1143 }
else if (*Cur ==
'\n')
1147 Line.append(Start, Cur);
1155 return (S.
size() >= 3 && S[0] ==
'\xef' && S[1] ==
'\xbb' && S[2] ==
'\xbf');
1169 TokenPos = ArgString.
find(Token, StartPos)) {
1173 if (ResponseFile.
empty())
1177 ResponseFile.
append(BasePath);
1178 StartPos = TokenPos + Token.
size();
1181 if (!ResponseFile.
empty()) {
1184 if (!Remaining.
empty())
1191Error ExpansionContext::expandResponseFile(
1192 StringRef FName, SmallVectorImpl<const char *> &NewArgv) {
1194 llvm::ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
1195 FS->getBufferForFile(FName);
1199 "': " +
EC.message());
1201 MemoryBuffer &MemBuf = *MemBufOrErr.
get();
1206 std::string UTF8Buf;
1210 "Could not convert UTF16 to UTF8");
1211 Str = StringRef(UTF8Buf);
1217 Str = StringRef(BufRef.data() + 3, BufRef.size() - 3);
1220 Tokenizer(Str, Saver, NewArgv, MarkEOLs);
1225 if (!RelativeNames && !InConfigFile)
1229 for (
const char *&Arg : NewArgv) {
1239 StringRef ArgStr(Arg);
1241 bool ConfigInclusion =
false;
1242 if (ArgStr.consume_front(
"@")) {
1246 }
else if (ArgStr.consume_front(
"--config=")) {
1248 ConfigInclusion =
true;
1254 SmallString<128> ResponseFile;
1257 SmallString<128> FilePath;
1260 std::make_error_code(std::errc::no_such_file_or_directory),
1261 "cannot not find configuration file: " + FileName);
1262 ResponseFile.
append(FilePath);
1264 ResponseFile.
append(BasePath);
1267 Arg = Saver.save(ResponseFile.
str()).
data();
1276 struct ResponseFileRecord {
1291 for (
unsigned I = 0;
I != Argv.
size();) {
1292 while (
I == FileStack.
back().End) {
1298 const char *Arg = Argv[
I];
1300 if (Arg ==
nullptr) {
1305 if (Arg[0] !=
'@') {
1310 const char *FName = Arg + 1;
1315 if (CurrentDir.empty()) {
1316 if (
auto CWD = FS->getCurrentWorkingDirectory()) {
1320 CWD.getError(),
Twine(
"cannot get absolute path for: ") + FName);
1323 CurrDir = CurrentDir;
1326 FName = CurrDir.
c_str();
1330 if (!Res || !Res->exists()) {
1331 std::error_code EC = Res.
getError();
1332 if (!InConfigFile) {
1343 "': " + EC.message());
1348 [FileStatus,
this](
const ResponseFileRecord &RFile) ->
ErrorOr<bool> {
1360 R.getError(),
Twine(
"recursive expansion of: '") +
F.File +
"'");
1363 Twine(
"cannot open file: ") +
F.File);
1370 if (
Error Err = expandResponseFile(FName, ExpandedArgv))
1373 for (ResponseFileRecord &
Record : FileStack) {
1404 Tokenize(*EnvValue, Saver, NewArgv,
false);
1407 NewArgv.
append(Argv + 1, Argv + Argc);
1428 : Saver(
A), Tokenizer(
T), FS(FS ? FS :
vfs::getRealFileSystem().
get()) {}
1434 auto Status = FS->status(Path);
1442 CfgFilePath = FileName;
1445 if (!FileExists(CfgFilePath))
1452 for (
const StringRef &Dir : SearchDirs) {
1458 if (FileExists(CfgFilePath)) {
1472 if (std::error_code EC = FS->makeAbsolute(AbsPath))
1474 EC,
Twine(
"cannot get absolute path for " + CfgFile));
1475 CfgFile = AbsPath.
str();
1477 InConfigFile =
true;
1478 RelativeNames =
true;
1479 if (
Error Err = expandResponseFile(CfgFile, Argv))
1488 bool LongOptionsUseDoubleDash) {
1497 if (std::optional<std::string> EnvValue =
1503 for (
int I = 1;
I < argc; ++
I)
1505 int NewArgc =
static_cast<int>(NewArgv.
size());
1509 NewArgc, &NewArgv[0], Overview, Errs, VFS, LongOptionsUseDoubleDash);
1513void CommandLineParser::ResetAllOptionOccurrences() {
1517 for (
auto *SC : RegisteredSubCommands) {
1521 Opts.
reserve(SC->OptionsMap.size());
1522 for (
auto &O : SC->OptionsMap)
1526 for (
Option *O : SC->PositionalOpts)
1528 for (
Option *O : SC->SinkOpts)
1530 if (SC->ConsumeAfterOpt)
1531 SC->ConsumeAfterOpt->reset();
1535bool CommandLineParser::ParseCommandLineOptions(
1538 assert(hasOptions() &&
"No options specified!");
1540 ProgramOverview = Overview;
1541 bool IgnoreErrors = Errs;
1546 bool ErrorParsing =
false;
1557 if (
Error Err = ECtx.expandResponseFiles(newArgv)) {
1558 *Errs <<
toString(std::move(Err)) <<
'\n';
1562 argc =
static_cast<int>(newArgv.size());
1568 unsigned NumPositionalRequired = 0;
1571 bool HasUnlimitedPositionals =
false;
1575 std::string NearestSubCommandString;
1576 bool MaybeNamedSubCommand =
1577 argc >= 2 && argv[FirstArg][0] !=
'-' && hasNamedSubCommands();
1578 if (MaybeNamedSubCommand) {
1582 LookupSubCommand(
StringRef(argv[FirstArg]), NearestSubCommandString);
1588 assert(ChosenSubCommand);
1591 auto &SinkOpts = ChosenSubCommand->
SinkOpts;
1592 auto &OptionsMap = ChosenSubCommand->
OptionsMap;
1594 for (
auto *O: DefaultOptions) {
1598 if (ConsumeAfterOpt) {
1599 assert(PositionalOpts.size() > 0 &&
1600 "Cannot specify cl::ConsumeAfter without a positional argument!");
1602 if (!PositionalOpts.empty()) {
1605 bool UnboundedFound =
false;
1606 for (
size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
1607 Option *Opt = PositionalOpts[i];
1609 ++NumPositionalRequired;
1610 else if (ConsumeAfterOpt) {
1613 if (PositionalOpts.size() > 1) {
1615 Opt->
error(
"error - this positional option will never be matched, "
1616 "because it does not Require a value, and a "
1617 "cl::ConsumeAfter option is active!");
1618 ErrorParsing =
true;
1620 }
else if (UnboundedFound && !Opt->
hasArgStr()) {
1626 Opt->
error(
"error - option can never match, because "
1627 "another positional argument will match an "
1628 "unbounded number of values, and this option"
1629 " does not require a value!");
1630 *Errs << ProgramName <<
": CommandLine Error: Option '" << Opt->
ArgStr
1631 <<
"' is all messed up!\n";
1632 *Errs << PositionalOpts.size();
1633 ErrorParsing =
true;
1637 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
1648 Option *ActivePositionalArg =
nullptr;
1651 bool DashDashFound =
false;
1652 for (
int i = FirstArg; i < argc; ++i) {
1653 Option *Handler =
nullptr;
1654 std::string NearestHandlerString;
1656 StringRef ArgName =
"";
1657 bool HaveDoubleDash =
false;
1663 if (argv[i][0] !=
'-' || argv[i][1] == 0 || DashDashFound) {
1665 if (ActivePositionalArg) {
1670 if (!PositionalOpts.empty()) {
1671 PositionalVals.
push_back(std::make_pair(StringRef(argv[i]), i));
1676 if (PositionalVals.
size() >= NumPositionalRequired && ConsumeAfterOpt) {
1677 for (++i; i < argc; ++i)
1678 PositionalVals.
push_back(std::make_pair(StringRef(argv[i]), i));
1685 }
else if (argv[i][0] ==
'-' && argv[i][1] ==
'-' && argv[i][2] == 0 &&
1687 DashDashFound =
true;
1689 }
else if (ActivePositionalArg &&
1694 ArgName = StringRef(argv[i] + 1);
1697 HaveDoubleDash =
true;
1699 Handler = LookupLongOption(*ChosenSubCommand, ArgName,
Value,
1700 LongOptionsUseDoubleDash, HaveDoubleDash);
1706 ArgName = StringRef(argv[i] + 1);
1709 HaveDoubleDash =
true;
1711 Handler = LookupLongOption(*ChosenSubCommand, ArgName,
Value,
1712 LongOptionsUseDoubleDash, HaveDoubleDash);
1719 LongOptionsUseDoubleDash, HaveDoubleDash);
1722 if (!Handler && !(LongOptionsUseDoubleDash && HaveDoubleDash))
1728 if (!Handler && SinkOpts.empty())
1733 if (!SinkOpts.empty()) {
1734 for (
Option *SinkOpt : SinkOpts)
1735 SinkOpt->addOccurrence(i,
"", StringRef(argv[i]));
1739 auto ReportUnknownArgument = [&](
bool IsArg,
1740 StringRef NearestArgumentName) {
1741 *Errs << ProgramName <<
": Unknown "
1742 << (IsArg ?
"command line argument" :
"subcommand") <<
" '"
1743 << argv[i] <<
"'. Try: '" << argv[0] <<
" --help'\n";
1745 if (NearestArgumentName.empty())
1748 *Errs << ProgramName <<
": Did you mean '";
1750 *Errs << PrintArg(NearestArgumentName, 0);
1752 *Errs << NearestArgumentName;
1756 if (i > 1 || !MaybeNamedSubCommand)
1757 ReportUnknownArgument(
true, NearestHandlerString);
1759 ReportUnknownArgument(
false, NearestSubCommandString);
1761 ErrorParsing =
true;
1769 Handler->
error(
"This argument does not take a value.\n"
1770 "\tInstead, it consumes any positional arguments until "
1771 "the next recognized option.", *Errs);
1772 ErrorParsing =
true;
1774 ActivePositionalArg = Handler;
1781 if (NumPositionalRequired > PositionalVals.
size()) {
1782 *Errs << ProgramName
1783 <<
": Not enough positional command line arguments specified!\n"
1784 <<
"Must specify at least " << NumPositionalRequired
1785 <<
" positional argument" << (NumPositionalRequired > 1 ?
"s" :
"")
1786 <<
": See: " << argv[0] <<
" --help\n";
1788 ErrorParsing =
true;
1789 }
else if (!HasUnlimitedPositionals &&
1790 PositionalVals.
size() > PositionalOpts.size()) {
1791 *Errs << ProgramName <<
": Too many positional arguments specified!\n"
1792 <<
"Can specify at most " << PositionalOpts.size()
1793 <<
" positional arguments: See: " << argv[0] <<
" --help\n";
1794 ErrorParsing =
true;
1796 }
else if (!ConsumeAfterOpt) {
1798 unsigned ValNo = 0, NumVals =
static_cast<unsigned>(PositionalVals.
size());
1799 for (
Option *Opt : PositionalOpts) {
1802 PositionalVals[ValNo].second);
1804 --NumPositionalRequired;
1812 while (NumVals - ValNo > NumPositionalRequired && !
Done) {
1820 PositionalVals[ValNo].second);
1825 "positional argument processing!");
1830 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.
size());
1832 for (
Option *Opt : PositionalOpts)
1835 Opt, PositionalVals[ValNo].first, PositionalVals[ValNo].second);
1844 if (PositionalOpts.size() == 1 && ValNo == 0 && !PositionalVals.
empty()) {
1846 PositionalVals[ValNo].first,
1847 PositionalVals[ValNo].second);
1853 for (; ValNo != PositionalVals.
size(); ++ValNo)
1856 PositionalVals[ValNo].second);
1860 for (
const auto &Opt : OptionsMap) {
1865 Opt.second->
error(
"must be specified at least once!");
1866 ErrorParsing =
true;
1878 for (
int i = 0; i < argc; ++i)
dbgs() << argv[i] <<
' ';
1899 if (!ArgName.
data())
1901 if (ArgName.
empty())
1904 Errs <<
globalParser().ProgramName <<
": for the " << PrintArg(ArgName, 0);
1906 Errs <<
" option: " << Message <<
"\n";
1915 return handleOccurrence(pos, ArgName, Value);
1922 if (O.ValueStr.empty())
1937 size_t FirstLineIndentedBy) {
1938 assert(Indent >= FirstLineIndentedBy);
1939 std::pair<StringRef, StringRef> Split =
HelpStr.split(
'\n');
1942 while (!Split.second.empty()) {
1943 Split = Split.second.split(
'\n');
1944 outs().
indent(Indent) << Split.first <<
"\n";
1949 size_t FirstLineIndentedBy) {
1951 assert(BaseIndent >= FirstLineIndentedBy);
1952 std::pair<StringRef, StringRef> Split =
HelpStr.split(
'\n');
1953 outs().
indent(BaseIndent - FirstLineIndentedBy)
1955 while (!Split.second.empty()) {
1956 Split = Split.second.split(
'\n');
1957 outs().
indent(BaseIndent + ValHelpPrefix.
size()) << Split.first <<
"\n";
1962void alias::printOptionInfo(
size_t GlobalWidth)
const {
1978 if (!ValName.empty()) {
1979 size_t FormattingLen = 3;
1992 size_t GlobalWidth)
const {
1993 outs() << PrintArg(O.ArgStr);
1996 if (!ValName.empty()) {
2002 outs() << (O.ArgStr.size() == 1 ?
" <" :
"=<") <<
getValueStr(O, ValName)
2011 size_t GlobalWidth)
const {
2012 outs() << PrintArg(O.ArgStr);
2013 outs().
indent(GlobalWidth - O.ArgStr.size());
2033template <
typename FixedOrScalableQuantityT>
2036 FixedOrScalableQuantityT &
Value) {
2037 using ScalarTy =
typename FixedOrScalableQuantityT::ScalarTy;
2043 Value = FixedOrScalableQuantityT::getFixed(MinValue);
2049 return O.error(
"'" + Arg +
"' value invalid for " + ValueKind +
2052 Remainder = Remainder.
ltrim();
2054 return O.error(
"'" + Arg +
"' value invalid for " + ValueKind +
2057 Remainder = Remainder.
ltrim();
2059 return O.error(
"'" + Arg +
"' value invalid for " + ValueKind +
2062 Value = FixedOrScalableQuantityT::getScalable(MinValue);
2071 return O.error(
"'" + Arg +
"' value invalid for integer argument!");
2080 return O.error(
"'" + Arg +
"' value invalid for long argument!");
2089 return O.error(
"'" + Arg +
"' value invalid for llong argument!");
2099 return O.error(
"'" + Arg +
"' value invalid for uint argument!");
2106 unsigned long &
Value) {
2109 return O.error(
"'" + Arg +
"' value invalid for ulong argument!");
2117 unsigned long long &
Value) {
2120 return O.error(
"'" + Arg +
"' value invalid for ullong argument!");
2127 ElementCount &
Value) {
2136 return O.error(
"'" + Arg +
"' value invalid for floating point argument!");
2162 for (
unsigned i = 0; i != e; ++i) {
2178 return O.getValueExpectedFlag() !=
ValueOptional || !Name.empty() ||
2179 !Description.
empty();
2184 if (O.hasArgStr()) {
2196 size_t BaseSize = 0;
2207 size_t GlobalWidth)
const {
2208 if (O.hasArgStr()) {
2214 outs() << PrintArg(O.ArgStr);
2233 if (OptionName.
empty()) {
2238 if (!Description.
empty())
2244 if (!O.HelpStr.empty())
2245 outs() <<
" " << O.HelpStr <<
'\n';
2262 outs() <<
" " << PrintArg(O.ArgStr);
2263 outs().
indent(GlobalWidth - O.ArgStr.size());
2266 for (
unsigned i = 0; i != NumOpts; ++i) {
2274 for (
unsigned j = 0; j != NumOpts; ++j) {
2283 outs() <<
"= *unknown option value*\n";
2291 return OS << static_cast<int>(V);
2296#define PRINT_OPT_DIFF(T) \
2297 void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D, \
2298 size_t GlobalWidth) const { \
2299 printOptionName(O, GlobalWidth); \
2302 raw_string_ostream SS(Str); \
2305 outs() << "= " << Str; \
2306 size_t NumSpaces = \
2307 MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0; \
2308 outs().indent(NumSpaces) << " (default: "; \
2310 outs() << D.getValue(); \
2312 outs() << "*no default*"; \
2331 size_t GlobalWidth)
const {
2332 printOptionName(O, GlobalWidth);
2333 outs() <<
"= " << V;
2337 outs() <<
D.getValue();
2339 outs() <<
"*no default*";
2344 const Option &O, std::optional<StringRef> V,
2345 const OptionValue<std::optional<std::string>> &
D,
2346 size_t GlobalWidth)
const {
2347 printOptionName(O, GlobalWidth);
2348 outs() <<
"= " <<
V;
2349 size_t VSize =
V.has_value() ?
V.value().size() : 0;
2352 if (
D.hasValue() &&
D.getValue().has_value())
2353 outs() <<
D.getValue();
2355 outs() <<
"*no value*";
2361 size_t GlobalWidth)
const {
2363 outs() <<
"= *cannot print option value*\n";
2371 const std::pair<const char *, Option *> *
RHS) {
2372 return strcmp(
LHS->first,
RHS->first);
2376 const std::pair<const char *, SubCommand *> *
RHS) {
2377 return strcmp(
LHS->first,
RHS->first);
2386 for (
auto I = OptMap.
begin(),
E = OptMap.
end();
I !=
E; ++
I) {
2392 if (
I->second->getOptionHiddenFlag() ==
Hidden && !ShowHidden)
2396 if (!OptionSet.
insert(
I->second).second)
2400 std::pair<const char *, Option *>(
I->first.data(),
I->second));
2410 for (
auto *S : SubMap) {
2411 if (S->getName().empty())
2413 Subs.push_back(std::make_pair(S->getName().data(), S));
2422 const bool ShowHidden;
2423 using StrOptionPairVector =
2425 using StrSubCommandPairVector =
2428 virtual void printOptions(StrOptionPairVector &Opts,
size_t MaxArgLen) {
2429 for (
const auto &Opt : Opts)
2433 void printSubCommands(StrSubCommandPairVector &Subs,
size_t MaxSubLen) {
2434 for (
const auto &S : Subs) {
2435 outs() <<
" " << S.first;
2436 if (!S.second->getDescription().empty()) {
2438 outs() <<
" - " << S.second->getDescription();
2445 explicit HelpPrinter(
bool showHidden) : ShowHidden(showHidden) {}
2446 virtual ~HelpPrinter() =
default;
2449 void operator=(
bool Value) {
2460 auto &OptionsMap =
Sub->OptionsMap;
2461 auto &PositionalOpts =
Sub->PositionalOpts;
2462 auto &ConsumeAfterOpt =
Sub->ConsumeAfterOpt;
2464 StrOptionPairVector Opts;
2465 sortOpts(OptionsMap, Opts, ShowHidden);
2467 StrSubCommandPairVector Subs;
2476 outs() <<
" [subcommand]";
2477 outs() <<
" [options]";
2479 if (!
Sub->getDescription().empty()) {
2480 outs() <<
"SUBCOMMAND '" <<
Sub->getName()
2481 <<
"': " <<
Sub->getDescription() <<
"\n\n";
2487 for (
auto *Opt : PositionalOpts) {
2494 if (ConsumeAfterOpt)
2495 outs() <<
" " << ConsumeAfterOpt->HelpStr;
2499 size_t MaxSubLen = 0;
2500 for (
const auto &
Sub : Subs)
2501 MaxSubLen = std::max(MaxSubLen, strlen(
Sub.first));
2504 outs() <<
"SUBCOMMANDS:\n\n";
2505 printSubCommands(Subs, MaxSubLen);
2508 <<
" <subcommand> --help\" to get more help on a specific "
2515 size_t MaxArgLen = 0;
2516 for (
const auto &Opt : Opts)
2519 outs() <<
"OPTIONS:\n";
2520 printOptions(Opts, MaxArgLen);
2529class CategorizedHelpPrinter :
public HelpPrinter {
2531 explicit CategorizedHelpPrinter(
bool showHidden) : HelpPrinter(showHidden) {}
2537 static int OptionCategoryCompare(OptionCategory *
const *
A,
2538 OptionCategory *
const *
B) {
2539 return (*A)->getName().compare((*B)->getName());
2543 using HelpPrinter::operator=;
2546 void printOptions(StrOptionPairVector &Opts,
size_t MaxArgLen)
override {
2547 std::vector<OptionCategory *> SortedCategories;
2548 DenseMap<OptionCategory *, std::vector<Option *>> CategorizedOptions;
2556 assert(SortedCategories.size() > 0 &&
"No option categories registered!");
2558 OptionCategoryCompare);
2563 for (
const auto &
I : Opts) {
2564 Option *Opt =
I.second;
2565 for (OptionCategory *Cat : Opt->
Categories) {
2567 "Option has an unregistered category");
2568 CategorizedOptions[Cat].push_back(Opt);
2573 for (OptionCategory *Category : SortedCategories) {
2575 const auto &CategoryOptions = CategorizedOptions[Category];
2576 if (CategoryOptions.empty())
2581 outs() << Category->getName() <<
":\n";
2584 if (!Category->getDescription().empty())
2585 outs() << Category->getDescription() <<
"\n\n";
2590 for (
const Option *Opt : CategoryOptions)
2598class HelpPrinterWrapper {
2600 HelpPrinter &UncategorizedPrinter;
2601 CategorizedHelpPrinter &CategorizedPrinter;
2604 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
2605 CategorizedHelpPrinter &CategorizedPrinter)
2606 : UncategorizedPrinter(UncategorizedPrinter),
2607 CategorizedPrinter(CategorizedPrinter) {}
2610 void operator=(
bool Value);
2615#if defined(__GNUC__)
2618# if defined(__OPTIMIZE__)
2619# define LLVM_IS_DEBUG_BUILD 0
2621# define LLVM_IS_DEBUG_BUILD 1
2623#elif defined(_MSC_VER)
2628# define LLVM_IS_DEBUG_BUILD 1
2630# define LLVM_IS_DEBUG_BUILD 0
2634# define LLVM_IS_DEBUG_BUILD 0
2638class VersionPrinter {
2640 void print(
const std::vector<VersionPrinterTy> &ExtraPrinters) {
2642#ifdef PACKAGE_VENDOR
2643 OS << PACKAGE_VENDOR <<
" ";
2645 OS <<
"LLVM (http://llvm.org/):\n ";
2647 OS << PACKAGE_NAME <<
" version " << PACKAGE_VERSION <<
"\n ";
2648#if LLVM_IS_DEBUG_BUILD
2649 OS <<
"DEBUG build";
2651 OS <<
"Optimized build";
2654 OS <<
" with assertions";
2660 if (!ExtraPrinters.empty()) {
2661 for (
const auto &
I : ExtraPrinters)
2665 void operator=(
bool OptionWasSpecified);
2668struct CommandLineCommonOptions {
2671 HelpPrinter UncategorizedNormalPrinter{
false};
2672 HelpPrinter UncategorizedHiddenPrinter{
true};
2673 CategorizedHelpPrinter CategorizedNormalPrinter{
false};
2674 CategorizedHelpPrinter CategorizedHiddenPrinter{
true};
2677 HelpPrinterWrapper WrappedNormalPrinter{UncategorizedNormalPrinter,
2678 CategorizedNormalPrinter};
2679 HelpPrinterWrapper WrappedHiddenPrinter{UncategorizedHiddenPrinter,
2680 CategorizedHiddenPrinter};
2690 "Display list of available options (--help-list-hidden for more)"),
2699 cl::desc(
"Display list of all available options"),
2711 cl::desc(
"Display available options (--help-hidden for more)"),
2722 cl::desc(
"Display all available options"),
2731 cl::desc(
"Print non-default options after command line parsing"),
2738 "print-all-options",
2739 cl::desc(
"Print all option values after command line parsing"),
2747 std::vector<VersionPrinterTy> ExtraVersionPrinters;
2750 VersionPrinter VersionPrinterInstance;
2753 "version",
cl::desc(
"Display the version of this program"),
2778 return GeneralCategory;
2781void VersionPrinter::operator=(
bool OptionWasSpecified) {
2782 if (!OptionWasSpecified)
2794void HelpPrinterWrapper::operator=(
bool Value) {
2801 if (
globalParser().RegisteredOptionCategories.size() > 1) {
2806 CategorizedPrinter =
true;
2808 UncategorizedPrinter =
true;
2815void CommandLineParser::printOptionValues() {
2820 sortOpts(ActiveSubCommand->OptionsMap, Opts,
true);
2823 size_t MaxArgLen = 0;
2824 for (
const auto &Opt : Opts)
2827 for (
const auto &Opt : Opts)
2833 if (!
Hidden && !Categorized)
2835 else if (!
Hidden && Categorized)
2837 else if (
Hidden && !Categorized)
2849#if LLVM_IS_DEBUG_BUILD
2855#ifdef EXPENSIVE_CHECKS
2856 "+expensive-checks",
2858#if __has_feature(address_sanitizer)
2861#if __has_feature(dataflow_sanitizer)
2864#if __has_feature(hwaddress_sanitizer)
2867#if __has_feature(memory_sanitizer)
2870#if __has_feature(thread_sanitizer)
2873#if __has_feature(undefined_behavior_sanitizer)
2876#ifdef LLVM_INTEGRATED_CRT_ALLOC
2877 "+alloc:" LLVM_INTEGRATED_CRT_ALLOC,
2885#if LLVM_VERSION_PRINTER_SHOW_BUILD_CONFIG
2886 OS <<
"Build config: ";
2910 return Sub.OptionsMap;
2920 for (
auto &
I :
Sub.OptionsMap) {
2921 bool Unrelated =
true;
2922 for (
auto &Cat :
I.second->Categories) {
2923 if (Cat == &Category || Cat == &
CommonOptions->GenericCategory)
2934 for (
auto &
I :
Sub.OptionsMap) {
2935 bool Unrelated =
true;
2936 for (
auto &Cat :
I.second->Categories) {
2952 const char *Overview) {
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 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 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 bool hasUTF8ByteOrderMark(ArrayRef< char > S)
static void ExpandBasePaths(StringRef BasePath, StringSaver &Saver, const char *&Arg)
static Option * getOptionPred(StringRef Name, size_t &Length, bool(*Pred)(const Option *), const OptionsMapTy &OptionsMap)
static SmallString< 8 > argPrefix(StringRef ArgName, size_t Pad=DefaultPad)
static StringRef ArgHelpPrefix
void opt_unsigned_anchor()
static bool isWindowsSpecialCharInCommandName(char C)
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 Option * HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value, bool &ErrorParsing, const OptionsMapTy &OptionsMap)
HandlePrefixedOrGroupedOption - The specified argument string (which started with at least one '-') d...
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 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 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 isGrouping(const Option *O)
#define LLVM_EXPORT_TEMPLATE
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.
iterator find(const_arg_type_t< KeyT > Val)
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
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.
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)
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.
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
virtual void printOptionValue(size_t GlobalWidth, bool Force) const =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)
virtual size_t getOptionWidth() const =0
Option(enum NumOccurrencesFlag OccurrencesFlag, enum OptionHidden Hidden)
StringRef getName() const
SubCommand(StringRef Name, StringRef Description="")
SmallVector< Option *, 4 > SinkOpts
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.
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 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 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 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 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 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)
LLVM_ABI 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 ...
initializer< Ty > init(const Ty &Val)
std::function< void(raw_ostream &)> VersionPrinterTy
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 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 bool ParseCommandLineOptions(int argc, const char *const *argv, StringRef Overview="", raw_ostream *Errs=nullptr, vfs::FileSystem *VFS=nullptr, const char *EnvVar=nullptr, bool LongOptionsUseDoubleDash=false)
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.
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)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
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 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.
@ Default
The result value is uniform if and only if all operands are uniform.