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