LLVM  15.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() : ActiveSubCommand(nullptr) {
170  registerSubCommand(&*TopLevelSubCommand);
171  registerSubCommand(&*AllSubCommands);
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 == &*AllSubCommands) {
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, &*TopLevelSubCommand, 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 == &*AllSubCommands) {
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, &*TopLevelSubCommand);
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, &*TopLevelSubCommand);
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, &*TopLevelSubCommand);
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 != &*AllSubCommands) {
380  for (auto &E : AllSubCommands->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 
412  TopLevelSubCommand->reset();
413  AllSubCommands->reset();
414  registerSubCommand(&*TopLevelSubCommand);
415  registerSubCommand(&*AllSubCommands);
416 
417  DefaultOptions.clear();
418  }
419 
420 private:
421  SubCommand *ActiveSubCommand;
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  GlobalParser->registerSubCommand(this);
496 }
497 
499  GlobalParser->unregisterSubCommand(this);
500 }
501 
503  PositionalOpts.clear();
504  SinkOpts.clear();
505  OptionsMap.clear();
506 
507  ConsumeAfterOpt = nullptr;
508 }
509 
510 SubCommand::operator bool() const {
511  return (GlobalParser->getActiveSubCommand() == this);
512 }
513 
514 //===----------------------------------------------------------------------===//
515 // Basic, shared command line option processing machinery.
516 //
517 
518 /// LookupOption - Lookup the option specified by the specified option on the
519 /// command line. If there is a value specified (after an equal sign) return
520 /// that as well. This assumes that leading dashes have already been stripped.
521 Option *CommandLineParser::LookupOption(SubCommand &Sub, StringRef &Arg,
522  StringRef &Value) {
523  // Reject all dashes.
524  if (Arg.empty())
525  return nullptr;
526  assert(&Sub != &*AllSubCommands);
527 
528  size_t EqualPos = Arg.find('=');
529 
530  // If we have an equals sign, remember the value.
531  if (EqualPos == StringRef::npos) {
532  // Look up the option.
533  return Sub.OptionsMap.lookup(Arg);
534  }
535 
536  // If the argument before the = is a valid option name and the option allows
537  // non-prefix form (ie is not AlwaysPrefix), we match. If not, signal match
538  // failure by returning nullptr.
539  auto I = Sub.OptionsMap.find(Arg.substr(0, EqualPos));
540  if (I == Sub.OptionsMap.end())
541  return nullptr;
542 
543  auto *O = I->second;
544  if (O->getFormattingFlag() == cl::AlwaysPrefix)
545  return nullptr;
546 
547  Value = Arg.substr(EqualPos + 1);
548  Arg = Arg.substr(0, EqualPos);
549  return I->second;
550 }
551 
552 SubCommand *CommandLineParser::LookupSubCommand(StringRef Name) {
553  if (Name.empty())
554  return &*TopLevelSubCommand;
555  for (auto *S : RegisteredSubCommands) {
556  if (S == &*AllSubCommands)
557  continue;
558  if (S->getName().empty())
559  continue;
560 
561  if (StringRef(S->getName()) == StringRef(Name))
562  return S;
563  }
564  return &*TopLevelSubCommand;
565 }
566 
567 /// LookupNearestOption - Lookup the closest match to the option specified by
568 /// the specified option on the command line. If there is a value specified
569 /// (after an equal sign) return that as well. This assumes that leading dashes
570 /// have already been stripped.
572  const StringMap<Option *> &OptionsMap,
573  std::string &NearestString) {
574  // Reject all dashes.
575  if (Arg.empty())
576  return nullptr;
577 
578  // Split on any equal sign.
579  std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
580  StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
581  StringRef &RHS = SplitArg.second;
582 
583  // Find the closest match.
584  Option *Best = nullptr;
585  unsigned BestDistance = 0;
586  for (StringMap<Option *>::const_iterator it = OptionsMap.begin(),
587  ie = OptionsMap.end();
588  it != ie; ++it) {
589  Option *O = it->second;
590  // Do not suggest really hidden options (not shown in any help).
591  if (O->getOptionHiddenFlag() == ReallyHidden)
592  continue;
593 
594  SmallVector<StringRef, 16> OptionNames;
595  O->getExtraOptionNames(OptionNames);
596  if (O->hasArgStr())
597  OptionNames.push_back(O->ArgStr);
598 
599  bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
600  StringRef Flag = PermitValue ? LHS : Arg;
601  for (const auto &Name : OptionNames) {
602  unsigned Distance = StringRef(Name).edit_distance(
603  Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
604  if (!Best || Distance < BestDistance) {
605  Best = O;
606  BestDistance = Distance;
607  if (RHS.empty() || !PermitValue)
608  NearestString = std::string(Name);
609  else
610  NearestString = (Twine(Name) + "=" + RHS).str();
611  }
612  }
613  }
614 
615  return Best;
616 }
617 
618 /// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence()
619 /// that does special handling of cl::CommaSeparated options.
620 static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos,
621  StringRef ArgName, StringRef Value,
622  bool MultiArg = false) {
623  // Check to see if this option accepts a comma separated list of values. If
624  // it does, we have to split up the value into multiple values.
625  if (Handler->getMiscFlags() & CommaSeparated) {
626  StringRef Val(Value);
627  StringRef::size_type Pos = Val.find(',');
628 
629  while (Pos != StringRef::npos) {
630  // Process the portion before the comma.
631  if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
632  return true;
633  // Erase the portion before the comma, AND the comma.
634  Val = Val.substr(Pos + 1);
635  // Check for another comma.
636  Pos = Val.find(',');
637  }
638 
639  Value = Val;
640  }
641 
642  return Handler->addOccurrence(pos, ArgName, Value, MultiArg);
643 }
644 
645 /// ProvideOption - For Value, this differentiates between an empty value ("")
646 /// and a null value (StringRef()). The later is accepted for arguments that
647 /// don't allow a value (-foo) the former is rejected (-foo=).
648 static inline bool ProvideOption(Option *Handler, StringRef ArgName,
649  StringRef Value, int argc,
650  const char *const *argv, int &i) {
651  // Is this a multi-argument option?
652  unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
653 
654  // Enforce value requirements
655  switch (Handler->getValueExpectedFlag()) {
656  case ValueRequired:
657  if (!Value.data()) { // No value specified?
658  // If no other argument or the option only supports prefix form, we
659  // cannot look at the next argument.
660  if (i + 1 >= argc || Handler->getFormattingFlag() == cl::AlwaysPrefix)
661  return Handler->error("requires a value!");
662  // Steal the next argument, like for '-o filename'
663  assert(argv && "null check");
664  Value = StringRef(argv[++i]);
665  }
666  break;
667  case ValueDisallowed:
668  if (NumAdditionalVals > 0)
669  return Handler->error("multi-valued option specified"
670  " with ValueDisallowed modifier!");
671 
672  if (Value.data())
673  return Handler->error("does not allow a value! '" + Twine(Value) +
674  "' specified.");
675  break;
676  case ValueOptional:
677  break;
678  }
679 
680  // If this isn't a multi-arg option, just run the handler.
681  if (NumAdditionalVals == 0)
682  return CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value);
683 
684  // If it is, run the handle several times.
685  bool MultiArg = false;
686 
687  if (Value.data()) {
688  if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
689  return true;
690  --NumAdditionalVals;
691  MultiArg = true;
692  }
693 
694  while (NumAdditionalVals > 0) {
695  if (i + 1 >= argc)
696  return Handler->error("not enough values!");
697  assert(argv && "null check");
698  Value = StringRef(argv[++i]);
699 
700  if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
701  return true;
702  MultiArg = true;
703  --NumAdditionalVals;
704  }
705  return false;
706 }
707 
709  int Dummy = i;
710  return ProvideOption(Handler, Handler->ArgStr, Arg, 0, nullptr, Dummy);
711 }
712 
713 // getOptionPred - Check to see if there are any options that satisfy the
714 // specified predicate with names that are the prefixes in Name. This is
715 // checked by progressively stripping characters off of the name, checking to
716 // see if there options that satisfy the predicate. If we find one, return it,
717 // otherwise return null.
718 //
719 static Option *getOptionPred(StringRef Name, size_t &Length,
720  bool (*Pred)(const Option *),
721  const StringMap<Option *> &OptionsMap) {
723  if (OMI != OptionsMap.end() && !Pred(OMI->getValue()))
724  OMI = OptionsMap.end();
725 
726  // Loop while we haven't found an option and Name still has at least two
727  // characters in it (so that the next iteration will not be the empty
728  // string.
729  while (OMI == OptionsMap.end() && Name.size() > 1) {
730  Name = Name.substr(0, Name.size() - 1); // Chop off the last character.
731  OMI = OptionsMap.find(Name);
732  if (OMI != OptionsMap.end() && !Pred(OMI->getValue()))
733  OMI = OptionsMap.end();
734  }
735 
736  if (OMI != OptionsMap.end() && Pred(OMI->second)) {
737  Length = Name.size();
738  return OMI->second; // Found one!
739  }
740  return nullptr; // No option found!
741 }
742 
743 /// HandlePrefixedOrGroupedOption - The specified argument string (which started
744 /// with at least one '-') does not fully match an available option. Check to
745 /// see if this is a prefix or grouped option. If so, split arg into output an
746 /// Arg/Value pair and return the Option to parse it with.
747 static Option *
749  bool &ErrorParsing,
750  const StringMap<Option *> &OptionsMap) {
751  if (Arg.size() == 1)
752  return nullptr;
753 
754  // Do the lookup!
755  size_t Length = 0;
756  Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
757  if (!PGOpt)
758  return nullptr;
759 
760  do {
761  StringRef MaybeValue =
762  (Length < Arg.size()) ? Arg.substr(Length) : StringRef();
763  Arg = Arg.substr(0, Length);
764  assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
765 
766  // cl::Prefix options do not preserve '=' when used separately.
767  // The behavior for them with grouped options should be the same.
768  if (MaybeValue.empty() || PGOpt->getFormattingFlag() == cl::AlwaysPrefix ||
769  (PGOpt->getFormattingFlag() == cl::Prefix && MaybeValue[0] != '=')) {
770  Value = MaybeValue;
771  return PGOpt;
772  }
773 
774  if (MaybeValue[0] == '=') {
775  Value = MaybeValue.substr(1);
776  return PGOpt;
777  }
778 
779  // This must be a grouped option.
780  assert(isGrouping(PGOpt) && "Broken getOptionPred!");
781 
782  // Grouping options inside a group can't have values.
783  if (PGOpt->getValueExpectedFlag() == cl::ValueRequired) {
784  ErrorParsing |= PGOpt->error("may not occur within a group!");
785  return nullptr;
786  }
787 
788  // Because the value for the option is not required, we don't need to pass
789  // argc/argv in.
790  int Dummy = 0;
791  ErrorParsing |= ProvideOption(PGOpt, Arg, StringRef(), 0, nullptr, Dummy);
792 
793  // Get the next grouping option.
794  Arg = MaybeValue;
795  PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
796  } while (PGOpt);
797 
798  // We could not find a grouping option in the remainder of Arg.
799  return nullptr;
800 }
801 
802 static bool RequiresValue(const Option *O) {
803  return O->getNumOccurrencesFlag() == cl::Required ||
804  O->getNumOccurrencesFlag() == cl::OneOrMore;
805 }
806 
807 static bool EatsUnboundedNumberOfValues(const Option *O) {
808  return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
809  O->getNumOccurrencesFlag() == cl::OneOrMore;
810 }
811 
812 static bool isWhitespace(char C) {
813  return C == ' ' || C == '\t' || C == '\r' || C == '\n';
814 }
815 
816 static bool isWhitespaceOrNull(char C) {
817  return isWhitespace(C) || C == '\0';
818 }
819 
820 static bool isQuote(char C) { return C == '\"' || C == '\''; }
821 
824  bool MarkEOLs) {
825  SmallString<128> Token;
826  for (size_t I = 0, E = Src.size(); I != E; ++I) {
827  // Consume runs of whitespace.
828  if (Token.empty()) {
829  while (I != E && isWhitespace(Src[I])) {
830  // Mark the end of lines in response files.
831  if (MarkEOLs && Src[I] == '\n')
832  NewArgv.push_back(nullptr);
833  ++I;
834  }
835  if (I == E)
836  break;
837  }
838 
839  char C = Src[I];
840 
841  // Backslash escapes the next character.
842  if (I + 1 < E && C == '\\') {
843  ++I; // Skip the escape.
844  Token.push_back(Src[I]);
845  continue;
846  }
847 
848  // Consume a quoted string.
849  if (isQuote(C)) {
850  ++I;
851  while (I != E && Src[I] != C) {
852  // Backslash escapes the next character.
853  if (Src[I] == '\\' && I + 1 != E)
854  ++I;
855  Token.push_back(Src[I]);
856  ++I;
857  }
858  if (I == E)
859  break;
860  continue;
861  }
862 
863  // End the token if this is whitespace.
864  if (isWhitespace(C)) {
865  if (!Token.empty())
866  NewArgv.push_back(Saver.save(Token.str()).data());
867  // Mark the end of lines in response files.
868  if (MarkEOLs && C == '\n')
869  NewArgv.push_back(nullptr);
870  Token.clear();
871  continue;
872  }
873 
874  // This is a normal character. Append it.
875  Token.push_back(C);
876  }
877 
878  // Append the last token after hitting EOF with no whitespace.
879  if (!Token.empty())
880  NewArgv.push_back(Saver.save(Token.str()).data());
881 }
882 
883 /// Backslashes are interpreted in a rather complicated way in the Windows-style
884 /// command line, because backslashes are used both to separate path and to
885 /// escape double quote. This method consumes runs of backslashes as well as the
886 /// following double quote if it's escaped.
887 ///
888 /// * If an even number of backslashes is followed by a double quote, one
889 /// backslash is output for every pair of backslashes, and the last double
890 /// quote remains unconsumed. The double quote will later be interpreted as
891 /// the start or end of a quoted string in the main loop outside of this
892 /// function.
893 ///
894 /// * If an odd number of backslashes is followed by a double quote, one
895 /// backslash is output for every pair of backslashes, and a double quote is
896 /// output for the last pair of backslash-double quote. The double quote is
897 /// consumed in this case.
898 ///
899 /// * Otherwise, backslashes are interpreted literally.
900 static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
901  size_t E = Src.size();
902  int BackslashCount = 0;
903  // Skip the backslashes.
904  do {
905  ++I;
906  ++BackslashCount;
907  } while (I != E && Src[I] == '\\');
908 
909  bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
910  if (FollowedByDoubleQuote) {
911  Token.append(BackslashCount / 2, '\\');
912  if (BackslashCount % 2 == 0)
913  return I - 1;
914  Token.push_back('"');
915  return I;
916  }
917  Token.append(BackslashCount, '\\');
918  return I - 1;
919 }
920 
921 // Windows treats whitespace, double quotes, and backslashes specially, except
922 // when parsing the first token of a full command line, in which case
923 // backslashes are not special.
924 static bool isWindowsSpecialChar(char C) {
925  return isWhitespaceOrNull(C) || C == '\\' || C == '\"';
926 }
928  return isWhitespaceOrNull(C) || C == '\"';
929 }
930 
931 // Windows tokenization implementation. The implementation is designed to be
932 // inlined and specialized for the two user entry points.
934  StringRef Src, StringSaver &Saver, function_ref<void(StringRef)> AddToken,
935  bool AlwaysCopy, function_ref<void()> MarkEOL, bool InitialCommandName) {
936  SmallString<128> Token;
937 
938  // Sometimes, this function will be handling a full command line including an
939  // executable pathname at the start. In that situation, the initial pathname
940  // needs different handling from the following arguments, because when
941  // CreateProcess or cmd.exe scans the pathname, it doesn't treat \ as
942  // escaping the quote character, whereas when libc scans the rest of the
943  // command line, it does.
944  bool CommandName = InitialCommandName;
945 
946  // Try to do as much work inside the state machine as possible.
947  enum { INIT, UNQUOTED, QUOTED } State = INIT;
948 
949  for (size_t I = 0, E = Src.size(); I < E; ++I) {
950  switch (State) {
951  case INIT: {
952  assert(Token.empty() && "token should be empty in initial state");
953  // Eat whitespace before a token.
954  while (I < E && isWhitespaceOrNull(Src[I])) {
955  if (Src[I] == '\n')
956  MarkEOL();
957  ++I;
958  }
959  // Stop if this was trailing whitespace.
960  if (I >= E)
961  break;
962  size_t Start = I;
963  if (CommandName) {
964  while (I < E && !isWindowsSpecialCharInCommandName(Src[I]))
965  ++I;
966  } else {
967  while (I < E && !isWindowsSpecialChar(Src[I]))
968  ++I;
969  }
970  StringRef NormalChars = Src.slice(Start, I);
971  if (I >= E || isWhitespaceOrNull(Src[I])) {
972  // No special characters: slice out the substring and start the next
973  // token. Copy the string if the caller asks us to.
974  AddToken(AlwaysCopy ? Saver.save(NormalChars) : NormalChars);
975  if (I < E && Src[I] == '\n') {
976  MarkEOL();
977  CommandName = InitialCommandName;
978  } else {
979  CommandName = false;
980  }
981  } else if (Src[I] == '\"') {
982  Token += NormalChars;
983  State = QUOTED;
984  } else if (Src[I] == '\\') {
985  assert(!CommandName && "or else we'd have treated it as a normal char");
986  Token += NormalChars;
987  I = parseBackslash(Src, I, Token);
988  State = UNQUOTED;
989  } else {
990  llvm_unreachable("unexpected special character");
991  }
992  break;
993  }
994 
995  case UNQUOTED:
996  if (isWhitespaceOrNull(Src[I])) {
997  // Whitespace means the end of the token. If we are in this state, the
998  // token must have contained a special character, so we must copy the
999  // token.
1000  AddToken(Saver.save(Token.str()));
1001  Token.clear();
1002  if (Src[I] == '\n') {
1003  CommandName = InitialCommandName;
1004  MarkEOL();
1005  } else {
1006  CommandName = false;
1007  }
1008  State = INIT;
1009  } else if (Src[I] == '\"') {
1010  State = QUOTED;
1011  } else if (Src[I] == '\\' && !CommandName) {
1012  I = parseBackslash(Src, I, Token);
1013  } else {
1014  Token.push_back(Src[I]);
1015  }
1016  break;
1017 
1018  case QUOTED:
1019  if (Src[I] == '\"') {
1020  if (I < (E - 1) && Src[I + 1] == '"') {
1021  // Consecutive double-quotes inside a quoted string implies one
1022  // double-quote.
1023  Token.push_back('"');
1024  ++I;
1025  } else {
1026  // Otherwise, end the quoted portion and return to the unquoted state.
1027  State = UNQUOTED;
1028  }
1029  } else if (Src[I] == '\\' && !CommandName) {
1030  I = parseBackslash(Src, I, Token);
1031  } else {
1032  Token.push_back(Src[I]);
1033  }
1034  break;
1035  }
1036  }
1037 
1038  if (State != INIT)
1039  AddToken(Saver.save(Token.str()));
1040 }
1041 
1044  bool MarkEOLs) {
1045  auto AddToken = [&](StringRef Tok) { NewArgv.push_back(Tok.data()); };
1046  auto OnEOL = [&]() {
1047  if (MarkEOLs)
1048  NewArgv.push_back(nullptr);
1049  };
1050  tokenizeWindowsCommandLineImpl(Src, Saver, AddToken,
1051  /*AlwaysCopy=*/true, OnEOL, false);
1052 }
1053 
1055  SmallVectorImpl<StringRef> &NewArgv) {
1056  auto AddToken = [&](StringRef Tok) { NewArgv.push_back(Tok); };
1057  auto OnEOL = []() {};
1058  tokenizeWindowsCommandLineImpl(Src, Saver, AddToken, /*AlwaysCopy=*/false,
1059  OnEOL, false);
1060 }
1061 
1064  bool MarkEOLs) {
1065  auto AddToken = [&](StringRef Tok) { NewArgv.push_back(Tok.data()); };
1066  auto OnEOL = [&]() {
1067  if (MarkEOLs)
1068  NewArgv.push_back(nullptr);
1069  };
1070  tokenizeWindowsCommandLineImpl(Src, Saver, AddToken,
1071  /*AlwaysCopy=*/true, OnEOL, true);
1072 }
1073 
1076  bool MarkEOLs) {
1077  for (const char *Cur = Source.begin(); Cur != Source.end();) {
1078  SmallString<128> Line;
1079  // Check for comment line.
1080  if (isWhitespace(*Cur)) {
1081  while (Cur != Source.end() && isWhitespace(*Cur))
1082  ++Cur;
1083  continue;
1084  }
1085  if (*Cur == '#') {
1086  while (Cur != Source.end() && *Cur != '\n')
1087  ++Cur;
1088  continue;
1089  }
1090  // Find end of the current line.
1091  const char *Start = Cur;
1092  for (const char *End = Source.end(); Cur != End; ++Cur) {
1093  if (*Cur == '\\') {
1094  if (Cur + 1 != End) {
1095  ++Cur;
1096  if (*Cur == '\n' ||
1097  (*Cur == '\r' && (Cur + 1 != End) && Cur[1] == '\n')) {
1098  Line.append(Start, Cur - 1);
1099  if (*Cur == '\r')
1100  ++Cur;
1101  Start = Cur + 1;
1102  }
1103  }
1104  } else if (*Cur == '\n')
1105  break;
1106  }
1107  // Tokenize line.
1108  Line.append(Start, Cur);
1109  cl::TokenizeGNUCommandLine(Line, Saver, NewArgv, MarkEOLs);
1110  }
1111 }
1112 
1113 // It is called byte order marker but the UTF-8 BOM is actually not affected
1114 // by the host system's endianness.
1116  return (S.size() >= 3 && S[0] == '\xef' && S[1] == '\xbb' && S[2] == '\xbf');
1117 }
1118 
1119 // Substitute <CFGDIR> with the file's base path.
1120 static void ExpandBasePaths(StringRef BasePath, StringSaver &Saver,
1121  const char *&Arg) {
1122  assert(sys::path::is_absolute(BasePath));
1123  constexpr StringLiteral Token("<CFGDIR>");
1124  const StringRef ArgString(Arg);
1125 
1126  SmallString<128> ResponseFile;
1127  StringRef::size_type StartPos = 0;
1128  for (StringRef::size_type TokenPos = ArgString.find(Token);
1129  TokenPos != StringRef::npos;
1130  TokenPos = ArgString.find(Token, StartPos)) {
1131  // Token may appear more than once per arg (e.g. comma-separated linker
1132  // args). Support by using path-append on any subsequent appearances.
1133  const StringRef LHS = ArgString.substr(StartPos, TokenPos - StartPos);
1134  if (ResponseFile.empty())
1135  ResponseFile = LHS;
1136  else
1137  llvm::sys::path::append(ResponseFile, LHS);
1138  ResponseFile.append(BasePath);
1139  StartPos = TokenPos + Token.size();
1140  }
1141 
1142  if (!ResponseFile.empty()) {
1143  // Path-append the remaining arg substring if at least one token appeared.
1144  const StringRef Remaining = ArgString.substr(StartPos);
1145  if (!Remaining.empty())
1146  llvm::sys::path::append(ResponseFile, Remaining);
1147  Arg = Saver.save(ResponseFile.str()).data();
1148  }
1149 }
1150 
1151 // FName must be an absolute path.
1153  TokenizerCallback Tokenizer,
1155  bool MarkEOLs, bool RelativeNames,
1156  bool ExpandBasePath,
1160  FS.getBufferForFile(FName);
1161  if (!MemBufOrErr)
1162  return llvm::errorCodeToError(MemBufOrErr.getError());
1163  MemoryBuffer &MemBuf = *MemBufOrErr.get();
1164  StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize());
1165 
1166  // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
1167  ArrayRef<char> BufRef(MemBuf.getBufferStart(), MemBuf.getBufferEnd());
1168  std::string UTF8Buf;
1169  if (hasUTF16ByteOrderMark(BufRef)) {
1170  if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
1171  return llvm::createStringError(std::errc::illegal_byte_sequence,
1172  "Could not convert UTF16 to UTF8");
1173  Str = StringRef(UTF8Buf);
1174  }
1175  // If we see UTF-8 BOM sequence at the beginning of a file, we shall remove
1176  // these bytes before parsing.
1177  // Reference: http://en.wikipedia.org/wiki/UTF-8#Byte_order_mark
1178  else if (hasUTF8ByteOrderMark(BufRef))
1179  Str = StringRef(BufRef.data() + 3, BufRef.size() - 3);
1180 
1181  // Tokenize the contents into NewArgv.
1182  Tokenizer(Str, Saver, NewArgv, MarkEOLs);
1183 
1184  if (!RelativeNames)
1185  return Error::success();
1187  // If names of nested response files should be resolved relative to including
1188  // file, replace the included response file names with their full paths
1189  // obtained by required resolution.
1190  for (auto &Arg : NewArgv) {
1191  if (!Arg)
1192  continue;
1193 
1194  // Substitute <CFGDIR> with the file's base path.
1195  if (ExpandBasePath)
1196  ExpandBasePaths(BasePath, Saver, Arg);
1197 
1198  // Skip non-rsp file arguments.
1199  if (Arg[0] != '@')
1200  continue;
1201 
1202  StringRef FileName(Arg + 1);
1203  // Skip if non-relative.
1204  if (!llvm::sys::path::is_relative(FileName))
1205  continue;
1206 
1207  SmallString<128> ResponseFile;
1208  ResponseFile.push_back('@');
1209  ResponseFile.append(BasePath);
1210  llvm::sys::path::append(ResponseFile, FileName);
1211  Arg = Saver.save(ResponseFile.str()).data();
1212  }
1213  return Error::success();
1214 }
1215 
1216 /// Expand response files on a command line recursively using the given
1217 /// StringSaver and tokenization strategy.
1219  SmallVectorImpl<const char *> &Argv, bool MarkEOLs,
1220  bool RelativeNames, bool ExpandBasePath,
1223  bool AllExpanded = true;
1224  struct ResponseFileRecord {
1225  std::string File;
1226  size_t End;
1227  };
1228 
1229  // To detect recursive response files, we maintain a stack of files and the
1230  // position of the last argument in the file. This position is updated
1231  // dynamically as we recursively expand files.
1233 
1234  // Push a dummy entry that represents the initial command line, removing
1235  // the need to check for an empty list.
1236  FileStack.push_back({"", Argv.size()});
1237 
1238  // Don't cache Argv.size() because it can change.
1239  for (unsigned I = 0; I != Argv.size();) {
1240  while (I == FileStack.back().End) {
1241  // Passing the end of a file's argument list, so we can remove it from the
1242  // stack.
1243  FileStack.pop_back();
1244  }
1245 
1246  const char *Arg = Argv[I];
1247  // Check if it is an EOL marker
1248  if (Arg == nullptr) {
1249  ++I;
1250  continue;
1251  }
1252 
1253  if (Arg[0] != '@') {
1254  ++I;
1255  continue;
1256  }
1257 
1258  const char *FName = Arg + 1;
1259  // Note that CurrentDir is only used for top-level rsp files, the rest will
1260  // always have an absolute path deduced from the containing file.
1261  SmallString<128> CurrDir;
1262  if (llvm::sys::path::is_relative(FName)) {
1263  if (!CurrentDir)
1264  llvm::sys::fs::current_path(CurrDir);
1265  else
1266  CurrDir = *CurrentDir;
1267  llvm::sys::path::append(CurrDir, FName);
1268  FName = CurrDir.c_str();
1269  }
1270  auto IsEquivalent = [FName, &FS](const ResponseFileRecord &RFile) {
1271  llvm::ErrorOr<llvm::vfs::Status> LHS = FS.status(FName);
1272  if (!LHS) {
1273  // TODO: The error should be propagated up the stack.
1275  return false;
1276  }
1277  llvm::ErrorOr<llvm::vfs::Status> RHS = FS.status(RFile.File);
1278  if (!RHS) {
1279  // TODO: The error should be propagated up the stack.
1281  return false;
1282  }
1283  return LHS->equivalent(*RHS);
1284  };
1285 
1286  // Check for recursive response files.
1287  if (any_of(drop_begin(FileStack), IsEquivalent)) {
1288  // This file is recursive, so we leave it in the argument stream and
1289  // move on.
1290  AllExpanded = false;
1291  ++I;
1292  continue;
1293  }
1294 
1295  // Replace this response file argument with the tokenization of its
1296  // contents. Nested response files are expanded in subsequent iterations.
1297  SmallVector<const char *, 0> ExpandedArgv;
1298  if (llvm::Error Err =
1299  ExpandResponseFile(FName, Saver, Tokenizer, ExpandedArgv, MarkEOLs,
1300  RelativeNames, ExpandBasePath, FS)) {
1301  // We couldn't read this file, so we leave it in the argument stream and
1302  // move on.
1303  // TODO: The error should be propagated up the stack.
1305  AllExpanded = false;
1306  ++I;
1307  continue;
1308  }
1309 
1310  for (ResponseFileRecord &Record : FileStack) {
1311  // Increase the end of all active records by the number of newly expanded
1312  // arguments, minus the response file itself.
1313  Record.End += ExpandedArgv.size() - 1;
1314  }
1315 
1316  FileStack.push_back({FName, I + ExpandedArgv.size()});
1317  Argv.erase(Argv.begin() + I);
1318  Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
1319  }
1320 
1321  // If successful, the top of the file stack will mark the end of the Argv
1322  // stream. A failure here indicates a bug in the stack popping logic above.
1323  // Note that FileStack may have more than one element at this point because we
1324  // don't have a chance to pop the stack when encountering recursive files at
1325  // the end of the stream, so seeing that doesn't indicate a bug.
1326  assert(FileStack.size() > 0 && Argv.size() == FileStack.back().End);
1327  return AllExpanded;
1328 }
1329 
1331  SmallVectorImpl<const char *> &Argv, bool MarkEOLs,
1332  bool RelativeNames, bool ExpandBasePath,
1333  llvm::Optional<StringRef> CurrentDir) {
1334  return ExpandResponseFiles(Saver, std::move(Tokenizer), Argv, MarkEOLs,
1335  RelativeNames, ExpandBasePath,
1336  std::move(CurrentDir), *vfs::getRealFileSystem());
1337 }
1338 
1339 bool cl::expandResponseFiles(int Argc, const char *const *Argv,
1340  const char *EnvVar, StringSaver &Saver,
1341  SmallVectorImpl<const char *> &NewArgv) {
1342  auto Tokenize = Triple(sys::getProcessTriple()).isOSWindows()
1345  // The environment variable specifies initial options.
1346  if (EnvVar)
1347  if (llvm::Optional<std::string> EnvValue = sys::Process::GetEnv(EnvVar))
1348  Tokenize(*EnvValue, Saver, NewArgv, /*MarkEOLs=*/false);
1349 
1350  // Command line options can override the environment variable.
1351  NewArgv.append(Argv + 1, Argv + Argc);
1352  return ExpandResponseFiles(Saver, Tokenize, NewArgv);
1353 }
1354 
1357  SmallString<128> AbsPath;
1358  if (sys::path::is_relative(CfgFile)) {
1359  llvm::sys::fs::current_path(AbsPath);
1360  llvm::sys::path::append(AbsPath, CfgFile);
1361  CfgFile = AbsPath.str();
1362  }
1363  if (llvm::Error Err = ExpandResponseFile(
1364  CfgFile, Saver, cl::tokenizeConfigFile, Argv,
1365  /*MarkEOLs=*/false, /*RelativeNames=*/true, /*ExpandBasePath=*/true,
1367  // TODO: The error should be propagated up the stack.
1369  return false;
1370  }
1371  return ExpandResponseFiles(Saver, cl::tokenizeConfigFile, Argv,
1372  /*MarkEOLs=*/false, /*RelativeNames=*/true,
1373  /*ExpandBasePath=*/true, llvm::None);
1374 }
1375 
1376 static void initCommonOptions();
1377 bool cl::ParseCommandLineOptions(int argc, const char *const *argv,
1378  StringRef Overview, raw_ostream *Errs,
1379  const char *EnvVar,
1380  bool LongOptionsUseDoubleDash) {
1383  BumpPtrAllocator A;
1384  StringSaver Saver(A);
1385  NewArgv.push_back(argv[0]);
1386 
1387  // Parse options from environment variable.
1388  if (EnvVar) {
1389  if (llvm::Optional<std::string> EnvValue =
1391  TokenizeGNUCommandLine(*EnvValue, Saver, NewArgv);
1392  }
1393 
1394  // Append options from command line.
1395  for (int I = 1; I < argc; ++I)
1396  NewArgv.push_back(argv[I]);
1397  int NewArgc = static_cast<int>(NewArgv.size());
1398 
1399  // Parse all options.
1400  return GlobalParser->ParseCommandLineOptions(NewArgc, &NewArgv[0], Overview,
1401  Errs, LongOptionsUseDoubleDash);
1402 }
1403 
1404 /// Reset all options at least once, so that we can parse different options.
1406  // Reset all option values to look like they have never been seen before.
1407  // Options might be reset twice (they can be reference in both OptionsMap
1408  // and one of the other members), but that does not harm.
1409  for (auto *SC : RegisteredSubCommands) {
1410  for (auto &O : SC->OptionsMap)
1411  O.second->reset();
1412  for (Option *O : SC->PositionalOpts)
1413  O->reset();
1414  for (Option *O : SC->SinkOpts)
1415  O->reset();
1416  if (SC->ConsumeAfterOpt)
1417  SC->ConsumeAfterOpt->reset();
1418  }
1419 }
1420 
1422  const char *const *argv,
1423  StringRef Overview,
1424  raw_ostream *Errs,
1425  bool LongOptionsUseDoubleDash) {
1426  assert(hasOptions() && "No options specified!");
1427 
1428  // Expand response files.
1429  SmallVector<const char *, 20> newArgv(argv, argv + argc);
1430  BumpPtrAllocator A;
1431  StringSaver Saver(A);
1432  ExpandResponseFiles(Saver,
1433  Triple(sys::getProcessTriple()).isOSWindows() ?
1435  newArgv);
1436  argv = &newArgv[0];
1437  argc = static_cast<int>(newArgv.size());
1438 
1439  // Copy the program name into ProgName, making sure not to overflow it.
1440  ProgramName = std::string(sys::path::filename(StringRef(argv[0])));
1441 
1442  ProgramOverview = Overview;
1443  bool IgnoreErrors = Errs;
1444  if (!Errs)
1445  Errs = &errs();
1446  bool ErrorParsing = false;
1447 
1448  // Check out the positional arguments to collect information about them.
1449  unsigned NumPositionalRequired = 0;
1450 
1451  // Determine whether or not there are an unlimited number of positionals
1452  bool HasUnlimitedPositionals = false;
1453 
1454  int FirstArg = 1;
1455  SubCommand *ChosenSubCommand = &*TopLevelSubCommand;
1456  if (argc >= 2 && argv[FirstArg][0] != '-') {
1457  // If the first argument specifies a valid subcommand, start processing
1458  // options from the second argument.
1459  ChosenSubCommand = LookupSubCommand(StringRef(argv[FirstArg]));
1460  if (ChosenSubCommand != &*TopLevelSubCommand)
1461  FirstArg = 2;
1462  }
1463  GlobalParser->ActiveSubCommand = ChosenSubCommand;
1464 
1465  assert(ChosenSubCommand);
1466  auto &ConsumeAfterOpt = ChosenSubCommand->ConsumeAfterOpt;
1467  auto &PositionalOpts = ChosenSubCommand->PositionalOpts;
1468  auto &SinkOpts = ChosenSubCommand->SinkOpts;
1469  auto &OptionsMap = ChosenSubCommand->OptionsMap;
1470 
1471  for (auto *O: DefaultOptions) {
1472  addOption(O, true);
1473  }
1474 
1475  if (ConsumeAfterOpt) {
1476  assert(PositionalOpts.size() > 0 &&
1477  "Cannot specify cl::ConsumeAfter without a positional argument!");
1478  }
1479  if (!PositionalOpts.empty()) {
1480 
1481  // Calculate how many positional values are _required_.
1482  bool UnboundedFound = false;
1483  for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
1484  Option *Opt = PositionalOpts[i];
1485  if (RequiresValue(Opt))
1486  ++NumPositionalRequired;
1487  else if (ConsumeAfterOpt) {
1488  // ConsumeAfter cannot be combined with "optional" positional options
1489  // unless there is only one positional argument...
1490  if (PositionalOpts.size() > 1) {
1491  if (!IgnoreErrors)
1492  Opt->error("error - this positional option will never be matched, "
1493  "because it does not Require a value, and a "
1494  "cl::ConsumeAfter option is active!");
1495  ErrorParsing = true;
1496  }
1497  } else if (UnboundedFound && !Opt->hasArgStr()) {
1498  // This option does not "require" a value... Make sure this option is
1499  // not specified after an option that eats all extra arguments, or this
1500  // one will never get any!
1501  //
1502  if (!IgnoreErrors)
1503  Opt->error("error - option can never match, because "
1504  "another positional argument will match an "
1505  "unbounded number of values, and this option"
1506  " does not require a value!");
1507  *Errs << ProgramName << ": CommandLine Error: Option '" << Opt->ArgStr
1508  << "' is all messed up!\n";
1509  *Errs << PositionalOpts.size();
1510  ErrorParsing = true;
1511  }
1512  UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
1513  }
1514  HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
1515  }
1516 
1517  // PositionalVals - A vector of "positional" arguments we accumulate into
1518  // the process at the end.
1519  //
1520  SmallVector<std::pair<StringRef, unsigned>, 4> PositionalVals;
1521 
1522  // If the program has named positional arguments, and the name has been run
1523  // across, keep track of which positional argument was named. Otherwise put
1524  // the positional args into the PositionalVals list...
1525  Option *ActivePositionalArg = nullptr;
1526 
1527  // Loop over all of the arguments... processing them.
1528  bool DashDashFound = false; // Have we read '--'?
1529  for (int i = FirstArg; i < argc; ++i) {
1530  Option *Handler = nullptr;
1531  Option *NearestHandler = nullptr;
1532  std::string NearestHandlerString;
1533  StringRef Value;
1534  StringRef ArgName = "";
1535  bool HaveDoubleDash = false;
1536 
1537  // Check to see if this is a positional argument. This argument is
1538  // considered to be positional if it doesn't start with '-', if it is "-"
1539  // itself, or if we have seen "--" already.
1540  //
1541  if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
1542  // Positional argument!
1543  if (ActivePositionalArg) {
1544  ProvidePositionalOption(ActivePositionalArg, StringRef(argv[i]), i);
1545  continue; // We are done!
1546  }
1547 
1548  if (!PositionalOpts.empty()) {
1549  PositionalVals.push_back(std::make_pair(StringRef(argv[i]), i));
1550 
1551  // All of the positional arguments have been fulfulled, give the rest to
1552  // the consume after option... if it's specified...
1553  //
1554  if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) {
1555  for (++i; i < argc; ++i)
1556  PositionalVals.push_back(std::make_pair(StringRef(argv[i]), i));
1557  break; // Handle outside of the argument processing loop...
1558  }
1559 
1560  // Delay processing positional arguments until the end...
1561  continue;
1562  }
1563  } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
1564  !DashDashFound) {
1565  DashDashFound = true; // This is the mythical "--"?
1566  continue; // Don't try to process it as an argument itself.
1567  } else if (ActivePositionalArg &&
1568  (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
1569  // If there is a positional argument eating options, check to see if this
1570  // option is another positional argument. If so, treat it as an argument,
1571  // otherwise feed it to the eating positional.
1572  ArgName = StringRef(argv[i] + 1);
1573  // Eat second dash.
1574  if (!ArgName.empty() && ArgName[0] == '-') {
1575  HaveDoubleDash = true;
1576  ArgName = ArgName.substr(1);
1577  }
1578 
1579  Handler = LookupLongOption(*ChosenSubCommand, ArgName, Value,
1580  LongOptionsUseDoubleDash, HaveDoubleDash);
1581  if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
1582  ProvidePositionalOption(ActivePositionalArg, StringRef(argv[i]), i);
1583  continue; // We are done!
1584  }
1585  } else { // We start with a '-', must be an argument.
1586  ArgName = StringRef(argv[i] + 1);
1587  // Eat second dash.
1588  if (!ArgName.empty() && ArgName[0] == '-') {
1589  HaveDoubleDash = true;
1590  ArgName = ArgName.substr(1);
1591  }
1592 
1593  Handler = LookupLongOption(*ChosenSubCommand, ArgName, Value,
1594  LongOptionsUseDoubleDash, HaveDoubleDash);
1595 
1596  // Check to see if this "option" is really a prefixed or grouped argument.
1597  if (!Handler && !(LongOptionsUseDoubleDash && HaveDoubleDash))
1598  Handler = HandlePrefixedOrGroupedOption(ArgName, Value, ErrorParsing,
1599  OptionsMap);
1600 
1601  // Otherwise, look for the closest available option to report to the user
1602  // in the upcoming error.
1603  if (!Handler && SinkOpts.empty())
1604  NearestHandler =
1605  LookupNearestOption(ArgName, OptionsMap, NearestHandlerString);
1606  }
1607 
1608  if (!Handler) {
1609  if (SinkOpts.empty()) {
1610  *Errs << ProgramName << ": Unknown command line argument '" << argv[i]
1611  << "'. Try: '" << argv[0] << " --help'\n";
1612 
1613  if (NearestHandler) {
1614  // If we know a near match, report it as well.
1615  *Errs << ProgramName << ": Did you mean '"
1616  << PrintArg(NearestHandlerString, 0) << "'?\n";
1617  }
1618 
1619  ErrorParsing = true;
1620  } else {
1621  for (Option *SinkOpt : SinkOpts)
1622  SinkOpt->addOccurrence(i, "", StringRef(argv[i]));
1623  }
1624  continue;
1625  }
1626 
1627  // If this is a named positional argument, just remember that it is the
1628  // active one...
1629  if (Handler->getFormattingFlag() == cl::Positional) {
1630  if ((Handler->getMiscFlags() & PositionalEatsArgs) && !Value.empty()) {
1631  Handler->error("This argument does not take a value.\n"
1632  "\tInstead, it consumes any positional arguments until "
1633  "the next recognized option.", *Errs);
1634  ErrorParsing = true;
1635  }
1636  ActivePositionalArg = Handler;
1637  }
1638  else
1639  ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
1640  }
1641 
1642  // Check and handle positional arguments now...
1643  if (NumPositionalRequired > PositionalVals.size()) {
1644  *Errs << ProgramName
1645  << ": Not enough positional command line arguments specified!\n"
1646  << "Must specify at least " << NumPositionalRequired
1647  << " positional argument" << (NumPositionalRequired > 1 ? "s" : "")
1648  << ": See: " << argv[0] << " --help\n";
1649 
1650  ErrorParsing = true;
1651  } else if (!HasUnlimitedPositionals &&
1652  PositionalVals.size() > PositionalOpts.size()) {
1653  *Errs << ProgramName << ": Too many positional arguments specified!\n"
1654  << "Can specify at most " << PositionalOpts.size()
1655  << " positional arguments: See: " << argv[0] << " --help\n";
1656  ErrorParsing = true;
1657 
1658  } else if (!ConsumeAfterOpt) {
1659  // Positional args have already been handled if ConsumeAfter is specified.
1660  unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
1661  for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
1662  if (RequiresValue(PositionalOpts[i])) {
1663  ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
1664  PositionalVals[ValNo].second);
1665  ValNo++;
1666  --NumPositionalRequired; // We fulfilled our duty...
1667  }
1668 
1669  // If we _can_ give this option more arguments, do so now, as long as we
1670  // do not give it values that others need. 'Done' controls whether the
1671  // option even _WANTS_ any more.
1672  //
1673  bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
1674  while (NumVals - ValNo > NumPositionalRequired && !Done) {
1675  switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
1676  case cl::Optional:
1677  Done = true; // Optional arguments want _at most_ one value
1679  case cl::ZeroOrMore: // Zero or more will take all they can get...
1680  case cl::OneOrMore: // One or more will take all they can get...
1681  ProvidePositionalOption(PositionalOpts[i],
1682  PositionalVals[ValNo].first,
1683  PositionalVals[ValNo].second);
1684  ValNo++;
1685  break;
1686  default:
1687  llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
1688  "positional argument processing!");
1689  }
1690  }
1691  }
1692  } else {
1693  assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
1694  unsigned ValNo = 0;
1695  for (size_t J = 0, E = PositionalOpts.size(); J != E; ++J)
1696  if (RequiresValue(PositionalOpts[J])) {
1697  ErrorParsing |= ProvidePositionalOption(PositionalOpts[J],
1698  PositionalVals[ValNo].first,
1699  PositionalVals[ValNo].second);
1700  ValNo++;
1701  }
1702 
1703  // Handle the case where there is just one positional option, and it's
1704  // optional. In this case, we want to give JUST THE FIRST option to the
1705  // positional option and keep the rest for the consume after. The above
1706  // loop would have assigned no values to positional options in this case.
1707  //
1708  if (PositionalOpts.size() == 1 && ValNo == 0 && !PositionalVals.empty()) {
1709  ErrorParsing |= ProvidePositionalOption(PositionalOpts[0],
1710  PositionalVals[ValNo].first,
1711  PositionalVals[ValNo].second);
1712  ValNo++;
1713  }
1714 
1715  // Handle over all of the rest of the arguments to the
1716  // cl::ConsumeAfter command line option...
1717  for (; ValNo != PositionalVals.size(); ++ValNo)
1718  ErrorParsing |=
1719  ProvidePositionalOption(ConsumeAfterOpt, PositionalVals[ValNo].first,
1720  PositionalVals[ValNo].second);
1721  }
1722 
1723  // Loop over args and make sure all required args are specified!
1724  for (const auto &Opt : OptionsMap) {
1725  switch (Opt.second->getNumOccurrencesFlag()) {
1726  case Required:
1727  case OneOrMore:
1728  if (Opt.second->getNumOccurrences() == 0) {
1729  Opt.second->error("must be specified at least once!");
1730  ErrorParsing = true;
1731  }
1733  default:
1734  break;
1735  }
1736  }
1737 
1738  // Now that we know if -debug is specified, we can use it.
1739  // Note that if ReadResponseFiles == true, this must be done before the
1740  // memory allocated for the expanded command line is free()d below.
1741  LLVM_DEBUG(dbgs() << "Args: ";
1742  for (int i = 0; i < argc; ++i) dbgs() << argv[i] << ' ';
1743  dbgs() << '\n';);
1744 
1745  // Free all of the memory allocated to the map. Command line options may only
1746  // be processed once!
1747  MoreHelp.clear();
1748 
1749  // If we had an error processing our arguments, don't let the program execute
1750  if (ErrorParsing) {
1751  if (!IgnoreErrors)
1752  exit(1);
1753  return false;
1754  }
1755  return true;
1756 }
1757 
1758 //===----------------------------------------------------------------------===//
1759 // Option Base class implementation
1760 //
1761 
1762 bool Option::error(const Twine &Message, StringRef ArgName, raw_ostream &Errs) {
1763  if (!ArgName.data())
1764  ArgName = ArgStr;
1765  if (ArgName.empty())
1766  Errs << HelpStr; // Be nice for positional arguments
1767  else
1768  Errs << GlobalParser->ProgramName << ": for the " << PrintArg(ArgName, 0);
1769 
1770  Errs << " option: " << Message << "\n";
1771  return true;
1772 }
1773 
1774 bool Option::addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
1775  bool MultiArg) {
1776  if (!MultiArg)
1777  NumOccurrences++; // Increment the number of times we have been seen
1778 
1779  return handleOccurrence(pos, ArgName, Value);
1780 }
1781 
1782 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
1783 // has been specified yet.
1784 //
1785 static StringRef getValueStr(const Option &O, StringRef DefaultMsg) {
1786  if (O.ValueStr.empty())
1787  return DefaultMsg;
1788  return O.ValueStr;
1789 }
1790 
1791 //===----------------------------------------------------------------------===//
1792 // cl::alias class implementation
1793 //
1794 
1795 // Return the width of the option tag for printing...
1796 size_t alias::getOptionWidth() const {
1797  return argPlusPrefixesSize(ArgStr);
1798 }
1799 
1800 void Option::printHelpStr(StringRef HelpStr, size_t Indent,
1801  size_t FirstLineIndentedBy) {
1802  assert(Indent >= FirstLineIndentedBy);
1803  std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1804  outs().indent(Indent - FirstLineIndentedBy)
1805  << ArgHelpPrefix << Split.first << "\n";
1806  while (!Split.second.empty()) {
1807  Split = Split.second.split('\n');
1808  outs().indent(Indent) << Split.first << "\n";
1809  }
1810 }
1811 
1812 void Option::printEnumValHelpStr(StringRef HelpStr, size_t BaseIndent,
1813  size_t FirstLineIndentedBy) {
1814  const StringRef ValHelpPrefix = " ";
1815  assert(BaseIndent >= FirstLineIndentedBy);
1816  std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1817  outs().indent(BaseIndent - FirstLineIndentedBy)
1818  << ArgHelpPrefix << ValHelpPrefix << Split.first << "\n";
1819  while (!Split.second.empty()) {
1820  Split = Split.second.split('\n');
1821  outs().indent(BaseIndent + ValHelpPrefix.size()) << Split.first << "\n";
1822  }
1823 }
1824 
1825 // Print out the option for the alias.
1826 void alias::printOptionInfo(size_t GlobalWidth) const {
1827  outs() << PrintArg(ArgStr);
1829 }
1830 
1831 //===----------------------------------------------------------------------===//
1832 // Parser Implementation code...
1833 //
1834 
1835 // basic_parser implementation
1836 //
1837 
1838 // Return the width of the option tag for printing...
1840  size_t Len = argPlusPrefixesSize(O.ArgStr);
1841  auto ValName = getValueName();
1842  if (!ValName.empty()) {
1843  size_t FormattingLen = 3;
1844  if (O.getMiscFlags() & PositionalEatsArgs)
1845  FormattingLen = 6;
1846  Len += getValueStr(O, ValName).size() + FormattingLen;
1847  }
1848 
1849  return Len;
1850 }
1851 
1852 // printOptionInfo - Print out information about this option. The
1853 // to-be-maintained width is specified.
1854 //
1856  size_t GlobalWidth) const {
1857  outs() << PrintArg(O.ArgStr);
1858 
1859  auto ValName = getValueName();
1860  if (!ValName.empty()) {
1861  if (O.getMiscFlags() & PositionalEatsArgs) {
1862  outs() << " <" << getValueStr(O, ValName) << ">...";
1863  } else if (O.getValueExpectedFlag() == ValueOptional)
1864  outs() << "[=<" << getValueStr(O, ValName) << ">]";
1865  else
1866  outs() << "=<" << getValueStr(O, ValName) << '>';
1867  }
1868 
1869  Option::printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
1870 }
1871 
1873  size_t GlobalWidth) const {
1874  outs() << PrintArg(O.ArgStr);
1875  outs().indent(GlobalWidth - O.ArgStr.size());
1876 }
1877 
1878 // parser<bool> implementation
1879 //
1881  bool &Value) {
1882  if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1883  Arg == "1") {
1884  Value = true;
1885  return false;
1886  }
1887 
1888  if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1889  Value = false;
1890  return false;
1891  }
1892  return O.error("'" + Arg +
1893  "' is invalid value for boolean argument! Try 0 or 1");
1894 }
1895 
1896 // parser<boolOrDefault> implementation
1897 //
1899  boolOrDefault &Value) {
1900  if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1901  Arg == "1") {
1902  Value = BOU_TRUE;
1903  return false;
1904  }
1905  if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1906  Value = BOU_FALSE;
1907  return false;
1908  }
1909 
1910  return O.error("'" + Arg +
1911  "' is invalid value for boolean argument! Try 0 or 1");
1912 }
1913 
1914 // parser<int> implementation
1915 //
1917  int &Value) {
1918  if (Arg.getAsInteger(0, Value))
1919  return O.error("'" + Arg + "' value invalid for integer argument!");
1920  return false;
1921 }
1922 
1923 // parser<long> implementation
1924 //
1926  long &Value) {
1927  if (Arg.getAsInteger(0, Value))
1928  return O.error("'" + Arg + "' value invalid for long argument!");
1929  return false;
1930 }
1931 
1932 // parser<long long> implementation
1933 //
1935  long long &Value) {
1936  if (Arg.getAsInteger(0, Value))
1937  return O.error("'" + Arg + "' value invalid for llong argument!");
1938  return false;
1939 }
1940 
1941 // parser<unsigned> implementation
1942 //
1944  unsigned &Value) {
1945 
1946  if (Arg.getAsInteger(0, Value))
1947  return O.error("'" + Arg + "' value invalid for uint argument!");
1948  return false;
1949 }
1950 
1951 // parser<unsigned long> implementation
1952 //
1954  unsigned long &Value) {
1955 
1956  if (Arg.getAsInteger(0, Value))
1957  return O.error("'" + Arg + "' value invalid for ulong argument!");
1958  return false;
1959 }
1960 
1961 // parser<unsigned long long> implementation
1962 //
1964  StringRef Arg,
1965  unsigned long long &Value) {
1966 
1967  if (Arg.getAsInteger(0, Value))
1968  return O.error("'" + Arg + "' value invalid for ullong argument!");
1969  return false;
1970 }
1971 
1972 // parser<double>/parser<float> implementation
1973 //
1974 static bool parseDouble(Option &O, StringRef Arg, double &Value) {
1975  if (to_float(Arg, Value))
1976  return false;
1977  return O.error("'" + Arg + "' value invalid for floating point argument!");
1978 }
1979 
1981  double &Val) {
1982  return parseDouble(O, Arg, Val);
1983 }
1984 
1986  float &Val) {
1987  double dVal;
1988  if (parseDouble(O, Arg, dVal))
1989  return true;
1990  Val = (float)dVal;
1991  return false;
1992 }
1993 
1994 // generic_parser_base implementation
1995 //
1996 
1997 // findOption - Return the option number corresponding to the specified
1998 // argument string. If the option is not found, getNumOptions() is returned.
1999 //
2001  unsigned e = getNumOptions();
2002 
2003  for (unsigned i = 0; i != e; ++i) {
2004  if (getOption(i) == Name)
2005  return i;
2006  }
2007  return e;
2008 }
2009 
2010 static StringRef EqValue = "=<value>";
2011 static StringRef EmptyOption = "<empty>";
2012 static StringRef OptionPrefix = " =";
2013 static size_t getOptionPrefixesSize() {
2014  return OptionPrefix.size() + ArgHelpPrefix.size();
2015 }
2016 
2017 static bool shouldPrintOption(StringRef Name, StringRef Description,
2018  const Option &O) {
2019  return O.getValueExpectedFlag() != ValueOptional || !Name.empty() ||
2020  !Description.empty();
2021 }
2022 
2023 // Return the width of the option tag for printing...
2025  if (O.hasArgStr()) {
2026  size_t Size =
2027  argPlusPrefixesSize(O.ArgStr) + EqValue.size();
2028  for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
2031  continue;
2032  size_t NameSize = Name.empty() ? EmptyOption.size() : Name.size();
2033  Size = std::max(Size, NameSize + getOptionPrefixesSize());
2034  }
2035  return Size;
2036  } else {
2037  size_t BaseSize = 0;
2038  for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
2039  BaseSize = std::max(BaseSize, getOption(i).size() + 8);
2040  return BaseSize;
2041  }
2042 }
2043 
2044 // printOptionInfo - Print out information about this option. The
2045 // to-be-maintained width is specified.
2046 //
2048  size_t GlobalWidth) const {
2049  if (O.hasArgStr()) {
2050  // When the value is optional, first print a line just describing the
2051  // option without values.
2052  if (O.getValueExpectedFlag() == ValueOptional) {
2053  for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
2054  if (getOption(i).empty()) {
2055  outs() << PrintArg(O.ArgStr);
2056  Option::printHelpStr(O.HelpStr, GlobalWidth,
2057  argPlusPrefixesSize(O.ArgStr));
2058  break;
2059  }
2060  }
2061  }
2062 
2063  outs() << PrintArg(O.ArgStr) << EqValue;
2064  Option::printHelpStr(O.HelpStr, GlobalWidth,
2065  EqValue.size() +
2066  argPlusPrefixesSize(O.ArgStr));
2067  for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
2068  StringRef OptionName = getOption(i);
2069  StringRef Description = getDescription(i);
2070  if (!shouldPrintOption(OptionName, Description, O))
2071  continue;
2072  size_t FirstLineIndent = OptionName.size() + getOptionPrefixesSize();
2073  outs() << OptionPrefix << OptionName;
2074  if (OptionName.empty()) {
2075  outs() << EmptyOption;
2076  assert(FirstLineIndent >= EmptyOption.size());
2077  FirstLineIndent += EmptyOption.size();
2078  }
2079  if (!Description.empty())
2080  Option::printEnumValHelpStr(Description, GlobalWidth, FirstLineIndent);
2081  else
2082  outs() << '\n';
2083  }
2084  } else {
2085  if (!O.HelpStr.empty())
2086  outs() << " " << O.HelpStr << '\n';
2087  for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
2089  outs() << " " << PrintArg(Option);
2090  Option::printHelpStr(getDescription(i), GlobalWidth, Option.size() + 8);
2091  }
2092  }
2093 }
2094 
2095 static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
2096 
2097 // printGenericOptionDiff - Print the value of this option and it's default.
2098 //
2099 // "Generic" options have each value mapped to a name.
2101  const Option &O, const GenericOptionValue &Value,
2102  const GenericOptionValue &Default, size_t GlobalWidth) const {
2103  outs() << " " << PrintArg(O.ArgStr);
2104  outs().indent(GlobalWidth - O.ArgStr.size());
2105 
2106  unsigned NumOpts = getNumOptions();
2107  for (unsigned i = 0; i != NumOpts; ++i) {
2108  if (Value.compare(getOptionValue(i)))
2109  continue;
2110 
2111  outs() << "= " << getOption(i);
2112  size_t L = getOption(i).size();
2113  size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
2114  outs().indent(NumSpaces) << " (default: ";
2115  for (unsigned j = 0; j != NumOpts; ++j) {
2116  if (Default.compare(getOptionValue(j)))
2117  continue;
2118  outs() << getOption(j);
2119  break;
2120  }
2121  outs() << ")\n";
2122  return;
2123  }
2124  outs() << "= *unknown option value*\n";
2125 }
2126 
2127 // printOptionDiff - Specializations for printing basic value types.
2128 //
2129 #define PRINT_OPT_DIFF(T) \
2130  void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D, \
2131  size_t GlobalWidth) const { \
2132  printOptionName(O, GlobalWidth); \
2133  std::string Str; \
2134  { \
2135  raw_string_ostream SS(Str); \
2136  SS << V; \
2137  } \
2138  outs() << "= " << Str; \
2139  size_t NumSpaces = \
2140  MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0; \
2141  outs().indent(NumSpaces) << " (default: "; \
2142  if (D.hasValue()) \
2143  outs() << D.getValue(); \
2144  else \
2145  outs() << "*no default*"; \
2146  outs() << ")\n"; \
2147  }
2148 
2149 PRINT_OPT_DIFF(bool)
2151 PRINT_OPT_DIFF(int)
2152 PRINT_OPT_DIFF(long)
2153 PRINT_OPT_DIFF(long long)
2154 PRINT_OPT_DIFF(unsigned)
2155 PRINT_OPT_DIFF(unsigned long)
2156 PRINT_OPT_DIFF(unsigned long long)
2157 PRINT_OPT_DIFF(double)
2158 PRINT_OPT_DIFF(float)
2159 PRINT_OPT_DIFF(char)
2160 
2162  const OptionValue<std::string> &D,
2163  size_t GlobalWidth) const {
2164  printOptionName(O, GlobalWidth);
2165  outs() << "= " << V;
2166  size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
2167  outs().indent(NumSpaces) << " (default: ";
2168  if (D.hasValue())
2169  outs() << D.getValue();
2170  else
2171  outs() << "*no default*";
2172  outs() << ")\n";
2173 }
2174 
2175 // Print a placeholder for options that don't yet support printOptionDiff().
2177  size_t GlobalWidth) const {
2178  printOptionName(O, GlobalWidth);
2179  outs() << "= *cannot print option value*\n";
2180 }
2181 
2182 //===----------------------------------------------------------------------===//
2183 // -help and -help-hidden option implementation
2184 //
2185 
2186 static int OptNameCompare(const std::pair<const char *, Option *> *LHS,
2187  const std::pair<const char *, Option *> *RHS) {
2188  return strcmp(LHS->first, RHS->first);
2189 }
2190 
2191 static int SubNameCompare(const std::pair<const char *, SubCommand *> *LHS,
2192  const std::pair<const char *, SubCommand *> *RHS) {
2193  return strcmp(LHS->first, RHS->first);
2194 }
2195 
2196 // Copy Options into a vector so we can sort them as we like.
2197 static void sortOpts(StringMap<Option *> &OptMap,
2198  SmallVectorImpl<std::pair<const char *, Option *>> &Opts,
2199  bool ShowHidden) {
2200  SmallPtrSet<Option *, 32> OptionSet; // Duplicate option detection.
2201 
2202  for (StringMap<Option *>::iterator I = OptMap.begin(), E = OptMap.end();
2203  I != E; ++I) {
2204  // Ignore really-hidden options.
2205  if (I->second->getOptionHiddenFlag() == ReallyHidden)
2206  continue;
2207 
2208  // Unless showhidden is set, ignore hidden flags.
2209  if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
2210  continue;
2211 
2212  // If we've already seen this option, don't add it to the list again.
2213  if (!OptionSet.insert(I->second).second)
2214  continue;
2215 
2216  Opts.push_back(
2217  std::pair<const char *, Option *>(I->getKey().data(), I->second));
2218  }
2219 
2220  // Sort the options list alphabetically.
2221  array_pod_sort(Opts.begin(), Opts.end(), OptNameCompare);
2222 }
2223 
2224 static void
2226  SmallVectorImpl<std::pair<const char *, SubCommand *>> &Subs) {
2227  for (auto *S : SubMap) {
2228  if (S->getName().empty())
2229  continue;
2230  Subs.push_back(std::make_pair(S->getName().data(), S));
2231  }
2232  array_pod_sort(Subs.begin(), Subs.end(), SubNameCompare);
2233 }
2234 
2235 namespace {
2236 
2237 class HelpPrinter {
2238 protected:
2239  const bool ShowHidden;
2241  StrOptionPairVector;
2243  StrSubCommandPairVector;
2244  // Print the options. Opts is assumed to be alphabetically sorted.
2245  virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
2246  for (size_t i = 0, e = Opts.size(); i != e; ++i)
2247  Opts[i].second->printOptionInfo(MaxArgLen);
2248  }
2249 
2250  void printSubCommands(StrSubCommandPairVector &Subs, size_t MaxSubLen) {
2251  for (const auto &S : Subs) {
2252  outs() << " " << S.first;
2253  if (!S.second->getDescription().empty()) {
2254  outs().indent(MaxSubLen - strlen(S.first));
2255  outs() << " - " << S.second->getDescription();
2256  }
2257  outs() << "\n";
2258  }
2259  }
2260 
2261 public:
2262  explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
2263  virtual ~HelpPrinter() = default;
2264 
2265  // Invoke the printer.
2266  void operator=(bool Value) {
2267  if (!Value)
2268  return;
2269  printHelp();
2270 
2271  // Halt the program since help information was printed
2272  exit(0);
2273  }
2274 
2275  void printHelp() {
2276  SubCommand *Sub = GlobalParser->getActiveSubCommand();
2277  auto &OptionsMap = Sub->OptionsMap;
2278  auto &PositionalOpts = Sub->PositionalOpts;
2279  auto &ConsumeAfterOpt = Sub->ConsumeAfterOpt;
2280 
2281  StrOptionPairVector Opts;
2282  sortOpts(OptionsMap, Opts, ShowHidden);
2283 
2284  StrSubCommandPairVector Subs;
2285  sortSubCommands(GlobalParser->RegisteredSubCommands, Subs);
2286 
2287  if (!GlobalParser->ProgramOverview.empty())
2288  outs() << "OVERVIEW: " << GlobalParser->ProgramOverview << "\n";
2289 
2290  if (Sub == &*TopLevelSubCommand) {
2291  outs() << "USAGE: " << GlobalParser->ProgramName;
2292  if (Subs.size() > 2)
2293  outs() << " [subcommand]";
2294  outs() << " [options]";
2295  } else {
2296  if (!Sub->getDescription().empty()) {
2297  outs() << "SUBCOMMAND '" << Sub->getName()
2298  << "': " << Sub->getDescription() << "\n\n";
2299  }
2300  outs() << "USAGE: " << GlobalParser->ProgramName << " " << Sub->getName()
2301  << " [options]";
2302  }
2303 
2304  for (auto *Opt : PositionalOpts) {
2305  if (Opt->hasArgStr())
2306  outs() << " --" << Opt->ArgStr;
2307  outs() << " " << Opt->HelpStr;
2308  }
2309 
2310  // Print the consume after option info if it exists...
2311  if (ConsumeAfterOpt)
2312  outs() << " " << ConsumeAfterOpt->HelpStr;
2313 
2314  if (Sub == &*TopLevelSubCommand && !Subs.empty()) {
2315  // Compute the maximum subcommand length...
2316  size_t MaxSubLen = 0;
2317  for (size_t i = 0, e = Subs.size(); i != e; ++i)
2318  MaxSubLen = std::max(MaxSubLen, strlen(Subs[i].first));
2319 
2320  outs() << "\n\n";
2321  outs() << "SUBCOMMANDS:\n\n";
2322  printSubCommands(Subs, MaxSubLen);
2323  outs() << "\n";
2324  outs() << " Type \"" << GlobalParser->ProgramName
2325  << " <subcommand> --help\" to get more help on a specific "
2326  "subcommand";
2327  }
2328 
2329  outs() << "\n\n";
2330 
2331  // Compute the maximum argument length...
2332  size_t MaxArgLen = 0;
2333  for (size_t i = 0, e = Opts.size(); i != e; ++i)
2334  MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
2335 
2336  outs() << "OPTIONS:\n";
2337  printOptions(Opts, MaxArgLen);
2338 
2339  // Print any extra help the user has declared.
2340  for (const auto &I : GlobalParser->MoreHelp)
2341  outs() << I;
2342  GlobalParser->MoreHelp.clear();
2343  }
2344 };
2345 
2346 class CategorizedHelpPrinter : public HelpPrinter {
2347 public:
2348  explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
2349 
2350  // Helper function for printOptions().
2351  // It shall return a negative value if A's name should be lexicographically
2352  // ordered before B's name. It returns a value greater than zero if B's name
2353  // should be ordered before A's name, and it returns 0 otherwise.
2354  static int OptionCategoryCompare(OptionCategory *const *A,
2355  OptionCategory *const *B) {
2356  return (*A)->getName().compare((*B)->getName());
2357  }
2358 
2359  // Make sure we inherit our base class's operator=()
2360  using HelpPrinter::operator=;
2361 
2362 protected:
2363  void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override {
2364  std::vector<OptionCategory *> SortedCategories;
2366 
2367  // Collect registered option categories into vector in preparation for
2368  // sorting.
2369  for (OptionCategory *Category : GlobalParser->RegisteredOptionCategories)
2370  SortedCategories.push_back(Category);
2371 
2372  // Sort the different option categories alphabetically.
2373  assert(SortedCategories.size() > 0 && "No option categories registered!");
2374  array_pod_sort(SortedCategories.begin(), SortedCategories.end(),
2375  OptionCategoryCompare);
2376 
2377  // Walk through pre-sorted options and assign into categories.
2378  // Because the options are already alphabetically sorted the
2379  // options within categories will also be alphabetically sorted.
2380  for (size_t I = 0, E = Opts.size(); I != E; ++I) {
2381  Option *Opt = Opts[I].second;
2382  for (auto &Cat : Opt->Categories) {
2383  assert(find(SortedCategories, Cat) != SortedCategories.end() &&
2384  "Option has an unregistered category");
2385  CategorizedOptions[Cat].push_back(Opt);
2386  }
2387  }
2388 
2389  // Now do printing.
2390  for (OptionCategory *Category : SortedCategories) {
2391  // Hide empty categories for --help, but show for --help-hidden.
2392  const auto &CategoryOptions = CategorizedOptions[Category];
2393  bool IsEmptyCategory = CategoryOptions.empty();
2394  if (!ShowHidden && IsEmptyCategory)
2395  continue;
2396 
2397  // Print category information.
2398  outs() << "\n";
2399  outs() << Category->getName() << ":\n";
2400 
2401  // Check if description is set.
2402  if (!Category->getDescription().empty())
2403  outs() << Category->getDescription() << "\n\n";
2404  else
2405  outs() << "\n";
2406 
2407  // When using --help-hidden explicitly state if the category has no
2408  // options associated with it.
2409  if (IsEmptyCategory) {
2410  outs() << " This option category has no options.\n";
2411  continue;
2412  }
2413  // Loop over the options in the category and print.
2414  for (const Option *Opt : CategoryOptions)
2415  Opt->printOptionInfo(MaxArgLen);
2416  }
2417  }
2418 };
2419 
2420 // This wraps the Uncategorizing and Categorizing printers and decides
2421 // at run time which should be invoked.
2422 class HelpPrinterWrapper {
2423 private:
2424  HelpPrinter &UncategorizedPrinter;
2425  CategorizedHelpPrinter &CategorizedPrinter;
2426 
2427 public:
2428  explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
2429  CategorizedHelpPrinter &CategorizedPrinter)
2430  : UncategorizedPrinter(UncategorizedPrinter),
2431  CategorizedPrinter(CategorizedPrinter) {}
2432 
2433  // Invoke the printer.
2434  void operator=(bool Value);
2435 };
2436 
2437 } // End anonymous namespace
2438 
2439 #if defined(__GNUC__)
2440 // GCC and GCC-compatible compilers define __OPTIMIZE__ when optimizations are
2441 // enabled.
2442 # if defined(__OPTIMIZE__)
2443 # define LLVM_IS_DEBUG_BUILD 0
2444 # else
2445 # define LLVM_IS_DEBUG_BUILD 1
2446 # endif
2447 #elif defined(_MSC_VER)
2448 // MSVC doesn't have a predefined macro indicating if optimizations are enabled.
2449 // Use _DEBUG instead. This macro actually corresponds to the choice between
2450 // debug and release CRTs, but it is a reasonable proxy.
2451 # if defined(_DEBUG)
2452 # define LLVM_IS_DEBUG_BUILD 1
2453 # else
2454 # define LLVM_IS_DEBUG_BUILD 0
2455 # endif
2456 #else
2457 // Otherwise, for an unknown compiler, assume this is an optimized build.
2458 # define LLVM_IS_DEBUG_BUILD 0
2459 #endif
2460 
2461 namespace {
2462 class VersionPrinter {
2463 public:
2464  void print() {
2465  raw_ostream &OS = outs();
2466 #ifdef PACKAGE_VENDOR
2467  OS << PACKAGE_VENDOR << " ";
2468 #else
2469  OS << "LLVM (http://llvm.org/):\n ";
2470 #endif
2471  OS << PACKAGE_NAME << " version " << PACKAGE_VERSION;
2472 #ifdef LLVM_VERSION_INFO
2473  OS << " " << LLVM_VERSION_INFO;
2474 #endif
2475  OS << "\n ";
2476 #if LLVM_IS_DEBUG_BUILD
2477  OS << "DEBUG build";
2478 #else
2479  OS << "Optimized build";
2480 #endif
2481 #ifndef NDEBUG
2482  OS << " with assertions";
2483 #endif
2484 #if LLVM_VERSION_PRINTER_SHOW_HOST_TARGET_INFO
2485  std::string CPU = std::string(sys::getHostCPUName());
2486  if (CPU == "generic")
2487  CPU = "(unknown)";
2488  OS << ".\n"
2489  << " Default target: " << sys::getDefaultTargetTriple() << '\n'
2490  << " Host CPU: " << CPU;
2491 #endif
2492  OS << '\n';
2493  }
2494  void operator=(bool OptionWasSpecified);
2495 };
2496 
2497 struct CommandLineCommonOptions {
2498  // Declare the four HelpPrinter instances that are used to print out help, or
2499  // help-hidden as an uncategorized list or in categories.
2500  HelpPrinter UncategorizedNormalPrinter{false};
2501  HelpPrinter UncategorizedHiddenPrinter{true};
2502  CategorizedHelpPrinter CategorizedNormalPrinter{false};
2503  CategorizedHelpPrinter CategorizedHiddenPrinter{true};
2504  // Declare HelpPrinter wrappers that will decide whether or not to invoke
2505  // a categorizing help printer
2506  HelpPrinterWrapper WrappedNormalPrinter{UncategorizedNormalPrinter,
2507  CategorizedNormalPrinter};
2508  HelpPrinterWrapper WrappedHiddenPrinter{UncategorizedHiddenPrinter,
2509  CategorizedHiddenPrinter};
2510  // Define a category for generic options that all tools should have.
2511  cl::OptionCategory GenericCategory{"Generic Options"};
2512 
2513  // Define uncategorized help printers.
2514  // --help-list is hidden by default because if Option categories are being
2515  // used then --help behaves the same as --help-list.
2517  "help-list",
2518  cl::desc(
2519  "Display list of available options (--help-list-hidden for more)"),
2520  cl::location(UncategorizedNormalPrinter),
2521  cl::Hidden,
2523  cl::cat(GenericCategory),
2525 
2527  "help-list-hidden",
2528  cl::desc("Display list of all available options"),
2529  cl::location(UncategorizedHiddenPrinter),
2530  cl::Hidden,
2532  cl::cat(GenericCategory),
2534 
2535  // Define uncategorized/categorized help printers. These printers change their
2536  // behaviour at runtime depending on whether one or more Option categories
2537  // have been declared.
2539  "help",
2540  cl::desc("Display available options (--help-hidden for more)"),
2541  cl::location(WrappedNormalPrinter),
2543  cl::cat(GenericCategory),
2545 
2546  cl::alias HOpA{"h", cl::desc("Alias for --help"), cl::aliasopt(HOp),
2548 
2550  "help-hidden",
2551  cl::desc("Display all available options"),
2552  cl::location(WrappedHiddenPrinter),
2553  cl::Hidden,
2555  cl::cat(GenericCategory),
2557 
2558  cl::opt<bool> PrintOptions{
2559  "print-options",
2560  cl::desc("Print non-default options after command line parsing"),
2561  cl::Hidden,
2562  cl::init(false),
2563  cl::cat(GenericCategory),
2565 
2566  cl::opt<bool> PrintAllOptions{
2567  "print-all-options",
2568  cl::desc("Print all option values after command line parsing"),
2569  cl::Hidden,
2570  cl::init(false),
2571  cl::cat(GenericCategory),
2573 
2574  VersionPrinterTy OverrideVersionPrinter = nullptr;
2575 
2576  std::vector<VersionPrinterTy> ExtraVersionPrinters;
2577 
2578  // Define the --version option that prints out the LLVM version for the tool
2579  VersionPrinter VersionPrinterInstance;
2580 
2582  "version", cl::desc("Display the version of this program"),
2583  cl::location(VersionPrinterInstance), cl::ValueDisallowed,
2584  cl::cat(GenericCategory)};
2585 };
2586 } // End anonymous namespace
2587 
2588 // Lazy-initialized global instance of options controlling the command-line
2589 // parser and general handling.
2591 
2592 static void initCommonOptions() {
2593  *CommonOptions;
2598  initTimerOptions();
2601  initDebugOptions();
2603 }
2604 
2606  // Initialise the general option category.
2607  static OptionCategory GeneralCategory{"General options"};
2608  return GeneralCategory;
2609 }
2610 
2611 void VersionPrinter::operator=(bool OptionWasSpecified) {
2612  if (!OptionWasSpecified)
2613  return;
2614 
2615  if (CommonOptions->OverrideVersionPrinter != nullptr) {
2616  CommonOptions->OverrideVersionPrinter(outs());
2617  exit(0);
2618  }
2619  print();
2620 
2621  // Iterate over any registered extra printers and call them to add further
2622  // information.
2623  if (!CommonOptions->ExtraVersionPrinters.empty()) {
2624  outs() << '\n';
2625  for (const auto &I : CommonOptions->ExtraVersionPrinters)
2626  I(outs());
2627  }
2628 
2629  exit(0);
2630 }
2631 
2632 void HelpPrinterWrapper::operator=(bool Value) {
2633  if (!Value)
2634  return;
2635 
2636  // Decide which printer to invoke. If more than one option category is
2637  // registered then it is useful to show the categorized help instead of
2638  // uncategorized help.
2639  if (GlobalParser->RegisteredOptionCategories.size() > 1) {
2640  // unhide --help-list option so user can have uncategorized output if they
2641  // want it.
2642  CommonOptions->HLOp.setHiddenFlag(NotHidden);
2643 
2644  CategorizedPrinter = true; // Invoke categorized printer
2645  } else
2646  UncategorizedPrinter = true; // Invoke uncategorized printer
2647 }
2648 
2649 // Print the value of each option.
2650 void cl::PrintOptionValues() { GlobalParser->printOptionValues(); }
2651 
2652 void CommandLineParser::printOptionValues() {
2653  if (!CommonOptions->PrintOptions && !CommonOptions->PrintAllOptions)
2654  return;
2655 
2657  sortOpts(ActiveSubCommand->OptionsMap, Opts, /*ShowHidden*/ true);
2658 
2659  // Compute the maximum argument length...
2660  size_t MaxArgLen = 0;
2661  for (size_t i = 0, e = Opts.size(); i != e; ++i)
2662  MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
2663 
2664  for (size_t i = 0, e = Opts.size(); i != e; ++i)
2665  Opts[i].second->printOptionValue(MaxArgLen, CommonOptions->PrintAllOptions);
2666 }
2667 
2668 // Utility function for printing the help message.
2669 void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
2670  if (!Hidden && !Categorized)
2671  CommonOptions->UncategorizedNormalPrinter.printHelp();
2672  else if (!Hidden && Categorized)
2673  CommonOptions->CategorizedNormalPrinter.printHelp();
2674  else if (Hidden && !Categorized)
2675  CommonOptions->UncategorizedHiddenPrinter.printHelp();
2676  else
2677  CommonOptions->CategorizedHiddenPrinter.printHelp();
2678 }
2679 
2680 /// Utility function for printing version number.
2682  CommonOptions->VersionPrinterInstance.print();
2683 }
2684 
2686  CommonOptions->OverrideVersionPrinter = func;
2687 }
2688 
2690  CommonOptions->ExtraVersionPrinters.push_back(func);
2691 }
2692 
2695  auto &Subs = GlobalParser->RegisteredSubCommands;
2696  (void)Subs;
2697  assert(is_contained(Subs, &Sub));
2698  return Sub.OptionsMap;
2699 }
2700 
2703  return GlobalParser->getRegisteredSubcommands();
2704 }
2705 
2708  for (auto &I : Sub.OptionsMap) {
2709  bool Unrelated = true;
2710  for (auto &Cat : I.second->Categories) {
2711  if (Cat == &Category || Cat == &CommonOptions->GenericCategory)
2712  Unrelated = false;
2713  }
2714  if (Unrelated)
2715  I.second->setHiddenFlag(cl::ReallyHidden);
2716  }
2717 }
2718 
2720  SubCommand &Sub) {
2722  for (auto &I : Sub.OptionsMap) {
2723  bool Unrelated = true;
2724  for (auto &Cat : I.second->Categories) {
2725  if (is_contained(Categories, Cat) ||
2726  Cat == &CommonOptions->GenericCategory)
2727  Unrelated = false;
2728  }
2729  if (Unrelated)
2730  I.second->setHiddenFlag(cl::ReallyHidden);
2731  }
2732 }
2733 
2736  GlobalParser->ResetAllOptionOccurrences();
2737 }
2738 
2739 void LLVMParseCommandLineOptions(int argc, const char *const *argv,
2740  const char *Overview) {
2741  llvm::cl::ParseCommandLineOptions(argc, argv, StringRef(Overview),
2742  &llvm::nulls());
2743 }
llvm::cl::readConfigFile
bool readConfigFile(StringRef CfgFileName, StringSaver &Saver, SmallVectorImpl< const char * > &Argv)
Reads command line options from the given configuration file.
Definition: CommandLine.cpp:1355
i
i
Definition: README.txt:29
MemoryBuffer.h
llvm::cl::AddExtraVersionPrinter
void AddExtraVersionPrinter(VersionPrinterTy func)
===------------------------------------------------------------------—===// Add an extra printer to u...
Definition: CommandLine.cpp:2689
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:1508
llvm::cl::SubCommand::reset
void reset()
Definition: CommandLine.cpp:502
llvm::cl::DefaultOption
@ DefaultOption
Definition: CommandLine.h:176
isWindowsSpecialChar
static bool isWindowsSpecialChar(char C)
Definition: CommandLine.cpp:924
llvm::cl::parser::parse
bool parse(Option &O, StringRef ArgName, StringRef Arg, DataType &V)
Definition: CommandLine.h:826
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:17
llvm::SmallVectorImpl::erase
iterator erase(const_iterator CI)
Definition: SmallVector.h:724
tokenizeWindowsCommandLineImpl
static void tokenizeWindowsCommandLineImpl(StringRef Src, StringSaver &Saver, function_ref< void(StringRef)> AddToken, bool AlwaysCopy, function_ref< void()> MarkEOL, bool InitialCommandName)
Definition: CommandLine.cpp:933
llvm::cl::SubCommand::OptionsMap
StringMap< Option * > OptionsMap
Definition: CommandLine.h:229
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:280
llvm::cl::Option::Categories
SmallVector< OptionCategory *, 1 > Categories
Definition: CommandLine.h:278
llvm::sys::fs::current_path
std::error_code current_path(SmallVectorImpl< char > &result)
Get the current path.
Optional.h
FileSystem.h
getOptionPred
static Option * getOptionPred(StringRef Name, size_t &Length, bool(*Pred)(const Option *), const StringMap< Option * > &OptionsMap)
Definition: CommandLine.cpp:719
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:2225
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:1774
llvm::cl::SubCommand::PositionalOpts
SmallVector< Option *, 4 > PositionalOpts
Definition: CommandLine.h:227
llvm::cl::location
LocationClass< Ty > location(Ty &L)
Definition: CommandLine.h:447
StringRef.h
llvm::cl::BOU_FALSE
@ BOU_FALSE
Definition: CommandLine.h:611
llvm::cl::basic_parser_impl::printOptionNoValue
void printOptionNoValue(const Option &O, size_t GlobalWidth) const
Definition: CommandLine.cpp:2176
llvm::cl::getRegisteredOptions
StringMap< Option * > & getRegisteredOptions(SubCommand &Sub= *TopLevelSubCommand)
Use this to get a StringMap to all registered named options (e.g.
Definition: CommandLine.cpp:2693
llvm::cl::Option::HelpStr
StringRef HelpStr
Definition: CommandLine.h:275
llvm::StringRef::npos
static constexpr size_t npos
Definition: StringRef.h:60
Host.h
llvm::StringRef::find
LLVM_NODISCARD size_t find(char C, size_t From=0) const
Search for the first character C in the string.
Definition: StringRef.h:315
llvm::SmallVector
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1185
llvm::cl::PrintVersionMessage
void PrintVersionMessage()
Utility function for printing version number.
Definition: CommandLine.cpp:2681
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:1405
llvm::cl::Option::error
bool error(const Twine &Message, StringRef ArgName=StringRef(), raw_ostream &Errs=llvm::errs())
Definition: CommandLine.cpp:1762
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
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:2734
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::StringMap::end
iterator end()
Definition: StringMap.h:205
DebugOptions.h
isWindowsSpecialCharInCommandName
static bool isWindowsSpecialCharInCommandName(char C)
Definition: CommandLine.cpp:927
llvm::Optional< llvm::StringRef >
llvm::cl::Option::setMiscFlag
void setMiscFlag(enum MiscFlags M)
Definition: CommandLine.h:325
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:508
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:1339
llvm::cl::SubCommand::unregisterSubCommand
void unregisterSubCommand()
Definition: CommandLine.cpp:498
llvm::errs
raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
Definition: raw_ostream.cpp:893
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:218
llvm::nulls
raw_ostream & nulls()
This returns a reference to a raw_ostream which simply discards output.
Definition: raw_ostream.cpp:900
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:1812
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:1704
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:1062
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:2013
llvm::cl::generic_parser_base::printOptionInfo
virtual void printOptionInfo(const Option &O, size_t GlobalWidth) const
Definition: CommandLine.cpp:2047
llvm::cl::Option::hasArgStr
bool hasArgStr() const
Definition: CommandLine.h:302
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:571
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
llvm::StringRef::substr
LLVM_NODISCARD StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition: StringRef.h:611
Arg
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
Definition: AMDGPULibCalls.cpp:186
isQuote
static bool isQuote(char C)
Definition: CommandLine.cpp:820
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:910
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:748
llvm::PPCISD::SC
@ SC
CHAIN = SC CHAIN, Imm128 - System call.
Definition: PPCISelLowering.h:418
CommonOptions
static ManagedStatic< CommandLineCommonOptions > CommonOptions
Definition: CommandLine.cpp:2590
llvm::outs
raw_fd_ostream & outs()
This returns a reference to a raw_fd_ostream for standard output.
Definition: raw_ostream.cpp:885
llvm::cl::generic_parser_base::findOption
unsigned findOption(StringRef Name)
Definition: CommandLine.cpp:2000
parseDouble
static bool parseDouble(Option &O, StringRef Arg, double &Value)
Definition: CommandLine.cpp:1974
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:289
llvm::MemoryBuffer::getBufferEnd
const char * getBufferEnd() const
Definition: MemoryBuffer.h:66
SmallString.h
llvm::cl::aliasopt
Definition: CommandLine.h:1898
E
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
isGrouping
static bool isGrouping(const Option *O)
Definition: CommandLine.cpp:124
llvm::SmallVectorImpl::append
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
Definition: SmallVector.h:667
llvm::StringRef::split
LLVM_NODISCARD std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition: StringRef.h:749
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:231
llvm::cl::Option::getMiscFlags
unsigned getMiscFlags() const
Definition: CommandLine.h:297
llvm::cl::Required
@ Required
Definition: CommandLine.h:117
Twine.h
llvm::cl::PrintOptionValues
void PrintOptionValues()
Definition: CommandLine.cpp:2650
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:90
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:293
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:1377
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:1042
llvm::cl::SubCommand::registerSubCommand
void registerSubCommand()
Definition: CommandLine.cpp:494
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:143
llvm::raw_ostream
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:54
llvm::cl::parser
Definition: CommandLine.h:797
llvm::cl::Option::getNumAdditionalVals
unsigned getNumAdditionalVals() const
Definition: CommandLine.h:299
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:395
llvm::cl::HideUnrelatedOptions
void HideUnrelatedOptions(cl::OptionCategory &Category, SubCommand &Sub= *TopLevelSubCommand)
Mark all options not part of this category as cl::ReallyHidden.
Definition: CommandLine.cpp:2706
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::cl::OneOrMore
@ OneOrMore
Definition: CommandLine.h:118
StringMap.h
MaxOptWidth
static const size_t MaxOptWidth
Definition: CommandLine.cpp:2095
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:225
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:648
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::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:812
OptNameCompare
static int OptNameCompare(const std::pair< const char *, Option * > *LHS, const std::pair< const char *, Option * > *RHS)
Definition: CommandLine.cpp:2186
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:274
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:1785
llvm::cl::opt
Definition: CommandLine.h:1392
llvm::SmallString::c_str
const char * c_str()
Definition: SmallString.h:263
llvm::RISCVFenceField::O
@ O
Definition: RISCVBaseInfo.h:239
llvm::cl::Option
Definition: CommandLine.h:242
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:747
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:228
llvm::StringMapIterator
Definition: StringMap.h:27
llvm::StringRef::empty
constexpr LLVM_NODISCARD bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:153
llvm::cl::Option::getValueExpectedFlag
enum ValueExpected getValueExpectedFlag() const
Definition: CommandLine.h:285
D
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
EqValue
static StringRef EqValue
Definition: CommandLine.cpp:2010
llvm::find
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1625
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:57
llvm::DenseMap
Definition: DenseMap.h:716
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:2685
Support.h
llvm::cl::init
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:432
llvm::cl::SubCommand
Definition: CommandLine.h:204
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:1218
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:1670
ArrayRef.h
RequiresValue
static bool RequiresValue(const Option *O)
Definition: CommandLine.cpp:802
llvm::StringMap::begin
iterator begin()
Definition: StringMap.h:204
llvm::cl::ProvidePositionalOption
bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i)
Parses Arg into the option handler Handler.
Definition: CommandLine.cpp:708
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:900
llvm::sys::Process::GetEnv
static Optional< std::string > GetEnv(StringRef name)
llvm::cl::ValueDisallowed
@ ValueDisallowed
Definition: CommandLine.h:134
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:1074
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:2669
llvm::Record
Definition: Record.h:1508
llvm::cl::generic_parser_base::printGenericOptionDiff
void printGenericOptionDiff(const Option &O, const GenericOptionValue &V, const GenericOptionValue &Default, size_t GlobalWidth) const
Definition: CommandLine.cpp:2100
llvm::initTypeSizeOptions
void initTypeSizeOptions()
Definition: TypeSize.cpp:34
llvm::cl::boolOrDefault
boolOrDefault
Definition: CommandLine.h:611
llvm::cl::basic_parser_impl::getValueName
virtual StringRef getValueName() const
Definition: CommandLine.h:890
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:1586
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:1054
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:2739
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:99
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:1612
llvm::StringRef
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:58
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:1115
llvm::cl::alias
Definition: CommandLine.h:1839
llvm::cl::TokenizerCallback
void(*)(StringRef Source, StringSaver &Saver, SmallVectorImpl< const char * > &NewArgv, bool MarkEOLs) TokenizerCallback
String tokenization function type.
Definition: CommandLine.h:2045
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:62
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:822
LLVM_FALLTHROUGH
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
Definition: Compiler.h:280
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:620
llvm::DenseMapBase< DenseMap< KeyT, ValueT, DenseMapInfo< KeyT >, llvm::detail::DenseMapPair< KeyT, ValueT > >, KeyT, ValueT, DenseMapInfo< KeyT >, llvm::detail::DenseMapPair< KeyT, ValueT > >::empty
LLVM_NODISCARD bool empty() const
Definition: DenseMap.h:98
llvm::cl::generic_parser_base::getDescription
virtual StringRef getDescription(unsigned N) const =0
llvm::cl::Option::Subs
SmallPtrSet< SubCommand *, 1 > Subs
Definition: CommandLine.h:279
llvm::Triple::isOSWindows
bool isOSWindows() const
Tests whether the OS is Windows.
Definition: Triple.h:563
llvm::cl::AlwaysPrefix
@ AlwaysPrefix
Definition: CommandLine.h:161
llvm::StringRef::size
constexpr LLVM_NODISCARD size_t size() const
size - Get the string size.
Definition: StringRef.h:157
j
return j(j<< 16)
llvm::Twine
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:83
llvm::empty
constexpr bool empty(const T &RangeOrContainer)
Test whether RangeOrContainer is empty. Similar to C++17 std::empty.
Definition: STLExtras.h:268
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:267
sortOpts
static void sortOpts(StringMap< Option * > &OptMap, SmallVectorImpl< std::pair< const char *, Option * >> &Opts, bool ShowHidden)
Definition: CommandLine.cpp:2197
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::initTimerOptions
void initTimerOptions()
Definition: Timer.cpp:90
initCommonOptions
static void initCommonOptions()
Definition: CommandLine.cpp:2592
llvm::sys::getProcessTriple
std::string getProcessTriple()
getProcessTriple() - Return an appropriate target triple for generating code to be loaded into the cu...
Definition: Host.cpp:1805
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:1839
llvm::cl::OptionCategory::getName
StringRef getName() const
Definition: CommandLine.h:195
EatsUnboundedNumberOfValues
static bool EatsUnboundedNumberOfValues(const Option *O)
Definition: CommandLine.cpp:807
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:1800
llvm::SmallVectorImpl::clear
void clear()
Definition: SmallVector.h:591
isWhitespaceOrNull
static bool isWhitespaceOrNull(char C)
Definition: CommandLine.cpp:816
llvm::cl::basic_parser_impl::printOptionName
void printOptionName(const Option &O, size_t GlobalWidth) const
Definition: CommandLine.cpp:1872
llvm::StringMap::count
size_type count(StringRef Key) const
count - Return 1 if the element is in the map, 0 otherwise.
Definition: StringMap.h:246
llvm::SmallString::str
StringRef str() const
Explicit conversion to StringRef.
Definition: SmallString.h:260
OptionPrefix
static StringRef OptionPrefix
Definition: CommandLine.cpp:2012
llvm::cl::BOU_TRUE
@ BOU_TRUE
Definition: CommandLine.h:611
shouldPrintOption
static bool shouldPrintOption(StringRef Name, StringRef Description, const Option &O)
Definition: CommandLine.cpp:2017
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:631
llvm::raw_ostream::indent
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
Definition: raw_ostream.cpp:496
llvm::cl::Option::getNumOccurrencesFlag
enum NumOccurrencesFlag getNumOccurrencesFlag() const
Definition: CommandLine.h:281
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:452
llvm::max
Align max(MaybeAlign Lhs, Align Rhs)
Definition: Alignment.h:340
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:1417
llvm::cl::generic_parser_base::getOptionWidth
virtual size_t getOptionWidth(const Option &O) const
Definition: CommandLine.cpp:2024
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::StringRef::data
const LLVM_NODISCARD char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition: StringRef.h:149
llvm::SmallVectorImpl< const char * >
EmptyOption
static StringRef EmptyOption
Definition: CommandLine.cpp:2011
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::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:1152
llvm::StringRef::edit_distance
LLVM_NODISCARD unsigned edit_distance(StringRef Other, bool AllowReplacements=true, unsigned MaxEditDistance=0) const
Determine the edit distance between this string and another string.
Definition: StringRef.cpp:92
ExpandBasePaths
static void ExpandBasePaths(StringRef BasePath, StringSaver &Saver, const char *&Arg)
Definition: CommandLine.cpp:1120
llvm::cl::desc
Definition: CommandLine.h:405
llvm::cl::Option::isDefaultOption
bool isDefaultOption() const
Definition: CommandLine.h:305
raw_ostream.h
llvm::X86AS::FS
@ FS
Definition: X86.h:188
llvm::cl::OptionValue
Definition: CommandLine.h:521
llvm::cl::Option::removeArgument
void removeArgument()
Unregisters this option from the CommandLine system.
Definition: CommandLine.cpp:451
llvm::cl::sub
Definition: CommandLine.h:461
llvm::cl::getGeneralCategory
OptionCategory & getGeneralCategory()
Definition: CommandLine.cpp:2605
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:1855
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:2191
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:2702
llvm::cl::SubCommand::getName
StringRef getName() const
Definition: CommandLine.h:224
PRINT_OPT_DIFF
#define PRINT_OPT_DIFF(T)
Definition: CommandLine.cpp:2129
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:792
llvm::cl::OptionCategory
Definition: CommandLine.h:181