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/Support/Debug.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/Support/MemoryBuffer.h"
23 #include "llvm/Support/ManagedStatic.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include "llvm/Target/TargetRegistry.h"
26 #include "llvm/System/Host.h"
27 #include "llvm/System/Path.h"
28 #include "llvm/ADT/OwningPtr.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/SmallString.h"
31 #include "llvm/ADT/StringMap.h"
32 #include "llvm/ADT/Twine.h"
33 #include "llvm/Config/config.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<double>);
48 TEMPLATE_INSTANTIATION(class basic_parser<float>);
49 TEMPLATE_INSTANTIATION(class basic_parser<std::string>);
50 TEMPLATE_INSTANTIATION(class basic_parser<char>);
52 TEMPLATE_INSTANTIATION(class opt<unsigned>);
53 TEMPLATE_INSTANTIATION(class opt<int>);
54 TEMPLATE_INSTANTIATION(class opt<std::string>);
55 TEMPLATE_INSTANTIATION(class opt<char>);
56 TEMPLATE_INSTANTIATION(class opt<bool>);
57 } } // end namespace llvm::cl
59 void Option::anchor() {}
60 void basic_parser_impl::anchor() {}
61 void parser<bool>::anchor() {}
62 void parser<boolOrDefault>::anchor() {}
63 void parser<int>::anchor() {}
64 void parser<unsigned>::anchor() {}
65 void parser<double>::anchor() {}
66 void parser<float>::anchor() {}
67 void parser<std::string>::anchor() {}
68 void parser<char>::anchor() {}
70 //===----------------------------------------------------------------------===//
72 // Globals for name and overview of program. Program name is not a string to
73 // avoid static ctor/dtor issues.
74 static char ProgramName[80] = "<premain>";
75 static const char *ProgramOverview = 0;
77 // This collects additional help to be printed.
78 static ManagedStatic<std::vector<const char*> > MoreHelp;
80 extrahelp::extrahelp(const char *Help)
82 MoreHelp->push_back(Help);
85 static bool OptionListChanged = false;
87 // MarkOptionsChanged - Internal helper function.
88 void cl::MarkOptionsChanged() {
89 OptionListChanged = true;
92 /// RegisteredOptionList - This is the list of the command line options that
93 /// have statically constructed themselves.
94 static Option *RegisteredOptionList = 0;
96 void Option::addArgument() {
97 assert(NextRegistered == 0 && "argument multiply registered!");
99 NextRegistered = RegisteredOptionList;
100 RegisteredOptionList = this;
101 MarkOptionsChanged();
105 //===----------------------------------------------------------------------===//
106 // Basic, shared command line option processing machinery.
109 /// GetOptionInfo - Scan the list of registered options, turning them into data
110 /// structures that are easier to handle.
111 static void GetOptionInfo(SmallVectorImpl<Option*> &PositionalOpts,
112 SmallVectorImpl<Option*> &SinkOpts,
113 StringMap<Option*> &OptionsMap) {
114 SmallVector<const char*, 16> OptionNames;
115 Option *CAOpt = 0; // The ConsumeAfter option if it exists.
116 for (Option *O = RegisteredOptionList; O; O = O->getNextRegisteredOption()) {
117 // If this option wants to handle multiple option names, get the full set.
118 // This handles enum options like "-O1 -O2" etc.
119 O->getExtraOptionNames(OptionNames);
121 OptionNames.push_back(O->ArgStr);
123 // Handle named options.
124 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
125 // Add argument to the argument map!
126 if (OptionsMap.GetOrCreateValue(OptionNames[i], O).second != O) {
127 errs() << ProgramName << ": CommandLine Error: Argument '"
128 << OptionNames[i] << "' defined more than once!\n";
134 // Remember information about positional options.
135 if (O->getFormattingFlag() == cl::Positional)
136 PositionalOpts.push_back(O);
137 else if (O->getMiscFlags() & cl::Sink) // Remember sink options
138 SinkOpts.push_back(O);
139 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
141 O->error("Cannot specify more than one option with cl::ConsumeAfter!");
147 PositionalOpts.push_back(CAOpt);
149 // Make sure that they are in order of registration not backwards.
150 std::reverse(PositionalOpts.begin(), PositionalOpts.end());
154 /// LookupOption - Lookup the option specified by the specified option on the
155 /// command line. If there is a value specified (after an equal sign) return
156 /// that as well. This assumes that leading dashes have already been stripped.
157 static Option *LookupOption(StringRef &Arg, StringRef &Value,
158 const StringMap<Option*> &OptionsMap) {
159 // Reject all dashes.
160 if (Arg.empty()) return 0;
162 size_t EqualPos = Arg.find('=');
164 // If we have an equals sign, remember the value.
165 if (EqualPos == StringRef::npos) {
166 // Look up the option.
167 StringMap<Option*>::const_iterator I = OptionsMap.find(Arg);
168 return I != OptionsMap.end() ? I->second : 0;
171 // If the argument before the = is a valid option name, we match. If not,
172 // return Arg unmolested.
173 StringMap<Option*>::const_iterator I =
174 OptionsMap.find(Arg.substr(0, EqualPos));
175 if (I == OptionsMap.end()) return 0;
177 Value = Arg.substr(EqualPos+1);
178 Arg = Arg.substr(0, EqualPos);
182 /// CommaSeparateAndAddOccurence - A wrapper around Handler->addOccurence() that
183 /// does special handling of cl::CommaSeparated options.
184 static bool CommaSeparateAndAddOccurence(Option *Handler, unsigned pos,
186 StringRef Value, bool MultiArg = false)
188 // Check to see if this option accepts a comma separated list of values. If
189 // it does, we have to split up the value into multiple values.
190 if (Handler->getMiscFlags() & CommaSeparated) {
191 StringRef Val(Value);
192 StringRef::size_type Pos = Val.find(',');
194 while (Pos != StringRef::npos) {
195 // Process the portion before the comma.
196 if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
198 // Erase the portion before the comma, AND the comma.
199 Val = Val.substr(Pos+1);
200 Value.substr(Pos+1); // Increment the original value pointer as well.
201 // Check for another comma.
208 if (Handler->addOccurrence(pos, ArgName, Value, MultiArg))
214 /// ProvideOption - For Value, this differentiates between an empty value ("")
215 /// and a null value (StringRef()). The later is accepted for arguments that
216 /// don't allow a value (-foo) the former is rejected (-foo=).
217 static inline bool ProvideOption(Option *Handler, StringRef ArgName,
218 StringRef Value, int argc, char **argv,
220 // Is this a multi-argument option?
221 unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
223 // Enforce value requirements
224 switch (Handler->getValueExpectedFlag()) {
226 if (Value.data() == 0) { // No value specified?
228 return Handler->error("requires a value!");
229 // Steal the next argument, like for '-o filename'
233 case ValueDisallowed:
234 if (NumAdditionalVals > 0)
235 return Handler->error("multi-valued option specified"
236 " with ValueDisallowed modifier!");
239 return Handler->error("does not allow a value! '" +
240 Twine(Value) + "' specified.");
246 errs() << ProgramName
247 << ": Bad ValueMask flag! CommandLine usage error:"
248 << Handler->getValueExpectedFlag() << "\n";
252 // If this isn't a multi-arg option, just run the handler.
253 if (NumAdditionalVals == 0)
254 return CommaSeparateAndAddOccurence(Handler, i, ArgName, Value);
256 // If it is, run the handle several times.
257 bool MultiArg = false;
260 if (CommaSeparateAndAddOccurence(Handler, i, ArgName, Value, MultiArg))
266 while (NumAdditionalVals > 0) {
268 return Handler->error("not enough values!");
271 if (CommaSeparateAndAddOccurence(Handler, i, ArgName, Value, MultiArg))
279 static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
281 return ProvideOption(Handler, Handler->ArgStr, Arg, 0, 0, Dummy);
285 // Option predicates...
286 static inline bool isGrouping(const Option *O) {
287 return O->getFormattingFlag() == cl::Grouping;
289 static inline bool isPrefixedOrGrouping(const Option *O) {
290 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
293 // getOptionPred - Check to see if there are any options that satisfy the
294 // specified predicate with names that are the prefixes in Name. This is
295 // checked by progressively stripping characters off of the name, checking to
296 // see if there options that satisfy the predicate. If we find one, return it,
297 // otherwise return null.
299 static Option *getOptionPred(StringRef Name, size_t &Length,
300 bool (*Pred)(const Option*),
301 const StringMap<Option*> &OptionsMap) {
303 StringMap<Option*>::const_iterator OMI = OptionsMap.find(Name);
305 // Loop while we haven't found an option and Name still has at least two
306 // characters in it (so that the next iteration will not be the empty
308 while (OMI == OptionsMap.end() && Name.size() > 1) {
309 Name = Name.substr(0, Name.size()-1); // Chop off the last character.
310 OMI = OptionsMap.find(Name);
313 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
314 Length = Name.size();
315 return OMI->second; // Found one!
317 return 0; // No option found!
320 /// HandlePrefixedOrGroupedOption - The specified argument string (which started
321 /// with at least one '-') does not fully match an available option. Check to
322 /// see if this is a prefix or grouped option. If so, split arg into output an
323 /// Arg/Value pair and return the Option to parse it with.
324 static Option *HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
326 const StringMap<Option*> &OptionsMap) {
327 if (Arg.size() == 1) return 0;
331 Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
332 if (PGOpt == 0) return 0;
334 // If the option is a prefixed option, then the value is simply the
335 // rest of the name... so fall through to later processing, by
336 // setting up the argument name flags and value fields.
337 if (PGOpt->getFormattingFlag() == cl::Prefix) {
338 Value = Arg.substr(Length);
339 Arg = Arg.substr(0, Length);
340 assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
344 // This must be a grouped option... handle them now. Grouping options can't
346 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
349 // Move current arg name out of Arg into OneArgName.
350 StringRef OneArgName = Arg.substr(0, Length);
351 Arg = Arg.substr(Length);
353 // Because ValueRequired is an invalid flag for grouped arguments,
354 // we don't need to pass argc/argv in.
355 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
356 "Option can not be cl::Grouping AND cl::ValueRequired!");
358 ErrorParsing |= ProvideOption(PGOpt, OneArgName,
359 StringRef(), 0, 0, Dummy);
361 // Get the next grouping option.
362 PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
363 } while (PGOpt && Length != Arg.size());
365 // Return the last option with Arg cut down to just the last one.
371 static bool RequiresValue(const Option *O) {
372 return O->getNumOccurrencesFlag() == cl::Required ||
373 O->getNumOccurrencesFlag() == cl::OneOrMore;
376 static bool EatsUnboundedNumberOfValues(const Option *O) {
377 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
378 O->getNumOccurrencesFlag() == cl::OneOrMore;
381 /// ParseCStringVector - Break INPUT up wherever one or more
382 /// whitespace characters are found, and store the resulting tokens in
383 /// OUTPUT. The tokens stored in OUTPUT are dynamically allocated
384 /// using strdup(), so it is the caller's responsibility to free()
387 static void ParseCStringVector(std::vector<char *> &OutputVector,
389 // Characters which will be treated as token separators:
390 StringRef Delims = " \v\f\t\r\n";
392 StringRef WorkStr(Input);
393 while (!WorkStr.empty()) {
394 // If the first character is a delimiter, strip them off.
395 if (Delims.find(WorkStr[0]) != StringRef::npos) {
396 size_t Pos = WorkStr.find_first_not_of(Delims);
397 if (Pos == StringRef::npos) Pos = WorkStr.size();
398 WorkStr = WorkStr.substr(Pos);
402 // Find position of first delimiter.
403 size_t Pos = WorkStr.find_first_of(Delims);
404 if (Pos == StringRef::npos) Pos = WorkStr.size();
406 // Everything from 0 to Pos is the next word to copy.
407 char *NewStr = (char*)malloc(Pos+1);
408 memcpy(NewStr, WorkStr.data(), Pos);
410 OutputVector.push_back(NewStr);
412 WorkStr = WorkStr.substr(Pos);
416 /// ParseEnvironmentOptions - An alternative entry point to the
417 /// CommandLine library, which allows you to read the program's name
418 /// from the caller (as PROGNAME) and its command-line arguments from
419 /// an environment variable (whose name is given in ENVVAR).
421 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
422 const char *Overview, bool ReadResponseFiles) {
424 assert(progName && "Program name not specified");
425 assert(envVar && "Environment variable name missing");
427 // Get the environment variable they want us to parse options out of.
428 const char *envValue = getenv(envVar);
432 // Get program's "name", which we wouldn't know without the caller
434 std::vector<char*> newArgv;
435 newArgv.push_back(strdup(progName));
437 // Parse the value of the environment variable into a "command line"
438 // and hand it off to ParseCommandLineOptions().
439 ParseCStringVector(newArgv, envValue);
440 int newArgc = static_cast<int>(newArgv.size());
441 ParseCommandLineOptions(newArgc, &newArgv[0], Overview, ReadResponseFiles);
443 // Free all the strdup()ed strings.
444 for (std::vector<char*>::iterator i = newArgv.begin(), e = newArgv.end();
450 /// ExpandResponseFiles - Copy the contents of argv into newArgv,
451 /// substituting the contents of the response files for the arguments
453 static void ExpandResponseFiles(unsigned argc, char** argv,
454 std::vector<char*>& newArgv) {
455 for (unsigned i = 1; i != argc; ++i) {
459 sys::PathWithStatus respFile(++arg);
461 // Check that the response file is not empty (mmap'ing empty
462 // files can be problematic).
463 const sys::FileStatus *FileStat = respFile.getFileStatus();
464 if (FileStat && FileStat->getSize() != 0) {
466 // Mmap the response file into memory.
467 OwningPtr<MemoryBuffer>
468 respFilePtr(MemoryBuffer::getFile(respFile.c_str()));
470 // If we could open the file, parse its contents, otherwise
471 // pass the @file option verbatim.
473 // TODO: we should also support recursive loading of response files,
474 // since this is how gcc behaves. (From their man page: "The file may
475 // itself contain additional @file options; any such options will be
476 // processed recursively.")
478 if (respFilePtr != 0) {
479 ParseCStringVector(newArgv, respFilePtr->getBufferStart());
484 newArgv.push_back(strdup(arg));
488 void cl::ParseCommandLineOptions(int argc, char **argv,
489 const char *Overview, bool ReadResponseFiles) {
490 // Process all registered options.
491 SmallVector<Option*, 4> PositionalOpts;
492 SmallVector<Option*, 4> SinkOpts;
493 StringMap<Option*> Opts;
494 GetOptionInfo(PositionalOpts, SinkOpts, Opts);
496 assert((!Opts.empty() || !PositionalOpts.empty()) &&
497 "No options specified!");
499 // Expand response files.
500 std::vector<char*> newArgv;
501 if (ReadResponseFiles) {
502 newArgv.push_back(strdup(argv[0]));
503 ExpandResponseFiles(argc, argv, newArgv);
505 argc = static_cast<int>(newArgv.size());
508 // Copy the program name into ProgName, making sure not to overflow it.
509 std::string ProgName = sys::Path(argv[0]).getLast();
510 if (ProgName.size() > 79) ProgName.resize(79);
511 strcpy(ProgramName, ProgName.c_str());
513 ProgramOverview = Overview;
514 bool ErrorParsing = false;
516 // Check out the positional arguments to collect information about them.
517 unsigned NumPositionalRequired = 0;
519 // Determine whether or not there are an unlimited number of positionals
520 bool HasUnlimitedPositionals = false;
522 Option *ConsumeAfterOpt = 0;
523 if (!PositionalOpts.empty()) {
524 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
525 assert(PositionalOpts.size() > 1 &&
526 "Cannot specify cl::ConsumeAfter without a positional argument!");
527 ConsumeAfterOpt = PositionalOpts[0];
530 // Calculate how many positional values are _required_.
531 bool UnboundedFound = false;
532 for (size_t i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
534 Option *Opt = PositionalOpts[i];
535 if (RequiresValue(Opt))
536 ++NumPositionalRequired;
537 else if (ConsumeAfterOpt) {
538 // ConsumeAfter cannot be combined with "optional" positional options
539 // unless there is only one positional argument...
540 if (PositionalOpts.size() > 2)
542 Opt->error("error - this positional option will never be matched, "
543 "because it does not Require a value, and a "
544 "cl::ConsumeAfter option is active!");
545 } else if (UnboundedFound && !Opt->ArgStr[0]) {
546 // This option does not "require" a value... Make sure this option is
547 // not specified after an option that eats all extra arguments, or this
548 // one will never get any!
550 ErrorParsing |= Opt->error("error - option can never match, because "
551 "another positional argument will match an "
552 "unbounded number of values, and this option"
553 " does not require a value!");
555 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
557 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
560 // PositionalVals - A vector of "positional" arguments we accumulate into
561 // the process at the end.
563 SmallVector<std::pair<StringRef,unsigned>, 4> PositionalVals;
565 // If the program has named positional arguments, and the name has been run
566 // across, keep track of which positional argument was named. Otherwise put
567 // the positional args into the PositionalVals list...
568 Option *ActivePositionalArg = 0;
570 // Loop over all of the arguments... processing them.
571 bool DashDashFound = false; // Have we read '--'?
572 for (int i = 1; i < argc; ++i) {
575 StringRef ArgName = "";
577 // If the option list changed, this means that some command line
578 // option has just been registered or deregistered. This can occur in
579 // response to things like -load, etc. If this happens, rescan the options.
580 if (OptionListChanged) {
581 PositionalOpts.clear();
584 GetOptionInfo(PositionalOpts, SinkOpts, Opts);
585 OptionListChanged = false;
588 // Check to see if this is a positional argument. This argument is
589 // considered to be positional if it doesn't start with '-', if it is "-"
590 // itself, or if we have seen "--" already.
592 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
593 // Positional argument!
594 if (ActivePositionalArg) {
595 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
596 continue; // We are done!
599 if (!PositionalOpts.empty()) {
600 PositionalVals.push_back(std::make_pair(argv[i],i));
602 // All of the positional arguments have been fulfulled, give the rest to
603 // the consume after option... if it's specified...
605 if (PositionalVals.size() >= NumPositionalRequired &&
606 ConsumeAfterOpt != 0) {
607 for (++i; i < argc; ++i)
608 PositionalVals.push_back(std::make_pair(argv[i],i));
609 break; // Handle outside of the argument processing loop...
612 // Delay processing positional arguments until the end...
615 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
617 DashDashFound = true; // This is the mythical "--"?
618 continue; // Don't try to process it as an argument itself.
619 } else if (ActivePositionalArg &&
620 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
621 // If there is a positional argument eating options, check to see if this
622 // option is another positional argument. If so, treat it as an argument,
623 // otherwise feed it to the eating positional.
625 // Eat leading dashes.
626 while (!ArgName.empty() && ArgName[0] == '-')
627 ArgName = ArgName.substr(1);
629 Handler = LookupOption(ArgName, Value, Opts);
630 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
631 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
632 continue; // We are done!
635 } else { // We start with a '-', must be an argument.
637 // Eat leading dashes.
638 while (!ArgName.empty() && ArgName[0] == '-')
639 ArgName = ArgName.substr(1);
641 Handler = LookupOption(ArgName, Value, Opts);
643 // Check to see if this "option" is really a prefixed or grouped argument.
645 Handler = HandlePrefixedOrGroupedOption(ArgName, Value,
650 if (SinkOpts.empty()) {
651 errs() << ProgramName << ": Unknown command line argument '"
652 << argv[i] << "'. Try: '" << argv[0] << " --help'\n";
655 for (SmallVectorImpl<Option*>::iterator I = SinkOpts.begin(),
656 E = SinkOpts.end(); I != E ; ++I)
657 (*I)->addOccurrence(i, "", argv[i]);
662 // If this is a named positional argument, just remember that it is the
664 if (Handler->getFormattingFlag() == cl::Positional)
665 ActivePositionalArg = Handler;
667 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
670 // Check and handle positional arguments now...
671 if (NumPositionalRequired > PositionalVals.size()) {
672 errs() << ProgramName
673 << ": Not enough positional command line arguments specified!\n"
674 << "Must specify at least " << NumPositionalRequired
675 << " positional arguments: See: " << argv[0] << " --help\n";
678 } else if (!HasUnlimitedPositionals
679 && PositionalVals.size() > PositionalOpts.size()) {
680 errs() << ProgramName
681 << ": Too many positional arguments specified!\n"
682 << "Can specify at most " << PositionalOpts.size()
683 << " positional arguments: See: " << argv[0] << " --help\n";
686 } else if (ConsumeAfterOpt == 0) {
687 // Positional args have already been handled if ConsumeAfter is specified.
688 unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
689 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
690 if (RequiresValue(PositionalOpts[i])) {
691 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
692 PositionalVals[ValNo].second);
694 --NumPositionalRequired; // We fulfilled our duty...
697 // If we _can_ give this option more arguments, do so now, as long as we
698 // do not give it values that others need. 'Done' controls whether the
699 // option even _WANTS_ any more.
701 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
702 while (NumVals-ValNo > NumPositionalRequired && !Done) {
703 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
705 Done = true; // Optional arguments want _at most_ one value
707 case cl::ZeroOrMore: // Zero or more will take all they can get...
708 case cl::OneOrMore: // One or more will take all they can get...
709 ProvidePositionalOption(PositionalOpts[i],
710 PositionalVals[ValNo].first,
711 PositionalVals[ValNo].second);
715 llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
716 "positional argument processing!");
721 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
723 for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
724 if (RequiresValue(PositionalOpts[j])) {
725 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
726 PositionalVals[ValNo].first,
727 PositionalVals[ValNo].second);
731 // Handle the case where there is just one positional option, and it's
732 // optional. In this case, we want to give JUST THE FIRST option to the
733 // positional option and keep the rest for the consume after. The above
734 // loop would have assigned no values to positional options in this case.
736 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
737 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
738 PositionalVals[ValNo].first,
739 PositionalVals[ValNo].second);
743 // Handle over all of the rest of the arguments to the
744 // cl::ConsumeAfter command line option...
745 for (; ValNo != PositionalVals.size(); ++ValNo)
746 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
747 PositionalVals[ValNo].first,
748 PositionalVals[ValNo].second);
751 // Loop over args and make sure all required args are specified!
752 for (StringMap<Option*>::iterator I = Opts.begin(),
753 E = Opts.end(); I != E; ++I) {
754 switch (I->second->getNumOccurrencesFlag()) {
757 if (I->second->getNumOccurrences() == 0) {
758 I->second->error("must be specified at least once!");
767 // Free all of the memory allocated to the map. Command line options may only
768 // be processed once!
770 PositionalOpts.clear();
773 // Free the memory allocated by ExpandResponseFiles.
774 if (ReadResponseFiles) {
775 // Free all the strdup()ed strings.
776 for (std::vector<char*>::iterator i = newArgv.begin(), e = newArgv.end();
781 DEBUG(dbgs() << "Args: ";
782 for (int i = 0; i < argc; ++i)
783 dbgs() << argv[i] << ' ';
787 // If we had an error processing our arguments, don't let the program execute
788 if (ErrorParsing) exit(1);
791 //===----------------------------------------------------------------------===//
792 // Option Base class implementation
795 bool Option::error(const Twine &Message, StringRef ArgName) {
796 if (ArgName.data() == 0) ArgName = ArgStr;
798 errs() << HelpStr; // Be nice for positional arguments
800 errs() << ProgramName << ": for the -" << ArgName;
802 errs() << " option: " << Message << "\n";
806 bool Option::addOccurrence(unsigned pos, StringRef ArgName,
807 StringRef Value, bool MultiArg) {
809 NumOccurrences++; // Increment the number of times we have been seen
811 switch (getNumOccurrencesFlag()) {
813 if (NumOccurrences > 1)
814 return error("may only occur zero or one times!", ArgName);
817 if (NumOccurrences > 1)
818 return error("must occur exactly one time!", ArgName);
822 case ConsumeAfter: break;
823 default: return error("bad num occurrences flag value!");
826 return handleOccurrence(pos, ArgName, Value);
830 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
831 // has been specified yet.
833 static const char *getValueStr(const Option &O, const char *DefaultMsg) {
834 if (O.ValueStr[0] == 0) return DefaultMsg;
838 //===----------------------------------------------------------------------===//
839 // cl::alias class implementation
842 // Return the width of the option tag for printing...
843 size_t alias::getOptionWidth() const {
844 return std::strlen(ArgStr)+6;
847 // Print out the option for the alias.
848 void alias::printOptionInfo(size_t GlobalWidth) const {
849 size_t L = std::strlen(ArgStr);
850 errs() << " -" << ArgStr;
851 errs().indent(GlobalWidth-L-6) << " - " << HelpStr << "\n";
856 //===----------------------------------------------------------------------===//
857 // Parser Implementation code...
860 // basic_parser implementation
863 // Return the width of the option tag for printing...
864 size_t basic_parser_impl::getOptionWidth(const Option &O) const {
865 size_t Len = std::strlen(O.ArgStr);
866 if (const char *ValName = getValueName())
867 Len += std::strlen(getValueStr(O, ValName))+3;
872 // printOptionInfo - Print out information about this option. The
873 // to-be-maintained width is specified.
875 void basic_parser_impl::printOptionInfo(const Option &O,
876 size_t GlobalWidth) const {
877 outs() << " -" << O.ArgStr;
879 if (const char *ValName = getValueName())
880 outs() << "=<" << getValueStr(O, ValName) << '>';
882 outs().indent(GlobalWidth-getOptionWidth(O)) << " - " << O.HelpStr << '\n';
888 // parser<bool> implementation
890 bool parser<bool>::parse(Option &O, StringRef ArgName,
891 StringRef Arg, bool &Value) {
892 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
898 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
902 return O.error("'" + Arg +
903 "' is invalid value for boolean argument! Try 0 or 1");
906 // parser<boolOrDefault> implementation
908 bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName,
909 StringRef Arg, boolOrDefault &Value) {
910 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
915 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
920 return O.error("'" + Arg +
921 "' is invalid value for boolean argument! Try 0 or 1");
924 // parser<int> implementation
926 bool parser<int>::parse(Option &O, StringRef ArgName,
927 StringRef Arg, int &Value) {
928 if (Arg.getAsInteger(0, Value))
929 return O.error("'" + Arg + "' value invalid for integer argument!");
933 // parser<unsigned> implementation
935 bool parser<unsigned>::parse(Option &O, StringRef ArgName,
936 StringRef Arg, unsigned &Value) {
938 if (Arg.getAsInteger(0, Value))
939 return O.error("'" + Arg + "' value invalid for uint argument!");
943 // parser<double>/parser<float> implementation
945 static bool parseDouble(Option &O, StringRef Arg, double &Value) {
946 SmallString<32> TmpStr(Arg.begin(), Arg.end());
947 const char *ArgStart = TmpStr.c_str();
949 Value = strtod(ArgStart, &End);
951 return O.error("'" + Arg + "' value invalid for floating point argument!");
955 bool parser<double>::parse(Option &O, StringRef ArgName,
956 StringRef Arg, double &Val) {
957 return parseDouble(O, Arg, Val);
960 bool parser<float>::parse(Option &O, StringRef ArgName,
961 StringRef Arg, float &Val) {
963 if (parseDouble(O, Arg, dVal))
971 // generic_parser_base implementation
974 // findOption - Return the option number corresponding to the specified
975 // argument string. If the option is not found, getNumOptions() is returned.
977 unsigned generic_parser_base::findOption(const char *Name) {
978 unsigned e = getNumOptions();
980 for (unsigned i = 0; i != e; ++i) {
981 if (strcmp(getOption(i), Name) == 0)
988 // Return the width of the option tag for printing...
989 size_t generic_parser_base::getOptionWidth(const Option &O) const {
991 size_t Size = std::strlen(O.ArgStr)+6;
992 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
993 Size = std::max(Size, std::strlen(getOption(i))+8);
997 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
998 BaseSize = std::max(BaseSize, std::strlen(getOption(i))+8);
1003 // printOptionInfo - Print out information about this option. The
1004 // to-be-maintained width is specified.
1006 void generic_parser_base::printOptionInfo(const Option &O,
1007 size_t GlobalWidth) const {
1008 if (O.hasArgStr()) {
1009 size_t L = std::strlen(O.ArgStr);
1010 outs() << " -" << O.ArgStr;
1011 outs().indent(GlobalWidth-L-6) << " - " << O.HelpStr << '\n';
1013 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1014 size_t NumSpaces = GlobalWidth-strlen(getOption(i))-8;
1015 outs() << " =" << getOption(i);
1016 outs().indent(NumSpaces) << " - " << getDescription(i) << '\n';
1020 outs() << " " << O.HelpStr << '\n';
1021 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1022 size_t L = std::strlen(getOption(i));
1023 outs() << " -" << getOption(i);
1024 outs().indent(GlobalWidth-L-8) << " - " << getDescription(i) << '\n';
1030 //===----------------------------------------------------------------------===//
1031 // --help and --help-hidden option implementation
1034 static int OptNameCompare(const void *LHS, const void *RHS) {
1035 typedef std::pair<const char *, Option*> pair_ty;
1037 return strcmp(((pair_ty*)LHS)->first, ((pair_ty*)RHS)->first);
1044 const Option *EmptyArg;
1045 const bool ShowHidden;
1048 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {
1052 void operator=(bool Value) {
1053 if (Value == false) return;
1055 // Get all the options.
1056 SmallVector<Option*, 4> PositionalOpts;
1057 SmallVector<Option*, 4> SinkOpts;
1058 StringMap<Option*> OptMap;
1059 GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
1061 // Copy Options into a vector so we can sort them as we like.
1062 SmallVector<std::pair<const char *, Option*>, 128> Opts;
1063 SmallPtrSet<Option*, 128> OptionSet; // Duplicate option detection.
1065 for (StringMap<Option*>::iterator I = OptMap.begin(), E = OptMap.end();
1067 // Ignore really-hidden options.
1068 if (I->second->getOptionHiddenFlag() == ReallyHidden)
1071 // Unless showhidden is set, ignore hidden flags.
1072 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
1075 // If we've already seen this option, don't add it to the list again.
1076 if (!OptionSet.insert(I->second))
1079 Opts.push_back(std::pair<const char *, Option*>(I->getKey().data(),
1083 // Sort the options list alphabetically.
1084 qsort(Opts.data(), Opts.size(), sizeof(Opts[0]), OptNameCompare);
1086 if (ProgramOverview)
1087 outs() << "OVERVIEW: " << ProgramOverview << "\n";
1089 outs() << "USAGE: " << ProgramName << " [options]";
1091 // Print out the positional options.
1092 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists...
1093 if (!PositionalOpts.empty() &&
1094 PositionalOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
1095 CAOpt = PositionalOpts[0];
1097 for (size_t i = CAOpt != 0, e = PositionalOpts.size(); i != e; ++i) {
1098 if (PositionalOpts[i]->ArgStr[0])
1099 outs() << " --" << PositionalOpts[i]->ArgStr;
1100 outs() << " " << PositionalOpts[i]->HelpStr;
1103 // Print the consume after option info if it exists...
1104 if (CAOpt) outs() << " " << CAOpt->HelpStr;
1108 // Compute the maximum argument length...
1110 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1111 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1113 outs() << "OPTIONS:\n";
1114 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1115 Opts[i].second->printOptionInfo(MaxArgLen);
1117 // Print any extra help the user has declared.
1118 for (std::vector<const char *>::iterator I = MoreHelp->begin(),
1119 E = MoreHelp->end(); I != E; ++I)
1123 // Halt the program since help information was printed
1127 } // End anonymous namespace
1129 // Define the two HelpPrinter instances that are used to print out help, or
1132 static HelpPrinter NormalPrinter(false);
1133 static HelpPrinter HiddenPrinter(true);
1135 static cl::opt<HelpPrinter, true, parser<bool> >
1136 HOp("help", cl::desc("Display available options (--help-hidden for more)"),
1137 cl::location(NormalPrinter), cl::ValueDisallowed);
1139 static cl::opt<HelpPrinter, true, parser<bool> >
1140 HHOp("help-hidden", cl::desc("Display all available options"),
1141 cl::location(HiddenPrinter), cl::Hidden, cl::ValueDisallowed);
1143 static void (*OverrideVersionPrinter)() = 0;
1145 static int TargetArraySortFn(const void *LHS, const void *RHS) {
1146 typedef std::pair<const char *, const Target*> pair_ty;
1147 return strcmp(((const pair_ty*)LHS)->first, ((const pair_ty*)RHS)->first);
1151 class VersionPrinter {
1154 raw_ostream &OS = outs();
1155 OS << "Low Level Virtual Machine (http://llvm.org/):\n"
1156 << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
1157 #ifdef LLVM_VERSION_INFO
1158 OS << LLVM_VERSION_INFO;
1161 #ifndef __OPTIMIZE__
1162 OS << "DEBUG build";
1164 OS << "Optimized build";
1167 OS << " with assertions";
1169 std::string CPU = sys::getHostCPUName();
1170 if (CPU == "generic") CPU = "(unknown)";
1172 << " Built " << __DATE__ << " (" << __TIME__ << ").\n"
1173 << " Host: " << sys::getHostTriple() << '\n'
1174 << " Host CPU: " << CPU << '\n'
1176 << " Registered Targets:\n";
1178 std::vector<std::pair<const char *, const Target*> > Targets;
1180 for (TargetRegistry::iterator it = TargetRegistry::begin(),
1181 ie = TargetRegistry::end(); it != ie; ++it) {
1182 Targets.push_back(std::make_pair(it->getName(), &*it));
1183 Width = std::max(Width, strlen(Targets.back().first));
1185 if (!Targets.empty())
1186 qsort(&Targets[0], Targets.size(), sizeof(Targets[0]),
1189 for (unsigned i = 0, e = Targets.size(); i != e; ++i) {
1190 OS << " " << Targets[i].first;
1191 OS.indent(Width - strlen(Targets[i].first)) << " - "
1192 << Targets[i].second->getShortDescription() << '\n';
1194 if (Targets.empty())
1197 void operator=(bool OptionWasSpecified) {
1198 if (!OptionWasSpecified) return;
1200 if (OverrideVersionPrinter == 0) {
1204 (*OverrideVersionPrinter)();
1208 } // End anonymous namespace
1211 // Define the --version option that prints out the LLVM version for the tool
1212 static VersionPrinter VersionPrinterInstance;
1214 static cl::opt<VersionPrinter, true, parser<bool> >
1215 VersOp("version", cl::desc("Display the version of this program"),
1216 cl::location(VersionPrinterInstance), cl::ValueDisallowed);
1218 // Utility function for printing the help message.
1219 void cl::PrintHelpMessage() {
1220 // This looks weird, but it actually prints the help message. The
1221 // NormalPrinter variable is a HelpPrinter and the help gets printed when
1222 // its operator= is invoked. That's because the "normal" usages of the
1223 // help printer is to be assigned true/false depending on whether the
1224 // --help option was given or not. Since we're circumventing that we have
1225 // to make it look like --help was given, so we assign true.
1226 NormalPrinter = true;
1229 /// Utility function for printing version number.
1230 void cl::PrintVersionMessage() {
1231 VersionPrinterInstance.print();
1234 void cl::SetVersionPrinter(void (*func)()) {
1235 OverrideVersionPrinter = func;