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