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