1 //===-- CommandLine.cpp - Command line parser implementation --------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This class implements a command line argument processor that is useful when 11 // creating a tool. It provides a simple, minimalistic interface that is easily 12 // extensible and supports nonlocal (library) command line options. 13 // 14 // Note that rather than trying to figure out what this code does, you could try 15 // reading the library documentation located in docs/CommandLine.html 16 // 17 //===----------------------------------------------------------------------===// 18 19 #include "llvm/Support/CommandLine.h" 20 #include "llvm/Support/Debug.h" 21 #include "llvm/Support/ErrorHandling.h" 22 #include "llvm/Support/MemoryBuffer.h" 23 #include "llvm/Support/ManagedStatic.h" 24 #include "llvm/Support/raw_ostream.h" 25 #include "llvm/Support/system_error.h" 26 #include "llvm/Support/Host.h" 27 #include "llvm/Support/Path.h" 28 #include "llvm/ADT/OwningPtr.h" 29 #include "llvm/ADT/SmallPtrSet.h" 30 #include "llvm/ADT/SmallString.h" 31 #include "llvm/ADT/StringMap.h" 32 #include "llvm/ADT/Twine.h" 33 #include "llvm/Config/config.h" 34 #include <cerrno> 35 #include <cstdlib> 36 using namespace llvm; 37 using namespace cl; 38 39 //===----------------------------------------------------------------------===// 40 // Template instantiations and anchors. 41 // 42 namespace llvm { namespace cl { 43 TEMPLATE_INSTANTIATION(class basic_parser<bool>); 44 TEMPLATE_INSTANTIATION(class basic_parser<boolOrDefault>); 45 TEMPLATE_INSTANTIATION(class basic_parser<int>); 46 TEMPLATE_INSTANTIATION(class basic_parser<unsigned>); 47 TEMPLATE_INSTANTIATION(class basic_parser<double>); 48 TEMPLATE_INSTANTIATION(class basic_parser<float>); 49 TEMPLATE_INSTANTIATION(class basic_parser<std::string>); 50 TEMPLATE_INSTANTIATION(class basic_parser<char>); 51 52 TEMPLATE_INSTANTIATION(class opt<unsigned>); 53 TEMPLATE_INSTANTIATION(class opt<int>); 54 TEMPLATE_INSTANTIATION(class opt<std::string>); 55 TEMPLATE_INSTANTIATION(class opt<char>); 56 TEMPLATE_INSTANTIATION(class opt<bool>); 57 } } // end namespace llvm::cl 58 59 void Option::anchor() {} 60 void basic_parser_impl::anchor() {} 61 void parser<bool>::anchor() {} 62 void parser<boolOrDefault>::anchor() {} 63 void parser<int>::anchor() {} 64 void parser<unsigned>::anchor() {} 65 void parser<double>::anchor() {} 66 void parser<float>::anchor() {} 67 void parser<std::string>::anchor() {} 68 void parser<char>::anchor() {} 69 70 //===----------------------------------------------------------------------===// 71 72 // Globals for name and overview of program. Program name is not a string to 73 // avoid static ctor/dtor issues. 74 static char ProgramName[80] = "<premain>"; 75 static const char *ProgramOverview = 0; 76 77 // This collects additional help to be printed. 78 static ManagedStatic<std::vector<const char*> > MoreHelp; 79 80 extrahelp::extrahelp(const char *Help) 81 : morehelp(Help) { 82 MoreHelp->push_back(Help); 83 } 84 85 static bool OptionListChanged = false; 86 87 // MarkOptionsChanged - Internal helper function. 88 void cl::MarkOptionsChanged() { 89 OptionListChanged = true; 90 } 91 92 /// RegisteredOptionList - This is the list of the command line options that 93 /// have statically constructed themselves. 94 static Option *RegisteredOptionList = 0; 95 96 void Option::addArgument() { 97 assert(NextRegistered == 0 && "argument multiply registered!"); 98 99 NextRegistered = RegisteredOptionList; 100 RegisteredOptionList = this; 101 MarkOptionsChanged(); 102 } 103 104 105 //===----------------------------------------------------------------------===// 106 // Basic, shared command line option processing machinery. 107 // 108 109 /// GetOptionInfo - Scan the list of registered options, turning them into data 110 /// structures that are easier to handle. 111 static void GetOptionInfo(SmallVectorImpl<Option*> &PositionalOpts, 112 SmallVectorImpl<Option*> &SinkOpts, 113 StringMap<Option*> &OptionsMap) { 114 SmallVector<const char*, 16> OptionNames; 115 Option *CAOpt = 0; // The ConsumeAfter option if it exists. 116 for (Option *O = RegisteredOptionList; O; O = O->getNextRegisteredOption()) { 117 // If this option wants to handle multiple option names, get the full set. 118 // This handles enum options like "-O1 -O2" etc. 119 O->getExtraOptionNames(OptionNames); 120 if (O->ArgStr[0]) 121 OptionNames.push_back(O->ArgStr); 122 123 // Handle named options. 124 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) { 125 // Add argument to the argument map! 126 if (OptionsMap.GetOrCreateValue(OptionNames[i], O).second != O) { 127 errs() << ProgramName << ": CommandLine Error: Argument '" 128 << OptionNames[i] << "' defined more than once!\n"; 129 } 130 } 131 132 OptionNames.clear(); 133 134 // Remember information about positional options. 135 if (O->getFormattingFlag() == cl::Positional) 136 PositionalOpts.push_back(O); 137 else if (O->getMiscFlags() & cl::Sink) // Remember sink options 138 SinkOpts.push_back(O); 139 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) { 140 if (CAOpt) 141 O->error("Cannot specify more than one option with cl::ConsumeAfter!"); 142 CAOpt = O; 143 } 144 } 145 146 if (CAOpt) 147 PositionalOpts.push_back(CAOpt); 148 149 // Make sure that they are in order of registration not backwards. 150 std::reverse(PositionalOpts.begin(), PositionalOpts.end()); 151 } 152 153 154 /// LookupOption - Lookup the option specified by the specified option on the 155 /// command line. If there is a value specified (after an equal sign) return 156 /// that as well. This assumes that leading dashes have already been stripped. 157 static Option *LookupOption(StringRef &Arg, StringRef &Value, 158 const StringMap<Option*> &OptionsMap) { 159 // Reject all dashes. 160 if (Arg.empty()) return 0; 161 162 size_t EqualPos = Arg.find('='); 163 164 // If we have an equals sign, remember the value. 165 if (EqualPos == StringRef::npos) { 166 // Look up the option. 167 StringMap<Option*>::const_iterator I = OptionsMap.find(Arg); 168 return I != OptionsMap.end() ? I->second : 0; 169 } 170 171 // If the argument before the = is a valid option name, we match. If not, 172 // return Arg unmolested. 173 StringMap<Option*>::const_iterator I = 174 OptionsMap.find(Arg.substr(0, EqualPos)); 175 if (I == OptionsMap.end()) return 0; 176 177 Value = Arg.substr(EqualPos+1); 178 Arg = Arg.substr(0, EqualPos); 179 return I->second; 180 } 181 182 /// LookupNearestOption - Lookup the closest match to the option specified by 183 /// the specified option on the command line. If there is a value specified 184 /// (after an equal sign) return that as well. This assumes that leading dashes 185 /// have already been stripped. 186 static Option *LookupNearestOption(StringRef Arg, 187 const StringMap<Option*> &OptionsMap, 188 std::string &NearestString) { 189 // Reject all dashes. 190 if (Arg.empty()) return 0; 191 192 // Split on any equal sign. 193 std::pair<StringRef, StringRef> SplitArg = Arg.split('='); 194 StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present. 195 StringRef &RHS = SplitArg.second; 196 197 // Find the closest match. 198 Option *Best = 0; 199 unsigned BestDistance = 0; 200 for (StringMap<Option*>::const_iterator it = OptionsMap.begin(), 201 ie = OptionsMap.end(); it != ie; ++it) { 202 Option *O = it->second; 203 SmallVector<const char*, 16> OptionNames; 204 O->getExtraOptionNames(OptionNames); 205 if (O->ArgStr[0]) 206 OptionNames.push_back(O->ArgStr); 207 208 bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed; 209 StringRef Flag = PermitValue ? LHS : Arg; 210 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) { 211 StringRef Name = OptionNames[i]; 212 unsigned Distance = StringRef(Name).edit_distance( 213 Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance); 214 if (!Best || Distance < BestDistance) { 215 Best = O; 216 BestDistance = Distance; 217 if (RHS.empty() || !PermitValue) 218 NearestString = OptionNames[i]; 219 else 220 NearestString = std::string(OptionNames[i]) + "=" + RHS.str(); 221 } 222 } 223 } 224 225 return Best; 226 } 227 228 /// CommaSeparateAndAddOccurence - A wrapper around Handler->addOccurence() that 229 /// does special handling of cl::CommaSeparated options. 230 static bool CommaSeparateAndAddOccurence(Option *Handler, unsigned pos, 231 StringRef ArgName, 232 StringRef Value, bool MultiArg = false) 233 { 234 // Check to see if this option accepts a comma separated list of values. If 235 // it does, we have to split up the value into multiple values. 236 if (Handler->getMiscFlags() & CommaSeparated) { 237 StringRef Val(Value); 238 StringRef::size_type Pos = Val.find(','); 239 240 while (Pos != StringRef::npos) { 241 // Process the portion before the comma. 242 if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg)) 243 return true; 244 // Erase the portion before the comma, AND the comma. 245 Val = Val.substr(Pos+1); 246 Value.substr(Pos+1); // Increment the original value pointer as well. 247 // Check for another comma. 248 Pos = Val.find(','); 249 } 250 251 Value = Val; 252 } 253 254 if (Handler->addOccurrence(pos, ArgName, Value, MultiArg)) 255 return true; 256 257 return false; 258 } 259 260 /// ProvideOption - For Value, this differentiates between an empty value ("") 261 /// and a null value (StringRef()). The later is accepted for arguments that 262 /// don't allow a value (-foo) the former is rejected (-foo=). 263 static inline bool ProvideOption(Option *Handler, StringRef ArgName, 264 StringRef Value, int argc, char **argv, 265 int &i) { 266 // Is this a multi-argument option? 267 unsigned NumAdditionalVals = Handler->getNumAdditionalVals(); 268 269 // Enforce value requirements 270 switch (Handler->getValueExpectedFlag()) { 271 case ValueRequired: 272 if (Value.data() == 0) { // No value specified? 273 if (i+1 >= argc) 274 return Handler->error("requires a value!"); 275 // Steal the next argument, like for '-o filename' 276 Value = argv[++i]; 277 } 278 break; 279 case ValueDisallowed: 280 if (NumAdditionalVals > 0) 281 return Handler->error("multi-valued option specified" 282 " with ValueDisallowed modifier!"); 283 284 if (Value.data()) 285 return Handler->error("does not allow a value! '" + 286 Twine(Value) + "' specified."); 287 break; 288 case ValueOptional: 289 break; 290 291 default: 292 errs() << ProgramName 293 << ": Bad ValueMask flag! CommandLine usage error:" 294 << Handler->getValueExpectedFlag() << "\n"; 295 llvm_unreachable(0); 296 } 297 298 // If this isn't a multi-arg option, just run the handler. 299 if (NumAdditionalVals == 0) 300 return CommaSeparateAndAddOccurence(Handler, i, ArgName, Value); 301 302 // If it is, run the handle several times. 303 bool MultiArg = false; 304 305 if (Value.data()) { 306 if (CommaSeparateAndAddOccurence(Handler, i, ArgName, Value, MultiArg)) 307 return true; 308 --NumAdditionalVals; 309 MultiArg = true; 310 } 311 312 while (NumAdditionalVals > 0) { 313 if (i+1 >= argc) 314 return Handler->error("not enough values!"); 315 Value = argv[++i]; 316 317 if (CommaSeparateAndAddOccurence(Handler, i, ArgName, Value, MultiArg)) 318 return true; 319 MultiArg = true; 320 --NumAdditionalVals; 321 } 322 return false; 323 } 324 325 static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) { 326 int Dummy = i; 327 return ProvideOption(Handler, Handler->ArgStr, Arg, 0, 0, Dummy); 328 } 329 330 331 // Option predicates... 332 static inline bool isGrouping(const Option *O) { 333 return O->getFormattingFlag() == cl::Grouping; 334 } 335 static inline bool isPrefixedOrGrouping(const Option *O) { 336 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix; 337 } 338 339 // getOptionPred - Check to see if there are any options that satisfy the 340 // specified predicate with names that are the prefixes in Name. This is 341 // checked by progressively stripping characters off of the name, checking to 342 // see if there options that satisfy the predicate. If we find one, return it, 343 // otherwise return null. 344 // 345 static Option *getOptionPred(StringRef Name, size_t &Length, 346 bool (*Pred)(const Option*), 347 const StringMap<Option*> &OptionsMap) { 348 349 StringMap<Option*>::const_iterator OMI = OptionsMap.find(Name); 350 351 // Loop while we haven't found an option and Name still has at least two 352 // characters in it (so that the next iteration will not be the empty 353 // string. 354 while (OMI == OptionsMap.end() && Name.size() > 1) { 355 Name = Name.substr(0, Name.size()-1); // Chop off the last character. 356 OMI = OptionsMap.find(Name); 357 } 358 359 if (OMI != OptionsMap.end() && Pred(OMI->second)) { 360 Length = Name.size(); 361 return OMI->second; // Found one! 362 } 363 return 0; // No option found! 364 } 365 366 /// HandlePrefixedOrGroupedOption - The specified argument string (which started 367 /// with at least one '-') does not fully match an available option. Check to 368 /// see if this is a prefix or grouped option. If so, split arg into output an 369 /// Arg/Value pair and return the Option to parse it with. 370 static Option *HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value, 371 bool &ErrorParsing, 372 const StringMap<Option*> &OptionsMap) { 373 if (Arg.size() == 1) return 0; 374 375 // Do the lookup! 376 size_t Length = 0; 377 Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap); 378 if (PGOpt == 0) return 0; 379 380 // If the option is a prefixed option, then the value is simply the 381 // rest of the name... so fall through to later processing, by 382 // setting up the argument name flags and value fields. 383 if (PGOpt->getFormattingFlag() == cl::Prefix) { 384 Value = Arg.substr(Length); 385 Arg = Arg.substr(0, Length); 386 assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt); 387 return PGOpt; 388 } 389 390 // This must be a grouped option... handle them now. Grouping options can't 391 // have values. 392 assert(isGrouping(PGOpt) && "Broken getOptionPred!"); 393 394 do { 395 // Move current arg name out of Arg into OneArgName. 396 StringRef OneArgName = Arg.substr(0, Length); 397 Arg = Arg.substr(Length); 398 399 // Because ValueRequired is an invalid flag for grouped arguments, 400 // we don't need to pass argc/argv in. 401 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired && 402 "Option can not be cl::Grouping AND cl::ValueRequired!"); 403 int Dummy = 0; 404 ErrorParsing |= ProvideOption(PGOpt, OneArgName, 405 StringRef(), 0, 0, Dummy); 406 407 // Get the next grouping option. 408 PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap); 409 } while (PGOpt && Length != Arg.size()); 410 411 // Return the last option with Arg cut down to just the last one. 412 return PGOpt; 413 } 414 415 416 417 static bool RequiresValue(const Option *O) { 418 return O->getNumOccurrencesFlag() == cl::Required || 419 O->getNumOccurrencesFlag() == cl::OneOrMore; 420 } 421 422 static bool EatsUnboundedNumberOfValues(const Option *O) { 423 return O->getNumOccurrencesFlag() == cl::ZeroOrMore || 424 O->getNumOccurrencesFlag() == cl::OneOrMore; 425 } 426 427 /// ParseCStringVector - Break INPUT up wherever one or more 428 /// whitespace characters are found, and store the resulting tokens in 429 /// OUTPUT. The tokens stored in OUTPUT are dynamically allocated 430 /// using strdup(), so it is the caller's responsibility to free() 431 /// them later. 432 /// 433 static void ParseCStringVector(std::vector<char *> &OutputVector, 434 const char *Input) { 435 // Characters which will be treated as token separators: 436 StringRef Delims = " \v\f\t\r\n"; 437 438 StringRef WorkStr(Input); 439 while (!WorkStr.empty()) { 440 // If the first character is a delimiter, strip them off. 441 if (Delims.find(WorkStr[0]) != StringRef::npos) { 442 size_t Pos = WorkStr.find_first_not_of(Delims); 443 if (Pos == StringRef::npos) Pos = WorkStr.size(); 444 WorkStr = WorkStr.substr(Pos); 445 continue; 446 } 447 448 // Find position of first delimiter. 449 size_t Pos = WorkStr.find_first_of(Delims); 450 if (Pos == StringRef::npos) Pos = WorkStr.size(); 451 452 // Everything from 0 to Pos is the next word to copy. 453 char *NewStr = (char*)malloc(Pos+1); 454 memcpy(NewStr, WorkStr.data(), Pos); 455 NewStr[Pos] = 0; 456 OutputVector.push_back(NewStr); 457 458 WorkStr = WorkStr.substr(Pos); 459 } 460 } 461 462 /// ParseEnvironmentOptions - An alternative entry point to the 463 /// CommandLine library, which allows you to read the program's name 464 /// from the caller (as PROGNAME) and its command-line arguments from 465 /// an environment variable (whose name is given in ENVVAR). 466 /// 467 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar, 468 const char *Overview, bool ReadResponseFiles) { 469 // Check args. 470 assert(progName && "Program name not specified"); 471 assert(envVar && "Environment variable name missing"); 472 473 // Get the environment variable they want us to parse options out of. 474 const char *envValue = getenv(envVar); 475 if (!envValue) 476 return; 477 478 // Get program's "name", which we wouldn't know without the caller 479 // telling us. 480 std::vector<char*> newArgv; 481 newArgv.push_back(strdup(progName)); 482 483 // Parse the value of the environment variable into a "command line" 484 // and hand it off to ParseCommandLineOptions(). 485 ParseCStringVector(newArgv, envValue); 486 int newArgc = static_cast<int>(newArgv.size()); 487 ParseCommandLineOptions(newArgc, &newArgv[0], Overview, ReadResponseFiles); 488 489 // Free all the strdup()ed strings. 490 for (std::vector<char*>::iterator i = newArgv.begin(), e = newArgv.end(); 491 i != e; ++i) 492 free(*i); 493 } 494 495 496 /// ExpandResponseFiles - Copy the contents of argv into newArgv, 497 /// substituting the contents of the response files for the arguments 498 /// of type @file. 499 static void ExpandResponseFiles(unsigned argc, char** argv, 500 std::vector<char*>& newArgv) { 501 for (unsigned i = 1; i != argc; ++i) { 502 char *arg = argv[i]; 503 504 if (arg[0] == '@') { 505 sys::PathWithStatus respFile(++arg); 506 507 // Check that the response file is not empty (mmap'ing empty 508 // files can be problematic). 509 const sys::FileStatus *FileStat = respFile.getFileStatus(); 510 if (FileStat && FileStat->getSize() != 0) { 511 512 // If we could open the file, parse its contents, otherwise 513 // pass the @file option verbatim. 514 515 // TODO: we should also support recursive loading of response files, 516 // since this is how gcc behaves. (From their man page: "The file may 517 // itself contain additional @file options; any such options will be 518 // processed recursively.") 519 520 // Mmap the response file into memory. 521 OwningPtr<MemoryBuffer> respFilePtr; 522 if (!MemoryBuffer::getFile(respFile.c_str(), respFilePtr)) { 523 ParseCStringVector(newArgv, respFilePtr->getBufferStart()); 524 continue; 525 } 526 } 527 } 528 newArgv.push_back(strdup(arg)); 529 } 530 } 531 532 void cl::ParseCommandLineOptions(int argc, char **argv, 533 const char *Overview, bool ReadResponseFiles) { 534 // Process all registered options. 535 SmallVector<Option*, 4> PositionalOpts; 536 SmallVector<Option*, 4> SinkOpts; 537 StringMap<Option*> Opts; 538 GetOptionInfo(PositionalOpts, SinkOpts, Opts); 539 540 assert((!Opts.empty() || !PositionalOpts.empty()) && 541 "No options specified!"); 542 543 // Expand response files. 544 std::vector<char*> newArgv; 545 if (ReadResponseFiles) { 546 newArgv.push_back(strdup(argv[0])); 547 ExpandResponseFiles(argc, argv, newArgv); 548 argv = &newArgv[0]; 549 argc = static_cast<int>(newArgv.size()); 550 } 551 552 // Copy the program name into ProgName, making sure not to overflow it. 553 std::string ProgName = sys::path::filename(argv[0]); 554 size_t Len = std::min(ProgName.size(), size_t(79)); 555 memcpy(ProgramName, ProgName.data(), Len); 556 ProgramName[Len] = '\0'; 557 558 ProgramOverview = Overview; 559 bool ErrorParsing = false; 560 561 // Check out the positional arguments to collect information about them. 562 unsigned NumPositionalRequired = 0; 563 564 // Determine whether or not there are an unlimited number of positionals 565 bool HasUnlimitedPositionals = false; 566 567 Option *ConsumeAfterOpt = 0; 568 if (!PositionalOpts.empty()) { 569 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) { 570 assert(PositionalOpts.size() > 1 && 571 "Cannot specify cl::ConsumeAfter without a positional argument!"); 572 ConsumeAfterOpt = PositionalOpts[0]; 573 } 574 575 // Calculate how many positional values are _required_. 576 bool UnboundedFound = false; 577 for (size_t i = ConsumeAfterOpt != 0, e = PositionalOpts.size(); 578 i != e; ++i) { 579 Option *Opt = PositionalOpts[i]; 580 if (RequiresValue(Opt)) 581 ++NumPositionalRequired; 582 else if (ConsumeAfterOpt) { 583 // ConsumeAfter cannot be combined with "optional" positional options 584 // unless there is only one positional argument... 585 if (PositionalOpts.size() > 2) 586 ErrorParsing |= 587 Opt->error("error - this positional option will never be matched, " 588 "because it does not Require a value, and a " 589 "cl::ConsumeAfter option is active!"); 590 } else if (UnboundedFound && !Opt->ArgStr[0]) { 591 // This option does not "require" a value... Make sure this option is 592 // not specified after an option that eats all extra arguments, or this 593 // one will never get any! 594 // 595 ErrorParsing |= Opt->error("error - option can never match, because " 596 "another positional argument will match an " 597 "unbounded number of values, and this option" 598 " does not require a value!"); 599 } 600 UnboundedFound |= EatsUnboundedNumberOfValues(Opt); 601 } 602 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt; 603 } 604 605 // PositionalVals - A vector of "positional" arguments we accumulate into 606 // the process at the end. 607 // 608 SmallVector<std::pair<StringRef,unsigned>, 4> PositionalVals; 609 610 // If the program has named positional arguments, and the name has been run 611 // across, keep track of which positional argument was named. Otherwise put 612 // the positional args into the PositionalVals list... 613 Option *ActivePositionalArg = 0; 614 615 // Loop over all of the arguments... processing them. 616 bool DashDashFound = false; // Have we read '--'? 617 for (int i = 1; i < argc; ++i) { 618 Option *Handler = 0; 619 Option *NearestHandler = 0; 620 std::string NearestHandlerString; 621 StringRef Value; 622 StringRef ArgName = ""; 623 624 // If the option list changed, this means that some command line 625 // option has just been registered or deregistered. This can occur in 626 // response to things like -load, etc. If this happens, rescan the options. 627 if (OptionListChanged) { 628 PositionalOpts.clear(); 629 SinkOpts.clear(); 630 Opts.clear(); 631 GetOptionInfo(PositionalOpts, SinkOpts, Opts); 632 OptionListChanged = false; 633 } 634 635 // Check to see if this is a positional argument. This argument is 636 // considered to be positional if it doesn't start with '-', if it is "-" 637 // itself, or if we have seen "--" already. 638 // 639 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) { 640 // Positional argument! 641 if (ActivePositionalArg) { 642 ProvidePositionalOption(ActivePositionalArg, argv[i], i); 643 continue; // We are done! 644 } 645 646 if (!PositionalOpts.empty()) { 647 PositionalVals.push_back(std::make_pair(argv[i],i)); 648 649 // All of the positional arguments have been fulfulled, give the rest to 650 // the consume after option... if it's specified... 651 // 652 if (PositionalVals.size() >= NumPositionalRequired && 653 ConsumeAfterOpt != 0) { 654 for (++i; i < argc; ++i) 655 PositionalVals.push_back(std::make_pair(argv[i],i)); 656 break; // Handle outside of the argument processing loop... 657 } 658 659 // Delay processing positional arguments until the end... 660 continue; 661 } 662 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 && 663 !DashDashFound) { 664 DashDashFound = true; // This is the mythical "--"? 665 continue; // Don't try to process it as an argument itself. 666 } else if (ActivePositionalArg && 667 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) { 668 // If there is a positional argument eating options, check to see if this 669 // option is another positional argument. If so, treat it as an argument, 670 // otherwise feed it to the eating positional. 671 ArgName = argv[i]+1; 672 // Eat leading dashes. 673 while (!ArgName.empty() && ArgName[0] == '-') 674 ArgName = ArgName.substr(1); 675 676 Handler = LookupOption(ArgName, Value, Opts); 677 if (!Handler || Handler->getFormattingFlag() != cl::Positional) { 678 ProvidePositionalOption(ActivePositionalArg, argv[i], i); 679 continue; // We are done! 680 } 681 682 } else { // We start with a '-', must be an argument. 683 ArgName = argv[i]+1; 684 // Eat leading dashes. 685 while (!ArgName.empty() && ArgName[0] == '-') 686 ArgName = ArgName.substr(1); 687 688 Handler = LookupOption(ArgName, Value, Opts); 689 690 // Check to see if this "option" is really a prefixed or grouped argument. 691 if (Handler == 0) 692 Handler = HandlePrefixedOrGroupedOption(ArgName, Value, 693 ErrorParsing, Opts); 694 695 // Otherwise, look for the closest available option to report to the user 696 // in the upcoming error. 697 if (Handler == 0 && SinkOpts.empty()) 698 NearestHandler = LookupNearestOption(ArgName, Opts, 699 NearestHandlerString); 700 } 701 702 if (Handler == 0) { 703 if (SinkOpts.empty()) { 704 errs() << ProgramName << ": Unknown command line argument '" 705 << argv[i] << "'. Try: '" << argv[0] << " -help'\n"; 706 707 if (NearestHandler) { 708 // If we know a near match, report it as well. 709 errs() << ProgramName << ": Did you mean '-" 710 << NearestHandlerString << "'?\n"; 711 } 712 713 ErrorParsing = true; 714 } else { 715 for (SmallVectorImpl<Option*>::iterator I = SinkOpts.begin(), 716 E = SinkOpts.end(); I != E ; ++I) 717 (*I)->addOccurrence(i, "", argv[i]); 718 } 719 continue; 720 } 721 722 // If this is a named positional argument, just remember that it is the 723 // active one... 724 if (Handler->getFormattingFlag() == cl::Positional) 725 ActivePositionalArg = Handler; 726 else 727 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i); 728 } 729 730 // Check and handle positional arguments now... 731 if (NumPositionalRequired > PositionalVals.size()) { 732 errs() << ProgramName 733 << ": Not enough positional command line arguments specified!\n" 734 << "Must specify at least " << NumPositionalRequired 735 << " positional arguments: See: " << argv[0] << " -help\n"; 736 737 ErrorParsing = true; 738 } else if (!HasUnlimitedPositionals && 739 PositionalVals.size() > PositionalOpts.size()) { 740 errs() << ProgramName 741 << ": Too many positional arguments specified!\n" 742 << "Can specify at most " << PositionalOpts.size() 743 << " positional arguments: See: " << argv[0] << " -help\n"; 744 ErrorParsing = true; 745 746 } else if (ConsumeAfterOpt == 0) { 747 // Positional args have already been handled if ConsumeAfter is specified. 748 unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size()); 749 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) { 750 if (RequiresValue(PositionalOpts[i])) { 751 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first, 752 PositionalVals[ValNo].second); 753 ValNo++; 754 --NumPositionalRequired; // We fulfilled our duty... 755 } 756 757 // If we _can_ give this option more arguments, do so now, as long as we 758 // do not give it values that others need. 'Done' controls whether the 759 // option even _WANTS_ any more. 760 // 761 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required; 762 while (NumVals-ValNo > NumPositionalRequired && !Done) { 763 switch (PositionalOpts[i]->getNumOccurrencesFlag()) { 764 case cl::Optional: 765 Done = true; // Optional arguments want _at most_ one value 766 // FALL THROUGH 767 case cl::ZeroOrMore: // Zero or more will take all they can get... 768 case cl::OneOrMore: // One or more will take all they can get... 769 ProvidePositionalOption(PositionalOpts[i], 770 PositionalVals[ValNo].first, 771 PositionalVals[ValNo].second); 772 ValNo++; 773 break; 774 default: 775 llvm_unreachable("Internal error, unexpected NumOccurrences flag in " 776 "positional argument processing!"); 777 } 778 } 779 } 780 } else { 781 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size()); 782 unsigned ValNo = 0; 783 for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j) 784 if (RequiresValue(PositionalOpts[j])) { 785 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j], 786 PositionalVals[ValNo].first, 787 PositionalVals[ValNo].second); 788 ValNo++; 789 } 790 791 // Handle the case where there is just one positional option, and it's 792 // optional. In this case, we want to give JUST THE FIRST option to the 793 // positional option and keep the rest for the consume after. The above 794 // loop would have assigned no values to positional options in this case. 795 // 796 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) { 797 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1], 798 PositionalVals[ValNo].first, 799 PositionalVals[ValNo].second); 800 ValNo++; 801 } 802 803 // Handle over all of the rest of the arguments to the 804 // cl::ConsumeAfter command line option... 805 for (; ValNo != PositionalVals.size(); ++ValNo) 806 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt, 807 PositionalVals[ValNo].first, 808 PositionalVals[ValNo].second); 809 } 810 811 // Loop over args and make sure all required args are specified! 812 for (StringMap<Option*>::iterator I = Opts.begin(), 813 E = Opts.end(); I != E; ++I) { 814 switch (I->second->getNumOccurrencesFlag()) { 815 case Required: 816 case OneOrMore: 817 if (I->second->getNumOccurrences() == 0) { 818 I->second->error("must be specified at least once!"); 819 ErrorParsing = true; 820 } 821 // Fall through 822 default: 823 break; 824 } 825 } 826 827 // Now that we know if -debug is specified, we can use it. 828 // Note that if ReadResponseFiles == true, this must be done before the 829 // memory allocated for the expanded command line is free()d below. 830 DEBUG(dbgs() << "Args: "; 831 for (int i = 0; i < argc; ++i) 832 dbgs() << argv[i] << ' '; 833 dbgs() << '\n'; 834 ); 835 836 // Free all of the memory allocated to the map. Command line options may only 837 // be processed once! 838 Opts.clear(); 839 PositionalOpts.clear(); 840 MoreHelp->clear(); 841 842 // Free the memory allocated by ExpandResponseFiles. 843 if (ReadResponseFiles) { 844 // Free all the strdup()ed strings. 845 for (std::vector<char*>::iterator i = newArgv.begin(), e = newArgv.end(); 846 i != e; ++i) 847 free(*i); 848 } 849 850 // If we had an error processing our arguments, don't let the program execute 851 if (ErrorParsing) exit(1); 852 } 853 854 //===----------------------------------------------------------------------===// 855 // Option Base class implementation 856 // 857 858 bool Option::error(const Twine &Message, StringRef ArgName) { 859 if (ArgName.data() == 0) ArgName = ArgStr; 860 if (ArgName.empty()) 861 errs() << HelpStr; // Be nice for positional arguments 862 else 863 errs() << ProgramName << ": for the -" << ArgName; 864 865 errs() << " option: " << Message << "\n"; 866 return true; 867 } 868 869 bool Option::addOccurrence(unsigned pos, StringRef ArgName, 870 StringRef Value, bool MultiArg) { 871 if (!MultiArg) 872 NumOccurrences++; // Increment the number of times we have been seen 873 874 switch (getNumOccurrencesFlag()) { 875 case Optional: 876 if (NumOccurrences > 1) 877 return error("may only occur zero or one times!", ArgName); 878 break; 879 case Required: 880 if (NumOccurrences > 1) 881 return error("must occur exactly one time!", ArgName); 882 // Fall through 883 case OneOrMore: 884 case ZeroOrMore: 885 case ConsumeAfter: break; 886 default: return error("bad num occurrences flag value!"); 887 } 888 889 return handleOccurrence(pos, ArgName, Value); 890 } 891 892 893 // getValueStr - Get the value description string, using "DefaultMsg" if nothing 894 // has been specified yet. 895 // 896 static const char *getValueStr(const Option &O, const char *DefaultMsg) { 897 if (O.ValueStr[0] == 0) return DefaultMsg; 898 return O.ValueStr; 899 } 900 901 //===----------------------------------------------------------------------===// 902 // cl::alias class implementation 903 // 904 905 // Return the width of the option tag for printing... 906 size_t alias::getOptionWidth() const { 907 return std::strlen(ArgStr)+6; 908 } 909 910 // Print out the option for the alias. 911 void alias::printOptionInfo(size_t GlobalWidth) const { 912 size_t L = std::strlen(ArgStr); 913 outs() << " -" << ArgStr; 914 outs().indent(GlobalWidth-L-6) << " - " << HelpStr << "\n"; 915 } 916 917 //===----------------------------------------------------------------------===// 918 // Parser Implementation code... 919 // 920 921 // basic_parser implementation 922 // 923 924 // Return the width of the option tag for printing... 925 size_t basic_parser_impl::getOptionWidth(const Option &O) const { 926 size_t Len = std::strlen(O.ArgStr); 927 if (const char *ValName = getValueName()) 928 Len += std::strlen(getValueStr(O, ValName))+3; 929 930 return Len + 6; 931 } 932 933 // printOptionInfo - Print out information about this option. The 934 // to-be-maintained width is specified. 935 // 936 void basic_parser_impl::printOptionInfo(const Option &O, 937 size_t GlobalWidth) const { 938 outs() << " -" << O.ArgStr; 939 940 if (const char *ValName = getValueName()) 941 outs() << "=<" << getValueStr(O, ValName) << '>'; 942 943 outs().indent(GlobalWidth-getOptionWidth(O)) << " - " << O.HelpStr << '\n'; 944 } 945 946 void basic_parser_impl::printOptionName(const Option &O, 947 size_t GlobalWidth) const { 948 outs() << " -" << O.ArgStr; 949 outs().indent(GlobalWidth-std::strlen(O.ArgStr)); 950 } 951 952 953 // parser<bool> implementation 954 // 955 bool parser<bool>::parse(Option &O, StringRef ArgName, 956 StringRef Arg, bool &Value) { 957 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" || 958 Arg == "1") { 959 Value = true; 960 return false; 961 } 962 963 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") { 964 Value = false; 965 return false; 966 } 967 return O.error("'" + Arg + 968 "' is invalid value for boolean argument! Try 0 or 1"); 969 } 970 971 // parser<boolOrDefault> implementation 972 // 973 bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName, 974 StringRef Arg, boolOrDefault &Value) { 975 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" || 976 Arg == "1") { 977 Value = BOU_TRUE; 978 return false; 979 } 980 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") { 981 Value = BOU_FALSE; 982 return false; 983 } 984 985 return O.error("'" + Arg + 986 "' is invalid value for boolean argument! Try 0 or 1"); 987 } 988 989 // parser<int> implementation 990 // 991 bool parser<int>::parse(Option &O, StringRef ArgName, 992 StringRef Arg, int &Value) { 993 if (Arg.getAsInteger(0, Value)) 994 return O.error("'" + Arg + "' value invalid for integer argument!"); 995 return false; 996 } 997 998 // parser<unsigned> implementation 999 // 1000 bool parser<unsigned>::parse(Option &O, StringRef ArgName, 1001 StringRef Arg, unsigned &Value) { 1002 1003 if (Arg.getAsInteger(0, Value)) 1004 return O.error("'" + Arg + "' value invalid for uint argument!"); 1005 return false; 1006 } 1007 1008 // parser<double>/parser<float> implementation 1009 // 1010 static bool parseDouble(Option &O, StringRef Arg, double &Value) { 1011 SmallString<32> TmpStr(Arg.begin(), Arg.end()); 1012 const char *ArgStart = TmpStr.c_str(); 1013 char *End; 1014 Value = strtod(ArgStart, &End); 1015 if (*End != 0) 1016 return O.error("'" + Arg + "' value invalid for floating point argument!"); 1017 return false; 1018 } 1019 1020 bool parser<double>::parse(Option &O, StringRef ArgName, 1021 StringRef Arg, double &Val) { 1022 return parseDouble(O, Arg, Val); 1023 } 1024 1025 bool parser<float>::parse(Option &O, StringRef ArgName, 1026 StringRef Arg, float &Val) { 1027 double dVal; 1028 if (parseDouble(O, Arg, dVal)) 1029 return true; 1030 Val = (float)dVal; 1031 return false; 1032 } 1033 1034 1035 1036 // generic_parser_base implementation 1037 // 1038 1039 // findOption - Return the option number corresponding to the specified 1040 // argument string. If the option is not found, getNumOptions() is returned. 1041 // 1042 unsigned generic_parser_base::findOption(const char *Name) { 1043 unsigned e = getNumOptions(); 1044 1045 for (unsigned i = 0; i != e; ++i) { 1046 if (strcmp(getOption(i), Name) == 0) 1047 return i; 1048 } 1049 return e; 1050 } 1051 1052 1053 // Return the width of the option tag for printing... 1054 size_t generic_parser_base::getOptionWidth(const Option &O) const { 1055 if (O.hasArgStr()) { 1056 size_t Size = std::strlen(O.ArgStr)+6; 1057 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) 1058 Size = std::max(Size, std::strlen(getOption(i))+8); 1059 return Size; 1060 } else { 1061 size_t BaseSize = 0; 1062 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) 1063 BaseSize = std::max(BaseSize, std::strlen(getOption(i))+8); 1064 return BaseSize; 1065 } 1066 } 1067 1068 // printOptionInfo - Print out information about this option. The 1069 // to-be-maintained width is specified. 1070 // 1071 void generic_parser_base::printOptionInfo(const Option &O, 1072 size_t GlobalWidth) const { 1073 if (O.hasArgStr()) { 1074 size_t L = std::strlen(O.ArgStr); 1075 outs() << " -" << O.ArgStr; 1076 outs().indent(GlobalWidth-L-6) << " - " << O.HelpStr << '\n'; 1077 1078 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) { 1079 size_t NumSpaces = GlobalWidth-strlen(getOption(i))-8; 1080 outs() << " =" << getOption(i); 1081 outs().indent(NumSpaces) << " - " << getDescription(i) << '\n'; 1082 } 1083 } else { 1084 if (O.HelpStr[0]) 1085 outs() << " " << O.HelpStr << '\n'; 1086 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) { 1087 size_t L = std::strlen(getOption(i)); 1088 outs() << " -" << getOption(i); 1089 outs().indent(GlobalWidth-L-8) << " - " << getDescription(i) << '\n'; 1090 } 1091 } 1092 } 1093 1094 static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff 1095 1096 // printGenericOptionDiff - Print the value of this option and it's default. 1097 // 1098 // "Generic" options have each value mapped to a name. 1099 void generic_parser_base:: 1100 printGenericOptionDiff(const Option &O, const GenericOptionValue &Value, 1101 const GenericOptionValue &Default, 1102 size_t GlobalWidth) const { 1103 outs() << " -" << O.ArgStr; 1104 outs().indent(GlobalWidth-std::strlen(O.ArgStr)); 1105 1106 unsigned NumOpts = getNumOptions(); 1107 for (unsigned i = 0; i != NumOpts; ++i) { 1108 if (Value.compare(getOptionValue(i))) 1109 continue; 1110 1111 outs() << "= " << getOption(i); 1112 size_t L = std::strlen(getOption(i)); 1113 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0; 1114 outs().indent(NumSpaces) << " (default: "; 1115 for (unsigned j = 0; j != NumOpts; ++j) { 1116 if (Default.compare(getOptionValue(j))) 1117 continue; 1118 outs() << getOption(j); 1119 break; 1120 } 1121 outs() << ")\n"; 1122 return; 1123 } 1124 outs() << "= *unknown option value*\n"; 1125 } 1126 1127 // printOptionDiff - Specializations for printing basic value types. 1128 // 1129 #define PRINT_OPT_DIFF(T) \ 1130 void parser<T>:: \ 1131 printOptionDiff(const Option &O, T V, OptionValue<T> D, \ 1132 size_t GlobalWidth) const { \ 1133 printOptionName(O, GlobalWidth); \ 1134 std::string Str; \ 1135 { \ 1136 raw_string_ostream SS(Str); \ 1137 SS << V; \ 1138 } \ 1139 outs() << "= " << Str; \ 1140 size_t NumSpaces = MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0;\ 1141 outs().indent(NumSpaces) << " (default: "; \ 1142 if (D.hasValue()) \ 1143 outs() << D.getValue(); \ 1144 else \ 1145 outs() << "*no default*"; \ 1146 outs() << ")\n"; \ 1147 } \ 1148 1149 PRINT_OPT_DIFF(bool) 1150 PRINT_OPT_DIFF(boolOrDefault) 1151 PRINT_OPT_DIFF(int) 1152 PRINT_OPT_DIFF(unsigned) 1153 PRINT_OPT_DIFF(double) 1154 PRINT_OPT_DIFF(float) 1155 PRINT_OPT_DIFF(char) 1156 1157 void parser<std::string>:: 1158 printOptionDiff(const Option &O, StringRef V, OptionValue<std::string> D, 1159 size_t GlobalWidth) const { 1160 printOptionName(O, GlobalWidth); 1161 outs() << "= " << V; 1162 size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0; 1163 outs().indent(NumSpaces) << " (default: "; 1164 if (D.hasValue()) 1165 outs() << D.getValue(); 1166 else 1167 outs() << "*no default*"; 1168 outs() << ")\n"; 1169 } 1170 1171 // Print a placeholder for options that don't yet support printOptionDiff(). 1172 void basic_parser_impl:: 1173 printOptionNoValue(const Option &O, size_t GlobalWidth) const { 1174 printOptionName(O, GlobalWidth); 1175 outs() << "= *cannot print option value*\n"; 1176 } 1177 1178 //===----------------------------------------------------------------------===// 1179 // -help and -help-hidden option implementation 1180 // 1181 1182 static int OptNameCompare(const void *LHS, const void *RHS) { 1183 typedef std::pair<const char *, Option*> pair_ty; 1184 1185 return strcmp(((pair_ty*)LHS)->first, ((pair_ty*)RHS)->first); 1186 } 1187 1188 // Copy Options into a vector so we can sort them as we like. 1189 static void 1190 sortOpts(StringMap<Option*> &OptMap, 1191 SmallVectorImpl< std::pair<const char *, Option*> > &Opts, 1192 bool ShowHidden) { 1193 SmallPtrSet<Option*, 128> OptionSet; // Duplicate option detection. 1194 1195 for (StringMap<Option*>::iterator I = OptMap.begin(), E = OptMap.end(); 1196 I != E; ++I) { 1197 // Ignore really-hidden options. 1198 if (I->second->getOptionHiddenFlag() == ReallyHidden) 1199 continue; 1200 1201 // Unless showhidden is set, ignore hidden flags. 1202 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden) 1203 continue; 1204 1205 // If we've already seen this option, don't add it to the list again. 1206 if (!OptionSet.insert(I->second)) 1207 continue; 1208 1209 Opts.push_back(std::pair<const char *, Option*>(I->getKey().data(), 1210 I->second)); 1211 } 1212 1213 // Sort the options list alphabetically. 1214 qsort(Opts.data(), Opts.size(), sizeof(Opts[0]), OptNameCompare); 1215 } 1216 1217 namespace { 1218 1219 class HelpPrinter { 1220 size_t MaxArgLen; 1221 const Option *EmptyArg; 1222 const bool ShowHidden; 1223 1224 public: 1225 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) { 1226 EmptyArg = 0; 1227 } 1228 1229 void operator=(bool Value) { 1230 if (Value == false) return; 1231 1232 // Get all the options. 1233 SmallVector<Option*, 4> PositionalOpts; 1234 SmallVector<Option*, 4> SinkOpts; 1235 StringMap<Option*> OptMap; 1236 GetOptionInfo(PositionalOpts, SinkOpts, OptMap); 1237 1238 SmallVector<std::pair<const char *, Option*>, 128> Opts; 1239 sortOpts(OptMap, Opts, ShowHidden); 1240 1241 if (ProgramOverview) 1242 outs() << "OVERVIEW: " << ProgramOverview << "\n"; 1243 1244 outs() << "USAGE: " << ProgramName << " [options]"; 1245 1246 // Print out the positional options. 1247 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists... 1248 if (!PositionalOpts.empty() && 1249 PositionalOpts[0]->getNumOccurrencesFlag() == ConsumeAfter) 1250 CAOpt = PositionalOpts[0]; 1251 1252 for (size_t i = CAOpt != 0, e = PositionalOpts.size(); i != e; ++i) { 1253 if (PositionalOpts[i]->ArgStr[0]) 1254 outs() << " --" << PositionalOpts[i]->ArgStr; 1255 outs() << " " << PositionalOpts[i]->HelpStr; 1256 } 1257 1258 // Print the consume after option info if it exists... 1259 if (CAOpt) outs() << " " << CAOpt->HelpStr; 1260 1261 outs() << "\n\n"; 1262 1263 // Compute the maximum argument length... 1264 MaxArgLen = 0; 1265 for (size_t i = 0, e = Opts.size(); i != e; ++i) 1266 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth()); 1267 1268 outs() << "OPTIONS:\n"; 1269 for (size_t i = 0, e = Opts.size(); i != e; ++i) 1270 Opts[i].second->printOptionInfo(MaxArgLen); 1271 1272 // Print any extra help the user has declared. 1273 for (std::vector<const char *>::iterator I = MoreHelp->begin(), 1274 E = MoreHelp->end(); I != E; ++I) 1275 outs() << *I; 1276 MoreHelp->clear(); 1277 1278 // Halt the program since help information was printed 1279 exit(1); 1280 } 1281 }; 1282 } // End anonymous namespace 1283 1284 // Define the two HelpPrinter instances that are used to print out help, or 1285 // help-hidden... 1286 // 1287 static HelpPrinter NormalPrinter(false); 1288 static HelpPrinter HiddenPrinter(true); 1289 1290 static cl::opt<HelpPrinter, true, parser<bool> > 1291 HOp("help", cl::desc("Display available options (-help-hidden for more)"), 1292 cl::location(NormalPrinter), cl::ValueDisallowed); 1293 1294 static cl::opt<HelpPrinter, true, parser<bool> > 1295 HHOp("help-hidden", cl::desc("Display all available options"), 1296 cl::location(HiddenPrinter), cl::Hidden, cl::ValueDisallowed); 1297 1298 static cl::opt<bool> 1299 PrintOptions("print-options", 1300 cl::desc("Print non-default options after command line parsing"), 1301 cl::Hidden, cl::init(false)); 1302 1303 static cl::opt<bool> 1304 PrintAllOptions("print-all-options", 1305 cl::desc("Print all option values after command line parsing"), 1306 cl::Hidden, cl::init(false)); 1307 1308 // Print the value of each option. 1309 void cl::PrintOptionValues() { 1310 if (!PrintOptions && !PrintAllOptions) return; 1311 1312 // Get all the options. 1313 SmallVector<Option*, 4> PositionalOpts; 1314 SmallVector<Option*, 4> SinkOpts; 1315 StringMap<Option*> OptMap; 1316 GetOptionInfo(PositionalOpts, SinkOpts, OptMap); 1317 1318 SmallVector<std::pair<const char *, Option*>, 128> Opts; 1319 sortOpts(OptMap, Opts, /*ShowHidden*/true); 1320 1321 // Compute the maximum argument length... 1322 size_t MaxArgLen = 0; 1323 for (size_t i = 0, e = Opts.size(); i != e; ++i) 1324 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth()); 1325 1326 for (size_t i = 0, e = Opts.size(); i != e; ++i) 1327 Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions); 1328 } 1329 1330 static void (*OverrideVersionPrinter)() = 0; 1331 1332 static std::vector<void (*)()>* ExtraVersionPrinters = 0; 1333 1334 namespace { 1335 class VersionPrinter { 1336 public: 1337 void print() { 1338 raw_ostream &OS = outs(); 1339 OS << "Low Level Virtual Machine (http://llvm.org/):\n" 1340 << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION; 1341 #ifdef LLVM_VERSION_INFO 1342 OS << LLVM_VERSION_INFO; 1343 #endif 1344 OS << "\n "; 1345 #ifndef __OPTIMIZE__ 1346 OS << "DEBUG build"; 1347 #else 1348 OS << "Optimized build"; 1349 #endif 1350 #ifndef NDEBUG 1351 OS << " with assertions"; 1352 #endif 1353 std::string CPU = sys::getHostCPUName(); 1354 if (CPU == "generic") CPU = "(unknown)"; 1355 OS << ".\n" 1356 #if (ENABLE_TIMESTAMPS == 1) 1357 << " Built " << __DATE__ << " (" << __TIME__ << ").\n" 1358 #endif 1359 << " Host: " << sys::getHostTriple() << '\n' 1360 << " Host CPU: " << CPU << '\n'; 1361 } 1362 void operator=(bool OptionWasSpecified) { 1363 if (!OptionWasSpecified) return; 1364 1365 if (OverrideVersionPrinter != 0) { 1366 (*OverrideVersionPrinter)(); 1367 exit(1); 1368 } 1369 print(); 1370 1371 // Iterate over any registered extra printers and call them to add further 1372 // information. 1373 if (ExtraVersionPrinters != 0) { 1374 outs() << '\n'; 1375 for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(), 1376 E = ExtraVersionPrinters->end(); 1377 I != E; ++I) 1378 (*I)(); 1379 } 1380 1381 exit(1); 1382 } 1383 }; 1384 } // End anonymous namespace 1385 1386 1387 // Define the --version option that prints out the LLVM version for the tool 1388 static VersionPrinter VersionPrinterInstance; 1389 1390 static cl::opt<VersionPrinter, true, parser<bool> > 1391 VersOp("version", cl::desc("Display the version of this program"), 1392 cl::location(VersionPrinterInstance), cl::ValueDisallowed); 1393 1394 // Utility function for printing the help message. 1395 void cl::PrintHelpMessage() { 1396 // This looks weird, but it actually prints the help message. The 1397 // NormalPrinter variable is a HelpPrinter and the help gets printed when 1398 // its operator= is invoked. That's because the "normal" usages of the 1399 // help printer is to be assigned true/false depending on whether the 1400 // -help option was given or not. Since we're circumventing that we have 1401 // to make it look like -help was given, so we assign true. 1402 NormalPrinter = true; 1403 } 1404 1405 /// Utility function for printing version number. 1406 void cl::PrintVersionMessage() { 1407 VersionPrinterInstance.print(); 1408 } 1409 1410 void cl::SetVersionPrinter(void (*func)()) { 1411 OverrideVersionPrinter = func; 1412 } 1413 1414 void cl::AddExtraVersionPrinter(void (*func)()) { 1415 if (ExtraVersionPrinters == 0) 1416 ExtraVersionPrinters = new std::vector<void (*)()>; 1417 1418 ExtraVersionPrinters->push_back(func); 1419 } 1420