APInt.h revision 193323
1//===-- llvm/ADT/APInt.h - For Arbitrary Precision Integer -----*- 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// This file implements a class to represent arbitrary precision integral 11// constant values and operations on them. 12// 13//===----------------------------------------------------------------------===// 14 15#ifndef LLVM_APINT_H 16#define LLVM_APINT_H 17 18#include "llvm/Support/DataTypes.h" 19#include "llvm/Support/MathExtras.h" 20#include <cassert> 21#include <climits> 22#include <cstring> 23#include <string> 24 25namespace llvm { 26 class Serializer; 27 class Deserializer; 28 class FoldingSetNodeID; 29 class raw_ostream; 30 31 template<typename T> 32 class SmallVectorImpl; 33 34 /* An unsigned host type used as a single part of a multi-part 35 bignum. */ 36 typedef uint64_t integerPart; 37 38 const unsigned int host_char_bit = 8; 39 const unsigned int integerPartWidth = host_char_bit * 40 static_cast<unsigned int>(sizeof(integerPart)); 41 42//===----------------------------------------------------------------------===// 43// APInt Class 44//===----------------------------------------------------------------------===// 45 46/// APInt - This class represents arbitrary precision constant integral values. 47/// It is a functional replacement for common case unsigned integer type like 48/// "unsigned", "unsigned long" or "uint64_t", but also allows non-byte-width 49/// integer sizes and large integer value types such as 3-bits, 15-bits, or more 50/// than 64-bits of precision. APInt provides a variety of arithmetic operators 51/// and methods to manipulate integer values of any bit-width. It supports both 52/// the typical integer arithmetic and comparison operations as well as bitwise 53/// manipulation. 54/// 55/// The class has several invariants worth noting: 56/// * All bit, byte, and word positions are zero-based. 57/// * Once the bit width is set, it doesn't change except by the Truncate, 58/// SignExtend, or ZeroExtend operations. 59/// * All binary operators must be on APInt instances of the same bit width. 60/// Attempting to use these operators on instances with different bit 61/// widths will yield an assertion. 62/// * The value is stored canonically as an unsigned value. For operations 63/// where it makes a difference, there are both signed and unsigned variants 64/// of the operation. For example, sdiv and udiv. However, because the bit 65/// widths must be the same, operations such as Mul and Add produce the same 66/// results regardless of whether the values are interpreted as signed or 67/// not. 68/// * In general, the class tries to follow the style of computation that LLVM 69/// uses in its IR. This simplifies its use for LLVM. 70/// 71/// @brief Class for arbitrary precision integers. 72class APInt { 73 unsigned BitWidth; ///< The number of bits in this APInt. 74 75 /// This union is used to store the integer value. When the 76 /// integer bit-width <= 64, it uses VAL, otherwise it uses pVal. 77 union { 78 uint64_t VAL; ///< Used to store the <= 64 bits integer value. 79 uint64_t *pVal; ///< Used to store the >64 bits integer value. 80 }; 81 82 /// This enum is used to hold the constants we needed for APInt. 83 enum { 84 /// Bits in a word 85 APINT_BITS_PER_WORD = static_cast<unsigned int>(sizeof(uint64_t)) * 86 CHAR_BIT, 87 /// Byte size of a word 88 APINT_WORD_SIZE = static_cast<unsigned int>(sizeof(uint64_t)) 89 }; 90 91 /// This constructor is used only internally for speed of construction of 92 /// temporaries. It is unsafe for general use so it is not public. 93 /// @brief Fast internal constructor 94 APInt(uint64_t* val, unsigned bits) : BitWidth(bits), pVal(val) { } 95 96 /// @returns true if the number of bits <= 64, false otherwise. 97 /// @brief Determine if this APInt just has one word to store value. 98 bool isSingleWord() const { 99 return BitWidth <= APINT_BITS_PER_WORD; 100 } 101 102 /// @returns the word position for the specified bit position. 103 /// @brief Determine which word a bit is in. 104 static unsigned whichWord(unsigned bitPosition) { 105 return bitPosition / APINT_BITS_PER_WORD; 106 } 107 108 /// @returns the bit position in a word for the specified bit position 109 /// in the APInt. 110 /// @brief Determine which bit in a word a bit is in. 111 static unsigned whichBit(unsigned bitPosition) { 112 return bitPosition % APINT_BITS_PER_WORD; 113 } 114 115 /// This method generates and returns a uint64_t (word) mask for a single 116 /// bit at a specific bit position. This is used to mask the bit in the 117 /// corresponding word. 118 /// @returns a uint64_t with only bit at "whichBit(bitPosition)" set 119 /// @brief Get a single bit mask. 120 static uint64_t maskBit(unsigned bitPosition) { 121 return 1ULL << whichBit(bitPosition); 122 } 123 124 /// This method is used internally to clear the to "N" bits in the high order 125 /// word that are not used by the APInt. This is needed after the most 126 /// significant word is assigned a value to ensure that those bits are 127 /// zero'd out. 128 /// @brief Clear unused high order bits 129 APInt& clearUnusedBits() { 130 // Compute how many bits are used in the final word 131 unsigned wordBits = BitWidth % APINT_BITS_PER_WORD; 132 if (wordBits == 0) 133 // If all bits are used, we want to leave the value alone. This also 134 // avoids the undefined behavior of >> when the shift is the same size as 135 // the word size (64). 136 return *this; 137 138 // Mask out the high bits. 139 uint64_t mask = ~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - wordBits); 140 if (isSingleWord()) 141 VAL &= mask; 142 else 143 pVal[getNumWords() - 1] &= mask; 144 return *this; 145 } 146 147 /// @returns the corresponding word for the specified bit position. 148 /// @brief Get the word corresponding to a bit position 149 uint64_t getWord(unsigned bitPosition) const { 150 return isSingleWord() ? VAL : pVal[whichWord(bitPosition)]; 151 } 152 153 /// This is used by the constructors that take string arguments. 154 /// @brief Convert a char array into an APInt 155 void fromString(unsigned numBits, const char *strStart, unsigned slen, 156 uint8_t radix); 157 158 /// This is used by the toString method to divide by the radix. It simply 159 /// provides a more convenient form of divide for internal use since KnuthDiv 160 /// has specific constraints on its inputs. If those constraints are not met 161 /// then it provides a simpler form of divide. 162 /// @brief An internal division function for dividing APInts. 163 static void divide(const APInt LHS, unsigned lhsWords, 164 const APInt &RHS, unsigned rhsWords, 165 APInt *Quotient, APInt *Remainder); 166 167 /// out-of-line slow case for inline constructor 168 void initSlowCase(unsigned numBits, uint64_t val, bool isSigned); 169 170 /// out-of-line slow case for inline copy constructor 171 void initSlowCase(const APInt& that); 172 173 /// out-of-line slow case for shl 174 APInt shlSlowCase(unsigned shiftAmt) const; 175 176 /// out-of-line slow case for operator& 177 APInt AndSlowCase(const APInt& RHS) const; 178 179 /// out-of-line slow case for operator| 180 APInt OrSlowCase(const APInt& RHS) const; 181 182 /// out-of-line slow case for operator^ 183 APInt XorSlowCase(const APInt& RHS) const; 184 185 /// out-of-line slow case for operator= 186 APInt& AssignSlowCase(const APInt& RHS); 187 188 /// out-of-line slow case for operator== 189 bool EqualSlowCase(const APInt& RHS) const; 190 191 /// out-of-line slow case for operator== 192 bool EqualSlowCase(uint64_t Val) const; 193 194 /// out-of-line slow case for countLeadingZeros 195 unsigned countLeadingZerosSlowCase() const; 196 197 /// out-of-line slow case for countTrailingOnes 198 unsigned countTrailingOnesSlowCase() const; 199 200 /// out-of-line slow case for countPopulation 201 unsigned countPopulationSlowCase() const; 202 203public: 204 /// @name Constructors 205 /// @{ 206 /// If isSigned is true then val is treated as if it were a signed value 207 /// (i.e. as an int64_t) and the appropriate sign extension to the bit width 208 /// will be done. Otherwise, no sign extension occurs (high order bits beyond 209 /// the range of val are zero filled). 210 /// @param numBits the bit width of the constructed APInt 211 /// @param val the initial value of the APInt 212 /// @param isSigned how to treat signedness of val 213 /// @brief Create a new APInt of numBits width, initialized as val. 214 APInt(unsigned numBits, uint64_t val, bool isSigned = false) 215 : BitWidth(numBits), VAL(0) { 216 assert(BitWidth && "bitwidth too small"); 217 if (isSingleWord()) 218 VAL = val; 219 else 220 initSlowCase(numBits, val, isSigned); 221 clearUnusedBits(); 222 } 223 224 /// Note that numWords can be smaller or larger than the corresponding bit 225 /// width but any extraneous bits will be dropped. 226 /// @param numBits the bit width of the constructed APInt 227 /// @param numWords the number of words in bigVal 228 /// @param bigVal a sequence of words to form the initial value of the APInt 229 /// @brief Construct an APInt of numBits width, initialized as bigVal[]. 230 APInt(unsigned numBits, unsigned numWords, const uint64_t bigVal[]); 231 232 /// This constructor interprets the slen characters starting at StrStart as 233 /// a string in the given radix. The interpretation stops when the first 234 /// character that is not suitable for the radix is encountered. Acceptable 235 /// radix values are 2, 8, 10 and 16. It is an error for the value implied by 236 /// the string to require more bits than numBits. 237 /// @param numBits the bit width of the constructed APInt 238 /// @param strStart the start of the string to be interpreted 239 /// @param slen the maximum number of characters to interpret 240 /// @param radix the radix to use for the conversion 241 /// @brief Construct an APInt from a string representation. 242 APInt(unsigned numBits, const char strStart[], unsigned slen, uint8_t radix); 243 244 /// Simply makes *this a copy of that. 245 /// @brief Copy Constructor. 246 APInt(const APInt& that) 247 : BitWidth(that.BitWidth), VAL(0) { 248 assert(BitWidth && "bitwidth too small"); 249 if (isSingleWord()) 250 VAL = that.VAL; 251 else 252 initSlowCase(that); 253 } 254 255 /// @brief Destructor. 256 ~APInt() { 257 if (!isSingleWord()) 258 delete [] pVal; 259 } 260 261 /// Default constructor that creates an uninitialized APInt. This is useful 262 /// for object deserialization (pair this with the static method Read). 263 explicit APInt() : BitWidth(1) {} 264 265 /// Profile - Used to insert APInt objects, or objects that contain APInt 266 /// objects, into FoldingSets. 267 void Profile(FoldingSetNodeID& id) const; 268 269 /// @brief Used by the Bitcode serializer to emit APInts to Bitcode. 270 void Emit(Serializer& S) const; 271 272 /// @brief Used by the Bitcode deserializer to deserialize APInts. 273 void Read(Deserializer& D); 274 275 /// @} 276 /// @name Value Tests 277 /// @{ 278 /// This tests the high bit of this APInt to determine if it is set. 279 /// @returns true if this APInt is negative, false otherwise 280 /// @brief Determine sign of this APInt. 281 bool isNegative() const { 282 return (*this)[BitWidth - 1]; 283 } 284 285 /// This tests the high bit of the APInt to determine if it is unset. 286 /// @brief Determine if this APInt Value is non-negative (>= 0) 287 bool isNonNegative() const { 288 return !isNegative(); 289 } 290 291 /// This tests if the value of this APInt is positive (> 0). Note 292 /// that 0 is not a positive value. 293 /// @returns true if this APInt is positive. 294 /// @brief Determine if this APInt Value is positive. 295 bool isStrictlyPositive() const { 296 return isNonNegative() && (*this) != 0; 297 } 298 299 /// This checks to see if the value has all bits of the APInt are set or not. 300 /// @brief Determine if all bits are set 301 bool isAllOnesValue() const { 302 return countPopulation() == BitWidth; 303 } 304 305 /// This checks to see if the value of this APInt is the maximum unsigned 306 /// value for the APInt's bit width. 307 /// @brief Determine if this is the largest unsigned value. 308 bool isMaxValue() const { 309 return countPopulation() == BitWidth; 310 } 311 312 /// This checks to see if the value of this APInt is the maximum signed 313 /// value for the APInt's bit width. 314 /// @brief Determine if this is the largest signed value. 315 bool isMaxSignedValue() const { 316 return BitWidth == 1 ? VAL == 0 : 317 !isNegative() && countPopulation() == BitWidth - 1; 318 } 319 320 /// This checks to see if the value of this APInt is the minimum unsigned 321 /// value for the APInt's bit width. 322 /// @brief Determine if this is the smallest unsigned value. 323 bool isMinValue() const { 324 return countPopulation() == 0; 325 } 326 327 /// This checks to see if the value of this APInt is the minimum signed 328 /// value for the APInt's bit width. 329 /// @brief Determine if this is the smallest signed value. 330 bool isMinSignedValue() const { 331 return BitWidth == 1 ? VAL == 1 : 332 isNegative() && countPopulation() == 1; 333 } 334 335 /// @brief Check if this APInt has an N-bits unsigned integer value. 336 bool isIntN(unsigned N) const { 337 assert(N && "N == 0 ???"); 338 if (N >= getBitWidth()) 339 return true; 340 341 if (isSingleWord()) 342 return VAL == (VAL & (~0ULL >> (64 - N))); 343 APInt Tmp(N, getNumWords(), pVal); 344 Tmp.zext(getBitWidth()); 345 return Tmp == (*this); 346 } 347 348 /// @brief Check if this APInt has an N-bits signed integer value. 349 bool isSignedIntN(unsigned N) const { 350 assert(N && "N == 0 ???"); 351 return getMinSignedBits() <= N; 352 } 353 354 /// @returns true if the argument APInt value is a power of two > 0. 355 bool isPowerOf2() const; 356 357 /// isSignBit - Return true if this is the value returned by getSignBit. 358 bool isSignBit() const { return isMinSignedValue(); } 359 360 /// This converts the APInt to a boolean value as a test against zero. 361 /// @brief Boolean conversion function. 362 bool getBoolValue() const { 363 return *this != 0; 364 } 365 366 /// getLimitedValue - If this value is smaller than the specified limit, 367 /// return it, otherwise return the limit value. This causes the value 368 /// to saturate to the limit. 369 uint64_t getLimitedValue(uint64_t Limit = ~0ULL) const { 370 return (getActiveBits() > 64 || getZExtValue() > Limit) ? 371 Limit : getZExtValue(); 372 } 373 374 /// @} 375 /// @name Value Generators 376 /// @{ 377 /// @brief Gets maximum unsigned value of APInt for specific bit width. 378 static APInt getMaxValue(unsigned numBits) { 379 return APInt(numBits, 0).set(); 380 } 381 382 /// @brief Gets maximum signed value of APInt for a specific bit width. 383 static APInt getSignedMaxValue(unsigned numBits) { 384 return APInt(numBits, 0).set().clear(numBits - 1); 385 } 386 387 /// @brief Gets minimum unsigned value of APInt for a specific bit width. 388 static APInt getMinValue(unsigned numBits) { 389 return APInt(numBits, 0); 390 } 391 392 /// @brief Gets minimum signed value of APInt for a specific bit width. 393 static APInt getSignedMinValue(unsigned numBits) { 394 return APInt(numBits, 0).set(numBits - 1); 395 } 396 397 /// getSignBit - This is just a wrapper function of getSignedMinValue(), and 398 /// it helps code readability when we want to get a SignBit. 399 /// @brief Get the SignBit for a specific bit width. 400 static APInt getSignBit(unsigned BitWidth) { 401 return getSignedMinValue(BitWidth); 402 } 403 404 /// @returns the all-ones value for an APInt of the specified bit-width. 405 /// @brief Get the all-ones value. 406 static APInt getAllOnesValue(unsigned numBits) { 407 return APInt(numBits, 0).set(); 408 } 409 410 /// @returns the '0' value for an APInt of the specified bit-width. 411 /// @brief Get the '0' value. 412 static APInt getNullValue(unsigned numBits) { 413 return APInt(numBits, 0); 414 } 415 416 /// Get an APInt with the same BitWidth as this APInt, just zero mask 417 /// the low bits and right shift to the least significant bit. 418 /// @returns the high "numBits" bits of this APInt. 419 APInt getHiBits(unsigned numBits) const; 420 421 /// Get an APInt with the same BitWidth as this APInt, just zero mask 422 /// the high bits. 423 /// @returns the low "numBits" bits of this APInt. 424 APInt getLoBits(unsigned numBits) const; 425 426 /// Constructs an APInt value that has a contiguous range of bits set. The 427 /// bits from loBit (inclusive) to hiBit (exclusive) will be set. All other 428 /// bits will be zero. For example, with parameters(32, 0, 16) you would get 429 /// 0x0000FFFF. If hiBit is less than loBit then the set bits "wrap". For 430 /// example, with parameters (32, 28, 4), you would get 0xF000000F. 431 /// @param numBits the intended bit width of the result 432 /// @param loBit the index of the lowest bit set. 433 /// @param hiBit the index of the highest bit set. 434 /// @returns An APInt value with the requested bits set. 435 /// @brief Get a value with a block of bits set. 436 static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit) { 437 assert(hiBit <= numBits && "hiBit out of range"); 438 assert(loBit < numBits && "loBit out of range"); 439 if (hiBit < loBit) 440 return getLowBitsSet(numBits, hiBit) | 441 getHighBitsSet(numBits, numBits-loBit); 442 return getLowBitsSet(numBits, hiBit-loBit).shl(loBit); 443 } 444 445 /// Constructs an APInt value that has the top hiBitsSet bits set. 446 /// @param numBits the bitwidth of the result 447 /// @param hiBitsSet the number of high-order bits set in the result. 448 /// @brief Get a value with high bits set 449 static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet) { 450 assert(hiBitsSet <= numBits && "Too many bits to set!"); 451 // Handle a degenerate case, to avoid shifting by word size 452 if (hiBitsSet == 0) 453 return APInt(numBits, 0); 454 unsigned shiftAmt = numBits - hiBitsSet; 455 // For small values, return quickly 456 if (numBits <= APINT_BITS_PER_WORD) 457 return APInt(numBits, ~0ULL << shiftAmt); 458 return (~APInt(numBits, 0)).shl(shiftAmt); 459 } 460 461 /// Constructs an APInt value that has the bottom loBitsSet bits set. 462 /// @param numBits the bitwidth of the result 463 /// @param loBitsSet the number of low-order bits set in the result. 464 /// @brief Get a value with low bits set 465 static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet) { 466 assert(loBitsSet <= numBits && "Too many bits to set!"); 467 // Handle a degenerate case, to avoid shifting by word size 468 if (loBitsSet == 0) 469 return APInt(numBits, 0); 470 if (loBitsSet == APINT_BITS_PER_WORD) 471 return APInt(numBits, -1ULL); 472 // For small values, return quickly. 473 if (numBits < APINT_BITS_PER_WORD) 474 return APInt(numBits, (1ULL << loBitsSet) - 1); 475 return (~APInt(numBits, 0)).lshr(numBits - loBitsSet); 476 } 477 478 /// The hash value is computed as the sum of the words and the bit width. 479 /// @returns A hash value computed from the sum of the APInt words. 480 /// @brief Get a hash value based on this APInt 481 uint64_t getHashValue() const; 482 483 /// This function returns a pointer to the internal storage of the APInt. 484 /// This is useful for writing out the APInt in binary form without any 485 /// conversions. 486 const uint64_t* getRawData() const { 487 if (isSingleWord()) 488 return &VAL; 489 return &pVal[0]; 490 } 491 492 /// @} 493 /// @name Unary Operators 494 /// @{ 495 /// @returns a new APInt value representing *this incremented by one 496 /// @brief Postfix increment operator. 497 const APInt operator++(int) { 498 APInt API(*this); 499 ++(*this); 500 return API; 501 } 502 503 /// @returns *this incremented by one 504 /// @brief Prefix increment operator. 505 APInt& operator++(); 506 507 /// @returns a new APInt representing *this decremented by one. 508 /// @brief Postfix decrement operator. 509 const APInt operator--(int) { 510 APInt API(*this); 511 --(*this); 512 return API; 513 } 514 515 /// @returns *this decremented by one. 516 /// @brief Prefix decrement operator. 517 APInt& operator--(); 518 519 /// Performs a bitwise complement operation on this APInt. 520 /// @returns an APInt that is the bitwise complement of *this 521 /// @brief Unary bitwise complement operator. 522 APInt operator~() const { 523 APInt Result(*this); 524 Result.flip(); 525 return Result; 526 } 527 528 /// Negates *this using two's complement logic. 529 /// @returns An APInt value representing the negation of *this. 530 /// @brief Unary negation operator 531 APInt operator-() const { 532 return APInt(BitWidth, 0) - (*this); 533 } 534 535 /// Performs logical negation operation on this APInt. 536 /// @returns true if *this is zero, false otherwise. 537 /// @brief Logical negation operator. 538 bool operator!() const; 539 540 /// @} 541 /// @name Assignment Operators 542 /// @{ 543 /// @returns *this after assignment of RHS. 544 /// @brief Copy assignment operator. 545 APInt& operator=(const APInt& RHS) { 546 // If the bitwidths are the same, we can avoid mucking with memory 547 if (isSingleWord() && RHS.isSingleWord()) { 548 VAL = RHS.VAL; 549 BitWidth = RHS.BitWidth; 550 return clearUnusedBits(); 551 } 552 553 return AssignSlowCase(RHS); 554 } 555 556 /// The RHS value is assigned to *this. If the significant bits in RHS exceed 557 /// the bit width, the excess bits are truncated. If the bit width is larger 558 /// than 64, the value is zero filled in the unspecified high order bits. 559 /// @returns *this after assignment of RHS value. 560 /// @brief Assignment operator. 561 APInt& operator=(uint64_t RHS); 562 563 /// Performs a bitwise AND operation on this APInt and RHS. The result is 564 /// assigned to *this. 565 /// @returns *this after ANDing with RHS. 566 /// @brief Bitwise AND assignment operator. 567 APInt& operator&=(const APInt& RHS); 568 569 /// Performs a bitwise OR operation on this APInt and RHS. The result is 570 /// assigned *this; 571 /// @returns *this after ORing with RHS. 572 /// @brief Bitwise OR assignment operator. 573 APInt& operator|=(const APInt& RHS); 574 575 /// Performs a bitwise XOR operation on this APInt and RHS. The result is 576 /// assigned to *this. 577 /// @returns *this after XORing with RHS. 578 /// @brief Bitwise XOR assignment operator. 579 APInt& operator^=(const APInt& RHS); 580 581 /// Multiplies this APInt by RHS and assigns the result to *this. 582 /// @returns *this 583 /// @brief Multiplication assignment operator. 584 APInt& operator*=(const APInt& RHS); 585 586 /// Adds RHS to *this and assigns the result to *this. 587 /// @returns *this 588 /// @brief Addition assignment operator. 589 APInt& operator+=(const APInt& RHS); 590 591 /// Subtracts RHS from *this and assigns the result to *this. 592 /// @returns *this 593 /// @brief Subtraction assignment operator. 594 APInt& operator-=(const APInt& RHS); 595 596 /// Shifts *this left by shiftAmt and assigns the result to *this. 597 /// @returns *this after shifting left by shiftAmt 598 /// @brief Left-shift assignment function. 599 APInt& operator<<=(unsigned shiftAmt) { 600 *this = shl(shiftAmt); 601 return *this; 602 } 603 604 /// @} 605 /// @name Binary Operators 606 /// @{ 607 /// Performs a bitwise AND operation on *this and RHS. 608 /// @returns An APInt value representing the bitwise AND of *this and RHS. 609 /// @brief Bitwise AND operator. 610 APInt operator&(const APInt& RHS) const { 611 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same"); 612 if (isSingleWord()) 613 return APInt(getBitWidth(), VAL & RHS.VAL); 614 return AndSlowCase(RHS); 615 } 616 APInt And(const APInt& RHS) const { 617 return this->operator&(RHS); 618 } 619 620 /// Performs a bitwise OR operation on *this and RHS. 621 /// @returns An APInt value representing the bitwise OR of *this and RHS. 622 /// @brief Bitwise OR operator. 623 APInt operator|(const APInt& RHS) const { 624 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same"); 625 if (isSingleWord()) 626 return APInt(getBitWidth(), VAL | RHS.VAL); 627 return OrSlowCase(RHS); 628 } 629 APInt Or(const APInt& RHS) const { 630 return this->operator|(RHS); 631 } 632 633 /// Performs a bitwise XOR operation on *this and RHS. 634 /// @returns An APInt value representing the bitwise XOR of *this and RHS. 635 /// @brief Bitwise XOR operator. 636 APInt operator^(const APInt& RHS) const { 637 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same"); 638 if (isSingleWord()) 639 return APInt(BitWidth, VAL ^ RHS.VAL); 640 return XorSlowCase(RHS); 641 } 642 APInt Xor(const APInt& RHS) const { 643 return this->operator^(RHS); 644 } 645 646 /// Multiplies this APInt by RHS and returns the result. 647 /// @brief Multiplication operator. 648 APInt operator*(const APInt& RHS) const; 649 650 /// Adds RHS to this APInt and returns the result. 651 /// @brief Addition operator. 652 APInt operator+(const APInt& RHS) const; 653 APInt operator+(uint64_t RHS) const { 654 return (*this) + APInt(BitWidth, RHS); 655 } 656 657 /// Subtracts RHS from this APInt and returns the result. 658 /// @brief Subtraction operator. 659 APInt operator-(const APInt& RHS) const; 660 APInt operator-(uint64_t RHS) const { 661 return (*this) - APInt(BitWidth, RHS); 662 } 663 664 APInt operator<<(unsigned Bits) const { 665 return shl(Bits); 666 } 667 668 APInt operator<<(const APInt &Bits) const { 669 return shl(Bits); 670 } 671 672 /// Arithmetic right-shift this APInt by shiftAmt. 673 /// @brief Arithmetic right-shift function. 674 APInt ashr(unsigned shiftAmt) const; 675 676 /// Logical right-shift this APInt by shiftAmt. 677 /// @brief Logical right-shift function. 678 APInt lshr(unsigned shiftAmt) const; 679 680 /// Left-shift this APInt by shiftAmt. 681 /// @brief Left-shift function. 682 APInt shl(unsigned shiftAmt) const { 683 assert(shiftAmt <= BitWidth && "Invalid shift amount"); 684 if (isSingleWord()) { 685 if (shiftAmt == BitWidth) 686 return APInt(BitWidth, 0); // avoid undefined shift results 687 return APInt(BitWidth, VAL << shiftAmt); 688 } 689 return shlSlowCase(shiftAmt); 690 } 691 692 /// @brief Rotate left by rotateAmt. 693 APInt rotl(unsigned rotateAmt) const; 694 695 /// @brief Rotate right by rotateAmt. 696 APInt rotr(unsigned rotateAmt) const; 697 698 /// Arithmetic right-shift this APInt by shiftAmt. 699 /// @brief Arithmetic right-shift function. 700 APInt ashr(const APInt &shiftAmt) const; 701 702 /// Logical right-shift this APInt by shiftAmt. 703 /// @brief Logical right-shift function. 704 APInt lshr(const APInt &shiftAmt) const; 705 706 /// Left-shift this APInt by shiftAmt. 707 /// @brief Left-shift function. 708 APInt shl(const APInt &shiftAmt) const; 709 710 /// @brief Rotate left by rotateAmt. 711 APInt rotl(const APInt &rotateAmt) const; 712 713 /// @brief Rotate right by rotateAmt. 714 APInt rotr(const APInt &rotateAmt) const; 715 716 /// Perform an unsigned divide operation on this APInt by RHS. Both this and 717 /// RHS are treated as unsigned quantities for purposes of this division. 718 /// @returns a new APInt value containing the division result 719 /// @brief Unsigned division operation. 720 APInt udiv(const APInt& RHS) const; 721 722 /// Signed divide this APInt by APInt RHS. 723 /// @brief Signed division function for APInt. 724 APInt sdiv(const APInt& RHS) const { 725 if (isNegative()) 726 if (RHS.isNegative()) 727 return (-(*this)).udiv(-RHS); 728 else 729 return -((-(*this)).udiv(RHS)); 730 else if (RHS.isNegative()) 731 return -(this->udiv(-RHS)); 732 return this->udiv(RHS); 733 } 734 735 /// Perform an unsigned remainder operation on this APInt with RHS being the 736 /// divisor. Both this and RHS are treated as unsigned quantities for purposes 737 /// of this operation. Note that this is a true remainder operation and not 738 /// a modulo operation because the sign follows the sign of the dividend 739 /// which is *this. 740 /// @returns a new APInt value containing the remainder result 741 /// @brief Unsigned remainder operation. 742 APInt urem(const APInt& RHS) const; 743 744 /// Signed remainder operation on APInt. 745 /// @brief Function for signed remainder operation. 746 APInt srem(const APInt& RHS) const { 747 if (isNegative()) 748 if (RHS.isNegative()) 749 return -((-(*this)).urem(-RHS)); 750 else 751 return -((-(*this)).urem(RHS)); 752 else if (RHS.isNegative()) 753 return this->urem(-RHS); 754 return this->urem(RHS); 755 } 756 757 /// Sometimes it is convenient to divide two APInt values and obtain both the 758 /// quotient and remainder. This function does both operations in the same 759 /// computation making it a little more efficient. The pair of input arguments 760 /// may overlap with the pair of output arguments. It is safe to call 761 /// udivrem(X, Y, X, Y), for example. 762 /// @brief Dual division/remainder interface. 763 static void udivrem(const APInt &LHS, const APInt &RHS, 764 APInt &Quotient, APInt &Remainder); 765 766 static void sdivrem(const APInt &LHS, const APInt &RHS, 767 APInt &Quotient, APInt &Remainder) 768 { 769 if (LHS.isNegative()) { 770 if (RHS.isNegative()) 771 APInt::udivrem(-LHS, -RHS, Quotient, Remainder); 772 else 773 APInt::udivrem(-LHS, RHS, Quotient, Remainder); 774 Quotient = -Quotient; 775 Remainder = -Remainder; 776 } else if (RHS.isNegative()) { 777 APInt::udivrem(LHS, -RHS, Quotient, Remainder); 778 Quotient = -Quotient; 779 } else { 780 APInt::udivrem(LHS, RHS, Quotient, Remainder); 781 } 782 } 783 784 /// @returns the bit value at bitPosition 785 /// @brief Array-indexing support. 786 bool operator[](unsigned bitPosition) const; 787 788 /// @} 789 /// @name Comparison Operators 790 /// @{ 791 /// Compares this APInt with RHS for the validity of the equality 792 /// relationship. 793 /// @brief Equality operator. 794 bool operator==(const APInt& RHS) const { 795 assert(BitWidth == RHS.BitWidth && "Comparison requires equal bit widths"); 796 if (isSingleWord()) 797 return VAL == RHS.VAL; 798 return EqualSlowCase(RHS); 799 } 800 801 /// Compares this APInt with a uint64_t for the validity of the equality 802 /// relationship. 803 /// @returns true if *this == Val 804 /// @brief Equality operator. 805 bool operator==(uint64_t Val) const { 806 if (isSingleWord()) 807 return VAL == Val; 808 return EqualSlowCase(Val); 809 } 810 811 /// Compares this APInt with RHS for the validity of the equality 812 /// relationship. 813 /// @returns true if *this == Val 814 /// @brief Equality comparison. 815 bool eq(const APInt &RHS) const { 816 return (*this) == RHS; 817 } 818 819 /// Compares this APInt with RHS for the validity of the inequality 820 /// relationship. 821 /// @returns true if *this != Val 822 /// @brief Inequality operator. 823 bool operator!=(const APInt& RHS) const { 824 return !((*this) == RHS); 825 } 826 827 /// Compares this APInt with a uint64_t for the validity of the inequality 828 /// relationship. 829 /// @returns true if *this != Val 830 /// @brief Inequality operator. 831 bool operator!=(uint64_t Val) const { 832 return !((*this) == Val); 833 } 834 835 /// Compares this APInt with RHS for the validity of the inequality 836 /// relationship. 837 /// @returns true if *this != Val 838 /// @brief Inequality comparison 839 bool ne(const APInt &RHS) const { 840 return !((*this) == RHS); 841 } 842 843 /// Regards both *this and RHS as unsigned quantities and compares them for 844 /// the validity of the less-than relationship. 845 /// @returns true if *this < RHS when both are considered unsigned. 846 /// @brief Unsigned less than comparison 847 bool ult(const APInt& RHS) const; 848 849 /// Regards both *this and RHS as signed quantities and compares them for 850 /// validity of the less-than relationship. 851 /// @returns true if *this < RHS when both are considered signed. 852 /// @brief Signed less than comparison 853 bool slt(const APInt& RHS) const; 854 855 /// Regards both *this and RHS as unsigned quantities and compares them for 856 /// validity of the less-or-equal relationship. 857 /// @returns true if *this <= RHS when both are considered unsigned. 858 /// @brief Unsigned less or equal comparison 859 bool ule(const APInt& RHS) const { 860 return ult(RHS) || eq(RHS); 861 } 862 863 /// Regards both *this and RHS as signed quantities and compares them for 864 /// validity of the less-or-equal relationship. 865 /// @returns true if *this <= RHS when both are considered signed. 866 /// @brief Signed less or equal comparison 867 bool sle(const APInt& RHS) const { 868 return slt(RHS) || eq(RHS); 869 } 870 871 /// Regards both *this and RHS as unsigned quantities and compares them for 872 /// the validity of the greater-than relationship. 873 /// @returns true if *this > RHS when both are considered unsigned. 874 /// @brief Unsigned greather than comparison 875 bool ugt(const APInt& RHS) const { 876 return !ult(RHS) && !eq(RHS); 877 } 878 879 /// Regards both *this and RHS as signed quantities and compares them for 880 /// the validity of the greater-than relationship. 881 /// @returns true if *this > RHS when both are considered signed. 882 /// @brief Signed greather than comparison 883 bool sgt(const APInt& RHS) const { 884 return !slt(RHS) && !eq(RHS); 885 } 886 887 /// Regards both *this and RHS as unsigned quantities and compares them for 888 /// validity of the greater-or-equal relationship. 889 /// @returns true if *this >= RHS when both are considered unsigned. 890 /// @brief Unsigned greater or equal comparison 891 bool uge(const APInt& RHS) const { 892 return !ult(RHS); 893 } 894 895 /// Regards both *this and RHS as signed quantities and compares them for 896 /// validity of the greater-or-equal relationship. 897 /// @returns true if *this >= RHS when both are considered signed. 898 /// @brief Signed greather or equal comparison 899 bool sge(const APInt& RHS) const { 900 return !slt(RHS); 901 } 902 903 /// This operation tests if there are any pairs of corresponding bits 904 /// between this APInt and RHS that are both set. 905 bool intersects(const APInt &RHS) const { 906 return (*this & RHS) != 0; 907 } 908 909 /// @} 910 /// @name Resizing Operators 911 /// @{ 912 /// Truncate the APInt to a specified width. It is an error to specify a width 913 /// that is greater than or equal to the current width. 914 /// @brief Truncate to new width. 915 APInt &trunc(unsigned width); 916 917 /// This operation sign extends the APInt to a new width. If the high order 918 /// bit is set, the fill on the left will be done with 1 bits, otherwise zero. 919 /// It is an error to specify a width that is less than or equal to the 920 /// current width. 921 /// @brief Sign extend to a new width. 922 APInt &sext(unsigned width); 923 924 /// This operation zero extends the APInt to a new width. The high order bits 925 /// are filled with 0 bits. It is an error to specify a width that is less 926 /// than or equal to the current width. 927 /// @brief Zero extend to a new width. 928 APInt &zext(unsigned width); 929 930 /// Make this APInt have the bit width given by \p width. The value is sign 931 /// extended, truncated, or left alone to make it that width. 932 /// @brief Sign extend or truncate to width 933 APInt &sextOrTrunc(unsigned width); 934 935 /// Make this APInt have the bit width given by \p width. The value is zero 936 /// extended, truncated, or left alone to make it that width. 937 /// @brief Zero extend or truncate to width 938 APInt &zextOrTrunc(unsigned width); 939 940 /// @} 941 /// @name Bit Manipulation Operators 942 /// @{ 943 /// @brief Set every bit to 1. 944 APInt& set() { 945 if (isSingleWord()) { 946 VAL = -1ULL; 947 return clearUnusedBits(); 948 } 949 950 // Set all the bits in all the words. 951 for (unsigned i = 0; i < getNumWords(); ++i) 952 pVal[i] = -1ULL; 953 // Clear the unused ones 954 return clearUnusedBits(); 955 } 956 957 /// Set the given bit to 1 whose position is given as "bitPosition". 958 /// @brief Set a given bit to 1. 959 APInt& set(unsigned bitPosition); 960 961 /// @brief Set every bit to 0. 962 APInt& clear() { 963 if (isSingleWord()) 964 VAL = 0; 965 else 966 memset(pVal, 0, getNumWords() * APINT_WORD_SIZE); 967 return *this; 968 } 969 970 /// Set the given bit to 0 whose position is given as "bitPosition". 971 /// @brief Set a given bit to 0. 972 APInt& clear(unsigned bitPosition); 973 974 /// @brief Toggle every bit to its opposite value. 975 APInt& flip() { 976 if (isSingleWord()) { 977 VAL ^= -1ULL; 978 return clearUnusedBits(); 979 } 980 for (unsigned i = 0; i < getNumWords(); ++i) 981 pVal[i] ^= -1ULL; 982 return clearUnusedBits(); 983 } 984 985 /// Toggle a given bit to its opposite value whose position is given 986 /// as "bitPosition". 987 /// @brief Toggles a given bit to its opposite value. 988 APInt& flip(unsigned bitPosition); 989 990 /// @} 991 /// @name Value Characterization Functions 992 /// @{ 993 994 /// @returns the total number of bits. 995 unsigned getBitWidth() const { 996 return BitWidth; 997 } 998 999 /// Here one word's bitwidth equals to that of uint64_t. 1000 /// @returns the number of words to hold the integer value of this APInt. 1001 /// @brief Get the number of words. 1002 unsigned getNumWords() const { 1003 return getNumWords(BitWidth); 1004 } 1005 1006 /// Here one word's bitwidth equals to that of uint64_t. 1007 /// @returns the number of words to hold the integer value with a 1008 /// given bit width. 1009 /// @brief Get the number of words. 1010 static unsigned getNumWords(unsigned BitWidth) { 1011 return (BitWidth + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD; 1012 } 1013 1014 /// This function returns the number of active bits which is defined as the 1015 /// bit width minus the number of leading zeros. This is used in several 1016 /// computations to see how "wide" the value is. 1017 /// @brief Compute the number of active bits in the value 1018 unsigned getActiveBits() const { 1019 return BitWidth - countLeadingZeros(); 1020 } 1021 1022 /// This function returns the number of active words in the value of this 1023 /// APInt. This is used in conjunction with getActiveData to extract the raw 1024 /// value of the APInt. 1025 unsigned getActiveWords() const { 1026 return whichWord(getActiveBits()-1) + 1; 1027 } 1028 1029 /// Computes the minimum bit width for this APInt while considering it to be 1030 /// a signed (and probably negative) value. If the value is not negative, 1031 /// this function returns the same value as getActiveBits()+1. Otherwise, it 1032 /// returns the smallest bit width that will retain the negative value. For 1033 /// example, -1 can be written as 0b1 or 0xFFFFFFFFFF. 0b1 is shorter and so 1034 /// for -1, this function will always return 1. 1035 /// @brief Get the minimum bit size for this signed APInt 1036 unsigned getMinSignedBits() const { 1037 if (isNegative()) 1038 return BitWidth - countLeadingOnes() + 1; 1039 return getActiveBits()+1; 1040 } 1041 1042 /// This method attempts to return the value of this APInt as a zero extended 1043 /// uint64_t. The bitwidth must be <= 64 or the value must fit within a 1044 /// uint64_t. Otherwise an assertion will result. 1045 /// @brief Get zero extended value 1046 uint64_t getZExtValue() const { 1047 if (isSingleWord()) 1048 return VAL; 1049 assert(getActiveBits() <= 64 && "Too many bits for uint64_t"); 1050 return pVal[0]; 1051 } 1052 1053 /// This method attempts to return the value of this APInt as a sign extended 1054 /// int64_t. The bit width must be <= 64 or the value must fit within an 1055 /// int64_t. Otherwise an assertion will result. 1056 /// @brief Get sign extended value 1057 int64_t getSExtValue() const { 1058 if (isSingleWord()) 1059 return int64_t(VAL << (APINT_BITS_PER_WORD - BitWidth)) >> 1060 (APINT_BITS_PER_WORD - BitWidth); 1061 assert(getMinSignedBits() <= 64 && "Too many bits for int64_t"); 1062 return int64_t(pVal[0]); 1063 } 1064 1065 /// This method determines how many bits are required to hold the APInt 1066 /// equivalent of the string given by \p str of length \p slen. 1067 /// @brief Get bits required for string value. 1068 static unsigned getBitsNeeded(const char* str, unsigned slen, uint8_t radix); 1069 1070 /// countLeadingZeros - This function is an APInt version of the 1071 /// countLeadingZeros_{32,64} functions in MathExtras.h. It counts the number 1072 /// of zeros from the most significant bit to the first one bit. 1073 /// @returns BitWidth if the value is zero. 1074 /// @returns the number of zeros from the most significant bit to the first 1075 /// one bits. 1076 unsigned countLeadingZeros() const { 1077 if (isSingleWord()) { 1078 unsigned unusedBits = APINT_BITS_PER_WORD - BitWidth; 1079 return CountLeadingZeros_64(VAL) - unusedBits; 1080 } 1081 return countLeadingZerosSlowCase(); 1082 } 1083 1084 /// countLeadingOnes - This function is an APInt version of the 1085 /// countLeadingOnes_{32,64} functions in MathExtras.h. It counts the number 1086 /// of ones from the most significant bit to the first zero bit. 1087 /// @returns 0 if the high order bit is not set 1088 /// @returns the number of 1 bits from the most significant to the least 1089 /// @brief Count the number of leading one bits. 1090 unsigned countLeadingOnes() const; 1091 1092 /// countTrailingZeros - This function is an APInt version of the 1093 /// countTrailingZeros_{32,64} functions in MathExtras.h. It counts 1094 /// the number of zeros from the least significant bit to the first set bit. 1095 /// @returns BitWidth if the value is zero. 1096 /// @returns the number of zeros from the least significant bit to the first 1097 /// one bit. 1098 /// @brief Count the number of trailing zero bits. 1099 unsigned countTrailingZeros() const; 1100 1101 /// countTrailingOnes - This function is an APInt version of the 1102 /// countTrailingOnes_{32,64} functions in MathExtras.h. It counts 1103 /// the number of ones from the least significant bit to the first zero bit. 1104 /// @returns BitWidth if the value is all ones. 1105 /// @returns the number of ones from the least significant bit to the first 1106 /// zero bit. 1107 /// @brief Count the number of trailing one bits. 1108 unsigned countTrailingOnes() const { 1109 if (isSingleWord()) 1110 return CountTrailingOnes_64(VAL); 1111 return countTrailingOnesSlowCase(); 1112 } 1113 1114 /// countPopulation - This function is an APInt version of the 1115 /// countPopulation_{32,64} functions in MathExtras.h. It counts the number 1116 /// of 1 bits in the APInt value. 1117 /// @returns 0 if the value is zero. 1118 /// @returns the number of set bits. 1119 /// @brief Count the number of bits set. 1120 unsigned countPopulation() const { 1121 if (isSingleWord()) 1122 return CountPopulation_64(VAL); 1123 return countPopulationSlowCase(); 1124 } 1125 1126 /// @} 1127 /// @name Conversion Functions 1128 /// @{ 1129 void print(raw_ostream &OS, bool isSigned) const; 1130 1131 /// toString - Converts an APInt to a string and append it to Str. Str is 1132 /// commonly a SmallString. 1133 void toString(SmallVectorImpl<char> &Str, unsigned Radix, bool Signed) const; 1134 1135 /// Considers the APInt to be unsigned and converts it into a string in the 1136 /// radix given. The radix can be 2, 8, 10 or 16. 1137 void toStringUnsigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const { 1138 toString(Str, Radix, false); 1139 } 1140 1141 /// Considers the APInt to be signed and converts it into a string in the 1142 /// radix given. The radix can be 2, 8, 10 or 16. 1143 void toStringSigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const { 1144 toString(Str, Radix, true); 1145 } 1146 1147 /// toString - This returns the APInt as a std::string. Note that this is an 1148 /// inefficient method. It is better to pass in a SmallVector/SmallString 1149 /// to the methods above to avoid thrashing the heap for the string. 1150 std::string toString(unsigned Radix, bool Signed) const; 1151 1152 1153 /// @returns a byte-swapped representation of this APInt Value. 1154 APInt byteSwap() const; 1155 1156 /// @brief Converts this APInt to a double value. 1157 double roundToDouble(bool isSigned) const; 1158 1159 /// @brief Converts this unsigned APInt to a double value. 1160 double roundToDouble() const { 1161 return roundToDouble(false); 1162 } 1163 1164 /// @brief Converts this signed APInt to a double value. 1165 double signedRoundToDouble() const { 1166 return roundToDouble(true); 1167 } 1168 1169 /// The conversion does not do a translation from integer to double, it just 1170 /// re-interprets the bits as a double. Note that it is valid to do this on 1171 /// any bit width. Exactly 64 bits will be translated. 1172 /// @brief Converts APInt bits to a double 1173 double bitsToDouble() const { 1174 union { 1175 uint64_t I; 1176 double D; 1177 } T; 1178 T.I = (isSingleWord() ? VAL : pVal[0]); 1179 return T.D; 1180 } 1181 1182 /// The conversion does not do a translation from integer to float, it just 1183 /// re-interprets the bits as a float. Note that it is valid to do this on 1184 /// any bit width. Exactly 32 bits will be translated. 1185 /// @brief Converts APInt bits to a double 1186 float bitsToFloat() const { 1187 union { 1188 unsigned I; 1189 float F; 1190 } T; 1191 T.I = unsigned((isSingleWord() ? VAL : pVal[0])); 1192 return T.F; 1193 } 1194 1195 /// The conversion does not do a translation from double to integer, it just 1196 /// re-interprets the bits of the double. Note that it is valid to do this on 1197 /// any bit width but bits from V may get truncated. 1198 /// @brief Converts a double to APInt bits. 1199 APInt& doubleToBits(double V) { 1200 union { 1201 uint64_t I; 1202 double D; 1203 } T; 1204 T.D = V; 1205 if (isSingleWord()) 1206 VAL = T.I; 1207 else 1208 pVal[0] = T.I; 1209 return clearUnusedBits(); 1210 } 1211 1212 /// The conversion does not do a translation from float to integer, it just 1213 /// re-interprets the bits of the float. Note that it is valid to do this on 1214 /// any bit width but bits from V may get truncated. 1215 /// @brief Converts a float to APInt bits. 1216 APInt& floatToBits(float V) { 1217 union { 1218 unsigned I; 1219 float F; 1220 } T; 1221 T.F = V; 1222 if (isSingleWord()) 1223 VAL = T.I; 1224 else 1225 pVal[0] = T.I; 1226 return clearUnusedBits(); 1227 } 1228 1229 /// @} 1230 /// @name Mathematics Operations 1231 /// @{ 1232 1233 /// @returns the floor log base 2 of this APInt. 1234 unsigned logBase2() const { 1235 return BitWidth - 1 - countLeadingZeros(); 1236 } 1237 1238 /// @returns the log base 2 of this APInt if its an exact power of two, -1 1239 /// otherwise 1240 int32_t exactLogBase2() const { 1241 if (!isPowerOf2()) 1242 return -1; 1243 return logBase2(); 1244 } 1245 1246 /// @brief Compute the square root 1247 APInt sqrt() const; 1248 1249 /// If *this is < 0 then return -(*this), otherwise *this; 1250 /// @brief Get the absolute value; 1251 APInt abs() const { 1252 if (isNegative()) 1253 return -(*this); 1254 return *this; 1255 } 1256 1257 /// @returns the multiplicative inverse for a given modulo. 1258 APInt multiplicativeInverse(const APInt& modulo) const; 1259 1260 /// @} 1261 /// @name Support for division by constant 1262 /// @{ 1263 1264 /// Calculate the magic number for signed division by a constant. 1265 struct ms; 1266 ms magic() const; 1267 1268 /// Calculate the magic number for unsigned division by a constant. 1269 struct mu; 1270 mu magicu() const; 1271 1272 /// @} 1273 /// @name Building-block Operations for APInt and APFloat 1274 /// @{ 1275 1276 // These building block operations operate on a representation of 1277 // arbitrary precision, two's-complement, bignum integer values. 1278 // They should be sufficient to implement APInt and APFloat bignum 1279 // requirements. Inputs are generally a pointer to the base of an 1280 // array of integer parts, representing an unsigned bignum, and a 1281 // count of how many parts there are. 1282 1283 /// Sets the least significant part of a bignum to the input value, 1284 /// and zeroes out higher parts. */ 1285 static void tcSet(integerPart *, integerPart, unsigned int); 1286 1287 /// Assign one bignum to another. 1288 static void tcAssign(integerPart *, const integerPart *, unsigned int); 1289 1290 /// Returns true if a bignum is zero, false otherwise. 1291 static bool tcIsZero(const integerPart *, unsigned int); 1292 1293 /// Extract the given bit of a bignum; returns 0 or 1. Zero-based. 1294 static int tcExtractBit(const integerPart *, unsigned int bit); 1295 1296 /// Copy the bit vector of width srcBITS from SRC, starting at bit 1297 /// srcLSB, to DST, of dstCOUNT parts, such that the bit srcLSB 1298 /// becomes the least significant bit of DST. All high bits above 1299 /// srcBITS in DST are zero-filled. 1300 static void tcExtract(integerPart *, unsigned int dstCount, 1301 const integerPart *, 1302 unsigned int srcBits, unsigned int srcLSB); 1303 1304 /// Set the given bit of a bignum. Zero-based. 1305 static void tcSetBit(integerPart *, unsigned int bit); 1306 1307 /// Returns the bit number of the least or most significant set bit 1308 /// of a number. If the input number has no bits set -1U is 1309 /// returned. 1310 static unsigned int tcLSB(const integerPart *, unsigned int); 1311 static unsigned int tcMSB(const integerPart *parts, unsigned int n); 1312 1313 /// Negate a bignum in-place. 1314 static void tcNegate(integerPart *, unsigned int); 1315 1316 /// DST += RHS + CARRY where CARRY is zero or one. Returns the 1317 /// carry flag. 1318 static integerPart tcAdd(integerPart *, const integerPart *, 1319 integerPart carry, unsigned); 1320 1321 /// DST -= RHS + CARRY where CARRY is zero or one. Returns the 1322 /// carry flag. 1323 static integerPart tcSubtract(integerPart *, const integerPart *, 1324 integerPart carry, unsigned); 1325 1326 /// DST += SRC * MULTIPLIER + PART if add is true 1327 /// DST = SRC * MULTIPLIER + PART if add is false 1328 /// 1329 /// Requires 0 <= DSTPARTS <= SRCPARTS + 1. If DST overlaps SRC 1330 /// they must start at the same point, i.e. DST == SRC. 1331 /// 1332 /// If DSTPARTS == SRC_PARTS + 1 no overflow occurs and zero is 1333 /// returned. Otherwise DST is filled with the least significant 1334 /// DSTPARTS parts of the result, and if all of the omitted higher 1335 /// parts were zero return zero, otherwise overflow occurred and 1336 /// return one. 1337 static int tcMultiplyPart(integerPart *dst, const integerPart *src, 1338 integerPart multiplier, integerPart carry, 1339 unsigned int srcParts, unsigned int dstParts, 1340 bool add); 1341 1342 /// DST = LHS * RHS, where DST has the same width as the operands 1343 /// and is filled with the least significant parts of the result. 1344 /// Returns one if overflow occurred, otherwise zero. DST must be 1345 /// disjoint from both operands. 1346 static int tcMultiply(integerPart *, const integerPart *, 1347 const integerPart *, unsigned); 1348 1349 /// DST = LHS * RHS, where DST has width the sum of the widths of 1350 /// the operands. No overflow occurs. DST must be disjoint from 1351 /// both operands. Returns the number of parts required to hold the 1352 /// result. 1353 static unsigned int tcFullMultiply(integerPart *, const integerPart *, 1354 const integerPart *, unsigned, unsigned); 1355 1356 /// If RHS is zero LHS and REMAINDER are left unchanged, return one. 1357 /// Otherwise set LHS to LHS / RHS with the fractional part 1358 /// discarded, set REMAINDER to the remainder, return zero. i.e. 1359 /// 1360 /// OLD_LHS = RHS * LHS + REMAINDER 1361 /// 1362 /// SCRATCH is a bignum of the same size as the operands and result 1363 /// for use by the routine; its contents need not be initialized 1364 /// and are destroyed. LHS, REMAINDER and SCRATCH must be 1365 /// distinct. 1366 static int tcDivide(integerPart *lhs, const integerPart *rhs, 1367 integerPart *remainder, integerPart *scratch, 1368 unsigned int parts); 1369 1370 /// Shift a bignum left COUNT bits. Shifted in bits are zero. 1371 /// There are no restrictions on COUNT. 1372 static void tcShiftLeft(integerPart *, unsigned int parts, 1373 unsigned int count); 1374 1375 /// Shift a bignum right COUNT bits. Shifted in bits are zero. 1376 /// There are no restrictions on COUNT. 1377 static void tcShiftRight(integerPart *, unsigned int parts, 1378 unsigned int count); 1379 1380 /// The obvious AND, OR and XOR and complement operations. 1381 static void tcAnd(integerPart *, const integerPart *, unsigned int); 1382 static void tcOr(integerPart *, const integerPart *, unsigned int); 1383 static void tcXor(integerPart *, const integerPart *, unsigned int); 1384 static void tcComplement(integerPart *, unsigned int); 1385 1386 /// Comparison (unsigned) of two bignums. 1387 static int tcCompare(const integerPart *, const integerPart *, 1388 unsigned int); 1389 1390 /// Increment a bignum in-place. Return the carry flag. 1391 static integerPart tcIncrement(integerPart *, unsigned int); 1392 1393 /// Set the least significant BITS and clear the rest. 1394 static void tcSetLeastSignificantBits(integerPart *, unsigned int, 1395 unsigned int bits); 1396 1397 /// @brief debug method 1398 void dump() const; 1399 1400 /// @} 1401}; 1402 1403/// Magic data for optimising signed division by a constant. 1404struct APInt::ms { 1405 APInt m; ///< magic number 1406 unsigned s; ///< shift amount 1407}; 1408 1409/// Magic data for optimising unsigned division by a constant. 1410struct APInt::mu { 1411 APInt m; ///< magic number 1412 bool a; ///< add indicator 1413 unsigned s; ///< shift amount 1414}; 1415 1416inline bool operator==(uint64_t V1, const APInt& V2) { 1417 return V2 == V1; 1418} 1419 1420inline bool operator!=(uint64_t V1, const APInt& V2) { 1421 return V2 != V1; 1422} 1423 1424inline raw_ostream &operator<<(raw_ostream &OS, const APInt &I) { 1425 I.print(OS, true); 1426 return OS; 1427} 1428 1429namespace APIntOps { 1430 1431/// @brief Determine the smaller of two APInts considered to be signed. 1432inline APInt smin(const APInt &A, const APInt &B) { 1433 return A.slt(B) ? A : B; 1434} 1435 1436/// @brief Determine the larger of two APInts considered to be signed. 1437inline APInt smax(const APInt &A, const APInt &B) { 1438 return A.sgt(B) ? A : B; 1439} 1440 1441/// @brief Determine the smaller of two APInts considered to be signed. 1442inline APInt umin(const APInt &A, const APInt &B) { 1443 return A.ult(B) ? A : B; 1444} 1445 1446/// @brief Determine the larger of two APInts considered to be unsigned. 1447inline APInt umax(const APInt &A, const APInt &B) { 1448 return A.ugt(B) ? A : B; 1449} 1450 1451/// @brief Check if the specified APInt has a N-bits unsigned integer value. 1452inline bool isIntN(unsigned N, const APInt& APIVal) { 1453 return APIVal.isIntN(N); 1454} 1455 1456/// @brief Check if the specified APInt has a N-bits signed integer value. 1457inline bool isSignedIntN(unsigned N, const APInt& APIVal) { 1458 return APIVal.isSignedIntN(N); 1459} 1460 1461/// @returns true if the argument APInt value is a sequence of ones 1462/// starting at the least significant bit with the remainder zero. 1463inline bool isMask(unsigned numBits, const APInt& APIVal) { 1464 return numBits <= APIVal.getBitWidth() && 1465 APIVal == APInt::getLowBitsSet(APIVal.getBitWidth(), numBits); 1466} 1467 1468/// @returns true if the argument APInt value contains a sequence of ones 1469/// with the remainder zero. 1470inline bool isShiftedMask(unsigned numBits, const APInt& APIVal) { 1471 return isMask(numBits, (APIVal - APInt(numBits,1)) | APIVal); 1472} 1473 1474/// @returns a byte-swapped representation of the specified APInt Value. 1475inline APInt byteSwap(const APInt& APIVal) { 1476 return APIVal.byteSwap(); 1477} 1478 1479/// @returns the floor log base 2 of the specified APInt value. 1480inline unsigned logBase2(const APInt& APIVal) { 1481 return APIVal.logBase2(); 1482} 1483 1484/// GreatestCommonDivisor - This function returns the greatest common 1485/// divisor of the two APInt values using Euclid's algorithm. 1486/// @returns the greatest common divisor of Val1 and Val2 1487/// @brief Compute GCD of two APInt values. 1488APInt GreatestCommonDivisor(const APInt& Val1, const APInt& Val2); 1489 1490/// Treats the APInt as an unsigned value for conversion purposes. 1491/// @brief Converts the given APInt to a double value. 1492inline double RoundAPIntToDouble(const APInt& APIVal) { 1493 return APIVal.roundToDouble(); 1494} 1495 1496/// Treats the APInt as a signed value for conversion purposes. 1497/// @brief Converts the given APInt to a double value. 1498inline double RoundSignedAPIntToDouble(const APInt& APIVal) { 1499 return APIVal.signedRoundToDouble(); 1500} 1501 1502/// @brief Converts the given APInt to a float vlalue. 1503inline float RoundAPIntToFloat(const APInt& APIVal) { 1504 return float(RoundAPIntToDouble(APIVal)); 1505} 1506 1507/// Treast the APInt as a signed value for conversion purposes. 1508/// @brief Converts the given APInt to a float value. 1509inline float RoundSignedAPIntToFloat(const APInt& APIVal) { 1510 return float(APIVal.signedRoundToDouble()); 1511} 1512 1513/// RoundDoubleToAPInt - This function convert a double value to an APInt value. 1514/// @brief Converts the given double value into a APInt. 1515APInt RoundDoubleToAPInt(double Double, unsigned width); 1516 1517/// RoundFloatToAPInt - Converts a float value into an APInt value. 1518/// @brief Converts a float value into a APInt. 1519inline APInt RoundFloatToAPInt(float Float, unsigned width) { 1520 return RoundDoubleToAPInt(double(Float), width); 1521} 1522 1523/// Arithmetic right-shift the APInt by shiftAmt. 1524/// @brief Arithmetic right-shift function. 1525inline APInt ashr(const APInt& LHS, unsigned shiftAmt) { 1526 return LHS.ashr(shiftAmt); 1527} 1528 1529/// Logical right-shift the APInt by shiftAmt. 1530/// @brief Logical right-shift function. 1531inline APInt lshr(const APInt& LHS, unsigned shiftAmt) { 1532 return LHS.lshr(shiftAmt); 1533} 1534 1535/// Left-shift the APInt by shiftAmt. 1536/// @brief Left-shift function. 1537inline APInt shl(const APInt& LHS, unsigned shiftAmt) { 1538 return LHS.shl(shiftAmt); 1539} 1540 1541/// Signed divide APInt LHS by APInt RHS. 1542/// @brief Signed division function for APInt. 1543inline APInt sdiv(const APInt& LHS, const APInt& RHS) { 1544 return LHS.sdiv(RHS); 1545} 1546 1547/// Unsigned divide APInt LHS by APInt RHS. 1548/// @brief Unsigned division function for APInt. 1549inline APInt udiv(const APInt& LHS, const APInt& RHS) { 1550 return LHS.udiv(RHS); 1551} 1552 1553/// Signed remainder operation on APInt. 1554/// @brief Function for signed remainder operation. 1555inline APInt srem(const APInt& LHS, const APInt& RHS) { 1556 return LHS.srem(RHS); 1557} 1558 1559/// Unsigned remainder operation on APInt. 1560/// @brief Function for unsigned remainder operation. 1561inline APInt urem(const APInt& LHS, const APInt& RHS) { 1562 return LHS.urem(RHS); 1563} 1564 1565/// Performs multiplication on APInt values. 1566/// @brief Function for multiplication operation. 1567inline APInt mul(const APInt& LHS, const APInt& RHS) { 1568 return LHS * RHS; 1569} 1570 1571/// Performs addition on APInt values. 1572/// @brief Function for addition operation. 1573inline APInt add(const APInt& LHS, const APInt& RHS) { 1574 return LHS + RHS; 1575} 1576 1577/// Performs subtraction on APInt values. 1578/// @brief Function for subtraction operation. 1579inline APInt sub(const APInt& LHS, const APInt& RHS) { 1580 return LHS - RHS; 1581} 1582 1583/// Performs bitwise AND operation on APInt LHS and 1584/// APInt RHS. 1585/// @brief Bitwise AND function for APInt. 1586inline APInt And(const APInt& LHS, const APInt& RHS) { 1587 return LHS & RHS; 1588} 1589 1590/// Performs bitwise OR operation on APInt LHS and APInt RHS. 1591/// @brief Bitwise OR function for APInt. 1592inline APInt Or(const APInt& LHS, const APInt& RHS) { 1593 return LHS | RHS; 1594} 1595 1596/// Performs bitwise XOR operation on APInt. 1597/// @brief Bitwise XOR function for APInt. 1598inline APInt Xor(const APInt& LHS, const APInt& RHS) { 1599 return LHS ^ RHS; 1600} 1601 1602/// Performs a bitwise complement operation on APInt. 1603/// @brief Bitwise complement function. 1604inline APInt Not(const APInt& APIVal) { 1605 return ~APIVal; 1606} 1607 1608} // End of APIntOps namespace 1609 1610} // End of llvm namespace 1611 1612#endif 1613