Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-05-10 08:43:10

0001 //===- Twine.h - Fast Temporary String Concatenation ------------*- C++ -*-===//
0002 //
0003 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
0004 // See https://llvm.org/LICENSE.txt for license information.
0005 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
0006 //
0007 //===----------------------------------------------------------------------===//
0008 
0009 #ifndef LLVM_ADT_TWINE_H
0010 #define LLVM_ADT_TWINE_H
0011 
0012 #include "llvm/ADT/SmallVector.h"
0013 #include "llvm/ADT/StringRef.h"
0014 #include "llvm/Support/ErrorHandling.h"
0015 #include <cassert>
0016 #include <cstdint>
0017 #include <string>
0018 #include <string_view>
0019 
0020 namespace llvm {
0021 
0022   class formatv_object_base;
0023   class raw_ostream;
0024 
0025   /// Twine - A lightweight data structure for efficiently representing the
0026   /// concatenation of temporary values as strings.
0027   ///
0028   /// A Twine is a kind of rope, it represents a concatenated string using a
0029   /// binary-tree, where the string is the preorder of the nodes. Since the
0030   /// Twine can be efficiently rendered into a buffer when its result is used,
0031   /// it avoids the cost of generating temporary values for intermediate string
0032   /// results -- particularly in cases when the Twine result is never
0033   /// required. By explicitly tracking the type of leaf nodes, we can also avoid
0034   /// the creation of temporary strings for conversions operations (such as
0035   /// appending an integer to a string).
0036   ///
0037   /// A Twine is not intended for use directly and should not be stored, its
0038   /// implementation relies on the ability to store pointers to temporary stack
0039   /// objects which may be deallocated at the end of a statement. Twines should
0040   /// only be used as const references in arguments, when an API wishes
0041   /// to accept possibly-concatenated strings.
0042   ///
0043   /// Twines support a special 'null' value, which always concatenates to form
0044   /// itself, and renders as an empty string. This can be returned from APIs to
0045   /// effectively nullify any concatenations performed on the result.
0046   ///
0047   /// \b Implementation
0048   ///
0049   /// Given the nature of a Twine, it is not possible for the Twine's
0050   /// concatenation method to construct interior nodes; the result must be
0051   /// represented inside the returned value. For this reason a Twine object
0052   /// actually holds two values, the left- and right-hand sides of a
0053   /// concatenation. We also have nullary Twine objects, which are effectively
0054   /// sentinel values that represent empty strings.
0055   ///
0056   /// Thus, a Twine can effectively have zero, one, or two children. The \see
0057   /// isNullary(), \see isUnary(), and \see isBinary() predicates exist for
0058   /// testing the number of children.
0059   ///
0060   /// We maintain a number of invariants on Twine objects (FIXME: Why):
0061   ///  - Nullary twines are always represented with their Kind on the left-hand
0062   ///    side, and the Empty kind on the right-hand side.
0063   ///  - Unary twines are always represented with the value on the left-hand
0064   ///    side, and the Empty kind on the right-hand side.
0065   ///  - If a Twine has another Twine as a child, that child should always be
0066   ///    binary (otherwise it could have been folded into the parent).
0067   ///
0068   /// These invariants are check by \see isValid().
0069   ///
0070   /// \b Efficiency Considerations
0071   ///
0072   /// The Twine is designed to yield efficient and small code for common
0073   /// situations. For this reason, the concat() method is inlined so that
0074   /// concatenations of leaf nodes can be optimized into stores directly into a
0075   /// single stack allocated object.
0076   ///
0077   /// In practice, not all compilers can be trusted to optimize concat() fully,
0078   /// so we provide two additional methods (and accompanying operator+
0079   /// overloads) to guarantee that particularly important cases (cstring plus
0080   /// StringRef) codegen as desired.
0081   class Twine {
0082     /// NodeKind - Represent the type of an argument.
0083     enum NodeKind : unsigned char {
0084       /// An empty string; the result of concatenating anything with it is also
0085       /// empty.
0086       NullKind,
0087 
0088       /// The empty string.
0089       EmptyKind,
0090 
0091       /// A pointer to a Twine instance.
0092       TwineKind,
0093 
0094       /// A pointer to a C string instance.
0095       CStringKind,
0096 
0097       /// A pointer to an std::string instance.
0098       StdStringKind,
0099 
0100       /// A Pointer and Length representation. Used for std::string_view,
0101       /// StringRef, and SmallString.  Can't use a StringRef here
0102       /// because they are not trivally constructible.
0103       PtrAndLengthKind,
0104 
0105       /// A pointer and length representation that's also null-terminated.
0106       /// Guaranteed to be constructed from a compile-time string literal.
0107       StringLiteralKind,
0108 
0109       /// A pointer to a formatv_object_base instance.
0110       FormatvObjectKind,
0111 
0112       /// A char value, to render as a character.
0113       CharKind,
0114 
0115       /// An unsigned int value, to render as an unsigned decimal integer.
0116       DecUIKind,
0117 
0118       /// An int value, to render as a signed decimal integer.
0119       DecIKind,
0120 
0121       /// A pointer to an unsigned long value, to render as an unsigned decimal
0122       /// integer.
0123       DecULKind,
0124 
0125       /// A pointer to a long value, to render as a signed decimal integer.
0126       DecLKind,
0127 
0128       /// A pointer to an unsigned long long value, to render as an unsigned
0129       /// decimal integer.
0130       DecULLKind,
0131 
0132       /// A pointer to a long long value, to render as a signed decimal integer.
0133       DecLLKind,
0134 
0135       /// A pointer to a uint64_t value, to render as an unsigned hexadecimal
0136       /// integer.
0137       UHexKind
0138     };
0139 
0140     union Child
0141     {
0142       const Twine *twine;
0143       const char *cString;
0144       const std::string *stdString;
0145       struct {
0146         const char *ptr;
0147         size_t length;
0148       } ptrAndLength;
0149       const formatv_object_base *formatvObject;
0150       char character;
0151       unsigned int decUI;
0152       int decI;
0153       const unsigned long *decUL;
0154       const long *decL;
0155       const unsigned long long *decULL;
0156       const long long *decLL;
0157       const uint64_t *uHex;
0158     };
0159 
0160     /// LHS - The prefix in the concatenation, which may be uninitialized for
0161     /// Null or Empty kinds.
0162     Child LHS;
0163 
0164     /// RHS - The suffix in the concatenation, which may be uninitialized for
0165     /// Null or Empty kinds.
0166     Child RHS;
0167 
0168     /// LHSKind - The NodeKind of the left hand side, \see getLHSKind().
0169     NodeKind LHSKind = EmptyKind;
0170 
0171     /// RHSKind - The NodeKind of the right hand side, \see getRHSKind().
0172     NodeKind RHSKind = EmptyKind;
0173 
0174     /// Construct a nullary twine; the kind must be NullKind or EmptyKind.
0175     explicit Twine(NodeKind Kind) : LHSKind(Kind) {
0176       assert(isNullary() && "Invalid kind!");
0177     }
0178 
0179     /// Construct a binary twine.
0180     explicit Twine(const Twine &LHS, const Twine &RHS)
0181         : LHSKind(TwineKind), RHSKind(TwineKind) {
0182       this->LHS.twine = &LHS;
0183       this->RHS.twine = &RHS;
0184       assert(isValid() && "Invalid twine!");
0185     }
0186 
0187     /// Construct a twine from explicit values.
0188     explicit Twine(Child LHS, NodeKind LHSKind, Child RHS, NodeKind RHSKind)
0189         : LHS(LHS), RHS(RHS), LHSKind(LHSKind), RHSKind(RHSKind) {
0190       assert(isValid() && "Invalid twine!");
0191     }
0192 
0193     /// Check for the null twine.
0194     bool isNull() const {
0195       return getLHSKind() == NullKind;
0196     }
0197 
0198     /// Check for the empty twine.
0199     bool isEmpty() const {
0200       return getLHSKind() == EmptyKind;
0201     }
0202 
0203     /// Check if this is a nullary twine (null or empty).
0204     bool isNullary() const {
0205       return isNull() || isEmpty();
0206     }
0207 
0208     /// Check if this is a unary twine.
0209     bool isUnary() const {
0210       return getRHSKind() == EmptyKind && !isNullary();
0211     }
0212 
0213     /// Check if this is a binary twine.
0214     bool isBinary() const {
0215       return getLHSKind() != NullKind && getRHSKind() != EmptyKind;
0216     }
0217 
0218     /// Check if this is a valid twine (satisfying the invariants on
0219     /// order and number of arguments).
0220     bool isValid() const {
0221       // Nullary twines always have Empty on the RHS.
0222       if (isNullary() && getRHSKind() != EmptyKind)
0223         return false;
0224 
0225       // Null should never appear on the RHS.
0226       if (getRHSKind() == NullKind)
0227         return false;
0228 
0229       // The RHS cannot be non-empty if the LHS is empty.
0230       if (getRHSKind() != EmptyKind && getLHSKind() == EmptyKind)
0231         return false;
0232 
0233       // A twine child should always be binary.
0234       if (getLHSKind() == TwineKind &&
0235           !LHS.twine->isBinary())
0236         return false;
0237       if (getRHSKind() == TwineKind &&
0238           !RHS.twine->isBinary())
0239         return false;
0240 
0241       return true;
0242     }
0243 
0244     /// Get the NodeKind of the left-hand side.
0245     NodeKind getLHSKind() const { return LHSKind; }
0246 
0247     /// Get the NodeKind of the right-hand side.
0248     NodeKind getRHSKind() const { return RHSKind; }
0249 
0250     /// Print one child from a twine.
0251     void printOneChild(raw_ostream &OS, Child Ptr, NodeKind Kind) const;
0252 
0253     /// Print the representation of one child from a twine.
0254     void printOneChildRepr(raw_ostream &OS, Child Ptr,
0255                            NodeKind Kind) const;
0256 
0257   public:
0258     /// @name Constructors
0259     /// @{
0260 
0261     /// Construct from an empty string.
0262     /*implicit*/ Twine() {
0263       assert(isValid() && "Invalid twine!");
0264     }
0265 
0266     Twine(const Twine &) = default;
0267 
0268     /// Construct from a C string.
0269     ///
0270     /// We take care here to optimize "" into the empty twine -- this will be
0271     /// optimized out for string constants. This allows Twine arguments have
0272     /// default "" values, without introducing unnecessary string constants.
0273     /*implicit*/ Twine(const char *Str) {
0274       if (Str[0] != '\0') {
0275         LHS.cString = Str;
0276         LHSKind = CStringKind;
0277       } else
0278         LHSKind = EmptyKind;
0279 
0280       assert(isValid() && "Invalid twine!");
0281     }
0282     /// Delete the implicit conversion from nullptr as Twine(const char *)
0283     /// cannot take nullptr.
0284     /*implicit*/ Twine(std::nullptr_t) = delete;
0285 
0286     /// Construct from an std::string.
0287     /*implicit*/ Twine(const std::string &Str) : LHSKind(StdStringKind) {
0288       LHS.stdString = &Str;
0289       assert(isValid() && "Invalid twine!");
0290     }
0291 
0292     /// Construct from an std::string_view by converting it to a pointer and
0293     /// length.  This handles string_views on a pure API basis, and avoids
0294     /// storing one (or a pointer to one) inside a Twine, which avoids problems
0295     /// when mixing code compiled under various C++ standards.
0296     /*implicit*/ Twine(const std::string_view &Str)
0297         : LHSKind(PtrAndLengthKind) {
0298       LHS.ptrAndLength.ptr = Str.data();
0299       LHS.ptrAndLength.length = Str.length();
0300       assert(isValid() && "Invalid twine!");
0301     }
0302 
0303     /// Construct from a StringRef.
0304     /*implicit*/ Twine(const StringRef &Str) : LHSKind(PtrAndLengthKind) {
0305       LHS.ptrAndLength.ptr = Str.data();
0306       LHS.ptrAndLength.length = Str.size();
0307       assert(isValid() && "Invalid twine!");
0308     }
0309 
0310     /// Construct from a StringLiteral.
0311     /*implicit*/ Twine(const StringLiteral &Str)
0312         : LHSKind(StringLiteralKind) {
0313       LHS.ptrAndLength.ptr = Str.data();
0314       LHS.ptrAndLength.length = Str.size();
0315       assert(isValid() && "Invalid twine!");
0316     }
0317 
0318     /// Construct from a SmallString.
0319     /*implicit*/ Twine(const SmallVectorImpl<char> &Str)
0320         : LHSKind(PtrAndLengthKind) {
0321       LHS.ptrAndLength.ptr = Str.data();
0322       LHS.ptrAndLength.length = Str.size();
0323       assert(isValid() && "Invalid twine!");
0324     }
0325 
0326     /// Construct from a formatv_object_base.
0327     /*implicit*/ Twine(const formatv_object_base &Fmt)
0328         : LHSKind(FormatvObjectKind) {
0329       LHS.formatvObject = &Fmt;
0330       assert(isValid() && "Invalid twine!");
0331     }
0332 
0333     /// Construct from a char.
0334     explicit Twine(char Val) : LHSKind(CharKind) {
0335       LHS.character = Val;
0336     }
0337 
0338     /// Construct from a signed char.
0339     explicit Twine(signed char Val) : LHSKind(CharKind) {
0340       LHS.character = static_cast<char>(Val);
0341     }
0342 
0343     /// Construct from an unsigned char.
0344     explicit Twine(unsigned char Val) : LHSKind(CharKind) {
0345       LHS.character = static_cast<char>(Val);
0346     }
0347 
0348     /// Construct a twine to print \p Val as an unsigned decimal integer.
0349     explicit Twine(unsigned Val) : LHSKind(DecUIKind) {
0350       LHS.decUI = Val;
0351     }
0352 
0353     /// Construct a twine to print \p Val as a signed decimal integer.
0354     explicit Twine(int Val) : LHSKind(DecIKind) {
0355       LHS.decI = Val;
0356     }
0357 
0358     /// Construct a twine to print \p Val as an unsigned decimal integer.
0359     explicit Twine(const unsigned long &Val) : LHSKind(DecULKind) {
0360       LHS.decUL = &Val;
0361     }
0362 
0363     /// Construct a twine to print \p Val as a signed decimal integer.
0364     explicit Twine(const long &Val) : LHSKind(DecLKind) {
0365       LHS.decL = &Val;
0366     }
0367 
0368     /// Construct a twine to print \p Val as an unsigned decimal integer.
0369     explicit Twine(const unsigned long long &Val) : LHSKind(DecULLKind) {
0370       LHS.decULL = &Val;
0371     }
0372 
0373     /// Construct a twine to print \p Val as a signed decimal integer.
0374     explicit Twine(const long long &Val) : LHSKind(DecLLKind) {
0375       LHS.decLL = &Val;
0376     }
0377 
0378     // FIXME: Unfortunately, to make sure this is as efficient as possible we
0379     // need extra binary constructors from particular types. We can't rely on
0380     // the compiler to be smart enough to fold operator+()/concat() down to the
0381     // right thing. Yet.
0382 
0383     /// Construct as the concatenation of a C string and a StringRef.
0384     /*implicit*/ Twine(const char *LHS, const StringRef &RHS)
0385         : LHSKind(CStringKind), RHSKind(PtrAndLengthKind) {
0386       this->LHS.cString = LHS;
0387       this->RHS.ptrAndLength.ptr = RHS.data();
0388       this->RHS.ptrAndLength.length = RHS.size();
0389       assert(isValid() && "Invalid twine!");
0390     }
0391 
0392     /// Construct as the concatenation of a StringRef and a C string.
0393     /*implicit*/ Twine(const StringRef &LHS, const char *RHS)
0394         : LHSKind(PtrAndLengthKind), RHSKind(CStringKind) {
0395       this->LHS.ptrAndLength.ptr = LHS.data();
0396       this->LHS.ptrAndLength.length = LHS.size();
0397       this->RHS.cString = RHS;
0398       assert(isValid() && "Invalid twine!");
0399     }
0400 
0401     /// Since the intended use of twines is as temporary objects, assignments
0402     /// when concatenating might cause undefined behavior or stack corruptions
0403     Twine &operator=(const Twine &) = delete;
0404 
0405     /// Create a 'null' string, which is an empty string that always
0406     /// concatenates to form another empty string.
0407     static Twine createNull() {
0408       return Twine(NullKind);
0409     }
0410 
0411     /// @}
0412     /// @name Numeric Conversions
0413     /// @{
0414 
0415     // Construct a twine to print \p Val as an unsigned hexadecimal integer.
0416     static Twine utohexstr(const uint64_t &Val) {
0417       Child LHS, RHS;
0418       LHS.uHex = &Val;
0419       RHS.twine = nullptr;
0420       return Twine(LHS, UHexKind, RHS, EmptyKind);
0421     }
0422 
0423     /// @}
0424     /// @name Predicate Operations
0425     /// @{
0426 
0427     /// Check if this twine is trivially empty; a false return value does not
0428     /// necessarily mean the twine is empty.
0429     bool isTriviallyEmpty() const {
0430       return isNullary();
0431     }
0432 
0433     /// Check if this twine is guaranteed to refer to single string literal.
0434     bool isSingleStringLiteral() const {
0435       return isUnary() && getLHSKind() == StringLiteralKind;
0436     }
0437 
0438     /// Return true if this twine can be dynamically accessed as a single
0439     /// StringRef value with getSingleStringRef().
0440     bool isSingleStringRef() const {
0441       if (getRHSKind() != EmptyKind) return false;
0442 
0443       switch (getLHSKind()) {
0444       case EmptyKind:
0445       case CStringKind:
0446       case StdStringKind:
0447       case PtrAndLengthKind:
0448       case StringLiteralKind:
0449         return true;
0450       default:
0451         return false;
0452       }
0453     }
0454 
0455     /// @}
0456     /// @name String Operations
0457     /// @{
0458 
0459     Twine concat(const Twine &Suffix) const;
0460 
0461     /// @}
0462     /// @name Output & Conversion.
0463     /// @{
0464 
0465     /// Return the twine contents as a std::string.
0466     std::string str() const;
0467 
0468     /// Append the concatenated string into the given SmallString or SmallVector.
0469     void toVector(SmallVectorImpl<char> &Out) const;
0470 
0471     /// This returns the twine as a single StringRef.  This method is only valid
0472     /// if isSingleStringRef() is true.
0473     StringRef getSingleStringRef() const {
0474       assert(isSingleStringRef() &&"This cannot be had as a single stringref!");
0475       switch (getLHSKind()) {
0476       default: llvm_unreachable("Out of sync with isSingleStringRef");
0477       case EmptyKind:
0478         return StringRef();
0479       case CStringKind:
0480         return StringRef(LHS.cString);
0481       case StdStringKind:
0482         return StringRef(*LHS.stdString);
0483       case PtrAndLengthKind:
0484       case StringLiteralKind:
0485         return StringRef(LHS.ptrAndLength.ptr, LHS.ptrAndLength.length);
0486       }
0487     }
0488 
0489     /// This returns the twine as a single StringRef if it can be
0490     /// represented as such. Otherwise the twine is written into the given
0491     /// SmallVector and a StringRef to the SmallVector's data is returned.
0492     StringRef toStringRef(SmallVectorImpl<char> &Out) const {
0493       if (isSingleStringRef())
0494         return getSingleStringRef();
0495       toVector(Out);
0496       return StringRef(Out.data(), Out.size());
0497     }
0498 
0499     /// This returns the twine as a single null terminated StringRef if it
0500     /// can be represented as such. Otherwise the twine is written into the
0501     /// given SmallVector and a StringRef to the SmallVector's data is returned.
0502     ///
0503     /// The returned StringRef's size does not include the null terminator.
0504     StringRef toNullTerminatedStringRef(SmallVectorImpl<char> &Out) const;
0505 
0506     /// Write the concatenated string represented by this twine to the
0507     /// stream \p OS.
0508     void print(raw_ostream &OS) const;
0509 
0510     /// Dump the concatenated string represented by this twine to stderr.
0511     void dump() const;
0512 
0513     /// Write the representation of this twine to the stream \p OS.
0514     void printRepr(raw_ostream &OS) const;
0515 
0516     /// Dump the representation of this twine to stderr.
0517     void dumpRepr() const;
0518 
0519     /// @}
0520   };
0521 
0522   /// @name Twine Inline Implementations
0523   /// @{
0524 
0525   inline Twine Twine::concat(const Twine &Suffix) const {
0526     // Concatenation with null is null.
0527     if (isNull() || Suffix.isNull())
0528       return Twine(NullKind);
0529 
0530     // Concatenation with empty yields the other side.
0531     if (isEmpty())
0532       return Suffix;
0533     if (Suffix.isEmpty())
0534       return *this;
0535 
0536     // Otherwise we need to create a new node, taking care to fold in unary
0537     // twines.
0538     Child NewLHS, NewRHS;
0539     NewLHS.twine = this;
0540     NewRHS.twine = &Suffix;
0541     NodeKind NewLHSKind = TwineKind, NewRHSKind = TwineKind;
0542     if (isUnary()) {
0543       NewLHS = LHS;
0544       NewLHSKind = getLHSKind();
0545     }
0546     if (Suffix.isUnary()) {
0547       NewRHS = Suffix.LHS;
0548       NewRHSKind = Suffix.getLHSKind();
0549     }
0550 
0551     return Twine(NewLHS, NewLHSKind, NewRHS, NewRHSKind);
0552   }
0553 
0554   inline Twine operator+(const Twine &LHS, const Twine &RHS) {
0555     return LHS.concat(RHS);
0556   }
0557 
0558   /// Additional overload to guarantee simplified codegen; this is equivalent to
0559   /// concat().
0560 
0561   inline Twine operator+(const char *LHS, const StringRef &RHS) {
0562     return Twine(LHS, RHS);
0563   }
0564 
0565   /// Additional overload to guarantee simplified codegen; this is equivalent to
0566   /// concat().
0567 
0568   inline Twine operator+(const StringRef &LHS, const char *RHS) {
0569     return Twine(LHS, RHS);
0570   }
0571 
0572   inline raw_ostream &operator<<(raw_ostream &OS, const Twine &RHS) {
0573     RHS.print(OS);
0574     return OS;
0575   }
0576 
0577   /// @}
0578 
0579 } // end namespace llvm
0580 
0581 #endif // LLVM_ADT_TWINE_H