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