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