LLVM 22.0.0git
ArgList.cpp
Go to the documentation of this file.
1//===- ArgList.cpp - Argument List Management -----------------------------===//
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
10#include "llvm/ADT/ArrayRef.h"
12#include "llvm/ADT/StringRef.h"
13#include "llvm/ADT/Twine.h"
14#include "llvm/Config/llvm-config.h"
15#include "llvm/Option/Arg.h"
18#include "llvm/Option/Option.h"
20#include "llvm/Support/Debug.h"
22#include <algorithm>
23#include <cassert>
24#include <cstddef>
25#include <memory>
26#include <string>
27#include <vector>
28
29using namespace llvm;
30using namespace llvm::opt;
31
33 Args.push_back(A);
34
35 // Update ranges for the option and all of its groups.
36 for (Option O = A->getOption().getUnaliasedOption(); O.isValid();
37 O = O.getGroup()) {
38 auto &R =
39 OptRanges.insert(std::make_pair(O.getID(), emptyRange())).first->second;
40 R.first = std::min<unsigned>(R.first, Args.size() - 1);
41 R.second = Args.size();
42 }
43}
44
46 // Zero out the removed entries but keep them around so that we don't
47 // need to invalidate OptRanges.
48 for (Arg *const &A : filtered(Id)) {
49 // Avoid the need for a non-const filtered iterator variant.
50 Arg **ArgsBegin = Args.data();
51 ArgsBegin[&A - ArgsBegin] = nullptr;
52 }
53 OptRanges.erase(Id.getID());
54}
55
56ArgList::OptRange
57ArgList::getRange(std::initializer_list<OptSpecifier> Ids) const {
58 OptRange R = emptyRange();
59 for (auto Id : Ids) {
60 auto I = OptRanges.find(Id.getID());
61 if (I != OptRanges.end()) {
62 R.first = std::min(R.first, I->second.first);
63 R.second = std::max(R.second, I->second.second);
64 }
65 }
66 // Map an empty {-1, 0} range to {0, 0} so it can be used to form iterators.
67 if (R.first == -1u)
68 R.first = 0;
69 return R;
70}
71
73 if (Arg *A = getLastArg(Pos, Neg))
74 return A->getOption().matches(Pos);
75 return Default;
76}
77
79 bool Default) const {
80 if (Arg *A = getLastArgNoClaim(Pos, Neg))
81 return A->getOption().matches(Pos);
82 return Default;
83}
84
86 bool Default) const {
87 if (Arg *A = getLastArg(Pos, PosAlias, Neg))
88 return A->getOption().matches(Pos) || A->getOption().matches(PosAlias);
89 return Default;
90}
91
93 if (Arg *A = getLastArg(Id))
94 return A->getValue();
95 return Default;
96}
97
98std::vector<std::string> ArgList::getAllArgValues(OptSpecifier Id) const {
100 AddAllArgValues(Values, Id);
101 return std::vector<std::string>(Values.begin(), Values.end());
102}
103
105 OptSpecifier Neg) const {
106 if (Arg *A = getLastArg(Pos, Neg))
107 if (A->getOption().matches(Pos))
108 A->render(*this, Output);
109}
110
113 ArrayRef<OptSpecifier> ExcludeIds) const {
114 for (const Arg *Arg : *this) {
115 bool Excluded = false;
116 for (OptSpecifier Id : ExcludeIds) {
117 if (Arg->getOption().matches(Id)) {
118 Excluded = true;
119 break;
120 }
121 }
122 if (!Excluded) {
123 for (OptSpecifier Id : Ids) {
124 if (Arg->getOption().matches(Id)) {
125 Arg->claim();
126 Arg->render(*this, Output);
127 break;
128 }
129 }
130 }
131 }
132}
133
134/// This is a nicer interface when you don't have a list of Ids to exclude.
136 ArrayRef<OptSpecifier> Ids) const {
137 ArrayRef<OptSpecifier> Exclude = {};
138 AddAllArgsExcept(Output, Ids, Exclude);
139}
140
142 for (auto *Arg : filtered(Id0)) {
143 Arg->claim();
144 Arg->render(*this, Output);
145 }
146}
147
149 OptSpecifier Id1, OptSpecifier Id2) const {
150 for (auto *Arg : filtered(Id0, Id1, Id2)) {
151 Arg->claim();
152 const auto &Values = Arg->getValues();
153 Output.append(Values.begin(), Values.end());
154 }
155}
156
158 const char *Translation,
159 bool Joined) const {
160 for (auto *Arg : filtered(Id0)) {
161 Arg->claim();
162
163 if (Joined) {
164 Output.push_back(MakeArgString(StringRef(Translation) +
165 Arg->getValue(0)));
166 } else {
167 Output.push_back(Translation);
168 Output.push_back(Arg->getValue(0));
169 }
170 }
171}
172
174 for (auto *Arg : filtered(Id0))
175 Arg->claim();
176}
177
179 for (auto *Arg : *this)
180 if (!Arg->isClaimed())
181 Arg->claim();
182}
183
184const char *ArgList::GetOrMakeJoinedArgString(unsigned Index,
185 StringRef LHS,
186 StringRef RHS) const {
187 StringRef Cur = getArgString(Index);
188 if (Cur.size() == LHS.size() + RHS.size() && Cur.starts_with(LHS) &&
189 Cur.ends_with(RHS))
190 return Cur.data();
191
192 return MakeArgString(LHS + RHS);
193}
194
196 for (Arg *A : *this) {
197 O << "* ";
198 A->print(O);
199 }
200}
201
202#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
204#endif
205
208 std::function<void(ArrayRef<StringRef>)> HandleMultipleSubcommands,
209 std::function<void(ArrayRef<StringRef>)> HandleOtherPositionals) const {
210
211 SmallVector<StringRef, 4> SubCommands;
212 SmallVector<StringRef, 4> OtherPositionals;
213 for (const Arg *A : *this) {
214 if (A->getOption().getKind() != Option::InputClass)
215 continue;
216
217 size_t OldSize = SubCommands.size();
218 for (const OptTable::SubCommand &CMD : AllSubCommands) {
219 if (StringRef(CMD.Name) == A->getValue())
220 SubCommands.push_back(A->getValue());
221 }
222
223 if (SubCommands.size() == OldSize)
224 OtherPositionals.push_back(A->getValue());
225 }
226
227 // Invoke callbacks if necessary.
228 if (SubCommands.size() > 1) {
229 HandleMultipleSubcommands(SubCommands);
230 return {};
231 }
232 if (!OtherPositionals.empty())
233 HandleOtherPositionals(OtherPositionals);
234
235 if (SubCommands.size() == 1)
236 return SubCommands.front();
237 return {}; // No valid usage of subcommand found.
238}
239
240void InputArgList::releaseMemory() {
241 // An InputArgList always owns its arguments.
242 for (Arg *A : *this)
243 delete A;
244}
245
246InputArgList::InputArgList(const char* const *ArgBegin,
247 const char* const *ArgEnd)
248 : NumInputArgStrings(ArgEnd - ArgBegin) {
249 ArgStrings.append(ArgBegin, ArgEnd);
250}
251
252unsigned InputArgList::MakeIndex(StringRef String0) const {
253 unsigned Index = ArgStrings.size();
254
255 // Tuck away so we have a reliable const char *.
256 SynthesizedStrings.push_back(std::string(String0));
257 ArgStrings.push_back(SynthesizedStrings.back().c_str());
258
259 return Index;
260}
261
263 StringRef String1) const {
264 unsigned Index0 = MakeIndex(String0);
265 unsigned Index1 = MakeIndex(String1);
266 assert(Index0 + 1 == Index1 && "Unexpected non-consecutive indices!");
267 (void) Index1;
268 return Index0;
269}
270
272 return getArgString(MakeIndex(Str));
273}
274
276 : BaseArgs(BaseArgs) {}
277
279 return BaseArgs.MakeArgString(Str);
280}
281
283 SynthesizedArgs.push_back(std::unique_ptr<Arg>(A));
284}
285
286Arg *DerivedArgList::MakeFlagArg(const Arg *BaseArg, const Option Opt) const {
287 SynthesizedArgs.push_back(
288 std::make_unique<Arg>(Opt, MakeArgString(Opt.getPrefix() + Opt.getName()),
289 BaseArgs.MakeIndex(Opt.getName()), BaseArg));
290 return SynthesizedArgs.back().get();
291}
292
294 StringRef Value) const {
295 unsigned Index = BaseArgs.MakeIndex(Value);
296 SynthesizedArgs.push_back(
297 std::make_unique<Arg>(Opt, MakeArgString(Opt.getPrefix() + Opt.getName()),
298 Index, BaseArgs.getArgString(Index), BaseArg));
299 return SynthesizedArgs.back().get();
300}
301
303 StringRef Value) const {
304 unsigned Index = BaseArgs.MakeIndex(Opt.getName(), Value);
305 SynthesizedArgs.push_back(
306 std::make_unique<Arg>(Opt, MakeArgString(Opt.getPrefix() + Opt.getName()),
307 Index, BaseArgs.getArgString(Index + 1), BaseArg));
308 return SynthesizedArgs.back().get();
309}
310
311Arg *DerivedArgList::MakeJoinedArg(const Arg *BaseArg, const Option Opt,
312 StringRef Value) const {
313 unsigned Index = BaseArgs.MakeIndex((Opt.getName() + Value).str());
314 SynthesizedArgs.push_back(std::make_unique<Arg>(
315 Opt, MakeArgString(Opt.getPrefix() + Opt.getName()), Index,
316 BaseArgs.getArgString(Index) + Opt.getName().size(), BaseArg));
317 return SynthesizedArgs.back().get();
318}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Defines the llvm::Arg class for parsed arguments.
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static ManagedStatic< SubCommand > AllSubCommands
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:638
#define I(x, y, z)
Definition MD5.cpp:57
This file defines the SmallVector class.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:178
iterator end()
Definition DenseMap.h:81
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:261
constexpr size_t size() const
size - Get the string size.
Definition StringRef.h:146
constexpr const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition StringRef.h:140
bool ends_with(StringRef Suffix) const
Check if this string ends with the given Suffix.
Definition StringRef.h:273
LLVM Value Representation.
Definition Value.h:75
LLVM_ABI void eraseArg(OptSpecifier Id)
eraseArg - Remove any option matching Id.
Definition ArgList.cpp:45
virtual const char * getArgString(unsigned Index) const =0
getArgString - Return the input argument string at Index.
LLVM_ABI void AddAllArgValues(ArgStringList &Output, OptSpecifier Id0, OptSpecifier Id1=0U, OptSpecifier Id2=0U) const
AddAllArgValues - Render the argument values of all arguments matching the given ids.
Definition ArgList.cpp:148
LLVM_ABI void print(raw_ostream &O) const
Definition ArgList.cpp:195
LLVM_ABI const char * GetOrMakeJoinedArgString(unsigned Index, StringRef LHS, StringRef RHS) const
Create an arg string for (LHS + RHS), reusing the string at Index if possible.
Definition ArgList.cpp:184
LLVM_ABI void addOptInFlag(ArgStringList &Output, OptSpecifier Pos, OptSpecifier Neg) const
Given an option Pos and its negative form Neg, render the option if Pos is present.
Definition ArgList.cpp:104
LLVM_ABI bool hasFlagNoClaim(OptSpecifier Pos, OptSpecifier Neg, bool Default) const
Definition ArgList.cpp:78
LLVM_ABI void AddAllArgsTranslated(ArgStringList &Output, OptSpecifier Id0, const char *Translation, bool Joined=false) const
AddAllArgsTranslated - Render all the arguments matching the given ids, but forced to separate args a...
Definition ArgList.cpp:157
LLVM_ABI void AddAllArgs(ArgStringList &Output, OptSpecifier Id0) const
AddAllArgs - Render all arguments matching the given ids.
Definition ArgList.cpp:141
const char * MakeArgString(const Twine &Str) const
Definition ArgList.h:400
LLVM_ABI_FOR_TEST StringRef getSubCommand(ArrayRef< OptTable::SubCommand > AllSubCommands, std::function< void(ArrayRef< StringRef >)> HandleMultipleSubcommands, std::function< void(ArrayRef< StringRef >)> HandleOtherPositionals) const
getSubCommand - Find subcommand from the arguments if the usage is valid.
Definition ArgList.cpp:206
LLVM_ABI void append(Arg *A)
append - Append A to the arg list.
Definition ArgList.cpp:32
LLVM_ABI void addAllArgs(ArgStringList &Output, ArrayRef< OptSpecifier > Ids) const
Render all arguments matching any of the given ids.
Definition ArgList.cpp:135
LLVM_ABI void ClaimAllArgs() const
ClaimAllArgs - Claim all arguments.
Definition ArgList.cpp:178
LLVM_ATTRIBUTE_NOINLINE Arg * getLastArgNoClaim(OptSpecifiers... Ids) const
Return the last argument matching Id, or null.
Definition ArgList.h:270
LLVM_ABI void dump() const
Definition ArgList.cpp:203
LLVM_ABI void AddAllArgsExcept(ArgStringList &Output, ArrayRef< OptSpecifier > Ids, ArrayRef< OptSpecifier > ExcludeIds) const
AddAllArgsExcept - Render all arguments matching any of the given ids and not matching any of the exc...
Definition ArgList.cpp:111
LLVM_ATTRIBUTE_NOINLINE Arg * getLastArg(OptSpecifiers... Ids) const
Return the last argument matching Id, or null.
Definition ArgList.h:258
LLVM_ABI std::vector< std::string > getAllArgValues(OptSpecifier Id) const
getAllArgValues - Get the values of all instances of the given argument as strings.
Definition ArgList.cpp:98
LLVM_ABI StringRef getLastArgValue(OptSpecifier Id, StringRef Default="") const
getLastArgValue - Return the value of the last argument, or a default.
Definition ArgList.cpp:92
iterator_range< filtered_iterator< sizeof...(OptSpecifiers)> > filtered(OptSpecifiers ...Ids) const
Definition ArgList.h:207
LLVM_ABI bool hasFlag(OptSpecifier Pos, OptSpecifier Neg, bool Default) const
hasFlag - Given an option Pos and its negative form Neg, return true if the option is present,...
Definition ArgList.cpp:72
A concrete instance of a particular driver option.
Definition Arg.h:35
LLVM_ABI void render(const ArgList &Args, ArgStringList &Output) const
Append the argument onto the given array as strings.
Definition Arg.cpp:89
SmallVectorImpl< const char * > & getValues()
Definition Arg.h:131
const Option & getOption() const
Definition Arg.h:85
bool isClaimed() const
Definition Arg.h:115
const char * getValue(unsigned N=0) const
Definition Arg.h:127
void claim() const
Definition Arg.h:116
const char * MakeArgStringRef(StringRef Str) const override
Construct a constant string pointer whose lifetime will match that of the ArgList.
Definition ArgList.cpp:278
Arg * MakeSeparateArg(const Arg *BaseArg, const Option Opt, StringRef Value) const
MakeSeparateArg - Construct a new Positional arg for the given option Id, with the provided Value.
Definition ArgList.cpp:302
void AddSynthesizedArg(Arg *A)
AddSynthesizedArg - Add a argument to the list of synthesized arguments (to be freed).
Definition ArgList.cpp:282
Arg * MakeJoinedArg(const Arg *BaseArg, const Option Opt, StringRef Value) const
MakeJoinedArg - Construct a new Positional arg for the given option Id, with the provided Value.
Definition ArgList.cpp:311
DerivedArgList(const InputArgList &BaseArgs)
Construct a new derived arg list from BaseArgs.
Definition ArgList.cpp:275
const char * MakeArgString(const Twine &Str) const
Definition ArgList.h:400
Arg * MakePositionalArg(const Arg *BaseArg, const Option Opt, StringRef Value) const
MakePositionalArg - Construct a new Positional arg for the given option Id, with the provided Value.
Definition ArgList.cpp:293
Arg * MakeFlagArg(const Arg *BaseArg, const Option Opt) const
MakeFlagArg - Construct a new FlagArg for the given option Id.
Definition ArgList.cpp:286
const char * getArgString(unsigned Index) const override
getArgString - Return the input argument string at Index.
Definition ArgList.h:461
unsigned MakeIndex(StringRef String0) const
MakeIndex - Get an index for the given string(s).
Definition ArgList.cpp:252
const char * MakeArgStringRef(StringRef Str) const override
Construct a constant string pointer whose lifetime will match that of the ArgList.
Definition ArgList.cpp:271
OptSpecifier - Wrapper class for abstracting references to option IDs.
Option - Abstract representation for a single form of driver argument.
Definition Option.h:55
LLVM_ABI bool matches(OptSpecifier ID) const
matches - Predicate for whether this option is part of the given option (which may be a group).
Definition Option.cpp:96
StringRef getPrefix() const
Get the default prefix for this option.
Definition Option.h:131
StringRef getName() const
Get the name of this option without any prefix.
Definition Option.h:102
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
SmallVector< const char *, 16 > ArgStringList
ArgStringList - Type used for constructing argv lists for subprocesses.
Definition Option.h:30
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
@ Default
The result values are uniform if and only if all operands are uniform.
Definition Uniformity.h:20
Represents a subcommand and its options in the option table.
Definition OptTable.h:57