Movatterモバイル変換


[0]ホーム

URL:


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

Generated on Thu Jul 17 2025 12:37:19 for LLVM by doxygen 1.9.6
[8]ページ先頭

©2009-2025 Movatter.jp