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.
47 namespace llvm { namespace cl {
48 TEMPLATE_INSTANTIATION(class basic_parser<bool>);
49 TEMPLATE_INSTANTIATION(class basic_parser<boolOrDefault>);
50 TEMPLATE_INSTANTIATION(class basic_parser<int>);
51 TEMPLATE_INSTANTIATION(class basic_parser<unsigned>);
52 TEMPLATE_INSTANTIATION(class basic_parser<unsigned long long>);
53 TEMPLATE_INSTANTIATION(class basic_parser<double>);
54 TEMPLATE_INSTANTIATION(class basic_parser<float>);
55 TEMPLATE_INSTANTIATION(class basic_parser<std::string>);
56 TEMPLATE_INSTANTIATION(class basic_parser<char>);
58 TEMPLATE_INSTANTIATION(class opt<unsigned>);
59 TEMPLATE_INSTANTIATION(class opt<int>);
60 TEMPLATE_INSTANTIATION(class opt<std::string>);
61 TEMPLATE_INSTANTIATION(class opt<char>);
62 TEMPLATE_INSTANTIATION(class opt<bool>);
63 } } // end namespace llvm::cl
65 // Pin the vtables to this file.
66 void GenericOptionValue::anchor() {}
67 void OptionValue<boolOrDefault>::anchor() {}
68 void OptionValue<std::string>::anchor() {}
69 void Option::anchor() {}
70 void basic_parser_impl::anchor() {}
71 void parser<bool>::anchor() {}
72 void parser<boolOrDefault>::anchor() {}
73 void parser<int>::anchor() {}
74 void parser<unsigned>::anchor() {}
75 void parser<unsigned long long>::anchor() {}
76 void parser<double>::anchor() {}
77 void parser<float>::anchor() {}
78 void parser<std::string>::anchor() {}
79 void parser<char>::anchor() {}
80 void StringSaver::anchor() {}
82 //===----------------------------------------------------------------------===//
84 // Globals for name and overview of program. Program name is not a string to
85 // avoid static ctor/dtor issues.
86 static char ProgramName[80] = "<premain>";
87 static const char *ProgramOverview = nullptr;
89 // This collects additional help to be printed.
90 static ManagedStatic<std::vector<const char*> > MoreHelp;
92 extrahelp::extrahelp(const char *Help)
94 MoreHelp->push_back(Help);
97 static bool OptionListChanged = false;
99 // MarkOptionsChanged - Internal helper function.
100 void cl::MarkOptionsChanged() {
101 OptionListChanged = true;
104 /// RegisteredOptionList - This is the list of the command line options that
105 /// have statically constructed themselves.
106 static Option *RegisteredOptionList = nullptr;
108 void Option::addArgument() {
109 assert(!NextRegistered && "argument multiply registered!");
111 NextRegistered = RegisteredOptionList;
112 RegisteredOptionList = this;
113 MarkOptionsChanged();
116 void Option::removeArgument() {
117 if (RegisteredOptionList == this) {
118 RegisteredOptionList = NextRegistered;
119 MarkOptionsChanged();
122 Option *O = RegisteredOptionList;
123 for (; O->NextRegistered != this; O = O->NextRegistered)
125 O->NextRegistered = NextRegistered;
126 MarkOptionsChanged();
129 // This collects the different option categories that have been registered.
130 typedef SmallPtrSet<OptionCategory*,16> OptionCatSet;
131 static ManagedStatic<OptionCatSet> RegisteredOptionCategories;
133 // Initialise the general option category.
134 OptionCategory llvm::cl::GeneralCategory("General options");
136 void OptionCategory::registerCategory() {
137 assert(std::count_if(RegisteredOptionCategories->begin(),
138 RegisteredOptionCategories->end(),
139 [this](const OptionCategory *Category) {
140 return getName() == Category->getName();
141 }) == 0 && "Duplicate option categories");
143 RegisteredOptionCategories->insert(this);
146 //===----------------------------------------------------------------------===//
147 // Basic, shared command line option processing machinery.
150 /// GetOptionInfo - Scan the list of registered options, turning them into data
151 /// structures that are easier to handle.
152 static void GetOptionInfo(SmallVectorImpl<Option*> &PositionalOpts,
153 SmallVectorImpl<Option*> &SinkOpts,
154 StringMap<Option*> &OptionsMap) {
155 bool HadErrors = false;
156 SmallVector<const char*, 16> OptionNames;
157 Option *CAOpt = nullptr; // The ConsumeAfter option if it exists.
158 for (Option *O = RegisteredOptionList; O; O = O->getNextRegisteredOption()) {
159 // If this option wants to handle multiple option names, get the full set.
160 // This handles enum options like "-O1 -O2" etc.
161 O->getExtraOptionNames(OptionNames);
163 OptionNames.push_back(O->ArgStr);
165 // Handle named options.
166 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
167 // Add argument to the argument map!
168 if (!OptionsMap.insert(std::make_pair(OptionNames[i], O)).second) {
169 errs() << ProgramName << ": CommandLine Error: Option '"
170 << OptionNames[i] << "' registered more than once!\n";
177 // Remember information about positional options.
178 if (O->getFormattingFlag() == cl::Positional)
179 PositionalOpts.push_back(O);
180 else if (O->getMiscFlags() & cl::Sink) // Remember sink options
181 SinkOpts.push_back(O);
182 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
184 O->error("Cannot specify more than one option with cl::ConsumeAfter!");
192 PositionalOpts.push_back(CAOpt);
194 // Make sure that they are in order of registration not backwards.
195 std::reverse(PositionalOpts.begin(), PositionalOpts.end());
197 // Fail hard if there were errors. These are strictly unrecoverable and
198 // indicate serious issues such as conflicting option names or an incorrectly
199 // linked LLVM distribution.
201 report_fatal_error("inconsistency in registered CommandLine options");
205 /// LookupOption - Lookup the option specified by the specified option on the
206 /// command line. If there is a value specified (after an equal sign) return
207 /// that as well. This assumes that leading dashes have already been stripped.
208 static Option *LookupOption(StringRef &Arg, StringRef &Value,
209 const StringMap<Option*> &OptionsMap) {
210 // Reject all dashes.
211 if (Arg.empty()) return nullptr;
213 size_t EqualPos = Arg.find('=');
215 // If we have an equals sign, remember the value.
216 if (EqualPos == StringRef::npos) {
217 // Look up the option.
218 StringMap<Option*>::const_iterator I = OptionsMap.find(Arg);
219 return I != OptionsMap.end() ? I->second : nullptr;
222 // If the argument before the = is a valid option name, we match. If not,
223 // return Arg unmolested.
224 StringMap<Option*>::const_iterator I =
225 OptionsMap.find(Arg.substr(0, EqualPos));
226 if (I == OptionsMap.end()) return nullptr;
228 Value = Arg.substr(EqualPos+1);
229 Arg = Arg.substr(0, EqualPos);
233 /// LookupNearestOption - Lookup the closest match to the option specified by
234 /// the specified option on the command line. If there is a value specified
235 /// (after an equal sign) return that as well. This assumes that leading dashes
236 /// have already been stripped.
237 static Option *LookupNearestOption(StringRef Arg,
238 const StringMap<Option*> &OptionsMap,
239 std::string &NearestString) {
240 // Reject all dashes.
241 if (Arg.empty()) return nullptr;
243 // Split on any equal sign.
244 std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
245 StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
246 StringRef &RHS = SplitArg.second;
248 // Find the closest match.
249 Option *Best = nullptr;
250 unsigned BestDistance = 0;
251 for (StringMap<Option*>::const_iterator it = OptionsMap.begin(),
252 ie = OptionsMap.end(); it != ie; ++it) {
253 Option *O = it->second;
254 SmallVector<const char*, 16> OptionNames;
255 O->getExtraOptionNames(OptionNames);
257 OptionNames.push_back(O->ArgStr);
259 bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
260 StringRef Flag = PermitValue ? LHS : Arg;
261 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
262 StringRef Name = OptionNames[i];
263 unsigned Distance = StringRef(Name).edit_distance(
264 Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
265 if (!Best || Distance < BestDistance) {
267 BestDistance = Distance;
268 if (RHS.empty() || !PermitValue)
269 NearestString = OptionNames[i];
271 NearestString = std::string(OptionNames[i]) + "=" + RHS.str();
279 /// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence()
280 /// that does special handling of cl::CommaSeparated options.
281 static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos,
282 StringRef ArgName, StringRef Value,
283 bool MultiArg = false) {
284 // Check to see if this option accepts a comma separated list of values. If
285 // it does, we have to split up the value into multiple values.
286 if (Handler->getMiscFlags() & CommaSeparated) {
287 StringRef Val(Value);
288 StringRef::size_type Pos = Val.find(',');
290 while (Pos != StringRef::npos) {
291 // Process the portion before the comma.
292 if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
294 // Erase the portion before the comma, AND the comma.
295 Val = Val.substr(Pos+1);
296 Value.substr(Pos+1); // Increment the original value pointer as well.
297 // Check for another comma.
304 if (Handler->addOccurrence(pos, ArgName, Value, MultiArg))
310 /// ProvideOption - For Value, this differentiates between an empty value ("")
311 /// and a null value (StringRef()). The later is accepted for arguments that
312 /// don't allow a value (-foo) the former is rejected (-foo=).
313 static inline bool ProvideOption(Option *Handler, StringRef ArgName,
314 StringRef Value, int argc,
315 const char *const *argv, int &i) {
316 // Is this a multi-argument option?
317 unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
319 // Enforce value requirements
320 switch (Handler->getValueExpectedFlag()) {
322 if (!Value.data()) { // No value specified?
324 return Handler->error("requires a value!");
325 // Steal the next argument, like for '-o filename'
326 assert(argv && "null check");
330 case ValueDisallowed:
331 if (NumAdditionalVals > 0)
332 return Handler->error("multi-valued option specified"
333 " with ValueDisallowed modifier!");
336 return Handler->error("does not allow a value! '" +
337 Twine(Value) + "' specified.");
343 // If this isn't a multi-arg option, just run the handler.
344 if (NumAdditionalVals == 0)
345 return CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value);
347 // If it is, run the handle several times.
348 bool MultiArg = false;
351 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
357 while (NumAdditionalVals > 0) {
359 return Handler->error("not enough values!");
360 assert(argv && "null check");
363 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
371 static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
373 return ProvideOption(Handler, Handler->ArgStr, Arg, 0, nullptr, Dummy);
377 // Option predicates...
378 static inline bool isGrouping(const Option *O) {
379 return O->getFormattingFlag() == cl::Grouping;
381 static inline bool isPrefixedOrGrouping(const Option *O) {
382 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
385 // getOptionPred - Check to see if there are any options that satisfy the
386 // specified predicate with names that are the prefixes in Name. This is
387 // checked by progressively stripping characters off of the name, checking to
388 // see if there options that satisfy the predicate. If we find one, return it,
389 // otherwise return null.
391 static Option *getOptionPred(StringRef Name, size_t &Length,
392 bool (*Pred)(const Option*),
393 const StringMap<Option*> &OptionsMap) {
395 StringMap<Option*>::const_iterator OMI = OptionsMap.find(Name);
397 // Loop while we haven't found an option and Name still has at least two
398 // characters in it (so that the next iteration will not be the empty
400 while (OMI == OptionsMap.end() && Name.size() > 1) {
401 Name = Name.substr(0, Name.size()-1); // Chop off the last character.
402 OMI = OptionsMap.find(Name);
405 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
406 Length = Name.size();
407 return OMI->second; // Found one!
409 return nullptr; // No option found!
412 /// HandlePrefixedOrGroupedOption - The specified argument string (which started
413 /// with at least one '-') does not fully match an available option. Check to
414 /// see if this is a prefix or grouped option. If so, split arg into output an
415 /// Arg/Value pair and return the Option to parse it with.
416 static Option *HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
418 const StringMap<Option*> &OptionsMap) {
419 if (Arg.size() == 1) return nullptr;
423 Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
424 if (!PGOpt) return nullptr;
426 // If the option is a prefixed option, then the value is simply the
427 // rest of the name... so fall through to later processing, by
428 // setting up the argument name flags and value fields.
429 if (PGOpt->getFormattingFlag() == cl::Prefix) {
430 Value = Arg.substr(Length);
431 Arg = Arg.substr(0, Length);
432 assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
436 // This must be a grouped option... handle them now. Grouping options can't
438 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
441 // Move current arg name out of Arg into OneArgName.
442 StringRef OneArgName = Arg.substr(0, Length);
443 Arg = Arg.substr(Length);
445 // Because ValueRequired is an invalid flag for grouped arguments,
446 // we don't need to pass argc/argv in.
447 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
448 "Option can not be cl::Grouping AND cl::ValueRequired!");
450 ErrorParsing |= ProvideOption(PGOpt, OneArgName,
451 StringRef(), 0, nullptr, Dummy);
453 // Get the next grouping option.
454 PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
455 } while (PGOpt && Length != Arg.size());
457 // Return the last option with Arg cut down to just the last one.
463 static bool RequiresValue(const Option *O) {
464 return O->getNumOccurrencesFlag() == cl::Required ||
465 O->getNumOccurrencesFlag() == cl::OneOrMore;
468 static bool EatsUnboundedNumberOfValues(const Option *O) {
469 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
470 O->getNumOccurrencesFlag() == cl::OneOrMore;
473 static bool isWhitespace(char C) {
474 return strchr(" \t\n\r\f\v", C);
477 static bool isQuote(char C) {
478 return C == '\"' || C == '\'';
481 static bool isGNUSpecial(char C) {
482 return strchr("\\\"\' ", C);
485 void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
486 SmallVectorImpl<const char *> &NewArgv,
488 SmallString<128> Token;
489 for (size_t I = 0, E = Src.size(); I != E; ++I) {
490 // Consume runs of whitespace.
492 while (I != E && isWhitespace(Src[I])) {
493 // Mark the end of lines in response files
494 if (MarkEOLs && Src[I] == '\n')
495 NewArgv.push_back(nullptr);
501 // Backslashes can escape backslashes, spaces, and other quotes. Otherwise
502 // they are literal. This makes it much easier to read Windows file paths.
503 if (I + 1 < E && Src[I] == '\\' && isGNUSpecial(Src[I + 1])) {
504 ++I; // Skip the escape.
505 Token.push_back(Src[I]);
509 // Consume a quoted string.
510 if (isQuote(Src[I])) {
511 char Quote = Src[I++];
512 while (I != E && Src[I] != Quote) {
513 // Backslashes are literal, unless they escape a special character.
514 if (Src[I] == '\\' && I + 1 != E && isGNUSpecial(Src[I + 1]))
516 Token.push_back(Src[I]);
523 // End the token if this is whitespace.
524 if (isWhitespace(Src[I])) {
526 NewArgv.push_back(Saver.SaveString(Token.c_str()));
531 // This is a normal character. Append it.
532 Token.push_back(Src[I]);
535 // Append the last token after hitting EOF with no whitespace.
537 NewArgv.push_back(Saver.SaveString(Token.c_str()));
538 // Mark the end of response files
540 NewArgv.push_back(nullptr);
543 /// Backslashes are interpreted in a rather complicated way in the Windows-style
544 /// command line, because backslashes are used both to separate path and to
545 /// escape double quote. This method consumes runs of backslashes as well as the
546 /// following double quote if it's escaped.
548 /// * If an even number of backslashes is followed by a double quote, one
549 /// backslash is output for every pair of backslashes, and the last double
550 /// quote remains unconsumed. The double quote will later be interpreted as
551 /// the start or end of a quoted string in the main loop outside of this
554 /// * If an odd number of backslashes is followed by a double quote, one
555 /// backslash is output for every pair of backslashes, and a double quote is
556 /// output for the last pair of backslash-double quote. The double quote is
557 /// consumed in this case.
559 /// * Otherwise, backslashes are interpreted literally.
560 static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
561 size_t E = Src.size();
562 int BackslashCount = 0;
563 // Skip the backslashes.
567 } while (I != E && Src[I] == '\\');
569 bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
570 if (FollowedByDoubleQuote) {
571 Token.append(BackslashCount / 2, '\\');
572 if (BackslashCount % 2 == 0)
574 Token.push_back('"');
577 Token.append(BackslashCount, '\\');
581 void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
582 SmallVectorImpl<const char *> &NewArgv,
584 SmallString<128> Token;
586 // This is a small state machine to consume characters until it reaches the
587 // end of the source string.
588 enum { INIT, UNQUOTED, QUOTED } State = INIT;
589 for (size_t I = 0, E = Src.size(); I != E; ++I) {
590 // INIT state indicates that the current input index is at the start of
591 // the string or between tokens.
593 if (isWhitespace(Src[I])) {
594 // Mark the end of lines in response files
595 if (MarkEOLs && Src[I] == '\n')
596 NewArgv.push_back(nullptr);
603 if (Src[I] == '\\') {
604 I = parseBackslash(Src, I, Token);
608 Token.push_back(Src[I]);
613 // UNQUOTED state means that it's reading a token not quoted by double
615 if (State == UNQUOTED) {
616 // Whitespace means the end of the token.
617 if (isWhitespace(Src[I])) {
618 NewArgv.push_back(Saver.SaveString(Token.c_str()));
621 // Mark the end of lines in response files
622 if (MarkEOLs && Src[I] == '\n')
623 NewArgv.push_back(nullptr);
630 if (Src[I] == '\\') {
631 I = parseBackslash(Src, I, Token);
634 Token.push_back(Src[I]);
638 // QUOTED state means that it's reading a token quoted by double quotes.
639 if (State == QUOTED) {
644 if (Src[I] == '\\') {
645 I = parseBackslash(Src, I, Token);
648 Token.push_back(Src[I]);
651 // Append the last token after hitting EOF with no whitespace.
653 NewArgv.push_back(Saver.SaveString(Token.c_str()));
654 // Mark the end of response files
656 NewArgv.push_back(nullptr);
659 static bool ExpandResponseFile(const char *FName, StringSaver &Saver,
660 TokenizerCallback Tokenizer,
661 SmallVectorImpl<const char *> &NewArgv,
662 bool MarkEOLs = false) {
663 ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
664 MemoryBuffer::getFile(FName);
667 MemoryBuffer &MemBuf = *MemBufOrErr.get();
668 StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize());
670 // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
671 ArrayRef<char> BufRef(MemBuf.getBufferStart(), MemBuf.getBufferEnd());
673 if (hasUTF16ByteOrderMark(BufRef)) {
674 if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
676 Str = StringRef(UTF8Buf);
679 // Tokenize the contents into NewArgv.
680 Tokenizer(Str, Saver, NewArgv, MarkEOLs);
685 /// \brief Expand response files on a command line recursively using the given
686 /// StringSaver and tokenization strategy.
687 bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
688 SmallVectorImpl<const char *> &Argv,
690 unsigned RspFiles = 0;
691 bool AllExpanded = true;
693 // Don't cache Argv.size() because it can change.
694 for (unsigned I = 0; I != Argv.size(); ) {
695 const char *Arg = Argv[I];
696 // Check if it is an EOL marker
697 if (Arg == nullptr) {
706 // If we have too many response files, leave some unexpanded. This avoids
707 // crashing on self-referential response files.
711 // Replace this response file argument with the tokenization of its
712 // contents. Nested response files are expanded in subsequent iterations.
713 // FIXME: If a nested response file uses a relative path, is it relative to
714 // the cwd of the process or the response file?
715 SmallVector<const char *, 0> ExpandedArgv;
716 if (!ExpandResponseFile(Arg + 1, Saver, Tokenizer, ExpandedArgv,
718 // We couldn't read this file, so we leave it in the argument stream and
724 Argv.erase(Argv.begin() + I);
725 Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
731 class StrDupSaver : public StringSaver {
732 std::vector<char*> Dups;
735 for (std::vector<char *>::iterator I = Dups.begin(), E = Dups.end();
741 const char *SaveString(const char *Str) override {
742 char *Dup = strdup(Str);
749 /// ParseEnvironmentOptions - An alternative entry point to the
750 /// CommandLine library, which allows you to read the program's name
751 /// from the caller (as PROGNAME) and its command-line arguments from
752 /// an environment variable (whose name is given in ENVVAR).
754 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
755 const char *Overview) {
757 assert(progName && "Program name not specified");
758 assert(envVar && "Environment variable name missing");
760 // Get the environment variable they want us to parse options out of.
761 const char *envValue = getenv(envVar);
765 // Get program's "name", which we wouldn't know without the caller
767 SmallVector<const char *, 20> newArgv;
769 newArgv.push_back(Saver.SaveString(progName));
771 // Parse the value of the environment variable into a "command line"
772 // and hand it off to ParseCommandLineOptions().
773 TokenizeGNUCommandLine(envValue, Saver, newArgv);
774 int newArgc = static_cast<int>(newArgv.size());
775 ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
778 void cl::ParseCommandLineOptions(int argc, const char * const *argv,
779 const char *Overview) {
780 // Process all registered options.
781 SmallVector<Option*, 4> PositionalOpts;
782 SmallVector<Option*, 4> SinkOpts;
783 StringMap<Option*> Opts;
784 GetOptionInfo(PositionalOpts, SinkOpts, Opts);
786 assert((!Opts.empty() || !PositionalOpts.empty()) &&
787 "No options specified!");
789 // Expand response files.
790 SmallVector<const char *, 20> newArgv;
791 for (int i = 0; i != argc; ++i)
792 newArgv.push_back(argv[i]);
794 ExpandResponseFiles(Saver, TokenizeGNUCommandLine, newArgv);
796 argc = static_cast<int>(newArgv.size());
798 // Copy the program name into ProgName, making sure not to overflow it.
799 StringRef ProgName = sys::path::filename(argv[0]);
800 size_t Len = std::min(ProgName.size(), size_t(79));
801 memcpy(ProgramName, ProgName.data(), Len);
802 ProgramName[Len] = '\0';
804 ProgramOverview = Overview;
805 bool ErrorParsing = false;
807 // Check out the positional arguments to collect information about them.
808 unsigned NumPositionalRequired = 0;
810 // Determine whether or not there are an unlimited number of positionals
811 bool HasUnlimitedPositionals = false;
813 Option *ConsumeAfterOpt = nullptr;
814 if (!PositionalOpts.empty()) {
815 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
816 assert(PositionalOpts.size() > 1 &&
817 "Cannot specify cl::ConsumeAfter without a positional argument!");
818 ConsumeAfterOpt = PositionalOpts[0];
821 // Calculate how many positional values are _required_.
822 bool UnboundedFound = false;
823 for (size_t i = ConsumeAfterOpt ? 1 : 0, e = PositionalOpts.size();
825 Option *Opt = PositionalOpts[i];
826 if (RequiresValue(Opt))
827 ++NumPositionalRequired;
828 else if (ConsumeAfterOpt) {
829 // ConsumeAfter cannot be combined with "optional" positional options
830 // unless there is only one positional argument...
831 if (PositionalOpts.size() > 2)
833 Opt->error("error - this positional option will never be matched, "
834 "because it does not Require a value, and a "
835 "cl::ConsumeAfter option is active!");
836 } else if (UnboundedFound && !Opt->ArgStr[0]) {
837 // This option does not "require" a value... Make sure this option is
838 // not specified after an option that eats all extra arguments, or this
839 // one will never get any!
841 ErrorParsing |= Opt->error("error - option can never match, because "
842 "another positional argument will match an "
843 "unbounded number of values, and this option"
844 " does not require a value!");
846 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
848 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
851 // PositionalVals - A vector of "positional" arguments we accumulate into
852 // the process at the end.
854 SmallVector<std::pair<StringRef,unsigned>, 4> PositionalVals;
856 // If the program has named positional arguments, and the name has been run
857 // across, keep track of which positional argument was named. Otherwise put
858 // the positional args into the PositionalVals list...
859 Option *ActivePositionalArg = nullptr;
861 // Loop over all of the arguments... processing them.
862 bool DashDashFound = false; // Have we read '--'?
863 for (int i = 1; i < argc; ++i) {
864 Option *Handler = nullptr;
865 Option *NearestHandler = nullptr;
866 std::string NearestHandlerString;
868 StringRef ArgName = "";
870 // If the option list changed, this means that some command line
871 // option has just been registered or deregistered. This can occur in
872 // response to things like -load, etc. If this happens, rescan the options.
873 if (OptionListChanged) {
874 PositionalOpts.clear();
877 GetOptionInfo(PositionalOpts, SinkOpts, Opts);
878 OptionListChanged = false;
881 // Check to see if this is a positional argument. This argument is
882 // considered to be positional if it doesn't start with '-', if it is "-"
883 // itself, or if we have seen "--" already.
885 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
886 // Positional argument!
887 if (ActivePositionalArg) {
888 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
889 continue; // We are done!
892 if (!PositionalOpts.empty()) {
893 PositionalVals.push_back(std::make_pair(argv[i],i));
895 // All of the positional arguments have been fulfulled, give the rest to
896 // the consume after option... if it's specified...
898 if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) {
899 for (++i; i < argc; ++i)
900 PositionalVals.push_back(std::make_pair(argv[i],i));
901 break; // Handle outside of the argument processing loop...
904 // Delay processing positional arguments until the end...
907 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
909 DashDashFound = true; // This is the mythical "--"?
910 continue; // Don't try to process it as an argument itself.
911 } else if (ActivePositionalArg &&
912 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
913 // If there is a positional argument eating options, check to see if this
914 // option is another positional argument. If so, treat it as an argument,
915 // otherwise feed it to the eating positional.
917 // Eat leading dashes.
918 while (!ArgName.empty() && ArgName[0] == '-')
919 ArgName = ArgName.substr(1);
921 Handler = LookupOption(ArgName, Value, Opts);
922 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
923 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
924 continue; // We are done!
927 } else { // We start with a '-', must be an argument.
929 // Eat leading dashes.
930 while (!ArgName.empty() && ArgName[0] == '-')
931 ArgName = ArgName.substr(1);
933 Handler = LookupOption(ArgName, Value, Opts);
935 // Check to see if this "option" is really a prefixed or grouped argument.
937 Handler = HandlePrefixedOrGroupedOption(ArgName, Value,
940 // Otherwise, look for the closest available option to report to the user
941 // in the upcoming error.
942 if (!Handler && SinkOpts.empty())
943 NearestHandler = LookupNearestOption(ArgName, Opts,
944 NearestHandlerString);
948 if (SinkOpts.empty()) {
949 errs() << ProgramName << ": Unknown command line argument '"
950 << argv[i] << "'. Try: '" << argv[0] << " -help'\n";
952 if (NearestHandler) {
953 // If we know a near match, report it as well.
954 errs() << ProgramName << ": Did you mean '-"
955 << NearestHandlerString << "'?\n";
960 for (SmallVectorImpl<Option*>::iterator I = SinkOpts.begin(),
961 E = SinkOpts.end(); I != E ; ++I)
962 (*I)->addOccurrence(i, "", argv[i]);
967 // If this is a named positional argument, just remember that it is the
969 if (Handler->getFormattingFlag() == cl::Positional)
970 ActivePositionalArg = Handler;
972 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
975 // Check and handle positional arguments now...
976 if (NumPositionalRequired > PositionalVals.size()) {
977 errs() << ProgramName
978 << ": Not enough positional command line arguments specified!\n"
979 << "Must specify at least " << NumPositionalRequired
980 << " positional arguments: See: " << argv[0] << " -help\n";
983 } else if (!HasUnlimitedPositionals &&
984 PositionalVals.size() > PositionalOpts.size()) {
985 errs() << ProgramName
986 << ": Too many positional arguments specified!\n"
987 << "Can specify at most " << PositionalOpts.size()
988 << " positional arguments: See: " << argv[0] << " -help\n";
991 } else if (!ConsumeAfterOpt) {
992 // Positional args have already been handled if ConsumeAfter is specified.
993 unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
994 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
995 if (RequiresValue(PositionalOpts[i])) {
996 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
997 PositionalVals[ValNo].second);
999 --NumPositionalRequired; // We fulfilled our duty...
1002 // If we _can_ give this option more arguments, do so now, as long as we
1003 // do not give it values that others need. 'Done' controls whether the
1004 // option even _WANTS_ any more.
1006 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
1007 while (NumVals-ValNo > NumPositionalRequired && !Done) {
1008 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
1010 Done = true; // Optional arguments want _at most_ one value
1012 case cl::ZeroOrMore: // Zero or more will take all they can get...
1013 case cl::OneOrMore: // One or more will take all they can get...
1014 ProvidePositionalOption(PositionalOpts[i],
1015 PositionalVals[ValNo].first,
1016 PositionalVals[ValNo].second);
1020 llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
1021 "positional argument processing!");
1026 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
1028 for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
1029 if (RequiresValue(PositionalOpts[j])) {
1030 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
1031 PositionalVals[ValNo].first,
1032 PositionalVals[ValNo].second);
1036 // Handle the case where there is just one positional option, and it's
1037 // optional. In this case, we want to give JUST THE FIRST option to the
1038 // positional option and keep the rest for the consume after. The above
1039 // loop would have assigned no values to positional options in this case.
1041 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
1042 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
1043 PositionalVals[ValNo].first,
1044 PositionalVals[ValNo].second);
1048 // Handle over all of the rest of the arguments to the
1049 // cl::ConsumeAfter command line option...
1050 for (; ValNo != PositionalVals.size(); ++ValNo)
1051 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
1052 PositionalVals[ValNo].first,
1053 PositionalVals[ValNo].second);
1056 // Loop over args and make sure all required args are specified!
1057 for (const auto &Opt : Opts) {
1058 switch (Opt.second->getNumOccurrencesFlag()) {
1061 if (Opt.second->getNumOccurrences() == 0) {
1062 Opt.second->error("must be specified at least once!");
1063 ErrorParsing = true;
1071 // Now that we know if -debug is specified, we can use it.
1072 // Note that if ReadResponseFiles == true, this must be done before the
1073 // memory allocated for the expanded command line is free()d below.
1074 DEBUG(dbgs() << "Args: ";
1075 for (int i = 0; i < argc; ++i)
1076 dbgs() << argv[i] << ' ';
1080 // Free all of the memory allocated to the map. Command line options may only
1081 // be processed once!
1083 PositionalOpts.clear();
1086 // If we had an error processing our arguments, don't let the program execute
1087 if (ErrorParsing) exit(1);
1090 //===----------------------------------------------------------------------===//
1091 // Option Base class implementation
1094 bool Option::error(const Twine &Message, StringRef ArgName) {
1095 if (!ArgName.data()) ArgName = ArgStr;
1096 if (ArgName.empty())
1097 errs() << HelpStr; // Be nice for positional arguments
1099 errs() << ProgramName << ": for the -" << ArgName;
1101 errs() << " option: " << Message << "\n";
1105 bool Option::addOccurrence(unsigned pos, StringRef ArgName,
1106 StringRef Value, bool MultiArg) {
1108 NumOccurrences++; // Increment the number of times we have been seen
1110 switch (getNumOccurrencesFlag()) {
1112 if (NumOccurrences > 1)
1113 return error("may only occur zero or one times!", ArgName);
1116 if (NumOccurrences > 1)
1117 return error("must occur exactly one time!", ArgName);
1121 case ConsumeAfter: break;
1124 return handleOccurrence(pos, ArgName, Value);
1128 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
1129 // has been specified yet.
1131 static const char *getValueStr(const Option &O, const char *DefaultMsg) {
1132 if (O.ValueStr[0] == 0) return DefaultMsg;
1136 //===----------------------------------------------------------------------===//
1137 // cl::alias class implementation
1140 // Return the width of the option tag for printing...
1141 size_t alias::getOptionWidth() const {
1142 return std::strlen(ArgStr)+6;
1145 static void printHelpStr(StringRef HelpStr, size_t Indent,
1146 size_t FirstLineIndentedBy) {
1147 std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1148 outs().indent(Indent - FirstLineIndentedBy) << " - " << Split.first << "\n";
1149 while (!Split.second.empty()) {
1150 Split = Split.second.split('\n');
1151 outs().indent(Indent) << Split.first << "\n";
1155 // Print out the option for the alias.
1156 void alias::printOptionInfo(size_t GlobalWidth) const {
1157 outs() << " -" << ArgStr;
1158 printHelpStr(HelpStr, GlobalWidth, std::strlen(ArgStr) + 6);
1161 //===----------------------------------------------------------------------===//
1162 // Parser Implementation code...
1165 // basic_parser implementation
1168 // Return the width of the option tag for printing...
1169 size_t basic_parser_impl::getOptionWidth(const Option &O) const {
1170 size_t Len = std::strlen(O.ArgStr);
1171 if (const char *ValName = getValueName())
1172 Len += std::strlen(getValueStr(O, ValName))+3;
1177 // printOptionInfo - Print out information about this option. The
1178 // to-be-maintained width is specified.
1180 void basic_parser_impl::printOptionInfo(const Option &O,
1181 size_t GlobalWidth) const {
1182 outs() << " -" << O.ArgStr;
1184 if (const char *ValName = getValueName())
1185 outs() << "=<" << getValueStr(O, ValName) << '>';
1187 printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
1190 void basic_parser_impl::printOptionName(const Option &O,
1191 size_t GlobalWidth) const {
1192 outs() << " -" << O.ArgStr;
1193 outs().indent(GlobalWidth-std::strlen(O.ArgStr));
1197 // parser<bool> implementation
1199 bool parser<bool>::parse(Option &O, StringRef ArgName,
1200 StringRef Arg, bool &Value) {
1201 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1207 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1211 return O.error("'" + Arg +
1212 "' is invalid value for boolean argument! Try 0 or 1");
1215 // parser<boolOrDefault> implementation
1217 bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName,
1218 StringRef Arg, boolOrDefault &Value) {
1219 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1224 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1229 return O.error("'" + Arg +
1230 "' is invalid value for boolean argument! Try 0 or 1");
1233 // parser<int> implementation
1235 bool parser<int>::parse(Option &O, StringRef ArgName,
1236 StringRef Arg, int &Value) {
1237 if (Arg.getAsInteger(0, Value))
1238 return O.error("'" + Arg + "' value invalid for integer argument!");
1242 // parser<unsigned> implementation
1244 bool parser<unsigned>::parse(Option &O, StringRef ArgName,
1245 StringRef Arg, unsigned &Value) {
1247 if (Arg.getAsInteger(0, Value))
1248 return O.error("'" + Arg + "' value invalid for uint argument!");
1252 // parser<unsigned long long> implementation
1254 bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
1255 StringRef Arg, unsigned long long &Value){
1257 if (Arg.getAsInteger(0, Value))
1258 return O.error("'" + Arg + "' value invalid for uint argument!");
1262 // parser<double>/parser<float> implementation
1264 static bool parseDouble(Option &O, StringRef Arg, double &Value) {
1265 SmallString<32> TmpStr(Arg.begin(), Arg.end());
1266 const char *ArgStart = TmpStr.c_str();
1268 Value = strtod(ArgStart, &End);
1270 return O.error("'" + Arg + "' value invalid for floating point argument!");
1274 bool parser<double>::parse(Option &O, StringRef ArgName,
1275 StringRef Arg, double &Val) {
1276 return parseDouble(O, Arg, Val);
1279 bool parser<float>::parse(Option &O, StringRef ArgName,
1280 StringRef Arg, float &Val) {
1282 if (parseDouble(O, Arg, dVal))
1290 // generic_parser_base implementation
1293 // findOption - Return the option number corresponding to the specified
1294 // argument string. If the option is not found, getNumOptions() is returned.
1296 unsigned generic_parser_base::findOption(const char *Name) {
1297 unsigned e = getNumOptions();
1299 for (unsigned i = 0; i != e; ++i) {
1300 if (strcmp(getOption(i), Name) == 0)
1307 // Return the width of the option tag for printing...
1308 size_t generic_parser_base::getOptionWidth(const Option &O) const {
1309 if (O.hasArgStr()) {
1310 size_t Size = std::strlen(O.ArgStr)+6;
1311 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1312 Size = std::max(Size, std::strlen(getOption(i))+8);
1315 size_t BaseSize = 0;
1316 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1317 BaseSize = std::max(BaseSize, std::strlen(getOption(i))+8);
1322 // printOptionInfo - Print out information about this option. The
1323 // to-be-maintained width is specified.
1325 void generic_parser_base::printOptionInfo(const Option &O,
1326 size_t GlobalWidth) const {
1327 if (O.hasArgStr()) {
1328 outs() << " -" << O.ArgStr;
1329 printHelpStr(O.HelpStr, GlobalWidth, std::strlen(O.ArgStr) + 6);
1331 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1332 size_t NumSpaces = GlobalWidth-strlen(getOption(i))-8;
1333 outs() << " =" << getOption(i);
1334 outs().indent(NumSpaces) << " - " << getDescription(i) << '\n';
1338 outs() << " " << O.HelpStr << '\n';
1339 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1340 const char *Option = getOption(i);
1341 outs() << " -" << Option;
1342 printHelpStr(getDescription(i), GlobalWidth, std::strlen(Option) + 8);
1347 static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1349 // printGenericOptionDiff - Print the value of this option and it's default.
1351 // "Generic" options have each value mapped to a name.
1352 void generic_parser_base::
1353 printGenericOptionDiff(const Option &O, const GenericOptionValue &Value,
1354 const GenericOptionValue &Default,
1355 size_t GlobalWidth) const {
1356 outs() << " -" << O.ArgStr;
1357 outs().indent(GlobalWidth-std::strlen(O.ArgStr));
1359 unsigned NumOpts = getNumOptions();
1360 for (unsigned i = 0; i != NumOpts; ++i) {
1361 if (Value.compare(getOptionValue(i)))
1364 outs() << "= " << getOption(i);
1365 size_t L = std::strlen(getOption(i));
1366 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1367 outs().indent(NumSpaces) << " (default: ";
1368 for (unsigned j = 0; j != NumOpts; ++j) {
1369 if (Default.compare(getOptionValue(j)))
1371 outs() << getOption(j);
1377 outs() << "= *unknown option value*\n";
1380 // printOptionDiff - Specializations for printing basic value types.
1382 #define PRINT_OPT_DIFF(T) \
1384 printOptionDiff(const Option &O, T V, OptionValue<T> D, \
1385 size_t GlobalWidth) const { \
1386 printOptionName(O, GlobalWidth); \
1389 raw_string_ostream SS(Str); \
1392 outs() << "= " << Str; \
1393 size_t NumSpaces = MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0;\
1394 outs().indent(NumSpaces) << " (default: "; \
1396 outs() << D.getValue(); \
1398 outs() << "*no default*"; \
1402 PRINT_OPT_DIFF(bool)
1403 PRINT_OPT_DIFF(boolOrDefault)
1405 PRINT_OPT_DIFF(unsigned)
1406 PRINT_OPT_DIFF(unsigned long long)
1407 PRINT_OPT_DIFF(double)
1408 PRINT_OPT_DIFF(float)
1409 PRINT_OPT_DIFF(char)
1411 void parser<std::string>::
1412 printOptionDiff(const Option &O, StringRef V, OptionValue<std::string> D,
1413 size_t GlobalWidth) const {
1414 printOptionName(O, GlobalWidth);
1415 outs() << "= " << V;
1416 size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
1417 outs().indent(NumSpaces) << " (default: ";
1419 outs() << D.getValue();
1421 outs() << "*no default*";
1425 // Print a placeholder for options that don't yet support printOptionDiff().
1426 void basic_parser_impl::
1427 printOptionNoValue(const Option &O, size_t GlobalWidth) const {
1428 printOptionName(O, GlobalWidth);
1429 outs() << "= *cannot print option value*\n";
1432 //===----------------------------------------------------------------------===//
1433 // -help and -help-hidden option implementation
1436 static int OptNameCompare(const void *LHS, const void *RHS) {
1437 typedef std::pair<const char *, Option*> pair_ty;
1439 return strcmp(((const pair_ty*)LHS)->first, ((const pair_ty*)RHS)->first);
1442 // Copy Options into a vector so we can sort them as we like.
1444 sortOpts(StringMap<Option*> &OptMap,
1445 SmallVectorImpl< std::pair<const char *, Option*> > &Opts,
1447 SmallPtrSet<Option*, 128> OptionSet; // Duplicate option detection.
1449 for (StringMap<Option*>::iterator I = OptMap.begin(), E = OptMap.end();
1451 // Ignore really-hidden options.
1452 if (I->second->getOptionHiddenFlag() == ReallyHidden)
1455 // Unless showhidden is set, ignore hidden flags.
1456 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
1459 // If we've already seen this option, don't add it to the list again.
1460 if (!OptionSet.insert(I->second).second)
1463 Opts.push_back(std::pair<const char *, Option*>(I->getKey().data(),
1467 // Sort the options list alphabetically.
1468 qsort(Opts.data(), Opts.size(), sizeof(Opts[0]), OptNameCompare);
1475 const bool ShowHidden;
1476 typedef SmallVector<std::pair<const char *, Option*>,128> StrOptionPairVector;
1477 // Print the options. Opts is assumed to be alphabetically sorted.
1478 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1479 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1480 Opts[i].second->printOptionInfo(MaxArgLen);
1484 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
1485 virtual ~HelpPrinter() {}
1487 // Invoke the printer.
1488 void operator=(bool Value) {
1489 if (Value == false) return;
1491 // Get all the options.
1492 SmallVector<Option*, 4> PositionalOpts;
1493 SmallVector<Option*, 4> SinkOpts;
1494 StringMap<Option*> OptMap;
1495 GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
1497 StrOptionPairVector Opts;
1498 sortOpts(OptMap, Opts, ShowHidden);
1500 if (ProgramOverview)
1501 outs() << "OVERVIEW: " << ProgramOverview << "\n";
1503 outs() << "USAGE: " << ProgramName << " [options]";
1505 // Print out the positional options.
1506 Option *CAOpt = nullptr; // The cl::ConsumeAfter option, if it exists...
1507 if (!PositionalOpts.empty() &&
1508 PositionalOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
1509 CAOpt = PositionalOpts[0];
1511 for (size_t i = CAOpt != nullptr, e = PositionalOpts.size(); i != e; ++i) {
1512 if (PositionalOpts[i]->ArgStr[0])
1513 outs() << " --" << PositionalOpts[i]->ArgStr;
1514 outs() << " " << PositionalOpts[i]->HelpStr;
1517 // Print the consume after option info if it exists...
1518 if (CAOpt) outs() << " " << CAOpt->HelpStr;
1522 // Compute the maximum argument length...
1523 size_t MaxArgLen = 0;
1524 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1525 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1527 outs() << "OPTIONS:\n";
1528 printOptions(Opts, MaxArgLen);
1530 // Print any extra help the user has declared.
1531 for (std::vector<const char *>::iterator I = MoreHelp->begin(),
1532 E = MoreHelp->end();
1537 // Halt the program since help information was printed
1542 class CategorizedHelpPrinter : public HelpPrinter {
1544 explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
1546 // Helper function for printOptions().
1547 // It shall return true if A's name should be lexographically
1548 // ordered before B's name. It returns false otherwise.
1549 static bool OptionCategoryCompare(OptionCategory *A, OptionCategory *B) {
1550 return strcmp(A->getName(), B->getName()) < 0;
1553 // Make sure we inherit our base class's operator=()
1554 using HelpPrinter::operator= ;
1557 void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override {
1558 std::vector<OptionCategory *> SortedCategories;
1559 std::map<OptionCategory *, std::vector<Option *> > CategorizedOptions;
1561 // Collect registered option categories into vector in preparation for
1563 for (OptionCatSet::const_iterator I = RegisteredOptionCategories->begin(),
1564 E = RegisteredOptionCategories->end();
1566 SortedCategories.push_back(*I);
1569 // Sort the different option categories alphabetically.
1570 assert(SortedCategories.size() > 0 && "No option categories registered!");
1571 std::sort(SortedCategories.begin(), SortedCategories.end(),
1572 OptionCategoryCompare);
1574 // Create map to empty vectors.
1575 for (std::vector<OptionCategory *>::const_iterator
1576 I = SortedCategories.begin(),
1577 E = SortedCategories.end();
1579 CategorizedOptions[*I] = std::vector<Option *>();
1581 // Walk through pre-sorted options and assign into categories.
1582 // Because the options are already alphabetically sorted the
1583 // options within categories will also be alphabetically sorted.
1584 for (size_t I = 0, E = Opts.size(); I != E; ++I) {
1585 Option *Opt = Opts[I].second;
1586 assert(CategorizedOptions.count(Opt->Category) > 0 &&
1587 "Option has an unregistered category");
1588 CategorizedOptions[Opt->Category].push_back(Opt);
1592 for (std::vector<OptionCategory *>::const_iterator
1593 Category = SortedCategories.begin(),
1594 E = SortedCategories.end();
1595 Category != E; ++Category) {
1596 // Hide empty categories for -help, but show for -help-hidden.
1597 bool IsEmptyCategory = CategorizedOptions[*Category].size() == 0;
1598 if (!ShowHidden && IsEmptyCategory)
1601 // Print category information.
1603 outs() << (*Category)->getName() << ":\n";
1605 // Check if description is set.
1606 if ((*Category)->getDescription() != nullptr)
1607 outs() << (*Category)->getDescription() << "\n\n";
1611 // When using -help-hidden explicitly state if the category has no
1612 // options associated with it.
1613 if (IsEmptyCategory) {
1614 outs() << " This option category has no options.\n";
1617 // Loop over the options in the category and print.
1618 for (std::vector<Option *>::const_iterator
1619 Opt = CategorizedOptions[*Category].begin(),
1620 E = CategorizedOptions[*Category].end();
1622 (*Opt)->printOptionInfo(MaxArgLen);
1627 // This wraps the Uncategorizing and Categorizing printers and decides
1628 // at run time which should be invoked.
1629 class HelpPrinterWrapper {
1631 HelpPrinter &UncategorizedPrinter;
1632 CategorizedHelpPrinter &CategorizedPrinter;
1635 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
1636 CategorizedHelpPrinter &CategorizedPrinter) :
1637 UncategorizedPrinter(UncategorizedPrinter),
1638 CategorizedPrinter(CategorizedPrinter) { }
1640 // Invoke the printer.
1641 void operator=(bool Value);
1644 } // End anonymous namespace
1646 // Declare the four HelpPrinter instances that are used to print out help, or
1647 // help-hidden as an uncategorized list or in categories.
1648 static HelpPrinter UncategorizedNormalPrinter(false);
1649 static HelpPrinter UncategorizedHiddenPrinter(true);
1650 static CategorizedHelpPrinter CategorizedNormalPrinter(false);
1651 static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
1654 // Declare HelpPrinter wrappers that will decide whether or not to invoke
1655 // a categorizing help printer
1656 static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
1657 CategorizedNormalPrinter);
1658 static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
1659 CategorizedHiddenPrinter);
1661 // Define uncategorized help printers.
1662 // -help-list is hidden by default because if Option categories are being used
1663 // then -help behaves the same as -help-list.
1664 static cl::opt<HelpPrinter, true, parser<bool> >
1666 cl::desc("Display list of available options (-help-list-hidden for more)"),
1667 cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed);
1669 static cl::opt<HelpPrinter, true, parser<bool> >
1670 HLHOp("help-list-hidden",
1671 cl::desc("Display list of all available options"),
1672 cl::location(UncategorizedHiddenPrinter), cl::Hidden, cl::ValueDisallowed);
1674 // Define uncategorized/categorized help printers. These printers change their
1675 // behaviour at runtime depending on whether one or more Option categories have
1677 static cl::opt<HelpPrinterWrapper, true, parser<bool> >
1678 HOp("help", cl::desc("Display available options (-help-hidden for more)"),
1679 cl::location(WrappedNormalPrinter), cl::ValueDisallowed);
1681 static cl::opt<HelpPrinterWrapper, true, parser<bool> >
1682 HHOp("help-hidden", cl::desc("Display all available options"),
1683 cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed);
1687 static cl::opt<bool>
1688 PrintOptions("print-options",
1689 cl::desc("Print non-default options after command line parsing"),
1690 cl::Hidden, cl::init(false));
1692 static cl::opt<bool>
1693 PrintAllOptions("print-all-options",
1694 cl::desc("Print all option values after command line parsing"),
1695 cl::Hidden, cl::init(false));
1697 void HelpPrinterWrapper::operator=(bool Value) {
1701 // Decide which printer to invoke. If more than one option category is
1702 // registered then it is useful to show the categorized help instead of
1703 // uncategorized help.
1704 if (RegisteredOptionCategories->size() > 1) {
1705 // unhide -help-list option so user can have uncategorized output if they
1707 HLOp.setHiddenFlag(NotHidden);
1709 CategorizedPrinter = true; // Invoke categorized printer
1712 UncategorizedPrinter = true; // Invoke uncategorized printer
1715 // Print the value of each option.
1716 void cl::PrintOptionValues() {
1717 if (!PrintOptions && !PrintAllOptions) return;
1719 // Get all the options.
1720 SmallVector<Option*, 4> PositionalOpts;
1721 SmallVector<Option*, 4> SinkOpts;
1722 StringMap<Option*> OptMap;
1723 GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
1725 SmallVector<std::pair<const char *, Option*>, 128> Opts;
1726 sortOpts(OptMap, Opts, /*ShowHidden*/true);
1728 // Compute the maximum argument length...
1729 size_t MaxArgLen = 0;
1730 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1731 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1733 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1734 Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
1737 static void (*OverrideVersionPrinter)() = nullptr;
1739 static std::vector<void (*)()>* ExtraVersionPrinters = nullptr;
1742 class VersionPrinter {
1745 raw_ostream &OS = outs();
1746 OS << "LLVM (http://llvm.org/):\n"
1747 << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
1748 #ifdef LLVM_VERSION_INFO
1749 OS << " " << LLVM_VERSION_INFO;
1752 #ifndef __OPTIMIZE__
1753 OS << "DEBUG build";
1755 OS << "Optimized build";
1758 OS << " with assertions";
1760 std::string CPU = sys::getHostCPUName();
1761 if (CPU == "generic") CPU = "(unknown)";
1763 #if (ENABLE_TIMESTAMPS == 1)
1764 << " Built " << __DATE__ << " (" << __TIME__ << ").\n"
1766 << " Default target: " << sys::getDefaultTargetTriple() << '\n'
1767 << " Host CPU: " << CPU << '\n';
1769 void operator=(bool OptionWasSpecified) {
1770 if (!OptionWasSpecified) return;
1772 if (OverrideVersionPrinter != nullptr) {
1773 (*OverrideVersionPrinter)();
1778 // Iterate over any registered extra printers and call them to add further
1780 if (ExtraVersionPrinters != nullptr) {
1782 for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(),
1783 E = ExtraVersionPrinters->end();
1791 } // End anonymous namespace
1794 // Define the --version option that prints out the LLVM version for the tool
1795 static VersionPrinter VersionPrinterInstance;
1797 static cl::opt<VersionPrinter, true, parser<bool> >
1798 VersOp("version", cl::desc("Display the version of this program"),
1799 cl::location(VersionPrinterInstance), cl::ValueDisallowed);
1801 // Utility function for printing the help message.
1802 void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
1803 // This looks weird, but it actually prints the help message. The Printers are
1804 // types of HelpPrinter and the help gets printed when its operator= is
1805 // invoked. That's because the "normal" usages of the help printer is to be
1806 // assigned true/false depending on whether -help or -help-hidden was given or
1807 // not. Since we're circumventing that we have to make it look like -help or
1808 // -help-hidden were given, so we assign true.
1810 if (!Hidden && !Categorized)
1811 UncategorizedNormalPrinter = true;
1812 else if (!Hidden && Categorized)
1813 CategorizedNormalPrinter = true;
1814 else if (Hidden && !Categorized)
1815 UncategorizedHiddenPrinter = true;
1817 CategorizedHiddenPrinter = true;
1820 /// Utility function for printing version number.
1821 void cl::PrintVersionMessage() {
1822 VersionPrinterInstance.print();
1825 void cl::SetVersionPrinter(void (*func)()) {
1826 OverrideVersionPrinter = func;
1829 void cl::AddExtraVersionPrinter(void (*func)()) {
1830 if (!ExtraVersionPrinters)
1831 ExtraVersionPrinters = new std::vector<void (*)()>;
1833 ExtraVersionPrinters->push_back(func);
1836 void cl::getRegisteredOptions(StringMap<Option*> &Map)
1838 // Get all the options.
1839 SmallVector<Option*, 4> PositionalOpts; //NOT USED
1840 SmallVector<Option*, 4> SinkOpts; //NOT USED
1841 assert(Map.size() == 0 && "StringMap must be empty");
1842 GetOptionInfo(PositionalOpts, SinkOpts, Map);
1846 void LLVMParseCommandLineOptions(int argc, const char *const *argv,
1847 const char *Overview) {
1848 llvm::cl::ParseCommandLineOptions(argc, argv, Overview);