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

Generated by: LCOV version 1.13