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* (&rest args)
128 (2 `(cons ,(first args) ,(second args)))
131 ;;; Translate RPLACx to LET and SETF.
132 (define-source-transform rplaca (x y)
137 (define-source-transform rplacd (x y)
143 (define-source-transform nth (n l) `(car (nthcdr ,n ,l)))
145 (deftransform last ((list &optional n) (t &optional t))
146 (let ((c (constant-lvar-p n)))
148 (and c (eql 1 (lvar-value n))))
150 ((and c (eql 0 (lvar-value n)))
153 (let ((type (lvar-type n)))
154 (cond ((csubtypep type (specifier-type 'fixnum))
155 '(%lastn/fixnum list n))
156 ((csubtypep type (specifier-type 'bignum))
157 '(%lastn/bignum list n))
159 (give-up-ir1-transform "second argument type too vague"))))))))
161 (define-source-transform gethash (&rest args)
163 (2 `(sb!impl::gethash3 ,@args nil))
164 (3 `(sb!impl::gethash3 ,@args))
166 (define-source-transform get (&rest args)
168 (2 `(sb!impl::get2 ,@args))
169 (3 `(sb!impl::get3 ,@args))
172 (defvar *default-nthcdr-open-code-limit* 6)
173 (defvar *extreme-nthcdr-open-code-limit* 20)
175 (deftransform nthcdr ((n l) (unsigned-byte t) * :node node)
176 "convert NTHCDR to CAxxR"
177 (unless (constant-lvar-p n)
178 (give-up-ir1-transform))
179 (let ((n (lvar-value n)))
181 (if (policy node (and (= speed 3) (= space 0)))
182 *extreme-nthcdr-open-code-limit*
183 *default-nthcdr-open-code-limit*))
184 (give-up-ir1-transform))
189 `(cdr ,(frob (1- n))))))
192 ;;;; arithmetic and numerology
194 (define-source-transform plusp (x) `(> ,x 0))
195 (define-source-transform minusp (x) `(< ,x 0))
196 (define-source-transform zerop (x) `(= ,x 0))
198 (define-source-transform 1+ (x) `(+ ,x 1))
199 (define-source-transform 1- (x) `(- ,x 1))
201 (define-source-transform oddp (x) `(logtest ,x 1))
202 (define-source-transform evenp (x) `(not (logtest ,x 1)))
204 ;;; Note that all the integer division functions are available for
205 ;;; inline expansion.
207 (macrolet ((deffrob (fun)
208 `(define-source-transform ,fun (x &optional (y nil y-p))
215 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
217 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
220 ;;; This used to be a source transform (hence the lack of restrictions
221 ;;; on the argument types), but we make it a regular transform so that
222 ;;; the VM has a chance to see the bare LOGTEST and potentiall choose
223 ;;; to implement it differently. --njf, 06-02-2006
224 (deftransform logtest ((x y) * *)
225 `(not (zerop (logand x y))))
227 (deftransform logbitp
228 ((index integer) (unsigned-byte (or (signed-byte #.sb!vm:n-word-bits)
229 (unsigned-byte #.sb!vm:n-word-bits))))
230 `(if (>= index #.sb!vm:n-word-bits)
232 (not (zerop (logand integer (ash 1 index))))))
234 (define-source-transform byte (size position)
235 `(cons ,size ,position))
236 (define-source-transform byte-size (spec) `(car ,spec))
237 (define-source-transform byte-position (spec) `(cdr ,spec))
238 (define-source-transform ldb-test (bytespec integer)
239 `(not (zerop (mask-field ,bytespec ,integer))))
241 ;;; With the ratio and complex accessors, we pick off the "identity"
242 ;;; case, and use a primitive to handle the cell access case.
243 (define-source-transform numerator (num)
244 (once-only ((n-num `(the rational ,num)))
248 (define-source-transform denominator (num)
249 (once-only ((n-num `(the rational ,num)))
251 (%denominator ,n-num)
254 ;;;; interval arithmetic for computing bounds
256 ;;;; This is a set of routines for operating on intervals. It
257 ;;;; implements a simple interval arithmetic package. Although SBCL
258 ;;;; has an interval type in NUMERIC-TYPE, we choose to use our own
259 ;;;; for two reasons:
261 ;;;; 1. This package is simpler than NUMERIC-TYPE.
263 ;;;; 2. It makes debugging much easier because you can just strip
264 ;;;; out these routines and test them independently of SBCL. (This is a
267 ;;;; One disadvantage is a probable increase in consing because we
268 ;;;; have to create these new interval structures even though
269 ;;;; numeric-type has everything we want to know. Reason 2 wins for
272 ;;; Support operations that mimic real arithmetic comparison
273 ;;; operators, but imposing a total order on the floating points such
274 ;;; that negative zeros are strictly less than positive zeros.
275 (macrolet ((def (name op)
278 (if (and (floatp x) (floatp y) (zerop x) (zerop y))
279 (,op (float-sign x) (float-sign y))
281 (def signed-zero->= >=)
282 (def signed-zero-> >)
283 (def signed-zero-= =)
284 (def signed-zero-< <)
285 (def signed-zero-<= <=))
287 ;;; The basic interval type. It can handle open and closed intervals.
288 ;;; A bound is open if it is a list containing a number, just like
289 ;;; Lisp says. NIL means unbounded.
290 (defstruct (interval (:constructor %make-interval)
294 (defun make-interval (&key low high)
295 (labels ((normalize-bound (val)
298 (float-infinity-p val))
299 ;; Handle infinities.
303 ;; Handle any closed bounds.
306 ;; We have an open bound. Normalize the numeric
307 ;; bound. If the normalized bound is still a number
308 ;; (not nil), keep the bound open. Otherwise, the
309 ;; bound is really unbounded, so drop the openness.
310 (let ((new-val (normalize-bound (first val))))
312 ;; The bound exists, so keep it open still.
315 (error "unknown bound type in MAKE-INTERVAL")))))
316 (%make-interval :low (normalize-bound low)
317 :high (normalize-bound high))))
319 ;;; Given a number X, create a form suitable as a bound for an
320 ;;; interval. Make the bound open if OPEN-P is T. NIL remains NIL.
321 #!-sb-fluid (declaim (inline set-bound))
322 (defun set-bound (x open-p)
323 (if (and x open-p) (list x) x))
325 ;;; Apply the function F to a bound X. If X is an open bound, then
326 ;;; the result will be open. IF X is NIL, the result is NIL.
327 (defun bound-func (f x)
328 (declare (type function f))
330 (with-float-traps-masked (:underflow :overflow :inexact :divide-by-zero)
331 ;; With these traps masked, we might get things like infinity
332 ;; or negative infinity returned. Check for this and return
333 ;; NIL to indicate unbounded.
334 (let ((y (funcall f (type-bound-number x))))
336 (float-infinity-p y))
338 (set-bound y (consp x)))))))
340 ;;; Apply a binary operator OP to two bounds X and Y. The result is
341 ;;; NIL if either is NIL. Otherwise bound is computed and the result
342 ;;; is open if either X or Y is open.
344 ;;; FIXME: only used in this file, not needed in target runtime
346 ;;; ANSI contaigon specifies coercion to floating point if one of the
347 ;;; arguments is floating point. Here we should check to be sure that
348 ;;; the other argument is within the bounds of that floating point
351 (defmacro safely-binop (op x y)
353 ((typep ,x 'single-float)
354 (if (or (typep ,y 'single-float)
355 (<= most-negative-single-float ,y most-positive-single-float))
357 ((typep ,x 'double-float)
358 (if (or (typep ,y 'double-float)
359 (<= most-negative-double-float ,y most-positive-double-float))
361 ((typep ,y 'single-float)
362 (if (<= most-negative-single-float ,x most-positive-single-float)
364 ((typep ,y 'double-float)
365 (if (<= most-negative-double-float ,x most-positive-double-float)
369 (defmacro bound-binop (op x y)
371 (with-float-traps-masked (:underflow :overflow :inexact :divide-by-zero)
372 (set-bound (safely-binop ,op (type-bound-number ,x)
373 (type-bound-number ,y))
374 (or (consp ,x) (consp ,y))))))
376 (defun coerce-for-bound (val type)
378 (list (coerce-for-bound (car val) type))
380 ((subtypep type 'double-float)
381 (if (<= most-negative-double-float val most-positive-double-float)
383 ((or (subtypep type 'single-float) (subtypep type 'float))
384 ;; coerce to float returns a single-float
385 (if (<= most-negative-single-float val most-positive-single-float)
387 (t (coerce val type)))))
389 (defun coerce-and-truncate-floats (val type)
392 (list (coerce-and-truncate-floats (car val) type))
394 ((subtypep type 'double-float)
395 (if (<= most-negative-double-float val most-positive-double-float)
397 (if (< val most-negative-double-float)
398 most-negative-double-float most-positive-double-float)))
399 ((or (subtypep type 'single-float) (subtypep type 'float))
400 ;; coerce to float returns a single-float
401 (if (<= most-negative-single-float val most-positive-single-float)
403 (if (< val most-negative-single-float)
404 most-negative-single-float most-positive-single-float)))
405 (t (coerce val type))))))
407 ;;; Convert a numeric-type object to an interval object.
408 (defun numeric-type->interval (x)
409 (declare (type numeric-type x))
410 (make-interval :low (numeric-type-low x)
411 :high (numeric-type-high x)))
413 (defun type-approximate-interval (type)
414 (declare (type ctype type))
415 (let ((types (prepare-arg-for-derive-type type))
418 (let ((type (if (member-type-p type)
419 (convert-member-type type)
421 (unless (numeric-type-p type)
422 (return-from type-approximate-interval nil))
423 (let ((interval (numeric-type->interval type)))
426 (interval-approximate-union result interval)
430 (defun copy-interval-limit (limit)
435 (defun copy-interval (x)
436 (declare (type interval x))
437 (make-interval :low (copy-interval-limit (interval-low x))
438 :high (copy-interval-limit (interval-high x))))
440 ;;; Given a point P contained in the interval X, split X into two
441 ;;; interval at the point P. If CLOSE-LOWER is T, then the left
442 ;;; interval contains P. If CLOSE-UPPER is T, the right interval
443 ;;; contains P. You can specify both to be T or NIL.
444 (defun interval-split (p x &optional close-lower close-upper)
445 (declare (type number p)
447 (list (make-interval :low (copy-interval-limit (interval-low x))
448 :high (if close-lower p (list p)))
449 (make-interval :low (if close-upper (list p) p)
450 :high (copy-interval-limit (interval-high x)))))
452 ;;; Return the closure of the interval. That is, convert open bounds
453 ;;; to closed bounds.
454 (defun interval-closure (x)
455 (declare (type interval x))
456 (make-interval :low (type-bound-number (interval-low x))
457 :high (type-bound-number (interval-high x))))
459 ;;; For an interval X, if X >= POINT, return '+. If X <= POINT, return
460 ;;; '-. Otherwise return NIL.
461 (defun interval-range-info (x &optional (point 0))
462 (declare (type interval x))
463 (let ((lo (interval-low x))
464 (hi (interval-high x)))
465 (cond ((and lo (signed-zero->= (type-bound-number lo) point))
467 ((and hi (signed-zero->= point (type-bound-number hi)))
472 ;;; Test to see whether the interval X is bounded. HOW determines the
473 ;;; test, and should be either ABOVE, BELOW, or BOTH.
474 (defun interval-bounded-p (x how)
475 (declare (type interval x))
482 (and (interval-low x) (interval-high x)))))
484 ;;; See whether the interval X contains the number P, taking into
485 ;;; account that the interval might not be closed.
486 (defun interval-contains-p (p x)
487 (declare (type number p)
489 ;; Does the interval X contain the number P? This would be a lot
490 ;; easier if all intervals were closed!
491 (let ((lo (interval-low x))
492 (hi (interval-high x)))
494 ;; The interval is bounded
495 (if (and (signed-zero-<= (type-bound-number lo) p)
496 (signed-zero-<= p (type-bound-number hi)))
497 ;; P is definitely in the closure of the interval.
498 ;; We just need to check the end points now.
499 (cond ((signed-zero-= p (type-bound-number lo))
501 ((signed-zero-= p (type-bound-number hi))
506 ;; Interval with upper bound
507 (if (signed-zero-< p (type-bound-number hi))
509 (and (numberp hi) (signed-zero-= p hi))))
511 ;; Interval with lower bound
512 (if (signed-zero-> p (type-bound-number lo))
514 (and (numberp lo) (signed-zero-= p lo))))
516 ;; Interval with no bounds
519 ;;; Determine whether two intervals X and Y intersect. Return T if so.
520 ;;; If CLOSED-INTERVALS-P is T, the treat the intervals as if they
521 ;;; were closed. Otherwise the intervals are treated as they are.
523 ;;; Thus if X = [0, 1) and Y = (1, 2), then they do not intersect
524 ;;; because no element in X is in Y. However, if CLOSED-INTERVALS-P
525 ;;; is T, then they do intersect because we use the closure of X = [0,
526 ;;; 1] and Y = [1, 2] to determine intersection.
527 (defun interval-intersect-p (x y &optional closed-intervals-p)
528 (declare (type interval x y))
529 (and (interval-intersection/difference (if closed-intervals-p
532 (if closed-intervals-p
537 ;;; Are the two intervals adjacent? That is, is there a number
538 ;;; between the two intervals that is not an element of either
539 ;;; interval? If so, they are not adjacent. For example [0, 1) and
540 ;;; [1, 2] are adjacent but [0, 1) and (1, 2] are not because 1 lies
541 ;;; between both intervals.
542 (defun interval-adjacent-p (x y)
543 (declare (type interval x y))
544 (flet ((adjacent (lo hi)
545 ;; Check to see whether lo and hi are adjacent. If either is
546 ;; nil, they can't be adjacent.
547 (when (and lo hi (= (type-bound-number lo) (type-bound-number hi)))
548 ;; The bounds are equal. They are adjacent if one of
549 ;; them is closed (a number). If both are open (consp),
550 ;; then there is a number that lies between them.
551 (or (numberp lo) (numberp hi)))))
552 (or (adjacent (interval-low y) (interval-high x))
553 (adjacent (interval-low x) (interval-high y)))))
555 ;;; Compute the intersection and difference between two intervals.
556 ;;; Two values are returned: the intersection and the difference.
558 ;;; Let the two intervals be X and Y, and let I and D be the two
559 ;;; values returned by this function. Then I = X intersect Y. If I
560 ;;; is NIL (the empty set), then D is X union Y, represented as the
561 ;;; list of X and Y. If I is not the empty set, then D is (X union Y)
562 ;;; - I, which is a list of two intervals.
564 ;;; For example, let X = [1,5] and Y = [-1,3). Then I = [1,3) and D =
565 ;;; [-1,1) union [3,5], which is returned as a list of two intervals.
566 (defun interval-intersection/difference (x y)
567 (declare (type interval x y))
568 (let ((x-lo (interval-low x))
569 (x-hi (interval-high x))
570 (y-lo (interval-low y))
571 (y-hi (interval-high y)))
574 ;; If p is an open bound, make it closed. If p is a closed
575 ;; bound, make it open.
579 (test-number (p int bound)
580 ;; Test whether P is in the interval.
581 (let ((pn (type-bound-number p)))
582 (when (interval-contains-p pn (interval-closure int))
583 ;; Check for endpoints.
584 (let* ((lo (interval-low int))
585 (hi (interval-high int))
586 (lon (type-bound-number lo))
587 (hin (type-bound-number hi)))
589 ;; Interval may be a point.
590 ((and lon hin (= lon hin pn))
591 (and (numberp p) (numberp lo) (numberp hi)))
592 ;; Point matches the low end.
593 ;; [P] [P,?} => TRUE [P] (P,?} => FALSE
594 ;; (P [P,?} => TRUE P) [P,?} => FALSE
595 ;; (P (P,?} => TRUE P) (P,?} => FALSE
596 ((and lon (= pn lon))
597 (or (and (numberp p) (numberp lo))
598 (and (consp p) (eq :low bound))))
599 ;; [P] {?,P] => TRUE [P] {?,P) => FALSE
600 ;; P) {?,P] => TRUE (P {?,P] => FALSE
601 ;; P) {?,P) => TRUE (P {?,P) => FALSE
602 ((and hin (= pn hin))
603 (or (and (numberp p) (numberp hi))
604 (and (consp p) (eq :high bound))))
605 ;; Not an endpoint, all is well.
608 (test-lower-bound (p int)
609 ;; P is a lower bound of an interval.
611 (test-number p int :low)
612 (not (interval-bounded-p int 'below))))
613 (test-upper-bound (p int)
614 ;; P is an upper bound of an interval.
616 (test-number p int :high)
617 (not (interval-bounded-p int 'above)))))
618 (let ((x-lo-in-y (test-lower-bound x-lo y))
619 (x-hi-in-y (test-upper-bound x-hi y))
620 (y-lo-in-x (test-lower-bound y-lo x))
621 (y-hi-in-x (test-upper-bound y-hi x)))
622 (cond ((or x-lo-in-y x-hi-in-y y-lo-in-x y-hi-in-x)
623 ;; Intervals intersect. Let's compute the intersection
624 ;; and the difference.
625 (multiple-value-bind (lo left-lo left-hi)
626 (cond (x-lo-in-y (values x-lo y-lo (opposite-bound x-lo)))
627 (y-lo-in-x (values y-lo x-lo (opposite-bound y-lo))))
628 (multiple-value-bind (hi right-lo right-hi)
630 (values x-hi (opposite-bound x-hi) y-hi))
632 (values y-hi (opposite-bound y-hi) x-hi)))
633 (values (make-interval :low lo :high hi)
634 (list (make-interval :low left-lo
636 (make-interval :low right-lo
639 (values nil (list x y))))))))
641 ;;; If intervals X and Y intersect, return a new interval that is the
642 ;;; union of the two. If they do not intersect, return NIL.
643 (defun interval-merge-pair (x y)
644 (declare (type interval x y))
645 ;; If x and y intersect or are adjacent, create the union.
646 ;; Otherwise return nil
647 (when (or (interval-intersect-p x y)
648 (interval-adjacent-p x y))
649 (flet ((select-bound (x1 x2 min-op max-op)
650 (let ((x1-val (type-bound-number x1))
651 (x2-val (type-bound-number x2)))
653 ;; Both bounds are finite. Select the right one.
654 (cond ((funcall min-op x1-val x2-val)
655 ;; x1 is definitely better.
657 ((funcall max-op x1-val x2-val)
658 ;; x2 is definitely better.
661 ;; Bounds are equal. Select either
662 ;; value and make it open only if
664 (set-bound x1-val (and (consp x1) (consp x2))))))
666 ;; At least one bound is not finite. The
667 ;; non-finite bound always wins.
669 (let* ((x-lo (copy-interval-limit (interval-low x)))
670 (x-hi (copy-interval-limit (interval-high x)))
671 (y-lo (copy-interval-limit (interval-low y)))
672 (y-hi (copy-interval-limit (interval-high y))))
673 (make-interval :low (select-bound x-lo y-lo #'< #'>)
674 :high (select-bound x-hi y-hi #'> #'<))))))
676 ;;; return the minimal interval, containing X and Y
677 (defun interval-approximate-union (x y)
678 (cond ((interval-merge-pair x y))
680 (make-interval :low (copy-interval-limit (interval-low x))
681 :high (copy-interval-limit (interval-high y))))
683 (make-interval :low (copy-interval-limit (interval-low y))
684 :high (copy-interval-limit (interval-high x))))))
686 ;;; basic arithmetic operations on intervals. We probably should do
687 ;;; true interval arithmetic here, but it's complicated because we
688 ;;; have float and integer types and bounds can be open or closed.
690 ;;; the negative of an interval
691 (defun interval-neg (x)
692 (declare (type interval x))
693 (make-interval :low (bound-func #'- (interval-high x))
694 :high (bound-func #'- (interval-low x))))
696 ;;; Add two intervals.
697 (defun interval-add (x y)
698 (declare (type interval x y))
699 (make-interval :low (bound-binop + (interval-low x) (interval-low y))
700 :high (bound-binop + (interval-high x) (interval-high y))))
702 ;;; Subtract two intervals.
703 (defun interval-sub (x y)
704 (declare (type interval x y))
705 (make-interval :low (bound-binop - (interval-low x) (interval-high y))
706 :high (bound-binop - (interval-high x) (interval-low y))))
708 ;;; Multiply two intervals.
709 (defun interval-mul (x y)
710 (declare (type interval x y))
711 (flet ((bound-mul (x y)
712 (cond ((or (null x) (null y))
713 ;; Multiply by infinity is infinity
715 ((or (and (numberp x) (zerop x))
716 (and (numberp y) (zerop y)))
717 ;; Multiply by closed zero is special. The result
718 ;; is always a closed bound. But don't replace this
719 ;; with zero; we want the multiplication to produce
720 ;; the correct signed zero, if needed. Use SIGNUM
721 ;; to avoid trying to multiply huge bignums with 0.0.
722 (* (signum (type-bound-number x)) (signum (type-bound-number y))))
723 ((or (and (floatp x) (float-infinity-p x))
724 (and (floatp y) (float-infinity-p y)))
725 ;; Infinity times anything is infinity
728 ;; General multiply. The result is open if either is open.
729 (bound-binop * x y)))))
730 (let ((x-range (interval-range-info x))
731 (y-range (interval-range-info y)))
732 (cond ((null x-range)
733 ;; Split x into two and multiply each separately
734 (destructuring-bind (x- x+) (interval-split 0 x t t)
735 (interval-merge-pair (interval-mul x- y)
736 (interval-mul x+ y))))
738 ;; Split y into two and multiply each separately
739 (destructuring-bind (y- y+) (interval-split 0 y t t)
740 (interval-merge-pair (interval-mul x y-)
741 (interval-mul x y+))))
743 (interval-neg (interval-mul (interval-neg x) y)))
745 (interval-neg (interval-mul x (interval-neg y))))
746 ((and (eq x-range '+) (eq y-range '+))
747 ;; If we are here, X and Y are both positive.
749 :low (bound-mul (interval-low x) (interval-low y))
750 :high (bound-mul (interval-high x) (interval-high y))))
752 (bug "excluded case in INTERVAL-MUL"))))))
754 ;;; Divide two intervals.
755 (defun interval-div (top bot)
756 (declare (type interval top bot))
757 (flet ((bound-div (x y y-low-p)
760 ;; Divide by infinity means result is 0. However,
761 ;; we need to watch out for the sign of the result,
762 ;; to correctly handle signed zeros. We also need
763 ;; to watch out for positive or negative infinity.
764 (if (floatp (type-bound-number x))
766 (- (float-sign (type-bound-number x) 0.0))
767 (float-sign (type-bound-number x) 0.0))
769 ((zerop (type-bound-number y))
770 ;; Divide by zero means result is infinity
772 ((and (numberp x) (zerop x))
773 ;; Zero divided by anything is zero.
776 (bound-binop / x y)))))
777 (let ((top-range (interval-range-info top))
778 (bot-range (interval-range-info bot)))
779 (cond ((null bot-range)
780 ;; The denominator contains zero, so anything goes!
781 (make-interval :low nil :high nil))
783 ;; Denominator is negative so flip the sign, compute the
784 ;; result, and flip it back.
785 (interval-neg (interval-div top (interval-neg bot))))
787 ;; Split top into two positive and negative parts, and
788 ;; divide each separately
789 (destructuring-bind (top- top+) (interval-split 0 top t t)
790 (interval-merge-pair (interval-div top- bot)
791 (interval-div top+ bot))))
793 ;; Top is negative so flip the sign, divide, and flip the
794 ;; sign of the result.
795 (interval-neg (interval-div (interval-neg top) bot)))
796 ((and (eq top-range '+) (eq bot-range '+))
799 :low (bound-div (interval-low top) (interval-high bot) t)
800 :high (bound-div (interval-high top) (interval-low bot) nil)))
802 (bug "excluded case in INTERVAL-DIV"))))))
804 ;;; Apply the function F to the interval X. If X = [a, b], then the
805 ;;; result is [f(a), f(b)]. It is up to the user to make sure the
806 ;;; result makes sense. It will if F is monotonic increasing (or
808 (defun interval-func (f x)
809 (declare (type function f)
811 (let ((lo (bound-func f (interval-low x)))
812 (hi (bound-func f (interval-high x))))
813 (make-interval :low lo :high hi)))
815 ;;; Return T if X < Y. That is every number in the interval X is
816 ;;; always less than any number in the interval Y.
817 (defun interval-< (x y)
818 (declare (type interval x y))
819 ;; X < Y only if X is bounded above, Y is bounded below, and they
821 (when (and (interval-bounded-p x 'above)
822 (interval-bounded-p y 'below))
823 ;; Intervals are bounded in the appropriate way. Make sure they
825 (let ((left (interval-high x))
826 (right (interval-low y)))
827 (cond ((> (type-bound-number left)
828 (type-bound-number right))
829 ;; The intervals definitely overlap, so result is NIL.
831 ((< (type-bound-number left)
832 (type-bound-number right))
833 ;; The intervals definitely don't touch, so result is T.
836 ;; Limits are equal. Check for open or closed bounds.
837 ;; Don't overlap if one or the other are open.
838 (or (consp left) (consp right)))))))
840 ;;; Return T if X >= Y. That is, every number in the interval X is
841 ;;; always greater than any number in the interval Y.
842 (defun interval->= (x y)
843 (declare (type interval x y))
844 ;; X >= Y if lower bound of X >= upper bound of Y
845 (when (and (interval-bounded-p x 'below)
846 (interval-bounded-p y 'above))
847 (>= (type-bound-number (interval-low x))
848 (type-bound-number (interval-high y)))))
850 ;;; Return T if X = Y.
851 (defun interval-= (x y)
852 (declare (type interval x y))
853 (and (interval-bounded-p x 'both)
854 (interval-bounded-p y 'both)
858 ;; Open intervals cannot be =
859 (return-from interval-= nil))))
860 ;; Both intervals refer to the same point
861 (= (bound (interval-high x)) (bound (interval-low x))
862 (bound (interval-high y)) (bound (interval-low y))))))
864 ;;; Return T if X /= Y
865 (defun interval-/= (x y)
866 (not (interval-intersect-p x y)))
868 ;;; Return an interval that is the absolute value of X. Thus, if
869 ;;; X = [-1 10], the result is [0, 10].
870 (defun interval-abs (x)
871 (declare (type interval x))
872 (case (interval-range-info x)
878 (destructuring-bind (x- x+) (interval-split 0 x t t)
879 (interval-merge-pair (interval-neg x-) x+)))))
881 ;;; Compute the square of an interval.
882 (defun interval-sqr (x)
883 (declare (type interval x))
884 (interval-func (lambda (x) (* x x))
887 ;;;; numeric DERIVE-TYPE methods
889 ;;; a utility for defining derive-type methods of integer operations. If
890 ;;; the types of both X and Y are integer types, then we compute a new
891 ;;; integer type with bounds determined Fun when applied to X and Y.
892 ;;; Otherwise, we use NUMERIC-CONTAGION.
893 (defun derive-integer-type-aux (x y fun)
894 (declare (type function fun))
895 (if (and (numeric-type-p x) (numeric-type-p y)
896 (eq (numeric-type-class x) 'integer)
897 (eq (numeric-type-class y) 'integer)
898 (eq (numeric-type-complexp x) :real)
899 (eq (numeric-type-complexp y) :real))
900 (multiple-value-bind (low high) (funcall fun x y)
901 (make-numeric-type :class 'integer
905 (numeric-contagion x y)))
907 (defun derive-integer-type (x y fun)
908 (declare (type lvar x y) (type function fun))
909 (let ((x (lvar-type x))
911 (derive-integer-type-aux x y fun)))
913 ;;; simple utility to flatten a list
914 (defun flatten-list (x)
915 (labels ((flatten-and-append (tree list)
916 (cond ((null tree) list)
917 ((atom tree) (cons tree list))
918 (t (flatten-and-append
919 (car tree) (flatten-and-append (cdr tree) list))))))
920 (flatten-and-append x nil)))
922 ;;; Take some type of lvar and massage it so that we get a list of the
923 ;;; constituent types. If ARG is *EMPTY-TYPE*, return NIL to indicate
925 (defun prepare-arg-for-derive-type (arg)
926 (flet ((listify (arg)
931 (union-type-types arg))
934 (unless (eq arg *empty-type*)
935 ;; Make sure all args are some type of numeric-type. For member
936 ;; types, convert the list of members into a union of equivalent
937 ;; single-element member-type's.
938 (let ((new-args nil))
939 (dolist (arg (listify arg))
940 (if (member-type-p arg)
941 ;; Run down the list of members and convert to a list of
943 (mapc-member-type-members
945 (push (if (numberp member)
946 (make-member-type :members (list member))
950 (push arg new-args)))
951 (unless (member *empty-type* new-args)
954 ;;; Convert from the standard type convention for which -0.0 and 0.0
955 ;;; are equal to an intermediate convention for which they are
956 ;;; considered different which is more natural for some of the
958 (defun convert-numeric-type (type)
959 (declare (type numeric-type type))
960 ;;; Only convert real float interval delimiters types.
961 (if (eq (numeric-type-complexp type) :real)
962 (let* ((lo (numeric-type-low type))
963 (lo-val (type-bound-number lo))
964 (lo-float-zero-p (and lo (floatp lo-val) (= lo-val 0.0)))
965 (hi (numeric-type-high type))
966 (hi-val (type-bound-number hi))
967 (hi-float-zero-p (and hi (floatp hi-val) (= hi-val 0.0))))
968 (if (or lo-float-zero-p hi-float-zero-p)
970 :class (numeric-type-class type)
971 :format (numeric-type-format type)
973 :low (if lo-float-zero-p
975 (list (float 0.0 lo-val))
976 (float (load-time-value (make-unportable-float :single-float-negative-zero)) lo-val))
978 :high (if hi-float-zero-p
980 (list (float (load-time-value (make-unportable-float :single-float-negative-zero)) hi-val))
987 ;;; Convert back from the intermediate convention for which -0.0 and
988 ;;; 0.0 are considered different to the standard type convention for
990 (defun convert-back-numeric-type (type)
991 (declare (type numeric-type type))
992 ;;; Only convert real float interval delimiters types.
993 (if (eq (numeric-type-complexp type) :real)
994 (let* ((lo (numeric-type-low type))
995 (lo-val (type-bound-number lo))
997 (and lo (floatp lo-val) (= lo-val 0.0)
998 (float-sign lo-val)))
999 (hi (numeric-type-high type))
1000 (hi-val (type-bound-number hi))
1002 (and hi (floatp hi-val) (= hi-val 0.0)
1003 (float-sign hi-val))))
1005 ;; (float +0.0 +0.0) => (member 0.0)
1006 ;; (float -0.0 -0.0) => (member -0.0)
1007 ((and lo-float-zero-p hi-float-zero-p)
1008 ;; shouldn't have exclusive bounds here..
1009 (aver (and (not (consp lo)) (not (consp hi))))
1010 (if (= lo-float-zero-p hi-float-zero-p)
1011 ;; (float +0.0 +0.0) => (member 0.0)
1012 ;; (float -0.0 -0.0) => (member -0.0)
1013 (specifier-type `(member ,lo-val))
1014 ;; (float -0.0 +0.0) => (float 0.0 0.0)
1015 ;; (float +0.0 -0.0) => (float 0.0 0.0)
1016 (make-numeric-type :class (numeric-type-class type)
1017 :format (numeric-type-format type)
1023 ;; (float -0.0 x) => (float 0.0 x)
1024 ((and (not (consp lo)) (minusp lo-float-zero-p))
1025 (make-numeric-type :class (numeric-type-class type)
1026 :format (numeric-type-format type)
1028 :low (float 0.0 lo-val)
1030 ;; (float (+0.0) x) => (float (0.0) x)
1031 ((and (consp lo) (plusp lo-float-zero-p))
1032 (make-numeric-type :class (numeric-type-class type)
1033 :format (numeric-type-format type)
1035 :low (list (float 0.0 lo-val))
1038 ;; (float +0.0 x) => (or (member 0.0) (float (0.0) x))
1039 ;; (float (-0.0) x) => (or (member 0.0) (float (0.0) x))
1040 (list (make-member-type :members (list (float 0.0 lo-val)))
1041 (make-numeric-type :class (numeric-type-class type)
1042 :format (numeric-type-format type)
1044 :low (list (float 0.0 lo-val))
1048 ;; (float x +0.0) => (float x 0.0)
1049 ((and (not (consp hi)) (plusp hi-float-zero-p))
1050 (make-numeric-type :class (numeric-type-class type)
1051 :format (numeric-type-format type)
1054 :high (float 0.0 hi-val)))
1055 ;; (float x (-0.0)) => (float x (0.0))
1056 ((and (consp hi) (minusp hi-float-zero-p))
1057 (make-numeric-type :class (numeric-type-class type)
1058 :format (numeric-type-format type)
1061 :high (list (float 0.0 hi-val))))
1063 ;; (float x (+0.0)) => (or (member -0.0) (float x (0.0)))
1064 ;; (float x -0.0) => (or (member -0.0) (float x (0.0)))
1065 (list (make-member-type :members (list (float -0.0 hi-val)))
1066 (make-numeric-type :class (numeric-type-class type)
1067 :format (numeric-type-format type)
1070 :high (list (float 0.0 hi-val)))))))
1076 ;;; Convert back a possible list of numeric types.
1077 (defun convert-back-numeric-type-list (type-list)
1080 (let ((results '()))
1081 (dolist (type type-list)
1082 (if (numeric-type-p type)
1083 (let ((result (convert-back-numeric-type type)))
1085 (setf results (append results result))
1086 (push result results)))
1087 (push type results)))
1090 (convert-back-numeric-type type-list))
1092 (convert-back-numeric-type-list (union-type-types type-list)))
1096 ;;; FIXME: MAKE-CANONICAL-UNION-TYPE and CONVERT-MEMBER-TYPE probably
1097 ;;; belong in the kernel's type logic, invoked always, instead of in
1098 ;;; the compiler, invoked only during some type optimizations. (In
1099 ;;; fact, as of 0.pre8.100 or so they probably are, under
1100 ;;; MAKE-MEMBER-TYPE, so probably this code can be deleted)
1102 ;;; Take a list of types and return a canonical type specifier,
1103 ;;; combining any MEMBER types together. If both positive and negative
1104 ;;; MEMBER types are present they are converted to a float type.
1105 ;;; XXX This would be far simpler if the type-union methods could handle
1106 ;;; member/number unions.
1107 (defun make-canonical-union-type (type-list)
1108 (let ((xset (alloc-xset))
1111 (dolist (type type-list)
1112 (cond ((member-type-p type)
1113 (mapc-member-type-members
1115 (if (fp-zero-p member)
1116 (unless (member member fp-zeroes)
1117 (pushnew member fp-zeroes))
1118 (add-to-xset member xset)))
1121 (push type misc-types))))
1122 (if (and (xset-empty-p xset) (not fp-zeroes))
1123 (apply #'type-union misc-types)
1124 (apply #'type-union (make-member-type :xset xset :fp-zeroes fp-zeroes) misc-types))))
1126 ;;; Convert a member type with a single member to a numeric type.
1127 (defun convert-member-type (arg)
1128 (let* ((members (member-type-members arg))
1129 (member (first members))
1130 (member-type (type-of member)))
1131 (aver (not (rest members)))
1132 (specifier-type (cond ((typep member 'integer)
1133 `(integer ,member ,member))
1134 ((memq member-type '(short-float single-float
1135 double-float long-float))
1136 `(,member-type ,member ,member))
1140 ;;; This is used in defoptimizers for computing the resulting type of
1143 ;;; Given the lvar ARG, derive the resulting type using the
1144 ;;; DERIVE-FUN. DERIVE-FUN takes exactly one argument which is some
1145 ;;; "atomic" lvar type like numeric-type or member-type (containing
1146 ;;; just one element). It should return the resulting type, which can
1147 ;;; be a list of types.
1149 ;;; For the case of member types, if a MEMBER-FUN is given it is
1150 ;;; called to compute the result otherwise the member type is first
1151 ;;; converted to a numeric type and the DERIVE-FUN is called.
1152 (defun one-arg-derive-type (arg derive-fun member-fun
1153 &optional (convert-type t))
1154 (declare (type function derive-fun)
1155 (type (or null function) member-fun))
1156 (let ((arg-list (prepare-arg-for-derive-type (lvar-type arg))))
1162 (with-float-traps-masked
1163 (:underflow :overflow :divide-by-zero)
1165 `(eql ,(funcall member-fun
1166 (first (member-type-members x))))))
1167 ;; Otherwise convert to a numeric type.
1168 (let ((result-type-list
1169 (funcall derive-fun (convert-member-type x))))
1171 (convert-back-numeric-type-list result-type-list)
1172 result-type-list))))
1175 (convert-back-numeric-type-list
1176 (funcall derive-fun (convert-numeric-type x)))
1177 (funcall derive-fun x)))
1179 *universal-type*))))
1180 ;; Run down the list of args and derive the type of each one,
1181 ;; saving all of the results in a list.
1182 (let ((results nil))
1183 (dolist (arg arg-list)
1184 (let ((result (deriver arg)))
1186 (setf results (append results result))
1187 (push result results))))
1189 (make-canonical-union-type results)
1190 (first results)))))))
1192 ;;; Same as ONE-ARG-DERIVE-TYPE, except we assume the function takes
1193 ;;; two arguments. DERIVE-FUN takes 3 args in this case: the two
1194 ;;; original args and a third which is T to indicate if the two args
1195 ;;; really represent the same lvar. This is useful for deriving the
1196 ;;; type of things like (* x x), which should always be positive. If
1197 ;;; we didn't do this, we wouldn't be able to tell.
1198 (defun two-arg-derive-type (arg1 arg2 derive-fun fun
1199 &optional (convert-type t))
1200 (declare (type function derive-fun fun))
1201 (flet ((deriver (x y same-arg)
1202 (cond ((and (member-type-p x) (member-type-p y))
1203 (let* ((x (first (member-type-members x)))
1204 (y (first (member-type-members y)))
1205 (result (ignore-errors
1206 (with-float-traps-masked
1207 (:underflow :overflow :divide-by-zero
1209 (funcall fun x y)))))
1210 (cond ((null result) *empty-type*)
1211 ((and (floatp result) (float-nan-p result))
1212 (make-numeric-type :class 'float
1213 :format (type-of result)
1216 (specifier-type `(eql ,result))))))
1217 ((and (member-type-p x) (numeric-type-p y))
1218 (let* ((x (convert-member-type x))
1219 (y (if convert-type (convert-numeric-type y) y))
1220 (result (funcall derive-fun x y same-arg)))
1222 (convert-back-numeric-type-list result)
1224 ((and (numeric-type-p x) (member-type-p y))
1225 (let* ((x (if convert-type (convert-numeric-type x) x))
1226 (y (convert-member-type y))
1227 (result (funcall derive-fun x y same-arg)))
1229 (convert-back-numeric-type-list result)
1231 ((and (numeric-type-p x) (numeric-type-p y))
1232 (let* ((x (if convert-type (convert-numeric-type x) x))
1233 (y (if convert-type (convert-numeric-type y) y))
1234 (result (funcall derive-fun x y same-arg)))
1236 (convert-back-numeric-type-list result)
1239 *universal-type*))))
1240 (let ((same-arg (same-leaf-ref-p arg1 arg2))
1241 (a1 (prepare-arg-for-derive-type (lvar-type arg1)))
1242 (a2 (prepare-arg-for-derive-type (lvar-type arg2))))
1244 (let ((results nil))
1246 ;; Since the args are the same LVARs, just run down the
1249 (let ((result (deriver x x same-arg)))
1251 (setf results (append results result))
1252 (push result results))))
1253 ;; Try all pairwise combinations.
1256 (let ((result (or (deriver x y same-arg)
1257 (numeric-contagion x y))))
1259 (setf results (append results result))
1260 (push result results))))))
1262 (make-canonical-union-type results)
1263 (first results)))))))
1265 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1267 (defoptimizer (+ derive-type) ((x y))
1268 (derive-integer-type
1275 (values (frob (numeric-type-low x) (numeric-type-low y))
1276 (frob (numeric-type-high x) (numeric-type-high y)))))))
1278 (defoptimizer (- derive-type) ((x y))
1279 (derive-integer-type
1286 (values (frob (numeric-type-low x) (numeric-type-high y))
1287 (frob (numeric-type-high x) (numeric-type-low y)))))))
1289 (defoptimizer (* derive-type) ((x y))
1290 (derive-integer-type
1293 (let ((x-low (numeric-type-low x))
1294 (x-high (numeric-type-high x))
1295 (y-low (numeric-type-low y))
1296 (y-high (numeric-type-high y)))
1297 (cond ((not (and x-low y-low))
1299 ((or (minusp x-low) (minusp y-low))
1300 (if (and x-high y-high)
1301 (let ((max (* (max (abs x-low) (abs x-high))
1302 (max (abs y-low) (abs y-high)))))
1303 (values (- max) max))
1306 (values (* x-low y-low)
1307 (if (and x-high y-high)
1311 (defoptimizer (/ derive-type) ((x y))
1312 (numeric-contagion (lvar-type x) (lvar-type y)))
1316 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1318 (defun +-derive-type-aux (x y same-arg)
1319 (if (and (numeric-type-real-p x)
1320 (numeric-type-real-p y))
1323 (let ((x-int (numeric-type->interval x)))
1324 (interval-add x-int x-int))
1325 (interval-add (numeric-type->interval x)
1326 (numeric-type->interval y))))
1327 (result-type (numeric-contagion x y)))
1328 ;; If the result type is a float, we need to be sure to coerce
1329 ;; the bounds into the correct type.
1330 (when (eq (numeric-type-class result-type) 'float)
1331 (setf result (interval-func
1333 (coerce-for-bound x (or (numeric-type-format result-type)
1337 :class (if (and (eq (numeric-type-class x) 'integer)
1338 (eq (numeric-type-class y) 'integer))
1339 ;; The sum of integers is always an integer.
1341 (numeric-type-class result-type))
1342 :format (numeric-type-format result-type)
1343 :low (interval-low result)
1344 :high (interval-high result)))
1345 ;; general contagion
1346 (numeric-contagion x y)))
1348 (defoptimizer (+ derive-type) ((x y))
1349 (two-arg-derive-type x y #'+-derive-type-aux #'+))
1351 (defun --derive-type-aux (x y same-arg)
1352 (if (and (numeric-type-real-p x)
1353 (numeric-type-real-p y))
1355 ;; (- X X) is always 0.
1357 (make-interval :low 0 :high 0)
1358 (interval-sub (numeric-type->interval x)
1359 (numeric-type->interval y))))
1360 (result-type (numeric-contagion x y)))
1361 ;; If the result type is a float, we need to be sure to coerce
1362 ;; the bounds into the correct type.
1363 (when (eq (numeric-type-class result-type) 'float)
1364 (setf result (interval-func
1366 (coerce-for-bound x (or (numeric-type-format result-type)
1370 :class (if (and (eq (numeric-type-class x) 'integer)
1371 (eq (numeric-type-class y) 'integer))
1372 ;; The difference of integers is always an integer.
1374 (numeric-type-class result-type))
1375 :format (numeric-type-format result-type)
1376 :low (interval-low result)
1377 :high (interval-high result)))
1378 ;; general contagion
1379 (numeric-contagion x y)))
1381 (defoptimizer (- derive-type) ((x y))
1382 (two-arg-derive-type x y #'--derive-type-aux #'-))
1384 (defun *-derive-type-aux (x y same-arg)
1385 (if (and (numeric-type-real-p x)
1386 (numeric-type-real-p y))
1388 ;; (* X X) is always positive, so take care to do it right.
1390 (interval-sqr (numeric-type->interval x))
1391 (interval-mul (numeric-type->interval x)
1392 (numeric-type->interval y))))
1393 (result-type (numeric-contagion x y)))
1394 ;; If the result type is a float, we need to be sure to coerce
1395 ;; the bounds into the correct type.
1396 (when (eq (numeric-type-class result-type) 'float)
1397 (setf result (interval-func
1399 (coerce-for-bound x (or (numeric-type-format result-type)
1403 :class (if (and (eq (numeric-type-class x) 'integer)
1404 (eq (numeric-type-class y) 'integer))
1405 ;; The product of integers is always an integer.
1407 (numeric-type-class result-type))
1408 :format (numeric-type-format result-type)
1409 :low (interval-low result)
1410 :high (interval-high result)))
1411 (numeric-contagion x y)))
1413 (defoptimizer (* derive-type) ((x y))
1414 (two-arg-derive-type x y #'*-derive-type-aux #'*))
1416 (defun /-derive-type-aux (x y same-arg)
1417 (if (and (numeric-type-real-p x)
1418 (numeric-type-real-p y))
1420 ;; (/ X X) is always 1, except if X can contain 0. In
1421 ;; that case, we shouldn't optimize the division away
1422 ;; because we want 0/0 to signal an error.
1424 (not (interval-contains-p
1425 0 (interval-closure (numeric-type->interval y)))))
1426 (make-interval :low 1 :high 1)
1427 (interval-div (numeric-type->interval x)
1428 (numeric-type->interval y))))
1429 (result-type (numeric-contagion x y)))
1430 ;; If the result type is a float, we need to be sure to coerce
1431 ;; the bounds into the correct type.
1432 (when (eq (numeric-type-class result-type) 'float)
1433 (setf result (interval-func
1435 (coerce-for-bound x (or (numeric-type-format result-type)
1438 (make-numeric-type :class (numeric-type-class result-type)
1439 :format (numeric-type-format result-type)
1440 :low (interval-low result)
1441 :high (interval-high result)))
1442 (numeric-contagion x y)))
1444 (defoptimizer (/ derive-type) ((x y))
1445 (two-arg-derive-type x y #'/-derive-type-aux #'/))
1449 (defun ash-derive-type-aux (n-type shift same-arg)
1450 (declare (ignore same-arg))
1451 ;; KLUDGE: All this ASH optimization is suppressed under CMU CL for
1452 ;; some bignum cases because as of version 2.4.6 for Debian and 18d,
1453 ;; CMU CL blows up on (ASH 1000000000 -100000000000) (i.e. ASH of
1454 ;; two bignums yielding zero) and it's hard to avoid that
1455 ;; calculation in here.
1456 #+(and cmu sb-xc-host)
1457 (when (and (or (typep (numeric-type-low n-type) 'bignum)
1458 (typep (numeric-type-high n-type) 'bignum))
1459 (or (typep (numeric-type-low shift) 'bignum)
1460 (typep (numeric-type-high shift) 'bignum)))
1461 (return-from ash-derive-type-aux *universal-type*))
1462 (flet ((ash-outer (n s)
1463 (when (and (fixnump s)
1465 (> s sb!xc:most-negative-fixnum))
1467 ;; KLUDGE: The bare 64's here should be related to
1468 ;; symbolic machine word size values somehow.
1471 (if (and (fixnump s)
1472 (> s sb!xc:most-negative-fixnum))
1474 (if (minusp n) -1 0))))
1475 (or (and (csubtypep n-type (specifier-type 'integer))
1476 (csubtypep shift (specifier-type 'integer))
1477 (let ((n-low (numeric-type-low n-type))
1478 (n-high (numeric-type-high n-type))
1479 (s-low (numeric-type-low shift))
1480 (s-high (numeric-type-high shift)))
1481 (make-numeric-type :class 'integer :complexp :real
1484 (ash-outer n-low s-high)
1485 (ash-inner n-low s-low)))
1488 (ash-inner n-high s-low)
1489 (ash-outer n-high s-high))))))
1492 (defoptimizer (ash derive-type) ((n shift))
1493 (two-arg-derive-type n shift #'ash-derive-type-aux #'ash))
1495 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1496 (macrolet ((frob (fun)
1497 `#'(lambda (type type2)
1498 (declare (ignore type2))
1499 (let ((lo (numeric-type-low type))
1500 (hi (numeric-type-high type)))
1501 (values (if hi (,fun hi) nil) (if lo (,fun lo) nil))))))
1503 (defoptimizer (%negate derive-type) ((num))
1504 (derive-integer-type num num (frob -))))
1506 (defun lognot-derive-type-aux (int)
1507 (derive-integer-type-aux int int
1508 (lambda (type type2)
1509 (declare (ignore type2))
1510 (let ((lo (numeric-type-low type))
1511 (hi (numeric-type-high type)))
1512 (values (if hi (lognot hi) nil)
1513 (if lo (lognot lo) nil)
1514 (numeric-type-class type)
1515 (numeric-type-format type))))))
1517 (defoptimizer (lognot derive-type) ((int))
1518 (lognot-derive-type-aux (lvar-type int)))
1520 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1521 (defoptimizer (%negate derive-type) ((num))
1522 (flet ((negate-bound (b)
1524 (set-bound (- (type-bound-number b))
1526 (one-arg-derive-type num
1528 (modified-numeric-type
1530 :low (negate-bound (numeric-type-high type))
1531 :high (negate-bound (numeric-type-low type))))
1534 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1535 (defoptimizer (abs derive-type) ((num))
1536 (let ((type (lvar-type num)))
1537 (if (and (numeric-type-p type)
1538 (eq (numeric-type-class type) 'integer)
1539 (eq (numeric-type-complexp type) :real))
1540 (let ((lo (numeric-type-low type))
1541 (hi (numeric-type-high type)))
1542 (make-numeric-type :class 'integer :complexp :real
1543 :low (cond ((and hi (minusp hi))
1549 :high (if (and hi lo)
1550 (max (abs hi) (abs lo))
1552 (numeric-contagion type type))))
1554 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1555 (defun abs-derive-type-aux (type)
1556 (cond ((eq (numeric-type-complexp type) :complex)
1557 ;; The absolute value of a complex number is always a
1558 ;; non-negative float.
1559 (let* ((format (case (numeric-type-class type)
1560 ((integer rational) 'single-float)
1561 (t (numeric-type-format type))))
1562 (bound-format (or format 'float)))
1563 (make-numeric-type :class 'float
1566 :low (coerce 0 bound-format)
1569 ;; The absolute value of a real number is a non-negative real
1570 ;; of the same type.
1571 (let* ((abs-bnd (interval-abs (numeric-type->interval type)))
1572 (class (numeric-type-class type))
1573 (format (numeric-type-format type))
1574 (bound-type (or format class 'real)))
1579 :low (coerce-and-truncate-floats (interval-low abs-bnd) bound-type)
1580 :high (coerce-and-truncate-floats
1581 (interval-high abs-bnd) bound-type))))))
1583 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1584 (defoptimizer (abs derive-type) ((num))
1585 (one-arg-derive-type num #'abs-derive-type-aux #'abs))
1587 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1588 (defoptimizer (truncate derive-type) ((number divisor))
1589 (let ((number-type (lvar-type number))
1590 (divisor-type (lvar-type divisor))
1591 (integer-type (specifier-type 'integer)))
1592 (if (and (numeric-type-p number-type)
1593 (csubtypep number-type integer-type)
1594 (numeric-type-p divisor-type)
1595 (csubtypep divisor-type integer-type))
1596 (let ((number-low (numeric-type-low number-type))
1597 (number-high (numeric-type-high number-type))
1598 (divisor-low (numeric-type-low divisor-type))
1599 (divisor-high (numeric-type-high divisor-type)))
1600 (values-specifier-type
1601 `(values ,(integer-truncate-derive-type number-low number-high
1602 divisor-low divisor-high)
1603 ,(integer-rem-derive-type number-low number-high
1604 divisor-low divisor-high))))
1607 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1610 (defun rem-result-type (number-type divisor-type)
1611 ;; Figure out what the remainder type is. The remainder is an
1612 ;; integer if both args are integers; a rational if both args are
1613 ;; rational; and a float otherwise.
1614 (cond ((and (csubtypep number-type (specifier-type 'integer))
1615 (csubtypep divisor-type (specifier-type 'integer)))
1617 ((and (csubtypep number-type (specifier-type 'rational))
1618 (csubtypep divisor-type (specifier-type 'rational)))
1620 ((and (csubtypep number-type (specifier-type 'float))
1621 (csubtypep divisor-type (specifier-type 'float)))
1622 ;; Both are floats so the result is also a float, of
1623 ;; the largest type.
1624 (or (float-format-max (numeric-type-format number-type)
1625 (numeric-type-format divisor-type))
1627 ((and (csubtypep number-type (specifier-type 'float))
1628 (csubtypep divisor-type (specifier-type 'rational)))
1629 ;; One of the arguments is a float and the other is a
1630 ;; rational. The remainder is a float of the same
1632 (or (numeric-type-format number-type) 'float))
1633 ((and (csubtypep divisor-type (specifier-type 'float))
1634 (csubtypep number-type (specifier-type 'rational)))
1635 ;; One of the arguments is a float and the other is a
1636 ;; rational. The remainder is a float of the same
1638 (or (numeric-type-format divisor-type) 'float))
1640 ;; Some unhandled combination. This usually means both args
1641 ;; are REAL so the result is a REAL.
1644 (defun truncate-derive-type-quot (number-type divisor-type)
1645 (let* ((rem-type (rem-result-type number-type divisor-type))
1646 (number-interval (numeric-type->interval number-type))
1647 (divisor-interval (numeric-type->interval divisor-type)))
1648 ;;(declare (type (member '(integer rational float)) rem-type))
1649 ;; We have real numbers now.
1650 (cond ((eq rem-type 'integer)
1651 ;; Since the remainder type is INTEGER, both args are
1653 (let* ((res (integer-truncate-derive-type
1654 (interval-low number-interval)
1655 (interval-high number-interval)
1656 (interval-low divisor-interval)
1657 (interval-high divisor-interval))))
1658 (specifier-type (if (listp res) res 'integer))))
1660 (let ((quot (truncate-quotient-bound
1661 (interval-div number-interval
1662 divisor-interval))))
1663 (specifier-type `(integer ,(or (interval-low quot) '*)
1664 ,(or (interval-high quot) '*))))))))
1666 (defun truncate-derive-type-rem (number-type divisor-type)
1667 (let* ((rem-type (rem-result-type number-type divisor-type))
1668 (number-interval (numeric-type->interval number-type))
1669 (divisor-interval (numeric-type->interval divisor-type))
1670 (rem (truncate-rem-bound number-interval divisor-interval)))
1671 ;;(declare (type (member '(integer rational float)) rem-type))
1672 ;; We have real numbers now.
1673 (cond ((eq rem-type 'integer)
1674 ;; Since the remainder type is INTEGER, both args are
1676 (specifier-type `(,rem-type ,(or (interval-low rem) '*)
1677 ,(or (interval-high rem) '*))))
1679 (multiple-value-bind (class format)
1682 (values 'integer nil))
1684 (values 'rational nil))
1685 ((or single-float double-float #!+long-float long-float)
1686 (values 'float rem-type))
1688 (values 'float nil))
1691 (when (member rem-type '(float single-float double-float
1692 #!+long-float long-float))
1693 (setf rem (interval-func #'(lambda (x)
1694 (coerce-for-bound x rem-type))
1696 (make-numeric-type :class class
1698 :low (interval-low rem)
1699 :high (interval-high rem)))))))
1701 (defun truncate-derive-type-quot-aux (num div same-arg)
1702 (declare (ignore same-arg))
1703 (if (and (numeric-type-real-p num)
1704 (numeric-type-real-p div))
1705 (truncate-derive-type-quot num div)
1708 (defun truncate-derive-type-rem-aux (num div same-arg)
1709 (declare (ignore same-arg))
1710 (if (and (numeric-type-real-p num)
1711 (numeric-type-real-p div))
1712 (truncate-derive-type-rem num div)
1715 (defoptimizer (truncate derive-type) ((number divisor))
1716 (let ((quot (two-arg-derive-type number divisor
1717 #'truncate-derive-type-quot-aux #'truncate))
1718 (rem (two-arg-derive-type number divisor
1719 #'truncate-derive-type-rem-aux #'rem)))
1720 (when (and quot rem)
1721 (make-values-type :required (list quot rem)))))
1723 (defun ftruncate-derive-type-quot (number-type divisor-type)
1724 ;; The bounds are the same as for truncate. However, the first
1725 ;; result is a float of some type. We need to determine what that
1726 ;; type is. Basically it's the more contagious of the two types.
1727 (let ((q-type (truncate-derive-type-quot number-type divisor-type))
1728 (res-type (numeric-contagion number-type divisor-type)))
1729 (make-numeric-type :class 'float
1730 :format (numeric-type-format res-type)
1731 :low (numeric-type-low q-type)
1732 :high (numeric-type-high q-type))))
1734 (defun ftruncate-derive-type-quot-aux (n d same-arg)
1735 (declare (ignore same-arg))
1736 (if (and (numeric-type-real-p n)
1737 (numeric-type-real-p d))
1738 (ftruncate-derive-type-quot n d)
1741 (defoptimizer (ftruncate derive-type) ((number divisor))
1743 (two-arg-derive-type number divisor
1744 #'ftruncate-derive-type-quot-aux #'ftruncate))
1745 (rem (two-arg-derive-type number divisor
1746 #'truncate-derive-type-rem-aux #'rem)))
1747 (when (and quot rem)
1748 (make-values-type :required (list quot rem)))))
1750 (defun %unary-truncate-derive-type-aux (number)
1751 (truncate-derive-type-quot number (specifier-type '(integer 1 1))))
1753 (defoptimizer (%unary-truncate derive-type) ((number))
1754 (one-arg-derive-type number
1755 #'%unary-truncate-derive-type-aux
1758 (defoptimizer (%unary-ftruncate derive-type) ((number))
1759 (let ((divisor (specifier-type '(integer 1 1))))
1760 (one-arg-derive-type number
1762 (ftruncate-derive-type-quot-aux n divisor nil))
1763 #'%unary-ftruncate)))
1765 ;;; Define optimizers for FLOOR and CEILING.
1767 ((def (name q-name r-name)
1768 (let ((q-aux (symbolicate q-name "-AUX"))
1769 (r-aux (symbolicate r-name "-AUX")))
1771 ;; Compute type of quotient (first) result.
1772 (defun ,q-aux (number-type divisor-type)
1773 (let* ((number-interval
1774 (numeric-type->interval number-type))
1776 (numeric-type->interval divisor-type))
1777 (quot (,q-name (interval-div number-interval
1778 divisor-interval))))
1779 (specifier-type `(integer ,(or (interval-low quot) '*)
1780 ,(or (interval-high quot) '*)))))
1781 ;; Compute type of remainder.
1782 (defun ,r-aux (number-type divisor-type)
1783 (let* ((divisor-interval
1784 (numeric-type->interval divisor-type))
1785 (rem (,r-name divisor-interval))
1786 (result-type (rem-result-type number-type divisor-type)))
1787 (multiple-value-bind (class format)
1790 (values 'integer nil))
1792 (values 'rational nil))
1793 ((or single-float double-float #!+long-float long-float)
1794 (values 'float result-type))
1796 (values 'float nil))
1799 (when (member result-type '(float single-float double-float
1800 #!+long-float long-float))
1801 ;; Make sure that the limits on the interval have
1803 (setf rem (interval-func (lambda (x)
1804 (coerce-for-bound x result-type))
1806 (make-numeric-type :class class
1808 :low (interval-low rem)
1809 :high (interval-high rem)))))
1810 ;; the optimizer itself
1811 (defoptimizer (,name derive-type) ((number divisor))
1812 (flet ((derive-q (n d same-arg)
1813 (declare (ignore same-arg))
1814 (if (and (numeric-type-real-p n)
1815 (numeric-type-real-p d))
1818 (derive-r (n d same-arg)
1819 (declare (ignore same-arg))
1820 (if (and (numeric-type-real-p n)
1821 (numeric-type-real-p d))
1824 (let ((quot (two-arg-derive-type
1825 number divisor #'derive-q #',name))
1826 (rem (two-arg-derive-type
1827 number divisor #'derive-r #'mod)))
1828 (when (and quot rem)
1829 (make-values-type :required (list quot rem))))))))))
1831 (def floor floor-quotient-bound floor-rem-bound)
1832 (def ceiling ceiling-quotient-bound ceiling-rem-bound))
1834 ;;; Define optimizers for FFLOOR and FCEILING
1835 (macrolet ((def (name q-name r-name)
1836 (let ((q-aux (symbolicate "F" q-name "-AUX"))
1837 (r-aux (symbolicate r-name "-AUX")))
1839 ;; Compute type of quotient (first) result.
1840 (defun ,q-aux (number-type divisor-type)
1841 (let* ((number-interval
1842 (numeric-type->interval number-type))
1844 (numeric-type->interval divisor-type))
1845 (quot (,q-name (interval-div number-interval
1847 (res-type (numeric-contagion number-type
1850 :class (numeric-type-class res-type)
1851 :format (numeric-type-format res-type)
1852 :low (interval-low quot)
1853 :high (interval-high quot))))
1855 (defoptimizer (,name derive-type) ((number divisor))
1856 (flet ((derive-q (n d same-arg)
1857 (declare (ignore same-arg))
1858 (if (and (numeric-type-real-p n)
1859 (numeric-type-real-p d))
1862 (derive-r (n d same-arg)
1863 (declare (ignore same-arg))
1864 (if (and (numeric-type-real-p n)
1865 (numeric-type-real-p d))
1868 (let ((quot (two-arg-derive-type
1869 number divisor #'derive-q #',name))
1870 (rem (two-arg-derive-type
1871 number divisor #'derive-r #'mod)))
1872 (when (and quot rem)
1873 (make-values-type :required (list quot rem))))))))))
1875 (def ffloor floor-quotient-bound floor-rem-bound)
1876 (def fceiling ceiling-quotient-bound ceiling-rem-bound))
1878 ;;; functions to compute the bounds on the quotient and remainder for
1879 ;;; the FLOOR function
1880 (defun floor-quotient-bound (quot)
1881 ;; Take the floor of the quotient and then massage it into what we
1883 (let ((lo (interval-low quot))
1884 (hi (interval-high quot)))
1885 ;; Take the floor of the lower bound. The result is always a
1886 ;; closed lower bound.
1888 (floor (type-bound-number lo))
1890 ;; For the upper bound, we need to be careful.
1893 ;; An open bound. We need to be careful here because
1894 ;; the floor of '(10.0) is 9, but the floor of
1896 (multiple-value-bind (q r) (floor (first hi))
1901 ;; A closed bound, so the answer is obvious.
1905 (make-interval :low lo :high hi)))
1906 (defun floor-rem-bound (div)
1907 ;; The remainder depends only on the divisor. Try to get the
1908 ;; correct sign for the remainder if we can.
1909 (case (interval-range-info div)
1911 ;; The divisor is always positive.
1912 (let ((rem (interval-abs div)))
1913 (setf (interval-low rem) 0)
1914 (when (and (numberp (interval-high rem))
1915 (not (zerop (interval-high rem))))
1916 ;; The remainder never contains the upper bound. However,
1917 ;; watch out for the case where the high limit is zero!
1918 (setf (interval-high rem) (list (interval-high rem))))
1921 ;; The divisor is always negative.
1922 (let ((rem (interval-neg (interval-abs div))))
1923 (setf (interval-high rem) 0)
1924 (when (numberp (interval-low rem))
1925 ;; The remainder never contains the lower bound.
1926 (setf (interval-low rem) (list (interval-low rem))))
1929 ;; The divisor can be positive or negative. All bets off. The
1930 ;; magnitude of remainder is the maximum value of the divisor.
1931 (let ((limit (type-bound-number (interval-high (interval-abs div)))))
1932 ;; The bound never reaches the limit, so make the interval open.
1933 (make-interval :low (if limit
1936 :high (list limit))))))
1938 (floor-quotient-bound (make-interval :low 0.3 :high 10.3))
1939 => #S(INTERVAL :LOW 0 :HIGH 10)
1940 (floor-quotient-bound (make-interval :low 0.3 :high '(10.3)))
1941 => #S(INTERVAL :LOW 0 :HIGH 10)
1942 (floor-quotient-bound (make-interval :low 0.3 :high 10))
1943 => #S(INTERVAL :LOW 0 :HIGH 10)
1944 (floor-quotient-bound (make-interval :low 0.3 :high '(10)))
1945 => #S(INTERVAL :LOW 0 :HIGH 9)
1946 (floor-quotient-bound (make-interval :low '(0.3) :high 10.3))
1947 => #S(INTERVAL :LOW 0 :HIGH 10)
1948 (floor-quotient-bound (make-interval :low '(0.0) :high 10.3))
1949 => #S(INTERVAL :LOW 0 :HIGH 10)
1950 (floor-quotient-bound (make-interval :low '(-1.3) :high 10.3))
1951 => #S(INTERVAL :LOW -2 :HIGH 10)
1952 (floor-quotient-bound (make-interval :low '(-1.0) :high 10.3))
1953 => #S(INTERVAL :LOW -1 :HIGH 10)
1954 (floor-quotient-bound (make-interval :low -1.0 :high 10.3))
1955 => #S(INTERVAL :LOW -1 :HIGH 10)
1957 (floor-rem-bound (make-interval :low 0.3 :high 10.3))
1958 => #S(INTERVAL :LOW 0 :HIGH '(10.3))
1959 (floor-rem-bound (make-interval :low 0.3 :high '(10.3)))
1960 => #S(INTERVAL :LOW 0 :HIGH '(10.3))
1961 (floor-rem-bound (make-interval :low -10 :high -2.3))
1962 #S(INTERVAL :LOW (-10) :HIGH 0)
1963 (floor-rem-bound (make-interval :low 0.3 :high 10))
1964 => #S(INTERVAL :LOW 0 :HIGH '(10))
1965 (floor-rem-bound (make-interval :low '(-1.3) :high 10.3))
1966 => #S(INTERVAL :LOW '(-10.3) :HIGH '(10.3))
1967 (floor-rem-bound (make-interval :low '(-20.3) :high 10.3))
1968 => #S(INTERVAL :LOW (-20.3) :HIGH (20.3))
1971 ;;; same functions for CEILING
1972 (defun ceiling-quotient-bound (quot)
1973 ;; Take the ceiling of the quotient and then massage it into what we
1975 (let ((lo (interval-low quot))
1976 (hi (interval-high quot)))
1977 ;; Take the ceiling of the upper bound. The result is always a
1978 ;; closed upper bound.
1980 (ceiling (type-bound-number hi))
1982 ;; For the lower bound, we need to be careful.
1985 ;; An open bound. We need to be careful here because
1986 ;; the ceiling of '(10.0) is 11, but the ceiling of
1988 (multiple-value-bind (q r) (ceiling (first lo))
1993 ;; A closed bound, so the answer is obvious.
1997 (make-interval :low lo :high hi)))
1998 (defun ceiling-rem-bound (div)
1999 ;; The remainder depends only on the divisor. Try to get the
2000 ;; correct sign for the remainder if we can.
2001 (case (interval-range-info div)
2003 ;; Divisor is always positive. The remainder is negative.
2004 (let ((rem (interval-neg (interval-abs div))))
2005 (setf (interval-high rem) 0)
2006 (when (and (numberp (interval-low rem))
2007 (not (zerop (interval-low rem))))
2008 ;; The remainder never contains the upper bound. However,
2009 ;; watch out for the case when the upper bound is zero!
2010 (setf (interval-low rem) (list (interval-low rem))))
2013 ;; Divisor is always negative. The remainder is positive
2014 (let ((rem (interval-abs div)))
2015 (setf (interval-low rem) 0)
2016 (when (numberp (interval-high rem))
2017 ;; The remainder never contains the lower bound.
2018 (setf (interval-high rem) (list (interval-high rem))))
2021 ;; The divisor can be positive or negative. All bets off. The
2022 ;; magnitude of remainder is the maximum value of the divisor.
2023 (let ((limit (type-bound-number (interval-high (interval-abs div)))))
2024 ;; The bound never reaches the limit, so make the interval open.
2025 (make-interval :low (if limit
2028 :high (list limit))))))
2031 (ceiling-quotient-bound (make-interval :low 0.3 :high 10.3))
2032 => #S(INTERVAL :LOW 1 :HIGH 11)
2033 (ceiling-quotient-bound (make-interval :low 0.3 :high '(10.3)))
2034 => #S(INTERVAL :LOW 1 :HIGH 11)
2035 (ceiling-quotient-bound (make-interval :low 0.3 :high 10))
2036 => #S(INTERVAL :LOW 1 :HIGH 10)
2037 (ceiling-quotient-bound (make-interval :low 0.3 :high '(10)))
2038 => #S(INTERVAL :LOW 1 :HIGH 10)
2039 (ceiling-quotient-bound (make-interval :low '(0.3) :high 10.3))
2040 => #S(INTERVAL :LOW 1 :HIGH 11)
2041 (ceiling-quotient-bound (make-interval :low '(0.0) :high 10.3))
2042 => #S(INTERVAL :LOW 1 :HIGH 11)
2043 (ceiling-quotient-bound (make-interval :low '(-1.3) :high 10.3))
2044 => #S(INTERVAL :LOW -1 :HIGH 11)
2045 (ceiling-quotient-bound (make-interval :low '(-1.0) :high 10.3))
2046 => #S(INTERVAL :LOW 0 :HIGH 11)
2047 (ceiling-quotient-bound (make-interval :low -1.0 :high 10.3))
2048 => #S(INTERVAL :LOW -1 :HIGH 11)
2050 (ceiling-rem-bound (make-interval :low 0.3 :high 10.3))
2051 => #S(INTERVAL :LOW (-10.3) :HIGH 0)
2052 (ceiling-rem-bound (make-interval :low 0.3 :high '(10.3)))
2053 => #S(INTERVAL :LOW 0 :HIGH '(10.3))
2054 (ceiling-rem-bound (make-interval :low -10 :high -2.3))
2055 => #S(INTERVAL :LOW 0 :HIGH (10))
2056 (ceiling-rem-bound (make-interval :low 0.3 :high 10))
2057 => #S(INTERVAL :LOW (-10) :HIGH 0)
2058 (ceiling-rem-bound (make-interval :low '(-1.3) :high 10.3))
2059 => #S(INTERVAL :LOW (-10.3) :HIGH (10.3))
2060 (ceiling-rem-bound (make-interval :low '(-20.3) :high 10.3))
2061 => #S(INTERVAL :LOW (-20.3) :HIGH (20.3))
2064 (defun truncate-quotient-bound (quot)
2065 ;; For positive quotients, truncate is exactly like floor. For
2066 ;; negative quotients, truncate is exactly like ceiling. Otherwise,
2067 ;; it's the union of the two pieces.
2068 (case (interval-range-info quot)
2071 (floor-quotient-bound quot))
2073 ;; just like CEILING
2074 (ceiling-quotient-bound quot))
2076 ;; Split the interval into positive and negative pieces, compute
2077 ;; the result for each piece and put them back together.
2078 (destructuring-bind (neg pos) (interval-split 0 quot t t)
2079 (interval-merge-pair (ceiling-quotient-bound neg)
2080 (floor-quotient-bound pos))))))
2082 (defun truncate-rem-bound (num div)
2083 ;; This is significantly more complicated than FLOOR or CEILING. We
2084 ;; need both the number and the divisor to determine the range. The
2085 ;; basic idea is to split the ranges of NUM and DEN into positive
2086 ;; and negative pieces and deal with each of the four possibilities
2088 (case (interval-range-info num)
2090 (case (interval-range-info div)
2092 (floor-rem-bound div))
2094 (ceiling-rem-bound div))
2096 (destructuring-bind (neg pos) (interval-split 0 div t t)
2097 (interval-merge-pair (truncate-rem-bound num neg)
2098 (truncate-rem-bound num pos))))))
2100 (case (interval-range-info div)
2102 (ceiling-rem-bound div))
2104 (floor-rem-bound div))
2106 (destructuring-bind (neg pos) (interval-split 0 div t t)
2107 (interval-merge-pair (truncate-rem-bound num neg)
2108 (truncate-rem-bound num pos))))))
2110 (destructuring-bind (neg pos) (interval-split 0 num t t)
2111 (interval-merge-pair (truncate-rem-bound neg div)
2112 (truncate-rem-bound pos div))))))
2115 ;;; Derive useful information about the range. Returns three values:
2116 ;;; - '+ if its positive, '- negative, or nil if it overlaps 0.
2117 ;;; - The abs of the minimal value (i.e. closest to 0) in the range.
2118 ;;; - The abs of the maximal value if there is one, or nil if it is
2120 (defun numeric-range-info (low high)
2121 (cond ((and low (not (minusp low)))
2122 (values '+ low high))
2123 ((and high (not (plusp high)))
2124 (values '- (- high) (if low (- low) nil)))
2126 (values nil 0 (and low high (max (- low) high))))))
2128 (defun integer-truncate-derive-type
2129 (number-low number-high divisor-low divisor-high)
2130 ;; The result cannot be larger in magnitude than the number, but the
2131 ;; sign might change. If we can determine the sign of either the
2132 ;; number or the divisor, we can eliminate some of the cases.
2133 (multiple-value-bind (number-sign number-min number-max)
2134 (numeric-range-info number-low number-high)
2135 (multiple-value-bind (divisor-sign divisor-min divisor-max)
2136 (numeric-range-info divisor-low divisor-high)
2137 (when (and divisor-max (zerop divisor-max))
2138 ;; We've got a problem: guaranteed division by zero.
2139 (return-from integer-truncate-derive-type t))
2140 (when (zerop divisor-min)
2141 ;; We'll assume that they aren't going to divide by zero.
2143 (cond ((and number-sign divisor-sign)
2144 ;; We know the sign of both.
2145 (if (eq number-sign divisor-sign)
2146 ;; Same sign, so the result will be positive.
2147 `(integer ,(if divisor-max
2148 (truncate number-min divisor-max)
2151 (truncate number-max divisor-min)
2153 ;; Different signs, the result will be negative.
2154 `(integer ,(if number-max
2155 (- (truncate number-max divisor-min))
2158 (- (truncate number-min divisor-max))
2160 ((eq divisor-sign '+)
2161 ;; The divisor is positive. Therefore, the number will just
2162 ;; become closer to zero.
2163 `(integer ,(if number-low
2164 (truncate number-low divisor-min)
2167 (truncate number-high divisor-min)
2169 ((eq divisor-sign '-)
2170 ;; The divisor is negative. Therefore, the absolute value of
2171 ;; the number will become closer to zero, but the sign will also
2173 `(integer ,(if number-high
2174 (- (truncate number-high divisor-min))
2177 (- (truncate number-low divisor-min))
2179 ;; The divisor could be either positive or negative.
2181 ;; The number we are dividing has a bound. Divide that by the
2182 ;; smallest posible divisor.
2183 (let ((bound (truncate number-max divisor-min)))
2184 `(integer ,(- bound) ,bound)))
2186 ;; The number we are dividing is unbounded, so we can't tell
2187 ;; anything about the result.
2190 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2191 (defun integer-rem-derive-type
2192 (number-low number-high divisor-low divisor-high)
2193 (if (and divisor-low divisor-high)
2194 ;; We know the range of the divisor, and the remainder must be
2195 ;; smaller than the divisor. We can tell the sign of the
2196 ;; remainer if we know the sign of the number.
2197 (let ((divisor-max (1- (max (abs divisor-low) (abs divisor-high)))))
2198 `(integer ,(if (or (null number-low)
2199 (minusp number-low))
2202 ,(if (or (null number-high)
2203 (plusp number-high))
2206 ;; The divisor is potentially either very positive or very
2207 ;; negative. Therefore, the remainer is unbounded, but we might
2208 ;; be able to tell something about the sign from the number.
2209 `(integer ,(if (and number-low (not (minusp number-low)))
2210 ;; The number we are dividing is positive.
2211 ;; Therefore, the remainder must be positive.
2214 ,(if (and number-high (not (plusp number-high)))
2215 ;; The number we are dividing is negative.
2216 ;; Therefore, the remainder must be negative.
2220 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2221 (defoptimizer (random derive-type) ((bound &optional state))
2222 (let ((type (lvar-type bound)))
2223 (when (numeric-type-p type)
2224 (let ((class (numeric-type-class type))
2225 (high (numeric-type-high type))
2226 (format (numeric-type-format type)))
2230 :low (coerce 0 (or format class 'real))
2231 :high (cond ((not high) nil)
2232 ((eq class 'integer) (max (1- high) 0))
2233 ((or (consp high) (zerop high)) high)
2236 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2237 (defun random-derive-type-aux (type)
2238 (let ((class (numeric-type-class type))
2239 (high (numeric-type-high type))
2240 (format (numeric-type-format type)))
2244 :low (coerce 0 (or format class 'real))
2245 :high (cond ((not high) nil)
2246 ((eq class 'integer) (max (1- high) 0))
2247 ((or (consp high) (zerop high)) high)
2250 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2251 (defoptimizer (random derive-type) ((bound &optional state))
2252 (one-arg-derive-type bound #'random-derive-type-aux nil))
2254 ;;;; DERIVE-TYPE methods for LOGAND, LOGIOR, and friends
2256 ;;; Return the maximum number of bits an integer of the supplied type
2257 ;;; can take up, or NIL if it is unbounded. The second (third) value
2258 ;;; is T if the integer can be positive (negative) and NIL if not.
2259 ;;; Zero counts as positive.
2260 (defun integer-type-length (type)
2261 (if (numeric-type-p type)
2262 (let ((min (numeric-type-low type))
2263 (max (numeric-type-high type)))
2264 (values (and min max (max (integer-length min) (integer-length max)))
2265 (or (null max) (not (minusp max)))
2266 (or (null min) (minusp min))))
2269 ;;; See _Hacker's Delight_, Henry S. Warren, Jr. pp 58-63 for an
2270 ;;; explanation of LOG{AND,IOR,XOR}-DERIVE-UNSIGNED-{LOW,HIGH}-BOUND.
2271 ;;; Credit also goes to Raymond Toy for writing (and debugging!) similar
2272 ;;; versions in CMUCL, from which these functions copy liberally.
2274 (defun logand-derive-unsigned-low-bound (x y)
2275 (let ((a (numeric-type-low x))
2276 (b (numeric-type-high x))
2277 (c (numeric-type-low y))
2278 (d (numeric-type-high y)))
2279 (loop for m = (ash 1 (integer-length (lognor a c))) then (ash m -1)
2281 (unless (zerop (logand m (lognot a) (lognot c)))
2282 (let ((temp (logandc2 (logior a m) (1- m))))
2286 (setf temp (logandc2 (logior c m) (1- m)))
2290 finally (return (logand a c)))))
2292 (defun logand-derive-unsigned-high-bound (x y)
2293 (let ((a (numeric-type-low x))
2294 (b (numeric-type-high x))
2295 (c (numeric-type-low y))
2296 (d (numeric-type-high y)))
2297 (loop for m = (ash 1 (integer-length (logxor b d))) then (ash m -1)
2300 ((not (zerop (logand b (lognot d) m)))
2301 (let ((temp (logior (logandc2 b m) (1- m))))
2305 ((not (zerop (logand (lognot b) d m)))
2306 (let ((temp (logior (logandc2 d m) (1- m))))
2310 finally (return (logand b d)))))
2312 (defun logand-derive-type-aux (x y &optional same-leaf)
2314 (return-from logand-derive-type-aux x))
2315 (multiple-value-bind (x-len x-pos x-neg) (integer-type-length x)
2316 (declare (ignore x-pos))
2317 (multiple-value-bind (y-len y-pos y-neg) (integer-type-length y)
2318 (declare (ignore y-pos))
2320 ;; X must be positive.
2322 ;; They must both be positive.
2323 (cond ((and (null x-len) (null y-len))
2324 (specifier-type 'unsigned-byte))
2326 (specifier-type `(unsigned-byte* ,y-len)))
2328 (specifier-type `(unsigned-byte* ,x-len)))
2330 (let ((low (logand-derive-unsigned-low-bound x y))
2331 (high (logand-derive-unsigned-high-bound x y)))
2332 (specifier-type `(integer ,low ,high)))))
2333 ;; X is positive, but Y might be negative.
2335 (specifier-type 'unsigned-byte))
2337 (specifier-type `(unsigned-byte* ,x-len)))))
2338 ;; X might be negative.
2340 ;; Y must be positive.
2342 (specifier-type 'unsigned-byte))
2343 (t (specifier-type `(unsigned-byte* ,y-len))))
2344 ;; Either might be negative.
2345 (if (and x-len y-len)
2346 ;; The result is bounded.
2347 (specifier-type `(signed-byte ,(1+ (max x-len y-len))))
2348 ;; We can't tell squat about the result.
2349 (specifier-type 'integer)))))))
2351 (defun logior-derive-unsigned-low-bound (x y)
2352 (let ((a (numeric-type-low x))
2353 (b (numeric-type-high x))
2354 (c (numeric-type-low y))
2355 (d (numeric-type-high y)))
2356 (loop for m = (ash 1 (integer-length (logxor a c))) then (ash m -1)
2359 ((not (zerop (logandc2 (logand c m) a)))
2360 (let ((temp (logand (logior a m) (1+ (lognot m)))))
2364 ((not (zerop (logandc2 (logand a m) c)))
2365 (let ((temp (logand (logior c m) (1+ (lognot m)))))
2369 finally (return (logior a c)))))
2371 (defun logior-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 (logand b d))) then (ash m -1)
2378 (unless (zerop (logand b d m))
2379 (let ((temp (logior (- b m) (1- m))))
2383 (setf temp (logior (- d m) (1- m)))
2387 finally (return (logior b d)))))
2389 (defun logior-derive-type-aux (x y &optional same-leaf)
2391 (return-from logior-derive-type-aux x))
2392 (multiple-value-bind (x-len x-pos x-neg) (integer-type-length x)
2393 (multiple-value-bind (y-len y-pos y-neg) (integer-type-length y)
2395 ((and (not x-neg) (not y-neg))
2396 ;; Both are positive.
2397 (if (and x-len y-len)
2398 (let ((low (logior-derive-unsigned-low-bound x y))
2399 (high (logior-derive-unsigned-high-bound x y)))
2400 (specifier-type `(integer ,low ,high)))
2401 (specifier-type `(unsigned-byte* *))))
2403 ;; X must be negative.
2405 ;; Both are negative. The result is going to be negative
2406 ;; and be the same length or shorter than the smaller.
2407 (if (and x-len y-len)
2409 (specifier-type `(integer ,(ash -1 (min x-len y-len)) -1))
2411 (specifier-type '(integer * -1)))
2412 ;; X is negative, but we don't know about Y. The result
2413 ;; will be negative, but no more negative than X.
2415 `(integer ,(or (numeric-type-low x) '*)
2418 ;; X might be either positive or negative.
2420 ;; But Y is negative. The result will be negative.
2422 `(integer ,(or (numeric-type-low y) '*)
2424 ;; We don't know squat about either. It won't get any bigger.
2425 (if (and x-len y-len)
2427 (specifier-type `(signed-byte ,(1+ (max x-len y-len))))
2429 (specifier-type 'integer))))))))
2431 (defun logxor-derive-unsigned-low-bound (x y)
2432 (let ((a (numeric-type-low x))
2433 (b (numeric-type-high x))
2434 (c (numeric-type-low y))
2435 (d (numeric-type-high y)))
2436 (loop for m = (ash 1 (integer-length (logxor a c))) then (ash m -1)
2439 ((not (zerop (logandc2 (logand c m) a)))
2440 (let ((temp (logand (logior a m)
2444 ((not (zerop (logandc2 (logand a m) c)))
2445 (let ((temp (logand (logior c m)
2449 finally (return (logxor a c)))))
2451 (defun logxor-derive-unsigned-high-bound (x y)
2452 (let ((a (numeric-type-low x))
2453 (b (numeric-type-high x))
2454 (c (numeric-type-low y))
2455 (d (numeric-type-high y)))
2456 (loop for m = (ash 1 (integer-length (logand b d))) then (ash m -1)
2458 (unless (zerop (logand b d m))
2459 (let ((temp (logior (- b m) (1- m))))
2461 ((>= temp a) (setf b temp))
2462 (t (let ((temp (logior (- d m) (1- m))))
2465 finally (return (logxor b d)))))
2467 (defun logxor-derive-type-aux (x y &optional same-leaf)
2469 (return-from logxor-derive-type-aux (specifier-type '(eql 0))))
2470 (multiple-value-bind (x-len x-pos x-neg) (integer-type-length x)
2471 (multiple-value-bind (y-len y-pos y-neg) (integer-type-length y)
2473 ((and (not x-neg) (not y-neg))
2474 ;; Both are positive
2475 (if (and x-len y-len)
2476 (let ((low (logxor-derive-unsigned-low-bound x y))
2477 (high (logxor-derive-unsigned-high-bound x y)))
2478 (specifier-type `(integer ,low ,high)))
2479 (specifier-type '(unsigned-byte* *))))
2480 ((and (not x-pos) (not y-pos))
2481 ;; Both are negative. The result will be positive, and as long
2483 (specifier-type `(unsigned-byte* ,(if (and x-len y-len)
2486 ((or (and (not x-pos) (not y-neg))
2487 (and (not y-pos) (not x-neg)))
2488 ;; Either X is negative and Y is positive or vice-versa. The
2489 ;; result will be negative.
2490 (specifier-type `(integer ,(if (and x-len y-len)
2491 (ash -1 (max x-len y-len))
2494 ;; We can't tell what the sign of the result is going to be.
2495 ;; All we know is that we don't create new bits.
2497 (specifier-type `(signed-byte ,(1+ (max x-len y-len)))))
2499 (specifier-type 'integer))))))
2501 (macrolet ((deffrob (logfun)
2502 (let ((fun-aux (symbolicate logfun "-DERIVE-TYPE-AUX")))
2503 `(defoptimizer (,logfun derive-type) ((x y))
2504 (two-arg-derive-type x y #',fun-aux #',logfun)))))
2509 (defoptimizer (logeqv derive-type) ((x y))
2510 (two-arg-derive-type x y (lambda (x y same-leaf)
2511 (lognot-derive-type-aux
2512 (logxor-derive-type-aux x y same-leaf)))
2514 (defoptimizer (lognand derive-type) ((x y))
2515 (two-arg-derive-type x y (lambda (x y same-leaf)
2516 (lognot-derive-type-aux
2517 (logand-derive-type-aux x y same-leaf)))
2519 (defoptimizer (lognor derive-type) ((x y))
2520 (two-arg-derive-type x y (lambda (x y same-leaf)
2521 (lognot-derive-type-aux
2522 (logior-derive-type-aux x y same-leaf)))
2524 (defoptimizer (logandc1 derive-type) ((x y))
2525 (two-arg-derive-type x y (lambda (x y same-leaf)
2527 (specifier-type '(eql 0))
2528 (logand-derive-type-aux
2529 (lognot-derive-type-aux x) y nil)))
2531 (defoptimizer (logandc2 derive-type) ((x y))
2532 (two-arg-derive-type x y (lambda (x y same-leaf)
2534 (specifier-type '(eql 0))
2535 (logand-derive-type-aux
2536 x (lognot-derive-type-aux y) nil)))
2538 (defoptimizer (logorc1 derive-type) ((x y))
2539 (two-arg-derive-type x y (lambda (x y same-leaf)
2541 (specifier-type '(eql -1))
2542 (logior-derive-type-aux
2543 (lognot-derive-type-aux x) y nil)))
2545 (defoptimizer (logorc2 derive-type) ((x y))
2546 (two-arg-derive-type x y (lambda (x y same-leaf)
2548 (specifier-type '(eql -1))
2549 (logior-derive-type-aux
2550 x (lognot-derive-type-aux y) nil)))
2553 ;;;; miscellaneous derive-type methods
2555 (defoptimizer (integer-length derive-type) ((x))
2556 (let ((x-type (lvar-type x)))
2557 (when (numeric-type-p x-type)
2558 ;; If the X is of type (INTEGER LO HI), then the INTEGER-LENGTH
2559 ;; of X is (INTEGER (MIN lo hi) (MAX lo hi), basically. Be
2560 ;; careful about LO or HI being NIL, though. Also, if 0 is
2561 ;; contained in X, the lower bound is obviously 0.
2562 (flet ((null-or-min (a b)
2563 (and a b (min (integer-length a)
2564 (integer-length b))))
2566 (and a b (max (integer-length a)
2567 (integer-length b)))))
2568 (let* ((min (numeric-type-low x-type))
2569 (max (numeric-type-high x-type))
2570 (min-len (null-or-min min max))
2571 (max-len (null-or-max min max)))
2572 (when (ctypep 0 x-type)
2574 (specifier-type `(integer ,(or min-len '*) ,(or max-len '*))))))))
2576 (defoptimizer (isqrt derive-type) ((x))
2577 (let ((x-type (lvar-type x)))
2578 (when (numeric-type-p x-type)
2579 (let* ((lo (numeric-type-low x-type))
2580 (hi (numeric-type-high x-type))
2581 (lo-res (if lo (isqrt lo) '*))
2582 (hi-res (if hi (isqrt hi) '*)))
2583 (specifier-type `(integer ,lo-res ,hi-res))))))
2585 (defoptimizer (code-char derive-type) ((code))
2586 (let ((type (lvar-type code)))
2587 ;; FIXME: unions of integral ranges? It ought to be easier to do
2588 ;; this, given that CHARACTER-SET is basically an integral range
2589 ;; type. -- CSR, 2004-10-04
2590 (when (numeric-type-p type)
2591 (let* ((lo (numeric-type-low type))
2592 (hi (numeric-type-high type))
2593 (type (specifier-type `(character-set ((,lo . ,hi))))))
2595 ;; KLUDGE: when running on the host, we lose a slight amount
2596 ;; of precision so that we don't have to "unparse" types
2597 ;; that formally we can't, such as (CHARACTER-SET ((0
2598 ;; . 0))). -- CSR, 2004-10-06
2600 ((csubtypep type (specifier-type 'standard-char)) type)
2602 ((csubtypep type (specifier-type 'base-char))
2603 (specifier-type 'base-char))
2605 ((csubtypep type (specifier-type 'extended-char))
2606 (specifier-type 'extended-char))
2607 (t #+sb-xc-host (specifier-type 'character)
2608 #-sb-xc-host type))))))
2610 (defoptimizer (values derive-type) ((&rest values))
2611 (make-values-type :required (mapcar #'lvar-type values)))
2613 (defun signum-derive-type-aux (type)
2614 (if (eq (numeric-type-complexp type) :complex)
2615 (let* ((format (case (numeric-type-class type)
2616 ((integer rational) 'single-float)
2617 (t (numeric-type-format type))))
2618 (bound-format (or format 'float)))
2619 (make-numeric-type :class 'float
2622 :low (coerce -1 bound-format)
2623 :high (coerce 1 bound-format)))
2624 (let* ((interval (numeric-type->interval type))
2625 (range-info (interval-range-info interval))
2626 (contains-0-p (interval-contains-p 0 interval))
2627 (class (numeric-type-class type))
2628 (format (numeric-type-format type))
2629 (one (coerce 1 (or format class 'real)))
2630 (zero (coerce 0 (or format class 'real)))
2631 (minus-one (coerce -1 (or format class 'real)))
2632 (plus (make-numeric-type :class class :format format
2633 :low one :high one))
2634 (minus (make-numeric-type :class class :format format
2635 :low minus-one :high minus-one))
2636 ;; KLUDGE: here we have a fairly horrible hack to deal
2637 ;; with the schizophrenia in the type derivation engine.
2638 ;; The problem is that the type derivers reinterpret
2639 ;; numeric types as being exact; so (DOUBLE-FLOAT 0d0
2640 ;; 0d0) within the derivation mechanism doesn't include
2641 ;; -0d0. Ugh. So force it in here, instead.
2642 (zero (make-numeric-type :class class :format format
2643 :low (- zero) :high zero)))
2645 (+ (if contains-0-p (type-union plus zero) plus))
2646 (- (if contains-0-p (type-union minus zero) minus))
2647 (t (type-union minus zero plus))))))
2649 (defoptimizer (signum derive-type) ((num))
2650 (one-arg-derive-type num #'signum-derive-type-aux nil))
2652 ;;;; byte operations
2654 ;;;; We try to turn byte operations into simple logical operations.
2655 ;;;; First, we convert byte specifiers into separate size and position
2656 ;;;; arguments passed to internal %FOO functions. We then attempt to
2657 ;;;; transform the %FOO functions into boolean operations when the
2658 ;;;; size and position are constant and the operands are fixnums.
2660 (macrolet (;; Evaluate body with SIZE-VAR and POS-VAR bound to
2661 ;; expressions that evaluate to the SIZE and POSITION of
2662 ;; the byte-specifier form SPEC. We may wrap a let around
2663 ;; the result of the body to bind some variables.
2665 ;; If the spec is a BYTE form, then bind the vars to the
2666 ;; subforms. otherwise, evaluate SPEC and use the BYTE-SIZE
2667 ;; and BYTE-POSITION. The goal of this transformation is to
2668 ;; avoid consing up byte specifiers and then immediately
2669 ;; throwing them away.
2670 (with-byte-specifier ((size-var pos-var spec) &body body)
2671 (once-only ((spec `(macroexpand ,spec))
2673 `(if (and (consp ,spec)
2674 (eq (car ,spec) 'byte)
2675 (= (length ,spec) 3))
2676 (let ((,size-var (second ,spec))
2677 (,pos-var (third ,spec)))
2679 (let ((,size-var `(byte-size ,,temp))
2680 (,pos-var `(byte-position ,,temp)))
2681 `(let ((,,temp ,,spec))
2684 (define-source-transform ldb (spec int)
2685 (with-byte-specifier (size pos spec)
2686 `(%ldb ,size ,pos ,int)))
2688 (define-source-transform dpb (newbyte spec int)
2689 (with-byte-specifier (size pos spec)
2690 `(%dpb ,newbyte ,size ,pos ,int)))
2692 (define-source-transform mask-field (spec int)
2693 (with-byte-specifier (size pos spec)
2694 `(%mask-field ,size ,pos ,int)))
2696 (define-source-transform deposit-field (newbyte spec int)
2697 (with-byte-specifier (size pos spec)
2698 `(%deposit-field ,newbyte ,size ,pos ,int))))
2700 (defoptimizer (%ldb derive-type) ((size posn num))
2701 (let ((size (lvar-type size)))
2702 (if (and (numeric-type-p size)
2703 (csubtypep size (specifier-type 'integer)))
2704 (let ((size-high (numeric-type-high size)))
2705 (if (and size-high (<= size-high sb!vm:n-word-bits))
2706 (specifier-type `(unsigned-byte* ,size-high))
2707 (specifier-type 'unsigned-byte)))
2710 (defoptimizer (%mask-field derive-type) ((size posn num))
2711 (let ((size (lvar-type size))
2712 (posn (lvar-type posn)))
2713 (if (and (numeric-type-p size)
2714 (csubtypep size (specifier-type 'integer))
2715 (numeric-type-p posn)
2716 (csubtypep posn (specifier-type 'integer)))
2717 (let ((size-high (numeric-type-high size))
2718 (posn-high (numeric-type-high posn)))
2719 (if (and size-high posn-high
2720 (<= (+ size-high posn-high) sb!vm:n-word-bits))
2721 (specifier-type `(unsigned-byte* ,(+ size-high posn-high)))
2722 (specifier-type 'unsigned-byte)))
2725 (defun %deposit-field-derive-type-aux (size posn int)
2726 (let ((size (lvar-type size))
2727 (posn (lvar-type posn))
2728 (int (lvar-type int)))
2729 (when (and (numeric-type-p size)
2730 (numeric-type-p posn)
2731 (numeric-type-p int))
2732 (let ((size-high (numeric-type-high size))
2733 (posn-high (numeric-type-high posn))
2734 (high (numeric-type-high int))
2735 (low (numeric-type-low int)))
2736 (when (and size-high posn-high high low
2737 ;; KLUDGE: we need this cutoff here, otherwise we
2738 ;; will merrily derive the type of %DPB as
2739 ;; (UNSIGNED-BYTE 1073741822), and then attempt to
2740 ;; canonicalize this type to (INTEGER 0 (1- (ASH 1
2741 ;; 1073741822))), with hilarious consequences. We
2742 ;; cutoff at 4*SB!VM:N-WORD-BITS to allow inference
2743 ;; over a reasonable amount of shifting, even on
2744 ;; the alpha/32 port, where N-WORD-BITS is 32 but
2745 ;; machine integers are 64-bits. -- CSR,
2747 (<= (+ size-high posn-high) (* 4 sb!vm:n-word-bits)))
2748 (let ((raw-bit-count (max (integer-length high)
2749 (integer-length low)
2750 (+ size-high posn-high))))
2753 `(signed-byte ,(1+ raw-bit-count))
2754 `(unsigned-byte* ,raw-bit-count)))))))))
2756 (defoptimizer (%dpb derive-type) ((newbyte size posn int))
2757 (%deposit-field-derive-type-aux size posn int))
2759 (defoptimizer (%deposit-field derive-type) ((newbyte size posn int))
2760 (%deposit-field-derive-type-aux size posn int))
2762 (deftransform %ldb ((size posn int)
2763 (fixnum fixnum integer)
2764 (unsigned-byte #.sb!vm:n-word-bits))
2765 "convert to inline logical operations"
2766 `(logand (ash int (- posn))
2767 (ash ,(1- (ash 1 sb!vm:n-word-bits))
2768 (- size ,sb!vm:n-word-bits))))
2770 (deftransform %mask-field ((size posn int)
2771 (fixnum fixnum integer)
2772 (unsigned-byte #.sb!vm:n-word-bits))
2773 "convert to inline logical operations"
2775 (ash (ash ,(1- (ash 1 sb!vm:n-word-bits))
2776 (- size ,sb!vm:n-word-bits))
2779 ;;; Note: for %DPB and %DEPOSIT-FIELD, we can't use
2780 ;;; (OR (SIGNED-BYTE N) (UNSIGNED-BYTE N))
2781 ;;; as the result type, as that would allow result types that cover
2782 ;;; the range -2^(n-1) .. 1-2^n, instead of allowing result types of
2783 ;;; (UNSIGNED-BYTE N) and result types of (SIGNED-BYTE N).
2785 (deftransform %dpb ((new size posn int)
2787 (unsigned-byte #.sb!vm:n-word-bits))
2788 "convert to inline logical operations"
2789 `(let ((mask (ldb (byte size 0) -1)))
2790 (logior (ash (logand new mask) posn)
2791 (logand int (lognot (ash mask posn))))))
2793 (deftransform %dpb ((new size posn int)
2795 (signed-byte #.sb!vm:n-word-bits))
2796 "convert to inline logical operations"
2797 `(let ((mask (ldb (byte size 0) -1)))
2798 (logior (ash (logand new mask) posn)
2799 (logand int (lognot (ash mask posn))))))
2801 (deftransform %deposit-field ((new size posn int)
2803 (unsigned-byte #.sb!vm:n-word-bits))
2804 "convert to inline logical operations"
2805 `(let ((mask (ash (ldb (byte size 0) -1) posn)))
2806 (logior (logand new mask)
2807 (logand int (lognot mask)))))
2809 (deftransform %deposit-field ((new size posn int)
2811 (signed-byte #.sb!vm:n-word-bits))
2812 "convert to inline logical operations"
2813 `(let ((mask (ash (ldb (byte size 0) -1) posn)))
2814 (logior (logand new mask)
2815 (logand int (lognot mask)))))
2817 (defoptimizer (mask-signed-field derive-type) ((size x))
2818 (let ((size (lvar-type size)))
2819 (if (numeric-type-p size)
2820 (let ((size-high (numeric-type-high size)))
2821 (if (and size-high (<= 1 size-high sb!vm:n-word-bits))
2822 (specifier-type `(signed-byte ,size-high))
2827 ;;; Modular functions
2829 ;;; (ldb (byte s 0) (foo x y ...)) =
2830 ;;; (ldb (byte s 0) (foo (ldb (byte s 0) x) y ...))
2832 ;;; and similar for other arguments.
2834 (defun make-modular-fun-type-deriver (prototype kind width signedp)
2835 (declare (ignore kind))
2837 (binding* ((info (info :function :info prototype) :exit-if-null)
2838 (fun (fun-info-derive-type info) :exit-if-null)
2839 (mask-type (specifier-type
2841 ((nil) (let ((mask (1- (ash 1 width))))
2842 `(integer ,mask ,mask)))
2843 ((t) `(signed-byte ,width))))))
2845 (let ((res (funcall fun call)))
2847 (if (eq signedp nil)
2848 (logand-derive-type-aux res mask-type))))))
2851 (binding* ((info (info :function :info prototype) :exit-if-null)
2852 (fun (fun-info-derive-type info) :exit-if-null)
2853 (res (funcall fun call) :exit-if-null)
2854 (mask-type (specifier-type
2856 ((nil) (let ((mask (1- (ash 1 width))))
2857 `(integer ,mask ,mask)))
2858 ((t) `(signed-byte ,width))))))
2859 (if (eq signedp nil)
2860 (logand-derive-type-aux res mask-type)))))
2862 ;;; Try to recursively cut all uses of LVAR to WIDTH bits.
2864 ;;; For good functions, we just recursively cut arguments; their
2865 ;;; "goodness" means that the result will not increase (in the
2866 ;;; (unsigned-byte +infinity) sense). An ordinary modular function is
2867 ;;; replaced with the version, cutting its result to WIDTH or more
2868 ;;; bits. For most functions (e.g. for +) we cut all arguments; for
2869 ;;; others (e.g. for ASH) we have "optimizers", cutting only necessary
2870 ;;; arguments (maybe to a different width) and returning the name of a
2871 ;;; modular version, if it exists, or NIL. If we have changed
2872 ;;; anything, we need to flush old derived types, because they have
2873 ;;; nothing in common with the new code.
2874 (defun cut-to-width (lvar kind width signedp)
2875 (declare (type lvar lvar) (type (integer 0) width))
2876 (let ((type (specifier-type (if (zerop width)
2879 ((nil) 'unsigned-byte)
2882 (labels ((reoptimize-node (node name)
2883 (setf (node-derived-type node)
2885 (info :function :type name)))
2886 (setf (lvar-%derived-type (node-lvar node)) nil)
2887 (setf (node-reoptimize node) t)
2888 (setf (block-reoptimize (node-block node)) t)
2889 (reoptimize-component (node-component node) :maybe))
2890 (cut-node (node &aux did-something)
2891 (when (and (not (block-delete-p (node-block node)))
2892 (combination-p node)
2893 (eq (basic-combination-kind node) :known))
2894 (let* ((fun-ref (lvar-use (combination-fun node)))
2895 (fun-name (leaf-source-name (ref-leaf fun-ref)))
2896 (modular-fun (find-modular-version fun-name kind signedp width)))
2897 (when (and modular-fun
2898 (not (and (eq fun-name 'logand)
2900 (single-value-type (node-derived-type node))
2902 (binding* ((name (etypecase modular-fun
2903 ((eql :good) fun-name)
2905 (modular-fun-info-name modular-fun))
2907 (funcall modular-fun node width)))
2909 (unless (eql modular-fun :good)
2910 (setq did-something t)
2913 (find-free-fun name "in a strange place"))
2914 (setf (combination-kind node) :full))
2915 (unless (functionp modular-fun)
2916 (dolist (arg (basic-combination-args node))
2917 (when (cut-lvar arg)
2918 (setq did-something t))))
2920 (reoptimize-node node name))
2922 (cut-lvar (lvar &aux did-something)
2923 (do-uses (node lvar)
2924 (when (cut-node node)
2925 (setq did-something t)))
2929 (defun best-modular-version (width signedp)
2930 ;; 1. exact width-matched :untagged
2931 ;; 2. >/>= width-matched :tagged
2932 ;; 3. >/>= width-matched :untagged
2933 (let* ((uuwidths (modular-class-widths *untagged-unsigned-modular-class*))
2934 (uswidths (modular-class-widths *untagged-signed-modular-class*))
2935 (uwidths (merge 'list uuwidths uswidths #'< :key #'car))
2936 (twidths (modular-class-widths *tagged-modular-class*)))
2937 (let ((exact (find (cons width signedp) uwidths :test #'equal)))
2939 (return-from best-modular-version (values width :untagged signedp))))
2940 (flet ((inexact-match (w)
2942 ((eq signedp (cdr w)) (<= width (car w)))
2943 ((eq signedp nil) (< width (car w))))))
2944 (let ((tgt (find-if #'inexact-match twidths)))
2946 (return-from best-modular-version
2947 (values (car tgt) :tagged (cdr tgt)))))
2948 (let ((ugt (find-if #'inexact-match uwidths)))
2950 (return-from best-modular-version
2951 (values (car ugt) :untagged (cdr ugt))))))))
2953 (defoptimizer (logand optimizer) ((x y) node)
2954 (let ((result-type (single-value-type (node-derived-type node))))
2955 (when (numeric-type-p result-type)
2956 (let ((low (numeric-type-low result-type))
2957 (high (numeric-type-high result-type)))
2958 (when (and (numberp low)
2961 (let ((width (integer-length high)))
2962 (multiple-value-bind (w kind signedp)
2963 (best-modular-version width nil)
2965 ;; FIXME: This should be (CUT-TO-WIDTH NODE KIND WIDTH SIGNEDP).
2966 (cut-to-width x kind width signedp)
2967 (cut-to-width y kind width signedp)
2968 nil ; After fixing above, replace with T.
2971 (defoptimizer (mask-signed-field optimizer) ((width x) node)
2972 (let ((result-type (single-value-type (node-derived-type node))))
2973 (when (numeric-type-p result-type)
2974 (let ((low (numeric-type-low result-type))
2975 (high (numeric-type-high result-type)))
2976 (when (and (numberp low) (numberp high))
2977 (let ((width (max (integer-length high) (integer-length low))))
2978 (multiple-value-bind (w kind)
2979 (best-modular-version width t)
2981 ;; FIXME: This should be (CUT-TO-WIDTH NODE KIND WIDTH T).
2982 (cut-to-width x kind width t)
2983 nil ; After fixing above, replace with T.
2986 ;;; miscellanous numeric transforms
2988 ;;; If a constant appears as the first arg, swap the args.
2989 (deftransform commutative-arg-swap ((x y) * * :defun-only t :node node)
2990 (if (and (constant-lvar-p x)
2991 (not (constant-lvar-p y)))
2992 `(,(lvar-fun-name (basic-combination-fun node))
2995 (give-up-ir1-transform)))
2997 (dolist (x '(= char= + * logior logand logxor))
2998 (%deftransform x '(function * *) #'commutative-arg-swap
2999 "place constant arg last"))
3001 ;;; Handle the case of a constant BOOLE-CODE.
3002 (deftransform boole ((op x y) * *)
3003 "convert to inline logical operations"
3004 (unless (constant-lvar-p op)
3005 (give-up-ir1-transform "BOOLE code is not a constant."))
3006 (let ((control (lvar-value op)))
3008 (#.sb!xc:boole-clr 0)
3009 (#.sb!xc:boole-set -1)
3010 (#.sb!xc:boole-1 'x)
3011 (#.sb!xc:boole-2 'y)
3012 (#.sb!xc:boole-c1 '(lognot x))
3013 (#.sb!xc:boole-c2 '(lognot y))
3014 (#.sb!xc:boole-and '(logand x y))
3015 (#.sb!xc:boole-ior '(logior x y))
3016 (#.sb!xc:boole-xor '(logxor x y))
3017 (#.sb!xc:boole-eqv '(logeqv x y))
3018 (#.sb!xc:boole-nand '(lognand x y))
3019 (#.sb!xc:boole-nor '(lognor x y))
3020 (#.sb!xc:boole-andc1 '(logandc1 x y))
3021 (#.sb!xc:boole-andc2 '(logandc2 x y))
3022 (#.sb!xc:boole-orc1 '(logorc1 x y))
3023 (#.sb!xc:boole-orc2 '(logorc2 x y))
3025 (abort-ir1-transform "~S is an illegal control arg to BOOLE."
3028 ;;;; converting special case multiply/divide to shifts
3030 ;;; If arg is a constant power of two, turn * into a shift.
3031 (deftransform * ((x y) (integer integer) *)
3032 "convert x*2^k to shift"
3033 (unless (constant-lvar-p y)
3034 (give-up-ir1-transform))
3035 (let* ((y (lvar-value y))
3037 (len (1- (integer-length y-abs))))
3038 (unless (and (> y-abs 0) (= y-abs (ash 1 len)))
3039 (give-up-ir1-transform))
3044 ;;; If arg is a constant power of two, turn FLOOR into a shift and
3045 ;;; mask. If CEILING, add in (1- (ABS Y)), do FLOOR and correct a
3047 (flet ((frob (y ceil-p)
3048 (unless (constant-lvar-p y)
3049 (give-up-ir1-transform))
3050 (let* ((y (lvar-value y))
3052 (len (1- (integer-length y-abs))))
3053 (unless (and (> y-abs 0) (= y-abs (ash 1 len)))
3054 (give-up-ir1-transform))
3055 (let ((shift (- len))
3057 (delta (if ceil-p (* (signum y) (1- y-abs)) 0)))
3058 `(let ((x (+ x ,delta)))
3060 `(values (ash (- x) ,shift)
3061 (- (- (logand (- x) ,mask)) ,delta))
3062 `(values (ash x ,shift)
3063 (- (logand x ,mask) ,delta))))))))
3064 (deftransform floor ((x y) (integer integer) *)
3065 "convert division by 2^k to shift"
3067 (deftransform ceiling ((x y) (integer integer) *)
3068 "convert division by 2^k to shift"
3071 ;;; Do the same for MOD.
3072 (deftransform mod ((x y) (integer integer) *)
3073 "convert remainder mod 2^k to LOGAND"
3074 (unless (constant-lvar-p y)
3075 (give-up-ir1-transform))
3076 (let* ((y (lvar-value y))
3078 (len (1- (integer-length y-abs))))
3079 (unless (and (> y-abs 0) (= y-abs (ash 1 len)))
3080 (give-up-ir1-transform))
3081 (let ((mask (1- y-abs)))
3083 `(- (logand (- x) ,mask))
3084 `(logand x ,mask)))))
3086 ;;; If arg is a constant power of two, turn TRUNCATE into a shift and mask.
3087 (deftransform truncate ((x y) (integer integer))
3088 "convert division by 2^k to shift"
3089 (unless (constant-lvar-p y)
3090 (give-up-ir1-transform))
3091 (let* ((y (lvar-value y))
3093 (len (1- (integer-length y-abs))))
3094 (unless (and (> y-abs 0) (= y-abs (ash 1 len)))
3095 (give-up-ir1-transform))
3096 (let* ((shift (- len))
3099 (values ,(if (minusp y)
3101 `(- (ash (- x) ,shift)))
3102 (- (logand (- x) ,mask)))
3103 (values ,(if (minusp y)
3104 `(ash (- ,mask x) ,shift)
3106 (logand x ,mask))))))
3108 ;;; And the same for REM.
3109 (deftransform rem ((x y) (integer integer) *)
3110 "convert remainder mod 2^k to LOGAND"
3111 (unless (constant-lvar-p y)
3112 (give-up-ir1-transform))
3113 (let* ((y (lvar-value y))
3115 (len (1- (integer-length y-abs))))
3116 (unless (and (> y-abs 0) (= y-abs (ash 1 len)))
3117 (give-up-ir1-transform))
3118 (let ((mask (1- y-abs)))
3120 (- (logand (- x) ,mask))
3121 (logand x ,mask)))))
3123 ;;;; arithmetic and logical identity operation elimination
3125 ;;; Flush calls to various arith functions that convert to the
3126 ;;; identity function or a constant.
3127 (macrolet ((def (name identity result)
3128 `(deftransform ,name ((x y) (* (constant-arg (member ,identity))) *)
3129 "fold identity operations"
3136 (def logxor -1 (lognot x))
3139 (deftransform logand ((x y) (* (constant-arg t)) *)
3140 "fold identity operation"
3141 (let ((y (lvar-value y)))
3142 (unless (and (plusp y)
3143 (= y (1- (ash 1 (integer-length y)))))
3144 (give-up-ir1-transform))
3145 (unless (csubtypep (lvar-type x)
3146 (specifier-type `(integer 0 ,y)))
3147 (give-up-ir1-transform))
3150 (deftransform mask-signed-field ((size x) ((constant-arg t) *) *)
3151 "fold identity operation"
3152 (let ((size (lvar-value size)))
3153 (unless (csubtypep (lvar-type x) (specifier-type `(signed-byte ,size)))
3154 (give-up-ir1-transform))
3157 ;;; These are restricted to rationals, because (- 0 0.0) is 0.0, not -0.0, and
3158 ;;; (* 0 -4.0) is -0.0.
3159 (deftransform - ((x y) ((constant-arg (member 0)) rational) *)
3160 "convert (- 0 x) to negate"
3162 (deftransform * ((x y) (rational (constant-arg (member 0))) *)
3163 "convert (* x 0) to 0"
3166 ;;; Return T if in an arithmetic op including lvars X and Y, the
3167 ;;; result type is not affected by the type of X. That is, Y is at
3168 ;;; least as contagious as X.
3170 (defun not-more-contagious (x y)
3171 (declare (type continuation x y))
3172 (let ((x (lvar-type x))
3174 (values (type= (numeric-contagion x y)
3175 (numeric-contagion y y)))))
3176 ;;; Patched version by Raymond Toy. dtc: Should be safer although it
3177 ;;; XXX needs more work as valid transforms are missed; some cases are
3178 ;;; specific to particular transform functions so the use of this
3179 ;;; function may need a re-think.
3180 (defun not-more-contagious (x y)
3181 (declare (type lvar x y))
3182 (flet ((simple-numeric-type (num)
3183 (and (numeric-type-p num)
3184 ;; Return non-NIL if NUM is integer, rational, or a float
3185 ;; of some type (but not FLOAT)
3186 (case (numeric-type-class num)
3190 (numeric-type-format num))
3193 (let ((x (lvar-type x))
3195 (if (and (simple-numeric-type x)
3196 (simple-numeric-type y))
3197 (values (type= (numeric-contagion x y)
3198 (numeric-contagion y y)))))))
3202 ;;; If y is not constant, not zerop, or is contagious, or a positive
3203 ;;; float +0.0 then give up.
3204 (deftransform + ((x y) (t (constant-arg t)) *)
3206 (let ((val (lvar-value y)))
3207 (unless (and (zerop val)
3208 (not (and (floatp val) (plusp (float-sign val))))
3209 (not-more-contagious y x))
3210 (give-up-ir1-transform)))
3215 ;;; If y is not constant, not zerop, or is contagious, or a negative
3216 ;;; float -0.0 then give up.
3217 (deftransform - ((x y) (t (constant-arg t)) *)
3219 (let ((val (lvar-value y)))
3220 (unless (and (zerop val)
3221 (not (and (floatp val) (minusp (float-sign val))))
3222 (not-more-contagious y x))
3223 (give-up-ir1-transform)))
3226 ;;; Fold (OP x +/-1)
3227 (macrolet ((def (name result minus-result)
3228 `(deftransform ,name ((x y) (t (constant-arg real)) *)
3229 "fold identity operations"
3230 (let ((val (lvar-value y)))
3231 (unless (and (= (abs val) 1)
3232 (not-more-contagious y x))
3233 (give-up-ir1-transform))
3234 (if (minusp val) ',minus-result ',result)))))
3235 (def * x (%negate x))
3236 (def / x (%negate x))
3237 (def expt x (/ 1 x)))
3239 ;;; Fold (expt x n) into multiplications for small integral values of
3240 ;;; N; convert (expt x 1/2) to sqrt.
3241 (deftransform expt ((x y) (t (constant-arg real)) *)
3242 "recode as multiplication or sqrt"
3243 (let ((val (lvar-value y)))
3244 ;; If Y would cause the result to be promoted to the same type as
3245 ;; Y, we give up. If not, then the result will be the same type
3246 ;; as X, so we can replace the exponentiation with simple
3247 ;; multiplication and division for small integral powers.
3248 (unless (not-more-contagious y x)
3249 (give-up-ir1-transform))
3251 (let ((x-type (lvar-type x)))
3252 (cond ((csubtypep x-type (specifier-type '(or rational
3253 (complex rational))))
3255 ((csubtypep x-type (specifier-type 'real))
3259 ((csubtypep x-type (specifier-type 'complex))
3260 ;; both parts are float
3262 (t (give-up-ir1-transform)))))
3263 ((= val 2) '(* x x))
3264 ((= val -2) '(/ (* x x)))
3265 ((= val 3) '(* x x x))
3266 ((= val -3) '(/ (* x x x)))
3267 ((= val 1/2) '(sqrt x))
3268 ((= val -1/2) '(/ (sqrt x)))
3269 (t (give-up-ir1-transform)))))
3271 ;;; KLUDGE: Shouldn't (/ 0.0 0.0), etc. cause exceptions in these
3272 ;;; transformations?
3273 ;;; Perhaps we should have to prove that the denominator is nonzero before
3274 ;;; doing them? -- WHN 19990917
3275 (macrolet ((def (name)
3276 `(deftransform ,name ((x y) ((constant-arg (integer 0 0)) integer)
3283 (macrolet ((def (name)
3284 `(deftransform ,name ((x y) ((constant-arg (integer 0 0)) integer)
3293 ;;;; character operations
3295 (deftransform char-equal ((a b) (base-char base-char))
3297 '(let* ((ac (char-code a))
3299 (sum (logxor ac bc)))
3301 (when (eql sum #x20)
3302 (let ((sum (+ ac bc)))
3303 (or (and (> sum 161) (< sum 213))
3304 (and (> sum 415) (< sum 461))
3305 (and (> sum 463) (< sum 477))))))))
3307 (deftransform char-upcase ((x) (base-char))
3309 '(let ((n-code (char-code x)))
3310 (if (or (and (> n-code #o140) ; Octal 141 is #\a.
3311 (< n-code #o173)) ; Octal 172 is #\z.
3312 (and (> n-code #o337)
3314 (and (> n-code #o367)
3316 (code-char (logxor #x20 n-code))
3319 (deftransform char-downcase ((x) (base-char))
3321 '(let ((n-code (char-code x)))
3322 (if (or (and (> n-code 64) ; 65 is #\A.
3323 (< n-code 91)) ; 90 is #\Z.
3328 (code-char (logxor #x20 n-code))
3331 ;;;; equality predicate transforms
3333 ;;; Return true if X and Y are lvars whose only use is a
3334 ;;; reference to the same leaf, and the value of the leaf cannot
3336 (defun same-leaf-ref-p (x y)
3337 (declare (type lvar x y))
3338 (let ((x-use (principal-lvar-use x))
3339 (y-use (principal-lvar-use y)))
3342 (eq (ref-leaf x-use) (ref-leaf y-use))
3343 (constant-reference-p x-use))))
3345 ;;; If X and Y are the same leaf, then the result is true. Otherwise,
3346 ;;; if there is no intersection between the types of the arguments,
3347 ;;; then the result is definitely false.
3348 (deftransform simple-equality-transform ((x y) * *
3351 ((same-leaf-ref-p x y) t)
3352 ((not (types-equal-or-intersect (lvar-type x) (lvar-type y)))
3354 (t (give-up-ir1-transform))))
3357 `(%deftransform ',x '(function * *) #'simple-equality-transform)))
3361 ;;; True if EQL comparisons involving type can be simplified to EQ.
3362 (defun eq-comparable-type-p (type)
3363 (csubtypep type (specifier-type '(or fixnum (not number)))))
3365 ;;; This is similar to SIMPLE-EQUALITY-TRANSFORM, except that we also
3366 ;;; try to convert to a type-specific predicate or EQ:
3367 ;;; -- If both args are characters, convert to CHAR=. This is better than
3368 ;;; just converting to EQ, since CHAR= may have special compilation
3369 ;;; strategies for non-standard representations, etc.
3370 ;;; -- If either arg is definitely a fixnum, we check to see if X is
3371 ;;; constant and if so, put X second. Doing this results in better
3372 ;;; code from the backend, since the backend assumes that any constant
3373 ;;; argument comes second.
3374 ;;; -- If either arg is definitely not a number or a fixnum, then we
3375 ;;; can compare with EQ.
3376 ;;; -- Otherwise, we try to put the arg we know more about second. If X
3377 ;;; is constant then we put it second. If X is a subtype of Y, we put
3378 ;;; it second. These rules make it easier for the back end to match
3379 ;;; these interesting cases.
3380 (deftransform eql ((x y) * * :node node)
3381 "convert to simpler equality predicate"
3382 (let ((x-type (lvar-type x))
3383 (y-type (lvar-type y))
3384 (char-type (specifier-type 'character)))
3385 (flet ((fixnum-type-p (type)
3386 (csubtypep type (specifier-type 'fixnum))))
3388 ((same-leaf-ref-p x y) t)
3389 ((not (types-equal-or-intersect x-type y-type))
3391 ((and (csubtypep x-type char-type)
3392 (csubtypep y-type char-type))
3394 ((or (fixnum-type-p x-type) (fixnum-type-p y-type))
3395 (commutative-arg-swap node))
3396 ((or (eq-comparable-type-p x-type) (eq-comparable-type-p y-type))
3398 ((and (not (constant-lvar-p y))
3399 (or (constant-lvar-p x)
3400 (and (csubtypep x-type y-type)
3401 (not (csubtypep y-type x-type)))))
3404 (give-up-ir1-transform))))))
3406 ;;; similarly to the EQL transform above, we attempt to constant-fold
3407 ;;; or convert to a simpler predicate: mostly we have to be careful
3408 ;;; with strings and bit-vectors.
3409 (deftransform equal ((x y) * *)
3410 "convert to simpler equality predicate"
3411 (let ((x-type (lvar-type x))
3412 (y-type (lvar-type y))
3413 (string-type (specifier-type 'string))
3414 (bit-vector-type (specifier-type 'bit-vector)))
3416 ((same-leaf-ref-p x y) t)
3417 ((and (csubtypep x-type string-type)
3418 (csubtypep y-type string-type))
3420 ((and (csubtypep x-type bit-vector-type)
3421 (csubtypep y-type bit-vector-type))
3422 '(bit-vector-= x y))
3423 ;; if at least one is not a string, and at least one is not a
3424 ;; bit-vector, then we can reason from types.
3425 ((and (not (and (types-equal-or-intersect x-type string-type)
3426 (types-equal-or-intersect y-type string-type)))
3427 (not (and (types-equal-or-intersect x-type bit-vector-type)
3428 (types-equal-or-intersect y-type bit-vector-type)))
3429 (not (types-equal-or-intersect x-type y-type)))
3431 (t (give-up-ir1-transform)))))
3433 ;;; Convert to EQL if both args are rational and complexp is specified
3434 ;;; and the same for both.
3435 (deftransform = ((x y) (number number) *)
3437 (let ((x-type (lvar-type x))
3438 (y-type (lvar-type y)))
3439 (cond ((or (and (csubtypep x-type (specifier-type 'float))
3440 (csubtypep y-type (specifier-type 'float)))
3441 (and (csubtypep x-type (specifier-type '(complex float)))
3442 (csubtypep y-type (specifier-type '(complex float)))))
3443 ;; They are both floats. Leave as = so that -0.0 is
3444 ;; handled correctly.
3445 (give-up-ir1-transform))
3446 ((or (and (csubtypep x-type (specifier-type 'rational))
3447 (csubtypep y-type (specifier-type 'rational)))
3448 (and (csubtypep x-type
3449 (specifier-type '(complex rational)))
3451 (specifier-type '(complex rational)))))
3452 ;; They are both rationals and complexp is the same.
3456 (give-up-ir1-transform
3457 "The operands might not be the same type.")))))
3459 (defun maybe-float-lvar-p (lvar)
3460 (neq *empty-type* (type-intersection (specifier-type 'float)
3463 (flet ((maybe-invert (node op inverted x y)
3464 ;; Don't invert if either argument can be a float (NaNs)
3466 ((or (maybe-float-lvar-p x) (maybe-float-lvar-p y))
3467 (delay-ir1-transform node :constraint)
3468 `(or (,op x y) (= x y)))
3470 `(if (,inverted x y) nil t)))))
3471 (deftransform >= ((x y) (number number) * :node node)
3472 "invert or open code"
3473 (maybe-invert node '> '< x y))
3474 (deftransform <= ((x y) (number number) * :node node)
3475 "invert or open code"
3476 (maybe-invert node '< '> x y)))
3478 ;;; See whether we can statically determine (< X Y) using type
3479 ;;; information. If X's high bound is < Y's low, then X < Y.
3480 ;;; Similarly, if X's low is >= to Y's high, the X >= Y (so return
3481 ;;; NIL). If not, at least make sure any constant arg is second.
3482 (macrolet ((def (name inverse reflexive-p surely-true surely-false)
3483 `(deftransform ,name ((x y))
3484 "optimize using intervals"
3485 (if (and (same-leaf-ref-p x y)
3486 ;; For non-reflexive functions we don't need
3487 ;; to worry about NaNs: (non-ref-op NaN NaN) => false,
3488 ;; but with reflexive ones we don't know...
3490 '((and (not (maybe-float-lvar-p x))
3491 (not (maybe-float-lvar-p y))))))
3493 (let ((ix (or (type-approximate-interval (lvar-type x))
3494 (give-up-ir1-transform)))
3495 (iy (or (type-approximate-interval (lvar-type y))
3496 (give-up-ir1-transform))))
3501 ((and (constant-lvar-p x)
3502 (not (constant-lvar-p y)))
3505 (give-up-ir1-transform))))))))
3506 (def = = t (interval-= ix iy) (interval-/= ix iy))
3507 (def /= /= nil (interval-/= ix iy) (interval-= ix iy))
3508 (def < > nil (interval-< ix iy) (interval->= ix iy))
3509 (def > < nil (interval-< iy ix) (interval->= iy ix))
3510 (def <= >= t (interval->= iy ix) (interval-< iy ix))
3511 (def >= <= t (interval->= ix iy) (interval-< ix iy)))
3513 (defun ir1-transform-char< (x y first second inverse)
3515 ((same-leaf-ref-p x y) nil)
3516 ;; If we had interval representation of character types, as we
3517 ;; might eventually have to to support 2^21 characters, then here
3518 ;; we could do some compile-time computation as in transforms for
3519 ;; < above. -- CSR, 2003-07-01
3520 ((and (constant-lvar-p first)
3521 (not (constant-lvar-p second)))
3523 (t (give-up-ir1-transform))))
3525 (deftransform char< ((x y) (character character) *)
3526 (ir1-transform-char< x y x y 'char>))
3528 (deftransform char> ((x y) (character character) *)
3529 (ir1-transform-char< y x x y 'char<))
3531 ;;;; converting N-arg comparisons
3533 ;;;; We convert calls to N-arg comparison functions such as < into
3534 ;;;; two-arg calls. This transformation is enabled for all such
3535 ;;;; comparisons in this file. If any of these predicates are not
3536 ;;;; open-coded, then the transformation should be removed at some
3537 ;;;; point to avoid pessimization.
3539 ;;; This function is used for source transformation of N-arg
3540 ;;; comparison functions other than inequality. We deal both with
3541 ;;; converting to two-arg calls and inverting the sense of the test,
3542 ;;; if necessary. If the call has two args, then we pass or return a
3543 ;;; negated test as appropriate. If it is a degenerate one-arg call,
3544 ;;; then we transform to code that returns true. Otherwise, we bind
3545 ;;; all the arguments and expand into a bunch of IFs.
3546 (defun multi-compare (predicate args not-p type &optional force-two-arg-p)
3547 (let ((nargs (length args)))
3548 (cond ((< nargs 1) (values nil t))
3549 ((= nargs 1) `(progn (the ,type ,@args) t))
3552 `(if (,predicate ,(first args) ,(second args)) nil t)
3554 `(,predicate ,(first args) ,(second args))
3557 (do* ((i (1- nargs) (1- i))
3559 (current (gensym) (gensym))
3560 (vars (list current) (cons current vars))
3562 `(if (,predicate ,current ,last)
3564 `(if (,predicate ,current ,last)
3567 `((lambda ,vars (declare (type ,type ,@vars)) ,result)
3570 (define-source-transform = (&rest args) (multi-compare '= args nil 'number))
3571 (define-source-transform < (&rest args) (multi-compare '< args nil 'real))
3572 (define-source-transform > (&rest args) (multi-compare '> args nil 'real))
3573 ;;; We cannot do the inversion for >= and <= here, since both
3574 ;;; (< NaN X) and (> NaN X)
3575 ;;; are false, and we don't have type-inforation available yet. The
3576 ;;; deftransforms for two-argument versions of >= and <= takes care of
3577 ;;; the inversion to > and < when possible.
3578 (define-source-transform <= (&rest args) (multi-compare '<= args nil 'real))
3579 (define-source-transform >= (&rest args) (multi-compare '>= args nil 'real))
3581 (define-source-transform char= (&rest args) (multi-compare 'char= args nil
3583 (define-source-transform char< (&rest args) (multi-compare 'char< args nil
3585 (define-source-transform char> (&rest args) (multi-compare 'char> args nil
3587 (define-source-transform char<= (&rest args) (multi-compare 'char> args t
3589 (define-source-transform char>= (&rest args) (multi-compare 'char< args t
3592 (define-source-transform char-equal (&rest args)
3593 (multi-compare 'sb!impl::two-arg-char-equal args nil 'character t))
3594 (define-source-transform char-lessp (&rest args)
3595 (multi-compare 'sb!impl::two-arg-char-lessp args nil 'character t))
3596 (define-source-transform char-greaterp (&rest args)
3597 (multi-compare 'sb!impl::two-arg-char-greaterp args nil 'character t))
3598 (define-source-transform char-not-greaterp (&rest args)
3599 (multi-compare 'sb!impl::two-arg-char-greaterp args t 'character t))
3600 (define-source-transform char-not-lessp (&rest args)
3601 (multi-compare 'sb!impl::two-arg-char-lessp args t 'character t))
3603 ;;; This function does source transformation of N-arg inequality
3604 ;;; functions such as /=. This is similar to MULTI-COMPARE in the <3
3605 ;;; arg cases. If there are more than two args, then we expand into
3606 ;;; the appropriate n^2 comparisons only when speed is important.
3607 (declaim (ftype (function (symbol list t) *) multi-not-equal))
3608 (defun multi-not-equal (predicate args type)
3609 (let ((nargs (length args)))
3610 (cond ((< nargs 1) (values nil t))
3611 ((= nargs 1) `(progn (the ,type ,@args) t))
3613 `(if (,predicate ,(first args) ,(second args)) nil t))
3614 ((not (policy *lexenv*
3615 (and (>= speed space)
3616 (>= speed compilation-speed))))
3619 (let ((vars (make-gensym-list nargs)))
3620 (do ((var vars next)
3621 (next (cdr vars) (cdr next))
3624 `((lambda ,vars (declare (type ,type ,@vars)) ,result)
3626 (let ((v1 (first var)))
3628 (setq result `(if (,predicate ,v1 ,v2) nil ,result))))))))))
3630 (define-source-transform /= (&rest args)
3631 (multi-not-equal '= args 'number))
3632 (define-source-transform char/= (&rest args)
3633 (multi-not-equal 'char= args 'character))
3634 (define-source-transform char-not-equal (&rest args)
3635 (multi-not-equal 'char-equal args 'character))
3637 ;;; Expand MAX and MIN into the obvious comparisons.
3638 (define-source-transform max (arg0 &rest rest)
3639 (once-only ((arg0 arg0))
3641 `(values (the real ,arg0))
3642 `(let ((maxrest (max ,@rest)))
3643 (if (>= ,arg0 maxrest) ,arg0 maxrest)))))
3644 (define-source-transform min (arg0 &rest rest)
3645 (once-only ((arg0 arg0))
3647 `(values (the real ,arg0))
3648 `(let ((minrest (min ,@rest)))
3649 (if (<= ,arg0 minrest) ,arg0 minrest)))))
3651 ;;;; converting N-arg arithmetic functions
3653 ;;;; N-arg arithmetic and logic functions are associated into two-arg
3654 ;;;; versions, and degenerate cases are flushed.
3656 ;;; Left-associate FIRST-ARG and MORE-ARGS using FUNCTION.
3657 (declaim (ftype (function (symbol t list) list) associate-args))
3658 (defun associate-args (function first-arg more-args)
3659 (let ((next (rest more-args))
3660 (arg (first more-args)))
3662 `(,function ,first-arg ,arg)
3663 (associate-args function `(,function ,first-arg ,arg) next))))
3665 ;;; Do source transformations for transitive functions such as +.
3666 ;;; One-arg cases are replaced with the arg and zero arg cases with
3667 ;;; the identity. ONE-ARG-RESULT-TYPE is, if non-NIL, the type to
3668 ;;; ensure (with THE) that the argument in one-argument calls is.
3669 (defun source-transform-transitive (fun args identity
3670 &optional one-arg-result-type)
3671 (declare (symbol fun) (list args))
3674 (1 (if one-arg-result-type
3675 `(values (the ,one-arg-result-type ,(first args)))
3676 `(values ,(first args))))
3679 (associate-args fun (first args) (rest args)))))
3681 (define-source-transform + (&rest args)
3682 (source-transform-transitive '+ args 0 'number))
3683 (define-source-transform * (&rest args)
3684 (source-transform-transitive '* args 1 'number))
3685 (define-source-transform logior (&rest args)
3686 (source-transform-transitive 'logior args 0 'integer))
3687 (define-source-transform logxor (&rest args)
3688 (source-transform-transitive 'logxor args 0 'integer))
3689 (define-source-transform logand (&rest args)
3690 (source-transform-transitive 'logand args -1 'integer))
3691 (define-source-transform logeqv (&rest args)
3692 (source-transform-transitive 'logeqv args -1 'integer))
3694 ;;; Note: we can't use SOURCE-TRANSFORM-TRANSITIVE for GCD and LCM
3695 ;;; because when they are given one argument, they return its absolute
3698 (define-source-transform gcd (&rest args)
3701 (1 `(abs (the integer ,(first args))))
3703 (t (associate-args 'gcd (first args) (rest args)))))
3705 (define-source-transform lcm (&rest args)
3708 (1 `(abs (the integer ,(first args))))
3710 (t (associate-args 'lcm (first args) (rest args)))))
3712 ;;; Do source transformations for intransitive n-arg functions such as
3713 ;;; /. With one arg, we form the inverse. With two args we pass.
3714 ;;; Otherwise we associate into two-arg calls.
3715 (declaim (ftype (function (symbol list t)
3716 (values list &optional (member nil t)))
3717 source-transform-intransitive))
3718 (defun source-transform-intransitive (function args inverse)
3720 ((0 2) (values nil t))
3721 (1 `(,@inverse ,(first args)))
3722 (t (associate-args function (first args) (rest args)))))
3724 (define-source-transform - (&rest args)
3725 (source-transform-intransitive '- args '(%negate)))
3726 (define-source-transform / (&rest args)
3727 (source-transform-intransitive '/ args '(/ 1)))
3729 ;;;; transforming APPLY
3731 ;;; We convert APPLY into MULTIPLE-VALUE-CALL so that the compiler
3732 ;;; only needs to understand one kind of variable-argument call. It is
3733 ;;; more efficient to convert APPLY to MV-CALL than MV-CALL to APPLY.
3734 (define-source-transform apply (fun arg &rest more-args)
3735 (let ((args (cons arg more-args)))
3736 `(multiple-value-call ,fun
3737 ,@(mapcar (lambda (x)
3740 (values-list ,(car (last args))))))
3742 ;;;; transforming FORMAT
3744 ;;;; If the control string is a compile-time constant, then replace it
3745 ;;;; with a use of the FORMATTER macro so that the control string is
3746 ;;;; ``compiled.'' Furthermore, if the destination is either a stream
3747 ;;;; or T and the control string is a function (i.e. FORMATTER), then
3748 ;;;; convert the call to FORMAT to just a FUNCALL of that function.
3750 ;;; for compile-time argument count checking.
3752 ;;; FIXME II: In some cases, type information could be correlated; for
3753 ;;; instance, ~{ ... ~} requires a list argument, so if the lvar-type
3754 ;;; of a corresponding argument is known and does not intersect the
3755 ;;; list type, a warning could be signalled.
3756 (defun check-format-args (string args fun)
3757 (declare (type string string))
3758 (unless (typep string 'simple-string)
3759 (setq string (coerce string 'simple-string)))
3760 (multiple-value-bind (min max)
3761 (handler-case (sb!format:%compiler-walk-format-string string args)
3762 (sb!format:format-error (c)
3763 (compiler-warn "~A" c)))
3765 (let ((nargs (length args)))
3768 (warn 'format-too-few-args-warning
3770 "Too few arguments (~D) to ~S ~S: requires at least ~D."
3771 :format-arguments (list nargs fun string min)))
3773 (warn 'format-too-many-args-warning
3775 "Too many arguments (~D) to ~S ~S: uses at most ~D."
3776 :format-arguments (list nargs fun string max))))))))
3778 (defoptimizer (format optimizer) ((dest control &rest args))
3779 (when (constant-lvar-p control)
3780 (let ((x (lvar-value control)))
3782 (check-format-args x args 'format)))))
3784 ;;; We disable this transform in the cross-compiler to save memory in
3785 ;;; the target image; most of the uses of FORMAT in the compiler are for
3786 ;;; error messages, and those don't need to be particularly fast.
3788 (deftransform format ((dest control &rest args) (t simple-string &rest t) *
3789 :policy (> speed space))
3790 (unless (constant-lvar-p control)
3791 (give-up-ir1-transform "The control string is not a constant."))
3792 (let ((arg-names (make-gensym-list (length args))))
3793 `(lambda (dest control ,@arg-names)
3794 (declare (ignore control))
3795 (format dest (formatter ,(lvar-value control)) ,@arg-names))))
3797 (deftransform format ((stream control &rest args) (stream function &rest t) *
3798 :policy (> speed space))
3799 (let ((arg-names (make-gensym-list (length args))))
3800 `(lambda (stream control ,@arg-names)
3801 (funcall control stream ,@arg-names)
3804 (deftransform format ((tee control &rest args) ((member t) function &rest t) *
3805 :policy (> speed space))
3806 (let ((arg-names (make-gensym-list (length args))))
3807 `(lambda (tee control ,@arg-names)
3808 (declare (ignore tee))
3809 (funcall control *standard-output* ,@arg-names)
3812 (deftransform pathname ((pathspec) (pathname) *)
3815 (deftransform pathname ((pathspec) (string) *)
3816 '(values (parse-namestring pathspec)))
3820 `(defoptimizer (,name optimizer) ((control &rest args))
3821 (when (constant-lvar-p control)
3822 (let ((x (lvar-value control)))
3824 (check-format-args x args ',name)))))))
3827 #+sb-xc-host ; Only we should be using these
3830 (def compiler-error)
3832 (def compiler-style-warn)
3833 (def compiler-notify)
3834 (def maybe-compiler-notify)
3837 (defoptimizer (cerror optimizer) ((report control &rest args))
3838 (when (and (constant-lvar-p control)
3839 (constant-lvar-p report))
3840 (let ((x (lvar-value control))
3841 (y (lvar-value report)))
3842 (when (and (stringp x) (stringp y))
3843 (multiple-value-bind (min1 max1)
3845 (sb!format:%compiler-walk-format-string x args)
3846 (sb!format:format-error (c)
3847 (compiler-warn "~A" c)))
3849 (multiple-value-bind (min2 max2)
3851 (sb!format:%compiler-walk-format-string y args)
3852 (sb!format:format-error (c)
3853 (compiler-warn "~A" c)))
3855 (let ((nargs (length args)))
3857 ((< nargs (min min1 min2))
3858 (warn 'format-too-few-args-warning
3860 "Too few arguments (~D) to ~S ~S ~S: ~
3861 requires at least ~D."
3863 (list nargs 'cerror y x (min min1 min2))))
3864 ((> nargs (max max1 max2))
3865 (warn 'format-too-many-args-warning
3867 "Too many arguments (~D) to ~S ~S ~S: ~
3870 (list nargs 'cerror y x (max max1 max2))))))))))))))
3872 (defoptimizer (coerce derive-type) ((value type))
3874 ((constant-lvar-p type)
3875 ;; This branch is essentially (RESULT-TYPE-SPECIFIER-NTH-ARG 2),
3876 ;; but dealing with the niggle that complex canonicalization gets
3877 ;; in the way: (COERCE 1 'COMPLEX) returns 1, which is not of
3879 (let* ((specifier (lvar-value type))
3880 (result-typeoid (careful-specifier-type specifier)))
3882 ((null result-typeoid) nil)
3883 ((csubtypep result-typeoid (specifier-type 'number))
3884 ;; the difficult case: we have to cope with ANSI 12.1.5.3
3885 ;; Rule of Canonical Representation for Complex Rationals,
3886 ;; which is a truly nasty delivery to field.
3888 ((csubtypep result-typeoid (specifier-type 'real))
3889 ;; cleverness required here: it would be nice to deduce
3890 ;; that something of type (INTEGER 2 3) coerced to type
3891 ;; DOUBLE-FLOAT should return (DOUBLE-FLOAT 2.0d0 3.0d0).
3892 ;; FLOAT gets its own clause because it's implemented as
3893 ;; a UNION-TYPE, so we don't catch it in the NUMERIC-TYPE
3896 ((and (numeric-type-p result-typeoid)
3897 (eq (numeric-type-complexp result-typeoid) :real))
3898 ;; FIXME: is this clause (a) necessary or (b) useful?
3900 ((or (csubtypep result-typeoid
3901 (specifier-type '(complex single-float)))
3902 (csubtypep result-typeoid
3903 (specifier-type '(complex double-float)))
3905 (csubtypep result-typeoid
3906 (specifier-type '(complex long-float))))
3907 ;; float complex types are never canonicalized.
3910 ;; if it's not a REAL, or a COMPLEX FLOAToid, it's
3911 ;; probably just a COMPLEX or equivalent. So, in that
3912 ;; case, we will return a complex or an object of the
3913 ;; provided type if it's rational:
3914 (type-union result-typeoid
3915 (type-intersection (lvar-type value)
3916 (specifier-type 'rational))))))
3917 (t result-typeoid))))
3919 ;; OK, the result-type argument isn't constant. However, there
3920 ;; are common uses where we can still do better than just
3921 ;; *UNIVERSAL-TYPE*: e.g. (COERCE X (ARRAY-ELEMENT-TYPE Y)),
3922 ;; where Y is of a known type. See messages on cmucl-imp
3923 ;; 2001-02-14 and sbcl-devel 2002-12-12. We only worry here
3924 ;; about types that can be returned by (ARRAY-ELEMENT-TYPE Y), on
3925 ;; the basis that it's unlikely that other uses are both
3926 ;; time-critical and get to this branch of the COND (non-constant
3927 ;; second argument to COERCE). -- CSR, 2002-12-16
3928 (let ((value-type (lvar-type value))
3929 (type-type (lvar-type type)))
3931 ((good-cons-type-p (cons-type)
3932 ;; Make sure the cons-type we're looking at is something
3933 ;; we're prepared to handle which is basically something
3934 ;; that array-element-type can return.
3935 (or (and (member-type-p cons-type)
3936 (eql 1 (member-type-size cons-type))
3937 (null (first (member-type-members cons-type))))
3938 (let ((car-type (cons-type-car-type cons-type)))
3939 (and (member-type-p car-type)
3940 (eql 1 (member-type-members car-type))
3941 (let ((elt (first (member-type-members car-type))))
3945 (numberp (first elt)))))
3946 (good-cons-type-p (cons-type-cdr-type cons-type))))))
3947 (unconsify-type (good-cons-type)
3948 ;; Convert the "printed" respresentation of a cons
3949 ;; specifier into a type specifier. That is, the
3950 ;; specifier (CONS (EQL SIGNED-BYTE) (CONS (EQL 16)
3951 ;; NULL)) is converted to (SIGNED-BYTE 16).
3952 (cond ((or (null good-cons-type)
3953 (eq good-cons-type 'null))
3955 ((and (eq (first good-cons-type) 'cons)
3956 (eq (first (second good-cons-type)) 'member))
3957 `(,(second (second good-cons-type))
3958 ,@(unconsify-type (caddr good-cons-type))))))
3959 (coerceable-p (c-type)
3960 ;; Can the value be coerced to the given type? Coerce is
3961 ;; complicated, so we don't handle every possible case
3962 ;; here---just the most common and easiest cases:
3964 ;; * Any REAL can be coerced to a FLOAT type.
3965 ;; * Any NUMBER can be coerced to a (COMPLEX
3966 ;; SINGLE/DOUBLE-FLOAT).
3968 ;; FIXME I: we should also be able to deal with characters
3971 ;; FIXME II: I'm not sure that anything is necessary
3972 ;; here, at least while COMPLEX is not a specialized
3973 ;; array element type in the system. Reasoning: if
3974 ;; something cannot be coerced to the requested type, an
3975 ;; error will be raised (and so any downstream compiled
3976 ;; code on the assumption of the returned type is
3977 ;; unreachable). If something can, then it will be of
3978 ;; the requested type, because (by assumption) COMPLEX
3979 ;; (and other difficult types like (COMPLEX INTEGER)
3980 ;; aren't specialized types.
3981 (let ((coerced-type c-type))
3982 (or (and (subtypep coerced-type 'float)
3983 (csubtypep value-type (specifier-type 'real)))
3984 (and (subtypep coerced-type
3985 '(or (complex single-float)
3986 (complex double-float)))
3987 (csubtypep value-type (specifier-type 'number))))))
3988 (process-types (type)
3989 ;; FIXME: This needs some work because we should be able
3990 ;; to derive the resulting type better than just the
3991 ;; type arg of coerce. That is, if X is (INTEGER 10
3992 ;; 20), then (COERCE X 'DOUBLE-FLOAT) should say
3993 ;; (DOUBLE-FLOAT 10d0 20d0) instead of just
3995 (cond ((member-type-p type)
3998 (mapc-member-type-members
4000 (if (coerceable-p member)
4001 (push member members)
4002 (return-from punt *universal-type*)))
4004 (specifier-type `(or ,@members)))))
4005 ((and (cons-type-p type)
4006 (good-cons-type-p type))
4007 (let ((c-type (unconsify-type (type-specifier type))))
4008 (if (coerceable-p c-type)
4009 (specifier-type c-type)
4012 *universal-type*))))
4013 (cond ((union-type-p type-type)
4014 (apply #'type-union (mapcar #'process-types
4015 (union-type-types type-type))))
4016 ((or (member-type-p type-type)
4017 (cons-type-p type-type))
4018 (process-types type-type))
4020 *universal-type*)))))))
4022 (defoptimizer (compile derive-type) ((nameoid function))
4023 (when (csubtypep (lvar-type nameoid)
4024 (specifier-type 'null))
4025 (values-specifier-type '(values function boolean boolean))))
4027 ;;; FIXME: Maybe also STREAM-ELEMENT-TYPE should be given some loving
4028 ;;; treatment along these lines? (See discussion in COERCE DERIVE-TYPE
4029 ;;; optimizer, above).
4030 (defoptimizer (array-element-type derive-type) ((array))
4031 (let ((array-type (lvar-type array)))
4032 (labels ((consify (list)
4035 `(cons (eql ,(car list)) ,(consify (rest list)))))
4036 (get-element-type (a)
4038 (type-specifier (array-type-specialized-element-type a))))
4039 (cond ((eq element-type '*)
4040 (specifier-type 'type-specifier))
4041 ((symbolp element-type)
4042 (make-member-type :members (list element-type)))
4043 ((consp element-type)
4044 (specifier-type (consify element-type)))
4046 (error "can't understand type ~S~%" element-type))))))
4047 (cond ((array-type-p array-type)
4048 (get-element-type array-type))
4049 ((union-type-p array-type)
4051 (mapcar #'get-element-type (union-type-types array-type))))
4053 *universal-type*)))))
4055 ;;; Like CMU CL, we use HEAPSORT. However, other than that, this code
4056 ;;; isn't really related to the CMU CL code, since instead of trying
4057 ;;; to generalize the CMU CL code to allow START and END values, this
4058 ;;; code has been written from scratch following Chapter 7 of
4059 ;;; _Introduction to Algorithms_ by Corman, Rivest, and Shamir.
4060 (define-source-transform sb!impl::sort-vector (vector start end predicate key)
4061 ;; Like CMU CL, we use HEAPSORT. However, other than that, this code
4062 ;; isn't really related to the CMU CL code, since instead of trying
4063 ;; to generalize the CMU CL code to allow START and END values, this
4064 ;; code has been written from scratch following Chapter 7 of
4065 ;; _Introduction to Algorithms_ by Corman, Rivest, and Shamir.
4066 `(macrolet ((%index (x) `(truly-the index ,x))
4067 (%parent (i) `(ash ,i -1))
4068 (%left (i) `(%index (ash ,i 1)))
4069 (%right (i) `(%index (1+ (ash ,i 1))))
4072 (left (%left i) (%left i)))
4073 ((> left current-heap-size))
4074 (declare (type index i left))
4075 (let* ((i-elt (%elt i))
4076 (i-key (funcall keyfun i-elt))
4077 (left-elt (%elt left))
4078 (left-key (funcall keyfun left-elt)))
4079 (multiple-value-bind (large large-elt large-key)
4080 (if (funcall ,',predicate i-key left-key)
4081 (values left left-elt left-key)
4082 (values i i-elt i-key))
4083 (let ((right (%right i)))
4084 (multiple-value-bind (largest largest-elt)
4085 (if (> right current-heap-size)
4086 (values large large-elt)
4087 (let* ((right-elt (%elt right))
4088 (right-key (funcall keyfun right-elt)))
4089 (if (funcall ,',predicate large-key right-key)
4090 (values right right-elt)
4091 (values large large-elt))))
4092 (cond ((= largest i)
4095 (setf (%elt i) largest-elt
4096 (%elt largest) i-elt
4098 (%sort-vector (keyfun &optional (vtype 'vector))
4099 `(macrolet (;; KLUDGE: In SBCL ca. 0.6.10, I had
4100 ;; trouble getting type inference to
4101 ;; propagate all the way through this
4102 ;; tangled mess of inlining. The TRULY-THE
4103 ;; here works around that. -- WHN
4105 `(aref (truly-the ,',vtype ,',',vector)
4106 (%index (+ (%index ,i) start-1)))))
4107 (let (;; Heaps prefer 1-based addressing.
4108 (start-1 (1- ,',start))
4109 (current-heap-size (- ,',end ,',start))
4111 (declare (type (integer -1 #.(1- most-positive-fixnum))
4113 (declare (type index current-heap-size))
4114 (declare (type function keyfun))
4115 (loop for i of-type index
4116 from (ash current-heap-size -1) downto 1 do
4119 (when (< current-heap-size 2)
4121 (rotatef (%elt 1) (%elt current-heap-size))
4122 (decf current-heap-size)
4124 (if (typep ,vector 'simple-vector)
4125 ;; (VECTOR T) is worth optimizing for, and SIMPLE-VECTOR is
4126 ;; what we get from (VECTOR T) inside WITH-ARRAY-DATA.
4128 ;; Special-casing the KEY=NIL case lets us avoid some
4130 (%sort-vector #'identity simple-vector)
4131 (%sort-vector ,key simple-vector))
4132 ;; It's hard to anticipate many speed-critical applications for
4133 ;; sorting vector types other than (VECTOR T), so we just lump
4134 ;; them all together in one slow dynamically typed mess.
4136 (declare (optimize (speed 2) (space 2) (inhibit-warnings 3)))
4137 (%sort-vector (or ,key #'identity))))))
4139 ;;;; debuggers' little helpers
4141 ;;; for debugging when transforms are behaving mysteriously,
4142 ;;; e.g. when debugging a problem with an ASH transform
4143 ;;; (defun foo (&optional s)
4144 ;;; (sb-c::/report-lvar s "S outside WHEN")
4145 ;;; (when (and (integerp s) (> s 3))
4146 ;;; (sb-c::/report-lvar s "S inside WHEN")
4147 ;;; (let ((bound (ash 1 (1- s))))
4148 ;;; (sb-c::/report-lvar bound "BOUND")
4149 ;;; (let ((x (- bound))
4151 ;;; (sb-c::/report-lvar x "X")
4152 ;;; (sb-c::/report-lvar x "Y"))
4153 ;;; `(integer ,(- bound) ,(1- bound)))))
4154 ;;; (The DEFTRANSFORM doesn't do anything but report at compile time,
4155 ;;; and the function doesn't do anything at all.)
4158 (defknown /report-lvar (t t) null)
4159 (deftransform /report-lvar ((x message) (t t))
4160 (format t "~%/in /REPORT-LVAR~%")
4161 (format t "/(LVAR-TYPE X)=~S~%" (lvar-type x))
4162 (when (constant-lvar-p x)
4163 (format t "/(LVAR-VALUE X)=~S~%" (lvar-value x)))
4164 (format t "/MESSAGE=~S~%" (lvar-value message))
4165 (give-up-ir1-transform "not a real transform"))
4166 (defun /report-lvar (x message)
4167 (declare (ignore x message))))
4170 ;;;; Transforms for internal compiler utilities
4172 ;;; If QUALITY-NAME is constant and a valid name, don't bother
4173 ;;; checking that it's still valid at run-time.
4174 (deftransform policy-quality ((policy quality-name)
4176 (unless (and (constant-lvar-p quality-name)
4177 (policy-quality-name-p (lvar-value quality-name)))
4178 (give-up-ir1-transform))
4179 '(%policy-quality policy quality-name))