1 //===-- CommandLine.cpp - Command line parser implementation --------------===//
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
7 //===----------------------------------------------------------------------===//
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.
13 // Note that rather than trying to figure out what this code does, you could try
14 // reading the library documentation located in docs/CommandLine.html
16 //===----------------------------------------------------------------------===//
18 #include "llvm/Support/CommandLine.h"
20 #include "DebugOptions.h"
22 #include "llvm-c/Support.h"
23 #include "llvm/ADT/ArrayRef.h"
24 #include "llvm/ADT/STLFunctionalExtras.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include "llvm/ADT/SmallString.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/ADT/StringMap.h"
29 #include "llvm/ADT/StringRef.h"
30 #include "llvm/ADT/Twine.h"
31 #include "llvm/Config/config.h"
32 #include "llvm/Support/ConvertUTF.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/Error.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/FileSystem.h"
37 #include "llvm/Support/ManagedStatic.h"
38 #include "llvm/Support/MemoryBuffer.h"
39 #include "llvm/Support/Path.h"
40 #include "llvm/Support/Process.h"
41 #include "llvm/Support/StringSaver.h"
42 #include "llvm/Support/VirtualFileSystem.h"
43 #include "llvm/Support/raw_ostream.h"
50 #define DEBUG_TYPE "commandline"
52 //===----------------------------------------------------------------------===//
53 // Template instantiations and anchors.
57 template class basic_parser
<bool>;
58 template class basic_parser
<boolOrDefault
>;
59 template class basic_parser
<int>;
60 template class basic_parser
<long>;
61 template class basic_parser
<long long>;
62 template class basic_parser
<unsigned>;
63 template class basic_parser
<unsigned long>;
64 template class basic_parser
<unsigned long long>;
65 template class basic_parser
<double>;
66 template class basic_parser
<float>;
67 template class basic_parser
<std::string
>;
68 template class basic_parser
<char>;
70 template class opt
<unsigned>;
71 template class opt
<int>;
72 template class opt
<std::string
>;
73 template class opt
<char>;
74 template class opt
<bool>;
78 // Pin the vtables to this file.
79 void GenericOptionValue::anchor() {}
80 void OptionValue
<boolOrDefault
>::anchor() {}
81 void OptionValue
<std::string
>::anchor() {}
82 void Option::anchor() {}
83 void basic_parser_impl::anchor() {}
84 void parser
<bool>::anchor() {}
85 void parser
<boolOrDefault
>::anchor() {}
86 void parser
<int>::anchor() {}
87 void parser
<long>::anchor() {}
88 void parser
<long long>::anchor() {}
89 void parser
<unsigned>::anchor() {}
90 void parser
<unsigned long>::anchor() {}
91 void parser
<unsigned long long>::anchor() {}
92 void parser
<double>::anchor() {}
93 void parser
<float>::anchor() {}
94 void parser
<std::string
>::anchor() {}
95 void parser
<char>::anchor() {}
97 //===----------------------------------------------------------------------===//
99 const static size_t DefaultPad
= 2;
101 static StringRef ArgPrefix
= "-";
102 static StringRef ArgPrefixLong
= "--";
103 static StringRef ArgHelpPrefix
= " - ";
105 static size_t argPlusPrefixesSize(StringRef ArgName
, size_t Pad
= DefaultPad
) {
106 size_t Len
= ArgName
.size();
108 return Len
+ Pad
+ ArgPrefix
.size() + ArgHelpPrefix
.size();
109 return Len
+ Pad
+ ArgPrefixLong
.size() + ArgHelpPrefix
.size();
112 static SmallString
<8> argPrefix(StringRef ArgName
, size_t Pad
= DefaultPad
) {
113 SmallString
<8> Prefix
;
114 for (size_t I
= 0; I
< Pad
; ++I
) {
115 Prefix
.push_back(' ');
117 Prefix
.append(ArgName
.size() > 1 ? ArgPrefixLong
: ArgPrefix
);
121 // Option predicates...
122 static inline bool isGrouping(const Option
*O
) {
123 return O
->getMiscFlags() & cl::Grouping
;
125 static inline bool isPrefixedOrGrouping(const Option
*O
) {
126 return isGrouping(O
) || O
->getFormattingFlag() == cl::Prefix
||
127 O
->getFormattingFlag() == cl::AlwaysPrefix
;
137 PrintArg(StringRef ArgName
, size_t Pad
= DefaultPad
) : ArgName(ArgName
), Pad(Pad
) {}
138 friend raw_ostream
&operator<<(raw_ostream
&OS
, const PrintArg
&);
141 raw_ostream
&operator<<(raw_ostream
&OS
, const PrintArg
& Arg
) {
142 OS
<< argPrefix(Arg
.ArgName
, Arg
.Pad
) << Arg
.ArgName
;
146 class CommandLineParser
{
148 // Globals for name and overview of program. Program name is not a string to
149 // avoid static ctor/dtor issues.
150 std::string ProgramName
;
151 StringRef ProgramOverview
;
153 // This collects additional help to be printed.
154 std::vector
<StringRef
> MoreHelp
;
156 // This collects Options added with the cl::DefaultOption flag. Since they can
157 // be overridden, they are not added to the appropriate SubCommands until
158 // ParseCommandLineOptions actually runs.
159 SmallVector
<Option
*, 4> DefaultOptions
;
161 // This collects the different option categories that have been registered.
162 SmallPtrSet
<OptionCategory
*, 16> RegisteredOptionCategories
;
164 // This collects the different subcommands that have been registered.
165 SmallPtrSet
<SubCommand
*, 4> RegisteredSubCommands
;
167 CommandLineParser() { registerSubCommand(&SubCommand::getTopLevel()); }
169 void ResetAllOptionOccurrences();
171 bool ParseCommandLineOptions(int argc
, const char *const *argv
,
172 StringRef Overview
, raw_ostream
*Errs
= nullptr,
173 bool LongOptionsUseDoubleDash
= false);
175 void forEachSubCommand(Option
&Opt
, function_ref
<void(SubCommand
&)> Action
) {
176 if (Opt
.Subs
.empty()) {
177 Action(SubCommand::getTopLevel());
180 if (Opt
.Subs
.size() == 1 && *Opt
.Subs
.begin() == &SubCommand::getAll()) {
181 for (auto *SC
: RegisteredSubCommands
)
183 Action(SubCommand::getAll());
186 for (auto *SC
: Opt
.Subs
) {
187 assert(SC
!= &SubCommand::getAll() &&
188 "SubCommand::getAll() should not be used with other subcommands");
193 void addLiteralOption(Option
&Opt
, SubCommand
*SC
, StringRef Name
) {
196 if (!SC
->OptionsMap
.insert(std::make_pair(Name
, &Opt
)).second
) {
197 errs() << ProgramName
<< ": CommandLine Error: Option '" << Name
198 << "' registered more than once!\n";
199 report_fatal_error("inconsistency in registered CommandLine options");
203 void addLiteralOption(Option
&Opt
, StringRef Name
) {
205 Opt
, [&](SubCommand
&SC
) { addLiteralOption(Opt
, &SC
, Name
); });
208 void addOption(Option
*O
, SubCommand
*SC
) {
209 bool HadErrors
= false;
210 if (O
->hasArgStr()) {
211 // If it's a DefaultOption, check to make sure it isn't already there.
212 if (O
->isDefaultOption() && SC
->OptionsMap
.contains(O
->ArgStr
))
215 // Add argument to the argument map!
216 if (!SC
->OptionsMap
.insert(std::make_pair(O
->ArgStr
, O
)).second
) {
217 errs() << ProgramName
<< ": CommandLine Error: Option '" << O
->ArgStr
218 << "' registered more than once!\n";
223 // Remember information about positional options.
224 if (O
->getFormattingFlag() == cl::Positional
)
225 SC
->PositionalOpts
.push_back(O
);
226 else if (O
->getMiscFlags() & cl::Sink
) // Remember sink options
227 SC
->SinkOpts
.push_back(O
);
228 else if (O
->getNumOccurrencesFlag() == cl::ConsumeAfter
) {
229 if (SC
->ConsumeAfterOpt
) {
230 O
->error("Cannot specify more than one option with cl::ConsumeAfter!");
233 SC
->ConsumeAfterOpt
= O
;
236 // Fail hard if there were errors. These are strictly unrecoverable and
237 // indicate serious issues such as conflicting option names or an
239 // linked LLVM distribution.
241 report_fatal_error("inconsistency in registered CommandLine options");
244 void addOption(Option
*O
, bool ProcessDefaultOption
= false) {
245 if (!ProcessDefaultOption
&& O
->isDefaultOption()) {
246 DefaultOptions
.push_back(O
);
249 forEachSubCommand(*O
, [&](SubCommand
&SC
) { addOption(O
, &SC
); });
252 void removeOption(Option
*O
, SubCommand
*SC
) {
253 SmallVector
<StringRef
, 16> OptionNames
;
254 O
->getExtraOptionNames(OptionNames
);
256 OptionNames
.push_back(O
->ArgStr
);
258 SubCommand
&Sub
= *SC
;
259 auto End
= Sub
.OptionsMap
.end();
260 for (auto Name
: OptionNames
) {
261 auto I
= Sub
.OptionsMap
.find(Name
);
262 if (I
!= End
&& I
->getValue() == O
)
263 Sub
.OptionsMap
.erase(I
);
266 if (O
->getFormattingFlag() == cl::Positional
)
267 for (auto *Opt
= Sub
.PositionalOpts
.begin();
268 Opt
!= Sub
.PositionalOpts
.end(); ++Opt
) {
270 Sub
.PositionalOpts
.erase(Opt
);
274 else if (O
->getMiscFlags() & cl::Sink
)
275 for (auto *Opt
= Sub
.SinkOpts
.begin(); Opt
!= Sub
.SinkOpts
.end(); ++Opt
) {
277 Sub
.SinkOpts
.erase(Opt
);
281 else if (O
== Sub
.ConsumeAfterOpt
)
282 Sub
.ConsumeAfterOpt
= nullptr;
285 void removeOption(Option
*O
) {
286 forEachSubCommand(*O
, [&](SubCommand
&SC
) { removeOption(O
, &SC
); });
289 bool hasOptions(const SubCommand
&Sub
) const {
290 return (!Sub
.OptionsMap
.empty() || !Sub
.PositionalOpts
.empty() ||
291 nullptr != Sub
.ConsumeAfterOpt
);
294 bool hasOptions() const {
295 for (const auto *S
: RegisteredSubCommands
) {
302 bool hasNamedSubCommands() const {
303 for (const auto *S
: RegisteredSubCommands
)
304 if (!S
->getName().empty())
309 SubCommand
*getActiveSubCommand() { return ActiveSubCommand
; }
311 void updateArgStr(Option
*O
, StringRef NewName
, SubCommand
*SC
) {
312 SubCommand
&Sub
= *SC
;
313 if (!Sub
.OptionsMap
.insert(std::make_pair(NewName
, O
)).second
) {
314 errs() << ProgramName
<< ": CommandLine Error: Option '" << O
->ArgStr
315 << "' registered more than once!\n";
316 report_fatal_error("inconsistency in registered CommandLine options");
318 Sub
.OptionsMap
.erase(O
->ArgStr
);
321 void updateArgStr(Option
*O
, StringRef NewName
) {
322 forEachSubCommand(*O
,
323 [&](SubCommand
&SC
) { updateArgStr(O
, NewName
, &SC
); });
326 void printOptionValues();
328 void registerCategory(OptionCategory
*cat
) {
329 assert(count_if(RegisteredOptionCategories
,
330 [cat
](const OptionCategory
*Category
) {
331 return cat
->getName() == Category
->getName();
333 "Duplicate option categories");
335 RegisteredOptionCategories
.insert(cat
);
338 void registerSubCommand(SubCommand
*sub
) {
339 assert(count_if(RegisteredSubCommands
,
340 [sub
](const SubCommand
*Sub
) {
341 return (!sub
->getName().empty()) &&
342 (Sub
->getName() == sub
->getName());
344 "Duplicate subcommands");
345 RegisteredSubCommands
.insert(sub
);
347 // For all options that have been registered for all subcommands, add the
348 // option to this subcommand now.
349 assert(sub
!= &SubCommand::getAll() &&
350 "SubCommand::getAll() should not be registered");
351 for (auto &E
: SubCommand::getAll().OptionsMap
) {
352 Option
*O
= E
.second
;
353 if ((O
->isPositional() || O
->isSink() || O
->isConsumeAfter()) ||
357 addLiteralOption(*O
, sub
, E
.first());
361 void unregisterSubCommand(SubCommand
*sub
) {
362 RegisteredSubCommands
.erase(sub
);
365 iterator_range
<typename SmallPtrSet
<SubCommand
*, 4>::iterator
>
366 getRegisteredSubcommands() {
367 return make_range(RegisteredSubCommands
.begin(),
368 RegisteredSubCommands
.end());
372 ActiveSubCommand
= nullptr;
374 ProgramOverview
= StringRef();
377 RegisteredOptionCategories
.clear();
379 ResetAllOptionOccurrences();
380 RegisteredSubCommands
.clear();
382 SubCommand::getTopLevel().reset();
383 SubCommand::getAll().reset();
384 registerSubCommand(&SubCommand::getTopLevel());
386 DefaultOptions
.clear();
390 SubCommand
*ActiveSubCommand
= nullptr;
392 Option
*LookupOption(SubCommand
&Sub
, StringRef
&Arg
, StringRef
&Value
);
393 Option
*LookupLongOption(SubCommand
&Sub
, StringRef
&Arg
, StringRef
&Value
,
394 bool LongOptionsUseDoubleDash
, bool HaveDoubleDash
) {
395 Option
*Opt
= LookupOption(Sub
, Arg
, Value
);
396 if (Opt
&& LongOptionsUseDoubleDash
&& !HaveDoubleDash
&& !isGrouping(Opt
))
400 SubCommand
*LookupSubCommand(StringRef Name
, std::string
&NearestString
);
405 static ManagedStatic
<CommandLineParser
> GlobalParser
;
407 template <typename T
, T TrueVal
, T FalseVal
>
408 static bool parseBool(Option
&O
, StringRef ArgName
, StringRef Arg
, T
&Value
) {
409 if (Arg
== "" || Arg
== "true" || Arg
== "TRUE" || Arg
== "True" ||
415 if (Arg
== "false" || Arg
== "FALSE" || Arg
== "False" || Arg
== "0") {
419 return O
.error("'" + Arg
+
420 "' is invalid value for boolean argument! Try 0 or 1");
423 void cl::AddLiteralOption(Option
&O
, StringRef Name
) {
424 GlobalParser
->addLiteralOption(O
, Name
);
427 extrahelp::extrahelp(StringRef Help
) : morehelp(Help
) {
428 GlobalParser
->MoreHelp
.push_back(Help
);
431 void Option::addArgument() {
432 GlobalParser
->addOption(this);
433 FullyInitialized
= true;
436 void Option::removeArgument() { GlobalParser
->removeOption(this); }
438 void Option::setArgStr(StringRef S
) {
439 if (FullyInitialized
)
440 GlobalParser
->updateArgStr(this, S
);
441 assert(!S
.starts_with("-") && "Option can't start with '-");
443 if (ArgStr
.size() == 1)
444 setMiscFlag(Grouping
);
447 void Option::addCategory(OptionCategory
&C
) {
448 assert(!Categories
.empty() && "Categories cannot be empty.");
449 // Maintain backward compatibility by replacing the default GeneralCategory
450 // if it's still set. Otherwise, just add the new one. The GeneralCategory
451 // must be explicitly added if you want multiple categories that include it.
452 if (&C
!= &getGeneralCategory() && Categories
[0] == &getGeneralCategory())
454 else if (!is_contained(Categories
, &C
))
455 Categories
.push_back(&C
);
458 void Option::reset() {
461 if (isDefaultOption())
465 void OptionCategory::registerCategory() {
466 GlobalParser
->registerCategory(this);
469 // A special subcommand representing no subcommand. It is particularly important
470 // that this ManagedStatic uses constant initailization and not dynamic
471 // initialization because it is referenced from cl::opt constructors, which run
472 // dynamically in an arbitrary order.
473 LLVM_REQUIRE_CONSTANT_INITIALIZATION
474 static ManagedStatic
<SubCommand
> TopLevelSubCommand
;
476 // A special subcommand that can be used to put an option into all subcommands.
477 static ManagedStatic
<SubCommand
> AllSubCommands
;
479 SubCommand
&SubCommand::getTopLevel() { return *TopLevelSubCommand
; }
481 SubCommand
&SubCommand::getAll() { return *AllSubCommands
; }
483 void SubCommand::registerSubCommand() {
484 GlobalParser
->registerSubCommand(this);
487 void SubCommand::unregisterSubCommand() {
488 GlobalParser
->unregisterSubCommand(this);
491 void SubCommand::reset() {
492 PositionalOpts
.clear();
496 ConsumeAfterOpt
= nullptr;
499 SubCommand::operator bool() const {
500 return (GlobalParser
->getActiveSubCommand() == this);
503 //===----------------------------------------------------------------------===//
504 // Basic, shared command line option processing machinery.
507 /// LookupOption - Lookup the option specified by the specified option on the
508 /// command line. If there is a value specified (after an equal sign) return
509 /// that as well. This assumes that leading dashes have already been stripped.
510 Option
*CommandLineParser::LookupOption(SubCommand
&Sub
, StringRef
&Arg
,
512 // Reject all dashes.
515 assert(&Sub
!= &SubCommand::getAll());
517 size_t EqualPos
= Arg
.find('=');
519 // If we have an equals sign, remember the value.
520 if (EqualPos
== StringRef::npos
) {
521 // Look up the option.
522 return Sub
.OptionsMap
.lookup(Arg
);
525 // If the argument before the = is a valid option name and the option allows
526 // non-prefix form (ie is not AlwaysPrefix), we match. If not, signal match
527 // failure by returning nullptr.
528 auto I
= Sub
.OptionsMap
.find(Arg
.substr(0, EqualPos
));
529 if (I
== Sub
.OptionsMap
.end())
533 if (O
->getFormattingFlag() == cl::AlwaysPrefix
)
536 Value
= Arg
.substr(EqualPos
+ 1);
537 Arg
= Arg
.substr(0, EqualPos
);
541 SubCommand
*CommandLineParser::LookupSubCommand(StringRef Name
,
542 std::string
&NearestString
) {
544 return &SubCommand::getTopLevel();
545 // Find a subcommand with the edit distance == 1.
546 SubCommand
*NearestMatch
= nullptr;
547 for (auto *S
: RegisteredSubCommands
) {
548 assert(S
!= &SubCommand::getAll() &&
549 "SubCommand::getAll() is not expected in RegisteredSubCommands");
550 if (S
->getName().empty())
553 if (S
->getName() == Name
)
556 if (!NearestMatch
&& S
->getName().edit_distance(Name
) < 2)
561 NearestString
= NearestMatch
->getName();
563 return &SubCommand::getTopLevel();
566 /// LookupNearestOption - Lookup the closest match to the option specified by
567 /// the specified option on the command line. If there is a value specified
568 /// (after an equal sign) return that as well. This assumes that leading dashes
569 /// have already been stripped.
570 static Option
*LookupNearestOption(StringRef Arg
,
571 const StringMap
<Option
*> &OptionsMap
,
572 std::string
&NearestString
) {
573 // Reject all dashes.
577 // Split on any equal sign.
578 std::pair
<StringRef
, StringRef
> SplitArg
= Arg
.split('=');
579 StringRef
&LHS
= SplitArg
.first
; // LHS == Arg when no '=' is present.
580 StringRef
&RHS
= SplitArg
.second
;
582 // Find the closest match.
583 Option
*Best
= nullptr;
584 unsigned BestDistance
= 0;
585 for (StringMap
<Option
*>::const_iterator it
= OptionsMap
.begin(),
586 ie
= OptionsMap
.end();
588 Option
*O
= it
->second
;
589 // Do not suggest really hidden options (not shown in any help).
590 if (O
->getOptionHiddenFlag() == ReallyHidden
)
593 SmallVector
<StringRef
, 16> OptionNames
;
594 O
->getExtraOptionNames(OptionNames
);
596 OptionNames
.push_back(O
->ArgStr
);
598 bool PermitValue
= O
->getValueExpectedFlag() != cl::ValueDisallowed
;
599 StringRef Flag
= PermitValue
? LHS
: Arg
;
600 for (const auto &Name
: OptionNames
) {
601 unsigned Distance
= StringRef(Name
).edit_distance(
602 Flag
, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance
);
603 if (!Best
|| Distance
< BestDistance
) {
605 BestDistance
= Distance
;
606 if (RHS
.empty() || !PermitValue
)
607 NearestString
= std::string(Name
);
609 NearestString
= (Twine(Name
) + "=" + RHS
).str();
617 /// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence()
618 /// that does special handling of cl::CommaSeparated options.
619 static bool CommaSeparateAndAddOccurrence(Option
*Handler
, unsigned pos
,
620 StringRef ArgName
, StringRef Value
,
621 bool MultiArg
= false) {
622 // Check to see if this option accepts a comma separated list of values. If
623 // it does, we have to split up the value into multiple values.
624 if (Handler
->getMiscFlags() & CommaSeparated
) {
625 StringRef
Val(Value
);
626 StringRef::size_type Pos
= Val
.find(',');
628 while (Pos
!= StringRef::npos
) {
629 // Process the portion before the comma.
630 if (Handler
->addOccurrence(pos
, ArgName
, Val
.substr(0, Pos
), MultiArg
))
632 // Erase the portion before the comma, AND the comma.
633 Val
= Val
.substr(Pos
+ 1);
634 // Check for another comma.
641 return Handler
->addOccurrence(pos
, ArgName
, Value
, MultiArg
);
644 /// ProvideOption - For Value, this differentiates between an empty value ("")
645 /// and a null value (StringRef()). The later is accepted for arguments that
646 /// don't allow a value (-foo) the former is rejected (-foo=).
647 static inline bool ProvideOption(Option
*Handler
, StringRef ArgName
,
648 StringRef Value
, int argc
,
649 const char *const *argv
, int &i
) {
650 // Is this a multi-argument option?
651 unsigned NumAdditionalVals
= Handler
->getNumAdditionalVals();
653 // Enforce value requirements
654 switch (Handler
->getValueExpectedFlag()) {
656 if (!Value
.data()) { // No value specified?
657 // If no other argument or the option only supports prefix form, we
658 // cannot look at the next argument.
659 if (i
+ 1 >= argc
|| Handler
->getFormattingFlag() == cl::AlwaysPrefix
)
660 return Handler
->error("requires a value!");
661 // Steal the next argument, like for '-o filename'
662 assert(argv
&& "null check");
663 Value
= StringRef(argv
[++i
]);
666 case ValueDisallowed
:
667 if (NumAdditionalVals
> 0)
668 return Handler
->error("multi-valued option specified"
669 " with ValueDisallowed modifier!");
672 return Handler
->error("does not allow a value! '" + Twine(Value
) +
679 // If this isn't a multi-arg option, just run the handler.
680 if (NumAdditionalVals
== 0)
681 return CommaSeparateAndAddOccurrence(Handler
, i
, ArgName
, Value
);
683 // If it is, run the handle several times.
684 bool MultiArg
= false;
687 if (CommaSeparateAndAddOccurrence(Handler
, i
, ArgName
, Value
, MultiArg
))
693 while (NumAdditionalVals
> 0) {
695 return Handler
->error("not enough values!");
696 assert(argv
&& "null check");
697 Value
= StringRef(argv
[++i
]);
699 if (CommaSeparateAndAddOccurrence(Handler
, i
, ArgName
, Value
, MultiArg
))
707 bool llvm::cl::ProvidePositionalOption(Option
*Handler
, StringRef Arg
, int i
) {
709 return ProvideOption(Handler
, Handler
->ArgStr
, Arg
, 0, nullptr, Dummy
);
712 // getOptionPred - Check to see if there are any options that satisfy the
713 // specified predicate with names that are the prefixes in Name. This is
714 // checked by progressively stripping characters off of the name, checking to
715 // see if there options that satisfy the predicate. If we find one, return it,
716 // otherwise return null.
718 static Option
*getOptionPred(StringRef Name
, size_t &Length
,
719 bool (*Pred
)(const Option
*),
720 const StringMap
<Option
*> &OptionsMap
) {
721 StringMap
<Option
*>::const_iterator OMI
= OptionsMap
.find(Name
);
722 if (OMI
!= OptionsMap
.end() && !Pred(OMI
->getValue()))
723 OMI
= OptionsMap
.end();
725 // Loop while we haven't found an option and Name still has at least two
726 // characters in it (so that the next iteration will not be the empty
728 while (OMI
== OptionsMap
.end() && Name
.size() > 1) {
729 Name
= Name
.substr(0, Name
.size() - 1); // Chop off the last character.
730 OMI
= OptionsMap
.find(Name
);
731 if (OMI
!= OptionsMap
.end() && !Pred(OMI
->getValue()))
732 OMI
= OptionsMap
.end();
735 if (OMI
!= OptionsMap
.end() && Pred(OMI
->second
)) {
736 Length
= Name
.size();
737 return OMI
->second
; // Found one!
739 return nullptr; // No option found!
742 /// HandlePrefixedOrGroupedOption - The specified argument string (which started
743 /// with at least one '-') does not fully match an available option. Check to
744 /// see if this is a prefix or grouped option. If so, split arg into output an
745 /// Arg/Value pair and return the Option to parse it with.
747 HandlePrefixedOrGroupedOption(StringRef
&Arg
, StringRef
&Value
,
749 const StringMap
<Option
*> &OptionsMap
) {
755 Option
*PGOpt
= getOptionPred(Arg
, Length
, isPrefixedOrGrouping
, OptionsMap
);
760 StringRef MaybeValue
=
761 (Length
< Arg
.size()) ? Arg
.substr(Length
) : StringRef();
762 Arg
= Arg
.substr(0, Length
);
763 assert(OptionsMap
.count(Arg
) && OptionsMap
.find(Arg
)->second
== PGOpt
);
765 // cl::Prefix options do not preserve '=' when used separately.
766 // The behavior for them with grouped options should be the same.
767 if (MaybeValue
.empty() || PGOpt
->getFormattingFlag() == cl::AlwaysPrefix
||
768 (PGOpt
->getFormattingFlag() == cl::Prefix
&& MaybeValue
[0] != '=')) {
773 if (MaybeValue
[0] == '=') {
774 Value
= MaybeValue
.substr(1);
778 // This must be a grouped option.
779 assert(isGrouping(PGOpt
) && "Broken getOptionPred!");
781 // Grouping options inside a group can't have values.
782 if (PGOpt
->getValueExpectedFlag() == cl::ValueRequired
) {
783 ErrorParsing
|= PGOpt
->error("may not occur within a group!");
787 // Because the value for the option is not required, we don't need to pass
790 ErrorParsing
|= ProvideOption(PGOpt
, Arg
, StringRef(), 0, nullptr, Dummy
);
792 // Get the next grouping option.
794 PGOpt
= getOptionPred(Arg
, Length
, isGrouping
, OptionsMap
);
797 // We could not find a grouping option in the remainder of Arg.
801 static bool RequiresValue(const Option
*O
) {
802 return O
->getNumOccurrencesFlag() == cl::Required
||
803 O
->getNumOccurrencesFlag() == cl::OneOrMore
;
806 static bool EatsUnboundedNumberOfValues(const Option
*O
) {
807 return O
->getNumOccurrencesFlag() == cl::ZeroOrMore
||
808 O
->getNumOccurrencesFlag() == cl::OneOrMore
;
811 static bool isWhitespace(char C
) {
812 return C
== ' ' || C
== '\t' || C
== '\r' || C
== '\n';
815 static bool isWhitespaceOrNull(char C
) {
816 return isWhitespace(C
) || C
== '\0';
819 static bool isQuote(char C
) { return C
== '\"' || C
== '\''; }
821 void cl::TokenizeGNUCommandLine(StringRef Src
, StringSaver
&Saver
,
822 SmallVectorImpl
<const char *> &NewArgv
,
824 SmallString
<128> Token
;
825 for (size_t I
= 0, E
= Src
.size(); I
!= E
; ++I
) {
826 // Consume runs of whitespace.
828 while (I
!= E
&& isWhitespace(Src
[I
])) {
829 // Mark the end of lines in response files.
830 if (MarkEOLs
&& Src
[I
] == '\n')
831 NewArgv
.push_back(nullptr);
840 // Backslash escapes the next character.
841 if (I
+ 1 < E
&& C
== '\\') {
842 ++I
; // Skip the escape.
843 Token
.push_back(Src
[I
]);
847 // Consume a quoted string.
850 while (I
!= E
&& Src
[I
] != C
) {
851 // Backslash escapes the next character.
852 if (Src
[I
] == '\\' && I
+ 1 != E
)
854 Token
.push_back(Src
[I
]);
862 // End the token if this is whitespace.
863 if (isWhitespace(C
)) {
865 NewArgv
.push_back(Saver
.save(Token
.str()).data());
866 // Mark the end of lines in response files.
867 if (MarkEOLs
&& C
== '\n')
868 NewArgv
.push_back(nullptr);
873 // This is a normal character. Append it.
877 // Append the last token after hitting EOF with no whitespace.
879 NewArgv
.push_back(Saver
.save(Token
.str()).data());
882 /// Backslashes are interpreted in a rather complicated way in the Windows-style
883 /// command line, because backslashes are used both to separate path and to
884 /// escape double quote. This method consumes runs of backslashes as well as the
885 /// following double quote if it's escaped.
887 /// * If an even number of backslashes is followed by a double quote, one
888 /// backslash is output for every pair of backslashes, and the last double
889 /// quote remains unconsumed. The double quote will later be interpreted as
890 /// the start or end of a quoted string in the main loop outside of this
893 /// * If an odd number of backslashes is followed by a double quote, one
894 /// backslash is output for every pair of backslashes, and a double quote is
895 /// output for the last pair of backslash-double quote. The double quote is
896 /// consumed in this case.
898 /// * Otherwise, backslashes are interpreted literally.
899 static size_t parseBackslash(StringRef Src
, size_t I
, SmallString
<128> &Token
) {
900 size_t E
= Src
.size();
901 int BackslashCount
= 0;
902 // Skip the backslashes.
906 } while (I
!= E
&& Src
[I
] == '\\');
908 bool FollowedByDoubleQuote
= (I
!= E
&& Src
[I
] == '"');
909 if (FollowedByDoubleQuote
) {
910 Token
.append(BackslashCount
/ 2, '\\');
911 if (BackslashCount
% 2 == 0)
913 Token
.push_back('"');
916 Token
.append(BackslashCount
, '\\');
920 // Windows treats whitespace, double quotes, and backslashes specially, except
921 // when parsing the first token of a full command line, in which case
922 // backslashes are not special.
923 static bool isWindowsSpecialChar(char C
) {
924 return isWhitespaceOrNull(C
) || C
== '\\' || C
== '\"';
926 static bool isWindowsSpecialCharInCommandName(char C
) {
927 return isWhitespaceOrNull(C
) || C
== '\"';
930 // Windows tokenization implementation. The implementation is designed to be
931 // inlined and specialized for the two user entry points.
932 static inline void tokenizeWindowsCommandLineImpl(
933 StringRef Src
, StringSaver
&Saver
, function_ref
<void(StringRef
)> AddToken
,
934 bool AlwaysCopy
, function_ref
<void()> MarkEOL
, bool InitialCommandName
) {
935 SmallString
<128> Token
;
937 // Sometimes, this function will be handling a full command line including an
938 // executable pathname at the start. In that situation, the initial pathname
939 // needs different handling from the following arguments, because when
940 // CreateProcess or cmd.exe scans the pathname, it doesn't treat \ as
941 // escaping the quote character, whereas when libc scans the rest of the
942 // command line, it does.
943 bool CommandName
= InitialCommandName
;
945 // Try to do as much work inside the state machine as possible.
946 enum { INIT
, UNQUOTED
, QUOTED
} State
= INIT
;
948 for (size_t I
= 0, E
= Src
.size(); I
< E
; ++I
) {
951 assert(Token
.empty() && "token should be empty in initial state");
952 // Eat whitespace before a token.
953 while (I
< E
&& isWhitespaceOrNull(Src
[I
])) {
958 // Stop if this was trailing whitespace.
963 while (I
< E
&& !isWindowsSpecialCharInCommandName(Src
[I
]))
966 while (I
< E
&& !isWindowsSpecialChar(Src
[I
]))
969 StringRef NormalChars
= Src
.slice(Start
, I
);
970 if (I
>= E
|| isWhitespaceOrNull(Src
[I
])) {
971 // No special characters: slice out the substring and start the next
972 // token. Copy the string if the caller asks us to.
973 AddToken(AlwaysCopy
? Saver
.save(NormalChars
) : NormalChars
);
974 if (I
< E
&& Src
[I
] == '\n') {
976 CommandName
= InitialCommandName
;
980 } else if (Src
[I
] == '\"') {
981 Token
+= NormalChars
;
983 } else if (Src
[I
] == '\\') {
984 assert(!CommandName
&& "or else we'd have treated it as a normal char");
985 Token
+= NormalChars
;
986 I
= parseBackslash(Src
, I
, Token
);
989 llvm_unreachable("unexpected special character");
995 if (isWhitespaceOrNull(Src
[I
])) {
996 // Whitespace means the end of the token. If we are in this state, the
997 // token must have contained a special character, so we must copy the
999 AddToken(Saver
.save(Token
.str()));
1001 if (Src
[I
] == '\n') {
1002 CommandName
= InitialCommandName
;
1005 CommandName
= false;
1008 } else if (Src
[I
] == '\"') {
1010 } else if (Src
[I
] == '\\' && !CommandName
) {
1011 I
= parseBackslash(Src
, I
, Token
);
1013 Token
.push_back(Src
[I
]);
1018 if (Src
[I
] == '\"') {
1019 if (I
< (E
- 1) && Src
[I
+ 1] == '"') {
1020 // Consecutive double-quotes inside a quoted string implies one
1022 Token
.push_back('"');
1025 // Otherwise, end the quoted portion and return to the unquoted state.
1028 } else if (Src
[I
] == '\\' && !CommandName
) {
1029 I
= parseBackslash(Src
, I
, Token
);
1031 Token
.push_back(Src
[I
]);
1038 AddToken(Saver
.save(Token
.str()));
1041 void cl::TokenizeWindowsCommandLine(StringRef Src
, StringSaver
&Saver
,
1042 SmallVectorImpl
<const char *> &NewArgv
,
1044 auto AddToken
= [&](StringRef Tok
) { NewArgv
.push_back(Tok
.data()); };
1045 auto OnEOL
= [&]() {
1047 NewArgv
.push_back(nullptr);
1049 tokenizeWindowsCommandLineImpl(Src
, Saver
, AddToken
,
1050 /*AlwaysCopy=*/true, OnEOL
, false);
1053 void cl::TokenizeWindowsCommandLineNoCopy(StringRef Src
, StringSaver
&Saver
,
1054 SmallVectorImpl
<StringRef
> &NewArgv
) {
1055 auto AddToken
= [&](StringRef Tok
) { NewArgv
.push_back(Tok
); };
1056 auto OnEOL
= []() {};
1057 tokenizeWindowsCommandLineImpl(Src
, Saver
, AddToken
, /*AlwaysCopy=*/false,
1061 void cl::TokenizeWindowsCommandLineFull(StringRef Src
, StringSaver
&Saver
,
1062 SmallVectorImpl
<const char *> &NewArgv
,
1064 auto AddToken
= [&](StringRef Tok
) { NewArgv
.push_back(Tok
.data()); };
1065 auto OnEOL
= [&]() {
1067 NewArgv
.push_back(nullptr);
1069 tokenizeWindowsCommandLineImpl(Src
, Saver
, AddToken
,
1070 /*AlwaysCopy=*/true, OnEOL
, true);
1073 void cl::tokenizeConfigFile(StringRef Source
, StringSaver
&Saver
,
1074 SmallVectorImpl
<const char *> &NewArgv
,
1076 for (const char *Cur
= Source
.begin(); Cur
!= Source
.end();) {
1077 SmallString
<128> Line
;
1078 // Check for comment line.
1079 if (isWhitespace(*Cur
)) {
1080 while (Cur
!= Source
.end() && isWhitespace(*Cur
))
1085 while (Cur
!= Source
.end() && *Cur
!= '\n')
1089 // Find end of the current line.
1090 const char *Start
= Cur
;
1091 for (const char *End
= Source
.end(); Cur
!= End
; ++Cur
) {
1093 if (Cur
+ 1 != End
) {
1096 (*Cur
== '\r' && (Cur
+ 1 != End
) && Cur
[1] == '\n')) {
1097 Line
.append(Start
, Cur
- 1);
1103 } else if (*Cur
== '\n')
1107 Line
.append(Start
, Cur
);
1108 cl::TokenizeGNUCommandLine(Line
, Saver
, NewArgv
, MarkEOLs
);
1112 // It is called byte order marker but the UTF-8 BOM is actually not affected
1113 // by the host system's endianness.
1114 static bool hasUTF8ByteOrderMark(ArrayRef
<char> S
) {
1115 return (S
.size() >= 3 && S
[0] == '\xef' && S
[1] == '\xbb' && S
[2] == '\xbf');
1118 // Substitute <CFGDIR> with the file's base path.
1119 static void ExpandBasePaths(StringRef BasePath
, StringSaver
&Saver
,
1121 assert(sys::path::is_absolute(BasePath
));
1122 constexpr StringLiteral
Token("<CFGDIR>");
1123 const StringRef
ArgString(Arg
);
1125 SmallString
<128> ResponseFile
;
1126 StringRef::size_type StartPos
= 0;
1127 for (StringRef::size_type TokenPos
= ArgString
.find(Token
);
1128 TokenPos
!= StringRef::npos
;
1129 TokenPos
= ArgString
.find(Token
, StartPos
)) {
1130 // Token may appear more than once per arg (e.g. comma-separated linker
1131 // args). Support by using path-append on any subsequent appearances.
1132 const StringRef LHS
= ArgString
.substr(StartPos
, TokenPos
- StartPos
);
1133 if (ResponseFile
.empty())
1136 llvm::sys::path::append(ResponseFile
, LHS
);
1137 ResponseFile
.append(BasePath
);
1138 StartPos
= TokenPos
+ Token
.size();
1141 if (!ResponseFile
.empty()) {
1142 // Path-append the remaining arg substring if at least one token appeared.
1143 const StringRef Remaining
= ArgString
.substr(StartPos
);
1144 if (!Remaining
.empty())
1145 llvm::sys::path::append(ResponseFile
, Remaining
);
1146 Arg
= Saver
.save(ResponseFile
.str()).data();
1150 // FName must be an absolute path.
1151 Error
ExpansionContext::expandResponseFile(
1152 StringRef FName
, SmallVectorImpl
<const char *> &NewArgv
) {
1153 assert(sys::path::is_absolute(FName
));
1154 llvm::ErrorOr
<std::unique_ptr
<MemoryBuffer
>> MemBufOrErr
=
1155 FS
->getBufferForFile(FName
);
1157 std::error_code EC
= MemBufOrErr
.getError();
1158 return llvm::createStringError(EC
, Twine("cannot not open file '") + FName
+
1159 "': " + EC
.message());
1161 MemoryBuffer
&MemBuf
= *MemBufOrErr
.get();
1162 StringRef
Str(MemBuf
.getBufferStart(), MemBuf
.getBufferSize());
1164 // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
1165 ArrayRef
<char> BufRef(MemBuf
.getBufferStart(), MemBuf
.getBufferEnd());
1166 std::string UTF8Buf
;
1167 if (hasUTF16ByteOrderMark(BufRef
)) {
1168 if (!convertUTF16ToUTF8String(BufRef
, UTF8Buf
))
1169 return llvm::createStringError(std::errc::illegal_byte_sequence
,
1170 "Could not convert UTF16 to UTF8");
1171 Str
= StringRef(UTF8Buf
);
1173 // If we see UTF-8 BOM sequence at the beginning of a file, we shall remove
1174 // these bytes before parsing.
1175 // Reference: http://en.wikipedia.org/wiki/UTF-8#Byte_order_mark
1176 else if (hasUTF8ByteOrderMark(BufRef
))
1177 Str
= StringRef(BufRef
.data() + 3, BufRef
.size() - 3);
1179 // Tokenize the contents into NewArgv.
1180 Tokenizer(Str
, Saver
, NewArgv
, MarkEOLs
);
1182 // Expanded file content may require additional transformations, like using
1183 // absolute paths instead of relative in '@file' constructs or expanding
1185 if (!RelativeNames
&& !InConfigFile
)
1186 return Error::success();
1188 StringRef BasePath
= llvm::sys::path::parent_path(FName
);
1189 for (const char *&Arg
: NewArgv
) {
1193 // Substitute <CFGDIR> with the file's base path.
1195 ExpandBasePaths(BasePath
, Saver
, Arg
);
1197 // Discover the case, when argument should be transformed into '@file' and
1198 // evaluate 'file' for it.
1199 StringRef
ArgStr(Arg
);
1201 bool ConfigInclusion
= false;
1202 if (ArgStr
.consume_front("@")) {
1204 if (!llvm::sys::path::is_relative(FileName
))
1206 } else if (ArgStr
.consume_front("--config=")) {
1208 ConfigInclusion
= true;
1213 // Update expansion construct.
1214 SmallString
<128> ResponseFile
;
1215 ResponseFile
.push_back('@');
1216 if (ConfigInclusion
&& !llvm::sys::path::has_parent_path(FileName
)) {
1217 SmallString
<128> FilePath
;
1218 if (!findConfigFile(FileName
, FilePath
))
1219 return createStringError(
1220 std::make_error_code(std::errc::no_such_file_or_directory
),
1221 "cannot not find configuration file: " + FileName
);
1222 ResponseFile
.append(FilePath
);
1224 ResponseFile
.append(BasePath
);
1225 llvm::sys::path::append(ResponseFile
, FileName
);
1227 Arg
= Saver
.save(ResponseFile
.str()).data();
1229 return Error::success();
1232 /// Expand response files on a command line recursively using the given
1233 /// StringSaver and tokenization strategy.
1234 Error
ExpansionContext::expandResponseFiles(
1235 SmallVectorImpl
<const char *> &Argv
) {
1236 struct ResponseFileRecord
{
1241 // To detect recursive response files, we maintain a stack of files and the
1242 // position of the last argument in the file. This position is updated
1243 // dynamically as we recursively expand files.
1244 SmallVector
<ResponseFileRecord
, 3> FileStack
;
1246 // Push a dummy entry that represents the initial command line, removing
1247 // the need to check for an empty list.
1248 FileStack
.push_back({"", Argv
.size()});
1250 // Don't cache Argv.size() because it can change.
1251 for (unsigned I
= 0; I
!= Argv
.size();) {
1252 while (I
== FileStack
.back().End
) {
1253 // Passing the end of a file's argument list, so we can remove it from the
1255 FileStack
.pop_back();
1258 const char *Arg
= Argv
[I
];
1259 // Check if it is an EOL marker
1260 if (Arg
== nullptr) {
1265 if (Arg
[0] != '@') {
1270 const char *FName
= Arg
+ 1;
1271 // Note that CurrentDir is only used for top-level rsp files, the rest will
1272 // always have an absolute path deduced from the containing file.
1273 SmallString
<128> CurrDir
;
1274 if (llvm::sys::path::is_relative(FName
)) {
1275 if (CurrentDir
.empty()) {
1276 if (auto CWD
= FS
->getCurrentWorkingDirectory()) {
1279 return createStringError(
1280 CWD
.getError(), Twine("cannot get absolute path for: ") + FName
);
1283 CurrDir
= CurrentDir
;
1285 llvm::sys::path::append(CurrDir
, FName
);
1286 FName
= CurrDir
.c_str();
1289 ErrorOr
<llvm::vfs::Status
> Res
= FS
->status(FName
);
1290 if (!Res
|| !Res
->exists()) {
1291 std::error_code EC
= Res
.getError();
1292 if (!InConfigFile
) {
1293 // If the specified file does not exist, leave '@file' unexpanded, as
1295 if (!EC
|| EC
== llvm::errc::no_such_file_or_directory
) {
1301 EC
= llvm::errc::no_such_file_or_directory
;
1302 return createStringError(EC
, Twine("cannot not open file '") + FName
+
1303 "': " + EC
.message());
1305 const llvm::vfs::Status
&FileStatus
= Res
.get();
1308 [FileStatus
, this](const ResponseFileRecord
&RFile
) -> ErrorOr
<bool> {
1309 ErrorOr
<llvm::vfs::Status
> RHS
= FS
->status(RFile
.File
);
1311 return RHS
.getError();
1312 return FileStatus
.equivalent(*RHS
);
1315 // Check for recursive response files.
1316 for (const auto &F
: drop_begin(FileStack
)) {
1317 if (ErrorOr
<bool> R
= IsEquivalent(F
)) {
1319 return createStringError(
1320 R
.getError(), Twine("recursive expansion of: '") + F
.File
+ "'");
1322 return createStringError(R
.getError(),
1323 Twine("cannot open file: ") + F
.File
);
1327 // Replace this response file argument with the tokenization of its
1328 // contents. Nested response files are expanded in subsequent iterations.
1329 SmallVector
<const char *, 0> ExpandedArgv
;
1330 if (Error Err
= expandResponseFile(FName
, ExpandedArgv
))
1333 for (ResponseFileRecord
&Record
: FileStack
) {
1334 // Increase the end of all active records by the number of newly expanded
1335 // arguments, minus the response file itself.
1336 Record
.End
+= ExpandedArgv
.size() - 1;
1339 FileStack
.push_back({FName
, I
+ ExpandedArgv
.size()});
1340 Argv
.erase(Argv
.begin() + I
);
1341 Argv
.insert(Argv
.begin() + I
, ExpandedArgv
.begin(), ExpandedArgv
.end());
1344 // If successful, the top of the file stack will mark the end of the Argv
1345 // stream. A failure here indicates a bug in the stack popping logic above.
1346 // Note that FileStack may have more than one element at this point because we
1347 // don't have a chance to pop the stack when encountering recursive files at
1348 // the end of the stream, so seeing that doesn't indicate a bug.
1349 assert(FileStack
.size() > 0 && Argv
.size() == FileStack
.back().End
);
1350 return Error::success();
1353 bool cl::expandResponseFiles(int Argc
, const char *const *Argv
,
1354 const char *EnvVar
, StringSaver
&Saver
,
1355 SmallVectorImpl
<const char *> &NewArgv
) {
1357 auto Tokenize
= cl::TokenizeWindowsCommandLine
;
1359 auto Tokenize
= cl::TokenizeGNUCommandLine
;
1361 // The environment variable specifies initial options.
1363 if (std::optional
<std::string
> EnvValue
= sys::Process::GetEnv(EnvVar
))
1364 Tokenize(*EnvValue
, Saver
, NewArgv
, /*MarkEOLs=*/false);
1366 // Command line options can override the environment variable.
1367 NewArgv
.append(Argv
+ 1, Argv
+ Argc
);
1368 ExpansionContext
ECtx(Saver
.getAllocator(), Tokenize
);
1369 if (Error Err
= ECtx
.expandResponseFiles(NewArgv
)) {
1370 errs() << toString(std::move(Err
)) << '\n';
1376 bool cl::ExpandResponseFiles(StringSaver
&Saver
, TokenizerCallback Tokenizer
,
1377 SmallVectorImpl
<const char *> &Argv
) {
1378 ExpansionContext
ECtx(Saver
.getAllocator(), Tokenizer
);
1379 if (Error Err
= ECtx
.expandResponseFiles(Argv
)) {
1380 errs() << toString(std::move(Err
)) << '\n';
1386 ExpansionContext::ExpansionContext(BumpPtrAllocator
&A
, TokenizerCallback T
)
1387 : Saver(A
), Tokenizer(T
), FS(vfs::getRealFileSystem().get()) {}
1389 bool ExpansionContext::findConfigFile(StringRef FileName
,
1390 SmallVectorImpl
<char> &FilePath
) {
1391 SmallString
<128> CfgFilePath
;
1392 const auto FileExists
= [this](SmallString
<128> Path
) -> bool {
1393 auto Status
= FS
->status(Path
);
1395 Status
->getType() == llvm::sys::fs::file_type::regular_file
;
1398 // If file name contains directory separator, treat it as a path to
1399 // configuration file.
1400 if (llvm::sys::path::has_parent_path(FileName
)) {
1401 CfgFilePath
= FileName
;
1402 if (llvm::sys::path::is_relative(FileName
) && FS
->makeAbsolute(CfgFilePath
))
1404 if (!FileExists(CfgFilePath
))
1406 FilePath
.assign(CfgFilePath
.begin(), CfgFilePath
.end());
1410 // Look for the file in search directories.
1411 for (const StringRef
&Dir
: SearchDirs
) {
1414 CfgFilePath
.assign(Dir
);
1415 llvm::sys::path::append(CfgFilePath
, FileName
);
1416 llvm::sys::path::native(CfgFilePath
);
1417 if (FileExists(CfgFilePath
)) {
1418 FilePath
.assign(CfgFilePath
.begin(), CfgFilePath
.end());
1426 Error
ExpansionContext::readConfigFile(StringRef CfgFile
,
1427 SmallVectorImpl
<const char *> &Argv
) {
1428 SmallString
<128> AbsPath
;
1429 if (sys::path::is_relative(CfgFile
)) {
1430 AbsPath
.assign(CfgFile
);
1431 if (std::error_code EC
= FS
->makeAbsolute(AbsPath
))
1432 return make_error
<StringError
>(
1433 EC
, Twine("cannot get absolute path for " + CfgFile
));
1434 CfgFile
= AbsPath
.str();
1436 InConfigFile
= true;
1437 RelativeNames
= true;
1438 if (Error Err
= expandResponseFile(CfgFile
, Argv
))
1440 return expandResponseFiles(Argv
);
1443 static void initCommonOptions();
1444 bool cl::ParseCommandLineOptions(int argc
, const char *const *argv
,
1445 StringRef Overview
, raw_ostream
*Errs
,
1447 bool LongOptionsUseDoubleDash
) {
1448 initCommonOptions();
1449 SmallVector
<const char *, 20> NewArgv
;
1451 StringSaver
Saver(A
);
1452 NewArgv
.push_back(argv
[0]);
1454 // Parse options from environment variable.
1456 if (std::optional
<std::string
> EnvValue
=
1457 sys::Process::GetEnv(StringRef(EnvVar
)))
1458 TokenizeGNUCommandLine(*EnvValue
, Saver
, NewArgv
);
1461 // Append options from command line.
1462 for (int I
= 1; I
< argc
; ++I
)
1463 NewArgv
.push_back(argv
[I
]);
1464 int NewArgc
= static_cast<int>(NewArgv
.size());
1466 // Parse all options.
1467 return GlobalParser
->ParseCommandLineOptions(NewArgc
, &NewArgv
[0], Overview
,
1468 Errs
, LongOptionsUseDoubleDash
);
1471 /// Reset all options at least once, so that we can parse different options.
1472 void CommandLineParser::ResetAllOptionOccurrences() {
1473 // Reset all option values to look like they have never been seen before.
1474 // Options might be reset twice (they can be reference in both OptionsMap
1475 // and one of the other members), but that does not harm.
1476 for (auto *SC
: RegisteredSubCommands
) {
1477 for (auto &O
: SC
->OptionsMap
)
1479 for (Option
*O
: SC
->PositionalOpts
)
1481 for (Option
*O
: SC
->SinkOpts
)
1483 if (SC
->ConsumeAfterOpt
)
1484 SC
->ConsumeAfterOpt
->reset();
1488 bool CommandLineParser::ParseCommandLineOptions(int argc
,
1489 const char *const *argv
,
1492 bool LongOptionsUseDoubleDash
) {
1493 assert(hasOptions() && "No options specified!");
1495 ProgramOverview
= Overview
;
1496 bool IgnoreErrors
= Errs
;
1499 bool ErrorParsing
= false;
1501 // Expand response files.
1502 SmallVector
<const char *, 20> newArgv(argv
, argv
+ argc
);
1505 auto Tokenize
= cl::TokenizeWindowsCommandLine
;
1507 auto Tokenize
= cl::TokenizeGNUCommandLine
;
1509 ExpansionContext
ECtx(A
, Tokenize
);
1510 if (Error Err
= ECtx
.expandResponseFiles(newArgv
)) {
1511 *Errs
<< toString(std::move(Err
)) << '\n';
1515 argc
= static_cast<int>(newArgv
.size());
1517 // Copy the program name into ProgName, making sure not to overflow it.
1518 ProgramName
= std::string(sys::path::filename(StringRef(argv
[0])));
1520 // Check out the positional arguments to collect information about them.
1521 unsigned NumPositionalRequired
= 0;
1523 // Determine whether or not there are an unlimited number of positionals
1524 bool HasUnlimitedPositionals
= false;
1527 SubCommand
*ChosenSubCommand
= &SubCommand::getTopLevel();
1528 std::string NearestSubCommandString
;
1529 bool MaybeNamedSubCommand
=
1530 argc
>= 2 && argv
[FirstArg
][0] != '-' && hasNamedSubCommands();
1531 if (MaybeNamedSubCommand
) {
1532 // If the first argument specifies a valid subcommand, start processing
1533 // options from the second argument.
1535 LookupSubCommand(StringRef(argv
[FirstArg
]), NearestSubCommandString
);
1536 if (ChosenSubCommand
!= &SubCommand::getTopLevel())
1539 GlobalParser
->ActiveSubCommand
= ChosenSubCommand
;
1541 assert(ChosenSubCommand
);
1542 auto &ConsumeAfterOpt
= ChosenSubCommand
->ConsumeAfterOpt
;
1543 auto &PositionalOpts
= ChosenSubCommand
->PositionalOpts
;
1544 auto &SinkOpts
= ChosenSubCommand
->SinkOpts
;
1545 auto &OptionsMap
= ChosenSubCommand
->OptionsMap
;
1547 for (auto *O
: DefaultOptions
) {
1551 if (ConsumeAfterOpt
) {
1552 assert(PositionalOpts
.size() > 0 &&
1553 "Cannot specify cl::ConsumeAfter without a positional argument!");
1555 if (!PositionalOpts
.empty()) {
1557 // Calculate how many positional values are _required_.
1558 bool UnboundedFound
= false;
1559 for (size_t i
= 0, e
= PositionalOpts
.size(); i
!= e
; ++i
) {
1560 Option
*Opt
= PositionalOpts
[i
];
1561 if (RequiresValue(Opt
))
1562 ++NumPositionalRequired
;
1563 else if (ConsumeAfterOpt
) {
1564 // ConsumeAfter cannot be combined with "optional" positional options
1565 // unless there is only one positional argument...
1566 if (PositionalOpts
.size() > 1) {
1568 Opt
->error("error - this positional option will never be matched, "
1569 "because it does not Require a value, and a "
1570 "cl::ConsumeAfter option is active!");
1571 ErrorParsing
= true;
1573 } else if (UnboundedFound
&& !Opt
->hasArgStr()) {
1574 // This option does not "require" a value... Make sure this option is
1575 // not specified after an option that eats all extra arguments, or this
1576 // one will never get any!
1579 Opt
->error("error - option can never match, because "
1580 "another positional argument will match an "
1581 "unbounded number of values, and this option"
1582 " does not require a value!");
1583 *Errs
<< ProgramName
<< ": CommandLine Error: Option '" << Opt
->ArgStr
1584 << "' is all messed up!\n";
1585 *Errs
<< PositionalOpts
.size();
1586 ErrorParsing
= true;
1588 UnboundedFound
|= EatsUnboundedNumberOfValues(Opt
);
1590 HasUnlimitedPositionals
= UnboundedFound
|| ConsumeAfterOpt
;
1593 // PositionalVals - A vector of "positional" arguments we accumulate into
1594 // the process at the end.
1596 SmallVector
<std::pair
<StringRef
, unsigned>, 4> PositionalVals
;
1598 // If the program has named positional arguments, and the name has been run
1599 // across, keep track of which positional argument was named. Otherwise put
1600 // the positional args into the PositionalVals list...
1601 Option
*ActivePositionalArg
= nullptr;
1603 // Loop over all of the arguments... processing them.
1604 bool DashDashFound
= false; // Have we read '--'?
1605 for (int i
= FirstArg
; i
< argc
; ++i
) {
1606 Option
*Handler
= nullptr;
1607 std::string NearestHandlerString
;
1609 StringRef ArgName
= "";
1610 bool HaveDoubleDash
= false;
1612 // Check to see if this is a positional argument. This argument is
1613 // considered to be positional if it doesn't start with '-', if it is "-"
1614 // itself, or if we have seen "--" already.
1616 if (argv
[i
][0] != '-' || argv
[i
][1] == 0 || DashDashFound
) {
1617 // Positional argument!
1618 if (ActivePositionalArg
) {
1619 ProvidePositionalOption(ActivePositionalArg
, StringRef(argv
[i
]), i
);
1620 continue; // We are done!
1623 if (!PositionalOpts
.empty()) {
1624 PositionalVals
.push_back(std::make_pair(StringRef(argv
[i
]), i
));
1626 // All of the positional arguments have been fulfulled, give the rest to
1627 // the consume after option... if it's specified...
1629 if (PositionalVals
.size() >= NumPositionalRequired
&& ConsumeAfterOpt
) {
1630 for (++i
; i
< argc
; ++i
)
1631 PositionalVals
.push_back(std::make_pair(StringRef(argv
[i
]), i
));
1632 break; // Handle outside of the argument processing loop...
1635 // Delay processing positional arguments until the end...
1638 } else if (argv
[i
][0] == '-' && argv
[i
][1] == '-' && argv
[i
][2] == 0 &&
1640 DashDashFound
= true; // This is the mythical "--"?
1641 continue; // Don't try to process it as an argument itself.
1642 } else if (ActivePositionalArg
&&
1643 (ActivePositionalArg
->getMiscFlags() & PositionalEatsArgs
)) {
1644 // If there is a positional argument eating options, check to see if this
1645 // option is another positional argument. If so, treat it as an argument,
1646 // otherwise feed it to the eating positional.
1647 ArgName
= StringRef(argv
[i
] + 1);
1649 if (ArgName
.consume_front("-"))
1650 HaveDoubleDash
= true;
1652 Handler
= LookupLongOption(*ChosenSubCommand
, ArgName
, Value
,
1653 LongOptionsUseDoubleDash
, HaveDoubleDash
);
1654 if (!Handler
|| Handler
->getFormattingFlag() != cl::Positional
) {
1655 ProvidePositionalOption(ActivePositionalArg
, StringRef(argv
[i
]), i
);
1656 continue; // We are done!
1658 } else { // We start with a '-', must be an argument.
1659 ArgName
= StringRef(argv
[i
] + 1);
1661 if (ArgName
.consume_front("-"))
1662 HaveDoubleDash
= true;
1664 Handler
= LookupLongOption(*ChosenSubCommand
, ArgName
, Value
,
1665 LongOptionsUseDoubleDash
, HaveDoubleDash
);
1667 // If Handler is not found in a specialized subcommand, look up handler
1668 // in the top-level subcommand.
1669 // cl::opt without cl::sub belongs to top-level subcommand.
1670 if (!Handler
&& ChosenSubCommand
!= &SubCommand::getTopLevel())
1671 Handler
= LookupLongOption(SubCommand::getTopLevel(), ArgName
, Value
,
1672 LongOptionsUseDoubleDash
, HaveDoubleDash
);
1674 // Check to see if this "option" is really a prefixed or grouped argument.
1675 if (!Handler
&& !(LongOptionsUseDoubleDash
&& HaveDoubleDash
))
1676 Handler
= HandlePrefixedOrGroupedOption(ArgName
, Value
, ErrorParsing
,
1679 // Otherwise, look for the closest available option to report to the user
1680 // in the upcoming error.
1681 if (!Handler
&& SinkOpts
.empty())
1682 LookupNearestOption(ArgName
, OptionsMap
, NearestHandlerString
);
1686 if (!SinkOpts
.empty()) {
1687 for (Option
*SinkOpt
: SinkOpts
)
1688 SinkOpt
->addOccurrence(i
, "", StringRef(argv
[i
]));
1692 auto ReportUnknownArgument
= [&](bool IsArg
,
1693 StringRef NearestArgumentName
) {
1694 *Errs
<< ProgramName
<< ": Unknown "
1695 << (IsArg
? "command line argument" : "subcommand") << " '"
1696 << argv
[i
] << "'. Try: '" << argv
[0] << " --help'\n";
1698 if (NearestArgumentName
.empty())
1701 *Errs
<< ProgramName
<< ": Did you mean '";
1703 *Errs
<< PrintArg(NearestArgumentName
, 0);
1705 *Errs
<< NearestArgumentName
;
1709 if (i
> 1 || !MaybeNamedSubCommand
)
1710 ReportUnknownArgument(/*IsArg=*/true, NearestHandlerString
);
1712 ReportUnknownArgument(/*IsArg=*/false, NearestSubCommandString
);
1714 ErrorParsing
= true;
1718 // If this is a named positional argument, just remember that it is the
1720 if (Handler
->getFormattingFlag() == cl::Positional
) {
1721 if ((Handler
->getMiscFlags() & PositionalEatsArgs
) && !Value
.empty()) {
1722 Handler
->error("This argument does not take a value.\n"
1723 "\tInstead, it consumes any positional arguments until "
1724 "the next recognized option.", *Errs
);
1725 ErrorParsing
= true;
1727 ActivePositionalArg
= Handler
;
1730 ErrorParsing
|= ProvideOption(Handler
, ArgName
, Value
, argc
, argv
, i
);
1733 // Check and handle positional arguments now...
1734 if (NumPositionalRequired
> PositionalVals
.size()) {
1735 *Errs
<< ProgramName
1736 << ": Not enough positional command line arguments specified!\n"
1737 << "Must specify at least " << NumPositionalRequired
1738 << " positional argument" << (NumPositionalRequired
> 1 ? "s" : "")
1739 << ": See: " << argv
[0] << " --help\n";
1741 ErrorParsing
= true;
1742 } else if (!HasUnlimitedPositionals
&&
1743 PositionalVals
.size() > PositionalOpts
.size()) {
1744 *Errs
<< ProgramName
<< ": Too many positional arguments specified!\n"
1745 << "Can specify at most " << PositionalOpts
.size()
1746 << " positional arguments: See: " << argv
[0] << " --help\n";
1747 ErrorParsing
= true;
1749 } else if (!ConsumeAfterOpt
) {
1750 // Positional args have already been handled if ConsumeAfter is specified.
1751 unsigned ValNo
= 0, NumVals
= static_cast<unsigned>(PositionalVals
.size());
1752 for (Option
*Opt
: PositionalOpts
) {
1753 if (RequiresValue(Opt
)) {
1754 ProvidePositionalOption(Opt
, PositionalVals
[ValNo
].first
,
1755 PositionalVals
[ValNo
].second
);
1757 --NumPositionalRequired
; // We fulfilled our duty...
1760 // If we _can_ give this option more arguments, do so now, as long as we
1761 // do not give it values that others need. 'Done' controls whether the
1762 // option even _WANTS_ any more.
1764 bool Done
= Opt
->getNumOccurrencesFlag() == cl::Required
;
1765 while (NumVals
- ValNo
> NumPositionalRequired
&& !Done
) {
1766 switch (Opt
->getNumOccurrencesFlag()) {
1768 Done
= true; // Optional arguments want _at most_ one value
1770 case cl::ZeroOrMore
: // Zero or more will take all they can get...
1771 case cl::OneOrMore
: // One or more will take all they can get...
1772 ProvidePositionalOption(Opt
, PositionalVals
[ValNo
].first
,
1773 PositionalVals
[ValNo
].second
);
1777 llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
1778 "positional argument processing!");
1783 assert(ConsumeAfterOpt
&& NumPositionalRequired
<= PositionalVals
.size());
1785 for (Option
*Opt
: PositionalOpts
)
1786 if (RequiresValue(Opt
)) {
1787 ErrorParsing
|= ProvidePositionalOption(
1788 Opt
, PositionalVals
[ValNo
].first
, PositionalVals
[ValNo
].second
);
1792 // Handle the case where there is just one positional option, and it's
1793 // optional. In this case, we want to give JUST THE FIRST option to the
1794 // positional option and keep the rest for the consume after. The above
1795 // loop would have assigned no values to positional options in this case.
1797 if (PositionalOpts
.size() == 1 && ValNo
== 0 && !PositionalVals
.empty()) {
1798 ErrorParsing
|= ProvidePositionalOption(PositionalOpts
[0],
1799 PositionalVals
[ValNo
].first
,
1800 PositionalVals
[ValNo
].second
);
1804 // Handle over all of the rest of the arguments to the
1805 // cl::ConsumeAfter command line option...
1806 for (; ValNo
!= PositionalVals
.size(); ++ValNo
)
1808 ProvidePositionalOption(ConsumeAfterOpt
, PositionalVals
[ValNo
].first
,
1809 PositionalVals
[ValNo
].second
);
1812 // Loop over args and make sure all required args are specified!
1813 for (const auto &Opt
: OptionsMap
) {
1814 switch (Opt
.second
->getNumOccurrencesFlag()) {
1817 if (Opt
.second
->getNumOccurrences() == 0) {
1818 Opt
.second
->error("must be specified at least once!");
1819 ErrorParsing
= true;
1827 // Now that we know if -debug is specified, we can use it.
1828 // Note that if ReadResponseFiles == true, this must be done before the
1829 // memory allocated for the expanded command line is free()d below.
1830 LLVM_DEBUG(dbgs() << "Args: ";
1831 for (int i
= 0; i
< argc
; ++i
) dbgs() << argv
[i
] << ' ';
1834 // Free all of the memory allocated to the map. Command line options may only
1835 // be processed once!
1838 // If we had an error processing our arguments, don't let the program execute
1847 //===----------------------------------------------------------------------===//
1848 // Option Base class implementation
1851 bool Option::error(const Twine
&Message
, StringRef ArgName
, raw_ostream
&Errs
) {
1852 if (!ArgName
.data())
1854 if (ArgName
.empty())
1855 Errs
<< HelpStr
; // Be nice for positional arguments
1857 Errs
<< GlobalParser
->ProgramName
<< ": for the " << PrintArg(ArgName
, 0);
1859 Errs
<< " option: " << Message
<< "\n";
1863 bool Option::addOccurrence(unsigned pos
, StringRef ArgName
, StringRef Value
,
1866 NumOccurrences
++; // Increment the number of times we have been seen
1868 return handleOccurrence(pos
, ArgName
, Value
);
1871 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
1872 // has been specified yet.
1874 static StringRef
getValueStr(const Option
&O
, StringRef DefaultMsg
) {
1875 if (O
.ValueStr
.empty())
1880 //===----------------------------------------------------------------------===//
1881 // cl::alias class implementation
1884 // Return the width of the option tag for printing...
1885 size_t alias::getOptionWidth() const {
1886 return argPlusPrefixesSize(ArgStr
);
1889 void Option::printHelpStr(StringRef HelpStr
, size_t Indent
,
1890 size_t FirstLineIndentedBy
) {
1891 assert(Indent
>= FirstLineIndentedBy
);
1892 std::pair
<StringRef
, StringRef
> Split
= HelpStr
.split('\n');
1893 outs().indent(Indent
- FirstLineIndentedBy
)
1894 << ArgHelpPrefix
<< Split
.first
<< "\n";
1895 while (!Split
.second
.empty()) {
1896 Split
= Split
.second
.split('\n');
1897 outs().indent(Indent
) << Split
.first
<< "\n";
1901 void Option::printEnumValHelpStr(StringRef HelpStr
, size_t BaseIndent
,
1902 size_t FirstLineIndentedBy
) {
1903 const StringRef ValHelpPrefix
= " ";
1904 assert(BaseIndent
>= FirstLineIndentedBy
);
1905 std::pair
<StringRef
, StringRef
> Split
= HelpStr
.split('\n');
1906 outs().indent(BaseIndent
- FirstLineIndentedBy
)
1907 << ArgHelpPrefix
<< ValHelpPrefix
<< Split
.first
<< "\n";
1908 while (!Split
.second
.empty()) {
1909 Split
= Split
.second
.split('\n');
1910 outs().indent(BaseIndent
+ ValHelpPrefix
.size()) << Split
.first
<< "\n";
1914 // Print out the option for the alias.
1915 void alias::printOptionInfo(size_t GlobalWidth
) const {
1916 outs() << PrintArg(ArgStr
);
1917 printHelpStr(HelpStr
, GlobalWidth
, argPlusPrefixesSize(ArgStr
));
1920 //===----------------------------------------------------------------------===//
1921 // Parser Implementation code...
1924 // basic_parser implementation
1927 // Return the width of the option tag for printing...
1928 size_t basic_parser_impl::getOptionWidth(const Option
&O
) const {
1929 size_t Len
= argPlusPrefixesSize(O
.ArgStr
);
1930 auto ValName
= getValueName();
1931 if (!ValName
.empty()) {
1932 size_t FormattingLen
= 3;
1933 if (O
.getMiscFlags() & PositionalEatsArgs
)
1935 Len
+= getValueStr(O
, ValName
).size() + FormattingLen
;
1941 // printOptionInfo - Print out information about this option. The
1942 // to-be-maintained width is specified.
1944 void basic_parser_impl::printOptionInfo(const Option
&O
,
1945 size_t GlobalWidth
) const {
1946 outs() << PrintArg(O
.ArgStr
);
1948 auto ValName
= getValueName();
1949 if (!ValName
.empty()) {
1950 if (O
.getMiscFlags() & PositionalEatsArgs
) {
1951 outs() << " <" << getValueStr(O
, ValName
) << ">...";
1952 } else if (O
.getValueExpectedFlag() == ValueOptional
)
1953 outs() << "[=<" << getValueStr(O
, ValName
) << ">]";
1955 outs() << (O
.ArgStr
.size() == 1 ? " <" : "=<") << getValueStr(O
, ValName
)
1960 Option::printHelpStr(O
.HelpStr
, GlobalWidth
, getOptionWidth(O
));
1963 void basic_parser_impl::printOptionName(const Option
&O
,
1964 size_t GlobalWidth
) const {
1965 outs() << PrintArg(O
.ArgStr
);
1966 outs().indent(GlobalWidth
- O
.ArgStr
.size());
1969 // parser<bool> implementation
1971 bool parser
<bool>::parse(Option
&O
, StringRef ArgName
, StringRef Arg
,
1973 return parseBool
<bool, true, false>(O
, ArgName
, Arg
, Value
);
1976 // parser<boolOrDefault> implementation
1978 bool parser
<boolOrDefault
>::parse(Option
&O
, StringRef ArgName
, StringRef Arg
,
1979 boolOrDefault
&Value
) {
1980 return parseBool
<boolOrDefault
, BOU_TRUE
, BOU_FALSE
>(O
, ArgName
, Arg
, Value
);
1983 // parser<int> implementation
1985 bool parser
<int>::parse(Option
&O
, StringRef ArgName
, StringRef Arg
,
1987 if (Arg
.getAsInteger(0, Value
))
1988 return O
.error("'" + Arg
+ "' value invalid for integer argument!");
1992 // parser<long> implementation
1994 bool parser
<long>::parse(Option
&O
, StringRef ArgName
, StringRef Arg
,
1996 if (Arg
.getAsInteger(0, Value
))
1997 return O
.error("'" + Arg
+ "' value invalid for long argument!");
2001 // parser<long long> implementation
2003 bool parser
<long long>::parse(Option
&O
, StringRef ArgName
, StringRef Arg
,
2005 if (Arg
.getAsInteger(0, Value
))
2006 return O
.error("'" + Arg
+ "' value invalid for llong argument!");
2010 // parser<unsigned> implementation
2012 bool parser
<unsigned>::parse(Option
&O
, StringRef ArgName
, StringRef Arg
,
2015 if (Arg
.getAsInteger(0, Value
))
2016 return O
.error("'" + Arg
+ "' value invalid for uint argument!");
2020 // parser<unsigned long> implementation
2022 bool parser
<unsigned long>::parse(Option
&O
, StringRef ArgName
, StringRef Arg
,
2023 unsigned long &Value
) {
2025 if (Arg
.getAsInteger(0, Value
))
2026 return O
.error("'" + Arg
+ "' value invalid for ulong argument!");
2030 // parser<unsigned long long> implementation
2032 bool parser
<unsigned long long>::parse(Option
&O
, StringRef ArgName
,
2034 unsigned long long &Value
) {
2036 if (Arg
.getAsInteger(0, Value
))
2037 return O
.error("'" + Arg
+ "' value invalid for ullong argument!");
2041 // parser<double>/parser<float> implementation
2043 static bool parseDouble(Option
&O
, StringRef Arg
, double &Value
) {
2044 if (to_float(Arg
, Value
))
2046 return O
.error("'" + Arg
+ "' value invalid for floating point argument!");
2049 bool parser
<double>::parse(Option
&O
, StringRef ArgName
, StringRef Arg
,
2051 return parseDouble(O
, Arg
, Val
);
2054 bool parser
<float>::parse(Option
&O
, StringRef ArgName
, StringRef Arg
,
2057 if (parseDouble(O
, Arg
, dVal
))
2063 // generic_parser_base implementation
2066 // findOption - Return the option number corresponding to the specified
2067 // argument string. If the option is not found, getNumOptions() is returned.
2069 unsigned generic_parser_base::findOption(StringRef Name
) {
2070 unsigned e
= getNumOptions();
2072 for (unsigned i
= 0; i
!= e
; ++i
) {
2073 if (getOption(i
) == Name
)
2079 static StringRef EqValue
= "=<value>";
2080 static StringRef EmptyOption
= "<empty>";
2081 static StringRef OptionPrefix
= " =";
2082 static size_t getOptionPrefixesSize() {
2083 return OptionPrefix
.size() + ArgHelpPrefix
.size();
2086 static bool shouldPrintOption(StringRef Name
, StringRef Description
,
2088 return O
.getValueExpectedFlag() != ValueOptional
|| !Name
.empty() ||
2089 !Description
.empty();
2092 // Return the width of the option tag for printing...
2093 size_t generic_parser_base::getOptionWidth(const Option
&O
) const {
2094 if (O
.hasArgStr()) {
2096 argPlusPrefixesSize(O
.ArgStr
) + EqValue
.size();
2097 for (unsigned i
= 0, e
= getNumOptions(); i
!= e
; ++i
) {
2098 StringRef Name
= getOption(i
);
2099 if (!shouldPrintOption(Name
, getDescription(i
), O
))
2101 size_t NameSize
= Name
.empty() ? EmptyOption
.size() : Name
.size();
2102 Size
= std::max(Size
, NameSize
+ getOptionPrefixesSize());
2106 size_t BaseSize
= 0;
2107 for (unsigned i
= 0, e
= getNumOptions(); i
!= e
; ++i
)
2108 BaseSize
= std::max(BaseSize
, getOption(i
).size() + 8);
2113 // printOptionInfo - Print out information about this option. The
2114 // to-be-maintained width is specified.
2116 void generic_parser_base::printOptionInfo(const Option
&O
,
2117 size_t GlobalWidth
) const {
2118 if (O
.hasArgStr()) {
2119 // When the value is optional, first print a line just describing the
2120 // option without values.
2121 if (O
.getValueExpectedFlag() == ValueOptional
) {
2122 for (unsigned i
= 0, e
= getNumOptions(); i
!= e
; ++i
) {
2123 if (getOption(i
).empty()) {
2124 outs() << PrintArg(O
.ArgStr
);
2125 Option::printHelpStr(O
.HelpStr
, GlobalWidth
,
2126 argPlusPrefixesSize(O
.ArgStr
));
2132 outs() << PrintArg(O
.ArgStr
) << EqValue
;
2133 Option::printHelpStr(O
.HelpStr
, GlobalWidth
,
2135 argPlusPrefixesSize(O
.ArgStr
));
2136 for (unsigned i
= 0, e
= getNumOptions(); i
!= e
; ++i
) {
2137 StringRef OptionName
= getOption(i
);
2138 StringRef Description
= getDescription(i
);
2139 if (!shouldPrintOption(OptionName
, Description
, O
))
2141 size_t FirstLineIndent
= OptionName
.size() + getOptionPrefixesSize();
2142 outs() << OptionPrefix
<< OptionName
;
2143 if (OptionName
.empty()) {
2144 outs() << EmptyOption
;
2145 assert(FirstLineIndent
>= EmptyOption
.size());
2146 FirstLineIndent
+= EmptyOption
.size();
2148 if (!Description
.empty())
2149 Option::printEnumValHelpStr(Description
, GlobalWidth
, FirstLineIndent
);
2154 if (!O
.HelpStr
.empty())
2155 outs() << " " << O
.HelpStr
<< '\n';
2156 for (unsigned i
= 0, e
= getNumOptions(); i
!= e
; ++i
) {
2157 StringRef Option
= getOption(i
);
2158 outs() << " " << PrintArg(Option
);
2159 Option::printHelpStr(getDescription(i
), GlobalWidth
, Option
.size() + 8);
2164 static const size_t MaxOptWidth
= 8; // arbitrary spacing for printOptionDiff
2166 // printGenericOptionDiff - Print the value of this option and it's default.
2168 // "Generic" options have each value mapped to a name.
2169 void generic_parser_base::printGenericOptionDiff(
2170 const Option
&O
, const GenericOptionValue
&Value
,
2171 const GenericOptionValue
&Default
, size_t GlobalWidth
) const {
2172 outs() << " " << PrintArg(O
.ArgStr
);
2173 outs().indent(GlobalWidth
- O
.ArgStr
.size());
2175 unsigned NumOpts
= getNumOptions();
2176 for (unsigned i
= 0; i
!= NumOpts
; ++i
) {
2177 if (!Value
.compare(getOptionValue(i
)))
2180 outs() << "= " << getOption(i
);
2181 size_t L
= getOption(i
).size();
2182 size_t NumSpaces
= MaxOptWidth
> L
? MaxOptWidth
- L
: 0;
2183 outs().indent(NumSpaces
) << " (default: ";
2184 for (unsigned j
= 0; j
!= NumOpts
; ++j
) {
2185 if (!Default
.compare(getOptionValue(j
)))
2187 outs() << getOption(j
);
2193 outs() << "= *unknown option value*\n";
2196 // printOptionDiff - Specializations for printing basic value types.
2198 #define PRINT_OPT_DIFF(T) \
2199 void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D, \
2200 size_t GlobalWidth) const { \
2201 printOptionName(O, GlobalWidth); \
2204 raw_string_ostream SS(Str); \
2207 outs() << "= " << Str; \
2208 size_t NumSpaces = \
2209 MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0; \
2210 outs().indent(NumSpaces) << " (default: "; \
2212 outs() << D.getValue(); \
2214 outs() << "*no default*"; \
2218 PRINT_OPT_DIFF(bool)
2219 PRINT_OPT_DIFF(boolOrDefault
)
2221 PRINT_OPT_DIFF(long)
2222 PRINT_OPT_DIFF(long long)
2223 PRINT_OPT_DIFF(unsigned)
2224 PRINT_OPT_DIFF(unsigned long)
2225 PRINT_OPT_DIFF(unsigned long long)
2226 PRINT_OPT_DIFF(double)
2227 PRINT_OPT_DIFF(float)
2228 PRINT_OPT_DIFF(char)
2230 void parser
<std::string
>::printOptionDiff(const Option
&O
, StringRef V
,
2231 const OptionValue
<std::string
> &D
,
2232 size_t GlobalWidth
) const {
2233 printOptionName(O
, GlobalWidth
);
2234 outs() << "= " << V
;
2235 size_t NumSpaces
= MaxOptWidth
> V
.size() ? MaxOptWidth
- V
.size() : 0;
2236 outs().indent(NumSpaces
) << " (default: ";
2238 outs() << D
.getValue();
2240 outs() << "*no default*";
2244 // Print a placeholder for options that don't yet support printOptionDiff().
2245 void basic_parser_impl::printOptionNoValue(const Option
&O
,
2246 size_t GlobalWidth
) const {
2247 printOptionName(O
, GlobalWidth
);
2248 outs() << "= *cannot print option value*\n";
2251 //===----------------------------------------------------------------------===//
2252 // -help and -help-hidden option implementation
2255 static int OptNameCompare(const std::pair
<const char *, Option
*> *LHS
,
2256 const std::pair
<const char *, Option
*> *RHS
) {
2257 return strcmp(LHS
->first
, RHS
->first
);
2260 static int SubNameCompare(const std::pair
<const char *, SubCommand
*> *LHS
,
2261 const std::pair
<const char *, SubCommand
*> *RHS
) {
2262 return strcmp(LHS
->first
, RHS
->first
);
2265 // Copy Options into a vector so we can sort them as we like.
2266 static void sortOpts(StringMap
<Option
*> &OptMap
,
2267 SmallVectorImpl
<std::pair
<const char *, Option
*>> &Opts
,
2269 SmallPtrSet
<Option
*, 32> OptionSet
; // Duplicate option detection.
2271 for (StringMap
<Option
*>::iterator I
= OptMap
.begin(), E
= OptMap
.end();
2273 // Ignore really-hidden options.
2274 if (I
->second
->getOptionHiddenFlag() == ReallyHidden
)
2277 // Unless showhidden is set, ignore hidden flags.
2278 if (I
->second
->getOptionHiddenFlag() == Hidden
&& !ShowHidden
)
2281 // If we've already seen this option, don't add it to the list again.
2282 if (!OptionSet
.insert(I
->second
).second
)
2286 std::pair
<const char *, Option
*>(I
->getKey().data(), I
->second
));
2289 // Sort the options list alphabetically.
2290 array_pod_sort(Opts
.begin(), Opts
.end(), OptNameCompare
);
2294 sortSubCommands(const SmallPtrSetImpl
<SubCommand
*> &SubMap
,
2295 SmallVectorImpl
<std::pair
<const char *, SubCommand
*>> &Subs
) {
2296 for (auto *S
: SubMap
) {
2297 if (S
->getName().empty())
2299 Subs
.push_back(std::make_pair(S
->getName().data(), S
));
2301 array_pod_sort(Subs
.begin(), Subs
.end(), SubNameCompare
);
2308 const bool ShowHidden
;
2309 typedef SmallVector
<std::pair
<const char *, Option
*>, 128>
2310 StrOptionPairVector
;
2311 typedef SmallVector
<std::pair
<const char *, SubCommand
*>, 128>
2312 StrSubCommandPairVector
;
2313 // Print the options. Opts is assumed to be alphabetically sorted.
2314 virtual void printOptions(StrOptionPairVector
&Opts
, size_t MaxArgLen
) {
2315 for (size_t i
= 0, e
= Opts
.size(); i
!= e
; ++i
)
2316 Opts
[i
].second
->printOptionInfo(MaxArgLen
);
2319 void printSubCommands(StrSubCommandPairVector
&Subs
, size_t MaxSubLen
) {
2320 for (const auto &S
: Subs
) {
2321 outs() << " " << S
.first
;
2322 if (!S
.second
->getDescription().empty()) {
2323 outs().indent(MaxSubLen
- strlen(S
.first
));
2324 outs() << " - " << S
.second
->getDescription();
2331 explicit HelpPrinter(bool showHidden
) : ShowHidden(showHidden
) {}
2332 virtual ~HelpPrinter() = default;
2334 // Invoke the printer.
2335 void operator=(bool Value
) {
2340 // Halt the program since help information was printed
2345 SubCommand
*Sub
= GlobalParser
->getActiveSubCommand();
2346 auto &OptionsMap
= Sub
->OptionsMap
;
2347 auto &PositionalOpts
= Sub
->PositionalOpts
;
2348 auto &ConsumeAfterOpt
= Sub
->ConsumeAfterOpt
;
2350 StrOptionPairVector Opts
;
2351 sortOpts(OptionsMap
, Opts
, ShowHidden
);
2353 StrSubCommandPairVector Subs
;
2354 sortSubCommands(GlobalParser
->RegisteredSubCommands
, Subs
);
2356 if (!GlobalParser
->ProgramOverview
.empty())
2357 outs() << "OVERVIEW: " << GlobalParser
->ProgramOverview
<< "\n";
2359 if (Sub
== &SubCommand::getTopLevel()) {
2360 outs() << "USAGE: " << GlobalParser
->ProgramName
;
2362 outs() << " [subcommand]";
2363 outs() << " [options]";
2365 if (!Sub
->getDescription().empty()) {
2366 outs() << "SUBCOMMAND '" << Sub
->getName()
2367 << "': " << Sub
->getDescription() << "\n\n";
2369 outs() << "USAGE: " << GlobalParser
->ProgramName
<< " " << Sub
->getName()
2373 for (auto *Opt
: PositionalOpts
) {
2374 if (Opt
->hasArgStr())
2375 outs() << " --" << Opt
->ArgStr
;
2376 outs() << " " << Opt
->HelpStr
;
2379 // Print the consume after option info if it exists...
2380 if (ConsumeAfterOpt
)
2381 outs() << " " << ConsumeAfterOpt
->HelpStr
;
2383 if (Sub
== &SubCommand::getTopLevel() && !Subs
.empty()) {
2384 // Compute the maximum subcommand length...
2385 size_t MaxSubLen
= 0;
2386 for (size_t i
= 0, e
= Subs
.size(); i
!= e
; ++i
)
2387 MaxSubLen
= std::max(MaxSubLen
, strlen(Subs
[i
].first
));
2390 outs() << "SUBCOMMANDS:\n\n";
2391 printSubCommands(Subs
, MaxSubLen
);
2393 outs() << " Type \"" << GlobalParser
->ProgramName
2394 << " <subcommand> --help\" to get more help on a specific "
2400 // Compute the maximum argument length...
2401 size_t MaxArgLen
= 0;
2402 for (size_t i
= 0, e
= Opts
.size(); i
!= e
; ++i
)
2403 MaxArgLen
= std::max(MaxArgLen
, Opts
[i
].second
->getOptionWidth());
2405 outs() << "OPTIONS:\n";
2406 printOptions(Opts
, MaxArgLen
);
2408 // Print any extra help the user has declared.
2409 for (const auto &I
: GlobalParser
->MoreHelp
)
2411 GlobalParser
->MoreHelp
.clear();
2415 class CategorizedHelpPrinter
: public HelpPrinter
{
2417 explicit CategorizedHelpPrinter(bool showHidden
) : HelpPrinter(showHidden
) {}
2419 // Helper function for printOptions().
2420 // It shall return a negative value if A's name should be lexicographically
2421 // ordered before B's name. It returns a value greater than zero if B's name
2422 // should be ordered before A's name, and it returns 0 otherwise.
2423 static int OptionCategoryCompare(OptionCategory
*const *A
,
2424 OptionCategory
*const *B
) {
2425 return (*A
)->getName().compare((*B
)->getName());
2428 // Make sure we inherit our base class's operator=()
2429 using HelpPrinter::operator=;
2432 void printOptions(StrOptionPairVector
&Opts
, size_t MaxArgLen
) override
{
2433 std::vector
<OptionCategory
*> SortedCategories
;
2434 DenseMap
<OptionCategory
*, std::vector
<Option
*>> CategorizedOptions
;
2436 // Collect registered option categories into vector in preparation for
2438 for (OptionCategory
*Category
: GlobalParser
->RegisteredOptionCategories
)
2439 SortedCategories
.push_back(Category
);
2441 // Sort the different option categories alphabetically.
2442 assert(SortedCategories
.size() > 0 && "No option categories registered!");
2443 array_pod_sort(SortedCategories
.begin(), SortedCategories
.end(),
2444 OptionCategoryCompare
);
2446 // Walk through pre-sorted options and assign into categories.
2447 // Because the options are already alphabetically sorted the
2448 // options within categories will also be alphabetically sorted.
2449 for (size_t I
= 0, E
= Opts
.size(); I
!= E
; ++I
) {
2450 Option
*Opt
= Opts
[I
].second
;
2451 for (auto &Cat
: Opt
->Categories
) {
2452 assert(llvm::is_contained(SortedCategories
, Cat
) &&
2453 "Option has an unregistered category");
2454 CategorizedOptions
[Cat
].push_back(Opt
);
2459 for (OptionCategory
*Category
: SortedCategories
) {
2460 // Hide empty categories for --help, but show for --help-hidden.
2461 const auto &CategoryOptions
= CategorizedOptions
[Category
];
2462 if (CategoryOptions
.empty())
2465 // Print category information.
2467 outs() << Category
->getName() << ":\n";
2469 // Check if description is set.
2470 if (!Category
->getDescription().empty())
2471 outs() << Category
->getDescription() << "\n\n";
2475 // Loop over the options in the category and print.
2476 for (const Option
*Opt
: CategoryOptions
)
2477 Opt
->printOptionInfo(MaxArgLen
);
2482 // This wraps the Uncategorizing and Categorizing printers and decides
2483 // at run time which should be invoked.
2484 class HelpPrinterWrapper
{
2486 HelpPrinter
&UncategorizedPrinter
;
2487 CategorizedHelpPrinter
&CategorizedPrinter
;
2490 explicit HelpPrinterWrapper(HelpPrinter
&UncategorizedPrinter
,
2491 CategorizedHelpPrinter
&CategorizedPrinter
)
2492 : UncategorizedPrinter(UncategorizedPrinter
),
2493 CategorizedPrinter(CategorizedPrinter
) {}
2495 // Invoke the printer.
2496 void operator=(bool Value
);
2499 } // End anonymous namespace
2501 #if defined(__GNUC__)
2502 // GCC and GCC-compatible compilers define __OPTIMIZE__ when optimizations are
2504 # if defined(__OPTIMIZE__)
2505 # define LLVM_IS_DEBUG_BUILD 0
2507 # define LLVM_IS_DEBUG_BUILD 1
2509 #elif defined(_MSC_VER)
2510 // MSVC doesn't have a predefined macro indicating if optimizations are enabled.
2511 // Use _DEBUG instead. This macro actually corresponds to the choice between
2512 // debug and release CRTs, but it is a reasonable proxy.
2513 # if defined(_DEBUG)
2514 # define LLVM_IS_DEBUG_BUILD 1
2516 # define LLVM_IS_DEBUG_BUILD 0
2519 // Otherwise, for an unknown compiler, assume this is an optimized build.
2520 # define LLVM_IS_DEBUG_BUILD 0
2524 class VersionPrinter
{
2526 void print(std::vector
<VersionPrinterTy
> ExtraPrinters
= {}) {
2527 raw_ostream
&OS
= outs();
2528 #ifdef PACKAGE_VENDOR
2529 OS
<< PACKAGE_VENDOR
<< " ";
2531 OS
<< "LLVM (http://llvm.org/):\n ";
2533 OS
<< PACKAGE_NAME
<< " version " << PACKAGE_VERSION
<< "\n ";
2534 #if LLVM_IS_DEBUG_BUILD
2535 OS
<< "DEBUG build";
2537 OS
<< "Optimized build";
2540 OS
<< " with assertions";
2544 // Iterate over any registered extra printers and call them to add further
2546 if (!ExtraPrinters
.empty()) {
2547 for (const auto &I
: ExtraPrinters
)
2551 void operator=(bool OptionWasSpecified
);
2554 struct CommandLineCommonOptions
{
2555 // Declare the four HelpPrinter instances that are used to print out help, or
2556 // help-hidden as an uncategorized list or in categories.
2557 HelpPrinter UncategorizedNormalPrinter
{false};
2558 HelpPrinter UncategorizedHiddenPrinter
{true};
2559 CategorizedHelpPrinter CategorizedNormalPrinter
{false};
2560 CategorizedHelpPrinter CategorizedHiddenPrinter
{true};
2561 // Declare HelpPrinter wrappers that will decide whether or not to invoke
2562 // a categorizing help printer
2563 HelpPrinterWrapper WrappedNormalPrinter
{UncategorizedNormalPrinter
,
2564 CategorizedNormalPrinter
};
2565 HelpPrinterWrapper WrappedHiddenPrinter
{UncategorizedHiddenPrinter
,
2566 CategorizedHiddenPrinter
};
2567 // Define a category for generic options that all tools should have.
2568 cl::OptionCategory GenericCategory
{"Generic Options"};
2570 // Define uncategorized help printers.
2571 // --help-list is hidden by default because if Option categories are being
2572 // used then --help behaves the same as --help-list.
2573 cl::opt
<HelpPrinter
, true, parser
<bool>> HLOp
{
2576 "Display list of available options (--help-list-hidden for more)"),
2577 cl::location(UncategorizedNormalPrinter
),
2579 cl::ValueDisallowed
,
2580 cl::cat(GenericCategory
),
2581 cl::sub(SubCommand::getAll())};
2583 cl::opt
<HelpPrinter
, true, parser
<bool>> HLHOp
{
2585 cl::desc("Display list of all available options"),
2586 cl::location(UncategorizedHiddenPrinter
),
2588 cl::ValueDisallowed
,
2589 cl::cat(GenericCategory
),
2590 cl::sub(SubCommand::getAll())};
2592 // Define uncategorized/categorized help printers. These printers change their
2593 // behaviour at runtime depending on whether one or more Option categories
2594 // have been declared.
2595 cl::opt
<HelpPrinterWrapper
, true, parser
<bool>> HOp
{
2597 cl::desc("Display available options (--help-hidden for more)"),
2598 cl::location(WrappedNormalPrinter
),
2599 cl::ValueDisallowed
,
2600 cl::cat(GenericCategory
),
2601 cl::sub(SubCommand::getAll())};
2603 cl::alias HOpA
{"h", cl::desc("Alias for --help"), cl::aliasopt(HOp
),
2606 cl::opt
<HelpPrinterWrapper
, true, parser
<bool>> HHOp
{
2608 cl::desc("Display all available options"),
2609 cl::location(WrappedHiddenPrinter
),
2611 cl::ValueDisallowed
,
2612 cl::cat(GenericCategory
),
2613 cl::sub(SubCommand::getAll())};
2615 cl::opt
<bool> PrintOptions
{
2617 cl::desc("Print non-default options after command line parsing"),
2620 cl::cat(GenericCategory
),
2621 cl::sub(SubCommand::getAll())};
2623 cl::opt
<bool> PrintAllOptions
{
2624 "print-all-options",
2625 cl::desc("Print all option values after command line parsing"),
2628 cl::cat(GenericCategory
),
2629 cl::sub(SubCommand::getAll())};
2631 VersionPrinterTy OverrideVersionPrinter
= nullptr;
2633 std::vector
<VersionPrinterTy
> ExtraVersionPrinters
;
2635 // Define the --version option that prints out the LLVM version for the tool
2636 VersionPrinter VersionPrinterInstance
;
2638 cl::opt
<VersionPrinter
, true, parser
<bool>> VersOp
{
2639 "version", cl::desc("Display the version of this program"),
2640 cl::location(VersionPrinterInstance
), cl::ValueDisallowed
,
2641 cl::cat(GenericCategory
)};
2643 } // End anonymous namespace
2645 // Lazy-initialized global instance of options controlling the command-line
2646 // parser and general handling.
2647 static ManagedStatic
<CommandLineCommonOptions
> CommonOptions
;
2649 static void initCommonOptions() {
2651 initDebugCounterOptions();
2652 initGraphWriterOptions();
2653 initSignalsOptions();
2654 initStatisticOptions();
2656 initTypeSizeOptions();
2657 initWithColorOptions();
2659 initRandomSeedOptions();
2662 OptionCategory
&cl::getGeneralCategory() {
2663 // Initialise the general option category.
2664 static OptionCategory GeneralCategory
{"General options"};
2665 return GeneralCategory
;
2668 void VersionPrinter::operator=(bool OptionWasSpecified
) {
2669 if (!OptionWasSpecified
)
2672 if (CommonOptions
->OverrideVersionPrinter
!= nullptr) {
2673 CommonOptions
->OverrideVersionPrinter(outs());
2676 print(CommonOptions
->ExtraVersionPrinters
);
2681 void HelpPrinterWrapper::operator=(bool Value
) {
2685 // Decide which printer to invoke. If more than one option category is
2686 // registered then it is useful to show the categorized help instead of
2687 // uncategorized help.
2688 if (GlobalParser
->RegisteredOptionCategories
.size() > 1) {
2689 // unhide --help-list option so user can have uncategorized output if they
2691 CommonOptions
->HLOp
.setHiddenFlag(NotHidden
);
2693 CategorizedPrinter
= true; // Invoke categorized printer
2695 UncategorizedPrinter
= true; // Invoke uncategorized printer
2698 // Print the value of each option.
2699 void cl::PrintOptionValues() { GlobalParser
->printOptionValues(); }
2701 void CommandLineParser::printOptionValues() {
2702 if (!CommonOptions
->PrintOptions
&& !CommonOptions
->PrintAllOptions
)
2705 SmallVector
<std::pair
<const char *, Option
*>, 128> Opts
;
2706 sortOpts(ActiveSubCommand
->OptionsMap
, Opts
, /*ShowHidden*/ true);
2708 // Compute the maximum argument length...
2709 size_t MaxArgLen
= 0;
2710 for (size_t i
= 0, e
= Opts
.size(); i
!= e
; ++i
)
2711 MaxArgLen
= std::max(MaxArgLen
, Opts
[i
].second
->getOptionWidth());
2713 for (size_t i
= 0, e
= Opts
.size(); i
!= e
; ++i
)
2714 Opts
[i
].second
->printOptionValue(MaxArgLen
, CommonOptions
->PrintAllOptions
);
2717 // Utility function for printing the help message.
2718 void cl::PrintHelpMessage(bool Hidden
, bool Categorized
) {
2719 if (!Hidden
&& !Categorized
)
2720 CommonOptions
->UncategorizedNormalPrinter
.printHelp();
2721 else if (!Hidden
&& Categorized
)
2722 CommonOptions
->CategorizedNormalPrinter
.printHelp();
2723 else if (Hidden
&& !Categorized
)
2724 CommonOptions
->UncategorizedHiddenPrinter
.printHelp();
2726 CommonOptions
->CategorizedHiddenPrinter
.printHelp();
2729 ArrayRef
<StringRef
> cl::getCompilerBuildConfig() {
2730 static const StringRef Config
[] = {
2731 // Placeholder to ensure the array always has elements, since it's an
2732 // error to have a zero-sized array. Slice this off before returning.
2734 // Actual compiler build config feature list:
2735 #if LLVM_IS_DEBUG_BUILD
2741 #ifdef EXPENSIVE_CHECKS
2742 "+expensive-checks",
2744 #if __has_feature(address_sanitizer)
2747 #if __has_feature(dataflow_sanitizer)
2750 #if __has_feature(hwaddress_sanitizer)
2753 #if __has_feature(memory_sanitizer)
2756 #if __has_feature(thread_sanitizer)
2759 #if __has_feature(undefined_behavior_sanitizer)
2763 return ArrayRef(Config
).drop_front(1);
2766 // Utility function for printing the build config.
2767 void cl::printBuildConfig(raw_ostream
&OS
) {
2768 #if LLVM_VERSION_PRINTER_SHOW_BUILD_CONFIG
2769 OS
<< "Build config: ";
2770 llvm::interleaveComma(cl::getCompilerBuildConfig(), OS
);
2775 /// Utility function for printing version number.
2776 void cl::PrintVersionMessage() {
2777 CommonOptions
->VersionPrinterInstance
.print(CommonOptions
->ExtraVersionPrinters
);
2780 void cl::SetVersionPrinter(VersionPrinterTy func
) {
2781 CommonOptions
->OverrideVersionPrinter
= func
;
2784 void cl::AddExtraVersionPrinter(VersionPrinterTy func
) {
2785 CommonOptions
->ExtraVersionPrinters
.push_back(func
);
2788 StringMap
<Option
*> &cl::getRegisteredOptions(SubCommand
&Sub
) {
2789 initCommonOptions();
2790 auto &Subs
= GlobalParser
->RegisteredSubCommands
;
2792 assert(Subs
.contains(&Sub
));
2793 return Sub
.OptionsMap
;
2796 iterator_range
<typename SmallPtrSet
<SubCommand
*, 4>::iterator
>
2797 cl::getRegisteredSubcommands() {
2798 return GlobalParser
->getRegisteredSubcommands();
2801 void cl::HideUnrelatedOptions(cl::OptionCategory
&Category
, SubCommand
&Sub
) {
2802 initCommonOptions();
2803 for (auto &I
: Sub
.OptionsMap
) {
2804 bool Unrelated
= true;
2805 for (auto &Cat
: I
.second
->Categories
) {
2806 if (Cat
== &Category
|| Cat
== &CommonOptions
->GenericCategory
)
2810 I
.second
->setHiddenFlag(cl::ReallyHidden
);
2814 void cl::HideUnrelatedOptions(ArrayRef
<const cl::OptionCategory
*> Categories
,
2816 initCommonOptions();
2817 for (auto &I
: Sub
.OptionsMap
) {
2818 bool Unrelated
= true;
2819 for (auto &Cat
: I
.second
->Categories
) {
2820 if (is_contained(Categories
, Cat
) ||
2821 Cat
== &CommonOptions
->GenericCategory
)
2825 I
.second
->setHiddenFlag(cl::ReallyHidden
);
2829 void cl::ResetCommandLineParser() { GlobalParser
->reset(); }
2830 void cl::ResetAllOptionOccurrences() {
2831 GlobalParser
->ResetAllOptionOccurrences();
2834 void LLVMParseCommandLineOptions(int argc
, const char *const *argv
,
2835 const char *Overview
) {
2836 llvm::cl::ParseCommandLineOptions(argc
, argv
, StringRef(Overview
),