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