LLVM  16.0.0git
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 
20 #include "DebugOptions.h"
21 
22 #include "llvm-c/Support.h"
23 #include "llvm/ADT/ArrayRef.h"
24 #include "llvm/ADT/Optional.h"
26 #include "llvm/ADT/SmallPtrSet.h"
27 #include "llvm/ADT/SmallString.h"
28 #include "llvm/ADT/StringExtras.h"
29 #include "llvm/ADT/StringMap.h"
30 #include "llvm/ADT/StringRef.h"
31 #include "llvm/ADT/Triple.h"
32 #include "llvm/ADT/Twine.h"
33 #include "llvm/Config/config.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/Error.h"
39 #include "llvm/Support/Host.h"
42 #include "llvm/Support/Path.h"
43 #include "llvm/Support/Process.h"
47 #include <cstdlib>
48 #include <string>
49 using namespace llvm;
50 using namespace cl;
51 
52 #define DEBUG_TYPE "commandline"
53 
54 //===----------------------------------------------------------------------===//
55 // Template instantiations and anchors.
56 //
57 namespace llvm {
58 namespace cl {
59 template class basic_parser<bool>;
60 template class basic_parser<boolOrDefault>;
61 template class basic_parser<int>;
62 template class basic_parser<long>;
63 template class basic_parser<long long>;
64 template class basic_parser<unsigned>;
65 template class basic_parser<unsigned long>;
67 template class basic_parser<double>;
68 template class basic_parser<float>;
69 template class basic_parser<std::string>;
70 template class basic_parser<char>;
71 
72 template class opt<unsigned>;
73 template class opt<int>;
74 template class opt<std::string>;
75 template class opt<char>;
76 template class opt<bool>;
77 } // namespace cl
78 } // namespace llvm
79 
80 // Pin the vtables to this file.
81 void GenericOptionValue::anchor() {}
84 void Option::anchor() {}
86 void parser<bool>::anchor() {}
88 void parser<int>::anchor() {}
89 void parser<long>::anchor() {}
94 void parser<double>::anchor() {}
95 void parser<float>::anchor() {}
97 void parser<char>::anchor() {}
98 
99 //===----------------------------------------------------------------------===//
100 
101 const static size_t DefaultPad = 2;
102 
103 static StringRef ArgPrefix = "-";
104 static StringRef ArgPrefixLong = "--";
105 static StringRef ArgHelpPrefix = " - ";
106 
107 static size_t argPlusPrefixesSize(StringRef ArgName, size_t Pad = DefaultPad) {
108  size_t Len = ArgName.size();
109  if (Len == 1)
110  return Len + Pad + ArgPrefix.size() + ArgHelpPrefix.size();
111  return Len + Pad + ArgPrefixLong.size() + ArgHelpPrefix.size();
112 }
113 
114 static SmallString<8> argPrefix(StringRef ArgName, size_t Pad = DefaultPad) {
116  for (size_t I = 0; I < Pad; ++I) {
117  Prefix.push_back(' ');
118  }
119  Prefix.append(ArgName.size() > 1 ? ArgPrefixLong : ArgPrefix);
120  return Prefix;
121 }
122 
123 // Option predicates...
124 static inline bool isGrouping(const Option *O) {
125  return O->getMiscFlags() & cl::Grouping;
126 }
127 static inline bool isPrefixedOrGrouping(const Option *O) {
128  return isGrouping(O) || O->getFormattingFlag() == cl::Prefix ||
129  O->getFormattingFlag() == cl::AlwaysPrefix;
130 }
131 
132 
133 namespace {
134 
135 class PrintArg {
136  StringRef ArgName;
137  size_t Pad;
138 public:
139  PrintArg(StringRef ArgName, size_t Pad = DefaultPad) : ArgName(ArgName), Pad(Pad) {}
140  friend raw_ostream &operator<<(raw_ostream &OS, const PrintArg &);
141 };
142 
143 raw_ostream &operator<<(raw_ostream &OS, const PrintArg& Arg) {
144  OS << argPrefix(Arg.ArgName, Arg.Pad) << Arg.ArgName;
145  return OS;
146 }
147 
148 class CommandLineParser {
149 public:
150  // Globals for name and overview of program. Program name is not a string to
151  // avoid static ctor/dtor issues.
152  std::string ProgramName;
153  StringRef ProgramOverview;
154 
155  // This collects additional help to be printed.
156  std::vector<StringRef> MoreHelp;
157 
158  // This collects Options added with the cl::DefaultOption flag. Since they can
159  // be overridden, they are not added to the appropriate SubCommands until
160  // ParseCommandLineOptions actually runs.
161  SmallVector<Option*, 4> DefaultOptions;
162 
163  // This collects the different option categories that have been registered.
164  SmallPtrSet<OptionCategory *, 16> RegisteredOptionCategories;
165 
166  // This collects the different subcommands that have been registered.
167  SmallPtrSet<SubCommand *, 4> RegisteredSubCommands;
168 
169  CommandLineParser() {
170  registerSubCommand(&SubCommand::getTopLevel());
171  registerSubCommand(&SubCommand::getAll());
172  }
173 
175 
176  bool ParseCommandLineOptions(int argc, const char *const *argv,
177  StringRef Overview, raw_ostream *Errs = nullptr,
178  bool LongOptionsUseDoubleDash = false);
179 
180  void addLiteralOption(Option &Opt, SubCommand *SC, StringRef Name) {
181  if (Opt.hasArgStr())
182  return;
183  if (!SC->OptionsMap.insert(std::make_pair(Name, &Opt)).second) {
184  errs() << ProgramName << ": CommandLine Error: Option '" << Name
185  << "' registered more than once!\n";
186  report_fatal_error("inconsistency in registered CommandLine options");
187  }
188 
189  // If we're adding this to all sub-commands, add it to the ones that have
190  // already been registered.
191  if (SC == &SubCommand::getAll()) {
192  for (auto *Sub : RegisteredSubCommands) {
193  if (SC == Sub)
194  continue;
195  addLiteralOption(Opt, Sub, Name);
196  }
197  }
198  }
199 
200  void addLiteralOption(Option &Opt, StringRef Name) {
201  if (Opt.Subs.empty())
202  addLiteralOption(Opt, &SubCommand::getTopLevel(), Name);
203  else {
204  for (auto *SC : Opt.Subs)
205  addLiteralOption(Opt, SC, Name);
206  }
207  }
208 
209  void addOption(Option *O, SubCommand *SC) {
210  bool HadErrors = false;
211  if (O->hasArgStr()) {
212  // If it's a DefaultOption, check to make sure it isn't already there.
213  if (O->isDefaultOption() &&
214  SC->OptionsMap.find(O->ArgStr) != SC->OptionsMap.end())
215  return;
216 
217  // Add argument to the argument map!
218  if (!SC->OptionsMap.insert(std::make_pair(O->ArgStr, O)).second) {
219  errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
220  << "' registered more than once!\n";
221  HadErrors = true;
222  }
223  }
224 
225  // Remember information about positional options.
226  if (O->getFormattingFlag() == cl::Positional)
227  SC->PositionalOpts.push_back(O);
228  else if (O->getMiscFlags() & cl::Sink) // Remember sink options
229  SC->SinkOpts.push_back(O);
230  else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
231  if (SC->ConsumeAfterOpt) {
232  O->error("Cannot specify more than one option with cl::ConsumeAfter!");
233  HadErrors = true;
234  }
235  SC->ConsumeAfterOpt = O;
236  }
237 
238  // Fail hard if there were errors. These are strictly unrecoverable and
239  // indicate serious issues such as conflicting option names or an
240  // incorrectly
241  // linked LLVM distribution.
242  if (HadErrors)
243  report_fatal_error("inconsistency in registered CommandLine options");
244 
245  // If we're adding this to all sub-commands, add it to the ones that have
246  // already been registered.
247  if (SC == &SubCommand::getAll()) {
248  for (auto *Sub : RegisteredSubCommands) {
249  if (SC == Sub)
250  continue;
251  addOption(O, Sub);
252  }
253  }
254  }
255 
256  void addOption(Option *O, bool ProcessDefaultOption = false) {
257  if (!ProcessDefaultOption && O->isDefaultOption()) {
258  DefaultOptions.push_back(O);
259  return;
260  }
261 
262  if (O->Subs.empty()) {
263  addOption(O, &SubCommand::getTopLevel());
264  } else {
265  for (auto *SC : O->Subs)
266  addOption(O, SC);
267  }
268  }
269 
270  void removeOption(Option *O, SubCommand *SC) {
271  SmallVector<StringRef, 16> OptionNames;
272  O->getExtraOptionNames(OptionNames);
273  if (O->hasArgStr())
274  OptionNames.push_back(O->ArgStr);
275 
276  SubCommand &Sub = *SC;
277  auto End = Sub.OptionsMap.end();
278  for (auto Name : OptionNames) {
279  auto I = Sub.OptionsMap.find(Name);
280  if (I != End && I->getValue() == O)
281  Sub.OptionsMap.erase(I);
282  }
283 
284  if (O->getFormattingFlag() == cl::Positional)
285  for (auto *Opt = Sub.PositionalOpts.begin();
286  Opt != Sub.PositionalOpts.end(); ++Opt) {
287  if (*Opt == O) {
288  Sub.PositionalOpts.erase(Opt);
289  break;
290  }
291  }
292  else if (O->getMiscFlags() & cl::Sink)
293  for (auto *Opt = Sub.SinkOpts.begin(); Opt != Sub.SinkOpts.end(); ++Opt) {
294  if (*Opt == O) {
295  Sub.SinkOpts.erase(Opt);
296  break;
297  }
298  }
299  else if (O == Sub.ConsumeAfterOpt)
300  Sub.ConsumeAfterOpt = nullptr;
301  }
302 
303  void removeOption(Option *O) {
304  if (O->Subs.empty())
305  removeOption(O, &SubCommand::getTopLevel());
306  else {
307  if (O->isInAllSubCommands()) {
308  for (auto *SC : RegisteredSubCommands)
309  removeOption(O, SC);
310  } else {
311  for (auto *SC : O->Subs)
312  removeOption(O, SC);
313  }
314  }
315  }
316 
317  bool hasOptions(const SubCommand &Sub) const {
318  return (!Sub.OptionsMap.empty() || !Sub.PositionalOpts.empty() ||
319  nullptr != Sub.ConsumeAfterOpt);
320  }
321 
322  bool hasOptions() const {
323  for (const auto *S : RegisteredSubCommands) {
324  if (hasOptions(*S))
325  return true;
326  }
327  return false;
328  }
329 
330  SubCommand *getActiveSubCommand() { return ActiveSubCommand; }
331 
332  void updateArgStr(Option *O, StringRef NewName, SubCommand *SC) {
333  SubCommand &Sub = *SC;
334  if (!Sub.OptionsMap.insert(std::make_pair(NewName, O)).second) {
335  errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
336  << "' registered more than once!\n";
337  report_fatal_error("inconsistency in registered CommandLine options");
338  }
339  Sub.OptionsMap.erase(O->ArgStr);
340  }
341 
342  void updateArgStr(Option *O, StringRef NewName) {
343  if (O->Subs.empty())
344  updateArgStr(O, NewName, &SubCommand::getTopLevel());
345  else {
346  if (O->isInAllSubCommands()) {
347  for (auto *SC : RegisteredSubCommands)
348  updateArgStr(O, NewName, SC);
349  } else {
350  for (auto *SC : O->Subs)
351  updateArgStr(O, NewName, SC);
352  }
353  }
354  }
355 
356  void printOptionValues();
357 
358  void registerCategory(OptionCategory *cat) {
359  assert(count_if(RegisteredOptionCategories,
360  [cat](const OptionCategory *Category) {
361  return cat->getName() == Category->getName();
362  }) == 0 &&
363  "Duplicate option categories");
364 
365  RegisteredOptionCategories.insert(cat);
366  }
367 
368  void registerSubCommand(SubCommand *sub) {
369  assert(count_if(RegisteredSubCommands,
370  [sub](const SubCommand *Sub) {
371  return (!sub->getName().empty()) &&
372  (Sub->getName() == sub->getName());
373  }) == 0 &&
374  "Duplicate subcommands");
375  RegisteredSubCommands.insert(sub);
376 
377  // For all options that have been registered for all subcommands, add the
378  // option to this subcommand now.
379  if (sub != &SubCommand::getAll()) {
380  for (auto &E : SubCommand::getAll().OptionsMap) {
381  Option *O = E.second;
382  if ((O->isPositional() || O->isSink() || O->isConsumeAfter()) ||
383  O->hasArgStr())
384  addOption(O, sub);
385  else
386  addLiteralOption(*O, sub, E.first());
387  }
388  }
389  }
390 
391  void unregisterSubCommand(SubCommand *sub) {
392  RegisteredSubCommands.erase(sub);
393  }
394 
397  return make_range(RegisteredSubCommands.begin(),
398  RegisteredSubCommands.end());
399  }
400 
401  void reset() {
402  ActiveSubCommand = nullptr;
403  ProgramName.clear();
404  ProgramOverview = StringRef();
405 
406  MoreHelp.clear();
407  RegisteredOptionCategories.clear();
408 
410  RegisteredSubCommands.clear();
411 
414  registerSubCommand(&SubCommand::getTopLevel());
415  registerSubCommand(&SubCommand::getAll());
416 
417  DefaultOptions.clear();
418  }
419 
420 private:
421  SubCommand *ActiveSubCommand = nullptr;
422 
423  Option *LookupOption(SubCommand &Sub, StringRef &Arg, StringRef &Value);
424  Option *LookupLongOption(SubCommand &Sub, StringRef &Arg, StringRef &Value,
425  bool LongOptionsUseDoubleDash, bool HaveDoubleDash) {
426  Option *Opt = LookupOption(Sub, Arg, Value);
427  if (Opt && LongOptionsUseDoubleDash && !HaveDoubleDash && !isGrouping(Opt))
428  return nullptr;
429  return Opt;
430  }
431  SubCommand *LookupSubCommand(StringRef Name);
432 };
433 
434 } // namespace
435 
437 
439  GlobalParser->addLiteralOption(O, Name);
440 }
441 
443  GlobalParser->MoreHelp.push_back(Help);
444 }
445 
447  GlobalParser->addOption(this);
448  FullyInitialized = true;
449 }
450 
451 void Option::removeArgument() { GlobalParser->removeOption(this); }
452 
454  if (FullyInitialized)
455  GlobalParser->updateArgStr(this, S);
456  assert((S.empty() || S[0] != '-') && "Option can't start with '-");
457  ArgStr = S;
458  if (ArgStr.size() == 1)
460 }
461 
463  assert(!Categories.empty() && "Categories cannot be empty.");
464  // Maintain backward compatibility by replacing the default GeneralCategory
465  // if it's still set. Otherwise, just add the new one. The GeneralCategory
466  // must be explicitly added if you want multiple categories that include it.
467  if (&C != &getGeneralCategory() && Categories[0] == &getGeneralCategory())
468  Categories[0] = &C;
469  else if (!is_contained(Categories, &C))
470  Categories.push_back(&C);
471 }
472 
474  NumOccurrences = 0;
475  setDefault();
476  if (isDefaultOption())
477  removeArgument();
478 }
479 
480 void OptionCategory::registerCategory() {
481  GlobalParser->registerCategory(this);
482 }
483 
484 // A special subcommand representing no subcommand. It is particularly important
485 // that this ManagedStatic uses constant initailization and not dynamic
486 // initialization because it is referenced from cl::opt constructors, which run
487 // dynamically in an arbitrary order.
490 
491 // A special subcommand that can be used to put an option into all subcommands.
493 
495 
497 
499  GlobalParser->registerSubCommand(this);
500 }
501 
503  GlobalParser->unregisterSubCommand(this);
504 }
505 
507  PositionalOpts.clear();
508  SinkOpts.clear();
509  OptionsMap.clear();
510 
511  ConsumeAfterOpt = nullptr;
512 }
513 
514 SubCommand::operator bool() const {
515  return (GlobalParser->getActiveSubCommand() == this);
516 }
517 
518 //===----------------------------------------------------------------------===//
519 // Basic, shared command line option processing machinery.
520 //
521 
522 /// LookupOption - Lookup the option specified by the specified option on the
523 /// command line. If there is a value specified (after an equal sign) return
524 /// that as well. This assumes that leading dashes have already been stripped.
525 Option *CommandLineParser::LookupOption(SubCommand &Sub, StringRef &Arg,
526  StringRef &Value) {
527  // Reject all dashes.
528  if (Arg.empty())
529  return nullptr;
530  assert(&Sub != &SubCommand::getAll());
531 
532  size_t EqualPos = Arg.find('=');
533 
534  // If we have an equals sign, remember the value.
535  if (EqualPos == StringRef::npos) {
536  // Look up the option.
537  return Sub.OptionsMap.lookup(Arg);
538  }
539 
540  // If the argument before the = is a valid option name and the option allows
541  // non-prefix form (ie is not AlwaysPrefix), we match. If not, signal match
542  // failure by returning nullptr.
543  auto I = Sub.OptionsMap.find(Arg.substr(0, EqualPos));
544  if (I == Sub.OptionsMap.end())
545  return nullptr;
546 
547  auto *O = I->second;
548  if (O->getFormattingFlag() == cl::AlwaysPrefix)
549  return nullptr;
550 
551  Value = Arg.substr(EqualPos + 1);
552  Arg = Arg.substr(0, EqualPos);
553  return I->second;
554 }
555 
556 SubCommand *CommandLineParser::LookupSubCommand(StringRef Name) {
557  if (Name.empty())
558  return &SubCommand::getTopLevel();
559  for (auto *S : RegisteredSubCommands) {
560  if (S == &SubCommand::getAll())
561  continue;
562  if (S->getName().empty())
563  continue;
564 
565  if (StringRef(S->getName()) == StringRef(Name))
566  return S;
567  }
568  return &SubCommand::getTopLevel();
569 }
570 
571 /// LookupNearestOption - Lookup the closest match to the option specified by
572 /// the specified option on the command line. If there is a value specified
573 /// (after an equal sign) return that as well. This assumes that leading dashes
574 /// have already been stripped.
576  const StringMap<Option *> &OptionsMap,
577  std::string &NearestString) {
578  // Reject all dashes.
579  if (Arg.empty())
580  return nullptr;
581 
582  // Split on any equal sign.
583  std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
584  StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
585  StringRef &RHS = SplitArg.second;
586 
587  // Find the closest match.
588  Option *Best = nullptr;
589  unsigned BestDistance = 0;
590  for (StringMap<Option *>::const_iterator it = OptionsMap.begin(),
591  ie = OptionsMap.end();
592  it != ie; ++it) {
593  Option *O = it->second;
594  // Do not suggest really hidden options (not shown in any help).
595  if (O->getOptionHiddenFlag() == ReallyHidden)
596  continue;
597 
598  SmallVector<StringRef, 16> OptionNames;
599  O->getExtraOptionNames(OptionNames);
600  if (O->hasArgStr())
601  OptionNames.push_back(O->ArgStr);
602 
603  bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
604  StringRef Flag = PermitValue ? LHS : Arg;
605  for (const auto &Name : OptionNames) {
606  unsigned Distance = StringRef(Name).edit_distance(
607  Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
608  if (!Best || Distance < BestDistance) {
609  Best = O;
610  BestDistance = Distance;
611  if (RHS.empty() || !PermitValue)
612  NearestString = std::string(Name);
613  else
614  NearestString = (Twine(Name) + "=" + RHS).str();
615  }
616  }
617  }
618 
619  return Best;
620 }
621 
622 /// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence()
623 /// that does special handling of cl::CommaSeparated options.
624 static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos,
625  StringRef ArgName, StringRef Value,
626  bool MultiArg = false) {
627  // Check to see if this option accepts a comma separated list of values. If
628  // it does, we have to split up the value into multiple values.
629  if (Handler->getMiscFlags() & CommaSeparated) {
630  StringRef Val(Value);
631  StringRef::size_type Pos = Val.find(',');
632 
633  while (Pos != StringRef::npos) {
634  // Process the portion before the comma.
635  if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
636  return true;
637  // Erase the portion before the comma, AND the comma.
638  Val = Val.substr(Pos + 1);
639  // Check for another comma.
640  Pos = Val.find(',');
641  }
642 
643  Value = Val;
644  }
645 
646  return Handler->addOccurrence(pos, ArgName, Value, MultiArg);
647 }
648 
649 /// ProvideOption - For Value, this differentiates between an empty value ("")
650 /// and a null value (StringRef()). The later is accepted for arguments that
651 /// don't allow a value (-foo) the former is rejected (-foo=).
652 static inline bool ProvideOption(Option *Handler, StringRef ArgName,
653  StringRef Value, int argc,
654  const char *const *argv, int &i) {
655  // Is this a multi-argument option?
656  unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
657 
658  // Enforce value requirements
659  switch (Handler->getValueExpectedFlag()) {
660  case ValueRequired:
661  if (!Value.data()) { // No value specified?
662  // If no other argument or the option only supports prefix form, we
663  // cannot look at the next argument.
664  if (i + 1 >= argc || Handler->getFormattingFlag() == cl::AlwaysPrefix)
665  return Handler->error("requires a value!");
666  // Steal the next argument, like for '-o filename'
667  assert(argv && "null check");
668  Value = StringRef(argv[++i]);
669  }
670  break;
671  case ValueDisallowed:
672  if (NumAdditionalVals > 0)
673  return Handler->error("multi-valued option specified"
674  " with ValueDisallowed modifier!");
675 
676  if (Value.data())
677  return Handler->error("does not allow a value! '" + Twine(Value) +
678  "' specified.");
679  break;
680  case ValueOptional:
681  break;
682  }
683 
684  // If this isn't a multi-arg option, just run the handler.
685  if (NumAdditionalVals == 0)
686  return CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value);
687 
688  // If it is, run the handle several times.
689  bool MultiArg = false;
690 
691  if (Value.data()) {
692  if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
693  return true;
694  --NumAdditionalVals;
695  MultiArg = true;
696  }
697 
698  while (NumAdditionalVals > 0) {
699  if (i + 1 >= argc)
700  return Handler->error("not enough values!");
701  assert(argv && "null check");
702  Value = StringRef(argv[++i]);
703 
704  if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
705  return true;
706  MultiArg = true;
707  --NumAdditionalVals;
708  }
709  return false;
710 }
711 
713  int Dummy = i;
714  return ProvideOption(Handler, Handler->ArgStr, Arg, 0, nullptr, Dummy);
715 }
716 
717 // getOptionPred - Check to see if there are any options that satisfy the
718 // specified predicate with names that are the prefixes in Name. This is
719 // checked by progressively stripping characters off of the name, checking to
720 // see if there options that satisfy the predicate. If we find one, return it,
721 // otherwise return null.
722 //
723 static Option *getOptionPred(StringRef Name, size_t &Length,
724  bool (*Pred)(const Option *),
725  const StringMap<Option *> &OptionsMap) {
727  if (OMI != OptionsMap.end() && !Pred(OMI->getValue()))
728  OMI = OptionsMap.end();
729 
730  // Loop while we haven't found an option and Name still has at least two
731  // characters in it (so that the next iteration will not be the empty
732  // string.
733  while (OMI == OptionsMap.end() && Name.size() > 1) {
734  Name = Name.substr(0, Name.size() - 1); // Chop off the last character.
735  OMI = OptionsMap.find(Name);
736  if (OMI != OptionsMap.end() && !Pred(OMI->getValue()))
737  OMI = OptionsMap.end();
738  }
739 
740  if (OMI != OptionsMap.end() && Pred(OMI->second)) {
741  Length = Name.size();
742  return OMI->second; // Found one!
743  }
744  return nullptr; // No option found!
745 }
746 
747 /// HandlePrefixedOrGroupedOption - The specified argument string (which started
748 /// with at least one '-') does not fully match an available option. Check to
749 /// see if this is a prefix or grouped option. If so, split arg into output an
750 /// Arg/Value pair and return the Option to parse it with.
751 static Option *
753  bool &ErrorParsing,
754  const StringMap<Option *> &OptionsMap) {
755  if (Arg.size() == 1)
756  return nullptr;
757 
758  // Do the lookup!
759  size_t Length = 0;
760  Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
761  if (!PGOpt)
762  return nullptr;
763 
764  do {
765  StringRef MaybeValue =
766  (Length < Arg.size()) ? Arg.substr(Length) : StringRef();
767  Arg = Arg.substr(0, Length);
768  assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
769 
770  // cl::Prefix options do not preserve '=' when used separately.
771  // The behavior for them with grouped options should be the same.
772  if (MaybeValue.empty() || PGOpt->getFormattingFlag() == cl::AlwaysPrefix ||
773  (PGOpt->getFormattingFlag() == cl::Prefix && MaybeValue[0] != '=')) {
774  Value = MaybeValue;
775  return PGOpt;
776  }
777 
778  if (MaybeValue[0] == '=') {
779  Value = MaybeValue.substr(1);
780  return PGOpt;
781  }
782 
783  // This must be a grouped option.
784  assert(isGrouping(PGOpt) && "Broken getOptionPred!");
785 
786  // Grouping options inside a group can't have values.
787  if (PGOpt->getValueExpectedFlag() == cl::ValueRequired) {
788  ErrorParsing |= PGOpt->error("may not occur within a group!");
789  return nullptr;
790  }
791 
792  // Because the value for the option is not required, we don't need to pass
793  // argc/argv in.
794  int Dummy = 0;
795  ErrorParsing |= ProvideOption(PGOpt, Arg, StringRef(), 0, nullptr, Dummy);
796 
797  // Get the next grouping option.
798  Arg = MaybeValue;
799  PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
800  } while (PGOpt);
801 
802  // We could not find a grouping option in the remainder of Arg.
803  return nullptr;
804 }
805 
806 static bool RequiresValue(const Option *O) {
807  return O->getNumOccurrencesFlag() == cl::Required ||
808  O->getNumOccurrencesFlag() == cl::OneOrMore;
809 }
810 
811 static bool EatsUnboundedNumberOfValues(const Option *O) {
812  return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
813  O->getNumOccurrencesFlag() == cl::OneOrMore;
814 }
815 
816 static bool isWhitespace(char C) {
817  return C == ' ' || C == '\t' || C == '\r' || C == '\n';
818 }
819 
820 static bool isWhitespaceOrNull(char C) {
821  return isWhitespace(C) || C == '\0';
822 }
823 
824 static bool isQuote(char C) { return C == '\"' || C == '\''; }
825 
828  bool MarkEOLs) {
829  SmallString<128> Token;
830  for (size_t I = 0, E = Src.size(); I != E; ++I) {
831  // Consume runs of whitespace.
832  if (Token.empty()) {
833  while (I != E && isWhitespace(Src[I])) {
834  // Mark the end of lines in response files.
835  if (MarkEOLs && Src[I] == '\n')
836  NewArgv.push_back(nullptr);
837  ++I;
838  }
839  if (I == E)
840  break;
841  }
842 
843  char C = Src[I];
844 
845  // Backslash escapes the next character.
846  if (I + 1 < E && C == '\\') {
847  ++I; // Skip the escape.
848  Token.push_back(Src[I]);
849  continue;
850  }
851 
852  // Consume a quoted string.
853  if (isQuote(C)) {
854  ++I;
855  while (I != E && Src[I] != C) {
856  // Backslash escapes the next character.
857  if (Src[I] == '\\' && I + 1 != E)
858  ++I;
859  Token.push_back(Src[I]);
860  ++I;
861  }
862  if (I == E)
863  break;
864  continue;
865  }
866 
867  // End the token if this is whitespace.
868  if (isWhitespace(C)) {
869  if (!Token.empty())
870  NewArgv.push_back(Saver.save(Token.str()).data());
871  // Mark the end of lines in response files.
872  if (MarkEOLs && C == '\n')
873  NewArgv.push_back(nullptr);
874  Token.clear();
875  continue;
876  }
877 
878  // This is a normal character. Append it.
879  Token.push_back(C);
880  }
881 
882  // Append the last token after hitting EOF with no whitespace.
883  if (!Token.empty())
884  NewArgv.push_back(Saver.save(Token.str()).data());
885 }
886 
887 /// Backslashes are interpreted in a rather complicated way in the Windows-style
888 /// command line, because backslashes are used both to separate path and to
889 /// escape double quote. This method consumes runs of backslashes as well as the
890 /// following double quote if it's escaped.
891 ///
892 /// * If an even number of backslashes is followed by a double quote, one
893 /// backslash is output for every pair of backslashes, and the last double
894 /// quote remains unconsumed. The double quote will later be interpreted as
895 /// the start or end of a quoted string in the main loop outside of this
896 /// function.
897 ///
898 /// * If an odd number of backslashes is followed by a double quote, one
899 /// backslash is output for every pair of backslashes, and a double quote is
900 /// output for the last pair of backslash-double quote. The double quote is
901 /// consumed in this case.
902 ///
903 /// * Otherwise, backslashes are interpreted literally.
904 static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
905  size_t E = Src.size();
906  int BackslashCount = 0;
907  // Skip the backslashes.
908  do {
909  ++I;
910  ++BackslashCount;
911  } while (I != E && Src[I] == '\\');
912 
913  bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
914  if (FollowedByDoubleQuote) {
915  Token.append(BackslashCount / 2, '\\');
916  if (BackslashCount % 2 == 0)
917  return I - 1;
918  Token.push_back('"');
919  return I;
920  }
921  Token.append(BackslashCount, '\\');
922  return I - 1;
923 }
924 
925 // Windows treats whitespace, double quotes, and backslashes specially, except
926 // when parsing the first token of a full command line, in which case
927 // backslashes are not special.
928 static bool isWindowsSpecialChar(char C) {
929  return isWhitespaceOrNull(C) || C == '\\' || C == '\"';
930 }
932  return isWhitespaceOrNull(C) || C == '\"';
933 }
934 
935 // Windows tokenization implementation. The implementation is designed to be
936 // inlined and specialized for the two user entry points.
938  StringRef Src, StringSaver &Saver, function_ref<void(StringRef)> AddToken,
939  bool AlwaysCopy, function_ref<void()> MarkEOL, bool InitialCommandName) {
940  SmallString<128> Token;
941 
942  // Sometimes, this function will be handling a full command line including an
943  // executable pathname at the start. In that situation, the initial pathname
944  // needs different handling from the following arguments, because when
945  // CreateProcess or cmd.exe scans the pathname, it doesn't treat \ as
946  // escaping the quote character, whereas when libc scans the rest of the
947  // command line, it does.
948  bool CommandName = InitialCommandName;
949 
950  // Try to do as much work inside the state machine as possible.
951  enum { INIT, UNQUOTED, QUOTED } State = INIT;
952 
953  for (size_t I = 0, E = Src.size(); I < E; ++I) {
954  switch (State) {
955  case INIT: {
956  assert(Token.empty() && "token should be empty in initial state");
957  // Eat whitespace before a token.
958  while (I < E && isWhitespaceOrNull(Src[I])) {
959  if (Src[I] == '\n')
960  MarkEOL();
961  ++I;
962  }
963  // Stop if this was trailing whitespace.
964  if (I >= E)
965  break;
966  size_t Start = I;
967  if (CommandName) {
968  while (I < E && !isWindowsSpecialCharInCommandName(Src[I]))
969  ++I;
970  } else {
971  while (I < E && !isWindowsSpecialChar(Src[I]))
972  ++I;
973  }
974  StringRef NormalChars = Src.slice(Start, I);
975  if (I >= E || isWhitespaceOrNull(Src[I])) {
976  // No special characters: slice out the substring and start the next
977  // token. Copy the string if the caller asks us to.
978  AddToken(AlwaysCopy ? Saver.save(NormalChars) : NormalChars);
979  if (I < E && Src[I] == '\n') {
980  MarkEOL();
981  CommandName = InitialCommandName;
982  } else {
983  CommandName = false;
984  }
985  } else if (Src[I] == '\"') {
986  Token += NormalChars;
987  State = QUOTED;
988  } else if (Src[I] == '\\') {
989  assert(!CommandName && "or else we'd have treated it as a normal char");
990  Token += NormalChars;
991  I = parseBackslash(Src, I, Token);
992  State = UNQUOTED;
993  } else {
994  llvm_unreachable("unexpected special character");
995  }
996  break;
997  }
998 
999  case UNQUOTED:
1000  if (isWhitespaceOrNull(Src[I])) {
1001  // Whitespace means the end of the token. If we are in this state, the
1002  // token must have contained a special character, so we must copy the
1003  // token.
1004  AddToken(Saver.save(Token.str()));
1005  Token.clear();
1006  if (Src[I] == '\n') {
1007  CommandName = InitialCommandName;
1008  MarkEOL();
1009  } else {
1010  CommandName = false;
1011  }
1012  State = INIT;
1013  } else if (Src[I] == '\"') {
1014  State = QUOTED;
1015  } else if (Src[I] == '\\' && !CommandName) {
1016  I = parseBackslash(Src, I, Token);
1017  } else {
1018  Token.push_back(Src[I]);
1019  }
1020  break;
1021 
1022  case QUOTED:
1023  if (Src[I] == '\"') {
1024  if (I < (E - 1) && Src[I + 1] == '"') {
1025  // Consecutive double-quotes inside a quoted string implies one
1026  // double-quote.
1027  Token.push_back('"');
1028  ++I;
1029  } else {
1030  // Otherwise, end the quoted portion and return to the unquoted state.
1031  State = UNQUOTED;
1032  }
1033  } else if (Src[I] == '\\' && !CommandName) {
1034  I = parseBackslash(Src, I, Token);
1035  } else {
1036  Token.push_back(Src[I]);
1037  }
1038  break;
1039  }
1040  }
1041 
1042  if (State != INIT)
1043  AddToken(Saver.save(Token.str()));
1044 }
1045 
1048  bool MarkEOLs) {
1049  auto AddToken = [&](StringRef Tok) { NewArgv.push_back(Tok.data()); };
1050  auto OnEOL = [&]() {
1051  if (MarkEOLs)
1052  NewArgv.push_back(nullptr);
1053  };
1054  tokenizeWindowsCommandLineImpl(Src, Saver, AddToken,
1055  /*AlwaysCopy=*/true, OnEOL, false);
1056 }
1057 
1059  SmallVectorImpl<StringRef> &NewArgv) {
1060  auto AddToken = [&](StringRef Tok) { NewArgv.push_back(Tok); };
1061  auto OnEOL = []() {};
1062  tokenizeWindowsCommandLineImpl(Src, Saver, AddToken, /*AlwaysCopy=*/false,
1063  OnEOL, false);
1064 }
1065 
1068  bool MarkEOLs) {
1069  auto AddToken = [&](StringRef Tok) { NewArgv.push_back(Tok.data()); };
1070  auto OnEOL = [&]() {
1071  if (MarkEOLs)
1072  NewArgv.push_back(nullptr);
1073  };
1074  tokenizeWindowsCommandLineImpl(Src, Saver, AddToken,
1075  /*AlwaysCopy=*/true, OnEOL, true);
1076 }
1077 
1080  bool MarkEOLs) {
1081  for (const char *Cur = Source.begin(); Cur != Source.end();) {
1082  SmallString<128> Line;
1083  // Check for comment line.
1084  if (isWhitespace(*Cur)) {
1085  while (Cur != Source.end() && isWhitespace(*Cur))
1086  ++Cur;
1087  continue;
1088  }
1089  if (*Cur == '#') {
1090  while (Cur != Source.end() && *Cur != '\n')
1091  ++Cur;
1092  continue;
1093  }
1094  // Find end of the current line.
1095  const char *Start = Cur;
1096  for (const char *End = Source.end(); Cur != End; ++Cur) {
1097  if (*Cur == '\\') {
1098  if (Cur + 1 != End) {
1099  ++Cur;
1100  if (*Cur == '\n' ||
1101  (*Cur == '\r' && (Cur + 1 != End) && Cur[1] == '\n')) {
1102  Line.append(Start, Cur - 1);
1103  if (*Cur == '\r')
1104  ++Cur;
1105  Start = Cur + 1;
1106  }
1107  }
1108  } else if (*Cur == '\n')
1109  break;
1110  }
1111  // Tokenize line.
1112  Line.append(Start, Cur);
1113  cl::TokenizeGNUCommandLine(Line, Saver, NewArgv, MarkEOLs);
1114  }
1115 }
1116 
1117 // It is called byte order marker but the UTF-8 BOM is actually not affected
1118 // by the host system's endianness.
1120  return (S.size() >= 3 && S[0] == '\xef' && S[1] == '\xbb' && S[2] == '\xbf');
1121 }
1122 
1123 // Substitute <CFGDIR> with the file's base path.
1124 static void ExpandBasePaths(StringRef BasePath, StringSaver &Saver,
1125  const char *&Arg) {
1126  assert(sys::path::is_absolute(BasePath));
1127  constexpr StringLiteral Token("<CFGDIR>");
1128  const StringRef ArgString(Arg);
1129 
1130  SmallString<128> ResponseFile;
1131  StringRef::size_type StartPos = 0;
1132  for (StringRef::size_type TokenPos = ArgString.find(Token);
1133  TokenPos != StringRef::npos;
1134  TokenPos = ArgString.find(Token, StartPos)) {
1135  // Token may appear more than once per arg (e.g. comma-separated linker
1136  // args). Support by using path-append on any subsequent appearances.
1137  const StringRef LHS = ArgString.substr(StartPos, TokenPos - StartPos);
1138  if (ResponseFile.empty())
1139  ResponseFile = LHS;
1140  else
1141  llvm::sys::path::append(ResponseFile, LHS);
1142  ResponseFile.append(BasePath);
1143  StartPos = TokenPos + Token.size();
1144  }
1145 
1146  if (!ResponseFile.empty()) {
1147  // Path-append the remaining arg substring if at least one token appeared.
1148  const StringRef Remaining = ArgString.substr(StartPos);
1149  if (!Remaining.empty())
1150  llvm::sys::path::append(ResponseFile, Remaining);
1151  Arg = Saver.save(ResponseFile.str()).data();
1152  }
1153 }
1154 
1155 // FName must be an absolute path.
1157  TokenizerCallback Tokenizer,
1159  bool MarkEOLs, bool RelativeNames,
1160  bool ExpandBasePath,
1164  FS.getBufferForFile(FName);
1165  if (!MemBufOrErr)
1166  return llvm::errorCodeToError(MemBufOrErr.getError());
1167  MemoryBuffer &MemBuf = *MemBufOrErr.get();
1168  StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize());
1169 
1170  // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
1171  ArrayRef<char> BufRef(MemBuf.getBufferStart(), MemBuf.getBufferEnd());
1172  std::string UTF8Buf;
1173  if (hasUTF16ByteOrderMark(BufRef)) {
1174  if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
1175  return llvm::createStringError(std::errc::illegal_byte_sequence,
1176  "Could not convert UTF16 to UTF8");
1177  Str = StringRef(UTF8Buf);
1178  }
1179  // If we see UTF-8 BOM sequence at the beginning of a file, we shall remove
1180  // these bytes before parsing.
1181  // Reference: http://en.wikipedia.org/wiki/UTF-8#Byte_order_mark
1182  else if (hasUTF8ByteOrderMark(BufRef))
1183  Str = StringRef(BufRef.data() + 3, BufRef.size() - 3);
1184 
1185  // Tokenize the contents into NewArgv.
1186  Tokenizer(Str, Saver, NewArgv, MarkEOLs);
1187 
1188  if (!RelativeNames)
1189  return Error::success();
1191  // If names of nested response files should be resolved relative to including
1192  // file, replace the included response file names with their full paths
1193  // obtained by required resolution.
1194  for (auto &Arg : NewArgv) {
1195  if (!Arg)
1196  continue;
1197 
1198  // Substitute <CFGDIR> with the file's base path.
1199  if (ExpandBasePath)
1200  ExpandBasePaths(BasePath, Saver, Arg);
1201 
1202  // Skip non-rsp file arguments.
1203  if (Arg[0] != '@')
1204  continue;
1205 
1206  StringRef FileName(Arg + 1);
1207  // Skip if non-relative.
1208  if (!llvm::sys::path::is_relative(FileName))
1209  continue;
1210 
1211  SmallString<128> ResponseFile;
1212  ResponseFile.push_back('@');
1213  ResponseFile.append(BasePath);
1214  llvm::sys::path::append(ResponseFile, FileName);
1215  Arg = Saver.save(ResponseFile.str()).data();
1216  }
1217  return Error::success();
1218 }
1219 
1220 /// Expand response files on a command line recursively using the given
1221 /// StringSaver and tokenization strategy.
1223  SmallVectorImpl<const char *> &Argv, bool MarkEOLs,
1224  bool RelativeNames, bool ExpandBasePath,
1227  bool AllExpanded = true;
1228  struct ResponseFileRecord {
1229  std::string File;
1230  size_t End;
1231  };
1232 
1233  // To detect recursive response files, we maintain a stack of files and the
1234  // position of the last argument in the file. This position is updated
1235  // dynamically as we recursively expand files.
1237 
1238  // Push a dummy entry that represents the initial command line, removing
1239  // the need to check for an empty list.
1240  FileStack.push_back({"", Argv.size()});
1241 
1242  // Don't cache Argv.size() because it can change.
1243  for (unsigned I = 0; I != Argv.size();) {
1244  while (I == FileStack.back().End) {
1245  // Passing the end of a file's argument list, so we can remove it from the
1246  // stack.
1247  FileStack.pop_back();
1248  }
1249 
1250  const char *Arg = Argv[I];
1251  // Check if it is an EOL marker
1252  if (Arg == nullptr) {
1253  ++I;
1254  continue;
1255  }
1256 
1257  if (Arg[0] != '@') {
1258  ++I;
1259  continue;
1260  }
1261 
1262  const char *FName = Arg + 1;
1263  // Note that CurrentDir is only used for top-level rsp files, the rest will
1264  // always have an absolute path deduced from the containing file.
1265  SmallString<128> CurrDir;
1266  if (llvm::sys::path::is_relative(FName)) {
1267  if (!CurrentDir) {
1268  if (auto CWD = FS.getCurrentWorkingDirectory()) {
1269  CurrDir = *CWD;
1270  } else {
1271  // TODO: The error should be propagated up the stack.
1272  llvm::consumeError(llvm::errorCodeToError(CWD.getError()));
1273  return false;
1274  }
1275  } else {
1276  CurrDir = *CurrentDir;
1277  }
1278  llvm::sys::path::append(CurrDir, FName);
1279  FName = CurrDir.c_str();
1280  }
1281  auto IsEquivalent = [FName, &FS](const ResponseFileRecord &RFile) {
1282  llvm::ErrorOr<llvm::vfs::Status> LHS = FS.status(FName);
1283  if (!LHS) {
1284  // TODO: The error should be propagated up the stack.
1286  return false;
1287  }
1288  llvm::ErrorOr<llvm::vfs::Status> RHS = FS.status(RFile.File);
1289  if (!RHS) {
1290  // TODO: The error should be propagated up the stack.
1292  return false;
1293  }
1294  return LHS->equivalent(*RHS);
1295  };
1296 
1297  // Check for recursive response files.
1298  if (any_of(drop_begin(FileStack), IsEquivalent)) {
1299  // This file is recursive, so we leave it in the argument stream and
1300  // move on.
1301  AllExpanded = false;
1302  ++I;
1303  continue;
1304  }
1305 
1306  // Replace this response file argument with the tokenization of its
1307  // contents. Nested response files are expanded in subsequent iterations.
1308  SmallVector<const char *, 0> ExpandedArgv;
1309  if (llvm::Error Err =
1310  ExpandResponseFile(FName, Saver, Tokenizer, ExpandedArgv, MarkEOLs,
1311  RelativeNames, ExpandBasePath, FS)) {
1312  // We couldn't read this file, so we leave it in the argument stream and
1313  // move on.
1314  // TODO: The error should be propagated up the stack.
1316  AllExpanded = false;
1317  ++I;
1318  continue;
1319  }
1320 
1321  for (ResponseFileRecord &Record : FileStack) {
1322  // Increase the end of all active records by the number of newly expanded
1323  // arguments, minus the response file itself.
1324  Record.End += ExpandedArgv.size() - 1;
1325  }
1326 
1327  FileStack.push_back({FName, I + ExpandedArgv.size()});
1328  Argv.erase(Argv.begin() + I);
1329  Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
1330  }
1331 
1332  // If successful, the top of the file stack will mark the end of the Argv
1333  // stream. A failure here indicates a bug in the stack popping logic above.
1334  // Note that FileStack may have more than one element at this point because we
1335  // don't have a chance to pop the stack when encountering recursive files at
1336  // the end of the stream, so seeing that doesn't indicate a bug.
1337  assert(FileStack.size() > 0 && Argv.size() == FileStack.back().End);
1338  return AllExpanded;
1339 }
1340 
1342  SmallVectorImpl<const char *> &Argv, bool MarkEOLs,
1343  bool RelativeNames, bool ExpandBasePath,
1344  llvm::Optional<StringRef> CurrentDir) {
1345  return ExpandResponseFiles(Saver, std::move(Tokenizer), Argv, MarkEOLs,
1346  RelativeNames, ExpandBasePath,
1347  std::move(CurrentDir), *vfs::getRealFileSystem());
1348 }
1349 
1350 bool cl::expandResponseFiles(int Argc, const char *const *Argv,
1351  const char *EnvVar, StringSaver &Saver,
1352  SmallVectorImpl<const char *> &NewArgv) {
1353  auto Tokenize = Triple(sys::getProcessTriple()).isOSWindows()
1356  // The environment variable specifies initial options.
1357  if (EnvVar)
1358  if (llvm::Optional<std::string> EnvValue = sys::Process::GetEnv(EnvVar))
1359  Tokenize(*EnvValue, Saver, NewArgv, /*MarkEOLs=*/false);
1360 
1361  // Command line options can override the environment variable.
1362  NewArgv.append(Argv + 1, Argv + Argc);
1363  return ExpandResponseFiles(Saver, Tokenize, NewArgv);
1364 }
1365 
1369  SmallString<128> AbsPath;
1370  if (sys::path::is_relative(CfgFile)) {
1371  AbsPath.assign(CfgFile);
1372  if (std::error_code EC = FS.makeAbsolute(AbsPath))
1373  return false;
1374  CfgFile = AbsPath.str();
1375  }
1376  if (llvm::Error Err =
1377  ExpandResponseFile(CfgFile, Saver, cl::tokenizeConfigFile, Argv,
1378  /*MarkEOLs=*/false, /*RelativeNames=*/true,
1379  /*ExpandBasePath=*/true, FS)) {
1380  // TODO: The error should be propagated up the stack.
1382  return false;
1383  }
1384  return ExpandResponseFiles(Saver, cl::tokenizeConfigFile, Argv,
1385  /*MarkEOLs=*/false, /*RelativeNames=*/true,
1386  /*ExpandBasePath=*/true, llvm::None, FS);
1387 }
1388 
1389 static void initCommonOptions();
1390 bool cl::ParseCommandLineOptions(int argc, const char *const *argv,
1391  StringRef Overview, raw_ostream *Errs,
1392  const char *EnvVar,
1393  bool LongOptionsUseDoubleDash) {
1396  BumpPtrAllocator A;
1397  StringSaver Saver(A);
1398  NewArgv.push_back(argv[0]);
1399 
1400  // Parse options from environment variable.
1401  if (EnvVar) {
1402  if (llvm::Optional<std::string> EnvValue =
1404  TokenizeGNUCommandLine(*EnvValue, Saver, NewArgv);
1405  }
1406 
1407  // Append options from command line.
1408  for (int I = 1; I < argc; ++I)
1409  NewArgv.push_back(argv[I]);
1410  int NewArgc = static_cast<int>(NewArgv.size());
1411 
1412  // Parse all options.
1413  return GlobalParser->ParseCommandLineOptions(NewArgc, &NewArgv[0], Overview,
1414  Errs, LongOptionsUseDoubleDash);
1415 }
1416 
1417 /// Reset all options at least once, so that we can parse different options.
1419  // Reset all option values to look like they have never been seen before.
1420  // Options might be reset twice (they can be reference in both OptionsMap
1421  // and one of the other members), but that does not harm.
1422  for (auto *SC : RegisteredSubCommands) {
1423  for (auto &O : SC->OptionsMap)
1424  O.second->reset();
1425  for (Option *O : SC->PositionalOpts)
1426  O->reset();
1427  for (Option *O : SC->SinkOpts)
1428  O->reset();
1429  if (SC->ConsumeAfterOpt)
1430  SC->ConsumeAfterOpt->reset();
1431  }
1432 }
1433 
1435  const char *const *argv,
1436  StringRef Overview,
1437  raw_ostream *Errs,
1438  bool LongOptionsUseDoubleDash) {
1439  assert(hasOptions() && "No options specified!");
1440 
1441  // Expand response files.
1442  SmallVector<const char *, 20> newArgv(argv, argv + argc);
1443  BumpPtrAllocator A;
1444  StringSaver Saver(A);
1445  ExpandResponseFiles(Saver,
1446  Triple(sys::getProcessTriple()).isOSWindows() ?
1448  newArgv);
1449  argv = &newArgv[0];
1450  argc = static_cast<int>(newArgv.size());
1451 
1452  // Copy the program name into ProgName, making sure not to overflow it.
1453  ProgramName = std::string(sys::path::filename(StringRef(argv[0])));
1454 
1455  ProgramOverview = Overview;
1456  bool IgnoreErrors = Errs;
1457  if (!Errs)
1458  Errs = &errs();
1459  bool ErrorParsing = false;
1460 
1461  // Check out the positional arguments to collect information about them.
1462  unsigned NumPositionalRequired = 0;
1463 
1464  // Determine whether or not there are an unlimited number of positionals
1465  bool HasUnlimitedPositionals = false;
1466 
1467  int FirstArg = 1;
1468  SubCommand *ChosenSubCommand = &SubCommand::getTopLevel();
1469  if (argc >= 2 && argv[FirstArg][0] != '-') {
1470  // If the first argument specifies a valid subcommand, start processing
1471  // options from the second argument.
1472  ChosenSubCommand = LookupSubCommand(StringRef(argv[FirstArg]));
1473  if (ChosenSubCommand != &SubCommand::getTopLevel())
1474  FirstArg = 2;
1475  }
1476  GlobalParser->ActiveSubCommand = ChosenSubCommand;
1477 
1478  assert(ChosenSubCommand);
1479  auto &ConsumeAfterOpt = ChosenSubCommand->ConsumeAfterOpt;
1480  auto &PositionalOpts = ChosenSubCommand->PositionalOpts;
1481  auto &SinkOpts = ChosenSubCommand->SinkOpts;
1482  auto &OptionsMap = ChosenSubCommand->OptionsMap;
1483 
1484  for (auto *O: DefaultOptions) {
1485  addOption(O, true);
1486  }
1487 
1488  if (ConsumeAfterOpt) {
1489  assert(PositionalOpts.size() > 0 &&
1490  "Cannot specify cl::ConsumeAfter without a positional argument!");
1491  }
1492  if (!PositionalOpts.empty()) {
1493 
1494  // Calculate how many positional values are _required_.
1495  bool UnboundedFound = false;
1496  for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
1497  Option *Opt = PositionalOpts[i];
1498  if (RequiresValue(Opt))
1499  ++NumPositionalRequired;
1500  else if (ConsumeAfterOpt) {
1501  // ConsumeAfter cannot be combined with "optional" positional options
1502  // unless there is only one positional argument...
1503  if (PositionalOpts.size() > 1) {
1504  if (!IgnoreErrors)
1505  Opt->error("error - this positional option will never be matched, "
1506  "because it does not Require a value, and a "
1507  "cl::ConsumeAfter option is active!");
1508  ErrorParsing = true;
1509  }
1510  } else if (UnboundedFound && !Opt->hasArgStr()) {
1511  // This option does not "require" a value... Make sure this option is
1512  // not specified after an option that eats all extra arguments, or this
1513  // one will never get any!
1514  //
1515  if (!IgnoreErrors)
1516  Opt->error("error - option can never match, because "
1517  "another positional argument will match an "
1518  "unbounded number of values, and this option"
1519  " does not require a value!");
1520  *Errs << ProgramName << ": CommandLine Error: Option '" << Opt->ArgStr
1521  << "' is all messed up!\n";
1522  *Errs << PositionalOpts.size();
1523  ErrorParsing = true;
1524  }
1525  UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
1526  }
1527  HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
1528  }
1529 
1530  // PositionalVals - A vector of "positional" arguments we accumulate into
1531  // the process at the end.
1532  //
1533  SmallVector<std::pair<StringRef, unsigned>, 4> PositionalVals;
1534 
1535  // If the program has named positional arguments, and the name has been run
1536  // across, keep track of which positional argument was named. Otherwise put
1537  // the positional args into the PositionalVals list...
1538  Option *ActivePositionalArg = nullptr;
1539 
1540  // Loop over all of the arguments... processing them.
1541  bool DashDashFound = false; // Have we read '--'?
1542  for (int i = FirstArg; i < argc; ++i) {
1543  Option *Handler = nullptr;
1544  Option *NearestHandler = nullptr;
1545  std::string NearestHandlerString;
1546  StringRef Value;
1547  StringRef ArgName = "";
1548  bool HaveDoubleDash = false;
1549 
1550  // Check to see if this is a positional argument. This argument is
1551  // considered to be positional if it doesn't start with '-', if it is "-"
1552  // itself, or if we have seen "--" already.
1553  //
1554  if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
1555  // Positional argument!
1556  if (ActivePositionalArg) {
1557  ProvidePositionalOption(ActivePositionalArg, StringRef(argv[i]), i);
1558  continue; // We are done!
1559  }
1560 
1561  if (!PositionalOpts.empty()) {
1562  PositionalVals.push_back(std::make_pair(StringRef(argv[i]), i));
1563 
1564  // All of the positional arguments have been fulfulled, give the rest to
1565  // the consume after option... if it's specified...
1566  //
1567  if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) {
1568  for (++i; i < argc; ++i)
1569  PositionalVals.push_back(std::make_pair(StringRef(argv[i]), i));
1570  break; // Handle outside of the argument processing loop...
1571  }
1572 
1573  // Delay processing positional arguments until the end...
1574  continue;
1575  }
1576  } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
1577  !DashDashFound) {
1578  DashDashFound = true; // This is the mythical "--"?
1579  continue; // Don't try to process it as an argument itself.
1580  } else if (ActivePositionalArg &&
1581  (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
1582  // If there is a positional argument eating options, check to see if this
1583  // option is another positional argument. If so, treat it as an argument,
1584  // otherwise feed it to the eating positional.
1585  ArgName = StringRef(argv[i] + 1);
1586  // Eat second dash.
1587  if (!ArgName.empty() && ArgName[0] == '-') {
1588  HaveDoubleDash = true;
1589  ArgName = ArgName.substr(1);
1590  }
1591 
1592  Handler = LookupLongOption(*ChosenSubCommand, ArgName, Value,
1593  LongOptionsUseDoubleDash, HaveDoubleDash);
1594  if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
1595  ProvidePositionalOption(ActivePositionalArg, StringRef(argv[i]), i);
1596  continue; // We are done!
1597  }
1598  } else { // We start with a '-', must be an argument.
1599  ArgName = StringRef(argv[i] + 1);
1600  // Eat second dash.
1601  if (!ArgName.empty() && ArgName[0] == '-') {
1602  HaveDoubleDash = true;
1603  ArgName = ArgName.substr(1);
1604  }
1605 
1606  Handler = LookupLongOption(*ChosenSubCommand, ArgName, Value,
1607  LongOptionsUseDoubleDash, HaveDoubleDash);
1608 
1609  // Check to see if this "option" is really a prefixed or grouped argument.
1610  if (!Handler && !(LongOptionsUseDoubleDash && HaveDoubleDash))
1611  Handler = HandlePrefixedOrGroupedOption(ArgName, Value, ErrorParsing,
1612  OptionsMap);
1613 
1614  // Otherwise, look for the closest available option to report to the user
1615  // in the upcoming error.
1616  if (!Handler && SinkOpts.empty())
1617  NearestHandler =
1618  LookupNearestOption(ArgName, OptionsMap, NearestHandlerString);
1619  }
1620 
1621  if (!Handler) {
1622  if (SinkOpts.empty()) {
1623  *Errs << ProgramName << ": Unknown command line argument '" << argv[i]
1624  << "'. Try: '" << argv[0] << " --help'\n";
1625 
1626  if (NearestHandler) {
1627  // If we know a near match, report it as well.
1628  *Errs << ProgramName << ": Did you mean '"
1629  << PrintArg(NearestHandlerString, 0) << "'?\n";
1630  }
1631 
1632  ErrorParsing = true;
1633  } else {
1634  for (Option *SinkOpt : SinkOpts)
1635  SinkOpt->addOccurrence(i, "", StringRef(argv[i]));
1636  }
1637  continue;
1638  }
1639 
1640  // If this is a named positional argument, just remember that it is the
1641  // active one...
1642  if (Handler->getFormattingFlag() == cl::Positional) {
1643  if ((Handler->getMiscFlags() & PositionalEatsArgs) && !Value.empty()) {
1644  Handler->error("This argument does not take a value.\n"
1645  "\tInstead, it consumes any positional arguments until "
1646  "the next recognized option.", *Errs);
1647  ErrorParsing = true;
1648  }
1649  ActivePositionalArg = Handler;
1650  }
1651  else
1652  ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
1653  }
1654 
1655  // Check and handle positional arguments now...
1656  if (NumPositionalRequired > PositionalVals.size()) {
1657  *Errs << ProgramName
1658  << ": Not enough positional command line arguments specified!\n"
1659  << "Must specify at least " << NumPositionalRequired
1660  << " positional argument" << (NumPositionalRequired > 1 ? "s" : "")
1661  << ": See: " << argv[0] << " --help\n";
1662 
1663  ErrorParsing = true;
1664  } else if (!HasUnlimitedPositionals &&
1665  PositionalVals.size() > PositionalOpts.size()) {
1666  *Errs << ProgramName << ": Too many positional arguments specified!\n"
1667  << "Can specify at most " << PositionalOpts.size()
1668  << " positional arguments: See: " << argv[0] << " --help\n";
1669  ErrorParsing = true;
1670 
1671  } else if (!ConsumeAfterOpt) {
1672  // Positional args have already been handled if ConsumeAfter is specified.
1673  unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
1674  for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
1675  if (RequiresValue(PositionalOpts[i])) {
1676  ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
1677  PositionalVals[ValNo].second);
1678  ValNo++;
1679  --NumPositionalRequired; // We fulfilled our duty...
1680  }
1681 
1682  // If we _can_ give this option more arguments, do so now, as long as we
1683  // do not give it values that others need. 'Done' controls whether the
1684  // option even _WANTS_ any more.
1685  //
1686  bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
1687  while (NumVals - ValNo > NumPositionalRequired && !Done) {
1688  switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
1689  case cl::Optional:
1690  Done = true; // Optional arguments want _at most_ one value
1691  [[fallthrough]];
1692  case cl::ZeroOrMore: // Zero or more will take all they can get...
1693  case cl::OneOrMore: // One or more will take all they can get...
1694  ProvidePositionalOption(PositionalOpts[i],
1695  PositionalVals[ValNo].first,
1696  PositionalVals[ValNo].second);
1697  ValNo++;
1698  break;
1699  default:
1700  llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
1701  "positional argument processing!");
1702  }
1703  }
1704  }
1705  } else {
1706  assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
1707  unsigned ValNo = 0;
1708  for (size_t J = 0, E = PositionalOpts.size(); J != E; ++J)
1709  if (RequiresValue(PositionalOpts[J])) {
1710  ErrorParsing |= ProvidePositionalOption(PositionalOpts[J],
1711  PositionalVals[ValNo].first,
1712  PositionalVals[ValNo].second);
1713  ValNo++;
1714  }
1715 
1716  // Handle the case where there is just one positional option, and it's
1717  // optional. In this case, we want to give JUST THE FIRST option to the
1718  // positional option and keep the rest for the consume after. The above
1719  // loop would have assigned no values to positional options in this case.
1720  //
1721  if (PositionalOpts.size() == 1 && ValNo == 0 && !PositionalVals.empty()) {
1722  ErrorParsing |= ProvidePositionalOption(PositionalOpts[0],
1723  PositionalVals[ValNo].first,
1724  PositionalVals[ValNo].second);
1725  ValNo++;
1726  }
1727 
1728  // Handle over all of the rest of the arguments to the
1729  // cl::ConsumeAfter command line option...
1730  for (; ValNo != PositionalVals.size(); ++ValNo)
1731  ErrorParsing |=
1732  ProvidePositionalOption(ConsumeAfterOpt, PositionalVals[ValNo].first,
1733  PositionalVals[ValNo].second);
1734  }
1735 
1736  // Loop over args and make sure all required args are specified!
1737  for (const auto &Opt : OptionsMap) {
1738  switch (Opt.second->getNumOccurrencesFlag()) {
1739  case Required:
1740  case OneOrMore:
1741  if (Opt.second->getNumOccurrences() == 0) {
1742  Opt.second->error("must be specified at least once!");
1743  ErrorParsing = true;
1744  }
1745  [[fallthrough]];
1746  default:
1747  break;
1748  }
1749  }
1750 
1751  // Now that we know if -debug is specified, we can use it.
1752  // Note that if ReadResponseFiles == true, this must be done before the
1753  // memory allocated for the expanded command line is free()d below.
1754  LLVM_DEBUG(dbgs() << "Args: ";
1755  for (int i = 0; i < argc; ++i) dbgs() << argv[i] << ' ';
1756  dbgs() << '\n';);
1757 
1758  // Free all of the memory allocated to the map. Command line options may only
1759  // be processed once!
1760  MoreHelp.clear();
1761 
1762  // If we had an error processing our arguments, don't let the program execute
1763  if (ErrorParsing) {
1764  if (!IgnoreErrors)
1765  exit(1);
1766  return false;
1767  }
1768  return true;
1769 }
1770 
1771 //===----------------------------------------------------------------------===//
1772 // Option Base class implementation
1773 //
1774 
1775 bool Option::error(const Twine &Message, StringRef ArgName, raw_ostream &Errs) {
1776  if (!ArgName.data())
1777  ArgName = ArgStr;
1778  if (ArgName.empty())
1779  Errs << HelpStr; // Be nice for positional arguments
1780  else
1781  Errs << GlobalParser->ProgramName << ": for the " << PrintArg(ArgName, 0);
1782 
1783  Errs << " option: " << Message << "\n";
1784  return true;
1785 }
1786 
1787 bool Option::addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
1788  bool MultiArg) {
1789  if (!MultiArg)
1790  NumOccurrences++; // Increment the number of times we have been seen
1791 
1792  return handleOccurrence(pos, ArgName, Value);
1793 }
1794 
1795 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
1796 // has been specified yet.
1797 //
1798 static StringRef getValueStr(const Option &O, StringRef DefaultMsg) {
1799  if (O.ValueStr.empty())
1800  return DefaultMsg;
1801  return O.ValueStr;
1802 }
1803 
1804 //===----------------------------------------------------------------------===//
1805 // cl::alias class implementation
1806 //
1807 
1808 // Return the width of the option tag for printing...
1809 size_t alias::getOptionWidth() const {
1810  return argPlusPrefixesSize(ArgStr);
1811 }
1812 
1813 void Option::printHelpStr(StringRef HelpStr, size_t Indent,
1814  size_t FirstLineIndentedBy) {
1815  assert(Indent >= FirstLineIndentedBy);
1816  std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1817  outs().indent(Indent - FirstLineIndentedBy)
1818  << ArgHelpPrefix << Split.first << "\n";
1819  while (!Split.second.empty()) {
1820  Split = Split.second.split('\n');
1821  outs().indent(Indent) << Split.first << "\n";
1822  }
1823 }
1824 
1825 void Option::printEnumValHelpStr(StringRef HelpStr, size_t BaseIndent,
1826  size_t FirstLineIndentedBy) {
1827  const StringRef ValHelpPrefix = " ";
1828  assert(BaseIndent >= FirstLineIndentedBy);
1829  std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1830  outs().indent(BaseIndent - FirstLineIndentedBy)
1831  << ArgHelpPrefix << ValHelpPrefix << Split.first << "\n";
1832  while (!Split.second.empty()) {
1833  Split = Split.second.split('\n');
1834  outs().indent(BaseIndent + ValHelpPrefix.size()) << Split.first << "\n";
1835  }
1836 }
1837 
1838 // Print out the option for the alias.
1839 void alias::printOptionInfo(size_t GlobalWidth) const {
1840  outs() << PrintArg(ArgStr);
1842 }
1843 
1844 //===----------------------------------------------------------------------===//
1845 // Parser Implementation code...
1846 //
1847 
1848 // basic_parser implementation
1849 //
1850 
1851 // Return the width of the option tag for printing...
1853  size_t Len = argPlusPrefixesSize(O.ArgStr);
1854  auto ValName = getValueName();
1855  if (!ValName.empty()) {
1856  size_t FormattingLen = 3;
1857  if (O.getMiscFlags() & PositionalEatsArgs)
1858  FormattingLen = 6;
1859  Len += getValueStr(O, ValName).size() + FormattingLen;
1860  }
1861 
1862  return Len;
1863 }
1864 
1865 // printOptionInfo - Print out information about this option. The
1866 // to-be-maintained width is specified.
1867 //
1869  size_t GlobalWidth) const {
1870  outs() << PrintArg(O.ArgStr);
1871 
1872  auto ValName = getValueName();
1873  if (!ValName.empty()) {
1874  if (O.getMiscFlags() & PositionalEatsArgs) {
1875  outs() << " <" << getValueStr(O, ValName) << ">...";
1876  } else if (O.getValueExpectedFlag() == ValueOptional)
1877  outs() << "[=<" << getValueStr(O, ValName) << ">]";
1878  else {
1879  outs() << (O.ArgStr.size() == 1 ? " <" : "=<") << getValueStr(O, ValName)
1880  << '>';
1881  }
1882  }
1883 
1884  Option::printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
1885 }
1886 
1888  size_t GlobalWidth) const {
1889  outs() << PrintArg(O.ArgStr);
1890  outs().indent(GlobalWidth - O.ArgStr.size());
1891 }
1892 
1893 // parser<bool> implementation
1894 //
1896  bool &Value) {
1897  if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1898  Arg == "1") {
1899  Value = true;
1900  return false;
1901  }
1902 
1903  if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1904  Value = false;
1905  return false;
1906  }
1907  return O.error("'" + Arg +
1908  "' is invalid value for boolean argument! Try 0 or 1");
1909 }
1910 
1911 // parser<boolOrDefault> implementation
1912 //
1914  boolOrDefault &Value) {
1915  if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1916  Arg == "1") {
1917  Value = BOU_TRUE;
1918  return false;
1919  }
1920  if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1921  Value = BOU_FALSE;
1922  return false;
1923  }
1924 
1925  return O.error("'" + Arg +
1926  "' is invalid value for boolean argument! Try 0 or 1");
1927 }
1928 
1929 // parser<int> implementation
1930 //
1932  int &Value) {
1933  if (Arg.getAsInteger(0, Value))
1934  return O.error("'" + Arg + "' value invalid for integer argument!");
1935  return false;
1936 }
1937 
1938 // parser<long> implementation
1939 //
1941  long &Value) {
1942  if (Arg.getAsInteger(0, Value))
1943  return O.error("'" + Arg + "' value invalid for long argument!");
1944  return false;
1945 }
1946 
1947 // parser<long long> implementation
1948 //
1950  long long &Value) {
1951  if (Arg.getAsInteger(0, Value))
1952  return O.error("'" + Arg + "' value invalid for llong argument!");
1953  return false;
1954 }
1955 
1956 // parser<unsigned> implementation
1957 //
1959  unsigned &Value) {
1960 
1961  if (Arg.getAsInteger(0, Value))
1962  return O.error("'" + Arg + "' value invalid for uint argument!");
1963  return false;
1964 }
1965 
1966 // parser<unsigned long> implementation
1967 //
1969  unsigned long &Value) {
1970 
1971  if (Arg.getAsInteger(0, Value))
1972  return O.error("'" + Arg + "' value invalid for ulong argument!");
1973  return false;
1974 }
1975 
1976 // parser<unsigned long long> implementation
1977 //
1979  StringRef Arg,
1980  unsigned long long &Value) {
1981 
1982  if (Arg.getAsInteger(0, Value))
1983  return O.error("'" + Arg + "' value invalid for ullong argument!");
1984  return false;
1985 }
1986 
1987 // parser<double>/parser<float> implementation
1988 //
1989 static bool parseDouble(Option &O, StringRef Arg, double &Value) {
1990  if (to_float(Arg, Value))
1991  return false;
1992  return O.error("'" + Arg + "' value invalid for floating point argument!");
1993 }
1994 
1996  double &Val) {
1997  return parseDouble(O, Arg, Val);
1998 }
1999 
2001  float &Val) {
2002  double dVal;
2003  if (parseDouble(O, Arg, dVal))
2004  return true;
2005  Val = (float)dVal;
2006  return false;
2007 }
2008 
2009 // generic_parser_base implementation
2010 //
2011 
2012 // findOption - Return the option number corresponding to the specified
2013 // argument string. If the option is not found, getNumOptions() is returned.
2014 //
2016  unsigned e = getNumOptions();
2017 
2018  for (unsigned i = 0; i != e; ++i) {
2019  if (getOption(i) == Name)
2020  return i;
2021  }
2022  return e;
2023 }
2024 
2025 static StringRef EqValue = "=<value>";
2026 static StringRef EmptyOption = "<empty>";
2027 static StringRef OptionPrefix = " =";
2028 static size_t getOptionPrefixesSize() {
2029  return OptionPrefix.size() + ArgHelpPrefix.size();
2030 }
2031 
2032 static bool shouldPrintOption(StringRef Name, StringRef Description,
2033  const Option &O) {
2034  return O.getValueExpectedFlag() != ValueOptional || !Name.empty() ||
2035  !Description.empty();
2036 }
2037 
2038 // Return the width of the option tag for printing...
2040  if (O.hasArgStr()) {
2041  size_t Size =
2042  argPlusPrefixesSize(O.ArgStr) + EqValue.size();
2043  for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
2046  continue;
2047  size_t NameSize = Name.empty() ? EmptyOption.size() : Name.size();
2048  Size = std::max(Size, NameSize + getOptionPrefixesSize());
2049  }
2050  return Size;
2051  } else {
2052  size_t BaseSize = 0;
2053  for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
2054  BaseSize = std::max(BaseSize, getOption(i).size() + 8);
2055  return BaseSize;
2056  }
2057 }
2058 
2059 // printOptionInfo - Print out information about this option. The
2060 // to-be-maintained width is specified.
2061 //
2063  size_t GlobalWidth) const {
2064  if (O.hasArgStr()) {
2065  // When the value is optional, first print a line just describing the
2066  // option without values.
2067  if (O.getValueExpectedFlag() == ValueOptional) {
2068  for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
2069  if (getOption(i).empty()) {
2070  outs() << PrintArg(O.ArgStr);
2071  Option::printHelpStr(O.HelpStr, GlobalWidth,
2072  argPlusPrefixesSize(O.ArgStr));
2073  break;
2074  }
2075  }
2076  }
2077 
2078  outs() << PrintArg(O.ArgStr) << EqValue;
2079  Option::printHelpStr(O.HelpStr, GlobalWidth,
2080  EqValue.size() +
2081  argPlusPrefixesSize(O.ArgStr));
2082  for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
2083  StringRef OptionName = getOption(i);
2084  StringRef Description = getDescription(i);
2085  if (!shouldPrintOption(OptionName, Description, O))
2086  continue;
2087  size_t FirstLineIndent = OptionName.size() + getOptionPrefixesSize();
2088  outs() << OptionPrefix << OptionName;
2089  if (OptionName.empty()) {
2090  outs() << EmptyOption;
2091  assert(FirstLineIndent >= EmptyOption.size());
2092  FirstLineIndent += EmptyOption.size();
2093  }
2094  if (!Description.empty())
2095  Option::printEnumValHelpStr(Description, GlobalWidth, FirstLineIndent);
2096  else
2097  outs() << '\n';
2098  }
2099  } else {
2100  if (!O.HelpStr.empty())
2101  outs() << " " << O.HelpStr << '\n';
2102  for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
2104  outs() << " " << PrintArg(Option);
2105  Option::printHelpStr(getDescription(i), GlobalWidth, Option.size() + 8);
2106  }
2107  }
2108 }
2109 
2110 static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
2111 
2112 // printGenericOptionDiff - Print the value of this option and it's default.
2113 //
2114 // "Generic" options have each value mapped to a name.
2116  const Option &O, const GenericOptionValue &Value,
2117  const GenericOptionValue &Default, size_t GlobalWidth) const {
2118  outs() << " " << PrintArg(O.ArgStr);
2119  outs().indent(GlobalWidth - O.ArgStr.size());
2120 
2121  unsigned NumOpts = getNumOptions();
2122  for (unsigned i = 0; i != NumOpts; ++i) {
2123  if (Value.compare(getOptionValue(i)))
2124  continue;
2125 
2126  outs() << "= " << getOption(i);
2127  size_t L = getOption(i).size();
2128  size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
2129  outs().indent(NumSpaces) << " (default: ";
2130  for (unsigned j = 0; j != NumOpts; ++j) {
2131  if (Default.compare(getOptionValue(j)))
2132  continue;
2133  outs() << getOption(j);
2134  break;
2135  }
2136  outs() << ")\n";
2137  return;
2138  }
2139  outs() << "= *unknown option value*\n";
2140 }
2141 
2142 // printOptionDiff - Specializations for printing basic value types.
2143 //
2144 #define PRINT_OPT_DIFF(T) \
2145  void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D, \
2146  size_t GlobalWidth) const { \
2147  printOptionName(O, GlobalWidth); \
2148  std::string Str; \
2149  { \
2150  raw_string_ostream SS(Str); \
2151  SS << V; \
2152  } \
2153  outs() << "= " << Str; \
2154  size_t NumSpaces = \
2155  MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0; \
2156  outs().indent(NumSpaces) << " (default: "; \
2157  if (D.hasValue()) \
2158  outs() << D.getValue(); \
2159  else \
2160  outs() << "*no default*"; \
2161  outs() << ")\n"; \
2162  }
2163 
2164 PRINT_OPT_DIFF(bool)
2166 PRINT_OPT_DIFF(int)
2167 PRINT_OPT_DIFF(long)
2168 PRINT_OPT_DIFF(long long)
2169 PRINT_OPT_DIFF(unsigned)
2170 PRINT_OPT_DIFF(unsigned long)
2171 PRINT_OPT_DIFF(unsigned long long)
2172 PRINT_OPT_DIFF(double)
2173 PRINT_OPT_DIFF(float)
2174 PRINT_OPT_DIFF(char)
2175 
2177  const OptionValue<std::string> &D,
2178  size_t GlobalWidth) const {
2179  printOptionName(O, GlobalWidth);
2180  outs() << "= " << V;
2181  size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
2182  outs().indent(NumSpaces) << " (default: ";
2183  if (D.hasValue())
2184  outs() << D.getValue();
2185  else
2186  outs() << "*no default*";
2187  outs() << ")\n";
2188 }
2189 
2190 // Print a placeholder for options that don't yet support printOptionDiff().
2192  size_t GlobalWidth) const {
2193  printOptionName(O, GlobalWidth);
2194  outs() << "= *cannot print option value*\n";
2195 }
2196 
2197 //===----------------------------------------------------------------------===//
2198 // -help and -help-hidden option implementation
2199 //
2200 
2201 static int OptNameCompare(const std::pair<const char *, Option *> *LHS,
2202  const std::pair<const char *, Option *> *RHS) {
2203  return strcmp(LHS->first, RHS->first);
2204 }
2205 
2206 static int SubNameCompare(const std::pair<const char *, SubCommand *> *LHS,
2207  const std::pair<const char *, SubCommand *> *RHS) {
2208  return strcmp(LHS->first, RHS->first);
2209 }
2210 
2211 // Copy Options into a vector so we can sort them as we like.
2212 static void sortOpts(StringMap<Option *> &OptMap,
2213  SmallVectorImpl<std::pair<const char *, Option *>> &Opts,
2214  bool ShowHidden) {
2215  SmallPtrSet<Option *, 32> OptionSet; // Duplicate option detection.
2216 
2217  for (StringMap<Option *>::iterator I = OptMap.begin(), E = OptMap.end();
2218  I != E; ++I) {
2219  // Ignore really-hidden options.
2220  if (I->second->getOptionHiddenFlag() == ReallyHidden)
2221  continue;
2222 
2223  // Unless showhidden is set, ignore hidden flags.
2224  if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
2225  continue;
2226 
2227  // If we've already seen this option, don't add it to the list again.
2228  if (!OptionSet.insert(I->second).second)
2229  continue;
2230 
2231  Opts.push_back(
2232  std::pair<const char *, Option *>(I->getKey().data(), I->second));
2233  }
2234 
2235  // Sort the options list alphabetically.
2236  array_pod_sort(Opts.begin(), Opts.end(), OptNameCompare);
2237 }
2238 
2239 static void
2241  SmallVectorImpl<std::pair<const char *, SubCommand *>> &Subs) {
2242  for (auto *S : SubMap) {
2243  if (S->getName().empty())
2244  continue;
2245  Subs.push_back(std::make_pair(S->getName().data(), S));
2246  }
2247  array_pod_sort(Subs.begin(), Subs.end(), SubNameCompare);
2248 }
2249 
2250 namespace {
2251 
2252 class HelpPrinter {
2253 protected:
2254  const bool ShowHidden;
2256  StrOptionPairVector;
2258  StrSubCommandPairVector;
2259  // Print the options. Opts is assumed to be alphabetically sorted.
2260  virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
2261  for (size_t i = 0, e = Opts.size(); i != e; ++i)
2262  Opts[i].second->printOptionInfo(MaxArgLen);
2263  }
2264 
2265  void printSubCommands(StrSubCommandPairVector &Subs, size_t MaxSubLen) {
2266  for (const auto &S : Subs) {
2267  outs() << " " << S.first;
2268  if (!S.second->getDescription().empty()) {
2269  outs().indent(MaxSubLen - strlen(S.first));
2270  outs() << " - " << S.second->getDescription();
2271  }
2272  outs() << "\n";
2273  }
2274  }
2275 
2276 public:
2277  explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
2278  virtual ~HelpPrinter() = default;
2279 
2280  // Invoke the printer.
2281  void operator=(bool Value) {
2282  if (!Value)
2283  return;
2284  printHelp();
2285 
2286  // Halt the program since help information was printed
2287  exit(0);
2288  }
2289 
2290  void printHelp() {
2291  SubCommand *Sub = GlobalParser->getActiveSubCommand();
2292  auto &OptionsMap = Sub->OptionsMap;
2293  auto &PositionalOpts = Sub->PositionalOpts;
2294  auto &ConsumeAfterOpt = Sub->ConsumeAfterOpt;
2295 
2296  StrOptionPairVector Opts;
2297  sortOpts(OptionsMap, Opts, ShowHidden);
2298 
2299  StrSubCommandPairVector Subs;
2300  sortSubCommands(GlobalParser->RegisteredSubCommands, Subs);
2301 
2302  if (!GlobalParser->ProgramOverview.empty())
2303  outs() << "OVERVIEW: " << GlobalParser->ProgramOverview << "\n";
2304 
2305  if (Sub == &SubCommand::getTopLevel()) {
2306  outs() << "USAGE: " << GlobalParser->ProgramName;
2307  if (Subs.size() > 2)
2308  outs() << " [subcommand]";
2309  outs() << " [options]";
2310  } else {
2311  if (!Sub->getDescription().empty()) {
2312  outs() << "SUBCOMMAND '" << Sub->getName()
2313  << "': " << Sub->getDescription() << "\n\n";
2314  }
2315  outs() << "USAGE: " << GlobalParser->ProgramName << " " << Sub->getName()
2316  << " [options]";
2317  }
2318 
2319  for (auto *Opt : PositionalOpts) {
2320  if (Opt->hasArgStr())
2321  outs() << " --" << Opt->ArgStr;
2322  outs() << " " << Opt->HelpStr;
2323  }
2324 
2325  // Print the consume after option info if it exists...
2326  if (ConsumeAfterOpt)
2327  outs() << " " << ConsumeAfterOpt->HelpStr;
2328 
2329  if (Sub == &SubCommand::getTopLevel() && !Subs.empty()) {
2330  // Compute the maximum subcommand length...
2331  size_t MaxSubLen = 0;
2332  for (size_t i = 0, e = Subs.size(); i != e; ++i)
2333  MaxSubLen = std::max(MaxSubLen, strlen(Subs[i].first));
2334 
2335  outs() << "\n\n";
2336  outs() << "SUBCOMMANDS:\n\n";
2337  printSubCommands(Subs, MaxSubLen);
2338  outs() << "\n";
2339  outs() << " Type \"" << GlobalParser->ProgramName
2340  << " <subcommand> --help\" to get more help on a specific "
2341  "subcommand";
2342  }
2343 
2344  outs() << "\n\n";
2345 
2346  // Compute the maximum argument length...
2347  size_t MaxArgLen = 0;
2348  for (size_t i = 0, e = Opts.size(); i != e; ++i)
2349  MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
2350 
2351  outs() << "OPTIONS:\n";
2352  printOptions(Opts, MaxArgLen);
2353 
2354  // Print any extra help the user has declared.
2355  for (const auto &I : GlobalParser->MoreHelp)
2356  outs() << I;
2357  GlobalParser->MoreHelp.clear();
2358  }
2359 };
2360 
2361 class CategorizedHelpPrinter : public HelpPrinter {
2362 public:
2363  explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
2364 
2365  // Helper function for printOptions().
2366  // It shall return a negative value if A's name should be lexicographically
2367  // ordered before B's name. It returns a value greater than zero if B's name
2368  // should be ordered before A's name, and it returns 0 otherwise.
2369  static int OptionCategoryCompare(OptionCategory *const *A,
2370  OptionCategory *const *B) {
2371  return (*A)->getName().compare((*B)->getName());
2372  }
2373 
2374  // Make sure we inherit our base class's operator=()
2375  using HelpPrinter::operator=;
2376 
2377 protected:
2378  void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override {
2379  std::vector<OptionCategory *> SortedCategories;
2381 
2382  // Collect registered option categories into vector in preparation for
2383  // sorting.
2384  for (OptionCategory *Category : GlobalParser->RegisteredOptionCategories)
2385  SortedCategories.push_back(Category);
2386 
2387  // Sort the different option categories alphabetically.
2388  assert(SortedCategories.size() > 0 && "No option categories registered!");
2389  array_pod_sort(SortedCategories.begin(), SortedCategories.end(),
2390  OptionCategoryCompare);
2391 
2392  // Walk through pre-sorted options and assign into categories.
2393  // Because the options are already alphabetically sorted the
2394  // options within categories will also be alphabetically sorted.
2395  for (size_t I = 0, E = Opts.size(); I != E; ++I) {
2396  Option *Opt = Opts[I].second;
2397  for (auto &Cat : Opt->Categories) {
2398  assert(llvm::is_contained(SortedCategories, Cat) &&
2399  "Option has an unregistered category");
2400  CategorizedOptions[Cat].push_back(Opt);
2401  }
2402  }
2403 
2404  // Now do printing.
2405  for (OptionCategory *Category : SortedCategories) {
2406  // Hide empty categories for --help, but show for --help-hidden.
2407  const auto &CategoryOptions = CategorizedOptions[Category];
2408  bool IsEmptyCategory = CategoryOptions.empty();
2409  if (!ShowHidden && IsEmptyCategory)
2410  continue;
2411 
2412  // Print category information.
2413  outs() << "\n";
2414  outs() << Category->getName() << ":\n";
2415 
2416  // Check if description is set.
2417  if (!Category->getDescription().empty())
2418  outs() << Category->getDescription() << "\n\n";
2419  else
2420  outs() << "\n";
2421 
2422  // When using --help-hidden explicitly state if the category has no
2423  // options associated with it.
2424  if (IsEmptyCategory) {
2425  outs() << " This option category has no options.\n";
2426  continue;
2427  }
2428  // Loop over the options in the category and print.
2429  for (const Option *Opt : CategoryOptions)
2430  Opt->printOptionInfo(MaxArgLen);
2431  }
2432  }
2433 };
2434 
2435 // This wraps the Uncategorizing and Categorizing printers and decides
2436 // at run time which should be invoked.
2437 class HelpPrinterWrapper {
2438 private:
2439  HelpPrinter &UncategorizedPrinter;
2440  CategorizedHelpPrinter &CategorizedPrinter;
2441 
2442 public:
2443  explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
2444  CategorizedHelpPrinter &CategorizedPrinter)
2445  : UncategorizedPrinter(UncategorizedPrinter),
2446  CategorizedPrinter(CategorizedPrinter) {}
2447 
2448  // Invoke the printer.
2449  void operator=(bool Value);
2450 };
2451 
2452 } // End anonymous namespace
2453 
2454 #if defined(__GNUC__)
2455 // GCC and GCC-compatible compilers define __OPTIMIZE__ when optimizations are
2456 // enabled.
2457 # if defined(__OPTIMIZE__)
2458 # define LLVM_IS_DEBUG_BUILD 0
2459 # else
2460 # define LLVM_IS_DEBUG_BUILD 1
2461 # endif
2462 #elif defined(_MSC_VER)
2463 // MSVC doesn't have a predefined macro indicating if optimizations are enabled.
2464 // Use _DEBUG instead. This macro actually corresponds to the choice between
2465 // debug and release CRTs, but it is a reasonable proxy.
2466 # if defined(_DEBUG)
2467 # define LLVM_IS_DEBUG_BUILD 1
2468 # else
2469 # define LLVM_IS_DEBUG_BUILD 0
2470 # endif
2471 #else
2472 // Otherwise, for an unknown compiler, assume this is an optimized build.
2473 # define LLVM_IS_DEBUG_BUILD 0
2474 #endif
2475 
2476 namespace {
2477 class VersionPrinter {
2478 public:
2479  void print() {
2480  raw_ostream &OS = outs();
2481 #ifdef PACKAGE_VENDOR
2482  OS << PACKAGE_VENDOR << " ";
2483 #else
2484  OS << "LLVM (http://llvm.org/):\n ";
2485 #endif
2486  OS << PACKAGE_NAME << " version " << PACKAGE_VERSION << "\n ";
2487 #if LLVM_IS_DEBUG_BUILD
2488  OS << "DEBUG build";
2489 #else
2490  OS << "Optimized build";
2491 #endif
2492 #ifndef NDEBUG
2493  OS << " with assertions";
2494 #endif
2495 #if LLVM_VERSION_PRINTER_SHOW_HOST_TARGET_INFO
2496  std::string CPU = std::string(sys::getHostCPUName());
2497  if (CPU == "generic")
2498  CPU = "(unknown)";
2499  OS << ".\n"
2500  << " Default target: " << sys::getDefaultTargetTriple() << '\n'
2501  << " Host CPU: " << CPU;
2502 #endif
2503  OS << '\n';
2504  }
2505  void operator=(bool OptionWasSpecified);
2506 };
2507 
2508 struct CommandLineCommonOptions {
2509  // Declare the four HelpPrinter instances that are used to print out help, or
2510  // help-hidden as an uncategorized list or in categories.
2511  HelpPrinter UncategorizedNormalPrinter{false};
2512  HelpPrinter UncategorizedHiddenPrinter{true};
2513  CategorizedHelpPrinter CategorizedNormalPrinter{false};
2514  CategorizedHelpPrinter CategorizedHiddenPrinter{true};
2515  // Declare HelpPrinter wrappers that will decide whether or not to invoke
2516  // a categorizing help printer
2517  HelpPrinterWrapper WrappedNormalPrinter{UncategorizedNormalPrinter,
2518  CategorizedNormalPrinter};
2519  HelpPrinterWrapper WrappedHiddenPrinter{UncategorizedHiddenPrinter,
2520  CategorizedHiddenPrinter};
2521  // Define a category for generic options that all tools should have.
2522  cl::OptionCategory GenericCategory{"Generic Options"};
2523 
2524  // Define uncategorized help printers.
2525  // --help-list is hidden by default because if Option categories are being
2526  // used then --help behaves the same as --help-list.
2528  "help-list",
2529  cl::desc(
2530  "Display list of available options (--help-list-hidden for more)"),
2531  cl::location(UncategorizedNormalPrinter),
2532  cl::Hidden,
2534  cl::cat(GenericCategory),
2536 
2538  "help-list-hidden",
2539  cl::desc("Display list of all available options"),
2540  cl::location(UncategorizedHiddenPrinter),
2541  cl::Hidden,
2543  cl::cat(GenericCategory),
2545 
2546  // Define uncategorized/categorized help printers. These printers change their
2547  // behaviour at runtime depending on whether one or more Option categories
2548  // have been declared.
2550  "help",
2551  cl::desc("Display available options (--help-hidden for more)"),
2552  cl::location(WrappedNormalPrinter),
2554  cl::cat(GenericCategory),
2556 
2557  cl::alias HOpA{"h", cl::desc("Alias for --help"), cl::aliasopt(HOp),
2559 
2561  "help-hidden",
2562  cl::desc("Display all available options"),
2563  cl::location(WrappedHiddenPrinter),
2564  cl::Hidden,
2566  cl::cat(GenericCategory),
2568 
2569  cl::opt<bool> PrintOptions{
2570  "print-options",
2571  cl::desc("Print non-default options after command line parsing"),
2572  cl::Hidden,
2573  cl::init(false),
2574  cl::cat(GenericCategory),
2576 
2577  cl::opt<bool> PrintAllOptions{
2578  "print-all-options",
2579  cl::desc("Print all option values after command line parsing"),
2580  cl::Hidden,
2581  cl::init(false),
2582  cl::cat(GenericCategory),
2584 
2585  VersionPrinterTy OverrideVersionPrinter = nullptr;
2586 
2587  std::vector<VersionPrinterTy> ExtraVersionPrinters;
2588 
2589  // Define the --version option that prints out the LLVM version for the tool
2590  VersionPrinter VersionPrinterInstance;
2591 
2593  "version", cl::desc("Display the version of this program"),
2594  cl::location(VersionPrinterInstance), cl::ValueDisallowed,
2595  cl::cat(GenericCategory)};
2596 };
2597 } // End anonymous namespace
2598 
2599 // Lazy-initialized global instance of options controlling the command-line
2600 // parser and general handling.
2602 
2603 static void initCommonOptions() {
2604  *CommonOptions;
2609  initTimerOptions();
2612  initDebugOptions();
2614 }
2615 
2617  // Initialise the general option category.
2618  static OptionCategory GeneralCategory{"General options"};
2619  return GeneralCategory;
2620 }
2621 
2622 void VersionPrinter::operator=(bool OptionWasSpecified) {
2623  if (!OptionWasSpecified)
2624  return;
2625 
2626  if (CommonOptions->OverrideVersionPrinter != nullptr) {
2627  CommonOptions->OverrideVersionPrinter(outs());
2628  exit(0);
2629  }
2630  print();
2631 
2632  // Iterate over any registered extra printers and call them to add further
2633  // information.
2634  if (!CommonOptions->ExtraVersionPrinters.empty()) {
2635  outs() << '\n';
2636  for (const auto &I : CommonOptions->ExtraVersionPrinters)
2637  I(outs());
2638  }
2639 
2640  exit(0);
2641 }
2642 
2643 void HelpPrinterWrapper::operator=(bool Value) {
2644  if (!Value)
2645  return;
2646 
2647  // Decide which printer to invoke. If more than one option category is
2648  // registered then it is useful to show the categorized help instead of
2649  // uncategorized help.
2650  if (GlobalParser->RegisteredOptionCategories.size() > 1) {
2651  // unhide --help-list option so user can have uncategorized output if they
2652  // want it.
2653  CommonOptions->HLOp.setHiddenFlag(NotHidden);
2654 
2655  CategorizedPrinter = true; // Invoke categorized printer
2656  } else
2657  UncategorizedPrinter = true; // Invoke uncategorized printer
2658 }
2659 
2660 // Print the value of each option.
2661 void cl::PrintOptionValues() { GlobalParser->printOptionValues(); }
2662 
2663 void CommandLineParser::printOptionValues() {
2664  if (!CommonOptions->PrintOptions && !CommonOptions->PrintAllOptions)
2665  return;
2666 
2668  sortOpts(ActiveSubCommand->OptionsMap, Opts, /*ShowHidden*/ true);
2669 
2670  // Compute the maximum argument length...
2671  size_t MaxArgLen = 0;
2672  for (size_t i = 0, e = Opts.size(); i != e; ++i)
2673  MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
2674 
2675  for (size_t i = 0, e = Opts.size(); i != e; ++i)
2676  Opts[i].second->printOptionValue(MaxArgLen, CommonOptions->PrintAllOptions);
2677 }
2678 
2679 // Utility function for printing the help message.
2680 void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
2681  if (!Hidden && !Categorized)
2682  CommonOptions->UncategorizedNormalPrinter.printHelp();
2683  else if (!Hidden && Categorized)
2684  CommonOptions->CategorizedNormalPrinter.printHelp();
2685  else if (Hidden && !Categorized)
2686  CommonOptions->UncategorizedHiddenPrinter.printHelp();
2687  else
2688  CommonOptions->CategorizedHiddenPrinter.printHelp();
2689 }
2690 
2691 /// Utility function for printing version number.
2693  CommonOptions->VersionPrinterInstance.print();
2694 }
2695 
2697  CommonOptions->OverrideVersionPrinter = func;
2698 }
2699 
2701  CommonOptions->ExtraVersionPrinters.push_back(func);
2702 }
2703 
2706  auto &Subs = GlobalParser->RegisteredSubCommands;
2707  (void)Subs;
2708  assert(is_contained(Subs, &Sub));
2709  return Sub.OptionsMap;
2710 }
2711 
2714  return GlobalParser->getRegisteredSubcommands();
2715 }
2716 
2719  for (auto &I : Sub.OptionsMap) {
2720  bool Unrelated = true;
2721  for (auto &Cat : I.second->Categories) {
2722  if (Cat == &Category || Cat == &CommonOptions->GenericCategory)
2723  Unrelated = false;
2724  }
2725  if (Unrelated)
2726  I.second->setHiddenFlag(cl::ReallyHidden);
2727  }
2728 }
2729 
2731  SubCommand &Sub) {
2733  for (auto &I : Sub.OptionsMap) {
2734  bool Unrelated = true;
2735  for (auto &Cat : I.second->Categories) {
2736  if (is_contained(Categories, Cat) ||
2737  Cat == &CommonOptions->GenericCategory)
2738  Unrelated = false;
2739  }
2740  if (Unrelated)
2741  I.second->setHiddenFlag(cl::ReallyHidden);
2742  }
2743 }
2744 
2747  GlobalParser->ResetAllOptionOccurrences();
2748 }
2749 
2750 void LLVMParseCommandLineOptions(int argc, const char *const *argv,
2751  const char *Overview) {
2752  llvm::cl::ParseCommandLineOptions(argc, argv, StringRef(Overview),
2753  &llvm::nulls());
2754 }
i
i
Definition: README.txt:29
MemoryBuffer.h
llvm::cl::AddExtraVersionPrinter
void AddExtraVersionPrinter(VersionPrinterTy func)
===------------------------------------------------------------------—===// Add an extra printer to u...
Definition: CommandLine.cpp:2700
llvm::array_pod_sort
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:1498
llvm::cl::SubCommand::reset
void reset()
Definition: CommandLine.cpp:506
llvm::cl::DefaultOption
@ DefaultOption
Definition: CommandLine.h:176
isWindowsSpecialChar
static bool isWindowsSpecialChar(char C)
Definition: CommandLine.cpp:928
llvm::cl::parser::parse
bool parse(Option &O, StringRef ArgName, StringRef Arg, DataType &V)
Definition: CommandLine.h:833
llvm::cl::generic_parser_base::getOptionValue
virtual const GenericOptionValue & getOptionValue(unsigned N) const =0
llvm::cl::extrahelp::extrahelp
extrahelp(StringRef help)
Definition: CommandLine.cpp:442
llvm
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
llvm::SmallVectorImpl::erase
iterator erase(const_iterator CI)
Definition: SmallVector.h:723
tokenizeWindowsCommandLineImpl
static void tokenizeWindowsCommandLineImpl(StringRef Src, StringSaver &Saver, function_ref< void(StringRef)> AddToken, bool AlwaysCopy, function_ref< void()> MarkEOL, bool InitialCommandName)
Definition: CommandLine.cpp:937
llvm::cl::SubCommand::OptionsMap
StringMap< Option * > OptionsMap
Definition: CommandLine.h:236
it
into xmm2 addss xmm2 xmm1 xmm3 addss xmm3 movaps xmm0 unpcklps xmm0 ret seems silly when it could just be one addps Expand libm rounding functions main should enable SSE DAZ mode and other fast SSE modes Think about doing i64 math in SSE regs on x86 This testcase should have no SSE instructions in it
Definition: README-SSE.txt:81
llvm::make_range
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
Definition: iterator_range.h:53
llvm::drop_begin
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition: STLExtras.h:268
llvm::cl::Option::Categories
SmallVector< OptionCategory *, 1 > Categories
Definition: CommandLine.h:285
Optional.h
FileSystem.h
getOptionPred
static Option * getOptionPred(StringRef Name, size_t &Length, bool(*Pred)(const Option *), const StringMap< Option * > &OptionsMap)
Definition: CommandLine.cpp:723
print
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
Definition: ArchiveWriter.cpp:189
llvm::cl::basic_parser_impl::anchor
virtual void anchor()
Definition: CommandLine.cpp:85
sortSubCommands
static void sortSubCommands(const SmallPtrSetImpl< SubCommand * > &SubMap, SmallVectorImpl< std::pair< const char *, SubCommand * >> &Subs)
Definition: CommandLine.cpp:2240
llvm::cl::Prefix
@ Prefix
Definition: CommandLine.h:160
llvm::cl::Option::addOccurrence
virtual bool addOccurrence(unsigned pos, StringRef ArgName, StringRef Value, bool MultiArg=false)
Definition: CommandLine.cpp:1787
llvm::cl::SubCommand::PositionalOpts
SmallVector< Option *, 4 > PositionalOpts
Definition: CommandLine.h:234
llvm::cl::location
LocationClass< Ty > location(Ty &L)
Definition: CommandLine.h:454
StringRef.h
llvm::cl::BOU_FALSE
@ BOU_FALSE
Definition: CommandLine.h:618
llvm::cl::basic_parser_impl::printOptionNoValue
void printOptionNoValue(const Option &O, size_t GlobalWidth) const
Definition: CommandLine.cpp:2191
llvm::cl::Option::HelpStr
StringRef HelpStr
Definition: CommandLine.h:282
llvm::StringRef::npos
static constexpr size_t npos
Definition: StringRef.h:52
Host.h
llvm::SmallVector
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1181
llvm::cl::PrintVersionMessage
void PrintVersionMessage()
Utility function for printing version number.
Definition: CommandLine.cpp:2692
llvm::cl::ResetAllOptionOccurrences
void ResetAllOptionOccurrences()
Reset all command line options to a state that looks as if they have never appeared on the command li...
Definition: CommandLine.cpp:1418
llvm::cl::Option::error
bool error(const Twine &Message, StringRef ArgName=StringRef(), raw_ostream &Errs=llvm::errs())
Definition: CommandLine.cpp:1775
Path.h
llvm::sys::path::is_absolute
bool is_absolute(const Twine &path, Style style=Style::native)
Is path absolute?
Definition: Path.cpp:671
ErrorHandling.h
llvm::cl::CommaSeparated
@ CommaSeparated
Definition: CommandLine.h:165
ManagedStatic.h
llvm::Error::success
static ErrorSuccess success()
Create a success value.
Definition: Error.h:329
llvm::cl::ValueOptional
@ ValueOptional
Definition: CommandLine.h:132
llvm::cl::SubCommand::getTopLevel
static SubCommand & getTopLevel()
Definition: CommandLine.cpp:494
llvm::SmallString::assign
void assign(StringRef RHS)
Assign from a StringRef.
Definition: SmallString.h:51
argPrefix
static SmallString< 8 > argPrefix(StringRef ArgName, size_t Pad=DefaultPad)
Definition: CommandLine.cpp:114
llvm::cl::ResetCommandLineParser
void ResetCommandLineParser()
Reset the command line parser back to its initial state.
Definition: CommandLine.cpp:2745
Error.h
llvm::hasUTF16ByteOrderMark
bool hasUTF16ByteOrderMark(ArrayRef< char > SrcBytes)
Returns true if a blob of text starts with a UTF-16 big or little endian byte order mark.
Definition: ConvertUTFWrapper.cpp:79
llvm::Triple
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
llvm::cl::Option::printOptionInfo
virtual void printOptionInfo(size_t GlobalWidth) const =0
llvm::cl::Hidden
@ Hidden
Definition: CommandLine.h:139
llvm::cl::SubCommand::getAll
static SubCommand & getAll()
Definition: CommandLine.cpp:496
llvm::StringMap::end
iterator end()
Definition: StringMap.h:204
DebugOptions.h
isWindowsSpecialCharInCommandName
static bool isWindowsSpecialCharInCommandName(char C)
Definition: CommandLine.cpp:931
llvm::Optional< llvm::StringRef >
llvm::cl::Option::setMiscFlag
void setMiscFlag(enum MiscFlags M)
Definition: CommandLine.h:332
llvm::StringRef::substr
StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition: StringRef.h:561
Help
static void Help(ArrayRef< SubtargetSubTypeKV > CPUTable, ArrayRef< SubtargetFeatureKV > FeatTable)
Display help for feature and mcpu choices.
Definition: MCSubtargetInfo.cpp:96
llvm::cl::GenericOptionValue
Definition: CommandLine.h:515
llvm::cl::generic_parser_base::getNumOptions
virtual unsigned getNumOptions() const =0
llvm::SmallPtrSet
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:450
llvm::cl::expandResponseFiles
bool expandResponseFiles(int Argc, const char *const *Argv, const char *EnvVar, StringSaver &Saver, SmallVectorImpl< const char * > &NewArgv)
A convenience helper which concatenates the options specified by the environment variable EnvVar and ...
Definition: CommandLine.cpp:1350
llvm::cl::SubCommand::unregisterSubCommand
void unregisterSubCommand()
Definition: CommandLine.cpp:502
llvm::max
Expected< ExpressionValue > max(const ExpressionValue &Lhs, const ExpressionValue &Rhs)
Definition: FileCheck.cpp:337
llvm::errs
raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
Definition: raw_ostream.cpp:891
llvm::cl::VersionPrinterTy
std::function< void(raw_ostream &)> VersionPrinterTy
Definition: CommandLine.h:77
llvm::initGraphWriterOptions
void initGraphWriterOptions()
Definition: GraphWriter.cpp:52
RHS
Value * RHS
Definition: X86PartialReduction.cpp:76
llvm::StringMap::find
iterator find(StringRef Key)
Definition: StringMap.h:217
llvm::nulls
raw_ostream & nulls()
This returns a reference to a raw_ostream which simply discards output.
Definition: raw_ostream.cpp:898
llvm::cl::ValueRequired
@ ValueRequired
Definition: CommandLine.h:133
llvm::cl::Option::printEnumValHelpStr
static void printEnumValHelpStr(StringRef HelpStr, size_t Indent, size_t FirstLineIndentedBy)
Definition: CommandLine.cpp:1825
llvm::count_if
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition: STLExtras.h:1707
llvm::cl::ReallyHidden
@ ReallyHidden
Definition: CommandLine.h:140
llvm::cl::TokenizeWindowsCommandLineFull
void TokenizeWindowsCommandLineFull(StringRef Source, StringSaver &Saver, SmallVectorImpl< const char * > &NewArgv, bool MarkEOLs=false)
Tokenizes a Windows full command line, including command name at the start.
Definition: CommandLine.cpp:1066
llvm::consumeError
void consumeError(Error Err)
Consume a Error without doing anything.
Definition: Error.h:1043
llvm::MemoryBuffer
This interface provides simple read-only access to a block of memory, and provides simple methods for...
Definition: MemoryBuffer.h:50
size_t
LLVM_DEBUG
#define LLVM_DEBUG(X)
Definition: Debug.h:101
llvm::ArrayRef::data
const T * data() const
Definition: ArrayRef.h:161
getOptionPrefixesSize
static size_t getOptionPrefixesSize()
Definition: CommandLine.cpp:2028
llvm::cl::generic_parser_base::printOptionInfo
virtual void printOptionInfo(const Option &O, size_t GlobalWidth) const
Definition: CommandLine.cpp:2062
llvm::cl::Option::hasArgStr
bool hasArgStr() const
Definition: CommandLine.h:309
LookupNearestOption
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...
Definition: CommandLine.cpp:575
llvm::sys::path::append
void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition: Path.cpp:456
llvm::dbgs
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
Arg
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
Definition: AMDGPULibCalls.cpp:186
isQuote
static bool isQuote(char C)
Definition: CommandLine.cpp:824
CommandLine.h
LHS
Value * LHS
Definition: X86PartialReduction.cpp:75
DefaultPad
const static size_t DefaultPad
Definition: CommandLine.cpp:101
llvm::initSignalsOptions
void initSignalsOptions()
Definition: Signals.cpp:63
llvm::StringLiteral
A wrapper around a string literal that serves as a proxy for constructing global tables of StringRefs...
Definition: StringRef.h:842
Process.h
llvm::cl::basic_parser< bool >
HandlePrefixedOrGroupedOption
static Option * HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value, bool &ErrorParsing, const StringMap< Option * > &OptionsMap)
HandlePrefixedOrGroupedOption - The specified argument string (which started with at least one '-') d...
Definition: CommandLine.cpp:752
llvm::PPCISD::SC
@ SC
CHAIN = SC CHAIN, Imm128 - System call.
Definition: PPCISelLowering.h:418
CommonOptions
static ManagedStatic< CommandLineCommonOptions > CommonOptions
Definition: CommandLine.cpp:2601
llvm::outs
raw_fd_ostream & outs()
This returns a reference to a raw_fd_ostream for standard output.
Definition: raw_ostream.cpp:883
llvm::cl::generic_parser_base::findOption
unsigned findOption(StringRef Name)
Definition: CommandLine.cpp:2015
parseDouble
static bool parseDouble(Option &O, StringRef Arg, double &Value)
Definition: CommandLine.cpp:1989
LLVM_REQUIRE_CONSTANT_INITIALIZATION
#define LLVM_REQUIRE_CONSTANT_INITIALIZATION
LLVM_REQUIRE_CONSTANT_INITIALIZATION - Apply this to globals to ensure that they are constant initial...
Definition: Compiler.h:279
llvm::MemoryBuffer::getBufferEnd
const char * getBufferEnd() const
Definition: MemoryBuffer.h:66
SmallString.h
llvm::cl::aliasopt
Definition: CommandLine.h:1905
E
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
isGrouping
static bool isGrouping(const Option *O)
Definition: CommandLine.cpp:124
llvm::cl::Option::reset
void reset()
Definition: CommandLine.cpp:473
llvm::MemoryBuffer::getBufferSize
size_t getBufferSize() const
Definition: MemoryBuffer.h:67
llvm::COFF::NameSize
@ NameSize
Definition: COFF.h:57
C
(vector float) vec_cmpeq(*A, *B) C
Definition: README_ALTIVEC.txt:86
llvm::cl::SubCommand::ConsumeAfterOpt
Option * ConsumeAfterOpt
Definition: CommandLine.h:238
llvm::cl::Option::getMiscFlags
unsigned getMiscFlags() const
Definition: CommandLine.h:304
llvm::cl::Required
@ Required
Definition: CommandLine.h:117
Twine.h
llvm::cl::PrintOptionValues
void PrintOptionValues()
Definition: CommandLine.cpp:2661
llvm::initWithColorOptions
void initWithColorOptions()
Definition: WithColor.cpp:34
llvm::errorCodeToError
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition: Error.cpp:92
llvm::cl::PositionalEatsArgs
@ PositionalEatsArgs
Definition: CommandLine.h:166
llvm::StringMapConstIterator
Definition: StringMap.h:26
ArgPrefix
static StringRef ArgPrefix
Definition: CommandLine.cpp:103
llvm::cl::Option::getFormattingFlag
enum FormattingFlags getFormattingFlag() const
Definition: CommandLine.h:300
llvm::cl::NotHidden
@ NotHidden
Definition: CommandLine.h:138
llvm::cl::ParseCommandLineOptions
bool ParseCommandLineOptions(int argc, const char *const *argv, StringRef Overview="", raw_ostream *Errs=nullptr, const char *EnvVar=nullptr, bool LongOptionsUseDoubleDash=false)
Definition: CommandLine.cpp:1390
llvm::ManagedStatic
ManagedStatic - This transparently changes the behavior of global statics to be lazily constructed on...
Definition: ManagedStatic.h:83
llvm::cl::generic_parser_base::getOption
virtual StringRef getOption(unsigned N) const =0
llvm::ErrorOr::getError
std::error_code getError() const
Definition: ErrorOr.h:153
llvm::cl::Positional
@ Positional
Definition: CommandLine.h:159
B
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
llvm::cl::ConsumeAfter
@ ConsumeAfter
Definition: CommandLine.h:127
llvm::MCID::Flag
Flag
These should be considered private to the implementation of the MCInstrDesc class.
Definition: MCInstrDesc.h:147
llvm::cl::TokenizeWindowsCommandLine
void TokenizeWindowsCommandLine(StringRef Source, StringSaver &Saver, SmallVectorImpl< const char * > &NewArgv, bool MarkEOLs=false)
Tokenizes a string of Windows command line arguments, which may contain quotes and escaped quotes.
Definition: CommandLine.cpp:1046
llvm::cl::SubCommand::registerSubCommand
void registerSubCommand()
Definition: CommandLine.cpp:498
llvm::report_fatal_error
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:145
llvm::raw_ostream
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
llvm::cl::parser
Definition: CommandLine.h:804
llvm::cl::Option::getNumAdditionalVals
unsigned getNumAdditionalVals() const
Definition: CommandLine.h:306
llvm::operator<<
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
Definition: APFixedPoint.h:230
llvm::cl::Option::getNumOccurrences
int getNumOccurrences() const
Definition: CommandLine.h:402
llvm::StringRef::data
const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition: StringRef.h:131
llvm::convertUTF16ToUTF8String
bool convertUTF16ToUTF8String(ArrayRef< char > SrcBytes, std::string &Out)
Converts a stream of raw bytes assumed to be UTF16 into a UTF8 std::string.
Definition: ConvertUTFWrapper.cpp:84
SmallPtrSet.h
STLFunctionalExtras.h
llvm::SmallVectorImpl::append
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
Definition: SmallVector.h:669
llvm::cl::OneOrMore
@ OneOrMore
Definition: CommandLine.h:118
MaxOptWidth
static const size_t MaxOptWidth
Definition: CommandLine.cpp:2110
ArgPrefixLong
static StringRef ArgPrefixLong
Definition: CommandLine.cpp:104
llvm::cl::AllSubCommands
ManagedStatic< SubCommand > AllSubCommands
Definition: CommandLine.cpp:492
llvm::cl::SubCommand::getDescription
StringRef getDescription() const
Definition: CommandLine.h:232
ProvideOption
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...
Definition: CommandLine.cpp:652
llvm::None
const NoneType None
Definition: None.h:24
argPlusPrefixesSize
static size_t argPlusPrefixesSize(StringRef ArgName, size_t Pad=DefaultPad)
Definition: CommandLine.cpp:107
llvm::cl::Option::addArgument
void addArgument()
Definition: CommandLine.cpp:446
llvm::cl::readConfigFile
bool readConfigFile(StringRef CfgFileName, StringSaver &Saver, SmallVectorImpl< const char * > &Argv, llvm::vfs::FileSystem &FS)
Reads command line options from the given configuration file.
Definition: CommandLine.cpp:1366
llvm::StringMap
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition: StringMap.h:110
llvm::SmallString< 8 >
isWhitespace
static bool isWhitespace(char C)
Definition: CommandLine.cpp:816
OptNameCompare
static int OptNameCompare(const std::pair< const char *, Option * > *LHS, const std::pair< const char *, Option * > *RHS)
Definition: CommandLine.cpp:2201
StringSaver.h
llvm::cl::ZeroOrMore
@ ZeroOrMore
Definition: CommandLine.h:116
llvm::function_ref
An efficient, type-erasing, non-owning reference to a callable.
Definition: STLFunctionalExtras.h:36
llvm::cl::Option::ArgStr
StringRef ArgStr
Definition: CommandLine.h:281
llvm::StringRef::empty
constexpr bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:134
llvm::SmallString::append
void append(StringRef RHS)
Append from a StringRef.
Definition: SmallString.h:68
getValueStr
static StringRef getValueStr(const Option &O, StringRef DefaultMsg)
Definition: CommandLine.cpp:1798
llvm::cl::opt
Definition: CommandLine.h:1399
llvm::SmallString::c_str
const char * c_str()
Definition: SmallString.h:263
llvm::RISCVFenceField::O
@ O
Definition: RISCVBaseInfo.h:264
llvm::cl::Option
Definition: CommandLine.h:249
INIT
#define INIT(o, n)
Definition: regexec.c:120
llvm::cl::OptionCategory::getDescription
StringRef getDescription() const
Definition: CommandLine.h:196
llvm::cl::generic_parser_base::printOptionDiff
void printOptionDiff(const Option &O, const AnyOptionValue &V, const AnyOptionValue &Default, size_t GlobalWidth) const
Definition: CommandLine.h:754
llvm::initDebugOptions
void initDebugOptions()
Definition: Debug.cpp:145
llvm::vfs::getRealFileSystem
IntrusiveRefCntPtr< FileSystem > getRealFileSystem()
Gets an vfs::FileSystem for the 'real' file system, as seen by the operating system.
Definition: VirtualFileSystem.cpp:376
llvm::cl::SubCommand::SinkOpts
SmallVector< Option *, 4 > SinkOpts
Definition: CommandLine.h:235
llvm::StringMapIterator
Definition: StringMap.h:27
llvm::cl::Option::getValueExpectedFlag
enum ValueExpected getValueExpectedFlag() const
Definition: CommandLine.h:292
D
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
EqValue
static StringRef EqValue
Definition: CommandLine.cpp:2025
llvm::BumpPtrAllocatorImpl
Allocate memory in an ever growing pool, as if by bump-pointer.
Definition: Allocator.h:63
move
compiles ldr LCPI1_0 ldr ldr mov lsr tst moveq r1 ldr LCPI1_1 and r0 bx lr It would be better to do something like to fold the shift into the conditional move
Definition: README.txt:546
llvm::numbers::e
constexpr double e
Definition: MathExtras.h:54
llvm::DenseMap
Definition: DenseMap.h:714
llvm::cl::Grouping
@ Grouping
Definition: CommandLine.h:173
I
#define I(x, y, z)
Definition: MD5.cpp:58
StringExtras.h
sub
we currently eax ecx subl eax ret We would use one fewer register if codegen d eax neg eax eax ret Note that this isn t beneficial if the load can be folded into the sub In this we want a sub
Definition: README.txt:460
llvm::cl::SetVersionPrinter
void SetVersionPrinter(VersionPrinterTy func)
===------------------------------------------------------------------—===// Override the default (LLV...
Definition: CommandLine.cpp:2696
Support.h
llvm::cl::init
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:439
llvm::cl::SubCommand
Definition: CommandLine.h:204
llvm::cl::getRegisteredOptions
StringMap< Option * > & getRegisteredOptions(SubCommand &Sub=SubCommand::getTopLevel())
Use this to get a StringMap to all registered named options (e.g.
Definition: CommandLine.cpp:2704
llvm::cl::ExpandResponseFiles
bool ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer, SmallVectorImpl< const char * > &Argv, bool MarkEOLs, bool RelativeNames, bool ExpandBasePath, llvm::Optional< llvm::StringRef > CurrentDir, llvm::vfs::FileSystem &FS)
Expand response files on a command line recursively using the given StringSaver and tokenization stra...
Definition: CommandLine.cpp:1222
llvm::is_contained
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:1673
ArrayRef.h
RequiresValue
static bool RequiresValue(const Option *O)
Definition: CommandLine.cpp:806
llvm::StringMap::begin
iterator begin()
Definition: StringMap.h:203
llvm::cl::ProvidePositionalOption
bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i)
Parses Arg into the option handler Handler.
Definition: CommandLine.cpp:712
assert
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
llvm::sys::path::parent_path
StringRef parent_path(StringRef path, Style style=Style::native)
Get parent path.
Definition: Path.cpp:467
parseBackslash
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,...
Definition: CommandLine.cpp:904
llvm::sys::Process::GetEnv
static Optional< std::string > GetEnv(StringRef name)
llvm::cl::ValueDisallowed
@ ValueDisallowed
Definition: CommandLine.h:134
llvm::X86AS::FS
@ FS
Definition: X86.h:200
GlobalParser
static ManagedStatic< CommandLineParser > GlobalParser
Definition: CommandLine.cpp:436
llvm::cl::tokenizeConfigFile
void tokenizeConfigFile(StringRef Source, StringSaver &Saver, SmallVectorImpl< const char * > &NewArgv, bool MarkEOLs=false)
Tokenizes content of configuration file.
Definition: CommandLine.cpp:1078
llvm::cl::Option::setDefault
virtual void setDefault()=0
llvm::cl::Option::setArgStr
void setArgStr(StringRef S)
Definition: CommandLine.cpp:453
llvm::cl::PrintHelpMessage
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...
Definition: CommandLine.cpp:2680
llvm::Record
Definition: Record.h:1552
llvm::DenseMapBase< DenseMap< KeyT, ValueT, DenseMapInfo< KeyT >, llvm::detail::DenseMapPair< KeyT, ValueT > >, KeyT, ValueT, DenseMapInfo< KeyT >, llvm::detail::DenseMapPair< KeyT, ValueT > >::empty
bool empty() const
Definition: DenseMap.h:98
llvm::cl::generic_parser_base::printGenericOptionDiff
void printGenericOptionDiff(const Option &O, const GenericOptionValue &V, const GenericOptionValue &Default, size_t GlobalWidth) const
Definition: CommandLine.cpp:2115
llvm::initTypeSizeOptions
void initTypeSizeOptions()
Definition: TypeSize.cpp:33
llvm::cl::boolOrDefault
boolOrDefault
Definition: CommandLine.h:618
llvm::cl::basic_parser_impl::getValueName
virtual StringRef getValueName() const
Definition: CommandLine.h:897
llvm::StringSaver
Saves strings in the provided stable storage and returns a StringRef with a stable character pointer.
Definition: StringSaver.h:21
Triple.h
llvm::size
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition: STLExtras.h:1571
llvm::cl::TokenizeWindowsCommandLineNoCopy
void TokenizeWindowsCommandLineNoCopy(StringRef Source, StringSaver &Saver, SmallVectorImpl< StringRef > &NewArgv)
Tokenizes a Windows command line while attempting to avoid copies.
Definition: CommandLine.cpp:1058
llvm::NVPTXISD::Dummy
@ Dummy
Definition: NVPTXISelLowering.h:60
LLVMParseCommandLineOptions
void LLVMParseCommandLineOptions(int argc, const char *const *argv, const char *Overview)
This function parses the given arguments using the LLVM command line parser.
Definition: CommandLine.cpp:2750
llvm::SmallPtrSetImplBase::clear
void clear()
Definition: SmallPtrSet.h:95
llvm::sys::getDefaultTargetTriple
std::string getDefaultTargetTriple()
getDefaultTargetTriple() - Return the default target triple the compiler has been configured to produ...
llvm::Sched::Source
@ Source
Definition: TargetLowering.h:98
llvm::ArrayRef< char >
llvm::any_of
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1597
llvm::StringRef
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
cl
http eax xorl edx cl sete al setne dl sall cl
Definition: README.txt:25
llvm_unreachable
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Definition: ErrorHandling.h:143
ArgHelpPrefix
static StringRef ArgHelpPrefix
Definition: CommandLine.cpp:105
llvm::cl::Sink
@ Sink
Definition: CommandLine.h:167
hasUTF8ByteOrderMark
static bool hasUTF8ByteOrderMark(ArrayRef< char > S)
Definition: CommandLine.cpp:1119
llvm::cl::alias
Definition: CommandLine.h:1846
llvm::cl::TokenizerCallback
void(*)(StringRef Source, StringSaver &Saver, SmallVectorImpl< const char * > &NewArgv, bool MarkEOLs) TokenizerCallback
String tokenization function type.
Definition: CommandLine.h:2053
S
add sub stmia L5 ldr r0 bl L_printf $stub Instead of a and a wouldn t it be better to do three moves *Return an aggregate type is even return S
Definition: README.txt:210
llvm::initDebugCounterOptions
void initDebugCounterOptions()
Definition: DebugCounter.cpp:61
llvm::cl::TokenizeGNUCommandLine
void TokenizeGNUCommandLine(StringRef Source, StringSaver &Saver, SmallVectorImpl< const char * > &NewArgv, bool MarkEOLs=false)
Tokenizes a command line that can contain escapes and quotes.
Definition: CommandLine.cpp:826
llvm::initRandomSeedOptions
void initRandomSeedOptions()
Definition: RandomNumberGenerator.cpp:41
VirtualFileSystem.h
ConvertUTF.h
llvm::cl::Optional
@ Optional
Definition: CommandLine.h:115
CommaSeparateAndAddOccurrence
static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos, StringRef ArgName, StringRef Value, bool MultiArg=false)
CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence() that does special handling ...
Definition: CommandLine.cpp:624
llvm::cl::generic_parser_base::getDescription
virtual StringRef getDescription(unsigned N) const =0
llvm::cl::Option::Subs
SmallPtrSet< SubCommand *, 1 > Subs
Definition: CommandLine.h:286
llvm::Triple::isOSWindows
bool isOSWindows() const
Tests whether the OS is Windows.
Definition: Triple.h:572
llvm::StringRef::size
constexpr size_t size() const
size - Get the string size.
Definition: StringRef.h:137
llvm::cl::AlwaysPrefix
@ AlwaysPrefix
Definition: CommandLine.h:161
j
return j(j<< 16)
llvm::Twine
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
llvm::empty
constexpr bool empty(const T &RangeOrContainer)
Test whether RangeOrContainer is empty. Similar to C++17 std::empty.
Definition: STLExtras.h:256
llvm::createStringError
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition: Error.h:1239
llvm::MemoryBuffer::getBufferStart
const char * getBufferStart() const
Definition: MemoryBuffer.h:65
llvm::vfs::FileSystem
The virtual file system interface.
Definition: VirtualFileSystem.h:268
sortOpts
static void sortOpts(StringMap< Option * > &OptMap, SmallVectorImpl< std::pair< const char *, Option * >> &Opts, bool ShowHidden)
Definition: CommandLine.cpp:2212
llvm::GraphProgram::Name
Name
Definition: GraphWriter.h:50
llvm::cl::AddLiteralOption
void AddLiteralOption(Option &O, StringRef Name)
Adds a new option for parsing and provides the option it refers to.
Definition: CommandLine.cpp:438
llvm::cl::HideUnrelatedOptions
void HideUnrelatedOptions(cl::OptionCategory &Category, SubCommand &Sub=SubCommand::getTopLevel())
Mark all options not part of this category as cl::ReallyHidden.
Definition: CommandLine.cpp:2717
llvm::initTimerOptions
void initTimerOptions()
Definition: Timer.cpp:90
initCommonOptions
static void initCommonOptions()
Definition: CommandLine.cpp:2603
llvm::sys::getProcessTriple
std::string getProcessTriple()
getProcessTriple() - Return an appropriate target triple for generating code to be loaded into the cu...
Definition: Host.cpp:1915
llvm::Error
Lightweight error class with error context and mandatory checking.
Definition: Error.h:155
llvm::cl::basic_parser_impl::getOptionWidth
size_t getOptionWidth(const Option &O) const
Definition: CommandLine.cpp:1852
llvm::cl::OptionCategory::getName
StringRef getName() const
Definition: CommandLine.h:195
EatsUnboundedNumberOfValues
static bool EatsUnboundedNumberOfValues(const Option *O)
Definition: CommandLine.cpp:811
llvm::TargetStackID::Value
Value
Definition: TargetFrameLowering.h:27
llvm::initStatisticOptions
void initStatisticOptions()
Definition: Statistic.cpp:49
llvm::cl::Option::printHelpStr
static void printHelpStr(StringRef HelpStr, size_t Indent, size_t FirstLineIndentedBy)
Definition: CommandLine.cpp:1813
llvm::SmallVectorImpl::clear
void clear()
Definition: SmallVector.h:596
isWhitespaceOrNull
static bool isWhitespaceOrNull(char C)
Definition: CommandLine.cpp:820
llvm::cl::basic_parser_impl::printOptionName
void printOptionName(const Option &O, size_t GlobalWidth) const
Definition: CommandLine.cpp:1887
llvm::StringMap::count
size_type count(StringRef Key) const
count - Return 1 if the element is in the map, 0 otherwise.
Definition: StringMap.h:245
llvm::SmallString::str
StringRef str() const
Explicit conversion to StringRef.
Definition: SmallString.h:260
OptionPrefix
static StringRef OptionPrefix
Definition: CommandLine.cpp:2027
llvm::cl::BOU_TRUE
@ BOU_TRUE
Definition: CommandLine.h:618
shouldPrintOption
static bool shouldPrintOption(StringRef Name, StringRef Description, const Option &O)
Definition: CommandLine.cpp:2032
llvm::sys::path::filename
StringRef filename(StringRef path, Style style=Style::native)
Get filename.
Definition: Path.cpp:577
llvm::ErrorOr::get
reference get()
Definition: ErrorOr.h:150
llvm::cl::OptionValue< std::string >
Definition: CommandLine.h:638
llvm::raw_ostream::indent
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
Definition: raw_ostream.cpp:494
llvm::cl::Option::getNumOccurrencesFlag
enum NumOccurrencesFlag getNumOccurrencesFlag() const
Definition: CommandLine.h:288
exit
declare void exit(i32) noreturn nounwind This compiles into
Definition: README.txt:1072
llvm::ErrorOr
Represents either an error or a value T.
Definition: ErrorOr.h:56
llvm::ArrayRef::size
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:164
llvm::cl::cat
Definition: CommandLine.h:459
llvm::StringSaver::save
StringRef save(const char *S)
Definition: StringSaver.h:28
llvm::sys::getHostCPUName
StringRef getHostCPUName()
getHostCPUName - Get the LLVM name for the host CPU.
Definition: Host.cpp:1526
llvm::cl::generic_parser_base::getOptionWidth
virtual size_t getOptionWidth(const Option &O) const
Definition: CommandLine.cpp:2039
llvm::iterator_range
A range adaptor for a pair of iterators.
Definition: iterator_range.h:30
llvm::cl::TopLevelSubCommand
ManagedStatic< SubCommand > TopLevelSubCommand
Definition: CommandLine.cpp:489
llvm::SmallVectorImpl< const char * >
EmptyOption
static StringRef EmptyOption
Definition: CommandLine.cpp:2026
isPrefixedOrGrouping
static bool isPrefixedOrGrouping(const Option *O)
Definition: CommandLine.cpp:127
llvm::SmallPtrSetImpl
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
Definition: SmallPtrSet.h:344
llvm::StringRef::find
size_t find(char C, size_t From=0) const
Search for the first character C in the string.
Definition: StringRef.h:281
llvm::cl::Option::addCategory
void addCategory(OptionCategory &C)
Definition: CommandLine.cpp:462
ExpandResponseFile
static llvm::Error ExpandResponseFile(StringRef FName, StringSaver &Saver, TokenizerCallback Tokenizer, SmallVectorImpl< const char * > &NewArgv, bool MarkEOLs, bool RelativeNames, bool ExpandBasePath, llvm::vfs::FileSystem &FS)
Definition: CommandLine.cpp:1156
llvm::StringRef::edit_distance
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:92
ExpandBasePaths
static void ExpandBasePaths(StringRef BasePath, StringSaver &Saver, const char *&Arg)
Definition: CommandLine.cpp:1124
StringMap.h
llvm::cl::desc
Definition: CommandLine.h:412
llvm::cl::Option::isDefaultOption
bool isDefaultOption() const
Definition: CommandLine.h:312
raw_ostream.h
llvm::cl::OptionValue
Definition: CommandLine.h:528
llvm::cl::Option::removeArgument
void removeArgument()
Unregisters this option from the CommandLine system.
Definition: CommandLine.cpp:451
llvm::cl::sub
Definition: CommandLine.h:468
llvm::cl::getGeneralCategory
OptionCategory & getGeneralCategory()
Definition: CommandLine.cpp:2616
llvm::sys::path::is_relative
bool is_relative(const Twine &path, Style style=Style::native)
Is path relative?
Definition: Path.cpp:699
llvm::cl::basic_parser_impl::printOptionInfo
void printOptionInfo(const Option &O, size_t GlobalWidth) const
Definition: CommandLine.cpp:1868
llvm::StringRef::split
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition: StringRef.h:689
llvm::Value
LLVM Value Representation.
Definition: Value.h:74
Debug.h
SubNameCompare
static int SubNameCompare(const std::pair< const char *, SubCommand * > *LHS, const std::pair< const char *, SubCommand * > *RHS)
Definition: CommandLine.cpp:2206
llvm::cl::getRegisteredSubcommands
iterator_range< typename SmallPtrSet< SubCommand *, 4 >::iterator > getRegisteredSubcommands()
Use this to get all registered SubCommands from the provided parser.
Definition: CommandLine.cpp:2713
llvm::cl::SubCommand::getName
StringRef getName() const
Definition: CommandLine.h:231
PRINT_OPT_DIFF
#define PRINT_OPT_DIFF(T)
Definition: CommandLine.cpp:2144
llvm::SmallPtrSetImpl::insert
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:365
llvm::SmallVectorImpl::insert
iterator insert(iterator I, T &&Elt)
Definition: SmallVector.h:791
llvm::cl::OptionCategory
Definition: CommandLine.h:181