APInt.cpp 96 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049
  1. //===-- APInt.cpp - Implement APInt class ---------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements a class to represent arbitrary precision integer
  10. // constant values and provide a variety of arithmetic operations on them.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/ADT/APInt.h"
  14. #include "llvm/ADT/ArrayRef.h"
  15. #include "llvm/ADT/FoldingSet.h"
  16. #include "llvm/ADT/Hashing.h"
  17. #include "llvm/ADT/Optional.h"
  18. #include "llvm/ADT/SmallString.h"
  19. #include "llvm/ADT/StringRef.h"
  20. #include "llvm/ADT/bit.h"
  21. #include "llvm/Config/llvm-config.h"
  22. #include "llvm/Support/Debug.h"
  23. #include "llvm/Support/ErrorHandling.h"
  24. #include "llvm/Support/MathExtras.h"
  25. #include "llvm/Support/raw_ostream.h"
  26. #include <cmath>
  27. #include <cstring>
  28. using namespace llvm;
  29. #define DEBUG_TYPE "apint"
  30. /// A utility function for allocating memory, checking for allocation failures,
  31. /// and ensuring the contents are zeroed.
  32. inline static uint64_t* getClearedMemory(unsigned numWords) {
  33. uint64_t *result = new uint64_t[numWords];
  34. memset(result, 0, numWords * sizeof(uint64_t));
  35. return result;
  36. }
  37. /// A utility function for allocating memory and checking for allocation
  38. /// failure. The content is not zeroed.
  39. inline static uint64_t* getMemory(unsigned numWords) {
  40. return new uint64_t[numWords];
  41. }
  42. /// A utility function that converts a character to a digit.
  43. inline static unsigned getDigit(char cdigit, uint8_t radix) {
  44. unsigned r;
  45. if (radix == 16 || radix == 36) {
  46. r = cdigit - '0';
  47. if (r <= 9)
  48. return r;
  49. r = cdigit - 'A';
  50. if (r <= radix - 11U)
  51. return r + 10;
  52. r = cdigit - 'a';
  53. if (r <= radix - 11U)
  54. return r + 10;
  55. radix = 10;
  56. }
  57. r = cdigit - '0';
  58. if (r < radix)
  59. return r;
  60. return -1U;
  61. }
  62. void APInt::initSlowCase(uint64_t val, bool isSigned) {
  63. U.pVal = getClearedMemory(getNumWords());
  64. U.pVal[0] = val;
  65. if (isSigned && int64_t(val) < 0)
  66. for (unsigned i = 1; i < getNumWords(); ++i)
  67. U.pVal[i] = WORDTYPE_MAX;
  68. clearUnusedBits();
  69. }
  70. void APInt::initSlowCase(const APInt& that) {
  71. U.pVal = getMemory(getNumWords());
  72. memcpy(U.pVal, that.U.pVal, getNumWords() * APINT_WORD_SIZE);
  73. }
  74. void APInt::initFromArray(ArrayRef<uint64_t> bigVal) {
  75. assert(bigVal.data() && "Null pointer detected!");
  76. if (isSingleWord())
  77. U.VAL = bigVal[0];
  78. else {
  79. // Get memory, cleared to 0
  80. U.pVal = getClearedMemory(getNumWords());
  81. // Calculate the number of words to copy
  82. unsigned words = std::min<unsigned>(bigVal.size(), getNumWords());
  83. // Copy the words from bigVal to pVal
  84. memcpy(U.pVal, bigVal.data(), words * APINT_WORD_SIZE);
  85. }
  86. // Make sure unused high bits are cleared
  87. clearUnusedBits();
  88. }
  89. APInt::APInt(unsigned numBits, ArrayRef<uint64_t> bigVal) : BitWidth(numBits) {
  90. initFromArray(bigVal);
  91. }
  92. APInt::APInt(unsigned numBits, unsigned numWords, const uint64_t bigVal[])
  93. : BitWidth(numBits) {
  94. initFromArray(makeArrayRef(bigVal, numWords));
  95. }
  96. APInt::APInt(unsigned numbits, StringRef Str, uint8_t radix)
  97. : BitWidth(numbits) {
  98. fromString(numbits, Str, radix);
  99. }
  100. void APInt::reallocate(unsigned NewBitWidth) {
  101. // If the number of words is the same we can just change the width and stop.
  102. if (getNumWords() == getNumWords(NewBitWidth)) {
  103. BitWidth = NewBitWidth;
  104. return;
  105. }
  106. // If we have an allocation, delete it.
  107. if (!isSingleWord())
  108. delete [] U.pVal;
  109. // Update BitWidth.
  110. BitWidth = NewBitWidth;
  111. // If we are supposed to have an allocation, create it.
  112. if (!isSingleWord())
  113. U.pVal = getMemory(getNumWords());
  114. }
  115. void APInt::assignSlowCase(const APInt &RHS) {
  116. // Don't do anything for X = X
  117. if (this == &RHS)
  118. return;
  119. // Adjust the bit width and handle allocations as necessary.
  120. reallocate(RHS.getBitWidth());
  121. // Copy the data.
  122. if (isSingleWord())
  123. U.VAL = RHS.U.VAL;
  124. else
  125. memcpy(U.pVal, RHS.U.pVal, getNumWords() * APINT_WORD_SIZE);
  126. }
  127. /// This method 'profiles' an APInt for use with FoldingSet.
  128. void APInt::Profile(FoldingSetNodeID& ID) const {
  129. ID.AddInteger(BitWidth);
  130. if (isSingleWord()) {
  131. ID.AddInteger(U.VAL);
  132. return;
  133. }
  134. unsigned NumWords = getNumWords();
  135. for (unsigned i = 0; i < NumWords; ++i)
  136. ID.AddInteger(U.pVal[i]);
  137. }
  138. /// Prefix increment operator. Increments the APInt by one.
  139. APInt& APInt::operator++() {
  140. if (isSingleWord())
  141. ++U.VAL;
  142. else
  143. tcIncrement(U.pVal, getNumWords());
  144. return clearUnusedBits();
  145. }
  146. /// Prefix decrement operator. Decrements the APInt by one.
  147. APInt& APInt::operator--() {
  148. if (isSingleWord())
  149. --U.VAL;
  150. else
  151. tcDecrement(U.pVal, getNumWords());
  152. return clearUnusedBits();
  153. }
  154. /// Adds the RHS APInt to this APInt.
  155. /// @returns this, after addition of RHS.
  156. /// Addition assignment operator.
  157. APInt& APInt::operator+=(const APInt& RHS) {
  158. assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
  159. if (isSingleWord())
  160. U.VAL += RHS.U.VAL;
  161. else
  162. tcAdd(U.pVal, RHS.U.pVal, 0, getNumWords());
  163. return clearUnusedBits();
  164. }
  165. APInt& APInt::operator+=(uint64_t RHS) {
  166. if (isSingleWord())
  167. U.VAL += RHS;
  168. else
  169. tcAddPart(U.pVal, RHS, getNumWords());
  170. return clearUnusedBits();
  171. }
  172. /// Subtracts the RHS APInt from this APInt
  173. /// @returns this, after subtraction
  174. /// Subtraction assignment operator.
  175. APInt& APInt::operator-=(const APInt& RHS) {
  176. assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
  177. if (isSingleWord())
  178. U.VAL -= RHS.U.VAL;
  179. else
  180. tcSubtract(U.pVal, RHS.U.pVal, 0, getNumWords());
  181. return clearUnusedBits();
  182. }
  183. APInt& APInt::operator-=(uint64_t RHS) {
  184. if (isSingleWord())
  185. U.VAL -= RHS;
  186. else
  187. tcSubtractPart(U.pVal, RHS, getNumWords());
  188. return clearUnusedBits();
  189. }
  190. APInt APInt::operator*(const APInt& RHS) const {
  191. assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
  192. if (isSingleWord())
  193. return APInt(BitWidth, U.VAL * RHS.U.VAL);
  194. APInt Result(getMemory(getNumWords()), getBitWidth());
  195. tcMultiply(Result.U.pVal, U.pVal, RHS.U.pVal, getNumWords());
  196. Result.clearUnusedBits();
  197. return Result;
  198. }
  199. void APInt::andAssignSlowCase(const APInt &RHS) {
  200. WordType *dst = U.pVal, *rhs = RHS.U.pVal;
  201. for (size_t i = 0, e = getNumWords(); i != e; ++i)
  202. dst[i] &= rhs[i];
  203. }
  204. void APInt::orAssignSlowCase(const APInt &RHS) {
  205. WordType *dst = U.pVal, *rhs = RHS.U.pVal;
  206. for (size_t i = 0, e = getNumWords(); i != e; ++i)
  207. dst[i] |= rhs[i];
  208. }
  209. void APInt::xorAssignSlowCase(const APInt &RHS) {
  210. WordType *dst = U.pVal, *rhs = RHS.U.pVal;
  211. for (size_t i = 0, e = getNumWords(); i != e; ++i)
  212. dst[i] ^= rhs[i];
  213. }
  214. APInt &APInt::operator*=(const APInt &RHS) {
  215. *this = *this * RHS;
  216. return *this;
  217. }
  218. APInt& APInt::operator*=(uint64_t RHS) {
  219. if (isSingleWord()) {
  220. U.VAL *= RHS;
  221. } else {
  222. unsigned NumWords = getNumWords();
  223. tcMultiplyPart(U.pVal, U.pVal, RHS, 0, NumWords, NumWords, false);
  224. }
  225. return clearUnusedBits();
  226. }
  227. bool APInt::equalSlowCase(const APInt &RHS) const {
  228. return std::equal(U.pVal, U.pVal + getNumWords(), RHS.U.pVal);
  229. }
  230. int APInt::compare(const APInt& RHS) const {
  231. assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
  232. if (isSingleWord())
  233. return U.VAL < RHS.U.VAL ? -1 : U.VAL > RHS.U.VAL;
  234. return tcCompare(U.pVal, RHS.U.pVal, getNumWords());
  235. }
  236. int APInt::compareSigned(const APInt& RHS) const {
  237. assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
  238. if (isSingleWord()) {
  239. int64_t lhsSext = SignExtend64(U.VAL, BitWidth);
  240. int64_t rhsSext = SignExtend64(RHS.U.VAL, BitWidth);
  241. return lhsSext < rhsSext ? -1 : lhsSext > rhsSext;
  242. }
  243. bool lhsNeg = isNegative();
  244. bool rhsNeg = RHS.isNegative();
  245. // If the sign bits don't match, then (LHS < RHS) if LHS is negative
  246. if (lhsNeg != rhsNeg)
  247. return lhsNeg ? -1 : 1;
  248. // Otherwise we can just use an unsigned comparison, because even negative
  249. // numbers compare correctly this way if both have the same signed-ness.
  250. return tcCompare(U.pVal, RHS.U.pVal, getNumWords());
  251. }
  252. void APInt::setBitsSlowCase(unsigned loBit, unsigned hiBit) {
  253. unsigned loWord = whichWord(loBit);
  254. unsigned hiWord = whichWord(hiBit);
  255. // Create an initial mask for the low word with zeros below loBit.
  256. uint64_t loMask = WORDTYPE_MAX << whichBit(loBit);
  257. // If hiBit is not aligned, we need a high mask.
  258. unsigned hiShiftAmt = whichBit(hiBit);
  259. if (hiShiftAmt != 0) {
  260. // Create a high mask with zeros above hiBit.
  261. uint64_t hiMask = WORDTYPE_MAX >> (APINT_BITS_PER_WORD - hiShiftAmt);
  262. // If loWord and hiWord are equal, then we combine the masks. Otherwise,
  263. // set the bits in hiWord.
  264. if (hiWord == loWord)
  265. loMask &= hiMask;
  266. else
  267. U.pVal[hiWord] |= hiMask;
  268. }
  269. // Apply the mask to the low word.
  270. U.pVal[loWord] |= loMask;
  271. // Fill any words between loWord and hiWord with all ones.
  272. for (unsigned word = loWord + 1; word < hiWord; ++word)
  273. U.pVal[word] = WORDTYPE_MAX;
  274. }
  275. // Complement a bignum in-place.
  276. static void tcComplement(APInt::WordType *dst, unsigned parts) {
  277. for (unsigned i = 0; i < parts; i++)
  278. dst[i] = ~dst[i];
  279. }
  280. /// Toggle every bit to its opposite value.
  281. void APInt::flipAllBitsSlowCase() {
  282. tcComplement(U.pVal, getNumWords());
  283. clearUnusedBits();
  284. }
  285. /// Concatenate the bits from "NewLSB" onto the bottom of *this. This is
  286. /// equivalent to:
  287. /// (this->zext(NewWidth) << NewLSB.getBitWidth()) | NewLSB.zext(NewWidth)
  288. /// In the slow case, we know the result is large.
  289. APInt APInt::concatSlowCase(const APInt &NewLSB) const {
  290. unsigned NewWidth = getBitWidth() + NewLSB.getBitWidth();
  291. APInt Result = NewLSB.zextOrSelf(NewWidth);
  292. Result.insertBits(*this, NewLSB.getBitWidth());
  293. return Result;
  294. }
  295. /// Toggle a given bit to its opposite value whose position is given
  296. /// as "bitPosition".
  297. /// Toggles a given bit to its opposite value.
  298. void APInt::flipBit(unsigned bitPosition) {
  299. assert(bitPosition < BitWidth && "Out of the bit-width range!");
  300. setBitVal(bitPosition, !(*this)[bitPosition]);
  301. }
  302. void APInt::insertBits(const APInt &subBits, unsigned bitPosition) {
  303. unsigned subBitWidth = subBits.getBitWidth();
  304. assert((subBitWidth + bitPosition) <= BitWidth && "Illegal bit insertion");
  305. // inserting no bits is a noop.
  306. if (subBitWidth == 0)
  307. return;
  308. // Insertion is a direct copy.
  309. if (subBitWidth == BitWidth) {
  310. *this = subBits;
  311. return;
  312. }
  313. // Single word result can be done as a direct bitmask.
  314. if (isSingleWord()) {
  315. uint64_t mask = WORDTYPE_MAX >> (APINT_BITS_PER_WORD - subBitWidth);
  316. U.VAL &= ~(mask << bitPosition);
  317. U.VAL |= (subBits.U.VAL << bitPosition);
  318. return;
  319. }
  320. unsigned loBit = whichBit(bitPosition);
  321. unsigned loWord = whichWord(bitPosition);
  322. unsigned hi1Word = whichWord(bitPosition + subBitWidth - 1);
  323. // Insertion within a single word can be done as a direct bitmask.
  324. if (loWord == hi1Word) {
  325. uint64_t mask = WORDTYPE_MAX >> (APINT_BITS_PER_WORD - subBitWidth);
  326. U.pVal[loWord] &= ~(mask << loBit);
  327. U.pVal[loWord] |= (subBits.U.VAL << loBit);
  328. return;
  329. }
  330. // Insert on word boundaries.
  331. if (loBit == 0) {
  332. // Direct copy whole words.
  333. unsigned numWholeSubWords = subBitWidth / APINT_BITS_PER_WORD;
  334. memcpy(U.pVal + loWord, subBits.getRawData(),
  335. numWholeSubWords * APINT_WORD_SIZE);
  336. // Mask+insert remaining bits.
  337. unsigned remainingBits = subBitWidth % APINT_BITS_PER_WORD;
  338. if (remainingBits != 0) {
  339. uint64_t mask = WORDTYPE_MAX >> (APINT_BITS_PER_WORD - remainingBits);
  340. U.pVal[hi1Word] &= ~mask;
  341. U.pVal[hi1Word] |= subBits.getWord(subBitWidth - 1);
  342. }
  343. return;
  344. }
  345. // General case - set/clear individual bits in dst based on src.
  346. // TODO - there is scope for optimization here, but at the moment this code
  347. // path is barely used so prefer readability over performance.
  348. for (unsigned i = 0; i != subBitWidth; ++i)
  349. setBitVal(bitPosition + i, subBits[i]);
  350. }
  351. void APInt::insertBits(uint64_t subBits, unsigned bitPosition, unsigned numBits) {
  352. uint64_t maskBits = maskTrailingOnes<uint64_t>(numBits);
  353. subBits &= maskBits;
  354. if (isSingleWord()) {
  355. U.VAL &= ~(maskBits << bitPosition);
  356. U.VAL |= subBits << bitPosition;
  357. return;
  358. }
  359. unsigned loBit = whichBit(bitPosition);
  360. unsigned loWord = whichWord(bitPosition);
  361. unsigned hiWord = whichWord(bitPosition + numBits - 1);
  362. if (loWord == hiWord) {
  363. U.pVal[loWord] &= ~(maskBits << loBit);
  364. U.pVal[loWord] |= subBits << loBit;
  365. return;
  366. }
  367. static_assert(8 * sizeof(WordType) <= 64, "This code assumes only two words affected");
  368. unsigned wordBits = 8 * sizeof(WordType);
  369. U.pVal[loWord] &= ~(maskBits << loBit);
  370. U.pVal[loWord] |= subBits << loBit;
  371. U.pVal[hiWord] &= ~(maskBits >> (wordBits - loBit));
  372. U.pVal[hiWord] |= subBits >> (wordBits - loBit);
  373. }
  374. APInt APInt::extractBits(unsigned numBits, unsigned bitPosition) const {
  375. assert(bitPosition < BitWidth && (numBits + bitPosition) <= BitWidth &&
  376. "Illegal bit extraction");
  377. if (isSingleWord())
  378. return APInt(numBits, U.VAL >> bitPosition);
  379. unsigned loBit = whichBit(bitPosition);
  380. unsigned loWord = whichWord(bitPosition);
  381. unsigned hiWord = whichWord(bitPosition + numBits - 1);
  382. // Single word result extracting bits from a single word source.
  383. if (loWord == hiWord)
  384. return APInt(numBits, U.pVal[loWord] >> loBit);
  385. // Extracting bits that start on a source word boundary can be done
  386. // as a fast memory copy.
  387. if (loBit == 0)
  388. return APInt(numBits, makeArrayRef(U.pVal + loWord, 1 + hiWord - loWord));
  389. // General case - shift + copy source words directly into place.
  390. APInt Result(numBits, 0);
  391. unsigned NumSrcWords = getNumWords();
  392. unsigned NumDstWords = Result.getNumWords();
  393. uint64_t *DestPtr = Result.isSingleWord() ? &Result.U.VAL : Result.U.pVal;
  394. for (unsigned word = 0; word < NumDstWords; ++word) {
  395. uint64_t w0 = U.pVal[loWord + word];
  396. uint64_t w1 =
  397. (loWord + word + 1) < NumSrcWords ? U.pVal[loWord + word + 1] : 0;
  398. DestPtr[word] = (w0 >> loBit) | (w1 << (APINT_BITS_PER_WORD - loBit));
  399. }
  400. return Result.clearUnusedBits();
  401. }
  402. uint64_t APInt::extractBitsAsZExtValue(unsigned numBits,
  403. unsigned bitPosition) const {
  404. assert(numBits > 0 && "Can't extract zero bits");
  405. assert(bitPosition < BitWidth && (numBits + bitPosition) <= BitWidth &&
  406. "Illegal bit extraction");
  407. assert(numBits <= 64 && "Illegal bit extraction");
  408. uint64_t maskBits = maskTrailingOnes<uint64_t>(numBits);
  409. if (isSingleWord())
  410. return (U.VAL >> bitPosition) & maskBits;
  411. unsigned loBit = whichBit(bitPosition);
  412. unsigned loWord = whichWord(bitPosition);
  413. unsigned hiWord = whichWord(bitPosition + numBits - 1);
  414. if (loWord == hiWord)
  415. return (U.pVal[loWord] >> loBit) & maskBits;
  416. static_assert(8 * sizeof(WordType) <= 64, "This code assumes only two words affected");
  417. unsigned wordBits = 8 * sizeof(WordType);
  418. uint64_t retBits = U.pVal[loWord] >> loBit;
  419. retBits |= U.pVal[hiWord] << (wordBits - loBit);
  420. retBits &= maskBits;
  421. return retBits;
  422. }
  423. unsigned APInt::getBitsNeeded(StringRef str, uint8_t radix) {
  424. assert(!str.empty() && "Invalid string length");
  425. assert((radix == 10 || radix == 8 || radix == 16 || radix == 2 ||
  426. radix == 36) &&
  427. "Radix should be 2, 8, 10, 16, or 36!");
  428. size_t slen = str.size();
  429. // Each computation below needs to know if it's negative.
  430. StringRef::iterator p = str.begin();
  431. unsigned isNegative = *p == '-';
  432. if (*p == '-' || *p == '+') {
  433. p++;
  434. slen--;
  435. assert(slen && "String is only a sign, needs a value.");
  436. }
  437. // For radixes of power-of-two values, the bits required is accurately and
  438. // easily computed
  439. if (radix == 2)
  440. return slen + isNegative;
  441. if (radix == 8)
  442. return slen * 3 + isNegative;
  443. if (radix == 16)
  444. return slen * 4 + isNegative;
  445. // FIXME: base 36
  446. // This is grossly inefficient but accurate. We could probably do something
  447. // with a computation of roughly slen*64/20 and then adjust by the value of
  448. // the first few digits. But, I'm not sure how accurate that could be.
  449. // Compute a sufficient number of bits that is always large enough but might
  450. // be too large. This avoids the assertion in the constructor. This
  451. // calculation doesn't work appropriately for the numbers 0-9, so just use 4
  452. // bits in that case.
  453. unsigned sufficient
  454. = radix == 10? (slen == 1 ? 4 : slen * 64/18)
  455. : (slen == 1 ? 7 : slen * 16/3);
  456. // Convert to the actual binary value.
  457. APInt tmp(sufficient, StringRef(p, slen), radix);
  458. // Compute how many bits are required. If the log is infinite, assume we need
  459. // just bit. If the log is exact and value is negative, then the value is
  460. // MinSignedValue with (log + 1) bits.
  461. unsigned log = tmp.logBase2();
  462. if (log == (unsigned)-1) {
  463. return isNegative + 1;
  464. } else if (isNegative && tmp.isPowerOf2()) {
  465. return isNegative + log;
  466. } else {
  467. return isNegative + log + 1;
  468. }
  469. }
  470. hash_code llvm::hash_value(const APInt &Arg) {
  471. if (Arg.isSingleWord())
  472. return hash_combine(Arg.BitWidth, Arg.U.VAL);
  473. return hash_combine(
  474. Arg.BitWidth,
  475. hash_combine_range(Arg.U.pVal, Arg.U.pVal + Arg.getNumWords()));
  476. }
  477. unsigned DenseMapInfo<APInt, void>::getHashValue(const APInt &Key) {
  478. return static_cast<unsigned>(hash_value(Key));
  479. }
  480. bool APInt::isSplat(unsigned SplatSizeInBits) const {
  481. assert(getBitWidth() % SplatSizeInBits == 0 &&
  482. "SplatSizeInBits must divide width!");
  483. // We can check that all parts of an integer are equal by making use of a
  484. // little trick: rotate and check if it's still the same value.
  485. return *this == rotl(SplatSizeInBits);
  486. }
  487. /// This function returns the high "numBits" bits of this APInt.
  488. APInt APInt::getHiBits(unsigned numBits) const {
  489. return this->lshr(BitWidth - numBits);
  490. }
  491. /// This function returns the low "numBits" bits of this APInt.
  492. APInt APInt::getLoBits(unsigned numBits) const {
  493. APInt Result(getLowBitsSet(BitWidth, numBits));
  494. Result &= *this;
  495. return Result;
  496. }
  497. /// Return a value containing V broadcasted over NewLen bits.
  498. APInt APInt::getSplat(unsigned NewLen, const APInt &V) {
  499. assert(NewLen >= V.getBitWidth() && "Can't splat to smaller bit width!");
  500. APInt Val = V.zextOrSelf(NewLen);
  501. for (unsigned I = V.getBitWidth(); I < NewLen; I <<= 1)
  502. Val |= Val << I;
  503. return Val;
  504. }
  505. unsigned APInt::countLeadingZerosSlowCase() const {
  506. unsigned Count = 0;
  507. for (int i = getNumWords()-1; i >= 0; --i) {
  508. uint64_t V = U.pVal[i];
  509. if (V == 0)
  510. Count += APINT_BITS_PER_WORD;
  511. else {
  512. Count += llvm::countLeadingZeros(V);
  513. break;
  514. }
  515. }
  516. // Adjust for unused bits in the most significant word (they are zero).
  517. unsigned Mod = BitWidth % APINT_BITS_PER_WORD;
  518. Count -= Mod > 0 ? APINT_BITS_PER_WORD - Mod : 0;
  519. return Count;
  520. }
  521. unsigned APInt::countLeadingOnesSlowCase() const {
  522. unsigned highWordBits = BitWidth % APINT_BITS_PER_WORD;
  523. unsigned shift;
  524. if (!highWordBits) {
  525. highWordBits = APINT_BITS_PER_WORD;
  526. shift = 0;
  527. } else {
  528. shift = APINT_BITS_PER_WORD - highWordBits;
  529. }
  530. int i = getNumWords() - 1;
  531. unsigned Count = llvm::countLeadingOnes(U.pVal[i] << shift);
  532. if (Count == highWordBits) {
  533. for (i--; i >= 0; --i) {
  534. if (U.pVal[i] == WORDTYPE_MAX)
  535. Count += APINT_BITS_PER_WORD;
  536. else {
  537. Count += llvm::countLeadingOnes(U.pVal[i]);
  538. break;
  539. }
  540. }
  541. }
  542. return Count;
  543. }
  544. unsigned APInt::countTrailingZerosSlowCase() const {
  545. unsigned Count = 0;
  546. unsigned i = 0;
  547. for (; i < getNumWords() && U.pVal[i] == 0; ++i)
  548. Count += APINT_BITS_PER_WORD;
  549. if (i < getNumWords())
  550. Count += llvm::countTrailingZeros(U.pVal[i]);
  551. return std::min(Count, BitWidth);
  552. }
  553. unsigned APInt::countTrailingOnesSlowCase() const {
  554. unsigned Count = 0;
  555. unsigned i = 0;
  556. for (; i < getNumWords() && U.pVal[i] == WORDTYPE_MAX; ++i)
  557. Count += APINT_BITS_PER_WORD;
  558. if (i < getNumWords())
  559. Count += llvm::countTrailingOnes(U.pVal[i]);
  560. assert(Count <= BitWidth);
  561. return Count;
  562. }
  563. unsigned APInt::countPopulationSlowCase() const {
  564. unsigned Count = 0;
  565. for (unsigned i = 0; i < getNumWords(); ++i)
  566. Count += llvm::countPopulation(U.pVal[i]);
  567. return Count;
  568. }
  569. bool APInt::intersectsSlowCase(const APInt &RHS) const {
  570. for (unsigned i = 0, e = getNumWords(); i != e; ++i)
  571. if ((U.pVal[i] & RHS.U.pVal[i]) != 0)
  572. return true;
  573. return false;
  574. }
  575. bool APInt::isSubsetOfSlowCase(const APInt &RHS) const {
  576. for (unsigned i = 0, e = getNumWords(); i != e; ++i)
  577. if ((U.pVal[i] & ~RHS.U.pVal[i]) != 0)
  578. return false;
  579. return true;
  580. }
  581. APInt APInt::byteSwap() const {
  582. assert(BitWidth >= 16 && BitWidth % 8 == 0 && "Cannot byteswap!");
  583. if (BitWidth == 16)
  584. return APInt(BitWidth, ByteSwap_16(uint16_t(U.VAL)));
  585. if (BitWidth == 32)
  586. return APInt(BitWidth, ByteSwap_32(unsigned(U.VAL)));
  587. if (BitWidth <= 64) {
  588. uint64_t Tmp1 = ByteSwap_64(U.VAL);
  589. Tmp1 >>= (64 - BitWidth);
  590. return APInt(BitWidth, Tmp1);
  591. }
  592. APInt Result(getNumWords() * APINT_BITS_PER_WORD, 0);
  593. for (unsigned I = 0, N = getNumWords(); I != N; ++I)
  594. Result.U.pVal[I] = ByteSwap_64(U.pVal[N - I - 1]);
  595. if (Result.BitWidth != BitWidth) {
  596. Result.lshrInPlace(Result.BitWidth - BitWidth);
  597. Result.BitWidth = BitWidth;
  598. }
  599. return Result;
  600. }
  601. APInt APInt::reverseBits() const {
  602. switch (BitWidth) {
  603. case 64:
  604. return APInt(BitWidth, llvm::reverseBits<uint64_t>(U.VAL));
  605. case 32:
  606. return APInt(BitWidth, llvm::reverseBits<uint32_t>(U.VAL));
  607. case 16:
  608. return APInt(BitWidth, llvm::reverseBits<uint16_t>(U.VAL));
  609. case 8:
  610. return APInt(BitWidth, llvm::reverseBits<uint8_t>(U.VAL));
  611. case 0:
  612. return *this;
  613. default:
  614. break;
  615. }
  616. APInt Val(*this);
  617. APInt Reversed(BitWidth, 0);
  618. unsigned S = BitWidth;
  619. for (; Val != 0; Val.lshrInPlace(1)) {
  620. Reversed <<= 1;
  621. Reversed |= Val[0];
  622. --S;
  623. }
  624. Reversed <<= S;
  625. return Reversed;
  626. }
  627. APInt llvm::APIntOps::GreatestCommonDivisor(APInt A, APInt B) {
  628. // Fast-path a common case.
  629. if (A == B) return A;
  630. // Corner cases: if either operand is zero, the other is the gcd.
  631. if (!A) return B;
  632. if (!B) return A;
  633. // Count common powers of 2 and remove all other powers of 2.
  634. unsigned Pow2;
  635. {
  636. unsigned Pow2_A = A.countTrailingZeros();
  637. unsigned Pow2_B = B.countTrailingZeros();
  638. if (Pow2_A > Pow2_B) {
  639. A.lshrInPlace(Pow2_A - Pow2_B);
  640. Pow2 = Pow2_B;
  641. } else if (Pow2_B > Pow2_A) {
  642. B.lshrInPlace(Pow2_B - Pow2_A);
  643. Pow2 = Pow2_A;
  644. } else {
  645. Pow2 = Pow2_A;
  646. }
  647. }
  648. // Both operands are odd multiples of 2^Pow_2:
  649. //
  650. // gcd(a, b) = gcd(|a - b| / 2^i, min(a, b))
  651. //
  652. // This is a modified version of Stein's algorithm, taking advantage of
  653. // efficient countTrailingZeros().
  654. while (A != B) {
  655. if (A.ugt(B)) {
  656. A -= B;
  657. A.lshrInPlace(A.countTrailingZeros() - Pow2);
  658. } else {
  659. B -= A;
  660. B.lshrInPlace(B.countTrailingZeros() - Pow2);
  661. }
  662. }
  663. return A;
  664. }
  665. APInt llvm::APIntOps::RoundDoubleToAPInt(double Double, unsigned width) {
  666. uint64_t I = bit_cast<uint64_t>(Double);
  667. // Get the sign bit from the highest order bit
  668. bool isNeg = I >> 63;
  669. // Get the 11-bit exponent and adjust for the 1023 bit bias
  670. int64_t exp = ((I >> 52) & 0x7ff) - 1023;
  671. // If the exponent is negative, the value is < 0 so just return 0.
  672. if (exp < 0)
  673. return APInt(width, 0u);
  674. // Extract the mantissa by clearing the top 12 bits (sign + exponent).
  675. uint64_t mantissa = (I & (~0ULL >> 12)) | 1ULL << 52;
  676. // If the exponent doesn't shift all bits out of the mantissa
  677. if (exp < 52)
  678. return isNeg ? -APInt(width, mantissa >> (52 - exp)) :
  679. APInt(width, mantissa >> (52 - exp));
  680. // If the client didn't provide enough bits for us to shift the mantissa into
  681. // then the result is undefined, just return 0
  682. if (width <= exp - 52)
  683. return APInt(width, 0);
  684. // Otherwise, we have to shift the mantissa bits up to the right location
  685. APInt Tmp(width, mantissa);
  686. Tmp <<= (unsigned)exp - 52;
  687. return isNeg ? -Tmp : Tmp;
  688. }
  689. /// This function converts this APInt to a double.
  690. /// The layout for double is as following (IEEE Standard 754):
  691. /// --------------------------------------
  692. /// | Sign Exponent Fraction Bias |
  693. /// |-------------------------------------- |
  694. /// | 1[63] 11[62-52] 52[51-00] 1023 |
  695. /// --------------------------------------
  696. double APInt::roundToDouble(bool isSigned) const {
  697. // Handle the simple case where the value is contained in one uint64_t.
  698. // It is wrong to optimize getWord(0) to VAL; there might be more than one word.
  699. if (isSingleWord() || getActiveBits() <= APINT_BITS_PER_WORD) {
  700. if (isSigned) {
  701. int64_t sext = SignExtend64(getWord(0), BitWidth);
  702. return double(sext);
  703. } else
  704. return double(getWord(0));
  705. }
  706. // Determine if the value is negative.
  707. bool isNeg = isSigned ? (*this)[BitWidth-1] : false;
  708. // Construct the absolute value if we're negative.
  709. APInt Tmp(isNeg ? -(*this) : (*this));
  710. // Figure out how many bits we're using.
  711. unsigned n = Tmp.getActiveBits();
  712. // The exponent (without bias normalization) is just the number of bits
  713. // we are using. Note that the sign bit is gone since we constructed the
  714. // absolute value.
  715. uint64_t exp = n;
  716. // Return infinity for exponent overflow
  717. if (exp > 1023) {
  718. if (!isSigned || !isNeg)
  719. return std::numeric_limits<double>::infinity();
  720. else
  721. return -std::numeric_limits<double>::infinity();
  722. }
  723. exp += 1023; // Increment for 1023 bias
  724. // Number of bits in mantissa is 52. To obtain the mantissa value, we must
  725. // extract the high 52 bits from the correct words in pVal.
  726. uint64_t mantissa;
  727. unsigned hiWord = whichWord(n-1);
  728. if (hiWord == 0) {
  729. mantissa = Tmp.U.pVal[0];
  730. if (n > 52)
  731. mantissa >>= n - 52; // shift down, we want the top 52 bits.
  732. } else {
  733. assert(hiWord > 0 && "huh?");
  734. uint64_t hibits = Tmp.U.pVal[hiWord] << (52 - n % APINT_BITS_PER_WORD);
  735. uint64_t lobits = Tmp.U.pVal[hiWord-1] >> (11 + n % APINT_BITS_PER_WORD);
  736. mantissa = hibits | lobits;
  737. }
  738. // The leading bit of mantissa is implicit, so get rid of it.
  739. uint64_t sign = isNeg ? (1ULL << (APINT_BITS_PER_WORD - 1)) : 0;
  740. uint64_t I = sign | (exp << 52) | mantissa;
  741. return bit_cast<double>(I);
  742. }
  743. // Truncate to new width.
  744. APInt APInt::trunc(unsigned width) const {
  745. assert(width < BitWidth && "Invalid APInt Truncate request");
  746. if (width <= APINT_BITS_PER_WORD)
  747. return APInt(width, getRawData()[0]);
  748. APInt Result(getMemory(getNumWords(width)), width);
  749. // Copy full words.
  750. unsigned i;
  751. for (i = 0; i != width / APINT_BITS_PER_WORD; i++)
  752. Result.U.pVal[i] = U.pVal[i];
  753. // Truncate and copy any partial word.
  754. unsigned bits = (0 - width) % APINT_BITS_PER_WORD;
  755. if (bits != 0)
  756. Result.U.pVal[i] = U.pVal[i] << bits >> bits;
  757. return Result;
  758. }
  759. // Truncate to new width with unsigned saturation.
  760. APInt APInt::truncUSat(unsigned width) const {
  761. assert(width < BitWidth && "Invalid APInt Truncate request");
  762. // Can we just losslessly truncate it?
  763. if (isIntN(width))
  764. return trunc(width);
  765. // If not, then just return the new limit.
  766. return APInt::getMaxValue(width);
  767. }
  768. // Truncate to new width with signed saturation.
  769. APInt APInt::truncSSat(unsigned width) const {
  770. assert(width < BitWidth && "Invalid APInt Truncate request");
  771. // Can we just losslessly truncate it?
  772. if (isSignedIntN(width))
  773. return trunc(width);
  774. // If not, then just return the new limits.
  775. return isNegative() ? APInt::getSignedMinValue(width)
  776. : APInt::getSignedMaxValue(width);
  777. }
  778. // Sign extend to a new width.
  779. APInt APInt::sext(unsigned Width) const {
  780. assert(Width > BitWidth && "Invalid APInt SignExtend request");
  781. if (Width <= APINT_BITS_PER_WORD)
  782. return APInt(Width, SignExtend64(U.VAL, BitWidth));
  783. APInt Result(getMemory(getNumWords(Width)), Width);
  784. // Copy words.
  785. std::memcpy(Result.U.pVal, getRawData(), getNumWords() * APINT_WORD_SIZE);
  786. // Sign extend the last word since there may be unused bits in the input.
  787. Result.U.pVal[getNumWords() - 1] =
  788. SignExtend64(Result.U.pVal[getNumWords() - 1],
  789. ((BitWidth - 1) % APINT_BITS_PER_WORD) + 1);
  790. // Fill with sign bits.
  791. std::memset(Result.U.pVal + getNumWords(), isNegative() ? -1 : 0,
  792. (Result.getNumWords() - getNumWords()) * APINT_WORD_SIZE);
  793. Result.clearUnusedBits();
  794. return Result;
  795. }
  796. // Zero extend to a new width.
  797. APInt APInt::zext(unsigned width) const {
  798. assert(width > BitWidth && "Invalid APInt ZeroExtend request");
  799. if (width <= APINT_BITS_PER_WORD)
  800. return APInt(width, U.VAL);
  801. APInt Result(getMemory(getNumWords(width)), width);
  802. // Copy words.
  803. std::memcpy(Result.U.pVal, getRawData(), getNumWords() * APINT_WORD_SIZE);
  804. // Zero remaining words.
  805. std::memset(Result.U.pVal + getNumWords(), 0,
  806. (Result.getNumWords() - getNumWords()) * APINT_WORD_SIZE);
  807. return Result;
  808. }
  809. APInt APInt::zextOrTrunc(unsigned width) const {
  810. if (BitWidth < width)
  811. return zext(width);
  812. if (BitWidth > width)
  813. return trunc(width);
  814. return *this;
  815. }
  816. APInt APInt::sextOrTrunc(unsigned width) const {
  817. if (BitWidth < width)
  818. return sext(width);
  819. if (BitWidth > width)
  820. return trunc(width);
  821. return *this;
  822. }
  823. APInt APInt::truncOrSelf(unsigned width) const {
  824. if (BitWidth > width)
  825. return trunc(width);
  826. return *this;
  827. }
  828. APInt APInt::zextOrSelf(unsigned width) const {
  829. if (BitWidth < width)
  830. return zext(width);
  831. return *this;
  832. }
  833. APInt APInt::sextOrSelf(unsigned width) const {
  834. if (BitWidth < width)
  835. return sext(width);
  836. return *this;
  837. }
  838. /// Arithmetic right-shift this APInt by shiftAmt.
  839. /// Arithmetic right-shift function.
  840. void APInt::ashrInPlace(const APInt &shiftAmt) {
  841. ashrInPlace((unsigned)shiftAmt.getLimitedValue(BitWidth));
  842. }
  843. /// Arithmetic right-shift this APInt by shiftAmt.
  844. /// Arithmetic right-shift function.
  845. void APInt::ashrSlowCase(unsigned ShiftAmt) {
  846. // Don't bother performing a no-op shift.
  847. if (!ShiftAmt)
  848. return;
  849. // Save the original sign bit for later.
  850. bool Negative = isNegative();
  851. // WordShift is the inter-part shift; BitShift is intra-part shift.
  852. unsigned WordShift = ShiftAmt / APINT_BITS_PER_WORD;
  853. unsigned BitShift = ShiftAmt % APINT_BITS_PER_WORD;
  854. unsigned WordsToMove = getNumWords() - WordShift;
  855. if (WordsToMove != 0) {
  856. // Sign extend the last word to fill in the unused bits.
  857. U.pVal[getNumWords() - 1] = SignExtend64(
  858. U.pVal[getNumWords() - 1], ((BitWidth - 1) % APINT_BITS_PER_WORD) + 1);
  859. // Fastpath for moving by whole words.
  860. if (BitShift == 0) {
  861. std::memmove(U.pVal, U.pVal + WordShift, WordsToMove * APINT_WORD_SIZE);
  862. } else {
  863. // Move the words containing significant bits.
  864. for (unsigned i = 0; i != WordsToMove - 1; ++i)
  865. U.pVal[i] = (U.pVal[i + WordShift] >> BitShift) |
  866. (U.pVal[i + WordShift + 1] << (APINT_BITS_PER_WORD - BitShift));
  867. // Handle the last word which has no high bits to copy.
  868. U.pVal[WordsToMove - 1] = U.pVal[WordShift + WordsToMove - 1] >> BitShift;
  869. // Sign extend one more time.
  870. U.pVal[WordsToMove - 1] =
  871. SignExtend64(U.pVal[WordsToMove - 1], APINT_BITS_PER_WORD - BitShift);
  872. }
  873. }
  874. // Fill in the remainder based on the original sign.
  875. std::memset(U.pVal + WordsToMove, Negative ? -1 : 0,
  876. WordShift * APINT_WORD_SIZE);
  877. clearUnusedBits();
  878. }
  879. /// Logical right-shift this APInt by shiftAmt.
  880. /// Logical right-shift function.
  881. void APInt::lshrInPlace(const APInt &shiftAmt) {
  882. lshrInPlace((unsigned)shiftAmt.getLimitedValue(BitWidth));
  883. }
  884. /// Logical right-shift this APInt by shiftAmt.
  885. /// Logical right-shift function.
  886. void APInt::lshrSlowCase(unsigned ShiftAmt) {
  887. tcShiftRight(U.pVal, getNumWords(), ShiftAmt);
  888. }
  889. /// Left-shift this APInt by shiftAmt.
  890. /// Left-shift function.
  891. APInt &APInt::operator<<=(const APInt &shiftAmt) {
  892. // It's undefined behavior in C to shift by BitWidth or greater.
  893. *this <<= (unsigned)shiftAmt.getLimitedValue(BitWidth);
  894. return *this;
  895. }
  896. void APInt::shlSlowCase(unsigned ShiftAmt) {
  897. tcShiftLeft(U.pVal, getNumWords(), ShiftAmt);
  898. clearUnusedBits();
  899. }
  900. // Calculate the rotate amount modulo the bit width.
  901. static unsigned rotateModulo(unsigned BitWidth, const APInt &rotateAmt) {
  902. if (LLVM_UNLIKELY(BitWidth == 0))
  903. return 0;
  904. unsigned rotBitWidth = rotateAmt.getBitWidth();
  905. APInt rot = rotateAmt;
  906. if (rotBitWidth < BitWidth) {
  907. // Extend the rotate APInt, so that the urem doesn't divide by 0.
  908. // e.g. APInt(1, 32) would give APInt(1, 0).
  909. rot = rotateAmt.zext(BitWidth);
  910. }
  911. rot = rot.urem(APInt(rot.getBitWidth(), BitWidth));
  912. return rot.getLimitedValue(BitWidth);
  913. }
  914. APInt APInt::rotl(const APInt &rotateAmt) const {
  915. return rotl(rotateModulo(BitWidth, rotateAmt));
  916. }
  917. APInt APInt::rotl(unsigned rotateAmt) const {
  918. if (LLVM_UNLIKELY(BitWidth == 0))
  919. return *this;
  920. rotateAmt %= BitWidth;
  921. if (rotateAmt == 0)
  922. return *this;
  923. return shl(rotateAmt) | lshr(BitWidth - rotateAmt);
  924. }
  925. APInt APInt::rotr(const APInt &rotateAmt) const {
  926. return rotr(rotateModulo(BitWidth, rotateAmt));
  927. }
  928. APInt APInt::rotr(unsigned rotateAmt) const {
  929. if (BitWidth == 0)
  930. return *this;
  931. rotateAmt %= BitWidth;
  932. if (rotateAmt == 0)
  933. return *this;
  934. return lshr(rotateAmt) | shl(BitWidth - rotateAmt);
  935. }
  936. /// \returns the nearest log base 2 of this APInt. Ties round up.
  937. ///
  938. /// NOTE: When we have a BitWidth of 1, we define:
  939. ///
  940. /// log2(0) = UINT32_MAX
  941. /// log2(1) = 0
  942. ///
  943. /// to get around any mathematical concerns resulting from
  944. /// referencing 2 in a space where 2 does no exist.
  945. unsigned APInt::nearestLogBase2() const {
  946. // Special case when we have a bitwidth of 1. If VAL is 1, then we
  947. // get 0. If VAL is 0, we get WORDTYPE_MAX which gets truncated to
  948. // UINT32_MAX.
  949. if (BitWidth == 1)
  950. return U.VAL - 1;
  951. // Handle the zero case.
  952. if (isZero())
  953. return UINT32_MAX;
  954. // The non-zero case is handled by computing:
  955. //
  956. // nearestLogBase2(x) = logBase2(x) + x[logBase2(x)-1].
  957. //
  958. // where x[i] is referring to the value of the ith bit of x.
  959. unsigned lg = logBase2();
  960. return lg + unsigned((*this)[lg - 1]);
  961. }
  962. // Square Root - this method computes and returns the square root of "this".
  963. // Three mechanisms are used for computation. For small values (<= 5 bits),
  964. // a table lookup is done. This gets some performance for common cases. For
  965. // values using less than 52 bits, the value is converted to double and then
  966. // the libc sqrt function is called. The result is rounded and then converted
  967. // back to a uint64_t which is then used to construct the result. Finally,
  968. // the Babylonian method for computing square roots is used.
  969. APInt APInt::sqrt() const {
  970. // Determine the magnitude of the value.
  971. unsigned magnitude = getActiveBits();
  972. // Use a fast table for some small values. This also gets rid of some
  973. // rounding errors in libc sqrt for small values.
  974. if (magnitude <= 5) {
  975. static const uint8_t results[32] = {
  976. /* 0 */ 0,
  977. /* 1- 2 */ 1, 1,
  978. /* 3- 6 */ 2, 2, 2, 2,
  979. /* 7-12 */ 3, 3, 3, 3, 3, 3,
  980. /* 13-20 */ 4, 4, 4, 4, 4, 4, 4, 4,
  981. /* 21-30 */ 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  982. /* 31 */ 6
  983. };
  984. return APInt(BitWidth, results[ (isSingleWord() ? U.VAL : U.pVal[0]) ]);
  985. }
  986. // If the magnitude of the value fits in less than 52 bits (the precision of
  987. // an IEEE double precision floating point value), then we can use the
  988. // libc sqrt function which will probably use a hardware sqrt computation.
  989. // This should be faster than the algorithm below.
  990. if (magnitude < 52) {
  991. return APInt(BitWidth,
  992. uint64_t(::round(::sqrt(double(isSingleWord() ? U.VAL
  993. : U.pVal[0])))));
  994. }
  995. // Okay, all the short cuts are exhausted. We must compute it. The following
  996. // is a classical Babylonian method for computing the square root. This code
  997. // was adapted to APInt from a wikipedia article on such computations.
  998. // See http://www.wikipedia.org/ and go to the page named
  999. // Calculate_an_integer_square_root.
  1000. unsigned nbits = BitWidth, i = 4;
  1001. APInt testy(BitWidth, 16);
  1002. APInt x_old(BitWidth, 1);
  1003. APInt x_new(BitWidth, 0);
  1004. APInt two(BitWidth, 2);
  1005. // Select a good starting value using binary logarithms.
  1006. for (;; i += 2, testy = testy.shl(2))
  1007. if (i >= nbits || this->ule(testy)) {
  1008. x_old = x_old.shl(i / 2);
  1009. break;
  1010. }
  1011. // Use the Babylonian method to arrive at the integer square root:
  1012. for (;;) {
  1013. x_new = (this->udiv(x_old) + x_old).udiv(two);
  1014. if (x_old.ule(x_new))
  1015. break;
  1016. x_old = x_new;
  1017. }
  1018. // Make sure we return the closest approximation
  1019. // NOTE: The rounding calculation below is correct. It will produce an
  1020. // off-by-one discrepancy with results from pari/gp. That discrepancy has been
  1021. // determined to be a rounding issue with pari/gp as it begins to use a
  1022. // floating point representation after 192 bits. There are no discrepancies
  1023. // between this algorithm and pari/gp for bit widths < 192 bits.
  1024. APInt square(x_old * x_old);
  1025. APInt nextSquare((x_old + 1) * (x_old +1));
  1026. if (this->ult(square))
  1027. return x_old;
  1028. assert(this->ule(nextSquare) && "Error in APInt::sqrt computation");
  1029. APInt midpoint((nextSquare - square).udiv(two));
  1030. APInt offset(*this - square);
  1031. if (offset.ult(midpoint))
  1032. return x_old;
  1033. return x_old + 1;
  1034. }
  1035. /// Computes the multiplicative inverse of this APInt for a given modulo. The
  1036. /// iterative extended Euclidean algorithm is used to solve for this value,
  1037. /// however we simplify it to speed up calculating only the inverse, and take
  1038. /// advantage of div+rem calculations. We also use some tricks to avoid copying
  1039. /// (potentially large) APInts around.
  1040. /// WARNING: a value of '0' may be returned,
  1041. /// signifying that no multiplicative inverse exists!
  1042. APInt APInt::multiplicativeInverse(const APInt& modulo) const {
  1043. assert(ult(modulo) && "This APInt must be smaller than the modulo");
  1044. // Using the properties listed at the following web page (accessed 06/21/08):
  1045. // http://www.numbertheory.org/php/euclid.html
  1046. // (especially the properties numbered 3, 4 and 9) it can be proved that
  1047. // BitWidth bits suffice for all the computations in the algorithm implemented
  1048. // below. More precisely, this number of bits suffice if the multiplicative
  1049. // inverse exists, but may not suffice for the general extended Euclidean
  1050. // algorithm.
  1051. APInt r[2] = { modulo, *this };
  1052. APInt t[2] = { APInt(BitWidth, 0), APInt(BitWidth, 1) };
  1053. APInt q(BitWidth, 0);
  1054. unsigned i;
  1055. for (i = 0; r[i^1] != 0; i ^= 1) {
  1056. // An overview of the math without the confusing bit-flipping:
  1057. // q = r[i-2] / r[i-1]
  1058. // r[i] = r[i-2] % r[i-1]
  1059. // t[i] = t[i-2] - t[i-1] * q
  1060. udivrem(r[i], r[i^1], q, r[i]);
  1061. t[i] -= t[i^1] * q;
  1062. }
  1063. // If this APInt and the modulo are not coprime, there is no multiplicative
  1064. // inverse, so return 0. We check this by looking at the next-to-last
  1065. // remainder, which is the gcd(*this,modulo) as calculated by the Euclidean
  1066. // algorithm.
  1067. if (r[i] != 1)
  1068. return APInt(BitWidth, 0);
  1069. // The next-to-last t is the multiplicative inverse. However, we are
  1070. // interested in a positive inverse. Calculate a positive one from a negative
  1071. // one if necessary. A simple addition of the modulo suffices because
  1072. // abs(t[i]) is known to be less than *this/2 (see the link above).
  1073. if (t[i].isNegative())
  1074. t[i] += modulo;
  1075. return std::move(t[i]);
  1076. }
  1077. /// Implementation of Knuth's Algorithm D (Division of nonnegative integers)
  1078. /// from "Art of Computer Programming, Volume 2", section 4.3.1, p. 272. The
  1079. /// variables here have the same names as in the algorithm. Comments explain
  1080. /// the algorithm and any deviation from it.
  1081. static void KnuthDiv(uint32_t *u, uint32_t *v, uint32_t *q, uint32_t* r,
  1082. unsigned m, unsigned n) {
  1083. assert(u && "Must provide dividend");
  1084. assert(v && "Must provide divisor");
  1085. assert(q && "Must provide quotient");
  1086. assert(u != v && u != q && v != q && "Must use different memory");
  1087. assert(n>1 && "n must be > 1");
  1088. // b denotes the base of the number system. In our case b is 2^32.
  1089. const uint64_t b = uint64_t(1) << 32;
  1090. // The DEBUG macros here tend to be spam in the debug output if you're not
  1091. // debugging this code. Disable them unless KNUTH_DEBUG is defined.
  1092. #ifdef KNUTH_DEBUG
  1093. #define DEBUG_KNUTH(X) LLVM_DEBUG(X)
  1094. #else
  1095. #define DEBUG_KNUTH(X) do {} while(false)
  1096. #endif
  1097. DEBUG_KNUTH(dbgs() << "KnuthDiv: m=" << m << " n=" << n << '\n');
  1098. DEBUG_KNUTH(dbgs() << "KnuthDiv: original:");
  1099. DEBUG_KNUTH(for (int i = m + n; i >= 0; i--) dbgs() << " " << u[i]);
  1100. DEBUG_KNUTH(dbgs() << " by");
  1101. DEBUG_KNUTH(for (int i = n; i > 0; i--) dbgs() << " " << v[i - 1]);
  1102. DEBUG_KNUTH(dbgs() << '\n');
  1103. // D1. [Normalize.] Set d = b / (v[n-1] + 1) and multiply all the digits of
  1104. // u and v by d. Note that we have taken Knuth's advice here to use a power
  1105. // of 2 value for d such that d * v[n-1] >= b/2 (b is the base). A power of
  1106. // 2 allows us to shift instead of multiply and it is easy to determine the
  1107. // shift amount from the leading zeros. We are basically normalizing the u
  1108. // and v so that its high bits are shifted to the top of v's range without
  1109. // overflow. Note that this can require an extra word in u so that u must
  1110. // be of length m+n+1.
  1111. unsigned shift = countLeadingZeros(v[n-1]);
  1112. uint32_t v_carry = 0;
  1113. uint32_t u_carry = 0;
  1114. if (shift) {
  1115. for (unsigned i = 0; i < m+n; ++i) {
  1116. uint32_t u_tmp = u[i] >> (32 - shift);
  1117. u[i] = (u[i] << shift) | u_carry;
  1118. u_carry = u_tmp;
  1119. }
  1120. for (unsigned i = 0; i < n; ++i) {
  1121. uint32_t v_tmp = v[i] >> (32 - shift);
  1122. v[i] = (v[i] << shift) | v_carry;
  1123. v_carry = v_tmp;
  1124. }
  1125. }
  1126. u[m+n] = u_carry;
  1127. DEBUG_KNUTH(dbgs() << "KnuthDiv: normal:");
  1128. DEBUG_KNUTH(for (int i = m + n; i >= 0; i--) dbgs() << " " << u[i]);
  1129. DEBUG_KNUTH(dbgs() << " by");
  1130. DEBUG_KNUTH(for (int i = n; i > 0; i--) dbgs() << " " << v[i - 1]);
  1131. DEBUG_KNUTH(dbgs() << '\n');
  1132. // D2. [Initialize j.] Set j to m. This is the loop counter over the places.
  1133. int j = m;
  1134. do {
  1135. DEBUG_KNUTH(dbgs() << "KnuthDiv: quotient digit #" << j << '\n');
  1136. // D3. [Calculate q'.].
  1137. // Set qp = (u[j+n]*b + u[j+n-1]) / v[n-1]. (qp=qprime=q')
  1138. // Set rp = (u[j+n]*b + u[j+n-1]) % v[n-1]. (rp=rprime=r')
  1139. // Now test if qp == b or qp*v[n-2] > b*rp + u[j+n-2]; if so, decrease
  1140. // qp by 1, increase rp by v[n-1], and repeat this test if rp < b. The test
  1141. // on v[n-2] determines at high speed most of the cases in which the trial
  1142. // value qp is one too large, and it eliminates all cases where qp is two
  1143. // too large.
  1144. uint64_t dividend = Make_64(u[j+n], u[j+n-1]);
  1145. DEBUG_KNUTH(dbgs() << "KnuthDiv: dividend == " << dividend << '\n');
  1146. uint64_t qp = dividend / v[n-1];
  1147. uint64_t rp = dividend % v[n-1];
  1148. if (qp == b || qp*v[n-2] > b*rp + u[j+n-2]) {
  1149. qp--;
  1150. rp += v[n-1];
  1151. if (rp < b && (qp == b || qp*v[n-2] > b*rp + u[j+n-2]))
  1152. qp--;
  1153. }
  1154. DEBUG_KNUTH(dbgs() << "KnuthDiv: qp == " << qp << ", rp == " << rp << '\n');
  1155. // D4. [Multiply and subtract.] Replace (u[j+n]u[j+n-1]...u[j]) with
  1156. // (u[j+n]u[j+n-1]..u[j]) - qp * (v[n-1]...v[1]v[0]). This computation
  1157. // consists of a simple multiplication by a one-place number, combined with
  1158. // a subtraction.
  1159. // The digits (u[j+n]...u[j]) should be kept positive; if the result of
  1160. // this step is actually negative, (u[j+n]...u[j]) should be left as the
  1161. // true value plus b**(n+1), namely as the b's complement of
  1162. // the true value, and a "borrow" to the left should be remembered.
  1163. int64_t borrow = 0;
  1164. for (unsigned i = 0; i < n; ++i) {
  1165. uint64_t p = uint64_t(qp) * uint64_t(v[i]);
  1166. int64_t subres = int64_t(u[j+i]) - borrow - Lo_32(p);
  1167. u[j+i] = Lo_32(subres);
  1168. borrow = Hi_32(p) - Hi_32(subres);
  1169. DEBUG_KNUTH(dbgs() << "KnuthDiv: u[j+i] = " << u[j + i]
  1170. << ", borrow = " << borrow << '\n');
  1171. }
  1172. bool isNeg = u[j+n] < borrow;
  1173. u[j+n] -= Lo_32(borrow);
  1174. DEBUG_KNUTH(dbgs() << "KnuthDiv: after subtraction:");
  1175. DEBUG_KNUTH(for (int i = m + n; i >= 0; i--) dbgs() << " " << u[i]);
  1176. DEBUG_KNUTH(dbgs() << '\n');
  1177. // D5. [Test remainder.] Set q[j] = qp. If the result of step D4 was
  1178. // negative, go to step D6; otherwise go on to step D7.
  1179. q[j] = Lo_32(qp);
  1180. if (isNeg) {
  1181. // D6. [Add back]. The probability that this step is necessary is very
  1182. // small, on the order of only 2/b. Make sure that test data accounts for
  1183. // this possibility. Decrease q[j] by 1
  1184. q[j]--;
  1185. // and add (0v[n-1]...v[1]v[0]) to (u[j+n]u[j+n-1]...u[j+1]u[j]).
  1186. // A carry will occur to the left of u[j+n], and it should be ignored
  1187. // since it cancels with the borrow that occurred in D4.
  1188. bool carry = false;
  1189. for (unsigned i = 0; i < n; i++) {
  1190. uint32_t limit = std::min(u[j+i],v[i]);
  1191. u[j+i] += v[i] + carry;
  1192. carry = u[j+i] < limit || (carry && u[j+i] == limit);
  1193. }
  1194. u[j+n] += carry;
  1195. }
  1196. DEBUG_KNUTH(dbgs() << "KnuthDiv: after correction:");
  1197. DEBUG_KNUTH(for (int i = m + n; i >= 0; i--) dbgs() << " " << u[i]);
  1198. DEBUG_KNUTH(dbgs() << "\nKnuthDiv: digit result = " << q[j] << '\n');
  1199. // D7. [Loop on j.] Decrease j by one. Now if j >= 0, go back to D3.
  1200. } while (--j >= 0);
  1201. DEBUG_KNUTH(dbgs() << "KnuthDiv: quotient:");
  1202. DEBUG_KNUTH(for (int i = m; i >= 0; i--) dbgs() << " " << q[i]);
  1203. DEBUG_KNUTH(dbgs() << '\n');
  1204. // D8. [Unnormalize]. Now q[...] is the desired quotient, and the desired
  1205. // remainder may be obtained by dividing u[...] by d. If r is non-null we
  1206. // compute the remainder (urem uses this).
  1207. if (r) {
  1208. // The value d is expressed by the "shift" value above since we avoided
  1209. // multiplication by d by using a shift left. So, all we have to do is
  1210. // shift right here.
  1211. if (shift) {
  1212. uint32_t carry = 0;
  1213. DEBUG_KNUTH(dbgs() << "KnuthDiv: remainder:");
  1214. for (int i = n-1; i >= 0; i--) {
  1215. r[i] = (u[i] >> shift) | carry;
  1216. carry = u[i] << (32 - shift);
  1217. DEBUG_KNUTH(dbgs() << " " << r[i]);
  1218. }
  1219. } else {
  1220. for (int i = n-1; i >= 0; i--) {
  1221. r[i] = u[i];
  1222. DEBUG_KNUTH(dbgs() << " " << r[i]);
  1223. }
  1224. }
  1225. DEBUG_KNUTH(dbgs() << '\n');
  1226. }
  1227. DEBUG_KNUTH(dbgs() << '\n');
  1228. }
  1229. void APInt::divide(const WordType *LHS, unsigned lhsWords, const WordType *RHS,
  1230. unsigned rhsWords, WordType *Quotient, WordType *Remainder) {
  1231. assert(lhsWords >= rhsWords && "Fractional result");
  1232. // First, compose the values into an array of 32-bit words instead of
  1233. // 64-bit words. This is a necessity of both the "short division" algorithm
  1234. // and the Knuth "classical algorithm" which requires there to be native
  1235. // operations for +, -, and * on an m bit value with an m*2 bit result. We
  1236. // can't use 64-bit operands here because we don't have native results of
  1237. // 128-bits. Furthermore, casting the 64-bit values to 32-bit values won't
  1238. // work on large-endian machines.
  1239. unsigned n = rhsWords * 2;
  1240. unsigned m = (lhsWords * 2) - n;
  1241. // Allocate space for the temporary values we need either on the stack, if
  1242. // it will fit, or on the heap if it won't.
  1243. uint32_t SPACE[128];
  1244. uint32_t *U = nullptr;
  1245. uint32_t *V = nullptr;
  1246. uint32_t *Q = nullptr;
  1247. uint32_t *R = nullptr;
  1248. if ((Remainder?4:3)*n+2*m+1 <= 128) {
  1249. U = &SPACE[0];
  1250. V = &SPACE[m+n+1];
  1251. Q = &SPACE[(m+n+1) + n];
  1252. if (Remainder)
  1253. R = &SPACE[(m+n+1) + n + (m+n)];
  1254. } else {
  1255. U = new uint32_t[m + n + 1];
  1256. V = new uint32_t[n];
  1257. Q = new uint32_t[m+n];
  1258. if (Remainder)
  1259. R = new uint32_t[n];
  1260. }
  1261. // Initialize the dividend
  1262. memset(U, 0, (m+n+1)*sizeof(uint32_t));
  1263. for (unsigned i = 0; i < lhsWords; ++i) {
  1264. uint64_t tmp = LHS[i];
  1265. U[i * 2] = Lo_32(tmp);
  1266. U[i * 2 + 1] = Hi_32(tmp);
  1267. }
  1268. U[m+n] = 0; // this extra word is for "spill" in the Knuth algorithm.
  1269. // Initialize the divisor
  1270. memset(V, 0, (n)*sizeof(uint32_t));
  1271. for (unsigned i = 0; i < rhsWords; ++i) {
  1272. uint64_t tmp = RHS[i];
  1273. V[i * 2] = Lo_32(tmp);
  1274. V[i * 2 + 1] = Hi_32(tmp);
  1275. }
  1276. // initialize the quotient and remainder
  1277. memset(Q, 0, (m+n) * sizeof(uint32_t));
  1278. if (Remainder)
  1279. memset(R, 0, n * sizeof(uint32_t));
  1280. // Now, adjust m and n for the Knuth division. n is the number of words in
  1281. // the divisor. m is the number of words by which the dividend exceeds the
  1282. // divisor (i.e. m+n is the length of the dividend). These sizes must not
  1283. // contain any zero words or the Knuth algorithm fails.
  1284. for (unsigned i = n; i > 0 && V[i-1] == 0; i--) {
  1285. n--;
  1286. m++;
  1287. }
  1288. for (unsigned i = m+n; i > 0 && U[i-1] == 0; i--)
  1289. m--;
  1290. // If we're left with only a single word for the divisor, Knuth doesn't work
  1291. // so we implement the short division algorithm here. This is much simpler
  1292. // and faster because we are certain that we can divide a 64-bit quantity
  1293. // by a 32-bit quantity at hardware speed and short division is simply a
  1294. // series of such operations. This is just like doing short division but we
  1295. // are using base 2^32 instead of base 10.
  1296. assert(n != 0 && "Divide by zero?");
  1297. if (n == 1) {
  1298. uint32_t divisor = V[0];
  1299. uint32_t remainder = 0;
  1300. for (int i = m; i >= 0; i--) {
  1301. uint64_t partial_dividend = Make_64(remainder, U[i]);
  1302. if (partial_dividend == 0) {
  1303. Q[i] = 0;
  1304. remainder = 0;
  1305. } else if (partial_dividend < divisor) {
  1306. Q[i] = 0;
  1307. remainder = Lo_32(partial_dividend);
  1308. } else if (partial_dividend == divisor) {
  1309. Q[i] = 1;
  1310. remainder = 0;
  1311. } else {
  1312. Q[i] = Lo_32(partial_dividend / divisor);
  1313. remainder = Lo_32(partial_dividend - (Q[i] * divisor));
  1314. }
  1315. }
  1316. if (R)
  1317. R[0] = remainder;
  1318. } else {
  1319. // Now we're ready to invoke the Knuth classical divide algorithm. In this
  1320. // case n > 1.
  1321. KnuthDiv(U, V, Q, R, m, n);
  1322. }
  1323. // If the caller wants the quotient
  1324. if (Quotient) {
  1325. for (unsigned i = 0; i < lhsWords; ++i)
  1326. Quotient[i] = Make_64(Q[i*2+1], Q[i*2]);
  1327. }
  1328. // If the caller wants the remainder
  1329. if (Remainder) {
  1330. for (unsigned i = 0; i < rhsWords; ++i)
  1331. Remainder[i] = Make_64(R[i*2+1], R[i*2]);
  1332. }
  1333. // Clean up the memory we allocated.
  1334. if (U != &SPACE[0]) {
  1335. delete [] U;
  1336. delete [] V;
  1337. delete [] Q;
  1338. delete [] R;
  1339. }
  1340. }
  1341. APInt APInt::udiv(const APInt &RHS) const {
  1342. assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
  1343. // First, deal with the easy case
  1344. if (isSingleWord()) {
  1345. assert(RHS.U.VAL != 0 && "Divide by zero?");
  1346. return APInt(BitWidth, U.VAL / RHS.U.VAL);
  1347. }
  1348. // Get some facts about the LHS and RHS number of bits and words
  1349. unsigned lhsWords = getNumWords(getActiveBits());
  1350. unsigned rhsBits = RHS.getActiveBits();
  1351. unsigned rhsWords = getNumWords(rhsBits);
  1352. assert(rhsWords && "Divided by zero???");
  1353. // Deal with some degenerate cases
  1354. if (!lhsWords)
  1355. // 0 / X ===> 0
  1356. return APInt(BitWidth, 0);
  1357. if (rhsBits == 1)
  1358. // X / 1 ===> X
  1359. return *this;
  1360. if (lhsWords < rhsWords || this->ult(RHS))
  1361. // X / Y ===> 0, iff X < Y
  1362. return APInt(BitWidth, 0);
  1363. if (*this == RHS)
  1364. // X / X ===> 1
  1365. return APInt(BitWidth, 1);
  1366. if (lhsWords == 1) // rhsWords is 1 if lhsWords is 1.
  1367. // All high words are zero, just use native divide
  1368. return APInt(BitWidth, this->U.pVal[0] / RHS.U.pVal[0]);
  1369. // We have to compute it the hard way. Invoke the Knuth divide algorithm.
  1370. APInt Quotient(BitWidth, 0); // to hold result.
  1371. divide(U.pVal, lhsWords, RHS.U.pVal, rhsWords, Quotient.U.pVal, nullptr);
  1372. return Quotient;
  1373. }
  1374. APInt APInt::udiv(uint64_t RHS) const {
  1375. assert(RHS != 0 && "Divide by zero?");
  1376. // First, deal with the easy case
  1377. if (isSingleWord())
  1378. return APInt(BitWidth, U.VAL / RHS);
  1379. // Get some facts about the LHS words.
  1380. unsigned lhsWords = getNumWords(getActiveBits());
  1381. // Deal with some degenerate cases
  1382. if (!lhsWords)
  1383. // 0 / X ===> 0
  1384. return APInt(BitWidth, 0);
  1385. if (RHS == 1)
  1386. // X / 1 ===> X
  1387. return *this;
  1388. if (this->ult(RHS))
  1389. // X / Y ===> 0, iff X < Y
  1390. return APInt(BitWidth, 0);
  1391. if (*this == RHS)
  1392. // X / X ===> 1
  1393. return APInt(BitWidth, 1);
  1394. if (lhsWords == 1) // rhsWords is 1 if lhsWords is 1.
  1395. // All high words are zero, just use native divide
  1396. return APInt(BitWidth, this->U.pVal[0] / RHS);
  1397. // We have to compute it the hard way. Invoke the Knuth divide algorithm.
  1398. APInt Quotient(BitWidth, 0); // to hold result.
  1399. divide(U.pVal, lhsWords, &RHS, 1, Quotient.U.pVal, nullptr);
  1400. return Quotient;
  1401. }
  1402. APInt APInt::sdiv(const APInt &RHS) const {
  1403. if (isNegative()) {
  1404. if (RHS.isNegative())
  1405. return (-(*this)).udiv(-RHS);
  1406. return -((-(*this)).udiv(RHS));
  1407. }
  1408. if (RHS.isNegative())
  1409. return -(this->udiv(-RHS));
  1410. return this->udiv(RHS);
  1411. }
  1412. APInt APInt::sdiv(int64_t RHS) const {
  1413. if (isNegative()) {
  1414. if (RHS < 0)
  1415. return (-(*this)).udiv(-RHS);
  1416. return -((-(*this)).udiv(RHS));
  1417. }
  1418. if (RHS < 0)
  1419. return -(this->udiv(-RHS));
  1420. return this->udiv(RHS);
  1421. }
  1422. APInt APInt::urem(const APInt &RHS) const {
  1423. assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
  1424. if (isSingleWord()) {
  1425. assert(RHS.U.VAL != 0 && "Remainder by zero?");
  1426. return APInt(BitWidth, U.VAL % RHS.U.VAL);
  1427. }
  1428. // Get some facts about the LHS
  1429. unsigned lhsWords = getNumWords(getActiveBits());
  1430. // Get some facts about the RHS
  1431. unsigned rhsBits = RHS.getActiveBits();
  1432. unsigned rhsWords = getNumWords(rhsBits);
  1433. assert(rhsWords && "Performing remainder operation by zero ???");
  1434. // Check the degenerate cases
  1435. if (lhsWords == 0)
  1436. // 0 % Y ===> 0
  1437. return APInt(BitWidth, 0);
  1438. if (rhsBits == 1)
  1439. // X % 1 ===> 0
  1440. return APInt(BitWidth, 0);
  1441. if (lhsWords < rhsWords || this->ult(RHS))
  1442. // X % Y ===> X, iff X < Y
  1443. return *this;
  1444. if (*this == RHS)
  1445. // X % X == 0;
  1446. return APInt(BitWidth, 0);
  1447. if (lhsWords == 1)
  1448. // All high words are zero, just use native remainder
  1449. return APInt(BitWidth, U.pVal[0] % RHS.U.pVal[0]);
  1450. // We have to compute it the hard way. Invoke the Knuth divide algorithm.
  1451. APInt Remainder(BitWidth, 0);
  1452. divide(U.pVal, lhsWords, RHS.U.pVal, rhsWords, nullptr, Remainder.U.pVal);
  1453. return Remainder;
  1454. }
  1455. uint64_t APInt::urem(uint64_t RHS) const {
  1456. assert(RHS != 0 && "Remainder by zero?");
  1457. if (isSingleWord())
  1458. return U.VAL % RHS;
  1459. // Get some facts about the LHS
  1460. unsigned lhsWords = getNumWords(getActiveBits());
  1461. // Check the degenerate cases
  1462. if (lhsWords == 0)
  1463. // 0 % Y ===> 0
  1464. return 0;
  1465. if (RHS == 1)
  1466. // X % 1 ===> 0
  1467. return 0;
  1468. if (this->ult(RHS))
  1469. // X % Y ===> X, iff X < Y
  1470. return getZExtValue();
  1471. if (*this == RHS)
  1472. // X % X == 0;
  1473. return 0;
  1474. if (lhsWords == 1)
  1475. // All high words are zero, just use native remainder
  1476. return U.pVal[0] % RHS;
  1477. // We have to compute it the hard way. Invoke the Knuth divide algorithm.
  1478. uint64_t Remainder;
  1479. divide(U.pVal, lhsWords, &RHS, 1, nullptr, &Remainder);
  1480. return Remainder;
  1481. }
  1482. APInt APInt::srem(const APInt &RHS) const {
  1483. if (isNegative()) {
  1484. if (RHS.isNegative())
  1485. return -((-(*this)).urem(-RHS));
  1486. return -((-(*this)).urem(RHS));
  1487. }
  1488. if (RHS.isNegative())
  1489. return this->urem(-RHS);
  1490. return this->urem(RHS);
  1491. }
  1492. int64_t APInt::srem(int64_t RHS) const {
  1493. if (isNegative()) {
  1494. if (RHS < 0)
  1495. return -((-(*this)).urem(-RHS));
  1496. return -((-(*this)).urem(RHS));
  1497. }
  1498. if (RHS < 0)
  1499. return this->urem(-RHS);
  1500. return this->urem(RHS);
  1501. }
  1502. void APInt::udivrem(const APInt &LHS, const APInt &RHS,
  1503. APInt &Quotient, APInt &Remainder) {
  1504. assert(LHS.BitWidth == RHS.BitWidth && "Bit widths must be the same");
  1505. unsigned BitWidth = LHS.BitWidth;
  1506. // First, deal with the easy case
  1507. if (LHS.isSingleWord()) {
  1508. assert(RHS.U.VAL != 0 && "Divide by zero?");
  1509. uint64_t QuotVal = LHS.U.VAL / RHS.U.VAL;
  1510. uint64_t RemVal = LHS.U.VAL % RHS.U.VAL;
  1511. Quotient = APInt(BitWidth, QuotVal);
  1512. Remainder = APInt(BitWidth, RemVal);
  1513. return;
  1514. }
  1515. // Get some size facts about the dividend and divisor
  1516. unsigned lhsWords = getNumWords(LHS.getActiveBits());
  1517. unsigned rhsBits = RHS.getActiveBits();
  1518. unsigned rhsWords = getNumWords(rhsBits);
  1519. assert(rhsWords && "Performing divrem operation by zero ???");
  1520. // Check the degenerate cases
  1521. if (lhsWords == 0) {
  1522. Quotient = APInt(BitWidth, 0); // 0 / Y ===> 0
  1523. Remainder = APInt(BitWidth, 0); // 0 % Y ===> 0
  1524. return;
  1525. }
  1526. if (rhsBits == 1) {
  1527. Quotient = LHS; // X / 1 ===> X
  1528. Remainder = APInt(BitWidth, 0); // X % 1 ===> 0
  1529. }
  1530. if (lhsWords < rhsWords || LHS.ult(RHS)) {
  1531. Remainder = LHS; // X % Y ===> X, iff X < Y
  1532. Quotient = APInt(BitWidth, 0); // X / Y ===> 0, iff X < Y
  1533. return;
  1534. }
  1535. if (LHS == RHS) {
  1536. Quotient = APInt(BitWidth, 1); // X / X ===> 1
  1537. Remainder = APInt(BitWidth, 0); // X % X ===> 0;
  1538. return;
  1539. }
  1540. // Make sure there is enough space to hold the results.
  1541. // NOTE: This assumes that reallocate won't affect any bits if it doesn't
  1542. // change the size. This is necessary if Quotient or Remainder is aliased
  1543. // with LHS or RHS.
  1544. Quotient.reallocate(BitWidth);
  1545. Remainder.reallocate(BitWidth);
  1546. if (lhsWords == 1) { // rhsWords is 1 if lhsWords is 1.
  1547. // There is only one word to consider so use the native versions.
  1548. uint64_t lhsValue = LHS.U.pVal[0];
  1549. uint64_t rhsValue = RHS.U.pVal[0];
  1550. Quotient = lhsValue / rhsValue;
  1551. Remainder = lhsValue % rhsValue;
  1552. return;
  1553. }
  1554. // Okay, lets do it the long way
  1555. divide(LHS.U.pVal, lhsWords, RHS.U.pVal, rhsWords, Quotient.U.pVal,
  1556. Remainder.U.pVal);
  1557. // Clear the rest of the Quotient and Remainder.
  1558. std::memset(Quotient.U.pVal + lhsWords, 0,
  1559. (getNumWords(BitWidth) - lhsWords) * APINT_WORD_SIZE);
  1560. std::memset(Remainder.U.pVal + rhsWords, 0,
  1561. (getNumWords(BitWidth) - rhsWords) * APINT_WORD_SIZE);
  1562. }
  1563. void APInt::udivrem(const APInt &LHS, uint64_t RHS, APInt &Quotient,
  1564. uint64_t &Remainder) {
  1565. assert(RHS != 0 && "Divide by zero?");
  1566. unsigned BitWidth = LHS.BitWidth;
  1567. // First, deal with the easy case
  1568. if (LHS.isSingleWord()) {
  1569. uint64_t QuotVal = LHS.U.VAL / RHS;
  1570. Remainder = LHS.U.VAL % RHS;
  1571. Quotient = APInt(BitWidth, QuotVal);
  1572. return;
  1573. }
  1574. // Get some size facts about the dividend and divisor
  1575. unsigned lhsWords = getNumWords(LHS.getActiveBits());
  1576. // Check the degenerate cases
  1577. if (lhsWords == 0) {
  1578. Quotient = APInt(BitWidth, 0); // 0 / Y ===> 0
  1579. Remainder = 0; // 0 % Y ===> 0
  1580. return;
  1581. }
  1582. if (RHS == 1) {
  1583. Quotient = LHS; // X / 1 ===> X
  1584. Remainder = 0; // X % 1 ===> 0
  1585. return;
  1586. }
  1587. if (LHS.ult(RHS)) {
  1588. Remainder = LHS.getZExtValue(); // X % Y ===> X, iff X < Y
  1589. Quotient = APInt(BitWidth, 0); // X / Y ===> 0, iff X < Y
  1590. return;
  1591. }
  1592. if (LHS == RHS) {
  1593. Quotient = APInt(BitWidth, 1); // X / X ===> 1
  1594. Remainder = 0; // X % X ===> 0;
  1595. return;
  1596. }
  1597. // Make sure there is enough space to hold the results.
  1598. // NOTE: This assumes that reallocate won't affect any bits if it doesn't
  1599. // change the size. This is necessary if Quotient is aliased with LHS.
  1600. Quotient.reallocate(BitWidth);
  1601. if (lhsWords == 1) { // rhsWords is 1 if lhsWords is 1.
  1602. // There is only one word to consider so use the native versions.
  1603. uint64_t lhsValue = LHS.U.pVal[0];
  1604. Quotient = lhsValue / RHS;
  1605. Remainder = lhsValue % RHS;
  1606. return;
  1607. }
  1608. // Okay, lets do it the long way
  1609. divide(LHS.U.pVal, lhsWords, &RHS, 1, Quotient.U.pVal, &Remainder);
  1610. // Clear the rest of the Quotient.
  1611. std::memset(Quotient.U.pVal + lhsWords, 0,
  1612. (getNumWords(BitWidth) - lhsWords) * APINT_WORD_SIZE);
  1613. }
  1614. void APInt::sdivrem(const APInt &LHS, const APInt &RHS,
  1615. APInt &Quotient, APInt &Remainder) {
  1616. if (LHS.isNegative()) {
  1617. if (RHS.isNegative())
  1618. APInt::udivrem(-LHS, -RHS, Quotient, Remainder);
  1619. else {
  1620. APInt::udivrem(-LHS, RHS, Quotient, Remainder);
  1621. Quotient.negate();
  1622. }
  1623. Remainder.negate();
  1624. } else if (RHS.isNegative()) {
  1625. APInt::udivrem(LHS, -RHS, Quotient, Remainder);
  1626. Quotient.negate();
  1627. } else {
  1628. APInt::udivrem(LHS, RHS, Quotient, Remainder);
  1629. }
  1630. }
  1631. void APInt::sdivrem(const APInt &LHS, int64_t RHS,
  1632. APInt &Quotient, int64_t &Remainder) {
  1633. uint64_t R = Remainder;
  1634. if (LHS.isNegative()) {
  1635. if (RHS < 0)
  1636. APInt::udivrem(-LHS, -RHS, Quotient, R);
  1637. else {
  1638. APInt::udivrem(-LHS, RHS, Quotient, R);
  1639. Quotient.negate();
  1640. }
  1641. R = -R;
  1642. } else if (RHS < 0) {
  1643. APInt::udivrem(LHS, -RHS, Quotient, R);
  1644. Quotient.negate();
  1645. } else {
  1646. APInt::udivrem(LHS, RHS, Quotient, R);
  1647. }
  1648. Remainder = R;
  1649. }
  1650. APInt APInt::sadd_ov(const APInt &RHS, bool &Overflow) const {
  1651. APInt Res = *this+RHS;
  1652. Overflow = isNonNegative() == RHS.isNonNegative() &&
  1653. Res.isNonNegative() != isNonNegative();
  1654. return Res;
  1655. }
  1656. APInt APInt::uadd_ov(const APInt &RHS, bool &Overflow) const {
  1657. APInt Res = *this+RHS;
  1658. Overflow = Res.ult(RHS);
  1659. return Res;
  1660. }
  1661. APInt APInt::ssub_ov(const APInt &RHS, bool &Overflow) const {
  1662. APInt Res = *this - RHS;
  1663. Overflow = isNonNegative() != RHS.isNonNegative() &&
  1664. Res.isNonNegative() != isNonNegative();
  1665. return Res;
  1666. }
  1667. APInt APInt::usub_ov(const APInt &RHS, bool &Overflow) const {
  1668. APInt Res = *this-RHS;
  1669. Overflow = Res.ugt(*this);
  1670. return Res;
  1671. }
  1672. APInt APInt::sdiv_ov(const APInt &RHS, bool &Overflow) const {
  1673. // MININT/-1 --> overflow.
  1674. Overflow = isMinSignedValue() && RHS.isAllOnes();
  1675. return sdiv(RHS);
  1676. }
  1677. APInt APInt::smul_ov(const APInt &RHS, bool &Overflow) const {
  1678. APInt Res = *this * RHS;
  1679. if (RHS != 0)
  1680. Overflow = Res.sdiv(RHS) != *this ||
  1681. (isMinSignedValue() && RHS.isAllOnes());
  1682. else
  1683. Overflow = false;
  1684. return Res;
  1685. }
  1686. APInt APInt::umul_ov(const APInt &RHS, bool &Overflow) const {
  1687. if (countLeadingZeros() + RHS.countLeadingZeros() + 2 <= BitWidth) {
  1688. Overflow = true;
  1689. return *this * RHS;
  1690. }
  1691. APInt Res = lshr(1) * RHS;
  1692. Overflow = Res.isNegative();
  1693. Res <<= 1;
  1694. if ((*this)[0]) {
  1695. Res += RHS;
  1696. if (Res.ult(RHS))
  1697. Overflow = true;
  1698. }
  1699. return Res;
  1700. }
  1701. APInt APInt::sshl_ov(const APInt &ShAmt, bool &Overflow) const {
  1702. Overflow = ShAmt.uge(getBitWidth());
  1703. if (Overflow)
  1704. return APInt(BitWidth, 0);
  1705. if (isNonNegative()) // Don't allow sign change.
  1706. Overflow = ShAmt.uge(countLeadingZeros());
  1707. else
  1708. Overflow = ShAmt.uge(countLeadingOnes());
  1709. return *this << ShAmt;
  1710. }
  1711. APInt APInt::ushl_ov(const APInt &ShAmt, bool &Overflow) const {
  1712. Overflow = ShAmt.uge(getBitWidth());
  1713. if (Overflow)
  1714. return APInt(BitWidth, 0);
  1715. Overflow = ShAmt.ugt(countLeadingZeros());
  1716. return *this << ShAmt;
  1717. }
  1718. APInt APInt::sadd_sat(const APInt &RHS) const {
  1719. bool Overflow;
  1720. APInt Res = sadd_ov(RHS, Overflow);
  1721. if (!Overflow)
  1722. return Res;
  1723. return isNegative() ? APInt::getSignedMinValue(BitWidth)
  1724. : APInt::getSignedMaxValue(BitWidth);
  1725. }
  1726. APInt APInt::uadd_sat(const APInt &RHS) const {
  1727. bool Overflow;
  1728. APInt Res = uadd_ov(RHS, Overflow);
  1729. if (!Overflow)
  1730. return Res;
  1731. return APInt::getMaxValue(BitWidth);
  1732. }
  1733. APInt APInt::ssub_sat(const APInt &RHS) const {
  1734. bool Overflow;
  1735. APInt Res = ssub_ov(RHS, Overflow);
  1736. if (!Overflow)
  1737. return Res;
  1738. return isNegative() ? APInt::getSignedMinValue(BitWidth)
  1739. : APInt::getSignedMaxValue(BitWidth);
  1740. }
  1741. APInt APInt::usub_sat(const APInt &RHS) const {
  1742. bool Overflow;
  1743. APInt Res = usub_ov(RHS, Overflow);
  1744. if (!Overflow)
  1745. return Res;
  1746. return APInt(BitWidth, 0);
  1747. }
  1748. APInt APInt::smul_sat(const APInt &RHS) const {
  1749. bool Overflow;
  1750. APInt Res = smul_ov(RHS, Overflow);
  1751. if (!Overflow)
  1752. return Res;
  1753. // The result is negative if one and only one of inputs is negative.
  1754. bool ResIsNegative = isNegative() ^ RHS.isNegative();
  1755. return ResIsNegative ? APInt::getSignedMinValue(BitWidth)
  1756. : APInt::getSignedMaxValue(BitWidth);
  1757. }
  1758. APInt APInt::umul_sat(const APInt &RHS) const {
  1759. bool Overflow;
  1760. APInt Res = umul_ov(RHS, Overflow);
  1761. if (!Overflow)
  1762. return Res;
  1763. return APInt::getMaxValue(BitWidth);
  1764. }
  1765. APInt APInt::sshl_sat(const APInt &RHS) const {
  1766. bool Overflow;
  1767. APInt Res = sshl_ov(RHS, Overflow);
  1768. if (!Overflow)
  1769. return Res;
  1770. return isNegative() ? APInt::getSignedMinValue(BitWidth)
  1771. : APInt::getSignedMaxValue(BitWidth);
  1772. }
  1773. APInt APInt::ushl_sat(const APInt &RHS) const {
  1774. bool Overflow;
  1775. APInt Res = ushl_ov(RHS, Overflow);
  1776. if (!Overflow)
  1777. return Res;
  1778. return APInt::getMaxValue(BitWidth);
  1779. }
  1780. void APInt::fromString(unsigned numbits, StringRef str, uint8_t radix) {
  1781. // Check our assumptions here
  1782. assert(!str.empty() && "Invalid string length");
  1783. assert((radix == 10 || radix == 8 || radix == 16 || radix == 2 ||
  1784. radix == 36) &&
  1785. "Radix should be 2, 8, 10, 16, or 36!");
  1786. StringRef::iterator p = str.begin();
  1787. size_t slen = str.size();
  1788. bool isNeg = *p == '-';
  1789. if (*p == '-' || *p == '+') {
  1790. p++;
  1791. slen--;
  1792. assert(slen && "String is only a sign, needs a value.");
  1793. }
  1794. assert((slen <= numbits || radix != 2) && "Insufficient bit width");
  1795. assert(((slen-1)*3 <= numbits || radix != 8) && "Insufficient bit width");
  1796. assert(((slen-1)*4 <= numbits || radix != 16) && "Insufficient bit width");
  1797. assert((((slen-1)*64)/22 <= numbits || radix != 10) &&
  1798. "Insufficient bit width");
  1799. // Allocate memory if needed
  1800. if (isSingleWord())
  1801. U.VAL = 0;
  1802. else
  1803. U.pVal = getClearedMemory(getNumWords());
  1804. // Figure out if we can shift instead of multiply
  1805. unsigned shift = (radix == 16 ? 4 : radix == 8 ? 3 : radix == 2 ? 1 : 0);
  1806. // Enter digit traversal loop
  1807. for (StringRef::iterator e = str.end(); p != e; ++p) {
  1808. unsigned digit = getDigit(*p, radix);
  1809. assert(digit < radix && "Invalid character in digit string");
  1810. // Shift or multiply the value by the radix
  1811. if (slen > 1) {
  1812. if (shift)
  1813. *this <<= shift;
  1814. else
  1815. *this *= radix;
  1816. }
  1817. // Add in the digit we just interpreted
  1818. *this += digit;
  1819. }
  1820. // If its negative, put it in two's complement form
  1821. if (isNeg)
  1822. this->negate();
  1823. }
  1824. void APInt::toString(SmallVectorImpl<char> &Str, unsigned Radix,
  1825. bool Signed, bool formatAsCLiteral) const {
  1826. assert((Radix == 10 || Radix == 8 || Radix == 16 || Radix == 2 ||
  1827. Radix == 36) &&
  1828. "Radix should be 2, 8, 10, 16, or 36!");
  1829. const char *Prefix = "";
  1830. if (formatAsCLiteral) {
  1831. switch (Radix) {
  1832. case 2:
  1833. // Binary literals are a non-standard extension added in gcc 4.3:
  1834. // http://gcc.gnu.org/onlinedocs/gcc-4.3.0/gcc/Binary-constants.html
  1835. Prefix = "0b";
  1836. break;
  1837. case 8:
  1838. Prefix = "0";
  1839. break;
  1840. case 10:
  1841. break; // No prefix
  1842. case 16:
  1843. Prefix = "0x";
  1844. break;
  1845. default:
  1846. llvm_unreachable("Invalid radix!");
  1847. }
  1848. }
  1849. // First, check for a zero value and just short circuit the logic below.
  1850. if (isZero()) {
  1851. while (*Prefix) {
  1852. Str.push_back(*Prefix);
  1853. ++Prefix;
  1854. };
  1855. Str.push_back('0');
  1856. return;
  1857. }
  1858. static const char Digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  1859. if (isSingleWord()) {
  1860. char Buffer[65];
  1861. char *BufPtr = std::end(Buffer);
  1862. uint64_t N;
  1863. if (!Signed) {
  1864. N = getZExtValue();
  1865. } else {
  1866. int64_t I = getSExtValue();
  1867. if (I >= 0) {
  1868. N = I;
  1869. } else {
  1870. Str.push_back('-');
  1871. N = -(uint64_t)I;
  1872. }
  1873. }
  1874. while (*Prefix) {
  1875. Str.push_back(*Prefix);
  1876. ++Prefix;
  1877. };
  1878. while (N) {
  1879. *--BufPtr = Digits[N % Radix];
  1880. N /= Radix;
  1881. }
  1882. Str.append(BufPtr, std::end(Buffer));
  1883. return;
  1884. }
  1885. APInt Tmp(*this);
  1886. if (Signed && isNegative()) {
  1887. // They want to print the signed version and it is a negative value
  1888. // Flip the bits and add one to turn it into the equivalent positive
  1889. // value and put a '-' in the result.
  1890. Tmp.negate();
  1891. Str.push_back('-');
  1892. }
  1893. while (*Prefix) {
  1894. Str.push_back(*Prefix);
  1895. ++Prefix;
  1896. };
  1897. // We insert the digits backward, then reverse them to get the right order.
  1898. unsigned StartDig = Str.size();
  1899. // For the 2, 8 and 16 bit cases, we can just shift instead of divide
  1900. // because the number of bits per digit (1, 3 and 4 respectively) divides
  1901. // equally. We just shift until the value is zero.
  1902. if (Radix == 2 || Radix == 8 || Radix == 16) {
  1903. // Just shift tmp right for each digit width until it becomes zero
  1904. unsigned ShiftAmt = (Radix == 16 ? 4 : (Radix == 8 ? 3 : 1));
  1905. unsigned MaskAmt = Radix - 1;
  1906. while (Tmp.getBoolValue()) {
  1907. unsigned Digit = unsigned(Tmp.getRawData()[0]) & MaskAmt;
  1908. Str.push_back(Digits[Digit]);
  1909. Tmp.lshrInPlace(ShiftAmt);
  1910. }
  1911. } else {
  1912. while (Tmp.getBoolValue()) {
  1913. uint64_t Digit;
  1914. udivrem(Tmp, Radix, Tmp, Digit);
  1915. assert(Digit < Radix && "divide failed");
  1916. Str.push_back(Digits[Digit]);
  1917. }
  1918. }
  1919. // Reverse the digits before returning.
  1920. std::reverse(Str.begin()+StartDig, Str.end());
  1921. }
  1922. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  1923. LLVM_DUMP_METHOD void APInt::dump() const {
  1924. SmallString<40> S, U;
  1925. this->toStringUnsigned(U);
  1926. this->toStringSigned(S);
  1927. dbgs() << "APInt(" << BitWidth << "b, "
  1928. << U << "u " << S << "s)\n";
  1929. }
  1930. #endif
  1931. void APInt::print(raw_ostream &OS, bool isSigned) const {
  1932. SmallString<40> S;
  1933. this->toString(S, 10, isSigned, /* formatAsCLiteral = */false);
  1934. OS << S;
  1935. }
  1936. // This implements a variety of operations on a representation of
  1937. // arbitrary precision, two's-complement, bignum integer values.
  1938. // Assumed by lowHalf, highHalf, partMSB and partLSB. A fairly safe
  1939. // and unrestricting assumption.
  1940. static_assert(APInt::APINT_BITS_PER_WORD % 2 == 0,
  1941. "Part width must be divisible by 2!");
  1942. // Returns the integer part with the least significant BITS set.
  1943. // BITS cannot be zero.
  1944. static inline APInt::WordType lowBitMask(unsigned bits) {
  1945. assert(bits != 0 && bits <= APInt::APINT_BITS_PER_WORD);
  1946. return ~(APInt::WordType) 0 >> (APInt::APINT_BITS_PER_WORD - bits);
  1947. }
  1948. /// Returns the value of the lower half of PART.
  1949. static inline APInt::WordType lowHalf(APInt::WordType part) {
  1950. return part & lowBitMask(APInt::APINT_BITS_PER_WORD / 2);
  1951. }
  1952. /// Returns the value of the upper half of PART.
  1953. static inline APInt::WordType highHalf(APInt::WordType part) {
  1954. return part >> (APInt::APINT_BITS_PER_WORD / 2);
  1955. }
  1956. /// Returns the bit number of the most significant set bit of a part.
  1957. /// If the input number has no bits set -1U is returned.
  1958. static unsigned partMSB(APInt::WordType value) {
  1959. return findLastSet(value, ZB_Max);
  1960. }
  1961. /// Returns the bit number of the least significant set bit of a part. If the
  1962. /// input number has no bits set -1U is returned.
  1963. static unsigned partLSB(APInt::WordType value) {
  1964. return findFirstSet(value, ZB_Max);
  1965. }
  1966. /// Sets the least significant part of a bignum to the input value, and zeroes
  1967. /// out higher parts.
  1968. void APInt::tcSet(WordType *dst, WordType part, unsigned parts) {
  1969. assert(parts > 0);
  1970. dst[0] = part;
  1971. for (unsigned i = 1; i < parts; i++)
  1972. dst[i] = 0;
  1973. }
  1974. /// Assign one bignum to another.
  1975. void APInt::tcAssign(WordType *dst, const WordType *src, unsigned parts) {
  1976. for (unsigned i = 0; i < parts; i++)
  1977. dst[i] = src[i];
  1978. }
  1979. /// Returns true if a bignum is zero, false otherwise.
  1980. bool APInt::tcIsZero(const WordType *src, unsigned parts) {
  1981. for (unsigned i = 0; i < parts; i++)
  1982. if (src[i])
  1983. return false;
  1984. return true;
  1985. }
  1986. /// Extract the given bit of a bignum; returns 0 or 1.
  1987. int APInt::tcExtractBit(const WordType *parts, unsigned bit) {
  1988. return (parts[whichWord(bit)] & maskBit(bit)) != 0;
  1989. }
  1990. /// Set the given bit of a bignum.
  1991. void APInt::tcSetBit(WordType *parts, unsigned bit) {
  1992. parts[whichWord(bit)] |= maskBit(bit);
  1993. }
  1994. /// Clears the given bit of a bignum.
  1995. void APInt::tcClearBit(WordType *parts, unsigned bit) {
  1996. parts[whichWord(bit)] &= ~maskBit(bit);
  1997. }
  1998. /// Returns the bit number of the least significant set bit of a number. If the
  1999. /// input number has no bits set -1U is returned.
  2000. unsigned APInt::tcLSB(const WordType *parts, unsigned n) {
  2001. for (unsigned i = 0; i < n; i++) {
  2002. if (parts[i] != 0) {
  2003. unsigned lsb = partLSB(parts[i]);
  2004. return lsb + i * APINT_BITS_PER_WORD;
  2005. }
  2006. }
  2007. return -1U;
  2008. }
  2009. /// Returns the bit number of the most significant set bit of a number.
  2010. /// If the input number has no bits set -1U is returned.
  2011. unsigned APInt::tcMSB(const WordType *parts, unsigned n) {
  2012. do {
  2013. --n;
  2014. if (parts[n] != 0) {
  2015. unsigned msb = partMSB(parts[n]);
  2016. return msb + n * APINT_BITS_PER_WORD;
  2017. }
  2018. } while (n);
  2019. return -1U;
  2020. }
  2021. /// Copy the bit vector of width srcBITS from SRC, starting at bit srcLSB, to
  2022. /// DST, of dstCOUNT parts, such that the bit srcLSB becomes the least
  2023. /// significant bit of DST. All high bits above srcBITS in DST are zero-filled.
  2024. /// */
  2025. void
  2026. APInt::tcExtract(WordType *dst, unsigned dstCount, const WordType *src,
  2027. unsigned srcBits, unsigned srcLSB) {
  2028. unsigned dstParts = (srcBits + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD;
  2029. assert(dstParts <= dstCount);
  2030. unsigned firstSrcPart = srcLSB / APINT_BITS_PER_WORD;
  2031. tcAssign(dst, src + firstSrcPart, dstParts);
  2032. unsigned shift = srcLSB % APINT_BITS_PER_WORD;
  2033. tcShiftRight(dst, dstParts, shift);
  2034. // We now have (dstParts * APINT_BITS_PER_WORD - shift) bits from SRC
  2035. // in DST. If this is less that srcBits, append the rest, else
  2036. // clear the high bits.
  2037. unsigned n = dstParts * APINT_BITS_PER_WORD - shift;
  2038. if (n < srcBits) {
  2039. WordType mask = lowBitMask (srcBits - n);
  2040. dst[dstParts - 1] |= ((src[firstSrcPart + dstParts] & mask)
  2041. << n % APINT_BITS_PER_WORD);
  2042. } else if (n > srcBits) {
  2043. if (srcBits % APINT_BITS_PER_WORD)
  2044. dst[dstParts - 1] &= lowBitMask (srcBits % APINT_BITS_PER_WORD);
  2045. }
  2046. // Clear high parts.
  2047. while (dstParts < dstCount)
  2048. dst[dstParts++] = 0;
  2049. }
  2050. //// DST += RHS + C where C is zero or one. Returns the carry flag.
  2051. APInt::WordType APInt::tcAdd(WordType *dst, const WordType *rhs,
  2052. WordType c, unsigned parts) {
  2053. assert(c <= 1);
  2054. for (unsigned i = 0; i < parts; i++) {
  2055. WordType l = dst[i];
  2056. if (c) {
  2057. dst[i] += rhs[i] + 1;
  2058. c = (dst[i] <= l);
  2059. } else {
  2060. dst[i] += rhs[i];
  2061. c = (dst[i] < l);
  2062. }
  2063. }
  2064. return c;
  2065. }
  2066. /// This function adds a single "word" integer, src, to the multiple
  2067. /// "word" integer array, dst[]. dst[] is modified to reflect the addition and
  2068. /// 1 is returned if there is a carry out, otherwise 0 is returned.
  2069. /// @returns the carry of the addition.
  2070. APInt::WordType APInt::tcAddPart(WordType *dst, WordType src,
  2071. unsigned parts) {
  2072. for (unsigned i = 0; i < parts; ++i) {
  2073. dst[i] += src;
  2074. if (dst[i] >= src)
  2075. return 0; // No need to carry so exit early.
  2076. src = 1; // Carry one to next digit.
  2077. }
  2078. return 1;
  2079. }
  2080. /// DST -= RHS + C where C is zero or one. Returns the carry flag.
  2081. APInt::WordType APInt::tcSubtract(WordType *dst, const WordType *rhs,
  2082. WordType c, unsigned parts) {
  2083. assert(c <= 1);
  2084. for (unsigned i = 0; i < parts; i++) {
  2085. WordType l = dst[i];
  2086. if (c) {
  2087. dst[i] -= rhs[i] + 1;
  2088. c = (dst[i] >= l);
  2089. } else {
  2090. dst[i] -= rhs[i];
  2091. c = (dst[i] > l);
  2092. }
  2093. }
  2094. return c;
  2095. }
  2096. /// This function subtracts a single "word" (64-bit word), src, from
  2097. /// the multi-word integer array, dst[], propagating the borrowed 1 value until
  2098. /// no further borrowing is needed or it runs out of "words" in dst. The result
  2099. /// is 1 if "borrowing" exhausted the digits in dst, or 0 if dst was not
  2100. /// exhausted. In other words, if src > dst then this function returns 1,
  2101. /// otherwise 0.
  2102. /// @returns the borrow out of the subtraction
  2103. APInt::WordType APInt::tcSubtractPart(WordType *dst, WordType src,
  2104. unsigned parts) {
  2105. for (unsigned i = 0; i < parts; ++i) {
  2106. WordType Dst = dst[i];
  2107. dst[i] -= src;
  2108. if (src <= Dst)
  2109. return 0; // No need to borrow so exit early.
  2110. src = 1; // We have to "borrow 1" from next "word"
  2111. }
  2112. return 1;
  2113. }
  2114. /// Negate a bignum in-place.
  2115. void APInt::tcNegate(WordType *dst, unsigned parts) {
  2116. tcComplement(dst, parts);
  2117. tcIncrement(dst, parts);
  2118. }
  2119. /// DST += SRC * MULTIPLIER + CARRY if add is true
  2120. /// DST = SRC * MULTIPLIER + CARRY if add is false
  2121. /// Requires 0 <= DSTPARTS <= SRCPARTS + 1. If DST overlaps SRC
  2122. /// they must start at the same point, i.e. DST == SRC.
  2123. /// If DSTPARTS == SRCPARTS + 1 no overflow occurs and zero is
  2124. /// returned. Otherwise DST is filled with the least significant
  2125. /// DSTPARTS parts of the result, and if all of the omitted higher
  2126. /// parts were zero return zero, otherwise overflow occurred and
  2127. /// return one.
  2128. int APInt::tcMultiplyPart(WordType *dst, const WordType *src,
  2129. WordType multiplier, WordType carry,
  2130. unsigned srcParts, unsigned dstParts,
  2131. bool add) {
  2132. // Otherwise our writes of DST kill our later reads of SRC.
  2133. assert(dst <= src || dst >= src + srcParts);
  2134. assert(dstParts <= srcParts + 1);
  2135. // N loops; minimum of dstParts and srcParts.
  2136. unsigned n = std::min(dstParts, srcParts);
  2137. for (unsigned i = 0; i < n; i++) {
  2138. // [LOW, HIGH] = MULTIPLIER * SRC[i] + DST[i] + CARRY.
  2139. // This cannot overflow, because:
  2140. // (n - 1) * (n - 1) + 2 (n - 1) = (n - 1) * (n + 1)
  2141. // which is less than n^2.
  2142. WordType srcPart = src[i];
  2143. WordType low, mid, high;
  2144. if (multiplier == 0 || srcPart == 0) {
  2145. low = carry;
  2146. high = 0;
  2147. } else {
  2148. low = lowHalf(srcPart) * lowHalf(multiplier);
  2149. high = highHalf(srcPart) * highHalf(multiplier);
  2150. mid = lowHalf(srcPart) * highHalf(multiplier);
  2151. high += highHalf(mid);
  2152. mid <<= APINT_BITS_PER_WORD / 2;
  2153. if (low + mid < low)
  2154. high++;
  2155. low += mid;
  2156. mid = highHalf(srcPart) * lowHalf(multiplier);
  2157. high += highHalf(mid);
  2158. mid <<= APINT_BITS_PER_WORD / 2;
  2159. if (low + mid < low)
  2160. high++;
  2161. low += mid;
  2162. // Now add carry.
  2163. if (low + carry < low)
  2164. high++;
  2165. low += carry;
  2166. }
  2167. if (add) {
  2168. // And now DST[i], and store the new low part there.
  2169. if (low + dst[i] < low)
  2170. high++;
  2171. dst[i] += low;
  2172. } else
  2173. dst[i] = low;
  2174. carry = high;
  2175. }
  2176. if (srcParts < dstParts) {
  2177. // Full multiplication, there is no overflow.
  2178. assert(srcParts + 1 == dstParts);
  2179. dst[srcParts] = carry;
  2180. return 0;
  2181. }
  2182. // We overflowed if there is carry.
  2183. if (carry)
  2184. return 1;
  2185. // We would overflow if any significant unwritten parts would be
  2186. // non-zero. This is true if any remaining src parts are non-zero
  2187. // and the multiplier is non-zero.
  2188. if (multiplier)
  2189. for (unsigned i = dstParts; i < srcParts; i++)
  2190. if (src[i])
  2191. return 1;
  2192. // We fitted in the narrow destination.
  2193. return 0;
  2194. }
  2195. /// DST = LHS * RHS, where DST has the same width as the operands and
  2196. /// is filled with the least significant parts of the result. Returns
  2197. /// one if overflow occurred, otherwise zero. DST must be disjoint
  2198. /// from both operands.
  2199. int APInt::tcMultiply(WordType *dst, const WordType *lhs,
  2200. const WordType *rhs, unsigned parts) {
  2201. assert(dst != lhs && dst != rhs);
  2202. int overflow = 0;
  2203. tcSet(dst, 0, parts);
  2204. for (unsigned i = 0; i < parts; i++)
  2205. overflow |= tcMultiplyPart(&dst[i], lhs, rhs[i], 0, parts,
  2206. parts - i, true);
  2207. return overflow;
  2208. }
  2209. /// DST = LHS * RHS, where DST has width the sum of the widths of the
  2210. /// operands. No overflow occurs. DST must be disjoint from both operands.
  2211. void APInt::tcFullMultiply(WordType *dst, const WordType *lhs,
  2212. const WordType *rhs, unsigned lhsParts,
  2213. unsigned rhsParts) {
  2214. // Put the narrower number on the LHS for less loops below.
  2215. if (lhsParts > rhsParts)
  2216. return tcFullMultiply (dst, rhs, lhs, rhsParts, lhsParts);
  2217. assert(dst != lhs && dst != rhs);
  2218. tcSet(dst, 0, rhsParts);
  2219. for (unsigned i = 0; i < lhsParts; i++)
  2220. tcMultiplyPart(&dst[i], rhs, lhs[i], 0, rhsParts, rhsParts + 1, true);
  2221. }
  2222. // If RHS is zero LHS and REMAINDER are left unchanged, return one.
  2223. // Otherwise set LHS to LHS / RHS with the fractional part discarded,
  2224. // set REMAINDER to the remainder, return zero. i.e.
  2225. //
  2226. // OLD_LHS = RHS * LHS + REMAINDER
  2227. //
  2228. // SCRATCH is a bignum of the same size as the operands and result for
  2229. // use by the routine; its contents need not be initialized and are
  2230. // destroyed. LHS, REMAINDER and SCRATCH must be distinct.
  2231. int APInt::tcDivide(WordType *lhs, const WordType *rhs,
  2232. WordType *remainder, WordType *srhs,
  2233. unsigned parts) {
  2234. assert(lhs != remainder && lhs != srhs && remainder != srhs);
  2235. unsigned shiftCount = tcMSB(rhs, parts) + 1;
  2236. if (shiftCount == 0)
  2237. return true;
  2238. shiftCount = parts * APINT_BITS_PER_WORD - shiftCount;
  2239. unsigned n = shiftCount / APINT_BITS_PER_WORD;
  2240. WordType mask = (WordType) 1 << (shiftCount % APINT_BITS_PER_WORD);
  2241. tcAssign(srhs, rhs, parts);
  2242. tcShiftLeft(srhs, parts, shiftCount);
  2243. tcAssign(remainder, lhs, parts);
  2244. tcSet(lhs, 0, parts);
  2245. // Loop, subtracting SRHS if REMAINDER is greater and adding that to the
  2246. // total.
  2247. for (;;) {
  2248. int compare = tcCompare(remainder, srhs, parts);
  2249. if (compare >= 0) {
  2250. tcSubtract(remainder, srhs, 0, parts);
  2251. lhs[n] |= mask;
  2252. }
  2253. if (shiftCount == 0)
  2254. break;
  2255. shiftCount--;
  2256. tcShiftRight(srhs, parts, 1);
  2257. if ((mask >>= 1) == 0) {
  2258. mask = (WordType) 1 << (APINT_BITS_PER_WORD - 1);
  2259. n--;
  2260. }
  2261. }
  2262. return false;
  2263. }
  2264. /// Shift a bignum left Cound bits in-place. Shifted in bits are zero. There are
  2265. /// no restrictions on Count.
  2266. void APInt::tcShiftLeft(WordType *Dst, unsigned Words, unsigned Count) {
  2267. // Don't bother performing a no-op shift.
  2268. if (!Count)
  2269. return;
  2270. // WordShift is the inter-part shift; BitShift is the intra-part shift.
  2271. unsigned WordShift = std::min(Count / APINT_BITS_PER_WORD, Words);
  2272. unsigned BitShift = Count % APINT_BITS_PER_WORD;
  2273. // Fastpath for moving by whole words.
  2274. if (BitShift == 0) {
  2275. std::memmove(Dst + WordShift, Dst, (Words - WordShift) * APINT_WORD_SIZE);
  2276. } else {
  2277. while (Words-- > WordShift) {
  2278. Dst[Words] = Dst[Words - WordShift] << BitShift;
  2279. if (Words > WordShift)
  2280. Dst[Words] |=
  2281. Dst[Words - WordShift - 1] >> (APINT_BITS_PER_WORD - BitShift);
  2282. }
  2283. }
  2284. // Fill in the remainder with 0s.
  2285. std::memset(Dst, 0, WordShift * APINT_WORD_SIZE);
  2286. }
  2287. /// Shift a bignum right Count bits in-place. Shifted in bits are zero. There
  2288. /// are no restrictions on Count.
  2289. void APInt::tcShiftRight(WordType *Dst, unsigned Words, unsigned Count) {
  2290. // Don't bother performing a no-op shift.
  2291. if (!Count)
  2292. return;
  2293. // WordShift is the inter-part shift; BitShift is the intra-part shift.
  2294. unsigned WordShift = std::min(Count / APINT_BITS_PER_WORD, Words);
  2295. unsigned BitShift = Count % APINT_BITS_PER_WORD;
  2296. unsigned WordsToMove = Words - WordShift;
  2297. // Fastpath for moving by whole words.
  2298. if (BitShift == 0) {
  2299. std::memmove(Dst, Dst + WordShift, WordsToMove * APINT_WORD_SIZE);
  2300. } else {
  2301. for (unsigned i = 0; i != WordsToMove; ++i) {
  2302. Dst[i] = Dst[i + WordShift] >> BitShift;
  2303. if (i + 1 != WordsToMove)
  2304. Dst[i] |= Dst[i + WordShift + 1] << (APINT_BITS_PER_WORD - BitShift);
  2305. }
  2306. }
  2307. // Fill in the remainder with 0s.
  2308. std::memset(Dst + WordsToMove, 0, WordShift * APINT_WORD_SIZE);
  2309. }
  2310. // Comparison (unsigned) of two bignums.
  2311. int APInt::tcCompare(const WordType *lhs, const WordType *rhs,
  2312. unsigned parts) {
  2313. while (parts) {
  2314. parts--;
  2315. if (lhs[parts] != rhs[parts])
  2316. return (lhs[parts] > rhs[parts]) ? 1 : -1;
  2317. }
  2318. return 0;
  2319. }
  2320. APInt llvm::APIntOps::RoundingUDiv(const APInt &A, const APInt &B,
  2321. APInt::Rounding RM) {
  2322. // Currently udivrem always rounds down.
  2323. switch (RM) {
  2324. case APInt::Rounding::DOWN:
  2325. case APInt::Rounding::TOWARD_ZERO:
  2326. return A.udiv(B);
  2327. case APInt::Rounding::UP: {
  2328. APInt Quo, Rem;
  2329. APInt::udivrem(A, B, Quo, Rem);
  2330. if (Rem.isZero())
  2331. return Quo;
  2332. return Quo + 1;
  2333. }
  2334. }
  2335. llvm_unreachable("Unknown APInt::Rounding enum");
  2336. }
  2337. APInt llvm::APIntOps::RoundingSDiv(const APInt &A, const APInt &B,
  2338. APInt::Rounding RM) {
  2339. switch (RM) {
  2340. case APInt::Rounding::DOWN:
  2341. case APInt::Rounding::UP: {
  2342. APInt Quo, Rem;
  2343. APInt::sdivrem(A, B, Quo, Rem);
  2344. if (Rem.isZero())
  2345. return Quo;
  2346. // This algorithm deals with arbitrary rounding mode used by sdivrem.
  2347. // We want to check whether the non-integer part of the mathematical value
  2348. // is negative or not. If the non-integer part is negative, we need to round
  2349. // down from Quo; otherwise, if it's positive or 0, we return Quo, as it's
  2350. // already rounded down.
  2351. if (RM == APInt::Rounding::DOWN) {
  2352. if (Rem.isNegative() != B.isNegative())
  2353. return Quo - 1;
  2354. return Quo;
  2355. }
  2356. if (Rem.isNegative() != B.isNegative())
  2357. return Quo;
  2358. return Quo + 1;
  2359. }
  2360. // Currently sdiv rounds towards zero.
  2361. case APInt::Rounding::TOWARD_ZERO:
  2362. return A.sdiv(B);
  2363. }
  2364. llvm_unreachable("Unknown APInt::Rounding enum");
  2365. }
  2366. Optional<APInt>
  2367. llvm::APIntOps::SolveQuadraticEquationWrap(APInt A, APInt B, APInt C,
  2368. unsigned RangeWidth) {
  2369. unsigned CoeffWidth = A.getBitWidth();
  2370. assert(CoeffWidth == B.getBitWidth() && CoeffWidth == C.getBitWidth());
  2371. assert(RangeWidth <= CoeffWidth &&
  2372. "Value range width should be less than coefficient width");
  2373. assert(RangeWidth > 1 && "Value range bit width should be > 1");
  2374. LLVM_DEBUG(dbgs() << __func__ << ": solving " << A << "x^2 + " << B
  2375. << "x + " << C << ", rw:" << RangeWidth << '\n');
  2376. // Identify 0 as a (non)solution immediately.
  2377. if (C.sextOrTrunc(RangeWidth).isZero()) {
  2378. LLVM_DEBUG(dbgs() << __func__ << ": zero solution\n");
  2379. return APInt(CoeffWidth, 0);
  2380. }
  2381. // The result of APInt arithmetic has the same bit width as the operands,
  2382. // so it can actually lose high bits. A product of two n-bit integers needs
  2383. // 2n-1 bits to represent the full value.
  2384. // The operation done below (on quadratic coefficients) that can produce
  2385. // the largest value is the evaluation of the equation during bisection,
  2386. // which needs 3 times the bitwidth of the coefficient, so the total number
  2387. // of required bits is 3n.
  2388. //
  2389. // The purpose of this extension is to simulate the set Z of all integers,
  2390. // where n+1 > n for all n in Z. In Z it makes sense to talk about positive
  2391. // and negative numbers (not so much in a modulo arithmetic). The method
  2392. // used to solve the equation is based on the standard formula for real
  2393. // numbers, and uses the concepts of "positive" and "negative" with their
  2394. // usual meanings.
  2395. CoeffWidth *= 3;
  2396. A = A.sext(CoeffWidth);
  2397. B = B.sext(CoeffWidth);
  2398. C = C.sext(CoeffWidth);
  2399. // Make A > 0 for simplicity. Negate cannot overflow at this point because
  2400. // the bit width has increased.
  2401. if (A.isNegative()) {
  2402. A.negate();
  2403. B.negate();
  2404. C.negate();
  2405. }
  2406. // Solving an equation q(x) = 0 with coefficients in modular arithmetic
  2407. // is really solving a set of equations q(x) = kR for k = 0, 1, 2, ...,
  2408. // and R = 2^BitWidth.
  2409. // Since we're trying not only to find exact solutions, but also values
  2410. // that "wrap around", such a set will always have a solution, i.e. an x
  2411. // that satisfies at least one of the equations, or such that |q(x)|
  2412. // exceeds kR, while |q(x-1)| for the same k does not.
  2413. //
  2414. // We need to find a value k, such that Ax^2 + Bx + C = kR will have a
  2415. // positive solution n (in the above sense), and also such that the n
  2416. // will be the least among all solutions corresponding to k = 0, 1, ...
  2417. // (more precisely, the least element in the set
  2418. // { n(k) | k is such that a solution n(k) exists }).
  2419. //
  2420. // Consider the parabola (over real numbers) that corresponds to the
  2421. // quadratic equation. Since A > 0, the arms of the parabola will point
  2422. // up. Picking different values of k will shift it up and down by R.
  2423. //
  2424. // We want to shift the parabola in such a way as to reduce the problem
  2425. // of solving q(x) = kR to solving shifted_q(x) = 0.
  2426. // (The interesting solutions are the ceilings of the real number
  2427. // solutions.)
  2428. APInt R = APInt::getOneBitSet(CoeffWidth, RangeWidth);
  2429. APInt TwoA = 2 * A;
  2430. APInt SqrB = B * B;
  2431. bool PickLow;
  2432. auto RoundUp = [] (const APInt &V, const APInt &A) -> APInt {
  2433. assert(A.isStrictlyPositive());
  2434. APInt T = V.abs().urem(A);
  2435. if (T.isZero())
  2436. return V;
  2437. return V.isNegative() ? V+T : V+(A-T);
  2438. };
  2439. // The vertex of the parabola is at -B/2A, but since A > 0, it's negative
  2440. // iff B is positive.
  2441. if (B.isNonNegative()) {
  2442. // If B >= 0, the vertex it at a negative location (or at 0), so in
  2443. // order to have a non-negative solution we need to pick k that makes
  2444. // C-kR negative. To satisfy all the requirements for the solution
  2445. // that we are looking for, it needs to be closest to 0 of all k.
  2446. C = C.srem(R);
  2447. if (C.isStrictlyPositive())
  2448. C -= R;
  2449. // Pick the greater solution.
  2450. PickLow = false;
  2451. } else {
  2452. // If B < 0, the vertex is at a positive location. For any solution
  2453. // to exist, the discriminant must be non-negative. This means that
  2454. // C-kR <= B^2/4A is a necessary condition for k, i.e. there is a
  2455. // lower bound on values of k: kR >= C - B^2/4A.
  2456. APInt LowkR = C - SqrB.udiv(2*TwoA); // udiv because all values > 0.
  2457. // Round LowkR up (towards +inf) to the nearest kR.
  2458. LowkR = RoundUp(LowkR, R);
  2459. // If there exists k meeting the condition above, and such that
  2460. // C-kR > 0, there will be two positive real number solutions of
  2461. // q(x) = kR. Out of all such values of k, pick the one that makes
  2462. // C-kR closest to 0, (i.e. pick maximum k such that C-kR > 0).
  2463. // In other words, find maximum k such that LowkR <= kR < C.
  2464. if (C.sgt(LowkR)) {
  2465. // If LowkR < C, then such a k is guaranteed to exist because
  2466. // LowkR itself is a multiple of R.
  2467. C -= -RoundUp(-C, R); // C = C - RoundDown(C, R)
  2468. // Pick the smaller solution.
  2469. PickLow = true;
  2470. } else {
  2471. // If C-kR < 0 for all potential k's, it means that one solution
  2472. // will be negative, while the other will be positive. The positive
  2473. // solution will shift towards 0 if the parabola is moved up.
  2474. // Pick the kR closest to the lower bound (i.e. make C-kR closest
  2475. // to 0, or in other words, out of all parabolas that have solutions,
  2476. // pick the one that is the farthest "up").
  2477. // Since LowkR is itself a multiple of R, simply take C-LowkR.
  2478. C -= LowkR;
  2479. // Pick the greater solution.
  2480. PickLow = false;
  2481. }
  2482. }
  2483. LLVM_DEBUG(dbgs() << __func__ << ": updated coefficients " << A << "x^2 + "
  2484. << B << "x + " << C << ", rw:" << RangeWidth << '\n');
  2485. APInt D = SqrB - 4*A*C;
  2486. assert(D.isNonNegative() && "Negative discriminant");
  2487. APInt SQ = D.sqrt();
  2488. APInt Q = SQ * SQ;
  2489. bool InexactSQ = Q != D;
  2490. // The calculated SQ may actually be greater than the exact (non-integer)
  2491. // value. If that's the case, decrement SQ to get a value that is lower.
  2492. if (Q.sgt(D))
  2493. SQ -= 1;
  2494. APInt X;
  2495. APInt Rem;
  2496. // SQ is rounded down (i.e SQ * SQ <= D), so the roots may be inexact.
  2497. // When using the quadratic formula directly, the calculated low root
  2498. // may be greater than the exact one, since we would be subtracting SQ.
  2499. // To make sure that the calculated root is not greater than the exact
  2500. // one, subtract SQ+1 when calculating the low root (for inexact value
  2501. // of SQ).
  2502. if (PickLow)
  2503. APInt::sdivrem(-B - (SQ+InexactSQ), TwoA, X, Rem);
  2504. else
  2505. APInt::sdivrem(-B + SQ, TwoA, X, Rem);
  2506. // The updated coefficients should be such that the (exact) solution is
  2507. // positive. Since APInt division rounds towards 0, the calculated one
  2508. // can be 0, but cannot be negative.
  2509. assert(X.isNonNegative() && "Solution should be non-negative");
  2510. if (!InexactSQ && Rem.isZero()) {
  2511. LLVM_DEBUG(dbgs() << __func__ << ": solution (root): " << X << '\n');
  2512. return X;
  2513. }
  2514. assert((SQ*SQ).sle(D) && "SQ = |_sqrt(D)_|, so SQ*SQ <= D");
  2515. // The exact value of the square root of D should be between SQ and SQ+1.
  2516. // This implies that the solution should be between that corresponding to
  2517. // SQ (i.e. X) and that corresponding to SQ+1.
  2518. //
  2519. // The calculated X cannot be greater than the exact (real) solution.
  2520. // Actually it must be strictly less than the exact solution, while
  2521. // X+1 will be greater than or equal to it.
  2522. APInt VX = (A*X + B)*X + C;
  2523. APInt VY = VX + TwoA*X + A + B;
  2524. bool SignChange =
  2525. VX.isNegative() != VY.isNegative() || VX.isZero() != VY.isZero();
  2526. // If the sign did not change between X and X+1, X is not a valid solution.
  2527. // This could happen when the actual (exact) roots don't have an integer
  2528. // between them, so they would both be contained between X and X+1.
  2529. if (!SignChange) {
  2530. LLVM_DEBUG(dbgs() << __func__ << ": no valid solution\n");
  2531. return None;
  2532. }
  2533. X += 1;
  2534. LLVM_DEBUG(dbgs() << __func__ << ": solution (wrap): " << X << '\n');
  2535. return X;
  2536. }
  2537. Optional<unsigned>
  2538. llvm::APIntOps::GetMostSignificantDifferentBit(const APInt &A, const APInt &B) {
  2539. assert(A.getBitWidth() == B.getBitWidth() && "Must have the same bitwidth");
  2540. if (A == B)
  2541. return llvm::None;
  2542. return A.getBitWidth() - ((A ^ B).countLeadingZeros() + 1);
  2543. }
  2544. APInt llvm::APIntOps::ScaleBitMask(const APInt &A, unsigned NewBitWidth) {
  2545. unsigned OldBitWidth = A.getBitWidth();
  2546. assert((((OldBitWidth % NewBitWidth) == 0) ||
  2547. ((NewBitWidth % OldBitWidth) == 0)) &&
  2548. "One size should be a multiple of the other one. "
  2549. "Can't do fractional scaling.");
  2550. // Check for matching bitwidths.
  2551. if (OldBitWidth == NewBitWidth)
  2552. return A;
  2553. APInt NewA = APInt::getZero(NewBitWidth);
  2554. // Check for null input.
  2555. if (A.isZero())
  2556. return NewA;
  2557. if (NewBitWidth > OldBitWidth) {
  2558. // Repeat bits.
  2559. unsigned Scale = NewBitWidth / OldBitWidth;
  2560. for (unsigned i = 0; i != OldBitWidth; ++i)
  2561. if (A[i])
  2562. NewA.setBits(i * Scale, (i + 1) * Scale);
  2563. } else {
  2564. // Merge bits - if any old bit is set, then set scale equivalent new bit.
  2565. unsigned Scale = OldBitWidth / NewBitWidth;
  2566. for (unsigned i = 0; i != NewBitWidth; ++i)
  2567. if (!A.extractBits(Scale, i * Scale).isZero())
  2568. NewA.setBit(i);
  2569. }
  2570. return NewA;
  2571. }
  2572. /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
  2573. /// with the integer held in IntVal.
  2574. void llvm::StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
  2575. unsigned StoreBytes) {
  2576. assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
  2577. const uint8_t *Src = (const uint8_t *)IntVal.getRawData();
  2578. if (sys::IsLittleEndianHost) {
  2579. // Little-endian host - the source is ordered from LSB to MSB. Order the
  2580. // destination from LSB to MSB: Do a straight copy.
  2581. memcpy(Dst, Src, StoreBytes);
  2582. } else {
  2583. // Big-endian host - the source is an array of 64 bit words ordered from
  2584. // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
  2585. // from MSB to LSB: Reverse the word order, but not the bytes in a word.
  2586. while (StoreBytes > sizeof(uint64_t)) {
  2587. StoreBytes -= sizeof(uint64_t);
  2588. // May not be aligned so use memcpy.
  2589. memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
  2590. Src += sizeof(uint64_t);
  2591. }
  2592. memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
  2593. }
  2594. }
  2595. /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
  2596. /// from Src into IntVal, which is assumed to be wide enough and to hold zero.
  2597. void llvm::LoadIntFromMemory(APInt &IntVal, const uint8_t *Src,
  2598. unsigned LoadBytes) {
  2599. assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
  2600. uint8_t *Dst = reinterpret_cast<uint8_t *>(
  2601. const_cast<uint64_t *>(IntVal.getRawData()));
  2602. if (sys::IsLittleEndianHost)
  2603. // Little-endian host - the destination must be ordered from LSB to MSB.
  2604. // The source is ordered from LSB to MSB: Do a straight copy.
  2605. memcpy(Dst, Src, LoadBytes);
  2606. else {
  2607. // Big-endian - the destination is an array of 64 bit words ordered from
  2608. // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
  2609. // ordered from MSB to LSB: Reverse the word order, but not the bytes in
  2610. // a word.
  2611. while (LoadBytes > sizeof(uint64_t)) {
  2612. LoadBytes -= sizeof(uint64_t);
  2613. // May not be aligned so use memcpy.
  2614. memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
  2615. Dst += sizeof(uint64_t);
  2616. }
  2617. memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
  2618. }
  2619. }