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