APInt.h 76 KB

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