1 //===- llvm/Support/CommandLine.h - Command line handler --------*- C++ -*-===//
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 should
15 // read the library documentation located in docs/CommandLine.html or looks at
16 // the many example usages in tools/*/*.cpp
18 //===----------------------------------------------------------------------===//
20 #ifndef LLVM_SUPPORT_COMMANDLINE_H
21 #define LLVM_SUPPORT_COMMANDLINE_H
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/StringMap.h"
25 #include "llvm/ADT/Twine.h"
26 #include "llvm/Support/Compiler.h"
35 /// cl Namespace - This namespace contains all of the command line option
36 /// processing machinery. It is intentionally a short name to make qualified
40 //===----------------------------------------------------------------------===//
41 // ParseCommandLineOptions - Command line option processing entry point.
43 void ParseCommandLineOptions(int argc, const char *const *argv,
44 const char *Overview = nullptr);
46 //===----------------------------------------------------------------------===//
47 // ParseEnvironmentOptions - Environment variable option processing alternate
50 void ParseEnvironmentOptions(const char *progName, const char *envvar,
51 const char *Overview = nullptr);
53 ///===---------------------------------------------------------------------===//
54 /// SetVersionPrinter - Override the default (LLVM specific) version printer
55 /// used to print out the version when --version is given
56 /// on the command line. This allows other systems using the
57 /// CommandLine utilities to print their own version string.
58 void SetVersionPrinter(void (*func)());
60 ///===---------------------------------------------------------------------===//
61 /// AddExtraVersionPrinter - Add an extra printer to use in addition to the
62 /// default one. This can be called multiple times,
63 /// and each time it adds a new function to the list
64 /// which will be called after the basic LLVM version
65 /// printing is complete. Each can then add additional
66 /// information specific to the tool.
67 void AddExtraVersionPrinter(void (*func)());
69 // PrintOptionValues - Print option values.
70 // With -print-options print the difference between option values and defaults.
71 // With -print-all-options print all option values.
72 // (Currently not perfect, but best-effort.)
73 void PrintOptionValues();
75 // MarkOptionsChanged - Internal helper function.
76 void MarkOptionsChanged();
78 //===----------------------------------------------------------------------===//
79 // Flags permitted to be passed to command line arguments
82 enum NumOccurrencesFlag { // Flags for the number of occurrences allowed
83 Optional = 0x00, // Zero or One occurrence
84 ZeroOrMore = 0x01, // Zero or more occurrences allowed
85 Required = 0x02, // One occurrence required
86 OneOrMore = 0x03, // One or more occurrences required
88 // ConsumeAfter - Indicates that this option is fed anything that follows the
89 // last positional argument required by the application (it is an error if
90 // there are zero positional arguments, and a ConsumeAfter option is used).
91 // Thus, for example, all arguments to LLI are processed until a filename is
92 // found. Once a filename is found, all of the succeeding arguments are
93 // passed, unprocessed, to the ConsumeAfter option.
98 enum ValueExpected { // Is a value required for the option?
99 // zero reserved for the unspecified value
100 ValueOptional = 0x01, // The value can appear... or not
101 ValueRequired = 0x02, // The value is required to appear!
102 ValueDisallowed = 0x03 // A value may not be specified (for flags)
105 enum OptionHidden { // Control whether -help shows this option
106 NotHidden = 0x00, // Option included in -help & -help-hidden
107 Hidden = 0x01, // -help doesn't, but -help-hidden does
108 ReallyHidden = 0x02 // Neither -help nor -help-hidden show this arg
111 // Formatting flags - This controls special features that the option might have
112 // that cause it to be parsed differently...
114 // Prefix - This option allows arguments that are otherwise unrecognized to be
115 // matched by options that are a prefix of the actual value. This is useful for
116 // cases like a linker, where options are typically of the form '-lfoo' or
117 // '-L../../include' where -l or -L are the actual flags. When prefix is
118 // enabled, and used, the value for the flag comes from the suffix of the
121 // Grouping - With this option enabled, multiple letter options are allowed to
122 // bunch together with only a single hyphen for the whole group. This allows
123 // emulation of the behavior that ls uses for example: ls -la === ls -l -a
126 enum FormattingFlags {
127 NormalFormatting = 0x00, // Nothing special
128 Positional = 0x01, // Is a positional argument, no '-' required
129 Prefix = 0x02, // Can this option directly prefix its value?
130 Grouping = 0x03 // Can this option group with other options?
133 enum MiscFlags { // Miscellaneous flags to adjust argument
134 CommaSeparated = 0x01, // Should this cl::list split between commas?
135 PositionalEatsArgs = 0x02, // Should this positional cl::list eat -args?
136 Sink = 0x04 // Should this cl::list eat all unknown options?
139 //===----------------------------------------------------------------------===//
140 // Option Category class
142 class OptionCategory {
144 const char *const Name;
145 const char *const Description;
146 void registerCategory();
149 OptionCategory(const char *const Name,
150 const char *const Description = nullptr)
151 : Name(Name), Description(Description) {
154 const char *getName() const { return Name; }
155 const char *getDescription() const { return Description; }
158 // The general Option Category (used as default category).
159 extern OptionCategory GeneralCategory;
161 //===----------------------------------------------------------------------===//
168 // handleOccurrences - Overriden by subclasses to handle the value passed into
169 // an argument. Should return true if there was an error processing the
170 // argument and the program should exit.
172 virtual bool handleOccurrence(unsigned pos, StringRef ArgName,
175 virtual enum ValueExpected getValueExpectedFlagDefault() const {
176 return ValueOptional;
179 // Out of line virtual function to provide home for the class.
180 virtual void anchor();
182 int NumOccurrences; // The number of times specified
183 // Occurrences, HiddenFlag, and Formatting are all enum types but to avoid
184 // problems with signed enums in bitfields.
185 unsigned Occurrences : 3; // enum NumOccurrencesFlag
186 // not using the enum type for 'Value' because zero is an implementation
187 // detail representing the non-value
189 unsigned HiddenFlag : 2; // enum OptionHidden
190 unsigned Formatting : 2; // enum FormattingFlags
192 unsigned Position; // Position of last occurrence of the option
193 unsigned AdditionalVals; // Greater than 0 for multi-valued option.
194 Option *NextRegistered; // Singly linked list of registered options.
197 const char *ArgStr; // The argument string itself (ex: "help", "o")
198 const char *HelpStr; // The descriptive text message for -help
199 const char *ValueStr; // String describing what the value of this option is
200 OptionCategory *Category; // The Category this option belongs to
202 inline enum NumOccurrencesFlag getNumOccurrencesFlag() const {
203 return (enum NumOccurrencesFlag)Occurrences;
205 inline enum ValueExpected getValueExpectedFlag() const {
206 return Value ? ((enum ValueExpected)Value) : getValueExpectedFlagDefault();
208 inline enum OptionHidden getOptionHiddenFlag() const {
209 return (enum OptionHidden)HiddenFlag;
211 inline enum FormattingFlags getFormattingFlag() const {
212 return (enum FormattingFlags)Formatting;
214 inline unsigned getMiscFlags() const { return Misc; }
215 inline unsigned getPosition() const { return Position; }
216 inline unsigned getNumAdditionalVals() const { return AdditionalVals; }
218 // hasArgStr - Return true if the argstr != ""
219 bool hasArgStr() const { return ArgStr[0] != 0; }
221 //-------------------------------------------------------------------------===
222 // Accessor functions set by OptionModifiers
224 void setArgStr(const char *S) { ArgStr = S; }
225 void setDescription(const char *S) { HelpStr = S; }
226 void setValueStr(const char *S) { ValueStr = S; }
227 void setNumOccurrencesFlag(enum NumOccurrencesFlag Val) { Occurrences = Val; }
228 void setValueExpectedFlag(enum ValueExpected Val) { Value = Val; }
229 void setHiddenFlag(enum OptionHidden Val) { HiddenFlag = Val; }
230 void setFormattingFlag(enum FormattingFlags V) { Formatting = V; }
231 void setMiscFlag(enum MiscFlags M) { Misc |= M; }
232 void setPosition(unsigned pos) { Position = pos; }
233 void setCategory(OptionCategory &C) { Category = &C; }
236 explicit Option(enum NumOccurrencesFlag OccurrencesFlag,
237 enum OptionHidden Hidden)
238 : NumOccurrences(0), Occurrences(OccurrencesFlag), Value(0),
239 HiddenFlag(Hidden), Formatting(NormalFormatting), Misc(0), Position(0),
240 AdditionalVals(0), NextRegistered(nullptr), ArgStr(""), HelpStr(""),
241 ValueStr(""), Category(&GeneralCategory) {}
243 inline void setNumAdditionalVals(unsigned n) { AdditionalVals = n; }
246 // addArgument - Register this argument with the commandline system.
250 /// Unregisters this option from the CommandLine system.
252 /// This option must have been the last option registered.
253 /// For testing purposes only.
254 void removeArgument();
256 Option *getNextRegisteredOption() const { return NextRegistered; }
258 // Return the width of the option tag for printing...
259 virtual size_t getOptionWidth() const = 0;
261 // printOptionInfo - Print out information about this option. The
262 // to-be-maintained width is specified.
264 virtual void printOptionInfo(size_t GlobalWidth) const = 0;
266 virtual void printOptionValue(size_t GlobalWidth, bool Force) const = 0;
268 virtual void getExtraOptionNames(SmallVectorImpl<const char *> &) {}
270 // addOccurrence - Wrapper around handleOccurrence that enforces Flags.
272 virtual bool addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
273 bool MultiArg = false);
275 // Prints option name followed by message. Always returns true.
276 bool error(const Twine &Message, StringRef ArgName = StringRef());
279 inline int getNumOccurrences() const { return NumOccurrences; }
283 //===----------------------------------------------------------------------===//
284 // Command line option modifiers that can be used to modify the behavior of
285 // command line option parsers...
288 // desc - Modifier to set the description shown in the -help output...
291 desc(const char *Str) : Desc(Str) {}
292 void apply(Option &O) const { O.setDescription(Desc); }
295 // value_desc - Modifier to set the value description shown in the -help
299 value_desc(const char *Str) : Desc(Str) {}
300 void apply(Option &O) const { O.setValueStr(Desc); }
303 // init - Specify a default (initial) value for the command line argument, if
304 // the default constructor for the argument type does not give you what you
305 // want. This is only valid on "opt" arguments, not on "list" arguments.
307 template <class Ty> struct initializer {
309 initializer(const Ty &Val) : Init(Val) {}
311 template <class Opt> void apply(Opt &O) const { O.setInitialValue(Init); }
314 template <class Ty> initializer<Ty> init(const Ty &Val) {
315 return initializer<Ty>(Val);
318 // location - Allow the user to specify which external variable they want to
319 // store the results of the command line argument processing into, if they don't
320 // want to store it in the option itself.
322 template <class Ty> struct LocationClass {
324 LocationClass(Ty &L) : Loc(L) {}
326 template <class Opt> void apply(Opt &O) const { O.setLocation(O, Loc); }
329 template <class Ty> LocationClass<Ty> location(Ty &L) {
330 return LocationClass<Ty>(L);
333 // cat - Specifiy the Option category for the command line argument to belong
336 OptionCategory &Category;
337 cat(OptionCategory &c) : Category(c) {}
339 template <class Opt> void apply(Opt &O) const { O.setCategory(Category); }
342 //===----------------------------------------------------------------------===//
345 // Support value comparison outside the template.
346 struct GenericOptionValue {
347 virtual ~GenericOptionValue() {}
348 virtual bool compare(const GenericOptionValue &V) const = 0;
351 virtual void anchor();
354 template <class DataType> struct OptionValue;
356 // The default value safely does nothing. Option value printing is only
358 template <class DataType, bool isClass>
359 struct OptionValueBase : public GenericOptionValue {
360 // Temporary storage for argument passing.
361 typedef OptionValue<DataType> WrapperType;
363 bool hasValue() const { return false; }
365 const DataType &getValue() const { llvm_unreachable("no default value"); }
367 // Some options may take their value from a different data type.
368 template <class DT> void setValue(const DT & /*V*/) {}
370 bool compare(const DataType & /*V*/) const { return false; }
372 bool compare(const GenericOptionValue & /*V*/) const override {
377 // Simple copy of the option value.
378 template <class DataType> class OptionValueCopy : public GenericOptionValue {
383 OptionValueCopy() : Valid(false) {}
385 bool hasValue() const { return Valid; }
387 const DataType &getValue() const {
388 assert(Valid && "invalid option value");
392 void setValue(const DataType &V) {
397 bool compare(const DataType &V) const { return Valid && (Value != V); }
399 bool compare(const GenericOptionValue &V) const override {
400 const OptionValueCopy<DataType> &VC =
401 static_cast<const OptionValueCopy<DataType> &>(V);
404 return compare(VC.getValue());
408 // Non-class option values.
409 template <class DataType>
410 struct OptionValueBase<DataType, false> : OptionValueCopy<DataType> {
411 typedef DataType WrapperType;
414 // Top-level option class.
415 template <class DataType>
416 struct OptionValue : OptionValueBase<DataType, std::is_class<DataType>::value> {
419 OptionValue(const DataType &V) { this->setValue(V); }
420 // Some options may take their value from a different data type.
421 template <class DT> OptionValue<DataType> &operator=(const DT &V) {
427 // Other safe-to-copy-by-value common option types.
428 enum boolOrDefault { BOU_UNSET, BOU_TRUE, BOU_FALSE };
430 struct OptionValue<cl::boolOrDefault> : OptionValueCopy<cl::boolOrDefault> {
431 typedef cl::boolOrDefault WrapperType;
435 OptionValue(const cl::boolOrDefault &V) { this->setValue(V); }
436 OptionValue<cl::boolOrDefault> &operator=(const cl::boolOrDefault &V) {
442 void anchor() override;
445 template <> struct OptionValue<std::string> : OptionValueCopy<std::string> {
446 typedef StringRef WrapperType;
450 OptionValue(const std::string &V) { this->setValue(V); }
451 OptionValue<std::string> &operator=(const std::string &V) {
457 void anchor() override;
460 //===----------------------------------------------------------------------===//
461 // Enum valued command line option
463 #define clEnumVal(ENUMVAL, DESC) #ENUMVAL, int(ENUMVAL), DESC
464 #define clEnumValN(ENUMVAL, FLAGNAME, DESC) FLAGNAME, int(ENUMVAL), DESC
465 #define clEnumValEnd (reinterpret_cast<void *>(0))
467 // values - For custom data types, allow specifying a group of values together
468 // as the values that go into the mapping that the option handler uses. Note
469 // that the values list must always have a 0 at the end of the list to indicate
470 // that the list has ended.
472 template <class DataType> class ValuesClass {
473 // Use a vector instead of a map, because the lists should be short,
474 // the overhead is less, and most importantly, it keeps them in the order
475 // inserted so we can print our option out nicely.
476 SmallVector<std::pair<const char *, std::pair<int, const char *>>, 4> Values;
477 void processValues(va_list Vals);
480 ValuesClass(const char *EnumName, DataType Val, const char *Desc,
482 // Insert the first value, which is required.
483 Values.push_back(std::make_pair(EnumName, std::make_pair(Val, Desc)));
485 // Process the varargs portion of the values...
486 while (const char *enumName = va_arg(ValueArgs, const char *)) {
487 DataType EnumVal = static_cast<DataType>(va_arg(ValueArgs, int));
488 const char *EnumDesc = va_arg(ValueArgs, const char *);
489 Values.push_back(std::make_pair(enumName, // Add value to value map
490 std::make_pair(EnumVal, EnumDesc)));
494 template <class Opt> void apply(Opt &O) const {
495 for (size_t i = 0, e = Values.size(); i != e; ++i)
496 O.getParser().addLiteralOption(Values[i].first, Values[i].second.first,
497 Values[i].second.second);
501 template <class DataType>
502 ValuesClass<DataType> LLVM_END_WITH_NULL
503 values(const char *Arg, DataType Val, const char *Desc, ...) {
505 va_start(ValueArgs, Desc);
506 ValuesClass<DataType> Vals(Arg, Val, Desc, ValueArgs);
511 //===----------------------------------------------------------------------===//
512 // parser class - Parameterizable parser for different data types. By default,
513 // known data types (string, int, bool) have specialized parsers, that do what
514 // you would expect. The default parser, used for data types that are not
515 // built-in, uses a mapping table to map specific options to values, which is
516 // used, among other things, to handle enum types.
518 //--------------------------------------------------
519 // generic_parser_base - This class holds all the non-generic code that we do
520 // not need replicated for every instance of the generic parser. This also
521 // allows us to put stuff into CommandLine.cpp
523 class generic_parser_base {
525 class GenericOptionInfo {
527 GenericOptionInfo(const char *name, const char *helpStr)
528 : Name(name), HelpStr(helpStr) {}
534 generic_parser_base(Option &O) : Owner(O) {}
536 virtual ~generic_parser_base() {} // Base class should have virtual-dtor
538 // getNumOptions - Virtual function implemented by generic subclass to
539 // indicate how many entries are in Values.
541 virtual unsigned getNumOptions() const = 0;
543 // getOption - Return option name N.
544 virtual const char *getOption(unsigned N) const = 0;
546 // getDescription - Return description N
547 virtual const char *getDescription(unsigned N) const = 0;
549 // Return the width of the option tag for printing...
550 virtual size_t getOptionWidth(const Option &O) const;
552 virtual const GenericOptionValue &getOptionValue(unsigned N) const = 0;
554 // printOptionInfo - Print out information about this option. The
555 // to-be-maintained width is specified.
557 virtual void printOptionInfo(const Option &O, size_t GlobalWidth) const;
559 void printGenericOptionDiff(const Option &O, const GenericOptionValue &V,
560 const GenericOptionValue &Default,
561 size_t GlobalWidth) const;
563 // printOptionDiff - print the value of an option and it's default.
565 // Template definition ensures that the option and default have the same
566 // DataType (via the same AnyOptionValue).
567 template <class AnyOptionValue>
568 void printOptionDiff(const Option &O, const AnyOptionValue &V,
569 const AnyOptionValue &Default,
570 size_t GlobalWidth) const {
571 printGenericOptionDiff(O, V, Default, GlobalWidth);
576 void getExtraOptionNames(SmallVectorImpl<const char *> &OptionNames) {
577 // If there has been no argstr specified, that means that we need to add an
578 // argument for every possible option. This ensures that our options are
580 if (!Owner.hasArgStr())
581 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
582 OptionNames.push_back(getOption(i));
585 enum ValueExpected getValueExpectedFlagDefault() const {
586 // If there is an ArgStr specified, then we are of the form:
588 // -opt=O2 or -opt O2 or -optO2
590 // In which case, the value is required. Otherwise if an arg str has not
591 // been specified, we are of the form:
593 // -O2 or O2 or -la (where -l and -a are separate options)
595 // If this is the case, we cannot allow a value.
597 if (Owner.hasArgStr())
598 return ValueRequired;
600 return ValueDisallowed;
603 // findOption - Return the option number corresponding to the specified
604 // argument string. If the option is not found, getNumOptions() is returned.
606 unsigned findOption(const char *Name);
612 // Default parser implementation - This implementation depends on having a
613 // mapping of recognized options to values of some sort. In addition to this,
614 // each entry in the mapping also tracks a help message that is printed with the
615 // command line option for -help. Because this is a simple mapping parser, the
616 // data type can be any unsupported type.
618 template <class DataType> class parser : public generic_parser_base {
620 class OptionInfo : public GenericOptionInfo {
622 OptionInfo(const char *name, DataType v, const char *helpStr)
623 : GenericOptionInfo(name, helpStr), V(v) {}
624 OptionValue<DataType> V;
626 SmallVector<OptionInfo, 8> Values;
629 parser(Option &O) : generic_parser_base(O) {}
630 typedef DataType parser_data_type;
632 // Implement virtual functions needed by generic_parser_base
633 unsigned getNumOptions() const override { return unsigned(Values.size()); }
634 const char *getOption(unsigned N) const override { return Values[N].Name; }
635 const char *getDescription(unsigned N) const override {
636 return Values[N].HelpStr;
639 // getOptionValue - Return the value of option name N.
640 const GenericOptionValue &getOptionValue(unsigned N) const override {
644 // parse - Return true on error.
645 bool parse(Option &O, StringRef ArgName, StringRef Arg, DataType &V) {
647 if (Owner.hasArgStr())
652 for (size_t i = 0, e = Values.size(); i != e; ++i)
653 if (Values[i].Name == ArgVal) {
654 V = Values[i].V.getValue();
658 return O.error("Cannot find option named '" + ArgVal + "'!");
661 /// addLiteralOption - Add an entry to the mapping table.
664 void addLiteralOption(const char *Name, const DT &V, const char *HelpStr) {
665 assert(findOption(Name) == Values.size() && "Option already exists!");
666 OptionInfo X(Name, static_cast<DataType>(V), HelpStr);
668 MarkOptionsChanged();
671 /// removeLiteralOption - Remove the specified option.
673 void removeLiteralOption(const char *Name) {
674 unsigned N = findOption(Name);
675 assert(N != Values.size() && "Option not found!");
676 Values.erase(Values.begin() + N);
680 //--------------------------------------------------
681 // basic_parser - Super class of parsers to provide boilerplate code
683 class basic_parser_impl { // non-template implementation of basic_parser<t>
685 basic_parser_impl(Option &O) {}
687 virtual ~basic_parser_impl() {}
689 enum ValueExpected getValueExpectedFlagDefault() const {
690 return ValueRequired;
693 void getExtraOptionNames(SmallVectorImpl<const char *> &) {}
697 // Return the width of the option tag for printing...
698 size_t getOptionWidth(const Option &O) const;
700 // printOptionInfo - Print out information about this option. The
701 // to-be-maintained width is specified.
703 void printOptionInfo(const Option &O, size_t GlobalWidth) const;
705 // printOptionNoValue - Print a placeholder for options that don't yet support
706 // printOptionDiff().
707 void printOptionNoValue(const Option &O, size_t GlobalWidth) const;
709 // getValueName - Overload in subclass to provide a better default value.
710 virtual const char *getValueName() const { return "value"; }
712 // An out-of-line virtual method to provide a 'home' for this class.
713 virtual void anchor();
716 // A helper for basic_parser::printOptionDiff.
717 void printOptionName(const Option &O, size_t GlobalWidth) const;
720 // basic_parser - The real basic parser is just a template wrapper that provides
721 // a typedef for the provided data type.
723 template <class DataType> class basic_parser : public basic_parser_impl {
725 basic_parser(Option &O) : basic_parser_impl(O) {}
726 typedef DataType parser_data_type;
727 typedef OptionValue<DataType> OptVal;
730 //--------------------------------------------------
733 template <> class parser<bool> : public basic_parser<bool> {
735 parser(Option &O) : basic_parser(O) {}
737 // parse - Return true on error.
738 bool parse(Option &O, StringRef ArgName, StringRef Arg, bool &Val);
742 enum ValueExpected getValueExpectedFlagDefault() const {
743 return ValueOptional;
746 // getValueName - Do not print =<value> at all.
747 const char *getValueName() const override { return nullptr; }
749 void printOptionDiff(const Option &O, bool V, OptVal Default,
750 size_t GlobalWidth) const;
752 // An out-of-line virtual method to provide a 'home' for this class.
753 void anchor() override;
756 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<bool>);
758 //--------------------------------------------------
759 // parser<boolOrDefault>
760 template <> class parser<boolOrDefault> : public basic_parser<boolOrDefault> {
762 parser(Option &O) : basic_parser(O) {}
764 // parse - Return true on error.
765 bool parse(Option &O, StringRef ArgName, StringRef Arg, boolOrDefault &Val);
767 enum ValueExpected getValueExpectedFlagDefault() const {
768 return ValueOptional;
771 // getValueName - Do not print =<value> at all.
772 const char *getValueName() const override { return nullptr; }
774 void printOptionDiff(const Option &O, boolOrDefault V, OptVal Default,
775 size_t GlobalWidth) const;
777 // An out-of-line virtual method to provide a 'home' for this class.
778 void anchor() override;
781 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<boolOrDefault>);
783 //--------------------------------------------------
786 template <> class parser<int> : public basic_parser<int> {
788 parser(Option &O) : basic_parser(O) {}
790 // parse - Return true on error.
791 bool parse(Option &O, StringRef ArgName, StringRef Arg, int &Val);
793 // getValueName - Overload in subclass to provide a better default value.
794 const char *getValueName() const override { return "int"; }
796 void printOptionDiff(const Option &O, int V, OptVal Default,
797 size_t GlobalWidth) const;
799 // An out-of-line virtual method to provide a 'home' for this class.
800 void anchor() override;
803 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<int>);
805 //--------------------------------------------------
808 template <> class parser<unsigned> : public basic_parser<unsigned> {
810 parser(Option &O) : basic_parser(O) {}
812 // parse - Return true on error.
813 bool parse(Option &O, StringRef ArgName, StringRef Arg, unsigned &Val);
815 // getValueName - Overload in subclass to provide a better default value.
816 const char *getValueName() const override { return "uint"; }
818 void printOptionDiff(const Option &O, unsigned V, OptVal Default,
819 size_t GlobalWidth) const;
821 // An out-of-line virtual method to provide a 'home' for this class.
822 void anchor() override;
825 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<unsigned>);
827 //--------------------------------------------------
828 // parser<unsigned long long>
831 class parser<unsigned long long> : public basic_parser<unsigned long long> {
833 parser(Option &O) : basic_parser(O) {}
835 // parse - Return true on error.
836 bool parse(Option &O, StringRef ArgName, StringRef Arg,
837 unsigned long long &Val);
839 // getValueName - Overload in subclass to provide a better default value.
840 const char *getValueName() const override { return "uint"; }
842 void printOptionDiff(const Option &O, unsigned long long V, OptVal Default,
843 size_t GlobalWidth) const;
845 // An out-of-line virtual method to provide a 'home' for this class.
846 void anchor() override;
849 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<unsigned long long>);
851 //--------------------------------------------------
854 template <> class parser<double> : public basic_parser<double> {
856 parser(Option &O) : basic_parser(O) {}
858 // parse - Return true on error.
859 bool parse(Option &O, StringRef ArgName, StringRef Arg, double &Val);
861 // getValueName - Overload in subclass to provide a better default value.
862 const char *getValueName() const override { return "number"; }
864 void printOptionDiff(const Option &O, double V, OptVal Default,
865 size_t GlobalWidth) const;
867 // An out-of-line virtual method to provide a 'home' for this class.
868 void anchor() override;
871 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<double>);
873 //--------------------------------------------------
876 template <> class parser<float> : public basic_parser<float> {
878 parser(Option &O) : basic_parser(O) {}
880 // parse - Return true on error.
881 bool parse(Option &O, StringRef ArgName, StringRef Arg, float &Val);
883 // getValueName - Overload in subclass to provide a better default value.
884 const char *getValueName() const override { return "number"; }
886 void printOptionDiff(const Option &O, float V, OptVal Default,
887 size_t GlobalWidth) const;
889 // An out-of-line virtual method to provide a 'home' for this class.
890 void anchor() override;
893 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<float>);
895 //--------------------------------------------------
896 // parser<std::string>
898 template <> class parser<std::string> : public basic_parser<std::string> {
900 parser(Option &O) : basic_parser(O) {}
902 // parse - Return true on error.
903 bool parse(Option &, StringRef, StringRef Arg, std::string &Value) {
908 // getValueName - Overload in subclass to provide a better default value.
909 const char *getValueName() const override { return "string"; }
911 void printOptionDiff(const Option &O, StringRef V, OptVal Default,
912 size_t GlobalWidth) const;
914 // An out-of-line virtual method to provide a 'home' for this class.
915 void anchor() override;
918 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<std::string>);
920 //--------------------------------------------------
923 template <> class parser<char> : public basic_parser<char> {
925 parser(Option &O) : basic_parser(O) {}
927 // parse - Return true on error.
928 bool parse(Option &, StringRef, StringRef Arg, char &Value) {
933 // getValueName - Overload in subclass to provide a better default value.
934 const char *getValueName() const override { return "char"; }
936 void printOptionDiff(const Option &O, char V, OptVal Default,
937 size_t GlobalWidth) const;
939 // An out-of-line virtual method to provide a 'home' for this class.
940 void anchor() override;
943 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<char>);
945 //--------------------------------------------------
948 // This collection of wrappers is the intermediary between class opt and class
949 // parser to handle all the template nastiness.
951 // This overloaded function is selected by the generic parser.
952 template <class ParserClass, class DT>
953 void printOptionDiff(const Option &O, const generic_parser_base &P, const DT &V,
954 const OptionValue<DT> &Default, size_t GlobalWidth) {
955 OptionValue<DT> OV = V;
956 P.printOptionDiff(O, OV, Default, GlobalWidth);
959 // This is instantiated for basic parsers when the parsed value has a different
960 // type than the option value. e.g. HelpPrinter.
961 template <class ParserDT, class ValDT> struct OptionDiffPrinter {
962 void print(const Option &O, const parser<ParserDT> P, const ValDT & /*V*/,
963 const OptionValue<ValDT> & /*Default*/, size_t GlobalWidth) {
964 P.printOptionNoValue(O, GlobalWidth);
968 // This is instantiated for basic parsers when the parsed value has the same
969 // type as the option value.
970 template <class DT> struct OptionDiffPrinter<DT, DT> {
971 void print(const Option &O, const parser<DT> P, const DT &V,
972 const OptionValue<DT> &Default, size_t GlobalWidth) {
973 P.printOptionDiff(O, V, Default, GlobalWidth);
977 // This overloaded function is selected by the basic parser, which may parse a
978 // different type than the option type.
979 template <class ParserClass, class ValDT>
980 void printOptionDiff(
982 const basic_parser<typename ParserClass::parser_data_type> &P,
983 const ValDT &V, const OptionValue<ValDT> &Default, size_t GlobalWidth) {
985 OptionDiffPrinter<typename ParserClass::parser_data_type, ValDT> printer;
986 printer.print(O, static_cast<const ParserClass &>(P), V, Default,
990 //===----------------------------------------------------------------------===//
991 // applicator class - This class is used because we must use partial
992 // specialization to handle literal string arguments specially (const char* does
993 // not correctly respond to the apply method). Because the syntax to use this
994 // is a pain, we have the 'apply' method below to handle the nastiness...
996 template <class Mod> struct applicator {
997 template <class Opt> static void opt(const Mod &M, Opt &O) { M.apply(O); }
1000 // Handle const char* as a special case...
1001 template <unsigned n> struct applicator<char[n]> {
1002 template <class Opt> static void opt(const char *Str, Opt &O) {
1006 template <unsigned n> struct applicator<const char[n]> {
1007 template <class Opt> static void opt(const char *Str, Opt &O) {
1011 template <> struct applicator<const char *> {
1012 template <class Opt> static void opt(const char *Str, Opt &O) {
1017 template <> struct applicator<NumOccurrencesFlag> {
1018 static void opt(NumOccurrencesFlag N, Option &O) {
1019 O.setNumOccurrencesFlag(N);
1022 template <> struct applicator<ValueExpected> {
1023 static void opt(ValueExpected VE, Option &O) { O.setValueExpectedFlag(VE); }
1025 template <> struct applicator<OptionHidden> {
1026 static void opt(OptionHidden OH, Option &O) { O.setHiddenFlag(OH); }
1028 template <> struct applicator<FormattingFlags> {
1029 static void opt(FormattingFlags FF, Option &O) { O.setFormattingFlag(FF); }
1031 template <> struct applicator<MiscFlags> {
1032 static void opt(MiscFlags MF, Option &O) { O.setMiscFlag(MF); }
1035 // apply method - Apply a modifier to an option in a type safe way.
1036 template <class Mod, class Opt> void apply(const Mod &M, Opt *O) {
1037 applicator<Mod>::opt(M, *O);
1040 //===----------------------------------------------------------------------===//
1041 // opt_storage class
1043 // Default storage class definition: external storage. This implementation
1044 // assumes the user will specify a variable to store the data into with the
1045 // cl::location(x) modifier.
1047 template <class DataType, bool ExternalStorage, bool isClass>
1049 DataType *Location; // Where to store the object...
1050 OptionValue<DataType> Default;
1052 void check_location() const {
1053 assert(Location && "cl::location(...) not specified for a command "
1054 "line option with external storage, "
1055 "or cl::init specified before cl::location()!!");
1059 opt_storage() : Location(nullptr) {}
1061 bool setLocation(Option &O, DataType &L) {
1063 return O.error("cl::location(x) specified more than once!");
1069 template <class T> void setValue(const T &V, bool initial = false) {
1076 DataType &getValue() {
1080 const DataType &getValue() const {
1085 operator DataType() const { return this->getValue(); }
1087 const OptionValue<DataType> &getDefault() const { return Default; }
1090 // Define how to hold a class type object, such as a string. Since we can
1091 // inherit from a class, we do so. This makes us exactly compatible with the
1092 // object in all cases that it is used.
1094 template <class DataType>
1095 class opt_storage<DataType, false, true> : public DataType {
1097 OptionValue<DataType> Default;
1099 template <class T> void setValue(const T &V, bool initial = false) {
1100 DataType::operator=(V);
1105 DataType &getValue() { return *this; }
1106 const DataType &getValue() const { return *this; }
1108 const OptionValue<DataType> &getDefault() const { return Default; }
1111 // Define a partial specialization to handle things we cannot inherit from. In
1112 // this case, we store an instance through containment, and overload operators
1113 // to get at the value.
1115 template <class DataType> class opt_storage<DataType, false, false> {
1118 OptionValue<DataType> Default;
1120 // Make sure we initialize the value with the default constructor for the
1122 opt_storage() : Value(DataType()), Default(DataType()) {}
1124 template <class T> void setValue(const T &V, bool initial = false) {
1129 DataType &getValue() { return Value; }
1130 DataType getValue() const { return Value; }
1132 const OptionValue<DataType> &getDefault() const { return Default; }
1134 operator DataType() const { return getValue(); }
1136 // If the datatype is a pointer, support -> on it.
1137 DataType operator->() const { return Value; }
1140 //===----------------------------------------------------------------------===//
1141 // opt - A scalar command line option.
1143 template <class DataType, bool ExternalStorage = false,
1144 class ParserClass = parser<DataType>>
1145 class opt : public Option,
1146 public opt_storage<DataType, ExternalStorage,
1147 std::is_class<DataType>::value> {
1150 bool handleOccurrence(unsigned pos, StringRef ArgName,
1151 StringRef Arg) override {
1152 typename ParserClass::parser_data_type Val =
1153 typename ParserClass::parser_data_type();
1154 if (Parser.parse(*this, ArgName, Arg, Val))
1155 return true; // Parse error!
1156 this->setValue(Val);
1157 this->setPosition(pos);
1161 enum ValueExpected getValueExpectedFlagDefault() const override {
1162 return Parser.getValueExpectedFlagDefault();
1165 getExtraOptionNames(SmallVectorImpl<const char *> &OptionNames) override {
1166 return Parser.getExtraOptionNames(OptionNames);
1169 // Forward printing stuff to the parser...
1170 size_t getOptionWidth() const override {
1171 return Parser.getOptionWidth(*this);
1173 void printOptionInfo(size_t GlobalWidth) const override {
1174 Parser.printOptionInfo(*this, GlobalWidth);
1177 void printOptionValue(size_t GlobalWidth, bool Force) const override {
1178 if (Force || this->getDefault().compare(this->getValue())) {
1179 cl::printOptionDiff<ParserClass>(*this, Parser, this->getValue(),
1180 this->getDefault(), GlobalWidth);
1186 Parser.initialize();
1189 // Command line options should not be copyable
1190 opt(const opt &) LLVM_DELETED_FUNCTION;
1191 opt &operator=(const opt &) LLVM_DELETED_FUNCTION;
1194 // setInitialValue - Used by the cl::init modifier...
1195 void setInitialValue(const DataType &V) { this->setValue(V, true); }
1197 ParserClass &getParser() { return Parser; }
1199 template <class T> DataType &operator=(const T &Val) {
1200 this->setValue(Val);
1201 return this->getValue();
1205 template <class M0t>
1206 explicit opt(const M0t &M0)
1207 : Option(Optional, NotHidden), Parser(*this) {
1213 template <class M0t, class M1t>
1214 opt(const M0t &M0, const M1t &M1)
1215 : Option(Optional, NotHidden), Parser(*this) {
1222 template <class M0t, class M1t, class M2t>
1223 opt(const M0t &M0, const M1t &M1, const M2t &M2)
1224 : Option(Optional, NotHidden), Parser(*this) {
1231 template <class M0t, class M1t, class M2t, class M3t>
1232 opt(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3)
1233 : Option(Optional, NotHidden), Parser(*this) {
1241 template <class M0t, class M1t, class M2t, class M3t, class M4t>
1242 opt(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3, const M4t &M4)
1243 : Option(Optional, NotHidden), Parser(*this) {
1252 template <class M0t, class M1t, class M2t, class M3t, class M4t, class M5t>
1253 opt(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3, const M4t &M4,
1255 : Option(Optional, NotHidden), Parser(*this) {
1265 template <class M0t, class M1t, class M2t, class M3t, class M4t, class M5t,
1267 opt(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3, const M4t &M4,
1268 const M5t &M5, const M6t &M6)
1269 : Option(Optional, NotHidden), Parser(*this) {
1280 template <class M0t, class M1t, class M2t, class M3t, class M4t, class M5t,
1281 class M6t, class M7t>
1282 opt(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3, const M4t &M4,
1283 const M5t &M5, const M6t &M6, const M7t &M7)
1284 : Option(Optional, NotHidden), Parser(*this) {
1297 EXTERN_TEMPLATE_INSTANTIATION(class opt<unsigned>);
1298 EXTERN_TEMPLATE_INSTANTIATION(class opt<int>);
1299 EXTERN_TEMPLATE_INSTANTIATION(class opt<std::string>);
1300 EXTERN_TEMPLATE_INSTANTIATION(class opt<char>);
1301 EXTERN_TEMPLATE_INSTANTIATION(class opt<bool>);
1303 //===----------------------------------------------------------------------===//
1304 // list_storage class
1306 // Default storage class definition: external storage. This implementation
1307 // assumes the user will specify a variable to store the data into with the
1308 // cl::location(x) modifier.
1310 template <class DataType, class StorageClass> class list_storage {
1311 StorageClass *Location; // Where to store the object...
1314 list_storage() : Location(0) {}
1316 bool setLocation(Option &O, StorageClass &L) {
1318 return O.error("cl::location(x) specified more than once!");
1323 template <class T> void addValue(const T &V) {
1324 assert(Location != 0 && "cl::location(...) not specified for a command "
1325 "line option with external storage!");
1326 Location->push_back(V);
1330 // Define how to hold a class type object, such as a string. Since we can
1331 // inherit from a class, we do so. This makes us exactly compatible with the
1332 // object in all cases that it is used.
1334 template <class DataType>
1335 class list_storage<DataType, bool> : public std::vector<DataType> {
1337 template <class T> void addValue(const T &V) {
1338 std::vector<DataType>::push_back(V);
1342 //===----------------------------------------------------------------------===//
1343 // list - A list of command line options.
1345 template <class DataType, class Storage = bool,
1346 class ParserClass = parser<DataType>>
1347 class list : public Option, public list_storage<DataType, Storage> {
1348 std::vector<unsigned> Positions;
1351 enum ValueExpected getValueExpectedFlagDefault() const override {
1352 return Parser.getValueExpectedFlagDefault();
1355 getExtraOptionNames(SmallVectorImpl<const char *> &OptionNames) override {
1356 return Parser.getExtraOptionNames(OptionNames);
1359 bool handleOccurrence(unsigned pos, StringRef ArgName,
1360 StringRef Arg) override {
1361 typename ParserClass::parser_data_type Val =
1362 typename ParserClass::parser_data_type();
1363 if (Parser.parse(*this, ArgName, Arg, Val))
1364 return true; // Parse Error!
1365 list_storage<DataType, Storage>::addValue(Val);
1367 Positions.push_back(pos);
1371 // Forward printing stuff to the parser...
1372 size_t getOptionWidth() const override {
1373 return Parser.getOptionWidth(*this);
1375 void printOptionInfo(size_t GlobalWidth) const override {
1376 Parser.printOptionInfo(*this, GlobalWidth);
1379 // Unimplemented: list options don't currently store their default value.
1380 void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override {
1385 Parser.initialize();
1388 // Command line options should not be copyable
1389 list(const list &) LLVM_DELETED_FUNCTION;
1390 list &operator=(const list &) LLVM_DELETED_FUNCTION;
1393 ParserClass &getParser() { return Parser; }
1395 unsigned getPosition(unsigned optnum) const {
1396 assert(optnum < this->size() && "Invalid option index");
1397 return Positions[optnum];
1400 void setNumAdditionalVals(unsigned n) { Option::setNumAdditionalVals(n); }
1403 template <class M0t>
1404 explicit list(const M0t &M0)
1405 : Option(ZeroOrMore, NotHidden), Parser(*this) {
1410 template <class M0t, class M1t>
1411 list(const M0t &M0, const M1t &M1)
1412 : Option(ZeroOrMore, NotHidden), Parser(*this) {
1418 template <class M0t, class M1t, class M2t>
1419 list(const M0t &M0, const M1t &M1, const M2t &M2)
1420 : Option(ZeroOrMore, NotHidden), Parser(*this) {
1427 template <class M0t, class M1t, class M2t, class M3t>
1428 list(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3)
1429 : Option(ZeroOrMore, NotHidden), Parser(*this) {
1437 template <class M0t, class M1t, class M2t, class M3t, class M4t>
1438 list(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
1440 : Option(ZeroOrMore, NotHidden), Parser(*this) {
1449 template <class M0t, class M1t, class M2t, class M3t, class M4t, class M5t>
1450 list(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
1451 const M4t &M4, const M5t &M5)
1452 : Option(ZeroOrMore, NotHidden), Parser(*this) {
1462 template <class M0t, class M1t, class M2t, class M3t, class M4t, class M5t,
1464 list(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
1465 const M4t &M4, const M5t &M5, const M6t &M6)
1466 : Option(ZeroOrMore, NotHidden), Parser(*this) {
1477 template <class M0t, class M1t, class M2t, class M3t, class M4t, class M5t,
1478 class M6t, class M7t>
1479 list(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
1480 const M4t &M4, const M5t &M5, const M6t &M6, const M7t &M7)
1481 : Option(ZeroOrMore, NotHidden), Parser(*this) {
1494 // multi_val - Modifier to set the number of additional values.
1496 unsigned AdditionalVals;
1497 explicit multi_val(unsigned N) : AdditionalVals(N) {}
1499 template <typename D, typename S, typename P>
1500 void apply(list<D, S, P> &L) const {
1501 L.setNumAdditionalVals(AdditionalVals);
1505 //===----------------------------------------------------------------------===//
1506 // bits_storage class
1508 // Default storage class definition: external storage. This implementation
1509 // assumes the user will specify a variable to store the data into with the
1510 // cl::location(x) modifier.
1512 template <class DataType, class StorageClass> class bits_storage {
1513 unsigned *Location; // Where to store the bits...
1515 template <class T> static unsigned Bit(const T &V) {
1516 unsigned BitPos = reinterpret_cast<unsigned>(V);
1517 assert(BitPos < sizeof(unsigned) * CHAR_BIT &&
1518 "enum exceeds width of bit vector!");
1523 bits_storage() : Location(nullptr) {}
1525 bool setLocation(Option &O, unsigned &L) {
1527 return O.error("cl::location(x) specified more than once!");
1532 template <class T> void addValue(const T &V) {
1533 assert(Location != 0 && "cl::location(...) not specified for a command "
1534 "line option with external storage!");
1535 *Location |= Bit(V);
1538 unsigned getBits() { return *Location; }
1540 template <class T> bool isSet(const T &V) {
1541 return (*Location & Bit(V)) != 0;
1545 // Define how to hold bits. Since we can inherit from a class, we do so.
1546 // This makes us exactly compatible with the bits in all cases that it is used.
1548 template <class DataType> class bits_storage<DataType, bool> {
1549 unsigned Bits; // Where to store the bits...
1551 template <class T> static unsigned Bit(const T &V) {
1552 unsigned BitPos = (unsigned)V;
1553 assert(BitPos < sizeof(unsigned) * CHAR_BIT &&
1554 "enum exceeds width of bit vector!");
1559 template <class T> void addValue(const T &V) { Bits |= Bit(V); }
1561 unsigned getBits() { return Bits; }
1563 template <class T> bool isSet(const T &V) { return (Bits & Bit(V)) != 0; }
1566 //===----------------------------------------------------------------------===//
1567 // bits - A bit vector of command options.
1569 template <class DataType, class Storage = bool,
1570 class ParserClass = parser<DataType>>
1571 class bits : public Option, public bits_storage<DataType, Storage> {
1572 std::vector<unsigned> Positions;
1575 enum ValueExpected getValueExpectedFlagDefault() const override {
1576 return Parser.getValueExpectedFlagDefault();
1579 getExtraOptionNames(SmallVectorImpl<const char *> &OptionNames) override {
1580 return Parser.getExtraOptionNames(OptionNames);
1583 bool handleOccurrence(unsigned pos, StringRef ArgName,
1584 StringRef Arg) override {
1585 typename ParserClass::parser_data_type Val =
1586 typename ParserClass::parser_data_type();
1587 if (Parser.parse(*this, ArgName, Arg, Val))
1588 return true; // Parse Error!
1589 this->addValue(Val);
1591 Positions.push_back(pos);
1595 // Forward printing stuff to the parser...
1596 size_t getOptionWidth() const override {
1597 return Parser.getOptionWidth(*this);
1599 void printOptionInfo(size_t GlobalWidth) const override {
1600 Parser.printOptionInfo(*this, GlobalWidth);
1603 // Unimplemented: bits options don't currently store their default values.
1604 void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override {
1609 Parser.initialize();
1612 // Command line options should not be copyable
1613 bits(const bits &) LLVM_DELETED_FUNCTION;
1614 bits &operator=(const bits &) LLVM_DELETED_FUNCTION;
1617 ParserClass &getParser() { return Parser; }
1619 unsigned getPosition(unsigned optnum) const {
1620 assert(optnum < this->size() && "Invalid option index");
1621 return Positions[optnum];
1625 template <class M0t>
1626 explicit bits(const M0t &M0)
1627 : Option(ZeroOrMore, NotHidden), Parser(*this) {
1632 template <class M0t, class M1t>
1633 bits(const M0t &M0, const M1t &M1)
1634 : Option(ZeroOrMore, NotHidden), Parser(*this) {
1640 template <class M0t, class M1t, class M2t>
1641 bits(const M0t &M0, const M1t &M1, const M2t &M2)
1642 : Option(ZeroOrMore, NotHidden), Parser(*this) {
1649 template <class M0t, class M1t, class M2t, class M3t>
1650 bits(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3)
1651 : Option(ZeroOrMore, NotHidden), Parser(*this) {
1659 template <class M0t, class M1t, class M2t, class M3t, class M4t>
1660 bits(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
1662 : Option(ZeroOrMore, NotHidden), Parser(*this) {
1671 template <class M0t, class M1t, class M2t, class M3t, class M4t, class M5t>
1672 bits(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
1673 const M4t &M4, const M5t &M5)
1674 : Option(ZeroOrMore, NotHidden), Parser(*this) {
1684 template <class M0t, class M1t, class M2t, class M3t, class M4t, class M5t,
1686 bits(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
1687 const M4t &M4, const M5t &M5, const M6t &M6)
1688 : Option(ZeroOrMore, NotHidden), Parser(*this) {
1699 template <class M0t, class M1t, class M2t, class M3t, class M4t, class M5t,
1700 class M6t, class M7t>
1701 bits(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
1702 const M4t &M4, const M5t &M5, const M6t &M6, const M7t &M7)
1703 : Option(ZeroOrMore, NotHidden), Parser(*this) {
1716 //===----------------------------------------------------------------------===//
1717 // Aliased command line option (alias this name to a preexisting name)
1720 class alias : public Option {
1722 bool handleOccurrence(unsigned pos, StringRef /*ArgName*/,
1723 StringRef Arg) override {
1724 return AliasFor->handleOccurrence(pos, AliasFor->ArgStr, Arg);
1726 bool addOccurrence(unsigned pos, StringRef /*ArgName*/, StringRef Value,
1727 bool MultiArg = false) override {
1728 return AliasFor->addOccurrence(pos, AliasFor->ArgStr, Value, MultiArg);
1730 // Handle printing stuff...
1731 size_t getOptionWidth() const override;
1732 void printOptionInfo(size_t GlobalWidth) const override;
1734 // Aliases do not need to print their values.
1735 void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override {
1738 ValueExpected getValueExpectedFlagDefault() const override {
1739 return AliasFor->getValueExpectedFlag();
1744 error("cl::alias must have argument name specified!");
1746 error("cl::alias must have an cl::aliasopt(option) specified!");
1750 // Command line options should not be copyable
1751 alias(const alias &) LLVM_DELETED_FUNCTION;
1752 alias &operator=(const alias &) LLVM_DELETED_FUNCTION;
1755 void setAliasFor(Option &O) {
1757 error("cl::alias must only have one cl::aliasopt(...) specified!");
1762 template <class M0t>
1763 explicit alias(const M0t &M0)
1764 : Option(Optional, Hidden), AliasFor(nullptr) {
1769 template <class M0t, class M1t>
1770 alias(const M0t &M0, const M1t &M1)
1771 : Option(Optional, Hidden), AliasFor(nullptr) {
1777 template <class M0t, class M1t, class M2t>
1778 alias(const M0t &M0, const M1t &M1, const M2t &M2)
1779 : Option(Optional, Hidden), AliasFor(nullptr) {
1786 template <class M0t, class M1t, class M2t, class M3t>
1787 alias(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3)
1788 : Option(Optional, Hidden), AliasFor(nullptr) {
1797 // aliasfor - Modifier to set the option an alias aliases.
1800 explicit aliasopt(Option &O) : Opt(O) {}
1801 void apply(alias &A) const { A.setAliasFor(Opt); }
1804 // extrahelp - provide additional help at the end of the normal help
1805 // output. All occurrences of cl::extrahelp will be accumulated and
1806 // printed to stderr at the end of the regular help, just before
1809 const char *morehelp;
1810 explicit extrahelp(const char *help);
1813 void PrintVersionMessage();
1815 /// This function just prints the help message, exactly the same way as if the
1816 /// -help or -help-hidden option had been given on the command line.
1818 /// NOTE: THIS FUNCTION TERMINATES THE PROGRAM!
1820 /// \param Hidden if true will print hidden options
1821 /// \param Categorized if true print options in categories
1822 void PrintHelpMessage(bool Hidden = false, bool Categorized = false);
1824 //===----------------------------------------------------------------------===//
1825 // Public interface for accessing registered options.
1828 /// \brief Use this to get a StringMap to all registered named options
1829 /// (e.g. -help). Note \p Map Should be an empty StringMap.
1831 /// \param [out] Map will be filled with mappings where the key is the
1832 /// Option argument string (e.g. "help") and value is the corresponding
1835 /// Access to unnamed arguments (i.e. positional) are not provided because
1836 /// it is expected that the client already has access to these.
1840 /// main(int argc,char* argv[]) {
1841 /// StringMap<llvm::cl::Option*> opts;
1842 /// llvm::cl::getRegisteredOptions(opts);
1843 /// assert(opts.count("help") == 1)
1844 /// opts["help"]->setDescription("Show alphabetical help information")
1846 /// llvm::cl::ParseCommandLineOptions(argc,argv);
1851 /// This interface is useful for modifying options in libraries that are out of
1852 /// the control of the client. The options should be modified before calling
1853 /// llvm::cl::ParseCommandLineOptions().
1854 void getRegisteredOptions(StringMap<Option *> &Map);
1856 //===----------------------------------------------------------------------===//
1857 // Standalone command line processing utilities.
1860 /// \brief Saves strings in the inheritor's stable storage and returns a stable
1861 /// raw character pointer.
1863 virtual void anchor();
1866 virtual const char *SaveString(const char *Str) = 0;
1867 virtual ~StringSaver(){}; // Pacify -Wnon-virtual-dtor.
1870 /// \brief Tokenizes a command line that can contain escapes and quotes.
1872 /// The quoting rules match those used by GCC and other tools that use
1873 /// libiberty's buildargv() or expandargv() utilities, and do not match bash.
1874 /// They differ from buildargv() on treatment of backslashes that do not escape
1875 /// a special character to make it possible to accept most Windows file paths.
1877 /// \param [in] Source The string to be split on whitespace with quotes.
1878 /// \param [in] Saver Delegates back to the caller for saving parsed strings.
1879 /// \param [in] MarkEOLs true if tokenizing a response file and you want end of
1880 /// lines and end of the response file to be marked with a nullptr string.
1881 /// \param [out] NewArgv All parsed strings are appended to NewArgv.
1882 void TokenizeGNUCommandLine(StringRef Source, StringSaver &Saver,
1883 SmallVectorImpl<const char *> &NewArgv,
1884 bool MarkEOLs = false);
1886 /// \brief Tokenizes a Windows command line which may contain quotes and escaped
1889 /// See MSDN docs for CommandLineToArgvW for information on the quoting rules.
1890 /// http://msdn.microsoft.com/en-us/library/windows/desktop/17w5ykft(v=vs.85).aspx
1892 /// \param [in] Source The string to be split on whitespace with quotes.
1893 /// \param [in] Saver Delegates back to the caller for saving parsed strings.
1894 /// \param [in] MarkEOLs true if tokenizing a response file and you want end of
1895 /// lines and end of the response file to be marked with a nullptr string.
1896 /// \param [out] NewArgv All parsed strings are appended to NewArgv.
1897 void TokenizeWindowsCommandLine(StringRef Source, StringSaver &Saver,
1898 SmallVectorImpl<const char *> &NewArgv,
1899 bool MarkEOLs = false);
1901 /// \brief String tokenization function type. Should be compatible with either
1902 /// Windows or Unix command line tokenizers.
1903 typedef void (*TokenizerCallback)(StringRef Source, StringSaver &Saver,
1904 SmallVectorImpl<const char *> &NewArgv,
1907 /// \brief Expand response files on a command line recursively using the given
1908 /// StringSaver and tokenization strategy. Argv should contain the command line
1909 /// before expansion and will be modified in place. If requested, Argv will
1910 /// also be populated with nullptrs indicating where each response file line
1911 /// ends, which is useful for the "/link" argument that needs to consume all
1912 /// remaining arguments only until the next end of line, when in a response
1915 /// \param [in] Saver Delegates back to the caller for saving parsed strings.
1916 /// \param [in] Tokenizer Tokenization strategy. Typically Unix or Windows.
1917 /// \param [in,out] Argv Command line into which to expand response files.
1918 /// \param [in] MarkEOLs Mark end of lines and the end of the response file
1919 /// with nullptrs in the Argv vector.
1920 /// \return true if all @files were expanded successfully or there were none.
1921 bool ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
1922 SmallVectorImpl<const char *> &Argv,
1923 bool MarkEOLs = false);
1925 /// \brief Mark all options not part of this category as cl::ReallyHidden.
1927 /// \param Category the category of options to keep displaying
1929 /// Some tools (like clang-format) like to be able to hide all options that are
1930 /// not specific to the tool. This function allows a tool to specify a single
1931 /// option category to display in the -help output.
1932 void HideUnrelatedOptions(cl::OptionCategory &Category);
1934 /// \brief Mark all options not part of the categories as cl::ReallyHidden.
1936 /// \param Categories the categories of options to keep displaying.
1938 /// Some tools (like clang-format) like to be able to hide all options that are
1939 /// not specific to the tool. This function allows a tool to specify a single
1940 /// option category to display in the -help output.
1941 void HideUnrelatedOptions(SmallVectorImpl<cl::OptionCategory *> &Categories);
1943 } // End namespace cl
1945 } // End namespace llvm