APInt.cpp 96 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059
  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/SmallString.h"
  18. #include "llvm/ADT/StringRef.h"
  19. #include "llvm/ADT/bit.h"
  20. #include "llvm/Config/llvm-config.h"
  21. #include "llvm/Support/Debug.h"
  22. #include "llvm/Support/ErrorHandling.h"
  23. #include "llvm/Support/MathExtras.h"
  24. #include "llvm/Support/raw_ostream.h"
  25. #include <cmath>
  26. #include <optional>
  27. using namespace llvm;
  28. #define DEBUG_TYPE "apint"
  29. /// A utility function for allocating memory, checking for allocation failures,
  30. /// and ensuring the contents are zeroed.
  31. inline static uint64_t* getClearedMemory(unsigned numWords) {
  32. uint64_t *result = new uint64_t[numWords];
  33. memset(result, 0, numWords * sizeof(uint64_t));
  34. return result;
  35. }
  36. /// A utility function for allocating memory and checking for allocation
  37. /// failure. The content is not zeroed.
  38. inline static uint64_t* getMemory(unsigned numWords) {
  39. return new uint64_t[numWords];
  40. }
  41. /// A utility function that converts a character to a digit.
  42. inline static unsigned getDigit(char cdigit, uint8_t radix) {
  43. unsigned r;
  44. if (radix == 16 || radix == 36) {
  45. r = cdigit - '0';
  46. if (r <= 9)
  47. return r;
  48. r = cdigit - 'A';
  49. if (r <= radix - 11U)
  50. return r + 10;
  51. r = cdigit - 'a';
  52. if (r <= radix - 11U)
  53. return r + 10;
  54. radix = 10;
  55. }
  56. r = cdigit - '0';
  57. if (r < radix)
  58. return r;
  59. return -1U;
  60. }
  61. void APInt::initSlowCase(uint64_t val, bool isSigned) {
  62. U.pVal = getClearedMemory(getNumWords());
  63. U.pVal[0] = val;
  64. if (isSigned && int64_t(val) < 0)
  65. for (unsigned i = 1; i < getNumWords(); ++i)
  66. U.pVal[i] = WORDTYPE_MAX;
  67. clearUnusedBits();
  68. }
  69. void APInt::initSlowCase(const APInt& that) {
  70. U.pVal = getMemory(getNumWords());
  71. memcpy(U.pVal, that.U.pVal, getNumWords() * APINT_WORD_SIZE);
  72. }
  73. void APInt::initFromArray(ArrayRef<uint64_t> bigVal) {
  74. assert(bigVal.data() && "Null pointer detected!");
  75. if (isSingleWord())
  76. U.VAL = bigVal[0];
  77. else {
  78. // Get memory, cleared to 0
  79. U.pVal = getClearedMemory(getNumWords());
  80. // Calculate the number of words to copy
  81. unsigned words = std::min<unsigned>(bigVal.size(), getNumWords());
  82. // Copy the words from bigVal to pVal
  83. memcpy(U.pVal, bigVal.data(), words * APINT_WORD_SIZE);
  84. }
  85. // Make sure unused high bits are cleared
  86. clearUnusedBits();
  87. }
  88. APInt::APInt(unsigned numBits, ArrayRef<uint64_t> bigVal) : BitWidth(numBits) {
  89. initFromArray(bigVal);
  90. }
  91. APInt::APInt(unsigned numBits, unsigned numWords, const uint64_t bigVal[])
  92. : BitWidth(numBits) {
  93. initFromArray(ArrayRef(bigVal, numWords));
  94. }
  95. APInt::APInt(unsigned numbits, StringRef Str, uint8_t radix)
  96. : BitWidth(numbits) {
  97. fromString(numbits, Str, radix);
  98. }
  99. void APInt::reallocate(unsigned NewBitWidth) {
  100. // If the number of words is the same we can just change the width and stop.
  101. if (getNumWords() == getNumWords(NewBitWidth)) {
  102. BitWidth = NewBitWidth;
  103. return;
  104. }
  105. // If we have an allocation, delete it.
  106. if (!isSingleWord())
  107. delete [] U.pVal;
  108. // Update BitWidth.
  109. BitWidth = NewBitWidth;
  110. // If we are supposed to have an allocation, create it.
  111. if (!isSingleWord())
  112. U.pVal = getMemory(getNumWords());
  113. }
  114. void APInt::assignSlowCase(const APInt &RHS) {
  115. // Don't do anything for X = X
  116. if (this == &RHS)
  117. return;
  118. // Adjust the bit width and handle allocations as necessary.
  119. reallocate(RHS.getBitWidth());
  120. // Copy the data.
  121. if (isSingleWord())
  122. U.VAL = RHS.U.VAL;
  123. else
  124. memcpy(U.pVal, RHS.U.pVal, getNumWords() * APINT_WORD_SIZE);
  125. }
  126. /// This method 'profiles' an APInt for use with FoldingSet.
  127. void APInt::Profile(FoldingSetNodeID& ID) const {
  128. ID.AddInteger(BitWidth);
  129. if (isSingleWord()) {
  130. ID.AddInteger(U.VAL);
  131. return;
  132. }
  133. unsigned NumWords = getNumWords();
  134. for (unsigned i = 0; i < NumWords; ++i)
  135. ID.AddInteger(U.pVal[i]);
  136. }
  137. /// Prefix increment operator. Increments the APInt by one.
  138. APInt& APInt::operator++() {
  139. if (isSingleWord())
  140. ++U.VAL;
  141. else
  142. tcIncrement(U.pVal, getNumWords());
  143. return clearUnusedBits();
  144. }
  145. /// Prefix decrement operator. Decrements the APInt by one.
  146. APInt& APInt::operator--() {
  147. if (isSingleWord())
  148. --U.VAL;
  149. else
  150. tcDecrement(U.pVal, getNumWords());
  151. return clearUnusedBits();
  152. }
  153. /// Adds the RHS APInt to this APInt.
  154. /// @returns this, after addition of RHS.
  155. /// Addition assignment operator.
  156. APInt& APInt::operator+=(const APInt& RHS) {
  157. assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
  158. if (isSingleWord())
  159. U.VAL += RHS.U.VAL;
  160. else
  161. tcAdd(U.pVal, RHS.U.pVal, 0, getNumWords());
  162. return clearUnusedBits();
  163. }
  164. APInt& APInt::operator+=(uint64_t RHS) {
  165. if (isSingleWord())
  166. U.VAL += RHS;
  167. else
  168. tcAddPart(U.pVal, RHS, getNumWords());
  169. return clearUnusedBits();
  170. }
  171. /// Subtracts the RHS APInt from this APInt
  172. /// @returns this, after subtraction
  173. /// Subtraction assignment operator.
  174. APInt& APInt::operator-=(const APInt& RHS) {
  175. assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
  176. if (isSingleWord())
  177. U.VAL -= RHS.U.VAL;
  178. else
  179. tcSubtract(U.pVal, RHS.U.pVal, 0, getNumWords());
  180. return clearUnusedBits();
  181. }
  182. APInt& APInt::operator-=(uint64_t RHS) {
  183. if (isSingleWord())
  184. U.VAL -= RHS;
  185. else
  186. tcSubtractPart(U.pVal, RHS, getNumWords());
  187. return clearUnusedBits();
  188. }
  189. APInt APInt::operator*(const APInt& RHS) const {
  190. assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
  191. if (isSingleWord())
  192. return APInt(BitWidth, U.VAL * RHS.U.VAL);
  193. APInt Result(getMemory(getNumWords()), getBitWidth());
  194. tcMultiply(Result.U.pVal, U.pVal, RHS.U.pVal, getNumWords());
  195. Result.clearUnusedBits();
  196. return Result;
  197. }
  198. void APInt::andAssignSlowCase(const APInt &RHS) {
  199. WordType *dst = U.pVal, *rhs = RHS.U.pVal;
  200. for (size_t i = 0, e = getNumWords(); i != e; ++i)
  201. dst[i] &= rhs[i];
  202. }
  203. void APInt::orAssignSlowCase(const APInt &RHS) {
  204. WordType *dst = U.pVal, *rhs = RHS.U.pVal;
  205. for (size_t i = 0, e = getNumWords(); i != e; ++i)
  206. dst[i] |= rhs[i];
  207. }
  208. void APInt::xorAssignSlowCase(const APInt &RHS) {
  209. WordType *dst = U.pVal, *rhs = RHS.U.pVal;
  210. for (size_t i = 0, e = getNumWords(); i != e; ++i)
  211. dst[i] ^= rhs[i];
  212. }
  213. APInt &APInt::operator*=(const APInt &RHS) {
  214. *this = *this * RHS;
  215. return *this;
  216. }
  217. APInt& APInt::operator*=(uint64_t RHS) {
  218. if (isSingleWord()) {
  219. U.VAL *= RHS;
  220. } else {
  221. unsigned NumWords = getNumWords();
  222. tcMultiplyPart(U.pVal, U.pVal, RHS, 0, NumWords, NumWords, false);
  223. }
  224. return clearUnusedBits();
  225. }
  226. bool APInt::equalSlowCase(const APInt &RHS) const {
  227. return std::equal(U.pVal, U.pVal + getNumWords(), RHS.U.pVal);
  228. }
  229. int APInt::compare(const APInt& RHS) const {
  230. assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
  231. if (isSingleWord())
  232. return U.VAL < RHS.U.VAL ? -1 : U.VAL > RHS.U.VAL;
  233. return tcCompare(U.pVal, RHS.U.pVal, getNumWords());
  234. }
  235. int APInt::compareSigned(const APInt& RHS) const {
  236. assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
  237. if (isSingleWord()) {
  238. int64_t lhsSext = SignExtend64(U.VAL, BitWidth);
  239. int64_t rhsSext = SignExtend64(RHS.U.VAL, BitWidth);
  240. return lhsSext < rhsSext ? -1 : lhsSext > rhsSext;
  241. }
  242. bool lhsNeg = isNegative();
  243. bool rhsNeg = RHS.isNegative();
  244. // If the sign bits don't match, then (LHS < RHS) if LHS is negative
  245. if (lhsNeg != rhsNeg)
  246. return lhsNeg ? -1 : 1;
  247. // Otherwise we can just use an unsigned comparison, because even negative
  248. // numbers compare correctly this way if both have the same signed-ness.
  249. return tcCompare(U.pVal, RHS.U.pVal, getNumWords());
  250. }
  251. void APInt::setBitsSlowCase(unsigned loBit, unsigned hiBit) {
  252. unsigned loWord = whichWord(loBit);
  253. unsigned hiWord = whichWord(hiBit);
  254. // Create an initial mask for the low word with zeros below loBit.
  255. uint64_t loMask = WORDTYPE_MAX << whichBit(loBit);
  256. // If hiBit is not aligned, we need a high mask.
  257. unsigned hiShiftAmt = whichBit(hiBit);
  258. if (hiShiftAmt != 0) {
  259. // Create a high mask with zeros above hiBit.
  260. uint64_t hiMask = WORDTYPE_MAX >> (APINT_BITS_PER_WORD - hiShiftAmt);
  261. // If loWord and hiWord are equal, then we combine the masks. Otherwise,
  262. // set the bits in hiWord.
  263. if (hiWord == loWord)
  264. loMask &= hiMask;
  265. else
  266. U.pVal[hiWord] |= hiMask;
  267. }
  268. // Apply the mask to the low word.
  269. U.pVal[loWord] |= loMask;
  270. // Fill any words between loWord and hiWord with all ones.
  271. for (unsigned word = loWord + 1; word < hiWord; ++word)
  272. U.pVal[word] = WORDTYPE_MAX;
  273. }
  274. // Complement a bignum in-place.
  275. static void tcComplement(APInt::WordType *dst, unsigned parts) {
  276. for (unsigned i = 0; i < parts; i++)
  277. dst[i] = ~dst[i];
  278. }
  279. /// Toggle every bit to its opposite value.
  280. void APInt::flipAllBitsSlowCase() {
  281. tcComplement(U.pVal, getNumWords());
  282. clearUnusedBits();
  283. }
  284. /// Concatenate the bits from "NewLSB" onto the bottom of *this. This is
  285. /// equivalent to:
  286. /// (this->zext(NewWidth) << NewLSB.getBitWidth()) | NewLSB.zext(NewWidth)
  287. /// In the slow case, we know the result is large.
  288. APInt APInt::concatSlowCase(const APInt &NewLSB) const {
  289. unsigned NewWidth = getBitWidth() + NewLSB.getBitWidth();
  290. APInt Result = NewLSB.zext(NewWidth);
  291. Result.insertBits(*this, NewLSB.getBitWidth());
  292. return Result;
  293. }
  294. /// Toggle a given bit to its opposite value whose position is given
  295. /// as "bitPosition".
  296. /// Toggles a given bit to its opposite value.
  297. void APInt::flipBit(unsigned bitPosition) {
  298. assert(bitPosition < BitWidth && "Out of the bit-width range!");
  299. setBitVal(bitPosition, !(*this)[bitPosition]);
  300. }
  301. void APInt::insertBits(const APInt &subBits, unsigned bitPosition) {
  302. unsigned subBitWidth = subBits.getBitWidth();
  303. assert((subBitWidth + bitPosition) <= BitWidth && "Illegal bit insertion");
  304. // inserting no bits is a noop.
  305. if (subBitWidth == 0)
  306. return;
  307. // Insertion is a direct copy.
  308. if (subBitWidth == BitWidth) {
  309. *this = subBits;
  310. return;
  311. }
  312. // Single word result can be done as a direct bitmask.
  313. if (isSingleWord()) {
  314. uint64_t mask = WORDTYPE_MAX >> (APINT_BITS_PER_WORD - subBitWidth);
  315. U.VAL &= ~(mask << bitPosition);
  316. U.VAL |= (subBits.U.VAL << bitPosition);
  317. return;
  318. }
  319. unsigned loBit = whichBit(bitPosition);
  320. unsigned loWord = whichWord(bitPosition);
  321. unsigned hi1Word = whichWord(bitPosition + subBitWidth - 1);
  322. // Insertion within a single word can be done as a direct bitmask.
  323. if (loWord == hi1Word) {
  324. uint64_t mask = WORDTYPE_MAX >> (APINT_BITS_PER_WORD - subBitWidth);
  325. U.pVal[loWord] &= ~(mask << loBit);
  326. U.pVal[loWord] |= (subBits.U.VAL << loBit);
  327. return;
  328. }
  329. // Insert on word boundaries.
  330. if (loBit == 0) {
  331. // Direct copy whole words.
  332. unsigned numWholeSubWords = subBitWidth / APINT_BITS_PER_WORD;
  333. memcpy(U.pVal + loWord, subBits.getRawData(),
  334. numWholeSubWords * APINT_WORD_SIZE);
  335. // Mask+insert remaining bits.
  336. unsigned remainingBits = subBitWidth % APINT_BITS_PER_WORD;
  337. if (remainingBits != 0) {
  338. uint64_t mask = WORDTYPE_MAX >> (APINT_BITS_PER_WORD - remainingBits);
  339. U.pVal[hi1Word] &= ~mask;
  340. U.pVal[hi1Word] |= subBits.getWord(subBitWidth - 1);
  341. }
  342. return;
  343. }
  344. // General case - set/clear individual bits in dst based on src.
  345. // TODO - there is scope for optimization here, but at the moment this code
  346. // path is barely used so prefer readability over performance.
  347. for (unsigned i = 0; i != subBitWidth; ++i)
  348. setBitVal(bitPosition + i, subBits[i]);
  349. }
  350. void APInt::insertBits(uint64_t subBits, unsigned bitPosition, unsigned numBits) {
  351. uint64_t maskBits = maskTrailingOnes<uint64_t>(numBits);
  352. subBits &= maskBits;
  353. if (isSingleWord()) {
  354. U.VAL &= ~(maskBits << bitPosition);
  355. U.VAL |= subBits << bitPosition;
  356. return;
  357. }
  358. unsigned loBit = whichBit(bitPosition);
  359. unsigned loWord = whichWord(bitPosition);
  360. unsigned hiWord = whichWord(bitPosition + numBits - 1);
  361. if (loWord == hiWord) {
  362. U.pVal[loWord] &= ~(maskBits << loBit);
  363. U.pVal[loWord] |= subBits << loBit;
  364. return;
  365. }
  366. static_assert(8 * sizeof(WordType) <= 64, "This code assumes only two words affected");
  367. unsigned wordBits = 8 * sizeof(WordType);
  368. U.pVal[loWord] &= ~(maskBits << loBit);
  369. U.pVal[loWord] |= subBits << loBit;
  370. U.pVal[hiWord] &= ~(maskBits >> (wordBits - loBit));
  371. U.pVal[hiWord] |= subBits >> (wordBits - loBit);
  372. }
  373. APInt APInt::extractBits(unsigned numBits, unsigned bitPosition) const {
  374. assert(bitPosition < BitWidth && (numBits + bitPosition) <= BitWidth &&
  375. "Illegal bit extraction");
  376. if (isSingleWord())
  377. return APInt(numBits, U.VAL >> bitPosition);
  378. unsigned loBit = whichBit(bitPosition);
  379. unsigned loWord = whichWord(bitPosition);
  380. unsigned hiWord = whichWord(bitPosition + numBits - 1);
  381. // Single word result extracting bits from a single word source.
  382. if (loWord == hiWord)
  383. return APInt(numBits, U.pVal[loWord] >> loBit);
  384. // Extracting bits that start on a source word boundary can be done
  385. // as a fast memory copy.
  386. if (loBit == 0)
  387. return APInt(numBits, ArrayRef(U.pVal + loWord, 1 + hiWord - loWord));
  388. // General case - shift + copy source words directly into place.
  389. APInt Result(numBits, 0);
  390. unsigned NumSrcWords = getNumWords();
  391. unsigned NumDstWords = Result.getNumWords();
  392. uint64_t *DestPtr = Result.isSingleWord() ? &Result.U.VAL : Result.U.pVal;
  393. for (unsigned word = 0; word < NumDstWords; ++word) {
  394. uint64_t w0 = U.pVal[loWord + word];
  395. uint64_t w1 =
  396. (loWord + word + 1) < NumSrcWords ? U.pVal[loWord + word + 1] : 0;
  397. DestPtr[word] = (w0 >> loBit) | (w1 << (APINT_BITS_PER_WORD - loBit));
  398. }
  399. return Result.clearUnusedBits();
  400. }
  401. uint64_t APInt::extractBitsAsZExtValue(unsigned numBits,
  402. unsigned bitPosition) const {
  403. assert(numBits > 0 && "Can't extract zero bits");
  404. assert(bitPosition < BitWidth && (numBits + bitPosition) <= BitWidth &&
  405. "Illegal bit extraction");
  406. assert(numBits <= 64 && "Illegal bit extraction");
  407. uint64_t maskBits = maskTrailingOnes<uint64_t>(numBits);
  408. if (isSingleWord())
  409. return (U.VAL >> bitPosition) & maskBits;
  410. unsigned loBit = whichBit(bitPosition);
  411. unsigned loWord = whichWord(bitPosition);
  412. unsigned hiWord = whichWord(bitPosition + numBits - 1);
  413. if (loWord == hiWord)
  414. return (U.pVal[loWord] >> loBit) & maskBits;
  415. static_assert(8 * sizeof(WordType) <= 64, "This code assumes only two words affected");
  416. unsigned wordBits = 8 * sizeof(WordType);
  417. uint64_t retBits = U.pVal[loWord] >> loBit;
  418. retBits |= U.pVal[hiWord] << (wordBits - loBit);
  419. retBits &= maskBits;
  420. return retBits;
  421. }
  422. unsigned APInt::getSufficientBitsNeeded(StringRef Str, uint8_t Radix) {
  423. assert(!Str.empty() && "Invalid string length");
  424. size_t StrLen = Str.size();
  425. // Each computation below needs to know if it's negative.
  426. unsigned IsNegative = false;
  427. if (Str[0] == '-' || Str[0] == '+') {
  428. IsNegative = Str[0] == '-';
  429. StrLen--;
  430. assert(StrLen && "String is only a sign, needs a value.");
  431. }
  432. // For radixes of power-of-two values, the bits required is accurately and
  433. // easily computed.
  434. if (Radix == 2)
  435. return StrLen + IsNegative;
  436. if (Radix == 8)
  437. return StrLen * 3 + IsNegative;
  438. if (Radix == 16)
  439. return StrLen * 4 + IsNegative;
  440. // Compute a sufficient number of bits that is always large enough but might
  441. // be too large. This avoids the assertion in the constructor. This
  442. // calculation doesn't work appropriately for the numbers 0-9, so just use 4
  443. // bits in that case.
  444. if (Radix == 10)
  445. return (StrLen == 1 ? 4 : StrLen * 64 / 18) + IsNegative;
  446. assert(Radix == 36);
  447. return (StrLen == 1 ? 7 : StrLen * 16 / 3) + IsNegative;
  448. }
  449. unsigned APInt::getBitsNeeded(StringRef str, uint8_t radix) {
  450. // Compute a sufficient number of bits that is always large enough but might
  451. // be too large.
  452. unsigned sufficient = getSufficientBitsNeeded(str, radix);
  453. // For bases 2, 8, and 16, the sufficient number of bits is exact and we can
  454. // return the value directly. For bases 10 and 36, we need to do extra work.
  455. if (radix == 2 || radix == 8 || radix == 16)
  456. return sufficient;
  457. // This is grossly inefficient but accurate. We could probably do something
  458. // with a computation of roughly slen*64/20 and then adjust by the value of
  459. // the first few digits. But, I'm not sure how accurate that could be.
  460. size_t slen = str.size();
  461. // Each computation below needs to know if it's negative.
  462. StringRef::iterator p = str.begin();
  463. unsigned isNegative = *p == '-';
  464. if (*p == '-' || *p == '+') {
  465. p++;
  466. slen--;
  467. assert(slen && "String is only a sign, needs a value.");
  468. }
  469. // Convert to the actual binary value.
  470. APInt tmp(sufficient, StringRef(p, slen), radix);
  471. // Compute how many bits are required. If the log is infinite, assume we need
  472. // just bit. If the log is exact and value is negative, then the value is
  473. // MinSignedValue with (log + 1) bits.
  474. unsigned log = tmp.logBase2();
  475. if (log == (unsigned)-1) {
  476. return isNegative + 1;
  477. } else if (isNegative && tmp.isPowerOf2()) {
  478. return isNegative + log;
  479. } else {
  480. return isNegative + log + 1;
  481. }
  482. }
  483. hash_code llvm::hash_value(const APInt &Arg) {
  484. if (Arg.isSingleWord())
  485. return hash_combine(Arg.BitWidth, Arg.U.VAL);
  486. return hash_combine(
  487. Arg.BitWidth,
  488. hash_combine_range(Arg.U.pVal, Arg.U.pVal + Arg.getNumWords()));
  489. }
  490. unsigned DenseMapInfo<APInt, void>::getHashValue(const APInt &Key) {
  491. return static_cast<unsigned>(hash_value(Key));
  492. }
  493. bool APInt::isSplat(unsigned SplatSizeInBits) const {
  494. assert(getBitWidth() % SplatSizeInBits == 0 &&
  495. "SplatSizeInBits must divide width!");
  496. // We can check that all parts of an integer are equal by making use of a
  497. // little trick: rotate and check if it's still the same value.
  498. return *this == rotl(SplatSizeInBits);
  499. }
  500. /// This function returns the high "numBits" bits of this APInt.
  501. APInt APInt::getHiBits(unsigned numBits) const {
  502. return this->lshr(BitWidth - numBits);
  503. }
  504. /// This function returns the low "numBits" bits of this APInt.
  505. APInt APInt::getLoBits(unsigned numBits) const {
  506. APInt Result(getLowBitsSet(BitWidth, numBits));
  507. Result &= *this;
  508. return Result;
  509. }
  510. /// Return a value containing V broadcasted over NewLen bits.
  511. APInt APInt::getSplat(unsigned NewLen, const APInt &V) {
  512. assert(NewLen >= V.getBitWidth() && "Can't splat to smaller bit width!");
  513. APInt Val = V.zext(NewLen);
  514. for (unsigned I = V.getBitWidth(); I < NewLen; I <<= 1)
  515. Val |= Val << I;
  516. return Val;
  517. }
  518. unsigned APInt::countLeadingZerosSlowCase() const {
  519. unsigned Count = 0;
  520. for (int i = getNumWords()-1; i >= 0; --i) {
  521. uint64_t V = U.pVal[i];
  522. if (V == 0)
  523. Count += APINT_BITS_PER_WORD;
  524. else {
  525. Count += llvm::countLeadingZeros(V);
  526. break;
  527. }
  528. }
  529. // Adjust for unused bits in the most significant word (they are zero).
  530. unsigned Mod = BitWidth % APINT_BITS_PER_WORD;
  531. Count -= Mod > 0 ? APINT_BITS_PER_WORD - Mod : 0;
  532. return Count;
  533. }
  534. unsigned APInt::countLeadingOnesSlowCase() const {
  535. unsigned highWordBits = BitWidth % APINT_BITS_PER_WORD;
  536. unsigned shift;
  537. if (!highWordBits) {
  538. highWordBits = APINT_BITS_PER_WORD;
  539. shift = 0;
  540. } else {
  541. shift = APINT_BITS_PER_WORD - highWordBits;
  542. }
  543. int i = getNumWords() - 1;
  544. unsigned Count = llvm::countLeadingOnes(U.pVal[i] << shift);
  545. if (Count == highWordBits) {
  546. for (i--; i >= 0; --i) {
  547. if (U.pVal[i] == WORDTYPE_MAX)
  548. Count += APINT_BITS_PER_WORD;
  549. else {
  550. Count += llvm::countLeadingOnes(U.pVal[i]);
  551. break;
  552. }
  553. }
  554. }
  555. return Count;
  556. }
  557. unsigned APInt::countTrailingZerosSlowCase() const {
  558. unsigned Count = 0;
  559. unsigned i = 0;
  560. for (; i < getNumWords() && U.pVal[i] == 0; ++i)
  561. Count += APINT_BITS_PER_WORD;
  562. if (i < getNumWords())
  563. Count += llvm::countTrailingZeros(U.pVal[i]);
  564. return std::min(Count, BitWidth);
  565. }
  566. unsigned APInt::countTrailingOnesSlowCase() const {
  567. unsigned Count = 0;
  568. unsigned i = 0;
  569. for (; i < getNumWords() && U.pVal[i] == WORDTYPE_MAX; ++i)
  570. Count += APINT_BITS_PER_WORD;
  571. if (i < getNumWords())
  572. Count += llvm::countTrailingOnes(U.pVal[i]);
  573. assert(Count <= BitWidth);
  574. return Count;
  575. }
  576. unsigned APInt::countPopulationSlowCase() const {
  577. unsigned Count = 0;
  578. for (unsigned i = 0; i < getNumWords(); ++i)
  579. Count += llvm::popcount(U.pVal[i]);
  580. return Count;
  581. }
  582. bool APInt::intersectsSlowCase(const APInt &RHS) const {
  583. for (unsigned i = 0, e = getNumWords(); i != e; ++i)
  584. if ((U.pVal[i] & RHS.U.pVal[i]) != 0)
  585. return true;
  586. return false;
  587. }
  588. bool APInt::isSubsetOfSlowCase(const APInt &RHS) const {
  589. for (unsigned i = 0, e = getNumWords(); i != e; ++i)
  590. if ((U.pVal[i] & ~RHS.U.pVal[i]) != 0)
  591. return false;
  592. return true;
  593. }
  594. APInt APInt::byteSwap() const {
  595. assert(BitWidth >= 16 && BitWidth % 8 == 0 && "Cannot byteswap!");
  596. if (BitWidth == 16)
  597. return APInt(BitWidth, ByteSwap_16(uint16_t(U.VAL)));
  598. if (BitWidth == 32)
  599. return APInt(BitWidth, ByteSwap_32(unsigned(U.VAL)));
  600. if (BitWidth <= 64) {
  601. uint64_t Tmp1 = ByteSwap_64(U.VAL);
  602. Tmp1 >>= (64 - BitWidth);
  603. return APInt(BitWidth, Tmp1);
  604. }
  605. APInt Result(getNumWords() * APINT_BITS_PER_WORD, 0);
  606. for (unsigned I = 0, N = getNumWords(); I != N; ++I)
  607. Result.U.pVal[I] = ByteSwap_64(U.pVal[N - I - 1]);
  608. if (Result.BitWidth != BitWidth) {
  609. Result.lshrInPlace(Result.BitWidth - BitWidth);
  610. Result.BitWidth = BitWidth;
  611. }
  612. return Result;
  613. }
  614. APInt APInt::reverseBits() const {
  615. switch (BitWidth) {
  616. case 64:
  617. return APInt(BitWidth, llvm::reverseBits<uint64_t>(U.VAL));
  618. case 32:
  619. return APInt(BitWidth, llvm::reverseBits<uint32_t>(U.VAL));
  620. case 16:
  621. return APInt(BitWidth, llvm::reverseBits<uint16_t>(U.VAL));
  622. case 8:
  623. return APInt(BitWidth, llvm::reverseBits<uint8_t>(U.VAL));
  624. case 0:
  625. return *this;
  626. default:
  627. break;
  628. }
  629. APInt Val(*this);
  630. APInt Reversed(BitWidth, 0);
  631. unsigned S = BitWidth;
  632. for (; Val != 0; Val.lshrInPlace(1)) {
  633. Reversed <<= 1;
  634. Reversed |= Val[0];
  635. --S;
  636. }
  637. Reversed <<= S;
  638. return Reversed;
  639. }
  640. APInt llvm::APIntOps::GreatestCommonDivisor(APInt A, APInt B) {
  641. // Fast-path a common case.
  642. if (A == B) return A;
  643. // Corner cases: if either operand is zero, the other is the gcd.
  644. if (!A) return B;
  645. if (!B) return A;
  646. // Count common powers of 2 and remove all other powers of 2.
  647. unsigned Pow2;
  648. {
  649. unsigned Pow2_A = A.countTrailingZeros();
  650. unsigned Pow2_B = B.countTrailingZeros();
  651. if (Pow2_A > Pow2_B) {
  652. A.lshrInPlace(Pow2_A - Pow2_B);
  653. Pow2 = Pow2_B;
  654. } else if (Pow2_B > Pow2_A) {
  655. B.lshrInPlace(Pow2_B - Pow2_A);
  656. Pow2 = Pow2_A;
  657. } else {
  658. Pow2 = Pow2_A;
  659. }
  660. }
  661. // Both operands are odd multiples of 2^Pow_2:
  662. //
  663. // gcd(a, b) = gcd(|a - b| / 2^i, min(a, b))
  664. //
  665. // This is a modified version of Stein's algorithm, taking advantage of
  666. // efficient countTrailingZeros().
  667. while (A != B) {
  668. if (A.ugt(B)) {
  669. A -= B;
  670. A.lshrInPlace(A.countTrailingZeros() - Pow2);
  671. } else {
  672. B -= A;
  673. B.lshrInPlace(B.countTrailingZeros() - Pow2);
  674. }
  675. }
  676. return A;
  677. }
  678. APInt llvm::APIntOps::RoundDoubleToAPInt(double Double, unsigned width) {
  679. uint64_t I = bit_cast<uint64_t>(Double);
  680. // Get the sign bit from the highest order bit
  681. bool isNeg = I >> 63;
  682. // Get the 11-bit exponent and adjust for the 1023 bit bias
  683. int64_t exp = ((I >> 52) & 0x7ff) - 1023;
  684. // If the exponent is negative, the value is < 0 so just return 0.
  685. if (exp < 0)
  686. return APInt(width, 0u);
  687. // Extract the mantissa by clearing the top 12 bits (sign + exponent).
  688. uint64_t mantissa = (I & (~0ULL >> 12)) | 1ULL << 52;
  689. // If the exponent doesn't shift all bits out of the mantissa
  690. if (exp < 52)
  691. return isNeg ? -APInt(width, mantissa >> (52 - exp)) :
  692. APInt(width, mantissa >> (52 - exp));
  693. // If the client didn't provide enough bits for us to shift the mantissa into
  694. // then the result is undefined, just return 0
  695. if (width <= exp - 52)
  696. return APInt(width, 0);
  697. // Otherwise, we have to shift the mantissa bits up to the right location
  698. APInt Tmp(width, mantissa);
  699. Tmp <<= (unsigned)exp - 52;
  700. return isNeg ? -Tmp : Tmp;
  701. }
  702. /// This function converts this APInt to a double.
  703. /// The layout for double is as following (IEEE Standard 754):
  704. /// --------------------------------------
  705. /// | Sign Exponent Fraction Bias |
  706. /// |-------------------------------------- |
  707. /// | 1[63] 11[62-52] 52[51-00] 1023 |
  708. /// --------------------------------------
  709. double APInt::roundToDouble(bool isSigned) const {
  710. // Handle the simple case where the value is contained in one uint64_t.
  711. // It is wrong to optimize getWord(0) to VAL; there might be more than one word.
  712. if (isSingleWord() || getActiveBits() <= APINT_BITS_PER_WORD) {
  713. if (isSigned) {
  714. int64_t sext = SignExtend64(getWord(0), BitWidth);
  715. return double(sext);
  716. } else
  717. return double(getWord(0));
  718. }
  719. // Determine if the value is negative.
  720. bool isNeg = isSigned ? (*this)[BitWidth-1] : false;
  721. // Construct the absolute value if we're negative.
  722. APInt Tmp(isNeg ? -(*this) : (*this));
  723. // Figure out how many bits we're using.
  724. unsigned n = Tmp.getActiveBits();
  725. // The exponent (without bias normalization) is just the number of bits
  726. // we are using. Note that the sign bit is gone since we constructed the
  727. // absolute value.
  728. uint64_t exp = n;
  729. // Return infinity for exponent overflow
  730. if (exp > 1023) {
  731. if (!isSigned || !isNeg)
  732. return std::numeric_limits<double>::infinity();
  733. else
  734. return -std::numeric_limits<double>::infinity();
  735. }
  736. exp += 1023; // Increment for 1023 bias
  737. // Number of bits in mantissa is 52. To obtain the mantissa value, we must
  738. // extract the high 52 bits from the correct words in pVal.
  739. uint64_t mantissa;
  740. unsigned hiWord = whichWord(n-1);
  741. if (hiWord == 0) {
  742. mantissa = Tmp.U.pVal[0];
  743. if (n > 52)
  744. mantissa >>= n - 52; // shift down, we want the top 52 bits.
  745. } else {
  746. assert(hiWord > 0 && "huh?");
  747. uint64_t hibits = Tmp.U.pVal[hiWord] << (52 - n % APINT_BITS_PER_WORD);
  748. uint64_t lobits = Tmp.U.pVal[hiWord-1] >> (11 + n % APINT_BITS_PER_WORD);
  749. mantissa = hibits | lobits;
  750. }
  751. // The leading bit of mantissa is implicit, so get rid of it.
  752. uint64_t sign = isNeg ? (1ULL << (APINT_BITS_PER_WORD - 1)) : 0;
  753. uint64_t I = sign | (exp << 52) | mantissa;
  754. return bit_cast<double>(I);
  755. }
  756. // Truncate to new width.
  757. APInt APInt::trunc(unsigned width) const {
  758. assert(width <= BitWidth && "Invalid APInt Truncate request");
  759. if (width <= APINT_BITS_PER_WORD)
  760. return APInt(width, getRawData()[0]);
  761. if (width == BitWidth)
  762. return *this;
  763. APInt Result(getMemory(getNumWords(width)), width);
  764. // Copy full words.
  765. unsigned i;
  766. for (i = 0; i != width / APINT_BITS_PER_WORD; i++)
  767. Result.U.pVal[i] = U.pVal[i];
  768. // Truncate and copy any partial word.
  769. unsigned bits = (0 - width) % APINT_BITS_PER_WORD;
  770. if (bits != 0)
  771. Result.U.pVal[i] = U.pVal[i] << bits >> bits;
  772. return Result;
  773. }
  774. // Truncate to new width with unsigned saturation.
  775. APInt APInt::truncUSat(unsigned width) const {
  776. assert(width <= BitWidth && "Invalid APInt Truncate request");
  777. // Can we just losslessly truncate it?
  778. if (isIntN(width))
  779. return trunc(width);
  780. // If not, then just return the new limit.
  781. return APInt::getMaxValue(width);
  782. }
  783. // Truncate to new width with signed saturation.
  784. APInt APInt::truncSSat(unsigned width) const {
  785. assert(width <= BitWidth && "Invalid APInt Truncate request");
  786. // Can we just losslessly truncate it?
  787. if (isSignedIntN(width))
  788. return trunc(width);
  789. // If not, then just return the new limits.
  790. return isNegative() ? APInt::getSignedMinValue(width)
  791. : APInt::getSignedMaxValue(width);
  792. }
  793. // Sign extend to a new width.
  794. APInt APInt::sext(unsigned Width) const {
  795. assert(Width >= BitWidth && "Invalid APInt SignExtend request");
  796. if (Width <= APINT_BITS_PER_WORD)
  797. return APInt(Width, SignExtend64(U.VAL, BitWidth));
  798. if (Width == BitWidth)
  799. return *this;
  800. APInt Result(getMemory(getNumWords(Width)), Width);
  801. // Copy words.
  802. std::memcpy(Result.U.pVal, getRawData(), getNumWords() * APINT_WORD_SIZE);
  803. // Sign extend the last word since there may be unused bits in the input.
  804. Result.U.pVal[getNumWords() - 1] =
  805. SignExtend64(Result.U.pVal[getNumWords() - 1],
  806. ((BitWidth - 1) % APINT_BITS_PER_WORD) + 1);
  807. // Fill with sign bits.
  808. std::memset(Result.U.pVal + getNumWords(), isNegative() ? -1 : 0,
  809. (Result.getNumWords() - getNumWords()) * APINT_WORD_SIZE);
  810. Result.clearUnusedBits();
  811. return Result;
  812. }
  813. // Zero extend to a new width.
  814. APInt APInt::zext(unsigned width) const {
  815. assert(width >= BitWidth && "Invalid APInt ZeroExtend request");
  816. if (width <= APINT_BITS_PER_WORD)
  817. return APInt(width, U.VAL);
  818. if (width == BitWidth)
  819. return *this;
  820. APInt Result(getMemory(getNumWords(width)), width);
  821. // Copy words.
  822. std::memcpy(Result.U.pVal, getRawData(), getNumWords() * APINT_WORD_SIZE);
  823. // Zero remaining words.
  824. std::memset(Result.U.pVal + getNumWords(), 0,
  825. (Result.getNumWords() - getNumWords()) * APINT_WORD_SIZE);
  826. return Result;
  827. }
  828. APInt APInt::zextOrTrunc(unsigned width) const {
  829. if (BitWidth < width)
  830. return zext(width);
  831. if (BitWidth > width)
  832. return trunc(width);
  833. return *this;
  834. }
  835. APInt APInt::sextOrTrunc(unsigned width) const {
  836. if (BitWidth < width)
  837. return sext(width);
  838. if (BitWidth > width)
  839. return trunc(width);
  840. return *this;
  841. }
  842. /// Arithmetic right-shift this APInt by shiftAmt.
  843. /// Arithmetic right-shift function.
  844. void APInt::ashrInPlace(const APInt &shiftAmt) {
  845. ashrInPlace((unsigned)shiftAmt.getLimitedValue(BitWidth));
  846. }
  847. /// Arithmetic right-shift this APInt by shiftAmt.
  848. /// Arithmetic right-shift function.
  849. void APInt::ashrSlowCase(unsigned ShiftAmt) {
  850. // Don't bother performing a no-op shift.
  851. if (!ShiftAmt)
  852. return;
  853. // Save the original sign bit for later.
  854. bool Negative = isNegative();
  855. // WordShift is the inter-part shift; BitShift is intra-part shift.
  856. unsigned WordShift = ShiftAmt / APINT_BITS_PER_WORD;
  857. unsigned BitShift = ShiftAmt % APINT_BITS_PER_WORD;
  858. unsigned WordsToMove = getNumWords() - WordShift;
  859. if (WordsToMove != 0) {
  860. // Sign extend the last word to fill in the unused bits.
  861. U.pVal[getNumWords() - 1] = SignExtend64(
  862. U.pVal[getNumWords() - 1], ((BitWidth - 1) % APINT_BITS_PER_WORD) + 1);
  863. // Fastpath for moving by whole words.
  864. if (BitShift == 0) {
  865. std::memmove(U.pVal, U.pVal + WordShift, WordsToMove * APINT_WORD_SIZE);
  866. } else {
  867. // Move the words containing significant bits.
  868. for (unsigned i = 0; i != WordsToMove - 1; ++i)
  869. U.pVal[i] = (U.pVal[i + WordShift] >> BitShift) |
  870. (U.pVal[i + WordShift + 1] << (APINT_BITS_PER_WORD - BitShift));
  871. // Handle the last word which has no high bits to copy.
  872. U.pVal[WordsToMove - 1] = U.pVal[WordShift + WordsToMove - 1] >> BitShift;
  873. // Sign extend one more time.
  874. U.pVal[WordsToMove - 1] =
  875. SignExtend64(U.pVal[WordsToMove - 1], APINT_BITS_PER_WORD - BitShift);
  876. }
  877. }
  878. // Fill in the remainder based on the original sign.
  879. std::memset(U.pVal + WordsToMove, Negative ? -1 : 0,
  880. WordShift * APINT_WORD_SIZE);
  881. clearUnusedBits();
  882. }
  883. /// Logical right-shift this APInt by shiftAmt.
  884. /// Logical right-shift function.
  885. void APInt::lshrInPlace(const APInt &shiftAmt) {
  886. lshrInPlace((unsigned)shiftAmt.getLimitedValue(BitWidth));
  887. }
  888. /// Logical right-shift this APInt by shiftAmt.
  889. /// Logical right-shift function.
  890. void APInt::lshrSlowCase(unsigned ShiftAmt) {
  891. tcShiftRight(U.pVal, getNumWords(), ShiftAmt);
  892. }
  893. /// Left-shift this APInt by shiftAmt.
  894. /// Left-shift function.
  895. APInt &APInt::operator<<=(const APInt &shiftAmt) {
  896. // It's undefined behavior in C to shift by BitWidth or greater.
  897. *this <<= (unsigned)shiftAmt.getLimitedValue(BitWidth);
  898. return *this;
  899. }
  900. void APInt::shlSlowCase(unsigned ShiftAmt) {
  901. tcShiftLeft(U.pVal, getNumWords(), ShiftAmt);
  902. clearUnusedBits();
  903. }
  904. // Calculate the rotate amount modulo the bit width.
  905. static unsigned rotateModulo(unsigned BitWidth, const APInt &rotateAmt) {
  906. if (LLVM_UNLIKELY(BitWidth == 0))
  907. return 0;
  908. unsigned rotBitWidth = rotateAmt.getBitWidth();
  909. APInt rot = rotateAmt;
  910. if (rotBitWidth < BitWidth) {
  911. // Extend the rotate APInt, so that the urem doesn't divide by 0.
  912. // e.g. APInt(1, 32) would give APInt(1, 0).
  913. rot = rotateAmt.zext(BitWidth);
  914. }
  915. rot = rot.urem(APInt(rot.getBitWidth(), BitWidth));
  916. return rot.getLimitedValue(BitWidth);
  917. }
  918. APInt APInt::rotl(const APInt &rotateAmt) const {
  919. return rotl(rotateModulo(BitWidth, rotateAmt));
  920. }
  921. APInt APInt::rotl(unsigned rotateAmt) const {
  922. if (LLVM_UNLIKELY(BitWidth == 0))
  923. return *this;
  924. rotateAmt %= BitWidth;
  925. if (rotateAmt == 0)
  926. return *this;
  927. return shl(rotateAmt) | lshr(BitWidth - rotateAmt);
  928. }
  929. APInt APInt::rotr(const APInt &rotateAmt) const {
  930. return rotr(rotateModulo(BitWidth, rotateAmt));
  931. }
  932. APInt APInt::rotr(unsigned rotateAmt) const {
  933. if (BitWidth == 0)
  934. return *this;
  935. rotateAmt %= BitWidth;
  936. if (rotateAmt == 0)
  937. return *this;
  938. return lshr(rotateAmt) | shl(BitWidth - rotateAmt);
  939. }
  940. /// \returns the nearest log base 2 of this APInt. Ties round up.
  941. ///
  942. /// NOTE: When we have a BitWidth of 1, we define:
  943. ///
  944. /// log2(0) = UINT32_MAX
  945. /// log2(1) = 0
  946. ///
  947. /// to get around any mathematical concerns resulting from
  948. /// referencing 2 in a space where 2 does no exist.
  949. unsigned APInt::nearestLogBase2() const {
  950. // Special case when we have a bitwidth of 1. If VAL is 1, then we
  951. // get 0. If VAL is 0, we get WORDTYPE_MAX which gets truncated to
  952. // UINT32_MAX.
  953. if (BitWidth == 1)
  954. return U.VAL - 1;
  955. // Handle the zero case.
  956. if (isZero())
  957. return UINT32_MAX;
  958. // The non-zero case is handled by computing:
  959. //
  960. // nearestLogBase2(x) = logBase2(x) + x[logBase2(x)-1].
  961. //
  962. // where x[i] is referring to the value of the ith bit of x.
  963. unsigned lg = logBase2();
  964. return lg + unsigned((*this)[lg - 1]);
  965. }
  966. // Square Root - this method computes and returns the square root of "this".
  967. // Three mechanisms are used for computation. For small values (<= 5 bits),
  968. // a table lookup is done. This gets some performance for common cases. For
  969. // values using less than 52 bits, the value is converted to double and then
  970. // the libc sqrt function is called. The result is rounded and then converted
  971. // back to a uint64_t which is then used to construct the result. Finally,
  972. // the Babylonian method for computing square roots is used.
  973. APInt APInt::sqrt() const {
  974. // Determine the magnitude of the value.
  975. unsigned magnitude = getActiveBits();
  976. // Use a fast table for some small values. This also gets rid of some
  977. // rounding errors in libc sqrt for small values.
  978. if (magnitude <= 5) {
  979. static const uint8_t results[32] = {
  980. /* 0 */ 0,
  981. /* 1- 2 */ 1, 1,
  982. /* 3- 6 */ 2, 2, 2, 2,
  983. /* 7-12 */ 3, 3, 3, 3, 3, 3,
  984. /* 13-20 */ 4, 4, 4, 4, 4, 4, 4, 4,
  985. /* 21-30 */ 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  986. /* 31 */ 6
  987. };
  988. return APInt(BitWidth, results[ (isSingleWord() ? U.VAL : U.pVal[0]) ]);
  989. }
  990. // If the magnitude of the value fits in less than 52 bits (the precision of
  991. // an IEEE double precision floating point value), then we can use the
  992. // libc sqrt function which will probably use a hardware sqrt computation.
  993. // This should be faster than the algorithm below.
  994. if (magnitude < 52) {
  995. return APInt(BitWidth,
  996. uint64_t(::round(::sqrt(double(isSingleWord() ? U.VAL
  997. : U.pVal[0])))));
  998. }
  999. // Okay, all the short cuts are exhausted. We must compute it. The following
  1000. // is a classical Babylonian method for computing the square root. This code
  1001. // was adapted to APInt from a wikipedia article on such computations.
  1002. // See http://www.wikipedia.org/ and go to the page named
  1003. // Calculate_an_integer_square_root.
  1004. unsigned nbits = BitWidth, i = 4;
  1005. APInt testy(BitWidth, 16);
  1006. APInt x_old(BitWidth, 1);
  1007. APInt x_new(BitWidth, 0);
  1008. APInt two(BitWidth, 2);
  1009. // Select a good starting value using binary logarithms.
  1010. for (;; i += 2, testy = testy.shl(2))
  1011. if (i >= nbits || this->ule(testy)) {
  1012. x_old = x_old.shl(i / 2);
  1013. break;
  1014. }
  1015. // Use the Babylonian method to arrive at the integer square root:
  1016. for (;;) {
  1017. x_new = (this->udiv(x_old) + x_old).udiv(two);
  1018. if (x_old.ule(x_new))
  1019. break;
  1020. x_old = x_new;
  1021. }
  1022. // Make sure we return the closest approximation
  1023. // NOTE: The rounding calculation below is correct. It will produce an
  1024. // off-by-one discrepancy with results from pari/gp. That discrepancy has been
  1025. // determined to be a rounding issue with pari/gp as it begins to use a
  1026. // floating point representation after 192 bits. There are no discrepancies
  1027. // between this algorithm and pari/gp for bit widths < 192 bits.
  1028. APInt square(x_old * x_old);
  1029. APInt nextSquare((x_old + 1) * (x_old +1));
  1030. if (this->ult(square))
  1031. return x_old;
  1032. assert(this->ule(nextSquare) && "Error in APInt::sqrt computation");
  1033. APInt midpoint((nextSquare - square).udiv(two));
  1034. APInt offset(*this - square);
  1035. if (offset.ult(midpoint))
  1036. return x_old;
  1037. return x_old + 1;
  1038. }
  1039. /// Computes the multiplicative inverse of this APInt for a given modulo. The
  1040. /// iterative extended Euclidean algorithm is used to solve for this value,
  1041. /// however we simplify it to speed up calculating only the inverse, and take
  1042. /// advantage of div+rem calculations. We also use some tricks to avoid copying
  1043. /// (potentially large) APInts around.
  1044. /// WARNING: a value of '0' may be returned,
  1045. /// signifying that no multiplicative inverse exists!
  1046. APInt APInt::multiplicativeInverse(const APInt& modulo) const {
  1047. assert(ult(modulo) && "This APInt must be smaller than the modulo");
  1048. // Using the properties listed at the following web page (accessed 06/21/08):
  1049. // http://www.numbertheory.org/php/euclid.html
  1050. // (especially the properties numbered 3, 4 and 9) it can be proved that
  1051. // BitWidth bits suffice for all the computations in the algorithm implemented
  1052. // below. More precisely, this number of bits suffice if the multiplicative
  1053. // inverse exists, but may not suffice for the general extended Euclidean
  1054. // algorithm.
  1055. APInt r[2] = { modulo, *this };
  1056. APInt t[2] = { APInt(BitWidth, 0), APInt(BitWidth, 1) };
  1057. APInt q(BitWidth, 0);
  1058. unsigned i;
  1059. for (i = 0; r[i^1] != 0; i ^= 1) {
  1060. // An overview of the math without the confusing bit-flipping:
  1061. // q = r[i-2] / r[i-1]
  1062. // r[i] = r[i-2] % r[i-1]
  1063. // t[i] = t[i-2] - t[i-1] * q
  1064. udivrem(r[i], r[i^1], q, r[i]);
  1065. t[i] -= t[i^1] * q;
  1066. }
  1067. // If this APInt and the modulo are not coprime, there is no multiplicative
  1068. // inverse, so return 0. We check this by looking at the next-to-last
  1069. // remainder, which is the gcd(*this,modulo) as calculated by the Euclidean
  1070. // algorithm.
  1071. if (r[i] != 1)
  1072. return APInt(BitWidth, 0);
  1073. // The next-to-last t is the multiplicative inverse. However, we are
  1074. // interested in a positive inverse. Calculate a positive one from a negative
  1075. // one if necessary. A simple addition of the modulo suffices because
  1076. // abs(t[i]) is known to be less than *this/2 (see the link above).
  1077. if (t[i].isNegative())
  1078. t[i] += modulo;
  1079. return std::move(t[i]);
  1080. }
  1081. /// Implementation of Knuth's Algorithm D (Division of nonnegative integers)
  1082. /// from "Art of Computer Programming, Volume 2", section 4.3.1, p. 272. The
  1083. /// variables here have the same names as in the algorithm. Comments explain
  1084. /// the algorithm and any deviation from it.
  1085. static void KnuthDiv(uint32_t *u, uint32_t *v, uint32_t *q, uint32_t* r,
  1086. unsigned m, unsigned n) {
  1087. assert(u && "Must provide dividend");
  1088. assert(v && "Must provide divisor");
  1089. assert(q && "Must provide quotient");
  1090. assert(u != v && u != q && v != q && "Must use different memory");
  1091. assert(n>1 && "n must be > 1");
  1092. // b denotes the base of the number system. In our case b is 2^32.
  1093. const uint64_t b = uint64_t(1) << 32;
  1094. // The DEBUG macros here tend to be spam in the debug output if you're not
  1095. // debugging this code. Disable them unless KNUTH_DEBUG is defined.
  1096. #ifdef KNUTH_DEBUG
  1097. #define DEBUG_KNUTH(X) LLVM_DEBUG(X)
  1098. #else
  1099. #define DEBUG_KNUTH(X) do {} while(false)
  1100. #endif
  1101. DEBUG_KNUTH(dbgs() << "KnuthDiv: m=" << m << " n=" << n << '\n');
  1102. DEBUG_KNUTH(dbgs() << "KnuthDiv: original:");
  1103. DEBUG_KNUTH(for (int i = m + n; i >= 0; i--) dbgs() << " " << u[i]);
  1104. DEBUG_KNUTH(dbgs() << " by");
  1105. DEBUG_KNUTH(for (int i = n; i > 0; i--) dbgs() << " " << v[i - 1]);
  1106. DEBUG_KNUTH(dbgs() << '\n');
  1107. // D1. [Normalize.] Set d = b / (v[n-1] + 1) and multiply all the digits of
  1108. // u and v by d. Note that we have taken Knuth's advice here to use a power
  1109. // of 2 value for d such that d * v[n-1] >= b/2 (b is the base). A power of
  1110. // 2 allows us to shift instead of multiply and it is easy to determine the
  1111. // shift amount from the leading zeros. We are basically normalizing the u
  1112. // and v so that its high bits are shifted to the top of v's range without
  1113. // overflow. Note that this can require an extra word in u so that u must
  1114. // be of length m+n+1.
  1115. unsigned shift = countLeadingZeros(v[n-1]);
  1116. uint32_t v_carry = 0;
  1117. uint32_t u_carry = 0;
  1118. if (shift) {
  1119. for (unsigned i = 0; i < m+n; ++i) {
  1120. uint32_t u_tmp = u[i] >> (32 - shift);
  1121. u[i] = (u[i] << shift) | u_carry;
  1122. u_carry = u_tmp;
  1123. }
  1124. for (unsigned i = 0; i < n; ++i) {
  1125. uint32_t v_tmp = v[i] >> (32 - shift);
  1126. v[i] = (v[i] << shift) | v_carry;
  1127. v_carry = v_tmp;
  1128. }
  1129. }
  1130. u[m+n] = u_carry;
  1131. DEBUG_KNUTH(dbgs() << "KnuthDiv: normal:");
  1132. DEBUG_KNUTH(for (int i = m + n; i >= 0; i--) dbgs() << " " << u[i]);
  1133. DEBUG_KNUTH(dbgs() << " by");
  1134. DEBUG_KNUTH(for (int i = n; i > 0; i--) dbgs() << " " << v[i - 1]);
  1135. DEBUG_KNUTH(dbgs() << '\n');
  1136. // D2. [Initialize j.] Set j to m. This is the loop counter over the places.
  1137. int j = m;
  1138. do {
  1139. DEBUG_KNUTH(dbgs() << "KnuthDiv: quotient digit #" << j << '\n');
  1140. // D3. [Calculate q'.].
  1141. // Set qp = (u[j+n]*b + u[j+n-1]) / v[n-1]. (qp=qprime=q')
  1142. // Set rp = (u[j+n]*b + u[j+n-1]) % v[n-1]. (rp=rprime=r')
  1143. // Now test if qp == b or qp*v[n-2] > b*rp + u[j+n-2]; if so, decrease
  1144. // qp by 1, increase rp by v[n-1], and repeat this test if rp < b. The test
  1145. // on v[n-2] determines at high speed most of the cases in which the trial
  1146. // value qp is one too large, and it eliminates all cases where qp is two
  1147. // too large.
  1148. uint64_t dividend = Make_64(u[j+n], u[j+n-1]);
  1149. DEBUG_KNUTH(dbgs() << "KnuthDiv: dividend == " << dividend << '\n');
  1150. uint64_t qp = dividend / v[n-1];
  1151. uint64_t rp = dividend % v[n-1];
  1152. if (qp == b || qp*v[n-2] > b*rp + u[j+n-2]) {
  1153. qp--;
  1154. rp += v[n-1];
  1155. if (rp < b && (qp == b || qp*v[n-2] > b*rp + u[j+n-2]))
  1156. qp--;
  1157. }
  1158. DEBUG_KNUTH(dbgs() << "KnuthDiv: qp == " << qp << ", rp == " << rp << '\n');
  1159. // D4. [Multiply and subtract.] Replace (u[j+n]u[j+n-1]...u[j]) with
  1160. // (u[j+n]u[j+n-1]..u[j]) - qp * (v[n-1]...v[1]v[0]). This computation
  1161. // consists of a simple multiplication by a one-place number, combined with
  1162. // a subtraction.
  1163. // The digits (u[j+n]...u[j]) should be kept positive; if the result of
  1164. // this step is actually negative, (u[j+n]...u[j]) should be left as the
  1165. // true value plus b**(n+1), namely as the b's complement of
  1166. // the true value, and a "borrow" to the left should be remembered.
  1167. int64_t borrow = 0;
  1168. for (unsigned i = 0; i < n; ++i) {
  1169. uint64_t p = uint64_t(qp) * uint64_t(v[i]);
  1170. int64_t subres = int64_t(u[j+i]) - borrow - Lo_32(p);
  1171. u[j+i] = Lo_32(subres);
  1172. borrow = Hi_32(p) - Hi_32(subres);
  1173. DEBUG_KNUTH(dbgs() << "KnuthDiv: u[j+i] = " << u[j + i]
  1174. << ", borrow = " << borrow << '\n');
  1175. }
  1176. bool isNeg = u[j+n] < borrow;
  1177. u[j+n] -= Lo_32(borrow);
  1178. DEBUG_KNUTH(dbgs() << "KnuthDiv: after subtraction:");
  1179. DEBUG_KNUTH(for (int i = m + n; i >= 0; i--) dbgs() << " " << u[i]);
  1180. DEBUG_KNUTH(dbgs() << '\n');
  1181. // D5. [Test remainder.] Set q[j] = qp. If the result of step D4 was
  1182. // negative, go to step D6; otherwise go on to step D7.
  1183. q[j] = Lo_32(qp);
  1184. if (isNeg) {
  1185. // D6. [Add back]. The probability that this step is necessary is very
  1186. // small, on the order of only 2/b. Make sure that test data accounts for
  1187. // this possibility. Decrease q[j] by 1
  1188. q[j]--;
  1189. // and add (0v[n-1]...v[1]v[0]) to (u[j+n]u[j+n-1]...u[j+1]u[j]).
  1190. // A carry will occur to the left of u[j+n], and it should be ignored
  1191. // since it cancels with the borrow that occurred in D4.
  1192. bool carry = false;
  1193. for (unsigned i = 0; i < n; i++) {
  1194. uint32_t limit = std::min(u[j+i],v[i]);
  1195. u[j+i] += v[i] + carry;
  1196. carry = u[j+i] < limit || (carry && u[j+i] == limit);
  1197. }
  1198. u[j+n] += carry;
  1199. }
  1200. DEBUG_KNUTH(dbgs() << "KnuthDiv: after correction:");
  1201. DEBUG_KNUTH(for (int i = m + n; i >= 0; i--) dbgs() << " " << u[i]);
  1202. DEBUG_KNUTH(dbgs() << "\nKnuthDiv: digit result = " << q[j] << '\n');
  1203. // D7. [Loop on j.] Decrease j by one. Now if j >= 0, go back to D3.
  1204. } while (--j >= 0);
  1205. DEBUG_KNUTH(dbgs() << "KnuthDiv: quotient:");
  1206. DEBUG_KNUTH(for (int i = m; i >= 0; i--) dbgs() << " " << q[i]);
  1207. DEBUG_KNUTH(dbgs() << '\n');
  1208. // D8. [Unnormalize]. Now q[...] is the desired quotient, and the desired
  1209. // remainder may be obtained by dividing u[...] by d. If r is non-null we
  1210. // compute the remainder (urem uses this).
  1211. if (r) {
  1212. // The value d is expressed by the "shift" value above since we avoided
  1213. // multiplication by d by using a shift left. So, all we have to do is
  1214. // shift right here.
  1215. if (shift) {
  1216. uint32_t carry = 0;
  1217. DEBUG_KNUTH(dbgs() << "KnuthDiv: remainder:");
  1218. for (int i = n-1; i >= 0; i--) {
  1219. r[i] = (u[i] >> shift) | carry;
  1220. carry = u[i] << (32 - shift);
  1221. DEBUG_KNUTH(dbgs() << " " << r[i]);
  1222. }
  1223. } else {
  1224. for (int i = n-1; i >= 0; i--) {
  1225. r[i] = u[i];
  1226. DEBUG_KNUTH(dbgs() << " " << r[i]);
  1227. }
  1228. }
  1229. DEBUG_KNUTH(dbgs() << '\n');
  1230. }
  1231. DEBUG_KNUTH(dbgs() << '\n');
  1232. }
  1233. void APInt::divide(const WordType *LHS, unsigned lhsWords, const WordType *RHS,
  1234. unsigned rhsWords, WordType *Quotient, WordType *Remainder) {
  1235. assert(lhsWords >= rhsWords && "Fractional result");
  1236. // First, compose the values into an array of 32-bit words instead of
  1237. // 64-bit words. This is a necessity of both the "short division" algorithm
  1238. // and the Knuth "classical algorithm" which requires there to be native
  1239. // operations for +, -, and * on an m bit value with an m*2 bit result. We
  1240. // can't use 64-bit operands here because we don't have native results of
  1241. // 128-bits. Furthermore, casting the 64-bit values to 32-bit values won't
  1242. // work on large-endian machines.
  1243. unsigned n = rhsWords * 2;
  1244. unsigned m = (lhsWords * 2) - n;
  1245. // Allocate space for the temporary values we need either on the stack, if
  1246. // it will fit, or on the heap if it won't.
  1247. uint32_t SPACE[128];
  1248. uint32_t *U = nullptr;
  1249. uint32_t *V = nullptr;
  1250. uint32_t *Q = nullptr;
  1251. uint32_t *R = nullptr;
  1252. if ((Remainder?4:3)*n+2*m+1 <= 128) {
  1253. U = &SPACE[0];
  1254. V = &SPACE[m+n+1];
  1255. Q = &SPACE[(m+n+1) + n];
  1256. if (Remainder)
  1257. R = &SPACE[(m+n+1) + n + (m+n)];
  1258. } else {
  1259. U = new uint32_t[m + n + 1];
  1260. V = new uint32_t[n];
  1261. Q = new uint32_t[m+n];
  1262. if (Remainder)
  1263. R = new uint32_t[n];
  1264. }
  1265. // Initialize the dividend
  1266. memset(U, 0, (m+n+1)*sizeof(uint32_t));
  1267. for (unsigned i = 0; i < lhsWords; ++i) {
  1268. uint64_t tmp = LHS[i];
  1269. U[i * 2] = Lo_32(tmp);
  1270. U[i * 2 + 1] = Hi_32(tmp);
  1271. }
  1272. U[m+n] = 0; // this extra word is for "spill" in the Knuth algorithm.
  1273. // Initialize the divisor
  1274. memset(V, 0, (n)*sizeof(uint32_t));
  1275. for (unsigned i = 0; i < rhsWords; ++i) {
  1276. uint64_t tmp = RHS[i];
  1277. V[i * 2] = Lo_32(tmp);
  1278. V[i * 2 + 1] = Hi_32(tmp);
  1279. }
  1280. // initialize the quotient and remainder
  1281. memset(Q, 0, (m+n) * sizeof(uint32_t));
  1282. if (Remainder)
  1283. memset(R, 0, n * sizeof(uint32_t));
  1284. // Now, adjust m and n for the Knuth division. n is the number of words in
  1285. // the divisor. m is the number of words by which the dividend exceeds the
  1286. // divisor (i.e. m+n is the length of the dividend). These sizes must not
  1287. // contain any zero words or the Knuth algorithm fails.
  1288. for (unsigned i = n; i > 0 && V[i-1] == 0; i--) {
  1289. n--;
  1290. m++;
  1291. }
  1292. for (unsigned i = m+n; i > 0 && U[i-1] == 0; i--)
  1293. m--;
  1294. // If we're left with only a single word for the divisor, Knuth doesn't work
  1295. // so we implement the short division algorithm here. This is much simpler
  1296. // and faster because we are certain that we can divide a 64-bit quantity
  1297. // by a 32-bit quantity at hardware speed and short division is simply a
  1298. // series of such operations. This is just like doing short division but we
  1299. // are using base 2^32 instead of base 10.
  1300. assert(n != 0 && "Divide by zero?");
  1301. if (n == 1) {
  1302. uint32_t divisor = V[0];
  1303. uint32_t remainder = 0;
  1304. for (int i = m; i >= 0; i--) {
  1305. uint64_t partial_dividend = Make_64(remainder, U[i]);
  1306. if (partial_dividend == 0) {
  1307. Q[i] = 0;
  1308. remainder = 0;
  1309. } else if (partial_dividend < divisor) {
  1310. Q[i] = 0;
  1311. remainder = Lo_32(partial_dividend);
  1312. } else if (partial_dividend == divisor) {
  1313. Q[i] = 1;
  1314. remainder = 0;
  1315. } else {
  1316. Q[i] = Lo_32(partial_dividend / divisor);
  1317. remainder = Lo_32(partial_dividend - (Q[i] * divisor));
  1318. }
  1319. }
  1320. if (R)
  1321. R[0] = remainder;
  1322. } else {
  1323. // Now we're ready to invoke the Knuth classical divide algorithm. In this
  1324. // case n > 1.
  1325. KnuthDiv(U, V, Q, R, m, n);
  1326. }
  1327. // If the caller wants the quotient
  1328. if (Quotient) {
  1329. for (unsigned i = 0; i < lhsWords; ++i)
  1330. Quotient[i] = Make_64(Q[i*2+1], Q[i*2]);
  1331. }
  1332. // If the caller wants the remainder
  1333. if (Remainder) {
  1334. for (unsigned i = 0; i < rhsWords; ++i)
  1335. Remainder[i] = Make_64(R[i*2+1], R[i*2]);
  1336. }
  1337. // Clean up the memory we allocated.
  1338. if (U != &SPACE[0]) {
  1339. delete [] U;
  1340. delete [] V;
  1341. delete [] Q;
  1342. delete [] R;
  1343. }
  1344. }
  1345. APInt APInt::udiv(const APInt &RHS) const {
  1346. assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
  1347. // First, deal with the easy case
  1348. if (isSingleWord()) {
  1349. assert(RHS.U.VAL != 0 && "Divide by zero?");
  1350. return APInt(BitWidth, U.VAL / RHS.U.VAL);
  1351. }
  1352. // Get some facts about the LHS and RHS number of bits and words
  1353. unsigned lhsWords = getNumWords(getActiveBits());
  1354. unsigned rhsBits = RHS.getActiveBits();
  1355. unsigned rhsWords = getNumWords(rhsBits);
  1356. assert(rhsWords && "Divided by zero???");
  1357. // Deal with some degenerate cases
  1358. if (!lhsWords)
  1359. // 0 / X ===> 0
  1360. return APInt(BitWidth, 0);
  1361. if (rhsBits == 1)
  1362. // X / 1 ===> X
  1363. return *this;
  1364. if (lhsWords < rhsWords || this->ult(RHS))
  1365. // X / Y ===> 0, iff X < Y
  1366. return APInt(BitWidth, 0);
  1367. if (*this == RHS)
  1368. // X / X ===> 1
  1369. return APInt(BitWidth, 1);
  1370. if (lhsWords == 1) // rhsWords is 1 if lhsWords is 1.
  1371. // All high words are zero, just use native divide
  1372. return APInt(BitWidth, this->U.pVal[0] / RHS.U.pVal[0]);
  1373. // We have to compute it the hard way. Invoke the Knuth divide algorithm.
  1374. APInt Quotient(BitWidth, 0); // to hold result.
  1375. divide(U.pVal, lhsWords, RHS.U.pVal, rhsWords, Quotient.U.pVal, nullptr);
  1376. return Quotient;
  1377. }
  1378. APInt APInt::udiv(uint64_t RHS) const {
  1379. assert(RHS != 0 && "Divide by zero?");
  1380. // First, deal with the easy case
  1381. if (isSingleWord())
  1382. return APInt(BitWidth, U.VAL / RHS);
  1383. // Get some facts about the LHS words.
  1384. unsigned lhsWords = getNumWords(getActiveBits());
  1385. // Deal with some degenerate cases
  1386. if (!lhsWords)
  1387. // 0 / X ===> 0
  1388. return APInt(BitWidth, 0);
  1389. if (RHS == 1)
  1390. // X / 1 ===> X
  1391. return *this;
  1392. if (this->ult(RHS))
  1393. // X / Y ===> 0, iff X < Y
  1394. return APInt(BitWidth, 0);
  1395. if (*this == RHS)
  1396. // X / X ===> 1
  1397. return APInt(BitWidth, 1);
  1398. if (lhsWords == 1) // rhsWords is 1 if lhsWords is 1.
  1399. // All high words are zero, just use native divide
  1400. return APInt(BitWidth, this->U.pVal[0] / RHS);
  1401. // We have to compute it the hard way. Invoke the Knuth divide algorithm.
  1402. APInt Quotient(BitWidth, 0); // to hold result.
  1403. divide(U.pVal, lhsWords, &RHS, 1, Quotient.U.pVal, nullptr);
  1404. return Quotient;
  1405. }
  1406. APInt APInt::sdiv(const APInt &RHS) const {
  1407. if (isNegative()) {
  1408. if (RHS.isNegative())
  1409. return (-(*this)).udiv(-RHS);
  1410. return -((-(*this)).udiv(RHS));
  1411. }
  1412. if (RHS.isNegative())
  1413. return -(this->udiv(-RHS));
  1414. return this->udiv(RHS);
  1415. }
  1416. APInt APInt::sdiv(int64_t RHS) const {
  1417. if (isNegative()) {
  1418. if (RHS < 0)
  1419. return (-(*this)).udiv(-RHS);
  1420. return -((-(*this)).udiv(RHS));
  1421. }
  1422. if (RHS < 0)
  1423. return -(this->udiv(-RHS));
  1424. return this->udiv(RHS);
  1425. }
  1426. APInt APInt::urem(const APInt &RHS) const {
  1427. assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
  1428. if (isSingleWord()) {
  1429. assert(RHS.U.VAL != 0 && "Remainder by zero?");
  1430. return APInt(BitWidth, U.VAL % RHS.U.VAL);
  1431. }
  1432. // Get some facts about the LHS
  1433. unsigned lhsWords = getNumWords(getActiveBits());
  1434. // Get some facts about the RHS
  1435. unsigned rhsBits = RHS.getActiveBits();
  1436. unsigned rhsWords = getNumWords(rhsBits);
  1437. assert(rhsWords && "Performing remainder operation by zero ???");
  1438. // Check the degenerate cases
  1439. if (lhsWords == 0)
  1440. // 0 % Y ===> 0
  1441. return APInt(BitWidth, 0);
  1442. if (rhsBits == 1)
  1443. // X % 1 ===> 0
  1444. return APInt(BitWidth, 0);
  1445. if (lhsWords < rhsWords || this->ult(RHS))
  1446. // X % Y ===> X, iff X < Y
  1447. return *this;
  1448. if (*this == RHS)
  1449. // X % X == 0;
  1450. return APInt(BitWidth, 0);
  1451. if (lhsWords == 1)
  1452. // All high words are zero, just use native remainder
  1453. return APInt(BitWidth, U.pVal[0] % RHS.U.pVal[0]);
  1454. // We have to compute it the hard way. Invoke the Knuth divide algorithm.
  1455. APInt Remainder(BitWidth, 0);
  1456. divide(U.pVal, lhsWords, RHS.U.pVal, rhsWords, nullptr, Remainder.U.pVal);
  1457. return Remainder;
  1458. }
  1459. uint64_t APInt::urem(uint64_t RHS) const {
  1460. assert(RHS != 0 && "Remainder by zero?");
  1461. if (isSingleWord())
  1462. return U.VAL % RHS;
  1463. // Get some facts about the LHS
  1464. unsigned lhsWords = getNumWords(getActiveBits());
  1465. // Check the degenerate cases
  1466. if (lhsWords == 0)
  1467. // 0 % Y ===> 0
  1468. return 0;
  1469. if (RHS == 1)
  1470. // X % 1 ===> 0
  1471. return 0;
  1472. if (this->ult(RHS))
  1473. // X % Y ===> X, iff X < Y
  1474. return getZExtValue();
  1475. if (*this == RHS)
  1476. // X % X == 0;
  1477. return 0;
  1478. if (lhsWords == 1)
  1479. // All high words are zero, just use native remainder
  1480. return U.pVal[0] % RHS;
  1481. // We have to compute it the hard way. Invoke the Knuth divide algorithm.
  1482. uint64_t Remainder;
  1483. divide(U.pVal, lhsWords, &RHS, 1, nullptr, &Remainder);
  1484. return Remainder;
  1485. }
  1486. APInt APInt::srem(const APInt &RHS) const {
  1487. if (isNegative()) {
  1488. if (RHS.isNegative())
  1489. return -((-(*this)).urem(-RHS));
  1490. return -((-(*this)).urem(RHS));
  1491. }
  1492. if (RHS.isNegative())
  1493. return this->urem(-RHS);
  1494. return this->urem(RHS);
  1495. }
  1496. int64_t APInt::srem(int64_t RHS) const {
  1497. if (isNegative()) {
  1498. if (RHS < 0)
  1499. return -((-(*this)).urem(-RHS));
  1500. return -((-(*this)).urem(RHS));
  1501. }
  1502. if (RHS < 0)
  1503. return this->urem(-RHS);
  1504. return this->urem(RHS);
  1505. }
  1506. void APInt::udivrem(const APInt &LHS, const APInt &RHS,
  1507. APInt &Quotient, APInt &Remainder) {
  1508. assert(LHS.BitWidth == RHS.BitWidth && "Bit widths must be the same");
  1509. unsigned BitWidth = LHS.BitWidth;
  1510. // First, deal with the easy case
  1511. if (LHS.isSingleWord()) {
  1512. assert(RHS.U.VAL != 0 && "Divide by zero?");
  1513. uint64_t QuotVal = LHS.U.VAL / RHS.U.VAL;
  1514. uint64_t RemVal = LHS.U.VAL % RHS.U.VAL;
  1515. Quotient = APInt(BitWidth, QuotVal);
  1516. Remainder = APInt(BitWidth, RemVal);
  1517. return;
  1518. }
  1519. // Get some size facts about the dividend and divisor
  1520. unsigned lhsWords = getNumWords(LHS.getActiveBits());
  1521. unsigned rhsBits = RHS.getActiveBits();
  1522. unsigned rhsWords = getNumWords(rhsBits);
  1523. assert(rhsWords && "Performing divrem operation by zero ???");
  1524. // Check the degenerate cases
  1525. if (lhsWords == 0) {
  1526. Quotient = APInt(BitWidth, 0); // 0 / Y ===> 0
  1527. Remainder = APInt(BitWidth, 0); // 0 % Y ===> 0
  1528. return;
  1529. }
  1530. if (rhsBits == 1) {
  1531. Quotient = LHS; // X / 1 ===> X
  1532. Remainder = APInt(BitWidth, 0); // X % 1 ===> 0
  1533. }
  1534. if (lhsWords < rhsWords || LHS.ult(RHS)) {
  1535. Remainder = LHS; // X % Y ===> X, iff X < Y
  1536. Quotient = APInt(BitWidth, 0); // X / Y ===> 0, iff X < Y
  1537. return;
  1538. }
  1539. if (LHS == RHS) {
  1540. Quotient = APInt(BitWidth, 1); // X / X ===> 1
  1541. Remainder = APInt(BitWidth, 0); // X % X ===> 0;
  1542. return;
  1543. }
  1544. // Make sure there is enough space to hold the results.
  1545. // NOTE: This assumes that reallocate won't affect any bits if it doesn't
  1546. // change the size. This is necessary if Quotient or Remainder is aliased
  1547. // with LHS or RHS.
  1548. Quotient.reallocate(BitWidth);
  1549. Remainder.reallocate(BitWidth);
  1550. if (lhsWords == 1) { // rhsWords is 1 if lhsWords is 1.
  1551. // There is only one word to consider so use the native versions.
  1552. uint64_t lhsValue = LHS.U.pVal[0];
  1553. uint64_t rhsValue = RHS.U.pVal[0];
  1554. Quotient = lhsValue / rhsValue;
  1555. Remainder = lhsValue % rhsValue;
  1556. return;
  1557. }
  1558. // Okay, lets do it the long way
  1559. divide(LHS.U.pVal, lhsWords, RHS.U.pVal, rhsWords, Quotient.U.pVal,
  1560. Remainder.U.pVal);
  1561. // Clear the rest of the Quotient and Remainder.
  1562. std::memset(Quotient.U.pVal + lhsWords, 0,
  1563. (getNumWords(BitWidth) - lhsWords) * APINT_WORD_SIZE);
  1564. std::memset(Remainder.U.pVal + rhsWords, 0,
  1565. (getNumWords(BitWidth) - rhsWords) * APINT_WORD_SIZE);
  1566. }
  1567. void APInt::udivrem(const APInt &LHS, uint64_t RHS, APInt &Quotient,
  1568. uint64_t &Remainder) {
  1569. assert(RHS != 0 && "Divide by zero?");
  1570. unsigned BitWidth = LHS.BitWidth;
  1571. // First, deal with the easy case
  1572. if (LHS.isSingleWord()) {
  1573. uint64_t QuotVal = LHS.U.VAL / RHS;
  1574. Remainder = LHS.U.VAL % RHS;
  1575. Quotient = APInt(BitWidth, QuotVal);
  1576. return;
  1577. }
  1578. // Get some size facts about the dividend and divisor
  1579. unsigned lhsWords = getNumWords(LHS.getActiveBits());
  1580. // Check the degenerate cases
  1581. if (lhsWords == 0) {
  1582. Quotient = APInt(BitWidth, 0); // 0 / Y ===> 0
  1583. Remainder = 0; // 0 % Y ===> 0
  1584. return;
  1585. }
  1586. if (RHS == 1) {
  1587. Quotient = LHS; // X / 1 ===> X
  1588. Remainder = 0; // X % 1 ===> 0
  1589. return;
  1590. }
  1591. if (LHS.ult(RHS)) {
  1592. Remainder = LHS.getZExtValue(); // X % Y ===> X, iff X < Y
  1593. Quotient = APInt(BitWidth, 0); // X / Y ===> 0, iff X < Y
  1594. return;
  1595. }
  1596. if (LHS == RHS) {
  1597. Quotient = APInt(BitWidth, 1); // X / X ===> 1
  1598. Remainder = 0; // X % X ===> 0;
  1599. return;
  1600. }
  1601. // Make sure there is enough space to hold the results.
  1602. // NOTE: This assumes that reallocate won't affect any bits if it doesn't
  1603. // change the size. This is necessary if Quotient is aliased with LHS.
  1604. Quotient.reallocate(BitWidth);
  1605. if (lhsWords == 1) { // rhsWords is 1 if lhsWords is 1.
  1606. // There is only one word to consider so use the native versions.
  1607. uint64_t lhsValue = LHS.U.pVal[0];
  1608. Quotient = lhsValue / RHS;
  1609. Remainder = lhsValue % RHS;
  1610. return;
  1611. }
  1612. // Okay, lets do it the long way
  1613. divide(LHS.U.pVal, lhsWords, &RHS, 1, Quotient.U.pVal, &Remainder);
  1614. // Clear the rest of the Quotient.
  1615. std::memset(Quotient.U.pVal + lhsWords, 0,
  1616. (getNumWords(BitWidth) - lhsWords) * APINT_WORD_SIZE);
  1617. }
  1618. void APInt::sdivrem(const APInt &LHS, const APInt &RHS,
  1619. APInt &Quotient, APInt &Remainder) {
  1620. if (LHS.isNegative()) {
  1621. if (RHS.isNegative())
  1622. APInt::udivrem(-LHS, -RHS, Quotient, Remainder);
  1623. else {
  1624. APInt::udivrem(-LHS, RHS, Quotient, Remainder);
  1625. Quotient.negate();
  1626. }
  1627. Remainder.negate();
  1628. } else if (RHS.isNegative()) {
  1629. APInt::udivrem(LHS, -RHS, Quotient, Remainder);
  1630. Quotient.negate();
  1631. } else {
  1632. APInt::udivrem(LHS, RHS, Quotient, Remainder);
  1633. }
  1634. }
  1635. void APInt::sdivrem(const APInt &LHS, int64_t RHS,
  1636. APInt &Quotient, int64_t &Remainder) {
  1637. uint64_t R = Remainder;
  1638. if (LHS.isNegative()) {
  1639. if (RHS < 0)
  1640. APInt::udivrem(-LHS, -RHS, Quotient, R);
  1641. else {
  1642. APInt::udivrem(-LHS, RHS, Quotient, R);
  1643. Quotient.negate();
  1644. }
  1645. R = -R;
  1646. } else if (RHS < 0) {
  1647. APInt::udivrem(LHS, -RHS, Quotient, R);
  1648. Quotient.negate();
  1649. } else {
  1650. APInt::udivrem(LHS, RHS, Quotient, R);
  1651. }
  1652. Remainder = R;
  1653. }
  1654. APInt APInt::sadd_ov(const APInt &RHS, bool &Overflow) const {
  1655. APInt Res = *this+RHS;
  1656. Overflow = isNonNegative() == RHS.isNonNegative() &&
  1657. Res.isNonNegative() != isNonNegative();
  1658. return Res;
  1659. }
  1660. APInt APInt::uadd_ov(const APInt &RHS, bool &Overflow) const {
  1661. APInt Res = *this+RHS;
  1662. Overflow = Res.ult(RHS);
  1663. return Res;
  1664. }
  1665. APInt APInt::ssub_ov(const APInt &RHS, bool &Overflow) const {
  1666. APInt Res = *this - RHS;
  1667. Overflow = isNonNegative() != RHS.isNonNegative() &&
  1668. Res.isNonNegative() != isNonNegative();
  1669. return Res;
  1670. }
  1671. APInt APInt::usub_ov(const APInt &RHS, bool &Overflow) const {
  1672. APInt Res = *this-RHS;
  1673. Overflow = Res.ugt(*this);
  1674. return Res;
  1675. }
  1676. APInt APInt::sdiv_ov(const APInt &RHS, bool &Overflow) const {
  1677. // MININT/-1 --> overflow.
  1678. Overflow = isMinSignedValue() && RHS.isAllOnes();
  1679. return sdiv(RHS);
  1680. }
  1681. APInt APInt::smul_ov(const APInt &RHS, bool &Overflow) const {
  1682. APInt Res = *this * RHS;
  1683. if (RHS != 0)
  1684. Overflow = Res.sdiv(RHS) != *this ||
  1685. (isMinSignedValue() && RHS.isAllOnes());
  1686. else
  1687. Overflow = false;
  1688. return Res;
  1689. }
  1690. APInt APInt::umul_ov(const APInt &RHS, bool &Overflow) const {
  1691. if (countLeadingZeros() + RHS.countLeadingZeros() + 2 <= BitWidth) {
  1692. Overflow = true;
  1693. return *this * RHS;
  1694. }
  1695. APInt Res = lshr(1) * RHS;
  1696. Overflow = Res.isNegative();
  1697. Res <<= 1;
  1698. if ((*this)[0]) {
  1699. Res += RHS;
  1700. if (Res.ult(RHS))
  1701. Overflow = true;
  1702. }
  1703. return Res;
  1704. }
  1705. APInt APInt::sshl_ov(const APInt &ShAmt, bool &Overflow) const {
  1706. Overflow = ShAmt.uge(getBitWidth());
  1707. if (Overflow)
  1708. return APInt(BitWidth, 0);
  1709. if (isNonNegative()) // Don't allow sign change.
  1710. Overflow = ShAmt.uge(countLeadingZeros());
  1711. else
  1712. Overflow = ShAmt.uge(countLeadingOnes());
  1713. return *this << ShAmt;
  1714. }
  1715. APInt APInt::ushl_ov(const APInt &ShAmt, bool &Overflow) const {
  1716. Overflow = ShAmt.uge(getBitWidth());
  1717. if (Overflow)
  1718. return APInt(BitWidth, 0);
  1719. Overflow = ShAmt.ugt(countLeadingZeros());
  1720. return *this << ShAmt;
  1721. }
  1722. APInt APInt::sadd_sat(const APInt &RHS) const {
  1723. bool Overflow;
  1724. APInt Res = sadd_ov(RHS, Overflow);
  1725. if (!Overflow)
  1726. return Res;
  1727. return isNegative() ? APInt::getSignedMinValue(BitWidth)
  1728. : APInt::getSignedMaxValue(BitWidth);
  1729. }
  1730. APInt APInt::uadd_sat(const APInt &RHS) const {
  1731. bool Overflow;
  1732. APInt Res = uadd_ov(RHS, Overflow);
  1733. if (!Overflow)
  1734. return Res;
  1735. return APInt::getMaxValue(BitWidth);
  1736. }
  1737. APInt APInt::ssub_sat(const APInt &RHS) const {
  1738. bool Overflow;
  1739. APInt Res = ssub_ov(RHS, Overflow);
  1740. if (!Overflow)
  1741. return Res;
  1742. return isNegative() ? APInt::getSignedMinValue(BitWidth)
  1743. : APInt::getSignedMaxValue(BitWidth);
  1744. }
  1745. APInt APInt::usub_sat(const APInt &RHS) const {
  1746. bool Overflow;
  1747. APInt Res = usub_ov(RHS, Overflow);
  1748. if (!Overflow)
  1749. return Res;
  1750. return APInt(BitWidth, 0);
  1751. }
  1752. APInt APInt::smul_sat(const APInt &RHS) const {
  1753. bool Overflow;
  1754. APInt Res = smul_ov(RHS, Overflow);
  1755. if (!Overflow)
  1756. return Res;
  1757. // The result is negative if one and only one of inputs is negative.
  1758. bool ResIsNegative = isNegative() ^ RHS.isNegative();
  1759. return ResIsNegative ? APInt::getSignedMinValue(BitWidth)
  1760. : APInt::getSignedMaxValue(BitWidth);
  1761. }
  1762. APInt APInt::umul_sat(const APInt &RHS) const {
  1763. bool Overflow;
  1764. APInt Res = umul_ov(RHS, Overflow);
  1765. if (!Overflow)
  1766. return Res;
  1767. return APInt::getMaxValue(BitWidth);
  1768. }
  1769. APInt APInt::sshl_sat(const APInt &RHS) const {
  1770. bool Overflow;
  1771. APInt Res = sshl_ov(RHS, Overflow);
  1772. if (!Overflow)
  1773. return Res;
  1774. return isNegative() ? APInt::getSignedMinValue(BitWidth)
  1775. : APInt::getSignedMaxValue(BitWidth);
  1776. }
  1777. APInt APInt::ushl_sat(const APInt &RHS) const {
  1778. bool Overflow;
  1779. APInt Res = ushl_ov(RHS, Overflow);
  1780. if (!Overflow)
  1781. return Res;
  1782. return APInt::getMaxValue(BitWidth);
  1783. }
  1784. void APInt::fromString(unsigned numbits, StringRef str, uint8_t radix) {
  1785. // Check our assumptions here
  1786. assert(!str.empty() && "Invalid string length");
  1787. assert((radix == 10 || radix == 8 || radix == 16 || radix == 2 ||
  1788. radix == 36) &&
  1789. "Radix should be 2, 8, 10, 16, or 36!");
  1790. StringRef::iterator p = str.begin();
  1791. size_t slen = str.size();
  1792. bool isNeg = *p == '-';
  1793. if (*p == '-' || *p == '+') {
  1794. p++;
  1795. slen--;
  1796. assert(slen && "String is only a sign, needs a value.");
  1797. }
  1798. assert((slen <= numbits || radix != 2) && "Insufficient bit width");
  1799. assert(((slen-1)*3 <= numbits || radix != 8) && "Insufficient bit width");
  1800. assert(((slen-1)*4 <= numbits || radix != 16) && "Insufficient bit width");
  1801. assert((((slen-1)*64)/22 <= numbits || radix != 10) &&
  1802. "Insufficient bit width");
  1803. // Allocate memory if needed
  1804. if (isSingleWord())
  1805. U.VAL = 0;
  1806. else
  1807. U.pVal = getClearedMemory(getNumWords());
  1808. // Figure out if we can shift instead of multiply
  1809. unsigned shift = (radix == 16 ? 4 : radix == 8 ? 3 : radix == 2 ? 1 : 0);
  1810. // Enter digit traversal loop
  1811. for (StringRef::iterator e = str.end(); p != e; ++p) {
  1812. unsigned digit = getDigit(*p, radix);
  1813. assert(digit < radix && "Invalid character in digit string");
  1814. // Shift or multiply the value by the radix
  1815. if (slen > 1) {
  1816. if (shift)
  1817. *this <<= shift;
  1818. else
  1819. *this *= radix;
  1820. }
  1821. // Add in the digit we just interpreted
  1822. *this += digit;
  1823. }
  1824. // If its negative, put it in two's complement form
  1825. if (isNeg)
  1826. this->negate();
  1827. }
  1828. void APInt::toString(SmallVectorImpl<char> &Str, unsigned Radix,
  1829. bool Signed, bool formatAsCLiteral) const {
  1830. assert((Radix == 10 || Radix == 8 || Radix == 16 || Radix == 2 ||
  1831. Radix == 36) &&
  1832. "Radix should be 2, 8, 10, 16, or 36!");
  1833. const char *Prefix = "";
  1834. if (formatAsCLiteral) {
  1835. switch (Radix) {
  1836. case 2:
  1837. // Binary literals are a non-standard extension added in gcc 4.3:
  1838. // http://gcc.gnu.org/onlinedocs/gcc-4.3.0/gcc/Binary-constants.html
  1839. Prefix = "0b";
  1840. break;
  1841. case 8:
  1842. Prefix = "0";
  1843. break;
  1844. case 10:
  1845. break; // No prefix
  1846. case 16:
  1847. Prefix = "0x";
  1848. break;
  1849. default:
  1850. llvm_unreachable("Invalid radix!");
  1851. }
  1852. }
  1853. // First, check for a zero value and just short circuit the logic below.
  1854. if (isZero()) {
  1855. while (*Prefix) {
  1856. Str.push_back(*Prefix);
  1857. ++Prefix;
  1858. };
  1859. Str.push_back('0');
  1860. return;
  1861. }
  1862. static const char Digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  1863. if (isSingleWord()) {
  1864. char Buffer[65];
  1865. char *BufPtr = std::end(Buffer);
  1866. uint64_t N;
  1867. if (!Signed) {
  1868. N = getZExtValue();
  1869. } else {
  1870. int64_t I = getSExtValue();
  1871. if (I >= 0) {
  1872. N = I;
  1873. } else {
  1874. Str.push_back('-');
  1875. N = -(uint64_t)I;
  1876. }
  1877. }
  1878. while (*Prefix) {
  1879. Str.push_back(*Prefix);
  1880. ++Prefix;
  1881. };
  1882. while (N) {
  1883. *--BufPtr = Digits[N % Radix];
  1884. N /= Radix;
  1885. }
  1886. Str.append(BufPtr, std::end(Buffer));
  1887. return;
  1888. }
  1889. APInt Tmp(*this);
  1890. if (Signed && isNegative()) {
  1891. // They want to print the signed version and it is a negative value
  1892. // Flip the bits and add one to turn it into the equivalent positive
  1893. // value and put a '-' in the result.
  1894. Tmp.negate();
  1895. Str.push_back('-');
  1896. }
  1897. while (*Prefix) {
  1898. Str.push_back(*Prefix);
  1899. ++Prefix;
  1900. };
  1901. // We insert the digits backward, then reverse them to get the right order.
  1902. unsigned StartDig = Str.size();
  1903. // For the 2, 8 and 16 bit cases, we can just shift instead of divide
  1904. // because the number of bits per digit (1, 3 and 4 respectively) divides
  1905. // equally. We just shift until the value is zero.
  1906. if (Radix == 2 || Radix == 8 || Radix == 16) {
  1907. // Just shift tmp right for each digit width until it becomes zero
  1908. unsigned ShiftAmt = (Radix == 16 ? 4 : (Radix == 8 ? 3 : 1));
  1909. unsigned MaskAmt = Radix - 1;
  1910. while (Tmp.getBoolValue()) {
  1911. unsigned Digit = unsigned(Tmp.getRawData()[0]) & MaskAmt;
  1912. Str.push_back(Digits[Digit]);
  1913. Tmp.lshrInPlace(ShiftAmt);
  1914. }
  1915. } else {
  1916. while (Tmp.getBoolValue()) {
  1917. uint64_t Digit;
  1918. udivrem(Tmp, Radix, Tmp, Digit);
  1919. assert(Digit < Radix && "divide failed");
  1920. Str.push_back(Digits[Digit]);
  1921. }
  1922. }
  1923. // Reverse the digits before returning.
  1924. std::reverse(Str.begin()+StartDig, Str.end());
  1925. }
  1926. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  1927. LLVM_DUMP_METHOD void APInt::dump() const {
  1928. SmallString<40> S, U;
  1929. this->toStringUnsigned(U);
  1930. this->toStringSigned(S);
  1931. dbgs() << "APInt(" << BitWidth << "b, "
  1932. << U << "u " << S << "s)\n";
  1933. }
  1934. #endif
  1935. void APInt::print(raw_ostream &OS, bool isSigned) const {
  1936. SmallString<40> S;
  1937. this->toString(S, 10, isSigned, /* formatAsCLiteral = */false);
  1938. OS << S;
  1939. }
  1940. // This implements a variety of operations on a representation of
  1941. // arbitrary precision, two's-complement, bignum integer values.
  1942. // Assumed by lowHalf, highHalf, partMSB and partLSB. A fairly safe
  1943. // and unrestricting assumption.
  1944. static_assert(APInt::APINT_BITS_PER_WORD % 2 == 0,
  1945. "Part width must be divisible by 2!");
  1946. // Returns the integer part with the least significant BITS set.
  1947. // BITS cannot be zero.
  1948. static inline APInt::WordType lowBitMask(unsigned bits) {
  1949. assert(bits != 0 && bits <= APInt::APINT_BITS_PER_WORD);
  1950. return ~(APInt::WordType) 0 >> (APInt::APINT_BITS_PER_WORD - bits);
  1951. }
  1952. /// Returns the value of the lower half of PART.
  1953. static inline APInt::WordType lowHalf(APInt::WordType part) {
  1954. return part & lowBitMask(APInt::APINT_BITS_PER_WORD / 2);
  1955. }
  1956. /// Returns the value of the upper half of PART.
  1957. static inline APInt::WordType highHalf(APInt::WordType part) {
  1958. return part >> (APInt::APINT_BITS_PER_WORD / 2);
  1959. }
  1960. /// Returns the bit number of the most significant set bit of a part.
  1961. /// If the input number has no bits set -1U is returned.
  1962. static unsigned partMSB(APInt::WordType value) { return findLastSet(value); }
  1963. /// Returns the bit number of the least significant set bit of a part. If the
  1964. /// input number has no bits set -1U is returned.
  1965. static unsigned partLSB(APInt::WordType value) { return findFirstSet(value); }
  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. std::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 std::nullopt;
  2532. }
  2533. X += 1;
  2534. LLVM_DEBUG(dbgs() << __func__ << ": solution (wrap): " << X << '\n');
  2535. return X;
  2536. }
  2537. std::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 std::nullopt;
  2542. return A.getBitWidth() - ((A ^ B).countLeadingZeros() + 1);
  2543. }
  2544. APInt llvm::APIntOps::ScaleBitMask(const APInt &A, unsigned NewBitWidth,
  2545. bool MatchAllBits) {
  2546. unsigned OldBitWidth = A.getBitWidth();
  2547. assert((((OldBitWidth % NewBitWidth) == 0) ||
  2548. ((NewBitWidth % OldBitWidth) == 0)) &&
  2549. "One size should be a multiple of the other one. "
  2550. "Can't do fractional scaling.");
  2551. // Check for matching bitwidths.
  2552. if (OldBitWidth == NewBitWidth)
  2553. return A;
  2554. APInt NewA = APInt::getZero(NewBitWidth);
  2555. // Check for null input.
  2556. if (A.isZero())
  2557. return NewA;
  2558. if (NewBitWidth > OldBitWidth) {
  2559. // Repeat bits.
  2560. unsigned Scale = NewBitWidth / OldBitWidth;
  2561. for (unsigned i = 0; i != OldBitWidth; ++i)
  2562. if (A[i])
  2563. NewA.setBits(i * Scale, (i + 1) * Scale);
  2564. } else {
  2565. unsigned Scale = OldBitWidth / NewBitWidth;
  2566. for (unsigned i = 0; i != NewBitWidth; ++i) {
  2567. if (MatchAllBits) {
  2568. if (A.extractBits(Scale, i * Scale).isAllOnes())
  2569. NewA.setBit(i);
  2570. } else {
  2571. if (!A.extractBits(Scale, i * Scale).isZero())
  2572. NewA.setBit(i);
  2573. }
  2574. }
  2575. }
  2576. return NewA;
  2577. }
  2578. /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
  2579. /// with the integer held in IntVal.
  2580. void llvm::StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
  2581. unsigned StoreBytes) {
  2582. assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
  2583. const uint8_t *Src = (const uint8_t *)IntVal.getRawData();
  2584. if (sys::IsLittleEndianHost) {
  2585. // Little-endian host - the source is ordered from LSB to MSB. Order the
  2586. // destination from LSB to MSB: Do a straight copy.
  2587. memcpy(Dst, Src, StoreBytes);
  2588. } else {
  2589. // Big-endian host - the source is an array of 64 bit words ordered from
  2590. // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
  2591. // from MSB to LSB: Reverse the word order, but not the bytes in a word.
  2592. while (StoreBytes > sizeof(uint64_t)) {
  2593. StoreBytes -= sizeof(uint64_t);
  2594. // May not be aligned so use memcpy.
  2595. memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
  2596. Src += sizeof(uint64_t);
  2597. }
  2598. memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
  2599. }
  2600. }
  2601. /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
  2602. /// from Src into IntVal, which is assumed to be wide enough and to hold zero.
  2603. void llvm::LoadIntFromMemory(APInt &IntVal, const uint8_t *Src,
  2604. unsigned LoadBytes) {
  2605. assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
  2606. uint8_t *Dst = reinterpret_cast<uint8_t *>(
  2607. const_cast<uint64_t *>(IntVal.getRawData()));
  2608. if (sys::IsLittleEndianHost)
  2609. // Little-endian host - the destination must be ordered from LSB to MSB.
  2610. // The source is ordered from LSB to MSB: Do a straight copy.
  2611. memcpy(Dst, Src, LoadBytes);
  2612. else {
  2613. // Big-endian - the destination is an array of 64 bit words ordered from
  2614. // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
  2615. // ordered from MSB to LSB: Reverse the word order, but not the bytes in
  2616. // a word.
  2617. while (LoadBytes > sizeof(uint64_t)) {
  2618. LoadBytes -= sizeof(uint64_t);
  2619. // May not be aligned so use memcpy.
  2620. memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
  2621. Dst += sizeof(uint64_t);
  2622. }
  2623. memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
  2624. }
  2625. }