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