This repository was archived by the owner on Nov 1, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 112
/
Copy pathAPInt.cpp
2913 lines (2508 loc) · 87.5 KB
/
APInt.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===-- APInt.cpp - Implement APInt class ---------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements a class to represent arbitrary precision integer
// constant values and provide a variety of arithmetic operations on them.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/FoldingSet.h"
#include "llvm/ADT/Hashing.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/raw_ostream.h"
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <limits>
using namespace llvm;
#define DEBUG_TYPE "apint"
/// A utility function for allocating memory, checking for allocation failures,
/// and ensuring the contents are zeroed.
inline static uint64_t* getClearedMemory(unsigned numWords) {
uint64_t * result = new uint64_t[numWords];
assert(result && "APInt memory allocation fails!");
memset(result, 0, numWords * sizeof(uint64_t));
return result;
}
/// A utility function for allocating memory and checking for allocation
/// failure. The content is not zeroed.
inline static uint64_t* getMemory(unsigned numWords) {
uint64_t * result = new uint64_t[numWords];
assert(result && "APInt memory allocation fails!");
return result;
}
/// A utility function that converts a character to a digit.
inline static unsigned getDigit(char cdigit, uint8_t radix) {
unsigned r;
if (radix == 16 || radix == 36) {
r = cdigit - '0';
if (r <= 9)
return r;
r = cdigit - 'A';
if (r <= radix - 11U)
return r + 10;
r = cdigit - 'a';
if (r <= radix - 11U)
return r + 10;
radix = 10;
}
r = cdigit - '0';
if (r < radix)
return r;
return -1U;
}
void APInt::initSlowCase(uint64_t val, bool isSigned) {
pVal = getClearedMemory(getNumWords());
pVal[0] = val;
if (isSigned && int64_t(val) < 0)
for (unsigned i = 1; i < getNumWords(); ++i)
pVal[i] = -1ULL;
}
void APInt::initSlowCase(const APInt& that) {
pVal = getMemory(getNumWords());
memcpy(pVal, that.pVal, getNumWords() * APINT_WORD_SIZE);
}
void APInt::initFromArray(ArrayRef<uint64_t> bigVal) {
assert(BitWidth && "Bitwidth too small");
assert(bigVal.data() && "Null pointer detected!");
if (isSingleWord())
VAL = bigVal[0];
else {
// Get memory, cleared to 0
pVal = getClearedMemory(getNumWords());
// Calculate the number of words to copy
unsigned words = std::min<unsigned>(bigVal.size(), getNumWords());
// Copy the words from bigVal to pVal
memcpy(pVal, bigVal.data(), words * APINT_WORD_SIZE);
}
// Make sure unused high bits are cleared
clearUnusedBits();
}
APInt::APInt(unsigned numBits, ArrayRef<uint64_t> bigVal)
: BitWidth(numBits), VAL(0) {
initFromArray(bigVal);
}
APInt::APInt(unsigned numBits, unsigned numWords, const uint64_t bigVal[])
: BitWidth(numBits), VAL(0) {
initFromArray(makeArrayRef(bigVal, numWords));
}
APInt::APInt(unsigned numbits, StringRef Str, uint8_t radix)
: BitWidth(numbits), VAL(0) {
assert(BitWidth && "Bitwidth too small");
fromString(numbits, Str, radix);
}
APInt& APInt::AssignSlowCase(const APInt& RHS) {
// Don't do anything for X = X
if (this == &RHS)
return *this;
if (BitWidth == RHS.getBitWidth()) {
// assume same bit-width single-word case is already handled
assert(!isSingleWord());
memcpy(pVal, RHS.pVal, getNumWords() * APINT_WORD_SIZE);
return *this;
}
if (isSingleWord()) {
// assume case where both are single words is already handled
assert(!RHS.isSingleWord());
VAL = 0;
pVal = getMemory(RHS.getNumWords());
memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
} else if (getNumWords() == RHS.getNumWords())
memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
else if (RHS.isSingleWord()) {
delete [] pVal;
VAL = RHS.VAL;
} else {
delete [] pVal;
pVal = getMemory(RHS.getNumWords());
memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
}
BitWidth = RHS.BitWidth;
return clearUnusedBits();
}
APInt& APInt::operator=(uint64_t RHS) {
if (isSingleWord())
VAL = RHS;
else {
pVal[0] = RHS;
memset(pVal+1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
}
return clearUnusedBits();
}
/// This method 'profiles' an APInt for use with FoldingSet.
void APInt::Profile(FoldingSetNodeID& ID) const {
ID.AddInteger(BitWidth);
if (isSingleWord()) {
ID.AddInteger(VAL);
return;
}
unsigned NumWords = getNumWords();
for (unsigned i = 0; i < NumWords; ++i)
ID.AddInteger(pVal[i]);
}
/// This function adds a single "digit" integer, y, to the multiple
/// "digit" integer array, x[]. x[] is modified to reflect the addition and
/// 1 is returned if there is a carry out, otherwise 0 is returned.
/// @returns the carry of the addition.
static bool add_1(uint64_t dest[], uint64_t x[], unsigned len, uint64_t y) {
for (unsigned i = 0; i < len; ++i) {
dest[i] = y + x[i];
if (dest[i] < y)
y = 1; // Carry one to next digit.
else {
y = 0; // No need to carry so exit early
break;
}
}
return y;
}
/// @brief Prefix increment operator. Increments the APInt by one.
APInt& APInt::operator++() {
if (isSingleWord())
++VAL;
else
add_1(pVal, pVal, getNumWords(), 1);
return clearUnusedBits();
}
/// This function subtracts a single "digit" (64-bit word), y, from
/// the multi-digit integer array, x[], propagating the borrowed 1 value until
/// no further borrowing is neeeded or it runs out of "digits" in x. The result
/// is 1 if "borrowing" exhausted the digits in x, or 0 if x was not exhausted.
/// In other words, if y > x then this function returns 1, otherwise 0.
/// @returns the borrow out of the subtraction
static bool sub_1(uint64_t x[], unsigned len, uint64_t y) {
for (unsigned i = 0; i < len; ++i) {
uint64_t X = x[i];
x[i] -= y;
if (y > X)
y = 1; // We have to "borrow 1" from next "digit"
else {
y = 0; // No need to borrow
break; // Remaining digits are unchanged so exit early
}
}
return bool(y);
}
/// @brief Prefix decrement operator. Decrements the APInt by one.
APInt& APInt::operator--() {
if (isSingleWord())
--VAL;
else
sub_1(pVal, getNumWords(), 1);
return clearUnusedBits();
}
/// This function adds the integer array x to the integer array Y and
/// places the result in dest.
/// @returns the carry out from the addition
/// @brief General addition of 64-bit integer arrays
static bool add(uint64_t *dest, const uint64_t *x, const uint64_t *y,
unsigned len) {
bool carry = false;
for (unsigned i = 0; i< len; ++i) {
uint64_t limit = std::min(x[i],y[i]); // must come first in case dest == x
dest[i] = x[i] + y[i] + carry;
carry = dest[i] < limit || (carry && dest[i] == limit);
}
return carry;
}
/// Adds the RHS APint to this APInt.
/// @returns this, after addition of RHS.
/// @brief Addition assignment operator.
APInt& APInt::operator+=(const APInt& RHS) {
assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
if (isSingleWord())
VAL += RHS.VAL;
else {
add(pVal, pVal, RHS.pVal, getNumWords());
}
return clearUnusedBits();
}
/// Subtracts the integer array y from the integer array x
/// @returns returns the borrow out.
/// @brief Generalized subtraction of 64-bit integer arrays.
static bool sub(uint64_t *dest, const uint64_t *x, const uint64_t *y,
unsigned len) {
bool borrow = false;
for (unsigned i = 0; i < len; ++i) {
uint64_t x_tmp = borrow ? x[i] - 1 : x[i];
borrow = y[i] > x_tmp || (borrow && x[i] == 0);
dest[i] = x_tmp - y[i];
}
return borrow;
}
/// Subtracts the RHS APInt from this APInt
/// @returns this, after subtraction
/// @brief Subtraction assignment operator.
APInt& APInt::operator-=(const APInt& RHS) {
assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
if (isSingleWord())
VAL -= RHS.VAL;
else
sub(pVal, pVal, RHS.pVal, getNumWords());
return clearUnusedBits();
}
/// Multiplies an integer array, x, by a uint64_t integer and places the result
/// into dest.
/// @returns the carry out of the multiplication.
/// @brief Multiply a multi-digit APInt by a single digit (64-bit) integer.
static uint64_t mul_1(uint64_t dest[], uint64_t x[], unsigned len, uint64_t y) {
// Split y into high 32-bit part (hy) and low 32-bit part (ly)
uint64_t ly = y & 0xffffffffULL, hy = y >> 32;
uint64_t carry = 0;
// For each digit of x.
for (unsigned i = 0; i < len; ++i) {
// Split x into high and low words
uint64_t lx = x[i] & 0xffffffffULL;
uint64_t hx = x[i] >> 32;
// hasCarry - A flag to indicate if there is a carry to the next digit.
// hasCarry == 0, no carry
// hasCarry == 1, has carry
// hasCarry == 2, no carry and the calculation result == 0.
uint8_t hasCarry = 0;
dest[i] = carry + lx * ly;
// Determine if the add above introduces carry.
hasCarry = (dest[i] < carry) ? 1 : 0;
carry = hx * ly + (dest[i] >> 32) + (hasCarry ? (1ULL << 32) : 0);
// The upper limit of carry can be (2^32 - 1)(2^32 - 1) +
// (2^32 - 1) + 2^32 = 2^64.
hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
carry += (lx * hy) & 0xffffffffULL;
dest[i] = (carry << 32) | (dest[i] & 0xffffffffULL);
carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0) +
(carry >> 32) + ((lx * hy) >> 32) + hx * hy;
}
return carry;
}
/// Multiplies integer array x by integer array y and stores the result into
/// the integer array dest. Note that dest's size must be >= xlen + ylen.
/// @brief Generalized multiplicate of integer arrays.
static void mul(uint64_t dest[], uint64_t x[], unsigned xlen, uint64_t y[],
unsigned ylen) {
dest[xlen] = mul_1(dest, x, xlen, y[0]);
for (unsigned i = 1; i < ylen; ++i) {
uint64_t ly = y[i] & 0xffffffffULL, hy = y[i] >> 32;
uint64_t carry = 0, lx = 0, hx = 0;
for (unsigned j = 0; j < xlen; ++j) {
lx = x[j] & 0xffffffffULL;
hx = x[j] >> 32;
// hasCarry - A flag to indicate if has carry.
// hasCarry == 0, no carry
// hasCarry == 1, has carry
// hasCarry == 2, no carry and the calculation result == 0.
uint8_t hasCarry = 0;
uint64_t resul = carry + lx * ly;
hasCarry = (resul < carry) ? 1 : 0;
carry = (hasCarry ? (1ULL << 32) : 0) + hx * ly + (resul >> 32);
hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
carry += (lx * hy) & 0xffffffffULL;
resul = (carry << 32) | (resul & 0xffffffffULL);
dest[i+j] += resul;
carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0)+
(carry >> 32) + (dest[i+j] < resul ? 1 : 0) +
((lx * hy) >> 32) + hx * hy;
}
dest[i+xlen] = carry;
}
}
APInt& APInt::operator*=(const APInt& RHS) {
assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
if (isSingleWord()) {
VAL *= RHS.VAL;
clearUnusedBits();
return *this;
}
// Get some bit facts about LHS and check for zero
unsigned lhsBits = getActiveBits();
unsigned lhsWords = !lhsBits ? 0 : whichWord(lhsBits - 1) + 1;
if (!lhsWords)
// 0 * X ===> 0
return *this;
// Get some bit facts about RHS and check for zero
unsigned rhsBits = RHS.getActiveBits();
unsigned rhsWords = !rhsBits ? 0 : whichWord(rhsBits - 1) + 1;
if (!rhsWords) {
// X * 0 ===> 0
clearAllBits();
return *this;
}
// Allocate space for the result
unsigned destWords = rhsWords + lhsWords;
uint64_t *dest = getMemory(destWords);
// Perform the long multiply
mul(dest, pVal, lhsWords, RHS.pVal, rhsWords);
// Copy result back into *this
clearAllBits();
unsigned wordsToCopy = destWords >= getNumWords() ? getNumWords() : destWords;
memcpy(pVal, dest, wordsToCopy * APINT_WORD_SIZE);
clearUnusedBits();
// delete dest array and return
delete[] dest;
return *this;
}
APInt& APInt::operator&=(const APInt& RHS) {
assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
if (isSingleWord()) {
VAL &= RHS.VAL;
return *this;
}
unsigned numWords = getNumWords();
for (unsigned i = 0; i < numWords; ++i)
pVal[i] &= RHS.pVal[i];
return *this;
}
APInt& APInt::operator|=(const APInt& RHS) {
assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
if (isSingleWord()) {
VAL |= RHS.VAL;
return *this;
}
unsigned numWords = getNumWords();
for (unsigned i = 0; i < numWords; ++i)
pVal[i] |= RHS.pVal[i];
return *this;
}
APInt& APInt::operator^=(const APInt& RHS) {
assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
if (isSingleWord()) {
VAL ^= RHS.VAL;
this->clearUnusedBits();
return *this;
}
unsigned numWords = getNumWords();
for (unsigned i = 0; i < numWords; ++i)
pVal[i] ^= RHS.pVal[i];
return clearUnusedBits();
}
APInt APInt::AndSlowCase(const APInt& RHS) const {
unsigned numWords = getNumWords();
uint64_t* val = getMemory(numWords);
for (unsigned i = 0; i < numWords; ++i)
val[i] = pVal[i] & RHS.pVal[i];
return APInt(val, getBitWidth());
}
APInt APInt::OrSlowCase(const APInt& RHS) const {
unsigned numWords = getNumWords();
uint64_t *val = getMemory(numWords);
for (unsigned i = 0; i < numWords; ++i)
val[i] = pVal[i] | RHS.pVal[i];
return APInt(val, getBitWidth());
}
APInt APInt::XorSlowCase(const APInt& RHS) const {
unsigned numWords = getNumWords();
uint64_t *val = getMemory(numWords);
for (unsigned i = 0; i < numWords; ++i)
val[i] = pVal[i] ^ RHS.pVal[i];
APInt Result(val, getBitWidth());
// 0^0==1 so clear the high bits in case they got set.
Result.clearUnusedBits();
return Result;
}
APInt APInt::operator*(const APInt& RHS) const {
assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
if (isSingleWord())
return APInt(BitWidth, VAL * RHS.VAL);
APInt Result(*this);
Result *= RHS;
return Result;
}
APInt APInt::operator+(const APInt& RHS) const {
assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
if (isSingleWord())
return APInt(BitWidth, VAL + RHS.VAL);
APInt Result(BitWidth, 0);
add(Result.pVal, this->pVal, RHS.pVal, getNumWords());
Result.clearUnusedBits();
return Result;
}
APInt APInt::operator+(uint64_t RHS) const {
if (isSingleWord())
return APInt(BitWidth, VAL + RHS);
APInt Result(*this);
add_1(Result.pVal, Result.pVal, getNumWords(), RHS);
Result.clearUnusedBits();
return Result;
}
APInt APInt::operator-(const APInt& RHS) const {
assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
if (isSingleWord())
return APInt(BitWidth, VAL - RHS.VAL);
APInt Result(BitWidth, 0);
sub(Result.pVal, this->pVal, RHS.pVal, getNumWords());
Result.clearUnusedBits();
return Result;
}
APInt APInt::operator-(uint64_t RHS) const {
if (isSingleWord())
return APInt(BitWidth, VAL - RHS);
APInt Result(*this);
sub_1(Result.pVal, getNumWords(), RHS);
Result.clearUnusedBits();
return Result;
}
bool APInt::EqualSlowCase(const APInt& RHS) const {
return std::equal(pVal, pVal + getNumWords(), RHS.pVal);
}
bool APInt::EqualSlowCase(uint64_t Val) const {
unsigned n = getActiveBits();
if (n <= APINT_BITS_PER_WORD)
return pVal[0] == Val;
else
return false;
}
bool APInt::ult(const APInt& RHS) const {
assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
if (isSingleWord())
return VAL < RHS.VAL;
// Get active bit length of both operands
unsigned n1 = getActiveBits();
unsigned n2 = RHS.getActiveBits();
// If magnitude of LHS is less than RHS, return true.
if (n1 < n2)
return true;
// If magnitude of RHS is greather than LHS, return false.
if (n2 < n1)
return false;
// If they bot fit in a word, just compare the low order word
if (n1 <= APINT_BITS_PER_WORD && n2 <= APINT_BITS_PER_WORD)
return pVal[0] < RHS.pVal[0];
// Otherwise, compare all words
unsigned topWord = whichWord(std::max(n1,n2)-1);
for (int i = topWord; i >= 0; --i) {
if (pVal[i] > RHS.pVal[i])
return false;
if (pVal[i] < RHS.pVal[i])
return true;
}
return false;
}
bool APInt::slt(const APInt& RHS) const {
assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
if (isSingleWord()) {
int64_t lhsSext = SignExtend64(VAL, BitWidth);
int64_t rhsSext = SignExtend64(RHS.VAL, BitWidth);
return lhsSext < rhsSext;
}
bool lhsNeg = isNegative();
bool rhsNeg = RHS.isNegative();
// If the sign bits don't match, then (LHS < RHS) if LHS is negative
if (lhsNeg != rhsNeg)
return lhsNeg;
// Otherwise we can just use an unsigned comparision, because even negative
// numbers compare correctly this way if both have the same signed-ness.
return ult(RHS);
}
void APInt::setBit(unsigned bitPosition) {
if (isSingleWord())
VAL |= maskBit(bitPosition);
else
pVal[whichWord(bitPosition)] |= maskBit(bitPosition);
}
/// Set the given bit to 0 whose position is given as "bitPosition".
/// @brief Set a given bit to 0.
void APInt::clearBit(unsigned bitPosition) {
if (isSingleWord())
VAL &= ~maskBit(bitPosition);
else
pVal[whichWord(bitPosition)] &= ~maskBit(bitPosition);
}
/// @brief Toggle every bit to its opposite value.
/// Toggle a given bit to its opposite value whose position is given
/// as "bitPosition".
/// @brief Toggles a given bit to its opposite value.
void APInt::flipBit(unsigned bitPosition) {
assert(bitPosition < BitWidth && "Out of the bit-width range!");
if ((*this)[bitPosition]) clearBit(bitPosition);
else setBit(bitPosition);
}
unsigned APInt::getBitsNeeded(StringRef str, uint8_t radix) {
assert(!str.empty() && "Invalid string length");
assert((radix == 10 || radix == 8 || radix == 16 || radix == 2 ||
radix == 36) &&
"Radix should be 2, 8, 10, 16, or 36!");
size_t slen = str.size();
// Each computation below needs to know if it's negative.
StringRef::iterator p = str.begin();
unsigned isNegative = *p == '-';
if (*p == '-' || *p == '+') {
p++;
slen--;
assert(slen && "String is only a sign, needs a value.");
}
// For radixes of power-of-two values, the bits required is accurately and
// easily computed
if (radix == 2)
return slen + isNegative;
if (radix == 8)
return slen * 3 + isNegative;
if (radix == 16)
return slen * 4 + isNegative;
// FIXME: base 36
// This is grossly inefficient but accurate. We could probably do something
// with a computation of roughly slen*64/20 and then adjust by the value of
// the first few digits. But, I'm not sure how accurate that could be.
// Compute a sufficient number of bits that is always large enough but might
// be too large. This avoids the assertion in the constructor. This
// calculation doesn't work appropriately for the numbers 0-9, so just use 4
// bits in that case.
unsigned sufficient
= radix == 10? (slen == 1 ? 4 : slen * 64/18)
: (slen == 1 ? 7 : slen * 16/3);
// Convert to the actual binary value.
APInt tmp(sufficient, StringRef(p, slen), radix);
// Compute how many bits are required. If the log is infinite, assume we need
// just bit.
unsigned log = tmp.logBase2();
if (log == (unsigned)-1) {
return isNegative + 1;
} else {
return isNegative + log + 1;
}
}
hash_code llvm::hash_value(const APInt &Arg) {
if (Arg.isSingleWord())
return hash_combine(Arg.VAL);
return hash_combine_range(Arg.pVal, Arg.pVal + Arg.getNumWords());
}
bool APInt::isSplat(unsigned SplatSizeInBits) const {
assert(getBitWidth() % SplatSizeInBits == 0 &&
"SplatSizeInBits must divide width!");
// We can check that all parts of an integer are equal by making use of a
// little trick: rotate and check if it's still the same value.
return *this == rotl(SplatSizeInBits);
}
/// This function returns the high "numBits" bits of this APInt.
APInt APInt::getHiBits(unsigned numBits) const {
return APIntOps::lshr(*this, BitWidth - numBits);
}
/// This function returns the low "numBits" bits of this APInt.
APInt APInt::getLoBits(unsigned numBits) const {
return APIntOps::lshr(APIntOps::shl(*this, BitWidth - numBits),
BitWidth - numBits);
}
unsigned APInt::countLeadingZerosSlowCase() const {
unsigned Count = 0;
for (int i = getNumWords()-1; i >= 0; --i) {
integerPart V = pVal[i];
if (V == 0)
Count += APINT_BITS_PER_WORD;
else {
Count += llvm::countLeadingZeros(V);
break;
}
}
// Adjust for unused bits in the most significant word (they are zero).
unsigned Mod = BitWidth % APINT_BITS_PER_WORD;
Count -= Mod > 0 ? APINT_BITS_PER_WORD - Mod : 0;
return Count;
}
unsigned APInt::countLeadingOnes() const {
if (isSingleWord())
return llvm::countLeadingOnes(VAL << (APINT_BITS_PER_WORD - BitWidth));
unsigned highWordBits = BitWidth % APINT_BITS_PER_WORD;
unsigned shift;
if (!highWordBits) {
highWordBits = APINT_BITS_PER_WORD;
shift = 0;
} else {
shift = APINT_BITS_PER_WORD - highWordBits;
}
int i = getNumWords() - 1;
unsigned Count = llvm::countLeadingOnes(pVal[i] << shift);
if (Count == highWordBits) {
for (i--; i >= 0; --i) {
if (pVal[i] == -1ULL)
Count += APINT_BITS_PER_WORD;
else {
Count += llvm::countLeadingOnes(pVal[i]);
break;
}
}
}
return Count;
}
unsigned APInt::countTrailingZeros() const {
if (isSingleWord())
return std::min(unsigned(llvm::countTrailingZeros(VAL)), BitWidth);
unsigned Count = 0;
unsigned i = 0;
for (; i < getNumWords() && pVal[i] == 0; ++i)
Count += APINT_BITS_PER_WORD;
if (i < getNumWords())
Count += llvm::countTrailingZeros(pVal[i]);
return std::min(Count, BitWidth);
}
unsigned APInt::countTrailingOnesSlowCase() const {
unsigned Count = 0;
unsigned i = 0;
for (; i < getNumWords() && pVal[i] == -1ULL; ++i)
Count += APINT_BITS_PER_WORD;
if (i < getNumWords())
Count += llvm::countTrailingOnes(pVal[i]);
return std::min(Count, BitWidth);
}
unsigned APInt::countPopulationSlowCase() const {
unsigned Count = 0;
for (unsigned i = 0; i < getNumWords(); ++i)
Count += llvm::countPopulation(pVal[i]);
return Count;
}
/// Perform a logical right-shift from Src to Dst, which must be equal or
/// non-overlapping, of Words words, by Shift, which must be less than 64.
static void lshrNear(uint64_t *Dst, uint64_t *Src, unsigned Words,
unsigned Shift) {
uint64_t Carry = 0;
for (int I = Words - 1; I >= 0; --I) {
uint64_t Tmp = Src[I];
Dst[I] = (Tmp >> Shift) | Carry;
Carry = Tmp << (64 - Shift);
}
}
APInt APInt::byteSwap() const {
assert(BitWidth >= 16 && BitWidth % 16 == 0 && "Cannot byteswap!");
if (BitWidth == 16)
return APInt(BitWidth, ByteSwap_16(uint16_t(VAL)));
if (BitWidth == 32)
return APInt(BitWidth, ByteSwap_32(unsigned(VAL)));
if (BitWidth == 48) {
unsigned Tmp1 = unsigned(VAL >> 16);
Tmp1 = ByteSwap_32(Tmp1);
uint16_t Tmp2 = uint16_t(VAL);
Tmp2 = ByteSwap_16(Tmp2);
return APInt(BitWidth, (uint64_t(Tmp2) << 32) | Tmp1);
}
if (BitWidth == 64)
return APInt(BitWidth, ByteSwap_64(VAL));
APInt Result(getNumWords() * APINT_BITS_PER_WORD, 0);
for (unsigned I = 0, N = getNumWords(); I != N; ++I)
Result.pVal[I] = ByteSwap_64(pVal[N - I - 1]);
if (Result.BitWidth != BitWidth) {
lshrNear(Result.pVal, Result.pVal, getNumWords(),
Result.BitWidth - BitWidth);
Result.BitWidth = BitWidth;
}
return Result;
}
APInt APInt::reverseBits() const {
switch (BitWidth) {
case 64:
return APInt(BitWidth, llvm::reverseBits<uint64_t>(VAL));
case 32:
return APInt(BitWidth, llvm::reverseBits<uint32_t>(VAL));
case 16:
return APInt(BitWidth, llvm::reverseBits<uint16_t>(VAL));
case 8:
return APInt(BitWidth, llvm::reverseBits<uint8_t>(VAL));
default:
break;
}
APInt Val(*this);
APInt Reversed(*this);
int S = BitWidth - 1;
const APInt One(BitWidth, 1);
for ((Val = Val.lshr(1)); Val != 0; (Val = Val.lshr(1))) {
Reversed <<= 1;
Reversed |= (Val & One);
--S;
}
Reversed <<= S;
return Reversed;
}
APInt llvm::APIntOps::GreatestCommonDivisor(const APInt& API1,
const APInt& API2) {
APInt A = API1, B = API2;
while (!!B) {
APInt T = B;
B = APIntOps::urem(A, B);
A = T;
}
return A;
}
APInt llvm::APIntOps::RoundDoubleToAPInt(double Double, unsigned width) {
union {
double D;
uint64_t I;
} T;
T.D = Double;
// Get the sign bit from the highest order bit
bool isNeg = T.I >> 63;
// Get the 11-bit exponent and adjust for the 1023 bit bias
int64_t exp = ((T.I >> 52) & 0x7ff) - 1023;
// If the exponent is negative, the value is < 0 so just return 0.
if (exp < 0)
return APInt(width, 0u);
// Extract the mantissa by clearing the top 12 bits (sign + exponent).
uint64_t mantissa = (T.I & (~0ULL >> 12)) | 1ULL << 52;
// If the exponent doesn't shift all bits out of the mantissa
if (exp < 52)
return isNeg ? -APInt(width, mantissa >> (52 - exp)) :
APInt(width, mantissa >> (52 - exp));
// If the client didn't provide enough bits for us to shift the mantissa into
// then the result is undefined, just return 0
if (width <= exp - 52)
return APInt(width, 0);
// Otherwise, we have to shift the mantissa bits up to the right location
APInt Tmp(width, mantissa);
Tmp = Tmp.shl((unsigned)exp - 52);
return isNeg ? -Tmp : Tmp;
}
/// This function converts this APInt to a double.
/// The layout for double is as following (IEEE Standard 754):
/// --------------------------------------
/// | Sign Exponent Fraction Bias |
/// |-------------------------------------- |
/// | 1[63] 11[62-52] 52[51-00] 1023 |
/// --------------------------------------
double APInt::roundToDouble(bool isSigned) const {
// Handle the simple case where the value is contained in one uint64_t.
// It is wrong to optimize getWord(0) to VAL; there might be more than one word.
if (isSingleWord() || getActiveBits() <= APINT_BITS_PER_WORD) {
if (isSigned) {
int64_t sext = SignExtend64(getWord(0), BitWidth);
return double(sext);
} else
return double(getWord(0));
}
// Determine if the value is negative.
bool isNeg = isSigned ? (*this)[BitWidth-1] : false;
// Construct the absolute value if we're negative.
APInt Tmp(isNeg ? -(*this) : (*this));
// Figure out how many bits we're using.
unsigned n = Tmp.getActiveBits();
// The exponent (without bias normalization) is just the number of bits
// we are using. Note that the sign bit is gone since we constructed the
// absolute value.
uint64_t exp = n;
// Return infinity for exponent overflow
if (exp > 1023) {
if (!isSigned || !isNeg)
return std::numeric_limits<double>::infinity();
else
return -std::numeric_limits<double>::infinity();
}
exp += 1023; // Increment for 1023 bias
// Number of bits in mantissa is 52. To obtain the mantissa value, we must
// extract the high 52 bits from the correct words in pVal.
uint64_t mantissa;
unsigned hiWord = whichWord(n-1);
if (hiWord == 0) {
mantissa = Tmp.pVal[0];
if (n > 52)
mantissa >>= n - 52; // shift down, we want the top 52 bits.
} else {
assert(hiWord > 0 && "huh?");
uint64_t hibits = Tmp.pVal[hiWord] << (52 - n % APINT_BITS_PER_WORD);
uint64_t lobits = Tmp.pVal[hiWord-1] >> (11 + n % APINT_BITS_PER_WORD);
mantissa = hibits | lobits;
}
// The leading bit of mantissa is implicit, so get rid of it.
uint64_t sign = isNeg ? (1ULL << (APINT_BITS_PER_WORD - 1)) : 0;
union {
double D;
uint64_t I;
} T;
T.I = sign | (exp << 52) | mantissa;
return T.D;
}
// Truncate to new width.
APInt APInt::trunc(unsigned width) const {
assert(width < BitWidth && "Invalid APInt Truncate request");
assert(width && "Can't truncate to 0 bits");
if (width <= APINT_BITS_PER_WORD)
return APInt(width, getRawData()[0]);
APInt Result(getMemory(getNumWords(width)), width);
// Copy full words.
unsigned i;
for (i = 0; i != width / APINT_BITS_PER_WORD; i++)
Result.pVal[i] = pVal[i];
// Truncate and copy any partial word.
unsigned bits = (0 - width) % APINT_BITS_PER_WORD;
if (bits != 0)
Result.pVal[i] = pVal[i] << bits >> bits;
return Result;
}
// Sign extend to a new width.
APInt APInt::sext(unsigned width) const {
assert(width > BitWidth && "Invalid APInt SignExtend request");
if (width <= APINT_BITS_PER_WORD) {
uint64_t val = VAL << (APINT_BITS_PER_WORD - BitWidth);
val = (int64_t)val >> (width - BitWidth);
return APInt(width, val >> (APINT_BITS_PER_WORD - width));
}
APInt Result(getMemory(getNumWords(width)), width);
// Copy full words.
unsigned i;
uint64_t word = 0;
for (i = 0; i != BitWidth / APINT_BITS_PER_WORD; i++) {
word = getRawData()[i];
Result.pVal[i] = word;
}
// Read and sign-extend any partial word.
unsigned bits = (0 - BitWidth) % APINT_BITS_PER_WORD;
if (bits != 0)
word = (int64_t)getRawData()[i] << bits >> bits;
else
word = (int64_t)word >> (APINT_BITS_PER_WORD - 1);
// Write remaining full words.
for (; i != width / APINT_BITS_PER_WORD; i++) {
Result.pVal[i] = word;
word = (int64_t)word >> (APINT_BITS_PER_WORD - 1);
}
// Write any partial word.
bits = (0 - width) % APINT_BITS_PER_WORD;
if (bits != 0)
Result.pVal[i] = word << bits >> bits;
return Result;
}