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