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 (symbol-name (car form))))
69 (do ((i (- (length name) 2) (1- i))
71 `(,(ecase (char name i)
77 ;;; Make source transforms to turn CxR forms into combinations of CAR
78 ;;; and CDR. ANSI specifies that everything up to 4 A/D operations is
80 (/show0 "about to set CxR source transforms")
81 (loop for i of-type index from 2 upto 4 do
82 ;; Iterate over BUF = all names CxR where x = an I-element
83 ;; string of #\A or #\D characters.
84 (let ((buf (make-string (+ 2 i))))
85 (setf (aref buf 0) #\C
86 (aref buf (1+ i)) #\R)
87 (dotimes (j (ash 2 i))
88 (declare (type index j))
90 (declare (type index k))
91 (setf (aref buf (1+ k))
92 (if (logbitp k j) #\A #\D)))
93 (setf (info :function :source-transform (intern buf))
94 #'source-transform-cxr))))
95 (/show0 "done setting CxR source transforms")
97 ;;; Turn FIRST..FOURTH and REST into the obvious synonym, assuming
98 ;;; whatever is right for them is right for us. FIFTH..TENTH turn into
99 ;;; Nth, which can be expanded into a CAR/CDR later on if policy
101 (define-source-transform first (x) `(car ,x))
102 (define-source-transform rest (x) `(cdr ,x))
103 (define-source-transform second (x) `(cadr ,x))
104 (define-source-transform third (x) `(caddr ,x))
105 (define-source-transform fourth (x) `(cadddr ,x))
106 (define-source-transform fifth (x) `(nth 4 ,x))
107 (define-source-transform sixth (x) `(nth 5 ,x))
108 (define-source-transform seventh (x) `(nth 6 ,x))
109 (define-source-transform eighth (x) `(nth 7 ,x))
110 (define-source-transform ninth (x) `(nth 8 ,x))
111 (define-source-transform tenth (x) `(nth 9 ,x))
113 ;;; Translate RPLACx to LET and SETF.
114 (define-source-transform rplaca (x y)
119 (define-source-transform rplacd (x y)
125 (define-source-transform nth (n l) `(car (nthcdr ,n ,l)))
127 (defvar *default-nthcdr-open-code-limit* 6)
128 (defvar *extreme-nthcdr-open-code-limit* 20)
130 (deftransform nthcdr ((n l) (unsigned-byte t) * :node node)
131 "convert NTHCDR to CAxxR"
132 (unless (constant-lvar-p n)
133 (give-up-ir1-transform))
134 (let ((n (lvar-value n)))
136 (if (policy node (and (= speed 3) (= space 0)))
137 *extreme-nthcdr-open-code-limit*
138 *default-nthcdr-open-code-limit*))
139 (give-up-ir1-transform))
144 `(cdr ,(frob (1- n))))))
147 ;;;; arithmetic and numerology
149 (define-source-transform plusp (x) `(> ,x 0))
150 (define-source-transform minusp (x) `(< ,x 0))
151 (define-source-transform zerop (x) `(= ,x 0))
153 (define-source-transform 1+ (x) `(+ ,x 1))
154 (define-source-transform 1- (x) `(- ,x 1))
156 (define-source-transform oddp (x) `(not (zerop (logand ,x 1))))
157 (define-source-transform evenp (x) `(zerop (logand ,x 1)))
159 ;;; Note that all the integer division functions are available for
160 ;;; inline expansion.
162 (macrolet ((deffrob (fun)
163 `(define-source-transform ,fun (x &optional (y nil y-p))
170 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
172 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
175 (define-source-transform logtest (x y) `(not (zerop (logand ,x ,y))))
177 (deftransform logbitp
178 ((index integer) (unsigned-byte (or (signed-byte #.sb!vm:n-word-bits)
179 (unsigned-byte #.sb!vm:n-word-bits))))
180 `(if (>= index #.sb!vm:n-word-bits)
182 (not (zerop (logand integer (ash 1 index))))))
184 (define-source-transform byte (size position)
185 `(cons ,size ,position))
186 (define-source-transform byte-size (spec) `(car ,spec))
187 (define-source-transform byte-position (spec) `(cdr ,spec))
188 (define-source-transform ldb-test (bytespec integer)
189 `(not (zerop (mask-field ,bytespec ,integer))))
191 ;;; With the ratio and complex accessors, we pick off the "identity"
192 ;;; case, and use a primitive to handle the cell access case.
193 (define-source-transform numerator (num)
194 (once-only ((n-num `(the rational ,num)))
198 (define-source-transform denominator (num)
199 (once-only ((n-num `(the rational ,num)))
201 (%denominator ,n-num)
204 ;;;; interval arithmetic for computing bounds
206 ;;;; This is a set of routines for operating on intervals. It
207 ;;;; implements a simple interval arithmetic package. Although SBCL
208 ;;;; has an interval type in NUMERIC-TYPE, we choose to use our own
209 ;;;; for two reasons:
211 ;;;; 1. This package is simpler than NUMERIC-TYPE.
213 ;;;; 2. It makes debugging much easier because you can just strip
214 ;;;; out these routines and test them independently of SBCL. (This is a
217 ;;;; One disadvantage is a probable increase in consing because we
218 ;;;; have to create these new interval structures even though
219 ;;;; numeric-type has everything we want to know. Reason 2 wins for
222 ;;; Support operations that mimic real arithmetic comparison
223 ;;; operators, but imposing a total order on the floating points such
224 ;;; that negative zeros are strictly less than positive zeros.
225 (macrolet ((def (name op)
228 (if (and (floatp x) (floatp y) (zerop x) (zerop y))
229 (,op (float-sign x) (float-sign y))
231 (def signed-zero->= >=)
232 (def signed-zero-> >)
233 (def signed-zero-= =)
234 (def signed-zero-< <)
235 (def signed-zero-<= <=))
237 ;;; The basic interval type. It can handle open and closed intervals.
238 ;;; A bound is open if it is a list containing a number, just like
239 ;;; Lisp says. NIL means unbounded.
240 (defstruct (interval (:constructor %make-interval)
244 (defun make-interval (&key low high)
245 (labels ((normalize-bound (val)
246 (cond ((and (floatp val)
247 (float-infinity-p val))
248 ;; Handle infinities.
252 ;; Handle any closed bounds.
255 ;; We have an open bound. Normalize the numeric
256 ;; bound. If the normalized bound is still a number
257 ;; (not nil), keep the bound open. Otherwise, the
258 ;; bound is really unbounded, so drop the openness.
259 (let ((new-val (normalize-bound (first val))))
261 ;; The bound exists, so keep it open still.
264 (error "unknown bound type in MAKE-INTERVAL")))))
265 (%make-interval :low (normalize-bound low)
266 :high (normalize-bound high))))
268 ;;; Given a number X, create a form suitable as a bound for an
269 ;;; interval. Make the bound open if OPEN-P is T. NIL remains NIL.
270 #!-sb-fluid (declaim (inline set-bound))
271 (defun set-bound (x open-p)
272 (if (and x open-p) (list x) x))
274 ;;; Apply the function F to a bound X. If X is an open bound, then
275 ;;; the result will be open. IF X is NIL, the result is NIL.
276 (defun bound-func (f x)
277 (declare (type function f))
279 (with-float-traps-masked (:underflow :overflow :inexact :divide-by-zero)
280 ;; With these traps masked, we might get things like infinity
281 ;; or negative infinity returned. Check for this and return
282 ;; NIL to indicate unbounded.
283 (let ((y (funcall f (type-bound-number x))))
285 (float-infinity-p y))
287 (set-bound (funcall f (type-bound-number x)) (consp x)))))))
289 ;;; Apply a binary operator OP to two bounds X and Y. The result is
290 ;;; NIL if either is NIL. Otherwise bound is computed and the result
291 ;;; is open if either X or Y is open.
293 ;;; FIXME: only used in this file, not needed in target runtime
294 (defmacro bound-binop (op x y)
296 (with-float-traps-masked (:underflow :overflow :inexact :divide-by-zero)
297 (set-bound (,op (type-bound-number ,x)
298 (type-bound-number ,y))
299 (or (consp ,x) (consp ,y))))))
301 ;;; Convert a numeric-type object to an interval object.
302 (defun numeric-type->interval (x)
303 (declare (type numeric-type x))
304 (make-interval :low (numeric-type-low x)
305 :high (numeric-type-high x)))
307 (defun copy-interval-limit (limit)
312 (defun copy-interval (x)
313 (declare (type interval x))
314 (make-interval :low (copy-interval-limit (interval-low x))
315 :high (copy-interval-limit (interval-high x))))
317 ;;; Given a point P contained in the interval X, split X into two
318 ;;; interval at the point P. If CLOSE-LOWER is T, then the left
319 ;;; interval contains P. If CLOSE-UPPER is T, the right interval
320 ;;; contains P. You can specify both to be T or NIL.
321 (defun interval-split (p x &optional close-lower close-upper)
322 (declare (type number p)
324 (list (make-interval :low (copy-interval-limit (interval-low x))
325 :high (if close-lower p (list p)))
326 (make-interval :low (if close-upper (list p) p)
327 :high (copy-interval-limit (interval-high x)))))
329 ;;; Return the closure of the interval. That is, convert open bounds
330 ;;; to closed bounds.
331 (defun interval-closure (x)
332 (declare (type interval x))
333 (make-interval :low (type-bound-number (interval-low x))
334 :high (type-bound-number (interval-high x))))
336 ;;; For an interval X, if X >= POINT, return '+. If X <= POINT, return
337 ;;; '-. Otherwise return NIL.
338 (defun interval-range-info (x &optional (point 0))
339 (declare (type interval x))
340 (let ((lo (interval-low x))
341 (hi (interval-high x)))
342 (cond ((and lo (signed-zero->= (type-bound-number lo) point))
344 ((and hi (signed-zero->= point (type-bound-number hi)))
349 ;;; Test to see whether the interval X is bounded. HOW determines the
350 ;;; test, and should be either ABOVE, BELOW, or BOTH.
351 (defun interval-bounded-p (x how)
352 (declare (type interval x))
359 (and (interval-low x) (interval-high x)))))
361 ;;; See whether the interval X contains the number P, taking into
362 ;;; account that the interval might not be closed.
363 (defun interval-contains-p (p x)
364 (declare (type number p)
366 ;; Does the interval X contain the number P? This would be a lot
367 ;; easier if all intervals were closed!
368 (let ((lo (interval-low x))
369 (hi (interval-high x)))
371 ;; The interval is bounded
372 (if (and (signed-zero-<= (type-bound-number lo) p)
373 (signed-zero-<= p (type-bound-number hi)))
374 ;; P is definitely in the closure of the interval.
375 ;; We just need to check the end points now.
376 (cond ((signed-zero-= p (type-bound-number lo))
378 ((signed-zero-= p (type-bound-number hi))
383 ;; Interval with upper bound
384 (if (signed-zero-< p (type-bound-number hi))
386 (and (numberp hi) (signed-zero-= p hi))))
388 ;; Interval with lower bound
389 (if (signed-zero-> p (type-bound-number lo))
391 (and (numberp lo) (signed-zero-= p lo))))
393 ;; Interval with no bounds
396 ;;; Determine whether two intervals X and Y intersect. Return T if so.
397 ;;; If CLOSED-INTERVALS-P is T, the treat the intervals as if they
398 ;;; were closed. Otherwise the intervals are treated as they are.
400 ;;; Thus if X = [0, 1) and Y = (1, 2), then they do not intersect
401 ;;; because no element in X is in Y. However, if CLOSED-INTERVALS-P
402 ;;; is T, then they do intersect because we use the closure of X = [0,
403 ;;; 1] and Y = [1, 2] to determine intersection.
404 (defun interval-intersect-p (x y &optional closed-intervals-p)
405 (declare (type interval x y))
406 (multiple-value-bind (intersect diff)
407 (interval-intersection/difference (if closed-intervals-p
410 (if closed-intervals-p
413 (declare (ignore diff))
416 ;;; Are the two intervals adjacent? That is, is there a number
417 ;;; between the two intervals that is not an element of either
418 ;;; interval? If so, they are not adjacent. For example [0, 1) and
419 ;;; [1, 2] are adjacent but [0, 1) and (1, 2] are not because 1 lies
420 ;;; between both intervals.
421 (defun interval-adjacent-p (x y)
422 (declare (type interval x y))
423 (flet ((adjacent (lo hi)
424 ;; Check to see whether lo and hi are adjacent. If either is
425 ;; nil, they can't be adjacent.
426 (when (and lo hi (= (type-bound-number lo) (type-bound-number hi)))
427 ;; The bounds are equal. They are adjacent if one of
428 ;; them is closed (a number). If both are open (consp),
429 ;; then there is a number that lies between them.
430 (or (numberp lo) (numberp hi)))))
431 (or (adjacent (interval-low y) (interval-high x))
432 (adjacent (interval-low x) (interval-high y)))))
434 ;;; Compute the intersection and difference between two intervals.
435 ;;; Two values are returned: the intersection and the difference.
437 ;;; Let the two intervals be X and Y, and let I and D be the two
438 ;;; values returned by this function. Then I = X intersect Y. If I
439 ;;; is NIL (the empty set), then D is X union Y, represented as the
440 ;;; list of X and Y. If I is not the empty set, then D is (X union Y)
441 ;;; - I, which is a list of two intervals.
443 ;;; For example, let X = [1,5] and Y = [-1,3). Then I = [1,3) and D =
444 ;;; [-1,1) union [3,5], which is returned as a list of two intervals.
445 (defun interval-intersection/difference (x y)
446 (declare (type interval x y))
447 (let ((x-lo (interval-low x))
448 (x-hi (interval-high x))
449 (y-lo (interval-low y))
450 (y-hi (interval-high y)))
453 ;; If p is an open bound, make it closed. If p is a closed
454 ;; bound, make it open.
459 ;; Test whether P is in the interval.
460 (when (interval-contains-p (type-bound-number p)
461 (interval-closure int))
462 (let ((lo (interval-low int))
463 (hi (interval-high int)))
464 ;; Check for endpoints.
465 (cond ((and lo (= (type-bound-number p) (type-bound-number lo)))
466 (not (and (consp p) (numberp lo))))
467 ((and hi (= (type-bound-number p) (type-bound-number hi)))
468 (not (and (numberp p) (consp hi))))
470 (test-lower-bound (p int)
471 ;; P is a lower bound of an interval.
474 (not (interval-bounded-p int 'below))))
475 (test-upper-bound (p int)
476 ;; P is an upper bound of an interval.
479 (not (interval-bounded-p int 'above)))))
480 (let ((x-lo-in-y (test-lower-bound x-lo y))
481 (x-hi-in-y (test-upper-bound x-hi y))
482 (y-lo-in-x (test-lower-bound y-lo x))
483 (y-hi-in-x (test-upper-bound y-hi x)))
484 (cond ((or x-lo-in-y x-hi-in-y y-lo-in-x y-hi-in-x)
485 ;; Intervals intersect. Let's compute the intersection
486 ;; and the difference.
487 (multiple-value-bind (lo left-lo left-hi)
488 (cond (x-lo-in-y (values x-lo y-lo (opposite-bound x-lo)))
489 (y-lo-in-x (values y-lo x-lo (opposite-bound y-lo))))
490 (multiple-value-bind (hi right-lo right-hi)
492 (values x-hi (opposite-bound x-hi) y-hi))
494 (values y-hi (opposite-bound y-hi) x-hi)))
495 (values (make-interval :low lo :high hi)
496 (list (make-interval :low left-lo
498 (make-interval :low right-lo
501 (values nil (list x y))))))))
503 ;;; If intervals X and Y intersect, return a new interval that is the
504 ;;; union of the two. If they do not intersect, return NIL.
505 (defun interval-merge-pair (x y)
506 (declare (type interval x y))
507 ;; If x and y intersect or are adjacent, create the union.
508 ;; Otherwise return nil
509 (when (or (interval-intersect-p x y)
510 (interval-adjacent-p x y))
511 (flet ((select-bound (x1 x2 min-op max-op)
512 (let ((x1-val (type-bound-number x1))
513 (x2-val (type-bound-number x2)))
515 ;; Both bounds are finite. Select the right one.
516 (cond ((funcall min-op x1-val x2-val)
517 ;; x1 is definitely better.
519 ((funcall max-op x1-val x2-val)
520 ;; x2 is definitely better.
523 ;; Bounds are equal. Select either
524 ;; value and make it open only if
526 (set-bound x1-val (and (consp x1) (consp x2))))))
528 ;; At least one bound is not finite. The
529 ;; non-finite bound always wins.
531 (let* ((x-lo (copy-interval-limit (interval-low x)))
532 (x-hi (copy-interval-limit (interval-high x)))
533 (y-lo (copy-interval-limit (interval-low y)))
534 (y-hi (copy-interval-limit (interval-high y))))
535 (make-interval :low (select-bound x-lo y-lo #'< #'>)
536 :high (select-bound x-hi y-hi #'> #'<))))))
538 ;;; basic arithmetic operations on intervals. We probably should do
539 ;;; true interval arithmetic here, but it's complicated because we
540 ;;; have float and integer types and bounds can be open or closed.
542 ;;; the negative of an interval
543 (defun interval-neg (x)
544 (declare (type interval x))
545 (make-interval :low (bound-func #'- (interval-high x))
546 :high (bound-func #'- (interval-low x))))
548 ;;; Add two intervals.
549 (defun interval-add (x y)
550 (declare (type interval x y))
551 (make-interval :low (bound-binop + (interval-low x) (interval-low y))
552 :high (bound-binop + (interval-high x) (interval-high y))))
554 ;;; Subtract two intervals.
555 (defun interval-sub (x y)
556 (declare (type interval x y))
557 (make-interval :low (bound-binop - (interval-low x) (interval-high y))
558 :high (bound-binop - (interval-high x) (interval-low y))))
560 ;;; Multiply two intervals.
561 (defun interval-mul (x y)
562 (declare (type interval x y))
563 (flet ((bound-mul (x y)
564 (cond ((or (null x) (null y))
565 ;; Multiply by infinity is infinity
567 ((or (and (numberp x) (zerop x))
568 (and (numberp y) (zerop y)))
569 ;; Multiply by closed zero is special. The result
570 ;; is always a closed bound. But don't replace this
571 ;; with zero; we want the multiplication to produce
572 ;; the correct signed zero, if needed.
573 (* (type-bound-number x) (type-bound-number y)))
574 ((or (and (floatp x) (float-infinity-p x))
575 (and (floatp y) (float-infinity-p y)))
576 ;; Infinity times anything is infinity
579 ;; General multiply. The result is open if either is open.
580 (bound-binop * x y)))))
581 (let ((x-range (interval-range-info x))
582 (y-range (interval-range-info y)))
583 (cond ((null x-range)
584 ;; Split x into two and multiply each separately
585 (destructuring-bind (x- x+) (interval-split 0 x t t)
586 (interval-merge-pair (interval-mul x- y)
587 (interval-mul x+ y))))
589 ;; Split y into two and multiply each separately
590 (destructuring-bind (y- y+) (interval-split 0 y t t)
591 (interval-merge-pair (interval-mul x y-)
592 (interval-mul x y+))))
594 (interval-neg (interval-mul (interval-neg x) y)))
596 (interval-neg (interval-mul x (interval-neg y))))
597 ((and (eq x-range '+) (eq y-range '+))
598 ;; If we are here, X and Y are both positive.
600 :low (bound-mul (interval-low x) (interval-low y))
601 :high (bound-mul (interval-high x) (interval-high y))))
603 (bug "excluded case in INTERVAL-MUL"))))))
605 ;;; Divide two intervals.
606 (defun interval-div (top bot)
607 (declare (type interval top bot))
608 (flet ((bound-div (x y y-low-p)
611 ;; Divide by infinity means result is 0. However,
612 ;; we need to watch out for the sign of the result,
613 ;; to correctly handle signed zeros. We also need
614 ;; to watch out for positive or negative infinity.
615 (if (floatp (type-bound-number x))
617 (- (float-sign (type-bound-number x) 0.0))
618 (float-sign (type-bound-number x) 0.0))
620 ((zerop (type-bound-number y))
621 ;; Divide by zero means result is infinity
623 ((and (numberp x) (zerop x))
624 ;; Zero divided by anything is zero.
627 (bound-binop / x y)))))
628 (let ((top-range (interval-range-info top))
629 (bot-range (interval-range-info bot)))
630 (cond ((null bot-range)
631 ;; The denominator contains zero, so anything goes!
632 (make-interval :low nil :high nil))
634 ;; Denominator is negative so flip the sign, compute the
635 ;; result, and flip it back.
636 (interval-neg (interval-div top (interval-neg bot))))
638 ;; Split top into two positive and negative parts, and
639 ;; divide each separately
640 (destructuring-bind (top- top+) (interval-split 0 top t t)
641 (interval-merge-pair (interval-div top- bot)
642 (interval-div top+ bot))))
644 ;; Top is negative so flip the sign, divide, and flip the
645 ;; sign of the result.
646 (interval-neg (interval-div (interval-neg top) bot)))
647 ((and (eq top-range '+) (eq bot-range '+))
650 :low (bound-div (interval-low top) (interval-high bot) t)
651 :high (bound-div (interval-high top) (interval-low bot) nil)))
653 (bug "excluded case in INTERVAL-DIV"))))))
655 ;;; Apply the function F to the interval X. If X = [a, b], then the
656 ;;; result is [f(a), f(b)]. It is up to the user to make sure the
657 ;;; result makes sense. It will if F is monotonic increasing (or
659 (defun interval-func (f x)
660 (declare (type function f)
662 (let ((lo (bound-func f (interval-low x)))
663 (hi (bound-func f (interval-high x))))
664 (make-interval :low lo :high hi)))
666 ;;; Return T if X < Y. That is every number in the interval X is
667 ;;; always less than any number in the interval Y.
668 (defun interval-< (x y)
669 (declare (type interval x y))
670 ;; X < Y only if X is bounded above, Y is bounded below, and they
672 (when (and (interval-bounded-p x 'above)
673 (interval-bounded-p y 'below))
674 ;; Intervals are bounded in the appropriate way. Make sure they
676 (let ((left (interval-high x))
677 (right (interval-low y)))
678 (cond ((> (type-bound-number left)
679 (type-bound-number right))
680 ;; The intervals definitely overlap, so result is NIL.
682 ((< (type-bound-number left)
683 (type-bound-number right))
684 ;; The intervals definitely don't touch, so result is T.
687 ;; Limits are equal. Check for open or closed bounds.
688 ;; Don't overlap if one or the other are open.
689 (or (consp left) (consp right)))))))
691 ;;; Return T if X >= Y. That is, every number in the interval X is
692 ;;; always greater than any number in the interval Y.
693 (defun interval->= (x y)
694 (declare (type interval x y))
695 ;; X >= Y if lower bound of X >= upper bound of Y
696 (when (and (interval-bounded-p x 'below)
697 (interval-bounded-p y 'above))
698 (>= (type-bound-number (interval-low x))
699 (type-bound-number (interval-high y)))))
701 ;;; Return an interval that is the absolute value of X. Thus, if
702 ;;; X = [-1 10], the result is [0, 10].
703 (defun interval-abs (x)
704 (declare (type interval x))
705 (case (interval-range-info x)
711 (destructuring-bind (x- x+) (interval-split 0 x t t)
712 (interval-merge-pair (interval-neg x-) x+)))))
714 ;;; Compute the square of an interval.
715 (defun interval-sqr (x)
716 (declare (type interval x))
717 (interval-func (lambda (x) (* x x))
720 ;;;; numeric DERIVE-TYPE methods
722 ;;; a utility for defining derive-type methods of integer operations. If
723 ;;; the types of both X and Y are integer types, then we compute a new
724 ;;; integer type with bounds determined Fun when applied to X and Y.
725 ;;; Otherwise, we use Numeric-Contagion.
726 (defun derive-integer-type-aux (x y fun)
727 (declare (type function fun))
728 (if (and (numeric-type-p x) (numeric-type-p y)
729 (eq (numeric-type-class x) 'integer)
730 (eq (numeric-type-class y) 'integer)
731 (eq (numeric-type-complexp x) :real)
732 (eq (numeric-type-complexp y) :real))
733 (multiple-value-bind (low high) (funcall fun x y)
734 (make-numeric-type :class 'integer
738 (numeric-contagion x y)))
740 (defun derive-integer-type (x y fun)
741 (declare (type lvar x y) (type function fun))
742 (let ((x (lvar-type x))
744 (derive-integer-type-aux x y fun)))
746 ;;; simple utility to flatten a list
747 (defun flatten-list (x)
748 (labels ((flatten-helper (x r);; 'r' is the stuff to the 'right'.
752 (t (flatten-helper (car x)
753 (flatten-helper (cdr x) r))))))
754 (flatten-helper x nil)))
756 ;;; Take some type of lvar and massage it so that we get a list of the
757 ;;; constituent types. If ARG is *EMPTY-TYPE*, return NIL to indicate
759 (defun prepare-arg-for-derive-type (arg)
760 (flet ((listify (arg)
765 (union-type-types arg))
768 (unless (eq arg *empty-type*)
769 ;; Make sure all args are some type of numeric-type. For member
770 ;; types, convert the list of members into a union of equivalent
771 ;; single-element member-type's.
772 (let ((new-args nil))
773 (dolist (arg (listify arg))
774 (if (member-type-p arg)
775 ;; Run down the list of members and convert to a list of
777 (dolist (member (member-type-members arg))
778 (push (if (numberp member)
779 (make-member-type :members (list member))
782 (push arg new-args)))
783 (unless (member *empty-type* new-args)
786 ;;; Convert from the standard type convention for which -0.0 and 0.0
787 ;;; are equal to an intermediate convention for which they are
788 ;;; considered different which is more natural for some of the
790 (defun convert-numeric-type (type)
791 (declare (type numeric-type type))
792 ;;; Only convert real float interval delimiters types.
793 (if (eq (numeric-type-complexp type) :real)
794 (let* ((lo (numeric-type-low type))
795 (lo-val (type-bound-number lo))
796 (lo-float-zero-p (and lo (floatp lo-val) (= lo-val 0.0)))
797 (hi (numeric-type-high type))
798 (hi-val (type-bound-number hi))
799 (hi-float-zero-p (and hi (floatp hi-val) (= hi-val 0.0))))
800 (if (or lo-float-zero-p hi-float-zero-p)
802 :class (numeric-type-class type)
803 :format (numeric-type-format type)
805 :low (if lo-float-zero-p
807 (list (float 0.0 lo-val))
808 (float (load-time-value (make-unportable-float :single-float-negative-zero)) lo-val))
810 :high (if hi-float-zero-p
812 (list (float (load-time-value (make-unportable-float :single-float-negative-zero)) hi-val))
819 ;;; Convert back from the intermediate convention for which -0.0 and
820 ;;; 0.0 are considered different to the standard type convention for
822 (defun convert-back-numeric-type (type)
823 (declare (type numeric-type type))
824 ;;; Only convert real float interval delimiters types.
825 (if (eq (numeric-type-complexp type) :real)
826 (let* ((lo (numeric-type-low type))
827 (lo-val (type-bound-number lo))
829 (and lo (floatp lo-val) (= lo-val 0.0)
830 (float-sign lo-val)))
831 (hi (numeric-type-high type))
832 (hi-val (type-bound-number hi))
834 (and hi (floatp hi-val) (= hi-val 0.0)
835 (float-sign hi-val))))
837 ;; (float +0.0 +0.0) => (member 0.0)
838 ;; (float -0.0 -0.0) => (member -0.0)
839 ((and lo-float-zero-p hi-float-zero-p)
840 ;; shouldn't have exclusive bounds here..
841 (aver (and (not (consp lo)) (not (consp hi))))
842 (if (= lo-float-zero-p hi-float-zero-p)
843 ;; (float +0.0 +0.0) => (member 0.0)
844 ;; (float -0.0 -0.0) => (member -0.0)
845 (specifier-type `(member ,lo-val))
846 ;; (float -0.0 +0.0) => (float 0.0 0.0)
847 ;; (float +0.0 -0.0) => (float 0.0 0.0)
848 (make-numeric-type :class (numeric-type-class type)
849 :format (numeric-type-format type)
855 ;; (float -0.0 x) => (float 0.0 x)
856 ((and (not (consp lo)) (minusp lo-float-zero-p))
857 (make-numeric-type :class (numeric-type-class type)
858 :format (numeric-type-format type)
860 :low (float 0.0 lo-val)
862 ;; (float (+0.0) x) => (float (0.0) x)
863 ((and (consp lo) (plusp lo-float-zero-p))
864 (make-numeric-type :class (numeric-type-class type)
865 :format (numeric-type-format type)
867 :low (list (float 0.0 lo-val))
870 ;; (float +0.0 x) => (or (member 0.0) (float (0.0) x))
871 ;; (float (-0.0) x) => (or (member 0.0) (float (0.0) x))
872 (list (make-member-type :members (list (float 0.0 lo-val)))
873 (make-numeric-type :class (numeric-type-class type)
874 :format (numeric-type-format type)
876 :low (list (float 0.0 lo-val))
880 ;; (float x +0.0) => (float x 0.0)
881 ((and (not (consp hi)) (plusp hi-float-zero-p))
882 (make-numeric-type :class (numeric-type-class type)
883 :format (numeric-type-format type)
886 :high (float 0.0 hi-val)))
887 ;; (float x (-0.0)) => (float x (0.0))
888 ((and (consp hi) (minusp hi-float-zero-p))
889 (make-numeric-type :class (numeric-type-class type)
890 :format (numeric-type-format type)
893 :high (list (float 0.0 hi-val))))
895 ;; (float x (+0.0)) => (or (member -0.0) (float x (0.0)))
896 ;; (float x -0.0) => (or (member -0.0) (float x (0.0)))
897 (list (make-member-type :members (list (float -0.0 hi-val)))
898 (make-numeric-type :class (numeric-type-class type)
899 :format (numeric-type-format type)
902 :high (list (float 0.0 hi-val)))))))
908 ;;; Convert back a possible list of numeric types.
909 (defun convert-back-numeric-type-list (type-list)
913 (dolist (type type-list)
914 (if (numeric-type-p type)
915 (let ((result (convert-back-numeric-type type)))
917 (setf results (append results result))
918 (push result results)))
919 (push type results)))
922 (convert-back-numeric-type type-list))
924 (convert-back-numeric-type-list (union-type-types type-list)))
928 ;;; FIXME: MAKE-CANONICAL-UNION-TYPE and CONVERT-MEMBER-TYPE probably
929 ;;; belong in the kernel's type logic, invoked always, instead of in
930 ;;; the compiler, invoked only during some type optimizations. (In
931 ;;; fact, as of 0.pre8.100 or so they probably are, under
932 ;;; MAKE-MEMBER-TYPE, so probably this code can be deleted)
934 ;;; Take a list of types and return a canonical type specifier,
935 ;;; combining any MEMBER types together. If both positive and negative
936 ;;; MEMBER types are present they are converted to a float type.
937 ;;; XXX This would be far simpler if the type-union methods could handle
938 ;;; member/number unions.
939 (defun make-canonical-union-type (type-list)
942 (dolist (type type-list)
943 (if (member-type-p type)
944 (setf members (union members (member-type-members type)))
945 (push type misc-types)))
947 (when (null (set-difference `(,(load-time-value (make-unportable-float :long-float-negative-zero)) 0.0l0) members))
948 (push (specifier-type '(long-float 0.0l0 0.0l0)) misc-types)
949 (setf members (set-difference members `(,(load-time-value (make-unportable-float :long-float-negative-zero)) 0.0l0))))
950 (when (null (set-difference `(,(load-time-value (make-unportable-float :double-float-negative-zero)) 0.0d0) members))
951 (push (specifier-type '(double-float 0.0d0 0.0d0)) misc-types)
952 (setf members (set-difference members `(,(load-time-value (make-unportable-float :double-float-negative-zero)) 0.0d0))))
953 (when (null (set-difference `(,(load-time-value (make-unportable-float :single-float-negative-zero)) 0.0f0) members))
954 (push (specifier-type '(single-float 0.0f0 0.0f0)) misc-types)
955 (setf members (set-difference members `(,(load-time-value (make-unportable-float :single-float-negative-zero)) 0.0f0))))
957 (apply #'type-union (make-member-type :members members) misc-types)
958 (apply #'type-union misc-types))))
960 ;;; Convert a member type with a single member to a numeric type.
961 (defun convert-member-type (arg)
962 (let* ((members (member-type-members arg))
963 (member (first members))
964 (member-type (type-of member)))
965 (aver (not (rest members)))
966 (specifier-type (cond ((typep member 'integer)
967 `(integer ,member ,member))
968 ((memq member-type '(short-float single-float
969 double-float long-float))
970 `(,member-type ,member ,member))
974 ;;; This is used in defoptimizers for computing the resulting type of
977 ;;; Given the lvar ARG, derive the resulting type using the
978 ;;; DERIVE-FUN. DERIVE-FUN takes exactly one argument which is some
979 ;;; "atomic" lvar type like numeric-type or member-type (containing
980 ;;; just one element). It should return the resulting type, which can
981 ;;; be a list of types.
983 ;;; For the case of member types, if a MEMBER-FUN is given it is
984 ;;; called to compute the result otherwise the member type is first
985 ;;; converted to a numeric type and the DERIVE-FUN is called.
986 (defun one-arg-derive-type (arg derive-fun member-fun
987 &optional (convert-type t))
988 (declare (type function derive-fun)
989 (type (or null function) member-fun))
990 (let ((arg-list (prepare-arg-for-derive-type (lvar-type arg))))
996 (with-float-traps-masked
997 (:underflow :overflow :divide-by-zero)
1001 (first (member-type-members x))))))
1002 ;; Otherwise convert to a numeric type.
1003 (let ((result-type-list
1004 (funcall derive-fun (convert-member-type x))))
1006 (convert-back-numeric-type-list result-type-list)
1007 result-type-list))))
1010 (convert-back-numeric-type-list
1011 (funcall derive-fun (convert-numeric-type x)))
1012 (funcall derive-fun x)))
1014 *universal-type*))))
1015 ;; Run down the list of args and derive the type of each one,
1016 ;; saving all of the results in a list.
1017 (let ((results nil))
1018 (dolist (arg arg-list)
1019 (let ((result (deriver arg)))
1021 (setf results (append results result))
1022 (push result results))))
1024 (make-canonical-union-type results)
1025 (first results)))))))
1027 ;;; Same as ONE-ARG-DERIVE-TYPE, except we assume the function takes
1028 ;;; two arguments. DERIVE-FUN takes 3 args in this case: the two
1029 ;;; original args and a third which is T to indicate if the two args
1030 ;;; really represent the same lvar. This is useful for deriving the
1031 ;;; type of things like (* x x), which should always be positive. If
1032 ;;; we didn't do this, we wouldn't be able to tell.
1033 (defun two-arg-derive-type (arg1 arg2 derive-fun fun
1034 &optional (convert-type t))
1035 (declare (type function derive-fun fun))
1036 (flet ((deriver (x y same-arg)
1037 (cond ((and (member-type-p x) (member-type-p y))
1038 (let* ((x (first (member-type-members x)))
1039 (y (first (member-type-members y)))
1040 (result (with-float-traps-masked
1041 (:underflow :overflow :divide-by-zero
1043 (funcall fun x y))))
1044 (cond ((null result))
1045 ((and (floatp result) (float-nan-p result))
1046 (make-numeric-type :class 'float
1047 :format (type-of result)
1050 (make-member-type :members (list result))))))
1051 ((and (member-type-p x) (numeric-type-p y))
1052 (let* ((x (convert-member-type x))
1053 (y (if convert-type (convert-numeric-type y) y))
1054 (result (funcall derive-fun x y same-arg)))
1056 (convert-back-numeric-type-list result)
1058 ((and (numeric-type-p x) (member-type-p y))
1059 (let* ((x (if convert-type (convert-numeric-type x) x))
1060 (y (convert-member-type y))
1061 (result (funcall derive-fun x y same-arg)))
1063 (convert-back-numeric-type-list result)
1065 ((and (numeric-type-p x) (numeric-type-p y))
1066 (let* ((x (if convert-type (convert-numeric-type x) x))
1067 (y (if convert-type (convert-numeric-type y) y))
1068 (result (funcall derive-fun x y same-arg)))
1070 (convert-back-numeric-type-list result)
1073 *universal-type*))))
1074 (let ((same-arg (same-leaf-ref-p arg1 arg2))
1075 (a1 (prepare-arg-for-derive-type (lvar-type arg1)))
1076 (a2 (prepare-arg-for-derive-type (lvar-type arg2))))
1078 (let ((results nil))
1080 ;; Since the args are the same LVARs, just run down the
1083 (let ((result (deriver x x same-arg)))
1085 (setf results (append results result))
1086 (push result results))))
1087 ;; Try all pairwise combinations.
1090 (let ((result (or (deriver x y same-arg)
1091 (numeric-contagion x y))))
1093 (setf results (append results result))
1094 (push result results))))))
1096 (make-canonical-union-type results)
1097 (first results)))))))
1099 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1101 (defoptimizer (+ derive-type) ((x y))
1102 (derive-integer-type
1109 (values (frob (numeric-type-low x) (numeric-type-low y))
1110 (frob (numeric-type-high x) (numeric-type-high y)))))))
1112 (defoptimizer (- derive-type) ((x y))
1113 (derive-integer-type
1120 (values (frob (numeric-type-low x) (numeric-type-high y))
1121 (frob (numeric-type-high x) (numeric-type-low y)))))))
1123 (defoptimizer (* derive-type) ((x y))
1124 (derive-integer-type
1127 (let ((x-low (numeric-type-low x))
1128 (x-high (numeric-type-high x))
1129 (y-low (numeric-type-low y))
1130 (y-high (numeric-type-high y)))
1131 (cond ((not (and x-low y-low))
1133 ((or (minusp x-low) (minusp y-low))
1134 (if (and x-high y-high)
1135 (let ((max (* (max (abs x-low) (abs x-high))
1136 (max (abs y-low) (abs y-high)))))
1137 (values (- max) max))
1140 (values (* x-low y-low)
1141 (if (and x-high y-high)
1145 (defoptimizer (/ derive-type) ((x y))
1146 (numeric-contagion (lvar-type x) (lvar-type y)))
1150 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1152 (defun +-derive-type-aux (x y same-arg)
1153 (if (and (numeric-type-real-p x)
1154 (numeric-type-real-p y))
1157 (let ((x-int (numeric-type->interval x)))
1158 (interval-add x-int x-int))
1159 (interval-add (numeric-type->interval x)
1160 (numeric-type->interval y))))
1161 (result-type (numeric-contagion x y)))
1162 ;; If the result type is a float, we need to be sure to coerce
1163 ;; the bounds into the correct type.
1164 (when (eq (numeric-type-class result-type) 'float)
1165 (setf result (interval-func
1167 (coerce x (or (numeric-type-format result-type)
1171 :class (if (and (eq (numeric-type-class x) 'integer)
1172 (eq (numeric-type-class y) 'integer))
1173 ;; The sum of integers is always an integer.
1175 (numeric-type-class result-type))
1176 :format (numeric-type-format result-type)
1177 :low (interval-low result)
1178 :high (interval-high result)))
1179 ;; general contagion
1180 (numeric-contagion x y)))
1182 (defoptimizer (+ derive-type) ((x y))
1183 (two-arg-derive-type x y #'+-derive-type-aux #'+))
1185 (defun --derive-type-aux (x y same-arg)
1186 (if (and (numeric-type-real-p x)
1187 (numeric-type-real-p y))
1189 ;; (- X X) is always 0.
1191 (make-interval :low 0 :high 0)
1192 (interval-sub (numeric-type->interval x)
1193 (numeric-type->interval y))))
1194 (result-type (numeric-contagion x y)))
1195 ;; If the result type is a float, we need to be sure to coerce
1196 ;; the bounds into the correct type.
1197 (when (eq (numeric-type-class result-type) 'float)
1198 (setf result (interval-func
1200 (coerce x (or (numeric-type-format result-type)
1204 :class (if (and (eq (numeric-type-class x) 'integer)
1205 (eq (numeric-type-class y) 'integer))
1206 ;; The difference of integers is always an integer.
1208 (numeric-type-class result-type))
1209 :format (numeric-type-format result-type)
1210 :low (interval-low result)
1211 :high (interval-high result)))
1212 ;; general contagion
1213 (numeric-contagion x y)))
1215 (defoptimizer (- derive-type) ((x y))
1216 (two-arg-derive-type x y #'--derive-type-aux #'-))
1218 (defun *-derive-type-aux (x y same-arg)
1219 (if (and (numeric-type-real-p x)
1220 (numeric-type-real-p y))
1222 ;; (* X X) is always positive, so take care to do it right.
1224 (interval-sqr (numeric-type->interval x))
1225 (interval-mul (numeric-type->interval x)
1226 (numeric-type->interval y))))
1227 (result-type (numeric-contagion x y)))
1228 ;; If the result type is a float, we need to be sure to coerce
1229 ;; the bounds into the correct type.
1230 (when (eq (numeric-type-class result-type) 'float)
1231 (setf result (interval-func
1233 (coerce x (or (numeric-type-format result-type)
1237 :class (if (and (eq (numeric-type-class x) 'integer)
1238 (eq (numeric-type-class y) 'integer))
1239 ;; The product of integers is always an integer.
1241 (numeric-type-class result-type))
1242 :format (numeric-type-format result-type)
1243 :low (interval-low result)
1244 :high (interval-high result)))
1245 (numeric-contagion x y)))
1247 (defoptimizer (* derive-type) ((x y))
1248 (two-arg-derive-type x y #'*-derive-type-aux #'*))
1250 (defun /-derive-type-aux (x y same-arg)
1251 (if (and (numeric-type-real-p x)
1252 (numeric-type-real-p y))
1254 ;; (/ X X) is always 1, except if X can contain 0. In
1255 ;; that case, we shouldn't optimize the division away
1256 ;; because we want 0/0 to signal an error.
1258 (not (interval-contains-p
1259 0 (interval-closure (numeric-type->interval y)))))
1260 (make-interval :low 1 :high 1)
1261 (interval-div (numeric-type->interval x)
1262 (numeric-type->interval y))))
1263 (result-type (numeric-contagion x y)))
1264 ;; If the result type is a float, we need to be sure to coerce
1265 ;; the bounds into the correct type.
1266 (when (eq (numeric-type-class result-type) 'float)
1267 (setf result (interval-func
1269 (coerce x (or (numeric-type-format result-type)
1272 (make-numeric-type :class (numeric-type-class result-type)
1273 :format (numeric-type-format result-type)
1274 :low (interval-low result)
1275 :high (interval-high result)))
1276 (numeric-contagion x y)))
1278 (defoptimizer (/ derive-type) ((x y))
1279 (two-arg-derive-type x y #'/-derive-type-aux #'/))
1283 (defun ash-derive-type-aux (n-type shift same-arg)
1284 (declare (ignore same-arg))
1285 ;; KLUDGE: All this ASH optimization is suppressed under CMU CL for
1286 ;; some bignum cases because as of version 2.4.6 for Debian and 18d,
1287 ;; CMU CL blows up on (ASH 1000000000 -100000000000) (i.e. ASH of
1288 ;; two bignums yielding zero) and it's hard to avoid that
1289 ;; calculation in here.
1290 #+(and cmu sb-xc-host)
1291 (when (and (or (typep (numeric-type-low n-type) 'bignum)
1292 (typep (numeric-type-high n-type) 'bignum))
1293 (or (typep (numeric-type-low shift) 'bignum)
1294 (typep (numeric-type-high shift) 'bignum)))
1295 (return-from ash-derive-type-aux *universal-type*))
1296 (flet ((ash-outer (n s)
1297 (when (and (fixnump s)
1299 (> s sb!xc:most-negative-fixnum))
1301 ;; KLUDGE: The bare 64's here should be related to
1302 ;; symbolic machine word size values somehow.
1305 (if (and (fixnump s)
1306 (> s sb!xc:most-negative-fixnum))
1308 (if (minusp n) -1 0))))
1309 (or (and (csubtypep n-type (specifier-type 'integer))
1310 (csubtypep shift (specifier-type 'integer))
1311 (let ((n-low (numeric-type-low n-type))
1312 (n-high (numeric-type-high n-type))
1313 (s-low (numeric-type-low shift))
1314 (s-high (numeric-type-high shift)))
1315 (make-numeric-type :class 'integer :complexp :real
1318 (ash-outer n-low s-high)
1319 (ash-inner n-low s-low)))
1322 (ash-inner n-high s-low)
1323 (ash-outer n-high s-high))))))
1326 (defoptimizer (ash derive-type) ((n shift))
1327 (two-arg-derive-type n shift #'ash-derive-type-aux #'ash))
1329 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1330 (macrolet ((frob (fun)
1331 `#'(lambda (type type2)
1332 (declare (ignore type2))
1333 (let ((lo (numeric-type-low type))
1334 (hi (numeric-type-high type)))
1335 (values (if hi (,fun hi) nil) (if lo (,fun lo) nil))))))
1337 (defoptimizer (%negate derive-type) ((num))
1338 (derive-integer-type num num (frob -))))
1340 (defun lognot-derive-type-aux (int)
1341 (derive-integer-type-aux int int
1342 (lambda (type type2)
1343 (declare (ignore type2))
1344 (let ((lo (numeric-type-low type))
1345 (hi (numeric-type-high type)))
1346 (values (if hi (lognot hi) nil)
1347 (if lo (lognot lo) nil)
1348 (numeric-type-class type)
1349 (numeric-type-format type))))))
1351 (defoptimizer (lognot derive-type) ((int))
1352 (lognot-derive-type-aux (lvar-type int)))
1354 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1355 (defoptimizer (%negate derive-type) ((num))
1356 (flet ((negate-bound (b)
1358 (set-bound (- (type-bound-number b))
1360 (one-arg-derive-type num
1362 (modified-numeric-type
1364 :low (negate-bound (numeric-type-high type))
1365 :high (negate-bound (numeric-type-low type))))
1368 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1369 (defoptimizer (abs derive-type) ((num))
1370 (let ((type (lvar-type num)))
1371 (if (and (numeric-type-p type)
1372 (eq (numeric-type-class type) 'integer)
1373 (eq (numeric-type-complexp type) :real))
1374 (let ((lo (numeric-type-low type))
1375 (hi (numeric-type-high type)))
1376 (make-numeric-type :class 'integer :complexp :real
1377 :low (cond ((and hi (minusp hi))
1383 :high (if (and hi lo)
1384 (max (abs hi) (abs lo))
1386 (numeric-contagion type type))))
1388 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1389 (defun abs-derive-type-aux (type)
1390 (cond ((eq (numeric-type-complexp type) :complex)
1391 ;; The absolute value of a complex number is always a
1392 ;; non-negative float.
1393 (let* ((format (case (numeric-type-class type)
1394 ((integer rational) 'single-float)
1395 (t (numeric-type-format type))))
1396 (bound-format (or format 'float)))
1397 (make-numeric-type :class 'float
1400 :low (coerce 0 bound-format)
1403 ;; The absolute value of a real number is a non-negative real
1404 ;; of the same type.
1405 (let* ((abs-bnd (interval-abs (numeric-type->interval type)))
1406 (class (numeric-type-class type))
1407 (format (numeric-type-format type))
1408 (bound-type (or format class 'real)))
1413 :low (coerce-numeric-bound (interval-low abs-bnd) bound-type)
1414 :high (coerce-numeric-bound
1415 (interval-high abs-bnd) bound-type))))))
1417 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1418 (defoptimizer (abs derive-type) ((num))
1419 (one-arg-derive-type num #'abs-derive-type-aux #'abs))
1421 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1422 (defoptimizer (truncate derive-type) ((number divisor))
1423 (let ((number-type (lvar-type number))
1424 (divisor-type (lvar-type divisor))
1425 (integer-type (specifier-type 'integer)))
1426 (if (and (numeric-type-p number-type)
1427 (csubtypep number-type integer-type)
1428 (numeric-type-p divisor-type)
1429 (csubtypep divisor-type integer-type))
1430 (let ((number-low (numeric-type-low number-type))
1431 (number-high (numeric-type-high number-type))
1432 (divisor-low (numeric-type-low divisor-type))
1433 (divisor-high (numeric-type-high divisor-type)))
1434 (values-specifier-type
1435 `(values ,(integer-truncate-derive-type number-low number-high
1436 divisor-low divisor-high)
1437 ,(integer-rem-derive-type number-low number-high
1438 divisor-low divisor-high))))
1441 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1444 (defun rem-result-type (number-type divisor-type)
1445 ;; Figure out what the remainder type is. The remainder is an
1446 ;; integer if both args are integers; a rational if both args are
1447 ;; rational; and a float otherwise.
1448 (cond ((and (csubtypep number-type (specifier-type 'integer))
1449 (csubtypep divisor-type (specifier-type 'integer)))
1451 ((and (csubtypep number-type (specifier-type 'rational))
1452 (csubtypep divisor-type (specifier-type 'rational)))
1454 ((and (csubtypep number-type (specifier-type 'float))
1455 (csubtypep divisor-type (specifier-type 'float)))
1456 ;; Both are floats so the result is also a float, of
1457 ;; the largest type.
1458 (or (float-format-max (numeric-type-format number-type)
1459 (numeric-type-format divisor-type))
1461 ((and (csubtypep number-type (specifier-type 'float))
1462 (csubtypep divisor-type (specifier-type 'rational)))
1463 ;; One of the arguments is a float and the other is a
1464 ;; rational. The remainder is a float of the same
1466 (or (numeric-type-format number-type) 'float))
1467 ((and (csubtypep divisor-type (specifier-type 'float))
1468 (csubtypep number-type (specifier-type 'rational)))
1469 ;; One of the arguments is a float and the other is a
1470 ;; rational. The remainder is a float of the same
1472 (or (numeric-type-format divisor-type) 'float))
1474 ;; Some unhandled combination. This usually means both args
1475 ;; are REAL so the result is a REAL.
1478 (defun truncate-derive-type-quot (number-type divisor-type)
1479 (let* ((rem-type (rem-result-type number-type divisor-type))
1480 (number-interval (numeric-type->interval number-type))
1481 (divisor-interval (numeric-type->interval divisor-type)))
1482 ;;(declare (type (member '(integer rational float)) rem-type))
1483 ;; We have real numbers now.
1484 (cond ((eq rem-type 'integer)
1485 ;; Since the remainder type is INTEGER, both args are
1487 (let* ((res (integer-truncate-derive-type
1488 (interval-low number-interval)
1489 (interval-high number-interval)
1490 (interval-low divisor-interval)
1491 (interval-high divisor-interval))))
1492 (specifier-type (if (listp res) res 'integer))))
1494 (let ((quot (truncate-quotient-bound
1495 (interval-div number-interval
1496 divisor-interval))))
1497 (specifier-type `(integer ,(or (interval-low quot) '*)
1498 ,(or (interval-high quot) '*))))))))
1500 (defun truncate-derive-type-rem (number-type divisor-type)
1501 (let* ((rem-type (rem-result-type number-type divisor-type))
1502 (number-interval (numeric-type->interval number-type))
1503 (divisor-interval (numeric-type->interval divisor-type))
1504 (rem (truncate-rem-bound number-interval divisor-interval)))
1505 ;;(declare (type (member '(integer rational float)) rem-type))
1506 ;; We have real numbers now.
1507 (cond ((eq rem-type 'integer)
1508 ;; Since the remainder type is INTEGER, both args are
1510 (specifier-type `(,rem-type ,(or (interval-low rem) '*)
1511 ,(or (interval-high rem) '*))))
1513 (multiple-value-bind (class format)
1516 (values 'integer nil))
1518 (values 'rational nil))
1519 ((or single-float double-float #!+long-float long-float)
1520 (values 'float rem-type))
1522 (values 'float nil))
1525 (when (member rem-type '(float single-float double-float
1526 #!+long-float long-float))
1527 (setf rem (interval-func #'(lambda (x)
1528 (coerce x rem-type))
1530 (make-numeric-type :class class
1532 :low (interval-low rem)
1533 :high (interval-high rem)))))))
1535 (defun truncate-derive-type-quot-aux (num div same-arg)
1536 (declare (ignore same-arg))
1537 (if (and (numeric-type-real-p num)
1538 (numeric-type-real-p div))
1539 (truncate-derive-type-quot num div)
1542 (defun truncate-derive-type-rem-aux (num div same-arg)
1543 (declare (ignore same-arg))
1544 (if (and (numeric-type-real-p num)
1545 (numeric-type-real-p div))
1546 (truncate-derive-type-rem num div)
1549 (defoptimizer (truncate derive-type) ((number divisor))
1550 (let ((quot (two-arg-derive-type number divisor
1551 #'truncate-derive-type-quot-aux #'truncate))
1552 (rem (two-arg-derive-type number divisor
1553 #'truncate-derive-type-rem-aux #'rem)))
1554 (when (and quot rem)
1555 (make-values-type :required (list quot rem)))))
1557 (defun ftruncate-derive-type-quot (number-type divisor-type)
1558 ;; The bounds are the same as for truncate. However, the first
1559 ;; result is a float of some type. We need to determine what that
1560 ;; type is. Basically it's the more contagious of the two types.
1561 (let ((q-type (truncate-derive-type-quot number-type divisor-type))
1562 (res-type (numeric-contagion number-type divisor-type)))
1563 (make-numeric-type :class 'float
1564 :format (numeric-type-format res-type)
1565 :low (numeric-type-low q-type)
1566 :high (numeric-type-high q-type))))
1568 (defun ftruncate-derive-type-quot-aux (n d same-arg)
1569 (declare (ignore same-arg))
1570 (if (and (numeric-type-real-p n)
1571 (numeric-type-real-p d))
1572 (ftruncate-derive-type-quot n d)
1575 (defoptimizer (ftruncate derive-type) ((number divisor))
1577 (two-arg-derive-type number divisor
1578 #'ftruncate-derive-type-quot-aux #'ftruncate))
1579 (rem (two-arg-derive-type number divisor
1580 #'truncate-derive-type-rem-aux #'rem)))
1581 (when (and quot rem)
1582 (make-values-type :required (list quot rem)))))
1584 (defun %unary-truncate-derive-type-aux (number)
1585 (truncate-derive-type-quot number (specifier-type '(integer 1 1))))
1587 (defoptimizer (%unary-truncate derive-type) ((number))
1588 (one-arg-derive-type number
1589 #'%unary-truncate-derive-type-aux
1592 ;;; Define optimizers for FLOOR and CEILING.
1594 ((def (name q-name r-name)
1595 (let ((q-aux (symbolicate q-name "-AUX"))
1596 (r-aux (symbolicate r-name "-AUX")))
1598 ;; Compute type of quotient (first) result.
1599 (defun ,q-aux (number-type divisor-type)
1600 (let* ((number-interval
1601 (numeric-type->interval number-type))
1603 (numeric-type->interval divisor-type))
1604 (quot (,q-name (interval-div number-interval
1605 divisor-interval))))
1606 (specifier-type `(integer ,(or (interval-low quot) '*)
1607 ,(or (interval-high quot) '*)))))
1608 ;; Compute type of remainder.
1609 (defun ,r-aux (number-type divisor-type)
1610 (let* ((divisor-interval
1611 (numeric-type->interval divisor-type))
1612 (rem (,r-name divisor-interval))
1613 (result-type (rem-result-type number-type divisor-type)))
1614 (multiple-value-bind (class format)
1617 (values 'integer nil))
1619 (values 'rational nil))
1620 ((or single-float double-float #!+long-float long-float)
1621 (values 'float result-type))
1623 (values 'float nil))
1626 (when (member result-type '(float single-float double-float
1627 #!+long-float long-float))
1628 ;; Make sure that the limits on the interval have
1630 (setf rem (interval-func (lambda (x)
1631 (coerce x result-type))
1633 (make-numeric-type :class class
1635 :low (interval-low rem)
1636 :high (interval-high rem)))))
1637 ;; the optimizer itself
1638 (defoptimizer (,name derive-type) ((number divisor))
1639 (flet ((derive-q (n d same-arg)
1640 (declare (ignore same-arg))
1641 (if (and (numeric-type-real-p n)
1642 (numeric-type-real-p d))
1645 (derive-r (n d same-arg)
1646 (declare (ignore same-arg))
1647 (if (and (numeric-type-real-p n)
1648 (numeric-type-real-p d))
1651 (let ((quot (two-arg-derive-type
1652 number divisor #'derive-q #',name))
1653 (rem (two-arg-derive-type
1654 number divisor #'derive-r #'mod)))
1655 (when (and quot rem)
1656 (make-values-type :required (list quot rem))))))))))
1658 (def floor floor-quotient-bound floor-rem-bound)
1659 (def ceiling ceiling-quotient-bound ceiling-rem-bound))
1661 ;;; Define optimizers for FFLOOR and FCEILING
1662 (macrolet ((def (name q-name r-name)
1663 (let ((q-aux (symbolicate "F" q-name "-AUX"))
1664 (r-aux (symbolicate r-name "-AUX")))
1666 ;; Compute type of quotient (first) result.
1667 (defun ,q-aux (number-type divisor-type)
1668 (let* ((number-interval
1669 (numeric-type->interval number-type))
1671 (numeric-type->interval divisor-type))
1672 (quot (,q-name (interval-div number-interval
1674 (res-type (numeric-contagion number-type
1677 :class (numeric-type-class res-type)
1678 :format (numeric-type-format res-type)
1679 :low (interval-low quot)
1680 :high (interval-high quot))))
1682 (defoptimizer (,name derive-type) ((number divisor))
1683 (flet ((derive-q (n d same-arg)
1684 (declare (ignore same-arg))
1685 (if (and (numeric-type-real-p n)
1686 (numeric-type-real-p d))
1689 (derive-r (n d same-arg)
1690 (declare (ignore same-arg))
1691 (if (and (numeric-type-real-p n)
1692 (numeric-type-real-p d))
1695 (let ((quot (two-arg-derive-type
1696 number divisor #'derive-q #',name))
1697 (rem (two-arg-derive-type
1698 number divisor #'derive-r #'mod)))
1699 (when (and quot rem)
1700 (make-values-type :required (list quot rem))))))))))
1702 (def ffloor floor-quotient-bound floor-rem-bound)
1703 (def fceiling ceiling-quotient-bound ceiling-rem-bound))
1705 ;;; functions to compute the bounds on the quotient and remainder for
1706 ;;; the FLOOR function
1707 (defun floor-quotient-bound (quot)
1708 ;; Take the floor of the quotient and then massage it into what we
1710 (let ((lo (interval-low quot))
1711 (hi (interval-high quot)))
1712 ;; Take the floor of the lower bound. The result is always a
1713 ;; closed lower bound.
1715 (floor (type-bound-number lo))
1717 ;; For the upper bound, we need to be careful.
1720 ;; An open bound. We need to be careful here because
1721 ;; the floor of '(10.0) is 9, but the floor of
1723 (multiple-value-bind (q r) (floor (first hi))
1728 ;; A closed bound, so the answer is obvious.
1732 (make-interval :low lo :high hi)))
1733 (defun floor-rem-bound (div)
1734 ;; The remainder depends only on the divisor. Try to get the
1735 ;; correct sign for the remainder if we can.
1736 (case (interval-range-info div)
1738 ;; The divisor is always positive.
1739 (let ((rem (interval-abs div)))
1740 (setf (interval-low rem) 0)
1741 (when (and (numberp (interval-high rem))
1742 (not (zerop (interval-high rem))))
1743 ;; The remainder never contains the upper bound. However,
1744 ;; watch out for the case where the high limit is zero!
1745 (setf (interval-high rem) (list (interval-high rem))))
1748 ;; The divisor is always negative.
1749 (let ((rem (interval-neg (interval-abs div))))
1750 (setf (interval-high rem) 0)
1751 (when (numberp (interval-low rem))
1752 ;; The remainder never contains the lower bound.
1753 (setf (interval-low rem) (list (interval-low rem))))
1756 ;; The divisor can be positive or negative. All bets off. The
1757 ;; magnitude of remainder is the maximum value of the divisor.
1758 (let ((limit (type-bound-number (interval-high (interval-abs div)))))
1759 ;; The bound never reaches the limit, so make the interval open.
1760 (make-interval :low (if limit
1763 :high (list limit))))))
1765 (floor-quotient-bound (make-interval :low 0.3 :high 10.3))
1766 => #S(INTERVAL :LOW 0 :HIGH 10)
1767 (floor-quotient-bound (make-interval :low 0.3 :high '(10.3)))
1768 => #S(INTERVAL :LOW 0 :HIGH 10)
1769 (floor-quotient-bound (make-interval :low 0.3 :high 10))
1770 => #S(INTERVAL :LOW 0 :HIGH 10)
1771 (floor-quotient-bound (make-interval :low 0.3 :high '(10)))
1772 => #S(INTERVAL :LOW 0 :HIGH 9)
1773 (floor-quotient-bound (make-interval :low '(0.3) :high 10.3))
1774 => #S(INTERVAL :LOW 0 :HIGH 10)
1775 (floor-quotient-bound (make-interval :low '(0.0) :high 10.3))
1776 => #S(INTERVAL :LOW 0 :HIGH 10)
1777 (floor-quotient-bound (make-interval :low '(-1.3) :high 10.3))
1778 => #S(INTERVAL :LOW -2 :HIGH 10)
1779 (floor-quotient-bound (make-interval :low '(-1.0) :high 10.3))
1780 => #S(INTERVAL :LOW -1 :HIGH 10)
1781 (floor-quotient-bound (make-interval :low -1.0 :high 10.3))
1782 => #S(INTERVAL :LOW -1 :HIGH 10)
1784 (floor-rem-bound (make-interval :low 0.3 :high 10.3))
1785 => #S(INTERVAL :LOW 0 :HIGH '(10.3))
1786 (floor-rem-bound (make-interval :low 0.3 :high '(10.3)))
1787 => #S(INTERVAL :LOW 0 :HIGH '(10.3))
1788 (floor-rem-bound (make-interval :low -10 :high -2.3))
1789 #S(INTERVAL :LOW (-10) :HIGH 0)
1790 (floor-rem-bound (make-interval :low 0.3 :high 10))
1791 => #S(INTERVAL :LOW 0 :HIGH '(10))
1792 (floor-rem-bound (make-interval :low '(-1.3) :high 10.3))
1793 => #S(INTERVAL :LOW '(-10.3) :HIGH '(10.3))
1794 (floor-rem-bound (make-interval :low '(-20.3) :high 10.3))
1795 => #S(INTERVAL :LOW (-20.3) :HIGH (20.3))
1798 ;;; same functions for CEILING
1799 (defun ceiling-quotient-bound (quot)
1800 ;; Take the ceiling of the quotient and then massage it into what we
1802 (let ((lo (interval-low quot))
1803 (hi (interval-high quot)))
1804 ;; Take the ceiling of the upper bound. The result is always a
1805 ;; closed upper bound.
1807 (ceiling (type-bound-number hi))
1809 ;; For the lower bound, we need to be careful.
1812 ;; An open bound. We need to be careful here because
1813 ;; the ceiling of '(10.0) is 11, but the ceiling of
1815 (multiple-value-bind (q r) (ceiling (first lo))
1820 ;; A closed bound, so the answer is obvious.
1824 (make-interval :low lo :high hi)))
1825 (defun ceiling-rem-bound (div)
1826 ;; The remainder depends only on the divisor. Try to get the
1827 ;; correct sign for the remainder if we can.
1828 (case (interval-range-info div)
1830 ;; Divisor is always positive. The remainder is negative.
1831 (let ((rem (interval-neg (interval-abs div))))
1832 (setf (interval-high rem) 0)
1833 (when (and (numberp (interval-low rem))
1834 (not (zerop (interval-low rem))))
1835 ;; The remainder never contains the upper bound. However,
1836 ;; watch out for the case when the upper bound is zero!
1837 (setf (interval-low rem) (list (interval-low rem))))
1840 ;; Divisor is always negative. The remainder is positive
1841 (let ((rem (interval-abs div)))
1842 (setf (interval-low rem) 0)
1843 (when (numberp (interval-high rem))
1844 ;; The remainder never contains the lower bound.
1845 (setf (interval-high rem) (list (interval-high rem))))
1848 ;; The divisor can be positive or negative. All bets off. The
1849 ;; magnitude of remainder is the maximum value of the divisor.
1850 (let ((limit (type-bound-number (interval-high (interval-abs div)))))
1851 ;; The bound never reaches the limit, so make the interval open.
1852 (make-interval :low (if limit
1855 :high (list limit))))))
1858 (ceiling-quotient-bound (make-interval :low 0.3 :high 10.3))
1859 => #S(INTERVAL :LOW 1 :HIGH 11)
1860 (ceiling-quotient-bound (make-interval :low 0.3 :high '(10.3)))
1861 => #S(INTERVAL :LOW 1 :HIGH 11)
1862 (ceiling-quotient-bound (make-interval :low 0.3 :high 10))
1863 => #S(INTERVAL :LOW 1 :HIGH 10)
1864 (ceiling-quotient-bound (make-interval :low 0.3 :high '(10)))
1865 => #S(INTERVAL :LOW 1 :HIGH 10)
1866 (ceiling-quotient-bound (make-interval :low '(0.3) :high 10.3))
1867 => #S(INTERVAL :LOW 1 :HIGH 11)
1868 (ceiling-quotient-bound (make-interval :low '(0.0) :high 10.3))
1869 => #S(INTERVAL :LOW 1 :HIGH 11)
1870 (ceiling-quotient-bound (make-interval :low '(-1.3) :high 10.3))
1871 => #S(INTERVAL :LOW -1 :HIGH 11)
1872 (ceiling-quotient-bound (make-interval :low '(-1.0) :high 10.3))
1873 => #S(INTERVAL :LOW 0 :HIGH 11)
1874 (ceiling-quotient-bound (make-interval :low -1.0 :high 10.3))
1875 => #S(INTERVAL :LOW -1 :HIGH 11)
1877 (ceiling-rem-bound (make-interval :low 0.3 :high 10.3))
1878 => #S(INTERVAL :LOW (-10.3) :HIGH 0)
1879 (ceiling-rem-bound (make-interval :low 0.3 :high '(10.3)))
1880 => #S(INTERVAL :LOW 0 :HIGH '(10.3))
1881 (ceiling-rem-bound (make-interval :low -10 :high -2.3))
1882 => #S(INTERVAL :LOW 0 :HIGH (10))
1883 (ceiling-rem-bound (make-interval :low 0.3 :high 10))
1884 => #S(INTERVAL :LOW (-10) :HIGH 0)
1885 (ceiling-rem-bound (make-interval :low '(-1.3) :high 10.3))
1886 => #S(INTERVAL :LOW (-10.3) :HIGH (10.3))
1887 (ceiling-rem-bound (make-interval :low '(-20.3) :high 10.3))
1888 => #S(INTERVAL :LOW (-20.3) :HIGH (20.3))
1891 (defun truncate-quotient-bound (quot)
1892 ;; For positive quotients, truncate is exactly like floor. For
1893 ;; negative quotients, truncate is exactly like ceiling. Otherwise,
1894 ;; it's the union of the two pieces.
1895 (case (interval-range-info quot)
1898 (floor-quotient-bound quot))
1900 ;; just like CEILING
1901 (ceiling-quotient-bound quot))
1903 ;; Split the interval into positive and negative pieces, compute
1904 ;; the result for each piece and put them back together.
1905 (destructuring-bind (neg pos) (interval-split 0 quot t t)
1906 (interval-merge-pair (ceiling-quotient-bound neg)
1907 (floor-quotient-bound pos))))))
1909 (defun truncate-rem-bound (num div)
1910 ;; This is significantly more complicated than FLOOR or CEILING. We
1911 ;; need both the number and the divisor to determine the range. The
1912 ;; basic idea is to split the ranges of NUM and DEN into positive
1913 ;; and negative pieces and deal with each of the four possibilities
1915 (case (interval-range-info num)
1917 (case (interval-range-info div)
1919 (floor-rem-bound div))
1921 (ceiling-rem-bound div))
1923 (destructuring-bind (neg pos) (interval-split 0 div t t)
1924 (interval-merge-pair (truncate-rem-bound num neg)
1925 (truncate-rem-bound num pos))))))
1927 (case (interval-range-info div)
1929 (ceiling-rem-bound div))
1931 (floor-rem-bound div))
1933 (destructuring-bind (neg pos) (interval-split 0 div t t)
1934 (interval-merge-pair (truncate-rem-bound num neg)
1935 (truncate-rem-bound num pos))))))
1937 (destructuring-bind (neg pos) (interval-split 0 num t t)
1938 (interval-merge-pair (truncate-rem-bound neg div)
1939 (truncate-rem-bound pos div))))))
1942 ;;; Derive useful information about the range. Returns three values:
1943 ;;; - '+ if its positive, '- negative, or nil if it overlaps 0.
1944 ;;; - The abs of the minimal value (i.e. closest to 0) in the range.
1945 ;;; - The abs of the maximal value if there is one, or nil if it is
1947 (defun numeric-range-info (low high)
1948 (cond ((and low (not (minusp low)))
1949 (values '+ low high))
1950 ((and high (not (plusp high)))
1951 (values '- (- high) (if low (- low) nil)))
1953 (values nil 0 (and low high (max (- low) high))))))
1955 (defun integer-truncate-derive-type
1956 (number-low number-high divisor-low divisor-high)
1957 ;; The result cannot be larger in magnitude than the number, but the
1958 ;; sign might change. If we can determine the sign of either the
1959 ;; number or the divisor, we can eliminate some of the cases.
1960 (multiple-value-bind (number-sign number-min number-max)
1961 (numeric-range-info number-low number-high)
1962 (multiple-value-bind (divisor-sign divisor-min divisor-max)
1963 (numeric-range-info divisor-low divisor-high)
1964 (when (and divisor-max (zerop divisor-max))
1965 ;; We've got a problem: guaranteed division by zero.
1966 (return-from integer-truncate-derive-type t))
1967 (when (zerop divisor-min)
1968 ;; We'll assume that they aren't going to divide by zero.
1970 (cond ((and number-sign divisor-sign)
1971 ;; We know the sign of both.
1972 (if (eq number-sign divisor-sign)
1973 ;; Same sign, so the result will be positive.
1974 `(integer ,(if divisor-max
1975 (truncate number-min divisor-max)
1978 (truncate number-max divisor-min)
1980 ;; Different signs, the result will be negative.
1981 `(integer ,(if number-max
1982 (- (truncate number-max divisor-min))
1985 (- (truncate number-min divisor-max))
1987 ((eq divisor-sign '+)
1988 ;; The divisor is positive. Therefore, the number will just
1989 ;; become closer to zero.
1990 `(integer ,(if number-low
1991 (truncate number-low divisor-min)
1994 (truncate number-high divisor-min)
1996 ((eq divisor-sign '-)
1997 ;; The divisor is negative. Therefore, the absolute value of
1998 ;; the number will become closer to zero, but the sign will also
2000 `(integer ,(if number-high
2001 (- (truncate number-high divisor-min))
2004 (- (truncate number-low divisor-min))
2006 ;; The divisor could be either positive or negative.
2008 ;; The number we are dividing has a bound. Divide that by the
2009 ;; smallest posible divisor.
2010 (let ((bound (truncate number-max divisor-min)))
2011 `(integer ,(- bound) ,bound)))
2013 ;; The number we are dividing is unbounded, so we can't tell
2014 ;; anything about the result.
2017 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2018 (defun integer-rem-derive-type
2019 (number-low number-high divisor-low divisor-high)
2020 (if (and divisor-low divisor-high)
2021 ;; We know the range of the divisor, and the remainder must be
2022 ;; smaller than the divisor. We can tell the sign of the
2023 ;; remainer if we know the sign of the number.
2024 (let ((divisor-max (1- (max (abs divisor-low) (abs divisor-high)))))
2025 `(integer ,(if (or (null number-low)
2026 (minusp number-low))
2029 ,(if (or (null number-high)
2030 (plusp number-high))
2033 ;; The divisor is potentially either very positive or very
2034 ;; negative. Therefore, the remainer is unbounded, but we might
2035 ;; be able to tell something about the sign from the number.
2036 `(integer ,(if (and number-low (not (minusp number-low)))
2037 ;; The number we are dividing is positive.
2038 ;; Therefore, the remainder must be positive.
2041 ,(if (and number-high (not (plusp number-high)))
2042 ;; The number we are dividing is negative.
2043 ;; Therefore, the remainder must be negative.
2047 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2048 (defoptimizer (random derive-type) ((bound &optional state))
2049 (let ((type (lvar-type bound)))
2050 (when (numeric-type-p type)
2051 (let ((class (numeric-type-class type))
2052 (high (numeric-type-high type))
2053 (format (numeric-type-format type)))
2057 :low (coerce 0 (or format class 'real))
2058 :high (cond ((not high) nil)
2059 ((eq class 'integer) (max (1- high) 0))
2060 ((or (consp high) (zerop high)) high)
2063 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2064 (defun random-derive-type-aux (type)
2065 (let ((class (numeric-type-class type))
2066 (high (numeric-type-high type))
2067 (format (numeric-type-format type)))
2071 :low (coerce 0 (or format class 'real))
2072 :high (cond ((not high) nil)
2073 ((eq class 'integer) (max (1- high) 0))
2074 ((or (consp high) (zerop high)) high)
2077 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2078 (defoptimizer (random derive-type) ((bound &optional state))
2079 (one-arg-derive-type bound #'random-derive-type-aux nil))
2081 ;;;; DERIVE-TYPE methods for LOGAND, LOGIOR, and friends
2083 ;;; Return the maximum number of bits an integer of the supplied type
2084 ;;; can take up, or NIL if it is unbounded. The second (third) value
2085 ;;; is T if the integer can be positive (negative) and NIL if not.
2086 ;;; Zero counts as positive.
2087 (defun integer-type-length (type)
2088 (if (numeric-type-p type)
2089 (let ((min (numeric-type-low type))
2090 (max (numeric-type-high type)))
2091 (values (and min max (max (integer-length min) (integer-length max)))
2092 (or (null max) (not (minusp max)))
2093 (or (null min) (minusp min))))
2096 (defun logand-derive-type-aux (x y &optional same-leaf)
2097 (declare (ignore same-leaf))
2098 (multiple-value-bind (x-len x-pos x-neg) (integer-type-length x)
2099 (declare (ignore x-pos))
2100 (multiple-value-bind (y-len y-pos y-neg) (integer-type-length y)
2101 (declare (ignore y-pos))
2103 ;; X must be positive.
2105 ;; They must both be positive.
2106 (cond ((or (null x-len) (null y-len))
2107 (specifier-type 'unsigned-byte))
2109 (specifier-type `(unsigned-byte* ,(min x-len y-len)))))
2110 ;; X is positive, but Y might be negative.
2112 (specifier-type 'unsigned-byte))
2114 (specifier-type `(unsigned-byte* ,x-len)))))
2115 ;; X might be negative.
2117 ;; Y must be positive.
2119 (specifier-type 'unsigned-byte))
2120 (t (specifier-type `(unsigned-byte* ,y-len))))
2121 ;; Either might be negative.
2122 (if (and x-len y-len)
2123 ;; The result is bounded.
2124 (specifier-type `(signed-byte ,(1+ (max x-len y-len))))
2125 ;; We can't tell squat about the result.
2126 (specifier-type 'integer)))))))
2128 (defun logior-derive-type-aux (x y &optional same-leaf)
2129 (declare (ignore same-leaf))
2130 (multiple-value-bind (x-len x-pos x-neg) (integer-type-length x)
2131 (multiple-value-bind (y-len y-pos y-neg) (integer-type-length y)
2133 ((and (not x-neg) (not y-neg))
2134 ;; Both are positive.
2135 (specifier-type `(unsigned-byte* ,(if (and x-len y-len)
2139 ;; X must be negative.
2141 ;; Both are negative. The result is going to be negative
2142 ;; and be the same length or shorter than the smaller.
2143 (if (and x-len y-len)
2145 (specifier-type `(integer ,(ash -1 (min x-len y-len)) -1))
2147 (specifier-type '(integer * -1)))
2148 ;; X is negative, but we don't know about Y. The result
2149 ;; will be negative, but no more negative than X.
2151 `(integer ,(or (numeric-type-low x) '*)
2154 ;; X might be either positive or negative.
2156 ;; But Y is negative. The result will be negative.
2158 `(integer ,(or (numeric-type-low y) '*)
2160 ;; We don't know squat about either. It won't get any bigger.
2161 (if (and x-len y-len)
2163 (specifier-type `(signed-byte ,(1+ (max x-len y-len))))
2165 (specifier-type 'integer))))))))
2167 (defun logxor-derive-type-aux (x y &optional same-leaf)
2168 (declare (ignore same-leaf))
2169 (multiple-value-bind (x-len x-pos x-neg) (integer-type-length x)
2170 (multiple-value-bind (y-len y-pos y-neg) (integer-type-length y)
2172 ((or (and (not x-neg) (not y-neg))
2173 (and (not x-pos) (not y-pos)))
2174 ;; Either both are negative or both are positive. The result
2175 ;; will be positive, and as long as the longer.
2176 (specifier-type `(unsigned-byte* ,(if (and x-len y-len)
2179 ((or (and (not x-pos) (not y-neg))
2180 (and (not y-neg) (not y-pos)))
2181 ;; Either X is negative and Y is positive or vice-versa. The
2182 ;; result will be negative.
2183 (specifier-type `(integer ,(if (and x-len y-len)
2184 (ash -1 (max x-len y-len))
2187 ;; We can't tell what the sign of the result is going to be.
2188 ;; All we know is that we don't create new bits.
2190 (specifier-type `(signed-byte ,(1+ (max x-len y-len)))))
2192 (specifier-type 'integer))))))
2194 (macrolet ((deffrob (logfun)
2195 (let ((fun-aux (symbolicate logfun "-DERIVE-TYPE-AUX")))
2196 `(defoptimizer (,logfun derive-type) ((x y))
2197 (two-arg-derive-type x y #',fun-aux #',logfun)))))
2202 ;;; FIXME: could actually do stuff with SAME-LEAF
2203 (defoptimizer (logeqv derive-type) ((x y))
2204 (two-arg-derive-type x y (lambda (x y same-leaf)
2205 (lognot-derive-type-aux
2206 (logxor-derive-type-aux x y same-leaf)))
2208 (defoptimizer (lognand derive-type) ((x y))
2209 (two-arg-derive-type x y (lambda (x y same-leaf)
2210 (lognot-derive-type-aux
2211 (logand-derive-type-aux x y same-leaf)))
2213 (defoptimizer (lognor derive-type) ((x y))
2214 (two-arg-derive-type x y (lambda (x y same-leaf)
2215 (lognot-derive-type-aux
2216 (logior-derive-type-aux x y same-leaf)))
2218 (defoptimizer (logandc1 derive-type) ((x y))
2219 (two-arg-derive-type x y (lambda (x y same-leaf)
2220 (logand-derive-type-aux
2221 (lognot-derive-type-aux x) y nil))
2223 (defoptimizer (logandc2 derive-type) ((x y))
2224 (two-arg-derive-type x y (lambda (x y same-leaf)
2225 (logand-derive-type-aux
2226 x (lognot-derive-type-aux y) nil))
2228 (defoptimizer (logorc1 derive-type) ((x y))
2229 (two-arg-derive-type x y (lambda (x y same-leaf)
2230 (logior-derive-type-aux
2231 (lognot-derive-type-aux x) y nil))
2233 (defoptimizer (logorc2 derive-type) ((x y))
2234 (two-arg-derive-type x y (lambda (x y same-leaf)
2235 (logior-derive-type-aux
2236 x (lognot-derive-type-aux y) nil))
2239 ;;;; miscellaneous derive-type methods
2241 (defoptimizer (integer-length derive-type) ((x))
2242 (let ((x-type (lvar-type x)))
2243 (when (and (numeric-type-p x-type)
2244 (csubtypep x-type (specifier-type 'integer)))
2245 ;; If the X is of type (INTEGER LO HI), then the INTEGER-LENGTH
2246 ;; of X is (INTEGER (MIN lo hi) (MAX lo hi), basically. Be
2247 ;; careful about LO or HI being NIL, though. Also, if 0 is
2248 ;; contained in X, the lower bound is obviously 0.
2249 (flet ((null-or-min (a b)
2250 (and a b (min (integer-length a)
2251 (integer-length b))))
2253 (and a b (max (integer-length a)
2254 (integer-length b)))))
2255 (let* ((min (numeric-type-low x-type))
2256 (max (numeric-type-high x-type))
2257 (min-len (null-or-min min max))
2258 (max-len (null-or-max min max)))
2259 (when (ctypep 0 x-type)
2261 (specifier-type `(integer ,(or min-len '*) ,(or max-len '*))))))))
2263 (defoptimizer (code-char derive-type) ((code))
2264 (specifier-type 'base-char))
2266 (defoptimizer (values derive-type) ((&rest values))
2267 (make-values-type :required (mapcar #'lvar-type values)))
2269 ;;;; byte operations
2271 ;;;; We try to turn byte operations into simple logical operations.
2272 ;;;; First, we convert byte specifiers into separate size and position
2273 ;;;; arguments passed to internal %FOO functions. We then attempt to
2274 ;;;; transform the %FOO functions into boolean operations when the
2275 ;;;; size and position are constant and the operands are fixnums.
2277 (macrolet (;; Evaluate body with SIZE-VAR and POS-VAR bound to
2278 ;; expressions that evaluate to the SIZE and POSITION of
2279 ;; the byte-specifier form SPEC. We may wrap a let around
2280 ;; the result of the body to bind some variables.
2282 ;; If the spec is a BYTE form, then bind the vars to the
2283 ;; subforms. otherwise, evaluate SPEC and use the BYTE-SIZE
2284 ;; and BYTE-POSITION. The goal of this transformation is to
2285 ;; avoid consing up byte specifiers and then immediately
2286 ;; throwing them away.
2287 (with-byte-specifier ((size-var pos-var spec) &body body)
2288 (once-only ((spec `(macroexpand ,spec))
2290 `(if (and (consp ,spec)
2291 (eq (car ,spec) 'byte)
2292 (= (length ,spec) 3))
2293 (let ((,size-var (second ,spec))
2294 (,pos-var (third ,spec)))
2296 (let ((,size-var `(byte-size ,,temp))
2297 (,pos-var `(byte-position ,,temp)))
2298 `(let ((,,temp ,,spec))
2301 (define-source-transform ldb (spec int)
2302 (with-byte-specifier (size pos spec)
2303 `(%ldb ,size ,pos ,int)))
2305 (define-source-transform dpb (newbyte spec int)
2306 (with-byte-specifier (size pos spec)
2307 `(%dpb ,newbyte ,size ,pos ,int)))
2309 (define-source-transform mask-field (spec int)
2310 (with-byte-specifier (size pos spec)
2311 `(%mask-field ,size ,pos ,int)))
2313 (define-source-transform deposit-field (newbyte spec int)
2314 (with-byte-specifier (size pos spec)
2315 `(%deposit-field ,newbyte ,size ,pos ,int))))
2317 (defoptimizer (%ldb derive-type) ((size posn num))
2318 (let ((size (lvar-type size)))
2319 (if (and (numeric-type-p size)
2320 (csubtypep size (specifier-type 'integer)))
2321 (let ((size-high (numeric-type-high size)))
2322 (if (and size-high (<= size-high sb!vm:n-word-bits))
2323 (specifier-type `(unsigned-byte* ,size-high))
2324 (specifier-type 'unsigned-byte)))
2327 (defoptimizer (%mask-field derive-type) ((size posn num))
2328 (let ((size (lvar-type size))
2329 (posn (lvar-type posn)))
2330 (if (and (numeric-type-p size)
2331 (csubtypep size (specifier-type 'integer))
2332 (numeric-type-p posn)
2333 (csubtypep posn (specifier-type 'integer)))
2334 (let ((size-high (numeric-type-high size))
2335 (posn-high (numeric-type-high posn)))
2336 (if (and size-high posn-high
2337 (<= (+ size-high posn-high) sb!vm:n-word-bits))
2338 (specifier-type `(unsigned-byte* ,(+ size-high posn-high)))
2339 (specifier-type 'unsigned-byte)))
2342 (defun %deposit-field-derive-type-aux (size posn int)
2343 (let ((size (lvar-type size))
2344 (posn (lvar-type posn))
2345 (int (lvar-type int)))
2346 (when (and (numeric-type-p size)
2347 (numeric-type-p posn)
2348 (numeric-type-p int))
2349 (let ((size-high (numeric-type-high size))
2350 (posn-high (numeric-type-high posn))
2351 (high (numeric-type-high int))
2352 (low (numeric-type-low int)))
2353 (when (and size-high posn-high high low
2354 ;; KLUDGE: we need this cutoff here, otherwise we
2355 ;; will merrily derive the type of %DPB as
2356 ;; (UNSIGNED-BYTE 1073741822), and then attempt to
2357 ;; canonicalize this type to (INTEGER 0 (1- (ASH 1
2358 ;; 1073741822))), with hilarious consequences. We
2359 ;; cutoff at 4*SB!VM:N-WORD-BITS to allow inference
2360 ;; over a reasonable amount of shifting, even on
2361 ;; the alpha/32 port, where N-WORD-BITS is 32 but
2362 ;; machine integers are 64-bits. -- CSR,
2364 (<= (+ size-high posn-high) (* 4 sb!vm:n-word-bits)))
2365 (let ((raw-bit-count (max (integer-length high)
2366 (integer-length low)
2367 (+ size-high posn-high))))
2370 `(signed-byte ,(1+ raw-bit-count))
2371 `(unsigned-byte* ,raw-bit-count)))))))))
2373 (defoptimizer (%dpb derive-type) ((newbyte size posn int))
2374 (%deposit-field-derive-type-aux size posn int))
2376 (defoptimizer (%deposit-field derive-type) ((newbyte size posn int))
2377 (%deposit-field-derive-type-aux size posn int))
2379 (deftransform %ldb ((size posn int)
2380 (fixnum fixnum integer)
2381 (unsigned-byte #.sb!vm:n-word-bits))
2382 "convert to inline logical operations"
2383 `(logand (ash int (- posn))
2384 (ash ,(1- (ash 1 sb!vm:n-word-bits))
2385 (- size ,sb!vm:n-word-bits))))
2387 (deftransform %mask-field ((size posn int)
2388 (fixnum fixnum integer)
2389 (unsigned-byte #.sb!vm:n-word-bits))
2390 "convert to inline logical operations"
2392 (ash (ash ,(1- (ash 1 sb!vm:n-word-bits))
2393 (- size ,sb!vm:n-word-bits))
2396 ;;; Note: for %DPB and %DEPOSIT-FIELD, we can't use
2397 ;;; (OR (SIGNED-BYTE N) (UNSIGNED-BYTE N))
2398 ;;; as the result type, as that would allow result types that cover
2399 ;;; the range -2^(n-1) .. 1-2^n, instead of allowing result types of
2400 ;;; (UNSIGNED-BYTE N) and result types of (SIGNED-BYTE N).
2402 (deftransform %dpb ((new size posn int)
2404 (unsigned-byte #.sb!vm:n-word-bits))
2405 "convert to inline logical operations"
2406 `(let ((mask (ldb (byte size 0) -1)))
2407 (logior (ash (logand new mask) posn)
2408 (logand int (lognot (ash mask posn))))))
2410 (deftransform %dpb ((new size posn int)
2412 (signed-byte #.sb!vm:n-word-bits))
2413 "convert to inline logical operations"
2414 `(let ((mask (ldb (byte size 0) -1)))
2415 (logior (ash (logand new mask) posn)
2416 (logand int (lognot (ash mask posn))))))
2418 (deftransform %deposit-field ((new size posn int)
2420 (unsigned-byte #.sb!vm:n-word-bits))
2421 "convert to inline logical operations"
2422 `(let ((mask (ash (ldb (byte size 0) -1) posn)))
2423 (logior (logand new mask)
2424 (logand int (lognot mask)))))
2426 (deftransform %deposit-field ((new size posn int)
2428 (signed-byte #.sb!vm:n-word-bits))
2429 "convert to inline logical operations"
2430 `(let ((mask (ash (ldb (byte size 0) -1) posn)))
2431 (logior (logand new mask)
2432 (logand int (lognot mask)))))
2434 ;;; Modular functions
2436 ;;; (ldb (byte s 0) (foo x y ...)) =
2437 ;;; (ldb (byte s 0) (foo (ldb (byte s 0) x) y ...))
2439 ;;; and similar for other arguments.
2441 ;;; Try to recursively cut all uses of LVAR to WIDTH bits.
2443 ;;; For good functions, we just recursively cut arguments; their
2444 ;;; "goodness" means that the result will not increase (in the
2445 ;;; (unsigned-byte +infinity) sense). An ordinary modular function is
2446 ;;; replaced with the version, cutting its result to WIDTH or more
2447 ;;; bits. If we have changed anything, we need to flush old derived
2448 ;;; types, because they have nothing in common with the new code.
2449 (defun cut-to-width (lvar width)
2450 (declare (type lvar lvar) (type (integer 0) width))
2451 (labels ((reoptimize-node (node name)
2452 (setf (node-derived-type node)
2454 (info :function :type name)))
2455 (setf (lvar-%derived-type (node-lvar node)) nil)
2456 (setf (node-reoptimize node) t)
2457 (setf (block-reoptimize (node-block node)) t)
2458 (setf (component-reoptimize (node-component node)) t))
2459 (cut-node (node &aux did-something)
2460 (when (and (combination-p node)
2461 (fun-info-p (basic-combination-kind node)))
2462 (let* ((fun-ref (lvar-use (combination-fun node)))
2463 (fun-name (leaf-source-name (ref-leaf fun-ref)))
2464 (modular-fun (find-modular-version fun-name width))
2465 (name (and (modular-fun-info-p modular-fun)
2466 (modular-fun-info-name modular-fun))))
2467 (when (and modular-fun
2468 (not (and (eq name 'logand)
2470 (single-value-type (node-derived-type node))
2471 (specifier-type `(unsigned-byte ,width))))))
2472 (unless (eq modular-fun :good)
2473 (setq did-something t)
2476 (find-free-fun name "in a strange place"))
2477 (setf (combination-kind node) :full))
2478 (dolist (arg (basic-combination-args node))
2479 (when (cut-lvar arg)
2480 (setq did-something t)))
2482 (reoptimize-node node fun-name))
2484 (cut-lvar (lvar &aux did-something)
2485 (do-uses (node lvar)
2486 (when (cut-node node)
2487 (setq did-something t)))
2491 (defoptimizer (logand optimizer) ((x y) node)
2492 (let ((result-type (single-value-type (node-derived-type node))))
2493 (when (numeric-type-p result-type)
2494 (let ((low (numeric-type-low result-type))
2495 (high (numeric-type-high result-type)))
2496 (when (and (numberp low)
2499 (let ((width (integer-length high)))
2500 (when (some (lambda (x) (<= width x))
2501 *modular-funs-widths*)
2502 ;; FIXME: This should be (CUT-TO-WIDTH NODE WIDTH).
2503 (cut-to-width x width)
2504 (cut-to-width y width)
2505 nil ; After fixing above, replace with T.
2508 ;;; miscellanous numeric transforms
2510 ;;; If a constant appears as the first arg, swap the args.
2511 (deftransform commutative-arg-swap ((x y) * * :defun-only t :node node)
2512 (if (and (constant-lvar-p x)
2513 (not (constant-lvar-p y)))
2514 `(,(lvar-fun-name (basic-combination-fun node))
2517 (give-up-ir1-transform)))
2519 (dolist (x '(= char= + * logior logand logxor))
2520 (%deftransform x '(function * *) #'commutative-arg-swap
2521 "place constant arg last"))
2523 ;;; Handle the case of a constant BOOLE-CODE.
2524 (deftransform boole ((op x y) * *)
2525 "convert to inline logical operations"
2526 (unless (constant-lvar-p op)
2527 (give-up-ir1-transform "BOOLE code is not a constant."))
2528 (let ((control (lvar-value op)))
2534 (#.boole-c1 '(lognot x))
2535 (#.boole-c2 '(lognot y))
2536 (#.boole-and '(logand x y))
2537 (#.boole-ior '(logior x y))
2538 (#.boole-xor '(logxor x y))
2539 (#.boole-eqv '(logeqv x y))
2540 (#.boole-nand '(lognand x y))
2541 (#.boole-nor '(lognor x y))
2542 (#.boole-andc1 '(logandc1 x y))
2543 (#.boole-andc2 '(logandc2 x y))
2544 (#.boole-orc1 '(logorc1 x y))
2545 (#.boole-orc2 '(logorc2 x y))
2547 (abort-ir1-transform "~S is an illegal control arg to BOOLE."
2550 ;;;; converting special case multiply/divide to shifts
2552 ;;; If arg is a constant power of two, turn * into a shift.
2553 (deftransform * ((x y) (integer integer) *)
2554 "convert x*2^k to shift"
2555 (unless (constant-lvar-p y)
2556 (give-up-ir1-transform))
2557 (let* ((y (lvar-value y))
2559 (len (1- (integer-length y-abs))))
2560 (unless (= y-abs (ash 1 len))
2561 (give-up-ir1-transform))
2566 ;;; If arg is a constant power of two, turn FLOOR into a shift and
2567 ;;; mask. If CEILING, add in (1- (ABS Y)), do FLOOR and correct a
2569 (flet ((frob (y ceil-p)
2570 (unless (constant-lvar-p y)
2571 (give-up-ir1-transform))
2572 (let* ((y (lvar-value y))
2574 (len (1- (integer-length y-abs))))
2575 (unless (= y-abs (ash 1 len))
2576 (give-up-ir1-transform))
2577 (let ((shift (- len))
2579 (delta (if ceil-p (* (signum y) (1- y-abs)) 0)))
2580 `(let ((x (+ x ,delta)))
2582 `(values (ash (- x) ,shift)
2583 (- (- (logand (- x) ,mask)) ,delta))
2584 `(values (ash x ,shift)
2585 (- (logand x ,mask) ,delta))))))))
2586 (deftransform floor ((x y) (integer integer) *)
2587 "convert division by 2^k to shift"
2589 (deftransform ceiling ((x y) (integer integer) *)
2590 "convert division by 2^k to shift"
2593 ;;; Do the same for MOD.
2594 (deftransform mod ((x y) (integer integer) *)
2595 "convert remainder mod 2^k to LOGAND"
2596 (unless (constant-lvar-p y)
2597 (give-up-ir1-transform))
2598 (let* ((y (lvar-value y))
2600 (len (1- (integer-length y-abs))))
2601 (unless (= y-abs (ash 1 len))
2602 (give-up-ir1-transform))
2603 (let ((mask (1- y-abs)))
2605 `(- (logand (- x) ,mask))
2606 `(logand x ,mask)))))
2608 ;;; If arg is a constant power of two, turn TRUNCATE into a shift and mask.
2609 (deftransform truncate ((x y) (integer integer))
2610 "convert division by 2^k to shift"
2611 (unless (constant-lvar-p y)
2612 (give-up-ir1-transform))
2613 (let* ((y (lvar-value y))
2615 (len (1- (integer-length y-abs))))
2616 (unless (= y-abs (ash 1 len))
2617 (give-up-ir1-transform))
2618 (let* ((shift (- len))
2621 (values ,(if (minusp y)
2623 `(- (ash (- x) ,shift)))
2624 (- (logand (- x) ,mask)))
2625 (values ,(if (minusp y)
2626 `(- (ash (- x) ,shift))
2628 (logand x ,mask))))))
2630 ;;; And the same for REM.
2631 (deftransform rem ((x y) (integer integer) *)
2632 "convert remainder mod 2^k to LOGAND"
2633 (unless (constant-lvar-p y)
2634 (give-up-ir1-transform))
2635 (let* ((y (lvar-value y))
2637 (len (1- (integer-length y-abs))))
2638 (unless (= y-abs (ash 1 len))
2639 (give-up-ir1-transform))
2640 (let ((mask (1- y-abs)))
2642 (- (logand (- x) ,mask))
2643 (logand x ,mask)))))
2645 ;;;; arithmetic and logical identity operation elimination
2647 ;;; Flush calls to various arith functions that convert to the
2648 ;;; identity function or a constant.
2649 (macrolet ((def (name identity result)
2650 `(deftransform ,name ((x y) (* (constant-arg (member ,identity))) *)
2651 "fold identity operations"
2658 (def logxor -1 (lognot x))
2661 (deftransform logand ((x y) (* (constant-arg t)) *)
2662 "fold identity operation"
2663 (let ((y (lvar-value y)))
2664 (unless (and (plusp y)
2665 (= y (1- (ash 1 (integer-length y)))))
2666 (give-up-ir1-transform))
2667 (unless (csubtypep (lvar-type x)
2668 (specifier-type `(integer 0 ,y)))
2669 (give-up-ir1-transform))
2672 ;;; These are restricted to rationals, because (- 0 0.0) is 0.0, not -0.0, and
2673 ;;; (* 0 -4.0) is -0.0.
2674 (deftransform - ((x y) ((constant-arg (member 0)) rational) *)
2675 "convert (- 0 x) to negate"
2677 (deftransform * ((x y) (rational (constant-arg (member 0))) *)
2678 "convert (* x 0) to 0"
2681 ;;; Return T if in an arithmetic op including lvars X and Y, the
2682 ;;; result type is not affected by the type of X. That is, Y is at
2683 ;;; least as contagious as X.
2685 (defun not-more-contagious (x y)
2686 (declare (type continuation x y))
2687 (let ((x (lvar-type x))
2689 (values (type= (numeric-contagion x y)
2690 (numeric-contagion y y)))))
2691 ;;; Patched version by Raymond Toy. dtc: Should be safer although it
2692 ;;; XXX needs more work as valid transforms are missed; some cases are
2693 ;;; specific to particular transform functions so the use of this
2694 ;;; function may need a re-think.
2695 (defun not-more-contagious (x y)
2696 (declare (type lvar x y))
2697 (flet ((simple-numeric-type (num)
2698 (and (numeric-type-p num)
2699 ;; Return non-NIL if NUM is integer, rational, or a float
2700 ;; of some type (but not FLOAT)
2701 (case (numeric-type-class num)
2705 (numeric-type-format num))
2708 (let ((x (lvar-type x))
2710 (if (and (simple-numeric-type x)
2711 (simple-numeric-type y))
2712 (values (type= (numeric-contagion x y)
2713 (numeric-contagion y y)))))))
2717 ;;; If y is not constant, not zerop, or is contagious, or a positive
2718 ;;; float +0.0 then give up.
2719 (deftransform + ((x y) (t (constant-arg t)) *)
2721 (let ((val (lvar-value y)))
2722 (unless (and (zerop val)
2723 (not (and (floatp val) (plusp (float-sign val))))
2724 (not-more-contagious y x))
2725 (give-up-ir1-transform)))
2730 ;;; If y is not constant, not zerop, or is contagious, or a negative
2731 ;;; float -0.0 then give up.
2732 (deftransform - ((x y) (t (constant-arg t)) *)
2734 (let ((val (lvar-value y)))
2735 (unless (and (zerop val)
2736 (not (and (floatp val) (minusp (float-sign val))))
2737 (not-more-contagious y x))
2738 (give-up-ir1-transform)))
2741 ;;; Fold (OP x +/-1)
2742 (macrolet ((def (name result minus-result)
2743 `(deftransform ,name ((x y) (t (constant-arg real)) *)
2744 "fold identity operations"
2745 (let ((val (lvar-value y)))
2746 (unless (and (= (abs val) 1)
2747 (not-more-contagious y x))
2748 (give-up-ir1-transform))
2749 (if (minusp val) ',minus-result ',result)))))
2750 (def * x (%negate x))
2751 (def / x (%negate x))
2752 (def expt x (/ 1 x)))
2754 ;;; Fold (expt x n) into multiplications for small integral values of
2755 ;;; N; convert (expt x 1/2) to sqrt.
2756 (deftransform expt ((x y) (t (constant-arg real)) *)
2757 "recode as multiplication or sqrt"
2758 (let ((val (lvar-value y)))
2759 ;; If Y would cause the result to be promoted to the same type as
2760 ;; Y, we give up. If not, then the result will be the same type
2761 ;; as X, so we can replace the exponentiation with simple
2762 ;; multiplication and division for small integral powers.
2763 (unless (not-more-contagious y x)
2764 (give-up-ir1-transform))
2766 (let ((x-type (lvar-type x)))
2767 (cond ((csubtypep x-type (specifier-type '(or rational
2768 (complex rational))))
2770 ((csubtypep x-type (specifier-type 'real))
2774 ((csubtypep x-type (specifier-type 'complex))
2775 ;; both parts are float
2777 (t (give-up-ir1-transform)))))
2778 ((= val 2) '(* x x))
2779 ((= val -2) '(/ (* x x)))
2780 ((= val 3) '(* x x x))
2781 ((= val -3) '(/ (* x x x)))
2782 ((= val 1/2) '(sqrt x))
2783 ((= val -1/2) '(/ (sqrt x)))
2784 (t (give-up-ir1-transform)))))
2786 ;;; KLUDGE: Shouldn't (/ 0.0 0.0), etc. cause exceptions in these
2787 ;;; transformations?
2788 ;;; Perhaps we should have to prove that the denominator is nonzero before
2789 ;;; doing them? -- WHN 19990917
2790 (macrolet ((def (name)
2791 `(deftransform ,name ((x y) ((constant-arg (integer 0 0)) integer)
2798 (macrolet ((def (name)
2799 `(deftransform ,name ((x y) ((constant-arg (integer 0 0)) integer)
2808 ;;;; character operations
2810 (deftransform char-equal ((a b) (base-char base-char))
2812 '(let* ((ac (char-code a))
2814 (sum (logxor ac bc)))
2816 (when (eql sum #x20)
2817 (let ((sum (+ ac bc)))
2818 (and (> sum 161) (< sum 213)))))))
2820 (deftransform char-upcase ((x) (base-char))
2822 '(let ((n-code (char-code x)))
2823 (if (and (> n-code #o140) ; Octal 141 is #\a.
2824 (< n-code #o173)) ; Octal 172 is #\z.
2825 (code-char (logxor #x20 n-code))
2828 (deftransform char-downcase ((x) (base-char))
2830 '(let ((n-code (char-code x)))
2831 (if (and (> n-code 64) ; 65 is #\A.
2832 (< n-code 91)) ; 90 is #\Z.
2833 (code-char (logxor #x20 n-code))
2836 ;;;; equality predicate transforms
2838 ;;; Return true if X and Y are lvars whose only use is a
2839 ;;; reference to the same leaf, and the value of the leaf cannot
2841 (defun same-leaf-ref-p (x y)
2842 (declare (type lvar x y))
2843 (let ((x-use (principal-lvar-use x))
2844 (y-use (principal-lvar-use y)))
2847 (eq (ref-leaf x-use) (ref-leaf y-use))
2848 (constant-reference-p x-use))))
2850 ;;; If X and Y are the same leaf, then the result is true. Otherwise,
2851 ;;; if there is no intersection between the types of the arguments,
2852 ;;; then the result is definitely false.
2853 (deftransform simple-equality-transform ((x y) * *
2855 (cond ((same-leaf-ref-p x y)
2857 ((not (types-equal-or-intersect (lvar-type x)
2861 (give-up-ir1-transform))))
2864 `(%deftransform ',x '(function * *) #'simple-equality-transform)))
2869 ;;; This is similar to SIMPLE-EQUALITY-PREDICATE, except that we also
2870 ;;; try to convert to a type-specific predicate or EQ:
2871 ;;; -- If both args are characters, convert to CHAR=. This is better than
2872 ;;; just converting to EQ, since CHAR= may have special compilation
2873 ;;; strategies for non-standard representations, etc.
2874 ;;; -- If either arg is definitely not a number, then we can compare
2876 ;;; -- Otherwise, we try to put the arg we know more about second. If X
2877 ;;; is constant then we put it second. If X is a subtype of Y, we put
2878 ;;; it second. These rules make it easier for the back end to match
2879 ;;; these interesting cases.
2880 ;;; -- If Y is a fixnum, then we quietly pass because the back end can
2881 ;;; handle that case, otherwise give an efficiency note.
2882 (deftransform eql ((x y) * *)
2883 "convert to simpler equality predicate"
2884 (let ((x-type (lvar-type x))
2885 (y-type (lvar-type y))
2886 (char-type (specifier-type 'character))
2887 (number-type (specifier-type 'number)))
2888 (cond ((same-leaf-ref-p x y)
2890 ((not (types-equal-or-intersect x-type y-type))
2892 ((and (csubtypep x-type char-type)
2893 (csubtypep y-type char-type))
2895 ((or (not (types-equal-or-intersect x-type number-type))
2896 (not (types-equal-or-intersect y-type number-type)))
2898 ((and (not (constant-lvar-p y))
2899 (or (constant-lvar-p x)
2900 (and (csubtypep x-type y-type)
2901 (not (csubtypep y-type x-type)))))
2904 (give-up-ir1-transform)))))
2906 ;;; Convert to EQL if both args are rational and complexp is specified
2907 ;;; and the same for both.
2908 (deftransform = ((x y) * *)
2910 (let ((x-type (lvar-type x))
2911 (y-type (lvar-type y)))
2912 (if (and (csubtypep x-type (specifier-type 'number))
2913 (csubtypep y-type (specifier-type 'number)))
2914 (cond ((or (and (csubtypep x-type (specifier-type 'float))
2915 (csubtypep y-type (specifier-type 'float)))
2916 (and (csubtypep x-type (specifier-type '(complex float)))
2917 (csubtypep y-type (specifier-type '(complex float)))))
2918 ;; They are both floats. Leave as = so that -0.0 is
2919 ;; handled correctly.
2920 (give-up-ir1-transform))
2921 ((or (and (csubtypep x-type (specifier-type 'rational))
2922 (csubtypep y-type (specifier-type 'rational)))
2923 (and (csubtypep x-type
2924 (specifier-type '(complex rational)))
2926 (specifier-type '(complex rational)))))
2927 ;; They are both rationals and complexp is the same.
2931 (give-up-ir1-transform
2932 "The operands might not be the same type.")))
2933 (give-up-ir1-transform
2934 "The operands might not be the same type."))))
2936 ;;; If LVAR's type is a numeric type, then return the type, otherwise
2937 ;;; GIVE-UP-IR1-TRANSFORM.
2938 (defun numeric-type-or-lose (lvar)
2939 (declare (type lvar lvar))
2940 (let ((res (lvar-type lvar)))
2941 (unless (numeric-type-p res) (give-up-ir1-transform))
2944 ;;; See whether we can statically determine (< X Y) using type
2945 ;;; information. If X's high bound is < Y's low, then X < Y.
2946 ;;; Similarly, if X's low is >= to Y's high, the X >= Y (so return
2947 ;;; NIL). If not, at least make sure any constant arg is second.
2949 ;;; FIXME: Why should constant argument be second? It would be nice to
2950 ;;; find out and explain.
2951 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2952 (defun ir1-transform-< (x y first second inverse)
2953 (if (same-leaf-ref-p x y)
2955 (let* ((x-type (numeric-type-or-lose x))
2956 (x-lo (numeric-type-low x-type))
2957 (x-hi (numeric-type-high x-type))
2958 (y-type (numeric-type-or-lose y))
2959 (y-lo (numeric-type-low y-type))
2960 (y-hi (numeric-type-high y-type)))
2961 (cond ((and x-hi y-lo (< x-hi y-lo))
2963 ((and y-hi x-lo (>= x-lo y-hi))
2965 ((and (constant-lvar-p first)
2966 (not (constant-lvar-p second)))
2969 (give-up-ir1-transform))))))
2970 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2971 (defun ir1-transform-< (x y first second inverse)
2972 (if (same-leaf-ref-p x y)
2974 (let ((xi (numeric-type->interval (numeric-type-or-lose x)))
2975 (yi (numeric-type->interval (numeric-type-or-lose y))))
2976 (cond ((interval-< xi yi)
2978 ((interval->= xi yi)
2980 ((and (constant-lvar-p first)
2981 (not (constant-lvar-p second)))
2984 (give-up-ir1-transform))))))
2986 (deftransform < ((x y) (integer integer) *)
2987 (ir1-transform-< x y x y '>))
2989 (deftransform > ((x y) (integer integer) *)
2990 (ir1-transform-< y x x y '<))
2992 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2993 (deftransform < ((x y) (float float) *)
2994 (ir1-transform-< x y x y '>))
2996 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2997 (deftransform > ((x y) (float float) *)
2998 (ir1-transform-< y x x y '<))
3000 (defun ir1-transform-char< (x y first second inverse)
3002 ((same-leaf-ref-p x y) nil)
3003 ;; If we had interval representation of character types, as we
3004 ;; might eventually have to to support 2^21 characters, then here
3005 ;; we could do some compile-time computation as in IR1-TRANSFORM-<
3006 ;; above. -- CSR, 2003-07-01
3007 ((and (constant-lvar-p first)
3008 (not (constant-lvar-p second)))
3010 (t (give-up-ir1-transform))))
3012 (deftransform char< ((x y) (character character) *)
3013 (ir1-transform-char< x y x y 'char>))
3015 (deftransform char> ((x y) (character character) *)
3016 (ir1-transform-char< y x x y 'char<))
3018 ;;;; converting N-arg comparisons
3020 ;;;; We convert calls to N-arg comparison functions such as < into
3021 ;;;; two-arg calls. This transformation is enabled for all such
3022 ;;;; comparisons in this file. If any of these predicates are not
3023 ;;;; open-coded, then the transformation should be removed at some
3024 ;;;; point to avoid pessimization.
3026 ;;; This function is used for source transformation of N-arg
3027 ;;; comparison functions other than inequality. We deal both with
3028 ;;; converting to two-arg calls and inverting the sense of the test,
3029 ;;; if necessary. If the call has two args, then we pass or return a
3030 ;;; negated test as appropriate. If it is a degenerate one-arg call,
3031 ;;; then we transform to code that returns true. Otherwise, we bind
3032 ;;; all the arguments and expand into a bunch of IFs.
3033 (declaim (ftype (function (symbol list boolean t) *) multi-compare))
3034 (defun multi-compare (predicate args not-p type)
3035 (let ((nargs (length args)))
3036 (cond ((< nargs 1) (values nil t))
3037 ((= nargs 1) `(progn (the ,type ,@args) t))
3040 `(if (,predicate ,(first args) ,(second args)) nil t)
3043 (do* ((i (1- nargs) (1- i))
3045 (current (gensym) (gensym))
3046 (vars (list current) (cons current vars))
3048 `(if (,predicate ,current ,last)
3050 `(if (,predicate ,current ,last)
3053 `((lambda ,vars (declare (type ,type ,@vars)) ,result)
3056 (define-source-transform = (&rest args) (multi-compare '= args nil 'number))
3057 (define-source-transform < (&rest args) (multi-compare '< args nil 'real))
3058 (define-source-transform > (&rest args) (multi-compare '> args nil 'real))
3059 (define-source-transform <= (&rest args) (multi-compare '> args t 'real))
3060 (define-source-transform >= (&rest args) (multi-compare '< args t 'real))
3062 (define-source-transform char= (&rest args) (multi-compare 'char= args nil
3064 (define-source-transform char< (&rest args) (multi-compare 'char< args nil
3066 (define-source-transform char> (&rest args) (multi-compare 'char> args nil
3068 (define-source-transform char<= (&rest args) (multi-compare 'char> args t
3070 (define-source-transform char>= (&rest args) (multi-compare 'char< args t
3073 (define-source-transform char-equal (&rest args)
3074 (multi-compare 'char-equal args nil 'character))
3075 (define-source-transform char-lessp (&rest args)
3076 (multi-compare 'char-lessp args nil 'character))
3077 (define-source-transform char-greaterp (&rest args)
3078 (multi-compare 'char-greaterp args nil 'character))
3079 (define-source-transform char-not-greaterp (&rest args)
3080 (multi-compare 'char-greaterp args t 'character))
3081 (define-source-transform char-not-lessp (&rest args)
3082 (multi-compare 'char-lessp args t 'character))
3084 ;;; This function does source transformation of N-arg inequality
3085 ;;; functions such as /=. This is similar to MULTI-COMPARE in the <3
3086 ;;; arg cases. If there are more than two args, then we expand into
3087 ;;; the appropriate n^2 comparisons only when speed is important.
3088 (declaim (ftype (function (symbol list t) *) multi-not-equal))
3089 (defun multi-not-equal (predicate args type)
3090 (let ((nargs (length args)))
3091 (cond ((< nargs 1) (values nil t))
3092 ((= nargs 1) `(progn (the ,type ,@args) t))
3094 `(if (,predicate ,(first args) ,(second args)) nil t))
3095 ((not (policy *lexenv*
3096 (and (>= speed space)
3097 (>= speed compilation-speed))))
3100 (let ((vars (make-gensym-list nargs)))
3101 (do ((var vars next)
3102 (next (cdr vars) (cdr next))
3105 `((lambda ,vars (declare (type ,type ,@vars)) ,result)
3107 (let ((v1 (first var)))
3109 (setq result `(if (,predicate ,v1 ,v2) nil ,result))))))))))
3111 (define-source-transform /= (&rest args)
3112 (multi-not-equal '= args 'number))
3113 (define-source-transform char/= (&rest args)
3114 (multi-not-equal 'char= args 'character))
3115 (define-source-transform char-not-equal (&rest args)
3116 (multi-not-equal 'char-equal args 'character))
3118 ;;; Expand MAX and MIN into the obvious comparisons.
3119 (define-source-transform max (arg0 &rest rest)
3120 (once-only ((arg0 arg0))
3122 `(values (the real ,arg0))
3123 `(let ((maxrest (max ,@rest)))
3124 (if (> ,arg0 maxrest) ,arg0 maxrest)))))
3125 (define-source-transform min (arg0 &rest rest)
3126 (once-only ((arg0 arg0))
3128 `(values (the real ,arg0))
3129 `(let ((minrest (min ,@rest)))
3130 (if (< ,arg0 minrest) ,arg0 minrest)))))
3132 ;;;; converting N-arg arithmetic functions
3134 ;;;; N-arg arithmetic and logic functions are associated into two-arg
3135 ;;;; versions, and degenerate cases are flushed.
3137 ;;; Left-associate FIRST-ARG and MORE-ARGS using FUNCTION.
3138 (declaim (ftype (function (symbol t list) list) associate-args))
3139 (defun associate-args (function first-arg more-args)
3140 (let ((next (rest more-args))
3141 (arg (first more-args)))
3143 `(,function ,first-arg ,arg)
3144 (associate-args function `(,function ,first-arg ,arg) next))))
3146 ;;; Do source transformations for transitive functions such as +.
3147 ;;; One-arg cases are replaced with the arg and zero arg cases with
3148 ;;; the identity. ONE-ARG-RESULT-TYPE is, if non-NIL, the type to
3149 ;;; ensure (with THE) that the argument in one-argument calls is.
3150 (defun source-transform-transitive (fun args identity
3151 &optional one-arg-result-type)
3152 (declare (symbol fun) (list args))
3155 (1 (if one-arg-result-type
3156 `(values (the ,one-arg-result-type ,(first args)))
3157 `(values ,(first args))))
3160 (associate-args fun (first args) (rest args)))))
3162 (define-source-transform + (&rest args)
3163 (source-transform-transitive '+ args 0 'number))
3164 (define-source-transform * (&rest args)
3165 (source-transform-transitive '* args 1 'number))
3166 (define-source-transform logior (&rest args)
3167 (source-transform-transitive 'logior args 0 'integer))
3168 (define-source-transform logxor (&rest args)
3169 (source-transform-transitive 'logxor args 0 'integer))
3170 (define-source-transform logand (&rest args)
3171 (source-transform-transitive 'logand args -1 'integer))
3172 (define-source-transform logeqv (&rest args)
3173 (source-transform-transitive 'logeqv args -1 'integer))
3175 ;;; Note: we can't use SOURCE-TRANSFORM-TRANSITIVE for GCD and LCM
3176 ;;; because when they are given one argument, they return its absolute
3179 (define-source-transform gcd (&rest args)
3182 (1 `(abs (the integer ,(first args))))
3184 (t (associate-args 'gcd (first args) (rest args)))))
3186 (define-source-transform lcm (&rest args)
3189 (1 `(abs (the integer ,(first args))))
3191 (t (associate-args 'lcm (first args) (rest args)))))
3193 ;;; Do source transformations for intransitive n-arg functions such as
3194 ;;; /. With one arg, we form the inverse. With two args we pass.
3195 ;;; Otherwise we associate into two-arg calls.
3196 (declaim (ftype (function (symbol list t)
3197 (values list &optional (member nil t)))
3198 source-transform-intransitive))
3199 (defun source-transform-intransitive (function args inverse)
3201 ((0 2) (values nil t))
3202 (1 `(,@inverse ,(first args)))
3203 (t (associate-args function (first args) (rest args)))))
3205 (define-source-transform - (&rest args)
3206 (source-transform-intransitive '- args '(%negate)))
3207 (define-source-transform / (&rest args)
3208 (source-transform-intransitive '/ args '(/ 1)))
3210 ;;;; transforming APPLY
3212 ;;; We convert APPLY into MULTIPLE-VALUE-CALL so that the compiler
3213 ;;; only needs to understand one kind of variable-argument call. It is
3214 ;;; more efficient to convert APPLY to MV-CALL than MV-CALL to APPLY.
3215 (define-source-transform apply (fun arg &rest more-args)
3216 (let ((args (cons arg more-args)))
3217 `(multiple-value-call ,fun
3218 ,@(mapcar (lambda (x)
3221 (values-list ,(car (last args))))))
3223 ;;;; transforming FORMAT
3225 ;;;; If the control string is a compile-time constant, then replace it
3226 ;;;; with a use of the FORMATTER macro so that the control string is
3227 ;;;; ``compiled.'' Furthermore, if the destination is either a stream
3228 ;;;; or T and the control string is a function (i.e. FORMATTER), then
3229 ;;;; convert the call to FORMAT to just a FUNCALL of that function.
3231 ;;; for compile-time argument count checking.
3233 ;;; FIXME I: this is currently called from DEFTRANSFORMs, the vast
3234 ;;; majority of which are not going to transform the code, but instead
3235 ;;; are going to GIVE-UP-IR1-TRANSFORM unconditionally. It would be
3236 ;;; nice to make this explicit, maybe by implementing a new
3237 ;;; "optimizer" (say, DEFOPTIMIZER CONSISTENCY-CHECK).
3239 ;;; FIXME II: In some cases, type information could be correlated; for
3240 ;;; instance, ~{ ... ~} requires a list argument, so if the lvar-type
3241 ;;; of a corresponding argument is known and does not intersect the
3242 ;;; list type, a warning could be signalled.
3243 (defun check-format-args (string args fun)
3244 (declare (type string string))
3245 (unless (typep string 'simple-string)
3246 (setq string (coerce string 'simple-string)))
3247 (multiple-value-bind (min max)
3248 (handler-case (sb!format:%compiler-walk-format-string string args)
3249 (sb!format:format-error (c)
3250 (compiler-warn "~A" c)))
3252 (let ((nargs (length args)))
3255 (compiler-warn "Too few arguments (~D) to ~S ~S: ~
3256 requires at least ~D."
3257 nargs fun string min))
3259 (;; to get warned about probably bogus code at
3260 ;; cross-compile time.
3261 #+sb-xc-host compiler-warn
3262 ;; ANSI saith that too many arguments doesn't cause a
3264 #-sb-xc-host compiler-style-warn
3265 "Too many arguments (~D) to ~S ~S: uses at most ~D."
3266 nargs fun string max)))))))
3268 (defoptimizer (format optimizer) ((dest control &rest args))
3269 (when (constant-lvar-p control)
3270 (let ((x (lvar-value control)))
3272 (check-format-args x args 'format)))))
3274 (deftransform format ((dest control &rest args) (t simple-string &rest t) *
3275 :policy (> speed space))
3276 (unless (constant-lvar-p control)
3277 (give-up-ir1-transform "The control string is not a constant."))
3278 (let ((arg-names (make-gensym-list (length args))))
3279 `(lambda (dest control ,@arg-names)
3280 (declare (ignore control))
3281 (format dest (formatter ,(lvar-value control)) ,@arg-names))))
3283 (deftransform format ((stream control &rest args) (stream function &rest t) *
3284 :policy (> speed space))
3285 (let ((arg-names (make-gensym-list (length args))))
3286 `(lambda (stream control ,@arg-names)
3287 (funcall control stream ,@arg-names)
3290 (deftransform format ((tee control &rest args) ((member t) function &rest t) *
3291 :policy (> speed space))
3292 (let ((arg-names (make-gensym-list (length args))))
3293 `(lambda (tee control ,@arg-names)
3294 (declare (ignore tee))
3295 (funcall control *standard-output* ,@arg-names)
3300 `(defoptimizer (,name optimizer) ((control &rest args))
3301 (when (constant-lvar-p control)
3302 (let ((x (lvar-value control)))
3304 (check-format-args x args ',name)))))))
3307 #+sb-xc-host ; Only we should be using these
3310 (def compiler-abort)
3311 (def compiler-error)
3313 (def compiler-style-warn)
3314 (def compiler-notify)
3315 (def maybe-compiler-notify)
3318 (defoptimizer (cerror optimizer) ((report control &rest args))
3319 (when (and (constant-lvar-p control)
3320 (constant-lvar-p report))
3321 (let ((x (lvar-value control))
3322 (y (lvar-value report)))
3323 (when (and (stringp x) (stringp y))
3324 (multiple-value-bind (min1 max1)
3326 (sb!format:%compiler-walk-format-string x args)
3327 (sb!format:format-error (c)
3328 (compiler-warn "~A" c)))
3330 (multiple-value-bind (min2 max2)
3332 (sb!format:%compiler-walk-format-string y args)
3333 (sb!format:format-error (c)
3334 (compiler-warn "~A" c)))
3336 (let ((nargs (length args)))
3338 ((< nargs (min min1 min2))
3339 (compiler-warn "Too few arguments (~D) to ~S ~S ~S: ~
3340 requires at least ~D."
3341 nargs 'cerror y x (min min1 min2)))
3342 ((> nargs (max max1 max2))
3343 (;; to get warned about probably bogus code at
3344 ;; cross-compile time.
3345 #+sb-xc-host compiler-warn
3346 ;; ANSI saith that too many arguments doesn't cause a
3348 #-sb-xc-host compiler-style-warn
3349 "Too many arguments (~D) to ~S ~S ~S: uses at most ~D."
3350 nargs 'cerror y x (max max1 max2)))))))))))))
3352 (defoptimizer (coerce derive-type) ((value type))
3354 ((constant-lvar-p type)
3355 ;; This branch is essentially (RESULT-TYPE-SPECIFIER-NTH-ARG 2),
3356 ;; but dealing with the niggle that complex canonicalization gets
3357 ;; in the way: (COERCE 1 'COMPLEX) returns 1, which is not of
3359 (let* ((specifier (lvar-value type))
3360 (result-typeoid (careful-specifier-type specifier)))
3362 ((null result-typeoid) nil)
3363 ((csubtypep result-typeoid (specifier-type 'number))
3364 ;; the difficult case: we have to cope with ANSI 12.1.5.3
3365 ;; Rule of Canonical Representation for Complex Rationals,
3366 ;; which is a truly nasty delivery to field.
3368 ((csubtypep result-typeoid (specifier-type 'real))
3369 ;; cleverness required here: it would be nice to deduce
3370 ;; that something of type (INTEGER 2 3) coerced to type
3371 ;; DOUBLE-FLOAT should return (DOUBLE-FLOAT 2.0d0 3.0d0).
3372 ;; FLOAT gets its own clause because it's implemented as
3373 ;; a UNION-TYPE, so we don't catch it in the NUMERIC-TYPE
3376 ((and (numeric-type-p result-typeoid)
3377 (eq (numeric-type-complexp result-typeoid) :real))
3378 ;; FIXME: is this clause (a) necessary or (b) useful?
3380 ((or (csubtypep result-typeoid
3381 (specifier-type '(complex single-float)))
3382 (csubtypep result-typeoid
3383 (specifier-type '(complex double-float)))
3385 (csubtypep result-typeoid
3386 (specifier-type '(complex long-float))))
3387 ;; float complex types are never canonicalized.
3390 ;; if it's not a REAL, or a COMPLEX FLOAToid, it's
3391 ;; probably just a COMPLEX or equivalent. So, in that
3392 ;; case, we will return a complex or an object of the
3393 ;; provided type if it's rational:
3394 (type-union result-typeoid
3395 (type-intersection (lvar-type value)
3396 (specifier-type 'rational))))))
3397 (t result-typeoid))))
3399 ;; OK, the result-type argument isn't constant. However, there
3400 ;; are common uses where we can still do better than just
3401 ;; *UNIVERSAL-TYPE*: e.g. (COERCE X (ARRAY-ELEMENT-TYPE Y)),
3402 ;; where Y is of a known type. See messages on cmucl-imp
3403 ;; 2001-02-14 and sbcl-devel 2002-12-12. We only worry here
3404 ;; about types that can be returned by (ARRAY-ELEMENT-TYPE Y), on
3405 ;; the basis that it's unlikely that other uses are both
3406 ;; time-critical and get to this branch of the COND (non-constant
3407 ;; second argument to COERCE). -- CSR, 2002-12-16
3408 (let ((value-type (lvar-type value))
3409 (type-type (lvar-type type)))
3411 ((good-cons-type-p (cons-type)
3412 ;; Make sure the cons-type we're looking at is something
3413 ;; we're prepared to handle which is basically something
3414 ;; that array-element-type can return.
3415 (or (and (member-type-p cons-type)
3416 (null (rest (member-type-members cons-type)))
3417 (null (first (member-type-members cons-type))))
3418 (let ((car-type (cons-type-car-type cons-type)))
3419 (and (member-type-p car-type)
3420 (null (rest (member-type-members car-type)))
3421 (or (symbolp (first (member-type-members car-type)))
3422 (numberp (first (member-type-members car-type)))
3423 (and (listp (first (member-type-members
3425 (numberp (first (first (member-type-members
3427 (good-cons-type-p (cons-type-cdr-type cons-type))))))
3428 (unconsify-type (good-cons-type)
3429 ;; Convert the "printed" respresentation of a cons
3430 ;; specifier into a type specifier. That is, the
3431 ;; specifier (CONS (EQL SIGNED-BYTE) (CONS (EQL 16)
3432 ;; NULL)) is converted to (SIGNED-BYTE 16).
3433 (cond ((or (null good-cons-type)
3434 (eq good-cons-type 'null))
3436 ((and (eq (first good-cons-type) 'cons)
3437 (eq (first (second good-cons-type)) 'member))
3438 `(,(second (second good-cons-type))
3439 ,@(unconsify-type (caddr good-cons-type))))))
3440 (coerceable-p (c-type)
3441 ;; Can the value be coerced to the given type? Coerce is
3442 ;; complicated, so we don't handle every possible case
3443 ;; here---just the most common and easiest cases:
3445 ;; * Any REAL can be coerced to a FLOAT type.
3446 ;; * Any NUMBER can be coerced to a (COMPLEX
3447 ;; SINGLE/DOUBLE-FLOAT).
3449 ;; FIXME I: we should also be able to deal with characters
3452 ;; FIXME II: I'm not sure that anything is necessary
3453 ;; here, at least while COMPLEX is not a specialized
3454 ;; array element type in the system. Reasoning: if
3455 ;; something cannot be coerced to the requested type, an
3456 ;; error will be raised (and so any downstream compiled
3457 ;; code on the assumption of the returned type is
3458 ;; unreachable). If something can, then it will be of
3459 ;; the requested type, because (by assumption) COMPLEX
3460 ;; (and other difficult types like (COMPLEX INTEGER)
3461 ;; aren't specialized types.
3462 (let ((coerced-type c-type))
3463 (or (and (subtypep coerced-type 'float)
3464 (csubtypep value-type (specifier-type 'real)))
3465 (and (subtypep coerced-type
3466 '(or (complex single-float)
3467 (complex double-float)))
3468 (csubtypep value-type (specifier-type 'number))))))
3469 (process-types (type)
3470 ;; FIXME: This needs some work because we should be able
3471 ;; to derive the resulting type better than just the
3472 ;; type arg of coerce. That is, if X is (INTEGER 10
3473 ;; 20), then (COERCE X 'DOUBLE-FLOAT) should say
3474 ;; (DOUBLE-FLOAT 10d0 20d0) instead of just
3476 (cond ((member-type-p type)
3477 (let ((members (member-type-members type)))
3478 (if (every #'coerceable-p members)
3479 (specifier-type `(or ,@members))
3481 ((and (cons-type-p type)
3482 (good-cons-type-p type))
3483 (let ((c-type (unconsify-type (type-specifier type))))
3484 (if (coerceable-p c-type)
3485 (specifier-type c-type)
3488 *universal-type*))))
3489 (cond ((union-type-p type-type)
3490 (apply #'type-union (mapcar #'process-types
3491 (union-type-types type-type))))
3492 ((or (member-type-p type-type)
3493 (cons-type-p type-type))
3494 (process-types type-type))
3496 *universal-type*)))))))
3498 (defoptimizer (compile derive-type) ((nameoid function))
3499 (when (csubtypep (lvar-type nameoid)
3500 (specifier-type 'null))
3501 (values-specifier-type '(values function boolean boolean))))
3503 ;;; FIXME: Maybe also STREAM-ELEMENT-TYPE should be given some loving
3504 ;;; treatment along these lines? (See discussion in COERCE DERIVE-TYPE
3505 ;;; optimizer, above).
3506 (defoptimizer (array-element-type derive-type) ((array))
3507 (let ((array-type (lvar-type array)))
3508 (labels ((consify (list)
3511 `(cons (eql ,(car list)) ,(consify (rest list)))))
3512 (get-element-type (a)
3514 (type-specifier (array-type-specialized-element-type a))))
3515 (cond ((eq element-type '*)
3516 (specifier-type 'type-specifier))
3517 ((symbolp element-type)
3518 (make-member-type :members (list element-type)))
3519 ((consp element-type)
3520 (specifier-type (consify element-type)))
3522 (error "can't understand type ~S~%" element-type))))))
3523 (cond ((array-type-p array-type)
3524 (get-element-type array-type))
3525 ((union-type-p array-type)
3527 (mapcar #'get-element-type (union-type-types array-type))))
3529 *universal-type*)))))
3531 (define-source-transform sb!impl::sort-vector (vector start end predicate key)
3532 `(macrolet ((%index (x) `(truly-the index ,x))
3533 (%parent (i) `(ash ,i -1))
3534 (%left (i) `(%index (ash ,i 1)))
3535 (%right (i) `(%index (1+ (ash ,i 1))))
3538 (left (%left i) (%left i)))
3539 ((> left current-heap-size))
3540 (declare (type index i left))
3541 (let* ((i-elt (%elt i))
3542 (i-key (funcall keyfun i-elt))
3543 (left-elt (%elt left))
3544 (left-key (funcall keyfun left-elt)))
3545 (multiple-value-bind (large large-elt large-key)
3546 (if (funcall ,',predicate i-key left-key)
3547 (values left left-elt left-key)
3548 (values i i-elt i-key))
3549 (let ((right (%right i)))
3550 (multiple-value-bind (largest largest-elt)
3551 (if (> right current-heap-size)
3552 (values large large-elt)
3553 (let* ((right-elt (%elt right))
3554 (right-key (funcall keyfun right-elt)))
3555 (if (funcall ,',predicate large-key right-key)
3556 (values right right-elt)
3557 (values large large-elt))))
3558 (cond ((= largest i)
3561 (setf (%elt i) largest-elt
3562 (%elt largest) i-elt
3564 (%sort-vector (keyfun &optional (vtype 'vector))
3565 `(macrolet (;; KLUDGE: In SBCL ca. 0.6.10, I had trouble getting
3566 ;; type inference to propagate all the way
3567 ;; through this tangled mess of
3568 ;; inlining. The TRULY-THE here works
3569 ;; around that. -- WHN
3571 `(aref (truly-the ,',vtype ,',',vector)
3572 (%index (+ (%index ,i) start-1)))))
3573 (let ((start-1 (1- ,',start)) ; Heaps prefer 1-based addressing.
3574 (current-heap-size (- ,',end ,',start))
3576 (declare (type (integer -1 #.(1- most-positive-fixnum))
3578 (declare (type index current-heap-size))
3579 (declare (type function keyfun))
3580 (loop for i of-type index
3581 from (ash current-heap-size -1) downto 1 do
3584 (when (< current-heap-size 2)
3586 (rotatef (%elt 1) (%elt current-heap-size))
3587 (decf current-heap-size)
3589 (if (typep ,vector 'simple-vector)
3590 ;; (VECTOR T) is worth optimizing for, and SIMPLE-VECTOR is
3591 ;; what we get from (VECTOR T) inside WITH-ARRAY-DATA.
3593 ;; Special-casing the KEY=NIL case lets us avoid some
3595 (%sort-vector #'identity simple-vector)
3596 (%sort-vector ,key simple-vector))
3597 ;; It's hard to anticipate many speed-critical applications for
3598 ;; sorting vector types other than (VECTOR T), so we just lump
3599 ;; them all together in one slow dynamically typed mess.
3601 (declare (optimize (speed 2) (space 2) (inhibit-warnings 3)))
3602 (%sort-vector (or ,key #'identity))))))
3604 ;;;; debuggers' little helpers
3606 ;;; for debugging when transforms are behaving mysteriously,
3607 ;;; e.g. when debugging a problem with an ASH transform
3608 ;;; (defun foo (&optional s)
3609 ;;; (sb-c::/report-lvar s "S outside WHEN")
3610 ;;; (when (and (integerp s) (> s 3))
3611 ;;; (sb-c::/report-lvar s "S inside WHEN")
3612 ;;; (let ((bound (ash 1 (1- s))))
3613 ;;; (sb-c::/report-lvar bound "BOUND")
3614 ;;; (let ((x (- bound))
3616 ;;; (sb-c::/report-lvar x "X")
3617 ;;; (sb-c::/report-lvar x "Y"))
3618 ;;; `(integer ,(- bound) ,(1- bound)))))
3619 ;;; (The DEFTRANSFORM doesn't do anything but report at compile time,
3620 ;;; and the function doesn't do anything at all.)
3623 (defknown /report-lvar (t t) null)
3624 (deftransform /report-lvar ((x message) (t t))
3625 (format t "~%/in /REPORT-LVAR~%")
3626 (format t "/(LVAR-TYPE X)=~S~%" (lvar-type x))
3627 (when (constant-lvar-p x)
3628 (format t "/(LVAR-VALUE X)=~S~%" (lvar-value x)))
3629 (format t "/MESSAGE=~S~%" (lvar-value message))
3630 (give-up-ir1-transform "not a real transform"))
3631 (defun /report-lvar (x message)
3632 (declare (ignore x message))))