LLVM 22.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/StringMap.h"
27#include "llvm/ADT/StringRef.h"
28#include "llvm/ADT/Twine.h"
34#include <cassert>
35#include <climits>
36#include <cstddef>
37#include <functional>
38#include <initializer_list>
39#include <string>
40#include <type_traits>
41#include <vector>
42
43namespace llvm {
44
45namespace vfs {
46class FileSystem;
47}
48
49class StringSaver;
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 : NumOccurrences(0), Occurrences(OccurrencesFlag), Value(0),
340 HiddenFlag(Hidden), Formatting(NormalFormatting), Misc(0),
341 FullyInitialized(false), Position(0), AdditionalVals(0) {
342 Categories.push_back(&getGeneralCategory());
343 }
344
345 inline void setNumAdditionalVals(unsigned n) { AdditionalVals = n; }
346
347public:
348 virtual ~Option() = default;
349
350 // Register this argument with the commandline system.
351 //
352 void addArgument();
353
354 /// Unregisters this option from the CommandLine system.
355 ///
356 /// This option must have been the last option registered.
357 /// For testing purposes only.
358 void removeArgument();
359
360 // Return the width of the option tag for printing...
361 virtual size_t getOptionWidth() const = 0;
362
363 // Print out information about this option. The to-be-maintained width is
364 // specified.
365 //
366 virtual void printOptionInfo(size_t GlobalWidth) const = 0;
367
368 virtual void printOptionValue(size_t GlobalWidth, bool Force) const = 0;
369
370 virtual void setDefault() = 0;
371
372 // Prints the help string for an option.
373 //
374 // This maintains the Indent for multi-line descriptions.
375 // FirstLineIndentedBy is the count of chars of the first line
376 // i.e. the one containing the --<option name>.
377 static void printHelpStr(StringRef HelpStr, size_t Indent,
378 size_t FirstLineIndentedBy);
379
380 // Prints the help string for an enum value.
381 //
382 // This maintains the Indent for multi-line descriptions.
383 // FirstLineIndentedBy is the count of chars of the first line
384 // i.e. the one containing the =<value>.
385 static void printEnumValHelpStr(StringRef HelpStr, size_t Indent,
386 size_t FirstLineIndentedBy);
387
389
390 // Wrapper around handleOccurrence that enforces Flags.
391 //
392 virtual bool addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
393 bool MultiArg = false);
394
395 // Prints option name followed by message. Always returns true.
396 bool error(const Twine &Message, StringRef ArgName = StringRef(), raw_ostream &Errs = llvm::errs());
397 bool error(const Twine &Message, raw_ostream &Errs) {
398 return error(Message, StringRef(), Errs);
399 }
400
401 inline int getNumOccurrences() const { return NumOccurrences; }
402 void reset();
403};
404
405//===----------------------------------------------------------------------===//
406// Command line option modifiers that can be used to modify the behavior of
407// command line option parsers...
408//
409
410// Modifier to set the description shown in the -help output...
411struct desc {
413
414 desc(StringRef Str) : Desc(Str) {}
415
416 void apply(Option &O) const { O.setDescription(Desc); }
417};
418
419// Modifier to set the value description shown in the -help output...
422
423 value_desc(StringRef Str) : Desc(Str) {}
424
425 void apply(Option &O) const { O.setValueStr(Desc); }
426};
427
428// Specify a default (initial) value for the command line argument, if the
429// default constructor for the argument type does not give you what you want.
430// This is only valid on "opt" arguments, not on "list" arguments.
431template <class Ty> struct initializer {
432 const Ty &Init;
433 initializer(const Ty &Val) : Init(Val) {}
434
435 template <class Opt> void apply(Opt &O) const { O.setInitialValue(Init); }
436};
437
438template <class Ty> struct list_initializer {
441
442 template <class Opt> void apply(Opt &O) const { O.setInitialValues(Inits); }
443};
444
445template <class Ty> initializer<Ty> init(const Ty &Val) {
446 return initializer<Ty>(Val);
447}
448
449template <class Ty>
453
454// Allow the user to specify which external variable they want to store the
455// results of the command line argument processing into, if they don't want to
456// store it in the option itself.
457template <class Ty> struct LocationClass {
458 Ty &Loc;
459
460 LocationClass(Ty &L) : Loc(L) {}
461
462 template <class Opt> void apply(Opt &O) const { O.setLocation(O, Loc); }
463};
464
465template <class Ty> LocationClass<Ty> location(Ty &L) {
466 return LocationClass<Ty>(L);
467}
468
469// Specify the Option category for the command line argument to belong to.
470struct cat {
472
474
475 template <class Opt> void apply(Opt &O) const { O.addCategory(Category); }
476};
477
478// Specify the subcommand that this option belongs to.
479struct sub {
480 SubCommand *Sub = nullptr;
482
483 sub(SubCommand &S) : Sub(&S) {}
485
486 template <class Opt> void apply(Opt &O) const {
487 if (Sub)
488 O.addSubCommand(*Sub);
489 else if (Group)
490 for (SubCommand *SC : Group->getSubCommands())
491 O.addSubCommand(*SC);
492 }
493};
494
495// Specify a callback function to be called when an option is seen.
496// Can be used to set other options automatically.
497template <typename R, typename Ty> struct cb {
498 std::function<R(Ty)> CB;
499
500 cb(std::function<R(Ty)> CB) : CB(CB) {}
501
502 template <typename Opt> void apply(Opt &O) const { O.setCallback(CB); }
503};
504
505namespace detail {
506template <typename F>
507struct callback_traits : public callback_traits<decltype(&F::operator())> {};
508
509template <typename R, typename C, typename... Args>
510struct callback_traits<R (C::*)(Args...) const> {
511 using result_type = R;
512 using arg_type = std::tuple_element_t<0, std::tuple<Args...>>;
513 static_assert(sizeof...(Args) == 1, "callback function must have one and only one parameter");
514 static_assert(std::is_same_v<result_type, void>,
515 "callback return type must be void");
516 static_assert(std::is_lvalue_reference_v<arg_type> &&
517 std::is_const_v<std::remove_reference_t<arg_type>>,
518 "callback arg_type must be a const lvalue reference");
519};
520} // namespace detail
521
522template <typename F>
526 using result_type = typename detail::callback_traits<F>::result_type;
527 using arg_type = typename detail::callback_traits<F>::arg_type;
528 return cb<result_type, arg_type>(CB);
529}
530
531//===----------------------------------------------------------------------===//
532
533// Support value comparison outside the template.
535 virtual bool compare(const GenericOptionValue &V) const = 0;
536
537protected:
542
543private:
544 virtual void anchor();
545};
546
547template <class DataType> struct OptionValue;
548
549// The default value safely does nothing. Option value printing is only
550// best-effort.
551template <class DataType, bool isClass>
553 // Temporary storage for argument passing.
555
556 bool hasValue() const { return false; }
557
558 const DataType &getValue() const { llvm_unreachable("no default value"); }
559
560 // Some options may take their value from a different data type.
561 template <class DT> void setValue(const DT & /*V*/) {}
562
563 // Returns whether this instance matches the argument.
564 bool compare(const DataType & /*V*/) const { return false; }
565
566 bool compare(const GenericOptionValue & /*V*/) const override {
567 return false;
568 }
569
570protected:
571 ~OptionValueBase() = default;
572};
573
574// Simple copy of the option value.
575template <class DataType> class OptionValueCopy : public GenericOptionValue {
576 DataType Value;
577 bool Valid = false;
578
579protected:
582 ~OptionValueCopy() = default;
583
584public:
585 OptionValueCopy() = default;
586
587 bool hasValue() const { return Valid; }
588
589 const DataType &getValue() const {
590 assert(Valid && "invalid option value");
591 return Value;
592 }
593
594 void setValue(const DataType &V) {
595 Valid = true;
596 Value = V;
597 }
598
599 // Returns whether this instance matches V.
600 bool compare(const DataType &V) const { return Valid && (Value == V); }
601
602 bool compare(const GenericOptionValue &V) const override {
603 const OptionValueCopy<DataType> &VC =
604 static_cast<const OptionValueCopy<DataType> &>(V);
605 if (!VC.hasValue())
606 return false;
607 return compare(VC.getValue());
608 }
609};
610
611// Non-class option values.
612template <class DataType>
613struct OptionValueBase<DataType, false> : OptionValueCopy<DataType> {
614 using WrapperType = DataType;
615
616protected:
617 OptionValueBase() = default;
620 ~OptionValueBase() = default;
621};
622
623// Top-level option class.
624template <class DataType>
625struct OptionValue final
626 : OptionValueBase<DataType, std::is_class_v<DataType>> {
627 OptionValue() = default;
628
629 OptionValue(const DataType &V) { this->setValue(V); }
630
631 // Some options may take their value from a different data type.
632 template <class DT> OptionValue<DataType> &operator=(const DT &V) {
633 this->setValue(V);
634 return *this;
635 }
636};
637
638// Other safe-to-copy-by-value common option types.
640template <>
642 : OptionValueCopy<cl::boolOrDefault> {
644
645 OptionValue() = default;
646
647 OptionValue(const cl::boolOrDefault &V) { this->setValue(V); }
648
650 setValue(V);
651 return *this;
652 }
653
654private:
655 void anchor() override;
656};
657
658template <>
659struct LLVM_ABI OptionValue<std::string> final : OptionValueCopy<std::string> {
661
662 OptionValue() = default;
663
664 OptionValue(const std::string &V) { this->setValue(V); }
665
666 OptionValue<std::string> &operator=(const std::string &V) {
667 setValue(V);
668 return *this;
669 }
670
671private:
672 void anchor() override;
673};
674
675//===----------------------------------------------------------------------===//
676// Enum valued command line option
677//
678
679// This represents a single enum value, using "int" as the underlying type.
685
686#define clEnumVal(ENUMVAL, DESC) \
687 llvm::cl::OptionEnumValue { #ENUMVAL, int(ENUMVAL), DESC }
688#define clEnumValN(ENUMVAL, FLAGNAME, DESC) \
689 llvm::cl::OptionEnumValue { FLAGNAME, int(ENUMVAL), DESC }
690
691// For custom data types, allow specifying a group of values together as the
692// values that go into the mapping that the option handler uses.
693//
695 // Use a vector instead of a map, because the lists should be short,
696 // the overhead is less, and most importantly, it keeps them in the order
697 // inserted so we can print our option out nicely.
699
700public:
701 ValuesClass(std::initializer_list<OptionEnumValue> Options)
702 : Values(Options) {}
703
704 template <class Opt> void apply(Opt &O) const {
705 for (const auto &Value : Values)
706 O.getParser().addLiteralOption(Value.Name, Value.Value,
707 Value.Description);
708 }
709};
710
711/// Helper to build a ValuesClass by forwarding a variable number of arguments
712/// as an initializer list to the ValuesClass constructor.
713template <typename... OptsTy> ValuesClass values(OptsTy... Options) {
714 return ValuesClass({Options...});
715}
716
717//===----------------------------------------------------------------------===//
718// Parameterizable parser for different data types. By default, known data types
719// (string, int, bool) have specialized parsers, that do what you would expect.
720// The default parser, used for data types that are not built-in, uses a mapping
721// table to map specific options to values, which is used, among other things,
722// to handle enum types.
723
724//--------------------------------------------------
725// This class holds all the non-generic code that we do not need replicated for
726// every instance of the generic parser. This also allows us to put stuff into
727// CommandLine.cpp
728//
730protected:
738
739public:
741
742 virtual ~generic_parser_base() = default;
743 // Base class should have virtual-destructor
744
745 // Virtual function implemented by generic subclass to indicate how many
746 // entries are in Values.
747 //
748 virtual unsigned getNumOptions() const = 0;
749
750 // Return option name N.
751 virtual StringRef getOption(unsigned N) const = 0;
752
753 // Return description N
754 virtual StringRef getDescription(unsigned N) const = 0;
755
756 // Return the width of the option tag for printing...
757 virtual size_t getOptionWidth(const Option &O) const;
758
759 virtual const GenericOptionValue &getOptionValue(unsigned N) const = 0;
760
761 // Print out information about this option. The to-be-maintained width is
762 // specified.
763 //
764 virtual void printOptionInfo(const Option &O, size_t GlobalWidth) const;
765
766 void printGenericOptionDiff(const Option &O, const GenericOptionValue &V,
768 size_t GlobalWidth) const;
769
770 // Print the value of an option and it's default.
771 //
772 // Template definition ensures that the option and default have the same
773 // DataType (via the same AnyOptionValue).
774 template <class AnyOptionValue>
775 void printOptionDiff(const Option &O, const AnyOptionValue &V,
776 const AnyOptionValue &Default,
777 size_t GlobalWidth) const {
778 printGenericOptionDiff(O, V, Default, GlobalWidth);
779 }
780
781 void initialize() {}
782
784 // If there has been no argstr specified, that means that we need to add an
785 // argument for every possible option. This ensures that our options are
786 // vectored to us.
787 if (!Owner.hasArgStr())
788 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
789 OptionNames.push_back(getOption(i));
790 }
791
793 // If there is an ArgStr specified, then we are of the form:
794 //
795 // -opt=O2 or -opt O2 or -optO2
796 //
797 // In which case, the value is required. Otherwise if an arg str has not
798 // been specified, we are of the form:
799 //
800 // -O2 or O2 or -la (where -l and -a are separate options)
801 //
802 // If this is the case, we cannot allow a value.
803 //
804 if (Owner.hasArgStr())
805 return ValueRequired;
806 else
807 return ValueDisallowed;
808 }
809
810 // Return the option number corresponding to the specified
811 // argument string. If the option is not found, getNumOptions() is returned.
812 //
813 unsigned findOption(StringRef Name);
814
815protected:
817};
818
819// Default parser implementation - This implementation depends on having a
820// mapping of recognized options to values of some sort. In addition to this,
821// each entry in the mapping also tracks a help message that is printed with the
822// command line option for -help. Because this is a simple mapping parser, the
823// data type can be any unsupported type.
824//
825template <class DataType> class parser : public generic_parser_base {
826protected:
828 public:
829 OptionInfo(StringRef name, DataType v, StringRef helpStr)
830 : GenericOptionInfo(name, helpStr), V(v) {}
831
833 };
835
836public:
838
839 using parser_data_type = DataType;
840
841 // Implement virtual functions needed by generic_parser_base
842 unsigned getNumOptions() const override { return unsigned(Values.size()); }
843 StringRef getOption(unsigned N) const override { return Values[N].Name; }
844 StringRef getDescription(unsigned N) const override {
845 return Values[N].HelpStr;
846 }
847
848 // Return the value of option name N.
849 const GenericOptionValue &getOptionValue(unsigned N) const override {
850 return Values[N].V;
851 }
852
853 // Return true on error.
854 bool parse(Option &O, StringRef ArgName, StringRef Arg, DataType &V) {
855 StringRef ArgVal;
856 if (Owner.hasArgStr())
857 ArgVal = Arg;
858 else
859 ArgVal = ArgName;
860
861 for (size_t i = 0, e = Values.size(); i != e; ++i)
862 if (Values[i].Name == ArgVal) {
863 V = Values[i].V.getValue();
864 return false;
865 }
866
867 return O.error("Cannot find option named '" + ArgVal + "'!");
868 }
869
870 /// Add an entry to the mapping table.
871 ///
872 template <class DT>
873 void addLiteralOption(StringRef Name, const DT &V, StringRef HelpStr) {
874#ifndef NDEBUG
875 if (findOption(Name) != Values.size())
876 report_fatal_error("Option '" + Name + "' already exists!");
877#endif
878 OptionInfo X(Name, static_cast<DataType>(V), HelpStr);
879 Values.push_back(X);
880 AddLiteralOption(Owner, Name);
881 }
882
883 /// Remove the specified option.
884 ///
886 unsigned N = findOption(Name);
887 assert(N != Values.size() && "Option not found!");
888 Values.erase(Values.begin() + N);
889 }
890};
891
892//--------------------------------------------------
893// Super class of parsers to provide boilerplate code
894//
896 basic_parser_impl { // non-template implementation of basic_parser<t>
897public:
899
900 virtual ~basic_parser_impl() = default;
901
905
907
908 void initialize() {}
909
910 // Return the width of the option tag for printing...
911 size_t getOptionWidth(const Option &O) const;
912
913 // Print out information about this option. The to-be-maintained width is
914 // specified.
915 //
916 void printOptionInfo(const Option &O, size_t GlobalWidth) const;
917
918 // Print a placeholder for options that don't yet support printOptionDiff().
919 void printOptionNoValue(const Option &O, size_t GlobalWidth) const;
920
921 // Overload in subclass to provide a better default value.
922 virtual StringRef getValueName() const { return "value"; }
923
924 // An out-of-line virtual method to provide a 'home' for this class.
925 virtual void anchor();
926
927protected:
928 // A helper for basic_parser::printOptionDiff.
929 void printOptionName(const Option &O, size_t GlobalWidth) const;
930};
931
932// The real basic parser is just a template wrapper that provides a typedef for
933// the provided data type.
934//
935template <class DataType> class basic_parser : public basic_parser_impl {
936public:
937 using parser_data_type = DataType;
939
941};
942
943//--------------------------------------------------
944
945extern template class LLVM_TEMPLATE_ABI basic_parser<bool>;
946
947template <> class LLVM_ABI parser<bool> : public basic_parser<bool> {
948public:
950
951 // Return true on error.
952 bool parse(Option &O, StringRef ArgName, StringRef Arg, bool &Val);
953
954 void initialize() {}
955
959
960 // Do not print =<value> at all.
961 StringRef getValueName() const override { return StringRef(); }
962
963 void printOptionDiff(const Option &O, bool V, OptVal Default,
964 size_t GlobalWidth) const;
965
966 // An out-of-line virtual method to provide a 'home' for this class.
967 void anchor() override;
968};
969
970//--------------------------------------------------
971
973
974template <>
976public:
978
979 // Return true on error.
980 bool parse(Option &O, StringRef ArgName, StringRef Arg, boolOrDefault &Val);
981
985
986 // Do not print =<value> at all.
987 StringRef getValueName() const override { return StringRef(); }
988
990 size_t GlobalWidth) const;
991
992 // An out-of-line virtual method to provide a 'home' for this class.
993 void anchor() override;
994};
995
996//--------------------------------------------------
997
998extern template class LLVM_TEMPLATE_ABI basic_parser<int>;
999
1000template <> class LLVM_ABI parser<int> : public basic_parser<int> {
1001public:
1003
1004 // Return true on error.
1005 bool parse(Option &O, StringRef ArgName, StringRef Arg, int &Val);
1006
1007 // Overload in subclass to provide a better default value.
1008 StringRef getValueName() const override { return "int"; }
1009
1010 void printOptionDiff(const Option &O, int V, OptVal Default,
1011 size_t GlobalWidth) const;
1012
1013 // An out-of-line virtual method to provide a 'home' for this class.
1014 void anchor() override;
1015};
1016
1017//--------------------------------------------------
1018
1019extern template class LLVM_TEMPLATE_ABI basic_parser<long>;
1020
1021template <> class LLVM_ABI parser<long> final : public basic_parser<long> {
1022public:
1024
1025 // Return true on error.
1026 bool parse(Option &O, StringRef ArgName, StringRef Arg, long &Val);
1027
1028 // Overload in subclass to provide a better default value.
1029 StringRef getValueName() const override { return "long"; }
1030
1031 void printOptionDiff(const Option &O, long V, OptVal Default,
1032 size_t GlobalWidth) const;
1033
1034 // An out-of-line virtual method to provide a 'home' for this class.
1035 void anchor() override;
1036};
1037
1038//--------------------------------------------------
1039
1040extern template class LLVM_TEMPLATE_ABI basic_parser<long long>;
1041
1043public:
1045
1046 // Return true on error.
1047 bool parse(Option &O, StringRef ArgName, StringRef Arg, long long &Val);
1048
1049 // Overload in subclass to provide a better default value.
1050 StringRef getValueName() const override { return "long"; }
1051
1052 void printOptionDiff(const Option &O, long long V, OptVal Default,
1053 size_t GlobalWidth) const;
1054
1055 // An out-of-line virtual method to provide a 'home' for this class.
1056 void anchor() override;
1057};
1058
1059//--------------------------------------------------
1060
1061extern template class LLVM_TEMPLATE_ABI basic_parser<unsigned>;
1062
1064public:
1066
1067 // Return true on error.
1068 bool parse(Option &O, StringRef ArgName, StringRef Arg, unsigned &Val);
1069
1070 // Overload in subclass to provide a better default value.
1071 StringRef getValueName() const override { return "uint"; }
1072
1073 void printOptionDiff(const Option &O, unsigned V, OptVal Default,
1074 size_t GlobalWidth) const;
1075
1076 // An out-of-line virtual method to provide a 'home' for this class.
1077 void anchor() override;
1078};
1079
1080//--------------------------------------------------
1081
1083
1084template <>
1087public:
1089
1090 // Return true on error.
1091 bool parse(Option &O, StringRef ArgName, StringRef Arg, unsigned long &Val);
1092
1093 // Overload in subclass to provide a better default value.
1094 StringRef getValueName() const override { return "ulong"; }
1095
1096 void printOptionDiff(const Option &O, unsigned long V, OptVal Default,
1097 size_t GlobalWidth) const;
1098
1099 // An out-of-line virtual method to provide a 'home' for this class.
1100 void anchor() override;
1101};
1102
1103//--------------------------------------------------
1104
1106
1107template <>
1110public:
1112
1113 // Return true on error.
1114 bool parse(Option &O, StringRef ArgName, StringRef Arg,
1115 unsigned long long &Val);
1116
1117 // Overload in subclass to provide a better default value.
1118 StringRef getValueName() const override { return "ulong"; }
1119
1120 void printOptionDiff(const Option &O, unsigned long long V, OptVal Default,
1121 size_t GlobalWidth) const;
1122
1123 // An out-of-line virtual method to provide a 'home' for this class.
1124 void anchor() override;
1125};
1126
1127//--------------------------------------------------
1128
1129extern template class LLVM_TEMPLATE_ABI basic_parser<double>;
1130
1132public:
1134
1135 // Return true on error.
1136 bool parse(Option &O, StringRef ArgName, StringRef Arg, double &Val);
1137
1138 // Overload in subclass to provide a better default value.
1139 StringRef getValueName() const override { return "number"; }
1140
1141 void printOptionDiff(const Option &O, double V, OptVal Default,
1142 size_t GlobalWidth) const;
1143
1144 // An out-of-line virtual method to provide a 'home' for this class.
1145 void anchor() override;
1146};
1147
1148//--------------------------------------------------
1149
1150extern template class LLVM_TEMPLATE_ABI basic_parser<float>;
1151
1152template <> class LLVM_ABI parser<float> : public basic_parser<float> {
1153public:
1155
1156 // Return true on error.
1157 bool parse(Option &O, StringRef ArgName, StringRef Arg, float &Val);
1158
1159 // Overload in subclass to provide a better default value.
1160 StringRef getValueName() const override { return "number"; }
1161
1162 void printOptionDiff(const Option &O, float V, OptVal Default,
1163 size_t GlobalWidth) const;
1164
1165 // An out-of-line virtual method to provide a 'home' for this class.
1166 void anchor() override;
1167};
1168
1169//--------------------------------------------------
1170
1171extern template class LLVM_TEMPLATE_ABI basic_parser<std::string>;
1172
1173template <>
1175public:
1177
1178 // Return true on error.
1179 bool parse(Option &, StringRef, StringRef Arg, std::string &Value) {
1180 Value = Arg.str();
1181 return false;
1182 }
1183
1184 // Overload in subclass to provide a better default value.
1185 StringRef getValueName() const override { return "string"; }
1186
1188 size_t GlobalWidth) const;
1189
1190 // An out-of-line virtual method to provide a 'home' for this class.
1191 void anchor() override;
1192};
1193
1194//--------------------------------------------------
1195
1196template <>
1199public:
1201
1202 // Return true on error.
1204 std::optional<std::string> &Value) {
1205 Value = Arg.str();
1206 return false;
1207 }
1208
1209 // Overload in subclass to provide a better default value.
1210 StringRef getValueName() const override { return "optional string"; }
1211
1212 void printOptionDiff(const Option &O, std::optional<StringRef> V,
1213 const OptVal &Default, size_t GlobalWidth) const;
1214
1215 // An out-of-line virtual method to provide a 'home' for this class.
1216 void anchor() override;
1217};
1218
1219//--------------------------------------------------
1220
1221extern template class LLVM_TEMPLATE_ABI basic_parser<char>;
1222
1223template <> class LLVM_ABI parser<char> : public basic_parser<char> {
1224public:
1226
1227 // Return true on error.
1228 bool parse(Option &, StringRef, StringRef Arg, char &Value) {
1229 Value = Arg[0];
1230 return false;
1231 }
1232
1233 // Overload in subclass to provide a better default value.
1234 StringRef getValueName() const override { return "char"; }
1235
1236 void printOptionDiff(const Option &O, char V, OptVal Default,
1237 size_t GlobalWidth) const;
1238
1239 // An out-of-line virtual method to provide a 'home' for this class.
1240 void anchor() override;
1241};
1242
1243//--------------------------------------------------
1244// This collection of wrappers is the intermediary between class opt and class
1245// parser to handle all the template nastiness.
1246
1247// This overloaded function is selected by the generic parser.
1248template <class ParserClass, class DT>
1249void printOptionDiff(const Option &O, const generic_parser_base &P, const DT &V,
1250 const OptionValue<DT> &Default, size_t GlobalWidth) {
1251 OptionValue<DT> OV = V;
1252 P.printOptionDiff(O, OV, Default, GlobalWidth);
1253}
1254
1255// This is instantiated for basic parsers when the parsed value has a different
1256// type than the option value. e.g. HelpPrinter.
1257template <class ParserDT, class ValDT> struct OptionDiffPrinter {
1258 void print(const Option &O, const parser<ParserDT> &P, const ValDT & /*V*/,
1259 const OptionValue<ValDT> & /*Default*/, size_t GlobalWidth) {
1260 P.printOptionNoValue(O, GlobalWidth);
1261 }
1262};
1263
1264// This is instantiated for basic parsers when the parsed value has the same
1265// type as the option value.
1266template <class DT> struct OptionDiffPrinter<DT, DT> {
1267 void print(const Option &O, const parser<DT> &P, const DT &V,
1268 const OptionValue<DT> &Default, size_t GlobalWidth) {
1269 P.printOptionDiff(O, V, Default, GlobalWidth);
1270 }
1271};
1272
1273// This overloaded function is selected by the basic parser, which may parse a
1274// different type than the option type.
1275template <class ParserClass, class ValDT>
1277 const Option &O,
1279 const ValDT &V, const OptionValue<ValDT> &Default, size_t GlobalWidth) {
1280
1282 printer.print(O, static_cast<const ParserClass &>(P), V, Default,
1283 GlobalWidth);
1284}
1285
1286//===----------------------------------------------------------------------===//
1287// This class is used because we must use partial specialization to handle
1288// literal string arguments specially (const char* does not correctly respond to
1289// the apply method). Because the syntax to use this is a pain, we have the
1290// 'apply' method below to handle the nastiness...
1291//
1292template <class Mod> struct applicator {
1293 template <class Opt> static void opt(const Mod &M, Opt &O) { M.apply(O); }
1294};
1295
1296// Handle const char* as a special case...
1297template <unsigned n> struct applicator<char[n]> {
1298 template <class Opt> static void opt(StringRef Str, Opt &O) {
1299 O.setArgStr(Str);
1300 }
1301};
1302template <unsigned n> struct applicator<const char[n]> {
1303 template <class Opt> static void opt(StringRef Str, Opt &O) {
1304 O.setArgStr(Str);
1305 }
1306};
1307template <> struct applicator<StringRef > {
1308 template <class Opt> static void opt(StringRef Str, Opt &O) {
1309 O.setArgStr(Str);
1310 }
1311};
1312
1314 static void opt(NumOccurrencesFlag N, Option &O) {
1315 O.setNumOccurrencesFlag(N);
1316 }
1317};
1318
1319template <> struct applicator<ValueExpected> {
1320 static void opt(ValueExpected VE, Option &O) { O.setValueExpectedFlag(VE); }
1321};
1322
1323template <> struct applicator<OptionHidden> {
1324 static void opt(OptionHidden OH, Option &O) { O.setHiddenFlag(OH); }
1325};
1326
1328 static void opt(FormattingFlags FF, Option &O) { O.setFormattingFlag(FF); }
1329};
1330
1331template <> struct applicator<MiscFlags> {
1332 static void opt(MiscFlags MF, Option &O) {
1333 assert((MF != Grouping || O.ArgStr.size() == 1) &&
1334 "cl::Grouping can only apply to single character Options.");
1335 O.setMiscFlag(MF);
1336 }
1337};
1338
1339// Apply modifiers to an option in a type safe way.
1340template <class Opt, class Mod, class... Mods>
1341void apply(Opt *O, const Mod &M, const Mods &... Ms) {
1342 applicator<Mod>::opt(M, *O);
1343 apply(O, Ms...);
1344}
1345
1346template <class Opt, class Mod> void apply(Opt *O, const Mod &M) {
1347 applicator<Mod>::opt(M, *O);
1348}
1349
1350//===----------------------------------------------------------------------===//
1351// Default storage class definition: external storage. This implementation
1352// assumes the user will specify a variable to store the data into with the
1353// cl::location(x) modifier.
1354//
1355template <class DataType, bool ExternalStorage, bool isClass>
1357 DataType *Location = nullptr; // Where to store the object...
1358 OptionValue<DataType> Default;
1359
1360 void check_location() const {
1361 assert(Location && "cl::location(...) not specified for a command "
1362 "line option with external storage, "
1363 "or cl::init specified before cl::location()!!");
1364 }
1365
1366public:
1367 opt_storage() = default;
1368
1369 bool setLocation(Option &O, DataType &L) {
1370 if (Location)
1371 return O.error("cl::location(x) specified more than once!");
1372 Location = &L;
1373 Default = L;
1374 return false;
1375 }
1376
1377 template <class T> void setValue(const T &V, bool initial = false) {
1378 check_location();
1379 *Location = V;
1380 if (initial)
1381 Default = V;
1382 }
1383
1384 DataType &getValue() {
1385 check_location();
1386 return *Location;
1387 }
1388 const DataType &getValue() const {
1389 check_location();
1390 return *Location;
1391 }
1392
1393 operator DataType() const { return this->getValue(); }
1394
1395 const OptionValue<DataType> &getDefault() const { return Default; }
1396};
1397
1398// Define how to hold a class type object, such as a string. Since we can
1399// inherit from a class, we do so. This makes us exactly compatible with the
1400// object in all cases that it is used.
1401//
1402template <class DataType>
1403class opt_storage<DataType, false, true> : public DataType {
1404public:
1406
1407 template <class T> void setValue(const T &V, bool initial = false) {
1408 DataType::operator=(V);
1409 if (initial)
1410 Default = V;
1411 }
1412
1413 DataType &getValue() { return *this; }
1414 const DataType &getValue() const { return *this; }
1415
1416 const OptionValue<DataType> &getDefault() const { return Default; }
1417};
1418
1419// Define a partial specialization to handle things we cannot inherit from. In
1420// this case, we store an instance through containment, and overload operators
1421// to get at the value.
1422//
1423template <class DataType> class opt_storage<DataType, false, false> {
1424public:
1425 DataType Value;
1427
1428 // Make sure we initialize the value with the default constructor for the
1429 // type.
1430 opt_storage() : Value(DataType()), Default() {}
1431
1432 template <class T> void setValue(const T &V, bool initial = false) {
1433 Value = V;
1434 if (initial)
1435 Default = V;
1436 }
1437 DataType &getValue() { return Value; }
1438 DataType getValue() const { return Value; }
1439
1440 const OptionValue<DataType> &getDefault() const { return Default; }
1441
1442 operator DataType() const { return getValue(); }
1443
1444 // If the datatype is a pointer, support -> on it.
1445 DataType operator->() const { return Value; }
1446};
1447
1448//===----------------------------------------------------------------------===//
1449// A scalar command line option.
1450//
1451template <class DataType, bool ExternalStorage = false,
1452 class ParserClass = parser<DataType>>
1453class opt
1454 : public Option,
1455 public opt_storage<DataType, ExternalStorage, std::is_class_v<DataType>> {
1456 ParserClass Parser;
1457
1458 bool handleOccurrence(unsigned pos, StringRef ArgName,
1459 StringRef Arg) override {
1460 typename ParserClass::parser_data_type Val =
1461 typename ParserClass::parser_data_type();
1462 if (Parser.parse(*this, ArgName, Arg, Val))
1463 return true; // Parse error!
1464 this->setValue(Val);
1465 this->setPosition(pos);
1466 Callback(Val);
1467 return false;
1468 }
1469
1470 enum ValueExpected getValueExpectedFlagDefault() const override {
1471 return Parser.getValueExpectedFlagDefault();
1472 }
1473
1474 void getExtraOptionNames(SmallVectorImpl<StringRef> &OptionNames) override {
1475 return Parser.getExtraOptionNames(OptionNames);
1476 }
1477
1478 // Forward printing stuff to the parser...
1479 size_t getOptionWidth() const override {
1480 return Parser.getOptionWidth(*this);
1481 }
1482
1483 void printOptionInfo(size_t GlobalWidth) const override {
1484 Parser.printOptionInfo(*this, GlobalWidth);
1485 }
1486
1487 void printOptionValue(size_t GlobalWidth, bool Force) const override {
1488 if (Force || !this->getDefault().compare(this->getValue())) {
1489 cl::printOptionDiff<ParserClass>(*this, Parser, this->getValue(),
1490 this->getDefault(), GlobalWidth);
1491 }
1492 }
1493
1494 void setDefault() override {
1495 if constexpr (std::is_assignable_v<DataType &, DataType>) {
1496 const OptionValue<DataType> &V = this->getDefault();
1497 if (V.hasValue())
1498 this->setValue(V.getValue());
1499 else
1500 this->setValue(DataType());
1501 }
1502 }
1503
1504 void done() {
1505 addArgument();
1506 Parser.initialize();
1507 }
1508
1509public:
1510 // Command line options should not be copyable
1511 opt(const opt &) = delete;
1512 opt &operator=(const opt &) = delete;
1513
1514 // setInitialValue - Used by the cl::init modifier...
1515 void setInitialValue(const DataType &V) { this->setValue(V, true); }
1516
1517 ParserClass &getParser() { return Parser; }
1518
1519 template <class T> DataType &operator=(const T &Val) {
1520 this->setValue(Val);
1521 Callback(Val);
1522 return this->getValue();
1523 }
1524
1525 template <class T> DataType &operator=(T &&Val) {
1526 this->getValue() = std::forward<T>(Val);
1527 Callback(this->getValue());
1528 return this->getValue();
1529 }
1530
1531 template <class... Mods>
1532 explicit opt(const Mods &... Ms)
1533 : Option(llvm::cl::Optional, NotHidden), Parser(*this) {
1534 apply(this, Ms...);
1535 done();
1536 }
1537
1539 std::function<void(const typename ParserClass::parser_data_type &)> CB) {
1540 Callback = CB;
1541 }
1542
1543 std::function<void(const typename ParserClass::parser_data_type &)> Callback =
1544 [](const typename ParserClass::parser_data_type &) {};
1545};
1546
1547#if !(defined(LLVM_ENABLE_LLVM_EXPORT_ANNOTATIONS) && defined(_MSC_VER))
1548// Only instantiate opt<std::string> when not building a Windows DLL. When
1549// exporting opt<std::string>, MSVC implicitly exports symbols for
1550// std::basic_string through transitive inheritance via std::string. These
1551// symbols may appear in clients, leading to duplicate symbol conflicts.
1552extern template class LLVM_TEMPLATE_ABI opt<std::string>;
1553#endif
1554
1555extern template class LLVM_TEMPLATE_ABI opt<unsigned>;
1556extern template class LLVM_TEMPLATE_ABI opt<int>;
1557extern template class LLVM_TEMPLATE_ABI opt<char>;
1558extern template class LLVM_TEMPLATE_ABI opt<bool>;
1559
1560//===----------------------------------------------------------------------===//
1561// Default storage class definition: external storage. This implementation
1562// assumes the user will specify a variable to store the data into with the
1563// cl::location(x) modifier.
1564//
1565template <class DataType, class StorageClass> class list_storage {
1566 StorageClass *Location = nullptr; // Where to store the object...
1567 std::vector<OptionValue<DataType>> Default =
1568 std::vector<OptionValue<DataType>>();
1569 bool DefaultAssigned = false;
1570
1571public:
1572 list_storage() = default;
1573
1574 void clear() {}
1575
1577 if (Location)
1578 return O.error("cl::location(x) specified more than once!");
1579 Location = &L;
1580 return false;
1581 }
1582
1583 template <class T> void addValue(const T &V, bool initial = false) {
1584 assert(Location != nullptr &&
1585 "cl::location(...) not specified for a command "
1586 "line option with external storage!");
1587 Location->push_back(V);
1588 if (initial)
1589 Default.push_back(V);
1590 }
1591
1592 const std::vector<OptionValue<DataType>> &getDefault() const {
1593 return Default;
1594 }
1595
1596 void assignDefault() { DefaultAssigned = true; }
1597 void overwriteDefault() { DefaultAssigned = false; }
1598 bool isDefaultAssigned() { return DefaultAssigned; }
1599};
1600
1601// Define how to hold a class type object, such as a string.
1602// Originally this code inherited from std::vector. In transitioning to a new
1603// API for command line options we should change this. The new implementation
1604// of this list_storage specialization implements the minimum subset of the
1605// std::vector API required for all the current clients.
1606//
1607// FIXME: Reduce this API to a more narrow subset of std::vector
1608//
1609template <class DataType> class list_storage<DataType, bool> {
1610 std::vector<DataType> Storage;
1611 std::vector<OptionValue<DataType>> Default;
1612 bool DefaultAssigned = false;
1613
1614public:
1615 using iterator = typename std::vector<DataType>::iterator;
1616
1617 iterator begin() { return Storage.begin(); }
1618 iterator end() { return Storage.end(); }
1619
1620 using const_iterator = typename std::vector<DataType>::const_iterator;
1621
1622 const_iterator begin() const { return Storage.begin(); }
1623 const_iterator end() const { return Storage.end(); }
1624
1625 using size_type = typename std::vector<DataType>::size_type;
1626
1627 size_type size() const { return Storage.size(); }
1628
1629 bool empty() const { return Storage.empty(); }
1630
1631 void push_back(const DataType &value) { Storage.push_back(value); }
1632 void push_back(DataType &&value) { Storage.push_back(value); }
1633
1634 using reference = typename std::vector<DataType>::reference;
1635 using const_reference = typename std::vector<DataType>::const_reference;
1636
1637 reference operator[](size_type pos) { return Storage[pos]; }
1638 const_reference operator[](size_type pos) const { return Storage[pos]; }
1639
1640 void clear() {
1641 Storage.clear();
1642 }
1643
1644 iterator erase(const_iterator pos) { return Storage.erase(pos); }
1646 return Storage.erase(first, last);
1647 }
1648
1649 iterator erase(iterator pos) { return Storage.erase(pos); }
1651 return Storage.erase(first, last);
1652 }
1653
1654 iterator insert(const_iterator pos, const DataType &value) {
1655 return Storage.insert(pos, value);
1656 }
1657 iterator insert(const_iterator pos, DataType &&value) {
1658 return Storage.insert(pos, value);
1659 }
1660
1661 iterator insert(iterator pos, const DataType &value) {
1662 return Storage.insert(pos, value);
1663 }
1664 iterator insert(iterator pos, DataType &&value) {
1665 return Storage.insert(pos, value);
1666 }
1667
1668 reference front() { return Storage.front(); }
1669 const_reference front() const { return Storage.front(); }
1670
1671 operator std::vector<DataType> &() { return Storage; }
1672 operator ArrayRef<DataType>() const { return Storage; }
1673 std::vector<DataType> *operator&() { return &Storage; }
1674 const std::vector<DataType> *operator&() const { return &Storage; }
1675
1676 template <class T> void addValue(const T &V, bool initial = false) {
1677 Storage.push_back(V);
1678 if (initial)
1679 Default.push_back(OptionValue<DataType>(V));
1680 }
1681
1682 const std::vector<OptionValue<DataType>> &getDefault() const {
1683 return Default;
1684 }
1685
1686 void assignDefault() { DefaultAssigned = true; }
1687 void overwriteDefault() { DefaultAssigned = false; }
1688 bool isDefaultAssigned() { return DefaultAssigned; }
1689};
1690
1691//===----------------------------------------------------------------------===//
1692// A list of command line options.
1693//
1694template <class DataType, class StorageClass = bool,
1695 class ParserClass = parser<DataType>>
1696class list : public Option, public list_storage<DataType, StorageClass> {
1697 std::vector<unsigned> Positions;
1698 ParserClass Parser;
1699
1700 enum ValueExpected getValueExpectedFlagDefault() const override {
1701 return Parser.getValueExpectedFlagDefault();
1702 }
1703
1704 void getExtraOptionNames(SmallVectorImpl<StringRef> &OptionNames) override {
1705 return Parser.getExtraOptionNames(OptionNames);
1706 }
1707
1708 bool handleOccurrence(unsigned pos, StringRef ArgName,
1709 StringRef Arg) override {
1710 typename ParserClass::parser_data_type Val =
1711 typename ParserClass::parser_data_type();
1713 clear();
1715 }
1716 if (Parser.parse(*this, ArgName, Arg, Val))
1717 return true; // Parse Error!
1719 setPosition(pos);
1720 Positions.push_back(pos);
1721 Callback(Val);
1722 return false;
1723 }
1724
1725 // Forward printing stuff to the parser...
1726 size_t getOptionWidth() const override {
1727 return Parser.getOptionWidth(*this);
1728 }
1729
1730 void printOptionInfo(size_t GlobalWidth) const override {
1731 Parser.printOptionInfo(*this, GlobalWidth);
1732 }
1733
1734 // Unimplemented: list options don't currently store their default value.
1735 void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override {
1736 }
1737
1738 void setDefault() override {
1739 Positions.clear();
1743 }
1744
1745 void done() {
1746 addArgument();
1747 Parser.initialize();
1748 }
1749
1750public:
1751 // Command line options should not be copyable
1752 list(const list &) = delete;
1753 list &operator=(const list &) = delete;
1754
1755 ParserClass &getParser() { return Parser; }
1756
1757 unsigned getPosition(unsigned optnum) const {
1758 assert(optnum < this->size() && "Invalid option index");
1759 return Positions[optnum];
1760 }
1761
1762 void clear() {
1763 Positions.clear();
1765 }
1766
1767 // setInitialValues - Used by the cl::list_init modifier...
1775
1777
1778 template <class... Mods>
1779 explicit list(const Mods &... Ms)
1780 : Option(ZeroOrMore, NotHidden), Parser(*this) {
1781 apply(this, Ms...);
1782 done();
1783 }
1784
1786 std::function<void(const typename ParserClass::parser_data_type &)> CB) {
1787 Callback = CB;
1788 }
1789
1790 std::function<void(const typename ParserClass::parser_data_type &)> Callback =
1791 [](const typename ParserClass::parser_data_type &) {};
1792};
1793
1794// Modifier to set the number of additional values.
1797 explicit multi_val(unsigned N) : AdditionalVals(N) {}
1798
1799 template <typename D, typename S, typename P>
1800 void apply(list<D, S, P> &L) const {
1801 L.setNumAdditionalVals(AdditionalVals);
1802 }
1803};
1804
1805//===----------------------------------------------------------------------===//
1806// Default storage class definition: external storage. This implementation
1807// assumes the user will specify a variable to store the data into with the
1808// cl::location(x) modifier.
1809//
1810template <class DataType, class StorageClass> class bits_storage {
1811 unsigned *Location = nullptr; // Where to store the bits...
1812
1813 template <class T> static unsigned Bit(const T &V) {
1814 unsigned BitPos = static_cast<unsigned>(V);
1815 assert(BitPos < sizeof(unsigned) * CHAR_BIT &&
1816 "enum exceeds width of bit vector!");
1817 return 1 << BitPos;
1818 }
1819
1820public:
1821 bits_storage() = default;
1822
1823 bool setLocation(Option &O, unsigned &L) {
1824 if (Location)
1825 return O.error("cl::location(x) specified more than once!");
1826 Location = &L;
1827 return false;
1828 }
1829
1830 template <class T> void addValue(const T &V) {
1831 assert(Location != nullptr &&
1832 "cl::location(...) not specified for a command "
1833 "line option with external storage!");
1834 *Location |= Bit(V);
1835 }
1836
1837 unsigned getBits() { return *Location; }
1838
1839 void clear() {
1840 if (Location)
1841 *Location = 0;
1842 }
1843
1844 template <class T> bool isSet(const T &V) {
1845 return (*Location & Bit(V)) != 0;
1846 }
1847};
1848
1849// Define how to hold bits. Since we can inherit from a class, we do so.
1850// This makes us exactly compatible with the bits in all cases that it is used.
1851//
1852template <class DataType> class bits_storage<DataType, bool> {
1853 unsigned Bits{0}; // Where to store the bits...
1854
1855 template <class T> static unsigned Bit(const T &V) {
1856 unsigned BitPos = static_cast<unsigned>(V);
1857 assert(BitPos < sizeof(unsigned) * CHAR_BIT &&
1858 "enum exceeds width of bit vector!");
1859 return 1 << BitPos;
1860 }
1861
1862public:
1863 template <class T> void addValue(const T &V) { Bits |= Bit(V); }
1864
1865 unsigned getBits() { return Bits; }
1866
1867 void clear() { Bits = 0; }
1868
1869 template <class T> bool isSet(const T &V) { return (Bits & Bit(V)) != 0; }
1870};
1871
1872//===----------------------------------------------------------------------===//
1873// A bit vector of command options.
1874//
1875template <class DataType, class Storage = bool,
1876 class ParserClass = parser<DataType>>
1877class bits : public Option, public bits_storage<DataType, Storage> {
1878 std::vector<unsigned> Positions;
1879 ParserClass Parser;
1880
1881 enum ValueExpected getValueExpectedFlagDefault() const override {
1882 return Parser.getValueExpectedFlagDefault();
1883 }
1884
1885 void getExtraOptionNames(SmallVectorImpl<StringRef> &OptionNames) override {
1886 return Parser.getExtraOptionNames(OptionNames);
1887 }
1888
1889 bool handleOccurrence(unsigned pos, StringRef ArgName,
1890 StringRef Arg) override {
1891 typename ParserClass::parser_data_type Val =
1892 typename ParserClass::parser_data_type();
1893 if (Parser.parse(*this, ArgName, Arg, Val))
1894 return true; // Parse Error!
1895 this->addValue(Val);
1896 setPosition(pos);
1897 Positions.push_back(pos);
1898 Callback(Val);
1899 return false;
1900 }
1901
1902 // Forward printing stuff to the parser...
1903 size_t getOptionWidth() const override {
1904 return Parser.getOptionWidth(*this);
1905 }
1906
1907 void printOptionInfo(size_t GlobalWidth) const override {
1908 Parser.printOptionInfo(*this, GlobalWidth);
1909 }
1910
1911 // Unimplemented: bits options don't currently store their default values.
1912 void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override {
1913 }
1914
1916
1917 void done() {
1918 addArgument();
1919 Parser.initialize();
1920 }
1921
1922public:
1923 // Command line options should not be copyable
1924 bits(const bits &) = delete;
1925 bits &operator=(const bits &) = delete;
1926
1927 ParserClass &getParser() { return Parser; }
1928
1929 unsigned getPosition(unsigned optnum) const {
1930 assert(optnum < this->size() && "Invalid option index");
1931 return Positions[optnum];
1932 }
1933
1934 template <class... Mods>
1935 explicit bits(const Mods &... Ms)
1936 : Option(ZeroOrMore, NotHidden), Parser(*this) {
1937 apply(this, Ms...);
1938 done();
1939 }
1940
1942 std::function<void(const typename ParserClass::parser_data_type &)> CB) {
1943 Callback = CB;
1944 }
1945
1946 std::function<void(const typename ParserClass::parser_data_type &)> Callback =
1947 [](const typename ParserClass::parser_data_type &) {};
1948};
1949
1950//===----------------------------------------------------------------------===//
1951// Aliased command line option (alias this name to a preexisting name)
1952//
1953
1954class LLVM_ABI alias : public Option {
1955 Option *AliasFor;
1956
1957 bool handleOccurrence(unsigned pos, StringRef /*ArgName*/,
1958 StringRef Arg) override {
1959 return AliasFor->handleOccurrence(pos, AliasFor->ArgStr, Arg);
1960 }
1961
1962 bool addOccurrence(unsigned pos, StringRef /*ArgName*/, StringRef Value,
1963 bool MultiArg = false) override {
1964 return AliasFor->addOccurrence(pos, AliasFor->ArgStr, Value, MultiArg);
1965 }
1966
1967 // Handle printing stuff...
1968 size_t getOptionWidth() const override;
1969 void printOptionInfo(size_t GlobalWidth) const override;
1970
1971 // Aliases do not need to print their values.
1972 void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override {
1973 }
1974
1975 void setDefault() override { AliasFor->setDefault(); }
1976
1977 ValueExpected getValueExpectedFlagDefault() const override {
1978 return AliasFor->getValueExpectedFlag();
1979 }
1980
1981 void done() {
1982 if (!hasArgStr())
1983 error("cl::alias must have argument name specified!");
1984 if (!AliasFor)
1985 error("cl::alias must have an cl::aliasopt(option) specified!");
1986 if (!Subs.empty())
1987 error("cl::alias must not have cl::sub(), aliased option's cl::sub() will be used!");
1988 Subs = AliasFor->Subs;
1989 Categories = AliasFor->Categories;
1990 addArgument();
1991 }
1992
1993public:
1994 // Command line options should not be copyable
1995 alias(const alias &) = delete;
1996 alias &operator=(const alias &) = delete;
1997
1999 if (AliasFor)
2000 error("cl::alias must only have one cl::aliasopt(...) specified!");
2001 AliasFor = &O;
2002 }
2003
2004 template <class... Mods>
2005 explicit alias(const Mods &... Ms)
2006 : Option(Optional, Hidden), AliasFor(nullptr) {
2007 apply(this, Ms...);
2008 done();
2009 }
2010};
2011
2012// Modifier to set the option an alias aliases.
2013struct aliasopt {
2015
2016 explicit aliasopt(Option &O) : Opt(O) {}
2017
2018 void apply(alias &A) const { A.setAliasFor(Opt); }
2019};
2020
2021// Provide additional help at the end of the normal help output. All occurrences
2022// of cl::extrahelp will be accumulated and printed to stderr at the end of the
2023// regular help, just before exit is called.
2026
2027 LLVM_ABI explicit extrahelp(StringRef help);
2028};
2029
2031
2032/// This function just prints the help message, exactly the same way as if the
2033/// -help or -help-hidden option had been given on the command line.
2034///
2035/// \param Hidden if true will print hidden options
2036/// \param Categorized if true print options in categories
2037LLVM_ABI void PrintHelpMessage(bool Hidden = false, bool Categorized = false);
2038
2039/// An array of optional enabled settings in the LLVM build configuration,
2040/// which may be of interest to compiler developers. For example, includes
2041/// "+assertions" if assertions are enabled. Used by printBuildConfig.
2043
2044/// Prints the compiler build configuration.
2045/// Designed for compiler developers, not compiler end-users.
2046/// Intended to be used in --version output when enabled.
2048
2049//===----------------------------------------------------------------------===//
2050// Public interface for accessing registered options.
2051//
2052
2053/// Use this to get a StringMap to all registered named options
2054/// (e.g. -help).
2055///
2056/// \return A reference to the StringMap used by the cl APIs to parse options.
2057///
2058/// Access to unnamed arguments (i.e. positional) are not provided because
2059/// it is expected that the client already has access to these.
2060///
2061/// Typical usage:
2062/// \code
2063/// main(int argc,char* argv[]) {
2064/// StringMap<llvm::cl::Option*> &opts = llvm::cl::getRegisteredOptions();
2065/// assert(opts.count("help") == 1)
2066/// opts["help"]->setDescription("Show alphabetical help information")
2067/// // More code
2068/// llvm::cl::ParseCommandLineOptions(argc,argv);
2069/// //More code
2070/// }
2071/// \endcode
2072///
2073/// This interface is useful for modifying options in libraries that are out of
2074/// the control of the client. The options should be modified before calling
2075/// llvm::cl::ParseCommandLineOptions().
2076///
2077/// Hopefully this API can be deprecated soon. Any situation where options need
2078/// to be modified by tools or libraries should be handled by sane APIs rather
2079/// than just handing around a global list.
2082
2083/// Use this to get all registered SubCommands from the provided parser.
2084///
2085/// \return A range of all SubCommand pointers registered with the parser.
2086///
2087/// Typical usage:
2088/// \code
2089/// main(int argc, char* argv[]) {
2090/// llvm::cl::ParseCommandLineOptions(argc, argv);
2091/// for (auto* S : llvm::cl::getRegisteredSubcommands()) {
2092/// if (*S) {
2093/// std::cout << "Executing subcommand: " << S->getName() << std::endl;
2094/// // Execute some function based on the name...
2095/// }
2096/// }
2097/// }
2098/// \endcode
2099///
2100/// This interface is useful for defining subcommands in libraries and
2101/// the dispatch from a single point (like in the main function).
2104
2105//===----------------------------------------------------------------------===//
2106// Standalone command line processing utilities.
2107//
2108
2109/// Tokenizes a command line that can contain escapes and quotes.
2110//
2111/// The quoting rules match those used by GCC and other tools that use
2112/// libiberty's buildargv() or expandargv() utilities, and do not match bash.
2113/// They differ from buildargv() on treatment of backslashes that do not escape
2114/// a special character to make it possible to accept most Windows file paths.
2115///
2116/// \param [in] Source The string to be split on whitespace with quotes.
2117/// \param [in] Saver Delegates back to the caller for saving parsed strings.
2118/// \param [in] MarkEOLs true if tokenizing a response file and you want end of
2119/// lines and end of the response file to be marked with a nullptr string.
2120/// \param [out] NewArgv All parsed strings are appended to NewArgv.
2123 bool MarkEOLs = false);
2124
2125/// Tokenizes a string of Windows command line arguments, which may contain
2126/// quotes and escaped quotes.
2127///
2128/// See MSDN docs for CommandLineToArgvW for information on the quoting rules.
2129/// http://msdn.microsoft.com/en-us/library/windows/desktop/17w5ykft(v=vs.85).aspx
2130///
2131/// For handling a full Windows command line including the executable name at
2132/// the start, see TokenizeWindowsCommandLineFull below.
2133///
2134/// \param [in] Source The string to be split on whitespace with quotes.
2135/// \param [in] Saver Delegates back to the caller for saving parsed strings.
2136/// \param [in] MarkEOLs true if tokenizing a response file and you want end of
2137/// lines and end of the response file to be marked with a nullptr string.
2138/// \param [out] NewArgv All parsed strings are appended to NewArgv.
2141 bool MarkEOLs = false);
2142
2143/// Tokenizes a Windows command line while attempting to avoid copies. If no
2144/// quoting or escaping was used, this produces substrings of the original
2145/// string. If a token requires unquoting, it will be allocated with the
2146/// StringSaver.
2147LLVM_ABI void
2150
2151/// Tokenizes a Windows full command line, including command name at the start.
2152///
2153/// This uses the same syntax rules as TokenizeWindowsCommandLine for all but
2154/// the first token. But the first token is expected to be parsed as the
2155/// executable file name in the way CreateProcess would do it, rather than the
2156/// way the C library startup code would do it: CreateProcess does not consider
2157/// that \ is ever an escape character (because " is not a valid filename char,
2158/// hence there's never a need to escape it to be used literally).
2159///
2160/// Parameters are the same as for TokenizeWindowsCommandLine. In particular,
2161/// if you set MarkEOLs = true, then the first word of every line will be
2162/// parsed using the special rules for command names, making this function
2163/// suitable for parsing a file full of commands to execute.
2164LLVM_ABI void
2167 bool MarkEOLs = false);
2168
2169/// String tokenization function type. Should be compatible with either
2170/// Windows or Unix command line tokenizers.
2171using TokenizerCallback = void (*)(StringRef Source, StringSaver &Saver,
2173 bool MarkEOLs);
2174
2175/// Tokenizes content of configuration file.
2176///
2177/// \param [in] Source The string representing content of config file.
2178/// \param [in] Saver Delegates back to the caller for saving parsed strings.
2179/// \param [out] NewArgv All parsed strings are appended to NewArgv.
2180/// \param [in] MarkEOLs Added for compatibility with TokenizerCallback.
2181///
2182/// It works like TokenizeGNUCommandLine with ability to skip comment lines.
2183///
2186 bool MarkEOLs = false);
2187
2188/// Contains options that control response file expansion.
2190 /// Provides persistent storage for parsed strings.
2191 StringSaver Saver;
2192
2193 /// Tokenization strategy. Typically Unix or Windows.
2194 TokenizerCallback Tokenizer;
2195
2196 /// File system used for all file access when running the expansion.
2197 vfs::FileSystem *FS;
2198
2199 /// Path used to resolve relative rsp files. If empty, the file system
2200 /// current directory is used instead.
2201 StringRef CurrentDir;
2202
2203 /// Directories used for search of config files.
2204 ArrayRef<StringRef> SearchDirs;
2205
2206 /// True if names of nested response files must be resolved relative to
2207 /// including file.
2208 bool RelativeNames = false;
2209
2210 /// If true, mark end of lines and the end of the response file with nullptrs
2211 /// in the Argv vector.
2212 bool MarkEOLs = false;
2213
2214 /// If true, body of config file is expanded.
2215 bool InConfigFile = false;
2216
2217 llvm::Error expandResponseFile(StringRef FName,
2219
2220public:
2222 vfs::FileSystem *FS = nullptr);
2223
2225 MarkEOLs = X;
2226 return *this;
2227 }
2228
2230 RelativeNames = X;
2231 return *this;
2232 }
2233
2235 CurrentDir = X;
2236 return *this;
2237 }
2238
2240 SearchDirs = X;
2241 return *this;
2242 }
2243
2245 FS = X;
2246 return *this;
2247 }
2248
2249 /// Looks for the specified configuration file.
2250 ///
2251 /// \param[in] FileName Name of the file to search for.
2252 /// \param[out] FilePath File absolute path, if it was found.
2253 /// \return True if file was found.
2254 ///
2255 /// If the specified file name contains a directory separator, it is searched
2256 /// for by its absolute path. Otherwise looks for file sequentially in
2257 /// directories specified by SearchDirs field.
2258 LLVM_ABI bool findConfigFile(StringRef FileName,
2259 SmallVectorImpl<char> &FilePath);
2260
2261 /// Reads command line options from the given configuration file.
2262 ///
2263 /// \param [in] CfgFile Path to configuration file.
2264 /// \param [out] Argv Array to which the read options are added.
2265 /// \return true if the file was successfully read.
2266 ///
2267 /// It reads content of the specified file, tokenizes it and expands "@file"
2268 /// commands resolving file names in them relative to the directory where
2269 /// CfgFilename resides. It also expands "<CFGDIR>" to the base path of the
2270 /// current config file.
2273
2274 /// Expands constructs "@file" in the provided array of arguments recursively.
2276};
2277
2278/// A convenience helper which concatenates the options specified by the
2279/// environment variable EnvVar and command line options, then expands
2280/// response files recursively.
2281/// \return true if all @files were expanded successfully or there were none.
2282LLVM_ABI bool expandResponseFiles(int Argc, const char *const *Argv,
2283 const char *EnvVar,
2285
2286/// A convenience helper which supports the typical use case of expansion
2287/// function call.
2289 TokenizerCallback Tokenizer,
2291
2292/// A convenience helper which concatenates the options specified by the
2293/// environment variable EnvVar and command line options, then expands response
2294/// files recursively. The tokenizer is a predefined GNU or Windows one.
2295/// \return true if all @files were expanded successfully or there were none.
2296LLVM_ABI bool expandResponseFiles(int Argc, const char *const *Argv,
2297 const char *EnvVar, StringSaver &Saver,
2299
2300/// Mark all options not part of this category as cl::ReallyHidden.
2301///
2302/// \param Category the category of options to keep displaying
2303///
2304/// Some tools (like clang-format) like to be able to hide all options that are
2305/// not specific to the tool. This function allows a tool to specify a single
2306/// option category to display in the -help output.
2309
2310/// Mark all options not part of the categories as cl::ReallyHidden.
2311///
2312/// \param Categories the categories of options to keep displaying.
2313///
2314/// Some tools (like clang-format) like to be able to hide all options that are
2315/// not specific to the tool. This function allows a tool to specify a single
2316/// option category to display in the -help output.
2317LLVM_ABI void
2320
2321/// Reset all command line options to a state that looks as if they have
2322/// never appeared on the command line. This is useful for being able to parse
2323/// a command line multiple times (especially useful for writing tests).
2325
2326/// Reset the command line parser back to its initial state. This
2327/// removes
2328/// all options, categories, and subcommands and returns the parser to a state
2329/// where no options are supported.
2331
2332/// Parses `Arg` into the option handler `Handler`.
2333LLVM_ABI bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i);
2334
2335} // end namespace cl
2336
2337} // end namespace llvm
2338
2339#endif // LLVM_SUPPORT_COMMANDLINE_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
This file defines the StringMap class.
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
#define LLVM_ABI
Definition Compiler.h:213
#define LLVM_TEMPLATE_ABI
Definition Compiler.h:214
dxil pretty printer
global merge func
static LVOptions Options
Definition LVOptions.cpp:25
#define F(x, y, z)
Definition MD5.cpp:55
#define G(x, y, z)
Definition MD5.cpp:56
#define T
#define P(N)
static const char * name
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
#define error(X)
static TableGen::Emitter::OptClass< SkeletonEmitter > X("gen-skeleton-class", "Generate example skeleton class")
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:41
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.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition StringMap.h:133
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
std::string str() const
str - Get the contents as an std::string.
Definition StringRef.h:225
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:53
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.
Option(enum NumOccurrencesFlag OccurrencesFlag, enum OptionHidden Hidden)
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
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()
LLVM_ABI void registerSubCommand()
SmallVector< Option *, 4 > PositionalOpts
StringMap< Option * > OptionsMap
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
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 CommandLine.h:53
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 StringMap< Option * > & getRegisteredOptions(SubCommand &Sub=SubCommand::getTopLevel())
Use this to get a StringMap to all registered named options (e.g.
LLVM_ABI void ResetCommandLineParser()
Reset the command line parser back to its initial state.
LLVM_ABI void PrintOptionValues()
LLVM_ABI iterator_range< typename SmallPtrSet< SubCommand *, 4 >::iterator > getRegisteredSubcommands()
Use this to get all registered SubCommands from the provided parser.
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:1657
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:167
BumpPtrAllocatorImpl BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition Allocator.h:383
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 >
@ Default
The result values are 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:851
#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)