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) {
156 OS <<
argPrefix(Arg.ArgName, Arg.Pad) << Arg.ArgName;
160class CommandLineParser {
164 std::string ProgramName;
168 std::vector<StringRef> MoreHelp;
180 size_t NumIndexedLibraries = 0;
194 if (Opt.
Subs.empty()) {
199 for (
auto *SC : RegisteredSubCommands)
204 for (
auto *SC : Opt.
Subs) {
206 "SubCommand::getAll() should not be used with other subcommands");
215 errs() << ProgramName <<
": CommandLine Error: Option '" << Name
216 <<
"' registered more than once!\n";
223 Opt, [&](
SubCommand &SC) { addLiteralOption(Opt, &SC, Name); });
227 bool HadErrors =
false;
228 if (O->hasArgStr()) {
233 (RegisteredSubCommands.
contains(SC) &&
234 LibraryIndex.
contains(O->ArgStr))) {
235 errs() << ProgramName <<
": CommandLine Error: Option '" << O->ArgStr
236 <<
"' registered more than once!\n";
246 O->error(
"Cannot specify more than one option with cl::ConsumeAfter!");
260 void addOption(
Option *O) {
261 forEachSubCommand(*O, [&](
SubCommand &SC) { addOption(O, &SC); });
266 O->getExtraOptionNames(OptionNames);
271 for (
auto Name : OptionNames) {
272 auto I =
Sub.OptionsMap.find(Name);
275 if (
I !=
Sub.OptionsMap.end() &&
I->second == O)
276 Sub.OptionsMap.erase(
I);
280 for (
auto *Opt =
Sub.PositionalOpts.begin();
281 Opt !=
Sub.PositionalOpts.end(); ++Opt) {
283 Sub.PositionalOpts.erase(Opt);
287 else if (O ==
Sub.ConsumeAfterOpt)
288 Sub.ConsumeAfterOpt =
nullptr;
291 void removeOption(
Option *O) {
292 forEachSubCommand(*O, [&](
SubCommand &SC) { removeOption(O, &SC); });
296 return (!
Sub.OptionsMap.empty() || !
Sub.PositionalOpts.empty() ||
297 nullptr !=
Sub.ConsumeAfterOpt);
300 bool hasOptions()
const {
301 for (
const auto *S : RegisteredSubCommands) {
305 return !Libraries.
empty();
308 bool hasNamedSubCommands()
const {
309 for (
const auto *S : RegisteredSubCommands)
310 if (!S->getName().empty())
315 SubCommand *getActiveSubCommand() {
return ActiveSubCommand; }
319 if (!
Sub.OptionsMap.insert(std::make_pair(NewName, O)).second) {
320 errs() << ProgramName <<
": CommandLine Error: Option '" << O->ArgStr
321 <<
"' registered more than once!\n";
324 Sub.OptionsMap.erase(O->ArgStr);
328 forEachSubCommand(*O,
329 [&](
SubCommand &SC) { updateArgStr(O, NewName, &SC); });
332 void printOptionValues();
334 void indexLibraryOptions() {
335 bool HadErrors =
false;
336 for (; NumIndexedLibraries != Libraries.
size(); ++NumIndexedLibraries) {
340 auto [It, Inserted] = LibraryIndex.
try_emplace(Name, L);
341 if (Inserted ?
none_of(RegisteredSubCommands,
347 errs() << ProgramName <<
": CommandLine Error: Option '" << Name
348 <<
"' registered more than once!\n";
358 indexLibraryOptions();
359 return LibraryIndex.
lookup(Name);
367 "Duplicate option categories");
375 return (!
sub->getName().empty()) &&
376 (
Sub->getName() ==
sub->getName());
378 "Duplicate subcommands");
384 "SubCommand::getAll() should not be registered");
387 if (O->isPositional() || O->isConsumeAfter() || O->hasArgStr())
390 addLiteralOption(*O,
sub,
E.first);
401 RegisteredSubCommands.
end());
405 ActiveSubCommand =
nullptr;
410 RegisteredOptionCategories.
clear();
413 RegisteredSubCommands.
clear();
415 LibraryIndex.
clear();
416 NumIndexedLibraries = 0;
439 return *GlobalParser;
442template <
typename T, T TrueVal, T FalseVal>
446 if (!Arg.
data() || Arg ==
"true" || Arg ==
"1") {
451 if (Arg ==
"false" || Arg ==
"0") {
455 return O.error(
"'" + Arg +
456 "' is invalid value for boolean argument! Try 0 or 1");
468 : NumOccurrences(0), Occurrences(OccurrencesFlag), Value(0),
470 FullyInitialized(
false), Position(0) {
476 FullyInitialized =
true;
482 if (FullyInitialized)
504void OptionCategory::registerCategory() {
515 return *TopLevelSubCommand;
521 return *AllSubCommands;
539SubCommand::operator
bool()
const {
557 size_t EqualPos = Arg.
find(
'=');
562 return Sub.OptionsMap.lookup(Arg);
568 auto I =
Sub.OptionsMap.find(Arg.
substr(0, EqualPos));
569 if (
I ==
Sub.OptionsMap.end())
577 Arg = Arg.
substr(0, EqualPos);
582 std::string &NearestString) {
587 for (
auto *S : RegisteredSubCommands) {
589 "SubCommand::getAll() is not expected in RegisteredSubCommands");
590 if (S->getName().empty())
593 if (S->getName() == Name)
596 if (!NearestMatch && S->getName().edit_distance(Name) < 2)
601 NearestString = NearestMatch->
getName();
612 std::string &NearestString) {
618 std::pair<StringRef, StringRef> SplitArg = Arg.
split(
'=');
624 unsigned BestDistance = 0;
625 for (
const auto &[
_, O] : OptionsMap) {
631 O->getExtraOptionNames(OptionNames);
637 for (
const auto &Name : OptionNames) {
639 Flag,
true, BestDistance);
640 if (!Best || Distance < BestDistance) {
642 BestDistance = Distance;
643 if (
RHS.empty() || !PermitValue)
644 NearestString = std::string(Name);
646 NearestString = (
Twine(Name) +
"=" +
RHS).str();
669 Val = Val.
substr(Pos + 1);
685 const char *
const *argv,
int &i) {
693 return Handler->
error(
"requires a value!");
695 assert(argv &&
"null check");
720 for (; !Name.empty(); Name = Name.drop_back()) {
722 if (O && (O->getFormattingFlag() ==
cl::Prefix ||
767 return C ==
' ' ||
C ==
'\t' ||
C ==
'\r' ||
C ==
'\n';
774static bool isQuote(
char C) {
return C ==
'\"' ||
C ==
'\''; }
780 bool InToken =
false;
781 for (
size_t I = 0, E = Src.size();
I != E; ++
I) {
786 if (MarkEOLs && Src[
I] ==
'\n')
798 if (
I + 1 < E &&
C ==
'\\') {
807 while (
I != E && Src[
I] !=
C) {
809 if (Src[
I] ==
'\\' &&
I + 1 != E)
823 if (MarkEOLs &&
C ==
'\n')
857 size_t E = Src.size();
858 int BackslashCount = 0;
863 }
while (
I !=
E && Src[
I] ==
'\\');
865 bool FollowedByDoubleQuote = (
I !=
E && Src[
I] ==
'"');
866 if (FollowedByDoubleQuote) {
867 Token.
append(BackslashCount / 2,
'\\');
868 if (BackslashCount % 2 == 0)
873 Token.
append(BackslashCount,
'\\');
891 bool AlwaysCopy,
function_ref<
void()> MarkEOL,
bool InitialCommandName) {
900 bool CommandName = InitialCommandName;
903 enum {
INIT, UNQUOTED, QUOTED } State =
INIT;
905 for (
size_t I = 0,
E = Src.size();
I <
E; ++
I) {
908 assert(Token.
empty() &&
"token should be empty in initial state");
930 AddToken(AlwaysCopy ? Saver.
save(NormalChars) : NormalChars);
931 if (
I <
E && Src[
I] ==
'\n') {
933 CommandName = InitialCommandName;
937 }
else if (Src[
I] ==
'\"') {
938 Token += NormalChars;
940 }
else if (Src[
I] ==
'\\') {
941 assert(!CommandName &&
"or else we'd have treated it as a normal char");
942 Token += NormalChars;
956 AddToken(Saver.
save(Token.
str()));
958 if (Src[
I] ==
'\n') {
959 CommandName = InitialCommandName;
965 }
else if (Src[
I] ==
'\"') {
967 }
else if (Src[
I] ==
'\\' && !CommandName) {
975 if (Src[
I] ==
'\"') {
976 if (
I < (
E - 1) && Src[
I + 1] ==
'"') {
985 }
else if (Src[
I] ==
'\\' && !CommandName) {
995 AddToken(Saver.
save(Token.
str()));
1002 auto OnEOL = [&]() {
1007 true, OnEOL,
false);
1013 auto OnEOL = []() {};
1022 auto OnEOL = [&]() {
1033 for (
const char *Cur = Source.begin(); Cur != Source.end();) {
1042 while (Cur != Source.end() && *Cur !=
'\n')
1047 const char *Start = Cur;
1048 for (
const char *End = Source.end(); Cur != End; ++Cur) {
1050 if (Cur + 1 != End) {
1053 (*Cur ==
'\r' && (Cur + 1 != End) && Cur[1] ==
'\n')) {
1054 Line.append(Start, Cur - 1);
1060 }
else if (*Cur ==
'\n')
1064 Line.append(Start, Cur);
1072 return (S.
size() >= 3 && S[0] ==
'\xef' && S[1] ==
'\xbb' && S[2] ==
'\xbf');
1086 TokenPos = ArgString.
find(Token, StartPos)) {
1090 if (ResponseFile.
empty())
1094 ResponseFile.
append(BasePath);
1095 StartPos = TokenPos + Token.
size();
1098 if (!ResponseFile.
empty()) {
1101 if (!Remaining.
empty())
1108Error ExpansionContext::expandResponseFile(
1109 StringRef FName, SmallVectorImpl<const char *> &NewArgv) {
1111 llvm::ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
1112 FS->getBufferForFile(FName);
1116 "': " +
EC.message());
1118 MemoryBuffer &MemBuf = *MemBufOrErr.
get();
1123 std::string UTF8Buf;
1127 "Could not convert UTF16 to UTF8");
1128 Str = StringRef(UTF8Buf);
1134 Str = StringRef(BufRef.data() + 3, BufRef.size() - 3);
1137 Tokenizer(Str, Saver, NewArgv, MarkEOLs);
1142 if (!RelativeNames && !InConfigFile)
1146 for (
const char *&Arg : NewArgv) {
1156 StringRef ArgStr(Arg);
1158 bool ConfigInclusion =
false;
1159 if (ArgStr.consume_front(
"@")) {
1163 }
else if (ArgStr.consume_front(
"--config=")) {
1165 ConfigInclusion =
true;
1171 SmallString<128> ResponseFile;
1174 SmallString<128> FilePath;
1177 std::make_error_code(std::errc::no_such_file_or_directory),
1178 "cannot not find configuration file: " + FileName);
1179 ResponseFile.
append(FilePath);
1181 ResponseFile.
append(BasePath);
1184 Arg = Saver.save(ResponseFile.
str()).
data();
1193 struct ResponseFileRecord {
1208 for (
unsigned I = 0;
I != Argv.
size();) {
1209 while (
I == FileStack.
back().End) {
1215 const char *Arg = Argv[
I];
1217 if (Arg ==
nullptr) {
1222 if (Arg[0] !=
'@') {
1227 const char *FName = Arg + 1;
1232 if (CurrentDir.empty()) {
1233 if (
auto CWD = FS->getCurrentWorkingDirectory()) {
1237 CWD.getError(),
Twine(
"cannot get absolute path for: ") + FName);
1240 CurrDir = CurrentDir;
1243 FName = CurrDir.
c_str();
1247 if (!Res || !Res->exists()) {
1248 std::error_code EC = Res.
getError();
1249 if (!InConfigFile) {
1260 "': " + EC.message());
1265 [FileStatus,
this](
const ResponseFileRecord &RFile) ->
ErrorOr<bool> {
1277 R.getError(),
Twine(
"recursive expansion of: '") +
F.File +
"'");
1280 Twine(
"cannot open file: ") +
F.File);
1287 if (
Error Err = expandResponseFile(FName, ExpandedArgv))
1290 for (ResponseFileRecord &
Record : FileStack) {
1321 Tokenize(*EnvValue, Saver, NewArgv,
false);
1324 NewArgv.
append(Argv + 1, Argv + Argc);
1345 : Saver(
A), Tokenizer(
T), FS(FS ? FS :
vfs::getRealFileSystem().
get()) {}
1351 auto Status = FS->status(Path);
1359 CfgFilePath = FileName;
1362 if (!FileExists(CfgFilePath))
1369 for (
const StringRef &Dir : SearchDirs) {
1375 if (FileExists(CfgFilePath)) {
1389 if (std::error_code EC = FS->makeAbsolute(AbsPath))
1391 EC,
Twine(
"cannot get absolute path for " + CfgFile));
1392 CfgFile = AbsPath.
str();
1394 InConfigFile =
true;
1395 RelativeNames =
true;
1396 if (
Error Err = expandResponseFile(CfgFile, Argv))
1413 if (std::optional<std::string> EnvValue =
1419 for (
int I = 1;
I < argc; ++
I)
1421 int NewArgc =
static_cast<int>(NewArgv.
size());
1424 return globalParser().ParseCommandLineOptions(NewArgc, &NewArgv[0], Overview,
1429void CommandLineParser::ResetAllOptionOccurrences() {
1433 for (
auto *SC : RegisteredSubCommands) {
1437 Opts.
reserve(SC->OptionsMap.size());
1438 for (
auto &O : SC->OptionsMap)
1442 for (
Option *O : SC->PositionalOpts)
1444 if (SC->ConsumeAfterOpt)
1445 SC->ConsumeAfterOpt->reset();
1449 LibraryArgAlloc.Reset();
1452bool CommandLineParser::ParseCommandLineOptions(
int argc,
1453 const char *
const *argv,
1457 assert(hasOptions() &&
"No options specified!");
1459 ProgramOverview = Overview;
1460 bool IgnoreErrors = Errs;
1465 bool ErrorParsing =
false;
1476 if (
Error Err = ECtx.expandResponseFiles(newArgv)) {
1477 *Errs <<
toString(std::move(Err)) <<
'\n';
1481 argc =
static_cast<int>(newArgv.size());
1485 indexLibraryOptions();
1488 unsigned NumPositionalRequired = 0;
1491 bool HasUnlimitedPositionals =
false;
1495 std::string NearestSubCommandString;
1496 bool MaybeNamedSubCommand =
1497 argc >= 2 && argv[FirstArg][0] !=
'-' && hasNamedSubCommands();
1498 if (MaybeNamedSubCommand) {
1502 LookupSubCommand(
StringRef(argv[FirstArg]), NearestSubCommandString);
1508 assert(ChosenSubCommand);
1511 auto &OptionsMap = ChosenSubCommand->
OptionsMap;
1513 if (ConsumeAfterOpt) {
1514 assert(PositionalOpts.size() > 0 &&
1515 "Cannot specify cl::ConsumeAfter without a positional argument!");
1517 if (!PositionalOpts.empty()) {
1520 bool UnboundedFound =
false;
1521 for (
size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
1522 Option *Opt = PositionalOpts[i];
1524 ++NumPositionalRequired;
1525 else if (ConsumeAfterOpt) {
1528 if (PositionalOpts.size() > 1) {
1530 Opt->
error(
"error - this positional option will never be matched, "
1531 "because it does not Require a value, and a "
1532 "cl::ConsumeAfter option is active!");
1533 ErrorParsing =
true;
1535 }
else if (UnboundedFound && !Opt->
hasArgStr()) {
1541 Opt->
error(
"error - option can never match, because "
1542 "another positional argument will match an "
1543 "unbounded number of values, and this option"
1544 " does not require a value!");
1545 *Errs << ProgramName <<
": CommandLine Error: Option '" << Opt->
ArgStr
1546 <<
"' is all messed up!\n";
1547 *Errs << PositionalOpts.size();
1548 ErrorParsing =
true;
1552 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
1563 Option *ActivePositionalArg =
nullptr;
1566 bool DashDashFound =
false;
1567 for (
int i = FirstArg; i < argc; ++i) {
1568 Option *Handler =
nullptr;
1569 std::string NearestHandlerString;
1571 StringRef ArgName =
"";
1577 if (argv[i][0] !=
'-' || argv[i][1] == 0 || DashDashFound) {
1579 if (ActivePositionalArg) {
1584 if (!PositionalOpts.empty()) {
1585 PositionalVals.
push_back(std::make_pair(StringRef(argv[i]), i));
1590 if (PositionalVals.
size() >= NumPositionalRequired && ConsumeAfterOpt) {
1591 for (++i; i < argc; ++i)
1592 PositionalVals.
push_back(std::make_pair(StringRef(argv[i]), i));
1599 }
else if (argv[i][0] ==
'-' && argv[i][1] ==
'-' && argv[i][2] == 0 &&
1601 DashDashFound =
true;
1603 }
else if (ActivePositionalArg &&
1608 ArgName = StringRef(argv[i] + 1);
1612 Handler = LookupOption(*ChosenSubCommand, ArgName,
Value);
1618 ArgName = StringRef(argv[i] + 1);
1622 Handler = LookupOption(*ChosenSubCommand, ArgName,
Value);
1633 StringSaver Saver(LibraryArgAlloc);
1634 const char *
Args[2];
1635 unsigned NumArgs = std::min(argc - i, 2);
1636 for (
unsigned J = 0; J != NumArgs; ++J)
1637 Args[J] = Saver.
save(argv[i + J]).
data();
1640 *Errs << ProgramName <<
": " <<
toString(std::move(
E)) <<
'\n';
1641 ErrorParsing =
true;
1659 auto ReportUnknownArgument = [&](
bool IsArg,
1660 StringRef NearestArgumentName) {
1661 *Errs << ProgramName <<
": Unknown "
1662 << (IsArg ?
"command line argument" :
"subcommand") <<
" '"
1663 << argv[i] <<
"'. Try: '" << argv[0] <<
" --help'\n";
1665 if (NearestArgumentName.empty())
1668 *Errs << ProgramName <<
": Did you mean '";
1670 *Errs << PrintArg(NearestArgumentName, 0);
1672 *Errs << NearestArgumentName;
1676 if (i > 1 || !MaybeNamedSubCommand)
1677 ReportUnknownArgument(
true, NearestHandlerString);
1679 ReportUnknownArgument(
false, NearestSubCommandString);
1681 ErrorParsing =
true;
1689 Handler->
error(
"This argument does not take a value.\n"
1690 "\tInstead, it consumes any positional arguments until "
1691 "the next recognized option.", *Errs);
1692 ErrorParsing =
true;
1694 ActivePositionalArg = Handler;
1701 if (NumPositionalRequired > PositionalVals.
size()) {
1702 *Errs << ProgramName
1703 <<
": Not enough positional command line arguments specified!\n"
1704 <<
"Must specify at least " << NumPositionalRequired
1705 <<
" positional argument" << (NumPositionalRequired > 1 ?
"s" :
"")
1706 <<
": See: " << argv[0] <<
" --help\n";
1708 ErrorParsing =
true;
1709 }
else if (!HasUnlimitedPositionals &&
1710 PositionalVals.
size() > PositionalOpts.size()) {
1711 *Errs << ProgramName <<
": Too many positional arguments specified!\n"
1712 <<
"Can specify at most " << PositionalOpts.size()
1713 <<
" positional arguments: See: " << argv[0] <<
" --help\n";
1714 ErrorParsing =
true;
1716 }
else if (!ConsumeAfterOpt) {
1718 unsigned ValNo = 0, NumVals =
static_cast<unsigned>(PositionalVals.
size());
1719 for (
Option *Opt : PositionalOpts) {
1722 PositionalVals[ValNo].second);
1724 --NumPositionalRequired;
1732 while (NumVals - ValNo > NumPositionalRequired && !
Done) {
1740 PositionalVals[ValNo].second);
1745 "positional argument processing!");
1750 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.
size());
1752 for (
Option *Opt : PositionalOpts)
1755 Opt, PositionalVals[ValNo].first, PositionalVals[ValNo].second);
1764 if (PositionalOpts.size() == 1 && ValNo == 0 && !PositionalVals.
empty()) {
1766 PositionalVals[ValNo].first,
1767 PositionalVals[ValNo].second);
1773 for (; ValNo != PositionalVals.
size(); ++ValNo)
1776 PositionalVals[ValNo].second);
1780 for (
const auto &Opt : OptionsMap) {
1785 Opt.second->
error(
"must be specified at least once!");
1786 ErrorParsing =
true;
1798 for (
int i = 0; i < argc; ++i)
dbgs() << argv[i] <<
' ';
1819 if (!ArgName.
data())
1821 if (ArgName.
empty())
1824 Errs <<
globalParser().ProgramName <<
": for the " << PrintArg(ArgName, 0);
1826 Errs <<
" option: " << Message <<
"\n";
1832 return handleOccurrence(pos, ArgName, Value);
1839 if (O.ValueStr.empty())
1854 size_t FirstLineIndentedBy) {
1855 assert(Indent >= FirstLineIndentedBy);
1856 std::pair<StringRef, StringRef> Split =
HelpStr.split(
'\n');
1859 while (!Split.second.empty()) {
1860 Split = Split.second.split(
'\n');
1861 outs().
indent(Indent) << Split.first <<
"\n";
1866 size_t FirstLineIndentedBy) {
1868 assert(BaseIndent >= FirstLineIndentedBy);
1869 std::pair<StringRef, StringRef> Split =
HelpStr.split(
'\n');
1870 outs().
indent(BaseIndent - FirstLineIndentedBy)
1872 while (!Split.second.empty()) {
1873 Split = Split.second.split(
'\n');
1874 outs().
indent(BaseIndent + ValHelpPrefix.
size()) << Split.first <<
"\n";
1879void alias::printOptionInfo(
size_t GlobalWidth)
const {
1895 if (!ValName.empty()) {
1896 size_t FormattingLen = 3;
1909 size_t GlobalWidth)
const {
1910 outs() << PrintArg(O.ArgStr);
1913 if (!ValName.empty()) {
1919 outs() << (O.ArgStr.size() == 1 ?
" <" :
"=<") <<
getValueStr(O, ValName)
1928 size_t GlobalWidth)
const {
1929 outs() << PrintArg(O.ArgStr);
1930 outs().
indent(GlobalWidth - O.ArgStr.size());
1950template <
typename FixedOrScalableQuantityT>
1953 FixedOrScalableQuantityT &
Value) {
1954 using ScalarTy =
typename FixedOrScalableQuantityT::ScalarTy;
1960 Value = FixedOrScalableQuantityT::getFixed(MinValue);
1966 return O.error(
"'" + Arg +
"' value invalid for " + ValueKind +
1969 Remainder = Remainder.
ltrim();
1971 return O.error(
"'" + Arg +
"' value invalid for " + ValueKind +
1974 Remainder = Remainder.
ltrim();
1976 return O.error(
"'" + Arg +
"' value invalid for " + ValueKind +
1979 Value = FixedOrScalableQuantityT::getScalable(MinValue);
1988 return O.error(
"'" + Arg +
"' value invalid for integer argument!");
1997 return O.error(
"'" + Arg +
"' value invalid for long argument!");
2006 return O.error(
"'" + Arg +
"' value invalid for llong argument!");
2016 return O.error(
"'" + Arg +
"' value invalid for uint argument!");
2023 unsigned long &
Value) {
2026 return O.error(
"'" + Arg +
"' value invalid for ulong argument!");
2034 unsigned long long &
Value) {
2037 return O.error(
"'" + Arg +
"' value invalid for ullong argument!");
2044 ElementCount &
Value) {
2053 return O.error(
"'" + Arg +
"' value invalid for floating point argument!");
2079 for (
unsigned i = 0; i != e; ++i) {
2095 return O.getValueExpectedFlag() !=
ValueOptional || !Name.empty() ||
2096 !Description.
empty();
2101 if (O.hasArgStr()) {
2113 size_t BaseSize = 0;
2124 size_t GlobalWidth)
const {
2125 if (O.hasArgStr()) {
2131 outs() << PrintArg(O.ArgStr);
2150 if (OptionName.
empty()) {
2155 if (!Description.
empty())
2161 if (!O.HelpStr.empty())
2162 outs() <<
" " << O.HelpStr <<
'\n';
2179 outs() <<
" " << PrintArg(O.ArgStr);
2180 outs().
indent(GlobalWidth - O.ArgStr.size());
2183 for (
unsigned i = 0; i != NumOpts; ++i) {
2191 for (
unsigned j = 0; j != NumOpts; ++j) {
2200 outs() <<
"= *unknown option value*\n";
2208 return OS << static_cast<int>(V);
2213#define PRINT_OPT_DIFF(T) \
2214 void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D, \
2215 size_t GlobalWidth) const { \
2216 printOptionName(O, GlobalWidth); \
2219 raw_string_ostream SS(Str); \
2222 outs() << "= " << Str; \
2223 size_t NumSpaces = \
2224 MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0; \
2225 outs().indent(NumSpaces) << " (default: "; \
2227 outs() << D.getValue(); \
2229 outs() << "*no default*"; \
2248 size_t GlobalWidth)
const {
2249 printOptionName(O, GlobalWidth);
2250 outs() <<
"= " << V;
2254 outs() <<
D.getValue();
2256 outs() <<
"*no default*";
2261 const Option &O, std::optional<StringRef> V,
2262 const OptionValue<std::optional<std::string>> &
D,
2263 size_t GlobalWidth)
const {
2264 printOptionName(O, GlobalWidth);
2265 outs() <<
"= " <<
V;
2266 size_t VSize =
V.has_value() ?
V.value().size() : 0;
2269 if (
D.hasValue() &&
D.getValue().has_value())
2270 outs() <<
D.getValue();
2272 outs() <<
"*no value*";
2278 size_t GlobalWidth)
const {
2280 outs() <<
"= *cannot print option value*\n";
2288 const std::pair<const char *, Option *> *
RHS) {
2289 return strcmp(
LHS->first,
RHS->first);
2293 const std::pair<const char *, SubCommand *> *
RHS) {
2294 return strcmp(
LHS->first,
RHS->first);
2303 for (
auto I = OptMap.
begin(),
E = OptMap.
end();
I !=
E; ++
I) {
2309 if (
I->second->getOptionHiddenFlag() ==
Hidden && !ShowHidden)
2313 if (!OptionSet.
insert(
I->second).second)
2317 std::pair<const char *, Option *>(
I->first.data(),
I->second));
2327 for (
auto *S : SubMap) {
2328 if (S->getName().empty())
2330 Subs.push_back(std::make_pair(S->getName().data(), S));
2339 const bool ShowHidden;
2340 using StrOptionPairVector =
2342 using StrSubCommandPairVector =
2345 virtual void printOptions(StrOptionPairVector &Opts,
size_t MaxArgLen) {
2346 for (
const auto &Opt : Opts)
2350 void printSubCommands(StrSubCommandPairVector &Subs,
size_t MaxSubLen) {
2351 for (
const auto &S : Subs) {
2352 outs() <<
" " << S.first;
2353 if (!S.second->getDescription().empty()) {
2355 outs() <<
" - " << S.second->getDescription();
2362 explicit HelpPrinter(
bool showHidden) : ShowHidden(showHidden) {}
2363 virtual ~HelpPrinter() =
default;
2366 void operator=(
bool Value) {
2377 auto &OptionsMap =
Sub->OptionsMap;
2378 auto &PositionalOpts =
Sub->PositionalOpts;
2379 auto &ConsumeAfterOpt =
Sub->ConsumeAfterOpt;
2381 StrOptionPairVector Opts;
2382 sortOpts(OptionsMap, Opts, ShowHidden);
2384 StrSubCommandPairVector Subs;
2393 outs() <<
" [subcommand]";
2394 outs() <<
" [options]";
2396 if (!
Sub->getDescription().empty()) {
2397 outs() <<
"SUBCOMMAND '" <<
Sub->getName()
2398 <<
"': " <<
Sub->getDescription() <<
"\n\n";
2404 for (
auto *Opt : PositionalOpts) {
2411 if (ConsumeAfterOpt)
2412 outs() <<
" " << ConsumeAfterOpt->HelpStr;
2416 size_t MaxSubLen = 0;
2417 for (
const auto &
Sub : Subs)
2418 MaxSubLen = std::max(MaxSubLen, strlen(
Sub.first));
2421 outs() <<
"SUBCOMMANDS:\n\n";
2422 printSubCommands(Subs, MaxSubLen);
2425 <<
" <subcommand> --help\" to get more help on a specific "
2432 size_t MaxArgLen = 0;
2433 for (
const auto &Opt : Opts)
2440 [&](StringRef Spelling, StringRef MetaVar, StringRef
Help) {
2445 for (
const auto &[Name,
Help] : LibraryOpts)
2448 outs() <<
"OPTIONS:\n";
2449 printOptions(Opts, MaxArgLen);
2451 if (!LibraryOpts.empty())
2452 outs() <<
"\nLibrary options:\n\n";
2453 for (
const auto &[Name,
Help] : LibraryOpts) {
2454 outs() << PrintArg(Name);
2465class CategorizedHelpPrinter :
public HelpPrinter {
2467 explicit CategorizedHelpPrinter(
bool showHidden) : HelpPrinter(showHidden) {}
2473 static int OptionCategoryCompare(OptionCategory *
const *
A,
2474 OptionCategory *
const *
B) {
2475 return (*A)->getName().compare((*B)->getName());
2479 using HelpPrinter::operator=;
2482 void printOptions(StrOptionPairVector &Opts,
size_t MaxArgLen)
override {
2483 std::vector<OptionCategory *> SortedCategories;
2484 DenseMap<OptionCategory *, std::vector<Option *>> CategorizedOptions;
2492 assert(SortedCategories.size() > 0 &&
"No option categories registered!");
2494 OptionCategoryCompare);
2499 for (
const auto &
I : Opts) {
2500 Option *Opt =
I.second;
2501 for (OptionCategory *Cat : Opt->
Categories) {
2503 "Option has an unregistered category");
2504 CategorizedOptions[Cat].push_back(Opt);
2509 for (OptionCategory *Category : SortedCategories) {
2511 const auto &CategoryOptions = CategorizedOptions[Category];
2512 if (CategoryOptions.empty())
2517 outs() << Category->getName() <<
":\n";
2520 if (!Category->getDescription().empty())
2521 outs() << Category->getDescription() <<
"\n\n";
2526 for (
const Option *Opt : CategoryOptions)
2534class HelpPrinterWrapper {
2536 HelpPrinter &UncategorizedPrinter;
2537 CategorizedHelpPrinter &CategorizedPrinter;
2540 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
2541 CategorizedHelpPrinter &CategorizedPrinter)
2542 : UncategorizedPrinter(UncategorizedPrinter),
2543 CategorizedPrinter(CategorizedPrinter) {}
2546 void operator=(
bool Value);
2551#if defined(__GNUC__)
2554# if defined(__OPTIMIZE__)
2555# define LLVM_IS_DEBUG_BUILD 0
2557# define LLVM_IS_DEBUG_BUILD 1
2559#elif defined(_MSC_VER)
2564# define LLVM_IS_DEBUG_BUILD 1
2566# define LLVM_IS_DEBUG_BUILD 0
2570# define LLVM_IS_DEBUG_BUILD 0
2574class VersionPrinter {
2576 void print(
const std::vector<VersionPrinterTy> &ExtraPrinters) {
2578#ifdef PACKAGE_VENDOR
2579 OS << PACKAGE_VENDOR <<
" ";
2581 OS <<
"LLVM (http://llvm.org/):\n ";
2583 OS << PACKAGE_NAME <<
" version " << PACKAGE_VERSION <<
"\n ";
2584#if LLVM_IS_DEBUG_BUILD
2585 OS <<
"DEBUG build";
2587 OS <<
"Optimized build";
2590 OS <<
" with assertions";
2596 if (!ExtraPrinters.empty()) {
2597 for (
const auto &
I : ExtraPrinters)
2601 void operator=(
bool OptionWasSpecified);
2604struct CommandLineCommonOptions {
2607 HelpPrinter UncategorizedNormalPrinter{
false};
2608 HelpPrinter UncategorizedHiddenPrinter{
true};
2609 CategorizedHelpPrinter CategorizedNormalPrinter{
false};
2610 CategorizedHelpPrinter CategorizedHiddenPrinter{
true};
2613 HelpPrinterWrapper WrappedNormalPrinter{UncategorizedNormalPrinter,
2614 CategorizedNormalPrinter};
2615 HelpPrinterWrapper WrappedHiddenPrinter{UncategorizedHiddenPrinter,
2616 CategorizedHiddenPrinter};
2626 "Display list of available options (--help-list-hidden for more)"),
2635 cl::desc(
"Display list of all available options"),
2647 cl::desc(
"Display available options (--help-hidden for more)"),
2657 cl::desc(
"Display all available options"),
2666 cl::desc(
"Print non-default options after command line parsing"),
2673 "print-all-options",
2674 cl::desc(
"Print all option values after command line parsing"),
2682 std::vector<VersionPrinterTy> ExtraVersionPrinters;
2685 VersionPrinter VersionPrinterInstance;
2688 "version",
cl::desc(
"Display the version of this program"),
2713 return GeneralCategory;
2716void VersionPrinter::operator=(
bool OptionWasSpecified) {
2717 if (!OptionWasSpecified)
2729void HelpPrinterWrapper::operator=(
bool Value) {
2736 if (
globalParser().RegisteredOptionCategories.size() > 1) {
2741 CategorizedPrinter =
true;
2743 UncategorizedPrinter =
true;
2750void CommandLineParser::printOptionValues() {
2755 sortOpts(ActiveSubCommand->OptionsMap, Opts,
true);
2758 size_t MaxArgLen = 0;
2759 for (
const auto &Opt : Opts)
2762 for (
const auto &Opt : Opts)
2768 if (!
Hidden && !Categorized)
2770 else if (!
Hidden && Categorized)
2772 else if (
Hidden && !Categorized)
2784#if LLVM_IS_DEBUG_BUILD
2790#ifdef EXPENSIVE_CHECKS
2791 "+expensive-checks",
2793#if __has_feature(address_sanitizer)
2796#if __has_feature(dataflow_sanitizer)
2799#if __has_feature(hwaddress_sanitizer)
2802#if __has_feature(memory_sanitizer)
2805#if __has_feature(thread_sanitizer)
2808#if __has_feature(undefined_behavior_sanitizer)
2811#ifdef LLVM_INTEGRATED_CRT_ALLOC
2812 "+alloc:" LLVM_INTEGRATED_CRT_ALLOC,
2820#if LLVM_VERSION_PRINTER_SHOW_BUILD_CONFIG
2821 OS <<
"Build config: ";
2845 return Sub.OptionsMap;
2855 for (
auto &
I :
Sub.OptionsMap) {
2856 bool Unrelated =
true;
2857 for (
auto &Cat :
I.second->Categories) {
2858 if (Cat == &Category || Cat == &
CommonOptions->GenericCategory)
2869 for (
auto &
I :
Sub.OptionsMap) {
2870 bool Unrelated =
true;
2871 for (
auto &Cat :
I.second->Categories) {
2892 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 StringRef OptionPrefix
static bool RequiresValue(const Option *O)
static int SubNameCompare(const std::pair< const char *, SubCommand * > *LHS, const std::pair< const char *, SubCommand * > *RHS)
static size_t argPlusPrefixesSize(StringRef ArgName, size_t Pad=DefaultPad)
static bool shouldPrintOption(StringRef Name, StringRef Description, const Option &O)
static bool parseDouble(Option &O, StringRef Arg, double &Value)
static CommandLineParser & globalParser()
static bool parseBool(Option &O, StringRef ArgName, StringRef Arg, T &Value)
static const size_t DefaultPad
static StringRef EmptyOption
static bool hasUTF8ByteOrderMark(ArrayRef< char > S)
static void ExpandBasePaths(StringRef BasePath, StringSaver &Saver, const char *&Arg)
static SmallString< 8 > argPrefix(StringRef ArgName, size_t Pad=DefaultPad)
static StringRef ArgHelpPrefix
void opt_unsigned_anchor()
static bool isWindowsSpecialCharInCommandName(char C)
static StringRef getValueStr(const Option &O, StringRef DefaultMsg)
static Option * HandlePrefixedOption(StringRef &Arg, StringRef &Value, const OptionsMapTy &OptionsMap)
The specified argument string (which started with at least one '-') does not fully match an available...
static size_t getOptionPrefixesSize()
static bool ProvideOption(Option *Handler, StringRef ArgName, StringRef Value, int argc, const char *const *argv, int &i)
ProvideOption - For Value, this differentiates between an empty value ("") and a null value (StringRe...
static bool isQuote(char C)
static ManagedStatic< CommandLineCommonOptions > CommonOptions
static void initCommonOptions()
static void sortOpts(OptionsMapTy &OptMap, SmallVectorImpl< std::pair< const char *, Option * > > &Opts, bool ShowHidden)
DenseMap< StringRef, Option * > OptionsMapTy
static void tokenizeWindowsCommandLineImpl(StringRef Src, StringSaver &Saver, function_ref< void(StringRef)> AddToken, bool AlwaysCopy, function_ref< void()> MarkEOL, bool InitialCommandName)
static Option * findPrefixOption(StringRef Name, size_t &Length, const OptionsMapTy &OptionsMap)
static bool isWhitespace(char C)
static bool parseFixedOrScalableQuantity(Option &O, StringRef Arg, StringRef ValueKind, FixedOrScalableQuantityT &Value)
static size_t parseBackslash(StringRef Src, size_t I, SmallString< 128 > &Token)
Backslashes are interpreted in a rather complicated way in the Windows-style command line,...
static StringRef ArgPrefixLong
static void sortSubCommands(const SmallPtrSetImpl< SubCommand * > &SubMap, SmallVectorImpl< std::pair< const char *, SubCommand * > > &Subs)
#define PRINT_OPT_DIFF(T)
static bool isWhitespaceOrNull(char C)
static const size_t MaxOptWidth
static bool EatsUnboundedNumberOfValues(const Option *O)
static int OptNameCompare(const std::pair< const char *, Option * > *LHS, const std::pair< const char *, Option * > *RHS)
static Option * LookupNearestOption(StringRef Arg, const OptionsMapTy &OptionsMap, std::string &NearestString)
LookupNearestOption - Lookup the closest match to the option specified by the specified option on the...
static StringRef ArgPrefix
static bool isWindowsSpecialChar(char C)
static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos, StringRef ArgName, StringRef Value)
CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence() that does special handling ...
#define LLVM_EXPORT_TEMPLATE
static void Help(StringTable CPUNames, ArrayRef< SubtargetFeatureKV > FeatTable)
Display help for feature and mcpu choices.
Provides a library for accessing information about this process and other processes on the operating ...
This file defines the SmallPtrSet class.
This file defines the SmallString class.
Defines the virtual file system interface vfs::FileSystem.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
Get the array size.
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Represents either an error or a value T.
std::error_code getError() const
Lightweight error class with error context and mandatory checking.
static ErrorSuccess success()
Create a success value.
ManagedStatic - This transparently changes the behavior of global statics to be lazily constructed on...
size_t getBufferSize() const
const char * getBufferEnd() const
const char * getBufferStart() const
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
bool erase(PtrType Ptr)
Remove pointer from the set.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
void assign(StringRef RHS)
Assign from a StringRef.
void append(StringRef RHS)
Append from a StringRef.
StringRef str() const
Explicit conversion to StringRef.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void assign(size_type NumElts, ValueParamT Elt)
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
iterator erase(const_iterator CI)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
iterator insert(iterator I, T &&Elt)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
A wrapper around a string literal that serves as a proxy for constructing global tables of StringRefs...
Represent a constant reference to a string, i.e.
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
static constexpr size_t npos
bool getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
constexpr bool empty() const
Check if the string is empty.
StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
LLVM_ABI unsigned edit_distance(StringRef Other, bool AllowReplacements=true, unsigned MaxEditDistance=0) const
Determine the edit distance between this string and another string.
StringRef slice(size_t Start, size_t End) const
Return a reference to the substring from [Start, End).
constexpr size_t size() const
Get the string size.
constexpr const char * data() const
Get a pointer to the start of the string (which may not be null terminated).
StringRef ltrim(char Char) const
Return string with consecutive Char characters starting from the the left removed.
size_t find(char C, size_t From=0) const
Search for the first character C in the string.
StringRef trim(char Char) const
Return string with consecutive Char characters starting from the left and right removed.
bool consume_front(char Prefix)
Returns true if this StringRef has the given prefix and removes that prefix.
Saves strings in the provided stable storage and returns a StringRef with a stable character pointer.
BumpPtrAllocator & getAllocator() const
StringRef save(const char *S)
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
LLVM Value Representation.
Contains options that control response file expansion.
LLVM_ABI ExpansionContext(BumpPtrAllocator &A, TokenizerCallback T, vfs::FileSystem *FS=nullptr)
LLVM_ABI bool findConfigFile(StringRef FileName, SmallVectorImpl< char > &FilePath)
Looks for the specified configuration file.
LLVM_ABI Error expandResponseFiles(SmallVectorImpl< const char * > &Argv)
Expands constructs "@file" in the provided array of arguments recursively.
LLVM_ABI Error readConfigFile(StringRef CfgFile, SmallVectorImpl< const char * > &Argv)
Reads command line options from the given configuration file.
The options of a library that declares them in TableGen rather than as cl::opt (see llvm/Option/Libra...
StringRef getName() const
SmallPtrSet< SubCommand *, 1 > Subs
int getNumOccurrences() const
enum ValueExpected getValueExpectedFlag() const
void addCategory(OptionCategory &C)
enum FormattingFlags getFormattingFlag() const
virtual void printOptionInfo(size_t GlobalWidth) const =0
enum NumOccurrencesFlag getNumOccurrencesFlag() const
virtual bool addOccurrence(unsigned pos, StringRef ArgName, StringRef Value)
SmallVector< OptionCategory *, 1 > Categories
bool error(const Twine &Message, StringRef ArgName=StringRef(), raw_ostream &Errs=llvm::errs())
void setArgStr(StringRef S)
unsigned getMiscFlags() const
virtual void setDefault()=0
virtual void printOptionValue(size_t GlobalWidth, bool Force) const =0
static void printEnumValHelpStr(StringRef HelpStr, size_t Indent, size_t FirstLineIndentedBy)
void removeArgument()
Unregisters this option from the CommandLine system.
static void printHelpStr(StringRef HelpStr, size_t Indent, size_t FirstLineIndentedBy)
virtual size_t getOptionWidth() const =0
Option(enum NumOccurrencesFlag OccurrencesFlag, enum OptionHidden Hidden)
StringRef getName() const
SubCommand(StringRef Name, StringRef Description="")
static LLVM_ABI SubCommand & getTopLevel()
LLVM_ABI void unregisterSubCommand()
static LLVM_ABI SubCommand & getAll()
DenseMap< StringRef, Option * > OptionsMap
LLVM_ABI void registerSubCommand()
SmallVector< Option *, 4 > PositionalOpts
void printOptionInfo(const Option &O, size_t GlobalWidth) const
virtual StringRef getValueName() const
void printOptionNoValue(const Option &O, size_t GlobalWidth) const
size_t getOptionWidth(const Option &O) const
void printOptionName(const Option &O, size_t GlobalWidth) const
virtual size_t getOptionWidth(const Option &O) const
virtual StringRef getDescription(unsigned N) const =0
virtual const GenericOptionValue & getOptionValue(unsigned N) const =0
virtual unsigned getNumOptions() const =0
virtual StringRef getOption(unsigned N) const =0
void printGenericOptionDiff(const Option &O, const GenericOptionValue &V, const GenericOptionValue &Default, size_t GlobalWidth) const
virtual void printOptionInfo(const Option &O, size_t GlobalWidth) const
unsigned findOption(StringRef Name)
bool parse(Option &O, StringRef ArgName, StringRef Arg, DataType &V)
An efficient, type-erasing, non-owning reference to a callable.
A range adaptor for a pair of iterators.
This class implements an extremely fast bulk output stream that can only output to a stream.
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
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 char Args[]
Key for Kernel::Metadata::mArgs.
constexpr size_t NameSize
This namespace contains all of the command line option processing machinery.
LLVM_ABI iterator_range< SmallPtrSet< SubCommand *, 4 >::iterator > getRegisteredSubcommands()
Use this to get all registered SubCommands from the provided parser.
LLVM_ABI void PrintVersionMessage()
Utility function for printing version number.
LLVM_ABI bool ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer, SmallVectorImpl< const char * > &Argv)
A convenience helper which supports the typical use case of expansion function call.
LLVM_ABI void TokenizeWindowsCommandLine(StringRef Source, StringSaver &Saver, SmallVectorImpl< const char * > &NewArgv, bool MarkEOLs=false)
Tokenizes a string of Windows command line arguments, which may contain quotes and escaped quotes.
LLVM_ABI OptionCategory & getGeneralCategory()
LLVM_ABI void addLibraryOptions(LibraryOptions &L)
Makes ParseCommandLineOptions recognize L's options.
LLVM_ABI void ResetAllOptionOccurrences()
Reset all command line options to a state that looks as if they have never appeared on the command li...
LLVM_ABI void SetVersionPrinter(VersionPrinterTy func)
===------------------------------------------------------------------—===// Override the default (LLV...
LLVM_ABI void tokenizeConfigFile(StringRef Source, StringSaver &Saver, SmallVectorImpl< const char * > &NewArgv, bool MarkEOLs=false)
Tokenizes content of configuration file.
LLVM_ABI DenseMap< StringRef, Option * > & getRegisteredOptions(SubCommand &Sub=SubCommand::getTopLevel())
Use this to get a map of all registered named options (e.g.
LLVM_ABI bool expandResponseFiles(int Argc, const char *const *Argv, const char *EnvVar, StringSaver &Saver, SmallVectorImpl< const char * > &NewArgv)
A convenience helper which concatenates the options specified by the environment variable EnvVar and ...
LLVM_ABI void ResetCommandLineParser()
Reset the command line parser back to its initial state.
LLVM_ABI void PrintOptionValues()
LLVM_ABI void AddLiteralOption(Option &O, StringRef Name)
Adds a new option for parsing and provides the option it refers to.
void printOptionDiff(const Option &O, const generic_parser_base &P, const DT &V, const OptionValue< DT > &Default, size_t GlobalWidth)
LLVM_ABI void TokenizeWindowsCommandLineNoCopy(StringRef Source, StringSaver &Saver, SmallVectorImpl< StringRef > &NewArgv)
Tokenizes a Windows command line while attempting to avoid copies.
LLVM_ABI void printBuildConfig(raw_ostream &OS)
Prints the compiler build configuration.
void(*)(StringRef Source, StringSaver &Saver, SmallVectorImpl< const char * > &NewArgv, bool MarkEOLs) TokenizerCallback
String tokenization function type.
LLVM_ABI bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i)
Parses Arg into the option handler Handler.
static raw_ostream & operator<<(raw_ostream &OS, boolOrDefault V)
initializer< Ty > init(const Ty &Val)
std::function< void(raw_ostream &)> VersionPrinterTy
LLVM_ABI ArrayRef< StringRef > getCompilerBuildConfig()
An array of optional enabled settings in the LLVM build configuration, which may be of interest to co...
LocationClass< Ty > location(Ty &L)
LLVM_ABI bool ParseCommandLineOptions(int argc, const char *const *argv, StringRef Overview="", raw_ostream *Errs=nullptr, vfs::FileSystem *VFS=nullptr, const char *EnvVar=nullptr)
LLVM_ABI void HideUnrelatedOptions(cl::OptionCategory &Category, SubCommand &Sub=SubCommand::getTopLevel())
Mark all options not part of this category as cl::ReallyHidden.
LLVM_ABI void AddExtraVersionPrinter(VersionPrinterTy func)
===------------------------------------------------------------------—===// Add an extra printer to u...
LLVM_ABI void PrintHelpMessage(bool Hidden=false, bool Categorized=false)
This function just prints the help message, exactly the same way as if the -help or -help-hidden opti...
LLVM_ABI void TokenizeWindowsCommandLineFull(StringRef Source, StringSaver &Saver, SmallVectorImpl< const char * > &NewArgv, bool MarkEOLs=false)
Tokenizes a Windows full command line, including command name at the start.
LLVM_ABI void TokenizeGNUCommandLine(StringRef Source, StringSaver &Saver, SmallVectorImpl< const char * > &NewArgv, bool MarkEOLs=false)
Tokenizes a command line that can contain escapes and quotes.
LLVM_ABI StringRef parent_path(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get parent path.
LLVM_ABI bool has_parent_path(const Twine &path, Style style=Style::native)
Has parent path?
LLVM_ABI bool is_relative(const Twine &path, Style style=Style::native)
Is path relative?
LLVM_ABI StringRef filename(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get filename.
LLVM_ABI bool is_absolute(const Twine &path, Style style=Style::native)
Is path absolute?
LLVM_ABI void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
LLVM_ABI IntrusiveRefCntPtr< FileSystem > getRealFileSystem()
Gets an vfs::FileSystem for the 'real' file system, as seen by the operating system.
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
void initWithColorOptions()
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
LLVM_ABI raw_fd_ostream & outs()
This returns a reference to a raw_fd_ostream for standard output.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
void interleaveComma(const Container &c, StreamT &os, UnaryFunctor each_fn)
LLVM_ABI bool hasUTF16ByteOrderMark(ArrayRef< char > SrcBytes)
Returns true if a blob of text starts with a UTF-16 big or little endian byte order mark.
void initDebugCounterOptions()
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
bool to_float(const Twine &T, float &Num)
@ no_such_file_or_directory
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
void sort(IteratorTy Start, IteratorTy End)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
LLVM_ABI bool convertUTF16ToUTF8String(ArrayRef< char > SrcBytes, std::string &Out)
Converts a stream of raw bytes assumed to be UTF16 into a UTF8 std::string.
void initSignalsOptions()
void initStatisticOptions()
LLVM_ABI raw_ostream & nulls()
This returns a reference to a raw_ostream which simply discards output.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
void 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.