APInt.h 78 KB

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