No more song and dance routine with BOOLE- constants.
[sbcl.git] / src / code / numbers.lisp
blob54765f71870c91647ed4a6c83538fd65157aa1b1
1 ;;;; This file contains the definitions of most number functions.
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!KERNEL")
14 ;;;; the NUMBER-DISPATCH macro
16 (eval-when (:compile-toplevel :load-toplevel :execute)
18 ;;; Grovel an individual case to NUMBER-DISPATCH, augmenting RESULT
19 ;;; with the type dispatches and bodies. Result is a tree built of
20 ;;; alists representing the dispatching off each arg (in order). The
21 ;;; leaf is the body to be executed in that case.
22 (defun parse-number-dispatch (vars result types var-types body)
23 (cond ((null vars)
24 (unless (null types) (error "More types than vars."))
25 (when (cdr result)
26 (error "Duplicate case: ~S." body))
27 (setf (cdr result)
28 (sublis var-types body :test #'equal)))
29 ((null types)
30 (error "More vars than types."))
32 (flet ((frob (var type)
33 (parse-number-dispatch
34 (rest vars)
35 (or (assoc type (cdr result) :test #'equal)
36 (car (setf (cdr result)
37 (acons type nil (cdr result)))))
38 (rest types)
39 (acons `(dispatch-type ,var) type var-types)
40 body)))
41 (let ((type (first types))
42 (var (first vars)))
43 (if (and (consp type) (eq (first type) 'foreach))
44 (dolist (type (rest type))
45 (frob var type))
46 (frob var type)))))))
48 ;;; our guess for the preferred order in which to do type tests
49 ;;; (cheaper and/or more probable first.)
50 (defparameter *type-test-ordering*
51 '(fixnum single-float double-float integer #!+long-float long-float
52 sb!vm:signed-word word bignum
53 complex ratio))
55 ;;; Should TYPE1 be tested before TYPE2?
56 (defun type-test-order (type1 type2)
57 (let ((o1 (position type1 *type-test-ordering*))
58 (o2 (position type2 *type-test-ordering*)))
59 (cond ((not o1) nil)
60 ((not o2) t)
62 (< o1 o2)))))
64 ;;; Return an ETYPECASE form that does the type dispatch, ordering the
65 ;;; cases for efficiency.
66 ;;; Check for some simple to detect problematic cases where the caller
67 ;;; used types that are not disjoint and where this may lead to
68 ;;; unexpected behaviour of the generated form, for example making
69 ;;; a clause unreachable, and throw an error if such a case is found.
70 ;;; An example:
71 ;;; (number-dispatch ((var1 integer) (var2 float))
72 ;;; ((fixnum single-float) a)
73 ;;; ((integer float) b))
74 ;;; Even though the types are not reordered here, the generated form,
75 ;;; basically
76 ;;; (etypecase var1
77 ;;; (fixnum (etypecase var2
78 ;;; (single-float a)))
79 ;;; (integer (etypecase var2
80 ;;; (float b))))
81 ;;; would fail at runtime if given var1 fixnum and var2 double-float,
82 ;;; even though the second clause matches this signature. To catch
83 ;;; this earlier than runtime we throw an error already here.
84 (defun generate-number-dispatch (vars error-tags cases)
85 (if vars
86 (let ((var (first vars))
87 (cases (sort cases #'type-test-order :key #'car)))
88 (flet ((error-if-sub-or-supertype (type1 type2)
89 (when (or (subtypep type1 type2)
90 (subtypep type2 type1))
91 (error "Types not disjoint: ~S ~S." type1 type2)))
92 (error-if-supertype (type1 type2)
93 (when (subtypep type2 type1)
94 (error "Type ~S ordered before subtype ~S."
95 type1 type2)))
96 (test-type-pairs (fun)
97 ;; Apply FUN to all (ordered) pairs of types from the
98 ;; cases.
99 (mapl (lambda (cases)
100 (when (cdr cases)
101 (let ((type1 (caar cases)))
102 (dolist (case (cdr cases))
103 (funcall fun type1 (car case))))))
104 cases)))
105 ;; For the last variable throw an error if a type is followed
106 ;; by a subtype, for all other variables additionally if a
107 ;; type is followed by a supertype.
108 (test-type-pairs (if (cdr vars)
109 #'error-if-sub-or-supertype
110 #'error-if-supertype)))
111 `((typecase ,var
112 ,@(mapcar (lambda (case)
113 `(,(first case)
114 ,@(generate-number-dispatch (rest vars)
115 (rest error-tags)
116 (cdr case))))
117 cases)
118 (t (go ,(first error-tags))))))
119 cases))
121 ) ; EVAL-WHEN
123 ;;; This is a vaguely case-like macro that does number cross-product
124 ;;; dispatches. The Vars are the variables we are dispatching off of.
125 ;;; The Type paired with each Var is used in the error message when no
126 ;;; case matches. Each case specifies a Type for each var, and is
127 ;;; executed when that signature holds. A type may be a list
128 ;;; (FOREACH Each-Type*), causing that case to be repeatedly
129 ;;; instantiated for every Each-Type. In the body of each case, any
130 ;;; list of the form (DISPATCH-TYPE Var-Name) is substituted with the
131 ;;; type of that var in that instance of the case.
133 ;;; As an alternate to a case spec, there may be a form whose CAR is a
134 ;;; symbol. In this case, we apply the CAR of the form to the CDR and
135 ;;; treat the result of the call as a list of cases. This process is
136 ;;; not applied recursively.
138 ;;; Be careful when using non-disjoint types in different cases for the
139 ;;; same variable. Some uses will behave as intended, others not, as the
140 ;;; variables are dispatched off sequentially and clauses are reordered
141 ;;; for efficiency. Some, but not all, problematic cases are detected
142 ;;; and lead to a compile time error; see GENERATE-NUMBER-DISPATCH above
143 ;;; for an example.
144 (defmacro number-dispatch (var-specs &body cases)
145 (let ((res (list nil))
146 (vars (mapcar #'car var-specs))
147 (block (gensym)))
148 (dolist (case cases)
149 (if (symbolp (first case))
150 (let ((cases (apply (symbol-function (first case)) (rest case))))
151 (dolist (case cases)
152 (parse-number-dispatch vars res (first case) nil (rest case))))
153 (parse-number-dispatch vars res (first case) nil (rest case))))
155 (collect ((errors)
156 (error-tags))
157 (dolist (spec var-specs)
158 (let ((var (first spec))
159 (type (second spec))
160 (tag (gensym)))
161 (error-tags tag)
162 (errors tag)
163 (errors `(return-from
164 ,block
165 (error 'simple-type-error :datum ,var
166 :expected-type ',type
167 :format-control
168 "~@<Argument ~A is not a ~S: ~2I~_~S~:>"
169 :format-arguments
170 (list ',var ',type ,var))))))
172 `(block ,block
173 (tagbody
174 (return-from ,block
175 ,@(generate-number-dispatch vars (error-tags)
176 (cdr res)))
177 ,@(errors))))))
179 ;;;; binary operation dispatching utilities
181 (eval-when (:compile-toplevel :execute)
183 ;;; Return NUMBER-DISPATCH forms for rational X float.
184 (defun float-contagion (op x y &optional (rat-types '(fixnum bignum ratio)))
185 `(((single-float single-float) (,op ,x ,y))
186 (((foreach ,@rat-types)
187 (foreach single-float double-float #!+long-float long-float))
188 (,op (coerce ,x '(dispatch-type ,y)) ,y))
189 (((foreach single-float double-float #!+long-float long-float)
190 (foreach ,@rat-types))
191 (,op ,x (coerce ,y '(dispatch-type ,x))))
192 #!+long-float
193 (((foreach single-float double-float long-float) long-float)
194 (,op (coerce ,x 'long-float) ,y))
195 #!+long-float
196 ((long-float (foreach single-float double-float))
197 (,op ,x (coerce ,y 'long-float)))
198 (((foreach single-float double-float) double-float)
199 (,op (coerce ,x 'double-float) ,y))
200 ((double-float single-float)
201 (,op ,x (coerce ,y 'double-float)))))
203 ;;; Return NUMBER-DISPATCH forms for bignum X fixnum.
204 (defun bignum-cross-fixnum (fix-op big-op)
205 `(((fixnum fixnum) (,fix-op x y))
206 ((fixnum bignum)
207 (,big-op (make-small-bignum x) y))
208 ((bignum fixnum)
209 (,big-op x (make-small-bignum y)))
210 ((bignum bignum)
211 (,big-op x y))))
213 ) ; EVAL-WHEN
215 ;;;; canonicalization utilities
217 ;;; If IMAGPART is 0, return REALPART, otherwise make a complex. This is
218 ;;; used when we know that REALPART and IMAGPART are the same type, but
219 ;;; rational canonicalization might still need to be done.
220 #!-sb-fluid (declaim (inline canonical-complex))
221 (defun canonical-complex (realpart imagpart)
222 (if (eql imagpart 0)
223 realpart
224 (cond #!+long-float
225 ((and (typep realpart 'long-float)
226 (typep imagpart 'long-float))
227 (truly-the (complex long-float) (complex realpart imagpart)))
228 ((and (typep realpart 'double-float)
229 (typep imagpart 'double-float))
230 (truly-the (complex double-float) (complex realpart imagpart)))
231 ((and (typep realpart 'single-float)
232 (typep imagpart 'single-float))
233 (truly-the (complex single-float) (complex realpart imagpart)))
235 (%make-complex realpart imagpart)))))
237 ;;; Given a numerator and denominator with the GCD already divided
238 ;;; out, make a canonical rational. We make the denominator positive,
239 ;;; and check whether it is 1.
240 #!-sb-fluid (declaim (inline build-ratio))
241 (defun build-ratio (num den)
242 (multiple-value-bind (num den)
243 (if (minusp den)
244 (values (- num) (- den))
245 (values num den))
246 (cond
247 ((eql den 0)
248 (error 'division-by-zero
249 :operands (list num den)
250 :operation 'build-ratio))
251 ((eql den 1) num)
252 (t (%make-ratio num den)))))
254 ;;; Truncate X and Y, but bum the case where Y is 1.
255 #!-sb-fluid (declaim (inline maybe-truncate))
256 (defun maybe-truncate (x y)
257 (if (eql y 1)
259 (truncate x y)))
261 ;;;; COMPLEXes
263 (defun complex (realpart &optional (imagpart 0))
264 #!+sb-doc
265 "Return a complex number with the specified real and imaginary components."
266 (declare (explicit-check))
267 (flet ((%%make-complex (realpart imagpart)
268 (cond #!+long-float
269 ((and (typep realpart 'long-float)
270 (typep imagpart 'long-float))
271 (truly-the (complex long-float)
272 (complex realpart imagpart)))
273 ((and (typep realpart 'double-float)
274 (typep imagpart 'double-float))
275 (truly-the (complex double-float)
276 (complex realpart imagpart)))
277 ((and (typep realpart 'single-float)
278 (typep imagpart 'single-float))
279 (truly-the (complex single-float)
280 (complex realpart imagpart)))
282 (%make-complex realpart imagpart)))))
283 (number-dispatch ((realpart real) (imagpart real))
284 ((rational rational)
285 (canonical-complex realpart imagpart))
286 (float-contagion %%make-complex realpart imagpart (rational)))))
288 (defun realpart (number)
289 #!+sb-doc
290 "Extract the real part of a number."
291 (etypecase number
292 #!+long-float
293 ((complex long-float)
294 (truly-the long-float (realpart number)))
295 ((complex double-float)
296 (truly-the double-float (realpart number)))
297 ((complex single-float)
298 (truly-the single-float (realpart number)))
299 ((complex rational)
300 (%realpart number))
301 (number
302 number)))
304 (defun imagpart (number)
305 #!+sb-doc
306 "Extract the imaginary part of a number."
307 (etypecase number
308 #!+long-float
309 ((complex long-float)
310 (truly-the long-float (imagpart number)))
311 ((complex double-float)
312 (truly-the double-float (imagpart number)))
313 ((complex single-float)
314 (truly-the single-float (imagpart number)))
315 ((complex rational)
316 (%imagpart number))
317 (float
318 (* 0 number))
319 (number
320 0)))
322 (defun conjugate (number)
323 #!+sb-doc
324 "Return the complex conjugate of NUMBER. For non-complex numbers, this is
325 an identity."
326 (declare (type number number) (explicit-check))
327 (if (complexp number)
328 (complex (realpart number) (- (imagpart number)))
329 number))
331 (defun signum (number)
332 #!+sb-doc
333 "If NUMBER is zero, return NUMBER, else return (/ NUMBER (ABS NUMBER))."
334 (declare (explicit-check))
335 (if (zerop number)
336 number
337 (if (rationalp number)
338 (if (plusp number) 1 -1)
339 (/ number (abs number)))))
341 ;;;; ratios
343 (defun numerator (number)
344 #!+sb-doc
345 "Return the numerator of NUMBER, which must be rational."
346 (numerator number))
348 (defun denominator (number)
349 #!+sb-doc
350 "Return the denominator of NUMBER, which must be rational."
351 (denominator number))
353 ;;;; arithmetic operations
354 ;;;;
355 ;;;; IMPORTANT NOTE: Accessing &REST arguments with NTH is actually extremely
356 ;;;; efficient in SBCL, as is taking their LENGTH -- so this code is very
357 ;;;; clever instead of being charmingly naive. Please check that "obvious"
358 ;;;; improvements don't actually ruin performance.
359 ;;;;
360 ;;;; (Granted that the difference between very clever and charmingly naivve
361 ;;;; can sometimes be sliced exceedingly thing...)
363 (macrolet ((define-arith (op init doc)
364 #!-sb-doc (declare (ignore doc))
365 `(defun ,op (&rest numbers)
366 (declare (explicit-check))
367 #!+sb-doc ,doc
368 (if numbers
369 (let ((result (the number (fast-&rest-nth 0 numbers))))
370 (do-rest-arg ((n) numbers 1 result)
371 (setq result (,op result n))))
372 ,init))))
373 (define-arith + 0
374 "Return the sum of its arguments. With no args, returns 0.")
375 (define-arith * 1
376 "Return the product of its arguments. With no args, returns 1."))
378 (defun - (number &rest more-numbers)
379 #!+sb-doc
380 "Subtract the second and all subsequent arguments from the first;
381 or with one argument, negate the first argument."
382 (declare (explicit-check))
383 (if more-numbers
384 (let ((result number))
385 (do-rest-arg ((n) more-numbers 0 result)
386 (setf result (- result n))))
387 (- number)))
389 (defun / (number &rest more-numbers)
390 #!+sb-doc
391 "Divide the first argument by each of the following arguments, in turn.
392 With one argument, return reciprocal."
393 (declare (explicit-check))
394 (if more-numbers
395 (let ((result number))
396 (do-rest-arg ((n) more-numbers 0 result)
397 (setf result (/ result n))))
398 (/ number)))
400 (defun 1+ (number)
401 #!+sb-doc
402 "Return NUMBER + 1."
403 (declare (explicit-check))
404 (1+ number))
406 (defun 1- (number)
407 #!+sb-doc
408 "Return NUMBER - 1."
409 (declare (explicit-check))
410 (1- number))
412 (eval-when (:compile-toplevel)
414 (sb!xc:defmacro two-arg-+/- (name op big-op)
415 `(defun ,name (x y)
416 (number-dispatch ((x number) (y number))
417 (bignum-cross-fixnum ,op ,big-op)
418 (float-contagion ,op x y)
420 ((complex complex)
421 (canonical-complex (,op (realpart x) (realpart y))
422 (,op (imagpart x) (imagpart y))))
423 (((foreach bignum fixnum ratio single-float double-float
424 #!+long-float long-float) complex)
425 (complex (,op x (realpart y)) (,op 0 (imagpart y))))
426 ((complex (or rational float))
427 (complex (,op (realpart x) y) (,op (imagpart x) 0)))
429 (((foreach fixnum bignum) ratio)
430 (let* ((dy (denominator y))
431 (n (,op (* x dy) (numerator y))))
432 (%make-ratio n dy)))
433 ((ratio integer)
434 (let* ((dx (denominator x))
435 (n (,op (numerator x) (* y dx))))
436 (%make-ratio n dx)))
437 ((ratio ratio)
438 (let* ((nx (numerator x))
439 (dx (denominator x))
440 (ny (numerator y))
441 (dy (denominator y))
442 (g1 (gcd dx dy)))
443 (if (eql g1 1)
444 (%make-ratio (,op (* nx dy) (* dx ny)) (* dx dy))
445 (let* ((t1 (,op (* nx (truncate dy g1)) (* (truncate dx g1) ny)))
446 (g2 (gcd t1 g1))
447 (t2 (truncate dx g1)))
448 (cond ((eql t1 0) 0)
449 ((eql g2 1)
450 (%make-ratio t1 (* t2 dy)))
451 (t (let* ((nn (truncate t1 g2))
452 (t3 (truncate dy g2))
453 (nd (if (eql t2 1) t3 (* t2 t3))))
454 (if (eql nd 1) nn (%make-ratio nn nd))))))))))))
456 ) ; EVAL-WHEN
458 (two-arg-+/- two-arg-+ + add-bignums)
459 (two-arg-+/- two-arg-- - subtract-bignum)
461 (defun two-arg-* (x y)
462 (flet ((integer*ratio (x y)
463 (if (eql x 0) 0
464 (let* ((ny (numerator y))
465 (dy (denominator y))
466 (gcd (gcd x dy)))
467 (if (eql gcd 1)
468 (%make-ratio (* x ny) dy)
469 (let ((nn (* (truncate x gcd) ny))
470 (nd (truncate dy gcd)))
471 (if (eql nd 1)
473 (%make-ratio nn nd)))))))
474 (complex*real (x y)
475 (canonical-complex (* (realpart x) y) (* (imagpart x) y))))
476 (number-dispatch ((x number) (y number))
477 (float-contagion * x y)
479 ((fixnum fixnum) (multiply-fixnums x y))
480 ((bignum fixnum) (multiply-bignum-and-fixnum x y))
481 ((fixnum bignum) (multiply-bignum-and-fixnum y x))
482 ((bignum bignum) (multiply-bignums x y))
484 ((complex complex)
485 (let* ((rx (realpart x))
486 (ix (imagpart x))
487 (ry (realpart y))
488 (iy (imagpart y)))
489 (canonical-complex (- (* rx ry) (* ix iy)) (+ (* rx iy) (* ix ry)))))
490 (((foreach bignum fixnum ratio single-float double-float
491 #!+long-float long-float)
492 complex)
493 (complex*real y x))
494 ((complex (or rational float))
495 (complex*real x y))
497 (((foreach bignum fixnum) ratio) (integer*ratio x y))
498 ((ratio integer) (integer*ratio y x))
499 ((ratio ratio)
500 (let* ((nx (numerator x))
501 (dx (denominator x))
502 (ny (numerator y))
503 (dy (denominator y))
504 (g1 (gcd nx dy))
505 (g2 (gcd dx ny)))
506 (build-ratio (* (maybe-truncate nx g1)
507 (maybe-truncate ny g2))
508 (* (maybe-truncate dx g2)
509 (maybe-truncate dy g1))))))))
511 ;;; Divide two integers, producing a canonical rational. If a fixnum,
512 ;;; we see whether they divide evenly before trying the GCD. In the
513 ;;; bignum case, we don't bother, since bignum division is expensive,
514 ;;; and the test is not very likely to succeed.
515 (defun integer-/-integer (x y)
516 (if (and (typep x 'fixnum) (typep y 'fixnum))
517 (multiple-value-bind (quo rem) (truncate x y)
518 (if (zerop rem)
520 (let ((gcd (gcd x y)))
521 (declare (fixnum gcd))
522 (if (eql gcd 1)
523 (build-ratio x y)
524 (build-ratio (truncate x gcd) (truncate y gcd))))))
525 (let ((gcd (gcd x y)))
526 (if (eql gcd 1)
527 (build-ratio x y)
528 (build-ratio (truncate x gcd) (truncate y gcd))))))
530 (defun two-arg-/ (x y)
531 (number-dispatch ((x number) (y number))
532 (float-contagion / x y (ratio integer))
534 ((complex complex)
535 (let* ((rx (realpart x))
536 (ix (imagpart x))
537 (ry (realpart y))
538 (iy (imagpart y)))
539 (if (> (abs ry) (abs iy))
540 (let* ((r (/ iy ry))
541 (dn (* ry (+ 1 (* r r)))))
542 (canonical-complex (/ (+ rx (* ix r)) dn)
543 (/ (- ix (* rx r)) dn)))
544 (let* ((r (/ ry iy))
545 (dn (* iy (+ 1 (* r r)))))
546 (canonical-complex (/ (+ (* rx r) ix) dn)
547 (/ (- (* ix r) rx) dn))))))
548 (((foreach integer ratio single-float double-float) complex)
549 (let* ((ry (realpart y))
550 (iy (imagpart y)))
551 (if (> (abs ry) (abs iy))
552 (let* ((r (/ iy ry))
553 (dn (* ry (+ 1 (* r r)))))
554 (canonical-complex (/ x dn)
555 (/ (- (* x r)) dn)))
556 (let* ((r (/ ry iy))
557 (dn (* iy (+ 1 (* r r)))))
558 (canonical-complex (/ (* x r) dn)
559 (/ (- x) dn))))))
560 ((complex (or rational float))
561 (canonical-complex (/ (realpart x) y)
562 (/ (imagpart x) y)))
564 ((ratio ratio)
565 (let* ((nx (numerator x))
566 (dx (denominator x))
567 (ny (numerator y))
568 (dy (denominator y))
569 (g1 (gcd nx ny))
570 (g2 (gcd dx dy)))
571 (build-ratio (* (maybe-truncate nx g1) (maybe-truncate dy g2))
572 (* (maybe-truncate dx g2) (maybe-truncate ny g1)))))
574 ((integer integer)
575 (integer-/-integer x y))
577 ((integer ratio)
578 (if (zerop x)
580 (let* ((ny (numerator y))
581 (dy (denominator y))
582 (gcd (gcd x ny)))
583 (build-ratio (* (maybe-truncate x gcd) dy)
584 (maybe-truncate ny gcd)))))
586 ((ratio integer)
587 (let* ((nx (numerator x))
588 (gcd (gcd nx y)))
589 (build-ratio (maybe-truncate nx gcd)
590 (* (maybe-truncate y gcd) (denominator x)))))))
592 (defun %negate (n)
593 (declare (explicit-check))
594 (number-dispatch ((n number))
595 (((foreach fixnum single-float double-float #!+long-float long-float))
596 (%negate n))
597 ((bignum)
598 (negate-bignum n))
599 ((ratio)
600 (%make-ratio (- (numerator n)) (denominator n)))
601 ((complex)
602 (complex (- (realpart n)) (- (imagpart n))))))
604 ;;;; TRUNCATE and friends
606 (defun truncate (number &optional (divisor 1))
607 #!+sb-doc
608 "Return number (or number/divisor) as an integer, rounded toward 0.
609 The second returned value is the remainder."
610 (declare (explicit-check))
611 (macrolet ((truncate-float (rtype)
612 `(let* ((float-div (coerce divisor ',rtype))
613 (res (%unary-truncate (/ number float-div))))
614 (values res
615 (- number
616 (* (coerce res ',rtype) float-div))))))
617 (number-dispatch ((number real) (divisor real))
618 ((fixnum fixnum) (truncate number divisor))
619 (((foreach fixnum bignum) ratio)
620 (if (= (numerator divisor) 1)
621 (values (* number (denominator divisor)) 0)
622 (multiple-value-bind (quot rem)
623 (truncate (* number (denominator divisor))
624 (numerator divisor))
625 (values quot (/ rem (denominator divisor))))))
626 ((fixnum bignum)
627 (bignum-truncate (make-small-bignum number) divisor))
628 ((ratio (or float rational))
629 (let ((q (truncate (numerator number)
630 (* (denominator number) divisor))))
631 (values q (- number (* q divisor)))))
632 ((bignum fixnum)
633 (bignum-truncate number (make-small-bignum divisor)))
634 ((bignum bignum)
635 (bignum-truncate number divisor))
637 (((foreach single-float double-float #!+long-float long-float)
638 (or rational single-float))
639 (if (eql divisor 1)
640 (let ((res (%unary-truncate number)))
641 (values res (- number (coerce res '(dispatch-type number)))))
642 (truncate-float (dispatch-type number))))
643 #!+long-float
644 ((long-float (or single-float double-float long-float))
645 (truncate-float long-float))
646 #!+long-float
647 (((foreach double-float single-float) long-float)
648 (truncate-float long-float))
649 ((double-float (or single-float double-float))
650 (truncate-float double-float))
651 ((single-float double-float)
652 (truncate-float double-float))
653 (((foreach fixnum bignum ratio)
654 (foreach single-float double-float #!+long-float long-float))
655 (truncate-float (dispatch-type divisor))))))
657 (defun %multiply-high (x y)
658 (declare (type word x y))
659 (%multiply-high x y))
661 (defun floor (number &optional (divisor 1))
662 #!+sb-doc
663 "Return the greatest integer not greater than number, or number/divisor.
664 The second returned value is (mod number divisor)."
665 (declare (explicit-check))
666 (floor number divisor))
668 (defun ceiling (number &optional (divisor 1))
669 #!+sb-doc
670 "Return the smallest integer not less than number, or number/divisor.
671 The second returned value is the remainder."
672 (declare (explicit-check))
673 (ceiling number divisor))
675 (defun rem (number divisor)
676 #!+sb-doc
677 "Return second result of TRUNCATE."
678 (declare (explicit-check))
679 (rem number divisor))
681 (defun mod (number divisor)
682 #!+sb-doc
683 "Return second result of FLOOR."
684 (declare (explicit-check))
685 (mod number divisor))
687 (defun round (number &optional (divisor 1))
688 #!+sb-doc
689 "Rounds number (or number/divisor) to nearest integer.
690 The second returned value is the remainder."
691 (declare (explicit-check))
692 (if (eql divisor 1)
693 (round number)
694 (multiple-value-bind (tru rem) (truncate number divisor)
695 (if (zerop rem)
696 (values tru rem)
697 (let ((thresh (/ (abs divisor) 2)))
698 (cond ((or (> rem thresh)
699 (and (= rem thresh) (oddp tru)))
700 (if (minusp divisor)
701 (values (- tru 1) (+ rem divisor))
702 (values (+ tru 1) (- rem divisor))))
703 ((let ((-thresh (- thresh)))
704 (or (< rem -thresh)
705 (and (= rem -thresh) (oddp tru))))
706 (if (minusp divisor)
707 (values (+ tru 1) (- rem divisor))
708 (values (- tru 1) (+ rem divisor))))
709 (t (values tru rem))))))))
711 (defmacro !define-float-rounding-function (name op doc)
712 `(defun ,name (number &optional (divisor 1))
713 ,doc
714 (multiple-value-bind (res rem) (,op number divisor)
715 (values (float res (if (floatp rem) rem 1.0)) rem))))
717 ;;; Declare these guys inline to let them get optimized a little.
718 ;;; ROUND and FROUND are not declared inline since they seem too
719 ;;; obscure and too big to inline-expand by default. Also, this gives
720 ;;; the compiler a chance to pick off the unary float case.
721 #!-sb-fluid (declaim (inline fceiling ffloor ftruncate))
722 (defun ftruncate (number &optional (divisor 1))
723 #!+sb-doc
724 "Same as TRUNCATE, but returns first value as a float."
725 (declare (explicit-check))
726 (macrolet ((ftruncate-float (rtype)
727 `(let* ((float-div (coerce divisor ',rtype))
728 (res (%unary-ftruncate (/ number float-div))))
729 (values res
730 (- number
731 (* (coerce res ',rtype) float-div))))))
732 (number-dispatch ((number real) (divisor real))
733 (((foreach fixnum bignum ratio) (or fixnum bignum ratio))
734 (multiple-value-bind (q r)
735 (truncate number divisor)
736 (values (float q) r)))
737 (((foreach single-float double-float #!+long-float long-float)
738 (or rational single-float))
739 (if (eql divisor 1)
740 (let ((res (%unary-ftruncate number)))
741 (values res (- number (coerce res '(dispatch-type number)))))
742 (ftruncate-float (dispatch-type number))))
743 #!+long-float
744 ((long-float (or single-float double-float long-float))
745 (ftruncate-float long-float))
746 #!+long-float
747 (((foreach double-float single-float) long-float)
748 (ftruncate-float long-float))
749 ((double-float (or single-float double-float))
750 (ftruncate-float double-float))
751 ((single-float double-float)
752 (ftruncate-float double-float))
753 (((foreach fixnum bignum ratio)
754 (foreach single-float double-float #!+long-float long-float))
755 (ftruncate-float (dispatch-type divisor))))))
757 (defun ffloor (number &optional (divisor 1))
758 #!+sb-doc
759 "Same as FLOOR, but returns first value as a float."
760 (declare (explicit-check))
761 (multiple-value-bind (tru rem) (ftruncate number divisor)
762 (if (and (not (zerop rem))
763 (if (minusp divisor)
764 (plusp number)
765 (minusp number)))
766 (values (1- tru) (+ rem divisor))
767 (values tru rem))))
769 (defun fceiling (number &optional (divisor 1))
770 #!+sb-doc
771 "Same as CEILING, but returns first value as a float."
772 (declare (explicit-check))
773 (multiple-value-bind (tru rem) (ftruncate number divisor)
774 (if (and (not (zerop rem))
775 (if (minusp divisor)
776 (minusp number)
777 (plusp number)))
778 (values (+ tru 1) (- rem divisor))
779 (values tru rem))))
781 ;;; FIXME: this probably needs treatment similar to the use of
782 ;;; %UNARY-FTRUNCATE for FTRUNCATE.
783 (defun fround (number &optional (divisor 1))
784 #!+sb-doc
785 "Same as ROUND, but returns first value as a float."
786 (declare (explicit-check))
787 (multiple-value-bind (res rem)
788 (round number divisor)
789 (values (float res (if (floatp rem) rem 1.0)) rem)))
791 ;;;; comparisons
793 (defun = (number &rest more-numbers)
794 #!+sb-doc
795 "Return T if all of its arguments are numerically equal, NIL otherwise."
796 (declare (number number) (explicit-check))
797 (do-rest-arg ((n i) more-numbers 0 t)
798 (unless (= number n)
799 (return (do-rest-arg ((n) more-numbers (1+ i))
800 (the number n)))))) ; for effect
802 (defun /= (number &rest more-numbers)
803 #!+sb-doc
804 "Return T if no two of its arguments are numerically equal, NIL otherwise."
805 (declare (number number) (explicit-check))
806 (if more-numbers
807 (do ((n number (nth i more-numbers))
808 (i 0 (1+ i)))
809 ((>= i (length more-numbers))
811 (do-rest-arg ((n2) more-numbers i)
812 (when (= n n2)
813 (return-from /= nil))))
816 (macrolet ((def (op doc)
817 (declare (ignorable doc))
818 `(defun ,op (number &rest more-numbers)
819 #!+sb-doc ,doc
820 (declare (explicit-check))
821 (let ((n1 number))
822 (declare (real n1))
823 (do-rest-arg ((n2 i) more-numbers 0 t)
824 (if (,op n1 n2)
825 (setf n1 n2)
826 (return (do-rest-arg ((n) more-numbers (1+ i))
827 (the real n))))))))) ; for effect
828 (def < "Return T if its arguments are in strictly increasing order, NIL otherwise.")
829 (def > "Return T if its arguments are in strictly decreasing order, NIL otherwise.")
830 (def <= "Return T if arguments are in strictly non-decreasing order, NIL otherwise.")
831 (def >= "Return T if arguments are in strictly non-increasing order, NIL otherwise."))
833 (defun max (number &rest more-numbers)
834 #!+sb-doc
835 "Return the greatest of its arguments; among EQUALP greatest, return
836 the first."
837 (declare (explicit-check))
838 (let ((n number))
839 (declare (real n))
840 (do-rest-arg ((arg) more-numbers 0 n)
841 (when (> arg n)
842 (setf n arg)))))
844 (defun min (number &rest more-numbers)
845 #!+sb-doc
846 "Return the least of its arguments; among EQUALP least, return
847 the first."
848 (declare (explicit-check))
849 (let ((n number))
850 (declare (real n))
851 (do-rest-arg ((arg) more-numbers 0 n)
852 (when (< arg n)
853 (setf n arg)))))
855 (defmacro make-fixnum-float-comparer (operation integer float float-type)
856 (multiple-value-bind (min max)
857 (ecase float-type
858 (single-float
859 (values most-negative-fixnum-single-float most-positive-fixnum-single-float))
860 (double-float
861 (values most-negative-fixnum-double-float most-positive-fixnum-double-float)))
862 ` (cond ((> ,float ,max)
863 ,(ecase operation
864 ((= >) nil)
865 (< t)))
866 ((< ,float ,min)
867 ,(ecase operation
868 ((= <) nil)
869 (> t)))
871 (let ((quot (%unary-truncate ,float)))
872 ,(ecase operation
874 `(and (= quot ,integer)
875 (= (float quot ,float) ,float)))
877 `(cond ((> ,integer quot))
878 ((< ,integer quot)
879 nil)
880 ((<= ,integer 0)
881 (> (float quot ,float) ,float))))
883 `(cond ((< ,integer quot))
884 ((> ,integer quot)
885 nil)
886 ((>= ,integer 0)
887 (< (float quot ,float) ,float))))))))))
889 (eval-when (:compile-toplevel :execute)
890 ;;; The INFINITE-X-FINITE-Y and INFINITE-Y-FINITE-X args tell us how
891 ;;; to handle the case when X or Y is a floating-point infinity and
892 ;;; the other arg is a rational. (Section 12.1.4.1 of the ANSI spec
893 ;;; says that comparisons are done by converting the float to a
894 ;;; rational when comparing with a rational, but infinities can't be
895 ;;; converted to a rational, so we show some initiative and do it this
896 ;;; way instead.)
897 (defun basic-compare (op &key infinite-x-finite-y infinite-y-finite-x)
898 `(((fixnum fixnum) (,op x y))
899 ((single-float single-float) (,op x y))
900 #!+long-float
901 (((foreach single-float double-float long-float) long-float)
902 (,op (coerce x 'long-float) y))
903 #!+long-float
904 ((long-float (foreach single-float double-float))
905 (,op x (coerce y 'long-float)))
906 ((fixnum (foreach single-float double-float))
907 (if (float-infinity-p y)
908 ,infinite-y-finite-x
909 (make-fixnum-float-comparer ,op x y (dispatch-type y))))
910 (((foreach single-float double-float) fixnum)
911 (if (eql y 0)
912 (,op x (coerce 0 '(dispatch-type x)))
913 (if (float-infinity-p x)
914 ,infinite-x-finite-y
915 ;; Likewise
916 (make-fixnum-float-comparer ,(case op
917 (> '<)
918 (< '>)
919 (= '=))
920 y x (dispatch-type x)))))
921 (((foreach single-float double-float) double-float)
922 (,op (coerce x 'double-float) y))
923 ((double-float single-float)
924 (,op x (coerce y 'double-float)))
925 (((foreach single-float double-float #!+long-float long-float) rational)
926 (if (eql y 0)
927 (,op x (coerce 0 '(dispatch-type x)))
928 (if (float-infinity-p x)
929 ,infinite-x-finite-y
930 (,op (rational x) y))))
931 (((foreach bignum fixnum ratio) float)
932 (if (float-infinity-p y)
933 ,infinite-y-finite-x
934 (,op x (rational y))))))
935 ) ; EVAL-WHEN
938 (macrolet ((def-two-arg-</> (name op ratio-arg1 ratio-arg2 &rest cases)
939 `(defun ,name (x y)
940 (number-dispatch ((x real) (y real))
941 (basic-compare
943 :infinite-x-finite-y
944 (,op x (coerce 0 '(dispatch-type x)))
945 :infinite-y-finite-x
946 (,op (coerce 0 '(dispatch-type y)) y))
947 (((foreach fixnum bignum) ratio)
948 (,op x (,ratio-arg2 (numerator y)
949 (denominator y))))
950 ((ratio integer)
951 (,op (,ratio-arg1 (numerator x)
952 (denominator x))
954 ((ratio ratio)
955 (,op (* (numerator (truly-the ratio x))
956 (denominator (truly-the ratio y)))
957 (* (numerator (truly-the ratio y))
958 (denominator (truly-the ratio x)))))
959 ,@cases))))
960 (def-two-arg-</> two-arg-< < floor ceiling
961 ((fixnum bignum)
962 (bignum-plus-p y))
963 ((bignum fixnum)
964 (not (bignum-plus-p x)))
965 ((bignum bignum)
966 (minusp (bignum-compare x y))))
967 (def-two-arg-</> two-arg-> > ceiling floor
968 ((fixnum bignum)
969 (not (bignum-plus-p y)))
970 ((bignum fixnum)
971 (bignum-plus-p x))
972 ((bignum bignum)
973 (plusp (bignum-compare x y)))))
975 (defun two-arg-= (x y)
976 (number-dispatch ((x number) (y number))
977 (basic-compare =
978 ;; An infinite value is never equal to a finite value.
979 :infinite-x-finite-y nil
980 :infinite-y-finite-x nil)
981 ((fixnum (or bignum ratio)) nil)
983 ((bignum (or fixnum ratio)) nil)
984 ((bignum bignum)
985 (zerop (bignum-compare x y)))
987 ((ratio integer) nil)
988 ((ratio ratio)
989 (and (eql (numerator x) (numerator y))
990 (eql (denominator x) (denominator y))))
992 ((complex complex)
993 (and (= (realpart x) (realpart y))
994 (= (imagpart x) (imagpart y))))
995 (((foreach fixnum bignum ratio single-float double-float
996 #!+long-float long-float) complex)
997 (and (= x (realpart y))
998 (zerop (imagpart y))))
999 ((complex (or float rational))
1000 (and (= (realpart x) y)
1001 (zerop (imagpart x))))))
1003 ;;;; logicals
1005 (macrolet ((def (op init doc)
1006 #!-sb-doc (declare (ignore doc))
1007 `(defun ,op (&rest integers)
1008 #!+sb-doc ,doc
1009 (declare (explicit-check))
1010 (if integers
1011 (do ((result (fast-&rest-nth 0 integers)
1012 (,op result (fast-&rest-nth i integers)))
1013 (i 1 (1+ i)))
1014 ((>= i (length integers))
1015 result)
1016 (declare (integer result)))
1017 ,init))))
1018 (def logior 0 "Return the bit-wise or of its arguments. Args must be integers.")
1019 (def logxor 0 "Return the bit-wise exclusive or of its arguments. Args must be integers.")
1020 (def logand -1 "Return the bit-wise and of its arguments. Args must be integers.")
1021 (def logeqv -1 "Return the bit-wise equivalence of its arguments. Args must be integers."))
1023 (defun lognot (number)
1024 #!+sb-doc
1025 "Return the bit-wise logical not of integer."
1026 (declare (explicit-check))
1027 (etypecase number
1028 (fixnum (lognot (truly-the fixnum number)))
1029 (bignum (bignum-logical-not number))))
1031 (macrolet ((def (name explicit-check op big-op &optional doc)
1032 `(defun ,name (integer1 integer2)
1033 ,@(when doc (list doc))
1034 ,@(when explicit-check `((declare (explicit-check))))
1035 (let ((x integer1)
1036 (y integer2))
1037 (number-dispatch ((x integer) (y integer))
1038 (bignum-cross-fixnum ,op ,big-op))))))
1039 (def two-arg-and nil logand bignum-logical-and)
1040 (def two-arg-ior nil logior bignum-logical-ior)
1041 (def two-arg-xor nil logxor bignum-logical-xor)
1042 ;; BIGNUM-LOGICAL-{AND,IOR,XOR} need not return a bignum, so must
1043 ;; call the generic LOGNOT...
1044 (def two-arg-eqv nil logeqv (lambda (x y) (lognot (bignum-logical-xor x y))))
1045 (def lognand t lognand
1046 (lambda (x y) (lognot (bignum-logical-and x y)))
1047 #!+sb-doc "Complement the logical AND of INTEGER1 and INTEGER2.")
1048 (def lognor t lognor
1049 (lambda (x y) (lognot (bignum-logical-ior x y)))
1050 #!+sb-doc "Complement the logical OR of INTEGER1 and INTEGER2.")
1051 ;; ... but BIGNUM-LOGICAL-NOT on a bignum will always return a bignum
1052 (def logandc1 t logandc1
1053 (lambda (x y) (bignum-logical-and (bignum-logical-not x) y))
1054 #!+sb-doc "Bitwise AND (LOGNOT INTEGER1) with INTEGER2.")
1055 (def logandc2 t logandc2
1056 (lambda (x y) (bignum-logical-and x (bignum-logical-not y)))
1057 #!+sb-doc "Bitwise AND INTEGER1 with (LOGNOT INTEGER2).")
1058 (def logorc1 t logorc1
1059 (lambda (x y) (bignum-logical-ior (bignum-logical-not x) y))
1060 #!+sb-doc "Bitwise OR (LOGNOT INTEGER1) with INTEGER2.")
1061 (def logorc2 t logorc2
1062 (lambda (x y) (bignum-logical-ior x (bignum-logical-not y)))
1063 #!+sb-doc "Bitwise OR INTEGER1 with (LOGNOT INTEGER2)."))
1065 (defun logcount (integer)
1066 #!+sb-doc
1067 "Count the number of 1 bits if INTEGER is non-negative,
1068 and the number of 0 bits if INTEGER is negative."
1069 (declare (explicit-check))
1070 (etypecase integer
1071 (fixnum
1072 (logcount (truly-the (integer 0
1073 #.(max sb!xc:most-positive-fixnum
1074 (lognot sb!xc:most-negative-fixnum)))
1075 (if (minusp (truly-the fixnum integer))
1076 (lognot (truly-the fixnum integer))
1077 integer))))
1078 (bignum
1079 (bignum-logcount integer))))
1081 (defun logtest (integer1 integer2)
1082 #!+sb-doc
1083 "Predicate which returns T if logand of integer1 and integer2 is not zero."
1084 (logtest integer1 integer2))
1086 (defun logbitp (index integer)
1087 #!+sb-doc
1088 "Predicate returns T if bit index of integer is a 1."
1089 (number-dispatch ((index integer) (integer integer))
1090 ((fixnum fixnum) (if (< index sb!vm:n-positive-fixnum-bits)
1091 (not (zerop (logand integer (ash 1 index))))
1092 (minusp integer)))
1093 ((fixnum bignum) (bignum-logbitp index integer))
1094 ((bignum (foreach fixnum bignum)) (minusp integer))))
1096 (defun ash (integer count)
1097 #!+sb-doc
1098 "Shifts integer left by count places preserving sign. - count shifts right."
1099 (declare (integer integer count) (explicit-check))
1100 (etypecase integer
1101 (fixnum
1102 (cond ((zerop integer)
1104 ((fixnump count)
1105 (let ((length (integer-length (truly-the fixnum integer)))
1106 (count (truly-the fixnum count)))
1107 (declare (fixnum length count))
1108 (cond ((and (plusp count)
1109 (>= (+ length count)
1110 sb!vm:n-word-bits))
1111 (bignum-ashift-left-fixnum integer count))
1113 (truly-the (signed-byte #.sb!vm:n-word-bits)
1114 (ash (truly-the fixnum integer) count))))))
1115 ((minusp count)
1116 (if (minusp integer) -1 0))
1118 (bignum-ashift-left (make-small-bignum integer) count))))
1119 (bignum
1120 (if (plusp count)
1121 (bignum-ashift-left integer count)
1122 (bignum-ashift-right integer (- count))))))
1124 (defun integer-length (integer)
1125 #!+sb-doc
1126 "Return the number of non-sign bits in the twos-complement representation
1127 of INTEGER."
1128 (declare (explicit-check))
1129 (etypecase integer
1130 (fixnum
1131 (integer-length (truly-the fixnum integer)))
1132 (bignum
1133 (bignum-integer-length integer))))
1135 ;;;; BYTE, bytespecs, and related operations
1137 (defun byte (size position)
1138 #!+sb-doc
1139 "Return a byte specifier which may be used by other byte functions
1140 (e.g. LDB)."
1141 (byte size position))
1143 (defun byte-size (bytespec)
1144 #!+sb-doc
1145 "Return the size part of the byte specifier bytespec."
1146 (byte-size bytespec))
1148 (defun byte-position (bytespec)
1149 #!+sb-doc
1150 "Return the position part of the byte specifier bytespec."
1151 (byte-position bytespec))
1153 (defun ldb (bytespec integer)
1154 #!+sb-doc
1155 "Extract the specified byte from integer, and right justify result."
1156 (ldb bytespec integer))
1158 (defun ldb-test (bytespec integer)
1159 #!+sb-doc
1160 "Return T if any of the specified bits in integer are 1's."
1161 (ldb-test bytespec integer))
1163 (defun mask-field (bytespec integer)
1164 #!+sb-doc
1165 "Extract the specified byte from integer, but do not right justify result."
1166 (mask-field bytespec integer))
1168 (defun dpb (newbyte bytespec integer)
1169 #!+sb-doc
1170 "Return new integer with newbyte in specified position, newbyte is right justified."
1171 (dpb newbyte bytespec integer))
1173 (defun deposit-field (newbyte bytespec integer)
1174 #!+sb-doc
1175 "Return new integer with newbyte in specified position, newbyte is not right justified."
1176 (deposit-field newbyte bytespec integer))
1178 (defun %ldb (size posn integer)
1179 (declare (type bit-index size posn) (explicit-check))
1180 ;; The naive algorithm is horrible in the general case.
1181 ;; Consider (LDB (BYTE 1 2) (SOME-GIANT-BIGNUM)) which has to shift the
1182 ;; input rightward 2 bits, consing a new bignum just to read 1 bit.
1183 (if (and (<= 0 size sb!vm:n-positive-fixnum-bits)
1184 (typep integer 'bignum))
1185 (sb!bignum::ldb-bignum=>fixnum size posn integer)
1186 (logand (ash integer (- posn))
1187 (1- (ash 1 size)))))
1189 (defun %mask-field (size posn integer)
1190 (declare (type bit-index size posn) (explicit-check))
1191 (logand integer (ash (1- (ash 1 size)) posn)))
1193 (defun %dpb (newbyte size posn integer)
1194 (declare (type bit-index size posn) (explicit-check))
1195 (let ((mask (1- (ash 1 size))))
1196 (logior (logand integer (lognot (ash mask posn)))
1197 (ash (logand newbyte mask) posn))))
1199 (defun %deposit-field (newbyte size posn integer)
1200 (declare (type bit-index size posn) (explicit-check))
1201 (let ((mask (ash (ldb (byte size 0) -1) posn)))
1202 (logior (logand newbyte mask)
1203 (logand integer (lognot mask)))))
1205 (defun sb!c::mask-signed-field (size integer)
1206 #!+sb-doc
1207 "Extract SIZE lower bits from INTEGER, considering them as a
1208 2-complement SIZE-bits representation of a signed integer."
1209 (macrolet ((msf (size integer)
1210 `(if (logbitp (1- ,size) ,integer)
1211 (dpb ,integer (byte (1- ,size) 0) -1)
1212 (ldb (byte (1- ,size) 0) ,integer))))
1213 (typecase size
1214 ((eql 0) 0)
1215 ((integer 1 #.sb!vm:n-fixnum-bits)
1216 (number-dispatch ((integer integer))
1217 ((fixnum) (msf size integer))
1218 ((bignum) (let ((fix (sb!c::mask-signed-field #.sb!vm:n-fixnum-bits (%bignum-ref integer 0))))
1219 (if (= size #.sb!vm:n-fixnum-bits)
1221 (msf size fix))))))
1222 ((integer (#.sb!vm:n-fixnum-bits) #.sb!vm:n-word-bits)
1223 (number-dispatch ((integer integer))
1224 ((fixnum) integer)
1225 ((bignum) (let ((word (sb!c::mask-signed-field #.sb!vm:n-word-bits (%bignum-ref integer 0))))
1226 (if (= size #.sb!vm:n-word-bits)
1227 word
1228 (msf size word))))))
1229 ((unsigned-byte) (msf size integer)))))
1231 ;;;; BOOLE
1233 (defun boole (op integer1 integer2)
1234 #!+sb-doc
1235 "Bit-wise boolean function on two integers. Function chosen by OP:
1236 0 BOOLE-CLR
1237 1 BOOLE-SET
1238 2 BOOLE-1
1239 3 BOOLE-2
1240 4 BOOLE-C1
1241 5 BOOLE-C2
1242 6 BOOLE-AND
1243 7 BOOLE-IOR
1244 8 BOOLE-XOR
1245 9 BOOLE-EQV
1246 10 BOOLE-NAND
1247 11 BOOLE-NOR
1248 12 BOOLE-ANDC1
1249 13 BOOLE-ANDC2
1250 14 BOOLE-ORC1
1251 15 BOOLE-ORC2"
1252 (case op
1253 (0 (boole 0 integer1 integer2))
1254 (1 (boole 1 integer1 integer2))
1255 (2 (boole 2 integer1 integer2))
1256 (3 (boole 3 integer1 integer2))
1257 (4 (boole 4 integer1 integer2))
1258 (5 (boole 5 integer1 integer2))
1259 (6 (boole 6 integer1 integer2))
1260 (7 (boole 7 integer1 integer2))
1261 (8 (boole 8 integer1 integer2))
1262 (9 (boole 9 integer1 integer2))
1263 (10 (boole 10 integer1 integer2))
1264 (11 (boole 11 integer1 integer2))
1265 (12 (boole 12 integer1 integer2))
1266 (13 (boole 13 integer1 integer2))
1267 (14 (boole 14 integer1 integer2))
1268 (15 (boole 15 integer1 integer2))
1269 (t (error 'type-error :datum op :expected-type '(mod 16)))))
1271 ;;;; GCD and LCM
1273 (defun gcd (&rest integers)
1274 #!+sb-doc
1275 "Return the greatest common divisor of the arguments, which must be
1276 integers. GCD with no arguments is defined to be 0."
1277 (declare (explicit-check))
1278 (case (length integers)
1279 (0 0)
1280 (1 (abs (the integer (fast-&rest-nth 0 integers))))
1281 (otherwise
1282 (do ((result (fast-&rest-nth 0 integers)
1283 (gcd result (the integer (fast-&rest-nth i integers))))
1284 (i 1 (1+ i)))
1285 ((>= i (length integers))
1286 result)
1287 (declare (integer result))))))
1289 (defun lcm (&rest integers)
1290 #!+sb-doc
1291 "Return the least common multiple of one or more integers. LCM of no
1292 arguments is defined to be 1."
1293 (declare (explicit-check))
1294 (case (length integers)
1295 (0 1)
1296 (1 (abs (the integer (fast-&rest-nth 0 integers))))
1297 (otherwise
1298 (do ((result (fast-&rest-nth 0 integers)
1299 (lcm result (the integer (fast-&rest-nth i integers))))
1300 (i 1 (1+ i)))
1301 ((>= i (length integers))
1302 result)
1303 (declare (integer result))))))
1305 (defun two-arg-lcm (n m)
1306 (declare (integer n m))
1307 (if (or (zerop n) (zerop m))
1309 ;; KLUDGE: I'm going to assume that it was written this way
1310 ;; originally for a reason. However, this is a somewhat
1311 ;; complicated way of writing the algorithm in the CLHS page for
1312 ;; LCM, and I don't know why. To be investigated. -- CSR,
1313 ;; 2003-09-11
1315 ;; It seems to me that this is written this way to avoid
1316 ;; unnecessary bignumification of intermediate results.
1317 ;; -- TCR, 2008-03-05
1318 (let ((m (abs m))
1319 (n (abs n)))
1320 (multiple-value-bind (max min)
1321 (if (> m n)
1322 (values m n)
1323 (values n m))
1324 (* (truncate max (gcd n m)) min)))))
1326 ;;; Do the GCD of two integer arguments. With fixnum arguments, we use the
1327 ;;; binary GCD algorithm from Knuth's seminumerical algorithms (slightly
1328 ;;; structurified), otherwise we call BIGNUM-GCD. We pick off the special case
1329 ;;; of 0 before the dispatch so that the bignum code doesn't have to worry
1330 ;;; about "small bignum" zeros.
1331 (defun two-arg-gcd (u v)
1332 (cond ((eql u 0) (abs v))
1333 ((eql v 0) (abs u))
1335 (number-dispatch ((u integer) (v integer))
1336 ((fixnum fixnum)
1337 (locally
1338 (declare (optimize (speed 3) (safety 0)))
1339 (do ((k 0 (1+ k))
1340 (u (abs u) (ash u -1))
1341 (v (abs v) (ash v -1)))
1342 ((oddp (logior u v))
1343 (do ((temp (if (oddp u) (- v) (ash u -1))
1344 (ash temp -1)))
1345 (nil)
1346 (declare (fixnum temp))
1347 (when (oddp temp)
1348 (if (plusp temp)
1349 (setq u temp)
1350 (setq v (- temp)))
1351 (setq temp (- u v))
1352 (when (zerop temp)
1353 (let ((res (ash u k)))
1354 (declare (type sb!vm:signed-word res)
1355 (optimize (inhibit-warnings 3)))
1356 (return res))))))
1357 (declare (type (mod #.sb!vm:n-word-bits) k)
1358 (type sb!vm:signed-word u v)))))
1359 ((bignum bignum)
1360 (bignum-gcd u v))
1361 ((bignum fixnum)
1362 (bignum-gcd u (make-small-bignum v)))
1363 ((fixnum bignum)
1364 (bignum-gcd (make-small-bignum u) v))))))
1366 ;;; from Robert Smith; changed not to cons unnecessarily, and tuned for
1367 ;;; faster operation on fixnum inputs by compiling the central recursive
1368 ;;; algorithm twice, once using generic and once fixnum arithmetic, and
1369 ;;; dispatching on function entry into the applicable part. For maximum
1370 ;;; speed, the fixnum part recurs into itself, thereby avoiding further
1371 ;;; type dispatching. This pattern is not supported by NUMBER-DISPATCH
1372 ;;; thus some special-purpose macrology is needed.
1373 (defun isqrt (n)
1374 #!+sb-doc
1375 "Return the greatest integer less than or equal to the square root of N."
1376 (declare (type unsigned-byte n) (explicit-check))
1377 (macrolet
1378 ((isqrt-recursion (arg recurse fixnum-p)
1379 ;; Expands into code for the recursive step of the ISQRT
1380 ;; calculation. ARG is the input variable and RECURSE the name
1381 ;; of the function to recur into. If FIXNUM-P is true, some
1382 ;; type declarations are added that, together with ARG being
1383 ;; declared as a fixnum outside of here, make the resulting code
1384 ;; compile into fixnum-specialized code without any calls to
1385 ;; generic arithmetic. Else, the code works for bignums, too.
1386 ;; The input must be at least 16 to ensure that RECURSE is called
1387 ;; with a strictly smaller number and that the result is correct
1388 ;; (provided that RECURSE correctly implements ISQRT, itself).
1389 `(macrolet ((if-fixnum-p-truly-the (type expr)
1390 ,@(if fixnum-p
1391 '(`(truly-the ,type ,expr))
1392 '((declare (ignore type))
1393 expr))))
1394 (let* ((fourth-size (ash (1- (integer-length ,arg)) -2))
1395 (significant-half (ash ,arg (- (ash fourth-size 1))))
1396 (significant-half-isqrt
1397 (if-fixnum-p-truly-the
1398 (integer 1 #.(isqrt sb!xc:most-positive-fixnum))
1399 (,recurse significant-half)))
1400 (zeroth-iteration (ash significant-half-isqrt
1401 fourth-size)))
1402 (multiple-value-bind (quot rem)
1403 (floor ,arg zeroth-iteration)
1404 (let ((first-iteration (ash (+ zeroth-iteration quot) -1)))
1405 (cond ((oddp quot)
1406 first-iteration)
1407 ((> (if-fixnum-p-truly-the
1408 fixnum
1409 (expt (- first-iteration zeroth-iteration) 2))
1410 rem)
1411 (1- first-iteration))
1413 first-iteration))))))))
1414 (typecase n
1415 (fixnum (labels ((fixnum-isqrt (n)
1416 (declare (type fixnum n))
1417 (cond ((> n 24)
1418 (isqrt-recursion n fixnum-isqrt t))
1419 ((> n 15) 4)
1420 ((> n 8) 3)
1421 ((> n 3) 2)
1422 ((> n 0) 1)
1423 ((= n 0) 0))))
1424 (fixnum-isqrt n)))
1425 (bignum (isqrt-recursion n isqrt nil)))))
1427 ;;;; miscellaneous number predicates
1429 (macrolet ((def (name doc)
1430 (declare (ignorable doc))
1431 `(defun ,name (number) #!+sb-doc ,doc
1432 (declare (explicit-check))
1433 (,name number))))
1434 (def zerop "Is this number zero?")
1435 (def plusp "Is this real number strictly positive?")
1436 (def minusp "Is this real number strictly negative?")
1437 (def oddp "Is this integer odd?")
1438 (def evenp "Is this integer even?"))
1440 ;;;; modular functions
1442 (collect ((forms))
1443 (flet ((unsigned-definition (name lambda-list width)
1444 (let ((pattern (1- (ash 1 width))))
1445 `(defun ,name ,(copy-list lambda-list)
1446 (flet ((prepare-argument (x)
1447 (declare (integer x))
1448 (etypecase x
1449 ((unsigned-byte ,width) x)
1450 (fixnum (logand x ,pattern))
1451 (bignum (logand x ,pattern)))))
1452 (,name ,@(loop for arg in lambda-list
1453 collect `(prepare-argument ,arg)))))))
1454 (signed-definition (name lambda-list width)
1455 `(defun ,name ,(copy-list lambda-list)
1456 (flet ((prepare-argument (x)
1457 (declare (integer x))
1458 (etypecase x
1459 ((signed-byte ,width) x)
1460 (fixnum (sb!c::mask-signed-field ,width x))
1461 (bignum (sb!c::mask-signed-field ,width x)))))
1462 (,name ,@(loop for arg in lambda-list
1463 collect `(prepare-argument ,arg)))))))
1464 (flet ((do-mfuns (class)
1465 (loop for infos being each hash-value of (sb!c::modular-class-funs class)
1466 ;; FIXME: We need to process only "toplevel" functions
1467 when (listp infos)
1468 do (loop for info in infos
1469 for name = (sb!c::modular-fun-info-name info)
1470 and width = (sb!c::modular-fun-info-width info)
1471 and signedp = (sb!c::modular-fun-info-signedp info)
1472 and lambda-list = (sb!c::modular-fun-info-lambda-list info)
1473 if signedp
1474 do (forms (signed-definition name lambda-list width))
1475 else
1476 do (forms (unsigned-definition name lambda-list width))))))
1477 (do-mfuns sb!c::*untagged-unsigned-modular-class*)
1478 (do-mfuns sb!c::*untagged-signed-modular-class*)
1479 (do-mfuns sb!c::*tagged-modular-class*)))
1480 `(progn ,@(sort (forms) #'string< :key #'cadr)))
1482 ;;; KLUDGE: these out-of-line definitions can't use the modular
1483 ;;; arithmetic, as that is only (currently) defined for constant
1484 ;;; shifts. See also the comment in (LOGAND OPTIMIZER) for more
1485 ;;; discussion of this hack. -- CSR, 2003-10-09
1486 #!-64-bit-registers
1487 (defun sb!vm::ash-left-mod32 (integer amount)
1488 (etypecase integer
1489 ((unsigned-byte 32) (ldb (byte 32 0) (ash integer amount)))
1490 (fixnum (ldb (byte 32 0) (ash (logand integer #xffffffff) amount)))
1491 (bignum (ldb (byte 32 0) (ash (logand integer #xffffffff) amount)))))
1492 #!+64-bit-registers
1493 (defun sb!vm::ash-left-mod64 (integer amount)
1494 (etypecase integer
1495 ((unsigned-byte 64) (ldb (byte 64 0) (ash integer amount)))
1496 (fixnum (ldb (byte 64 0) (ash (logand integer #xffffffffffffffff) amount)))
1497 (bignum (ldb (byte 64 0)
1498 (ash (logand integer #xffffffffffffffff) amount)))))
1500 #!+(or x86 x86-64 arm arm64)
1501 (defun sb!vm::ash-left-modfx (integer amount)
1502 (let ((fixnum-width (- sb!vm:n-word-bits sb!vm:n-fixnum-tag-bits)))
1503 (etypecase integer
1504 (fixnum (sb!c::mask-signed-field fixnum-width (ash integer amount)))
1505 (integer (sb!c::mask-signed-field fixnum-width (ash (sb!c::mask-signed-field fixnum-width integer) amount))))))