LLVM 17.0.0git
OptTable.h
Go to the documentation of this file.
1//===- OptTable.h - Option Table --------------------------------*- C++ -*-===//
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#ifndef LLVM_OPTION_OPTTABLE_H
10#define LLVM_OPTION_OPTTABLE_H
11
12#include "llvm/ADT/ArrayRef.h"
14#include "llvm/ADT/StringRef.h"
17#include <cassert>
18#include <string>
19#include <vector>
20
21namespace llvm {
22
23class raw_ostream;
24template <typename Fn> class function_ref;
25
26namespace opt {
27
28class Arg;
29class ArgList;
30class InputArgList;
31class Option;
32
33/// Provide access to the Option info table.
34///
35/// The OptTable class provides a layer of indirection which allows Option
36/// instance to be created lazily. In the common case, only a few options will
37/// be needed at runtime; the OptTable class maintains enough information to
38/// parse command lines without instantiating Options, while letting other
39/// parts of the driver still use Option instances where convenient.
40class OptTable {
41public:
42 /// Entry for a single option instance in the option data table.
43 struct Info {
44 /// A null terminated array of prefix strings to apply to name while
45 /// matching.
48 const char *HelpText;
49 const char *MetaVar;
50 unsigned ID;
51 unsigned char Kind;
52 unsigned char Param;
53 unsigned int Flags;
54 unsigned short GroupID;
55 unsigned short AliasID;
56 const char *AliasArgs;
57 const char *Values;
58 };
59
60private:
61 /// The option information table.
62 ArrayRef<Info> OptionInfos;
63 bool IgnoreCase;
64 bool GroupedShortOptions = false;
65 const char *EnvVar = nullptr;
66
67 unsigned InputOptionID = 0;
68 unsigned UnknownOptionID = 0;
69
70protected:
71 /// The index of the first option which can be parsed (i.e., is not a
72 /// special option like 'input' or 'unknown', and is not an option group).
74
75 /// The union of the first element of all option prefixes.
77
78 /// The union of all option prefixes. If an argument does not begin with
79 /// one of these, it is an input.
81
82private:
83 const Info &getInfo(OptSpecifier Opt) const {
84 unsigned id = Opt.getID();
85 assert(id > 0 && id - 1 < getNumOptions() && "Invalid Option ID.");
86 return OptionInfos[id - 1];
87 }
88
89 std::unique_ptr<Arg> parseOneArgGrouped(InputArgList &Args,
90 unsigned &Index) const;
91
92protected:
93 /// Initialize OptTable using Tablegen'ed OptionInfos. Child class must
94 /// manually call \c buildPrefixChars once they are fully constructed.
95 OptTable(ArrayRef<Info> OptionInfos, bool IgnoreCase = false);
96
97 /// Build (or rebuild) the PrefixChars member.
98 void buildPrefixChars();
99
100public:
101 virtual ~OptTable();
102
103 /// Return the total number of option classes.
104 unsigned getNumOptions() const { return OptionInfos.size(); }
105
106 /// Get the given Opt's Option instance, lazily creating it
107 /// if necessary.
108 ///
109 /// \return The option, or null for the INVALID option id.
110 const Option getOption(OptSpecifier Opt) const;
111
112 /// Lookup the name of the given option.
113 StringRef getOptionName(OptSpecifier id) const { return getInfo(id).Name; }
114
115 /// Get the kind of the given option.
116 unsigned getOptionKind(OptSpecifier id) const {
117 return getInfo(id).Kind;
118 }
119
120 /// Get the group id for the given option.
121 unsigned getOptionGroupID(OptSpecifier id) const {
122 return getInfo(id).GroupID;
123 }
124
125 /// Get the help text to use to describe this option.
126 const char *getOptionHelpText(OptSpecifier id) const {
127 return getInfo(id).HelpText;
128 }
129
130 /// Get the meta-variable name to use when describing
131 /// this options values in the help text.
132 const char *getOptionMetaVar(OptSpecifier id) const {
133 return getInfo(id).MetaVar;
134 }
135
136 /// Specify the environment variable where initial options should be read.
137 void setInitialOptionsFromEnvironment(const char *E) { EnvVar = E; }
138
139 /// Support grouped short options. e.g. -ab represents -a -b.
140 void setGroupedShortOptions(bool Value) { GroupedShortOptions = Value; }
141
142 /// Find possible value for given flags. This is used for shell
143 /// autocompletion.
144 ///
145 /// \param [in] Option - Key flag like "-stdlib=" when "-stdlib=l"
146 /// was passed to clang.
147 ///
148 /// \param [in] Arg - Value which we want to autocomplete like "l"
149 /// when "-stdlib=l" was passed to clang.
150 ///
151 /// \return The vector of possible values.
152 std::vector<std::string> suggestValueCompletions(StringRef Option,
153 StringRef Arg) const;
154
155 /// Find flags from OptTable which starts with Cur.
156 ///
157 /// \param [in] Cur - String prefix that all returned flags need
158 // to start with.
159 ///
160 /// \return The vector of flags which start with Cur.
161 std::vector<std::string> findByPrefix(StringRef Cur,
162 unsigned int DisableFlags) const;
163
164 /// Find the OptTable option that most closely matches the given string.
165 ///
166 /// \param [in] Option - A string, such as "-stdlibs=l", that represents user
167 /// input of an option that may not exist in the OptTable. Note that the
168 /// string includes prefix dashes "-" as well as values "=l".
169 /// \param [out] NearestString - The nearest option string found in the
170 /// OptTable.
171 /// \param [in] FlagsToInclude - Only find options with any of these flags.
172 /// Zero is the default, which includes all flags.
173 /// \param [in] FlagsToExclude - Don't find options with this flag. Zero
174 /// is the default, and means exclude nothing.
175 /// \param [in] MinimumLength - Don't find options shorter than this length.
176 /// For example, a minimum length of 3 prevents "-x" from being considered
177 /// near to "-S".
178 /// \param [in] MaximumDistance - Don't find options whose distance is greater
179 /// than this value.
180 ///
181 /// \return The edit distance of the nearest string found.
182 unsigned findNearest(StringRef Option, std::string &NearestString,
183 unsigned FlagsToInclude = 0, unsigned FlagsToExclude = 0,
184 unsigned MinimumLength = 4,
185 unsigned MaximumDistance = UINT_MAX) const;
186
187 bool findExact(StringRef Option, std::string &ExactString,
188 unsigned FlagsToInclude = 0,
189 unsigned FlagsToExclude = 0) const {
190 return findNearest(Option, ExactString, FlagsToInclude, FlagsToExclude, 4,
191 0) == 0;
192 }
193
194 /// Parse a single argument; returning the new argument and
195 /// updating Index.
196 ///
197 /// \param [in,out] Index - The current parsing position in the argument
198 /// string list; on return this will be the index of the next argument
199 /// string to parse.
200 /// \param [in] FlagsToInclude - Only parse options with any of these flags.
201 /// Zero is the default which includes all flags.
202 /// \param [in] FlagsToExclude - Don't parse options with this flag. Zero
203 /// is the default and means exclude nothing.
204 ///
205 /// \return The parsed argument, or 0 if the argument is missing values
206 /// (in which case Index still points at the conceptual next argument string
207 /// to parse).
208 std::unique_ptr<Arg> ParseOneArg(const ArgList &Args, unsigned &Index,
209 unsigned FlagsToInclude = 0,
210 unsigned FlagsToExclude = 0) const;
211
212 /// Parse an list of arguments into an InputArgList.
213 ///
214 /// The resulting InputArgList will reference the strings in [\p ArgBegin,
215 /// \p ArgEnd), and their lifetime should extend past that of the returned
216 /// InputArgList.
217 ///
218 /// The only error that can occur in this routine is if an argument is
219 /// missing values; in this case \p MissingArgCount will be non-zero.
220 ///
221 /// \param MissingArgIndex - On error, the index of the option which could
222 /// not be parsed.
223 /// \param MissingArgCount - On error, the number of missing options.
224 /// \param FlagsToInclude - Only parse options with any of these flags.
225 /// Zero is the default which includes all flags.
226 /// \param FlagsToExclude - Don't parse options with this flag. Zero
227 /// is the default and means exclude nothing.
228 /// \return An InputArgList; on error this will contain all the options
229 /// which could be parsed.
230 InputArgList ParseArgs(ArrayRef<const char *> Args, unsigned &MissingArgIndex,
231 unsigned &MissingArgCount, unsigned FlagsToInclude = 0,
232 unsigned FlagsToExclude = 0) const;
233
234 /// A convenience helper which handles optional initial options populated from
235 /// an environment variable, expands response files recursively and parses
236 /// options.
237 ///
238 /// \param ErrorFn - Called on a formatted error message for missing arguments
239 /// or unknown options.
240 /// \return An InputArgList; on error this will contain all the options which
241 /// could be parsed.
242 InputArgList parseArgs(int Argc, char *const *Argv, OptSpecifier Unknown,
243 StringSaver &Saver,
244 function_ref<void(StringRef)> ErrorFn) const;
245
246 /// Render the help text for an option table.
247 ///
248 /// \param OS - The stream to write the help text to.
249 /// \param Usage - USAGE: Usage
250 /// \param Title - OVERVIEW: Title
251 /// \param FlagsToInclude - If non-zero, only include options with any
252 /// of these flags set.
253 /// \param FlagsToExclude - Exclude options with any of these flags set.
254 /// \param ShowAllAliases - If true, display all options including aliases
255 /// that don't have help texts. By default, we display
256 /// only options that are not hidden and have help
257 /// texts.
258 void printHelp(raw_ostream &OS, const char *Usage, const char *Title,
259 unsigned FlagsToInclude, unsigned FlagsToExclude,
260 bool ShowAllAliases) const;
261
262 void printHelp(raw_ostream &OS, const char *Usage, const char *Title,
263 bool ShowHidden = false, bool ShowAllAliases = false) const;
264};
265
266/// Specialization of OptTable
267class GenericOptTable : public OptTable {
268 SmallVector<StringLiteral> PrefixesUnionBuffer;
269
270protected:
271 GenericOptTable(ArrayRef<Info> OptionInfos, bool IgnoreCase = false);
273 return PrefixesUnionBuffer;
274 }
275};
276
278 ArrayRef<StringLiteral> PrefixesUnion;
279
280protected:
282 ArrayRef<StringLiteral> PrefixesTable,
283 bool IgnoreCase = false)
284 : OptTable(OptionInfos, IgnoreCase), PrefixesUnion(PrefixesTable) {
286 }
288 return PrefixesUnion;
289 }
290};
291
292} // end namespace opt
293
294} // end namespace llvm
295
296#endif // LLVM_OPTION_OPTTABLE_H
aarch64 promote const
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
arm prera ldst opt
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
raw_pwrite_stream & OS
This file defines the SmallString class.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:163
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:26
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1200
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
Saves strings in the provided stable storage and returns a StringRef with a stable character pointer.
Definition: StringSaver.h:21
LLVM Value Representation.
Definition: Value.h:74
An efficient, type-erasing, non-owning reference to a callable.
ArgList - Ordered collection of driver arguments.
Definition: ArgList.h:116
A concrete instance of a particular driver option.
Definition: Arg.h:34
Specialization of OptTable.
Definition: OptTable.h:267
ArrayRef< StringLiteral > getPrefixesUnion() const final
The union of all option prefixes.
Definition: OptTable.h:272
OptSpecifier - Wrapper class for abstracting references to option IDs.
Definition: OptSpecifier.h:18
unsigned getID() const
Definition: OptSpecifier.h:29
Provide access to the Option info table.
Definition: OptTable.h:40
void buildPrefixChars()
Build (or rebuild) the PrefixChars member.
Definition: OptTable.cpp:130
StringRef getOptionName(OptSpecifier id) const
Lookup the name of the given option.
Definition: OptTable.h:113
std::unique_ptr< 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:383
unsigned getOptionKind(OptSpecifier id) const
Get the kind of the given option.
Definition: OptTable.h:116
unsigned FirstSearchableIndex
The index of the first option which can be parsed (i.e., is not a special option like 'input' or 'unk...
Definition: OptTable.h:73
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:132
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:447
const Option getOption(OptSpecifier Opt) const
Get the given Opt's Option instance, lazily creating it if necessary.
Definition: OptTable.cpp:143
const char * getOptionHelpText(OptSpecifier id) const
Get the help text to use to describe this option.
Definition: OptTable.h:126
InputArgList parseArgs(int Argc, char *const *Argv, OptSpecifier Unknown, StringSaver &Saver, function_ref< void(StringRef)> ErrorFn) const
A convenience helper which handles optional initial options populated from an environment variable,...
Definition: OptTable.cpp:493
std::vector< std::string > findByPrefix(StringRef Cur, unsigned int DisableFlags) const
Find flags from OptTable which starts with Cur.
Definition: OptTable.cpp:208
void setInitialOptionsFromEnvironment(const char *E)
Specify the environment variable where initial options should be read.
Definition: OptTable.h:137
void printHelp(raw_ostream &OS, const char *Usage, const char *Title, unsigned FlagsToInclude, unsigned FlagsToExclude, bool ShowAllAliases) const
Render the help text for an option table.
Definition: OptTable.cpp:624
unsigned findNearest(StringRef Option, std::string &NearestString, unsigned FlagsToInclude=0, unsigned FlagsToExclude=0, unsigned MinimumLength=4, unsigned MaximumDistance=UINT_MAX) const
Find the OptTable option that most closely matches the given string.
Definition: OptTable.cpp:228
bool findExact(StringRef Option, std::string &ExactString, unsigned FlagsToInclude=0, unsigned FlagsToExclude=0) const
Definition: OptTable.h:187
unsigned getOptionGroupID(OptSpecifier id) const
Get the group id for the given option.
Definition: OptTable.h:121
std::vector< std::string > suggestValueCompletions(StringRef Option, StringRef Arg) const
Find possible value for given flags.
Definition: OptTable.cpp:188
SmallString< 8 > PrefixChars
The union of the first element of all option prefixes.
Definition: OptTable.h:76
virtual ArrayRef< StringLiteral > getPrefixesUnion() const =0
The union of all option prefixes.
unsigned getNumOptions() const
Return the total number of option classes.
Definition: OptTable.h:104
void setGroupedShortOptions(bool Value)
Support grouped short options. e.g. -ab represents -a -b.
Definition: OptTable.h:140
Option - Abstract representation for a single form of driver argument.
Definition: Option.h:51
PrecomputedOptTable(ArrayRef< Info > OptionInfos, ArrayRef< StringLiteral > PrefixesTable, bool IgnoreCase=false)
Definition: OptTable.h:281
ArrayRef< StringLiteral > getPrefixesUnion() const final
The union of all option prefixes.
Definition: OptTable.h:287
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
Entry for a single option instance in the option data table.
Definition: OptTable.h:43
unsigned char Param
Definition: OptTable.h:52
const char * Values
Definition: OptTable.h:57
unsigned short AliasID
Definition: OptTable.h:55
unsigned short GroupID
Definition: OptTable.h:54
unsigned int Flags
Definition: OptTable.h:53
ArrayRef< StringLiteral > Prefixes
A null terminated array of prefix strings to apply to name while matching.
Definition: OptTable.h:46
const char * HelpText
Definition: OptTable.h:48
const char * MetaVar
Definition: OptTable.h:49
unsigned char Kind
Definition: OptTable.h:51
const char * AliasArgs
Definition: OptTable.h:56