1 //===-- CommandLine.cpp - Command line parser implementation --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This class implements a command line argument processor that is useful when
11 // creating a tool. It provides a simple, minimalistic interface that is easily
12 // extensible and supports nonlocal (library) command line options.
14 // Note that rather than trying to figure out what this code does, you could try
15 // reading the library documentation located in docs/CommandLine.html
17 //===----------------------------------------------------------------------===//
19 #include "llvm/Support/CommandLine.h"
20 #include "llvm/ADT/OwningPtr.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/ADT/StringMap.h"
24 #include "llvm/ADT/Twine.h"
25 #include "llvm/Config/config.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/Host.h"
29 #include "llvm/Support/ManagedStatic.h"
30 #include "llvm/Support/MemoryBuffer.h"
31 #include "llvm/Support/Path.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Support/system_error.h"
40 //===----------------------------------------------------------------------===//
41 // Template instantiations and anchors.
43 namespace llvm { namespace cl {
44 TEMPLATE_INSTANTIATION(class basic_parser<bool>);
45 TEMPLATE_INSTANTIATION(class basic_parser<boolOrDefault>);
46 TEMPLATE_INSTANTIATION(class basic_parser<int>);
47 TEMPLATE_INSTANTIATION(class basic_parser<unsigned>);
48 TEMPLATE_INSTANTIATION(class basic_parser<unsigned long long>);
49 TEMPLATE_INSTANTIATION(class basic_parser<double>);
50 TEMPLATE_INSTANTIATION(class basic_parser<float>);
51 TEMPLATE_INSTANTIATION(class basic_parser<std::string>);
52 TEMPLATE_INSTANTIATION(class basic_parser<char>);
54 TEMPLATE_INSTANTIATION(class opt<unsigned>);
55 TEMPLATE_INSTANTIATION(class opt<int>);
56 TEMPLATE_INSTANTIATION(class opt<std::string>);
57 TEMPLATE_INSTANTIATION(class opt<char>);
58 TEMPLATE_INSTANTIATION(class opt<bool>);
59 } } // end namespace llvm::cl
61 void OptionValue<boolOrDefault>::anchor() {}
62 void OptionValue<std::string>::anchor() {}
63 void Option::anchor() {}
64 void basic_parser_impl::anchor() {}
65 void parser<bool>::anchor() {}
66 void parser<boolOrDefault>::anchor() {}
67 void parser<int>::anchor() {}
68 void parser<unsigned>::anchor() {}
69 void parser<unsigned long long>::anchor() {}
70 void parser<double>::anchor() {}
71 void parser<float>::anchor() {}
72 void parser<std::string>::anchor() {}
73 void parser<char>::anchor() {}
75 //===----------------------------------------------------------------------===//
77 // Globals for name and overview of program. Program name is not a string to
78 // avoid static ctor/dtor issues.
79 static char ProgramName[80] = "<premain>";
80 static const char *ProgramOverview = 0;
82 // This collects additional help to be printed.
83 static ManagedStatic<std::vector<const char*> > MoreHelp;
85 extrahelp::extrahelp(const char *Help)
87 MoreHelp->push_back(Help);
90 static bool OptionListChanged = false;
92 // MarkOptionsChanged - Internal helper function.
93 void cl::MarkOptionsChanged() {
94 OptionListChanged = true;
97 /// RegisteredOptionList - This is the list of the command line options that
98 /// have statically constructed themselves.
99 static Option *RegisteredOptionList = 0;
101 void Option::addArgument() {
102 assert(NextRegistered == 0 && "argument multiply registered!");
104 NextRegistered = RegisteredOptionList;
105 RegisteredOptionList = this;
106 MarkOptionsChanged();
109 // This collects the different option categories that have been registered.
110 typedef SmallPtrSet<OptionCategory*,16> OptionCatSet;
111 static ManagedStatic<OptionCatSet> RegisteredOptionCategories;
113 // Initialise the general option category.
114 OptionCategory llvm::cl::GeneralCategory("General options");
116 void OptionCategory::registerCategory()
118 RegisteredOptionCategories->insert(this);
121 //===----------------------------------------------------------------------===//
122 // Basic, shared command line option processing machinery.
125 /// GetOptionInfo - Scan the list of registered options, turning them into data
126 /// structures that are easier to handle.
127 static void GetOptionInfo(SmallVectorImpl<Option*> &PositionalOpts,
128 SmallVectorImpl<Option*> &SinkOpts,
129 StringMap<Option*> &OptionsMap) {
130 SmallVector<const char*, 16> OptionNames;
131 Option *CAOpt = 0; // The ConsumeAfter option if it exists.
132 for (Option *O = RegisteredOptionList; O; O = O->getNextRegisteredOption()) {
133 // If this option wants to handle multiple option names, get the full set.
134 // This handles enum options like "-O1 -O2" etc.
135 O->getExtraOptionNames(OptionNames);
137 OptionNames.push_back(O->ArgStr);
139 // Handle named options.
140 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
141 // Add argument to the argument map!
142 if (OptionsMap.GetOrCreateValue(OptionNames[i], O).second != O) {
143 errs() << ProgramName << ": CommandLine Error: Argument '"
144 << OptionNames[i] << "' defined more than once!\n";
150 // Remember information about positional options.
151 if (O->getFormattingFlag() == cl::Positional)
152 PositionalOpts.push_back(O);
153 else if (O->getMiscFlags() & cl::Sink) // Remember sink options
154 SinkOpts.push_back(O);
155 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
157 O->error("Cannot specify more than one option with cl::ConsumeAfter!");
163 PositionalOpts.push_back(CAOpt);
165 // Make sure that they are in order of registration not backwards.
166 std::reverse(PositionalOpts.begin(), PositionalOpts.end());
170 /// LookupOption - Lookup the option specified by the specified option on the
171 /// command line. If there is a value specified (after an equal sign) return
172 /// that as well. This assumes that leading dashes have already been stripped.
173 static Option *LookupOption(StringRef &Arg, StringRef &Value,
174 const StringMap<Option*> &OptionsMap) {
175 // Reject all dashes.
176 if (Arg.empty()) return 0;
178 size_t EqualPos = Arg.find('=');
180 // If we have an equals sign, remember the value.
181 if (EqualPos == StringRef::npos) {
182 // Look up the option.
183 StringMap<Option*>::const_iterator I = OptionsMap.find(Arg);
184 return I != OptionsMap.end() ? I->second : 0;
187 // If the argument before the = is a valid option name, we match. If not,
188 // return Arg unmolested.
189 StringMap<Option*>::const_iterator I =
190 OptionsMap.find(Arg.substr(0, EqualPos));
191 if (I == OptionsMap.end()) return 0;
193 Value = Arg.substr(EqualPos+1);
194 Arg = Arg.substr(0, EqualPos);
198 /// LookupNearestOption - Lookup the closest match to the option specified by
199 /// the specified option on the command line. If there is a value specified
200 /// (after an equal sign) return that as well. This assumes that leading dashes
201 /// have already been stripped.
202 static Option *LookupNearestOption(StringRef Arg,
203 const StringMap<Option*> &OptionsMap,
204 std::string &NearestString) {
205 // Reject all dashes.
206 if (Arg.empty()) return 0;
208 // Split on any equal sign.
209 std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
210 StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
211 StringRef &RHS = SplitArg.second;
213 // Find the closest match.
215 unsigned BestDistance = 0;
216 for (StringMap<Option*>::const_iterator it = OptionsMap.begin(),
217 ie = OptionsMap.end(); it != ie; ++it) {
218 Option *O = it->second;
219 SmallVector<const char*, 16> OptionNames;
220 O->getExtraOptionNames(OptionNames);
222 OptionNames.push_back(O->ArgStr);
224 bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
225 StringRef Flag = PermitValue ? LHS : Arg;
226 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
227 StringRef Name = OptionNames[i];
228 unsigned Distance = StringRef(Name).edit_distance(
229 Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
230 if (!Best || Distance < BestDistance) {
232 BestDistance = Distance;
233 if (RHS.empty() || !PermitValue)
234 NearestString = OptionNames[i];
236 NearestString = std::string(OptionNames[i]) + "=" + RHS.str();
244 /// CommaSeparateAndAddOccurence - A wrapper around Handler->addOccurence() that
245 /// does special handling of cl::CommaSeparated options.
246 static bool CommaSeparateAndAddOccurence(Option *Handler, unsigned pos,
248 StringRef Value, bool MultiArg = false)
250 // Check to see if this option accepts a comma separated list of values. If
251 // it does, we have to split up the value into multiple values.
252 if (Handler->getMiscFlags() & CommaSeparated) {
253 StringRef Val(Value);
254 StringRef::size_type Pos = Val.find(',');
256 while (Pos != StringRef::npos) {
257 // Process the portion before the comma.
258 if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
260 // Erase the portion before the comma, AND the comma.
261 Val = Val.substr(Pos+1);
262 Value.substr(Pos+1); // Increment the original value pointer as well.
263 // Check for another comma.
270 if (Handler->addOccurrence(pos, ArgName, Value, MultiArg))
276 /// ProvideOption - For Value, this differentiates between an empty value ("")
277 /// and a null value (StringRef()). The later is accepted for arguments that
278 /// don't allow a value (-foo) the former is rejected (-foo=).
279 static inline bool ProvideOption(Option *Handler, StringRef ArgName,
280 StringRef Value, int argc,
281 const char *const *argv, int &i) {
282 // Is this a multi-argument option?
283 unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
285 // Enforce value requirements
286 switch (Handler->getValueExpectedFlag()) {
288 if (Value.data() == 0) { // No value specified?
290 return Handler->error("requires a value!");
291 // Steal the next argument, like for '-o filename'
295 case ValueDisallowed:
296 if (NumAdditionalVals > 0)
297 return Handler->error("multi-valued option specified"
298 " with ValueDisallowed modifier!");
301 return Handler->error("does not allow a value! '" +
302 Twine(Value) + "' specified.");
308 // If this isn't a multi-arg option, just run the handler.
309 if (NumAdditionalVals == 0)
310 return CommaSeparateAndAddOccurence(Handler, i, ArgName, Value);
312 // If it is, run the handle several times.
313 bool MultiArg = false;
316 if (CommaSeparateAndAddOccurence(Handler, i, ArgName, Value, MultiArg))
322 while (NumAdditionalVals > 0) {
324 return Handler->error("not enough values!");
327 if (CommaSeparateAndAddOccurence(Handler, i, ArgName, Value, MultiArg))
335 static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
337 return ProvideOption(Handler, Handler->ArgStr, Arg, 0, 0, Dummy);
341 // Option predicates...
342 static inline bool isGrouping(const Option *O) {
343 return O->getFormattingFlag() == cl::Grouping;
345 static inline bool isPrefixedOrGrouping(const Option *O) {
346 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
349 // getOptionPred - Check to see if there are any options that satisfy the
350 // specified predicate with names that are the prefixes in Name. This is
351 // checked by progressively stripping characters off of the name, checking to
352 // see if there options that satisfy the predicate. If we find one, return it,
353 // otherwise return null.
355 static Option *getOptionPred(StringRef Name, size_t &Length,
356 bool (*Pred)(const Option*),
357 const StringMap<Option*> &OptionsMap) {
359 StringMap<Option*>::const_iterator OMI = OptionsMap.find(Name);
361 // Loop while we haven't found an option and Name still has at least two
362 // characters in it (so that the next iteration will not be the empty
364 while (OMI == OptionsMap.end() && Name.size() > 1) {
365 Name = Name.substr(0, Name.size()-1); // Chop off the last character.
366 OMI = OptionsMap.find(Name);
369 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
370 Length = Name.size();
371 return OMI->second; // Found one!
373 return 0; // No option found!
376 /// HandlePrefixedOrGroupedOption - The specified argument string (which started
377 /// with at least one '-') does not fully match an available option. Check to
378 /// see if this is a prefix or grouped option. If so, split arg into output an
379 /// Arg/Value pair and return the Option to parse it with.
380 static Option *HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
382 const StringMap<Option*> &OptionsMap) {
383 if (Arg.size() == 1) return 0;
387 Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
388 if (PGOpt == 0) return 0;
390 // If the option is a prefixed option, then the value is simply the
391 // rest of the name... so fall through to later processing, by
392 // setting up the argument name flags and value fields.
393 if (PGOpt->getFormattingFlag() == cl::Prefix) {
394 Value = Arg.substr(Length);
395 Arg = Arg.substr(0, Length);
396 assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
400 // This must be a grouped option... handle them now. Grouping options can't
402 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
405 // Move current arg name out of Arg into OneArgName.
406 StringRef OneArgName = Arg.substr(0, Length);
407 Arg = Arg.substr(Length);
409 // Because ValueRequired is an invalid flag for grouped arguments,
410 // we don't need to pass argc/argv in.
411 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
412 "Option can not be cl::Grouping AND cl::ValueRequired!");
414 ErrorParsing |= ProvideOption(PGOpt, OneArgName,
415 StringRef(), 0, 0, Dummy);
417 // Get the next grouping option.
418 PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
419 } while (PGOpt && Length != Arg.size());
421 // Return the last option with Arg cut down to just the last one.
427 static bool RequiresValue(const Option *O) {
428 return O->getNumOccurrencesFlag() == cl::Required ||
429 O->getNumOccurrencesFlag() == cl::OneOrMore;
432 static bool EatsUnboundedNumberOfValues(const Option *O) {
433 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
434 O->getNumOccurrencesFlag() == cl::OneOrMore;
437 /// ParseCStringVector - Break INPUT up wherever one or more
438 /// whitespace characters are found, and store the resulting tokens in
439 /// OUTPUT. The tokens stored in OUTPUT are dynamically allocated
440 /// using strdup(), so it is the caller's responsibility to free()
443 static void ParseCStringVector(std::vector<char *> &OutputVector,
445 // Characters which will be treated as token separators:
446 StringRef Delims = " \v\f\t\r\n";
448 StringRef WorkStr(Input);
449 while (!WorkStr.empty()) {
450 // If the first character is a delimiter, strip them off.
451 if (Delims.find(WorkStr[0]) != StringRef::npos) {
452 size_t Pos = WorkStr.find_first_not_of(Delims);
453 if (Pos == StringRef::npos) Pos = WorkStr.size();
454 WorkStr = WorkStr.substr(Pos);
458 // Find position of first delimiter.
459 size_t Pos = WorkStr.find_first_of(Delims);
460 if (Pos == StringRef::npos) Pos = WorkStr.size();
462 // Everything from 0 to Pos is the next word to copy.
463 char *NewStr = (char*)malloc(Pos+1);
464 memcpy(NewStr, WorkStr.data(), Pos);
466 OutputVector.push_back(NewStr);
468 WorkStr = WorkStr.substr(Pos);
472 /// ParseEnvironmentOptions - An alternative entry point to the
473 /// CommandLine library, which allows you to read the program's name
474 /// from the caller (as PROGNAME) and its command-line arguments from
475 /// an environment variable (whose name is given in ENVVAR).
477 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
478 const char *Overview) {
480 assert(progName && "Program name not specified");
481 assert(envVar && "Environment variable name missing");
483 // Get the environment variable they want us to parse options out of.
484 const char *envValue = getenv(envVar);
488 // Get program's "name", which we wouldn't know without the caller
490 std::vector<char*> newArgv;
491 newArgv.push_back(strdup(progName));
493 // Parse the value of the environment variable into a "command line"
494 // and hand it off to ParseCommandLineOptions().
495 ParseCStringVector(newArgv, envValue);
496 int newArgc = static_cast<int>(newArgv.size());
497 ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
499 // Free all the strdup()ed strings.
500 for (std::vector<char*>::iterator i = newArgv.begin(), e = newArgv.end();
506 /// ExpandResponseFiles - Copy the contents of argv into newArgv,
507 /// substituting the contents of the response files for the arguments
509 static void ExpandResponseFiles(unsigned argc, const char*const* argv,
510 std::vector<char*>& newArgv) {
511 for (unsigned i = 1; i != argc; ++i) {
512 const char *arg = argv[i];
515 // TODO: we should also support recursive loading of response files,
516 // since this is how gcc behaves. (From their man page: "The file may
517 // itself contain additional @file options; any such options will be
518 // processed recursively.")
520 // Mmap the response file into memory.
521 OwningPtr<MemoryBuffer> respFilePtr;
522 if (!MemoryBuffer::getFile(arg + 1, respFilePtr)) {
523 ParseCStringVector(newArgv, respFilePtr->getBufferStart());
527 newArgv.push_back(strdup(arg));
531 void cl::ParseCommandLineOptions(int argc, const char * const *argv,
532 const char *Overview) {
533 // Process all registered options.
534 SmallVector<Option*, 4> PositionalOpts;
535 SmallVector<Option*, 4> SinkOpts;
536 StringMap<Option*> Opts;
537 GetOptionInfo(PositionalOpts, SinkOpts, Opts);
539 assert((!Opts.empty() || !PositionalOpts.empty()) &&
540 "No options specified!");
542 // Expand response files.
543 std::vector<char*> newArgv;
544 newArgv.push_back(strdup(argv[0]));
545 ExpandResponseFiles(argc, argv, newArgv);
547 argc = static_cast<int>(newArgv.size());
549 // Copy the program name into ProgName, making sure not to overflow it.
550 std::string ProgName = sys::path::filename(argv[0]);
551 size_t Len = std::min(ProgName.size(), size_t(79));
552 memcpy(ProgramName, ProgName.data(), Len);
553 ProgramName[Len] = '\0';
555 ProgramOverview = Overview;
556 bool ErrorParsing = false;
558 // Check out the positional arguments to collect information about them.
559 unsigned NumPositionalRequired = 0;
561 // Determine whether or not there are an unlimited number of positionals
562 bool HasUnlimitedPositionals = false;
564 Option *ConsumeAfterOpt = 0;
565 if (!PositionalOpts.empty()) {
566 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
567 assert(PositionalOpts.size() > 1 &&
568 "Cannot specify cl::ConsumeAfter without a positional argument!");
569 ConsumeAfterOpt = PositionalOpts[0];
572 // Calculate how many positional values are _required_.
573 bool UnboundedFound = false;
574 for (size_t i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
576 Option *Opt = PositionalOpts[i];
577 if (RequiresValue(Opt))
578 ++NumPositionalRequired;
579 else if (ConsumeAfterOpt) {
580 // ConsumeAfter cannot be combined with "optional" positional options
581 // unless there is only one positional argument...
582 if (PositionalOpts.size() > 2)
584 Opt->error("error - this positional option will never be matched, "
585 "because it does not Require a value, and a "
586 "cl::ConsumeAfter option is active!");
587 } else if (UnboundedFound && !Opt->ArgStr[0]) {
588 // This option does not "require" a value... Make sure this option is
589 // not specified after an option that eats all extra arguments, or this
590 // one will never get any!
592 ErrorParsing |= Opt->error("error - option can never match, because "
593 "another positional argument will match an "
594 "unbounded number of values, and this option"
595 " does not require a value!");
597 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
599 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
602 // PositionalVals - A vector of "positional" arguments we accumulate into
603 // the process at the end.
605 SmallVector<std::pair<StringRef,unsigned>, 4> PositionalVals;
607 // If the program has named positional arguments, and the name has been run
608 // across, keep track of which positional argument was named. Otherwise put
609 // the positional args into the PositionalVals list...
610 Option *ActivePositionalArg = 0;
612 // Loop over all of the arguments... processing them.
613 bool DashDashFound = false; // Have we read '--'?
614 for (int i = 1; i < argc; ++i) {
616 Option *NearestHandler = 0;
617 std::string NearestHandlerString;
619 StringRef ArgName = "";
621 // If the option list changed, this means that some command line
622 // option has just been registered or deregistered. This can occur in
623 // response to things like -load, etc. If this happens, rescan the options.
624 if (OptionListChanged) {
625 PositionalOpts.clear();
628 GetOptionInfo(PositionalOpts, SinkOpts, Opts);
629 OptionListChanged = false;
632 // Check to see if this is a positional argument. This argument is
633 // considered to be positional if it doesn't start with '-', if it is "-"
634 // itself, or if we have seen "--" already.
636 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
637 // Positional argument!
638 if (ActivePositionalArg) {
639 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
640 continue; // We are done!
643 if (!PositionalOpts.empty()) {
644 PositionalVals.push_back(std::make_pair(argv[i],i));
646 // All of the positional arguments have been fulfulled, give the rest to
647 // the consume after option... if it's specified...
649 if (PositionalVals.size() >= NumPositionalRequired &&
650 ConsumeAfterOpt != 0) {
651 for (++i; i < argc; ++i)
652 PositionalVals.push_back(std::make_pair(argv[i],i));
653 break; // Handle outside of the argument processing loop...
656 // Delay processing positional arguments until the end...
659 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
661 DashDashFound = true; // This is the mythical "--"?
662 continue; // Don't try to process it as an argument itself.
663 } else if (ActivePositionalArg &&
664 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
665 // If there is a positional argument eating options, check to see if this
666 // option is another positional argument. If so, treat it as an argument,
667 // otherwise feed it to the eating positional.
669 // Eat leading dashes.
670 while (!ArgName.empty() && ArgName[0] == '-')
671 ArgName = ArgName.substr(1);
673 Handler = LookupOption(ArgName, Value, Opts);
674 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
675 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
676 continue; // We are done!
679 } else { // We start with a '-', must be an argument.
681 // Eat leading dashes.
682 while (!ArgName.empty() && ArgName[0] == '-')
683 ArgName = ArgName.substr(1);
685 Handler = LookupOption(ArgName, Value, Opts);
687 // Check to see if this "option" is really a prefixed or grouped argument.
689 Handler = HandlePrefixedOrGroupedOption(ArgName, Value,
692 // Otherwise, look for the closest available option to report to the user
693 // in the upcoming error.
694 if (Handler == 0 && SinkOpts.empty())
695 NearestHandler = LookupNearestOption(ArgName, Opts,
696 NearestHandlerString);
700 if (SinkOpts.empty()) {
701 errs() << ProgramName << ": Unknown command line argument '"
702 << argv[i] << "'. Try: '" << argv[0] << " -help'\n";
704 if (NearestHandler) {
705 // If we know a near match, report it as well.
706 errs() << ProgramName << ": Did you mean '-"
707 << NearestHandlerString << "'?\n";
712 for (SmallVectorImpl<Option*>::iterator I = SinkOpts.begin(),
713 E = SinkOpts.end(); I != E ; ++I)
714 (*I)->addOccurrence(i, "", argv[i]);
719 // If this is a named positional argument, just remember that it is the
721 if (Handler->getFormattingFlag() == cl::Positional)
722 ActivePositionalArg = Handler;
724 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
727 // Check and handle positional arguments now...
728 if (NumPositionalRequired > PositionalVals.size()) {
729 errs() << ProgramName
730 << ": Not enough positional command line arguments specified!\n"
731 << "Must specify at least " << NumPositionalRequired
732 << " positional arguments: See: " << argv[0] << " -help\n";
735 } else if (!HasUnlimitedPositionals &&
736 PositionalVals.size() > PositionalOpts.size()) {
737 errs() << ProgramName
738 << ": Too many positional arguments specified!\n"
739 << "Can specify at most " << PositionalOpts.size()
740 << " positional arguments: See: " << argv[0] << " -help\n";
743 } else if (ConsumeAfterOpt == 0) {
744 // Positional args have already been handled if ConsumeAfter is specified.
745 unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
746 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
747 if (RequiresValue(PositionalOpts[i])) {
748 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
749 PositionalVals[ValNo].second);
751 --NumPositionalRequired; // We fulfilled our duty...
754 // If we _can_ give this option more arguments, do so now, as long as we
755 // do not give it values that others need. 'Done' controls whether the
756 // option even _WANTS_ any more.
758 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
759 while (NumVals-ValNo > NumPositionalRequired && !Done) {
760 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
762 Done = true; // Optional arguments want _at most_ one value
764 case cl::ZeroOrMore: // Zero or more will take all they can get...
765 case cl::OneOrMore: // One or more will take all they can get...
766 ProvidePositionalOption(PositionalOpts[i],
767 PositionalVals[ValNo].first,
768 PositionalVals[ValNo].second);
772 llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
773 "positional argument processing!");
778 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
780 for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
781 if (RequiresValue(PositionalOpts[j])) {
782 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
783 PositionalVals[ValNo].first,
784 PositionalVals[ValNo].second);
788 // Handle the case where there is just one positional option, and it's
789 // optional. In this case, we want to give JUST THE FIRST option to the
790 // positional option and keep the rest for the consume after. The above
791 // loop would have assigned no values to positional options in this case.
793 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
794 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
795 PositionalVals[ValNo].first,
796 PositionalVals[ValNo].second);
800 // Handle over all of the rest of the arguments to the
801 // cl::ConsumeAfter command line option...
802 for (; ValNo != PositionalVals.size(); ++ValNo)
803 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
804 PositionalVals[ValNo].first,
805 PositionalVals[ValNo].second);
808 // Loop over args and make sure all required args are specified!
809 for (StringMap<Option*>::iterator I = Opts.begin(),
810 E = Opts.end(); I != E; ++I) {
811 switch (I->second->getNumOccurrencesFlag()) {
814 if (I->second->getNumOccurrences() == 0) {
815 I->second->error("must be specified at least once!");
824 // Now that we know if -debug is specified, we can use it.
825 // Note that if ReadResponseFiles == true, this must be done before the
826 // memory allocated for the expanded command line is free()d below.
827 DEBUG(dbgs() << "Args: ";
828 for (int i = 0; i < argc; ++i)
829 dbgs() << argv[i] << ' ';
833 // Free all of the memory allocated to the map. Command line options may only
834 // be processed once!
836 PositionalOpts.clear();
839 // Free the memory allocated by ExpandResponseFiles.
840 // Free all the strdup()ed strings.
841 for (std::vector<char*>::iterator i = newArgv.begin(), e = newArgv.end();
845 // If we had an error processing our arguments, don't let the program execute
846 if (ErrorParsing) exit(1);
849 //===----------------------------------------------------------------------===//
850 // Option Base class implementation
853 bool Option::error(const Twine &Message, StringRef ArgName) {
854 if (ArgName.data() == 0) ArgName = ArgStr;
856 errs() << HelpStr; // Be nice for positional arguments
858 errs() << ProgramName << ": for the -" << ArgName;
860 errs() << " option: " << Message << "\n";
864 bool Option::addOccurrence(unsigned pos, StringRef ArgName,
865 StringRef Value, bool MultiArg) {
867 NumOccurrences++; // Increment the number of times we have been seen
869 switch (getNumOccurrencesFlag()) {
871 if (NumOccurrences > 1)
872 return error("may only occur zero or one times!", ArgName);
875 if (NumOccurrences > 1)
876 return error("must occur exactly one time!", ArgName);
880 case ConsumeAfter: break;
883 return handleOccurrence(pos, ArgName, Value);
887 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
888 // has been specified yet.
890 static const char *getValueStr(const Option &O, const char *DefaultMsg) {
891 if (O.ValueStr[0] == 0) return DefaultMsg;
895 //===----------------------------------------------------------------------===//
896 // cl::alias class implementation
899 // Return the width of the option tag for printing...
900 size_t alias::getOptionWidth() const {
901 return std::strlen(ArgStr)+6;
904 static void printHelpStr(StringRef HelpStr, size_t Indent,
905 size_t FirstLineIndentedBy) {
906 std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
907 outs().indent(Indent - FirstLineIndentedBy) << " - " << Split.first << "\n";
908 while (!Split.second.empty()) {
909 Split = Split.second.split('\n');
910 outs().indent(Indent) << Split.first << "\n";
914 // Print out the option for the alias.
915 void alias::printOptionInfo(size_t GlobalWidth) const {
916 outs() << " -" << ArgStr;
917 printHelpStr(HelpStr, GlobalWidth, std::strlen(ArgStr) + 6);
920 //===----------------------------------------------------------------------===//
921 // Parser Implementation code...
924 // basic_parser implementation
927 // Return the width of the option tag for printing...
928 size_t basic_parser_impl::getOptionWidth(const Option &O) const {
929 size_t Len = std::strlen(O.ArgStr);
930 if (const char *ValName = getValueName())
931 Len += std::strlen(getValueStr(O, ValName))+3;
936 // printOptionInfo - Print out information about this option. The
937 // to-be-maintained width is specified.
939 void basic_parser_impl::printOptionInfo(const Option &O,
940 size_t GlobalWidth) const {
941 outs() << " -" << O.ArgStr;
943 if (const char *ValName = getValueName())
944 outs() << "=<" << getValueStr(O, ValName) << '>';
946 printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
949 void basic_parser_impl::printOptionName(const Option &O,
950 size_t GlobalWidth) const {
951 outs() << " -" << O.ArgStr;
952 outs().indent(GlobalWidth-std::strlen(O.ArgStr));
956 // parser<bool> implementation
958 bool parser<bool>::parse(Option &O, StringRef ArgName,
959 StringRef Arg, bool &Value) {
960 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
966 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
970 return O.error("'" + Arg +
971 "' is invalid value for boolean argument! Try 0 or 1");
974 // parser<boolOrDefault> implementation
976 bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName,
977 StringRef Arg, boolOrDefault &Value) {
978 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
983 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
988 return O.error("'" + Arg +
989 "' is invalid value for boolean argument! Try 0 or 1");
992 // parser<int> implementation
994 bool parser<int>::parse(Option &O, StringRef ArgName,
995 StringRef Arg, int &Value) {
996 if (Arg.getAsInteger(0, Value))
997 return O.error("'" + Arg + "' value invalid for integer argument!");
1001 // parser<unsigned> implementation
1003 bool parser<unsigned>::parse(Option &O, StringRef ArgName,
1004 StringRef Arg, unsigned &Value) {
1006 if (Arg.getAsInteger(0, Value))
1007 return O.error("'" + Arg + "' value invalid for uint argument!");
1011 // parser<unsigned long long> implementation
1013 bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
1014 StringRef Arg, unsigned long long &Value){
1016 if (Arg.getAsInteger(0, Value))
1017 return O.error("'" + Arg + "' value invalid for uint argument!");
1021 // parser<double>/parser<float> implementation
1023 static bool parseDouble(Option &O, StringRef Arg, double &Value) {
1024 SmallString<32> TmpStr(Arg.begin(), Arg.end());
1025 const char *ArgStart = TmpStr.c_str();
1027 Value = strtod(ArgStart, &End);
1029 return O.error("'" + Arg + "' value invalid for floating point argument!");
1033 bool parser<double>::parse(Option &O, StringRef ArgName,
1034 StringRef Arg, double &Val) {
1035 return parseDouble(O, Arg, Val);
1038 bool parser<float>::parse(Option &O, StringRef ArgName,
1039 StringRef Arg, float &Val) {
1041 if (parseDouble(O, Arg, dVal))
1049 // generic_parser_base implementation
1052 // findOption - Return the option number corresponding to the specified
1053 // argument string. If the option is not found, getNumOptions() is returned.
1055 unsigned generic_parser_base::findOption(const char *Name) {
1056 unsigned e = getNumOptions();
1058 for (unsigned i = 0; i != e; ++i) {
1059 if (strcmp(getOption(i), Name) == 0)
1066 // Return the width of the option tag for printing...
1067 size_t generic_parser_base::getOptionWidth(const Option &O) const {
1068 if (O.hasArgStr()) {
1069 size_t Size = std::strlen(O.ArgStr)+6;
1070 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1071 Size = std::max(Size, std::strlen(getOption(i))+8);
1074 size_t BaseSize = 0;
1075 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1076 BaseSize = std::max(BaseSize, std::strlen(getOption(i))+8);
1081 // printOptionInfo - Print out information about this option. The
1082 // to-be-maintained width is specified.
1084 void generic_parser_base::printOptionInfo(const Option &O,
1085 size_t GlobalWidth) const {
1086 if (O.hasArgStr()) {
1087 outs() << " -" << O.ArgStr;
1088 printHelpStr(O.HelpStr, GlobalWidth, std::strlen(O.ArgStr) + 6);
1090 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1091 size_t NumSpaces = GlobalWidth-strlen(getOption(i))-8;
1092 outs() << " =" << getOption(i);
1093 outs().indent(NumSpaces) << " - " << getDescription(i) << '\n';
1097 outs() << " " << O.HelpStr << '\n';
1098 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1099 const char *Option = getOption(i);
1100 outs() << " -" << Option;
1101 printHelpStr(getDescription(i), GlobalWidth, std::strlen(Option) + 8);
1106 static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1108 // printGenericOptionDiff - Print the value of this option and it's default.
1110 // "Generic" options have each value mapped to a name.
1111 void generic_parser_base::
1112 printGenericOptionDiff(const Option &O, const GenericOptionValue &Value,
1113 const GenericOptionValue &Default,
1114 size_t GlobalWidth) const {
1115 outs() << " -" << O.ArgStr;
1116 outs().indent(GlobalWidth-std::strlen(O.ArgStr));
1118 unsigned NumOpts = getNumOptions();
1119 for (unsigned i = 0; i != NumOpts; ++i) {
1120 if (Value.compare(getOptionValue(i)))
1123 outs() << "= " << getOption(i);
1124 size_t L = std::strlen(getOption(i));
1125 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1126 outs().indent(NumSpaces) << " (default: ";
1127 for (unsigned j = 0; j != NumOpts; ++j) {
1128 if (Default.compare(getOptionValue(j)))
1130 outs() << getOption(j);
1136 outs() << "= *unknown option value*\n";
1139 // printOptionDiff - Specializations for printing basic value types.
1141 #define PRINT_OPT_DIFF(T) \
1143 printOptionDiff(const Option &O, T V, OptionValue<T> D, \
1144 size_t GlobalWidth) const { \
1145 printOptionName(O, GlobalWidth); \
1148 raw_string_ostream SS(Str); \
1151 outs() << "= " << Str; \
1152 size_t NumSpaces = MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0;\
1153 outs().indent(NumSpaces) << " (default: "; \
1155 outs() << D.getValue(); \
1157 outs() << "*no default*"; \
1161 PRINT_OPT_DIFF(bool)
1162 PRINT_OPT_DIFF(boolOrDefault)
1164 PRINT_OPT_DIFF(unsigned)
1165 PRINT_OPT_DIFF(unsigned long long)
1166 PRINT_OPT_DIFF(double)
1167 PRINT_OPT_DIFF(float)
1168 PRINT_OPT_DIFF(char)
1170 void parser<std::string>::
1171 printOptionDiff(const Option &O, StringRef V, OptionValue<std::string> D,
1172 size_t GlobalWidth) const {
1173 printOptionName(O, GlobalWidth);
1174 outs() << "= " << V;
1175 size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
1176 outs().indent(NumSpaces) << " (default: ";
1178 outs() << D.getValue();
1180 outs() << "*no default*";
1184 // Print a placeholder for options that don't yet support printOptionDiff().
1185 void basic_parser_impl::
1186 printOptionNoValue(const Option &O, size_t GlobalWidth) const {
1187 printOptionName(O, GlobalWidth);
1188 outs() << "= *cannot print option value*\n";
1191 //===----------------------------------------------------------------------===//
1192 // -help and -help-hidden option implementation
1195 static int OptNameCompare(const void *LHS, const void *RHS) {
1196 typedef std::pair<const char *, Option*> pair_ty;
1198 return strcmp(((const pair_ty*)LHS)->first, ((const pair_ty*)RHS)->first);
1201 // Copy Options into a vector so we can sort them as we like.
1203 sortOpts(StringMap<Option*> &OptMap,
1204 SmallVectorImpl< std::pair<const char *, Option*> > &Opts,
1206 SmallPtrSet<Option*, 128> OptionSet; // Duplicate option detection.
1208 for (StringMap<Option*>::iterator I = OptMap.begin(), E = OptMap.end();
1210 // Ignore really-hidden options.
1211 if (I->second->getOptionHiddenFlag() == ReallyHidden)
1214 // Unless showhidden is set, ignore hidden flags.
1215 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
1218 // If we've already seen this option, don't add it to the list again.
1219 if (!OptionSet.insert(I->second))
1222 Opts.push_back(std::pair<const char *, Option*>(I->getKey().data(),
1226 // Sort the options list alphabetically.
1227 qsort(Opts.data(), Opts.size(), sizeof(Opts[0]), OptNameCompare);
1234 const bool ShowHidden;
1235 typedef SmallVector<std::pair<const char *, Option*>,128> StrOptionPairVector;
1236 // Print the options. Opts is assumed to be alphabetically sorted.
1237 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1238 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1239 Opts[i].second->printOptionInfo(MaxArgLen);
1243 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
1244 virtual ~HelpPrinter() {}
1246 // Invoke the printer.
1247 void operator=(bool Value) {
1248 if (Value == false) return;
1250 // Get all the options.
1251 SmallVector<Option*, 4> PositionalOpts;
1252 SmallVector<Option*, 4> SinkOpts;
1253 StringMap<Option*> OptMap;
1254 GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
1256 StrOptionPairVector Opts;
1257 sortOpts(OptMap, Opts, ShowHidden);
1259 if (ProgramOverview)
1260 outs() << "OVERVIEW: " << ProgramOverview << "\n";
1262 outs() << "USAGE: " << ProgramName << " [options]";
1264 // Print out the positional options.
1265 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists...
1266 if (!PositionalOpts.empty() &&
1267 PositionalOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
1268 CAOpt = PositionalOpts[0];
1270 for (size_t i = CAOpt != 0, e = PositionalOpts.size(); i != e; ++i) {
1271 if (PositionalOpts[i]->ArgStr[0])
1272 outs() << " --" << PositionalOpts[i]->ArgStr;
1273 outs() << " " << PositionalOpts[i]->HelpStr;
1276 // Print the consume after option info if it exists...
1277 if (CAOpt) outs() << " " << CAOpt->HelpStr;
1281 // Compute the maximum argument length...
1282 size_t MaxArgLen = 0;
1283 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1284 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1286 outs() << "OPTIONS:\n";
1287 printOptions(Opts, MaxArgLen);
1289 // Print any extra help the user has declared.
1290 for (std::vector<const char *>::iterator I = MoreHelp->begin(),
1291 E = MoreHelp->end();
1296 // Halt the program since help information was printed
1301 class CategorizedHelpPrinter : public HelpPrinter {
1303 explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
1305 // Helper function for printOptions().
1306 // It shall return true if A's name should be lexographically
1307 // ordered before B's name. It returns false otherwise.
1308 static bool OptionCategoryCompare(OptionCategory *A, OptionCategory *B) {
1309 int Length = strcmp(A->getName(), B->getName());
1310 assert(Length != 0 && "Duplicate option categories");
1314 // Make sure we inherit our base class's operator=()
1315 using HelpPrinter::operator= ;
1318 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1319 std::vector<OptionCategory *> SortedCategories;
1320 std::map<OptionCategory *, std::vector<Option *> > CategorizedOptions;
1322 // Collect registered option categories into vector in preperation for
1324 for (OptionCatSet::const_iterator I = RegisteredOptionCategories->begin(),
1325 E = RegisteredOptionCategories->end();
1327 SortedCategories.push_back(*I);
1329 // Sort the different option categories alphabetically.
1330 assert(SortedCategories.size() > 0 && "No option categories registered!");
1331 std::sort(SortedCategories.begin(), SortedCategories.end(),
1332 OptionCategoryCompare);
1334 // Create map to empty vectors.
1335 for (std::vector<OptionCategory *>::const_iterator
1336 I = SortedCategories.begin(),
1337 E = SortedCategories.end();
1339 CategorizedOptions[*I] = std::vector<Option *>();
1341 // Walk through pre-sorted options and assign into categories.
1342 // Because the options are already alphabetically sorted the
1343 // options within categories will also be alphabetically sorted.
1344 for (size_t I = 0, E = Opts.size(); I != E; ++I) {
1345 Option *Opt = Opts[I].second;
1346 assert(CategorizedOptions.count(Opt->Category) > 0 &&
1347 "Option has an unregistered category");
1348 CategorizedOptions[Opt->Category].push_back(Opt);
1352 for (std::vector<OptionCategory *>::const_iterator
1353 Category = SortedCategories.begin(),
1354 E = SortedCategories.end();
1355 Category != E; ++Category) {
1356 // Hide empty categories for -help, but show for -help-hidden.
1357 bool IsEmptyCategory = CategorizedOptions[*Category].size() == 0;
1358 if (!ShowHidden && IsEmptyCategory)
1361 // Print category information.
1363 outs() << (*Category)->getName() << ":\n";
1365 // Check if description is set.
1366 if ((*Category)->getDescription() != 0)
1367 outs() << (*Category)->getDescription() << "\n\n";
1371 // When using -help-hidden explicitly state if the category has no
1372 // options associated with it.
1373 if (IsEmptyCategory) {
1374 outs() << " This option category has no options.\n";
1377 // Loop over the options in the category and print.
1378 for (std::vector<Option *>::const_iterator
1379 Opt = CategorizedOptions[*Category].begin(),
1380 E = CategorizedOptions[*Category].end();
1382 (*Opt)->printOptionInfo(MaxArgLen);
1387 // This wraps the Uncategorizing and Categorizing printers and decides
1388 // at run time which should be invoked.
1389 class HelpPrinterWrapper {
1391 HelpPrinter &UncategorizedPrinter;
1392 CategorizedHelpPrinter &CategorizedPrinter;
1395 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
1396 CategorizedHelpPrinter &CategorizedPrinter) :
1397 UncategorizedPrinter(UncategorizedPrinter),
1398 CategorizedPrinter(CategorizedPrinter) { }
1400 // Invoke the printer.
1401 void operator=(bool Value);
1404 } // End anonymous namespace
1406 // Declare the four HelpPrinter instances that are used to print out help, or
1407 // help-hidden as an uncategorized list or in categories.
1408 static HelpPrinter UncategorizedNormalPrinter(false);
1409 static HelpPrinter UncategorizedHiddenPrinter(true);
1410 static CategorizedHelpPrinter CategorizedNormalPrinter(false);
1411 static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
1414 // Declare HelpPrinter wrappers that will decide whether or not to invoke
1415 // a categorizing help printer
1416 static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
1417 CategorizedNormalPrinter);
1418 static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
1419 CategorizedHiddenPrinter);
1421 // Define uncategorized help printers.
1422 // -help-list is hidden by default because if Option categories are being used
1423 // then -help behaves the same as -help-list.
1424 static cl::opt<HelpPrinter, true, parser<bool> >
1426 cl::desc("Display list of available options (-help-list-hidden for more)"),
1427 cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed);
1429 static cl::opt<HelpPrinter, true, parser<bool> >
1430 HLHOp("help-list-hidden",
1431 cl::desc("Display list of all available options"),
1432 cl::location(UncategorizedHiddenPrinter), cl::Hidden, cl::ValueDisallowed);
1434 // Define uncategorized/categorized help printers. These printers change their
1435 // behaviour at runtime depending on whether one or more Option categories have
1437 static cl::opt<HelpPrinterWrapper, true, parser<bool> >
1438 HOp("help", cl::desc("Display available options (-help-hidden for more)"),
1439 cl::location(WrappedNormalPrinter), cl::ValueDisallowed);
1441 static cl::opt<HelpPrinterWrapper, true, parser<bool> >
1442 HHOp("help-hidden", cl::desc("Display all available options"),
1443 cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed);
1447 static cl::opt<bool>
1448 PrintOptions("print-options",
1449 cl::desc("Print non-default options after command line parsing"),
1450 cl::Hidden, cl::init(false));
1452 static cl::opt<bool>
1453 PrintAllOptions("print-all-options",
1454 cl::desc("Print all option values after command line parsing"),
1455 cl::Hidden, cl::init(false));
1457 void HelpPrinterWrapper::operator=(bool Value) {
1461 // Decide which printer to invoke. If more than one option category is
1462 // registered then it is useful to show the categorized help instead of
1463 // uncategorized help.
1464 if (RegisteredOptionCategories->size() > 1) {
1465 // unhide -help-list option so user can have uncategorized output if they
1467 HLOp.setHiddenFlag(NotHidden);
1469 CategorizedPrinter = true; // Invoke categorized printer
1472 UncategorizedPrinter = true; // Invoke uncategorized printer
1475 // Print the value of each option.
1476 void cl::PrintOptionValues() {
1477 if (!PrintOptions && !PrintAllOptions) return;
1479 // Get all the options.
1480 SmallVector<Option*, 4> PositionalOpts;
1481 SmallVector<Option*, 4> SinkOpts;
1482 StringMap<Option*> OptMap;
1483 GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
1485 SmallVector<std::pair<const char *, Option*>, 128> Opts;
1486 sortOpts(OptMap, Opts, /*ShowHidden*/true);
1488 // Compute the maximum argument length...
1489 size_t MaxArgLen = 0;
1490 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1491 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1493 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1494 Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
1497 static void (*OverrideVersionPrinter)() = 0;
1499 static std::vector<void (*)()>* ExtraVersionPrinters = 0;
1502 class VersionPrinter {
1505 raw_ostream &OS = outs();
1506 OS << "LLVM (http://llvm.org/):\n"
1507 << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
1508 #ifdef LLVM_VERSION_INFO
1509 OS << LLVM_VERSION_INFO;
1512 #ifndef __OPTIMIZE__
1513 OS << "DEBUG build";
1515 OS << "Optimized build";
1518 OS << " with assertions";
1520 std::string CPU = sys::getHostCPUName();
1521 if (CPU == "generic") CPU = "(unknown)";
1523 #if (ENABLE_TIMESTAMPS == 1)
1524 << " Built " << __DATE__ << " (" << __TIME__ << ").\n"
1526 << " Default target: " << sys::getDefaultTargetTriple() << '\n'
1527 << " Host CPU: " << CPU << '\n';
1529 void operator=(bool OptionWasSpecified) {
1530 if (!OptionWasSpecified) return;
1532 if (OverrideVersionPrinter != 0) {
1533 (*OverrideVersionPrinter)();
1538 // Iterate over any registered extra printers and call them to add further
1540 if (ExtraVersionPrinters != 0) {
1542 for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(),
1543 E = ExtraVersionPrinters->end();
1551 } // End anonymous namespace
1554 // Define the --version option that prints out the LLVM version for the tool
1555 static VersionPrinter VersionPrinterInstance;
1557 static cl::opt<VersionPrinter, true, parser<bool> >
1558 VersOp("version", cl::desc("Display the version of this program"),
1559 cl::location(VersionPrinterInstance), cl::ValueDisallowed);
1561 // Utility function for printing the help message.
1562 void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
1563 // This looks weird, but it actually prints the help message. The Printers are
1564 // types of HelpPrinter and the help gets printed when its operator= is
1565 // invoked. That's because the "normal" usages of the help printer is to be
1566 // assigned true/false depending on whether -help or -help-hidden was given or
1567 // not. Since we're circumventing that we have to make it look like -help or
1568 // -help-hidden were given, so we assign true.
1570 if (!Hidden && !Categorized)
1571 UncategorizedNormalPrinter = true;
1572 else if (!Hidden && Categorized)
1573 CategorizedNormalPrinter = true;
1574 else if (Hidden && !Categorized)
1575 UncategorizedHiddenPrinter = true;
1577 CategorizedHiddenPrinter = true;
1580 /// Utility function for printing version number.
1581 void cl::PrintVersionMessage() {
1582 VersionPrinterInstance.print();
1585 void cl::SetVersionPrinter(void (*func)()) {
1586 OverrideVersionPrinter = func;
1589 void cl::AddExtraVersionPrinter(void (*func)()) {
1590 if (ExtraVersionPrinters == 0)
1591 ExtraVersionPrinters = new std::vector<void (*)()>;
1593 ExtraVersionPrinters->push_back(func);
1596 void cl::getRegisteredOptions(StringMap<Option*> &Map)
1598 // Get all the options.
1599 SmallVector<Option*, 4> PositionalOpts; //NOT USED
1600 SmallVector<Option*, 4> SinkOpts; //NOT USED
1601 assert(Map.size() == 0 && "StringMap must be empty");
1602 GetOptionInfo(PositionalOpts, SinkOpts, Map);