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