Remove 8-bit hash codes in packages.
[sbcl.git] / src / code / bignum.lisp
blobf3e76dda4eecde1ef75f4cb41be3d3f5c744df3a
1 ;;;; code to implement bignum support
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.
12 (in-package "SB!BIGNUM")
14 ;;;; notes
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
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-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 %bigfloor %fixnum-digit-with-correct-sign %ashl
32 ;;; %ashr %digit-logical-shift-right))
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 ;;; Relational operators:
61 ;;; %LOGAND
62 ;;; %LOGIOR
63 ;;; %LOGXOR
64 ;;; LDB
65 ;;; %FIXNUM-TO-DIGIT
66 ;;; TRUNCATE
67 ;;; %BIGFLOOR
68 ;;;
69 ;;; Note: The floating routines know about the float representation.
70 ;;;
71 ;;; PROBLEM 1:
72 ;;; There might be a problem with various LET's and parameters that take a
73 ;;; digit value. We need to write these so those things stay in machine
74 ;;; registers and number stack slots. I bind locals to these values, and I
75 ;;; use function on them -- ZEROP, ASH, etc.
76 ;;;
77 ;;; PROBLEM 2:
78 ;;; In shifting and byte operations, I use masks and logical operations that
79 ;;; could result in intermediate bignums. This is hidden by the current system,
80 ;;; but I may need to write these in a way that keeps these masks and logical
81 ;;; operations from diving into the Lisp level bignum code.
82 ;;;
83 ;;; To do:
84 ;;; fixnums
85 ;;; logior, logxor, logand
86 ;;; depending on relationals, < (twice) and <= (twice)
87 ;;; or write compare thing (twice).
88 ;;; LDB on fixnum with bignum result.
89 ;;; DPB on fixnum with bignum result.
90 ;;; TRUNCATE returns zero or one as one value and fixnum or minus fixnum
91 ;;; for the other value when given (truncate fixnum bignum).
92 ;;; Returns (truncate bignum fixnum) otherwise.
93 ;;; addition
94 ;;; subtraction (twice)
95 ;;; multiply
96 ;;; GCD
97 ;;; Write MASK-FIELD and DEPOSIT-FIELD in terms of logical operations.
98 ;;; DIVIDE
99 ;;; IF (/ x y) with bignums:
100 ;;; do the truncate, and if rem is 0, return quotient.
101 ;;; if rem is non-0
102 ;;; gcd of x and y.
103 ;;; "truncate" each by gcd, ignoring remainder 0.
104 ;;; form ratio of each result, bottom is positive.
106 ;;;; What's a bignum?
108 (defconstant digit-size sb!vm:n-word-bits)
110 (defconstant maximum-bignum-length (1- (ash 1 (- sb!vm:n-word-bits
111 sb!vm:n-widetag-bits))))
113 (defconstant all-ones-digit (1- (ash 1 sb!vm:n-word-bits)))
115 ;;;; internal inline routines
117 ;;; %ALLOCATE-BIGNUM must zero all elements.
118 (defun %allocate-bignum (length)
119 (declare (type bignum-length length))
120 (%allocate-bignum length))
122 ;;; Extract the length of the bignum.
123 (defun %bignum-length (bignum)
124 (declare (type bignum bignum))
125 (%bignum-length bignum))
127 ;;; %BIGNUM-REF needs to access bignums as obviously as possible, and it needs
128 ;;; to be able to return the digit somewhere no one looks for real objects.
129 (defun %bignum-ref (bignum i)
130 (declare (type bignum bignum)
131 (type bignum-index i))
132 (%bignum-ref bignum i))
133 (defun %bignum-set (bignum i value)
134 (declare (type bignum bignum)
135 (type bignum-index i)
136 (type bignum-element-type value))
137 (%bignum-set bignum i value))
139 ;;; Return T if digit is positive, or NIL if negative.
140 (defun %digit-0-or-plusp (digit)
141 (declare (type bignum-element-type digit))
142 (not (logbitp (1- digit-size) digit)))
144 #!-sb-fluid (declaim (inline %bignum-0-or-plusp))
145 (defun %bignum-0-or-plusp (bignum len)
146 (declare (type bignum bignum)
147 (type bignum-length len))
148 (%digit-0-or-plusp (%bignum-ref bignum (1- len))))
150 ;;; This should be in assembler, and should not cons intermediate
151 ;;; results. It returns a bignum digit and a carry resulting from adding
152 ;;; together a, b, and an incoming carry.
153 (defun %add-with-carry (a b carry)
154 (declare (type bignum-element-type a b)
155 (type (mod 2) carry))
156 (%add-with-carry a b carry))
158 ;;; This should be in assembler, and should not cons intermediate
159 ;;; results. It returns a bignum digit and a borrow resulting from
160 ;;; subtracting b from a, and subtracting a possible incoming borrow.
162 ;;; We really do: a - b - 1 + borrow, where borrow is either 0 or 1.
163 (defun %subtract-with-borrow (a b borrow)
164 (declare (type bignum-element-type a b)
165 (type (mod 2) borrow))
166 (%subtract-with-borrow a b borrow))
168 ;;; Multiply two digit-size numbers, returning a 2*digit-size result
169 ;;; split into two digit-size quantities.
170 (defun %multiply (x y)
171 (declare (type bignum-element-type x y))
172 (%multiply x y))
174 ;;; This multiplies x-digit and y-digit, producing high and low digits
175 ;;; manifesting the result. Then it adds the low digit, res-digit, and
176 ;;; carry-in-digit. Any carries (note, you still have to add two digits
177 ;;; at a time possibly producing two carries) from adding these three
178 ;;; digits get added to the high digit from the multiply, producing the
179 ;;; next carry digit. Res-digit is optional since two uses of this
180 ;;; primitive multiplies a single digit bignum by a multiple digit
181 ;;; bignum, and in this situation there is no need for a result buffer
182 ;;; accumulating partial results which is where the res-digit comes
183 ;;; from.
184 (defun %multiply-and-add (x-digit y-digit carry-in-digit
185 &optional (res-digit 0))
186 (declare (type bignum-element-type x-digit y-digit res-digit carry-in-digit))
187 (%multiply-and-add x-digit y-digit carry-in-digit res-digit))
189 (defun %lognot (digit)
190 (declare (type bignum-element-type digit))
191 (%lognot digit))
193 ;;; Each of these does the digit-size unsigned op.
194 (declaim (inline %logand %logior %logxor))
195 (defun %logand (a b)
196 (declare (type bignum-element-type a b))
197 (logand a b))
198 (defun %logior (a b)
199 (declare (type bignum-element-type a b))
200 (logior a b))
201 (defun %logxor (a b)
202 (declare (type bignum-element-type a b))
203 (logxor a b))
205 ;;; This takes a fixnum and sets it up as an unsigned digit-size
206 ;;; quantity.
207 (defun %fixnum-to-digit (x)
208 (declare (fixnum x))
209 (logand x (1- (ash 1 digit-size))))
211 #!-32x16-divide
212 ;;; This takes three digits and returns the FLOOR'ed result of
213 ;;; dividing the first two as a 2*digit-size integer by the third.
215 ;;; Do weird LET and SETQ stuff to bamboozle the compiler into allowing
216 ;;; the %BIGFLOOR transform to expand into pseudo-assembler for which the
217 ;;; compiler can later correctly allocate registers.
218 (defun %bigfloor (a b c)
219 (let ((a a) (b b) (c c))
220 (declare (type bignum-element-type a b c))
221 (setq a a b b c c)
222 (%bigfloor a b c)))
224 ;;; Convert the digit to a regular integer assuming that the digit is signed.
225 (defun %fixnum-digit-with-correct-sign (digit)
226 (declare (type bignum-element-type digit))
227 (if (logbitp (1- digit-size) digit)
228 (logior digit (ash -1 digit-size))
229 digit))
231 ;;; Do an arithmetic shift right of data even though bignum-element-type is
232 ;;; unsigned.
233 (defun %ashr (data count)
234 (declare (type bignum-element-type data)
235 (type (mod #.sb!vm:n-word-bits) count))
236 (%ashr data count))
238 ;;; This takes a digit-size quantity and shifts it to the left,
239 ;;; returning a digit-size quantity.
240 (defun %ashl (data count)
241 (declare (type bignum-element-type data)
242 (type (mod #.sb!vm:n-word-bits) count))
243 (%ashl data count))
245 ;;; Do an unsigned (logical) right shift of a digit by Count.
246 (defun %digit-logical-shift-right (data count)
247 (declare (type bignum-element-type data)
248 (type (mod #.sb!vm:n-word-bits) count))
249 (%digit-logical-shift-right data count))
251 ;;; Change the length of bignum to be newlen. Newlen must be the same or
252 ;;; smaller than the old length, and any elements beyond newlen must be zeroed.
253 (defun %bignum-set-length (bignum newlen)
254 (declare (type bignum bignum)
255 (type bignum-length newlen))
256 (%bignum-set-length bignum newlen))
258 ;;; This returns 0 or "-1" depending on whether the bignum is positive. This
259 ;;; is suitable for infinite sign extension to complete additions,
260 ;;; subtractions, negations, etc. This cannot return a -1 represented as
261 ;;; a negative fixnum since it would then have to low zeros.
262 #!-sb-fluid (declaim (inline %sign-digit))
263 (defun %sign-digit (bignum len)
264 (declare (type bignum bignum)
265 (type bignum-length len))
266 (%ashr (%bignum-ref bignum (1- len)) (1- digit-size)))
268 (declaim (inline bignum-plus-p))
269 (defun bignum-plus-p (bignum)
270 (declare (type bignum bignum))
271 (%bignum-0-or-plusp bignum (%bignum-length bignum)))
273 (declaim (optimize (speed 3) (safety 0)))
275 ;;;; addition
277 (defun add-bignums (a b)
278 (declare (type bignum a b))
279 (declare (muffle-conditions compiler-note)) ; returns lispobj, so what.
280 (let ((len-a (%bignum-length a))
281 (len-b (%bignum-length b)))
282 (multiple-value-bind (a len-a b len-b)
283 (if (> len-a len-b)
284 (values a len-a b len-b)
285 (values b len-b a len-a))
286 (declare (type bignum a b)
287 (type bignum-length len-a len-b))
288 (let* ((len-res (1+ len-a))
289 (res (%allocate-bignum len-res))
290 (carry 0))
291 (declare (type bignum-length len-res)
292 (type bignum res)
293 (type (mod 2) carry))
294 (dotimes (i len-b)
295 (declare (type bignum-index i))
296 (multiple-value-bind (v k)
297 (%add-with-carry (%bignum-ref a i) (%bignum-ref b i) carry)
298 (declare (type bignum-element-type v)
299 (type (mod 2) k))
300 (setf (%bignum-ref res i) v)
301 (setf carry k)))
302 (if (/= len-a len-b)
303 (finish-add a res carry (%sign-digit b len-b) len-b len-a)
304 (setf (%bignum-ref res len-a)
305 (%add-with-carry (%sign-digit a len-a)
306 (%sign-digit b len-b)
307 carry)))
308 (%normalize-bignum res len-res)))))
310 ;;; This takes the longer of two bignums and propagates the carry through its
311 ;;; remaining high order digits.
312 (defun finish-add (a res carry sign-digit-b start end)
313 (declare (type bignum a res)
314 (type (mod 2) carry)
315 (type bignum-element-type sign-digit-b)
316 (type bignum-index start)
317 (type bignum-length end))
318 (do ((i start (1+ i)))
319 ((= i end)
320 (setf (%bignum-ref res end)
321 (%add-with-carry (%sign-digit a end) sign-digit-b carry)))
322 (declare (type bignum-index i))
323 (multiple-value-bind (v k)
324 (%add-with-carry (%bignum-ref a i) sign-digit-b carry)
325 (setf (%bignum-ref res i) v)
326 (setf carry k)))
327 (values))
329 ;;;; subtraction
331 (eval-when (:compile-toplevel :execute)
333 ;;; This subtracts b from a plugging result into res. Return-fun is the
334 ;;; function to call that fixes up the result returning any useful values, such
335 ;;; as the result. This macro may evaluate its arguments more than once.
336 (sb!xc:defmacro subtract-bignum-loop (a len-a b len-b res len-res return-fun)
337 (with-unique-names (borrow a-digit a-sign b-digit b-sign i v k)
338 `(let* ((,borrow 1)
339 (,a-sign (%sign-digit ,a ,len-a))
340 (,b-sign (%sign-digit ,b ,len-b)))
341 (declare (type bignum-element-type ,a-sign ,b-sign))
342 (dotimes (,i ,len-res)
343 (declare (type bignum-index ,i))
344 (let ((,a-digit (if (< ,i ,len-a) (%bignum-ref ,a ,i) ,a-sign))
345 (,b-digit (if (< ,i ,len-b) (%bignum-ref ,b ,i) ,b-sign)))
346 (declare (type bignum-element-type ,a-digit ,b-digit))
347 (multiple-value-bind (,v ,k)
348 (%subtract-with-borrow ,a-digit ,b-digit ,borrow)
349 (setf (%bignum-ref ,res ,i) ,v)
350 (setf ,borrow ,k))))
351 (,return-fun ,res ,len-res))))
353 ) ;EVAL-WHEN
355 (defun subtract-bignum (a b)
356 (declare (type bignum a b))
357 (let* ((len-a (%bignum-length a))
358 (len-b (%bignum-length b))
359 (len-res (1+ (max len-a len-b)))
360 (res (%allocate-bignum len-res)))
361 (declare (type bignum-length len-a len-b len-res)) ;Test len-res for bounds?
362 (subtract-bignum-loop a len-a b len-b res len-res %normalize-bignum)))
364 ;;; Operations requiring a subtraction without the overhead of intermediate
365 ;;; results, such as GCD, use this. It assumes Result is big enough for the
366 ;;; result.
367 (defun subtract-bignum-buffers-with-len (a len-a b len-b result len-res)
368 (declare (type bignum a b result)
369 (type bignum-length len-a len-b len-res))
370 (subtract-bignum-loop a len-a b len-b result len-res
371 %normalize-bignum-buffer))
373 (defun subtract-bignum-buffers (a len-a b len-b result)
374 (declare (type bignum a b result)
375 (type bignum-length len-a len-b))
376 (subtract-bignum-loop a len-a b len-b result (max len-a len-b)
377 %normalize-bignum-buffer))
379 ;;;; multiplication
381 (defun multiply-bignums (a b)
382 (declare (type bignum a b))
383 (let* ((a-plusp (bignum-plus-p a))
384 (b-plusp (bignum-plus-p b))
385 (a (if a-plusp a (negate-bignum a)))
386 (b (if b-plusp b (negate-bignum b)))
387 (len-a (%bignum-length a))
388 (len-b (%bignum-length b))
389 (len-res (+ len-a len-b))
390 (res (%allocate-bignum len-res))
391 (negate-res (not (eq a-plusp b-plusp))))
392 (declare (type bignum-length len-a len-b len-res))
393 (dotimes (i len-a)
394 (declare (type bignum-index i))
395 (let ((carry-digit 0)
396 (x (%bignum-ref a i))
397 (k i))
398 (declare (type bignum-index k)
399 (type bignum-element-type carry-digit x))
400 (dotimes (j len-b)
401 (multiple-value-bind (big-carry res-digit)
402 (%multiply-and-add x
403 (%bignum-ref b j)
404 (%bignum-ref res k)
405 carry-digit)
406 (declare (type bignum-element-type big-carry res-digit))
407 (setf (%bignum-ref res k) res-digit)
408 (setf carry-digit big-carry)
409 (incf k)))
410 (setf (%bignum-ref res k) carry-digit)))
411 (when negate-res (negate-bignum-in-place res))
412 (%normalize-bignum res len-res)))
414 (defun multiply-bignum-and-fixnum (bignum fixnum)
415 (declare (type bignum bignum) (type fixnum fixnum))
416 (let* ((bignum-plus-p (bignum-plus-p bignum))
417 (fixnum-plus-p (not (minusp fixnum)))
418 (bignum (if bignum-plus-p bignum (negate-bignum bignum)))
419 (bignum-len (%bignum-length bignum))
420 (fixnum (if fixnum-plus-p fixnum (- fixnum)))
421 (result (%allocate-bignum (1+ bignum-len)))
422 (carry-digit 0))
423 (declare (type bignum bignum result)
424 (type bignum-element-type fixnum carry-digit))
425 (dotimes (index bignum-len)
426 (declare (type bignum-index index))
427 (multiple-value-bind (next-digit low)
428 (%multiply-and-add (%bignum-ref bignum index) fixnum carry-digit)
429 (declare (type bignum-element-type next-digit low))
430 (setf carry-digit next-digit)
431 (setf (%bignum-ref result index) low)))
432 (setf (%bignum-ref result bignum-len) carry-digit)
433 (unless (eq bignum-plus-p fixnum-plus-p)
434 (negate-bignum-in-place result))
435 (%normalize-bignum result (1+ bignum-len))))
437 (defun multiply-fixnums (a b)
438 (declare (fixnum a b))
439 (declare (muffle-conditions compiler-note)) ; returns lispobj, so what.
440 (let* ((a-minusp (minusp a))
441 (b-minusp (minusp b)))
442 (multiple-value-bind (high low)
443 (%multiply (if a-minusp (- a) a)
444 (if b-minusp (- b) b))
445 (declare (type bignum-element-type high low))
446 (if (and (zerop high)
447 (%digit-0-or-plusp low))
448 (let ((low (truly-the (unsigned-byte #.(1- sb!vm:n-word-bits))
449 (%fixnum-digit-with-correct-sign low))))
450 (if (eq a-minusp b-minusp)
452 (- low)))
453 (let ((res (%allocate-bignum 2)))
454 (%bignum-set res 0 low)
455 (%bignum-set res 1 high)
456 (unless (eq a-minusp b-minusp) (negate-bignum-in-place res))
457 (%normalize-bignum res 2))))))
459 ;;;; BIGNUM-REPLACE and WITH-BIGNUM-BUFFERS
461 (eval-when (:compile-toplevel :execute)
463 (sb!xc:defmacro bignum-replace (dest
465 &key
466 (start1 '0)
467 end1
468 (start2 '0)
469 end2
470 from-end)
471 (sb!int:once-only ((n-dest dest)
472 (n-src src))
473 (with-unique-names (n-start1 n-end1 n-start2 n-end2 i1 i2)
474 (let ((end1 (or end1 `(%bignum-length ,n-dest)))
475 (end2 (or end2 `(%bignum-length ,n-src))))
476 (if from-end
477 `(let ((,n-start1 ,start1)
478 (,n-start2 ,start2))
479 (do ((,i1 (1- ,end1) (1- ,i1))
480 (,i2 (1- ,end2) (1- ,i2)))
481 ((or (< ,i1 ,n-start1) (< ,i2 ,n-start2)))
482 (declare (fixnum ,i1 ,i2))
483 (%bignum-set ,n-dest ,i1 (%bignum-ref ,n-src ,i2))))
484 (if (eql start1 start2)
485 `(let ((,n-end1 (min ,end1 ,end2)))
486 (do ((,i1 ,start1 (1+ ,i1)))
487 ((>= ,i1 ,n-end1))
488 (declare (type bignum-index ,i1))
489 (%bignum-set ,n-dest ,i1 (%bignum-ref ,n-src ,i1))))
490 `(let ((,n-end1 ,end1)
491 (,n-end2 ,end2))
492 (do ((,i1 ,start1 (1+ ,i1))
493 (,i2 ,start2 (1+ ,i2)))
494 ((or (>= ,i1 ,n-end1) (>= ,i2 ,n-end2)))
495 (declare (type bignum-index ,i1 ,i2))
496 (%bignum-set ,n-dest ,i1 (%bignum-ref ,n-src ,i2))))))))))
498 (sb!xc:defmacro with-bignum-buffers (specs &body body)
499 #!+sb-doc
500 "WITH-BIGNUM-BUFFERS ({(var size [init])}*) Form*"
501 (sb!int:collect ((binds)
502 (inits))
503 (dolist (spec specs)
504 (let ((name (first spec))
505 (size (second spec)))
506 (binds `(,name (%allocate-bignum ,size)))
507 (let ((init (third spec)))
508 (when init
509 (inits `(bignum-replace ,name ,init))))))
510 `(let* ,(binds)
511 ,@(inits)
512 ,@body)))
514 ) ;EVAL-WHEN
516 ;;;; GCD
518 (eval-when (:compile-toplevel :load-toplevel :execute)
519 ;; The asserts in the GCD implementation are way too expensive to
520 ;; check in normal use, and are disabled here.
521 (sb!xc:defmacro gcd-assert (&rest args)
522 (declare (ignore args))
523 #+sb-bignum-assertions `(assert ,@args))
524 ;; We'll be doing a lot of modular arithmetic.
525 (sb!xc:defmacro modularly (form)
526 `(logand all-ones-digit ,form)))
528 ;;; I'm not sure why I need this FTYPE declaration. Compiled by the
529 ;;; target compiler, it can deduce the return type fine, but without
530 ;;; it, we pay a heavy price in BIGNUM-GCD when compiled by the
531 ;;; cross-compiler. -- CSR, 2004-07-19
532 (declaim (ftype (sfunction (bignum bignum-length bignum bignum-length)
533 (and unsigned-byte fixnum))
534 bignum-factors-of-two))
535 (defun bignum-factors-of-two (a len-a b len-b)
536 (declare (type bignum-length len-a len-b) (type bignum a b))
537 (do ((i 0 (1+ i))
538 (end (min len-a len-b)))
539 ((= i end) (error "Unexpected zero bignums?"))
540 (declare (type bignum-index i)
541 (type bignum-length end))
542 (let ((or-digits (%logior (%bignum-ref a i) (%bignum-ref b i))))
543 (unless (zerop or-digits)
544 (return (do ((j 0 (1+ j))
545 (or-digits or-digits (%ashr or-digits 1)))
546 ((oddp or-digits) (+ (* i digit-size) j))
547 (declare (type (mod #.sb!vm:n-word-bits) j))))))))
549 ;;; Multiply a bignum buffer with a fixnum or a digit, storing the
550 ;;; result in another bignum buffer, and without using any
551 ;;; temporaries. Inlined to avoid boxing smallnum if it's actually a
552 ;;; digit. Needed by GCD, should possibly OAOO with
553 ;;; MULTIPLY-BIGNUM-AND-FIXNUM.
554 (declaim (inline multiply-bignum-buffer-and-smallnum-to-buffer))
555 (defun multiply-bignum-buffer-and-smallnum-to-buffer (bignum bignum-len
556 smallnum res)
557 (declare (type bignum bignum))
558 (let* ((bignum-plus-p (%bignum-0-or-plusp bignum bignum-len))
559 (smallnum-plus-p (not (minusp smallnum)))
560 (smallnum (if smallnum-plus-p smallnum (- smallnum)))
561 (carry-digit 0))
562 (declare (type bignum bignum res)
563 (type bignum-length bignum-len)
564 (type bignum-element-type smallnum carry-digit))
565 (unless bignum-plus-p
566 (negate-bignum-buffer-in-place bignum bignum-len))
567 (dotimes (index bignum-len)
568 (declare (type bignum-index index))
569 (multiple-value-bind (next-digit low)
570 (%multiply-and-add (%bignum-ref bignum index)
571 smallnum
572 carry-digit)
573 (declare (type bignum-element-type next-digit low))
574 (setf carry-digit next-digit)
575 (setf (%bignum-ref res index) low)))
576 (setf (%bignum-ref res bignum-len) carry-digit)
577 (unless bignum-plus-p
578 (negate-bignum-buffer-in-place bignum bignum-len))
579 (let ((res-len (%normalize-bignum-buffer res (1+ bignum-len))))
580 (unless (eq bignum-plus-p smallnum-plus-p)
581 (negate-bignum-buffer-in-place res res-len))
582 res-len)))
584 ;;; Given U and V, return U / V mod 2^32. Implements the algorithm in the
585 ;;; paper, but uses some clever bit-twiddling nicked from Nickle to do it.
586 (declaim (inline bmod))
587 (defun bmod (u v)
588 (declare (muffle-conditions compiler-note)) ; returns lispobj, so what.
589 (let ((ud (%bignum-ref u 0))
590 (vd (%bignum-ref v 0))
591 (umask 0)
592 (imask 1)
593 (m 0))
594 (declare (type (unsigned-byte #.sb!vm:n-word-bits) ud vd umask imask m))
595 (dotimes (i digit-size)
596 (setf umask (logior umask imask))
597 (when (logtest ud umask)
598 (setf ud (modularly (- ud vd)))
599 (setf m (modularly (logior m imask))))
600 (setf imask (modularly (ash imask 1)))
601 (setf vd (modularly (ash vd 1))))
604 (defun dmod (u u-len v v-len tmp1)
605 (loop while (> (bignum-buffer-integer-length u u-len)
606 (+ (bignum-buffer-integer-length v v-len)
607 digit-size))
609 (unless (zerop (%bignum-ref u 0))
610 (let* ((bmod (bmod u v))
611 (tmp1-len (multiply-bignum-buffer-and-smallnum-to-buffer v v-len
612 bmod
613 tmp1)))
614 (setf u-len (subtract-bignum-buffers u u-len
615 tmp1 tmp1-len
617 (bignum-abs-buffer u u-len)))
618 (gcd-assert (zerop (%bignum-ref u 0)))
619 (setf u-len (bignum-buffer-ashift-right u u-len digit-size)))
620 (let* ((d (+ 1 (- (bignum-buffer-integer-length u u-len)
621 (bignum-buffer-integer-length v v-len))))
622 (n (1- (ash 1 d))))
623 (declare (type (unsigned-byte #.(integer-length #.sb!vm:n-word-bits)) d)
624 (type (unsigned-byte #.sb!vm:n-word-bits) n))
625 (gcd-assert (>= d 0))
626 (when (logtest (%bignum-ref u 0) n)
627 (let ((tmp1-len
628 (multiply-bignum-buffer-and-smallnum-to-buffer v v-len
629 (logand n (bmod u
631 tmp1)))
632 (setf u-len (subtract-bignum-buffers u u-len
633 tmp1 tmp1-len
635 (bignum-abs-buffer u u-len)))
636 u-len))
638 (defconstant lower-ones-digit (1- (ash 1 (truncate sb!vm:n-word-bits 2))))
640 ;;; Find D and N such that (LOGAND ALL-ONES-DIGIT (- (* D X) (* N Y))) is 0,
641 ;;; (< 0 N LOWER-ONES-DIGIT) and (< 0 (ABS D) LOWER-ONES-DIGIT).
642 (defun reduced-ratio-mod (x y)
643 (let* ((c (bmod x y))
644 (n1 c)
645 (d1 1)
646 (n2 (modularly (1+ (modularly (lognot n1)))))
647 (d2 (modularly -1)))
648 (declare (type (unsigned-byte #.sb!vm:n-word-bits) n1 d1 n2 d2))
649 (loop while (> n2 (expt 2 (truncate digit-size 2))) do
650 (loop for i of-type (mod #.sb!vm:n-word-bits)
651 downfrom (- (integer-length n1) (integer-length n2))
652 while (>= n1 n2) do
653 (when (>= n1 (modularly (ash n2 i)))
654 (psetf n1 (modularly (- n1 (modularly (ash n2 i))))
655 d1 (modularly (- d1 (modularly (ash d2 i)))))))
656 (psetf n1 n2
657 d1 d2
658 n2 n1
659 d2 d1))
660 (values n2 (if (>= d2 (expt 2 (1- digit-size)))
661 (lognot (logand most-positive-fixnum (lognot d2)))
662 (logand lower-ones-digit d2)))))
665 (defun copy-bignum (a &optional (len (%bignum-length a)))
666 (let ((b (%allocate-bignum len)))
667 (bignum-replace b a)
668 (%bignum-set-length b len)
671 ;;; Allocate a single word bignum that holds fixnum. This is useful when
672 ;;; we are trying to mix fixnum and bignum operands.
673 #!-sb-fluid (declaim (inline make-small-bignum))
674 (defun make-small-bignum (fixnum)
675 (let ((res (%allocate-bignum 1)))
676 (setf (%bignum-ref res 0) (%fixnum-to-digit fixnum))
677 res))
679 ;; When the larger number is less than this many bignum digits long, revert
680 ;; to old algorithm.
681 (defparameter *accelerated-gcd-cutoff* 3)
683 ;;; Alternate between k-ary reduction with the help of
684 ;;; REDUCED-RATIO-MOD and digit modulus reduction via DMOD. Once the
685 ;;; arguments get small enough, drop through to BIGNUM-MOD-GCD (since
686 ;;; k-ary reduction can introduce spurious factors, which need to be
687 ;;; filtered out). Reference: Kenneth Weber, "The accelerated integer
688 ;;; GCD algorithm", ACM Transactions on Mathematical Software, volume
689 ;;; 21, number 1, March 1995, epp. 111-122.
690 (defun bignum-gcd (u0 v0)
691 (declare (type bignum u0 v0))
692 (let* ((u1 (if (bignum-plus-p u0)
694 (negate-bignum u0 nil)))
695 (v1 (if (bignum-plus-p v0)
697 (negate-bignum v0 nil))))
698 (if (zerop v1)
699 (return-from bignum-gcd u1))
700 (when (> u1 v1)
701 (rotatef u1 v1))
702 (let ((n (mod v1 u1)))
703 (setf v1 (if (fixnump n)
704 (make-small-bignum n)
705 n)))
706 (if (and (= 1 (%bignum-length v1))
707 (zerop (%bignum-ref v1 0)))
708 (return-from bignum-gcd (%normalize-bignum u1
709 (%bignum-length u1))))
710 (let* ((buffer-len (+ 2 (%bignum-length u1)))
711 (u (%allocate-bignum buffer-len))
712 (u-len (%bignum-length u1))
713 (v (%allocate-bignum buffer-len))
714 (v-len (%bignum-length v1))
715 (tmp1 (%allocate-bignum buffer-len))
716 (tmp1-len 0)
717 (tmp2 (%allocate-bignum buffer-len))
718 (tmp2-len 0)
719 (factors-of-two
720 (bignum-factors-of-two u1 (%bignum-length u1)
721 v1 (%bignum-length v1))))
722 (declare (type (or null bignum-length)
723 buffer-len u-len v-len tmp1-len tmp2-len))
724 (bignum-replace u u1)
725 (bignum-replace v v1)
726 (setf u-len
727 (make-gcd-bignum-odd u
728 (bignum-buffer-ashift-right u u-len
729 factors-of-two)))
730 (setf v-len
731 (make-gcd-bignum-odd v
732 (bignum-buffer-ashift-right v v-len
733 factors-of-two)))
734 (loop until (or (< u-len *accelerated-gcd-cutoff*)
735 (not v-len)
736 (zerop v-len)
737 (and (= 1 v-len)
738 (zerop (%bignum-ref v 0))))
740 (gcd-assert (= buffer-len (%bignum-length u)
741 (%bignum-length v)
742 (%bignum-length tmp1)
743 (%bignum-length tmp2)))
744 (if (> (bignum-buffer-integer-length u u-len)
745 (+ #.(truncate sb!vm:n-word-bits 4)
746 (bignum-buffer-integer-length v v-len)))
747 (setf u-len (dmod u u-len
748 v v-len
749 tmp1))
750 (multiple-value-bind (n d) (reduced-ratio-mod u v)
751 (setf tmp1-len
752 (multiply-bignum-buffer-and-smallnum-to-buffer v v-len
753 n tmp1))
754 (setf tmp2-len
755 (multiply-bignum-buffer-and-smallnum-to-buffer u u-len
756 d tmp2))
757 (gcd-assert (= (copy-bignum tmp2 tmp2-len)
758 (* (copy-bignum u u-len) d)))
759 (gcd-assert (= (copy-bignum tmp1 tmp1-len)
760 (* (copy-bignum v v-len) n)))
761 (setf u-len
762 (subtract-bignum-buffers-with-len tmp1 tmp1-len
763 tmp2 tmp2-len
765 (1+ (max tmp1-len
766 tmp2-len))))
767 (gcd-assert (or (zerop (- (copy-bignum tmp1 tmp1-len)
768 (copy-bignum tmp2 tmp2-len)))
769 (= (copy-bignum u u-len)
770 (- (copy-bignum tmp1 tmp1-len)
771 (copy-bignum tmp2 tmp2-len)))))
772 (bignum-abs-buffer u u-len)
773 (gcd-assert (zerop (modularly u)))))
774 (setf u-len (make-gcd-bignum-odd u u-len))
775 (rotatef u v)
776 (rotatef u-len v-len))
777 (bignum-abs-buffer u u-len)
778 (setf u (copy-bignum u u-len))
779 (let ((n (bignum-mod-gcd v1 u)))
780 (ash (bignum-mod-gcd u1 (if (fixnump n)
781 (make-small-bignum n)
783 factors-of-two)))))
785 (defun bignum-mod-gcd (a b)
786 (declare (type bignum a b))
787 (when (< a b)
788 (rotatef a b))
789 ;; While the length difference of A and B is sufficiently large,
790 ;; reduce using MOD (slowish, but it should equalize the sizes of
791 ;; A and B pretty quickly). After that, use the binary GCD
792 ;; algorithm to handle the rest.
793 (loop until (and (= (%bignum-length b) 1) (zerop (%bignum-ref b 0))) do
794 (when (<= (%bignum-length a) (1+ (%bignum-length b)))
795 (return-from bignum-mod-gcd (bignum-binary-gcd a b)))
796 (let ((rem (mod a b)))
797 (if (fixnump rem)
798 (setf a (make-small-bignum rem))
799 (setf a rem))
800 (rotatef a b)))
801 (if (= (%bignum-length a) 1)
802 (%normalize-bignum a 1)
805 (defun bignum-binary-gcd (a b)
806 (declare (type bignum a b))
807 (let* ((len-a (%bignum-length a))
808 (len-b (%bignum-length b)))
809 (with-bignum-buffers ((a-buffer len-a a)
810 (b-buffer len-b b)
811 (res-buffer (max len-a len-b)))
812 (let* ((factors-of-two
813 (bignum-factors-of-two a-buffer len-a
814 b-buffer len-b))
815 (len-a (make-gcd-bignum-odd
816 a-buffer
817 (bignum-buffer-ashift-right a-buffer len-a
818 factors-of-two)))
819 (len-b (make-gcd-bignum-odd
820 b-buffer
821 (bignum-buffer-ashift-right b-buffer len-b
822 factors-of-two))))
823 (declare (type bignum-length len-a len-b))
824 (let ((x a-buffer)
825 (len-x len-a)
826 (y b-buffer)
827 (len-y len-b)
828 (z res-buffer))
829 (loop
830 (multiple-value-bind (u v len-v r len-r)
831 (bignum-gcd-order-and-subtract x len-x y len-y z)
832 (declare (type bignum-length len-v len-r))
833 (when (and (= len-r 1) (zerop (%bignum-ref r 0)))
834 (if (zerop factors-of-two)
835 (let ((ret (%allocate-bignum len-v)))
836 (dotimes (i len-v)
837 (setf (%bignum-ref ret i) (%bignum-ref v i)))
838 (return (%normalize-bignum ret len-v)))
839 (return (bignum-ashift-left v factors-of-two len-v))))
840 (setf x v len-x len-v)
841 (setf y r len-y (make-gcd-bignum-odd r len-r))
842 (setf z u))))))))
844 (defun bignum-gcd-order-and-subtract (a len-a b len-b res)
845 (declare (type bignum-length len-a len-b) (type bignum a b))
846 (cond ((= len-a len-b)
847 (do ((i (1- len-a) (1- i)))
848 ((= i -1)
849 (setf (%bignum-ref res 0) 0)
850 (values a b len-b res 1))
851 (let ((a-digit (%bignum-ref a i))
852 (b-digit (%bignum-ref b i)))
853 (cond ((= a-digit b-digit))
854 ((> a-digit b-digit)
855 (return
856 (values a b len-b res
857 (subtract-bignum-buffers a len-a b len-b
858 res))))
860 (return
861 (values b a len-a res
862 (subtract-bignum-buffers b len-b
863 a len-a
864 res))))))))
865 ((> len-a len-b)
866 (values a b len-b res
867 (subtract-bignum-buffers a len-a b len-b res)))
869 (values b a len-a res
870 (subtract-bignum-buffers b len-b a len-a res)))))
872 (defun make-gcd-bignum-odd (a len-a)
873 (declare (type bignum a) (type bignum-length len-a))
874 (dotimes (index len-a)
875 (declare (type bignum-index index))
876 (do ((digit (%bignum-ref a index) (%ashr digit 1))
877 (increment 0 (1+ increment)))
878 ((zerop digit))
879 (declare (type (mod #.sb!vm:n-word-bits) increment))
880 (when (oddp digit)
881 (return-from make-gcd-bignum-odd
882 (bignum-buffer-ashift-right a len-a
883 (+ (* index digit-size)
884 increment)))))))
887 ;;;; negation
889 (eval-when (:compile-toplevel :execute)
891 ;;; This negates bignum-len digits of bignum, storing the resulting digits into
892 ;;; result (possibly EQ to bignum) and returning whatever end-carry there is.
893 (sb!xc:defmacro bignum-negate-loop
894 (bignum bignum-len &optional (result nil resultp))
895 (with-unique-names (carry end value last)
896 `(let* (,@(if (not resultp) `(,last))
897 (,carry
898 (multiple-value-bind (,value ,carry)
899 (%add-with-carry (%lognot (%bignum-ref ,bignum 0)) 1 0)
900 ,(if resultp
901 `(setf (%bignum-ref ,result 0) ,value)
902 `(setf ,last ,value))
903 ,carry))
904 (i 1)
905 (,end ,bignum-len))
906 (declare (type bit ,carry)
907 (type bignum-index i)
908 (type bignum-length ,end))
909 (loop
910 (when (= i ,end) (return))
911 (multiple-value-bind (,value temp)
912 (%add-with-carry (%lognot (%bignum-ref ,bignum i)) 0 ,carry)
913 ,(if resultp
914 `(setf (%bignum-ref ,result i) ,value)
915 `(setf ,last ,value))
916 (setf ,carry temp))
917 (incf i))
918 ,(if resultp carry `(values ,carry ,last)))))
920 ) ; EVAL-WHEN
922 ;;; Fully-normalize is an internal optional. It cause this to always return
923 ;;; a bignum, without any extraneous digits, and it never returns a fixnum.
924 (defun negate-bignum (x &optional (fully-normalize t))
925 (declare (type bignum x))
926 (let* ((len-x (%bignum-length x))
927 (len-res (1+ len-x))
928 (res (%allocate-bignum len-res)))
929 (declare (type bignum-length len-x len-res)) ;Test len-res for range?
930 (let ((carry (bignum-negate-loop x len-x res)))
931 (setf (%bignum-ref res len-x)
932 (%add-with-carry (%lognot (%sign-digit x len-x)) 0 carry)))
933 (if fully-normalize
934 (%normalize-bignum res len-res)
935 (%mostly-normalize-bignum res len-res))))
937 ;;; This assumes bignum is positive; that is, the result of negating it will
938 ;;; stay in the provided allocated bignum.
939 (declaim (maybe-inline negate-bignum-buffer-in-place))
940 (defun negate-bignum-buffer-in-place (bignum bignum-len)
941 (bignum-negate-loop bignum bignum-len bignum)
942 bignum)
944 (defun negate-bignum-in-place (bignum)
945 (declare (inline negate-bignum-buffer-in-place))
946 (negate-bignum-buffer-in-place bignum (%bignum-length bignum)))
948 (defun bignum-abs-buffer (bignum len)
949 (unless (%bignum-0-or-plusp bignum len)
950 (negate-bignum-buffer-in-place bignum len)))
952 ;;;; shifting
954 (eval-when (:compile-toplevel :execute)
956 ;;; This macro is used by BIGNUM-ASHIFT-RIGHT, BIGNUM-BUFFER-ASHIFT-RIGHT, and
957 ;;; BIGNUM-LDB-BIGNUM-RES. They supply a termination form that references
958 ;;; locals established by this form. Source is the source bignum. Start-digit
959 ;;; is the first digit in source from which we pull bits. Start-pos is the
960 ;;; first bit we want. Res-len-form is the form that computes the length of
961 ;;; the resulting bignum. Termination is a DO termination form with a test and
962 ;;; body. When result is supplied, it is the variable to which this binds a
963 ;;; newly allocated bignum.
965 ;;; Given start-pos, 1-31 inclusively, of shift, we form the j'th resulting
966 ;;; digit from high bits of the i'th source digit and the start-pos number of
967 ;;; bits from the i+1'th source digit.
968 (sb!xc:defmacro shift-right-unaligned (source
969 start-digit
970 start-pos
971 res-len-form
972 termination
973 &optional result)
974 `(let* ((high-bits-in-first-digit (- digit-size ,start-pos))
975 (res-len ,res-len-form)
976 (res-len-1 (1- res-len))
977 ,@(if result `((,result (%allocate-bignum res-len)))))
978 (declare (type bignum-length res-len res-len-1))
979 (do ((i ,start-digit (1+ i))
980 (j 0 (1+ j)))
981 ,termination
982 (declare (type bignum-index i j))
983 (setf (%bignum-ref ,(if result result source) j)
984 (%logior (%digit-logical-shift-right (%bignum-ref ,source i)
985 ,start-pos)
986 (%ashl (%bignum-ref ,source (1+ i))
987 high-bits-in-first-digit))))))
989 ) ; EVAL-WHEN
991 ;;; First compute the number of whole digits to shift, shifting them by
992 ;;; skipping them when we start to pick up bits, and the number of bits to
993 ;;; shift the remaining digits into place. If the number of digits is greater
994 ;;; than the length of the bignum, then the result is either 0 or -1. If we
995 ;;; shift on a digit boundary (that is, n-bits is zero), then we just copy
996 ;;; digits. The last branch handles the general case which uses a macro that a
997 ;;; couple other routines use. The fifth argument to the macro references
998 ;;; locals established by the macro.
999 (defun bignum-ashift-right (bignum count)
1000 (declare (type bignum bignum)
1001 (type unsigned-byte count))
1002 (let ((bignum-len (%bignum-length bignum)))
1003 (cond ((fixnump count)
1004 (multiple-value-bind (digits n-bits) (truncate count digit-size)
1005 (declare (type bignum-length digits))
1006 (cond
1007 ((>= digits bignum-len)
1008 (if (%bignum-0-or-plusp bignum bignum-len) 0 -1))
1009 ((zerop n-bits)
1010 (bignum-ashift-right-digits bignum digits))
1012 (shift-right-unaligned bignum digits n-bits (- bignum-len digits)
1013 ((= j res-len-1)
1014 (setf (%bignum-ref res j)
1015 (%ashr (%bignum-ref bignum i) n-bits))
1016 (%normalize-bignum res res-len))
1017 res)))))
1018 ((> count bignum-len)
1019 (if (%bignum-0-or-plusp bignum bignum-len) 0 -1))
1020 ;; Since a FIXNUM should be big enough to address anything in
1021 ;; memory, including arrays of bits, and since arrays of bits
1022 ;; take up about the same space as corresponding fixnums, there
1023 ;; should be no way that we fall through to this case: any shift
1024 ;; right by a bignum should give zero. But let's check anyway:
1025 (t (error "bignum overflow: can't shift right by ~S" count)))))
1027 (defun bignum-ashift-right-digits (bignum digits)
1028 (declare (type bignum bignum)
1029 (type bignum-length digits))
1030 (let* ((res-len (- (%bignum-length bignum) digits))
1031 (res (%allocate-bignum res-len)))
1032 (declare (type bignum-length res-len)
1033 (type bignum res))
1034 (bignum-replace res bignum :start2 digits)
1035 (%normalize-bignum res res-len)))
1037 ;;; GCD uses this for an in-place shifting operation. This is different enough
1038 ;;; from BIGNUM-ASHIFT-RIGHT that it isn't worth folding the bodies into a
1039 ;;; macro, but they share the basic algorithm. This routine foregoes a first
1040 ;;; test for digits being greater than or equal to bignum-len since that will
1041 ;;; never happen for its uses in GCD. We did fold the last branch into a macro
1042 ;;; since it was duplicated a few times, and the fifth argument to it
1043 ;;; references locals established by the macro.
1044 (defun bignum-buffer-ashift-right (bignum bignum-len x)
1045 (declare (type bignum-length bignum-len) (fixnum x))
1046 (multiple-value-bind (digits n-bits) (truncate x digit-size)
1047 (declare (type bignum-length digits))
1048 (cond
1049 ((zerop n-bits)
1050 (let ((new-end (- bignum-len digits)))
1051 (bignum-replace bignum bignum :end1 new-end :start2 digits
1052 :end2 bignum-len)
1053 (%normalize-bignum-buffer bignum new-end)))
1055 (shift-right-unaligned bignum digits n-bits (- bignum-len digits)
1056 ((= j res-len-1)
1057 (setf (%bignum-ref bignum j)
1058 (%ashr (%bignum-ref bignum i) n-bits))
1059 (%normalize-bignum-buffer bignum res-len)))))))
1061 ;;; This handles shifting a bignum buffer to provide fresh bignum data for some
1062 ;;; internal routines. We know bignum is safe when called with bignum-len.
1063 ;;; First we compute the number of whole digits to shift, shifting them
1064 ;;; starting to store farther along the result bignum. If we shift on a digit
1065 ;;; boundary (that is, n-bits is zero), then we just copy digits. The last
1066 ;;; branch handles the general case.
1067 (defun bignum-ashift-left (bignum x &optional bignum-len)
1068 (declare (type bignum bignum)
1069 (type unsigned-byte x)
1070 (type (or null bignum-length) bignum-len))
1071 (if (fixnump x)
1072 (multiple-value-bind (digits n-bits) (truncate x digit-size)
1073 (let* ((bignum-len (or bignum-len (%bignum-length bignum)))
1074 (res-len (+ digits bignum-len 1)))
1075 (when (> res-len maximum-bignum-length)
1076 (error "can't represent result of left shift"))
1077 (if (zerop n-bits)
1078 (bignum-ashift-left-digits bignum bignum-len digits)
1079 (bignum-ashift-left-unaligned bignum digits n-bits res-len))))
1080 ;; Left shift by a number too big to be represented as a fixnum
1081 ;; would exceed our memory capacity, since a fixnum is big enough
1082 ;; to index any array, including a bit array.
1083 (error "can't represent result of left shift")))
1085 (defun bignum-ashift-left-digits (bignum bignum-len digits)
1086 (declare (type bignum-length bignum-len digits))
1087 (let* ((res-len (+ bignum-len digits))
1088 (res (%allocate-bignum res-len)))
1089 (declare (type bignum-length res-len))
1090 (bignum-replace res bignum :start1 digits :end1 res-len :end2 bignum-len
1091 :from-end t)
1092 res))
1094 ;;; BIGNUM-TRUNCATE uses this to store into a bignum buffer by supplying res.
1095 ;;; When res comes in non-nil, then this foregoes allocating a result, and it
1096 ;;; normalizes the buffer instead of the would-be allocated result.
1098 ;;; We start storing into one digit higher than digits, storing a whole result
1099 ;;; digit from parts of two contiguous digits from bignum. When the loop
1100 ;;; finishes, we store the remaining bits from bignum's first digit in the
1101 ;;; first non-zero result digit, digits. We also grab some left over high
1102 ;;; bits from the last digit of bignum.
1103 (defun bignum-ashift-left-unaligned (bignum digits n-bits res-len
1104 &optional (res nil resp))
1105 (declare (type bignum-length digits res-len)
1106 (type (mod #.digit-size) n-bits))
1107 (let* ((remaining-bits (- digit-size n-bits))
1108 (res-len-1 (1- res-len))
1109 (res (or res (%allocate-bignum res-len))))
1110 (declare (type bignum-length res-len res-len-1))
1111 (do ((i 0 (1+ i))
1112 (j (1+ digits) (1+ j)))
1113 ((= j res-len-1)
1114 (setf (%bignum-ref res digits)
1115 (%ashl (%bignum-ref bignum 0) n-bits))
1116 (setf (%bignum-ref res j)
1117 (%ashr (%bignum-ref bignum i) remaining-bits))
1118 (if resp
1119 (%normalize-bignum-buffer res res-len)
1120 (%normalize-bignum res res-len)))
1121 (declare (type bignum-index i j))
1122 (setf (%bignum-ref res j)
1123 (%logior (%digit-logical-shift-right (%bignum-ref bignum i)
1124 remaining-bits)
1125 (%ashl (%bignum-ref bignum (1+ i)) n-bits))))))
1127 ;;; FIXNUM is assumed to be non-zero and the result of the shift should be a bignum
1128 (defun bignum-ashift-left-fixnum (fixnum count)
1129 (declare (bignum-length count)
1130 (fixnum fixnum))
1131 (multiple-value-bind (right-zero-digits remaining)
1132 (truncate count digit-size)
1133 (let* ((right-half (ldb (byte digit-size 0)
1134 (ash fixnum remaining)))
1135 (sign-bit-p
1136 (logbitp (1- digit-size) right-half))
1137 (left-half (ash fixnum
1138 (- remaining digit-size)))
1139 ;; Even if the left-half is 0 or -1 it might need to be sign
1140 ;; extended based on the left-most bit of the right-half
1141 (left-half-p (if sign-bit-p
1142 (/= left-half -1)
1143 (/= left-half 0)))
1144 (length (+ right-zero-digits
1145 (if left-half-p 2 1)))
1146 (result (%allocate-bignum length)))
1147 (setf (%bignum-ref result right-zero-digits) right-half)
1148 (when left-half-p
1149 (setf (%bignum-ref result (1+ right-zero-digits))
1150 (ldb (byte digit-size 0) left-half)))
1151 result)))
1153 ;;;; relational operators
1155 ;;; This compares two bignums returning -1, 0, or 1, depending on
1156 ;;; whether a is less than, equal to, or greater than b.
1157 (declaim (ftype (function (bignum bignum) (integer -1 1)) bignum-compare))
1158 (defun bignum-compare (a b)
1159 (declare (type bignum a b))
1160 (let* ((len-a (%bignum-length a))
1161 (len-b (%bignum-length b))
1162 (a-plusp (%bignum-0-or-plusp a len-a))
1163 (b-plusp (%bignum-0-or-plusp b len-b)))
1164 (declare (type bignum-length len-a len-b))
1165 (cond ((not (eq a-plusp b-plusp))
1166 (if a-plusp 1 -1))
1167 ((= len-a len-b)
1168 (do ((i (1- len-a) (1- i)))
1169 (())
1170 (declare (type bignum-index i))
1171 (let ((a-digit (%bignum-ref a i))
1172 (b-digit (%bignum-ref b i)))
1173 (declare (type bignum-element-type a-digit b-digit))
1174 (when (> a-digit b-digit)
1175 (return 1))
1176 (when (> b-digit a-digit)
1177 (return -1)))
1178 (when (zerop i) (return 0))))
1179 ((> len-a len-b)
1180 (if a-plusp 1 -1))
1181 (t (if a-plusp -1 1)))))
1183 ;;;; float conversion
1185 ;;; Make a single or double float with the specified significand,
1186 ;;; exponent and sign.
1187 (defun single-float-from-bits (bits exp plusp)
1188 (declare (fixnum exp))
1189 (declare (optimize #-sb-xc-host (inhibit-warnings 3)))
1190 (let ((res (dpb exp
1191 sb!vm:single-float-exponent-byte
1192 (logandc2 (logand #xffffffff
1193 (%bignum-ref bits 1))
1194 sb!vm:single-float-hidden-bit))))
1195 (make-single-float
1196 (if plusp
1198 (logior res (ash -1 sb!vm:float-sign-shift))))))
1199 (defun double-float-from-bits (bits exp plusp)
1200 (declare (fixnum exp))
1201 (declare (optimize #-sb-xc-host (inhibit-warnings 3)))
1202 (let ((hi (dpb exp
1203 sb!vm:double-float-exponent-byte
1204 (logandc2 (ecase sb!vm::n-word-bits
1205 (32 (%bignum-ref bits 2))
1206 (64 (ash (%bignum-ref bits 1) -32)))
1207 sb!vm:double-float-hidden-bit)))
1208 (lo (logand #xffffffff (%bignum-ref bits 1))))
1209 (make-double-float (if plusp
1211 (logior hi (ash -1 sb!vm:float-sign-shift)))
1212 lo)))
1213 #!+(and long-float x86)
1214 (defun long-float-from-bits (bits exp plusp)
1215 (declare (fixnum exp))
1216 (declare (optimize #-sb-xc-host (inhibit-warnings 3)))
1217 (make-long-float
1218 (if plusp
1220 (logior exp (ash 1 15)))
1221 (%bignum-ref bits 2)
1222 (%bignum-ref bits 1)))
1224 ;;; Convert Bignum to a float in the specified Format, rounding to the best
1225 ;;; approximation.
1226 (defun bignum-to-float (bignum format)
1227 (let* ((plusp (bignum-plus-p bignum))
1228 (x (if plusp bignum (negate-bignum bignum)))
1229 (len (bignum-integer-length x))
1230 (digits (float-format-digits format))
1231 (keep (+ digits digit-size))
1232 (shift (- keep len))
1233 (shifted (if (minusp shift)
1234 (bignum-ashift-right x (- shift))
1235 (bignum-ashift-left x shift)))
1236 (low (%bignum-ref shifted 0))
1237 (round-bit (ash 1 (1- digit-size))))
1238 (declare (type bignum-length len digits keep) (fixnum shift))
1239 (labels ((round-up ()
1240 (let ((rounded (add-bignums shifted round-bit)))
1241 (if (> (integer-length rounded) keep)
1242 (float-from-bits (bignum-ashift-right rounded 1)
1243 (1+ len))
1244 (float-from-bits rounded len))))
1245 (float-from-bits (bits len)
1246 (declare (type bignum-length len))
1247 (ecase format
1248 (single-float
1249 (single-float-from-bits
1250 bits
1251 (check-exponent len sb!vm:single-float-bias
1252 sb!vm:single-float-normal-exponent-max)
1253 plusp))
1254 (double-float
1255 (double-float-from-bits
1256 bits
1257 (check-exponent len sb!vm:double-float-bias
1258 sb!vm:double-float-normal-exponent-max)
1259 plusp))
1260 #!+long-float
1261 (long-float
1262 (long-float-from-bits
1263 bits
1264 (check-exponent len sb!vm:long-float-bias
1265 sb!vm:long-float-normal-exponent-max)
1266 plusp))))
1267 (check-exponent (exp bias max)
1268 (declare (type bignum-length len))
1269 (let ((exp (+ exp bias)))
1270 (when (> exp max)
1271 ;; Why a SIMPLE-TYPE-ERROR? Well, this is mainly
1272 ;; called by COERCE, which requires an error of
1273 ;; TYPE-ERROR if the conversion can't happen
1274 ;; (except in certain circumstances when we are
1275 ;; coercing to a FUNCTION) -- CSR, 2002-09-18
1276 (error 'simple-type-error
1277 :format-control "Too large to be represented as a ~S:~% ~S"
1278 :format-arguments (list format x)
1279 :expected-type format
1280 :datum x))
1281 exp)))
1283 (cond
1284 ;; Round down if round bit is 0.
1285 ((not (logtest round-bit low))
1286 (float-from-bits shifted len))
1287 ;; If only round bit is set, then round to even.
1288 ((and (= low round-bit)
1289 (dotimes (i (- (%bignum-length x) (ceiling keep digit-size))
1291 (unless (zerop (%bignum-ref x i)) (return nil))))
1292 (let ((next (%bignum-ref shifted 1)))
1293 (if (oddp next)
1294 (round-up)
1295 (float-from-bits shifted len))))
1296 ;; Otherwise, round up.
1298 (round-up))))))
1300 ;;;; integer length and logbitp/logcount
1302 (defun bignum-buffer-integer-length (bignum len)
1303 (declare (type bignum bignum))
1304 (let* ((len-1 (1- len))
1305 (digit (%bignum-ref bignum len-1)))
1306 (declare (type bignum-length len len-1)
1307 (type bignum-element-type digit))
1308 (+ (integer-length (%fixnum-digit-with-correct-sign digit))
1309 (* len-1 digit-size))))
1311 (defun bignum-integer-length (bignum)
1312 (declare (type bignum bignum))
1313 (bignum-buffer-integer-length bignum (%bignum-length bignum)))
1315 (defun bignum-logbitp (index bignum)
1316 (declare (type bignum bignum)
1317 (type bignum-index index))
1318 (let ((len (%bignum-length bignum)))
1319 (declare (type bignum-length len))
1320 (multiple-value-bind (word-index bit-index)
1321 (floor index digit-size)
1322 (if (>= word-index len)
1323 (not (bignum-plus-p bignum))
1324 (logbitp bit-index (%bignum-ref bignum word-index))))))
1326 (defun bignum-logcount (bignum)
1327 (declare (type bignum bignum)
1328 (optimize speed))
1329 (declare (muffle-conditions compiler-note)) ; returns lispobj, so what.
1330 (let ((length (%bignum-length bignum))
1331 (result 0))
1332 (declare (type bignum-length length)
1333 (fixnum result))
1334 (do ((index 0 (1+ index)))
1335 ((= index length)
1336 (if (%bignum-0-or-plusp bignum length)
1337 result
1338 (- (* length digit-size) result)))
1339 (let ((digit (%bignum-ref bignum index)))
1340 (declare (type bignum-element-type digit))
1341 (incf result (logcount digit))))))
1343 ;;;; logical operations
1345 ;;;; NOT
1347 (defun bignum-logical-not (a)
1348 (declare (type bignum a))
1349 (let* ((len (%bignum-length a))
1350 (res (%allocate-bignum len)))
1351 (declare (type bignum-length len))
1352 (dotimes (i len res)
1353 (declare (type bignum-index i))
1354 (setf (%bignum-ref res i) (%lognot (%bignum-ref a i))))))
1356 ;;;; AND
1358 (defun bignum-logical-and (a b)
1359 (declare (type bignum a b))
1360 (let* ((len-a (%bignum-length a))
1361 (len-b (%bignum-length b))
1362 (a-plusp (%bignum-0-or-plusp a len-a))
1363 (b-plusp (%bignum-0-or-plusp b len-b)))
1364 (declare (type bignum-length len-a len-b))
1365 (cond
1366 ((< len-a len-b)
1367 (if a-plusp
1368 (logand-shorter-positive a len-a b (%allocate-bignum len-a))
1369 (logand-shorter-negative a len-a b len-b (%allocate-bignum len-b))))
1370 ((< len-b len-a)
1371 (if b-plusp
1372 (logand-shorter-positive b len-b a (%allocate-bignum len-b))
1373 (logand-shorter-negative b len-b a len-a (%allocate-bignum len-a))))
1374 (t (logand-shorter-positive a len-a b (%allocate-bignum len-a))))))
1376 ;;; This takes a shorter bignum, a and len-a, that is positive. Because this
1377 ;;; is AND, we don't care about any bits longer than a's since its infinite 0
1378 ;;; sign bits will mask the other bits out of b. The result is len-a big.
1379 (defun logand-shorter-positive (a len-a b res)
1380 (declare (type bignum a b res)
1381 (type bignum-length len-a))
1382 (dotimes (i len-a)
1383 (declare (type bignum-index i))
1384 (setf (%bignum-ref res i)
1385 (%logand (%bignum-ref a i) (%bignum-ref b i))))
1386 (%normalize-bignum res len-a))
1388 ;;; This takes a shorter bignum, a and len-a, that is negative. Because this
1389 ;;; is AND, we just copy any bits longer than a's since its infinite 1 sign
1390 ;;; bits will include any bits from b. The result is len-b big.
1391 (defun logand-shorter-negative (a len-a b len-b res)
1392 (declare (type bignum a b res)
1393 (type bignum-length len-a len-b))
1394 (dotimes (i len-a)
1395 (declare (type bignum-index i))
1396 (setf (%bignum-ref res i)
1397 (%logand (%bignum-ref a i) (%bignum-ref b i))))
1398 (do ((i len-a (1+ i)))
1399 ((= i len-b))
1400 (declare (type bignum-index i))
1401 (setf (%bignum-ref res i) (%bignum-ref b i)))
1402 (%normalize-bignum res len-b))
1404 ;;;; IOR
1406 (defun bignum-logical-ior (a b)
1407 (declare (type bignum a b))
1408 (let* ((len-a (%bignum-length a))
1409 (len-b (%bignum-length b))
1410 (a-plusp (%bignum-0-or-plusp a len-a))
1411 (b-plusp (%bignum-0-or-plusp b len-b)))
1412 (declare (type bignum-length len-a len-b))
1413 (cond
1414 ((< len-a len-b)
1415 (if a-plusp
1416 (logior-shorter-positive a len-a b len-b (%allocate-bignum len-b))
1417 (logior-shorter-negative a len-a b len-b (%allocate-bignum len-b))))
1418 ((< len-b len-a)
1419 (if b-plusp
1420 (logior-shorter-positive b len-b a len-a (%allocate-bignum len-a))
1421 (logior-shorter-negative b len-b a len-a (%allocate-bignum len-a))))
1422 (t (logior-shorter-positive a len-a b len-b (%allocate-bignum len-a))))))
1424 ;;; This takes a shorter bignum, a and len-a, that is positive. Because this
1425 ;;; is IOR, we don't care about any bits longer than a's since its infinite
1426 ;;; 0 sign bits will mask the other bits out of b out to len-b. The result
1427 ;;; is len-b long.
1428 (defun logior-shorter-positive (a len-a b len-b res)
1429 (declare (type bignum a b res)
1430 (type bignum-length len-a len-b))
1431 (dotimes (i len-a)
1432 (declare (type bignum-index i))
1433 (setf (%bignum-ref res i)
1434 (%logior (%bignum-ref a i) (%bignum-ref b i))))
1435 (do ((i len-a (1+ i)))
1436 ((= i len-b))
1437 (declare (type bignum-index i))
1438 (setf (%bignum-ref res i) (%bignum-ref b i)))
1439 (%normalize-bignum res len-b))
1441 ;;; This takes a shorter bignum, a and len-a, that is negative. Because this
1442 ;;; is IOR, we just copy any bits longer than a's since its infinite 1 sign
1443 ;;; bits will include any bits from b. The result is len-b long.
1444 (defun logior-shorter-negative (a len-a b len-b res)
1445 (declare (type bignum a b res)
1446 (type bignum-length len-a len-b))
1447 (dotimes (i len-a)
1448 (declare (type bignum-index i))
1449 (setf (%bignum-ref res i)
1450 (%logior (%bignum-ref a i) (%bignum-ref b i))))
1451 (do ((i len-a (1+ i))
1452 (sign (%sign-digit a len-a)))
1453 ((= i len-b))
1454 (declare (type bignum-index i))
1455 (setf (%bignum-ref res i) sign))
1456 (%normalize-bignum res len-b))
1458 ;;;; XOR
1460 (defun bignum-logical-xor (a b)
1461 (declare (type bignum a b))
1462 (let ((len-a (%bignum-length a))
1463 (len-b (%bignum-length b)))
1464 (declare (type bignum-length len-a len-b))
1465 (if (< len-a len-b)
1466 (bignum-logical-xor-aux a len-a b len-b (%allocate-bignum len-b))
1467 (bignum-logical-xor-aux b len-b a len-a (%allocate-bignum len-a)))))
1469 ;;; This takes the shorter of two bignums in a and len-a. Res is len-b
1470 ;;; long. Do the XOR.
1471 (defun bignum-logical-xor-aux (a len-a b len-b res)
1472 (declare (type bignum a b res)
1473 (type bignum-length len-a len-b))
1474 (dotimes (i len-a)
1475 (declare (type bignum-index i))
1476 (setf (%bignum-ref res i)
1477 (%logxor (%bignum-ref a i) (%bignum-ref b i))))
1478 (do ((i len-a (1+ i))
1479 (sign (%sign-digit a len-a)))
1480 ((= i len-b))
1481 (declare (type bignum-index i))
1482 (setf (%bignum-ref res i) (%logxor sign (%bignum-ref b i))))
1483 (%normalize-bignum res len-b))
1485 ;;;; There used to be a bunch of code to implement "efficient" versions of LDB
1486 ;;;; and DPB here. But it apparently was never used, so it's been deleted.
1487 ;;;; --njf, 2007-02-04
1489 ;; This could be used by way of a transform, though for now it's specifically
1490 ;; a helper for %LDB in the limited case that it recognizes as non-consing.
1491 (defun ldb-bignum=>fixnum (byte-size byte-pos bignum)
1492 (declare (type (integer 0 #.sb!vm:n-positive-fixnum-bits) byte-size)
1493 (type bit-index byte-pos))
1494 (multiple-value-bind (word-index bit-index) (floor byte-pos digit-size)
1495 (let ((n-digits (%bignum-length bignum)))
1496 (cond ((>= word-index n-digits) ; load from the infinitely extended sign word
1497 (ldb (byte byte-size 0) (%sign-digit bignum n-digits)))
1498 ((<= (+ bit-index byte-size) digit-size) ; contained in one word
1499 ;; This case takes care of byte-size = 0 also.
1500 (ldb (byte byte-size bit-index) (%bignum-ref bignum word-index)))
1502 ;; At least one bit is obtained from each of two words,
1503 ;; and not more than two words.
1504 (let* ((low-part-size
1505 (truly-the (integer 1 #.(1- sb!vm:n-positive-fixnum-bits))
1506 (- digit-size bit-index)))
1507 (high-part-size
1508 (truly-the (integer 1 #.(1- sb!vm:n-positive-fixnum-bits))
1509 (- byte-size low-part-size))))
1510 (logior (truly-the (and fixnum unsigned-byte) ; high part
1511 (let ((word-index (1+ word-index)))
1512 (if (< word-index n-digits) ; next word exists
1513 (ash (ldb (byte high-part-size 0)
1514 (%bignum-ref bignum word-index))
1515 low-part-size)
1516 (mask-field (byte high-part-size low-part-size)
1517 (%sign-digit bignum n-digits)))))
1518 (ldb (byte low-part-size bit-index) ; low part
1519 (%bignum-ref bignum word-index)))))))))
1521 ;;;; TRUNCATE
1523 ;;; This is the original sketch of the algorithm from which I implemented this
1524 ;;; TRUNCATE, assuming both operands are bignums. I should modify this to work
1525 ;;; with the documentation on my functions, as a general introduction. I've
1526 ;;; left this here just in case someone needs it in the future. Don't look at
1527 ;;; this unless reading the functions' comments leaves you at a loss. Remember
1528 ;;; this comes from Knuth, so the book might give you the right general
1529 ;;; overview.
1531 ;;; (truncate x y):
1533 ;;; If X's magnitude is less than Y's, then result is 0 with remainder X.
1535 ;;; Make x and y positive, copying x if it is already positive.
1537 ;;; Shift y left until there's a 1 in the 30'th bit (most significant, non-sign
1538 ;;; digit)
1539 ;;; Just do most sig digit to determine how much to shift whole number.
1540 ;;; Shift x this much too.
1541 ;;; Remember this initial shift count.
1543 ;;; Allocate q to be len-x minus len-y quantity plus 1.
1545 ;;; i = last digit of x.
1546 ;;; k = last digit of q.
1548 ;;; LOOP
1550 ;;; j = last digit of y.
1552 ;;; compute guess.
1553 ;;; if x[i] = y[j] then g = (1- (ash 1 digit-size))
1554 ;;; else g = x[i]x[i-1]/y[j].
1556 ;;; check guess.
1557 ;;; %UNSIGNED-MULTIPLY returns b and c defined below.
1558 ;;; a = x[i-1] - (logand (* g y[j]) #xFFFFFFFF).
1559 ;;; Use %UNSIGNED-MULTIPLY taking low-order result.
1560 ;;; b = (logand (ash (* g y[j-1]) (- digit-size)) (1- (ash 1 digit-size))).
1561 ;;; c = (logand (* g y[j-1]) (1- (ash 1 digit-size))).
1562 ;;; if a < b, okay.
1563 ;;; if a > b, guess is too high
1564 ;;; g = g - 1; go back to "check guess".
1565 ;;; if a = b and c > x[i-2], guess is too high
1566 ;;; g = g - 1; go back to "check guess".
1567 ;;; GUESS IS 32-BIT NUMBER, SO USE THING TO KEEP IN SPECIAL REGISTER
1568 ;;; SAME FOR A, B, AND C.
1570 ;;; Subtract g * y from x[i - len-y+1]..x[i]. See paper for doing this in step.
1571 ;;; If x[i] < 0, guess is screwed up.
1572 ;;; negative g, then add 1
1573 ;;; zero or positive g, then subtract 1
1574 ;;; AND add y back into x[len-y+1..i].
1576 ;;; q[k] = g.
1577 ;;; i = i - 1.
1578 ;;; k = k - 1.
1580 ;;; If k>=0, goto LOOP.
1582 ;;; Now quotient is good, but remainder is not.
1583 ;;; Shift x right by saved initial left shifting count.
1585 ;;; Check quotient and remainder signs.
1586 ;;; x pos y pos --> q pos r pos
1587 ;;; x pos y neg --> q neg r pos
1588 ;;; x neg y pos --> q neg r neg
1589 ;;; x neg y neg --> q pos r neg
1591 ;;; Normalize quotient and remainder. Cons result if necessary.
1594 ;;; This used to be split into multiple functions, which shared state
1595 ;;; in special variables *TRUNCATE-X* and *TRUNCATE-Y*. Having so many
1596 ;;; special variable accesses in tight inner loops was having a large
1597 ;;; effect on performance, so the helper functions have now been
1598 ;;; refactored into local functions and the special variables into
1599 ;;; lexicals. There was also a lot of boxing and unboxing of
1600 ;;; (UNSIGNED-BYTE 32)'s going on, which this refactoring
1601 ;;; eliminated. This improves the performance on some CL-BENCH tests
1602 ;;; by up to 50%, which is probably signigicant enough to justify the
1603 ;;; reduction in readability that was introduced. --JES, 2004-08-07
1604 (defun bignum-truncate (x y)
1605 (declare (type bignum x y))
1606 (declare (muffle-conditions compiler-note)) ; returns lispobj, so what.
1607 (let (truncate-x truncate-y)
1608 (labels
1609 ;;; Divide X by Y when Y is a single bignum digit. BIGNUM-TRUNCATE
1610 ;;; fixes up the quotient and remainder with respect to sign and
1611 ;;; normalization.
1613 ;;; We don't have to worry about shifting Y to make its most
1614 ;;; significant digit sufficiently large for %BIGFLOOR to return
1615 ;;; digit-size quantities for the q-digit and r-digit. If Y is
1616 ;;; a single digit bignum, it is already large enough for
1617 ;;; %BIGFLOOR. That is, it has some bits on pretty high in the
1618 ;;; digit.
1619 ((bignum-truncate-single-digit (x len-x y)
1620 (declare (type bignum-length len-x))
1621 (let ((y (%bignum-ref y 0)))
1622 (declare (type bignum-element-type y))
1623 (if (not (logtest y (1- y)))
1624 ;; Y is a power of two.
1625 ;; SHIFT-RIGHT-UNALIGNED won't do the right thing
1626 ;; with a shift count of 0 or -1, so special case this.
1627 (cond ((= y 0)
1628 (error 'division-by-zero :operation 'truncate
1629 :operands (list x y)))
1630 ((= y 1)
1631 ;; We could probably get away with (VALUES X 0)
1632 ;; here, but it's not clear that some of the
1633 ;; normalization logic further down would avoid
1634 ;; mutilating X. Just go ahead and cons, consing's
1635 ;; cheap.
1636 (values (copy-bignum x len-x) 0))
1638 (let ((n-bits (1- (integer-length y))))
1639 (values
1640 (shift-right-unaligned x 0 n-bits len-x
1641 ((= j res-len-1)
1642 (setf (%bignum-ref res j)
1643 (%ashr (%bignum-ref x i) n-bits))
1644 res)
1645 res)
1646 (logand (%bignum-ref x 0) (1- y))))))
1647 (do ((i (1- len-x) (1- i))
1648 (q (%allocate-bignum len-x))
1649 (r 0))
1650 ((minusp i)
1651 (let ((rem (%allocate-bignum 1)))
1652 (setf (%bignum-ref rem 0) r)
1653 (values q rem)))
1654 (declare (type bignum-element-type r))
1655 (multiple-value-bind (q-digit r-digit)
1656 (%bigfloor r (%bignum-ref x i) y)
1657 (declare (type bignum-element-type q-digit r-digit))
1658 (setf (%bignum-ref q i) q-digit)
1659 (setf r r-digit))))))
1660 ;;; This returns a guess for the next division step. Y1 is the
1661 ;;; highest y digit, and y2 is the second to highest y
1662 ;;; digit. The x... variables are the three highest x digits
1663 ;;; for the next division step.
1665 ;;; From Knuth, our guess is either all ones or x-i and x-i-1
1666 ;;; divided by y1, depending on whether x-i and y1 are the
1667 ;;; same. We test this guess by determining whether guess*y2
1668 ;;; is greater than the three high digits of x minus guess*y1
1669 ;;; shifted left one digit:
1670 ;;; ------------------------------
1671 ;;; | x-i | x-i-1 | x-i-2 |
1672 ;;; ------------------------------
1673 ;;; ------------------------------
1674 ;;; - | g*y1 high | g*y1 low | 0 |
1675 ;;; ------------------------------
1676 ;;; ... < guess*y2 ???
1677 ;;; If guess*y2 is greater, then we decrement our guess by one
1678 ;;; and try again. This returns a guess that is either
1679 ;;; correct or one too large.
1680 (bignum-truncate-guess (y1 y2 x-i x-i-1 x-i-2)
1681 (declare (type bignum-element-type y1 y2 x-i x-i-1 x-i-2))
1682 (let ((guess (if (= x-i y1)
1683 all-ones-digit
1684 (%bigfloor x-i x-i-1 y1))))
1685 (declare (type bignum-element-type guess))
1686 (loop
1687 (multiple-value-bind (high-guess*y1 low-guess*y1)
1688 (%multiply guess y1)
1689 (declare (type bignum-element-type low-guess*y1
1690 high-guess*y1))
1691 (multiple-value-bind (high-guess*y2 low-guess*y2)
1692 (%multiply guess y2)
1693 (declare (type bignum-element-type high-guess*y2
1694 low-guess*y2))
1695 (multiple-value-bind (middle-digit borrow)
1696 (%subtract-with-borrow x-i-1 low-guess*y1 1)
1697 (declare (type bignum-element-type middle-digit)
1698 (fixnum borrow))
1699 ;; Supplying borrow of 1 means there was no
1700 ;; borrow, and we know x-i-2 minus 0 requires
1701 ;; no borrow.
1702 (let ((high-digit (%subtract-with-borrow x-i
1703 high-guess*y1
1704 borrow)))
1705 (declare (type bignum-element-type high-digit))
1706 (if (and (= high-digit 0)
1707 (or (> high-guess*y2 middle-digit)
1708 (and (= middle-digit high-guess*y2)
1709 (> low-guess*y2 x-i-2))))
1710 (setf guess (%subtract-with-borrow guess 1 1))
1711 (return guess)))))))))
1712 ;;; Divide TRUNCATE-X by TRUNCATE-Y, returning the quotient
1713 ;;; and destructively modifying TRUNCATE-X so that it holds
1714 ;;; the remainder.
1716 ;;; LEN-X and LEN-Y tell us how much of the buffers we care about.
1718 ;;; TRUNCATE-X definitely has at least three digits, and it has one
1719 ;;; more than TRUNCATE-Y. This keeps i, i-1, i-2, and low-x-digit
1720 ;;; happy. Thanks to SHIFT-AND-STORE-TRUNCATE-BUFFERS.
1721 (return-quotient-leaving-remainder (len-x len-y)
1722 (declare (type bignum-length len-x len-y))
1723 (let* ((len-q (- len-x len-y))
1724 ;; Add one for extra sign digit in case high bit is on.
1725 (q (%allocate-bignum (1+ len-q)))
1726 (k (1- len-q))
1727 (y1 (%bignum-ref truncate-y (1- len-y)))
1728 (y2 (%bignum-ref truncate-y (- len-y 2)))
1729 (i (1- len-x))
1730 (i-1 (1- i))
1731 (i-2 (1- i-1))
1732 (low-x-digit (- i len-y)))
1733 (declare (type bignum-length len-q)
1734 (type bignum-index k i i-1 i-2 low-x-digit)
1735 (type bignum-element-type y1 y2))
1736 (loop
1737 (setf (%bignum-ref q k)
1738 (try-bignum-truncate-guess
1739 ;; This modifies TRUNCATE-X. Must access
1740 ;; elements each pass.
1741 (bignum-truncate-guess y1 y2
1742 (%bignum-ref truncate-x i)
1743 (%bignum-ref truncate-x i-1)
1744 (%bignum-ref truncate-x i-2))
1745 len-y low-x-digit))
1746 (cond ((zerop k) (return))
1747 (t (decf k)
1748 (decf low-x-digit)
1749 (shiftf i i-1 i-2 (1- i-2)))))
1751 ;;; This takes a digit guess, multiplies it by TRUNCATE-Y for a
1752 ;;; result one greater in length than LEN-Y, and subtracts this result
1753 ;;; from TRUNCATE-X. LOW-X-DIGIT is the first digit of X to start
1754 ;;; the subtraction, and we know X is long enough to subtract a LEN-Y
1755 ;;; plus one length bignum from it. Next we check the result of the
1756 ;;; subtraction, and if the high digit in X became negative, then our
1757 ;;; guess was one too big. In this case, return one less than GUESS
1758 ;;; passed in, and add one value of Y back into X to account for
1759 ;;; subtracting one too many. Knuth shows that the guess is wrong on
1760 ;;; the order of 3/b, where b is the base (2 to the digit-size power)
1761 ;;; -- pretty rarely.
1762 (try-bignum-truncate-guess (guess len-y low-x-digit)
1763 (declare (type bignum-index low-x-digit)
1764 (type bignum-length len-y)
1765 (type bignum-element-type guess))
1766 (let ((carry-digit 0)
1767 (borrow 1)
1768 (i low-x-digit))
1769 (declare (type bignum-element-type carry-digit)
1770 (type bignum-index i)
1771 (fixnum borrow))
1772 ;; Multiply guess and divisor, subtracting from dividend
1773 ;; simultaneously.
1774 (dotimes (j len-y)
1775 (multiple-value-bind (high-digit low-digit)
1776 (%multiply-and-add guess
1777 (%bignum-ref truncate-y j)
1778 carry-digit)
1779 (declare (type bignum-element-type high-digit low-digit))
1780 (setf carry-digit high-digit)
1781 (multiple-value-bind (x temp-borrow)
1782 (%subtract-with-borrow (%bignum-ref truncate-x i)
1783 low-digit
1784 borrow)
1785 (declare (type bignum-element-type x)
1786 (fixnum temp-borrow))
1787 (setf (%bignum-ref truncate-x i) x)
1788 (setf borrow temp-borrow)))
1789 (incf i))
1790 (setf (%bignum-ref truncate-x i)
1791 (%subtract-with-borrow (%bignum-ref truncate-x i)
1792 carry-digit borrow))
1793 ;; See whether guess is off by one, adding one
1794 ;; Y back in if necessary.
1795 (cond ((%digit-0-or-plusp (%bignum-ref truncate-x i))
1796 guess)
1798 ;; If subtraction has negative result, add one
1799 ;; divisor value back in. The guess was one too
1800 ;; large in magnitude.
1801 (let ((i low-x-digit)
1802 (carry 0))
1803 (dotimes (j len-y)
1804 (multiple-value-bind (v k)
1805 (%add-with-carry (%bignum-ref truncate-y j)
1806 (%bignum-ref truncate-x i)
1807 carry)
1808 (declare (type bignum-element-type v))
1809 (setf (%bignum-ref truncate-x i) v)
1810 (setf carry k))
1811 (incf i))
1812 (setf (%bignum-ref truncate-x i)
1813 (%add-with-carry (%bignum-ref truncate-x i)
1814 0 carry)))
1815 (%subtract-with-borrow guess 1 1)))))
1816 ;;; This returns the amount to shift y to place a one in the
1817 ;;; second highest bit. Y must be positive. If the last digit
1818 ;;; of y is zero, then y has a one in the previous digit's
1819 ;;; sign bit, so we know it will take one less than digit-size
1820 ;;; to get a one where we want. Otherwise, we count how many
1821 ;;; right shifts it takes to get zero; subtracting this value
1822 ;;; from digit-size tells us how many high zeros there are
1823 ;;; which is one more than the shift amount sought.
1825 ;;; Note: This is exactly the same as one less than the
1826 ;;; integer-length of the last digit subtracted from the
1827 ;;; digit-size.
1829 ;;; We shift y to make it sufficiently large that doing the
1830 ;;; 2*digit-size by digit-size %BIGFLOOR calls ensures the quotient and
1831 ;;; remainder fit in digit-size.
1832 (shift-y-for-truncate (y)
1833 (let* ((len (%bignum-length y))
1834 (last (%bignum-ref y (1- len))))
1835 (declare (type bignum-length len)
1836 (type bignum-element-type last))
1837 (- digit-size (integer-length last) 1)))
1838 ;;; Stores two bignums into the truncation bignum buffers,
1839 ;;; shifting them on the way in. This assumes x and y are
1840 ;;; positive and at least two in length, and it assumes
1841 ;;; truncate-x and truncate-y are one digit longer than x and
1842 ;;; y.
1843 (shift-and-store-truncate-buffers (x len-x y len-y shift)
1844 (declare (type bignum-length len-x len-y)
1845 (type (integer 0 (#.digit-size)) shift))
1846 (cond ((zerop shift)
1847 (bignum-replace truncate-x x :end1 len-x)
1848 (bignum-replace truncate-y y :end1 len-y))
1850 (bignum-ashift-left-unaligned x 0 shift (1+ len-x)
1851 truncate-x)
1852 (bignum-ashift-left-unaligned y 0 shift (1+ len-y)
1853 truncate-y))))) ;; LABELS
1854 ;;; Divide X by Y returning the quotient and remainder. In the
1855 ;;; general case, we shift Y to set up for the algorithm, and we
1856 ;;; use two buffers to save consing intermediate values. X gets
1857 ;;; destructively modified to become the remainder, and we have
1858 ;;; to shift it to account for the initial Y shift. After we
1859 ;;; multiple bind q and r, we first fix up the signs and then
1860 ;;; return the normalized results.
1861 (let* ((x-plusp (bignum-plus-p x))
1862 (y-plusp (bignum-plus-p y))
1863 (x (if x-plusp x (negate-bignum x nil)))
1864 (y (if y-plusp y (negate-bignum y nil)))
1865 (len-x (%bignum-length x))
1866 (len-y (%bignum-length y)))
1867 (multiple-value-bind (q r)
1868 (cond ((< len-y 2)
1869 (bignum-truncate-single-digit x len-x y))
1870 ((plusp (bignum-compare y x))
1871 (let ((res (%allocate-bignum len-x)))
1872 (dotimes (i len-x)
1873 (setf (%bignum-ref res i) (%bignum-ref x i)))
1874 (values 0 res)))
1876 (let ((len-x+1 (1+ len-x)))
1877 (setf truncate-x (%allocate-bignum len-x+1))
1878 (setf truncate-y (%allocate-bignum (1+ len-y)))
1879 (let ((y-shift (shift-y-for-truncate y)))
1880 (shift-and-store-truncate-buffers x len-x y
1881 len-y y-shift)
1882 (values (return-quotient-leaving-remainder len-x+1
1883 len-y)
1884 ;; Now that RETURN-QUOTIENT-LEAVING-REMAINDER
1885 ;; has executed, we just tidy up the remainder
1886 ;; (in TRUNCATE-X) and return it.
1887 (cond
1888 ((zerop y-shift)
1889 (let ((res (%allocate-bignum len-y)))
1890 (declare (type bignum res))
1891 (bignum-replace res truncate-x :end2 len-y)
1892 (%normalize-bignum res len-y)))
1894 (shift-right-unaligned
1895 truncate-x 0 y-shift len-y
1896 ((= j res-len-1)
1897 (setf (%bignum-ref res j)
1898 (%ashr (%bignum-ref truncate-x i)
1899 y-shift))
1900 (%normalize-bignum res res-len))
1901 res))))))))
1902 (let ((quotient (cond ((eq x-plusp y-plusp) q)
1903 ((typep q 'fixnum) (the fixnum (- q)))
1904 (t (negate-bignum-in-place q))))
1905 (rem (cond (x-plusp r)
1906 ((typep r 'fixnum) (the fixnum (- r)))
1907 (t (negate-bignum-in-place r)))))
1908 (values (if (typep quotient 'fixnum)
1909 quotient
1910 (%normalize-bignum quotient (%bignum-length quotient)))
1911 (if (typep rem 'fixnum)
1913 (%normalize-bignum rem (%bignum-length rem))))))))))
1916 ;;;; There used to be a pile of code for implementing division for bignum digits
1917 ;;;; for machines that don't have a 2*digit-size by digit-size divide instruction.
1918 ;;;; This happens to be most machines, but all the SBCL ports seem to be content
1919 ;;;; to implement SB-BIGNUM:%BIGFLOOR as a VOP rather than using the code here.
1920 ;;;; So it's been deleted. --njf, 2007-02-04
1922 ;;;; general utilities
1924 ;;; Internal in-place operations use this to fixup remaining digits in the
1925 ;;; incoming data, such as in-place shifting. This is basically the same as
1926 ;;; the first form in %NORMALIZE-BIGNUM, but we return the length of the buffer
1927 ;;; instead of shrinking the bignum.
1928 #!-sb-fluid (declaim (maybe-inline %normalize-bignum-buffer))
1929 (defun %normalize-bignum-buffer (result len)
1930 (declare (type bignum result)
1931 (type bignum-length len))
1932 (unless (= len 1)
1933 (do ((next-digit (%bignum-ref result (- len 2))
1934 (%bignum-ref result (- len 2)))
1935 (sign-digit (%bignum-ref result (1- len)) next-digit))
1936 ((not (zerop (logxor sign-digit (%ashr next-digit (1- digit-size))))))
1937 (decf len)
1938 (setf (%bignum-ref result len) 0)
1939 (when (= len 1)
1940 (return))))
1941 len)
1943 ;;; This drops the last digit if it is unnecessary sign information. It repeats
1944 ;;; this as needed, possibly ending with a fixnum. If the resulting length from
1945 ;;; shrinking is one, see whether our one word is a fixnum. Shift the possible
1946 ;;; fixnum bits completely out of the word, and compare this with shifting the
1947 ;;; sign bit all the way through. If the bits are all 1's or 0's in both words,
1948 ;;; then there are just sign bits between the fixnum bits and the sign bit. If
1949 ;;; we do have a fixnum, shift it over for the two low-tag bits.
1950 (defun %normalize-bignum (result len)
1951 (declare (type bignum result)
1952 (type bignum-length len)
1953 (muffle-conditions compiler-note)
1954 #!-sb-fluid (inline %normalize-bignum-buffer))
1955 (let ((newlen (%normalize-bignum-buffer result len)))
1956 (declare (type bignum-length newlen))
1957 (unless (= newlen len)
1958 (%bignum-set-length result newlen))
1959 (if (= newlen 1)
1960 (let ((digit (%bignum-ref result 0)))
1961 (if (= (%ashr digit sb!vm:n-positive-fixnum-bits)
1962 (%ashr digit (1- digit-size)))
1963 (%fixnum-digit-with-correct-sign digit)
1964 result))
1965 result)))
1967 ;;; This drops the last digit if it is unnecessary sign information. It
1968 ;;; repeats this as needed, possibly ending with a fixnum magnitude but never
1969 ;;; returning a fixnum.
1970 (defun %mostly-normalize-bignum (result len)
1971 (declare (type bignum result)
1972 (type bignum-length len)
1973 #!-sb-fluid (inline %normalize-bignum-buffer))
1974 (let ((newlen (%normalize-bignum-buffer result len)))
1975 (declare (type bignum-length newlen))
1976 (unless (= newlen len)
1977 (%bignum-set-length result newlen))
1978 result))
1980 ;;;; hashing
1982 ;;; the bignum case of the SXHASH function
1983 (defun sxhash-bignum (x)
1984 (let ((result 316495330))
1985 (declare (type fixnum result))
1986 (dotimes (i (%bignum-length x))
1987 (declare (type index i))
1988 (let ((xi (%bignum-ref x i)))
1989 (mixf result
1990 (logand most-positive-fixnum
1991 (logxor xi
1992 (ash xi -7))))))
1993 result))