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