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