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