LLVM  3.7.0
OptTable.cpp
Go to the documentation of this file.
1 //===--- OptTable.cpp - Option Table Implementation -----------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "llvm/Option/OptTable.h"
11 #include "llvm/Option/Arg.h"
12 #include "llvm/Option/ArgList.h"
13 #include "llvm/Option/Option.h"
16 #include <algorithm>
17 #include <cctype>
18 #include <map>
19 
20 using namespace llvm;
21 using namespace llvm::opt;
22 
23 namespace llvm {
24 namespace opt {
25 
26 // Ordering on Info. The ordering is *almost* case-insensitive lexicographic,
27 // with an exceptions. '\0' comes at the end of the alphabet instead of the
28 // beginning (thus options precede any other options which prefix them).
29 static int StrCmpOptionNameIgnoreCase(const char *A, const char *B) {
30  const char *X = A, *Y = B;
31  char a = tolower(*A), b = tolower(*B);
32  while (a == b) {
33  if (a == '\0')
34  return 0;
35 
36  a = tolower(*++X);
37  b = tolower(*++Y);
38  }
39 
40  if (a == '\0') // A is a prefix of B.
41  return 1;
42  if (b == '\0') // B is a prefix of A.
43  return -1;
44 
45  // Otherwise lexicographic.
46  return (a < b) ? -1 : 1;
47 }
48 
49 #ifndef NDEBUG
50 static int StrCmpOptionName(const char *A, const char *B) {
51  if (int N = StrCmpOptionNameIgnoreCase(A, B))
52  return N;
53  return strcmp(A, B);
54 }
55 
56 static inline bool operator<(const OptTable::Info &A, const OptTable::Info &B) {
57  if (&A == &B)
58  return false;
59 
60  if (int N = StrCmpOptionName(A.Name, B.Name))
61  return N < 0;
62 
63  for (const char * const *APre = A.Prefixes,
64  * const *BPre = B.Prefixes;
65  *APre != nullptr && *BPre != nullptr; ++APre, ++BPre){
66  if (int N = StrCmpOptionName(*APre, *BPre))
67  return N < 0;
68  }
69 
70  // Names are the same, check that classes are in order; exactly one
71  // should be joined, and it should succeed the other.
72  assert(((A.Kind == Option::JoinedClass) ^ (B.Kind == Option::JoinedClass)) &&
73  "Unexpected classes for options with same name.");
74  return B.Kind == Option::JoinedClass;
75 }
76 #endif
77 
78 // Support lower_bound between info and an option name.
79 static inline bool operator<(const OptTable::Info &I, const char *Name) {
80  return StrCmpOptionNameIgnoreCase(I.Name, Name) < 0;
81 }
82 }
83 }
84 
85 OptSpecifier::OptSpecifier(const Option *Opt) : ID(Opt->getID()) {}
86 
87 OptTable::OptTable(const Info *OptionInfos, unsigned NumOptionInfos,
88  bool IgnoreCase)
89  : OptionInfos(OptionInfos), NumOptionInfos(NumOptionInfos),
90  IgnoreCase(IgnoreCase), TheInputOptionID(0), TheUnknownOptionID(0),
91  FirstSearchableIndex(0) {
92  // Explicitly zero initialize the error to work around a bug in array
93  // value-initialization on MinGW with gcc 4.3.5.
94 
95  // Find start of normal options.
96  for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
97  unsigned Kind = getInfo(i + 1).Kind;
98  if (Kind == Option::InputClass) {
99  assert(!TheInputOptionID && "Cannot have multiple input options!");
100  TheInputOptionID = getInfo(i + 1).ID;
101  } else if (Kind == Option::UnknownClass) {
102  assert(!TheUnknownOptionID && "Cannot have multiple unknown options!");
103  TheUnknownOptionID = getInfo(i + 1).ID;
104  } else if (Kind != Option::GroupClass) {
105  FirstSearchableIndex = i;
106  break;
107  }
108  }
109  assert(FirstSearchableIndex != 0 && "No searchable options?");
110 
111 #ifndef NDEBUG
112  // Check that everything after the first searchable option is a
113  // regular option class.
114  for (unsigned i = FirstSearchableIndex, e = getNumOptions(); i != e; ++i) {
116  assert((Kind != Option::InputClass && Kind != Option::UnknownClass &&
117  Kind != Option::GroupClass) &&
118  "Special options should be defined first!");
119  }
120 
121  // Check that options are in order.
122  for (unsigned i = FirstSearchableIndex + 1, e = getNumOptions(); i != e; ++i){
123  if (!(getInfo(i) < getInfo(i + 1))) {
124  getOption(i).dump();
125  getOption(i + 1).dump();
126  llvm_unreachable("Options are not in order!");
127  }
128  }
129 #endif
130 
131  // Build prefixes.
132  for (unsigned i = FirstSearchableIndex + 1, e = getNumOptions() + 1;
133  i != e; ++i) {
134  if (const char *const *P = getInfo(i).Prefixes) {
135  for (; *P != nullptr; ++P) {
136  PrefixesUnion.insert(*P);
137  }
138  }
139  }
140 
141  // Build prefix chars.
142  for (llvm::StringSet<>::const_iterator I = PrefixesUnion.begin(),
143  E = PrefixesUnion.end(); I != E; ++I) {
144  StringRef Prefix = I->getKey();
145  for (StringRef::const_iterator C = Prefix.begin(), CE = Prefix.end();
146  C != CE; ++C)
147  if (std::find(PrefixChars.begin(), PrefixChars.end(), *C)
148  == PrefixChars.end())
149  PrefixChars.push_back(*C);
150  }
151 }
152 
154 }
155 
157  unsigned id = Opt.getID();
158  if (id == 0)
159  return Option(nullptr, nullptr);
160  assert((unsigned) (id - 1) < getNumOptions() && "Invalid ID.");
161  return Option(&getInfo(id), this);
162 }
163 
164 static bool isInput(const llvm::StringSet<> &Prefixes, StringRef Arg) {
165  if (Arg == "-")
166  return true;
167  for (llvm::StringSet<>::const_iterator I = Prefixes.begin(),
168  E = Prefixes.end(); I != E; ++I)
169  if (Arg.startswith(I->getKey()))
170  return false;
171  return true;
172 }
173 
174 /// \returns Matched size. 0 means no match.
175 static unsigned matchOption(const OptTable::Info *I, StringRef Str,
176  bool IgnoreCase) {
177  for (const char * const *Pre = I->Prefixes; *Pre != nullptr; ++Pre) {
178  StringRef Prefix(*Pre);
179  if (Str.startswith(Prefix)) {
180  StringRef Rest = Str.substr(Prefix.size());
181  bool Matched = IgnoreCase
182  ? Rest.startswith_lower(I->Name)
183  : Rest.startswith(I->Name);
184  if (Matched)
185  return Prefix.size() + StringRef(I->Name).size();
186  }
187  }
188  return 0;
189 }
190 
191 Arg *OptTable::ParseOneArg(const ArgList &Args, unsigned &Index,
192  unsigned FlagsToInclude,
193  unsigned FlagsToExclude) const {
194  unsigned Prev = Index;
195  const char *Str = Args.getArgString(Index);
196 
197  // Anything that doesn't start with PrefixesUnion is an input, as is '-'
198  // itself.
199  if (isInput(PrefixesUnion, Str))
200  return new Arg(getOption(TheInputOptionID), Str, Index++, Str);
201 
202  const Info *Start = OptionInfos + FirstSearchableIndex;
203  const Info *End = OptionInfos + getNumOptions();
204  StringRef Name = StringRef(Str).ltrim(PrefixChars);
205 
206  // Search for the first next option which could be a prefix.
207  Start = std::lower_bound(Start, End, Name.data());
208 
209  // Options are stored in sorted order, with '\0' at the end of the
210  // alphabet. Since the only options which can accept a string must
211  // prefix it, we iteratively search for the next option which could
212  // be a prefix.
213  //
214  // FIXME: This is searching much more than necessary, but I am
215  // blanking on the simplest way to make it fast. We can solve this
216  // problem when we move to TableGen.
217  for (; Start != End; ++Start) {
218  unsigned ArgSize = 0;
219  // Scan for first option which is a proper prefix.
220  for (; Start != End; ++Start)
221  if ((ArgSize = matchOption(Start, Str, IgnoreCase)))
222  break;
223  if (Start == End)
224  break;
225 
226  Option Opt(Start, this);
227 
228  if (FlagsToInclude && !Opt.hasFlag(FlagsToInclude))
229  continue;
230  if (Opt.hasFlag(FlagsToExclude))
231  continue;
232 
233  // See if this option matches.
234  if (Arg *A = Opt.accept(Args, Index, ArgSize))
235  return A;
236 
237  // Otherwise, see if this argument was missing values.
238  if (Prev != Index)
239  return nullptr;
240  }
241 
242  // If we failed to find an option and this arg started with /, then it's
243  // probably an input path.
244  if (Str[0] == '/')
245  return new Arg(getOption(TheInputOptionID), Str, Index++, Str);
246 
247  return new Arg(getOption(TheUnknownOptionID), Str, Index++, Str);
248 }
249 
251  unsigned &MissingArgIndex,
252  unsigned &MissingArgCount,
253  unsigned FlagsToInclude,
254  unsigned FlagsToExclude) const {
255  InputArgList Args(ArgArr.begin(), ArgArr.end());
256 
257  // FIXME: Handle '@' args (or at least error on them).
258 
259  MissingArgIndex = MissingArgCount = 0;
260  unsigned Index = 0, End = ArgArr.size();
261  while (Index < End) {
262  // Ingore nullptrs, they are response file's EOL markers
263  if (Args.getArgString(Index) == nullptr) {
264  ++Index;
265  continue;
266  }
267  // Ignore empty arguments (other things may still take them as arguments).
268  StringRef Str = Args.getArgString(Index);
269  if (Str == "") {
270  ++Index;
271  continue;
272  }
273 
274  unsigned Prev = Index;
275  Arg *A = ParseOneArg(Args, Index, FlagsToInclude, FlagsToExclude);
276  assert(Index > Prev && "Parser failed to consume argument.");
277 
278  // Check for missing argument error.
279  if (!A) {
280  assert(Index >= End && "Unexpected parser error.");
281  assert(Index - Prev - 1 && "No missing arguments!");
282  MissingArgIndex = Prev;
283  MissingArgCount = Index - Prev - 1;
284  break;
285  }
286 
287  Args.append(A);
288  }
289 
290  return Args;
291 }
292 
293 static std::string getOptionHelpName(const OptTable &Opts, OptSpecifier Id) {
294  const Option O = Opts.getOption(Id);
295  std::string Name = O.getPrefixedName();
296 
297  // Add metavar, if used.
298  switch (O.getKind()) {
300  llvm_unreachable("Invalid option with help text.");
301 
303  if (const char *MetaVarName = Opts.getOptionMetaVar(Id)) {
304  // For MultiArgs, metavar is full list of all argument names.
305  Name += ' ';
306  Name += MetaVarName;
307  }
308  else {
309  // For MultiArgs<N>, if metavar not supplied, print <value> N times.
310  for (unsigned i=0, e=O.getNumArgs(); i< e; ++i) {
311  Name += " <value>";
312  }
313  }
314  break;
315 
316  case Option::FlagClass:
317  break;
318 
321  Name += ' ';
322  // FALLTHROUGH
325  if (const char *MetaVarName = Opts.getOptionMetaVar(Id))
326  Name += MetaVarName;
327  else
328  Name += "<value>";
329  break;
330  }
331 
332  return Name;
333 }
334 
336  std::vector<std::pair<std::string,
337  const char*> > &OptionHelp) {
338  OS << Title << ":\n";
339 
340  // Find the maximum option length.
341  unsigned OptionFieldWidth = 0;
342  for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
343  // Skip titles.
344  if (!OptionHelp[i].second)
345  continue;
346 
347  // Limit the amount of padding we are willing to give up for alignment.
348  unsigned Length = OptionHelp[i].first.size();
349  if (Length <= 23)
350  OptionFieldWidth = std::max(OptionFieldWidth, Length);
351  }
352 
353  const unsigned InitialPad = 2;
354  for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
355  const std::string &Option = OptionHelp[i].first;
356  int Pad = OptionFieldWidth - int(Option.size());
357  OS.indent(InitialPad) << Option;
358 
359  // Break on long option names.
360  if (Pad < 0) {
361  OS << "\n";
362  Pad = OptionFieldWidth + InitialPad;
363  }
364  OS.indent(Pad + 1) << OptionHelp[i].second << '\n';
365  }
366 }
367 
368 static const char *getOptionHelpGroup(const OptTable &Opts, OptSpecifier Id) {
369  unsigned GroupID = Opts.getOptionGroupID(Id);
370 
371  // If not in a group, return the default help group.
372  if (!GroupID)
373  return "OPTIONS";
374 
375  // Abuse the help text of the option groups to store the "help group"
376  // name.
377  //
378  // FIXME: Split out option groups.
379  if (const char *GroupHelp = Opts.getOptionHelpText(GroupID))
380  return GroupHelp;
381 
382  // Otherwise keep looking.
383  return getOptionHelpGroup(Opts, GroupID);
384 }
385 
386 void OptTable::PrintHelp(raw_ostream &OS, const char *Name, const char *Title,
387  bool ShowHidden) const {
388  PrintHelp(OS, Name, Title, /*Include*/ 0, /*Exclude*/
389  (ShowHidden ? 0 : HelpHidden));
390 }
391 
392 
393 void OptTable::PrintHelp(raw_ostream &OS, const char *Name, const char *Title,
394  unsigned FlagsToInclude,
395  unsigned FlagsToExclude) const {
396  OS << "OVERVIEW: " << Title << "\n";
397  OS << '\n';
398  OS << "USAGE: " << Name << " [options] <inputs>\n";
399  OS << '\n';
400 
401  // Render help text into a map of group-name to a list of (option, help)
402  // pairs.
403  typedef std::map<std::string,
404  std::vector<std::pair<std::string, const char*> > > helpmap_ty;
405  helpmap_ty GroupedOptionHelp;
406 
407  for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
408  unsigned Id = i + 1;
409 
410  // FIXME: Split out option groups.
412  continue;
413 
414  unsigned Flags = getInfo(Id).Flags;
415  if (FlagsToInclude && !(Flags & FlagsToInclude))
416  continue;
417  if (Flags & FlagsToExclude)
418  continue;
419 
420  if (const char *Text = getOptionHelpText(Id)) {
421  const char *HelpGroup = getOptionHelpGroup(*this, Id);
422  const std::string &OptName = getOptionHelpName(*this, Id);
423  GroupedOptionHelp[HelpGroup].push_back(std::make_pair(OptName, Text));
424  }
425  }
426 
427  for (helpmap_ty::iterator it = GroupedOptionHelp .begin(),
428  ie = GroupedOptionHelp.end(); it != ie; ++it) {
429  if (it != GroupedOptionHelp .begin())
430  OS << "\n";
431  PrintHelpOptionList(OS, it->first, it->second);
432  }
433 
434  OS.flush();
435 }
void dump() const
Definition: Option.cpp:38
unsigned short Flags
Definition: OptTable.h:45
size_t size() const
size - Get the string size.
Definition: StringRef.h:113
static bool operator<(const OptTable::Info &A, const OptTable::Info &B)
Definition: OptTable.cpp:56
iterator end() const
Definition: ArrayRef.h:123
bool hasFlag(unsigned Val) const
Test if this option has the flag Val.
Definition: Option.h:159
static unsigned matchOption(const OptTable::Info *I, StringRef Str, bool IgnoreCase)
Definition: OptTable.cpp:175
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition: StringRef.h:405
const_iterator begin(StringRef path)
Get begin iterator over path.
Definition: Path.cpp:232
InputArgList ParseArgs(ArrayRef< const char * > Args, unsigned &MissingArgIndex, unsigned &MissingArgCount, unsigned FlagsToInclude=0, unsigned FlagsToExclude=0) const
Parse an list of arguments into an InputArgList.
Definition: OptTable.cpp:250
OptionClass getKind() const
Definition: Option.h:83
static bool isInput(const llvm::StringSet<> &Prefixes, StringRef Arg)
Definition: OptTable.cpp:164
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Definition: ErrorHandling.h:98
const char * getOptionHelpText(OptSpecifier id) const
Get the help text to use to describe this option.
Definition: OptTable.h:108
OptTable(const Info *OptionInfos, unsigned NumOptionInfos, bool IgnoreCase=false)
Definition: OptTable.cpp:87
static int getID(struct InternalInstruction *insn, const void *miiArg)
unsigned char Kind
Definition: OptTable.h:43
const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition: StringRef.h:107
unsigned getNumArgs() const
Definition: Option.h:129
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: ArrayRef.h:31
static const char * getOptionHelpGroup(const OptTable &Opts, OptSpecifier Id)
Definition: OptTable.cpp:368
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:134
iterator begin() const
Definition: StringRef.h:90
#define P(N)
friend const_iterator end(StringRef path)
Get end iterator over path.
Definition: Path.cpp:240
Option - Abstract representation for a single form of driver argument.
Definition: Option.h:44
A concrete instance of a particular driver option.
Definition: Arg.h:31
Provide access to the Option info table.
Definition: OptTable.h:32
std::string getPrefixedName() const
Get the name of this option with the default prefix.
Definition: Option.h:123
const char *const * Prefixes
A null terminated array of prefix strings to apply to name while matching.
Definition: OptTable.h:38
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang","erlang-compatible garbage collector")
iterator begin() const
Definition: ArrayRef.h:122
static int StrCmpOptionName(const char *A, const char *B)
Definition: OptTable.cpp:50
unsigned getID() const
Definition: OptSpecifier.h:33
std::pair< typename base::iterator, bool > insert(StringRef Key)
Definition: StringSet.h:27
const char * const_iterator
Definition: StringRef.h:43
bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:215
virtual const char * getArgString(unsigned Index) const =0
getArgString - Return the input argument string at Index.
static int StrCmpOptionNameIgnoreCase(const char *A, const char *B)
Definition: OptTable.cpp:29
void PrintHelp(raw_ostream &OS, const char *Name, const char *Title, unsigned FlagsToInclude, unsigned FlagsToExclude) const
Render the help text for an option table.
Definition: OptTable.cpp:393
unsigned getNumOptions() const
Return the total number of option classes.
Definition: OptTable.h:84
Defines the llvm::Arg class for parsed arguments.
unsigned getOptionKind(OptSpecifier id) const
Get the kind of the given option.
Definition: OptTable.h:98
OptSpecifier - Wrapper class for abstracting references to option IDs.
Definition: OptSpecifier.h:20
iterator begin()
Definition: StringMap.h:252
const Option getOption(OptSpecifier Opt) const
Get the given Opt's Option instance, lazily creating it if necessary.
Definition: OptTable.cpp:156
Entry for a single option instance in the option data table.
Definition: OptTable.h:35
#define I(x, y, z)
Definition: MD5.cpp:54
#define N
Arg * ParseOneArg(const ArgList &Args, unsigned &Index, unsigned FlagsToInclude=0, unsigned FlagsToExclude=0) const
Parse a single argument; returning the new argument and updating Index.
Definition: OptTable.cpp:191
static std::string getOptionHelpName(const OptTable &Opts, OptSpecifier Id)
Definition: OptTable.cpp:293
const ARM::ArchExtKind Kind
static void PrintHelpOptionList(raw_ostream &OS, StringRef Title, std::vector< std::pair< std::string, const char * > > &OptionHelp)
Definition: OptTable.cpp:335
StringSet - A wrapper for StringMap that provides set-like functionality.
Definition: StringSet.h:23
iterator end() const
Definition: StringRef.h:92
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:38
Arg * accept(const ArgList &Args, unsigned &Index, unsigned ArgSize) const
accept - Potentially accept the current argument, returning a new Arg instance, or 0 if the option do...
Definition: Option.cpp:100
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:40
ArgList - Ordered collection of driver arguments.
Definition: ArgList.h:94
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml","ocaml 3.10-compatible collector")
unsigned getOptionGroupID(OptSpecifier id) const
Get the group id for the given option.
Definition: OptTable.h:103
bool startswith_lower(StringRef Prefix) const
Check if this string starts with the given Prefix, ignoring case.
Definition: StringRef.cpp:61
iterator end()
Definition: StringMap.h:255
StringRef ltrim(StringRef Chars=" \t\n\v\f\r") const
Return string with consecutive characters in Chars starting from the left removed.
Definition: StringRef.h:511
const char * getOptionMetaVar(OptSpecifier id) const
Get the meta-variable name to use when describing this options values in the help text...
Definition: OptTable.h:114