5fd2fe00f52b8bbbeb76876792317ea81ffa1bf5
[sbcl.git] / src / code / bignum.lisp
1 ;;;; code to implement bignum support
2
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
5 ;;;;
6 ;;;; This software is derived from the CMU CL system, which was
7 ;;;; written at Carnegie Mellon University and released into the
8 ;;;; public domain. The software is in the public domain and is
9 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
10 ;;;; files for more information.
11
12 (in-package "SB!BIGNUM")
13 \f
14 ;;;; notes
15
16 ;;; comments from CMU CL:
17 ;;;   These symbols define the interface to the number code:
18 ;;;       add-bignums multiply-bignums negate-bignum subtract-bignum
19 ;;;       multiply-bignum-and-fixnum multiply-fixnums
20 ;;;       bignum-ashift-right bignum-ashift-left bignum-gcd
21 ;;;       bignum-to-float bignum-integer-length
22 ;;;       bignum-logical-and bignum-logical-ior bignum-logical-xor
23 ;;;       bignum-logical-not bignum-load-byte bignum-deposit-byte
24 ;;;       bignum-truncate bignum-plus-p bignum-compare make-small-bignum
25 ;;;       bignum-logcount
26 ;;;   These symbols define the interface to the compiler:
27 ;;;       bignum-type bignum-element-type bignum-index %allocate-bignum
28 ;;;       %bignum-length %bignum-set-length %bignum-ref %bignum-set
29 ;;;       %digit-0-or-plusp %add-with-carry %subtract-with-borrow
30 ;;;       %multiply-and-add %multiply %lognot %logand %logior %logxor
31 ;;;       %fixnum-to-digit %floor %fixnum-digit-with-correct-sign %ashl
32 ;;;       %ashr %digit-logical-shift-right))
33
34 ;;; The following interfaces will either be assembler routines or code
35 ;;; sequences expanded into the code as basic bignum operations:
36 ;;;    General:
37 ;;;       %BIGNUM-LENGTH
38 ;;;       %ALLOCATE-BIGNUM
39 ;;;       %BIGNUM-REF
40 ;;;       %NORMALIZE-BIGNUM
41 ;;;       %BIGNUM-SET-LENGTH
42 ;;;       %FIXNUM-DIGIT-WITH-CORRECT-SIGN
43 ;;;       %SIGN-DIGIT
44 ;;;       %ASHR
45 ;;;       %ASHL
46 ;;;       %BIGNUM-0-OR-PLUSP
47 ;;;       %DIGIT-LOGICAL-SHIFT-RIGHT
48 ;;;    General (May not exist when done due to sole use in %-routines.)
49 ;;;       %DIGIT-0-OR-PLUSP
50 ;;;    Addition:
51 ;;;       %ADD-WITH-CARRY
52 ;;;    Subtraction:
53 ;;;       %SUBTRACT-WITH-BORROW
54 ;;;    Multiplication
55 ;;;       %MULTIPLY
56 ;;;    Negation
57 ;;;       %LOGNOT
58 ;;;    Shifting (in place)
59 ;;;       %NORMALIZE-BIGNUM-BUFFER
60 ;;;    GCD/Relational operators:
61 ;;;       %DIGIT-COMPARE
62 ;;;       %DIGIT-GREATER
63 ;;;    Relational operators:
64 ;;;       %LOGAND
65 ;;;       %LOGIOR
66 ;;;       %LOGXOR
67 ;;;    LDB
68 ;;;       %FIXNUM-TO-DIGIT
69 ;;;    TRUNCATE
70 ;;;       %FLOOR
71 ;;;
72 ;;; Note: The floating routines know about the float representation.
73 ;;;
74 ;;; PROBLEM 1:
75 ;;; There might be a problem with various LET's and parameters that take a
76 ;;; digit value. We need to write these so those things stay in 32-bit
77 ;;; registers and number stack slots. I bind locals to these values, and I
78 ;;; use function on them -- ZEROP, ASH, etc.
79 ;;;
80 ;;; PROBLEM 2:
81 ;;; In shifting and byte operations, I use masks and logical operations that
82 ;;; could result in intermediate bignums. This is hidden by the current system,
83 ;;; but I may need to write these in a way that keeps these masks and logical
84 ;;; operations from diving into the Lisp level bignum code.
85 ;;;
86 ;;; To do:
87 ;;;    fixnums
88 ;;;       logior, logxor, logand
89 ;;;       depending on relationals, < (twice) and <= (twice)
90 ;;;       or write compare thing (twice).
91 ;;;       LDB on fixnum with bignum result.
92 ;;;       DPB on fixnum with bignum result.
93 ;;;       TRUNCATE returns zero or one as one value and fixnum or minus fixnum
94 ;;;       for the other value when given (truncate fixnum bignum).
95 ;;;       Returns (truncate bignum fixnum) otherwise.
96 ;;;       addition
97 ;;;       subtraction (twice)
98 ;;;       multiply
99 ;;;       GCD
100 ;;;    Write MASK-FIELD and DEPOSIT-FIELD in terms of logical operations.
101 ;;;    DIVIDE
102 ;;;       IF (/ x y) with bignums:
103 ;;;       do the truncate, and if rem is 0, return quotient.
104 ;;;       if rem is non-0
105 ;;;          gcd of x and y.
106 ;;;          "truncate" each by gcd, ignoring remainder 0.
107 ;;;          form ratio of each result, bottom is positive.
108 \f
109 ;;;; What's a bignum?
110
111 (eval-when (:compile-toplevel :load-toplevel :execute) ; necessary for DEFTYPE
112
113 (defconstant digit-size 32)
114
115 (defconstant maximum-bignum-length (1- (ash 1 (- 32 sb!vm:type-bits))))
116
117 ) ; EVAL-WHEN
118 \f
119 ;;;; internal inline routines
120
121 ;;; %ALLOCATE-BIGNUM must zero all elements.
122 (defun %allocate-bignum (length)
123   (declare (type bignum-index length))
124   (%allocate-bignum length))
125
126 ;;; Extract the length of the bignum.
127 (defun %bignum-length (bignum)
128   (declare (type bignum-type bignum))
129   (%bignum-length bignum))
130
131 ;;; %BIGNUM-REF needs to access bignums as obviously as possible, and it needs
132 ;;; to be able to return 32 bits somewhere no one looks for real objects.
133 (defun %bignum-ref (bignum i)
134   (declare (type bignum-type bignum)
135            (type bignum-index i))
136   (%bignum-ref bignum i))
137 (defun %bignum-set (bignum i value)
138   (declare (type bignum-type bignum)
139            (type bignum-index i)
140            (type bignum-element-type value))
141   (%bignum-set bignum i value))
142
143 ;;; Return T if digit is positive, or NIL if negative.
144 (defun %digit-0-or-plusp (digit)
145   (declare (type bignum-element-type digit))
146   (not (logbitp (1- digit-size) digit)))
147
148 #!-sb-fluid (declaim (inline %bignum-0-or-plusp))
149 (defun %bignum-0-or-plusp (bignum len)
150   (declare (type bignum-type bignum)
151            (type bignum-index len))
152   (%digit-0-or-plusp (%bignum-ref bignum (1- len))))
153
154 ;;; This should be in assembler, and should not cons intermediate results. It
155 ;;; returns a 32bit digit and a carry resulting from adding together a, b, and
156 ;;; an incoming carry.
157 (defun %add-with-carry (a b carry)
158   (declare (type bignum-element-type a b)
159            (type (mod 2) carry))
160   (%add-with-carry a b carry))
161
162 ;;; This should be in assembler, and should not cons intermediate results. It
163 ;;; returns a 32bit digit and a borrow resulting from subtracting b from a, and
164 ;;; subtracting a possible incoming borrow.
165 ;;;
166 ;;; We really do:  a - b - 1 + borrow, where borrow is either 0 or 1.
167 (defun %subtract-with-borrow (a b borrow)
168   (declare (type bignum-element-type a b)
169            (type (mod 2) borrow))
170   (%subtract-with-borrow a b borrow))
171
172 ;;; Multiply two digit-size (32-bit) numbers, returning a 64-bit result
173 ;;; split into two 32-bit quantities.
174 (defun %multiply (x y)
175   (declare (type bignum-element-type x y))
176   (%multiply x y))
177
178 ;;; This multiplies x-digit and y-digit, producing high and low digits
179 ;;; manifesting the result. Then it adds the low digit, res-digit, and
180 ;;; carry-in-digit. Any carries (note, you still have to add two digits at a
181 ;;; time possibly producing two carries) from adding these three digits get
182 ;;; added to the high digit from the multiply, producing the next carry digit.
183 ;;; Res-digit is optional since two uses of this primitive multiplies a single
184 ;;; digit bignum by a multiple digit bignum, and in this situation there is no
185 ;;; need for a result buffer accumulating partial results which is where the
186 ;;; res-digit comes from.
187 (defun %multiply-and-add (x-digit y-digit carry-in-digit
188                           &optional (res-digit 0))
189   (declare (type bignum-element-type x-digit y-digit res-digit carry-in-digit))
190   (%multiply-and-add x-digit y-digit carry-in-digit res-digit))
191
192 (defun %lognot (digit)
193   (declare (type bignum-element-type digit))
194   (%lognot digit))
195
196 ;;; Each of these does the 32-bit unsigned op.
197 #!-sb-fluid (declaim (inline %logand %logior %logxor))
198 (defun %logand (a b)
199   (declare (type bignum-element-type a b))
200   (logand a b))
201 (defun %logior (a b)
202   (declare (type bignum-element-type a b))
203   (logior a b))
204 (defun %logxor (a b)
205   (declare (type bignum-element-type a b))
206   (logxor a b))
207
208 ;;; This takes a fixnum and sets it up as an unsigned 32-bit quantity. In
209 ;;; the new system this will mean shifting it right two bits.
210 (defun %fixnum-to-digit (x)
211   (declare (fixnum x))
212   (logand x (1- (ash 1 digit-size))))
213
214 #!-32x16-divide
215 ;;; This takes three digits and returns the FLOOR'ed result of dividing the
216 ;;; first two as a 64-bit integer by the third.
217 ;;;
218 ;;; DO WEIRD let AND setq STUFF TO SLIME THE COMPILER INTO ALLOWING THE %FLOOR
219 ;;; TRANSFORM TO EXPAND INTO PSEUDO-ASSEMBLER FOR WHICH THE COMPILER CAN LATER
220 ;;; CORRECTLY ALLOCATE REGISTERS.
221 (defun %floor (a b c)
222   (let ((a a) (b b) (c c))
223     (declare (type bignum-element-type a b c))
224     (setq a a b b c c)
225     (%floor a b c)))
226
227 ;;; Convert the digit to a regular integer assuming that the digit is signed.
228 (defun %fixnum-digit-with-correct-sign (digit)
229   (declare (type bignum-element-type digit))
230   (if (logbitp (1- digit-size) digit)
231       (logior digit (ash -1 digit-size))
232       digit))
233
234 ;;; Do an arithmetic shift right of data even though bignum-element-type is
235 ;;; unsigned.
236 (defun %ashr (data count)
237   (declare (type bignum-element-type data)
238            (type (mod 32) count))
239   (%ashr data count))
240
241 ;;; This takes a 32-bit quantity and shifts it to the left, returning a 32-bit
242 ;;; quantity.
243 (defun %ashl (data count)
244   (declare (type bignum-element-type data)
245            (type (mod 32) count))
246   (%ashl data count))
247
248 ;;; Do an unsigned (logical) right shift of a digit by Count.
249 (defun %digit-logical-shift-right (data count)
250   (declare (type bignum-element-type data)
251            (type (mod 32) count))
252   (%digit-logical-shift-right data count))
253
254 ;;; Change the length of bignum to be newlen. Newlen must be the same or
255 ;;; smaller than the old length, and any elements beyond newlen must be zeroed.
256 (defun %bignum-set-length (bignum newlen)
257   (declare (type bignum-type bignum)
258            (type bignum-index newlen))
259   (%bignum-set-length bignum newlen))
260
261 ;;; This returns 0 or "-1" depending on whether the bignum is positive. This
262 ;;; is suitable for infinite sign extension to complete additions,
263 ;;; subtractions, negations, etc. This cannot return a -1 represented as
264 ;;; a negative fixnum since it would then have to low zeros.
265 #!-sb-fluid (declaim (inline %sign-digit))
266 (defun %sign-digit (bignum len)
267   (declare (type bignum-type bignum)
268            (type bignum-index len))
269   (%ashr (%bignum-ref bignum (1- len)) (1- digit-size)))
270
271 ;;; These take two 32 bit quantities and compare or contrast them without
272 ;;; wasting time with incorrect type checking.
273 #!-sb-fluid (declaim (inline %digit-compare %digit-greater))
274 (defun %digit-compare (x y)
275   (= x y))
276 (defun %digit-greater (x y)
277   (> x y))
278 \f
279 (declaim (optimize (speed 3) (safety 0)))
280 \f
281 ;;;; addition
282
283 (defun add-bignums (a b)
284   (declare (type bignum-type a b))
285   (let ((len-a (%bignum-length a))
286         (len-b (%bignum-length b)))
287     (declare (type bignum-index len-a len-b))
288     (multiple-value-bind (a len-a b len-b)
289         (if (> len-a len-b)
290             (values a len-a b len-b)
291             (values b len-b a len-a))
292       (declare (type bignum-type a b)
293                (type bignum-index len-a len-b))
294       (let* ((len-res (1+ len-a))
295              (res (%allocate-bignum len-res))
296              (carry 0))
297         (declare (type bignum-index len-res)
298                  (type bignum-type res)
299                  (type (mod 2) carry))
300         (dotimes (i len-b)
301           (declare (type bignum-index i))
302           (multiple-value-bind (v k)
303               (%add-with-carry (%bignum-ref a i) (%bignum-ref b i) carry)
304             (declare (type bignum-element-type v)
305                      (type (mod 2) k))
306             (setf (%bignum-ref res i) v)
307             (setf carry k)))
308         (if (/= len-a len-b)
309             (finish-add a res carry (%sign-digit b len-b) len-b len-a)
310             (setf (%bignum-ref res len-a)
311                   (%add-with-carry (%sign-digit a len-a)
312                                    (%sign-digit b len-b)
313                                    carry)))
314         (%normalize-bignum res len-res)))))
315
316 ;;; This takes the longer of two bignums and propagates the carry through its
317 ;;; remaining high order digits.
318 (defun finish-add (a res carry sign-digit-b start end)
319   (declare (type bignum-type a res)
320            (type (mod 2) carry)
321            (type bignum-element-type sign-digit-b)
322            (type bignum-index start end))
323   (do ((i start (1+ i)))
324       ((= i end)
325        (setf (%bignum-ref res end)
326              (%add-with-carry (%sign-digit a end) sign-digit-b carry)))
327     (declare (type bignum-index i))
328     (multiple-value-bind (v k)
329         (%add-with-carry (%bignum-ref a i) sign-digit-b carry)
330       (setf (%bignum-ref res i) v)
331       (setf carry k)))
332   (values))
333 \f
334 ;;;; subtraction
335
336 (eval-when (:compile-toplevel :execute)
337
338 ;;; This subtracts b from a plugging result into res. Return-fun is the
339 ;;; function to call that fixes up the result returning any useful values, such
340 ;;; as the result. This macro may evaluate its arguments more than once.
341 (sb!xc:defmacro subtract-bignum-loop (a len-a b len-b res len-res return-fun)
342   (let ((borrow (gensym))
343         (a-digit (gensym))
344         (a-sign (gensym))
345         (b-digit (gensym))
346         (b-sign (gensym))
347         (i (gensym))
348         (v (gensym))
349         (k (gensym)))
350     `(let* ((,borrow 1)
351             (,a-sign (%sign-digit ,a ,len-a))
352             (,b-sign (%sign-digit ,b ,len-b)))
353        (declare (type bignum-element-type ,a-sign ,b-sign))
354        (dotimes (,i ,len-res)
355          (declare (type bignum-index ,i))
356          (let ((,a-digit (if (< ,i ,len-a) (%bignum-ref ,a ,i) ,a-sign))
357                (,b-digit (if (< ,i ,len-b) (%bignum-ref ,b ,i) ,b-sign)))
358            (declare (type bignum-element-type ,a-digit ,b-digit))
359            (multiple-value-bind (,v ,k)
360                (%subtract-with-borrow ,a-digit ,b-digit ,borrow)
361              (setf (%bignum-ref ,res ,i) ,v)
362              (setf ,borrow ,k))))
363        (,return-fun ,res ,len-res))))
364
365 ) ;EVAL-WHEN
366
367 (defun subtract-bignum (a b)
368   (declare (type bignum-type a b))
369   (let* ((len-a (%bignum-length a))
370          (len-b (%bignum-length b))
371          (len-res (1+ (max len-a len-b)))
372          (res (%allocate-bignum len-res)))
373     (declare (type bignum-index len-a len-b len-res)) ;Test len-res for bounds?
374     (subtract-bignum-loop a len-a b len-b res len-res %normalize-bignum)))
375
376 ;;; Operations requiring a subtraction without the overhead of intermediate
377 ;;; results, such as GCD, use this. It assumes Result is big enough for the
378 ;;; result.
379 (defun subtract-bignum-buffers (a len-a b len-b result)
380   (declare (type bignum-type a b)
381            (type bignum-index len-a len-b))
382   (let ((len-res (max len-a len-b)))
383     (subtract-bignum-loop a len-a b len-b result len-res
384                           %normalize-bignum-buffer)))
385 \f
386 ;;;; multiplication
387
388 (defun multiply-bignums (a b)
389   (declare (type bignum-type a b))
390   (let* ((a-plusp (%bignum-0-or-plusp a (%bignum-length a)))
391          (b-plusp (%bignum-0-or-plusp b (%bignum-length b)))
392          (a (if a-plusp a (negate-bignum a)))
393          (b (if b-plusp b (negate-bignum b)))
394          (len-a (%bignum-length a))
395          (len-b (%bignum-length b))
396          (len-res (+ len-a len-b))
397          (res (%allocate-bignum len-res))
398          (negate-res (not (eq a-plusp b-plusp))))
399     (declare (type bignum-index len-a len-b len-res))
400     (dotimes (i len-a)
401       (declare (type bignum-index i))
402       (let ((carry-digit 0)
403             (x (%bignum-ref a i))
404             (k i))
405         (declare (type bignum-index k)
406                  (type bignum-element-type carry-digit x))
407         (dotimes (j len-b)
408           (multiple-value-bind (big-carry res-digit)
409               (%multiply-and-add x
410                                  (%bignum-ref b j)
411                                  (%bignum-ref res k)
412                                  carry-digit)
413             (declare (type bignum-element-type big-carry res-digit))
414             (setf (%bignum-ref res k) res-digit)
415             (setf carry-digit big-carry)
416             (incf k)))
417         (setf (%bignum-ref res k) carry-digit)))
418     (when negate-res (negate-bignum-in-place res))
419     (%normalize-bignum res len-res)))
420
421 (defun multiply-bignum-and-fixnum (bignum fixnum)
422   (declare (type bignum-type bignum) (type fixnum fixnum))
423   (let* ((bignum-plus-p (%bignum-0-or-plusp bignum (%bignum-length bignum)))
424          (fixnum-plus-p (not (minusp fixnum)))
425          (bignum (if bignum-plus-p bignum (negate-bignum bignum)))
426          (bignum-len (%bignum-length bignum))
427          (fixnum (if fixnum-plus-p fixnum (- fixnum)))
428          (result (%allocate-bignum (1+ bignum-len)))
429          (carry-digit 0))
430     (declare (type bignum-type bignum result)
431              (type bignum-index bignum-len)
432              (type bignum-element-type fixnum carry-digit))
433     (dotimes (index bignum-len)
434       (declare (type bignum-index index))
435       (multiple-value-bind (next-digit low)
436           (%multiply-and-add (%bignum-ref bignum index) fixnum carry-digit)
437         (declare (type bignum-element-type next-digit low))
438         (setf carry-digit next-digit)
439         (setf (%bignum-ref result index) low)))
440     (setf (%bignum-ref result bignum-len) carry-digit)
441     (unless (eq bignum-plus-p fixnum-plus-p)
442       (negate-bignum-in-place result))
443     (%normalize-bignum result (1+ bignum-len))))
444
445 (defun multiply-fixnums (a b)
446   (declare (fixnum a b))
447   (let* ((a-minusp (minusp a))
448          (b-minusp (minusp b)))
449     (multiple-value-bind (high low)
450         (%multiply (if a-minusp (- a) a)
451                    (if b-minusp (- b) b))
452       (declare (type bignum-element-type high low))
453       (if (and (zerop high)
454                (%digit-0-or-plusp low))
455           (let ((low (sb!ext:truly-the (unsigned-byte 31)
456                                        (%fixnum-digit-with-correct-sign low))))
457             (if (eq a-minusp b-minusp)
458                 low
459                 (- low)))
460           (let ((res (%allocate-bignum 2)))
461             (%bignum-set res 0 low)
462             (%bignum-set res 1 high)
463             (unless (eq a-minusp b-minusp) (negate-bignum-in-place res))
464             (%normalize-bignum res 2))))))
465 \f
466 ;;;; BIGNUM-REPLACE and WITH-BIGNUM-BUFFERS
467
468 (eval-when (:compile-toplevel :execute)
469
470 (sb!xc:defmacro bignum-replace (dest
471                                 src
472                                 &key
473                                 (start1 '0)
474                                 end1
475                                 (start2 '0)
476                                 end2
477                                 from-end)
478   (sb!int:once-only ((n-dest dest)
479                      (n-src src))
480     (let ((n-start1 (gensym))
481           (n-end1 (gensym))
482           (n-start2 (gensym))
483           (n-end2 (gensym))
484           (i1 (gensym))
485           (i2 (gensym))
486           (end1 (or end1 `(%bignum-length ,n-dest)))
487           (end2 (or end2 `(%bignum-length ,n-src))))
488       (if from-end
489           `(let ((,n-start1 ,start1)
490                  (,n-start2 ,start2))
491              (do ((,i1 (1- ,end1) (1- ,i1))
492                   (,i2 (1- ,end2) (1- ,i2)))
493                  ((or (< ,i1 ,n-start1) (< ,i2 ,n-start2)))
494                (declare (fixnum ,i1 ,i2))
495                (%bignum-set ,n-dest ,i1
496                             (%bignum-ref ,n-src ,i2))))
497           `(let ((,n-end1 ,end1)
498                  (,n-end2 ,end2))
499              (do ((,i1 ,start1 (1+ ,i1))
500                   (,i2 ,start2 (1+ ,i2)))
501                  ((or (>= ,i1 ,n-end1) (>= ,i2 ,n-end2)))
502                (declare (type bignum-index ,i1 ,i2))
503                (%bignum-set ,n-dest ,i1
504                             (%bignum-ref ,n-src ,i2))))))))
505
506 (sb!xc:defmacro with-bignum-buffers (specs &body body)
507   #!+sb-doc
508   "WITH-BIGNUM-BUFFERS ({(var size [init])}*) Form*"
509   (sb!int:collect ((binds)
510                    (inits))
511     (dolist (spec specs)
512       (let ((name (first spec))
513             (size (second spec)))
514         (binds `(,name (%allocate-bignum ,size)))
515         (let ((init (third spec)))
516           (when init
517             (inits `(bignum-replace ,name ,init))))))
518     `(let* ,(binds)
519        ,@(inits)
520        ,@body)))
521
522 ) ;EVAL-WHEN
523 \f
524 ;;;; GCD
525
526 (defun bignum-gcd (a b)
527   (declare (type bignum-type a b))
528   (let* ((a (if (%bignum-0-or-plusp a (%bignum-length a))
529                 a
530                 (negate-bignum a nil)))
531          (b (if (%bignum-0-or-plusp b (%bignum-length b))
532                 b
533                 (negate-bignum b nil)))
534          (len-a (%bignum-length a))
535          (len-b (%bignum-length b)))
536       (declare (type bignum-index len-a len-b))
537     (with-bignum-buffers ((a-buffer len-a a)
538                           (b-buffer len-b b)
539                           (res-buffer (max len-a len-b)))
540       (let* ((factors-of-two
541               (bignum-factors-of-two a-buffer len-a
542                                      b-buffer len-b))
543              (len-a (make-gcd-bignum-odd
544                      a-buffer
545                      (bignum-buffer-ashift-right a-buffer len-a
546                                                  factors-of-two)))
547              (len-b (make-gcd-bignum-odd
548                      b-buffer
549                      (bignum-buffer-ashift-right b-buffer len-b
550                                                  factors-of-two))))
551         (declare (type bignum-index len-a len-b))
552         (let ((x a-buffer)
553               (len-x len-a)
554               (y b-buffer)
555               (len-y len-b)
556               (z res-buffer))
557           (loop
558             (multiple-value-bind (u v len-v r len-r)
559                 (bignum-gcd-order-and-subtract x len-x y len-y z)
560               (declare (type bignum-index len-v len-r))
561               (when (and (= len-r 1) (zerop (%bignum-ref r 0)))
562                 (if (zerop factors-of-two)
563                     (let ((ret (%allocate-bignum len-v)))
564                       (dotimes (i len-v)
565                         (setf (%bignum-ref ret i) (%bignum-ref v i)))
566                       (return (%normalize-bignum ret len-v)))
567                     (return (bignum-ashift-left v factors-of-two len-v))))
568               (setf x v  len-x len-v)
569               (setf y r  len-y (make-gcd-bignum-odd r len-r))
570               (setf z u))))))))
571
572 (defun bignum-gcd-order-and-subtract (a len-a b len-b res)
573   (declare (type bignum-index len-a len-b) (type bignum-type a b))
574   (cond ((= len-a len-b)
575          (do ((i (1- len-a) (1- i)))
576              ((= i -1)
577               (setf (%bignum-ref res 0) 0)
578               (values a b len-b res 1))
579            (let ((a-digit (%bignum-ref a i))
580                  (b-digit (%bignum-ref b i)))
581              (cond ((%digit-compare a-digit b-digit))
582                    ((%digit-greater a-digit b-digit)
583                     (return
584                      (values a b len-b res
585                              (subtract-bignum-buffers a len-a b len-b res))))
586                    (t
587                     (return
588                      (values b a len-a res
589                              (subtract-bignum-buffers b len-b
590                                                       a len-a
591                                                       res))))))))
592         ((> len-a len-b)
593          (values a b len-b res
594                  (subtract-bignum-buffers a len-a b len-b res)))
595         (t
596          (values b a len-a res
597                  (subtract-bignum-buffers b len-b a len-a res)))))
598
599 (defun make-gcd-bignum-odd (a len-a)
600   (declare (type bignum-type a) (type bignum-index len-a))
601   (dotimes (index len-a)
602     (declare (type bignum-index index))
603     (do ((digit (%bignum-ref a index) (%ashr digit 1))
604          (increment 0 (1+ increment)))
605         ((zerop digit))
606       (declare (type (mod 32) increment))
607       (when (oddp digit)
608         (return-from make-gcd-bignum-odd
609                      (bignum-buffer-ashift-right a len-a
610                                                  (+ (* index digit-size)
611                                                     increment)))))))
612
613 (defun bignum-factors-of-two (a len-a b len-b)
614   (declare (type bignum-index len-a len-b) (type bignum-type a))
615   (do ((i 0 (1+ i))
616        (end (min len-a len-b)))
617       ((= i end) (error "Unexpected zero bignums?"))
618     (declare (type bignum-index i end))
619     (let ((or-digits (%logior (%bignum-ref a i) (%bignum-ref b i))))
620       (unless (zerop or-digits)
621         (return (do ((j 0 (1+ j))
622                      (or-digits or-digits (%ashr or-digits 1)))
623                     ((oddp or-digits) (+ (* i digit-size) j))
624                   (declare (type (mod 32) j))))))))
625 \f
626 ;;;; negation
627
628 (eval-when (:compile-toplevel :execute)
629
630 ;;; This negates bignum-len digits of bignum, storing the resulting digits into
631 ;;; result (possibly EQ to bignum) and returning whatever end-carry there is.
632 (sb!xc:defmacro bignum-negate-loop (bignum
633                                     bignum-len
634                                     &optional (result nil resultp))
635   (let ((carry (gensym))
636         (end (gensym))
637         (value (gensym))
638         (last (gensym)))
639     `(let* (,@(if (not resultp) `(,last))
640             (,carry
641              (multiple-value-bind (,value ,carry)
642                  (%add-with-carry (%lognot (%bignum-ref ,bignum 0)) 1 0)
643                ,(if resultp
644                     `(setf (%bignum-ref ,result 0) ,value)
645                     `(setf ,last ,value))
646                ,carry))
647             (i 1)
648             (,end ,bignum-len))
649        (declare (type bit ,carry)
650                 (type bignum-index i ,end))
651        (loop
652          (when (= i ,end) (return))
653          (multiple-value-bind (,value temp)
654              (%add-with-carry (%lognot (%bignum-ref ,bignum i)) 0 ,carry)
655            ,(if resultp
656                 `(setf (%bignum-ref ,result i) ,value)
657                 `(setf ,last ,value))
658            (setf ,carry temp))
659          (incf i))
660        ,(if resultp carry `(values ,carry ,last)))))
661
662 ) ; EVAL-WHEN
663
664 ;;; Fully-normalize is an internal optional. It cause this to always return
665 ;;; a bignum, without any extraneous digits, and it never returns a fixnum.
666 (defun negate-bignum (x &optional (fully-normalize t))
667   (declare (type bignum-type x))
668   (let* ((len-x (%bignum-length x))
669          (len-res (1+ len-x))
670          (res (%allocate-bignum len-res)))
671     (declare (type bignum-index len-x len-res)) ;Test len-res for range?
672     (let ((carry (bignum-negate-loop x len-x res)))
673       (setf (%bignum-ref res len-x)
674             (%add-with-carry (%lognot (%sign-digit x len-x)) 0 carry)))
675     (if fully-normalize
676         (%normalize-bignum res len-res)
677         (%mostly-normalize-bignum res len-res))))
678
679 ;;; This assumes bignum is positive; that is, the result of negating it will
680 ;;; stay in the provided allocated bignum.
681 (defun negate-bignum-in-place (bignum)
682   (bignum-negate-loop bignum (%bignum-length bignum) bignum)
683   bignum)
684 \f
685 ;;;; shifting
686
687 (defconstant all-ones-digit #xFFFFFFFF)
688
689 (eval-when (:compile-toplevel :execute)
690
691 ;;; This macro is used by BIGNUM-ASHIFT-RIGHT, BIGNUM-BUFFER-ASHIFT-RIGHT, and
692 ;;; BIGNUM-LDB-BIGNUM-RES. They supply a termination form that references
693 ;;; locals established by this form. Source is the source bignum. Start-digit
694 ;;; is the first digit in source from which we pull bits. Start-pos is the
695 ;;; first bit we want. Res-len-form is the form that computes the length of
696 ;;; the resulting bignum. Termination is a DO termination form with a test and
697 ;;; body. When result is supplied, it is the variable to which this binds a
698 ;;; newly allocated bignum.
699 ;;;
700 ;;; Given start-pos, 1-31 inclusively, of shift, we form the j'th resulting
701 ;;; digit from high bits of the i'th source digit and the start-pos number of
702 ;;; bits from the i+1'th source digit.
703 (sb!xc:defmacro shift-right-unaligned (source
704                                        start-digit
705                                        start-pos
706                                        res-len-form
707                                        termination
708                                        &optional result)
709   `(let* ((high-bits-in-first-digit (- digit-size ,start-pos))
710           (res-len ,res-len-form)
711           (res-len-1 (1- res-len))
712           ,@(if result `((,result (%allocate-bignum res-len)))))
713      (declare (type bignum-index res-len res-len-1))
714      (do ((i ,start-digit i+1)
715           (i+1 (1+ ,start-digit) (1+ i+1))
716           (j 0 (1+ j)))
717          ,termination
718        (declare (type bignum-index i i+1 j))
719        (setf (%bignum-ref ,(if result result source) j)
720              (%logior (%digit-logical-shift-right (%bignum-ref ,source i)
721                                                   ,start-pos)
722                       (%ashl (%bignum-ref ,source i+1)
723                              high-bits-in-first-digit))))))
724
725 ) ; EVAL-WHEN
726
727 ;;; First compute the number of whole digits to shift, shifting them by
728 ;;; skipping them when we start to pick up bits, and the number of bits to
729 ;;; shift the remaining digits into place. If the number of digits is greater
730 ;;; than the length of the bignum, then the result is either 0 or -1. If we
731 ;;; shift on a digit boundary (that is, n-bits is zero), then we just copy
732 ;;; digits. The last branch handles the general case which uses a macro that a
733 ;;; couple other routines use. The fifth argument to the macro references
734 ;;; locals established by the macro.
735 (defun bignum-ashift-right (bignum count)
736   (declare (type bignum-type bignum)
737            (type unsigned-byte count))
738   (let ((bignum-len (%bignum-length bignum)))
739     (declare (type bignum-index bignum-len))
740     (cond ((fixnump count)
741            (multiple-value-bind (digits n-bits) (truncate count digit-size)
742              (declare (type bignum-index digits))
743              (cond
744               ((>= digits bignum-len)
745                (if (%bignum-0-or-plusp bignum bignum-len) 0 -1))
746               ((zerop n-bits)
747                (bignum-ashift-right-digits bignum digits))
748               (t
749                (shift-right-unaligned bignum digits n-bits (- bignum-len digits)
750                                       ((= j res-len-1)
751                                        (setf (%bignum-ref res j)
752                                              (%ashr (%bignum-ref bignum i) n-bits))
753                                        (%normalize-bignum res res-len))
754                                       res)))))
755           ((> count bignum-len)
756            0)
757            ;; Since a FIXNUM should be big enough to address anything in
758            ;; memory, including arrays of bits, and since arrays of bits
759            ;; take up about the same space as corresponding fixnums, there
760            ;; should be no way that we fall through to this case: any shift
761            ;; right by a bignum should give zero. But let's check anyway:
762           (t (error "bignum overflow: can't shift right by ~S")))))
763
764 (defun bignum-ashift-right-digits (bignum digits)
765   (declare (type bignum-type bignum)
766            (type bignum-index digits))
767   (let* ((res-len (- (%bignum-length bignum) digits))
768          (res (%allocate-bignum res-len)))
769     (declare (type bignum-index res-len)
770              (type bignum-type res))
771     (bignum-replace res bignum :start2 digits)
772     (%normalize-bignum res res-len)))
773
774 ;;; GCD uses this for an in-place shifting operation. This is different enough
775 ;;; from BIGNUM-ASHIFT-RIGHT that it isn't worth folding the bodies into a
776 ;;; macro, but they share the basic algorithm. This routine foregoes a first
777 ;;; test for digits being greater than or equal to bignum-len since that will
778 ;;; never happen for its uses in GCD. We did fold the last branch into a macro
779 ;;; since it was duplicated a few times, and the fifth argument to it
780 ;;; references locals established by the macro.
781 (defun bignum-buffer-ashift-right (bignum bignum-len x)
782   (declare (type bignum-index bignum-len) (fixnum x))
783   (multiple-value-bind (digits n-bits) (truncate x digit-size)
784     (declare (type bignum-index digits))
785     (cond
786      ((zerop n-bits)
787       (let ((new-end (- bignum-len digits)))
788         (bignum-replace bignum bignum :end1 new-end :start2 digits
789                         :end2 bignum-len)
790         (%normalize-bignum-buffer bignum new-end)))
791      (t
792       (shift-right-unaligned bignum digits n-bits (- bignum-len digits)
793                              ((= j res-len-1)
794                               (setf (%bignum-ref bignum j)
795                                     (%ashr (%bignum-ref bignum i) n-bits))
796                               (%normalize-bignum-buffer bignum res-len)))))))
797
798 ;;; This handles shifting a bignum buffer to provide fresh bignum data for some
799 ;;; internal routines. We know bignum is safe when called with bignum-len.
800 ;;; First we compute the number of whole digits to shift, shifting them
801 ;;; starting to store farther along the result bignum. If we shift on a digit
802 ;;; boundary (that is, n-bits is zero), then we just copy digits. The last
803 ;;; branch handles the general case.
804 (defun bignum-ashift-left (bignum x &optional bignum-len)
805   (declare (type bignum-type bignum)
806            (type unsigned-byte x)
807            (type (or null bignum-index) bignum-len))
808   (if (fixnump x)
809     (multiple-value-bind (digits n-bits) (truncate x digit-size)
810       (let* ((bignum-len (or bignum-len (%bignum-length bignum)))
811              (res-len (+ digits bignum-len 1)))
812         (when (> res-len maximum-bignum-length)
813           (error "can't represent result of left shift"))
814         (if (zerop n-bits)
815           (bignum-ashift-left-digits bignum bignum-len digits)
816           (bignum-ashift-left-unaligned bignum digits n-bits res-len))))
817     ;; Left shift by a number too big to be represented as a fixnum
818     ;; would exceed our memory capacity, since a fixnum is big enough
819     ;; index any array, including a bit array.
820     (error "can't represent result of left shift")))
821
822 (defun bignum-ashift-left-digits (bignum bignum-len digits)
823   (declare (type bignum-index bignum-len digits))
824   (let* ((res-len (+ bignum-len digits))
825          (res (%allocate-bignum res-len)))
826     (declare (type bignum-index res-len))
827     (bignum-replace res bignum :start1 digits :end1 res-len :end2 bignum-len
828                     :from-end t)
829     res))
830
831 ;;; BIGNUM-TRUNCATE uses this to store into a bignum buffer by supplying res.
832 ;;; When res comes in non-nil, then this foregoes allocating a result, and it
833 ;;; normalizes the buffer instead of the would-be allocated result.
834 ;;;
835 ;;; We start storing into one digit higher than digits, storing a whole result
836 ;;; digit from parts of two contiguous digits from bignum. When the loop
837 ;;; finishes, we store the remaining bits from bignum's first digit in the
838 ;;; first non-zero result digit, digits. We also grab some left over high
839 ;;; bits from the last digit of bignum.
840 (defun bignum-ashift-left-unaligned (bignum digits n-bits res-len
841                                      &optional (res nil resp))
842   (declare (type bignum-index digits res-len)
843            (type (mod #.digit-size) n-bits))
844   (let* ((remaining-bits (- digit-size n-bits))
845          (res-len-1 (1- res-len))
846          (res (or res (%allocate-bignum res-len))))
847     (declare (type bignum-index res-len res-len-1))
848     (do ((i 0 i+1)
849          (i+1 1 (1+ i+1))
850          (j (1+ digits) (1+ j)))
851         ((= j res-len-1)
852          (setf (%bignum-ref res digits)
853                (%ashl (%bignum-ref bignum 0) n-bits))
854          (setf (%bignum-ref res j)
855                (%ashr (%bignum-ref bignum i) remaining-bits))
856          (if resp
857              (%normalize-bignum-buffer res res-len)
858              (%normalize-bignum res res-len)))
859       (declare (type bignum-index i i+1 j))
860       (setf (%bignum-ref res j)
861             (%logior (%digit-logical-shift-right (%bignum-ref bignum i)
862                                                  remaining-bits)
863                      (%ashl (%bignum-ref bignum i+1) n-bits))))))
864 \f
865 ;;;; relational operators
866
867 ;;; Return T iff bignum is positive.
868 (defun bignum-plus-p (bignum)
869   (declare (type bignum-type bignum))
870   (%bignum-0-or-plusp bignum (%bignum-length bignum)))
871
872 ;;; This compares two bignums returning -1, 0, or 1, depending on
873 ;;; whether a is less than, equal to, or greater than b.
874 (declaim (ftype (function (bignum bignum) (integer -1 1)) bignum-compare))
875 (defun bignum-compare (a b)
876   (declare (type bignum-type a b))
877   (let* ((len-a (%bignum-length a))
878          (len-b (%bignum-length b))
879          (a-plusp (%bignum-0-or-plusp a len-a))
880          (b-plusp (%bignum-0-or-plusp b len-b)))
881     (declare (type bignum-index len-a len-b))
882     (cond ((not (eq a-plusp b-plusp))
883            (if a-plusp 1 -1))
884           ((= len-a len-b)
885            (do ((i (1- len-a) (1- i)))
886                (())
887              (declare (type bignum-index i))
888              (let ((a-digit (%bignum-ref a i))
889                    (b-digit (%bignum-ref b i)))
890                (declare (type bignum-element-type a-digit b-digit))
891                (when (%digit-greater a-digit b-digit)
892                  (return 1))
893                (when (%digit-greater b-digit a-digit)
894                  (return -1)))
895              (when (zerop i) (return 0))))
896           ((> len-a len-b)
897            (if a-plusp 1 -1))
898           (t (if a-plusp -1 1)))))
899 \f
900 ;;;; float conversion
901
902 ;;; Make a single or double float with the specified significand,
903 ;;; exponent and sign.
904 (defun single-float-from-bits (bits exp plusp)
905   (declare (fixnum exp))
906   (declare (optimize #-sb-xc-host (sb!ext:inhibit-warnings 3)))
907   (let ((res (dpb exp
908                   sb!vm:single-float-exponent-byte
909                   (logandc2 (sb!ext:truly-the (unsigned-byte 31)
910                                               (%bignum-ref bits 1))
911                             sb!vm:single-float-hidden-bit))))
912     (make-single-float
913      (if plusp
914          res
915          (logior res (ash -1 sb!vm:float-sign-shift))))))
916 (defun double-float-from-bits (bits exp plusp)
917   (declare (fixnum exp))
918   (declare (optimize #-sb-xc-host (sb!ext:inhibit-warnings 3)))
919   (let ((hi (dpb exp
920                  sb!vm:double-float-exponent-byte
921                  (logandc2 (sb!ext:truly-the (unsigned-byte 31)
922                                              (%bignum-ref bits 2))
923                            sb!vm:double-float-hidden-bit))))
924     (make-double-float
925      (if plusp
926          hi
927          (logior hi (ash -1 sb!vm:float-sign-shift)))
928      (%bignum-ref bits 1))))
929 #!+(and long-float x86)
930 (defun long-float-from-bits (bits exp plusp)
931   (declare (fixnum exp))
932   (declare (optimize #-sb-xc-host (sb!ext:inhibit-warnings 3)))
933   (make-long-float
934    (if plusp
935        exp
936        (logior exp (ash 1 15)))
937    (%bignum-ref bits 2)
938    (%bignum-ref bits 1)))
939
940 ;;; Convert Bignum to a float in the specified Format, rounding to the best
941 ;;; approximation.
942 (defun bignum-to-float (bignum format)
943   (let* ((plusp (bignum-plus-p bignum))
944          (x (if plusp bignum (negate-bignum bignum)))
945          (len (bignum-integer-length x))
946          (digits (float-format-digits format))
947          (keep (+ digits digit-size))
948          (shift (- keep len))
949          (shifted (if (minusp shift)
950                       (bignum-ashift-right x (- shift))
951                       (bignum-ashift-left x shift)))
952          (low (%bignum-ref shifted 0))
953          (round-bit (ash 1 (1- digit-size))))
954     (declare (type bignum-index len digits keep) (fixnum shift))
955     (labels ((round-up ()
956                (let ((rounded (add-bignums shifted round-bit)))
957                  (if (> (integer-length rounded) keep)
958                      (float-from-bits (bignum-ashift-right rounded 1)
959                                       (1+ len))
960                      (float-from-bits rounded len))))
961              (float-from-bits (bits len)
962                (declare (type bignum-index len))
963                (ecase format
964                  (single-float
965                   (single-float-from-bits
966                    bits
967                    (check-exponent len sb!vm:single-float-bias
968                                    sb!vm:single-float-normal-exponent-max)
969                    plusp))
970                  (double-float
971                   (double-float-from-bits
972                    bits
973                    (check-exponent len sb!vm:double-float-bias
974                                    sb!vm:double-float-normal-exponent-max)
975                    plusp))
976                  #!+long-float
977                  (long-float
978                   (long-float-from-bits
979                    bits
980                    (check-exponent len sb!vm:long-float-bias
981                                    sb!vm:long-float-normal-exponent-max)
982                    plusp))))
983              (check-exponent (exp bias max)
984                (declare (type bignum-index len))
985                (let ((exp (+ exp bias)))
986                  (when (> exp max)
987                    (error "Too large to be represented as a ~S:~%  ~S"
988                           format x))
989                  exp)))
990
991     (cond
992      ;; Round down if round bit is 0.
993      ((zerop (logand round-bit low))
994       (float-from-bits shifted len))
995      ;; If only round bit is set, then round to even.
996      ((and (= low round-bit)
997            (dotimes (i (- (%bignum-length x) (ceiling keep digit-size))
998                        t)
999              (unless (zerop (%bignum-ref x i)) (return nil))))
1000       (let ((next (%bignum-ref shifted 1)))
1001         (if (oddp next)
1002             (round-up)
1003             (float-from-bits shifted len))))
1004      ;; Otherwise, round up.
1005      (t
1006       (round-up))))))
1007 \f
1008 ;;;; integer length and logcount
1009
1010 (defun bignum-integer-length (bignum)
1011   (declare (type bignum-type bignum))
1012   (let* ((len (%bignum-length bignum))
1013          (len-1 (1- len))
1014          (digit (%bignum-ref bignum len-1)))
1015     (declare (type bignum-index len len-1)
1016              (type bignum-element-type digit))
1017     (+ (integer-length (%fixnum-digit-with-correct-sign digit))
1018        (* len-1 digit-size))))
1019
1020 (defun bignum-logcount (bignum)
1021   (declare (type bignum-type bignum))
1022   (let* ((length (%bignum-length bignum))
1023          (plusp (%bignum-0-or-plusp bignum length))
1024          (result 0))
1025     (declare (type bignum-index length)
1026              (fixnum result))
1027     (do ((index 0 (1+ index)))
1028         ((= index length) result)
1029       (let ((digit (%bignum-ref bignum index)))
1030         (declare (type bignum-element-type digit))
1031         (incf result (logcount (if plusp digit (%lognot digit))))))))
1032 \f
1033 ;;;; logical operations
1034
1035 ;;;; NOT
1036
1037 (defun bignum-logical-not (a)
1038   (declare (type bignum-type a))
1039   (let* ((len (%bignum-length a))
1040          (res (%allocate-bignum len)))
1041     (declare (type bignum-index len))
1042     (dotimes (i len res)
1043       (declare (type bignum-index i))
1044       (setf (%bignum-ref res i) (%lognot (%bignum-ref a i))))))
1045
1046 ;;;; AND
1047
1048 (defun bignum-logical-and (a b)
1049   (declare (type bignum-type a b))
1050   (let* ((len-a (%bignum-length a))
1051          (len-b (%bignum-length b))
1052          (a-plusp (%bignum-0-or-plusp a len-a))
1053          (b-plusp (%bignum-0-or-plusp b len-b)))
1054     (declare (type bignum-index len-a len-b))
1055     (cond
1056      ((< len-a len-b)
1057       (if a-plusp
1058           (logand-shorter-positive a len-a b (%allocate-bignum len-a))
1059           (logand-shorter-negative a len-a b len-b (%allocate-bignum len-b))))
1060      ((< len-b len-a)
1061       (if b-plusp
1062           (logand-shorter-positive b len-b a (%allocate-bignum len-b))
1063           (logand-shorter-negative b len-b a len-a (%allocate-bignum len-a))))
1064      (t (logand-shorter-positive a len-a b (%allocate-bignum len-a))))))
1065
1066 ;;; This takes a shorter bignum, a and len-a, that is positive. Because this
1067 ;;; is AND, we don't care about any bits longer than a's since its infinite 0
1068 ;;; sign bits will mask the other bits out of b. The result is len-a big.
1069 (defun logand-shorter-positive (a len-a b res)
1070   (declare (type bignum-type a b res)
1071            (type bignum-index len-a))
1072   (dotimes (i len-a)
1073     (declare (type bignum-index i))
1074     (setf (%bignum-ref res i)
1075           (%logand (%bignum-ref a i) (%bignum-ref b i))))
1076   (%normalize-bignum res len-a))
1077
1078 ;;; This takes a shorter bignum, a and len-a, that is negative. Because this
1079 ;;; is AND, we just copy any bits longer than a's since its infinite 1 sign
1080 ;;; bits will include any bits from b. The result is len-b big.
1081 (defun logand-shorter-negative (a len-a b len-b res)
1082   (declare (type bignum-type a b res)
1083            (type bignum-index len-a len-b))
1084   (dotimes (i len-a)
1085     (declare (type bignum-index i))
1086     (setf (%bignum-ref res i)
1087           (%logand (%bignum-ref a i) (%bignum-ref b i))))
1088   (do ((i len-a (1+ i)))
1089       ((= i len-b))
1090     (declare (type bignum-index i))
1091     (setf (%bignum-ref res i) (%bignum-ref b i)))
1092   (%normalize-bignum res len-b))
1093
1094 ;;;; IOR
1095
1096 (defun bignum-logical-ior (a b)
1097   (declare (type bignum-type a b))
1098   (let* ((len-a (%bignum-length a))
1099          (len-b (%bignum-length b))
1100          (a-plusp (%bignum-0-or-plusp a len-a))
1101          (b-plusp (%bignum-0-or-plusp b len-b)))
1102     (declare (type bignum-index len-a len-b))
1103     (cond
1104      ((< len-a len-b)
1105       (if a-plusp
1106           (logior-shorter-positive a len-a b len-b (%allocate-bignum len-b))
1107           (logior-shorter-negative a len-a b len-b (%allocate-bignum len-b))))
1108      ((< len-b len-a)
1109       (if b-plusp
1110           (logior-shorter-positive b len-b a len-a (%allocate-bignum len-a))
1111           (logior-shorter-negative b len-b a len-a (%allocate-bignum len-a))))
1112      (t (logior-shorter-positive a len-a b len-b (%allocate-bignum len-a))))))
1113
1114 ;;; This takes a shorter bignum, a and len-a, that is positive. Because this
1115 ;;; is IOR, we don't care about any bits longer than a's since its infinite
1116 ;;; 0 sign bits will mask the other bits out of b out to len-b. The result
1117 ;;; is len-b long.
1118 (defun logior-shorter-positive (a len-a b len-b res)
1119   (declare (type bignum-type a b res)
1120            (type bignum-index len-a len-b))
1121   (dotimes (i len-a)
1122     (declare (type bignum-index i))
1123     (setf (%bignum-ref res i)
1124           (%logior (%bignum-ref a i) (%bignum-ref b i))))
1125   (do ((i len-a (1+ i)))
1126       ((= i len-b))
1127     (declare (type bignum-index i))
1128     (setf (%bignum-ref res i) (%bignum-ref b i)))
1129   (%normalize-bignum res len-b))
1130
1131 ;;; This takes a shorter bignum, a and len-a, that is negative. Because this
1132 ;;; is IOR, we just copy any bits longer than a's since its infinite 1 sign
1133 ;;; bits will include any bits from b. The result is len-b long.
1134 (defun logior-shorter-negative (a len-a b len-b res)
1135   (declare (type bignum-type a b res)
1136            (type bignum-index len-a len-b))
1137   (dotimes (i len-a)
1138     (declare (type bignum-index i))
1139     (setf (%bignum-ref res i)
1140           (%logior (%bignum-ref a i) (%bignum-ref b i))))
1141   (do ((i len-a (1+ i))
1142        (sign (%sign-digit a len-a)))
1143       ((= i len-b))
1144     (declare (type bignum-index i))
1145     (setf (%bignum-ref res i) sign))
1146   (%normalize-bignum res len-b))
1147
1148 ;;;; XOR
1149
1150 (defun bignum-logical-xor (a b)
1151   (declare (type bignum-type a b))
1152   (let ((len-a (%bignum-length a))
1153         (len-b (%bignum-length b)))
1154     (declare (type bignum-index len-a len-b))
1155     (if (< len-a len-b)
1156         (bignum-logical-xor-aux a len-a b len-b (%allocate-bignum len-b))
1157         (bignum-logical-xor-aux b len-b a len-a (%allocate-bignum len-a)))))
1158
1159 ;;; This takes the shorter of two bignums in a and len-a. Res is len-b
1160 ;;; long. Do the XOR.
1161 (defun bignum-logical-xor-aux (a len-a b len-b res)
1162   (declare (type bignum-type a b res)
1163            (type bignum-index len-a len-b))
1164   (dotimes (i len-a)
1165     (declare (type bignum-index i))
1166     (setf (%bignum-ref res i)
1167           (%logxor (%bignum-ref a i) (%bignum-ref b i))))
1168   (do ((i len-a (1+ i))
1169        (sign (%sign-digit a len-a)))
1170       ((= i len-b))
1171     (declare (type bignum-index i))
1172     (setf (%bignum-ref res i) (%logxor sign (%bignum-ref b i))))
1173   (%normalize-bignum res len-b))
1174 \f
1175 ;;;; LDB (load byte)
1176
1177 #|
1178 FOR NOW WE DON'T USE LDB OR DPB. WE USE SHIFTS AND MASKS IN NUMBERS.LISP WHICH
1179 IS LESS EFFICIENT BUT EASIER TO MAINTAIN. BILL SAYS THIS CODE CERTAINLY WORKS!
1180
1181 (defconstant maximum-fixnum-bits #!+ibm-rt-pc 27 #!-ibm-rt-pc 30)
1182
1183 (defun bignum-load-byte (byte bignum)
1184   (declare (type bignum-type bignum))
1185   (let ((byte-len (byte-size byte))
1186         (byte-pos (byte-position byte)))
1187     (if (< byte-len maximum-fixnum-bits)
1188         (bignum-ldb-fixnum-res bignum byte-len byte-pos)
1189         (bignum-ldb-bignum-res bignum byte-len byte-pos))))
1190
1191 ;;; This returns a fixnum result of loading a byte from a bignum. In order, we
1192 ;;; check for the following conditions:
1193 ;;;    Insufficient bignum digits to start loading a byte --
1194 ;;;       Return 0 or byte-len 1's depending on sign of bignum.
1195 ;;;    One bignum digit containing the whole byte spec --
1196 ;;;       Grab 'em, shift 'em, and mask out what we don't want.
1197 ;;;    Insufficient bignum digits to cover crossing a digit boundary --
1198 ;;;       Grab the available bits in the last digit, and or in whatever
1199 ;;;       virtual sign bits we need to return a full byte spec.
1200 ;;;    Else (we cross a digit boundary with all bits available) --
1201 ;;;       Make a couple masks, grab what we want, shift it around, and
1202 ;;;       LOGIOR it all together.
1203 ;;; Because (< maximum-fixnum-bits digit-size) and
1204 ;;;      (< byte-len maximum-fixnum-bits),
1205 ;;; we only cross one digit boundary if any.
1206 (defun bignum-ldb-fixnum-res (bignum byte-len byte-pos)
1207   (multiple-value-bind (skipped-digits pos) (truncate byte-pos digit-size)
1208     (let ((bignum-len (%bignum-length bignum))
1209           (s-digits+1 (1+ skipped-digits)))
1210       (declare (type bignum-index bignum-len s-digits+1))
1211       (if (>= skipped-digits bignum-len)
1212           (if (%bignum-0-or-plusp bignum bignum-len)
1213               0
1214               (%make-ones byte-len))
1215           (let ((end (+ pos byte-len)))
1216             (cond ((<= end digit-size)
1217                    (logand (ash (%bignum-ref bignum skipped-digits) (- pos))
1218                            ;; Must LOGAND after shift here.
1219                            (%make-ones byte-len)))
1220                   ((>= s-digits+1 bignum-len)
1221                    (let* ((available-bits (- digit-size pos))
1222                           (res (logand (ash (%bignum-ref bignum skipped-digits)
1223                                             (- pos))
1224                                        ;; LOGAND should be unnecessary here
1225                                        ;; with a logical right shift or a
1226                                        ;; correct unsigned-byte-32 one.
1227                                        (%make-ones available-bits))))
1228                      (if (%bignum-0-or-plusp bignum bignum-len)
1229                          res
1230                          (logior (%ashl (%make-ones (- end digit-size))
1231                                         available-bits)
1232                                  res))))
1233                   (t
1234                    (let* ((high-bits-in-first-digit (- digit-size pos))
1235                           (high-mask (%make-ones high-bits-in-first-digit))
1236                           (low-bits-in-next-digit (- end digit-size))
1237                           (low-mask (%make-ones low-bits-in-next-digit)))
1238                      (declare (type bignum-element-type high-mask low-mask))
1239                      (logior (%ashl (logand (%bignum-ref bignum s-digits+1)
1240                                             low-mask)
1241                                     high-bits-in-first-digit)
1242                              (logand (ash (%bignum-ref bignum skipped-digits)
1243                                           (- pos))
1244                                      ;; LOGAND should be unnecessary here with
1245                                      ;; a logical right shift or a correct
1246                                      ;; unsigned-byte-32 one.
1247                                      high-mask))))))))))
1248
1249 ;;; This returns a bignum result of loading a byte from a bignum. In order, we
1250 ;;; check for the following conditions:
1251 ;;;    Insufficient bignum digits to start loading a byte --
1252 ;;;    Byte-pos starting on a digit boundary --
1253 ;;;    Byte spec contained in one bignum digit --
1254 ;;;       Grab the bits we want and stick them in a single digit result.
1255 ;;;       Since we know byte-pos is non-zero here, we know our single digit
1256 ;;;       will have a zero high sign bit.
1257 ;;;    Else (unaligned multiple digits) --
1258 ;;;       This is like doing a shift right combined with either masking
1259 ;;;       out unwanted high bits from bignum or filling in virtual sign
1260 ;;;       bits if bignum had insufficient bits. We use SHIFT-RIGHT-ALIGNED
1261 ;;;       and reference lots of local variables this macro establishes.
1262 (defun bignum-ldb-bignum-res (bignum byte-len byte-pos)
1263   (multiple-value-bind (skipped-digits pos) (truncate byte-pos digit-size)
1264     (let ((bignum-len (%bignum-length bignum)))
1265       (declare (type bignum-index bignum-len))
1266       (cond
1267        ((>= skipped-digits bignum-len)
1268         (make-bignum-virtual-ldb-bits bignum bignum-len byte-len))
1269        ((zerop pos)
1270         (make-aligned-ldb-bignum bignum bignum-len byte-len skipped-digits))
1271        ((< (+ pos byte-len) digit-size)
1272         (let ((res (%allocate-bignum 1)))
1273           (setf (%bignum-ref res 0)
1274                 (logand (%ashr (%bignum-ref bignum skipped-digits) pos)
1275                         (%make-ones byte-len)))
1276           res))
1277        (t
1278         (make-unaligned-ldb-bignum bignum bignum-len
1279                                    byte-len skipped-digits pos))))))
1280
1281 ;;; This returns bits from bignum that don't physically exist. These are
1282 ;;; all zero or one depending on the sign of the bignum.
1283 (defun make-bignum-virtual-ldb-bits (bignum bignum-len byte-len)
1284   (if (%bignum-0-or-plusp bignum bignum-len)
1285       0
1286       (multiple-value-bind (res-len-1 extra) (truncate byte-len digit-size)
1287         (declare (type bignum-index res-len-1))
1288         (let* ((res-len (1+ res-len-1))
1289                (res (%allocate-bignum res-len)))
1290           (declare (type bignum-index res-len))
1291           (do ((j 0 (1+ j)))
1292               ((= j res-len-1)
1293                (setf (%bignum-ref res j) (%make-ones extra))
1294                (%normalize-bignum res res-len))
1295             (declare (type bignum-index j))
1296             (setf (%bignum-ref res j) all-ones-digit))))))
1297
1298 ;;; Since we are picking up aligned digits, we just copy the whole digits
1299 ;;; we want and fill in extra bits. We might have a byte-len that extends
1300 ;;; off the end of the bignum, so we may have to fill in extra 1's if the
1301 ;;; bignum is negative.
1302 (defun make-aligned-ldb-bignum (bignum bignum-len byte-len skipped-digits)
1303   (multiple-value-bind (res-len-1 extra) (truncate byte-len digit-size)
1304     (declare (type bignum-index res-len-1))
1305     (let* ((res-len (1+ res-len-1))
1306            (res (%allocate-bignum res-len)))
1307       (declare (type bignum-index res-len))
1308       (do ((i skipped-digits (1+ i))
1309            (j 0 (1+ j)))
1310           ((or (= j res-len-1) (= i bignum-len))
1311            (cond ((< i bignum-len)
1312                   (setf (%bignum-ref res j)
1313                         (logand (%bignum-ref bignum i)
1314                                 (the bignum-element-type (%make-ones extra)))))
1315                  ((%bignum-0-or-plusp bignum bignum-len))
1316                  (t
1317                   (do ((j j (1+ j)))
1318                       ((= j res-len-1)
1319                        (setf (%bignum-ref res j) (%make-ones extra)))
1320                     (setf (%bignum-ref res j) all-ones-digit))))
1321            (%normalize-bignum res res-len))
1322       (declare (type bignum-index i j))
1323       (setf (%bignum-ref res j) (%bignum-ref bignum i))))))
1324
1325 ;;; This grabs unaligned bignum bits from bignum assuming byte-len causes at
1326 ;;; least one digit boundary crossing. We use SHIFT-RIGHT-UNALIGNED referencing
1327 ;;; lots of local variables established by it.
1328 (defun make-unaligned-ldb-bignum (bignum
1329                                   bignum-len
1330                                   byte-len
1331                                   skipped-digits
1332                                   pos)
1333   (multiple-value-bind (res-len-1 extra) (truncate byte-len digit-size)
1334     (shift-right-unaligned
1335      bignum skipped-digits pos (1+ res-len-1)
1336      ((or (= j res-len-1) (= i+1 bignum-len))
1337       (cond ((= j res-len-1)
1338              (cond
1339               ((< extra high-bits-in-first-digit)
1340                (setf (%bignum-ref res j)
1341                      (logand (ash (%bignum-ref bignum i) minus-start-pos)
1342                              ;; Must LOGAND after shift here.
1343                              (%make-ones extra))))
1344               (t
1345                (setf (%bignum-ref res j)
1346                      (logand (ash (%bignum-ref bignum i) minus-start-pos)
1347                              ;; LOGAND should be unnecessary here with a logical
1348                              ;; right shift or a correct unsigned-byte-32 one.
1349                              high-mask))
1350                (when (%bignum-0-or-plusp bignum bignum-len)
1351                  (setf (%bignum-ref res j)
1352                        (logior (%bignum-ref res j)
1353                                (%ashl (%make-ones
1354                                        (- extra high-bits-in-first-digit))
1355                                       high-bits-in-first-digit)))))))
1356             (t
1357              (setf (%bignum-ref res j)
1358                    (logand (ash (%bignum-ref bignum i) minus-start-pos)
1359                            ;; LOGAND should be unnecessary here with a logical
1360                            ;; right shift or a correct unsigned-byte-32 one.
1361                            high-mask))
1362              (unless (%bignum-0-or-plusp bignum bignum-len)
1363                ;; Fill in upper half of this result digit with 1's.
1364                (setf (%bignum-ref res j)
1365                      (logior (%bignum-ref res j)
1366                              (%ashl low-mask high-bits-in-first-digit)))
1367                ;; Fill in any extra 1's we need to be byte-len long.
1368                (do ((j (1+ j) (1+ j)))
1369                    ((>= j res-len-1)
1370                     (setf (%bignum-ref res j) (%make-ones extra)))
1371                  (setf (%bignum-ref res j) all-ones-digit)))))
1372       (%normalize-bignum res res-len))
1373      res)))
1374 \f
1375 ;;;; DPB (deposit byte)
1376
1377 (defun bignum-deposit-byte (new-byte byte-spec bignum)
1378   (declare (type bignum-type bignum))
1379   (let* ((byte-len (byte-size byte-spec))
1380          (byte-pos (byte-position byte-spec))
1381          (bignum-len (%bignum-length bignum))
1382          (bignum-plusp (%bignum-0-or-plusp bignum bignum-len))
1383          (byte-end (+ byte-pos byte-len))
1384          (res-len (1+ (max (ceiling byte-end digit-size) bignum-len)))
1385          (res (%allocate-bignum res-len)))
1386     (declare (type bignum-index bignum-len res-len))
1387     ;; Fill in an extra sign digit in case we set what would otherwise be the
1388     ;; last digit's last bit. Normalize at the end in case this was
1389     ;; unnecessary.
1390     (unless bignum-plusp
1391       (setf (%bignum-ref res (1- res-len)) all-ones-digit))
1392     (multiple-value-bind (end-digit end-bits) (truncate byte-end digit-size)
1393       (declare (type bignum-index end-digit))
1394       ;; Fill in bits from bignum up to byte-pos.
1395       (multiple-value-bind (pos-digit pos-bits) (truncate byte-pos digit-size)
1396         (declare (type bignum-index pos-digit))
1397         (do ((i 0 (1+ i))
1398              (end (min pos-digit bignum-len)))
1399             ((= i end)
1400              (cond ((< i bignum-len)
1401                     (unless (zerop pos-bits)
1402                       (setf (%bignum-ref res i)
1403                             (logand (%bignum-ref bignum i)
1404                                     (%make-ones pos-bits)))))
1405                    (bignum-plusp)
1406                    (t
1407                     (do ((i i (1+ i)))
1408                         ((= i pos-digit)
1409                          (unless (zerop pos-bits)
1410                            (setf (%bignum-ref res i) (%make-ones pos-bits))))
1411                       (setf (%bignum-ref res i) all-ones-digit)))))
1412           (setf (%bignum-ref res i) (%bignum-ref bignum i)))
1413         ;; Fill in bits from new-byte.
1414         (if (typep new-byte 'fixnum)
1415             (deposit-fixnum-bits new-byte byte-len pos-digit pos-bits
1416                                  end-digit end-bits res)
1417             (deposit-bignum-bits new-byte byte-len pos-digit pos-bits
1418                                  end-digit end-bits res)))
1419       ;; Fill in remaining bits from bignum after byte-spec.
1420       (when (< end-digit bignum-len)
1421         (setf (%bignum-ref res end-digit)
1422               (logior (logand (%bignum-ref bignum end-digit)
1423                               (%ashl (%make-ones (- digit-size end-bits))
1424                                      end-bits))
1425                       ;; DEPOSIT-FIXNUM-BITS and DEPOSIT-BIGNUM-BITS only store
1426                       ;; bits from new-byte into res's end-digit element, so
1427                       ;; we don't need to mask out unwanted high bits.
1428                       (%bignum-ref res end-digit)))
1429         (do ((i (1+ end-digit) (1+ i)))
1430             ((= i bignum-len))
1431           (setf (%bignum-ref res i) (%bignum-ref bignum i)))))
1432     (%normalize-bignum res res-len)))
1433
1434 ;;; This starts at result's pos-digit skipping pos-bits, and it stores bits
1435 ;;; from new-byte, a fixnum, into result. It effectively stores byte-len
1436 ;;; number of bits, but never stores past end-digit and end-bits in result.
1437 ;;; The first branch fires when all the bits we want from new-byte are present;
1438 ;;; if byte-len crosses from the current result digit into the next, the last
1439 ;;; argument to DEPOSIT-FIXNUM-DIGIT is a mask for those bits. The second
1440 ;;; branch handles the need to grab more bits than the fixnum new-byte has, but
1441 ;;; new-byte is positive; therefore, any virtual bits are zero. The mask for
1442 ;;; bits that don't fit in the current result digit is simply the remaining
1443 ;;; bits in the bignum digit containing new-byte; we don't care if we store
1444 ;;; some extra in the next result digit since they will be zeros. The last
1445 ;;; branch handles the need to grab more bits than the fixnum new-byte has, but
1446 ;;; new-byte is negative; therefore, any virtual bits must be explicitly filled
1447 ;;; in as ones. We call DEPOSIT-FIXNUM-DIGIT to grab what bits actually exist
1448 ;;; and to fill in the current result digit.
1449 (defun deposit-fixnum-bits (new-byte byte-len pos-digit pos-bits
1450                             end-digit end-bits result)
1451   (declare (type bignum-index pos-digit end-digit))
1452   (let ((other-bits (- digit-size pos-bits))
1453         (new-byte-digit (%fixnum-to-digit new-byte)))
1454     (declare (type bignum-element-type new-byte-digit))
1455     (cond ((< byte-len maximum-fixnum-bits)
1456            (deposit-fixnum-digit new-byte-digit byte-len pos-digit pos-bits
1457                                  other-bits result
1458                                  (- byte-len other-bits)))
1459           ((or (plusp new-byte) (zerop new-byte))
1460            (deposit-fixnum-digit new-byte-digit byte-len pos-digit pos-bits
1461                                  other-bits result pos-bits))
1462           (t
1463            (multiple-value-bind (digit bits)
1464                (deposit-fixnum-digit new-byte-digit byte-len pos-digit pos-bits
1465                                      other-bits result
1466                                      (if (< (- byte-len other-bits) digit-size)
1467                                          (- byte-len other-bits)
1468                                          digit-size))
1469              (declare (type bignum-index digit))
1470              (cond ((< digit end-digit)
1471                     (setf (%bignum-ref result digit)
1472                           (logior (%bignum-ref result digit)
1473                                   (%ashl (%make-ones (- digit-size bits)) bits)))
1474                     (do ((i (1+ digit) (1+ i)))
1475                         ((= i end-digit)
1476                          (setf (%bignum-ref result i) (%make-ones end-bits)))
1477                       (setf (%bignum-ref result i) all-ones-digit)))
1478                    ((> digit end-digit))
1479                    ((< bits end-bits)
1480                     (setf (%bignum-ref result digit)
1481                           (logior (%bignum-ref result digit)
1482                                   (%ashl (%make-ones (- end-bits bits))
1483                                          bits))))))))))
1484
1485 ;;; This fills in the current result digit from new-byte-digit. The first case
1486 ;;; handles everything we want fitting in the current digit, and other-bits is
1487 ;;; the number of bits remaining to be filled in result's current digit. This
1488 ;;; number is digit-size minus pos-bits. The second branch handles filling in
1489 ;;; result's current digit, and it shoves the unused bits of new-byte-digit
1490 ;;; into the next result digit. This is correct regardless of new-byte-digit's
1491 ;;; sign. It returns the new current result digit and how many bits already
1492 ;;; filled in the result digit.
1493 (defun deposit-fixnum-digit (new-byte-digit byte-len pos-digit pos-bits
1494                              other-bits result next-digit-bits-needed)
1495   (declare (type bignum-index pos-digit)
1496            (type bignum-element-type new-byte-digit next-digit-mask))
1497   (cond ((<= byte-len other-bits)
1498          ;; Bits from new-byte fit in the current result digit.
1499          (setf (%bignum-ref result pos-digit)
1500                (logior (%bignum-ref result pos-digit)
1501                        (%ashl (logand new-byte-digit (%make-ones byte-len))
1502                               pos-bits)))
1503          (if (= byte-len other-bits)
1504              (values (1+ pos-digit) 0)
1505              (values pos-digit (+ byte-len pos-bits))))
1506         (t
1507          ;; Some of new-byte's bits go in current result digit.
1508          (setf (%bignum-ref result pos-digit)
1509                (logior (%bignum-ref result pos-digit)
1510                        (%ashl (logand new-byte-digit (%make-ones other-bits))
1511                               pos-bits)))
1512          (let ((pos-digit+1 (1+ pos-digit)))
1513            ;; The rest of new-byte's bits go in the next result digit.
1514            (setf (%bignum-ref result pos-digit+1)
1515                  (logand (ash new-byte-digit (- other-bits))
1516                          ;; Must LOGAND after shift here.
1517                          (%make-ones next-digit-bits-needed)))
1518            (if (= next-digit-bits-needed digit-size)
1519                (values (1+ pos-digit+1) 0)
1520                (values pos-digit+1 next-digit-bits-needed))))))
1521
1522 ;;; This starts at result's pos-digit skipping pos-bits, and it stores bits
1523 ;;; from new-byte, a bignum, into result. It effectively stores byte-len
1524 ;;; number of bits, but never stores past end-digit and end-bits in result.
1525 ;;; When handling a starting bit unaligned with a digit boundary, we check
1526 ;;; in the second branch for the byte spec fitting into the pos-digit element
1527 ;;; after after pos-bits; DEPOSIT-UNALIGNED-BIGNUM-BITS expects at least one
1528 ;;; digit boundary crossing.
1529 (defun deposit-bignum-bits (bignum-byte byte-len pos-digit pos-bits
1530                             end-digit end-bits result)
1531   (declare (type bignum-index pos-digit end-digit))
1532   (cond ((zerop pos-bits)
1533          (deposit-aligned-bignum-bits bignum-byte pos-digit end-digit end-bits
1534                                       result))
1535         ((or (= end-digit pos-digit)
1536              (and (= end-digit (1+ pos-digit))
1537                   (zerop end-bits)))
1538          (setf (%bignum-ref result pos-digit)
1539                (logior (%bignum-ref result pos-digit)
1540                        (%ashl (logand (%bignum-ref bignum-byte 0)
1541                                       (%make-ones byte-len))
1542                               pos-bits))))
1543         (t (deposit-unaligned-bignum-bits bignum-byte pos-digit pos-bits
1544                                           end-digit end-bits result))))
1545
1546 ;;; This deposits bits from bignum-byte into result starting at pos-digit and
1547 ;;; the zero'th bit. It effectively only stores bits to end-bits in the
1548 ;;; end-digit element of result. The loop termination code takes care of
1549 ;;; picking up the last digit's bits or filling in virtual negative sign bits.
1550 (defun deposit-aligned-bignum-bits (bignum-byte pos-digit end-digit end-bits
1551                                     result)
1552   (declare (type bignum-index pos-digit end-digit))
1553   (let* ((bignum-len (%bignum-length bignum-byte))
1554          (bignum-plusp (%bignum-0-or-plusp bignum-byte bignum-len)))
1555     (declare (type bignum-index bignum-len))
1556     (do ((i 0 (1+ i ))
1557          (j pos-digit (1+ j)))
1558         ((or (= j end-digit) (= i bignum-len))
1559          (cond ((= j end-digit)
1560                 (cond ((< i bignum-len)
1561                        (setf (%bignum-ref result j)
1562                              (logand (%bignum-ref bignum-byte i)
1563                                      (%make-ones end-bits))))
1564                       (bignum-plusp)
1565                       (t
1566                        (setf (%bignum-ref result j) (%make-ones end-bits)))))
1567                (bignum-plusp)
1568                (t
1569                 (do ((j j (1+ j)))
1570                     ((= j end-digit)
1571                      (setf (%bignum-ref result j) (%make-ones end-bits)))
1572                   (setf (%bignum-ref result j) all-ones-digit)))))
1573       (setf (%bignum-ref result j) (%bignum-ref bignum-byte i)))))
1574
1575 ;;; This assumes at least one digit crossing.
1576 (defun deposit-unaligned-bignum-bits (bignum-byte pos-digit pos-bits
1577                                       end-digit end-bits result)
1578   (declare (type bignum-index pos-digit end-digit))
1579   (let* ((bignum-len (%bignum-length bignum-byte))
1580          (bignum-plusp (%bignum-0-or-plusp bignum-byte bignum-len))
1581          (low-mask (%make-ones pos-bits))
1582          (bits-past-pos-bits (- digit-size pos-bits))
1583          (high-mask (%make-ones bits-past-pos-bits))
1584          (minus-high-bits (- bits-past-pos-bits)))
1585     (declare (type bignum-element-type low-mask high-mask)
1586              (type bignum-index bignum-len))
1587     (do ((i 0 (1+ i))
1588          (j pos-digit j+1)
1589          (j+1 (1+ pos-digit) (1+ j+1)))
1590         ((or (= j end-digit) (= i bignum-len))
1591          (cond
1592           ((= j end-digit)
1593            (setf (%bignum-ref result j)
1594                  (cond
1595                   ((>= pos-bits end-bits)
1596                    (logand (%bignum-ref result j) (%make-ones end-bits)))
1597                   ((< i bignum-len)
1598                    (logior (%bignum-ref result j)
1599                            (%ashl (logand (%bignum-ref bignum-byte i)
1600                                           (%make-ones (- end-bits pos-bits)))
1601                                   pos-bits)))
1602                   (bignum-plusp
1603                    (logand (%bignum-ref result j)
1604                            ;; 0's between pos-bits and end-bits positions.
1605                            (logior (%ashl (%make-ones (- digit-size end-bits))
1606                                           end-bits)
1607                                    low-mask)))
1608                   (t (logior (%bignum-ref result j)
1609                              (%ashl (%make-ones (- end-bits pos-bits))
1610                                     pos-bits))))))
1611           (bignum-plusp)
1612           (t
1613            (setf (%bignum-ref result j)
1614                  (%ashl (%make-ones bits-past-pos-bits) pos-bits))
1615            (do ((j j+1 (1+ j)))
1616                ((= j end-digit)
1617                 (setf (%bignum-ref result j) (%make-ones end-bits)))
1618              (declare (type bignum-index j))
1619              (setf (%bignum-ref result j) all-ones-digit)))))
1620       (declare (type bignum-index i j j+1))
1621       (let ((digit (%bignum-ref bignum-byte i)))
1622         (declare (type bignum-element-type digit))
1623         (setf (%bignum-ref result j)
1624               (logior (%bignum-ref result j)
1625                       (%ashl (logand digit high-mask) pos-bits)))
1626         (setf (%bignum-ref result j+1)
1627               (logand (ash digit minus-high-bits)
1628                       ;; LOGAND should be unnecessary here with a logical right
1629                       ;; shift or a correct unsigned-byte-32 one.
1630                       low-mask))))))
1631 |#
1632 \f
1633 ;;;; TRUNCATE
1634
1635 ;;; This is the original sketch of the algorithm from which I implemented this
1636 ;;; TRUNCATE, assuming both operands are bignums. I should modify this to work
1637 ;;; with the documentation on my functions, as a general introduction. I've
1638 ;;; left this here just in case someone needs it in the future. Don't look at
1639 ;;; this unless reading the functions' comments leaves you at a loss. Remember
1640 ;;; this comes from Knuth, so the book might give you the right general
1641 ;;; overview.
1642 ;;;
1643 ;;; (truncate x y):
1644 ;;;
1645 ;;; If X's magnitude is less than Y's, then result is 0 with remainder X.
1646 ;;;
1647 ;;; Make x and y positive, copying x if it is already positive.
1648 ;;;
1649 ;;; Shift y left until there's a 1 in the 30'th bit (most significant, non-sign
1650 ;;;       digit)
1651 ;;;    Just do most sig digit to determine how much to shift whole number.
1652 ;;; Shift x this much too.
1653 ;;; Remember this initial shift count.
1654 ;;;
1655 ;;; Allocate q to be len-x minus len-y quantity plus 1.
1656 ;;;
1657 ;;; i = last digit of x.
1658 ;;; k = last digit of q.
1659 ;;;
1660 ;;; LOOP
1661 ;;;
1662 ;;; j = last digit of y.
1663 ;;;
1664 ;;; compute guess.
1665 ;;; if x[i] = y[j] then g = #xFFFFFFFF
1666 ;;; else g = x[i]x[i-1]/y[j].
1667 ;;;
1668 ;;; check guess.
1669 ;;; %UNSIGNED-MULTIPLY returns b and c defined below.
1670 ;;;    a = x[i-1] - (logand (* g y[j]) #xFFFFFFFF).
1671 ;;;       Use %UNSIGNED-MULTIPLY taking low-order result.
1672 ;;;    b = (logand (ash (* g y[j-1]) -32) #xFFFFFFFF).
1673 ;;;    c = (logand (* g y[j-1]) #xFFFFFFFF).
1674 ;;; if a < b, okay.
1675 ;;; if a > b, guess is too high
1676 ;;;    g = g - 1; go back to "check guess".
1677 ;;; if a = b and c > x[i-2], guess is too high
1678 ;;;    g = g - 1; go back to "check guess".
1679 ;;; GUESS IS 32-BIT NUMBER, SO USE THING TO KEEP IN SPECIAL REGISTER
1680 ;;; SAME FOR A, B, AND C.
1681 ;;;
1682 ;;; Subtract g * y from x[i - len-y+1]..x[i]. See paper for doing this in step.
1683 ;;; If x[i] < 0, guess is screwed up.
1684 ;;;    negative g, then add 1
1685 ;;;    zero or positive g, then subtract 1
1686 ;;; AND add y back into x[len-y+1..i].
1687 ;;;
1688 ;;; q[k] = g.
1689 ;;; i = i - 1.
1690 ;;; k = k - 1.
1691 ;;;
1692 ;;; If k>=0, goto LOOP.
1693 ;;;
1694 ;;; Now quotient is good, but remainder is not.
1695 ;;; Shift x right by saved initial left shifting count.
1696 ;;;
1697 ;;; Check quotient and remainder signs.
1698 ;;; x pos y pos --> q pos r pos
1699 ;;; x pos y neg --> q neg r pos
1700 ;;; x neg y pos --> q neg r neg
1701 ;;; x neg y neg --> q pos r neg
1702 ;;;
1703 ;;; Normalize quotient and remainder. Cons result if necessary.
1704
1705 ;;; These are used by BIGNUM-TRUNCATE and friends in the general case.
1706 (defvar *truncate-x*)
1707 (defvar *truncate-y*)
1708
1709 ;;; This divides x by y returning the quotient and remainder. In the general
1710 ;;; case, we shift y to setup for the algorithm, and we use two buffers to save
1711 ;;; consing intermediate values. X gets destructively modified to become the
1712 ;;; remainder, and we have to shift it to account for the initial Y shift.
1713 ;;; After we multiple bind q and r, we first fix up the signs and then return
1714 ;;; the normalized results.
1715 (defun bignum-truncate (x y)
1716   (declare (type bignum-type x y))
1717   (let* ((x-plusp (%bignum-0-or-plusp x (%bignum-length x)))
1718          (y-plusp (%bignum-0-or-plusp y (%bignum-length y)))
1719          (x (if x-plusp x (negate-bignum x nil)))
1720          (y (if y-plusp y (negate-bignum y nil)))
1721          (len-x (%bignum-length x))
1722          (len-y (%bignum-length y)))
1723     (multiple-value-bind (q r)
1724         (cond ((< len-y 2)
1725                (bignum-truncate-single-digit x len-x y))
1726               ((plusp (bignum-compare y x))
1727                (let ((res (%allocate-bignum len-x)))
1728                  (dotimes (i len-x)
1729                    (setf (%bignum-ref res i) (%bignum-ref x i)))
1730                  (values 0 res)))
1731               (t
1732                (let ((len-x+1 (1+ len-x)))
1733                  (with-bignum-buffers ((*truncate-x* len-x+1)
1734                                        (*truncate-y* (1+ len-y)))
1735                    (let ((y-shift (shift-y-for-truncate y)))
1736                      (shift-and-store-truncate-buffers x len-x y len-y y-shift)
1737                      (values (do-truncate len-x+1 len-y)
1738                              ;; DO-TRUNCATE must execute first.
1739                              (cond
1740                               ((zerop y-shift)
1741                                (let ((res (%allocate-bignum len-y)))
1742                                  (declare (type bignum-type res))
1743                                  (bignum-replace res *truncate-x* :end2 len-y)
1744                                  (%normalize-bignum res len-y)))
1745                               (t
1746                                (shift-right-unaligned
1747                                 *truncate-x* 0 y-shift len-y
1748                                 ((= j res-len-1)
1749                                  (setf (%bignum-ref res j)
1750                                        (%ashr (%bignum-ref *truncate-x* i)
1751                                               y-shift))
1752                                  (%normalize-bignum res res-len))
1753                                 res)))))))))
1754       (let ((quotient (cond ((eq x-plusp y-plusp) q)
1755                             ((typep q 'fixnum) (the fixnum (- q)))
1756                             (t (negate-bignum-in-place q))))
1757             (rem (cond (x-plusp r)
1758                        ((typep r 'fixnum) (the fixnum (- r)))
1759                        (t (negate-bignum-in-place r)))))
1760         (values (if (typep quotient 'fixnum)
1761                     quotient
1762                     (%normalize-bignum quotient (%bignum-length quotient)))
1763                 (if (typep rem 'fixnum)
1764                     rem
1765                     (%normalize-bignum rem (%bignum-length rem))))))))
1766
1767 ;;; This divides x by y when y is a single bignum digit. BIGNUM-TRUNCATE fixes
1768 ;;; up the quotient and remainder with respect to sign and normalization.
1769 ;;;
1770 ;;; We don't have to worry about shifting y to make its most significant digit
1771 ;;; sufficiently large for %FLOOR to return 32-bit quantities for the q-digit
1772 ;;; and r-digit. If y is a single digit bignum, it is already large enough
1773 ;;; for %FLOOR. That is, it has some bits on pretty high in the digit.
1774 (defun bignum-truncate-single-digit (x len-x y)
1775   (declare (type bignum-index len-x))
1776   (let ((q (%allocate-bignum len-x))
1777         (r 0)
1778         (y (%bignum-ref y 0)))
1779     (declare (type bignum-element-type r y))
1780     (do ((i (1- len-x) (1- i)))
1781         ((minusp i))
1782       (multiple-value-bind (q-digit r-digit) (%floor r (%bignum-ref x i) y)
1783         (declare (type bignum-element-type q-digit r-digit))
1784         (setf (%bignum-ref q i) q-digit)
1785         (setf r r-digit)))
1786     (let ((rem (%allocate-bignum 1)))
1787       (setf (%bignum-ref rem 0) r)
1788       (values q rem))))
1789
1790 ;;; This divides *truncate-x* by *truncate-y*, and len-x and len-y tell us how
1791 ;;; much of the buffers we care about. TRY-BIGNUM-TRUNCATE-GUESS modifies
1792 ;;; *truncate-x* on each interation, and this buffer becomes our remainder.
1793 ;;;
1794 ;;; *truncate-x* definitely has at least three digits, and it has one more than
1795 ;;; *truncate-y*. This keeps i, i-1, i-2, and low-x-digit happy. Thanks to
1796 ;;; SHIFT-AND-STORE-TRUNCATE-BUFFERS.
1797 (defun do-truncate (len-x len-y)
1798   (declare (type bignum-index len-x len-y))
1799   (let* ((len-q (- len-x len-y))
1800          ;; Add one for extra sign digit in case high bit is on.
1801          (q (%allocate-bignum (1+ len-q)))
1802          (k (1- len-q))
1803          (y1 (%bignum-ref *truncate-y* (1- len-y)))
1804          (y2 (%bignum-ref *truncate-y* (- len-y 2)))
1805          (i (1- len-x))
1806          (i-1 (1- i))
1807          (i-2 (1- i-1))
1808          (low-x-digit (- i len-y)))
1809     (declare (type bignum-index len-q k i i-1 i-2 low-x-digit)
1810              (type bignum-element-type y1 y2))
1811     (loop
1812       (setf (%bignum-ref q k)
1813             (try-bignum-truncate-guess
1814              ;; This modifies *truncate-x*. Must access elements each pass.
1815              (bignum-truncate-guess y1 y2
1816                                     (%bignum-ref *truncate-x* i)
1817                                     (%bignum-ref *truncate-x* i-1)
1818                                     (%bignum-ref *truncate-x* i-2))
1819              len-y low-x-digit))
1820       (cond ((zerop k) (return))
1821             (t (decf k)
1822                (decf low-x-digit)
1823                (shiftf i i-1 i-2 (1- i-2)))))
1824     q))
1825
1826 ;;; This takes a digit guess, multiplies it by *truncate-y* for a result one
1827 ;;; greater in length than len-y, and subtracts this result from *truncate-x*.
1828 ;;; Low-x-digit is the first digit of x to start the subtraction, and we know x
1829 ;;; is long enough to subtract a len-y plus one length bignum from it. Next we
1830 ;;; check the result of the subtraction, and if the high digit in x became
1831 ;;; negative, then our guess was one too big. In this case, return one less
1832 ;;; than guess passed in, and add one value of y back into x to account for
1833 ;;; subtracting one too many. Knuth shows that the guess is wrong on the order
1834 ;;; of 3/b, where b is the base (2 to the digit-size power) -- pretty rarely.
1835 (defun try-bignum-truncate-guess (guess len-y low-x-digit)
1836   (declare (type bignum-index low-x-digit len-y)
1837            (type bignum-element-type guess))
1838   (let ((carry-digit 0)
1839         (borrow 1)
1840         (i low-x-digit))
1841     (declare (type bignum-element-type carry-digit)
1842              (type bignum-index i)
1843              (fixnum borrow))
1844     ;; Multiply guess and divisor, subtracting from dividend simultaneously.
1845     (dotimes (j len-y)
1846       (multiple-value-bind (high-digit low-digit)
1847           (%multiply-and-add guess
1848                              (%bignum-ref *truncate-y* j)
1849                              carry-digit)
1850         (declare (type bignum-element-type high-digit low-digit))
1851         (setf carry-digit high-digit)
1852         (multiple-value-bind (x temp-borrow)
1853             (%subtract-with-borrow (%bignum-ref *truncate-x* i)
1854                                    low-digit
1855                                    borrow)
1856           (declare (type bignum-element-type x)
1857                    (fixnum temp-borrow))
1858           (setf (%bignum-ref *truncate-x* i) x)
1859           (setf borrow temp-borrow)))
1860       (incf i))
1861     (setf (%bignum-ref *truncate-x* i)
1862           (%subtract-with-borrow (%bignum-ref *truncate-x* i)
1863                                  carry-digit borrow))
1864     ;; See whether guess is off by one, adding one Y back in if necessary.
1865     (cond ((%digit-0-or-plusp (%bignum-ref *truncate-x* i))
1866            guess)
1867           (t
1868            ;; If subtraction has negative result, add one divisor value back
1869            ;; in. The guess was one too large in magnitude.
1870            (let ((i low-x-digit)
1871                  (carry 0))
1872              (dotimes (j len-y)
1873                (multiple-value-bind (v k)
1874                    (%add-with-carry (%bignum-ref *truncate-y* j)
1875                                     (%bignum-ref *truncate-x* i)
1876                                     carry)
1877                  (declare (type bignum-element-type v))
1878                  (setf (%bignum-ref *truncate-x* i) v)
1879                  (setf carry k))
1880                (incf i))
1881              (setf (%bignum-ref *truncate-x* i)
1882                    (%add-with-carry (%bignum-ref *truncate-x* i) 0 carry)))
1883            (%subtract-with-borrow guess 1 1)))))
1884
1885 ;;; This returns a guess for the next division step. Y1 is the highest y
1886 ;;; digit, and y2 is the second to highest y digit. The x... variables are
1887 ;;; the three highest x digits for the next division step.
1888 ;;;
1889 ;;; From Knuth, our guess is either all ones or x-i and x-i-1 divided by y1,
1890 ;;; depending on whether x-i and y1 are the same. We test this guess by
1891 ;;; determining whether guess*y2 is greater than the three high digits of x
1892 ;;; minus guess*y1 shifted left one digit:
1893 ;;;    ------------------------------
1894 ;;;   |    x-i    |   x-i-1  | x-i-2 |
1895 ;;;    ------------------------------
1896 ;;;    ------------------------------
1897 ;;; - | g*y1 high | g*y1 low |   0   |
1898 ;;;    ------------------------------
1899 ;;;             ...               <   guess*y2     ???
1900 ;;; If guess*y2 is greater, then we decrement our guess by one and try again.
1901 ;;; This returns a guess that is either correct or one too large.
1902 (defun bignum-truncate-guess (y1 y2 x-i x-i-1 x-i-2)
1903   (declare (type bignum-element-type y1 y2 x-i x-i-1 x-i-2))
1904   (let ((guess (if (%digit-compare x-i y1)
1905                    all-ones-digit
1906                    (%floor x-i x-i-1 y1))))
1907     (declare (type bignum-element-type guess))
1908     (loop
1909       (multiple-value-bind (high-guess*y1 low-guess*y1) (%multiply guess y1)
1910         (declare (type bignum-element-type low-guess*y1 high-guess*y1))
1911         (multiple-value-bind (high-guess*y2 low-guess*y2)
1912             (%multiply guess y2)
1913           (declare (type bignum-element-type high-guess*y2 low-guess*y2))
1914           (multiple-value-bind (middle-digit borrow)
1915               (%subtract-with-borrow x-i-1 low-guess*y1 1)
1916             (declare (type bignum-element-type middle-digit)
1917                      (fixnum borrow))
1918             ;; Supplying borrow of 1 means there was no borrow, and we know
1919             ;; x-i-2 minus 0 requires no borrow.
1920             (let ((high-digit (%subtract-with-borrow x-i high-guess*y1 borrow)))
1921               (declare (type bignum-element-type high-digit))
1922               (if (and (%digit-compare high-digit 0)
1923                        (or (%digit-greater high-guess*y2 middle-digit)
1924                            (and (%digit-compare middle-digit high-guess*y2)
1925                                 (%digit-greater low-guess*y2 x-i-2))))
1926                   (setf guess (%subtract-with-borrow guess 1 1))
1927                   (return guess)))))))))
1928
1929 ;;; This returns the amount to shift y to place a one in the second highest
1930 ;;; bit. Y must be positive. If the last digit of y is zero, then y has a
1931 ;;; one in the previous digit's sign bit, so we know it will take one less
1932 ;;; than digit-size to get a one where we want. Otherwise, we count how many
1933 ;;; right shifts it takes to get zero; subtracting this value from digit-size
1934 ;;; tells us how many high zeros there are which is one more than the shift
1935 ;;; amount sought.
1936 ;;;
1937 ;;; Note: This is exactly the same as one less than the integer-length of the
1938 ;;; last digit subtracted from the digit-size.
1939 ;;;
1940 ;;; We shift y to make it sufficiently large that doing the 64-bit by 32-bit
1941 ;;; %FLOOR calls ensures the quotient and remainder fit in 32-bits.
1942 (defun shift-y-for-truncate (y)
1943   (let* ((len (%bignum-length y))
1944          (last (%bignum-ref y (1- len))))
1945     (declare (type bignum-index len)
1946              (type bignum-element-type last))
1947     (- digit-size (integer-length last) 1)))
1948
1949 ;;; Stores two bignums into the truncation bignum buffers, shifting them on the
1950 ;;; way in. This assumes x and y are positive and at least two in length, and
1951 ;;; it assumes *truncate-x* and *truncate-y* are one digit longer than x and y.
1952 (defun shift-and-store-truncate-buffers (x len-x y len-y shift)
1953   (declare (type bignum-index len-x len-y)
1954            (type (integer 0 (#.digit-size)) shift))
1955   (cond ((zerop shift)
1956          (bignum-replace *truncate-x* x :end1 len-x)
1957          (bignum-replace *truncate-y* y :end1 len-y))
1958         (t
1959          (bignum-ashift-left-unaligned x 0 shift (1+ len-x) *truncate-x*)
1960          (bignum-ashift-left-unaligned y 0 shift (1+ len-y) *truncate-y*))))
1961 \f
1962 ;;;; %FLOOR primitive for BIGNUM-TRUNCATE
1963
1964 ;;; When a machine leaves out a 64-bit by 32-bit divide instruction (that is,
1965 ;;; two bignum-digits divided by one), we have to roll our own (the hard way).
1966 ;;; Basically, we treat the operation as four 16-bit digits divided by two
1967 ;;; 16-bit digits. This means we have duplicated most of the code above to do
1968 ;;; this nearly general 16-bit digit bignum divide, but we've unrolled loops
1969 ;;; and made use of other properties of this specific divide situation.
1970
1971 ;;;; %FLOOR for machines with a 32x32 divider.
1972
1973 #!-sb-fluid
1974 (declaim (inline 32x16-subtract-with-borrow 32x16-add-with-carry
1975                  32x16-divide 32x16-multiply 32x16-multiply-split))
1976
1977 #!+32x16-divide
1978 (defconstant 32x16-base-1 #xFFFF)
1979
1980 ;;; This is similar to %SUBTRACT-WITH-BORROW. It returns a 16-bit difference
1981 ;;; and a borrow. Returning a 1 for the borrow means there was no borrow, and
1982 ;;; 0 means there was one.
1983 #!+32x16-divide
1984 (defun 32x16-subtract-with-borrow (a b borrow)
1985   (declare (type (unsigned-byte 16) a b)
1986            (type (integer 0 1) borrow))
1987   (let ((diff (+ (- a b) borrow 32x16-base-1)))
1988     (declare (type (unsigned-byte 17) diff))
1989     (values (logand diff #xFFFF)
1990             (ash diff -16))))
1991
1992 ;;; This adds a and b, 16-bit quantities, with the carry k. It returns a
1993 ;;; 16-bit sum and a second value, 0 or 1, indicating whether there was a
1994 ;;; carry.
1995 #!+32x16-divide
1996 (defun 32x16-add-with-carry (a b k)
1997   (declare (type (unsigned-byte 16) a b)
1998            (type (integer 0 1) k))
1999   (let ((res (the fixnum (+ a b k))))
2000     (declare (type (unsigned-byte 17) res))
2001     (if (zerop (the fixnum (logand #x10000 res)))
2002         (values res 0)
2003         (values (the (unsigned-byte 16) (logand #xFFFF res))
2004                 1))))
2005
2006 ;;; This is probably a 32-bit by 32-bit divide instruction.
2007 #!+32x16-divide
2008 (defun 32x16-divide (a b c)
2009   (declare (type (unsigned-byte 16) a b c))
2010   (floor (the bignum-element-type
2011               (logior (the bignum-element-type (ash a 16))
2012                       b))
2013          c))
2014
2015 ;;; This basically exists since we know the answer won't overflow
2016 ;;; bignum-element-type. It's probably just a basic multiply instruction, but
2017 ;;; it can't cons an intermediate bignum. The result goes in a non-descriptor
2018 ;;; register.
2019 #!+32x16-divide
2020 (defun 32x16-multiply (a b)
2021   (declare (type (unsigned-byte 16) a b))
2022   (the bignum-element-type (* a b)))
2023
2024 ;;; This multiplies a and b, 16-bit quantities, and returns the result as two
2025 ;;; 16-bit quantities, high and low.
2026 #!+32x16-divide
2027 (defun 32x16-multiply-split (a b)
2028   (let ((res (32x16-multiply a b)))
2029     (declare (the bignum-element-type res))
2030     (values (the (unsigned-byte 16) (logand #xFFFF (ash res -16)))
2031             (the (unsigned-byte 16) (logand #xFFFF res)))))
2032
2033 ;;; The %FLOOR below uses this buffer the same way BIGNUM-TRUNCATE uses
2034 ;;; *truncate-x*. There's no y buffer since we pass around the two 16-bit
2035 ;;; digits and use them slightly differently than the general truncation
2036 ;;; algorithm above.
2037 #!+32x16-divide
2038 (defvar *32x16-truncate-x* (make-array 4 :element-type '(unsigned-byte 16)
2039                                        :initial-element 0))
2040
2041 ;;; This does the same thing as the %FLOOR above, but it does it at Lisp level
2042 ;;; when there is no 64x32-bit divide instruction on the machine.
2043 ;;;
2044 ;;; It implements the higher level tactics of BIGNUM-TRUNCATE, but it makes use
2045 ;;; of special situation provided, four 16-bit digits divided by two 16-bit
2046 ;;; digits.
2047 #!+32x16-divide
2048 (defun %floor (a b c)
2049   (declare (type bignum-element-type a b c))
2050   ;; Setup *32x16-truncate-x* buffer from a and b.
2051   (setf (aref *32x16-truncate-x* 0)
2052         (the (unsigned-byte 16) (logand #xFFFF b)))
2053   (setf (aref *32x16-truncate-x* 1)
2054         (the (unsigned-byte 16)
2055              (logand #xFFFF
2056                      (the (unsigned-byte 16) (ash b -16)))))
2057   (setf (aref *32x16-truncate-x* 2)
2058         (the (unsigned-byte 16) (logand #xFFFF a)))
2059   (setf (aref *32x16-truncate-x* 3)
2060         (the (unsigned-byte 16)
2061              (logand #xFFFF
2062                      (the (unsigned-byte 16) (ash a -16)))))
2063   ;; From DO-TRUNCATE, but unroll the loop.
2064   (let* ((y1 (logand #xFFFF (ash c -16)))
2065          (y2 (logand #xFFFF c))
2066          (q (the bignum-element-type
2067                  (ash (32x16-try-bignum-truncate-guess
2068                        (32x16-truncate-guess y1 y2
2069                                              (aref *32x16-truncate-x* 3)
2070                                              (aref *32x16-truncate-x* 2)
2071                                              (aref *32x16-truncate-x* 1))
2072                        y1 y2 1)
2073                       16))))
2074     (declare (type bignum-element-type q)
2075              (type (unsigned-byte 16) y1 y2))
2076     (values (the bignum-element-type
2077                  (logior q
2078                          (the (unsigned-byte 16)
2079                               (32x16-try-bignum-truncate-guess
2080                                (32x16-truncate-guess
2081                                 y1 y2
2082                                 (aref *32x16-truncate-x* 2)
2083                                 (aref *32x16-truncate-x* 1)
2084                                 (aref *32x16-truncate-x* 0))
2085                                y1 y2 0))))
2086             (the bignum-element-type
2087                  (logior (the bignum-element-type
2088                               (ash (aref *32x16-truncate-x* 1) 16))
2089                          (the (unsigned-byte 16)
2090                               (aref *32x16-truncate-x* 0)))))))
2091
2092 ;;; This is similar to TRY-BIGNUM-TRUNCATE-GUESS, but this unrolls the two
2093 ;;; loops. This also substitutes for %DIGIT-0-OR-PLUSP the equivalent
2094 ;;; expression without any embellishment or pretense of abstraction. The first
2095 ;;; loop is unrolled, but we've put the body of the loop into the function
2096 ;;; 32X16-TRY-GUESS-ONE-RESULT-DIGIT.
2097 #!+32x16-divide
2098 (defun 32x16-try-bignum-truncate-guess (guess y-high y-low low-x-digit)
2099   (declare (type bignum-index low-x-digit)
2100            (type (unsigned-byte 16) guess y-high y-low))
2101   (let ((high-x-digit (+ 2 low-x-digit)))
2102     ;; Multiply guess and divisor, subtracting from dividend simultaneously.
2103     (multiple-value-bind (guess*y-hold carry borrow)
2104         (32x16-try-guess-one-result-digit guess y-low 0 0 1 low-x-digit)
2105       (declare (type (unsigned-byte 16) guess*y-hold)
2106                (fixnum carry borrow))
2107       (multiple-value-bind (guess*y-hold carry borrow)
2108           (32x16-try-guess-one-result-digit guess y-high guess*y-hold
2109                                             carry borrow (1+ low-x-digit))
2110         (declare (type (unsigned-byte 16) guess*y-hold)
2111                  (fixnum borrow)
2112                  (ignore carry))
2113         (setf (aref *32x16-truncate-x* high-x-digit)
2114               (32x16-subtract-with-borrow (aref *32x16-truncate-x* high-x-digit)
2115                                           guess*y-hold borrow))))
2116     ;; See whether guess is off by one, adding one Y back in if necessary.
2117     (cond ((zerop (logand #x8000 (aref *32x16-truncate-x* high-x-digit)))
2118            ;; The subtraction result is zero or positive.
2119            guess)
2120           (t
2121            ;; If subtraction has negative result, add one divisor value back
2122            ;; in. The guess was one too large in magnitude.
2123            (multiple-value-bind (v carry)
2124                (32x16-add-with-carry y-low
2125                                      (aref *32x16-truncate-x* low-x-digit)
2126                                      0)
2127              (declare (type (unsigned-byte 16) v))
2128              (setf (aref *32x16-truncate-x* low-x-digit) v)
2129              (multiple-value-bind (v carry)
2130                  (32x16-add-with-carry y-high
2131                                        (aref *32x16-truncate-x*
2132                                              (1+ low-x-digit))
2133                                        carry)
2134                (setf (aref *32x16-truncate-x* (1+ low-x-digit)) v)
2135                (setf (aref *32x16-truncate-x* high-x-digit)
2136                      (32x16-add-with-carry (aref *32x16-truncate-x* high-x-digit)
2137                                            carry 0))))
2138            (if (zerop (logand #x8000 guess))
2139                (1- guess)
2140                (1+ guess))))))
2141
2142 ;;; This is similar to the body of the loop in TRY-BIGNUM-TRUNCATE-GUESS that
2143 ;;; multiplies the guess by y and subtracts the result from x simultaneously.
2144 ;;; This returns the digit remembered as part of the multiplication, the carry
2145 ;;; from additions done on behalf of the multiplication, and the borrow from
2146 ;;; doing the subtraction.
2147 #!+32x16-divide
2148 (defun 32x16-try-guess-one-result-digit (guess y-digit guess*y-hold
2149                                          carry borrow x-index)
2150   (multiple-value-bind (high-digit low-digit)
2151       (32x16-multiply-split guess y-digit)
2152     (declare (type (unsigned-byte 16) high-digit low-digit))
2153     (multiple-value-bind (low-digit temp-carry)
2154         (32x16-add-with-carry low-digit guess*y-hold carry)
2155       (declare (type (unsigned-byte 16) low-digit))
2156       (multiple-value-bind (high-digit temp-carry)
2157           (32x16-add-with-carry high-digit temp-carry 0)
2158         (declare (type (unsigned-byte 16) high-digit))
2159         (multiple-value-bind (x temp-borrow)
2160             (32x16-subtract-with-borrow (aref *32x16-truncate-x* x-index)
2161                                         low-digit borrow)
2162           (declare (type (unsigned-byte 16) x))
2163           (setf (aref *32x16-truncate-x* x-index) x)
2164           (values high-digit temp-carry temp-borrow))))))
2165
2166 ;;; This is similar to BIGNUM-TRUNCATE-GUESS, but instead of computing the
2167 ;;; guess exactly as described in the its comments (digit by digit), this
2168 ;;; massages the 16-bit quantities into 32-bit quantities and performs the
2169 #!+32x16-divide
2170 (defun 32x16-truncate-guess (y1 y2 x-i x-i-1 x-i-2)
2171   (declare (type (unsigned-byte 16) y1 y2 x-i x-i-1 x-i-2))
2172   (let ((guess (if (= x-i y1)
2173                    #xFFFF
2174                    (32x16-divide x-i x-i-1 y1))))
2175     (declare (type (unsigned-byte 16) guess))
2176     (loop
2177       (let* ((guess*y1 (the bignum-element-type
2178                             (ash (logand #xFFFF
2179                                          (the bignum-element-type
2180                                               (32x16-multiply guess y1)))
2181                                  16)))
2182              (x-y (%subtract-with-borrow
2183                    (the bignum-element-type
2184                         (logior (the bignum-element-type
2185                                      (ash x-i-1 16))
2186                                 x-i-2))
2187                    guess*y1
2188                    1))
2189              (guess*y2 (the bignum-element-type (%multiply guess y2))))
2190         (declare (type bignum-element-type guess*y1 x-y guess*y2))
2191         (if (%digit-greater guess*y2 x-y)
2192             (decf guess)
2193             (return guess))))))
2194 \f
2195 ;;;; general utilities
2196
2197 ;;; Allocate a single word bignum that holds fixnum. This is useful when
2198 ;;; we are trying to mix fixnum and bignum operands.
2199 #!-sb-fluid (declaim (inline make-small-bignum))
2200 (defun make-small-bignum (fixnum)
2201   (let ((res (%allocate-bignum 1)))
2202     (setf (%bignum-ref res 0) (%fixnum-to-digit fixnum))
2203     res))
2204
2205 ;;; Internal in-place operations use this to fixup remaining digits in the
2206 ;;; incoming data, such as in-place shifting. This is basically the same as
2207 ;;; the first form in %NORMALIZE-BIGNUM, but we return the length of the buffer
2208 ;;; instead of shrinking the bignum.
2209 #!-sb-fluid (declaim (sb!ext:maybe-inline %normalize-bignum-buffer))
2210 (defun %normalize-bignum-buffer (result len)
2211   (declare (type bignum-type result)
2212            (type bignum-index len))
2213   (unless (= len 1)
2214     (do ((next-digit (%bignum-ref result (- len 2))
2215                      (%bignum-ref result (- len 2)))
2216          (sign-digit (%bignum-ref result (1- len)) next-digit))
2217         ((not (zerop (logxor sign-digit (%ashr next-digit (1- digit-size))))))
2218         (decf len)
2219         (setf (%bignum-ref result len) 0)       
2220         (when (= len 1)
2221               (return))))
2222   len)
2223
2224 ;;; This drops the last digit if it is unnecessary sign information. It repeats
2225 ;;; this as needed, possibly ending with a fixnum. If the resulting length from
2226 ;;; shrinking is one, see whether our one word is a fixnum. Shift the possible
2227 ;;; fixnum bits completely out of the word, and compare this with shifting the
2228 ;;; sign bit all the way through. If the bits are all 1's or 0's in both words,
2229 ;;; then there are just sign bits between the fixnum bits and the sign bit. If
2230 ;;; we do have a fixnum, shift it over for the two low-tag bits.
2231 (defun %normalize-bignum (result len)
2232   (declare (type bignum-type result)
2233            (type bignum-index len)
2234            (inline %normalize-bignum-buffer))
2235   (let ((newlen (%normalize-bignum-buffer result len)))
2236     (declare (type bignum-index newlen))
2237     (unless (= newlen len)
2238       (%bignum-set-length result newlen))
2239     (if (= newlen 1)
2240         (let ((digit (%bignum-ref result 0)))
2241           (if (= (%ashr digit 29) (%ashr digit (1- digit-size)))
2242               (%fixnum-digit-with-correct-sign digit)
2243               result))
2244         result)))
2245
2246 ;;; This drops the last digit if it is unnecessary sign information. It
2247 ;;; repeats this as needed, possibly ending with a fixnum magnitude but never
2248 ;;; returning a fixnum.
2249 (defun %mostly-normalize-bignum (result len)
2250   (declare (type bignum-type result)
2251            (type bignum-index len)
2252            (inline %normalize-bignum-buffer))
2253   (let ((newlen (%normalize-bignum-buffer result len)))
2254     (declare (type bignum-index newlen))
2255     (unless (= newlen len)
2256       (%bignum-set-length result newlen))
2257     result))
2258 \f
2259 ;;;; hashing
2260
2261 ;;; the bignum case of the SXHASH function
2262 (defun sxhash-bignum (x)
2263   (let ((result 316495330))
2264     (declare (type fixnum result))
2265     (dotimes (i (%bignum-length x))
2266       (declare (type index i))
2267       (let ((xi (%bignum-ref x i)))
2268         (mixf result
2269               (logand most-positive-fixnum
2270                       xi
2271                       (ash xi -7)))))
2272     result))