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