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