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