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