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