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/ADT/ArrayRef.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/ADT/StringMap.h"
24 #include "llvm/ADT/Twine.h"
25 #include "llvm/Config/config.h"
26 #include "llvm/Support/ConvertUTF.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/Host.h"
30 #include "llvm/Support/ManagedStatic.h"
31 #include "llvm/Support/MemoryBuffer.h"
32 #include "llvm/Support/Path.h"
33 #include "llvm/Support/raw_ostream.h"
37 #include <system_error>
41 #define DEBUG_TYPE "commandline"
43 //===----------------------------------------------------------------------===//
44 // Template instantiations and anchors.
46 namespace llvm { namespace cl {
47 TEMPLATE_INSTANTIATION(class basic_parser<bool>);
48 TEMPLATE_INSTANTIATION(class basic_parser<boolOrDefault>);
49 TEMPLATE_INSTANTIATION(class basic_parser<int>);
50 TEMPLATE_INSTANTIATION(class basic_parser<unsigned>);
51 TEMPLATE_INSTANTIATION(class basic_parser<unsigned long long>);
52 TEMPLATE_INSTANTIATION(class basic_parser<double>);
53 TEMPLATE_INSTANTIATION(class basic_parser<float>);
54 TEMPLATE_INSTANTIATION(class basic_parser<std::string>);
55 TEMPLATE_INSTANTIATION(class basic_parser<char>);
57 TEMPLATE_INSTANTIATION(class opt<unsigned>);
58 TEMPLATE_INSTANTIATION(class opt<int>);
59 TEMPLATE_INSTANTIATION(class opt<std::string>);
60 TEMPLATE_INSTANTIATION(class opt<char>);
61 TEMPLATE_INSTANTIATION(class opt<bool>);
62 } } // end namespace llvm::cl
64 // Pin the vtables to this file.
65 void GenericOptionValue::anchor() {}
66 void OptionValue<boolOrDefault>::anchor() {}
67 void OptionValue<std::string>::anchor() {}
68 void Option::anchor() {}
69 void basic_parser_impl::anchor() {}
70 void parser<bool>::anchor() {}
71 void parser<boolOrDefault>::anchor() {}
72 void parser<int>::anchor() {}
73 void parser<unsigned>::anchor() {}
74 void parser<unsigned long long>::anchor() {}
75 void parser<double>::anchor() {}
76 void parser<float>::anchor() {}
77 void parser<std::string>::anchor() {}
78 void parser<char>::anchor() {}
79 void StringSaver::anchor() {}
81 //===----------------------------------------------------------------------===//
83 // Globals for name and overview of program. Program name is not a string to
84 // avoid static ctor/dtor issues.
85 static char ProgramName[80] = "<premain>";
86 static const char *ProgramOverview = nullptr;
88 // This collects additional help to be printed.
89 static ManagedStatic<std::vector<const char*> > MoreHelp;
91 extrahelp::extrahelp(const char *Help)
93 MoreHelp->push_back(Help);
96 static bool OptionListChanged = false;
98 // MarkOptionsChanged - Internal helper function.
99 void cl::MarkOptionsChanged() {
100 OptionListChanged = true;
103 /// RegisteredOptionList - This is the list of the command line options that
104 /// have statically constructed themselves.
105 static Option *RegisteredOptionList = nullptr;
107 void Option::addArgument() {
108 assert(!NextRegistered && "argument multiply registered!");
110 NextRegistered = RegisteredOptionList;
111 RegisteredOptionList = this;
112 MarkOptionsChanged();
115 void Option::removeArgument() {
116 assert(NextRegistered && "argument never registered");
117 assert(RegisteredOptionList == this && "argument is not the last registered");
118 RegisteredOptionList = NextRegistered;
119 MarkOptionsChanged();
122 // This collects the different option categories that have been registered.
123 typedef SmallPtrSet<OptionCategory*,16> OptionCatSet;
124 static ManagedStatic<OptionCatSet> RegisteredOptionCategories;
126 // Initialise the general option category.
127 OptionCategory llvm::cl::GeneralCategory("General options");
129 void OptionCategory::registerCategory() {
130 assert(std::count_if(RegisteredOptionCategories->begin(),
131 RegisteredOptionCategories->end(),
132 [this](const OptionCategory *Category) {
133 return getName() == Category->getName();
134 }) == 0 && "Duplicate option categories");
136 RegisteredOptionCategories->insert(this);
139 //===----------------------------------------------------------------------===//
140 // Basic, shared command line option processing machinery.
143 /// GetOptionInfo - Scan the list of registered options, turning them into data
144 /// structures that are easier to handle.
145 static void GetOptionInfo(SmallVectorImpl<Option*> &PositionalOpts,
146 SmallVectorImpl<Option*> &SinkOpts,
147 StringMap<Option*> &OptionsMap) {
148 bool HadErrors = false;
149 SmallVector<const char*, 16> OptionNames;
150 Option *CAOpt = nullptr; // The ConsumeAfter option if it exists.
151 for (Option *O = RegisteredOptionList; O; O = O->getNextRegisteredOption()) {
152 // If this option wants to handle multiple option names, get the full set.
153 // This handles enum options like "-O1 -O2" etc.
154 O->getExtraOptionNames(OptionNames);
156 OptionNames.push_back(O->ArgStr);
158 // Handle named options.
159 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
160 // Add argument to the argument map!
161 if (OptionsMap.GetOrCreateValue(OptionNames[i], O).second != O) {
162 errs() << ProgramName << ": CommandLine Error: Option '"
163 << OptionNames[i] << "' registered more than once!\n";
170 // Remember information about positional options.
171 if (O->getFormattingFlag() == cl::Positional)
172 PositionalOpts.push_back(O);
173 else if (O->getMiscFlags() & cl::Sink) // Remember sink options
174 SinkOpts.push_back(O);
175 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
177 O->error("Cannot specify more than one option with cl::ConsumeAfter!");
185 PositionalOpts.push_back(CAOpt);
187 // Make sure that they are in order of registration not backwards.
188 std::reverse(PositionalOpts.begin(), PositionalOpts.end());
190 // Fail hard if there were errors. These are strictly unrecoverable and
191 // indicate serious issues such as conflicting option names or an incorrectly
192 // linked LLVM distribution.
194 report_fatal_error("inconsistency in registered CommandLine options");
198 /// LookupOption - Lookup the option specified by the specified option on the
199 /// command line. If there is a value specified (after an equal sign) return
200 /// that as well. This assumes that leading dashes have already been stripped.
201 static Option *LookupOption(StringRef &Arg, StringRef &Value,
202 const StringMap<Option*> &OptionsMap) {
203 // Reject all dashes.
204 if (Arg.empty()) return nullptr;
206 size_t EqualPos = Arg.find('=');
208 // If we have an equals sign, remember the value.
209 if (EqualPos == StringRef::npos) {
210 // Look up the option.
211 StringMap<Option*>::const_iterator I = OptionsMap.find(Arg);
212 return I != OptionsMap.end() ? I->second : nullptr;
215 // If the argument before the = is a valid option name, we match. If not,
216 // return Arg unmolested.
217 StringMap<Option*>::const_iterator I =
218 OptionsMap.find(Arg.substr(0, EqualPos));
219 if (I == OptionsMap.end()) return nullptr;
221 Value = Arg.substr(EqualPos+1);
222 Arg = Arg.substr(0, EqualPos);
226 /// LookupNearestOption - Lookup the closest match to the option specified by
227 /// the specified option on the command line. If there is a value specified
228 /// (after an equal sign) return that as well. This assumes that leading dashes
229 /// have already been stripped.
230 static Option *LookupNearestOption(StringRef Arg,
231 const StringMap<Option*> &OptionsMap,
232 std::string &NearestString) {
233 // Reject all dashes.
234 if (Arg.empty()) return nullptr;
236 // Split on any equal sign.
237 std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
238 StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
239 StringRef &RHS = SplitArg.second;
241 // Find the closest match.
242 Option *Best = nullptr;
243 unsigned BestDistance = 0;
244 for (StringMap<Option*>::const_iterator it = OptionsMap.begin(),
245 ie = OptionsMap.end(); it != ie; ++it) {
246 Option *O = it->second;
247 SmallVector<const char*, 16> OptionNames;
248 O->getExtraOptionNames(OptionNames);
250 OptionNames.push_back(O->ArgStr);
252 bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
253 StringRef Flag = PermitValue ? LHS : Arg;
254 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
255 StringRef Name = OptionNames[i];
256 unsigned Distance = StringRef(Name).edit_distance(
257 Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
258 if (!Best || Distance < BestDistance) {
260 BestDistance = Distance;
261 if (RHS.empty() || !PermitValue)
262 NearestString = OptionNames[i];
264 NearestString = std::string(OptionNames[i]) + "=" + RHS.str();
272 /// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence()
273 /// that does special handling of cl::CommaSeparated options.
274 static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos,
275 StringRef ArgName, StringRef Value,
276 bool MultiArg = false) {
277 // Check to see if this option accepts a comma separated list of values. If
278 // it does, we have to split up the value into multiple values.
279 if (Handler->getMiscFlags() & CommaSeparated) {
280 StringRef Val(Value);
281 StringRef::size_type Pos = Val.find(',');
283 while (Pos != StringRef::npos) {
284 // Process the portion before the comma.
285 if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
287 // Erase the portion before the comma, AND the comma.
288 Val = Val.substr(Pos+1);
289 Value.substr(Pos+1); // Increment the original value pointer as well.
290 // Check for another comma.
297 if (Handler->addOccurrence(pos, ArgName, Value, MultiArg))
303 /// ProvideOption - For Value, this differentiates between an empty value ("")
304 /// and a null value (StringRef()). The later is accepted for arguments that
305 /// don't allow a value (-foo) the former is rejected (-foo=).
306 static inline bool ProvideOption(Option *Handler, StringRef ArgName,
307 StringRef Value, int argc,
308 const char *const *argv, int &i) {
309 // Is this a multi-argument option?
310 unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
312 // Enforce value requirements
313 switch (Handler->getValueExpectedFlag()) {
315 if (!Value.data()) { // No value specified?
317 return Handler->error("requires a value!");
318 // Steal the next argument, like for '-o filename'
322 case ValueDisallowed:
323 if (NumAdditionalVals > 0)
324 return Handler->error("multi-valued option specified"
325 " with ValueDisallowed modifier!");
328 return Handler->error("does not allow a value! '" +
329 Twine(Value) + "' specified.");
335 // If this isn't a multi-arg option, just run the handler.
336 if (NumAdditionalVals == 0)
337 return CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value);
339 // If it is, run the handle several times.
340 bool MultiArg = false;
343 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
349 while (NumAdditionalVals > 0) {
351 return Handler->error("not enough values!");
354 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
362 static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
364 return ProvideOption(Handler, Handler->ArgStr, Arg, 0, nullptr, Dummy);
368 // Option predicates...
369 static inline bool isGrouping(const Option *O) {
370 return O->getFormattingFlag() == cl::Grouping;
372 static inline bool isPrefixedOrGrouping(const Option *O) {
373 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
376 // getOptionPred - Check to see if there are any options that satisfy the
377 // specified predicate with names that are the prefixes in Name. This is
378 // checked by progressively stripping characters off of the name, checking to
379 // see if there options that satisfy the predicate. If we find one, return it,
380 // otherwise return null.
382 static Option *getOptionPred(StringRef Name, size_t &Length,
383 bool (*Pred)(const Option*),
384 const StringMap<Option*> &OptionsMap) {
386 StringMap<Option*>::const_iterator OMI = OptionsMap.find(Name);
388 // Loop while we haven't found an option and Name still has at least two
389 // characters in it (so that the next iteration will not be the empty
391 while (OMI == OptionsMap.end() && Name.size() > 1) {
392 Name = Name.substr(0, Name.size()-1); // Chop off the last character.
393 OMI = OptionsMap.find(Name);
396 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
397 Length = Name.size();
398 return OMI->second; // Found one!
400 return nullptr; // No option found!
403 /// HandlePrefixedOrGroupedOption - The specified argument string (which started
404 /// with at least one '-') does not fully match an available option. Check to
405 /// see if this is a prefix or grouped option. If so, split arg into output an
406 /// Arg/Value pair and return the Option to parse it with.
407 static Option *HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
409 const StringMap<Option*> &OptionsMap) {
410 if (Arg.size() == 1) return nullptr;
414 Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
415 if (!PGOpt) return nullptr;
417 // If the option is a prefixed option, then the value is simply the
418 // rest of the name... so fall through to later processing, by
419 // setting up the argument name flags and value fields.
420 if (PGOpt->getFormattingFlag() == cl::Prefix) {
421 Value = Arg.substr(Length);
422 Arg = Arg.substr(0, Length);
423 assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
427 // This must be a grouped option... handle them now. Grouping options can't
429 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
432 // Move current arg name out of Arg into OneArgName.
433 StringRef OneArgName = Arg.substr(0, Length);
434 Arg = Arg.substr(Length);
436 // Because ValueRequired is an invalid flag for grouped arguments,
437 // we don't need to pass argc/argv in.
438 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
439 "Option can not be cl::Grouping AND cl::ValueRequired!");
441 ErrorParsing |= ProvideOption(PGOpt, OneArgName,
442 StringRef(), 0, nullptr, Dummy);
444 // Get the next grouping option.
445 PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
446 } while (PGOpt && Length != Arg.size());
448 // Return the last option with Arg cut down to just the last one.
454 static bool RequiresValue(const Option *O) {
455 return O->getNumOccurrencesFlag() == cl::Required ||
456 O->getNumOccurrencesFlag() == cl::OneOrMore;
459 static bool EatsUnboundedNumberOfValues(const Option *O) {
460 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
461 O->getNumOccurrencesFlag() == cl::OneOrMore;
464 static bool isWhitespace(char C) {
465 return strchr(" \t\n\r\f\v", C);
468 static bool isQuote(char C) {
469 return C == '\"' || C == '\'';
472 static bool isGNUSpecial(char C) {
473 return strchr("\\\"\' ", C);
476 void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
477 SmallVectorImpl<const char *> &NewArgv) {
478 SmallString<128> Token;
479 for (size_t I = 0, E = Src.size(); I != E; ++I) {
480 // Consume runs of whitespace.
482 while (I != E && isWhitespace(Src[I]))
487 // Backslashes can escape backslashes, spaces, and other quotes. Otherwise
488 // they are literal. This makes it much easier to read Windows file paths.
489 if (I + 1 < E && Src[I] == '\\' && isGNUSpecial(Src[I + 1])) {
490 ++I; // Skip the escape.
491 Token.push_back(Src[I]);
495 // Consume a quoted string.
496 if (isQuote(Src[I])) {
497 char Quote = Src[I++];
498 while (I != E && Src[I] != Quote) {
499 // Backslashes are literal, unless they escape a special character.
500 if (Src[I] == '\\' && I + 1 != E && isGNUSpecial(Src[I + 1]))
502 Token.push_back(Src[I]);
509 // End the token if this is whitespace.
510 if (isWhitespace(Src[I])) {
512 NewArgv.push_back(Saver.SaveString(Token.c_str()));
517 // This is a normal character. Append it.
518 Token.push_back(Src[I]);
521 // Append the last token after hitting EOF with no whitespace.
523 NewArgv.push_back(Saver.SaveString(Token.c_str()));
526 /// Backslashes are interpreted in a rather complicated way in the Windows-style
527 /// command line, because backslashes are used both to separate path and to
528 /// escape double quote. This method consumes runs of backslashes as well as the
529 /// following double quote if it's escaped.
531 /// * If an even number of backslashes is followed by a double quote, one
532 /// backslash is output for every pair of backslashes, and the last double
533 /// quote remains unconsumed. The double quote will later be interpreted as
534 /// the start or end of a quoted string in the main loop outside of this
537 /// * If an odd number of backslashes is followed by a double quote, one
538 /// backslash is output for every pair of backslashes, and a double quote is
539 /// output for the last pair of backslash-double quote. The double quote is
540 /// consumed in this case.
542 /// * Otherwise, backslashes are interpreted literally.
543 static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
544 size_t E = Src.size();
545 int BackslashCount = 0;
546 // Skip the backslashes.
550 } while (I != E && Src[I] == '\\');
552 bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
553 if (FollowedByDoubleQuote) {
554 Token.append(BackslashCount / 2, '\\');
555 if (BackslashCount % 2 == 0)
557 Token.push_back('"');
560 Token.append(BackslashCount, '\\');
564 void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
565 SmallVectorImpl<const char *> &NewArgv) {
566 SmallString<128> Token;
568 // This is a small state machine to consume characters until it reaches the
569 // end of the source string.
570 enum { INIT, UNQUOTED, QUOTED } State = INIT;
571 for (size_t I = 0, E = Src.size(); I != E; ++I) {
572 // INIT state indicates that the current input index is at the start of
573 // the string or between tokens.
575 if (isWhitespace(Src[I]))
581 if (Src[I] == '\\') {
582 I = parseBackslash(Src, I, Token);
586 Token.push_back(Src[I]);
591 // UNQUOTED state means that it's reading a token not quoted by double
593 if (State == UNQUOTED) {
594 // Whitespace means the end of the token.
595 if (isWhitespace(Src[I])) {
596 NewArgv.push_back(Saver.SaveString(Token.c_str()));
605 if (Src[I] == '\\') {
606 I = parseBackslash(Src, I, Token);
609 Token.push_back(Src[I]);
613 // QUOTED state means that it's reading a token quoted by double quotes.
614 if (State == QUOTED) {
619 if (Src[I] == '\\') {
620 I = parseBackslash(Src, I, Token);
623 Token.push_back(Src[I]);
626 // Append the last token after hitting EOF with no whitespace.
628 NewArgv.push_back(Saver.SaveString(Token.c_str()));
631 static bool ExpandResponseFile(const char *FName, StringSaver &Saver,
632 TokenizerCallback Tokenizer,
633 SmallVectorImpl<const char *> &NewArgv) {
634 ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
635 MemoryBuffer::getFile(FName);
638 std::unique_ptr<MemoryBuffer> MemBuf = std::move(MemBufOrErr.get());
639 StringRef Str(MemBuf->getBufferStart(), MemBuf->getBufferSize());
641 // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
642 ArrayRef<char> BufRef(MemBuf->getBufferStart(), MemBuf->getBufferEnd());
644 if (hasUTF16ByteOrderMark(BufRef)) {
645 if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
647 Str = StringRef(UTF8Buf);
650 // Tokenize the contents into NewArgv.
651 Tokenizer(Str, Saver, NewArgv);
656 /// \brief Expand response files on a command line recursively using the given
657 /// StringSaver and tokenization strategy.
658 bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
659 SmallVectorImpl<const char *> &Argv) {
660 unsigned RspFiles = 0;
661 bool AllExpanded = true;
663 // Don't cache Argv.size() because it can change.
664 for (unsigned I = 0; I != Argv.size(); ) {
665 const char *Arg = Argv[I];
671 // If we have too many response files, leave some unexpanded. This avoids
672 // crashing on self-referential response files.
676 // Replace this response file argument with the tokenization of its
677 // contents. Nested response files are expanded in subsequent iterations.
678 // FIXME: If a nested response file uses a relative path, is it relative to
679 // the cwd of the process or the response file?
680 SmallVector<const char *, 0> ExpandedArgv;
681 if (!ExpandResponseFile(Arg + 1, Saver, Tokenizer, ExpandedArgv)) {
682 // We couldn't read this file, so we leave it in the argument stream and
688 Argv.erase(Argv.begin() + I);
689 Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
695 class StrDupSaver : public StringSaver {
696 std::vector<char*> Dups;
699 for (std::vector<char *>::iterator I = Dups.begin(), E = Dups.end();
705 const char *SaveString(const char *Str) override {
706 char *Dup = strdup(Str);
713 /// ParseEnvironmentOptions - An alternative entry point to the
714 /// CommandLine library, which allows you to read the program's name
715 /// from the caller (as PROGNAME) and its command-line arguments from
716 /// an environment variable (whose name is given in ENVVAR).
718 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
719 const char *Overview) {
721 assert(progName && "Program name not specified");
722 assert(envVar && "Environment variable name missing");
724 // Get the environment variable they want us to parse options out of.
725 const char *envValue = getenv(envVar);
729 // Get program's "name", which we wouldn't know without the caller
731 SmallVector<const char *, 20> newArgv;
733 newArgv.push_back(Saver.SaveString(progName));
735 // Parse the value of the environment variable into a "command line"
736 // and hand it off to ParseCommandLineOptions().
737 TokenizeGNUCommandLine(envValue, Saver, newArgv);
738 int newArgc = static_cast<int>(newArgv.size());
739 ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
742 void cl::ParseCommandLineOptions(int argc, const char * const *argv,
743 const char *Overview) {
744 // Process all registered options.
745 SmallVector<Option*, 4> PositionalOpts;
746 SmallVector<Option*, 4> SinkOpts;
747 StringMap<Option*> Opts;
748 GetOptionInfo(PositionalOpts, SinkOpts, Opts);
750 assert((!Opts.empty() || !PositionalOpts.empty()) &&
751 "No options specified!");
753 // Expand response files.
754 SmallVector<const char *, 20> newArgv;
755 for (int i = 0; i != argc; ++i)
756 newArgv.push_back(argv[i]);
758 ExpandResponseFiles(Saver, TokenizeGNUCommandLine, newArgv);
760 argc = static_cast<int>(newArgv.size());
762 // Copy the program name into ProgName, making sure not to overflow it.
763 StringRef ProgName = sys::path::filename(argv[0]);
764 size_t Len = std::min(ProgName.size(), size_t(79));
765 memcpy(ProgramName, ProgName.data(), Len);
766 ProgramName[Len] = '\0';
768 ProgramOverview = Overview;
769 bool ErrorParsing = false;
771 // Check out the positional arguments to collect information about them.
772 unsigned NumPositionalRequired = 0;
774 // Determine whether or not there are an unlimited number of positionals
775 bool HasUnlimitedPositionals = false;
777 Option *ConsumeAfterOpt = nullptr;
778 if (!PositionalOpts.empty()) {
779 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
780 assert(PositionalOpts.size() > 1 &&
781 "Cannot specify cl::ConsumeAfter without a positional argument!");
782 ConsumeAfterOpt = PositionalOpts[0];
785 // Calculate how many positional values are _required_.
786 bool UnboundedFound = false;
787 for (size_t i = ConsumeAfterOpt ? 1 : 0, e = PositionalOpts.size();
789 Option *Opt = PositionalOpts[i];
790 if (RequiresValue(Opt))
791 ++NumPositionalRequired;
792 else if (ConsumeAfterOpt) {
793 // ConsumeAfter cannot be combined with "optional" positional options
794 // unless there is only one positional argument...
795 if (PositionalOpts.size() > 2)
797 Opt->error("error - this positional option will never be matched, "
798 "because it does not Require a value, and a "
799 "cl::ConsumeAfter option is active!");
800 } else if (UnboundedFound && !Opt->ArgStr[0]) {
801 // This option does not "require" a value... Make sure this option is
802 // not specified after an option that eats all extra arguments, or this
803 // one will never get any!
805 ErrorParsing |= Opt->error("error - option can never match, because "
806 "another positional argument will match an "
807 "unbounded number of values, and this option"
808 " does not require a value!");
810 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
812 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
815 // PositionalVals - A vector of "positional" arguments we accumulate into
816 // the process at the end.
818 SmallVector<std::pair<StringRef,unsigned>, 4> PositionalVals;
820 // If the program has named positional arguments, and the name has been run
821 // across, keep track of which positional argument was named. Otherwise put
822 // the positional args into the PositionalVals list...
823 Option *ActivePositionalArg = nullptr;
825 // Loop over all of the arguments... processing them.
826 bool DashDashFound = false; // Have we read '--'?
827 for (int i = 1; i < argc; ++i) {
828 Option *Handler = nullptr;
829 Option *NearestHandler = nullptr;
830 std::string NearestHandlerString;
832 StringRef ArgName = "";
834 // If the option list changed, this means that some command line
835 // option has just been registered or deregistered. This can occur in
836 // response to things like -load, etc. If this happens, rescan the options.
837 if (OptionListChanged) {
838 PositionalOpts.clear();
841 GetOptionInfo(PositionalOpts, SinkOpts, Opts);
842 OptionListChanged = false;
845 // Check to see if this is a positional argument. This argument is
846 // considered to be positional if it doesn't start with '-', if it is "-"
847 // itself, or if we have seen "--" already.
849 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
850 // Positional argument!
851 if (ActivePositionalArg) {
852 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
853 continue; // We are done!
856 if (!PositionalOpts.empty()) {
857 PositionalVals.push_back(std::make_pair(argv[i],i));
859 // All of the positional arguments have been fulfulled, give the rest to
860 // the consume after option... if it's specified...
862 if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) {
863 for (++i; i < argc; ++i)
864 PositionalVals.push_back(std::make_pair(argv[i],i));
865 break; // Handle outside of the argument processing loop...
868 // Delay processing positional arguments until the end...
871 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
873 DashDashFound = true; // This is the mythical "--"?
874 continue; // Don't try to process it as an argument itself.
875 } else if (ActivePositionalArg &&
876 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
877 // If there is a positional argument eating options, check to see if this
878 // option is another positional argument. If so, treat it as an argument,
879 // otherwise feed it to the eating positional.
881 // Eat leading dashes.
882 while (!ArgName.empty() && ArgName[0] == '-')
883 ArgName = ArgName.substr(1);
885 Handler = LookupOption(ArgName, Value, Opts);
886 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
887 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
888 continue; // We are done!
891 } else { // We start with a '-', must be an argument.
893 // Eat leading dashes.
894 while (!ArgName.empty() && ArgName[0] == '-')
895 ArgName = ArgName.substr(1);
897 Handler = LookupOption(ArgName, Value, Opts);
899 // Check to see if this "option" is really a prefixed or grouped argument.
901 Handler = HandlePrefixedOrGroupedOption(ArgName, Value,
904 // Otherwise, look for the closest available option to report to the user
905 // in the upcoming error.
906 if (!Handler && SinkOpts.empty())
907 NearestHandler = LookupNearestOption(ArgName, Opts,
908 NearestHandlerString);
912 if (SinkOpts.empty()) {
913 errs() << ProgramName << ": Unknown command line argument '"
914 << argv[i] << "'. Try: '" << argv[0] << " -help'\n";
916 if (NearestHandler) {
917 // If we know a near match, report it as well.
918 errs() << ProgramName << ": Did you mean '-"
919 << NearestHandlerString << "'?\n";
924 for (SmallVectorImpl<Option*>::iterator I = SinkOpts.begin(),
925 E = SinkOpts.end(); I != E ; ++I)
926 (*I)->addOccurrence(i, "", argv[i]);
931 // If this is a named positional argument, just remember that it is the
933 if (Handler->getFormattingFlag() == cl::Positional)
934 ActivePositionalArg = Handler;
936 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
939 // Check and handle positional arguments now...
940 if (NumPositionalRequired > PositionalVals.size()) {
941 errs() << ProgramName
942 << ": Not enough positional command line arguments specified!\n"
943 << "Must specify at least " << NumPositionalRequired
944 << " positional arguments: See: " << argv[0] << " -help\n";
947 } else if (!HasUnlimitedPositionals &&
948 PositionalVals.size() > PositionalOpts.size()) {
949 errs() << ProgramName
950 << ": Too many positional arguments specified!\n"
951 << "Can specify at most " << PositionalOpts.size()
952 << " positional arguments: See: " << argv[0] << " -help\n";
955 } else if (!ConsumeAfterOpt) {
956 // Positional args have already been handled if ConsumeAfter is specified.
957 unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
958 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
959 if (RequiresValue(PositionalOpts[i])) {
960 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
961 PositionalVals[ValNo].second);
963 --NumPositionalRequired; // We fulfilled our duty...
966 // If we _can_ give this option more arguments, do so now, as long as we
967 // do not give it values that others need. 'Done' controls whether the
968 // option even _WANTS_ any more.
970 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
971 while (NumVals-ValNo > NumPositionalRequired && !Done) {
972 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
974 Done = true; // Optional arguments want _at most_ one value
976 case cl::ZeroOrMore: // Zero or more will take all they can get...
977 case cl::OneOrMore: // One or more will take all they can get...
978 ProvidePositionalOption(PositionalOpts[i],
979 PositionalVals[ValNo].first,
980 PositionalVals[ValNo].second);
984 llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
985 "positional argument processing!");
990 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
992 for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
993 if (RequiresValue(PositionalOpts[j])) {
994 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
995 PositionalVals[ValNo].first,
996 PositionalVals[ValNo].second);
1000 // Handle the case where there is just one positional option, and it's
1001 // optional. In this case, we want to give JUST THE FIRST option to the
1002 // positional option and keep the rest for the consume after. The above
1003 // loop would have assigned no values to positional options in this case.
1005 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
1006 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
1007 PositionalVals[ValNo].first,
1008 PositionalVals[ValNo].second);
1012 // Handle over all of the rest of the arguments to the
1013 // cl::ConsumeAfter command line option...
1014 for (; ValNo != PositionalVals.size(); ++ValNo)
1015 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
1016 PositionalVals[ValNo].first,
1017 PositionalVals[ValNo].second);
1020 // Loop over args and make sure all required args are specified!
1021 for (StringMap<Option*>::iterator I = Opts.begin(),
1022 E = Opts.end(); I != E; ++I) {
1023 switch (I->second->getNumOccurrencesFlag()) {
1026 if (I->second->getNumOccurrences() == 0) {
1027 I->second->error("must be specified at least once!");
1028 ErrorParsing = true;
1036 // Now that we know if -debug is specified, we can use it.
1037 // Note that if ReadResponseFiles == true, this must be done before the
1038 // memory allocated for the expanded command line is free()d below.
1039 DEBUG(dbgs() << "Args: ";
1040 for (int i = 0; i < argc; ++i)
1041 dbgs() << argv[i] << ' ';
1045 // Free all of the memory allocated to the map. Command line options may only
1046 // be processed once!
1048 PositionalOpts.clear();
1051 // If we had an error processing our arguments, don't let the program execute
1052 if (ErrorParsing) exit(1);
1055 //===----------------------------------------------------------------------===//
1056 // Option Base class implementation
1059 bool Option::error(const Twine &Message, StringRef ArgName) {
1060 if (!ArgName.data()) ArgName = ArgStr;
1061 if (ArgName.empty())
1062 errs() << HelpStr; // Be nice for positional arguments
1064 errs() << ProgramName << ": for the -" << ArgName;
1066 errs() << " option: " << Message << "\n";
1070 bool Option::addOccurrence(unsigned pos, StringRef ArgName,
1071 StringRef Value, bool MultiArg) {
1073 NumOccurrences++; // Increment the number of times we have been seen
1075 switch (getNumOccurrencesFlag()) {
1077 if (NumOccurrences > 1)
1078 return error("may only occur zero or one times!", ArgName);
1081 if (NumOccurrences > 1)
1082 return error("must occur exactly one time!", ArgName);
1086 case ConsumeAfter: break;
1089 return handleOccurrence(pos, ArgName, Value);
1093 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
1094 // has been specified yet.
1096 static const char *getValueStr(const Option &O, const char *DefaultMsg) {
1097 if (O.ValueStr[0] == 0) return DefaultMsg;
1101 //===----------------------------------------------------------------------===//
1102 // cl::alias class implementation
1105 // Return the width of the option tag for printing...
1106 size_t alias::getOptionWidth() const {
1107 return std::strlen(ArgStr)+6;
1110 static void printHelpStr(StringRef HelpStr, size_t Indent,
1111 size_t FirstLineIndentedBy) {
1112 std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1113 outs().indent(Indent - FirstLineIndentedBy) << " - " << Split.first << "\n";
1114 while (!Split.second.empty()) {
1115 Split = Split.second.split('\n');
1116 outs().indent(Indent) << Split.first << "\n";
1120 // Print out the option for the alias.
1121 void alias::printOptionInfo(size_t GlobalWidth) const {
1122 outs() << " -" << ArgStr;
1123 printHelpStr(HelpStr, GlobalWidth, std::strlen(ArgStr) + 6);
1126 //===----------------------------------------------------------------------===//
1127 // Parser Implementation code...
1130 // basic_parser implementation
1133 // Return the width of the option tag for printing...
1134 size_t basic_parser_impl::getOptionWidth(const Option &O) const {
1135 size_t Len = std::strlen(O.ArgStr);
1136 if (const char *ValName = getValueName())
1137 Len += std::strlen(getValueStr(O, ValName))+3;
1142 // printOptionInfo - Print out information about this option. The
1143 // to-be-maintained width is specified.
1145 void basic_parser_impl::printOptionInfo(const Option &O,
1146 size_t GlobalWidth) const {
1147 outs() << " -" << O.ArgStr;
1149 if (const char *ValName = getValueName())
1150 outs() << "=<" << getValueStr(O, ValName) << '>';
1152 printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
1155 void basic_parser_impl::printOptionName(const Option &O,
1156 size_t GlobalWidth) const {
1157 outs() << " -" << O.ArgStr;
1158 outs().indent(GlobalWidth-std::strlen(O.ArgStr));
1162 // parser<bool> implementation
1164 bool parser<bool>::parse(Option &O, StringRef ArgName,
1165 StringRef Arg, bool &Value) {
1166 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1172 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1176 return O.error("'" + Arg +
1177 "' is invalid value for boolean argument! Try 0 or 1");
1180 // parser<boolOrDefault> implementation
1182 bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName,
1183 StringRef Arg, boolOrDefault &Value) {
1184 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1189 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1194 return O.error("'" + Arg +
1195 "' is invalid value for boolean argument! Try 0 or 1");
1198 // parser<int> implementation
1200 bool parser<int>::parse(Option &O, StringRef ArgName,
1201 StringRef Arg, int &Value) {
1202 if (Arg.getAsInteger(0, Value))
1203 return O.error("'" + Arg + "' value invalid for integer argument!");
1207 // parser<unsigned> implementation
1209 bool parser<unsigned>::parse(Option &O, StringRef ArgName,
1210 StringRef Arg, unsigned &Value) {
1212 if (Arg.getAsInteger(0, Value))
1213 return O.error("'" + Arg + "' value invalid for uint argument!");
1217 // parser<unsigned long long> implementation
1219 bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
1220 StringRef Arg, unsigned long long &Value){
1222 if (Arg.getAsInteger(0, Value))
1223 return O.error("'" + Arg + "' value invalid for uint argument!");
1227 // parser<double>/parser<float> implementation
1229 static bool parseDouble(Option &O, StringRef Arg, double &Value) {
1230 SmallString<32> TmpStr(Arg.begin(), Arg.end());
1231 const char *ArgStart = TmpStr.c_str();
1233 Value = strtod(ArgStart, &End);
1235 return O.error("'" + Arg + "' value invalid for floating point argument!");
1239 bool parser<double>::parse(Option &O, StringRef ArgName,
1240 StringRef Arg, double &Val) {
1241 return parseDouble(O, Arg, Val);
1244 bool parser<float>::parse(Option &O, StringRef ArgName,
1245 StringRef Arg, float &Val) {
1247 if (parseDouble(O, Arg, dVal))
1255 // generic_parser_base implementation
1258 // findOption - Return the option number corresponding to the specified
1259 // argument string. If the option is not found, getNumOptions() is returned.
1261 unsigned generic_parser_base::findOption(const char *Name) {
1262 unsigned e = getNumOptions();
1264 for (unsigned i = 0; i != e; ++i) {
1265 if (strcmp(getOption(i), Name) == 0)
1272 // Return the width of the option tag for printing...
1273 size_t generic_parser_base::getOptionWidth(const Option &O) const {
1274 if (O.hasArgStr()) {
1275 size_t Size = std::strlen(O.ArgStr)+6;
1276 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1277 Size = std::max(Size, std::strlen(getOption(i))+8);
1280 size_t BaseSize = 0;
1281 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1282 BaseSize = std::max(BaseSize, std::strlen(getOption(i))+8);
1287 // printOptionInfo - Print out information about this option. The
1288 // to-be-maintained width is specified.
1290 void generic_parser_base::printOptionInfo(const Option &O,
1291 size_t GlobalWidth) const {
1292 if (O.hasArgStr()) {
1293 outs() << " -" << O.ArgStr;
1294 printHelpStr(O.HelpStr, GlobalWidth, std::strlen(O.ArgStr) + 6);
1296 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1297 size_t NumSpaces = GlobalWidth-strlen(getOption(i))-8;
1298 outs() << " =" << getOption(i);
1299 outs().indent(NumSpaces) << " - " << getDescription(i) << '\n';
1303 outs() << " " << O.HelpStr << '\n';
1304 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1305 const char *Option = getOption(i);
1306 outs() << " -" << Option;
1307 printHelpStr(getDescription(i), GlobalWidth, std::strlen(Option) + 8);
1312 static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1314 // printGenericOptionDiff - Print the value of this option and it's default.
1316 // "Generic" options have each value mapped to a name.
1317 void generic_parser_base::
1318 printGenericOptionDiff(const Option &O, const GenericOptionValue &Value,
1319 const GenericOptionValue &Default,
1320 size_t GlobalWidth) const {
1321 outs() << " -" << O.ArgStr;
1322 outs().indent(GlobalWidth-std::strlen(O.ArgStr));
1324 unsigned NumOpts = getNumOptions();
1325 for (unsigned i = 0; i != NumOpts; ++i) {
1326 if (Value.compare(getOptionValue(i)))
1329 outs() << "= " << getOption(i);
1330 size_t L = std::strlen(getOption(i));
1331 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1332 outs().indent(NumSpaces) << " (default: ";
1333 for (unsigned j = 0; j != NumOpts; ++j) {
1334 if (Default.compare(getOptionValue(j)))
1336 outs() << getOption(j);
1342 outs() << "= *unknown option value*\n";
1345 // printOptionDiff - Specializations for printing basic value types.
1347 #define PRINT_OPT_DIFF(T) \
1349 printOptionDiff(const Option &O, T V, OptionValue<T> D, \
1350 size_t GlobalWidth) const { \
1351 printOptionName(O, GlobalWidth); \
1354 raw_string_ostream SS(Str); \
1357 outs() << "= " << Str; \
1358 size_t NumSpaces = MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0;\
1359 outs().indent(NumSpaces) << " (default: "; \
1361 outs() << D.getValue(); \
1363 outs() << "*no default*"; \
1367 PRINT_OPT_DIFF(bool)
1368 PRINT_OPT_DIFF(boolOrDefault)
1370 PRINT_OPT_DIFF(unsigned)
1371 PRINT_OPT_DIFF(unsigned long long)
1372 PRINT_OPT_DIFF(double)
1373 PRINT_OPT_DIFF(float)
1374 PRINT_OPT_DIFF(char)
1376 void parser<std::string>::
1377 printOptionDiff(const Option &O, StringRef V, OptionValue<std::string> D,
1378 size_t GlobalWidth) const {
1379 printOptionName(O, GlobalWidth);
1380 outs() << "= " << V;
1381 size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
1382 outs().indent(NumSpaces) << " (default: ";
1384 outs() << D.getValue();
1386 outs() << "*no default*";
1390 // Print a placeholder for options that don't yet support printOptionDiff().
1391 void basic_parser_impl::
1392 printOptionNoValue(const Option &O, size_t GlobalWidth) const {
1393 printOptionName(O, GlobalWidth);
1394 outs() << "= *cannot print option value*\n";
1397 //===----------------------------------------------------------------------===//
1398 // -help and -help-hidden option implementation
1401 static int OptNameCompare(const void *LHS, const void *RHS) {
1402 typedef std::pair<const char *, Option*> pair_ty;
1404 return strcmp(((const pair_ty*)LHS)->first, ((const pair_ty*)RHS)->first);
1407 // Copy Options into a vector so we can sort them as we like.
1409 sortOpts(StringMap<Option*> &OptMap,
1410 SmallVectorImpl< std::pair<const char *, Option*> > &Opts,
1412 SmallPtrSet<Option*, 128> OptionSet; // Duplicate option detection.
1414 for (StringMap<Option*>::iterator I = OptMap.begin(), E = OptMap.end();
1416 // Ignore really-hidden options.
1417 if (I->second->getOptionHiddenFlag() == ReallyHidden)
1420 // Unless showhidden is set, ignore hidden flags.
1421 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
1424 // If we've already seen this option, don't add it to the list again.
1425 if (!OptionSet.insert(I->second))
1428 Opts.push_back(std::pair<const char *, Option*>(I->getKey().data(),
1432 // Sort the options list alphabetically.
1433 qsort(Opts.data(), Opts.size(), sizeof(Opts[0]), OptNameCompare);
1440 const bool ShowHidden;
1441 typedef SmallVector<std::pair<const char *, Option*>,128> StrOptionPairVector;
1442 // Print the options. Opts is assumed to be alphabetically sorted.
1443 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1444 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1445 Opts[i].second->printOptionInfo(MaxArgLen);
1449 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
1450 virtual ~HelpPrinter() {}
1452 // Invoke the printer.
1453 void operator=(bool Value) {
1454 if (Value == false) return;
1456 // Get all the options.
1457 SmallVector<Option*, 4> PositionalOpts;
1458 SmallVector<Option*, 4> SinkOpts;
1459 StringMap<Option*> OptMap;
1460 GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
1462 StrOptionPairVector Opts;
1463 sortOpts(OptMap, Opts, ShowHidden);
1465 if (ProgramOverview)
1466 outs() << "OVERVIEW: " << ProgramOverview << "\n";
1468 outs() << "USAGE: " << ProgramName << " [options]";
1470 // Print out the positional options.
1471 Option *CAOpt = nullptr; // The cl::ConsumeAfter option, if it exists...
1472 if (!PositionalOpts.empty() &&
1473 PositionalOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
1474 CAOpt = PositionalOpts[0];
1476 for (size_t i = CAOpt != nullptr, e = PositionalOpts.size(); i != e; ++i) {
1477 if (PositionalOpts[i]->ArgStr[0])
1478 outs() << " --" << PositionalOpts[i]->ArgStr;
1479 outs() << " " << PositionalOpts[i]->HelpStr;
1482 // Print the consume after option info if it exists...
1483 if (CAOpt) outs() << " " << CAOpt->HelpStr;
1487 // Compute the maximum argument length...
1488 size_t MaxArgLen = 0;
1489 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1490 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1492 outs() << "OPTIONS:\n";
1493 printOptions(Opts, MaxArgLen);
1495 // Print any extra help the user has declared.
1496 for (std::vector<const char *>::iterator I = MoreHelp->begin(),
1497 E = MoreHelp->end();
1502 // Halt the program since help information was printed
1507 class CategorizedHelpPrinter : public HelpPrinter {
1509 explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
1511 // Helper function for printOptions().
1512 // It shall return true if A's name should be lexographically
1513 // ordered before B's name. It returns false otherwise.
1514 static bool OptionCategoryCompare(OptionCategory *A, OptionCategory *B) {
1515 return strcmp(A->getName(), B->getName()) < 0;
1518 // Make sure we inherit our base class's operator=()
1519 using HelpPrinter::operator= ;
1522 void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override {
1523 std::vector<OptionCategory *> SortedCategories;
1524 std::map<OptionCategory *, std::vector<Option *> > CategorizedOptions;
1526 // Collect registered option categories into vector in preparation for
1528 for (OptionCatSet::const_iterator I = RegisteredOptionCategories->begin(),
1529 E = RegisteredOptionCategories->end();
1531 SortedCategories.push_back(*I);
1534 // Sort the different option categories alphabetically.
1535 assert(SortedCategories.size() > 0 && "No option categories registered!");
1536 std::sort(SortedCategories.begin(), SortedCategories.end(),
1537 OptionCategoryCompare);
1539 // Create map to empty vectors.
1540 for (std::vector<OptionCategory *>::const_iterator
1541 I = SortedCategories.begin(),
1542 E = SortedCategories.end();
1544 CategorizedOptions[*I] = std::vector<Option *>();
1546 // Walk through pre-sorted options and assign into categories.
1547 // Because the options are already alphabetically sorted the
1548 // options within categories will also be alphabetically sorted.
1549 for (size_t I = 0, E = Opts.size(); I != E; ++I) {
1550 Option *Opt = Opts[I].second;
1551 assert(CategorizedOptions.count(Opt->Category) > 0 &&
1552 "Option has an unregistered category");
1553 CategorizedOptions[Opt->Category].push_back(Opt);
1557 for (std::vector<OptionCategory *>::const_iterator
1558 Category = SortedCategories.begin(),
1559 E = SortedCategories.end();
1560 Category != E; ++Category) {
1561 // Hide empty categories for -help, but show for -help-hidden.
1562 bool IsEmptyCategory = CategorizedOptions[*Category].size() == 0;
1563 if (!ShowHidden && IsEmptyCategory)
1566 // Print category information.
1568 outs() << (*Category)->getName() << ":\n";
1570 // Check if description is set.
1571 if ((*Category)->getDescription() != nullptr)
1572 outs() << (*Category)->getDescription() << "\n\n";
1576 // When using -help-hidden explicitly state if the category has no
1577 // options associated with it.
1578 if (IsEmptyCategory) {
1579 outs() << " This option category has no options.\n";
1582 // Loop over the options in the category and print.
1583 for (std::vector<Option *>::const_iterator
1584 Opt = CategorizedOptions[*Category].begin(),
1585 E = CategorizedOptions[*Category].end();
1587 (*Opt)->printOptionInfo(MaxArgLen);
1592 // This wraps the Uncategorizing and Categorizing printers and decides
1593 // at run time which should be invoked.
1594 class HelpPrinterWrapper {
1596 HelpPrinter &UncategorizedPrinter;
1597 CategorizedHelpPrinter &CategorizedPrinter;
1600 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
1601 CategorizedHelpPrinter &CategorizedPrinter) :
1602 UncategorizedPrinter(UncategorizedPrinter),
1603 CategorizedPrinter(CategorizedPrinter) { }
1605 // Invoke the printer.
1606 void operator=(bool Value);
1609 } // End anonymous namespace
1611 // Declare the four HelpPrinter instances that are used to print out help, or
1612 // help-hidden as an uncategorized list or in categories.
1613 static HelpPrinter UncategorizedNormalPrinter(false);
1614 static HelpPrinter UncategorizedHiddenPrinter(true);
1615 static CategorizedHelpPrinter CategorizedNormalPrinter(false);
1616 static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
1619 // Declare HelpPrinter wrappers that will decide whether or not to invoke
1620 // a categorizing help printer
1621 static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
1622 CategorizedNormalPrinter);
1623 static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
1624 CategorizedHiddenPrinter);
1626 // Define uncategorized help printers.
1627 // -help-list is hidden by default because if Option categories are being used
1628 // then -help behaves the same as -help-list.
1629 static cl::opt<HelpPrinter, true, parser<bool> >
1631 cl::desc("Display list of available options (-help-list-hidden for more)"),
1632 cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed);
1634 static cl::opt<HelpPrinter, true, parser<bool> >
1635 HLHOp("help-list-hidden",
1636 cl::desc("Display list of all available options"),
1637 cl::location(UncategorizedHiddenPrinter), cl::Hidden, cl::ValueDisallowed);
1639 // Define uncategorized/categorized help printers. These printers change their
1640 // behaviour at runtime depending on whether one or more Option categories have
1642 static cl::opt<HelpPrinterWrapper, true, parser<bool> >
1643 HOp("help", cl::desc("Display available options (-help-hidden for more)"),
1644 cl::location(WrappedNormalPrinter), cl::ValueDisallowed);
1646 static cl::opt<HelpPrinterWrapper, true, parser<bool> >
1647 HHOp("help-hidden", cl::desc("Display all available options"),
1648 cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed);
1652 static cl::opt<bool>
1653 PrintOptions("print-options",
1654 cl::desc("Print non-default options after command line parsing"),
1655 cl::Hidden, cl::init(false));
1657 static cl::opt<bool>
1658 PrintAllOptions("print-all-options",
1659 cl::desc("Print all option values after command line parsing"),
1660 cl::Hidden, cl::init(false));
1662 void HelpPrinterWrapper::operator=(bool Value) {
1666 // Decide which printer to invoke. If more than one option category is
1667 // registered then it is useful to show the categorized help instead of
1668 // uncategorized help.
1669 if (RegisteredOptionCategories->size() > 1) {
1670 // unhide -help-list option so user can have uncategorized output if they
1672 HLOp.setHiddenFlag(NotHidden);
1674 CategorizedPrinter = true; // Invoke categorized printer
1677 UncategorizedPrinter = true; // Invoke uncategorized printer
1680 // Print the value of each option.
1681 void cl::PrintOptionValues() {
1682 if (!PrintOptions && !PrintAllOptions) return;
1684 // Get all the options.
1685 SmallVector<Option*, 4> PositionalOpts;
1686 SmallVector<Option*, 4> SinkOpts;
1687 StringMap<Option*> OptMap;
1688 GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
1690 SmallVector<std::pair<const char *, Option*>, 128> Opts;
1691 sortOpts(OptMap, Opts, /*ShowHidden*/true);
1693 // Compute the maximum argument length...
1694 size_t MaxArgLen = 0;
1695 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1696 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1698 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1699 Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
1702 static void (*OverrideVersionPrinter)() = nullptr;
1704 static std::vector<void (*)()>* ExtraVersionPrinters = nullptr;
1707 class VersionPrinter {
1710 raw_ostream &OS = outs();
1711 OS << "LLVM (http://llvm.org/):\n"
1712 << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
1713 #ifdef LLVM_VERSION_INFO
1714 OS << " " << LLVM_VERSION_INFO;
1717 #ifndef __OPTIMIZE__
1718 OS << "DEBUG build";
1720 OS << "Optimized build";
1723 OS << " with assertions";
1725 std::string CPU = sys::getHostCPUName();
1726 if (CPU == "generic") CPU = "(unknown)";
1728 #if (ENABLE_TIMESTAMPS == 1)
1729 << " Built " << __DATE__ << " (" << __TIME__ << ").\n"
1731 << " Default target: " << sys::getDefaultTargetTriple() << '\n'
1732 << " Host CPU: " << CPU << '\n';
1734 void operator=(bool OptionWasSpecified) {
1735 if (!OptionWasSpecified) return;
1737 if (OverrideVersionPrinter != nullptr) {
1738 (*OverrideVersionPrinter)();
1743 // Iterate over any registered extra printers and call them to add further
1745 if (ExtraVersionPrinters != nullptr) {
1747 for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(),
1748 E = ExtraVersionPrinters->end();
1756 } // End anonymous namespace
1759 // Define the --version option that prints out the LLVM version for the tool
1760 static VersionPrinter VersionPrinterInstance;
1762 static cl::opt<VersionPrinter, true, parser<bool> >
1763 VersOp("version", cl::desc("Display the version of this program"),
1764 cl::location(VersionPrinterInstance), cl::ValueDisallowed);
1766 // Utility function for printing the help message.
1767 void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
1768 // This looks weird, but it actually prints the help message. The Printers are
1769 // types of HelpPrinter and the help gets printed when its operator= is
1770 // invoked. That's because the "normal" usages of the help printer is to be
1771 // assigned true/false depending on whether -help or -help-hidden was given or
1772 // not. Since we're circumventing that we have to make it look like -help or
1773 // -help-hidden were given, so we assign true.
1775 if (!Hidden && !Categorized)
1776 UncategorizedNormalPrinter = true;
1777 else if (!Hidden && Categorized)
1778 CategorizedNormalPrinter = true;
1779 else if (Hidden && !Categorized)
1780 UncategorizedHiddenPrinter = true;
1782 CategorizedHiddenPrinter = true;
1785 /// Utility function for printing version number.
1786 void cl::PrintVersionMessage() {
1787 VersionPrinterInstance.print();
1790 void cl::SetVersionPrinter(void (*func)()) {
1791 OverrideVersionPrinter = func;
1794 void cl::AddExtraVersionPrinter(void (*func)()) {
1795 if (!ExtraVersionPrinters)
1796 ExtraVersionPrinters = new std::vector<void (*)()>;
1798 ExtraVersionPrinters->push_back(func);
1801 void cl::getRegisteredOptions(StringMap<Option*> &Map)
1803 // Get all the options.
1804 SmallVector<Option*, 4> PositionalOpts; //NOT USED
1805 SmallVector<Option*, 4> SinkOpts; //NOT USED
1806 assert(Map.size() == 0 && "StringMap must be empty");
1807 GetOptionInfo(PositionalOpts, SinkOpts, Map);