363e3c69016bffa2480e291314af63473ca6d755
[sbcl.git] / src / compiler / srctran.lisp
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.
4
5 ;;;; This software is part of the SBCL system. See the README file for
6 ;;;; more information.
7 ;;;;
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.
13
14 (in-package "SB!C")
15
16 ;;; Convert into an IF so that IF optimizations will eliminate redundant
17 ;;; negations.
18 (define-source-transform not (x) `(if ,x nil t))
19 (define-source-transform null (x) `(if ,x nil t))
20
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)))
25
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
28 ;;; arg.
29 (define-source-transform identity (x) `(prog1 ,x))
30 (define-source-transform values (x) `(prog1 ,x))
31
32 ;;; Bind the value and make a closure that returns it.
33 (define-source-transform constantly (value)
34   (let ((rest (gensym "CONSTANTLY-REST-"))
35         (n-value (gensym "CONSTANTLY-VALUE-")))
36     `(let ((,n-value ,value))
37       (lambda (&rest ,rest)
38         (declare (ignore ,rest))
39         ,n-value))))
40
41 ;;; If the function has a known number of arguments, then return a
42 ;;; lambda with the appropriate fixed number of args. If the
43 ;;; destination is a FUNCALL, then do the &REST APPLY thing, and let
44 ;;; MV optimization figure things out.
45 (deftransform complement ((fun) * * :node node)
46   "open code"
47   (multiple-value-bind (min max)
48       (fun-type-nargs (continuation-type fun))
49     (cond
50      ((and min (eql min max))
51       (let ((dums (make-gensym-list min)))
52         `#'(lambda ,dums (not (funcall fun ,@dums)))))
53      ((let* ((cont (node-cont node))
54              (dest (continuation-dest cont)))
55         (and (combination-p dest)
56              (eq (combination-fun dest) cont)))
57       '#'(lambda (&rest args)
58            (not (apply fun args))))
59      (t
60       (give-up-ir1-transform
61        "The function doesn't have a fixed argument count.")))))
62 \f
63 ;;;; list hackery
64
65 ;;; Translate CxR into CAR/CDR combos.
66 (defun source-transform-cxr (form)
67   (if (/= (length form) 2)
68       (values nil t)
69       (let ((name (symbol-name (car form))))
70         (do ((i (- (length name) 2) (1- i))
71              (res (cadr form)
72                   `(,(ecase (char name i)
73                        (#\A 'car)
74                        (#\D 'cdr))
75                     ,res)))
76             ((zerop i) res)))))
77
78 ;;; Make source transforms to turn CxR forms into combinations of CAR
79 ;;; and CDR. ANSI specifies that everything up to 4 A/D operations is
80 ;;; defined.
81 (/show0 "about to set CxR source transforms")
82 (loop for i of-type index from 2 upto 4 do
83       ;; Iterate over BUF = all names CxR where x = an I-element
84       ;; string of #\A or #\D characters.
85       (let ((buf (make-string (+ 2 i))))
86         (setf (aref buf 0) #\C
87               (aref buf (1+ i)) #\R)
88         (dotimes (j (ash 2 i))
89           (declare (type index j))
90           (dotimes (k i)
91             (declare (type index k))
92             (setf (aref buf (1+ k))
93                   (if (logbitp k j) #\A #\D)))
94           (setf (info :function :source-transform (intern buf))
95                 #'source-transform-cxr))))
96 (/show0 "done setting CxR source transforms")
97
98 ;;; Turn FIRST..FOURTH and REST into the obvious synonym, assuming
99 ;;; whatever is right for them is right for us. FIFTH..TENTH turn into
100 ;;; Nth, which can be expanded into a CAR/CDR later on if policy
101 ;;; favors it.
102 (define-source-transform first (x) `(car ,x))
103 (define-source-transform rest (x) `(cdr ,x))
104 (define-source-transform second (x) `(cadr ,x))
105 (define-source-transform third (x) `(caddr ,x))
106 (define-source-transform fourth (x) `(cadddr ,x))
107 (define-source-transform fifth (x) `(nth 4 ,x))
108 (define-source-transform sixth (x) `(nth 5 ,x))
109 (define-source-transform seventh (x) `(nth 6 ,x))
110 (define-source-transform eighth (x) `(nth 7 ,x))
111 (define-source-transform ninth (x) `(nth 8 ,x))
112 (define-source-transform tenth (x) `(nth 9 ,x))
113
114 ;;; Translate RPLACx to LET and SETF.
115 (define-source-transform rplaca (x y)
116   (once-only ((n-x x))
117     `(progn
118        (setf (car ,n-x) ,y)
119        ,n-x)))
120 (define-source-transform rplacd (x y)
121   (once-only ((n-x x))
122     `(progn
123        (setf (cdr ,n-x) ,y)
124        ,n-x)))
125
126 (define-source-transform nth (n l) `(car (nthcdr ,n ,l)))
127
128 (defvar *default-nthcdr-open-code-limit* 6)
129 (defvar *extreme-nthcdr-open-code-limit* 20)
130
131 (deftransform nthcdr ((n l) (unsigned-byte t) * :node node)
132   "convert NTHCDR to CAxxR"
133   (unless (constant-continuation-p n)
134     (give-up-ir1-transform))
135   (let ((n (continuation-value n)))
136     (when (> n
137              (if (policy node (and (= speed 3) (= space 0)))
138                  *extreme-nthcdr-open-code-limit*
139                  *default-nthcdr-open-code-limit*))
140       (give-up-ir1-transform))
141
142     (labels ((frob (n)
143                (if (zerop n)
144                    'l
145                    `(cdr ,(frob (1- n))))))
146       (frob n))))
147 \f
148 ;;;; arithmetic and numerology
149
150 (define-source-transform plusp (x) `(> ,x 0))
151 (define-source-transform minusp (x) `(< ,x 0))
152 (define-source-transform zerop (x) `(= ,x 0))
153
154 (define-source-transform 1+ (x) `(+ ,x 1))
155 (define-source-transform 1- (x) `(- ,x 1))
156
157 (define-source-transform oddp (x) `(not (zerop (logand ,x 1))))
158 (define-source-transform evenp (x) `(zerop (logand ,x 1)))
159
160 ;;; Note that all the integer division functions are available for
161 ;;; inline expansion.
162
163 (macrolet ((deffrob (fun)
164              `(define-source-transform ,fun (x &optional (y nil y-p))
165                 (declare (ignore y))
166                 (if y-p
167                     (values nil t)
168                     `(,',fun ,x 1)))))
169   (deffrob truncate)
170   (deffrob round)
171   #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
172   (deffrob floor)
173   #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
174   (deffrob ceiling))
175
176 (define-source-transform lognand (x y) `(lognot (logand ,x ,y)))
177 (define-source-transform lognor (x y) `(lognot (logior ,x ,y)))
178 (define-source-transform logandc1 (x y) `(logand (lognot ,x) ,y))
179 (define-source-transform logandc2 (x y) `(logand ,x (lognot ,y)))
180 (define-source-transform logorc1 (x y) `(logior (lognot ,x) ,y))
181 (define-source-transform logorc2 (x y) `(logior ,x (lognot ,y)))
182 (define-source-transform logtest (x y) `(not (zerop (logand ,x ,y))))
183 (define-source-transform logbitp (index integer)
184   `(not (zerop (logand (ash 1 ,index) ,integer))))
185 (define-source-transform byte (size position)
186   `(cons ,size ,position))
187 (define-source-transform byte-size (spec) `(car ,spec))
188 (define-source-transform byte-position (spec) `(cdr ,spec))
189 (define-source-transform ldb-test (bytespec integer)
190   `(not (zerop (mask-field ,bytespec ,integer))))
191
192 ;;; With the ratio and complex accessors, we pick off the "identity"
193 ;;; case, and use a primitive to handle the cell access case.
194 (define-source-transform numerator (num)
195   (once-only ((n-num `(the rational ,num)))
196     `(if (ratiop ,n-num)
197          (%numerator ,n-num)
198          ,n-num)))
199 (define-source-transform denominator (num)
200   (once-only ((n-num `(the rational ,num)))
201     `(if (ratiop ,n-num)
202          (%denominator ,n-num)
203          1)))
204 \f
205 ;;;; interval arithmetic for computing bounds
206 ;;;;
207 ;;;; This is a set of routines for operating on intervals. It
208 ;;;; implements a simple interval arithmetic package. Although SBCL
209 ;;;; has an interval type in NUMERIC-TYPE, we choose to use our own
210 ;;;; for two reasons:
211 ;;;;
212 ;;;;   1. This package is simpler than NUMERIC-TYPE.
213 ;;;;
214 ;;;;   2. It makes debugging much easier because you can just strip
215 ;;;;   out these routines and test them independently of SBCL. (This is a
216 ;;;;   big win!)
217 ;;;;
218 ;;;; One disadvantage is a probable increase in consing because we
219 ;;;; have to create these new interval structures even though
220 ;;;; numeric-type has everything we want to know. Reason 2 wins for
221 ;;;; now.
222
223 ;;; The basic interval type. It can handle open and closed intervals.
224 ;;; A bound is open if it is a list containing a number, just like
225 ;;; Lisp says. NIL means unbounded.
226 (defstruct (interval (:constructor %make-interval)
227                      (:copier nil))
228   low high)
229
230 (defun make-interval (&key low high)
231   (labels ((normalize-bound (val)
232              (cond ((and (floatp val)
233                          (float-infinity-p val))
234                     ;; Handle infinities.
235                     nil)
236                    ((or (numberp val)
237                         (eq val nil))
238                     ;; Handle any closed bounds.
239                     val)
240                    ((listp val)
241                     ;; We have an open bound. Normalize the numeric
242                     ;; bound. If the normalized bound is still a number
243                     ;; (not nil), keep the bound open. Otherwise, the
244                     ;; bound is really unbounded, so drop the openness.
245                     (let ((new-val (normalize-bound (first val))))
246                       (when new-val
247                         ;; The bound exists, so keep it open still.
248                         (list new-val))))
249                    (t
250                     (error "unknown bound type in MAKE-INTERVAL")))))
251     (%make-interval :low (normalize-bound low)
252                     :high (normalize-bound high))))
253
254 ;;; Given a number X, create a form suitable as a bound for an
255 ;;; interval. Make the bound open if OPEN-P is T. NIL remains NIL.
256 #!-sb-fluid (declaim (inline set-bound))
257 (defun set-bound (x open-p)
258   (if (and x open-p) (list x) x))
259
260 ;;; Apply the function F to a bound X. If X is an open bound, then
261 ;;; the result will be open. IF X is NIL, the result is NIL.
262 (defun bound-func (f x)
263   (declare (type function f))
264   (and x
265        (with-float-traps-masked (:underflow :overflow :inexact :divide-by-zero)
266          ;; With these traps masked, we might get things like infinity
267          ;; or negative infinity returned. Check for this and return
268          ;; NIL to indicate unbounded.
269          (let ((y (funcall f (type-bound-number x))))
270            (if (and (floatp y)
271                     (float-infinity-p y))
272                nil
273                (set-bound (funcall f (type-bound-number x)) (consp x)))))))
274
275 ;;; Apply a binary operator OP to two bounds X and Y. The result is
276 ;;; NIL if either is NIL. Otherwise bound is computed and the result
277 ;;; is open if either X or Y is open.
278 ;;;
279 ;;; FIXME: only used in this file, not needed in target runtime
280 (defmacro bound-binop (op x y)
281   `(and ,x ,y
282        (with-float-traps-masked (:underflow :overflow :inexact :divide-by-zero)
283          (set-bound (,op (type-bound-number ,x)
284                          (type-bound-number ,y))
285                     (or (consp ,x) (consp ,y))))))
286
287 ;;; Convert a numeric-type object to an interval object.
288 (defun numeric-type->interval (x)
289   (declare (type numeric-type x))
290   (make-interval :low (numeric-type-low x)
291                  :high (numeric-type-high x)))
292
293 (defun copy-interval-limit (limit)
294   (if (numberp limit)
295       limit
296       (copy-list limit)))
297
298 (defun copy-interval (x)
299   (declare (type interval x))
300   (make-interval :low (copy-interval-limit (interval-low x))
301                  :high (copy-interval-limit (interval-high x))))
302
303 ;;; Given a point P contained in the interval X, split X into two
304 ;;; interval at the point P. If CLOSE-LOWER is T, then the left
305 ;;; interval contains P. If CLOSE-UPPER is T, the right interval
306 ;;; contains P. You can specify both to be T or NIL.
307 (defun interval-split (p x &optional close-lower close-upper)
308   (declare (type number p)
309            (type interval x))
310   (list (make-interval :low (copy-interval-limit (interval-low x))
311                        :high (if close-lower p (list p)))
312         (make-interval :low (if close-upper (list p) p)
313                        :high (copy-interval-limit (interval-high x)))))
314
315 ;;; Return the closure of the interval. That is, convert open bounds
316 ;;; to closed bounds.
317 (defun interval-closure (x)
318   (declare (type interval x))
319   (make-interval :low (type-bound-number (interval-low x))
320                  :high (type-bound-number (interval-high x))))
321
322 (defun signed-zero->= (x y)
323   (declare (real x y))
324   (or (> x y)
325       (and (= x y)
326            (>= (float-sign (float x))
327                (float-sign (float y))))))
328
329 ;;; For an interval X, if X >= POINT, return '+. If X <= POINT, return
330 ;;; '-. Otherwise return NIL.
331 #+nil
332 (defun interval-range-info (x &optional (point 0))
333   (declare (type interval x))
334   (let ((lo (interval-low x))
335         (hi (interval-high x)))
336     (cond ((and lo (signed-zero->= (type-bound-number lo) point))
337            '+)
338           ((and hi (signed-zero->= point (type-bound-number hi)))
339            '-)
340           (t
341            nil))))
342 (defun interval-range-info (x &optional (point 0))
343   (declare (type interval x))
344   (labels ((signed->= (x y)
345              (if (and (zerop x) (zerop y) (floatp x) (floatp y))
346                  (>= (float-sign x) (float-sign y))
347                  (>= x y))))
348     (let ((lo (interval-low x))
349           (hi (interval-high x)))
350       (cond ((and lo (signed->= (type-bound-number lo) point))
351              '+)
352             ((and hi (signed->= point (type-bound-number hi)))
353              '-)
354             (t
355              nil)))))
356
357 ;;; Test to see whether the interval X is bounded. HOW determines the
358 ;;; test, and should be either ABOVE, BELOW, or BOTH.
359 (defun interval-bounded-p (x how)
360   (declare (type interval x))
361   (ecase how
362     (above
363      (interval-high x))
364     (below
365      (interval-low x))
366     (both
367      (and (interval-low x) (interval-high x)))))
368
369 ;;; signed zero comparison functions. Use these functions if we need
370 ;;; to distinguish between signed zeroes.
371 (defun signed-zero-< (x y)
372   (declare (real x y))
373   (or (< x y)
374       (and (= x y)
375            (< (float-sign (float x))
376               (float-sign (float y))))))
377 (defun signed-zero-> (x y)
378   (declare (real x y))
379   (or (> x y)
380       (and (= x y)
381            (> (float-sign (float x))
382               (float-sign (float y))))))
383 (defun signed-zero-= (x y)
384   (declare (real x y))
385   (and (= x y)
386        (= (float-sign (float x))
387           (float-sign (float y)))))
388 (defun signed-zero-<= (x y)
389   (declare (real x y))
390   (or (< x y)
391       (and (= x y)
392            (<= (float-sign (float x))
393                (float-sign (float y))))))
394
395 ;;; See whether the interval X contains the number P, taking into
396 ;;; account that the interval might not be closed.
397 (defun interval-contains-p (p x)
398   (declare (type number p)
399            (type interval x))
400   ;; Does the interval X contain the number P?  This would be a lot
401   ;; easier if all intervals were closed!
402   (let ((lo (interval-low x))
403         (hi (interval-high x)))
404     (cond ((and lo hi)
405            ;; The interval is bounded
406            (if (and (signed-zero-<= (type-bound-number lo) p)
407                     (signed-zero-<= p (type-bound-number hi)))
408                ;; P is definitely in the closure of the interval.
409                ;; We just need to check the end points now.
410                (cond ((signed-zero-= p (type-bound-number lo))
411                       (numberp lo))
412                      ((signed-zero-= p (type-bound-number hi))
413                       (numberp hi))
414                      (t t))
415                nil))
416           (hi
417            ;; Interval with upper bound
418            (if (signed-zero-< p (type-bound-number hi))
419                t
420                (and (numberp hi) (signed-zero-= p hi))))
421           (lo
422            ;; Interval with lower bound
423            (if (signed-zero-> p (type-bound-number lo))
424                t
425                (and (numberp lo) (signed-zero-= p lo))))
426           (t
427            ;; Interval with no bounds
428            t))))
429
430 ;;; Determine whether two intervals X and Y intersect. Return T if so.
431 ;;; If CLOSED-INTERVALS-P is T, the treat the intervals as if they
432 ;;; were closed. Otherwise the intervals are treated as they are.
433 ;;;
434 ;;; Thus if X = [0, 1) and Y = (1, 2), then they do not intersect
435 ;;; because no element in X is in Y. However, if CLOSED-INTERVALS-P
436 ;;; is T, then they do intersect because we use the closure of X = [0,
437 ;;; 1] and Y = [1, 2] to determine intersection.
438 (defun interval-intersect-p (x y &optional closed-intervals-p)
439   (declare (type interval x y))
440   (multiple-value-bind (intersect diff)
441       (interval-intersection/difference (if closed-intervals-p
442                                             (interval-closure x)
443                                             x)
444                                         (if closed-intervals-p
445                                             (interval-closure y)
446                                             y))
447     (declare (ignore diff))
448     intersect))
449
450 ;;; Are the two intervals adjacent?  That is, is there a number
451 ;;; between the two intervals that is not an element of either
452 ;;; interval?  If so, they are not adjacent. For example [0, 1) and
453 ;;; [1, 2] are adjacent but [0, 1) and (1, 2] are not because 1 lies
454 ;;; between both intervals.
455 (defun interval-adjacent-p (x y)
456   (declare (type interval x y))
457   (flet ((adjacent (lo hi)
458            ;; Check to see whether lo and hi are adjacent. If either is
459            ;; nil, they can't be adjacent.
460            (when (and lo hi (= (type-bound-number lo) (type-bound-number hi)))
461              ;; The bounds are equal. They are adjacent if one of
462              ;; them is closed (a number). If both are open (consp),
463              ;; then there is a number that lies between them.
464              (or (numberp lo) (numberp hi)))))
465     (or (adjacent (interval-low y) (interval-high x))
466         (adjacent (interval-low x) (interval-high y)))))
467
468 ;;; Compute the intersection and difference between two intervals.
469 ;;; Two values are returned: the intersection and the difference.
470 ;;;
471 ;;; Let the two intervals be X and Y, and let I and D be the two
472 ;;; values returned by this function. Then I = X intersect Y. If I
473 ;;; is NIL (the empty set), then D is X union Y, represented as the
474 ;;; list of X and Y. If I is not the empty set, then D is (X union Y)
475 ;;; - I, which is a list of two intervals.
476 ;;;
477 ;;; For example, let X = [1,5] and Y = [-1,3). Then I = [1,3) and D =
478 ;;; [-1,1) union [3,5], which is returned as a list of two intervals.
479 (defun interval-intersection/difference (x y)
480   (declare (type interval x y))
481   (let ((x-lo (interval-low x))
482         (x-hi (interval-high x))
483         (y-lo (interval-low y))
484         (y-hi (interval-high y)))
485     (labels
486         ((opposite-bound (p)
487            ;; If p is an open bound, make it closed. If p is a closed
488            ;; bound, make it open.
489            (if (listp p)
490                (first p)
491                (list p)))
492          (test-number (p int)
493            ;; Test whether P is in the interval.
494            (when (interval-contains-p (type-bound-number p)
495                                       (interval-closure int))
496              (let ((lo (interval-low int))
497                    (hi (interval-high int)))
498                ;; Check for endpoints.
499                (cond ((and lo (= (type-bound-number p) (type-bound-number lo)))
500                       (not (and (consp p) (numberp lo))))
501                      ((and hi (= (type-bound-number p) (type-bound-number hi)))
502                       (not (and (numberp p) (consp hi))))
503                      (t t)))))
504          (test-lower-bound (p int)
505            ;; P is a lower bound of an interval.
506            (if p
507                (test-number p int)
508                (not (interval-bounded-p int 'below))))
509          (test-upper-bound (p int)
510            ;; P is an upper bound of an interval.
511            (if p
512                (test-number p int)
513                (not (interval-bounded-p int 'above)))))
514       (let ((x-lo-in-y (test-lower-bound x-lo y))
515             (x-hi-in-y (test-upper-bound x-hi y))
516             (y-lo-in-x (test-lower-bound y-lo x))
517             (y-hi-in-x (test-upper-bound y-hi x)))
518         (cond ((or x-lo-in-y x-hi-in-y y-lo-in-x y-hi-in-x)
519                ;; Intervals intersect. Let's compute the intersection
520                ;; and the difference.
521                (multiple-value-bind (lo left-lo left-hi)
522                    (cond (x-lo-in-y (values x-lo y-lo (opposite-bound x-lo)))
523                          (y-lo-in-x (values y-lo x-lo (opposite-bound y-lo))))
524                  (multiple-value-bind (hi right-lo right-hi)
525                      (cond (x-hi-in-y
526                             (values x-hi (opposite-bound x-hi) y-hi))
527                            (y-hi-in-x
528                             (values y-hi (opposite-bound y-hi) x-hi)))
529                    (values (make-interval :low lo :high hi)
530                            (list (make-interval :low left-lo
531                                                 :high left-hi)
532                                  (make-interval :low right-lo
533                                                 :high right-hi))))))
534               (t
535                (values nil (list x y))))))))
536
537 ;;; If intervals X and Y intersect, return a new interval that is the
538 ;;; union of the two. If they do not intersect, return NIL.
539 (defun interval-merge-pair (x y)
540   (declare (type interval x y))
541   ;; If x and y intersect or are adjacent, create the union.
542   ;; Otherwise return nil
543   (when (or (interval-intersect-p x y)
544             (interval-adjacent-p x y))
545     (flet ((select-bound (x1 x2 min-op max-op)
546              (let ((x1-val (type-bound-number x1))
547                    (x2-val (type-bound-number x2)))
548                (cond ((and x1 x2)
549                       ;; Both bounds are finite. Select the right one.
550                       (cond ((funcall min-op x1-val x2-val)
551                              ;; x1 is definitely better.
552                              x1)
553                             ((funcall max-op x1-val x2-val)
554                              ;; x2 is definitely better.
555                              x2)
556                             (t
557                              ;; Bounds are equal. Select either
558                              ;; value and make it open only if
559                              ;; both were open.
560                              (set-bound x1-val (and (consp x1) (consp x2))))))
561                      (t
562                       ;; At least one bound is not finite. The
563                       ;; non-finite bound always wins.
564                       nil)))))
565       (let* ((x-lo (copy-interval-limit (interval-low x)))
566              (x-hi (copy-interval-limit (interval-high x)))
567              (y-lo (copy-interval-limit (interval-low y)))
568              (y-hi (copy-interval-limit (interval-high y))))
569         (make-interval :low (select-bound x-lo y-lo #'< #'>)
570                        :high (select-bound x-hi y-hi #'> #'<))))))
571
572 ;;; basic arithmetic operations on intervals. We probably should do
573 ;;; true interval arithmetic here, but it's complicated because we
574 ;;; have float and integer types and bounds can be open or closed.
575
576 ;;; the negative of an interval
577 (defun interval-neg (x)
578   (declare (type interval x))
579   (make-interval :low (bound-func #'- (interval-high x))
580                  :high (bound-func #'- (interval-low x))))
581
582 ;;; Add two intervals.
583 (defun interval-add (x y)
584   (declare (type interval x y))
585   (make-interval :low (bound-binop + (interval-low x) (interval-low y))
586                  :high (bound-binop + (interval-high x) (interval-high y))))
587
588 ;;; Subtract two intervals.
589 (defun interval-sub (x y)
590   (declare (type interval x y))
591   (make-interval :low (bound-binop - (interval-low x) (interval-high y))
592                  :high (bound-binop - (interval-high x) (interval-low y))))
593
594 ;;; Multiply two intervals.
595 (defun interval-mul (x y)
596   (declare (type interval x y))
597   (flet ((bound-mul (x y)
598            (cond ((or (null x) (null y))
599                   ;; Multiply by infinity is infinity
600                   nil)
601                  ((or (and (numberp x) (zerop x))
602                       (and (numberp y) (zerop y)))
603                   ;; Multiply by closed zero is special. The result
604                   ;; is always a closed bound. But don't replace this
605                   ;; with zero; we want the multiplication to produce
606                   ;; the correct signed zero, if needed.
607                   (* (type-bound-number x) (type-bound-number y)))
608                  ((or (and (floatp x) (float-infinity-p x))
609                       (and (floatp y) (float-infinity-p y)))
610                   ;; Infinity times anything is infinity
611                   nil)
612                  (t
613                   ;; General multiply. The result is open if either is open.
614                   (bound-binop * x y)))))
615     (let ((x-range (interval-range-info x))
616           (y-range (interval-range-info y)))
617       (cond ((null x-range)
618              ;; Split x into two and multiply each separately
619              (destructuring-bind (x- x+) (interval-split 0 x t t)
620                (interval-merge-pair (interval-mul x- y)
621                                     (interval-mul x+ y))))
622             ((null y-range)
623              ;; Split y into two and multiply each separately
624              (destructuring-bind (y- y+) (interval-split 0 y t t)
625                (interval-merge-pair (interval-mul x y-)
626                                     (interval-mul x y+))))
627             ((eq x-range '-)
628              (interval-neg (interval-mul (interval-neg x) y)))
629             ((eq y-range '-)
630              (interval-neg (interval-mul x (interval-neg y))))
631             ((and (eq x-range '+) (eq y-range '+))
632              ;; If we are here, X and Y are both positive.
633              (make-interval
634               :low (bound-mul (interval-low x) (interval-low y))
635               :high (bound-mul (interval-high x) (interval-high y))))
636             (t
637              (bug "excluded case in INTERVAL-MUL"))))))
638
639 ;;; Divide two intervals.
640 (defun interval-div (top bot)
641   (declare (type interval top bot))
642   (flet ((bound-div (x y y-low-p)
643            ;; Compute x/y
644            (cond ((null y)
645                   ;; Divide by infinity means result is 0. However,
646                   ;; we need to watch out for the sign of the result,
647                   ;; to correctly handle signed zeros. We also need
648                   ;; to watch out for positive or negative infinity.
649                   (if (floatp (type-bound-number x))
650                       (if y-low-p
651                           (- (float-sign (type-bound-number x) 0.0))
652                           (float-sign (type-bound-number x) 0.0))
653                       0))
654                  ((zerop (type-bound-number y))
655                   ;; Divide by zero means result is infinity
656                   nil)
657                  ((and (numberp x) (zerop x))
658                   ;; Zero divided by anything is zero.
659                   x)
660                  (t
661                   (bound-binop / x y)))))
662     (let ((top-range (interval-range-info top))
663           (bot-range (interval-range-info bot)))
664       (cond ((null bot-range)
665              ;; The denominator contains zero, so anything goes!
666              (make-interval :low nil :high nil))
667             ((eq bot-range '-)
668              ;; Denominator is negative so flip the sign, compute the
669              ;; result, and flip it back.
670              (interval-neg (interval-div top (interval-neg bot))))
671             ((null top-range)
672              ;; Split top into two positive and negative parts, and
673              ;; divide each separately
674              (destructuring-bind (top- top+) (interval-split 0 top t t)
675                (interval-merge-pair (interval-div top- bot)
676                                     (interval-div top+ bot))))
677             ((eq top-range '-)
678              ;; Top is negative so flip the sign, divide, and flip the
679              ;; sign of the result.
680              (interval-neg (interval-div (interval-neg top) bot)))
681             ((and (eq top-range '+) (eq bot-range '+))
682              ;; the easy case
683              (make-interval
684               :low (bound-div (interval-low top) (interval-high bot) t)
685               :high (bound-div (interval-high top) (interval-low bot) nil)))
686             (t
687              (bug "excluded case in INTERVAL-DIV"))))))
688
689 ;;; Apply the function F to the interval X. If X = [a, b], then the
690 ;;; result is [f(a), f(b)]. It is up to the user to make sure the
691 ;;; result makes sense. It will if F is monotonic increasing (or
692 ;;; non-decreasing).
693 (defun interval-func (f x)
694   (declare (type function f)
695            (type interval x))
696   (let ((lo (bound-func f (interval-low x)))
697         (hi (bound-func f (interval-high x))))
698     (make-interval :low lo :high hi)))
699
700 ;;; Return T if X < Y. That is every number in the interval X is
701 ;;; always less than any number in the interval Y.
702 (defun interval-< (x y)
703   (declare (type interval x y))
704   ;; X < Y only if X is bounded above, Y is bounded below, and they
705   ;; don't overlap.
706   (when (and (interval-bounded-p x 'above)
707              (interval-bounded-p y 'below))
708     ;; Intervals are bounded in the appropriate way. Make sure they
709     ;; don't overlap.
710     (let ((left (interval-high x))
711           (right (interval-low y)))
712       (cond ((> (type-bound-number left)
713                 (type-bound-number right))
714              ;; The intervals definitely overlap, so result is NIL.
715              nil)
716             ((< (type-bound-number left)
717                 (type-bound-number right))
718              ;; The intervals definitely don't touch, so result is T.
719              t)
720             (t
721              ;; Limits are equal. Check for open or closed bounds.
722              ;; Don't overlap if one or the other are open.
723              (or (consp left) (consp right)))))))
724
725 ;;; Return T if X >= Y. That is, every number in the interval X is
726 ;;; always greater than any number in the interval Y.
727 (defun interval->= (x y)
728   (declare (type interval x y))
729   ;; X >= Y if lower bound of X >= upper bound of Y
730   (when (and (interval-bounded-p x 'below)
731              (interval-bounded-p y 'above))
732     (>= (type-bound-number (interval-low x))
733         (type-bound-number (interval-high y)))))
734
735 ;;; Return an interval that is the absolute value of X. Thus, if
736 ;;; X = [-1 10], the result is [0, 10].
737 (defun interval-abs (x)
738   (declare (type interval x))
739   (case (interval-range-info x)
740     (+
741      (copy-interval x))
742     (-
743      (interval-neg x))
744     (t
745      (destructuring-bind (x- x+) (interval-split 0 x t t)
746        (interval-merge-pair (interval-neg x-) x+)))))
747
748 ;;; Compute the square of an interval.
749 (defun interval-sqr (x)
750   (declare (type interval x))
751   (interval-func (lambda (x) (* x x))
752                  (interval-abs x)))
753 \f
754 ;;;; numeric DERIVE-TYPE methods
755
756 ;;; a utility for defining derive-type methods of integer operations. If
757 ;;; the types of both X and Y are integer types, then we compute a new
758 ;;; integer type with bounds determined Fun when applied to X and Y.
759 ;;; Otherwise, we use Numeric-Contagion.
760 (defun derive-integer-type (x y fun)
761   (declare (type continuation x y) (type function fun))
762   (let ((x (continuation-type x))
763         (y (continuation-type y)))
764     (if (and (numeric-type-p x) (numeric-type-p y)
765              (eq (numeric-type-class x) 'integer)
766              (eq (numeric-type-class y) 'integer)
767              (eq (numeric-type-complexp x) :real)
768              (eq (numeric-type-complexp y) :real))
769         (multiple-value-bind (low high) (funcall fun x y)
770           (make-numeric-type :class 'integer
771                              :complexp :real
772                              :low low
773                              :high high))
774         (numeric-contagion x y))))
775
776 ;;; simple utility to flatten a list
777 (defun flatten-list (x)
778   (labels ((flatten-helper (x r);; 'r' is the stuff to the 'right'.
779              (cond ((null x) r)
780                    ((atom x)
781                     (cons x r))
782                    (t (flatten-helper (car x)
783                                       (flatten-helper (cdr x) r))))))
784     (flatten-helper x nil)))
785
786 ;;; Take some type of continuation and massage it so that we get a
787 ;;; list of the constituent types. If ARG is *EMPTY-TYPE*, return NIL
788 ;;; to indicate failure.
789 (defun prepare-arg-for-derive-type (arg)
790   (flet ((listify (arg)
791            (typecase arg
792              (numeric-type
793               (list arg))
794              (union-type
795               (union-type-types arg))
796              (t
797               (list arg)))))
798     (unless (eq arg *empty-type*)
799       ;; Make sure all args are some type of numeric-type. For member
800       ;; types, convert the list of members into a union of equivalent
801       ;; single-element member-type's.
802       (let ((new-args nil))
803         (dolist (arg (listify arg))
804           (if (member-type-p arg)
805               ;; Run down the list of members and convert to a list of
806               ;; member types.
807               (dolist (member (member-type-members arg))
808                 (push (if (numberp member)
809                           (make-member-type :members (list member))
810                           *empty-type*)
811                       new-args))
812               (push arg new-args)))
813         (unless (member *empty-type* new-args)
814           new-args)))))
815
816 ;;; Convert from the standard type convention for which -0.0 and 0.0
817 ;;; are equal to an intermediate convention for which they are
818 ;;; considered different which is more natural for some of the
819 ;;; optimisers.
820 #!-negative-zero-is-not-zero
821 (defun convert-numeric-type (type)
822   (declare (type numeric-type type))
823   ;;; Only convert real float interval delimiters types.
824   (if (eq (numeric-type-complexp type) :real)
825       (let* ((lo (numeric-type-low type))
826              (lo-val (type-bound-number lo))
827              (lo-float-zero-p (and lo (floatp lo-val) (= lo-val 0.0)))
828              (hi (numeric-type-high type))
829              (hi-val (type-bound-number hi))
830              (hi-float-zero-p (and hi (floatp hi-val) (= hi-val 0.0))))
831         (if (or lo-float-zero-p hi-float-zero-p)
832             (make-numeric-type
833              :class (numeric-type-class type)
834              :format (numeric-type-format type)
835              :complexp :real
836              :low (if lo-float-zero-p
837                       (if (consp lo)
838                           (list (float 0.0 lo-val))
839                           (float -0.0 lo-val))
840                       lo)
841              :high (if hi-float-zero-p
842                        (if (consp hi)
843                            (list (float -0.0 hi-val))
844                            (float 0.0 hi-val))
845                        hi))
846             type))
847       ;; Not real float.
848       type))
849
850 ;;; Convert back from the intermediate convention for which -0.0 and
851 ;;; 0.0 are considered different to the standard type convention for
852 ;;; which and equal.
853 #!-negative-zero-is-not-zero
854 (defun convert-back-numeric-type (type)
855   (declare (type numeric-type type))
856   ;;; Only convert real float interval delimiters types.
857   (if (eq (numeric-type-complexp type) :real)
858       (let* ((lo (numeric-type-low type))
859              (lo-val (type-bound-number lo))
860              (lo-float-zero-p
861               (and lo (floatp lo-val) (= lo-val 0.0)
862                    (float-sign lo-val)))
863              (hi (numeric-type-high type))
864              (hi-val (type-bound-number hi))
865              (hi-float-zero-p
866               (and hi (floatp hi-val) (= hi-val 0.0)
867                    (float-sign hi-val))))
868         (cond
869           ;; (float +0.0 +0.0) => (member 0.0)
870           ;; (float -0.0 -0.0) => (member -0.0)
871           ((and lo-float-zero-p hi-float-zero-p)
872            ;; shouldn't have exclusive bounds here..
873            (aver (and (not (consp lo)) (not (consp hi))))
874            (if (= lo-float-zero-p hi-float-zero-p)
875                ;; (float +0.0 +0.0) => (member 0.0)
876                ;; (float -0.0 -0.0) => (member -0.0)
877                (specifier-type `(member ,lo-val))
878                ;; (float -0.0 +0.0) => (float 0.0 0.0)
879                ;; (float +0.0 -0.0) => (float 0.0 0.0)
880                (make-numeric-type :class (numeric-type-class type)
881                                   :format (numeric-type-format type)
882                                   :complexp :real
883                                   :low hi-val
884                                   :high hi-val)))
885           (lo-float-zero-p
886            (cond
887              ;; (float -0.0 x) => (float 0.0 x)
888              ((and (not (consp lo)) (minusp lo-float-zero-p))
889               (make-numeric-type :class (numeric-type-class type)
890                                  :format (numeric-type-format type)
891                                  :complexp :real
892                                  :low (float 0.0 lo-val)
893                                  :high hi))
894              ;; (float (+0.0) x) => (float (0.0) x)
895              ((and (consp lo) (plusp lo-float-zero-p))
896               (make-numeric-type :class (numeric-type-class type)
897                                  :format (numeric-type-format type)
898                                  :complexp :real
899                                  :low (list (float 0.0 lo-val))
900                                  :high hi))
901              (t
902               ;; (float +0.0 x) => (or (member 0.0) (float (0.0) x))
903               ;; (float (-0.0) x) => (or (member 0.0) (float (0.0) x))
904               (list (make-member-type :members (list (float 0.0 lo-val)))
905                     (make-numeric-type :class (numeric-type-class type)
906                                        :format (numeric-type-format type)
907                                        :complexp :real
908                                        :low (list (float 0.0 lo-val))
909                                        :high hi)))))
910           (hi-float-zero-p
911            (cond
912              ;; (float x +0.0) => (float x 0.0)
913              ((and (not (consp hi)) (plusp hi-float-zero-p))
914               (make-numeric-type :class (numeric-type-class type)
915                                  :format (numeric-type-format type)
916                                  :complexp :real
917                                  :low lo
918                                  :high (float 0.0 hi-val)))
919              ;; (float x (-0.0)) => (float x (0.0))
920              ((and (consp hi) (minusp hi-float-zero-p))
921               (make-numeric-type :class (numeric-type-class type)
922                                  :format (numeric-type-format type)
923                                  :complexp :real
924                                  :low lo
925                                  :high (list (float 0.0 hi-val))))
926              (t
927               ;; (float x (+0.0)) => (or (member -0.0) (float x (0.0)))
928               ;; (float x -0.0) => (or (member -0.0) (float x (0.0)))
929               (list (make-member-type :members (list (float -0.0 hi-val)))
930                     (make-numeric-type :class (numeric-type-class type)
931                                        :format (numeric-type-format type)
932                                        :complexp :real
933                                        :low lo
934                                        :high (list (float 0.0 hi-val)))))))
935           (t
936            type)))
937       ;; not real float
938       type))
939
940 ;;; Convert back a possible list of numeric types.
941 #!-negative-zero-is-not-zero
942 (defun convert-back-numeric-type-list (type-list)
943   (typecase type-list
944     (list
945      (let ((results '()))
946        (dolist (type type-list)
947          (if (numeric-type-p type)
948              (let ((result (convert-back-numeric-type type)))
949                (if (listp result)
950                    (setf results (append results result))
951                    (push result results)))
952              (push type results)))
953        results))
954     (numeric-type
955      (convert-back-numeric-type type-list))
956     (union-type
957      (convert-back-numeric-type-list (union-type-types type-list)))
958     (t
959      type-list)))
960
961 ;;; FIXME: MAKE-CANONICAL-UNION-TYPE and CONVERT-MEMBER-TYPE probably
962 ;;; belong in the kernel's type logic, invoked always, instead of in
963 ;;; the compiler, invoked only during some type optimizations.
964
965 ;;; Take a list of types and return a canonical type specifier,
966 ;;; combining any MEMBER types together. If both positive and negative
967 ;;; MEMBER types are present they are converted to a float type.
968 ;;; XXX This would be far simpler if the type-union methods could handle
969 ;;; member/number unions.
970 (defun make-canonical-union-type (type-list)
971   (let ((members '())
972         (misc-types '()))
973     (dolist (type type-list)
974       (if (member-type-p type)
975           (setf members (union members (member-type-members type)))
976           (push type misc-types)))
977     #!+long-float
978     (when (null (set-difference '(-0l0 0l0) members))
979       #!-negative-zero-is-not-zero
980       (push (specifier-type '(long-float 0l0 0l0)) misc-types)
981       #!+negative-zero-is-not-zero
982       (push (specifier-type '(long-float -0l0 0l0)) misc-types)
983       (setf members (set-difference members '(-0l0 0l0))))
984     (when (null (set-difference '(-0d0 0d0) members))
985       #!-negative-zero-is-not-zero
986       (push (specifier-type '(double-float 0d0 0d0)) misc-types)
987       #!+negative-zero-is-not-zero
988       (push (specifier-type '(double-float -0d0 0d0)) misc-types)
989       (setf members (set-difference members '(-0d0 0d0))))
990     (when (null (set-difference '(-0f0 0f0) members))
991       #!-negative-zero-is-not-zero
992       (push (specifier-type '(single-float 0f0 0f0)) misc-types)
993       #!+negative-zero-is-not-zero
994       (push (specifier-type '(single-float -0f0 0f0)) misc-types)
995       (setf members (set-difference members '(-0f0 0f0))))
996     (if members
997         (apply #'type-union (make-member-type :members members) misc-types)
998         (apply #'type-union misc-types))))
999
1000 ;;; Convert a member type with a single member to a numeric type.
1001 (defun convert-member-type (arg)
1002   (let* ((members (member-type-members arg))
1003          (member (first members))
1004          (member-type (type-of member)))
1005     (aver (not (rest members)))
1006     (specifier-type `(,(if (subtypep member-type 'integer)
1007                            'integer
1008                            member-type)
1009                       ,member ,member))))
1010
1011 ;;; This is used in defoptimizers for computing the resulting type of
1012 ;;; a function.
1013 ;;;
1014 ;;; Given the continuation ARG, derive the resulting type using the
1015 ;;; DERIVE-FCN. DERIVE-FCN takes exactly one argument which is some
1016 ;;; "atomic" continuation type like numeric-type or member-type
1017 ;;; (containing just one element). It should return the resulting
1018 ;;; type, which can be a list of types.
1019 ;;;
1020 ;;; For the case of member types, if a member-fcn is given it is
1021 ;;; called to compute the result otherwise the member type is first
1022 ;;; converted to a numeric type and the derive-fcn is call.
1023 (defun one-arg-derive-type (arg derive-fcn member-fcn
1024                                 &optional (convert-type t))
1025   (declare (type function derive-fcn)
1026            (type (or null function) member-fcn)
1027            #!+negative-zero-is-not-zero (ignore convert-type))
1028   (let ((arg-list (prepare-arg-for-derive-type (continuation-type arg))))
1029     (when arg-list
1030       (flet ((deriver (x)
1031                (typecase x
1032                  (member-type
1033                   (if member-fcn
1034                       (with-float-traps-masked
1035                           (:underflow :overflow :divide-by-zero)
1036                         (make-member-type
1037                          :members (list
1038                                    (funcall member-fcn
1039                                             (first (member-type-members x))))))
1040                       ;; Otherwise convert to a numeric type.
1041                       (let ((result-type-list
1042                              (funcall derive-fcn (convert-member-type x))))
1043                         #!-negative-zero-is-not-zero
1044                         (if convert-type
1045                             (convert-back-numeric-type-list result-type-list)
1046                             result-type-list)
1047                         #!+negative-zero-is-not-zero
1048                         result-type-list)))
1049                  (numeric-type
1050                   #!-negative-zero-is-not-zero
1051                   (if convert-type
1052                       (convert-back-numeric-type-list
1053                        (funcall derive-fcn (convert-numeric-type x)))
1054                       (funcall derive-fcn x))
1055                   #!+negative-zero-is-not-zero
1056                   (funcall derive-fcn x))
1057                  (t
1058                   *universal-type*))))
1059         ;; Run down the list of args and derive the type of each one,
1060         ;; saving all of the results in a list.
1061         (let ((results nil))
1062           (dolist (arg arg-list)
1063             (let ((result (deriver arg)))
1064               (if (listp result)
1065                   (setf results (append results result))
1066                   (push result results))))
1067           (if (rest results)
1068               (make-canonical-union-type results)
1069               (first results)))))))
1070
1071 ;;; Same as ONE-ARG-DERIVE-TYPE, except we assume the function takes
1072 ;;; two arguments. DERIVE-FCN takes 3 args in this case: the two
1073 ;;; original args and a third which is T to indicate if the two args
1074 ;;; really represent the same continuation. This is useful for
1075 ;;; deriving the type of things like (* x x), which should always be
1076 ;;; positive. If we didn't do this, we wouldn't be able to tell.
1077 (defun two-arg-derive-type (arg1 arg2 derive-fcn fcn
1078                                  &optional (convert-type t))
1079   (declare (type function derive-fcn fcn))
1080   #!+negative-zero-is-not-zero
1081   (declare (ignore convert-type))
1082   (flet (#!-negative-zero-is-not-zero
1083          (deriver (x y same-arg)
1084            (cond ((and (member-type-p x) (member-type-p y))
1085                   (let* ((x (first (member-type-members x)))
1086                          (y (first (member-type-members y)))
1087                          (result (with-float-traps-masked
1088                                      (:underflow :overflow :divide-by-zero
1089                                       :invalid)
1090                                    (funcall fcn x y))))
1091                     (cond ((null result))
1092                           ((and (floatp result) (float-nan-p result))
1093                            (make-numeric-type :class 'float
1094                                               :format (type-of result)
1095                                               :complexp :real))
1096                           (t
1097                            (make-member-type :members (list result))))))
1098                  ((and (member-type-p x) (numeric-type-p y))
1099                   (let* ((x (convert-member-type x))
1100                          (y (if convert-type (convert-numeric-type y) y))
1101                          (result (funcall derive-fcn x y same-arg)))
1102                     (if convert-type
1103                         (convert-back-numeric-type-list result)
1104                         result)))
1105                  ((and (numeric-type-p x) (member-type-p y))
1106                   (let* ((x (if convert-type (convert-numeric-type x) x))
1107                          (y (convert-member-type y))
1108                          (result (funcall derive-fcn x y same-arg)))
1109                     (if convert-type
1110                         (convert-back-numeric-type-list result)
1111                         result)))
1112                  ((and (numeric-type-p x) (numeric-type-p y))
1113                   (let* ((x (if convert-type (convert-numeric-type x) x))
1114                          (y (if convert-type (convert-numeric-type y) y))
1115                          (result (funcall derive-fcn x y same-arg)))
1116                     (if convert-type
1117                         (convert-back-numeric-type-list result)
1118                         result)))
1119                  (t
1120                   *universal-type*)))
1121          #!+negative-zero-is-not-zero
1122          (deriver (x y same-arg)
1123            (cond ((and (member-type-p x) (member-type-p y))
1124                   (let* ((x (first (member-type-members x)))
1125                          (y (first (member-type-members y)))
1126                          (result (with-float-traps-masked
1127                                      (:underflow :overflow :divide-by-zero)
1128                                    (funcall fcn x y))))
1129                     (if result
1130                         (make-member-type :members (list result)))))
1131                  ((and (member-type-p x) (numeric-type-p y))
1132                   (let ((x (convert-member-type x)))
1133                     (funcall derive-fcn x y same-arg)))
1134                  ((and (numeric-type-p x) (member-type-p y))
1135                   (let ((y (convert-member-type y)))
1136                     (funcall derive-fcn x y same-arg)))
1137                  ((and (numeric-type-p x) (numeric-type-p y))
1138                   (funcall derive-fcn x y same-arg))
1139                  (t
1140                   *universal-type*))))
1141     (let ((same-arg (same-leaf-ref-p arg1 arg2))
1142           (a1 (prepare-arg-for-derive-type (continuation-type arg1)))
1143           (a2 (prepare-arg-for-derive-type (continuation-type arg2))))
1144       (when (and a1 a2)
1145         (let ((results nil))
1146           (if same-arg
1147               ;; Since the args are the same continuation, just run
1148               ;; down the lists.
1149               (dolist (x a1)
1150                 (let ((result (deriver x x same-arg)))
1151                   (if (listp result)
1152                       (setf results (append results result))
1153                       (push result results))))
1154               ;; Try all pairwise combinations.
1155               (dolist (x a1)
1156                 (dolist (y a2)
1157                   (let ((result (or (deriver x y same-arg)
1158                                     (numeric-contagion x y))))
1159                     (if (listp result)
1160                         (setf results (append results result))
1161                         (push result results))))))
1162           (if (rest results)
1163               (make-canonical-union-type results)
1164               (first results)))))))
1165 \f
1166 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1167 (progn
1168 (defoptimizer (+ derive-type) ((x y))
1169   (derive-integer-type
1170    x y
1171    #'(lambda (x y)
1172        (flet ((frob (x y)
1173                 (if (and x y)
1174                     (+ x y)
1175                     nil)))
1176          (values (frob (numeric-type-low x) (numeric-type-low y))
1177                  (frob (numeric-type-high x) (numeric-type-high y)))))))
1178
1179 (defoptimizer (- derive-type) ((x y))
1180   (derive-integer-type
1181    x y
1182    #'(lambda (x y)
1183        (flet ((frob (x y)
1184                 (if (and x y)
1185                     (- x y)
1186                     nil)))
1187          (values (frob (numeric-type-low x) (numeric-type-high y))
1188                  (frob (numeric-type-high x) (numeric-type-low y)))))))
1189
1190 (defoptimizer (* derive-type) ((x y))
1191   (derive-integer-type
1192    x y
1193    #'(lambda (x y)
1194        (let ((x-low (numeric-type-low x))
1195              (x-high (numeric-type-high x))
1196              (y-low (numeric-type-low y))
1197              (y-high (numeric-type-high y)))
1198          (cond ((not (and x-low y-low))
1199                 (values nil nil))
1200                ((or (minusp x-low) (minusp y-low))
1201                 (if (and x-high y-high)
1202                     (let ((max (* (max (abs x-low) (abs x-high))
1203                                   (max (abs y-low) (abs y-high)))))
1204                       (values (- max) max))
1205                     (values nil nil)))
1206                (t
1207                 (values (* x-low y-low)
1208                         (if (and x-high y-high)
1209                             (* x-high y-high)
1210                             nil))))))))
1211
1212 (defoptimizer (/ derive-type) ((x y))
1213   (numeric-contagion (continuation-type x) (continuation-type y)))
1214
1215 ) ; PROGN
1216
1217 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1218 (progn
1219 (defun +-derive-type-aux (x y same-arg)
1220   (if (and (numeric-type-real-p x)
1221            (numeric-type-real-p y))
1222       (let ((result
1223              (if same-arg
1224                  (let ((x-int (numeric-type->interval x)))
1225                    (interval-add x-int x-int))
1226                  (interval-add (numeric-type->interval x)
1227                                (numeric-type->interval y))))
1228             (result-type (numeric-contagion x y)))
1229         ;; If the result type is a float, we need to be sure to coerce
1230         ;; the bounds into the correct type.
1231         (when (eq (numeric-type-class result-type) 'float)
1232           (setf result (interval-func
1233                         #'(lambda (x)
1234                             (coerce x (or (numeric-type-format result-type)
1235                                           'float)))
1236                         result)))
1237         (make-numeric-type
1238          :class (if (and (eq (numeric-type-class x) 'integer)
1239                          (eq (numeric-type-class y) 'integer))
1240                     ;; The sum of integers is always an integer.
1241                     'integer
1242                     (numeric-type-class result-type))
1243          :format (numeric-type-format result-type)
1244          :low (interval-low result)
1245          :high (interval-high result)))
1246       ;; general contagion
1247       (numeric-contagion x y)))
1248
1249 (defoptimizer (+ derive-type) ((x y))
1250   (two-arg-derive-type x y #'+-derive-type-aux #'+))
1251
1252 (defun --derive-type-aux (x y same-arg)
1253   (if (and (numeric-type-real-p x)
1254            (numeric-type-real-p y))
1255       (let ((result
1256              ;; (- X X) is always 0.
1257              (if same-arg
1258                  (make-interval :low 0 :high 0)
1259                  (interval-sub (numeric-type->interval x)
1260                                (numeric-type->interval y))))
1261             (result-type (numeric-contagion x y)))
1262         ;; If the result type is a float, we need to be sure to coerce
1263         ;; the bounds into the correct type.
1264         (when (eq (numeric-type-class result-type) 'float)
1265           (setf result (interval-func
1266                         #'(lambda (x)
1267                             (coerce x (or (numeric-type-format result-type)
1268                                           'float)))
1269                         result)))
1270         (make-numeric-type
1271          :class (if (and (eq (numeric-type-class x) 'integer)
1272                          (eq (numeric-type-class y) 'integer))
1273                     ;; The difference of integers is always an integer.
1274                     'integer
1275                     (numeric-type-class result-type))
1276          :format (numeric-type-format result-type)
1277          :low (interval-low result)
1278          :high (interval-high result)))
1279       ;; general contagion
1280       (numeric-contagion x y)))
1281
1282 (defoptimizer (- derive-type) ((x y))
1283   (two-arg-derive-type x y #'--derive-type-aux #'-))
1284
1285 (defun *-derive-type-aux (x y same-arg)
1286   (if (and (numeric-type-real-p x)
1287            (numeric-type-real-p y))
1288       (let ((result
1289              ;; (* X X) is always positive, so take care to do it right.
1290              (if same-arg
1291                  (interval-sqr (numeric-type->interval x))
1292                  (interval-mul (numeric-type->interval x)
1293                                (numeric-type->interval y))))
1294             (result-type (numeric-contagion x y)))
1295         ;; If the result type is a float, we need to be sure to coerce
1296         ;; the bounds into the correct type.
1297         (when (eq (numeric-type-class result-type) 'float)
1298           (setf result (interval-func
1299                         #'(lambda (x)
1300                             (coerce x (or (numeric-type-format result-type)
1301                                           'float)))
1302                         result)))
1303         (make-numeric-type
1304          :class (if (and (eq (numeric-type-class x) 'integer)
1305                          (eq (numeric-type-class y) 'integer))
1306                     ;; The product of integers is always an integer.
1307                     'integer
1308                     (numeric-type-class result-type))
1309          :format (numeric-type-format result-type)
1310          :low (interval-low result)
1311          :high (interval-high result)))
1312       (numeric-contagion x y)))
1313
1314 (defoptimizer (* derive-type) ((x y))
1315   (two-arg-derive-type x y #'*-derive-type-aux #'*))
1316
1317 (defun /-derive-type-aux (x y same-arg)
1318   (if (and (numeric-type-real-p x)
1319            (numeric-type-real-p y))
1320       (let ((result
1321              ;; (/ X X) is always 1, except if X can contain 0. In
1322              ;; that case, we shouldn't optimize the division away
1323              ;; because we want 0/0 to signal an error.
1324              (if (and same-arg
1325                       (not (interval-contains-p
1326                             0 (interval-closure (numeric-type->interval y)))))
1327                  (make-interval :low 1 :high 1)
1328                  (interval-div (numeric-type->interval x)
1329                                (numeric-type->interval y))))
1330             (result-type (numeric-contagion x y)))
1331         ;; If the result type is a float, we need to be sure to coerce
1332         ;; the bounds into the correct type.
1333         (when (eq (numeric-type-class result-type) 'float)
1334           (setf result (interval-func
1335                         #'(lambda (x)
1336                             (coerce x (or (numeric-type-format result-type)
1337                                           'float)))
1338                         result)))
1339         (make-numeric-type :class (numeric-type-class result-type)
1340                            :format (numeric-type-format result-type)
1341                            :low (interval-low result)
1342                            :high (interval-high result)))
1343       (numeric-contagion x y)))
1344
1345 (defoptimizer (/ derive-type) ((x y))
1346   (two-arg-derive-type x y #'/-derive-type-aux #'/))
1347
1348 ) ; PROGN
1349
1350 (defun ash-derive-type-aux (n-type shift same-arg)
1351   (declare (ignore same-arg))
1352   ;; KLUDGE: All this ASH optimization is suppressed under CMU CL for
1353   ;; some bignum cases because as of version 2.4.6 for Debian and 18d,
1354   ;; CMU CL blows up on (ASH 1000000000 -100000000000) (i.e. ASH of
1355   ;; two bignums yielding zero) and it's hard to avoid that
1356   ;; calculation in here.
1357   #+(and cmu sb-xc-host)
1358   (when (and (or (typep (numeric-type-low n-type) 'bignum)
1359                  (typep (numeric-type-high n-type) 'bignum))
1360              (or (typep (numeric-type-low shift) 'bignum)
1361                  (typep (numeric-type-high shift) 'bignum)))
1362     (return-from ash-derive-type-aux *universal-type*))
1363   (flet ((ash-outer (n s)
1364            (when (and (fixnump s)
1365                       (<= s 64)
1366                       (> s sb!xc:most-negative-fixnum))
1367              (ash n s)))
1368          ;; KLUDGE: The bare 64's here should be related to
1369          ;; symbolic machine word size values somehow.
1370
1371          (ash-inner (n s)
1372            (if (and (fixnump s)
1373                     (> s sb!xc:most-negative-fixnum))
1374              (ash n (min s 64))
1375              (if (minusp n) -1 0))))
1376     (or (and (csubtypep n-type (specifier-type 'integer))
1377              (csubtypep shift (specifier-type 'integer))
1378              (let ((n-low (numeric-type-low n-type))
1379                    (n-high (numeric-type-high n-type))
1380                    (s-low (numeric-type-low shift))
1381                    (s-high (numeric-type-high shift)))
1382                (make-numeric-type :class 'integer  :complexp :real
1383                                   :low (when n-low
1384                                          (if (minusp n-low)
1385                                            (ash-outer n-low s-high)
1386                                            (ash-inner n-low s-low)))
1387                                   :high (when n-high
1388                                           (if (minusp n-high)
1389                                             (ash-inner n-high s-low)
1390                                             (ash-outer n-high s-high))))))
1391         *universal-type*)))
1392
1393 (defoptimizer (ash derive-type) ((n shift))
1394   (two-arg-derive-type n shift #'ash-derive-type-aux #'ash))
1395
1396 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1397 (macrolet ((frob (fun)
1398              `#'(lambda (type type2)
1399                   (declare (ignore type2))
1400                   (let ((lo (numeric-type-low type))
1401                         (hi (numeric-type-high type)))
1402                     (values (if hi (,fun hi) nil) (if lo (,fun lo) nil))))))
1403
1404   (defoptimizer (%negate derive-type) ((num))
1405     (derive-integer-type num num (frob -))))
1406
1407 (defoptimizer (lognot derive-type) ((int))
1408   (derive-integer-type int int
1409                        (lambda (type type2)
1410                          (declare (ignore type2))
1411                          (let ((lo (numeric-type-low type))
1412                                (hi (numeric-type-high type)))
1413                            (values (if hi (lognot hi) nil)
1414                                    (if lo (lognot lo) nil)
1415                                    (numeric-type-class type)
1416                                    (numeric-type-format type))))))
1417
1418 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1419 (defoptimizer (%negate derive-type) ((num))
1420   (flet ((negate-bound (b)
1421            (and b
1422                 (set-bound (- (type-bound-number b))
1423                            (consp b)))))
1424     (one-arg-derive-type num
1425                          (lambda (type)
1426                            (modified-numeric-type
1427                             type
1428                             :low (negate-bound (numeric-type-high type))
1429                             :high (negate-bound (numeric-type-low type))))
1430                          #'-)))
1431
1432 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1433 (defoptimizer (abs derive-type) ((num))
1434   (let ((type (continuation-type num)))
1435     (if (and (numeric-type-p type)
1436              (eq (numeric-type-class type) 'integer)
1437              (eq (numeric-type-complexp type) :real))
1438         (let ((lo (numeric-type-low type))
1439               (hi (numeric-type-high type)))
1440           (make-numeric-type :class 'integer :complexp :real
1441                              :low (cond ((and hi (minusp hi))
1442                                          (abs hi))
1443                                         (lo
1444                                          (max 0 lo))
1445                                         (t
1446                                          0))
1447                              :high (if (and hi lo)
1448                                        (max (abs hi) (abs lo))
1449                                        nil)))
1450         (numeric-contagion type type))))
1451
1452 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1453 (defun abs-derive-type-aux (type)
1454   (cond ((eq (numeric-type-complexp type) :complex)
1455          ;; The absolute value of a complex number is always a
1456          ;; non-negative float.
1457          (let* ((format (case (numeric-type-class type)
1458                           ((integer rational) 'single-float)
1459                           (t (numeric-type-format type))))
1460                 (bound-format (or format 'float)))
1461            (make-numeric-type :class 'float
1462                               :format format
1463                               :complexp :real
1464                               :low (coerce 0 bound-format)
1465                               :high nil)))
1466         (t
1467          ;; The absolute value of a real number is a non-negative real
1468          ;; of the same type.
1469          (let* ((abs-bnd (interval-abs (numeric-type->interval type)))
1470                 (class (numeric-type-class type))
1471                 (format (numeric-type-format type))
1472                 (bound-type (or format class 'real)))
1473            (make-numeric-type
1474             :class class
1475             :format format
1476             :complexp :real
1477             :low (coerce-numeric-bound (interval-low abs-bnd) bound-type)
1478             :high (coerce-numeric-bound
1479                    (interval-high abs-bnd) bound-type))))))
1480
1481 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1482 (defoptimizer (abs derive-type) ((num))
1483   (one-arg-derive-type num #'abs-derive-type-aux #'abs))
1484
1485 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1486 (defoptimizer (truncate derive-type) ((number divisor))
1487   (let ((number-type (continuation-type number))
1488         (divisor-type (continuation-type divisor))
1489         (integer-type (specifier-type 'integer)))
1490     (if (and (numeric-type-p number-type)
1491              (csubtypep number-type integer-type)
1492              (numeric-type-p divisor-type)
1493              (csubtypep divisor-type integer-type))
1494         (let ((number-low (numeric-type-low number-type))
1495               (number-high (numeric-type-high number-type))
1496               (divisor-low (numeric-type-low divisor-type))
1497               (divisor-high (numeric-type-high divisor-type)))
1498           (values-specifier-type
1499            `(values ,(integer-truncate-derive-type number-low number-high
1500                                                    divisor-low divisor-high)
1501                     ,(integer-rem-derive-type number-low number-high
1502                                               divisor-low divisor-high))))
1503         *universal-type*)))
1504
1505 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1506 (progn
1507
1508 (defun rem-result-type (number-type divisor-type)
1509   ;; Figure out what the remainder type is. The remainder is an
1510   ;; integer if both args are integers; a rational if both args are
1511   ;; rational; and a float otherwise.
1512   (cond ((and (csubtypep number-type (specifier-type 'integer))
1513               (csubtypep divisor-type (specifier-type 'integer)))
1514          'integer)
1515         ((and (csubtypep number-type (specifier-type 'rational))
1516               (csubtypep divisor-type (specifier-type 'rational)))
1517          'rational)
1518         ((and (csubtypep number-type (specifier-type 'float))
1519               (csubtypep divisor-type (specifier-type 'float)))
1520          ;; Both are floats so the result is also a float, of
1521          ;; the largest type.
1522          (or (float-format-max (numeric-type-format number-type)
1523                                (numeric-type-format divisor-type))
1524              'float))
1525         ((and (csubtypep number-type (specifier-type 'float))
1526               (csubtypep divisor-type (specifier-type 'rational)))
1527          ;; One of the arguments is a float and the other is a
1528          ;; rational. The remainder is a float of the same
1529          ;; type.
1530          (or (numeric-type-format number-type) 'float))
1531         ((and (csubtypep divisor-type (specifier-type 'float))
1532               (csubtypep number-type (specifier-type 'rational)))
1533          ;; One of the arguments is a float and the other is a
1534          ;; rational. The remainder is a float of the same
1535          ;; type.
1536          (or (numeric-type-format divisor-type) 'float))
1537         (t
1538          ;; Some unhandled combination. This usually means both args
1539          ;; are REAL so the result is a REAL.
1540          'real)))
1541
1542 (defun truncate-derive-type-quot (number-type divisor-type)
1543   (let* ((rem-type (rem-result-type number-type divisor-type))
1544          (number-interval (numeric-type->interval number-type))
1545          (divisor-interval (numeric-type->interval divisor-type)))
1546     ;;(declare (type (member '(integer rational float)) rem-type))
1547     ;; We have real numbers now.
1548     (cond ((eq rem-type 'integer)
1549            ;; Since the remainder type is INTEGER, both args are
1550            ;; INTEGERs.
1551            (let* ((res (integer-truncate-derive-type
1552                         (interval-low number-interval)
1553                         (interval-high number-interval)
1554                         (interval-low divisor-interval)
1555                         (interval-high divisor-interval))))
1556              (specifier-type (if (listp res) res 'integer))))
1557           (t
1558            (let ((quot (truncate-quotient-bound
1559                         (interval-div number-interval
1560                                       divisor-interval))))
1561              (specifier-type `(integer ,(or (interval-low quot) '*)
1562                                        ,(or (interval-high quot) '*))))))))
1563
1564 (defun truncate-derive-type-rem (number-type divisor-type)
1565   (let* ((rem-type (rem-result-type number-type divisor-type))
1566          (number-interval (numeric-type->interval number-type))
1567          (divisor-interval (numeric-type->interval divisor-type))
1568          (rem (truncate-rem-bound number-interval divisor-interval)))
1569     ;;(declare (type (member '(integer rational float)) rem-type))
1570     ;; We have real numbers now.
1571     (cond ((eq rem-type 'integer)
1572            ;; Since the remainder type is INTEGER, both args are
1573            ;; INTEGERs.
1574            (specifier-type `(,rem-type ,(or (interval-low rem) '*)
1575                                        ,(or (interval-high rem) '*))))
1576           (t
1577            (multiple-value-bind (class format)
1578                (ecase rem-type
1579                  (integer
1580                   (values 'integer nil))
1581                  (rational
1582                   (values 'rational nil))
1583                  ((or single-float double-float #!+long-float long-float)
1584                   (values 'float rem-type))
1585                  (float
1586                   (values 'float nil))
1587                  (real
1588                   (values nil nil)))
1589              (when (member rem-type '(float single-float double-float
1590                                             #!+long-float long-float))
1591                (setf rem (interval-func #'(lambda (x)
1592                                             (coerce x rem-type))
1593                                         rem)))
1594              (make-numeric-type :class class
1595                                 :format format
1596                                 :low (interval-low rem)
1597                                 :high (interval-high rem)))))))
1598
1599 (defun truncate-derive-type-quot-aux (num div same-arg)
1600   (declare (ignore same-arg))
1601   (if (and (numeric-type-real-p num)
1602            (numeric-type-real-p div))
1603       (truncate-derive-type-quot num div)
1604       *empty-type*))
1605
1606 (defun truncate-derive-type-rem-aux (num div same-arg)
1607   (declare (ignore same-arg))
1608   (if (and (numeric-type-real-p num)
1609            (numeric-type-real-p div))
1610       (truncate-derive-type-rem num div)
1611       *empty-type*))
1612
1613 (defoptimizer (truncate derive-type) ((number divisor))
1614   (let ((quot (two-arg-derive-type number divisor
1615                                    #'truncate-derive-type-quot-aux #'truncate))
1616         (rem (two-arg-derive-type number divisor
1617                                   #'truncate-derive-type-rem-aux #'rem)))
1618     (when (and quot rem)
1619       (make-values-type :required (list quot rem)))))
1620
1621 (defun ftruncate-derive-type-quot (number-type divisor-type)
1622   ;; The bounds are the same as for truncate. However, the first
1623   ;; result is a float of some type. We need to determine what that
1624   ;; type is. Basically it's the more contagious of the two types.
1625   (let ((q-type (truncate-derive-type-quot number-type divisor-type))
1626         (res-type (numeric-contagion number-type divisor-type)))
1627     (make-numeric-type :class 'float
1628                        :format (numeric-type-format res-type)
1629                        :low (numeric-type-low q-type)
1630                        :high (numeric-type-high q-type))))
1631
1632 (defun ftruncate-derive-type-quot-aux (n d same-arg)
1633   (declare (ignore same-arg))
1634   (if (and (numeric-type-real-p n)
1635            (numeric-type-real-p d))
1636       (ftruncate-derive-type-quot n d)
1637       *empty-type*))
1638
1639 (defoptimizer (ftruncate derive-type) ((number divisor))
1640   (let ((quot
1641          (two-arg-derive-type number divisor
1642                               #'ftruncate-derive-type-quot-aux #'ftruncate))
1643         (rem (two-arg-derive-type number divisor
1644                                   #'truncate-derive-type-rem-aux #'rem)))
1645     (when (and quot rem)
1646       (make-values-type :required (list quot rem)))))
1647
1648 (defun %unary-truncate-derive-type-aux (number)
1649   (truncate-derive-type-quot number (specifier-type '(integer 1 1))))
1650
1651 (defoptimizer (%unary-truncate derive-type) ((number))
1652   (one-arg-derive-type number
1653                        #'%unary-truncate-derive-type-aux
1654                        #'%unary-truncate))
1655
1656 ;;; Define optimizers for FLOOR and CEILING.
1657 (macrolet
1658     ((def (name q-name r-name)
1659        (let ((q-aux (symbolicate q-name "-AUX"))
1660              (r-aux (symbolicate r-name "-AUX")))
1661          `(progn
1662            ;; Compute type of quotient (first) result.
1663            (defun ,q-aux (number-type divisor-type)
1664              (let* ((number-interval
1665                      (numeric-type->interval number-type))
1666                     (divisor-interval
1667                      (numeric-type->interval divisor-type))
1668                     (quot (,q-name (interval-div number-interval
1669                                                  divisor-interval))))
1670                (specifier-type `(integer ,(or (interval-low quot) '*)
1671                                          ,(or (interval-high quot) '*)))))
1672            ;; Compute type of remainder.
1673            (defun ,r-aux (number-type divisor-type)
1674              (let* ((divisor-interval
1675                      (numeric-type->interval divisor-type))
1676                     (rem (,r-name divisor-interval))
1677                     (result-type (rem-result-type number-type divisor-type)))
1678                (multiple-value-bind (class format)
1679                    (ecase result-type
1680                      (integer
1681                       (values 'integer nil))
1682                      (rational
1683                       (values 'rational nil))
1684                      ((or single-float double-float #!+long-float long-float)
1685                       (values 'float result-type))
1686                      (float
1687                       (values 'float nil))
1688                      (real
1689                       (values nil nil)))
1690                  (when (member result-type '(float single-float double-float
1691                                              #!+long-float long-float))
1692                    ;; Make sure that the limits on the interval have
1693                    ;; the right type.
1694                    (setf rem (interval-func (lambda (x)
1695                                               (coerce x result-type))
1696                                             rem)))
1697                  (make-numeric-type :class class
1698                                     :format format
1699                                     :low (interval-low rem)
1700                                     :high (interval-high rem)))))
1701            ;; the optimizer itself
1702            (defoptimizer (,name derive-type) ((number divisor))
1703              (flet ((derive-q (n d same-arg)
1704                       (declare (ignore same-arg))
1705                       (if (and (numeric-type-real-p n)
1706                                (numeric-type-real-p d))
1707                           (,q-aux n d)
1708                           *empty-type*))
1709                     (derive-r (n d same-arg)
1710                       (declare (ignore same-arg))
1711                       (if (and (numeric-type-real-p n)
1712                                (numeric-type-real-p d))
1713                           (,r-aux n d)
1714                           *empty-type*)))
1715                (let ((quot (two-arg-derive-type
1716                             number divisor #'derive-q #',name))
1717                      (rem (two-arg-derive-type
1718                            number divisor #'derive-r #'mod)))
1719                  (when (and quot rem)
1720                    (make-values-type :required (list quot rem))))))))))
1721
1722   (def floor floor-quotient-bound floor-rem-bound)
1723   (def ceiling ceiling-quotient-bound ceiling-rem-bound))
1724
1725 ;;; Define optimizers for FFLOOR and FCEILING
1726 (macrolet ((def (name q-name r-name)
1727              (let ((q-aux (symbolicate "F" q-name "-AUX"))
1728                    (r-aux (symbolicate r-name "-AUX")))
1729                `(progn
1730                   ;; Compute type of quotient (first) result.
1731                   (defun ,q-aux (number-type divisor-type)
1732                     (let* ((number-interval
1733                             (numeric-type->interval number-type))
1734                            (divisor-interval
1735                             (numeric-type->interval divisor-type))
1736                            (quot (,q-name (interval-div number-interval
1737                                                         divisor-interval)))
1738                            (res-type (numeric-contagion number-type
1739                                                         divisor-type)))
1740                       (make-numeric-type
1741                        :class (numeric-type-class res-type)
1742                        :format (numeric-type-format res-type)
1743                        :low  (interval-low quot)
1744                        :high (interval-high quot))))
1745
1746                   (defoptimizer (,name derive-type) ((number divisor))
1747                     (flet ((derive-q (n d same-arg)
1748                              (declare (ignore same-arg))
1749                              (if (and (numeric-type-real-p n)
1750                                       (numeric-type-real-p d))
1751                                  (,q-aux n d)
1752                                  *empty-type*))
1753                            (derive-r (n d same-arg)
1754                              (declare (ignore same-arg))
1755                              (if (and (numeric-type-real-p n)
1756                                       (numeric-type-real-p d))
1757                                  (,r-aux n d)
1758                                  *empty-type*)))
1759                       (let ((quot (two-arg-derive-type
1760                                    number divisor #'derive-q #',name))
1761                             (rem (two-arg-derive-type
1762                                   number divisor #'derive-r #'mod)))
1763                         (when (and quot rem)
1764                           (make-values-type :required (list quot rem))))))))))
1765
1766   (def ffloor floor-quotient-bound floor-rem-bound)
1767   (def fceiling ceiling-quotient-bound ceiling-rem-bound))
1768
1769 ;;; functions to compute the bounds on the quotient and remainder for
1770 ;;; the FLOOR function
1771 (defun floor-quotient-bound (quot)
1772   ;; Take the floor of the quotient and then massage it into what we
1773   ;; need.
1774   (let ((lo (interval-low quot))
1775         (hi (interval-high quot)))
1776     ;; Take the floor of the lower bound. The result is always a
1777     ;; closed lower bound.
1778     (setf lo (if lo
1779                  (floor (type-bound-number lo))
1780                  nil))
1781     ;; For the upper bound, we need to be careful.
1782     (setf hi
1783           (cond ((consp hi)
1784                  ;; An open bound. We need to be careful here because
1785                  ;; the floor of '(10.0) is 9, but the floor of
1786                  ;; 10.0 is 10.
1787                  (multiple-value-bind (q r) (floor (first hi))
1788                    (if (zerop r)
1789                        (1- q)
1790                        q)))
1791                 (hi
1792                  ;; A closed bound, so the answer is obvious.
1793                  (floor hi))
1794                 (t
1795                  hi)))
1796     (make-interval :low lo :high hi)))
1797 (defun floor-rem-bound (div)
1798   ;; The remainder depends only on the divisor. Try to get the
1799   ;; correct sign for the remainder if we can.
1800   (case (interval-range-info div)
1801     (+
1802      ;; The divisor is always positive.
1803      (let ((rem (interval-abs div)))
1804        (setf (interval-low rem) 0)
1805        (when (and (numberp (interval-high rem))
1806                   (not (zerop (interval-high rem))))
1807          ;; The remainder never contains the upper bound. However,
1808          ;; watch out for the case where the high limit is zero!
1809          (setf (interval-high rem) (list (interval-high rem))))
1810        rem))
1811     (-
1812      ;; The divisor is always negative.
1813      (let ((rem (interval-neg (interval-abs div))))
1814        (setf (interval-high rem) 0)
1815        (when (numberp (interval-low rem))
1816          ;; The remainder never contains the lower bound.
1817          (setf (interval-low rem) (list (interval-low rem))))
1818        rem))
1819     (otherwise
1820      ;; The divisor can be positive or negative. All bets off. The
1821      ;; magnitude of remainder is the maximum value of the divisor.
1822      (let ((limit (type-bound-number (interval-high (interval-abs div)))))
1823        ;; The bound never reaches the limit, so make the interval open.
1824        (make-interval :low (if limit
1825                                (list (- limit))
1826                                limit)
1827                       :high (list limit))))))
1828 #| Test cases
1829 (floor-quotient-bound (make-interval :low 0.3 :high 10.3))
1830 => #S(INTERVAL :LOW 0 :HIGH 10)
1831 (floor-quotient-bound (make-interval :low 0.3 :high '(10.3)))
1832 => #S(INTERVAL :LOW 0 :HIGH 10)
1833 (floor-quotient-bound (make-interval :low 0.3 :high 10))
1834 => #S(INTERVAL :LOW 0 :HIGH 10)
1835 (floor-quotient-bound (make-interval :low 0.3 :high '(10)))
1836 => #S(INTERVAL :LOW 0 :HIGH 9)
1837 (floor-quotient-bound (make-interval :low '(0.3) :high 10.3))
1838 => #S(INTERVAL :LOW 0 :HIGH 10)
1839 (floor-quotient-bound (make-interval :low '(0.0) :high 10.3))
1840 => #S(INTERVAL :LOW 0 :HIGH 10)
1841 (floor-quotient-bound (make-interval :low '(-1.3) :high 10.3))
1842 => #S(INTERVAL :LOW -2 :HIGH 10)
1843 (floor-quotient-bound (make-interval :low '(-1.0) :high 10.3))
1844 => #S(INTERVAL :LOW -1 :HIGH 10)
1845 (floor-quotient-bound (make-interval :low -1.0 :high 10.3))
1846 => #S(INTERVAL :LOW -1 :HIGH 10)
1847
1848 (floor-rem-bound (make-interval :low 0.3 :high 10.3))
1849 => #S(INTERVAL :LOW 0 :HIGH '(10.3))
1850 (floor-rem-bound (make-interval :low 0.3 :high '(10.3)))
1851 => #S(INTERVAL :LOW 0 :HIGH '(10.3))
1852 (floor-rem-bound (make-interval :low -10 :high -2.3))
1853 #S(INTERVAL :LOW (-10) :HIGH 0)
1854 (floor-rem-bound (make-interval :low 0.3 :high 10))
1855 => #S(INTERVAL :LOW 0 :HIGH '(10))
1856 (floor-rem-bound (make-interval :low '(-1.3) :high 10.3))
1857 => #S(INTERVAL :LOW '(-10.3) :HIGH '(10.3))
1858 (floor-rem-bound (make-interval :low '(-20.3) :high 10.3))
1859 => #S(INTERVAL :LOW (-20.3) :HIGH (20.3))
1860 |#
1861 \f
1862 ;;; same functions for CEILING
1863 (defun ceiling-quotient-bound (quot)
1864   ;; Take the ceiling of the quotient and then massage it into what we
1865   ;; need.
1866   (let ((lo (interval-low quot))
1867         (hi (interval-high quot)))
1868     ;; Take the ceiling of the upper bound. The result is always a
1869     ;; closed upper bound.
1870     (setf hi (if hi
1871                  (ceiling (type-bound-number hi))
1872                  nil))
1873     ;; For the lower bound, we need to be careful.
1874     (setf lo
1875           (cond ((consp lo)
1876                  ;; An open bound. We need to be careful here because
1877                  ;; the ceiling of '(10.0) is 11, but the ceiling of
1878                  ;; 10.0 is 10.
1879                  (multiple-value-bind (q r) (ceiling (first lo))
1880                    (if (zerop r)
1881                        (1+ q)
1882                        q)))
1883                 (lo
1884                  ;; A closed bound, so the answer is obvious.
1885                  (ceiling lo))
1886                 (t
1887                  lo)))
1888     (make-interval :low lo :high hi)))
1889 (defun ceiling-rem-bound (div)
1890   ;; The remainder depends only on the divisor. Try to get the
1891   ;; correct sign for the remainder if we can.
1892   (case (interval-range-info div)
1893     (+
1894      ;; Divisor is always positive. The remainder is negative.
1895      (let ((rem (interval-neg (interval-abs div))))
1896        (setf (interval-high rem) 0)
1897        (when (and (numberp (interval-low rem))
1898                   (not (zerop (interval-low rem))))
1899          ;; The remainder never contains the upper bound. However,
1900          ;; watch out for the case when the upper bound is zero!
1901          (setf (interval-low rem) (list (interval-low rem))))
1902        rem))
1903     (-
1904      ;; Divisor is always negative. The remainder is positive
1905      (let ((rem (interval-abs div)))
1906        (setf (interval-low rem) 0)
1907        (when (numberp (interval-high rem))
1908          ;; The remainder never contains the lower bound.
1909          (setf (interval-high rem) (list (interval-high rem))))
1910        rem))
1911     (otherwise
1912      ;; The divisor can be positive or negative. All bets off. The
1913      ;; magnitude of remainder is the maximum value of the divisor.
1914      (let ((limit (type-bound-number (interval-high (interval-abs div)))))
1915        ;; The bound never reaches the limit, so make the interval open.
1916        (make-interval :low (if limit
1917                                (list (- limit))
1918                                limit)
1919                       :high (list limit))))))
1920
1921 #| Test cases
1922 (ceiling-quotient-bound (make-interval :low 0.3 :high 10.3))
1923 => #S(INTERVAL :LOW 1 :HIGH 11)
1924 (ceiling-quotient-bound (make-interval :low 0.3 :high '(10.3)))
1925 => #S(INTERVAL :LOW 1 :HIGH 11)
1926 (ceiling-quotient-bound (make-interval :low 0.3 :high 10))
1927 => #S(INTERVAL :LOW 1 :HIGH 10)
1928 (ceiling-quotient-bound (make-interval :low 0.3 :high '(10)))
1929 => #S(INTERVAL :LOW 1 :HIGH 10)
1930 (ceiling-quotient-bound (make-interval :low '(0.3) :high 10.3))
1931 => #S(INTERVAL :LOW 1 :HIGH 11)
1932 (ceiling-quotient-bound (make-interval :low '(0.0) :high 10.3))
1933 => #S(INTERVAL :LOW 1 :HIGH 11)
1934 (ceiling-quotient-bound (make-interval :low '(-1.3) :high 10.3))
1935 => #S(INTERVAL :LOW -1 :HIGH 11)
1936 (ceiling-quotient-bound (make-interval :low '(-1.0) :high 10.3))
1937 => #S(INTERVAL :LOW 0 :HIGH 11)
1938 (ceiling-quotient-bound (make-interval :low -1.0 :high 10.3))
1939 => #S(INTERVAL :LOW -1 :HIGH 11)
1940
1941 (ceiling-rem-bound (make-interval :low 0.3 :high 10.3))
1942 => #S(INTERVAL :LOW (-10.3) :HIGH 0)
1943 (ceiling-rem-bound (make-interval :low 0.3 :high '(10.3)))
1944 => #S(INTERVAL :LOW 0 :HIGH '(10.3))
1945 (ceiling-rem-bound (make-interval :low -10 :high -2.3))
1946 => #S(INTERVAL :LOW 0 :HIGH (10))
1947 (ceiling-rem-bound (make-interval :low 0.3 :high 10))
1948 => #S(INTERVAL :LOW (-10) :HIGH 0)
1949 (ceiling-rem-bound (make-interval :low '(-1.3) :high 10.3))
1950 => #S(INTERVAL :LOW (-10.3) :HIGH (10.3))
1951 (ceiling-rem-bound (make-interval :low '(-20.3) :high 10.3))
1952 => #S(INTERVAL :LOW (-20.3) :HIGH (20.3))
1953 |#
1954 \f
1955 (defun truncate-quotient-bound (quot)
1956   ;; For positive quotients, truncate is exactly like floor. For
1957   ;; negative quotients, truncate is exactly like ceiling. Otherwise,
1958   ;; it's the union of the two pieces.
1959   (case (interval-range-info quot)
1960     (+
1961      ;; just like FLOOR
1962      (floor-quotient-bound quot))
1963     (-
1964      ;; just like CEILING
1965      (ceiling-quotient-bound quot))
1966     (otherwise
1967      ;; Split the interval into positive and negative pieces, compute
1968      ;; the result for each piece and put them back together.
1969      (destructuring-bind (neg pos) (interval-split 0 quot t t)
1970        (interval-merge-pair (ceiling-quotient-bound neg)
1971                             (floor-quotient-bound pos))))))
1972
1973 (defun truncate-rem-bound (num div)
1974   ;; This is significantly more complicated than FLOOR or CEILING. We
1975   ;; need both the number and the divisor to determine the range. The
1976   ;; basic idea is to split the ranges of NUM and DEN into positive
1977   ;; and negative pieces and deal with each of the four possibilities
1978   ;; in turn.
1979   (case (interval-range-info num)
1980     (+
1981      (case (interval-range-info div)
1982        (+
1983         (floor-rem-bound div))
1984        (-
1985         (ceiling-rem-bound div))
1986        (otherwise
1987         (destructuring-bind (neg pos) (interval-split 0 div t t)
1988           (interval-merge-pair (truncate-rem-bound num neg)
1989                                (truncate-rem-bound num pos))))))
1990     (-
1991      (case (interval-range-info div)
1992        (+
1993         (ceiling-rem-bound div))
1994        (-
1995         (floor-rem-bound div))
1996        (otherwise
1997         (destructuring-bind (neg pos) (interval-split 0 div t t)
1998           (interval-merge-pair (truncate-rem-bound num neg)
1999                                (truncate-rem-bound num pos))))))
2000     (otherwise
2001      (destructuring-bind (neg pos) (interval-split 0 num t t)
2002        (interval-merge-pair (truncate-rem-bound neg div)
2003                             (truncate-rem-bound pos div))))))
2004 ) ; PROGN
2005
2006 ;;; Derive useful information about the range. Returns three values:
2007 ;;; - '+ if its positive, '- negative, or nil if it overlaps 0.
2008 ;;; - The abs of the minimal value (i.e. closest to 0) in the range.
2009 ;;; - The abs of the maximal value if there is one, or nil if it is
2010 ;;;   unbounded.
2011 (defun numeric-range-info (low high)
2012   (cond ((and low (not (minusp low)))
2013          (values '+ low high))
2014         ((and high (not (plusp high)))
2015          (values '- (- high) (if low (- low) nil)))
2016         (t
2017          (values nil 0 (and low high (max (- low) high))))))
2018
2019 (defun integer-truncate-derive-type
2020        (number-low number-high divisor-low divisor-high)
2021   ;; The result cannot be larger in magnitude than the number, but the
2022   ;; sign might change. If we can determine the sign of either the
2023   ;; number or the divisor, we can eliminate some of the cases.
2024   (multiple-value-bind (number-sign number-min number-max)
2025       (numeric-range-info number-low number-high)
2026     (multiple-value-bind (divisor-sign divisor-min divisor-max)
2027         (numeric-range-info divisor-low divisor-high)
2028       (when (and divisor-max (zerop divisor-max))
2029         ;; We've got a problem: guaranteed division by zero.
2030         (return-from integer-truncate-derive-type t))
2031       (when (zerop divisor-min)
2032         ;; We'll assume that they aren't going to divide by zero.
2033         (incf divisor-min))
2034       (cond ((and number-sign divisor-sign)
2035              ;; We know the sign of both.
2036              (if (eq number-sign divisor-sign)
2037                  ;; Same sign, so the result will be positive.
2038                  `(integer ,(if divisor-max
2039                                 (truncate number-min divisor-max)
2040                                 0)
2041                            ,(if number-max
2042                                 (truncate number-max divisor-min)
2043                                 '*))
2044                  ;; Different signs, the result will be negative.
2045                  `(integer ,(if number-max
2046                                 (- (truncate number-max divisor-min))
2047                                 '*)
2048                            ,(if divisor-max
2049                                 (- (truncate number-min divisor-max))
2050                                 0))))
2051             ((eq divisor-sign '+)
2052              ;; The divisor is positive. Therefore, the number will just
2053              ;; become closer to zero.
2054              `(integer ,(if number-low
2055                             (truncate number-low divisor-min)
2056                             '*)
2057                        ,(if number-high
2058                             (truncate number-high divisor-min)
2059                             '*)))
2060             ((eq divisor-sign '-)
2061              ;; The divisor is negative. Therefore, the absolute value of
2062              ;; the number will become closer to zero, but the sign will also
2063              ;; change.
2064              `(integer ,(if number-high
2065                             (- (truncate number-high divisor-min))
2066                             '*)
2067                        ,(if number-low
2068                             (- (truncate number-low divisor-min))
2069                             '*)))
2070             ;; The divisor could be either positive or negative.
2071             (number-max
2072              ;; The number we are dividing has a bound. Divide that by the
2073              ;; smallest posible divisor.
2074              (let ((bound (truncate number-max divisor-min)))
2075                `(integer ,(- bound) ,bound)))
2076             (t
2077              ;; The number we are dividing is unbounded, so we can't tell
2078              ;; anything about the result.
2079              `integer)))))
2080
2081 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2082 (defun integer-rem-derive-type
2083        (number-low number-high divisor-low divisor-high)
2084   (if (and divisor-low divisor-high)
2085       ;; We know the range of the divisor, and the remainder must be
2086       ;; smaller than the divisor. We can tell the sign of the
2087       ;; remainer if we know the sign of the number.
2088       (let ((divisor-max (1- (max (abs divisor-low) (abs divisor-high)))))
2089         `(integer ,(if (or (null number-low)
2090                            (minusp number-low))
2091                        (- divisor-max)
2092                        0)
2093                   ,(if (or (null number-high)
2094                            (plusp number-high))
2095                        divisor-max
2096                        0)))
2097       ;; The divisor is potentially either very positive or very
2098       ;; negative. Therefore, the remainer is unbounded, but we might
2099       ;; be able to tell something about the sign from the number.
2100       `(integer ,(if (and number-low (not (minusp number-low)))
2101                      ;; The number we are dividing is positive.
2102                      ;; Therefore, the remainder must be positive.
2103                      0
2104                      '*)
2105                 ,(if (and number-high (not (plusp number-high)))
2106                      ;; The number we are dividing is negative.
2107                      ;; Therefore, the remainder must be negative.
2108                      0
2109                      '*))))
2110
2111 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2112 (defoptimizer (random derive-type) ((bound &optional state))
2113   (let ((type (continuation-type bound)))
2114     (when (numeric-type-p type)
2115       (let ((class (numeric-type-class type))
2116             (high (numeric-type-high type))
2117             (format (numeric-type-format type)))
2118         (make-numeric-type
2119          :class class
2120          :format format
2121          :low (coerce 0 (or format class 'real))
2122          :high (cond ((not high) nil)
2123                      ((eq class 'integer) (max (1- high) 0))
2124                      ((or (consp high) (zerop high)) high)
2125                      (t `(,high))))))))
2126
2127 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2128 (defun random-derive-type-aux (type)
2129   (let ((class (numeric-type-class type))
2130         (high (numeric-type-high type))
2131         (format (numeric-type-format type)))
2132     (make-numeric-type
2133          :class class
2134          :format format
2135          :low (coerce 0 (or format class 'real))
2136          :high (cond ((not high) nil)
2137                      ((eq class 'integer) (max (1- high) 0))
2138                      ((or (consp high) (zerop high)) high)
2139                      (t `(,high))))))
2140
2141 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2142 (defoptimizer (random derive-type) ((bound &optional state))
2143   (one-arg-derive-type bound #'random-derive-type-aux nil))
2144 \f
2145 ;;;; DERIVE-TYPE methods for LOGAND, LOGIOR, and friends
2146
2147 ;;; Return the maximum number of bits an integer of the supplied type
2148 ;;; can take up, or NIL if it is unbounded. The second (third) value
2149 ;;; is T if the integer can be positive (negative) and NIL if not.
2150 ;;; Zero counts as positive.
2151 (defun integer-type-length (type)
2152   (if (numeric-type-p type)
2153       (let ((min (numeric-type-low type))
2154             (max (numeric-type-high type)))
2155         (values (and min max (max (integer-length min) (integer-length max)))
2156                 (or (null max) (not (minusp max)))
2157                 (or (null min) (minusp min))))
2158       (values nil t t)))
2159
2160 (defun logand-derive-type-aux (x y &optional same-leaf)
2161   (declare (ignore same-leaf))
2162   (multiple-value-bind (x-len x-pos x-neg) (integer-type-length x)
2163     (declare (ignore x-pos))
2164     (multiple-value-bind (y-len y-pos y-neg) (integer-type-length  y)
2165       (declare (ignore y-pos))
2166       (if (not x-neg)
2167           ;; X must be positive.
2168           (if (not y-neg)
2169               ;; They must both be positive.
2170               (cond ((or (null x-len) (null y-len))
2171                      (specifier-type 'unsigned-byte))
2172                     ((or (zerop x-len) (zerop y-len))
2173                      (specifier-type '(integer 0 0)))
2174                     (t
2175                      (specifier-type `(unsigned-byte ,(min x-len y-len)))))
2176               ;; X is positive, but Y might be negative.
2177               (cond ((null x-len)
2178                      (specifier-type 'unsigned-byte))
2179                     ((zerop x-len)
2180                      (specifier-type '(integer 0 0)))
2181                     (t
2182                      (specifier-type `(unsigned-byte ,x-len)))))
2183           ;; X might be negative.
2184           (if (not y-neg)
2185               ;; Y must be positive.
2186               (cond ((null y-len)
2187                      (specifier-type 'unsigned-byte))
2188                     ((zerop y-len)
2189                      (specifier-type '(integer 0 0)))
2190                     (t
2191                      (specifier-type
2192                       `(unsigned-byte ,y-len))))
2193               ;; Either might be negative.
2194               (if (and x-len y-len)
2195                   ;; The result is bounded.
2196                   (specifier-type `(signed-byte ,(1+ (max x-len y-len))))
2197                   ;; We can't tell squat about the result.
2198                   (specifier-type 'integer)))))))
2199
2200 (defun logior-derive-type-aux (x y &optional same-leaf)
2201   (declare (ignore same-leaf))
2202   (multiple-value-bind (x-len x-pos x-neg) (integer-type-length x)
2203     (multiple-value-bind (y-len y-pos y-neg) (integer-type-length y)
2204       (cond
2205        ((and (not x-neg) (not y-neg))
2206         ;; Both are positive.
2207         (if (and x-len y-len (zerop x-len) (zerop y-len))
2208             (specifier-type '(integer 0 0))
2209             (specifier-type `(unsigned-byte ,(if (and x-len y-len)
2210                                              (max x-len y-len)
2211                                              '*)))))
2212        ((not x-pos)
2213         ;; X must be negative.
2214         (if (not y-pos)
2215             ;; Both are negative. The result is going to be negative
2216             ;; and be the same length or shorter than the smaller.
2217             (if (and x-len y-len)
2218                 ;; It's bounded.
2219                 (specifier-type `(integer ,(ash -1 (min x-len y-len)) -1))
2220                 ;; It's unbounded.
2221                 (specifier-type '(integer * -1)))
2222             ;; X is negative, but we don't know about Y. The result
2223             ;; will be negative, but no more negative than X.
2224             (specifier-type
2225              `(integer ,(or (numeric-type-low x) '*)
2226                        -1))))
2227        (t
2228         ;; X might be either positive or negative.
2229         (if (not y-pos)
2230             ;; But Y is negative. The result will be negative.
2231             (specifier-type
2232              `(integer ,(or (numeric-type-low y) '*)
2233                        -1))
2234             ;; We don't know squat about either. It won't get any bigger.
2235             (if (and x-len y-len)
2236                 ;; Bounded.
2237                 (specifier-type `(signed-byte ,(1+ (max x-len y-len))))
2238                 ;; Unbounded.
2239                 (specifier-type 'integer))))))))
2240
2241 (defun logxor-derive-type-aux (x y &optional same-leaf)
2242   (declare (ignore same-leaf))
2243   (multiple-value-bind (x-len x-pos x-neg) (integer-type-length x)
2244     (multiple-value-bind (y-len y-pos y-neg) (integer-type-length y)
2245       (cond
2246        ((or (and (not x-neg) (not y-neg))
2247             (and (not x-pos) (not y-pos)))
2248         ;; Either both are negative or both are positive. The result
2249         ;; will be positive, and as long as the longer.
2250         (if (and x-len y-len (zerop x-len) (zerop y-len))
2251             (specifier-type '(integer 0 0))
2252             (specifier-type `(unsigned-byte ,(if (and x-len y-len)
2253                                              (max x-len y-len)
2254                                              '*)))))
2255        ((or (and (not x-pos) (not y-neg))
2256             (and (not y-neg) (not y-pos)))
2257         ;; Either X is negative and Y is positive of vice-versa. The
2258         ;; result will be negative.
2259         (specifier-type `(integer ,(if (and x-len y-len)
2260                                        (ash -1 (max x-len y-len))
2261                                        '*)
2262                                   -1)))
2263        ;; We can't tell what the sign of the result is going to be.
2264        ;; All we know is that we don't create new bits.
2265        ((and x-len y-len)
2266         (specifier-type `(signed-byte ,(1+ (max x-len y-len)))))
2267        (t
2268         (specifier-type 'integer))))))
2269
2270 (macrolet ((deffrob (logfcn)
2271              (let ((fcn-aux (symbolicate logfcn "-DERIVE-TYPE-AUX")))
2272              `(defoptimizer (,logfcn derive-type) ((x y))
2273                 (two-arg-derive-type x y #',fcn-aux #',logfcn)))))
2274   (deffrob logand)
2275   (deffrob logior)
2276   (deffrob logxor))
2277 \f
2278 ;;;; miscellaneous derive-type methods
2279
2280 (defoptimizer (integer-length derive-type) ((x))
2281   (let ((x-type (continuation-type x)))
2282     (when (and (numeric-type-p x-type)
2283                (csubtypep x-type (specifier-type 'integer)))
2284       ;; If the X is of type (INTEGER LO HI), then the INTEGER-LENGTH
2285       ;; of X is (INTEGER (MIN lo hi) (MAX lo hi), basically.  Be
2286       ;; careful about LO or HI being NIL, though.  Also, if 0 is
2287       ;; contained in X, the lower bound is obviously 0.
2288       (flet ((null-or-min (a b)
2289                (and a b (min (integer-length a)
2290                              (integer-length b))))
2291              (null-or-max (a b)
2292                (and a b (max (integer-length a)
2293                              (integer-length b)))))
2294         (let* ((min (numeric-type-low x-type))
2295                (max (numeric-type-high x-type))
2296                (min-len (null-or-min min max))
2297                (max-len (null-or-max min max)))
2298           (when (ctypep 0 x-type)
2299             (setf min-len 0))
2300           (specifier-type `(integer ,(or min-len '*) ,(or max-len '*))))))))
2301
2302 (defoptimizer (code-char derive-type) ((code))
2303   (specifier-type 'base-char))
2304
2305 (defoptimizer (values derive-type) ((&rest values))
2306   (values-specifier-type
2307    `(values ,@(mapcar (lambda (x)
2308                         (type-specifier (continuation-type x)))
2309                       values))))
2310 \f
2311 ;;;; byte operations
2312 ;;;;
2313 ;;;; We try to turn byte operations into simple logical operations.
2314 ;;;; First, we convert byte specifiers into separate size and position
2315 ;;;; arguments passed to internal %FOO functions. We then attempt to
2316 ;;;; transform the %FOO functions into boolean operations when the
2317 ;;;; size and position are constant and the operands are fixnums.
2318
2319 (macrolet (;; Evaluate body with SIZE-VAR and POS-VAR bound to
2320            ;; expressions that evaluate to the SIZE and POSITION of
2321            ;; the byte-specifier form SPEC. We may wrap a let around
2322            ;; the result of the body to bind some variables.
2323            ;;
2324            ;; If the spec is a BYTE form, then bind the vars to the
2325            ;; subforms. otherwise, evaluate SPEC and use the BYTE-SIZE
2326            ;; and BYTE-POSITION. The goal of this transformation is to
2327            ;; avoid consing up byte specifiers and then immediately
2328            ;; throwing them away.
2329            (with-byte-specifier ((size-var pos-var spec) &body body)
2330              (once-only ((spec `(macroexpand ,spec))
2331                          (temp '(gensym)))
2332                         `(if (and (consp ,spec)
2333                                   (eq (car ,spec) 'byte)
2334                                   (= (length ,spec) 3))
2335                         (let ((,size-var (second ,spec))
2336                               (,pos-var (third ,spec)))
2337                           ,@body)
2338                         (let ((,size-var `(byte-size ,,temp))
2339                               (,pos-var `(byte-position ,,temp)))
2340                           `(let ((,,temp ,,spec))
2341                              ,,@body))))))
2342
2343   (define-source-transform ldb (spec int)
2344     (with-byte-specifier (size pos spec)
2345       `(%ldb ,size ,pos ,int)))
2346
2347   (define-source-transform dpb (newbyte spec int)
2348     (with-byte-specifier (size pos spec)
2349       `(%dpb ,newbyte ,size ,pos ,int)))
2350
2351   (define-source-transform mask-field (spec int)
2352     (with-byte-specifier (size pos spec)
2353       `(%mask-field ,size ,pos ,int)))
2354
2355   (define-source-transform deposit-field (newbyte spec int)
2356     (with-byte-specifier (size pos spec)
2357       `(%deposit-field ,newbyte ,size ,pos ,int))))
2358
2359 (defoptimizer (%ldb derive-type) ((size posn num))
2360   (let ((size (continuation-type size)))
2361     (if (and (numeric-type-p size)
2362              (csubtypep size (specifier-type 'integer)))
2363         (let ((size-high (numeric-type-high size)))
2364           (if (and size-high (<= size-high sb!vm:n-word-bits))
2365               (specifier-type `(unsigned-byte ,size-high))
2366               (specifier-type 'unsigned-byte)))
2367         *universal-type*)))
2368
2369 (defoptimizer (%mask-field derive-type) ((size posn num))
2370   (let ((size (continuation-type size))
2371         (posn (continuation-type posn)))
2372     (if (and (numeric-type-p size)
2373              (csubtypep size (specifier-type 'integer))
2374              (numeric-type-p posn)
2375              (csubtypep posn (specifier-type 'integer)))
2376         (let ((size-high (numeric-type-high size))
2377               (posn-high (numeric-type-high posn)))
2378           (if (and size-high posn-high
2379                    (<= (+ size-high posn-high) sb!vm:n-word-bits))
2380               (specifier-type `(unsigned-byte ,(+ size-high posn-high)))
2381               (specifier-type 'unsigned-byte)))
2382         *universal-type*)))
2383
2384 (defoptimizer (%dpb derive-type) ((newbyte size posn int))
2385   (let ((size (continuation-type size))
2386         (posn (continuation-type posn))
2387         (int (continuation-type int)))
2388     (if (and (numeric-type-p size)
2389              (csubtypep size (specifier-type 'integer))
2390              (numeric-type-p posn)
2391              (csubtypep posn (specifier-type 'integer))
2392              (numeric-type-p int)
2393              (csubtypep int (specifier-type 'integer)))
2394         (let ((size-high (numeric-type-high size))
2395               (posn-high (numeric-type-high posn))
2396               (high (numeric-type-high int))
2397               (low (numeric-type-low int)))
2398           (if (and size-high posn-high high low
2399                    (<= (+ size-high posn-high) sb!vm:n-word-bits))
2400               (specifier-type
2401                (list (if (minusp low) 'signed-byte 'unsigned-byte)
2402                      (max (integer-length high)
2403                           (integer-length low)
2404                           (+ size-high posn-high))))
2405               *universal-type*))
2406         *universal-type*)))
2407
2408 (defoptimizer (%deposit-field derive-type) ((newbyte size posn int))
2409   (let ((size (continuation-type size))
2410         (posn (continuation-type posn))
2411         (int (continuation-type int)))
2412     (if (and (numeric-type-p size)
2413              (csubtypep size (specifier-type 'integer))
2414              (numeric-type-p posn)
2415              (csubtypep posn (specifier-type 'integer))
2416              (numeric-type-p int)
2417              (csubtypep int (specifier-type 'integer)))
2418         (let ((size-high (numeric-type-high size))
2419               (posn-high (numeric-type-high posn))
2420               (high (numeric-type-high int))
2421               (low (numeric-type-low int)))
2422           (if (and size-high posn-high high low
2423                    (<= (+ size-high posn-high) sb!vm:n-word-bits))
2424               (specifier-type
2425                (list (if (minusp low) 'signed-byte 'unsigned-byte)
2426                      (max (integer-length high)
2427                           (integer-length low)
2428                           (+ size-high posn-high))))
2429               *universal-type*))
2430         *universal-type*)))
2431
2432 (deftransform %ldb ((size posn int)
2433                     (fixnum fixnum integer)
2434                     (unsigned-byte #.sb!vm:n-word-bits))
2435   "convert to inline logical operations"
2436   `(logand (ash int (- posn))
2437            (ash ,(1- (ash 1 sb!vm:n-word-bits))
2438                 (- size ,sb!vm:n-word-bits))))
2439
2440 (deftransform %mask-field ((size posn int)
2441                            (fixnum fixnum integer)
2442                            (unsigned-byte #.sb!vm:n-word-bits))
2443   "convert to inline logical operations"
2444   `(logand int
2445            (ash (ash ,(1- (ash 1 sb!vm:n-word-bits))
2446                      (- size ,sb!vm:n-word-bits))
2447                 posn)))
2448
2449 ;;; Note: for %DPB and %DEPOSIT-FIELD, we can't use
2450 ;;;   (OR (SIGNED-BYTE N) (UNSIGNED-BYTE N))
2451 ;;; as the result type, as that would allow result types that cover
2452 ;;; the range -2^(n-1) .. 1-2^n, instead of allowing result types of
2453 ;;; (UNSIGNED-BYTE N) and result types of (SIGNED-BYTE N).
2454
2455 (deftransform %dpb ((new size posn int)
2456                     *
2457                     (unsigned-byte #.sb!vm:n-word-bits))
2458   "convert to inline logical operations"
2459   `(let ((mask (ldb (byte size 0) -1)))
2460      (logior (ash (logand new mask) posn)
2461              (logand int (lognot (ash mask posn))))))
2462
2463 (deftransform %dpb ((new size posn int)
2464                     *
2465                     (signed-byte #.sb!vm:n-word-bits))
2466   "convert to inline logical operations"
2467   `(let ((mask (ldb (byte size 0) -1)))
2468      (logior (ash (logand new mask) posn)
2469              (logand int (lognot (ash mask posn))))))
2470
2471 (deftransform %deposit-field ((new size posn int)
2472                               *
2473                               (unsigned-byte #.sb!vm:n-word-bits))
2474   "convert to inline logical operations"
2475   `(let ((mask (ash (ldb (byte size 0) -1) posn)))
2476      (logior (logand new mask)
2477              (logand int (lognot mask)))))
2478
2479 (deftransform %deposit-field ((new size posn int)
2480                               *
2481                               (signed-byte #.sb!vm:n-word-bits))
2482   "convert to inline logical operations"
2483   `(let ((mask (ash (ldb (byte size 0) -1) posn)))
2484      (logior (logand new mask)
2485              (logand int (lognot mask)))))
2486 \f
2487 ;;; miscellanous numeric transforms
2488
2489 ;;; If a constant appears as the first arg, swap the args.
2490 (deftransform commutative-arg-swap ((x y) * * :defun-only t :node node)
2491   (if (and (constant-continuation-p x)
2492            (not (constant-continuation-p y)))
2493       `(,(continuation-fun-name (basic-combination-fun node))
2494         y
2495         ,(continuation-value x))
2496       (give-up-ir1-transform)))
2497
2498 (dolist (x '(= char= + * logior logand logxor))
2499   (%deftransform x '(function * *) #'commutative-arg-swap
2500                  "place constant arg last"))
2501
2502 ;;; Handle the case of a constant BOOLE-CODE.
2503 (deftransform boole ((op x y) * *)
2504   "convert to inline logical operations"
2505   (unless (constant-continuation-p op)
2506     (give-up-ir1-transform "BOOLE code is not a constant."))
2507   (let ((control (continuation-value op)))
2508     (case control
2509       (#.boole-clr 0)
2510       (#.boole-set -1)
2511       (#.boole-1 'x)
2512       (#.boole-2 'y)
2513       (#.boole-c1 '(lognot x))
2514       (#.boole-c2 '(lognot y))
2515       (#.boole-and '(logand x y))
2516       (#.boole-ior '(logior x y))
2517       (#.boole-xor '(logxor x y))
2518       (#.boole-eqv '(logeqv x y))
2519       (#.boole-nand '(lognand x y))
2520       (#.boole-nor '(lognor x y))
2521       (#.boole-andc1 '(logandc1 x y))
2522       (#.boole-andc2 '(logandc2 x y))
2523       (#.boole-orc1 '(logorc1 x y))
2524       (#.boole-orc2 '(logorc2 x y))
2525       (t
2526        (abort-ir1-transform "~S is an illegal control arg to BOOLE."
2527                             control)))))
2528 \f
2529 ;;;; converting special case multiply/divide to shifts
2530
2531 ;;; If arg is a constant power of two, turn * into a shift.
2532 (deftransform * ((x y) (integer integer) *)
2533   "convert x*2^k to shift"
2534   (unless (constant-continuation-p y)
2535     (give-up-ir1-transform))
2536   (let* ((y (continuation-value y))
2537          (y-abs (abs y))
2538          (len (1- (integer-length y-abs))))
2539     (unless (= y-abs (ash 1 len))
2540       (give-up-ir1-transform))
2541     (if (minusp y)
2542         `(- (ash x ,len))
2543         `(ash x ,len))))
2544
2545 ;;; If both arguments and the result are (UNSIGNED-BYTE 32), try to
2546 ;;; come up with a ``better'' multiplication using multiplier
2547 ;;; recoding. There are two different ways the multiplier can be
2548 ;;; recoded. The more obvious is to shift X by the correct amount for
2549 ;;; each bit set in Y and to sum the results. But if there is a string
2550 ;;; of bits that are all set, you can add X shifted by one more then
2551 ;;; the bit position of the first set bit and subtract X shifted by
2552 ;;; the bit position of the last set bit. We can't use this second
2553 ;;; method when the high order bit is bit 31 because shifting by 32
2554 ;;; doesn't work too well.
2555 (deftransform * ((x y)
2556                  ((unsigned-byte 32) (unsigned-byte 32))
2557                  (unsigned-byte 32))
2558   "recode as shift and add"
2559   (unless (constant-continuation-p y)
2560     (give-up-ir1-transform))
2561   (let ((y (continuation-value y))
2562         (result nil)
2563         (first-one nil))
2564     (labels ((tub32 (x) `(truly-the (unsigned-byte 32) ,x))
2565              (add (next-factor)
2566                (setf result
2567                      (tub32
2568                       (if result
2569                           `(+ ,result ,(tub32 next-factor))
2570                           next-factor)))))
2571       (declare (inline add))
2572       (dotimes (bitpos 32)
2573         (if first-one
2574             (when (not (logbitp bitpos y))
2575               (add (if (= (1+ first-one) bitpos)
2576                        ;; There is only a single bit in the string.
2577                        `(ash x ,first-one)
2578                        ;; There are at least two.
2579                        `(- ,(tub32 `(ash x ,bitpos))
2580                            ,(tub32 `(ash x ,first-one)))))
2581               (setf first-one nil))
2582             (when (logbitp bitpos y)
2583               (setf first-one bitpos))))
2584       (when first-one
2585         (cond ((= first-one 31))
2586               ((= first-one 30)
2587                (add '(ash x 30)))
2588               (t
2589                (add `(- ,(tub32 '(ash x 31)) ,(tub32 `(ash x ,first-one))))))
2590         (add '(ash x 31))))
2591     (or result 0)))
2592
2593 ;;; If arg is a constant power of two, turn FLOOR into a shift and
2594 ;;; mask. If CEILING, add in (1- (ABS Y)), do FLOOR and correct a
2595 ;;; remainder.
2596 (flet ((frob (y ceil-p)
2597          (unless (constant-continuation-p y)
2598            (give-up-ir1-transform))
2599          (let* ((y (continuation-value y))
2600                 (y-abs (abs y))
2601                 (len (1- (integer-length y-abs))))
2602            (unless (= y-abs (ash 1 len))
2603              (give-up-ir1-transform))
2604            (let ((shift (- len))
2605                  (mask (1- y-abs))
2606                  (delta (if ceil-p (* (signum y) (1- y-abs)) 0)))
2607              `(let ((x (+ x ,delta)))
2608                 ,(if (minusp y)
2609                      `(values (ash (- x) ,shift)
2610                               (- (- (logand (- x) ,mask)) ,delta))
2611                      `(values (ash x ,shift)
2612                               (- (logand x ,mask) ,delta))))))))
2613   (deftransform floor ((x y) (integer integer) *)
2614     "convert division by 2^k to shift"
2615     (frob y nil))
2616   (deftransform ceiling ((x y) (integer integer) *)
2617     "convert division by 2^k to shift"
2618     (frob y t)))
2619
2620 ;;; Do the same for MOD.
2621 (deftransform mod ((x y) (integer integer) *)
2622   "convert remainder mod 2^k to LOGAND"
2623   (unless (constant-continuation-p y)
2624     (give-up-ir1-transform))
2625   (let* ((y (continuation-value y))
2626          (y-abs (abs y))
2627          (len (1- (integer-length y-abs))))
2628     (unless (= y-abs (ash 1 len))
2629       (give-up-ir1-transform))
2630     (let ((mask (1- y-abs)))
2631       (if (minusp y)
2632           `(- (logand (- x) ,mask))
2633           `(logand x ,mask)))))
2634
2635 ;;; If arg is a constant power of two, turn TRUNCATE into a shift and mask.
2636 (deftransform truncate ((x y) (integer integer))
2637   "convert division by 2^k to shift"
2638   (unless (constant-continuation-p y)
2639     (give-up-ir1-transform))
2640   (let* ((y (continuation-value y))
2641          (y-abs (abs y))
2642          (len (1- (integer-length y-abs))))
2643     (unless (= y-abs (ash 1 len))
2644       (give-up-ir1-transform))
2645     (let* ((shift (- len))
2646            (mask (1- y-abs)))
2647       `(if (minusp x)
2648            (values ,(if (minusp y)
2649                         `(ash (- x) ,shift)
2650                         `(- (ash (- x) ,shift)))
2651                    (- (logand (- x) ,mask)))
2652            (values ,(if (minusp y)
2653                         `(- (ash (- x) ,shift))
2654                         `(ash x ,shift))
2655                    (logand x ,mask))))))
2656
2657 ;;; And the same for REM.
2658 (deftransform rem ((x y) (integer integer) *)
2659   "convert remainder mod 2^k to LOGAND"
2660   (unless (constant-continuation-p y)
2661     (give-up-ir1-transform))
2662   (let* ((y (continuation-value y))
2663          (y-abs (abs y))
2664          (len (1- (integer-length y-abs))))
2665     (unless (= y-abs (ash 1 len))
2666       (give-up-ir1-transform))
2667     (let ((mask (1- y-abs)))
2668       `(if (minusp x)
2669            (- (logand (- x) ,mask))
2670            (logand x ,mask)))))
2671 \f
2672 ;;;; arithmetic and logical identity operation elimination
2673
2674 ;;; Flush calls to various arith functions that convert to the
2675 ;;; identity function or a constant.
2676 (macrolet ((def (name identity result)
2677              `(deftransform ,name ((x y) (* (constant-arg (member ,identity))) *)
2678                 "fold identity operations"
2679                 ',result)))
2680   (def ash 0 x)
2681   (def logand -1 x)
2682   (def logand 0 0)
2683   (def logior 0 x)
2684   (def logior -1 -1)
2685   (def logxor -1 (lognot x))
2686   (def logxor 0 x))
2687
2688 ;;; These are restricted to rationals, because (- 0 0.0) is 0.0, not -0.0, and
2689 ;;; (* 0 -4.0) is -0.0.
2690 (deftransform - ((x y) ((constant-arg (member 0)) rational) *)
2691   "convert (- 0 x) to negate"
2692   '(%negate y))
2693 (deftransform * ((x y) (rational (constant-arg (member 0))) *)
2694   "convert (* x 0) to 0"
2695   0)
2696
2697 ;;; Return T if in an arithmetic op including continuations X and Y,
2698 ;;; the result type is not affected by the type of X. That is, Y is at
2699 ;;; least as contagious as X.
2700 #+nil
2701 (defun not-more-contagious (x y)
2702   (declare (type continuation x y))
2703   (let ((x (continuation-type x))
2704         (y (continuation-type y)))
2705     (values (type= (numeric-contagion x y)
2706                    (numeric-contagion y y)))))
2707 ;;; Patched version by Raymond Toy. dtc: Should be safer although it
2708 ;;; XXX needs more work as valid transforms are missed; some cases are
2709 ;;; specific to particular transform functions so the use of this
2710 ;;; function may need a re-think.
2711 (defun not-more-contagious (x y)
2712   (declare (type continuation x y))
2713   (flet ((simple-numeric-type (num)
2714            (and (numeric-type-p num)
2715                 ;; Return non-NIL if NUM is integer, rational, or a float
2716                 ;; of some type (but not FLOAT)
2717                 (case (numeric-type-class num)
2718                   ((integer rational)
2719                    t)
2720                   (float
2721                    (numeric-type-format num))
2722                   (t
2723                    nil)))))
2724     (let ((x (continuation-type x))
2725           (y (continuation-type y)))
2726       (if (and (simple-numeric-type x)
2727                (simple-numeric-type y))
2728           (values (type= (numeric-contagion x y)
2729                          (numeric-contagion y y)))))))
2730
2731 ;;; Fold (+ x 0).
2732 ;;;
2733 ;;; If y is not constant, not zerop, or is contagious, or a positive
2734 ;;; float +0.0 then give up.
2735 (deftransform + ((x y) (t (constant-arg t)) *)
2736   "fold zero arg"
2737   (let ((val (continuation-value y)))
2738     (unless (and (zerop val)
2739                  (not (and (floatp val) (plusp (float-sign val))))
2740                  (not-more-contagious y x))
2741       (give-up-ir1-transform)))
2742   'x)
2743
2744 ;;; Fold (- x 0).
2745 ;;;
2746 ;;; If y is not constant, not zerop, or is contagious, or a negative
2747 ;;; float -0.0 then give up.
2748 (deftransform - ((x y) (t (constant-arg t)) *)
2749   "fold zero arg"
2750   (let ((val (continuation-value y)))
2751     (unless (and (zerop val)
2752                  (not (and (floatp val) (minusp (float-sign val))))
2753                  (not-more-contagious y x))
2754       (give-up-ir1-transform)))
2755   'x)
2756
2757 ;;; Fold (OP x +/-1)
2758 (macrolet ((def (name result minus-result)
2759              `(deftransform ,name ((x y) (t (constant-arg real)) *)
2760                 "fold identity operations"
2761                 (let ((val (continuation-value y)))
2762                   (unless (and (= (abs val) 1)
2763                                (not-more-contagious y x))
2764                     (give-up-ir1-transform))
2765                   (if (minusp val) ',minus-result ',result)))))
2766   (def * x (%negate x))
2767   (def / x (%negate x))
2768   (def expt x (/ 1 x)))
2769
2770 ;;; Fold (expt x n) into multiplications for small integral values of
2771 ;;; N; convert (expt x 1/2) to sqrt.
2772 (deftransform expt ((x y) (t (constant-arg real)) *)
2773   "recode as multiplication or sqrt"
2774   (let ((val (continuation-value y)))
2775     ;; If Y would cause the result to be promoted to the same type as
2776     ;; Y, we give up. If not, then the result will be the same type
2777     ;; as X, so we can replace the exponentiation with simple
2778     ;; multiplication and division for small integral powers.
2779     (unless (not-more-contagious y x)
2780       (give-up-ir1-transform))
2781     (cond ((zerop val) '(float 1 x))
2782           ((= val 2) '(* x x))
2783           ((= val -2) '(/ (* x x)))
2784           ((= val 3) '(* x x x))
2785           ((= val -3) '(/ (* x x x)))
2786           ((= val 1/2) '(sqrt x))
2787           ((= val -1/2) '(/ (sqrt x)))
2788           (t (give-up-ir1-transform)))))
2789
2790 ;;; KLUDGE: Shouldn't (/ 0.0 0.0), etc. cause exceptions in these
2791 ;;; transformations?
2792 ;;; Perhaps we should have to prove that the denominator is nonzero before
2793 ;;; doing them?  -- WHN 19990917
2794 (macrolet ((def (name)
2795              `(deftransform ,name ((x y) ((constant-arg (integer 0 0)) integer)
2796                                    *)
2797                 "fold zero arg"
2798                 0)))
2799   (def ash)
2800   (def /))
2801
2802 (macrolet ((def (name)
2803              `(deftransform ,name ((x y) ((constant-arg (integer 0 0)) integer)
2804                                    *)
2805                 "fold zero arg"
2806                 '(values 0 0))))
2807   (def truncate)
2808   (def round)
2809   (def floor)
2810   (def ceiling))
2811 \f
2812 ;;;; character operations
2813
2814 (deftransform char-equal ((a b) (base-char base-char))
2815   "open code"
2816   '(let* ((ac (char-code a))
2817           (bc (char-code b))
2818           (sum (logxor ac bc)))
2819      (or (zerop sum)
2820          (when (eql sum #x20)
2821            (let ((sum (+ ac bc)))
2822              (and (> sum 161) (< sum 213)))))))
2823
2824 (deftransform char-upcase ((x) (base-char))
2825   "open code"
2826   '(let ((n-code (char-code x)))
2827      (if (and (> n-code #o140)  ; Octal 141 is #\a.
2828               (< n-code #o173)) ; Octal 172 is #\z.
2829          (code-char (logxor #x20 n-code))
2830          x)))
2831
2832 (deftransform char-downcase ((x) (base-char))
2833   "open code"
2834   '(let ((n-code (char-code x)))
2835      (if (and (> n-code 64)     ; 65 is #\A.
2836               (< n-code 91))    ; 90 is #\Z.
2837          (code-char (logxor #x20 n-code))
2838          x)))
2839 \f
2840 ;;;; equality predicate transforms
2841
2842 ;;; Return true if X and Y are continuations whose only use is a
2843 ;;; reference to the same leaf, and the value of the leaf cannot
2844 ;;; change.
2845 (defun same-leaf-ref-p (x y)
2846   (declare (type continuation x y))
2847   (let ((x-use (continuation-use x))
2848         (y-use (continuation-use y)))
2849     (and (ref-p x-use)
2850          (ref-p y-use)
2851          (eq (ref-leaf x-use) (ref-leaf y-use))
2852          (constant-reference-p x-use))))
2853
2854 ;;; If X and Y are the same leaf, then the result is true. Otherwise,
2855 ;;; if there is no intersection between the types of the arguments,
2856 ;;; then the result is definitely false.
2857 (deftransform simple-equality-transform ((x y) * *
2858                                          :defun-only t)
2859   (cond ((same-leaf-ref-p x y)
2860          t)
2861         ((not (types-equal-or-intersect (continuation-type x)
2862                                         (continuation-type y)))
2863          nil)
2864         (t
2865          (give-up-ir1-transform))))
2866
2867 (macrolet ((def (x)
2868              `(%deftransform ',x '(function * *) #'simple-equality-transform)))
2869   (def eq)
2870   (def char=)
2871   (def equal))
2872
2873 ;;; This is similar to SIMPLE-EQUALITY-PREDICATE, except that we also
2874 ;;; try to convert to a type-specific predicate or EQ:
2875 ;;; -- If both args are characters, convert to CHAR=. This is better than
2876 ;;;    just converting to EQ, since CHAR= may have special compilation
2877 ;;;    strategies for non-standard representations, etc.
2878 ;;; -- If either arg is definitely not a number, then we can compare
2879 ;;;    with EQ.
2880 ;;; -- Otherwise, we try to put the arg we know more about second. If X
2881 ;;;    is constant then we put it second. If X is a subtype of Y, we put
2882 ;;;    it second. These rules make it easier for the back end to match
2883 ;;;    these interesting cases.
2884 ;;; -- If Y is a fixnum, then we quietly pass because the back end can
2885 ;;;    handle that case, otherwise give an efficiency note.
2886 (deftransform eql ((x y) * *)
2887   "convert to simpler equality predicate"
2888   (let ((x-type (continuation-type x))
2889         (y-type (continuation-type y))
2890         (char-type (specifier-type 'character))
2891         (number-type (specifier-type 'number)))
2892     (cond ((same-leaf-ref-p x y)
2893            t)
2894           ((not (types-equal-or-intersect x-type y-type))
2895            nil)
2896           ((and (csubtypep x-type char-type)
2897                 (csubtypep y-type char-type))
2898            '(char= x y))
2899           ((or (not (types-equal-or-intersect x-type number-type))
2900                (not (types-equal-or-intersect y-type number-type)))
2901            '(eq x y))
2902           ((and (not (constant-continuation-p y))
2903                 (or (constant-continuation-p x)
2904                     (and (csubtypep x-type y-type)
2905                          (not (csubtypep y-type x-type)))))
2906            '(eql y x))
2907           (t
2908            (give-up-ir1-transform)))))
2909
2910 ;;; Convert to EQL if both args are rational and complexp is specified
2911 ;;; and the same for both.
2912 (deftransform = ((x y) * *)
2913   "open code"
2914   (let ((x-type (continuation-type x))
2915         (y-type (continuation-type y)))
2916     (if (and (csubtypep x-type (specifier-type 'number))
2917              (csubtypep y-type (specifier-type 'number)))
2918         (cond ((or (and (csubtypep x-type (specifier-type 'float))
2919                         (csubtypep y-type (specifier-type 'float)))
2920                    (and (csubtypep x-type (specifier-type '(complex float)))
2921                         (csubtypep y-type (specifier-type '(complex float)))))
2922                ;; They are both floats. Leave as = so that -0.0 is
2923                ;; handled correctly.
2924                (give-up-ir1-transform))
2925               ((or (and (csubtypep x-type (specifier-type 'rational))
2926                         (csubtypep y-type (specifier-type 'rational)))
2927                    (and (csubtypep x-type
2928                                    (specifier-type '(complex rational)))
2929                         (csubtypep y-type
2930                                    (specifier-type '(complex rational)))))
2931                ;; They are both rationals and complexp is the same.
2932                ;; Convert to EQL.
2933                '(eql x y))
2934               (t
2935                (give-up-ir1-transform
2936                 "The operands might not be the same type.")))
2937         (give-up-ir1-transform
2938          "The operands might not be the same type."))))
2939
2940 ;;; If CONT's type is a numeric type, then return the type, otherwise
2941 ;;; GIVE-UP-IR1-TRANSFORM.
2942 (defun numeric-type-or-lose (cont)
2943   (declare (type continuation cont))
2944   (let ((res (continuation-type cont)))
2945     (unless (numeric-type-p res) (give-up-ir1-transform))
2946     res))
2947
2948 ;;; See whether we can statically determine (< X Y) using type
2949 ;;; information. If X's high bound is < Y's low, then X < Y.
2950 ;;; Similarly, if X's low is >= to Y's high, the X >= Y (so return
2951 ;;; NIL). If not, at least make sure any constant arg is second.
2952 ;;;
2953 ;;; FIXME: Why should constant argument be second? It would be nice to
2954 ;;; find out and explain.
2955 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2956 (defun ir1-transform-< (x y first second inverse)
2957   (if (same-leaf-ref-p x y)
2958       nil
2959       (let* ((x-type (numeric-type-or-lose x))
2960              (x-lo (numeric-type-low x-type))
2961              (x-hi (numeric-type-high x-type))
2962              (y-type (numeric-type-or-lose y))
2963              (y-lo (numeric-type-low y-type))
2964              (y-hi (numeric-type-high y-type)))
2965         (cond ((and x-hi y-lo (< x-hi y-lo))
2966                t)
2967               ((and y-hi x-lo (>= x-lo y-hi))
2968                nil)
2969               ((and (constant-continuation-p first)
2970                     (not (constant-continuation-p second)))
2971                `(,inverse y x))
2972               (t
2973                (give-up-ir1-transform))))))
2974 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2975 (defun ir1-transform-< (x y first second inverse)
2976   (if (same-leaf-ref-p x y)
2977       nil
2978       (let ((xi (numeric-type->interval (numeric-type-or-lose x)))
2979             (yi (numeric-type->interval (numeric-type-or-lose y))))
2980         (cond ((interval-< xi yi)
2981                t)
2982               ((interval->= xi yi)
2983                nil)
2984               ((and (constant-continuation-p first)
2985                     (not (constant-continuation-p second)))
2986                `(,inverse y x))
2987               (t
2988                (give-up-ir1-transform))))))
2989
2990 (deftransform < ((x y) (integer integer) *)
2991   (ir1-transform-< x y x y '>))
2992
2993 (deftransform > ((x y) (integer integer) *)
2994   (ir1-transform-< y x x y '<))
2995
2996 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2997 (deftransform < ((x y) (float float) *)
2998   (ir1-transform-< x y x y '>))
2999
3000 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
3001 (deftransform > ((x y) (float float) *)
3002   (ir1-transform-< y x x y '<))
3003 \f
3004 ;;;; converting N-arg comparisons
3005 ;;;;
3006 ;;;; We convert calls to N-arg comparison functions such as < into
3007 ;;;; two-arg calls. This transformation is enabled for all such
3008 ;;;; comparisons in this file. If any of these predicates are not
3009 ;;;; open-coded, then the transformation should be removed at some
3010 ;;;; point to avoid pessimization.
3011
3012 ;;; This function is used for source transformation of N-arg
3013 ;;; comparison functions other than inequality. We deal both with
3014 ;;; converting to two-arg calls and inverting the sense of the test,
3015 ;;; if necessary. If the call has two args, then we pass or return a
3016 ;;; negated test as appropriate. If it is a degenerate one-arg call,
3017 ;;; then we transform to code that returns true. Otherwise, we bind
3018 ;;; all the arguments and expand into a bunch of IFs.
3019 (declaim (ftype (function (symbol list boolean) *) multi-compare))
3020 (defun multi-compare (predicate args not-p)
3021   (let ((nargs (length args)))
3022     (cond ((< nargs 1) (values nil t))
3023           ((= nargs 1) `(progn ,@args t))
3024           ((= nargs 2)
3025            (if not-p
3026                `(if (,predicate ,(first args) ,(second args)) nil t)
3027                (values nil t)))
3028           (t
3029            (do* ((i (1- nargs) (1- i))
3030                  (last nil current)
3031                  (current (gensym) (gensym))
3032                  (vars (list current) (cons current vars))
3033                  (result t (if not-p
3034                                `(if (,predicate ,current ,last)
3035                                     nil ,result)
3036                                `(if (,predicate ,current ,last)
3037                                     ,result nil))))
3038                ((zerop i)
3039                 `((lambda ,vars ,result) . ,args)))))))
3040
3041 (define-source-transform = (&rest args) (multi-compare '= args nil))
3042 (define-source-transform < (&rest args) (multi-compare '< args nil))
3043 (define-source-transform > (&rest args) (multi-compare '> args nil))
3044 (define-source-transform <= (&rest args) (multi-compare '> args t))
3045 (define-source-transform >= (&rest args) (multi-compare '< args t))
3046
3047 (define-source-transform char= (&rest args) (multi-compare 'char= args nil))
3048 (define-source-transform char< (&rest args) (multi-compare 'char< args nil))
3049 (define-source-transform char> (&rest args) (multi-compare 'char> args nil))
3050 (define-source-transform char<= (&rest args) (multi-compare 'char> args t))
3051 (define-source-transform char>= (&rest args) (multi-compare 'char< args t))
3052
3053 (define-source-transform char-equal (&rest args)
3054   (multi-compare 'char-equal args nil))
3055 (define-source-transform char-lessp (&rest args)
3056   (multi-compare 'char-lessp args nil))
3057 (define-source-transform char-greaterp (&rest args)
3058   (multi-compare 'char-greaterp args nil))
3059 (define-source-transform char-not-greaterp (&rest args)
3060   (multi-compare 'char-greaterp args t))
3061 (define-source-transform char-not-lessp (&rest args)
3062   (multi-compare 'char-lessp args t))
3063
3064 ;;; This function does source transformation of N-arg inequality
3065 ;;; functions such as /=. This is similar to MULTI-COMPARE in the <3
3066 ;;; arg cases. If there are more than two args, then we expand into
3067 ;;; the appropriate n^2 comparisons only when speed is important.
3068 (declaim (ftype (function (symbol list) *) multi-not-equal))
3069 (defun multi-not-equal (predicate args)
3070   (let ((nargs (length args)))
3071     (cond ((< nargs 1) (values nil t))
3072           ((= nargs 1) `(progn ,@args t))
3073           ((= nargs 2)
3074            `(if (,predicate ,(first args) ,(second args)) nil t))
3075           ((not (policy *lexenv*
3076                         (and (>= speed space)
3077                              (>= speed compilation-speed))))
3078            (values nil t))
3079           (t
3080            (let ((vars (make-gensym-list nargs)))
3081              (do ((var vars next)
3082                   (next (cdr vars) (cdr next))
3083                   (result t))
3084                  ((null next)
3085                   `((lambda ,vars ,result) . ,args))
3086                (let ((v1 (first var)))
3087                  (dolist (v2 next)
3088                    (setq result `(if (,predicate ,v1 ,v2) nil ,result))))))))))
3089
3090 (define-source-transform /= (&rest args) (multi-not-equal '= args))
3091 (define-source-transform char/= (&rest args) (multi-not-equal 'char= args))
3092 (define-source-transform char-not-equal (&rest args)
3093   (multi-not-equal 'char-equal args))
3094
3095 ;;; FIXME: can go away once bug 194 is fixed and we can use (THE REAL X)
3096 ;;; as God intended
3097 (defun error-not-a-real (x)
3098   (error 'simple-type-error
3099          :datum x
3100          :expected-type 'real
3101          :format-control "not a REAL: ~S"
3102          :format-arguments (list x)))
3103
3104 ;;; Expand MAX and MIN into the obvious comparisons.
3105 (define-source-transform max (arg0 &rest rest)
3106   (once-only ((arg0 arg0))
3107     (if (null rest)
3108         `(values (the real ,arg0))
3109         `(let ((maxrest (max ,@rest)))
3110           (if (> ,arg0 maxrest) ,arg0 maxrest)))))
3111 (define-source-transform min (arg0 &rest rest)
3112   (once-only ((arg0 arg0))
3113     (if (null rest)
3114         `(values (the real ,arg0))
3115         `(let ((minrest (min ,@rest)))
3116           (if (< ,arg0 minrest) ,arg0 minrest)))))
3117 \f
3118 ;;;; converting N-arg arithmetic functions
3119 ;;;;
3120 ;;;; N-arg arithmetic and logic functions are associated into two-arg
3121 ;;;; versions, and degenerate cases are flushed.
3122
3123 ;;; Left-associate FIRST-ARG and MORE-ARGS using FUNCTION.
3124 (declaim (ftype (function (symbol t list) list) associate-args))
3125 (defun associate-args (function first-arg more-args)
3126   (let ((next (rest more-args))
3127         (arg (first more-args)))
3128     (if (null next)
3129         `(,function ,first-arg ,arg)
3130         (associate-args function `(,function ,first-arg ,arg) next))))
3131
3132 ;;; Do source transformations for transitive functions such as +.
3133 ;;; One-arg cases are replaced with the arg and zero arg cases with
3134 ;;; the identity.  ONE-ARG-RESULT-TYPE is, if non-NIL, the type to
3135 ;;; ensure (with THE) that the argument in one-argument calls is.
3136 (defun source-transform-transitive (fun args identity
3137                                     &optional one-arg-result-type)
3138   (declare (symbol fun leaf-fun) (list args))
3139   (case (length args)
3140     (0 identity)
3141     (1 (if one-arg-result-type
3142            `(values (the ,one-arg-result-type ,(first args)))
3143            `(values ,(first args))))
3144     (2 (values nil t))
3145     (t
3146      (associate-args fun (first args) (rest args)))))
3147
3148 (define-source-transform + (&rest args)
3149   (source-transform-transitive '+ args 0 'number))
3150 (define-source-transform * (&rest args)
3151   (source-transform-transitive '* args 1 'number))
3152 (define-source-transform logior (&rest args)
3153   (source-transform-transitive 'logior args 0 'integer))
3154 (define-source-transform logxor (&rest args)
3155   (source-transform-transitive 'logxor args 0 'integer))
3156 (define-source-transform logand (&rest args)
3157   (source-transform-transitive 'logand args -1 'integer))
3158
3159 (define-source-transform logeqv (&rest args)
3160   (if (evenp (length args))
3161       `(lognot (logxor ,@args))
3162       `(logxor ,@args)))
3163
3164 ;;; Note: we can't use SOURCE-TRANSFORM-TRANSITIVE for GCD and LCM
3165 ;;; because when they are given one argument, they return its absolute
3166 ;;; value.
3167
3168 (define-source-transform gcd (&rest args)
3169   (case (length args)
3170     (0 0)
3171     (1 `(abs (the integer ,(first args))))
3172     (2 (values nil t))
3173     (t (associate-args 'gcd (first args) (rest args)))))
3174
3175 (define-source-transform lcm (&rest args)
3176   (case (length args)
3177     (0 1)
3178     (1 `(abs (the integer ,(first args))))
3179     (2 (values nil t))
3180     (t (associate-args 'lcm (first args) (rest args)))))
3181
3182 ;;; Do source transformations for intransitive n-arg functions such as
3183 ;;; /. With one arg, we form the inverse. With two args we pass.
3184 ;;; Otherwise we associate into two-arg calls.
3185 (declaim (ftype (function (symbol list t)
3186                           (values list &optional (member nil t)))
3187                 source-transform-intransitive))
3188 (defun source-transform-intransitive (function args inverse)
3189   (case (length args)
3190     ((0 2) (values nil t))
3191     (1 `(,@inverse ,(first args)))
3192     (t (associate-args function (first args) (rest args)))))
3193
3194 (define-source-transform - (&rest args)
3195   (source-transform-intransitive '- args '(%negate)))
3196 (define-source-transform / (&rest args)
3197   (source-transform-intransitive '/ args '(/ 1)))
3198 \f
3199 ;;;; transforming APPLY
3200
3201 ;;; We convert APPLY into MULTIPLE-VALUE-CALL so that the compiler
3202 ;;; only needs to understand one kind of variable-argument call. It is
3203 ;;; more efficient to convert APPLY to MV-CALL than MV-CALL to APPLY.
3204 (define-source-transform apply (fun arg &rest more-args)
3205   (let ((args (cons arg more-args)))
3206     `(multiple-value-call ,fun
3207        ,@(mapcar (lambda (x)
3208                    `(values ,x))
3209                  (butlast args))
3210        (values-list ,(car (last args))))))
3211 \f
3212 ;;;; transforming FORMAT
3213 ;;;;
3214 ;;;; If the control string is a compile-time constant, then replace it
3215 ;;;; with a use of the FORMATTER macro so that the control string is
3216 ;;;; ``compiled.'' Furthermore, if the destination is either a stream
3217 ;;;; or T and the control string is a function (i.e. FORMATTER), then
3218 ;;;; convert the call to FORMAT to just a FUNCALL of that function.
3219
3220 (deftransform format ((dest control &rest args) (t simple-string &rest t) *
3221                       :policy (> speed space))
3222   (unless (constant-continuation-p control)
3223     (give-up-ir1-transform "The control string is not a constant."))
3224   (let ((arg-names (make-gensym-list (length args))))
3225     `(lambda (dest control ,@arg-names)
3226        (declare (ignore control))
3227        (format dest (formatter ,(continuation-value control)) ,@arg-names))))
3228
3229 (deftransform format ((stream control &rest args) (stream function &rest t) *
3230                       :policy (> speed space))
3231   (let ((arg-names (make-gensym-list (length args))))
3232     `(lambda (stream control ,@arg-names)
3233        (funcall control stream ,@arg-names)
3234        nil)))
3235
3236 (deftransform format ((tee control &rest args) ((member t) function &rest t) *
3237                       :policy (> speed space))
3238   (let ((arg-names (make-gensym-list (length args))))
3239     `(lambda (tee control ,@arg-names)
3240        (declare (ignore tee))
3241        (funcall control *standard-output* ,@arg-names)
3242        nil)))
3243
3244 (defoptimizer (coerce derive-type) ((value type))
3245   (cond
3246     ((constant-continuation-p type)
3247      ;; This branch is essentially (RESULT-TYPE-SPECIFIER-NTH-ARG 2),
3248      ;; but dealing with the niggle that complex canonicalization gets
3249      ;; in the way: (COERCE 1 'COMPLEX) returns 1, which is not of
3250      ;; type COMPLEX.
3251      (let* ((specifier (continuation-value type))
3252             (result-typeoid (careful-specifier-type specifier)))
3253        (cond
3254          ((null result-typeoid) nil)
3255          ((csubtypep result-typeoid (specifier-type 'number))
3256           ;; the difficult case: we have to cope with ANSI 12.1.5.3
3257           ;; Rule of Canonical Representation for Complex Rationals,
3258           ;; which is a truly nasty delivery to field.
3259           (cond
3260             ((csubtypep result-typeoid (specifier-type 'real))
3261              ;; cleverness required here: it would be nice to deduce
3262              ;; that something of type (INTEGER 2 3) coerced to type
3263              ;; DOUBLE-FLOAT should return (DOUBLE-FLOAT 2.0d0 3.0d0).
3264              ;; FLOAT gets its own clause because it's implemented as
3265              ;; a UNION-TYPE, so we don't catch it in the NUMERIC-TYPE
3266              ;; logic below.
3267              result-typeoid)
3268             ((and (numeric-type-p result-typeoid)
3269                   (eq (numeric-type-complexp result-typeoid) :real))
3270              ;; FIXME: is this clause (a) necessary or (b) useful?
3271              result-typeoid)
3272             ((or (csubtypep result-typeoid
3273                             (specifier-type '(complex single-float)))
3274                  (csubtypep result-typeoid
3275                             (specifier-type '(complex double-float)))
3276                  #!+long-float
3277                  (csubtypep result-typeoid
3278                             (specifier-type '(complex long-float))))
3279              ;; float complex types are never canonicalized.
3280              result-typeoid)
3281             (t
3282              ;; if it's not a REAL, or a COMPLEX FLOAToid, it's
3283              ;; probably just a COMPLEX or equivalent.  So, in that
3284              ;; case, we will return a complex or an object of the
3285              ;; provided type if it's rational:
3286              (type-union result-typeoid
3287                          (type-intersection (continuation-type value)
3288                                             (specifier-type 'rational))))))
3289          (t result-typeoid))))
3290     (t
3291      ;; OK, the result-type argument isn't constant.  However, there
3292      ;; are common uses where we can still do better than just
3293      ;; *UNIVERSAL-TYPE*: e.g. (COERCE X (ARRAY-ELEMENT-TYPE Y)),
3294      ;; where Y is of a known type.  See messages on cmucl-imp
3295      ;; 2001-02-14 and sbcl-devel 2002-12-12.  We only worry here
3296      ;; about types that can be returned by (ARRAY-ELEMENT-TYPE Y), on
3297      ;; the basis that it's unlikely that other uses are both
3298      ;; time-critical and get to this branch of the COND (non-constant
3299      ;; second argument to COERCE).  -- CSR, 2002-12-16
3300      (let ((value-type (continuation-type value))
3301            (type-type (continuation-type type)))
3302        (labels
3303            ((good-cons-type-p (cons-type)
3304               ;; Make sure the cons-type we're looking at is something
3305               ;; we're prepared to handle which is basically something
3306               ;; that array-element-type can return.
3307               (or (and (member-type-p cons-type)
3308                        (null (rest (member-type-members cons-type)))
3309                        (null (first (member-type-members cons-type))))
3310                   (let ((car-type (cons-type-car-type cons-type)))
3311                     (and (member-type-p car-type)
3312                          (null (rest (member-type-members car-type)))
3313                          (or (symbolp (first (member-type-members car-type)))
3314                              (numberp (first (member-type-members car-type)))
3315                              (and (listp (first (member-type-members
3316                                                  car-type)))
3317                                   (numberp (first (first (member-type-members
3318                                                           car-type))))))
3319                          (good-cons-type-p (cons-type-cdr-type cons-type))))))
3320             (unconsify-type (good-cons-type)
3321               ;; Convert the "printed" respresentation of a cons
3322               ;; specifier into a type specifier.  That is, the
3323               ;; specifier (CONS (EQL SIGNED-BYTE) (CONS (EQL 16)
3324               ;; NULL)) is converted to (SIGNED-BYTE 16).
3325               (cond ((or (null good-cons-type)
3326                          (eq good-cons-type 'null))
3327                      nil)
3328                     ((and (eq (first good-cons-type) 'cons)
3329                           (eq (first (second good-cons-type)) 'member))
3330                      `(,(second (second good-cons-type))
3331                        ,@(unconsify-type (caddr good-cons-type))))))
3332             (coerceable-p (c-type)
3333               ;; Can the value be coerced to the given type?  Coerce is
3334               ;; complicated, so we don't handle every possible case
3335               ;; here---just the most common and easiest cases:
3336               ;;
3337               ;; * Any REAL can be coerced to a FLOAT type.
3338               ;; * Any NUMBER can be coerced to a (COMPLEX
3339               ;;   SINGLE/DOUBLE-FLOAT).
3340               ;;
3341               ;; FIXME I: we should also be able to deal with characters
3342               ;; here.
3343               ;;
3344               ;; FIXME II: I'm not sure that anything is necessary
3345               ;; here, at least while COMPLEX is not a specialized
3346               ;; array element type in the system.  Reasoning: if
3347               ;; something cannot be coerced to the requested type, an
3348               ;; error will be raised (and so any downstream compiled
3349               ;; code on the assumption of the returned type is
3350               ;; unreachable).  If something can, then it will be of
3351               ;; the requested type, because (by assumption) COMPLEX
3352               ;; (and other difficult types like (COMPLEX INTEGER)
3353               ;; aren't specialized types.
3354               (let ((coerced-type c-type))
3355                 (or (and (subtypep coerced-type 'float)
3356                          (csubtypep value-type (specifier-type 'real)))
3357                     (and (subtypep coerced-type
3358                                    '(or (complex single-float)
3359                                         (complex double-float)))
3360                          (csubtypep value-type (specifier-type 'number))))))
3361             (process-types (type)
3362               ;; FIXME: This needs some work because we should be able
3363               ;; to derive the resulting type better than just the
3364               ;; type arg of coerce.  That is, if X is (INTEGER 10
3365               ;; 20), then (COERCE X 'DOUBLE-FLOAT) should say
3366               ;; (DOUBLE-FLOAT 10d0 20d0) instead of just
3367               ;; double-float.
3368               (cond ((member-type-p type)
3369                      (let ((members (member-type-members type)))
3370                        (if (every #'coerceable-p members)
3371                            (specifier-type `(or ,@members))
3372                            *universal-type*)))
3373                     ((and (cons-type-p type)
3374                           (good-cons-type-p type))
3375                      (let ((c-type (unconsify-type (type-specifier type))))
3376                        (if (coerceable-p c-type)
3377                            (specifier-type c-type)
3378                            *universal-type*)))
3379                     (t
3380                      *universal-type*))))
3381          (cond ((union-type-p type-type)
3382                 (apply #'type-union (mapcar #'process-types
3383                                             (union-type-types type-type))))
3384                ((or (member-type-p type-type)
3385                     (cons-type-p type-type))
3386                 (process-types type-type))
3387                (t
3388                 *universal-type*)))))))
3389
3390 (defoptimizer (compile derive-type) ((nameoid function))
3391   (when (csubtypep (continuation-type nameoid)
3392                    (specifier-type 'null))
3393     (values-specifier-type '(values function boolean boolean))))
3394
3395 ;;; FIXME: Maybe also STREAM-ELEMENT-TYPE should be given some loving
3396 ;;; treatment along these lines? (See discussion in COERCE DERIVE-TYPE
3397 ;;; optimizer, above).
3398 (defoptimizer (array-element-type derive-type) ((array))
3399   (let ((array-type (continuation-type array)))
3400     (labels ((consify (list)
3401               (if (endp list)
3402                   '(eql nil)
3403                   `(cons (eql ,(car list)) ,(consify (rest list)))))
3404             (get-element-type (a)
3405               (let ((element-type
3406                      (type-specifier (array-type-specialized-element-type a))))
3407                 (cond ((eq element-type '*)
3408                        (specifier-type 'type-specifier))
3409                       ((symbolp element-type)
3410                        (make-member-type :members (list element-type)))
3411                       ((consp element-type)
3412                        (specifier-type (consify element-type)))
3413                       (t
3414                        (error "can't understand type ~S~%" element-type))))))
3415       (cond ((array-type-p array-type)
3416              (get-element-type array-type))
3417             ((union-type-p array-type)             
3418              (apply #'type-union
3419                     (mapcar #'get-element-type (union-type-types array-type))))
3420             (t
3421              *universal-type*)))))
3422
3423 (define-source-transform sb!impl::sort-vector (vector start end predicate key)
3424   `(macrolet ((%index (x) `(truly-the index ,x))
3425               (%parent (i) `(ash ,i -1))
3426               (%left (i) `(%index (ash ,i 1)))
3427               (%right (i) `(%index (1+ (ash ,i 1))))
3428               (%heapify (i)
3429                `(do* ((i ,i)
3430                       (left (%left i) (%left i)))
3431                  ((> left current-heap-size))
3432                  (declare (type index i left))
3433                  (let* ((i-elt (%elt i))
3434                         (i-key (funcall keyfun i-elt))
3435                         (left-elt (%elt left))
3436                         (left-key (funcall keyfun left-elt)))
3437                    (multiple-value-bind (large large-elt large-key)
3438                        (if (funcall ,',predicate i-key left-key)
3439                            (values left left-elt left-key)
3440                            (values i i-elt i-key))
3441                      (let ((right (%right i)))
3442                        (multiple-value-bind (largest largest-elt)
3443                            (if (> right current-heap-size)
3444                                (values large large-elt)
3445                                (let* ((right-elt (%elt right))
3446                                       (right-key (funcall keyfun right-elt)))
3447                                  (if (funcall ,',predicate large-key right-key)
3448                                      (values right right-elt)
3449                                      (values large large-elt))))
3450                          (cond ((= largest i)
3451                                 (return))
3452                                (t
3453                                 (setf (%elt i) largest-elt
3454                                       (%elt largest) i-elt
3455                                       i largest)))))))))
3456               (%sort-vector (keyfun &optional (vtype 'vector))
3457                `(macrolet (;; KLUDGE: In SBCL ca. 0.6.10, I had trouble getting
3458                            ;; type inference to propagate all the way
3459                            ;; through this tangled mess of
3460                            ;; inlining. The TRULY-THE here works
3461                            ;; around that. -- WHN
3462                            (%elt (i)
3463                             `(aref (truly-the ,',vtype ,',',vector)
3464                               (%index (+ (%index ,i) start-1)))))
3465                  (let ((start-1 (1- ,',start)) ; Heaps prefer 1-based addressing.
3466                        (current-heap-size (- ,',end ,',start))
3467                        (keyfun ,keyfun))
3468                    (declare (type (integer -1 #.(1- most-positive-fixnum))
3469                                   start-1))
3470                    (declare (type index current-heap-size))
3471                    (declare (type function keyfun))
3472                    (loop for i of-type index
3473                          from (ash current-heap-size -1) downto 1 do
3474                          (%heapify i))
3475                    (loop 
3476                     (when (< current-heap-size 2)
3477                       (return))
3478                     (rotatef (%elt 1) (%elt current-heap-size))
3479                     (decf current-heap-size)
3480                     (%heapify 1))))))
3481     (if (typep ,vector 'simple-vector)
3482         ;; (VECTOR T) is worth optimizing for, and SIMPLE-VECTOR is
3483         ;; what we get from (VECTOR T) inside WITH-ARRAY-DATA.
3484         (if (null ,key)
3485             ;; Special-casing the KEY=NIL case lets us avoid some
3486             ;; function calls.
3487             (%sort-vector #'identity simple-vector)
3488             (%sort-vector ,key simple-vector))
3489         ;; It's hard to anticipate many speed-critical applications for
3490         ;; sorting vector types other than (VECTOR T), so we just lump
3491         ;; them all together in one slow dynamically typed mess.
3492         (locally
3493           (declare (optimize (speed 2) (space 2) (inhibit-warnings 3)))
3494           (%sort-vector (or ,key #'identity))))))
3495 \f
3496 ;;;; debuggers' little helpers
3497
3498 ;;; for debugging when transforms are behaving mysteriously,
3499 ;;; e.g. when debugging a problem with an ASH transform
3500 ;;;   (defun foo (&optional s)
3501 ;;;     (sb-c::/report-continuation s "S outside WHEN")
3502 ;;;     (when (and (integerp s) (> s 3))
3503 ;;;       (sb-c::/report-continuation s "S inside WHEN")
3504 ;;;       (let ((bound (ash 1 (1- s))))
3505 ;;;         (sb-c::/report-continuation bound "BOUND")
3506 ;;;         (let ((x (- bound))
3507 ;;;               (y (1- bound)))
3508 ;;;           (sb-c::/report-continuation x "X")
3509 ;;;           (sb-c::/report-continuation x "Y"))
3510 ;;;         `(integer ,(- bound) ,(1- bound)))))
3511 ;;; (The DEFTRANSFORM doesn't do anything but report at compile time,
3512 ;;; and the function doesn't do anything at all.)
3513 #!+sb-show
3514 (progn
3515   (defknown /report-continuation (t t) null)
3516   (deftransform /report-continuation ((x message) (t t))
3517     (format t "~%/in /REPORT-CONTINUATION~%")
3518     (format t "/(CONTINUATION-TYPE X)=~S~%" (continuation-type x))
3519     (when (constant-continuation-p x)
3520       (format t "/(CONTINUATION-VALUE X)=~S~%" (continuation-value x)))
3521     (format t "/MESSAGE=~S~%" (continuation-value message))
3522     (give-up-ir1-transform "not a real transform"))
3523   (defun /report-continuation (&rest rest)
3524     (declare (ignore rest))))