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