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"
39 //===----------------------------------------------------------------------===//
40 // Template instantiations and anchors.
42 namespace llvm { namespace cl {
43 TEMPLATE_INSTANTIATION(class basic_parser<bool>);
44 TEMPLATE_INSTANTIATION(class basic_parser<boolOrDefault>);
45 TEMPLATE_INSTANTIATION(class basic_parser<int>);
46 TEMPLATE_INSTANTIATION(class basic_parser<unsigned>);
47 TEMPLATE_INSTANTIATION(class basic_parser<unsigned long long>);
48 TEMPLATE_INSTANTIATION(class basic_parser<double>);
49 TEMPLATE_INSTANTIATION(class basic_parser<float>);
50 TEMPLATE_INSTANTIATION(class basic_parser<std::string>);
51 TEMPLATE_INSTANTIATION(class basic_parser<char>);
53 TEMPLATE_INSTANTIATION(class opt<unsigned>);
54 TEMPLATE_INSTANTIATION(class opt<int>);
55 TEMPLATE_INSTANTIATION(class opt<std::string>);
56 TEMPLATE_INSTANTIATION(class opt<char>);
57 TEMPLATE_INSTANTIATION(class opt<bool>);
58 } } // end namespace llvm::cl
60 void GenericOptionValue::anchor() {}
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();
110 //===----------------------------------------------------------------------===//
111 // Basic, shared command line option processing machinery.
114 /// GetOptionInfo - Scan the list of registered options, turning them into data
115 /// structures that are easier to handle.
116 static void GetOptionInfo(SmallVectorImpl<Option*> &PositionalOpts,
117 SmallVectorImpl<Option*> &SinkOpts,
118 StringMap<Option*> &OptionsMap) {
119 SmallVector<const char*, 16> OptionNames;
120 Option *CAOpt = 0; // The ConsumeAfter option if it exists.
121 for (Option *O = RegisteredOptionList; O; O = O->getNextRegisteredOption()) {
122 // If this option wants to handle multiple option names, get the full set.
123 // This handles enum options like "-O1 -O2" etc.
124 O->getExtraOptionNames(OptionNames);
126 OptionNames.push_back(O->ArgStr);
128 // Handle named options.
129 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
130 // Add argument to the argument map!
131 if (OptionsMap.GetOrCreateValue(OptionNames[i], O).second != O) {
132 errs() << ProgramName << ": CommandLine Error: Argument '"
133 << OptionNames[i] << "' defined more than once!\n";
139 // Remember information about positional options.
140 if (O->getFormattingFlag() == cl::Positional)
141 PositionalOpts.push_back(O);
142 else if (O->getMiscFlags() & cl::Sink) // Remember sink options
143 SinkOpts.push_back(O);
144 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
146 O->error("Cannot specify more than one option with cl::ConsumeAfter!");
152 PositionalOpts.push_back(CAOpt);
154 // Make sure that they are in order of registration not backwards.
155 std::reverse(PositionalOpts.begin(), PositionalOpts.end());
159 /// LookupOption - Lookup the option specified by the specified option on the
160 /// command line. If there is a value specified (after an equal sign) return
161 /// that as well. This assumes that leading dashes have already been stripped.
162 static Option *LookupOption(StringRef &Arg, StringRef &Value,
163 const StringMap<Option*> &OptionsMap) {
164 // Reject all dashes.
165 if (Arg.empty()) return 0;
167 size_t EqualPos = Arg.find('=');
169 // If we have an equals sign, remember the value.
170 if (EqualPos == StringRef::npos) {
171 // Look up the option.
172 StringMap<Option*>::const_iterator I = OptionsMap.find(Arg);
173 return I != OptionsMap.end() ? I->second : 0;
176 // If the argument before the = is a valid option name, we match. If not,
177 // return Arg unmolested.
178 StringMap<Option*>::const_iterator I =
179 OptionsMap.find(Arg.substr(0, EqualPos));
180 if (I == OptionsMap.end()) return 0;
182 Value = Arg.substr(EqualPos+1);
183 Arg = Arg.substr(0, EqualPos);
187 /// LookupNearestOption - Lookup the closest match to the option specified by
188 /// the specified option on the command line. If there is a value specified
189 /// (after an equal sign) return that as well. This assumes that leading dashes
190 /// have already been stripped.
191 static Option *LookupNearestOption(StringRef Arg,
192 const StringMap<Option*> &OptionsMap,
193 std::string &NearestString) {
194 // Reject all dashes.
195 if (Arg.empty()) return 0;
197 // Split on any equal sign.
198 std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
199 StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
200 StringRef &RHS = SplitArg.second;
202 // Find the closest match.
204 unsigned BestDistance = 0;
205 for (StringMap<Option*>::const_iterator it = OptionsMap.begin(),
206 ie = OptionsMap.end(); it != ie; ++it) {
207 Option *O = it->second;
208 SmallVector<const char*, 16> OptionNames;
209 O->getExtraOptionNames(OptionNames);
211 OptionNames.push_back(O->ArgStr);
213 bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
214 StringRef Flag = PermitValue ? LHS : Arg;
215 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
216 StringRef Name = OptionNames[i];
217 unsigned Distance = StringRef(Name).edit_distance(
218 Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
219 if (!Best || Distance < BestDistance) {
221 BestDistance = Distance;
222 if (RHS.empty() || !PermitValue)
223 NearestString = OptionNames[i];
225 NearestString = std::string(OptionNames[i]) + "=" + RHS.str();
233 /// CommaSeparateAndAddOccurence - A wrapper around Handler->addOccurence() that
234 /// does special handling of cl::CommaSeparated options.
235 static bool CommaSeparateAndAddOccurence(Option *Handler, unsigned pos,
237 StringRef Value, bool MultiArg = false)
239 // Check to see if this option accepts a comma separated list of values. If
240 // it does, we have to split up the value into multiple values.
241 if (Handler->getMiscFlags() & CommaSeparated) {
242 StringRef Val(Value);
243 StringRef::size_type Pos = Val.find(',');
245 while (Pos != StringRef::npos) {
246 // Process the portion before the comma.
247 if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
249 // Erase the portion before the comma, AND the comma.
250 Val = Val.substr(Pos+1);
251 Value.substr(Pos+1); // Increment the original value pointer as well.
252 // Check for another comma.
259 if (Handler->addOccurrence(pos, ArgName, Value, MultiArg))
265 /// ProvideOption - For Value, this differentiates between an empty value ("")
266 /// and a null value (StringRef()). The later is accepted for arguments that
267 /// don't allow a value (-foo) the former is rejected (-foo=).
268 static inline bool ProvideOption(Option *Handler, StringRef ArgName,
269 StringRef Value, int argc,
270 const char *const *argv, int &i) {
271 // Is this a multi-argument option?
272 unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
274 // Enforce value requirements
275 switch (Handler->getValueExpectedFlag()) {
277 if (Value.data() == 0) { // No value specified?
279 return Handler->error("requires a value!");
280 // Steal the next argument, like for '-o filename'
284 case ValueDisallowed:
285 if (NumAdditionalVals > 0)
286 return Handler->error("multi-valued option specified"
287 " with ValueDisallowed modifier!");
290 return Handler->error("does not allow a value! '" +
291 Twine(Value) + "' specified.");
297 // If this isn't a multi-arg option, just run the handler.
298 if (NumAdditionalVals == 0)
299 return CommaSeparateAndAddOccurence(Handler, i, ArgName, Value);
301 // If it is, run the handle several times.
302 bool MultiArg = false;
305 if (CommaSeparateAndAddOccurence(Handler, i, ArgName, Value, MultiArg))
311 while (NumAdditionalVals > 0) {
313 return Handler->error("not enough values!");
316 if (CommaSeparateAndAddOccurence(Handler, i, ArgName, Value, MultiArg))
324 static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
326 return ProvideOption(Handler, Handler->ArgStr, Arg, 0, 0, Dummy);
330 // Option predicates...
331 static inline bool isGrouping(const Option *O) {
332 return O->getFormattingFlag() == cl::Grouping;
334 static inline bool isPrefixedOrGrouping(const Option *O) {
335 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
338 // getOptionPred - Check to see if there are any options that satisfy the
339 // specified predicate with names that are the prefixes in Name. This is
340 // checked by progressively stripping characters off of the name, checking to
341 // see if there options that satisfy the predicate. If we find one, return it,
342 // otherwise return null.
344 static Option *getOptionPred(StringRef Name, size_t &Length,
345 bool (*Pred)(const Option*),
346 const StringMap<Option*> &OptionsMap) {
348 StringMap<Option*>::const_iterator OMI = OptionsMap.find(Name);
350 // Loop while we haven't found an option and Name still has at least two
351 // characters in it (so that the next iteration will not be the empty
353 while (OMI == OptionsMap.end() && Name.size() > 1) {
354 Name = Name.substr(0, Name.size()-1); // Chop off the last character.
355 OMI = OptionsMap.find(Name);
358 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
359 Length = Name.size();
360 return OMI->second; // Found one!
362 return 0; // No option found!
365 /// HandlePrefixedOrGroupedOption - The specified argument string (which started
366 /// with at least one '-') does not fully match an available option. Check to
367 /// see if this is a prefix or grouped option. If so, split arg into output an
368 /// Arg/Value pair and return the Option to parse it with.
369 static Option *HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
371 const StringMap<Option*> &OptionsMap) {
372 if (Arg.size() == 1) return 0;
376 Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
377 if (PGOpt == 0) return 0;
379 // If the option is a prefixed option, then the value is simply the
380 // rest of the name... so fall through to later processing, by
381 // setting up the argument name flags and value fields.
382 if (PGOpt->getFormattingFlag() == cl::Prefix) {
383 Value = Arg.substr(Length);
384 Arg = Arg.substr(0, Length);
385 assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
389 // This must be a grouped option... handle them now. Grouping options can't
391 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
394 // Move current arg name out of Arg into OneArgName.
395 StringRef OneArgName = Arg.substr(0, Length);
396 Arg = Arg.substr(Length);
398 // Because ValueRequired is an invalid flag for grouped arguments,
399 // we don't need to pass argc/argv in.
400 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
401 "Option can not be cl::Grouping AND cl::ValueRequired!");
403 ErrorParsing |= ProvideOption(PGOpt, OneArgName,
404 StringRef(), 0, 0, Dummy);
406 // Get the next grouping option.
407 PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
408 } while (PGOpt && Length != Arg.size());
410 // Return the last option with Arg cut down to just the last one.
416 static bool RequiresValue(const Option *O) {
417 return O->getNumOccurrencesFlag() == cl::Required ||
418 O->getNumOccurrencesFlag() == cl::OneOrMore;
421 static bool EatsUnboundedNumberOfValues(const Option *O) {
422 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
423 O->getNumOccurrencesFlag() == cl::OneOrMore;
426 /// ParseCStringVector - Break INPUT up wherever one or more
427 /// whitespace characters are found, and store the resulting tokens in
428 /// OUTPUT. The tokens stored in OUTPUT are dynamically allocated
429 /// using strdup(), so it is the caller's responsibility to free()
432 static void ParseCStringVector(std::vector<char *> &OutputVector,
434 // Characters which will be treated as token separators:
435 StringRef Delims = " \v\f\t\r\n";
437 StringRef WorkStr(Input);
438 while (!WorkStr.empty()) {
439 // If the first character is a delimiter, strip them off.
440 if (Delims.find(WorkStr[0]) != StringRef::npos) {
441 size_t Pos = WorkStr.find_first_not_of(Delims);
442 if (Pos == StringRef::npos) Pos = WorkStr.size();
443 WorkStr = WorkStr.substr(Pos);
447 // Find position of first delimiter.
448 size_t Pos = WorkStr.find_first_of(Delims);
449 if (Pos == StringRef::npos) Pos = WorkStr.size();
451 // Everything from 0 to Pos is the next word to copy.
452 char *NewStr = (char*)malloc(Pos+1);
453 memcpy(NewStr, WorkStr.data(), Pos);
455 OutputVector.push_back(NewStr);
457 WorkStr = WorkStr.substr(Pos);
461 /// ParseEnvironmentOptions - An alternative entry point to the
462 /// CommandLine library, which allows you to read the program's name
463 /// from the caller (as PROGNAME) and its command-line arguments from
464 /// an environment variable (whose name is given in ENVVAR).
466 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
467 const char *Overview) {
469 assert(progName && "Program name not specified");
470 assert(envVar && "Environment variable name missing");
472 // Get the environment variable they want us to parse options out of.
473 const char *envValue = getenv(envVar);
477 // Get program's "name", which we wouldn't know without the caller
479 std::vector<char*> newArgv;
480 newArgv.push_back(strdup(progName));
482 // Parse the value of the environment variable into a "command line"
483 // and hand it off to ParseCommandLineOptions().
484 ParseCStringVector(newArgv, envValue);
485 int newArgc = static_cast<int>(newArgv.size());
486 ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
488 // Free all the strdup()ed strings.
489 for (std::vector<char*>::iterator i = newArgv.begin(), e = newArgv.end();
495 /// ExpandResponseFiles - Copy the contents of argv into newArgv,
496 /// substituting the contents of the response files for the arguments
498 static void ExpandResponseFiles(unsigned argc, const char*const* argv,
499 std::vector<char*>& newArgv) {
500 for (unsigned i = 1; i != argc; ++i) {
501 const char *arg = argv[i];
504 sys::PathWithStatus respFile(++arg);
506 // Check that the response file is not empty (mmap'ing empty
507 // files can be problematic).
508 const sys::FileStatus *FileStat = respFile.getFileStatus();
509 if (FileStat && FileStat->getSize() != 0) {
511 // If we could open the file, parse its contents, otherwise
512 // pass the @file option verbatim.
514 // TODO: we should also support recursive loading of response files,
515 // since this is how gcc behaves. (From their man page: "The file may
516 // itself contain additional @file options; any such options will be
517 // processed recursively.")
519 // Mmap the response file into memory.
520 OwningPtr<MemoryBuffer> respFilePtr;
521 if (!MemoryBuffer::getFile(respFile.c_str(), respFilePtr)) {
522 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 // Print out the option for the alias.
905 void alias::printOptionInfo(size_t GlobalWidth) const {
906 size_t L = std::strlen(ArgStr);
907 outs() << " -" << ArgStr;
908 outs().indent(GlobalWidth-L-6) << " - " << HelpStr << "\n";
911 //===----------------------------------------------------------------------===//
912 // Parser Implementation code...
915 // basic_parser implementation
918 // Return the width of the option tag for printing...
919 size_t basic_parser_impl::getOptionWidth(const Option &O) const {
920 size_t Len = std::strlen(O.ArgStr);
921 if (const char *ValName = getValueName())
922 Len += std::strlen(getValueStr(O, ValName))+3;
927 // printOptionInfo - Print out information about this option. The
928 // to-be-maintained width is specified.
930 void basic_parser_impl::printOptionInfo(const Option &O,
931 size_t GlobalWidth) const {
932 outs() << " -" << O.ArgStr;
934 if (const char *ValName = getValueName())
935 outs() << "=<" << getValueStr(O, ValName) << '>';
937 outs().indent(GlobalWidth-getOptionWidth(O)) << " - " << O.HelpStr << '\n';
940 void basic_parser_impl::printOptionName(const Option &O,
941 size_t GlobalWidth) const {
942 outs() << " -" << O.ArgStr;
943 outs().indent(GlobalWidth-std::strlen(O.ArgStr));
947 // parser<bool> implementation
949 bool parser<bool>::parse(Option &O, StringRef ArgName,
950 StringRef Arg, bool &Value) {
951 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
957 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
961 return O.error("'" + Arg +
962 "' is invalid value for boolean argument! Try 0 or 1");
965 // parser<boolOrDefault> implementation
967 bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName,
968 StringRef Arg, boolOrDefault &Value) {
969 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
974 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
979 return O.error("'" + Arg +
980 "' is invalid value for boolean argument! Try 0 or 1");
983 // parser<int> implementation
985 bool parser<int>::parse(Option &O, StringRef ArgName,
986 StringRef Arg, int &Value) {
987 if (Arg.getAsInteger(0, Value))
988 return O.error("'" + Arg + "' value invalid for integer argument!");
992 // parser<unsigned> implementation
994 bool parser<unsigned>::parse(Option &O, StringRef ArgName,
995 StringRef Arg, unsigned &Value) {
997 if (Arg.getAsInteger(0, Value))
998 return O.error("'" + Arg + "' value invalid for uint argument!");
1002 // parser<unsigned long long> implementation
1004 bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
1005 StringRef Arg, unsigned long long &Value){
1007 if (Arg.getAsInteger(0, Value))
1008 return O.error("'" + Arg + "' value invalid for uint argument!");
1012 // parser<double>/parser<float> implementation
1014 static bool parseDouble(Option &O, StringRef Arg, double &Value) {
1015 SmallString<32> TmpStr(Arg.begin(), Arg.end());
1016 const char *ArgStart = TmpStr.c_str();
1018 Value = strtod(ArgStart, &End);
1020 return O.error("'" + Arg + "' value invalid for floating point argument!");
1024 bool parser<double>::parse(Option &O, StringRef ArgName,
1025 StringRef Arg, double &Val) {
1026 return parseDouble(O, Arg, Val);
1029 bool parser<float>::parse(Option &O, StringRef ArgName,
1030 StringRef Arg, float &Val) {
1032 if (parseDouble(O, Arg, dVal))
1040 // generic_parser_base implementation
1043 // findOption - Return the option number corresponding to the specified
1044 // argument string. If the option is not found, getNumOptions() is returned.
1046 unsigned generic_parser_base::findOption(const char *Name) {
1047 unsigned e = getNumOptions();
1049 for (unsigned i = 0; i != e; ++i) {
1050 if (strcmp(getOption(i), Name) == 0)
1057 // Return the width of the option tag for printing...
1058 size_t generic_parser_base::getOptionWidth(const Option &O) const {
1059 if (O.hasArgStr()) {
1060 size_t Size = std::strlen(O.ArgStr)+6;
1061 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1062 Size = std::max(Size, std::strlen(getOption(i))+8);
1065 size_t BaseSize = 0;
1066 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1067 BaseSize = std::max(BaseSize, std::strlen(getOption(i))+8);
1072 // printOptionInfo - Print out information about this option. The
1073 // to-be-maintained width is specified.
1075 void generic_parser_base::printOptionInfo(const Option &O,
1076 size_t GlobalWidth) const {
1077 if (O.hasArgStr()) {
1078 size_t L = std::strlen(O.ArgStr);
1079 outs() << " -" << O.ArgStr;
1080 outs().indent(GlobalWidth-L-6) << " - " << O.HelpStr << '\n';
1082 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1083 size_t NumSpaces = GlobalWidth-strlen(getOption(i))-8;
1084 outs() << " =" << getOption(i);
1085 outs().indent(NumSpaces) << " - " << getDescription(i) << '\n';
1089 outs() << " " << O.HelpStr << '\n';
1090 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1091 size_t L = std::strlen(getOption(i));
1092 outs() << " -" << getOption(i);
1093 outs().indent(GlobalWidth-L-8) << " - " << getDescription(i) << '\n';
1098 static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1100 // printGenericOptionDiff - Print the value of this option and it's default.
1102 // "Generic" options have each value mapped to a name.
1103 void generic_parser_base::
1104 printGenericOptionDiff(const Option &O, const GenericOptionValue &Value,
1105 const GenericOptionValue &Default,
1106 size_t GlobalWidth) const {
1107 outs() << " -" << O.ArgStr;
1108 outs().indent(GlobalWidth-std::strlen(O.ArgStr));
1110 unsigned NumOpts = getNumOptions();
1111 for (unsigned i = 0; i != NumOpts; ++i) {
1112 if (Value.compare(getOptionValue(i)))
1115 outs() << "= " << getOption(i);
1116 size_t L = std::strlen(getOption(i));
1117 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1118 outs().indent(NumSpaces) << " (default: ";
1119 for (unsigned j = 0; j != NumOpts; ++j) {
1120 if (Default.compare(getOptionValue(j)))
1122 outs() << getOption(j);
1128 outs() << "= *unknown option value*\n";
1131 // printOptionDiff - Specializations for printing basic value types.
1133 #define PRINT_OPT_DIFF(T) \
1135 printOptionDiff(const Option &O, T V, OptionValue<T> D, \
1136 size_t GlobalWidth) const { \
1137 printOptionName(O, GlobalWidth); \
1140 raw_string_ostream SS(Str); \
1143 outs() << "= " << Str; \
1144 size_t NumSpaces = MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0;\
1145 outs().indent(NumSpaces) << " (default: "; \
1147 outs() << D.getValue(); \
1149 outs() << "*no default*"; \
1153 PRINT_OPT_DIFF(bool)
1154 PRINT_OPT_DIFF(boolOrDefault)
1156 PRINT_OPT_DIFF(unsigned)
1157 PRINT_OPT_DIFF(unsigned long long)
1158 PRINT_OPT_DIFF(double)
1159 PRINT_OPT_DIFF(float)
1160 PRINT_OPT_DIFF(char)
1162 void parser<std::string>::
1163 printOptionDiff(const Option &O, StringRef V, OptionValue<std::string> D,
1164 size_t GlobalWidth) const {
1165 printOptionName(O, GlobalWidth);
1166 outs() << "= " << V;
1167 size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
1168 outs().indent(NumSpaces) << " (default: ";
1170 outs() << D.getValue();
1172 outs() << "*no default*";
1176 // Print a placeholder for options that don't yet support printOptionDiff().
1177 void basic_parser_impl::
1178 printOptionNoValue(const Option &O, size_t GlobalWidth) const {
1179 printOptionName(O, GlobalWidth);
1180 outs() << "= *cannot print option value*\n";
1183 //===----------------------------------------------------------------------===//
1184 // -help and -help-hidden option implementation
1187 static int OptNameCompare(const void *LHS, const void *RHS) {
1188 typedef std::pair<const char *, Option*> pair_ty;
1190 return strcmp(((const pair_ty*)LHS)->first, ((const pair_ty*)RHS)->first);
1193 // Copy Options into a vector so we can sort them as we like.
1195 sortOpts(StringMap<Option*> &OptMap,
1196 SmallVectorImpl< std::pair<const char *, Option*> > &Opts,
1198 SmallPtrSet<Option*, 128> OptionSet; // Duplicate option detection.
1200 for (StringMap<Option*>::iterator I = OptMap.begin(), E = OptMap.end();
1202 // Ignore really-hidden options.
1203 if (I->second->getOptionHiddenFlag() == ReallyHidden)
1206 // Unless showhidden is set, ignore hidden flags.
1207 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
1210 // If we've already seen this option, don't add it to the list again.
1211 if (!OptionSet.insert(I->second))
1214 Opts.push_back(std::pair<const char *, Option*>(I->getKey().data(),
1218 // Sort the options list alphabetically.
1219 qsort(Opts.data(), Opts.size(), sizeof(Opts[0]), OptNameCompare);
1226 const Option *EmptyArg;
1227 const bool ShowHidden;
1230 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {
1234 void operator=(bool Value) {
1235 if (Value == false) return;
1237 // Get all the options.
1238 SmallVector<Option*, 4> PositionalOpts;
1239 SmallVector<Option*, 4> SinkOpts;
1240 StringMap<Option*> OptMap;
1241 GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
1243 SmallVector<std::pair<const char *, Option*>, 128> Opts;
1244 sortOpts(OptMap, Opts, ShowHidden);
1246 if (ProgramOverview)
1247 outs() << "OVERVIEW: " << ProgramOverview << "\n";
1249 outs() << "USAGE: " << ProgramName << " [options]";
1251 // Print out the positional options.
1252 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists...
1253 if (!PositionalOpts.empty() &&
1254 PositionalOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
1255 CAOpt = PositionalOpts[0];
1257 for (size_t i = CAOpt != 0, e = PositionalOpts.size(); i != e; ++i) {
1258 if (PositionalOpts[i]->ArgStr[0])
1259 outs() << " --" << PositionalOpts[i]->ArgStr;
1260 outs() << " " << PositionalOpts[i]->HelpStr;
1263 // Print the consume after option info if it exists...
1264 if (CAOpt) outs() << " " << CAOpt->HelpStr;
1268 // Compute the maximum argument length...
1270 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1271 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1273 outs() << "OPTIONS:\n";
1274 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1275 Opts[i].second->printOptionInfo(MaxArgLen);
1277 // Print any extra help the user has declared.
1278 for (std::vector<const char *>::iterator I = MoreHelp->begin(),
1279 E = MoreHelp->end(); I != E; ++I)
1283 // Halt the program since help information was printed
1287 } // End anonymous namespace
1289 // Define the two HelpPrinter instances that are used to print out help, or
1292 static HelpPrinter NormalPrinter(false);
1293 static HelpPrinter HiddenPrinter(true);
1295 static cl::opt<HelpPrinter, true, parser<bool> >
1296 HOp("help", cl::desc("Display available options (-help-hidden for more)"),
1297 cl::location(NormalPrinter), cl::ValueDisallowed);
1299 static cl::opt<HelpPrinter, true, parser<bool> >
1300 HHOp("help-hidden", cl::desc("Display all available options"),
1301 cl::location(HiddenPrinter), cl::Hidden, cl::ValueDisallowed);
1303 static cl::opt<bool>
1304 PrintOptions("print-options",
1305 cl::desc("Print non-default options after command line parsing"),
1306 cl::Hidden, cl::init(false));
1308 static cl::opt<bool>
1309 PrintAllOptions("print-all-options",
1310 cl::desc("Print all option values after command line parsing"),
1311 cl::Hidden, cl::init(false));
1313 // Print the value of each option.
1314 void cl::PrintOptionValues() {
1315 if (!PrintOptions && !PrintAllOptions) return;
1317 // Get all the options.
1318 SmallVector<Option*, 4> PositionalOpts;
1319 SmallVector<Option*, 4> SinkOpts;
1320 StringMap<Option*> OptMap;
1321 GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
1323 SmallVector<std::pair<const char *, Option*>, 128> Opts;
1324 sortOpts(OptMap, Opts, /*ShowHidden*/true);
1326 // Compute the maximum argument length...
1327 size_t MaxArgLen = 0;
1328 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1329 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1331 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1332 Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
1335 static void (*OverrideVersionPrinter)() = 0;
1337 static std::vector<void (*)()>* ExtraVersionPrinters = 0;
1340 class VersionPrinter {
1343 raw_ostream &OS = outs();
1344 OS << "LLVM (http://llvm.org/):\n"
1345 << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
1346 #ifdef LLVM_VERSION_INFO
1347 OS << LLVM_VERSION_INFO;
1350 #ifndef __OPTIMIZE__
1351 OS << "DEBUG build";
1353 OS << "Optimized build";
1356 OS << " with assertions";
1358 std::string CPU = sys::getHostCPUName();
1359 if (CPU == "generic") CPU = "(unknown)";
1361 #if (ENABLE_TIMESTAMPS == 1)
1362 << " Built " << __DATE__ << " (" << __TIME__ << ").\n"
1364 << " Default target: " << sys::getDefaultTargetTriple() << '\n'
1365 << " Host CPU: " << CPU << '\n';
1367 void operator=(bool OptionWasSpecified) {
1368 if (!OptionWasSpecified) return;
1370 if (OverrideVersionPrinter != 0) {
1371 (*OverrideVersionPrinter)();
1376 // Iterate over any registered extra printers and call them to add further
1378 if (ExtraVersionPrinters != 0) {
1380 for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(),
1381 E = ExtraVersionPrinters->end();
1389 } // End anonymous namespace
1392 // Define the --version option that prints out the LLVM version for the tool
1393 static VersionPrinter VersionPrinterInstance;
1395 static cl::opt<VersionPrinter, true, parser<bool> >
1396 VersOp("version", cl::desc("Display the version of this program"),
1397 cl::location(VersionPrinterInstance), cl::ValueDisallowed);
1399 // Utility function for printing the help message.
1400 void cl::PrintHelpMessage() {
1401 // This looks weird, but it actually prints the help message. The
1402 // NormalPrinter variable is a HelpPrinter and the help gets printed when
1403 // its operator= is invoked. That's because the "normal" usages of the
1404 // help printer is to be assigned true/false depending on whether the
1405 // -help option was given or not. Since we're circumventing that we have
1406 // to make it look like -help was given, so we assign true.
1407 NormalPrinter = true;
1410 /// Utility function for printing version number.
1411 void cl::PrintVersionMessage() {
1412 VersionPrinterInstance.print();
1415 void cl::SetVersionPrinter(void (*func)()) {
1416 OverrideVersionPrinter = func;
1419 void cl::AddExtraVersionPrinter(void (*func)()) {
1420 if (ExtraVersionPrinters == 0)
1421 ExtraVersionPrinters = new std::vector<void (*)()>;
1423 ExtraVersionPrinters->push_back(func);