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