1 //===-- Twine.h - Fast Temporary String Concatenation -----------*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 #ifndef LLVM_ADT_TWINE_H 11 #define LLVM_ADT_TWINE_H 12 13 #include "llvm/ADT/StringRef.h" 14 #include "llvm/Support/DataTypes.h" 15 #include "llvm/Support/ErrorHandling.h" 16 #include <cassert> 17 #include <string> 18 19 namespace llvm { 20 template <typename T> 21 class SmallVectorImpl; 22 class StringRef; 23 class raw_ostream; 24 25 /// Twine - A lightweight data structure for efficiently representing the 26 /// concatenation of temporary values as strings. 27 /// 28 /// A Twine is a kind of rope, it represents a concatenated string using a 29 /// binary-tree, where the string is the preorder of the nodes. Since the 30 /// Twine can be efficiently rendered into a buffer when its result is used, 31 /// it avoids the cost of generating temporary values for intermediate string 32 /// results -- particularly in cases when the Twine result is never 33 /// required. By explicitly tracking the type of leaf nodes, we can also avoid 34 /// the creation of temporary strings for conversions operations (such as 35 /// appending an integer to a string). 36 /// 37 /// A Twine is not intended for use directly and should not be stored, its 38 /// implementation relies on the ability to store pointers to temporary stack 39 /// objects which may be deallocated at the end of a statement. Twines should 40 /// only be used accepted as const references in arguments, when an API wishes 41 /// to accept possibly-concatenated strings. 42 /// 43 /// Twines support a special 'null' value, which always concatenates to form 44 /// itself, and renders as an empty string. This can be returned from APIs to 45 /// effectively nullify any concatenations performed on the result. 46 /// 47 /// \b Implementation 48 /// 49 /// Given the nature of a Twine, it is not possible for the Twine's 50 /// concatenation method to construct interior nodes; the result must be 51 /// represented inside the returned value. For this reason a Twine object 52 /// actually holds two values, the left- and right-hand sides of a 53 /// concatenation. We also have nullary Twine objects, which are effectively 54 /// sentinel values that represent empty strings. 55 /// 56 /// Thus, a Twine can effectively have zero, one, or two children. The \see 57 /// isNullary(), \see isUnary(), and \see isBinary() predicates exist for 58 /// testing the number of children. 59 /// 60 /// We maintain a number of invariants on Twine objects (FIXME: Why): 61 /// - Nullary twines are always represented with their Kind on the left-hand 62 /// side, and the Empty kind on the right-hand side. 63 /// - Unary twines are always represented with the value on the left-hand 64 /// side, and the Empty kind on the right-hand side. 65 /// - If a Twine has another Twine as a child, that child should always be 66 /// binary (otherwise it could have been folded into the parent). 67 /// 68 /// These invariants are check by \see isValid(). 69 /// 70 /// \b Efficiency Considerations 71 /// 72 /// The Twine is designed to yield efficient and small code for common 73 /// situations. For this reason, the concat() method is inlined so that 74 /// concatenations of leaf nodes can be optimized into stores directly into a 75 /// single stack allocated object. 76 /// 77 /// In practice, not all compilers can be trusted to optimize concat() fully, 78 /// so we provide two additional methods (and accompanying operator+ 79 /// overloads) to guarantee that particularly important cases (cstring plus 80 /// StringRef) codegen as desired. 81 class Twine { 82 /// NodeKind - Represent the type of an argument. 83 enum NodeKind : unsigned char { 84 /// An empty string; the result of concatenating anything with it is also 85 /// empty. 86 NullKind, 87 88 /// The empty string. 89 EmptyKind, 90 91 /// A pointer to a Twine instance. 92 TwineKind, 93 94 /// A pointer to a C string instance. 95 CStringKind, 96 97 /// A pointer to an std::string instance. 98 StdStringKind, 99 100 /// A pointer to a StringRef instance. 101 StringRefKind, 102 103 /// A char value reinterpreted as a pointer, to render as a character. 104 CharKind, 105 106 /// An unsigned int value reinterpreted as a pointer, to render as an 107 /// unsigned decimal integer. 108 DecUIKind, 109 110 /// An int value reinterpreted as a pointer, to render as a signed 111 /// decimal integer. 112 DecIKind, 113 114 /// A pointer to an unsigned long value, to render as an unsigned decimal 115 /// integer. 116 DecULKind, 117 118 /// A pointer to a long value, to render as a signed decimal integer. 119 DecLKind, 120 121 /// A pointer to an unsigned long long value, to render as an unsigned 122 /// decimal integer. 123 DecULLKind, 124 125 /// A pointer to a long long value, to render as a signed decimal integer. 126 DecLLKind, 127 128 /// A pointer to a uint64_t value, to render as an unsigned hexadecimal 129 /// integer. 130 UHexKind 131 }; 132 133 union Child 134 { 135 const Twine *twine; 136 const char *cString; 137 const std::string *stdString; 138 const StringRef *stringRef; 139 char character; 140 unsigned int decUI; 141 int decI; 142 const unsigned long *decUL; 143 const long *decL; 144 const unsigned long long *decULL; 145 const long long *decLL; 146 const uint64_t *uHex; 147 }; 148 149 private: 150 /// LHS - The prefix in the concatenation, which may be uninitialized for 151 /// Null or Empty kinds. 152 Child LHS; 153 /// RHS - The suffix in the concatenation, which may be uninitialized for 154 /// Null or Empty kinds. 155 Child RHS; 156 /// LHSKind - The NodeKind of the left hand side, \see getLHSKind(). 157 NodeKind LHSKind; 158 /// RHSKind - The NodeKind of the right hand side, \see getRHSKind(). 159 NodeKind RHSKind; 160 161 private: 162 /// Construct a nullary twine; the kind must be NullKind or EmptyKind. Twine(NodeKind Kind)163 explicit Twine(NodeKind Kind) 164 : LHSKind(Kind), RHSKind(EmptyKind) { 165 assert(isNullary() && "Invalid kind!"); 166 } 167 168 /// Construct a binary twine. Twine(const Twine & LHS,const Twine & RHS)169 explicit Twine(const Twine &LHS, const Twine &RHS) 170 : LHSKind(TwineKind), RHSKind(TwineKind) { 171 this->LHS.twine = &LHS; 172 this->RHS.twine = &RHS; 173 assert(isValid() && "Invalid twine!"); 174 } 175 176 /// Construct a twine from explicit values. Twine(Child LHS,NodeKind LHSKind,Child RHS,NodeKind RHSKind)177 explicit Twine(Child LHS, NodeKind LHSKind, Child RHS, NodeKind RHSKind) 178 : LHS(LHS), RHS(RHS), LHSKind(LHSKind), RHSKind(RHSKind) { 179 assert(isValid() && "Invalid twine!"); 180 } 181 182 /// Since the intended use of twines is as temporary objects, assignments 183 /// when concatenating might cause undefined behavior or stack corruptions 184 Twine &operator=(const Twine &Other) = delete; 185 186 /// isNull - Check for the null twine. isNull()187 bool isNull() const { 188 return getLHSKind() == NullKind; 189 } 190 191 /// isEmpty - Check for the empty twine. isEmpty()192 bool isEmpty() const { 193 return getLHSKind() == EmptyKind; 194 } 195 196 /// isNullary - Check if this is a nullary twine (null or empty). isNullary()197 bool isNullary() const { 198 return isNull() || isEmpty(); 199 } 200 201 /// isUnary - Check if this is a unary twine. isUnary()202 bool isUnary() const { 203 return getRHSKind() == EmptyKind && !isNullary(); 204 } 205 206 /// isBinary - Check if this is a binary twine. isBinary()207 bool isBinary() const { 208 return getLHSKind() != NullKind && getRHSKind() != EmptyKind; 209 } 210 211 /// isValid - Check if this is a valid twine (satisfying the invariants on 212 /// order and number of arguments). isValid()213 bool isValid() const { 214 // Nullary twines always have Empty on the RHS. 215 if (isNullary() && getRHSKind() != EmptyKind) 216 return false; 217 218 // Null should never appear on the RHS. 219 if (getRHSKind() == NullKind) 220 return false; 221 222 // The RHS cannot be non-empty if the LHS is empty. 223 if (getRHSKind() != EmptyKind && getLHSKind() == EmptyKind) 224 return false; 225 226 // A twine child should always be binary. 227 if (getLHSKind() == TwineKind && 228 !LHS.twine->isBinary()) 229 return false; 230 if (getRHSKind() == TwineKind && 231 !RHS.twine->isBinary()) 232 return false; 233 234 return true; 235 } 236 237 /// getLHSKind - Get the NodeKind of the left-hand side. getLHSKind()238 NodeKind getLHSKind() const { return LHSKind; } 239 240 /// getRHSKind - Get the NodeKind of the right-hand side. getRHSKind()241 NodeKind getRHSKind() const { return RHSKind; } 242 243 /// printOneChild - Print one child from a twine. 244 void printOneChild(raw_ostream &OS, Child Ptr, NodeKind Kind) const; 245 246 /// printOneChildRepr - Print the representation of one child from a twine. 247 void printOneChildRepr(raw_ostream &OS, Child Ptr, 248 NodeKind Kind) const; 249 250 public: 251 /// @name Constructors 252 /// @{ 253 254 /// Construct from an empty string. Twine()255 /*implicit*/ Twine() : LHSKind(EmptyKind), RHSKind(EmptyKind) { 256 assert(isValid() && "Invalid twine!"); 257 } 258 259 Twine(const Twine &) = default; 260 261 /// Construct from a C string. 262 /// 263 /// We take care here to optimize "" into the empty twine -- this will be 264 /// optimized out for string constants. This allows Twine arguments have 265 /// default "" values, without introducing unnecessary string constants. Twine(const char * Str)266 /*implicit*/ Twine(const char *Str) 267 : RHSKind(EmptyKind) { 268 if (Str[0] != '\0') { 269 LHS.cString = Str; 270 LHSKind = CStringKind; 271 } else 272 LHSKind = EmptyKind; 273 274 assert(isValid() && "Invalid twine!"); 275 } 276 277 /// Construct from an std::string. Twine(const std::string & Str)278 /*implicit*/ Twine(const std::string &Str) 279 : LHSKind(StdStringKind), RHSKind(EmptyKind) { 280 LHS.stdString = &Str; 281 assert(isValid() && "Invalid twine!"); 282 } 283 284 /// Construct from a StringRef. Twine(const StringRef & Str)285 /*implicit*/ Twine(const StringRef &Str) 286 : LHSKind(StringRefKind), RHSKind(EmptyKind) { 287 LHS.stringRef = &Str; 288 assert(isValid() && "Invalid twine!"); 289 } 290 291 /// Construct from a char. Twine(char Val)292 explicit Twine(char Val) 293 : LHSKind(CharKind), RHSKind(EmptyKind) { 294 LHS.character = Val; 295 } 296 297 /// Construct from a signed char. Twine(signed char Val)298 explicit Twine(signed char Val) 299 : LHSKind(CharKind), RHSKind(EmptyKind) { 300 LHS.character = static_cast<char>(Val); 301 } 302 303 /// Construct from an unsigned char. Twine(unsigned char Val)304 explicit Twine(unsigned char Val) 305 : LHSKind(CharKind), RHSKind(EmptyKind) { 306 LHS.character = static_cast<char>(Val); 307 } 308 309 /// Construct a twine to print \p Val as an unsigned decimal integer. Twine(unsigned Val)310 explicit Twine(unsigned Val) 311 : LHSKind(DecUIKind), RHSKind(EmptyKind) { 312 LHS.decUI = Val; 313 } 314 315 /// Construct a twine to print \p Val as a signed decimal integer. Twine(int Val)316 explicit Twine(int Val) 317 : LHSKind(DecIKind), RHSKind(EmptyKind) { 318 LHS.decI = Val; 319 } 320 321 /// Construct a twine to print \p Val as an unsigned decimal integer. Twine(const unsigned long & Val)322 explicit Twine(const unsigned long &Val) 323 : LHSKind(DecULKind), RHSKind(EmptyKind) { 324 LHS.decUL = &Val; 325 } 326 327 /// Construct a twine to print \p Val as a signed decimal integer. Twine(const long & Val)328 explicit Twine(const long &Val) 329 : LHSKind(DecLKind), RHSKind(EmptyKind) { 330 LHS.decL = &Val; 331 } 332 333 /// Construct a twine to print \p Val as an unsigned decimal integer. Twine(const unsigned long long & Val)334 explicit Twine(const unsigned long long &Val) 335 : LHSKind(DecULLKind), RHSKind(EmptyKind) { 336 LHS.decULL = &Val; 337 } 338 339 /// Construct a twine to print \p Val as a signed decimal integer. Twine(const long long & Val)340 explicit Twine(const long long &Val) 341 : LHSKind(DecLLKind), RHSKind(EmptyKind) { 342 LHS.decLL = &Val; 343 } 344 345 // FIXME: Unfortunately, to make sure this is as efficient as possible we 346 // need extra binary constructors from particular types. We can't rely on 347 // the compiler to be smart enough to fold operator+()/concat() down to the 348 // right thing. Yet. 349 350 /// Construct as the concatenation of a C string and a StringRef. Twine(const char * LHS,const StringRef & RHS)351 /*implicit*/ Twine(const char *LHS, const StringRef &RHS) 352 : LHSKind(CStringKind), RHSKind(StringRefKind) { 353 this->LHS.cString = LHS; 354 this->RHS.stringRef = &RHS; 355 assert(isValid() && "Invalid twine!"); 356 } 357 358 /// Construct as the concatenation of a StringRef and a C string. Twine(const StringRef & LHS,const char * RHS)359 /*implicit*/ Twine(const StringRef &LHS, const char *RHS) 360 : LHSKind(StringRefKind), RHSKind(CStringKind) { 361 this->LHS.stringRef = &LHS; 362 this->RHS.cString = RHS; 363 assert(isValid() && "Invalid twine!"); 364 } 365 366 /// Create a 'null' string, which is an empty string that always 367 /// concatenates to form another empty string. createNull()368 static Twine createNull() { 369 return Twine(NullKind); 370 } 371 372 /// @} 373 /// @name Numeric Conversions 374 /// @{ 375 376 // Construct a twine to print \p Val as an unsigned hexadecimal integer. utohexstr(const uint64_t & Val)377 static Twine utohexstr(const uint64_t &Val) { 378 Child LHS, RHS; 379 LHS.uHex = &Val; 380 RHS.twine = nullptr; 381 return Twine(LHS, UHexKind, RHS, EmptyKind); 382 } 383 384 /// @} 385 /// @name Predicate Operations 386 /// @{ 387 388 /// isTriviallyEmpty - Check if this twine is trivially empty; a false 389 /// return value does not necessarily mean the twine is empty. isTriviallyEmpty()390 bool isTriviallyEmpty() const { 391 return isNullary(); 392 } 393 394 /// isSingleStringRef - Return true if this twine can be dynamically 395 /// accessed as a single StringRef value with getSingleStringRef(). isSingleStringRef()396 bool isSingleStringRef() const { 397 if (getRHSKind() != EmptyKind) return false; 398 399 switch (getLHSKind()) { 400 case EmptyKind: 401 case CStringKind: 402 case StdStringKind: 403 case StringRefKind: 404 return true; 405 default: 406 return false; 407 } 408 } 409 410 /// @} 411 /// @name String Operations 412 /// @{ 413 414 Twine concat(const Twine &Suffix) const; 415 416 /// @} 417 /// @name Output & Conversion. 418 /// @{ 419 420 /// str - Return the twine contents as a std::string. 421 std::string str() const; 422 423 /// toVector - Write the concatenated string into the given SmallString or 424 /// SmallVector. 425 void toVector(SmallVectorImpl<char> &Out) const; 426 427 /// getSingleStringRef - This returns the twine as a single StringRef. This 428 /// method is only valid if isSingleStringRef() is true. getSingleStringRef()429 StringRef getSingleStringRef() const { 430 assert(isSingleStringRef() &&"This cannot be had as a single stringref!"); 431 switch (getLHSKind()) { 432 default: llvm_unreachable("Out of sync with isSingleStringRef"); 433 case EmptyKind: return StringRef(); 434 case CStringKind: return StringRef(LHS.cString); 435 case StdStringKind: return StringRef(*LHS.stdString); 436 case StringRefKind: return *LHS.stringRef; 437 } 438 } 439 440 /// toStringRef - This returns the twine as a single StringRef if it can be 441 /// represented as such. Otherwise the twine is written into the given 442 /// SmallVector and a StringRef to the SmallVector's data is returned. 443 StringRef toStringRef(SmallVectorImpl<char> &Out) const; 444 445 /// toNullTerminatedStringRef - This returns the twine as a single null 446 /// terminated StringRef if it can be represented as such. Otherwise the 447 /// twine is written into the given SmallVector and a StringRef to the 448 /// SmallVector's data is returned. 449 /// 450 /// The returned StringRef's size does not include the null terminator. 451 StringRef toNullTerminatedStringRef(SmallVectorImpl<char> &Out) const; 452 453 /// Write the concatenated string represented by this twine to the 454 /// stream \p OS. 455 void print(raw_ostream &OS) const; 456 457 /// Dump the concatenated string represented by this twine to stderr. 458 void dump() const; 459 460 /// Write the representation of this twine to the stream \p OS. 461 void printRepr(raw_ostream &OS) const; 462 463 /// Dump the representation of this twine to stderr. 464 void dumpRepr() const; 465 466 /// @} 467 }; 468 469 /// @name Twine Inline Implementations 470 /// @{ 471 concat(const Twine & Suffix)472 inline Twine Twine::concat(const Twine &Suffix) const { 473 // Concatenation with null is null. 474 if (isNull() || Suffix.isNull()) 475 return Twine(NullKind); 476 477 // Concatenation with empty yields the other side. 478 if (isEmpty()) 479 return Suffix; 480 if (Suffix.isEmpty()) 481 return *this; 482 483 // Otherwise we need to create a new node, taking care to fold in unary 484 // twines. 485 Child NewLHS, NewRHS; 486 NewLHS.twine = this; 487 NewRHS.twine = &Suffix; 488 NodeKind NewLHSKind = TwineKind, NewRHSKind = TwineKind; 489 if (isUnary()) { 490 NewLHS = LHS; 491 NewLHSKind = getLHSKind(); 492 } 493 if (Suffix.isUnary()) { 494 NewRHS = Suffix.LHS; 495 NewRHSKind = Suffix.getLHSKind(); 496 } 497 498 return Twine(NewLHS, NewLHSKind, NewRHS, NewRHSKind); 499 } 500 501 inline Twine operator+(const Twine &LHS, const Twine &RHS) { 502 return LHS.concat(RHS); 503 } 504 505 /// Additional overload to guarantee simplified codegen; this is equivalent to 506 /// concat(). 507 508 inline Twine operator+(const char *LHS, const StringRef &RHS) { 509 return Twine(LHS, RHS); 510 } 511 512 /// Additional overload to guarantee simplified codegen; this is equivalent to 513 /// concat(). 514 515 inline Twine operator+(const StringRef &LHS, const char *RHS) { 516 return Twine(LHS, RHS); 517 } 518 519 inline raw_ostream &operator<<(raw_ostream &OS, const Twine &RHS) { 520 RHS.print(OS); 521 return OS; 522 } 523 524 /// @} 525 } 526 527 #endif 528