LLVM API Documentation

CommandLine.cpp
Go to the documentation of this file.
00001 //===-- CommandLine.cpp - Command line parser implementation --------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This class implements a command line argument processor that is useful when
00011 // creating a tool.  It provides a simple, minimalistic interface that is easily
00012 // extensible and supports nonlocal (library) command line options.
00013 //
00014 // Note that rather than trying to figure out what this code does, you could try
00015 // reading the library documentation located in docs/CommandLine.html
00016 //
00017 //===----------------------------------------------------------------------===//
00018 
00019 #include "llvm/Support/CommandLine.h"
00020 #include "llvm/ADT/ArrayRef.h"
00021 #include "llvm/ADT/SmallPtrSet.h"
00022 #include "llvm/ADT/SmallString.h"
00023 #include "llvm/ADT/StringMap.h"
00024 #include "llvm/ADT/Twine.h"
00025 #include "llvm/Config/config.h"
00026 #include "llvm/Support/ConvertUTF.h"
00027 #include "llvm/Support/Debug.h"
00028 #include "llvm/Support/ErrorHandling.h"
00029 #include "llvm/Support/Host.h"
00030 #include "llvm/Support/ManagedStatic.h"
00031 #include "llvm/Support/MemoryBuffer.h"
00032 #include "llvm/Support/Path.h"
00033 #include "llvm/Support/raw_ostream.h"
00034 #include <cerrno>
00035 #include <cstdlib>
00036 #include <map>
00037 #include <system_error>
00038 using namespace llvm;
00039 using namespace cl;
00040 
00041 #define DEBUG_TYPE "commandline"
00042 
00043 //===----------------------------------------------------------------------===//
00044 // Template instantiations and anchors.
00045 //
00046 namespace llvm { namespace cl {
00047 TEMPLATE_INSTANTIATION(class basic_parser<bool>);
00048 TEMPLATE_INSTANTIATION(class basic_parser<boolOrDefault>);
00049 TEMPLATE_INSTANTIATION(class basic_parser<int>);
00050 TEMPLATE_INSTANTIATION(class basic_parser<unsigned>);
00051 TEMPLATE_INSTANTIATION(class basic_parser<unsigned long long>);
00052 TEMPLATE_INSTANTIATION(class basic_parser<double>);
00053 TEMPLATE_INSTANTIATION(class basic_parser<float>);
00054 TEMPLATE_INSTANTIATION(class basic_parser<std::string>);
00055 TEMPLATE_INSTANTIATION(class basic_parser<char>);
00056 
00057 TEMPLATE_INSTANTIATION(class opt<unsigned>);
00058 TEMPLATE_INSTANTIATION(class opt<int>);
00059 TEMPLATE_INSTANTIATION(class opt<std::string>);
00060 TEMPLATE_INSTANTIATION(class opt<char>);
00061 TEMPLATE_INSTANTIATION(class opt<bool>);
00062 } } // end namespace llvm::cl
00063 
00064 // Pin the vtables to this file.
00065 void GenericOptionValue::anchor() {}
00066 void OptionValue<boolOrDefault>::anchor() {}
00067 void OptionValue<std::string>::anchor() {}
00068 void Option::anchor() {}
00069 void basic_parser_impl::anchor() {}
00070 void parser<bool>::anchor() {}
00071 void parser<boolOrDefault>::anchor() {}
00072 void parser<int>::anchor() {}
00073 void parser<unsigned>::anchor() {}
00074 void parser<unsigned long long>::anchor() {}
00075 void parser<double>::anchor() {}
00076 void parser<float>::anchor() {}
00077 void parser<std::string>::anchor() {}
00078 void parser<char>::anchor() {}
00079 void StringSaver::anchor() {}
00080 
00081 //===----------------------------------------------------------------------===//
00082 
00083 // Globals for name and overview of program.  Program name is not a string to
00084 // avoid static ctor/dtor issues.
00085 static char ProgramName[80] = "<premain>";
00086 static const char *ProgramOverview = nullptr;
00087 
00088 // This collects additional help to be printed.
00089 static ManagedStatic<std::vector<const char*> > MoreHelp;
00090 
00091 extrahelp::extrahelp(const char *Help)
00092   : morehelp(Help) {
00093   MoreHelp->push_back(Help);
00094 }
00095 
00096 static bool OptionListChanged = false;
00097 
00098 // MarkOptionsChanged - Internal helper function.
00099 void cl::MarkOptionsChanged() {
00100   OptionListChanged = true;
00101 }
00102 
00103 /// RegisteredOptionList - This is the list of the command line options that
00104 /// have statically constructed themselves.
00105 static Option *RegisteredOptionList = nullptr;
00106 
00107 void Option::addArgument() {
00108   assert(!NextRegistered && "argument multiply registered!");
00109 
00110   NextRegistered = RegisteredOptionList;
00111   RegisteredOptionList = this;
00112   MarkOptionsChanged();
00113 }
00114 
00115 void Option::removeArgument() {
00116   assert(NextRegistered && "argument never registered");
00117   assert(RegisteredOptionList == this && "argument is not the last registered");
00118   RegisteredOptionList = NextRegistered;
00119   MarkOptionsChanged();
00120 }
00121 
00122 // This collects the different option categories that have been registered.
00123 typedef SmallPtrSet<OptionCategory*,16> OptionCatSet;
00124 static ManagedStatic<OptionCatSet> RegisteredOptionCategories;
00125 
00126 // Initialise the general option category.
00127 OptionCategory llvm::cl::GeneralCategory("General options");
00128 
00129 void OptionCategory::registerCategory() {
00130   assert(std::count_if(RegisteredOptionCategories->begin(),
00131                        RegisteredOptionCategories->end(),
00132                        [this](const OptionCategory *Category) {
00133                          return getName() == Category->getName();
00134                        }) == 0 && "Duplicate option categories");
00135 
00136   RegisteredOptionCategories->insert(this);
00137 }
00138 
00139 //===----------------------------------------------------------------------===//
00140 // Basic, shared command line option processing machinery.
00141 //
00142 
00143 /// GetOptionInfo - Scan the list of registered options, turning them into data
00144 /// structures that are easier to handle.
00145 static void GetOptionInfo(SmallVectorImpl<Option*> &PositionalOpts,
00146                           SmallVectorImpl<Option*> &SinkOpts,
00147                           StringMap<Option*> &OptionsMap) {
00148   bool HadErrors = false;
00149   SmallVector<const char*, 16> OptionNames;
00150   Option *CAOpt = nullptr;  // The ConsumeAfter option if it exists.
00151   for (Option *O = RegisteredOptionList; O; O = O->getNextRegisteredOption()) {
00152     // If this option wants to handle multiple option names, get the full set.
00153     // This handles enum options like "-O1 -O2" etc.
00154     O->getExtraOptionNames(OptionNames);
00155     if (O->ArgStr[0])
00156       OptionNames.push_back(O->ArgStr);
00157 
00158     // Handle named options.
00159     for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
00160       // Add argument to the argument map!
00161       if (OptionsMap.GetOrCreateValue(OptionNames[i], O).second != O) {
00162         errs() << ProgramName << ": CommandLine Error: Option '"
00163                << OptionNames[i] << "' registered more than once!\n";
00164         HadErrors = true;
00165       }
00166     }
00167 
00168     OptionNames.clear();
00169 
00170     // Remember information about positional options.
00171     if (O->getFormattingFlag() == cl::Positional)
00172       PositionalOpts.push_back(O);
00173     else if (O->getMiscFlags() & cl::Sink) // Remember sink options
00174       SinkOpts.push_back(O);
00175     else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
00176       if (CAOpt) {
00177         O->error("Cannot specify more than one option with cl::ConsumeAfter!");
00178         HadErrors = true;
00179       }
00180       CAOpt = O;
00181     }
00182   }
00183 
00184   if (CAOpt)
00185     PositionalOpts.push_back(CAOpt);
00186 
00187   // Make sure that they are in order of registration not backwards.
00188   std::reverse(PositionalOpts.begin(), PositionalOpts.end());
00189 
00190   // Fail hard if there were errors. These are strictly unrecoverable and
00191   // indicate serious issues such as conflicting option names or an incorrectly
00192   // linked LLVM distribution.
00193   if (HadErrors)
00194     report_fatal_error("inconsistency in registered CommandLine options");
00195 }
00196 
00197 
00198 /// LookupOption - Lookup the option specified by the specified option on the
00199 /// command line.  If there is a value specified (after an equal sign) return
00200 /// that as well.  This assumes that leading dashes have already been stripped.
00201 static Option *LookupOption(StringRef &Arg, StringRef &Value,
00202                             const StringMap<Option*> &OptionsMap) {
00203   // Reject all dashes.
00204   if (Arg.empty()) return nullptr;
00205 
00206   size_t EqualPos = Arg.find('=');
00207 
00208   // If we have an equals sign, remember the value.
00209   if (EqualPos == StringRef::npos) {
00210     // Look up the option.
00211     StringMap<Option*>::const_iterator I = OptionsMap.find(Arg);
00212     return I != OptionsMap.end() ? I->second : nullptr;
00213   }
00214 
00215   // If the argument before the = is a valid option name, we match.  If not,
00216   // return Arg unmolested.
00217   StringMap<Option*>::const_iterator I =
00218     OptionsMap.find(Arg.substr(0, EqualPos));
00219   if (I == OptionsMap.end()) return nullptr;
00220 
00221   Value = Arg.substr(EqualPos+1);
00222   Arg = Arg.substr(0, EqualPos);
00223   return I->second;
00224 }
00225 
00226 /// LookupNearestOption - Lookup the closest match to the option specified by
00227 /// the specified option on the command line.  If there is a value specified
00228 /// (after an equal sign) return that as well.  This assumes that leading dashes
00229 /// have already been stripped.
00230 static Option *LookupNearestOption(StringRef Arg,
00231                                    const StringMap<Option*> &OptionsMap,
00232                                    std::string &NearestString) {
00233   // Reject all dashes.
00234   if (Arg.empty()) return nullptr;
00235 
00236   // Split on any equal sign.
00237   std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
00238   StringRef &LHS = SplitArg.first;  // LHS == Arg when no '=' is present.
00239   StringRef &RHS = SplitArg.second;
00240 
00241   // Find the closest match.
00242   Option *Best = nullptr;
00243   unsigned BestDistance = 0;
00244   for (StringMap<Option*>::const_iterator it = OptionsMap.begin(),
00245          ie = OptionsMap.end(); it != ie; ++it) {
00246     Option *O = it->second;
00247     SmallVector<const char*, 16> OptionNames;
00248     O->getExtraOptionNames(OptionNames);
00249     if (O->ArgStr[0])
00250       OptionNames.push_back(O->ArgStr);
00251 
00252     bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
00253     StringRef Flag = PermitValue ? LHS : Arg;
00254     for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
00255       StringRef Name = OptionNames[i];
00256       unsigned Distance = StringRef(Name).edit_distance(
00257         Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
00258       if (!Best || Distance < BestDistance) {
00259         Best = O;
00260         BestDistance = Distance;
00261         if (RHS.empty() || !PermitValue)
00262           NearestString = OptionNames[i];
00263         else
00264           NearestString = std::string(OptionNames[i]) + "=" + RHS.str();
00265       }
00266     }
00267   }
00268 
00269   return Best;
00270 }
00271 
00272 /// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence()
00273 /// that does special handling of cl::CommaSeparated options.
00274 static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos,
00275                                           StringRef ArgName, StringRef Value,
00276                                           bool MultiArg = false) {
00277   // Check to see if this option accepts a comma separated list of values.  If
00278   // it does, we have to split up the value into multiple values.
00279   if (Handler->getMiscFlags() & CommaSeparated) {
00280     StringRef Val(Value);
00281     StringRef::size_type Pos = Val.find(',');
00282 
00283     while (Pos != StringRef::npos) {
00284       // Process the portion before the comma.
00285       if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
00286         return true;
00287       // Erase the portion before the comma, AND the comma.
00288       Val = Val.substr(Pos+1);
00289       Value.substr(Pos+1);  // Increment the original value pointer as well.
00290       // Check for another comma.
00291       Pos = Val.find(',');
00292     }
00293 
00294     Value = Val;
00295   }
00296 
00297   if (Handler->addOccurrence(pos, ArgName, Value, MultiArg))
00298     return true;
00299 
00300   return false;
00301 }
00302 
00303 /// ProvideOption - For Value, this differentiates between an empty value ("")
00304 /// and a null value (StringRef()).  The later is accepted for arguments that
00305 /// don't allow a value (-foo) the former is rejected (-foo=).
00306 static inline bool ProvideOption(Option *Handler, StringRef ArgName,
00307                                  StringRef Value, int argc,
00308                                  const char *const *argv, int &i) {
00309   // Is this a multi-argument option?
00310   unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
00311 
00312   // Enforce value requirements
00313   switch (Handler->getValueExpectedFlag()) {
00314   case ValueRequired:
00315     if (!Value.data()) { // No value specified?
00316       if (i+1 >= argc)
00317         return Handler->error("requires a value!");
00318       // Steal the next argument, like for '-o filename'
00319       Value = argv[++i];
00320     }
00321     break;
00322   case ValueDisallowed:
00323     if (NumAdditionalVals > 0)
00324       return Handler->error("multi-valued option specified"
00325                             " with ValueDisallowed modifier!");
00326 
00327     if (Value.data())
00328       return Handler->error("does not allow a value! '" +
00329                             Twine(Value) + "' specified.");
00330     break;
00331   case ValueOptional:
00332     break;
00333   }
00334 
00335   // If this isn't a multi-arg option, just run the handler.
00336   if (NumAdditionalVals == 0)
00337     return CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value);
00338 
00339   // If it is, run the handle several times.
00340   bool MultiArg = false;
00341 
00342   if (Value.data()) {
00343     if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
00344       return true;
00345     --NumAdditionalVals;
00346     MultiArg = true;
00347   }
00348 
00349   while (NumAdditionalVals > 0) {
00350     if (i+1 >= argc)
00351       return Handler->error("not enough values!");
00352     Value = argv[++i];
00353 
00354     if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
00355       return true;
00356     MultiArg = true;
00357     --NumAdditionalVals;
00358   }
00359   return false;
00360 }
00361 
00362 static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
00363   int Dummy = i;
00364   return ProvideOption(Handler, Handler->ArgStr, Arg, 0, nullptr, Dummy);
00365 }
00366 
00367 
00368 // Option predicates...
00369 static inline bool isGrouping(const Option *O) {
00370   return O->getFormattingFlag() == cl::Grouping;
00371 }
00372 static inline bool isPrefixedOrGrouping(const Option *O) {
00373   return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
00374 }
00375 
00376 // getOptionPred - Check to see if there are any options that satisfy the
00377 // specified predicate with names that are the prefixes in Name.  This is
00378 // checked by progressively stripping characters off of the name, checking to
00379 // see if there options that satisfy the predicate.  If we find one, return it,
00380 // otherwise return null.
00381 //
00382 static Option *getOptionPred(StringRef Name, size_t &Length,
00383                              bool (*Pred)(const Option*),
00384                              const StringMap<Option*> &OptionsMap) {
00385 
00386   StringMap<Option*>::const_iterator OMI = OptionsMap.find(Name);
00387 
00388   // Loop while we haven't found an option and Name still has at least two
00389   // characters in it (so that the next iteration will not be the empty
00390   // string.
00391   while (OMI == OptionsMap.end() && Name.size() > 1) {
00392     Name = Name.substr(0, Name.size()-1);   // Chop off the last character.
00393     OMI = OptionsMap.find(Name);
00394   }
00395 
00396   if (OMI != OptionsMap.end() && Pred(OMI->second)) {
00397     Length = Name.size();
00398     return OMI->second;    // Found one!
00399   }
00400   return nullptr;          // No option found!
00401 }
00402 
00403 /// HandlePrefixedOrGroupedOption - The specified argument string (which started
00404 /// with at least one '-') does not fully match an available option.  Check to
00405 /// see if this is a prefix or grouped option.  If so, split arg into output an
00406 /// Arg/Value pair and return the Option to parse it with.
00407 static Option *HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
00408                                              bool &ErrorParsing,
00409                                          const StringMap<Option*> &OptionsMap) {
00410   if (Arg.size() == 1) return nullptr;
00411 
00412   // Do the lookup!
00413   size_t Length = 0;
00414   Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
00415   if (!PGOpt) return nullptr;
00416 
00417   // If the option is a prefixed option, then the value is simply the
00418   // rest of the name...  so fall through to later processing, by
00419   // setting up the argument name flags and value fields.
00420   if (PGOpt->getFormattingFlag() == cl::Prefix) {
00421     Value = Arg.substr(Length);
00422     Arg = Arg.substr(0, Length);
00423     assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
00424     return PGOpt;
00425   }
00426 
00427   // This must be a grouped option... handle them now.  Grouping options can't
00428   // have values.
00429   assert(isGrouping(PGOpt) && "Broken getOptionPred!");
00430 
00431   do {
00432     // Move current arg name out of Arg into OneArgName.
00433     StringRef OneArgName = Arg.substr(0, Length);
00434     Arg = Arg.substr(Length);
00435 
00436     // Because ValueRequired is an invalid flag for grouped arguments,
00437     // we don't need to pass argc/argv in.
00438     assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
00439            "Option can not be cl::Grouping AND cl::ValueRequired!");
00440     int Dummy = 0;
00441     ErrorParsing |= ProvideOption(PGOpt, OneArgName,
00442                                   StringRef(), 0, nullptr, Dummy);
00443 
00444     // Get the next grouping option.
00445     PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
00446   } while (PGOpt && Length != Arg.size());
00447 
00448   // Return the last option with Arg cut down to just the last one.
00449   return PGOpt;
00450 }
00451 
00452 
00453 
00454 static bool RequiresValue(const Option *O) {
00455   return O->getNumOccurrencesFlag() == cl::Required ||
00456          O->getNumOccurrencesFlag() == cl::OneOrMore;
00457 }
00458 
00459 static bool EatsUnboundedNumberOfValues(const Option *O) {
00460   return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
00461          O->getNumOccurrencesFlag() == cl::OneOrMore;
00462 }
00463 
00464 static bool isWhitespace(char C) {
00465   return strchr(" \t\n\r\f\v", C);
00466 }
00467 
00468 static bool isQuote(char C) {
00469   return C == '\"' || C == '\'';
00470 }
00471 
00472 static bool isGNUSpecial(char C) {
00473   return strchr("\\\"\' ", C);
00474 }
00475 
00476 void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
00477                                 SmallVectorImpl<const char *> &NewArgv,
00478                                 bool MarkEOLs) {
00479   SmallString<128> Token;
00480   for (size_t I = 0, E = Src.size(); I != E; ++I) {
00481     // Consume runs of whitespace.
00482     if (Token.empty()) {
00483       while (I != E && isWhitespace(Src[I])) {
00484         // Mark the end of lines in response files
00485         if (MarkEOLs && Src[I] == '\n')
00486           NewArgv.push_back(nullptr);
00487         ++I;
00488       }
00489       if (I == E) break;
00490     }
00491 
00492     // Backslashes can escape backslashes, spaces, and other quotes.  Otherwise
00493     // they are literal.  This makes it much easier to read Windows file paths.
00494     if (I + 1 < E && Src[I] == '\\' && isGNUSpecial(Src[I + 1])) {
00495       ++I;  // Skip the escape.
00496       Token.push_back(Src[I]);
00497       continue;
00498     }
00499 
00500     // Consume a quoted string.
00501     if (isQuote(Src[I])) {
00502       char Quote = Src[I++];
00503       while (I != E && Src[I] != Quote) {
00504         // Backslashes are literal, unless they escape a special character.
00505         if (Src[I] == '\\' && I + 1 != E && isGNUSpecial(Src[I + 1]))
00506           ++I;
00507         Token.push_back(Src[I]);
00508         ++I;
00509       }
00510       if (I == E) break;
00511       continue;
00512     }
00513 
00514     // End the token if this is whitespace.
00515     if (isWhitespace(Src[I])) {
00516       if (!Token.empty())
00517         NewArgv.push_back(Saver.SaveString(Token.c_str()));
00518       Token.clear();
00519       continue;
00520     }
00521 
00522     // This is a normal character.  Append it.
00523     Token.push_back(Src[I]);
00524   }
00525 
00526   // Append the last token after hitting EOF with no whitespace.
00527   if (!Token.empty())
00528     NewArgv.push_back(Saver.SaveString(Token.c_str()));
00529   // Mark the end of response files
00530   if (MarkEOLs)
00531     NewArgv.push_back(nullptr);
00532 }
00533 
00534 /// Backslashes are interpreted in a rather complicated way in the Windows-style
00535 /// command line, because backslashes are used both to separate path and to
00536 /// escape double quote. This method consumes runs of backslashes as well as the
00537 /// following double quote if it's escaped.
00538 ///
00539 ///  * If an even number of backslashes is followed by a double quote, one
00540 ///    backslash is output for every pair of backslashes, and the last double
00541 ///    quote remains unconsumed. The double quote will later be interpreted as
00542 ///    the start or end of a quoted string in the main loop outside of this
00543 ///    function.
00544 ///
00545 ///  * If an odd number of backslashes is followed by a double quote, one
00546 ///    backslash is output for every pair of backslashes, and a double quote is
00547 ///    output for the last pair of backslash-double quote. The double quote is
00548 ///    consumed in this case.
00549 ///
00550 ///  * Otherwise, backslashes are interpreted literally.
00551 static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
00552   size_t E = Src.size();
00553   int BackslashCount = 0;
00554   // Skip the backslashes.
00555   do {
00556     ++I;
00557     ++BackslashCount;
00558   } while (I != E && Src[I] == '\\');
00559 
00560   bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
00561   if (FollowedByDoubleQuote) {
00562     Token.append(BackslashCount / 2, '\\');
00563     if (BackslashCount % 2 == 0)
00564       return I - 1;
00565     Token.push_back('"');
00566     return I;
00567   }
00568   Token.append(BackslashCount, '\\');
00569   return I - 1;
00570 }
00571 
00572 void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
00573                                     SmallVectorImpl<const char *> &NewArgv,
00574                                     bool MarkEOLs) {
00575   SmallString<128> Token;
00576 
00577   // This is a small state machine to consume characters until it reaches the
00578   // end of the source string.
00579   enum { INIT, UNQUOTED, QUOTED } State = INIT;
00580   for (size_t I = 0, E = Src.size(); I != E; ++I) {
00581     // INIT state indicates that the current input index is at the start of
00582     // the string or between tokens.
00583     if (State == INIT) {
00584       if (isWhitespace(Src[I])) {
00585         // Mark the end of lines in response files
00586         if (MarkEOLs && Src[I] == '\n')
00587           NewArgv.push_back(nullptr);
00588         continue;
00589       }
00590       if (Src[I] == '"') {
00591         State = QUOTED;
00592         continue;
00593       }
00594       if (Src[I] == '\\') {
00595         I = parseBackslash(Src, I, Token);
00596         State = UNQUOTED;
00597         continue;
00598       }
00599       Token.push_back(Src[I]);
00600       State = UNQUOTED;
00601       continue;
00602     }
00603 
00604     // UNQUOTED state means that it's reading a token not quoted by double
00605     // quotes.
00606     if (State == UNQUOTED) {
00607       // Whitespace means the end of the token.
00608       if (isWhitespace(Src[I])) {
00609         NewArgv.push_back(Saver.SaveString(Token.c_str()));
00610         Token.clear();
00611         State = INIT;
00612         // Mark the end of lines in response files
00613         if (MarkEOLs && Src[I] == '\n')
00614           NewArgv.push_back(nullptr);
00615         continue;
00616       }
00617       if (Src[I] == '"') {
00618         State = QUOTED;
00619         continue;
00620       }
00621       if (Src[I] == '\\') {
00622         I = parseBackslash(Src, I, Token);
00623         continue;
00624       }
00625       Token.push_back(Src[I]);
00626       continue;
00627     }
00628 
00629     // QUOTED state means that it's reading a token quoted by double quotes.
00630     if (State == QUOTED) {
00631       if (Src[I] == '"') {
00632         State = UNQUOTED;
00633         continue;
00634       }
00635       if (Src[I] == '\\') {
00636         I = parseBackslash(Src, I, Token);
00637         continue;
00638       }
00639       Token.push_back(Src[I]);
00640     }
00641   }
00642   // Append the last token after hitting EOF with no whitespace.
00643   if (!Token.empty())
00644     NewArgv.push_back(Saver.SaveString(Token.c_str()));
00645   // Mark the end of response files
00646   if (MarkEOLs)
00647     NewArgv.push_back(nullptr);
00648 }
00649 
00650 static bool ExpandResponseFile(const char *FName, StringSaver &Saver,
00651                                TokenizerCallback Tokenizer,
00652                                SmallVectorImpl<const char *> &NewArgv,
00653                                bool MarkEOLs = false) {
00654   ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
00655       MemoryBuffer::getFile(FName);
00656   if (!MemBufOrErr)
00657     return false;
00658   MemoryBuffer &MemBuf = *MemBufOrErr.get();
00659   StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize());
00660 
00661   // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
00662   ArrayRef<char> BufRef(MemBuf.getBufferStart(), MemBuf.getBufferEnd());
00663   std::string UTF8Buf;
00664   if (hasUTF16ByteOrderMark(BufRef)) {
00665     if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
00666       return false;
00667     Str = StringRef(UTF8Buf);
00668   }
00669 
00670   // Tokenize the contents into NewArgv.
00671   Tokenizer(Str, Saver, NewArgv, MarkEOLs);
00672 
00673   return true;
00674 }
00675 
00676 /// \brief Expand response files on a command line recursively using the given
00677 /// StringSaver and tokenization strategy.
00678 bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
00679                              SmallVectorImpl<const char *> &Argv,
00680                              bool MarkEOLs) {
00681   unsigned RspFiles = 0;
00682   bool AllExpanded = true;
00683 
00684   // Don't cache Argv.size() because it can change.
00685   for (unsigned I = 0; I != Argv.size(); ) {
00686     const char *Arg = Argv[I];
00687     // Check if it is an EOL marker
00688     if (Arg == nullptr) {
00689       ++I;
00690       continue;
00691     }
00692     if (Arg[0] != '@') {
00693       ++I;
00694       continue;
00695     }
00696 
00697     // If we have too many response files, leave some unexpanded.  This avoids
00698     // crashing on self-referential response files.
00699     if (RspFiles++ > 20)
00700       return false;
00701 
00702     // Replace this response file argument with the tokenization of its
00703     // contents.  Nested response files are expanded in subsequent iterations.
00704     // FIXME: If a nested response file uses a relative path, is it relative to
00705     // the cwd of the process or the response file?
00706     SmallVector<const char *, 0> ExpandedArgv;
00707     if (!ExpandResponseFile(Arg + 1, Saver, Tokenizer, ExpandedArgv,
00708                             MarkEOLs)) {
00709       // We couldn't read this file, so we leave it in the argument stream and
00710       // move on.
00711       AllExpanded = false;
00712       ++I;
00713       continue;
00714     }
00715     Argv.erase(Argv.begin() + I);
00716     Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
00717   }
00718   return AllExpanded;
00719 }
00720 
00721 namespace {
00722   class StrDupSaver : public StringSaver {
00723     std::vector<char*> Dups;
00724   public:
00725     ~StrDupSaver() {
00726       for (std::vector<char *>::iterator I = Dups.begin(), E = Dups.end();
00727            I != E; ++I) {
00728         char *Dup = *I;
00729         free(Dup);
00730       }
00731     }
00732     const char *SaveString(const char *Str) override {
00733       char *Dup = strdup(Str);
00734       Dups.push_back(Dup);
00735       return Dup;
00736     }
00737   };
00738 }
00739 
00740 /// ParseEnvironmentOptions - An alternative entry point to the
00741 /// CommandLine library, which allows you to read the program's name
00742 /// from the caller (as PROGNAME) and its command-line arguments from
00743 /// an environment variable (whose name is given in ENVVAR).
00744 ///
00745 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
00746                                  const char *Overview) {
00747   // Check args.
00748   assert(progName && "Program name not specified");
00749   assert(envVar && "Environment variable name missing");
00750 
00751   // Get the environment variable they want us to parse options out of.
00752   const char *envValue = getenv(envVar);
00753   if (!envValue)
00754     return;
00755 
00756   // Get program's "name", which we wouldn't know without the caller
00757   // telling us.
00758   SmallVector<const char *, 20> newArgv;
00759   StrDupSaver Saver;
00760   newArgv.push_back(Saver.SaveString(progName));
00761 
00762   // Parse the value of the environment variable into a "command line"
00763   // and hand it off to ParseCommandLineOptions().
00764   TokenizeGNUCommandLine(envValue, Saver, newArgv);
00765   int newArgc = static_cast<int>(newArgv.size());
00766   ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
00767 }
00768 
00769 void cl::ParseCommandLineOptions(int argc, const char * const *argv,
00770                                  const char *Overview) {
00771   // Process all registered options.
00772   SmallVector<Option*, 4> PositionalOpts;
00773   SmallVector<Option*, 4> SinkOpts;
00774   StringMap<Option*> Opts;
00775   GetOptionInfo(PositionalOpts, SinkOpts, Opts);
00776 
00777   assert((!Opts.empty() || !PositionalOpts.empty()) &&
00778          "No options specified!");
00779 
00780   // Expand response files.
00781   SmallVector<const char *, 20> newArgv;
00782   for (int i = 0; i != argc; ++i)
00783     newArgv.push_back(argv[i]);
00784   StrDupSaver Saver;
00785   ExpandResponseFiles(Saver, TokenizeGNUCommandLine, newArgv);
00786   argv = &newArgv[0];
00787   argc = static_cast<int>(newArgv.size());
00788 
00789   // Copy the program name into ProgName, making sure not to overflow it.
00790   StringRef ProgName = sys::path::filename(argv[0]);
00791   size_t Len = std::min(ProgName.size(), size_t(79));
00792   memcpy(ProgramName, ProgName.data(), Len);
00793   ProgramName[Len] = '\0';
00794 
00795   ProgramOverview = Overview;
00796   bool ErrorParsing = false;
00797 
00798   // Check out the positional arguments to collect information about them.
00799   unsigned NumPositionalRequired = 0;
00800 
00801   // Determine whether or not there are an unlimited number of positionals
00802   bool HasUnlimitedPositionals = false;
00803 
00804   Option *ConsumeAfterOpt = nullptr;
00805   if (!PositionalOpts.empty()) {
00806     if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
00807       assert(PositionalOpts.size() > 1 &&
00808              "Cannot specify cl::ConsumeAfter without a positional argument!");
00809       ConsumeAfterOpt = PositionalOpts[0];
00810     }
00811 
00812     // Calculate how many positional values are _required_.
00813     bool UnboundedFound = false;
00814     for (size_t i = ConsumeAfterOpt ? 1 : 0, e = PositionalOpts.size();
00815          i != e; ++i) {
00816       Option *Opt = PositionalOpts[i];
00817       if (RequiresValue(Opt))
00818         ++NumPositionalRequired;
00819       else if (ConsumeAfterOpt) {
00820         // ConsumeAfter cannot be combined with "optional" positional options
00821         // unless there is only one positional argument...
00822         if (PositionalOpts.size() > 2)
00823           ErrorParsing |=
00824             Opt->error("error - this positional option will never be matched, "
00825                        "because it does not Require a value, and a "
00826                        "cl::ConsumeAfter option is active!");
00827       } else if (UnboundedFound && !Opt->ArgStr[0]) {
00828         // This option does not "require" a value...  Make sure this option is
00829         // not specified after an option that eats all extra arguments, or this
00830         // one will never get any!
00831         //
00832         ErrorParsing |= Opt->error("error - option can never match, because "
00833                                    "another positional argument will match an "
00834                                    "unbounded number of values, and this option"
00835                                    " does not require a value!");
00836       }
00837       UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
00838     }
00839     HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
00840   }
00841 
00842   // PositionalVals - A vector of "positional" arguments we accumulate into
00843   // the process at the end.
00844   //
00845   SmallVector<std::pair<StringRef,unsigned>, 4> PositionalVals;
00846 
00847   // If the program has named positional arguments, and the name has been run
00848   // across, keep track of which positional argument was named.  Otherwise put
00849   // the positional args into the PositionalVals list...
00850   Option *ActivePositionalArg = nullptr;
00851 
00852   // Loop over all of the arguments... processing them.
00853   bool DashDashFound = false;  // Have we read '--'?
00854   for (int i = 1; i < argc; ++i) {
00855     Option *Handler = nullptr;
00856     Option *NearestHandler = nullptr;
00857     std::string NearestHandlerString;
00858     StringRef Value;
00859     StringRef ArgName = "";
00860 
00861     // If the option list changed, this means that some command line
00862     // option has just been registered or deregistered.  This can occur in
00863     // response to things like -load, etc.  If this happens, rescan the options.
00864     if (OptionListChanged) {
00865       PositionalOpts.clear();
00866       SinkOpts.clear();
00867       Opts.clear();
00868       GetOptionInfo(PositionalOpts, SinkOpts, Opts);
00869       OptionListChanged = false;
00870     }
00871 
00872     // Check to see if this is a positional argument.  This argument is
00873     // considered to be positional if it doesn't start with '-', if it is "-"
00874     // itself, or if we have seen "--" already.
00875     //
00876     if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
00877       // Positional argument!
00878       if (ActivePositionalArg) {
00879         ProvidePositionalOption(ActivePositionalArg, argv[i], i);
00880         continue;  // We are done!
00881       }
00882 
00883       if (!PositionalOpts.empty()) {
00884         PositionalVals.push_back(std::make_pair(argv[i],i));
00885 
00886         // All of the positional arguments have been fulfulled, give the rest to
00887         // the consume after option... if it's specified...
00888         //
00889         if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) {
00890           for (++i; i < argc; ++i)
00891             PositionalVals.push_back(std::make_pair(argv[i],i));
00892           break;   // Handle outside of the argument processing loop...
00893         }
00894 
00895         // Delay processing positional arguments until the end...
00896         continue;
00897       }
00898     } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
00899                !DashDashFound) {
00900       DashDashFound = true;  // This is the mythical "--"?
00901       continue;              // Don't try to process it as an argument itself.
00902     } else if (ActivePositionalArg &&
00903                (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
00904       // If there is a positional argument eating options, check to see if this
00905       // option is another positional argument.  If so, treat it as an argument,
00906       // otherwise feed it to the eating positional.
00907       ArgName = argv[i]+1;
00908       // Eat leading dashes.
00909       while (!ArgName.empty() && ArgName[0] == '-')
00910         ArgName = ArgName.substr(1);
00911 
00912       Handler = LookupOption(ArgName, Value, Opts);
00913       if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
00914         ProvidePositionalOption(ActivePositionalArg, argv[i], i);
00915         continue;  // We are done!
00916       }
00917 
00918     } else {     // We start with a '-', must be an argument.
00919       ArgName = argv[i]+1;
00920       // Eat leading dashes.
00921       while (!ArgName.empty() && ArgName[0] == '-')
00922         ArgName = ArgName.substr(1);
00923 
00924       Handler = LookupOption(ArgName, Value, Opts);
00925 
00926       // Check to see if this "option" is really a prefixed or grouped argument.
00927       if (!Handler)
00928         Handler = HandlePrefixedOrGroupedOption(ArgName, Value,
00929                                                 ErrorParsing, Opts);
00930 
00931       // Otherwise, look for the closest available option to report to the user
00932       // in the upcoming error.
00933       if (!Handler && SinkOpts.empty())
00934         NearestHandler = LookupNearestOption(ArgName, Opts,
00935                                              NearestHandlerString);
00936     }
00937 
00938     if (!Handler) {
00939       if (SinkOpts.empty()) {
00940         errs() << ProgramName << ": Unknown command line argument '"
00941              << argv[i] << "'.  Try: '" << argv[0] << " -help'\n";
00942 
00943         if (NearestHandler) {
00944           // If we know a near match, report it as well.
00945           errs() << ProgramName << ": Did you mean '-"
00946                  << NearestHandlerString << "'?\n";
00947         }
00948 
00949         ErrorParsing = true;
00950       } else {
00951         for (SmallVectorImpl<Option*>::iterator I = SinkOpts.begin(),
00952                E = SinkOpts.end(); I != E ; ++I)
00953           (*I)->addOccurrence(i, "", argv[i]);
00954       }
00955       continue;
00956     }
00957 
00958     // If this is a named positional argument, just remember that it is the
00959     // active one...
00960     if (Handler->getFormattingFlag() == cl::Positional)
00961       ActivePositionalArg = Handler;
00962     else
00963       ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
00964   }
00965 
00966   // Check and handle positional arguments now...
00967   if (NumPositionalRequired > PositionalVals.size()) {
00968     errs() << ProgramName
00969          << ": Not enough positional command line arguments specified!\n"
00970          << "Must specify at least " << NumPositionalRequired
00971          << " positional arguments: See: " << argv[0] << " -help\n";
00972 
00973     ErrorParsing = true;
00974   } else if (!HasUnlimitedPositionals &&
00975              PositionalVals.size() > PositionalOpts.size()) {
00976     errs() << ProgramName
00977          << ": Too many positional arguments specified!\n"
00978          << "Can specify at most " << PositionalOpts.size()
00979          << " positional arguments: See: " << argv[0] << " -help\n";
00980     ErrorParsing = true;
00981 
00982   } else if (!ConsumeAfterOpt) {
00983     // Positional args have already been handled if ConsumeAfter is specified.
00984     unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
00985     for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
00986       if (RequiresValue(PositionalOpts[i])) {
00987         ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
00988                                 PositionalVals[ValNo].second);
00989         ValNo++;
00990         --NumPositionalRequired;  // We fulfilled our duty...
00991       }
00992 
00993       // If we _can_ give this option more arguments, do so now, as long as we
00994       // do not give it values that others need.  'Done' controls whether the
00995       // option even _WANTS_ any more.
00996       //
00997       bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
00998       while (NumVals-ValNo > NumPositionalRequired && !Done) {
00999         switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
01000         case cl::Optional:
01001           Done = true;          // Optional arguments want _at most_ one value
01002           // FALL THROUGH
01003         case cl::ZeroOrMore:    // Zero or more will take all they can get...
01004         case cl::OneOrMore:     // One or more will take all they can get...
01005           ProvidePositionalOption(PositionalOpts[i],
01006                                   PositionalVals[ValNo].first,
01007                                   PositionalVals[ValNo].second);
01008           ValNo++;
01009           break;
01010         default:
01011           llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
01012                  "positional argument processing!");
01013         }
01014       }
01015     }
01016   } else {
01017     assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
01018     unsigned ValNo = 0;
01019     for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
01020       if (RequiresValue(PositionalOpts[j])) {
01021         ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
01022                                                 PositionalVals[ValNo].first,
01023                                                 PositionalVals[ValNo].second);
01024         ValNo++;
01025       }
01026 
01027     // Handle the case where there is just one positional option, and it's
01028     // optional.  In this case, we want to give JUST THE FIRST option to the
01029     // positional option and keep the rest for the consume after.  The above
01030     // loop would have assigned no values to positional options in this case.
01031     //
01032     if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
01033       ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
01034                                               PositionalVals[ValNo].first,
01035                                               PositionalVals[ValNo].second);
01036       ValNo++;
01037     }
01038 
01039     // Handle over all of the rest of the arguments to the
01040     // cl::ConsumeAfter command line option...
01041     for (; ValNo != PositionalVals.size(); ++ValNo)
01042       ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
01043                                               PositionalVals[ValNo].first,
01044                                               PositionalVals[ValNo].second);
01045   }
01046 
01047   // Loop over args and make sure all required args are specified!
01048   for (const auto &Opt : Opts) {
01049     switch (Opt.second->getNumOccurrencesFlag()) {
01050     case Required:
01051     case OneOrMore:
01052       if (Opt.second->getNumOccurrences() == 0) {
01053         Opt.second->error("must be specified at least once!");
01054         ErrorParsing = true;
01055       }
01056       // Fall through
01057     default:
01058       break;
01059     }
01060   }
01061 
01062   // Now that we know if -debug is specified, we can use it.
01063   // Note that if ReadResponseFiles == true, this must be done before the
01064   // memory allocated for the expanded command line is free()d below.
01065   DEBUG(dbgs() << "Args: ";
01066         for (int i = 0; i < argc; ++i)
01067           dbgs() << argv[i] << ' ';
01068         dbgs() << '\n';
01069        );
01070 
01071   // Free all of the memory allocated to the map.  Command line options may only
01072   // be processed once!
01073   Opts.clear();
01074   PositionalOpts.clear();
01075   MoreHelp->clear();
01076 
01077   // If we had an error processing our arguments, don't let the program execute
01078   if (ErrorParsing) exit(1);
01079 }
01080 
01081 //===----------------------------------------------------------------------===//
01082 // Option Base class implementation
01083 //
01084 
01085 bool Option::error(const Twine &Message, StringRef ArgName) {
01086   if (!ArgName.data()) ArgName = ArgStr;
01087   if (ArgName.empty())
01088     errs() << HelpStr;  // Be nice for positional arguments
01089   else
01090     errs() << ProgramName << ": for the -" << ArgName;
01091 
01092   errs() << " option: " << Message << "\n";
01093   return true;
01094 }
01095 
01096 bool Option::addOccurrence(unsigned pos, StringRef ArgName,
01097                            StringRef Value, bool MultiArg) {
01098   if (!MultiArg)
01099     NumOccurrences++;   // Increment the number of times we have been seen
01100 
01101   switch (getNumOccurrencesFlag()) {
01102   case Optional:
01103     if (NumOccurrences > 1)
01104       return error("may only occur zero or one times!", ArgName);
01105     break;
01106   case Required:
01107     if (NumOccurrences > 1)
01108       return error("must occur exactly one time!", ArgName);
01109     // Fall through
01110   case OneOrMore:
01111   case ZeroOrMore:
01112   case ConsumeAfter: break;
01113   }
01114 
01115   return handleOccurrence(pos, ArgName, Value);
01116 }
01117 
01118 
01119 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
01120 // has been specified yet.
01121 //
01122 static const char *getValueStr(const Option &O, const char *DefaultMsg) {
01123   if (O.ValueStr[0] == 0) return DefaultMsg;
01124   return O.ValueStr;
01125 }
01126 
01127 //===----------------------------------------------------------------------===//
01128 // cl::alias class implementation
01129 //
01130 
01131 // Return the width of the option tag for printing...
01132 size_t alias::getOptionWidth() const {
01133   return std::strlen(ArgStr)+6;
01134 }
01135 
01136 static void printHelpStr(StringRef HelpStr, size_t Indent,
01137                          size_t FirstLineIndentedBy) {
01138   std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
01139   outs().indent(Indent - FirstLineIndentedBy) << " - " << Split.first << "\n";
01140   while (!Split.second.empty()) {
01141     Split = Split.second.split('\n');
01142     outs().indent(Indent) << Split.first << "\n";
01143   }
01144 }
01145 
01146 // Print out the option for the alias.
01147 void alias::printOptionInfo(size_t GlobalWidth) const {
01148   outs() << "  -" << ArgStr;
01149   printHelpStr(HelpStr, GlobalWidth, std::strlen(ArgStr) + 6);
01150 }
01151 
01152 //===----------------------------------------------------------------------===//
01153 // Parser Implementation code...
01154 //
01155 
01156 // basic_parser implementation
01157 //
01158 
01159 // Return the width of the option tag for printing...
01160 size_t basic_parser_impl::getOptionWidth(const Option &O) const {
01161   size_t Len = std::strlen(O.ArgStr);
01162   if (const char *ValName = getValueName())
01163     Len += std::strlen(getValueStr(O, ValName))+3;
01164 
01165   return Len + 6;
01166 }
01167 
01168 // printOptionInfo - Print out information about this option.  The
01169 // to-be-maintained width is specified.
01170 //
01171 void basic_parser_impl::printOptionInfo(const Option &O,
01172                                         size_t GlobalWidth) const {
01173   outs() << "  -" << O.ArgStr;
01174 
01175   if (const char *ValName = getValueName())
01176     outs() << "=<" << getValueStr(O, ValName) << '>';
01177 
01178   printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
01179 }
01180 
01181 void basic_parser_impl::printOptionName(const Option &O,
01182                                         size_t GlobalWidth) const {
01183   outs() << "  -" << O.ArgStr;
01184   outs().indent(GlobalWidth-std::strlen(O.ArgStr));
01185 }
01186 
01187 
01188 // parser<bool> implementation
01189 //
01190 bool parser<bool>::parse(Option &O, StringRef ArgName,
01191                          StringRef Arg, bool &Value) {
01192   if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
01193       Arg == "1") {
01194     Value = true;
01195     return false;
01196   }
01197 
01198   if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
01199     Value = false;
01200     return false;
01201   }
01202   return O.error("'" + Arg +
01203                  "' is invalid value for boolean argument! Try 0 or 1");
01204 }
01205 
01206 // parser<boolOrDefault> implementation
01207 //
01208 bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName,
01209                                   StringRef Arg, boolOrDefault &Value) {
01210   if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
01211       Arg == "1") {
01212     Value = BOU_TRUE;
01213     return false;
01214   }
01215   if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
01216     Value = BOU_FALSE;
01217     return false;
01218   }
01219 
01220   return O.error("'" + Arg +
01221                  "' is invalid value for boolean argument! Try 0 or 1");
01222 }
01223 
01224 // parser<int> implementation
01225 //
01226 bool parser<int>::parse(Option &O, StringRef ArgName,
01227                         StringRef Arg, int &Value) {
01228   if (Arg.getAsInteger(0, Value))
01229     return O.error("'" + Arg + "' value invalid for integer argument!");
01230   return false;
01231 }
01232 
01233 // parser<unsigned> implementation
01234 //
01235 bool parser<unsigned>::parse(Option &O, StringRef ArgName,
01236                              StringRef Arg, unsigned &Value) {
01237 
01238   if (Arg.getAsInteger(0, Value))
01239     return O.error("'" + Arg + "' value invalid for uint argument!");
01240   return false;
01241 }
01242 
01243 // parser<unsigned long long> implementation
01244 //
01245 bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
01246                                       StringRef Arg, unsigned long long &Value){
01247 
01248   if (Arg.getAsInteger(0, Value))
01249     return O.error("'" + Arg + "' value invalid for uint argument!");
01250   return false;
01251 }
01252 
01253 // parser<double>/parser<float> implementation
01254 //
01255 static bool parseDouble(Option &O, StringRef Arg, double &Value) {
01256   SmallString<32> TmpStr(Arg.begin(), Arg.end());
01257   const char *ArgStart = TmpStr.c_str();
01258   char *End;
01259   Value = strtod(ArgStart, &End);
01260   if (*End != 0)
01261     return O.error("'" + Arg + "' value invalid for floating point argument!");
01262   return false;
01263 }
01264 
01265 bool parser<double>::parse(Option &O, StringRef ArgName,
01266                            StringRef Arg, double &Val) {
01267   return parseDouble(O, Arg, Val);
01268 }
01269 
01270 bool parser<float>::parse(Option &O, StringRef ArgName,
01271                           StringRef Arg, float &Val) {
01272   double dVal;
01273   if (parseDouble(O, Arg, dVal))
01274     return true;
01275   Val = (float)dVal;
01276   return false;
01277 }
01278 
01279 
01280 
01281 // generic_parser_base implementation
01282 //
01283 
01284 // findOption - Return the option number corresponding to the specified
01285 // argument string.  If the option is not found, getNumOptions() is returned.
01286 //
01287 unsigned generic_parser_base::findOption(const char *Name) {
01288   unsigned e = getNumOptions();
01289 
01290   for (unsigned i = 0; i != e; ++i) {
01291     if (strcmp(getOption(i), Name) == 0)
01292       return i;
01293   }
01294   return e;
01295 }
01296 
01297 
01298 // Return the width of the option tag for printing...
01299 size_t generic_parser_base::getOptionWidth(const Option &O) const {
01300   if (O.hasArgStr()) {
01301     size_t Size = std::strlen(O.ArgStr)+6;
01302     for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
01303       Size = std::max(Size, std::strlen(getOption(i))+8);
01304     return Size;
01305   } else {
01306     size_t BaseSize = 0;
01307     for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
01308       BaseSize = std::max(BaseSize, std::strlen(getOption(i))+8);
01309     return BaseSize;
01310   }
01311 }
01312 
01313 // printOptionInfo - Print out information about this option.  The
01314 // to-be-maintained width is specified.
01315 //
01316 void generic_parser_base::printOptionInfo(const Option &O,
01317                                           size_t GlobalWidth) const {
01318   if (O.hasArgStr()) {
01319     outs() << "  -" << O.ArgStr;
01320     printHelpStr(O.HelpStr, GlobalWidth, std::strlen(O.ArgStr) + 6);
01321 
01322     for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
01323       size_t NumSpaces = GlobalWidth-strlen(getOption(i))-8;
01324       outs() << "    =" << getOption(i);
01325       outs().indent(NumSpaces) << " -   " << getDescription(i) << '\n';
01326     }
01327   } else {
01328     if (O.HelpStr[0])
01329       outs() << "  " << O.HelpStr << '\n';
01330     for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
01331       const char *Option = getOption(i);
01332       outs() << "    -" << Option;
01333       printHelpStr(getDescription(i), GlobalWidth, std::strlen(Option) + 8);
01334     }
01335   }
01336 }
01337 
01338 static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
01339 
01340 // printGenericOptionDiff - Print the value of this option and it's default.
01341 //
01342 // "Generic" options have each value mapped to a name.
01343 void generic_parser_base::
01344 printGenericOptionDiff(const Option &O, const GenericOptionValue &Value,
01345                        const GenericOptionValue &Default,
01346                        size_t GlobalWidth) const {
01347   outs() << "  -" << O.ArgStr;
01348   outs().indent(GlobalWidth-std::strlen(O.ArgStr));
01349 
01350   unsigned NumOpts = getNumOptions();
01351   for (unsigned i = 0; i != NumOpts; ++i) {
01352     if (Value.compare(getOptionValue(i)))
01353       continue;
01354 
01355     outs() << "= " << getOption(i);
01356     size_t L = std::strlen(getOption(i));
01357     size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
01358     outs().indent(NumSpaces) << " (default: ";
01359     for (unsigned j = 0; j != NumOpts; ++j) {
01360       if (Default.compare(getOptionValue(j)))
01361         continue;
01362       outs() << getOption(j);
01363       break;
01364     }
01365     outs() << ")\n";
01366     return;
01367   }
01368   outs() << "= *unknown option value*\n";
01369 }
01370 
01371 // printOptionDiff - Specializations for printing basic value types.
01372 //
01373 #define PRINT_OPT_DIFF(T)                                               \
01374   void parser<T>::                                                      \
01375   printOptionDiff(const Option &O, T V, OptionValue<T> D,               \
01376                   size_t GlobalWidth) const {                           \
01377     printOptionName(O, GlobalWidth);                                    \
01378     std::string Str;                                                    \
01379     {                                                                   \
01380       raw_string_ostream SS(Str);                                       \
01381       SS << V;                                                          \
01382     }                                                                   \
01383     outs() << "= " << Str;                                              \
01384     size_t NumSpaces = MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0;\
01385     outs().indent(NumSpaces) << " (default: ";                          \
01386     if (D.hasValue())                                                   \
01387       outs() << D.getValue();                                           \
01388     else                                                                \
01389       outs() << "*no default*";                                         \
01390     outs() << ")\n";                                                    \
01391   }                                                                     \
01392 
01393 PRINT_OPT_DIFF(bool)
01394 PRINT_OPT_DIFF(boolOrDefault)
01395 PRINT_OPT_DIFF(int)
01396 PRINT_OPT_DIFF(unsigned)
01397 PRINT_OPT_DIFF(unsigned long long)
01398 PRINT_OPT_DIFF(double)
01399 PRINT_OPT_DIFF(float)
01400 PRINT_OPT_DIFF(char)
01401 
01402 void parser<std::string>::
01403 printOptionDiff(const Option &O, StringRef V, OptionValue<std::string> D,
01404                 size_t GlobalWidth) const {
01405   printOptionName(O, GlobalWidth);
01406   outs() << "= " << V;
01407   size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
01408   outs().indent(NumSpaces) << " (default: ";
01409   if (D.hasValue())
01410     outs() << D.getValue();
01411   else
01412     outs() << "*no default*";
01413   outs() << ")\n";
01414 }
01415 
01416 // Print a placeholder for options that don't yet support printOptionDiff().
01417 void basic_parser_impl::
01418 printOptionNoValue(const Option &O, size_t GlobalWidth) const {
01419   printOptionName(O, GlobalWidth);
01420   outs() << "= *cannot print option value*\n";
01421 }
01422 
01423 //===----------------------------------------------------------------------===//
01424 // -help and -help-hidden option implementation
01425 //
01426 
01427 static int OptNameCompare(const void *LHS, const void *RHS) {
01428   typedef std::pair<const char *, Option*> pair_ty;
01429 
01430   return strcmp(((const pair_ty*)LHS)->first, ((const pair_ty*)RHS)->first);
01431 }
01432 
01433 // Copy Options into a vector so we can sort them as we like.
01434 static void
01435 sortOpts(StringMap<Option*> &OptMap,
01436          SmallVectorImpl< std::pair<const char *, Option*> > &Opts,
01437          bool ShowHidden) {
01438   SmallPtrSet<Option*, 128> OptionSet;  // Duplicate option detection.
01439 
01440   for (StringMap<Option*>::iterator I = OptMap.begin(), E = OptMap.end();
01441        I != E; ++I) {
01442     // Ignore really-hidden options.
01443     if (I->second->getOptionHiddenFlag() == ReallyHidden)
01444       continue;
01445 
01446     // Unless showhidden is set, ignore hidden flags.
01447     if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
01448       continue;
01449 
01450     // If we've already seen this option, don't add it to the list again.
01451     if (!OptionSet.insert(I->second))
01452       continue;
01453 
01454     Opts.push_back(std::pair<const char *, Option*>(I->getKey().data(),
01455                                                     I->second));
01456   }
01457 
01458   // Sort the options list alphabetically.
01459   qsort(Opts.data(), Opts.size(), sizeof(Opts[0]), OptNameCompare);
01460 }
01461 
01462 namespace {
01463 
01464 class HelpPrinter {
01465 protected:
01466   const bool ShowHidden;
01467   typedef SmallVector<std::pair<const char *, Option*>,128> StrOptionPairVector;
01468   // Print the options. Opts is assumed to be alphabetically sorted.
01469   virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
01470     for (size_t i = 0, e = Opts.size(); i != e; ++i)
01471       Opts[i].second->printOptionInfo(MaxArgLen);
01472   }
01473 
01474 public:
01475   explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
01476   virtual ~HelpPrinter() {}
01477 
01478   // Invoke the printer.
01479   void operator=(bool Value) {
01480     if (Value == false) return;
01481 
01482     // Get all the options.
01483     SmallVector<Option*, 4> PositionalOpts;
01484     SmallVector<Option*, 4> SinkOpts;
01485     StringMap<Option*> OptMap;
01486     GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
01487 
01488     StrOptionPairVector Opts;
01489     sortOpts(OptMap, Opts, ShowHidden);
01490 
01491     if (ProgramOverview)
01492       outs() << "OVERVIEW: " << ProgramOverview << "\n";
01493 
01494     outs() << "USAGE: " << ProgramName << " [options]";
01495 
01496     // Print out the positional options.
01497     Option *CAOpt = nullptr;   // The cl::ConsumeAfter option, if it exists...
01498     if (!PositionalOpts.empty() &&
01499         PositionalOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
01500       CAOpt = PositionalOpts[0];
01501 
01502     for (size_t i = CAOpt != nullptr, e = PositionalOpts.size(); i != e; ++i) {
01503       if (PositionalOpts[i]->ArgStr[0])
01504         outs() << " --" << PositionalOpts[i]->ArgStr;
01505       outs() << " " << PositionalOpts[i]->HelpStr;
01506     }
01507 
01508     // Print the consume after option info if it exists...
01509     if (CAOpt) outs() << " " << CAOpt->HelpStr;
01510 
01511     outs() << "\n\n";
01512 
01513     // Compute the maximum argument length...
01514     size_t MaxArgLen = 0;
01515     for (size_t i = 0, e = Opts.size(); i != e; ++i)
01516       MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
01517 
01518     outs() << "OPTIONS:\n";
01519     printOptions(Opts, MaxArgLen);
01520 
01521     // Print any extra help the user has declared.
01522     for (std::vector<const char *>::iterator I = MoreHelp->begin(),
01523                                              E = MoreHelp->end();
01524          I != E; ++I)
01525       outs() << *I;
01526     MoreHelp->clear();
01527 
01528     // Halt the program since help information was printed
01529     exit(0);
01530   }
01531 };
01532 
01533 class CategorizedHelpPrinter : public HelpPrinter {
01534 public:
01535   explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
01536 
01537   // Helper function for printOptions().
01538   // It shall return true if A's name should be lexographically
01539   // ordered before B's name. It returns false otherwise.
01540   static bool OptionCategoryCompare(OptionCategory *A, OptionCategory *B) {
01541     return strcmp(A->getName(), B->getName()) < 0;
01542   }
01543 
01544   // Make sure we inherit our base class's operator=()
01545   using HelpPrinter::operator= ;
01546 
01547 protected:
01548   void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override {
01549     std::vector<OptionCategory *> SortedCategories;
01550     std::map<OptionCategory *, std::vector<Option *> > CategorizedOptions;
01551 
01552     // Collect registered option categories into vector in preparation for
01553     // sorting.
01554     for (OptionCatSet::const_iterator I = RegisteredOptionCategories->begin(),
01555                                       E = RegisteredOptionCategories->end();
01556          I != E; ++I) {
01557       SortedCategories.push_back(*I);
01558     }
01559 
01560     // Sort the different option categories alphabetically.
01561     assert(SortedCategories.size() > 0 && "No option categories registered!");
01562     std::sort(SortedCategories.begin(), SortedCategories.end(),
01563               OptionCategoryCompare);
01564 
01565     // Create map to empty vectors.
01566     for (std::vector<OptionCategory *>::const_iterator
01567              I = SortedCategories.begin(),
01568              E = SortedCategories.end();
01569          I != E; ++I)
01570       CategorizedOptions[*I] = std::vector<Option *>();
01571 
01572     // Walk through pre-sorted options and assign into categories.
01573     // Because the options are already alphabetically sorted the
01574     // options within categories will also be alphabetically sorted.
01575     for (size_t I = 0, E = Opts.size(); I != E; ++I) {
01576       Option *Opt = Opts[I].second;
01577       assert(CategorizedOptions.count(Opt->Category) > 0 &&
01578              "Option has an unregistered category");
01579       CategorizedOptions[Opt->Category].push_back(Opt);
01580     }
01581 
01582     // Now do printing.
01583     for (std::vector<OptionCategory *>::const_iterator
01584              Category = SortedCategories.begin(),
01585              E = SortedCategories.end();
01586          Category != E; ++Category) {
01587       // Hide empty categories for -help, but show for -help-hidden.
01588       bool IsEmptyCategory = CategorizedOptions[*Category].size() == 0;
01589       if (!ShowHidden && IsEmptyCategory)
01590         continue;
01591 
01592       // Print category information.
01593       outs() << "\n";
01594       outs() << (*Category)->getName() << ":\n";
01595 
01596       // Check if description is set.
01597       if ((*Category)->getDescription() != nullptr)
01598         outs() << (*Category)->getDescription() << "\n\n";
01599       else
01600         outs() << "\n";
01601 
01602       // When using -help-hidden explicitly state if the category has no
01603       // options associated with it.
01604       if (IsEmptyCategory) {
01605         outs() << "  This option category has no options.\n";
01606         continue;
01607       }
01608       // Loop over the options in the category and print.
01609       for (std::vector<Option *>::const_iterator
01610                Opt = CategorizedOptions[*Category].begin(),
01611                E = CategorizedOptions[*Category].end();
01612            Opt != E; ++Opt)
01613         (*Opt)->printOptionInfo(MaxArgLen);
01614     }
01615   }
01616 };
01617 
01618 // This wraps the Uncategorizing and Categorizing printers and decides
01619 // at run time which should be invoked.
01620 class HelpPrinterWrapper {
01621 private:
01622   HelpPrinter &UncategorizedPrinter;
01623   CategorizedHelpPrinter &CategorizedPrinter;
01624 
01625 public:
01626   explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
01627                               CategorizedHelpPrinter &CategorizedPrinter) :
01628     UncategorizedPrinter(UncategorizedPrinter),
01629     CategorizedPrinter(CategorizedPrinter) { }
01630 
01631   // Invoke the printer.
01632   void operator=(bool Value);
01633 };
01634 
01635 } // End anonymous namespace
01636 
01637 // Declare the four HelpPrinter instances that are used to print out help, or
01638 // help-hidden as an uncategorized list or in categories.
01639 static HelpPrinter UncategorizedNormalPrinter(false);
01640 static HelpPrinter UncategorizedHiddenPrinter(true);
01641 static CategorizedHelpPrinter CategorizedNormalPrinter(false);
01642 static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
01643 
01644 
01645 // Declare HelpPrinter wrappers that will decide whether or not to invoke
01646 // a categorizing help printer
01647 static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
01648                                                CategorizedNormalPrinter);
01649 static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
01650                                                CategorizedHiddenPrinter);
01651 
01652 // Define uncategorized help printers.
01653 // -help-list is hidden by default because if Option categories are being used
01654 // then -help behaves the same as -help-list.
01655 static cl::opt<HelpPrinter, true, parser<bool> >
01656 HLOp("help-list",
01657      cl::desc("Display list of available options (-help-list-hidden for more)"),
01658      cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed);
01659 
01660 static cl::opt<HelpPrinter, true, parser<bool> >
01661 HLHOp("help-list-hidden",
01662      cl::desc("Display list of all available options"),
01663      cl::location(UncategorizedHiddenPrinter), cl::Hidden, cl::ValueDisallowed);
01664 
01665 // Define uncategorized/categorized help printers. These printers change their
01666 // behaviour at runtime depending on whether one or more Option categories have
01667 // been declared.
01668 static cl::opt<HelpPrinterWrapper, true, parser<bool> >
01669 HOp("help", cl::desc("Display available options (-help-hidden for more)"),
01670     cl::location(WrappedNormalPrinter), cl::ValueDisallowed);
01671 
01672 static cl::opt<HelpPrinterWrapper, true, parser<bool> >
01673 HHOp("help-hidden", cl::desc("Display all available options"),
01674      cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed);
01675 
01676 
01677 
01678 static cl::opt<bool>
01679 PrintOptions("print-options",
01680              cl::desc("Print non-default options after command line parsing"),
01681              cl::Hidden, cl::init(false));
01682 
01683 static cl::opt<bool>
01684 PrintAllOptions("print-all-options",
01685                 cl::desc("Print all option values after command line parsing"),
01686                 cl::Hidden, cl::init(false));
01687 
01688 void HelpPrinterWrapper::operator=(bool Value) {
01689   if (Value == false)
01690     return;
01691 
01692   // Decide which printer to invoke. If more than one option category is
01693   // registered then it is useful to show the categorized help instead of
01694   // uncategorized help.
01695   if (RegisteredOptionCategories->size() > 1) {
01696     // unhide -help-list option so user can have uncategorized output if they
01697     // want it.
01698     HLOp.setHiddenFlag(NotHidden);
01699 
01700     CategorizedPrinter = true; // Invoke categorized printer
01701   }
01702   else
01703     UncategorizedPrinter = true; // Invoke uncategorized printer
01704 }
01705 
01706 // Print the value of each option.
01707 void cl::PrintOptionValues() {
01708   if (!PrintOptions && !PrintAllOptions) return;
01709 
01710   // Get all the options.
01711   SmallVector<Option*, 4> PositionalOpts;
01712   SmallVector<Option*, 4> SinkOpts;
01713   StringMap<Option*> OptMap;
01714   GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
01715 
01716   SmallVector<std::pair<const char *, Option*>, 128> Opts;
01717   sortOpts(OptMap, Opts, /*ShowHidden*/true);
01718 
01719   // Compute the maximum argument length...
01720   size_t MaxArgLen = 0;
01721   for (size_t i = 0, e = Opts.size(); i != e; ++i)
01722     MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
01723 
01724   for (size_t i = 0, e = Opts.size(); i != e; ++i)
01725     Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
01726 }
01727 
01728 static void (*OverrideVersionPrinter)() = nullptr;
01729 
01730 static std::vector<void (*)()>* ExtraVersionPrinters = nullptr;
01731 
01732 namespace {
01733 class VersionPrinter {
01734 public:
01735   void print() {
01736     raw_ostream &OS = outs();
01737     OS << "LLVM (http://llvm.org/):\n"
01738        << "  " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
01739 #ifdef LLVM_VERSION_INFO
01740     OS << " " << LLVM_VERSION_INFO;
01741 #endif
01742     OS << "\n  ";
01743 #ifndef __OPTIMIZE__
01744     OS << "DEBUG build";
01745 #else
01746     OS << "Optimized build";
01747 #endif
01748 #ifndef NDEBUG
01749     OS << " with assertions";
01750 #endif
01751     std::string CPU = sys::getHostCPUName();
01752     if (CPU == "generic") CPU = "(unknown)";
01753     OS << ".\n"
01754 #if (ENABLE_TIMESTAMPS == 1)
01755        << "  Built " << __DATE__ << " (" << __TIME__ << ").\n"
01756 #endif
01757        << "  Default target: " << sys::getDefaultTargetTriple() << '\n'
01758        << "  Host CPU: " << CPU << '\n';
01759   }
01760   void operator=(bool OptionWasSpecified) {
01761     if (!OptionWasSpecified) return;
01762 
01763     if (OverrideVersionPrinter != nullptr) {
01764       (*OverrideVersionPrinter)();
01765       exit(0);
01766     }
01767     print();
01768 
01769     // Iterate over any registered extra printers and call them to add further
01770     // information.
01771     if (ExtraVersionPrinters != nullptr) {
01772       outs() << '\n';
01773       for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(),
01774                                              E = ExtraVersionPrinters->end();
01775            I != E; ++I)
01776         (*I)();
01777     }
01778 
01779     exit(0);
01780   }
01781 };
01782 } // End anonymous namespace
01783 
01784 
01785 // Define the --version option that prints out the LLVM version for the tool
01786 static VersionPrinter VersionPrinterInstance;
01787 
01788 static cl::opt<VersionPrinter, true, parser<bool> >
01789 VersOp("version", cl::desc("Display the version of this program"),
01790     cl::location(VersionPrinterInstance), cl::ValueDisallowed);
01791 
01792 // Utility function for printing the help message.
01793 void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
01794   // This looks weird, but it actually prints the help message. The Printers are
01795   // types of HelpPrinter and the help gets printed when its operator= is
01796   // invoked. That's because the "normal" usages of the help printer is to be
01797   // assigned true/false depending on whether -help or -help-hidden was given or
01798   // not.  Since we're circumventing that we have to make it look like -help or
01799   // -help-hidden were given, so we assign true.
01800 
01801   if (!Hidden && !Categorized)
01802     UncategorizedNormalPrinter = true;
01803   else if (!Hidden && Categorized)
01804     CategorizedNormalPrinter = true;
01805   else if (Hidden && !Categorized)
01806     UncategorizedHiddenPrinter = true;
01807   else
01808     CategorizedHiddenPrinter = true;
01809 }
01810 
01811 /// Utility function for printing version number.
01812 void cl::PrintVersionMessage() {
01813   VersionPrinterInstance.print();
01814 }
01815 
01816 void cl::SetVersionPrinter(void (*func)()) {
01817   OverrideVersionPrinter = func;
01818 }
01819 
01820 void cl::AddExtraVersionPrinter(void (*func)()) {
01821   if (!ExtraVersionPrinters)
01822     ExtraVersionPrinters = new std::vector<void (*)()>;
01823 
01824   ExtraVersionPrinters->push_back(func);
01825 }
01826 
01827 void cl::getRegisteredOptions(StringMap<Option*> &Map)
01828 {
01829   // Get all the options.
01830   SmallVector<Option*, 4> PositionalOpts; //NOT USED
01831   SmallVector<Option*, 4> SinkOpts;  //NOT USED
01832   assert(Map.size() == 0 && "StringMap must be empty");
01833   GetOptionInfo(PositionalOpts, SinkOpts, Map);
01834   return;
01835 }