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/ADT/ArrayRef.h" 21 #include "llvm/ADT/OwningPtr.h" 22 #include "llvm/ADT/SmallPtrSet.h" 23 #include "llvm/ADT/SmallString.h" 24 #include "llvm/ADT/StringMap.h" 25 #include "llvm/ADT/Twine.h" 26 #include "llvm/Config/config.h" 27 #include "llvm/Support/ConvertUTF.h" 28 #include "llvm/Support/Debug.h" 29 #include "llvm/Support/ErrorHandling.h" 30 #include "llvm/Support/Host.h" 31 #include "llvm/Support/ManagedStatic.h" 32 #include "llvm/Support/MemoryBuffer.h" 33 #include "llvm/Support/Path.h" 34 #include "llvm/Support/raw_ostream.h" 35 #include "llvm/Support/system_error.h" 36 #include <cerrno> 37 #include <cstdlib> 38 #include <map> 39 #include <set> 40 using namespace llvm; 41 using namespace cl; 42 43 //===----------------------------------------------------------------------===// 44 // Template instantiations and anchors. 45 // 46 namespace llvm { namespace cl { 47 TEMPLATE_INSTANTIATION(class basic_parser<bool>); 48 TEMPLATE_INSTANTIATION(class basic_parser<boolOrDefault>); 49 TEMPLATE_INSTANTIATION(class basic_parser<int>); 50 TEMPLATE_INSTANTIATION(class basic_parser<unsigned>); 51 TEMPLATE_INSTANTIATION(class basic_parser<unsigned long long>); 52 TEMPLATE_INSTANTIATION(class basic_parser<double>); 53 TEMPLATE_INSTANTIATION(class basic_parser<float>); 54 TEMPLATE_INSTANTIATION(class basic_parser<std::string>); 55 TEMPLATE_INSTANTIATION(class basic_parser<char>); 56 57 TEMPLATE_INSTANTIATION(class opt<unsigned>); 58 TEMPLATE_INSTANTIATION(class opt<int>); 59 TEMPLATE_INSTANTIATION(class opt<std::string>); 60 TEMPLATE_INSTANTIATION(class opt<char>); 61 TEMPLATE_INSTANTIATION(class opt<bool>); 62 } } // end namespace llvm::cl 63 64 // Pin the vtables to this file. 65 void GenericOptionValue::anchor() {} 66 void OptionValue<boolOrDefault>::anchor() {} 67 void OptionValue<std::string>::anchor() {} 68 void Option::anchor() {} 69 void basic_parser_impl::anchor() {} 70 void parser<bool>::anchor() {} 71 void parser<boolOrDefault>::anchor() {} 72 void parser<int>::anchor() {} 73 void parser<unsigned>::anchor() {} 74 void parser<unsigned long long>::anchor() {} 75 void parser<double>::anchor() {} 76 void parser<float>::anchor() {} 77 void parser<std::string>::anchor() {} 78 void parser<char>::anchor() {} 79 void StringSaver::anchor() {} 80 81 //===----------------------------------------------------------------------===// 82 83 // Globals for name and overview of program. Program name is not a string to 84 // avoid static ctor/dtor issues. 85 static char ProgramName[80] = "<premain>"; 86 static const char *ProgramOverview = 0; 87 88 // This collects additional help to be printed. 89 static ManagedStatic<std::vector<const char*> > MoreHelp; 90 91 extrahelp::extrahelp(const char *Help) 92 : morehelp(Help) { 93 MoreHelp->push_back(Help); 94 } 95 96 static bool OptionListChanged = false; 97 98 // MarkOptionsChanged - Internal helper function. 99 void cl::MarkOptionsChanged() { 100 OptionListChanged = true; 101 } 102 103 /// RegisteredOptionList - This is the list of the command line options that 104 /// have statically constructed themselves. 105 static Option *RegisteredOptionList = 0; 106 107 void Option::addArgument() { 108 assert(NextRegistered == 0 && "argument multiply registered!"); 109 110 NextRegistered = RegisteredOptionList; 111 RegisteredOptionList = this; 112 MarkOptionsChanged(); 113 } 114 115 void Option::removeArgument() { 116 assert(NextRegistered != 0 && "argument never registered"); 117 assert(RegisteredOptionList == this && "argument is not the last registered"); 118 RegisteredOptionList = NextRegistered; 119 MarkOptionsChanged(); 120 } 121 122 // This collects the different option categories that have been registered. 123 typedef SmallPtrSet<OptionCategory*,16> OptionCatSet; 124 static ManagedStatic<OptionCatSet> RegisteredOptionCategories; 125 126 // Initialise the general option category. 127 OptionCategory llvm::cl::GeneralCategory("General options"); 128 129 void OptionCategory::registerCategory() 130 { 131 RegisteredOptionCategories->insert(this); 132 } 133 134 //===----------------------------------------------------------------------===// 135 // Basic, shared command line option processing machinery. 136 // 137 138 /// GetOptionInfo - Scan the list of registered options, turning them into data 139 /// structures that are easier to handle. 140 static void GetOptionInfo(SmallVectorImpl<Option*> &PositionalOpts, 141 SmallVectorImpl<Option*> &SinkOpts, 142 StringMap<Option*> &OptionsMap) { 143 SmallVector<const char*, 16> OptionNames; 144 Option *CAOpt = 0; // The ConsumeAfter option if it exists. 145 for (Option *O = RegisteredOptionList; O; O = O->getNextRegisteredOption()) { 146 // If this option wants to handle multiple option names, get the full set. 147 // This handles enum options like "-O1 -O2" etc. 148 O->getExtraOptionNames(OptionNames); 149 if (O->ArgStr[0]) 150 OptionNames.push_back(O->ArgStr); 151 152 // Handle named options. 153 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) { 154 // Add argument to the argument map! 155 if (OptionsMap.GetOrCreateValue(OptionNames[i], O).second != O) { 156 errs() << ProgramName << ": CommandLine Error: Argument '" 157 << OptionNames[i] << "' defined more than once!\n"; 158 } 159 } 160 161 OptionNames.clear(); 162 163 // Remember information about positional options. 164 if (O->getFormattingFlag() == cl::Positional) 165 PositionalOpts.push_back(O); 166 else if (O->getMiscFlags() & cl::Sink) // Remember sink options 167 SinkOpts.push_back(O); 168 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) { 169 if (CAOpt) 170 O->error("Cannot specify more than one option with cl::ConsumeAfter!"); 171 CAOpt = O; 172 } 173 } 174 175 if (CAOpt) 176 PositionalOpts.push_back(CAOpt); 177 178 // Make sure that they are in order of registration not backwards. 179 std::reverse(PositionalOpts.begin(), PositionalOpts.end()); 180 } 181 182 183 /// LookupOption - Lookup the option specified by the specified option on the 184 /// command line. If there is a value specified (after an equal sign) return 185 /// that as well. This assumes that leading dashes have already been stripped. 186 static Option *LookupOption(StringRef &Arg, StringRef &Value, 187 const StringMap<Option*> &OptionsMap) { 188 // Reject all dashes. 189 if (Arg.empty()) return 0; 190 191 size_t EqualPos = Arg.find('='); 192 193 // If we have an equals sign, remember the value. 194 if (EqualPos == StringRef::npos) { 195 // Look up the option. 196 StringMap<Option*>::const_iterator I = OptionsMap.find(Arg); 197 return I != OptionsMap.end() ? I->second : 0; 198 } 199 200 // If the argument before the = is a valid option name, we match. If not, 201 // return Arg unmolested. 202 StringMap<Option*>::const_iterator I = 203 OptionsMap.find(Arg.substr(0, EqualPos)); 204 if (I == OptionsMap.end()) return 0; 205 206 Value = Arg.substr(EqualPos+1); 207 Arg = Arg.substr(0, EqualPos); 208 return I->second; 209 } 210 211 /// LookupNearestOption - Lookup the closest match to the option specified by 212 /// the specified option on the command line. If there is a value specified 213 /// (after an equal sign) return that as well. This assumes that leading dashes 214 /// have already been stripped. 215 static Option *LookupNearestOption(StringRef Arg, 216 const StringMap<Option*> &OptionsMap, 217 std::string &NearestString) { 218 // Reject all dashes. 219 if (Arg.empty()) return 0; 220 221 // Split on any equal sign. 222 std::pair<StringRef, StringRef> SplitArg = Arg.split('='); 223 StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present. 224 StringRef &RHS = SplitArg.second; 225 226 // Find the closest match. 227 Option *Best = 0; 228 unsigned BestDistance = 0; 229 for (StringMap<Option*>::const_iterator it = OptionsMap.begin(), 230 ie = OptionsMap.end(); it != ie; ++it) { 231 Option *O = it->second; 232 SmallVector<const char*, 16> OptionNames; 233 O->getExtraOptionNames(OptionNames); 234 if (O->ArgStr[0]) 235 OptionNames.push_back(O->ArgStr); 236 237 bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed; 238 StringRef Flag = PermitValue ? LHS : Arg; 239 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) { 240 StringRef Name = OptionNames[i]; 241 unsigned Distance = StringRef(Name).edit_distance( 242 Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance); 243 if (!Best || Distance < BestDistance) { 244 Best = O; 245 BestDistance = Distance; 246 if (RHS.empty() || !PermitValue) 247 NearestString = OptionNames[i]; 248 else 249 NearestString = std::string(OptionNames[i]) + "=" + RHS.str(); 250 } 251 } 252 } 253 254 return Best; 255 } 256 257 /// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence() 258 /// that does special handling of cl::CommaSeparated options. 259 static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos, 260 StringRef ArgName, StringRef Value, 261 bool MultiArg = false) { 262 // Check to see if this option accepts a comma separated list of values. If 263 // it does, we have to split up the value into multiple values. 264 if (Handler->getMiscFlags() & CommaSeparated) { 265 StringRef Val(Value); 266 StringRef::size_type Pos = Val.find(','); 267 268 while (Pos != StringRef::npos) { 269 // Process the portion before the comma. 270 if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg)) 271 return true; 272 // Erase the portion before the comma, AND the comma. 273 Val = Val.substr(Pos+1); 274 Value.substr(Pos+1); // Increment the original value pointer as well. 275 // Check for another comma. 276 Pos = Val.find(','); 277 } 278 279 Value = Val; 280 } 281 282 if (Handler->addOccurrence(pos, ArgName, Value, MultiArg)) 283 return true; 284 285 return false; 286 } 287 288 /// ProvideOption - For Value, this differentiates between an empty value ("") 289 /// and a null value (StringRef()). The later is accepted for arguments that 290 /// don't allow a value (-foo) the former is rejected (-foo=). 291 static inline bool ProvideOption(Option *Handler, StringRef ArgName, 292 StringRef Value, int argc, 293 const char *const *argv, int &i) { 294 // Is this a multi-argument option? 295 unsigned NumAdditionalVals = Handler->getNumAdditionalVals(); 296 297 // Enforce value requirements 298 switch (Handler->getValueExpectedFlag()) { 299 case ValueRequired: 300 if (Value.data() == 0) { // No value specified? 301 if (i+1 >= argc) 302 return Handler->error("requires a value!"); 303 // Steal the next argument, like for '-o filename' 304 Value = argv[++i]; 305 } 306 break; 307 case ValueDisallowed: 308 if (NumAdditionalVals > 0) 309 return Handler->error("multi-valued option specified" 310 " with ValueDisallowed modifier!"); 311 312 if (Value.data()) 313 return Handler->error("does not allow a value! '" + 314 Twine(Value) + "' specified."); 315 break; 316 case ValueOptional: 317 break; 318 } 319 320 // If this isn't a multi-arg option, just run the handler. 321 if (NumAdditionalVals == 0) 322 return CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value); 323 324 // If it is, run the handle several times. 325 bool MultiArg = false; 326 327 if (Value.data()) { 328 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg)) 329 return true; 330 --NumAdditionalVals; 331 MultiArg = true; 332 } 333 334 while (NumAdditionalVals > 0) { 335 if (i+1 >= argc) 336 return Handler->error("not enough values!"); 337 Value = argv[++i]; 338 339 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg)) 340 return true; 341 MultiArg = true; 342 --NumAdditionalVals; 343 } 344 return false; 345 } 346 347 static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) { 348 int Dummy = i; 349 return ProvideOption(Handler, Handler->ArgStr, Arg, 0, 0, Dummy); 350 } 351 352 353 // Option predicates... 354 static inline bool isGrouping(const Option *O) { 355 return O->getFormattingFlag() == cl::Grouping; 356 } 357 static inline bool isPrefixedOrGrouping(const Option *O) { 358 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix; 359 } 360 361 // getOptionPred - Check to see if there are any options that satisfy the 362 // specified predicate with names that are the prefixes in Name. This is 363 // checked by progressively stripping characters off of the name, checking to 364 // see if there options that satisfy the predicate. If we find one, return it, 365 // otherwise return null. 366 // 367 static Option *getOptionPred(StringRef Name, size_t &Length, 368 bool (*Pred)(const Option*), 369 const StringMap<Option*> &OptionsMap) { 370 371 StringMap<Option*>::const_iterator OMI = OptionsMap.find(Name); 372 373 // Loop while we haven't found an option and Name still has at least two 374 // characters in it (so that the next iteration will not be the empty 375 // string. 376 while (OMI == OptionsMap.end() && Name.size() > 1) { 377 Name = Name.substr(0, Name.size()-1); // Chop off the last character. 378 OMI = OptionsMap.find(Name); 379 } 380 381 if (OMI != OptionsMap.end() && Pred(OMI->second)) { 382 Length = Name.size(); 383 return OMI->second; // Found one! 384 } 385 return 0; // No option found! 386 } 387 388 /// HandlePrefixedOrGroupedOption - The specified argument string (which started 389 /// with at least one '-') does not fully match an available option. Check to 390 /// see if this is a prefix or grouped option. If so, split arg into output an 391 /// Arg/Value pair and return the Option to parse it with. 392 static Option *HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value, 393 bool &ErrorParsing, 394 const StringMap<Option*> &OptionsMap) { 395 if (Arg.size() == 1) return 0; 396 397 // Do the lookup! 398 size_t Length = 0; 399 Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap); 400 if (PGOpt == 0) return 0; 401 402 // If the option is a prefixed option, then the value is simply the 403 // rest of the name... so fall through to later processing, by 404 // setting up the argument name flags and value fields. 405 if (PGOpt->getFormattingFlag() == cl::Prefix) { 406 Value = Arg.substr(Length); 407 Arg = Arg.substr(0, Length); 408 assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt); 409 return PGOpt; 410 } 411 412 // This must be a grouped option... handle them now. Grouping options can't 413 // have values. 414 assert(isGrouping(PGOpt) && "Broken getOptionPred!"); 415 416 do { 417 // Move current arg name out of Arg into OneArgName. 418 StringRef OneArgName = Arg.substr(0, Length); 419 Arg = Arg.substr(Length); 420 421 // Because ValueRequired is an invalid flag for grouped arguments, 422 // we don't need to pass argc/argv in. 423 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired && 424 "Option can not be cl::Grouping AND cl::ValueRequired!"); 425 int Dummy = 0; 426 ErrorParsing |= ProvideOption(PGOpt, OneArgName, 427 StringRef(), 0, 0, Dummy); 428 429 // Get the next grouping option. 430 PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap); 431 } while (PGOpt && Length != Arg.size()); 432 433 // Return the last option with Arg cut down to just the last one. 434 return PGOpt; 435 } 436 437 438 439 static bool RequiresValue(const Option *O) { 440 return O->getNumOccurrencesFlag() == cl::Required || 441 O->getNumOccurrencesFlag() == cl::OneOrMore; 442 } 443 444 static bool EatsUnboundedNumberOfValues(const Option *O) { 445 return O->getNumOccurrencesFlag() == cl::ZeroOrMore || 446 O->getNumOccurrencesFlag() == cl::OneOrMore; 447 } 448 449 static bool isWhitespace(char C) { 450 return strchr(" \t\n\r\f\v", C); 451 } 452 453 static bool isQuote(char C) { 454 return C == '\"' || C == '\''; 455 } 456 457 static bool isGNUSpecial(char C) { 458 return strchr("\\\"\' ", C); 459 } 460 461 void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver, 462 SmallVectorImpl<const char *> &NewArgv) { 463 SmallString<128> Token; 464 for (size_t I = 0, E = Src.size(); I != E; ++I) { 465 // Consume runs of whitespace. 466 if (Token.empty()) { 467 while (I != E && isWhitespace(Src[I])) 468 ++I; 469 if (I == E) break; 470 } 471 472 // Backslashes can escape backslashes, spaces, and other quotes. Otherwise 473 // they are literal. This makes it much easier to read Windows file paths. 474 if (I + 1 < E && Src[I] == '\\' && isGNUSpecial(Src[I + 1])) { 475 ++I; // Skip the escape. 476 Token.push_back(Src[I]); 477 continue; 478 } 479 480 // Consume a quoted string. 481 if (isQuote(Src[I])) { 482 char Quote = Src[I++]; 483 while (I != E && Src[I] != Quote) { 484 // Backslashes are literal, unless they escape a special character. 485 if (Src[I] == '\\' && I + 1 != E && isGNUSpecial(Src[I + 1])) 486 ++I; 487 Token.push_back(Src[I]); 488 ++I; 489 } 490 if (I == E) break; 491 continue; 492 } 493 494 // End the token if this is whitespace. 495 if (isWhitespace(Src[I])) { 496 if (!Token.empty()) 497 NewArgv.push_back(Saver.SaveString(Token.c_str())); 498 Token.clear(); 499 continue; 500 } 501 502 // This is a normal character. Append it. 503 Token.push_back(Src[I]); 504 } 505 506 // Append the last token after hitting EOF with no whitespace. 507 if (!Token.empty()) 508 NewArgv.push_back(Saver.SaveString(Token.c_str())); 509 } 510 511 /// Backslashes are interpreted in a rather complicated way in the Windows-style 512 /// command line, because backslashes are used both to separate path and to 513 /// escape double quote. This method consumes runs of backslashes as well as the 514 /// following double quote if it's escaped. 515 /// 516 /// * If an even number of backslashes is followed by a double quote, one 517 /// backslash is output for every pair of backslashes, and the last double 518 /// quote remains unconsumed. The double quote will later be interpreted as 519 /// the start or end of a quoted string in the main loop outside of this 520 /// function. 521 /// 522 /// * If an odd number of backslashes is followed by a double quote, one 523 /// backslash is output for every pair of backslashes, and a double quote is 524 /// output for the last pair of backslash-double quote. The double quote is 525 /// consumed in this case. 526 /// 527 /// * Otherwise, backslashes are interpreted literally. 528 static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) { 529 size_t E = Src.size(); 530 int BackslashCount = 0; 531 // Skip the backslashes. 532 do { 533 ++I; 534 ++BackslashCount; 535 } while (I != E && Src[I] == '\\'); 536 537 bool FollowedByDoubleQuote = (I != E && Src[I] == '"'); 538 if (FollowedByDoubleQuote) { 539 Token.append(BackslashCount / 2, '\\'); 540 if (BackslashCount % 2 == 0) 541 return I - 1; 542 Token.push_back('"'); 543 return I; 544 } 545 Token.append(BackslashCount, '\\'); 546 return I - 1; 547 } 548 549 void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver, 550 SmallVectorImpl<const char *> &NewArgv) { 551 SmallString<128> Token; 552 553 // This is a small state machine to consume characters until it reaches the 554 // end of the source string. 555 enum { INIT, UNQUOTED, QUOTED } State = INIT; 556 for (size_t I = 0, E = Src.size(); I != E; ++I) { 557 // INIT state indicates that the current input index is at the start of 558 // the string or between tokens. 559 if (State == INIT) { 560 if (isWhitespace(Src[I])) 561 continue; 562 if (Src[I] == '"') { 563 State = QUOTED; 564 continue; 565 } 566 if (Src[I] == '\\') { 567 I = parseBackslash(Src, I, Token); 568 State = UNQUOTED; 569 continue; 570 } 571 Token.push_back(Src[I]); 572 State = UNQUOTED; 573 continue; 574 } 575 576 // UNQUOTED state means that it's reading a token not quoted by double 577 // quotes. 578 if (State == UNQUOTED) { 579 // Whitespace means the end of the token. 580 if (isWhitespace(Src[I])) { 581 NewArgv.push_back(Saver.SaveString(Token.c_str())); 582 Token.clear(); 583 State = INIT; 584 continue; 585 } 586 if (Src[I] == '"') { 587 State = QUOTED; 588 continue; 589 } 590 if (Src[I] == '\\') { 591 I = parseBackslash(Src, I, Token); 592 continue; 593 } 594 Token.push_back(Src[I]); 595 continue; 596 } 597 598 // QUOTED state means that it's reading a token quoted by double quotes. 599 if (State == QUOTED) { 600 if (Src[I] == '"') { 601 State = UNQUOTED; 602 continue; 603 } 604 if (Src[I] == '\\') { 605 I = parseBackslash(Src, I, Token); 606 continue; 607 } 608 Token.push_back(Src[I]); 609 } 610 } 611 // Append the last token after hitting EOF with no whitespace. 612 if (!Token.empty()) 613 NewArgv.push_back(Saver.SaveString(Token.c_str())); 614 } 615 616 static bool ExpandResponseFile(const char *FName, StringSaver &Saver, 617 TokenizerCallback Tokenizer, 618 SmallVectorImpl<const char *> &NewArgv) { 619 OwningPtr<MemoryBuffer> MemBuf; 620 if (MemoryBuffer::getFile(FName, MemBuf)) 621 return false; 622 StringRef Str(MemBuf->getBufferStart(), MemBuf->getBufferSize()); 623 624 // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing. 625 ArrayRef<char> BufRef(MemBuf->getBufferStart(), MemBuf->getBufferEnd()); 626 std::string UTF8Buf; 627 if (hasUTF16ByteOrderMark(BufRef)) { 628 if (!convertUTF16ToUTF8String(BufRef, UTF8Buf)) 629 return false; 630 Str = StringRef(UTF8Buf); 631 } 632 633 // Tokenize the contents into NewArgv. 634 Tokenizer(Str, Saver, NewArgv); 635 636 return true; 637 } 638 639 /// \brief Expand response files on a command line recursively using the given 640 /// StringSaver and tokenization strategy. 641 bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer, 642 SmallVectorImpl<const char *> &Argv) { 643 unsigned RspFiles = 0; 644 bool AllExpanded = true; 645 646 // Don't cache Argv.size() because it can change. 647 for (unsigned I = 0; I != Argv.size(); ) { 648 const char *Arg = Argv[I]; 649 if (Arg[0] != '@') { 650 ++I; 651 continue; 652 } 653 654 // If we have too many response files, leave some unexpanded. This avoids 655 // crashing on self-referential response files. 656 if (RspFiles++ > 20) 657 return false; 658 659 // Replace this response file argument with the tokenization of its 660 // contents. Nested response files are expanded in subsequent iterations. 661 // FIXME: If a nested response file uses a relative path, is it relative to 662 // the cwd of the process or the response file? 663 SmallVector<const char *, 0> ExpandedArgv; 664 if (!ExpandResponseFile(Arg + 1, Saver, Tokenizer, ExpandedArgv)) { 665 // We couldn't read this file, so we leave it in the argument stream and 666 // move on. 667 AllExpanded = false; 668 ++I; 669 continue; 670 } 671 Argv.erase(Argv.begin() + I); 672 Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end()); 673 } 674 return AllExpanded; 675 } 676 677 namespace { 678 class StrDupSaver : public StringSaver { 679 std::vector<char*> Dups; 680 public: 681 ~StrDupSaver() { 682 for (std::vector<char *>::iterator I = Dups.begin(), E = Dups.end(); 683 I != E; ++I) { 684 char *Dup = *I; 685 free(Dup); 686 } 687 } 688 const char *SaveString(const char *Str) LLVM_OVERRIDE { 689 char *Dup = strdup(Str); 690 Dups.push_back(Dup); 691 return Dup; 692 } 693 }; 694 } 695 696 /// ParseEnvironmentOptions - An alternative entry point to the 697 /// CommandLine library, which allows you to read the program's name 698 /// from the caller (as PROGNAME) and its command-line arguments from 699 /// an environment variable (whose name is given in ENVVAR). 700 /// 701 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar, 702 const char *Overview) { 703 // Check args. 704 assert(progName && "Program name not specified"); 705 assert(envVar && "Environment variable name missing"); 706 707 // Get the environment variable they want us to parse options out of. 708 const char *envValue = getenv(envVar); 709 if (!envValue) 710 return; 711 712 // Get program's "name", which we wouldn't know without the caller 713 // telling us. 714 SmallVector<const char *, 20> newArgv; 715 StrDupSaver Saver; 716 newArgv.push_back(Saver.SaveString(progName)); 717 718 // Parse the value of the environment variable into a "command line" 719 // and hand it off to ParseCommandLineOptions(). 720 TokenizeGNUCommandLine(envValue, Saver, newArgv); 721 int newArgc = static_cast<int>(newArgv.size()); 722 ParseCommandLineOptions(newArgc, &newArgv[0], Overview); 723 } 724 725 void cl::ParseCommandLineOptions(int argc, const char * const *argv, 726 const char *Overview) { 727 // Process all registered options. 728 SmallVector<Option*, 4> PositionalOpts; 729 SmallVector<Option*, 4> SinkOpts; 730 StringMap<Option*> Opts; 731 GetOptionInfo(PositionalOpts, SinkOpts, Opts); 732 733 assert((!Opts.empty() || !PositionalOpts.empty()) && 734 "No options specified!"); 735 736 // Expand response files. 737 SmallVector<const char *, 20> newArgv; 738 for (int i = 0; i != argc; ++i) 739 newArgv.push_back(argv[i]); 740 StrDupSaver Saver; 741 ExpandResponseFiles(Saver, TokenizeGNUCommandLine, newArgv); 742 argv = &newArgv[0]; 743 argc = static_cast<int>(newArgv.size()); 744 745 // Copy the program name into ProgName, making sure not to overflow it. 746 std::string ProgName = sys::path::filename(argv[0]); 747 size_t Len = std::min(ProgName.size(), size_t(79)); 748 memcpy(ProgramName, ProgName.data(), Len); 749 ProgramName[Len] = '\0'; 750 751 ProgramOverview = Overview; 752 bool ErrorParsing = false; 753 754 // Check out the positional arguments to collect information about them. 755 unsigned NumPositionalRequired = 0; 756 757 // Determine whether or not there are an unlimited number of positionals 758 bool HasUnlimitedPositionals = false; 759 760 Option *ConsumeAfterOpt = 0; 761 if (!PositionalOpts.empty()) { 762 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) { 763 assert(PositionalOpts.size() > 1 && 764 "Cannot specify cl::ConsumeAfter without a positional argument!"); 765 ConsumeAfterOpt = PositionalOpts[0]; 766 } 767 768 // Calculate how many positional values are _required_. 769 bool UnboundedFound = false; 770 for (size_t i = ConsumeAfterOpt != 0, e = PositionalOpts.size(); 771 i != e; ++i) { 772 Option *Opt = PositionalOpts[i]; 773 if (RequiresValue(Opt)) 774 ++NumPositionalRequired; 775 else if (ConsumeAfterOpt) { 776 // ConsumeAfter cannot be combined with "optional" positional options 777 // unless there is only one positional argument... 778 if (PositionalOpts.size() > 2) 779 ErrorParsing |= 780 Opt->error("error - this positional option will never be matched, " 781 "because it does not Require a value, and a " 782 "cl::ConsumeAfter option is active!"); 783 } else if (UnboundedFound && !Opt->ArgStr[0]) { 784 // This option does not "require" a value... Make sure this option is 785 // not specified after an option that eats all extra arguments, or this 786 // one will never get any! 787 // 788 ErrorParsing |= Opt->error("error - option can never match, because " 789 "another positional argument will match an " 790 "unbounded number of values, and this option" 791 " does not require a value!"); 792 } 793 UnboundedFound |= EatsUnboundedNumberOfValues(Opt); 794 } 795 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt; 796 } 797 798 // PositionalVals - A vector of "positional" arguments we accumulate into 799 // the process at the end. 800 // 801 SmallVector<std::pair<StringRef,unsigned>, 4> PositionalVals; 802 803 // If the program has named positional arguments, and the name has been run 804 // across, keep track of which positional argument was named. Otherwise put 805 // the positional args into the PositionalVals list... 806 Option *ActivePositionalArg = 0; 807 808 // Loop over all of the arguments... processing them. 809 bool DashDashFound = false; // Have we read '--'? 810 for (int i = 1; i < argc; ++i) { 811 Option *Handler = 0; 812 Option *NearestHandler = 0; 813 std::string NearestHandlerString; 814 StringRef Value; 815 StringRef ArgName = ""; 816 817 // If the option list changed, this means that some command line 818 // option has just been registered or deregistered. This can occur in 819 // response to things like -load, etc. If this happens, rescan the options. 820 if (OptionListChanged) { 821 PositionalOpts.clear(); 822 SinkOpts.clear(); 823 Opts.clear(); 824 GetOptionInfo(PositionalOpts, SinkOpts, Opts); 825 OptionListChanged = false; 826 } 827 828 // Check to see if this is a positional argument. This argument is 829 // considered to be positional if it doesn't start with '-', if it is "-" 830 // itself, or if we have seen "--" already. 831 // 832 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) { 833 // Positional argument! 834 if (ActivePositionalArg) { 835 ProvidePositionalOption(ActivePositionalArg, argv[i], i); 836 continue; // We are done! 837 } 838 839 if (!PositionalOpts.empty()) { 840 PositionalVals.push_back(std::make_pair(argv[i],i)); 841 842 // All of the positional arguments have been fulfulled, give the rest to 843 // the consume after option... if it's specified... 844 // 845 if (PositionalVals.size() >= NumPositionalRequired && 846 ConsumeAfterOpt != 0) { 847 for (++i; i < argc; ++i) 848 PositionalVals.push_back(std::make_pair(argv[i],i)); 849 break; // Handle outside of the argument processing loop... 850 } 851 852 // Delay processing positional arguments until the end... 853 continue; 854 } 855 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 && 856 !DashDashFound) { 857 DashDashFound = true; // This is the mythical "--"? 858 continue; // Don't try to process it as an argument itself. 859 } else if (ActivePositionalArg && 860 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) { 861 // If there is a positional argument eating options, check to see if this 862 // option is another positional argument. If so, treat it as an argument, 863 // otherwise feed it to the eating positional. 864 ArgName = argv[i]+1; 865 // Eat leading dashes. 866 while (!ArgName.empty() && ArgName[0] == '-') 867 ArgName = ArgName.substr(1); 868 869 Handler = LookupOption(ArgName, Value, Opts); 870 if (!Handler || Handler->getFormattingFlag() != cl::Positional) { 871 ProvidePositionalOption(ActivePositionalArg, argv[i], i); 872 continue; // We are done! 873 } 874 875 } else { // We start with a '-', must be an argument. 876 ArgName = argv[i]+1; 877 // Eat leading dashes. 878 while (!ArgName.empty() && ArgName[0] == '-') 879 ArgName = ArgName.substr(1); 880 881 Handler = LookupOption(ArgName, Value, Opts); 882 883 // Check to see if this "option" is really a prefixed or grouped argument. 884 if (Handler == 0) 885 Handler = HandlePrefixedOrGroupedOption(ArgName, Value, 886 ErrorParsing, Opts); 887 888 // Otherwise, look for the closest available option to report to the user 889 // in the upcoming error. 890 if (Handler == 0 && SinkOpts.empty()) 891 NearestHandler = LookupNearestOption(ArgName, Opts, 892 NearestHandlerString); 893 } 894 895 if (Handler == 0) { 896 if (SinkOpts.empty()) { 897 errs() << ProgramName << ": Unknown command line argument '" 898 << argv[i] << "'. Try: '" << argv[0] << " -help'\n"; 899 900 if (NearestHandler) { 901 // If we know a near match, report it as well. 902 errs() << ProgramName << ": Did you mean '-" 903 << NearestHandlerString << "'?\n"; 904 } 905 906 ErrorParsing = true; 907 } else { 908 for (SmallVectorImpl<Option*>::iterator I = SinkOpts.begin(), 909 E = SinkOpts.end(); I != E ; ++I) 910 (*I)->addOccurrence(i, "", argv[i]); 911 } 912 continue; 913 } 914 915 // If this is a named positional argument, just remember that it is the 916 // active one... 917 if (Handler->getFormattingFlag() == cl::Positional) 918 ActivePositionalArg = Handler; 919 else 920 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i); 921 } 922 923 // Check and handle positional arguments now... 924 if (NumPositionalRequired > PositionalVals.size()) { 925 errs() << ProgramName 926 << ": Not enough positional command line arguments specified!\n" 927 << "Must specify at least " << NumPositionalRequired 928 << " positional arguments: See: " << argv[0] << " -help\n"; 929 930 ErrorParsing = true; 931 } else if (!HasUnlimitedPositionals && 932 PositionalVals.size() > PositionalOpts.size()) { 933 errs() << ProgramName 934 << ": Too many positional arguments specified!\n" 935 << "Can specify at most " << PositionalOpts.size() 936 << " positional arguments: See: " << argv[0] << " -help\n"; 937 ErrorParsing = true; 938 939 } else if (ConsumeAfterOpt == 0) { 940 // Positional args have already been handled if ConsumeAfter is specified. 941 unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size()); 942 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) { 943 if (RequiresValue(PositionalOpts[i])) { 944 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first, 945 PositionalVals[ValNo].second); 946 ValNo++; 947 --NumPositionalRequired; // We fulfilled our duty... 948 } 949 950 // If we _can_ give this option more arguments, do so now, as long as we 951 // do not give it values that others need. 'Done' controls whether the 952 // option even _WANTS_ any more. 953 // 954 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required; 955 while (NumVals-ValNo > NumPositionalRequired && !Done) { 956 switch (PositionalOpts[i]->getNumOccurrencesFlag()) { 957 case cl::Optional: 958 Done = true; // Optional arguments want _at most_ one value 959 // FALL THROUGH 960 case cl::ZeroOrMore: // Zero or more will take all they can get... 961 case cl::OneOrMore: // One or more will take all they can get... 962 ProvidePositionalOption(PositionalOpts[i], 963 PositionalVals[ValNo].first, 964 PositionalVals[ValNo].second); 965 ValNo++; 966 break; 967 default: 968 llvm_unreachable("Internal error, unexpected NumOccurrences flag in " 969 "positional argument processing!"); 970 } 971 } 972 } 973 } else { 974 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size()); 975 unsigned ValNo = 0; 976 for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j) 977 if (RequiresValue(PositionalOpts[j])) { 978 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j], 979 PositionalVals[ValNo].first, 980 PositionalVals[ValNo].second); 981 ValNo++; 982 } 983 984 // Handle the case where there is just one positional option, and it's 985 // optional. In this case, we want to give JUST THE FIRST option to the 986 // positional option and keep the rest for the consume after. The above 987 // loop would have assigned no values to positional options in this case. 988 // 989 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) { 990 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1], 991 PositionalVals[ValNo].first, 992 PositionalVals[ValNo].second); 993 ValNo++; 994 } 995 996 // Handle over all of the rest of the arguments to the 997 // cl::ConsumeAfter command line option... 998 for (; ValNo != PositionalVals.size(); ++ValNo) 999 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt, 1000 PositionalVals[ValNo].first, 1001 PositionalVals[ValNo].second); 1002 } 1003 1004 // Loop over args and make sure all required args are specified! 1005 for (StringMap<Option*>::iterator I = Opts.begin(), 1006 E = Opts.end(); I != E; ++I) { 1007 switch (I->second->getNumOccurrencesFlag()) { 1008 case Required: 1009 case OneOrMore: 1010 if (I->second->getNumOccurrences() == 0) { 1011 I->second->error("must be specified at least once!"); 1012 ErrorParsing = true; 1013 } 1014 // Fall through 1015 default: 1016 break; 1017 } 1018 } 1019 1020 // Now that we know if -debug is specified, we can use it. 1021 // Note that if ReadResponseFiles == true, this must be done before the 1022 // memory allocated for the expanded command line is free()d below. 1023 DEBUG(dbgs() << "Args: "; 1024 for (int i = 0; i < argc; ++i) 1025 dbgs() << argv[i] << ' '; 1026 dbgs() << '\n'; 1027 ); 1028 1029 // Free all of the memory allocated to the map. Command line options may only 1030 // be processed once! 1031 Opts.clear(); 1032 PositionalOpts.clear(); 1033 MoreHelp->clear(); 1034 1035 // If we had an error processing our arguments, don't let the program execute 1036 if (ErrorParsing) exit(1); 1037 } 1038 1039 //===----------------------------------------------------------------------===// 1040 // Option Base class implementation 1041 // 1042 1043 bool Option::error(const Twine &Message, StringRef ArgName) { 1044 if (ArgName.data() == 0) ArgName = ArgStr; 1045 if (ArgName.empty()) 1046 errs() << HelpStr; // Be nice for positional arguments 1047 else 1048 errs() << ProgramName << ": for the -" << ArgName; 1049 1050 errs() << " option: " << Message << "\n"; 1051 return true; 1052 } 1053 1054 bool Option::addOccurrence(unsigned pos, StringRef ArgName, 1055 StringRef Value, bool MultiArg) { 1056 if (!MultiArg) 1057 NumOccurrences++; // Increment the number of times we have been seen 1058 1059 switch (getNumOccurrencesFlag()) { 1060 case Optional: 1061 if (NumOccurrences > 1) 1062 return error("may only occur zero or one times!", ArgName); 1063 break; 1064 case Required: 1065 if (NumOccurrences > 1) 1066 return error("must occur exactly one time!", ArgName); 1067 // Fall through 1068 case OneOrMore: 1069 case ZeroOrMore: 1070 case ConsumeAfter: break; 1071 } 1072 1073 return handleOccurrence(pos, ArgName, Value); 1074 } 1075 1076 1077 // getValueStr - Get the value description string, using "DefaultMsg" if nothing 1078 // has been specified yet. 1079 // 1080 static const char *getValueStr(const Option &O, const char *DefaultMsg) { 1081 if (O.ValueStr[0] == 0) return DefaultMsg; 1082 return O.ValueStr; 1083 } 1084 1085 //===----------------------------------------------------------------------===// 1086 // cl::alias class implementation 1087 // 1088 1089 // Return the width of the option tag for printing... 1090 size_t alias::getOptionWidth() const { 1091 return std::strlen(ArgStr)+6; 1092 } 1093 1094 static void printHelpStr(StringRef HelpStr, size_t Indent, 1095 size_t FirstLineIndentedBy) { 1096 std::pair<StringRef, StringRef> Split = HelpStr.split('\n'); 1097 outs().indent(Indent - FirstLineIndentedBy) << " - " << Split.first << "\n"; 1098 while (!Split.second.empty()) { 1099 Split = Split.second.split('\n'); 1100 outs().indent(Indent) << Split.first << "\n"; 1101 } 1102 } 1103 1104 // Print out the option for the alias. 1105 void alias::printOptionInfo(size_t GlobalWidth) const { 1106 outs() << " -" << ArgStr; 1107 printHelpStr(HelpStr, GlobalWidth, std::strlen(ArgStr) + 6); 1108 } 1109 1110 //===----------------------------------------------------------------------===// 1111 // Parser Implementation code... 1112 // 1113 1114 // basic_parser implementation 1115 // 1116 1117 // Return the width of the option tag for printing... 1118 size_t basic_parser_impl::getOptionWidth(const Option &O) const { 1119 size_t Len = std::strlen(O.ArgStr); 1120 if (const char *ValName = getValueName()) 1121 Len += std::strlen(getValueStr(O, ValName))+3; 1122 1123 return Len + 6; 1124 } 1125 1126 // printOptionInfo - Print out information about this option. The 1127 // to-be-maintained width is specified. 1128 // 1129 void basic_parser_impl::printOptionInfo(const Option &O, 1130 size_t GlobalWidth) const { 1131 outs() << " -" << O.ArgStr; 1132 1133 if (const char *ValName = getValueName()) 1134 outs() << "=<" << getValueStr(O, ValName) << '>'; 1135 1136 printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O)); 1137 } 1138 1139 void basic_parser_impl::printOptionName(const Option &O, 1140 size_t GlobalWidth) const { 1141 outs() << " -" << O.ArgStr; 1142 outs().indent(GlobalWidth-std::strlen(O.ArgStr)); 1143 } 1144 1145 1146 // parser<bool> implementation 1147 // 1148 bool parser<bool>::parse(Option &O, StringRef ArgName, 1149 StringRef Arg, bool &Value) { 1150 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" || 1151 Arg == "1") { 1152 Value = true; 1153 return false; 1154 } 1155 1156 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") { 1157 Value = false; 1158 return false; 1159 } 1160 return O.error("'" + Arg + 1161 "' is invalid value for boolean argument! Try 0 or 1"); 1162 } 1163 1164 // parser<boolOrDefault> implementation 1165 // 1166 bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName, 1167 StringRef Arg, boolOrDefault &Value) { 1168 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" || 1169 Arg == "1") { 1170 Value = BOU_TRUE; 1171 return false; 1172 } 1173 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") { 1174 Value = BOU_FALSE; 1175 return false; 1176 } 1177 1178 return O.error("'" + Arg + 1179 "' is invalid value for boolean argument! Try 0 or 1"); 1180 } 1181 1182 // parser<int> implementation 1183 // 1184 bool parser<int>::parse(Option &O, StringRef ArgName, 1185 StringRef Arg, int &Value) { 1186 if (Arg.getAsInteger(0, Value)) 1187 return O.error("'" + Arg + "' value invalid for integer argument!"); 1188 return false; 1189 } 1190 1191 // parser<unsigned> implementation 1192 // 1193 bool parser<unsigned>::parse(Option &O, StringRef ArgName, 1194 StringRef Arg, unsigned &Value) { 1195 1196 if (Arg.getAsInteger(0, Value)) 1197 return O.error("'" + Arg + "' value invalid for uint argument!"); 1198 return false; 1199 } 1200 1201 // parser<unsigned long long> implementation 1202 // 1203 bool parser<unsigned long long>::parse(Option &O, StringRef ArgName, 1204 StringRef Arg, unsigned long long &Value){ 1205 1206 if (Arg.getAsInteger(0, Value)) 1207 return O.error("'" + Arg + "' value invalid for uint argument!"); 1208 return false; 1209 } 1210 1211 // parser<double>/parser<float> implementation 1212 // 1213 static bool parseDouble(Option &O, StringRef Arg, double &Value) { 1214 SmallString<32> TmpStr(Arg.begin(), Arg.end()); 1215 const char *ArgStart = TmpStr.c_str(); 1216 char *End; 1217 Value = strtod(ArgStart, &End); 1218 if (*End != 0) 1219 return O.error("'" + Arg + "' value invalid for floating point argument!"); 1220 return false; 1221 } 1222 1223 bool parser<double>::parse(Option &O, StringRef ArgName, 1224 StringRef Arg, double &Val) { 1225 return parseDouble(O, Arg, Val); 1226 } 1227 1228 bool parser<float>::parse(Option &O, StringRef ArgName, 1229 StringRef Arg, float &Val) { 1230 double dVal; 1231 if (parseDouble(O, Arg, dVal)) 1232 return true; 1233 Val = (float)dVal; 1234 return false; 1235 } 1236 1237 1238 1239 // generic_parser_base implementation 1240 // 1241 1242 // findOption - Return the option number corresponding to the specified 1243 // argument string. If the option is not found, getNumOptions() is returned. 1244 // 1245 unsigned generic_parser_base::findOption(const char *Name) { 1246 unsigned e = getNumOptions(); 1247 1248 for (unsigned i = 0; i != e; ++i) { 1249 if (strcmp(getOption(i), Name) == 0) 1250 return i; 1251 } 1252 return e; 1253 } 1254 1255 1256 // Return the width of the option tag for printing... 1257 size_t generic_parser_base::getOptionWidth(const Option &O) const { 1258 if (O.hasArgStr()) { 1259 size_t Size = std::strlen(O.ArgStr)+6; 1260 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) 1261 Size = std::max(Size, std::strlen(getOption(i))+8); 1262 return Size; 1263 } else { 1264 size_t BaseSize = 0; 1265 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) 1266 BaseSize = std::max(BaseSize, std::strlen(getOption(i))+8); 1267 return BaseSize; 1268 } 1269 } 1270 1271 // printOptionInfo - Print out information about this option. The 1272 // to-be-maintained width is specified. 1273 // 1274 void generic_parser_base::printOptionInfo(const Option &O, 1275 size_t GlobalWidth) const { 1276 if (O.hasArgStr()) { 1277 outs() << " -" << O.ArgStr; 1278 printHelpStr(O.HelpStr, GlobalWidth, std::strlen(O.ArgStr) + 6); 1279 1280 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) { 1281 size_t NumSpaces = GlobalWidth-strlen(getOption(i))-8; 1282 outs() << " =" << getOption(i); 1283 outs().indent(NumSpaces) << " - " << getDescription(i) << '\n'; 1284 } 1285 } else { 1286 if (O.HelpStr[0]) 1287 outs() << " " << O.HelpStr << '\n'; 1288 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) { 1289 const char *Option = getOption(i); 1290 outs() << " -" << Option; 1291 printHelpStr(getDescription(i), GlobalWidth, std::strlen(Option) + 8); 1292 } 1293 } 1294 } 1295 1296 static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff 1297 1298 // printGenericOptionDiff - Print the value of this option and it's default. 1299 // 1300 // "Generic" options have each value mapped to a name. 1301 void generic_parser_base:: 1302 printGenericOptionDiff(const Option &O, const GenericOptionValue &Value, 1303 const GenericOptionValue &Default, 1304 size_t GlobalWidth) const { 1305 outs() << " -" << O.ArgStr; 1306 outs().indent(GlobalWidth-std::strlen(O.ArgStr)); 1307 1308 unsigned NumOpts = getNumOptions(); 1309 for (unsigned i = 0; i != NumOpts; ++i) { 1310 if (Value.compare(getOptionValue(i))) 1311 continue; 1312 1313 outs() << "= " << getOption(i); 1314 size_t L = std::strlen(getOption(i)); 1315 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0; 1316 outs().indent(NumSpaces) << " (default: "; 1317 for (unsigned j = 0; j != NumOpts; ++j) { 1318 if (Default.compare(getOptionValue(j))) 1319 continue; 1320 outs() << getOption(j); 1321 break; 1322 } 1323 outs() << ")\n"; 1324 return; 1325 } 1326 outs() << "= *unknown option value*\n"; 1327 } 1328 1329 // printOptionDiff - Specializations for printing basic value types. 1330 // 1331 #define PRINT_OPT_DIFF(T) \ 1332 void parser<T>:: \ 1333 printOptionDiff(const Option &O, T V, OptionValue<T> D, \ 1334 size_t GlobalWidth) const { \ 1335 printOptionName(O, GlobalWidth); \ 1336 std::string Str; \ 1337 { \ 1338 raw_string_ostream SS(Str); \ 1339 SS << V; \ 1340 } \ 1341 outs() << "= " << Str; \ 1342 size_t NumSpaces = MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0;\ 1343 outs().indent(NumSpaces) << " (default: "; \ 1344 if (D.hasValue()) \ 1345 outs() << D.getValue(); \ 1346 else \ 1347 outs() << "*no default*"; \ 1348 outs() << ")\n"; \ 1349 } \ 1350 1351 PRINT_OPT_DIFF(bool) 1352 PRINT_OPT_DIFF(boolOrDefault) 1353 PRINT_OPT_DIFF(int) 1354 PRINT_OPT_DIFF(unsigned) 1355 PRINT_OPT_DIFF(unsigned long long) 1356 PRINT_OPT_DIFF(double) 1357 PRINT_OPT_DIFF(float) 1358 PRINT_OPT_DIFF(char) 1359 1360 void parser<std::string>:: 1361 printOptionDiff(const Option &O, StringRef V, OptionValue<std::string> D, 1362 size_t GlobalWidth) const { 1363 printOptionName(O, GlobalWidth); 1364 outs() << "= " << V; 1365 size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0; 1366 outs().indent(NumSpaces) << " (default: "; 1367 if (D.hasValue()) 1368 outs() << D.getValue(); 1369 else 1370 outs() << "*no default*"; 1371 outs() << ")\n"; 1372 } 1373 1374 // Print a placeholder for options that don't yet support printOptionDiff(). 1375 void basic_parser_impl:: 1376 printOptionNoValue(const Option &O, size_t GlobalWidth) const { 1377 printOptionName(O, GlobalWidth); 1378 outs() << "= *cannot print option value*\n"; 1379 } 1380 1381 //===----------------------------------------------------------------------===// 1382 // -help and -help-hidden option implementation 1383 // 1384 1385 static int OptNameCompare(const void *LHS, const void *RHS) { 1386 typedef std::pair<const char *, Option*> pair_ty; 1387 1388 return strcmp(((const pair_ty*)LHS)->first, ((const pair_ty*)RHS)->first); 1389 } 1390 1391 // Copy Options into a vector so we can sort them as we like. 1392 static void 1393 sortOpts(StringMap<Option*> &OptMap, 1394 SmallVectorImpl< std::pair<const char *, Option*> > &Opts, 1395 bool ShowHidden) { 1396 SmallPtrSet<Option*, 128> OptionSet; // Duplicate option detection. 1397 1398 for (StringMap<Option*>::iterator I = OptMap.begin(), E = OptMap.end(); 1399 I != E; ++I) { 1400 // Ignore really-hidden options. 1401 if (I->second->getOptionHiddenFlag() == ReallyHidden) 1402 continue; 1403 1404 // Unless showhidden is set, ignore hidden flags. 1405 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden) 1406 continue; 1407 1408 // If we've already seen this option, don't add it to the list again. 1409 if (!OptionSet.insert(I->second)) 1410 continue; 1411 1412 Opts.push_back(std::pair<const char *, Option*>(I->getKey().data(), 1413 I->second)); 1414 } 1415 1416 // Sort the options list alphabetically. 1417 qsort(Opts.data(), Opts.size(), sizeof(Opts[0]), OptNameCompare); 1418 } 1419 1420 namespace { 1421 1422 class HelpPrinter { 1423 protected: 1424 const bool ShowHidden; 1425 typedef SmallVector<std::pair<const char *, Option*>,128> StrOptionPairVector; 1426 // Print the options. Opts is assumed to be alphabetically sorted. 1427 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) { 1428 for (size_t i = 0, e = Opts.size(); i != e; ++i) 1429 Opts[i].second->printOptionInfo(MaxArgLen); 1430 } 1431 1432 public: 1433 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {} 1434 virtual ~HelpPrinter() {} 1435 1436 // Invoke the printer. 1437 void operator=(bool Value) { 1438 if (Value == false) return; 1439 1440 // Get all the options. 1441 SmallVector<Option*, 4> PositionalOpts; 1442 SmallVector<Option*, 4> SinkOpts; 1443 StringMap<Option*> OptMap; 1444 GetOptionInfo(PositionalOpts, SinkOpts, OptMap); 1445 1446 StrOptionPairVector Opts; 1447 sortOpts(OptMap, Opts, ShowHidden); 1448 1449 if (ProgramOverview) 1450 outs() << "OVERVIEW: " << ProgramOverview << "\n"; 1451 1452 outs() << "USAGE: " << ProgramName << " [options]"; 1453 1454 // Print out the positional options. 1455 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists... 1456 if (!PositionalOpts.empty() && 1457 PositionalOpts[0]->getNumOccurrencesFlag() == ConsumeAfter) 1458 CAOpt = PositionalOpts[0]; 1459 1460 for (size_t i = CAOpt != 0, e = PositionalOpts.size(); i != e; ++i) { 1461 if (PositionalOpts[i]->ArgStr[0]) 1462 outs() << " --" << PositionalOpts[i]->ArgStr; 1463 outs() << " " << PositionalOpts[i]->HelpStr; 1464 } 1465 1466 // Print the consume after option info if it exists... 1467 if (CAOpt) outs() << " " << CAOpt->HelpStr; 1468 1469 outs() << "\n\n"; 1470 1471 // Compute the maximum argument length... 1472 size_t MaxArgLen = 0; 1473 for (size_t i = 0, e = Opts.size(); i != e; ++i) 1474 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth()); 1475 1476 outs() << "OPTIONS:\n"; 1477 printOptions(Opts, MaxArgLen); 1478 1479 // Print any extra help the user has declared. 1480 for (std::vector<const char *>::iterator I = MoreHelp->begin(), 1481 E = MoreHelp->end(); 1482 I != E; ++I) 1483 outs() << *I; 1484 MoreHelp->clear(); 1485 1486 // Halt the program since help information was printed 1487 exit(1); 1488 } 1489 }; 1490 1491 class CategorizedHelpPrinter : public HelpPrinter { 1492 public: 1493 explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {} 1494 1495 // Helper function for printOptions(). 1496 // It shall return true if A's name should be lexographically 1497 // ordered before B's name. It returns false otherwise. 1498 static bool OptionCategoryCompare(OptionCategory *A, OptionCategory *B) { 1499 return strcmp(A->getName(), B->getName()) < 0; 1500 } 1501 1502 // Make sure we inherit our base class's operator=() 1503 using HelpPrinter::operator= ; 1504 1505 protected: 1506 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) { 1507 std::vector<OptionCategory *> SortedCategories; 1508 std::map<OptionCategory *, std::vector<Option *> > CategorizedOptions; 1509 std::set<std::string> CategoryNames; 1510 1511 // Collect registered option categories into vector in preparation for 1512 // sorting. 1513 for (OptionCatSet::const_iterator I = RegisteredOptionCategories->begin(), 1514 E = RegisteredOptionCategories->end(); 1515 I != E; ++I) { 1516 SortedCategories.push_back(*I); 1517 // FIXME: Move this check to OptionCategory::registerCategory after the 1518 // problem with analyzer plugins linking to llvm/Support and causing 1519 // assertion on the duplicate llvm::cl::GeneralCategory is solved. 1520 assert(CategoryNames.insert((*I)->getName()).second && 1521 "Duplicate option categories"); 1522 } 1523 1524 // Sort the different option categories alphabetically. 1525 assert(SortedCategories.size() > 0 && "No option categories registered!"); 1526 std::sort(SortedCategories.begin(), SortedCategories.end(), 1527 OptionCategoryCompare); 1528 1529 // Create map to empty vectors. 1530 for (std::vector<OptionCategory *>::const_iterator 1531 I = SortedCategories.begin(), 1532 E = SortedCategories.end(); 1533 I != E; ++I) 1534 CategorizedOptions[*I] = std::vector<Option *>(); 1535 1536 // Walk through pre-sorted options and assign into categories. 1537 // Because the options are already alphabetically sorted the 1538 // options within categories will also be alphabetically sorted. 1539 for (size_t I = 0, E = Opts.size(); I != E; ++I) { 1540 Option *Opt = Opts[I].second; 1541 assert(CategorizedOptions.count(Opt->Category) > 0 && 1542 "Option has an unregistered category"); 1543 CategorizedOptions[Opt->Category].push_back(Opt); 1544 } 1545 1546 // Now do printing. 1547 for (std::vector<OptionCategory *>::const_iterator 1548 Category = SortedCategories.begin(), 1549 E = SortedCategories.end(); 1550 Category != E; ++Category) { 1551 // Hide empty categories for -help, but show for -help-hidden. 1552 bool IsEmptyCategory = CategorizedOptions[*Category].size() == 0; 1553 if (!ShowHidden && IsEmptyCategory) 1554 continue; 1555 1556 // Print category information. 1557 outs() << "\n"; 1558 outs() << (*Category)->getName() << ":\n"; 1559 1560 // Check if description is set. 1561 if ((*Category)->getDescription() != 0) 1562 outs() << (*Category)->getDescription() << "\n\n"; 1563 else 1564 outs() << "\n"; 1565 1566 // When using -help-hidden explicitly state if the category has no 1567 // options associated with it. 1568 if (IsEmptyCategory) { 1569 outs() << " This option category has no options.\n"; 1570 continue; 1571 } 1572 // Loop over the options in the category and print. 1573 for (std::vector<Option *>::const_iterator 1574 Opt = CategorizedOptions[*Category].begin(), 1575 E = CategorizedOptions[*Category].end(); 1576 Opt != E; ++Opt) 1577 (*Opt)->printOptionInfo(MaxArgLen); 1578 } 1579 } 1580 }; 1581 1582 // This wraps the Uncategorizing and Categorizing printers and decides 1583 // at run time which should be invoked. 1584 class HelpPrinterWrapper { 1585 private: 1586 HelpPrinter &UncategorizedPrinter; 1587 CategorizedHelpPrinter &CategorizedPrinter; 1588 1589 public: 1590 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter, 1591 CategorizedHelpPrinter &CategorizedPrinter) : 1592 UncategorizedPrinter(UncategorizedPrinter), 1593 CategorizedPrinter(CategorizedPrinter) { } 1594 1595 // Invoke the printer. 1596 void operator=(bool Value); 1597 }; 1598 1599 } // End anonymous namespace 1600 1601 // Declare the four HelpPrinter instances that are used to print out help, or 1602 // help-hidden as an uncategorized list or in categories. 1603 static HelpPrinter UncategorizedNormalPrinter(false); 1604 static HelpPrinter UncategorizedHiddenPrinter(true); 1605 static CategorizedHelpPrinter CategorizedNormalPrinter(false); 1606 static CategorizedHelpPrinter CategorizedHiddenPrinter(true); 1607 1608 1609 // Declare HelpPrinter wrappers that will decide whether or not to invoke 1610 // a categorizing help printer 1611 static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter, 1612 CategorizedNormalPrinter); 1613 static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter, 1614 CategorizedHiddenPrinter); 1615 1616 // Define uncategorized help printers. 1617 // -help-list is hidden by default because if Option categories are being used 1618 // then -help behaves the same as -help-list. 1619 static cl::opt<HelpPrinter, true, parser<bool> > 1620 HLOp("help-list", 1621 cl::desc("Display list of available options (-help-list-hidden for more)"), 1622 cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed); 1623 1624 static cl::opt<HelpPrinter, true, parser<bool> > 1625 HLHOp("help-list-hidden", 1626 cl::desc("Display list of all available options"), 1627 cl::location(UncategorizedHiddenPrinter), cl::Hidden, cl::ValueDisallowed); 1628 1629 // Define uncategorized/categorized help printers. These printers change their 1630 // behaviour at runtime depending on whether one or more Option categories have 1631 // been declared. 1632 static cl::opt<HelpPrinterWrapper, true, parser<bool> > 1633 HOp("help", cl::desc("Display available options (-help-hidden for more)"), 1634 cl::location(WrappedNormalPrinter), cl::ValueDisallowed); 1635 1636 static cl::opt<HelpPrinterWrapper, true, parser<bool> > 1637 HHOp("help-hidden", cl::desc("Display all available options"), 1638 cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed); 1639 1640 1641 1642 static cl::opt<bool> 1643 PrintOptions("print-options", 1644 cl::desc("Print non-default options after command line parsing"), 1645 cl::Hidden, cl::init(false)); 1646 1647 static cl::opt<bool> 1648 PrintAllOptions("print-all-options", 1649 cl::desc("Print all option values after command line parsing"), 1650 cl::Hidden, cl::init(false)); 1651 1652 void HelpPrinterWrapper::operator=(bool Value) { 1653 if (Value == false) 1654 return; 1655 1656 // Decide which printer to invoke. If more than one option category is 1657 // registered then it is useful to show the categorized help instead of 1658 // uncategorized help. 1659 if (RegisteredOptionCategories->size() > 1) { 1660 // unhide -help-list option so user can have uncategorized output if they 1661 // want it. 1662 HLOp.setHiddenFlag(NotHidden); 1663 1664 CategorizedPrinter = true; // Invoke categorized printer 1665 } 1666 else 1667 UncategorizedPrinter = true; // Invoke uncategorized printer 1668 } 1669 1670 // Print the value of each option. 1671 void cl::PrintOptionValues() { 1672 if (!PrintOptions && !PrintAllOptions) return; 1673 1674 // Get all the options. 1675 SmallVector<Option*, 4> PositionalOpts; 1676 SmallVector<Option*, 4> SinkOpts; 1677 StringMap<Option*> OptMap; 1678 GetOptionInfo(PositionalOpts, SinkOpts, OptMap); 1679 1680 SmallVector<std::pair<const char *, Option*>, 128> Opts; 1681 sortOpts(OptMap, Opts, /*ShowHidden*/true); 1682 1683 // Compute the maximum argument length... 1684 size_t MaxArgLen = 0; 1685 for (size_t i = 0, e = Opts.size(); i != e; ++i) 1686 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth()); 1687 1688 for (size_t i = 0, e = Opts.size(); i != e; ++i) 1689 Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions); 1690 } 1691 1692 static void (*OverrideVersionPrinter)() = 0; 1693 1694 static std::vector<void (*)()>* ExtraVersionPrinters = 0; 1695 1696 namespace { 1697 class VersionPrinter { 1698 public: 1699 void print() { 1700 raw_ostream &OS = outs(); 1701 OS << "LLVM (http://llvm.org/):\n" 1702 << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION; 1703 #ifdef LLVM_VERSION_INFO 1704 OS << LLVM_VERSION_INFO; 1705 #endif 1706 OS << "\n "; 1707 #ifndef __OPTIMIZE__ 1708 OS << "DEBUG build"; 1709 #else 1710 OS << "Optimized build"; 1711 #endif 1712 #ifndef NDEBUG 1713 OS << " with assertions"; 1714 #endif 1715 std::string CPU = sys::getHostCPUName(); 1716 if (CPU == "generic") CPU = "(unknown)"; 1717 OS << ".\n" 1718 #if (ENABLE_TIMESTAMPS == 1) 1719 << " Built " << __DATE__ << " (" << __TIME__ << ").\n" 1720 #endif 1721 << " Default target: " << sys::getDefaultTargetTriple() << '\n' 1722 << " Host CPU: " << CPU << '\n'; 1723 } 1724 void operator=(bool OptionWasSpecified) { 1725 if (!OptionWasSpecified) return; 1726 1727 if (OverrideVersionPrinter != 0) { 1728 (*OverrideVersionPrinter)(); 1729 exit(1); 1730 } 1731 print(); 1732 1733 // Iterate over any registered extra printers and call them to add further 1734 // information. 1735 if (ExtraVersionPrinters != 0) { 1736 outs() << '\n'; 1737 for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(), 1738 E = ExtraVersionPrinters->end(); 1739 I != E; ++I) 1740 (*I)(); 1741 } 1742 1743 exit(1); 1744 } 1745 }; 1746 } // End anonymous namespace 1747 1748 1749 // Define the --version option that prints out the LLVM version for the tool 1750 static VersionPrinter VersionPrinterInstance; 1751 1752 static cl::opt<VersionPrinter, true, parser<bool> > 1753 VersOp("version", cl::desc("Display the version of this program"), 1754 cl::location(VersionPrinterInstance), cl::ValueDisallowed); 1755 1756 // Utility function for printing the help message. 1757 void cl::PrintHelpMessage(bool Hidden, bool Categorized) { 1758 // This looks weird, but it actually prints the help message. The Printers are 1759 // types of HelpPrinter and the help gets printed when its operator= is 1760 // invoked. That's because the "normal" usages of the help printer is to be 1761 // assigned true/false depending on whether -help or -help-hidden was given or 1762 // not. Since we're circumventing that we have to make it look like -help or 1763 // -help-hidden were given, so we assign true. 1764 1765 if (!Hidden && !Categorized) 1766 UncategorizedNormalPrinter = true; 1767 else if (!Hidden && Categorized) 1768 CategorizedNormalPrinter = true; 1769 else if (Hidden && !Categorized) 1770 UncategorizedHiddenPrinter = true; 1771 else 1772 CategorizedHiddenPrinter = true; 1773 } 1774 1775 /// Utility function for printing version number. 1776 void cl::PrintVersionMessage() { 1777 VersionPrinterInstance.print(); 1778 } 1779 1780 void cl::SetVersionPrinter(void (*func)()) { 1781 OverrideVersionPrinter = func; 1782 } 1783 1784 void cl::AddExtraVersionPrinter(void (*func)()) { 1785 if (ExtraVersionPrinters == 0) 1786 ExtraVersionPrinters = new std::vector<void (*)()>; 1787 1788 ExtraVersionPrinters->push_back(func); 1789 } 1790 1791 void cl::getRegisteredOptions(StringMap<Option*> &Map) 1792 { 1793 // Get all the options. 1794 SmallVector<Option*, 4> PositionalOpts; //NOT USED 1795 SmallVector<Option*, 4> SinkOpts; //NOT USED 1796 assert(Map.size() == 0 && "StringMap must be empty"); 1797 GetOptionInfo(PositionalOpts, SinkOpts, Map); 1798 return; 1799 } 1800