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