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