APInt.cpp 87 KB

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