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