LLVM API Documentation

APInt.h
Go to the documentation of this file.
00001 //===-- llvm/ADT/APInt.h - For Arbitrary Precision Integer -----*- C++ -*--===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements a class to represent arbitrary precision integral
00011 // constant values and operations on them.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #ifndef LLVM_ADT_APINT_H
00016 #define LLVM_ADT_APINT_H
00017 
00018 #include "llvm/ADT/ArrayRef.h"
00019 #include "llvm/Support/Compiler.h"
00020 #include "llvm/Support/MathExtras.h"
00021 #include <cassert>
00022 #include <climits>
00023 #include <cstring>
00024 #include <string>
00025 
00026 namespace llvm {
00027   class Deserializer;
00028   class FoldingSetNodeID;
00029   class Serializer;
00030   class StringRef;
00031   class hash_code;
00032   class raw_ostream;
00033 
00034   template<typename T>
00035   class SmallVectorImpl;
00036 
00037   // An unsigned host type used as a single part of a multi-part
00038   // bignum.
00039   typedef uint64_t integerPart;
00040 
00041   const unsigned int host_char_bit = 8;
00042   const unsigned int integerPartWidth = host_char_bit *
00043     static_cast<unsigned int>(sizeof(integerPart));
00044 
00045 //===----------------------------------------------------------------------===//
00046 //                              APInt Class
00047 //===----------------------------------------------------------------------===//
00048 
00049 /// APInt - This class represents arbitrary precision constant integral values.
00050 /// It is a functional replacement for common case unsigned integer type like
00051 /// "unsigned", "unsigned long" or "uint64_t", but also allows non-byte-width
00052 /// integer sizes and large integer value types such as 3-bits, 15-bits, or more
00053 /// than 64-bits of precision. APInt provides a variety of arithmetic operators
00054 /// and methods to manipulate integer values of any bit-width. It supports both
00055 /// the typical integer arithmetic and comparison operations as well as bitwise
00056 /// manipulation.
00057 ///
00058 /// The class has several invariants worth noting:
00059 ///   * All bit, byte, and word positions are zero-based.
00060 ///   * Once the bit width is set, it doesn't change except by the Truncate,
00061 ///     SignExtend, or ZeroExtend operations.
00062 ///   * All binary operators must be on APInt instances of the same bit width.
00063 ///     Attempting to use these operators on instances with different bit
00064 ///     widths will yield an assertion.
00065 ///   * The value is stored canonically as an unsigned value. For operations
00066 ///     where it makes a difference, there are both signed and unsigned variants
00067 ///     of the operation. For example, sdiv and udiv. However, because the bit
00068 ///     widths must be the same, operations such as Mul and Add produce the same
00069 ///     results regardless of whether the values are interpreted as signed or
00070 ///     not.
00071 ///   * In general, the class tries to follow the style of computation that LLVM
00072 ///     uses in its IR. This simplifies its use for LLVM.
00073 ///
00074 /// @brief Class for arbitrary precision integers.
00075 class APInt {
00076   unsigned BitWidth;      ///< The number of bits in this APInt.
00077 
00078   /// This union is used to store the integer value. When the
00079   /// integer bit-width <= 64, it uses VAL, otherwise it uses pVal.
00080   union {
00081     uint64_t VAL;    ///< Used to store the <= 64 bits integer value.
00082     uint64_t *pVal;  ///< Used to store the >64 bits integer value.
00083   };
00084 
00085   /// This enum is used to hold the constants we needed for APInt.
00086   enum {
00087     /// Bits in a word
00088     APINT_BITS_PER_WORD = static_cast<unsigned int>(sizeof(uint64_t)) *
00089                           CHAR_BIT,
00090     /// Byte size of a word
00091     APINT_WORD_SIZE = static_cast<unsigned int>(sizeof(uint64_t))
00092   };
00093 
00094   /// This constructor is used only internally for speed of construction of
00095   /// temporaries. It is unsafe for general use so it is not public.
00096   /// @brief Fast internal constructor
00097   APInt(uint64_t* val, unsigned bits) : BitWidth(bits), pVal(val) { }
00098 
00099   /// @returns true if the number of bits <= 64, false otherwise.
00100   /// @brief Determine if this APInt just has one word to store value.
00101   bool isSingleWord() const {
00102     return BitWidth <= APINT_BITS_PER_WORD;
00103   }
00104 
00105   /// @returns the word position for the specified bit position.
00106   /// @brief Determine which word a bit is in.
00107   static unsigned whichWord(unsigned bitPosition) {
00108     return bitPosition / APINT_BITS_PER_WORD;
00109   }
00110 
00111   /// @returns the bit position in a word for the specified bit position
00112   /// in the APInt.
00113   /// @brief Determine which bit in a word a bit is in.
00114   static unsigned whichBit(unsigned bitPosition) {
00115     return bitPosition % APINT_BITS_PER_WORD;
00116   }
00117 
00118   /// This method generates and returns a uint64_t (word) mask for a single
00119   /// bit at a specific bit position. This is used to mask the bit in the
00120   /// corresponding word.
00121   /// @returns a uint64_t with only bit at "whichBit(bitPosition)" set
00122   /// @brief Get a single bit mask.
00123   static uint64_t maskBit(unsigned bitPosition) {
00124     return 1ULL << whichBit(bitPosition);
00125   }
00126 
00127   /// This method is used internally to clear the to "N" bits in the high order
00128   /// word that are not used by the APInt. This is needed after the most
00129   /// significant word is assigned a value to ensure that those bits are
00130   /// zero'd out.
00131   /// @brief Clear unused high order bits
00132   APInt& clearUnusedBits() {
00133     // Compute how many bits are used in the final word
00134     unsigned wordBits = BitWidth % APINT_BITS_PER_WORD;
00135     if (wordBits == 0)
00136       // If all bits are used, we want to leave the value alone. This also
00137       // avoids the undefined behavior of >> when the shift is the same size as
00138       // the word size (64).
00139       return *this;
00140 
00141     // Mask out the high bits.
00142     uint64_t mask = ~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - wordBits);
00143     if (isSingleWord())
00144       VAL &= mask;
00145     else
00146       pVal[getNumWords() - 1] &= mask;
00147     return *this;
00148   }
00149 
00150   /// @returns the corresponding word for the specified bit position.
00151   /// @brief Get the word corresponding to a bit position
00152   uint64_t getWord(unsigned bitPosition) const {
00153     return isSingleWord() ? VAL : pVal[whichWord(bitPosition)];
00154   }
00155 
00156   /// Converts a string into a number.  The string must be non-empty
00157   /// and well-formed as a number of the given base. The bit-width
00158   /// must be sufficient to hold the result.
00159   ///
00160   /// This is used by the constructors that take string arguments.
00161   ///
00162   /// StringRef::getAsInteger is superficially similar but (1) does
00163   /// not assume that the string is well-formed and (2) grows the
00164   /// result to hold the input.
00165   ///
00166   /// @param radix 2, 8, 10, 16, or 36
00167   /// @brief Convert a char array into an APInt
00168   void fromString(unsigned numBits, StringRef str, uint8_t radix);
00169 
00170   /// This is used by the toString method to divide by the radix. It simply
00171   /// provides a more convenient form of divide for internal use since KnuthDiv
00172   /// has specific constraints on its inputs. If those constraints are not met
00173   /// then it provides a simpler form of divide.
00174   /// @brief An internal division function for dividing APInts.
00175   static void divide(const APInt LHS, unsigned lhsWords,
00176                      const APInt &RHS, unsigned rhsWords,
00177                      APInt *Quotient, APInt *Remainder);
00178 
00179   /// out-of-line slow case for inline constructor
00180   void initSlowCase(unsigned numBits, uint64_t val, bool isSigned);
00181 
00182   /// shared code between two array constructors
00183   void initFromArray(ArrayRef<uint64_t> array);
00184 
00185   /// out-of-line slow case for inline copy constructor
00186   void initSlowCase(const APInt& that);
00187 
00188   /// out-of-line slow case for shl
00189   APInt shlSlowCase(unsigned shiftAmt) const;
00190 
00191   /// out-of-line slow case for operator&
00192   APInt AndSlowCase(const APInt& RHS) const;
00193 
00194   /// out-of-line slow case for operator|
00195   APInt OrSlowCase(const APInt& RHS) const;
00196 
00197   /// out-of-line slow case for operator^
00198   APInt XorSlowCase(const APInt& RHS) const;
00199 
00200   /// out-of-line slow case for operator=
00201   APInt& AssignSlowCase(const APInt& RHS);
00202 
00203   /// out-of-line slow case for operator==
00204   bool EqualSlowCase(const APInt& RHS) const;
00205 
00206   /// out-of-line slow case for operator==
00207   bool EqualSlowCase(uint64_t Val) const;
00208 
00209   /// out-of-line slow case for countLeadingZeros
00210   unsigned countLeadingZerosSlowCase() const;
00211 
00212   /// out-of-line slow case for countTrailingOnes
00213   unsigned countTrailingOnesSlowCase() const;
00214 
00215   /// out-of-line slow case for countPopulation
00216   unsigned countPopulationSlowCase() const;
00217 
00218 public:
00219   /// @name Constructors
00220   /// @{
00221   /// If isSigned is true then val is treated as if it were a signed value
00222   /// (i.e. as an int64_t) and the appropriate sign extension to the bit width
00223   /// will be done. Otherwise, no sign extension occurs (high order bits beyond
00224   /// the range of val are zero filled).
00225   /// @param numBits the bit width of the constructed APInt
00226   /// @param val the initial value of the APInt
00227   /// @param isSigned how to treat signedness of val
00228   /// @brief Create a new APInt of numBits width, initialized as val.
00229   APInt(unsigned numBits, uint64_t val, bool isSigned = false)
00230     : BitWidth(numBits), VAL(0) {
00231     assert(BitWidth && "bitwidth too small");
00232     if (isSingleWord())
00233       VAL = val;
00234     else
00235       initSlowCase(numBits, val, isSigned);
00236     clearUnusedBits();
00237   }
00238 
00239   /// Note that bigVal.size() can be smaller or larger than the corresponding
00240   /// bit width but any extraneous bits will be dropped.
00241   /// @param numBits the bit width of the constructed APInt
00242   /// @param bigVal a sequence of words to form the initial value of the APInt
00243   /// @brief Construct an APInt of numBits width, initialized as bigVal[].
00244   APInt(unsigned numBits, ArrayRef<uint64_t> bigVal);
00245   /// Equivalent to APInt(numBits, ArrayRef<uint64_t>(bigVal, numWords)), but
00246   /// deprecated because this constructor is prone to ambiguity with the
00247   /// APInt(unsigned, uint64_t, bool) constructor.
00248   ///
00249   /// If this overload is ever deleted, care should be taken to prevent calls
00250   /// from being incorrectly captured by the APInt(unsigned, uint64_t, bool)
00251   /// constructor.
00252   APInt(unsigned numBits, unsigned numWords, const uint64_t bigVal[]);
00253 
00254   /// This constructor interprets the string \p str in the given radix. The
00255   /// interpretation stops when the first character that is not suitable for the
00256   /// radix is encountered, or the end of the string. Acceptable radix values
00257   /// are 2, 8, 10, 16, and 36. It is an error for the value implied by the 
00258   /// string to require more bits than numBits.
00259   ///
00260   /// @param numBits the bit width of the constructed APInt
00261   /// @param str the string to be interpreted
00262   /// @param radix the radix to use for the conversion 
00263   /// @brief Construct an APInt from a string representation.
00264   APInt(unsigned numBits, StringRef str, uint8_t radix);
00265 
00266   /// Simply makes *this a copy of that.
00267   /// @brief Copy Constructor.
00268   APInt(const APInt& that)
00269     : BitWidth(that.BitWidth), VAL(0) {
00270     assert(BitWidth && "bitwidth too small");
00271     if (isSingleWord())
00272       VAL = that.VAL;
00273     else
00274       initSlowCase(that);
00275   }
00276 
00277 #if LLVM_HAS_RVALUE_REFERENCES
00278   /// @brief Move Constructor.
00279   APInt(APInt&& that) : BitWidth(that.BitWidth), VAL(that.VAL) {
00280     that.BitWidth = 0;
00281   }
00282 #endif
00283 
00284   /// @brief Destructor.
00285   ~APInt() {
00286     if (!isSingleWord())
00287       delete [] pVal;
00288   }
00289 
00290   /// Default constructor that creates an uninitialized APInt.  This is useful
00291   ///  for object deserialization (pair this with the static method Read).
00292   explicit APInt() : BitWidth(1) {}
00293 
00294   /// Profile - Used to insert APInt objects, or objects that contain APInt
00295   ///  objects, into FoldingSets.
00296   void Profile(FoldingSetNodeID& id) const;
00297 
00298   /// @}
00299   /// @name Value Tests
00300   /// @{
00301   /// This tests the high bit of this APInt to determine if it is set.
00302   /// @returns true if this APInt is negative, false otherwise
00303   /// @brief Determine sign of this APInt.
00304   bool isNegative() const {
00305     return (*this)[BitWidth - 1];
00306   }
00307 
00308   /// This tests the high bit of the APInt to determine if it is unset.
00309   /// @brief Determine if this APInt Value is non-negative (>= 0)
00310   bool isNonNegative() const {
00311     return !isNegative();
00312   }
00313 
00314   /// This tests if the value of this APInt is positive (> 0). Note
00315   /// that 0 is not a positive value.
00316   /// @returns true if this APInt is positive.
00317   /// @brief Determine if this APInt Value is positive.
00318   bool isStrictlyPositive() const {
00319     return isNonNegative() && !!*this;
00320   }
00321 
00322   /// This checks to see if the value has all bits of the APInt are set or not.
00323   /// @brief Determine if all bits are set
00324   bool isAllOnesValue() const {
00325     return countPopulation() == BitWidth;
00326   }
00327 
00328   /// This checks to see if the value of this APInt is the maximum unsigned
00329   /// value for the APInt's bit width.
00330   /// @brief Determine if this is the largest unsigned value.
00331   bool isMaxValue() const {
00332     return countPopulation() == BitWidth;
00333   }
00334 
00335   /// This checks to see if the value of this APInt is the maximum signed
00336   /// value for the APInt's bit width.
00337   /// @brief Determine if this is the largest signed value.
00338   bool isMaxSignedValue() const {
00339     return BitWidth == 1 ? VAL == 0 :
00340                           !isNegative() && countPopulation() == BitWidth - 1;
00341   }
00342 
00343   /// This checks to see if the value of this APInt is the minimum unsigned
00344   /// value for the APInt's bit width.
00345   /// @brief Determine if this is the smallest unsigned value.
00346   bool isMinValue() const {
00347     return !*this;
00348   }
00349 
00350   /// This checks to see if the value of this APInt is the minimum signed
00351   /// value for the APInt's bit width.
00352   /// @brief Determine if this is the smallest signed value.
00353   bool isMinSignedValue() const {
00354     return BitWidth == 1 ? VAL == 1 : isNegative() && isPowerOf2();
00355   }
00356 
00357   /// @brief Check if this APInt has an N-bits unsigned integer value.
00358   bool isIntN(unsigned N) const {
00359     assert(N && "N == 0 ???");
00360     return getActiveBits() <= N;
00361   }
00362 
00363   /// @brief Check if this APInt has an N-bits signed integer value.
00364   bool isSignedIntN(unsigned N) const {
00365     assert(N && "N == 0 ???");
00366     return getMinSignedBits() <= N;
00367   }
00368 
00369   /// @returns true if the argument APInt value is a power of two > 0.
00370   bool isPowerOf2() const {
00371     if (isSingleWord())
00372       return isPowerOf2_64(VAL);
00373     return countPopulationSlowCase() == 1;
00374   }
00375 
00376   /// isSignBit - Return true if this is the value returned by getSignBit.
00377   bool isSignBit() const { return isMinSignedValue(); }
00378 
00379   /// This converts the APInt to a boolean value as a test against zero.
00380   /// @brief Boolean conversion function.
00381   bool getBoolValue() const {
00382     return !!*this;
00383   }
00384 
00385   /// getLimitedValue - If this value is smaller than the specified limit,
00386   /// return it, otherwise return the limit value.  This causes the value
00387   /// to saturate to the limit.
00388   uint64_t getLimitedValue(uint64_t Limit = ~0ULL) const {
00389     return (getActiveBits() > 64 || getZExtValue() > Limit) ?
00390       Limit :  getZExtValue();
00391   }
00392 
00393   /// @}
00394   /// @name Value Generators
00395   /// @{
00396   /// @brief Gets maximum unsigned value of APInt for specific bit width.
00397   static APInt getMaxValue(unsigned numBits) {
00398     return getAllOnesValue(numBits);
00399   }
00400 
00401   /// @brief Gets maximum signed value of APInt for a specific bit width.
00402   static APInt getSignedMaxValue(unsigned numBits) {
00403     APInt API = getAllOnesValue(numBits);
00404     API.clearBit(numBits - 1);
00405     return API;
00406   }
00407 
00408   /// @brief Gets minimum unsigned value of APInt for a specific bit width.
00409   static APInt getMinValue(unsigned numBits) {
00410     return APInt(numBits, 0);
00411   }
00412 
00413   /// @brief Gets minimum signed value of APInt for a specific bit width.
00414   static APInt getSignedMinValue(unsigned numBits) {
00415     APInt API(numBits, 0);
00416     API.setBit(numBits - 1);
00417     return API;
00418   }
00419 
00420   /// getSignBit - This is just a wrapper function of getSignedMinValue(), and
00421   /// it helps code readability when we want to get a SignBit.
00422   /// @brief Get the SignBit for a specific bit width.
00423   static APInt getSignBit(unsigned BitWidth) {
00424     return getSignedMinValue(BitWidth);
00425   }
00426 
00427   /// @returns the all-ones value for an APInt of the specified bit-width.
00428   /// @brief Get the all-ones value.
00429   static APInt getAllOnesValue(unsigned numBits) {
00430     return APInt(numBits, UINT64_MAX, true);
00431   }
00432 
00433   /// @returns the '0' value for an APInt of the specified bit-width.
00434   /// @brief Get the '0' value.
00435   static APInt getNullValue(unsigned numBits) {
00436     return APInt(numBits, 0);
00437   }
00438 
00439   /// Get an APInt with the same BitWidth as this APInt, just zero mask
00440   /// the low bits and right shift to the least significant bit.
00441   /// @returns the high "numBits" bits of this APInt.
00442   APInt getHiBits(unsigned numBits) const;
00443 
00444   /// Get an APInt with the same BitWidth as this APInt, just zero mask
00445   /// the high bits.
00446   /// @returns the low "numBits" bits of this APInt.
00447   APInt getLoBits(unsigned numBits) const;
00448 
00449   /// getOneBitSet - Return an APInt with exactly one bit set in the result.
00450   static APInt getOneBitSet(unsigned numBits, unsigned BitNo) {
00451     APInt Res(numBits, 0);
00452     Res.setBit(BitNo);
00453     return Res;
00454   }
00455   
00456   /// Constructs an APInt value that has a contiguous range of bits set. The
00457   /// bits from loBit (inclusive) to hiBit (exclusive) will be set. All other
00458   /// bits will be zero. For example, with parameters(32, 0, 16) you would get
00459   /// 0x0000FFFF. If hiBit is less than loBit then the set bits "wrap". For
00460   /// example, with parameters (32, 28, 4), you would get 0xF000000F.
00461   /// @param numBits the intended bit width of the result
00462   /// @param loBit the index of the lowest bit set.
00463   /// @param hiBit the index of the highest bit set.
00464   /// @returns An APInt value with the requested bits set.
00465   /// @brief Get a value with a block of bits set.
00466   static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit) {
00467     assert(hiBit <= numBits && "hiBit out of range");
00468     assert(loBit < numBits && "loBit out of range");
00469     if (hiBit < loBit)
00470       return getLowBitsSet(numBits, hiBit) |
00471              getHighBitsSet(numBits, numBits-loBit);
00472     return getLowBitsSet(numBits, hiBit-loBit).shl(loBit);
00473   }
00474 
00475   /// Constructs an APInt value that has the top hiBitsSet bits set.
00476   /// @param numBits the bitwidth of the result
00477   /// @param hiBitsSet the number of high-order bits set in the result.
00478   /// @brief Get a value with high bits set
00479   static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet) {
00480     assert(hiBitsSet <= numBits && "Too many bits to set!");
00481     // Handle a degenerate case, to avoid shifting by word size
00482     if (hiBitsSet == 0)
00483       return APInt(numBits, 0);
00484     unsigned shiftAmt = numBits - hiBitsSet;
00485     // For small values, return quickly
00486     if (numBits <= APINT_BITS_PER_WORD)
00487       return APInt(numBits, ~0ULL << shiftAmt);
00488     return getAllOnesValue(numBits).shl(shiftAmt);
00489   }
00490 
00491   /// Constructs an APInt value that has the bottom loBitsSet bits set.
00492   /// @param numBits the bitwidth of the result
00493   /// @param loBitsSet the number of low-order bits set in the result.
00494   /// @brief Get a value with low bits set
00495   static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet) {
00496     assert(loBitsSet <= numBits && "Too many bits to set!");
00497     // Handle a degenerate case, to avoid shifting by word size
00498     if (loBitsSet == 0)
00499       return APInt(numBits, 0);
00500     if (loBitsSet == APINT_BITS_PER_WORD)
00501       return APInt(numBits, UINT64_MAX);
00502     // For small values, return quickly.
00503     if (loBitsSet <= APINT_BITS_PER_WORD)
00504       return APInt(numBits, UINT64_MAX >> (APINT_BITS_PER_WORD - loBitsSet));
00505     return getAllOnesValue(numBits).lshr(numBits - loBitsSet);
00506   }
00507 
00508   /// \brief Return a value containing V broadcasted over NewLen bits.
00509   static APInt getSplat(unsigned NewLen, const APInt &V) {
00510     assert(NewLen >= V.getBitWidth() && "Can't splat to smaller bit width!");
00511 
00512     APInt Val = V.zextOrSelf(NewLen);
00513     for (unsigned I = V.getBitWidth(); I < NewLen; I <<= 1)
00514       Val |= Val << I;
00515 
00516     return Val;
00517   }
00518 
00519   /// \brief Determine if two APInts have the same value, after zero-extending
00520   /// one of them (if needed!) to ensure that the bit-widths match.
00521   static bool isSameValue(const APInt &I1, const APInt &I2) {
00522     if (I1.getBitWidth() == I2.getBitWidth())
00523       return I1 == I2;
00524 
00525     if (I1.getBitWidth() > I2.getBitWidth())
00526       return I1 == I2.zext(I1.getBitWidth());
00527 
00528     return I1.zext(I2.getBitWidth()) == I2;
00529   }
00530   
00531   /// \brief Overload to compute a hash_code for an APInt value.
00532   friend hash_code hash_value(const APInt &Arg);
00533 
00534   /// This function returns a pointer to the internal storage of the APInt.
00535   /// This is useful for writing out the APInt in binary form without any
00536   /// conversions.
00537   const uint64_t* getRawData() const {
00538     if (isSingleWord())
00539       return &VAL;
00540     return &pVal[0];
00541   }
00542 
00543   /// @}
00544   /// @name Unary Operators
00545   /// @{
00546   /// @returns a new APInt value representing *this incremented by one
00547   /// @brief Postfix increment operator.
00548   const APInt operator++(int) {
00549     APInt API(*this);
00550     ++(*this);
00551     return API;
00552   }
00553 
00554   /// @returns *this incremented by one
00555   /// @brief Prefix increment operator.
00556   APInt& operator++();
00557 
00558   /// @returns a new APInt representing *this decremented by one.
00559   /// @brief Postfix decrement operator.
00560   const APInt operator--(int) {
00561     APInt API(*this);
00562     --(*this);
00563     return API;
00564   }
00565 
00566   /// @returns *this decremented by one.
00567   /// @brief Prefix decrement operator.
00568   APInt& operator--();
00569 
00570   /// Performs a bitwise complement operation on this APInt.
00571   /// @returns an APInt that is the bitwise complement of *this
00572   /// @brief Unary bitwise complement operator.
00573   APInt operator~() const {
00574     APInt Result(*this);
00575     Result.flipAllBits();
00576     return Result;
00577   }
00578 
00579   /// Negates *this using two's complement logic.
00580   /// @returns An APInt value representing the negation of *this.
00581   /// @brief Unary negation operator
00582   APInt operator-() const {
00583     return APInt(BitWidth, 0) - (*this);
00584   }
00585 
00586   /// Performs logical negation operation on this APInt.
00587   /// @returns true if *this is zero, false otherwise.
00588   /// @brief Logical negation operator.
00589   bool operator!() const {
00590     if (isSingleWord())
00591       return !VAL;
00592 
00593     for (unsigned i = 0; i != getNumWords(); ++i)
00594       if (pVal[i])
00595         return false;
00596     return true;
00597   }
00598 
00599   /// @}
00600   /// @name Assignment Operators
00601   /// @{
00602   /// @returns *this after assignment of RHS.
00603   /// @brief Copy assignment operator.
00604   APInt& operator=(const APInt& RHS) {
00605     // If the bitwidths are the same, we can avoid mucking with memory
00606     if (isSingleWord() && RHS.isSingleWord()) {
00607       VAL = RHS.VAL;
00608       BitWidth = RHS.BitWidth;
00609       return clearUnusedBits();
00610     }
00611 
00612     return AssignSlowCase(RHS);
00613   }
00614 
00615 #if LLVM_HAS_RVALUE_REFERENCES
00616   /// @brief Move assignment operator.
00617   APInt& operator=(APInt&& that) {
00618     if (!isSingleWord())
00619       delete [] pVal;
00620 
00621     BitWidth = that.BitWidth;
00622     VAL = that.VAL;
00623 
00624     that.BitWidth = 0;
00625 
00626     return *this;
00627   }
00628 #endif
00629 
00630   /// The RHS value is assigned to *this. If the significant bits in RHS exceed
00631   /// the bit width, the excess bits are truncated. If the bit width is larger
00632   /// than 64, the value is zero filled in the unspecified high order bits.
00633   /// @returns *this after assignment of RHS value.
00634   /// @brief Assignment operator.
00635   APInt& operator=(uint64_t RHS);
00636 
00637   /// Performs a bitwise AND operation on this APInt and RHS. The result is
00638   /// assigned to *this.
00639   /// @returns *this after ANDing with RHS.
00640   /// @brief Bitwise AND assignment operator.
00641   APInt& operator&=(const APInt& RHS);
00642 
00643   /// Performs a bitwise OR operation on this APInt and RHS. The result is
00644   /// assigned *this;
00645   /// @returns *this after ORing with RHS.
00646   /// @brief Bitwise OR assignment operator.
00647   APInt& operator|=(const APInt& RHS);
00648 
00649   /// Performs a bitwise OR operation on this APInt and RHS. RHS is
00650   /// logically zero-extended or truncated to match the bit-width of
00651   /// the LHS.
00652   /// 
00653   /// @brief Bitwise OR assignment operator.
00654   APInt& operator|=(uint64_t RHS) {
00655     if (isSingleWord()) {
00656       VAL |= RHS;
00657       clearUnusedBits();
00658     } else {
00659       pVal[0] |= RHS;
00660     }
00661     return *this;
00662   }
00663 
00664   /// Performs a bitwise XOR operation on this APInt and RHS. The result is
00665   /// assigned to *this.
00666   /// @returns *this after XORing with RHS.
00667   /// @brief Bitwise XOR assignment operator.
00668   APInt& operator^=(const APInt& RHS);
00669 
00670   /// Multiplies this APInt by RHS and assigns the result to *this.
00671   /// @returns *this
00672   /// @brief Multiplication assignment operator.
00673   APInt& operator*=(const APInt& RHS);
00674 
00675   /// Adds RHS to *this and assigns the result to *this.
00676   /// @returns *this
00677   /// @brief Addition assignment operator.
00678   APInt& operator+=(const APInt& RHS);
00679 
00680   /// Subtracts RHS from *this and assigns the result to *this.
00681   /// @returns *this
00682   /// @brief Subtraction assignment operator.
00683   APInt& operator-=(const APInt& RHS);
00684 
00685   /// Shifts *this left by shiftAmt and assigns the result to *this.
00686   /// @returns *this after shifting left by shiftAmt
00687   /// @brief Left-shift assignment function.
00688   APInt& operator<<=(unsigned shiftAmt) {
00689     *this = shl(shiftAmt);
00690     return *this;
00691   }
00692 
00693   /// @}
00694   /// @name Binary Operators
00695   /// @{
00696   /// Performs a bitwise AND operation on *this and RHS.
00697   /// @returns An APInt value representing the bitwise AND of *this and RHS.
00698   /// @brief Bitwise AND operator.
00699   APInt operator&(const APInt& RHS) const {
00700     assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
00701     if (isSingleWord())
00702       return APInt(getBitWidth(), VAL & RHS.VAL);
00703     return AndSlowCase(RHS);
00704   }
00705   APInt And(const APInt& RHS) const {
00706     return this->operator&(RHS);
00707   }
00708 
00709   /// Performs a bitwise OR operation on *this and RHS.
00710   /// @returns An APInt value representing the bitwise OR of *this and RHS.
00711   /// @brief Bitwise OR operator.
00712   APInt operator|(const APInt& RHS) const {
00713     assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
00714     if (isSingleWord())
00715       return APInt(getBitWidth(), VAL | RHS.VAL);
00716     return OrSlowCase(RHS);
00717   }
00718   APInt Or(const APInt& RHS) const {
00719     return this->operator|(RHS);
00720   }
00721 
00722   /// Performs a bitwise XOR operation on *this and RHS.
00723   /// @returns An APInt value representing the bitwise XOR of *this and RHS.
00724   /// @brief Bitwise XOR operator.
00725   APInt operator^(const APInt& RHS) const {
00726     assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
00727     if (isSingleWord())
00728       return APInt(BitWidth, VAL ^ RHS.VAL);
00729     return XorSlowCase(RHS);
00730   }
00731   APInt Xor(const APInt& RHS) const {
00732     return this->operator^(RHS);
00733   }
00734 
00735   /// Multiplies this APInt by RHS and returns the result.
00736   /// @brief Multiplication operator.
00737   APInt operator*(const APInt& RHS) const;
00738 
00739   /// Adds RHS to this APInt and returns the result.
00740   /// @brief Addition operator.
00741   APInt operator+(const APInt& RHS) const;
00742   APInt operator+(uint64_t RHS) const {
00743     return (*this) + APInt(BitWidth, RHS);
00744   }
00745 
00746   /// Subtracts RHS from this APInt and returns the result.
00747   /// @brief Subtraction operator.
00748   APInt operator-(const APInt& RHS) const;
00749   APInt operator-(uint64_t RHS) const {
00750     return (*this) - APInt(BitWidth, RHS);
00751   }
00752 
00753   APInt operator<<(unsigned Bits) const {
00754     return shl(Bits);
00755   }
00756 
00757   APInt operator<<(const APInt &Bits) const {
00758     return shl(Bits);
00759   }
00760 
00761   /// Arithmetic right-shift this APInt by shiftAmt.
00762   /// @brief Arithmetic right-shift function.
00763   APInt ashr(unsigned shiftAmt) const;
00764 
00765   /// Logical right-shift this APInt by shiftAmt.
00766   /// @brief Logical right-shift function.
00767   APInt lshr(unsigned shiftAmt) const;
00768 
00769   /// Left-shift this APInt by shiftAmt.
00770   /// @brief Left-shift function.
00771   APInt shl(unsigned shiftAmt) const {
00772     assert(shiftAmt <= BitWidth && "Invalid shift amount");
00773     if (isSingleWord()) {
00774       if (shiftAmt >= BitWidth)
00775         return APInt(BitWidth, 0); // avoid undefined shift results
00776       return APInt(BitWidth, VAL << shiftAmt);
00777     }
00778     return shlSlowCase(shiftAmt);
00779   }
00780 
00781   /// @brief Rotate left by rotateAmt.
00782   APInt rotl(unsigned rotateAmt) const;
00783 
00784   /// @brief Rotate right by rotateAmt.
00785   APInt rotr(unsigned rotateAmt) const;
00786 
00787   /// Arithmetic right-shift this APInt by shiftAmt.
00788   /// @brief Arithmetic right-shift function.
00789   APInt ashr(const APInt &shiftAmt) const;
00790 
00791   /// Logical right-shift this APInt by shiftAmt.
00792   /// @brief Logical right-shift function.
00793   APInt lshr(const APInt &shiftAmt) const;
00794 
00795   /// Left-shift this APInt by shiftAmt.
00796   /// @brief Left-shift function.
00797   APInt shl(const APInt &shiftAmt) const;
00798 
00799   /// @brief Rotate left by rotateAmt.
00800   APInt rotl(const APInt &rotateAmt) const;
00801 
00802   /// @brief Rotate right by rotateAmt.
00803   APInt rotr(const APInt &rotateAmt) const;
00804 
00805   /// Perform an unsigned divide operation on this APInt by RHS. Both this and
00806   /// RHS are treated as unsigned quantities for purposes of this division.
00807   /// @returns a new APInt value containing the division result
00808   /// @brief Unsigned division operation.
00809   APInt udiv(const APInt &RHS) const;
00810 
00811   /// Signed divide this APInt by APInt RHS.
00812   /// @brief Signed division function for APInt.
00813   APInt sdiv(const APInt &RHS) const;
00814 
00815   /// Perform an unsigned remainder operation on this APInt with RHS being the
00816   /// divisor. Both this and RHS are treated as unsigned quantities for purposes
00817   /// of this operation. Note that this is a true remainder operation and not
00818   /// a modulo operation because the sign follows the sign of the dividend
00819   /// which is *this.
00820   /// @returns a new APInt value containing the remainder result
00821   /// @brief Unsigned remainder operation.
00822   APInt urem(const APInt &RHS) const;
00823 
00824   /// Signed remainder operation on APInt.
00825   /// @brief Function for signed remainder operation.
00826   APInt srem(const APInt &RHS) const;
00827 
00828   /// Sometimes it is convenient to divide two APInt values and obtain both the
00829   /// quotient and remainder. This function does both operations in the same
00830   /// computation making it a little more efficient. The pair of input arguments
00831   /// may overlap with the pair of output arguments. It is safe to call
00832   /// udivrem(X, Y, X, Y), for example.
00833   /// @brief Dual division/remainder interface.
00834   static void udivrem(const APInt &LHS, const APInt &RHS,
00835                       APInt &Quotient, APInt &Remainder);
00836 
00837   static void sdivrem(const APInt &LHS, const APInt &RHS,
00838                       APInt &Quotient, APInt &Remainder);
00839 
00840 
00841   // Operations that return overflow indicators.
00842   APInt sadd_ov(const APInt &RHS, bool &Overflow) const;
00843   APInt uadd_ov(const APInt &RHS, bool &Overflow) const;
00844   APInt ssub_ov(const APInt &RHS, bool &Overflow) const;
00845   APInt usub_ov(const APInt &RHS, bool &Overflow) const;
00846   APInt sdiv_ov(const APInt &RHS, bool &Overflow) const;
00847   APInt smul_ov(const APInt &RHS, bool &Overflow) const;
00848   APInt umul_ov(const APInt &RHS, bool &Overflow) const;
00849   APInt sshl_ov(unsigned Amt, bool &Overflow) const;
00850 
00851   /// @returns the bit value at bitPosition
00852   /// @brief Array-indexing support.
00853   bool operator[](unsigned bitPosition) const {
00854     assert(bitPosition < getBitWidth() && "Bit position out of bounds!");
00855     return (maskBit(bitPosition) &
00856             (isSingleWord() ? VAL : pVal[whichWord(bitPosition)])) != 0;
00857   }
00858 
00859   /// @}
00860   /// @name Comparison Operators
00861   /// @{
00862   /// Compares this APInt with RHS for the validity of the equality
00863   /// relationship.
00864   /// @brief Equality operator.
00865   bool operator==(const APInt& RHS) const {
00866     assert(BitWidth == RHS.BitWidth && "Comparison requires equal bit widths");
00867     if (isSingleWord())
00868       return VAL == RHS.VAL;
00869     return EqualSlowCase(RHS);
00870   }
00871 
00872   /// Compares this APInt with a uint64_t for the validity of the equality
00873   /// relationship.
00874   /// @returns true if *this == Val
00875   /// @brief Equality operator.
00876   bool operator==(uint64_t Val) const {
00877     if (isSingleWord())
00878       return VAL == Val;
00879     return EqualSlowCase(Val);
00880   }
00881 
00882   /// Compares this APInt with RHS for the validity of the equality
00883   /// relationship.
00884   /// @returns true if *this == Val
00885   /// @brief Equality comparison.
00886   bool eq(const APInt &RHS) const {
00887     return (*this) == RHS;
00888   }
00889 
00890   /// Compares this APInt with RHS for the validity of the inequality
00891   /// relationship.
00892   /// @returns true if *this != Val
00893   /// @brief Inequality operator.
00894   bool operator!=(const APInt& RHS) const {
00895     return !((*this) == RHS);
00896   }
00897 
00898   /// Compares this APInt with a uint64_t for the validity of the inequality
00899   /// relationship.
00900   /// @returns true if *this != Val
00901   /// @brief Inequality operator.
00902   bool operator!=(uint64_t Val) const {
00903     return !((*this) == Val);
00904   }
00905 
00906   /// Compares this APInt with RHS for the validity of the inequality
00907   /// relationship.
00908   /// @returns true if *this != Val
00909   /// @brief Inequality comparison
00910   bool ne(const APInt &RHS) const {
00911     return !((*this) == RHS);
00912   }
00913 
00914   /// Regards both *this and RHS as unsigned quantities and compares them for
00915   /// the validity of the less-than relationship.
00916   /// @returns true if *this < RHS when both are considered unsigned.
00917   /// @brief Unsigned less than comparison
00918   bool ult(const APInt &RHS) const;
00919 
00920   /// Regards both *this as an unsigned quantity and compares it with RHS for
00921   /// the validity of the less-than relationship.
00922   /// @returns true if *this < RHS when considered unsigned.
00923   /// @brief Unsigned less than comparison
00924   bool ult(uint64_t RHS) const {
00925     return ult(APInt(getBitWidth(), RHS));
00926   }
00927 
00928   /// Regards both *this and RHS as signed quantities and compares them for
00929   /// validity of the less-than relationship.
00930   /// @returns true if *this < RHS when both are considered signed.
00931   /// @brief Signed less than comparison
00932   bool slt(const APInt& RHS) const;
00933 
00934   /// Regards both *this as a signed quantity and compares it with RHS for
00935   /// the validity of the less-than relationship.
00936   /// @returns true if *this < RHS when considered signed.
00937   /// @brief Signed less than comparison
00938   bool slt(uint64_t RHS) const {
00939     return slt(APInt(getBitWidth(), RHS));
00940   }
00941 
00942   /// Regards both *this and RHS as unsigned quantities and compares them for
00943   /// validity of the less-or-equal relationship.
00944   /// @returns true if *this <= RHS when both are considered unsigned.
00945   /// @brief Unsigned less or equal comparison
00946   bool ule(const APInt& RHS) const {
00947     return ult(RHS) || eq(RHS);
00948   }
00949 
00950   /// Regards both *this as an unsigned quantity and compares it with RHS for
00951   /// the validity of the less-or-equal relationship.
00952   /// @returns true if *this <= RHS when considered unsigned.
00953   /// @brief Unsigned less or equal comparison
00954   bool ule(uint64_t RHS) const {
00955     return ule(APInt(getBitWidth(), RHS));
00956   }
00957 
00958   /// Regards both *this and RHS as signed quantities and compares them for
00959   /// validity of the less-or-equal relationship.
00960   /// @returns true if *this <= RHS when both are considered signed.
00961   /// @brief Signed less or equal comparison
00962   bool sle(const APInt& RHS) const {
00963     return slt(RHS) || eq(RHS);
00964   }
00965 
00966   /// Regards both *this as a signed quantity and compares it with RHS for
00967   /// the validity of the less-or-equal relationship.
00968   /// @returns true if *this <= RHS when considered signed.
00969   /// @brief Signed less or equal comparison
00970   bool sle(uint64_t RHS) const {
00971     return sle(APInt(getBitWidth(), RHS));
00972   }
00973 
00974   /// Regards both *this and RHS as unsigned quantities and compares them for
00975   /// the validity of the greater-than relationship.
00976   /// @returns true if *this > RHS when both are considered unsigned.
00977   /// @brief Unsigned greather than comparison
00978   bool ugt(const APInt& RHS) const {
00979     return !ult(RHS) && !eq(RHS);
00980   }
00981 
00982   /// Regards both *this as an unsigned quantity and compares it with RHS for
00983   /// the validity of the greater-than relationship.
00984   /// @returns true if *this > RHS when considered unsigned.
00985   /// @brief Unsigned greater than comparison
00986   bool ugt(uint64_t RHS) const {
00987     return ugt(APInt(getBitWidth(), RHS));
00988   }
00989 
00990   /// Regards both *this and RHS as signed quantities and compares them for
00991   /// the validity of the greater-than relationship.
00992   /// @returns true if *this > RHS when both are considered signed.
00993   /// @brief Signed greather than comparison
00994   bool sgt(const APInt& RHS) const {
00995     return !slt(RHS) && !eq(RHS);
00996   }
00997 
00998   /// Regards both *this as a signed quantity and compares it with RHS for
00999   /// the validity of the greater-than relationship.
01000   /// @returns true if *this > RHS when considered signed.
01001   /// @brief Signed greater than comparison
01002   bool sgt(uint64_t RHS) const {
01003     return sgt(APInt(getBitWidth(), RHS));
01004   }
01005 
01006   /// Regards both *this and RHS as unsigned quantities and compares them for
01007   /// validity of the greater-or-equal relationship.
01008   /// @returns true if *this >= RHS when both are considered unsigned.
01009   /// @brief Unsigned greater or equal comparison
01010   bool uge(const APInt& RHS) const {
01011     return !ult(RHS);
01012   }
01013 
01014   /// Regards both *this as an unsigned quantity and compares it with RHS for
01015   /// the validity of the greater-or-equal relationship.
01016   /// @returns true if *this >= RHS when considered unsigned.
01017   /// @brief Unsigned greater or equal comparison
01018   bool uge(uint64_t RHS) const {
01019     return uge(APInt(getBitWidth(), RHS));
01020   }
01021 
01022   /// Regards both *this and RHS as signed quantities and compares them for
01023   /// validity of the greater-or-equal relationship.
01024   /// @returns true if *this >= RHS when both are considered signed.
01025   /// @brief Signed greather or equal comparison
01026   bool sge(const APInt& RHS) const {
01027     return !slt(RHS);
01028   }
01029 
01030   /// Regards both *this as a signed quantity and compares it with RHS for
01031   /// the validity of the greater-or-equal relationship.
01032   /// @returns true if *this >= RHS when considered signed.
01033   /// @brief Signed greater or equal comparison
01034   bool sge(uint64_t RHS) const {
01035     return sge(APInt(getBitWidth(), RHS));
01036   }
01037 
01038   
01039   
01040   
01041   /// This operation tests if there are any pairs of corresponding bits
01042   /// between this APInt and RHS that are both set.
01043   bool intersects(const APInt &RHS) const {
01044     return (*this & RHS) != 0;
01045   }
01046 
01047   /// @}
01048   /// @name Resizing Operators
01049   /// @{
01050   /// Truncate the APInt to a specified width. It is an error to specify a width
01051   /// that is greater than or equal to the current width.
01052   /// @brief Truncate to new width.
01053   APInt trunc(unsigned width) const;
01054 
01055   /// This operation sign extends the APInt to a new width. If the high order
01056   /// bit is set, the fill on the left will be done with 1 bits, otherwise zero.
01057   /// It is an error to specify a width that is less than or equal to the
01058   /// current width.
01059   /// @brief Sign extend to a new width.
01060   APInt sext(unsigned width) const;
01061 
01062   /// This operation zero extends the APInt to a new width. The high order bits
01063   /// are filled with 0 bits.  It is an error to specify a width that is less
01064   /// than or equal to the current width.
01065   /// @brief Zero extend to a new width.
01066   APInt zext(unsigned width) const;
01067 
01068   /// Make this APInt have the bit width given by \p width. The value is sign
01069   /// extended, truncated, or left alone to make it that width.
01070   /// @brief Sign extend or truncate to width
01071   APInt sextOrTrunc(unsigned width) const;
01072 
01073   /// Make this APInt have the bit width given by \p width. The value is zero
01074   /// extended, truncated, or left alone to make it that width.
01075   /// @brief Zero extend or truncate to width
01076   APInt zextOrTrunc(unsigned width) const;
01077 
01078   /// Make this APInt have the bit width given by \p width. The value is sign
01079   /// extended, or left alone to make it that width.
01080   /// @brief Sign extend or truncate to width
01081   APInt sextOrSelf(unsigned width) const;
01082 
01083   /// Make this APInt have the bit width given by \p width. The value is zero
01084   /// extended, or left alone to make it that width.
01085   /// @brief Zero extend or truncate to width
01086   APInt zextOrSelf(unsigned width) const;
01087 
01088   /// @}
01089   /// @name Bit Manipulation Operators
01090   /// @{
01091   /// @brief Set every bit to 1.
01092   void setAllBits() {
01093     if (isSingleWord())
01094       VAL = UINT64_MAX;
01095     else {
01096       // Set all the bits in all the words.
01097       for (unsigned i = 0; i < getNumWords(); ++i)
01098         pVal[i] = UINT64_MAX;
01099     }
01100     // Clear the unused ones
01101     clearUnusedBits();
01102   }
01103 
01104   /// Set the given bit to 1 whose position is given as "bitPosition".
01105   /// @brief Set a given bit to 1.
01106   void setBit(unsigned bitPosition);
01107 
01108   /// @brief Set every bit to 0.
01109   void clearAllBits() {
01110     if (isSingleWord())
01111       VAL = 0;
01112     else
01113       memset(pVal, 0, getNumWords() * APINT_WORD_SIZE);
01114   }
01115 
01116   /// Set the given bit to 0 whose position is given as "bitPosition".
01117   /// @brief Set a given bit to 0.
01118   void clearBit(unsigned bitPosition);
01119 
01120   /// @brief Toggle every bit to its opposite value.
01121   void flipAllBits() {
01122     if (isSingleWord())
01123       VAL ^= UINT64_MAX;
01124     else {
01125       for (unsigned i = 0; i < getNumWords(); ++i)
01126         pVal[i] ^= UINT64_MAX;
01127     }
01128     clearUnusedBits();
01129   }
01130 
01131   /// Toggle a given bit to its opposite value whose position is given
01132   /// as "bitPosition".
01133   /// @brief Toggles a given bit to its opposite value.
01134   void flipBit(unsigned bitPosition);
01135 
01136   /// @}
01137   /// @name Value Characterization Functions
01138   /// @{
01139 
01140   /// @returns the total number of bits.
01141   unsigned getBitWidth() const {
01142     return BitWidth;
01143   }
01144 
01145   /// Here one word's bitwidth equals to that of uint64_t.
01146   /// @returns the number of words to hold the integer value of this APInt.
01147   /// @brief Get the number of words.
01148   unsigned getNumWords() const {
01149     return getNumWords(BitWidth);
01150   }
01151 
01152   /// Here one word's bitwidth equals to that of uint64_t.
01153   /// @returns the number of words to hold the integer value with a
01154   /// given bit width.
01155   /// @brief Get the number of words.
01156   static unsigned getNumWords(unsigned BitWidth) {
01157     return (BitWidth + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD;
01158   }
01159 
01160   /// This function returns the number of active bits which is defined as the
01161   /// bit width minus the number of leading zeros. This is used in several
01162   /// computations to see how "wide" the value is.
01163   /// @brief Compute the number of active bits in the value
01164   unsigned getActiveBits() const {
01165     return BitWidth - countLeadingZeros();
01166   }
01167 
01168   /// This function returns the number of active words in the value of this
01169   /// APInt. This is used in conjunction with getActiveData to extract the raw
01170   /// value of the APInt.
01171   unsigned getActiveWords() const {
01172     unsigned numActiveBits = getActiveBits();
01173     return numActiveBits ? whichWord(numActiveBits - 1) + 1 : 1;
01174   }
01175 
01176   /// Computes the minimum bit width for this APInt while considering it to be
01177   /// a signed (and probably negative) value. If the value is not negative,
01178   /// this function returns the same value as getActiveBits()+1. Otherwise, it
01179   /// returns the smallest bit width that will retain the negative value. For
01180   /// example, -1 can be written as 0b1 or 0xFFFFFFFFFF. 0b1 is shorter and so
01181   /// for -1, this function will always return 1.
01182   /// @brief Get the minimum bit size for this signed APInt
01183   unsigned getMinSignedBits() const {
01184     if (isNegative())
01185       return BitWidth - countLeadingOnes() + 1;
01186     return getActiveBits()+1;
01187   }
01188 
01189   /// This method attempts to return the value of this APInt as a zero extended
01190   /// uint64_t. The bitwidth must be <= 64 or the value must fit within a
01191   /// uint64_t. Otherwise an assertion will result.
01192   /// @brief Get zero extended value
01193   uint64_t getZExtValue() const {
01194     if (isSingleWord())
01195       return VAL;
01196     assert(getActiveBits() <= 64 && "Too many bits for uint64_t");
01197     return pVal[0];
01198   }
01199 
01200   /// This method attempts to return the value of this APInt as a sign extended
01201   /// int64_t. The bit width must be <= 64 or the value must fit within an
01202   /// int64_t. Otherwise an assertion will result.
01203   /// @brief Get sign extended value
01204   int64_t getSExtValue() const {
01205     if (isSingleWord())
01206       return int64_t(VAL << (APINT_BITS_PER_WORD - BitWidth)) >>
01207                      (APINT_BITS_PER_WORD - BitWidth);
01208     assert(getMinSignedBits() <= 64 && "Too many bits for int64_t");
01209     return int64_t(pVal[0]);
01210   }
01211 
01212   /// This method determines how many bits are required to hold the APInt
01213   /// equivalent of the string given by \p str.
01214   /// @brief Get bits required for string value.
01215   static unsigned getBitsNeeded(StringRef str, uint8_t radix);
01216 
01217   /// countLeadingZeros - This function is an APInt version of the
01218   /// countLeadingZeros_{32,64} functions in MathExtras.h. It counts the number
01219   /// of zeros from the most significant bit to the first one bit.
01220   /// @returns BitWidth if the value is zero, otherwise
01221   /// returns the number of zeros from the most significant bit to the first
01222   /// one bits.
01223   unsigned countLeadingZeros() const {
01224     if (isSingleWord()) {
01225       unsigned unusedBits = APINT_BITS_PER_WORD - BitWidth;
01226       return CountLeadingZeros_64(VAL) - unusedBits;
01227     }
01228     return countLeadingZerosSlowCase();
01229   }
01230 
01231   /// countLeadingOnes - This function is an APInt version of the
01232   /// countLeadingOnes_{32,64} functions in MathExtras.h. It counts the number
01233   /// of ones from the most significant bit to the first zero bit.
01234   /// @returns 0 if the high order bit is not set, otherwise
01235   /// returns the number of 1 bits from the most significant to the least
01236   /// @brief Count the number of leading one bits.
01237   unsigned countLeadingOnes() const;
01238 
01239   /// Computes the number of leading bits of this APInt that are equal to its
01240   /// sign bit.
01241   unsigned getNumSignBits() const {
01242     return isNegative() ? countLeadingOnes() : countLeadingZeros();
01243   }
01244 
01245   /// countTrailingZeros - This function is an APInt version of the
01246   /// countTrailingZeros_{32,64} functions in MathExtras.h. It counts
01247   /// the number of zeros from the least significant bit to the first set bit.
01248   /// @returns BitWidth if the value is zero, otherwise
01249   /// returns the number of zeros from the least significant bit to the first
01250   /// one bit.
01251   /// @brief Count the number of trailing zero bits.
01252   unsigned countTrailingZeros() const;
01253 
01254   /// countTrailingOnes - This function is an APInt version of the
01255   /// countTrailingOnes_{32,64} functions in MathExtras.h. It counts
01256   /// the number of ones from the least significant bit to the first zero bit.
01257   /// @returns BitWidth if the value is all ones, otherwise
01258   /// returns the number of ones from the least significant bit to the first
01259   /// zero bit.
01260   /// @brief Count the number of trailing one bits.
01261   unsigned countTrailingOnes() const {
01262     if (isSingleWord())
01263       return CountTrailingOnes_64(VAL);
01264     return countTrailingOnesSlowCase();
01265   }
01266 
01267   /// countPopulation - This function is an APInt version of the
01268   /// countPopulation_{32,64} functions in MathExtras.h. It counts the number
01269   /// of 1 bits in the APInt value.
01270   /// @returns 0 if the value is zero, otherwise returns the number of set
01271   /// bits.
01272   /// @brief Count the number of bits set.
01273   unsigned countPopulation() const {
01274     if (isSingleWord())
01275       return CountPopulation_64(VAL);
01276     return countPopulationSlowCase();
01277   }
01278 
01279   /// @}
01280   /// @name Conversion Functions
01281   /// @{
01282   void print(raw_ostream &OS, bool isSigned) const;
01283 
01284   /// toString - Converts an APInt to a string and append it to Str.  Str is
01285   /// commonly a SmallString.
01286   void toString(SmallVectorImpl<char> &Str, unsigned Radix, bool Signed,
01287                 bool formatAsCLiteral = false) const;
01288 
01289   /// Considers the APInt to be unsigned and converts it into a string in the
01290   /// radix given. The radix can be 2, 8, 10 16, or 36.
01291   void toStringUnsigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const {
01292     toString(Str, Radix, false, false);
01293   }
01294 
01295   /// Considers the APInt to be signed and converts it into a string in the
01296   /// radix given. The radix can be 2, 8, 10, 16, or 36.
01297   void toStringSigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const {
01298     toString(Str, Radix, true, false);
01299   }
01300 
01301   /// toString - This returns the APInt as a std::string.  Note that this is an
01302   /// inefficient method.  It is better to pass in a SmallVector/SmallString
01303   /// to the methods above to avoid thrashing the heap for the string.
01304   std::string toString(unsigned Radix, bool Signed) const;
01305 
01306 
01307   /// @returns a byte-swapped representation of this APInt Value.
01308   APInt byteSwap() const;
01309 
01310   /// @brief Converts this APInt to a double value.
01311   double roundToDouble(bool isSigned) const;
01312 
01313   /// @brief Converts this unsigned APInt to a double value.
01314   double roundToDouble() const {
01315     return roundToDouble(false);
01316   }
01317 
01318   /// @brief Converts this signed APInt to a double value.
01319   double signedRoundToDouble() const {
01320     return roundToDouble(true);
01321   }
01322 
01323   /// The conversion does not do a translation from integer to double, it just
01324   /// re-interprets the bits as a double. Note that it is valid to do this on
01325   /// any bit width. Exactly 64 bits will be translated.
01326   /// @brief Converts APInt bits to a double
01327   double bitsToDouble() const {
01328     union {
01329       uint64_t I;
01330       double D;
01331     } T;
01332     T.I = (isSingleWord() ? VAL : pVal[0]);
01333     return T.D;
01334   }
01335 
01336   /// The conversion does not do a translation from integer to float, it just
01337   /// re-interprets the bits as a float. Note that it is valid to do this on
01338   /// any bit width. Exactly 32 bits will be translated.
01339   /// @brief Converts APInt bits to a double
01340   float bitsToFloat() const {
01341     union {
01342       unsigned I;
01343       float F;
01344     } T;
01345     T.I = unsigned((isSingleWord() ? VAL : pVal[0]));
01346     return T.F;
01347   }
01348 
01349   /// The conversion does not do a translation from double to integer, it just
01350   /// re-interprets the bits of the double.
01351   /// @brief Converts a double to APInt bits.
01352   static APInt doubleToBits(double V) {
01353     union {
01354       uint64_t I;
01355       double D;
01356     } T;
01357     T.D = V;
01358     return APInt(sizeof T * CHAR_BIT, T.I);
01359   }
01360 
01361   /// The conversion does not do a translation from float to integer, it just
01362   /// re-interprets the bits of the float.
01363   /// @brief Converts a float to APInt bits.
01364   static APInt floatToBits(float V) {
01365     union {
01366       unsigned I;
01367       float F;
01368     } T;
01369     T.F = V;
01370     return APInt(sizeof T * CHAR_BIT, T.I);
01371   }
01372 
01373   /// @}
01374   /// @name Mathematics Operations
01375   /// @{
01376 
01377   /// @returns the floor log base 2 of this APInt.
01378   unsigned logBase2() const {
01379     return BitWidth - 1 - countLeadingZeros();
01380   }
01381 
01382   /// @returns the ceil log base 2 of this APInt.
01383   unsigned ceilLogBase2() const {
01384     return BitWidth - (*this - 1).countLeadingZeros();
01385   }
01386 
01387   /// @returns the log base 2 of this APInt if its an exact power of two, -1
01388   /// otherwise
01389   int32_t exactLogBase2() const {
01390     if (!isPowerOf2())
01391       return -1;
01392     return logBase2();
01393   }
01394 
01395   /// @brief Compute the square root
01396   APInt sqrt() const;
01397 
01398   /// If *this is < 0 then return -(*this), otherwise *this;
01399   /// @brief Get the absolute value;
01400   APInt abs() const {
01401     if (isNegative())
01402       return -(*this);
01403     return *this;
01404   }
01405 
01406   /// @returns the multiplicative inverse for a given modulo.
01407   APInt multiplicativeInverse(const APInt& modulo) const;
01408 
01409   /// @}
01410   /// @name Support for division by constant
01411   /// @{
01412 
01413   /// Calculate the magic number for signed division by a constant.
01414   struct ms;
01415   ms magic() const;
01416 
01417   /// Calculate the magic number for unsigned division by a constant.
01418   struct mu;
01419   mu magicu(unsigned LeadingZeros = 0) const;
01420 
01421   /// @}
01422   /// @name Building-block Operations for APInt and APFloat
01423   /// @{
01424 
01425   // These building block operations operate on a representation of
01426   // arbitrary precision, two's-complement, bignum integer values.
01427   // They should be sufficient to implement APInt and APFloat bignum
01428   // requirements.  Inputs are generally a pointer to the base of an
01429   // array of integer parts, representing an unsigned bignum, and a
01430   // count of how many parts there are.
01431 
01432   /// Sets the least significant part of a bignum to the input value,
01433   /// and zeroes out higher parts.  */
01434   static void tcSet(integerPart *, integerPart, unsigned int);
01435 
01436   /// Assign one bignum to another.
01437   static void tcAssign(integerPart *, const integerPart *, unsigned int);
01438 
01439   /// Returns true if a bignum is zero, false otherwise.
01440   static bool tcIsZero(const integerPart *, unsigned int);
01441 
01442   /// Extract the given bit of a bignum; returns 0 or 1.  Zero-based.
01443   static int tcExtractBit(const integerPart *, unsigned int bit);
01444 
01445   /// Copy the bit vector of width srcBITS from SRC, starting at bit
01446   /// srcLSB, to DST, of dstCOUNT parts, such that the bit srcLSB
01447   /// becomes the least significant bit of DST.  All high bits above
01448   /// srcBITS in DST are zero-filled.
01449   static void tcExtract(integerPart *, unsigned int dstCount,
01450                         const integerPart *,
01451                         unsigned int srcBits, unsigned int srcLSB);
01452 
01453   /// Set the given bit of a bignum.  Zero-based.
01454   static void tcSetBit(integerPart *, unsigned int bit);
01455 
01456   /// Clear the given bit of a bignum.  Zero-based.
01457   static void tcClearBit(integerPart *, unsigned int bit);
01458 
01459   /// Returns the bit number of the least or most significant set bit
01460   /// of a number.  If the input number has no bits set -1U is
01461   /// returned.
01462   static unsigned int tcLSB(const integerPart *, unsigned int);
01463   static unsigned int tcMSB(const integerPart *parts, unsigned int n);
01464 
01465   /// Negate a bignum in-place.
01466   static void tcNegate(integerPart *, unsigned int);
01467 
01468   /// DST += RHS + CARRY where CARRY is zero or one.  Returns the
01469   /// carry flag.
01470   static integerPart tcAdd(integerPart *, const integerPart *,
01471                            integerPart carry, unsigned);
01472 
01473   /// DST -= RHS + CARRY where CARRY is zero or one.  Returns the
01474   /// carry flag.
01475   static integerPart tcSubtract(integerPart *, const integerPart *,
01476                                 integerPart carry, unsigned);
01477 
01478   ///  DST += SRC * MULTIPLIER + PART   if add is true
01479   ///  DST  = SRC * MULTIPLIER + PART   if add is false
01480   ///
01481   ///  Requires 0 <= DSTPARTS <= SRCPARTS + 1.  If DST overlaps SRC
01482   ///  they must start at the same point, i.e. DST == SRC.
01483   ///
01484   ///  If DSTPARTS == SRC_PARTS + 1 no overflow occurs and zero is
01485   ///  returned.  Otherwise DST is filled with the least significant
01486   ///  DSTPARTS parts of the result, and if all of the omitted higher
01487   ///  parts were zero return zero, otherwise overflow occurred and
01488   ///  return one.
01489   static int tcMultiplyPart(integerPart *dst, const integerPart *src,
01490                             integerPart multiplier, integerPart carry,
01491                             unsigned int srcParts, unsigned int dstParts,
01492                             bool add);
01493 
01494   /// DST = LHS * RHS, where DST has the same width as the operands
01495   /// and is filled with the least significant parts of the result.
01496   /// Returns one if overflow occurred, otherwise zero.  DST must be
01497   /// disjoint from both operands.
01498   static int tcMultiply(integerPart *, const integerPart *,
01499                         const integerPart *, unsigned);
01500 
01501   /// DST = LHS * RHS, where DST has width the sum of the widths of
01502   /// the operands.  No overflow occurs.  DST must be disjoint from
01503   /// both operands. Returns the number of parts required to hold the
01504   /// result.
01505   static unsigned int tcFullMultiply(integerPart *, const integerPart *,
01506                                      const integerPart *, unsigned, unsigned);
01507 
01508   /// If RHS is zero LHS and REMAINDER are left unchanged, return one.
01509   /// Otherwise set LHS to LHS / RHS with the fractional part
01510   /// discarded, set REMAINDER to the remainder, return zero.  i.e.
01511   ///
01512   ///  OLD_LHS = RHS * LHS + REMAINDER
01513   ///
01514   ///  SCRATCH is a bignum of the same size as the operands and result
01515   ///  for use by the routine; its contents need not be initialized
01516   ///  and are destroyed.  LHS, REMAINDER and SCRATCH must be
01517   ///  distinct.
01518   static int tcDivide(integerPart *lhs, const integerPart *rhs,
01519                       integerPart *remainder, integerPart *scratch,
01520                       unsigned int parts);
01521 
01522   /// Shift a bignum left COUNT bits.  Shifted in bits are zero.
01523   /// There are no restrictions on COUNT.
01524   static void tcShiftLeft(integerPart *, unsigned int parts,
01525                           unsigned int count);
01526 
01527   /// Shift a bignum right COUNT bits.  Shifted in bits are zero.
01528   /// There are no restrictions on COUNT.
01529   static void tcShiftRight(integerPart *, unsigned int parts,
01530                            unsigned int count);
01531 
01532   /// The obvious AND, OR and XOR and complement operations.
01533   static void tcAnd(integerPart *, const integerPart *, unsigned int);
01534   static void tcOr(integerPart *, const integerPart *, unsigned int);
01535   static void tcXor(integerPart *, const integerPart *, unsigned int);
01536   static void tcComplement(integerPart *, unsigned int);
01537 
01538   /// Comparison (unsigned) of two bignums.
01539   static int tcCompare(const integerPart *, const integerPart *,
01540                        unsigned int);
01541 
01542   /// Increment a bignum in-place.  Return the carry flag.
01543   static integerPart tcIncrement(integerPart *, unsigned int);
01544 
01545   /// Set the least significant BITS and clear the rest.
01546   static void tcSetLeastSignificantBits(integerPart *, unsigned int,
01547                                         unsigned int bits);
01548 
01549   /// @brief debug method
01550   void dump() const;
01551 
01552   /// @}
01553 };
01554 
01555 /// Magic data for optimising signed division by a constant.
01556 struct APInt::ms {
01557   APInt m;  ///< magic number
01558   unsigned s;  ///< shift amount
01559 };
01560 
01561 /// Magic data for optimising unsigned division by a constant.
01562 struct APInt::mu {
01563   APInt m;     ///< magic number
01564   bool a;      ///< add indicator
01565   unsigned s;  ///< shift amount
01566 };
01567 
01568 inline bool operator==(uint64_t V1, const APInt& V2) {
01569   return V2 == V1;
01570 }
01571 
01572 inline bool operator!=(uint64_t V1, const APInt& V2) {
01573   return V2 != V1;
01574 }
01575 
01576 inline raw_ostream &operator<<(raw_ostream &OS, const APInt &I) {
01577   I.print(OS, true);
01578   return OS;
01579 }
01580 
01581 namespace APIntOps {
01582 
01583 /// @brief Determine the smaller of two APInts considered to be signed.
01584 inline APInt smin(const APInt &A, const APInt &B) {
01585   return A.slt(B) ? A : B;
01586 }
01587 
01588 /// @brief Determine the larger of two APInts considered to be signed.
01589 inline APInt smax(const APInt &A, const APInt &B) {
01590   return A.sgt(B) ? A : B;
01591 }
01592 
01593 /// @brief Determine the smaller of two APInts considered to be signed.
01594 inline APInt umin(const APInt &A, const APInt &B) {
01595   return A.ult(B) ? A : B;
01596 }
01597 
01598 /// @brief Determine the larger of two APInts considered to be unsigned.
01599 inline APInt umax(const APInt &A, const APInt &B) {
01600   return A.ugt(B) ? A : B;
01601 }
01602 
01603 /// @brief Check if the specified APInt has a N-bits unsigned integer value.
01604 inline bool isIntN(unsigned N, const APInt& APIVal) {
01605   return APIVal.isIntN(N);
01606 }
01607 
01608 /// @brief Check if the specified APInt has a N-bits signed integer value.
01609 inline bool isSignedIntN(unsigned N, const APInt& APIVal) {
01610   return APIVal.isSignedIntN(N);
01611 }
01612 
01613 /// @returns true if the argument APInt value is a sequence of ones
01614 /// starting at the least significant bit with the remainder zero.
01615 inline bool isMask(unsigned numBits, const APInt& APIVal) {
01616   return numBits <= APIVal.getBitWidth() &&
01617     APIVal == APInt::getLowBitsSet(APIVal.getBitWidth(), numBits);
01618 }
01619 
01620 /// @returns true if the argument APInt value contains a sequence of ones
01621 /// with the remainder zero.
01622 inline bool isShiftedMask(unsigned numBits, const APInt& APIVal) {
01623   return isMask(numBits, (APIVal - APInt(numBits,1)) | APIVal);
01624 }
01625 
01626 /// @returns a byte-swapped representation of the specified APInt Value.
01627 inline APInt byteSwap(const APInt& APIVal) {
01628   return APIVal.byteSwap();
01629 }
01630 
01631 /// @returns the floor log base 2 of the specified APInt value.
01632 inline unsigned logBase2(const APInt& APIVal) {
01633   return APIVal.logBase2();
01634 }
01635 
01636 /// GreatestCommonDivisor - This function returns the greatest common
01637 /// divisor of the two APInt values using Euclid's algorithm.
01638 /// @returns the greatest common divisor of Val1 and Val2
01639 /// @brief Compute GCD of two APInt values.
01640 APInt GreatestCommonDivisor(const APInt& Val1, const APInt& Val2);
01641 
01642 /// Treats the APInt as an unsigned value for conversion purposes.
01643 /// @brief Converts the given APInt to a double value.
01644 inline double RoundAPIntToDouble(const APInt& APIVal) {
01645   return APIVal.roundToDouble();
01646 }
01647 
01648 /// Treats the APInt as a signed value for conversion purposes.
01649 /// @brief Converts the given APInt to a double value.
01650 inline double RoundSignedAPIntToDouble(const APInt& APIVal) {
01651   return APIVal.signedRoundToDouble();
01652 }
01653 
01654 /// @brief Converts the given APInt to a float vlalue.
01655 inline float RoundAPIntToFloat(const APInt& APIVal) {
01656   return float(RoundAPIntToDouble(APIVal));
01657 }
01658 
01659 /// Treast the APInt as a signed value for conversion purposes.
01660 /// @brief Converts the given APInt to a float value.
01661 inline float RoundSignedAPIntToFloat(const APInt& APIVal) {
01662   return float(APIVal.signedRoundToDouble());
01663 }
01664 
01665 /// RoundDoubleToAPInt - This function convert a double value to an APInt value.
01666 /// @brief Converts the given double value into a APInt.
01667 APInt RoundDoubleToAPInt(double Double, unsigned width);
01668 
01669 /// RoundFloatToAPInt - Converts a float value into an APInt value.
01670 /// @brief Converts a float value into a APInt.
01671 inline APInt RoundFloatToAPInt(float Float, unsigned width) {
01672   return RoundDoubleToAPInt(double(Float), width);
01673 }
01674 
01675 /// Arithmetic right-shift the APInt by shiftAmt.
01676 /// @brief Arithmetic right-shift function.
01677 inline APInt ashr(const APInt& LHS, unsigned shiftAmt) {
01678   return LHS.ashr(shiftAmt);
01679 }
01680 
01681 /// Logical right-shift the APInt by shiftAmt.
01682 /// @brief Logical right-shift function.
01683 inline APInt lshr(const APInt& LHS, unsigned shiftAmt) {
01684   return LHS.lshr(shiftAmt);
01685 }
01686 
01687 /// Left-shift the APInt by shiftAmt.
01688 /// @brief Left-shift function.
01689 inline APInt shl(const APInt& LHS, unsigned shiftAmt) {
01690   return LHS.shl(shiftAmt);
01691 }
01692 
01693 /// Signed divide APInt LHS by APInt RHS.
01694 /// @brief Signed division function for APInt.
01695 inline APInt sdiv(const APInt& LHS, const APInt& RHS) {
01696   return LHS.sdiv(RHS);
01697 }
01698 
01699 /// Unsigned divide APInt LHS by APInt RHS.
01700 /// @brief Unsigned division function for APInt.
01701 inline APInt udiv(const APInt& LHS, const APInt& RHS) {
01702   return LHS.udiv(RHS);
01703 }
01704 
01705 /// Signed remainder operation on APInt.
01706 /// @brief Function for signed remainder operation.
01707 inline APInt srem(const APInt& LHS, const APInt& RHS) {
01708   return LHS.srem(RHS);
01709 }
01710 
01711 /// Unsigned remainder operation on APInt.
01712 /// @brief Function for unsigned remainder operation.
01713 inline APInt urem(const APInt& LHS, const APInt& RHS) {
01714   return LHS.urem(RHS);
01715 }
01716 
01717 /// Performs multiplication on APInt values.
01718 /// @brief Function for multiplication operation.
01719 inline APInt mul(const APInt& LHS, const APInt& RHS) {
01720   return LHS * RHS;
01721 }
01722 
01723 /// Performs addition on APInt values.
01724 /// @brief Function for addition operation.
01725 inline APInt add(const APInt& LHS, const APInt& RHS) {
01726   return LHS + RHS;
01727 }
01728 
01729 /// Performs subtraction on APInt values.
01730 /// @brief Function for subtraction operation.
01731 inline APInt sub(const APInt& LHS, const APInt& RHS) {
01732   return LHS - RHS;
01733 }
01734 
01735 /// Performs bitwise AND operation on APInt LHS and
01736 /// APInt RHS.
01737 /// @brief Bitwise AND function for APInt.
01738 inline APInt And(const APInt& LHS, const APInt& RHS) {
01739   return LHS & RHS;
01740 }
01741 
01742 /// Performs bitwise OR operation on APInt LHS and APInt RHS.
01743 /// @brief Bitwise OR function for APInt.
01744 inline APInt Or(const APInt& LHS, const APInt& RHS) {
01745   return LHS | RHS;
01746 }
01747 
01748 /// Performs bitwise XOR operation on APInt.
01749 /// @brief Bitwise XOR function for APInt.
01750 inline APInt Xor(const APInt& LHS, const APInt& RHS) {
01751   return LHS ^ RHS;
01752 }
01753 
01754 /// Performs a bitwise complement operation on APInt.
01755 /// @brief Bitwise complement function.
01756 inline APInt Not(const APInt& APIVal) {
01757   return ~APIVal;
01758 }
01759 
01760 } // End of APIntOps namespace
01761 
01762   // See friend declaration above. This additional declaration is required in
01763   // order to compile LLVM with IBM xlC compiler.
01764   hash_code hash_value(const APInt &Arg);
01765 } // End of llvm namespace
01766 
01767 #endif