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