APInt.h 66 KB

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