Implemented public interface for modifying registered (not positional or sink options...
[oota-llvm.git] / include / llvm / Support / CommandLine.h
1 //===- llvm/Support/CommandLine.h - Command line handler --------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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.
13 //
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
17 //
18 //===----------------------------------------------------------------------===//
19
20 #ifndef LLVM_SUPPORT_COMMANDLINE_H
21 #define LLVM_SUPPORT_COMMANDLINE_H
22
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/Twine.h"
25 #include "llvm/ADT/StringMap.h"
26 #include "llvm/Support/Compiler.h"
27 #include "llvm/Support/type_traits.h"
28 #include <cassert>
29 #include <climits>
30 #include <cstdarg>
31 #include <utility>
32 #include <vector>
33
34 namespace llvm {
35
36 /// cl Namespace - This namespace contains all of the command line option
37 /// processing machinery.  It is intentionally a short name to make qualified
38 /// usage concise.
39 namespace cl {
40
41 //===----------------------------------------------------------------------===//
42 // ParseCommandLineOptions - Command line option processing entry point.
43 //
44 void ParseCommandLineOptions(int argc, const char * const *argv,
45                              const char *Overview = 0);
46
47 //===----------------------------------------------------------------------===//
48 // ParseEnvironmentOptions - Environment variable option processing alternate
49 //                           entry point.
50 //
51 void ParseEnvironmentOptions(const char *progName, const char *envvar,
52                              const char *Overview = 0);
53
54 ///===---------------------------------------------------------------------===//
55 /// SetVersionPrinter - Override the default (LLVM specific) version printer
56 ///                     used to print out the version when --version is given
57 ///                     on the command line. This allows other systems using the
58 ///                     CommandLine utilities to print their own version string.
59 void SetVersionPrinter(void (*func)());
60
61 ///===---------------------------------------------------------------------===//
62 /// AddExtraVersionPrinter - Add an extra printer to use in addition to the
63 ///                          default one. This can be called multiple times,
64 ///                          and each time it adds a new function to the list
65 ///                          which will be called after the basic LLVM version
66 ///                          printing is complete. Each can then add additional
67 ///                          information specific to the tool.
68 void AddExtraVersionPrinter(void (*func)());
69
70
71 // PrintOptionValues - Print option values.
72 // With -print-options print the difference between option values and defaults.
73 // With -print-all-options print all option values.
74 // (Currently not perfect, but best-effort.)
75 void PrintOptionValues();
76
77 // MarkOptionsChanged - Internal helper function.
78 void MarkOptionsChanged();
79
80 //===----------------------------------------------------------------------===//
81 // Flags permitted to be passed to command line arguments
82 //
83
84 enum NumOccurrencesFlag {      // Flags for the number of occurrences allowed
85   Optional        = 0x00,      // Zero or One occurrence
86   ZeroOrMore      = 0x01,      // Zero or more occurrences allowed
87   Required        = 0x02,      // One occurrence required
88   OneOrMore       = 0x03,      // One or more occurrences required
89
90   // ConsumeAfter - Indicates that this option is fed anything that follows the
91   // last positional argument required by the application (it is an error if
92   // there are zero positional arguments, and a ConsumeAfter option is used).
93   // Thus, for example, all arguments to LLI are processed until a filename is
94   // found.  Once a filename is found, all of the succeeding arguments are
95   // passed, unprocessed, to the ConsumeAfter option.
96   //
97   ConsumeAfter    = 0x04
98 };
99
100 enum ValueExpected {           // Is a value required for the option?
101   // zero reserved for the unspecified value
102   ValueOptional   = 0x01,      // The value can appear... or not
103   ValueRequired   = 0x02,      // The value is required to appear!
104   ValueDisallowed = 0x03       // A value may not be specified (for flags)
105 };
106
107 enum OptionHidden {            // Control whether -help shows this option
108   NotHidden       = 0x00,      // Option included in -help & -help-hidden
109   Hidden          = 0x01,      // -help doesn't, but -help-hidden does
110   ReallyHidden    = 0x02       // Neither -help nor -help-hidden show this arg
111 };
112
113 // Formatting flags - This controls special features that the option might have
114 // that cause it to be parsed differently...
115 //
116 // Prefix - This option allows arguments that are otherwise unrecognized to be
117 // matched by options that are a prefix of the actual value.  This is useful for
118 // cases like a linker, where options are typically of the form '-lfoo' or
119 // '-L../../include' where -l or -L are the actual flags.  When prefix is
120 // enabled, and used, the value for the flag comes from the suffix of the
121 // argument.
122 //
123 // Grouping - With this option enabled, multiple letter options are allowed to
124 // bunch together with only a single hyphen for the whole group.  This allows
125 // emulation of the behavior that ls uses for example: ls -la === ls -l -a
126 //
127
128 enum FormattingFlags {
129   NormalFormatting = 0x00,     // Nothing special
130   Positional       = 0x01,     // Is a positional argument, no '-' required
131   Prefix           = 0x02,     // Can this option directly prefix its value?
132   Grouping         = 0x03      // Can this option group with other options?
133 };
134
135 enum MiscFlags {               // Miscellaneous flags to adjust argument
136   CommaSeparated     = 0x01,  // Should this cl::list split between commas?
137   PositionalEatsArgs = 0x02,  // Should this positional cl::list eat -args?
138   Sink               = 0x04   // Should this cl::list eat all unknown options?
139 };
140
141 //===----------------------------------------------------------------------===//
142 // Option Category class
143 //
144 class OptionCategory {
145 private:
146   const char *const Name;
147   const char *const Description;
148   void registerCategory();
149 public:
150   OptionCategory(const char *const Name, const char *const Description = 0)
151       : Name(Name), Description(Description) { registerCategory(); }
152   const char *getName() { return Name; }
153   const char *getDescription() { return Description; }
154 };
155
156 // The general Option Category (used as default category).
157 extern OptionCategory GeneralCategory;
158
159 //===----------------------------------------------------------------------===//
160 // Option Base class
161 //
162 class alias;
163 class Option {
164   friend class alias;
165
166   // handleOccurrences - Overriden by subclasses to handle the value passed into
167   // an argument.  Should return true if there was an error processing the
168   // argument and the program should exit.
169   //
170   virtual bool handleOccurrence(unsigned pos, StringRef ArgName,
171                                 StringRef Arg) = 0;
172
173   virtual enum ValueExpected getValueExpectedFlagDefault() const {
174     return ValueOptional;
175   }
176
177   // Out of line virtual function to provide home for the class.
178   virtual void anchor();
179
180   int NumOccurrences;     // The number of times specified
181   // Occurrences, HiddenFlag, and Formatting are all enum types but to avoid
182   // problems with signed enums in bitfields.
183   unsigned Occurrences : 3; // enum NumOccurrencesFlag
184   // not using the enum type for 'Value' because zero is an implementation
185   // detail representing the non-value
186   unsigned Value : 2;
187   unsigned HiddenFlag : 2; // enum OptionHidden
188   unsigned Formatting : 2; // enum FormattingFlags
189   unsigned Misc : 3;
190   unsigned Position;      // Position of last occurrence of the option
191   unsigned AdditionalVals;// Greater than 0 for multi-valued option.
192   Option *NextRegistered; // Singly linked list of registered options.
193
194 public:
195   const char *ArgStr;   // The argument string itself (ex: "help", "o")
196   const char *HelpStr;  // The descriptive text message for -help
197   const char *ValueStr; // String describing what the value of this option is
198   OptionCategory *Category; // The Category this option belongs to
199
200   inline enum NumOccurrencesFlag getNumOccurrencesFlag() const {
201     return (enum NumOccurrencesFlag)Occurrences;
202   }
203   inline enum ValueExpected getValueExpectedFlag() const {
204     return Value ? ((enum ValueExpected)Value)
205               : getValueExpectedFlagDefault();
206   }
207   inline enum OptionHidden getOptionHiddenFlag() const {
208     return (enum OptionHidden)HiddenFlag;
209   }
210   inline enum FormattingFlags getFormattingFlag() const {
211     return (enum FormattingFlags)Formatting;
212   }
213   inline unsigned getMiscFlags() const {
214     return Misc;
215   }
216   inline unsigned getPosition() const { return Position; }
217   inline unsigned getNumAdditionalVals() const { return AdditionalVals; }
218
219   // hasArgStr - Return true if the argstr != ""
220   bool hasArgStr() const { return ArgStr[0] != 0; }
221
222   //-------------------------------------------------------------------------===
223   // Accessor functions set by OptionModifiers
224   //
225   void setArgStr(const char *S) { ArgStr = S; }
226   void setDescription(const char *S) { HelpStr = S; }
227   void setValueStr(const char *S) { ValueStr = S; }
228   void setNumOccurrencesFlag(enum NumOccurrencesFlag Val) {
229     Occurrences = Val;
230   }
231   void setValueExpectedFlag(enum ValueExpected Val) { Value = Val; }
232   void setHiddenFlag(enum OptionHidden Val) { HiddenFlag = Val; }
233   void setFormattingFlag(enum FormattingFlags V) { Formatting = V; }
234   void setMiscFlag(enum MiscFlags M) { Misc |= M; }
235   void setPosition(unsigned pos) { Position = pos; }
236   void setCategory(OptionCategory &C) { Category = &C; }
237 protected:
238   explicit Option(enum NumOccurrencesFlag OccurrencesFlag,
239                   enum OptionHidden Hidden)
240     : NumOccurrences(0), Occurrences(OccurrencesFlag), Value(0),
241       HiddenFlag(Hidden), Formatting(NormalFormatting), Misc(0),
242       Position(0), AdditionalVals(0), NextRegistered(0),
243       ArgStr(""), HelpStr(""), ValueStr(""), Category(&GeneralCategory) {
244   }
245
246   inline void setNumAdditionalVals(unsigned n) { AdditionalVals = n; }
247 public:
248   // addArgument - Register this argument with the commandline system.
249   //
250   void addArgument();
251
252   Option *getNextRegisteredOption() const { return NextRegistered; }
253
254   // Return the width of the option tag for printing...
255   virtual size_t getOptionWidth() const = 0;
256
257   // printOptionInfo - Print out information about this option.  The
258   // to-be-maintained width is specified.
259   //
260   virtual void printOptionInfo(size_t GlobalWidth) const = 0;
261
262   virtual void printOptionValue(size_t GlobalWidth, bool Force) const = 0;
263
264   virtual void getExtraOptionNames(SmallVectorImpl<const char*> &) {}
265
266   // addOccurrence - Wrapper around handleOccurrence that enforces Flags.
267   //
268   bool addOccurrence(unsigned pos, StringRef ArgName,
269                      StringRef Value, bool MultiArg = false);
270
271   // Prints option name followed by message.  Always returns true.
272   bool error(const Twine &Message, StringRef ArgName = StringRef());
273
274 public:
275   inline int getNumOccurrences() const { return NumOccurrences; }
276   virtual ~Option() {}
277 };
278
279
280 //===----------------------------------------------------------------------===//
281 // Command line option modifiers that can be used to modify the behavior of
282 // command line option parsers...
283 //
284
285 // desc - Modifier to set the description shown in the -help output...
286 struct desc {
287   const char *Desc;
288   desc(const char *Str) : Desc(Str) {}
289   void apply(Option &O) const { O.setDescription(Desc); }
290 };
291
292 // value_desc - Modifier to set the value description shown in the -help
293 // output...
294 struct value_desc {
295   const char *Desc;
296   value_desc(const char *Str) : Desc(Str) {}
297   void apply(Option &O) const { O.setValueStr(Desc); }
298 };
299
300 // init - Specify a default (initial) value for the command line argument, if
301 // the default constructor for the argument type does not give you what you
302 // want.  This is only valid on "opt" arguments, not on "list" arguments.
303 //
304 template<class Ty>
305 struct initializer {
306   const Ty &Init;
307   initializer(const Ty &Val) : Init(Val) {}
308
309   template<class Opt>
310   void apply(Opt &O) const { O.setInitialValue(Init); }
311 };
312
313 template<class Ty>
314 initializer<Ty> init(const Ty &Val) {
315   return initializer<Ty>(Val);
316 }
317
318
319 // location - Allow the user to specify which external variable they want to
320 // store the results of the command line argument processing into, if they don't
321 // want to store it in the option itself.
322 //
323 template<class Ty>
324 struct LocationClass {
325   Ty &Loc;
326   LocationClass(Ty &L) : Loc(L) {}
327
328   template<class Opt>
329   void apply(Opt &O) const { O.setLocation(O, Loc); }
330 };
331
332 template<class Ty>
333 LocationClass<Ty> location(Ty &L) { return LocationClass<Ty>(L); }
334
335 // cat - Specifiy the Option category for the command line argument to belong
336 // to.
337 struct cat {
338   OptionCategory &Category;
339   cat(OptionCategory &c) : Category(c) {}
340
341   template<class Opt>
342   void apply(Opt &O) const { O.setCategory(Category); }
343 };
344
345
346 //===----------------------------------------------------------------------===//
347 // OptionValue class
348
349 // Support value comparison outside the template.
350 struct GenericOptionValue {
351   virtual ~GenericOptionValue() {}
352   virtual bool compare(const GenericOptionValue &V) const = 0;
353 private:
354   virtual void anchor();
355 };
356
357 template<class DataType> struct OptionValue;
358
359 // The default value safely does nothing. Option value printing is only
360 // best-effort.
361 template<class DataType, bool isClass>
362 struct OptionValueBase : public GenericOptionValue {
363   // Temporary storage for argument passing.
364   typedef OptionValue<DataType> WrapperType;
365
366   bool hasValue() const { return false; }
367
368   const DataType &getValue() const { llvm_unreachable("no default value"); }
369
370   // Some options may take their value from a different data type.
371   template<class DT>
372   void setValue(const DT& /*V*/) {}
373
374   bool compare(const DataType &/*V*/) const { return false; }
375
376   virtual bool compare(const GenericOptionValue& /*V*/) const { return false; }
377 };
378
379 // Simple copy of the option value.
380 template<class DataType>
381 class OptionValueCopy : public GenericOptionValue {
382   DataType Value;
383   bool Valid;
384 public:
385   OptionValueCopy() : Valid(false) {}
386
387   bool hasValue() const { return Valid; }
388
389   const DataType &getValue() const {
390     assert(Valid && "invalid option value");
391     return Value;
392   }
393
394   void setValue(const DataType &V) { Valid = true; Value = V; }
395
396   bool compare(const DataType &V) const {
397     return Valid && (Value != V);
398   }
399
400   virtual bool compare(const GenericOptionValue &V) const {
401     const OptionValueCopy<DataType> &VC =
402       static_cast< const OptionValueCopy<DataType>& >(V);
403     if (!VC.hasValue()) return false;
404     return compare(VC.getValue());
405   }
406 };
407
408 // Non-class option values.
409 template<class DataType>
410 struct OptionValueBase<DataType, false> : OptionValueCopy<DataType> {
411   typedef DataType WrapperType;
412 };
413
414 // Top-level option class.
415 template<class DataType>
416 struct OptionValue : OptionValueBase<DataType, is_class<DataType>::value> {
417   OptionValue() {}
418
419   OptionValue(const DataType& V) {
420     this->setValue(V);
421   }
422   // Some options may take their value from a different data type.
423   template<class DT>
424   OptionValue<DataType> &operator=(const DT& V) {
425     this->setValue(V);
426     return *this;
427   }
428 };
429
430 // Other safe-to-copy-by-value common option types.
431 enum boolOrDefault { BOU_UNSET, BOU_TRUE, BOU_FALSE };
432 template<>
433 struct OptionValue<cl::boolOrDefault> : OptionValueCopy<cl::boolOrDefault> {
434   typedef cl::boolOrDefault WrapperType;
435
436   OptionValue() {}
437
438   OptionValue(const cl::boolOrDefault& V) {
439     this->setValue(V);
440   }
441   OptionValue<cl::boolOrDefault> &operator=(const cl::boolOrDefault& V) {
442     setValue(V);
443     return *this;
444   }
445 private:
446   virtual void anchor();
447 };
448
449 template<>
450 struct OptionValue<std::string> : OptionValueCopy<std::string> {
451   typedef StringRef WrapperType;
452
453   OptionValue() {}
454
455   OptionValue(const std::string& V) {
456     this->setValue(V);
457   }
458   OptionValue<std::string> &operator=(const std::string& V) {
459     setValue(V);
460     return *this;
461   }
462 private:
463   virtual void anchor();
464 };
465
466 //===----------------------------------------------------------------------===//
467 // Enum valued command line option
468 //
469 #define clEnumVal(ENUMVAL, DESC) #ENUMVAL, int(ENUMVAL), DESC
470 #define clEnumValN(ENUMVAL, FLAGNAME, DESC) FLAGNAME, int(ENUMVAL), DESC
471 #define clEnumValEnd (reinterpret_cast<void*>(0))
472
473 // values - For custom data types, allow specifying a group of values together
474 // as the values that go into the mapping that the option handler uses.  Note
475 // that the values list must always have a 0 at the end of the list to indicate
476 // that the list has ended.
477 //
478 template<class DataType>
479 class ValuesClass {
480   // Use a vector instead of a map, because the lists should be short,
481   // the overhead is less, and most importantly, it keeps them in the order
482   // inserted so we can print our option out nicely.
483   SmallVector<std::pair<const char *, std::pair<int, const char *> >,4> Values;
484   void processValues(va_list Vals);
485 public:
486   ValuesClass(const char *EnumName, DataType Val, const char *Desc,
487               va_list ValueArgs) {
488     // Insert the first value, which is required.
489     Values.push_back(std::make_pair(EnumName, std::make_pair(Val, Desc)));
490
491     // Process the varargs portion of the values...
492     while (const char *enumName = va_arg(ValueArgs, const char *)) {
493       DataType EnumVal = static_cast<DataType>(va_arg(ValueArgs, int));
494       const char *EnumDesc = va_arg(ValueArgs, const char *);
495       Values.push_back(std::make_pair(enumName,      // Add value to value map
496                                       std::make_pair(EnumVal, EnumDesc)));
497     }
498   }
499
500   template<class Opt>
501   void apply(Opt &O) const {
502     for (size_t i = 0, e = Values.size(); i != e; ++i)
503       O.getParser().addLiteralOption(Values[i].first, Values[i].second.first,
504                                      Values[i].second.second);
505   }
506 };
507
508 template<class DataType>
509 ValuesClass<DataType> END_WITH_NULL values(const char *Arg, DataType Val,
510                                            const char *Desc, ...) {
511     va_list ValueArgs;
512     va_start(ValueArgs, Desc);
513     ValuesClass<DataType> Vals(Arg, Val, Desc, ValueArgs);
514     va_end(ValueArgs);
515     return Vals;
516 }
517
518 //===----------------------------------------------------------------------===//
519 // parser class - Parameterizable parser for different data types.  By default,
520 // known data types (string, int, bool) have specialized parsers, that do what
521 // you would expect.  The default parser, used for data types that are not
522 // built-in, uses a mapping table to map specific options to values, which is
523 // used, among other things, to handle enum types.
524
525 //--------------------------------------------------
526 // generic_parser_base - This class holds all the non-generic code that we do
527 // not need replicated for every instance of the generic parser.  This also
528 // allows us to put stuff into CommandLine.cpp
529 //
530 class generic_parser_base {
531 protected:
532   class GenericOptionInfo {
533   public:
534     GenericOptionInfo(const char *name, const char *helpStr) :
535       Name(name), HelpStr(helpStr) {}
536     const char *Name;
537     const char *HelpStr;
538   };
539 public:
540   virtual ~generic_parser_base() {}  // Base class should have virtual-dtor
541
542   // getNumOptions - Virtual function implemented by generic subclass to
543   // indicate how many entries are in Values.
544   //
545   virtual unsigned getNumOptions() const = 0;
546
547   // getOption - Return option name N.
548   virtual const char *getOption(unsigned N) const = 0;
549
550   // getDescription - Return description N
551   virtual const char *getDescription(unsigned N) const = 0;
552
553   // Return the width of the option tag for printing...
554   virtual size_t getOptionWidth(const Option &O) const;
555
556   virtual const GenericOptionValue &getOptionValue(unsigned N) const = 0;
557
558   // printOptionInfo - Print out information about this option.  The
559   // to-be-maintained width is specified.
560   //
561   virtual void printOptionInfo(const Option &O, size_t GlobalWidth) const;
562
563   void printGenericOptionDiff(const Option &O, const GenericOptionValue &V,
564                               const GenericOptionValue &Default,
565                               size_t GlobalWidth) const;
566
567   // printOptionDiff - print the value of an option and it's default.
568   //
569   // Template definition ensures that the option and default have the same
570   // DataType (via the same AnyOptionValue).
571   template<class AnyOptionValue>
572   void printOptionDiff(const Option &O, const AnyOptionValue &V,
573                        const AnyOptionValue &Default,
574                        size_t GlobalWidth) const {
575     printGenericOptionDiff(O, V, Default, GlobalWidth);
576   }
577
578   void initialize(Option &O) {
579     // All of the modifiers for the option have been processed by now, so the
580     // argstr field should be stable, copy it down now.
581     //
582     hasArgStr = O.hasArgStr();
583   }
584
585   void getExtraOptionNames(SmallVectorImpl<const char*> &OptionNames) {
586     // If there has been no argstr specified, that means that we need to add an
587     // argument for every possible option.  This ensures that our options are
588     // vectored to us.
589     if (!hasArgStr)
590       for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
591         OptionNames.push_back(getOption(i));
592   }
593
594
595   enum ValueExpected getValueExpectedFlagDefault() const {
596     // If there is an ArgStr specified, then we are of the form:
597     //
598     //    -opt=O2   or   -opt O2  or  -optO2
599     //
600     // In which case, the value is required.  Otherwise if an arg str has not
601     // been specified, we are of the form:
602     //
603     //    -O2 or O2 or -la (where -l and -a are separate options)
604     //
605     // If this is the case, we cannot allow a value.
606     //
607     if (hasArgStr)
608       return ValueRequired;
609     else
610       return ValueDisallowed;
611   }
612
613   // findOption - Return the option number corresponding to the specified
614   // argument string.  If the option is not found, getNumOptions() is returned.
615   //
616   unsigned findOption(const char *Name);
617
618 protected:
619   bool hasArgStr;
620 };
621
622 // Default parser implementation - This implementation depends on having a
623 // mapping of recognized options to values of some sort.  In addition to this,
624 // each entry in the mapping also tracks a help message that is printed with the
625 // command line option for -help.  Because this is a simple mapping parser, the
626 // data type can be any unsupported type.
627 //
628 template <class DataType>
629 class parser : public generic_parser_base {
630 protected:
631   class OptionInfo : public GenericOptionInfo {
632   public:
633     OptionInfo(const char *name, DataType v, const char *helpStr) :
634       GenericOptionInfo(name, helpStr), V(v) {}
635     OptionValue<DataType> V;
636   };
637   SmallVector<OptionInfo, 8> Values;
638 public:
639   typedef DataType parser_data_type;
640
641   // Implement virtual functions needed by generic_parser_base
642   unsigned getNumOptions() const { return unsigned(Values.size()); }
643   const char *getOption(unsigned N) const { return Values[N].Name; }
644   const char *getDescription(unsigned N) const {
645     return Values[N].HelpStr;
646   }
647
648   // getOptionValue - Return the value of option name N.
649   virtual const GenericOptionValue &getOptionValue(unsigned N) const {
650     return Values[N].V;
651   }
652
653   // parse - Return true on error.
654   bool parse(Option &O, StringRef ArgName, StringRef Arg, DataType &V) {
655     StringRef ArgVal;
656     if (hasArgStr)
657       ArgVal = Arg;
658     else
659       ArgVal = ArgName;
660
661     for (size_t i = 0, e = Values.size(); i != e; ++i)
662       if (Values[i].Name == ArgVal) {
663         V = Values[i].V.getValue();
664         return false;
665       }
666
667     return O.error("Cannot find option named '" + ArgVal + "'!");
668   }
669
670   /// addLiteralOption - Add an entry to the mapping table.
671   ///
672   template <class DT>
673   void addLiteralOption(const char *Name, const DT &V, const char *HelpStr) {
674     assert(findOption(Name) == Values.size() && "Option already exists!");
675     OptionInfo X(Name, static_cast<DataType>(V), HelpStr);
676     Values.push_back(X);
677     MarkOptionsChanged();
678   }
679
680   /// removeLiteralOption - Remove the specified option.
681   ///
682   void removeLiteralOption(const char *Name) {
683     unsigned N = findOption(Name);
684     assert(N != Values.size() && "Option not found!");
685     Values.erase(Values.begin()+N);
686   }
687 };
688
689 //--------------------------------------------------
690 // basic_parser - Super class of parsers to provide boilerplate code
691 //
692 class basic_parser_impl {  // non-template implementation of basic_parser<t>
693 public:
694   virtual ~basic_parser_impl() {}
695
696   enum ValueExpected getValueExpectedFlagDefault() const {
697     return ValueRequired;
698   }
699
700   void getExtraOptionNames(SmallVectorImpl<const char*> &) {}
701
702   void initialize(Option &) {}
703
704   // Return the width of the option tag for printing...
705   size_t getOptionWidth(const Option &O) const;
706
707   // printOptionInfo - Print out information about this option.  The
708   // to-be-maintained width is specified.
709   //
710   void printOptionInfo(const Option &O, size_t GlobalWidth) const;
711
712   // printOptionNoValue - Print a placeholder for options that don't yet support
713   // printOptionDiff().
714   void printOptionNoValue(const Option &O, size_t GlobalWidth) const;
715
716   // getValueName - Overload in subclass to provide a better default value.
717   virtual const char *getValueName() const { return "value"; }
718
719   // An out-of-line virtual method to provide a 'home' for this class.
720   virtual void anchor();
721
722 protected:
723   // A helper for basic_parser::printOptionDiff.
724   void printOptionName(const Option &O, size_t GlobalWidth) const;
725 };
726
727 // basic_parser - The real basic parser is just a template wrapper that provides
728 // a typedef for the provided data type.
729 //
730 template<class DataType>
731 class basic_parser : public basic_parser_impl {
732 public:
733   typedef DataType parser_data_type;
734   typedef OptionValue<DataType> OptVal;
735 };
736
737 //--------------------------------------------------
738 // parser<bool>
739 //
740 template<>
741 class parser<bool> : public basic_parser<bool> {
742   const char *ArgStr;
743 public:
744
745   // parse - Return true on error.
746   bool parse(Option &O, StringRef ArgName, StringRef Arg, bool &Val);
747
748   template <class Opt>
749   void initialize(Opt &O) {
750     ArgStr = O.ArgStr;
751   }
752
753   enum ValueExpected getValueExpectedFlagDefault() const {
754     return ValueOptional;
755   }
756
757   // getValueName - Do not print =<value> at all.
758   virtual const char *getValueName() const { return 0; }
759
760   void printOptionDiff(const Option &O, bool V, OptVal Default,
761                        size_t GlobalWidth) const;
762
763   // An out-of-line virtual method to provide a 'home' for this class.
764   virtual void anchor();
765 };
766
767 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<bool>);
768
769 //--------------------------------------------------
770 // parser<boolOrDefault>
771 template<>
772 class parser<boolOrDefault> : public basic_parser<boolOrDefault> {
773 public:
774   // parse - Return true on error.
775   bool parse(Option &O, StringRef ArgName, StringRef Arg, boolOrDefault &Val);
776
777   enum ValueExpected getValueExpectedFlagDefault() const {
778     return ValueOptional;
779   }
780
781   // getValueName - Do not print =<value> at all.
782   virtual const char *getValueName() const { return 0; }
783
784   void printOptionDiff(const Option &O, boolOrDefault V, OptVal Default,
785                        size_t GlobalWidth) const;
786
787   // An out-of-line virtual method to provide a 'home' for this class.
788   virtual void anchor();
789 };
790
791 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<boolOrDefault>);
792
793 //--------------------------------------------------
794 // parser<int>
795 //
796 template<>
797 class parser<int> : public basic_parser<int> {
798 public:
799   // parse - Return true on error.
800   bool parse(Option &O, StringRef ArgName, StringRef Arg, int &Val);
801
802   // getValueName - Overload in subclass to provide a better default value.
803   virtual const char *getValueName() const { return "int"; }
804
805   void printOptionDiff(const Option &O, int V, OptVal Default,
806                        size_t GlobalWidth) const;
807
808   // An out-of-line virtual method to provide a 'home' for this class.
809   virtual void anchor();
810 };
811
812 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<int>);
813
814
815 //--------------------------------------------------
816 // parser<unsigned>
817 //
818 template<>
819 class parser<unsigned> : public basic_parser<unsigned> {
820 public:
821   // parse - Return true on error.
822   bool parse(Option &O, StringRef ArgName, StringRef Arg, unsigned &Val);
823
824   // getValueName - Overload in subclass to provide a better default value.
825   virtual const char *getValueName() const { return "uint"; }
826
827   void printOptionDiff(const Option &O, unsigned V, OptVal Default,
828                        size_t GlobalWidth) const;
829
830   // An out-of-line virtual method to provide a 'home' for this class.
831   virtual void anchor();
832 };
833
834 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<unsigned>);
835
836 //--------------------------------------------------
837 // parser<unsigned long long>
838 //
839 template<>
840 class parser<unsigned long long> : public basic_parser<unsigned long long> {
841 public:
842   // parse - Return true on error.
843   bool parse(Option &O, StringRef ArgName, StringRef Arg,
844              unsigned long long &Val);
845
846   // getValueName - Overload in subclass to provide a better default value.
847   virtual const char *getValueName() const { return "uint"; }
848
849   void printOptionDiff(const Option &O, unsigned long long V, OptVal Default,
850                        size_t GlobalWidth) const;
851
852   // An out-of-line virtual method to provide a 'home' for this class.
853   virtual void anchor();
854 };
855
856 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<unsigned long long>);
857
858 //--------------------------------------------------
859 // parser<double>
860 //
861 template<>
862 class parser<double> : public basic_parser<double> {
863 public:
864   // parse - Return true on error.
865   bool parse(Option &O, StringRef ArgName, StringRef Arg, double &Val);
866
867   // getValueName - Overload in subclass to provide a better default value.
868   virtual const char *getValueName() const { return "number"; }
869
870   void printOptionDiff(const Option &O, double V, OptVal Default,
871                        size_t GlobalWidth) const;
872
873   // An out-of-line virtual method to provide a 'home' for this class.
874   virtual void anchor();
875 };
876
877 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<double>);
878
879 //--------------------------------------------------
880 // parser<float>
881 //
882 template<>
883 class parser<float> : public basic_parser<float> {
884 public:
885   // parse - Return true on error.
886   bool parse(Option &O, StringRef ArgName, StringRef Arg, float &Val);
887
888   // getValueName - Overload in subclass to provide a better default value.
889   virtual const char *getValueName() const { return "number"; }
890
891   void printOptionDiff(const Option &O, float V, OptVal Default,
892                        size_t GlobalWidth) const;
893
894   // An out-of-line virtual method to provide a 'home' for this class.
895   virtual void anchor();
896 };
897
898 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<float>);
899
900 //--------------------------------------------------
901 // parser<std::string>
902 //
903 template<>
904 class parser<std::string> : public basic_parser<std::string> {
905 public:
906   // parse - Return true on error.
907   bool parse(Option &, StringRef, StringRef Arg, std::string &Value) {
908     Value = Arg.str();
909     return false;
910   }
911
912   // getValueName - Overload in subclass to provide a better default value.
913   virtual const char *getValueName() const { return "string"; }
914
915   void printOptionDiff(const Option &O, StringRef V, OptVal Default,
916                        size_t GlobalWidth) const;
917
918   // An out-of-line virtual method to provide a 'home' for this class.
919   virtual void anchor();
920 };
921
922 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<std::string>);
923
924 //--------------------------------------------------
925 // parser<char>
926 //
927 template<>
928 class parser<char> : public basic_parser<char> {
929 public:
930   // parse - Return true on error.
931   bool parse(Option &, StringRef, StringRef Arg, char &Value) {
932     Value = Arg[0];
933     return false;
934   }
935
936   // getValueName - Overload in subclass to provide a better default value.
937   virtual const char *getValueName() const { return "char"; }
938
939   void printOptionDiff(const Option &O, char V, OptVal Default,
940                        size_t GlobalWidth) const;
941
942   // An out-of-line virtual method to provide a 'home' for this class.
943   virtual void anchor();
944 };
945
946 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<char>);
947
948 //--------------------------------------------------
949 // PrintOptionDiff
950 //
951 // This collection of wrappers is the intermediary between class opt and class
952 // parser to handle all the template nastiness.
953
954 // This overloaded function is selected by the generic parser.
955 template<class ParserClass, class DT>
956 void printOptionDiff(const Option &O, const generic_parser_base &P, const DT &V,
957                      const OptionValue<DT> &Default, size_t GlobalWidth) {
958   OptionValue<DT> OV = V;
959   P.printOptionDiff(O, OV, Default, GlobalWidth);
960 }
961
962 // This is instantiated for basic parsers when the parsed value has a different
963 // type than the option value. e.g. HelpPrinter.
964 template<class ParserDT, class ValDT>
965 struct OptionDiffPrinter {
966   void print(const Option &O, const parser<ParserDT> P, const ValDT &/*V*/,
967              const OptionValue<ValDT> &/*Default*/, size_t GlobalWidth) {
968     P.printOptionNoValue(O, GlobalWidth);
969   }
970 };
971
972 // This is instantiated for basic parsers when the parsed value has the same
973 // type as the option value.
974 template<class DT>
975 struct OptionDiffPrinter<DT, DT> {
976   void print(const Option &O, const parser<DT> P, const DT &V,
977              const OptionValue<DT> &Default, size_t GlobalWidth) {
978     P.printOptionDiff(O, V, Default, GlobalWidth);
979   }
980 };
981
982 // This overloaded function is selected by the basic parser, which may parse a
983 // different type than the option type.
984 template<class ParserClass, class ValDT>
985 void printOptionDiff(
986   const Option &O,
987   const basic_parser<typename ParserClass::parser_data_type> &P,
988   const ValDT &V, const OptionValue<ValDT> &Default,
989   size_t GlobalWidth) {
990
991   OptionDiffPrinter<typename ParserClass::parser_data_type, ValDT> printer;
992   printer.print(O, static_cast<const ParserClass&>(P), V, Default,
993                 GlobalWidth);
994 }
995
996 //===----------------------------------------------------------------------===//
997 // applicator class - This class is used because we must use partial
998 // specialization to handle literal string arguments specially (const char* does
999 // not correctly respond to the apply method).  Because the syntax to use this
1000 // is a pain, we have the 'apply' method below to handle the nastiness...
1001 //
1002 template<class Mod> struct applicator {
1003   template<class Opt>
1004   static void opt(const Mod &M, Opt &O) { M.apply(O); }
1005 };
1006
1007 // Handle const char* as a special case...
1008 template<unsigned n> struct applicator<char[n]> {
1009   template<class Opt>
1010   static void opt(const char *Str, Opt &O) { O.setArgStr(Str); }
1011 };
1012 template<unsigned n> struct applicator<const char[n]> {
1013   template<class Opt>
1014   static void opt(const char *Str, Opt &O) { O.setArgStr(Str); }
1015 };
1016 template<> struct applicator<const char*> {
1017   template<class Opt>
1018   static void opt(const char *Str, Opt &O) { O.setArgStr(Str); }
1019 };
1020
1021 template<> struct applicator<NumOccurrencesFlag> {
1022   static void opt(NumOccurrencesFlag NO, Option &O) {
1023     O.setNumOccurrencesFlag(NO);
1024   }
1025 };
1026 template<> struct applicator<ValueExpected> {
1027   static void opt(ValueExpected VE, Option &O) { O.setValueExpectedFlag(VE); }
1028 };
1029 template<> struct applicator<OptionHidden> {
1030   static void opt(OptionHidden OH, Option &O) { O.setHiddenFlag(OH); }
1031 };
1032 template<> struct applicator<FormattingFlags> {
1033   static void opt(FormattingFlags FF, Option &O) { O.setFormattingFlag(FF); }
1034 };
1035 template<> struct applicator<MiscFlags> {
1036   static void opt(MiscFlags MF, Option &O) { O.setMiscFlag(MF); }
1037 };
1038
1039 // apply method - Apply a modifier to an option in a type safe way.
1040 template<class Mod, class Opt>
1041 void apply(const Mod &M, Opt *O) {
1042   applicator<Mod>::opt(M, *O);
1043 }
1044
1045 //===----------------------------------------------------------------------===//
1046 // opt_storage class
1047
1048 // Default storage class definition: external storage.  This implementation
1049 // assumes the user will specify a variable to store the data into with the
1050 // cl::location(x) modifier.
1051 //
1052 template<class DataType, bool ExternalStorage, bool isClass>
1053 class opt_storage {
1054   DataType *Location;   // Where to store the object...
1055   OptionValue<DataType> Default;
1056
1057   void check() const {
1058     assert(Location != 0 && "cl::location(...) not specified for a command "
1059            "line option with external storage, "
1060            "or cl::init specified before cl::location()!!");
1061   }
1062 public:
1063   opt_storage() : Location(0) {}
1064
1065   bool setLocation(Option &O, DataType &L) {
1066     if (Location)
1067       return O.error("cl::location(x) specified more than once!");
1068     Location = &L;
1069     Default = L;
1070     return false;
1071   }
1072
1073   template<class T>
1074   void setValue(const T &V, bool initial = false) {
1075     check();
1076     *Location = V;
1077     if (initial)
1078       Default = V;
1079   }
1080
1081   DataType &getValue() { check(); return *Location; }
1082   const DataType &getValue() const { check(); return *Location; }
1083
1084   operator DataType() const { return this->getValue(); }
1085
1086   const OptionValue<DataType> &getDefault() const { return Default; }
1087 };
1088
1089 // Define how to hold a class type object, such as a string.  Since we can
1090 // inherit from a class, we do so.  This makes us exactly compatible with the
1091 // object in all cases that it is used.
1092 //
1093 template<class DataType>
1094 class opt_storage<DataType,false,true> : public DataType {
1095 public:
1096   OptionValue<DataType> Default;
1097
1098   template<class T>
1099   void setValue(const T &V, bool initial = false) {
1100     DataType::operator=(V);
1101     if (initial)
1102       Default = V;
1103   }
1104
1105   DataType &getValue() { return *this; }
1106   const DataType &getValue() const { return *this; }
1107
1108   const OptionValue<DataType> &getDefault() const { return Default; }
1109 };
1110
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.
1114 //
1115 template<class DataType>
1116 class opt_storage<DataType, false, false> {
1117 public:
1118   DataType Value;
1119   OptionValue<DataType> Default;
1120
1121   // Make sure we initialize the value with the default constructor for the
1122   // type.
1123   opt_storage() : Value(DataType()), Default(DataType()) {}
1124
1125   template<class T>
1126   void setValue(const T &V, bool initial = false) {
1127     Value = V;
1128     if (initial)
1129       Default = V;
1130   }
1131   DataType &getValue() { return Value; }
1132   DataType getValue() const { return Value; }
1133
1134   const OptionValue<DataType> &getDefault() const { return Default; }
1135
1136   operator DataType() const { return getValue(); }
1137
1138   // If the datatype is a pointer, support -> on it.
1139   DataType operator->() const { return Value; }
1140 };
1141
1142
1143 //===----------------------------------------------------------------------===//
1144 // opt - A scalar command line option.
1145 //
1146 template <class DataType, bool ExternalStorage = false,
1147           class ParserClass = parser<DataType> >
1148 class opt : public Option,
1149             public opt_storage<DataType, ExternalStorage,
1150                                is_class<DataType>::value> {
1151   ParserClass Parser;
1152
1153   virtual bool handleOccurrence(unsigned pos, StringRef ArgName,
1154                                 StringRef Arg) {
1155     typename ParserClass::parser_data_type Val =
1156        typename ParserClass::parser_data_type();
1157     if (Parser.parse(*this, ArgName, Arg, Val))
1158       return true;                            // Parse error!
1159     this->setValue(Val);
1160     this->setPosition(pos);
1161     return false;
1162   }
1163
1164   virtual enum ValueExpected getValueExpectedFlagDefault() const {
1165     return Parser.getValueExpectedFlagDefault();
1166   }
1167   virtual void getExtraOptionNames(SmallVectorImpl<const char*> &OptionNames) {
1168     return Parser.getExtraOptionNames(OptionNames);
1169   }
1170
1171   // Forward printing stuff to the parser...
1172   virtual size_t getOptionWidth() const {return Parser.getOptionWidth(*this);}
1173   virtual void printOptionInfo(size_t GlobalWidth) const {
1174     Parser.printOptionInfo(*this, GlobalWidth);
1175   }
1176
1177   virtual void printOptionValue(size_t GlobalWidth, bool Force) const {
1178     if (Force || this->getDefault().compare(this->getValue())) {
1179       cl::printOptionDiff<ParserClass>(
1180         *this, Parser, this->getValue(), this->getDefault(), GlobalWidth);
1181     }
1182   }
1183
1184   void done() {
1185     addArgument();
1186     Parser.initialize(*this);
1187   }
1188 public:
1189   // setInitialValue - Used by the cl::init modifier...
1190   void setInitialValue(const DataType &V) { this->setValue(V, true); }
1191
1192   ParserClass &getParser() { return Parser; }
1193
1194   template<class T>
1195   DataType &operator=(const T &Val) {
1196     this->setValue(Val);
1197     return this->getValue();
1198   }
1199
1200   // One option...
1201   template<class M0t>
1202   explicit opt(const M0t &M0) : Option(Optional, NotHidden) {
1203     apply(M0, this);
1204     done();
1205   }
1206
1207   // Two options...
1208   template<class M0t, class M1t>
1209   opt(const M0t &M0, const M1t &M1) : Option(Optional, NotHidden) {
1210     apply(M0, this); apply(M1, this);
1211     done();
1212   }
1213
1214   // Three options...
1215   template<class M0t, class M1t, class M2t>
1216   opt(const M0t &M0, const M1t &M1,
1217       const M2t &M2) : Option(Optional, NotHidden) {
1218     apply(M0, this); apply(M1, this); apply(M2, this);
1219     done();
1220   }
1221   // Four options...
1222   template<class M0t, class M1t, class M2t, class M3t>
1223   opt(const M0t &M0, const M1t &M1, const M2t &M2,
1224       const M3t &M3) : Option(Optional, NotHidden) {
1225     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
1226     done();
1227   }
1228   // Five options...
1229   template<class M0t, class M1t, class M2t, class M3t, class M4t>
1230   opt(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
1231       const M4t &M4) : Option(Optional, NotHidden) {
1232     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
1233     apply(M4, this);
1234     done();
1235   }
1236   // Six options...
1237   template<class M0t, class M1t, class M2t, class M3t,
1238            class M4t, class M5t>
1239   opt(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
1240       const M4t &M4, const M5t &M5) : Option(Optional, NotHidden) {
1241     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
1242     apply(M4, this); apply(M5, this);
1243     done();
1244   }
1245   // Seven options...
1246   template<class M0t, class M1t, class M2t, class M3t,
1247            class M4t, class M5t, class M6t>
1248   opt(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
1249       const M4t &M4, const M5t &M5,
1250       const M6t &M6) : Option(Optional, NotHidden) {
1251     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
1252     apply(M4, this); apply(M5, this); apply(M6, this);
1253     done();
1254   }
1255   // Eight options...
1256   template<class M0t, class M1t, class M2t, class M3t,
1257            class M4t, class M5t, class M6t, class M7t>
1258   opt(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
1259       const M4t &M4, const M5t &M5, const M6t &M6,
1260       const M7t &M7) : Option(Optional, NotHidden) {
1261     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
1262     apply(M4, this); apply(M5, this); apply(M6, this); apply(M7, this);
1263     done();
1264   }
1265 };
1266
1267 EXTERN_TEMPLATE_INSTANTIATION(class opt<unsigned>);
1268 EXTERN_TEMPLATE_INSTANTIATION(class opt<int>);
1269 EXTERN_TEMPLATE_INSTANTIATION(class opt<std::string>);
1270 EXTERN_TEMPLATE_INSTANTIATION(class opt<char>);
1271 EXTERN_TEMPLATE_INSTANTIATION(class opt<bool>);
1272
1273 //===----------------------------------------------------------------------===//
1274 // list_storage class
1275
1276 // Default storage class definition: external storage.  This implementation
1277 // assumes the user will specify a variable to store the data into with the
1278 // cl::location(x) modifier.
1279 //
1280 template<class DataType, class StorageClass>
1281 class list_storage {
1282   StorageClass *Location;   // Where to store the object...
1283
1284 public:
1285   list_storage() : Location(0) {}
1286
1287   bool setLocation(Option &O, StorageClass &L) {
1288     if (Location)
1289       return O.error("cl::location(x) specified more than once!");
1290     Location = &L;
1291     return false;
1292   }
1293
1294   template<class T>
1295   void addValue(const T &V) {
1296     assert(Location != 0 && "cl::location(...) not specified for a command "
1297            "line option with external storage!");
1298     Location->push_back(V);
1299   }
1300 };
1301
1302
1303 // Define how to hold a class type object, such as a string.  Since we can
1304 // inherit from a class, we do so.  This makes us exactly compatible with the
1305 // object in all cases that it is used.
1306 //
1307 template<class DataType>
1308 class list_storage<DataType, bool> : public std::vector<DataType> {
1309 public:
1310   template<class T>
1311   void addValue(const T &V) { std::vector<DataType>::push_back(V); }
1312 };
1313
1314
1315 //===----------------------------------------------------------------------===//
1316 // list - A list of command line options.
1317 //
1318 template <class DataType, class Storage = bool,
1319           class ParserClass = parser<DataType> >
1320 class list : public Option, public list_storage<DataType, Storage> {
1321   std::vector<unsigned> Positions;
1322   ParserClass Parser;
1323
1324   virtual enum ValueExpected getValueExpectedFlagDefault() const {
1325     return Parser.getValueExpectedFlagDefault();
1326   }
1327   virtual void getExtraOptionNames(SmallVectorImpl<const char*> &OptionNames) {
1328     return Parser.getExtraOptionNames(OptionNames);
1329   }
1330
1331   virtual bool handleOccurrence(unsigned pos, StringRef ArgName, StringRef Arg){
1332     typename ParserClass::parser_data_type Val =
1333       typename ParserClass::parser_data_type();
1334     if (Parser.parse(*this, ArgName, Arg, Val))
1335       return true;  // Parse Error!
1336     list_storage<DataType, Storage>::addValue(Val);
1337     setPosition(pos);
1338     Positions.push_back(pos);
1339     return false;
1340   }
1341
1342   // Forward printing stuff to the parser...
1343   virtual size_t getOptionWidth() const {return Parser.getOptionWidth(*this);}
1344   virtual void printOptionInfo(size_t GlobalWidth) const {
1345     Parser.printOptionInfo(*this, GlobalWidth);
1346   }
1347
1348   // Unimplemented: list options don't currently store their default value.
1349   virtual void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const {}
1350
1351   void done() {
1352     addArgument();
1353     Parser.initialize(*this);
1354   }
1355 public:
1356   ParserClass &getParser() { return Parser; }
1357
1358   unsigned getPosition(unsigned optnum) const {
1359     assert(optnum < this->size() && "Invalid option index");
1360     return Positions[optnum];
1361   }
1362
1363   void setNumAdditionalVals(unsigned n) {
1364     Option::setNumAdditionalVals(n);
1365   }
1366
1367   // One option...
1368   template<class M0t>
1369   explicit list(const M0t &M0) : Option(ZeroOrMore, NotHidden) {
1370     apply(M0, this);
1371     done();
1372   }
1373   // Two options...
1374   template<class M0t, class M1t>
1375   list(const M0t &M0, const M1t &M1) : Option(ZeroOrMore, NotHidden) {
1376     apply(M0, this); apply(M1, this);
1377     done();
1378   }
1379   // Three options...
1380   template<class M0t, class M1t, class M2t>
1381   list(const M0t &M0, const M1t &M1, const M2t &M2)
1382     : Option(ZeroOrMore, NotHidden) {
1383     apply(M0, this); apply(M1, this); apply(M2, this);
1384     done();
1385   }
1386   // Four options...
1387   template<class M0t, class M1t, class M2t, class M3t>
1388   list(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3)
1389     : Option(ZeroOrMore, NotHidden) {
1390     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
1391     done();
1392   }
1393   // Five options...
1394   template<class M0t, class M1t, class M2t, class M3t, class M4t>
1395   list(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
1396        const M4t &M4) : Option(ZeroOrMore, NotHidden) {
1397     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
1398     apply(M4, this);
1399     done();
1400   }
1401   // Six options...
1402   template<class M0t, class M1t, class M2t, class M3t,
1403            class M4t, class M5t>
1404   list(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
1405        const M4t &M4, const M5t &M5) : Option(ZeroOrMore, NotHidden) {
1406     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
1407     apply(M4, this); apply(M5, this);
1408     done();
1409   }
1410   // Seven options...
1411   template<class M0t, class M1t, class M2t, class M3t,
1412            class M4t, class M5t, class M6t>
1413   list(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
1414        const M4t &M4, const M5t &M5, const M6t &M6)
1415     : Option(ZeroOrMore, NotHidden) {
1416     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
1417     apply(M4, this); apply(M5, this); apply(M6, this);
1418     done();
1419   }
1420   // Eight options...
1421   template<class M0t, class M1t, class M2t, class M3t,
1422            class M4t, class M5t, class M6t, class M7t>
1423   list(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
1424        const M4t &M4, const M5t &M5, const M6t &M6,
1425        const M7t &M7) : Option(ZeroOrMore, NotHidden) {
1426     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
1427     apply(M4, this); apply(M5, this); apply(M6, this); apply(M7, this);
1428     done();
1429   }
1430 };
1431
1432 // multi_val - Modifier to set the number of additional values.
1433 struct multi_val {
1434   unsigned AdditionalVals;
1435   explicit multi_val(unsigned N) : AdditionalVals(N) {}
1436
1437   template <typename D, typename S, typename P>
1438   void apply(list<D, S, P> &L) const { L.setNumAdditionalVals(AdditionalVals); }
1439 };
1440
1441
1442 //===----------------------------------------------------------------------===//
1443 // bits_storage class
1444
1445 // Default storage class definition: external storage.  This implementation
1446 // assumes the user will specify a variable to store the data into with the
1447 // cl::location(x) modifier.
1448 //
1449 template<class DataType, class StorageClass>
1450 class bits_storage {
1451   unsigned *Location;   // Where to store the bits...
1452
1453   template<class T>
1454   static unsigned Bit(const T &V) {
1455     unsigned BitPos = reinterpret_cast<unsigned>(V);
1456     assert(BitPos < sizeof(unsigned) * CHAR_BIT &&
1457           "enum exceeds width of bit vector!");
1458     return 1 << BitPos;
1459   }
1460
1461 public:
1462   bits_storage() : Location(0) {}
1463
1464   bool setLocation(Option &O, unsigned &L) {
1465     if (Location)
1466       return O.error("cl::location(x) specified more than once!");
1467     Location = &L;
1468     return false;
1469   }
1470
1471   template<class T>
1472   void addValue(const T &V) {
1473     assert(Location != 0 && "cl::location(...) not specified for a command "
1474            "line option with external storage!");
1475     *Location |= Bit(V);
1476   }
1477
1478   unsigned getBits() { return *Location; }
1479
1480   template<class T>
1481   bool isSet(const T &V) {
1482     return (*Location & Bit(V)) != 0;
1483   }
1484 };
1485
1486
1487 // Define how to hold bits.  Since we can inherit from a class, we do so.
1488 // This makes us exactly compatible with the bits in all cases that it is used.
1489 //
1490 template<class DataType>
1491 class bits_storage<DataType, bool> {
1492   unsigned Bits;   // Where to store the bits...
1493
1494   template<class T>
1495   static unsigned Bit(const T &V) {
1496     unsigned BitPos = (unsigned)V;
1497     assert(BitPos < sizeof(unsigned) * CHAR_BIT &&
1498           "enum exceeds width of bit vector!");
1499     return 1 << BitPos;
1500   }
1501
1502 public:
1503   template<class T>
1504   void addValue(const T &V) {
1505     Bits |=  Bit(V);
1506   }
1507
1508   unsigned getBits() { return Bits; }
1509
1510   template<class T>
1511   bool isSet(const T &V) {
1512     return (Bits & Bit(V)) != 0;
1513   }
1514 };
1515
1516
1517 //===----------------------------------------------------------------------===//
1518 // bits - A bit vector of command options.
1519 //
1520 template <class DataType, class Storage = bool,
1521           class ParserClass = parser<DataType> >
1522 class bits : public Option, public bits_storage<DataType, Storage> {
1523   std::vector<unsigned> Positions;
1524   ParserClass Parser;
1525
1526   virtual enum ValueExpected getValueExpectedFlagDefault() const {
1527     return Parser.getValueExpectedFlagDefault();
1528   }
1529   virtual void getExtraOptionNames(SmallVectorImpl<const char*> &OptionNames) {
1530     return Parser.getExtraOptionNames(OptionNames);
1531   }
1532
1533   virtual bool handleOccurrence(unsigned pos, StringRef ArgName, StringRef Arg){
1534     typename ParserClass::parser_data_type Val =
1535       typename ParserClass::parser_data_type();
1536     if (Parser.parse(*this, ArgName, Arg, Val))
1537       return true;  // Parse Error!
1538     this->addValue(Val);
1539     setPosition(pos);
1540     Positions.push_back(pos);
1541     return false;
1542   }
1543
1544   // Forward printing stuff to the parser...
1545   virtual size_t getOptionWidth() const {return Parser.getOptionWidth(*this);}
1546   virtual void printOptionInfo(size_t GlobalWidth) const {
1547     Parser.printOptionInfo(*this, GlobalWidth);
1548   }
1549
1550   // Unimplemented: bits options don't currently store their default values.
1551   virtual void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const {}
1552
1553   void done() {
1554     addArgument();
1555     Parser.initialize(*this);
1556   }
1557 public:
1558   ParserClass &getParser() { return Parser; }
1559
1560   unsigned getPosition(unsigned optnum) const {
1561     assert(optnum < this->size() && "Invalid option index");
1562     return Positions[optnum];
1563   }
1564
1565   // One option...
1566   template<class M0t>
1567   explicit bits(const M0t &M0) : Option(ZeroOrMore, NotHidden) {
1568     apply(M0, this);
1569     done();
1570   }
1571   // Two options...
1572   template<class M0t, class M1t>
1573   bits(const M0t &M0, const M1t &M1) : Option(ZeroOrMore, NotHidden) {
1574     apply(M0, this); apply(M1, this);
1575     done();
1576   }
1577   // Three options...
1578   template<class M0t, class M1t, class M2t>
1579   bits(const M0t &M0, const M1t &M1, const M2t &M2)
1580     : Option(ZeroOrMore, NotHidden) {
1581     apply(M0, this); apply(M1, this); apply(M2, this);
1582     done();
1583   }
1584   // Four options...
1585   template<class M0t, class M1t, class M2t, class M3t>
1586   bits(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3)
1587     : Option(ZeroOrMore, NotHidden) {
1588     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
1589     done();
1590   }
1591   // Five options...
1592   template<class M0t, class M1t, class M2t, class M3t, class M4t>
1593   bits(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
1594        const M4t &M4) : Option(ZeroOrMore, NotHidden) {
1595     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
1596     apply(M4, this);
1597     done();
1598   }
1599   // Six options...
1600   template<class M0t, class M1t, class M2t, class M3t,
1601            class M4t, class M5t>
1602   bits(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
1603        const M4t &M4, const M5t &M5) : Option(ZeroOrMore, NotHidden) {
1604     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
1605     apply(M4, this); apply(M5, this);
1606     done();
1607   }
1608   // Seven options...
1609   template<class M0t, class M1t, class M2t, class M3t,
1610            class M4t, class M5t, class M6t>
1611   bits(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
1612        const M4t &M4, const M5t &M5, const M6t &M6)
1613     : Option(ZeroOrMore, NotHidden) {
1614     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
1615     apply(M4, this); apply(M5, this); apply(M6, this);
1616     done();
1617   }
1618   // Eight options...
1619   template<class M0t, class M1t, class M2t, class M3t,
1620            class M4t, class M5t, class M6t, class M7t>
1621   bits(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
1622        const M4t &M4, const M5t &M5, const M6t &M6,
1623        const M7t &M7) : Option(ZeroOrMore, NotHidden) {
1624     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
1625     apply(M4, this); apply(M5, this); apply(M6, this); apply(M7, this);
1626     done();
1627   }
1628 };
1629
1630 //===----------------------------------------------------------------------===//
1631 // Aliased command line option (alias this name to a preexisting name)
1632 //
1633
1634 class alias : public Option {
1635   Option *AliasFor;
1636   virtual bool handleOccurrence(unsigned pos, StringRef /*ArgName*/,
1637                                 StringRef Arg) LLVM_OVERRIDE {
1638     return AliasFor->handleOccurrence(pos, AliasFor->ArgStr, Arg);
1639   }
1640   // Handle printing stuff...
1641   virtual size_t getOptionWidth() const LLVM_OVERRIDE;
1642   virtual void printOptionInfo(size_t GlobalWidth) const LLVM_OVERRIDE;
1643
1644   // Aliases do not need to print their values.
1645   virtual void printOptionValue(size_t /*GlobalWidth*/,
1646                                 bool /*Force*/) const LLVM_OVERRIDE {}
1647
1648   void done() {
1649     if (!hasArgStr())
1650       error("cl::alias must have argument name specified!");
1651     if (AliasFor == 0)
1652       error("cl::alias must have an cl::aliasopt(option) specified!");
1653       addArgument();
1654   }
1655 public:
1656   void setAliasFor(Option &O) {
1657     if (AliasFor)
1658       error("cl::alias must only have one cl::aliasopt(...) specified!");
1659     AliasFor = &O;
1660   }
1661
1662   // One option...
1663   template<class M0t>
1664   explicit alias(const M0t &M0) : Option(Optional, Hidden), AliasFor(0) {
1665     apply(M0, this);
1666     done();
1667   }
1668   // Two options...
1669   template<class M0t, class M1t>
1670   alias(const M0t &M0, const M1t &M1) : Option(Optional, Hidden), AliasFor(0) {
1671     apply(M0, this); apply(M1, this);
1672     done();
1673   }
1674   // Three options...
1675   template<class M0t, class M1t, class M2t>
1676   alias(const M0t &M0, const M1t &M1, const M2t &M2)
1677     : Option(Optional, Hidden), AliasFor(0) {
1678     apply(M0, this); apply(M1, this); apply(M2, this);
1679     done();
1680   }
1681   // Four options...
1682   template<class M0t, class M1t, class M2t, class M3t>
1683   alias(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3)
1684     : Option(Optional, Hidden), AliasFor(0) {
1685     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
1686     done();
1687   }
1688 };
1689
1690 // aliasfor - Modifier to set the option an alias aliases.
1691 struct aliasopt {
1692   Option &Opt;
1693   explicit aliasopt(Option &O) : Opt(O) {}
1694   void apply(alias &A) const { A.setAliasFor(Opt); }
1695 };
1696
1697 // extrahelp - provide additional help at the end of the normal help
1698 // output. All occurrences of cl::extrahelp will be accumulated and
1699 // printed to stderr at the end of the regular help, just before
1700 // exit is called.
1701 struct extrahelp {
1702   const char * morehelp;
1703   explicit extrahelp(const char* help);
1704 };
1705
1706 void PrintVersionMessage();
1707
1708 /// This function just prints the help message, exactly the same way as if the
1709 /// -help or -help-hidden option had been given on the command line.
1710 ///
1711 /// NOTE: THIS FUNCTION TERMINATES THE PROGRAM!
1712 ///
1713 /// \param hidden if true will print hidden options
1714 /// \param categorized if true print options in categories
1715 void PrintHelpMessage(bool Hidden=false, bool Categorized=false);
1716
1717
1718 //===----------------------------------------------------------------------===//
1719 // Public interface for accessing registered options.
1720 //
1721
1722 /// \brief Use this to get a StringMap to all registered named options
1723 /// (e.g. -help). Note \p Map Should be an empty StringMap.
1724 ///
1725 /// \param [out] map will be filled with mappings where the key is the
1726 /// Option argument string (e.g. "help") and value is the corresponding
1727 /// Option*.
1728 ///
1729 /// Access to unnamed arguments (i.e. positional) are not provided because
1730 /// it is expected that the client already has access to these.
1731 ///
1732 /// Typical usage:
1733 /// \code
1734 /// main(int argc,char* argv[]) {
1735 /// StringMap<llvm::cl::Option*> opts;
1736 /// llvm::cl::getRegisteredOptions(opts);
1737 /// assert(opts.count("help") == 1)
1738 /// opts["help"]->setDescription("Show alphabetical help information")
1739 /// // More code
1740 /// llvm::cl::ParseCommandLineOptions(argc,argv);
1741 /// //More code
1742 /// }
1743 /// \endcode
1744 ///
1745 /// This interface is useful for modifying options in libraries that are out of
1746 /// the control of the client. The options should be modified before calling
1747 /// llvm::cl::ParseCommandLineOptions().
1748 void getRegisteredOptions(StringMap<Option*> &Map);
1749
1750 } // End namespace cl
1751
1752 } // End namespace llvm
1753
1754 #endif