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