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