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