1 ;;;; This file contains macro-like source transformations which
2 ;;;; convert uses of certain functions into the canonical form desired
3 ;;;; within the compiler. FIXME: and other IR1 transforms and stuff.
5 ;;;; This software is part of the SBCL system. See the README file for
8 ;;;; This software is derived from the CMU CL system, which was
9 ;;;; written at Carnegie Mellon University and released into the
10 ;;;; public domain. The software is in the public domain and is
11 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
12 ;;;; files for more information.
16 ;;; Convert into an IF so that IF optimizations will eliminate redundant
18 (define-source-transform not (x) `(if ,x nil t))
19 (define-source-transform null (x) `(if ,x nil t))
21 ;;; ENDP is just NULL with a LIST assertion. The assertion will be
22 ;;; optimized away when SAFETY optimization is low; hopefully that
23 ;;; is consistent with ANSI's "should return an error".
24 (define-source-transform endp (x) `(null (the list ,x)))
26 ;;; We turn IDENTITY into PROG1 so that it is obvious that it just
27 ;;; returns the first value of its argument. Ditto for VALUES with one
29 (define-source-transform identity (x) `(prog1 ,x))
30 (define-source-transform values (x) `(prog1 ,x))
32 ;;; Bind the value and make a closure that returns it.
33 (define-source-transform constantly (value)
34 (with-unique-names (rest n-value)
35 `(let ((,n-value ,value))
37 (declare (ignore ,rest))
40 ;;; If the function has a known number of arguments, then return a
41 ;;; lambda with the appropriate fixed number of args. If the
42 ;;; destination is a FUNCALL, then do the &REST APPLY thing, and let
43 ;;; MV optimization figure things out.
44 (deftransform complement ((fun) * * :node node)
46 (multiple-value-bind (min max)
47 (fun-type-nargs (lvar-type fun))
49 ((and min (eql min max))
50 (let ((dums (make-gensym-list min)))
51 `#'(lambda ,dums (not (funcall fun ,@dums)))))
52 ((awhen (node-lvar node)
53 (let ((dest (lvar-dest it)))
54 (and (combination-p dest)
55 (eq (combination-fun dest) it))))
56 '#'(lambda (&rest args)
57 (not (apply fun args))))
59 (give-up-ir1-transform
60 "The function doesn't have a fixed argument count.")))))
64 ;;; Translate CxR into CAR/CDR combos.
65 (defun source-transform-cxr (form)
66 (if (/= (length form) 2)
68 (let* ((name (car form))
72 (leaf (leaf-source-name name))))))
73 (do ((i (- (length string) 2) (1- i))
75 `(,(ecase (char string i)
81 ;;; Make source transforms to turn CxR forms into combinations of CAR
82 ;;; and CDR. ANSI specifies that everything up to 4 A/D operations is
84 (/show0 "about to set CxR source transforms")
85 (loop for i of-type index from 2 upto 4 do
86 ;; Iterate over BUF = all names CxR where x = an I-element
87 ;; string of #\A or #\D characters.
88 (let ((buf (make-string (+ 2 i))))
89 (setf (aref buf 0) #\C
90 (aref buf (1+ i)) #\R)
91 (dotimes (j (ash 2 i))
92 (declare (type index j))
94 (declare (type index k))
95 (setf (aref buf (1+ k))
96 (if (logbitp k j) #\A #\D)))
97 (setf (info :function :source-transform (intern buf))
98 #'source-transform-cxr))))
99 (/show0 "done setting CxR source transforms")
101 ;;; Turn FIRST..FOURTH and REST into the obvious synonym, assuming
102 ;;; whatever is right for them is right for us. FIFTH..TENTH turn into
103 ;;; Nth, which can be expanded into a CAR/CDR later on if policy
105 (define-source-transform first (x) `(car ,x))
106 (define-source-transform rest (x) `(cdr ,x))
107 (define-source-transform second (x) `(cadr ,x))
108 (define-source-transform third (x) `(caddr ,x))
109 (define-source-transform fourth (x) `(cadddr ,x))
110 (define-source-transform fifth (x) `(nth 4 ,x))
111 (define-source-transform sixth (x) `(nth 5 ,x))
112 (define-source-transform seventh (x) `(nth 6 ,x))
113 (define-source-transform eighth (x) `(nth 7 ,x))
114 (define-source-transform ninth (x) `(nth 8 ,x))
115 (define-source-transform tenth (x) `(nth 9 ,x))
117 ;;; LIST with one arg is an extremely common operation (at least inside
118 ;;; SBCL itself); translate it to CONS to take advantage of common
119 ;;; allocation routines.
120 (define-source-transform list (&rest args)
122 (1 `(cons ,(first args) nil))
125 ;;; And similarly for LIST*.
126 (define-source-transform list* (arg &rest others)
127 (cond ((not others) arg)
128 ((not (cdr others)) `(cons ,arg ,(car others)))
131 (defoptimizer (list* derive-type) ((arg &rest args))
133 (specifier-type 'cons)
136 ;;; Translate RPLACx to LET and SETF.
137 (define-source-transform rplaca (x y)
142 (define-source-transform rplacd (x y)
148 (define-source-transform nth (n l) `(car (nthcdr ,n ,l)))
150 (deftransform last ((list &optional n) (t &optional t))
151 (let ((c (constant-lvar-p n)))
153 (and c (eql 1 (lvar-value n))))
155 ((and c (eql 0 (lvar-value n)))
158 (let ((type (lvar-type n)))
159 (cond ((csubtypep type (specifier-type 'fixnum))
160 '(%lastn/fixnum list n))
161 ((csubtypep type (specifier-type 'bignum))
162 '(%lastn/bignum list n))
164 (give-up-ir1-transform "second argument type too vague"))))))))
166 (define-source-transform gethash (&rest args)
168 (2 `(sb!impl::gethash3 ,@args nil))
169 (3 `(sb!impl::gethash3 ,@args))
171 (define-source-transform get (&rest args)
173 (2 `(sb!impl::get2 ,@args))
174 (3 `(sb!impl::get3 ,@args))
177 (defvar *default-nthcdr-open-code-limit* 6)
178 (defvar *extreme-nthcdr-open-code-limit* 20)
180 (deftransform nthcdr ((n l) (unsigned-byte t) * :node node)
181 "convert NTHCDR to CAxxR"
182 (unless (constant-lvar-p n)
183 (give-up-ir1-transform))
184 (let ((n (lvar-value n)))
186 (if (policy node (and (= speed 3) (= space 0)))
187 *extreme-nthcdr-open-code-limit*
188 *default-nthcdr-open-code-limit*))
189 (give-up-ir1-transform))
194 `(cdr ,(frob (1- n))))))
197 ;;;; arithmetic and numerology
199 (define-source-transform plusp (x) `(> ,x 0))
200 (define-source-transform minusp (x) `(< ,x 0))
201 (define-source-transform zerop (x) `(= ,x 0))
203 (define-source-transform 1+ (x) `(+ ,x 1))
204 (define-source-transform 1- (x) `(- ,x 1))
206 (define-source-transform oddp (x) `(logtest ,x 1))
207 (define-source-transform evenp (x) `(not (logtest ,x 1)))
209 ;;; Note that all the integer division functions are available for
210 ;;; inline expansion.
212 (macrolet ((deffrob (fun)
213 `(define-source-transform ,fun (x &optional (y nil y-p))
220 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
222 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
225 ;;; This used to be a source transform (hence the lack of restrictions
226 ;;; on the argument types), but we make it a regular transform so that
227 ;;; the VM has a chance to see the bare LOGTEST and potentiall choose
228 ;;; to implement it differently. --njf, 06-02-2006
229 (deftransform logtest ((x y) * *)
230 `(not (zerop (logand x y))))
232 (deftransform logbitp
233 ((index integer) (unsigned-byte (or (signed-byte #.sb!vm:n-word-bits)
234 (unsigned-byte #.sb!vm:n-word-bits))))
235 `(if (>= index #.sb!vm:n-word-bits)
237 (not (zerop (logand integer (ash 1 index))))))
239 (define-source-transform byte (size position)
240 `(cons ,size ,position))
241 (define-source-transform byte-size (spec) `(car ,spec))
242 (define-source-transform byte-position (spec) `(cdr ,spec))
243 (define-source-transform ldb-test (bytespec integer)
244 `(not (zerop (mask-field ,bytespec ,integer))))
246 ;;; With the ratio and complex accessors, we pick off the "identity"
247 ;;; case, and use a primitive to handle the cell access case.
248 (define-source-transform numerator (num)
249 (once-only ((n-num `(the rational ,num)))
253 (define-source-transform denominator (num)
254 (once-only ((n-num `(the rational ,num)))
256 (%denominator ,n-num)
259 ;;;; interval arithmetic for computing bounds
261 ;;;; This is a set of routines for operating on intervals. It
262 ;;;; implements a simple interval arithmetic package. Although SBCL
263 ;;;; has an interval type in NUMERIC-TYPE, we choose to use our own
264 ;;;; for two reasons:
266 ;;;; 1. This package is simpler than NUMERIC-TYPE.
268 ;;;; 2. It makes debugging much easier because you can just strip
269 ;;;; out these routines and test them independently of SBCL. (This is a
272 ;;;; One disadvantage is a probable increase in consing because we
273 ;;;; have to create these new interval structures even though
274 ;;;; numeric-type has everything we want to know. Reason 2 wins for
277 ;;; Support operations that mimic real arithmetic comparison
278 ;;; operators, but imposing a total order on the floating points such
279 ;;; that negative zeros are strictly less than positive zeros.
280 (macrolet ((def (name op)
283 (if (and (floatp x) (floatp y) (zerop x) (zerop y))
284 (,op (float-sign x) (float-sign y))
286 (def signed-zero->= >=)
287 (def signed-zero-> >)
288 (def signed-zero-= =)
289 (def signed-zero-< <)
290 (def signed-zero-<= <=))
292 ;;; The basic interval type. It can handle open and closed intervals.
293 ;;; A bound is open if it is a list containing a number, just like
294 ;;; Lisp says. NIL means unbounded.
295 (defstruct (interval (:constructor %make-interval)
299 (defun make-interval (&key low high)
300 (labels ((normalize-bound (val)
303 (float-infinity-p val))
304 ;; Handle infinities.
308 ;; Handle any closed bounds.
311 ;; We have an open bound. Normalize the numeric
312 ;; bound. If the normalized bound is still a number
313 ;; (not nil), keep the bound open. Otherwise, the
314 ;; bound is really unbounded, so drop the openness.
315 (let ((new-val (normalize-bound (first val))))
317 ;; The bound exists, so keep it open still.
320 (error "unknown bound type in MAKE-INTERVAL")))))
321 (%make-interval :low (normalize-bound low)
322 :high (normalize-bound high))))
324 ;;; Given a number X, create a form suitable as a bound for an
325 ;;; interval. Make the bound open if OPEN-P is T. NIL remains NIL.
326 #!-sb-fluid (declaim (inline set-bound))
327 (defun set-bound (x open-p)
328 (if (and x open-p) (list x) x))
330 ;;; Apply the function F to a bound X. If X is an open bound, then
331 ;;; the result will be open. IF X is NIL, the result is NIL.
332 (defun bound-func (f x)
333 (declare (type function f))
335 (with-float-traps-masked (:underflow :overflow :inexact :divide-by-zero)
336 ;; With these traps masked, we might get things like infinity
337 ;; or negative infinity returned. Check for this and return
338 ;; NIL to indicate unbounded.
339 (let ((y (funcall f (type-bound-number x))))
341 (float-infinity-p y))
343 (set-bound y (consp x)))))))
345 (defun safe-double-coercion-p (x)
346 (or (typep x 'double-float)
347 (<= most-negative-double-float x most-positive-double-float)))
349 (defun safe-single-coercion-p (x)
350 (or (typep x 'single-float)
351 ;; Fix for bug 420, and related issues: during type derivation we often
352 ;; end up deriving types for both
354 ;; (some-op <int> <single>)
356 ;; (some-op (coerce <int> 'single-float) <single>)
358 ;; or other equivalent transformed forms. The problem with this is that
359 ;; on some platforms like x86 (+ <int> <single>) is on the machine level
362 ;; (coerce (+ (coerce <int> 'double-float)
363 ;; (coerce <single> 'double-float))
366 ;; so if the result of (coerce <int> 'single-float) is not exact, the
367 ;; derived types for the transformed forms will have an empty
368 ;; intersection -- which in turn means that the compiler will conclude
369 ;; that the call never returns, and all hell breaks lose when it *does*
370 ;; return at runtime. (This affects not just +, but other operators are
372 (and (not (typep x `(or (integer * (,most-negative-exactly-single-float-fixnum))
373 (integer (,most-positive-exactly-single-float-fixnum) *))))
374 (<= most-negative-single-float x most-positive-single-float))))
376 ;;; Apply a binary operator OP to two bounds X and Y. The result is
377 ;;; NIL if either is NIL. Otherwise bound is computed and the result
378 ;;; is open if either X or Y is open.
380 ;;; FIXME: only used in this file, not needed in target runtime
382 ;;; ANSI contaigon specifies coercion to floating point if one of the
383 ;;; arguments is floating point. Here we should check to be sure that
384 ;;; the other argument is within the bounds of that floating point
387 (defmacro safely-binop (op x y)
389 ((typep ,x 'double-float)
390 (when (safe-double-coercion-p ,y)
392 ((typep ,y 'double-float)
393 (when (safe-double-coercion-p ,x)
395 ((typep ,x 'single-float)
396 (when (safe-single-coercion-p ,y)
398 ((typep ,y 'single-float)
399 (when (safe-single-coercion-p ,x)
403 (defmacro bound-binop (op x y)
405 (with-float-traps-masked (:underflow :overflow :inexact :divide-by-zero)
406 (set-bound (safely-binop ,op (type-bound-number ,x)
407 (type-bound-number ,y))
408 (or (consp ,x) (consp ,y))))))
410 (defun coerce-for-bound (val type)
412 (list (coerce-for-bound (car val) type))
414 ((subtypep type 'double-float)
415 (if (<= most-negative-double-float val most-positive-double-float)
417 ((or (subtypep type 'single-float) (subtypep type 'float))
418 ;; coerce to float returns a single-float
419 (if (<= most-negative-single-float val most-positive-single-float)
421 (t (coerce val type)))))
423 (defun coerce-and-truncate-floats (val type)
426 (list (coerce-and-truncate-floats (car val) type))
428 ((subtypep type 'double-float)
429 (if (<= most-negative-double-float val most-positive-double-float)
431 (if (< val most-negative-double-float)
432 most-negative-double-float most-positive-double-float)))
433 ((or (subtypep type 'single-float) (subtypep type 'float))
434 ;; coerce to float returns a single-float
435 (if (<= most-negative-single-float val most-positive-single-float)
437 (if (< val most-negative-single-float)
438 most-negative-single-float most-positive-single-float)))
439 (t (coerce val type))))))
441 ;;; Convert a numeric-type object to an interval object.
442 (defun numeric-type->interval (x)
443 (declare (type numeric-type x))
444 (make-interval :low (numeric-type-low x)
445 :high (numeric-type-high x)))
447 (defun type-approximate-interval (type)
448 (declare (type ctype type))
449 (let ((types (prepare-arg-for-derive-type type))
452 (let ((type (if (member-type-p type)
453 (convert-member-type type)
455 (unless (numeric-type-p type)
456 (return-from type-approximate-interval nil))
457 (let ((interval (numeric-type->interval type)))
460 (interval-approximate-union result interval)
464 (defun copy-interval-limit (limit)
469 (defun copy-interval (x)
470 (declare (type interval x))
471 (make-interval :low (copy-interval-limit (interval-low x))
472 :high (copy-interval-limit (interval-high x))))
474 ;;; Given a point P contained in the interval X, split X into two
475 ;;; interval at the point P. If CLOSE-LOWER is T, then the left
476 ;;; interval contains P. If CLOSE-UPPER is T, the right interval
477 ;;; contains P. You can specify both to be T or NIL.
478 (defun interval-split (p x &optional close-lower close-upper)
479 (declare (type number p)
481 (list (make-interval :low (copy-interval-limit (interval-low x))
482 :high (if close-lower p (list p)))
483 (make-interval :low (if close-upper (list p) p)
484 :high (copy-interval-limit (interval-high x)))))
486 ;;; Return the closure of the interval. That is, convert open bounds
487 ;;; to closed bounds.
488 (defun interval-closure (x)
489 (declare (type interval x))
490 (make-interval :low (type-bound-number (interval-low x))
491 :high (type-bound-number (interval-high x))))
493 ;;; For an interval X, if X >= POINT, return '+. If X <= POINT, return
494 ;;; '-. Otherwise return NIL.
495 (defun interval-range-info (x &optional (point 0))
496 (declare (type interval x))
497 (let ((lo (interval-low x))
498 (hi (interval-high x)))
499 (cond ((and lo (signed-zero->= (type-bound-number lo) point))
501 ((and hi (signed-zero->= point (type-bound-number hi)))
506 ;;; Test to see whether the interval X is bounded. HOW determines the
507 ;;; test, and should be either ABOVE, BELOW, or BOTH.
508 (defun interval-bounded-p (x how)
509 (declare (type interval x))
516 (and (interval-low x) (interval-high x)))))
518 ;;; See whether the interval X contains the number P, taking into
519 ;;; account that the interval might not be closed.
520 (defun interval-contains-p (p x)
521 (declare (type number p)
523 ;; Does the interval X contain the number P? This would be a lot
524 ;; easier if all intervals were closed!
525 (let ((lo (interval-low x))
526 (hi (interval-high x)))
528 ;; The interval is bounded
529 (if (and (signed-zero-<= (type-bound-number lo) p)
530 (signed-zero-<= p (type-bound-number hi)))
531 ;; P is definitely in the closure of the interval.
532 ;; We just need to check the end points now.
533 (cond ((signed-zero-= p (type-bound-number lo))
535 ((signed-zero-= p (type-bound-number hi))
540 ;; Interval with upper bound
541 (if (signed-zero-< p (type-bound-number hi))
543 (and (numberp hi) (signed-zero-= p hi))))
545 ;; Interval with lower bound
546 (if (signed-zero-> p (type-bound-number lo))
548 (and (numberp lo) (signed-zero-= p lo))))
550 ;; Interval with no bounds
553 ;;; Determine whether two intervals X and Y intersect. Return T if so.
554 ;;; If CLOSED-INTERVALS-P is T, the treat the intervals as if they
555 ;;; were closed. Otherwise the intervals are treated as they are.
557 ;;; Thus if X = [0, 1) and Y = (1, 2), then they do not intersect
558 ;;; because no element in X is in Y. However, if CLOSED-INTERVALS-P
559 ;;; is T, then they do intersect because we use the closure of X = [0,
560 ;;; 1] and Y = [1, 2] to determine intersection.
561 (defun interval-intersect-p (x y &optional closed-intervals-p)
562 (declare (type interval x y))
563 (and (interval-intersection/difference (if closed-intervals-p
566 (if closed-intervals-p
571 ;;; Are the two intervals adjacent? That is, is there a number
572 ;;; between the two intervals that is not an element of either
573 ;;; interval? If so, they are not adjacent. For example [0, 1) and
574 ;;; [1, 2] are adjacent but [0, 1) and (1, 2] are not because 1 lies
575 ;;; between both intervals.
576 (defun interval-adjacent-p (x y)
577 (declare (type interval x y))
578 (flet ((adjacent (lo hi)
579 ;; Check to see whether lo and hi are adjacent. If either is
580 ;; nil, they can't be adjacent.
581 (when (and lo hi (= (type-bound-number lo) (type-bound-number hi)))
582 ;; The bounds are equal. They are adjacent if one of
583 ;; them is closed (a number). If both are open (consp),
584 ;; then there is a number that lies between them.
585 (or (numberp lo) (numberp hi)))))
586 (or (adjacent (interval-low y) (interval-high x))
587 (adjacent (interval-low x) (interval-high y)))))
589 ;;; Compute the intersection and difference between two intervals.
590 ;;; Two values are returned: the intersection and the difference.
592 ;;; Let the two intervals be X and Y, and let I and D be the two
593 ;;; values returned by this function. Then I = X intersect Y. If I
594 ;;; is NIL (the empty set), then D is X union Y, represented as the
595 ;;; list of X and Y. If I is not the empty set, then D is (X union Y)
596 ;;; - I, which is a list of two intervals.
598 ;;; For example, let X = [1,5] and Y = [-1,3). Then I = [1,3) and D =
599 ;;; [-1,1) union [3,5], which is returned as a list of two intervals.
600 (defun interval-intersection/difference (x y)
601 (declare (type interval x y))
602 (let ((x-lo (interval-low x))
603 (x-hi (interval-high x))
604 (y-lo (interval-low y))
605 (y-hi (interval-high y)))
608 ;; If p is an open bound, make it closed. If p is a closed
609 ;; bound, make it open.
613 (test-number (p int bound)
614 ;; Test whether P is in the interval.
615 (let ((pn (type-bound-number p)))
616 (when (interval-contains-p pn (interval-closure int))
617 ;; Check for endpoints.
618 (let* ((lo (interval-low int))
619 (hi (interval-high int))
620 (lon (type-bound-number lo))
621 (hin (type-bound-number hi)))
623 ;; Interval may be a point.
624 ((and lon hin (= lon hin pn))
625 (and (numberp p) (numberp lo) (numberp hi)))
626 ;; Point matches the low end.
627 ;; [P] [P,?} => TRUE [P] (P,?} => FALSE
628 ;; (P [P,?} => TRUE P) [P,?} => FALSE
629 ;; (P (P,?} => TRUE P) (P,?} => FALSE
630 ((and lon (= pn lon))
631 (or (and (numberp p) (numberp lo))
632 (and (consp p) (eq :low bound))))
633 ;; [P] {?,P] => TRUE [P] {?,P) => FALSE
634 ;; P) {?,P] => TRUE (P {?,P] => FALSE
635 ;; P) {?,P) => TRUE (P {?,P) => FALSE
636 ((and hin (= pn hin))
637 (or (and (numberp p) (numberp hi))
638 (and (consp p) (eq :high bound))))
639 ;; Not an endpoint, all is well.
642 (test-lower-bound (p int)
643 ;; P is a lower bound of an interval.
645 (test-number p int :low)
646 (not (interval-bounded-p int 'below))))
647 (test-upper-bound (p int)
648 ;; P is an upper bound of an interval.
650 (test-number p int :high)
651 (not (interval-bounded-p int 'above)))))
652 (let ((x-lo-in-y (test-lower-bound x-lo y))
653 (x-hi-in-y (test-upper-bound x-hi y))
654 (y-lo-in-x (test-lower-bound y-lo x))
655 (y-hi-in-x (test-upper-bound y-hi x)))
656 (cond ((or x-lo-in-y x-hi-in-y y-lo-in-x y-hi-in-x)
657 ;; Intervals intersect. Let's compute the intersection
658 ;; and the difference.
659 (multiple-value-bind (lo left-lo left-hi)
660 (cond (x-lo-in-y (values x-lo y-lo (opposite-bound x-lo)))
661 (y-lo-in-x (values y-lo x-lo (opposite-bound y-lo))))
662 (multiple-value-bind (hi right-lo right-hi)
664 (values x-hi (opposite-bound x-hi) y-hi))
666 (values y-hi (opposite-bound y-hi) x-hi)))
667 (values (make-interval :low lo :high hi)
668 (list (make-interval :low left-lo
670 (make-interval :low right-lo
673 (values nil (list x y))))))))
675 ;;; If intervals X and Y intersect, return a new interval that is the
676 ;;; union of the two. If they do not intersect, return NIL.
677 (defun interval-merge-pair (x y)
678 (declare (type interval x y))
679 ;; If x and y intersect or are adjacent, create the union.
680 ;; Otherwise return nil
681 (when (or (interval-intersect-p x y)
682 (interval-adjacent-p x y))
683 (flet ((select-bound (x1 x2 min-op max-op)
684 (let ((x1-val (type-bound-number x1))
685 (x2-val (type-bound-number x2)))
687 ;; Both bounds are finite. Select the right one.
688 (cond ((funcall min-op x1-val x2-val)
689 ;; x1 is definitely better.
691 ((funcall max-op x1-val x2-val)
692 ;; x2 is definitely better.
695 ;; Bounds are equal. Select either
696 ;; value and make it open only if
698 (set-bound x1-val (and (consp x1) (consp x2))))))
700 ;; At least one bound is not finite. The
701 ;; non-finite bound always wins.
703 (let* ((x-lo (copy-interval-limit (interval-low x)))
704 (x-hi (copy-interval-limit (interval-high x)))
705 (y-lo (copy-interval-limit (interval-low y)))
706 (y-hi (copy-interval-limit (interval-high y))))
707 (make-interval :low (select-bound x-lo y-lo #'< #'>)
708 :high (select-bound x-hi y-hi #'> #'<))))))
710 ;;; return the minimal interval, containing X and Y
711 (defun interval-approximate-union (x y)
712 (cond ((interval-merge-pair x y))
714 (make-interval :low (copy-interval-limit (interval-low x))
715 :high (copy-interval-limit (interval-high y))))
717 (make-interval :low (copy-interval-limit (interval-low y))
718 :high (copy-interval-limit (interval-high x))))))
720 ;;; basic arithmetic operations on intervals. We probably should do
721 ;;; true interval arithmetic here, but it's complicated because we
722 ;;; have float and integer types and bounds can be open or closed.
724 ;;; the negative of an interval
725 (defun interval-neg (x)
726 (declare (type interval x))
727 (make-interval :low (bound-func #'- (interval-high x))
728 :high (bound-func #'- (interval-low x))))
730 ;;; Add two intervals.
731 (defun interval-add (x y)
732 (declare (type interval x y))
733 (make-interval :low (bound-binop + (interval-low x) (interval-low y))
734 :high (bound-binop + (interval-high x) (interval-high y))))
736 ;;; Subtract two intervals.
737 (defun interval-sub (x y)
738 (declare (type interval x y))
739 (make-interval :low (bound-binop - (interval-low x) (interval-high y))
740 :high (bound-binop - (interval-high x) (interval-low y))))
742 ;;; Multiply two intervals.
743 (defun interval-mul (x y)
744 (declare (type interval x y))
745 (flet ((bound-mul (x y)
746 (cond ((or (null x) (null y))
747 ;; Multiply by infinity is infinity
749 ((or (and (numberp x) (zerop x))
750 (and (numberp y) (zerop y)))
751 ;; Multiply by closed zero is special. The result
752 ;; is always a closed bound. But don't replace this
753 ;; with zero; we want the multiplication to produce
754 ;; the correct signed zero, if needed. Use SIGNUM
755 ;; to avoid trying to multiply huge bignums with 0.0.
756 (* (signum (type-bound-number x)) (signum (type-bound-number y))))
757 ((or (and (floatp x) (float-infinity-p x))
758 (and (floatp y) (float-infinity-p y)))
759 ;; Infinity times anything is infinity
762 ;; General multiply. The result is open if either is open.
763 (bound-binop * x y)))))
764 (let ((x-range (interval-range-info x))
765 (y-range (interval-range-info y)))
766 (cond ((null x-range)
767 ;; Split x into two and multiply each separately
768 (destructuring-bind (x- x+) (interval-split 0 x t t)
769 (interval-merge-pair (interval-mul x- y)
770 (interval-mul x+ y))))
772 ;; Split y into two and multiply each separately
773 (destructuring-bind (y- y+) (interval-split 0 y t t)
774 (interval-merge-pair (interval-mul x y-)
775 (interval-mul x y+))))
777 (interval-neg (interval-mul (interval-neg x) y)))
779 (interval-neg (interval-mul x (interval-neg y))))
780 ((and (eq x-range '+) (eq y-range '+))
781 ;; If we are here, X and Y are both positive.
783 :low (bound-mul (interval-low x) (interval-low y))
784 :high (bound-mul (interval-high x) (interval-high y))))
786 (bug "excluded case in INTERVAL-MUL"))))))
788 ;;; Divide two intervals.
789 (defun interval-div (top bot)
790 (declare (type interval top bot))
791 (flet ((bound-div (x y y-low-p)
794 ;; Divide by infinity means result is 0. However,
795 ;; we need to watch out for the sign of the result,
796 ;; to correctly handle signed zeros. We also need
797 ;; to watch out for positive or negative infinity.
798 (if (floatp (type-bound-number x))
800 (- (float-sign (type-bound-number x) 0.0))
801 (float-sign (type-bound-number x) 0.0))
803 ((zerop (type-bound-number y))
804 ;; Divide by zero means result is infinity
806 ((and (numberp x) (zerop x))
807 ;; Zero divided by anything is zero.
810 (bound-binop / x y)))))
811 (let ((top-range (interval-range-info top))
812 (bot-range (interval-range-info bot)))
813 (cond ((null bot-range)
814 ;; The denominator contains zero, so anything goes!
815 (make-interval :low nil :high nil))
817 ;; Denominator is negative so flip the sign, compute the
818 ;; result, and flip it back.
819 (interval-neg (interval-div top (interval-neg bot))))
821 ;; Split top into two positive and negative parts, and
822 ;; divide each separately
823 (destructuring-bind (top- top+) (interval-split 0 top t t)
824 (interval-merge-pair (interval-div top- bot)
825 (interval-div top+ bot))))
827 ;; Top is negative so flip the sign, divide, and flip the
828 ;; sign of the result.
829 (interval-neg (interval-div (interval-neg top) bot)))
830 ((and (eq top-range '+) (eq bot-range '+))
833 :low (bound-div (interval-low top) (interval-high bot) t)
834 :high (bound-div (interval-high top) (interval-low bot) nil)))
836 (bug "excluded case in INTERVAL-DIV"))))))
838 ;;; Apply the function F to the interval X. If X = [a, b], then the
839 ;;; result is [f(a), f(b)]. It is up to the user to make sure the
840 ;;; result makes sense. It will if F is monotonic increasing (or
842 (defun interval-func (f x)
843 (declare (type function f)
845 (let ((lo (bound-func f (interval-low x)))
846 (hi (bound-func f (interval-high x))))
847 (make-interval :low lo :high hi)))
849 ;;; Return T if X < Y. That is every number in the interval X is
850 ;;; always less than any number in the interval Y.
851 (defun interval-< (x y)
852 (declare (type interval x y))
853 ;; X < Y only if X is bounded above, Y is bounded below, and they
855 (when (and (interval-bounded-p x 'above)
856 (interval-bounded-p y 'below))
857 ;; Intervals are bounded in the appropriate way. Make sure they
859 (let ((left (interval-high x))
860 (right (interval-low y)))
861 (cond ((> (type-bound-number left)
862 (type-bound-number right))
863 ;; The intervals definitely overlap, so result is NIL.
865 ((< (type-bound-number left)
866 (type-bound-number right))
867 ;; The intervals definitely don't touch, so result is T.
870 ;; Limits are equal. Check for open or closed bounds.
871 ;; Don't overlap if one or the other are open.
872 (or (consp left) (consp right)))))))
874 ;;; Return T if X >= Y. That is, every number in the interval X is
875 ;;; always greater than any number in the interval Y.
876 (defun interval->= (x y)
877 (declare (type interval x y))
878 ;; X >= Y if lower bound of X >= upper bound of Y
879 (when (and (interval-bounded-p x 'below)
880 (interval-bounded-p y 'above))
881 (>= (type-bound-number (interval-low x))
882 (type-bound-number (interval-high y)))))
884 ;;; Return T if X = Y.
885 (defun interval-= (x y)
886 (declare (type interval x y))
887 (and (interval-bounded-p x 'both)
888 (interval-bounded-p y 'both)
892 ;; Open intervals cannot be =
893 (return-from interval-= nil))))
894 ;; Both intervals refer to the same point
895 (= (bound (interval-high x)) (bound (interval-low x))
896 (bound (interval-high y)) (bound (interval-low y))))))
898 ;;; Return T if X /= Y
899 (defun interval-/= (x y)
900 (not (interval-intersect-p x y)))
902 ;;; Return an interval that is the absolute value of X. Thus, if
903 ;;; X = [-1 10], the result is [0, 10].
904 (defun interval-abs (x)
905 (declare (type interval x))
906 (case (interval-range-info x)
912 (destructuring-bind (x- x+) (interval-split 0 x t t)
913 (interval-merge-pair (interval-neg x-) x+)))))
915 ;;; Compute the square of an interval.
916 (defun interval-sqr (x)
917 (declare (type interval x))
918 (interval-func (lambda (x) (* x x))
921 ;;;; numeric DERIVE-TYPE methods
923 ;;; a utility for defining derive-type methods of integer operations. If
924 ;;; the types of both X and Y are integer types, then we compute a new
925 ;;; integer type with bounds determined Fun when applied to X and Y.
926 ;;; Otherwise, we use NUMERIC-CONTAGION.
927 (defun derive-integer-type-aux (x y fun)
928 (declare (type function fun))
929 (if (and (numeric-type-p x) (numeric-type-p y)
930 (eq (numeric-type-class x) 'integer)
931 (eq (numeric-type-class y) 'integer)
932 (eq (numeric-type-complexp x) :real)
933 (eq (numeric-type-complexp y) :real))
934 (multiple-value-bind (low high) (funcall fun x y)
935 (make-numeric-type :class 'integer
939 (numeric-contagion x y)))
941 (defun derive-integer-type (x y fun)
942 (declare (type lvar x y) (type function fun))
943 (let ((x (lvar-type x))
945 (derive-integer-type-aux x y fun)))
947 ;;; simple utility to flatten a list
948 (defun flatten-list (x)
949 (labels ((flatten-and-append (tree list)
950 (cond ((null tree) list)
951 ((atom tree) (cons tree list))
952 (t (flatten-and-append
953 (car tree) (flatten-and-append (cdr tree) list))))))
954 (flatten-and-append x nil)))
956 ;;; Take some type of lvar and massage it so that we get a list of the
957 ;;; constituent types. If ARG is *EMPTY-TYPE*, return NIL to indicate
959 (defun prepare-arg-for-derive-type (arg)
960 (flet ((listify (arg)
965 (union-type-types arg))
968 (unless (eq arg *empty-type*)
969 ;; Make sure all args are some type of numeric-type. For member
970 ;; types, convert the list of members into a union of equivalent
971 ;; single-element member-type's.
972 (let ((new-args nil))
973 (dolist (arg (listify arg))
974 (if (member-type-p arg)
975 ;; Run down the list of members and convert to a list of
977 (mapc-member-type-members
979 (push (if (numberp member)
980 (make-member-type :members (list member))
984 (push arg new-args)))
985 (unless (member *empty-type* new-args)
988 ;;; Convert from the standard type convention for which -0.0 and 0.0
989 ;;; are equal to an intermediate convention for which they are
990 ;;; considered different which is more natural for some of the
992 (defun convert-numeric-type (type)
993 (declare (type numeric-type type))
994 ;;; Only convert real float interval delimiters types.
995 (if (eq (numeric-type-complexp type) :real)
996 (let* ((lo (numeric-type-low type))
997 (lo-val (type-bound-number lo))
998 (lo-float-zero-p (and lo (floatp lo-val) (= lo-val 0.0)))
999 (hi (numeric-type-high type))
1000 (hi-val (type-bound-number hi))
1001 (hi-float-zero-p (and hi (floatp hi-val) (= hi-val 0.0))))
1002 (if (or lo-float-zero-p hi-float-zero-p)
1004 :class (numeric-type-class type)
1005 :format (numeric-type-format type)
1007 :low (if lo-float-zero-p
1009 (list (float 0.0 lo-val))
1010 (float (load-time-value (make-unportable-float :single-float-negative-zero)) lo-val))
1012 :high (if hi-float-zero-p
1014 (list (float (load-time-value (make-unportable-float :single-float-negative-zero)) hi-val))
1021 ;;; Convert back from the intermediate convention for which -0.0 and
1022 ;;; 0.0 are considered different to the standard type convention for
1023 ;;; which and equal.
1024 (defun convert-back-numeric-type (type)
1025 (declare (type numeric-type type))
1026 ;;; Only convert real float interval delimiters types.
1027 (if (eq (numeric-type-complexp type) :real)
1028 (let* ((lo (numeric-type-low type))
1029 (lo-val (type-bound-number lo))
1031 (and lo (floatp lo-val) (= lo-val 0.0)
1032 (float-sign lo-val)))
1033 (hi (numeric-type-high type))
1034 (hi-val (type-bound-number hi))
1036 (and hi (floatp hi-val) (= hi-val 0.0)
1037 (float-sign hi-val))))
1039 ;; (float +0.0 +0.0) => (member 0.0)
1040 ;; (float -0.0 -0.0) => (member -0.0)
1041 ((and lo-float-zero-p hi-float-zero-p)
1042 ;; shouldn't have exclusive bounds here..
1043 (aver (and (not (consp lo)) (not (consp hi))))
1044 (if (= lo-float-zero-p hi-float-zero-p)
1045 ;; (float +0.0 +0.0) => (member 0.0)
1046 ;; (float -0.0 -0.0) => (member -0.0)
1047 (specifier-type `(member ,lo-val))
1048 ;; (float -0.0 +0.0) => (float 0.0 0.0)
1049 ;; (float +0.0 -0.0) => (float 0.0 0.0)
1050 (make-numeric-type :class (numeric-type-class type)
1051 :format (numeric-type-format type)
1057 ;; (float -0.0 x) => (float 0.0 x)
1058 ((and (not (consp lo)) (minusp lo-float-zero-p))
1059 (make-numeric-type :class (numeric-type-class type)
1060 :format (numeric-type-format type)
1062 :low (float 0.0 lo-val)
1064 ;; (float (+0.0) x) => (float (0.0) x)
1065 ((and (consp lo) (plusp lo-float-zero-p))
1066 (make-numeric-type :class (numeric-type-class type)
1067 :format (numeric-type-format type)
1069 :low (list (float 0.0 lo-val))
1072 ;; (float +0.0 x) => (or (member 0.0) (float (0.0) x))
1073 ;; (float (-0.0) x) => (or (member 0.0) (float (0.0) x))
1074 (list (make-member-type :members (list (float 0.0 lo-val)))
1075 (make-numeric-type :class (numeric-type-class type)
1076 :format (numeric-type-format type)
1078 :low (list (float 0.0 lo-val))
1082 ;; (float x +0.0) => (float x 0.0)
1083 ((and (not (consp hi)) (plusp hi-float-zero-p))
1084 (make-numeric-type :class (numeric-type-class type)
1085 :format (numeric-type-format type)
1088 :high (float 0.0 hi-val)))
1089 ;; (float x (-0.0)) => (float x (0.0))
1090 ((and (consp hi) (minusp hi-float-zero-p))
1091 (make-numeric-type :class (numeric-type-class type)
1092 :format (numeric-type-format type)
1095 :high (list (float 0.0 hi-val))))
1097 ;; (float x (+0.0)) => (or (member -0.0) (float x (0.0)))
1098 ;; (float x -0.0) => (or (member -0.0) (float x (0.0)))
1099 (list (make-member-type :members (list (float (load-time-value (make-unportable-float :single-float-negative-zero)) hi-val)))
1100 (make-numeric-type :class (numeric-type-class type)
1101 :format (numeric-type-format type)
1104 :high (list (float 0.0 hi-val)))))))
1110 ;;; Convert back a possible list of numeric types.
1111 (defun convert-back-numeric-type-list (type-list)
1114 (let ((results '()))
1115 (dolist (type type-list)
1116 (if (numeric-type-p type)
1117 (let ((result (convert-back-numeric-type type)))
1119 (setf results (append results result))
1120 (push result results)))
1121 (push type results)))
1124 (convert-back-numeric-type type-list))
1126 (convert-back-numeric-type-list (union-type-types type-list)))
1130 ;;; Take a list of types and return a canonical type specifier,
1131 ;;; combining any MEMBER types together. If both positive and negative
1132 ;;; MEMBER types are present they are converted to a float type.
1133 ;;; XXX This would be far simpler if the type-union methods could handle
1134 ;;; member/number unions.
1136 ;;; If we're about to generate an overly complex union of numeric types, start
1137 ;;; collapse the ranges together.
1139 ;;; FIXME: The MEMBER canonicalization parts of MAKE-DERIVED-UNION-TYPE and
1140 ;;; entire CONVERT-MEMBER-TYPE probably belong in the kernel's type logic,
1141 ;;; invoked always, instead of in the compiler, invoked only during some type
1143 (defvar *derived-numeric-union-complexity-limit* 6)
1145 (defun make-derived-union-type (type-list)
1146 (let ((xset (alloc-xset))
1149 (numeric-type *empty-type*))
1150 (dolist (type type-list)
1151 (cond ((member-type-p type)
1152 (mapc-member-type-members
1154 (if (fp-zero-p member)
1155 (unless (member member fp-zeroes)
1156 (pushnew member fp-zeroes))
1157 (add-to-xset member xset)))
1159 ((numeric-type-p type)
1160 (let ((*approximate-numeric-unions*
1161 (when (and (union-type-p numeric-type)
1162 (nthcdr *derived-numeric-union-complexity-limit*
1163 (union-type-types numeric-type)))
1165 (setf numeric-type (type-union type numeric-type))))
1167 (push type misc-types))))
1168 (if (and (xset-empty-p xset) (not fp-zeroes))
1169 (apply #'type-union numeric-type misc-types)
1170 (apply #'type-union (make-member-type :xset xset :fp-zeroes fp-zeroes)
1171 numeric-type misc-types))))
1173 ;;; Convert a member type with a single member to a numeric type.
1174 (defun convert-member-type (arg)
1175 (let* ((members (member-type-members arg))
1176 (member (first members))
1177 (member-type (type-of member)))
1178 (aver (not (rest members)))
1179 (specifier-type (cond ((typep member 'integer)
1180 `(integer ,member ,member))
1181 ((memq member-type '(short-float single-float
1182 double-float long-float))
1183 `(,member-type ,member ,member))
1187 ;;; This is used in defoptimizers for computing the resulting type of
1190 ;;; Given the lvar ARG, derive the resulting type using the
1191 ;;; DERIVE-FUN. DERIVE-FUN takes exactly one argument which is some
1192 ;;; "atomic" lvar type like numeric-type or member-type (containing
1193 ;;; just one element). It should return the resulting type, which can
1194 ;;; be a list of types.
1196 ;;; For the case of member types, if a MEMBER-FUN is given it is
1197 ;;; called to compute the result otherwise the member type is first
1198 ;;; converted to a numeric type and the DERIVE-FUN is called.
1199 (defun one-arg-derive-type (arg derive-fun member-fun
1200 &optional (convert-type t))
1201 (declare (type function derive-fun)
1202 (type (or null function) member-fun))
1203 (let ((arg-list (prepare-arg-for-derive-type (lvar-type arg))))
1209 (with-float-traps-masked
1210 (:underflow :overflow :divide-by-zero)
1212 `(eql ,(funcall member-fun
1213 (first (member-type-members x))))))
1214 ;; Otherwise convert to a numeric type.
1215 (let ((result-type-list
1216 (funcall derive-fun (convert-member-type x))))
1218 (convert-back-numeric-type-list result-type-list)
1219 result-type-list))))
1222 (convert-back-numeric-type-list
1223 (funcall derive-fun (convert-numeric-type x)))
1224 (funcall derive-fun x)))
1226 *universal-type*))))
1227 ;; Run down the list of args and derive the type of each one,
1228 ;; saving all of the results in a list.
1229 (let ((results nil))
1230 (dolist (arg arg-list)
1231 (let ((result (deriver arg)))
1233 (setf results (append results result))
1234 (push result results))))
1236 (make-derived-union-type results)
1237 (first results)))))))
1239 ;;; Same as ONE-ARG-DERIVE-TYPE, except we assume the function takes
1240 ;;; two arguments. DERIVE-FUN takes 3 args in this case: the two
1241 ;;; original args and a third which is T to indicate if the two args
1242 ;;; really represent the same lvar. This is useful for deriving the
1243 ;;; type of things like (* x x), which should always be positive. If
1244 ;;; we didn't do this, we wouldn't be able to tell.
1245 (defun two-arg-derive-type (arg1 arg2 derive-fun fun
1246 &optional (convert-type t))
1247 (declare (type function derive-fun fun))
1248 (flet ((deriver (x y same-arg)
1249 (cond ((and (member-type-p x) (member-type-p y))
1250 (let* ((x (first (member-type-members x)))
1251 (y (first (member-type-members y)))
1252 (result (ignore-errors
1253 (with-float-traps-masked
1254 (:underflow :overflow :divide-by-zero
1256 (funcall fun x y)))))
1257 (cond ((null result) *empty-type*)
1258 ((and (floatp result) (float-nan-p result))
1259 (make-numeric-type :class 'float
1260 :format (type-of result)
1263 (specifier-type `(eql ,result))))))
1264 ((and (member-type-p x) (numeric-type-p y))
1265 (let* ((x (convert-member-type x))
1266 (y (if convert-type (convert-numeric-type y) y))
1267 (result (funcall derive-fun x y same-arg)))
1269 (convert-back-numeric-type-list result)
1271 ((and (numeric-type-p x) (member-type-p y))
1272 (let* ((x (if convert-type (convert-numeric-type x) x))
1273 (y (convert-member-type y))
1274 (result (funcall derive-fun x y same-arg)))
1276 (convert-back-numeric-type-list result)
1278 ((and (numeric-type-p x) (numeric-type-p y))
1279 (let* ((x (if convert-type (convert-numeric-type x) x))
1280 (y (if convert-type (convert-numeric-type y) y))
1281 (result (funcall derive-fun x y same-arg)))
1283 (convert-back-numeric-type-list result)
1286 *universal-type*))))
1287 (let ((same-arg (same-leaf-ref-p arg1 arg2))
1288 (a1 (prepare-arg-for-derive-type (lvar-type arg1)))
1289 (a2 (prepare-arg-for-derive-type (lvar-type arg2))))
1291 (let ((results nil))
1293 ;; Since the args are the same LVARs, just run down the
1296 (let ((result (deriver x x same-arg)))
1298 (setf results (append results result))
1299 (push result results))))
1300 ;; Try all pairwise combinations.
1303 (let ((result (or (deriver x y same-arg)
1304 (numeric-contagion x y))))
1306 (setf results (append results result))
1307 (push result results))))))
1309 (make-derived-union-type results)
1310 (first results)))))))
1312 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1314 (defoptimizer (+ derive-type) ((x y))
1315 (derive-integer-type
1322 (values (frob (numeric-type-low x) (numeric-type-low y))
1323 (frob (numeric-type-high x) (numeric-type-high y)))))))
1325 (defoptimizer (- derive-type) ((x y))
1326 (derive-integer-type
1333 (values (frob (numeric-type-low x) (numeric-type-high y))
1334 (frob (numeric-type-high x) (numeric-type-low y)))))))
1336 (defoptimizer (* derive-type) ((x y))
1337 (derive-integer-type
1340 (let ((x-low (numeric-type-low x))
1341 (x-high (numeric-type-high x))
1342 (y-low (numeric-type-low y))
1343 (y-high (numeric-type-high y)))
1344 (cond ((not (and x-low y-low))
1346 ((or (minusp x-low) (minusp y-low))
1347 (if (and x-high y-high)
1348 (let ((max (* (max (abs x-low) (abs x-high))
1349 (max (abs y-low) (abs y-high)))))
1350 (values (- max) max))
1353 (values (* x-low y-low)
1354 (if (and x-high y-high)
1358 (defoptimizer (/ derive-type) ((x y))
1359 (numeric-contagion (lvar-type x) (lvar-type y)))
1363 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1365 (defun +-derive-type-aux (x y same-arg)
1366 (if (and (numeric-type-real-p x)
1367 (numeric-type-real-p y))
1370 (let ((x-int (numeric-type->interval x)))
1371 (interval-add x-int x-int))
1372 (interval-add (numeric-type->interval x)
1373 (numeric-type->interval y))))
1374 (result-type (numeric-contagion x y)))
1375 ;; If the result type is a float, we need to be sure to coerce
1376 ;; the bounds into the correct type.
1377 (when (eq (numeric-type-class result-type) 'float)
1378 (setf result (interval-func
1380 (coerce-for-bound x (or (numeric-type-format result-type)
1384 :class (if (and (eq (numeric-type-class x) 'integer)
1385 (eq (numeric-type-class y) 'integer))
1386 ;; The sum of integers is always an integer.
1388 (numeric-type-class result-type))
1389 :format (numeric-type-format result-type)
1390 :low (interval-low result)
1391 :high (interval-high result)))
1392 ;; general contagion
1393 (numeric-contagion x y)))
1395 (defoptimizer (+ derive-type) ((x y))
1396 (two-arg-derive-type x y #'+-derive-type-aux #'+))
1398 (defun --derive-type-aux (x y same-arg)
1399 (if (and (numeric-type-real-p x)
1400 (numeric-type-real-p y))
1402 ;; (- X X) is always 0.
1404 (make-interval :low 0 :high 0)
1405 (interval-sub (numeric-type->interval x)
1406 (numeric-type->interval y))))
1407 (result-type (numeric-contagion x y)))
1408 ;; If the result type is a float, we need to be sure to coerce
1409 ;; the bounds into the correct type.
1410 (when (eq (numeric-type-class result-type) 'float)
1411 (setf result (interval-func
1413 (coerce-for-bound x (or (numeric-type-format result-type)
1417 :class (if (and (eq (numeric-type-class x) 'integer)
1418 (eq (numeric-type-class y) 'integer))
1419 ;; The difference of integers is always an integer.
1421 (numeric-type-class result-type))
1422 :format (numeric-type-format result-type)
1423 :low (interval-low result)
1424 :high (interval-high result)))
1425 ;; general contagion
1426 (numeric-contagion x y)))
1428 (defoptimizer (- derive-type) ((x y))
1429 (two-arg-derive-type x y #'--derive-type-aux #'-))
1431 (defun *-derive-type-aux (x y same-arg)
1432 (if (and (numeric-type-real-p x)
1433 (numeric-type-real-p y))
1435 ;; (* X X) is always positive, so take care to do it right.
1437 (interval-sqr (numeric-type->interval x))
1438 (interval-mul (numeric-type->interval x)
1439 (numeric-type->interval y))))
1440 (result-type (numeric-contagion x y)))
1441 ;; If the result type is a float, we need to be sure to coerce
1442 ;; the bounds into the correct type.
1443 (when (eq (numeric-type-class result-type) 'float)
1444 (setf result (interval-func
1446 (coerce-for-bound x (or (numeric-type-format result-type)
1450 :class (if (and (eq (numeric-type-class x) 'integer)
1451 (eq (numeric-type-class y) 'integer))
1452 ;; The product of integers is always an integer.
1454 (numeric-type-class result-type))
1455 :format (numeric-type-format result-type)
1456 :low (interval-low result)
1457 :high (interval-high result)))
1458 (numeric-contagion x y)))
1460 (defoptimizer (* derive-type) ((x y))
1461 (two-arg-derive-type x y #'*-derive-type-aux #'*))
1463 (defun /-derive-type-aux (x y same-arg)
1464 (if (and (numeric-type-real-p x)
1465 (numeric-type-real-p y))
1467 ;; (/ X X) is always 1, except if X can contain 0. In
1468 ;; that case, we shouldn't optimize the division away
1469 ;; because we want 0/0 to signal an error.
1471 (not (interval-contains-p
1472 0 (interval-closure (numeric-type->interval y)))))
1473 (make-interval :low 1 :high 1)
1474 (interval-div (numeric-type->interval x)
1475 (numeric-type->interval y))))
1476 (result-type (numeric-contagion x y)))
1477 ;; If the result type is a float, we need to be sure to coerce
1478 ;; the bounds into the correct type.
1479 (when (eq (numeric-type-class result-type) 'float)
1480 (setf result (interval-func
1482 (coerce-for-bound x (or (numeric-type-format result-type)
1485 (make-numeric-type :class (numeric-type-class result-type)
1486 :format (numeric-type-format result-type)
1487 :low (interval-low result)
1488 :high (interval-high result)))
1489 (numeric-contagion x y)))
1491 (defoptimizer (/ derive-type) ((x y))
1492 (two-arg-derive-type x y #'/-derive-type-aux #'/))
1496 (defun ash-derive-type-aux (n-type shift same-arg)
1497 (declare (ignore same-arg))
1498 ;; KLUDGE: All this ASH optimization is suppressed under CMU CL for
1499 ;; some bignum cases because as of version 2.4.6 for Debian and 18d,
1500 ;; CMU CL blows up on (ASH 1000000000 -100000000000) (i.e. ASH of
1501 ;; two bignums yielding zero) and it's hard to avoid that
1502 ;; calculation in here.
1503 #+(and cmu sb-xc-host)
1504 (when (and (or (typep (numeric-type-low n-type) 'bignum)
1505 (typep (numeric-type-high n-type) 'bignum))
1506 (or (typep (numeric-type-low shift) 'bignum)
1507 (typep (numeric-type-high shift) 'bignum)))
1508 (return-from ash-derive-type-aux *universal-type*))
1509 (flet ((ash-outer (n s)
1510 (when (and (fixnump s)
1512 (> s sb!xc:most-negative-fixnum))
1514 ;; KLUDGE: The bare 64's here should be related to
1515 ;; symbolic machine word size values somehow.
1518 (if (and (fixnump s)
1519 (> s sb!xc:most-negative-fixnum))
1521 (if (minusp n) -1 0))))
1522 (or (and (csubtypep n-type (specifier-type 'integer))
1523 (csubtypep shift (specifier-type 'integer))
1524 (let ((n-low (numeric-type-low n-type))
1525 (n-high (numeric-type-high n-type))
1526 (s-low (numeric-type-low shift))
1527 (s-high (numeric-type-high shift)))
1528 (make-numeric-type :class 'integer :complexp :real
1531 (ash-outer n-low s-high)
1532 (ash-inner n-low s-low)))
1535 (ash-inner n-high s-low)
1536 (ash-outer n-high s-high))))))
1539 (defoptimizer (ash derive-type) ((n shift))
1540 (two-arg-derive-type n shift #'ash-derive-type-aux #'ash))
1542 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1543 (macrolet ((frob (fun)
1544 `#'(lambda (type type2)
1545 (declare (ignore type2))
1546 (let ((lo (numeric-type-low type))
1547 (hi (numeric-type-high type)))
1548 (values (if hi (,fun hi) nil) (if lo (,fun lo) nil))))))
1550 (defoptimizer (%negate derive-type) ((num))
1551 (derive-integer-type num num (frob -))))
1553 (defun lognot-derive-type-aux (int)
1554 (derive-integer-type-aux int int
1555 (lambda (type type2)
1556 (declare (ignore type2))
1557 (let ((lo (numeric-type-low type))
1558 (hi (numeric-type-high type)))
1559 (values (if hi (lognot hi) nil)
1560 (if lo (lognot lo) nil)
1561 (numeric-type-class type)
1562 (numeric-type-format type))))))
1564 (defoptimizer (lognot derive-type) ((int))
1565 (lognot-derive-type-aux (lvar-type int)))
1567 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1568 (defoptimizer (%negate derive-type) ((num))
1569 (flet ((negate-bound (b)
1571 (set-bound (- (type-bound-number b))
1573 (one-arg-derive-type num
1575 (modified-numeric-type
1577 :low (negate-bound (numeric-type-high type))
1578 :high (negate-bound (numeric-type-low type))))
1581 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1582 (defoptimizer (abs derive-type) ((num))
1583 (let ((type (lvar-type num)))
1584 (if (and (numeric-type-p type)
1585 (eq (numeric-type-class type) 'integer)
1586 (eq (numeric-type-complexp type) :real))
1587 (let ((lo (numeric-type-low type))
1588 (hi (numeric-type-high type)))
1589 (make-numeric-type :class 'integer :complexp :real
1590 :low (cond ((and hi (minusp hi))
1596 :high (if (and hi lo)
1597 (max (abs hi) (abs lo))
1599 (numeric-contagion type type))))
1601 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1602 (defun abs-derive-type-aux (type)
1603 (cond ((eq (numeric-type-complexp type) :complex)
1604 ;; The absolute value of a complex number is always a
1605 ;; non-negative float.
1606 (let* ((format (case (numeric-type-class type)
1607 ((integer rational) 'single-float)
1608 (t (numeric-type-format type))))
1609 (bound-format (or format 'float)))
1610 (make-numeric-type :class 'float
1613 :low (coerce 0 bound-format)
1616 ;; The absolute value of a real number is a non-negative real
1617 ;; of the same type.
1618 (let* ((abs-bnd (interval-abs (numeric-type->interval type)))
1619 (class (numeric-type-class type))
1620 (format (numeric-type-format type))
1621 (bound-type (or format class 'real)))
1626 :low (coerce-and-truncate-floats (interval-low abs-bnd) bound-type)
1627 :high (coerce-and-truncate-floats
1628 (interval-high abs-bnd) bound-type))))))
1630 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1631 (defoptimizer (abs derive-type) ((num))
1632 (one-arg-derive-type num #'abs-derive-type-aux #'abs))
1634 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1635 (defoptimizer (truncate derive-type) ((number divisor))
1636 (let ((number-type (lvar-type number))
1637 (divisor-type (lvar-type divisor))
1638 (integer-type (specifier-type 'integer)))
1639 (if (and (numeric-type-p number-type)
1640 (csubtypep number-type integer-type)
1641 (numeric-type-p divisor-type)
1642 (csubtypep divisor-type integer-type))
1643 (let ((number-low (numeric-type-low number-type))
1644 (number-high (numeric-type-high number-type))
1645 (divisor-low (numeric-type-low divisor-type))
1646 (divisor-high (numeric-type-high divisor-type)))
1647 (values-specifier-type
1648 `(values ,(integer-truncate-derive-type number-low number-high
1649 divisor-low divisor-high)
1650 ,(integer-rem-derive-type number-low number-high
1651 divisor-low divisor-high))))
1654 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1657 (defun rem-result-type (number-type divisor-type)
1658 ;; Figure out what the remainder type is. The remainder is an
1659 ;; integer if both args are integers; a rational if both args are
1660 ;; rational; and a float otherwise.
1661 (cond ((and (csubtypep number-type (specifier-type 'integer))
1662 (csubtypep divisor-type (specifier-type 'integer)))
1664 ((and (csubtypep number-type (specifier-type 'rational))
1665 (csubtypep divisor-type (specifier-type 'rational)))
1667 ((and (csubtypep number-type (specifier-type 'float))
1668 (csubtypep divisor-type (specifier-type 'float)))
1669 ;; Both are floats so the result is also a float, of
1670 ;; the largest type.
1671 (or (float-format-max (numeric-type-format number-type)
1672 (numeric-type-format divisor-type))
1674 ((and (csubtypep number-type (specifier-type 'float))
1675 (csubtypep divisor-type (specifier-type 'rational)))
1676 ;; One of the arguments is a float and the other is a
1677 ;; rational. The remainder is a float of the same
1679 (or (numeric-type-format number-type) 'float))
1680 ((and (csubtypep divisor-type (specifier-type 'float))
1681 (csubtypep number-type (specifier-type 'rational)))
1682 ;; One of the arguments is a float and the other is a
1683 ;; rational. The remainder is a float of the same
1685 (or (numeric-type-format divisor-type) 'float))
1687 ;; Some unhandled combination. This usually means both args
1688 ;; are REAL so the result is a REAL.
1691 (defun truncate-derive-type-quot (number-type divisor-type)
1692 (let* ((rem-type (rem-result-type number-type divisor-type))
1693 (number-interval (numeric-type->interval number-type))
1694 (divisor-interval (numeric-type->interval divisor-type)))
1695 ;;(declare (type (member '(integer rational float)) rem-type))
1696 ;; We have real numbers now.
1697 (cond ((eq rem-type 'integer)
1698 ;; Since the remainder type is INTEGER, both args are
1700 (let* ((res (integer-truncate-derive-type
1701 (interval-low number-interval)
1702 (interval-high number-interval)
1703 (interval-low divisor-interval)
1704 (interval-high divisor-interval))))
1705 (specifier-type (if (listp res) res 'integer))))
1707 (let ((quot (truncate-quotient-bound
1708 (interval-div number-interval
1709 divisor-interval))))
1710 (specifier-type `(integer ,(or (interval-low quot) '*)
1711 ,(or (interval-high quot) '*))))))))
1713 (defun truncate-derive-type-rem (number-type divisor-type)
1714 (let* ((rem-type (rem-result-type number-type divisor-type))
1715 (number-interval (numeric-type->interval number-type))
1716 (divisor-interval (numeric-type->interval divisor-type))
1717 (rem (truncate-rem-bound number-interval divisor-interval)))
1718 ;;(declare (type (member '(integer rational float)) rem-type))
1719 ;; We have real numbers now.
1720 (cond ((eq rem-type 'integer)
1721 ;; Since the remainder type is INTEGER, both args are
1723 (specifier-type `(,rem-type ,(or (interval-low rem) '*)
1724 ,(or (interval-high rem) '*))))
1726 (multiple-value-bind (class format)
1729 (values 'integer nil))
1731 (values 'rational nil))
1732 ((or single-float double-float #!+long-float long-float)
1733 (values 'float rem-type))
1735 (values 'float nil))
1738 (when (member rem-type '(float single-float double-float
1739 #!+long-float long-float))
1740 (setf rem (interval-func #'(lambda (x)
1741 (coerce-for-bound x rem-type))
1743 (make-numeric-type :class class
1745 :low (interval-low rem)
1746 :high (interval-high rem)))))))
1748 (defun truncate-derive-type-quot-aux (num div same-arg)
1749 (declare (ignore same-arg))
1750 (if (and (numeric-type-real-p num)
1751 (numeric-type-real-p div))
1752 (truncate-derive-type-quot num div)
1755 (defun truncate-derive-type-rem-aux (num div same-arg)
1756 (declare (ignore same-arg))
1757 (if (and (numeric-type-real-p num)
1758 (numeric-type-real-p div))
1759 (truncate-derive-type-rem num div)
1762 (defoptimizer (truncate derive-type) ((number divisor))
1763 (let ((quot (two-arg-derive-type number divisor
1764 #'truncate-derive-type-quot-aux #'truncate))
1765 (rem (two-arg-derive-type number divisor
1766 #'truncate-derive-type-rem-aux #'rem)))
1767 (when (and quot rem)
1768 (make-values-type :required (list quot rem)))))
1770 (defun ftruncate-derive-type-quot (number-type divisor-type)
1771 ;; The bounds are the same as for truncate. However, the first
1772 ;; result is a float of some type. We need to determine what that
1773 ;; type is. Basically it's the more contagious of the two types.
1774 (let ((q-type (truncate-derive-type-quot number-type divisor-type))
1775 (res-type (numeric-contagion number-type divisor-type)))
1776 (make-numeric-type :class 'float
1777 :format (numeric-type-format res-type)
1778 :low (numeric-type-low q-type)
1779 :high (numeric-type-high q-type))))
1781 (defun ftruncate-derive-type-quot-aux (n d same-arg)
1782 (declare (ignore same-arg))
1783 (if (and (numeric-type-real-p n)
1784 (numeric-type-real-p d))
1785 (ftruncate-derive-type-quot n d)
1788 (defoptimizer (ftruncate derive-type) ((number divisor))
1790 (two-arg-derive-type number divisor
1791 #'ftruncate-derive-type-quot-aux #'ftruncate))
1792 (rem (two-arg-derive-type number divisor
1793 #'truncate-derive-type-rem-aux #'rem)))
1794 (when (and quot rem)
1795 (make-values-type :required (list quot rem)))))
1797 (defun %unary-truncate-derive-type-aux (number)
1798 (truncate-derive-type-quot number (specifier-type '(integer 1 1))))
1800 (defoptimizer (%unary-truncate derive-type) ((number))
1801 (one-arg-derive-type number
1802 #'%unary-truncate-derive-type-aux
1805 (defoptimizer (%unary-truncate/single-float derive-type) ((number))
1806 (one-arg-derive-type number
1807 #'%unary-truncate-derive-type-aux
1810 (defoptimizer (%unary-truncate/double-float derive-type) ((number))
1811 (one-arg-derive-type number
1812 #'%unary-truncate-derive-type-aux
1815 (defoptimizer (%unary-ftruncate derive-type) ((number))
1816 (let ((divisor (specifier-type '(integer 1 1))))
1817 (one-arg-derive-type number
1819 (ftruncate-derive-type-quot-aux n divisor nil))
1820 #'%unary-ftruncate)))
1822 (defoptimizer (%unary-round derive-type) ((number))
1823 (one-arg-derive-type number
1826 (unless (numeric-type-real-p n)
1827 (return *empty-type*))
1828 (let* ((interval (numeric-type->interval n))
1829 (low (interval-low interval))
1830 (high (interval-high interval)))
1832 (setf low (car low)))
1834 (setf high (car high)))
1844 ;;; Define optimizers for FLOOR and CEILING.
1846 ((def (name q-name r-name)
1847 (let ((q-aux (symbolicate q-name "-AUX"))
1848 (r-aux (symbolicate r-name "-AUX")))
1850 ;; Compute type of quotient (first) result.
1851 (defun ,q-aux (number-type divisor-type)
1852 (let* ((number-interval
1853 (numeric-type->interval number-type))
1855 (numeric-type->interval divisor-type))
1856 (quot (,q-name (interval-div number-interval
1857 divisor-interval))))
1858 (specifier-type `(integer ,(or (interval-low quot) '*)
1859 ,(or (interval-high quot) '*)))))
1860 ;; Compute type of remainder.
1861 (defun ,r-aux (number-type divisor-type)
1862 (let* ((divisor-interval
1863 (numeric-type->interval divisor-type))
1864 (rem (,r-name divisor-interval))
1865 (result-type (rem-result-type number-type divisor-type)))
1866 (multiple-value-bind (class format)
1869 (values 'integer nil))
1871 (values 'rational nil))
1872 ((or single-float double-float #!+long-float long-float)
1873 (values 'float result-type))
1875 (values 'float nil))
1878 (when (member result-type '(float single-float double-float
1879 #!+long-float long-float))
1880 ;; Make sure that the limits on the interval have
1882 (setf rem (interval-func (lambda (x)
1883 (coerce-for-bound x result-type))
1885 (make-numeric-type :class class
1887 :low (interval-low rem)
1888 :high (interval-high rem)))))
1889 ;; the optimizer itself
1890 (defoptimizer (,name derive-type) ((number divisor))
1891 (flet ((derive-q (n d same-arg)
1892 (declare (ignore same-arg))
1893 (if (and (numeric-type-real-p n)
1894 (numeric-type-real-p d))
1897 (derive-r (n d same-arg)
1898 (declare (ignore same-arg))
1899 (if (and (numeric-type-real-p n)
1900 (numeric-type-real-p d))
1903 (let ((quot (two-arg-derive-type
1904 number divisor #'derive-q #',name))
1905 (rem (two-arg-derive-type
1906 number divisor #'derive-r #'mod)))
1907 (when (and quot rem)
1908 (make-values-type :required (list quot rem))))))))))
1910 (def floor floor-quotient-bound floor-rem-bound)
1911 (def ceiling ceiling-quotient-bound ceiling-rem-bound))
1913 ;;; Define optimizers for FFLOOR and FCEILING
1914 (macrolet ((def (name q-name r-name)
1915 (let ((q-aux (symbolicate "F" q-name "-AUX"))
1916 (r-aux (symbolicate r-name "-AUX")))
1918 ;; Compute type of quotient (first) result.
1919 (defun ,q-aux (number-type divisor-type)
1920 (let* ((number-interval
1921 (numeric-type->interval number-type))
1923 (numeric-type->interval divisor-type))
1924 (quot (,q-name (interval-div number-interval
1926 (res-type (numeric-contagion number-type
1929 :class (numeric-type-class res-type)
1930 :format (numeric-type-format res-type)
1931 :low (interval-low quot)
1932 :high (interval-high quot))))
1934 (defoptimizer (,name derive-type) ((number divisor))
1935 (flet ((derive-q (n d same-arg)
1936 (declare (ignore same-arg))
1937 (if (and (numeric-type-real-p n)
1938 (numeric-type-real-p d))
1941 (derive-r (n d same-arg)
1942 (declare (ignore same-arg))
1943 (if (and (numeric-type-real-p n)
1944 (numeric-type-real-p d))
1947 (let ((quot (two-arg-derive-type
1948 number divisor #'derive-q #',name))
1949 (rem (two-arg-derive-type
1950 number divisor #'derive-r #'mod)))
1951 (when (and quot rem)
1952 (make-values-type :required (list quot rem))))))))))
1954 (def ffloor floor-quotient-bound floor-rem-bound)
1955 (def fceiling ceiling-quotient-bound ceiling-rem-bound))
1957 ;;; functions to compute the bounds on the quotient and remainder for
1958 ;;; the FLOOR function
1959 (defun floor-quotient-bound (quot)
1960 ;; Take the floor of the quotient and then massage it into what we
1962 (let ((lo (interval-low quot))
1963 (hi (interval-high quot)))
1964 ;; Take the floor of the lower bound. The result is always a
1965 ;; closed lower bound.
1967 (floor (type-bound-number lo))
1969 ;; For the upper bound, we need to be careful.
1972 ;; An open bound. We need to be careful here because
1973 ;; the floor of '(10.0) is 9, but the floor of
1975 (multiple-value-bind (q r) (floor (first hi))
1980 ;; A closed bound, so the answer is obvious.
1984 (make-interval :low lo :high hi)))
1985 (defun floor-rem-bound (div)
1986 ;; The remainder depends only on the divisor. Try to get the
1987 ;; correct sign for the remainder if we can.
1988 (case (interval-range-info div)
1990 ;; The divisor is always positive.
1991 (let ((rem (interval-abs div)))
1992 (setf (interval-low rem) 0)
1993 (when (and (numberp (interval-high rem))
1994 (not (zerop (interval-high rem))))
1995 ;; The remainder never contains the upper bound. However,
1996 ;; watch out for the case where the high limit is zero!
1997 (setf (interval-high rem) (list (interval-high rem))))
2000 ;; The divisor is always negative.
2001 (let ((rem (interval-neg (interval-abs div))))
2002 (setf (interval-high rem) 0)
2003 (when (numberp (interval-low rem))
2004 ;; The remainder never contains the lower bound.
2005 (setf (interval-low rem) (list (interval-low rem))))
2008 ;; The divisor can be positive or negative. All bets off. The
2009 ;; magnitude of remainder is the maximum value of the divisor.
2010 (let ((limit (type-bound-number (interval-high (interval-abs div)))))
2011 ;; The bound never reaches the limit, so make the interval open.
2012 (make-interval :low (if limit
2015 :high (list limit))))))
2017 (floor-quotient-bound (make-interval :low 0.3 :high 10.3))
2018 => #S(INTERVAL :LOW 0 :HIGH 10)
2019 (floor-quotient-bound (make-interval :low 0.3 :high '(10.3)))
2020 => #S(INTERVAL :LOW 0 :HIGH 10)
2021 (floor-quotient-bound (make-interval :low 0.3 :high 10))
2022 => #S(INTERVAL :LOW 0 :HIGH 10)
2023 (floor-quotient-bound (make-interval :low 0.3 :high '(10)))
2024 => #S(INTERVAL :LOW 0 :HIGH 9)
2025 (floor-quotient-bound (make-interval :low '(0.3) :high 10.3))
2026 => #S(INTERVAL :LOW 0 :HIGH 10)
2027 (floor-quotient-bound (make-interval :low '(0.0) :high 10.3))
2028 => #S(INTERVAL :LOW 0 :HIGH 10)
2029 (floor-quotient-bound (make-interval :low '(-1.3) :high 10.3))
2030 => #S(INTERVAL :LOW -2 :HIGH 10)
2031 (floor-quotient-bound (make-interval :low '(-1.0) :high 10.3))
2032 => #S(INTERVAL :LOW -1 :HIGH 10)
2033 (floor-quotient-bound (make-interval :low -1.0 :high 10.3))
2034 => #S(INTERVAL :LOW -1 :HIGH 10)
2036 (floor-rem-bound (make-interval :low 0.3 :high 10.3))
2037 => #S(INTERVAL :LOW 0 :HIGH '(10.3))
2038 (floor-rem-bound (make-interval :low 0.3 :high '(10.3)))
2039 => #S(INTERVAL :LOW 0 :HIGH '(10.3))
2040 (floor-rem-bound (make-interval :low -10 :high -2.3))
2041 #S(INTERVAL :LOW (-10) :HIGH 0)
2042 (floor-rem-bound (make-interval :low 0.3 :high 10))
2043 => #S(INTERVAL :LOW 0 :HIGH '(10))
2044 (floor-rem-bound (make-interval :low '(-1.3) :high 10.3))
2045 => #S(INTERVAL :LOW '(-10.3) :HIGH '(10.3))
2046 (floor-rem-bound (make-interval :low '(-20.3) :high 10.3))
2047 => #S(INTERVAL :LOW (-20.3) :HIGH (20.3))
2050 ;;; same functions for CEILING
2051 (defun ceiling-quotient-bound (quot)
2052 ;; Take the ceiling of the quotient and then massage it into what we
2054 (let ((lo (interval-low quot))
2055 (hi (interval-high quot)))
2056 ;; Take the ceiling of the upper bound. The result is always a
2057 ;; closed upper bound.
2059 (ceiling (type-bound-number hi))
2061 ;; For the lower bound, we need to be careful.
2064 ;; An open bound. We need to be careful here because
2065 ;; the ceiling of '(10.0) is 11, but the ceiling of
2067 (multiple-value-bind (q r) (ceiling (first lo))
2072 ;; A closed bound, so the answer is obvious.
2076 (make-interval :low lo :high hi)))
2077 (defun ceiling-rem-bound (div)
2078 ;; The remainder depends only on the divisor. Try to get the
2079 ;; correct sign for the remainder if we can.
2080 (case (interval-range-info div)
2082 ;; Divisor is always positive. The remainder is negative.
2083 (let ((rem (interval-neg (interval-abs div))))
2084 (setf (interval-high rem) 0)
2085 (when (and (numberp (interval-low rem))
2086 (not (zerop (interval-low rem))))
2087 ;; The remainder never contains the upper bound. However,
2088 ;; watch out for the case when the upper bound is zero!
2089 (setf (interval-low rem) (list (interval-low rem))))
2092 ;; Divisor is always negative. The remainder is positive
2093 (let ((rem (interval-abs div)))
2094 (setf (interval-low rem) 0)
2095 (when (numberp (interval-high rem))
2096 ;; The remainder never contains the lower bound.
2097 (setf (interval-high rem) (list (interval-high rem))))
2100 ;; The divisor can be positive or negative. All bets off. The
2101 ;; magnitude of remainder is the maximum value of the divisor.
2102 (let ((limit (type-bound-number (interval-high (interval-abs div)))))
2103 ;; The bound never reaches the limit, so make the interval open.
2104 (make-interval :low (if limit
2107 :high (list limit))))))
2110 (ceiling-quotient-bound (make-interval :low 0.3 :high 10.3))
2111 => #S(INTERVAL :LOW 1 :HIGH 11)
2112 (ceiling-quotient-bound (make-interval :low 0.3 :high '(10.3)))
2113 => #S(INTERVAL :LOW 1 :HIGH 11)
2114 (ceiling-quotient-bound (make-interval :low 0.3 :high 10))
2115 => #S(INTERVAL :LOW 1 :HIGH 10)
2116 (ceiling-quotient-bound (make-interval :low 0.3 :high '(10)))
2117 => #S(INTERVAL :LOW 1 :HIGH 10)
2118 (ceiling-quotient-bound (make-interval :low '(0.3) :high 10.3))
2119 => #S(INTERVAL :LOW 1 :HIGH 11)
2120 (ceiling-quotient-bound (make-interval :low '(0.0) :high 10.3))
2121 => #S(INTERVAL :LOW 1 :HIGH 11)
2122 (ceiling-quotient-bound (make-interval :low '(-1.3) :high 10.3))
2123 => #S(INTERVAL :LOW -1 :HIGH 11)
2124 (ceiling-quotient-bound (make-interval :low '(-1.0) :high 10.3))
2125 => #S(INTERVAL :LOW 0 :HIGH 11)
2126 (ceiling-quotient-bound (make-interval :low -1.0 :high 10.3))
2127 => #S(INTERVAL :LOW -1 :HIGH 11)
2129 (ceiling-rem-bound (make-interval :low 0.3 :high 10.3))
2130 => #S(INTERVAL :LOW (-10.3) :HIGH 0)
2131 (ceiling-rem-bound (make-interval :low 0.3 :high '(10.3)))
2132 => #S(INTERVAL :LOW 0 :HIGH '(10.3))
2133 (ceiling-rem-bound (make-interval :low -10 :high -2.3))
2134 => #S(INTERVAL :LOW 0 :HIGH (10))
2135 (ceiling-rem-bound (make-interval :low 0.3 :high 10))
2136 => #S(INTERVAL :LOW (-10) :HIGH 0)
2137 (ceiling-rem-bound (make-interval :low '(-1.3) :high 10.3))
2138 => #S(INTERVAL :LOW (-10.3) :HIGH (10.3))
2139 (ceiling-rem-bound (make-interval :low '(-20.3) :high 10.3))
2140 => #S(INTERVAL :LOW (-20.3) :HIGH (20.3))
2143 (defun truncate-quotient-bound (quot)
2144 ;; For positive quotients, truncate is exactly like floor. For
2145 ;; negative quotients, truncate is exactly like ceiling. Otherwise,
2146 ;; it's the union of the two pieces.
2147 (case (interval-range-info quot)
2150 (floor-quotient-bound quot))
2152 ;; just like CEILING
2153 (ceiling-quotient-bound quot))
2155 ;; Split the interval into positive and negative pieces, compute
2156 ;; the result for each piece and put them back together.
2157 (destructuring-bind (neg pos) (interval-split 0 quot t t)
2158 (interval-merge-pair (ceiling-quotient-bound neg)
2159 (floor-quotient-bound pos))))))
2161 (defun truncate-rem-bound (num div)
2162 ;; This is significantly more complicated than FLOOR or CEILING. We
2163 ;; need both the number and the divisor to determine the range. The
2164 ;; basic idea is to split the ranges of NUM and DEN into positive
2165 ;; and negative pieces and deal with each of the four possibilities
2167 (case (interval-range-info num)
2169 (case (interval-range-info div)
2171 (floor-rem-bound div))
2173 (ceiling-rem-bound div))
2175 (destructuring-bind (neg pos) (interval-split 0 div t t)
2176 (interval-merge-pair (truncate-rem-bound num neg)
2177 (truncate-rem-bound num pos))))))
2179 (case (interval-range-info div)
2181 (ceiling-rem-bound div))
2183 (floor-rem-bound div))
2185 (destructuring-bind (neg pos) (interval-split 0 div t t)
2186 (interval-merge-pair (truncate-rem-bound num neg)
2187 (truncate-rem-bound num pos))))))
2189 (destructuring-bind (neg pos) (interval-split 0 num t t)
2190 (interval-merge-pair (truncate-rem-bound neg div)
2191 (truncate-rem-bound pos div))))))
2194 ;;; Derive useful information about the range. Returns three values:
2195 ;;; - '+ if its positive, '- negative, or nil if it overlaps 0.
2196 ;;; - The abs of the minimal value (i.e. closest to 0) in the range.
2197 ;;; - The abs of the maximal value if there is one, or nil if it is
2199 (defun numeric-range-info (low high)
2200 (cond ((and low (not (minusp low)))
2201 (values '+ low high))
2202 ((and high (not (plusp high)))
2203 (values '- (- high) (if low (- low) nil)))
2205 (values nil 0 (and low high (max (- low) high))))))
2207 (defun integer-truncate-derive-type
2208 (number-low number-high divisor-low divisor-high)
2209 ;; The result cannot be larger in magnitude than the number, but the
2210 ;; sign might change. If we can determine the sign of either the
2211 ;; number or the divisor, we can eliminate some of the cases.
2212 (multiple-value-bind (number-sign number-min number-max)
2213 (numeric-range-info number-low number-high)
2214 (multiple-value-bind (divisor-sign divisor-min divisor-max)
2215 (numeric-range-info divisor-low divisor-high)
2216 (when (and divisor-max (zerop divisor-max))
2217 ;; We've got a problem: guaranteed division by zero.
2218 (return-from integer-truncate-derive-type t))
2219 (when (zerop divisor-min)
2220 ;; We'll assume that they aren't going to divide by zero.
2222 (cond ((and number-sign divisor-sign)
2223 ;; We know the sign of both.
2224 (if (eq number-sign divisor-sign)
2225 ;; Same sign, so the result will be positive.
2226 `(integer ,(if divisor-max
2227 (truncate number-min divisor-max)
2230 (truncate number-max divisor-min)
2232 ;; Different signs, the result will be negative.
2233 `(integer ,(if number-max
2234 (- (truncate number-max divisor-min))
2237 (- (truncate number-min divisor-max))
2239 ((eq divisor-sign '+)
2240 ;; The divisor is positive. Therefore, the number will just
2241 ;; become closer to zero.
2242 `(integer ,(if number-low
2243 (truncate number-low divisor-min)
2246 (truncate number-high divisor-min)
2248 ((eq divisor-sign '-)
2249 ;; The divisor is negative. Therefore, the absolute value of
2250 ;; the number will become closer to zero, but the sign will also
2252 `(integer ,(if number-high
2253 (- (truncate number-high divisor-min))
2256 (- (truncate number-low divisor-min))
2258 ;; The divisor could be either positive or negative.
2260 ;; The number we are dividing has a bound. Divide that by the
2261 ;; smallest posible divisor.
2262 (let ((bound (truncate number-max divisor-min)))
2263 `(integer ,(- bound) ,bound)))
2265 ;; The number we are dividing is unbounded, so we can't tell
2266 ;; anything about the result.
2269 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2270 (defun integer-rem-derive-type
2271 (number-low number-high divisor-low divisor-high)
2272 (if (and divisor-low divisor-high)
2273 ;; We know the range of the divisor, and the remainder must be
2274 ;; smaller than the divisor. We can tell the sign of the
2275 ;; remainer if we know the sign of the number.
2276 (let ((divisor-max (1- (max (abs divisor-low) (abs divisor-high)))))
2277 `(integer ,(if (or (null number-low)
2278 (minusp number-low))
2281 ,(if (or (null number-high)
2282 (plusp number-high))
2285 ;; The divisor is potentially either very positive or very
2286 ;; negative. Therefore, the remainer is unbounded, but we might
2287 ;; be able to tell something about the sign from the number.
2288 `(integer ,(if (and number-low (not (minusp number-low)))
2289 ;; The number we are dividing is positive.
2290 ;; Therefore, the remainder must be positive.
2293 ,(if (and number-high (not (plusp number-high)))
2294 ;; The number we are dividing is negative.
2295 ;; Therefore, the remainder must be negative.
2299 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2300 (defoptimizer (random derive-type) ((bound &optional state))
2301 (let ((type (lvar-type bound)))
2302 (when (numeric-type-p type)
2303 (let ((class (numeric-type-class type))
2304 (high (numeric-type-high type))
2305 (format (numeric-type-format type)))
2309 :low (coerce 0 (or format class 'real))
2310 :high (cond ((not high) nil)
2311 ((eq class 'integer) (max (1- high) 0))
2312 ((or (consp high) (zerop high)) high)
2315 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2316 (defun random-derive-type-aux (type)
2317 (let ((class (numeric-type-class type))
2318 (high (numeric-type-high type))
2319 (format (numeric-type-format type)))
2323 :low (coerce 0 (or format class 'real))
2324 :high (cond ((not high) nil)
2325 ((eq class 'integer) (max (1- high) 0))
2326 ((or (consp high) (zerop high)) high)
2329 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2330 (defoptimizer (random derive-type) ((bound &optional state))
2331 (one-arg-derive-type bound #'random-derive-type-aux nil))
2333 ;;;; DERIVE-TYPE methods for LOGAND, LOGIOR, and friends
2335 ;;; Return the maximum number of bits an integer of the supplied type
2336 ;;; can take up, or NIL if it is unbounded. The second (third) value
2337 ;;; is T if the integer can be positive (negative) and NIL if not.
2338 ;;; Zero counts as positive.
2339 (defun integer-type-length (type)
2340 (if (numeric-type-p type)
2341 (let ((min (numeric-type-low type))
2342 (max (numeric-type-high type)))
2343 (values (and min max (max (integer-length min) (integer-length max)))
2344 (or (null max) (not (minusp max)))
2345 (or (null min) (minusp min))))
2348 ;;; See _Hacker's Delight_, Henry S. Warren, Jr. pp 58-63 for an
2349 ;;; explanation of LOG{AND,IOR,XOR}-DERIVE-UNSIGNED-{LOW,HIGH}-BOUND.
2350 ;;; Credit also goes to Raymond Toy for writing (and debugging!) similar
2351 ;;; versions in CMUCL, from which these functions copy liberally.
2353 (defun logand-derive-unsigned-low-bound (x y)
2354 (let ((a (numeric-type-low x))
2355 (b (numeric-type-high x))
2356 (c (numeric-type-low y))
2357 (d (numeric-type-high y)))
2358 (loop for m = (ash 1 (integer-length (lognor a c))) then (ash m -1)
2360 (unless (zerop (logand m (lognot a) (lognot c)))
2361 (let ((temp (logandc2 (logior a m) (1- m))))
2365 (setf temp (logandc2 (logior c m) (1- m)))
2369 finally (return (logand a c)))))
2371 (defun logand-derive-unsigned-high-bound (x y)
2372 (let ((a (numeric-type-low x))
2373 (b (numeric-type-high x))
2374 (c (numeric-type-low y))
2375 (d (numeric-type-high y)))
2376 (loop for m = (ash 1 (integer-length (logxor b d))) then (ash m -1)
2379 ((not (zerop (logand b (lognot d) m)))
2380 (let ((temp (logior (logandc2 b m) (1- m))))
2384 ((not (zerop (logand (lognot b) d m)))
2385 (let ((temp (logior (logandc2 d m) (1- m))))
2389 finally (return (logand b d)))))
2391 (defun logand-derive-type-aux (x y &optional same-leaf)
2393 (return-from logand-derive-type-aux x))
2394 (multiple-value-bind (x-len x-pos x-neg) (integer-type-length x)
2395 (declare (ignore x-pos))
2396 (multiple-value-bind (y-len y-pos y-neg) (integer-type-length y)
2397 (declare (ignore y-pos))
2399 ;; X must be positive.
2401 ;; They must both be positive.
2402 (cond ((and (null x-len) (null y-len))
2403 (specifier-type 'unsigned-byte))
2405 (specifier-type `(unsigned-byte* ,y-len)))
2407 (specifier-type `(unsigned-byte* ,x-len)))
2409 (let ((low (logand-derive-unsigned-low-bound x y))
2410 (high (logand-derive-unsigned-high-bound x y)))
2411 (specifier-type `(integer ,low ,high)))))
2412 ;; X is positive, but Y might be negative.
2414 (specifier-type 'unsigned-byte))
2416 (specifier-type `(unsigned-byte* ,x-len)))))
2417 ;; X might be negative.
2419 ;; Y must be positive.
2421 (specifier-type 'unsigned-byte))
2422 (t (specifier-type `(unsigned-byte* ,y-len))))
2423 ;; Either might be negative.
2424 (if (and x-len y-len)
2425 ;; The result is bounded.
2426 (specifier-type `(signed-byte ,(1+ (max x-len y-len))))
2427 ;; We can't tell squat about the result.
2428 (specifier-type 'integer)))))))
2430 (defun logior-derive-unsigned-low-bound (x y)
2431 (let ((a (numeric-type-low x))
2432 (b (numeric-type-high x))
2433 (c (numeric-type-low y))
2434 (d (numeric-type-high y)))
2435 (loop for m = (ash 1 (integer-length (logxor a c))) then (ash m -1)
2438 ((not (zerop (logandc2 (logand c m) a)))
2439 (let ((temp (logand (logior a m) (1+ (lognot m)))))
2443 ((not (zerop (logandc2 (logand a m) c)))
2444 (let ((temp (logand (logior c m) (1+ (lognot m)))))
2448 finally (return (logior a c)))))
2450 (defun logior-derive-unsigned-high-bound (x y)
2451 (let ((a (numeric-type-low x))
2452 (b (numeric-type-high x))
2453 (c (numeric-type-low y))
2454 (d (numeric-type-high y)))
2455 (loop for m = (ash 1 (integer-length (logand b d))) then (ash m -1)
2457 (unless (zerop (logand b d m))
2458 (let ((temp (logior (- b m) (1- m))))
2462 (setf temp (logior (- d m) (1- m)))
2466 finally (return (logior b d)))))
2468 (defun logior-derive-type-aux (x y &optional same-leaf)
2470 (return-from logior-derive-type-aux x))
2471 (multiple-value-bind (x-len x-pos x-neg) (integer-type-length x)
2472 (multiple-value-bind (y-len y-pos y-neg) (integer-type-length y)
2474 ((and (not x-neg) (not y-neg))
2475 ;; Both are positive.
2476 (if (and x-len y-len)
2477 (let ((low (logior-derive-unsigned-low-bound x y))
2478 (high (logior-derive-unsigned-high-bound x y)))
2479 (specifier-type `(integer ,low ,high)))
2480 (specifier-type `(unsigned-byte* *))))
2482 ;; X must be negative.
2484 ;; Both are negative. The result is going to be negative
2485 ;; and be the same length or shorter than the smaller.
2486 (if (and x-len y-len)
2488 (specifier-type `(integer ,(ash -1 (min x-len y-len)) -1))
2490 (specifier-type '(integer * -1)))
2491 ;; X is negative, but we don't know about Y. The result
2492 ;; will be negative, but no more negative than X.
2494 `(integer ,(or (numeric-type-low x) '*)
2497 ;; X might be either positive or negative.
2499 ;; But Y is negative. The result will be negative.
2501 `(integer ,(or (numeric-type-low y) '*)
2503 ;; We don't know squat about either. It won't get any bigger.
2504 (if (and x-len y-len)
2506 (specifier-type `(signed-byte ,(1+ (max x-len y-len))))
2508 (specifier-type 'integer))))))))
2510 (defun logxor-derive-unsigned-low-bound (x y)
2511 (let ((a (numeric-type-low x))
2512 (b (numeric-type-high x))
2513 (c (numeric-type-low y))
2514 (d (numeric-type-high y)))
2515 (loop for m = (ash 1 (integer-length (logxor a c))) then (ash m -1)
2518 ((not (zerop (logandc2 (logand c m) a)))
2519 (let ((temp (logand (logior a m)
2523 ((not (zerop (logandc2 (logand a m) c)))
2524 (let ((temp (logand (logior c m)
2528 finally (return (logxor a c)))))
2530 (defun logxor-derive-unsigned-high-bound (x y)
2531 (let ((a (numeric-type-low x))
2532 (b (numeric-type-high x))
2533 (c (numeric-type-low y))
2534 (d (numeric-type-high y)))
2535 (loop for m = (ash 1 (integer-length (logand b d))) then (ash m -1)
2537 (unless (zerop (logand b d m))
2538 (let ((temp (logior (- b m) (1- m))))
2540 ((>= temp a) (setf b temp))
2541 (t (let ((temp (logior (- d m) (1- m))))
2544 finally (return (logxor b d)))))
2546 (defun logxor-derive-type-aux (x y &optional same-leaf)
2548 (return-from logxor-derive-type-aux (specifier-type '(eql 0))))
2549 (multiple-value-bind (x-len x-pos x-neg) (integer-type-length x)
2550 (multiple-value-bind (y-len y-pos y-neg) (integer-type-length y)
2552 ((and (not x-neg) (not y-neg))
2553 ;; Both are positive
2554 (if (and x-len y-len)
2555 (let ((low (logxor-derive-unsigned-low-bound x y))
2556 (high (logxor-derive-unsigned-high-bound x y)))
2557 (specifier-type `(integer ,low ,high)))
2558 (specifier-type '(unsigned-byte* *))))
2559 ((and (not x-pos) (not y-pos))
2560 ;; Both are negative. The result will be positive, and as long
2562 (specifier-type `(unsigned-byte* ,(if (and x-len y-len)
2565 ((or (and (not x-pos) (not y-neg))
2566 (and (not y-pos) (not x-neg)))
2567 ;; Either X is negative and Y is positive or vice-versa. The
2568 ;; result will be negative.
2569 (specifier-type `(integer ,(if (and x-len y-len)
2570 (ash -1 (max x-len y-len))
2573 ;; We can't tell what the sign of the result is going to be.
2574 ;; All we know is that we don't create new bits.
2576 (specifier-type `(signed-byte ,(1+ (max x-len y-len)))))
2578 (specifier-type 'integer))))))
2580 (macrolet ((deffrob (logfun)
2581 (let ((fun-aux (symbolicate logfun "-DERIVE-TYPE-AUX")))
2582 `(defoptimizer (,logfun derive-type) ((x y))
2583 (two-arg-derive-type x y #',fun-aux #',logfun)))))
2588 (defoptimizer (logeqv derive-type) ((x y))
2589 (two-arg-derive-type x y (lambda (x y same-leaf)
2590 (lognot-derive-type-aux
2591 (logxor-derive-type-aux x y same-leaf)))
2593 (defoptimizer (lognand derive-type) ((x y))
2594 (two-arg-derive-type x y (lambda (x y same-leaf)
2595 (lognot-derive-type-aux
2596 (logand-derive-type-aux x y same-leaf)))
2598 (defoptimizer (lognor derive-type) ((x y))
2599 (two-arg-derive-type x y (lambda (x y same-leaf)
2600 (lognot-derive-type-aux
2601 (logior-derive-type-aux x y same-leaf)))
2603 (defoptimizer (logandc1 derive-type) ((x y))
2604 (two-arg-derive-type x y (lambda (x y same-leaf)
2606 (specifier-type '(eql 0))
2607 (logand-derive-type-aux
2608 (lognot-derive-type-aux x) y nil)))
2610 (defoptimizer (logandc2 derive-type) ((x y))
2611 (two-arg-derive-type x y (lambda (x y same-leaf)
2613 (specifier-type '(eql 0))
2614 (logand-derive-type-aux
2615 x (lognot-derive-type-aux y) nil)))
2617 (defoptimizer (logorc1 derive-type) ((x y))
2618 (two-arg-derive-type x y (lambda (x y same-leaf)
2620 (specifier-type '(eql -1))
2621 (logior-derive-type-aux
2622 (lognot-derive-type-aux x) y nil)))
2624 (defoptimizer (logorc2 derive-type) ((x y))
2625 (two-arg-derive-type x y (lambda (x y same-leaf)
2627 (specifier-type '(eql -1))
2628 (logior-derive-type-aux
2629 x (lognot-derive-type-aux y) nil)))
2632 ;;;; miscellaneous derive-type methods
2634 (defoptimizer (integer-length derive-type) ((x))
2635 (let ((x-type (lvar-type x)))
2636 (when (numeric-type-p x-type)
2637 ;; If the X is of type (INTEGER LO HI), then the INTEGER-LENGTH
2638 ;; of X is (INTEGER (MIN lo hi) (MAX lo hi), basically. Be
2639 ;; careful about LO or HI being NIL, though. Also, if 0 is
2640 ;; contained in X, the lower bound is obviously 0.
2641 (flet ((null-or-min (a b)
2642 (and a b (min (integer-length a)
2643 (integer-length b))))
2645 (and a b (max (integer-length a)
2646 (integer-length b)))))
2647 (let* ((min (numeric-type-low x-type))
2648 (max (numeric-type-high x-type))
2649 (min-len (null-or-min min max))
2650 (max-len (null-or-max min max)))
2651 (when (ctypep 0 x-type)
2653 (specifier-type `(integer ,(or min-len '*) ,(or max-len '*))))))))
2655 (defoptimizer (isqrt derive-type) ((x))
2656 (let ((x-type (lvar-type x)))
2657 (when (numeric-type-p x-type)
2658 (let* ((lo (numeric-type-low x-type))
2659 (hi (numeric-type-high x-type))
2660 (lo-res (if lo (isqrt lo) '*))
2661 (hi-res (if hi (isqrt hi) '*)))
2662 (specifier-type `(integer ,lo-res ,hi-res))))))
2664 (defoptimizer (char-code derive-type) ((char))
2665 (let ((type (type-intersection (lvar-type char) (specifier-type 'character))))
2666 (cond ((member-type-p type)
2669 ,@(loop for member in (member-type-members type)
2670 when (characterp member)
2671 collect (char-code member)))))
2672 ((sb!kernel::character-set-type-p type)
2675 ,@(loop for (low . high)
2676 in (character-set-type-pairs type)
2677 collect `(integer ,low ,high)))))
2678 ((csubtypep type (specifier-type 'base-char))
2680 `(mod ,base-char-code-limit)))
2683 `(mod ,char-code-limit))))))
2685 (defoptimizer (code-char derive-type) ((code))
2686 (let ((type (lvar-type code)))
2687 ;; FIXME: unions of integral ranges? It ought to be easier to do
2688 ;; this, given that CHARACTER-SET is basically an integral range
2689 ;; type. -- CSR, 2004-10-04
2690 (when (numeric-type-p type)
2691 (let* ((lo (numeric-type-low type))
2692 (hi (numeric-type-high type))
2693 (type (specifier-type `(character-set ((,lo . ,hi))))))
2695 ;; KLUDGE: when running on the host, we lose a slight amount
2696 ;; of precision so that we don't have to "unparse" types
2697 ;; that formally we can't, such as (CHARACTER-SET ((0
2698 ;; . 0))). -- CSR, 2004-10-06
2700 ((csubtypep type (specifier-type 'standard-char)) type)
2702 ((csubtypep type (specifier-type 'base-char))
2703 (specifier-type 'base-char))
2705 ((csubtypep type (specifier-type 'extended-char))
2706 (specifier-type 'extended-char))
2707 (t #+sb-xc-host (specifier-type 'character)
2708 #-sb-xc-host type))))))
2710 (defoptimizer (values derive-type) ((&rest values))
2711 (make-values-type :required (mapcar #'lvar-type values)))
2713 (defun signum-derive-type-aux (type)
2714 (if (eq (numeric-type-complexp type) :complex)
2715 (let* ((format (case (numeric-type-class type)
2716 ((integer rational) 'single-float)
2717 (t (numeric-type-format type))))
2718 (bound-format (or format 'float)))
2719 (make-numeric-type :class 'float
2722 :low (coerce -1 bound-format)
2723 :high (coerce 1 bound-format)))
2724 (let* ((interval (numeric-type->interval type))
2725 (range-info (interval-range-info interval))
2726 (contains-0-p (interval-contains-p 0 interval))
2727 (class (numeric-type-class type))
2728 (format (numeric-type-format type))
2729 (one (coerce 1 (or format class 'real)))
2730 (zero (coerce 0 (or format class 'real)))
2731 (minus-one (coerce -1 (or format class 'real)))
2732 (plus (make-numeric-type :class class :format format
2733 :low one :high one))
2734 (minus (make-numeric-type :class class :format format
2735 :low minus-one :high minus-one))
2736 ;; KLUDGE: here we have a fairly horrible hack to deal
2737 ;; with the schizophrenia in the type derivation engine.
2738 ;; The problem is that the type derivers reinterpret
2739 ;; numeric types as being exact; so (DOUBLE-FLOAT 0d0
2740 ;; 0d0) within the derivation mechanism doesn't include
2741 ;; -0d0. Ugh. So force it in here, instead.
2742 (zero (make-numeric-type :class class :format format
2743 :low (- zero) :high zero)))
2745 (+ (if contains-0-p (type-union plus zero) plus))
2746 (- (if contains-0-p (type-union minus zero) minus))
2747 (t (type-union minus zero plus))))))
2749 (defoptimizer (signum derive-type) ((num))
2750 (one-arg-derive-type num #'signum-derive-type-aux nil))
2752 ;;;; byte operations
2754 ;;;; We try to turn byte operations into simple logical operations.
2755 ;;;; First, we convert byte specifiers into separate size and position
2756 ;;;; arguments passed to internal %FOO functions. We then attempt to
2757 ;;;; transform the %FOO functions into boolean operations when the
2758 ;;;; size and position are constant and the operands are fixnums.
2760 (macrolet (;; Evaluate body with SIZE-VAR and POS-VAR bound to
2761 ;; expressions that evaluate to the SIZE and POSITION of
2762 ;; the byte-specifier form SPEC. We may wrap a let around
2763 ;; the result of the body to bind some variables.
2765 ;; If the spec is a BYTE form, then bind the vars to the
2766 ;; subforms. otherwise, evaluate SPEC and use the BYTE-SIZE
2767 ;; and BYTE-POSITION. The goal of this transformation is to
2768 ;; avoid consing up byte specifiers and then immediately
2769 ;; throwing them away.
2770 (with-byte-specifier ((size-var pos-var spec) &body body)
2771 (once-only ((spec `(macroexpand ,spec))
2773 `(if (and (consp ,spec)
2774 (eq (car ,spec) 'byte)
2775 (= (length ,spec) 3))
2776 (let ((,size-var (second ,spec))
2777 (,pos-var (third ,spec)))
2779 (let ((,size-var `(byte-size ,,temp))
2780 (,pos-var `(byte-position ,,temp)))
2781 `(let ((,,temp ,,spec))
2784 (define-source-transform ldb (spec int)
2785 (with-byte-specifier (size pos spec)
2786 `(%ldb ,size ,pos ,int)))
2788 (define-source-transform dpb (newbyte spec int)
2789 (with-byte-specifier (size pos spec)
2790 `(%dpb ,newbyte ,size ,pos ,int)))
2792 (define-source-transform mask-field (spec int)
2793 (with-byte-specifier (size pos spec)
2794 `(%mask-field ,size ,pos ,int)))
2796 (define-source-transform deposit-field (newbyte spec int)
2797 (with-byte-specifier (size pos spec)
2798 `(%deposit-field ,newbyte ,size ,pos ,int))))
2800 (defoptimizer (%ldb derive-type) ((size posn num))
2801 (let ((size (lvar-type size)))
2802 (if (and (numeric-type-p size)
2803 (csubtypep size (specifier-type 'integer)))
2804 (let ((size-high (numeric-type-high size)))
2805 (if (and size-high (<= size-high sb!vm:n-word-bits))
2806 (specifier-type `(unsigned-byte* ,size-high))
2807 (specifier-type 'unsigned-byte)))
2810 (defoptimizer (%mask-field derive-type) ((size posn num))
2811 (let ((size (lvar-type size))
2812 (posn (lvar-type posn)))
2813 (if (and (numeric-type-p size)
2814 (csubtypep size (specifier-type 'integer))
2815 (numeric-type-p posn)
2816 (csubtypep posn (specifier-type 'integer)))
2817 (let ((size-high (numeric-type-high size))
2818 (posn-high (numeric-type-high posn)))
2819 (if (and size-high posn-high
2820 (<= (+ size-high posn-high) sb!vm:n-word-bits))
2821 (specifier-type `(unsigned-byte* ,(+ size-high posn-high)))
2822 (specifier-type 'unsigned-byte)))
2825 (defun %deposit-field-derive-type-aux (size posn int)
2826 (let ((size (lvar-type size))
2827 (posn (lvar-type posn))
2828 (int (lvar-type int)))
2829 (when (and (numeric-type-p size)
2830 (numeric-type-p posn)
2831 (numeric-type-p int))
2832 (let ((size-high (numeric-type-high size))
2833 (posn-high (numeric-type-high posn))
2834 (high (numeric-type-high int))
2835 (low (numeric-type-low int)))
2836 (when (and size-high posn-high high low
2837 ;; KLUDGE: we need this cutoff here, otherwise we
2838 ;; will merrily derive the type of %DPB as
2839 ;; (UNSIGNED-BYTE 1073741822), and then attempt to
2840 ;; canonicalize this type to (INTEGER 0 (1- (ASH 1
2841 ;; 1073741822))), with hilarious consequences. We
2842 ;; cutoff at 4*SB!VM:N-WORD-BITS to allow inference
2843 ;; over a reasonable amount of shifting, even on
2844 ;; the alpha/32 port, where N-WORD-BITS is 32 but
2845 ;; machine integers are 64-bits. -- CSR,
2847 (<= (+ size-high posn-high) (* 4 sb!vm:n-word-bits)))
2848 (let ((raw-bit-count (max (integer-length high)
2849 (integer-length low)
2850 (+ size-high posn-high))))
2853 `(signed-byte ,(1+ raw-bit-count))
2854 `(unsigned-byte* ,raw-bit-count)))))))))
2856 (defoptimizer (%dpb derive-type) ((newbyte size posn int))
2857 (%deposit-field-derive-type-aux size posn int))
2859 (defoptimizer (%deposit-field derive-type) ((newbyte size posn int))
2860 (%deposit-field-derive-type-aux size posn int))
2862 (deftransform %ldb ((size posn int)
2863 (fixnum fixnum integer)
2864 (unsigned-byte #.sb!vm:n-word-bits))
2865 "convert to inline logical operations"
2866 `(logand (ash int (- posn))
2867 (ash ,(1- (ash 1 sb!vm:n-word-bits))
2868 (- size ,sb!vm:n-word-bits))))
2870 (deftransform %mask-field ((size posn int)
2871 (fixnum fixnum integer)
2872 (unsigned-byte #.sb!vm:n-word-bits))
2873 "convert to inline logical operations"
2875 (ash (ash ,(1- (ash 1 sb!vm:n-word-bits))
2876 (- size ,sb!vm:n-word-bits))
2879 ;;; Note: for %DPB and %DEPOSIT-FIELD, we can't use
2880 ;;; (OR (SIGNED-BYTE N) (UNSIGNED-BYTE N))
2881 ;;; as the result type, as that would allow result types that cover
2882 ;;; the range -2^(n-1) .. 1-2^n, instead of allowing result types of
2883 ;;; (UNSIGNED-BYTE N) and result types of (SIGNED-BYTE N).
2885 (deftransform %dpb ((new size posn int)
2887 (unsigned-byte #.sb!vm:n-word-bits))
2888 "convert to inline logical operations"
2889 `(let ((mask (ldb (byte size 0) -1)))
2890 (logior (ash (logand new mask) posn)
2891 (logand int (lognot (ash mask posn))))))
2893 (deftransform %dpb ((new size posn int)
2895 (signed-byte #.sb!vm:n-word-bits))
2896 "convert to inline logical operations"
2897 `(let ((mask (ldb (byte size 0) -1)))
2898 (logior (ash (logand new mask) posn)
2899 (logand int (lognot (ash mask posn))))))
2901 (deftransform %deposit-field ((new size posn int)
2903 (unsigned-byte #.sb!vm:n-word-bits))
2904 "convert to inline logical operations"
2905 `(let ((mask (ash (ldb (byte size 0) -1) posn)))
2906 (logior (logand new mask)
2907 (logand int (lognot mask)))))
2909 (deftransform %deposit-field ((new size posn int)
2911 (signed-byte #.sb!vm:n-word-bits))
2912 "convert to inline logical operations"
2913 `(let ((mask (ash (ldb (byte size 0) -1) posn)))
2914 (logior (logand new mask)
2915 (logand int (lognot mask)))))
2917 (defoptimizer (mask-signed-field derive-type) ((size x))
2918 (let ((size (lvar-type size)))
2919 (if (numeric-type-p size)
2920 (let ((size-high (numeric-type-high size)))
2921 (if (and size-high (<= 1 size-high sb!vm:n-word-bits))
2922 (specifier-type `(signed-byte ,size-high))
2927 ;;; Modular functions
2929 ;;; (ldb (byte s 0) (foo x y ...)) =
2930 ;;; (ldb (byte s 0) (foo (ldb (byte s 0) x) y ...))
2932 ;;; and similar for other arguments.
2934 (defun make-modular-fun-type-deriver (prototype kind width signedp)
2935 (declare (ignore kind))
2937 (binding* ((info (info :function :info prototype) :exit-if-null)
2938 (fun (fun-info-derive-type info) :exit-if-null)
2939 (mask-type (specifier-type
2941 ((nil) (let ((mask (1- (ash 1 width))))
2942 `(integer ,mask ,mask)))
2943 ((t) `(signed-byte ,width))))))
2945 (let ((res (funcall fun call)))
2947 (if (eq signedp nil)
2948 (logand-derive-type-aux res mask-type))))))
2951 (binding* ((info (info :function :info prototype) :exit-if-null)
2952 (fun (fun-info-derive-type info) :exit-if-null)
2953 (res (funcall fun call) :exit-if-null)
2954 (mask-type (specifier-type
2956 ((nil) (let ((mask (1- (ash 1 width))))
2957 `(integer ,mask ,mask)))
2958 ((t) `(signed-byte ,width))))))
2959 (if (eq signedp nil)
2960 (logand-derive-type-aux res mask-type)))))
2962 ;;; Try to recursively cut all uses of LVAR to WIDTH bits.
2964 ;;; For good functions, we just recursively cut arguments; their
2965 ;;; "goodness" means that the result will not increase (in the
2966 ;;; (unsigned-byte +infinity) sense). An ordinary modular function is
2967 ;;; replaced with the version, cutting its result to WIDTH or more
2968 ;;; bits. For most functions (e.g. for +) we cut all arguments; for
2969 ;;; others (e.g. for ASH) we have "optimizers", cutting only necessary
2970 ;;; arguments (maybe to a different width) and returning the name of a
2971 ;;; modular version, if it exists, or NIL. If we have changed
2972 ;;; anything, we need to flush old derived types, because they have
2973 ;;; nothing in common with the new code.
2974 (defun cut-to-width (lvar kind width signedp)
2975 (declare (type lvar lvar) (type (integer 0) width))
2976 (let ((type (specifier-type (if (zerop width)
2979 ((nil) 'unsigned-byte)
2982 (labels ((reoptimize-node (node name)
2983 (setf (node-derived-type node)
2985 (info :function :type name)))
2986 (setf (lvar-%derived-type (node-lvar node)) nil)
2987 (setf (node-reoptimize node) t)
2988 (setf (block-reoptimize (node-block node)) t)
2989 (reoptimize-component (node-component node) :maybe))
2990 (cut-node (node &aux did-something)
2991 (when (and (not (block-delete-p (node-block node)))
2992 (combination-p node)
2993 (eq (basic-combination-kind node) :known))
2994 (let* ((fun-ref (lvar-use (combination-fun node)))
2995 (fun-name (leaf-source-name (ref-leaf fun-ref)))
2996 (modular-fun (find-modular-version fun-name kind signedp width)))
2997 (when (and modular-fun
2998 (not (and (eq fun-name 'logand)
3000 (single-value-type (node-derived-type node))
3002 (binding* ((name (etypecase modular-fun
3003 ((eql :good) fun-name)
3005 (modular-fun-info-name modular-fun))
3007 (funcall modular-fun node width)))
3009 (unless (eql modular-fun :good)
3010 (setq did-something t)
3013 (find-free-fun name "in a strange place"))
3014 (setf (combination-kind node) :full))
3015 (unless (functionp modular-fun)
3016 (dolist (arg (basic-combination-args node))
3017 (when (cut-lvar arg)
3018 (setq did-something t))))
3020 (reoptimize-node node name))
3022 (cut-lvar (lvar &aux did-something)
3023 (do-uses (node lvar)
3024 (when (cut-node node)
3025 (setq did-something t)))
3029 (defun best-modular-version (width signedp)
3030 ;; 1. exact width-matched :untagged
3031 ;; 2. >/>= width-matched :tagged
3032 ;; 3. >/>= width-matched :untagged
3033 (let* ((uuwidths (modular-class-widths *untagged-unsigned-modular-class*))
3034 (uswidths (modular-class-widths *untagged-signed-modular-class*))
3035 (uwidths (merge 'list uuwidths uswidths #'< :key #'car))
3036 (twidths (modular-class-widths *tagged-modular-class*)))
3037 (let ((exact (find (cons width signedp) uwidths :test #'equal)))
3039 (return-from best-modular-version (values width :untagged signedp))))
3040 (flet ((inexact-match (w)
3042 ((eq signedp (cdr w)) (<= width (car w)))
3043 ((eq signedp nil) (< width (car w))))))
3044 (let ((tgt (find-if #'inexact-match twidths)))
3046 (return-from best-modular-version
3047 (values (car tgt) :tagged (cdr tgt)))))
3048 (let ((ugt (find-if #'inexact-match uwidths)))
3050 (return-from best-modular-version
3051 (values (car ugt) :untagged (cdr ugt))))))))
3053 (defoptimizer (logand optimizer) ((x y) node)
3054 (let ((result-type (single-value-type (node-derived-type node))))
3055 (when (numeric-type-p result-type)
3056 (let ((low (numeric-type-low result-type))
3057 (high (numeric-type-high result-type)))
3058 (when (and (numberp low)
3061 (let ((width (integer-length high)))
3062 (multiple-value-bind (w kind signedp)
3063 (best-modular-version width nil)
3065 ;; FIXME: This should be (CUT-TO-WIDTH NODE KIND WIDTH SIGNEDP).
3066 (cut-to-width x kind width signedp)
3067 (cut-to-width y kind width signedp)
3068 nil ; After fixing above, replace with T.
3071 (defoptimizer (mask-signed-field optimizer) ((width x) node)
3072 (let ((result-type (single-value-type (node-derived-type node))))
3073 (when (numeric-type-p result-type)
3074 (let ((low (numeric-type-low result-type))
3075 (high (numeric-type-high result-type)))
3076 (when (and (numberp low) (numberp high))
3077 (let ((width (max (integer-length high) (integer-length low))))
3078 (multiple-value-bind (w kind)
3079 (best-modular-version width t)
3081 ;; FIXME: This should be (CUT-TO-WIDTH NODE KIND WIDTH T).
3082 (cut-to-width x kind width t)
3083 nil ; After fixing above, replace with T.
3086 ;;; miscellanous numeric transforms
3088 ;;; If a constant appears as the first arg, swap the args.
3089 (deftransform commutative-arg-swap ((x y) * * :defun-only t :node node)
3090 (if (and (constant-lvar-p x)
3091 (not (constant-lvar-p y)))
3092 `(,(lvar-fun-name (basic-combination-fun node))
3095 (give-up-ir1-transform)))
3097 (dolist (x '(= char= + * logior logand logxor))
3098 (%deftransform x '(function * *) #'commutative-arg-swap
3099 "place constant arg last"))
3101 ;;; Handle the case of a constant BOOLE-CODE.
3102 (deftransform boole ((op x y) * *)
3103 "convert to inline logical operations"
3104 (unless (constant-lvar-p op)
3105 (give-up-ir1-transform "BOOLE code is not a constant."))
3106 (let ((control (lvar-value op)))
3108 (#.sb!xc:boole-clr 0)
3109 (#.sb!xc:boole-set -1)
3110 (#.sb!xc:boole-1 'x)
3111 (#.sb!xc:boole-2 'y)
3112 (#.sb!xc:boole-c1 '(lognot x))
3113 (#.sb!xc:boole-c2 '(lognot y))
3114 (#.sb!xc:boole-and '(logand x y))
3115 (#.sb!xc:boole-ior '(logior x y))
3116 (#.sb!xc:boole-xor '(logxor x y))
3117 (#.sb!xc:boole-eqv '(logeqv x y))
3118 (#.sb!xc:boole-nand '(lognand x y))
3119 (#.sb!xc:boole-nor '(lognor x y))
3120 (#.sb!xc:boole-andc1 '(logandc1 x y))
3121 (#.sb!xc:boole-andc2 '(logandc2 x y))
3122 (#.sb!xc:boole-orc1 '(logorc1 x y))
3123 (#.sb!xc:boole-orc2 '(logorc2 x y))
3125 (abort-ir1-transform "~S is an illegal control arg to BOOLE."
3128 ;;;; converting special case multiply/divide to shifts
3130 ;;; If arg is a constant power of two, turn * into a shift.
3131 (deftransform * ((x y) (integer integer) *)
3132 "convert x*2^k to shift"
3133 (unless (constant-lvar-p y)
3134 (give-up-ir1-transform))
3135 (let* ((y (lvar-value y))
3137 (len (1- (integer-length y-abs))))
3138 (unless (and (> y-abs 0) (= y-abs (ash 1 len)))
3139 (give-up-ir1-transform))
3144 ;;; If arg is a constant power of two, turn FLOOR into a shift and
3145 ;;; mask. If CEILING, add in (1- (ABS Y)), do FLOOR and correct a
3147 (flet ((frob (y ceil-p)
3148 (unless (constant-lvar-p y)
3149 (give-up-ir1-transform))
3150 (let* ((y (lvar-value y))
3152 (len (1- (integer-length y-abs))))
3153 (unless (and (> y-abs 0) (= y-abs (ash 1 len)))
3154 (give-up-ir1-transform))
3155 (let ((shift (- len))
3157 (delta (if ceil-p (* (signum y) (1- y-abs)) 0)))
3158 `(let ((x (+ x ,delta)))
3160 `(values (ash (- x) ,shift)
3161 (- (- (logand (- x) ,mask)) ,delta))
3162 `(values (ash x ,shift)
3163 (- (logand x ,mask) ,delta))))))))
3164 (deftransform floor ((x y) (integer integer) *)
3165 "convert division by 2^k to shift"
3167 (deftransform ceiling ((x y) (integer integer) *)
3168 "convert division by 2^k to shift"
3171 ;;; Do the same for MOD.
3172 (deftransform mod ((x y) (integer integer) *)
3173 "convert remainder mod 2^k to LOGAND"
3174 (unless (constant-lvar-p y)
3175 (give-up-ir1-transform))
3176 (let* ((y (lvar-value y))
3178 (len (1- (integer-length y-abs))))
3179 (unless (and (> y-abs 0) (= y-abs (ash 1 len)))
3180 (give-up-ir1-transform))
3181 (let ((mask (1- y-abs)))
3183 `(- (logand (- x) ,mask))
3184 `(logand x ,mask)))))
3186 ;;; If arg is a constant power of two, turn TRUNCATE into a shift and mask.
3187 (deftransform truncate ((x y) (integer integer))
3188 "convert division by 2^k to shift"
3189 (unless (constant-lvar-p y)
3190 (give-up-ir1-transform))
3191 (let* ((y (lvar-value y))
3193 (len (1- (integer-length y-abs))))
3194 (unless (and (> y-abs 0) (= y-abs (ash 1 len)))
3195 (give-up-ir1-transform))
3196 (let* ((shift (- len))
3199 (values ,(if (minusp y)
3201 `(- (ash (- x) ,shift)))
3202 (- (logand (- x) ,mask)))
3203 (values ,(if (minusp y)
3204 `(ash (- ,mask x) ,shift)
3206 (logand x ,mask))))))
3208 ;;; And the same for REM.
3209 (deftransform rem ((x y) (integer integer) *)
3210 "convert remainder mod 2^k to LOGAND"
3211 (unless (constant-lvar-p y)
3212 (give-up-ir1-transform))
3213 (let* ((y (lvar-value y))
3215 (len (1- (integer-length y-abs))))
3216 (unless (and (> y-abs 0) (= y-abs (ash 1 len)))
3217 (give-up-ir1-transform))
3218 (let ((mask (1- y-abs)))
3220 (- (logand (- x) ,mask))
3221 (logand x ,mask)))))
3223 ;;;; arithmetic and logical identity operation elimination
3225 ;;; Flush calls to various arith functions that convert to the
3226 ;;; identity function or a constant.
3227 (macrolet ((def (name identity result)
3228 `(deftransform ,name ((x y) (* (constant-arg (member ,identity))) *)
3229 "fold identity operations"
3236 (def logxor -1 (lognot x))
3239 (deftransform logand ((x y) (* (constant-arg t)) *)
3240 "fold identity operation"
3241 (let ((y (lvar-value y)))
3242 (unless (and (plusp y)
3243 (= y (1- (ash 1 (integer-length y)))))
3244 (give-up-ir1-transform))
3245 (unless (csubtypep (lvar-type x)
3246 (specifier-type `(integer 0 ,y)))
3247 (give-up-ir1-transform))
3250 (deftransform mask-signed-field ((size x) ((constant-arg t) *) *)
3251 "fold identity operation"
3252 (let ((size (lvar-value size)))
3253 (unless (csubtypep (lvar-type x) (specifier-type `(signed-byte ,size)))
3254 (give-up-ir1-transform))
3257 ;;; These are restricted to rationals, because (- 0 0.0) is 0.0, not -0.0, and
3258 ;;; (* 0 -4.0) is -0.0.
3259 (deftransform - ((x y) ((constant-arg (member 0)) rational) *)
3260 "convert (- 0 x) to negate"
3262 (deftransform * ((x y) (rational (constant-arg (member 0))) *)
3263 "convert (* x 0) to 0"
3266 ;;; Return T if in an arithmetic op including lvars X and Y, the
3267 ;;; result type is not affected by the type of X. That is, Y is at
3268 ;;; least as contagious as X.
3270 (defun not-more-contagious (x y)
3271 (declare (type continuation x y))
3272 (let ((x (lvar-type x))
3274 (values (type= (numeric-contagion x y)
3275 (numeric-contagion y y)))))
3276 ;;; Patched version by Raymond Toy. dtc: Should be safer although it
3277 ;;; XXX needs more work as valid transforms are missed; some cases are
3278 ;;; specific to particular transform functions so the use of this
3279 ;;; function may need a re-think.
3280 (defun not-more-contagious (x y)
3281 (declare (type lvar x y))
3282 (flet ((simple-numeric-type (num)
3283 (and (numeric-type-p num)
3284 ;; Return non-NIL if NUM is integer, rational, or a float
3285 ;; of some type (but not FLOAT)
3286 (case (numeric-type-class num)
3290 (numeric-type-format num))
3293 (let ((x (lvar-type x))
3295 (if (and (simple-numeric-type x)
3296 (simple-numeric-type y))
3297 (values (type= (numeric-contagion x y)
3298 (numeric-contagion y y)))))))
3300 (def!type exact-number ()
3301 '(or rational (complex rational)))
3305 ;;; Only safely applicable for exact numbers. For floating-point
3306 ;;; x, one would have to first show that neither x or y are signed
3307 ;;; 0s, and that x isn't an SNaN.
3308 (deftransform + ((x y) (exact-number (constant-arg (eql 0))) *)
3313 (deftransform - ((x y) (exact-number (constant-arg (eql 0))) *)
3317 ;;; Fold (OP x +/-1)
3319 ;;; %NEGATE might not always signal correctly.
3321 ((def (name result minus-result)
3322 `(deftransform ,name ((x y)
3323 (exact-number (constant-arg (member 1 -1))))
3324 "fold identity operations"
3325 (if (minusp (lvar-value y)) ',minus-result ',result))))
3326 (def * x (%negate x))
3327 (def / x (%negate x))
3328 (def expt x (/ 1 x)))
3330 ;;; Fold (expt x n) into multiplications for small integral values of
3331 ;;; N; convert (expt x 1/2) to sqrt.
3332 (deftransform expt ((x y) (t (constant-arg real)) *)
3333 "recode as multiplication or sqrt"
3334 (let ((val (lvar-value y)))
3335 ;; If Y would cause the result to be promoted to the same type as
3336 ;; Y, we give up. If not, then the result will be the same type
3337 ;; as X, so we can replace the exponentiation with simple
3338 ;; multiplication and division for small integral powers.
3339 (unless (not-more-contagious y x)
3340 (give-up-ir1-transform))
3342 (let ((x-type (lvar-type x)))
3343 (cond ((csubtypep x-type (specifier-type '(or rational
3344 (complex rational))))
3346 ((csubtypep x-type (specifier-type 'real))
3350 ((csubtypep x-type (specifier-type 'complex))
3351 ;; both parts are float
3353 (t (give-up-ir1-transform)))))
3354 ((= val 2) '(* x x))
3355 ((= val -2) '(/ (* x x)))
3356 ((= val 3) '(* x x x))
3357 ((= val -3) '(/ (* x x x)))
3358 ((= val 1/2) '(sqrt x))
3359 ((= val -1/2) '(/ (sqrt x)))
3360 (t (give-up-ir1-transform)))))
3362 (deftransform expt ((x y) ((constant-arg (member -1 -1.0 -1.0d0)) integer) *)
3363 "recode as an ODDP check"
3364 (let ((val (lvar-value x)))
3366 '(- 1 (* 2 (logand 1 y)))
3371 ;;; KLUDGE: Shouldn't (/ 0.0 0.0), etc. cause exceptions in these
3372 ;;; transformations?
3373 ;;; Perhaps we should have to prove that the denominator is nonzero before
3374 ;;; doing them? -- WHN 19990917
3375 (macrolet ((def (name)
3376 `(deftransform ,name ((x y) ((constant-arg (integer 0 0)) integer)
3383 (macrolet ((def (name)
3384 `(deftransform ,name ((x y) ((constant-arg (integer 0 0)) integer)
3393 ;;;; character operations
3395 (deftransform char-equal ((a b) (base-char base-char))
3397 '(let* ((ac (char-code a))
3399 (sum (logxor ac bc)))
3401 (when (eql sum #x20)
3402 (let ((sum (+ ac bc)))
3403 (or (and (> sum 161) (< sum 213))
3404 (and (> sum 415) (< sum 461))
3405 (and (> sum 463) (< sum 477))))))))
3407 (deftransform char-upcase ((x) (base-char))
3409 '(let ((n-code (char-code x)))
3410 (if (or (and (> n-code #o140) ; Octal 141 is #\a.
3411 (< n-code #o173)) ; Octal 172 is #\z.
3412 (and (> n-code #o337)
3414 (and (> n-code #o367)
3416 (code-char (logxor #x20 n-code))
3419 (deftransform char-downcase ((x) (base-char))
3421 '(let ((n-code (char-code x)))
3422 (if (or (and (> n-code 64) ; 65 is #\A.
3423 (< n-code 91)) ; 90 is #\Z.
3428 (code-char (logxor #x20 n-code))
3431 ;;;; equality predicate transforms
3433 ;;; Return true if X and Y are lvars whose only use is a
3434 ;;; reference to the same leaf, and the value of the leaf cannot
3436 (defun same-leaf-ref-p (x y)
3437 (declare (type lvar x y))
3438 (let ((x-use (principal-lvar-use x))
3439 (y-use (principal-lvar-use y)))
3442 (eq (ref-leaf x-use) (ref-leaf y-use))
3443 (constant-reference-p x-use))))
3445 ;;; If X and Y are the same leaf, then the result is true. Otherwise,
3446 ;;; if there is no intersection between the types of the arguments,
3447 ;;; then the result is definitely false.
3448 (deftransform simple-equality-transform ((x y) * *
3451 ((same-leaf-ref-p x y) t)
3452 ((not (types-equal-or-intersect (lvar-type x) (lvar-type y)))
3454 (t (give-up-ir1-transform))))
3457 `(%deftransform ',x '(function * *) #'simple-equality-transform)))
3461 ;;; This is similar to SIMPLE-EQUALITY-TRANSFORM, except that we also
3462 ;;; try to convert to a type-specific predicate or EQ:
3463 ;;; -- If both args are characters, convert to CHAR=. This is better than
3464 ;;; just converting to EQ, since CHAR= may have special compilation
3465 ;;; strategies for non-standard representations, etc.
3466 ;;; -- If either arg is definitely a fixnum, we check to see if X is
3467 ;;; constant and if so, put X second. Doing this results in better
3468 ;;; code from the backend, since the backend assumes that any constant
3469 ;;; argument comes second.
3470 ;;; -- If either arg is definitely not a number or a fixnum, then we
3471 ;;; can compare with EQ.
3472 ;;; -- Otherwise, we try to put the arg we know more about second. If X
3473 ;;; is constant then we put it second. If X is a subtype of Y, we put
3474 ;;; it second. These rules make it easier for the back end to match
3475 ;;; these interesting cases.
3476 (deftransform eql ((x y) * * :node node)
3477 "convert to simpler equality predicate"
3478 (let ((x-type (lvar-type x))
3479 (y-type (lvar-type y))
3480 (char-type (specifier-type 'character)))
3481 (flet ((fixnum-type-p (type)
3482 (csubtypep type (specifier-type 'fixnum))))
3484 ((same-leaf-ref-p x y) t)
3485 ((not (types-equal-or-intersect x-type y-type))
3487 ((and (csubtypep x-type char-type)
3488 (csubtypep y-type char-type))
3490 ((or (fixnum-type-p x-type) (fixnum-type-p y-type))
3491 (commutative-arg-swap node))
3492 ((or (eq-comparable-type-p x-type) (eq-comparable-type-p y-type))
3494 ((and (not (constant-lvar-p y))
3495 (or (constant-lvar-p x)
3496 (and (csubtypep x-type y-type)
3497 (not (csubtypep y-type x-type)))))
3500 (give-up-ir1-transform))))))
3502 ;;; similarly to the EQL transform above, we attempt to constant-fold
3503 ;;; or convert to a simpler predicate: mostly we have to be careful
3504 ;;; with strings and bit-vectors.
3505 (deftransform equal ((x y) * *)
3506 "convert to simpler equality predicate"
3507 (let ((x-type (lvar-type x))
3508 (y-type (lvar-type y))
3509 (string-type (specifier-type 'string))
3510 (bit-vector-type (specifier-type 'bit-vector)))
3512 ((same-leaf-ref-p x y) t)
3513 ((and (csubtypep x-type string-type)
3514 (csubtypep y-type string-type))
3516 ((and (csubtypep x-type bit-vector-type)
3517 (csubtypep y-type bit-vector-type))
3518 '(bit-vector-= x y))
3519 ;; if at least one is not a string, and at least one is not a
3520 ;; bit-vector, then we can reason from types.
3521 ((and (not (and (types-equal-or-intersect x-type string-type)
3522 (types-equal-or-intersect y-type string-type)))
3523 (not (and (types-equal-or-intersect x-type bit-vector-type)
3524 (types-equal-or-intersect y-type bit-vector-type)))
3525 (not (types-equal-or-intersect x-type y-type)))
3527 (t (give-up-ir1-transform)))))
3529 ;;; Convert to EQL if both args are rational and complexp is specified
3530 ;;; and the same for both.
3531 (deftransform = ((x y) (number number) *)
3533 (let ((x-type (lvar-type x))
3534 (y-type (lvar-type y)))
3535 (cond ((or (and (csubtypep x-type (specifier-type 'float))
3536 (csubtypep y-type (specifier-type 'float)))
3537 (and (csubtypep x-type (specifier-type '(complex float)))
3538 (csubtypep y-type (specifier-type '(complex float))))
3539 #!+complex-float-vops
3540 (and (csubtypep x-type (specifier-type '(or single-float (complex single-float))))
3541 (csubtypep y-type (specifier-type '(or single-float (complex single-float)))))
3542 #!+complex-float-vops
3543 (and (csubtypep x-type (specifier-type '(or double-float (complex double-float))))
3544 (csubtypep y-type (specifier-type '(or double-float (complex double-float))))))
3545 ;; They are both floats. Leave as = so that -0.0 is
3546 ;; handled correctly.
3547 (give-up-ir1-transform))
3548 ((or (and (csubtypep x-type (specifier-type 'rational))
3549 (csubtypep y-type (specifier-type 'rational)))
3550 (and (csubtypep x-type
3551 (specifier-type '(complex rational)))
3553 (specifier-type '(complex rational)))))
3554 ;; They are both rationals and complexp is the same.
3558 (give-up-ir1-transform
3559 "The operands might not be the same type.")))))
3561 (defun maybe-float-lvar-p (lvar)
3562 (neq *empty-type* (type-intersection (specifier-type 'float)
3565 (flet ((maybe-invert (node op inverted x y)
3566 ;; Don't invert if either argument can be a float (NaNs)
3568 ((or (maybe-float-lvar-p x) (maybe-float-lvar-p y))
3569 (delay-ir1-transform node :constraint)
3570 `(or (,op x y) (= x y)))
3572 `(if (,inverted x y) nil t)))))
3573 (deftransform >= ((x y) (number number) * :node node)
3574 "invert or open code"
3575 (maybe-invert node '> '< x y))
3576 (deftransform <= ((x y) (number number) * :node node)
3577 "invert or open code"
3578 (maybe-invert node '< '> x y)))
3580 ;;; See whether we can statically determine (< X Y) using type
3581 ;;; information. If X's high bound is < Y's low, then X < Y.
3582 ;;; Similarly, if X's low is >= to Y's high, the X >= Y (so return
3583 ;;; NIL). If not, at least make sure any constant arg is second.
3584 (macrolet ((def (name inverse reflexive-p surely-true surely-false)
3585 `(deftransform ,name ((x y))
3586 "optimize using intervals"
3587 (if (and (same-leaf-ref-p x y)
3588 ;; For non-reflexive functions we don't need
3589 ;; to worry about NaNs: (non-ref-op NaN NaN) => false,
3590 ;; but with reflexive ones we don't know...
3592 '((and (not (maybe-float-lvar-p x))
3593 (not (maybe-float-lvar-p y))))))
3595 (let ((ix (or (type-approximate-interval (lvar-type x))
3596 (give-up-ir1-transform)))
3597 (iy (or (type-approximate-interval (lvar-type y))
3598 (give-up-ir1-transform))))
3603 ((and (constant-lvar-p x)
3604 (not (constant-lvar-p y)))
3607 (give-up-ir1-transform))))))))
3608 (def = = t (interval-= ix iy) (interval-/= ix iy))
3609 (def /= /= nil (interval-/= ix iy) (interval-= ix iy))
3610 (def < > nil (interval-< ix iy) (interval->= ix iy))
3611 (def > < nil (interval-< iy ix) (interval->= iy ix))
3612 (def <= >= t (interval->= iy ix) (interval-< iy ix))
3613 (def >= <= t (interval->= ix iy) (interval-< ix iy)))
3615 (defun ir1-transform-char< (x y first second inverse)
3617 ((same-leaf-ref-p x y) nil)
3618 ;; If we had interval representation of character types, as we
3619 ;; might eventually have to to support 2^21 characters, then here
3620 ;; we could do some compile-time computation as in transforms for
3621 ;; < above. -- CSR, 2003-07-01
3622 ((and (constant-lvar-p first)
3623 (not (constant-lvar-p second)))
3625 (t (give-up-ir1-transform))))
3627 (deftransform char< ((x y) (character character) *)
3628 (ir1-transform-char< x y x y 'char>))
3630 (deftransform char> ((x y) (character character) *)
3631 (ir1-transform-char< y x x y 'char<))
3633 ;;;; converting N-arg comparisons
3635 ;;;; We convert calls to N-arg comparison functions such as < into
3636 ;;;; two-arg calls. This transformation is enabled for all such
3637 ;;;; comparisons in this file. If any of these predicates are not
3638 ;;;; open-coded, then the transformation should be removed at some
3639 ;;;; point to avoid pessimization.
3641 ;;; This function is used for source transformation of N-arg
3642 ;;; comparison functions other than inequality. We deal both with
3643 ;;; converting to two-arg calls and inverting the sense of the test,
3644 ;;; if necessary. If the call has two args, then we pass or return a
3645 ;;; negated test as appropriate. If it is a degenerate one-arg call,
3646 ;;; then we transform to code that returns true. Otherwise, we bind
3647 ;;; all the arguments and expand into a bunch of IFs.
3648 (defun multi-compare (predicate args not-p type &optional force-two-arg-p)
3649 (let ((nargs (length args)))
3650 (cond ((< nargs 1) (values nil t))
3651 ((= nargs 1) `(progn (the ,type ,@args) t))
3654 `(if (,predicate ,(first args) ,(second args)) nil t)
3656 `(,predicate ,(first args) ,(second args))
3659 (do* ((i (1- nargs) (1- i))
3661 (current (gensym) (gensym))
3662 (vars (list current) (cons current vars))
3664 `(if (,predicate ,current ,last)
3666 `(if (,predicate ,current ,last)
3669 `((lambda ,vars (declare (type ,type ,@vars)) ,result)
3672 (define-source-transform = (&rest args) (multi-compare '= args nil 'number))
3673 (define-source-transform < (&rest args) (multi-compare '< args nil 'real))
3674 (define-source-transform > (&rest args) (multi-compare '> args nil 'real))
3675 ;;; We cannot do the inversion for >= and <= here, since both
3676 ;;; (< NaN X) and (> NaN X)
3677 ;;; are false, and we don't have type-inforation available yet. The
3678 ;;; deftransforms for two-argument versions of >= and <= takes care of
3679 ;;; the inversion to > and < when possible.
3680 (define-source-transform <= (&rest args) (multi-compare '<= args nil 'real))
3681 (define-source-transform >= (&rest args) (multi-compare '>= args nil 'real))
3683 (define-source-transform char= (&rest args) (multi-compare 'char= args nil
3685 (define-source-transform char< (&rest args) (multi-compare 'char< args nil
3687 (define-source-transform char> (&rest args) (multi-compare 'char> args nil
3689 (define-source-transform char<= (&rest args) (multi-compare 'char> args t
3691 (define-source-transform char>= (&rest args) (multi-compare 'char< args t
3694 (define-source-transform char-equal (&rest args)
3695 (multi-compare 'sb!impl::two-arg-char-equal args nil 'character t))
3696 (define-source-transform char-lessp (&rest args)
3697 (multi-compare 'sb!impl::two-arg-char-lessp args nil 'character t))
3698 (define-source-transform char-greaterp (&rest args)
3699 (multi-compare 'sb!impl::two-arg-char-greaterp args nil 'character t))
3700 (define-source-transform char-not-greaterp (&rest args)
3701 (multi-compare 'sb!impl::two-arg-char-greaterp args t 'character t))
3702 (define-source-transform char-not-lessp (&rest args)
3703 (multi-compare 'sb!impl::two-arg-char-lessp args t 'character t))
3705 ;;; This function does source transformation of N-arg inequality
3706 ;;; functions such as /=. This is similar to MULTI-COMPARE in the <3
3707 ;;; arg cases. If there are more than two args, then we expand into
3708 ;;; the appropriate n^2 comparisons only when speed is important.
3709 (declaim (ftype (function (symbol list t) *) multi-not-equal))
3710 (defun multi-not-equal (predicate args type)
3711 (let ((nargs (length args)))
3712 (cond ((< nargs 1) (values nil t))
3713 ((= nargs 1) `(progn (the ,type ,@args) t))
3715 `(if (,predicate ,(first args) ,(second args)) nil t))
3716 ((not (policy *lexenv*
3717 (and (>= speed space)
3718 (>= speed compilation-speed))))
3721 (let ((vars (make-gensym-list nargs)))
3722 (do ((var vars next)
3723 (next (cdr vars) (cdr next))
3726 `((lambda ,vars (declare (type ,type ,@vars)) ,result)
3728 (let ((v1 (first var)))
3730 (setq result `(if (,predicate ,v1 ,v2) nil ,result))))))))))
3732 (define-source-transform /= (&rest args)
3733 (multi-not-equal '= args 'number))
3734 (define-source-transform char/= (&rest args)
3735 (multi-not-equal 'char= args 'character))
3736 (define-source-transform char-not-equal (&rest args)
3737 (multi-not-equal 'char-equal args 'character))
3739 ;;; Expand MAX and MIN into the obvious comparisons.
3740 (define-source-transform max (arg0 &rest rest)
3741 (once-only ((arg0 arg0))
3743 `(values (the real ,arg0))
3744 `(let ((maxrest (max ,@rest)))
3745 (if (>= ,arg0 maxrest) ,arg0 maxrest)))))
3746 (define-source-transform min (arg0 &rest rest)
3747 (once-only ((arg0 arg0))
3749 `(values (the real ,arg0))
3750 `(let ((minrest (min ,@rest)))
3751 (if (<= ,arg0 minrest) ,arg0 minrest)))))
3753 ;;;; converting N-arg arithmetic functions
3755 ;;;; N-arg arithmetic and logic functions are associated into two-arg
3756 ;;;; versions, and degenerate cases are flushed.
3758 ;;; Left-associate FIRST-ARG and MORE-ARGS using FUNCTION.
3759 (declaim (ftype (function (symbol t list) list) associate-args))
3760 (defun associate-args (function first-arg more-args)
3761 (let ((next (rest more-args))
3762 (arg (first more-args)))
3764 `(,function ,first-arg ,arg)
3765 (associate-args function `(,function ,first-arg ,arg) next))))
3767 ;;; Do source transformations for transitive functions such as +.
3768 ;;; One-arg cases are replaced with the arg and zero arg cases with
3769 ;;; the identity. ONE-ARG-RESULT-TYPE is, if non-NIL, the type to
3770 ;;; ensure (with THE) that the argument in one-argument calls is.
3771 (defun source-transform-transitive (fun args identity
3772 &optional one-arg-result-type)
3773 (declare (symbol fun) (list args))
3776 (1 (if one-arg-result-type
3777 `(values (the ,one-arg-result-type ,(first args)))
3778 `(values ,(first args))))
3781 (associate-args fun (first args) (rest args)))))
3783 (define-source-transform + (&rest args)
3784 (source-transform-transitive '+ args 0 'number))
3785 (define-source-transform * (&rest args)
3786 (source-transform-transitive '* args 1 'number))
3787 (define-source-transform logior (&rest args)
3788 (source-transform-transitive 'logior args 0 'integer))
3789 (define-source-transform logxor (&rest args)
3790 (source-transform-transitive 'logxor args 0 'integer))
3791 (define-source-transform logand (&rest args)
3792 (source-transform-transitive 'logand args -1 'integer))
3793 (define-source-transform logeqv (&rest args)
3794 (source-transform-transitive 'logeqv args -1 'integer))
3796 ;;; Note: we can't use SOURCE-TRANSFORM-TRANSITIVE for GCD and LCM
3797 ;;; because when they are given one argument, they return its absolute
3800 (define-source-transform gcd (&rest args)
3803 (1 `(abs (the integer ,(first args))))
3805 (t (associate-args 'gcd (first args) (rest args)))))
3807 (define-source-transform lcm (&rest args)
3810 (1 `(abs (the integer ,(first args))))
3812 (t (associate-args 'lcm (first args) (rest args)))))
3814 ;;; Do source transformations for intransitive n-arg functions such as
3815 ;;; /. With one arg, we form the inverse. With two args we pass.
3816 ;;; Otherwise we associate into two-arg calls.
3817 (declaim (ftype (function (symbol list t)
3818 (values list &optional (member nil t)))
3819 source-transform-intransitive))
3820 (defun source-transform-intransitive (function args inverse)
3822 ((0 2) (values nil t))
3823 (1 `(,@inverse ,(first args)))
3824 (t (associate-args function (first args) (rest args)))))
3826 (define-source-transform - (&rest args)
3827 (source-transform-intransitive '- args '(%negate)))
3828 (define-source-transform / (&rest args)
3829 (source-transform-intransitive '/ args '(/ 1)))
3831 ;;;; transforming APPLY
3833 ;;; We convert APPLY into MULTIPLE-VALUE-CALL so that the compiler
3834 ;;; only needs to understand one kind of variable-argument call. It is
3835 ;;; more efficient to convert APPLY to MV-CALL than MV-CALL to APPLY.
3836 (define-source-transform apply (fun arg &rest more-args)
3837 (let ((args (cons arg more-args)))
3838 `(multiple-value-call ,fun
3839 ,@(mapcar (lambda (x)
3842 (values-list ,(car (last args))))))
3844 ;;;; transforming FORMAT
3846 ;;;; If the control string is a compile-time constant, then replace it
3847 ;;;; with a use of the FORMATTER macro so that the control string is
3848 ;;;; ``compiled.'' Furthermore, if the destination is either a stream
3849 ;;;; or T and the control string is a function (i.e. FORMATTER), then
3850 ;;;; convert the call to FORMAT to just a FUNCALL of that function.
3852 ;;; for compile-time argument count checking.
3854 ;;; FIXME II: In some cases, type information could be correlated; for
3855 ;;; instance, ~{ ... ~} requires a list argument, so if the lvar-type
3856 ;;; of a corresponding argument is known and does not intersect the
3857 ;;; list type, a warning could be signalled.
3858 (defun check-format-args (string args fun)
3859 (declare (type string string))
3860 (unless (typep string 'simple-string)
3861 (setq string (coerce string 'simple-string)))
3862 (multiple-value-bind (min max)
3863 (handler-case (sb!format:%compiler-walk-format-string string args)
3864 (sb!format:format-error (c)
3865 (compiler-warn "~A" c)))
3867 (let ((nargs (length args)))
3870 (warn 'format-too-few-args-warning
3872 "Too few arguments (~D) to ~S ~S: requires at least ~D."
3873 :format-arguments (list nargs fun string min)))
3875 (warn 'format-too-many-args-warning
3877 "Too many arguments (~D) to ~S ~S: uses at most ~D."
3878 :format-arguments (list nargs fun string max))))))))
3880 (defoptimizer (format optimizer) ((dest control &rest args))
3881 (when (constant-lvar-p control)
3882 (let ((x (lvar-value control)))
3884 (check-format-args x args 'format)))))
3886 ;;; We disable this transform in the cross-compiler to save memory in
3887 ;;; the target image; most of the uses of FORMAT in the compiler are for
3888 ;;; error messages, and those don't need to be particularly fast.
3890 (deftransform format ((dest control &rest args) (t simple-string &rest t) *
3891 :policy (>= speed space))
3892 (unless (constant-lvar-p control)
3893 (give-up-ir1-transform "The control string is not a constant."))
3894 (let ((arg-names (make-gensym-list (length args))))
3895 `(lambda (dest control ,@arg-names)
3896 (declare (ignore control))
3897 (format dest (formatter ,(lvar-value control)) ,@arg-names))))
3899 (deftransform format ((stream control &rest args) (stream function &rest t))
3900 (let ((arg-names (make-gensym-list (length args))))
3901 `(lambda (stream control ,@arg-names)
3902 (funcall control stream ,@arg-names)
3905 (deftransform format ((tee control &rest args) ((member t) function &rest t))
3906 (let ((arg-names (make-gensym-list (length args))))
3907 `(lambda (tee control ,@arg-names)
3908 (declare (ignore tee))
3909 (funcall control *standard-output* ,@arg-names)
3912 (deftransform pathname ((pathspec) (pathname) *)
3915 (deftransform pathname ((pathspec) (string) *)
3916 '(values (parse-namestring pathspec)))
3920 `(defoptimizer (,name optimizer) ((control &rest args))
3921 (when (constant-lvar-p control)
3922 (let ((x (lvar-value control)))
3924 (check-format-args x args ',name)))))))
3927 #+sb-xc-host ; Only we should be using these
3930 (def compiler-error)
3932 (def compiler-style-warn)
3933 (def compiler-notify)
3934 (def maybe-compiler-notify)
3937 (defoptimizer (cerror optimizer) ((report control &rest args))
3938 (when (and (constant-lvar-p control)
3939 (constant-lvar-p report))
3940 (let ((x (lvar-value control))
3941 (y (lvar-value report)))
3942 (when (and (stringp x) (stringp y))
3943 (multiple-value-bind (min1 max1)
3945 (sb!format:%compiler-walk-format-string x args)
3946 (sb!format:format-error (c)
3947 (compiler-warn "~A" c)))
3949 (multiple-value-bind (min2 max2)
3951 (sb!format:%compiler-walk-format-string y args)
3952 (sb!format:format-error (c)
3953 (compiler-warn "~A" c)))
3955 (let ((nargs (length args)))
3957 ((< nargs (min min1 min2))
3958 (warn 'format-too-few-args-warning
3960 "Too few arguments (~D) to ~S ~S ~S: ~
3961 requires at least ~D."
3963 (list nargs 'cerror y x (min min1 min2))))
3964 ((> nargs (max max1 max2))
3965 (warn 'format-too-many-args-warning
3967 "Too many arguments (~D) to ~S ~S ~S: ~
3970 (list nargs 'cerror y x (max max1 max2))))))))))))))
3972 (defoptimizer (coerce derive-type) ((value type) node)
3974 ((constant-lvar-p type)
3975 ;; This branch is essentially (RESULT-TYPE-SPECIFIER-NTH-ARG 2),
3976 ;; but dealing with the niggle that complex canonicalization gets
3977 ;; in the way: (COERCE 1 'COMPLEX) returns 1, which is not of
3979 (let* ((specifier (lvar-value type))
3980 (result-typeoid (careful-specifier-type specifier)))
3982 ((null result-typeoid) nil)
3983 ((csubtypep result-typeoid (specifier-type 'number))
3984 ;; the difficult case: we have to cope with ANSI 12.1.5.3
3985 ;; Rule of Canonical Representation for Complex Rationals,
3986 ;; which is a truly nasty delivery to field.
3988 ((csubtypep result-typeoid (specifier-type 'real))
3989 ;; cleverness required here: it would be nice to deduce
3990 ;; that something of type (INTEGER 2 3) coerced to type
3991 ;; DOUBLE-FLOAT should return (DOUBLE-FLOAT 2.0d0 3.0d0).
3992 ;; FLOAT gets its own clause because it's implemented as
3993 ;; a UNION-TYPE, so we don't catch it in the NUMERIC-TYPE
3996 ((and (numeric-type-p result-typeoid)
3997 (eq (numeric-type-complexp result-typeoid) :real))
3998 ;; FIXME: is this clause (a) necessary or (b) useful?
4000 ((or (csubtypep result-typeoid
4001 (specifier-type '(complex single-float)))
4002 (csubtypep result-typeoid
4003 (specifier-type '(complex double-float)))
4005 (csubtypep result-typeoid
4006 (specifier-type '(complex long-float))))
4007 ;; float complex types are never canonicalized.
4010 ;; if it's not a REAL, or a COMPLEX FLOAToid, it's
4011 ;; probably just a COMPLEX or equivalent. So, in that
4012 ;; case, we will return a complex or an object of the
4013 ;; provided type if it's rational:
4014 (type-union result-typeoid
4015 (type-intersection (lvar-type value)
4016 (specifier-type 'rational))))))
4017 ((and (policy node (zerop safety))
4018 (csubtypep result-typeoid (specifier-type '(array * (*)))))
4019 ;; At zero safety the deftransform for COERCE can elide dimension
4020 ;; checks for the things like (COERCE X '(SIMPLE-VECTOR 5)) -- so we
4021 ;; need to simplify the type to drop the dimension information.
4022 (let ((vtype (simplify-vector-type result-typeoid)))
4024 (specifier-type vtype)
4029 ;; OK, the result-type argument isn't constant. However, there
4030 ;; are common uses where we can still do better than just
4031 ;; *UNIVERSAL-TYPE*: e.g. (COERCE X (ARRAY-ELEMENT-TYPE Y)),
4032 ;; where Y is of a known type. See messages on cmucl-imp
4033 ;; 2001-02-14 and sbcl-devel 2002-12-12. We only worry here
4034 ;; about types that can be returned by (ARRAY-ELEMENT-TYPE Y), on
4035 ;; the basis that it's unlikely that other uses are both
4036 ;; time-critical and get to this branch of the COND (non-constant
4037 ;; second argument to COERCE). -- CSR, 2002-12-16
4038 (let ((value-type (lvar-type value))
4039 (type-type (lvar-type type)))
4041 ((good-cons-type-p (cons-type)
4042 ;; Make sure the cons-type we're looking at is something
4043 ;; we're prepared to handle which is basically something
4044 ;; that array-element-type can return.
4045 (or (and (member-type-p cons-type)
4046 (eql 1 (member-type-size cons-type))
4047 (null (first (member-type-members cons-type))))
4048 (let ((car-type (cons-type-car-type cons-type)))
4049 (and (member-type-p car-type)
4050 (eql 1 (member-type-members car-type))
4051 (let ((elt (first (member-type-members car-type))))
4055 (numberp (first elt)))))
4056 (good-cons-type-p (cons-type-cdr-type cons-type))))))
4057 (unconsify-type (good-cons-type)
4058 ;; Convert the "printed" respresentation of a cons
4059 ;; specifier into a type specifier. That is, the
4060 ;; specifier (CONS (EQL SIGNED-BYTE) (CONS (EQL 16)
4061 ;; NULL)) is converted to (SIGNED-BYTE 16).
4062 (cond ((or (null good-cons-type)
4063 (eq good-cons-type 'null))
4065 ((and (eq (first good-cons-type) 'cons)
4066 (eq (first (second good-cons-type)) 'member))
4067 `(,(second (second good-cons-type))
4068 ,@(unconsify-type (caddr good-cons-type))))))
4069 (coerceable-p (part)
4070 ;; Can the value be coerced to the given type? Coerce is
4071 ;; complicated, so we don't handle every possible case
4072 ;; here---just the most common and easiest cases:
4074 ;; * Any REAL can be coerced to a FLOAT type.
4075 ;; * Any NUMBER can be coerced to a (COMPLEX
4076 ;; SINGLE/DOUBLE-FLOAT).
4078 ;; FIXME I: we should also be able to deal with characters
4081 ;; FIXME II: I'm not sure that anything is necessary
4082 ;; here, at least while COMPLEX is not a specialized
4083 ;; array element type in the system. Reasoning: if
4084 ;; something cannot be coerced to the requested type, an
4085 ;; error will be raised (and so any downstream compiled
4086 ;; code on the assumption of the returned type is
4087 ;; unreachable). If something can, then it will be of
4088 ;; the requested type, because (by assumption) COMPLEX
4089 ;; (and other difficult types like (COMPLEX INTEGER)
4090 ;; aren't specialized types.
4091 (let ((coerced-type (careful-specifier-type part)))
4093 (or (and (csubtypep coerced-type (specifier-type 'float))
4094 (csubtypep value-type (specifier-type 'real)))
4095 (and (csubtypep coerced-type
4096 (specifier-type `(or (complex single-float)
4097 (complex double-float))))
4098 (csubtypep value-type (specifier-type 'number)))))))
4099 (process-types (type)
4100 ;; FIXME: This needs some work because we should be able
4101 ;; to derive the resulting type better than just the
4102 ;; type arg of coerce. That is, if X is (INTEGER 10
4103 ;; 20), then (COERCE X 'DOUBLE-FLOAT) should say
4104 ;; (DOUBLE-FLOAT 10d0 20d0) instead of just
4106 (cond ((member-type-p type)
4109 (mapc-member-type-members
4111 (if (coerceable-p member)
4112 (push member members)
4113 (return-from punt *universal-type*)))
4115 (specifier-type `(or ,@members)))))
4116 ((and (cons-type-p type)
4117 (good-cons-type-p type))
4118 (let ((c-type (unconsify-type (type-specifier type))))
4119 (if (coerceable-p c-type)
4120 (specifier-type c-type)
4123 *universal-type*))))
4124 (cond ((union-type-p type-type)
4125 (apply #'type-union (mapcar #'process-types
4126 (union-type-types type-type))))
4127 ((or (member-type-p type-type)
4128 (cons-type-p type-type))
4129 (process-types type-type))
4131 *universal-type*)))))))
4133 (defoptimizer (compile derive-type) ((nameoid function))
4134 (when (csubtypep (lvar-type nameoid)
4135 (specifier-type 'null))
4136 (values-specifier-type '(values function boolean boolean))))
4138 ;;; FIXME: Maybe also STREAM-ELEMENT-TYPE should be given some loving
4139 ;;; treatment along these lines? (See discussion in COERCE DERIVE-TYPE
4140 ;;; optimizer, above).
4141 (defoptimizer (array-element-type derive-type) ((array))
4142 (let ((array-type (lvar-type array)))
4143 (labels ((consify (list)
4146 `(cons (eql ,(car list)) ,(consify (rest list)))))
4147 (get-element-type (a)
4149 (type-specifier (array-type-specialized-element-type a))))
4150 (cond ((eq element-type '*)
4151 (specifier-type 'type-specifier))
4152 ((symbolp element-type)
4153 (make-member-type :members (list element-type)))
4154 ((consp element-type)
4155 (specifier-type (consify element-type)))
4157 (error "can't understand type ~S~%" element-type))))))
4158 (labels ((recurse (type)
4159 (cond ((array-type-p type)
4160 (get-element-type type))
4161 ((union-type-p type)
4163 (mapcar #'recurse (union-type-types type))))
4165 *universal-type*))))
4166 (recurse array-type)))))
4168 (define-source-transform sb!impl::sort-vector (vector start end predicate key)
4169 ;; Like CMU CL, we use HEAPSORT. However, other than that, this code
4170 ;; isn't really related to the CMU CL code, since instead of trying
4171 ;; to generalize the CMU CL code to allow START and END values, this
4172 ;; code has been written from scratch following Chapter 7 of
4173 ;; _Introduction to Algorithms_ by Corman, Rivest, and Shamir.
4174 `(macrolet ((%index (x) `(truly-the index ,x))
4175 (%parent (i) `(ash ,i -1))
4176 (%left (i) `(%index (ash ,i 1)))
4177 (%right (i) `(%index (1+ (ash ,i 1))))
4180 (left (%left i) (%left i)))
4181 ((> left current-heap-size))
4182 (declare (type index i left))
4183 (let* ((i-elt (%elt i))
4184 (i-key (funcall keyfun i-elt))
4185 (left-elt (%elt left))
4186 (left-key (funcall keyfun left-elt)))
4187 (multiple-value-bind (large large-elt large-key)
4188 (if (funcall ,',predicate i-key left-key)
4189 (values left left-elt left-key)
4190 (values i i-elt i-key))
4191 (let ((right (%right i)))
4192 (multiple-value-bind (largest largest-elt)
4193 (if (> right current-heap-size)
4194 (values large large-elt)
4195 (let* ((right-elt (%elt right))
4196 (right-key (funcall keyfun right-elt)))
4197 (if (funcall ,',predicate large-key right-key)
4198 (values right right-elt)
4199 (values large large-elt))))
4200 (cond ((= largest i)
4203 (setf (%elt i) largest-elt
4204 (%elt largest) i-elt
4206 (%sort-vector (keyfun &optional (vtype 'vector))
4207 `(macrolet (;; KLUDGE: In SBCL ca. 0.6.10, I had
4208 ;; trouble getting type inference to
4209 ;; propagate all the way through this
4210 ;; tangled mess of inlining. The TRULY-THE
4211 ;; here works around that. -- WHN
4213 `(aref (truly-the ,',vtype ,',',vector)
4214 (%index (+ (%index ,i) start-1)))))
4215 (let (;; Heaps prefer 1-based addressing.
4216 (start-1 (1- ,',start))
4217 (current-heap-size (- ,',end ,',start))
4219 (declare (type (integer -1 #.(1- sb!xc:most-positive-fixnum))
4221 (declare (type index current-heap-size))
4222 (declare (type function keyfun))
4223 (loop for i of-type index
4224 from (ash current-heap-size -1) downto 1 do
4227 (when (< current-heap-size 2)
4229 (rotatef (%elt 1) (%elt current-heap-size))
4230 (decf current-heap-size)
4232 (if (typep ,vector 'simple-vector)
4233 ;; (VECTOR T) is worth optimizing for, and SIMPLE-VECTOR is
4234 ;; what we get from (VECTOR T) inside WITH-ARRAY-DATA.
4236 ;; Special-casing the KEY=NIL case lets us avoid some
4238 (%sort-vector #'identity simple-vector)
4239 (%sort-vector ,key simple-vector))
4240 ;; It's hard to anticipate many speed-critical applications for
4241 ;; sorting vector types other than (VECTOR T), so we just lump
4242 ;; them all together in one slow dynamically typed mess.
4244 (declare (optimize (speed 2) (space 2) (inhibit-warnings 3)))
4245 (%sort-vector (or ,key #'identity))))))
4247 ;;;; debuggers' little helpers
4249 ;;; for debugging when transforms are behaving mysteriously,
4250 ;;; e.g. when debugging a problem with an ASH transform
4251 ;;; (defun foo (&optional s)
4252 ;;; (sb-c::/report-lvar s "S outside WHEN")
4253 ;;; (when (and (integerp s) (> s 3))
4254 ;;; (sb-c::/report-lvar s "S inside WHEN")
4255 ;;; (let ((bound (ash 1 (1- s))))
4256 ;;; (sb-c::/report-lvar bound "BOUND")
4257 ;;; (let ((x (- bound))
4259 ;;; (sb-c::/report-lvar x "X")
4260 ;;; (sb-c::/report-lvar x "Y"))
4261 ;;; `(integer ,(- bound) ,(1- bound)))))
4262 ;;; (The DEFTRANSFORM doesn't do anything but report at compile time,
4263 ;;; and the function doesn't do anything at all.)
4266 (defknown /report-lvar (t t) null)
4267 (deftransform /report-lvar ((x message) (t t))
4268 (format t "~%/in /REPORT-LVAR~%")
4269 (format t "/(LVAR-TYPE X)=~S~%" (lvar-type x))
4270 (when (constant-lvar-p x)
4271 (format t "/(LVAR-VALUE X)=~S~%" (lvar-value x)))
4272 (format t "/MESSAGE=~S~%" (lvar-value message))
4273 (give-up-ir1-transform "not a real transform"))
4274 (defun /report-lvar (x message)
4275 (declare (ignore x message))))
4278 ;;;; Transforms for internal compiler utilities
4280 ;;; If QUALITY-NAME is constant and a valid name, don't bother
4281 ;;; checking that it's still valid at run-time.
4282 (deftransform policy-quality ((policy quality-name)
4284 (unless (and (constant-lvar-p quality-name)
4285 (policy-quality-name-p (lvar-value quality-name)))
4286 (give-up-ir1-transform))
4287 '(%policy-quality policy quality-name))