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