LCOV - code coverage report
Current view: top level - lib/Support - CommandLine.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 737 915 80.5 %
Date: 2018-07-13 00:08:38 Functions: 87 118 73.7 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.13