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