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