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/Config/config.h"
00020 #include "llvm/ADT/OwningPtr.h"
00021 #include "llvm/Support/CommandLine.h"
00022 #include "llvm/Support/ErrorHandling.h"
00023 #include "llvm/Support/MemoryBuffer.h"
00024 #include "llvm/Support/ManagedStatic.h"
00025 #include "llvm/Support/Streams.h"
00026 #include "llvm/Target/TargetRegistry.h"
00027 #include "llvm/System/Path.h"
00028 #include <algorithm>
00029 #include <functional>
00030 #include <map>
00031 #include <ostream>
00032 #include <set>
00033 #include <cstdlib>
00034 #include <cerrno>
00035 #include <cstring>
00036 #include <climits>
00037 using namespace llvm;
00038 using namespace cl;
00039 
00040 //===----------------------------------------------------------------------===//
00041 // Template instantiations and anchors.
00042 //
00043 TEMPLATE_INSTANTIATION(class basic_parser<bool>);
00044 TEMPLATE_INSTANTIATION(class basic_parser<boolOrDefault>);
00045 TEMPLATE_INSTANTIATION(class basic_parser<int>);
00046 TEMPLATE_INSTANTIATION(class basic_parser<unsigned>);
00047 TEMPLATE_INSTANTIATION(class basic_parser<double>);
00048 TEMPLATE_INSTANTIATION(class basic_parser<float>);
00049 TEMPLATE_INSTANTIATION(class basic_parser<std::string>);
00050 TEMPLATE_INSTANTIATION(class basic_parser<char>);
00051 
00052 TEMPLATE_INSTANTIATION(class opt<unsigned>);
00053 TEMPLATE_INSTANTIATION(class opt<int>);
00054 TEMPLATE_INSTANTIATION(class opt<std::string>);
00055 TEMPLATE_INSTANTIATION(class opt<char>);
00056 TEMPLATE_INSTANTIATION(class opt<bool>);
00057 
00058 void Option::anchor() {}
00059 void basic_parser_impl::anchor() {}
00060 void parser<bool>::anchor() {}
00061 void parser<boolOrDefault>::anchor() {}
00062 void parser<int>::anchor() {}
00063 void parser<unsigned>::anchor() {}
00064 void parser<double>::anchor() {}
00065 void parser<float>::anchor() {}
00066 void parser<std::string>::anchor() {}
00067 void parser<char>::anchor() {}
00068 
00069 //===----------------------------------------------------------------------===//
00070 
00071 // Globals for name and overview of program.  Program name is not a string to
00072 // avoid static ctor/dtor issues.
00073 static char ProgramName[80] = "<premain>";
00074 static const char *ProgramOverview = 0;
00075 
00076 // This collects additional help to be printed.
00077 static ManagedStatic<std::vector<const char*> > MoreHelp;
00078 
00079 extrahelp::extrahelp(const char *Help)
00080   : morehelp(Help) {
00081   MoreHelp->push_back(Help);
00082 }
00083 
00084 static bool OptionListChanged = false;
00085 
00086 // MarkOptionsChanged - Internal helper function.
00087 void cl::MarkOptionsChanged() {
00088   OptionListChanged = true;
00089 }
00090 
00091 /// RegisteredOptionList - This is the list of the command line options that
00092 /// have statically constructed themselves.
00093 static Option *RegisteredOptionList = 0;
00094 
00095 void Option::addArgument() {
00096   assert(NextRegistered == 0 && "argument multiply registered!");
00097 
00098   NextRegistered = RegisteredOptionList;
00099   RegisteredOptionList = this;
00100   MarkOptionsChanged();
00101 }
00102 
00103 
00104 //===----------------------------------------------------------------------===//
00105 // Basic, shared command line option processing machinery.
00106 //
00107 
00108 /// GetOptionInfo - Scan the list of registered options, turning them into data
00109 /// structures that are easier to handle.
00110 static void GetOptionInfo(std::vector<Option*> &PositionalOpts,
00111                           std::vector<Option*> &SinkOpts,
00112                           std::map<std::string, Option*> &OptionsMap) {
00113   std::vector<const char*> OptionNames;
00114   Option *CAOpt = 0;  // The ConsumeAfter option if it exists.
00115   for (Option *O = RegisteredOptionList; O; O = O->getNextRegisteredOption()) {
00116     // If this option wants to handle multiple option names, get the full set.
00117     // This handles enum options like "-O1 -O2" etc.
00118     O->getExtraOptionNames(OptionNames);
00119     if (O->ArgStr[0])
00120       OptionNames.push_back(O->ArgStr);
00121 
00122     // Handle named options.
00123     for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
00124       // Add argument to the argument map!
00125       if (!OptionsMap.insert(std::pair<std::string,Option*>(OptionNames[i],
00126                                                             O)).second) {
00127         cerr << ProgramName << ": CommandLine Error: Argument '"
00128              << OptionNames[i] << "' defined more than once!\n";
00129       }
00130     }
00131 
00132     OptionNames.clear();
00133 
00134     // Remember information about positional options.
00135     if (O->getFormattingFlag() == cl::Positional)
00136       PositionalOpts.push_back(O);
00137     else if (O->getMiscFlags() & cl::Sink) // Remember sink options
00138       SinkOpts.push_back(O);
00139     else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
00140       if (CAOpt)
00141         O->error("Cannot specify more than one option with cl::ConsumeAfter!");
00142       CAOpt = O;
00143     }
00144   }
00145 
00146   if (CAOpt)
00147     PositionalOpts.push_back(CAOpt);
00148 
00149   // Make sure that they are in order of registration not backwards.
00150   std::reverse(PositionalOpts.begin(), PositionalOpts.end());
00151 }
00152 
00153 
00154 /// LookupOption - Lookup the option specified by the specified option on the
00155 /// command line.  If there is a value specified (after an equal sign) return
00156 /// that as well.
00157 static Option *LookupOption(const char *&Arg, const char *&Value,
00158                             std::map<std::string, Option*> &OptionsMap) {
00159   while (*Arg == '-') ++Arg;  // Eat leading dashes
00160 
00161   const char *ArgEnd = Arg;
00162   while (*ArgEnd && *ArgEnd != '=')
00163     ++ArgEnd; // Scan till end of argument name.
00164 
00165   if (*ArgEnd == '=')  // If we have an equals sign...
00166     Value = ArgEnd+1;  // Get the value, not the equals
00167 
00168 
00169   if (*Arg == 0) return 0;
00170 
00171   // Look up the option.
00172   std::map<std::string, Option*>::iterator I =
00173     OptionsMap.find(std::string(Arg, ArgEnd));
00174   return I != OptionsMap.end() ? I->second : 0;
00175 }
00176 
00177 static inline bool ProvideOption(Option *Handler, const char *ArgName,
00178                                  const char *Value, int argc, char **argv,
00179                                  int &i) {
00180   // Is this a multi-argument option?
00181   unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
00182 
00183   // Enforce value requirements
00184   switch (Handler->getValueExpectedFlag()) {
00185   case ValueRequired:
00186     if (Value == 0) {       // No value specified?
00187       if (i+1 < argc) {     // Steal the next argument, like for '-o filename'
00188         Value = argv[++i];
00189       } else {
00190         return Handler->error("requires a value!");
00191       }
00192     }
00193     break;
00194   case ValueDisallowed:
00195     if (NumAdditionalVals > 0)
00196       return Handler->error("multi-valued option specified"
00197       " with ValueDisallowed modifier!");
00198 
00199     if (Value)
00200       return Handler->error("does not allow a value! '" +
00201                             std::string(Value) + "' specified.");
00202     break;
00203   case ValueOptional:
00204     break;
00205   default:
00206     cerr << ProgramName
00207          << ": Bad ValueMask flag! CommandLine usage error:"
00208          << Handler->getValueExpectedFlag() << "\n";
00209     llvm_unreachable(0);
00210   }
00211 
00212   // If this isn't a multi-arg option, just run the handler.
00213   if (NumAdditionalVals == 0) {
00214     return Handler->addOccurrence(i, ArgName, Value ? Value : "");
00215   }
00216   // If it is, run the handle several times.
00217   else {
00218     bool MultiArg = false;
00219 
00220     if (Value) {
00221       if (Handler->addOccurrence(i, ArgName, Value, MultiArg))
00222         return true;
00223       --NumAdditionalVals;
00224       MultiArg = true;
00225     }
00226 
00227     while (NumAdditionalVals > 0) {
00228 
00229       if (i+1 < argc) {
00230         Value = argv[++i];
00231       } else {
00232         return Handler->error("not enough values!");
00233       }
00234       if (Handler->addOccurrence(i, ArgName, Value, MultiArg))
00235         return true;
00236       MultiArg = true;
00237       --NumAdditionalVals;
00238     }
00239     return false;
00240   }
00241 }
00242 
00243 static bool ProvidePositionalOption(Option *Handler, const std::string &Arg,
00244                                     int i) {
00245   int Dummy = i;
00246   return ProvideOption(Handler, Handler->ArgStr, Arg.c_str(), 0, 0, Dummy);
00247 }
00248 
00249 
00250 // Option predicates...
00251 static inline bool isGrouping(const Option *O) {
00252   return O->getFormattingFlag() == cl::Grouping;
00253 }
00254 static inline bool isPrefixedOrGrouping(const Option *O) {
00255   return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
00256 }
00257 
00258 // getOptionPred - Check to see if there are any options that satisfy the
00259 // specified predicate with names that are the prefixes in Name.  This is
00260 // checked by progressively stripping characters off of the name, checking to
00261 // see if there options that satisfy the predicate.  If we find one, return it,
00262 // otherwise return null.
00263 //
00264 static Option *getOptionPred(std::string Name, size_t &Length,
00265                              bool (*Pred)(const Option*),
00266                              std::map<std::string, Option*> &OptionsMap) {
00267 
00268   std::map<std::string, Option*>::iterator OMI = OptionsMap.find(Name);
00269   if (OMI != OptionsMap.end() && Pred(OMI->second)) {
00270     Length = Name.length();
00271     return OMI->second;
00272   }
00273 
00274   if (Name.size() == 1) return 0;
00275   do {
00276     Name.erase(Name.end()-1, Name.end());   // Chop off the last character...
00277     OMI = OptionsMap.find(Name);
00278 
00279     // Loop while we haven't found an option and Name still has at least two
00280     // characters in it (so that the next iteration will not be the empty
00281     // string...
00282   } while ((OMI == OptionsMap.end() || !Pred(OMI->second)) && Name.size() > 1);
00283 
00284   if (OMI != OptionsMap.end() && Pred(OMI->second)) {
00285     Length = Name.length();
00286     return OMI->second;    // Found one!
00287   }
00288   return 0;                // No option found!
00289 }
00290 
00291 static bool RequiresValue(const Option *O) {
00292   return O->getNumOccurrencesFlag() == cl::Required ||
00293          O->getNumOccurrencesFlag() == cl::OneOrMore;
00294 }
00295 
00296 static bool EatsUnboundedNumberOfValues(const Option *O) {
00297   return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
00298          O->getNumOccurrencesFlag() == cl::OneOrMore;
00299 }
00300 
00301 /// ParseCStringVector - Break INPUT up wherever one or more
00302 /// whitespace characters are found, and store the resulting tokens in
00303 /// OUTPUT. The tokens stored in OUTPUT are dynamically allocated
00304 /// using strdup (), so it is the caller's responsibility to free ()
00305 /// them later.
00306 ///
00307 static void ParseCStringVector(std::vector<char *> &output,
00308                                const char *input) {
00309   // Characters which will be treated as token separators:
00310   static const char *const delims = " \v\f\t\r\n";
00311 
00312   std::string work (input);
00313   // Skip past any delims at head of input string.
00314   size_t pos = work.find_first_not_of (delims);
00315   // If the string consists entirely of delims, then exit early.
00316   if (pos == std::string::npos) return;
00317   // Otherwise, jump forward to beginning of first word.
00318   work = work.substr (pos);
00319   // Find position of first delimiter.
00320   pos = work.find_first_of (delims);
00321 
00322   while (!work.empty() && pos != std::string::npos) {
00323     // Everything from 0 to POS is the next word to copy.
00324     output.push_back (strdup (work.substr (0,pos).c_str ()));
00325     // Is there another word in the string?
00326     size_t nextpos = work.find_first_not_of (delims, pos + 1);
00327     if (nextpos != std::string::npos) {
00328       // Yes? Then remove delims from beginning ...
00329       work = work.substr (work.find_first_not_of (delims, pos + 1));
00330       // and find the end of the word.
00331       pos = work.find_first_of (delims);
00332     } else {
00333       // No? (Remainder of string is delims.) End the loop.
00334       work = "";
00335       pos = std::string::npos;
00336     }
00337   }
00338 
00339   // If `input' ended with non-delim char, then we'll get here with
00340   // the last word of `input' in `work'; copy it now.
00341   if (!work.empty ()) {
00342     output.push_back (strdup (work.c_str ()));
00343   }
00344 }
00345 
00346 /// ParseEnvironmentOptions - An alternative entry point to the
00347 /// CommandLine library, which allows you to read the program's name
00348 /// from the caller (as PROGNAME) and its command-line arguments from
00349 /// an environment variable (whose name is given in ENVVAR).
00350 ///
00351 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
00352                                  const char *Overview, bool ReadResponseFiles) {
00353   // Check args.
00354   assert(progName && "Program name not specified");
00355   assert(envVar && "Environment variable name missing");
00356 
00357   // Get the environment variable they want us to parse options out of.
00358   const char *envValue = getenv(envVar);
00359   if (!envValue)
00360     return;
00361 
00362   // Get program's "name", which we wouldn't know without the caller
00363   // telling us.
00364   std::vector<char*> newArgv;
00365   newArgv.push_back(strdup(progName));
00366 
00367   // Parse the value of the environment variable into a "command line"
00368   // and hand it off to ParseCommandLineOptions().
00369   ParseCStringVector(newArgv, envValue);
00370   int newArgc = static_cast<int>(newArgv.size());
00371   ParseCommandLineOptions(newArgc, &newArgv[0], Overview, ReadResponseFiles);
00372 
00373   // Free all the strdup()ed strings.
00374   for (std::vector<char*>::iterator i = newArgv.begin(), e = newArgv.end();
00375        i != e; ++i)
00376     free (*i);
00377 }
00378 
00379 
00380 /// ExpandResponseFiles - Copy the contents of argv into newArgv,
00381 /// substituting the contents of the response files for the arguments
00382 /// of type @file.
00383 static void ExpandResponseFiles(int argc, char** argv,
00384                                 std::vector<char*>& newArgv) {
00385   for (int i = 1; i != argc; ++i) {
00386     char* arg = argv[i];
00387 
00388     if (arg[0] == '@') {
00389 
00390       sys::PathWithStatus respFile(++arg);
00391 
00392       // Check that the response file is not empty (mmap'ing empty
00393       // files can be problematic).
00394       const sys::FileStatus *FileStat = respFile.getFileStatus();
00395       if (FileStat && FileStat->getSize() != 0) {
00396 
00397         // Mmap the response file into memory.
00398         OwningPtr<MemoryBuffer>
00399           respFilePtr(MemoryBuffer::getFile(respFile.c_str()));
00400 
00401         // If we could open the file, parse its contents, otherwise
00402         // pass the @file option verbatim.
00403 
00404         // TODO: we should also support recursive loading of response files,
00405         // since this is how gcc behaves. (From their man page: "The file may
00406         // itself contain additional @file options; any such options will be
00407         // processed recursively.")
00408 
00409         if (respFilePtr != 0) {
00410           ParseCStringVector(newArgv, respFilePtr->getBufferStart());
00411           continue;
00412         }
00413       }
00414     }
00415     newArgv.push_back(strdup(arg));
00416   }
00417 }
00418 
00419 void cl::ParseCommandLineOptions(int argc, char **argv,
00420                                  const char *Overview, bool ReadResponseFiles) {
00421   // Process all registered options.
00422   std::vector<Option*> PositionalOpts;
00423   std::vector<Option*> SinkOpts;
00424   std::map<std::string, Option*> Opts;
00425   GetOptionInfo(PositionalOpts, SinkOpts, Opts);
00426 
00427   assert((!Opts.empty() || !PositionalOpts.empty()) &&
00428          "No options specified!");
00429 
00430   // Expand response files.
00431   std::vector<char*> newArgv;
00432   if (ReadResponseFiles) {
00433     newArgv.push_back(strdup(argv[0]));
00434     ExpandResponseFiles(argc, argv, newArgv);
00435     argv = &newArgv[0];
00436     argc = static_cast<int>(newArgv.size());
00437   }
00438 
00439   // Copy the program name into ProgName, making sure not to overflow it.
00440   std::string ProgName = sys::Path(argv[0]).getLast();
00441   if (ProgName.size() > 79) ProgName.resize(79);
00442   strcpy(ProgramName, ProgName.c_str());
00443 
00444   ProgramOverview = Overview;
00445   bool ErrorParsing = false;
00446 
00447   // Check out the positional arguments to collect information about them.
00448   unsigned NumPositionalRequired = 0;
00449 
00450   // Determine whether or not there are an unlimited number of positionals
00451   bool HasUnlimitedPositionals = false;
00452 
00453   Option *ConsumeAfterOpt = 0;
00454   if (!PositionalOpts.empty()) {
00455     if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
00456       assert(PositionalOpts.size() > 1 &&
00457              "Cannot specify cl::ConsumeAfter without a positional argument!");
00458       ConsumeAfterOpt = PositionalOpts[0];
00459     }
00460 
00461     // Calculate how many positional values are _required_.
00462     bool UnboundedFound = false;
00463     for (size_t i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
00464          i != e; ++i) {
00465       Option *Opt = PositionalOpts[i];
00466       if (RequiresValue(Opt))
00467         ++NumPositionalRequired;
00468       else if (ConsumeAfterOpt) {
00469         // ConsumeAfter cannot be combined with "optional" positional options
00470         // unless there is only one positional argument...
00471         if (PositionalOpts.size() > 2)
00472           ErrorParsing |=
00473             Opt->error("error - this positional option will never be matched, "
00474                        "because it does not Require a value, and a "
00475                        "cl::ConsumeAfter option is active!");
00476       } else if (UnboundedFound && !Opt->ArgStr[0]) {
00477         // This option does not "require" a value...  Make sure this option is
00478         // not specified after an option that eats all extra arguments, or this
00479         // one will never get any!
00480         //
00481         ErrorParsing |= Opt->error("error - option can never match, because "
00482                                    "another positional argument will match an "
00483                                    "unbounded number of values, and this option"
00484                                    " does not require a value!");
00485       }
00486       UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
00487     }
00488     HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
00489   }
00490 
00491   // PositionalVals - A vector of "positional" arguments we accumulate into
00492   // the process at the end...
00493   //
00494   std::vector<std::pair<std::string,unsigned> > PositionalVals;
00495 
00496   // If the program has named positional arguments, and the name has been run
00497   // across, keep track of which positional argument was named.  Otherwise put
00498   // the positional args into the PositionalVals list...
00499   Option *ActivePositionalArg = 0;
00500 
00501   // Loop over all of the arguments... processing them.
00502   bool DashDashFound = false;  // Have we read '--'?
00503   for (int i = 1; i < argc; ++i) {
00504     Option *Handler = 0;
00505     const char *Value = 0;
00506     const char *ArgName = "";
00507 
00508     // If the option list changed, this means that some command line
00509     // option has just been registered or deregistered.  This can occur in
00510     // response to things like -load, etc.  If this happens, rescan the options.
00511     if (OptionListChanged) {
00512       PositionalOpts.clear();
00513       SinkOpts.clear();
00514       Opts.clear();
00515       GetOptionInfo(PositionalOpts, SinkOpts, Opts);
00516       OptionListChanged = false;
00517     }
00518 
00519     // Check to see if this is a positional argument.  This argument is
00520     // considered to be positional if it doesn't start with '-', if it is "-"
00521     // itself, or if we have seen "--" already.
00522     //
00523     if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
00524       // Positional argument!
00525       if (ActivePositionalArg) {
00526         ProvidePositionalOption(ActivePositionalArg, argv[i], i);
00527         continue;  // We are done!
00528       } else if (!PositionalOpts.empty()) {
00529         PositionalVals.push_back(std::make_pair(argv[i],i));
00530 
00531         // All of the positional arguments have been fulfulled, give the rest to
00532         // the consume after option... if it's specified...
00533         //
00534         if (PositionalVals.size() >= NumPositionalRequired &&
00535             ConsumeAfterOpt != 0) {
00536           for (++i; i < argc; ++i)
00537             PositionalVals.push_back(std::make_pair(argv[i],i));
00538           break;   // Handle outside of the argument processing loop...
00539         }
00540 
00541         // Delay processing positional arguments until the end...
00542         continue;
00543       }
00544     } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
00545                !DashDashFound) {
00546       DashDashFound = true;  // This is the mythical "--"?
00547       continue;              // Don't try to process it as an argument itself.
00548     } else if (ActivePositionalArg &&
00549                (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
00550       // If there is a positional argument eating options, check to see if this
00551       // option is another positional argument.  If so, treat it as an argument,
00552       // otherwise feed it to the eating positional.
00553       ArgName = argv[i]+1;
00554       Handler = LookupOption(ArgName, Value, Opts);
00555       if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
00556         ProvidePositionalOption(ActivePositionalArg, argv[i], i);
00557         continue;  // We are done!
00558       }
00559 
00560     } else {     // We start with a '-', must be an argument...
00561       ArgName = argv[i]+1;
00562       Handler = LookupOption(ArgName, Value, Opts);
00563 
00564       // Check to see if this "option" is really a prefixed or grouped argument.
00565       if (Handler == 0) {
00566         std::string RealName(ArgName);
00567         if (RealName.size() > 1) {
00568           size_t Length = 0;
00569           Option *PGOpt = getOptionPred(RealName, Length, isPrefixedOrGrouping,
00570                                         Opts);
00571 
00572           // If the option is a prefixed option, then the value is simply the
00573           // rest of the name...  so fall through to later processing, by
00574           // setting up the argument name flags and value fields.
00575           //
00576           if (PGOpt && PGOpt->getFormattingFlag() == cl::Prefix) {
00577             Value = ArgName+Length;
00578             assert(Opts.find(std::string(ArgName, Value)) != Opts.end() &&
00579                    Opts.find(std::string(ArgName, Value))->second == PGOpt);
00580             Handler = PGOpt;
00581           } else if (PGOpt) {
00582             // This must be a grouped option... handle them now.
00583             assert(isGrouping(PGOpt) && "Broken getOptionPred!");
00584 
00585             do {
00586               // Move current arg name out of RealName into RealArgName...
00587               std::string RealArgName(RealName.begin(),
00588                                       RealName.begin() + Length);
00589               RealName.erase(RealName.begin(), RealName.begin() + Length);
00590 
00591               // Because ValueRequired is an invalid flag for grouped arguments,
00592               // we don't need to pass argc/argv in...
00593               //
00594               assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
00595                      "Option can not be cl::Grouping AND cl::ValueRequired!");
00596               int Dummy;
00597               ErrorParsing |= ProvideOption(PGOpt, RealArgName.c_str(),
00598                                             0, 0, 0, Dummy);
00599 
00600               // Get the next grouping option...
00601               PGOpt = getOptionPred(RealName, Length, isGrouping, Opts);
00602             } while (PGOpt && Length != RealName.size());
00603 
00604             Handler = PGOpt; // Ate all of the options.
00605           }
00606         }
00607       }
00608     }
00609 
00610     if (Handler == 0) {
00611       if (SinkOpts.empty()) {
00612         cerr << ProgramName << ": Unknown command line argument '"
00613              << argv[i] << "'.  Try: '" << argv[0] << " --help'\n";
00614         ErrorParsing = true;
00615       } else {
00616         for (std::vector<Option*>::iterator I = SinkOpts.begin(),
00617                E = SinkOpts.end(); I != E ; ++I)
00618           (*I)->addOccurrence(i, "", argv[i]);
00619       }
00620       continue;
00621     }
00622 
00623     // Check to see if this option accepts a comma separated list of values.  If
00624     // it does, we have to split up the value into multiple values...
00625     if (Value && Handler->getMiscFlags() & CommaSeparated) {
00626       std::string Val(Value);
00627       std::string::size_type Pos = Val.find(',');
00628 
00629       while (Pos != std::string::npos) {
00630         // Process the portion before the comma...
00631         ErrorParsing |= ProvideOption(Handler, ArgName,
00632                                       std::string(Val.begin(),
00633                                                   Val.begin()+Pos).c_str(),
00634                                       argc, argv, i);
00635         // Erase the portion before the comma, AND the comma...
00636         Val.erase(Val.begin(), Val.begin()+Pos+1);
00637         Value += Pos+1;  // Increment the original value pointer as well...
00638 
00639         // Check for another comma...
00640         Pos = Val.find(',');
00641       }
00642     }
00643 
00644     // If this is a named positional argument, just remember that it is the
00645     // active one...
00646     if (Handler->getFormattingFlag() == cl::Positional)
00647       ActivePositionalArg = Handler;
00648     else
00649       ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
00650   }
00651 
00652   // Check and handle positional arguments now...
00653   if (NumPositionalRequired > PositionalVals.size()) {
00654     cerr << ProgramName
00655          << ": Not enough positional command line arguments specified!\n"
00656          << "Must specify at least " << NumPositionalRequired
00657          << " positional arguments: See: " << argv[0] << " --help\n";
00658 
00659     ErrorParsing = true;
00660   } else if (!HasUnlimitedPositionals
00661              && PositionalVals.size() > PositionalOpts.size()) {
00662     cerr << ProgramName
00663          << ": Too many positional arguments specified!\n"
00664          << "Can specify at most " << PositionalOpts.size()
00665          << " positional arguments: See: " << argv[0] << " --help\n";
00666     ErrorParsing = true;
00667 
00668   } else if (ConsumeAfterOpt == 0) {
00669     // Positional args have already been handled if ConsumeAfter is specified...
00670     unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
00671     for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
00672       if (RequiresValue(PositionalOpts[i])) {
00673         ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
00674                                 PositionalVals[ValNo].second);
00675         ValNo++;
00676         --NumPositionalRequired;  // We fulfilled our duty...
00677       }
00678 
00679       // If we _can_ give this option more arguments, do so now, as long as we
00680       // do not give it values that others need.  'Done' controls whether the
00681       // option even _WANTS_ any more.
00682       //
00683       bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
00684       while (NumVals-ValNo > NumPositionalRequired && !Done) {
00685         switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
00686         case cl::Optional:
00687           Done = true;          // Optional arguments want _at most_ one value
00688           // FALL THROUGH
00689         case cl::ZeroOrMore:    // Zero or more will take all they can get...
00690         case cl::OneOrMore:     // One or more will take all they can get...
00691           ProvidePositionalOption(PositionalOpts[i],
00692                                   PositionalVals[ValNo].first,
00693                                   PositionalVals[ValNo].second);
00694           ValNo++;
00695           break;
00696         default:
00697           llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
00698                  "positional argument processing!");
00699         }
00700       }
00701     }
00702   } else {
00703     assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
00704     unsigned ValNo = 0;
00705     for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
00706       if (RequiresValue(PositionalOpts[j])) {
00707         ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
00708                                                 PositionalVals[ValNo].first,
00709                                                 PositionalVals[ValNo].second);
00710         ValNo++;
00711       }
00712 
00713     // Handle the case where there is just one positional option, and it's
00714     // optional.  In this case, we want to give JUST THE FIRST option to the
00715     // positional option and keep the rest for the consume after.  The above
00716     // loop would have assigned no values to positional options in this case.
00717     //
00718     if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
00719       ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
00720                                               PositionalVals[ValNo].first,
00721                                               PositionalVals[ValNo].second);
00722       ValNo++;
00723     }
00724 
00725     // Handle over all of the rest of the arguments to the
00726     // cl::ConsumeAfter command line option...
00727     for (; ValNo != PositionalVals.size(); ++ValNo)
00728       ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
00729                                               PositionalVals[ValNo].first,
00730                                               PositionalVals[ValNo].second);
00731   }
00732 
00733   // Loop over args and make sure all required args are specified!
00734   for (std::map<std::string, Option*>::iterator I = Opts.begin(),
00735          E = Opts.end(); I != E; ++I) {
00736     switch (I->second->getNumOccurrencesFlag()) {
00737     case Required:
00738     case OneOrMore:
00739       if (I->second->getNumOccurrences() == 0) {
00740         I->second->error("must be specified at least once!");
00741         ErrorParsing = true;
00742       }
00743       // Fall through
00744     default:
00745       break;
00746     }
00747   }
00748 
00749   // Free all of the memory allocated to the map.  Command line options may only
00750   // be processed once!
00751   Opts.clear();
00752   PositionalOpts.clear();
00753   MoreHelp->clear();
00754 
00755   // Free the memory allocated by ExpandResponseFiles.
00756   if (ReadResponseFiles) {
00757     // Free all the strdup()ed strings.
00758     for (std::vector<char*>::iterator i = newArgv.begin(), e = newArgv.end();
00759          i != e; ++i)
00760       free (*i);
00761   }
00762 
00763   // If we had an error processing our arguments, don't let the program execute
00764   if (ErrorParsing) exit(1);
00765 }
00766 
00767 //===----------------------------------------------------------------------===//
00768 // Option Base class implementation
00769 //
00770 
00771 bool Option::error(std::string Message, const char *ArgName) {
00772   if (ArgName == 0) ArgName = ArgStr;
00773   if (ArgName[0] == 0)
00774     cerr << HelpStr;  // Be nice for positional arguments
00775   else
00776     cerr << ProgramName << ": for the -" << ArgName;
00777 
00778   cerr << " option: " << Message << "\n";
00779   return true;
00780 }
00781 
00782 bool Option::addOccurrence(unsigned pos, const char *ArgName,
00783                            const std::string &Value,
00784                            bool MultiArg) {
00785   if (!MultiArg)
00786     NumOccurrences++;   // Increment the number of times we have been seen
00787 
00788   switch (getNumOccurrencesFlag()) {
00789   case Optional:
00790     if (NumOccurrences > 1)
00791       return error("may only occur zero or one times!", ArgName);
00792     break;
00793   case Required:
00794     if (NumOccurrences > 1)
00795       return error("must occur exactly one time!", ArgName);
00796     // Fall through
00797   case OneOrMore:
00798   case ZeroOrMore:
00799   case ConsumeAfter: break;
00800   default: return error("bad num occurrences flag value!");
00801   }
00802 
00803   return handleOccurrence(pos, ArgName, Value);
00804 }
00805 
00806 
00807 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
00808 // has been specified yet.
00809 //
00810 static const char *getValueStr(const Option &O, const char *DefaultMsg) {
00811   if (O.ValueStr[0] == 0) return DefaultMsg;
00812   return O.ValueStr;
00813 }
00814 
00815 //===----------------------------------------------------------------------===//
00816 // cl::alias class implementation
00817 //
00818 
00819 // Return the width of the option tag for printing...
00820 size_t alias::getOptionWidth() const {
00821   return std::strlen(ArgStr)+6;
00822 }
00823 
00824 // Print out the option for the alias.
00825 void alias::printOptionInfo(size_t GlobalWidth) const {
00826   size_t L = std::strlen(ArgStr);
00827   cerr << "  -" << ArgStr << std::string(GlobalWidth-L-6, ' ') << " - "
00828          << HelpStr << "\n";
00829 }
00830 
00831 
00832 
00833 //===----------------------------------------------------------------------===//
00834 // Parser Implementation code...
00835 //
00836 
00837 // basic_parser implementation
00838 //
00839 
00840 // Return the width of the option tag for printing...
00841 size_t basic_parser_impl::getOptionWidth(const Option &O) const {
00842   size_t Len = std::strlen(O.ArgStr);
00843   if (const char *ValName = getValueName())
00844     Len += std::strlen(getValueStr(O, ValName))+3;
00845 
00846   return Len + 6;
00847 }
00848 
00849 // printOptionInfo - Print out information about this option.  The
00850 // to-be-maintained width is specified.
00851 //
00852 void basic_parser_impl::printOptionInfo(const Option &O,
00853                                         size_t GlobalWidth) const {
00854   cout << "  -" << O.ArgStr;
00855 
00856   if (const char *ValName = getValueName())
00857     cout << "=<" << getValueStr(O, ValName) << ">";
00858 
00859   cout << std::string(GlobalWidth-getOptionWidth(O), ' ') << " - "
00860        << O.HelpStr << "\n";
00861 }
00862 
00863 
00864 
00865 
00866 // parser<bool> implementation
00867 //
00868 bool parser<bool>::parse(Option &O, const char *ArgName,
00869                          const std::string &Arg, bool &Value) {
00870   if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
00871       Arg == "1") {
00872     Value = true;
00873   } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
00874     Value = false;
00875   } else {
00876     return O.error("'" + Arg +
00877                    "' is invalid value for boolean argument! Try 0 or 1");
00878   }
00879   return false;
00880 }
00881 
00882 // parser<boolOrDefault> implementation
00883 //
00884 bool parser<boolOrDefault>::parse(Option &O, const char *ArgName,
00885                          const std::string &Arg, boolOrDefault &Value) {
00886   if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
00887       Arg == "1") {
00888     Value = BOU_TRUE;
00889   } else if (Arg == "false" || Arg == "FALSE"
00890              || Arg == "False" || Arg == "0") {
00891     Value = BOU_FALSE;
00892   } else {
00893     return O.error("'" + Arg +
00894                    "' is invalid value for boolean argument! Try 0 or 1");
00895   }
00896   return false;
00897 }
00898 
00899 // parser<int> implementation
00900 //
00901 bool parser<int>::parse(Option &O, const char *ArgName,
00902                         const std::string &Arg, int &Value) {
00903   char *End;
00904   Value = (int)strtol(Arg.c_str(), &End, 0);
00905   if (*End != 0)
00906     return O.error("'" + Arg + "' value invalid for integer argument!");
00907   return false;
00908 }
00909 
00910 // parser<unsigned> implementation
00911 //
00912 bool parser<unsigned>::parse(Option &O, const char *ArgName,
00913                              const std::string &Arg, unsigned &Value) {
00914   char *End;
00915   errno = 0;
00916   unsigned long V = strtoul(Arg.c_str(), &End, 0);
00917   Value = (unsigned)V;
00918   if (((V == ULONG_MAX) && (errno == ERANGE))
00919       || (*End != 0)
00920       || (Value != V))
00921     return O.error("'" + Arg + "' value invalid for uint argument!");
00922   return false;
00923 }
00924 
00925 // parser<double>/parser<float> implementation
00926 //
00927 static bool parseDouble(Option &O, const std::string &Arg, double &Value) {
00928   const char *ArgStart = Arg.c_str();
00929   char *End;
00930   Value = strtod(ArgStart, &End);
00931   if (*End != 0)
00932     return O.error("'" + Arg + "' value invalid for floating point argument!");
00933   return false;
00934 }
00935 
00936 bool parser<double>::parse(Option &O, const char *AN,
00937                            const std::string &Arg, double &Val) {
00938   return parseDouble(O, Arg, Val);
00939 }
00940 
00941 bool parser<float>::parse(Option &O, const char *AN,
00942                           const std::string &Arg, float &Val) {
00943   double dVal;
00944   if (parseDouble(O, Arg, dVal))
00945     return true;
00946   Val = (float)dVal;
00947   return false;
00948 }
00949 
00950 
00951 
00952 // generic_parser_base implementation
00953 //
00954 
00955 // findOption - Return the option number corresponding to the specified
00956 // argument string.  If the option is not found, getNumOptions() is returned.
00957 //
00958 unsigned generic_parser_base::findOption(const char *Name) {
00959   unsigned i = 0, e = getNumOptions();
00960   std::string N(Name);
00961 
00962   while (i != e)
00963     if (getOption(i) == N)
00964       return i;
00965     else
00966       ++i;
00967   return e;
00968 }
00969 
00970 
00971 // Return the width of the option tag for printing...
00972 size_t generic_parser_base::getOptionWidth(const Option &O) const {
00973   if (O.hasArgStr()) {
00974     size_t Size = std::strlen(O.ArgStr)+6;
00975     for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
00976       Size = std::max(Size, std::strlen(getOption(i))+8);
00977     return Size;
00978   } else {
00979     size_t BaseSize = 0;
00980     for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
00981       BaseSize = std::max(BaseSize, std::strlen(getOption(i))+8);
00982     return BaseSize;
00983   }
00984 }
00985 
00986 // printOptionInfo - Print out information about this option.  The
00987 // to-be-maintained width is specified.
00988 //
00989 void generic_parser_base::printOptionInfo(const Option &O,
00990                                           size_t GlobalWidth) const {
00991   if (O.hasArgStr()) {
00992     size_t L = std::strlen(O.ArgStr);
00993     cout << "  -" << O.ArgStr << std::string(GlobalWidth-L-6, ' ')
00994          << " - " << O.HelpStr << "\n";
00995 
00996     for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
00997       size_t NumSpaces = GlobalWidth-strlen(getOption(i))-8;
00998       cout << "    =" << getOption(i) << std::string(NumSpaces, ' ')
00999            << " -   " << getDescription(i) << "\n";
01000     }
01001   } else {
01002     if (O.HelpStr[0])
01003       cout << "  " << O.HelpStr << "\n";
01004     for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
01005       size_t L = std::strlen(getOption(i));
01006       cout << "    -" << getOption(i) << std::string(GlobalWidth-L-8, ' ')
01007            << " - " << getDescription(i) << "\n";
01008     }
01009   }
01010 }
01011 
01012 
01013 //===----------------------------------------------------------------------===//
01014 // --help and --help-hidden option implementation
01015 //
01016 
01017 namespace {
01018 
01019 class HelpPrinter {
01020   size_t MaxArgLen;
01021   const Option *EmptyArg;
01022   const bool ShowHidden;
01023 
01024   // isHidden/isReallyHidden - Predicates to be used to filter down arg lists.
01025   inline static bool isHidden(std::pair<std::string, Option *> &OptPair) {
01026     return OptPair.second->getOptionHiddenFlag() >= Hidden;
01027   }
01028   inline static bool isReallyHidden(std::pair<std::string, Option *> &OptPair) {
01029     return OptPair.second->getOptionHiddenFlag() == ReallyHidden;
01030   }
01031 
01032 public:
01033   explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {
01034     EmptyArg = 0;
01035   }
01036 
01037   void operator=(bool Value) {
01038     if (Value == false) return;
01039 
01040     // Get all the options.
01041     std::vector<Option*> PositionalOpts;
01042     std::vector<Option*> SinkOpts;
01043     std::map<std::string, Option*> OptMap;
01044     GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
01045 
01046     // Copy Options into a vector so we can sort them as we like...
01047     std::vector<std::pair<std::string, Option*> > Opts;
01048     copy(OptMap.begin(), OptMap.end(), std::back_inserter(Opts));
01049 
01050     // Eliminate Hidden or ReallyHidden arguments, depending on ShowHidden
01051     Opts.erase(std::remove_if(Opts.begin(), Opts.end(),
01052                           std::ptr_fun(ShowHidden ? isReallyHidden : isHidden)),
01053                Opts.end());
01054 
01055     // Eliminate duplicate entries in table (from enum flags options, f.e.)
01056     {  // Give OptionSet a scope
01057       std::set<Option*> OptionSet;
01058       for (unsigned i = 0; i != Opts.size(); ++i)
01059         if (OptionSet.count(Opts[i].second) == 0)
01060           OptionSet.insert(Opts[i].second);   // Add new entry to set
01061         else
01062           Opts.erase(Opts.begin()+i--);    // Erase duplicate
01063     }
01064 
01065     if (ProgramOverview)
01066       cout << "OVERVIEW: " << ProgramOverview << "\n";
01067 
01068     cout << "USAGE: " << ProgramName << " [options]";
01069 
01070     // Print out the positional options.
01071     Option *CAOpt = 0;   // The cl::ConsumeAfter option, if it exists...
01072     if (!PositionalOpts.empty() &&
01073         PositionalOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
01074       CAOpt = PositionalOpts[0];
01075 
01076     for (size_t i = CAOpt != 0, e = PositionalOpts.size(); i != e; ++i) {
01077       if (PositionalOpts[i]->ArgStr[0])
01078         cout << " --" << PositionalOpts[i]->ArgStr;
01079       cout << " " << PositionalOpts[i]->HelpStr;
01080     }
01081 
01082     // Print the consume after option info if it exists...
01083     if (CAOpt) cout << " " << CAOpt->HelpStr;
01084 
01085     cout << "\n\n";
01086 
01087     // Compute the maximum argument length...
01088     MaxArgLen = 0;
01089     for (size_t i = 0, e = Opts.size(); i != e; ++i)
01090       MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
01091 
01092     cout << "OPTIONS:\n";
01093     for (size_t i = 0, e = Opts.size(); i != e; ++i)
01094       Opts[i].second->printOptionInfo(MaxArgLen);
01095 
01096     // Print any extra help the user has declared.
01097     for (std::vector<const char *>::iterator I = MoreHelp->begin(),
01098           E = MoreHelp->end(); I != E; ++I)
01099       cout << *I;
01100     MoreHelp->clear();
01101 
01102     // Halt the program since help information was printed
01103     exit(1);
01104   }
01105 };
01106 } // End anonymous namespace
01107 
01108 // Define the two HelpPrinter instances that are used to print out help, or
01109 // help-hidden...
01110 //
01111 static HelpPrinter NormalPrinter(false);
01112 static HelpPrinter HiddenPrinter(true);
01113 
01114 static cl::opt<HelpPrinter, true, parser<bool> >
01115 HOp("help", cl::desc("Display available options (--help-hidden for more)"),
01116     cl::location(NormalPrinter), cl::ValueDisallowed);
01117 
01118 static cl::opt<HelpPrinter, true, parser<bool> >
01119 HHOp("help-hidden", cl::desc("Display all available options"),
01120      cl::location(HiddenPrinter), cl::Hidden, cl::ValueDisallowed);
01121 
01122 static void (*OverrideVersionPrinter)() = 0;
01123 
01124 namespace {
01125 class VersionPrinter {
01126 public:
01127   void print() {
01128         cout << "Low Level Virtual Machine (http://llvm.org/):\n";
01129         cout << "  " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
01130 #ifdef LLVM_VERSION_INFO
01131         cout << LLVM_VERSION_INFO;
01132 #endif
01133         cout << "\n  ";
01134 #ifndef __OPTIMIZE__
01135         cout << "DEBUG build";
01136 #else
01137         cout << "Optimized build";
01138 #endif
01139 #ifndef NDEBUG
01140         cout << " with assertions";
01141 #endif
01142         cout << ".\n";
01143         cout << "  Built " << __DATE__ << "(" << __TIME__ << ").\n";
01144         cout << "\n";
01145         cout << "  Registered Targets:\n";
01146 
01147         std::vector<std::pair<std::string, const Target*> > Targets;
01148         size_t Width = 0;
01149         for (TargetRegistry::iterator it = TargetRegistry::begin(), 
01150                ie = TargetRegistry::end(); it != ie; ++it) {
01151           Targets.push_back(std::make_pair(it->getName(), &*it));
01152           Width = std::max(Width, ::strlen(it->getName()));
01153         }
01154         std::sort(Targets.begin(), Targets.end());
01155 
01156         for (unsigned i = 0, e = Targets.size(); i != e; ++i) {
01157           const Target *T = Targets[i].second;
01158           cout << "    " << T->getName()
01159                << std::string(Width - ::strlen(T->getName()), ' ') << " - "
01160                << T->getShortDescription() << "\n";
01161         }
01162         if (Targets.empty())
01163           cout << "    (none)\n";
01164   }
01165   void operator=(bool OptionWasSpecified) {
01166     if (OptionWasSpecified) {
01167       if (OverrideVersionPrinter == 0) {
01168         print();
01169         exit(1);
01170       } else {
01171         (*OverrideVersionPrinter)();
01172         exit(1);
01173       }
01174     }
01175   }
01176 };
01177 } // End anonymous namespace
01178 
01179 
01180 // Define the --version option that prints out the LLVM version for the tool
01181 static VersionPrinter VersionPrinterInstance;
01182 
01183 static cl::opt<VersionPrinter, true, parser<bool> >
01184 VersOp("version", cl::desc("Display the version of this program"),
01185     cl::location(VersionPrinterInstance), cl::ValueDisallowed);
01186 
01187 // Utility function for printing the help message.
01188 void cl::PrintHelpMessage() {
01189   // This looks weird, but it actually prints the help message. The
01190   // NormalPrinter variable is a HelpPrinter and the help gets printed when
01191   // its operator= is invoked. That's because the "normal" usages of the
01192   // help printer is to be assigned true/false depending on whether the
01193   // --help option was given or not. Since we're circumventing that we have
01194   // to make it look like --help was given, so we assign true.
01195   NormalPrinter = true;
01196 }
01197 
01198 /// Utility function for printing version number.
01199 void cl::PrintVersionMessage() {
01200   VersionPrinterInstance.print();
01201 }
01202 
01203 void cl::SetVersionPrinter(void (*func)()) {
01204   OverrideVersionPrinter = func;
01205 }