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'
329 case ValueDisallowed:
330 if (NumAdditionalVals > 0)
331 return Handler->error("multi-valued option specified"
332 " with ValueDisallowed modifier!");
335 return Handler->error("does not allow a value! '" +
336 Twine(Value) + "' specified.");
342 // If this isn't a multi-arg option, just run the handler.
343 if (NumAdditionalVals == 0)
344 return CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value);
346 // If it is, run the handle several times.
347 bool MultiArg = false;
350 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
356 while (NumAdditionalVals > 0) {
358 return Handler->error("not enough values!");
361 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
369 static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
371 return ProvideOption(Handler, Handler->ArgStr, Arg, 0, nullptr, Dummy);
375 // Option predicates...
376 static inline bool isGrouping(const Option *O) {
377 return O->getFormattingFlag() == cl::Grouping;
379 static inline bool isPrefixedOrGrouping(const Option *O) {
380 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
383 // getOptionPred - Check to see if there are any options that satisfy the
384 // specified predicate with names that are the prefixes in Name. This is
385 // checked by progressively stripping characters off of the name, checking to
386 // see if there options that satisfy the predicate. If we find one, return it,
387 // otherwise return null.
389 static Option *getOptionPred(StringRef Name, size_t &Length,
390 bool (*Pred)(const Option*),
391 const StringMap<Option*> &OptionsMap) {
393 StringMap<Option*>::const_iterator OMI = OptionsMap.find(Name);
395 // Loop while we haven't found an option and Name still has at least two
396 // characters in it (so that the next iteration will not be the empty
398 while (OMI == OptionsMap.end() && Name.size() > 1) {
399 Name = Name.substr(0, Name.size()-1); // Chop off the last character.
400 OMI = OptionsMap.find(Name);
403 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
404 Length = Name.size();
405 return OMI->second; // Found one!
407 return nullptr; // No option found!
410 /// HandlePrefixedOrGroupedOption - The specified argument string (which started
411 /// with at least one '-') does not fully match an available option. Check to
412 /// see if this is a prefix or grouped option. If so, split arg into output an
413 /// Arg/Value pair and return the Option to parse it with.
414 static Option *HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
416 const StringMap<Option*> &OptionsMap) {
417 if (Arg.size() == 1) return nullptr;
421 Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
422 if (!PGOpt) return nullptr;
424 // If the option is a prefixed option, then the value is simply the
425 // rest of the name... so fall through to later processing, by
426 // setting up the argument name flags and value fields.
427 if (PGOpt->getFormattingFlag() == cl::Prefix) {
428 Value = Arg.substr(Length);
429 Arg = Arg.substr(0, Length);
430 assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
434 // This must be a grouped option... handle them now. Grouping options can't
436 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
439 // Move current arg name out of Arg into OneArgName.
440 StringRef OneArgName = Arg.substr(0, Length);
441 Arg = Arg.substr(Length);
443 // Because ValueRequired is an invalid flag for grouped arguments,
444 // we don't need to pass argc/argv in.
445 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
446 "Option can not be cl::Grouping AND cl::ValueRequired!");
448 ErrorParsing |= ProvideOption(PGOpt, OneArgName,
449 StringRef(), 0, nullptr, Dummy);
451 // Get the next grouping option.
452 PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
453 } while (PGOpt && Length != Arg.size());
455 // Return the last option with Arg cut down to just the last one.
461 static bool RequiresValue(const Option *O) {
462 return O->getNumOccurrencesFlag() == cl::Required ||
463 O->getNumOccurrencesFlag() == cl::OneOrMore;
466 static bool EatsUnboundedNumberOfValues(const Option *O) {
467 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
468 O->getNumOccurrencesFlag() == cl::OneOrMore;
471 static bool isWhitespace(char C) {
472 return strchr(" \t\n\r\f\v", C);
475 static bool isQuote(char C) {
476 return C == '\"' || C == '\'';
479 static bool isGNUSpecial(char C) {
480 return strchr("\\\"\' ", C);
483 void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
484 SmallVectorImpl<const char *> &NewArgv,
486 SmallString<128> Token;
487 for (size_t I = 0, E = Src.size(); I != E; ++I) {
488 // Consume runs of whitespace.
490 while (I != E && isWhitespace(Src[I])) {
491 // Mark the end of lines in response files
492 if (MarkEOLs && Src[I] == '\n')
493 NewArgv.push_back(nullptr);
499 // Backslashes can escape backslashes, spaces, and other quotes. Otherwise
500 // they are literal. This makes it much easier to read Windows file paths.
501 if (I + 1 < E && Src[I] == '\\' && isGNUSpecial(Src[I + 1])) {
502 ++I; // Skip the escape.
503 Token.push_back(Src[I]);
507 // Consume a quoted string.
508 if (isQuote(Src[I])) {
509 char Quote = Src[I++];
510 while (I != E && Src[I] != Quote) {
511 // Backslashes are literal, unless they escape a special character.
512 if (Src[I] == '\\' && I + 1 != E && isGNUSpecial(Src[I + 1]))
514 Token.push_back(Src[I]);
521 // End the token if this is whitespace.
522 if (isWhitespace(Src[I])) {
524 NewArgv.push_back(Saver.SaveString(Token.c_str()));
529 // This is a normal character. Append it.
530 Token.push_back(Src[I]);
533 // Append the last token after hitting EOF with no whitespace.
535 NewArgv.push_back(Saver.SaveString(Token.c_str()));
536 // Mark the end of response files
538 NewArgv.push_back(nullptr);
541 /// Backslashes are interpreted in a rather complicated way in the Windows-style
542 /// command line, because backslashes are used both to separate path and to
543 /// escape double quote. This method consumes runs of backslashes as well as the
544 /// following double quote if it's escaped.
546 /// * If an even number of backslashes is followed by a double quote, one
547 /// backslash is output for every pair of backslashes, and the last double
548 /// quote remains unconsumed. The double quote will later be interpreted as
549 /// the start or end of a quoted string in the main loop outside of this
552 /// * If an odd number of backslashes is followed by a double quote, one
553 /// backslash is output for every pair of backslashes, and a double quote is
554 /// output for the last pair of backslash-double quote. The double quote is
555 /// consumed in this case.
557 /// * Otherwise, backslashes are interpreted literally.
558 static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
559 size_t E = Src.size();
560 int BackslashCount = 0;
561 // Skip the backslashes.
565 } while (I != E && Src[I] == '\\');
567 bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
568 if (FollowedByDoubleQuote) {
569 Token.append(BackslashCount / 2, '\\');
570 if (BackslashCount % 2 == 0)
572 Token.push_back('"');
575 Token.append(BackslashCount, '\\');
579 void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
580 SmallVectorImpl<const char *> &NewArgv,
582 SmallString<128> Token;
584 // This is a small state machine to consume characters until it reaches the
585 // end of the source string.
586 enum { INIT, UNQUOTED, QUOTED } State = INIT;
587 for (size_t I = 0, E = Src.size(); I != E; ++I) {
588 // INIT state indicates that the current input index is at the start of
589 // the string or between tokens.
591 if (isWhitespace(Src[I])) {
592 // Mark the end of lines in response files
593 if (MarkEOLs && Src[I] == '\n')
594 NewArgv.push_back(nullptr);
601 if (Src[I] == '\\') {
602 I = parseBackslash(Src, I, Token);
606 Token.push_back(Src[I]);
611 // UNQUOTED state means that it's reading a token not quoted by double
613 if (State == UNQUOTED) {
614 // Whitespace means the end of the token.
615 if (isWhitespace(Src[I])) {
616 NewArgv.push_back(Saver.SaveString(Token.c_str()));
619 // Mark the end of lines in response files
620 if (MarkEOLs && Src[I] == '\n')
621 NewArgv.push_back(nullptr);
628 if (Src[I] == '\\') {
629 I = parseBackslash(Src, I, Token);
632 Token.push_back(Src[I]);
636 // QUOTED state means that it's reading a token quoted by double quotes.
637 if (State == QUOTED) {
642 if (Src[I] == '\\') {
643 I = parseBackslash(Src, I, Token);
646 Token.push_back(Src[I]);
649 // Append the last token after hitting EOF with no whitespace.
651 NewArgv.push_back(Saver.SaveString(Token.c_str()));
652 // Mark the end of response files
654 NewArgv.push_back(nullptr);
657 static bool ExpandResponseFile(const char *FName, StringSaver &Saver,
658 TokenizerCallback Tokenizer,
659 SmallVectorImpl<const char *> &NewArgv,
660 bool MarkEOLs = false) {
661 ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
662 MemoryBuffer::getFile(FName);
665 MemoryBuffer &MemBuf = *MemBufOrErr.get();
666 StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize());
668 // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
669 ArrayRef<char> BufRef(MemBuf.getBufferStart(), MemBuf.getBufferEnd());
671 if (hasUTF16ByteOrderMark(BufRef)) {
672 if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
674 Str = StringRef(UTF8Buf);
677 // Tokenize the contents into NewArgv.
678 Tokenizer(Str, Saver, NewArgv, MarkEOLs);
683 /// \brief Expand response files on a command line recursively using the given
684 /// StringSaver and tokenization strategy.
685 bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
686 SmallVectorImpl<const char *> &Argv,
688 unsigned RspFiles = 0;
689 bool AllExpanded = true;
691 // Don't cache Argv.size() because it can change.
692 for (unsigned I = 0; I != Argv.size(); ) {
693 const char *Arg = Argv[I];
694 // Check if it is an EOL marker
695 if (Arg == nullptr) {
704 // If we have too many response files, leave some unexpanded. This avoids
705 // crashing on self-referential response files.
709 // Replace this response file argument with the tokenization of its
710 // contents. Nested response files are expanded in subsequent iterations.
711 // FIXME: If a nested response file uses a relative path, is it relative to
712 // the cwd of the process or the response file?
713 SmallVector<const char *, 0> ExpandedArgv;
714 if (!ExpandResponseFile(Arg + 1, Saver, Tokenizer, ExpandedArgv,
716 // We couldn't read this file, so we leave it in the argument stream and
722 Argv.erase(Argv.begin() + I);
723 Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
729 class StrDupSaver : public StringSaver {
730 std::vector<char*> Dups;
733 for (std::vector<char *>::iterator I = Dups.begin(), E = Dups.end();
739 const char *SaveString(const char *Str) override {
740 char *Dup = strdup(Str);
747 /// ParseEnvironmentOptions - An alternative entry point to the
748 /// CommandLine library, which allows you to read the program's name
749 /// from the caller (as PROGNAME) and its command-line arguments from
750 /// an environment variable (whose name is given in ENVVAR).
752 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
753 const char *Overview) {
755 assert(progName && "Program name not specified");
756 assert(envVar && "Environment variable name missing");
758 // Get the environment variable they want us to parse options out of.
759 const char *envValue = getenv(envVar);
763 // Get program's "name", which we wouldn't know without the caller
765 SmallVector<const char *, 20> newArgv;
767 newArgv.push_back(Saver.SaveString(progName));
769 // Parse the value of the environment variable into a "command line"
770 // and hand it off to ParseCommandLineOptions().
771 TokenizeGNUCommandLine(envValue, Saver, newArgv);
772 int newArgc = static_cast<int>(newArgv.size());
773 ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
776 void cl::ParseCommandLineOptions(int argc, const char * const *argv,
777 const char *Overview) {
778 // Process all registered options.
779 SmallVector<Option*, 4> PositionalOpts;
780 SmallVector<Option*, 4> SinkOpts;
781 StringMap<Option*> Opts;
782 GetOptionInfo(PositionalOpts, SinkOpts, Opts);
784 assert((!Opts.empty() || !PositionalOpts.empty()) &&
785 "No options specified!");
787 // Expand response files.
788 SmallVector<const char *, 20> newArgv;
789 for (int i = 0; i != argc; ++i)
790 newArgv.push_back(argv[i]);
792 ExpandResponseFiles(Saver, TokenizeGNUCommandLine, newArgv);
794 argc = static_cast<int>(newArgv.size());
796 // Copy the program name into ProgName, making sure not to overflow it.
797 StringRef ProgName = sys::path::filename(argv[0]);
798 size_t Len = std::min(ProgName.size(), size_t(79));
799 memcpy(ProgramName, ProgName.data(), Len);
800 ProgramName[Len] = '\0';
802 ProgramOverview = Overview;
803 bool ErrorParsing = false;
805 // Check out the positional arguments to collect information about them.
806 unsigned NumPositionalRequired = 0;
808 // Determine whether or not there are an unlimited number of positionals
809 bool HasUnlimitedPositionals = false;
811 Option *ConsumeAfterOpt = nullptr;
812 if (!PositionalOpts.empty()) {
813 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
814 assert(PositionalOpts.size() > 1 &&
815 "Cannot specify cl::ConsumeAfter without a positional argument!");
816 ConsumeAfterOpt = PositionalOpts[0];
819 // Calculate how many positional values are _required_.
820 bool UnboundedFound = false;
821 for (size_t i = ConsumeAfterOpt ? 1 : 0, e = PositionalOpts.size();
823 Option *Opt = PositionalOpts[i];
824 if (RequiresValue(Opt))
825 ++NumPositionalRequired;
826 else if (ConsumeAfterOpt) {
827 // ConsumeAfter cannot be combined with "optional" positional options
828 // unless there is only one positional argument...
829 if (PositionalOpts.size() > 2)
831 Opt->error("error - this positional option will never be matched, "
832 "because it does not Require a value, and a "
833 "cl::ConsumeAfter option is active!");
834 } else if (UnboundedFound && !Opt->ArgStr[0]) {
835 // This option does not "require" a value... Make sure this option is
836 // not specified after an option that eats all extra arguments, or this
837 // one will never get any!
839 ErrorParsing |= Opt->error("error - option can never match, because "
840 "another positional argument will match an "
841 "unbounded number of values, and this option"
842 " does not require a value!");
844 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
846 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
849 // PositionalVals - A vector of "positional" arguments we accumulate into
850 // the process at the end.
852 SmallVector<std::pair<StringRef,unsigned>, 4> PositionalVals;
854 // If the program has named positional arguments, and the name has been run
855 // across, keep track of which positional argument was named. Otherwise put
856 // the positional args into the PositionalVals list...
857 Option *ActivePositionalArg = nullptr;
859 // Loop over all of the arguments... processing them.
860 bool DashDashFound = false; // Have we read '--'?
861 for (int i = 1; i < argc; ++i) {
862 Option *Handler = nullptr;
863 Option *NearestHandler = nullptr;
864 std::string NearestHandlerString;
866 StringRef ArgName = "";
868 // If the option list changed, this means that some command line
869 // option has just been registered or deregistered. This can occur in
870 // response to things like -load, etc. If this happens, rescan the options.
871 if (OptionListChanged) {
872 PositionalOpts.clear();
875 GetOptionInfo(PositionalOpts, SinkOpts, Opts);
876 OptionListChanged = false;
879 // Check to see if this is a positional argument. This argument is
880 // considered to be positional if it doesn't start with '-', if it is "-"
881 // itself, or if we have seen "--" already.
883 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
884 // Positional argument!
885 if (ActivePositionalArg) {
886 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
887 continue; // We are done!
890 if (!PositionalOpts.empty()) {
891 PositionalVals.push_back(std::make_pair(argv[i],i));
893 // All of the positional arguments have been fulfulled, give the rest to
894 // the consume after option... if it's specified...
896 if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) {
897 for (++i; i < argc; ++i)
898 PositionalVals.push_back(std::make_pair(argv[i],i));
899 break; // Handle outside of the argument processing loop...
902 // Delay processing positional arguments until the end...
905 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
907 DashDashFound = true; // This is the mythical "--"?
908 continue; // Don't try to process it as an argument itself.
909 } else if (ActivePositionalArg &&
910 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
911 // If there is a positional argument eating options, check to see if this
912 // option is another positional argument. If so, treat it as an argument,
913 // otherwise feed it to the eating positional.
915 // Eat leading dashes.
916 while (!ArgName.empty() && ArgName[0] == '-')
917 ArgName = ArgName.substr(1);
919 Handler = LookupOption(ArgName, Value, Opts);
920 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
921 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
922 continue; // We are done!
925 } else { // We start with a '-', must be an argument.
927 // Eat leading dashes.
928 while (!ArgName.empty() && ArgName[0] == '-')
929 ArgName = ArgName.substr(1);
931 Handler = LookupOption(ArgName, Value, Opts);
933 // Check to see if this "option" is really a prefixed or grouped argument.
935 Handler = HandlePrefixedOrGroupedOption(ArgName, Value,
938 // Otherwise, look for the closest available option to report to the user
939 // in the upcoming error.
940 if (!Handler && SinkOpts.empty())
941 NearestHandler = LookupNearestOption(ArgName, Opts,
942 NearestHandlerString);
946 if (SinkOpts.empty()) {
947 errs() << ProgramName << ": Unknown command line argument '"
948 << argv[i] << "'. Try: '" << argv[0] << " -help'\n";
950 if (NearestHandler) {
951 // If we know a near match, report it as well.
952 errs() << ProgramName << ": Did you mean '-"
953 << NearestHandlerString << "'?\n";
958 for (SmallVectorImpl<Option*>::iterator I = SinkOpts.begin(),
959 E = SinkOpts.end(); I != E ; ++I)
960 (*I)->addOccurrence(i, "", argv[i]);
965 // If this is a named positional argument, just remember that it is the
967 if (Handler->getFormattingFlag() == cl::Positional)
968 ActivePositionalArg = Handler;
970 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
973 // Check and handle positional arguments now...
974 if (NumPositionalRequired > PositionalVals.size()) {
975 errs() << ProgramName
976 << ": Not enough positional command line arguments specified!\n"
977 << "Must specify at least " << NumPositionalRequired
978 << " positional arguments: See: " << argv[0] << " -help\n";
981 } else if (!HasUnlimitedPositionals &&
982 PositionalVals.size() > PositionalOpts.size()) {
983 errs() << ProgramName
984 << ": Too many positional arguments specified!\n"
985 << "Can specify at most " << PositionalOpts.size()
986 << " positional arguments: See: " << argv[0] << " -help\n";
989 } else if (!ConsumeAfterOpt) {
990 // Positional args have already been handled if ConsumeAfter is specified.
991 unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
992 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
993 if (RequiresValue(PositionalOpts[i])) {
994 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
995 PositionalVals[ValNo].second);
997 --NumPositionalRequired; // We fulfilled our duty...
1000 // If we _can_ give this option more arguments, do so now, as long as we
1001 // do not give it values that others need. 'Done' controls whether the
1002 // option even _WANTS_ any more.
1004 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
1005 while (NumVals-ValNo > NumPositionalRequired && !Done) {
1006 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
1008 Done = true; // Optional arguments want _at most_ one value
1010 case cl::ZeroOrMore: // Zero or more will take all they can get...
1011 case cl::OneOrMore: // One or more will take all they can get...
1012 ProvidePositionalOption(PositionalOpts[i],
1013 PositionalVals[ValNo].first,
1014 PositionalVals[ValNo].second);
1018 llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
1019 "positional argument processing!");
1024 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
1026 for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
1027 if (RequiresValue(PositionalOpts[j])) {
1028 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
1029 PositionalVals[ValNo].first,
1030 PositionalVals[ValNo].second);
1034 // Handle the case where there is just one positional option, and it's
1035 // optional. In this case, we want to give JUST THE FIRST option to the
1036 // positional option and keep the rest for the consume after. The above
1037 // loop would have assigned no values to positional options in this case.
1039 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
1040 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
1041 PositionalVals[ValNo].first,
1042 PositionalVals[ValNo].second);
1046 // Handle over all of the rest of the arguments to the
1047 // cl::ConsumeAfter command line option...
1048 for (; ValNo != PositionalVals.size(); ++ValNo)
1049 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
1050 PositionalVals[ValNo].first,
1051 PositionalVals[ValNo].second);
1054 // Loop over args and make sure all required args are specified!
1055 for (const auto &Opt : Opts) {
1056 switch (Opt.second->getNumOccurrencesFlag()) {
1059 if (Opt.second->getNumOccurrences() == 0) {
1060 Opt.second->error("must be specified at least once!");
1061 ErrorParsing = true;
1069 // Now that we know if -debug is specified, we can use it.
1070 // Note that if ReadResponseFiles == true, this must be done before the
1071 // memory allocated for the expanded command line is free()d below.
1072 DEBUG(dbgs() << "Args: ";
1073 for (int i = 0; i < argc; ++i)
1074 dbgs() << argv[i] << ' ';
1078 // Free all of the memory allocated to the map. Command line options may only
1079 // be processed once!
1081 PositionalOpts.clear();
1084 // If we had an error processing our arguments, don't let the program execute
1085 if (ErrorParsing) exit(1);
1088 //===----------------------------------------------------------------------===//
1089 // Option Base class implementation
1092 bool Option::error(const Twine &Message, StringRef ArgName) {
1093 if (!ArgName.data()) ArgName = ArgStr;
1094 if (ArgName.empty())
1095 errs() << HelpStr; // Be nice for positional arguments
1097 errs() << ProgramName << ": for the -" << ArgName;
1099 errs() << " option: " << Message << "\n";
1103 bool Option::addOccurrence(unsigned pos, StringRef ArgName,
1104 StringRef Value, bool MultiArg) {
1106 NumOccurrences++; // Increment the number of times we have been seen
1108 switch (getNumOccurrencesFlag()) {
1110 if (NumOccurrences > 1)
1111 return error("may only occur zero or one times!", ArgName);
1114 if (NumOccurrences > 1)
1115 return error("must occur exactly one time!", ArgName);
1119 case ConsumeAfter: break;
1122 return handleOccurrence(pos, ArgName, Value);
1126 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
1127 // has been specified yet.
1129 static const char *getValueStr(const Option &O, const char *DefaultMsg) {
1130 if (O.ValueStr[0] == 0) return DefaultMsg;
1134 //===----------------------------------------------------------------------===//
1135 // cl::alias class implementation
1138 // Return the width of the option tag for printing...
1139 size_t alias::getOptionWidth() const {
1140 return std::strlen(ArgStr)+6;
1143 static void printHelpStr(StringRef HelpStr, size_t Indent,
1144 size_t FirstLineIndentedBy) {
1145 std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1146 outs().indent(Indent - FirstLineIndentedBy) << " - " << Split.first << "\n";
1147 while (!Split.second.empty()) {
1148 Split = Split.second.split('\n');
1149 outs().indent(Indent) << Split.first << "\n";
1153 // Print out the option for the alias.
1154 void alias::printOptionInfo(size_t GlobalWidth) const {
1155 outs() << " -" << ArgStr;
1156 printHelpStr(HelpStr, GlobalWidth, std::strlen(ArgStr) + 6);
1159 //===----------------------------------------------------------------------===//
1160 // Parser Implementation code...
1163 // basic_parser implementation
1166 // Return the width of the option tag for printing...
1167 size_t basic_parser_impl::getOptionWidth(const Option &O) const {
1168 size_t Len = std::strlen(O.ArgStr);
1169 if (const char *ValName = getValueName())
1170 Len += std::strlen(getValueStr(O, ValName))+3;
1175 // printOptionInfo - Print out information about this option. The
1176 // to-be-maintained width is specified.
1178 void basic_parser_impl::printOptionInfo(const Option &O,
1179 size_t GlobalWidth) const {
1180 outs() << " -" << O.ArgStr;
1182 if (const char *ValName = getValueName())
1183 outs() << "=<" << getValueStr(O, ValName) << '>';
1185 printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
1188 void basic_parser_impl::printOptionName(const Option &O,
1189 size_t GlobalWidth) const {
1190 outs() << " -" << O.ArgStr;
1191 outs().indent(GlobalWidth-std::strlen(O.ArgStr));
1195 // parser<bool> implementation
1197 bool parser<bool>::parse(Option &O, StringRef ArgName,
1198 StringRef Arg, bool &Value) {
1199 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1205 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1209 return O.error("'" + Arg +
1210 "' is invalid value for boolean argument! Try 0 or 1");
1213 // parser<boolOrDefault> implementation
1215 bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName,
1216 StringRef Arg, boolOrDefault &Value) {
1217 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1222 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1227 return O.error("'" + Arg +
1228 "' is invalid value for boolean argument! Try 0 or 1");
1231 // parser<int> implementation
1233 bool parser<int>::parse(Option &O, StringRef ArgName,
1234 StringRef Arg, int &Value) {
1235 if (Arg.getAsInteger(0, Value))
1236 return O.error("'" + Arg + "' value invalid for integer argument!");
1240 // parser<unsigned> implementation
1242 bool parser<unsigned>::parse(Option &O, StringRef ArgName,
1243 StringRef Arg, unsigned &Value) {
1245 if (Arg.getAsInteger(0, Value))
1246 return O.error("'" + Arg + "' value invalid for uint argument!");
1250 // parser<unsigned long long> implementation
1252 bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
1253 StringRef Arg, unsigned long long &Value){
1255 if (Arg.getAsInteger(0, Value))
1256 return O.error("'" + Arg + "' value invalid for uint argument!");
1260 // parser<double>/parser<float> implementation
1262 static bool parseDouble(Option &O, StringRef Arg, double &Value) {
1263 SmallString<32> TmpStr(Arg.begin(), Arg.end());
1264 const char *ArgStart = TmpStr.c_str();
1266 Value = strtod(ArgStart, &End);
1268 return O.error("'" + Arg + "' value invalid for floating point argument!");
1272 bool parser<double>::parse(Option &O, StringRef ArgName,
1273 StringRef Arg, double &Val) {
1274 return parseDouble(O, Arg, Val);
1277 bool parser<float>::parse(Option &O, StringRef ArgName,
1278 StringRef Arg, float &Val) {
1280 if (parseDouble(O, Arg, dVal))
1288 // generic_parser_base implementation
1291 // findOption - Return the option number corresponding to the specified
1292 // argument string. If the option is not found, getNumOptions() is returned.
1294 unsigned generic_parser_base::findOption(const char *Name) {
1295 unsigned e = getNumOptions();
1297 for (unsigned i = 0; i != e; ++i) {
1298 if (strcmp(getOption(i), Name) == 0)
1305 // Return the width of the option tag for printing...
1306 size_t generic_parser_base::getOptionWidth(const Option &O) const {
1307 if (O.hasArgStr()) {
1308 size_t Size = std::strlen(O.ArgStr)+6;
1309 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1310 Size = std::max(Size, std::strlen(getOption(i))+8);
1313 size_t BaseSize = 0;
1314 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1315 BaseSize = std::max(BaseSize, std::strlen(getOption(i))+8);
1320 // printOptionInfo - Print out information about this option. The
1321 // to-be-maintained width is specified.
1323 void generic_parser_base::printOptionInfo(const Option &O,
1324 size_t GlobalWidth) const {
1325 if (O.hasArgStr()) {
1326 outs() << " -" << O.ArgStr;
1327 printHelpStr(O.HelpStr, GlobalWidth, std::strlen(O.ArgStr) + 6);
1329 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1330 size_t NumSpaces = GlobalWidth-strlen(getOption(i))-8;
1331 outs() << " =" << getOption(i);
1332 outs().indent(NumSpaces) << " - " << getDescription(i) << '\n';
1336 outs() << " " << O.HelpStr << '\n';
1337 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1338 const char *Option = getOption(i);
1339 outs() << " -" << Option;
1340 printHelpStr(getDescription(i), GlobalWidth, std::strlen(Option) + 8);
1345 static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1347 // printGenericOptionDiff - Print the value of this option and it's default.
1349 // "Generic" options have each value mapped to a name.
1350 void generic_parser_base::
1351 printGenericOptionDiff(const Option &O, const GenericOptionValue &Value,
1352 const GenericOptionValue &Default,
1353 size_t GlobalWidth) const {
1354 outs() << " -" << O.ArgStr;
1355 outs().indent(GlobalWidth-std::strlen(O.ArgStr));
1357 unsigned NumOpts = getNumOptions();
1358 for (unsigned i = 0; i != NumOpts; ++i) {
1359 if (Value.compare(getOptionValue(i)))
1362 outs() << "= " << getOption(i);
1363 size_t L = std::strlen(getOption(i));
1364 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1365 outs().indent(NumSpaces) << " (default: ";
1366 for (unsigned j = 0; j != NumOpts; ++j) {
1367 if (Default.compare(getOptionValue(j)))
1369 outs() << getOption(j);
1375 outs() << "= *unknown option value*\n";
1378 // printOptionDiff - Specializations for printing basic value types.
1380 #define PRINT_OPT_DIFF(T) \
1382 printOptionDiff(const Option &O, T V, OptionValue<T> D, \
1383 size_t GlobalWidth) const { \
1384 printOptionName(O, GlobalWidth); \
1387 raw_string_ostream SS(Str); \
1390 outs() << "= " << Str; \
1391 size_t NumSpaces = MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0;\
1392 outs().indent(NumSpaces) << " (default: "; \
1394 outs() << D.getValue(); \
1396 outs() << "*no default*"; \
1400 PRINT_OPT_DIFF(bool)
1401 PRINT_OPT_DIFF(boolOrDefault)
1403 PRINT_OPT_DIFF(unsigned)
1404 PRINT_OPT_DIFF(unsigned long long)
1405 PRINT_OPT_DIFF(double)
1406 PRINT_OPT_DIFF(float)
1407 PRINT_OPT_DIFF(char)
1409 void parser<std::string>::
1410 printOptionDiff(const Option &O, StringRef V, OptionValue<std::string> D,
1411 size_t GlobalWidth) const {
1412 printOptionName(O, GlobalWidth);
1413 outs() << "= " << V;
1414 size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
1415 outs().indent(NumSpaces) << " (default: ";
1417 outs() << D.getValue();
1419 outs() << "*no default*";
1423 // Print a placeholder for options that don't yet support printOptionDiff().
1424 void basic_parser_impl::
1425 printOptionNoValue(const Option &O, size_t GlobalWidth) const {
1426 printOptionName(O, GlobalWidth);
1427 outs() << "= *cannot print option value*\n";
1430 //===----------------------------------------------------------------------===//
1431 // -help and -help-hidden option implementation
1434 static int OptNameCompare(const void *LHS, const void *RHS) {
1435 typedef std::pair<const char *, Option*> pair_ty;
1437 return strcmp(((const pair_ty*)LHS)->first, ((const pair_ty*)RHS)->first);
1440 // Copy Options into a vector so we can sort them as we like.
1442 sortOpts(StringMap<Option*> &OptMap,
1443 SmallVectorImpl< std::pair<const char *, Option*> > &Opts,
1445 SmallPtrSet<Option*, 128> OptionSet; // Duplicate option detection.
1447 for (StringMap<Option*>::iterator I = OptMap.begin(), E = OptMap.end();
1449 // Ignore really-hidden options.
1450 if (I->second->getOptionHiddenFlag() == ReallyHidden)
1453 // Unless showhidden is set, ignore hidden flags.
1454 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
1457 // If we've already seen this option, don't add it to the list again.
1458 if (!OptionSet.insert(I->second))
1461 Opts.push_back(std::pair<const char *, Option*>(I->getKey().data(),
1465 // Sort the options list alphabetically.
1466 qsort(Opts.data(), Opts.size(), sizeof(Opts[0]), OptNameCompare);
1473 const bool ShowHidden;
1474 typedef SmallVector<std::pair<const char *, Option*>,128> StrOptionPairVector;
1475 // Print the options. Opts is assumed to be alphabetically sorted.
1476 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1477 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1478 Opts[i].second->printOptionInfo(MaxArgLen);
1482 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
1483 virtual ~HelpPrinter() {}
1485 // Invoke the printer.
1486 void operator=(bool Value) {
1487 if (Value == false) return;
1489 // Get all the options.
1490 SmallVector<Option*, 4> PositionalOpts;
1491 SmallVector<Option*, 4> SinkOpts;
1492 StringMap<Option*> OptMap;
1493 GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
1495 StrOptionPairVector Opts;
1496 sortOpts(OptMap, Opts, ShowHidden);
1498 if (ProgramOverview)
1499 outs() << "OVERVIEW: " << ProgramOverview << "\n";
1501 outs() << "USAGE: " << ProgramName << " [options]";
1503 // Print out the positional options.
1504 Option *CAOpt = nullptr; // The cl::ConsumeAfter option, if it exists...
1505 if (!PositionalOpts.empty() &&
1506 PositionalOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
1507 CAOpt = PositionalOpts[0];
1509 for (size_t i = CAOpt != nullptr, e = PositionalOpts.size(); i != e; ++i) {
1510 if (PositionalOpts[i]->ArgStr[0])
1511 outs() << " --" << PositionalOpts[i]->ArgStr;
1512 outs() << " " << PositionalOpts[i]->HelpStr;
1515 // Print the consume after option info if it exists...
1516 if (CAOpt) outs() << " " << CAOpt->HelpStr;
1520 // Compute the maximum argument length...
1521 size_t MaxArgLen = 0;
1522 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1523 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1525 outs() << "OPTIONS:\n";
1526 printOptions(Opts, MaxArgLen);
1528 // Print any extra help the user has declared.
1529 for (std::vector<const char *>::iterator I = MoreHelp->begin(),
1530 E = MoreHelp->end();
1535 // Halt the program since help information was printed
1540 class CategorizedHelpPrinter : public HelpPrinter {
1542 explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
1544 // Helper function for printOptions().
1545 // It shall return true if A's name should be lexographically
1546 // ordered before B's name. It returns false otherwise.
1547 static bool OptionCategoryCompare(OptionCategory *A, OptionCategory *B) {
1548 return strcmp(A->getName(), B->getName()) < 0;
1551 // Make sure we inherit our base class's operator=()
1552 using HelpPrinter::operator= ;
1555 void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override {
1556 std::vector<OptionCategory *> SortedCategories;
1557 std::map<OptionCategory *, std::vector<Option *> > CategorizedOptions;
1559 // Collect registered option categories into vector in preparation for
1561 for (OptionCatSet::const_iterator I = RegisteredOptionCategories->begin(),
1562 E = RegisteredOptionCategories->end();
1564 SortedCategories.push_back(*I);
1567 // Sort the different option categories alphabetically.
1568 assert(SortedCategories.size() > 0 && "No option categories registered!");
1569 std::sort(SortedCategories.begin(), SortedCategories.end(),
1570 OptionCategoryCompare);
1572 // Create map to empty vectors.
1573 for (std::vector<OptionCategory *>::const_iterator
1574 I = SortedCategories.begin(),
1575 E = SortedCategories.end();
1577 CategorizedOptions[*I] = std::vector<Option *>();
1579 // Walk through pre-sorted options and assign into categories.
1580 // Because the options are already alphabetically sorted the
1581 // options within categories will also be alphabetically sorted.
1582 for (size_t I = 0, E = Opts.size(); I != E; ++I) {
1583 Option *Opt = Opts[I].second;
1584 assert(CategorizedOptions.count(Opt->Category) > 0 &&
1585 "Option has an unregistered category");
1586 CategorizedOptions[Opt->Category].push_back(Opt);
1590 for (std::vector<OptionCategory *>::const_iterator
1591 Category = SortedCategories.begin(),
1592 E = SortedCategories.end();
1593 Category != E; ++Category) {
1594 // Hide empty categories for -help, but show for -help-hidden.
1595 bool IsEmptyCategory = CategorizedOptions[*Category].size() == 0;
1596 if (!ShowHidden && IsEmptyCategory)
1599 // Print category information.
1601 outs() << (*Category)->getName() << ":\n";
1603 // Check if description is set.
1604 if ((*Category)->getDescription() != nullptr)
1605 outs() << (*Category)->getDescription() << "\n\n";
1609 // When using -help-hidden explicitly state if the category has no
1610 // options associated with it.
1611 if (IsEmptyCategory) {
1612 outs() << " This option category has no options.\n";
1615 // Loop over the options in the category and print.
1616 for (std::vector<Option *>::const_iterator
1617 Opt = CategorizedOptions[*Category].begin(),
1618 E = CategorizedOptions[*Category].end();
1620 (*Opt)->printOptionInfo(MaxArgLen);
1625 // This wraps the Uncategorizing and Categorizing printers and decides
1626 // at run time which should be invoked.
1627 class HelpPrinterWrapper {
1629 HelpPrinter &UncategorizedPrinter;
1630 CategorizedHelpPrinter &CategorizedPrinter;
1633 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
1634 CategorizedHelpPrinter &CategorizedPrinter) :
1635 UncategorizedPrinter(UncategorizedPrinter),
1636 CategorizedPrinter(CategorizedPrinter) { }
1638 // Invoke the printer.
1639 void operator=(bool Value);
1642 } // End anonymous namespace
1644 // Declare the four HelpPrinter instances that are used to print out help, or
1645 // help-hidden as an uncategorized list or in categories.
1646 static HelpPrinter UncategorizedNormalPrinter(false);
1647 static HelpPrinter UncategorizedHiddenPrinter(true);
1648 static CategorizedHelpPrinter CategorizedNormalPrinter(false);
1649 static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
1652 // Declare HelpPrinter wrappers that will decide whether or not to invoke
1653 // a categorizing help printer
1654 static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
1655 CategorizedNormalPrinter);
1656 static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
1657 CategorizedHiddenPrinter);
1659 // Define uncategorized help printers.
1660 // -help-list is hidden by default because if Option categories are being used
1661 // then -help behaves the same as -help-list.
1662 static cl::opt<HelpPrinter, true, parser<bool> >
1664 cl::desc("Display list of available options (-help-list-hidden for more)"),
1665 cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed);
1667 static cl::opt<HelpPrinter, true, parser<bool> >
1668 HLHOp("help-list-hidden",
1669 cl::desc("Display list of all available options"),
1670 cl::location(UncategorizedHiddenPrinter), cl::Hidden, cl::ValueDisallowed);
1672 // Define uncategorized/categorized help printers. These printers change their
1673 // behaviour at runtime depending on whether one or more Option categories have
1675 static cl::opt<HelpPrinterWrapper, true, parser<bool> >
1676 HOp("help", cl::desc("Display available options (-help-hidden for more)"),
1677 cl::location(WrappedNormalPrinter), cl::ValueDisallowed);
1679 static cl::opt<HelpPrinterWrapper, true, parser<bool> >
1680 HHOp("help-hidden", cl::desc("Display all available options"),
1681 cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed);
1685 static cl::opt<bool>
1686 PrintOptions("print-options",
1687 cl::desc("Print non-default options after command line parsing"),
1688 cl::Hidden, cl::init(false));
1690 static cl::opt<bool>
1691 PrintAllOptions("print-all-options",
1692 cl::desc("Print all option values after command line parsing"),
1693 cl::Hidden, cl::init(false));
1695 void HelpPrinterWrapper::operator=(bool Value) {
1699 // Decide which printer to invoke. If more than one option category is
1700 // registered then it is useful to show the categorized help instead of
1701 // uncategorized help.
1702 if (RegisteredOptionCategories->size() > 1) {
1703 // unhide -help-list option so user can have uncategorized output if they
1705 HLOp.setHiddenFlag(NotHidden);
1707 CategorizedPrinter = true; // Invoke categorized printer
1710 UncategorizedPrinter = true; // Invoke uncategorized printer
1713 // Print the value of each option.
1714 void cl::PrintOptionValues() {
1715 if (!PrintOptions && !PrintAllOptions) return;
1717 // Get all the options.
1718 SmallVector<Option*, 4> PositionalOpts;
1719 SmallVector<Option*, 4> SinkOpts;
1720 StringMap<Option*> OptMap;
1721 GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
1723 SmallVector<std::pair<const char *, Option*>, 128> Opts;
1724 sortOpts(OptMap, Opts, /*ShowHidden*/true);
1726 // Compute the maximum argument length...
1727 size_t MaxArgLen = 0;
1728 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1729 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1731 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1732 Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
1735 static void (*OverrideVersionPrinter)() = nullptr;
1737 static std::vector<void (*)()>* ExtraVersionPrinters = nullptr;
1740 class VersionPrinter {
1743 raw_ostream &OS = outs();
1744 OS << "LLVM (http://llvm.org/):\n"
1745 << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
1746 #ifdef LLVM_VERSION_INFO
1747 OS << " " << LLVM_VERSION_INFO;
1750 #ifndef __OPTIMIZE__
1751 OS << "DEBUG build";
1753 OS << "Optimized build";
1756 OS << " with assertions";
1758 std::string CPU = sys::getHostCPUName();
1759 if (CPU == "generic") CPU = "(unknown)";
1761 #if (ENABLE_TIMESTAMPS == 1)
1762 << " Built " << __DATE__ << " (" << __TIME__ << ").\n"
1764 << " Default target: " << sys::getDefaultTargetTriple() << '\n'
1765 << " Host CPU: " << CPU << '\n';
1767 void operator=(bool OptionWasSpecified) {
1768 if (!OptionWasSpecified) return;
1770 if (OverrideVersionPrinter != nullptr) {
1771 (*OverrideVersionPrinter)();
1776 // Iterate over any registered extra printers and call them to add further
1778 if (ExtraVersionPrinters != nullptr) {
1780 for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(),
1781 E = ExtraVersionPrinters->end();
1789 } // End anonymous namespace
1792 // Define the --version option that prints out the LLVM version for the tool
1793 static VersionPrinter VersionPrinterInstance;
1795 static cl::opt<VersionPrinter, true, parser<bool> >
1796 VersOp("version", cl::desc("Display the version of this program"),
1797 cl::location(VersionPrinterInstance), cl::ValueDisallowed);
1799 // Utility function for printing the help message.
1800 void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
1801 // This looks weird, but it actually prints the help message. The Printers are
1802 // types of HelpPrinter and the help gets printed when its operator= is
1803 // invoked. That's because the "normal" usages of the help printer is to be
1804 // assigned true/false depending on whether -help or -help-hidden was given or
1805 // not. Since we're circumventing that we have to make it look like -help or
1806 // -help-hidden were given, so we assign true.
1808 if (!Hidden && !Categorized)
1809 UncategorizedNormalPrinter = true;
1810 else if (!Hidden && Categorized)
1811 CategorizedNormalPrinter = true;
1812 else if (Hidden && !Categorized)
1813 UncategorizedHiddenPrinter = true;
1815 CategorizedHiddenPrinter = true;
1818 /// Utility function for printing version number.
1819 void cl::PrintVersionMessage() {
1820 VersionPrinterInstance.print();
1823 void cl::SetVersionPrinter(void (*func)()) {
1824 OverrideVersionPrinter = func;
1827 void cl::AddExtraVersionPrinter(void (*func)()) {
1828 if (!ExtraVersionPrinters)
1829 ExtraVersionPrinters = new std::vector<void (*)()>;
1831 ExtraVersionPrinters->push_back(func);
1834 void cl::getRegisteredOptions(StringMap<Option*> &Map)
1836 // Get all the options.
1837 SmallVector<Option*, 4> PositionalOpts; //NOT USED
1838 SmallVector<Option*, 4> SinkOpts; //NOT USED
1839 assert(Map.size() == 0 && "StringMap must be empty");
1840 GetOptionInfo(PositionalOpts, SinkOpts, Map);
1844 void LLVMParseCommandLineOptions(int argc, const char *const *argv,
1845 const char *Overview) {
1846 llvm::cl::ParseCommandLineOptions(argc, argv, Overview);