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