APInt.h 75 KB

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