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