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