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