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