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