1 //===-- CommandLine.cpp - Command line parser implementation --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This class implements a command line argument processor that is useful when
11 // creating a tool. It provides a simple, minimalistic interface that is easily
12 // extensible and supports nonlocal (library) command line options.
14 // Note that rather than trying to figure out what this code does, you could try
15 // reading the library documentation located in docs/CommandLine.html
17 //===----------------------------------------------------------------------===//
19 #include "llvm/Support/CommandLine.h"
20 #include "llvm-c/Support.h"
21 #include "llvm/ADT/ArrayRef.h"
22 #include "llvm/ADT/Optional.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/ADT/SmallString.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringMap.h"
28 #include "llvm/ADT/Triple.h"
29 #include "llvm/ADT/Twine.h"
30 #include "llvm/Config/config.h"
31 #include "llvm/Support/ConvertUTF.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/FileSystem.h"
35 #include "llvm/Support/Host.h"
36 #include "llvm/Support/ManagedStatic.h"
37 #include "llvm/Support/MemoryBuffer.h"
38 #include "llvm/Support/Path.h"
39 #include "llvm/Support/Process.h"
40 #include "llvm/Support/StringSaver.h"
41 #include "llvm/Support/raw_ostream.h"
47 #define DEBUG_TYPE "commandline"
49 //===----------------------------------------------------------------------===//
50 // Template instantiations and anchors.
54 template class basic_parser<bool>;
55 template class basic_parser<boolOrDefault>;
56 template class basic_parser<int>;
57 template class basic_parser<unsigned>;
58 template class basic_parser<unsigned long long>;
59 template class basic_parser<double>;
60 template class basic_parser<float>;
61 template class basic_parser<std::string>;
62 template class basic_parser<char>;
64 template class opt<unsigned>;
65 template class opt<int>;
66 template class opt<std::string>;
67 template class opt<char>;
68 template class opt<bool>;
70 } // end namespace llvm::cl
72 // Pin the vtables to this file.
73 void GenericOptionValue::anchor() {}
74 void OptionValue<boolOrDefault>::anchor() {}
75 void OptionValue<std::string>::anchor() {}
76 void Option::anchor() {}
77 void basic_parser_impl::anchor() {}
78 void parser<bool>::anchor() {}
79 void parser<boolOrDefault>::anchor() {}
80 void parser<int>::anchor() {}
81 void parser<unsigned>::anchor() {}
82 void parser<unsigned long long>::anchor() {}
83 void parser<double>::anchor() {}
84 void parser<float>::anchor() {}
85 void parser<std::string>::anchor() {}
86 void parser<char>::anchor() {}
88 //===----------------------------------------------------------------------===//
92 class CommandLineParser {
94 // Globals for name and overview of program. Program name is not a string to
95 // avoid static ctor/dtor issues.
96 std::string ProgramName;
97 StringRef ProgramOverview;
99 // This collects additional help to be printed.
100 std::vector<StringRef> MoreHelp;
102 // This collects the different option categories that have been registered.
103 SmallPtrSet<OptionCategory *, 16> RegisteredOptionCategories;
105 // This collects the different subcommands that have been registered.
106 SmallPtrSet<SubCommand *, 4> RegisteredSubCommands;
108 CommandLineParser() : ActiveSubCommand(nullptr) {
109 registerSubCommand(&*TopLevelSubCommand);
110 registerSubCommand(&*AllSubCommands);
113 void ResetAllOptionOccurrences();
115 bool ParseCommandLineOptions(int argc, const char *const *argv,
116 StringRef Overview, raw_ostream *Errs = nullptr);
118 void addLiteralOption(Option &Opt, SubCommand *SC, StringRef Name) {
121 if (!SC->OptionsMap.insert(std::make_pair(Name, &Opt)).second) {
122 errs() << ProgramName << ": CommandLine Error: Option '" << Name
123 << "' registered more than once!\n";
124 report_fatal_error("inconsistency in registered CommandLine options");
127 // If we're adding this to all sub-commands, add it to the ones that have
128 // already been registered.
129 if (SC == &*AllSubCommands) {
130 for (const auto &Sub : RegisteredSubCommands) {
133 addLiteralOption(Opt, Sub, Name);
138 void addLiteralOption(Option &Opt, StringRef Name) {
139 if (Opt.Subs.empty())
140 addLiteralOption(Opt, &*TopLevelSubCommand, Name);
142 for (auto SC : Opt.Subs)
143 addLiteralOption(Opt, SC, Name);
147 void addOption(Option *O, SubCommand *SC) {
148 bool HadErrors = false;
149 if (O->hasArgStr()) {
150 // Add argument to the argument map!
151 if (!SC->OptionsMap.insert(std::make_pair(O->ArgStr, O)).second) {
152 errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
153 << "' registered more than once!\n";
158 // Remember information about positional options.
159 if (O->getFormattingFlag() == cl::Positional)
160 SC->PositionalOpts.push_back(O);
161 else if (O->getMiscFlags() & cl::Sink) // Remember sink options
162 SC->SinkOpts.push_back(O);
163 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
164 if (SC->ConsumeAfterOpt) {
165 O->error("Cannot specify more than one option with cl::ConsumeAfter!");
168 SC->ConsumeAfterOpt = O;
171 // Fail hard if there were errors. These are strictly unrecoverable and
172 // indicate serious issues such as conflicting option names or an
174 // linked LLVM distribution.
176 report_fatal_error("inconsistency in registered CommandLine options");
178 // If we're adding this to all sub-commands, add it to the ones that have
179 // already been registered.
180 if (SC == &*AllSubCommands) {
181 for (const auto &Sub : RegisteredSubCommands) {
189 void addOption(Option *O) {
190 if (O->Subs.empty()) {
191 addOption(O, &*TopLevelSubCommand);
193 for (auto SC : O->Subs)
198 void removeOption(Option *O, SubCommand *SC) {
199 SmallVector<StringRef, 16> OptionNames;
200 O->getExtraOptionNames(OptionNames);
202 OptionNames.push_back(O->ArgStr);
204 SubCommand &Sub = *SC;
205 for (auto Name : OptionNames)
206 Sub.OptionsMap.erase(Name);
208 if (O->getFormattingFlag() == cl::Positional)
209 for (auto Opt = Sub.PositionalOpts.begin();
210 Opt != Sub.PositionalOpts.end(); ++Opt) {
212 Sub.PositionalOpts.erase(Opt);
216 else if (O->getMiscFlags() & cl::Sink)
217 for (auto Opt = Sub.SinkOpts.begin(); Opt != Sub.SinkOpts.end(); ++Opt) {
219 Sub.SinkOpts.erase(Opt);
223 else if (O == Sub.ConsumeAfterOpt)
224 Sub.ConsumeAfterOpt = nullptr;
227 void removeOption(Option *O) {
229 removeOption(O, &*TopLevelSubCommand);
231 if (O->isInAllSubCommands()) {
232 for (auto SC : RegisteredSubCommands)
235 for (auto SC : O->Subs)
241 bool hasOptions(const SubCommand &Sub) const {
242 return (!Sub.OptionsMap.empty() || !Sub.PositionalOpts.empty() ||
243 nullptr != Sub.ConsumeAfterOpt);
246 bool hasOptions() const {
247 for (const auto &S : RegisteredSubCommands) {
254 SubCommand *getActiveSubCommand() { return ActiveSubCommand; }
256 void updateArgStr(Option *O, StringRef NewName, SubCommand *SC) {
257 SubCommand &Sub = *SC;
258 if (!Sub.OptionsMap.insert(std::make_pair(NewName, O)).second) {
259 errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
260 << "' registered more than once!\n";
261 report_fatal_error("inconsistency in registered CommandLine options");
263 Sub.OptionsMap.erase(O->ArgStr);
266 void updateArgStr(Option *O, StringRef NewName) {
268 updateArgStr(O, NewName, &*TopLevelSubCommand);
270 for (auto SC : O->Subs)
271 updateArgStr(O, NewName, SC);
275 void printOptionValues();
277 void registerCategory(OptionCategory *cat) {
278 assert(count_if(RegisteredOptionCategories,
279 [cat](const OptionCategory *Category) {
280 return cat->getName() == Category->getName();
282 "Duplicate option categories");
284 RegisteredOptionCategories.insert(cat);
287 void registerSubCommand(SubCommand *sub) {
288 assert(count_if(RegisteredSubCommands,
289 [sub](const SubCommand *Sub) {
290 return (!sub->getName().empty()) &&
291 (Sub->getName() == sub->getName());
293 "Duplicate subcommands");
294 RegisteredSubCommands.insert(sub);
296 // For all options that have been registered for all subcommands, add the
297 // option to this subcommand now.
298 if (sub != &*AllSubCommands) {
299 for (auto &E : AllSubCommands->OptionsMap) {
300 Option *O = E.second;
301 if ((O->isPositional() || O->isSink() || O->isConsumeAfter()) ||
305 addLiteralOption(*O, sub, E.first());
310 void unregisterSubCommand(SubCommand *sub) {
311 RegisteredSubCommands.erase(sub);
314 iterator_range<typename SmallPtrSet<SubCommand *, 4>::iterator>
315 getRegisteredSubcommands() {
316 return make_range(RegisteredSubCommands.begin(),
317 RegisteredSubCommands.end());
321 ActiveSubCommand = nullptr;
323 ProgramOverview = StringRef();
326 RegisteredOptionCategories.clear();
328 ResetAllOptionOccurrences();
329 RegisteredSubCommands.clear();
331 TopLevelSubCommand->reset();
332 AllSubCommands->reset();
333 registerSubCommand(&*TopLevelSubCommand);
334 registerSubCommand(&*AllSubCommands);
338 SubCommand *ActiveSubCommand;
340 Option *LookupOption(SubCommand &Sub, StringRef &Arg, StringRef &Value);
341 SubCommand *LookupSubCommand(StringRef Name);
346 static ManagedStatic<CommandLineParser> GlobalParser;
348 void cl::AddLiteralOption(Option &O, StringRef Name) {
349 GlobalParser->addLiteralOption(O, Name);
352 extrahelp::extrahelp(StringRef Help) : morehelp(Help) {
353 GlobalParser->MoreHelp.push_back(Help);
356 void Option::addArgument() {
357 GlobalParser->addOption(this);
358 FullyInitialized = true;
361 void Option::removeArgument() { GlobalParser->removeOption(this); }
363 void Option::setArgStr(StringRef S) {
364 if (FullyInitialized)
365 GlobalParser->updateArgStr(this, S);
366 assert((S.empty() || S[0] != '-') && "Option can't start with '-");
370 // Initialise the general option category.
371 OptionCategory llvm::cl::GeneralCategory("General options");
373 void OptionCategory::registerCategory() {
374 GlobalParser->registerCategory(this);
377 // A special subcommand representing no subcommand
378 ManagedStatic<SubCommand> llvm::cl::TopLevelSubCommand;
380 // A special subcommand that can be used to put an option into all subcommands.
381 ManagedStatic<SubCommand> llvm::cl::AllSubCommands;
383 void SubCommand::registerSubCommand() {
384 GlobalParser->registerSubCommand(this);
387 void SubCommand::unregisterSubCommand() {
388 GlobalParser->unregisterSubCommand(this);
391 void SubCommand::reset() {
392 PositionalOpts.clear();
396 ConsumeAfterOpt = nullptr;
399 SubCommand::operator bool() const {
400 return (GlobalParser->getActiveSubCommand() == this);
403 //===----------------------------------------------------------------------===//
404 // Basic, shared command line option processing machinery.
407 /// LookupOption - Lookup the option specified by the specified option on the
408 /// command line. If there is a value specified (after an equal sign) return
409 /// that as well. This assumes that leading dashes have already been stripped.
410 Option *CommandLineParser::LookupOption(SubCommand &Sub, StringRef &Arg,
412 // Reject all dashes.
415 assert(&Sub != &*AllSubCommands);
417 size_t EqualPos = Arg.find('=');
419 // If we have an equals sign, remember the value.
420 if (EqualPos == StringRef::npos) {
421 // Look up the option.
422 auto I = Sub.OptionsMap.find(Arg);
423 if (I == Sub.OptionsMap.end())
426 return I != Sub.OptionsMap.end() ? I->second : nullptr;
429 // If the argument before the = is a valid option name and the option allows
430 // non-prefix form (ie is not AlwaysPrefix), we match. If not, signal match
431 // failure by returning nullptr.
432 auto I = Sub.OptionsMap.find(Arg.substr(0, EqualPos));
433 if (I == Sub.OptionsMap.end())
437 if (O->getFormattingFlag() == cl::AlwaysPrefix)
440 Value = Arg.substr(EqualPos + 1);
441 Arg = Arg.substr(0, EqualPos);
445 SubCommand *CommandLineParser::LookupSubCommand(StringRef Name) {
447 return &*TopLevelSubCommand;
448 for (auto S : RegisteredSubCommands) {
449 if (S == &*AllSubCommands)
451 if (S->getName().empty())
454 if (StringRef(S->getName()) == StringRef(Name))
457 return &*TopLevelSubCommand;
460 /// LookupNearestOption - Lookup the closest match to the option specified by
461 /// the specified option on the command line. If there is a value specified
462 /// (after an equal sign) return that as well. This assumes that leading dashes
463 /// have already been stripped.
464 static Option *LookupNearestOption(StringRef Arg,
465 const StringMap<Option *> &OptionsMap,
466 std::string &NearestString) {
467 // Reject all dashes.
471 // Split on any equal sign.
472 std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
473 StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
474 StringRef &RHS = SplitArg.second;
476 // Find the closest match.
477 Option *Best = nullptr;
478 unsigned BestDistance = 0;
479 for (StringMap<Option *>::const_iterator it = OptionsMap.begin(),
480 ie = OptionsMap.end();
482 Option *O = it->second;
483 SmallVector<StringRef, 16> OptionNames;
484 O->getExtraOptionNames(OptionNames);
486 OptionNames.push_back(O->ArgStr);
488 bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
489 StringRef Flag = PermitValue ? LHS : Arg;
490 for (auto Name : OptionNames) {
491 unsigned Distance = StringRef(Name).edit_distance(
492 Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
493 if (!Best || Distance < BestDistance) {
495 BestDistance = Distance;
496 if (RHS.empty() || !PermitValue)
497 NearestString = Name;
499 NearestString = (Twine(Name) + "=" + RHS).str();
507 /// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence()
508 /// that does special handling of cl::CommaSeparated options.
509 static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos,
510 StringRef ArgName, StringRef Value,
511 bool MultiArg = false) {
512 // Check to see if this option accepts a comma separated list of values. If
513 // it does, we have to split up the value into multiple values.
514 if (Handler->getMiscFlags() & CommaSeparated) {
515 StringRef Val(Value);
516 StringRef::size_type Pos = Val.find(',');
518 while (Pos != StringRef::npos) {
519 // Process the portion before the comma.
520 if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
522 // Erase the portion before the comma, AND the comma.
523 Val = Val.substr(Pos + 1);
524 // Check for another comma.
531 return Handler->addOccurrence(pos, ArgName, Value, MultiArg);
534 /// ProvideOption - For Value, this differentiates between an empty value ("")
535 /// and a null value (StringRef()). The later is accepted for arguments that
536 /// don't allow a value (-foo) the former is rejected (-foo=).
537 static inline bool ProvideOption(Option *Handler, StringRef ArgName,
538 StringRef Value, int argc,
539 const char *const *argv, int &i) {
540 // Is this a multi-argument option?
541 unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
543 // Enforce value requirements
544 switch (Handler->getValueExpectedFlag()) {
546 if (!Value.data()) { // No value specified?
547 // If no other argument or the option only supports prefix form, we
548 // cannot look at the next argument.
549 if (i + 1 >= argc || Handler->getFormattingFlag() == cl::AlwaysPrefix)
550 return Handler->error("requires a value!");
551 // Steal the next argument, like for '-o filename'
552 assert(argv && "null check");
553 Value = StringRef(argv[++i]);
556 case ValueDisallowed:
557 if (NumAdditionalVals > 0)
558 return Handler->error("multi-valued option specified"
559 " with ValueDisallowed modifier!");
562 return Handler->error("does not allow a value! '" + Twine(Value) +
569 // If this isn't a multi-arg option, just run the handler.
570 if (NumAdditionalVals == 0)
571 return CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value);
573 // If it is, run the handle several times.
574 bool MultiArg = false;
577 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
583 while (NumAdditionalVals > 0) {
585 return Handler->error("not enough values!");
586 assert(argv && "null check");
587 Value = StringRef(argv[++i]);
589 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
597 static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
599 return ProvideOption(Handler, Handler->ArgStr, Arg, 0, nullptr, Dummy);
602 // Option predicates...
603 static inline bool isGrouping(const Option *O) {
604 return O->getFormattingFlag() == cl::Grouping;
606 static inline bool isPrefixedOrGrouping(const Option *O) {
607 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix ||
608 O->getFormattingFlag() == cl::AlwaysPrefix;
611 // getOptionPred - Check to see if there are any options that satisfy the
612 // specified predicate with names that are the prefixes in Name. This is
613 // checked by progressively stripping characters off of the name, checking to
614 // see if there options that satisfy the predicate. If we find one, return it,
615 // otherwise return null.
617 static Option *getOptionPred(StringRef Name, size_t &Length,
618 bool (*Pred)(const Option *),
619 const StringMap<Option *> &OptionsMap) {
621 StringMap<Option *>::const_iterator OMI = OptionsMap.find(Name);
623 // Loop while we haven't found an option and Name still has at least two
624 // characters in it (so that the next iteration will not be the empty
626 while (OMI == OptionsMap.end() && Name.size() > 1) {
627 Name = Name.substr(0, Name.size() - 1); // Chop off the last character.
628 OMI = OptionsMap.find(Name);
631 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
632 Length = Name.size();
633 return OMI->second; // Found one!
635 return nullptr; // No option found!
638 /// HandlePrefixedOrGroupedOption - The specified argument string (which started
639 /// with at least one '-') does not fully match an available option. Check to
640 /// see if this is a prefix or grouped option. If so, split arg into output an
641 /// Arg/Value pair and return the Option to parse it with.
643 HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
645 const StringMap<Option *> &OptionsMap) {
651 Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
655 // If the option is a prefixed option, then the value is simply the
656 // rest of the name... so fall through to later processing, by
657 // setting up the argument name flags and value fields.
658 if (PGOpt->getFormattingFlag() == cl::Prefix ||
659 PGOpt->getFormattingFlag() == cl::AlwaysPrefix) {
660 Value = Arg.substr(Length);
661 Arg = Arg.substr(0, Length);
662 assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
666 // This must be a grouped option... handle them now. Grouping options can't
668 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
671 // Move current arg name out of Arg into OneArgName.
672 StringRef OneArgName = Arg.substr(0, Length);
673 Arg = Arg.substr(Length);
675 // Because ValueRequired is an invalid flag for grouped arguments,
676 // we don't need to pass argc/argv in.
677 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
678 "Option can not be cl::Grouping AND cl::ValueRequired!");
681 ProvideOption(PGOpt, OneArgName, StringRef(), 0, nullptr, Dummy);
683 // Get the next grouping option.
684 PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
685 } while (PGOpt && Length != Arg.size());
687 // Return the last option with Arg cut down to just the last one.
691 static bool RequiresValue(const Option *O) {
692 return O->getNumOccurrencesFlag() == cl::Required ||
693 O->getNumOccurrencesFlag() == cl::OneOrMore;
696 static bool EatsUnboundedNumberOfValues(const Option *O) {
697 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
698 O->getNumOccurrencesFlag() == cl::OneOrMore;
701 static bool isWhitespace(char C) {
702 return C == ' ' || C == '\t' || C == '\r' || C == '\n';
705 static bool isWhitespaceOrNull(char C) {
706 return isWhitespace(C) || C == '\0';
709 static bool isQuote(char C) { return C == '\"' || C == '\''; }
711 void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
712 SmallVectorImpl<const char *> &NewArgv,
714 SmallString<128> Token;
715 for (size_t I = 0, E = Src.size(); I != E; ++I) {
716 // Consume runs of whitespace.
718 while (I != E && isWhitespace(Src[I])) {
719 // Mark the end of lines in response files
720 if (MarkEOLs && Src[I] == '\n')
721 NewArgv.push_back(nullptr);
730 // Backslash escapes the next character.
731 if (I + 1 < E && C == '\\') {
732 ++I; // Skip the escape.
733 Token.push_back(Src[I]);
737 // Consume a quoted string.
740 while (I != E && Src[I] != C) {
741 // Backslash escapes the next character.
742 if (Src[I] == '\\' && I + 1 != E)
744 Token.push_back(Src[I]);
752 // End the token if this is whitespace.
753 if (isWhitespace(C)) {
755 NewArgv.push_back(Saver.save(StringRef(Token)).data());
760 // This is a normal character. Append it.
764 // Append the last token after hitting EOF with no whitespace.
766 NewArgv.push_back(Saver.save(StringRef(Token)).data());
767 // Mark the end of response files
769 NewArgv.push_back(nullptr);
772 /// Backslashes are interpreted in a rather complicated way in the Windows-style
773 /// command line, because backslashes are used both to separate path and to
774 /// escape double quote. This method consumes runs of backslashes as well as the
775 /// following double quote if it's escaped.
777 /// * If an even number of backslashes is followed by a double quote, one
778 /// backslash is output for every pair of backslashes, and the last double
779 /// quote remains unconsumed. The double quote will later be interpreted as
780 /// the start or end of a quoted string in the main loop outside of this
783 /// * If an odd number of backslashes is followed by a double quote, one
784 /// backslash is output for every pair of backslashes, and a double quote is
785 /// output for the last pair of backslash-double quote. The double quote is
786 /// consumed in this case.
788 /// * Otherwise, backslashes are interpreted literally.
789 static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
790 size_t E = Src.size();
791 int BackslashCount = 0;
792 // Skip the backslashes.
796 } while (I != E && Src[I] == '\\');
798 bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
799 if (FollowedByDoubleQuote) {
800 Token.append(BackslashCount / 2, '\\');
801 if (BackslashCount % 2 == 0)
803 Token.push_back('"');
806 Token.append(BackslashCount, '\\');
810 void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
811 SmallVectorImpl<const char *> &NewArgv,
813 SmallString<128> Token;
815 // This is a small state machine to consume characters until it reaches the
816 // end of the source string.
817 enum { INIT, UNQUOTED, QUOTED } State = INIT;
818 for (size_t I = 0, E = Src.size(); I != E; ++I) {
821 // INIT state indicates that the current input index is at the start of
822 // the string or between tokens.
824 if (isWhitespaceOrNull(C)) {
825 // Mark the end of lines in response files
826 if (MarkEOLs && C == '\n')
827 NewArgv.push_back(nullptr);
835 I = parseBackslash(Src, I, Token);
844 // UNQUOTED state means that it's reading a token not quoted by double
846 if (State == UNQUOTED) {
847 // Whitespace means the end of the token.
848 if (isWhitespaceOrNull(C)) {
849 NewArgv.push_back(Saver.save(StringRef(Token)).data());
852 // Mark the end of lines in response files
853 if (MarkEOLs && C == '\n')
854 NewArgv.push_back(nullptr);
862 I = parseBackslash(Src, I, Token);
869 // QUOTED state means that it's reading a token quoted by double quotes.
870 if (State == QUOTED) {
876 I = parseBackslash(Src, I, Token);
882 // Append the last token after hitting EOF with no whitespace.
884 NewArgv.push_back(Saver.save(StringRef(Token)).data());
885 // Mark the end of response files
887 NewArgv.push_back(nullptr);
890 void cl::tokenizeConfigFile(StringRef Source, StringSaver &Saver,
891 SmallVectorImpl<const char *> &NewArgv,
893 for (const char *Cur = Source.begin(); Cur != Source.end();) {
894 SmallString<128> Line;
895 // Check for comment line.
896 if (isWhitespace(*Cur)) {
897 while (Cur != Source.end() && isWhitespace(*Cur))
902 while (Cur != Source.end() && *Cur != '\n')
906 // Find end of the current line.
907 const char *Start = Cur;
908 for (const char *End = Source.end(); Cur != End; ++Cur) {
910 if (Cur + 1 != End) {
913 (*Cur == '\r' && (Cur + 1 != End) && Cur[1] == '\n')) {
914 Line.append(Start, Cur - 1);
920 } else if (*Cur == '\n')
924 Line.append(Start, Cur);
925 cl::TokenizeGNUCommandLine(Line, Saver, NewArgv, MarkEOLs);
929 // It is called byte order marker but the UTF-8 BOM is actually not affected
930 // by the host system's endianness.
931 static bool hasUTF8ByteOrderMark(ArrayRef<char> S) {
932 return (S.size() >= 3 && S[0] == '\xef' && S[1] == '\xbb' && S[2] == '\xbf');
935 static bool ExpandResponseFile(StringRef FName, StringSaver &Saver,
936 TokenizerCallback Tokenizer,
937 SmallVectorImpl<const char *> &NewArgv,
938 bool MarkEOLs, bool RelativeNames) {
939 ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
940 MemoryBuffer::getFile(FName);
943 MemoryBuffer &MemBuf = *MemBufOrErr.get();
944 StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize());
946 // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
947 ArrayRef<char> BufRef(MemBuf.getBufferStart(), MemBuf.getBufferEnd());
949 if (hasUTF16ByteOrderMark(BufRef)) {
950 if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
952 Str = StringRef(UTF8Buf);
954 // If we see UTF-8 BOM sequence at the beginning of a file, we shall remove
955 // these bytes before parsing.
956 // Reference: http://en.wikipedia.org/wiki/UTF-8#Byte_order_mark
957 else if (hasUTF8ByteOrderMark(BufRef))
958 Str = StringRef(BufRef.data() + 3, BufRef.size() - 3);
960 // Tokenize the contents into NewArgv.
961 Tokenizer(Str, Saver, NewArgv, MarkEOLs);
963 // If names of nested response files should be resolved relative to including
964 // file, replace the included response file names with their full paths
965 // obtained by required resolution.
967 for (unsigned I = 0; I < NewArgv.size(); ++I)
969 StringRef Arg = NewArgv[I];
970 if (Arg.front() == '@') {
971 StringRef FileName = Arg.drop_front();
972 if (llvm::sys::path::is_relative(FileName)) {
973 SmallString<128> ResponseFile;
974 ResponseFile.append(1, '@');
975 if (llvm::sys::path::is_relative(FName)) {
976 SmallString<128> curr_dir;
977 llvm::sys::fs::current_path(curr_dir);
978 ResponseFile.append(curr_dir.str());
980 llvm::sys::path::append(
981 ResponseFile, llvm::sys::path::parent_path(FName), FileName);
982 NewArgv[I] = Saver.save(ResponseFile.c_str()).data();
990 /// Expand response files on a command line recursively using the given
991 /// StringSaver and tokenization strategy.
992 bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
993 SmallVectorImpl<const char *> &Argv,
994 bool MarkEOLs, bool RelativeNames) {
995 unsigned RspFiles = 0;
996 bool AllExpanded = true;
998 // Don't cache Argv.size() because it can change.
999 for (unsigned I = 0; I != Argv.size();) {
1000 const char *Arg = Argv[I];
1001 // Check if it is an EOL marker
1002 if (Arg == nullptr) {
1006 if (Arg[0] != '@') {
1011 // If we have too many response files, leave some unexpanded. This avoids
1012 // crashing on self-referential response files.
1013 if (RspFiles++ > 20)
1016 // Replace this response file argument with the tokenization of its
1017 // contents. Nested response files are expanded in subsequent iterations.
1018 SmallVector<const char *, 0> ExpandedArgv;
1019 if (!ExpandResponseFile(Arg + 1, Saver, Tokenizer, ExpandedArgv,
1020 MarkEOLs, RelativeNames)) {
1021 // We couldn't read this file, so we leave it in the argument stream and
1023 AllExpanded = false;
1027 Argv.erase(Argv.begin() + I);
1028 Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
1033 bool cl::readConfigFile(StringRef CfgFile, StringSaver &Saver,
1034 SmallVectorImpl<const char *> &Argv) {
1035 if (!ExpandResponseFile(CfgFile, Saver, cl::tokenizeConfigFile, Argv,
1036 /*MarkEOLs*/ false, /*RelativeNames*/ true))
1038 return ExpandResponseFiles(Saver, cl::tokenizeConfigFile, Argv,
1039 /*MarkEOLs*/ false, /*RelativeNames*/ true);
1042 /// ParseEnvironmentOptions - An alternative entry point to the
1043 /// CommandLine library, which allows you to read the program's name
1044 /// from the caller (as PROGNAME) and its command-line arguments from
1045 /// an environment variable (whose name is given in ENVVAR).
1047 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
1048 const char *Overview) {
1050 assert(progName && "Program name not specified");
1051 assert(envVar && "Environment variable name missing");
1053 // Get the environment variable they want us to parse options out of.
1054 llvm::Optional<std::string> envValue = sys::Process::GetEnv(StringRef(envVar));
1058 // Get program's "name", which we wouldn't know without the caller
1060 SmallVector<const char *, 20> newArgv;
1062 StringSaver Saver(A);
1063 newArgv.push_back(Saver.save(progName).data());
1065 // Parse the value of the environment variable into a "command line"
1066 // and hand it off to ParseCommandLineOptions().
1067 TokenizeGNUCommandLine(*envValue, Saver, newArgv);
1068 int newArgc = static_cast<int>(newArgv.size());
1069 ParseCommandLineOptions(newArgc, &newArgv[0], StringRef(Overview));
1072 bool cl::ParseCommandLineOptions(int argc, const char *const *argv,
1073 StringRef Overview, raw_ostream *Errs,
1074 const char *EnvVar) {
1075 SmallVector<const char *, 20> NewArgv;
1077 StringSaver Saver(A);
1078 NewArgv.push_back(argv[0]);
1080 // Parse options from environment variable.
1082 if (llvm::Optional<std::string> EnvValue =
1083 sys::Process::GetEnv(StringRef(EnvVar)))
1084 TokenizeGNUCommandLine(*EnvValue, Saver, NewArgv);
1087 // Append options from command line.
1088 for (int I = 1; I < argc; ++I)
1089 NewArgv.push_back(argv[I]);
1090 int NewArgc = static_cast<int>(NewArgv.size());
1092 // Parse all options.
1093 return GlobalParser->ParseCommandLineOptions(NewArgc, &NewArgv[0], Overview,
1097 void CommandLineParser::ResetAllOptionOccurrences() {
1098 // So that we can parse different command lines multiple times in succession
1099 // we reset all option values to look like they have never been seen before.
1100 for (auto SC : RegisteredSubCommands) {
1101 for (auto &O : SC->OptionsMap)
1106 bool CommandLineParser::ParseCommandLineOptions(int argc,
1107 const char *const *argv,
1109 raw_ostream *Errs) {
1110 assert(hasOptions() && "No options specified!");
1112 // Expand response files.
1113 SmallVector<const char *, 20> newArgv(argv, argv + argc);
1115 StringSaver Saver(A);
1116 ExpandResponseFiles(Saver,
1117 Triple(sys::getProcessTriple()).isOSWindows() ?
1118 cl::TokenizeWindowsCommandLine : cl::TokenizeGNUCommandLine,
1121 argc = static_cast<int>(newArgv.size());
1123 // Copy the program name into ProgName, making sure not to overflow it.
1124 ProgramName = sys::path::filename(StringRef(argv[0]));
1126 ProgramOverview = Overview;
1127 bool IgnoreErrors = Errs;
1130 bool ErrorParsing = false;
1132 // Check out the positional arguments to collect information about them.
1133 unsigned NumPositionalRequired = 0;
1135 // Determine whether or not there are an unlimited number of positionals
1136 bool HasUnlimitedPositionals = false;
1139 SubCommand *ChosenSubCommand = &*TopLevelSubCommand;
1140 if (argc >= 2 && argv[FirstArg][0] != '-') {
1141 // If the first argument specifies a valid subcommand, start processing
1142 // options from the second argument.
1143 ChosenSubCommand = LookupSubCommand(StringRef(argv[FirstArg]));
1144 if (ChosenSubCommand != &*TopLevelSubCommand)
1147 GlobalParser->ActiveSubCommand = ChosenSubCommand;
1149 assert(ChosenSubCommand);
1150 auto &ConsumeAfterOpt = ChosenSubCommand->ConsumeAfterOpt;
1151 auto &PositionalOpts = ChosenSubCommand->PositionalOpts;
1152 auto &SinkOpts = ChosenSubCommand->SinkOpts;
1153 auto &OptionsMap = ChosenSubCommand->OptionsMap;
1155 if (ConsumeAfterOpt) {
1156 assert(PositionalOpts.size() > 0 &&
1157 "Cannot specify cl::ConsumeAfter without a positional argument!");
1159 if (!PositionalOpts.empty()) {
1161 // Calculate how many positional values are _required_.
1162 bool UnboundedFound = false;
1163 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
1164 Option *Opt = PositionalOpts[i];
1165 if (RequiresValue(Opt))
1166 ++NumPositionalRequired;
1167 else if (ConsumeAfterOpt) {
1168 // ConsumeAfter cannot be combined with "optional" positional options
1169 // unless there is only one positional argument...
1170 if (PositionalOpts.size() > 1) {
1172 Opt->error("error - this positional option will never be matched, "
1173 "because it does not Require a value, and a "
1174 "cl::ConsumeAfter option is active!");
1175 ErrorParsing = true;
1177 } else if (UnboundedFound && !Opt->hasArgStr()) {
1178 // This option does not "require" a value... Make sure this option is
1179 // not specified after an option that eats all extra arguments, or this
1180 // one will never get any!
1183 Opt->error("error - option can never match, because "
1184 "another positional argument will match an "
1185 "unbounded number of values, and this option"
1186 " does not require a value!");
1187 *Errs << ProgramName << ": CommandLine Error: Option '" << Opt->ArgStr
1188 << "' is all messed up!\n";
1189 *Errs << PositionalOpts.size();
1190 ErrorParsing = true;
1192 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
1194 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
1197 // PositionalVals - A vector of "positional" arguments we accumulate into
1198 // the process at the end.
1200 SmallVector<std::pair<StringRef, unsigned>, 4> PositionalVals;
1202 // If the program has named positional arguments, and the name has been run
1203 // across, keep track of which positional argument was named. Otherwise put
1204 // the positional args into the PositionalVals list...
1205 Option *ActivePositionalArg = nullptr;
1207 // Loop over all of the arguments... processing them.
1208 bool DashDashFound = false; // Have we read '--'?
1209 for (int i = FirstArg; i < argc; ++i) {
1210 Option *Handler = nullptr;
1211 Option *NearestHandler = nullptr;
1212 std::string NearestHandlerString;
1214 StringRef ArgName = "";
1216 // Check to see if this is a positional argument. This argument is
1217 // considered to be positional if it doesn't start with '-', if it is "-"
1218 // itself, or if we have seen "--" already.
1220 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
1221 // Positional argument!
1222 if (ActivePositionalArg) {
1223 ProvidePositionalOption(ActivePositionalArg, StringRef(argv[i]), i);
1224 continue; // We are done!
1227 if (!PositionalOpts.empty()) {
1228 PositionalVals.push_back(std::make_pair(StringRef(argv[i]), i));
1230 // All of the positional arguments have been fulfulled, give the rest to
1231 // the consume after option... if it's specified...
1233 if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) {
1234 for (++i; i < argc; ++i)
1235 PositionalVals.push_back(std::make_pair(StringRef(argv[i]), i));
1236 break; // Handle outside of the argument processing loop...
1239 // Delay processing positional arguments until the end...
1242 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
1244 DashDashFound = true; // This is the mythical "--"?
1245 continue; // Don't try to process it as an argument itself.
1246 } else if (ActivePositionalArg &&
1247 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
1248 // If there is a positional argument eating options, check to see if this
1249 // option is another positional argument. If so, treat it as an argument,
1250 // otherwise feed it to the eating positional.
1251 ArgName = StringRef(argv[i] + 1);
1252 // Eat leading dashes.
1253 while (!ArgName.empty() && ArgName[0] == '-')
1254 ArgName = ArgName.substr(1);
1256 Handler = LookupOption(*ChosenSubCommand, ArgName, Value);
1257 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
1258 ProvidePositionalOption(ActivePositionalArg, StringRef(argv[i]), i);
1259 continue; // We are done!
1262 } else { // We start with a '-', must be an argument.
1263 ArgName = StringRef(argv[i] + 1);
1264 // Eat leading dashes.
1265 while (!ArgName.empty() && ArgName[0] == '-')
1266 ArgName = ArgName.substr(1);
1268 Handler = LookupOption(*ChosenSubCommand, ArgName, Value);
1270 // Check to see if this "option" is really a prefixed or grouped argument.
1272 Handler = HandlePrefixedOrGroupedOption(ArgName, Value, ErrorParsing,
1275 // Otherwise, look for the closest available option to report to the user
1276 // in the upcoming error.
1277 if (!Handler && SinkOpts.empty())
1279 LookupNearestOption(ArgName, OptionsMap, NearestHandlerString);
1283 if (SinkOpts.empty()) {
1284 *Errs << ProgramName << ": Unknown command line argument '" << argv[i]
1285 << "'. Try: '" << argv[0] << " -help'\n";
1287 if (NearestHandler) {
1288 // If we know a near match, report it as well.
1289 *Errs << ProgramName << ": Did you mean '-" << NearestHandlerString
1293 ErrorParsing = true;
1295 for (SmallVectorImpl<Option *>::iterator I = SinkOpts.begin(),
1298 (*I)->addOccurrence(i, "", StringRef(argv[i]));
1303 // If this is a named positional argument, just remember that it is the
1305 if (Handler->getFormattingFlag() == cl::Positional) {
1306 if ((Handler->getMiscFlags() & PositionalEatsArgs) && !Value.empty()) {
1307 Handler->error("This argument does not take a value.\n"
1308 "\tInstead, it consumes any positional arguments until "
1309 "the next recognized option.", *Errs);
1310 ErrorParsing = true;
1312 ActivePositionalArg = Handler;
1315 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
1318 // Check and handle positional arguments now...
1319 if (NumPositionalRequired > PositionalVals.size()) {
1320 *Errs << ProgramName
1321 << ": Not enough positional command line arguments specified!\n"
1322 << "Must specify at least " << NumPositionalRequired
1323 << " positional argument" << (NumPositionalRequired > 1 ? "s" : "")
1324 << ": See: " << argv[0] << " -help\n";
1326 ErrorParsing = true;
1327 } else if (!HasUnlimitedPositionals &&
1328 PositionalVals.size() > PositionalOpts.size()) {
1329 *Errs << ProgramName << ": Too many positional arguments specified!\n"
1330 << "Can specify at most " << PositionalOpts.size()
1331 << " positional arguments: See: " << argv[0] << " -help\n";
1332 ErrorParsing = true;
1334 } else if (!ConsumeAfterOpt) {
1335 // Positional args have already been handled if ConsumeAfter is specified.
1336 unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
1337 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
1338 if (RequiresValue(PositionalOpts[i])) {
1339 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
1340 PositionalVals[ValNo].second);
1342 --NumPositionalRequired; // We fulfilled our duty...
1345 // If we _can_ give this option more arguments, do so now, as long as we
1346 // do not give it values that others need. 'Done' controls whether the
1347 // option even _WANTS_ any more.
1349 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
1350 while (NumVals - ValNo > NumPositionalRequired && !Done) {
1351 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
1353 Done = true; // Optional arguments want _at most_ one value
1355 case cl::ZeroOrMore: // Zero or more will take all they can get...
1356 case cl::OneOrMore: // One or more will take all they can get...
1357 ProvidePositionalOption(PositionalOpts[i],
1358 PositionalVals[ValNo].first,
1359 PositionalVals[ValNo].second);
1363 llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
1364 "positional argument processing!");
1369 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
1371 for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
1372 if (RequiresValue(PositionalOpts[j])) {
1373 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
1374 PositionalVals[ValNo].first,
1375 PositionalVals[ValNo].second);
1379 // Handle the case where there is just one positional option, and it's
1380 // optional. In this case, we want to give JUST THE FIRST option to the
1381 // positional option and keep the rest for the consume after. The above
1382 // loop would have assigned no values to positional options in this case.
1384 if (PositionalOpts.size() == 1 && ValNo == 0 && !PositionalVals.empty()) {
1385 ErrorParsing |= ProvidePositionalOption(PositionalOpts[0],
1386 PositionalVals[ValNo].first,
1387 PositionalVals[ValNo].second);
1391 // Handle over all of the rest of the arguments to the
1392 // cl::ConsumeAfter command line option...
1393 for (; ValNo != PositionalVals.size(); ++ValNo)
1395 ProvidePositionalOption(ConsumeAfterOpt, PositionalVals[ValNo].first,
1396 PositionalVals[ValNo].second);
1399 // Loop over args and make sure all required args are specified!
1400 for (const auto &Opt : OptionsMap) {
1401 switch (Opt.second->getNumOccurrencesFlag()) {
1404 if (Opt.second->getNumOccurrences() == 0) {
1405 Opt.second->error("must be specified at least once!");
1406 ErrorParsing = true;
1414 // Now that we know if -debug is specified, we can use it.
1415 // Note that if ReadResponseFiles == true, this must be done before the
1416 // memory allocated for the expanded command line is free()d below.
1417 LLVM_DEBUG(dbgs() << "Args: ";
1418 for (int i = 0; i < argc; ++i) dbgs() << argv[i] << ' ';
1421 // Free all of the memory allocated to the map. Command line options may only
1422 // be processed once!
1425 // If we had an error processing our arguments, don't let the program execute
1434 //===----------------------------------------------------------------------===//
1435 // Option Base class implementation
1438 bool Option::error(const Twine &Message, StringRef ArgName, raw_ostream &Errs) {
1439 if (!ArgName.data())
1441 if (ArgName.empty())
1442 Errs << HelpStr; // Be nice for positional arguments
1444 Errs << GlobalParser->ProgramName << ": for the -" << ArgName;
1446 Errs << " option: " << Message << "\n";
1450 bool Option::addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
1453 NumOccurrences++; // Increment the number of times we have been seen
1455 switch (getNumOccurrencesFlag()) {
1457 if (NumOccurrences > 1)
1458 return error("may only occur zero or one times!", ArgName);
1461 if (NumOccurrences > 1)
1462 return error("must occur exactly one time!", ArgName);
1470 return handleOccurrence(pos, ArgName, Value);
1473 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
1474 // has been specified yet.
1476 static StringRef getValueStr(const Option &O, StringRef DefaultMsg) {
1477 if (O.ValueStr.empty())
1482 //===----------------------------------------------------------------------===//
1483 // cl::alias class implementation
1486 // Return the width of the option tag for printing...
1487 size_t alias::getOptionWidth() const { return ArgStr.size() + 6; }
1489 void Option::printHelpStr(StringRef HelpStr, size_t Indent,
1490 size_t FirstLineIndentedBy) {
1491 std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1492 outs().indent(Indent - FirstLineIndentedBy) << " - " << Split.first << "\n";
1493 while (!Split.second.empty()) {
1494 Split = Split.second.split('\n');
1495 outs().indent(Indent) << Split.first << "\n";
1499 // Print out the option for the alias.
1500 void alias::printOptionInfo(size_t GlobalWidth) const {
1501 outs() << " -" << ArgStr;
1502 printHelpStr(HelpStr, GlobalWidth, ArgStr.size() + 6);
1505 //===----------------------------------------------------------------------===//
1506 // Parser Implementation code...
1509 // basic_parser implementation
1512 // Return the width of the option tag for printing...
1513 size_t basic_parser_impl::getOptionWidth(const Option &O) const {
1514 size_t Len = O.ArgStr.size();
1515 auto ValName = getValueName();
1516 if (!ValName.empty()) {
1517 size_t FormattingLen = 3;
1518 if (O.getMiscFlags() & PositionalEatsArgs)
1520 Len += getValueStr(O, ValName).size() + FormattingLen;
1526 // printOptionInfo - Print out information about this option. The
1527 // to-be-maintained width is specified.
1529 void basic_parser_impl::printOptionInfo(const Option &O,
1530 size_t GlobalWidth) const {
1531 outs() << " -" << O.ArgStr;
1533 auto ValName = getValueName();
1534 if (!ValName.empty()) {
1535 if (O.getMiscFlags() & PositionalEatsArgs) {
1536 outs() << " <" << getValueStr(O, ValName) << ">...";
1538 outs() << "=<" << getValueStr(O, ValName) << '>';
1542 Option::printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
1545 void basic_parser_impl::printOptionName(const Option &O,
1546 size_t GlobalWidth) const {
1547 outs() << " -" << O.ArgStr;
1548 outs().indent(GlobalWidth - O.ArgStr.size());
1551 // parser<bool> implementation
1553 bool parser<bool>::parse(Option &O, StringRef ArgName, StringRef Arg,
1555 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1561 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1565 return O.error("'" + Arg +
1566 "' is invalid value for boolean argument! Try 0 or 1");
1569 // parser<boolOrDefault> implementation
1571 bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName, StringRef Arg,
1572 boolOrDefault &Value) {
1573 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1578 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1583 return O.error("'" + Arg +
1584 "' is invalid value for boolean argument! Try 0 or 1");
1587 // parser<int> implementation
1589 bool parser<int>::parse(Option &O, StringRef ArgName, StringRef Arg,
1591 if (Arg.getAsInteger(0, Value))
1592 return O.error("'" + Arg + "' value invalid for integer argument!");
1596 // parser<unsigned> implementation
1598 bool parser<unsigned>::parse(Option &O, StringRef ArgName, StringRef Arg,
1601 if (Arg.getAsInteger(0, Value))
1602 return O.error("'" + Arg + "' value invalid for uint argument!");
1606 // parser<unsigned long long> implementation
1608 bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
1610 unsigned long long &Value) {
1612 if (Arg.getAsInteger(0, Value))
1613 return O.error("'" + Arg + "' value invalid for uint argument!");
1617 // parser<double>/parser<float> implementation
1619 static bool parseDouble(Option &O, StringRef Arg, double &Value) {
1620 if (to_float(Arg, Value))
1622 return O.error("'" + Arg + "' value invalid for floating point argument!");
1625 bool parser<double>::parse(Option &O, StringRef ArgName, StringRef Arg,
1627 return parseDouble(O, Arg, Val);
1630 bool parser<float>::parse(Option &O, StringRef ArgName, StringRef Arg,
1633 if (parseDouble(O, Arg, dVal))
1639 // generic_parser_base implementation
1642 // findOption - Return the option number corresponding to the specified
1643 // argument string. If the option is not found, getNumOptions() is returned.
1645 unsigned generic_parser_base::findOption(StringRef Name) {
1646 unsigned e = getNumOptions();
1648 for (unsigned i = 0; i != e; ++i) {
1649 if (getOption(i) == Name)
1655 // Return the width of the option tag for printing...
1656 size_t generic_parser_base::getOptionWidth(const Option &O) const {
1657 if (O.hasArgStr()) {
1658 size_t Size = O.ArgStr.size() + 6;
1659 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1660 Size = std::max(Size, getOption(i).size() + 8);
1663 size_t BaseSize = 0;
1664 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1665 BaseSize = std::max(BaseSize, getOption(i).size() + 8);
1670 // printOptionInfo - Print out information about this option. The
1671 // to-be-maintained width is specified.
1673 void generic_parser_base::printOptionInfo(const Option &O,
1674 size_t GlobalWidth) const {
1675 if (O.hasArgStr()) {
1676 outs() << " -" << O.ArgStr;
1677 Option::printHelpStr(O.HelpStr, GlobalWidth, O.ArgStr.size() + 6);
1679 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1680 size_t NumSpaces = GlobalWidth - getOption(i).size() - 8;
1681 outs() << " =" << getOption(i);
1682 outs().indent(NumSpaces) << " - " << getDescription(i) << '\n';
1685 if (!O.HelpStr.empty())
1686 outs() << " " << O.HelpStr << '\n';
1687 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1688 auto Option = getOption(i);
1689 outs() << " -" << Option;
1690 Option::printHelpStr(getDescription(i), GlobalWidth, Option.size() + 8);
1695 static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1697 // printGenericOptionDiff - Print the value of this option and it's default.
1699 // "Generic" options have each value mapped to a name.
1700 void generic_parser_base::printGenericOptionDiff(
1701 const Option &O, const GenericOptionValue &Value,
1702 const GenericOptionValue &Default, size_t GlobalWidth) const {
1703 outs() << " -" << O.ArgStr;
1704 outs().indent(GlobalWidth - O.ArgStr.size());
1706 unsigned NumOpts = getNumOptions();
1707 for (unsigned i = 0; i != NumOpts; ++i) {
1708 if (Value.compare(getOptionValue(i)))
1711 outs() << "= " << getOption(i);
1712 size_t L = getOption(i).size();
1713 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1714 outs().indent(NumSpaces) << " (default: ";
1715 for (unsigned j = 0; j != NumOpts; ++j) {
1716 if (Default.compare(getOptionValue(j)))
1718 outs() << getOption(j);
1724 outs() << "= *unknown option value*\n";
1727 // printOptionDiff - Specializations for printing basic value types.
1729 #define PRINT_OPT_DIFF(T) \
1730 void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D, \
1731 size_t GlobalWidth) const { \
1732 printOptionName(O, GlobalWidth); \
1735 raw_string_ostream SS(Str); \
1738 outs() << "= " << Str; \
1739 size_t NumSpaces = \
1740 MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0; \
1741 outs().indent(NumSpaces) << " (default: "; \
1743 outs() << D.getValue(); \
1745 outs() << "*no default*"; \
1749 PRINT_OPT_DIFF(bool)
1750 PRINT_OPT_DIFF(boolOrDefault)
1752 PRINT_OPT_DIFF(unsigned)
1753 PRINT_OPT_DIFF(unsigned long long)
1754 PRINT_OPT_DIFF(double)
1755 PRINT_OPT_DIFF(float)
1756 PRINT_OPT_DIFF(char)
1758 void parser<std::string>::printOptionDiff(const Option &O, StringRef V,
1759 const OptionValue<std::string> &D,
1760 size_t GlobalWidth) const {
1761 printOptionName(O, GlobalWidth);
1762 outs() << "= " << V;
1763 size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
1764 outs().indent(NumSpaces) << " (default: ";
1766 outs() << D.getValue();
1768 outs() << "*no default*";
1772 // Print a placeholder for options that don't yet support printOptionDiff().
1773 void basic_parser_impl::printOptionNoValue(const Option &O,
1774 size_t GlobalWidth) const {
1775 printOptionName(O, GlobalWidth);
1776 outs() << "= *cannot print option value*\n";
1779 //===----------------------------------------------------------------------===//
1780 // -help and -help-hidden option implementation
1783 static int OptNameCompare(const std::pair<const char *, Option *> *LHS,
1784 const std::pair<const char *, Option *> *RHS) {
1785 return strcmp(LHS->first, RHS->first);
1788 static int SubNameCompare(const std::pair<const char *, SubCommand *> *LHS,
1789 const std::pair<const char *, SubCommand *> *RHS) {
1790 return strcmp(LHS->first, RHS->first);
1793 // Copy Options into a vector so we can sort them as we like.
1794 static void sortOpts(StringMap<Option *> &OptMap,
1795 SmallVectorImpl<std::pair<const char *, Option *>> &Opts,
1797 SmallPtrSet<Option *, 32> OptionSet; // Duplicate option detection.
1799 for (StringMap<Option *>::iterator I = OptMap.begin(), E = OptMap.end();
1801 // Ignore really-hidden options.
1802 if (I->second->getOptionHiddenFlag() == ReallyHidden)
1805 // Unless showhidden is set, ignore hidden flags.
1806 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
1809 // If we've already seen this option, don't add it to the list again.
1810 if (!OptionSet.insert(I->second).second)
1814 std::pair<const char *, Option *>(I->getKey().data(), I->second));
1817 // Sort the options list alphabetically.
1818 array_pod_sort(Opts.begin(), Opts.end(), OptNameCompare);
1822 sortSubCommands(const SmallPtrSetImpl<SubCommand *> &SubMap,
1823 SmallVectorImpl<std::pair<const char *, SubCommand *>> &Subs) {
1824 for (const auto &S : SubMap) {
1825 if (S->getName().empty())
1827 Subs.push_back(std::make_pair(S->getName().data(), S));
1829 array_pod_sort(Subs.begin(), Subs.end(), SubNameCompare);
1836 const bool ShowHidden;
1837 typedef SmallVector<std::pair<const char *, Option *>, 128>
1838 StrOptionPairVector;
1839 typedef SmallVector<std::pair<const char *, SubCommand *>, 128>
1840 StrSubCommandPairVector;
1841 // Print the options. Opts is assumed to be alphabetically sorted.
1842 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1843 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1844 Opts[i].second->printOptionInfo(MaxArgLen);
1847 void printSubCommands(StrSubCommandPairVector &Subs, size_t MaxSubLen) {
1848 for (const auto &S : Subs) {
1849 outs() << " " << S.first;
1850 if (!S.second->getDescription().empty()) {
1851 outs().indent(MaxSubLen - strlen(S.first));
1852 outs() << " - " << S.second->getDescription();
1859 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
1860 virtual ~HelpPrinter() {}
1862 // Invoke the printer.
1863 void operator=(bool Value) {
1868 // Halt the program since help information was printed
1873 SubCommand *Sub = GlobalParser->getActiveSubCommand();
1874 auto &OptionsMap = Sub->OptionsMap;
1875 auto &PositionalOpts = Sub->PositionalOpts;
1876 auto &ConsumeAfterOpt = Sub->ConsumeAfterOpt;
1878 StrOptionPairVector Opts;
1879 sortOpts(OptionsMap, Opts, ShowHidden);
1881 StrSubCommandPairVector Subs;
1882 sortSubCommands(GlobalParser->RegisteredSubCommands, Subs);
1884 if (!GlobalParser->ProgramOverview.empty())
1885 outs() << "OVERVIEW: " << GlobalParser->ProgramOverview << "\n";
1887 if (Sub == &*TopLevelSubCommand) {
1888 outs() << "USAGE: " << GlobalParser->ProgramName;
1889 if (Subs.size() > 2)
1890 outs() << " [subcommand]";
1891 outs() << " [options]";
1893 if (!Sub->getDescription().empty()) {
1894 outs() << "SUBCOMMAND '" << Sub->getName()
1895 << "': " << Sub->getDescription() << "\n\n";
1897 outs() << "USAGE: " << GlobalParser->ProgramName << " " << Sub->getName()
1901 for (auto Opt : PositionalOpts) {
1902 if (Opt->hasArgStr())
1903 outs() << " --" << Opt->ArgStr;
1904 outs() << " " << Opt->HelpStr;
1907 // Print the consume after option info if it exists...
1908 if (ConsumeAfterOpt)
1909 outs() << " " << ConsumeAfterOpt->HelpStr;
1911 if (Sub == &*TopLevelSubCommand && !Subs.empty()) {
1912 // Compute the maximum subcommand length...
1913 size_t MaxSubLen = 0;
1914 for (size_t i = 0, e = Subs.size(); i != e; ++i)
1915 MaxSubLen = std::max(MaxSubLen, strlen(Subs[i].first));
1918 outs() << "SUBCOMMANDS:\n\n";
1919 printSubCommands(Subs, MaxSubLen);
1921 outs() << " Type \"" << GlobalParser->ProgramName
1922 << " <subcommand> -help\" to get more help on a specific "
1928 // Compute the maximum argument length...
1929 size_t MaxArgLen = 0;
1930 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1931 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1933 outs() << "OPTIONS:\n";
1934 printOptions(Opts, MaxArgLen);
1936 // Print any extra help the user has declared.
1937 for (auto I : GlobalParser->MoreHelp)
1939 GlobalParser->MoreHelp.clear();
1943 class CategorizedHelpPrinter : public HelpPrinter {
1945 explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
1947 // Helper function for printOptions().
1948 // It shall return a negative value if A's name should be lexicographically
1949 // ordered before B's name. It returns a value greater than zero if B's name
1950 // should be ordered before A's name, and it returns 0 otherwise.
1951 static int OptionCategoryCompare(OptionCategory *const *A,
1952 OptionCategory *const *B) {
1953 return (*A)->getName().compare((*B)->getName());
1956 // Make sure we inherit our base class's operator=()
1957 using HelpPrinter::operator=;
1960 void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override {
1961 std::vector<OptionCategory *> SortedCategories;
1962 std::map<OptionCategory *, std::vector<Option *>> CategorizedOptions;
1964 // Collect registered option categories into vector in preparation for
1966 for (auto I = GlobalParser->RegisteredOptionCategories.begin(),
1967 E = GlobalParser->RegisteredOptionCategories.end();
1969 SortedCategories.push_back(*I);
1972 // Sort the different option categories alphabetically.
1973 assert(SortedCategories.size() > 0 && "No option categories registered!");
1974 array_pod_sort(SortedCategories.begin(), SortedCategories.end(),
1975 OptionCategoryCompare);
1977 // Create map to empty vectors.
1978 for (std::vector<OptionCategory *>::const_iterator
1979 I = SortedCategories.begin(),
1980 E = SortedCategories.end();
1982 CategorizedOptions[*I] = std::vector<Option *>();
1984 // Walk through pre-sorted options and assign into categories.
1985 // Because the options are already alphabetically sorted the
1986 // options within categories will also be alphabetically sorted.
1987 for (size_t I = 0, E = Opts.size(); I != E; ++I) {
1988 Option *Opt = Opts[I].second;
1989 assert(CategorizedOptions.count(Opt->Category) > 0 &&
1990 "Option has an unregistered category");
1991 CategorizedOptions[Opt->Category].push_back(Opt);
1995 for (std::vector<OptionCategory *>::const_iterator
1996 Category = SortedCategories.begin(),
1997 E = SortedCategories.end();
1998 Category != E; ++Category) {
1999 // Hide empty categories for -help, but show for -help-hidden.
2000 const auto &CategoryOptions = CategorizedOptions[*Category];
2001 bool IsEmptyCategory = CategoryOptions.empty();
2002 if (!ShowHidden && IsEmptyCategory)
2005 // Print category information.
2007 outs() << (*Category)->getName() << ":\n";
2009 // Check if description is set.
2010 if (!(*Category)->getDescription().empty())
2011 outs() << (*Category)->getDescription() << "\n\n";
2015 // When using -help-hidden explicitly state if the category has no
2016 // options associated with it.
2017 if (IsEmptyCategory) {
2018 outs() << " This option category has no options.\n";
2021 // Loop over the options in the category and print.
2022 for (const Option *Opt : CategoryOptions)
2023 Opt->printOptionInfo(MaxArgLen);
2028 // This wraps the Uncategorizing and Categorizing printers and decides
2029 // at run time which should be invoked.
2030 class HelpPrinterWrapper {
2032 HelpPrinter &UncategorizedPrinter;
2033 CategorizedHelpPrinter &CategorizedPrinter;
2036 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
2037 CategorizedHelpPrinter &CategorizedPrinter)
2038 : UncategorizedPrinter(UncategorizedPrinter),
2039 CategorizedPrinter(CategorizedPrinter) {}
2041 // Invoke the printer.
2042 void operator=(bool Value);
2045 } // End anonymous namespace
2047 // Declare the four HelpPrinter instances that are used to print out help, or
2048 // help-hidden as an uncategorized list or in categories.
2049 static HelpPrinter UncategorizedNormalPrinter(false);
2050 static HelpPrinter UncategorizedHiddenPrinter(true);
2051 static CategorizedHelpPrinter CategorizedNormalPrinter(false);
2052 static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
2054 // Declare HelpPrinter wrappers that will decide whether or not to invoke
2055 // a categorizing help printer
2056 static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
2057 CategorizedNormalPrinter);
2058 static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
2059 CategorizedHiddenPrinter);
2061 // Define a category for generic options that all tools should have.
2062 static cl::OptionCategory GenericCategory("Generic Options");
2064 // Define uncategorized help printers.
2065 // -help-list is hidden by default because if Option categories are being used
2066 // then -help behaves the same as -help-list.
2067 static cl::opt<HelpPrinter, true, parser<bool>> HLOp(
2069 cl::desc("Display list of available options (-help-list-hidden for more)"),
2070 cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed,
2071 cl::cat(GenericCategory), cl::sub(*AllSubCommands));
2073 static cl::opt<HelpPrinter, true, parser<bool>>
2074 HLHOp("help-list-hidden", cl::desc("Display list of all available options"),
2075 cl::location(UncategorizedHiddenPrinter), cl::Hidden,
2076 cl::ValueDisallowed, cl::cat(GenericCategory),
2077 cl::sub(*AllSubCommands));
2079 // Define uncategorized/categorized help printers. These printers change their
2080 // behaviour at runtime depending on whether one or more Option categories have
2082 static cl::opt<HelpPrinterWrapper, true, parser<bool>>
2083 HOp("help", cl::desc("Display available options (-help-hidden for more)"),
2084 cl::location(WrappedNormalPrinter), cl::ValueDisallowed,
2085 cl::cat(GenericCategory), cl::sub(*AllSubCommands));
2087 static cl::opt<HelpPrinterWrapper, true, parser<bool>>
2088 HHOp("help-hidden", cl::desc("Display all available options"),
2089 cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed,
2090 cl::cat(GenericCategory), cl::sub(*AllSubCommands));
2092 static cl::opt<bool> PrintOptions(
2094 cl::desc("Print non-default options after command line parsing"),
2095 cl::Hidden, cl::init(false), cl::cat(GenericCategory),
2096 cl::sub(*AllSubCommands));
2098 static cl::opt<bool> PrintAllOptions(
2099 "print-all-options",
2100 cl::desc("Print all option values after command line parsing"), cl::Hidden,
2101 cl::init(false), cl::cat(GenericCategory), cl::sub(*AllSubCommands));
2103 void HelpPrinterWrapper::operator=(bool Value) {
2107 // Decide which printer to invoke. If more than one option category is
2108 // registered then it is useful to show the categorized help instead of
2109 // uncategorized help.
2110 if (GlobalParser->RegisteredOptionCategories.size() > 1) {
2111 // unhide -help-list option so user can have uncategorized output if they
2113 HLOp.setHiddenFlag(NotHidden);
2115 CategorizedPrinter = true; // Invoke categorized printer
2117 UncategorizedPrinter = true; // Invoke uncategorized printer
2120 // Print the value of each option.
2121 void cl::PrintOptionValues() { GlobalParser->printOptionValues(); }
2123 void CommandLineParser::printOptionValues() {
2124 if (!PrintOptions && !PrintAllOptions)
2127 SmallVector<std::pair<const char *, Option *>, 128> Opts;
2128 sortOpts(ActiveSubCommand->OptionsMap, Opts, /*ShowHidden*/ true);
2130 // Compute the maximum argument length...
2131 size_t MaxArgLen = 0;
2132 for (size_t i = 0, e = Opts.size(); i != e; ++i)
2133 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
2135 for (size_t i = 0, e = Opts.size(); i != e; ++i)
2136 Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
2139 static VersionPrinterTy OverrideVersionPrinter = nullptr;
2141 static std::vector<VersionPrinterTy> *ExtraVersionPrinters = nullptr;
2144 class VersionPrinter {
2147 raw_ostream &OS = outs();
2148 #ifdef PACKAGE_VENDOR
2149 OS << PACKAGE_VENDOR << " ";
2151 OS << "LLVM (http://llvm.org/):\n ";
2153 OS << PACKAGE_NAME << " version " << PACKAGE_VERSION;
2154 #ifdef LLVM_VERSION_INFO
2155 OS << " " << LLVM_VERSION_INFO;
2158 #ifndef __OPTIMIZE__
2159 OS << "DEBUG build";
2161 OS << "Optimized build";
2164 OS << " with assertions";
2166 #if LLVM_VERSION_PRINTER_SHOW_HOST_TARGET_INFO
2167 std::string CPU = sys::getHostCPUName();
2168 if (CPU == "generic")
2171 << " Default target: " << sys::getDefaultTargetTriple() << '\n'
2172 << " Host CPU: " << CPU;
2176 void operator=(bool OptionWasSpecified) {
2177 if (!OptionWasSpecified)
2180 if (OverrideVersionPrinter != nullptr) {
2181 OverrideVersionPrinter(outs());
2186 // Iterate over any registered extra printers and call them to add further
2188 if (ExtraVersionPrinters != nullptr) {
2190 for (auto I : *ExtraVersionPrinters)
2197 } // End anonymous namespace
2199 // Define the --version option that prints out the LLVM version for the tool
2200 static VersionPrinter VersionPrinterInstance;
2202 static cl::opt<VersionPrinter, true, parser<bool>>
2203 VersOp("version", cl::desc("Display the version of this program"),
2204 cl::location(VersionPrinterInstance), cl::ValueDisallowed,
2205 cl::cat(GenericCategory));
2207 // Utility function for printing the help message.
2208 void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
2209 if (!Hidden && !Categorized)
2210 UncategorizedNormalPrinter.printHelp();
2211 else if (!Hidden && Categorized)
2212 CategorizedNormalPrinter.printHelp();
2213 else if (Hidden && !Categorized)
2214 UncategorizedHiddenPrinter.printHelp();
2216 CategorizedHiddenPrinter.printHelp();
2219 /// Utility function for printing version number.
2220 void cl::PrintVersionMessage() { VersionPrinterInstance.print(); }
2222 void cl::SetVersionPrinter(VersionPrinterTy func) { OverrideVersionPrinter = func; }
2224 void cl::AddExtraVersionPrinter(VersionPrinterTy func) {
2225 if (!ExtraVersionPrinters)
2226 ExtraVersionPrinters = new std::vector<VersionPrinterTy>;
2228 ExtraVersionPrinters->push_back(func);
2231 StringMap<Option *> &cl::getRegisteredOptions(SubCommand &Sub) {
2232 auto &Subs = GlobalParser->RegisteredSubCommands;
2234 assert(is_contained(Subs, &Sub));
2235 return Sub.OptionsMap;
2238 iterator_range<typename SmallPtrSet<SubCommand *, 4>::iterator>
2239 cl::getRegisteredSubcommands() {
2240 return GlobalParser->getRegisteredSubcommands();
2243 void cl::HideUnrelatedOptions(cl::OptionCategory &Category, SubCommand &Sub) {
2244 for (auto &I : Sub.OptionsMap) {
2245 if (I.second->Category != &Category &&
2246 I.second->Category != &GenericCategory)
2247 I.second->setHiddenFlag(cl::ReallyHidden);
2251 void cl::HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories,
2253 auto CategoriesBegin = Categories.begin();
2254 auto CategoriesEnd = Categories.end();
2255 for (auto &I : Sub.OptionsMap) {
2256 if (std::find(CategoriesBegin, CategoriesEnd, I.second->Category) ==
2258 I.second->Category != &GenericCategory)
2259 I.second->setHiddenFlag(cl::ReallyHidden);
2263 void cl::ResetCommandLineParser() { GlobalParser->reset(); }
2264 void cl::ResetAllOptionOccurrences() {
2265 GlobalParser->ResetAllOptionOccurrences();
2268 void LLVMParseCommandLineOptions(int argc, const char *const *argv,
2269 const char *Overview) {
2270 llvm::cl::ParseCommandLineOptions(argc, argv, StringRef(Overview),