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 //===----------------------------------------------------------------------===//
86 class CommandLineParser {
88 // Globals for name and overview of program. Program name is not a string to
89 // avoid static ctor/dtor issues.
90 std::string ProgramName;
91 const char *ProgramOverview;
93 // This collects additional help to be printed.
94 std::vector<const char *> MoreHelp;
96 SmallVector<Option *, 4> PositionalOpts;
97 SmallVector<Option *, 4> SinkOpts;
98 StringMap<Option *> OptionsMap;
100 Option *ConsumeAfterOpt; // The ConsumeAfter option if it exists.
102 CommandLineParser() : ProgramOverview(nullptr), ConsumeAfterOpt(nullptr) {}
104 void ParseCommandLineOptions(int argc, const char *const *argv,
105 const char *Overview);
107 void addLiteralOption(Option &Opt, const char *Name) {
108 if (!Opt.hasArgStr()) {
109 if (!OptionsMap.insert(std::make_pair(Name, &Opt)).second) {
110 errs() << ProgramName << ": CommandLine Error: Option '" << Name
111 << "' registered more than once!\n";
112 report_fatal_error("inconsistency in registered CommandLine options");
117 void addOption(Option *O) {
118 bool HadErrors = false;
120 // Add argument to the argument map!
121 if (!OptionsMap.insert(std::make_pair(O->ArgStr, O)).second) {
122 errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
123 << "' registered more than once!\n";
128 // Remember information about positional options.
129 if (O->getFormattingFlag() == cl::Positional)
130 PositionalOpts.push_back(O);
131 else if (O->getMiscFlags() & cl::Sink) // Remember sink options
132 SinkOpts.push_back(O);
133 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
134 if (ConsumeAfterOpt) {
135 O->error("Cannot specify more than one option with cl::ConsumeAfter!");
141 // Fail hard if there were errors. These are strictly unrecoverable and
142 // indicate serious issues such as conflicting option names or an
144 // linked LLVM distribution.
146 report_fatal_error("inconsistency in registered CommandLine options");
149 void removeOption(Option *O) {
150 SmallVector<const char *, 16> OptionNames;
151 O->getExtraOptionNames(OptionNames);
153 OptionNames.push_back(O->ArgStr);
154 for (auto Name : OptionNames)
155 OptionsMap.erase(StringRef(Name));
157 if (O->getFormattingFlag() == cl::Positional)
158 for (auto Opt = PositionalOpts.begin(); Opt != PositionalOpts.end();
161 PositionalOpts.erase(Opt);
165 else if (O->getMiscFlags() & cl::Sink)
166 for (auto Opt = SinkOpts.begin(); Opt != SinkOpts.end(); ++Opt) {
172 else if (O == ConsumeAfterOpt)
173 ConsumeAfterOpt = nullptr;
177 return (!OptionsMap.empty() || !PositionalOpts.empty() ||
178 nullptr != ConsumeAfterOpt);
181 void updateArgStr(Option *O, const char *NewName) {
182 if (!OptionsMap.insert(std::make_pair(NewName, O)).second) {
183 errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
184 << "' registered more than once!\n";
185 report_fatal_error("inconsistency in registered CommandLine options");
187 OptionsMap.erase(StringRef(O->ArgStr));
190 void printOptionValues();
193 static ManagedStatic<CommandLineParser> GlobalParser;
195 void cl::AddLiteralOption(Option &O, const char *Name) {
196 GlobalParser->addLiteralOption(O, Name);
199 extrahelp::extrahelp(const char *Help) : morehelp(Help) {
200 GlobalParser->MoreHelp.push_back(Help);
203 void Option::addArgument() {
204 GlobalParser->addOption(this);
205 FullyInitialized = true;
208 void Option::removeArgument() { GlobalParser->removeOption(this); }
210 void Option::setArgStr(const char *S) {
211 if (FullyInitialized)
212 GlobalParser->updateArgStr(this, S);
216 // This collects the different option categories that have been registered.
217 typedef SmallPtrSet<OptionCategory *, 16> OptionCatSet;
218 static ManagedStatic<OptionCatSet> RegisteredOptionCategories;
220 // Initialise the general option category.
221 OptionCategory llvm::cl::GeneralCategory("General options");
223 void OptionCategory::registerCategory() {
224 assert(std::count_if(RegisteredOptionCategories->begin(),
225 RegisteredOptionCategories->end(),
226 [this](const OptionCategory *Category) {
227 return getName() == Category->getName();
229 "Duplicate option categories");
231 RegisteredOptionCategories->insert(this);
234 //===----------------------------------------------------------------------===//
235 // Basic, shared command line option processing machinery.
238 /// LookupOption - Lookup the option specified by the specified option on the
239 /// command line. If there is a value specified (after an equal sign) return
240 /// that as well. This assumes that leading dashes have already been stripped.
241 static Option *LookupOption(StringRef &Arg, StringRef &Value,
242 const StringMap<Option *> &OptionsMap) {
243 // Reject all dashes.
247 size_t EqualPos = Arg.find('=');
249 // If we have an equals sign, remember the value.
250 if (EqualPos == StringRef::npos) {
251 // Look up the option.
252 StringMap<Option *>::const_iterator I = OptionsMap.find(Arg);
253 return I != OptionsMap.end() ? I->second : nullptr;
256 // If the argument before the = is a valid option name, we match. If not,
257 // return Arg unmolested.
258 StringMap<Option *>::const_iterator I =
259 OptionsMap.find(Arg.substr(0, EqualPos));
260 if (I == OptionsMap.end())
263 Value = Arg.substr(EqualPos + 1);
264 Arg = Arg.substr(0, EqualPos);
268 /// LookupNearestOption - Lookup the closest match to the option specified by
269 /// the specified option on the command line. If there is a value specified
270 /// (after an equal sign) return that as well. This assumes that leading dashes
271 /// have already been stripped.
272 static Option *LookupNearestOption(StringRef Arg,
273 const StringMap<Option *> &OptionsMap,
274 std::string &NearestString) {
275 // Reject all dashes.
279 // Split on any equal sign.
280 std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
281 StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
282 StringRef &RHS = SplitArg.second;
284 // Find the closest match.
285 Option *Best = nullptr;
286 unsigned BestDistance = 0;
287 for (StringMap<Option *>::const_iterator it = OptionsMap.begin(),
288 ie = OptionsMap.end();
290 Option *O = it->second;
291 SmallVector<const char *, 16> OptionNames;
292 O->getExtraOptionNames(OptionNames);
294 OptionNames.push_back(O->ArgStr);
296 bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
297 StringRef Flag = PermitValue ? LHS : Arg;
298 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
299 StringRef Name = OptionNames[i];
300 unsigned Distance = StringRef(Name).edit_distance(
301 Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
302 if (!Best || Distance < BestDistance) {
304 BestDistance = Distance;
305 if (RHS.empty() || !PermitValue)
306 NearestString = OptionNames[i];
308 NearestString = std::string(OptionNames[i]) + "=" + RHS.str();
316 /// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence()
317 /// that does special handling of cl::CommaSeparated options.
318 static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos,
319 StringRef ArgName, StringRef Value,
320 bool MultiArg = false) {
321 // Check to see if this option accepts a comma separated list of values. If
322 // it does, we have to split up the value into multiple values.
323 if (Handler->getMiscFlags() & CommaSeparated) {
324 StringRef Val(Value);
325 StringRef::size_type Pos = Val.find(',');
327 while (Pos != StringRef::npos) {
328 // Process the portion before the comma.
329 if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
331 // Erase the portion before the comma, AND the comma.
332 Val = Val.substr(Pos + 1);
333 Value.substr(Pos + 1); // Increment the original value pointer as well.
334 // Check for another comma.
341 if (Handler->addOccurrence(pos, ArgName, Value, MultiArg))
347 /// ProvideOption - For Value, this differentiates between an empty value ("")
348 /// and a null value (StringRef()). The later is accepted for arguments that
349 /// don't allow a value (-foo) the former is rejected (-foo=).
350 static inline bool ProvideOption(Option *Handler, StringRef ArgName,
351 StringRef Value, int argc,
352 const char *const *argv, int &i) {
353 // Is this a multi-argument option?
354 unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
356 // Enforce value requirements
357 switch (Handler->getValueExpectedFlag()) {
359 if (!Value.data()) { // No value specified?
361 return Handler->error("requires a value!");
362 // Steal the next argument, like for '-o filename'
363 assert(argv && "null check");
367 case ValueDisallowed:
368 if (NumAdditionalVals > 0)
369 return Handler->error("multi-valued option specified"
370 " with ValueDisallowed modifier!");
373 return Handler->error("does not allow a value! '" + Twine(Value) +
380 // If this isn't a multi-arg option, just run the handler.
381 if (NumAdditionalVals == 0)
382 return CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value);
384 // If it is, run the handle several times.
385 bool MultiArg = false;
388 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
394 while (NumAdditionalVals > 0) {
396 return Handler->error("not enough values!");
397 assert(argv && "null check");
400 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
408 static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
410 return ProvideOption(Handler, Handler->ArgStr, Arg, 0, nullptr, Dummy);
413 // Option predicates...
414 static inline bool isGrouping(const Option *O) {
415 return O->getFormattingFlag() == cl::Grouping;
417 static inline bool isPrefixedOrGrouping(const Option *O) {
418 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
421 // getOptionPred - Check to see if there are any options that satisfy the
422 // specified predicate with names that are the prefixes in Name. This is
423 // checked by progressively stripping characters off of the name, checking to
424 // see if there options that satisfy the predicate. If we find one, return it,
425 // otherwise return null.
427 static Option *getOptionPred(StringRef Name, size_t &Length,
428 bool (*Pred)(const Option *),
429 const StringMap<Option *> &OptionsMap) {
431 StringMap<Option *>::const_iterator OMI = OptionsMap.find(Name);
433 // Loop while we haven't found an option and Name still has at least two
434 // characters in it (so that the next iteration will not be the empty
436 while (OMI == OptionsMap.end() && Name.size() > 1) {
437 Name = Name.substr(0, Name.size() - 1); // Chop off the last character.
438 OMI = OptionsMap.find(Name);
441 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
442 Length = Name.size();
443 return OMI->second; // Found one!
445 return nullptr; // No option found!
448 /// HandlePrefixedOrGroupedOption - The specified argument string (which started
449 /// with at least one '-') does not fully match an available option. Check to
450 /// see if this is a prefix or grouped option. If so, split arg into output an
451 /// Arg/Value pair and return the Option to parse it with.
453 HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
455 const StringMap<Option *> &OptionsMap) {
461 Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
465 // If the option is a prefixed option, then the value is simply the
466 // rest of the name... so fall through to later processing, by
467 // setting up the argument name flags and value fields.
468 if (PGOpt->getFormattingFlag() == cl::Prefix) {
469 Value = Arg.substr(Length);
470 Arg = Arg.substr(0, Length);
471 assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
475 // This must be a grouped option... handle them now. Grouping options can't
477 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
480 // Move current arg name out of Arg into OneArgName.
481 StringRef OneArgName = Arg.substr(0, Length);
482 Arg = Arg.substr(Length);
484 // Because ValueRequired is an invalid flag for grouped arguments,
485 // we don't need to pass argc/argv in.
486 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
487 "Option can not be cl::Grouping AND cl::ValueRequired!");
490 ProvideOption(PGOpt, OneArgName, StringRef(), 0, nullptr, Dummy);
492 // Get the next grouping option.
493 PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
494 } while (PGOpt && Length != Arg.size());
496 // Return the last option with Arg cut down to just the last one.
500 static bool RequiresValue(const Option *O) {
501 return O->getNumOccurrencesFlag() == cl::Required ||
502 O->getNumOccurrencesFlag() == cl::OneOrMore;
505 static bool EatsUnboundedNumberOfValues(const Option *O) {
506 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
507 O->getNumOccurrencesFlag() == cl::OneOrMore;
510 static bool isWhitespace(char C) { return strchr(" \t\n\r\f\v", C); }
512 static bool isQuote(char C) { return C == '\"' || C == '\''; }
514 static bool isGNUSpecial(char C) { return strchr("\\\"\' ", C); }
516 void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
517 SmallVectorImpl<const char *> &NewArgv,
519 SmallString<128> Token;
520 for (size_t I = 0, E = Src.size(); I != E; ++I) {
521 // Consume runs of whitespace.
523 while (I != E && isWhitespace(Src[I])) {
524 // Mark the end of lines in response files
525 if (MarkEOLs && Src[I] == '\n')
526 NewArgv.push_back(nullptr);
533 // Backslashes can escape backslashes, spaces, and other quotes. Otherwise
534 // they are literal. This makes it much easier to read Windows file paths.
535 if (I + 1 < E && Src[I] == '\\' && isGNUSpecial(Src[I + 1])) {
536 ++I; // Skip the escape.
537 Token.push_back(Src[I]);
541 // Consume a quoted string.
542 if (isQuote(Src[I])) {
543 char Quote = Src[I++];
544 while (I != E && Src[I] != Quote) {
545 // Backslashes are literal, unless they escape a special character.
546 if (Src[I] == '\\' && I + 1 != E && isGNUSpecial(Src[I + 1]))
548 Token.push_back(Src[I]);
556 // End the token if this is whitespace.
557 if (isWhitespace(Src[I])) {
559 NewArgv.push_back(Saver.SaveString(Token.c_str()));
564 // This is a normal character. Append it.
565 Token.push_back(Src[I]);
568 // Append the last token after hitting EOF with no whitespace.
570 NewArgv.push_back(Saver.SaveString(Token.c_str()));
571 // Mark the end of response files
573 NewArgv.push_back(nullptr);
576 /// Backslashes are interpreted in a rather complicated way in the Windows-style
577 /// command line, because backslashes are used both to separate path and to
578 /// escape double quote. This method consumes runs of backslashes as well as the
579 /// following double quote if it's escaped.
581 /// * If an even number of backslashes is followed by a double quote, one
582 /// backslash is output for every pair of backslashes, and the last double
583 /// quote remains unconsumed. The double quote will later be interpreted as
584 /// the start or end of a quoted string in the main loop outside of this
587 /// * If an odd number of backslashes is followed by a double quote, one
588 /// backslash is output for every pair of backslashes, and a double quote is
589 /// output for the last pair of backslash-double quote. The double quote is
590 /// consumed in this case.
592 /// * Otherwise, backslashes are interpreted literally.
593 static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
594 size_t E = Src.size();
595 int BackslashCount = 0;
596 // Skip the backslashes.
600 } while (I != E && Src[I] == '\\');
602 bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
603 if (FollowedByDoubleQuote) {
604 Token.append(BackslashCount / 2, '\\');
605 if (BackslashCount % 2 == 0)
607 Token.push_back('"');
610 Token.append(BackslashCount, '\\');
614 void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
615 SmallVectorImpl<const char *> &NewArgv,
617 SmallString<128> Token;
619 // This is a small state machine to consume characters until it reaches the
620 // end of the source string.
621 enum { INIT, UNQUOTED, QUOTED } State = INIT;
622 for (size_t I = 0, E = Src.size(); I != E; ++I) {
623 // INIT state indicates that the current input index is at the start of
624 // the string or between tokens.
626 if (isWhitespace(Src[I])) {
627 // Mark the end of lines in response files
628 if (MarkEOLs && Src[I] == '\n')
629 NewArgv.push_back(nullptr);
636 if (Src[I] == '\\') {
637 I = parseBackslash(Src, I, Token);
641 Token.push_back(Src[I]);
646 // UNQUOTED state means that it's reading a token not quoted by double
648 if (State == UNQUOTED) {
649 // Whitespace means the end of the token.
650 if (isWhitespace(Src[I])) {
651 NewArgv.push_back(Saver.SaveString(Token.c_str()));
654 // Mark the end of lines in response files
655 if (MarkEOLs && Src[I] == '\n')
656 NewArgv.push_back(nullptr);
663 if (Src[I] == '\\') {
664 I = parseBackslash(Src, I, Token);
667 Token.push_back(Src[I]);
671 // QUOTED state means that it's reading a token quoted by double quotes.
672 if (State == QUOTED) {
677 if (Src[I] == '\\') {
678 I = parseBackslash(Src, I, Token);
681 Token.push_back(Src[I]);
684 // Append the last token after hitting EOF with no whitespace.
686 NewArgv.push_back(Saver.SaveString(Token.c_str()));
687 // Mark the end of response files
689 NewArgv.push_back(nullptr);
692 // It is called byte order marker but the UTF-8 BOM is actually not affected
693 // by the host system's endianness.
694 static bool hasUTF8ByteOrderMark(ArrayRef<char> S) {
695 return (S.size() >= 3 &&
696 S[0] == '\xef' && S[1] == '\xbb' && S[2] == '\xbf');
699 static bool ExpandResponseFile(const char *FName, StringSaver &Saver,
700 TokenizerCallback Tokenizer,
701 SmallVectorImpl<const char *> &NewArgv,
702 bool MarkEOLs = false) {
703 ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
704 MemoryBuffer::getFile(FName);
707 MemoryBuffer &MemBuf = *MemBufOrErr.get();
708 StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize());
710 // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
711 ArrayRef<char> BufRef(MemBuf.getBufferStart(), MemBuf.getBufferEnd());
713 if (hasUTF16ByteOrderMark(BufRef)) {
714 if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
716 Str = StringRef(UTF8Buf);
718 // If we see UTF-8 BOM sequence at the beginning of a file, we shall remove
719 // these bytes before parsing.
720 // Reference: http://en.wikipedia.org/wiki/UTF-8#Byte_order_mark
721 else if (hasUTF8ByteOrderMark(BufRef))
722 Str = StringRef(BufRef.data() + 3, BufRef.size() - 3);
724 // Tokenize the contents into NewArgv.
725 Tokenizer(Str, Saver, NewArgv, MarkEOLs);
730 /// \brief Expand response files on a command line recursively using the given
731 /// StringSaver and tokenization strategy.
732 bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
733 SmallVectorImpl<const char *> &Argv,
735 unsigned RspFiles = 0;
736 bool AllExpanded = true;
738 // Don't cache Argv.size() because it can change.
739 for (unsigned I = 0; I != Argv.size();) {
740 const char *Arg = Argv[I];
741 // Check if it is an EOL marker
742 if (Arg == nullptr) {
751 // If we have too many response files, leave some unexpanded. This avoids
752 // crashing on self-referential response files.
756 // Replace this response file argument with the tokenization of its
757 // contents. Nested response files are expanded in subsequent iterations.
758 // FIXME: If a nested response file uses a relative path, is it relative to
759 // the cwd of the process or the response file?
760 SmallVector<const char *, 0> ExpandedArgv;
761 if (!ExpandResponseFile(Arg + 1, Saver, Tokenizer, ExpandedArgv,
763 // We couldn't read this file, so we leave it in the argument stream and
769 Argv.erase(Argv.begin() + I);
770 Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
776 class StrDupSaver : public StringSaver {
777 std::vector<char *> Dups;
781 for (std::vector<char *>::iterator I = Dups.begin(), E = Dups.end(); I != E;
787 const char *SaveString(const char *Str) override {
788 char *Dup = strdup(Str);
795 /// ParseEnvironmentOptions - An alternative entry point to the
796 /// CommandLine library, which allows you to read the program's name
797 /// from the caller (as PROGNAME) and its command-line arguments from
798 /// an environment variable (whose name is given in ENVVAR).
800 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
801 const char *Overview) {
803 assert(progName && "Program name not specified");
804 assert(envVar && "Environment variable name missing");
806 // Get the environment variable they want us to parse options out of.
807 const char *envValue = getenv(envVar);
811 // Get program's "name", which we wouldn't know without the caller
813 SmallVector<const char *, 20> newArgv;
815 newArgv.push_back(Saver.SaveString(progName));
817 // Parse the value of the environment variable into a "command line"
818 // and hand it off to ParseCommandLineOptions().
819 TokenizeGNUCommandLine(envValue, Saver, newArgv);
820 int newArgc = static_cast<int>(newArgv.size());
821 ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
824 void cl::ParseCommandLineOptions(int argc, const char *const *argv,
825 const char *Overview) {
826 GlobalParser->ParseCommandLineOptions(argc, argv, Overview);
829 void CommandLineParser::ParseCommandLineOptions(int argc,
830 const char *const *argv,
831 const char *Overview) {
832 assert(hasOptions() && "No options specified!");
834 // Expand response files.
835 SmallVector<const char *, 20> newArgv;
836 for (int i = 0; i != argc; ++i)
837 newArgv.push_back(argv[i]);
839 ExpandResponseFiles(Saver, TokenizeGNUCommandLine, newArgv);
841 argc = static_cast<int>(newArgv.size());
843 // Copy the program name into ProgName, making sure not to overflow it.
844 ProgramName = sys::path::filename(argv[0]);
846 ProgramOverview = Overview;
847 bool ErrorParsing = false;
849 // Check out the positional arguments to collect information about them.
850 unsigned NumPositionalRequired = 0;
852 // Determine whether or not there are an unlimited number of positionals
853 bool HasUnlimitedPositionals = false;
855 if (ConsumeAfterOpt) {
856 assert(PositionalOpts.size() > 0 &&
857 "Cannot specify cl::ConsumeAfter without a positional argument!");
859 if (!PositionalOpts.empty()) {
861 // Calculate how many positional values are _required_.
862 bool UnboundedFound = false;
863 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
864 Option *Opt = PositionalOpts[i];
865 if (RequiresValue(Opt))
866 ++NumPositionalRequired;
867 else if (ConsumeAfterOpt) {
868 // ConsumeAfter cannot be combined with "optional" positional options
869 // unless there is only one positional argument...
870 if (PositionalOpts.size() > 1)
871 ErrorParsing |= Opt->error(
872 "error - this positional option will never be matched, "
873 "because it does not Require a value, and a "
874 "cl::ConsumeAfter option is active!");
875 } else if (UnboundedFound && !Opt->ArgStr[0]) {
876 // This option does not "require" a value... Make sure this option is
877 // not specified after an option that eats all extra arguments, or this
878 // one will never get any!
880 ErrorParsing |= Opt->error("error - option can never match, because "
881 "another positional argument will match an "
882 "unbounded number of values, and this option"
883 " does not require a value!");
884 errs() << ProgramName << ": CommandLine Error: Option '" << Opt->ArgStr
885 << "' is all messed up!\n";
886 errs() << PositionalOpts.size();
888 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
890 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
893 // PositionalVals - A vector of "positional" arguments we accumulate into
894 // the process at the end.
896 SmallVector<std::pair<StringRef, unsigned>, 4> PositionalVals;
898 // If the program has named positional arguments, and the name has been run
899 // across, keep track of which positional argument was named. Otherwise put
900 // the positional args into the PositionalVals list...
901 Option *ActivePositionalArg = nullptr;
903 // Loop over all of the arguments... processing them.
904 bool DashDashFound = false; // Have we read '--'?
905 for (int i = 1; i < argc; ++i) {
906 Option *Handler = nullptr;
907 Option *NearestHandler = nullptr;
908 std::string NearestHandlerString;
910 StringRef ArgName = "";
912 // Check to see if this is a positional argument. This argument is
913 // considered to be positional if it doesn't start with '-', if it is "-"
914 // itself, or if we have seen "--" already.
916 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
917 // Positional argument!
918 if (ActivePositionalArg) {
919 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
920 continue; // We are done!
923 if (!PositionalOpts.empty()) {
924 PositionalVals.push_back(std::make_pair(argv[i], i));
926 // All of the positional arguments have been fulfulled, give the rest to
927 // the consume after option... if it's specified...
929 if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) {
930 for (++i; i < argc; ++i)
931 PositionalVals.push_back(std::make_pair(argv[i], i));
932 break; // Handle outside of the argument processing loop...
935 // Delay processing positional arguments until the end...
938 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
940 DashDashFound = true; // This is the mythical "--"?
941 continue; // Don't try to process it as an argument itself.
942 } else if (ActivePositionalArg &&
943 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
944 // If there is a positional argument eating options, check to see if this
945 // option is another positional argument. If so, treat it as an argument,
946 // otherwise feed it to the eating positional.
947 ArgName = argv[i] + 1;
948 // Eat leading dashes.
949 while (!ArgName.empty() && ArgName[0] == '-')
950 ArgName = ArgName.substr(1);
952 Handler = LookupOption(ArgName, Value, OptionsMap);
953 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
954 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
955 continue; // We are done!
958 } else { // We start with a '-', must be an argument.
959 ArgName = argv[i] + 1;
960 // Eat leading dashes.
961 while (!ArgName.empty() && ArgName[0] == '-')
962 ArgName = ArgName.substr(1);
964 Handler = LookupOption(ArgName, Value, OptionsMap);
966 // Check to see if this "option" is really a prefixed or grouped argument.
968 Handler = HandlePrefixedOrGroupedOption(ArgName, Value, ErrorParsing,
971 // Otherwise, look for the closest available option to report to the user
972 // in the upcoming error.
973 if (!Handler && SinkOpts.empty())
975 LookupNearestOption(ArgName, OptionsMap, NearestHandlerString);
979 if (SinkOpts.empty()) {
980 errs() << ProgramName << ": Unknown command line argument '" << argv[i]
981 << "'. Try: '" << argv[0] << " -help'\n";
983 if (NearestHandler) {
984 // If we know a near match, report it as well.
985 errs() << ProgramName << ": Did you mean '-" << NearestHandlerString
991 for (SmallVectorImpl<Option *>::iterator I = SinkOpts.begin(),
994 (*I)->addOccurrence(i, "", argv[i]);
999 // If this is a named positional argument, just remember that it is the
1001 if (Handler->getFormattingFlag() == cl::Positional)
1002 ActivePositionalArg = Handler;
1004 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
1007 // Check and handle positional arguments now...
1008 if (NumPositionalRequired > PositionalVals.size()) {
1009 errs() << ProgramName
1010 << ": Not enough positional command line arguments specified!\n"
1011 << "Must specify at least " << NumPositionalRequired
1012 << " positional arguments: See: " << argv[0] << " -help\n";
1014 ErrorParsing = true;
1015 } else if (!HasUnlimitedPositionals &&
1016 PositionalVals.size() > PositionalOpts.size()) {
1017 errs() << ProgramName << ": Too many positional arguments specified!\n"
1018 << "Can specify at most " << PositionalOpts.size()
1019 << " positional arguments: See: " << argv[0] << " -help\n";
1020 ErrorParsing = true;
1022 } else if (!ConsumeAfterOpt) {
1023 // Positional args have already been handled if ConsumeAfter is specified.
1024 unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
1025 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
1026 if (RequiresValue(PositionalOpts[i])) {
1027 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
1028 PositionalVals[ValNo].second);
1030 --NumPositionalRequired; // We fulfilled our duty...
1033 // If we _can_ give this option more arguments, do so now, as long as we
1034 // do not give it values that others need. 'Done' controls whether the
1035 // option even _WANTS_ any more.
1037 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
1038 while (NumVals - ValNo > NumPositionalRequired && !Done) {
1039 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
1041 Done = true; // Optional arguments want _at most_ one value
1043 case cl::ZeroOrMore: // Zero or more will take all they can get...
1044 case cl::OneOrMore: // One or more will take all they can get...
1045 ProvidePositionalOption(PositionalOpts[i],
1046 PositionalVals[ValNo].first,
1047 PositionalVals[ValNo].second);
1051 llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
1052 "positional argument processing!");
1057 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
1059 for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
1060 if (RequiresValue(PositionalOpts[j])) {
1061 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
1062 PositionalVals[ValNo].first,
1063 PositionalVals[ValNo].second);
1067 // Handle the case where there is just one positional option, and it's
1068 // optional. In this case, we want to give JUST THE FIRST option to the
1069 // positional option and keep the rest for the consume after. The above
1070 // loop would have assigned no values to positional options in this case.
1072 if (PositionalOpts.size() == 1 && ValNo == 0 && !PositionalVals.empty()) {
1073 ErrorParsing |= ProvidePositionalOption(PositionalOpts[0],
1074 PositionalVals[ValNo].first,
1075 PositionalVals[ValNo].second);
1079 // Handle over all of the rest of the arguments to the
1080 // cl::ConsumeAfter command line option...
1081 for (; ValNo != PositionalVals.size(); ++ValNo)
1083 ProvidePositionalOption(ConsumeAfterOpt, PositionalVals[ValNo].first,
1084 PositionalVals[ValNo].second);
1087 // Loop over args and make sure all required args are specified!
1088 for (const auto &Opt : OptionsMap) {
1089 switch (Opt.second->getNumOccurrencesFlag()) {
1092 if (Opt.second->getNumOccurrences() == 0) {
1093 Opt.second->error("must be specified at least once!");
1094 ErrorParsing = true;
1102 // Now that we know if -debug is specified, we can use it.
1103 // Note that if ReadResponseFiles == true, this must be done before the
1104 // memory allocated for the expanded command line is free()d below.
1105 DEBUG(dbgs() << "Args: ";
1106 for (int i = 0; i < argc; ++i) dbgs() << argv[i] << ' ';
1109 // Free all of the memory allocated to the map. Command line options may only
1110 // be processed once!
1113 // If we had an error processing our arguments, don't let the program execute
1118 //===----------------------------------------------------------------------===//
1119 // Option Base class implementation
1122 bool Option::error(const Twine &Message, StringRef ArgName) {
1123 if (!ArgName.data())
1125 if (ArgName.empty())
1126 errs() << HelpStr; // Be nice for positional arguments
1128 errs() << GlobalParser->ProgramName << ": for the -" << ArgName;
1130 errs() << " option: " << Message << "\n";
1134 bool Option::addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
1137 NumOccurrences++; // Increment the number of times we have been seen
1139 switch (getNumOccurrencesFlag()) {
1141 if (NumOccurrences > 1)
1142 return error("may only occur zero or one times!", ArgName);
1145 if (NumOccurrences > 1)
1146 return error("must occur exactly one time!", ArgName);
1154 return handleOccurrence(pos, ArgName, Value);
1157 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
1158 // has been specified yet.
1160 static const char *getValueStr(const Option &O, const char *DefaultMsg) {
1161 if (O.ValueStr[0] == 0)
1166 //===----------------------------------------------------------------------===//
1167 // cl::alias class implementation
1170 // Return the width of the option tag for printing...
1171 size_t alias::getOptionWidth() const { return std::strlen(ArgStr) + 6; }
1173 static void printHelpStr(StringRef HelpStr, size_t Indent,
1174 size_t FirstLineIndentedBy) {
1175 std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1176 outs().indent(Indent - FirstLineIndentedBy) << " - " << Split.first << "\n";
1177 while (!Split.second.empty()) {
1178 Split = Split.second.split('\n');
1179 outs().indent(Indent) << Split.first << "\n";
1183 // Print out the option for the alias.
1184 void alias::printOptionInfo(size_t GlobalWidth) const {
1185 outs() << " -" << ArgStr;
1186 printHelpStr(HelpStr, GlobalWidth, std::strlen(ArgStr) + 6);
1189 //===----------------------------------------------------------------------===//
1190 // Parser Implementation code...
1193 // basic_parser implementation
1196 // Return the width of the option tag for printing...
1197 size_t basic_parser_impl::getOptionWidth(const Option &O) const {
1198 size_t Len = std::strlen(O.ArgStr);
1199 if (const char *ValName = getValueName())
1200 Len += std::strlen(getValueStr(O, ValName)) + 3;
1205 // printOptionInfo - Print out information about this option. The
1206 // to-be-maintained width is specified.
1208 void basic_parser_impl::printOptionInfo(const Option &O,
1209 size_t GlobalWidth) const {
1210 outs() << " -" << O.ArgStr;
1212 if (const char *ValName = getValueName())
1213 outs() << "=<" << getValueStr(O, ValName) << '>';
1215 printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
1218 void basic_parser_impl::printOptionName(const Option &O,
1219 size_t GlobalWidth) const {
1220 outs() << " -" << O.ArgStr;
1221 outs().indent(GlobalWidth - std::strlen(O.ArgStr));
1224 // parser<bool> implementation
1226 bool parser<bool>::parse(Option &O, StringRef ArgName, StringRef Arg,
1228 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1234 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1238 return O.error("'" + Arg +
1239 "' is invalid value for boolean argument! Try 0 or 1");
1242 // parser<boolOrDefault> implementation
1244 bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName, StringRef Arg,
1245 boolOrDefault &Value) {
1246 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1251 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1256 return O.error("'" + Arg +
1257 "' is invalid value for boolean argument! Try 0 or 1");
1260 // parser<int> implementation
1262 bool parser<int>::parse(Option &O, StringRef ArgName, StringRef Arg,
1264 if (Arg.getAsInteger(0, Value))
1265 return O.error("'" + Arg + "' value invalid for integer argument!");
1269 // parser<unsigned> implementation
1271 bool parser<unsigned>::parse(Option &O, StringRef ArgName, StringRef Arg,
1274 if (Arg.getAsInteger(0, Value))
1275 return O.error("'" + Arg + "' value invalid for uint argument!");
1279 // parser<unsigned long long> implementation
1281 bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
1283 unsigned long long &Value) {
1285 if (Arg.getAsInteger(0, Value))
1286 return O.error("'" + Arg + "' value invalid for uint argument!");
1290 // parser<double>/parser<float> implementation
1292 static bool parseDouble(Option &O, StringRef Arg, double &Value) {
1293 SmallString<32> TmpStr(Arg.begin(), Arg.end());
1294 const char *ArgStart = TmpStr.c_str();
1296 Value = strtod(ArgStart, &End);
1298 return O.error("'" + Arg + "' value invalid for floating point argument!");
1302 bool parser<double>::parse(Option &O, StringRef ArgName, StringRef Arg,
1304 return parseDouble(O, Arg, Val);
1307 bool parser<float>::parse(Option &O, StringRef ArgName, StringRef Arg,
1310 if (parseDouble(O, Arg, dVal))
1316 // generic_parser_base implementation
1319 // findOption - Return the option number corresponding to the specified
1320 // argument string. If the option is not found, getNumOptions() is returned.
1322 unsigned generic_parser_base::findOption(const char *Name) {
1323 unsigned e = getNumOptions();
1325 for (unsigned i = 0; i != e; ++i) {
1326 if (strcmp(getOption(i), Name) == 0)
1332 // Return the width of the option tag for printing...
1333 size_t generic_parser_base::getOptionWidth(const Option &O) const {
1334 if (O.hasArgStr()) {
1335 size_t Size = std::strlen(O.ArgStr) + 6;
1336 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1337 Size = std::max(Size, std::strlen(getOption(i)) + 8);
1340 size_t BaseSize = 0;
1341 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1342 BaseSize = std::max(BaseSize, std::strlen(getOption(i)) + 8);
1347 // printOptionInfo - Print out information about this option. The
1348 // to-be-maintained width is specified.
1350 void generic_parser_base::printOptionInfo(const Option &O,
1351 size_t GlobalWidth) const {
1352 if (O.hasArgStr()) {
1353 outs() << " -" << O.ArgStr;
1354 printHelpStr(O.HelpStr, GlobalWidth, std::strlen(O.ArgStr) + 6);
1356 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1357 size_t NumSpaces = GlobalWidth - strlen(getOption(i)) - 8;
1358 outs() << " =" << getOption(i);
1359 outs().indent(NumSpaces) << " - " << getDescription(i) << '\n';
1363 outs() << " " << O.HelpStr << '\n';
1364 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1365 const char *Option = getOption(i);
1366 outs() << " -" << Option;
1367 printHelpStr(getDescription(i), GlobalWidth, std::strlen(Option) + 8);
1372 static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1374 // printGenericOptionDiff - Print the value of this option and it's default.
1376 // "Generic" options have each value mapped to a name.
1377 void generic_parser_base::printGenericOptionDiff(
1378 const Option &O, const GenericOptionValue &Value,
1379 const GenericOptionValue &Default, size_t GlobalWidth) const {
1380 outs() << " -" << O.ArgStr;
1381 outs().indent(GlobalWidth - std::strlen(O.ArgStr));
1383 unsigned NumOpts = getNumOptions();
1384 for (unsigned i = 0; i != NumOpts; ++i) {
1385 if (Value.compare(getOptionValue(i)))
1388 outs() << "= " << getOption(i);
1389 size_t L = std::strlen(getOption(i));
1390 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1391 outs().indent(NumSpaces) << " (default: ";
1392 for (unsigned j = 0; j != NumOpts; ++j) {
1393 if (Default.compare(getOptionValue(j)))
1395 outs() << getOption(j);
1401 outs() << "= *unknown option value*\n";
1404 // printOptionDiff - Specializations for printing basic value types.
1406 #define PRINT_OPT_DIFF(T) \
1407 void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D, \
1408 size_t GlobalWidth) const { \
1409 printOptionName(O, GlobalWidth); \
1412 raw_string_ostream SS(Str); \
1415 outs() << "= " << Str; \
1416 size_t NumSpaces = \
1417 MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0; \
1418 outs().indent(NumSpaces) << " (default: "; \
1420 outs() << D.getValue(); \
1422 outs() << "*no default*"; \
1426 PRINT_OPT_DIFF(bool)
1427 PRINT_OPT_DIFF(boolOrDefault)
1429 PRINT_OPT_DIFF(unsigned)
1430 PRINT_OPT_DIFF(unsigned long long)
1431 PRINT_OPT_DIFF(double)
1432 PRINT_OPT_DIFF(float)
1433 PRINT_OPT_DIFF(char)
1435 void parser<std::string>::printOptionDiff(const Option &O, StringRef V,
1436 OptionValue<std::string> D,
1437 size_t GlobalWidth) const {
1438 printOptionName(O, GlobalWidth);
1439 outs() << "= " << V;
1440 size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
1441 outs().indent(NumSpaces) << " (default: ";
1443 outs() << D.getValue();
1445 outs() << "*no default*";
1449 // Print a placeholder for options that don't yet support printOptionDiff().
1450 void basic_parser_impl::printOptionNoValue(const Option &O,
1451 size_t GlobalWidth) const {
1452 printOptionName(O, GlobalWidth);
1453 outs() << "= *cannot print option value*\n";
1456 //===----------------------------------------------------------------------===//
1457 // -help and -help-hidden option implementation
1460 static int OptNameCompare(const void *LHS, const void *RHS) {
1461 typedef std::pair<const char *, Option *> pair_ty;
1463 return strcmp(((const pair_ty *)LHS)->first, ((const pair_ty *)RHS)->first);
1466 // Copy Options into a vector so we can sort them as we like.
1467 static void sortOpts(StringMap<Option *> &OptMap,
1468 SmallVectorImpl<std::pair<const char *, Option *>> &Opts,
1470 SmallPtrSet<Option *, 128> OptionSet; // Duplicate option detection.
1472 for (StringMap<Option *>::iterator I = OptMap.begin(), E = OptMap.end();
1474 // Ignore really-hidden options.
1475 if (I->second->getOptionHiddenFlag() == ReallyHidden)
1478 // Unless showhidden is set, ignore hidden flags.
1479 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
1482 // If we've already seen this option, don't add it to the list again.
1483 if (!OptionSet.insert(I->second).second)
1487 std::pair<const char *, Option *>(I->getKey().data(), I->second));
1490 // Sort the options list alphabetically.
1491 qsort(Opts.data(), Opts.size(), sizeof(Opts[0]), OptNameCompare);
1498 const bool ShowHidden;
1499 typedef SmallVector<std::pair<const char *, Option *>, 128>
1500 StrOptionPairVector;
1501 // Print the options. Opts is assumed to be alphabetically sorted.
1502 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1503 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1504 Opts[i].second->printOptionInfo(MaxArgLen);
1508 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
1509 virtual ~HelpPrinter() {}
1511 // Invoke the printer.
1512 void operator=(bool Value) {
1516 StrOptionPairVector Opts;
1517 sortOpts(GlobalParser->OptionsMap, Opts, ShowHidden);
1519 if (GlobalParser->ProgramOverview)
1520 outs() << "OVERVIEW: " << GlobalParser->ProgramOverview << "\n";
1522 outs() << "USAGE: " << GlobalParser->ProgramName << " [options]";
1524 for (auto Opt : GlobalParser->PositionalOpts) {
1526 outs() << " --" << Opt->ArgStr;
1527 outs() << " " << Opt->HelpStr;
1530 // Print the consume after option info if it exists...
1531 if (GlobalParser->ConsumeAfterOpt)
1532 outs() << " " << GlobalParser->ConsumeAfterOpt->HelpStr;
1536 // Compute the maximum argument length...
1537 size_t MaxArgLen = 0;
1538 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1539 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1541 outs() << "OPTIONS:\n";
1542 printOptions(Opts, MaxArgLen);
1544 // Print any extra help the user has declared.
1545 for (auto I : GlobalParser->MoreHelp)
1547 GlobalParser->MoreHelp.clear();
1549 // Halt the program since help information was printed
1554 class CategorizedHelpPrinter : public HelpPrinter {
1556 explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
1558 // Helper function for printOptions().
1559 // It shall return true if A's name should be lexographically
1560 // ordered before B's name. It returns false otherwise.
1561 static bool OptionCategoryCompare(OptionCategory *A, OptionCategory *B) {
1562 return strcmp(A->getName(), B->getName()) < 0;
1565 // Make sure we inherit our base class's operator=()
1566 using HelpPrinter::operator=;
1569 void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override {
1570 std::vector<OptionCategory *> SortedCategories;
1571 std::map<OptionCategory *, std::vector<Option *>> CategorizedOptions;
1573 // Collect registered option categories into vector in preparation for
1575 for (OptionCatSet::const_iterator I = RegisteredOptionCategories->begin(),
1576 E = RegisteredOptionCategories->end();
1578 SortedCategories.push_back(*I);
1581 // Sort the different option categories alphabetically.
1582 assert(SortedCategories.size() > 0 && "No option categories registered!");
1583 std::sort(SortedCategories.begin(), SortedCategories.end(),
1584 OptionCategoryCompare);
1586 // Create map to empty vectors.
1587 for (std::vector<OptionCategory *>::const_iterator
1588 I = SortedCategories.begin(),
1589 E = SortedCategories.end();
1591 CategorizedOptions[*I] = std::vector<Option *>();
1593 // Walk through pre-sorted options and assign into categories.
1594 // Because the options are already alphabetically sorted the
1595 // options within categories will also be alphabetically sorted.
1596 for (size_t I = 0, E = Opts.size(); I != E; ++I) {
1597 Option *Opt = Opts[I].second;
1598 assert(CategorizedOptions.count(Opt->Category) > 0 &&
1599 "Option has an unregistered category");
1600 CategorizedOptions[Opt->Category].push_back(Opt);
1604 for (std::vector<OptionCategory *>::const_iterator
1605 Category = SortedCategories.begin(),
1606 E = SortedCategories.end();
1607 Category != E; ++Category) {
1608 // Hide empty categories for -help, but show for -help-hidden.
1609 bool IsEmptyCategory = CategorizedOptions[*Category].size() == 0;
1610 if (!ShowHidden && IsEmptyCategory)
1613 // Print category information.
1615 outs() << (*Category)->getName() << ":\n";
1617 // Check if description is set.
1618 if ((*Category)->getDescription() != nullptr)
1619 outs() << (*Category)->getDescription() << "\n\n";
1623 // When using -help-hidden explicitly state if the category has no
1624 // options associated with it.
1625 if (IsEmptyCategory) {
1626 outs() << " This option category has no options.\n";
1629 // Loop over the options in the category and print.
1630 for (std::vector<Option *>::const_iterator
1631 Opt = CategorizedOptions[*Category].begin(),
1632 E = CategorizedOptions[*Category].end();
1634 (*Opt)->printOptionInfo(MaxArgLen);
1639 // This wraps the Uncategorizing and Categorizing printers and decides
1640 // at run time which should be invoked.
1641 class HelpPrinterWrapper {
1643 HelpPrinter &UncategorizedPrinter;
1644 CategorizedHelpPrinter &CategorizedPrinter;
1647 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
1648 CategorizedHelpPrinter &CategorizedPrinter)
1649 : UncategorizedPrinter(UncategorizedPrinter),
1650 CategorizedPrinter(CategorizedPrinter) {}
1652 // Invoke the printer.
1653 void operator=(bool Value);
1656 } // End anonymous namespace
1658 // Declare the four HelpPrinter instances that are used to print out help, or
1659 // help-hidden as an uncategorized list or in categories.
1660 static HelpPrinter UncategorizedNormalPrinter(false);
1661 static HelpPrinter UncategorizedHiddenPrinter(true);
1662 static CategorizedHelpPrinter CategorizedNormalPrinter(false);
1663 static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
1665 // Declare HelpPrinter wrappers that will decide whether or not to invoke
1666 // a categorizing help printer
1667 static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
1668 CategorizedNormalPrinter);
1669 static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
1670 CategorizedHiddenPrinter);
1672 // Define a category for generic options that all tools should have.
1673 static cl::OptionCategory GenericCategory("Generic Options");
1675 // Define uncategorized help printers.
1676 // -help-list is hidden by default because if Option categories are being used
1677 // then -help behaves the same as -help-list.
1678 static cl::opt<HelpPrinter, true, parser<bool>> HLOp(
1680 cl::desc("Display list of available options (-help-list-hidden for more)"),
1681 cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed,
1682 cl::cat(GenericCategory));
1684 static cl::opt<HelpPrinter, true, parser<bool>>
1685 HLHOp("help-list-hidden", cl::desc("Display list of all available options"),
1686 cl::location(UncategorizedHiddenPrinter), cl::Hidden,
1687 cl::ValueDisallowed, cl::cat(GenericCategory));
1689 // Define uncategorized/categorized help printers. These printers change their
1690 // behaviour at runtime depending on whether one or more Option categories have
1692 static cl::opt<HelpPrinterWrapper, true, parser<bool>>
1693 HOp("help", cl::desc("Display available options (-help-hidden for more)"),
1694 cl::location(WrappedNormalPrinter), cl::ValueDisallowed,
1695 cl::cat(GenericCategory));
1697 static cl::opt<HelpPrinterWrapper, true, parser<bool>>
1698 HHOp("help-hidden", cl::desc("Display all available options"),
1699 cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed,
1700 cl::cat(GenericCategory));
1702 static cl::opt<bool> PrintOptions(
1704 cl::desc("Print non-default options after command line parsing"),
1705 cl::Hidden, cl::init(false), cl::cat(GenericCategory));
1707 static cl::opt<bool> PrintAllOptions(
1708 "print-all-options",
1709 cl::desc("Print all option values after command line parsing"), cl::Hidden,
1710 cl::init(false), cl::cat(GenericCategory));
1712 void HelpPrinterWrapper::operator=(bool Value) {
1716 // Decide which printer to invoke. If more than one option category is
1717 // registered then it is useful to show the categorized help instead of
1718 // uncategorized help.
1719 if (RegisteredOptionCategories->size() > 1) {
1720 // unhide -help-list option so user can have uncategorized output if they
1722 HLOp.setHiddenFlag(NotHidden);
1724 CategorizedPrinter = true; // Invoke categorized printer
1726 UncategorizedPrinter = true; // Invoke uncategorized printer
1729 // Print the value of each option.
1730 void cl::PrintOptionValues() { GlobalParser->printOptionValues(); }
1732 void CommandLineParser::printOptionValues() {
1733 if (!PrintOptions && !PrintAllOptions)
1736 SmallVector<std::pair<const char *, Option *>, 128> Opts;
1737 sortOpts(OptionsMap, Opts, /*ShowHidden*/ true);
1739 // Compute the maximum argument length...
1740 size_t MaxArgLen = 0;
1741 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1742 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1744 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1745 Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
1748 static void (*OverrideVersionPrinter)() = nullptr;
1750 static std::vector<void (*)()> *ExtraVersionPrinters = nullptr;
1753 class VersionPrinter {
1756 raw_ostream &OS = outs();
1757 OS << "LLVM (http://llvm.org/):\n"
1758 << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
1759 #ifdef LLVM_VERSION_INFO
1760 OS << " " << LLVM_VERSION_INFO;
1763 #ifndef __OPTIMIZE__
1764 OS << "DEBUG build";
1766 OS << "Optimized build";
1769 OS << " with assertions";
1771 std::string CPU = sys::getHostCPUName();
1772 if (CPU == "generic")
1775 #if (ENABLE_TIMESTAMPS == 1)
1776 << " Built " << __DATE__ << " (" << __TIME__ << ").\n"
1778 << " Default target: " << sys::getDefaultTargetTriple() << '\n'
1779 << " Host CPU: " << CPU << '\n';
1781 void operator=(bool OptionWasSpecified) {
1782 if (!OptionWasSpecified)
1785 if (OverrideVersionPrinter != nullptr) {
1786 (*OverrideVersionPrinter)();
1791 // Iterate over any registered extra printers and call them to add further
1793 if (ExtraVersionPrinters != nullptr) {
1795 for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(),
1796 E = ExtraVersionPrinters->end();
1804 } // End anonymous namespace
1806 // Define the --version option that prints out the LLVM version for the tool
1807 static VersionPrinter VersionPrinterInstance;
1809 static cl::opt<VersionPrinter, true, parser<bool>>
1810 VersOp("version", cl::desc("Display the version of this program"),
1811 cl::location(VersionPrinterInstance), cl::ValueDisallowed,
1812 cl::cat(GenericCategory));
1814 // Utility function for printing the help message.
1815 void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
1816 // This looks weird, but it actually prints the help message. The Printers are
1817 // types of HelpPrinter and the help gets printed when its operator= is
1818 // invoked. That's because the "normal" usages of the help printer is to be
1819 // assigned true/false depending on whether -help or -help-hidden was given or
1820 // not. Since we're circumventing that we have to make it look like -help or
1821 // -help-hidden were given, so we assign true.
1823 if (!Hidden && !Categorized)
1824 UncategorizedNormalPrinter = true;
1825 else if (!Hidden && Categorized)
1826 CategorizedNormalPrinter = true;
1827 else if (Hidden && !Categorized)
1828 UncategorizedHiddenPrinter = true;
1830 CategorizedHiddenPrinter = true;
1833 /// Utility function for printing version number.
1834 void cl::PrintVersionMessage() { VersionPrinterInstance.print(); }
1836 void cl::SetVersionPrinter(void (*func)()) { OverrideVersionPrinter = func; }
1838 void cl::AddExtraVersionPrinter(void (*func)()) {
1839 if (!ExtraVersionPrinters)
1840 ExtraVersionPrinters = new std::vector<void (*)()>;
1842 ExtraVersionPrinters->push_back(func);
1845 StringMap<Option *> &cl::getRegisteredOptions() {
1846 return GlobalParser->OptionsMap;
1849 void cl::HideUnrelatedOptions(cl::OptionCategory &Category) {
1850 for (auto &I : GlobalParser->OptionsMap) {
1851 if (I.second->Category != &Category &&
1852 I.second->Category != &GenericCategory)
1853 I.second->setHiddenFlag(cl::ReallyHidden);
1857 void cl::HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories) {
1858 auto CategoriesBegin = Categories.begin();
1859 auto CategoriesEnd = Categories.end();
1860 for (auto &I : GlobalParser->OptionsMap) {
1861 if (std::find(CategoriesBegin, CategoriesEnd, I.second->Category) ==
1863 I.second->Category != &GenericCategory)
1864 I.second->setHiddenFlag(cl::ReallyHidden);
1868 void LLVMParseCommandLineOptions(int argc, const char *const *argv,
1869 const char *Overview) {
1870 llvm::cl::ParseCommandLineOptions(argc, argv, Overview);