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