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/SmallPtrSet.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/ADT/StringMap.h"
25 #include "llvm/ADT/Twine.h"
26 #include "llvm/Config/config.h"
27 #include "llvm/Support/ConvertUTF.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/Host.h"
31 #include "llvm/Support/ManagedStatic.h"
32 #include "llvm/Support/MemoryBuffer.h"
33 #include "llvm/Support/Path.h"
34 #include "llvm/Support/raw_ostream.h"
38 #include <system_error>
42 #define DEBUG_TYPE "commandline"
44 //===----------------------------------------------------------------------===//
45 // Template instantiations and anchors.
49 TEMPLATE_INSTANTIATION(class basic_parser<bool>);
50 TEMPLATE_INSTANTIATION(class basic_parser<boolOrDefault>);
51 TEMPLATE_INSTANTIATION(class basic_parser<int>);
52 TEMPLATE_INSTANTIATION(class basic_parser<unsigned>);
53 TEMPLATE_INSTANTIATION(class basic_parser<unsigned long long>);
54 TEMPLATE_INSTANTIATION(class basic_parser<double>);
55 TEMPLATE_INSTANTIATION(class basic_parser<float>);
56 TEMPLATE_INSTANTIATION(class basic_parser<std::string>);
57 TEMPLATE_INSTANTIATION(class basic_parser<char>);
59 TEMPLATE_INSTANTIATION(class opt<unsigned>);
60 TEMPLATE_INSTANTIATION(class opt<int>);
61 TEMPLATE_INSTANTIATION(class opt<std::string>);
62 TEMPLATE_INSTANTIATION(class opt<char>);
63 TEMPLATE_INSTANTIATION(class opt<bool>);
65 } // end namespace llvm::cl
67 // Pin the vtables to this file.
68 void GenericOptionValue::anchor() {}
69 void OptionValue<boolOrDefault>::anchor() {}
70 void OptionValue<std::string>::anchor() {}
71 void Option::anchor() {}
72 void basic_parser_impl::anchor() {}
73 void parser<bool>::anchor() {}
74 void parser<boolOrDefault>::anchor() {}
75 void parser<int>::anchor() {}
76 void parser<unsigned>::anchor() {}
77 void parser<unsigned long long>::anchor() {}
78 void parser<double>::anchor() {}
79 void parser<float>::anchor() {}
80 void parser<std::string>::anchor() {}
81 void parser<char>::anchor() {}
82 void StringSaver::anchor() {}
84 //===----------------------------------------------------------------------===//
88 class CommandLineParser {
90 // Globals for name and overview of program. Program name is not a string to
91 // avoid static ctor/dtor issues.
92 std::string ProgramName;
93 const char *ProgramOverview;
95 // This collects additional help to be printed.
96 std::vector<const char *> MoreHelp;
98 SmallVector<Option *, 4> PositionalOpts;
99 SmallVector<Option *, 4> SinkOpts;
100 StringMap<Option *> OptionsMap;
102 Option *ConsumeAfterOpt; // The ConsumeAfter option if it exists.
104 // This collects the different option categories that have been registered.
105 SmallPtrSet<OptionCategory *, 16> RegisteredOptionCategories;
107 CommandLineParser() : ProgramOverview(nullptr), ConsumeAfterOpt(nullptr) {}
109 void ParseCommandLineOptions(int argc, const char *const *argv,
110 const char *Overview);
112 void addLiteralOption(Option &Opt, const char *Name) {
113 if (!Opt.hasArgStr()) {
114 if (!OptionsMap.insert(std::make_pair(Name, &Opt)).second) {
115 errs() << ProgramName << ": CommandLine Error: Option '" << Name
116 << "' registered more than once!\n";
117 report_fatal_error("inconsistency in registered CommandLine options");
122 void addOption(Option *O) {
123 bool HadErrors = false;
125 // Add argument to the argument map!
126 if (!OptionsMap.insert(std::make_pair(O->ArgStr, O)).second) {
127 errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
128 << "' registered more than once!\n";
133 // Remember information about positional options.
134 if (O->getFormattingFlag() == cl::Positional)
135 PositionalOpts.push_back(O);
136 else if (O->getMiscFlags() & cl::Sink) // Remember sink options
137 SinkOpts.push_back(O);
138 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
139 if (ConsumeAfterOpt) {
140 O->error("Cannot specify more than one option with cl::ConsumeAfter!");
146 // Fail hard if there were errors. These are strictly unrecoverable and
147 // indicate serious issues such as conflicting option names or an
149 // linked LLVM distribution.
151 report_fatal_error("inconsistency in registered CommandLine options");
154 void removeOption(Option *O) {
155 SmallVector<const char *, 16> OptionNames;
156 O->getExtraOptionNames(OptionNames);
158 OptionNames.push_back(O->ArgStr);
159 for (auto Name : OptionNames)
160 OptionsMap.erase(StringRef(Name));
162 if (O->getFormattingFlag() == cl::Positional)
163 for (auto Opt = PositionalOpts.begin(); Opt != PositionalOpts.end();
166 PositionalOpts.erase(Opt);
170 else if (O->getMiscFlags() & cl::Sink)
171 for (auto Opt = SinkOpts.begin(); Opt != SinkOpts.end(); ++Opt) {
177 else if (O == ConsumeAfterOpt)
178 ConsumeAfterOpt = nullptr;
182 return (!OptionsMap.empty() || !PositionalOpts.empty() ||
183 nullptr != ConsumeAfterOpt);
186 void updateArgStr(Option *O, const char *NewName) {
187 if (!OptionsMap.insert(std::make_pair(NewName, O)).second) {
188 errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
189 << "' registered more than once!\n";
190 report_fatal_error("inconsistency in registered CommandLine options");
192 OptionsMap.erase(StringRef(O->ArgStr));
195 void printOptionValues();
197 void registerCategory(OptionCategory *cat) {
198 assert(std::count_if(RegisteredOptionCategories.begin(),
199 RegisteredOptionCategories.end(),
200 [cat](const OptionCategory *Category) {
201 return cat->getName() == Category->getName();
203 "Duplicate option categories");
205 RegisteredOptionCategories.insert(cat);
209 Option *LookupOption(StringRef &Arg, StringRef &Value);
214 static ManagedStatic<CommandLineParser> GlobalParser;
216 void cl::AddLiteralOption(Option &O, const char *Name) {
217 GlobalParser->addLiteralOption(O, Name);
220 extrahelp::extrahelp(const char *Help) : morehelp(Help) {
221 GlobalParser->MoreHelp.push_back(Help);
224 void Option::addArgument() {
225 GlobalParser->addOption(this);
226 FullyInitialized = true;
229 void Option::removeArgument() { GlobalParser->removeOption(this); }
231 void Option::setArgStr(const char *S) {
232 if (FullyInitialized)
233 GlobalParser->updateArgStr(this, S);
237 // Initialise the general option category.
238 OptionCategory llvm::cl::GeneralCategory("General options");
240 void OptionCategory::registerCategory() {
241 GlobalParser->registerCategory(this);
244 //===----------------------------------------------------------------------===//
245 // Basic, shared command line option processing machinery.
248 /// LookupOption - Lookup the option specified by the specified option on the
249 /// command line. If there is a value specified (after an equal sign) return
250 /// that as well. This assumes that leading dashes have already been stripped.
251 Option *CommandLineParser::LookupOption(StringRef &Arg, StringRef &Value) {
252 // Reject all dashes.
256 size_t EqualPos = Arg.find('=');
258 // If we have an equals sign, remember the value.
259 if (EqualPos == StringRef::npos) {
260 // Look up the option.
261 StringMap<Option *>::const_iterator I = OptionsMap.find(Arg);
262 return I != OptionsMap.end() ? I->second : nullptr;
265 // If the argument before the = is a valid option name, we match. If not,
266 // return Arg unmolested.
267 StringMap<Option *>::const_iterator I =
268 OptionsMap.find(Arg.substr(0, EqualPos));
269 if (I == OptionsMap.end())
272 Value = Arg.substr(EqualPos + 1);
273 Arg = Arg.substr(0, EqualPos);
277 /// LookupNearestOption - Lookup the closest match to the option specified by
278 /// the specified option on the command line. If there is a value specified
279 /// (after an equal sign) return that as well. This assumes that leading dashes
280 /// have already been stripped.
281 static Option *LookupNearestOption(StringRef Arg,
282 const StringMap<Option *> &OptionsMap,
283 std::string &NearestString) {
284 // Reject all dashes.
288 // Split on any equal sign.
289 std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
290 StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
291 StringRef &RHS = SplitArg.second;
293 // Find the closest match.
294 Option *Best = nullptr;
295 unsigned BestDistance = 0;
296 for (StringMap<Option *>::const_iterator it = OptionsMap.begin(),
297 ie = OptionsMap.end();
299 Option *O = it->second;
300 SmallVector<const char *, 16> OptionNames;
301 O->getExtraOptionNames(OptionNames);
303 OptionNames.push_back(O->ArgStr);
305 bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
306 StringRef Flag = PermitValue ? LHS : Arg;
307 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
308 StringRef Name = OptionNames[i];
309 unsigned Distance = StringRef(Name).edit_distance(
310 Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
311 if (!Best || Distance < BestDistance) {
313 BestDistance = Distance;
314 if (RHS.empty() || !PermitValue)
315 NearestString = OptionNames[i];
317 NearestString = std::string(OptionNames[i]) + "=" + RHS.str();
325 /// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence()
326 /// that does special handling of cl::CommaSeparated options.
327 static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos,
328 StringRef ArgName, StringRef Value,
329 bool MultiArg = false) {
330 // Check to see if this option accepts a comma separated list of values. If
331 // it does, we have to split up the value into multiple values.
332 if (Handler->getMiscFlags() & CommaSeparated) {
333 StringRef Val(Value);
334 StringRef::size_type Pos = Val.find(',');
336 while (Pos != StringRef::npos) {
337 // Process the portion before the comma.
338 if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
340 // Erase the portion before the comma, AND the comma.
341 Val = Val.substr(Pos + 1);
342 Value.substr(Pos + 1); // Increment the original value pointer as well.
343 // Check for another comma.
350 if (Handler->addOccurrence(pos, ArgName, Value, MultiArg))
356 /// ProvideOption - For Value, this differentiates between an empty value ("")
357 /// and a null value (StringRef()). The later is accepted for arguments that
358 /// don't allow a value (-foo) the former is rejected (-foo=).
359 static inline bool ProvideOption(Option *Handler, StringRef ArgName,
360 StringRef Value, int argc,
361 const char *const *argv, int &i) {
362 // Is this a multi-argument option?
363 unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
365 // Enforce value requirements
366 switch (Handler->getValueExpectedFlag()) {
368 if (!Value.data()) { // No value specified?
370 return Handler->error("requires a value!");
371 // Steal the next argument, like for '-o filename'
372 assert(argv && "null check");
376 case ValueDisallowed:
377 if (NumAdditionalVals > 0)
378 return Handler->error("multi-valued option specified"
379 " with ValueDisallowed modifier!");
382 return Handler->error("does not allow a value! '" + Twine(Value) +
389 // If this isn't a multi-arg option, just run the handler.
390 if (NumAdditionalVals == 0)
391 return CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value);
393 // If it is, run the handle several times.
394 bool MultiArg = false;
397 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
403 while (NumAdditionalVals > 0) {
405 return Handler->error("not enough values!");
406 assert(argv && "null check");
409 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
417 static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
419 return ProvideOption(Handler, Handler->ArgStr, Arg, 0, nullptr, Dummy);
422 // Option predicates...
423 static inline bool isGrouping(const Option *O) {
424 return O->getFormattingFlag() == cl::Grouping;
426 static inline bool isPrefixedOrGrouping(const Option *O) {
427 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
430 // getOptionPred - Check to see if there are any options that satisfy the
431 // specified predicate with names that are the prefixes in Name. This is
432 // checked by progressively stripping characters off of the name, checking to
433 // see if there options that satisfy the predicate. If we find one, return it,
434 // otherwise return null.
436 static Option *getOptionPred(StringRef Name, size_t &Length,
437 bool (*Pred)(const Option *),
438 const StringMap<Option *> &OptionsMap) {
440 StringMap<Option *>::const_iterator OMI = OptionsMap.find(Name);
442 // Loop while we haven't found an option and Name still has at least two
443 // characters in it (so that the next iteration will not be the empty
445 while (OMI == OptionsMap.end() && Name.size() > 1) {
446 Name = Name.substr(0, Name.size() - 1); // Chop off the last character.
447 OMI = OptionsMap.find(Name);
450 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
451 Length = Name.size();
452 return OMI->second; // Found one!
454 return nullptr; // No option found!
457 /// HandlePrefixedOrGroupedOption - The specified argument string (which started
458 /// with at least one '-') does not fully match an available option. Check to
459 /// see if this is a prefix or grouped option. If so, split arg into output an
460 /// Arg/Value pair and return the Option to parse it with.
462 HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
464 const StringMap<Option *> &OptionsMap) {
470 Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
474 // If the option is a prefixed option, then the value is simply the
475 // rest of the name... so fall through to later processing, by
476 // setting up the argument name flags and value fields.
477 if (PGOpt->getFormattingFlag() == cl::Prefix) {
478 Value = Arg.substr(Length);
479 Arg = Arg.substr(0, Length);
480 assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
484 // This must be a grouped option... handle them now. Grouping options can't
486 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
489 // Move current arg name out of Arg into OneArgName.
490 StringRef OneArgName = Arg.substr(0, Length);
491 Arg = Arg.substr(Length);
493 // Because ValueRequired is an invalid flag for grouped arguments,
494 // we don't need to pass argc/argv in.
495 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
496 "Option can not be cl::Grouping AND cl::ValueRequired!");
499 ProvideOption(PGOpt, OneArgName, StringRef(), 0, nullptr, Dummy);
501 // Get the next grouping option.
502 PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
503 } while (PGOpt && Length != Arg.size());
505 // Return the last option with Arg cut down to just the last one.
509 static bool RequiresValue(const Option *O) {
510 return O->getNumOccurrencesFlag() == cl::Required ||
511 O->getNumOccurrencesFlag() == cl::OneOrMore;
514 static bool EatsUnboundedNumberOfValues(const Option *O) {
515 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
516 O->getNumOccurrencesFlag() == cl::OneOrMore;
519 static bool isWhitespace(char C) { return strchr(" \t\n\r\f\v", C); }
521 static bool isQuote(char C) { return C == '\"' || C == '\''; }
523 static bool isGNUSpecial(char C) { return strchr("\\\"\' ", C); }
525 void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
526 SmallVectorImpl<const char *> &NewArgv,
528 SmallString<128> Token;
529 for (size_t I = 0, E = Src.size(); I != E; ++I) {
530 // Consume runs of whitespace.
532 while (I != E && isWhitespace(Src[I])) {
533 // Mark the end of lines in response files
534 if (MarkEOLs && Src[I] == '\n')
535 NewArgv.push_back(nullptr);
542 // Backslashes can escape backslashes, spaces, and other quotes. Otherwise
543 // they are literal. This makes it much easier to read Windows file paths.
544 if (I + 1 < E && Src[I] == '\\' && isGNUSpecial(Src[I + 1])) {
545 ++I; // Skip the escape.
546 Token.push_back(Src[I]);
550 // Consume a quoted string.
551 if (isQuote(Src[I])) {
552 char Quote = Src[I++];
553 while (I != E && Src[I] != Quote) {
554 // Backslashes are literal, unless they escape a special character.
555 if (Src[I] == '\\' && I + 1 != E && isGNUSpecial(Src[I + 1]))
557 Token.push_back(Src[I]);
565 // End the token if this is whitespace.
566 if (isWhitespace(Src[I])) {
568 NewArgv.push_back(Saver.SaveString(Token.c_str()));
573 // This is a normal character. Append it.
574 Token.push_back(Src[I]);
577 // Append the last token after hitting EOF with no whitespace.
579 NewArgv.push_back(Saver.SaveString(Token.c_str()));
580 // Mark the end of response files
582 NewArgv.push_back(nullptr);
585 /// Backslashes are interpreted in a rather complicated way in the Windows-style
586 /// command line, because backslashes are used both to separate path and to
587 /// escape double quote. This method consumes runs of backslashes as well as the
588 /// following double quote if it's escaped.
590 /// * If an even number of backslashes is followed by a double quote, one
591 /// backslash is output for every pair of backslashes, and the last double
592 /// quote remains unconsumed. The double quote will later be interpreted as
593 /// the start or end of a quoted string in the main loop outside of this
596 /// * If an odd number of backslashes is followed by a double quote, one
597 /// backslash is output for every pair of backslashes, and a double quote is
598 /// output for the last pair of backslash-double quote. The double quote is
599 /// consumed in this case.
601 /// * Otherwise, backslashes are interpreted literally.
602 static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
603 size_t E = Src.size();
604 int BackslashCount = 0;
605 // Skip the backslashes.
609 } while (I != E && Src[I] == '\\');
611 bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
612 if (FollowedByDoubleQuote) {
613 Token.append(BackslashCount / 2, '\\');
614 if (BackslashCount % 2 == 0)
616 Token.push_back('"');
619 Token.append(BackslashCount, '\\');
623 void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
624 SmallVectorImpl<const char *> &NewArgv,
626 SmallString<128> Token;
628 // This is a small state machine to consume characters until it reaches the
629 // end of the source string.
630 enum { INIT, UNQUOTED, QUOTED } State = INIT;
631 for (size_t I = 0, E = Src.size(); I != E; ++I) {
632 // INIT state indicates that the current input index is at the start of
633 // the string or between tokens.
635 if (isWhitespace(Src[I])) {
636 // Mark the end of lines in response files
637 if (MarkEOLs && Src[I] == '\n')
638 NewArgv.push_back(nullptr);
645 if (Src[I] == '\\') {
646 I = parseBackslash(Src, I, Token);
650 Token.push_back(Src[I]);
655 // UNQUOTED state means that it's reading a token not quoted by double
657 if (State == UNQUOTED) {
658 // Whitespace means the end of the token.
659 if (isWhitespace(Src[I])) {
660 NewArgv.push_back(Saver.SaveString(Token.c_str()));
663 // Mark the end of lines in response files
664 if (MarkEOLs && Src[I] == '\n')
665 NewArgv.push_back(nullptr);
672 if (Src[I] == '\\') {
673 I = parseBackslash(Src, I, Token);
676 Token.push_back(Src[I]);
680 // QUOTED state means that it's reading a token quoted by double quotes.
681 if (State == QUOTED) {
686 if (Src[I] == '\\') {
687 I = parseBackslash(Src, I, Token);
690 Token.push_back(Src[I]);
693 // Append the last token after hitting EOF with no whitespace.
695 NewArgv.push_back(Saver.SaveString(Token.c_str()));
696 // Mark the end of response files
698 NewArgv.push_back(nullptr);
701 // It is called byte order marker but the UTF-8 BOM is actually not affected
702 // by the host system's endianness.
703 static bool hasUTF8ByteOrderMark(ArrayRef<char> S) {
704 return (S.size() >= 3 && S[0] == '\xef' && S[1] == '\xbb' && S[2] == '\xbf');
707 static bool ExpandResponseFile(const char *FName, StringSaver &Saver,
708 TokenizerCallback Tokenizer,
709 SmallVectorImpl<const char *> &NewArgv,
710 bool MarkEOLs = false) {
711 ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
712 MemoryBuffer::getFile(FName);
715 MemoryBuffer &MemBuf = *MemBufOrErr.get();
716 StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize());
718 // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
719 ArrayRef<char> BufRef(MemBuf.getBufferStart(), MemBuf.getBufferEnd());
721 if (hasUTF16ByteOrderMark(BufRef)) {
722 if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
724 Str = StringRef(UTF8Buf);
726 // If we see UTF-8 BOM sequence at the beginning of a file, we shall remove
727 // these bytes before parsing.
728 // Reference: http://en.wikipedia.org/wiki/UTF-8#Byte_order_mark
729 else if (hasUTF8ByteOrderMark(BufRef))
730 Str = StringRef(BufRef.data() + 3, BufRef.size() - 3);
732 // Tokenize the contents into NewArgv.
733 Tokenizer(Str, Saver, NewArgv, MarkEOLs);
738 /// \brief Expand response files on a command line recursively using the given
739 /// StringSaver and tokenization strategy.
740 bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
741 SmallVectorImpl<const char *> &Argv,
743 unsigned RspFiles = 0;
744 bool AllExpanded = true;
746 // Don't cache Argv.size() because it can change.
747 for (unsigned I = 0; I != Argv.size();) {
748 const char *Arg = Argv[I];
749 // Check if it is an EOL marker
750 if (Arg == nullptr) {
759 // If we have too many response files, leave some unexpanded. This avoids
760 // crashing on self-referential response files.
764 // Replace this response file argument with the tokenization of its
765 // contents. Nested response files are expanded in subsequent iterations.
766 // FIXME: If a nested response file uses a relative path, is it relative to
767 // the cwd of the process or the response file?
768 SmallVector<const char *, 0> ExpandedArgv;
769 if (!ExpandResponseFile(Arg + 1, Saver, Tokenizer, ExpandedArgv,
771 // We couldn't read this file, so we leave it in the argument stream and
777 Argv.erase(Argv.begin() + I);
778 Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
784 class StrDupSaver : public StringSaver {
785 std::vector<char *> Dups;
789 for (std::vector<char *>::iterator I = Dups.begin(), E = Dups.end(); I != E;
795 const char *SaveString(const char *Str) override {
796 char *Dup = strdup(Str);
803 /// ParseEnvironmentOptions - An alternative entry point to the
804 /// CommandLine library, which allows you to read the program's name
805 /// from the caller (as PROGNAME) and its command-line arguments from
806 /// an environment variable (whose name is given in ENVVAR).
808 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
809 const char *Overview) {
811 assert(progName && "Program name not specified");
812 assert(envVar && "Environment variable name missing");
814 // Get the environment variable they want us to parse options out of.
815 const char *envValue = getenv(envVar);
819 // Get program's "name", which we wouldn't know without the caller
821 SmallVector<const char *, 20> newArgv;
823 newArgv.push_back(Saver.SaveString(progName));
825 // Parse the value of the environment variable into a "command line"
826 // and hand it off to ParseCommandLineOptions().
827 TokenizeGNUCommandLine(envValue, Saver, newArgv);
828 int newArgc = static_cast<int>(newArgv.size());
829 ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
832 void cl::ParseCommandLineOptions(int argc, const char *const *argv,
833 const char *Overview) {
834 GlobalParser->ParseCommandLineOptions(argc, argv, Overview);
837 void CommandLineParser::ParseCommandLineOptions(int argc,
838 const char *const *argv,
839 const char *Overview) {
840 assert(hasOptions() && "No options specified!");
842 // Expand response files.
843 SmallVector<const char *, 20> newArgv;
844 for (int i = 0; i != argc; ++i)
845 newArgv.push_back(argv[i]);
847 ExpandResponseFiles(Saver, TokenizeGNUCommandLine, newArgv);
849 argc = static_cast<int>(newArgv.size());
851 // Copy the program name into ProgName, making sure not to overflow it.
852 ProgramName = sys::path::filename(argv[0]);
854 ProgramOverview = Overview;
855 bool ErrorParsing = false;
857 // Check out the positional arguments to collect information about them.
858 unsigned NumPositionalRequired = 0;
860 // Determine whether or not there are an unlimited number of positionals
861 bool HasUnlimitedPositionals = false;
863 if (ConsumeAfterOpt) {
864 assert(PositionalOpts.size() > 0 &&
865 "Cannot specify cl::ConsumeAfter without a positional argument!");
867 if (!PositionalOpts.empty()) {
869 // Calculate how many positional values are _required_.
870 bool UnboundedFound = false;
871 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
872 Option *Opt = PositionalOpts[i];
873 if (RequiresValue(Opt))
874 ++NumPositionalRequired;
875 else if (ConsumeAfterOpt) {
876 // ConsumeAfter cannot be combined with "optional" positional options
877 // unless there is only one positional argument...
878 if (PositionalOpts.size() > 1)
879 ErrorParsing |= Opt->error(
880 "error - this positional option will never be matched, "
881 "because it does not Require a value, and a "
882 "cl::ConsumeAfter option is active!");
883 } else if (UnboundedFound && !Opt->ArgStr[0]) {
884 // This option does not "require" a value... Make sure this option is
885 // not specified after an option that eats all extra arguments, or this
886 // one will never get any!
888 ErrorParsing |= Opt->error("error - option can never match, because "
889 "another positional argument will match an "
890 "unbounded number of values, and this option"
891 " does not require a value!");
892 errs() << ProgramName << ": CommandLine Error: Option '" << Opt->ArgStr
893 << "' is all messed up!\n";
894 errs() << PositionalOpts.size();
896 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
898 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
901 // PositionalVals - A vector of "positional" arguments we accumulate into
902 // the process at the end.
904 SmallVector<std::pair<StringRef, unsigned>, 4> PositionalVals;
906 // If the program has named positional arguments, and the name has been run
907 // across, keep track of which positional argument was named. Otherwise put
908 // the positional args into the PositionalVals list...
909 Option *ActivePositionalArg = nullptr;
911 // Loop over all of the arguments... processing them.
912 bool DashDashFound = false; // Have we read '--'?
913 for (int i = 1; i < argc; ++i) {
914 Option *Handler = nullptr;
915 Option *NearestHandler = nullptr;
916 std::string NearestHandlerString;
918 StringRef ArgName = "";
920 // Check to see if this is a positional argument. This argument is
921 // considered to be positional if it doesn't start with '-', if it is "-"
922 // itself, or if we have seen "--" already.
924 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
925 // Positional argument!
926 if (ActivePositionalArg) {
927 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
928 continue; // We are done!
931 if (!PositionalOpts.empty()) {
932 PositionalVals.push_back(std::make_pair(argv[i], i));
934 // All of the positional arguments have been fulfulled, give the rest to
935 // the consume after option... if it's specified...
937 if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) {
938 for (++i; i < argc; ++i)
939 PositionalVals.push_back(std::make_pair(argv[i], i));
940 break; // Handle outside of the argument processing loop...
943 // Delay processing positional arguments until the end...
946 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
948 DashDashFound = true; // This is the mythical "--"?
949 continue; // Don't try to process it as an argument itself.
950 } else if (ActivePositionalArg &&
951 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
952 // If there is a positional argument eating options, check to see if this
953 // option is another positional argument. If so, treat it as an argument,
954 // otherwise feed it to the eating positional.
955 ArgName = argv[i] + 1;
956 // Eat leading dashes.
957 while (!ArgName.empty() && ArgName[0] == '-')
958 ArgName = ArgName.substr(1);
960 Handler = LookupOption(ArgName, Value);
961 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
962 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
963 continue; // We are done!
966 } else { // We start with a '-', must be an argument.
967 ArgName = argv[i] + 1;
968 // Eat leading dashes.
969 while (!ArgName.empty() && ArgName[0] == '-')
970 ArgName = ArgName.substr(1);
972 Handler = LookupOption(ArgName, Value);
974 // Check to see if this "option" is really a prefixed or grouped argument.
976 Handler = HandlePrefixedOrGroupedOption(ArgName, Value, ErrorParsing,
979 // Otherwise, look for the closest available option to report to the user
980 // in the upcoming error.
981 if (!Handler && SinkOpts.empty())
983 LookupNearestOption(ArgName, OptionsMap, NearestHandlerString);
987 if (SinkOpts.empty()) {
988 errs() << ProgramName << ": Unknown command line argument '" << argv[i]
989 << "'. Try: '" << argv[0] << " -help'\n";
991 if (NearestHandler) {
992 // If we know a near match, report it as well.
993 errs() << ProgramName << ": Did you mean '-" << NearestHandlerString
999 for (SmallVectorImpl<Option *>::iterator I = SinkOpts.begin(),
1002 (*I)->addOccurrence(i, "", argv[i]);
1007 // If this is a named positional argument, just remember that it is the
1009 if (Handler->getFormattingFlag() == cl::Positional)
1010 ActivePositionalArg = Handler;
1012 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
1015 // Check and handle positional arguments now...
1016 if (NumPositionalRequired > PositionalVals.size()) {
1017 errs() << ProgramName
1018 << ": Not enough positional command line arguments specified!\n"
1019 << "Must specify at least " << NumPositionalRequired
1020 << " positional arguments: See: " << argv[0] << " -help\n";
1022 ErrorParsing = true;
1023 } else if (!HasUnlimitedPositionals &&
1024 PositionalVals.size() > PositionalOpts.size()) {
1025 errs() << ProgramName << ": Too many positional arguments specified!\n"
1026 << "Can specify at most " << PositionalOpts.size()
1027 << " positional arguments: See: " << argv[0] << " -help\n";
1028 ErrorParsing = true;
1030 } else if (!ConsumeAfterOpt) {
1031 // Positional args have already been handled if ConsumeAfter is specified.
1032 unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
1033 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
1034 if (RequiresValue(PositionalOpts[i])) {
1035 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
1036 PositionalVals[ValNo].second);
1038 --NumPositionalRequired; // We fulfilled our duty...
1041 // If we _can_ give this option more arguments, do so now, as long as we
1042 // do not give it values that others need. 'Done' controls whether the
1043 // option even _WANTS_ any more.
1045 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
1046 while (NumVals - ValNo > NumPositionalRequired && !Done) {
1047 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
1049 Done = true; // Optional arguments want _at most_ one value
1051 case cl::ZeroOrMore: // Zero or more will take all they can get...
1052 case cl::OneOrMore: // One or more will take all they can get...
1053 ProvidePositionalOption(PositionalOpts[i],
1054 PositionalVals[ValNo].first,
1055 PositionalVals[ValNo].second);
1059 llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
1060 "positional argument processing!");
1065 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
1067 for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
1068 if (RequiresValue(PositionalOpts[j])) {
1069 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
1070 PositionalVals[ValNo].first,
1071 PositionalVals[ValNo].second);
1075 // Handle the case where there is just one positional option, and it's
1076 // optional. In this case, we want to give JUST THE FIRST option to the
1077 // positional option and keep the rest for the consume after. The above
1078 // loop would have assigned no values to positional options in this case.
1080 if (PositionalOpts.size() == 1 && ValNo == 0 && !PositionalVals.empty()) {
1081 ErrorParsing |= ProvidePositionalOption(PositionalOpts[0],
1082 PositionalVals[ValNo].first,
1083 PositionalVals[ValNo].second);
1087 // Handle over all of the rest of the arguments to the
1088 // cl::ConsumeAfter command line option...
1089 for (; ValNo != PositionalVals.size(); ++ValNo)
1091 ProvidePositionalOption(ConsumeAfterOpt, PositionalVals[ValNo].first,
1092 PositionalVals[ValNo].second);
1095 // Loop over args and make sure all required args are specified!
1096 for (const auto &Opt : OptionsMap) {
1097 switch (Opt.second->getNumOccurrencesFlag()) {
1100 if (Opt.second->getNumOccurrences() == 0) {
1101 Opt.second->error("must be specified at least once!");
1102 ErrorParsing = true;
1110 // Now that we know if -debug is specified, we can use it.
1111 // Note that if ReadResponseFiles == true, this must be done before the
1112 // memory allocated for the expanded command line is free()d below.
1113 DEBUG(dbgs() << "Args: ";
1114 for (int i = 0; i < argc; ++i) dbgs() << argv[i] << ' ';
1117 // Free all of the memory allocated to the map. Command line options may only
1118 // be processed once!
1121 // If we had an error processing our arguments, don't let the program execute
1126 //===----------------------------------------------------------------------===//
1127 // Option Base class implementation
1130 bool Option::error(const Twine &Message, StringRef ArgName) {
1131 if (!ArgName.data())
1133 if (ArgName.empty())
1134 errs() << HelpStr; // Be nice for positional arguments
1136 errs() << GlobalParser->ProgramName << ": for the -" << ArgName;
1138 errs() << " option: " << Message << "\n";
1142 bool Option::addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
1145 NumOccurrences++; // Increment the number of times we have been seen
1147 switch (getNumOccurrencesFlag()) {
1149 if (NumOccurrences > 1)
1150 return error("may only occur zero or one times!", ArgName);
1153 if (NumOccurrences > 1)
1154 return error("must occur exactly one time!", ArgName);
1162 return handleOccurrence(pos, ArgName, Value);
1165 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
1166 // has been specified yet.
1168 static const char *getValueStr(const Option &O, const char *DefaultMsg) {
1169 if (O.ValueStr[0] == 0)
1174 //===----------------------------------------------------------------------===//
1175 // cl::alias class implementation
1178 // Return the width of the option tag for printing...
1179 size_t alias::getOptionWidth() const { return std::strlen(ArgStr) + 6; }
1181 static void printHelpStr(StringRef HelpStr, size_t Indent,
1182 size_t FirstLineIndentedBy) {
1183 std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1184 outs().indent(Indent - FirstLineIndentedBy) << " - " << Split.first << "\n";
1185 while (!Split.second.empty()) {
1186 Split = Split.second.split('\n');
1187 outs().indent(Indent) << Split.first << "\n";
1191 // Print out the option for the alias.
1192 void alias::printOptionInfo(size_t GlobalWidth) const {
1193 outs() << " -" << ArgStr;
1194 printHelpStr(HelpStr, GlobalWidth, std::strlen(ArgStr) + 6);
1197 //===----------------------------------------------------------------------===//
1198 // Parser Implementation code...
1201 // basic_parser implementation
1204 // Return the width of the option tag for printing...
1205 size_t basic_parser_impl::getOptionWidth(const Option &O) const {
1206 size_t Len = std::strlen(O.ArgStr);
1207 if (const char *ValName = getValueName())
1208 Len += std::strlen(getValueStr(O, ValName)) + 3;
1213 // printOptionInfo - Print out information about this option. The
1214 // to-be-maintained width is specified.
1216 void basic_parser_impl::printOptionInfo(const Option &O,
1217 size_t GlobalWidth) const {
1218 outs() << " -" << O.ArgStr;
1220 if (const char *ValName = getValueName())
1221 outs() << "=<" << getValueStr(O, ValName) << '>';
1223 printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
1226 void basic_parser_impl::printOptionName(const Option &O,
1227 size_t GlobalWidth) const {
1228 outs() << " -" << O.ArgStr;
1229 outs().indent(GlobalWidth - std::strlen(O.ArgStr));
1232 // parser<bool> implementation
1234 bool parser<bool>::parse(Option &O, StringRef ArgName, StringRef Arg,
1236 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1242 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1246 return O.error("'" + Arg +
1247 "' is invalid value for boolean argument! Try 0 or 1");
1250 // parser<boolOrDefault> implementation
1252 bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName, StringRef Arg,
1253 boolOrDefault &Value) {
1254 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1259 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1264 return O.error("'" + Arg +
1265 "' is invalid value for boolean argument! Try 0 or 1");
1268 // parser<int> implementation
1270 bool parser<int>::parse(Option &O, StringRef ArgName, StringRef Arg,
1272 if (Arg.getAsInteger(0, Value))
1273 return O.error("'" + Arg + "' value invalid for integer argument!");
1277 // parser<unsigned> implementation
1279 bool parser<unsigned>::parse(Option &O, StringRef ArgName, StringRef Arg,
1282 if (Arg.getAsInteger(0, Value))
1283 return O.error("'" + Arg + "' value invalid for uint argument!");
1287 // parser<unsigned long long> implementation
1289 bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
1291 unsigned long long &Value) {
1293 if (Arg.getAsInteger(0, Value))
1294 return O.error("'" + Arg + "' value invalid for uint argument!");
1298 // parser<double>/parser<float> implementation
1300 static bool parseDouble(Option &O, StringRef Arg, double &Value) {
1301 SmallString<32> TmpStr(Arg.begin(), Arg.end());
1302 const char *ArgStart = TmpStr.c_str();
1304 Value = strtod(ArgStart, &End);
1306 return O.error("'" + Arg + "' value invalid for floating point argument!");
1310 bool parser<double>::parse(Option &O, StringRef ArgName, StringRef Arg,
1312 return parseDouble(O, Arg, Val);
1315 bool parser<float>::parse(Option &O, StringRef ArgName, StringRef Arg,
1318 if (parseDouble(O, Arg, dVal))
1324 // generic_parser_base implementation
1327 // findOption - Return the option number corresponding to the specified
1328 // argument string. If the option is not found, getNumOptions() is returned.
1330 unsigned generic_parser_base::findOption(const char *Name) {
1331 unsigned e = getNumOptions();
1333 for (unsigned i = 0; i != e; ++i) {
1334 if (strcmp(getOption(i), Name) == 0)
1340 // Return the width of the option tag for printing...
1341 size_t generic_parser_base::getOptionWidth(const Option &O) const {
1342 if (O.hasArgStr()) {
1343 size_t Size = std::strlen(O.ArgStr) + 6;
1344 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1345 Size = std::max(Size, std::strlen(getOption(i)) + 8);
1348 size_t BaseSize = 0;
1349 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1350 BaseSize = std::max(BaseSize, std::strlen(getOption(i)) + 8);
1355 // printOptionInfo - Print out information about this option. The
1356 // to-be-maintained width is specified.
1358 void generic_parser_base::printOptionInfo(const Option &O,
1359 size_t GlobalWidth) const {
1360 if (O.hasArgStr()) {
1361 outs() << " -" << O.ArgStr;
1362 printHelpStr(O.HelpStr, GlobalWidth, std::strlen(O.ArgStr) + 6);
1364 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1365 size_t NumSpaces = GlobalWidth - strlen(getOption(i)) - 8;
1366 outs() << " =" << getOption(i);
1367 outs().indent(NumSpaces) << " - " << getDescription(i) << '\n';
1371 outs() << " " << O.HelpStr << '\n';
1372 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1373 const char *Option = getOption(i);
1374 outs() << " -" << Option;
1375 printHelpStr(getDescription(i), GlobalWidth, std::strlen(Option) + 8);
1380 static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1382 // printGenericOptionDiff - Print the value of this option and it's default.
1384 // "Generic" options have each value mapped to a name.
1385 void generic_parser_base::printGenericOptionDiff(
1386 const Option &O, const GenericOptionValue &Value,
1387 const GenericOptionValue &Default, size_t GlobalWidth) const {
1388 outs() << " -" << O.ArgStr;
1389 outs().indent(GlobalWidth - std::strlen(O.ArgStr));
1391 unsigned NumOpts = getNumOptions();
1392 for (unsigned i = 0; i != NumOpts; ++i) {
1393 if (Value.compare(getOptionValue(i)))
1396 outs() << "= " << getOption(i);
1397 size_t L = std::strlen(getOption(i));
1398 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1399 outs().indent(NumSpaces) << " (default: ";
1400 for (unsigned j = 0; j != NumOpts; ++j) {
1401 if (Default.compare(getOptionValue(j)))
1403 outs() << getOption(j);
1409 outs() << "= *unknown option value*\n";
1412 // printOptionDiff - Specializations for printing basic value types.
1414 #define PRINT_OPT_DIFF(T) \
1415 void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D, \
1416 size_t GlobalWidth) const { \
1417 printOptionName(O, GlobalWidth); \
1420 raw_string_ostream SS(Str); \
1423 outs() << "= " << Str; \
1424 size_t NumSpaces = \
1425 MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0; \
1426 outs().indent(NumSpaces) << " (default: "; \
1428 outs() << D.getValue(); \
1430 outs() << "*no default*"; \
1434 PRINT_OPT_DIFF(bool)
1435 PRINT_OPT_DIFF(boolOrDefault)
1437 PRINT_OPT_DIFF(unsigned)
1438 PRINT_OPT_DIFF(unsigned long long)
1439 PRINT_OPT_DIFF(double)
1440 PRINT_OPT_DIFF(float)
1441 PRINT_OPT_DIFF(char)
1443 void parser<std::string>::printOptionDiff(const Option &O, StringRef V,
1444 OptionValue<std::string> D,
1445 size_t GlobalWidth) const {
1446 printOptionName(O, GlobalWidth);
1447 outs() << "= " << V;
1448 size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
1449 outs().indent(NumSpaces) << " (default: ";
1451 outs() << D.getValue();
1453 outs() << "*no default*";
1457 // Print a placeholder for options that don't yet support printOptionDiff().
1458 void basic_parser_impl::printOptionNoValue(const Option &O,
1459 size_t GlobalWidth) const {
1460 printOptionName(O, GlobalWidth);
1461 outs() << "= *cannot print option value*\n";
1464 //===----------------------------------------------------------------------===//
1465 // -help and -help-hidden option implementation
1468 static int OptNameCompare(const void *LHS, const void *RHS) {
1469 typedef std::pair<const char *, Option *> pair_ty;
1471 return strcmp(((const pair_ty *)LHS)->first, ((const pair_ty *)RHS)->first);
1474 // Copy Options into a vector so we can sort them as we like.
1475 static void sortOpts(StringMap<Option *> &OptMap,
1476 SmallVectorImpl<std::pair<const char *, Option *>> &Opts,
1478 SmallPtrSet<Option *, 128> OptionSet; // Duplicate option detection.
1480 for (StringMap<Option *>::iterator I = OptMap.begin(), E = OptMap.end();
1482 // Ignore really-hidden options.
1483 if (I->second->getOptionHiddenFlag() == ReallyHidden)
1486 // Unless showhidden is set, ignore hidden flags.
1487 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
1490 // If we've already seen this option, don't add it to the list again.
1491 if (!OptionSet.insert(I->second).second)
1495 std::pair<const char *, Option *>(I->getKey().data(), I->second));
1498 // Sort the options list alphabetically.
1499 qsort(Opts.data(), Opts.size(), sizeof(Opts[0]), OptNameCompare);
1506 const bool ShowHidden;
1507 typedef SmallVector<std::pair<const char *, Option *>, 128>
1508 StrOptionPairVector;
1509 // Print the options. Opts is assumed to be alphabetically sorted.
1510 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1511 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1512 Opts[i].second->printOptionInfo(MaxArgLen);
1516 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
1517 virtual ~HelpPrinter() {}
1519 // Invoke the printer.
1520 void operator=(bool Value) {
1524 StrOptionPairVector Opts;
1525 sortOpts(GlobalParser->OptionsMap, Opts, ShowHidden);
1527 if (GlobalParser->ProgramOverview)
1528 outs() << "OVERVIEW: " << GlobalParser->ProgramOverview << "\n";
1530 outs() << "USAGE: " << GlobalParser->ProgramName << " [options]";
1532 for (auto Opt : GlobalParser->PositionalOpts) {
1534 outs() << " --" << Opt->ArgStr;
1535 outs() << " " << Opt->HelpStr;
1538 // Print the consume after option info if it exists...
1539 if (GlobalParser->ConsumeAfterOpt)
1540 outs() << " " << GlobalParser->ConsumeAfterOpt->HelpStr;
1544 // Compute the maximum argument length...
1545 size_t MaxArgLen = 0;
1546 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1547 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1549 outs() << "OPTIONS:\n";
1550 printOptions(Opts, MaxArgLen);
1552 // Print any extra help the user has declared.
1553 for (auto I : GlobalParser->MoreHelp)
1555 GlobalParser->MoreHelp.clear();
1557 // Halt the program since help information was printed
1562 class CategorizedHelpPrinter : public HelpPrinter {
1564 explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
1566 // Helper function for printOptions().
1567 // It shall return true if A's name should be lexographically
1568 // ordered before B's name. It returns false otherwise.
1569 static bool OptionCategoryCompare(OptionCategory *A, OptionCategory *B) {
1570 return strcmp(A->getName(), B->getName()) < 0;
1573 // Make sure we inherit our base class's operator=()
1574 using HelpPrinter::operator=;
1577 void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override {
1578 std::vector<OptionCategory *> SortedCategories;
1579 std::map<OptionCategory *, std::vector<Option *>> CategorizedOptions;
1581 // Collect registered option categories into vector in preparation for
1583 for (auto I = GlobalParser->RegisteredOptionCategories.begin(),
1584 E = GlobalParser->RegisteredOptionCategories.end();
1586 SortedCategories.push_back(*I);
1589 // Sort the different option categories alphabetically.
1590 assert(SortedCategories.size() > 0 && "No option categories registered!");
1591 std::sort(SortedCategories.begin(), SortedCategories.end(),
1592 OptionCategoryCompare);
1594 // Create map to empty vectors.
1595 for (std::vector<OptionCategory *>::const_iterator
1596 I = SortedCategories.begin(),
1597 E = SortedCategories.end();
1599 CategorizedOptions[*I] = std::vector<Option *>();
1601 // Walk through pre-sorted options and assign into categories.
1602 // Because the options are already alphabetically sorted the
1603 // options within categories will also be alphabetically sorted.
1604 for (size_t I = 0, E = Opts.size(); I != E; ++I) {
1605 Option *Opt = Opts[I].second;
1606 assert(CategorizedOptions.count(Opt->Category) > 0 &&
1607 "Option has an unregistered category");
1608 CategorizedOptions[Opt->Category].push_back(Opt);
1612 for (std::vector<OptionCategory *>::const_iterator
1613 Category = SortedCategories.begin(),
1614 E = SortedCategories.end();
1615 Category != E; ++Category) {
1616 // Hide empty categories for -help, but show for -help-hidden.
1617 bool IsEmptyCategory = CategorizedOptions[*Category].size() == 0;
1618 if (!ShowHidden && IsEmptyCategory)
1621 // Print category information.
1623 outs() << (*Category)->getName() << ":\n";
1625 // Check if description is set.
1626 if ((*Category)->getDescription() != nullptr)
1627 outs() << (*Category)->getDescription() << "\n\n";
1631 // When using -help-hidden explicitly state if the category has no
1632 // options associated with it.
1633 if (IsEmptyCategory) {
1634 outs() << " This option category has no options.\n";
1637 // Loop over the options in the category and print.
1638 for (std::vector<Option *>::const_iterator
1639 Opt = CategorizedOptions[*Category].begin(),
1640 E = CategorizedOptions[*Category].end();
1642 (*Opt)->printOptionInfo(MaxArgLen);
1647 // This wraps the Uncategorizing and Categorizing printers and decides
1648 // at run time which should be invoked.
1649 class HelpPrinterWrapper {
1651 HelpPrinter &UncategorizedPrinter;
1652 CategorizedHelpPrinter &CategorizedPrinter;
1655 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
1656 CategorizedHelpPrinter &CategorizedPrinter)
1657 : UncategorizedPrinter(UncategorizedPrinter),
1658 CategorizedPrinter(CategorizedPrinter) {}
1660 // Invoke the printer.
1661 void operator=(bool Value);
1664 } // End anonymous namespace
1666 // Declare the four HelpPrinter instances that are used to print out help, or
1667 // help-hidden as an uncategorized list or in categories.
1668 static HelpPrinter UncategorizedNormalPrinter(false);
1669 static HelpPrinter UncategorizedHiddenPrinter(true);
1670 static CategorizedHelpPrinter CategorizedNormalPrinter(false);
1671 static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
1673 // Declare HelpPrinter wrappers that will decide whether or not to invoke
1674 // a categorizing help printer
1675 static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
1676 CategorizedNormalPrinter);
1677 static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
1678 CategorizedHiddenPrinter);
1680 // Define a category for generic options that all tools should have.
1681 static cl::OptionCategory GenericCategory("Generic Options");
1683 // Define uncategorized help printers.
1684 // -help-list is hidden by default because if Option categories are being used
1685 // then -help behaves the same as -help-list.
1686 static cl::opt<HelpPrinter, true, parser<bool>> HLOp(
1688 cl::desc("Display list of available options (-help-list-hidden for more)"),
1689 cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed,
1690 cl::cat(GenericCategory));
1692 static cl::opt<HelpPrinter, true, parser<bool>>
1693 HLHOp("help-list-hidden", cl::desc("Display list of all available options"),
1694 cl::location(UncategorizedHiddenPrinter), cl::Hidden,
1695 cl::ValueDisallowed, cl::cat(GenericCategory));
1697 // Define uncategorized/categorized help printers. These printers change their
1698 // behaviour at runtime depending on whether one or more Option categories have
1700 static cl::opt<HelpPrinterWrapper, true, parser<bool>>
1701 HOp("help", cl::desc("Display available options (-help-hidden for more)"),
1702 cl::location(WrappedNormalPrinter), cl::ValueDisallowed,
1703 cl::cat(GenericCategory));
1705 static cl::opt<HelpPrinterWrapper, true, parser<bool>>
1706 HHOp("help-hidden", cl::desc("Display all available options"),
1707 cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed,
1708 cl::cat(GenericCategory));
1710 static cl::opt<bool> PrintOptions(
1712 cl::desc("Print non-default options after command line parsing"),
1713 cl::Hidden, cl::init(false), cl::cat(GenericCategory));
1715 static cl::opt<bool> PrintAllOptions(
1716 "print-all-options",
1717 cl::desc("Print all option values after command line parsing"), cl::Hidden,
1718 cl::init(false), cl::cat(GenericCategory));
1720 void HelpPrinterWrapper::operator=(bool Value) {
1724 // Decide which printer to invoke. If more than one option category is
1725 // registered then it is useful to show the categorized help instead of
1726 // uncategorized help.
1727 if (GlobalParser->RegisteredOptionCategories.size() > 1) {
1728 // unhide -help-list option so user can have uncategorized output if they
1730 HLOp.setHiddenFlag(NotHidden);
1732 CategorizedPrinter = true; // Invoke categorized printer
1734 UncategorizedPrinter = true; // Invoke uncategorized printer
1737 // Print the value of each option.
1738 void cl::PrintOptionValues() { GlobalParser->printOptionValues(); }
1740 void CommandLineParser::printOptionValues() {
1741 if (!PrintOptions && !PrintAllOptions)
1744 SmallVector<std::pair<const char *, Option *>, 128> Opts;
1745 sortOpts(OptionsMap, Opts, /*ShowHidden*/ true);
1747 // Compute the maximum argument length...
1748 size_t MaxArgLen = 0;
1749 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1750 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1752 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1753 Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
1756 static void (*OverrideVersionPrinter)() = nullptr;
1758 static std::vector<void (*)()> *ExtraVersionPrinters = nullptr;
1761 class VersionPrinter {
1764 raw_ostream &OS = outs();
1765 OS << "LLVM (http://llvm.org/):\n"
1766 << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
1767 #ifdef LLVM_VERSION_INFO
1768 OS << " " << LLVM_VERSION_INFO;
1771 #ifndef __OPTIMIZE__
1772 OS << "DEBUG build";
1774 OS << "Optimized build";
1777 OS << " with assertions";
1779 std::string CPU = sys::getHostCPUName();
1780 if (CPU == "generic")
1783 #if (ENABLE_TIMESTAMPS == 1)
1784 << " Built " << __DATE__ << " (" << __TIME__ << ").\n"
1786 << " Default target: " << sys::getDefaultTargetTriple() << '\n'
1787 << " Host CPU: " << CPU << '\n';
1789 void operator=(bool OptionWasSpecified) {
1790 if (!OptionWasSpecified)
1793 if (OverrideVersionPrinter != nullptr) {
1794 (*OverrideVersionPrinter)();
1799 // Iterate over any registered extra printers and call them to add further
1801 if (ExtraVersionPrinters != nullptr) {
1803 for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(),
1804 E = ExtraVersionPrinters->end();
1812 } // End anonymous namespace
1814 // Define the --version option that prints out the LLVM version for the tool
1815 static VersionPrinter VersionPrinterInstance;
1817 static cl::opt<VersionPrinter, true, parser<bool>>
1818 VersOp("version", cl::desc("Display the version of this program"),
1819 cl::location(VersionPrinterInstance), cl::ValueDisallowed,
1820 cl::cat(GenericCategory));
1822 // Utility function for printing the help message.
1823 void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
1824 // This looks weird, but it actually prints the help message. The Printers are
1825 // types of HelpPrinter and the help gets printed when its operator= is
1826 // invoked. That's because the "normal" usages of the help printer is to be
1827 // assigned true/false depending on whether -help or -help-hidden was given or
1828 // not. Since we're circumventing that we have to make it look like -help or
1829 // -help-hidden were given, so we assign true.
1831 if (!Hidden && !Categorized)
1832 UncategorizedNormalPrinter = true;
1833 else if (!Hidden && Categorized)
1834 CategorizedNormalPrinter = true;
1835 else if (Hidden && !Categorized)
1836 UncategorizedHiddenPrinter = true;
1838 CategorizedHiddenPrinter = true;
1841 /// Utility function for printing version number.
1842 void cl::PrintVersionMessage() { VersionPrinterInstance.print(); }
1844 void cl::SetVersionPrinter(void (*func)()) { OverrideVersionPrinter = func; }
1846 void cl::AddExtraVersionPrinter(void (*func)()) {
1847 if (!ExtraVersionPrinters)
1848 ExtraVersionPrinters = new std::vector<void (*)()>;
1850 ExtraVersionPrinters->push_back(func);
1853 StringMap<Option *> &cl::getRegisteredOptions() {
1854 return GlobalParser->OptionsMap;
1857 void cl::HideUnrelatedOptions(cl::OptionCategory &Category) {
1858 for (auto &I : GlobalParser->OptionsMap) {
1859 if (I.second->Category != &Category &&
1860 I.second->Category != &GenericCategory)
1861 I.second->setHiddenFlag(cl::ReallyHidden);
1865 void cl::HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories) {
1866 auto CategoriesBegin = Categories.begin();
1867 auto CategoriesEnd = Categories.end();
1868 for (auto &I : GlobalParser->OptionsMap) {
1869 if (std::find(CategoriesBegin, CategoriesEnd, I.second->Category) ==
1871 I.second->Category != &GenericCategory)
1872 I.second->setHiddenFlag(cl::ReallyHidden);
1876 void LLVMParseCommandLineOptions(int argc, const char *const *argv,
1877 const char *Overview) {
1878 llvm::cl::ParseCommandLineOptions(argc, argv, Overview);