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