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