xref: /llvm-project/llvm/lib/Support/CommandLine.cpp (revision ec4fb5ba9736c1910b8a1631c46d653172e5a4df)
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   StringRef ProgramOverview;
96 
97   // This collects additional help to be printed.
98   std::vector<StringRef> 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() : ActiveSubCommand(nullptr) {
107     registerSubCommand(&*TopLevelSubCommand);
108     registerSubCommand(&*AllSubCommands);
109   }
110 
111   void ResetAllOptionOccurrences();
112 
113   bool ParseCommandLineOptions(int argc, const char *const *argv,
114                                StringRef Overview, bool IgnoreErrors);
115 
116   void addLiteralOption(Option &Opt, SubCommand *SC, StringRef 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, StringRef 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().empty()) &&
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());
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 = StringRef();
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(StringRef Name);
334 };
335 
336 } // namespace
337 
338 static ManagedStatic<CommandLineParser> GlobalParser;
339 
340 void cl::AddLiteralOption(Option &O, StringRef Name) {
341   GlobalParser->addLiteralOption(O, Name);
342 }
343 
344 extrahelp::extrahelp(StringRef 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(StringRef Name) {
432   if (Name.empty())
433     return &*TopLevelSubCommand;
434   for (auto S : RegisteredSubCommands) {
435     if (S == &*AllSubCommands)
436       continue;
437     if (S->getName().empty())
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 = StringRef(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 = StringRef(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(StringRef(Token)).data());
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(StringRef(Token)).data());
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(StringRef(Token)).data());
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(StringRef(Token)).data());
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(StringRef(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).data());
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], StringRef(Overview));
972 }
973 
974 bool cl::ParseCommandLineOptions(int argc, const char *const *argv,
975                                  StringRef 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                                                 StringRef 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(StringRef(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(StringRef(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, StringRef(argv[i]), i);
1102         continue; // We are done!
1103       }
1104 
1105       if (!PositionalOpts.empty()) {
1106         PositionalVals.push_back(std::make_pair(StringRef(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(StringRef(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 = StringRef(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, StringRef(argv[i]), i);
1137         continue; // We are done!
1138       }
1139 
1140     } else { // We start with a '-', must be an argument.
1141       ArgName = StringRef(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, "", StringRef(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   auto ValName = getValueName();
1393   if (!ValName.empty())
1394     Len += getValueStr(O, ValName).size() + 3;
1395 
1396   return Len + 6;
1397 }
1398 
1399 // printOptionInfo - Print out information about this option.  The
1400 // to-be-maintained width is specified.
1401 //
1402 void basic_parser_impl::printOptionInfo(const Option &O,
1403                                         size_t GlobalWidth) const {
1404   outs() << "  -" << O.ArgStr;
1405 
1406   auto ValName = getValueName();
1407   if (!ValName.empty())
1408     outs() << "=<" << getValueStr(O, ValName) << '>';
1409 
1410   printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
1411 }
1412 
1413 void basic_parser_impl::printOptionName(const Option &O,
1414                                         size_t GlobalWidth) const {
1415   outs() << "  -" << O.ArgStr;
1416   outs().indent(GlobalWidth - O.ArgStr.size());
1417 }
1418 
1419 // parser<bool> implementation
1420 //
1421 bool parser<bool>::parse(Option &O, StringRef ArgName, StringRef Arg,
1422                          bool &Value) {
1423   if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1424       Arg == "1") {
1425     Value = true;
1426     return false;
1427   }
1428 
1429   if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1430     Value = false;
1431     return false;
1432   }
1433   return O.error("'" + Arg +
1434                  "' is invalid value for boolean argument! Try 0 or 1");
1435 }
1436 
1437 // parser<boolOrDefault> implementation
1438 //
1439 bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName, StringRef Arg,
1440                                   boolOrDefault &Value) {
1441   if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1442       Arg == "1") {
1443     Value = BOU_TRUE;
1444     return false;
1445   }
1446   if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1447     Value = BOU_FALSE;
1448     return false;
1449   }
1450 
1451   return O.error("'" + Arg +
1452                  "' is invalid value for boolean argument! Try 0 or 1");
1453 }
1454 
1455 // parser<int> implementation
1456 //
1457 bool parser<int>::parse(Option &O, StringRef ArgName, StringRef Arg,
1458                         int &Value) {
1459   if (Arg.getAsInteger(0, Value))
1460     return O.error("'" + Arg + "' value invalid for integer argument!");
1461   return false;
1462 }
1463 
1464 // parser<unsigned> implementation
1465 //
1466 bool parser<unsigned>::parse(Option &O, StringRef ArgName, StringRef Arg,
1467                              unsigned &Value) {
1468 
1469   if (Arg.getAsInteger(0, Value))
1470     return O.error("'" + Arg + "' value invalid for uint argument!");
1471   return false;
1472 }
1473 
1474 // parser<unsigned long long> implementation
1475 //
1476 bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
1477                                        StringRef Arg,
1478                                        unsigned long long &Value) {
1479 
1480   if (Arg.getAsInteger(0, Value))
1481     return O.error("'" + Arg + "' value invalid for uint argument!");
1482   return false;
1483 }
1484 
1485 // parser<double>/parser<float> implementation
1486 //
1487 static bool parseDouble(Option &O, StringRef Arg, double &Value) {
1488   SmallString<32> TmpStr(Arg.begin(), Arg.end());
1489   const char *ArgStart = TmpStr.c_str();
1490   char *End;
1491   Value = strtod(ArgStart, &End);
1492   if (*End != 0)
1493     return O.error("'" + Arg + "' value invalid for floating point argument!");
1494   return false;
1495 }
1496 
1497 bool parser<double>::parse(Option &O, StringRef ArgName, StringRef Arg,
1498                            double &Val) {
1499   return parseDouble(O, Arg, Val);
1500 }
1501 
1502 bool parser<float>::parse(Option &O, StringRef ArgName, StringRef Arg,
1503                           float &Val) {
1504   double dVal;
1505   if (parseDouble(O, Arg, dVal))
1506     return true;
1507   Val = (float)dVal;
1508   return false;
1509 }
1510 
1511 // generic_parser_base implementation
1512 //
1513 
1514 // findOption - Return the option number corresponding to the specified
1515 // argument string.  If the option is not found, getNumOptions() is returned.
1516 //
1517 unsigned generic_parser_base::findOption(StringRef Name) {
1518   unsigned e = getNumOptions();
1519 
1520   for (unsigned i = 0; i != e; ++i) {
1521     if (getOption(i) == Name)
1522       return i;
1523   }
1524   return e;
1525 }
1526 
1527 // Return the width of the option tag for printing...
1528 size_t generic_parser_base::getOptionWidth(const Option &O) const {
1529   if (O.hasArgStr()) {
1530     size_t Size = O.ArgStr.size() + 6;
1531     for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1532       Size = std::max(Size, getOption(i).size() + 8);
1533     return Size;
1534   } else {
1535     size_t BaseSize = 0;
1536     for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1537       BaseSize = std::max(BaseSize, getOption(i).size() + 8);
1538     return BaseSize;
1539   }
1540 }
1541 
1542 // printOptionInfo - Print out information about this option.  The
1543 // to-be-maintained width is specified.
1544 //
1545 void generic_parser_base::printOptionInfo(const Option &O,
1546                                           size_t GlobalWidth) const {
1547   if (O.hasArgStr()) {
1548     outs() << "  -" << O.ArgStr;
1549     printHelpStr(O.HelpStr, GlobalWidth, O.ArgStr.size() + 6);
1550 
1551     for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1552       size_t NumSpaces = GlobalWidth - getOption(i).size() - 8;
1553       outs() << "    =" << getOption(i);
1554       outs().indent(NumSpaces) << " -   " << getDescription(i) << '\n';
1555     }
1556   } else {
1557     if (!O.HelpStr.empty())
1558       outs() << "  " << O.HelpStr << '\n';
1559     for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1560       auto Option = getOption(i);
1561       outs() << "    -" << Option;
1562       printHelpStr(getDescription(i), GlobalWidth, Option.size() + 8);
1563     }
1564   }
1565 }
1566 
1567 static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1568 
1569 // printGenericOptionDiff - Print the value of this option and it's default.
1570 //
1571 // "Generic" options have each value mapped to a name.
1572 void generic_parser_base::printGenericOptionDiff(
1573     const Option &O, const GenericOptionValue &Value,
1574     const GenericOptionValue &Default, size_t GlobalWidth) const {
1575   outs() << "  -" << O.ArgStr;
1576   outs().indent(GlobalWidth - O.ArgStr.size());
1577 
1578   unsigned NumOpts = getNumOptions();
1579   for (unsigned i = 0; i != NumOpts; ++i) {
1580     if (Value.compare(getOptionValue(i)))
1581       continue;
1582 
1583     outs() << "= " << getOption(i);
1584     size_t L = getOption(i).size();
1585     size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1586     outs().indent(NumSpaces) << " (default: ";
1587     for (unsigned j = 0; j != NumOpts; ++j) {
1588       if (Default.compare(getOptionValue(j)))
1589         continue;
1590       outs() << getOption(j);
1591       break;
1592     }
1593     outs() << ")\n";
1594     return;
1595   }
1596   outs() << "= *unknown option value*\n";
1597 }
1598 
1599 // printOptionDiff - Specializations for printing basic value types.
1600 //
1601 #define PRINT_OPT_DIFF(T)                                                      \
1602   void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D,      \
1603                                   size_t GlobalWidth) const {                  \
1604     printOptionName(O, GlobalWidth);                                           \
1605     std::string Str;                                                           \
1606     {                                                                          \
1607       raw_string_ostream SS(Str);                                              \
1608       SS << V;                                                                 \
1609     }                                                                          \
1610     outs() << "= " << Str;                                                     \
1611     size_t NumSpaces =                                                         \
1612         MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0;               \
1613     outs().indent(NumSpaces) << " (default: ";                                 \
1614     if (D.hasValue())                                                          \
1615       outs() << D.getValue();                                                  \
1616     else                                                                       \
1617       outs() << "*no default*";                                                \
1618     outs() << ")\n";                                                           \
1619   }
1620 
1621 PRINT_OPT_DIFF(bool)
1622 PRINT_OPT_DIFF(boolOrDefault)
1623 PRINT_OPT_DIFF(int)
1624 PRINT_OPT_DIFF(unsigned)
1625 PRINT_OPT_DIFF(unsigned long long)
1626 PRINT_OPT_DIFF(double)
1627 PRINT_OPT_DIFF(float)
1628 PRINT_OPT_DIFF(char)
1629 
1630 void parser<std::string>::printOptionDiff(const Option &O, StringRef V,
1631                                           const OptionValue<std::string> &D,
1632                                           size_t GlobalWidth) const {
1633   printOptionName(O, GlobalWidth);
1634   outs() << "= " << V;
1635   size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
1636   outs().indent(NumSpaces) << " (default: ";
1637   if (D.hasValue())
1638     outs() << D.getValue();
1639   else
1640     outs() << "*no default*";
1641   outs() << ")\n";
1642 }
1643 
1644 // Print a placeholder for options that don't yet support printOptionDiff().
1645 void basic_parser_impl::printOptionNoValue(const Option &O,
1646                                            size_t GlobalWidth) const {
1647   printOptionName(O, GlobalWidth);
1648   outs() << "= *cannot print option value*\n";
1649 }
1650 
1651 //===----------------------------------------------------------------------===//
1652 // -help and -help-hidden option implementation
1653 //
1654 
1655 static int OptNameCompare(const std::pair<const char *, Option *> *LHS,
1656                           const std::pair<const char *, Option *> *RHS) {
1657   return strcmp(LHS->first, RHS->first);
1658 }
1659 
1660 static int SubNameCompare(const std::pair<const char *, SubCommand *> *LHS,
1661                           const std::pair<const char *, SubCommand *> *RHS) {
1662   return strcmp(LHS->first, RHS->first);
1663 }
1664 
1665 // Copy Options into a vector so we can sort them as we like.
1666 static void sortOpts(StringMap<Option *> &OptMap,
1667                      SmallVectorImpl<std::pair<const char *, Option *>> &Opts,
1668                      bool ShowHidden) {
1669   SmallPtrSet<Option *, 32> OptionSet; // Duplicate option detection.
1670 
1671   for (StringMap<Option *>::iterator I = OptMap.begin(), E = OptMap.end();
1672        I != E; ++I) {
1673     // Ignore really-hidden options.
1674     if (I->second->getOptionHiddenFlag() == ReallyHidden)
1675       continue;
1676 
1677     // Unless showhidden is set, ignore hidden flags.
1678     if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
1679       continue;
1680 
1681     // If we've already seen this option, don't add it to the list again.
1682     if (!OptionSet.insert(I->second).second)
1683       continue;
1684 
1685     Opts.push_back(
1686         std::pair<const char *, Option *>(I->getKey().data(), I->second));
1687   }
1688 
1689   // Sort the options list alphabetically.
1690   array_pod_sort(Opts.begin(), Opts.end(), OptNameCompare);
1691 }
1692 
1693 static void
1694 sortSubCommands(const SmallPtrSetImpl<SubCommand *> &SubMap,
1695                 SmallVectorImpl<std::pair<const char *, SubCommand *>> &Subs) {
1696   for (const auto &S : SubMap) {
1697     if (S->getName().empty())
1698       continue;
1699     Subs.push_back(std::make_pair(S->getName().data(), S));
1700   }
1701   array_pod_sort(Subs.begin(), Subs.end(), SubNameCompare);
1702 }
1703 
1704 namespace {
1705 
1706 class HelpPrinter {
1707 protected:
1708   const bool ShowHidden;
1709   typedef SmallVector<std::pair<const char *, Option *>, 128>
1710       StrOptionPairVector;
1711   typedef SmallVector<std::pair<const char *, SubCommand *>, 128>
1712       StrSubCommandPairVector;
1713   // Print the options. Opts is assumed to be alphabetically sorted.
1714   virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1715     for (size_t i = 0, e = Opts.size(); i != e; ++i)
1716       Opts[i].second->printOptionInfo(MaxArgLen);
1717   }
1718 
1719   void printSubCommands(StrSubCommandPairVector &Subs, size_t MaxSubLen) {
1720     for (const auto &S : Subs) {
1721       outs() << "  " << S.first;
1722       if (!S.second->getDescription().empty()) {
1723         outs().indent(MaxSubLen - strlen(S.first));
1724         outs() << " - " << S.second->getDescription();
1725       }
1726       outs() << "\n";
1727     }
1728   }
1729 
1730 public:
1731   explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
1732   virtual ~HelpPrinter() {}
1733 
1734   // Invoke the printer.
1735   void operator=(bool Value) {
1736     if (!Value)
1737       return;
1738 
1739     SubCommand *Sub = GlobalParser->getActiveSubCommand();
1740     auto &OptionsMap = Sub->OptionsMap;
1741     auto &PositionalOpts = Sub->PositionalOpts;
1742     auto &ConsumeAfterOpt = Sub->ConsumeAfterOpt;
1743 
1744     StrOptionPairVector Opts;
1745     sortOpts(OptionsMap, Opts, ShowHidden);
1746 
1747     StrSubCommandPairVector Subs;
1748     sortSubCommands(GlobalParser->RegisteredSubCommands, Subs);
1749 
1750     if (!GlobalParser->ProgramOverview.empty())
1751       outs() << "OVERVIEW: " << GlobalParser->ProgramOverview << "\n";
1752 
1753     if (Sub == &*TopLevelSubCommand)
1754       outs() << "USAGE: " << GlobalParser->ProgramName
1755              << " [subcommand] [options]";
1756     else {
1757       if (!Sub->getDescription().empty()) {
1758         outs() << "SUBCOMMAND '" << Sub->getName()
1759                << "': " << Sub->getDescription() << "\n\n";
1760       }
1761       outs() << "USAGE: " << GlobalParser->ProgramName << " " << Sub->getName()
1762              << " [options]";
1763     }
1764 
1765     for (auto Opt : PositionalOpts) {
1766       if (Opt->hasArgStr())
1767         outs() << " --" << Opt->ArgStr;
1768       outs() << " " << Opt->HelpStr;
1769     }
1770 
1771     // Print the consume after option info if it exists...
1772     if (ConsumeAfterOpt)
1773       outs() << " " << ConsumeAfterOpt->HelpStr;
1774 
1775     if (Sub == &*TopLevelSubCommand && Subs.size() > 2) {
1776       // Compute the maximum subcommand length...
1777       size_t MaxSubLen = 0;
1778       for (size_t i = 0, e = Subs.size(); i != e; ++i)
1779         MaxSubLen = std::max(MaxSubLen, strlen(Subs[i].first));
1780 
1781       outs() << "\n\n";
1782       outs() << "SUBCOMMANDS:\n\n";
1783       printSubCommands(Subs, MaxSubLen);
1784       outs() << "\n";
1785       outs() << "  Type \"" << GlobalParser->ProgramName
1786              << " <subcommand> -help\" to get more help on a specific "
1787                 "subcommand";
1788     }
1789 
1790     outs() << "\n\n";
1791 
1792     // Compute the maximum argument length...
1793     size_t MaxArgLen = 0;
1794     for (size_t i = 0, e = Opts.size(); i != e; ++i)
1795       MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1796 
1797     outs() << "OPTIONS:\n";
1798     printOptions(Opts, MaxArgLen);
1799 
1800     // Print any extra help the user has declared.
1801     for (auto I : GlobalParser->MoreHelp)
1802       outs() << I;
1803     GlobalParser->MoreHelp.clear();
1804 
1805     // Halt the program since help information was printed
1806     exit(0);
1807   }
1808 };
1809 
1810 class CategorizedHelpPrinter : public HelpPrinter {
1811 public:
1812   explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
1813 
1814   // Helper function for printOptions().
1815   // It shall return a negative value if A's name should be lexicographically
1816   // ordered before B's name. It returns a value greater equal zero otherwise.
1817   static int OptionCategoryCompare(OptionCategory *const *A,
1818                                    OptionCategory *const *B) {
1819     return (*A)->getName() == (*B)->getName();
1820   }
1821 
1822   // Make sure we inherit our base class's operator=()
1823   using HelpPrinter::operator=;
1824 
1825 protected:
1826   void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override {
1827     std::vector<OptionCategory *> SortedCategories;
1828     std::map<OptionCategory *, std::vector<Option *>> CategorizedOptions;
1829 
1830     // Collect registered option categories into vector in preparation for
1831     // sorting.
1832     for (auto I = GlobalParser->RegisteredOptionCategories.begin(),
1833               E = GlobalParser->RegisteredOptionCategories.end();
1834          I != E; ++I) {
1835       SortedCategories.push_back(*I);
1836     }
1837 
1838     // Sort the different option categories alphabetically.
1839     assert(SortedCategories.size() > 0 && "No option categories registered!");
1840     array_pod_sort(SortedCategories.begin(), SortedCategories.end(),
1841                    OptionCategoryCompare);
1842 
1843     // Create map to empty vectors.
1844     for (std::vector<OptionCategory *>::const_iterator
1845              I = SortedCategories.begin(),
1846              E = SortedCategories.end();
1847          I != E; ++I)
1848       CategorizedOptions[*I] = std::vector<Option *>();
1849 
1850     // Walk through pre-sorted options and assign into categories.
1851     // Because the options are already alphabetically sorted the
1852     // options within categories will also be alphabetically sorted.
1853     for (size_t I = 0, E = Opts.size(); I != E; ++I) {
1854       Option *Opt = Opts[I].second;
1855       assert(CategorizedOptions.count(Opt->Category) > 0 &&
1856              "Option has an unregistered category");
1857       CategorizedOptions[Opt->Category].push_back(Opt);
1858     }
1859 
1860     // Now do printing.
1861     for (std::vector<OptionCategory *>::const_iterator
1862              Category = SortedCategories.begin(),
1863              E = SortedCategories.end();
1864          Category != E; ++Category) {
1865       // Hide empty categories for -help, but show for -help-hidden.
1866       const auto &CategoryOptions = CategorizedOptions[*Category];
1867       bool IsEmptyCategory = CategoryOptions.empty();
1868       if (!ShowHidden && IsEmptyCategory)
1869         continue;
1870 
1871       // Print category information.
1872       outs() << "\n";
1873       outs() << (*Category)->getName() << ":\n";
1874 
1875       // Check if description is set.
1876       if (!(*Category)->getDescription().empty())
1877         outs() << (*Category)->getDescription() << "\n\n";
1878       else
1879         outs() << "\n";
1880 
1881       // When using -help-hidden explicitly state if the category has no
1882       // options associated with it.
1883       if (IsEmptyCategory) {
1884         outs() << "  This option category has no options.\n";
1885         continue;
1886       }
1887       // Loop over the options in the category and print.
1888       for (const Option *Opt : CategoryOptions)
1889         Opt->printOptionInfo(MaxArgLen);
1890     }
1891   }
1892 };
1893 
1894 // This wraps the Uncategorizing and Categorizing printers and decides
1895 // at run time which should be invoked.
1896 class HelpPrinterWrapper {
1897 private:
1898   HelpPrinter &UncategorizedPrinter;
1899   CategorizedHelpPrinter &CategorizedPrinter;
1900 
1901 public:
1902   explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
1903                               CategorizedHelpPrinter &CategorizedPrinter)
1904       : UncategorizedPrinter(UncategorizedPrinter),
1905         CategorizedPrinter(CategorizedPrinter) {}
1906 
1907   // Invoke the printer.
1908   void operator=(bool Value);
1909 };
1910 
1911 } // End anonymous namespace
1912 
1913 // Declare the four HelpPrinter instances that are used to print out help, or
1914 // help-hidden as an uncategorized list or in categories.
1915 static HelpPrinter UncategorizedNormalPrinter(false);
1916 static HelpPrinter UncategorizedHiddenPrinter(true);
1917 static CategorizedHelpPrinter CategorizedNormalPrinter(false);
1918 static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
1919 
1920 // Declare HelpPrinter wrappers that will decide whether or not to invoke
1921 // a categorizing help printer
1922 static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
1923                                                CategorizedNormalPrinter);
1924 static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
1925                                                CategorizedHiddenPrinter);
1926 
1927 // Define a category for generic options that all tools should have.
1928 static cl::OptionCategory GenericCategory("Generic Options");
1929 
1930 // Define uncategorized help printers.
1931 // -help-list is hidden by default because if Option categories are being used
1932 // then -help behaves the same as -help-list.
1933 static cl::opt<HelpPrinter, true, parser<bool>> HLOp(
1934     "help-list",
1935     cl::desc("Display list of available options (-help-list-hidden for more)"),
1936     cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed,
1937     cl::cat(GenericCategory), cl::sub(*AllSubCommands));
1938 
1939 static cl::opt<HelpPrinter, true, parser<bool>>
1940     HLHOp("help-list-hidden", cl::desc("Display list of all available options"),
1941           cl::location(UncategorizedHiddenPrinter), cl::Hidden,
1942           cl::ValueDisallowed, cl::cat(GenericCategory),
1943           cl::sub(*AllSubCommands));
1944 
1945 // Define uncategorized/categorized help printers. These printers change their
1946 // behaviour at runtime depending on whether one or more Option categories have
1947 // been declared.
1948 static cl::opt<HelpPrinterWrapper, true, parser<bool>>
1949     HOp("help", cl::desc("Display available options (-help-hidden for more)"),
1950         cl::location(WrappedNormalPrinter), cl::ValueDisallowed,
1951         cl::cat(GenericCategory), cl::sub(*AllSubCommands));
1952 
1953 static cl::opt<HelpPrinterWrapper, true, parser<bool>>
1954     HHOp("help-hidden", cl::desc("Display all available options"),
1955          cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed,
1956          cl::cat(GenericCategory), cl::sub(*AllSubCommands));
1957 
1958 static cl::opt<bool> PrintOptions(
1959     "print-options",
1960     cl::desc("Print non-default options after command line parsing"),
1961     cl::Hidden, cl::init(false), cl::cat(GenericCategory),
1962     cl::sub(*AllSubCommands));
1963 
1964 static cl::opt<bool> PrintAllOptions(
1965     "print-all-options",
1966     cl::desc("Print all option values after command line parsing"), cl::Hidden,
1967     cl::init(false), cl::cat(GenericCategory), cl::sub(*AllSubCommands));
1968 
1969 void HelpPrinterWrapper::operator=(bool Value) {
1970   if (!Value)
1971     return;
1972 
1973   // Decide which printer to invoke. If more than one option category is
1974   // registered then it is useful to show the categorized help instead of
1975   // uncategorized help.
1976   if (GlobalParser->RegisteredOptionCategories.size() > 1) {
1977     // unhide -help-list option so user can have uncategorized output if they
1978     // want it.
1979     HLOp.setHiddenFlag(NotHidden);
1980 
1981     CategorizedPrinter = true; // Invoke categorized printer
1982   } else
1983     UncategorizedPrinter = true; // Invoke uncategorized printer
1984 }
1985 
1986 // Print the value of each option.
1987 void cl::PrintOptionValues() { GlobalParser->printOptionValues(); }
1988 
1989 void CommandLineParser::printOptionValues() {
1990   if (!PrintOptions && !PrintAllOptions)
1991     return;
1992 
1993   SmallVector<std::pair<const char *, Option *>, 128> Opts;
1994   sortOpts(ActiveSubCommand->OptionsMap, Opts, /*ShowHidden*/ true);
1995 
1996   // Compute the maximum argument length...
1997   size_t MaxArgLen = 0;
1998   for (size_t i = 0, e = Opts.size(); i != e; ++i)
1999     MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
2000 
2001   for (size_t i = 0, e = Opts.size(); i != e; ++i)
2002     Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
2003 }
2004 
2005 static void (*OverrideVersionPrinter)() = nullptr;
2006 
2007 static std::vector<void (*)()> *ExtraVersionPrinters = nullptr;
2008 
2009 namespace {
2010 class VersionPrinter {
2011 public:
2012   void print() {
2013     raw_ostream &OS = outs();
2014 #ifdef PACKAGE_VENDOR
2015     OS << PACKAGE_VENDOR << " ";
2016 #else
2017     OS << "LLVM (http://llvm.org/):\n  ";
2018 #endif
2019     OS << PACKAGE_NAME << " version " << PACKAGE_VERSION;
2020 #ifdef LLVM_VERSION_INFO
2021     OS << " " << LLVM_VERSION_INFO;
2022 #endif
2023     OS << "\n  ";
2024 #ifndef __OPTIMIZE__
2025     OS << "DEBUG build";
2026 #else
2027     OS << "Optimized build";
2028 #endif
2029 #ifndef NDEBUG
2030     OS << " with assertions";
2031 #endif
2032     std::string CPU = sys::getHostCPUName();
2033     if (CPU == "generic")
2034       CPU = "(unknown)";
2035     OS << ".\n"
2036        << "  Default target: " << sys::getDefaultTargetTriple() << '\n'
2037        << "  Host CPU: " << CPU << '\n';
2038   }
2039   void operator=(bool OptionWasSpecified) {
2040     if (!OptionWasSpecified)
2041       return;
2042 
2043     if (OverrideVersionPrinter != nullptr) {
2044       (*OverrideVersionPrinter)();
2045       exit(0);
2046     }
2047     print();
2048 
2049     // Iterate over any registered extra printers and call them to add further
2050     // information.
2051     if (ExtraVersionPrinters != nullptr) {
2052       outs() << '\n';
2053       for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(),
2054                                              E = ExtraVersionPrinters->end();
2055            I != E; ++I)
2056         (*I)();
2057     }
2058 
2059     exit(0);
2060   }
2061 };
2062 } // End anonymous namespace
2063 
2064 // Define the --version option that prints out the LLVM version for the tool
2065 static VersionPrinter VersionPrinterInstance;
2066 
2067 static cl::opt<VersionPrinter, true, parser<bool>>
2068     VersOp("version", cl::desc("Display the version of this program"),
2069            cl::location(VersionPrinterInstance), cl::ValueDisallowed,
2070            cl::cat(GenericCategory));
2071 
2072 // Utility function for printing the help message.
2073 void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
2074   // This looks weird, but it actually prints the help message. The Printers are
2075   // types of HelpPrinter and the help gets printed when its operator= is
2076   // invoked. That's because the "normal" usages of the help printer is to be
2077   // assigned true/false depending on whether -help or -help-hidden was given or
2078   // not.  Since we're circumventing that we have to make it look like -help or
2079   // -help-hidden were given, so we assign true.
2080 
2081   if (!Hidden && !Categorized)
2082     UncategorizedNormalPrinter = true;
2083   else if (!Hidden && Categorized)
2084     CategorizedNormalPrinter = true;
2085   else if (Hidden && !Categorized)
2086     UncategorizedHiddenPrinter = true;
2087   else
2088     CategorizedHiddenPrinter = true;
2089 }
2090 
2091 /// Utility function for printing version number.
2092 void cl::PrintVersionMessage() { VersionPrinterInstance.print(); }
2093 
2094 void cl::SetVersionPrinter(void (*func)()) { OverrideVersionPrinter = func; }
2095 
2096 void cl::AddExtraVersionPrinter(void (*func)()) {
2097   if (!ExtraVersionPrinters)
2098     ExtraVersionPrinters = new std::vector<void (*)()>;
2099 
2100   ExtraVersionPrinters->push_back(func);
2101 }
2102 
2103 StringMap<Option *> &cl::getRegisteredOptions(SubCommand &Sub) {
2104   auto &Subs = GlobalParser->RegisteredSubCommands;
2105   (void)Subs;
2106   assert(is_contained(Subs, &Sub));
2107   return Sub.OptionsMap;
2108 }
2109 
2110 void cl::HideUnrelatedOptions(cl::OptionCategory &Category, SubCommand &Sub) {
2111   for (auto &I : Sub.OptionsMap) {
2112     if (I.second->Category != &Category &&
2113         I.second->Category != &GenericCategory)
2114       I.second->setHiddenFlag(cl::ReallyHidden);
2115   }
2116 }
2117 
2118 void cl::HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories,
2119                               SubCommand &Sub) {
2120   auto CategoriesBegin = Categories.begin();
2121   auto CategoriesEnd = Categories.end();
2122   for (auto &I : Sub.OptionsMap) {
2123     if (std::find(CategoriesBegin, CategoriesEnd, I.second->Category) ==
2124             CategoriesEnd &&
2125         I.second->Category != &GenericCategory)
2126       I.second->setHiddenFlag(cl::ReallyHidden);
2127   }
2128 }
2129 
2130 void cl::ResetCommandLineParser() { GlobalParser->reset(); }
2131 void cl::ResetAllOptionOccurrences() {
2132   GlobalParser->ResetAllOptionOccurrences();
2133 }
2134 
2135 void LLVMParseCommandLineOptions(int argc, const char *const *argv,
2136                                  const char *Overview) {
2137   llvm::cl::ParseCommandLineOptions(argc, argv, StringRef(Overview), true);
2138 }
2139