Switch some vectors to smallvectors. This reduces amount of malloc'd
[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 was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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/DataTypes.h"
25 #include "llvm/Support/Compiler.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include <string>
28 #include <vector>
29 #include <utility>
30 #include <cstdarg>
31 #include <cassert>
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, char **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 gives other systems using the
57 ///                     CommandLine utilities to print their own version string.
58 void SetVersionPrinter(void (*func)());
59
60 //===----------------------------------------------------------------------===//
61 // Flags permitted to be passed to command line arguments
62 //
63
64 enum NumOccurrences {          // Flags for the number of occurrences allowed
65   Optional        = 0x01,      // Zero or One occurrence
66   ZeroOrMore      = 0x02,      // Zero or more occurrences allowed
67   Required        = 0x03,      // One occurrence required
68   OneOrMore       = 0x04,      // One or more occurrences required
69
70   // ConsumeAfter - Indicates that this option is fed anything that follows the
71   // last positional argument required by the application (it is an error if
72   // there are zero positional arguments, and a ConsumeAfter option is used).
73   // Thus, for example, all arguments to LLI are processed until a filename is
74   // found.  Once a filename is found, all of the succeeding arguments are
75   // passed, unprocessed, to the ConsumeAfter option.
76   //
77   ConsumeAfter    = 0x05,
78
79   OccurrencesMask  = 0x07
80 };
81
82 enum ValueExpected {           // Is a value required for the option?
83   ValueOptional   = 0x08,      // The value can appear... or not
84   ValueRequired   = 0x10,      // The value is required to appear!
85   ValueDisallowed = 0x18,      // A value may not be specified (for flags)
86   ValueMask       = 0x18
87 };
88
89 enum OptionHidden {            // Control whether -help shows this option
90   NotHidden       = 0x20,      // Option included in --help & --help-hidden
91   Hidden          = 0x40,      // -help doesn't, but --help-hidden does
92   ReallyHidden    = 0x60,      // Neither --help nor --help-hidden show this arg
93   HiddenMask      = 0x60
94 };
95
96 // Formatting flags - This controls special features that the option might have
97 // that cause it to be parsed differently...
98 //
99 // Prefix - This option allows arguments that are otherwise unrecognized to be
100 // matched by options that are a prefix of the actual value.  This is useful for
101 // cases like a linker, where options are typically of the form '-lfoo' or
102 // '-L../../include' where -l or -L are the actual flags.  When prefix is
103 // enabled, and used, the value for the flag comes from the suffix of the
104 // argument.
105 //
106 // Grouping - With this option enabled, multiple letter options are allowed to
107 // bunch together with only a single hyphen for the whole group.  This allows
108 // emulation of the behavior that ls uses for example: ls -la === ls -l -a
109 //
110
111 enum FormattingFlags {
112   NormalFormatting = 0x000,     // Nothing special
113   Positional       = 0x080,     // Is a positional argument, no '-' required
114   Prefix           = 0x100,     // Can this option directly prefix its value?
115   Grouping         = 0x180,     // Can this option group with other options?
116   FormattingMask   = 0x180      // Union of the above flags.
117 };
118
119 enum MiscFlags {               // Miscellaneous flags to adjust argument
120   CommaSeparated     = 0x200,  // Should this cl::list split between commas?
121   PositionalEatsArgs = 0x400,  // Should this positional cl::list eat -args?
122   MiscMask           = 0x600   // Union of the above flags.
123 };
124
125
126
127 //===----------------------------------------------------------------------===//
128 // Option Base class
129 //
130 class alias;
131 class Option {
132   friend void cl::ParseCommandLineOptions(int &, char **, const char *);
133   friend class alias;
134
135   // handleOccurrences - Overriden by subclasses to handle the value passed into
136   // an argument.  Should return true if there was an error processing the
137   // argument and the program should exit.
138   //
139   virtual bool handleOccurrence(unsigned pos, const char *ArgName,
140                                 const std::string &Arg) = 0;
141
142   virtual enum ValueExpected getValueExpectedFlagDefault() const {
143     return ValueOptional;
144   }
145   // Out of line virtual function to provide home for the class.
146   virtual void anchor();
147   
148   int NumOccurrences;   // The number of times specified
149   int Flags;            // Flags for the argument
150   unsigned Position;    // Position of last occurrence of the option
151 public:
152   const char *ArgStr;   // The argument string itself (ex: "help", "o")
153   const char *HelpStr;  // The descriptive text message for --help
154   const char *ValueStr; // String describing what the value of this option is
155
156   inline enum NumOccurrences getNumOccurrencesFlag() const {
157     return static_cast<enum NumOccurrences>(Flags & OccurrencesMask);
158   }
159   inline enum ValueExpected getValueExpectedFlag() const {
160     int VE = Flags & ValueMask;
161     return VE ? static_cast<enum ValueExpected>(VE)
162               : getValueExpectedFlagDefault();
163   }
164   inline enum OptionHidden getOptionHiddenFlag() const {
165     return static_cast<enum OptionHidden>(Flags & HiddenMask);
166   }
167   inline enum FormattingFlags getFormattingFlag() const {
168     return static_cast<enum FormattingFlags>(Flags & FormattingMask);
169   }
170   inline unsigned getMiscFlags() const {
171     return Flags & MiscMask;
172   }
173   inline unsigned getPosition() const { return Position; }
174
175   // hasArgStr - Return true if the argstr != ""
176   bool hasArgStr() const { return ArgStr[0] != 0; }
177
178   //-------------------------------------------------------------------------===
179   // Accessor functions set by OptionModifiers
180   //
181   void setArgStr(const char *S) { ArgStr = S; }
182   void setDescription(const char *S) { HelpStr = S; }
183   void setValueStr(const char *S) { ValueStr = S; }
184
185   void setFlag(unsigned Flag, unsigned FlagMask) {
186     Flags &= ~FlagMask;
187     Flags |= Flag;
188   }
189
190   void setNumOccurrencesFlag(enum NumOccurrences Val) {
191     setFlag(Val, OccurrencesMask);
192   }
193   void setValueExpectedFlag(enum ValueExpected Val) { setFlag(Val, ValueMask); }
194   void setHiddenFlag(enum OptionHidden Val) { setFlag(Val, HiddenMask); }
195   void setFormattingFlag(enum FormattingFlags V) { setFlag(V, FormattingMask); }
196   void setMiscFlag(enum MiscFlags M) { setFlag(M, M); }
197   void setPosition(unsigned pos) { Position = pos; }
198 protected:
199   Option(unsigned DefaultFlags)
200     : NumOccurrences(0), Flags(DefaultFlags | NormalFormatting), Position(0),
201       ArgStr(""), HelpStr(""), ValueStr("") {
202     assert(getNumOccurrencesFlag() != 0 &&
203            getOptionHiddenFlag() != 0 && "Not all default flags specified!");
204   }
205
206 public:
207   // addArgument - Tell the system that this Option subclass will handle all
208   // occurrences of -ArgStr on the command line.
209   //
210   void addArgument(const char *ArgStr);
211
212   // Return the width of the option tag for printing...
213   virtual unsigned getOptionWidth() const = 0;
214
215   // printOptionInfo - Print out information about this option.  The
216   // to-be-maintained width is specified.
217   //
218   virtual void printOptionInfo(unsigned GlobalWidth) const = 0;
219
220   // addOccurrence - Wrapper around handleOccurrence that enforces Flags
221   //
222   bool addOccurrence(unsigned pos, const char *ArgName,
223                      const std::string &Value);
224
225   // Prints option name followed by message.  Always returns true.
226   bool error(std::string Message, const char *ArgName = 0);
227
228 public:
229   inline int getNumOccurrences() const { return NumOccurrences; }
230   virtual ~Option() {}
231 };
232
233
234 //===----------------------------------------------------------------------===//
235 // Command line option modifiers that can be used to modify the behavior of
236 // command line option parsers...
237 //
238
239 // desc - Modifier to set the description shown in the --help output...
240 struct desc {
241   const char *Desc;
242   desc(const char *Str) : Desc(Str) {}
243   void apply(Option &O) const { O.setDescription(Desc); }
244 };
245
246 // value_desc - Modifier to set the value description shown in the --help
247 // output...
248 struct value_desc {
249   const char *Desc;
250   value_desc(const char *Str) : Desc(Str) {}
251   void apply(Option &O) const { O.setValueStr(Desc); }
252 };
253
254 // init - Specify a default (initial) value for the command line argument, if
255 // the default constructor for the argument type does not give you what you
256 // want.  This is only valid on "opt" arguments, not on "list" arguments.
257 //
258 template<class Ty>
259 struct initializer {
260   const Ty &Init;
261   initializer(const Ty &Val) : Init(Val) {}
262
263   template<class Opt>
264   void apply(Opt &O) const { O.setInitialValue(Init); }
265 };
266
267 template<class Ty>
268 initializer<Ty> init(const Ty &Val) {
269   return initializer<Ty>(Val);
270 }
271
272
273 // location - Allow the user to specify which external variable they want to
274 // store the results of the command line argument processing into, if they don't
275 // want to store it in the option itself.
276 //
277 template<class Ty>
278 struct LocationClass {
279   Ty &Loc;
280   LocationClass(Ty &L) : Loc(L) {}
281
282   template<class Opt>
283   void apply(Opt &O) const { O.setLocation(O, Loc); }
284 };
285
286 template<class Ty>
287 LocationClass<Ty> location(Ty &L) { return LocationClass<Ty>(L); }
288
289
290 //===----------------------------------------------------------------------===//
291 // Enum valued command line option
292 //
293 #define clEnumVal(ENUMVAL, DESC) #ENUMVAL, int(ENUMVAL), DESC
294 #define clEnumValN(ENUMVAL, FLAGNAME, DESC) FLAGNAME, int(ENUMVAL), DESC
295 #define clEnumValEnd (reinterpret_cast<void*>(0))
296
297 // values - For custom data types, allow specifying a group of values together
298 // as the values that go into the mapping that the option handler uses.  Note
299 // that the values list must always have a 0 at the end of the list to indicate
300 // that the list has ended.
301 //
302 template<class DataType>
303 class ValuesClass {
304   // Use a vector instead of a map, because the lists should be short,
305   // the overhead is less, and most importantly, it keeps them in the order
306   // inserted so we can print our option out nicely.
307   SmallVector<std::pair<const char *, std::pair<int, const char *> >,4> Values;
308   void processValues(va_list Vals);
309 public:
310   ValuesClass(const char *EnumName, DataType Val, const char *Desc,
311               va_list ValueArgs) {
312     // Insert the first value, which is required.
313     Values.push_back(std::make_pair(EnumName, std::make_pair(Val, Desc)));
314
315     // Process the varargs portion of the values...
316     while (const char *EnumName = va_arg(ValueArgs, const char *)) {
317       DataType EnumVal = static_cast<DataType>(va_arg(ValueArgs, int));
318       const char *EnumDesc = va_arg(ValueArgs, const char *);
319       Values.push_back(std::make_pair(EnumName,      // Add value to value map
320                                       std::make_pair(EnumVal, EnumDesc)));
321     }
322   }
323
324   template<class Opt>
325   void apply(Opt &O) const {
326     for (unsigned i = 0, e = Values.size(); i != e; ++i)
327       O.getParser().addLiteralOption(Values[i].first, Values[i].second.first,
328                                      Values[i].second.second);
329   }
330 };
331
332 template<class DataType>
333 ValuesClass<DataType> END_WITH_NULL values(const char *Arg, DataType Val, 
334                                            const char *Desc, ...) {
335     va_list ValueArgs;
336     va_start(ValueArgs, Desc);
337     ValuesClass<DataType> Vals(Arg, Val, Desc, ValueArgs);
338     va_end(ValueArgs);
339     return Vals;
340 }
341
342
343 //===----------------------------------------------------------------------===//
344 // parser class - Parameterizable parser for different data types.  By default,
345 // known data types (string, int, bool) have specialized parsers, that do what
346 // you would expect.  The default parser, used for data types that are not
347 // built-in, uses a mapping table to map specific options to values, which is
348 // used, among other things, to handle enum types.
349
350 //--------------------------------------------------
351 // generic_parser_base - This class holds all the non-generic code that we do
352 // not need replicated for every instance of the generic parser.  This also
353 // allows us to put stuff into CommandLine.cpp
354 //
355 struct generic_parser_base {
356   virtual ~generic_parser_base() {}  // Base class should have virtual-dtor
357
358   // getNumOptions - Virtual function implemented by generic subclass to
359   // indicate how many entries are in Values.
360   //
361   virtual unsigned getNumOptions() const = 0;
362
363   // getOption - Return option name N.
364   virtual const char *getOption(unsigned N) const = 0;
365
366   // getDescription - Return description N
367   virtual const char *getDescription(unsigned N) const = 0;
368
369   // Return the width of the option tag for printing...
370   virtual unsigned getOptionWidth(const Option &O) const;
371
372   // printOptionInfo - Print out information about this option.  The
373   // to-be-maintained width is specified.
374   //
375   virtual void printOptionInfo(const Option &O, unsigned GlobalWidth) const;
376
377   void initialize(Option &O) {
378     // All of the modifiers for the option have been processed by now, so the
379     // argstr field should be stable, copy it down now.
380     //
381     hasArgStr = O.hasArgStr();
382
383     // If there has been no argstr specified, that means that we need to add an
384     // argument for every possible option.  This ensures that our options are
385     // vectored to us.
386     //
387     if (!hasArgStr)
388       for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
389         O.addArgument(getOption(i));
390   }
391
392   enum ValueExpected getValueExpectedFlagDefault() const {
393     // If there is an ArgStr specified, then we are of the form:
394     //
395     //    -opt=O2   or   -opt O2  or  -optO2
396     //
397     // In which case, the value is required.  Otherwise if an arg str has not
398     // been specified, we are of the form:
399     //
400     //    -O2 or O2 or -la (where -l and -a are separate options)
401     //
402     // If this is the case, we cannot allow a value.
403     //
404     if (hasArgStr)
405       return ValueRequired;
406     else
407       return ValueDisallowed;
408   }
409
410   // findOption - Return the option number corresponding to the specified
411   // argument string.  If the option is not found, getNumOptions() is returned.
412   //
413   unsigned findOption(const char *Name);
414
415 protected:
416   bool hasArgStr;
417 };
418
419 // Default parser implementation - This implementation depends on having a
420 // mapping of recognized options to values of some sort.  In addition to this,
421 // each entry in the mapping also tracks a help message that is printed with the
422 // command line option for --help.  Because this is a simple mapping parser, the
423 // data type can be any unsupported type.
424 //
425 template <class DataType>
426 class parser : public generic_parser_base {
427 protected:
428   SmallVector<std::pair<const char *,
429                         std::pair<DataType, const char *> >, 8> Values;
430 public:
431   typedef DataType parser_data_type;
432
433   // Implement virtual functions needed by generic_parser_base
434   unsigned getNumOptions() const { return unsigned(Values.size()); }
435   const char *getOption(unsigned N) const { return Values[N].first; }
436   const char *getDescription(unsigned N) const {
437     return Values[N].second.second;
438   }
439
440   // parse - Return true on error.
441   bool parse(Option &O, const char *ArgName, const std::string &Arg,
442              DataType &V) {
443     std::string ArgVal;
444     if (hasArgStr)
445       ArgVal = Arg;
446     else
447       ArgVal = ArgName;
448
449     for (unsigned i = 0, e = Values.size(); i != e; ++i)
450       if (ArgVal == Values[i].first) {
451         V = Values[i].second.first;
452         return false;
453       }
454
455     return O.error(": Cannot find option named '" + ArgVal + "'!");
456   }
457
458   /// addLiteralOption - Add an entry to the mapping table.
459   ///
460   template <class DT>
461   void addLiteralOption(const char *Name, const DT &V, const char *HelpStr) {
462     assert(findOption(Name) == Values.size() && "Option already exists!");
463     Values.push_back(std::make_pair(Name,
464                              std::make_pair(static_cast<DataType>(V),HelpStr)));
465   }
466
467   /// removeLiteralOption - Remove the specified option.
468   ///
469   void removeLiteralOption(const char *Name) {
470     unsigned N = findOption(Name);
471     assert(N != Values.size() && "Option not found!");
472     Values.erase(Values.begin()+N);
473   }
474 };
475
476 //--------------------------------------------------
477 // basic_parser - Super class of parsers to provide boilerplate code
478 //
479 struct basic_parser_impl {  // non-template implementation of basic_parser<t>
480   virtual ~basic_parser_impl() {}
481
482   enum ValueExpected getValueExpectedFlagDefault() const {
483     return ValueRequired;
484   }
485
486   void initialize(Option &O) {}
487
488   // Return the width of the option tag for printing...
489   unsigned getOptionWidth(const Option &O) const;
490
491   // printOptionInfo - Print out information about this option.  The
492   // to-be-maintained width is specified.
493   //
494   void printOptionInfo(const Option &O, unsigned GlobalWidth) const;
495
496   // getValueName - Overload in subclass to provide a better default value.
497   virtual const char *getValueName() const { return "value"; }
498
499   // An out-of-line virtual method to provide a 'home' for this class.
500   virtual void anchor();
501 };
502
503 // basic_parser - The real basic parser is just a template wrapper that provides
504 // a typedef for the provided data type.
505 //
506 template<class DataType>
507 struct basic_parser : public basic_parser_impl {
508   typedef DataType parser_data_type;
509 };
510
511 //--------------------------------------------------
512 // parser<bool>
513 //
514 template<>
515 class parser<bool> : public basic_parser<bool> {
516 public:
517   // parse - Return true on error.
518   bool parse(Option &O, const char *ArgName, const std::string &Arg, bool &Val);
519
520   enum ValueExpected getValueExpectedFlagDefault() const {
521     return ValueOptional;
522   }
523
524   // getValueName - Do not print =<value> at all.
525   virtual const char *getValueName() const { return 0; }
526   
527   // An out-of-line virtual method to provide a 'home' for this class.
528   virtual void anchor();
529 };
530
531 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<bool>);
532
533
534 //--------------------------------------------------
535 // parser<int>
536 //
537 template<>
538 class parser<int> : public basic_parser<int> {
539 public:
540   // parse - Return true on error.
541   bool parse(Option &O, const char *ArgName, const std::string &Arg, int &Val);
542
543   // getValueName - Overload in subclass to provide a better default value.
544   virtual const char *getValueName() const { return "int"; }
545
546   // An out-of-line virtual method to provide a 'home' for this class.
547   virtual void anchor();
548 };
549
550 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<int>);
551
552
553 //--------------------------------------------------
554 // parser<unsigned>
555 //
556 template<>
557 class parser<unsigned> : public basic_parser<unsigned> {
558 public:
559   // parse - Return true on error.
560   bool parse(Option &O, const char *AN, const std::string &Arg, unsigned &Val);
561
562   // getValueName - Overload in subclass to provide a better default value.
563   virtual const char *getValueName() const { return "uint"; }
564
565   // An out-of-line virtual method to provide a 'home' for this class.
566   virtual void anchor();
567 };
568
569 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<unsigned>);
570
571 //--------------------------------------------------
572 // parser<double>
573 //
574 template<>
575 class parser<double> : public basic_parser<double> {
576 public:
577   // parse - Return true on error.
578   bool parse(Option &O, const char *AN, const std::string &Arg, double &Val);
579
580   // getValueName - Overload in subclass to provide a better default value.
581   virtual const char *getValueName() const { return "number"; }
582
583   // An out-of-line virtual method to provide a 'home' for this class.
584   virtual void anchor();
585 };
586
587 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<double>);
588
589 //--------------------------------------------------
590 // parser<float>
591 //
592 template<>
593 class parser<float> : public basic_parser<float> {
594 public:
595   // parse - Return true on error.
596   bool parse(Option &O, const char *AN, const std::string &Arg, float &Val);
597
598   // getValueName - Overload in subclass to provide a better default value.
599   virtual const char *getValueName() const { return "number"; }
600
601   // An out-of-line virtual method to provide a 'home' for this class.
602   virtual void anchor();
603 };
604
605 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<float>);
606
607 //--------------------------------------------------
608 // parser<std::string>
609 //
610 template<>
611 class parser<std::string> : public basic_parser<std::string> {
612 public:
613   // parse - Return true on error.
614   bool parse(Option &O, const char *AN, const std::string &Arg,
615              std::string &Value) {
616     Value = Arg;
617     return false;
618   }
619
620   // getValueName - Overload in subclass to provide a better default value.
621   virtual const char *getValueName() const { return "string"; }
622
623   // An out-of-line virtual method to provide a 'home' for this class.
624   virtual void anchor();
625 };
626
627 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<std::string>);
628
629 //===----------------------------------------------------------------------===//
630 // applicator class - This class is used because we must use partial
631 // specialization to handle literal string arguments specially (const char* does
632 // not correctly respond to the apply method).  Because the syntax to use this
633 // is a pain, we have the 'apply' method below to handle the nastiness...
634 //
635 template<class Mod> struct applicator {
636   template<class Opt>
637   static void opt(const Mod &M, Opt &O) { M.apply(O); }
638 };
639
640 // Handle const char* as a special case...
641 template<unsigned n> struct applicator<char[n]> {
642   template<class Opt>
643   static void opt(const char *Str, Opt &O) { O.setArgStr(Str); }
644 };
645 template<unsigned n> struct applicator<const char[n]> {
646   template<class Opt>
647   static void opt(const char *Str, Opt &O) { O.setArgStr(Str); }
648 };
649 template<> struct applicator<const char*> {
650   template<class Opt>
651   static void opt(const char *Str, Opt &O) { O.setArgStr(Str); }
652 };
653
654 template<> struct applicator<NumOccurrences> {
655   static void opt(NumOccurrences NO, Option &O) { O.setNumOccurrencesFlag(NO); }
656 };
657 template<> struct applicator<ValueExpected> {
658   static void opt(ValueExpected VE, Option &O) { O.setValueExpectedFlag(VE); }
659 };
660 template<> struct applicator<OptionHidden> {
661   static void opt(OptionHidden OH, Option &O) { O.setHiddenFlag(OH); }
662 };
663 template<> struct applicator<FormattingFlags> {
664   static void opt(FormattingFlags FF, Option &O) { O.setFormattingFlag(FF); }
665 };
666 template<> struct applicator<MiscFlags> {
667   static void opt(MiscFlags MF, Option &O) { O.setMiscFlag(MF); }
668 };
669
670 // apply method - Apply a modifier to an option in a type safe way.
671 template<class Mod, class Opt>
672 void apply(const Mod &M, Opt *O) {
673   applicator<Mod>::opt(M, *O);
674 }
675
676
677 //===----------------------------------------------------------------------===//
678 // opt_storage class
679
680 // Default storage class definition: external storage.  This implementation
681 // assumes the user will specify a variable to store the data into with the
682 // cl::location(x) modifier.
683 //
684 template<class DataType, bool ExternalStorage, bool isClass>
685 class opt_storage {
686   DataType *Location;   // Where to store the object...
687
688   void check() {
689     assert(Location != 0 && "cl::location(...) not specified for a command "
690            "line option with external storage, "
691            "or cl::init specified before cl::location()!!");
692   }
693 public:
694   opt_storage() : Location(0) {}
695
696   bool setLocation(Option &O, DataType &L) {
697     if (Location)
698       return O.error(": cl::location(x) specified more than once!");
699     Location = &L;
700     return false;
701   }
702
703   template<class T>
704   void setValue(const T &V) {
705     check();
706     *Location = V;
707   }
708
709   DataType &getValue() { check(); return *Location; }
710   const DataType &getValue() const { check(); return *Location; }
711 };
712
713
714 // Define how to hold a class type object, such as a string.  Since we can
715 // inherit from a class, we do so.  This makes us exactly compatible with the
716 // object in all cases that it is used.
717 //
718 template<class DataType>
719 class opt_storage<DataType,false,true> : public DataType {
720 public:
721   template<class T>
722   void setValue(const T &V) { DataType::operator=(V); }
723
724   DataType &getValue() { return *this; }
725   const DataType &getValue() const { return *this; }
726 };
727
728 // Define a partial specialization to handle things we cannot inherit from.  In
729 // this case, we store an instance through containment, and overload operators
730 // to get at the value.
731 //
732 template<class DataType>
733 class opt_storage<DataType, false, false> {
734 public:
735   DataType Value;
736
737   // Make sure we initialize the value with the default constructor for the
738   // type.
739   opt_storage() : Value(DataType()) {}
740
741   template<class T>
742   void setValue(const T &V) { Value = V; }
743   DataType &getValue() { return Value; }
744   DataType getValue() const { return Value; }
745
746   // If the datatype is a pointer, support -> on it.
747   DataType operator->() const { return Value; }
748 };
749
750
751 //===----------------------------------------------------------------------===//
752 // opt - A scalar command line option.
753 //
754 template <class DataType, bool ExternalStorage = false,
755           class ParserClass = parser<DataType> >
756 class opt : public Option,
757             public opt_storage<DataType, ExternalStorage,
758                                is_class<DataType>::value> {
759   ParserClass Parser;
760
761   virtual bool handleOccurrence(unsigned pos, const char *ArgName,
762                                 const std::string &Arg) {
763     typename ParserClass::parser_data_type Val =
764        typename ParserClass::parser_data_type();
765     if (Parser.parse(*this, ArgName, Arg, Val))
766       return true;                            // Parse error!
767     setValue(Val);
768     setPosition(pos);
769     return false;
770   }
771
772   virtual enum ValueExpected getValueExpectedFlagDefault() const {
773     return Parser.getValueExpectedFlagDefault();
774   }
775
776   // Forward printing stuff to the parser...
777   virtual unsigned getOptionWidth() const {return Parser.getOptionWidth(*this);}
778   virtual void printOptionInfo(unsigned GlobalWidth) const {
779     Parser.printOptionInfo(*this, GlobalWidth);
780   }
781
782   void done() {
783     addArgument(ArgStr);
784     Parser.initialize(*this);
785   }
786 public:
787   // setInitialValue - Used by the cl::init modifier...
788   void setInitialValue(const DataType &V) { this->setValue(V); }
789
790   ParserClass &getParser() { return Parser; }
791
792   operator DataType() const { return this->getValue(); }
793
794   template<class T>
795   DataType &operator=(const T &Val) {
796     this->setValue(Val);
797     return this->getValue();
798   }
799
800   // One option...
801   template<class M0t>
802   opt(const M0t &M0) : Option(Optional | NotHidden) {
803     apply(M0, this);
804     done();
805   }
806
807   // Two options...
808   template<class M0t, class M1t>
809   opt(const M0t &M0, const M1t &M1) : Option(Optional | NotHidden) {
810     apply(M0, this); apply(M1, this);
811     done();
812   }
813
814   // Three options...
815   template<class M0t, class M1t, class M2t>
816   opt(const M0t &M0, const M1t &M1,
817       const M2t &M2) : Option(Optional | NotHidden) {
818     apply(M0, this); apply(M1, this); apply(M2, this);
819     done();
820   }
821   // Four options...
822   template<class M0t, class M1t, class M2t, class M3t>
823   opt(const M0t &M0, const M1t &M1, const M2t &M2,
824       const M3t &M3) : Option(Optional | NotHidden) {
825     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
826     done();
827   }
828   // Five options...
829   template<class M0t, class M1t, class M2t, class M3t, class M4t>
830   opt(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
831       const M4t &M4) : Option(Optional | NotHidden) {
832     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
833     apply(M4, this);
834     done();
835   }
836   // Six options...
837   template<class M0t, class M1t, class M2t, class M3t,
838            class M4t, class M5t>
839   opt(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
840       const M4t &M4, const M5t &M5) : Option(Optional | NotHidden) {
841     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
842     apply(M4, this); apply(M5, this);
843     done();
844   }
845   // Seven options...
846   template<class M0t, class M1t, class M2t, class M3t,
847            class M4t, class M5t, class M6t>
848   opt(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
849       const M4t &M4, const M5t &M5,
850       const M6t &M6) : Option(Optional | NotHidden) {
851     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
852     apply(M4, this); apply(M5, this); apply(M6, this);
853     done();
854   }
855   // Eight options...
856   template<class M0t, class M1t, class M2t, class M3t,
857            class M4t, class M5t, class M6t, class M7t>
858   opt(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
859       const M4t &M4, const M5t &M5, const M6t &M6,
860       const M7t &M7) : Option(Optional | NotHidden) {
861     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
862     apply(M4, this); apply(M5, this); apply(M6, this); apply(M7, this);
863     done();
864   }
865 };
866
867 EXTERN_TEMPLATE_INSTANTIATION(class opt<unsigned>);
868 EXTERN_TEMPLATE_INSTANTIATION(class opt<int>);
869 EXTERN_TEMPLATE_INSTANTIATION(class opt<std::string>);
870 EXTERN_TEMPLATE_INSTANTIATION(class opt<bool>);
871
872 //===----------------------------------------------------------------------===//
873 // list_storage class
874
875 // Default storage class definition: external storage.  This implementation
876 // assumes the user will specify a variable to store the data into with the
877 // cl::location(x) modifier.
878 //
879 template<class DataType, class StorageClass>
880 class list_storage {
881   StorageClass *Location;   // Where to store the object...
882
883 public:
884   list_storage() : Location(0) {}
885
886   bool setLocation(Option &O, StorageClass &L) {
887     if (Location)
888       return O.error(": cl::location(x) specified more than once!");
889     Location = &L;
890     return false;
891   }
892
893   template<class T>
894   void addValue(const T &V) {
895     assert(Location != 0 && "cl::location(...) not specified for a command "
896            "line option with external storage!");
897     Location->push_back(V);
898   }
899 };
900
901
902 // Define how to hold a class type object, such as a string.  Since we can
903 // inherit from a class, we do so.  This makes us exactly compatible with the
904 // object in all cases that it is used.
905 //
906 template<class DataType>
907 class list_storage<DataType, bool> : public std::vector<DataType> {
908 public:
909   template<class T>
910   void addValue(const T &V) { push_back(V); }
911 };
912
913
914 //===----------------------------------------------------------------------===//
915 // list - A list of command line options.
916 //
917 template <class DataType, class Storage = bool,
918           class ParserClass = parser<DataType> >
919 class list : public Option, public list_storage<DataType, Storage> {
920   std::vector<unsigned> Positions;
921   ParserClass Parser;
922
923   virtual enum ValueExpected getValueExpectedFlagDefault() const {
924     return Parser.getValueExpectedFlagDefault();
925   }
926
927   virtual bool handleOccurrence(unsigned pos, const char *ArgName,
928                                 const std::string &Arg) {
929     typename ParserClass::parser_data_type Val =
930       typename ParserClass::parser_data_type();
931     if (Parser.parse(*this, ArgName, Arg, Val))
932       return true;  // Parse Error!
933     addValue(Val);
934     setPosition(pos);
935     Positions.push_back(pos);
936     return false;
937   }
938
939   // Forward printing stuff to the parser...
940   virtual unsigned getOptionWidth() const {return Parser.getOptionWidth(*this);}
941   virtual void printOptionInfo(unsigned GlobalWidth) const {
942     Parser.printOptionInfo(*this, GlobalWidth);
943   }
944
945   void done() {
946     addArgument(ArgStr);
947     Parser.initialize(*this);
948   }
949 public:
950   ParserClass &getParser() { return Parser; }
951
952   unsigned getPosition(unsigned optnum) const {
953     assert(optnum < this->size() && "Invalid option index");
954     return Positions[optnum];
955   }
956
957   // One option...
958   template<class M0t>
959   list(const M0t &M0) : Option(ZeroOrMore | NotHidden) {
960     apply(M0, this);
961     done();
962   }
963   // Two options...
964   template<class M0t, class M1t>
965   list(const M0t &M0, const M1t &M1) : Option(ZeroOrMore | NotHidden) {
966     apply(M0, this); apply(M1, this);
967     done();
968   }
969   // Three options...
970   template<class M0t, class M1t, class M2t>
971   list(const M0t &M0, const M1t &M1, const M2t &M2)
972     : Option(ZeroOrMore | NotHidden) {
973     apply(M0, this); apply(M1, this); apply(M2, this);
974     done();
975   }
976   // Four options...
977   template<class M0t, class M1t, class M2t, class M3t>
978   list(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3)
979     : Option(ZeroOrMore | NotHidden) {
980     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
981     done();
982   }
983   // Five options...
984   template<class M0t, class M1t, class M2t, class M3t, class M4t>
985   list(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
986        const M4t &M4) : Option(ZeroOrMore | NotHidden) {
987     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
988     apply(M4, this);
989     done();
990   }
991   // Six options...
992   template<class M0t, class M1t, class M2t, class M3t,
993            class M4t, class M5t>
994   list(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
995        const M4t &M4, const M5t &M5) : Option(ZeroOrMore | NotHidden) {
996     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
997     apply(M4, this); apply(M5, this);
998     done();
999   }
1000   // Seven options...
1001   template<class M0t, class M1t, class M2t, class M3t,
1002            class M4t, class M5t, class M6t>
1003   list(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
1004        const M4t &M4, const M5t &M5, const M6t &M6)
1005     : Option(ZeroOrMore | NotHidden) {
1006     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
1007     apply(M4, this); apply(M5, this); apply(M6, this);
1008     done();
1009   }
1010   // Eight options...
1011   template<class M0t, class M1t, class M2t, class M3t,
1012            class M4t, class M5t, class M6t, class M7t>
1013   list(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
1014        const M4t &M4, const M5t &M5, const M6t &M6,
1015        const M7t &M7) : Option(ZeroOrMore | NotHidden) {
1016     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
1017     apply(M4, this); apply(M5, this); apply(M6, this); apply(M7, this);
1018     done();
1019   }
1020 };
1021
1022 //===----------------------------------------------------------------------===//
1023 // bits_storage class
1024
1025 // Default storage class definition: external storage.  This implementation
1026 // assumes the user will specify a variable to store the data into with the
1027 // cl::location(x) modifier.
1028 //
1029 template<class DataType, class StorageClass>
1030 class bits_storage {
1031   unsigned *Location;   // Where to store the bits...
1032   
1033   template<class T>
1034   static unsigned Bit(const T &V) {
1035     unsigned BitPos = reinterpret_cast<unsigned>(V);
1036     assert(BitPos < sizeof(unsigned) * 8 &&
1037           "enum exceeds width of bit vector!");
1038     return 1 << BitPos;
1039   }
1040
1041 public:
1042   bits_storage() : Location(0) {}
1043
1044   bool setLocation(Option &O, unsigned &L) {
1045     if (Location)
1046       return O.error(": cl::location(x) specified more than once!");
1047     Location = &L;
1048     return false;
1049   }
1050
1051   template<class T>
1052   void addValue(const T &V) {
1053     assert(Location != 0 && "cl::location(...) not specified for a command "
1054            "line option with external storage!");
1055     *Location |= Bit(V);
1056   }
1057   
1058   unsigned getBits() { return *Location; }
1059   
1060   template<class T>
1061   bool isSet(const T &V) {
1062     return (*Location & Bit(V)) != 0;
1063   }
1064 };
1065
1066
1067 // Define how to hold bits.  Since we can inherit from a class, we do so. 
1068 // This makes us exactly compatible with the bits in all cases that it is used.
1069 //
1070 template<class DataType>
1071 class bits_storage<DataType, bool> {
1072   unsigned Bits;   // Where to store the bits...
1073   
1074   template<class T>
1075   static unsigned Bit(const T &V) {
1076     unsigned BitPos = reinterpret_cast<unsigned>(V);
1077     assert(BitPos < sizeof(unsigned) * 8 &&
1078           "enum exceeds width of bit vector!");
1079     return 1 << BitPos;
1080   }
1081   
1082 public:
1083   template<class T>
1084   void addValue(const T &V) {
1085     Bits |=  Bit(V);
1086   }
1087   
1088   unsigned getBits() { return Bits; }
1089   
1090   template<class T>
1091   bool isSet(const T &V) {
1092     return (Bits & Bit(V)) != 0;
1093   }
1094 };
1095
1096
1097 //===----------------------------------------------------------------------===//
1098 // bits - A bit vector of command options.
1099 //
1100 template <class DataType, class Storage = bool,
1101           class ParserClass = parser<DataType> >
1102 class bits : public Option, public bits_storage<DataType, Storage> {
1103   std::vector<unsigned> Positions;
1104   ParserClass Parser;
1105
1106   virtual enum ValueExpected getValueExpectedFlagDefault() const {
1107     return Parser.getValueExpectedFlagDefault();
1108   }
1109
1110   virtual bool handleOccurrence(unsigned pos, const char *ArgName,
1111                                 const std::string &Arg) {
1112     typename ParserClass::parser_data_type Val =
1113       typename ParserClass::parser_data_type();
1114     if (Parser.parse(*this, ArgName, Arg, Val))
1115       return true;  // Parse Error!
1116     addValue(Val);
1117     setPosition(pos);
1118     Positions.push_back(pos);
1119     return false;
1120   }
1121
1122   // Forward printing stuff to the parser...
1123   virtual unsigned getOptionWidth() const {return Parser.getOptionWidth(*this);}
1124   virtual void printOptionInfo(unsigned GlobalWidth) const {
1125     Parser.printOptionInfo(*this, GlobalWidth);
1126   }
1127
1128   void done() {
1129     addArgument(ArgStr);
1130     Parser.initialize(*this);
1131   }
1132 public:
1133   ParserClass &getParser() { return Parser; }
1134
1135   unsigned getPosition(unsigned optnum) const {
1136     assert(optnum < this->size() && "Invalid option index");
1137     return Positions[optnum];
1138   }
1139
1140   // One option...
1141   template<class M0t>
1142   bits(const M0t &M0) : Option(ZeroOrMore | NotHidden) {
1143     apply(M0, this);
1144     done();
1145   }
1146   // Two options...
1147   template<class M0t, class M1t>
1148   bits(const M0t &M0, const M1t &M1) : Option(ZeroOrMore | NotHidden) {
1149     apply(M0, this); apply(M1, this);
1150     done();
1151   }
1152   // Three options...
1153   template<class M0t, class M1t, class M2t>
1154   bits(const M0t &M0, const M1t &M1, const M2t &M2)
1155     : Option(ZeroOrMore | NotHidden) {
1156     apply(M0, this); apply(M1, this); apply(M2, this);
1157     done();
1158   }
1159   // Four options...
1160   template<class M0t, class M1t, class M2t, class M3t>
1161   bits(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3)
1162     : Option(ZeroOrMore | NotHidden) {
1163     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
1164     done();
1165   }
1166   // Five options...
1167   template<class M0t, class M1t, class M2t, class M3t, class M4t>
1168   bits(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
1169        const M4t &M4) : Option(ZeroOrMore | NotHidden) {
1170     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
1171     apply(M4, this);
1172     done();
1173   }
1174   // Six options...
1175   template<class M0t, class M1t, class M2t, class M3t,
1176            class M4t, class M5t>
1177   bits(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
1178        const M4t &M4, const M5t &M5) : Option(ZeroOrMore | NotHidden) {
1179     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
1180     apply(M4, this); apply(M5, this);
1181     done();
1182   }
1183   // Seven options...
1184   template<class M0t, class M1t, class M2t, class M3t,
1185            class M4t, class M5t, class M6t>
1186   bits(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
1187        const M4t &M4, const M5t &M5, const M6t &M6)
1188     : Option(ZeroOrMore | NotHidden) {
1189     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
1190     apply(M4, this); apply(M5, this); apply(M6, this);
1191     done();
1192   }
1193   // Eight options...
1194   template<class M0t, class M1t, class M2t, class M3t,
1195            class M4t, class M5t, class M6t, class M7t>
1196   bits(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
1197        const M4t &M4, const M5t &M5, const M6t &M6,
1198        const M7t &M7) : Option(ZeroOrMore | NotHidden) {
1199     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
1200     apply(M4, this); apply(M5, this); apply(M6, this); apply(M7, this);
1201     done();
1202   }
1203 };
1204
1205 //===----------------------------------------------------------------------===//
1206 // Aliased command line option (alias this name to a preexisting name)
1207 //
1208
1209 class alias : public Option {
1210   Option *AliasFor;
1211   virtual bool handleOccurrence(unsigned pos, const char *ArgName,
1212                                 const std::string &Arg) {
1213     return AliasFor->handleOccurrence(pos, AliasFor->ArgStr, Arg);
1214   }
1215   // Handle printing stuff...
1216   virtual unsigned getOptionWidth() const;
1217   virtual void printOptionInfo(unsigned GlobalWidth) const;
1218
1219   void done() {
1220     if (!hasArgStr())
1221       error(": cl::alias must have argument name specified!");
1222     if (AliasFor == 0)
1223       error(": cl::alias must have an cl::aliasopt(option) specified!");
1224     addArgument(ArgStr);
1225   }
1226 public:
1227   void setAliasFor(Option &O) {
1228     if (AliasFor)
1229       error(": cl::alias must only have one cl::aliasopt(...) specified!");
1230     AliasFor = &O;
1231   }
1232
1233   // One option...
1234   template<class M0t>
1235   alias(const M0t &M0) : Option(Optional | Hidden), AliasFor(0) {
1236     apply(M0, this);
1237     done();
1238   }
1239   // Two options...
1240   template<class M0t, class M1t>
1241   alias(const M0t &M0, const M1t &M1) : Option(Optional | Hidden), AliasFor(0) {
1242     apply(M0, this); apply(M1, this);
1243     done();
1244   }
1245   // Three options...
1246   template<class M0t, class M1t, class M2t>
1247   alias(const M0t &M0, const M1t &M1, const M2t &M2)
1248     : Option(Optional | Hidden), AliasFor(0) {
1249     apply(M0, this); apply(M1, this); apply(M2, this);
1250     done();
1251   }
1252   // Four options...
1253   template<class M0t, class M1t, class M2t, class M3t>
1254   alias(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3)
1255     : Option(Optional | Hidden), AliasFor(0) {
1256     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
1257     done();
1258   }
1259 };
1260
1261 // aliasfor - Modifier to set the option an alias aliases.
1262 struct aliasopt {
1263   Option &Opt;
1264   aliasopt(Option &O) : Opt(O) {}
1265   void apply(alias &A) const { A.setAliasFor(Opt); }
1266 };
1267
1268 // extrahelp - provide additional help at the end of the normal help
1269 // output. All occurrences of cl::extrahelp will be accumulated and
1270 // printed to std::cerr at the end of the regular help, just before
1271 // exit is called.
1272 struct extrahelp {
1273   const char * morehelp;
1274   extrahelp(const char* help);
1275 };
1276
1277 void PrintVersionMessage();
1278 // This function just prints the help message, exactly the same way as if the
1279 // --help option had been given on the command line.
1280 // NOTE: THIS FUNCTION TERMINATES THE PROGRAM!
1281 void PrintHelpMessage();
1282
1283 } // End namespace cl
1284
1285 } // End namespace llvm
1286
1287 #endif