xref: /llvm-project/llvm/lib/Support/CommandLine.cpp (revision 75656005dbc8866e1888932a68a830b0df403560)
1 //===-- CommandLine.cpp - Command line parser implementation --------------===//
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 could try
14 // reading the library documentation located in docs/CommandLine.html
15 //
16 //===----------------------------------------------------------------------===//
17 
18 #include "llvm/Support/CommandLine.h"
19 #include "llvm-c/Support.h"
20 #include "llvm/ADT/ArrayRef.h"
21 #include "llvm/ADT/Optional.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/StringMap.h"
27 #include "llvm/ADT/StringRef.h"
28 #include "llvm/ADT/Triple.h"
29 #include "llvm/ADT/Twine.h"
30 #include "llvm/Config/config.h"
31 #include "llvm/Support/ConvertUTF.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/Error.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/FileSystem.h"
36 #include "llvm/Support/Host.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"
44 #include <cstdlib>
45 #include <map>
46 #include <string>
47 using namespace llvm;
48 using namespace cl;
49 
50 #define DEBUG_TYPE "commandline"
51 
52 //===----------------------------------------------------------------------===//
53 // Template instantiations and anchors.
54 //
55 namespace llvm {
56 namespace cl {
57 template class basic_parser<bool>;
58 template class basic_parser<boolOrDefault>;
59 template class basic_parser<int>;
60 template class basic_parser<unsigned>;
61 template class basic_parser<unsigned long>;
62 template class basic_parser<unsigned long long>;
63 template class basic_parser<double>;
64 template class basic_parser<float>;
65 template class basic_parser<std::string>;
66 template class basic_parser<char>;
67 
68 template class opt<unsigned>;
69 template class opt<int>;
70 template class opt<std::string>;
71 template class opt<char>;
72 template class opt<bool>;
73 }
74 } // end namespace llvm::cl
75 
76 // Pin the vtables to this file.
77 void GenericOptionValue::anchor() {}
78 void OptionValue<boolOrDefault>::anchor() {}
79 void OptionValue<std::string>::anchor() {}
80 void Option::anchor() {}
81 void basic_parser_impl::anchor() {}
82 void parser<bool>::anchor() {}
83 void parser<boolOrDefault>::anchor() {}
84 void parser<int>::anchor() {}
85 void parser<unsigned>::anchor() {}
86 void parser<unsigned long>::anchor() {}
87 void parser<unsigned long long>::anchor() {}
88 void parser<double>::anchor() {}
89 void parser<float>::anchor() {}
90 void parser<std::string>::anchor() {}
91 void parser<char>::anchor() {}
92 
93 //===----------------------------------------------------------------------===//
94 
95 const static size_t DefaultPad = 2;
96 
97 static StringRef ArgPrefix = "-";
98 static StringRef ArgPrefixLong = "--";
99 static StringRef ArgHelpPrefix = " - ";
100 
101 static size_t argPlusPrefixesSize(StringRef ArgName, size_t Pad = DefaultPad) {
102   size_t Len = ArgName.size();
103   if (Len == 1)
104     return Len + Pad + ArgPrefix.size() + ArgHelpPrefix.size();
105   return Len + Pad + ArgPrefixLong.size() + ArgHelpPrefix.size();
106 }
107 
108 static SmallString<8> argPrefix(StringRef ArgName, size_t Pad = DefaultPad) {
109   SmallString<8> Prefix;
110   for (size_t I = 0; I < Pad; ++I) {
111     Prefix.push_back(' ');
112   }
113   Prefix.append(ArgName.size() > 1 ? ArgPrefixLong : ArgPrefix);
114   return Prefix;
115 }
116 
117 // Option predicates...
118 static inline bool isGrouping(const Option *O) {
119   return O->getMiscFlags() & cl::Grouping;
120 }
121 static inline bool isPrefixedOrGrouping(const Option *O) {
122   return isGrouping(O) || O->getFormattingFlag() == cl::Prefix ||
123          O->getFormattingFlag() == cl::AlwaysPrefix;
124 }
125 
126 
127 namespace {
128 
129 class PrintArg {
130   StringRef ArgName;
131   size_t Pad;
132 public:
133   PrintArg(StringRef ArgName, size_t Pad = DefaultPad) : ArgName(ArgName), Pad(Pad) {}
134   friend raw_ostream &operator<<(raw_ostream &OS, const PrintArg &);
135 };
136 
137 raw_ostream &operator<<(raw_ostream &OS, const PrintArg& Arg) {
138   OS << argPrefix(Arg.ArgName, Arg.Pad) << Arg.ArgName;
139   return OS;
140 }
141 
142 class CommandLineParser {
143 public:
144   // Globals for name and overview of program.  Program name is not a string to
145   // avoid static ctor/dtor issues.
146   std::string ProgramName;
147   StringRef ProgramOverview;
148 
149   // This collects additional help to be printed.
150   std::vector<StringRef> MoreHelp;
151 
152   // This collects Options added with the cl::DefaultOption flag. Since they can
153   // be overridden, they are not added to the appropriate SubCommands until
154   // ParseCommandLineOptions actually runs.
155   SmallVector<Option*, 4> DefaultOptions;
156 
157   // This collects the different option categories that have been registered.
158   SmallPtrSet<OptionCategory *, 16> RegisteredOptionCategories;
159 
160   // This collects the different subcommands that have been registered.
161   SmallPtrSet<SubCommand *, 4> RegisteredSubCommands;
162 
163   CommandLineParser() : ActiveSubCommand(nullptr) {
164     registerSubCommand(&*TopLevelSubCommand);
165     registerSubCommand(&*AllSubCommands);
166   }
167 
168   void ResetAllOptionOccurrences();
169 
170   bool ParseCommandLineOptions(int argc, const char *const *argv,
171                                StringRef Overview, raw_ostream *Errs = nullptr,
172                                bool LongOptionsUseDoubleDash = false);
173 
174   void addLiteralOption(Option &Opt, SubCommand *SC, StringRef Name) {
175     if (Opt.hasArgStr())
176       return;
177     if (!SC->OptionsMap.insert(std::make_pair(Name, &Opt)).second) {
178       errs() << ProgramName << ": CommandLine Error: Option '" << Name
179              << "' registered more than once!\n";
180       report_fatal_error("inconsistency in registered CommandLine options");
181     }
182 
183     // If we're adding this to all sub-commands, add it to the ones that have
184     // already been registered.
185     if (SC == &*AllSubCommands) {
186       for (const auto &Sub : RegisteredSubCommands) {
187         if (SC == Sub)
188           continue;
189         addLiteralOption(Opt, Sub, Name);
190       }
191     }
192   }
193 
194   void addLiteralOption(Option &Opt, StringRef Name) {
195     if (Opt.Subs.empty())
196       addLiteralOption(Opt, &*TopLevelSubCommand, Name);
197     else {
198       for (auto SC : Opt.Subs)
199         addLiteralOption(Opt, SC, Name);
200     }
201   }
202 
203   void addOption(Option *O, SubCommand *SC) {
204     bool HadErrors = false;
205     if (O->hasArgStr()) {
206       // If it's a DefaultOption, check to make sure it isn't already there.
207       if (O->isDefaultOption() &&
208           SC->OptionsMap.find(O->ArgStr) != SC->OptionsMap.end())
209         return;
210 
211       // Add argument to the argument map!
212       if (!SC->OptionsMap.insert(std::make_pair(O->ArgStr, O)).second) {
213         errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
214                << "' registered more than once!\n";
215         HadErrors = true;
216       }
217     }
218 
219     // Remember information about positional options.
220     if (O->getFormattingFlag() == cl::Positional)
221       SC->PositionalOpts.push_back(O);
222     else if (O->getMiscFlags() & cl::Sink) // Remember sink options
223       SC->SinkOpts.push_back(O);
224     else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
225       if (SC->ConsumeAfterOpt) {
226         O->error("Cannot specify more than one option with cl::ConsumeAfter!");
227         HadErrors = true;
228       }
229       SC->ConsumeAfterOpt = O;
230     }
231 
232     // Fail hard if there were errors. These are strictly unrecoverable and
233     // indicate serious issues such as conflicting option names or an
234     // incorrectly
235     // linked LLVM distribution.
236     if (HadErrors)
237       report_fatal_error("inconsistency in registered CommandLine options");
238 
239     // If we're adding this to all sub-commands, add it to the ones that have
240     // already been registered.
241     if (SC == &*AllSubCommands) {
242       for (const auto &Sub : RegisteredSubCommands) {
243         if (SC == Sub)
244           continue;
245         addOption(O, Sub);
246       }
247     }
248   }
249 
250   void addOption(Option *O, bool ProcessDefaultOption = false) {
251     if (!ProcessDefaultOption && O->isDefaultOption()) {
252       DefaultOptions.push_back(O);
253       return;
254     }
255 
256     if (O->Subs.empty()) {
257       addOption(O, &*TopLevelSubCommand);
258     } else {
259       for (auto SC : O->Subs)
260         addOption(O, SC);
261     }
262   }
263 
264   void removeOption(Option *O, SubCommand *SC) {
265     SmallVector<StringRef, 16> OptionNames;
266     O->getExtraOptionNames(OptionNames);
267     if (O->hasArgStr())
268       OptionNames.push_back(O->ArgStr);
269 
270     SubCommand &Sub = *SC;
271     auto End = Sub.OptionsMap.end();
272     for (auto Name : OptionNames) {
273       auto I = Sub.OptionsMap.find(Name);
274       if (I != End && I->getValue() == O)
275         Sub.OptionsMap.erase(I);
276       }
277 
278     if (O->getFormattingFlag() == cl::Positional)
279       for (auto Opt = Sub.PositionalOpts.begin();
280            Opt != Sub.PositionalOpts.end(); ++Opt) {
281         if (*Opt == O) {
282           Sub.PositionalOpts.erase(Opt);
283           break;
284         }
285       }
286     else if (O->getMiscFlags() & cl::Sink)
287       for (auto Opt = Sub.SinkOpts.begin(); Opt != Sub.SinkOpts.end(); ++Opt) {
288         if (*Opt == O) {
289           Sub.SinkOpts.erase(Opt);
290           break;
291         }
292       }
293     else if (O == Sub.ConsumeAfterOpt)
294       Sub.ConsumeAfterOpt = nullptr;
295   }
296 
297   void removeOption(Option *O) {
298     if (O->Subs.empty())
299       removeOption(O, &*TopLevelSubCommand);
300     else {
301       if (O->isInAllSubCommands()) {
302         for (auto SC : RegisteredSubCommands)
303           removeOption(O, SC);
304       } else {
305         for (auto SC : O->Subs)
306           removeOption(O, SC);
307       }
308     }
309   }
310 
311   bool hasOptions(const SubCommand &Sub) const {
312     return (!Sub.OptionsMap.empty() || !Sub.PositionalOpts.empty() ||
313             nullptr != Sub.ConsumeAfterOpt);
314   }
315 
316   bool hasOptions() const {
317     for (const auto &S : RegisteredSubCommands) {
318       if (hasOptions(*S))
319         return true;
320     }
321     return false;
322   }
323 
324   SubCommand *getActiveSubCommand() { return ActiveSubCommand; }
325 
326   void updateArgStr(Option *O, StringRef NewName, SubCommand *SC) {
327     SubCommand &Sub = *SC;
328     if (!Sub.OptionsMap.insert(std::make_pair(NewName, O)).second) {
329       errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
330              << "' registered more than once!\n";
331       report_fatal_error("inconsistency in registered CommandLine options");
332     }
333     Sub.OptionsMap.erase(O->ArgStr);
334   }
335 
336   void updateArgStr(Option *O, StringRef NewName) {
337     if (O->Subs.empty())
338       updateArgStr(O, NewName, &*TopLevelSubCommand);
339     else {
340       if (O->isInAllSubCommands()) {
341         for (auto SC : RegisteredSubCommands)
342           updateArgStr(O, NewName, SC);
343       } else {
344         for (auto SC : O->Subs)
345           updateArgStr(O, NewName, SC);
346       }
347     }
348   }
349 
350   void printOptionValues();
351 
352   void registerCategory(OptionCategory *cat) {
353     assert(count_if(RegisteredOptionCategories,
354                     [cat](const OptionCategory *Category) {
355              return cat->getName() == Category->getName();
356            }) == 0 &&
357            "Duplicate option categories");
358 
359     RegisteredOptionCategories.insert(cat);
360   }
361 
362   void registerSubCommand(SubCommand *sub) {
363     assert(count_if(RegisteredSubCommands,
364                     [sub](const SubCommand *Sub) {
365                       return (!sub->getName().empty()) &&
366                              (Sub->getName() == sub->getName());
367                     }) == 0 &&
368            "Duplicate subcommands");
369     RegisteredSubCommands.insert(sub);
370 
371     // For all options that have been registered for all subcommands, add the
372     // option to this subcommand now.
373     if (sub != &*AllSubCommands) {
374       for (auto &E : AllSubCommands->OptionsMap) {
375         Option *O = E.second;
376         if ((O->isPositional() || O->isSink() || O->isConsumeAfter()) ||
377             O->hasArgStr())
378           addOption(O, sub);
379         else
380           addLiteralOption(*O, sub, E.first());
381       }
382     }
383   }
384 
385   void unregisterSubCommand(SubCommand *sub) {
386     RegisteredSubCommands.erase(sub);
387   }
388 
389   iterator_range<typename SmallPtrSet<SubCommand *, 4>::iterator>
390   getRegisteredSubcommands() {
391     return make_range(RegisteredSubCommands.begin(),
392                       RegisteredSubCommands.end());
393   }
394 
395   void reset() {
396     ActiveSubCommand = nullptr;
397     ProgramName.clear();
398     ProgramOverview = StringRef();
399 
400     MoreHelp.clear();
401     RegisteredOptionCategories.clear();
402 
403     ResetAllOptionOccurrences();
404     RegisteredSubCommands.clear();
405 
406     TopLevelSubCommand->reset();
407     AllSubCommands->reset();
408     registerSubCommand(&*TopLevelSubCommand);
409     registerSubCommand(&*AllSubCommands);
410 
411     DefaultOptions.clear();
412   }
413 
414 private:
415   SubCommand *ActiveSubCommand;
416 
417   Option *LookupOption(SubCommand &Sub, StringRef &Arg, StringRef &Value);
418   Option *LookupLongOption(SubCommand &Sub, StringRef &Arg, StringRef &Value,
419                            bool LongOptionsUseDoubleDash, bool HaveDoubleDash) {
420     Option *Opt = LookupOption(Sub, Arg, Value);
421     if (Opt && LongOptionsUseDoubleDash && !HaveDoubleDash && !isGrouping(Opt))
422       return nullptr;
423     return Opt;
424   }
425   SubCommand *LookupSubCommand(StringRef Name);
426 };
427 
428 } // namespace
429 
430 static ManagedStatic<CommandLineParser> GlobalParser;
431 
432 void cl::AddLiteralOption(Option &O, StringRef Name) {
433   GlobalParser->addLiteralOption(O, Name);
434 }
435 
436 extrahelp::extrahelp(StringRef Help) : morehelp(Help) {
437   GlobalParser->MoreHelp.push_back(Help);
438 }
439 
440 void Option::addArgument() {
441   GlobalParser->addOption(this);
442   FullyInitialized = true;
443 }
444 
445 void Option::removeArgument() { GlobalParser->removeOption(this); }
446 
447 void Option::setArgStr(StringRef S) {
448   if (FullyInitialized)
449     GlobalParser->updateArgStr(this, S);
450   assert((S.empty() || S[0] != '-') && "Option can't start with '-");
451   ArgStr = S;
452   if (ArgStr.size() == 1)
453     setMiscFlag(Grouping);
454 }
455 
456 void Option::addCategory(OptionCategory &C) {
457   assert(!Categories.empty() && "Categories cannot be empty.");
458   // Maintain backward compatibility by replacing the default GeneralCategory
459   // if it's still set.  Otherwise, just add the new one.  The GeneralCategory
460   // must be explicitly added if you want multiple categories that include it.
461   if (&C != &GeneralCategory && Categories[0] == &GeneralCategory)
462     Categories[0] = &C;
463   else if (find(Categories, &C) == Categories.end())
464     Categories.push_back(&C);
465 }
466 
467 void Option::reset() {
468   NumOccurrences = 0;
469   setDefault();
470   if (isDefaultOption())
471     removeArgument();
472 }
473 
474 // Initialise the general option category.
475 OptionCategory llvm::cl::GeneralCategory("General options");
476 
477 void OptionCategory::registerCategory() {
478   GlobalParser->registerCategory(this);
479 }
480 
481 // A special subcommand representing no subcommand. It is particularly important
482 // that this ManagedStatic uses constant initailization and not dynamic
483 // initialization because it is referenced from cl::opt constructors, which run
484 // dynamically in an arbitrary order.
485 LLVM_REQUIRE_CONSTANT_INITIALIZATION
486 ManagedStatic<SubCommand> llvm::cl::TopLevelSubCommand;
487 
488 // A special subcommand that can be used to put an option into all subcommands.
489 ManagedStatic<SubCommand> llvm::cl::AllSubCommands;
490 
491 void SubCommand::registerSubCommand() {
492   GlobalParser->registerSubCommand(this);
493 }
494 
495 void SubCommand::unregisterSubCommand() {
496   GlobalParser->unregisterSubCommand(this);
497 }
498 
499 void SubCommand::reset() {
500   PositionalOpts.clear();
501   SinkOpts.clear();
502   OptionsMap.clear();
503 
504   ConsumeAfterOpt = nullptr;
505 }
506 
507 SubCommand::operator bool() const {
508   return (GlobalParser->getActiveSubCommand() == this);
509 }
510 
511 //===----------------------------------------------------------------------===//
512 // Basic, shared command line option processing machinery.
513 //
514 
515 /// LookupOption - Lookup the option specified by the specified option on the
516 /// command line.  If there is a value specified (after an equal sign) return
517 /// that as well.  This assumes that leading dashes have already been stripped.
518 Option *CommandLineParser::LookupOption(SubCommand &Sub, StringRef &Arg,
519                                         StringRef &Value) {
520   // Reject all dashes.
521   if (Arg.empty())
522     return nullptr;
523   assert(&Sub != &*AllSubCommands);
524 
525   size_t EqualPos = Arg.find('=');
526 
527   // If we have an equals sign, remember the value.
528   if (EqualPos == StringRef::npos) {
529     // Look up the option.
530     auto I = Sub.OptionsMap.find(Arg);
531     if (I == Sub.OptionsMap.end())
532       return nullptr;
533 
534     return I != Sub.OptionsMap.end() ? I->second : nullptr;
535   }
536 
537   // If the argument before the = is a valid option name and the option allows
538   // non-prefix form (ie is not AlwaysPrefix), we match.  If not, signal match
539   // failure by returning nullptr.
540   auto I = Sub.OptionsMap.find(Arg.substr(0, EqualPos));
541   if (I == Sub.OptionsMap.end())
542     return nullptr;
543 
544   auto O = I->second;
545   if (O->getFormattingFlag() == cl::AlwaysPrefix)
546     return nullptr;
547 
548   Value = Arg.substr(EqualPos + 1);
549   Arg = Arg.substr(0, EqualPos);
550   return I->second;
551 }
552 
553 SubCommand *CommandLineParser::LookupSubCommand(StringRef Name) {
554   if (Name.empty())
555     return &*TopLevelSubCommand;
556   for (auto S : RegisteredSubCommands) {
557     if (S == &*AllSubCommands)
558       continue;
559     if (S->getName().empty())
560       continue;
561 
562     if (StringRef(S->getName()) == StringRef(Name))
563       return S;
564   }
565   return &*TopLevelSubCommand;
566 }
567 
568 /// LookupNearestOption - Lookup the closest match to the option specified by
569 /// the specified option on the command line.  If there is a value specified
570 /// (after an equal sign) return that as well.  This assumes that leading dashes
571 /// have already been stripped.
572 static Option *LookupNearestOption(StringRef Arg,
573                                    const StringMap<Option *> &OptionsMap,
574                                    std::string &NearestString) {
575   // Reject all dashes.
576   if (Arg.empty())
577     return nullptr;
578 
579   // Split on any equal sign.
580   std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
581   StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
582   StringRef &RHS = SplitArg.second;
583 
584   // Find the closest match.
585   Option *Best = nullptr;
586   unsigned BestDistance = 0;
587   for (StringMap<Option *>::const_iterator it = OptionsMap.begin(),
588                                            ie = OptionsMap.end();
589        it != ie; ++it) {
590     Option *O = it->second;
591     SmallVector<StringRef, 16> OptionNames;
592     O->getExtraOptionNames(OptionNames);
593     if (O->hasArgStr())
594       OptionNames.push_back(O->ArgStr);
595 
596     bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
597     StringRef Flag = PermitValue ? LHS : Arg;
598     for (auto Name : OptionNames) {
599       unsigned Distance = StringRef(Name).edit_distance(
600           Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
601       if (!Best || Distance < BestDistance) {
602         Best = O;
603         BestDistance = Distance;
604         if (RHS.empty() || !PermitValue)
605           NearestString = Name;
606         else
607           NearestString = (Twine(Name) + "=" + RHS).str();
608       }
609     }
610   }
611 
612   return Best;
613 }
614 
615 /// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence()
616 /// that does special handling of cl::CommaSeparated options.
617 static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos,
618                                           StringRef ArgName, StringRef Value,
619                                           bool MultiArg = false) {
620   // Check to see if this option accepts a comma separated list of values.  If
621   // it does, we have to split up the value into multiple values.
622   if (Handler->getMiscFlags() & CommaSeparated) {
623     StringRef Val(Value);
624     StringRef::size_type Pos = Val.find(',');
625 
626     while (Pos != StringRef::npos) {
627       // Process the portion before the comma.
628       if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
629         return true;
630       // Erase the portion before the comma, AND the comma.
631       Val = Val.substr(Pos + 1);
632       // Check for another comma.
633       Pos = Val.find(',');
634     }
635 
636     Value = Val;
637   }
638 
639   return Handler->addOccurrence(pos, ArgName, Value, MultiArg);
640 }
641 
642 /// ProvideOption - For Value, this differentiates between an empty value ("")
643 /// and a null value (StringRef()).  The later is accepted for arguments that
644 /// don't allow a value (-foo) the former is rejected (-foo=).
645 static inline bool ProvideOption(Option *Handler, StringRef ArgName,
646                                  StringRef Value, int argc,
647                                  const char *const *argv, int &i) {
648   // Is this a multi-argument option?
649   unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
650 
651   // Enforce value requirements
652   switch (Handler->getValueExpectedFlag()) {
653   case ValueRequired:
654     if (!Value.data()) { // No value specified?
655       // If no other argument or the option only supports prefix form, we
656       // cannot look at the next argument.
657       if (i + 1 >= argc || Handler->getFormattingFlag() == cl::AlwaysPrefix)
658         return Handler->error("requires a value!");
659       // Steal the next argument, like for '-o filename'
660       assert(argv && "null check");
661       Value = StringRef(argv[++i]);
662     }
663     break;
664   case ValueDisallowed:
665     if (NumAdditionalVals > 0)
666       return Handler->error("multi-valued option specified"
667                             " with ValueDisallowed modifier!");
668 
669     if (Value.data())
670       return Handler->error("does not allow a value! '" + Twine(Value) +
671                             "' specified.");
672     break;
673   case ValueOptional:
674     break;
675   }
676 
677   // If this isn't a multi-arg option, just run the handler.
678   if (NumAdditionalVals == 0)
679     return CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value);
680 
681   // If it is, run the handle several times.
682   bool MultiArg = false;
683 
684   if (Value.data()) {
685     if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
686       return true;
687     --NumAdditionalVals;
688     MultiArg = true;
689   }
690 
691   while (NumAdditionalVals > 0) {
692     if (i + 1 >= argc)
693       return Handler->error("not enough values!");
694     assert(argv && "null check");
695     Value = StringRef(argv[++i]);
696 
697     if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
698       return true;
699     MultiArg = true;
700     --NumAdditionalVals;
701   }
702   return false;
703 }
704 
705 bool llvm::cl::ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
706   int Dummy = i;
707   return ProvideOption(Handler, Handler->ArgStr, Arg, 0, nullptr, Dummy);
708 }
709 
710 // getOptionPred - Check to see if there are any options that satisfy the
711 // specified predicate with names that are the prefixes in Name.  This is
712 // checked by progressively stripping characters off of the name, checking to
713 // see if there options that satisfy the predicate.  If we find one, return it,
714 // otherwise return null.
715 //
716 static Option *getOptionPred(StringRef Name, size_t &Length,
717                              bool (*Pred)(const Option *),
718                              const StringMap<Option *> &OptionsMap) {
719   StringMap<Option *>::const_iterator OMI = OptionsMap.find(Name);
720   if (OMI != OptionsMap.end() && !Pred(OMI->getValue()))
721     OMI = OptionsMap.end();
722 
723   // Loop while we haven't found an option and Name still has at least two
724   // characters in it (so that the next iteration will not be the empty
725   // string.
726   while (OMI == OptionsMap.end() && Name.size() > 1) {
727     Name = Name.substr(0, Name.size() - 1); // Chop off the last character.
728     OMI = OptionsMap.find(Name);
729     if (OMI != OptionsMap.end() && !Pred(OMI->getValue()))
730       OMI = OptionsMap.end();
731   }
732 
733   if (OMI != OptionsMap.end() && Pred(OMI->second)) {
734     Length = Name.size();
735     return OMI->second; // Found one!
736   }
737   return nullptr; // No option found!
738 }
739 
740 /// HandlePrefixedOrGroupedOption - The specified argument string (which started
741 /// with at least one '-') does not fully match an available option.  Check to
742 /// see if this is a prefix or grouped option.  If so, split arg into output an
743 /// Arg/Value pair and return the Option to parse it with.
744 static Option *
745 HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
746                               bool &ErrorParsing,
747                               const StringMap<Option *> &OptionsMap) {
748   if (Arg.size() == 1)
749     return nullptr;
750 
751   // Do the lookup!
752   size_t Length = 0;
753   Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
754   if (!PGOpt)
755     return nullptr;
756 
757   do {
758     StringRef MaybeValue =
759         (Length < Arg.size()) ? Arg.substr(Length) : StringRef();
760     Arg = Arg.substr(0, Length);
761     assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
762 
763     // cl::Prefix options do not preserve '=' when used separately.
764     // The behavior for them with grouped options should be the same.
765     if (MaybeValue.empty() || PGOpt->getFormattingFlag() == cl::AlwaysPrefix ||
766         (PGOpt->getFormattingFlag() == cl::Prefix && MaybeValue[0] != '=')) {
767       Value = MaybeValue;
768       return PGOpt;
769     }
770 
771     if (MaybeValue[0] == '=') {
772       Value = MaybeValue.substr(1);
773       return PGOpt;
774     }
775 
776     // This must be a grouped option.
777     assert(isGrouping(PGOpt) && "Broken getOptionPred!");
778 
779     // Grouping options inside a group can't have values.
780     if (PGOpt->getValueExpectedFlag() == cl::ValueRequired) {
781       ErrorParsing |= PGOpt->error("may not occur within a group!");
782       return nullptr;
783     }
784 
785     // Because the value for the option is not required, we don't need to pass
786     // argc/argv in.
787     int Dummy = 0;
788     ErrorParsing |= ProvideOption(PGOpt, Arg, StringRef(), 0, nullptr, Dummy);
789 
790     // Get the next grouping option.
791     Arg = MaybeValue;
792     PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
793   } while (PGOpt);
794 
795   // We could not find a grouping option in the remainder of Arg.
796   return nullptr;
797 }
798 
799 static bool RequiresValue(const Option *O) {
800   return O->getNumOccurrencesFlag() == cl::Required ||
801          O->getNumOccurrencesFlag() == cl::OneOrMore;
802 }
803 
804 static bool EatsUnboundedNumberOfValues(const Option *O) {
805   return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
806          O->getNumOccurrencesFlag() == cl::OneOrMore;
807 }
808 
809 static bool isWhitespace(char C) {
810   return C == ' ' || C == '\t' || C == '\r' || C == '\n';
811 }
812 
813 static bool isWhitespaceOrNull(char C) {
814   return isWhitespace(C) || C == '\0';
815 }
816 
817 static bool isQuote(char C) { return C == '\"' || C == '\''; }
818 
819 void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
820                                 SmallVectorImpl<const char *> &NewArgv,
821                                 bool MarkEOLs) {
822   SmallString<128> Token;
823   for (size_t I = 0, E = Src.size(); I != E; ++I) {
824     // Consume runs of whitespace.
825     if (Token.empty()) {
826       while (I != E && isWhitespace(Src[I])) {
827         // Mark the end of lines in response files
828         if (MarkEOLs && Src[I] == '\n')
829           NewArgv.push_back(nullptr);
830         ++I;
831       }
832       if (I == E)
833         break;
834     }
835 
836     char C = Src[I];
837 
838     // Backslash escapes the next character.
839     if (I + 1 < E && C == '\\') {
840       ++I; // Skip the escape.
841       Token.push_back(Src[I]);
842       continue;
843     }
844 
845     // Consume a quoted string.
846     if (isQuote(C)) {
847       ++I;
848       while (I != E && Src[I] != C) {
849         // Backslash escapes the next character.
850         if (Src[I] == '\\' && I + 1 != E)
851           ++I;
852         Token.push_back(Src[I]);
853         ++I;
854       }
855       if (I == E)
856         break;
857       continue;
858     }
859 
860     // End the token if this is whitespace.
861     if (isWhitespace(C)) {
862       if (!Token.empty())
863         NewArgv.push_back(Saver.save(StringRef(Token)).data());
864       Token.clear();
865       continue;
866     }
867 
868     // This is a normal character.  Append it.
869     Token.push_back(C);
870   }
871 
872   // Append the last token after hitting EOF with no whitespace.
873   if (!Token.empty())
874     NewArgv.push_back(Saver.save(StringRef(Token)).data());
875   // Mark the end of response files
876   if (MarkEOLs)
877     NewArgv.push_back(nullptr);
878 }
879 
880 /// Backslashes are interpreted in a rather complicated way in the Windows-style
881 /// command line, because backslashes are used both to separate path and to
882 /// escape double quote. This method consumes runs of backslashes as well as the
883 /// following double quote if it's escaped.
884 ///
885 ///  * If an even number of backslashes is followed by a double quote, one
886 ///    backslash is output for every pair of backslashes, and the last double
887 ///    quote remains unconsumed. The double quote will later be interpreted as
888 ///    the start or end of a quoted string in the main loop outside of this
889 ///    function.
890 ///
891 ///  * If an odd number of backslashes is followed by a double quote, one
892 ///    backslash is output for every pair of backslashes, and a double quote is
893 ///    output for the last pair of backslash-double quote. The double quote is
894 ///    consumed in this case.
895 ///
896 ///  * Otherwise, backslashes are interpreted literally.
897 static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
898   size_t E = Src.size();
899   int BackslashCount = 0;
900   // Skip the backslashes.
901   do {
902     ++I;
903     ++BackslashCount;
904   } while (I != E && Src[I] == '\\');
905 
906   bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
907   if (FollowedByDoubleQuote) {
908     Token.append(BackslashCount / 2, '\\');
909     if (BackslashCount % 2 == 0)
910       return I - 1;
911     Token.push_back('"');
912     return I;
913   }
914   Token.append(BackslashCount, '\\');
915   return I - 1;
916 }
917 
918 void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
919                                     SmallVectorImpl<const char *> &NewArgv,
920                                     bool MarkEOLs) {
921   SmallString<128> Token;
922 
923   // This is a small state machine to consume characters until it reaches the
924   // end of the source string.
925   enum { INIT, UNQUOTED, QUOTED } State = INIT;
926   for (size_t I = 0, E = Src.size(); I != E; ++I) {
927     char C = Src[I];
928 
929     // INIT state indicates that the current input index is at the start of
930     // the string or between tokens.
931     if (State == INIT) {
932       if (isWhitespaceOrNull(C)) {
933         // Mark the end of lines in response files
934         if (MarkEOLs && C == '\n')
935           NewArgv.push_back(nullptr);
936         continue;
937       }
938       if (C == '"') {
939         State = QUOTED;
940         continue;
941       }
942       if (C == '\\') {
943         I = parseBackslash(Src, I, Token);
944         State = UNQUOTED;
945         continue;
946       }
947       Token.push_back(C);
948       State = UNQUOTED;
949       continue;
950     }
951 
952     // UNQUOTED state means that it's reading a token not quoted by double
953     // quotes.
954     if (State == UNQUOTED) {
955       // Whitespace means the end of the token.
956       if (isWhitespaceOrNull(C)) {
957         NewArgv.push_back(Saver.save(StringRef(Token)).data());
958         Token.clear();
959         State = INIT;
960         // Mark the end of lines in response files
961         if (MarkEOLs && C == '\n')
962           NewArgv.push_back(nullptr);
963         continue;
964       }
965       if (C == '"') {
966         State = QUOTED;
967         continue;
968       }
969       if (C == '\\') {
970         I = parseBackslash(Src, I, Token);
971         continue;
972       }
973       Token.push_back(C);
974       continue;
975     }
976 
977     // QUOTED state means that it's reading a token quoted by double quotes.
978     if (State == QUOTED) {
979       if (C == '"') {
980         if (I < (E - 1) && Src[I + 1] == '"') {
981           // Consecutive double-quotes inside a quoted string implies one
982           // double-quote.
983           Token.push_back('"');
984           I = I + 1;
985           continue;
986         }
987         State = UNQUOTED;
988         continue;
989       }
990       if (C == '\\') {
991         I = parseBackslash(Src, I, Token);
992         continue;
993       }
994       Token.push_back(C);
995     }
996   }
997   // Append the last token after hitting EOF with no whitespace.
998   if (!Token.empty())
999     NewArgv.push_back(Saver.save(StringRef(Token)).data());
1000   // Mark the end of response files
1001   if (MarkEOLs)
1002     NewArgv.push_back(nullptr);
1003 }
1004 
1005 void cl::tokenizeConfigFile(StringRef Source, StringSaver &Saver,
1006                             SmallVectorImpl<const char *> &NewArgv,
1007                             bool MarkEOLs) {
1008   for (const char *Cur = Source.begin(); Cur != Source.end();) {
1009     SmallString<128> Line;
1010     // Check for comment line.
1011     if (isWhitespace(*Cur)) {
1012       while (Cur != Source.end() && isWhitespace(*Cur))
1013         ++Cur;
1014       continue;
1015     }
1016     if (*Cur == '#') {
1017       while (Cur != Source.end() && *Cur != '\n')
1018         ++Cur;
1019       continue;
1020     }
1021     // Find end of the current line.
1022     const char *Start = Cur;
1023     for (const char *End = Source.end(); Cur != End; ++Cur) {
1024       if (*Cur == '\\') {
1025         if (Cur + 1 != End) {
1026           ++Cur;
1027           if (*Cur == '\n' ||
1028               (*Cur == '\r' && (Cur + 1 != End) && Cur[1] == '\n')) {
1029             Line.append(Start, Cur - 1);
1030             if (*Cur == '\r')
1031               ++Cur;
1032             Start = Cur + 1;
1033           }
1034         }
1035       } else if (*Cur == '\n')
1036         break;
1037     }
1038     // Tokenize line.
1039     Line.append(Start, Cur);
1040     cl::TokenizeGNUCommandLine(Line, Saver, NewArgv, MarkEOLs);
1041   }
1042 }
1043 
1044 // It is called byte order marker but the UTF-8 BOM is actually not affected
1045 // by the host system's endianness.
1046 static bool hasUTF8ByteOrderMark(ArrayRef<char> S) {
1047   return (S.size() >= 3 && S[0] == '\xef' && S[1] == '\xbb' && S[2] == '\xbf');
1048 }
1049 
1050 // FName must be an absolute path.
1051 static llvm::Error ExpandResponseFile(
1052     StringRef FName, StringSaver &Saver, TokenizerCallback Tokenizer,
1053     SmallVectorImpl<const char *> &NewArgv, bool MarkEOLs, bool RelativeNames,
1054     llvm::vfs::FileSystem &FS) {
1055   assert(sys::path::is_absolute(FName));
1056   llvm::ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
1057       FS.getBufferForFile(FName);
1058   if (!MemBufOrErr)
1059     return llvm::errorCodeToError(MemBufOrErr.getError());
1060   MemoryBuffer &MemBuf = *MemBufOrErr.get();
1061   StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize());
1062 
1063   // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
1064   ArrayRef<char> BufRef(MemBuf.getBufferStart(), MemBuf.getBufferEnd());
1065   std::string UTF8Buf;
1066   if (hasUTF16ByteOrderMark(BufRef)) {
1067     if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
1068       return llvm::createStringError(std::errc::illegal_byte_sequence,
1069                                      "Could not convert UTF16 to UTF8");
1070     Str = StringRef(UTF8Buf);
1071   }
1072   // If we see UTF-8 BOM sequence at the beginning of a file, we shall remove
1073   // these bytes before parsing.
1074   // Reference: http://en.wikipedia.org/wiki/UTF-8#Byte_order_mark
1075   else if (hasUTF8ByteOrderMark(BufRef))
1076     Str = StringRef(BufRef.data() + 3, BufRef.size() - 3);
1077 
1078   // Tokenize the contents into NewArgv.
1079   Tokenizer(Str, Saver, NewArgv, MarkEOLs);
1080 
1081   if (!RelativeNames)
1082     return Error::success();
1083   llvm::StringRef BasePath = llvm::sys::path::parent_path(FName);
1084   // If names of nested response files should be resolved relative to including
1085   // file, replace the included response file names with their full paths
1086   // obtained by required resolution.
1087   for (auto &Arg : NewArgv) {
1088     // Skip non-rsp file arguments.
1089     if (!Arg || Arg[0] != '@')
1090       continue;
1091 
1092     StringRef FileName(Arg + 1);
1093     // Skip if non-relative.
1094     if (!llvm::sys::path::is_relative(FileName))
1095       continue;
1096 
1097     SmallString<128> ResponseFile;
1098     ResponseFile.push_back('@');
1099     ResponseFile.append(BasePath);
1100     llvm::sys::path::append(ResponseFile, FileName);
1101     Arg = Saver.save(ResponseFile.c_str()).data();
1102   }
1103   return Error::success();
1104 }
1105 
1106 /// Expand response files on a command line recursively using the given
1107 /// StringSaver and tokenization strategy.
1108 bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
1109                              SmallVectorImpl<const char *> &Argv, bool MarkEOLs,
1110                              bool RelativeNames, llvm::vfs::FileSystem &FS,
1111                              llvm::Optional<llvm::StringRef> CurrentDir) {
1112   bool AllExpanded = true;
1113   struct ResponseFileRecord {
1114     std::string File;
1115     size_t End;
1116   };
1117 
1118   // To detect recursive response files, we maintain a stack of files and the
1119   // position of the last argument in the file. This position is updated
1120   // dynamically as we recursively expand files.
1121   SmallVector<ResponseFileRecord, 3> FileStack;
1122 
1123   // Push a dummy entry that represents the initial command line, removing
1124   // the need to check for an empty list.
1125   FileStack.push_back({"", Argv.size()});
1126 
1127   // Don't cache Argv.size() because it can change.
1128   for (unsigned I = 0; I != Argv.size();) {
1129     while (I == FileStack.back().End) {
1130       // Passing the end of a file's argument list, so we can remove it from the
1131       // stack.
1132       FileStack.pop_back();
1133     }
1134 
1135     const char *Arg = Argv[I];
1136     // Check if it is an EOL marker
1137     if (Arg == nullptr) {
1138       ++I;
1139       continue;
1140     }
1141 
1142     if (Arg[0] != '@') {
1143       ++I;
1144       continue;
1145     }
1146 
1147     const char *FName = Arg + 1;
1148     // Note that CurrentDir is only used for top-level rsp files, the rest will
1149     // always have an absolute path deduced from the containing file.
1150     SmallString<128> CurrDir;
1151     if (llvm::sys::path::is_relative(FName)) {
1152       if (!CurrentDir)
1153         llvm::sys::fs::current_path(CurrDir);
1154       else
1155         CurrDir = *CurrentDir;
1156       llvm::sys::path::append(CurrDir, FName);
1157       FName = CurrDir.c_str();
1158     }
1159     auto IsEquivalent = [FName, &FS](const ResponseFileRecord &RFile) {
1160       llvm::ErrorOr<llvm::vfs::Status> LHS = FS.status(FName);
1161       if (!LHS) {
1162         // TODO: The error should be propagated up the stack.
1163         llvm::consumeError(llvm::errorCodeToError(LHS.getError()));
1164         return false;
1165       }
1166       llvm::ErrorOr<llvm::vfs::Status> RHS = FS.status(RFile.File);
1167       if (!RHS) {
1168         // TODO: The error should be propagated up the stack.
1169         llvm::consumeError(llvm::errorCodeToError(RHS.getError()));
1170         return false;
1171       }
1172       return LHS->equivalent(*RHS);
1173     };
1174 
1175     // Check for recursive response files.
1176     if (std::any_of(FileStack.begin() + 1, FileStack.end(), IsEquivalent)) {
1177       // This file is recursive, so we leave it in the argument stream and
1178       // move on.
1179       AllExpanded = false;
1180       ++I;
1181       continue;
1182     }
1183 
1184     // Replace this response file argument with the tokenization of its
1185     // contents.  Nested response files are expanded in subsequent iterations.
1186     SmallVector<const char *, 0> ExpandedArgv;
1187     if (llvm::Error Err =
1188             ExpandResponseFile(FName, Saver, Tokenizer, ExpandedArgv, MarkEOLs,
1189                                RelativeNames, FS)) {
1190       // We couldn't read this file, so we leave it in the argument stream and
1191       // move on.
1192       // TODO: The error should be propagated up the stack.
1193       llvm::consumeError(std::move(Err));
1194       AllExpanded = false;
1195       ++I;
1196       continue;
1197     }
1198 
1199     for (ResponseFileRecord &Record : FileStack) {
1200       // Increase the end of all active records by the number of newly expanded
1201       // arguments, minus the response file itself.
1202       Record.End += ExpandedArgv.size() - 1;
1203     }
1204 
1205     FileStack.push_back({FName, I + ExpandedArgv.size()});
1206     Argv.erase(Argv.begin() + I);
1207     Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
1208   }
1209 
1210   // If successful, the top of the file stack will mark the end of the Argv
1211   // stream. A failure here indicates a bug in the stack popping logic above.
1212   // Note that FileStack may have more than one element at this point because we
1213   // don't have a chance to pop the stack when encountering recursive files at
1214   // the end of the stream, so seeing that doesn't indicate a bug.
1215   assert(FileStack.size() > 0 && Argv.size() == FileStack.back().End);
1216   return AllExpanded;
1217 }
1218 
1219 bool cl::readConfigFile(StringRef CfgFile, StringSaver &Saver,
1220                         SmallVectorImpl<const char *> &Argv) {
1221   SmallString<128> AbsPath;
1222   if (sys::path::is_relative(CfgFile)) {
1223     llvm::sys::fs::current_path(AbsPath);
1224     llvm::sys::path::append(AbsPath, CfgFile);
1225     CfgFile = AbsPath.str();
1226   }
1227   if (llvm::Error Err =
1228           ExpandResponseFile(CfgFile, Saver, cl::tokenizeConfigFile, Argv,
1229                              /*MarkEOLs*/ false, /*RelativeNames*/ true,
1230                              *llvm::vfs::getRealFileSystem())) {
1231     // TODO: The error should be propagated up the stack.
1232     llvm::consumeError(std::move(Err));
1233     return false;
1234   }
1235   return ExpandResponseFiles(Saver, cl::tokenizeConfigFile, Argv,
1236                              /*MarkEOLs*/ false, /*RelativeNames*/ true);
1237 }
1238 
1239 /// ParseEnvironmentOptions - An alternative entry point to the
1240 /// CommandLine library, which allows you to read the program's name
1241 /// from the caller (as PROGNAME) and its command-line arguments from
1242 /// an environment variable (whose name is given in ENVVAR).
1243 ///
1244 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
1245                                  const char *Overview) {
1246   // Check args.
1247   assert(progName && "Program name not specified");
1248   assert(envVar && "Environment variable name missing");
1249 
1250   // Get the environment variable they want us to parse options out of.
1251   llvm::Optional<std::string> envValue = sys::Process::GetEnv(StringRef(envVar));
1252   if (!envValue)
1253     return;
1254 
1255   // Get program's "name", which we wouldn't know without the caller
1256   // telling us.
1257   SmallVector<const char *, 20> newArgv;
1258   BumpPtrAllocator A;
1259   StringSaver Saver(A);
1260   newArgv.push_back(Saver.save(progName).data());
1261 
1262   // Parse the value of the environment variable into a "command line"
1263   // and hand it off to ParseCommandLineOptions().
1264   TokenizeGNUCommandLine(*envValue, Saver, newArgv);
1265   int newArgc = static_cast<int>(newArgv.size());
1266   ParseCommandLineOptions(newArgc, &newArgv[0], StringRef(Overview));
1267 }
1268 
1269 bool cl::ParseCommandLineOptions(int argc, const char *const *argv,
1270                                  StringRef Overview, raw_ostream *Errs,
1271                                  const char *EnvVar,
1272                                  bool LongOptionsUseDoubleDash) {
1273   SmallVector<const char *, 20> NewArgv;
1274   BumpPtrAllocator A;
1275   StringSaver Saver(A);
1276   NewArgv.push_back(argv[0]);
1277 
1278   // Parse options from environment variable.
1279   if (EnvVar) {
1280     if (llvm::Optional<std::string> EnvValue =
1281             sys::Process::GetEnv(StringRef(EnvVar)))
1282       TokenizeGNUCommandLine(*EnvValue, Saver, NewArgv);
1283   }
1284 
1285   // Append options from command line.
1286   for (int I = 1; I < argc; ++I)
1287     NewArgv.push_back(argv[I]);
1288   int NewArgc = static_cast<int>(NewArgv.size());
1289 
1290   // Parse all options.
1291   return GlobalParser->ParseCommandLineOptions(NewArgc, &NewArgv[0], Overview,
1292                                                Errs, LongOptionsUseDoubleDash);
1293 }
1294 
1295 void CommandLineParser::ResetAllOptionOccurrences() {
1296   // So that we can parse different command lines multiple times in succession
1297   // we reset all option values to look like they have never been seen before.
1298   for (auto SC : RegisteredSubCommands) {
1299     for (auto &O : SC->OptionsMap)
1300       O.second->reset();
1301   }
1302 }
1303 
1304 bool CommandLineParser::ParseCommandLineOptions(int argc,
1305                                                 const char *const *argv,
1306                                                 StringRef Overview,
1307                                                 raw_ostream *Errs,
1308                                                 bool LongOptionsUseDoubleDash) {
1309   assert(hasOptions() && "No options specified!");
1310 
1311   // Expand response files.
1312   SmallVector<const char *, 20> newArgv(argv, argv + argc);
1313   BumpPtrAllocator A;
1314   StringSaver Saver(A);
1315   ExpandResponseFiles(Saver,
1316          Triple(sys::getProcessTriple()).isOSWindows() ?
1317          cl::TokenizeWindowsCommandLine : cl::TokenizeGNUCommandLine,
1318          newArgv);
1319   argv = &newArgv[0];
1320   argc = static_cast<int>(newArgv.size());
1321 
1322   // Copy the program name into ProgName, making sure not to overflow it.
1323   ProgramName = sys::path::filename(StringRef(argv[0]));
1324 
1325   ProgramOverview = Overview;
1326   bool IgnoreErrors = Errs;
1327   if (!Errs)
1328     Errs = &errs();
1329   bool ErrorParsing = false;
1330 
1331   // Check out the positional arguments to collect information about them.
1332   unsigned NumPositionalRequired = 0;
1333 
1334   // Determine whether or not there are an unlimited number of positionals
1335   bool HasUnlimitedPositionals = false;
1336 
1337   int FirstArg = 1;
1338   SubCommand *ChosenSubCommand = &*TopLevelSubCommand;
1339   if (argc >= 2 && argv[FirstArg][0] != '-') {
1340     // If the first argument specifies a valid subcommand, start processing
1341     // options from the second argument.
1342     ChosenSubCommand = LookupSubCommand(StringRef(argv[FirstArg]));
1343     if (ChosenSubCommand != &*TopLevelSubCommand)
1344       FirstArg = 2;
1345   }
1346   GlobalParser->ActiveSubCommand = ChosenSubCommand;
1347 
1348   assert(ChosenSubCommand);
1349   auto &ConsumeAfterOpt = ChosenSubCommand->ConsumeAfterOpt;
1350   auto &PositionalOpts = ChosenSubCommand->PositionalOpts;
1351   auto &SinkOpts = ChosenSubCommand->SinkOpts;
1352   auto &OptionsMap = ChosenSubCommand->OptionsMap;
1353 
1354   for (auto O: DefaultOptions) {
1355     addOption(O, true);
1356   }
1357 
1358   if (ConsumeAfterOpt) {
1359     assert(PositionalOpts.size() > 0 &&
1360            "Cannot specify cl::ConsumeAfter without a positional argument!");
1361   }
1362   if (!PositionalOpts.empty()) {
1363 
1364     // Calculate how many positional values are _required_.
1365     bool UnboundedFound = false;
1366     for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
1367       Option *Opt = PositionalOpts[i];
1368       if (RequiresValue(Opt))
1369         ++NumPositionalRequired;
1370       else if (ConsumeAfterOpt) {
1371         // ConsumeAfter cannot be combined with "optional" positional options
1372         // unless there is only one positional argument...
1373         if (PositionalOpts.size() > 1) {
1374           if (!IgnoreErrors)
1375             Opt->error("error - this positional option will never be matched, "
1376                        "because it does not Require a value, and a "
1377                        "cl::ConsumeAfter option is active!");
1378           ErrorParsing = true;
1379         }
1380       } else if (UnboundedFound && !Opt->hasArgStr()) {
1381         // This option does not "require" a value...  Make sure this option is
1382         // not specified after an option that eats all extra arguments, or this
1383         // one will never get any!
1384         //
1385         if (!IgnoreErrors)
1386           Opt->error("error - option can never match, because "
1387                      "another positional argument will match an "
1388                      "unbounded number of values, and this option"
1389                      " does not require a value!");
1390         *Errs << ProgramName << ": CommandLine Error: Option '" << Opt->ArgStr
1391               << "' is all messed up!\n";
1392         *Errs << PositionalOpts.size();
1393         ErrorParsing = true;
1394       }
1395       UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
1396     }
1397     HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
1398   }
1399 
1400   // PositionalVals - A vector of "positional" arguments we accumulate into
1401   // the process at the end.
1402   //
1403   SmallVector<std::pair<StringRef, unsigned>, 4> PositionalVals;
1404 
1405   // If the program has named positional arguments, and the name has been run
1406   // across, keep track of which positional argument was named.  Otherwise put
1407   // the positional args into the PositionalVals list...
1408   Option *ActivePositionalArg = nullptr;
1409 
1410   // Loop over all of the arguments... processing them.
1411   bool DashDashFound = false; // Have we read '--'?
1412   for (int i = FirstArg; i < argc; ++i) {
1413     Option *Handler = nullptr;
1414     Option *NearestHandler = nullptr;
1415     std::string NearestHandlerString;
1416     StringRef Value;
1417     StringRef ArgName = "";
1418     bool HaveDoubleDash = false;
1419 
1420     // Check to see if this is a positional argument.  This argument is
1421     // considered to be positional if it doesn't start with '-', if it is "-"
1422     // itself, or if we have seen "--" already.
1423     //
1424     if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
1425       // Positional argument!
1426       if (ActivePositionalArg) {
1427         ProvidePositionalOption(ActivePositionalArg, StringRef(argv[i]), i);
1428         continue; // We are done!
1429       }
1430 
1431       if (!PositionalOpts.empty()) {
1432         PositionalVals.push_back(std::make_pair(StringRef(argv[i]), i));
1433 
1434         // All of the positional arguments have been fulfulled, give the rest to
1435         // the consume after option... if it's specified...
1436         //
1437         if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) {
1438           for (++i; i < argc; ++i)
1439             PositionalVals.push_back(std::make_pair(StringRef(argv[i]), i));
1440           break; // Handle outside of the argument processing loop...
1441         }
1442 
1443         // Delay processing positional arguments until the end...
1444         continue;
1445       }
1446     } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
1447                !DashDashFound) {
1448       DashDashFound = true; // This is the mythical "--"?
1449       continue;             // Don't try to process it as an argument itself.
1450     } else if (ActivePositionalArg &&
1451                (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
1452       // If there is a positional argument eating options, check to see if this
1453       // option is another positional argument.  If so, treat it as an argument,
1454       // otherwise feed it to the eating positional.
1455       ArgName = StringRef(argv[i] + 1);
1456       // Eat second dash.
1457       if (!ArgName.empty() && ArgName[0] == '-') {
1458         HaveDoubleDash = true;
1459         ArgName = ArgName.substr(1);
1460       }
1461 
1462       Handler = LookupLongOption(*ChosenSubCommand, ArgName, Value,
1463                                  LongOptionsUseDoubleDash, HaveDoubleDash);
1464       if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
1465         ProvidePositionalOption(ActivePositionalArg, StringRef(argv[i]), i);
1466         continue; // We are done!
1467       }
1468     } else { // We start with a '-', must be an argument.
1469       ArgName = StringRef(argv[i] + 1);
1470       // Eat second dash.
1471       if (!ArgName.empty() && ArgName[0] == '-') {
1472         HaveDoubleDash = true;
1473         ArgName = ArgName.substr(1);
1474       }
1475 
1476       Handler = LookupLongOption(*ChosenSubCommand, ArgName, Value,
1477                                  LongOptionsUseDoubleDash, HaveDoubleDash);
1478 
1479       // Check to see if this "option" is really a prefixed or grouped argument.
1480       if (!Handler && !(LongOptionsUseDoubleDash && HaveDoubleDash))
1481         Handler = HandlePrefixedOrGroupedOption(ArgName, Value, ErrorParsing,
1482                                                 OptionsMap);
1483 
1484       // Otherwise, look for the closest available option to report to the user
1485       // in the upcoming error.
1486       if (!Handler && SinkOpts.empty())
1487         NearestHandler =
1488             LookupNearestOption(ArgName, OptionsMap, NearestHandlerString);
1489     }
1490 
1491     if (!Handler) {
1492       if (SinkOpts.empty()) {
1493         *Errs << ProgramName << ": Unknown command line argument '" << argv[i]
1494               << "'.  Try: '" << argv[0] << " --help'\n";
1495 
1496         if (NearestHandler) {
1497           // If we know a near match, report it as well.
1498           *Errs << ProgramName << ": Did you mean '"
1499                 << PrintArg(NearestHandlerString, 0) << "'?\n";
1500         }
1501 
1502         ErrorParsing = true;
1503       } else {
1504         for (SmallVectorImpl<Option *>::iterator I = SinkOpts.begin(),
1505                                                  E = SinkOpts.end();
1506              I != E; ++I)
1507           (*I)->addOccurrence(i, "", StringRef(argv[i]));
1508       }
1509       continue;
1510     }
1511 
1512     // If this is a named positional argument, just remember that it is the
1513     // active one...
1514     if (Handler->getFormattingFlag() == cl::Positional) {
1515       if ((Handler->getMiscFlags() & PositionalEatsArgs) && !Value.empty()) {
1516         Handler->error("This argument does not take a value.\n"
1517                        "\tInstead, it consumes any positional arguments until "
1518                        "the next recognized option.", *Errs);
1519         ErrorParsing = true;
1520       }
1521       ActivePositionalArg = Handler;
1522     }
1523     else
1524       ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
1525   }
1526 
1527   // Check and handle positional arguments now...
1528   if (NumPositionalRequired > PositionalVals.size()) {
1529       *Errs << ProgramName
1530              << ": Not enough positional command line arguments specified!\n"
1531              << "Must specify at least " << NumPositionalRequired
1532              << " positional argument" << (NumPositionalRequired > 1 ? "s" : "")
1533              << ": See: " << argv[0] << " --help\n";
1534 
1535     ErrorParsing = true;
1536   } else if (!HasUnlimitedPositionals &&
1537              PositionalVals.size() > PositionalOpts.size()) {
1538     *Errs << ProgramName << ": Too many positional arguments specified!\n"
1539           << "Can specify at most " << PositionalOpts.size()
1540           << " positional arguments: See: " << argv[0] << " --help\n";
1541     ErrorParsing = true;
1542 
1543   } else if (!ConsumeAfterOpt) {
1544     // Positional args have already been handled if ConsumeAfter is specified.
1545     unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
1546     for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
1547       if (RequiresValue(PositionalOpts[i])) {
1548         ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
1549                                 PositionalVals[ValNo].second);
1550         ValNo++;
1551         --NumPositionalRequired; // We fulfilled our duty...
1552       }
1553 
1554       // If we _can_ give this option more arguments, do so now, as long as we
1555       // do not give it values that others need.  'Done' controls whether the
1556       // option even _WANTS_ any more.
1557       //
1558       bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
1559       while (NumVals - ValNo > NumPositionalRequired && !Done) {
1560         switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
1561         case cl::Optional:
1562           Done = true; // Optional arguments want _at most_ one value
1563           LLVM_FALLTHROUGH;
1564         case cl::ZeroOrMore: // Zero or more will take all they can get...
1565         case cl::OneOrMore:  // One or more will take all they can get...
1566           ProvidePositionalOption(PositionalOpts[i],
1567                                   PositionalVals[ValNo].first,
1568                                   PositionalVals[ValNo].second);
1569           ValNo++;
1570           break;
1571         default:
1572           llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
1573                            "positional argument processing!");
1574         }
1575       }
1576     }
1577   } else {
1578     assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
1579     unsigned ValNo = 0;
1580     for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
1581       if (RequiresValue(PositionalOpts[j])) {
1582         ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
1583                                                 PositionalVals[ValNo].first,
1584                                                 PositionalVals[ValNo].second);
1585         ValNo++;
1586       }
1587 
1588     // Handle the case where there is just one positional option, and it's
1589     // optional.  In this case, we want to give JUST THE FIRST option to the
1590     // positional option and keep the rest for the consume after.  The above
1591     // loop would have assigned no values to positional options in this case.
1592     //
1593     if (PositionalOpts.size() == 1 && ValNo == 0 && !PositionalVals.empty()) {
1594       ErrorParsing |= ProvidePositionalOption(PositionalOpts[0],
1595                                               PositionalVals[ValNo].first,
1596                                               PositionalVals[ValNo].second);
1597       ValNo++;
1598     }
1599 
1600     // Handle over all of the rest of the arguments to the
1601     // cl::ConsumeAfter command line option...
1602     for (; ValNo != PositionalVals.size(); ++ValNo)
1603       ErrorParsing |=
1604           ProvidePositionalOption(ConsumeAfterOpt, PositionalVals[ValNo].first,
1605                                   PositionalVals[ValNo].second);
1606   }
1607 
1608   // Loop over args and make sure all required args are specified!
1609   for (const auto &Opt : OptionsMap) {
1610     switch (Opt.second->getNumOccurrencesFlag()) {
1611     case Required:
1612     case OneOrMore:
1613       if (Opt.second->getNumOccurrences() == 0) {
1614         Opt.second->error("must be specified at least once!");
1615         ErrorParsing = true;
1616       }
1617       LLVM_FALLTHROUGH;
1618     default:
1619       break;
1620     }
1621   }
1622 
1623   // Now that we know if -debug is specified, we can use it.
1624   // Note that if ReadResponseFiles == true, this must be done before the
1625   // memory allocated for the expanded command line is free()d below.
1626   LLVM_DEBUG(dbgs() << "Args: ";
1627              for (int i = 0; i < argc; ++i) dbgs() << argv[i] << ' ';
1628              dbgs() << '\n';);
1629 
1630   // Free all of the memory allocated to the map.  Command line options may only
1631   // be processed once!
1632   MoreHelp.clear();
1633 
1634   // If we had an error processing our arguments, don't let the program execute
1635   if (ErrorParsing) {
1636     if (!IgnoreErrors)
1637       exit(1);
1638     return false;
1639   }
1640   return true;
1641 }
1642 
1643 //===----------------------------------------------------------------------===//
1644 // Option Base class implementation
1645 //
1646 
1647 bool Option::error(const Twine &Message, StringRef ArgName, raw_ostream &Errs) {
1648   if (!ArgName.data())
1649     ArgName = ArgStr;
1650   if (ArgName.empty())
1651     Errs << HelpStr; // Be nice for positional arguments
1652   else
1653     Errs << GlobalParser->ProgramName << ": for the " << PrintArg(ArgName, 0);
1654 
1655   Errs << " option: " << Message << "\n";
1656   return true;
1657 }
1658 
1659 bool Option::addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
1660                            bool MultiArg) {
1661   if (!MultiArg)
1662     NumOccurrences++; // Increment the number of times we have been seen
1663 
1664   switch (getNumOccurrencesFlag()) {
1665   case Optional:
1666     if (NumOccurrences > 1)
1667       return error("may only occur zero or one times!", ArgName);
1668     break;
1669   case Required:
1670     if (NumOccurrences > 1)
1671       return error("must occur exactly one time!", ArgName);
1672     LLVM_FALLTHROUGH;
1673   case OneOrMore:
1674   case ZeroOrMore:
1675   case ConsumeAfter:
1676     break;
1677   }
1678 
1679   return handleOccurrence(pos, ArgName, Value);
1680 }
1681 
1682 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
1683 // has been specified yet.
1684 //
1685 static StringRef getValueStr(const Option &O, StringRef DefaultMsg) {
1686   if (O.ValueStr.empty())
1687     return DefaultMsg;
1688   return O.ValueStr;
1689 }
1690 
1691 //===----------------------------------------------------------------------===//
1692 // cl::alias class implementation
1693 //
1694 
1695 // Return the width of the option tag for printing...
1696 size_t alias::getOptionWidth() const {
1697   return argPlusPrefixesSize(ArgStr);
1698 }
1699 
1700 void Option::printHelpStr(StringRef HelpStr, size_t Indent,
1701                           size_t FirstLineIndentedBy) {
1702   assert(Indent >= FirstLineIndentedBy);
1703   std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1704   outs().indent(Indent - FirstLineIndentedBy)
1705       << ArgHelpPrefix << Split.first << "\n";
1706   while (!Split.second.empty()) {
1707     Split = Split.second.split('\n');
1708     outs().indent(Indent) << Split.first << "\n";
1709   }
1710 }
1711 
1712 // Print out the option for the alias.
1713 void alias::printOptionInfo(size_t GlobalWidth) const {
1714   outs() << PrintArg(ArgStr);
1715   printHelpStr(HelpStr, GlobalWidth, argPlusPrefixesSize(ArgStr));
1716 }
1717 
1718 //===----------------------------------------------------------------------===//
1719 // Parser Implementation code...
1720 //
1721 
1722 // basic_parser implementation
1723 //
1724 
1725 // Return the width of the option tag for printing...
1726 size_t basic_parser_impl::getOptionWidth(const Option &O) const {
1727   size_t Len = argPlusPrefixesSize(O.ArgStr);
1728   auto ValName = getValueName();
1729   if (!ValName.empty()) {
1730     size_t FormattingLen = 3;
1731     if (O.getMiscFlags() & PositionalEatsArgs)
1732       FormattingLen = 6;
1733     Len += getValueStr(O, ValName).size() + FormattingLen;
1734   }
1735 
1736   return Len;
1737 }
1738 
1739 // printOptionInfo - Print out information about this option.  The
1740 // to-be-maintained width is specified.
1741 //
1742 void basic_parser_impl::printOptionInfo(const Option &O,
1743                                         size_t GlobalWidth) const {
1744   outs() << PrintArg(O.ArgStr);
1745 
1746   auto ValName = getValueName();
1747   if (!ValName.empty()) {
1748     if (O.getMiscFlags() & PositionalEatsArgs) {
1749       outs() << " <" << getValueStr(O, ValName) << ">...";
1750     } else {
1751       outs() << "=<" << getValueStr(O, ValName) << '>';
1752     }
1753   }
1754 
1755   Option::printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
1756 }
1757 
1758 void basic_parser_impl::printOptionName(const Option &O,
1759                                         size_t GlobalWidth) const {
1760   outs() << PrintArg(O.ArgStr);
1761   outs().indent(GlobalWidth - O.ArgStr.size());
1762 }
1763 
1764 // parser<bool> implementation
1765 //
1766 bool parser<bool>::parse(Option &O, StringRef ArgName, StringRef Arg,
1767                          bool &Value) {
1768   if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1769       Arg == "1") {
1770     Value = true;
1771     return false;
1772   }
1773 
1774   if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1775     Value = false;
1776     return false;
1777   }
1778   return O.error("'" + Arg +
1779                  "' is invalid value for boolean argument! Try 0 or 1");
1780 }
1781 
1782 // parser<boolOrDefault> implementation
1783 //
1784 bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName, StringRef Arg,
1785                                   boolOrDefault &Value) {
1786   if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1787       Arg == "1") {
1788     Value = BOU_TRUE;
1789     return false;
1790   }
1791   if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1792     Value = BOU_FALSE;
1793     return false;
1794   }
1795 
1796   return O.error("'" + Arg +
1797                  "' is invalid value for boolean argument! Try 0 or 1");
1798 }
1799 
1800 // parser<int> implementation
1801 //
1802 bool parser<int>::parse(Option &O, StringRef ArgName, StringRef Arg,
1803                         int &Value) {
1804   if (Arg.getAsInteger(0, Value))
1805     return O.error("'" + Arg + "' value invalid for integer argument!");
1806   return false;
1807 }
1808 
1809 // parser<unsigned> implementation
1810 //
1811 bool parser<unsigned>::parse(Option &O, StringRef ArgName, StringRef Arg,
1812                              unsigned &Value) {
1813 
1814   if (Arg.getAsInteger(0, Value))
1815     return O.error("'" + Arg + "' value invalid for uint argument!");
1816   return false;
1817 }
1818 
1819 // parser<unsigned long> implementation
1820 //
1821 bool parser<unsigned long>::parse(Option &O, StringRef ArgName, StringRef Arg,
1822                                   unsigned long &Value) {
1823 
1824   if (Arg.getAsInteger(0, Value))
1825     return O.error("'" + Arg + "' value invalid for ulong argument!");
1826   return false;
1827 }
1828 
1829 // parser<unsigned long long> implementation
1830 //
1831 bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
1832                                        StringRef Arg,
1833                                        unsigned long long &Value) {
1834 
1835   if (Arg.getAsInteger(0, Value))
1836     return O.error("'" + Arg + "' value invalid for ullong argument!");
1837   return false;
1838 }
1839 
1840 // parser<double>/parser<float> implementation
1841 //
1842 static bool parseDouble(Option &O, StringRef Arg, double &Value) {
1843   if (to_float(Arg, Value))
1844     return false;
1845   return O.error("'" + Arg + "' value invalid for floating point argument!");
1846 }
1847 
1848 bool parser<double>::parse(Option &O, StringRef ArgName, StringRef Arg,
1849                            double &Val) {
1850   return parseDouble(O, Arg, Val);
1851 }
1852 
1853 bool parser<float>::parse(Option &O, StringRef ArgName, StringRef Arg,
1854                           float &Val) {
1855   double dVal;
1856   if (parseDouble(O, Arg, dVal))
1857     return true;
1858   Val = (float)dVal;
1859   return false;
1860 }
1861 
1862 // generic_parser_base implementation
1863 //
1864 
1865 // findOption - Return the option number corresponding to the specified
1866 // argument string.  If the option is not found, getNumOptions() is returned.
1867 //
1868 unsigned generic_parser_base::findOption(StringRef Name) {
1869   unsigned e = getNumOptions();
1870 
1871   for (unsigned i = 0; i != e; ++i) {
1872     if (getOption(i) == Name)
1873       return i;
1874   }
1875   return e;
1876 }
1877 
1878 static StringRef EqValue = "=<value>";
1879 static StringRef EmptyOption = "<empty>";
1880 static StringRef OptionPrefix = "    =";
1881 static size_t OptionPrefixesSize = OptionPrefix.size() + ArgHelpPrefix.size();
1882 
1883 static bool shouldPrintOption(StringRef Name, StringRef Description,
1884                               const Option &O) {
1885   return O.getValueExpectedFlag() != ValueOptional || !Name.empty() ||
1886          !Description.empty();
1887 }
1888 
1889 // Return the width of the option tag for printing...
1890 size_t generic_parser_base::getOptionWidth(const Option &O) const {
1891   if (O.hasArgStr()) {
1892     size_t Size =
1893         argPlusPrefixesSize(O.ArgStr) + EqValue.size();
1894     for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1895       StringRef Name = getOption(i);
1896       if (!shouldPrintOption(Name, getDescription(i), O))
1897         continue;
1898       size_t NameSize = Name.empty() ? EmptyOption.size() : Name.size();
1899       Size = std::max(Size, NameSize + OptionPrefixesSize);
1900     }
1901     return Size;
1902   } else {
1903     size_t BaseSize = 0;
1904     for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1905       BaseSize = std::max(BaseSize, getOption(i).size() + 8);
1906     return BaseSize;
1907   }
1908 }
1909 
1910 // printOptionInfo - Print out information about this option.  The
1911 // to-be-maintained width is specified.
1912 //
1913 void generic_parser_base::printOptionInfo(const Option &O,
1914                                           size_t GlobalWidth) const {
1915   if (O.hasArgStr()) {
1916     // When the value is optional, first print a line just describing the
1917     // option without values.
1918     if (O.getValueExpectedFlag() == ValueOptional) {
1919       for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1920         if (getOption(i).empty()) {
1921           outs() << PrintArg(O.ArgStr);
1922           Option::printHelpStr(O.HelpStr, GlobalWidth,
1923                                argPlusPrefixesSize(O.ArgStr));
1924           break;
1925         }
1926       }
1927     }
1928 
1929     outs() << PrintArg(O.ArgStr) << EqValue;
1930     Option::printHelpStr(O.HelpStr, GlobalWidth,
1931                          EqValue.size() +
1932                              argPlusPrefixesSize(O.ArgStr));
1933     for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1934       StringRef OptionName = getOption(i);
1935       StringRef Description = getDescription(i);
1936       if (!shouldPrintOption(OptionName, Description, O))
1937         continue;
1938       assert(GlobalWidth >= OptionName.size() + OptionPrefixesSize);
1939       size_t NumSpaces = GlobalWidth - OptionName.size() - OptionPrefixesSize;
1940       outs() << OptionPrefix << OptionName;
1941       if (OptionName.empty()) {
1942         outs() << EmptyOption;
1943         assert(NumSpaces >= EmptyOption.size());
1944         NumSpaces -= EmptyOption.size();
1945       }
1946       if (!Description.empty())
1947         outs().indent(NumSpaces) << ArgHelpPrefix << "  " << Description;
1948       outs() << '\n';
1949     }
1950   } else {
1951     if (!O.HelpStr.empty())
1952       outs() << "  " << O.HelpStr << '\n';
1953     for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1954       StringRef Option = getOption(i);
1955       outs() << "    " << PrintArg(Option);
1956       Option::printHelpStr(getDescription(i), GlobalWidth, Option.size() + 8);
1957     }
1958   }
1959 }
1960 
1961 static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1962 
1963 // printGenericOptionDiff - Print the value of this option and it's default.
1964 //
1965 // "Generic" options have each value mapped to a name.
1966 void generic_parser_base::printGenericOptionDiff(
1967     const Option &O, const GenericOptionValue &Value,
1968     const GenericOptionValue &Default, size_t GlobalWidth) const {
1969   outs() << "  " << PrintArg(O.ArgStr);
1970   outs().indent(GlobalWidth - O.ArgStr.size());
1971 
1972   unsigned NumOpts = getNumOptions();
1973   for (unsigned i = 0; i != NumOpts; ++i) {
1974     if (Value.compare(getOptionValue(i)))
1975       continue;
1976 
1977     outs() << "= " << getOption(i);
1978     size_t L = getOption(i).size();
1979     size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1980     outs().indent(NumSpaces) << " (default: ";
1981     for (unsigned j = 0; j != NumOpts; ++j) {
1982       if (Default.compare(getOptionValue(j)))
1983         continue;
1984       outs() << getOption(j);
1985       break;
1986     }
1987     outs() << ")\n";
1988     return;
1989   }
1990   outs() << "= *unknown option value*\n";
1991 }
1992 
1993 // printOptionDiff - Specializations for printing basic value types.
1994 //
1995 #define PRINT_OPT_DIFF(T)                                                      \
1996   void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D,      \
1997                                   size_t GlobalWidth) const {                  \
1998     printOptionName(O, GlobalWidth);                                           \
1999     std::string Str;                                                           \
2000     {                                                                          \
2001       raw_string_ostream SS(Str);                                              \
2002       SS << V;                                                                 \
2003     }                                                                          \
2004     outs() << "= " << Str;                                                     \
2005     size_t NumSpaces =                                                         \
2006         MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0;               \
2007     outs().indent(NumSpaces) << " (default: ";                                 \
2008     if (D.hasValue())                                                          \
2009       outs() << D.getValue();                                                  \
2010     else                                                                       \
2011       outs() << "*no default*";                                                \
2012     outs() << ")\n";                                                           \
2013   }
2014 
2015 PRINT_OPT_DIFF(bool)
2016 PRINT_OPT_DIFF(boolOrDefault)
2017 PRINT_OPT_DIFF(int)
2018 PRINT_OPT_DIFF(unsigned)
2019 PRINT_OPT_DIFF(unsigned long)
2020 PRINT_OPT_DIFF(unsigned long long)
2021 PRINT_OPT_DIFF(double)
2022 PRINT_OPT_DIFF(float)
2023 PRINT_OPT_DIFF(char)
2024 
2025 void parser<std::string>::printOptionDiff(const Option &O, StringRef V,
2026                                           const OptionValue<std::string> &D,
2027                                           size_t GlobalWidth) const {
2028   printOptionName(O, GlobalWidth);
2029   outs() << "= " << V;
2030   size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
2031   outs().indent(NumSpaces) << " (default: ";
2032   if (D.hasValue())
2033     outs() << D.getValue();
2034   else
2035     outs() << "*no default*";
2036   outs() << ")\n";
2037 }
2038 
2039 // Print a placeholder for options that don't yet support printOptionDiff().
2040 void basic_parser_impl::printOptionNoValue(const Option &O,
2041                                            size_t GlobalWidth) const {
2042   printOptionName(O, GlobalWidth);
2043   outs() << "= *cannot print option value*\n";
2044 }
2045 
2046 //===----------------------------------------------------------------------===//
2047 // -help and -help-hidden option implementation
2048 //
2049 
2050 static int OptNameCompare(const std::pair<const char *, Option *> *LHS,
2051                           const std::pair<const char *, Option *> *RHS) {
2052   return strcmp(LHS->first, RHS->first);
2053 }
2054 
2055 static int SubNameCompare(const std::pair<const char *, SubCommand *> *LHS,
2056                           const std::pair<const char *, SubCommand *> *RHS) {
2057   return strcmp(LHS->first, RHS->first);
2058 }
2059 
2060 // Copy Options into a vector so we can sort them as we like.
2061 static void sortOpts(StringMap<Option *> &OptMap,
2062                      SmallVectorImpl<std::pair<const char *, Option *>> &Opts,
2063                      bool ShowHidden) {
2064   SmallPtrSet<Option *, 32> OptionSet; // Duplicate option detection.
2065 
2066   for (StringMap<Option *>::iterator I = OptMap.begin(), E = OptMap.end();
2067        I != E; ++I) {
2068     // Ignore really-hidden options.
2069     if (I->second->getOptionHiddenFlag() == ReallyHidden)
2070       continue;
2071 
2072     // Unless showhidden is set, ignore hidden flags.
2073     if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
2074       continue;
2075 
2076     // If we've already seen this option, don't add it to the list again.
2077     if (!OptionSet.insert(I->second).second)
2078       continue;
2079 
2080     Opts.push_back(
2081         std::pair<const char *, Option *>(I->getKey().data(), I->second));
2082   }
2083 
2084   // Sort the options list alphabetically.
2085   array_pod_sort(Opts.begin(), Opts.end(), OptNameCompare);
2086 }
2087 
2088 static void
2089 sortSubCommands(const SmallPtrSetImpl<SubCommand *> &SubMap,
2090                 SmallVectorImpl<std::pair<const char *, SubCommand *>> &Subs) {
2091   for (const auto &S : SubMap) {
2092     if (S->getName().empty())
2093       continue;
2094     Subs.push_back(std::make_pair(S->getName().data(), S));
2095   }
2096   array_pod_sort(Subs.begin(), Subs.end(), SubNameCompare);
2097 }
2098 
2099 namespace {
2100 
2101 class HelpPrinter {
2102 protected:
2103   const bool ShowHidden;
2104   typedef SmallVector<std::pair<const char *, Option *>, 128>
2105       StrOptionPairVector;
2106   typedef SmallVector<std::pair<const char *, SubCommand *>, 128>
2107       StrSubCommandPairVector;
2108   // Print the options. Opts is assumed to be alphabetically sorted.
2109   virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
2110     for (size_t i = 0, e = Opts.size(); i != e; ++i)
2111       Opts[i].second->printOptionInfo(MaxArgLen);
2112   }
2113 
2114   void printSubCommands(StrSubCommandPairVector &Subs, size_t MaxSubLen) {
2115     for (const auto &S : Subs) {
2116       outs() << "  " << S.first;
2117       if (!S.second->getDescription().empty()) {
2118         outs().indent(MaxSubLen - strlen(S.first));
2119         outs() << " - " << S.second->getDescription();
2120       }
2121       outs() << "\n";
2122     }
2123   }
2124 
2125 public:
2126   explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
2127   virtual ~HelpPrinter() {}
2128 
2129   // Invoke the printer.
2130   void operator=(bool Value) {
2131     if (!Value)
2132       return;
2133     printHelp();
2134 
2135     // Halt the program since help information was printed
2136     exit(0);
2137   }
2138 
2139   void printHelp() {
2140     SubCommand *Sub = GlobalParser->getActiveSubCommand();
2141     auto &OptionsMap = Sub->OptionsMap;
2142     auto &PositionalOpts = Sub->PositionalOpts;
2143     auto &ConsumeAfterOpt = Sub->ConsumeAfterOpt;
2144 
2145     StrOptionPairVector Opts;
2146     sortOpts(OptionsMap, Opts, ShowHidden);
2147 
2148     StrSubCommandPairVector Subs;
2149     sortSubCommands(GlobalParser->RegisteredSubCommands, Subs);
2150 
2151     if (!GlobalParser->ProgramOverview.empty())
2152       outs() << "OVERVIEW: " << GlobalParser->ProgramOverview << "\n";
2153 
2154     if (Sub == &*TopLevelSubCommand) {
2155       outs() << "USAGE: " << GlobalParser->ProgramName;
2156       if (Subs.size() > 2)
2157         outs() << " [subcommand]";
2158       outs() << " [options]";
2159     } else {
2160       if (!Sub->getDescription().empty()) {
2161         outs() << "SUBCOMMAND '" << Sub->getName()
2162                << "': " << Sub->getDescription() << "\n\n";
2163       }
2164       outs() << "USAGE: " << GlobalParser->ProgramName << " " << Sub->getName()
2165              << " [options]";
2166     }
2167 
2168     for (auto Opt : PositionalOpts) {
2169       if (Opt->hasArgStr())
2170         outs() << " --" << Opt->ArgStr;
2171       outs() << " " << Opt->HelpStr;
2172     }
2173 
2174     // Print the consume after option info if it exists...
2175     if (ConsumeAfterOpt)
2176       outs() << " " << ConsumeAfterOpt->HelpStr;
2177 
2178     if (Sub == &*TopLevelSubCommand && !Subs.empty()) {
2179       // Compute the maximum subcommand length...
2180       size_t MaxSubLen = 0;
2181       for (size_t i = 0, e = Subs.size(); i != e; ++i)
2182         MaxSubLen = std::max(MaxSubLen, strlen(Subs[i].first));
2183 
2184       outs() << "\n\n";
2185       outs() << "SUBCOMMANDS:\n\n";
2186       printSubCommands(Subs, MaxSubLen);
2187       outs() << "\n";
2188       outs() << "  Type \"" << GlobalParser->ProgramName
2189              << " <subcommand> --help\" to get more help on a specific "
2190                 "subcommand";
2191     }
2192 
2193     outs() << "\n\n";
2194 
2195     // Compute the maximum argument length...
2196     size_t MaxArgLen = 0;
2197     for (size_t i = 0, e = Opts.size(); i != e; ++i)
2198       MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
2199 
2200     outs() << "OPTIONS:\n";
2201     printOptions(Opts, MaxArgLen);
2202 
2203     // Print any extra help the user has declared.
2204     for (auto I : GlobalParser->MoreHelp)
2205       outs() << I;
2206     GlobalParser->MoreHelp.clear();
2207   }
2208 };
2209 
2210 class CategorizedHelpPrinter : public HelpPrinter {
2211 public:
2212   explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
2213 
2214   // Helper function for printOptions().
2215   // It shall return a negative value if A's name should be lexicographically
2216   // ordered before B's name. It returns a value greater than zero if B's name
2217   // should be ordered before A's name, and it returns 0 otherwise.
2218   static int OptionCategoryCompare(OptionCategory *const *A,
2219                                    OptionCategory *const *B) {
2220     return (*A)->getName().compare((*B)->getName());
2221   }
2222 
2223   // Make sure we inherit our base class's operator=()
2224   using HelpPrinter::operator=;
2225 
2226 protected:
2227   void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override {
2228     std::vector<OptionCategory *> SortedCategories;
2229     std::map<OptionCategory *, std::vector<Option *>> CategorizedOptions;
2230 
2231     // Collect registered option categories into vector in preparation for
2232     // sorting.
2233     for (auto I = GlobalParser->RegisteredOptionCategories.begin(),
2234               E = GlobalParser->RegisteredOptionCategories.end();
2235          I != E; ++I) {
2236       SortedCategories.push_back(*I);
2237     }
2238 
2239     // Sort the different option categories alphabetically.
2240     assert(SortedCategories.size() > 0 && "No option categories registered!");
2241     array_pod_sort(SortedCategories.begin(), SortedCategories.end(),
2242                    OptionCategoryCompare);
2243 
2244     // Create map to empty vectors.
2245     for (std::vector<OptionCategory *>::const_iterator
2246              I = SortedCategories.begin(),
2247              E = SortedCategories.end();
2248          I != E; ++I)
2249       CategorizedOptions[*I] = std::vector<Option *>();
2250 
2251     // Walk through pre-sorted options and assign into categories.
2252     // Because the options are already alphabetically sorted the
2253     // options within categories will also be alphabetically sorted.
2254     for (size_t I = 0, E = Opts.size(); I != E; ++I) {
2255       Option *Opt = Opts[I].second;
2256       for (auto &Cat : Opt->Categories) {
2257         assert(CategorizedOptions.count(Cat) > 0 &&
2258                "Option has an unregistered category");
2259         CategorizedOptions[Cat].push_back(Opt);
2260       }
2261     }
2262 
2263     // Now do printing.
2264     for (std::vector<OptionCategory *>::const_iterator
2265              Category = SortedCategories.begin(),
2266              E = SortedCategories.end();
2267          Category != E; ++Category) {
2268       // Hide empty categories for --help, but show for --help-hidden.
2269       const auto &CategoryOptions = CategorizedOptions[*Category];
2270       bool IsEmptyCategory = CategoryOptions.empty();
2271       if (!ShowHidden && IsEmptyCategory)
2272         continue;
2273 
2274       // Print category information.
2275       outs() << "\n";
2276       outs() << (*Category)->getName() << ":\n";
2277 
2278       // Check if description is set.
2279       if (!(*Category)->getDescription().empty())
2280         outs() << (*Category)->getDescription() << "\n\n";
2281       else
2282         outs() << "\n";
2283 
2284       // When using --help-hidden explicitly state if the category has no
2285       // options associated with it.
2286       if (IsEmptyCategory) {
2287         outs() << "  This option category has no options.\n";
2288         continue;
2289       }
2290       // Loop over the options in the category and print.
2291       for (const Option *Opt : CategoryOptions)
2292         Opt->printOptionInfo(MaxArgLen);
2293     }
2294   }
2295 };
2296 
2297 // This wraps the Uncategorizing and Categorizing printers and decides
2298 // at run time which should be invoked.
2299 class HelpPrinterWrapper {
2300 private:
2301   HelpPrinter &UncategorizedPrinter;
2302   CategorizedHelpPrinter &CategorizedPrinter;
2303 
2304 public:
2305   explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
2306                               CategorizedHelpPrinter &CategorizedPrinter)
2307       : UncategorizedPrinter(UncategorizedPrinter),
2308         CategorizedPrinter(CategorizedPrinter) {}
2309 
2310   // Invoke the printer.
2311   void operator=(bool Value);
2312 };
2313 
2314 } // End anonymous namespace
2315 
2316 // Declare the four HelpPrinter instances that are used to print out help, or
2317 // help-hidden as an uncategorized list or in categories.
2318 static HelpPrinter UncategorizedNormalPrinter(false);
2319 static HelpPrinter UncategorizedHiddenPrinter(true);
2320 static CategorizedHelpPrinter CategorizedNormalPrinter(false);
2321 static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
2322 
2323 // Declare HelpPrinter wrappers that will decide whether or not to invoke
2324 // a categorizing help printer
2325 static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
2326                                                CategorizedNormalPrinter);
2327 static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
2328                                                CategorizedHiddenPrinter);
2329 
2330 // Define a category for generic options that all tools should have.
2331 static cl::OptionCategory GenericCategory("Generic Options");
2332 
2333 // Define uncategorized help printers.
2334 // --help-list is hidden by default because if Option categories are being used
2335 // then --help behaves the same as --help-list.
2336 static cl::opt<HelpPrinter, true, parser<bool>> HLOp(
2337     "help-list",
2338     cl::desc("Display list of available options (--help-list-hidden for more)"),
2339     cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed,
2340     cl::cat(GenericCategory), cl::sub(*AllSubCommands));
2341 
2342 static cl::opt<HelpPrinter, true, parser<bool>>
2343     HLHOp("help-list-hidden", cl::desc("Display list of all available options"),
2344           cl::location(UncategorizedHiddenPrinter), cl::Hidden,
2345           cl::ValueDisallowed, cl::cat(GenericCategory),
2346           cl::sub(*AllSubCommands));
2347 
2348 // Define uncategorized/categorized help printers. These printers change their
2349 // behaviour at runtime depending on whether one or more Option categories have
2350 // been declared.
2351 static cl::opt<HelpPrinterWrapper, true, parser<bool>>
2352     HOp("help", cl::desc("Display available options (--help-hidden for more)"),
2353         cl::location(WrappedNormalPrinter), cl::ValueDisallowed,
2354         cl::cat(GenericCategory), cl::sub(*AllSubCommands));
2355 
2356 static cl::alias HOpA("h", cl::desc("Alias for --help"), cl::aliasopt(HOp),
2357                       cl::DefaultOption);
2358 
2359 static cl::opt<HelpPrinterWrapper, true, parser<bool>>
2360     HHOp("help-hidden", cl::desc("Display all available options"),
2361          cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed,
2362          cl::cat(GenericCategory), cl::sub(*AllSubCommands));
2363 
2364 static cl::opt<bool> PrintOptions(
2365     "print-options",
2366     cl::desc("Print non-default options after command line parsing"),
2367     cl::Hidden, cl::init(false), cl::cat(GenericCategory),
2368     cl::sub(*AllSubCommands));
2369 
2370 static cl::opt<bool> PrintAllOptions(
2371     "print-all-options",
2372     cl::desc("Print all option values after command line parsing"), cl::Hidden,
2373     cl::init(false), cl::cat(GenericCategory), cl::sub(*AllSubCommands));
2374 
2375 void HelpPrinterWrapper::operator=(bool Value) {
2376   if (!Value)
2377     return;
2378 
2379   // Decide which printer to invoke. If more than one option category is
2380   // registered then it is useful to show the categorized help instead of
2381   // uncategorized help.
2382   if (GlobalParser->RegisteredOptionCategories.size() > 1) {
2383     // unhide --help-list option so user can have uncategorized output if they
2384     // want it.
2385     HLOp.setHiddenFlag(NotHidden);
2386 
2387     CategorizedPrinter = true; // Invoke categorized printer
2388   } else
2389     UncategorizedPrinter = true; // Invoke uncategorized printer
2390 }
2391 
2392 // Print the value of each option.
2393 void cl::PrintOptionValues() { GlobalParser->printOptionValues(); }
2394 
2395 void CommandLineParser::printOptionValues() {
2396   if (!PrintOptions && !PrintAllOptions)
2397     return;
2398 
2399   SmallVector<std::pair<const char *, Option *>, 128> Opts;
2400   sortOpts(ActiveSubCommand->OptionsMap, Opts, /*ShowHidden*/ true);
2401 
2402   // Compute the maximum argument length...
2403   size_t MaxArgLen = 0;
2404   for (size_t i = 0, e = Opts.size(); i != e; ++i)
2405     MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
2406 
2407   for (size_t i = 0, e = Opts.size(); i != e; ++i)
2408     Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
2409 }
2410 
2411 static VersionPrinterTy OverrideVersionPrinter = nullptr;
2412 
2413 static std::vector<VersionPrinterTy> *ExtraVersionPrinters = nullptr;
2414 
2415 namespace {
2416 class VersionPrinter {
2417 public:
2418   void print() {
2419     raw_ostream &OS = outs();
2420 #ifdef PACKAGE_VENDOR
2421     OS << PACKAGE_VENDOR << " ";
2422 #else
2423     OS << "LLVM (http://llvm.org/):\n  ";
2424 #endif
2425     OS << PACKAGE_NAME << " version " << PACKAGE_VERSION;
2426 #ifdef LLVM_VERSION_INFO
2427     OS << " " << LLVM_VERSION_INFO;
2428 #endif
2429     OS << "\n  ";
2430 #ifndef __OPTIMIZE__
2431     OS << "DEBUG build";
2432 #else
2433     OS << "Optimized build";
2434 #endif
2435 #ifndef NDEBUG
2436     OS << " with assertions";
2437 #endif
2438 #if LLVM_VERSION_PRINTER_SHOW_HOST_TARGET_INFO
2439     std::string CPU = sys::getHostCPUName();
2440     if (CPU == "generic")
2441       CPU = "(unknown)";
2442     OS << ".\n"
2443        << "  Default target: " << sys::getDefaultTargetTriple() << '\n'
2444        << "  Host CPU: " << CPU;
2445 #endif
2446     OS << '\n';
2447   }
2448   void operator=(bool OptionWasSpecified) {
2449     if (!OptionWasSpecified)
2450       return;
2451 
2452     if (OverrideVersionPrinter != nullptr) {
2453       OverrideVersionPrinter(outs());
2454       exit(0);
2455     }
2456     print();
2457 
2458     // Iterate over any registered extra printers and call them to add further
2459     // information.
2460     if (ExtraVersionPrinters != nullptr) {
2461       outs() << '\n';
2462       for (auto I : *ExtraVersionPrinters)
2463         I(outs());
2464     }
2465 
2466     exit(0);
2467   }
2468 };
2469 } // End anonymous namespace
2470 
2471 // Define the --version option that prints out the LLVM version for the tool
2472 static VersionPrinter VersionPrinterInstance;
2473 
2474 static cl::opt<VersionPrinter, true, parser<bool>>
2475     VersOp("version", cl::desc("Display the version of this program"),
2476            cl::location(VersionPrinterInstance), cl::ValueDisallowed,
2477            cl::cat(GenericCategory));
2478 
2479 // Utility function for printing the help message.
2480 void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
2481   if (!Hidden && !Categorized)
2482     UncategorizedNormalPrinter.printHelp();
2483   else if (!Hidden && Categorized)
2484     CategorizedNormalPrinter.printHelp();
2485   else if (Hidden && !Categorized)
2486     UncategorizedHiddenPrinter.printHelp();
2487   else
2488     CategorizedHiddenPrinter.printHelp();
2489 }
2490 
2491 /// Utility function for printing version number.
2492 void cl::PrintVersionMessage() { VersionPrinterInstance.print(); }
2493 
2494 void cl::SetVersionPrinter(VersionPrinterTy func) { OverrideVersionPrinter = func; }
2495 
2496 void cl::AddExtraVersionPrinter(VersionPrinterTy func) {
2497   if (!ExtraVersionPrinters)
2498     ExtraVersionPrinters = new std::vector<VersionPrinterTy>;
2499 
2500   ExtraVersionPrinters->push_back(func);
2501 }
2502 
2503 StringMap<Option *> &cl::getRegisteredOptions(SubCommand &Sub) {
2504   auto &Subs = GlobalParser->RegisteredSubCommands;
2505   (void)Subs;
2506   assert(is_contained(Subs, &Sub));
2507   return Sub.OptionsMap;
2508 }
2509 
2510 iterator_range<typename SmallPtrSet<SubCommand *, 4>::iterator>
2511 cl::getRegisteredSubcommands() {
2512   return GlobalParser->getRegisteredSubcommands();
2513 }
2514 
2515 void cl::HideUnrelatedOptions(cl::OptionCategory &Category, SubCommand &Sub) {
2516   for (auto &I : Sub.OptionsMap) {
2517     for (auto &Cat : I.second->Categories) {
2518       if (Cat != &Category &&
2519           Cat != &GenericCategory)
2520         I.second->setHiddenFlag(cl::ReallyHidden);
2521     }
2522   }
2523 }
2524 
2525 void cl::HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories,
2526                               SubCommand &Sub) {
2527   for (auto &I : Sub.OptionsMap) {
2528     for (auto &Cat : I.second->Categories) {
2529       if (find(Categories, Cat) == Categories.end() && Cat != &GenericCategory)
2530         I.second->setHiddenFlag(cl::ReallyHidden);
2531     }
2532   }
2533 }
2534 
2535 void cl::ResetCommandLineParser() { GlobalParser->reset(); }
2536 void cl::ResetAllOptionOccurrences() {
2537   GlobalParser->ResetAllOptionOccurrences();
2538 }
2539 
2540 void LLVMParseCommandLineOptions(int argc, const char *const *argv,
2541                                  const char *Overview) {
2542   llvm::cl::ParseCommandLineOptions(argc, argv, StringRef(Overview),
2543                                     &llvm::nulls());
2544 }
2545