Devirtualize OptionValue::~OptionValue in favor of protected in the base, with final...
[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
360 private:
361   virtual void anchor();
362 };
363
364 template <class DataType> struct OptionValue;
365
366 // The default value safely does nothing. Option value printing is only
367 // best-effort.
368 template <class DataType, bool isClass>
369 struct OptionValueBase : public GenericOptionValue {
370   // Temporary storage for argument passing.
371   typedef OptionValue<DataType> WrapperType;
372
373   bool hasValue() const { return false; }
374
375   const DataType &getValue() const { llvm_unreachable("no default value"); }
376
377   // Some options may take their value from a different data type.
378   template <class DT> void setValue(const DT & /*V*/) {}
379
380   bool compare(const DataType & /*V*/) const { return false; }
381
382   bool compare(const GenericOptionValue & /*V*/) const override {
383     return false;
384   }
385
386 protected:
387   ~OptionValueBase() = default;
388 };
389
390 // Simple copy of the option value.
391 template <class DataType> class OptionValueCopy : public GenericOptionValue {
392   DataType Value;
393   bool Valid;
394
395 protected:
396   ~OptionValueCopy() = default;
397
398 public:
399   OptionValueCopy() : Valid(false) {}
400
401   bool hasValue() const { return Valid; }
402
403   const DataType &getValue() const {
404     assert(Valid && "invalid option value");
405     return Value;
406   }
407
408   void setValue(const DataType &V) {
409     Valid = true;
410     Value = V;
411   }
412
413   bool compare(const DataType &V) const { return Valid && (Value != V); }
414
415   bool compare(const GenericOptionValue &V) const override {
416     const OptionValueCopy<DataType> &VC =
417         static_cast<const OptionValueCopy<DataType> &>(V);
418     if (!VC.hasValue())
419       return false;
420     return compare(VC.getValue());
421   }
422 };
423
424 // Non-class option values.
425 template <class DataType>
426 struct OptionValueBase<DataType, false> : OptionValueCopy<DataType> {
427   typedef DataType WrapperType;
428
429 protected:
430   ~OptionValueBase() = default;
431 };
432
433 // Top-level option class.
434 template <class DataType>
435 struct OptionValue final
436     : OptionValueBase<DataType, std::is_class<DataType>::value> {
437   OptionValue() = default;
438
439   OptionValue(const DataType &V) { this->setValue(V); }
440   // Some options may take their value from a different data type.
441   template <class DT> OptionValue<DataType> &operator=(const DT &V) {
442     this->setValue(V);
443     return *this;
444   }
445 };
446
447 // Other safe-to-copy-by-value common option types.
448 enum boolOrDefault { BOU_UNSET, BOU_TRUE, BOU_FALSE };
449 template <>
450 struct OptionValue<cl::boolOrDefault> final
451     : OptionValueCopy<cl::boolOrDefault> {
452   typedef cl::boolOrDefault WrapperType;
453
454   OptionValue() {}
455
456   OptionValue(const cl::boolOrDefault &V) { this->setValue(V); }
457   OptionValue<cl::boolOrDefault> &operator=(const cl::boolOrDefault &V) {
458     setValue(V);
459     return *this;
460   }
461
462 private:
463   void anchor() override;
464 };
465
466 template <>
467 struct OptionValue<std::string> final : OptionValueCopy<std::string> {
468   typedef StringRef WrapperType;
469
470   OptionValue() {}
471
472   OptionValue(const std::string &V) { this->setValue(V); }
473   OptionValue<std::string> &operator=(const std::string &V) {
474     setValue(V);
475     return *this;
476   }
477
478 private:
479   void anchor() override;
480 };
481
482 //===----------------------------------------------------------------------===//
483 // Enum valued command line option
484 //
485 #define clEnumVal(ENUMVAL, DESC) #ENUMVAL, int(ENUMVAL), DESC
486 #define clEnumValN(ENUMVAL, FLAGNAME, DESC) FLAGNAME, int(ENUMVAL), DESC
487 #define clEnumValEnd (reinterpret_cast<void *>(0))
488
489 // values - For custom data types, allow specifying a group of values together
490 // as the values that go into the mapping that the option handler uses.  Note
491 // that the values list must always have a 0 at the end of the list to indicate
492 // that the list has ended.
493 //
494 template <class DataType> class ValuesClass {
495   // Use a vector instead of a map, because the lists should be short,
496   // the overhead is less, and most importantly, it keeps them in the order
497   // inserted so we can print our option out nicely.
498   SmallVector<std::pair<const char *, std::pair<int, const char *>>, 4> Values;
499   void processValues(va_list Vals);
500
501 public:
502   ValuesClass(const char *EnumName, DataType Val, const char *Desc,
503               va_list ValueArgs) {
504     // Insert the first value, which is required.
505     Values.push_back(std::make_pair(EnumName, std::make_pair(Val, Desc)));
506
507     // Process the varargs portion of the values...
508     while (const char *enumName = va_arg(ValueArgs, const char *)) {
509       DataType EnumVal = static_cast<DataType>(va_arg(ValueArgs, int));
510       const char *EnumDesc = va_arg(ValueArgs, const char *);
511       Values.push_back(std::make_pair(enumName, // Add value to value map
512                                       std::make_pair(EnumVal, EnumDesc)));
513     }
514   }
515
516   template <class Opt> void apply(Opt &O) const {
517     for (size_t i = 0, e = Values.size(); i != e; ++i)
518       O.getParser().addLiteralOption(Values[i].first, Values[i].second.first,
519                                      Values[i].second.second);
520   }
521 };
522
523 template <class DataType>
524 ValuesClass<DataType> LLVM_END_WITH_NULL
525 values(const char *Arg, DataType Val, const char *Desc, ...) {
526   va_list ValueArgs;
527   va_start(ValueArgs, Desc);
528   ValuesClass<DataType> Vals(Arg, Val, Desc, ValueArgs);
529   va_end(ValueArgs);
530   return Vals;
531 }
532
533 //===----------------------------------------------------------------------===//
534 // parser class - Parameterizable parser for different data types.  By default,
535 // known data types (string, int, bool) have specialized parsers, that do what
536 // you would expect.  The default parser, used for data types that are not
537 // built-in, uses a mapping table to map specific options to values, which is
538 // used, among other things, to handle enum types.
539
540 //--------------------------------------------------
541 // generic_parser_base - This class holds all the non-generic code that we do
542 // not need replicated for every instance of the generic parser.  This also
543 // allows us to put stuff into CommandLine.cpp
544 //
545 class generic_parser_base {
546 protected:
547   class GenericOptionInfo {
548   public:
549     GenericOptionInfo(const char *name, const char *helpStr)
550         : Name(name), HelpStr(helpStr) {}
551     const char *Name;
552     const char *HelpStr;
553   };
554
555 public:
556   generic_parser_base(Option &O) : Owner(O) {}
557
558   virtual ~generic_parser_base() {} // Base class should have virtual-dtor
559
560   // getNumOptions - Virtual function implemented by generic subclass to
561   // indicate how many entries are in Values.
562   //
563   virtual unsigned getNumOptions() const = 0;
564
565   // getOption - Return option name N.
566   virtual const char *getOption(unsigned N) const = 0;
567
568   // getDescription - Return description N
569   virtual const char *getDescription(unsigned N) const = 0;
570
571   // Return the width of the option tag for printing...
572   virtual size_t getOptionWidth(const Option &O) const;
573
574   virtual const GenericOptionValue &getOptionValue(unsigned N) const = 0;
575
576   // printOptionInfo - Print out information about this option.  The
577   // to-be-maintained width is specified.
578   //
579   virtual void printOptionInfo(const Option &O, size_t GlobalWidth) const;
580
581   void printGenericOptionDiff(const Option &O, const GenericOptionValue &V,
582                               const GenericOptionValue &Default,
583                               size_t GlobalWidth) const;
584
585   // printOptionDiff - print the value of an option and it's default.
586   //
587   // Template definition ensures that the option and default have the same
588   // DataType (via the same AnyOptionValue).
589   template <class AnyOptionValue>
590   void printOptionDiff(const Option &O, const AnyOptionValue &V,
591                        const AnyOptionValue &Default,
592                        size_t GlobalWidth) const {
593     printGenericOptionDiff(O, V, Default, GlobalWidth);
594   }
595
596   void initialize() {}
597
598   void getExtraOptionNames(SmallVectorImpl<const char *> &OptionNames) {
599     // If there has been no argstr specified, that means that we need to add an
600     // argument for every possible option.  This ensures that our options are
601     // vectored to us.
602     if (!Owner.hasArgStr())
603       for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
604         OptionNames.push_back(getOption(i));
605   }
606
607   enum ValueExpected getValueExpectedFlagDefault() const {
608     // If there is an ArgStr specified, then we are of the form:
609     //
610     //    -opt=O2   or   -opt O2  or  -optO2
611     //
612     // In which case, the value is required.  Otherwise if an arg str has not
613     // been specified, we are of the form:
614     //
615     //    -O2 or O2 or -la (where -l and -a are separate options)
616     //
617     // If this is the case, we cannot allow a value.
618     //
619     if (Owner.hasArgStr())
620       return ValueRequired;
621     else
622       return ValueDisallowed;
623   }
624
625   // findOption - Return the option number corresponding to the specified
626   // argument string.  If the option is not found, getNumOptions() is returned.
627   //
628   unsigned findOption(const char *Name);
629
630 protected:
631   Option &Owner;
632 };
633
634 // Default parser implementation - This implementation depends on having a
635 // mapping of recognized options to values of some sort.  In addition to this,
636 // each entry in the mapping also tracks a help message that is printed with the
637 // command line option for -help.  Because this is a simple mapping parser, the
638 // data type can be any unsupported type.
639 //
640 template <class DataType> class parser : public generic_parser_base {
641 protected:
642   class OptionInfo : public GenericOptionInfo {
643   public:
644     OptionInfo(const char *name, DataType v, const char *helpStr)
645         : GenericOptionInfo(name, helpStr), V(v) {}
646     OptionValue<DataType> V;
647   };
648   SmallVector<OptionInfo, 8> Values;
649
650 public:
651   parser(Option &O) : generic_parser_base(O) {}
652   typedef DataType parser_data_type;
653
654   // Implement virtual functions needed by generic_parser_base
655   unsigned getNumOptions() const override { return unsigned(Values.size()); }
656   const char *getOption(unsigned N) const override { return Values[N].Name; }
657   const char *getDescription(unsigned N) const override {
658     return Values[N].HelpStr;
659   }
660
661   // getOptionValue - Return the value of option name N.
662   const GenericOptionValue &getOptionValue(unsigned N) const override {
663     return Values[N].V;
664   }
665
666   // parse - Return true on error.
667   bool parse(Option &O, StringRef ArgName, StringRef Arg, DataType &V) {
668     StringRef ArgVal;
669     if (Owner.hasArgStr())
670       ArgVal = Arg;
671     else
672       ArgVal = ArgName;
673
674     for (size_t i = 0, e = Values.size(); i != e; ++i)
675       if (Values[i].Name == ArgVal) {
676         V = Values[i].V.getValue();
677         return false;
678       }
679
680     return O.error("Cannot find option named '" + ArgVal + "'!");
681   }
682
683   /// addLiteralOption - Add an entry to the mapping table.
684   ///
685   template <class DT>
686   void addLiteralOption(const char *Name, const DT &V, const char *HelpStr) {
687     assert(findOption(Name) == Values.size() && "Option already exists!");
688     OptionInfo X(Name, static_cast<DataType>(V), HelpStr);
689     Values.push_back(X);
690     AddLiteralOption(Owner, Name);
691   }
692
693   /// removeLiteralOption - Remove the specified option.
694   ///
695   void removeLiteralOption(const char *Name) {
696     unsigned N = findOption(Name);
697     assert(N != Values.size() && "Option not found!");
698     Values.erase(Values.begin() + N);
699   }
700 };
701
702 //--------------------------------------------------
703 // basic_parser - Super class of parsers to provide boilerplate code
704 //
705 class basic_parser_impl { // non-template implementation of basic_parser<t>
706 public:
707   basic_parser_impl(Option &O) {}
708
709   virtual ~basic_parser_impl() {}
710
711   enum ValueExpected getValueExpectedFlagDefault() const {
712     return ValueRequired;
713   }
714
715   void getExtraOptionNames(SmallVectorImpl<const char *> &) {}
716
717   void initialize() {}
718
719   // Return the width of the option tag for printing...
720   size_t getOptionWidth(const Option &O) const;
721
722   // printOptionInfo - Print out information about this option.  The
723   // to-be-maintained width is specified.
724   //
725   void printOptionInfo(const Option &O, size_t GlobalWidth) const;
726
727   // printOptionNoValue - Print a placeholder for options that don't yet support
728   // printOptionDiff().
729   void printOptionNoValue(const Option &O, size_t GlobalWidth) const;
730
731   // getValueName - Overload in subclass to provide a better default value.
732   virtual const char *getValueName() const { return "value"; }
733
734   // An out-of-line virtual method to provide a 'home' for this class.
735   virtual void anchor();
736
737 protected:
738   // A helper for basic_parser::printOptionDiff.
739   void printOptionName(const Option &O, size_t GlobalWidth) const;
740 };
741
742 // basic_parser - The real basic parser is just a template wrapper that provides
743 // a typedef for the provided data type.
744 //
745 template <class DataType> class basic_parser : public basic_parser_impl {
746 public:
747   basic_parser(Option &O) : basic_parser_impl(O) {}
748   typedef DataType parser_data_type;
749   typedef OptionValue<DataType> OptVal;
750 };
751
752 //--------------------------------------------------
753 // parser<bool>
754 //
755 template <> class parser<bool> : public basic_parser<bool> {
756 public:
757   parser(Option &O) : basic_parser(O) {}
758
759   // parse - Return true on error.
760   bool parse(Option &O, StringRef ArgName, StringRef Arg, bool &Val);
761
762   void initialize() {}
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, bool 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<bool>);
779
780 //--------------------------------------------------
781 // parser<boolOrDefault>
782 template <> class parser<boolOrDefault> : public basic_parser<boolOrDefault> {
783 public:
784   parser(Option &O) : basic_parser(O) {}
785
786   // parse - Return true on error.
787   bool parse(Option &O, StringRef ArgName, StringRef Arg, boolOrDefault &Val);
788
789   enum ValueExpected getValueExpectedFlagDefault() const {
790     return ValueOptional;
791   }
792
793   // getValueName - Do not print =<value> at all.
794   const char *getValueName() const override { return nullptr; }
795
796   void printOptionDiff(const Option &O, boolOrDefault V, OptVal Default,
797                        size_t GlobalWidth) const;
798
799   // An out-of-line virtual method to provide a 'home' for this class.
800   void anchor() override;
801 };
802
803 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<boolOrDefault>);
804
805 //--------------------------------------------------
806 // parser<int>
807 //
808 template <> class parser<int> : public basic_parser<int> {
809 public:
810   parser(Option &O) : basic_parser(O) {}
811
812   // parse - Return true on error.
813   bool parse(Option &O, StringRef ArgName, StringRef Arg, int &Val);
814
815   // getValueName - Overload in subclass to provide a better default value.
816   const char *getValueName() const override { return "int"; }
817
818   void printOptionDiff(const Option &O, int V, OptVal Default,
819                        size_t GlobalWidth) const;
820
821   // An out-of-line virtual method to provide a 'home' for this class.
822   void anchor() override;
823 };
824
825 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<int>);
826
827 //--------------------------------------------------
828 // parser<unsigned>
829 //
830 template <> class parser<unsigned> : public basic_parser<unsigned> {
831 public:
832   parser(Option &O) : basic_parser(O) {}
833
834   // parse - Return true on error.
835   bool parse(Option &O, StringRef ArgName, StringRef Arg, unsigned &Val);
836
837   // getValueName - Overload in subclass to provide a better default value.
838   const char *getValueName() const override { return "uint"; }
839
840   void printOptionDiff(const Option &O, unsigned V, OptVal Default,
841                        size_t GlobalWidth) const;
842
843   // An out-of-line virtual method to provide a 'home' for this class.
844   void anchor() override;
845 };
846
847 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<unsigned>);
848
849 //--------------------------------------------------
850 // parser<unsigned long long>
851 //
852 template <>
853 class parser<unsigned long long> : public basic_parser<unsigned long long> {
854 public:
855   parser(Option &O) : basic_parser(O) {}
856
857   // parse - Return true on error.
858   bool parse(Option &O, StringRef ArgName, StringRef Arg,
859              unsigned long long &Val);
860
861   // getValueName - Overload in subclass to provide a better default value.
862   const char *getValueName() const override { return "uint"; }
863
864   void printOptionDiff(const Option &O, unsigned long long V, OptVal Default,
865                        size_t GlobalWidth) const;
866
867   // An out-of-line virtual method to provide a 'home' for this class.
868   void anchor() override;
869 };
870
871 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<unsigned long long>);
872
873 //--------------------------------------------------
874 // parser<double>
875 //
876 template <> class parser<double> : public basic_parser<double> {
877 public:
878   parser(Option &O) : basic_parser(O) {}
879
880   // parse - Return true on error.
881   bool parse(Option &O, StringRef ArgName, StringRef Arg, double &Val);
882
883   // getValueName - Overload in subclass to provide a better default value.
884   const char *getValueName() const override { return "number"; }
885
886   void printOptionDiff(const Option &O, double V, OptVal Default,
887                        size_t GlobalWidth) const;
888
889   // An out-of-line virtual method to provide a 'home' for this class.
890   void anchor() override;
891 };
892
893 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<double>);
894
895 //--------------------------------------------------
896 // parser<float>
897 //
898 template <> class parser<float> : public basic_parser<float> {
899 public:
900   parser(Option &O) : basic_parser(O) {}
901
902   // parse - Return true on error.
903   bool parse(Option &O, StringRef ArgName, StringRef Arg, float &Val);
904
905   // getValueName - Overload in subclass to provide a better default value.
906   const char *getValueName() const override { return "number"; }
907
908   void printOptionDiff(const Option &O, float V, OptVal Default,
909                        size_t GlobalWidth) const;
910
911   // An out-of-line virtual method to provide a 'home' for this class.
912   void anchor() override;
913 };
914
915 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<float>);
916
917 //--------------------------------------------------
918 // parser<std::string>
919 //
920 template <> class parser<std::string> : public basic_parser<std::string> {
921 public:
922   parser(Option &O) : basic_parser(O) {}
923
924   // parse - Return true on error.
925   bool parse(Option &, StringRef, StringRef Arg, std::string &Value) {
926     Value = Arg.str();
927     return false;
928   }
929
930   // getValueName - Overload in subclass to provide a better default value.
931   const char *getValueName() const override { return "string"; }
932
933   void printOptionDiff(const Option &O, StringRef V, OptVal Default,
934                        size_t GlobalWidth) const;
935
936   // An out-of-line virtual method to provide a 'home' for this class.
937   void anchor() override;
938 };
939
940 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<std::string>);
941
942 //--------------------------------------------------
943 // parser<char>
944 //
945 template <> class parser<char> : public basic_parser<char> {
946 public:
947   parser(Option &O) : basic_parser(O) {}
948
949   // parse - Return true on error.
950   bool parse(Option &, StringRef, StringRef Arg, char &Value) {
951     Value = Arg[0];
952     return false;
953   }
954
955   // getValueName - Overload in subclass to provide a better default value.
956   const char *getValueName() const override { return "char"; }
957
958   void printOptionDiff(const Option &O, char V, OptVal Default,
959                        size_t GlobalWidth) const;
960
961   // An out-of-line virtual method to provide a 'home' for this class.
962   void anchor() override;
963 };
964
965 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<char>);
966
967 //--------------------------------------------------
968 // PrintOptionDiff
969 //
970 // This collection of wrappers is the intermediary between class opt and class
971 // parser to handle all the template nastiness.
972
973 // This overloaded function is selected by the generic parser.
974 template <class ParserClass, class DT>
975 void printOptionDiff(const Option &O, const generic_parser_base &P, const DT &V,
976                      const OptionValue<DT> &Default, size_t GlobalWidth) {
977   OptionValue<DT> OV = V;
978   P.printOptionDiff(O, OV, Default, GlobalWidth);
979 }
980
981 // This is instantiated for basic parsers when the parsed value has a different
982 // type than the option value. e.g. HelpPrinter.
983 template <class ParserDT, class ValDT> struct OptionDiffPrinter {
984   void print(const Option &O, const parser<ParserDT> P, const ValDT & /*V*/,
985              const OptionValue<ValDT> & /*Default*/, size_t GlobalWidth) {
986     P.printOptionNoValue(O, GlobalWidth);
987   }
988 };
989
990 // This is instantiated for basic parsers when the parsed value has the same
991 // type as the option value.
992 template <class DT> struct OptionDiffPrinter<DT, DT> {
993   void print(const Option &O, const parser<DT> P, const DT &V,
994              const OptionValue<DT> &Default, size_t GlobalWidth) {
995     P.printOptionDiff(O, V, Default, GlobalWidth);
996   }
997 };
998
999 // This overloaded function is selected by the basic parser, which may parse a
1000 // different type than the option type.
1001 template <class ParserClass, class ValDT>
1002 void printOptionDiff(
1003     const Option &O,
1004     const basic_parser<typename ParserClass::parser_data_type> &P,
1005     const ValDT &V, const OptionValue<ValDT> &Default, size_t GlobalWidth) {
1006
1007   OptionDiffPrinter<typename ParserClass::parser_data_type, ValDT> printer;
1008   printer.print(O, static_cast<const ParserClass &>(P), V, Default,
1009                 GlobalWidth);
1010 }
1011
1012 //===----------------------------------------------------------------------===//
1013 // applicator class - This class is used because we must use partial
1014 // specialization to handle literal string arguments specially (const char* does
1015 // not correctly respond to the apply method).  Because the syntax to use this
1016 // is a pain, we have the 'apply' method below to handle the nastiness...
1017 //
1018 template <class Mod> struct applicator {
1019   template <class Opt> static void opt(const Mod &M, Opt &O) { M.apply(O); }
1020 };
1021
1022 // Handle const char* as a special case...
1023 template <unsigned n> struct applicator<char[n]> {
1024   template <class Opt> static void opt(const char *Str, Opt &O) {
1025     O.setArgStr(Str);
1026   }
1027 };
1028 template <unsigned n> struct applicator<const char[n]> {
1029   template <class Opt> static void opt(const char *Str, Opt &O) {
1030     O.setArgStr(Str);
1031   }
1032 };
1033 template <> struct applicator<const char *> {
1034   template <class Opt> static void opt(const char *Str, Opt &O) {
1035     O.setArgStr(Str);
1036   }
1037 };
1038
1039 template <> struct applicator<NumOccurrencesFlag> {
1040   static void opt(NumOccurrencesFlag N, Option &O) {
1041     O.setNumOccurrencesFlag(N);
1042   }
1043 };
1044 template <> struct applicator<ValueExpected> {
1045   static void opt(ValueExpected VE, Option &O) { O.setValueExpectedFlag(VE); }
1046 };
1047 template <> struct applicator<OptionHidden> {
1048   static void opt(OptionHidden OH, Option &O) { O.setHiddenFlag(OH); }
1049 };
1050 template <> struct applicator<FormattingFlags> {
1051   static void opt(FormattingFlags FF, Option &O) { O.setFormattingFlag(FF); }
1052 };
1053 template <> struct applicator<MiscFlags> {
1054   static void opt(MiscFlags MF, Option &O) { O.setMiscFlag(MF); }
1055 };
1056
1057 // apply method - Apply modifiers to an option in a type safe way.
1058 template <class Opt, class Mod, class... Mods>
1059 void apply(Opt *O, const Mod &M, const Mods &... Ms) {
1060   applicator<Mod>::opt(M, *O);
1061   apply(O, Ms...);
1062 }
1063
1064 template <class Opt, class Mod> void apply(Opt *O, const Mod &M) {
1065   applicator<Mod>::opt(M, *O);
1066 }
1067
1068 //===----------------------------------------------------------------------===//
1069 // opt_storage class
1070
1071 // Default storage class definition: external storage.  This implementation
1072 // assumes the user will specify a variable to store the data into with the
1073 // cl::location(x) modifier.
1074 //
1075 template <class DataType, bool ExternalStorage, bool isClass>
1076 class opt_storage {
1077   DataType *Location; // Where to store the object...
1078   OptionValue<DataType> Default;
1079
1080   void check_location() const {
1081     assert(Location && "cl::location(...) not specified for a command "
1082                        "line option with external storage, "
1083                        "or cl::init specified before cl::location()!!");
1084   }
1085
1086 public:
1087   opt_storage() : Location(nullptr) {}
1088
1089   bool setLocation(Option &O, DataType &L) {
1090     if (Location)
1091       return O.error("cl::location(x) specified more than once!");
1092     Location = &L;
1093     Default = L;
1094     return false;
1095   }
1096
1097   template <class T> void setValue(const T &V, bool initial = false) {
1098     check_location();
1099     *Location = V;
1100     if (initial)
1101       Default = V;
1102   }
1103
1104   DataType &getValue() {
1105     check_location();
1106     return *Location;
1107   }
1108   const DataType &getValue() const {
1109     check_location();
1110     return *Location;
1111   }
1112
1113   operator DataType() const { return this->getValue(); }
1114
1115   const OptionValue<DataType> &getDefault() const { return Default; }
1116 };
1117
1118 // Define how to hold a class type object, such as a string.  Since we can
1119 // inherit from a class, we do so.  This makes us exactly compatible with the
1120 // object in all cases that it is used.
1121 //
1122 template <class DataType>
1123 class opt_storage<DataType, false, true> : public DataType {
1124 public:
1125   OptionValue<DataType> Default;
1126
1127   template <class T> void setValue(const T &V, bool initial = false) {
1128     DataType::operator=(V);
1129     if (initial)
1130       Default = V;
1131   }
1132
1133   DataType &getValue() { return *this; }
1134   const DataType &getValue() const { return *this; }
1135
1136   const OptionValue<DataType> &getDefault() const { return Default; }
1137 };
1138
1139 // Define a partial specialization to handle things we cannot inherit from.  In
1140 // this case, we store an instance through containment, and overload operators
1141 // to get at the value.
1142 //
1143 template <class DataType> class opt_storage<DataType, false, false> {
1144 public:
1145   DataType Value;
1146   OptionValue<DataType> Default;
1147
1148   // Make sure we initialize the value with the default constructor for the
1149   // type.
1150   opt_storage() : Value(DataType()), Default(DataType()) {}
1151
1152   template <class T> void setValue(const T &V, bool initial = false) {
1153     Value = V;
1154     if (initial)
1155       Default = V;
1156   }
1157   DataType &getValue() { return Value; }
1158   DataType getValue() const { return Value; }
1159
1160   const OptionValue<DataType> &getDefault() const { return Default; }
1161
1162   operator DataType() const { return getValue(); }
1163
1164   // If the datatype is a pointer, support -> on it.
1165   DataType operator->() const { return Value; }
1166 };
1167
1168 //===----------------------------------------------------------------------===//
1169 // opt - A scalar command line option.
1170 //
1171 template <class DataType, bool ExternalStorage = false,
1172           class ParserClass = parser<DataType>>
1173 class opt : public Option,
1174             public opt_storage<DataType, ExternalStorage,
1175                                std::is_class<DataType>::value> {
1176   ParserClass Parser;
1177
1178   bool handleOccurrence(unsigned pos, StringRef ArgName,
1179                         StringRef Arg) override {
1180     typename ParserClass::parser_data_type Val =
1181         typename ParserClass::parser_data_type();
1182     if (Parser.parse(*this, ArgName, Arg, Val))
1183       return true; // Parse error!
1184     this->setValue(Val);
1185     this->setPosition(pos);
1186     return false;
1187   }
1188
1189   enum ValueExpected getValueExpectedFlagDefault() const override {
1190     return Parser.getValueExpectedFlagDefault();
1191   }
1192   void
1193   getExtraOptionNames(SmallVectorImpl<const char *> &OptionNames) override {
1194     return Parser.getExtraOptionNames(OptionNames);
1195   }
1196
1197   // Forward printing stuff to the parser...
1198   size_t getOptionWidth() const override {
1199     return Parser.getOptionWidth(*this);
1200   }
1201   void printOptionInfo(size_t GlobalWidth) const override {
1202     Parser.printOptionInfo(*this, GlobalWidth);
1203   }
1204
1205   void printOptionValue(size_t GlobalWidth, bool Force) const override {
1206     if (Force || this->getDefault().compare(this->getValue())) {
1207       cl::printOptionDiff<ParserClass>(*this, Parser, this->getValue(),
1208                                        this->getDefault(), GlobalWidth);
1209     }
1210   }
1211
1212   void done() {
1213     addArgument();
1214     Parser.initialize();
1215   }
1216
1217   // Command line options should not be copyable
1218   opt(const opt &) = delete;
1219   opt &operator=(const opt &) = delete;
1220
1221 public:
1222   // setInitialValue - Used by the cl::init modifier...
1223   void setInitialValue(const DataType &V) { this->setValue(V, true); }
1224
1225   ParserClass &getParser() { return Parser; }
1226
1227   template <class T> DataType &operator=(const T &Val) {
1228     this->setValue(Val);
1229     return this->getValue();
1230   }
1231
1232   template <class... Mods>
1233   explicit opt(const Mods &... Ms)
1234       : Option(Optional, NotHidden), Parser(*this) {
1235     apply(this, Ms...);
1236     done();
1237   }
1238 };
1239
1240 EXTERN_TEMPLATE_INSTANTIATION(class opt<unsigned>);
1241 EXTERN_TEMPLATE_INSTANTIATION(class opt<int>);
1242 EXTERN_TEMPLATE_INSTANTIATION(class opt<std::string>);
1243 EXTERN_TEMPLATE_INSTANTIATION(class opt<char>);
1244 EXTERN_TEMPLATE_INSTANTIATION(class opt<bool>);
1245
1246 //===----------------------------------------------------------------------===//
1247 // list_storage class
1248
1249 // Default storage class definition: external storage.  This implementation
1250 // assumes the user will specify a variable to store the data into with the
1251 // cl::location(x) modifier.
1252 //
1253 template <class DataType, class StorageClass> class list_storage {
1254   StorageClass *Location; // Where to store the object...
1255
1256 public:
1257   list_storage() : Location(0) {}
1258
1259   bool setLocation(Option &O, StorageClass &L) {
1260     if (Location)
1261       return O.error("cl::location(x) specified more than once!");
1262     Location = &L;
1263     return false;
1264   }
1265
1266   template <class T> void addValue(const T &V) {
1267     assert(Location != 0 && "cl::location(...) not specified for a command "
1268                             "line option with external storage!");
1269     Location->push_back(V);
1270   }
1271 };
1272
1273 // Define how to hold a class type object, such as a string.  Since we can
1274 // inherit from a class, we do so.  This makes us exactly compatible with the
1275 // object in all cases that it is used.
1276 //
1277 template <class DataType>
1278 class list_storage<DataType, bool> : public std::vector<DataType> {
1279 public:
1280   template <class T> void addValue(const T &V) {
1281     std::vector<DataType>::push_back(V);
1282   }
1283 };
1284
1285 //===----------------------------------------------------------------------===//
1286 // list - A list of command line options.
1287 //
1288 template <class DataType, class Storage = bool,
1289           class ParserClass = parser<DataType>>
1290 class list : public Option, public list_storage<DataType, Storage> {
1291   std::vector<unsigned> Positions;
1292   ParserClass Parser;
1293
1294   enum ValueExpected getValueExpectedFlagDefault() const override {
1295     return Parser.getValueExpectedFlagDefault();
1296   }
1297   void
1298   getExtraOptionNames(SmallVectorImpl<const char *> &OptionNames) override {
1299     return Parser.getExtraOptionNames(OptionNames);
1300   }
1301
1302   bool handleOccurrence(unsigned pos, StringRef ArgName,
1303                         StringRef Arg) override {
1304     typename ParserClass::parser_data_type Val =
1305         typename ParserClass::parser_data_type();
1306     if (Parser.parse(*this, ArgName, Arg, Val))
1307       return true; // Parse Error!
1308     list_storage<DataType, Storage>::addValue(Val);
1309     setPosition(pos);
1310     Positions.push_back(pos);
1311     return false;
1312   }
1313
1314   // Forward printing stuff to the parser...
1315   size_t getOptionWidth() const override {
1316     return Parser.getOptionWidth(*this);
1317   }
1318   void printOptionInfo(size_t GlobalWidth) const override {
1319     Parser.printOptionInfo(*this, GlobalWidth);
1320   }
1321
1322   // Unimplemented: list options don't currently store their default value.
1323   void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override {
1324   }
1325
1326   void done() {
1327     addArgument();
1328     Parser.initialize();
1329   }
1330
1331   // Command line options should not be copyable
1332   list(const list &) = delete;
1333   list &operator=(const list &) = delete;
1334
1335 public:
1336   ParserClass &getParser() { return Parser; }
1337
1338   unsigned getPosition(unsigned optnum) const {
1339     assert(optnum < this->size() && "Invalid option index");
1340     return Positions[optnum];
1341   }
1342
1343   void setNumAdditionalVals(unsigned n) { Option::setNumAdditionalVals(n); }
1344
1345   template <class... Mods>
1346   explicit list(const Mods &... Ms)
1347       : Option(ZeroOrMore, NotHidden), Parser(*this) {
1348     apply(this, Ms...);
1349     done();
1350   }
1351 };
1352
1353 // multi_val - Modifier to set the number of additional values.
1354 struct multi_val {
1355   unsigned AdditionalVals;
1356   explicit multi_val(unsigned N) : AdditionalVals(N) {}
1357
1358   template <typename D, typename S, typename P>
1359   void apply(list<D, S, P> &L) const {
1360     L.setNumAdditionalVals(AdditionalVals);
1361   }
1362 };
1363
1364 //===----------------------------------------------------------------------===//
1365 // bits_storage class
1366
1367 // Default storage class definition: external storage.  This implementation
1368 // assumes the user will specify a variable to store the data into with the
1369 // cl::location(x) modifier.
1370 //
1371 template <class DataType, class StorageClass> class bits_storage {
1372   unsigned *Location; // Where to store the bits...
1373
1374   template <class T> static unsigned Bit(const T &V) {
1375     unsigned BitPos = reinterpret_cast<unsigned>(V);
1376     assert(BitPos < sizeof(unsigned) * CHAR_BIT &&
1377            "enum exceeds width of bit vector!");
1378     return 1 << BitPos;
1379   }
1380
1381 public:
1382   bits_storage() : Location(nullptr) {}
1383
1384   bool setLocation(Option &O, unsigned &L) {
1385     if (Location)
1386       return O.error("cl::location(x) specified more than once!");
1387     Location = &L;
1388     return false;
1389   }
1390
1391   template <class T> void addValue(const T &V) {
1392     assert(Location != 0 && "cl::location(...) not specified for a command "
1393                             "line option with external storage!");
1394     *Location |= Bit(V);
1395   }
1396
1397   unsigned getBits() { return *Location; }
1398
1399   template <class T> bool isSet(const T &V) {
1400     return (*Location & Bit(V)) != 0;
1401   }
1402 };
1403
1404 // Define how to hold bits.  Since we can inherit from a class, we do so.
1405 // This makes us exactly compatible with the bits in all cases that it is used.
1406 //
1407 template <class DataType> class bits_storage<DataType, bool> {
1408   unsigned Bits; // Where to store the bits...
1409
1410   template <class T> static unsigned Bit(const T &V) {
1411     unsigned BitPos = (unsigned)V;
1412     assert(BitPos < sizeof(unsigned) * CHAR_BIT &&
1413            "enum exceeds width of bit vector!");
1414     return 1 << BitPos;
1415   }
1416
1417 public:
1418   template <class T> void addValue(const T &V) { Bits |= Bit(V); }
1419
1420   unsigned getBits() { return Bits; }
1421
1422   template <class T> bool isSet(const T &V) { return (Bits & Bit(V)) != 0; }
1423 };
1424
1425 //===----------------------------------------------------------------------===//
1426 // bits - A bit vector of command options.
1427 //
1428 template <class DataType, class Storage = bool,
1429           class ParserClass = parser<DataType>>
1430 class bits : public Option, public bits_storage<DataType, Storage> {
1431   std::vector<unsigned> Positions;
1432   ParserClass Parser;
1433
1434   enum ValueExpected getValueExpectedFlagDefault() const override {
1435     return Parser.getValueExpectedFlagDefault();
1436   }
1437   void
1438   getExtraOptionNames(SmallVectorImpl<const char *> &OptionNames) override {
1439     return Parser.getExtraOptionNames(OptionNames);
1440   }
1441
1442   bool handleOccurrence(unsigned pos, StringRef ArgName,
1443                         StringRef Arg) override {
1444     typename ParserClass::parser_data_type Val =
1445         typename ParserClass::parser_data_type();
1446     if (Parser.parse(*this, ArgName, Arg, Val))
1447       return true; // Parse Error!
1448     this->addValue(Val);
1449     setPosition(pos);
1450     Positions.push_back(pos);
1451     return false;
1452   }
1453
1454   // Forward printing stuff to the parser...
1455   size_t getOptionWidth() const override {
1456     return Parser.getOptionWidth(*this);
1457   }
1458   void printOptionInfo(size_t GlobalWidth) const override {
1459     Parser.printOptionInfo(*this, GlobalWidth);
1460   }
1461
1462   // Unimplemented: bits options don't currently store their default values.
1463   void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override {
1464   }
1465
1466   void done() {
1467     addArgument();
1468     Parser.initialize();
1469   }
1470
1471   // Command line options should not be copyable
1472   bits(const bits &) = delete;
1473   bits &operator=(const bits &) = delete;
1474
1475 public:
1476   ParserClass &getParser() { return Parser; }
1477
1478   unsigned getPosition(unsigned optnum) const {
1479     assert(optnum < this->size() && "Invalid option index");
1480     return Positions[optnum];
1481   }
1482
1483   template <class... Mods>
1484   explicit bits(const Mods &... Ms)
1485       : Option(ZeroOrMore, NotHidden), Parser(*this) {
1486     apply(this, Ms...);
1487     done();
1488   }
1489 };
1490
1491 //===----------------------------------------------------------------------===//
1492 // Aliased command line option (alias this name to a preexisting name)
1493 //
1494
1495 class alias : public Option {
1496   Option *AliasFor;
1497   bool handleOccurrence(unsigned pos, StringRef /*ArgName*/,
1498                         StringRef Arg) override {
1499     return AliasFor->handleOccurrence(pos, AliasFor->ArgStr, Arg);
1500   }
1501   bool addOccurrence(unsigned pos, StringRef /*ArgName*/, StringRef Value,
1502                      bool MultiArg = false) override {
1503     return AliasFor->addOccurrence(pos, AliasFor->ArgStr, Value, MultiArg);
1504   }
1505   // Handle printing stuff...
1506   size_t getOptionWidth() const override;
1507   void printOptionInfo(size_t GlobalWidth) const override;
1508
1509   // Aliases do not need to print their values.
1510   void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override {
1511   }
1512
1513   ValueExpected getValueExpectedFlagDefault() const override {
1514     return AliasFor->getValueExpectedFlag();
1515   }
1516
1517   void done() {
1518     if (!hasArgStr())
1519       error("cl::alias must have argument name specified!");
1520     if (!AliasFor)
1521       error("cl::alias must have an cl::aliasopt(option) specified!");
1522     addArgument();
1523   }
1524
1525   // Command line options should not be copyable
1526   alias(const alias &) = delete;
1527   alias &operator=(const alias &) = delete;
1528
1529 public:
1530   void setAliasFor(Option &O) {
1531     if (AliasFor)
1532       error("cl::alias must only have one cl::aliasopt(...) specified!");
1533     AliasFor = &O;
1534   }
1535
1536   template <class... Mods>
1537   explicit alias(const Mods &... Ms)
1538       : Option(Optional, Hidden), AliasFor(nullptr) {
1539     apply(this, Ms...);
1540     done();
1541   }
1542 };
1543
1544 // aliasfor - Modifier to set the option an alias aliases.
1545 struct aliasopt {
1546   Option &Opt;
1547   explicit aliasopt(Option &O) : Opt(O) {}
1548   void apply(alias &A) const { A.setAliasFor(Opt); }
1549 };
1550
1551 // extrahelp - provide additional help at the end of the normal help
1552 // output. All occurrences of cl::extrahelp will be accumulated and
1553 // printed to stderr at the end of the regular help, just before
1554 // exit is called.
1555 struct extrahelp {
1556   const char *morehelp;
1557   explicit extrahelp(const char *help);
1558 };
1559
1560 void PrintVersionMessage();
1561
1562 /// This function just prints the help message, exactly the same way as if the
1563 /// -help or -help-hidden option had been given on the command line.
1564 ///
1565 /// NOTE: THIS FUNCTION TERMINATES THE PROGRAM!
1566 ///
1567 /// \param Hidden if true will print hidden options
1568 /// \param Categorized if true print options in categories
1569 void PrintHelpMessage(bool Hidden = false, bool Categorized = false);
1570
1571 //===----------------------------------------------------------------------===//
1572 // Public interface for accessing registered options.
1573 //
1574
1575 /// \brief Use this to get a StringMap to all registered named options
1576 /// (e.g. -help). Note \p Map Should be an empty StringMap.
1577 ///
1578 /// \return A reference to the StringMap used by the cl APIs to parse options.
1579 ///
1580 /// Access to unnamed arguments (i.e. positional) are not provided because
1581 /// it is expected that the client already has access to these.
1582 ///
1583 /// Typical usage:
1584 /// \code
1585 /// main(int argc,char* argv[]) {
1586 /// StringMap<llvm::cl::Option*> &opts = llvm::cl::getRegisteredOptions();
1587 /// assert(opts.count("help") == 1)
1588 /// opts["help"]->setDescription("Show alphabetical help information")
1589 /// // More code
1590 /// llvm::cl::ParseCommandLineOptions(argc,argv);
1591 /// //More code
1592 /// }
1593 /// \endcode
1594 ///
1595 /// This interface is useful for modifying options in libraries that are out of
1596 /// the control of the client. The options should be modified before calling
1597 /// llvm::cl::ParseCommandLineOptions().
1598 ///
1599 /// Hopefully this API can be depricated soon. Any situation where options need
1600 /// to be modified by tools or libraries should be handled by sane APIs rather
1601 /// than just handing around a global list.
1602 StringMap<Option *> &getRegisteredOptions();
1603
1604 //===----------------------------------------------------------------------===//
1605 // Standalone command line processing utilities.
1606 //
1607
1608 /// \brief Saves strings in the inheritor's stable storage and returns a stable
1609 /// raw character pointer.
1610 class StringSaver {
1611   virtual void anchor();
1612
1613 public:
1614   virtual const char *SaveString(const char *Str) = 0;
1615   virtual ~StringSaver(){}; // Pacify -Wnon-virtual-dtor.
1616 };
1617
1618 /// \brief Tokenizes a command line that can contain escapes and quotes.
1619 //
1620 /// The quoting rules match those used by GCC and other tools that use
1621 /// libiberty's buildargv() or expandargv() utilities, and do not match bash.
1622 /// They differ from buildargv() on treatment of backslashes that do not escape
1623 /// a special character to make it possible to accept most Windows file paths.
1624 ///
1625 /// \param [in] Source The string to be split on whitespace with quotes.
1626 /// \param [in] Saver Delegates back to the caller for saving parsed strings.
1627 /// \param [in] MarkEOLs true if tokenizing a response file and you want end of
1628 /// lines and end of the response file to be marked with a nullptr string.
1629 /// \param [out] NewArgv All parsed strings are appended to NewArgv.
1630 void TokenizeGNUCommandLine(StringRef Source, StringSaver &Saver,
1631                             SmallVectorImpl<const char *> &NewArgv,
1632                             bool MarkEOLs = false);
1633
1634 /// \brief Tokenizes a Windows command line which may contain quotes and escaped
1635 /// quotes.
1636 ///
1637 /// See MSDN docs for CommandLineToArgvW for information on the quoting rules.
1638 /// http://msdn.microsoft.com/en-us/library/windows/desktop/17w5ykft(v=vs.85).aspx
1639 ///
1640 /// \param [in] Source The string to be split on whitespace with quotes.
1641 /// \param [in] Saver Delegates back to the caller for saving parsed strings.
1642 /// \param [in] MarkEOLs true if tokenizing a response file and you want end of
1643 /// lines and end of the response file to be marked with a nullptr string.
1644 /// \param [out] NewArgv All parsed strings are appended to NewArgv.
1645 void TokenizeWindowsCommandLine(StringRef Source, StringSaver &Saver,
1646                                 SmallVectorImpl<const char *> &NewArgv,
1647                                 bool MarkEOLs = false);
1648
1649 /// \brief String tokenization function type.  Should be compatible with either
1650 /// Windows or Unix command line tokenizers.
1651 typedef void (*TokenizerCallback)(StringRef Source, StringSaver &Saver,
1652                                   SmallVectorImpl<const char *> &NewArgv,
1653                                   bool MarkEOLs);
1654
1655 /// \brief Expand response files on a command line recursively using the given
1656 /// StringSaver and tokenization strategy.  Argv should contain the command line
1657 /// before expansion and will be modified in place. If requested, Argv will
1658 /// also be populated with nullptrs indicating where each response file line
1659 /// ends, which is useful for the "/link" argument that needs to consume all
1660 /// remaining arguments only until the next end of line, when in a response
1661 /// file.
1662 ///
1663 /// \param [in] Saver Delegates back to the caller for saving parsed strings.
1664 /// \param [in] Tokenizer Tokenization strategy. Typically Unix or Windows.
1665 /// \param [in,out] Argv Command line into which to expand response files.
1666 /// \param [in] MarkEOLs Mark end of lines and the end of the response file
1667 /// with nullptrs in the Argv vector.
1668 /// \return true if all @files were expanded successfully or there were none.
1669 bool ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
1670                          SmallVectorImpl<const char *> &Argv,
1671                          bool MarkEOLs = false);
1672
1673 /// \brief Mark all options not part of this category as cl::ReallyHidden.
1674 ///
1675 /// \param Category the category of options to keep displaying
1676 ///
1677 /// Some tools (like clang-format) like to be able to hide all options that are
1678 /// not specific to the tool. This function allows a tool to specify a single
1679 /// option category to display in the -help output.
1680 void HideUnrelatedOptions(cl::OptionCategory &Category);
1681
1682 /// \brief Mark all options not part of the categories as cl::ReallyHidden.
1683 ///
1684 /// \param Categories the categories of options to keep displaying.
1685 ///
1686 /// Some tools (like clang-format) like to be able to hide all options that are
1687 /// not specific to the tool. This function allows a tool to specify a single
1688 /// option category to display in the -help output.
1689 void HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories);
1690
1691 } // End namespace cl
1692
1693 } // End namespace llvm
1694
1695 #endif