1 //===- ArgList.h - Argument List Management ---------------------*- 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_ARGLIST_H 10 #define LLVM_OPTION_ARGLIST_H 11 12 #include "llvm/ADT/ArrayRef.h" 13 #include "llvm/ADT/DenseMap.h" 14 #include "llvm/ADT/iterator_range.h" 15 #include "llvm/ADT/SmallString.h" 16 #include "llvm/ADT/SmallVector.h" 17 #include "llvm/ADT/StringRef.h" 18 #include "llvm/ADT/Twine.h" 19 #include "llvm/Option/Arg.h" 20 #include "llvm/Option/OptSpecifier.h" 21 #include "llvm/Option/Option.h" 22 #include <algorithm> 23 #include <cstddef> 24 #include <initializer_list> 25 #include <iterator> 26 #include <list> 27 #include <memory> 28 #include <string> 29 #include <utility> 30 #include <vector> 31 32 namespace llvm { 33 34 class raw_ostream; 35 36 namespace opt { 37 38 /// arg_iterator - Iterates through arguments stored inside an ArgList. 39 template<typename BaseIter, unsigned NumOptSpecifiers = 0> 40 class arg_iterator { 41 /// The current argument and the end of the sequence we're iterating. 42 BaseIter Current, End; 43 44 /// Optional filters on the arguments which will be match. To avoid a 45 /// zero-sized array, we store one specifier even if we're asked for none. 46 OptSpecifier Ids[NumOptSpecifiers ? NumOptSpecifiers : 1]; 47 SkipToNextArg()48 void SkipToNextArg() { 49 for (; Current != End; ++Current) { 50 // Skip erased elements. 51 if (!*Current) 52 continue; 53 54 // Done if there are no filters. 55 if (!NumOptSpecifiers) 56 return; 57 58 // Otherwise require a match. 59 const Option &O = (*Current)->getOption(); 60 for (auto Id : Ids) { 61 if (!Id.isValid()) 62 break; 63 if (O.matches(Id)) 64 return; 65 } 66 } 67 } 68 69 using Traits = std::iterator_traits<BaseIter>; 70 71 public: 72 using value_type = typename Traits::value_type; 73 using reference = typename Traits::reference; 74 using pointer = typename Traits::pointer; 75 using iterator_category = std::forward_iterator_tag; 76 using difference_type = std::ptrdiff_t; 77 78 arg_iterator( 79 BaseIter Current, BaseIter End, 80 const OptSpecifier (&Ids)[NumOptSpecifiers ? NumOptSpecifiers : 1] = {}) Current(Current)81 : Current(Current), End(End) { 82 for (unsigned I = 0; I != NumOptSpecifiers; ++I) 83 this->Ids[I] = Ids[I]; 84 SkipToNextArg(); 85 } 86 87 reference operator*() const { return *Current; } 88 pointer operator->() const { return Current; } 89 90 arg_iterator &operator++() { 91 ++Current; 92 SkipToNextArg(); 93 return *this; 94 } 95 96 arg_iterator operator++(int) { 97 arg_iterator tmp(*this); 98 ++(*this); 99 return tmp; 100 } 101 102 friend bool operator==(arg_iterator LHS, arg_iterator RHS) { 103 return LHS.Current == RHS.Current; 104 } 105 friend bool operator!=(arg_iterator LHS, arg_iterator RHS) { 106 return !(LHS == RHS); 107 } 108 }; 109 110 /// ArgList - Ordered collection of driver arguments. 111 /// 112 /// The ArgList class manages a list of Arg instances as well as 113 /// auxiliary data and convenience methods to allow Tools to quickly 114 /// check for the presence of Arg instances for a particular Option 115 /// and to iterate over groups of arguments. 116 class ArgList { 117 public: 118 using arglist_type = SmallVector<Arg *, 16>; 119 using iterator = arg_iterator<arglist_type::iterator>; 120 using const_iterator = arg_iterator<arglist_type::const_iterator>; 121 using reverse_iterator = arg_iterator<arglist_type::reverse_iterator>; 122 using const_reverse_iterator = 123 arg_iterator<arglist_type::const_reverse_iterator>; 124 125 template<unsigned N> using filtered_iterator = 126 arg_iterator<arglist_type::const_iterator, N>; 127 template<unsigned N> using filtered_reverse_iterator = 128 arg_iterator<arglist_type::const_reverse_iterator, N>; 129 130 private: 131 /// The internal list of arguments. 132 arglist_type Args; 133 134 using OptRange = std::pair<unsigned, unsigned>; emptyRange()135 static OptRange emptyRange() { return {-1u, 0u}; } 136 137 /// The first and last index of each different OptSpecifier ID. 138 DenseMap<unsigned, OptRange> OptRanges; 139 140 /// Get the range of indexes in which options with the specified IDs might 141 /// reside, or (0, 0) if there are no such options. 142 OptRange getRange(std::initializer_list<OptSpecifier> Ids) const; 143 144 protected: 145 // Make the default special members protected so they won't be used to slice 146 // derived objects, but can still be used by derived objects to implement 147 // their own special members. 148 ArgList() = default; 149 150 // Explicit move operations to ensure the container is cleared post-move 151 // otherwise it could lead to a double-delete in the case of moving of an 152 // InputArgList which deletes the contents of the container. If we could fix 153 // up the ownership here (delegate storage/ownership to the derived class so 154 // it can be a container of unique_ptr) this would be simpler. ArgList(ArgList && RHS)155 ArgList(ArgList &&RHS) 156 : Args(std::move(RHS.Args)), OptRanges(std::move(RHS.OptRanges)) { 157 RHS.Args.clear(); 158 RHS.OptRanges.clear(); 159 } 160 161 ArgList &operator=(ArgList &&RHS) { 162 Args = std::move(RHS.Args); 163 RHS.Args.clear(); 164 OptRanges = std::move(RHS.OptRanges); 165 RHS.OptRanges.clear(); 166 return *this; 167 } 168 169 // Protect the dtor to ensure this type is never destroyed polymorphically. 170 ~ArgList() = default; 171 172 // Implicitly convert a value to an OptSpecifier. Used to work around a bug 173 // in MSVC's implementation of narrowing conversion checking. toOptSpecifier(OptSpecifier S)174 static OptSpecifier toOptSpecifier(OptSpecifier S) { return S; } 175 176 public: 177 /// @name Arg Access 178 /// @{ 179 180 /// append - Append \p A to the arg list. 181 void append(Arg *A); 182 getArgs()183 const arglist_type &getArgs() const { return Args; } 184 size()185 unsigned size() const { return Args.size(); } 186 187 /// @} 188 /// @name Arg Iteration 189 /// @{ 190 begin()191 iterator begin() { return {Args.begin(), Args.end()}; } end()192 iterator end() { return {Args.end(), Args.end()}; } 193 rbegin()194 reverse_iterator rbegin() { return {Args.rbegin(), Args.rend()}; } rend()195 reverse_iterator rend() { return {Args.rend(), Args.rend()}; } 196 begin()197 const_iterator begin() const { return {Args.begin(), Args.end()}; } end()198 const_iterator end() const { return {Args.end(), Args.end()}; } 199 rbegin()200 const_reverse_iterator rbegin() const { return {Args.rbegin(), Args.rend()}; } rend()201 const_reverse_iterator rend() const { return {Args.rend(), Args.rend()}; } 202 203 template<typename ...OptSpecifiers> 204 iterator_range<filtered_iterator<sizeof...(OptSpecifiers)>> filtered(OptSpecifiers...Ids)205 filtered(OptSpecifiers ...Ids) const { 206 OptRange Range = getRange({toOptSpecifier(Ids)...}); 207 auto B = Args.begin() + Range.first; 208 auto E = Args.begin() + Range.second; 209 using Iterator = filtered_iterator<sizeof...(OptSpecifiers)>; 210 return make_range(Iterator(B, E, {toOptSpecifier(Ids)...}), 211 Iterator(E, E, {toOptSpecifier(Ids)...})); 212 } 213 214 template<typename ...OptSpecifiers> 215 iterator_range<filtered_reverse_iterator<sizeof...(OptSpecifiers)>> filtered_reverse(OptSpecifiers...Ids)216 filtered_reverse(OptSpecifiers ...Ids) const { 217 OptRange Range = getRange({toOptSpecifier(Ids)...}); 218 auto B = Args.rend() - Range.second; 219 auto E = Args.rend() - Range.first; 220 using Iterator = filtered_reverse_iterator<sizeof...(OptSpecifiers)>; 221 return make_range(Iterator(B, E, {toOptSpecifier(Ids)...}), 222 Iterator(E, E, {toOptSpecifier(Ids)...})); 223 } 224 225 /// @} 226 /// @name Arg Removal 227 /// @{ 228 229 /// eraseArg - Remove any option matching \p Id. 230 void eraseArg(OptSpecifier Id); 231 232 /// @} 233 /// @name Arg Access 234 /// @{ 235 236 /// hasArg - Does the arg list contain any option matching \p Id. 237 /// 238 /// \p Claim Whether the argument should be claimed, if it exists. 239 template<typename ...OptSpecifiers> hasArgNoClaim(OptSpecifiers...Ids)240 bool hasArgNoClaim(OptSpecifiers ...Ids) const { 241 return getLastArgNoClaim(Ids...) != nullptr; 242 } 243 template<typename ...OptSpecifiers> hasArg(OptSpecifiers...Ids)244 bool hasArg(OptSpecifiers ...Ids) const { 245 return getLastArg(Ids...) != nullptr; 246 } 247 248 /// Return the last argument matching \p Id, or null. 249 template<typename ...OptSpecifiers> getLastArg(OptSpecifiers...Ids)250 Arg *getLastArg(OptSpecifiers ...Ids) const { 251 Arg *Res = nullptr; 252 for (Arg *A : filtered(Ids...)) { 253 Res = A; 254 Res->claim(); 255 } 256 return Res; 257 } 258 259 /// Return the last argument matching \p Id, or null. Do not "claim" the 260 /// option (don't mark it as having been used). 261 template<typename ...OptSpecifiers> getLastArgNoClaim(OptSpecifiers...Ids)262 Arg *getLastArgNoClaim(OptSpecifiers ...Ids) const { 263 for (Arg *A : filtered_reverse(Ids...)) 264 return A; 265 return nullptr; 266 } 267 268 /// getArgString - Return the input argument string at \p Index. 269 virtual const char *getArgString(unsigned Index) const = 0; 270 271 /// getNumInputArgStrings - Return the number of original argument strings, 272 /// which are guaranteed to be the first strings in the argument string 273 /// list. 274 virtual unsigned getNumInputArgStrings() const = 0; 275 276 /// @} 277 /// @name Argument Lookup Utilities 278 /// @{ 279 280 /// getLastArgValue - Return the value of the last argument, or a default. 281 StringRef getLastArgValue(OptSpecifier Id, StringRef Default = "") const; 282 283 /// getAllArgValues - Get the values of all instances of the given argument 284 /// as strings. 285 std::vector<std::string> getAllArgValues(OptSpecifier Id) const; 286 287 /// @} 288 /// @name Translation Utilities 289 /// @{ 290 291 /// hasFlag - Given an option \p Pos and its negative form \p Neg, return 292 /// true if the option is present, false if the negation is present, and 293 /// \p Default if neither option is given. If both the option and its 294 /// negation are present, the last one wins. 295 bool hasFlag(OptSpecifier Pos, OptSpecifier Neg, bool Default=true) const; 296 297 /// hasFlag - Given an option \p Pos, an alias \p PosAlias and its negative 298 /// form \p Neg, return true if the option or its alias is present, false if 299 /// the negation is present, and \p Default if none of the options are 300 /// given. If multiple options are present, the last one wins. 301 bool hasFlag(OptSpecifier Pos, OptSpecifier PosAlias, OptSpecifier Neg, 302 bool Default = true) const; 303 304 /// Render only the last argument match \p Id0, if present. 305 template<typename ...OptSpecifiers> AddLastArg(ArgStringList & Output,OptSpecifiers...Ids)306 void AddLastArg(ArgStringList &Output, OptSpecifiers ...Ids) const { 307 if (Arg *A = getLastArg(Ids...)) // Calls claim() on all Ids's Args. 308 A->render(*this, Output); 309 } 310 311 /// AddAllArgsExcept - Render all arguments matching any of the given ids 312 /// and not matching any of the excluded ids. 313 void AddAllArgsExcept(ArgStringList &Output, ArrayRef<OptSpecifier> Ids, 314 ArrayRef<OptSpecifier> ExcludeIds) const; 315 /// AddAllArgs - Render all arguments matching any of the given ids. 316 void AddAllArgs(ArgStringList &Output, ArrayRef<OptSpecifier> Ids) const; 317 318 /// AddAllArgs - Render all arguments matching the given ids. 319 void AddAllArgs(ArgStringList &Output, OptSpecifier Id0, 320 OptSpecifier Id1 = 0U, OptSpecifier Id2 = 0U) const; 321 322 /// AddAllArgValues - Render the argument values of all arguments 323 /// matching the given ids. 324 void AddAllArgValues(ArgStringList &Output, OptSpecifier Id0, 325 OptSpecifier Id1 = 0U, OptSpecifier Id2 = 0U) const; 326 327 /// AddAllArgsTranslated - Render all the arguments matching the 328 /// given ids, but forced to separate args and using the provided 329 /// name instead of the first option value. 330 /// 331 /// \param Joined - If true, render the argument as joined with 332 /// the option specifier. 333 void AddAllArgsTranslated(ArgStringList &Output, OptSpecifier Id0, 334 const char *Translation, 335 bool Joined = false) const; 336 337 /// ClaimAllArgs - Claim all arguments which match the given 338 /// option id. 339 void ClaimAllArgs(OptSpecifier Id0) const; 340 341 /// ClaimAllArgs - Claim all arguments. 342 /// 343 void ClaimAllArgs() const; 344 345 /// @} 346 /// @name Arg Synthesis 347 /// @{ 348 349 /// Construct a constant string pointer whose 350 /// lifetime will match that of the ArgList. 351 virtual const char *MakeArgStringRef(StringRef Str) const = 0; MakeArgString(const Twine & Str)352 const char *MakeArgString(const Twine &Str) const { 353 SmallString<256> Buf; 354 return MakeArgStringRef(Str.toStringRef(Buf)); 355 } 356 357 /// Create an arg string for (\p LHS + \p RHS), reusing the 358 /// string at \p Index if possible. 359 const char *GetOrMakeJoinedArgString(unsigned Index, StringRef LHS, 360 StringRef RHS) const; 361 362 void print(raw_ostream &O) const; 363 void dump() const; 364 365 /// @} 366 }; 367 368 class InputArgList final : public ArgList { 369 private: 370 /// List of argument strings used by the contained Args. 371 /// 372 /// This is mutable since we treat the ArgList as being the list 373 /// of Args, and allow routines to add new strings (to have a 374 /// convenient place to store the memory) via MakeIndex. 375 mutable ArgStringList ArgStrings; 376 377 /// Strings for synthesized arguments. 378 /// 379 /// This is mutable since we treat the ArgList as being the list 380 /// of Args, and allow routines to add new strings (to have a 381 /// convenient place to store the memory) via MakeIndex. 382 mutable std::list<std::string> SynthesizedStrings; 383 384 /// The number of original input argument strings. 385 unsigned NumInputArgStrings; 386 387 /// Release allocated arguments. 388 void releaseMemory(); 389 390 public: InputArgList()391 InputArgList() : NumInputArgStrings(0) {} 392 393 InputArgList(const char* const *ArgBegin, const char* const *ArgEnd); 394 InputArgList(InputArgList && RHS)395 InputArgList(InputArgList &&RHS) 396 : ArgList(std::move(RHS)), ArgStrings(std::move(RHS.ArgStrings)), 397 SynthesizedStrings(std::move(RHS.SynthesizedStrings)), 398 NumInputArgStrings(RHS.NumInputArgStrings) {} 399 400 InputArgList &operator=(InputArgList &&RHS) { 401 releaseMemory(); 402 ArgList::operator=(std::move(RHS)); 403 ArgStrings = std::move(RHS.ArgStrings); 404 SynthesizedStrings = std::move(RHS.SynthesizedStrings); 405 NumInputArgStrings = RHS.NumInputArgStrings; 406 return *this; 407 } 408 ~InputArgList()409 ~InputArgList() { releaseMemory(); } 410 getArgString(unsigned Index)411 const char *getArgString(unsigned Index) const override { 412 return ArgStrings[Index]; 413 } 414 getNumInputArgStrings()415 unsigned getNumInputArgStrings() const override { 416 return NumInputArgStrings; 417 } 418 419 /// @name Arg Synthesis 420 /// @{ 421 422 public: 423 /// MakeIndex - Get an index for the given string(s). 424 unsigned MakeIndex(StringRef String0) const; 425 unsigned MakeIndex(StringRef String0, StringRef String1) const; 426 427 using ArgList::MakeArgString; 428 const char *MakeArgStringRef(StringRef Str) const override; 429 430 /// @} 431 }; 432 433 /// DerivedArgList - An ordered collection of driver arguments, 434 /// whose storage may be in another argument list. 435 class DerivedArgList final : public ArgList { 436 const InputArgList &BaseArgs; 437 438 /// The list of arguments we synthesized. 439 mutable SmallVector<std::unique_ptr<Arg>, 16> SynthesizedArgs; 440 441 public: 442 /// Construct a new derived arg list from \p BaseArgs. 443 DerivedArgList(const InputArgList &BaseArgs); 444 getArgString(unsigned Index)445 const char *getArgString(unsigned Index) const override { 446 return BaseArgs.getArgString(Index); 447 } 448 getNumInputArgStrings()449 unsigned getNumInputArgStrings() const override { 450 return BaseArgs.getNumInputArgStrings(); 451 } 452 getBaseArgs()453 const InputArgList &getBaseArgs() const { 454 return BaseArgs; 455 } 456 457 /// @name Arg Synthesis 458 /// @{ 459 460 /// AddSynthesizedArg - Add a argument to the list of synthesized arguments 461 /// (to be freed). 462 void AddSynthesizedArg(Arg *A); 463 464 using ArgList::MakeArgString; 465 const char *MakeArgStringRef(StringRef Str) const override; 466 467 /// AddFlagArg - Construct a new FlagArg for the given option \p Id and 468 /// append it to the argument list. AddFlagArg(const Arg * BaseArg,const Option Opt)469 void AddFlagArg(const Arg *BaseArg, const Option Opt) { 470 append(MakeFlagArg(BaseArg, Opt)); 471 } 472 473 /// AddPositionalArg - Construct a new Positional arg for the given option 474 /// \p Id, with the provided \p Value and append it to the argument 475 /// list. AddPositionalArg(const Arg * BaseArg,const Option Opt,StringRef Value)476 void AddPositionalArg(const Arg *BaseArg, const Option Opt, 477 StringRef Value) { 478 append(MakePositionalArg(BaseArg, Opt, Value)); 479 } 480 481 /// AddSeparateArg - Construct a new Positional arg for the given option 482 /// \p Id, with the provided \p Value and append it to the argument 483 /// list. AddSeparateArg(const Arg * BaseArg,const Option Opt,StringRef Value)484 void AddSeparateArg(const Arg *BaseArg, const Option Opt, 485 StringRef Value) { 486 append(MakeSeparateArg(BaseArg, Opt, Value)); 487 } 488 489 /// AddJoinedArg - Construct a new Positional arg for the given option 490 /// \p Id, with the provided \p Value and append it to the argument list. AddJoinedArg(const Arg * BaseArg,const Option Opt,StringRef Value)491 void AddJoinedArg(const Arg *BaseArg, const Option Opt, 492 StringRef Value) { 493 append(MakeJoinedArg(BaseArg, Opt, Value)); 494 } 495 496 /// MakeFlagArg - Construct a new FlagArg for the given option \p Id. 497 Arg *MakeFlagArg(const Arg *BaseArg, const Option Opt) const; 498 499 /// MakePositionalArg - Construct a new Positional arg for the 500 /// given option \p Id, with the provided \p Value. 501 Arg *MakePositionalArg(const Arg *BaseArg, const Option Opt, 502 StringRef Value) const; 503 504 /// MakeSeparateArg - Construct a new Positional arg for the 505 /// given option \p Id, with the provided \p Value. 506 Arg *MakeSeparateArg(const Arg *BaseArg, const Option Opt, 507 StringRef Value) const; 508 509 /// MakeJoinedArg - Construct a new Positional arg for the 510 /// given option \p Id, with the provided \p Value. 511 Arg *MakeJoinedArg(const Arg *BaseArg, const Option Opt, 512 StringRef Value) const; 513 514 /// @} 515 }; 516 517 } // end namespace opt 518 519 } // end namespace llvm 520 521 #endif // LLVM_OPTION_ARGLIST_H 522