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