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