xref: /llvm-project/llvm/lib/Support/CommandLine.cpp (revision d90b5a2e5119fe3a67633a9880ff712630d26061)
1 //===-- CommandLine.cpp - Command line parser implementation --------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This class implements a command line argument processor that is useful when
10 // creating a tool.  It provides a simple, minimalistic interface that is easily
11 // extensible and supports nonlocal (library) command line options.
12 //
13 // Note that rather than trying to figure out what this code does, you could try
14 // reading the library documentation located in docs/CommandLine.html
15 //
16 //===----------------------------------------------------------------------===//
17 
18 #include "llvm/Support/CommandLine.h"
19 #include "llvm-c/Support.h"
20 #include "llvm/ADT/ArrayRef.h"
21 #include "llvm/ADT/Optional.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/StringMap.h"
27 #include "llvm/ADT/Triple.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 isWhitespaceOrNull(char C) {
696   return isWhitespace(C) || C == '\0';
697 }
698 
699 static bool isQuote(char C) { return C == '\"' || C == '\''; }
700 
701 void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
702                                 SmallVectorImpl<const char *> &NewArgv,
703                                 bool MarkEOLs) {
704   SmallString<128> Token;
705   for (size_t I = 0, E = Src.size(); I != E; ++I) {
706     // Consume runs of whitespace.
707     if (Token.empty()) {
708       while (I != E && isWhitespace(Src[I])) {
709         // Mark the end of lines in response files
710         if (MarkEOLs && Src[I] == '\n')
711           NewArgv.push_back(nullptr);
712         ++I;
713       }
714       if (I == E)
715         break;
716     }
717 
718     char C = Src[I];
719 
720     // Backslash escapes the next character.
721     if (I + 1 < E && C == '\\') {
722       ++I; // Skip the escape.
723       Token.push_back(Src[I]);
724       continue;
725     }
726 
727     // Consume a quoted string.
728     if (isQuote(C)) {
729       ++I;
730       while (I != E && Src[I] != C) {
731         // Backslash escapes the next character.
732         if (Src[I] == '\\' && I + 1 != E)
733           ++I;
734         Token.push_back(Src[I]);
735         ++I;
736       }
737       if (I == E)
738         break;
739       continue;
740     }
741 
742     // End the token if this is whitespace.
743     if (isWhitespace(C)) {
744       if (!Token.empty())
745         NewArgv.push_back(Saver.save(StringRef(Token)).data());
746       Token.clear();
747       continue;
748     }
749 
750     // This is a normal character.  Append it.
751     Token.push_back(C);
752   }
753 
754   // Append the last token after hitting EOF with no whitespace.
755   if (!Token.empty())
756     NewArgv.push_back(Saver.save(StringRef(Token)).data());
757   // Mark the end of response files
758   if (MarkEOLs)
759     NewArgv.push_back(nullptr);
760 }
761 
762 /// Backslashes are interpreted in a rather complicated way in the Windows-style
763 /// command line, because backslashes are used both to separate path and to
764 /// escape double quote. This method consumes runs of backslashes as well as the
765 /// following double quote if it's escaped.
766 ///
767 ///  * If an even number of backslashes is followed by a double quote, one
768 ///    backslash is output for every pair of backslashes, and the last double
769 ///    quote remains unconsumed. The double quote will later be interpreted as
770 ///    the start or end of a quoted string in the main loop outside of this
771 ///    function.
772 ///
773 ///  * If an odd number of backslashes is followed by a double quote, one
774 ///    backslash is output for every pair of backslashes, and a double quote is
775 ///    output for the last pair of backslash-double quote. The double quote is
776 ///    consumed in this case.
777 ///
778 ///  * Otherwise, backslashes are interpreted literally.
779 static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
780   size_t E = Src.size();
781   int BackslashCount = 0;
782   // Skip the backslashes.
783   do {
784     ++I;
785     ++BackslashCount;
786   } while (I != E && Src[I] == '\\');
787 
788   bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
789   if (FollowedByDoubleQuote) {
790     Token.append(BackslashCount / 2, '\\');
791     if (BackslashCount % 2 == 0)
792       return I - 1;
793     Token.push_back('"');
794     return I;
795   }
796   Token.append(BackslashCount, '\\');
797   return I - 1;
798 }
799 
800 void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
801                                     SmallVectorImpl<const char *> &NewArgv,
802                                     bool MarkEOLs) {
803   SmallString<128> Token;
804 
805   // This is a small state machine to consume characters until it reaches the
806   // end of the source string.
807   enum { INIT, UNQUOTED, QUOTED } State = INIT;
808   for (size_t I = 0, E = Src.size(); I != E; ++I) {
809     char C = Src[I];
810 
811     // INIT state indicates that the current input index is at the start of
812     // the string or between tokens.
813     if (State == INIT) {
814       if (isWhitespaceOrNull(C)) {
815         // Mark the end of lines in response files
816         if (MarkEOLs && C == '\n')
817           NewArgv.push_back(nullptr);
818         continue;
819       }
820       if (C == '"') {
821         State = QUOTED;
822         continue;
823       }
824       if (C == '\\') {
825         I = parseBackslash(Src, I, Token);
826         State = UNQUOTED;
827         continue;
828       }
829       Token.push_back(C);
830       State = UNQUOTED;
831       continue;
832     }
833 
834     // UNQUOTED state means that it's reading a token not quoted by double
835     // quotes.
836     if (State == UNQUOTED) {
837       // Whitespace means the end of the token.
838       if (isWhitespaceOrNull(C)) {
839         NewArgv.push_back(Saver.save(StringRef(Token)).data());
840         Token.clear();
841         State = INIT;
842         // Mark the end of lines in response files
843         if (MarkEOLs && C == '\n')
844           NewArgv.push_back(nullptr);
845         continue;
846       }
847       if (C == '"') {
848         State = QUOTED;
849         continue;
850       }
851       if (C == '\\') {
852         I = parseBackslash(Src, I, Token);
853         continue;
854       }
855       Token.push_back(C);
856       continue;
857     }
858 
859     // QUOTED state means that it's reading a token quoted by double quotes.
860     if (State == QUOTED) {
861       if (C == '"') {
862         State = UNQUOTED;
863         continue;
864       }
865       if (C == '\\') {
866         I = parseBackslash(Src, I, Token);
867         continue;
868       }
869       Token.push_back(C);
870     }
871   }
872   // Append the last token after hitting EOF with no whitespace.
873   if (!Token.empty())
874     NewArgv.push_back(Saver.save(StringRef(Token)).data());
875   // Mark the end of response files
876   if (MarkEOLs)
877     NewArgv.push_back(nullptr);
878 }
879 
880 void cl::tokenizeConfigFile(StringRef Source, StringSaver &Saver,
881                             SmallVectorImpl<const char *> &NewArgv,
882                             bool MarkEOLs) {
883   for (const char *Cur = Source.begin(); Cur != Source.end();) {
884     SmallString<128> Line;
885     // Check for comment line.
886     if (isWhitespace(*Cur)) {
887       while (Cur != Source.end() && isWhitespace(*Cur))
888         ++Cur;
889       continue;
890     }
891     if (*Cur == '#') {
892       while (Cur != Source.end() && *Cur != '\n')
893         ++Cur;
894       continue;
895     }
896     // Find end of the current line.
897     const char *Start = Cur;
898     for (const char *End = Source.end(); Cur != End; ++Cur) {
899       if (*Cur == '\\') {
900         if (Cur + 1 != End) {
901           ++Cur;
902           if (*Cur == '\n' ||
903               (*Cur == '\r' && (Cur + 1 != End) && Cur[1] == '\n')) {
904             Line.append(Start, Cur - 1);
905             if (*Cur == '\r')
906               ++Cur;
907             Start = Cur + 1;
908           }
909         }
910       } else if (*Cur == '\n')
911         break;
912     }
913     // Tokenize line.
914     Line.append(Start, Cur);
915     cl::TokenizeGNUCommandLine(Line, Saver, NewArgv, MarkEOLs);
916   }
917 }
918 
919 // It is called byte order marker but the UTF-8 BOM is actually not affected
920 // by the host system's endianness.
921 static bool hasUTF8ByteOrderMark(ArrayRef<char> S) {
922   return (S.size() >= 3 && S[0] == '\xef' && S[1] == '\xbb' && S[2] == '\xbf');
923 }
924 
925 static bool ExpandResponseFile(StringRef FName, StringSaver &Saver,
926                                TokenizerCallback Tokenizer,
927                                SmallVectorImpl<const char *> &NewArgv,
928                                bool MarkEOLs, bool RelativeNames) {
929   ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
930       MemoryBuffer::getFile(FName);
931   if (!MemBufOrErr)
932     return false;
933   MemoryBuffer &MemBuf = *MemBufOrErr.get();
934   StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize());
935 
936   // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
937   ArrayRef<char> BufRef(MemBuf.getBufferStart(), MemBuf.getBufferEnd());
938   std::string UTF8Buf;
939   if (hasUTF16ByteOrderMark(BufRef)) {
940     if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
941       return false;
942     Str = StringRef(UTF8Buf);
943   }
944   // If we see UTF-8 BOM sequence at the beginning of a file, we shall remove
945   // these bytes before parsing.
946   // Reference: http://en.wikipedia.org/wiki/UTF-8#Byte_order_mark
947   else if (hasUTF8ByteOrderMark(BufRef))
948     Str = StringRef(BufRef.data() + 3, BufRef.size() - 3);
949 
950   // Tokenize the contents into NewArgv.
951   Tokenizer(Str, Saver, NewArgv, MarkEOLs);
952 
953   // If names of nested response files should be resolved relative to including
954   // file, replace the included response file names with their full paths
955   // obtained by required resolution.
956   if (RelativeNames)
957     for (unsigned I = 0; I < NewArgv.size(); ++I)
958       if (NewArgv[I]) {
959         StringRef Arg = NewArgv[I];
960         if (Arg.front() == '@') {
961           StringRef FileName = Arg.drop_front();
962           if (llvm::sys::path::is_relative(FileName)) {
963             SmallString<128> ResponseFile;
964             ResponseFile.append(1, '@');
965             if (llvm::sys::path::is_relative(FName)) {
966               SmallString<128> curr_dir;
967               llvm::sys::fs::current_path(curr_dir);
968               ResponseFile.append(curr_dir.str());
969             }
970             llvm::sys::path::append(
971                 ResponseFile, llvm::sys::path::parent_path(FName), FileName);
972             NewArgv[I] = Saver.save(ResponseFile.c_str()).data();
973           }
974         }
975       }
976 
977   return true;
978 }
979 
980 /// Expand response files on a command line recursively using the given
981 /// StringSaver and tokenization strategy.
982 bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
983                              SmallVectorImpl<const char *> &Argv,
984                              bool MarkEOLs, bool RelativeNames) {
985   unsigned RspFiles = 0;
986   bool AllExpanded = true;
987 
988   // Don't cache Argv.size() because it can change.
989   for (unsigned I = 0; I != Argv.size();) {
990     const char *Arg = Argv[I];
991     // Check if it is an EOL marker
992     if (Arg == nullptr) {
993       ++I;
994       continue;
995     }
996     if (Arg[0] != '@') {
997       ++I;
998       continue;
999     }
1000 
1001     // If we have too many response files, leave some unexpanded.  This avoids
1002     // crashing on self-referential response files.
1003     if (RspFiles++ > 20)
1004       return false;
1005 
1006     // Replace this response file argument with the tokenization of its
1007     // contents.  Nested response files are expanded in subsequent iterations.
1008     SmallVector<const char *, 0> ExpandedArgv;
1009     if (!ExpandResponseFile(Arg + 1, Saver, Tokenizer, ExpandedArgv,
1010                             MarkEOLs, RelativeNames)) {
1011       // We couldn't read this file, so we leave it in the argument stream and
1012       // move on.
1013       AllExpanded = false;
1014       ++I;
1015       continue;
1016     }
1017     Argv.erase(Argv.begin() + I);
1018     Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
1019   }
1020   return AllExpanded;
1021 }
1022 
1023 bool cl::readConfigFile(StringRef CfgFile, StringSaver &Saver,
1024                         SmallVectorImpl<const char *> &Argv) {
1025   if (!ExpandResponseFile(CfgFile, Saver, cl::tokenizeConfigFile, Argv,
1026                           /*MarkEOLs*/ false, /*RelativeNames*/ true))
1027     return false;
1028   return ExpandResponseFiles(Saver, cl::tokenizeConfigFile, Argv,
1029                              /*MarkEOLs*/ false, /*RelativeNames*/ true);
1030 }
1031 
1032 /// ParseEnvironmentOptions - An alternative entry point to the
1033 /// CommandLine library, which allows you to read the program's name
1034 /// from the caller (as PROGNAME) and its command-line arguments from
1035 /// an environment variable (whose name is given in ENVVAR).
1036 ///
1037 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
1038                                  const char *Overview) {
1039   // Check args.
1040   assert(progName && "Program name not specified");
1041   assert(envVar && "Environment variable name missing");
1042 
1043   // Get the environment variable they want us to parse options out of.
1044   llvm::Optional<std::string> envValue = sys::Process::GetEnv(StringRef(envVar));
1045   if (!envValue)
1046     return;
1047 
1048   // Get program's "name", which we wouldn't know without the caller
1049   // telling us.
1050   SmallVector<const char *, 20> newArgv;
1051   BumpPtrAllocator A;
1052   StringSaver Saver(A);
1053   newArgv.push_back(Saver.save(progName).data());
1054 
1055   // Parse the value of the environment variable into a "command line"
1056   // and hand it off to ParseCommandLineOptions().
1057   TokenizeGNUCommandLine(*envValue, Saver, newArgv);
1058   int newArgc = static_cast<int>(newArgv.size());
1059   ParseCommandLineOptions(newArgc, &newArgv[0], StringRef(Overview));
1060 }
1061 
1062 bool cl::ParseCommandLineOptions(int argc, const char *const *argv,
1063                                  StringRef Overview, raw_ostream *Errs,
1064                                  const char *EnvVar) {
1065   SmallVector<const char *, 20> NewArgv;
1066   BumpPtrAllocator A;
1067   StringSaver Saver(A);
1068   NewArgv.push_back(argv[0]);
1069 
1070   // Parse options from environment variable.
1071   if (EnvVar) {
1072     if (llvm::Optional<std::string> EnvValue =
1073             sys::Process::GetEnv(StringRef(EnvVar)))
1074       TokenizeGNUCommandLine(*EnvValue, Saver, NewArgv);
1075   }
1076 
1077   // Append options from command line.
1078   for (int I = 1; I < argc; ++I)
1079     NewArgv.push_back(argv[I]);
1080   int NewArgc = static_cast<int>(NewArgv.size());
1081 
1082   // Parse all options.
1083   return GlobalParser->ParseCommandLineOptions(NewArgc, &NewArgv[0], Overview,
1084                                                Errs);
1085 }
1086 
1087 void CommandLineParser::ResetAllOptionOccurrences() {
1088   // So that we can parse different command lines multiple times in succession
1089   // we reset all option values to look like they have never been seen before.
1090   for (auto SC : RegisteredSubCommands) {
1091     for (auto &O : SC->OptionsMap)
1092       O.second->reset();
1093   }
1094 }
1095 
1096 bool CommandLineParser::ParseCommandLineOptions(int argc,
1097                                                 const char *const *argv,
1098                                                 StringRef Overview,
1099                                                 raw_ostream *Errs) {
1100   assert(hasOptions() && "No options specified!");
1101 
1102   // Expand response files.
1103   SmallVector<const char *, 20> newArgv(argv, argv + argc);
1104   BumpPtrAllocator A;
1105   StringSaver Saver(A);
1106   ExpandResponseFiles(Saver,
1107          Triple(sys::getProcessTriple()).isOSWindows() ?
1108          cl::TokenizeWindowsCommandLine : cl::TokenizeGNUCommandLine,
1109          newArgv);
1110   argv = &newArgv[0];
1111   argc = static_cast<int>(newArgv.size());
1112 
1113   // Copy the program name into ProgName, making sure not to overflow it.
1114   ProgramName = sys::path::filename(StringRef(argv[0]));
1115 
1116   ProgramOverview = Overview;
1117   bool IgnoreErrors = Errs;
1118   if (!Errs)
1119     Errs = &errs();
1120   bool ErrorParsing = false;
1121 
1122   // Check out the positional arguments to collect information about them.
1123   unsigned NumPositionalRequired = 0;
1124 
1125   // Determine whether or not there are an unlimited number of positionals
1126   bool HasUnlimitedPositionals = false;
1127 
1128   int FirstArg = 1;
1129   SubCommand *ChosenSubCommand = &*TopLevelSubCommand;
1130   if (argc >= 2 && argv[FirstArg][0] != '-') {
1131     // If the first argument specifies a valid subcommand, start processing
1132     // options from the second argument.
1133     ChosenSubCommand = LookupSubCommand(StringRef(argv[FirstArg]));
1134     if (ChosenSubCommand != &*TopLevelSubCommand)
1135       FirstArg = 2;
1136   }
1137   GlobalParser->ActiveSubCommand = ChosenSubCommand;
1138 
1139   assert(ChosenSubCommand);
1140   auto &ConsumeAfterOpt = ChosenSubCommand->ConsumeAfterOpt;
1141   auto &PositionalOpts = ChosenSubCommand->PositionalOpts;
1142   auto &SinkOpts = ChosenSubCommand->SinkOpts;
1143   auto &OptionsMap = ChosenSubCommand->OptionsMap;
1144 
1145   if (ConsumeAfterOpt) {
1146     assert(PositionalOpts.size() > 0 &&
1147            "Cannot specify cl::ConsumeAfter without a positional argument!");
1148   }
1149   if (!PositionalOpts.empty()) {
1150 
1151     // Calculate how many positional values are _required_.
1152     bool UnboundedFound = false;
1153     for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
1154       Option *Opt = PositionalOpts[i];
1155       if (RequiresValue(Opt))
1156         ++NumPositionalRequired;
1157       else if (ConsumeAfterOpt) {
1158         // ConsumeAfter cannot be combined with "optional" positional options
1159         // unless there is only one positional argument...
1160         if (PositionalOpts.size() > 1) {
1161           if (!IgnoreErrors)
1162             Opt->error("error - this positional option will never be matched, "
1163                        "because it does not Require a value, and a "
1164                        "cl::ConsumeAfter option is active!");
1165           ErrorParsing = true;
1166         }
1167       } else if (UnboundedFound && !Opt->hasArgStr()) {
1168         // This option does not "require" a value...  Make sure this option is
1169         // not specified after an option that eats all extra arguments, or this
1170         // one will never get any!
1171         //
1172         if (!IgnoreErrors)
1173           Opt->error("error - option can never match, because "
1174                      "another positional argument will match an "
1175                      "unbounded number of values, and this option"
1176                      " does not require a value!");
1177         *Errs << ProgramName << ": CommandLine Error: Option '" << Opt->ArgStr
1178               << "' is all messed up!\n";
1179         *Errs << PositionalOpts.size();
1180         ErrorParsing = true;
1181       }
1182       UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
1183     }
1184     HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
1185   }
1186 
1187   // PositionalVals - A vector of "positional" arguments we accumulate into
1188   // the process at the end.
1189   //
1190   SmallVector<std::pair<StringRef, unsigned>, 4> PositionalVals;
1191 
1192   // If the program has named positional arguments, and the name has been run
1193   // across, keep track of which positional argument was named.  Otherwise put
1194   // the positional args into the PositionalVals list...
1195   Option *ActivePositionalArg = nullptr;
1196 
1197   // Loop over all of the arguments... processing them.
1198   bool DashDashFound = false; // Have we read '--'?
1199   for (int i = FirstArg; i < argc; ++i) {
1200     Option *Handler = nullptr;
1201     Option *NearestHandler = nullptr;
1202     std::string NearestHandlerString;
1203     StringRef Value;
1204     StringRef ArgName = "";
1205 
1206     // Check to see if this is a positional argument.  This argument is
1207     // considered to be positional if it doesn't start with '-', if it is "-"
1208     // itself, or if we have seen "--" already.
1209     //
1210     if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
1211       // Positional argument!
1212       if (ActivePositionalArg) {
1213         ProvidePositionalOption(ActivePositionalArg, StringRef(argv[i]), i);
1214         continue; // We are done!
1215       }
1216 
1217       if (!PositionalOpts.empty()) {
1218         PositionalVals.push_back(std::make_pair(StringRef(argv[i]), i));
1219 
1220         // All of the positional arguments have been fulfulled, give the rest to
1221         // the consume after option... if it's specified...
1222         //
1223         if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) {
1224           for (++i; i < argc; ++i)
1225             PositionalVals.push_back(std::make_pair(StringRef(argv[i]), i));
1226           break; // Handle outside of the argument processing loop...
1227         }
1228 
1229         // Delay processing positional arguments until the end...
1230         continue;
1231       }
1232     } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
1233                !DashDashFound) {
1234       DashDashFound = true; // This is the mythical "--"?
1235       continue;             // Don't try to process it as an argument itself.
1236     } else if (ActivePositionalArg &&
1237                (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
1238       // If there is a positional argument eating options, check to see if this
1239       // option is another positional argument.  If so, treat it as an argument,
1240       // otherwise feed it to the eating positional.
1241       ArgName = StringRef(argv[i] + 1);
1242       // Eat leading dashes.
1243       while (!ArgName.empty() && ArgName[0] == '-')
1244         ArgName = ArgName.substr(1);
1245 
1246       Handler = LookupOption(*ChosenSubCommand, ArgName, Value);
1247       if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
1248         ProvidePositionalOption(ActivePositionalArg, StringRef(argv[i]), i);
1249         continue; // We are done!
1250       }
1251 
1252     } else { // We start with a '-', must be an argument.
1253       ArgName = StringRef(argv[i] + 1);
1254       // Eat leading dashes.
1255       while (!ArgName.empty() && ArgName[0] == '-')
1256         ArgName = ArgName.substr(1);
1257 
1258       Handler = LookupOption(*ChosenSubCommand, ArgName, Value);
1259 
1260       // Check to see if this "option" is really a prefixed or grouped argument.
1261       if (!Handler)
1262         Handler = HandlePrefixedOrGroupedOption(ArgName, Value, ErrorParsing,
1263                                                 OptionsMap);
1264 
1265       // Otherwise, look for the closest available option to report to the user
1266       // in the upcoming error.
1267       if (!Handler && SinkOpts.empty())
1268         NearestHandler =
1269             LookupNearestOption(ArgName, OptionsMap, NearestHandlerString);
1270     }
1271 
1272     if (!Handler) {
1273       if (SinkOpts.empty()) {
1274         *Errs << ProgramName << ": Unknown command line argument '" << argv[i]
1275               << "'.  Try: '" << argv[0] << " -help'\n";
1276 
1277         if (NearestHandler) {
1278           // If we know a near match, report it as well.
1279           *Errs << ProgramName << ": Did you mean '-" << NearestHandlerString
1280                  << "'?\n";
1281         }
1282 
1283         ErrorParsing = true;
1284       } else {
1285         for (SmallVectorImpl<Option *>::iterator I = SinkOpts.begin(),
1286                                                  E = SinkOpts.end();
1287              I != E; ++I)
1288           (*I)->addOccurrence(i, "", StringRef(argv[i]));
1289       }
1290       continue;
1291     }
1292 
1293     // If this is a named positional argument, just remember that it is the
1294     // active one...
1295     if (Handler->getFormattingFlag() == cl::Positional) {
1296       if ((Handler->getMiscFlags() & PositionalEatsArgs) && !Value.empty()) {
1297         Handler->error("This argument does not take a value.\n"
1298                        "\tInstead, it consumes any positional arguments until "
1299                        "the next recognized option.", *Errs);
1300         ErrorParsing = true;
1301       }
1302       ActivePositionalArg = Handler;
1303     }
1304     else
1305       ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
1306   }
1307 
1308   // Check and handle positional arguments now...
1309   if (NumPositionalRequired > PositionalVals.size()) {
1310       *Errs << ProgramName
1311              << ": Not enough positional command line arguments specified!\n"
1312              << "Must specify at least " << NumPositionalRequired
1313              << " positional argument" << (NumPositionalRequired > 1 ? "s" : "")
1314              << ": See: " << argv[0] << " -help\n";
1315 
1316     ErrorParsing = true;
1317   } else if (!HasUnlimitedPositionals &&
1318              PositionalVals.size() > PositionalOpts.size()) {
1319     *Errs << ProgramName << ": Too many positional arguments specified!\n"
1320           << "Can specify at most " << PositionalOpts.size()
1321           << " positional arguments: See: " << argv[0] << " -help\n";
1322     ErrorParsing = true;
1323 
1324   } else if (!ConsumeAfterOpt) {
1325     // Positional args have already been handled if ConsumeAfter is specified.
1326     unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
1327     for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
1328       if (RequiresValue(PositionalOpts[i])) {
1329         ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
1330                                 PositionalVals[ValNo].second);
1331         ValNo++;
1332         --NumPositionalRequired; // We fulfilled our duty...
1333       }
1334 
1335       // If we _can_ give this option more arguments, do so now, as long as we
1336       // do not give it values that others need.  'Done' controls whether the
1337       // option even _WANTS_ any more.
1338       //
1339       bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
1340       while (NumVals - ValNo > NumPositionalRequired && !Done) {
1341         switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
1342         case cl::Optional:
1343           Done = true; // Optional arguments want _at most_ one value
1344           LLVM_FALLTHROUGH;
1345         case cl::ZeroOrMore: // Zero or more will take all they can get...
1346         case cl::OneOrMore:  // One or more will take all they can get...
1347           ProvidePositionalOption(PositionalOpts[i],
1348                                   PositionalVals[ValNo].first,
1349                                   PositionalVals[ValNo].second);
1350           ValNo++;
1351           break;
1352         default:
1353           llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
1354                            "positional argument processing!");
1355         }
1356       }
1357     }
1358   } else {
1359     assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
1360     unsigned ValNo = 0;
1361     for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
1362       if (RequiresValue(PositionalOpts[j])) {
1363         ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
1364                                                 PositionalVals[ValNo].first,
1365                                                 PositionalVals[ValNo].second);
1366         ValNo++;
1367       }
1368 
1369     // Handle the case where there is just one positional option, and it's
1370     // optional.  In this case, we want to give JUST THE FIRST option to the
1371     // positional option and keep the rest for the consume after.  The above
1372     // loop would have assigned no values to positional options in this case.
1373     //
1374     if (PositionalOpts.size() == 1 && ValNo == 0 && !PositionalVals.empty()) {
1375       ErrorParsing |= ProvidePositionalOption(PositionalOpts[0],
1376                                               PositionalVals[ValNo].first,
1377                                               PositionalVals[ValNo].second);
1378       ValNo++;
1379     }
1380 
1381     // Handle over all of the rest of the arguments to the
1382     // cl::ConsumeAfter command line option...
1383     for (; ValNo != PositionalVals.size(); ++ValNo)
1384       ErrorParsing |=
1385           ProvidePositionalOption(ConsumeAfterOpt, PositionalVals[ValNo].first,
1386                                   PositionalVals[ValNo].second);
1387   }
1388 
1389   // Loop over args and make sure all required args are specified!
1390   for (const auto &Opt : OptionsMap) {
1391     switch (Opt.second->getNumOccurrencesFlag()) {
1392     case Required:
1393     case OneOrMore:
1394       if (Opt.second->getNumOccurrences() == 0) {
1395         Opt.second->error("must be specified at least once!");
1396         ErrorParsing = true;
1397       }
1398       LLVM_FALLTHROUGH;
1399     default:
1400       break;
1401     }
1402   }
1403 
1404   // Now that we know if -debug is specified, we can use it.
1405   // Note that if ReadResponseFiles == true, this must be done before the
1406   // memory allocated for the expanded command line is free()d below.
1407   LLVM_DEBUG(dbgs() << "Args: ";
1408              for (int i = 0; i < argc; ++i) dbgs() << argv[i] << ' ';
1409              dbgs() << '\n';);
1410 
1411   // Free all of the memory allocated to the map.  Command line options may only
1412   // be processed once!
1413   MoreHelp.clear();
1414 
1415   // If we had an error processing our arguments, don't let the program execute
1416   if (ErrorParsing) {
1417     if (!IgnoreErrors)
1418       exit(1);
1419     return false;
1420   }
1421   return true;
1422 }
1423 
1424 //===----------------------------------------------------------------------===//
1425 // Option Base class implementation
1426 //
1427 
1428 bool Option::error(const Twine &Message, StringRef ArgName, raw_ostream &Errs) {
1429   if (!ArgName.data())
1430     ArgName = ArgStr;
1431   if (ArgName.empty())
1432     Errs << HelpStr; // Be nice for positional arguments
1433   else
1434     Errs << GlobalParser->ProgramName << ": for the -" << ArgName;
1435 
1436   Errs << " option: " << Message << "\n";
1437   return true;
1438 }
1439 
1440 bool Option::addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
1441                            bool MultiArg) {
1442   if (!MultiArg)
1443     NumOccurrences++; // Increment the number of times we have been seen
1444 
1445   switch (getNumOccurrencesFlag()) {
1446   case Optional:
1447     if (NumOccurrences > 1)
1448       return error("may only occur zero or one times!", ArgName);
1449     break;
1450   case Required:
1451     if (NumOccurrences > 1)
1452       return error("must occur exactly one time!", ArgName);
1453     LLVM_FALLTHROUGH;
1454   case OneOrMore:
1455   case ZeroOrMore:
1456   case ConsumeAfter:
1457     break;
1458   }
1459 
1460   return handleOccurrence(pos, ArgName, Value);
1461 }
1462 
1463 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
1464 // has been specified yet.
1465 //
1466 static StringRef getValueStr(const Option &O, StringRef DefaultMsg) {
1467   if (O.ValueStr.empty())
1468     return DefaultMsg;
1469   return O.ValueStr;
1470 }
1471 
1472 static StringRef ArgPrefix = "  -";
1473 static StringRef ArgHelpPrefix = " - ";
1474 static size_t ArgPrefixesSize = ArgPrefix.size() + ArgHelpPrefix.size();
1475 
1476 //===----------------------------------------------------------------------===//
1477 // cl::alias class implementation
1478 //
1479 
1480 // Return the width of the option tag for printing...
1481 size_t alias::getOptionWidth() const { return ArgStr.size() + ArgPrefixesSize; }
1482 
1483 void Option::printHelpStr(StringRef HelpStr, size_t Indent,
1484                           size_t FirstLineIndentedBy) {
1485   assert(Indent >= FirstLineIndentedBy);
1486   std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1487   outs().indent(Indent - FirstLineIndentedBy)
1488       << ArgHelpPrefix << Split.first << "\n";
1489   while (!Split.second.empty()) {
1490     Split = Split.second.split('\n');
1491     outs().indent(Indent) << Split.first << "\n";
1492   }
1493 }
1494 
1495 // Print out the option for the alias.
1496 void alias::printOptionInfo(size_t GlobalWidth) const {
1497   outs() << ArgPrefix << ArgStr;
1498   printHelpStr(HelpStr, GlobalWidth, ArgStr.size() + ArgPrefixesSize);
1499 }
1500 
1501 //===----------------------------------------------------------------------===//
1502 // Parser Implementation code...
1503 //
1504 
1505 // basic_parser implementation
1506 //
1507 
1508 // Return the width of the option tag for printing...
1509 size_t basic_parser_impl::getOptionWidth(const Option &O) const {
1510   size_t Len = O.ArgStr.size();
1511   auto ValName = getValueName();
1512   if (!ValName.empty()) {
1513     size_t FormattingLen = 3;
1514     if (O.getMiscFlags() & PositionalEatsArgs)
1515       FormattingLen = 6;
1516     Len += getValueStr(O, ValName).size() + FormattingLen;
1517   }
1518 
1519   return Len + ArgPrefixesSize;
1520 }
1521 
1522 // printOptionInfo - Print out information about this option.  The
1523 // to-be-maintained width is specified.
1524 //
1525 void basic_parser_impl::printOptionInfo(const Option &O,
1526                                         size_t GlobalWidth) const {
1527   outs() << ArgPrefix << O.ArgStr;
1528 
1529   auto ValName = getValueName();
1530   if (!ValName.empty()) {
1531     if (O.getMiscFlags() & PositionalEatsArgs) {
1532       outs() << " <" << getValueStr(O, ValName) << ">...";
1533     } else {
1534       outs() << "=<" << getValueStr(O, ValName) << '>';
1535     }
1536   }
1537 
1538   Option::printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
1539 }
1540 
1541 void basic_parser_impl::printOptionName(const Option &O,
1542                                         size_t GlobalWidth) const {
1543   outs() << ArgPrefix << O.ArgStr;
1544   outs().indent(GlobalWidth - O.ArgStr.size());
1545 }
1546 
1547 // parser<bool> implementation
1548 //
1549 bool parser<bool>::parse(Option &O, StringRef ArgName, StringRef Arg,
1550                          bool &Value) {
1551   if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1552       Arg == "1") {
1553     Value = true;
1554     return false;
1555   }
1556 
1557   if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1558     Value = false;
1559     return false;
1560   }
1561   return O.error("'" + Arg +
1562                  "' is invalid value for boolean argument! Try 0 or 1");
1563 }
1564 
1565 // parser<boolOrDefault> implementation
1566 //
1567 bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName, StringRef Arg,
1568                                   boolOrDefault &Value) {
1569   if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1570       Arg == "1") {
1571     Value = BOU_TRUE;
1572     return false;
1573   }
1574   if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1575     Value = BOU_FALSE;
1576     return false;
1577   }
1578 
1579   return O.error("'" + Arg +
1580                  "' is invalid value for boolean argument! Try 0 or 1");
1581 }
1582 
1583 // parser<int> implementation
1584 //
1585 bool parser<int>::parse(Option &O, StringRef ArgName, StringRef Arg,
1586                         int &Value) {
1587   if (Arg.getAsInteger(0, Value))
1588     return O.error("'" + Arg + "' value invalid for integer argument!");
1589   return false;
1590 }
1591 
1592 // parser<unsigned> implementation
1593 //
1594 bool parser<unsigned>::parse(Option &O, StringRef ArgName, StringRef Arg,
1595                              unsigned &Value) {
1596 
1597   if (Arg.getAsInteger(0, Value))
1598     return O.error("'" + Arg + "' value invalid for uint argument!");
1599   return false;
1600 }
1601 
1602 // parser<unsigned long long> implementation
1603 //
1604 bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
1605                                        StringRef Arg,
1606                                        unsigned long long &Value) {
1607 
1608   if (Arg.getAsInteger(0, Value))
1609     return O.error("'" + Arg + "' value invalid for uint argument!");
1610   return false;
1611 }
1612 
1613 // parser<double>/parser<float> implementation
1614 //
1615 static bool parseDouble(Option &O, StringRef Arg, double &Value) {
1616   if (to_float(Arg, Value))
1617     return false;
1618   return O.error("'" + Arg + "' value invalid for floating point argument!");
1619 }
1620 
1621 bool parser<double>::parse(Option &O, StringRef ArgName, StringRef Arg,
1622                            double &Val) {
1623   return parseDouble(O, Arg, Val);
1624 }
1625 
1626 bool parser<float>::parse(Option &O, StringRef ArgName, StringRef Arg,
1627                           float &Val) {
1628   double dVal;
1629   if (parseDouble(O, Arg, dVal))
1630     return true;
1631   Val = (float)dVal;
1632   return false;
1633 }
1634 
1635 // generic_parser_base implementation
1636 //
1637 
1638 // findOption - Return the option number corresponding to the specified
1639 // argument string.  If the option is not found, getNumOptions() is returned.
1640 //
1641 unsigned generic_parser_base::findOption(StringRef Name) {
1642   unsigned e = getNumOptions();
1643 
1644   for (unsigned i = 0; i != e; ++i) {
1645     if (getOption(i) == Name)
1646       return i;
1647   }
1648   return e;
1649 }
1650 
1651 static StringRef EqValue = "=<value>";
1652 static StringRef EmptyOption = "<empty>";
1653 static StringRef OptionPrefix = "    =";
1654 static size_t OptionPrefixesSize = OptionPrefix.size() + ArgHelpPrefix.size();
1655 
1656 static bool shouldPrintOption(StringRef Name, StringRef Description,
1657                               const Option &O) {
1658   return O.getValueExpectedFlag() != ValueOptional || !Name.empty() ||
1659          !Description.empty();
1660 }
1661 
1662 // Return the width of the option tag for printing...
1663 size_t generic_parser_base::getOptionWidth(const Option &O) const {
1664   if (O.hasArgStr()) {
1665     size_t Size = O.ArgStr.size() + ArgPrefixesSize + EqValue.size();
1666     for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1667       StringRef Name = getOption(i);
1668       if (!shouldPrintOption(Name, getDescription(i), O))
1669         continue;
1670       size_t NameSize = Name.empty() ? EmptyOption.size() : Name.size();
1671       Size = std::max(Size, NameSize + OptionPrefixesSize);
1672     }
1673     return Size;
1674   } else {
1675     size_t BaseSize = 0;
1676     for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1677       BaseSize = std::max(BaseSize, getOption(i).size() + 8);
1678     return BaseSize;
1679   }
1680 }
1681 
1682 // printOptionInfo - Print out information about this option.  The
1683 // to-be-maintained width is specified.
1684 //
1685 void generic_parser_base::printOptionInfo(const Option &O,
1686                                           size_t GlobalWidth) const {
1687   if (O.hasArgStr()) {
1688     // When the value is optional, first print a line just describing the
1689     // option without values.
1690     if (O.getValueExpectedFlag() == ValueOptional) {
1691       for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1692         if (getOption(i).empty()) {
1693           outs() << ArgPrefix << O.ArgStr;
1694           Option::printHelpStr(O.HelpStr, GlobalWidth,
1695                                O.ArgStr.size() + ArgPrefixesSize);
1696           break;
1697         }
1698       }
1699     }
1700 
1701     outs() << ArgPrefix << O.ArgStr << EqValue;
1702     Option::printHelpStr(O.HelpStr, GlobalWidth,
1703                          O.ArgStr.size() + EqValue.size() + ArgPrefixesSize);
1704     for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1705       StringRef OptionName = getOption(i);
1706       StringRef Description = getDescription(i);
1707       if (!shouldPrintOption(OptionName, Description, O))
1708         continue;
1709       assert(GlobalWidth >= OptionName.size() + OptionPrefixesSize);
1710       size_t NumSpaces = GlobalWidth - OptionName.size() - OptionPrefixesSize;
1711       outs() << OptionPrefix << OptionName;
1712       if (OptionName.empty()) {
1713         outs() << EmptyOption;
1714         assert(NumSpaces >= EmptyOption.size());
1715         NumSpaces -= EmptyOption.size();
1716       }
1717       if (!Description.empty())
1718         outs().indent(NumSpaces) << ArgHelpPrefix << "  " << Description;
1719       outs() << '\n';
1720     }
1721   } else {
1722     if (!O.HelpStr.empty())
1723       outs() << "  " << O.HelpStr << '\n';
1724     for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1725       auto Option = getOption(i);
1726       outs() << "    -" << Option;
1727       Option::printHelpStr(getDescription(i), GlobalWidth, Option.size() + 8);
1728     }
1729   }
1730 }
1731 
1732 static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1733 
1734 // printGenericOptionDiff - Print the value of this option and it's default.
1735 //
1736 // "Generic" options have each value mapped to a name.
1737 void generic_parser_base::printGenericOptionDiff(
1738     const Option &O, const GenericOptionValue &Value,
1739     const GenericOptionValue &Default, size_t GlobalWidth) const {
1740   outs() << "  -" << O.ArgStr;
1741   outs().indent(GlobalWidth - O.ArgStr.size());
1742 
1743   unsigned NumOpts = getNumOptions();
1744   for (unsigned i = 0; i != NumOpts; ++i) {
1745     if (Value.compare(getOptionValue(i)))
1746       continue;
1747 
1748     outs() << "= " << getOption(i);
1749     size_t L = getOption(i).size();
1750     size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1751     outs().indent(NumSpaces) << " (default: ";
1752     for (unsigned j = 0; j != NumOpts; ++j) {
1753       if (Default.compare(getOptionValue(j)))
1754         continue;
1755       outs() << getOption(j);
1756       break;
1757     }
1758     outs() << ")\n";
1759     return;
1760   }
1761   outs() << "= *unknown option value*\n";
1762 }
1763 
1764 // printOptionDiff - Specializations for printing basic value types.
1765 //
1766 #define PRINT_OPT_DIFF(T)                                                      \
1767   void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D,      \
1768                                   size_t GlobalWidth) const {                  \
1769     printOptionName(O, GlobalWidth);                                           \
1770     std::string Str;                                                           \
1771     {                                                                          \
1772       raw_string_ostream SS(Str);                                              \
1773       SS << V;                                                                 \
1774     }                                                                          \
1775     outs() << "= " << Str;                                                     \
1776     size_t NumSpaces =                                                         \
1777         MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0;               \
1778     outs().indent(NumSpaces) << " (default: ";                                 \
1779     if (D.hasValue())                                                          \
1780       outs() << D.getValue();                                                  \
1781     else                                                                       \
1782       outs() << "*no default*";                                                \
1783     outs() << ")\n";                                                           \
1784   }
1785 
1786 PRINT_OPT_DIFF(bool)
1787 PRINT_OPT_DIFF(boolOrDefault)
1788 PRINT_OPT_DIFF(int)
1789 PRINT_OPT_DIFF(unsigned)
1790 PRINT_OPT_DIFF(unsigned long long)
1791 PRINT_OPT_DIFF(double)
1792 PRINT_OPT_DIFF(float)
1793 PRINT_OPT_DIFF(char)
1794 
1795 void parser<std::string>::printOptionDiff(const Option &O, StringRef V,
1796                                           const OptionValue<std::string> &D,
1797                                           size_t GlobalWidth) const {
1798   printOptionName(O, GlobalWidth);
1799   outs() << "= " << V;
1800   size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
1801   outs().indent(NumSpaces) << " (default: ";
1802   if (D.hasValue())
1803     outs() << D.getValue();
1804   else
1805     outs() << "*no default*";
1806   outs() << ")\n";
1807 }
1808 
1809 // Print a placeholder for options that don't yet support printOptionDiff().
1810 void basic_parser_impl::printOptionNoValue(const Option &O,
1811                                            size_t GlobalWidth) const {
1812   printOptionName(O, GlobalWidth);
1813   outs() << "= *cannot print option value*\n";
1814 }
1815 
1816 //===----------------------------------------------------------------------===//
1817 // -help and -help-hidden option implementation
1818 //
1819 
1820 static int OptNameCompare(const std::pair<const char *, Option *> *LHS,
1821                           const std::pair<const char *, Option *> *RHS) {
1822   return strcmp(LHS->first, RHS->first);
1823 }
1824 
1825 static int SubNameCompare(const std::pair<const char *, SubCommand *> *LHS,
1826                           const std::pair<const char *, SubCommand *> *RHS) {
1827   return strcmp(LHS->first, RHS->first);
1828 }
1829 
1830 // Copy Options into a vector so we can sort them as we like.
1831 static void sortOpts(StringMap<Option *> &OptMap,
1832                      SmallVectorImpl<std::pair<const char *, Option *>> &Opts,
1833                      bool ShowHidden) {
1834   SmallPtrSet<Option *, 32> OptionSet; // Duplicate option detection.
1835 
1836   for (StringMap<Option *>::iterator I = OptMap.begin(), E = OptMap.end();
1837        I != E; ++I) {
1838     // Ignore really-hidden options.
1839     if (I->second->getOptionHiddenFlag() == ReallyHidden)
1840       continue;
1841 
1842     // Unless showhidden is set, ignore hidden flags.
1843     if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
1844       continue;
1845 
1846     // If we've already seen this option, don't add it to the list again.
1847     if (!OptionSet.insert(I->second).second)
1848       continue;
1849 
1850     Opts.push_back(
1851         std::pair<const char *, Option *>(I->getKey().data(), I->second));
1852   }
1853 
1854   // Sort the options list alphabetically.
1855   array_pod_sort(Opts.begin(), Opts.end(), OptNameCompare);
1856 }
1857 
1858 static void
1859 sortSubCommands(const SmallPtrSetImpl<SubCommand *> &SubMap,
1860                 SmallVectorImpl<std::pair<const char *, SubCommand *>> &Subs) {
1861   for (const auto &S : SubMap) {
1862     if (S->getName().empty())
1863       continue;
1864     Subs.push_back(std::make_pair(S->getName().data(), S));
1865   }
1866   array_pod_sort(Subs.begin(), Subs.end(), SubNameCompare);
1867 }
1868 
1869 namespace {
1870 
1871 class HelpPrinter {
1872 protected:
1873   const bool ShowHidden;
1874   typedef SmallVector<std::pair<const char *, Option *>, 128>
1875       StrOptionPairVector;
1876   typedef SmallVector<std::pair<const char *, SubCommand *>, 128>
1877       StrSubCommandPairVector;
1878   // Print the options. Opts is assumed to be alphabetically sorted.
1879   virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1880     for (size_t i = 0, e = Opts.size(); i != e; ++i)
1881       Opts[i].second->printOptionInfo(MaxArgLen);
1882   }
1883 
1884   void printSubCommands(StrSubCommandPairVector &Subs, size_t MaxSubLen) {
1885     for (const auto &S : Subs) {
1886       outs() << "  " << S.first;
1887       if (!S.second->getDescription().empty()) {
1888         outs().indent(MaxSubLen - strlen(S.first));
1889         outs() << " - " << S.second->getDescription();
1890       }
1891       outs() << "\n";
1892     }
1893   }
1894 
1895 public:
1896   explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
1897   virtual ~HelpPrinter() {}
1898 
1899   // Invoke the printer.
1900   void operator=(bool Value) {
1901     if (!Value)
1902       return;
1903     printHelp();
1904 
1905     // Halt the program since help information was printed
1906     exit(0);
1907   }
1908 
1909   void printHelp() {
1910     SubCommand *Sub = GlobalParser->getActiveSubCommand();
1911     auto &OptionsMap = Sub->OptionsMap;
1912     auto &PositionalOpts = Sub->PositionalOpts;
1913     auto &ConsumeAfterOpt = Sub->ConsumeAfterOpt;
1914 
1915     StrOptionPairVector Opts;
1916     sortOpts(OptionsMap, Opts, ShowHidden);
1917 
1918     StrSubCommandPairVector Subs;
1919     sortSubCommands(GlobalParser->RegisteredSubCommands, Subs);
1920 
1921     if (!GlobalParser->ProgramOverview.empty())
1922       outs() << "OVERVIEW: " << GlobalParser->ProgramOverview << "\n";
1923 
1924     if (Sub == &*TopLevelSubCommand) {
1925       outs() << "USAGE: " << GlobalParser->ProgramName;
1926       if (Subs.size() > 2)
1927         outs() << " [subcommand]";
1928       outs() << " [options]";
1929     } else {
1930       if (!Sub->getDescription().empty()) {
1931         outs() << "SUBCOMMAND '" << Sub->getName()
1932                << "': " << Sub->getDescription() << "\n\n";
1933       }
1934       outs() << "USAGE: " << GlobalParser->ProgramName << " " << Sub->getName()
1935              << " [options]";
1936     }
1937 
1938     for (auto Opt : PositionalOpts) {
1939       if (Opt->hasArgStr())
1940         outs() << " --" << Opt->ArgStr;
1941       outs() << " " << Opt->HelpStr;
1942     }
1943 
1944     // Print the consume after option info if it exists...
1945     if (ConsumeAfterOpt)
1946       outs() << " " << ConsumeAfterOpt->HelpStr;
1947 
1948     if (Sub == &*TopLevelSubCommand && !Subs.empty()) {
1949       // Compute the maximum subcommand length...
1950       size_t MaxSubLen = 0;
1951       for (size_t i = 0, e = Subs.size(); i != e; ++i)
1952         MaxSubLen = std::max(MaxSubLen, strlen(Subs[i].first));
1953 
1954       outs() << "\n\n";
1955       outs() << "SUBCOMMANDS:\n\n";
1956       printSubCommands(Subs, MaxSubLen);
1957       outs() << "\n";
1958       outs() << "  Type \"" << GlobalParser->ProgramName
1959              << " <subcommand> -help\" to get more help on a specific "
1960                 "subcommand";
1961     }
1962 
1963     outs() << "\n\n";
1964 
1965     // Compute the maximum argument length...
1966     size_t MaxArgLen = 0;
1967     for (size_t i = 0, e = Opts.size(); i != e; ++i)
1968       MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1969 
1970     outs() << "OPTIONS:\n";
1971     printOptions(Opts, MaxArgLen);
1972 
1973     // Print any extra help the user has declared.
1974     for (auto I : GlobalParser->MoreHelp)
1975       outs() << I;
1976     GlobalParser->MoreHelp.clear();
1977   }
1978 };
1979 
1980 class CategorizedHelpPrinter : public HelpPrinter {
1981 public:
1982   explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
1983 
1984   // Helper function for printOptions().
1985   // It shall return a negative value if A's name should be lexicographically
1986   // ordered before B's name. It returns a value greater than zero if B's name
1987   // should be ordered before A's name, and it returns 0 otherwise.
1988   static int OptionCategoryCompare(OptionCategory *const *A,
1989                                    OptionCategory *const *B) {
1990     return (*A)->getName().compare((*B)->getName());
1991   }
1992 
1993   // Make sure we inherit our base class's operator=()
1994   using HelpPrinter::operator=;
1995 
1996 protected:
1997   void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override {
1998     std::vector<OptionCategory *> SortedCategories;
1999     std::map<OptionCategory *, std::vector<Option *>> CategorizedOptions;
2000 
2001     // Collect registered option categories into vector in preparation for
2002     // sorting.
2003     for (auto I = GlobalParser->RegisteredOptionCategories.begin(),
2004               E = GlobalParser->RegisteredOptionCategories.end();
2005          I != E; ++I) {
2006       SortedCategories.push_back(*I);
2007     }
2008 
2009     // Sort the different option categories alphabetically.
2010     assert(SortedCategories.size() > 0 && "No option categories registered!");
2011     array_pod_sort(SortedCategories.begin(), SortedCategories.end(),
2012                    OptionCategoryCompare);
2013 
2014     // Create map to empty vectors.
2015     for (std::vector<OptionCategory *>::const_iterator
2016              I = SortedCategories.begin(),
2017              E = SortedCategories.end();
2018          I != E; ++I)
2019       CategorizedOptions[*I] = std::vector<Option *>();
2020 
2021     // Walk through pre-sorted options and assign into categories.
2022     // Because the options are already alphabetically sorted the
2023     // options within categories will also be alphabetically sorted.
2024     for (size_t I = 0, E = Opts.size(); I != E; ++I) {
2025       Option *Opt = Opts[I].second;
2026       assert(CategorizedOptions.count(Opt->Category) > 0 &&
2027              "Option has an unregistered category");
2028       CategorizedOptions[Opt->Category].push_back(Opt);
2029     }
2030 
2031     // Now do printing.
2032     for (std::vector<OptionCategory *>::const_iterator
2033              Category = SortedCategories.begin(),
2034              E = SortedCategories.end();
2035          Category != E; ++Category) {
2036       // Hide empty categories for -help, but show for -help-hidden.
2037       const auto &CategoryOptions = CategorizedOptions[*Category];
2038       bool IsEmptyCategory = CategoryOptions.empty();
2039       if (!ShowHidden && IsEmptyCategory)
2040         continue;
2041 
2042       // Print category information.
2043       outs() << "\n";
2044       outs() << (*Category)->getName() << ":\n";
2045 
2046       // Check if description is set.
2047       if (!(*Category)->getDescription().empty())
2048         outs() << (*Category)->getDescription() << "\n\n";
2049       else
2050         outs() << "\n";
2051 
2052       // When using -help-hidden explicitly state if the category has no
2053       // options associated with it.
2054       if (IsEmptyCategory) {
2055         outs() << "  This option category has no options.\n";
2056         continue;
2057       }
2058       // Loop over the options in the category and print.
2059       for (const Option *Opt : CategoryOptions)
2060         Opt->printOptionInfo(MaxArgLen);
2061     }
2062   }
2063 };
2064 
2065 // This wraps the Uncategorizing and Categorizing printers and decides
2066 // at run time which should be invoked.
2067 class HelpPrinterWrapper {
2068 private:
2069   HelpPrinter &UncategorizedPrinter;
2070   CategorizedHelpPrinter &CategorizedPrinter;
2071 
2072 public:
2073   explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
2074                               CategorizedHelpPrinter &CategorizedPrinter)
2075       : UncategorizedPrinter(UncategorizedPrinter),
2076         CategorizedPrinter(CategorizedPrinter) {}
2077 
2078   // Invoke the printer.
2079   void operator=(bool Value);
2080 };
2081 
2082 } // End anonymous namespace
2083 
2084 // Declare the four HelpPrinter instances that are used to print out help, or
2085 // help-hidden as an uncategorized list or in categories.
2086 static HelpPrinter UncategorizedNormalPrinter(false);
2087 static HelpPrinter UncategorizedHiddenPrinter(true);
2088 static CategorizedHelpPrinter CategorizedNormalPrinter(false);
2089 static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
2090 
2091 // Declare HelpPrinter wrappers that will decide whether or not to invoke
2092 // a categorizing help printer
2093 static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
2094                                                CategorizedNormalPrinter);
2095 static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
2096                                                CategorizedHiddenPrinter);
2097 
2098 // Define a category for generic options that all tools should have.
2099 static cl::OptionCategory GenericCategory("Generic Options");
2100 
2101 // Define uncategorized help printers.
2102 // -help-list is hidden by default because if Option categories are being used
2103 // then -help behaves the same as -help-list.
2104 static cl::opt<HelpPrinter, true, parser<bool>> HLOp(
2105     "help-list",
2106     cl::desc("Display list of available options (-help-list-hidden for more)"),
2107     cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed,
2108     cl::cat(GenericCategory), cl::sub(*AllSubCommands));
2109 
2110 static cl::opt<HelpPrinter, true, parser<bool>>
2111     HLHOp("help-list-hidden", cl::desc("Display list of all available options"),
2112           cl::location(UncategorizedHiddenPrinter), cl::Hidden,
2113           cl::ValueDisallowed, cl::cat(GenericCategory),
2114           cl::sub(*AllSubCommands));
2115 
2116 // Define uncategorized/categorized help printers. These printers change their
2117 // behaviour at runtime depending on whether one or more Option categories have
2118 // been declared.
2119 static cl::opt<HelpPrinterWrapper, true, parser<bool>>
2120     HOp("help", cl::desc("Display available options (-help-hidden for more)"),
2121         cl::location(WrappedNormalPrinter), cl::ValueDisallowed,
2122         cl::cat(GenericCategory), cl::sub(*AllSubCommands));
2123 
2124 static cl::opt<HelpPrinterWrapper, true, parser<bool>>
2125     HHOp("help-hidden", cl::desc("Display all available options"),
2126          cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed,
2127          cl::cat(GenericCategory), cl::sub(*AllSubCommands));
2128 
2129 static cl::opt<bool> PrintOptions(
2130     "print-options",
2131     cl::desc("Print non-default options after command line parsing"),
2132     cl::Hidden, cl::init(false), cl::cat(GenericCategory),
2133     cl::sub(*AllSubCommands));
2134 
2135 static cl::opt<bool> PrintAllOptions(
2136     "print-all-options",
2137     cl::desc("Print all option values after command line parsing"), cl::Hidden,
2138     cl::init(false), cl::cat(GenericCategory), cl::sub(*AllSubCommands));
2139 
2140 void HelpPrinterWrapper::operator=(bool Value) {
2141   if (!Value)
2142     return;
2143 
2144   // Decide which printer to invoke. If more than one option category is
2145   // registered then it is useful to show the categorized help instead of
2146   // uncategorized help.
2147   if (GlobalParser->RegisteredOptionCategories.size() > 1) {
2148     // unhide -help-list option so user can have uncategorized output if they
2149     // want it.
2150     HLOp.setHiddenFlag(NotHidden);
2151 
2152     CategorizedPrinter = true; // Invoke categorized printer
2153   } else
2154     UncategorizedPrinter = true; // Invoke uncategorized printer
2155 }
2156 
2157 // Print the value of each option.
2158 void cl::PrintOptionValues() { GlobalParser->printOptionValues(); }
2159 
2160 void CommandLineParser::printOptionValues() {
2161   if (!PrintOptions && !PrintAllOptions)
2162     return;
2163 
2164   SmallVector<std::pair<const char *, Option *>, 128> Opts;
2165   sortOpts(ActiveSubCommand->OptionsMap, Opts, /*ShowHidden*/ true);
2166 
2167   // Compute the maximum argument length...
2168   size_t MaxArgLen = 0;
2169   for (size_t i = 0, e = Opts.size(); i != e; ++i)
2170     MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
2171 
2172   for (size_t i = 0, e = Opts.size(); i != e; ++i)
2173     Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
2174 }
2175 
2176 static VersionPrinterTy OverrideVersionPrinter = nullptr;
2177 
2178 static std::vector<VersionPrinterTy> *ExtraVersionPrinters = nullptr;
2179 
2180 namespace {
2181 class VersionPrinter {
2182 public:
2183   void print() {
2184     raw_ostream &OS = outs();
2185 #ifdef PACKAGE_VENDOR
2186     OS << PACKAGE_VENDOR << " ";
2187 #else
2188     OS << "LLVM (http://llvm.org/):\n  ";
2189 #endif
2190     OS << PACKAGE_NAME << " version " << PACKAGE_VERSION;
2191 #ifdef LLVM_VERSION_INFO
2192     OS << " " << LLVM_VERSION_INFO;
2193 #endif
2194     OS << "\n  ";
2195 #ifndef __OPTIMIZE__
2196     OS << "DEBUG build";
2197 #else
2198     OS << "Optimized build";
2199 #endif
2200 #ifndef NDEBUG
2201     OS << " with assertions";
2202 #endif
2203 #if LLVM_VERSION_PRINTER_SHOW_HOST_TARGET_INFO
2204     std::string CPU = sys::getHostCPUName();
2205     if (CPU == "generic")
2206       CPU = "(unknown)";
2207     OS << ".\n"
2208        << "  Default target: " << sys::getDefaultTargetTriple() << '\n'
2209        << "  Host CPU: " << CPU;
2210 #endif
2211     OS << '\n';
2212   }
2213   void operator=(bool OptionWasSpecified) {
2214     if (!OptionWasSpecified)
2215       return;
2216 
2217     if (OverrideVersionPrinter != nullptr) {
2218       OverrideVersionPrinter(outs());
2219       exit(0);
2220     }
2221     print();
2222 
2223     // Iterate over any registered extra printers and call them to add further
2224     // information.
2225     if (ExtraVersionPrinters != nullptr) {
2226       outs() << '\n';
2227       for (auto I : *ExtraVersionPrinters)
2228         I(outs());
2229     }
2230 
2231     exit(0);
2232   }
2233 };
2234 } // End anonymous namespace
2235 
2236 // Define the --version option that prints out the LLVM version for the tool
2237 static VersionPrinter VersionPrinterInstance;
2238 
2239 static cl::opt<VersionPrinter, true, parser<bool>>
2240     VersOp("version", cl::desc("Display the version of this program"),
2241            cl::location(VersionPrinterInstance), cl::ValueDisallowed,
2242            cl::cat(GenericCategory));
2243 
2244 // Utility function for printing the help message.
2245 void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
2246   if (!Hidden && !Categorized)
2247     UncategorizedNormalPrinter.printHelp();
2248   else if (!Hidden && Categorized)
2249     CategorizedNormalPrinter.printHelp();
2250   else if (Hidden && !Categorized)
2251     UncategorizedHiddenPrinter.printHelp();
2252   else
2253     CategorizedHiddenPrinter.printHelp();
2254 }
2255 
2256 /// Utility function for printing version number.
2257 void cl::PrintVersionMessage() { VersionPrinterInstance.print(); }
2258 
2259 void cl::SetVersionPrinter(VersionPrinterTy func) { OverrideVersionPrinter = func; }
2260 
2261 void cl::AddExtraVersionPrinter(VersionPrinterTy func) {
2262   if (!ExtraVersionPrinters)
2263     ExtraVersionPrinters = new std::vector<VersionPrinterTy>;
2264 
2265   ExtraVersionPrinters->push_back(func);
2266 }
2267 
2268 StringMap<Option *> &cl::getRegisteredOptions(SubCommand &Sub) {
2269   auto &Subs = GlobalParser->RegisteredSubCommands;
2270   (void)Subs;
2271   assert(is_contained(Subs, &Sub));
2272   return Sub.OptionsMap;
2273 }
2274 
2275 iterator_range<typename SmallPtrSet<SubCommand *, 4>::iterator>
2276 cl::getRegisteredSubcommands() {
2277   return GlobalParser->getRegisteredSubcommands();
2278 }
2279 
2280 void cl::HideUnrelatedOptions(cl::OptionCategory &Category, SubCommand &Sub) {
2281   for (auto &I : Sub.OptionsMap) {
2282     if (I.second->Category != &Category &&
2283         I.second->Category != &GenericCategory)
2284       I.second->setHiddenFlag(cl::ReallyHidden);
2285   }
2286 }
2287 
2288 void cl::HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories,
2289                               SubCommand &Sub) {
2290   auto CategoriesBegin = Categories.begin();
2291   auto CategoriesEnd = Categories.end();
2292   for (auto &I : Sub.OptionsMap) {
2293     if (std::find(CategoriesBegin, CategoriesEnd, I.second->Category) ==
2294             CategoriesEnd &&
2295         I.second->Category != &GenericCategory)
2296       I.second->setHiddenFlag(cl::ReallyHidden);
2297   }
2298 }
2299 
2300 void cl::ResetCommandLineParser() { GlobalParser->reset(); }
2301 void cl::ResetAllOptionOccurrences() {
2302   GlobalParser->ResetAllOptionOccurrences();
2303 }
2304 
2305 void LLVMParseCommandLineOptions(int argc, const char *const *argv,
2306                                  const char *Overview) {
2307   llvm::cl::ParseCommandLineOptions(argc, argv, StringRef(Overview),
2308                                     &llvm::nulls());
2309 }
2310