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