xref: /freebsd-src/contrib/llvm-project/llvm/lib/Support/CommandLine.cpp (revision 0eae32dcef82f6f06de6419a0d623d7def0cc8f6)
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 
20 #include "DebugOptions.h"
21 
22 #include "llvm-c/Support.h"
23 #include "llvm/ADT/ArrayRef.h"
24 #include "llvm/ADT/Optional.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SmallPtrSet.h"
27 #include "llvm/ADT/SmallString.h"
28 #include "llvm/ADT/StringExtras.h"
29 #include "llvm/ADT/StringMap.h"
30 #include "llvm/ADT/StringRef.h"
31 #include "llvm/ADT/Triple.h"
32 #include "llvm/ADT/Twine.h"
33 #include "llvm/Config/config.h"
34 #include "llvm/Support/ConvertUTF.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/Error.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/FileSystem.h"
39 #include "llvm/Support/Host.h"
40 #include "llvm/Support/ManagedStatic.h"
41 #include "llvm/Support/MemoryBuffer.h"
42 #include "llvm/Support/Path.h"
43 #include "llvm/Support/Process.h"
44 #include "llvm/Support/StringSaver.h"
45 #include "llvm/Support/VirtualFileSystem.h"
46 #include "llvm/Support/raw_ostream.h"
47 #include <cstdlib>
48 #include <map>
49 #include <string>
50 using namespace llvm;
51 using namespace cl;
52 
53 #define DEBUG_TYPE "commandline"
54 
55 //===----------------------------------------------------------------------===//
56 // Template instantiations and anchors.
57 //
58 namespace llvm {
59 namespace cl {
60 template class basic_parser<bool>;
61 template class basic_parser<boolOrDefault>;
62 template class basic_parser<int>;
63 template class basic_parser<long>;
64 template class basic_parser<long long>;
65 template class basic_parser<unsigned>;
66 template class basic_parser<unsigned long>;
67 template class basic_parser<unsigned long long>;
68 template class basic_parser<double>;
69 template class basic_parser<float>;
70 template class basic_parser<std::string>;
71 template class basic_parser<char>;
72 
73 template class opt<unsigned>;
74 template class opt<int>;
75 template class opt<std::string>;
76 template class opt<char>;
77 template class opt<bool>;
78 } // namespace cl
79 } // namespace llvm
80 
81 // Pin the vtables to this file.
82 void GenericOptionValue::anchor() {}
83 void OptionValue<boolOrDefault>::anchor() {}
84 void OptionValue<std::string>::anchor() {}
85 void Option::anchor() {}
86 void basic_parser_impl::anchor() {}
87 void parser<bool>::anchor() {}
88 void parser<boolOrDefault>::anchor() {}
89 void parser<int>::anchor() {}
90 void parser<long>::anchor() {}
91 void parser<long long>::anchor() {}
92 void parser<unsigned>::anchor() {}
93 void parser<unsigned long>::anchor() {}
94 void parser<unsigned long long>::anchor() {}
95 void parser<double>::anchor() {}
96 void parser<float>::anchor() {}
97 void parser<std::string>::anchor() {}
98 void parser<char>::anchor() {}
99 
100 //===----------------------------------------------------------------------===//
101 
102 const static size_t DefaultPad = 2;
103 
104 static StringRef ArgPrefix = "-";
105 static StringRef ArgPrefixLong = "--";
106 static StringRef ArgHelpPrefix = " - ";
107 
108 static size_t argPlusPrefixesSize(StringRef ArgName, size_t Pad = DefaultPad) {
109   size_t Len = ArgName.size();
110   if (Len == 1)
111     return Len + Pad + ArgPrefix.size() + ArgHelpPrefix.size();
112   return Len + Pad + ArgPrefixLong.size() + ArgHelpPrefix.size();
113 }
114 
115 static SmallString<8> argPrefix(StringRef ArgName, size_t Pad = DefaultPad) {
116   SmallString<8> Prefix;
117   for (size_t I = 0; I < Pad; ++I) {
118     Prefix.push_back(' ');
119   }
120   Prefix.append(ArgName.size() > 1 ? ArgPrefixLong : ArgPrefix);
121   return Prefix;
122 }
123 
124 // Option predicates...
125 static inline bool isGrouping(const Option *O) {
126   return O->getMiscFlags() & cl::Grouping;
127 }
128 static inline bool isPrefixedOrGrouping(const Option *O) {
129   return isGrouping(O) || O->getFormattingFlag() == cl::Prefix ||
130          O->getFormattingFlag() == cl::AlwaysPrefix;
131 }
132 
133 
134 namespace {
135 
136 class PrintArg {
137   StringRef ArgName;
138   size_t Pad;
139 public:
140   PrintArg(StringRef ArgName, size_t Pad = DefaultPad) : ArgName(ArgName), Pad(Pad) {}
141   friend raw_ostream &operator<<(raw_ostream &OS, const PrintArg &);
142 };
143 
144 raw_ostream &operator<<(raw_ostream &OS, const PrintArg& Arg) {
145   OS << argPrefix(Arg.ArgName, Arg.Pad) << Arg.ArgName;
146   return OS;
147 }
148 
149 class CommandLineParser {
150 public:
151   // Globals for name and overview of program.  Program name is not a string to
152   // avoid static ctor/dtor issues.
153   std::string ProgramName;
154   StringRef ProgramOverview;
155 
156   // This collects additional help to be printed.
157   std::vector<StringRef> MoreHelp;
158 
159   // This collects Options added with the cl::DefaultOption flag. Since they can
160   // be overridden, they are not added to the appropriate SubCommands until
161   // ParseCommandLineOptions actually runs.
162   SmallVector<Option*, 4> DefaultOptions;
163 
164   // This collects the different option categories that have been registered.
165   SmallPtrSet<OptionCategory *, 16> RegisteredOptionCategories;
166 
167   // This collects the different subcommands that have been registered.
168   SmallPtrSet<SubCommand *, 4> RegisteredSubCommands;
169 
170   CommandLineParser() : ActiveSubCommand(nullptr) {
171     registerSubCommand(&*TopLevelSubCommand);
172     registerSubCommand(&*AllSubCommands);
173   }
174 
175   void ResetAllOptionOccurrences();
176 
177   bool ParseCommandLineOptions(int argc, const char *const *argv,
178                                StringRef Overview, raw_ostream *Errs = nullptr,
179                                bool LongOptionsUseDoubleDash = false);
180 
181   void addLiteralOption(Option &Opt, SubCommand *SC, StringRef Name) {
182     if (Opt.hasArgStr())
183       return;
184     if (!SC->OptionsMap.insert(std::make_pair(Name, &Opt)).second) {
185       errs() << ProgramName << ": CommandLine Error: Option '" << Name
186              << "' registered more than once!\n";
187       report_fatal_error("inconsistency in registered CommandLine options");
188     }
189 
190     // If we're adding this to all sub-commands, add it to the ones that have
191     // already been registered.
192     if (SC == &*AllSubCommands) {
193       for (auto *Sub : RegisteredSubCommands) {
194         if (SC == Sub)
195           continue;
196         addLiteralOption(Opt, Sub, Name);
197       }
198     }
199   }
200 
201   void addLiteralOption(Option &Opt, StringRef Name) {
202     if (Opt.Subs.empty())
203       addLiteralOption(Opt, &*TopLevelSubCommand, Name);
204     else {
205       for (auto *SC : Opt.Subs)
206         addLiteralOption(Opt, SC, Name);
207     }
208   }
209 
210   void addOption(Option *O, SubCommand *SC) {
211     bool HadErrors = false;
212     if (O->hasArgStr()) {
213       // If it's a DefaultOption, check to make sure it isn't already there.
214       if (O->isDefaultOption() &&
215           SC->OptionsMap.find(O->ArgStr) != SC->OptionsMap.end())
216         return;
217 
218       // Add argument to the argument map!
219       if (!SC->OptionsMap.insert(std::make_pair(O->ArgStr, O)).second) {
220         errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
221                << "' registered more than once!\n";
222         HadErrors = true;
223       }
224     }
225 
226     // Remember information about positional options.
227     if (O->getFormattingFlag() == cl::Positional)
228       SC->PositionalOpts.push_back(O);
229     else if (O->getMiscFlags() & cl::Sink) // Remember sink options
230       SC->SinkOpts.push_back(O);
231     else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
232       if (SC->ConsumeAfterOpt) {
233         O->error("Cannot specify more than one option with cl::ConsumeAfter!");
234         HadErrors = true;
235       }
236       SC->ConsumeAfterOpt = O;
237     }
238 
239     // Fail hard if there were errors. These are strictly unrecoverable and
240     // indicate serious issues such as conflicting option names or an
241     // incorrectly
242     // linked LLVM distribution.
243     if (HadErrors)
244       report_fatal_error("inconsistency in registered CommandLine options");
245 
246     // If we're adding this to all sub-commands, add it to the ones that have
247     // already been registered.
248     if (SC == &*AllSubCommands) {
249       for (auto *Sub : RegisteredSubCommands) {
250         if (SC == Sub)
251           continue;
252         addOption(O, Sub);
253       }
254     }
255   }
256 
257   void addOption(Option *O, bool ProcessDefaultOption = false) {
258     if (!ProcessDefaultOption && O->isDefaultOption()) {
259       DefaultOptions.push_back(O);
260       return;
261     }
262 
263     if (O->Subs.empty()) {
264       addOption(O, &*TopLevelSubCommand);
265     } else {
266       for (auto *SC : O->Subs)
267         addOption(O, SC);
268     }
269   }
270 
271   void removeOption(Option *O, SubCommand *SC) {
272     SmallVector<StringRef, 16> OptionNames;
273     O->getExtraOptionNames(OptionNames);
274     if (O->hasArgStr())
275       OptionNames.push_back(O->ArgStr);
276 
277     SubCommand &Sub = *SC;
278     auto End = Sub.OptionsMap.end();
279     for (auto Name : OptionNames) {
280       auto I = Sub.OptionsMap.find(Name);
281       if (I != End && I->getValue() == O)
282         Sub.OptionsMap.erase(I);
283     }
284 
285     if (O->getFormattingFlag() == cl::Positional)
286       for (auto *Opt = Sub.PositionalOpts.begin();
287            Opt != Sub.PositionalOpts.end(); ++Opt) {
288         if (*Opt == O) {
289           Sub.PositionalOpts.erase(Opt);
290           break;
291         }
292       }
293     else if (O->getMiscFlags() & cl::Sink)
294       for (auto *Opt = Sub.SinkOpts.begin(); Opt != Sub.SinkOpts.end(); ++Opt) {
295         if (*Opt == O) {
296           Sub.SinkOpts.erase(Opt);
297           break;
298         }
299       }
300     else if (O == Sub.ConsumeAfterOpt)
301       Sub.ConsumeAfterOpt = nullptr;
302   }
303 
304   void removeOption(Option *O) {
305     if (O->Subs.empty())
306       removeOption(O, &*TopLevelSubCommand);
307     else {
308       if (O->isInAllSubCommands()) {
309         for (auto *SC : RegisteredSubCommands)
310           removeOption(O, SC);
311       } else {
312         for (auto *SC : O->Subs)
313           removeOption(O, SC);
314       }
315     }
316   }
317 
318   bool hasOptions(const SubCommand &Sub) const {
319     return (!Sub.OptionsMap.empty() || !Sub.PositionalOpts.empty() ||
320             nullptr != Sub.ConsumeAfterOpt);
321   }
322 
323   bool hasOptions() const {
324     for (const auto *S : RegisteredSubCommands) {
325       if (hasOptions(*S))
326         return true;
327     }
328     return false;
329   }
330 
331   SubCommand *getActiveSubCommand() { return ActiveSubCommand; }
332 
333   void updateArgStr(Option *O, StringRef NewName, SubCommand *SC) {
334     SubCommand &Sub = *SC;
335     if (!Sub.OptionsMap.insert(std::make_pair(NewName, O)).second) {
336       errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
337              << "' registered more than once!\n";
338       report_fatal_error("inconsistency in registered CommandLine options");
339     }
340     Sub.OptionsMap.erase(O->ArgStr);
341   }
342 
343   void updateArgStr(Option *O, StringRef NewName) {
344     if (O->Subs.empty())
345       updateArgStr(O, NewName, &*TopLevelSubCommand);
346     else {
347       if (O->isInAllSubCommands()) {
348         for (auto *SC : RegisteredSubCommands)
349           updateArgStr(O, NewName, SC);
350       } else {
351         for (auto *SC : O->Subs)
352           updateArgStr(O, NewName, SC);
353       }
354     }
355   }
356 
357   void printOptionValues();
358 
359   void registerCategory(OptionCategory *cat) {
360     assert(count_if(RegisteredOptionCategories,
361                     [cat](const OptionCategory *Category) {
362              return cat->getName() == Category->getName();
363            }) == 0 &&
364            "Duplicate option categories");
365 
366     RegisteredOptionCategories.insert(cat);
367   }
368 
369   void registerSubCommand(SubCommand *sub) {
370     assert(count_if(RegisteredSubCommands,
371                     [sub](const SubCommand *Sub) {
372                       return (!sub->getName().empty()) &&
373                              (Sub->getName() == sub->getName());
374                     }) == 0 &&
375            "Duplicate subcommands");
376     RegisteredSubCommands.insert(sub);
377 
378     // For all options that have been registered for all subcommands, add the
379     // option to this subcommand now.
380     if (sub != &*AllSubCommands) {
381       for (auto &E : AllSubCommands->OptionsMap) {
382         Option *O = E.second;
383         if ((O->isPositional() || O->isSink() || O->isConsumeAfter()) ||
384             O->hasArgStr())
385           addOption(O, sub);
386         else
387           addLiteralOption(*O, sub, E.first());
388       }
389     }
390   }
391 
392   void unregisterSubCommand(SubCommand *sub) {
393     RegisteredSubCommands.erase(sub);
394   }
395 
396   iterator_range<typename SmallPtrSet<SubCommand *, 4>::iterator>
397   getRegisteredSubcommands() {
398     return make_range(RegisteredSubCommands.begin(),
399                       RegisteredSubCommands.end());
400   }
401 
402   void reset() {
403     ActiveSubCommand = nullptr;
404     ProgramName.clear();
405     ProgramOverview = StringRef();
406 
407     MoreHelp.clear();
408     RegisteredOptionCategories.clear();
409 
410     ResetAllOptionOccurrences();
411     RegisteredSubCommands.clear();
412 
413     TopLevelSubCommand->reset();
414     AllSubCommands->reset();
415     registerSubCommand(&*TopLevelSubCommand);
416     registerSubCommand(&*AllSubCommands);
417 
418     DefaultOptions.clear();
419   }
420 
421 private:
422   SubCommand *ActiveSubCommand;
423 
424   Option *LookupOption(SubCommand &Sub, StringRef &Arg, StringRef &Value);
425   Option *LookupLongOption(SubCommand &Sub, StringRef &Arg, StringRef &Value,
426                            bool LongOptionsUseDoubleDash, bool HaveDoubleDash) {
427     Option *Opt = LookupOption(Sub, Arg, Value);
428     if (Opt && LongOptionsUseDoubleDash && !HaveDoubleDash && !isGrouping(Opt))
429       return nullptr;
430     return Opt;
431   }
432   SubCommand *LookupSubCommand(StringRef Name);
433 };
434 
435 } // namespace
436 
437 static ManagedStatic<CommandLineParser> GlobalParser;
438 
439 void cl::AddLiteralOption(Option &O, StringRef Name) {
440   GlobalParser->addLiteralOption(O, Name);
441 }
442 
443 extrahelp::extrahelp(StringRef Help) : morehelp(Help) {
444   GlobalParser->MoreHelp.push_back(Help);
445 }
446 
447 void Option::addArgument() {
448   GlobalParser->addOption(this);
449   FullyInitialized = true;
450 }
451 
452 void Option::removeArgument() { GlobalParser->removeOption(this); }
453 
454 void Option::setArgStr(StringRef S) {
455   if (FullyInitialized)
456     GlobalParser->updateArgStr(this, S);
457   assert((S.empty() || S[0] != '-') && "Option can't start with '-");
458   ArgStr = S;
459   if (ArgStr.size() == 1)
460     setMiscFlag(Grouping);
461 }
462 
463 void Option::addCategory(OptionCategory &C) {
464   assert(!Categories.empty() && "Categories cannot be empty.");
465   // Maintain backward compatibility by replacing the default GeneralCategory
466   // if it's still set.  Otherwise, just add the new one.  The GeneralCategory
467   // must be explicitly added if you want multiple categories that include it.
468   if (&C != &getGeneralCategory() && Categories[0] == &getGeneralCategory())
469     Categories[0] = &C;
470   else if (!is_contained(Categories, &C))
471     Categories.push_back(&C);
472 }
473 
474 void Option::reset() {
475   NumOccurrences = 0;
476   setDefault();
477   if (isDefaultOption())
478     removeArgument();
479 }
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     return Sub.OptionsMap.lookup(Arg);
535   }
536 
537   // If the argument before the = is a valid option name and the option allows
538   // non-prefix form (ie is not AlwaysPrefix), we match.  If not, signal match
539   // failure by returning nullptr.
540   auto I = Sub.OptionsMap.find(Arg.substr(0, EqualPos));
541   if (I == Sub.OptionsMap.end())
542     return nullptr;
543 
544   auto *O = I->second;
545   if (O->getFormattingFlag() == cl::AlwaysPrefix)
546     return nullptr;
547 
548   Value = Arg.substr(EqualPos + 1);
549   Arg = Arg.substr(0, EqualPos);
550   return I->second;
551 }
552 
553 SubCommand *CommandLineParser::LookupSubCommand(StringRef Name) {
554   if (Name.empty())
555     return &*TopLevelSubCommand;
556   for (auto *S : RegisteredSubCommands) {
557     if (S == &*AllSubCommands)
558       continue;
559     if (S->getName().empty())
560       continue;
561 
562     if (StringRef(S->getName()) == StringRef(Name))
563       return S;
564   }
565   return &*TopLevelSubCommand;
566 }
567 
568 /// LookupNearestOption - Lookup the closest match to the option specified by
569 /// the specified option on the command line.  If there is a value specified
570 /// (after an equal sign) return that as well.  This assumes that leading dashes
571 /// have already been stripped.
572 static Option *LookupNearestOption(StringRef Arg,
573                                    const StringMap<Option *> &OptionsMap,
574                                    std::string &NearestString) {
575   // Reject all dashes.
576   if (Arg.empty())
577     return nullptr;
578 
579   // Split on any equal sign.
580   std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
581   StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
582   StringRef &RHS = SplitArg.second;
583 
584   // Find the closest match.
585   Option *Best = nullptr;
586   unsigned BestDistance = 0;
587   for (StringMap<Option *>::const_iterator it = OptionsMap.begin(),
588                                            ie = OptionsMap.end();
589        it != ie; ++it) {
590     Option *O = it->second;
591     // Do not suggest really hidden options (not shown in any help).
592     if (O->getOptionHiddenFlag() == ReallyHidden)
593       continue;
594 
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 (const 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(Token.str()).data());
868       // Mark the end of lines in response files.
869       if (MarkEOLs && C == '\n')
870         NewArgv.push_back(nullptr);
871       Token.clear();
872       continue;
873     }
874 
875     // This is a normal character.  Append it.
876     Token.push_back(C);
877   }
878 
879   // Append the last token after hitting EOF with no whitespace.
880   if (!Token.empty())
881     NewArgv.push_back(Saver.save(Token.str()).data());
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         // No special characters: slice out the substring and start the next
956         // token. Copy the string if the caller asks us to.
957         AddToken(AlwaysCopy ? Saver.save(NormalChars) : NormalChars);
958         if (I < E && Src[I] == '\n')
959           MarkEOL();
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,
1142                              llvm::Optional<llvm::StringRef> CurrentDir,
1143                              llvm::vfs::FileSystem &FS) {
1144   bool AllExpanded = true;
1145   struct ResponseFileRecord {
1146     std::string File;
1147     size_t End;
1148   };
1149 
1150   // To detect recursive response files, we maintain a stack of files and the
1151   // position of the last argument in the file. This position is updated
1152   // dynamically as we recursively expand files.
1153   SmallVector<ResponseFileRecord, 3> FileStack;
1154 
1155   // Push a dummy entry that represents the initial command line, removing
1156   // the need to check for an empty list.
1157   FileStack.push_back({"", Argv.size()});
1158 
1159   // Don't cache Argv.size() because it can change.
1160   for (unsigned I = 0; I != Argv.size();) {
1161     while (I == FileStack.back().End) {
1162       // Passing the end of a file's argument list, so we can remove it from the
1163       // stack.
1164       FileStack.pop_back();
1165     }
1166 
1167     const char *Arg = Argv[I];
1168     // Check if it is an EOL marker
1169     if (Arg == nullptr) {
1170       ++I;
1171       continue;
1172     }
1173 
1174     if (Arg[0] != '@') {
1175       ++I;
1176       continue;
1177     }
1178 
1179     const char *FName = Arg + 1;
1180     // Note that CurrentDir is only used for top-level rsp files, the rest will
1181     // always have an absolute path deduced from the containing file.
1182     SmallString<128> CurrDir;
1183     if (llvm::sys::path::is_relative(FName)) {
1184       if (!CurrentDir)
1185         llvm::sys::fs::current_path(CurrDir);
1186       else
1187         CurrDir = *CurrentDir;
1188       llvm::sys::path::append(CurrDir, FName);
1189       FName = CurrDir.c_str();
1190     }
1191     auto IsEquivalent = [FName, &FS](const ResponseFileRecord &RFile) {
1192       llvm::ErrorOr<llvm::vfs::Status> LHS = FS.status(FName);
1193       if (!LHS) {
1194         // TODO: The error should be propagated up the stack.
1195         llvm::consumeError(llvm::errorCodeToError(LHS.getError()));
1196         return false;
1197       }
1198       llvm::ErrorOr<llvm::vfs::Status> RHS = FS.status(RFile.File);
1199       if (!RHS) {
1200         // TODO: The error should be propagated up the stack.
1201         llvm::consumeError(llvm::errorCodeToError(RHS.getError()));
1202         return false;
1203       }
1204       return LHS->equivalent(*RHS);
1205     };
1206 
1207     // Check for recursive response files.
1208     if (any_of(drop_begin(FileStack), IsEquivalent)) {
1209       // This file is recursive, so we leave it in the argument stream and
1210       // move on.
1211       AllExpanded = false;
1212       ++I;
1213       continue;
1214     }
1215 
1216     // Replace this response file argument with the tokenization of its
1217     // contents.  Nested response files are expanded in subsequent iterations.
1218     SmallVector<const char *, 0> ExpandedArgv;
1219     if (llvm::Error Err =
1220             ExpandResponseFile(FName, Saver, Tokenizer, ExpandedArgv, MarkEOLs,
1221                                RelativeNames, FS)) {
1222       // We couldn't read this file, so we leave it in the argument stream and
1223       // move on.
1224       // TODO: The error should be propagated up the stack.
1225       llvm::consumeError(std::move(Err));
1226       AllExpanded = false;
1227       ++I;
1228       continue;
1229     }
1230 
1231     for (ResponseFileRecord &Record : FileStack) {
1232       // Increase the end of all active records by the number of newly expanded
1233       // arguments, minus the response file itself.
1234       Record.End += ExpandedArgv.size() - 1;
1235     }
1236 
1237     FileStack.push_back({FName, I + ExpandedArgv.size()});
1238     Argv.erase(Argv.begin() + I);
1239     Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
1240   }
1241 
1242   // If successful, the top of the file stack will mark the end of the Argv
1243   // stream. A failure here indicates a bug in the stack popping logic above.
1244   // Note that FileStack may have more than one element at this point because we
1245   // don't have a chance to pop the stack when encountering recursive files at
1246   // the end of the stream, so seeing that doesn't indicate a bug.
1247   assert(FileStack.size() > 0 && Argv.size() == FileStack.back().End);
1248   return AllExpanded;
1249 }
1250 
1251 bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
1252                              SmallVectorImpl<const char *> &Argv, bool MarkEOLs,
1253                              bool RelativeNames,
1254                              llvm::Optional<StringRef> CurrentDir) {
1255   return ExpandResponseFiles(Saver, std::move(Tokenizer), Argv, MarkEOLs,
1256                              RelativeNames, std::move(CurrentDir),
1257                              *vfs::getRealFileSystem());
1258 }
1259 
1260 bool cl::expandResponseFiles(int Argc, const char *const *Argv,
1261                              const char *EnvVar, StringSaver &Saver,
1262                              SmallVectorImpl<const char *> &NewArgv) {
1263   auto Tokenize = Triple(sys::getProcessTriple()).isOSWindows()
1264                       ? cl::TokenizeWindowsCommandLine
1265                       : cl::TokenizeGNUCommandLine;
1266   // The environment variable specifies initial options.
1267   if (EnvVar)
1268     if (llvm::Optional<std::string> EnvValue = sys::Process::GetEnv(EnvVar))
1269       Tokenize(*EnvValue, Saver, NewArgv, /*MarkEOLs=*/false);
1270 
1271   // Command line options can override the environment variable.
1272   NewArgv.append(Argv + 1, Argv + Argc);
1273   return ExpandResponseFiles(Saver, Tokenize, NewArgv);
1274 }
1275 
1276 bool cl::readConfigFile(StringRef CfgFile, StringSaver &Saver,
1277                         SmallVectorImpl<const char *> &Argv) {
1278   SmallString<128> AbsPath;
1279   if (sys::path::is_relative(CfgFile)) {
1280     llvm::sys::fs::current_path(AbsPath);
1281     llvm::sys::path::append(AbsPath, CfgFile);
1282     CfgFile = AbsPath.str();
1283   }
1284   if (llvm::Error Err =
1285           ExpandResponseFile(CfgFile, Saver, cl::tokenizeConfigFile, Argv,
1286                              /*MarkEOLs=*/false, /*RelativeNames=*/true,
1287                              *llvm::vfs::getRealFileSystem())) {
1288     // TODO: The error should be propagated up the stack.
1289     llvm::consumeError(std::move(Err));
1290     return false;
1291   }
1292   return ExpandResponseFiles(Saver, cl::tokenizeConfigFile, Argv,
1293                              /*MarkEOLs=*/false, /*RelativeNames=*/true);
1294 }
1295 
1296 static void initCommonOptions();
1297 bool cl::ParseCommandLineOptions(int argc, const char *const *argv,
1298                                  StringRef Overview, raw_ostream *Errs,
1299                                  const char *EnvVar,
1300                                  bool LongOptionsUseDoubleDash) {
1301   initCommonOptions();
1302   SmallVector<const char *, 20> NewArgv;
1303   BumpPtrAllocator A;
1304   StringSaver Saver(A);
1305   NewArgv.push_back(argv[0]);
1306 
1307   // Parse options from environment variable.
1308   if (EnvVar) {
1309     if (llvm::Optional<std::string> EnvValue =
1310             sys::Process::GetEnv(StringRef(EnvVar)))
1311       TokenizeGNUCommandLine(*EnvValue, Saver, NewArgv);
1312   }
1313 
1314   // Append options from command line.
1315   for (int I = 1; I < argc; ++I)
1316     NewArgv.push_back(argv[I]);
1317   int NewArgc = static_cast<int>(NewArgv.size());
1318 
1319   // Parse all options.
1320   return GlobalParser->ParseCommandLineOptions(NewArgc, &NewArgv[0], Overview,
1321                                                Errs, LongOptionsUseDoubleDash);
1322 }
1323 
1324 /// Reset all options at least once, so that we can parse different options.
1325 void CommandLineParser::ResetAllOptionOccurrences() {
1326   // Reset all option values to look like they have never been seen before.
1327   // Options might be reset twice (they can be reference in both OptionsMap
1328   // and one of the other members), but that does not harm.
1329   for (auto *SC : RegisteredSubCommands) {
1330     for (auto &O : SC->OptionsMap)
1331       O.second->reset();
1332     for (Option *O : SC->PositionalOpts)
1333       O->reset();
1334     for (Option *O : SC->SinkOpts)
1335       O->reset();
1336     if (SC->ConsumeAfterOpt)
1337       SC->ConsumeAfterOpt->reset();
1338   }
1339 }
1340 
1341 bool CommandLineParser::ParseCommandLineOptions(int argc,
1342                                                 const char *const *argv,
1343                                                 StringRef Overview,
1344                                                 raw_ostream *Errs,
1345                                                 bool LongOptionsUseDoubleDash) {
1346   assert(hasOptions() && "No options specified!");
1347 
1348   // Expand response files.
1349   SmallVector<const char *, 20> newArgv(argv, argv + argc);
1350   BumpPtrAllocator A;
1351   StringSaver Saver(A);
1352   ExpandResponseFiles(Saver,
1353          Triple(sys::getProcessTriple()).isOSWindows() ?
1354          cl::TokenizeWindowsCommandLine : cl::TokenizeGNUCommandLine,
1355          newArgv);
1356   argv = &newArgv[0];
1357   argc = static_cast<int>(newArgv.size());
1358 
1359   // Copy the program name into ProgName, making sure not to overflow it.
1360   ProgramName = std::string(sys::path::filename(StringRef(argv[0])));
1361 
1362   ProgramOverview = Overview;
1363   bool IgnoreErrors = Errs;
1364   if (!Errs)
1365     Errs = &errs();
1366   bool ErrorParsing = false;
1367 
1368   // Check out the positional arguments to collect information about them.
1369   unsigned NumPositionalRequired = 0;
1370 
1371   // Determine whether or not there are an unlimited number of positionals
1372   bool HasUnlimitedPositionals = false;
1373 
1374   int FirstArg = 1;
1375   SubCommand *ChosenSubCommand = &*TopLevelSubCommand;
1376   if (argc >= 2 && argv[FirstArg][0] != '-') {
1377     // If the first argument specifies a valid subcommand, start processing
1378     // options from the second argument.
1379     ChosenSubCommand = LookupSubCommand(StringRef(argv[FirstArg]));
1380     if (ChosenSubCommand != &*TopLevelSubCommand)
1381       FirstArg = 2;
1382   }
1383   GlobalParser->ActiveSubCommand = ChosenSubCommand;
1384 
1385   assert(ChosenSubCommand);
1386   auto &ConsumeAfterOpt = ChosenSubCommand->ConsumeAfterOpt;
1387   auto &PositionalOpts = ChosenSubCommand->PositionalOpts;
1388   auto &SinkOpts = ChosenSubCommand->SinkOpts;
1389   auto &OptionsMap = ChosenSubCommand->OptionsMap;
1390 
1391   for (auto *O: DefaultOptions) {
1392     addOption(O, true);
1393   }
1394 
1395   if (ConsumeAfterOpt) {
1396     assert(PositionalOpts.size() > 0 &&
1397            "Cannot specify cl::ConsumeAfter without a positional argument!");
1398   }
1399   if (!PositionalOpts.empty()) {
1400 
1401     // Calculate how many positional values are _required_.
1402     bool UnboundedFound = false;
1403     for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
1404       Option *Opt = PositionalOpts[i];
1405       if (RequiresValue(Opt))
1406         ++NumPositionalRequired;
1407       else if (ConsumeAfterOpt) {
1408         // ConsumeAfter cannot be combined with "optional" positional options
1409         // unless there is only one positional argument...
1410         if (PositionalOpts.size() > 1) {
1411           if (!IgnoreErrors)
1412             Opt->error("error - this positional option will never be matched, "
1413                        "because it does not Require a value, and a "
1414                        "cl::ConsumeAfter option is active!");
1415           ErrorParsing = true;
1416         }
1417       } else if (UnboundedFound && !Opt->hasArgStr()) {
1418         // This option does not "require" a value...  Make sure this option is
1419         // not specified after an option that eats all extra arguments, or this
1420         // one will never get any!
1421         //
1422         if (!IgnoreErrors)
1423           Opt->error("error - option can never match, because "
1424                      "another positional argument will match an "
1425                      "unbounded number of values, and this option"
1426                      " does not require a value!");
1427         *Errs << ProgramName << ": CommandLine Error: Option '" << Opt->ArgStr
1428               << "' is all messed up!\n";
1429         *Errs << PositionalOpts.size();
1430         ErrorParsing = true;
1431       }
1432       UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
1433     }
1434     HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
1435   }
1436 
1437   // PositionalVals - A vector of "positional" arguments we accumulate into
1438   // the process at the end.
1439   //
1440   SmallVector<std::pair<StringRef, unsigned>, 4> PositionalVals;
1441 
1442   // If the program has named positional arguments, and the name has been run
1443   // across, keep track of which positional argument was named.  Otherwise put
1444   // the positional args into the PositionalVals list...
1445   Option *ActivePositionalArg = nullptr;
1446 
1447   // Loop over all of the arguments... processing them.
1448   bool DashDashFound = false; // Have we read '--'?
1449   for (int i = FirstArg; i < argc; ++i) {
1450     Option *Handler = nullptr;
1451     Option *NearestHandler = nullptr;
1452     std::string NearestHandlerString;
1453     StringRef Value;
1454     StringRef ArgName = "";
1455     bool HaveDoubleDash = false;
1456 
1457     // Check to see if this is a positional argument.  This argument is
1458     // considered to be positional if it doesn't start with '-', if it is "-"
1459     // itself, or if we have seen "--" already.
1460     //
1461     if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
1462       // Positional argument!
1463       if (ActivePositionalArg) {
1464         ProvidePositionalOption(ActivePositionalArg, StringRef(argv[i]), i);
1465         continue; // We are done!
1466       }
1467 
1468       if (!PositionalOpts.empty()) {
1469         PositionalVals.push_back(std::make_pair(StringRef(argv[i]), i));
1470 
1471         // All of the positional arguments have been fulfulled, give the rest to
1472         // the consume after option... if it's specified...
1473         //
1474         if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) {
1475           for (++i; i < argc; ++i)
1476             PositionalVals.push_back(std::make_pair(StringRef(argv[i]), i));
1477           break; // Handle outside of the argument processing loop...
1478         }
1479 
1480         // Delay processing positional arguments until the end...
1481         continue;
1482       }
1483     } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
1484                !DashDashFound) {
1485       DashDashFound = true; // This is the mythical "--"?
1486       continue;             // Don't try to process it as an argument itself.
1487     } else if (ActivePositionalArg &&
1488                (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
1489       // If there is a positional argument eating options, check to see if this
1490       // option is another positional argument.  If so, treat it as an argument,
1491       // otherwise feed it to the eating positional.
1492       ArgName = StringRef(argv[i] + 1);
1493       // Eat second dash.
1494       if (!ArgName.empty() && ArgName[0] == '-') {
1495         HaveDoubleDash = true;
1496         ArgName = ArgName.substr(1);
1497       }
1498 
1499       Handler = LookupLongOption(*ChosenSubCommand, ArgName, Value,
1500                                  LongOptionsUseDoubleDash, HaveDoubleDash);
1501       if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
1502         ProvidePositionalOption(ActivePositionalArg, StringRef(argv[i]), i);
1503         continue; // We are done!
1504       }
1505     } else { // We start with a '-', must be an argument.
1506       ArgName = StringRef(argv[i] + 1);
1507       // Eat second dash.
1508       if (!ArgName.empty() && ArgName[0] == '-') {
1509         HaveDoubleDash = true;
1510         ArgName = ArgName.substr(1);
1511       }
1512 
1513       Handler = LookupLongOption(*ChosenSubCommand, ArgName, Value,
1514                                  LongOptionsUseDoubleDash, HaveDoubleDash);
1515 
1516       // Check to see if this "option" is really a prefixed or grouped argument.
1517       if (!Handler && !(LongOptionsUseDoubleDash && HaveDoubleDash))
1518         Handler = HandlePrefixedOrGroupedOption(ArgName, Value, ErrorParsing,
1519                                                 OptionsMap);
1520 
1521       // Otherwise, look for the closest available option to report to the user
1522       // in the upcoming error.
1523       if (!Handler && SinkOpts.empty())
1524         NearestHandler =
1525             LookupNearestOption(ArgName, OptionsMap, NearestHandlerString);
1526     }
1527 
1528     if (!Handler) {
1529       if (SinkOpts.empty()) {
1530         *Errs << ProgramName << ": Unknown command line argument '" << argv[i]
1531               << "'.  Try: '" << argv[0] << " --help'\n";
1532 
1533         if (NearestHandler) {
1534           // If we know a near match, report it as well.
1535           *Errs << ProgramName << ": Did you mean '"
1536                 << PrintArg(NearestHandlerString, 0) << "'?\n";
1537         }
1538 
1539         ErrorParsing = true;
1540       } else {
1541         for (Option *SinkOpt : SinkOpts)
1542           SinkOpt->addOccurrence(i, "", StringRef(argv[i]));
1543       }
1544       continue;
1545     }
1546 
1547     // If this is a named positional argument, just remember that it is the
1548     // active one...
1549     if (Handler->getFormattingFlag() == cl::Positional) {
1550       if ((Handler->getMiscFlags() & PositionalEatsArgs) && !Value.empty()) {
1551         Handler->error("This argument does not take a value.\n"
1552                        "\tInstead, it consumes any positional arguments until "
1553                        "the next recognized option.", *Errs);
1554         ErrorParsing = true;
1555       }
1556       ActivePositionalArg = Handler;
1557     }
1558     else
1559       ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
1560   }
1561 
1562   // Check and handle positional arguments now...
1563   if (NumPositionalRequired > PositionalVals.size()) {
1564       *Errs << ProgramName
1565              << ": Not enough positional command line arguments specified!\n"
1566              << "Must specify at least " << NumPositionalRequired
1567              << " positional argument" << (NumPositionalRequired > 1 ? "s" : "")
1568              << ": See: " << argv[0] << " --help\n";
1569 
1570     ErrorParsing = true;
1571   } else if (!HasUnlimitedPositionals &&
1572              PositionalVals.size() > PositionalOpts.size()) {
1573     *Errs << ProgramName << ": Too many positional arguments specified!\n"
1574           << "Can specify at most " << PositionalOpts.size()
1575           << " positional arguments: See: " << argv[0] << " --help\n";
1576     ErrorParsing = true;
1577 
1578   } else if (!ConsumeAfterOpt) {
1579     // Positional args have already been handled if ConsumeAfter is specified.
1580     unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
1581     for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
1582       if (RequiresValue(PositionalOpts[i])) {
1583         ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
1584                                 PositionalVals[ValNo].second);
1585         ValNo++;
1586         --NumPositionalRequired; // We fulfilled our duty...
1587       }
1588 
1589       // If we _can_ give this option more arguments, do so now, as long as we
1590       // do not give it values that others need.  'Done' controls whether the
1591       // option even _WANTS_ any more.
1592       //
1593       bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
1594       while (NumVals - ValNo > NumPositionalRequired && !Done) {
1595         switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
1596         case cl::Optional:
1597           Done = true; // Optional arguments want _at most_ one value
1598           LLVM_FALLTHROUGH;
1599         case cl::ZeroOrMore: // Zero or more will take all they can get...
1600         case cl::OneOrMore:  // One or more will take all they can get...
1601           ProvidePositionalOption(PositionalOpts[i],
1602                                   PositionalVals[ValNo].first,
1603                                   PositionalVals[ValNo].second);
1604           ValNo++;
1605           break;
1606         default:
1607           llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
1608                            "positional argument processing!");
1609         }
1610       }
1611     }
1612   } else {
1613     assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
1614     unsigned ValNo = 0;
1615     for (size_t J = 0, E = PositionalOpts.size(); J != E; ++J)
1616       if (RequiresValue(PositionalOpts[J])) {
1617         ErrorParsing |= ProvidePositionalOption(PositionalOpts[J],
1618                                                 PositionalVals[ValNo].first,
1619                                                 PositionalVals[ValNo].second);
1620         ValNo++;
1621       }
1622 
1623     // Handle the case where there is just one positional option, and it's
1624     // optional.  In this case, we want to give JUST THE FIRST option to the
1625     // positional option and keep the rest for the consume after.  The above
1626     // loop would have assigned no values to positional options in this case.
1627     //
1628     if (PositionalOpts.size() == 1 && ValNo == 0 && !PositionalVals.empty()) {
1629       ErrorParsing |= ProvidePositionalOption(PositionalOpts[0],
1630                                               PositionalVals[ValNo].first,
1631                                               PositionalVals[ValNo].second);
1632       ValNo++;
1633     }
1634 
1635     // Handle over all of the rest of the arguments to the
1636     // cl::ConsumeAfter command line option...
1637     for (; ValNo != PositionalVals.size(); ++ValNo)
1638       ErrorParsing |=
1639           ProvidePositionalOption(ConsumeAfterOpt, PositionalVals[ValNo].first,
1640                                   PositionalVals[ValNo].second);
1641   }
1642 
1643   // Loop over args and make sure all required args are specified!
1644   for (const auto &Opt : OptionsMap) {
1645     switch (Opt.second->getNumOccurrencesFlag()) {
1646     case Required:
1647     case OneOrMore:
1648       if (Opt.second->getNumOccurrences() == 0) {
1649         Opt.second->error("must be specified at least once!");
1650         ErrorParsing = true;
1651       }
1652       LLVM_FALLTHROUGH;
1653     default:
1654       break;
1655     }
1656   }
1657 
1658   // Now that we know if -debug is specified, we can use it.
1659   // Note that if ReadResponseFiles == true, this must be done before the
1660   // memory allocated for the expanded command line is free()d below.
1661   LLVM_DEBUG(dbgs() << "Args: ";
1662              for (int i = 0; i < argc; ++i) dbgs() << argv[i] << ' ';
1663              dbgs() << '\n';);
1664 
1665   // Free all of the memory allocated to the map.  Command line options may only
1666   // be processed once!
1667   MoreHelp.clear();
1668 
1669   // If we had an error processing our arguments, don't let the program execute
1670   if (ErrorParsing) {
1671     if (!IgnoreErrors)
1672       exit(1);
1673     return false;
1674   }
1675   return true;
1676 }
1677 
1678 //===----------------------------------------------------------------------===//
1679 // Option Base class implementation
1680 //
1681 
1682 bool Option::error(const Twine &Message, StringRef ArgName, raw_ostream &Errs) {
1683   if (!ArgName.data())
1684     ArgName = ArgStr;
1685   if (ArgName.empty())
1686     Errs << HelpStr; // Be nice for positional arguments
1687   else
1688     Errs << GlobalParser->ProgramName << ": for the " << PrintArg(ArgName, 0);
1689 
1690   Errs << " option: " << Message << "\n";
1691   return true;
1692 }
1693 
1694 bool Option::addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
1695                            bool MultiArg) {
1696   if (!MultiArg)
1697     NumOccurrences++; // Increment the number of times we have been seen
1698 
1699   switch (getNumOccurrencesFlag()) {
1700   case Optional:
1701     if (NumOccurrences > 1)
1702       return error("may only occur zero or one times!", ArgName);
1703     break;
1704   case Required:
1705     if (NumOccurrences > 1)
1706       return error("must occur exactly one time!", ArgName);
1707     LLVM_FALLTHROUGH;
1708   case OneOrMore:
1709   case ZeroOrMore:
1710   case ConsumeAfter:
1711     break;
1712   }
1713 
1714   return handleOccurrence(pos, ArgName, Value);
1715 }
1716 
1717 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
1718 // has been specified yet.
1719 //
1720 static StringRef getValueStr(const Option &O, StringRef DefaultMsg) {
1721   if (O.ValueStr.empty())
1722     return DefaultMsg;
1723   return O.ValueStr;
1724 }
1725 
1726 //===----------------------------------------------------------------------===//
1727 // cl::alias class implementation
1728 //
1729 
1730 // Return the width of the option tag for printing...
1731 size_t alias::getOptionWidth() const {
1732   return argPlusPrefixesSize(ArgStr);
1733 }
1734 
1735 void Option::printHelpStr(StringRef HelpStr, size_t Indent,
1736                           size_t FirstLineIndentedBy) {
1737   assert(Indent >= FirstLineIndentedBy);
1738   std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1739   outs().indent(Indent - FirstLineIndentedBy)
1740       << ArgHelpPrefix << Split.first << "\n";
1741   while (!Split.second.empty()) {
1742     Split = Split.second.split('\n');
1743     outs().indent(Indent) << Split.first << "\n";
1744   }
1745 }
1746 
1747 void Option::printEnumValHelpStr(StringRef HelpStr, size_t BaseIndent,
1748                                  size_t FirstLineIndentedBy) {
1749   const StringRef ValHelpPrefix = "  ";
1750   assert(BaseIndent >= FirstLineIndentedBy);
1751   std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1752   outs().indent(BaseIndent - FirstLineIndentedBy)
1753       << ArgHelpPrefix << ValHelpPrefix << Split.first << "\n";
1754   while (!Split.second.empty()) {
1755     Split = Split.second.split('\n');
1756     outs().indent(BaseIndent + ValHelpPrefix.size()) << Split.first << "\n";
1757   }
1758 }
1759 
1760 // Print out the option for the alias.
1761 void alias::printOptionInfo(size_t GlobalWidth) const {
1762   outs() << PrintArg(ArgStr);
1763   printHelpStr(HelpStr, GlobalWidth, argPlusPrefixesSize(ArgStr));
1764 }
1765 
1766 //===----------------------------------------------------------------------===//
1767 // Parser Implementation code...
1768 //
1769 
1770 // basic_parser implementation
1771 //
1772 
1773 // Return the width of the option tag for printing...
1774 size_t basic_parser_impl::getOptionWidth(const Option &O) const {
1775   size_t Len = argPlusPrefixesSize(O.ArgStr);
1776   auto ValName = getValueName();
1777   if (!ValName.empty()) {
1778     size_t FormattingLen = 3;
1779     if (O.getMiscFlags() & PositionalEatsArgs)
1780       FormattingLen = 6;
1781     Len += getValueStr(O, ValName).size() + FormattingLen;
1782   }
1783 
1784   return Len;
1785 }
1786 
1787 // printOptionInfo - Print out information about this option.  The
1788 // to-be-maintained width is specified.
1789 //
1790 void basic_parser_impl::printOptionInfo(const Option &O,
1791                                         size_t GlobalWidth) const {
1792   outs() << PrintArg(O.ArgStr);
1793 
1794   auto ValName = getValueName();
1795   if (!ValName.empty()) {
1796     if (O.getMiscFlags() & PositionalEatsArgs) {
1797       outs() << " <" << getValueStr(O, ValName) << ">...";
1798     } else if (O.getValueExpectedFlag() == ValueOptional)
1799       outs() << "[=<" << getValueStr(O, ValName) << ">]";
1800     else
1801       outs() << "=<" << getValueStr(O, ValName) << '>';
1802   }
1803 
1804   Option::printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
1805 }
1806 
1807 void basic_parser_impl::printOptionName(const Option &O,
1808                                         size_t GlobalWidth) const {
1809   outs() << PrintArg(O.ArgStr);
1810   outs().indent(GlobalWidth - O.ArgStr.size());
1811 }
1812 
1813 // parser<bool> implementation
1814 //
1815 bool parser<bool>::parse(Option &O, StringRef ArgName, StringRef Arg,
1816                          bool &Value) {
1817   if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1818       Arg == "1") {
1819     Value = true;
1820     return false;
1821   }
1822 
1823   if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1824     Value = false;
1825     return false;
1826   }
1827   return O.error("'" + Arg +
1828                  "' is invalid value for boolean argument! Try 0 or 1");
1829 }
1830 
1831 // parser<boolOrDefault> implementation
1832 //
1833 bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName, StringRef Arg,
1834                                   boolOrDefault &Value) {
1835   if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1836       Arg == "1") {
1837     Value = BOU_TRUE;
1838     return false;
1839   }
1840   if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1841     Value = BOU_FALSE;
1842     return false;
1843   }
1844 
1845   return O.error("'" + Arg +
1846                  "' is invalid value for boolean argument! Try 0 or 1");
1847 }
1848 
1849 // parser<int> implementation
1850 //
1851 bool parser<int>::parse(Option &O, StringRef ArgName, StringRef Arg,
1852                         int &Value) {
1853   if (Arg.getAsInteger(0, Value))
1854     return O.error("'" + Arg + "' value invalid for integer argument!");
1855   return false;
1856 }
1857 
1858 // parser<long> implementation
1859 //
1860 bool parser<long>::parse(Option &O, StringRef ArgName, StringRef Arg,
1861                          long &Value) {
1862   if (Arg.getAsInteger(0, Value))
1863     return O.error("'" + Arg + "' value invalid for long argument!");
1864   return false;
1865 }
1866 
1867 // parser<long long> implementation
1868 //
1869 bool parser<long long>::parse(Option &O, StringRef ArgName, StringRef Arg,
1870                               long long &Value) {
1871   if (Arg.getAsInteger(0, Value))
1872     return O.error("'" + Arg + "' value invalid for llong argument!");
1873   return false;
1874 }
1875 
1876 // parser<unsigned> implementation
1877 //
1878 bool parser<unsigned>::parse(Option &O, StringRef ArgName, StringRef Arg,
1879                              unsigned &Value) {
1880 
1881   if (Arg.getAsInteger(0, Value))
1882     return O.error("'" + Arg + "' value invalid for uint argument!");
1883   return false;
1884 }
1885 
1886 // parser<unsigned long> implementation
1887 //
1888 bool parser<unsigned long>::parse(Option &O, StringRef ArgName, StringRef Arg,
1889                                   unsigned long &Value) {
1890 
1891   if (Arg.getAsInteger(0, Value))
1892     return O.error("'" + Arg + "' value invalid for ulong argument!");
1893   return false;
1894 }
1895 
1896 // parser<unsigned long long> implementation
1897 //
1898 bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
1899                                        StringRef Arg,
1900                                        unsigned long long &Value) {
1901 
1902   if (Arg.getAsInteger(0, Value))
1903     return O.error("'" + Arg + "' value invalid for ullong argument!");
1904   return false;
1905 }
1906 
1907 // parser<double>/parser<float> implementation
1908 //
1909 static bool parseDouble(Option &O, StringRef Arg, double &Value) {
1910   if (to_float(Arg, Value))
1911     return false;
1912   return O.error("'" + Arg + "' value invalid for floating point argument!");
1913 }
1914 
1915 bool parser<double>::parse(Option &O, StringRef ArgName, StringRef Arg,
1916                            double &Val) {
1917   return parseDouble(O, Arg, Val);
1918 }
1919 
1920 bool parser<float>::parse(Option &O, StringRef ArgName, StringRef Arg,
1921                           float &Val) {
1922   double dVal;
1923   if (parseDouble(O, Arg, dVal))
1924     return true;
1925   Val = (float)dVal;
1926   return false;
1927 }
1928 
1929 // generic_parser_base implementation
1930 //
1931 
1932 // findOption - Return the option number corresponding to the specified
1933 // argument string.  If the option is not found, getNumOptions() is returned.
1934 //
1935 unsigned generic_parser_base::findOption(StringRef Name) {
1936   unsigned e = getNumOptions();
1937 
1938   for (unsigned i = 0; i != e; ++i) {
1939     if (getOption(i) == Name)
1940       return i;
1941   }
1942   return e;
1943 }
1944 
1945 static StringRef EqValue = "=<value>";
1946 static StringRef EmptyOption = "<empty>";
1947 static StringRef OptionPrefix = "    =";
1948 static size_t getOptionPrefixesSize() {
1949   return OptionPrefix.size() + ArgHelpPrefix.size();
1950 }
1951 
1952 static bool shouldPrintOption(StringRef Name, StringRef Description,
1953                               const Option &O) {
1954   return O.getValueExpectedFlag() != ValueOptional || !Name.empty() ||
1955          !Description.empty();
1956 }
1957 
1958 // Return the width of the option tag for printing...
1959 size_t generic_parser_base::getOptionWidth(const Option &O) const {
1960   if (O.hasArgStr()) {
1961     size_t Size =
1962         argPlusPrefixesSize(O.ArgStr) + EqValue.size();
1963     for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1964       StringRef Name = getOption(i);
1965       if (!shouldPrintOption(Name, getDescription(i), O))
1966         continue;
1967       size_t NameSize = Name.empty() ? EmptyOption.size() : Name.size();
1968       Size = std::max(Size, NameSize + getOptionPrefixesSize());
1969     }
1970     return Size;
1971   } else {
1972     size_t BaseSize = 0;
1973     for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1974       BaseSize = std::max(BaseSize, getOption(i).size() + 8);
1975     return BaseSize;
1976   }
1977 }
1978 
1979 // printOptionInfo - Print out information about this option.  The
1980 // to-be-maintained width is specified.
1981 //
1982 void generic_parser_base::printOptionInfo(const Option &O,
1983                                           size_t GlobalWidth) const {
1984   if (O.hasArgStr()) {
1985     // When the value is optional, first print a line just describing the
1986     // option without values.
1987     if (O.getValueExpectedFlag() == ValueOptional) {
1988       for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1989         if (getOption(i).empty()) {
1990           outs() << PrintArg(O.ArgStr);
1991           Option::printHelpStr(O.HelpStr, GlobalWidth,
1992                                argPlusPrefixesSize(O.ArgStr));
1993           break;
1994         }
1995       }
1996     }
1997 
1998     outs() << PrintArg(O.ArgStr) << EqValue;
1999     Option::printHelpStr(O.HelpStr, GlobalWidth,
2000                          EqValue.size() +
2001                              argPlusPrefixesSize(O.ArgStr));
2002     for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
2003       StringRef OptionName = getOption(i);
2004       StringRef Description = getDescription(i);
2005       if (!shouldPrintOption(OptionName, Description, O))
2006         continue;
2007       size_t FirstLineIndent = OptionName.size() + getOptionPrefixesSize();
2008       outs() << OptionPrefix << OptionName;
2009       if (OptionName.empty()) {
2010         outs() << EmptyOption;
2011         assert(FirstLineIndent >= EmptyOption.size());
2012         FirstLineIndent += EmptyOption.size();
2013       }
2014       if (!Description.empty())
2015         Option::printEnumValHelpStr(Description, GlobalWidth, FirstLineIndent);
2016       else
2017         outs() << '\n';
2018     }
2019   } else {
2020     if (!O.HelpStr.empty())
2021       outs() << "  " << O.HelpStr << '\n';
2022     for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
2023       StringRef Option = getOption(i);
2024       outs() << "    " << PrintArg(Option);
2025       Option::printHelpStr(getDescription(i), GlobalWidth, Option.size() + 8);
2026     }
2027   }
2028 }
2029 
2030 static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
2031 
2032 // printGenericOptionDiff - Print the value of this option and it's default.
2033 //
2034 // "Generic" options have each value mapped to a name.
2035 void generic_parser_base::printGenericOptionDiff(
2036     const Option &O, const GenericOptionValue &Value,
2037     const GenericOptionValue &Default, size_t GlobalWidth) const {
2038   outs() << "  " << PrintArg(O.ArgStr);
2039   outs().indent(GlobalWidth - O.ArgStr.size());
2040 
2041   unsigned NumOpts = getNumOptions();
2042   for (unsigned i = 0; i != NumOpts; ++i) {
2043     if (Value.compare(getOptionValue(i)))
2044       continue;
2045 
2046     outs() << "= " << getOption(i);
2047     size_t L = getOption(i).size();
2048     size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
2049     outs().indent(NumSpaces) << " (default: ";
2050     for (unsigned j = 0; j != NumOpts; ++j) {
2051       if (Default.compare(getOptionValue(j)))
2052         continue;
2053       outs() << getOption(j);
2054       break;
2055     }
2056     outs() << ")\n";
2057     return;
2058   }
2059   outs() << "= *unknown option value*\n";
2060 }
2061 
2062 // printOptionDiff - Specializations for printing basic value types.
2063 //
2064 #define PRINT_OPT_DIFF(T)                                                      \
2065   void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D,      \
2066                                   size_t GlobalWidth) const {                  \
2067     printOptionName(O, GlobalWidth);                                           \
2068     std::string Str;                                                           \
2069     {                                                                          \
2070       raw_string_ostream SS(Str);                                              \
2071       SS << V;                                                                 \
2072     }                                                                          \
2073     outs() << "= " << Str;                                                     \
2074     size_t NumSpaces =                                                         \
2075         MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0;               \
2076     outs().indent(NumSpaces) << " (default: ";                                 \
2077     if (D.hasValue())                                                          \
2078       outs() << D.getValue();                                                  \
2079     else                                                                       \
2080       outs() << "*no default*";                                                \
2081     outs() << ")\n";                                                           \
2082   }
2083 
2084 PRINT_OPT_DIFF(bool)
2085 PRINT_OPT_DIFF(boolOrDefault)
2086 PRINT_OPT_DIFF(int)
2087 PRINT_OPT_DIFF(long)
2088 PRINT_OPT_DIFF(long long)
2089 PRINT_OPT_DIFF(unsigned)
2090 PRINT_OPT_DIFF(unsigned long)
2091 PRINT_OPT_DIFF(unsigned long long)
2092 PRINT_OPT_DIFF(double)
2093 PRINT_OPT_DIFF(float)
2094 PRINT_OPT_DIFF(char)
2095 
2096 void parser<std::string>::printOptionDiff(const Option &O, StringRef V,
2097                                           const OptionValue<std::string> &D,
2098                                           size_t GlobalWidth) const {
2099   printOptionName(O, GlobalWidth);
2100   outs() << "= " << V;
2101   size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
2102   outs().indent(NumSpaces) << " (default: ";
2103   if (D.hasValue())
2104     outs() << D.getValue();
2105   else
2106     outs() << "*no default*";
2107   outs() << ")\n";
2108 }
2109 
2110 // Print a placeholder for options that don't yet support printOptionDiff().
2111 void basic_parser_impl::printOptionNoValue(const Option &O,
2112                                            size_t GlobalWidth) const {
2113   printOptionName(O, GlobalWidth);
2114   outs() << "= *cannot print option value*\n";
2115 }
2116 
2117 //===----------------------------------------------------------------------===//
2118 // -help and -help-hidden option implementation
2119 //
2120 
2121 static int OptNameCompare(const std::pair<const char *, Option *> *LHS,
2122                           const std::pair<const char *, Option *> *RHS) {
2123   return strcmp(LHS->first, RHS->first);
2124 }
2125 
2126 static int SubNameCompare(const std::pair<const char *, SubCommand *> *LHS,
2127                           const std::pair<const char *, SubCommand *> *RHS) {
2128   return strcmp(LHS->first, RHS->first);
2129 }
2130 
2131 // Copy Options into a vector so we can sort them as we like.
2132 static void sortOpts(StringMap<Option *> &OptMap,
2133                      SmallVectorImpl<std::pair<const char *, Option *>> &Opts,
2134                      bool ShowHidden) {
2135   SmallPtrSet<Option *, 32> OptionSet; // Duplicate option detection.
2136 
2137   for (StringMap<Option *>::iterator I = OptMap.begin(), E = OptMap.end();
2138        I != E; ++I) {
2139     // Ignore really-hidden options.
2140     if (I->second->getOptionHiddenFlag() == ReallyHidden)
2141       continue;
2142 
2143     // Unless showhidden is set, ignore hidden flags.
2144     if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
2145       continue;
2146 
2147     // If we've already seen this option, don't add it to the list again.
2148     if (!OptionSet.insert(I->second).second)
2149       continue;
2150 
2151     Opts.push_back(
2152         std::pair<const char *, Option *>(I->getKey().data(), I->second));
2153   }
2154 
2155   // Sort the options list alphabetically.
2156   array_pod_sort(Opts.begin(), Opts.end(), OptNameCompare);
2157 }
2158 
2159 static void
2160 sortSubCommands(const SmallPtrSetImpl<SubCommand *> &SubMap,
2161                 SmallVectorImpl<std::pair<const char *, SubCommand *>> &Subs) {
2162   for (auto *S : SubMap) {
2163     if (S->getName().empty())
2164       continue;
2165     Subs.push_back(std::make_pair(S->getName().data(), S));
2166   }
2167   array_pod_sort(Subs.begin(), Subs.end(), SubNameCompare);
2168 }
2169 
2170 namespace {
2171 
2172 class HelpPrinter {
2173 protected:
2174   const bool ShowHidden;
2175   typedef SmallVector<std::pair<const char *, Option *>, 128>
2176       StrOptionPairVector;
2177   typedef SmallVector<std::pair<const char *, SubCommand *>, 128>
2178       StrSubCommandPairVector;
2179   // Print the options. Opts is assumed to be alphabetically sorted.
2180   virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
2181     for (size_t i = 0, e = Opts.size(); i != e; ++i)
2182       Opts[i].second->printOptionInfo(MaxArgLen);
2183   }
2184 
2185   void printSubCommands(StrSubCommandPairVector &Subs, size_t MaxSubLen) {
2186     for (const auto &S : Subs) {
2187       outs() << "  " << S.first;
2188       if (!S.second->getDescription().empty()) {
2189         outs().indent(MaxSubLen - strlen(S.first));
2190         outs() << " - " << S.second->getDescription();
2191       }
2192       outs() << "\n";
2193     }
2194   }
2195 
2196 public:
2197   explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
2198   virtual ~HelpPrinter() {}
2199 
2200   // Invoke the printer.
2201   void operator=(bool Value) {
2202     if (!Value)
2203       return;
2204     printHelp();
2205 
2206     // Halt the program since help information was printed
2207     exit(0);
2208   }
2209 
2210   void printHelp() {
2211     SubCommand *Sub = GlobalParser->getActiveSubCommand();
2212     auto &OptionsMap = Sub->OptionsMap;
2213     auto &PositionalOpts = Sub->PositionalOpts;
2214     auto &ConsumeAfterOpt = Sub->ConsumeAfterOpt;
2215 
2216     StrOptionPairVector Opts;
2217     sortOpts(OptionsMap, Opts, ShowHidden);
2218 
2219     StrSubCommandPairVector Subs;
2220     sortSubCommands(GlobalParser->RegisteredSubCommands, Subs);
2221 
2222     if (!GlobalParser->ProgramOverview.empty())
2223       outs() << "OVERVIEW: " << GlobalParser->ProgramOverview << "\n";
2224 
2225     if (Sub == &*TopLevelSubCommand) {
2226       outs() << "USAGE: " << GlobalParser->ProgramName;
2227       if (Subs.size() > 2)
2228         outs() << " [subcommand]";
2229       outs() << " [options]";
2230     } else {
2231       if (!Sub->getDescription().empty()) {
2232         outs() << "SUBCOMMAND '" << Sub->getName()
2233                << "': " << Sub->getDescription() << "\n\n";
2234       }
2235       outs() << "USAGE: " << GlobalParser->ProgramName << " " << Sub->getName()
2236              << " [options]";
2237     }
2238 
2239     for (auto *Opt : PositionalOpts) {
2240       if (Opt->hasArgStr())
2241         outs() << " --" << Opt->ArgStr;
2242       outs() << " " << Opt->HelpStr;
2243     }
2244 
2245     // Print the consume after option info if it exists...
2246     if (ConsumeAfterOpt)
2247       outs() << " " << ConsumeAfterOpt->HelpStr;
2248 
2249     if (Sub == &*TopLevelSubCommand && !Subs.empty()) {
2250       // Compute the maximum subcommand length...
2251       size_t MaxSubLen = 0;
2252       for (size_t i = 0, e = Subs.size(); i != e; ++i)
2253         MaxSubLen = std::max(MaxSubLen, strlen(Subs[i].first));
2254 
2255       outs() << "\n\n";
2256       outs() << "SUBCOMMANDS:\n\n";
2257       printSubCommands(Subs, MaxSubLen);
2258       outs() << "\n";
2259       outs() << "  Type \"" << GlobalParser->ProgramName
2260              << " <subcommand> --help\" to get more help on a specific "
2261                 "subcommand";
2262     }
2263 
2264     outs() << "\n\n";
2265 
2266     // Compute the maximum argument length...
2267     size_t MaxArgLen = 0;
2268     for (size_t i = 0, e = Opts.size(); i != e; ++i)
2269       MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
2270 
2271     outs() << "OPTIONS:\n";
2272     printOptions(Opts, MaxArgLen);
2273 
2274     // Print any extra help the user has declared.
2275     for (const auto &I : GlobalParser->MoreHelp)
2276       outs() << I;
2277     GlobalParser->MoreHelp.clear();
2278   }
2279 };
2280 
2281 class CategorizedHelpPrinter : public HelpPrinter {
2282 public:
2283   explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
2284 
2285   // Helper function for printOptions().
2286   // It shall return a negative value if A's name should be lexicographically
2287   // ordered before B's name. It returns a value greater than zero if B's name
2288   // should be ordered before A's name, and it returns 0 otherwise.
2289   static int OptionCategoryCompare(OptionCategory *const *A,
2290                                    OptionCategory *const *B) {
2291     return (*A)->getName().compare((*B)->getName());
2292   }
2293 
2294   // Make sure we inherit our base class's operator=()
2295   using HelpPrinter::operator=;
2296 
2297 protected:
2298   void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override {
2299     std::vector<OptionCategory *> SortedCategories;
2300     std::map<OptionCategory *, std::vector<Option *>> CategorizedOptions;
2301 
2302     // Collect registered option categories into vector in preparation for
2303     // sorting.
2304     for (OptionCategory *Category : GlobalParser->RegisteredOptionCategories)
2305       SortedCategories.push_back(Category);
2306 
2307     // Sort the different option categories alphabetically.
2308     assert(SortedCategories.size() > 0 && "No option categories registered!");
2309     array_pod_sort(SortedCategories.begin(), SortedCategories.end(),
2310                    OptionCategoryCompare);
2311 
2312     // Create map to empty vectors.
2313     for (OptionCategory *Category : SortedCategories)
2314       CategorizedOptions[Category] = std::vector<Option *>();
2315 
2316     // Walk through pre-sorted options and assign into categories.
2317     // Because the options are already alphabetically sorted the
2318     // options within categories will also be alphabetically sorted.
2319     for (size_t I = 0, E = Opts.size(); I != E; ++I) {
2320       Option *Opt = Opts[I].second;
2321       for (auto &Cat : Opt->Categories) {
2322         assert(CategorizedOptions.count(Cat) > 0 &&
2323                "Option has an unregistered category");
2324         CategorizedOptions[Cat].push_back(Opt);
2325       }
2326     }
2327 
2328     // Now do printing.
2329     for (OptionCategory *Category : SortedCategories) {
2330       // Hide empty categories for --help, but show for --help-hidden.
2331       const auto &CategoryOptions = CategorizedOptions[Category];
2332       bool IsEmptyCategory = CategoryOptions.empty();
2333       if (!ShowHidden && IsEmptyCategory)
2334         continue;
2335 
2336       // Print category information.
2337       outs() << "\n";
2338       outs() << Category->getName() << ":\n";
2339 
2340       // Check if description is set.
2341       if (!Category->getDescription().empty())
2342         outs() << Category->getDescription() << "\n\n";
2343       else
2344         outs() << "\n";
2345 
2346       // When using --help-hidden explicitly state if the category has no
2347       // options associated with it.
2348       if (IsEmptyCategory) {
2349         outs() << "  This option category has no options.\n";
2350         continue;
2351       }
2352       // Loop over the options in the category and print.
2353       for (const Option *Opt : CategoryOptions)
2354         Opt->printOptionInfo(MaxArgLen);
2355     }
2356   }
2357 };
2358 
2359 // This wraps the Uncategorizing and Categorizing printers and decides
2360 // at run time which should be invoked.
2361 class HelpPrinterWrapper {
2362 private:
2363   HelpPrinter &UncategorizedPrinter;
2364   CategorizedHelpPrinter &CategorizedPrinter;
2365 
2366 public:
2367   explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
2368                               CategorizedHelpPrinter &CategorizedPrinter)
2369       : UncategorizedPrinter(UncategorizedPrinter),
2370         CategorizedPrinter(CategorizedPrinter) {}
2371 
2372   // Invoke the printer.
2373   void operator=(bool Value);
2374 };
2375 
2376 } // End anonymous namespace
2377 
2378 #if defined(__GNUC__)
2379 // GCC and GCC-compatible compilers define __OPTIMIZE__ when optimizations are
2380 // enabled.
2381 # if defined(__OPTIMIZE__)
2382 #  define LLVM_IS_DEBUG_BUILD 0
2383 # else
2384 #  define LLVM_IS_DEBUG_BUILD 1
2385 # endif
2386 #elif defined(_MSC_VER)
2387 // MSVC doesn't have a predefined macro indicating if optimizations are enabled.
2388 // Use _DEBUG instead. This macro actually corresponds to the choice between
2389 // debug and release CRTs, but it is a reasonable proxy.
2390 # if defined(_DEBUG)
2391 #  define LLVM_IS_DEBUG_BUILD 1
2392 # else
2393 #  define LLVM_IS_DEBUG_BUILD 0
2394 # endif
2395 #else
2396 // Otherwise, for an unknown compiler, assume this is an optimized build.
2397 # define LLVM_IS_DEBUG_BUILD 0
2398 #endif
2399 
2400 namespace {
2401 class VersionPrinter {
2402 public:
2403   void print() {
2404     raw_ostream &OS = outs();
2405 #ifdef PACKAGE_VENDOR
2406     OS << PACKAGE_VENDOR << " ";
2407 #else
2408     OS << "LLVM (http://llvm.org/):\n  ";
2409 #endif
2410     OS << PACKAGE_NAME << " version " << PACKAGE_VERSION;
2411 #ifdef LLVM_VERSION_INFO
2412     OS << " " << LLVM_VERSION_INFO;
2413 #endif
2414     OS << "\n  ";
2415 #if LLVM_IS_DEBUG_BUILD
2416     OS << "DEBUG build";
2417 #else
2418     OS << "Optimized build";
2419 #endif
2420 #ifndef NDEBUG
2421     OS << " with assertions";
2422 #endif
2423 #if LLVM_VERSION_PRINTER_SHOW_HOST_TARGET_INFO
2424     std::string CPU = std::string(sys::getHostCPUName());
2425     if (CPU == "generic")
2426       CPU = "(unknown)";
2427     OS << ".\n"
2428        << "  Default target: " << sys::getDefaultTargetTriple() << '\n'
2429        << "  Host CPU: " << CPU;
2430 #endif
2431     OS << '\n';
2432   }
2433   void operator=(bool OptionWasSpecified);
2434 };
2435 
2436 struct CommandLineCommonOptions {
2437   // Declare the four HelpPrinter instances that are used to print out help, or
2438   // help-hidden as an uncategorized list or in categories.
2439   HelpPrinter UncategorizedNormalPrinter{false};
2440   HelpPrinter UncategorizedHiddenPrinter{true};
2441   CategorizedHelpPrinter CategorizedNormalPrinter{false};
2442   CategorizedHelpPrinter CategorizedHiddenPrinter{true};
2443   // Declare HelpPrinter wrappers that will decide whether or not to invoke
2444   // a categorizing help printer
2445   HelpPrinterWrapper WrappedNormalPrinter{UncategorizedNormalPrinter,
2446                                           CategorizedNormalPrinter};
2447   HelpPrinterWrapper WrappedHiddenPrinter{UncategorizedHiddenPrinter,
2448                                           CategorizedHiddenPrinter};
2449   // Define a category for generic options that all tools should have.
2450   cl::OptionCategory GenericCategory{"Generic Options"};
2451 
2452   // Define uncategorized help printers.
2453   // --help-list is hidden by default because if Option categories are being
2454   // used then --help behaves the same as --help-list.
2455   cl::opt<HelpPrinter, true, parser<bool>> HLOp{
2456       "help-list",
2457       cl::desc(
2458           "Display list of available options (--help-list-hidden for more)"),
2459       cl::location(UncategorizedNormalPrinter),
2460       cl::Hidden,
2461       cl::ValueDisallowed,
2462       cl::cat(GenericCategory),
2463       cl::sub(*AllSubCommands)};
2464 
2465   cl::opt<HelpPrinter, true, parser<bool>> HLHOp{
2466       "help-list-hidden",
2467       cl::desc("Display list of all available options"),
2468       cl::location(UncategorizedHiddenPrinter),
2469       cl::Hidden,
2470       cl::ValueDisallowed,
2471       cl::cat(GenericCategory),
2472       cl::sub(*AllSubCommands)};
2473 
2474   // Define uncategorized/categorized help printers. These printers change their
2475   // behaviour at runtime depending on whether one or more Option categories
2476   // have been declared.
2477   cl::opt<HelpPrinterWrapper, true, parser<bool>> HOp{
2478       "help",
2479       cl::desc("Display available options (--help-hidden for more)"),
2480       cl::location(WrappedNormalPrinter),
2481       cl::ValueDisallowed,
2482       cl::cat(GenericCategory),
2483       cl::sub(*AllSubCommands)};
2484 
2485   cl::alias HOpA{"h", cl::desc("Alias for --help"), cl::aliasopt(HOp),
2486                  cl::DefaultOption};
2487 
2488   cl::opt<HelpPrinterWrapper, true, parser<bool>> HHOp{
2489       "help-hidden",
2490       cl::desc("Display all available options"),
2491       cl::location(WrappedHiddenPrinter),
2492       cl::Hidden,
2493       cl::ValueDisallowed,
2494       cl::cat(GenericCategory),
2495       cl::sub(*AllSubCommands)};
2496 
2497   cl::opt<bool> PrintOptions{
2498       "print-options",
2499       cl::desc("Print non-default options after command line parsing"),
2500       cl::Hidden,
2501       cl::init(false),
2502       cl::cat(GenericCategory),
2503       cl::sub(*AllSubCommands)};
2504 
2505   cl::opt<bool> PrintAllOptions{
2506       "print-all-options",
2507       cl::desc("Print all option values after command line parsing"),
2508       cl::Hidden,
2509       cl::init(false),
2510       cl::cat(GenericCategory),
2511       cl::sub(*AllSubCommands)};
2512 
2513   VersionPrinterTy OverrideVersionPrinter = nullptr;
2514 
2515   std::vector<VersionPrinterTy> ExtraVersionPrinters;
2516 
2517   // Define the --version option that prints out the LLVM version for the tool
2518   VersionPrinter VersionPrinterInstance;
2519 
2520   cl::opt<VersionPrinter, true, parser<bool>> VersOp{
2521       "version", cl::desc("Display the version of this program"),
2522       cl::location(VersionPrinterInstance), cl::ValueDisallowed,
2523       cl::cat(GenericCategory)};
2524 };
2525 } // End anonymous namespace
2526 
2527 // Lazy-initialized global instance of options controlling the command-line
2528 // parser and general handling.
2529 static ManagedStatic<CommandLineCommonOptions> CommonOptions;
2530 
2531 static void initCommonOptions() {
2532   *CommonOptions;
2533   initDebugCounterOptions();
2534   initGraphWriterOptions();
2535   initSignalsOptions();
2536   initStatisticOptions();
2537   initTimerOptions();
2538   initTypeSizeOptions();
2539   initWithColorOptions();
2540   initDebugOptions();
2541   initRandomSeedOptions();
2542 }
2543 
2544 OptionCategory &cl::getGeneralCategory() {
2545   // Initialise the general option category.
2546   static OptionCategory GeneralCategory{"General options"};
2547   return GeneralCategory;
2548 }
2549 
2550 void VersionPrinter::operator=(bool OptionWasSpecified) {
2551   if (!OptionWasSpecified)
2552     return;
2553 
2554   if (CommonOptions->OverrideVersionPrinter != nullptr) {
2555     CommonOptions->OverrideVersionPrinter(outs());
2556     exit(0);
2557   }
2558   print();
2559 
2560   // Iterate over any registered extra printers and call them to add further
2561   // information.
2562   if (!CommonOptions->ExtraVersionPrinters.empty()) {
2563     outs() << '\n';
2564     for (const auto &I : CommonOptions->ExtraVersionPrinters)
2565       I(outs());
2566   }
2567 
2568   exit(0);
2569 }
2570 
2571 void HelpPrinterWrapper::operator=(bool Value) {
2572   if (!Value)
2573     return;
2574 
2575   // Decide which printer to invoke. If more than one option category is
2576   // registered then it is useful to show the categorized help instead of
2577   // uncategorized help.
2578   if (GlobalParser->RegisteredOptionCategories.size() > 1) {
2579     // unhide --help-list option so user can have uncategorized output if they
2580     // want it.
2581     CommonOptions->HLOp.setHiddenFlag(NotHidden);
2582 
2583     CategorizedPrinter = true; // Invoke categorized printer
2584   } else
2585     UncategorizedPrinter = true; // Invoke uncategorized printer
2586 }
2587 
2588 // Print the value of each option.
2589 void cl::PrintOptionValues() { GlobalParser->printOptionValues(); }
2590 
2591 void CommandLineParser::printOptionValues() {
2592   if (!CommonOptions->PrintOptions && !CommonOptions->PrintAllOptions)
2593     return;
2594 
2595   SmallVector<std::pair<const char *, Option *>, 128> Opts;
2596   sortOpts(ActiveSubCommand->OptionsMap, Opts, /*ShowHidden*/ true);
2597 
2598   // Compute the maximum argument length...
2599   size_t MaxArgLen = 0;
2600   for (size_t i = 0, e = Opts.size(); i != e; ++i)
2601     MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
2602 
2603   for (size_t i = 0, e = Opts.size(); i != e; ++i)
2604     Opts[i].second->printOptionValue(MaxArgLen, CommonOptions->PrintAllOptions);
2605 }
2606 
2607 // Utility function for printing the help message.
2608 void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
2609   if (!Hidden && !Categorized)
2610     CommonOptions->UncategorizedNormalPrinter.printHelp();
2611   else if (!Hidden && Categorized)
2612     CommonOptions->CategorizedNormalPrinter.printHelp();
2613   else if (Hidden && !Categorized)
2614     CommonOptions->UncategorizedHiddenPrinter.printHelp();
2615   else
2616     CommonOptions->CategorizedHiddenPrinter.printHelp();
2617 }
2618 
2619 /// Utility function for printing version number.
2620 void cl::PrintVersionMessage() {
2621   CommonOptions->VersionPrinterInstance.print();
2622 }
2623 
2624 void cl::SetVersionPrinter(VersionPrinterTy func) {
2625   CommonOptions->OverrideVersionPrinter = func;
2626 }
2627 
2628 void cl::AddExtraVersionPrinter(VersionPrinterTy func) {
2629   CommonOptions->ExtraVersionPrinters.push_back(func);
2630 }
2631 
2632 StringMap<Option *> &cl::getRegisteredOptions(SubCommand &Sub) {
2633   initCommonOptions();
2634   auto &Subs = GlobalParser->RegisteredSubCommands;
2635   (void)Subs;
2636   assert(is_contained(Subs, &Sub));
2637   return Sub.OptionsMap;
2638 }
2639 
2640 iterator_range<typename SmallPtrSet<SubCommand *, 4>::iterator>
2641 cl::getRegisteredSubcommands() {
2642   return GlobalParser->getRegisteredSubcommands();
2643 }
2644 
2645 void cl::HideUnrelatedOptions(cl::OptionCategory &Category, SubCommand &Sub) {
2646   initCommonOptions();
2647   for (auto &I : Sub.OptionsMap) {
2648     bool Unrelated = true;
2649     for (auto &Cat : I.second->Categories) {
2650       if (Cat == &Category || Cat == &CommonOptions->GenericCategory)
2651         Unrelated = false;
2652     }
2653     if (Unrelated)
2654       I.second->setHiddenFlag(cl::ReallyHidden);
2655   }
2656 }
2657 
2658 void cl::HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories,
2659                               SubCommand &Sub) {
2660   initCommonOptions();
2661   for (auto &I : Sub.OptionsMap) {
2662     bool Unrelated = true;
2663     for (auto &Cat : I.second->Categories) {
2664       if (is_contained(Categories, Cat) ||
2665           Cat == &CommonOptions->GenericCategory)
2666         Unrelated = false;
2667     }
2668     if (Unrelated)
2669       I.second->setHiddenFlag(cl::ReallyHidden);
2670   }
2671 }
2672 
2673 void cl::ResetCommandLineParser() { GlobalParser->reset(); }
2674 void cl::ResetAllOptionOccurrences() {
2675   GlobalParser->ResetAllOptionOccurrences();
2676 }
2677 
2678 void LLVMParseCommandLineOptions(int argc, const char *const *argv,
2679                                  const char *Overview) {
2680   llvm::cl::ParseCommandLineOptions(argc, argv, StringRef(Overview),
2681                                     &llvm::nulls());
2682 }
2683