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