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