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