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