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