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