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