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 (continuation-type fun))
49 ((and min (eql min max))
50 (let ((dums (make-gensym-list min)))
51 `#'(lambda ,dums (not (funcall fun ,@dums)))))
52 ((let* ((cont (node-cont node))
53 (dest (continuation-dest cont)))
54 (and (combination-p dest)
55 (eq (combination-fun dest) cont)))
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-continuation-p n)
133 (give-up-ir1-transform))
134 (let ((n (continuation-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 lognand (x y) `(lognot (logand ,x ,y)))
176 (define-source-transform lognor (x y) `(lognot (logior ,x ,y)))
177 (define-source-transform logandc1 (x y) `(logand (lognot ,x) ,y))
178 (define-source-transform logandc2 (x y) `(logand ,x (lognot ,y)))
179 (define-source-transform logorc1 (x y) `(logior (lognot ,x) ,y))
180 (define-source-transform logorc2 (x y) `(logior ,x (lognot ,y)))
181 (define-source-transform logtest (x y) `(not (zerop (logand ,x ,y))))
183 (deftransform logbitp
184 ((index integer) (unsigned-byte (or (signed-byte #.sb!vm:n-word-bits)
185 (unsigned-byte #.sb!vm:n-word-bits))))
186 `(if (>= index #.sb!vm:n-word-bits)
188 (not (zerop (logand integer (ash 1 index))))))
190 (define-source-transform byte (size position)
191 `(cons ,size ,position))
192 (define-source-transform byte-size (spec) `(car ,spec))
193 (define-source-transform byte-position (spec) `(cdr ,spec))
194 (define-source-transform ldb-test (bytespec integer)
195 `(not (zerop (mask-field ,bytespec ,integer))))
197 ;;; With the ratio and complex accessors, we pick off the "identity"
198 ;;; case, and use a primitive to handle the cell access case.
199 (define-source-transform numerator (num)
200 (once-only ((n-num `(the rational ,num)))
204 (define-source-transform denominator (num)
205 (once-only ((n-num `(the rational ,num)))
207 (%denominator ,n-num)
210 ;;;; interval arithmetic for computing bounds
212 ;;;; This is a set of routines for operating on intervals. It
213 ;;;; implements a simple interval arithmetic package. Although SBCL
214 ;;;; has an interval type in NUMERIC-TYPE, we choose to use our own
215 ;;;; for two reasons:
217 ;;;; 1. This package is simpler than NUMERIC-TYPE.
219 ;;;; 2. It makes debugging much easier because you can just strip
220 ;;;; out these routines and test them independently of SBCL. (This is a
223 ;;;; One disadvantage is a probable increase in consing because we
224 ;;;; have to create these new interval structures even though
225 ;;;; numeric-type has everything we want to know. Reason 2 wins for
228 ;;; The basic interval type. It can handle open and closed intervals.
229 ;;; A bound is open if it is a list containing a number, just like
230 ;;; Lisp says. NIL means unbounded.
231 (defstruct (interval (:constructor %make-interval)
235 (defun make-interval (&key low high)
236 (labels ((normalize-bound (val)
237 (cond ((and (floatp val)
238 (float-infinity-p val))
239 ;; Handle infinities.
243 ;; Handle any closed bounds.
246 ;; We have an open bound. Normalize the numeric
247 ;; bound. If the normalized bound is still a number
248 ;; (not nil), keep the bound open. Otherwise, the
249 ;; bound is really unbounded, so drop the openness.
250 (let ((new-val (normalize-bound (first val))))
252 ;; The bound exists, so keep it open still.
255 (error "unknown bound type in MAKE-INTERVAL")))))
256 (%make-interval :low (normalize-bound low)
257 :high (normalize-bound high))))
259 ;;; Given a number X, create a form suitable as a bound for an
260 ;;; interval. Make the bound open if OPEN-P is T. NIL remains NIL.
261 #!-sb-fluid (declaim (inline set-bound))
262 (defun set-bound (x open-p)
263 (if (and x open-p) (list x) x))
265 ;;; Apply the function F to a bound X. If X is an open bound, then
266 ;;; the result will be open. IF X is NIL, the result is NIL.
267 (defun bound-func (f x)
268 (declare (type function f))
270 (with-float-traps-masked (:underflow :overflow :inexact :divide-by-zero)
271 ;; With these traps masked, we might get things like infinity
272 ;; or negative infinity returned. Check for this and return
273 ;; NIL to indicate unbounded.
274 (let ((y (funcall f (type-bound-number x))))
276 (float-infinity-p y))
278 (set-bound (funcall f (type-bound-number x)) (consp x)))))))
280 ;;; Apply a binary operator OP to two bounds X and Y. The result is
281 ;;; NIL if either is NIL. Otherwise bound is computed and the result
282 ;;; is open if either X or Y is open.
284 ;;; FIXME: only used in this file, not needed in target runtime
285 (defmacro bound-binop (op x y)
287 (with-float-traps-masked (:underflow :overflow :inexact :divide-by-zero)
288 (set-bound (,op (type-bound-number ,x)
289 (type-bound-number ,y))
290 (or (consp ,x) (consp ,y))))))
292 ;;; Convert a numeric-type object to an interval object.
293 (defun numeric-type->interval (x)
294 (declare (type numeric-type x))
295 (make-interval :low (numeric-type-low x)
296 :high (numeric-type-high x)))
298 (defun copy-interval-limit (limit)
303 (defun copy-interval (x)
304 (declare (type interval x))
305 (make-interval :low (copy-interval-limit (interval-low x))
306 :high (copy-interval-limit (interval-high x))))
308 ;;; Given a point P contained in the interval X, split X into two
309 ;;; interval at the point P. If CLOSE-LOWER is T, then the left
310 ;;; interval contains P. If CLOSE-UPPER is T, the right interval
311 ;;; contains P. You can specify both to be T or NIL.
312 (defun interval-split (p x &optional close-lower close-upper)
313 (declare (type number p)
315 (list (make-interval :low (copy-interval-limit (interval-low x))
316 :high (if close-lower p (list p)))
317 (make-interval :low (if close-upper (list p) p)
318 :high (copy-interval-limit (interval-high x)))))
320 ;;; Return the closure of the interval. That is, convert open bounds
321 ;;; to closed bounds.
322 (defun interval-closure (x)
323 (declare (type interval x))
324 (make-interval :low (type-bound-number (interval-low x))
325 :high (type-bound-number (interval-high x))))
327 (defun signed-zero->= (x y)
331 (>= (float-sign (float x))
332 (float-sign (float y))))))
334 ;;; For an interval X, if X >= POINT, return '+. If X <= POINT, return
335 ;;; '-. Otherwise return NIL.
337 (defun interval-range-info (x &optional (point 0))
338 (declare (type interval x))
339 (let ((lo (interval-low x))
340 (hi (interval-high x)))
341 (cond ((and lo (signed-zero->= (type-bound-number lo) point))
343 ((and hi (signed-zero->= point (type-bound-number hi)))
347 (defun interval-range-info (x &optional (point 0))
348 (declare (type interval x))
349 (labels ((signed->= (x y)
350 (if (and (zerop x) (zerop y) (floatp x) (floatp y))
351 (>= (float-sign x) (float-sign y))
353 (let ((lo (interval-low x))
354 (hi (interval-high x)))
355 (cond ((and lo (signed->= (type-bound-number lo) point))
357 ((and hi (signed->= point (type-bound-number hi)))
362 ;;; Test to see whether the interval X is bounded. HOW determines the
363 ;;; test, and should be either ABOVE, BELOW, or BOTH.
364 (defun interval-bounded-p (x how)
365 (declare (type interval x))
372 (and (interval-low x) (interval-high x)))))
374 ;;; signed zero comparison functions. Use these functions if we need
375 ;;; to distinguish between signed zeroes.
376 (defun signed-zero-< (x y)
380 (< (float-sign (float x))
381 (float-sign (float y))))))
382 (defun signed-zero-> (x y)
386 (> (float-sign (float x))
387 (float-sign (float y))))))
388 (defun signed-zero-= (x y)
391 (= (float-sign (float x))
392 (float-sign (float y)))))
393 (defun signed-zero-<= (x y)
397 (<= (float-sign (float x))
398 (float-sign (float y))))))
400 ;;; See whether the interval X contains the number P, taking into
401 ;;; account that the interval might not be closed.
402 (defun interval-contains-p (p x)
403 (declare (type number p)
405 ;; Does the interval X contain the number P? This would be a lot
406 ;; easier if all intervals were closed!
407 (let ((lo (interval-low x))
408 (hi (interval-high x)))
410 ;; The interval is bounded
411 (if (and (signed-zero-<= (type-bound-number lo) p)
412 (signed-zero-<= p (type-bound-number hi)))
413 ;; P is definitely in the closure of the interval.
414 ;; We just need to check the end points now.
415 (cond ((signed-zero-= p (type-bound-number lo))
417 ((signed-zero-= p (type-bound-number hi))
422 ;; Interval with upper bound
423 (if (signed-zero-< p (type-bound-number hi))
425 (and (numberp hi) (signed-zero-= p hi))))
427 ;; Interval with lower bound
428 (if (signed-zero-> p (type-bound-number lo))
430 (and (numberp lo) (signed-zero-= p lo))))
432 ;; Interval with no bounds
435 ;;; Determine whether two intervals X and Y intersect. Return T if so.
436 ;;; If CLOSED-INTERVALS-P is T, the treat the intervals as if they
437 ;;; were closed. Otherwise the intervals are treated as they are.
439 ;;; Thus if X = [0, 1) and Y = (1, 2), then they do not intersect
440 ;;; because no element in X is in Y. However, if CLOSED-INTERVALS-P
441 ;;; is T, then they do intersect because we use the closure of X = [0,
442 ;;; 1] and Y = [1, 2] to determine intersection.
443 (defun interval-intersect-p (x y &optional closed-intervals-p)
444 (declare (type interval x y))
445 (multiple-value-bind (intersect diff)
446 (interval-intersection/difference (if closed-intervals-p
449 (if closed-intervals-p
452 (declare (ignore diff))
455 ;;; Are the two intervals adjacent? That is, is there a number
456 ;;; between the two intervals that is not an element of either
457 ;;; interval? If so, they are not adjacent. For example [0, 1) and
458 ;;; [1, 2] are adjacent but [0, 1) and (1, 2] are not because 1 lies
459 ;;; between both intervals.
460 (defun interval-adjacent-p (x y)
461 (declare (type interval x y))
462 (flet ((adjacent (lo hi)
463 ;; Check to see whether lo and hi are adjacent. If either is
464 ;; nil, they can't be adjacent.
465 (when (and lo hi (= (type-bound-number lo) (type-bound-number hi)))
466 ;; The bounds are equal. They are adjacent if one of
467 ;; them is closed (a number). If both are open (consp),
468 ;; then there is a number that lies between them.
469 (or (numberp lo) (numberp hi)))))
470 (or (adjacent (interval-low y) (interval-high x))
471 (adjacent (interval-low x) (interval-high y)))))
473 ;;; Compute the intersection and difference between two intervals.
474 ;;; Two values are returned: the intersection and the difference.
476 ;;; Let the two intervals be X and Y, and let I and D be the two
477 ;;; values returned by this function. Then I = X intersect Y. If I
478 ;;; is NIL (the empty set), then D is X union Y, represented as the
479 ;;; list of X and Y. If I is not the empty set, then D is (X union Y)
480 ;;; - I, which is a list of two intervals.
482 ;;; For example, let X = [1,5] and Y = [-1,3). Then I = [1,3) and D =
483 ;;; [-1,1) union [3,5], which is returned as a list of two intervals.
484 (defun interval-intersection/difference (x y)
485 (declare (type interval x y))
486 (let ((x-lo (interval-low x))
487 (x-hi (interval-high x))
488 (y-lo (interval-low y))
489 (y-hi (interval-high y)))
492 ;; If p is an open bound, make it closed. If p is a closed
493 ;; bound, make it open.
498 ;; Test whether P is in the interval.
499 (when (interval-contains-p (type-bound-number p)
500 (interval-closure int))
501 (let ((lo (interval-low int))
502 (hi (interval-high int)))
503 ;; Check for endpoints.
504 (cond ((and lo (= (type-bound-number p) (type-bound-number lo)))
505 (not (and (consp p) (numberp lo))))
506 ((and hi (= (type-bound-number p) (type-bound-number hi)))
507 (not (and (numberp p) (consp hi))))
509 (test-lower-bound (p int)
510 ;; P is a lower bound of an interval.
513 (not (interval-bounded-p int 'below))))
514 (test-upper-bound (p int)
515 ;; P is an upper bound of an interval.
518 (not (interval-bounded-p int 'above)))))
519 (let ((x-lo-in-y (test-lower-bound x-lo y))
520 (x-hi-in-y (test-upper-bound x-hi y))
521 (y-lo-in-x (test-lower-bound y-lo x))
522 (y-hi-in-x (test-upper-bound y-hi x)))
523 (cond ((or x-lo-in-y x-hi-in-y y-lo-in-x y-hi-in-x)
524 ;; Intervals intersect. Let's compute the intersection
525 ;; and the difference.
526 (multiple-value-bind (lo left-lo left-hi)
527 (cond (x-lo-in-y (values x-lo y-lo (opposite-bound x-lo)))
528 (y-lo-in-x (values y-lo x-lo (opposite-bound y-lo))))
529 (multiple-value-bind (hi right-lo right-hi)
531 (values x-hi (opposite-bound x-hi) y-hi))
533 (values y-hi (opposite-bound y-hi) x-hi)))
534 (values (make-interval :low lo :high hi)
535 (list (make-interval :low left-lo
537 (make-interval :low right-lo
540 (values nil (list x y))))))))
542 ;;; If intervals X and Y intersect, return a new interval that is the
543 ;;; union of the two. If they do not intersect, return NIL.
544 (defun interval-merge-pair (x y)
545 (declare (type interval x y))
546 ;; If x and y intersect or are adjacent, create the union.
547 ;; Otherwise return nil
548 (when (or (interval-intersect-p x y)
549 (interval-adjacent-p x y))
550 (flet ((select-bound (x1 x2 min-op max-op)
551 (let ((x1-val (type-bound-number x1))
552 (x2-val (type-bound-number x2)))
554 ;; Both bounds are finite. Select the right one.
555 (cond ((funcall min-op x1-val x2-val)
556 ;; x1 is definitely better.
558 ((funcall max-op x1-val x2-val)
559 ;; x2 is definitely better.
562 ;; Bounds are equal. Select either
563 ;; value and make it open only if
565 (set-bound x1-val (and (consp x1) (consp x2))))))
567 ;; At least one bound is not finite. The
568 ;; non-finite bound always wins.
570 (let* ((x-lo (copy-interval-limit (interval-low x)))
571 (x-hi (copy-interval-limit (interval-high x)))
572 (y-lo (copy-interval-limit (interval-low y)))
573 (y-hi (copy-interval-limit (interval-high y))))
574 (make-interval :low (select-bound x-lo y-lo #'< #'>)
575 :high (select-bound x-hi y-hi #'> #'<))))))
577 ;;; basic arithmetic operations on intervals. We probably should do
578 ;;; true interval arithmetic here, but it's complicated because we
579 ;;; have float and integer types and bounds can be open or closed.
581 ;;; the negative of an interval
582 (defun interval-neg (x)
583 (declare (type interval x))
584 (make-interval :low (bound-func #'- (interval-high x))
585 :high (bound-func #'- (interval-low x))))
587 ;;; Add two intervals.
588 (defun interval-add (x y)
589 (declare (type interval x y))
590 (make-interval :low (bound-binop + (interval-low x) (interval-low y))
591 :high (bound-binop + (interval-high x) (interval-high y))))
593 ;;; Subtract two intervals.
594 (defun interval-sub (x y)
595 (declare (type interval x y))
596 (make-interval :low (bound-binop - (interval-low x) (interval-high y))
597 :high (bound-binop - (interval-high x) (interval-low y))))
599 ;;; Multiply two intervals.
600 (defun interval-mul (x y)
601 (declare (type interval x y))
602 (flet ((bound-mul (x y)
603 (cond ((or (null x) (null y))
604 ;; Multiply by infinity is infinity
606 ((or (and (numberp x) (zerop x))
607 (and (numberp y) (zerop y)))
608 ;; Multiply by closed zero is special. The result
609 ;; is always a closed bound. But don't replace this
610 ;; with zero; we want the multiplication to produce
611 ;; the correct signed zero, if needed.
612 (* (type-bound-number x) (type-bound-number y)))
613 ((or (and (floatp x) (float-infinity-p x))
614 (and (floatp y) (float-infinity-p y)))
615 ;; Infinity times anything is infinity
618 ;; General multiply. The result is open if either is open.
619 (bound-binop * x y)))))
620 (let ((x-range (interval-range-info x))
621 (y-range (interval-range-info y)))
622 (cond ((null x-range)
623 ;; Split x into two and multiply each separately
624 (destructuring-bind (x- x+) (interval-split 0 x t t)
625 (interval-merge-pair (interval-mul x- y)
626 (interval-mul x+ y))))
628 ;; Split y into two and multiply each separately
629 (destructuring-bind (y- y+) (interval-split 0 y t t)
630 (interval-merge-pair (interval-mul x y-)
631 (interval-mul x y+))))
633 (interval-neg (interval-mul (interval-neg x) y)))
635 (interval-neg (interval-mul x (interval-neg y))))
636 ((and (eq x-range '+) (eq y-range '+))
637 ;; If we are here, X and Y are both positive.
639 :low (bound-mul (interval-low x) (interval-low y))
640 :high (bound-mul (interval-high x) (interval-high y))))
642 (bug "excluded case in INTERVAL-MUL"))))))
644 ;;; Divide two intervals.
645 (defun interval-div (top bot)
646 (declare (type interval top bot))
647 (flet ((bound-div (x y y-low-p)
650 ;; Divide by infinity means result is 0. However,
651 ;; we need to watch out for the sign of the result,
652 ;; to correctly handle signed zeros. We also need
653 ;; to watch out for positive or negative infinity.
654 (if (floatp (type-bound-number x))
656 (- (float-sign (type-bound-number x) 0.0))
657 (float-sign (type-bound-number x) 0.0))
659 ((zerop (type-bound-number y))
660 ;; Divide by zero means result is infinity
662 ((and (numberp x) (zerop x))
663 ;; Zero divided by anything is zero.
666 (bound-binop / x y)))))
667 (let ((top-range (interval-range-info top))
668 (bot-range (interval-range-info bot)))
669 (cond ((null bot-range)
670 ;; The denominator contains zero, so anything goes!
671 (make-interval :low nil :high nil))
673 ;; Denominator is negative so flip the sign, compute the
674 ;; result, and flip it back.
675 (interval-neg (interval-div top (interval-neg bot))))
677 ;; Split top into two positive and negative parts, and
678 ;; divide each separately
679 (destructuring-bind (top- top+) (interval-split 0 top t t)
680 (interval-merge-pair (interval-div top- bot)
681 (interval-div top+ bot))))
683 ;; Top is negative so flip the sign, divide, and flip the
684 ;; sign of the result.
685 (interval-neg (interval-div (interval-neg top) bot)))
686 ((and (eq top-range '+) (eq bot-range '+))
689 :low (bound-div (interval-low top) (interval-high bot) t)
690 :high (bound-div (interval-high top) (interval-low bot) nil)))
692 (bug "excluded case in INTERVAL-DIV"))))))
694 ;;; Apply the function F to the interval X. If X = [a, b], then the
695 ;;; result is [f(a), f(b)]. It is up to the user to make sure the
696 ;;; result makes sense. It will if F is monotonic increasing (or
698 (defun interval-func (f x)
699 (declare (type function f)
701 (let ((lo (bound-func f (interval-low x)))
702 (hi (bound-func f (interval-high x))))
703 (make-interval :low lo :high hi)))
705 ;;; Return T if X < Y. That is every number in the interval X is
706 ;;; always less than any number in the interval Y.
707 (defun interval-< (x y)
708 (declare (type interval x y))
709 ;; X < Y only if X is bounded above, Y is bounded below, and they
711 (when (and (interval-bounded-p x 'above)
712 (interval-bounded-p y 'below))
713 ;; Intervals are bounded in the appropriate way. Make sure they
715 (let ((left (interval-high x))
716 (right (interval-low y)))
717 (cond ((> (type-bound-number left)
718 (type-bound-number right))
719 ;; The intervals definitely overlap, so result is NIL.
721 ((< (type-bound-number left)
722 (type-bound-number right))
723 ;; The intervals definitely don't touch, so result is T.
726 ;; Limits are equal. Check for open or closed bounds.
727 ;; Don't overlap if one or the other are open.
728 (or (consp left) (consp right)))))))
730 ;;; Return T if X >= Y. That is, every number in the interval X is
731 ;;; always greater than any number in the interval Y.
732 (defun interval->= (x y)
733 (declare (type interval x y))
734 ;; X >= Y if lower bound of X >= upper bound of Y
735 (when (and (interval-bounded-p x 'below)
736 (interval-bounded-p y 'above))
737 (>= (type-bound-number (interval-low x))
738 (type-bound-number (interval-high y)))))
740 ;;; Return an interval that is the absolute value of X. Thus, if
741 ;;; X = [-1 10], the result is [0, 10].
742 (defun interval-abs (x)
743 (declare (type interval x))
744 (case (interval-range-info x)
750 (destructuring-bind (x- x+) (interval-split 0 x t t)
751 (interval-merge-pair (interval-neg x-) x+)))))
753 ;;; Compute the square of an interval.
754 (defun interval-sqr (x)
755 (declare (type interval x))
756 (interval-func (lambda (x) (* x x))
759 ;;;; numeric DERIVE-TYPE methods
761 ;;; a utility for defining derive-type methods of integer operations. If
762 ;;; the types of both X and Y are integer types, then we compute a new
763 ;;; integer type with bounds determined Fun when applied to X and Y.
764 ;;; Otherwise, we use Numeric-Contagion.
765 (defun derive-integer-type (x y fun)
766 (declare (type continuation x y) (type function fun))
767 (let ((x (continuation-type x))
768 (y (continuation-type y)))
769 (if (and (numeric-type-p x) (numeric-type-p y)
770 (eq (numeric-type-class x) 'integer)
771 (eq (numeric-type-class y) 'integer)
772 (eq (numeric-type-complexp x) :real)
773 (eq (numeric-type-complexp y) :real))
774 (multiple-value-bind (low high) (funcall fun x y)
775 (make-numeric-type :class 'integer
779 (numeric-contagion x y))))
781 ;;; simple utility to flatten a list
782 (defun flatten-list (x)
783 (labels ((flatten-helper (x r);; 'r' is the stuff to the 'right'.
787 (t (flatten-helper (car x)
788 (flatten-helper (cdr x) r))))))
789 (flatten-helper x nil)))
791 ;;; Take some type of continuation and massage it so that we get a
792 ;;; list of the constituent types. If ARG is *EMPTY-TYPE*, return NIL
793 ;;; to indicate failure.
794 (defun prepare-arg-for-derive-type (arg)
795 (flet ((listify (arg)
800 (union-type-types arg))
803 (unless (eq arg *empty-type*)
804 ;; Make sure all args are some type of numeric-type. For member
805 ;; types, convert the list of members into a union of equivalent
806 ;; single-element member-type's.
807 (let ((new-args nil))
808 (dolist (arg (listify arg))
809 (if (member-type-p arg)
810 ;; Run down the list of members and convert to a list of
812 (dolist (member (member-type-members arg))
813 (push (if (numberp member)
814 (make-member-type :members (list member))
817 (push arg new-args)))
818 (unless (member *empty-type* new-args)
821 ;;; Convert from the standard type convention for which -0.0 and 0.0
822 ;;; are equal to an intermediate convention for which they are
823 ;;; considered different which is more natural for some of the
825 (defun convert-numeric-type (type)
826 (declare (type numeric-type type))
827 ;;; Only convert real float interval delimiters types.
828 (if (eq (numeric-type-complexp type) :real)
829 (let* ((lo (numeric-type-low type))
830 (lo-val (type-bound-number lo))
831 (lo-float-zero-p (and lo (floatp lo-val) (= lo-val 0.0)))
832 (hi (numeric-type-high type))
833 (hi-val (type-bound-number hi))
834 (hi-float-zero-p (and hi (floatp hi-val) (= hi-val 0.0))))
835 (if (or lo-float-zero-p hi-float-zero-p)
837 :class (numeric-type-class type)
838 :format (numeric-type-format type)
840 :low (if lo-float-zero-p
842 (list (float 0.0 lo-val))
843 (float (load-time-value (make-unportable-float :single-float-negative-zero)) lo-val))
845 :high (if hi-float-zero-p
847 (list (float (load-time-value (make-unportable-float :single-float-negative-zero)) hi-val))
854 ;;; Convert back from the intermediate convention for which -0.0 and
855 ;;; 0.0 are considered different to the standard type convention for
857 (defun convert-back-numeric-type (type)
858 (declare (type numeric-type type))
859 ;;; Only convert real float interval delimiters types.
860 (if (eq (numeric-type-complexp type) :real)
861 (let* ((lo (numeric-type-low type))
862 (lo-val (type-bound-number lo))
864 (and lo (floatp lo-val) (= lo-val 0.0)
865 (float-sign lo-val)))
866 (hi (numeric-type-high type))
867 (hi-val (type-bound-number hi))
869 (and hi (floatp hi-val) (= hi-val 0.0)
870 (float-sign hi-val))))
872 ;; (float +0.0 +0.0) => (member 0.0)
873 ;; (float -0.0 -0.0) => (member -0.0)
874 ((and lo-float-zero-p hi-float-zero-p)
875 ;; shouldn't have exclusive bounds here..
876 (aver (and (not (consp lo)) (not (consp hi))))
877 (if (= lo-float-zero-p hi-float-zero-p)
878 ;; (float +0.0 +0.0) => (member 0.0)
879 ;; (float -0.0 -0.0) => (member -0.0)
880 (specifier-type `(member ,lo-val))
881 ;; (float -0.0 +0.0) => (float 0.0 0.0)
882 ;; (float +0.0 -0.0) => (float 0.0 0.0)
883 (make-numeric-type :class (numeric-type-class type)
884 :format (numeric-type-format type)
890 ;; (float -0.0 x) => (float 0.0 x)
891 ((and (not (consp lo)) (minusp lo-float-zero-p))
892 (make-numeric-type :class (numeric-type-class type)
893 :format (numeric-type-format type)
895 :low (float 0.0 lo-val)
897 ;; (float (+0.0) x) => (float (0.0) x)
898 ((and (consp lo) (plusp lo-float-zero-p))
899 (make-numeric-type :class (numeric-type-class type)
900 :format (numeric-type-format type)
902 :low (list (float 0.0 lo-val))
905 ;; (float +0.0 x) => (or (member 0.0) (float (0.0) x))
906 ;; (float (-0.0) x) => (or (member 0.0) (float (0.0) x))
907 (list (make-member-type :members (list (float 0.0 lo-val)))
908 (make-numeric-type :class (numeric-type-class type)
909 :format (numeric-type-format type)
911 :low (list (float 0.0 lo-val))
915 ;; (float x +0.0) => (float x 0.0)
916 ((and (not (consp hi)) (plusp hi-float-zero-p))
917 (make-numeric-type :class (numeric-type-class type)
918 :format (numeric-type-format type)
921 :high (float 0.0 hi-val)))
922 ;; (float x (-0.0)) => (float x (0.0))
923 ((and (consp hi) (minusp hi-float-zero-p))
924 (make-numeric-type :class (numeric-type-class type)
925 :format (numeric-type-format type)
928 :high (list (float 0.0 hi-val))))
930 ;; (float x (+0.0)) => (or (member -0.0) (float x (0.0)))
931 ;; (float x -0.0) => (or (member -0.0) (float x (0.0)))
932 (list (make-member-type :members (list (float -0.0 hi-val)))
933 (make-numeric-type :class (numeric-type-class type)
934 :format (numeric-type-format type)
937 :high (list (float 0.0 hi-val)))))))
943 ;;; Convert back a possible list of numeric types.
944 (defun convert-back-numeric-type-list (type-list)
948 (dolist (type type-list)
949 (if (numeric-type-p type)
950 (let ((result (convert-back-numeric-type type)))
952 (setf results (append results result))
953 (push result results)))
954 (push type results)))
957 (convert-back-numeric-type type-list))
959 (convert-back-numeric-type-list (union-type-types type-list)))
963 ;;; FIXME: MAKE-CANONICAL-UNION-TYPE and CONVERT-MEMBER-TYPE probably
964 ;;; belong in the kernel's type logic, invoked always, instead of in
965 ;;; the compiler, invoked only during some type optimizations. (In
966 ;;; fact, as of 0.pre8.100 or so they probably are, under
967 ;;; MAKE-MEMBER-TYPE, so probably this code can be deleted)
969 ;;; Take a list of types and return a canonical type specifier,
970 ;;; combining any MEMBER types together. If both positive and negative
971 ;;; MEMBER types are present they are converted to a float type.
972 ;;; XXX This would be far simpler if the type-union methods could handle
973 ;;; member/number unions.
974 (defun make-canonical-union-type (type-list)
977 (dolist (type type-list)
978 (if (member-type-p type)
979 (setf members (union members (member-type-members type)))
980 (push type misc-types)))
982 (when (null (set-difference `(,(load-time-value (make-unportable-float :long-float-negative-zero)) 0.0l0) members))
983 (push (specifier-type '(long-float 0.0l0 0.0l0)) misc-types)
984 (setf members (set-difference members `(,(load-time-value (make-unportable-float :long-float-negative-zero)) 0.0l0))))
985 (when (null (set-difference `(,(load-time-value (make-unportable-float :double-float-negative-zero)) 0.0d0) members))
986 (push (specifier-type '(double-float 0.0d0 0.0d0)) misc-types)
987 (setf members (set-difference members `(,(load-time-value (make-unportable-float :double-float-negative-zero)) 0.0d0))))
988 (when (null (set-difference `(,(load-time-value (make-unportable-float :single-float-negative-zero)) 0.0f0) members))
989 (push (specifier-type '(single-float 0.0f0 0.0f0)) misc-types)
990 (setf members (set-difference members `(,(load-time-value (make-unportable-float :single-float-negative-zero)) 0.0f0))))
992 (apply #'type-union (make-member-type :members members) misc-types)
993 (apply #'type-union misc-types))))
995 ;;; Convert a member type with a single member to a numeric type.
996 (defun convert-member-type (arg)
997 (let* ((members (member-type-members arg))
998 (member (first members))
999 (member-type (type-of member)))
1000 (aver (not (rest members)))
1001 (specifier-type (cond ((typep member 'integer)
1002 `(integer ,member ,member))
1003 ((memq member-type '(short-float single-float
1004 double-float long-float))
1005 `(,member-type ,member ,member))
1009 ;;; This is used in defoptimizers for computing the resulting type of
1012 ;;; Given the continuation ARG, derive the resulting type using the
1013 ;;; DERIVE-FUN. DERIVE-FUN takes exactly one argument which is some
1014 ;;; "atomic" continuation type like numeric-type or member-type
1015 ;;; (containing just one element). It should return the resulting
1016 ;;; type, which can be a list of types.
1018 ;;; For the case of member types, if a MEMBER-FUN is given it is
1019 ;;; called to compute the result otherwise the member type is first
1020 ;;; converted to a numeric type and the DERIVE-FUN is called.
1021 (defun one-arg-derive-type (arg derive-fun member-fun
1022 &optional (convert-type t))
1023 (declare (type function derive-fun)
1024 (type (or null function) member-fun))
1025 (let ((arg-list (prepare-arg-for-derive-type (continuation-type arg))))
1031 (with-float-traps-masked
1032 (:underflow :overflow :divide-by-zero)
1036 (first (member-type-members x))))))
1037 ;; Otherwise convert to a numeric type.
1038 (let ((result-type-list
1039 (funcall derive-fun (convert-member-type x))))
1041 (convert-back-numeric-type-list result-type-list)
1042 result-type-list))))
1045 (convert-back-numeric-type-list
1046 (funcall derive-fun (convert-numeric-type x)))
1047 (funcall derive-fun x)))
1049 *universal-type*))))
1050 ;; Run down the list of args and derive the type of each one,
1051 ;; saving all of the results in a list.
1052 (let ((results nil))
1053 (dolist (arg arg-list)
1054 (let ((result (deriver arg)))
1056 (setf results (append results result))
1057 (push result results))))
1059 (make-canonical-union-type results)
1060 (first results)))))))
1062 ;;; Same as ONE-ARG-DERIVE-TYPE, except we assume the function takes
1063 ;;; two arguments. DERIVE-FUN takes 3 args in this case: the two
1064 ;;; original args and a third which is T to indicate if the two args
1065 ;;; really represent the same continuation. This is useful for
1066 ;;; deriving the type of things like (* x x), which should always be
1067 ;;; positive. If we didn't do this, we wouldn't be able to tell.
1068 (defun two-arg-derive-type (arg1 arg2 derive-fun fun
1069 &optional (convert-type t))
1070 (declare (type function derive-fun fun))
1071 (flet ((deriver (x y same-arg)
1072 (cond ((and (member-type-p x) (member-type-p y))
1073 (let* ((x (first (member-type-members x)))
1074 (y (first (member-type-members y)))
1075 (result (with-float-traps-masked
1076 (:underflow :overflow :divide-by-zero
1078 (funcall fun x y))))
1079 (cond ((null result))
1080 ((and (floatp result) (float-nan-p result))
1081 (make-numeric-type :class 'float
1082 :format (type-of result)
1085 (make-member-type :members (list result))))))
1086 ((and (member-type-p x) (numeric-type-p y))
1087 (let* ((x (convert-member-type x))
1088 (y (if convert-type (convert-numeric-type y) y))
1089 (result (funcall derive-fun x y same-arg)))
1091 (convert-back-numeric-type-list result)
1093 ((and (numeric-type-p x) (member-type-p y))
1094 (let* ((x (if convert-type (convert-numeric-type x) x))
1095 (y (convert-member-type y))
1096 (result (funcall derive-fun x y same-arg)))
1098 (convert-back-numeric-type-list result)
1100 ((and (numeric-type-p x) (numeric-type-p y))
1101 (let* ((x (if convert-type (convert-numeric-type x) x))
1102 (y (if convert-type (convert-numeric-type y) y))
1103 (result (funcall derive-fun x y same-arg)))
1105 (convert-back-numeric-type-list result)
1108 *universal-type*))))
1109 (let ((same-arg (same-leaf-ref-p arg1 arg2))
1110 (a1 (prepare-arg-for-derive-type (continuation-type arg1)))
1111 (a2 (prepare-arg-for-derive-type (continuation-type arg2))))
1113 (let ((results nil))
1115 ;; Since the args are the same continuation, just run
1118 (let ((result (deriver x x same-arg)))
1120 (setf results (append results result))
1121 (push result results))))
1122 ;; Try all pairwise combinations.
1125 (let ((result (or (deriver x y same-arg)
1126 (numeric-contagion x y))))
1128 (setf results (append results result))
1129 (push result results))))))
1131 (make-canonical-union-type results)
1132 (first results)))))))
1134 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1136 (defoptimizer (+ derive-type) ((x y))
1137 (derive-integer-type
1144 (values (frob (numeric-type-low x) (numeric-type-low y))
1145 (frob (numeric-type-high x) (numeric-type-high y)))))))
1147 (defoptimizer (- derive-type) ((x y))
1148 (derive-integer-type
1155 (values (frob (numeric-type-low x) (numeric-type-high y))
1156 (frob (numeric-type-high x) (numeric-type-low y)))))))
1158 (defoptimizer (* derive-type) ((x y))
1159 (derive-integer-type
1162 (let ((x-low (numeric-type-low x))
1163 (x-high (numeric-type-high x))
1164 (y-low (numeric-type-low y))
1165 (y-high (numeric-type-high y)))
1166 (cond ((not (and x-low y-low))
1168 ((or (minusp x-low) (minusp y-low))
1169 (if (and x-high y-high)
1170 (let ((max (* (max (abs x-low) (abs x-high))
1171 (max (abs y-low) (abs y-high)))))
1172 (values (- max) max))
1175 (values (* x-low y-low)
1176 (if (and x-high y-high)
1180 (defoptimizer (/ derive-type) ((x y))
1181 (numeric-contagion (continuation-type x) (continuation-type y)))
1185 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1187 (defun +-derive-type-aux (x y same-arg)
1188 (if (and (numeric-type-real-p x)
1189 (numeric-type-real-p y))
1192 (let ((x-int (numeric-type->interval x)))
1193 (interval-add x-int x-int))
1194 (interval-add (numeric-type->interval x)
1195 (numeric-type->interval y))))
1196 (result-type (numeric-contagion x y)))
1197 ;; If the result type is a float, we need to be sure to coerce
1198 ;; the bounds into the correct type.
1199 (when (eq (numeric-type-class result-type) 'float)
1200 (setf result (interval-func
1202 (coerce x (or (numeric-type-format result-type)
1206 :class (if (and (eq (numeric-type-class x) 'integer)
1207 (eq (numeric-type-class y) 'integer))
1208 ;; The sum of integers is always an integer.
1210 (numeric-type-class result-type))
1211 :format (numeric-type-format result-type)
1212 :low (interval-low result)
1213 :high (interval-high result)))
1214 ;; general contagion
1215 (numeric-contagion x y)))
1217 (defoptimizer (+ derive-type) ((x y))
1218 (two-arg-derive-type x y #'+-derive-type-aux #'+))
1220 (defun --derive-type-aux (x y same-arg)
1221 (if (and (numeric-type-real-p x)
1222 (numeric-type-real-p y))
1224 ;; (- X X) is always 0.
1226 (make-interval :low 0 :high 0)
1227 (interval-sub (numeric-type->interval x)
1228 (numeric-type->interval y))))
1229 (result-type (numeric-contagion x y)))
1230 ;; If the result type is a float, we need to be sure to coerce
1231 ;; the bounds into the correct type.
1232 (when (eq (numeric-type-class result-type) 'float)
1233 (setf result (interval-func
1235 (coerce x (or (numeric-type-format result-type)
1239 :class (if (and (eq (numeric-type-class x) 'integer)
1240 (eq (numeric-type-class y) 'integer))
1241 ;; The difference of integers is always an integer.
1243 (numeric-type-class result-type))
1244 :format (numeric-type-format result-type)
1245 :low (interval-low result)
1246 :high (interval-high result)))
1247 ;; general contagion
1248 (numeric-contagion x y)))
1250 (defoptimizer (- derive-type) ((x y))
1251 (two-arg-derive-type x y #'--derive-type-aux #'-))
1253 (defun *-derive-type-aux (x y same-arg)
1254 (if (and (numeric-type-real-p x)
1255 (numeric-type-real-p y))
1257 ;; (* X X) is always positive, so take care to do it right.
1259 (interval-sqr (numeric-type->interval x))
1260 (interval-mul (numeric-type->interval x)
1261 (numeric-type->interval y))))
1262 (result-type (numeric-contagion x y)))
1263 ;; If the result type is a float, we need to be sure to coerce
1264 ;; the bounds into the correct type.
1265 (when (eq (numeric-type-class result-type) 'float)
1266 (setf result (interval-func
1268 (coerce x (or (numeric-type-format result-type)
1272 :class (if (and (eq (numeric-type-class x) 'integer)
1273 (eq (numeric-type-class y) 'integer))
1274 ;; The product of integers is always an integer.
1276 (numeric-type-class result-type))
1277 :format (numeric-type-format result-type)
1278 :low (interval-low result)
1279 :high (interval-high result)))
1280 (numeric-contagion x y)))
1282 (defoptimizer (* derive-type) ((x y))
1283 (two-arg-derive-type x y #'*-derive-type-aux #'*))
1285 (defun /-derive-type-aux (x y same-arg)
1286 (if (and (numeric-type-real-p x)
1287 (numeric-type-real-p y))
1289 ;; (/ X X) is always 1, except if X can contain 0. In
1290 ;; that case, we shouldn't optimize the division away
1291 ;; because we want 0/0 to signal an error.
1293 (not (interval-contains-p
1294 0 (interval-closure (numeric-type->interval y)))))
1295 (make-interval :low 1 :high 1)
1296 (interval-div (numeric-type->interval x)
1297 (numeric-type->interval y))))
1298 (result-type (numeric-contagion x y)))
1299 ;; If the result type is a float, we need to be sure to coerce
1300 ;; the bounds into the correct type.
1301 (when (eq (numeric-type-class result-type) 'float)
1302 (setf result (interval-func
1304 (coerce x (or (numeric-type-format result-type)
1307 (make-numeric-type :class (numeric-type-class result-type)
1308 :format (numeric-type-format result-type)
1309 :low (interval-low result)
1310 :high (interval-high result)))
1311 (numeric-contagion x y)))
1313 (defoptimizer (/ derive-type) ((x y))
1314 (two-arg-derive-type x y #'/-derive-type-aux #'/))
1318 (defun ash-derive-type-aux (n-type shift same-arg)
1319 (declare (ignore same-arg))
1320 ;; KLUDGE: All this ASH optimization is suppressed under CMU CL for
1321 ;; some bignum cases because as of version 2.4.6 for Debian and 18d,
1322 ;; CMU CL blows up on (ASH 1000000000 -100000000000) (i.e. ASH of
1323 ;; two bignums yielding zero) and it's hard to avoid that
1324 ;; calculation in here.
1325 #+(and cmu sb-xc-host)
1326 (when (and (or (typep (numeric-type-low n-type) 'bignum)
1327 (typep (numeric-type-high n-type) 'bignum))
1328 (or (typep (numeric-type-low shift) 'bignum)
1329 (typep (numeric-type-high shift) 'bignum)))
1330 (return-from ash-derive-type-aux *universal-type*))
1331 (flet ((ash-outer (n s)
1332 (when (and (fixnump s)
1334 (> s sb!xc:most-negative-fixnum))
1336 ;; KLUDGE: The bare 64's here should be related to
1337 ;; symbolic machine word size values somehow.
1340 (if (and (fixnump s)
1341 (> s sb!xc:most-negative-fixnum))
1343 (if (minusp n) -1 0))))
1344 (or (and (csubtypep n-type (specifier-type 'integer))
1345 (csubtypep shift (specifier-type 'integer))
1346 (let ((n-low (numeric-type-low n-type))
1347 (n-high (numeric-type-high n-type))
1348 (s-low (numeric-type-low shift))
1349 (s-high (numeric-type-high shift)))
1350 (make-numeric-type :class 'integer :complexp :real
1353 (ash-outer n-low s-high)
1354 (ash-inner n-low s-low)))
1357 (ash-inner n-high s-low)
1358 (ash-outer n-high s-high))))))
1361 (defoptimizer (ash derive-type) ((n shift))
1362 (two-arg-derive-type n shift #'ash-derive-type-aux #'ash))
1364 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1365 (macrolet ((frob (fun)
1366 `#'(lambda (type type2)
1367 (declare (ignore type2))
1368 (let ((lo (numeric-type-low type))
1369 (hi (numeric-type-high type)))
1370 (values (if hi (,fun hi) nil) (if lo (,fun lo) nil))))))
1372 (defoptimizer (%negate derive-type) ((num))
1373 (derive-integer-type num num (frob -))))
1375 (defoptimizer (lognot derive-type) ((int))
1376 (derive-integer-type int int
1377 (lambda (type type2)
1378 (declare (ignore type2))
1379 (let ((lo (numeric-type-low type))
1380 (hi (numeric-type-high type)))
1381 (values (if hi (lognot hi) nil)
1382 (if lo (lognot lo) nil)
1383 (numeric-type-class type)
1384 (numeric-type-format type))))))
1386 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1387 (defoptimizer (%negate derive-type) ((num))
1388 (flet ((negate-bound (b)
1390 (set-bound (- (type-bound-number b))
1392 (one-arg-derive-type num
1394 (modified-numeric-type
1396 :low (negate-bound (numeric-type-high type))
1397 :high (negate-bound (numeric-type-low type))))
1400 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1401 (defoptimizer (abs derive-type) ((num))
1402 (let ((type (continuation-type num)))
1403 (if (and (numeric-type-p type)
1404 (eq (numeric-type-class type) 'integer)
1405 (eq (numeric-type-complexp type) :real))
1406 (let ((lo (numeric-type-low type))
1407 (hi (numeric-type-high type)))
1408 (make-numeric-type :class 'integer :complexp :real
1409 :low (cond ((and hi (minusp hi))
1415 :high (if (and hi lo)
1416 (max (abs hi) (abs lo))
1418 (numeric-contagion type type))))
1420 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1421 (defun abs-derive-type-aux (type)
1422 (cond ((eq (numeric-type-complexp type) :complex)
1423 ;; The absolute value of a complex number is always a
1424 ;; non-negative float.
1425 (let* ((format (case (numeric-type-class type)
1426 ((integer rational) 'single-float)
1427 (t (numeric-type-format type))))
1428 (bound-format (or format 'float)))
1429 (make-numeric-type :class 'float
1432 :low (coerce 0 bound-format)
1435 ;; The absolute value of a real number is a non-negative real
1436 ;; of the same type.
1437 (let* ((abs-bnd (interval-abs (numeric-type->interval type)))
1438 (class (numeric-type-class type))
1439 (format (numeric-type-format type))
1440 (bound-type (or format class 'real)))
1445 :low (coerce-numeric-bound (interval-low abs-bnd) bound-type)
1446 :high (coerce-numeric-bound
1447 (interval-high abs-bnd) bound-type))))))
1449 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1450 (defoptimizer (abs derive-type) ((num))
1451 (one-arg-derive-type num #'abs-derive-type-aux #'abs))
1453 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1454 (defoptimizer (truncate derive-type) ((number divisor))
1455 (let ((number-type (continuation-type number))
1456 (divisor-type (continuation-type divisor))
1457 (integer-type (specifier-type 'integer)))
1458 (if (and (numeric-type-p number-type)
1459 (csubtypep number-type integer-type)
1460 (numeric-type-p divisor-type)
1461 (csubtypep divisor-type integer-type))
1462 (let ((number-low (numeric-type-low number-type))
1463 (number-high (numeric-type-high number-type))
1464 (divisor-low (numeric-type-low divisor-type))
1465 (divisor-high (numeric-type-high divisor-type)))
1466 (values-specifier-type
1467 `(values ,(integer-truncate-derive-type number-low number-high
1468 divisor-low divisor-high)
1469 ,(integer-rem-derive-type number-low number-high
1470 divisor-low divisor-high))))
1473 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1476 (defun rem-result-type (number-type divisor-type)
1477 ;; Figure out what the remainder type is. The remainder is an
1478 ;; integer if both args are integers; a rational if both args are
1479 ;; rational; and a float otherwise.
1480 (cond ((and (csubtypep number-type (specifier-type 'integer))
1481 (csubtypep divisor-type (specifier-type 'integer)))
1483 ((and (csubtypep number-type (specifier-type 'rational))
1484 (csubtypep divisor-type (specifier-type 'rational)))
1486 ((and (csubtypep number-type (specifier-type 'float))
1487 (csubtypep divisor-type (specifier-type 'float)))
1488 ;; Both are floats so the result is also a float, of
1489 ;; the largest type.
1490 (or (float-format-max (numeric-type-format number-type)
1491 (numeric-type-format divisor-type))
1493 ((and (csubtypep number-type (specifier-type 'float))
1494 (csubtypep divisor-type (specifier-type 'rational)))
1495 ;; One of the arguments is a float and the other is a
1496 ;; rational. The remainder is a float of the same
1498 (or (numeric-type-format number-type) 'float))
1499 ((and (csubtypep divisor-type (specifier-type 'float))
1500 (csubtypep number-type (specifier-type 'rational)))
1501 ;; One of the arguments is a float and the other is a
1502 ;; rational. The remainder is a float of the same
1504 (or (numeric-type-format divisor-type) 'float))
1506 ;; Some unhandled combination. This usually means both args
1507 ;; are REAL so the result is a REAL.
1510 (defun truncate-derive-type-quot (number-type divisor-type)
1511 (let* ((rem-type (rem-result-type number-type divisor-type))
1512 (number-interval (numeric-type->interval number-type))
1513 (divisor-interval (numeric-type->interval divisor-type)))
1514 ;;(declare (type (member '(integer rational float)) rem-type))
1515 ;; We have real numbers now.
1516 (cond ((eq rem-type 'integer)
1517 ;; Since the remainder type is INTEGER, both args are
1519 (let* ((res (integer-truncate-derive-type
1520 (interval-low number-interval)
1521 (interval-high number-interval)
1522 (interval-low divisor-interval)
1523 (interval-high divisor-interval))))
1524 (specifier-type (if (listp res) res 'integer))))
1526 (let ((quot (truncate-quotient-bound
1527 (interval-div number-interval
1528 divisor-interval))))
1529 (specifier-type `(integer ,(or (interval-low quot) '*)
1530 ,(or (interval-high quot) '*))))))))
1532 (defun truncate-derive-type-rem (number-type divisor-type)
1533 (let* ((rem-type (rem-result-type number-type divisor-type))
1534 (number-interval (numeric-type->interval number-type))
1535 (divisor-interval (numeric-type->interval divisor-type))
1536 (rem (truncate-rem-bound number-interval divisor-interval)))
1537 ;;(declare (type (member '(integer rational float)) rem-type))
1538 ;; We have real numbers now.
1539 (cond ((eq rem-type 'integer)
1540 ;; Since the remainder type is INTEGER, both args are
1542 (specifier-type `(,rem-type ,(or (interval-low rem) '*)
1543 ,(or (interval-high rem) '*))))
1545 (multiple-value-bind (class format)
1548 (values 'integer nil))
1550 (values 'rational nil))
1551 ((or single-float double-float #!+long-float long-float)
1552 (values 'float rem-type))
1554 (values 'float nil))
1557 (when (member rem-type '(float single-float double-float
1558 #!+long-float long-float))
1559 (setf rem (interval-func #'(lambda (x)
1560 (coerce x rem-type))
1562 (make-numeric-type :class class
1564 :low (interval-low rem)
1565 :high (interval-high rem)))))))
1567 (defun truncate-derive-type-quot-aux (num div same-arg)
1568 (declare (ignore same-arg))
1569 (if (and (numeric-type-real-p num)
1570 (numeric-type-real-p div))
1571 (truncate-derive-type-quot num div)
1574 (defun truncate-derive-type-rem-aux (num div same-arg)
1575 (declare (ignore same-arg))
1576 (if (and (numeric-type-real-p num)
1577 (numeric-type-real-p div))
1578 (truncate-derive-type-rem num div)
1581 (defoptimizer (truncate derive-type) ((number divisor))
1582 (let ((quot (two-arg-derive-type number divisor
1583 #'truncate-derive-type-quot-aux #'truncate))
1584 (rem (two-arg-derive-type number divisor
1585 #'truncate-derive-type-rem-aux #'rem)))
1586 (when (and quot rem)
1587 (make-values-type :required (list quot rem)))))
1589 (defun ftruncate-derive-type-quot (number-type divisor-type)
1590 ;; The bounds are the same as for truncate. However, the first
1591 ;; result is a float of some type. We need to determine what that
1592 ;; type is. Basically it's the more contagious of the two types.
1593 (let ((q-type (truncate-derive-type-quot number-type divisor-type))
1594 (res-type (numeric-contagion number-type divisor-type)))
1595 (make-numeric-type :class 'float
1596 :format (numeric-type-format res-type)
1597 :low (numeric-type-low q-type)
1598 :high (numeric-type-high q-type))))
1600 (defun ftruncate-derive-type-quot-aux (n d same-arg)
1601 (declare (ignore same-arg))
1602 (if (and (numeric-type-real-p n)
1603 (numeric-type-real-p d))
1604 (ftruncate-derive-type-quot n d)
1607 (defoptimizer (ftruncate derive-type) ((number divisor))
1609 (two-arg-derive-type number divisor
1610 #'ftruncate-derive-type-quot-aux #'ftruncate))
1611 (rem (two-arg-derive-type number divisor
1612 #'truncate-derive-type-rem-aux #'rem)))
1613 (when (and quot rem)
1614 (make-values-type :required (list quot rem)))))
1616 (defun %unary-truncate-derive-type-aux (number)
1617 (truncate-derive-type-quot number (specifier-type '(integer 1 1))))
1619 (defoptimizer (%unary-truncate derive-type) ((number))
1620 (one-arg-derive-type number
1621 #'%unary-truncate-derive-type-aux
1624 ;;; Define optimizers for FLOOR and CEILING.
1626 ((def (name q-name r-name)
1627 (let ((q-aux (symbolicate q-name "-AUX"))
1628 (r-aux (symbolicate r-name "-AUX")))
1630 ;; Compute type of quotient (first) result.
1631 (defun ,q-aux (number-type divisor-type)
1632 (let* ((number-interval
1633 (numeric-type->interval number-type))
1635 (numeric-type->interval divisor-type))
1636 (quot (,q-name (interval-div number-interval
1637 divisor-interval))))
1638 (specifier-type `(integer ,(or (interval-low quot) '*)
1639 ,(or (interval-high quot) '*)))))
1640 ;; Compute type of remainder.
1641 (defun ,r-aux (number-type divisor-type)
1642 (let* ((divisor-interval
1643 (numeric-type->interval divisor-type))
1644 (rem (,r-name divisor-interval))
1645 (result-type (rem-result-type number-type divisor-type)))
1646 (multiple-value-bind (class format)
1649 (values 'integer nil))
1651 (values 'rational nil))
1652 ((or single-float double-float #!+long-float long-float)
1653 (values 'float result-type))
1655 (values 'float nil))
1658 (when (member result-type '(float single-float double-float
1659 #!+long-float long-float))
1660 ;; Make sure that the limits on the interval have
1662 (setf rem (interval-func (lambda (x)
1663 (coerce x result-type))
1665 (make-numeric-type :class class
1667 :low (interval-low rem)
1668 :high (interval-high rem)))))
1669 ;; the optimizer itself
1670 (defoptimizer (,name derive-type) ((number divisor))
1671 (flet ((derive-q (n d same-arg)
1672 (declare (ignore same-arg))
1673 (if (and (numeric-type-real-p n)
1674 (numeric-type-real-p d))
1677 (derive-r (n d same-arg)
1678 (declare (ignore same-arg))
1679 (if (and (numeric-type-real-p n)
1680 (numeric-type-real-p d))
1683 (let ((quot (two-arg-derive-type
1684 number divisor #'derive-q #',name))
1685 (rem (two-arg-derive-type
1686 number divisor #'derive-r #'mod)))
1687 (when (and quot rem)
1688 (make-values-type :required (list quot rem))))))))))
1690 (def floor floor-quotient-bound floor-rem-bound)
1691 (def ceiling ceiling-quotient-bound ceiling-rem-bound))
1693 ;;; Define optimizers for FFLOOR and FCEILING
1694 (macrolet ((def (name q-name r-name)
1695 (let ((q-aux (symbolicate "F" q-name "-AUX"))
1696 (r-aux (symbolicate r-name "-AUX")))
1698 ;; Compute type of quotient (first) result.
1699 (defun ,q-aux (number-type divisor-type)
1700 (let* ((number-interval
1701 (numeric-type->interval number-type))
1703 (numeric-type->interval divisor-type))
1704 (quot (,q-name (interval-div number-interval
1706 (res-type (numeric-contagion number-type
1709 :class (numeric-type-class res-type)
1710 :format (numeric-type-format res-type)
1711 :low (interval-low quot)
1712 :high (interval-high quot))))
1714 (defoptimizer (,name derive-type) ((number divisor))
1715 (flet ((derive-q (n d same-arg)
1716 (declare (ignore same-arg))
1717 (if (and (numeric-type-real-p n)
1718 (numeric-type-real-p d))
1721 (derive-r (n d same-arg)
1722 (declare (ignore same-arg))
1723 (if (and (numeric-type-real-p n)
1724 (numeric-type-real-p d))
1727 (let ((quot (two-arg-derive-type
1728 number divisor #'derive-q #',name))
1729 (rem (two-arg-derive-type
1730 number divisor #'derive-r #'mod)))
1731 (when (and quot rem)
1732 (make-values-type :required (list quot rem))))))))))
1734 (def ffloor floor-quotient-bound floor-rem-bound)
1735 (def fceiling ceiling-quotient-bound ceiling-rem-bound))
1737 ;;; functions to compute the bounds on the quotient and remainder for
1738 ;;; the FLOOR function
1739 (defun floor-quotient-bound (quot)
1740 ;; Take the floor of the quotient and then massage it into what we
1742 (let ((lo (interval-low quot))
1743 (hi (interval-high quot)))
1744 ;; Take the floor of the lower bound. The result is always a
1745 ;; closed lower bound.
1747 (floor (type-bound-number lo))
1749 ;; For the upper bound, we need to be careful.
1752 ;; An open bound. We need to be careful here because
1753 ;; the floor of '(10.0) is 9, but the floor of
1755 (multiple-value-bind (q r) (floor (first hi))
1760 ;; A closed bound, so the answer is obvious.
1764 (make-interval :low lo :high hi)))
1765 (defun floor-rem-bound (div)
1766 ;; The remainder depends only on the divisor. Try to get the
1767 ;; correct sign for the remainder if we can.
1768 (case (interval-range-info div)
1770 ;; The divisor is always positive.
1771 (let ((rem (interval-abs div)))
1772 (setf (interval-low rem) 0)
1773 (when (and (numberp (interval-high rem))
1774 (not (zerop (interval-high rem))))
1775 ;; The remainder never contains the upper bound. However,
1776 ;; watch out for the case where the high limit is zero!
1777 (setf (interval-high rem) (list (interval-high rem))))
1780 ;; The divisor is always negative.
1781 (let ((rem (interval-neg (interval-abs div))))
1782 (setf (interval-high rem) 0)
1783 (when (numberp (interval-low rem))
1784 ;; The remainder never contains the lower bound.
1785 (setf (interval-low rem) (list (interval-low rem))))
1788 ;; The divisor can be positive or negative. All bets off. The
1789 ;; magnitude of remainder is the maximum value of the divisor.
1790 (let ((limit (type-bound-number (interval-high (interval-abs div)))))
1791 ;; The bound never reaches the limit, so make the interval open.
1792 (make-interval :low (if limit
1795 :high (list limit))))))
1797 (floor-quotient-bound (make-interval :low 0.3 :high 10.3))
1798 => #S(INTERVAL :LOW 0 :HIGH 10)
1799 (floor-quotient-bound (make-interval :low 0.3 :high '(10.3)))
1800 => #S(INTERVAL :LOW 0 :HIGH 10)
1801 (floor-quotient-bound (make-interval :low 0.3 :high 10))
1802 => #S(INTERVAL :LOW 0 :HIGH 10)
1803 (floor-quotient-bound (make-interval :low 0.3 :high '(10)))
1804 => #S(INTERVAL :LOW 0 :HIGH 9)
1805 (floor-quotient-bound (make-interval :low '(0.3) :high 10.3))
1806 => #S(INTERVAL :LOW 0 :HIGH 10)
1807 (floor-quotient-bound (make-interval :low '(0.0) :high 10.3))
1808 => #S(INTERVAL :LOW 0 :HIGH 10)
1809 (floor-quotient-bound (make-interval :low '(-1.3) :high 10.3))
1810 => #S(INTERVAL :LOW -2 :HIGH 10)
1811 (floor-quotient-bound (make-interval :low '(-1.0) :high 10.3))
1812 => #S(INTERVAL :LOW -1 :HIGH 10)
1813 (floor-quotient-bound (make-interval :low -1.0 :high 10.3))
1814 => #S(INTERVAL :LOW -1 :HIGH 10)
1816 (floor-rem-bound (make-interval :low 0.3 :high 10.3))
1817 => #S(INTERVAL :LOW 0 :HIGH '(10.3))
1818 (floor-rem-bound (make-interval :low 0.3 :high '(10.3)))
1819 => #S(INTERVAL :LOW 0 :HIGH '(10.3))
1820 (floor-rem-bound (make-interval :low -10 :high -2.3))
1821 #S(INTERVAL :LOW (-10) :HIGH 0)
1822 (floor-rem-bound (make-interval :low 0.3 :high 10))
1823 => #S(INTERVAL :LOW 0 :HIGH '(10))
1824 (floor-rem-bound (make-interval :low '(-1.3) :high 10.3))
1825 => #S(INTERVAL :LOW '(-10.3) :HIGH '(10.3))
1826 (floor-rem-bound (make-interval :low '(-20.3) :high 10.3))
1827 => #S(INTERVAL :LOW (-20.3) :HIGH (20.3))
1830 ;;; same functions for CEILING
1831 (defun ceiling-quotient-bound (quot)
1832 ;; Take the ceiling of the quotient and then massage it into what we
1834 (let ((lo (interval-low quot))
1835 (hi (interval-high quot)))
1836 ;; Take the ceiling of the upper bound. The result is always a
1837 ;; closed upper bound.
1839 (ceiling (type-bound-number hi))
1841 ;; For the lower bound, we need to be careful.
1844 ;; An open bound. We need to be careful here because
1845 ;; the ceiling of '(10.0) is 11, but the ceiling of
1847 (multiple-value-bind (q r) (ceiling (first lo))
1852 ;; A closed bound, so the answer is obvious.
1856 (make-interval :low lo :high hi)))
1857 (defun ceiling-rem-bound (div)
1858 ;; The remainder depends only on the divisor. Try to get the
1859 ;; correct sign for the remainder if we can.
1860 (case (interval-range-info div)
1862 ;; Divisor is always positive. The remainder is negative.
1863 (let ((rem (interval-neg (interval-abs div))))
1864 (setf (interval-high rem) 0)
1865 (when (and (numberp (interval-low rem))
1866 (not (zerop (interval-low rem))))
1867 ;; The remainder never contains the upper bound. However,
1868 ;; watch out for the case when the upper bound is zero!
1869 (setf (interval-low rem) (list (interval-low rem))))
1872 ;; Divisor is always negative. The remainder is positive
1873 (let ((rem (interval-abs div)))
1874 (setf (interval-low rem) 0)
1875 (when (numberp (interval-high rem))
1876 ;; The remainder never contains the lower bound.
1877 (setf (interval-high rem) (list (interval-high rem))))
1880 ;; The divisor can be positive or negative. All bets off. The
1881 ;; magnitude of remainder is the maximum value of the divisor.
1882 (let ((limit (type-bound-number (interval-high (interval-abs div)))))
1883 ;; The bound never reaches the limit, so make the interval open.
1884 (make-interval :low (if limit
1887 :high (list limit))))))
1890 (ceiling-quotient-bound (make-interval :low 0.3 :high 10.3))
1891 => #S(INTERVAL :LOW 1 :HIGH 11)
1892 (ceiling-quotient-bound (make-interval :low 0.3 :high '(10.3)))
1893 => #S(INTERVAL :LOW 1 :HIGH 11)
1894 (ceiling-quotient-bound (make-interval :low 0.3 :high 10))
1895 => #S(INTERVAL :LOW 1 :HIGH 10)
1896 (ceiling-quotient-bound (make-interval :low 0.3 :high '(10)))
1897 => #S(INTERVAL :LOW 1 :HIGH 10)
1898 (ceiling-quotient-bound (make-interval :low '(0.3) :high 10.3))
1899 => #S(INTERVAL :LOW 1 :HIGH 11)
1900 (ceiling-quotient-bound (make-interval :low '(0.0) :high 10.3))
1901 => #S(INTERVAL :LOW 1 :HIGH 11)
1902 (ceiling-quotient-bound (make-interval :low '(-1.3) :high 10.3))
1903 => #S(INTERVAL :LOW -1 :HIGH 11)
1904 (ceiling-quotient-bound (make-interval :low '(-1.0) :high 10.3))
1905 => #S(INTERVAL :LOW 0 :HIGH 11)
1906 (ceiling-quotient-bound (make-interval :low -1.0 :high 10.3))
1907 => #S(INTERVAL :LOW -1 :HIGH 11)
1909 (ceiling-rem-bound (make-interval :low 0.3 :high 10.3))
1910 => #S(INTERVAL :LOW (-10.3) :HIGH 0)
1911 (ceiling-rem-bound (make-interval :low 0.3 :high '(10.3)))
1912 => #S(INTERVAL :LOW 0 :HIGH '(10.3))
1913 (ceiling-rem-bound (make-interval :low -10 :high -2.3))
1914 => #S(INTERVAL :LOW 0 :HIGH (10))
1915 (ceiling-rem-bound (make-interval :low 0.3 :high 10))
1916 => #S(INTERVAL :LOW (-10) :HIGH 0)
1917 (ceiling-rem-bound (make-interval :low '(-1.3) :high 10.3))
1918 => #S(INTERVAL :LOW (-10.3) :HIGH (10.3))
1919 (ceiling-rem-bound (make-interval :low '(-20.3) :high 10.3))
1920 => #S(INTERVAL :LOW (-20.3) :HIGH (20.3))
1923 (defun truncate-quotient-bound (quot)
1924 ;; For positive quotients, truncate is exactly like floor. For
1925 ;; negative quotients, truncate is exactly like ceiling. Otherwise,
1926 ;; it's the union of the two pieces.
1927 (case (interval-range-info quot)
1930 (floor-quotient-bound quot))
1932 ;; just like CEILING
1933 (ceiling-quotient-bound quot))
1935 ;; Split the interval into positive and negative pieces, compute
1936 ;; the result for each piece and put them back together.
1937 (destructuring-bind (neg pos) (interval-split 0 quot t t)
1938 (interval-merge-pair (ceiling-quotient-bound neg)
1939 (floor-quotient-bound pos))))))
1941 (defun truncate-rem-bound (num div)
1942 ;; This is significantly more complicated than FLOOR or CEILING. We
1943 ;; need both the number and the divisor to determine the range. The
1944 ;; basic idea is to split the ranges of NUM and DEN into positive
1945 ;; and negative pieces and deal with each of the four possibilities
1947 (case (interval-range-info num)
1949 (case (interval-range-info div)
1951 (floor-rem-bound div))
1953 (ceiling-rem-bound div))
1955 (destructuring-bind (neg pos) (interval-split 0 div t t)
1956 (interval-merge-pair (truncate-rem-bound num neg)
1957 (truncate-rem-bound num pos))))))
1959 (case (interval-range-info div)
1961 (ceiling-rem-bound div))
1963 (floor-rem-bound div))
1965 (destructuring-bind (neg pos) (interval-split 0 div t t)
1966 (interval-merge-pair (truncate-rem-bound num neg)
1967 (truncate-rem-bound num pos))))))
1969 (destructuring-bind (neg pos) (interval-split 0 num t t)
1970 (interval-merge-pair (truncate-rem-bound neg div)
1971 (truncate-rem-bound pos div))))))
1974 ;;; Derive useful information about the range. Returns three values:
1975 ;;; - '+ if its positive, '- negative, or nil if it overlaps 0.
1976 ;;; - The abs of the minimal value (i.e. closest to 0) in the range.
1977 ;;; - The abs of the maximal value if there is one, or nil if it is
1979 (defun numeric-range-info (low high)
1980 (cond ((and low (not (minusp low)))
1981 (values '+ low high))
1982 ((and high (not (plusp high)))
1983 (values '- (- high) (if low (- low) nil)))
1985 (values nil 0 (and low high (max (- low) high))))))
1987 (defun integer-truncate-derive-type
1988 (number-low number-high divisor-low divisor-high)
1989 ;; The result cannot be larger in magnitude than the number, but the
1990 ;; sign might change. If we can determine the sign of either the
1991 ;; number or the divisor, we can eliminate some of the cases.
1992 (multiple-value-bind (number-sign number-min number-max)
1993 (numeric-range-info number-low number-high)
1994 (multiple-value-bind (divisor-sign divisor-min divisor-max)
1995 (numeric-range-info divisor-low divisor-high)
1996 (when (and divisor-max (zerop divisor-max))
1997 ;; We've got a problem: guaranteed division by zero.
1998 (return-from integer-truncate-derive-type t))
1999 (when (zerop divisor-min)
2000 ;; We'll assume that they aren't going to divide by zero.
2002 (cond ((and number-sign divisor-sign)
2003 ;; We know the sign of both.
2004 (if (eq number-sign divisor-sign)
2005 ;; Same sign, so the result will be positive.
2006 `(integer ,(if divisor-max
2007 (truncate number-min divisor-max)
2010 (truncate number-max divisor-min)
2012 ;; Different signs, the result will be negative.
2013 `(integer ,(if number-max
2014 (- (truncate number-max divisor-min))
2017 (- (truncate number-min divisor-max))
2019 ((eq divisor-sign '+)
2020 ;; The divisor is positive. Therefore, the number will just
2021 ;; become closer to zero.
2022 `(integer ,(if number-low
2023 (truncate number-low divisor-min)
2026 (truncate number-high divisor-min)
2028 ((eq divisor-sign '-)
2029 ;; The divisor is negative. Therefore, the absolute value of
2030 ;; the number will become closer to zero, but the sign will also
2032 `(integer ,(if number-high
2033 (- (truncate number-high divisor-min))
2036 (- (truncate number-low divisor-min))
2038 ;; The divisor could be either positive or negative.
2040 ;; The number we are dividing has a bound. Divide that by the
2041 ;; smallest posible divisor.
2042 (let ((bound (truncate number-max divisor-min)))
2043 `(integer ,(- bound) ,bound)))
2045 ;; The number we are dividing is unbounded, so we can't tell
2046 ;; anything about the result.
2049 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2050 (defun integer-rem-derive-type
2051 (number-low number-high divisor-low divisor-high)
2052 (if (and divisor-low divisor-high)
2053 ;; We know the range of the divisor, and the remainder must be
2054 ;; smaller than the divisor. We can tell the sign of the
2055 ;; remainer if we know the sign of the number.
2056 (let ((divisor-max (1- (max (abs divisor-low) (abs divisor-high)))))
2057 `(integer ,(if (or (null number-low)
2058 (minusp number-low))
2061 ,(if (or (null number-high)
2062 (plusp number-high))
2065 ;; The divisor is potentially either very positive or very
2066 ;; negative. Therefore, the remainer is unbounded, but we might
2067 ;; be able to tell something about the sign from the number.
2068 `(integer ,(if (and number-low (not (minusp number-low)))
2069 ;; The number we are dividing is positive.
2070 ;; Therefore, the remainder must be positive.
2073 ,(if (and number-high (not (plusp number-high)))
2074 ;; The number we are dividing is negative.
2075 ;; Therefore, the remainder must be negative.
2079 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2080 (defoptimizer (random derive-type) ((bound &optional state))
2081 (let ((type (continuation-type bound)))
2082 (when (numeric-type-p type)
2083 (let ((class (numeric-type-class type))
2084 (high (numeric-type-high type))
2085 (format (numeric-type-format type)))
2089 :low (coerce 0 (or format class 'real))
2090 :high (cond ((not high) nil)
2091 ((eq class 'integer) (max (1- high) 0))
2092 ((or (consp high) (zerop high)) high)
2095 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2096 (defun random-derive-type-aux (type)
2097 (let ((class (numeric-type-class type))
2098 (high (numeric-type-high type))
2099 (format (numeric-type-format type)))
2103 :low (coerce 0 (or format class 'real))
2104 :high (cond ((not high) nil)
2105 ((eq class 'integer) (max (1- high) 0))
2106 ((or (consp high) (zerop high)) high)
2109 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2110 (defoptimizer (random derive-type) ((bound &optional state))
2111 (one-arg-derive-type bound #'random-derive-type-aux nil))
2113 ;;;; DERIVE-TYPE methods for LOGAND, LOGIOR, and friends
2115 ;;; Return the maximum number of bits an integer of the supplied type
2116 ;;; can take up, or NIL if it is unbounded. The second (third) value
2117 ;;; is T if the integer can be positive (negative) and NIL if not.
2118 ;;; Zero counts as positive.
2119 (defun integer-type-length (type)
2120 (if (numeric-type-p type)
2121 (let ((min (numeric-type-low type))
2122 (max (numeric-type-high type)))
2123 (values (and min max (max (integer-length min) (integer-length max)))
2124 (or (null max) (not (minusp max)))
2125 (or (null min) (minusp min))))
2128 (defun logand-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 (declare (ignore x-pos))
2132 (multiple-value-bind (y-len y-pos y-neg) (integer-type-length y)
2133 (declare (ignore y-pos))
2135 ;; X must be positive.
2137 ;; They must both be positive.
2138 (cond ((or (null x-len) (null y-len))
2139 (specifier-type 'unsigned-byte))
2140 ((or (zerop x-len) (zerop y-len))
2141 (specifier-type '(integer 0 0)))
2143 (specifier-type `(unsigned-byte ,(min x-len y-len)))))
2144 ;; X is positive, but Y might be negative.
2146 (specifier-type 'unsigned-byte))
2148 (specifier-type '(integer 0 0)))
2150 (specifier-type `(unsigned-byte ,x-len)))))
2151 ;; X might be negative.
2153 ;; Y must be positive.
2155 (specifier-type 'unsigned-byte))
2157 (specifier-type '(integer 0 0)))
2160 `(unsigned-byte ,y-len))))
2161 ;; Either might be negative.
2162 (if (and x-len y-len)
2163 ;; The result is bounded.
2164 (specifier-type `(signed-byte ,(1+ (max x-len y-len))))
2165 ;; We can't tell squat about the result.
2166 (specifier-type 'integer)))))))
2168 (defun logior-derive-type-aux (x y &optional same-leaf)
2169 (declare (ignore same-leaf))
2170 (multiple-value-bind (x-len x-pos x-neg) (integer-type-length x)
2171 (multiple-value-bind (y-len y-pos y-neg) (integer-type-length y)
2173 ((and (not x-neg) (not y-neg))
2174 ;; Both are positive.
2175 (if (and x-len y-len (zerop x-len) (zerop y-len))
2176 (specifier-type '(integer 0 0))
2177 (specifier-type `(unsigned-byte ,(if (and x-len y-len)
2181 ;; X must be negative.
2183 ;; Both are negative. The result is going to be negative
2184 ;; and be the same length or shorter than the smaller.
2185 (if (and x-len y-len)
2187 (specifier-type `(integer ,(ash -1 (min x-len y-len)) -1))
2189 (specifier-type '(integer * -1)))
2190 ;; X is negative, but we don't know about Y. The result
2191 ;; will be negative, but no more negative than X.
2193 `(integer ,(or (numeric-type-low x) '*)
2196 ;; X might be either positive or negative.
2198 ;; But Y is negative. The result will be negative.
2200 `(integer ,(or (numeric-type-low y) '*)
2202 ;; We don't know squat about either. It won't get any bigger.
2203 (if (and x-len y-len)
2205 (specifier-type `(signed-byte ,(1+ (max x-len y-len))))
2207 (specifier-type 'integer))))))))
2209 (defun logxor-derive-type-aux (x y &optional same-leaf)
2210 (declare (ignore same-leaf))
2211 (multiple-value-bind (x-len x-pos x-neg) (integer-type-length x)
2212 (multiple-value-bind (y-len y-pos y-neg) (integer-type-length y)
2214 ((or (and (not x-neg) (not y-neg))
2215 (and (not x-pos) (not y-pos)))
2216 ;; Either both are negative or both are positive. The result
2217 ;; will be positive, and as long as the longer.
2218 (if (and x-len y-len (zerop x-len) (zerop y-len))
2219 (specifier-type '(integer 0 0))
2220 (specifier-type `(unsigned-byte ,(if (and x-len y-len)
2223 ((or (and (not x-pos) (not y-neg))
2224 (and (not y-neg) (not y-pos)))
2225 ;; Either X is negative and Y is positive of vice-versa. The
2226 ;; result will be negative.
2227 (specifier-type `(integer ,(if (and x-len y-len)
2228 (ash -1 (max x-len y-len))
2231 ;; We can't tell what the sign of the result is going to be.
2232 ;; All we know is that we don't create new bits.
2234 (specifier-type `(signed-byte ,(1+ (max x-len y-len)))))
2236 (specifier-type 'integer))))))
2238 (macrolet ((deffrob (logfun)
2239 (let ((fun-aux (symbolicate logfun "-DERIVE-TYPE-AUX")))
2240 `(defoptimizer (,logfun derive-type) ((x y))
2241 (two-arg-derive-type x y #',fun-aux #',logfun)))))
2246 ;;;; miscellaneous derive-type methods
2248 (defoptimizer (integer-length derive-type) ((x))
2249 (let ((x-type (continuation-type x)))
2250 (when (and (numeric-type-p x-type)
2251 (csubtypep x-type (specifier-type 'integer)))
2252 ;; If the X is of type (INTEGER LO HI), then the INTEGER-LENGTH
2253 ;; of X is (INTEGER (MIN lo hi) (MAX lo hi), basically. Be
2254 ;; careful about LO or HI being NIL, though. Also, if 0 is
2255 ;; contained in X, the lower bound is obviously 0.
2256 (flet ((null-or-min (a b)
2257 (and a b (min (integer-length a)
2258 (integer-length b))))
2260 (and a b (max (integer-length a)
2261 (integer-length b)))))
2262 (let* ((min (numeric-type-low x-type))
2263 (max (numeric-type-high x-type))
2264 (min-len (null-or-min min max))
2265 (max-len (null-or-max min max)))
2266 (when (ctypep 0 x-type)
2268 (specifier-type `(integer ,(or min-len '*) ,(or max-len '*))))))))
2270 (defoptimizer (code-char derive-type) ((code))
2271 (specifier-type 'base-char))
2273 (defoptimizer (values derive-type) ((&rest values))
2274 (make-values-type :required (mapcar #'continuation-type values)))
2276 ;;;; byte operations
2278 ;;;; We try to turn byte operations into simple logical operations.
2279 ;;;; First, we convert byte specifiers into separate size and position
2280 ;;;; arguments passed to internal %FOO functions. We then attempt to
2281 ;;;; transform the %FOO functions into boolean operations when the
2282 ;;;; size and position are constant and the operands are fixnums.
2284 (macrolet (;; Evaluate body with SIZE-VAR and POS-VAR bound to
2285 ;; expressions that evaluate to the SIZE and POSITION of
2286 ;; the byte-specifier form SPEC. We may wrap a let around
2287 ;; the result of the body to bind some variables.
2289 ;; If the spec is a BYTE form, then bind the vars to the
2290 ;; subforms. otherwise, evaluate SPEC and use the BYTE-SIZE
2291 ;; and BYTE-POSITION. The goal of this transformation is to
2292 ;; avoid consing up byte specifiers and then immediately
2293 ;; throwing them away.
2294 (with-byte-specifier ((size-var pos-var spec) &body body)
2295 (once-only ((spec `(macroexpand ,spec))
2297 `(if (and (consp ,spec)
2298 (eq (car ,spec) 'byte)
2299 (= (length ,spec) 3))
2300 (let ((,size-var (second ,spec))
2301 (,pos-var (third ,spec)))
2303 (let ((,size-var `(byte-size ,,temp))
2304 (,pos-var `(byte-position ,,temp)))
2305 `(let ((,,temp ,,spec))
2308 (define-source-transform ldb (spec int)
2309 (with-byte-specifier (size pos spec)
2310 `(%ldb ,size ,pos ,int)))
2312 (define-source-transform dpb (newbyte spec int)
2313 (with-byte-specifier (size pos spec)
2314 `(%dpb ,newbyte ,size ,pos ,int)))
2316 (define-source-transform mask-field (spec int)
2317 (with-byte-specifier (size pos spec)
2318 `(%mask-field ,size ,pos ,int)))
2320 (define-source-transform deposit-field (newbyte spec int)
2321 (with-byte-specifier (size pos spec)
2322 `(%deposit-field ,newbyte ,size ,pos ,int))))
2324 (defoptimizer (%ldb derive-type) ((size posn num))
2325 (let ((size (continuation-type size)))
2326 (if (and (numeric-type-p size)
2327 (csubtypep size (specifier-type 'integer)))
2328 (let ((size-high (numeric-type-high size)))
2329 (if (and size-high (<= size-high sb!vm:n-word-bits))
2330 (specifier-type `(unsigned-byte ,size-high))
2331 (specifier-type 'unsigned-byte)))
2334 (defoptimizer (%mask-field derive-type) ((size posn num))
2335 (let ((size (continuation-type size))
2336 (posn (continuation-type posn)))
2337 (if (and (numeric-type-p size)
2338 (csubtypep size (specifier-type 'integer))
2339 (numeric-type-p posn)
2340 (csubtypep posn (specifier-type 'integer)))
2341 (let ((size-high (numeric-type-high size))
2342 (posn-high (numeric-type-high posn)))
2343 (if (and size-high posn-high
2344 (<= (+ size-high posn-high) sb!vm:n-word-bits))
2345 (specifier-type `(unsigned-byte ,(+ size-high posn-high)))
2346 (specifier-type 'unsigned-byte)))
2349 (defoptimizer (%dpb derive-type) ((newbyte size posn int))
2350 (let ((size (continuation-type size))
2351 (posn (continuation-type posn))
2352 (int (continuation-type int)))
2353 (if (and (numeric-type-p size)
2354 (csubtypep size (specifier-type 'integer))
2355 (numeric-type-p posn)
2356 (csubtypep posn (specifier-type 'integer))
2357 (numeric-type-p int)
2358 (csubtypep int (specifier-type 'integer)))
2359 (let ((size-high (numeric-type-high size))
2360 (posn-high (numeric-type-high posn))
2361 (high (numeric-type-high int))
2362 (low (numeric-type-low int)))
2363 (if (and size-high posn-high high low
2364 (<= (+ size-high posn-high) sb!vm:n-word-bits))
2366 (list (if (minusp low) 'signed-byte 'unsigned-byte)
2367 (max (integer-length high)
2368 (integer-length low)
2369 (+ size-high posn-high))))
2373 (defoptimizer (%deposit-field derive-type) ((newbyte size posn int))
2374 (let ((size (continuation-type size))
2375 (posn (continuation-type posn))
2376 (int (continuation-type int)))
2377 (if (and (numeric-type-p size)
2378 (csubtypep size (specifier-type 'integer))
2379 (numeric-type-p posn)
2380 (csubtypep posn (specifier-type 'integer))
2381 (numeric-type-p int)
2382 (csubtypep int (specifier-type 'integer)))
2383 (let ((size-high (numeric-type-high size))
2384 (posn-high (numeric-type-high posn))
2385 (high (numeric-type-high int))
2386 (low (numeric-type-low int)))
2387 (if (and size-high posn-high high low
2388 (<= (+ size-high posn-high) sb!vm:n-word-bits))
2390 (list (if (minusp low) 'signed-byte 'unsigned-byte)
2391 (max (integer-length high)
2392 (integer-length low)
2393 (+ size-high posn-high))))
2397 (deftransform %ldb ((size posn int)
2398 (fixnum fixnum integer)
2399 (unsigned-byte #.sb!vm:n-word-bits))
2400 "convert to inline logical operations"
2401 `(logand (ash int (- posn))
2402 (ash ,(1- (ash 1 sb!vm:n-word-bits))
2403 (- size ,sb!vm:n-word-bits))))
2405 (deftransform %mask-field ((size posn int)
2406 (fixnum fixnum integer)
2407 (unsigned-byte #.sb!vm:n-word-bits))
2408 "convert to inline logical operations"
2410 (ash (ash ,(1- (ash 1 sb!vm:n-word-bits))
2411 (- size ,sb!vm:n-word-bits))
2414 ;;; Note: for %DPB and %DEPOSIT-FIELD, we can't use
2415 ;;; (OR (SIGNED-BYTE N) (UNSIGNED-BYTE N))
2416 ;;; as the result type, as that would allow result types that cover
2417 ;;; the range -2^(n-1) .. 1-2^n, instead of allowing result types of
2418 ;;; (UNSIGNED-BYTE N) and result types of (SIGNED-BYTE N).
2420 (deftransform %dpb ((new size posn int)
2422 (unsigned-byte #.sb!vm:n-word-bits))
2423 "convert to inline logical operations"
2424 `(let ((mask (ldb (byte size 0) -1)))
2425 (logior (ash (logand new mask) posn)
2426 (logand int (lognot (ash mask posn))))))
2428 (deftransform %dpb ((new size posn int)
2430 (signed-byte #.sb!vm:n-word-bits))
2431 "convert to inline logical operations"
2432 `(let ((mask (ldb (byte size 0) -1)))
2433 (logior (ash (logand new mask) posn)
2434 (logand int (lognot (ash mask posn))))))
2436 (deftransform %deposit-field ((new size posn int)
2438 (unsigned-byte #.sb!vm:n-word-bits))
2439 "convert to inline logical operations"
2440 `(let ((mask (ash (ldb (byte size 0) -1) posn)))
2441 (logior (logand new mask)
2442 (logand int (lognot mask)))))
2444 (deftransform %deposit-field ((new size posn int)
2446 (signed-byte #.sb!vm:n-word-bits))
2447 "convert to inline logical operations"
2448 `(let ((mask (ash (ldb (byte size 0) -1) posn)))
2449 (logior (logand new mask)
2450 (logand int (lognot mask)))))
2452 ;;; Modular functions
2454 ;;; (ldb (byte s 0) (foo x y ...)) =
2455 ;;; (ldb (byte s 0) (foo (ldb (byte s 0) x) y ...))
2457 ;;; and similar for other arguments.
2459 ;;; Try to recursively cut all uses of the continuation CONT to WIDTH
2462 ;;; For good functions, we just recursively cut arguments; their
2463 ;;; "goodness" means that the result will not increase (in the
2464 ;;; (unsigned-byte +infinity) sense). An ordinary modular function is
2465 ;;; replaced with the version, cutting its result to WIDTH or more
2466 ;;; bits. If we have changed anything, we need to flush old derived
2467 ;;; types, because they have nothing in common with the new code.
2468 (defun cut-to-width (cont width)
2469 (declare (type continuation cont) (type (integer 0) width))
2470 (labels ((reoptimize-node (node name)
2471 (setf (node-derived-type node)
2473 (info :function :type name)))
2474 (setf (continuation-%derived-type (node-cont node)) nil)
2475 (setf (node-reoptimize node) t)
2476 (setf (block-reoptimize (node-block node)) t)
2477 (setf (component-reoptimize (node-component node)) t))
2478 (cut-node (node &aux did-something)
2479 (when (and (combination-p node)
2480 (fun-info-p (basic-combination-kind node)))
2481 (let* ((fun-ref (continuation-use (combination-fun node)))
2482 (fun-name (leaf-source-name (ref-leaf fun-ref)))
2483 (modular-fun (find-modular-version fun-name width))
2484 (name (and (modular-fun-info-p modular-fun)
2485 (modular-fun-info-name modular-fun))))
2486 (when (and modular-fun
2487 (not (and (eq name 'logand)
2489 (single-value-type (node-derived-type node))
2490 (specifier-type `(unsigned-byte ,width))))))
2491 (unless (eq modular-fun :good)
2492 (setq did-something t)
2495 (find-free-fun name "in a strange place"))
2496 (setf (combination-kind node) :full))
2497 (dolist (arg (basic-combination-args node))
2498 (when (cut-continuation arg)
2499 (setq did-something t)))
2501 (reoptimize-node node fun-name))
2503 (cut-continuation (cont &aux did-something)
2504 (do-uses (node cont)
2505 (when (cut-node node)
2506 (setq did-something t)))
2508 (cut-continuation cont)))
2510 (defoptimizer (logand optimizer) ((x y) node)
2511 (let ((result-type (single-value-type (node-derived-type node))))
2512 (when (numeric-type-p result-type)
2513 (let ((low (numeric-type-low result-type))
2514 (high (numeric-type-high result-type)))
2515 (when (and (numberp low)
2518 (let ((width (integer-length high)))
2519 (when (some (lambda (x) (<= width x))
2520 *modular-funs-widths*)
2521 ;; FIXME: This should be (CUT-TO-WIDTH NODE WIDTH).
2522 (cut-to-width x width)
2523 (cut-to-width y width)
2524 nil ; After fixing above, replace with T.
2527 ;;; miscellanous numeric transforms
2529 ;;; If a constant appears as the first arg, swap the args.
2530 (deftransform commutative-arg-swap ((x y) * * :defun-only t :node node)
2531 (if (and (constant-continuation-p x)
2532 (not (constant-continuation-p y)))
2533 `(,(continuation-fun-name (basic-combination-fun node))
2535 ,(continuation-value x))
2536 (give-up-ir1-transform)))
2538 (dolist (x '(= char= + * logior logand logxor))
2539 (%deftransform x '(function * *) #'commutative-arg-swap
2540 "place constant arg last"))
2542 ;;; Handle the case of a constant BOOLE-CODE.
2543 (deftransform boole ((op x y) * *)
2544 "convert to inline logical operations"
2545 (unless (constant-continuation-p op)
2546 (give-up-ir1-transform "BOOLE code is not a constant."))
2547 (let ((control (continuation-value op)))
2553 (#.boole-c1 '(lognot x))
2554 (#.boole-c2 '(lognot y))
2555 (#.boole-and '(logand x y))
2556 (#.boole-ior '(logior x y))
2557 (#.boole-xor '(logxor x y))
2558 (#.boole-eqv '(logeqv x y))
2559 (#.boole-nand '(lognand x y))
2560 (#.boole-nor '(lognor x y))
2561 (#.boole-andc1 '(logandc1 x y))
2562 (#.boole-andc2 '(logandc2 x y))
2563 (#.boole-orc1 '(logorc1 x y))
2564 (#.boole-orc2 '(logorc2 x y))
2566 (abort-ir1-transform "~S is an illegal control arg to BOOLE."
2569 ;;;; converting special case multiply/divide to shifts
2571 ;;; If arg is a constant power of two, turn * into a shift.
2572 (deftransform * ((x y) (integer integer) *)
2573 "convert x*2^k to shift"
2574 (unless (constant-continuation-p y)
2575 (give-up-ir1-transform))
2576 (let* ((y (continuation-value y))
2578 (len (1- (integer-length y-abs))))
2579 (unless (= y-abs (ash 1 len))
2580 (give-up-ir1-transform))
2585 ;;; If arg is a constant power of two, turn FLOOR into a shift and
2586 ;;; mask. If CEILING, add in (1- (ABS Y)), do FLOOR and correct a
2588 (flet ((frob (y ceil-p)
2589 (unless (constant-continuation-p y)
2590 (give-up-ir1-transform))
2591 (let* ((y (continuation-value y))
2593 (len (1- (integer-length y-abs))))
2594 (unless (= y-abs (ash 1 len))
2595 (give-up-ir1-transform))
2596 (let ((shift (- len))
2598 (delta (if ceil-p (* (signum y) (1- y-abs)) 0)))
2599 `(let ((x (+ x ,delta)))
2601 `(values (ash (- x) ,shift)
2602 (- (- (logand (- x) ,mask)) ,delta))
2603 `(values (ash x ,shift)
2604 (- (logand x ,mask) ,delta))))))))
2605 (deftransform floor ((x y) (integer integer) *)
2606 "convert division by 2^k to shift"
2608 (deftransform ceiling ((x y) (integer integer) *)
2609 "convert division by 2^k to shift"
2612 ;;; Do the same for MOD.
2613 (deftransform mod ((x y) (integer integer) *)
2614 "convert remainder mod 2^k to LOGAND"
2615 (unless (constant-continuation-p y)
2616 (give-up-ir1-transform))
2617 (let* ((y (continuation-value y))
2619 (len (1- (integer-length y-abs))))
2620 (unless (= y-abs (ash 1 len))
2621 (give-up-ir1-transform))
2622 (let ((mask (1- y-abs)))
2624 `(- (logand (- x) ,mask))
2625 `(logand x ,mask)))))
2627 ;;; If arg is a constant power of two, turn TRUNCATE into a shift and mask.
2628 (deftransform truncate ((x y) (integer integer))
2629 "convert division by 2^k to shift"
2630 (unless (constant-continuation-p y)
2631 (give-up-ir1-transform))
2632 (let* ((y (continuation-value y))
2634 (len (1- (integer-length y-abs))))
2635 (unless (= y-abs (ash 1 len))
2636 (give-up-ir1-transform))
2637 (let* ((shift (- len))
2640 (values ,(if (minusp y)
2642 `(- (ash (- x) ,shift)))
2643 (- (logand (- x) ,mask)))
2644 (values ,(if (minusp y)
2645 `(- (ash (- x) ,shift))
2647 (logand x ,mask))))))
2649 ;;; And the same for REM.
2650 (deftransform rem ((x y) (integer integer) *)
2651 "convert remainder mod 2^k to LOGAND"
2652 (unless (constant-continuation-p y)
2653 (give-up-ir1-transform))
2654 (let* ((y (continuation-value y))
2656 (len (1- (integer-length y-abs))))
2657 (unless (= y-abs (ash 1 len))
2658 (give-up-ir1-transform))
2659 (let ((mask (1- y-abs)))
2661 (- (logand (- x) ,mask))
2662 (logand x ,mask)))))
2664 ;;;; arithmetic and logical identity operation elimination
2666 ;;; Flush calls to various arith functions that convert to the
2667 ;;; identity function or a constant.
2668 (macrolet ((def (name identity result)
2669 `(deftransform ,name ((x y) (* (constant-arg (member ,identity))) *)
2670 "fold identity operations"
2677 (def logxor -1 (lognot x))
2680 (deftransform logand ((x y) (* (constant-arg t)) *)
2681 "fold identity operation"
2682 (let ((y (continuation-value y)))
2683 (unless (and (plusp y)
2684 (= y (1- (ash 1 (integer-length y)))))
2685 (give-up-ir1-transform))
2686 (unless (csubtypep (continuation-type x)
2687 (specifier-type `(integer 0 ,y)))
2688 (give-up-ir1-transform))
2691 ;;; These are restricted to rationals, because (- 0 0.0) is 0.0, not -0.0, and
2692 ;;; (* 0 -4.0) is -0.0.
2693 (deftransform - ((x y) ((constant-arg (member 0)) rational) *)
2694 "convert (- 0 x) to negate"
2696 (deftransform * ((x y) (rational (constant-arg (member 0))) *)
2697 "convert (* x 0) to 0"
2700 ;;; Return T if in an arithmetic op including continuations X and Y,
2701 ;;; the result type is not affected by the type of X. That is, Y is at
2702 ;;; least as contagious as X.
2704 (defun not-more-contagious (x y)
2705 (declare (type continuation x y))
2706 (let ((x (continuation-type x))
2707 (y (continuation-type y)))
2708 (values (type= (numeric-contagion x y)
2709 (numeric-contagion y y)))))
2710 ;;; Patched version by Raymond Toy. dtc: Should be safer although it
2711 ;;; XXX needs more work as valid transforms are missed; some cases are
2712 ;;; specific to particular transform functions so the use of this
2713 ;;; function may need a re-think.
2714 (defun not-more-contagious (x y)
2715 (declare (type continuation x y))
2716 (flet ((simple-numeric-type (num)
2717 (and (numeric-type-p num)
2718 ;; Return non-NIL if NUM is integer, rational, or a float
2719 ;; of some type (but not FLOAT)
2720 (case (numeric-type-class num)
2724 (numeric-type-format num))
2727 (let ((x (continuation-type x))
2728 (y (continuation-type y)))
2729 (if (and (simple-numeric-type x)
2730 (simple-numeric-type y))
2731 (values (type= (numeric-contagion x y)
2732 (numeric-contagion y y)))))))
2736 ;;; If y is not constant, not zerop, or is contagious, or a positive
2737 ;;; float +0.0 then give up.
2738 (deftransform + ((x y) (t (constant-arg t)) *)
2740 (let ((val (continuation-value y)))
2741 (unless (and (zerop val)
2742 (not (and (floatp val) (plusp (float-sign val))))
2743 (not-more-contagious y x))
2744 (give-up-ir1-transform)))
2749 ;;; If y is not constant, not zerop, or is contagious, or a negative
2750 ;;; float -0.0 then give up.
2751 (deftransform - ((x y) (t (constant-arg t)) *)
2753 (let ((val (continuation-value y)))
2754 (unless (and (zerop val)
2755 (not (and (floatp val) (minusp (float-sign val))))
2756 (not-more-contagious y x))
2757 (give-up-ir1-transform)))
2760 ;;; Fold (OP x +/-1)
2761 (macrolet ((def (name result minus-result)
2762 `(deftransform ,name ((x y) (t (constant-arg real)) *)
2763 "fold identity operations"
2764 (let ((val (continuation-value y)))
2765 (unless (and (= (abs val) 1)
2766 (not-more-contagious y x))
2767 (give-up-ir1-transform))
2768 (if (minusp val) ',minus-result ',result)))))
2769 (def * x (%negate x))
2770 (def / x (%negate x))
2771 (def expt x (/ 1 x)))
2773 ;;; Fold (expt x n) into multiplications for small integral values of
2774 ;;; N; convert (expt x 1/2) to sqrt.
2775 (deftransform expt ((x y) (t (constant-arg real)) *)
2776 "recode as multiplication or sqrt"
2777 (let ((val (continuation-value y)))
2778 ;; If Y would cause the result to be promoted to the same type as
2779 ;; Y, we give up. If not, then the result will be the same type
2780 ;; as X, so we can replace the exponentiation with simple
2781 ;; multiplication and division for small integral powers.
2782 (unless (not-more-contagious y x)
2783 (give-up-ir1-transform))
2785 (let ((x-type (continuation-type x)))
2786 (cond ((csubtypep x-type (specifier-type '(or rational
2787 (complex rational))))
2789 ((csubtypep x-type (specifier-type 'real))
2793 ((csubtypep x-type (specifier-type 'complex))
2794 ;; both parts are float
2796 (t (give-up-ir1-transform)))))
2797 ((= val 2) '(* x x))
2798 ((= val -2) '(/ (* x x)))
2799 ((= val 3) '(* x x x))
2800 ((= val -3) '(/ (* x x x)))
2801 ((= val 1/2) '(sqrt x))
2802 ((= val -1/2) '(/ (sqrt x)))
2803 (t (give-up-ir1-transform)))))
2805 ;;; KLUDGE: Shouldn't (/ 0.0 0.0), etc. cause exceptions in these
2806 ;;; transformations?
2807 ;;; Perhaps we should have to prove that the denominator is nonzero before
2808 ;;; doing them? -- WHN 19990917
2809 (macrolet ((def (name)
2810 `(deftransform ,name ((x y) ((constant-arg (integer 0 0)) integer)
2817 (macrolet ((def (name)
2818 `(deftransform ,name ((x y) ((constant-arg (integer 0 0)) integer)
2827 ;;;; character operations
2829 (deftransform char-equal ((a b) (base-char base-char))
2831 '(let* ((ac (char-code a))
2833 (sum (logxor ac bc)))
2835 (when (eql sum #x20)
2836 (let ((sum (+ ac bc)))
2837 (and (> sum 161) (< sum 213)))))))
2839 (deftransform char-upcase ((x) (base-char))
2841 '(let ((n-code (char-code x)))
2842 (if (and (> n-code #o140) ; Octal 141 is #\a.
2843 (< n-code #o173)) ; Octal 172 is #\z.
2844 (code-char (logxor #x20 n-code))
2847 (deftransform char-downcase ((x) (base-char))
2849 '(let ((n-code (char-code x)))
2850 (if (and (> n-code 64) ; 65 is #\A.
2851 (< n-code 91)) ; 90 is #\Z.
2852 (code-char (logxor #x20 n-code))
2855 ;;;; equality predicate transforms
2857 ;;; Return true if X and Y are continuations whose only use is a
2858 ;;; reference to the same leaf, and the value of the leaf cannot
2860 (defun same-leaf-ref-p (x y)
2861 (declare (type continuation x y))
2862 (let ((x-use (principal-continuation-use x))
2863 (y-use (principal-continuation-use y)))
2866 (eq (ref-leaf x-use) (ref-leaf y-use))
2867 (constant-reference-p x-use))))
2869 ;;; If X and Y are the same leaf, then the result is true. Otherwise,
2870 ;;; if there is no intersection between the types of the arguments,
2871 ;;; then the result is definitely false.
2872 (deftransform simple-equality-transform ((x y) * *
2874 (cond ((same-leaf-ref-p x y)
2876 ((not (types-equal-or-intersect (continuation-type x)
2877 (continuation-type y)))
2880 (give-up-ir1-transform))))
2883 `(%deftransform ',x '(function * *) #'simple-equality-transform)))
2888 ;;; This is similar to SIMPLE-EQUALITY-PREDICATE, except that we also
2889 ;;; try to convert to a type-specific predicate or EQ:
2890 ;;; -- If both args are characters, convert to CHAR=. This is better than
2891 ;;; just converting to EQ, since CHAR= may have special compilation
2892 ;;; strategies for non-standard representations, etc.
2893 ;;; -- If either arg is definitely not a number, then we can compare
2895 ;;; -- Otherwise, we try to put the arg we know more about second. If X
2896 ;;; is constant then we put it second. If X is a subtype of Y, we put
2897 ;;; it second. These rules make it easier for the back end to match
2898 ;;; these interesting cases.
2899 ;;; -- If Y is a fixnum, then we quietly pass because the back end can
2900 ;;; handle that case, otherwise give an efficiency note.
2901 (deftransform eql ((x y) * *)
2902 "convert to simpler equality predicate"
2903 (let ((x-type (continuation-type x))
2904 (y-type (continuation-type y))
2905 (char-type (specifier-type 'character))
2906 (number-type (specifier-type 'number)))
2907 (cond ((same-leaf-ref-p x y)
2909 ((not (types-equal-or-intersect x-type y-type))
2911 ((and (csubtypep x-type char-type)
2912 (csubtypep y-type char-type))
2914 ((or (not (types-equal-or-intersect x-type number-type))
2915 (not (types-equal-or-intersect y-type number-type)))
2917 ((and (not (constant-continuation-p y))
2918 (or (constant-continuation-p x)
2919 (and (csubtypep x-type y-type)
2920 (not (csubtypep y-type x-type)))))
2923 (give-up-ir1-transform)))))
2925 ;;; Convert to EQL if both args are rational and complexp is specified
2926 ;;; and the same for both.
2927 (deftransform = ((x y) * *)
2929 (let ((x-type (continuation-type x))
2930 (y-type (continuation-type y)))
2931 (if (and (csubtypep x-type (specifier-type 'number))
2932 (csubtypep y-type (specifier-type 'number)))
2933 (cond ((or (and (csubtypep x-type (specifier-type 'float))
2934 (csubtypep y-type (specifier-type 'float)))
2935 (and (csubtypep x-type (specifier-type '(complex float)))
2936 (csubtypep y-type (specifier-type '(complex float)))))
2937 ;; They are both floats. Leave as = so that -0.0 is
2938 ;; handled correctly.
2939 (give-up-ir1-transform))
2940 ((or (and (csubtypep x-type (specifier-type 'rational))
2941 (csubtypep y-type (specifier-type 'rational)))
2942 (and (csubtypep x-type
2943 (specifier-type '(complex rational)))
2945 (specifier-type '(complex rational)))))
2946 ;; They are both rationals and complexp is the same.
2950 (give-up-ir1-transform
2951 "The operands might not be the same type.")))
2952 (give-up-ir1-transform
2953 "The operands might not be the same type."))))
2955 ;;; If CONT's type is a numeric type, then return the type, otherwise
2956 ;;; GIVE-UP-IR1-TRANSFORM.
2957 (defun numeric-type-or-lose (cont)
2958 (declare (type continuation cont))
2959 (let ((res (continuation-type cont)))
2960 (unless (numeric-type-p res) (give-up-ir1-transform))
2963 ;;; See whether we can statically determine (< X Y) using type
2964 ;;; information. If X's high bound is < Y's low, then X < Y.
2965 ;;; Similarly, if X's low is >= to Y's high, the X >= Y (so return
2966 ;;; NIL). If not, at least make sure any constant arg is second.
2968 ;;; FIXME: Why should constant argument be second? It would be nice to
2969 ;;; find out and explain.
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* ((x-type (numeric-type-or-lose x))
2975 (x-lo (numeric-type-low x-type))
2976 (x-hi (numeric-type-high x-type))
2977 (y-type (numeric-type-or-lose y))
2978 (y-lo (numeric-type-low y-type))
2979 (y-hi (numeric-type-high y-type)))
2980 (cond ((and x-hi y-lo (< x-hi y-lo))
2982 ((and y-hi x-lo (>= x-lo y-hi))
2984 ((and (constant-continuation-p first)
2985 (not (constant-continuation-p second)))
2988 (give-up-ir1-transform))))))
2989 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2990 (defun ir1-transform-< (x y first second inverse)
2991 (if (same-leaf-ref-p x y)
2993 (let ((xi (numeric-type->interval (numeric-type-or-lose x)))
2994 (yi (numeric-type->interval (numeric-type-or-lose y))))
2995 (cond ((interval-< xi yi)
2997 ((interval->= xi yi)
2999 ((and (constant-continuation-p first)
3000 (not (constant-continuation-p second)))
3003 (give-up-ir1-transform))))))
3005 (deftransform < ((x y) (integer integer) *)
3006 (ir1-transform-< x y x y '>))
3008 (deftransform > ((x y) (integer integer) *)
3009 (ir1-transform-< y x x y '<))
3011 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
3012 (deftransform < ((x y) (float float) *)
3013 (ir1-transform-< x y x y '>))
3015 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
3016 (deftransform > ((x y) (float float) *)
3017 (ir1-transform-< y x x y '<))
3019 (defun ir1-transform-char< (x y first second inverse)
3021 ((same-leaf-ref-p x y) nil)
3022 ;; If we had interval representation of character types, as we
3023 ;; might eventually have to to support 2^21 characters, then here
3024 ;; we could do some compile-time computation as in IR1-TRANSFORM-<
3025 ;; above. -- CSR, 2003-07-01
3026 ((and (constant-continuation-p first)
3027 (not (constant-continuation-p second)))
3029 (t (give-up-ir1-transform))))
3031 (deftransform char< ((x y) (character character) *)
3032 (ir1-transform-char< x y x y 'char>))
3034 (deftransform char> ((x y) (character character) *)
3035 (ir1-transform-char< y x x y 'char<))
3037 ;;;; converting N-arg comparisons
3039 ;;;; We convert calls to N-arg comparison functions such as < into
3040 ;;;; two-arg calls. This transformation is enabled for all such
3041 ;;;; comparisons in this file. If any of these predicates are not
3042 ;;;; open-coded, then the transformation should be removed at some
3043 ;;;; point to avoid pessimization.
3045 ;;; This function is used for source transformation of N-arg
3046 ;;; comparison functions other than inequality. We deal both with
3047 ;;; converting to two-arg calls and inverting the sense of the test,
3048 ;;; if necessary. If the call has two args, then we pass or return a
3049 ;;; negated test as appropriate. If it is a degenerate one-arg call,
3050 ;;; then we transform to code that returns true. Otherwise, we bind
3051 ;;; all the arguments and expand into a bunch of IFs.
3052 (declaim (ftype (function (symbol list boolean t) *) multi-compare))
3053 (defun multi-compare (predicate args not-p type)
3054 (let ((nargs (length args)))
3055 (cond ((< nargs 1) (values nil t))
3056 ((= nargs 1) `(progn (the ,type ,@args) t))
3059 `(if (,predicate ,(first args) ,(second args)) nil t)
3062 (do* ((i (1- nargs) (1- i))
3064 (current (gensym) (gensym))
3065 (vars (list current) (cons current vars))
3067 `(if (,predicate ,current ,last)
3069 `(if (,predicate ,current ,last)
3072 `((lambda ,vars (declare (type ,type ,@vars)) ,result)
3075 (define-source-transform = (&rest args) (multi-compare '= args nil 'number))
3076 (define-source-transform < (&rest args) (multi-compare '< args nil 'real))
3077 (define-source-transform > (&rest args) (multi-compare '> args nil 'real))
3078 (define-source-transform <= (&rest args) (multi-compare '> args t 'real))
3079 (define-source-transform >= (&rest args) (multi-compare '< args t 'real))
3081 (define-source-transform char= (&rest args) (multi-compare 'char= args nil
3083 (define-source-transform char< (&rest args) (multi-compare 'char< args nil
3085 (define-source-transform char> (&rest args) (multi-compare 'char> args nil
3087 (define-source-transform char<= (&rest args) (multi-compare 'char> args t
3089 (define-source-transform char>= (&rest args) (multi-compare 'char< args t
3092 (define-source-transform char-equal (&rest args)
3093 (multi-compare 'char-equal args nil 'character))
3094 (define-source-transform char-lessp (&rest args)
3095 (multi-compare 'char-lessp args nil 'character))
3096 (define-source-transform char-greaterp (&rest args)
3097 (multi-compare 'char-greaterp args nil 'character))
3098 (define-source-transform char-not-greaterp (&rest args)
3099 (multi-compare 'char-greaterp args t 'character))
3100 (define-source-transform char-not-lessp (&rest args)
3101 (multi-compare 'char-lessp args t 'character))
3103 ;;; This function does source transformation of N-arg inequality
3104 ;;; functions such as /=. This is similar to MULTI-COMPARE in the <3
3105 ;;; arg cases. If there are more than two args, then we expand into
3106 ;;; the appropriate n^2 comparisons only when speed is important.
3107 (declaim (ftype (function (symbol list t) *) multi-not-equal))
3108 (defun multi-not-equal (predicate args type)
3109 (let ((nargs (length args)))
3110 (cond ((< nargs 1) (values nil t))
3111 ((= nargs 1) `(progn (the ,type ,@args) t))
3113 `(if (,predicate ,(first args) ,(second args)) nil t))
3114 ((not (policy *lexenv*
3115 (and (>= speed space)
3116 (>= speed compilation-speed))))
3119 (let ((vars (make-gensym-list nargs)))
3120 (do ((var vars next)
3121 (next (cdr vars) (cdr next))
3124 `((lambda ,vars (declare (type ,type ,@vars)) ,result)
3126 (let ((v1 (first var)))
3128 (setq result `(if (,predicate ,v1 ,v2) nil ,result))))))))))
3130 (define-source-transform /= (&rest args)
3131 (multi-not-equal '= args 'number))
3132 (define-source-transform char/= (&rest args)
3133 (multi-not-equal 'char= args 'character))
3134 (define-source-transform char-not-equal (&rest args)
3135 (multi-not-equal 'char-equal args 'character))
3137 ;;; Expand MAX and MIN into the obvious comparisons.
3138 (define-source-transform max (arg0 &rest rest)
3139 (once-only ((arg0 arg0))
3141 `(values (the real ,arg0))
3142 `(let ((maxrest (max ,@rest)))
3143 (if (> ,arg0 maxrest) ,arg0 maxrest)))))
3144 (define-source-transform min (arg0 &rest rest)
3145 (once-only ((arg0 arg0))
3147 `(values (the real ,arg0))
3148 `(let ((minrest (min ,@rest)))
3149 (if (< ,arg0 minrest) ,arg0 minrest)))))
3151 ;;;; converting N-arg arithmetic functions
3153 ;;;; N-arg arithmetic and logic functions are associated into two-arg
3154 ;;;; versions, and degenerate cases are flushed.
3156 ;;; Left-associate FIRST-ARG and MORE-ARGS using FUNCTION.
3157 (declaim (ftype (function (symbol t list) list) associate-args))
3158 (defun associate-args (function first-arg more-args)
3159 (let ((next (rest more-args))
3160 (arg (first more-args)))
3162 `(,function ,first-arg ,arg)
3163 (associate-args function `(,function ,first-arg ,arg) next))))
3165 ;;; Do source transformations for transitive functions such as +.
3166 ;;; One-arg cases are replaced with the arg and zero arg cases with
3167 ;;; the identity. ONE-ARG-RESULT-TYPE is, if non-NIL, the type to
3168 ;;; ensure (with THE) that the argument in one-argument calls is.
3169 (defun source-transform-transitive (fun args identity
3170 &optional one-arg-result-type)
3171 (declare (symbol fun leaf-fun) (list args))
3174 (1 (if one-arg-result-type
3175 `(values (the ,one-arg-result-type ,(first args)))
3176 `(values ,(first args))))
3179 (associate-args fun (first args) (rest args)))))
3181 (define-source-transform + (&rest args)
3182 (source-transform-transitive '+ args 0 'number))
3183 (define-source-transform * (&rest args)
3184 (source-transform-transitive '* args 1 'number))
3185 (define-source-transform logior (&rest args)
3186 (source-transform-transitive 'logior args 0 'integer))
3187 (define-source-transform logxor (&rest args)
3188 (source-transform-transitive 'logxor args 0 'integer))
3189 (define-source-transform logand (&rest args)
3190 (source-transform-transitive 'logand args -1 'integer))
3192 (define-source-transform logeqv (&rest args)
3193 (if (evenp (length args))
3194 `(lognot (logxor ,@args))
3197 ;;; Note: we can't use SOURCE-TRANSFORM-TRANSITIVE for GCD and LCM
3198 ;;; because when they are given one argument, they return its absolute
3201 (define-source-transform gcd (&rest args)
3204 (1 `(abs (the integer ,(first args))))
3206 (t (associate-args 'gcd (first args) (rest args)))))
3208 (define-source-transform lcm (&rest args)
3211 (1 `(abs (the integer ,(first args))))
3213 (t (associate-args 'lcm (first args) (rest args)))))
3215 ;;; Do source transformations for intransitive n-arg functions such as
3216 ;;; /. With one arg, we form the inverse. With two args we pass.
3217 ;;; Otherwise we associate into two-arg calls.
3218 (declaim (ftype (function (symbol list t)
3219 (values list &optional (member nil t)))
3220 source-transform-intransitive))
3221 (defun source-transform-intransitive (function args inverse)
3223 ((0 2) (values nil t))
3224 (1 `(,@inverse ,(first args)))
3225 (t (associate-args function (first args) (rest args)))))
3227 (define-source-transform - (&rest args)
3228 (source-transform-intransitive '- args '(%negate)))
3229 (define-source-transform / (&rest args)
3230 (source-transform-intransitive '/ args '(/ 1)))
3232 ;;;; transforming APPLY
3234 ;;; We convert APPLY into MULTIPLE-VALUE-CALL so that the compiler
3235 ;;; only needs to understand one kind of variable-argument call. It is
3236 ;;; more efficient to convert APPLY to MV-CALL than MV-CALL to APPLY.
3237 (define-source-transform apply (fun arg &rest more-args)
3238 (let ((args (cons arg more-args)))
3239 `(multiple-value-call ,fun
3240 ,@(mapcar (lambda (x)
3243 (values-list ,(car (last args))))))
3245 ;;;; transforming FORMAT
3247 ;;;; If the control string is a compile-time constant, then replace it
3248 ;;;; with a use of the FORMATTER macro so that the control string is
3249 ;;;; ``compiled.'' Furthermore, if the destination is either a stream
3250 ;;;; or T and the control string is a function (i.e. FORMATTER), then
3251 ;;;; convert the call to FORMAT to just a FUNCALL of that function.
3253 ;;; for compile-time argument count checking.
3255 ;;; FIXME I: this is currently called from DEFTRANSFORMs, the vast
3256 ;;; majority of which are not going to transform the code, but instead
3257 ;;; are going to GIVE-UP-IR1-TRANSFORM unconditionally. It would be
3258 ;;; nice to make this explicit, maybe by implementing a new
3259 ;;; "optimizer" (say, DEFOPTIMIZER CONSISTENCY-CHECK).
3261 ;;; FIXME II: In some cases, type information could be correlated; for
3262 ;;; instance, ~{ ... ~} requires a list argument, so if the
3263 ;;; continuation-type of a corresponding argument is known and does
3264 ;;; not intersect the list type, a warning could be signalled.
3265 (defun check-format-args (string args fun)
3266 (declare (type string string))
3267 (unless (typep string 'simple-string)
3268 (setq string (coerce string 'simple-string)))
3269 (multiple-value-bind (min max)
3270 (handler-case (sb!format:%compiler-walk-format-string string args)
3271 (sb!format:format-error (c)
3272 (compiler-warn "~A" c)))
3274 (let ((nargs (length args)))
3277 (compiler-warn "Too few arguments (~D) to ~S ~S: ~
3278 requires at least ~D."
3279 nargs fun string min))
3281 (;; to get warned about probably bogus code at
3282 ;; cross-compile time.
3283 #+sb-xc-host compiler-warn
3284 ;; ANSI saith that too many arguments doesn't cause a
3286 #-sb-xc-host compiler-style-warn
3287 "Too many arguments (~D) to ~S ~S: uses at most ~D."
3288 nargs fun string max)))))))
3290 (defoptimizer (format optimizer) ((dest control &rest args))
3291 (when (constant-continuation-p control)
3292 (let ((x (continuation-value control)))
3294 (check-format-args x args 'format)))))
3296 (deftransform format ((dest control &rest args) (t simple-string &rest t) *
3297 :policy (> speed space))
3298 (unless (constant-continuation-p control)
3299 (give-up-ir1-transform "The control string is not a constant."))
3300 (let ((arg-names (make-gensym-list (length args))))
3301 `(lambda (dest control ,@arg-names)
3302 (declare (ignore control))
3303 (format dest (formatter ,(continuation-value control)) ,@arg-names))))
3305 (deftransform format ((stream control &rest args) (stream function &rest t) *
3306 :policy (> speed space))
3307 (let ((arg-names (make-gensym-list (length args))))
3308 `(lambda (stream control ,@arg-names)
3309 (funcall control stream ,@arg-names)
3312 (deftransform format ((tee control &rest args) ((member t) function &rest t) *
3313 :policy (> speed space))
3314 (let ((arg-names (make-gensym-list (length args))))
3315 `(lambda (tee control ,@arg-names)
3316 (declare (ignore tee))
3317 (funcall control *standard-output* ,@arg-names)
3322 `(defoptimizer (,name optimizer) ((control &rest args))
3323 (when (constant-continuation-p control)
3324 (let ((x (continuation-value control)))
3326 (check-format-args x args ',name)))))))
3329 #+sb-xc-host ; Only we should be using these
3332 (def compiler-abort)
3333 (def compiler-error)
3335 (def compiler-style-warn)
3336 (def compiler-notify)
3337 (def maybe-compiler-notify)
3340 (defoptimizer (cerror optimizer) ((report control &rest args))
3341 (when (and (constant-continuation-p control)
3342 (constant-continuation-p report))
3343 (let ((x (continuation-value control))
3344 (y (continuation-value report)))
3345 (when (and (stringp x) (stringp y))
3346 (multiple-value-bind (min1 max1)
3348 (sb!format:%compiler-walk-format-string x args)
3349 (sb!format:format-error (c)
3350 (compiler-warn "~A" c)))
3352 (multiple-value-bind (min2 max2)
3354 (sb!format:%compiler-walk-format-string y args)
3355 (sb!format:format-error (c)
3356 (compiler-warn "~A" c)))
3358 (let ((nargs (length args)))
3360 ((< nargs (min min1 min2))
3361 (compiler-warn "Too few arguments (~D) to ~S ~S ~S: ~
3362 requires at least ~D."
3363 nargs 'cerror y x (min min1 min2)))
3364 ((> nargs (max max1 max2))
3365 (;; to get warned about probably bogus code at
3366 ;; cross-compile time.
3367 #+sb-xc-host compiler-warn
3368 ;; ANSI saith that too many arguments doesn't cause a
3370 #-sb-xc-host compiler-style-warn
3371 "Too many arguments (~D) to ~S ~S ~S: uses at most ~D."
3372 nargs 'cerror y x (max max1 max2)))))))))))))
3374 (defoptimizer (coerce derive-type) ((value type))
3376 ((constant-continuation-p type)
3377 ;; This branch is essentially (RESULT-TYPE-SPECIFIER-NTH-ARG 2),
3378 ;; but dealing with the niggle that complex canonicalization gets
3379 ;; in the way: (COERCE 1 'COMPLEX) returns 1, which is not of
3381 (let* ((specifier (continuation-value type))
3382 (result-typeoid (careful-specifier-type specifier)))
3384 ((null result-typeoid) nil)
3385 ((csubtypep result-typeoid (specifier-type 'number))
3386 ;; the difficult case: we have to cope with ANSI 12.1.5.3
3387 ;; Rule of Canonical Representation for Complex Rationals,
3388 ;; which is a truly nasty delivery to field.
3390 ((csubtypep result-typeoid (specifier-type 'real))
3391 ;; cleverness required here: it would be nice to deduce
3392 ;; that something of type (INTEGER 2 3) coerced to type
3393 ;; DOUBLE-FLOAT should return (DOUBLE-FLOAT 2.0d0 3.0d0).
3394 ;; FLOAT gets its own clause because it's implemented as
3395 ;; a UNION-TYPE, so we don't catch it in the NUMERIC-TYPE
3398 ((and (numeric-type-p result-typeoid)
3399 (eq (numeric-type-complexp result-typeoid) :real))
3400 ;; FIXME: is this clause (a) necessary or (b) useful?
3402 ((or (csubtypep result-typeoid
3403 (specifier-type '(complex single-float)))
3404 (csubtypep result-typeoid
3405 (specifier-type '(complex double-float)))
3407 (csubtypep result-typeoid
3408 (specifier-type '(complex long-float))))
3409 ;; float complex types are never canonicalized.
3412 ;; if it's not a REAL, or a COMPLEX FLOAToid, it's
3413 ;; probably just a COMPLEX or equivalent. So, in that
3414 ;; case, we will return a complex or an object of the
3415 ;; provided type if it's rational:
3416 (type-union result-typeoid
3417 (type-intersection (continuation-type value)
3418 (specifier-type 'rational))))))
3419 (t result-typeoid))))
3421 ;; OK, the result-type argument isn't constant. However, there
3422 ;; are common uses where we can still do better than just
3423 ;; *UNIVERSAL-TYPE*: e.g. (COERCE X (ARRAY-ELEMENT-TYPE Y)),
3424 ;; where Y is of a known type. See messages on cmucl-imp
3425 ;; 2001-02-14 and sbcl-devel 2002-12-12. We only worry here
3426 ;; about types that can be returned by (ARRAY-ELEMENT-TYPE Y), on
3427 ;; the basis that it's unlikely that other uses are both
3428 ;; time-critical and get to this branch of the COND (non-constant
3429 ;; second argument to COERCE). -- CSR, 2002-12-16
3430 (let ((value-type (continuation-type value))
3431 (type-type (continuation-type type)))
3433 ((good-cons-type-p (cons-type)
3434 ;; Make sure the cons-type we're looking at is something
3435 ;; we're prepared to handle which is basically something
3436 ;; that array-element-type can return.
3437 (or (and (member-type-p cons-type)
3438 (null (rest (member-type-members cons-type)))
3439 (null (first (member-type-members cons-type))))
3440 (let ((car-type (cons-type-car-type cons-type)))
3441 (and (member-type-p car-type)
3442 (null (rest (member-type-members car-type)))
3443 (or (symbolp (first (member-type-members car-type)))
3444 (numberp (first (member-type-members car-type)))
3445 (and (listp (first (member-type-members
3447 (numberp (first (first (member-type-members
3449 (good-cons-type-p (cons-type-cdr-type cons-type))))))
3450 (unconsify-type (good-cons-type)
3451 ;; Convert the "printed" respresentation of a cons
3452 ;; specifier into a type specifier. That is, the
3453 ;; specifier (CONS (EQL SIGNED-BYTE) (CONS (EQL 16)
3454 ;; NULL)) is converted to (SIGNED-BYTE 16).
3455 (cond ((or (null good-cons-type)
3456 (eq good-cons-type 'null))
3458 ((and (eq (first good-cons-type) 'cons)
3459 (eq (first (second good-cons-type)) 'member))
3460 `(,(second (second good-cons-type))
3461 ,@(unconsify-type (caddr good-cons-type))))))
3462 (coerceable-p (c-type)
3463 ;; Can the value be coerced to the given type? Coerce is
3464 ;; complicated, so we don't handle every possible case
3465 ;; here---just the most common and easiest cases:
3467 ;; * Any REAL can be coerced to a FLOAT type.
3468 ;; * Any NUMBER can be coerced to a (COMPLEX
3469 ;; SINGLE/DOUBLE-FLOAT).
3471 ;; FIXME I: we should also be able to deal with characters
3474 ;; FIXME II: I'm not sure that anything is necessary
3475 ;; here, at least while COMPLEX is not a specialized
3476 ;; array element type in the system. Reasoning: if
3477 ;; something cannot be coerced to the requested type, an
3478 ;; error will be raised (and so any downstream compiled
3479 ;; code on the assumption of the returned type is
3480 ;; unreachable). If something can, then it will be of
3481 ;; the requested type, because (by assumption) COMPLEX
3482 ;; (and other difficult types like (COMPLEX INTEGER)
3483 ;; aren't specialized types.
3484 (let ((coerced-type c-type))
3485 (or (and (subtypep coerced-type 'float)
3486 (csubtypep value-type (specifier-type 'real)))
3487 (and (subtypep coerced-type
3488 '(or (complex single-float)
3489 (complex double-float)))
3490 (csubtypep value-type (specifier-type 'number))))))
3491 (process-types (type)
3492 ;; FIXME: This needs some work because we should be able
3493 ;; to derive the resulting type better than just the
3494 ;; type arg of coerce. That is, if X is (INTEGER 10
3495 ;; 20), then (COERCE X 'DOUBLE-FLOAT) should say
3496 ;; (DOUBLE-FLOAT 10d0 20d0) instead of just
3498 (cond ((member-type-p type)
3499 (let ((members (member-type-members type)))
3500 (if (every #'coerceable-p members)
3501 (specifier-type `(or ,@members))
3503 ((and (cons-type-p type)
3504 (good-cons-type-p type))
3505 (let ((c-type (unconsify-type (type-specifier type))))
3506 (if (coerceable-p c-type)
3507 (specifier-type c-type)
3510 *universal-type*))))
3511 (cond ((union-type-p type-type)
3512 (apply #'type-union (mapcar #'process-types
3513 (union-type-types type-type))))
3514 ((or (member-type-p type-type)
3515 (cons-type-p type-type))
3516 (process-types type-type))
3518 *universal-type*)))))))
3520 (defoptimizer (compile derive-type) ((nameoid function))
3521 (when (csubtypep (continuation-type nameoid)
3522 (specifier-type 'null))
3523 (values-specifier-type '(values function boolean boolean))))
3525 ;;; FIXME: Maybe also STREAM-ELEMENT-TYPE should be given some loving
3526 ;;; treatment along these lines? (See discussion in COERCE DERIVE-TYPE
3527 ;;; optimizer, above).
3528 (defoptimizer (array-element-type derive-type) ((array))
3529 (let ((array-type (continuation-type array)))
3530 (labels ((consify (list)
3533 `(cons (eql ,(car list)) ,(consify (rest list)))))
3534 (get-element-type (a)
3536 (type-specifier (array-type-specialized-element-type a))))
3537 (cond ((eq element-type '*)
3538 (specifier-type 'type-specifier))
3539 ((symbolp element-type)
3540 (make-member-type :members (list element-type)))
3541 ((consp element-type)
3542 (specifier-type (consify element-type)))
3544 (error "can't understand type ~S~%" element-type))))))
3545 (cond ((array-type-p array-type)
3546 (get-element-type array-type))
3547 ((union-type-p array-type)
3549 (mapcar #'get-element-type (union-type-types array-type))))
3551 *universal-type*)))))
3553 (define-source-transform sb!impl::sort-vector (vector start end predicate key)
3554 `(macrolet ((%index (x) `(truly-the index ,x))
3555 (%parent (i) `(ash ,i -1))
3556 (%left (i) `(%index (ash ,i 1)))
3557 (%right (i) `(%index (1+ (ash ,i 1))))
3560 (left (%left i) (%left i)))
3561 ((> left current-heap-size))
3562 (declare (type index i left))
3563 (let* ((i-elt (%elt i))
3564 (i-key (funcall keyfun i-elt))
3565 (left-elt (%elt left))
3566 (left-key (funcall keyfun left-elt)))
3567 (multiple-value-bind (large large-elt large-key)
3568 (if (funcall ,',predicate i-key left-key)
3569 (values left left-elt left-key)
3570 (values i i-elt i-key))
3571 (let ((right (%right i)))
3572 (multiple-value-bind (largest largest-elt)
3573 (if (> right current-heap-size)
3574 (values large large-elt)
3575 (let* ((right-elt (%elt right))
3576 (right-key (funcall keyfun right-elt)))
3577 (if (funcall ,',predicate large-key right-key)
3578 (values right right-elt)
3579 (values large large-elt))))
3580 (cond ((= largest i)
3583 (setf (%elt i) largest-elt
3584 (%elt largest) i-elt
3586 (%sort-vector (keyfun &optional (vtype 'vector))
3587 `(macrolet (;; KLUDGE: In SBCL ca. 0.6.10, I had trouble getting
3588 ;; type inference to propagate all the way
3589 ;; through this tangled mess of
3590 ;; inlining. The TRULY-THE here works
3591 ;; around that. -- WHN
3593 `(aref (truly-the ,',vtype ,',',vector)
3594 (%index (+ (%index ,i) start-1)))))
3595 (let ((start-1 (1- ,',start)) ; Heaps prefer 1-based addressing.
3596 (current-heap-size (- ,',end ,',start))
3598 (declare (type (integer -1 #.(1- most-positive-fixnum))
3600 (declare (type index current-heap-size))
3601 (declare (type function keyfun))
3602 (loop for i of-type index
3603 from (ash current-heap-size -1) downto 1 do
3606 (when (< current-heap-size 2)
3608 (rotatef (%elt 1) (%elt current-heap-size))
3609 (decf current-heap-size)
3611 (if (typep ,vector 'simple-vector)
3612 ;; (VECTOR T) is worth optimizing for, and SIMPLE-VECTOR is
3613 ;; what we get from (VECTOR T) inside WITH-ARRAY-DATA.
3615 ;; Special-casing the KEY=NIL case lets us avoid some
3617 (%sort-vector #'identity simple-vector)
3618 (%sort-vector ,key simple-vector))
3619 ;; It's hard to anticipate many speed-critical applications for
3620 ;; sorting vector types other than (VECTOR T), so we just lump
3621 ;; them all together in one slow dynamically typed mess.
3623 (declare (optimize (speed 2) (space 2) (inhibit-warnings 3)))
3624 (%sort-vector (or ,key #'identity))))))
3626 ;;;; debuggers' little helpers
3628 ;;; for debugging when transforms are behaving mysteriously,
3629 ;;; e.g. when debugging a problem with an ASH transform
3630 ;;; (defun foo (&optional s)
3631 ;;; (sb-c::/report-continuation s "S outside WHEN")
3632 ;;; (when (and (integerp s) (> s 3))
3633 ;;; (sb-c::/report-continuation s "S inside WHEN")
3634 ;;; (let ((bound (ash 1 (1- s))))
3635 ;;; (sb-c::/report-continuation bound "BOUND")
3636 ;;; (let ((x (- bound))
3638 ;;; (sb-c::/report-continuation x "X")
3639 ;;; (sb-c::/report-continuation x "Y"))
3640 ;;; `(integer ,(- bound) ,(1- bound)))))
3641 ;;; (The DEFTRANSFORM doesn't do anything but report at compile time,
3642 ;;; and the function doesn't do anything at all.)
3645 (defknown /report-continuation (t t) null)
3646 (deftransform /report-continuation ((x message) (t t))
3647 (format t "~%/in /REPORT-CONTINUATION~%")
3648 (format t "/(CONTINUATION-TYPE X)=~S~%" (continuation-type x))
3649 (when (constant-continuation-p x)
3650 (format t "/(CONTINUATION-VALUE X)=~S~%" (continuation-value x)))
3651 (format t "/MESSAGE=~S~%" (continuation-value message))
3652 (give-up-ir1-transform "not a real transform"))
3653 (defun /report-continuation (x message)
3654 (declare (ignore x message))))