1.0.30.5: optimize some floating point operations
[sbcl.git] / src / compiler / float-tran.lisp
1 ;;;; This file contains floating-point-specific transforms, and may be
2 ;;;; somewhat implementation-dependent in its assumptions of what the
3 ;;;; formats are.
4
5 ;;;; This software is part of the SBCL system. See the README file for
6 ;;;; more information.
7 ;;;;
8 ;;;; This software is derived from the CMU CL system, which was
9 ;;;; written at Carnegie Mellon University and released into the
10 ;;;; public domain. The software is in the public domain and is
11 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
12 ;;;; files for more information.
13
14 (in-package "SB!C")
15 \f
16 ;;;; coercions
17
18 (defknown %single-float (real) single-float (movable foldable))
19 (defknown %double-float (real) double-float (movable foldable))
20
21 (deftransform float ((n f) (* single-float) *)
22   '(%single-float n))
23
24 (deftransform float ((n f) (* double-float) *)
25   '(%double-float n))
26
27 (deftransform float ((n) *)
28   '(if (floatp n)
29        n
30        (%single-float n)))
31
32 (deftransform %single-float ((n) (single-float) *)
33   'n)
34
35 (deftransform %double-float ((n) (double-float) *)
36   'n)
37
38 ;;; RANDOM
39 (macrolet ((frob (fun type)
40              `(deftransform random ((num &optional state)
41                                     (,type &optional *) *)
42                 "Use inline float operations."
43                 '(,fun num (or state *random-state*)))))
44   (frob %random-single-float single-float)
45   (frob %random-double-float double-float))
46
47 ;;; Mersenne Twister RNG
48 ;;;
49 ;;; FIXME: It's unpleasant to have RANDOM functionality scattered
50 ;;; through the code this way. It would be nice to move this into the
51 ;;; same file as the other RANDOM definitions.
52 (deftransform random ((num &optional state)
53                       ((integer 1 #.(expt 2 sb!vm::n-word-bits)) &optional *))
54   ;; FIXME: I almost conditionalized this as #!+sb-doc. Find some way
55   ;; of automatically finding #!+sb-doc in proximity to DEFTRANSFORM
56   ;; to let me scan for places that I made this mistake and didn't
57   ;; catch myself.
58   "use inline (UNSIGNED-BYTE 32) operations"
59   (let ((type (lvar-type num))
60         (limit (expt 2 sb!vm::n-word-bits))
61         (random-chunk (ecase sb!vm::n-word-bits
62                         (32 'random-chunk)
63                         (64 'sb!kernel::big-random-chunk))))
64     (if (numeric-type-p type)
65         (let ((num-high (numeric-type-high (lvar-type num))))
66           (aver num-high)
67           (cond ((constant-lvar-p num)
68                  ;; Check the worst case sum absolute error for the
69                  ;; random number expectations.
70                  (let ((rem (rem limit num-high)))
71                    (unless (< (/ (* 2 rem (- num-high rem))
72                                  num-high limit)
73                               (expt 2 (- sb!kernel::random-integer-extra-bits)))
74                      (give-up-ir1-transform
75                       "The random number expectations are inaccurate."))
76                    (if (= num-high limit)
77                        `(,random-chunk (or state *random-state*))
78                        #!-(or x86 x86-64)
79                        `(rem (,random-chunk (or state *random-state*)) num)
80                        #!+(or x86 x86-64)
81                        ;; Use multiplication, which is faster.
82                        `(values (sb!bignum::%multiply
83                                  (,random-chunk (or state *random-state*))
84                                  num)))))
85                 ((> num-high random-fixnum-max)
86                  (give-up-ir1-transform
87                   "The range is too large to ensure an accurate result."))
88                 #!+(or x86 x86-64)
89                 ((< num-high limit)
90                  `(values (sb!bignum::%multiply
91                            (,random-chunk (or state *random-state*))
92                            num)))
93                 (t
94                  `(rem (,random-chunk (or state *random-state*)) num))))
95         ;; KLUDGE: a relatively conservative treatment, but better
96         ;; than a bug (reported by PFD sbcl-devel towards the end of
97         ;; 2004-11.
98         '(rem (random-chunk (or state *random-state*)) num))))
99 \f
100 ;;;; float accessors
101
102 (defknown make-single-float ((signed-byte 32)) single-float
103   (movable foldable flushable))
104
105 (defknown make-double-float ((signed-byte 32) (unsigned-byte 32)) double-float
106   (movable foldable flushable))
107
108 (defknown single-float-bits (single-float) (signed-byte 32)
109   (movable foldable flushable))
110
111 (defknown double-float-high-bits (double-float) (signed-byte 32)
112   (movable foldable flushable))
113
114 (defknown double-float-low-bits (double-float) (unsigned-byte 32)
115   (movable foldable flushable))
116
117 (deftransform float-sign ((float &optional float2)
118                           (single-float &optional single-float) *)
119   (if float2
120       (let ((temp (gensym)))
121         `(let ((,temp (abs float2)))
122           (if (minusp (single-float-bits float)) (- ,temp) ,temp)))
123       '(if (minusp (single-float-bits float)) -1f0 1f0)))
124
125 (deftransform float-sign ((float &optional float2)
126                           (double-float &optional double-float) *)
127   (if float2
128       (let ((temp (gensym)))
129         `(let ((,temp (abs float2)))
130           (if (minusp (double-float-high-bits float)) (- ,temp) ,temp)))
131       '(if (minusp (double-float-high-bits float)) -1d0 1d0)))
132 \f
133 ;;;; DECODE-FLOAT, INTEGER-DECODE-FLOAT, and SCALE-FLOAT
134
135 (defknown decode-single-float (single-float)
136   (values single-float single-float-exponent (single-float -1f0 1f0))
137   (movable foldable flushable))
138
139 (defknown decode-double-float (double-float)
140   (values double-float double-float-exponent (double-float -1d0 1d0))
141   (movable foldable flushable))
142
143 (defknown integer-decode-single-float (single-float)
144   (values single-float-significand single-float-int-exponent (integer -1 1))
145   (movable foldable flushable))
146
147 (defknown integer-decode-double-float (double-float)
148   (values double-float-significand double-float-int-exponent (integer -1 1))
149   (movable foldable flushable))
150
151 (defknown scale-single-float (single-float integer) single-float
152   (movable foldable flushable))
153
154 (defknown scale-double-float (double-float integer) double-float
155   (movable foldable flushable))
156
157 (deftransform decode-float ((x) (single-float) *)
158   '(decode-single-float x))
159
160 (deftransform decode-float ((x) (double-float) *)
161   '(decode-double-float x))
162
163 (deftransform integer-decode-float ((x) (single-float) *)
164   '(integer-decode-single-float x))
165
166 (deftransform integer-decode-float ((x) (double-float) *)
167   '(integer-decode-double-float x))
168
169 (deftransform scale-float ((f ex) (single-float *) *)
170   (if (and #!+x86 t #!-x86 nil
171            (csubtypep (lvar-type ex)
172                       (specifier-type '(signed-byte 32))))
173       '(coerce (%scalbn (coerce f 'double-float) ex) 'single-float)
174       '(scale-single-float f ex)))
175
176 (deftransform scale-float ((f ex) (double-float *) *)
177   (if (and #!+x86 t #!-x86 nil
178            (csubtypep (lvar-type ex)
179                       (specifier-type '(signed-byte 32))))
180       '(%scalbn f ex)
181       '(scale-double-float f ex)))
182
183 ;;; What is the CROSS-FLOAT-INFINITY-KLUDGE?
184 ;;;
185 ;;; SBCL's own implementation of floating point supports floating
186 ;;; point infinities. Some of the old CMU CL :PROPAGATE-FLOAT-TYPE and
187 ;;; :PROPAGATE-FUN-TYPE code, like the DEFOPTIMIZERs below, uses this
188 ;;; floating point support. Thus, we have to avoid running it on the
189 ;;; cross-compilation host, since we're not guaranteed that the
190 ;;; cross-compilation host will support floating point infinities.
191 ;;;
192 ;;; If we wanted to live dangerously, we could conditionalize the code
193 ;;; with #+(OR SBCL SB-XC) instead. That way, if the cross-compilation
194 ;;; host happened to be SBCL, we'd be able to run the infinity-using
195 ;;; code. Pro:
196 ;;;   * SBCL itself gets built with more complete optimization.
197 ;;; Con:
198 ;;;   * You get a different SBCL depending on what your cross-compilation
199 ;;;     host is.
200 ;;; So far the pros and cons seem seem to be mostly academic, since
201 ;;; AFAIK (WHN 2001-08-28) the propagate-foo-type optimizations aren't
202 ;;; actually important in compiling SBCL itself. If this changes, then
203 ;;; we have to decide:
204 ;;;   * Go for simplicity, leaving things as they are.
205 ;;;   * Go for performance at the expense of conceptual clarity,
206 ;;;     using #+(OR SBCL SB-XC) and otherwise leaving the build
207 ;;;     process as is.
208 ;;;   * Go for performance at the expense of build time, using
209 ;;;     #+(OR SBCL SB-XC) and also making SBCL do not just
210 ;;;     make-host-1.sh and make-host-2.sh, but a third step
211 ;;;     make-host-3.sh where it builds itself under itself. (Such a
212 ;;;     3-step build process could also help with other things, e.g.
213 ;;;     using specialized arrays to represent debug information.)
214 ;;;   * Rewrite the code so that it doesn't depend on unportable
215 ;;;     floating point infinities.
216
217 ;;; optimizers for SCALE-FLOAT. If the float has bounds, new bounds
218 ;;; are computed for the result, if possible.
219 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
220 (progn
221
222 (defun scale-float-derive-type-aux (f ex same-arg)
223   (declare (ignore same-arg))
224   (flet ((scale-bound (x n)
225            ;; We need to be a bit careful here and catch any overflows
226            ;; that might occur. We can ignore underflows which become
227            ;; zeros.
228            (set-bound
229             (handler-case
230              (scale-float (type-bound-number x) n)
231              (floating-point-overflow ()
232                 nil))
233             (consp x))))
234     (when (and (numeric-type-p f) (numeric-type-p ex))
235       (let ((f-lo (numeric-type-low f))
236             (f-hi (numeric-type-high f))
237             (ex-lo (numeric-type-low ex))
238             (ex-hi (numeric-type-high ex))
239             (new-lo nil)
240             (new-hi nil))
241         (when f-hi
242           (if (< (float-sign (type-bound-number f-hi)) 0.0)
243               (when ex-lo
244                 (setf new-hi (scale-bound f-hi ex-lo)))
245               (when ex-hi
246                 (setf new-hi (scale-bound f-hi ex-hi)))))
247         (when f-lo
248           (if (< (float-sign (type-bound-number f-lo)) 0.0)
249               (when ex-hi
250                 (setf new-lo (scale-bound f-lo ex-hi)))
251               (when ex-lo
252                 (setf new-lo (scale-bound f-lo ex-lo)))))
253         (make-numeric-type :class (numeric-type-class f)
254                            :format (numeric-type-format f)
255                            :complexp :real
256                            :low new-lo
257                            :high new-hi)))))
258 (defoptimizer (scale-single-float derive-type) ((f ex))
259   (two-arg-derive-type f ex #'scale-float-derive-type-aux
260                        #'scale-single-float t))
261 (defoptimizer (scale-double-float derive-type) ((f ex))
262   (two-arg-derive-type f ex #'scale-float-derive-type-aux
263                        #'scale-double-float t))
264
265 ;;; DEFOPTIMIZERs for %SINGLE-FLOAT and %DOUBLE-FLOAT. This makes the
266 ;;; FLOAT function return the correct ranges if the input has some
267 ;;; defined range. Quite useful if we want to convert some type of
268 ;;; bounded integer into a float.
269 (macrolet
270     ((frob (fun type most-negative most-positive)
271        (let ((aux-name (symbolicate fun "-DERIVE-TYPE-AUX")))
272          `(progn
273             (defun ,aux-name (num)
274               ;; When converting a number to a float, the limits are
275               ;; the same.
276               (let* ((lo (bound-func (lambda (x)
277                                        (if (< x ,most-negative)
278                                            ,most-negative
279                                            (coerce x ',type)))
280                                      (numeric-type-low num)))
281                      (hi (bound-func (lambda (x)
282                                        (if (< ,most-positive x )
283                                            ,most-positive
284                                            (coerce x ',type)))
285                                      (numeric-type-high num))))
286                 (specifier-type `(,',type ,(or lo '*) ,(or hi '*)))))
287
288             (defoptimizer (,fun derive-type) ((num))
289               (handler-case
290                   (one-arg-derive-type num #',aux-name #',fun)
291                 (type-error ()
292                   nil)))))))
293   (frob %single-float single-float
294         most-negative-single-float most-positive-single-float)
295   (frob %double-float double-float
296         most-negative-double-float most-positive-double-float))
297 ) ; PROGN
298 \f
299 ;;;; float contagion
300
301 (defun safe-ctype-for-single-coercion-p (x)
302   ;; See comment in SAFE-SINGLE-COERCION-P -- this deals with the same
303   ;; problem, but in the context of evaluated and compiled (+ <int> <single>)
304   ;; giving different result if we fail to check for this.
305   (or (not (csubtypep x (specifier-type 'integer)))
306       (csubtypep x (specifier-type `(integer ,most-negative-exactly-single-float-fixnum
307                                              ,most-positive-exactly-single-float-fixnum)))))
308
309 ;;; Do some stuff to recognize when the loser is doing mixed float and
310 ;;; rational arithmetic, or different float types, and fix it up. If
311 ;;; we don't, he won't even get so much as an efficiency note.
312 (deftransform float-contagion-arg1 ((x y) * * :defun-only t :node node)
313   (if (or (not (types-equal-or-intersect (lvar-type y) (specifier-type 'single-float)))
314           (safe-ctype-for-single-coercion-p (lvar-type x)))
315       `(,(lvar-fun-name (basic-combination-fun node))
316          (float x y) y)
317       (give-up-ir1-transform)))
318 (deftransform float-contagion-arg2 ((x y) * * :defun-only t :node node)
319   (if (or (not (types-equal-or-intersect (lvar-type x) (specifier-type 'single-float)))
320           (safe-ctype-for-single-coercion-p (lvar-type y)))
321       `(,(lvar-fun-name (basic-combination-fun node))
322          x (float y x))
323       (give-up-ir1-transform)))
324
325 (dolist (x '(+ * / -))
326   (%deftransform x '(function (rational float) *) #'float-contagion-arg1)
327   (%deftransform x '(function (float rational) *) #'float-contagion-arg2))
328
329 (dolist (x '(= < > + * / -))
330   (%deftransform x '(function (single-float double-float) *)
331                  #'float-contagion-arg1)
332   (%deftransform x '(function (double-float single-float) *)
333                  #'float-contagion-arg2))
334
335 ;;; Optimize division and multiplication by one and minus one.
336 (macrolet ((def (op type &rest args)
337              `(deftransform ,op ((x y) (,type (constant-arg (member ,@args))))
338                 (if (minusp (lvar-value y))
339                     '(+ (%negate x) ,(coerce 0 type))
340                     '(+ x ,(coerce 0 type))))))
341   (def / single-float 1 1.0 -1 -1.0)
342   (def * single-float 1 1.0 -1 -1.0)
343   (def / double-float 1 1.0 1.0d0 -1 -1.0 -1.0d0)
344   (def * double-float 1 1.0 1.0d0 -1 -1.0 -1.0d0))
345
346 ;;; Optimize addition and subsctraction of zero
347 (macrolet ((def (op type &rest args)
348              `(deftransform ,op ((x y) (,type (constant-arg (member ,@args))) *
349                                  ;; Beware the SNaN!
350                                  :policy (zerop float-accuracy))
351                 'x)))
352   ;; No signed zeros, thanks.
353   (def + single-float 0 0.0)
354   (def - single-float 0 0.0)
355   (def + double-float 0 0.0 0.0d0)
356   (def - double-float 0 0.0 0.0d0))
357
358 ;;; On most platforms (+ x x) is faster than (* x 2)
359 (macrolet ((def (type &rest args)
360              `(deftransform * ((x y) (,type (constant-arg (member ,@args))))
361                 '(+ x x))))
362   (def single-float 2 2.0)
363   (def double-float 2 2.0 2.0d0))
364
365 ;;; Prevent ZEROP, PLUSP, and MINUSP from losing horribly. We can't in
366 ;;; general float rational args to comparison, since Common Lisp
367 ;;; semantics says we are supposed to compare as rationals, but we can
368 ;;; do it for any rational that has a precise representation as a
369 ;;; float (such as 0).
370 (macrolet ((frob (op)
371              `(deftransform ,op ((x y) (float rational) *)
372                 "open-code FLOAT to RATIONAL comparison"
373                 (unless (constant-lvar-p y)
374                   (give-up-ir1-transform
375                    "The RATIONAL value isn't known at compile time."))
376                 (let ((val (lvar-value y)))
377                   (unless (eql (rational (float val)) val)
378                     (give-up-ir1-transform
379                      "~S doesn't have a precise float representation."
380                      val)))
381                 `(,',op x (float y x)))))
382   (frob <)
383   (frob >)
384   (frob =))
385 \f
386 ;;;; irrational derive-type methods
387
388 ;;; Derive the result to be float for argument types in the
389 ;;; appropriate domain.
390 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
391 (dolist (stuff '((asin (real -1.0 1.0))
392                  (acos (real -1.0 1.0))
393                  (acosh (real 1.0))
394                  (atanh (real -1.0 1.0))
395                  (sqrt (real 0.0))))
396   (destructuring-bind (name type) stuff
397     (let ((type (specifier-type type)))
398       (setf (fun-info-derive-type (fun-info-or-lose name))
399             (lambda (call)
400               (declare (type combination call))
401               (when (csubtypep (lvar-type
402                                 (first (combination-args call)))
403                                type)
404                 (specifier-type 'float)))))))
405
406 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
407 (defoptimizer (log derive-type) ((x &optional y))
408   (when (and (csubtypep (lvar-type x)
409                         (specifier-type '(real 0.0)))
410              (or (null y)
411                  (csubtypep (lvar-type y)
412                             (specifier-type '(real 0.0)))))
413     (specifier-type 'float)))
414 \f
415 ;;;; irrational transforms
416
417 (defknown (%tan %sinh %asinh %atanh %log %logb %log10 %tan-quick)
418           (double-float) double-float
419   (movable foldable flushable))
420
421 (defknown (%sin %cos %tanh %sin-quick %cos-quick)
422   (double-float) (double-float -1.0d0 1.0d0)
423   (movable foldable flushable))
424
425 (defknown (%asin %atan)
426   (double-float)
427   (double-float #.(coerce (- (/ pi 2)) 'double-float)
428                 #.(coerce (/ pi 2) 'double-float))
429   (movable foldable flushable))
430
431 (defknown (%acos)
432   (double-float) (double-float 0.0d0 #.(coerce pi 'double-float))
433   (movable foldable flushable))
434
435 (defknown (%cosh)
436   (double-float) (double-float 1.0d0)
437   (movable foldable flushable))
438
439 (defknown (%acosh %exp %sqrt)
440   (double-float) (double-float 0.0d0)
441   (movable foldable flushable))
442
443 (defknown %expm1
444   (double-float) (double-float -1d0)
445   (movable foldable flushable))
446
447 (defknown (%hypot)
448   (double-float double-float) (double-float 0d0)
449   (movable foldable flushable))
450
451 (defknown (%pow)
452   (double-float double-float) double-float
453   (movable foldable flushable))
454
455 (defknown (%atan2)
456   (double-float double-float)
457   (double-float #.(coerce (- pi) 'double-float)
458                 #.(coerce pi 'double-float))
459   (movable foldable flushable))
460
461 (defknown (%scalb)
462   (double-float double-float) double-float
463   (movable foldable flushable))
464
465 (defknown (%scalbn)
466   (double-float (signed-byte 32)) double-float
467   (movable foldable flushable))
468
469 (defknown (%log1p)
470   (double-float) double-float
471   (movable foldable flushable))
472
473 (macrolet ((def (name prim rtype)
474              `(progn
475                (deftransform ,name ((x) (single-float) ,rtype)
476                  `(coerce (,',prim (coerce x 'double-float)) 'single-float))
477                (deftransform ,name ((x) (double-float) ,rtype)
478                  `(,',prim x)))))
479   (def exp %exp *)
480   (def log %log float)
481   (def sqrt %sqrt float)
482   (def asin %asin float)
483   (def acos %acos float)
484   (def atan %atan *)
485   (def sinh %sinh *)
486   (def cosh %cosh *)
487   (def tanh %tanh *)
488   (def asinh %asinh *)
489   (def acosh %acosh float)
490   (def atanh %atanh float))
491
492 ;;; The argument range is limited on the x86 FP trig. functions. A
493 ;;; post-test can detect a failure (and load a suitable result), but
494 ;;; this test is avoided if possible.
495 (macrolet ((def (name prim prim-quick)
496              (declare (ignorable prim-quick))
497              `(progn
498                 (deftransform ,name ((x) (single-float) *)
499                   #!+x86 (cond ((csubtypep (lvar-type x)
500                                            (specifier-type '(single-float
501                                                              (#.(- (expt 2f0 64)))
502                                                              (#.(expt 2f0 64)))))
503                                 `(coerce (,',prim-quick (coerce x 'double-float))
504                                   'single-float))
505                                (t
506                                 (compiler-notify
507                                  "unable to avoid inline argument range check~@
508                                   because the argument range (~S) was not within 2^64"
509                                  (type-specifier (lvar-type x)))
510                                 `(coerce (,',prim (coerce x 'double-float)) 'single-float)))
511                   #!-x86 `(coerce (,',prim (coerce x 'double-float)) 'single-float))
512                (deftransform ,name ((x) (double-float) *)
513                  #!+x86 (cond ((csubtypep (lvar-type x)
514                                           (specifier-type '(double-float
515                                                             (#.(- (expt 2d0 64)))
516                                                             (#.(expt 2d0 64)))))
517                                `(,',prim-quick x))
518                               (t
519                                (compiler-notify
520                                 "unable to avoid inline argument range check~@
521                                  because the argument range (~S) was not within 2^64"
522                                 (type-specifier (lvar-type x)))
523                                `(,',prim x)))
524                  #!-x86 `(,',prim x)))))
525   (def sin %sin %sin-quick)
526   (def cos %cos %cos-quick)
527   (def tan %tan %tan-quick))
528
529 (deftransform atan ((x y) (single-float single-float) *)
530   `(coerce (%atan2 (coerce x 'double-float) (coerce y 'double-float))
531     'single-float))
532 (deftransform atan ((x y) (double-float double-float) *)
533   `(%atan2 x y))
534
535 (deftransform expt ((x y) ((single-float 0f0) single-float) *)
536   `(coerce (%pow (coerce x 'double-float) (coerce y 'double-float))
537     'single-float))
538 (deftransform expt ((x y) ((double-float 0d0) double-float) *)
539   `(%pow x y))
540 (deftransform expt ((x y) ((single-float 0f0) (signed-byte 32)) *)
541   `(coerce (%pow (coerce x 'double-float) (coerce y 'double-float))
542     'single-float))
543 (deftransform expt ((x y) ((double-float 0d0) (signed-byte 32)) *)
544   `(%pow x (coerce y 'double-float)))
545
546 ;;; ANSI says log with base zero returns zero.
547 (deftransform log ((x y) (float float) float)
548   '(if (zerop y) y (/ (log x) (log y))))
549 \f
550 ;;; Handle some simple transformations.
551
552 (deftransform abs ((x) ((complex double-float)) double-float)
553   '(%hypot (realpart x) (imagpart x)))
554
555 (deftransform abs ((x) ((complex single-float)) single-float)
556   '(coerce (%hypot (coerce (realpart x) 'double-float)
557                    (coerce (imagpart x) 'double-float))
558           'single-float))
559
560 (deftransform phase ((x) ((complex double-float)) double-float)
561   '(%atan2 (imagpart x) (realpart x)))
562
563 (deftransform phase ((x) ((complex single-float)) single-float)
564   '(coerce (%atan2 (coerce (imagpart x) 'double-float)
565                    (coerce (realpart x) 'double-float))
566           'single-float))
567
568 (deftransform phase ((x) ((float)) float)
569   '(if (minusp (float-sign x))
570        (float pi x)
571        (float 0 x)))
572
573 ;;; The number is of type REAL.
574 (defun numeric-type-real-p (type)
575   (and (numeric-type-p type)
576        (eq (numeric-type-complexp type) :real)))
577
578 ;;; Coerce a numeric type bound to the given type while handling
579 ;;; exclusive bounds.
580 (defun coerce-numeric-bound (bound type)
581   (when bound
582     (if (consp bound)
583         (list (coerce (car bound) type))
584         (coerce bound type))))
585
586 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
587 (progn
588
589 ;;;; optimizers for elementary functions
590 ;;;;
591 ;;;; These optimizers compute the output range of the elementary
592 ;;;; function, based on the domain of the input.
593
594 ;;; Generate a specifier for a complex type specialized to the same
595 ;;; type as the argument.
596 (defun complex-float-type (arg)
597   (declare (type numeric-type arg))
598   (let* ((format (case (numeric-type-class arg)
599                    ((integer rational) 'single-float)
600                    (t (numeric-type-format arg))))
601          (float-type (or format 'float)))
602     (specifier-type `(complex ,float-type))))
603
604 ;;; Compute a specifier like '(OR FLOAT (COMPLEX FLOAT)), except float
605 ;;; should be the right kind of float. Allow bounds for the float
606 ;;; part too.
607 (defun float-or-complex-float-type (arg &optional lo hi)
608   (declare (type numeric-type arg))
609   (let* ((format (case (numeric-type-class arg)
610                    ((integer rational) 'single-float)
611                    (t (numeric-type-format arg))))
612          (float-type (or format 'float))
613          (lo (coerce-numeric-bound lo float-type))
614          (hi (coerce-numeric-bound hi float-type)))
615     (specifier-type `(or (,float-type ,(or lo '*) ,(or hi '*))
616                          (complex ,float-type)))))
617
618 ) ; PROGN
619
620 (eval-when (:compile-toplevel :execute)
621   ;; So the problem with this hack is that it's actually broken.  If
622   ;; the host does not have long floats, then setting *R-D-F-F* to
623   ;; LONG-FLOAT doesn't actually buy us anything.  FIXME.
624   (setf *read-default-float-format*
625         #!+long-float 'long-float #!-long-float 'double-float))
626 ;;; Test whether the numeric-type ARG is within in domain specified by
627 ;;; DOMAIN-LOW and DOMAIN-HIGH, consider negative and positive zero to
628 ;;; be distinct.
629 #-sb-xc-host  ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
630 (defun domain-subtypep (arg domain-low domain-high)
631   (declare (type numeric-type arg)
632            (type (or real null) domain-low domain-high))
633   (let* ((arg-lo (numeric-type-low arg))
634          (arg-lo-val (type-bound-number arg-lo))
635          (arg-hi (numeric-type-high arg))
636          (arg-hi-val (type-bound-number arg-hi)))
637     ;; Check that the ARG bounds are correctly canonicalized.
638     (when (and arg-lo (floatp arg-lo-val) (zerop arg-lo-val) (consp arg-lo)
639                (minusp (float-sign arg-lo-val)))
640       (compiler-notify "float zero bound ~S not correctly canonicalized?" arg-lo)
641       (setq arg-lo 0e0 arg-lo-val arg-lo))
642     (when (and arg-hi (zerop arg-hi-val) (floatp arg-hi-val) (consp arg-hi)
643                (plusp (float-sign arg-hi-val)))
644       (compiler-notify "float zero bound ~S not correctly canonicalized?" arg-hi)
645       (setq arg-hi (ecase *read-default-float-format*
646                      (double-float (load-time-value (make-unportable-float :double-float-negative-zero)))
647                      #!+long-float
648                      (long-float (load-time-value (make-unportable-float :long-float-negative-zero))))
649             arg-hi-val arg-hi))
650     (flet ((fp-neg-zero-p (f)           ; Is F -0.0?
651              (and (floatp f) (zerop f) (minusp (float-sign f))))
652            (fp-pos-zero-p (f)           ; Is F +0.0?
653              (and (floatp f) (zerop f) (plusp (float-sign f)))))
654       (and (or (null domain-low)
655                (and arg-lo (>= arg-lo-val domain-low)
656                     (not (and (fp-pos-zero-p domain-low)
657                               (fp-neg-zero-p arg-lo)))))
658            (or (null domain-high)
659                (and arg-hi (<= arg-hi-val domain-high)
660                     (not (and (fp-neg-zero-p domain-high)
661                               (fp-pos-zero-p arg-hi)))))))))
662 (eval-when (:compile-toplevel :execute)
663   (setf *read-default-float-format* 'single-float))
664
665 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
666 (progn
667
668 ;;; Handle monotonic functions of a single variable whose domain is
669 ;;; possibly part of the real line. ARG is the variable, FUN is the
670 ;;; function, and DOMAIN is a specifier that gives the (real) domain
671 ;;; of the function. If ARG is a subset of the DOMAIN, we compute the
672 ;;; bounds directly. Otherwise, we compute the bounds for the
673 ;;; intersection between ARG and DOMAIN, and then append a complex
674 ;;; result, which occurs for the parts of ARG not in the DOMAIN.
675 ;;;
676 ;;; Negative and positive zero are considered distinct within
677 ;;; DOMAIN-LOW and DOMAIN-HIGH.
678 ;;;
679 ;;; DEFAULT-LOW and DEFAULT-HIGH are the lower and upper bounds if we
680 ;;; can't compute the bounds using FUN.
681 (defun elfun-derive-type-simple (arg fun domain-low domain-high
682                                      default-low default-high
683                                      &optional (increasingp t))
684   (declare (type (or null real) domain-low domain-high))
685   (etypecase arg
686     (numeric-type
687      (cond ((eq (numeric-type-complexp arg) :complex)
688             (complex-float-type arg))
689            ((numeric-type-real-p arg)
690             ;; The argument is real, so let's find the intersection
691             ;; between the argument and the domain of the function.
692             ;; We compute the bounds on the intersection, and for
693             ;; everything else, we return a complex number of the
694             ;; appropriate type.
695             (multiple-value-bind (intersection difference)
696                 (interval-intersection/difference (numeric-type->interval arg)
697                                                   (make-interval
698                                                    :low domain-low
699                                                    :high domain-high))
700               (cond
701                 (intersection
702                  ;; Process the intersection.
703                  (let* ((low (interval-low intersection))
704                         (high (interval-high intersection))
705                         (res-lo (or (bound-func fun (if increasingp low high))
706                                     default-low))
707                         (res-hi (or (bound-func fun (if increasingp high low))
708                                     default-high))
709                         (format (case (numeric-type-class arg)
710                                   ((integer rational) 'single-float)
711                                   (t (numeric-type-format arg))))
712                         (bound-type (or format 'float))
713                         (result-type
714                          (make-numeric-type
715                           :class 'float
716                           :format format
717                           :low (coerce-numeric-bound res-lo bound-type)
718                           :high (coerce-numeric-bound res-hi bound-type))))
719                    ;; If the ARG is a subset of the domain, we don't
720                    ;; have to worry about the difference, because that
721                    ;; can't occur.
722                    (if (or (null difference)
723                            ;; Check whether the arg is within the domain.
724                            (domain-subtypep arg domain-low domain-high))
725                        result-type
726                        (list result-type
727                              (specifier-type `(complex ,bound-type))))))
728                 (t
729                  ;; No intersection so the result must be purely complex.
730                  (complex-float-type arg)))))
731            (t
732             (float-or-complex-float-type arg default-low default-high))))))
733
734 (macrolet
735     ((frob (name domain-low domain-high def-low-bnd def-high-bnd
736                  &key (increasingp t))
737        (let ((num (gensym)))
738          `(defoptimizer (,name derive-type) ((,num))
739            (one-arg-derive-type
740             ,num
741             (lambda (arg)
742               (elfun-derive-type-simple arg #',name
743                                         ,domain-low ,domain-high
744                                         ,def-low-bnd ,def-high-bnd
745                                         ,increasingp))
746             #',name)))))
747   ;; These functions are easy because they are defined for the whole
748   ;; real line.
749   (frob exp nil nil 0 nil)
750   (frob sinh nil nil nil nil)
751   (frob tanh nil nil -1 1)
752   (frob asinh nil nil nil nil)
753
754   ;; These functions are only defined for part of the real line. The
755   ;; condition selects the desired part of the line.
756   (frob asin -1d0 1d0 (- (/ pi 2)) (/ pi 2))
757   ;; Acos is monotonic decreasing, so we need to swap the function
758   ;; values at the lower and upper bounds of the input domain.
759   (frob acos -1d0 1d0 0 pi :increasingp nil)
760   (frob acosh 1d0 nil nil nil)
761   (frob atanh -1d0 1d0 -1 1)
762   ;; Kahan says that (sqrt -0.0) is -0.0, so use a specifier that
763   ;; includes -0.0.
764   (frob sqrt (load-time-value (make-unportable-float :double-float-negative-zero)) nil 0 nil))
765
766 ;;; Compute bounds for (expt x y). This should be easy since (expt x
767 ;;; y) = (exp (* y (log x))). However, computations done this way
768 ;;; have too much roundoff. Thus we have to do it the hard way.
769 (defun safe-expt (x y)
770   (handler-case
771       (when (< (abs y) 10000)
772         (expt x y))
773     (error ()
774       nil)))
775
776 ;;; Handle the case when x >= 1.
777 (defun interval-expt-> (x y)
778   (case (sb!c::interval-range-info y 0d0)
779     (+
780      ;; Y is positive and log X >= 0. The range of exp(y * log(x)) is
781      ;; obviously non-negative. We just have to be careful for
782      ;; infinite bounds (given by nil).
783      (let ((lo (safe-expt (type-bound-number (sb!c::interval-low x))
784                           (type-bound-number (sb!c::interval-low y))))
785            (hi (safe-expt (type-bound-number (sb!c::interval-high x))
786                           (type-bound-number (sb!c::interval-high y)))))
787        (list (sb!c::make-interval :low (or lo 1) :high hi))))
788     (-
789      ;; Y is negative and log x >= 0. The range of exp(y * log(x)) is
790      ;; obviously [0, 1]. However, underflow (nil) means 0 is the
791      ;; result.
792      (let ((lo (safe-expt (type-bound-number (sb!c::interval-high x))
793                           (type-bound-number (sb!c::interval-low y))))
794            (hi (safe-expt (type-bound-number (sb!c::interval-low x))
795                           (type-bound-number (sb!c::interval-high y)))))
796        (list (sb!c::make-interval :low (or lo 0) :high (or hi 1)))))
797     (t
798      ;; Split the interval in half.
799      (destructuring-bind (y- y+)
800          (sb!c::interval-split 0 y t)
801        (list (interval-expt-> x y-)
802              (interval-expt-> x y+))))))
803
804 ;;; Handle the case when x <= 1
805 (defun interval-expt-< (x y)
806   (case (sb!c::interval-range-info x 0d0)
807     (+
808      ;; The case of 0 <= x <= 1 is easy
809      (case (sb!c::interval-range-info y)
810        (+
811         ;; Y is positive and log X <= 0. The range of exp(y * log(x)) is
812         ;; obviously [0, 1]. We just have to be careful for infinite bounds
813         ;; (given by nil).
814         (let ((lo (safe-expt (type-bound-number (sb!c::interval-low x))
815                              (type-bound-number (sb!c::interval-high y))))
816               (hi (safe-expt (type-bound-number (sb!c::interval-high x))
817                              (type-bound-number (sb!c::interval-low y)))))
818           (list (sb!c::make-interval :low (or lo 0) :high (or hi 1)))))
819        (-
820         ;; Y is negative and log x <= 0. The range of exp(y * log(x)) is
821         ;; obviously [1, inf].
822         (let ((hi (safe-expt (type-bound-number (sb!c::interval-low x))
823                              (type-bound-number (sb!c::interval-low y))))
824               (lo (safe-expt (type-bound-number (sb!c::interval-high x))
825                              (type-bound-number (sb!c::interval-high y)))))
826           (list (sb!c::make-interval :low (or lo 1) :high hi))))
827        (t
828         ;; Split the interval in half
829         (destructuring-bind (y- y+)
830             (sb!c::interval-split 0 y t)
831           (list (interval-expt-< x y-)
832                 (interval-expt-< x y+))))))
833     (-
834      ;; The case where x <= 0. Y MUST be an INTEGER for this to work!
835      ;; The calling function must insure this! For now we'll just
836      ;; return the appropriate unbounded float type.
837      (list (sb!c::make-interval :low nil :high nil)))
838     (t
839      (destructuring-bind (neg pos)
840          (interval-split 0 x t t)
841        (list (interval-expt-< neg y)
842              (interval-expt-< pos y))))))
843
844 ;;; Compute bounds for (expt x y).
845 (defun interval-expt (x y)
846   (case (interval-range-info x 1)
847     (+
848      ;; X >= 1
849          (interval-expt-> x y))
850     (-
851      ;; X <= 1
852      (interval-expt-< x y))
853     (t
854      (destructuring-bind (left right)
855          (interval-split 1 x t t)
856        (list (interval-expt left y)
857              (interval-expt right y))))))
858
859 (defun fixup-interval-expt (bnd x-int y-int x-type y-type)
860   (declare (ignore x-int))
861   ;; Figure out what the return type should be, given the argument
862   ;; types and bounds and the result type and bounds.
863   (cond ((csubtypep x-type (specifier-type 'integer))
864          ;; an integer to some power
865          (case (numeric-type-class y-type)
866            (integer
867             ;; Positive integer to an integer power is either an
868             ;; integer or a rational.
869             (let ((lo (or (interval-low bnd) '*))
870                   (hi (or (interval-high bnd) '*)))
871               (if (and (interval-low y-int)
872                        (>= (type-bound-number (interval-low y-int)) 0))
873                   (specifier-type `(integer ,lo ,hi))
874                   (specifier-type `(rational ,lo ,hi)))))
875            (rational
876             ;; Positive integer to rational power is either a rational
877             ;; or a single-float.
878             (let* ((lo (interval-low bnd))
879                    (hi (interval-high bnd))
880                    (int-lo (if lo
881                                (floor (type-bound-number lo))
882                                '*))
883                    (int-hi (if hi
884                                (ceiling (type-bound-number hi))
885                                '*))
886                    (f-lo (if lo
887                              (bound-func #'float lo)
888                              '*))
889                    (f-hi (if hi
890                              (bound-func #'float hi)
891                              '*)))
892               (specifier-type `(or (rational ,int-lo ,int-hi)
893                                 (single-float ,f-lo, f-hi)))))
894            (float
895             ;; A positive integer to a float power is a float.
896             (modified-numeric-type y-type
897                                    :low (interval-low bnd)
898                                    :high (interval-high bnd)))
899            (t
900             ;; A positive integer to a number is a number (for now).
901             (specifier-type 'number))))
902         ((csubtypep x-type (specifier-type 'rational))
903          ;; a rational to some power
904          (case (numeric-type-class y-type)
905            (integer
906             ;; A positive rational to an integer power is always a rational.
907             (specifier-type `(rational ,(or (interval-low bnd) '*)
908                                        ,(or (interval-high bnd) '*))))
909            (rational
910             ;; A positive rational to rational power is either a rational
911             ;; or a single-float.
912             (let* ((lo (interval-low bnd))
913                    (hi (interval-high bnd))
914                    (int-lo (if lo
915                                (floor (type-bound-number lo))
916                                '*))
917                    (int-hi (if hi
918                                (ceiling (type-bound-number hi))
919                                '*))
920                    (f-lo (if lo
921                              (bound-func #'float lo)
922                              '*))
923                    (f-hi (if hi
924                              (bound-func #'float hi)
925                              '*)))
926               (specifier-type `(or (rational ,int-lo ,int-hi)
927                                 (single-float ,f-lo, f-hi)))))
928            (float
929             ;; A positive rational to a float power is a float.
930             (modified-numeric-type y-type
931                                    :low (interval-low bnd)
932                                    :high (interval-high bnd)))
933            (t
934             ;; A positive rational to a number is a number (for now).
935             (specifier-type 'number))))
936         ((csubtypep x-type (specifier-type 'float))
937          ;; a float to some power
938          (case (numeric-type-class y-type)
939            ((or integer rational)
940             ;; A positive float to an integer or rational power is
941             ;; always a float.
942             (make-numeric-type
943              :class 'float
944              :format (numeric-type-format x-type)
945              :low (interval-low bnd)
946              :high (interval-high bnd)))
947            (float
948             ;; A positive float to a float power is a float of the
949             ;; higher type.
950             (make-numeric-type
951              :class 'float
952              :format (float-format-max (numeric-type-format x-type)
953                                        (numeric-type-format y-type))
954              :low (interval-low bnd)
955              :high (interval-high bnd)))
956            (t
957             ;; A positive float to a number is a number (for now)
958             (specifier-type 'number))))
959         (t
960          ;; A number to some power is a number.
961          (specifier-type 'number))))
962
963 (defun merged-interval-expt (x y)
964   (let* ((x-int (numeric-type->interval x))
965          (y-int (numeric-type->interval y)))
966     (mapcar (lambda (type)
967               (fixup-interval-expt type x-int y-int x y))
968             (flatten-list (interval-expt x-int y-int)))))
969
970 (defun expt-derive-type-aux (x y same-arg)
971   (declare (ignore same-arg))
972   (cond ((or (not (numeric-type-real-p x))
973              (not (numeric-type-real-p y)))
974          ;; Use numeric contagion if either is not real.
975          (numeric-contagion x y))
976         ((csubtypep y (specifier-type 'integer))
977          ;; A real raised to an integer power is well-defined.
978          (merged-interval-expt x y))
979         ;; A real raised to a non-integral power can be a float or a
980         ;; complex number.
981         ((or (csubtypep x (specifier-type '(rational 0)))
982              (csubtypep x (specifier-type '(float (0d0)))))
983          ;; But a positive real to any power is well-defined.
984          (merged-interval-expt x y))
985         ((and (csubtypep x (specifier-type 'rational))
986               (csubtypep x (specifier-type 'rational)))
987          ;; A rational to the power of a rational could be a rational
988          ;; or a possibly-complex single float
989          (specifier-type '(or rational single-float (complex single-float))))
990         (t
991          ;; a real to some power. The result could be a real or a
992          ;; complex.
993          (float-or-complex-float-type (numeric-contagion x y)))))
994
995 (defoptimizer (expt derive-type) ((x y))
996   (two-arg-derive-type x y #'expt-derive-type-aux #'expt))
997
998 ;;; Note we must assume that a type including 0.0 may also include
999 ;;; -0.0 and thus the result may be complex -infinity + i*pi.
1000 (defun log-derive-type-aux-1 (x)
1001   (elfun-derive-type-simple x #'log 0d0 nil nil nil))
1002
1003 (defun log-derive-type-aux-2 (x y same-arg)
1004   (let ((log-x (log-derive-type-aux-1 x))
1005         (log-y (log-derive-type-aux-1 y))
1006         (accumulated-list nil))
1007     ;; LOG-X or LOG-Y might be union types. We need to run through
1008     ;; the union types ourselves because /-DERIVE-TYPE-AUX doesn't.
1009     (dolist (x-type (prepare-arg-for-derive-type log-x))
1010       (dolist (y-type (prepare-arg-for-derive-type log-y))
1011         (push (/-derive-type-aux x-type y-type same-arg) accumulated-list)))
1012     (apply #'type-union (flatten-list accumulated-list))))
1013
1014 (defoptimizer (log derive-type) ((x &optional y))
1015   (if y
1016       (two-arg-derive-type x y #'log-derive-type-aux-2 #'log)
1017       (one-arg-derive-type x #'log-derive-type-aux-1 #'log)))
1018
1019 (defun atan-derive-type-aux-1 (y)
1020   (elfun-derive-type-simple y #'atan nil nil (- (/ pi 2)) (/ pi 2)))
1021
1022 (defun atan-derive-type-aux-2 (y x same-arg)
1023   (declare (ignore same-arg))
1024   ;; The hard case with two args. We just return the max bounds.
1025   (let ((result-type (numeric-contagion y x)))
1026     (cond ((and (numeric-type-real-p x)
1027                 (numeric-type-real-p y))
1028            (let* (;; FIXME: This expression for FORMAT seems to
1029                   ;; appear multiple times, and should be factored out.
1030                   (format (case (numeric-type-class result-type)
1031                             ((integer rational) 'single-float)
1032                             (t (numeric-type-format result-type))))
1033                   (bound-format (or format 'float)))
1034              (make-numeric-type :class 'float
1035                                 :format format
1036                                 :complexp :real
1037                                 :low (coerce (- pi) bound-format)
1038                                 :high (coerce pi bound-format))))
1039           (t
1040            ;; The result is a float or a complex number
1041            (float-or-complex-float-type result-type)))))
1042
1043 (defoptimizer (atan derive-type) ((y &optional x))
1044   (if x
1045       (two-arg-derive-type y x #'atan-derive-type-aux-2 #'atan)
1046       (one-arg-derive-type y #'atan-derive-type-aux-1 #'atan)))
1047
1048 (defun cosh-derive-type-aux (x)
1049   ;; We note that cosh x = cosh |x| for all real x.
1050   (elfun-derive-type-simple
1051    (if (numeric-type-real-p x)
1052        (abs-derive-type-aux x)
1053        x)
1054    #'cosh nil nil 0 nil))
1055
1056 (defoptimizer (cosh derive-type) ((num))
1057   (one-arg-derive-type num #'cosh-derive-type-aux #'cosh))
1058
1059 (defun phase-derive-type-aux (arg)
1060   (let* ((format (case (numeric-type-class arg)
1061                    ((integer rational) 'single-float)
1062                    (t (numeric-type-format arg))))
1063          (bound-type (or format 'float)))
1064     (cond ((numeric-type-real-p arg)
1065            (case (interval-range-info (numeric-type->interval arg) 0.0)
1066              (+
1067               ;; The number is positive, so the phase is 0.
1068               (make-numeric-type :class 'float
1069                                  :format format
1070                                  :complexp :real
1071                                  :low (coerce 0 bound-type)
1072                                  :high (coerce 0 bound-type)))
1073              (-
1074               ;; The number is always negative, so the phase is pi.
1075               (make-numeric-type :class 'float
1076                                  :format format
1077                                  :complexp :real
1078                                  :low (coerce pi bound-type)
1079                                  :high (coerce pi bound-type)))
1080              (t
1081               ;; We can't tell. The result is 0 or pi. Use a union
1082               ;; type for this.
1083               (list
1084                (make-numeric-type :class 'float
1085                                   :format format
1086                                   :complexp :real
1087                                   :low (coerce 0 bound-type)
1088                                   :high (coerce 0 bound-type))
1089                (make-numeric-type :class 'float
1090                                   :format format
1091                                   :complexp :real
1092                                   :low (coerce pi bound-type)
1093                                   :high (coerce pi bound-type))))))
1094           (t
1095            ;; We have a complex number. The answer is the range -pi
1096            ;; to pi. (-pi is included because we have -0.)
1097            (make-numeric-type :class 'float
1098                               :format format
1099                               :complexp :real
1100                               :low (coerce (- pi) bound-type)
1101                               :high (coerce pi bound-type))))))
1102
1103 (defoptimizer (phase derive-type) ((num))
1104   (one-arg-derive-type num #'phase-derive-type-aux #'phase))
1105
1106 ) ; PROGN
1107
1108 (deftransform realpart ((x) ((complex rational)) *)
1109   '(sb!kernel:%realpart x))
1110 (deftransform imagpart ((x) ((complex rational)) *)
1111   '(sb!kernel:%imagpart x))
1112
1113 ;;; Make REALPART and IMAGPART return the appropriate types. This
1114 ;;; should help a lot in optimized code.
1115 (defun realpart-derive-type-aux (type)
1116   (let ((class (numeric-type-class type))
1117         (format (numeric-type-format type)))
1118     (cond ((numeric-type-real-p type)
1119            ;; The realpart of a real has the same type and range as
1120            ;; the input.
1121            (make-numeric-type :class class
1122                               :format format
1123                               :complexp :real
1124                               :low (numeric-type-low type)
1125                               :high (numeric-type-high type)))
1126           (t
1127            ;; We have a complex number. The result has the same type
1128            ;; as the real part, except that it's real, not complex,
1129            ;; obviously.
1130            (make-numeric-type :class class
1131                               :format format
1132                               :complexp :real
1133                               :low (numeric-type-low type)
1134                               :high (numeric-type-high type))))))
1135 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1136 (defoptimizer (realpart derive-type) ((num))
1137   (one-arg-derive-type num #'realpart-derive-type-aux #'realpart))
1138 (defun imagpart-derive-type-aux (type)
1139   (let ((class (numeric-type-class type))
1140         (format (numeric-type-format type)))
1141     (cond ((numeric-type-real-p type)
1142            ;; The imagpart of a real has the same type as the input,
1143            ;; except that it's zero.
1144            (let ((bound-format (or format class 'real)))
1145              (make-numeric-type :class class
1146                                 :format format
1147                                 :complexp :real
1148                                 :low (coerce 0 bound-format)
1149                                 :high (coerce 0 bound-format))))
1150           (t
1151            ;; We have a complex number. The result has the same type as
1152            ;; the imaginary part, except that it's real, not complex,
1153            ;; obviously.
1154            (make-numeric-type :class class
1155                               :format format
1156                               :complexp :real
1157                               :low (numeric-type-low type)
1158                               :high (numeric-type-high type))))))
1159 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1160 (defoptimizer (imagpart derive-type) ((num))
1161   (one-arg-derive-type num #'imagpart-derive-type-aux #'imagpart))
1162
1163 (defun complex-derive-type-aux-1 (re-type)
1164   (if (numeric-type-p re-type)
1165       (make-numeric-type :class (numeric-type-class re-type)
1166                          :format (numeric-type-format re-type)
1167                          :complexp (if (csubtypep re-type
1168                                                   (specifier-type 'rational))
1169                                        :real
1170                                        :complex)
1171                          :low (numeric-type-low re-type)
1172                          :high (numeric-type-high re-type))
1173       (specifier-type 'complex)))
1174
1175 (defun complex-derive-type-aux-2 (re-type im-type same-arg)
1176   (declare (ignore same-arg))
1177   (if (and (numeric-type-p re-type)
1178            (numeric-type-p im-type))
1179       ;; Need to check to make sure numeric-contagion returns the
1180       ;; right type for what we want here.
1181
1182       ;; Also, what about rational canonicalization, like (complex 5 0)
1183       ;; is 5?  So, if the result must be complex, we make it so.
1184       ;; If the result might be complex, which happens only if the
1185       ;; arguments are rational, we make it a union type of (or
1186       ;; rational (complex rational)).
1187       (let* ((element-type (numeric-contagion re-type im-type))
1188              (rat-result-p (csubtypep element-type
1189                                       (specifier-type 'rational))))
1190         (if rat-result-p
1191             (type-union element-type
1192                         (specifier-type
1193                          `(complex ,(numeric-type-class element-type))))
1194             (make-numeric-type :class (numeric-type-class element-type)
1195                                :format (numeric-type-format element-type)
1196                                :complexp (if rat-result-p
1197                                              :real
1198                                              :complex))))
1199       (specifier-type 'complex)))
1200
1201 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1202 (defoptimizer (complex derive-type) ((re &optional im))
1203   (if im
1204       (two-arg-derive-type re im #'complex-derive-type-aux-2 #'complex)
1205       (one-arg-derive-type re #'complex-derive-type-aux-1 #'complex)))
1206
1207 ;;; Define some transforms for complex operations. We do this in lieu
1208 ;;; of complex operation VOPs.
1209 (macrolet ((frob (type)
1210              `(progn
1211                 (deftransform complex ((r) (,type))
1212                   '(complex r ,(coerce 0 type)))
1213                 (deftransform complex ((r i) (,type (and real (not ,type))))
1214                   '(complex r (truly-the ,type (coerce i ',type))))
1215                 (deftransform complex ((r i) ((and real (not ,type)) ,type))
1216                   '(complex (truly-the ,type (coerce r ',type)) i))
1217                ;; negation
1218                 #!-complex-float-vops
1219                (deftransform %negate ((z) ((complex ,type)) *)
1220                  '(complex (%negate (realpart z)) (%negate (imagpart z))))
1221                ;; complex addition and subtraction
1222                #!-complex-float-vops
1223                (deftransform + ((w z) ((complex ,type) (complex ,type)) *)
1224                  '(complex (+ (realpart w) (realpart z))
1225                            (+ (imagpart w) (imagpart z))))
1226                #!-complex-float-vops
1227                (deftransform - ((w z) ((complex ,type) (complex ,type)) *)
1228                  '(complex (- (realpart w) (realpart z))
1229                            (- (imagpart w) (imagpart z))))
1230                ;; Add and subtract a complex and a real.
1231                #!-complex-float-vops
1232                (deftransform + ((w z) ((complex ,type) real) *)
1233                  `(complex (+ (realpart w) z)
1234                            (+ (imagpart w) ,(coerce 0 ',type))))
1235                #!-complex-float-vops
1236                (deftransform + ((z w) (real (complex ,type)) *)
1237                  `(complex (+ (realpart w) z)
1238                            (+ (imagpart w) ,(coerce 0 ',type))))
1239                ;; Add and subtract a real and a complex number.
1240                #!-complex-float-vops
1241                (deftransform - ((w z) ((complex ,type) real) *)
1242                  `(complex (- (realpart w) z)
1243                            (- (imagpart w) ,(coerce 0 ',type))))
1244                #!-complex-float-vops
1245                (deftransform - ((z w) (real (complex ,type)) *)
1246                  `(complex (- z (realpart w))
1247                            (- ,(coerce 0 ',type) (imagpart w))))
1248                ;; Multiply and divide two complex numbers.
1249                #!-complex-float-vops
1250                (deftransform * ((x y) ((complex ,type) (complex ,type)) *)
1251                  '(let* ((rx (realpart x))
1252                          (ix (imagpart x))
1253                          (ry (realpart y))
1254                          (iy (imagpart y)))
1255                     (complex (- (* rx ry) (* ix iy))
1256                              (+ (* rx iy) (* ix ry)))))
1257                (deftransform / ((x y) ((complex ,type) (complex ,type)) *)
1258                  #!-complex-float-vops
1259                  '(let* ((rx (realpart x))
1260                          (ix (imagpart x))
1261                          (ry (realpart y))
1262                          (iy (imagpart y)))
1263                     (if (> (abs ry) (abs iy))
1264                         (let* ((r (/ iy ry))
1265                                (dn (+ ry (* r iy))))
1266                           (complex (/ (+ rx (* ix r)) dn)
1267                                    (/ (- ix (* rx r)) dn)))
1268                         (let* ((r (/ ry iy))
1269                                (dn (+ iy (* r ry))))
1270                           (complex (/ (+ (* rx r) ix) dn)
1271                                    (/ (- (* ix r) rx) dn)))))
1272                  #!+complex-float-vops
1273                  `(let* ((cs (conjugate (sb!vm::swap-complex x)))
1274                          (ry (realpart y))
1275                          (iy (imagpart y)))
1276                     (if (> (abs ry) (abs iy))
1277                         (let* ((r (/ iy ry))
1278                                (dn (+ ry (* r iy))))
1279                           (/ (+ x (* cs r)) dn))
1280                         (let* ((r (/ ry iy))
1281                                (dn (+ iy (* r ry))))
1282                           (/ (+ (* x r) cs) dn)))))
1283                ;; Multiply a complex by a real or vice versa.
1284                #!-complex-float-vops
1285                (deftransform * ((w z) ((complex ,type) real) *)
1286                  '(complex (* (realpart w) z) (* (imagpart w) z)))
1287                #!-complex-float-vops
1288                (deftransform * ((z w) (real (complex ,type)) *)
1289                  '(complex (* (realpart w) z) (* (imagpart w) z)))
1290                ;; Divide a complex by a real or vice versa.
1291                #!-complex-float-vops
1292                (deftransform / ((w z) ((complex ,type) real) *)
1293                  '(complex (/ (realpart w) z) (/ (imagpart w) z)))
1294                (deftransform / ((x y) (,type (complex ,type)) *)
1295                  #!-complex-float-vops
1296                  '(let* ((ry (realpart y))
1297                          (iy (imagpart y)))
1298                     (if (> (abs ry) (abs iy))
1299                         (let* ((r (/ iy ry))
1300                                (dn (+ ry (* r iy))))
1301                           (complex (/ x dn)
1302                                    (/ (- (* x r)) dn)))
1303                         (let* ((r (/ ry iy))
1304                                (dn (+ iy (* r ry))))
1305                           (complex (/ (* x r) dn)
1306                                    (/ (- x) dn)))))
1307                  #!+complex-float-vops
1308                  '(let* ((ry (realpart y))
1309                          (iy (imagpart y)))
1310                    (if (> (abs ry) (abs iy))
1311                        (let* ((r (/ iy ry))
1312                               (dn (+ ry (* r iy))))
1313                          (/ (complex x (- (* x r))) dn))
1314                        (let* ((r (/ ry iy))
1315                               (dn (+ iy (* r ry))))
1316                          (/ (complex (* x r) (- x)) dn)))))
1317                ;; conjugate of complex number
1318                #!-complex-float-vops
1319                (deftransform conjugate ((z) ((complex ,type)) *)
1320                  '(complex (realpart z) (- (imagpart z))))
1321                ;; CIS
1322                (deftransform cis ((z) ((,type)) *)
1323                  '(complex (cos z) (sin z)))
1324                ;; comparison
1325                #!-complex-float-vops
1326                (deftransform = ((w z) ((complex ,type) (complex ,type)) *)
1327                  '(and (= (realpart w) (realpart z))
1328                        (= (imagpart w) (imagpart z))))
1329                #!-complex-float-vops
1330                (deftransform = ((w z) ((complex ,type) real) *)
1331                  '(and (= (realpart w) z) (zerop (imagpart w))))
1332                #!-complex-float-vops
1333                (deftransform = ((w z) (real (complex ,type)) *)
1334                  '(and (= (realpart z) w) (zerop (imagpart z)))))))
1335
1336   (frob single-float)
1337   (frob double-float))
1338
1339 ;;; Here are simple optimizers for SIN, COS, and TAN. They do not
1340 ;;; produce a minimal range for the result; the result is the widest
1341 ;;; possible answer. This gets around the problem of doing range
1342 ;;; reduction correctly but still provides useful results when the
1343 ;;; inputs are union types.
1344 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1345 (progn
1346 (defun trig-derive-type-aux (arg domain fun
1347                                  &optional def-lo def-hi (increasingp t))
1348   (etypecase arg
1349     (numeric-type
1350      (cond ((eq (numeric-type-complexp arg) :complex)
1351             (make-numeric-type :class (numeric-type-class arg)
1352                                :format (numeric-type-format arg)
1353                                :complexp :complex))
1354            ((numeric-type-real-p arg)
1355             (let* ((format (case (numeric-type-class arg)
1356                              ((integer rational) 'single-float)
1357                              (t (numeric-type-format arg))))
1358                    (bound-type (or format 'float)))
1359               ;; If the argument is a subset of the "principal" domain
1360               ;; of the function, we can compute the bounds because
1361               ;; the function is monotonic. We can't do this in
1362               ;; general for these periodic functions because we can't
1363               ;; (and don't want to) do the argument reduction in
1364               ;; exactly the same way as the functions themselves do
1365               ;; it.
1366               (if (csubtypep arg domain)
1367                   (let ((res-lo (bound-func fun (numeric-type-low arg)))
1368                         (res-hi (bound-func fun (numeric-type-high arg))))
1369                     (unless increasingp
1370                       (rotatef res-lo res-hi))
1371                     (make-numeric-type
1372                      :class 'float
1373                      :format format
1374                      :low (coerce-numeric-bound res-lo bound-type)
1375                      :high (coerce-numeric-bound res-hi bound-type)))
1376                   (make-numeric-type
1377                    :class 'float
1378                    :format format
1379                    :low (and def-lo (coerce def-lo bound-type))
1380                    :high (and def-hi (coerce def-hi bound-type))))))
1381            (t
1382             (float-or-complex-float-type arg def-lo def-hi))))))
1383
1384 (defoptimizer (sin derive-type) ((num))
1385   (one-arg-derive-type
1386    num
1387    (lambda (arg)
1388      ;; Derive the bounds if the arg is in [-pi/2, pi/2].
1389      (trig-derive-type-aux
1390       arg
1391       (specifier-type `(float ,(- (/ pi 2)) ,(/ pi 2)))
1392       #'sin
1393       -1 1))
1394    #'sin))
1395
1396 (defoptimizer (cos derive-type) ((num))
1397   (one-arg-derive-type
1398    num
1399    (lambda (arg)
1400      ;; Derive the bounds if the arg is in [0, pi].
1401      (trig-derive-type-aux arg
1402                            (specifier-type `(float 0d0 ,pi))
1403                            #'cos
1404                            -1 1
1405                            nil))
1406    #'cos))
1407
1408 (defoptimizer (tan derive-type) ((num))
1409   (one-arg-derive-type
1410    num
1411    (lambda (arg)
1412      ;; Derive the bounds if the arg is in [-pi/2, pi/2].
1413      (trig-derive-type-aux arg
1414                            (specifier-type `(float ,(- (/ pi 2)) ,(/ pi 2)))
1415                            #'tan
1416                            nil nil))
1417    #'tan))
1418
1419 (defoptimizer (conjugate derive-type) ((num))
1420   (one-arg-derive-type num
1421     (lambda (arg)
1422       (flet ((most-negative-bound (l h)
1423                (and l h
1424                     (if (< (type-bound-number l) (- (type-bound-number h)))
1425                         l
1426                         (set-bound (- (type-bound-number h)) (consp h)))))
1427              (most-positive-bound (l h)
1428                (and l h
1429                     (if (> (type-bound-number h) (- (type-bound-number l)))
1430                         h
1431                         (set-bound (- (type-bound-number l)) (consp l))))))
1432         (if (numeric-type-real-p arg)
1433             (lvar-type num)
1434             (let ((low (numeric-type-low arg))
1435                   (high (numeric-type-high arg)))
1436               (let ((new-low (most-negative-bound low high))
1437                     (new-high (most-positive-bound low high)))
1438               (modified-numeric-type arg :low new-low :high new-high))))))
1439     #'conjugate))
1440
1441 (defoptimizer (cis derive-type) ((num))
1442   (one-arg-derive-type num
1443     (lambda (arg)
1444       (sb!c::specifier-type
1445        `(complex ,(or (numeric-type-format arg) 'float))))
1446     #'cis))
1447
1448 ) ; PROGN
1449 \f
1450 ;;;; TRUNCATE, FLOOR, CEILING, and ROUND
1451
1452 (macrolet ((define-frobs (fun ufun)
1453              `(progn
1454                 (defknown ,ufun (real) integer (movable foldable flushable))
1455                 (deftransform ,fun ((x &optional by)
1456                                     (* &optional
1457                                        (constant-arg (member 1))))
1458                   '(let ((res (,ufun x)))
1459                      (values res (- x res)))))))
1460   (define-frobs truncate %unary-truncate)
1461   (define-frobs round %unary-round))
1462
1463 ;;; Convert (TRUNCATE x y) to the obvious implementation.  We only want
1464 ;;; this when under certain conditions and let the generic TRUNCATE
1465 ;;; handle the rest.  (Note: if Y = 1, the divide and multiply by Y
1466 ;;; should be removed by other DEFTRANSFORMs.)
1467 (deftransform truncate ((x &optional y)
1468                         (float &optional (or float integer)))
1469   (let ((defaulted-y (if y 'y 1)))
1470     `(let ((res (%unary-truncate (/ x ,defaulted-y))))
1471        (values res (- x (* ,defaulted-y res))))))
1472
1473 (deftransform floor ((number &optional divisor)
1474                      (float &optional (or integer float)))
1475   (let ((defaulted-divisor (if divisor 'divisor 1)))
1476     `(multiple-value-bind (tru rem) (truncate number ,defaulted-divisor)
1477        (if (and (not (zerop rem))
1478                 (if (minusp ,defaulted-divisor)
1479                     (plusp number)
1480                     (minusp number)))
1481            (values (1- tru) (+ rem ,defaulted-divisor))
1482            (values tru rem)))))
1483
1484 (deftransform ceiling ((number &optional divisor)
1485                        (float &optional (or integer float)))
1486   (let ((defaulted-divisor (if divisor 'divisor 1)))
1487     `(multiple-value-bind (tru rem) (truncate number ,defaulted-divisor)
1488        (if (and (not (zerop rem))
1489                 (if (minusp ,defaulted-divisor)
1490                     (minusp number)
1491                     (plusp number)))
1492            (values (1+ tru) (- rem ,defaulted-divisor))
1493            (values tru rem)))))
1494
1495 (defknown %unary-ftruncate (real) float (movable foldable flushable))
1496 (defknown %unary-ftruncate/single (single-float) single-float
1497   (movable foldable flushable))
1498 (defknown %unary-ftruncate/double (double-float) double-float
1499   (movable foldable flushable))
1500
1501 (defun %unary-ftruncate/single (x)
1502   (declare (type single-float x))
1503   (declare (optimize speed (safety 0)))
1504   (let* ((bits (single-float-bits x))
1505          (exp (ldb sb!vm:single-float-exponent-byte bits))
1506          (biased (the single-float-exponent
1507                    (- exp sb!vm:single-float-bias))))
1508     (declare (type (signed-byte 32) bits))
1509     (cond
1510       ((= exp sb!vm:single-float-normal-exponent-max) x)
1511       ((<= biased 0) (* x 0f0))
1512       ((>= biased (float-digits x)) x)
1513       (t
1514        (let ((frac-bits (- (float-digits x) biased)))
1515          (setf bits (logandc2 bits (- (ash 1 frac-bits) 1)))
1516          (make-single-float bits))))))
1517
1518 (defun %unary-ftruncate/double (x)
1519   (declare (type double-float x))
1520   (declare (optimize speed (safety 0)))
1521   (let* ((high (double-float-high-bits x))
1522          (low (double-float-low-bits x))
1523          (exp (ldb sb!vm:double-float-exponent-byte high))
1524          (biased (the double-float-exponent
1525                    (- exp sb!vm:double-float-bias))))
1526     (declare (type (signed-byte 32) high)
1527              (type (unsigned-byte 32) low))
1528     (cond
1529       ((= exp sb!vm:double-float-normal-exponent-max) x)
1530       ((<= biased 0) (* x 0d0))
1531       ((>= biased (float-digits x)) x)
1532       (t
1533        (let ((frac-bits (- (float-digits x) biased)))
1534          (cond ((< frac-bits 32)
1535                 (setf low (logandc2 low (- (ash 1 frac-bits) 1))))
1536                (t
1537                 (setf low 0)
1538                 (setf high (logandc2 high (- (ash 1 (- frac-bits 32)) 1)))))
1539          (make-double-float high low))))))
1540
1541 (macrolet
1542     ((def (float-type fun)
1543          `(deftransform %unary-ftruncate ((x) (,float-type))
1544             '(,fun x))))
1545   (def single-float %unary-ftruncate/single)
1546   (def double-float %unary-ftruncate/double))