0.6.12.3:
[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 flushable))
19 (defknown %double-float (real) double-float (movable foldable flushable))
20
21 (deftransform float ((n &optional f) (* &optional single-float) * :when :both)
22   '(%single-float n))
23
24 (deftransform float ((n f) (* double-float) * :when :both)
25   '(%double-float n))
26
27 (deftransform %single-float ((n) (single-float) * :when :both)
28   'n)
29
30 (deftransform %double-float ((n) (double-float) * :when :both)
31   'n)
32
33 ;;; not strictly float functions, but primarily useful on floats:
34 (macrolet ((frob (fun ufun)
35              `(progn
36                 (defknown ,ufun (real) integer (movable foldable flushable))
37                 (deftransform ,fun ((x &optional by)
38                                     (* &optional
39                                        (constant-argument (member 1))))
40                   '(let ((res (,ufun x)))
41                      (values res (- x res)))))))
42   (frob truncate %unary-truncate)
43   (frob round %unary-round))
44
45 ;;; RANDOM
46 (macrolet ((frob (fun type)
47              `(deftransform random ((num &optional state)
48                                     (,type &optional *) *
49                                     :when :both)
50                 "Use inline float operations."
51                 '(,fun num (or state *random-state*)))))
52   (frob %random-single-float single-float)
53   (frob %random-double-float double-float))
54
55 ;;; Mersenne Twister RNG
56 ;;;
57 ;;; FIXME: It's unpleasant to have RANDOM functionality scattered
58 ;;; through the code this way. It would be nice to move this into the
59 ;;; same file as the other RANDOM definitions.
60 (deftransform random ((num &optional state)
61                       ((integer 1 #.(expt 2 32)) &optional *))
62   ;; FIXME: I almost conditionalized this as #!+sb-doc. Find some way
63   ;; of automatically finding #!+sb-doc in proximity to DEFTRANSFORM
64   ;; to let me scan for places that I made this mistake and didn't
65   ;; catch myself.
66   "use inline (UNSIGNED-BYTE 32) operations"
67   (let ((num-high (numeric-type-high (continuation-type num))))
68     (when (null num-high)
69       (give-up-ir1-transform))
70     (cond ((constant-continuation-p num)
71            ;; Check the worst case sum absolute error for the random number
72            ;; expectations.
73            (let ((rem (rem (expt 2 32) num-high)))
74              (unless (< (/ (* 2 rem (- num-high rem)) num-high (expt 2 32))
75                         (expt 2 (- sb!kernel::random-integer-extra-bits)))
76                (give-up-ir1-transform
77                 "The random number expectations are inaccurate."))
78              (if (= num-high (expt 2 32))
79                  '(random-chunk (or state *random-state*))
80                  #!-x86 '(rem (random-chunk (or state *random-state*)) num)
81                  #!+x86
82                  ;; Use multiplication, which is faster.
83                  '(values (sb!bignum::%multiply
84                            (random-chunk (or state *random-state*))
85                            num)))))
86           ((> num-high random-fixnum-max)
87            (give-up-ir1-transform
88             "The range is too large to ensure an accurate result."))
89           #!+x86
90           ((< num-high (expt 2 32))
91            '(values (sb!bignum::%multiply (random-chunk (or state
92                                                             *random-state*))
93                      num)))
94           (t
95            '(rem (random-chunk (or state *random-state*)) num)))))
96 \f
97 ;;;; float accessors
98
99 (defknown make-single-float ((signed-byte 32)) single-float
100   (movable foldable flushable))
101
102 (defknown make-double-float ((signed-byte 32) (unsigned-byte 32)) double-float
103   (movable foldable flushable))
104
105 (defknown single-float-bits (single-float) (signed-byte 32)
106   (movable foldable flushable))
107
108 (defknown double-float-high-bits (double-float) (signed-byte 32)
109   (movable foldable flushable))
110
111 (defknown double-float-low-bits (double-float) (unsigned-byte 32)
112   (movable foldable flushable))
113
114 (deftransform float-sign ((float &optional float2)
115                           (single-float &optional single-float) *)
116   (if float2
117       (let ((temp (gensym)))
118         `(let ((,temp (abs float2)))
119           (if (minusp (single-float-bits float)) (- ,temp) ,temp)))
120       '(if (minusp (single-float-bits float)) -1f0 1f0)))
121
122 (deftransform float-sign ((float &optional float2)
123                           (double-float &optional double-float) *)
124   (if float2
125       (let ((temp (gensym)))
126         `(let ((,temp (abs float2)))
127           (if (minusp (double-float-high-bits float)) (- ,temp) ,temp)))
128       '(if (minusp (double-float-high-bits float)) -1d0 1d0)))
129 \f
130 ;;;; DECODE-FLOAT, INTEGER-DECODE-FLOAT, and SCALE-FLOAT
131
132 (defknown decode-single-float (single-float)
133   (values single-float single-float-exponent (single-float -1f0 1f0))
134   (movable foldable flushable))
135
136 (defknown decode-double-float (double-float)
137   (values double-float double-float-exponent (double-float -1d0 1d0))
138   (movable foldable flushable))
139
140 (defknown integer-decode-single-float (single-float)
141   (values single-float-significand single-float-int-exponent (integer -1 1))
142   (movable foldable flushable))
143
144 (defknown integer-decode-double-float (double-float)
145   (values double-float-significand double-float-int-exponent (integer -1 1))
146   (movable foldable flushable))
147
148 (defknown scale-single-float (single-float fixnum) single-float
149   (movable foldable flushable))
150
151 (defknown scale-double-float (double-float fixnum) double-float
152   (movable foldable flushable))
153
154 (deftransform decode-float ((x) (single-float) * :when :both)
155   '(decode-single-float x))
156
157 (deftransform decode-float ((x) (double-float) * :when :both)
158   '(decode-double-float x))
159
160 (deftransform integer-decode-float ((x) (single-float) * :when :both)
161   '(integer-decode-single-float x))
162
163 (deftransform integer-decode-float ((x) (double-float) * :when :both)
164   '(integer-decode-double-float x))
165
166 (deftransform scale-float ((f ex) (single-float *) * :when :both)
167   (if (and #!+x86 t #!-x86 nil
168            (csubtypep (continuation-type ex)
169                       (specifier-type '(signed-byte 32)))
170            (not (byte-compiling)))
171       '(coerce (%scalbn (coerce f 'double-float) ex) 'single-float)
172       '(scale-single-float f ex)))
173
174 (deftransform scale-float ((f ex) (double-float *) * :when :both)
175   (if (and #!+x86 t #!-x86 nil
176            (csubtypep (continuation-type ex)
177                       (specifier-type '(signed-byte 32))))
178       '(%scalbn f ex)
179       '(scale-double-float f ex)))
180
181 ;;; optimizers for SCALE-FLOAT. If the float has bounds, new bounds
182 ;;; are computed for the result, if possible.
183 #!+sb-propagate-float-type
184 (progn
185
186 (defun scale-float-derive-type-aux (f ex same-arg)
187   (declare (ignore same-arg))
188   (flet ((scale-bound (x n)
189            ;; We need to be a bit careful here and catch any overflows
190            ;; that might occur. We can ignore underflows which become
191            ;; zeros.
192            (set-bound
193             (handler-case
194              (scale-float (type-bound-number x) n)
195              (floating-point-overflow ()
196                 nil))
197             (consp x))))
198     (when (and (numeric-type-p f) (numeric-type-p ex))
199       (let ((f-lo (numeric-type-low f))
200             (f-hi (numeric-type-high f))
201             (ex-lo (numeric-type-low ex))
202             (ex-hi (numeric-type-high ex))
203             (new-lo nil)
204             (new-hi nil))
205         (when (and f-hi ex-hi)
206           (setf new-hi (scale-bound f-hi ex-hi)))
207         (when (and f-lo ex-lo)
208           (setf new-lo (scale-bound f-lo ex-lo)))
209         (make-numeric-type :class (numeric-type-class f)
210                            :format (numeric-type-format f)
211                            :complexp :real
212                            :low new-lo
213                            :high new-hi)))))
214 (defoptimizer (scale-single-float derive-type) ((f ex))
215   (two-arg-derive-type f ex #'scale-float-derive-type-aux
216                        #'scale-single-float t))
217 (defoptimizer (scale-double-float derive-type) ((f ex))
218   (two-arg-derive-type f ex #'scale-float-derive-type-aux
219                        #'scale-double-float t))
220
221 ;;; DEFOPTIMIZERs for %SINGLE-FLOAT and %DOUBLE-FLOAT. This makes the
222 ;;; FLOAT function return the correct ranges if the input has some
223 ;;; defined range. Quite useful if we want to convert some type of
224 ;;; bounded integer into a float.
225 (macrolet
226     ((frob (fun type)
227        (let ((aux-name (symbolicate fun "-DERIVE-TYPE-AUX")))
228          `(progn
229            (defun ,aux-name (num)
230              ;; When converting a number to a float, the limits are
231              ;; the same.
232              (let* ((lo (bound-func #'(lambda (x)
233                                         (coerce x ',type))
234                                     (numeric-type-low num)))
235                     (hi (bound-func #'(lambda (x)
236                                         (coerce x ',type))
237                                     (numeric-type-high num))))
238                (specifier-type `(,',type ,(or lo '*) ,(or hi '*)))))
239
240            (defoptimizer (,fun derive-type) ((num))
241              (one-arg-derive-type num #',aux-name #',fun))))))
242   (frob %single-float single-float)
243   (frob %double-float double-float))
244 ) ; PROGN 
245 \f
246 ;;;; float contagion
247
248 ;;; Do some stuff to recognize when the loser is doing mixed float and
249 ;;; rational arithmetic, or different float types, and fix it up. If
250 ;;; we don't, he won't even get so much as an efficency note.
251 (deftransform float-contagion-arg1 ((x y) * * :defun-only t :node node)
252   `(,(continuation-function-name (basic-combination-fun node))
253     (float x y) y))
254 (deftransform float-contagion-arg2 ((x y) * * :defun-only t :node node)
255   `(,(continuation-function-name (basic-combination-fun node))
256     x (float y x)))
257
258 (dolist (x '(+ * / -))
259   (%deftransform x '(function (rational float) *) #'float-contagion-arg1)
260   (%deftransform x '(function (float rational) *) #'float-contagion-arg2))
261
262 (dolist (x '(= < > + * / -))
263   (%deftransform x '(function (single-float double-float) *)
264                  #'float-contagion-arg1)
265   (%deftransform x '(function (double-float single-float) *)
266                  #'float-contagion-arg2))
267
268 ;;; Prevent ZEROP, PLUSP, and MINUSP from losing horribly. We can't in
269 ;;; general float rational args to comparison, since Common Lisp
270 ;;; semantics says we are supposed to compare as rationals, but we can
271 ;;; do it for any rational that has a precise representation as a
272 ;;; float (such as 0).
273 (macrolet ((frob (op)
274              `(deftransform ,op ((x y) (float rational) * :when :both)
275                 "open-code FLOAT to RATIONAL comparison"
276                 (unless (constant-continuation-p y)
277                   (give-up-ir1-transform
278                    "The RATIONAL value isn't known at compile time."))
279                 (let ((val (continuation-value y)))
280                   (unless (eql (rational (float val)) val)
281                     (give-up-ir1-transform
282                      "~S doesn't have a precise float representation."
283                      val)))
284                 `(,',op x (float y x)))))
285   (frob <)
286   (frob >)
287   (frob =))
288 \f
289 ;;;; irrational derive-type methods
290
291 ;;; Derive the result to be float for argument types in the
292 ;;; appropriate domain.
293 #!-sb-propagate-fun-type
294 (dolist (stuff '((asin (real -1.0 1.0))
295                  (acos (real -1.0 1.0))
296                  (acosh (real 1.0))
297                  (atanh (real -1.0 1.0))
298                  (sqrt (real 0.0))))
299   (destructuring-bind (name type) stuff
300     (let ((type (specifier-type type)))
301       (setf (function-info-derive-type (function-info-or-lose name))
302             (lambda (call)
303               (declare (type combination call))
304               (when (csubtypep (continuation-type
305                                 (first (combination-args call)))
306                                type)
307                 (specifier-type 'float)))))))
308
309 #!-sb-propagate-fun-type
310 (defoptimizer (log derive-type) ((x &optional y))
311   (when (and (csubtypep (continuation-type x)
312                         (specifier-type '(real 0.0)))
313              (or (null y)
314                  (csubtypep (continuation-type y)
315                             (specifier-type '(real 0.0)))))
316     (specifier-type 'float)))
317 \f
318 ;;;; irrational transforms
319
320 (defknown (%tan %sinh %asinh %atanh %log %logb %log10 %tan-quick)
321           (double-float) double-float
322   (movable foldable flushable))
323
324 (defknown (%sin %cos %tanh %sin-quick %cos-quick)
325   (double-float) (double-float -1.0d0 1.0d0)
326   (movable foldable flushable))
327
328 (defknown (%asin %atan)
329   (double-float) (double-float #.(- (/ pi 2)) #.(/ pi 2))
330   (movable foldable flushable))
331
332 (defknown (%acos)
333   (double-float) (double-float 0.0d0 #.pi)
334   (movable foldable flushable))
335
336 (defknown (%cosh)
337   (double-float) (double-float 1.0d0)
338   (movable foldable flushable))
339
340 (defknown (%acosh %exp %sqrt)
341   (double-float) (double-float 0.0d0)
342   (movable foldable flushable))
343
344 (defknown %expm1
345   (double-float) (double-float -1d0)
346   (movable foldable flushable))
347
348 (defknown (%hypot)
349   (double-float double-float) (double-float 0d0)
350   (movable foldable flushable))
351
352 (defknown (%pow)
353   (double-float double-float) double-float
354   (movable foldable flushable))
355
356 (defknown (%atan2)
357   (double-float double-float) (double-float #.(- pi) #.pi)
358   (movable foldable flushable))
359
360 (defknown (%scalb)
361   (double-float double-float) double-float
362   (movable foldable flushable))
363
364 (defknown (%scalbn)
365   (double-float (signed-byte 32)) double-float
366   (movable foldable flushable))
367
368 (defknown (%log1p)
369   (double-float) double-float
370   (movable foldable flushable))
371
372 (dolist (stuff '((exp %exp *)
373                  (log %log float)
374                  (sqrt %sqrt float)
375                  (asin %asin float)
376                  (acos %acos float)
377                  (atan %atan *)
378                  (sinh %sinh *)
379                  (cosh %cosh *)
380                  (tanh %tanh *)
381                  (asinh %asinh *)
382                  (acosh %acosh float)
383                  (atanh %atanh float)))
384   (destructuring-bind (name prim rtype) stuff
385     (deftransform name ((x) '(single-float) rtype :eval-name t)
386       `(coerce (,prim (coerce x 'double-float)) 'single-float))
387     (deftransform name ((x) '(double-float) rtype :eval-name t :when :both)
388       `(,prim x))))
389
390 ;;; The argument range is limited on the x86 FP trig. functions. A
391 ;;; post-test can detect a failure (and load a suitable result), but
392 ;;; this test is avoided if possible.
393 (dolist (stuff '((sin %sin %sin-quick)
394                  (cos %cos %cos-quick)
395                  (tan %tan %tan-quick)))
396   (destructuring-bind (name prim prim-quick) stuff
397     (declare (ignorable prim-quick))
398     (deftransform name ((x) '(single-float) '* :eval-name t)
399       #!+x86 (cond ((csubtypep (continuation-type x)
400                                (specifier-type '(single-float
401                                                  (#.(- (expt 2f0 64)))
402                                                  (#.(expt 2f0 64)))))
403                     `(coerce (,prim-quick (coerce x 'double-float))
404                     'single-float))
405                    (t
406                     (compiler-note
407                     "unable to avoid inline argument range check~@
408                       because the argument range (~S) was not within 2^64"
409                     (type-specifier (continuation-type x)))
410                     `(coerce (,prim (coerce x 'double-float)) 'single-float)))
411       #!-x86 `(coerce (,prim (coerce x 'double-float)) 'single-float))
412     (deftransform name ((x) '(double-float) '* :eval-name t :when :both)
413       #!+x86 (cond ((csubtypep (continuation-type x)
414                                (specifier-type '(double-float
415                                                  (#.(- (expt 2d0 64)))
416                                                  (#.(expt 2d0 64)))))
417                     `(,prim-quick x))
418                    (t
419                     (compiler-note
420                     "unable to avoid inline argument range check~@
421                    because the argument range (~S) was not within 2^64"
422                     (type-specifier (continuation-type x)))
423                     `(,prim x)))
424       #!-x86 `(,prim x))))
425
426 (deftransform atan ((x y) (single-float single-float) *)
427   `(coerce (%atan2 (coerce x 'double-float) (coerce y 'double-float))
428     'single-float))
429 (deftransform atan ((x y) (double-float double-float) * :when :both)
430   `(%atan2 x y))
431
432 (deftransform expt ((x y) ((single-float 0f0) single-float) *)
433   `(coerce (%pow (coerce x 'double-float) (coerce y 'double-float))
434     'single-float))
435 (deftransform expt ((x y) ((double-float 0d0) double-float) * :when :both)
436   `(%pow x y))
437 (deftransform expt ((x y) ((single-float 0f0) (signed-byte 32)) *)
438   `(coerce (%pow (coerce x 'double-float) (coerce y 'double-float))
439     'single-float))
440 (deftransform expt ((x y) ((double-float 0d0) (signed-byte 32)) * :when :both)
441   `(%pow x (coerce y 'double-float)))
442
443 ;;; ANSI says log with base zero returns zero.
444 (deftransform log ((x y) (float float) float)
445   '(if (zerop y) y (/ (log x) (log y))))
446 \f
447 ;;; Handle some simple transformations.
448
449 (deftransform abs ((x) ((complex double-float)) double-float :when :both)
450   '(%hypot (realpart x) (imagpart x)))
451
452 (deftransform abs ((x) ((complex single-float)) single-float)
453   '(coerce (%hypot (coerce (realpart x) 'double-float)
454                    (coerce (imagpart x) 'double-float))
455           'single-float))
456
457 (deftransform phase ((x) ((complex double-float)) double-float :when :both)
458   '(%atan2 (imagpart x) (realpart x)))
459
460 (deftransform phase ((x) ((complex single-float)) single-float)
461   '(coerce (%atan2 (coerce (imagpart x) 'double-float)
462                    (coerce (realpart x) 'double-float))
463           'single-float))
464
465 (deftransform phase ((x) ((float)) float :when :both)
466   '(if (minusp (float-sign x))
467        (float pi x)
468        (float 0 x)))
469
470 ;; #!+(or propagate-float-type propagate-fun-type)
471 (progn
472
473 ;;; The number is of type REAL.
474 #!-sb-fluid (declaim (inline numeric-type-real-p))
475 (defun numeric-type-real-p (type)
476   (and (numeric-type-p type)
477        (eq (numeric-type-complexp type) :real)))
478
479 ;;; Coerce a numeric type bound to the given type while handling
480 ;;; exclusive bounds.
481 (defun coerce-numeric-bound (bound type)
482   (when bound
483     (if (consp bound)
484         (list (coerce (car bound) type))
485         (coerce bound type))))
486
487 ) ; PROGN
488
489 #!+sb-propagate-fun-type
490 (progn
491
492 ;;;; optimizers for elementary functions
493 ;;;;
494 ;;;; These optimizers compute the output range of the elementary
495 ;;;; function, based on the domain of the input.
496
497 ;;; Generate a specifier for a complex type specialized to the same
498 ;;; type as the argument.
499 (defun complex-float-type (arg)
500   (declare (type numeric-type arg))
501   (let* ((format (case (numeric-type-class arg)
502                    ((integer rational) 'single-float)
503                    (t (numeric-type-format arg))))
504          (float-type (or format 'float)))
505     (specifier-type `(complex ,float-type))))
506
507 ;;; Compute a specifier like '(OR FLOAT (COMPLEX FLOAT)), except float
508 ;;; should be the right kind of float. Allow bounds for the float
509 ;;; part too.
510 (defun float-or-complex-float-type (arg &optional lo hi)
511   (declare (type numeric-type arg))
512   (let* ((format (case (numeric-type-class arg)
513                    ((integer rational) 'single-float)
514                    (t (numeric-type-format arg))))
515          (float-type (or format 'float))
516          (lo (coerce-numeric-bound lo float-type))
517          (hi (coerce-numeric-bound hi float-type)))
518     (specifier-type `(or (,float-type ,(or lo '*) ,(or hi '*))
519                          (complex ,float-type)))))
520
521 ;;; Test whether the numeric-type ARG is within in domain specified by
522 ;;; DOMAIN-LOW and DOMAIN-HIGH, consider negative and positive zero to
523 ;;; be distinct as for the :NEGATIVE-ZERO-IS-NOT-ZERO feature. With
524 ;;; the :NEGATIVE-ZERO-IS-NOT-ZERO feature this could be handled by
525 ;;; the numeric subtype code in type.lisp.
526 (defun domain-subtypep (arg domain-low domain-high)
527   (declare (type numeric-type arg)
528            (type (or real null) domain-low domain-high))
529   (let* ((arg-lo (numeric-type-low arg))
530          (arg-lo-val (type-bound-number arg-lo))
531          (arg-hi (numeric-type-high arg))
532          (arg-hi-val (type-bound-number arg-hi)))
533     ;; Check that the ARG bounds are correctly canonicalized.
534     (when (and arg-lo (floatp arg-lo-val) (zerop arg-lo-val) (consp arg-lo)
535                (minusp (float-sign arg-lo-val)))
536       (compiler-note "float zero bound ~S not correctly canonicalized?" arg-lo)
537       (setq arg-lo '(0l0) arg-lo-val 0l0))
538     (when (and arg-hi (zerop arg-hi-val) (floatp arg-hi-val) (consp arg-hi)
539                (plusp (float-sign arg-hi-val)))
540       (compiler-note "float zero bound ~S not correctly canonicalized?" arg-hi)
541       (setq arg-hi '(-0l0) arg-hi-val -0l0))
542     (and (or (null domain-low)
543              (and arg-lo (>= arg-lo-val domain-low)
544                   (not (and (zerop domain-low) (floatp domain-low)
545                             (plusp (float-sign domain-low))
546                             (zerop arg-lo-val) (floatp arg-lo-val)
547                             (if (consp arg-lo)
548                                 (plusp (float-sign arg-lo-val))
549                                 (minusp (float-sign arg-lo-val)))))))
550          (or (null domain-high)
551              (and arg-hi (<= arg-hi-val domain-high)
552                   (not (and (zerop domain-high) (floatp domain-high)
553                             (minusp (float-sign domain-high))
554                             (zerop arg-hi-val) (floatp arg-hi-val)
555                             (if (consp arg-hi)
556                                 (minusp (float-sign arg-hi-val))
557                                 (plusp (float-sign arg-hi-val))))))))))
558
559 ;;; Handle monotonic functions of a single variable whose domain is
560 ;;; possibly part of the real line. ARG is the variable, FCN is the
561 ;;; function, and DOMAIN is a specifier that gives the (real) domain
562 ;;; of the function. If ARG is a subset of the DOMAIN, we compute the
563 ;;; bounds directly. Otherwise, we compute the bounds for the
564 ;;; intersection between ARG and DOMAIN, and then append a complex
565 ;;; result, which occurs for the parts of ARG not in the DOMAIN.
566 ;;;
567 ;;; Negative and positive zero are considered distinct within
568 ;;; DOMAIN-LOW and DOMAIN-HIGH, as for the :negative-zero-is-not-zero
569 ;;; feature.
570 ;;;
571 ;;; DEFAULT-LOW and DEFAULT-HIGH are the lower and upper bounds if we
572 ;;; can't compute the bounds using FCN.
573 (defun elfun-derive-type-simple (arg fcn domain-low domain-high
574                                      default-low default-high
575                                      &optional (increasingp t))
576   (declare (type (or null real) domain-low domain-high))
577   (etypecase arg
578     (numeric-type
579      (cond ((eq (numeric-type-complexp arg) :complex)
580             (make-numeric-type :class (numeric-type-class arg)
581                                :format (numeric-type-format arg)
582                                :complexp :complex))
583            ((numeric-type-real-p arg)
584             ;; The argument is real, so let's find the intersection
585             ;; between the argument and the domain of the function.
586             ;; We compute the bounds on the intersection, and for
587             ;; everything else, we return a complex number of the
588             ;; appropriate type.
589             (multiple-value-bind (intersection difference)
590                 (interval-intersection/difference (numeric-type->interval arg)
591                                                   (make-interval
592                                                    :low domain-low
593                                                    :high domain-high))
594               (cond
595                 (intersection
596                  ;; Process the intersection.
597                  (let* ((low (interval-low intersection))
598                         (high (interval-high intersection))
599                         (res-lo (or (bound-func fcn (if increasingp low high))
600                                     default-low))
601                         (res-hi (or (bound-func fcn (if increasingp high low))
602                                     default-high))
603                         (format (case (numeric-type-class arg)
604                                   ((integer rational) 'single-float)
605                                   (t (numeric-type-format arg))))
606                         (bound-type (or format 'float))
607                         (result-type
608                          (make-numeric-type
609                           :class 'float
610                           :format format
611                           :low (coerce-numeric-bound res-lo bound-type)
612                           :high (coerce-numeric-bound res-hi bound-type))))
613                    ;; If the ARG is a subset of the domain, we don't
614                    ;; have to worry about the difference, because that
615                    ;; can't occur.
616                    (if (or (null difference)
617                            ;; Check whether the arg is within the domain.
618                            (domain-subtypep arg domain-low domain-high))
619                        result-type
620                        (list result-type
621                              (specifier-type `(complex ,bound-type))))))
622                 (t
623                  ;; No intersection so the result must be purely complex.
624                  (complex-float-type arg)))))
625            (t
626             (float-or-complex-float-type arg default-low default-high))))))
627
628 (macrolet
629     ((frob (name domain-low domain-high def-low-bnd def-high-bnd
630                  &key (increasingp t))
631        (let ((num (gensym)))
632          `(defoptimizer (,name derive-type) ((,num))
633            (one-arg-derive-type
634             ,num
635             #'(lambda (arg)
636                 (elfun-derive-type-simple arg #',name
637                                           ,domain-low ,domain-high
638                                           ,def-low-bnd ,def-high-bnd
639                                           ,increasingp))
640             #',name)))))
641   ;; These functions are easy because they are defined for the whole
642   ;; real line.
643   (frob exp nil nil 0 nil)
644   (frob sinh nil nil nil nil)
645   (frob tanh nil nil -1 1)
646   (frob asinh nil nil nil nil)
647
648   ;; These functions are only defined for part of the real line. The
649   ;; condition selects the desired part of the line.
650   (frob asin -1d0 1d0 (- (/ pi 2)) (/ pi 2))
651   ;; Acos is monotonic decreasing, so we need to swap the function
652   ;; values at the lower and upper bounds of the input domain.
653   (frob acos -1d0 1d0 0 pi :increasingp nil)
654   (frob acosh 1d0 nil nil nil)
655   (frob atanh -1d0 1d0 -1 1)
656   ;; Kahan says that (sqrt -0.0) is -0.0, so use a specifier that
657   ;; includes -0.0.
658   (frob sqrt -0d0 nil 0 nil))
659
660 ;;; Compute bounds for (expt x y). This should be easy since (expt x
661 ;;; y) = (exp (* y (log x))). However, computations done this way
662 ;;; have too much roundoff. Thus we have to do it the hard way.
663 (defun safe-expt (x y)
664   (handler-case
665       (expt x y)
666     (error ()
667       nil)))
668
669 ;;; Handle the case when x >= 1.
670 (defun interval-expt-> (x y)
671   (case (sb!c::interval-range-info y 0d0)
672     ('+
673      ;; Y is positive and log X >= 0. The range of exp(y * log(x)) is
674      ;; obviously non-negative. We just have to be careful for
675      ;; infinite bounds (given by nil).
676      (let ((lo (safe-expt (type-bound-number (sb!c::interval-low x))
677                           (type-bound-number (sb!c::interval-low y))))
678            (hi (safe-expt (type-bound-number (sb!c::interval-high x))
679                           (type-bound-number (sb!c::interval-high y)))))
680        (list (sb!c::make-interval :low (or lo 1) :high hi))))
681     ('-
682      ;; Y is negative and log x >= 0. The range of exp(y * log(x)) is
683      ;; obviously [0, 1]. However, underflow (nil) means 0 is the
684      ;; result.
685      (let ((lo (safe-expt (type-bound-number (sb!c::interval-high x))
686                           (type-bound-number (sb!c::interval-low y))))
687            (hi (safe-expt (type-bound-number (sb!c::interval-low x))
688                           (type-bound-number (sb!c::interval-high y)))))
689        (list (sb!c::make-interval :low (or lo 0) :high (or hi 1)))))
690     (t
691      ;; Split the interval in half.
692      (destructuring-bind (y- y+)
693          (sb!c::interval-split 0 y t)
694        (list (interval-expt-> x y-)
695              (interval-expt-> x y+))))))
696
697 ;;; Handle the case when x <= 1
698 (defun interval-expt-< (x y)
699   (case (sb!c::interval-range-info x 0d0)
700     ('+
701      ;; The case of 0 <= x <= 1 is easy
702      (case (sb!c::interval-range-info y)
703        ('+
704         ;; Y is positive and log X <= 0. The range of exp(y * log(x)) is
705         ;; obviously [0, 1]. We just have to be careful for infinite bounds
706         ;; (given by nil).
707         (let ((lo (safe-expt (type-bound-number (sb!c::interval-low x))
708                              (type-bound-number (sb!c::interval-high y))))
709               (hi (safe-expt (type-bound-number (sb!c::interval-high x))
710                              (type-bound-number (sb!c::interval-low y)))))
711           (list (sb!c::make-interval :low (or lo 0) :high (or hi 1)))))
712        ('-
713         ;; Y is negative and log x <= 0. The range of exp(y * log(x)) is
714         ;; obviously [1, inf].
715         (let ((hi (safe-expt (type-bound-number (sb!c::interval-low x))
716                              (type-bound-number (sb!c::interval-low y))))
717               (lo (safe-expt (type-bound-number (sb!c::interval-high x))
718                              (type-bound-number (sb!c::interval-high y)))))
719           (list (sb!c::make-interval :low (or lo 1) :high hi))))
720        (t
721         ;; Split the interval in half
722         (destructuring-bind (y- y+)
723             (sb!c::interval-split 0 y t)
724           (list (interval-expt-< x y-)
725                 (interval-expt-< x y+))))))
726     ('-
727      ;; The case where x <= 0. Y MUST be an INTEGER for this to work!
728      ;; The calling function must insure this! For now we'll just
729      ;; return the appropriate unbounded float type.
730      (list (sb!c::make-interval :low nil :high nil)))
731     (t
732      (destructuring-bind (neg pos)
733          (interval-split 0 x t t)
734        (list (interval-expt-< neg y)
735              (interval-expt-< pos y))))))
736
737 ;;; Compute bounds for (expt x y).
738 (defun interval-expt (x y)
739   (case (interval-range-info x 1)
740     ('+
741      ;; X >= 1
742          (interval-expt-> x y))
743     ('-
744      ;; X <= 1
745      (interval-expt-< x y))
746     (t
747      (destructuring-bind (left right)
748          (interval-split 1 x t t)
749        (list (interval-expt left y)
750              (interval-expt right y))))))
751
752 (defun fixup-interval-expt (bnd x-int y-int x-type y-type)
753   (declare (ignore x-int))
754   ;; Figure out what the return type should be, given the argument
755   ;; types and bounds and the result type and bounds.
756   (cond ((csubtypep x-type (specifier-type 'integer))
757          ;; an integer to some power
758          (case (numeric-type-class y-type)
759            (integer
760             ;; Positive integer to an integer power is either an
761             ;; integer or a rational.
762             (let ((lo (or (interval-low bnd) '*))
763                   (hi (or (interval-high bnd) '*)))
764               (if (and (interval-low y-int)
765                        (>= (type-bound-number (interval-low y-int)) 0))
766                   (specifier-type `(integer ,lo ,hi))
767                   (specifier-type `(rational ,lo ,hi)))))
768            (rational
769             ;; Positive integer to rational power is either a rational
770             ;; or a single-float.
771             (let* ((lo (interval-low bnd))
772                    (hi (interval-high bnd))
773                    (int-lo (if lo
774                                (floor (type-bound-number lo))
775                                '*))
776                    (int-hi (if hi
777                                (ceiling (type-bound-number hi))
778                                '*))
779                    (f-lo (if lo
780                              (bound-func #'float lo)
781                              '*))
782                    (f-hi (if hi
783                              (bound-func #'float hi)
784                              '*)))
785               (specifier-type `(or (rational ,int-lo ,int-hi)
786                                 (single-float ,f-lo, f-hi)))))
787            (float
788             ;; A positive integer to a float power is a float.
789             (modified-numeric-type y-type
790                                    :low (interval-low bnd)
791                                    :high (interval-high bnd)))
792            (t
793             ;; A positive integer to a number is a number (for now).
794             (specifier-type 'number))))
795         ((csubtypep x-type (specifier-type 'rational))
796          ;; a rational to some power
797          (case (numeric-type-class y-type)
798            (integer
799             ;; A positive rational to an integer power is always a rational.
800             (specifier-type `(rational ,(or (interval-low bnd) '*)
801                                        ,(or (interval-high bnd) '*))))
802            (rational
803             ;; A positive rational to rational power is either a rational
804             ;; or a single-float.
805             (let* ((lo (interval-low bnd))
806                    (hi (interval-high bnd))
807                    (int-lo (if lo
808                                (floor (type-bound-number lo))
809                                '*))
810                    (int-hi (if hi
811                                (ceiling (type-bound-number hi))
812                                '*))
813                    (f-lo (if lo
814                              (bound-func #'float lo)
815                              '*))
816                    (f-hi (if hi
817                              (bound-func #'float hi)
818                              '*)))
819               (specifier-type `(or (rational ,int-lo ,int-hi)
820                                 (single-float ,f-lo, f-hi)))))
821            (float
822             ;; A positive rational to a float power is a float.
823             (modified-numeric-type y-type
824                                    :low (interval-low bnd)
825                                    :high (interval-high bnd)))
826            (t
827             ;; A positive rational to a number is a number (for now).
828             (specifier-type 'number))))
829         ((csubtypep x-type (specifier-type 'float))
830          ;; a float to some power
831          (case (numeric-type-class y-type)
832            ((or integer rational)
833             ;; A positive float to an integer or rational power is
834             ;; always a float.
835             (make-numeric-type
836              :class 'float
837              :format (numeric-type-format x-type)
838              :low (interval-low bnd)
839              :high (interval-high bnd)))
840            (float
841             ;; A positive float to a float power is a float of the
842             ;; higher type.
843             (make-numeric-type
844              :class 'float
845              :format (float-format-max (numeric-type-format x-type)
846                                        (numeric-type-format y-type))
847              :low (interval-low bnd)
848              :high (interval-high bnd)))
849            (t
850             ;; A positive float to a number is a number (for now)
851             (specifier-type 'number))))
852         (t
853          ;; A number to some power is a number.
854          (specifier-type 'number))))
855
856 (defun merged-interval-expt (x y)
857   (let* ((x-int (numeric-type->interval x))
858          (y-int (numeric-type->interval y)))
859     (mapcar (lambda (type)
860               (fixup-interval-expt type x-int y-int x y))
861             (flatten-list (interval-expt x-int y-int)))))
862
863 (defun expt-derive-type-aux (x y same-arg)
864   (declare (ignore same-arg))
865   (cond ((or (not (numeric-type-real-p x))
866              (not (numeric-type-real-p y)))
867          ;; Use numeric contagion if either is not real.
868          (numeric-contagion x y))
869         ((csubtypep y (specifier-type 'integer))
870          ;; A real raised to an integer power is well-defined.
871          (merged-interval-expt x y))
872         (t
873          ;; A real raised to a non-integral power can be a float or a
874          ;; complex number.
875          (cond ((or (csubtypep x (specifier-type '(rational 0)))
876                     (csubtypep x (specifier-type '(float (0d0)))))
877                 ;; But a positive real to any power is well-defined.
878                 (merged-interval-expt x y))
879                (t
880                 ;; a real to some power. The result could be a real
881                 ;; or a complex.
882                 (float-or-complex-float-type (numeric-contagion x y)))))))
883
884 (defoptimizer (expt derive-type) ((x y))
885   (two-arg-derive-type x y #'expt-derive-type-aux #'expt))
886
887 ;;; Note we must assume that a type including 0.0 may also include
888 ;;; -0.0 and thus the result may be complex -infinity + i*pi.
889 (defun log-derive-type-aux-1 (x)
890   (elfun-derive-type-simple x #'log 0d0 nil nil nil))
891
892 (defun log-derive-type-aux-2 (x y same-arg)
893   (let ((log-x (log-derive-type-aux-1 x))
894         (log-y (log-derive-type-aux-1 y))
895         (accumulated-list nil))
896     ;; LOG-X or LOG-Y might be union types. We need to run through
897     ;; the union types ourselves because /-DERIVE-TYPE-AUX doesn't.
898     (dolist (x-type (prepare-arg-for-derive-type log-x))
899       (dolist (y-type (prepare-arg-for-derive-type log-y))
900         (push (/-derive-type-aux x-type y-type same-arg) accumulated-list)))
901     (apply #'type-union (flatten-list accumulated-list))))
902
903 (defoptimizer (log derive-type) ((x &optional y))
904   (if y
905       (two-arg-derive-type x y #'log-derive-type-aux-2 #'log)
906       (one-arg-derive-type x #'log-derive-type-aux-1 #'log)))
907
908 (defun atan-derive-type-aux-1 (y)
909   (elfun-derive-type-simple y #'atan nil nil (- (/ pi 2)) (/ pi 2)))
910
911 (defun atan-derive-type-aux-2 (y x same-arg)
912   (declare (ignore same-arg))
913   ;; The hard case with two args. We just return the max bounds.
914   (let ((result-type (numeric-contagion y x)))
915     (cond ((and (numeric-type-real-p x)
916                 (numeric-type-real-p y))
917            (let* (;; FIXME: This expression for FORMAT seems to
918                   ;; appear multiple times, and should be factored out.
919                   (format (case (numeric-type-class result-type)
920                             ((integer rational) 'single-float)
921                             (t (numeric-type-format result-type))))
922                   (bound-format (or format 'float)))
923              (make-numeric-type :class 'float
924                                 :format format
925                                 :complexp :real
926                                 :low (coerce (- pi) bound-format)
927                                 :high (coerce pi bound-format))))
928           (t
929            ;; The result is a float or a complex number
930            (float-or-complex-float-type result-type)))))
931
932 (defoptimizer (atan derive-type) ((y &optional x))
933   (if x
934       (two-arg-derive-type y x #'atan-derive-type-aux-2 #'atan)
935       (one-arg-derive-type y #'atan-derive-type-aux-1 #'atan)))
936
937 (defun cosh-derive-type-aux (x)
938   ;; We note that cosh x = cosh |x| for all real x.
939   (elfun-derive-type-simple
940    (if (numeric-type-real-p x)
941        (abs-derive-type-aux x)
942        x)
943    #'cosh nil nil 0 nil))
944
945 (defoptimizer (cosh derive-type) ((num))
946   (one-arg-derive-type num #'cosh-derive-type-aux #'cosh))
947
948 (defun phase-derive-type-aux (arg)
949   (let* ((format (case (numeric-type-class arg)
950                    ((integer rational) 'single-float)
951                    (t (numeric-type-format arg))))
952          (bound-type (or format 'float)))
953     (cond ((numeric-type-real-p arg)
954            (case (interval-range-info (numeric-type->interval arg) 0.0)
955              ('+
956               ;; The number is positive, so the phase is 0.
957               (make-numeric-type :class 'float
958                                  :format format
959                                  :complexp :real
960                                  :low (coerce 0 bound-type)
961                                  :high (coerce 0 bound-type)))
962              ('-
963               ;; The number is always negative, so the phase is pi.
964               (make-numeric-type :class 'float
965                                  :format format
966                                  :complexp :real
967                                  :low (coerce pi bound-type)
968                                  :high (coerce pi bound-type)))
969              (t
970               ;; We can't tell. The result is 0 or pi. Use a union
971               ;; type for this.
972               (list
973                (make-numeric-type :class 'float
974                                   :format format
975                                   :complexp :real
976                                   :low (coerce 0 bound-type)
977                                   :high (coerce 0 bound-type))
978                (make-numeric-type :class 'float
979                                   :format format
980                                   :complexp :real
981                                   :low (coerce pi bound-type)
982                                   :high (coerce pi bound-type))))))
983           (t
984            ;; We have a complex number. The answer is the range -pi
985            ;; to pi. (-pi is included because we have -0.)
986            (make-numeric-type :class 'float
987                               :format format
988                               :complexp :real
989                               :low (coerce (- pi) bound-type)
990                               :high (coerce pi bound-type))))))
991
992 (defoptimizer (phase derive-type) ((num))
993   (one-arg-derive-type num #'phase-derive-type-aux #'phase))
994
995 ) ; PROGN
996
997 (deftransform realpart ((x) ((complex rational)) *)
998   '(sb!kernel:%realpart x))
999 (deftransform imagpart ((x) ((complex rational)) *)
1000   '(sb!kernel:%imagpart x))
1001
1002 ;;; Make REALPART and IMAGPART return the appropriate types. This
1003 ;;; should help a lot in optimized code.
1004 (defun realpart-derive-type-aux (type)
1005   (let ((class (numeric-type-class type))
1006         (format (numeric-type-format type)))
1007     (cond ((numeric-type-real-p type)
1008            ;; The realpart of a real has the same type and range as
1009            ;; the input.
1010            (make-numeric-type :class class
1011                               :format format
1012                               :complexp :real
1013                               :low (numeric-type-low type)
1014                               :high (numeric-type-high type)))
1015           (t
1016            ;; We have a complex number. The result has the same type
1017            ;; as the real part, except that it's real, not complex,
1018            ;; obviously.
1019            (make-numeric-type :class class
1020                               :format format
1021                               :complexp :real
1022                               :low (numeric-type-low type)
1023                               :high (numeric-type-high type))))))
1024 #!+(or sb-propagate-fun-type sb-propagate-float-type)
1025 (defoptimizer (realpart derive-type) ((num))
1026   (one-arg-derive-type num #'realpart-derive-type-aux #'realpart))
1027 (defun imagpart-derive-type-aux (type)
1028   (let ((class (numeric-type-class type))
1029         (format (numeric-type-format type)))
1030     (cond ((numeric-type-real-p type)
1031            ;; The imagpart of a real has the same type as the input,
1032            ;; except that it's zero.
1033            (let ((bound-format (or format class 'real)))
1034              (make-numeric-type :class class
1035                                 :format format
1036                                 :complexp :real
1037                                 :low (coerce 0 bound-format)
1038                                 :high (coerce 0 bound-format))))
1039           (t
1040            ;; We have a complex number. The result has the same type as
1041            ;; the imaginary part, except that it's real, not complex,
1042            ;; obviously.
1043            (make-numeric-type :class class
1044                               :format format
1045                               :complexp :real
1046                               :low (numeric-type-low type)
1047                               :high (numeric-type-high type))))))
1048 #!+(or sb-propagate-fun-type sb-propagate-float-type)
1049 (defoptimizer (imagpart derive-type) ((num))
1050   (one-arg-derive-type num #'imagpart-derive-type-aux #'imagpart))
1051
1052 (defun complex-derive-type-aux-1 (re-type)
1053   (if (numeric-type-p re-type)
1054       (make-numeric-type :class (numeric-type-class re-type)
1055                          :format (numeric-type-format re-type)
1056                          :complexp (if (csubtypep re-type
1057                                                   (specifier-type 'rational))
1058                                        :real
1059                                        :complex)
1060                          :low (numeric-type-low re-type)
1061                          :high (numeric-type-high re-type))
1062       (specifier-type 'complex)))
1063
1064 (defun complex-derive-type-aux-2 (re-type im-type same-arg)
1065   (declare (ignore same-arg))
1066   (if (and (numeric-type-p re-type)
1067            (numeric-type-p im-type))
1068       ;; Need to check to make sure numeric-contagion returns the
1069       ;; right type for what we want here.
1070
1071       ;; Also, what about rational canonicalization, like (complex 5 0)
1072       ;; is 5?  So, if the result must be complex, we make it so.
1073       ;; If the result might be complex, which happens only if the
1074       ;; arguments are rational, we make it a union type of (or
1075       ;; rational (complex rational)).
1076       (let* ((element-type (numeric-contagion re-type im-type))
1077              (rat-result-p (csubtypep element-type
1078                                       (specifier-type 'rational))))
1079         (if rat-result-p
1080             (type-union element-type
1081                         (specifier-type
1082                          `(complex ,(numeric-type-class element-type))))
1083             (make-numeric-type :class (numeric-type-class element-type)
1084                                :format (numeric-type-format element-type)
1085                                :complexp (if rat-result-p
1086                                              :real
1087                                              :complex))))
1088       (specifier-type 'complex)))
1089
1090 #!+(or sb-propagate-fun-type sb-propagate-float-type)
1091 (defoptimizer (complex derive-type) ((re &optional im))
1092   (if im
1093       (two-arg-derive-type re im #'complex-derive-type-aux-2 #'complex)
1094       (one-arg-derive-type re #'complex-derive-type-aux-1 #'complex)))
1095
1096 ;;; Define some transforms for complex operations. We do this in lieu
1097 ;;; of complex operation VOPs.
1098 (macrolet ((frob (type)
1099              `(progn
1100                ;; negation
1101                (deftransform %negate ((z) ((complex ,type)) *)
1102                  '(complex (%negate (realpart z)) (%negate (imagpart z))))
1103                ;; complex addition and subtraction
1104                (deftransform + ((w z) ((complex ,type) (complex ,type)) *)
1105                  '(complex (+ (realpart w) (realpart z))
1106                            (+ (imagpart w) (imagpart z))))
1107                (deftransform - ((w z) ((complex ,type) (complex ,type)) *)
1108                  '(complex (- (realpart w) (realpart z))
1109                            (- (imagpart w) (imagpart z))))
1110                ;; Add and subtract a complex and a real.
1111                (deftransform + ((w z) ((complex ,type) real) *)
1112                  '(complex (+ (realpart w) z) (imagpart w)))
1113                (deftransform + ((z w) (real (complex ,type)) *)
1114                  '(complex (+ (realpart w) z) (imagpart w)))
1115                ;; Add and subtract a real and a complex number.
1116                (deftransform - ((w z) ((complex ,type) real) *)
1117                  '(complex (- (realpart w) z) (imagpart w)))
1118                (deftransform - ((z w) (real (complex ,type)) *)
1119                  '(complex (- z (realpart w)) (- (imagpart w))))
1120                ;; Multiply and divide two complex numbers.
1121                (deftransform * ((x y) ((complex ,type) (complex ,type)) *)
1122                  '(let* ((rx (realpart x))
1123                          (ix (imagpart x))
1124                          (ry (realpart y))
1125                          (iy (imagpart y)))
1126                     (complex (- (* rx ry) (* ix iy))
1127                              (+ (* rx iy) (* ix ry)))))
1128                (deftransform / ((x y) ((complex ,type) (complex ,type)) *)
1129                  '(let* ((rx (realpart x))
1130                          (ix (imagpart x))
1131                          (ry (realpart y))
1132                          (iy (imagpart y)))
1133                     (if (> (abs ry) (abs iy))
1134                         (let* ((r (/ iy ry))
1135                                (dn (* ry (+ 1 (* r r)))))
1136                           (complex (/ (+ rx (* ix r)) dn)
1137                                    (/ (- ix (* rx r)) dn)))
1138                         (let* ((r (/ ry iy))
1139                                (dn (* iy (+ 1 (* r r)))))
1140                           (complex (/ (+ (* rx r) ix) dn)
1141                                    (/ (- (* ix r) rx) dn))))))
1142                ;; Multiply a complex by a real or vice versa.
1143                (deftransform * ((w z) ((complex ,type) real) *)
1144                  '(complex (* (realpart w) z) (* (imagpart w) z)))
1145                (deftransform * ((z w) (real (complex ,type)) *)
1146                  '(complex (* (realpart w) z) (* (imagpart w) z)))
1147                ;; Divide a complex by a real.
1148                (deftransform / ((w z) ((complex ,type) real) *)
1149                  '(complex (/ (realpart w) z) (/ (imagpart w) z)))
1150                ;; conjugate of complex number
1151                (deftransform conjugate ((z) ((complex ,type)) *)
1152                  '(complex (realpart z) (- (imagpart z))))
1153                ;; CIS
1154                (deftransform cis ((z) ((,type)) *)
1155                  '(complex (cos z) (sin z)))
1156                ;; comparison
1157                (deftransform = ((w z) ((complex ,type) (complex ,type)) *)
1158                  '(and (= (realpart w) (realpart z))
1159                        (= (imagpart w) (imagpart z))))
1160                (deftransform = ((w z) ((complex ,type) real) *)
1161                  '(and (= (realpart w) z) (zerop (imagpart w))))
1162                (deftransform = ((w z) (real (complex ,type)) *)
1163                  '(and (= (realpart z) w) (zerop (imagpart z)))))))
1164
1165   (frob single-float)
1166   (frob double-float))
1167
1168 ;;; Here are simple optimizers for SIN, COS, and TAN. They do not
1169 ;;; produce a minimal range for the result; the result is the widest
1170 ;;; possible answer. This gets around the problem of doing range
1171 ;;; reduction correctly but still provides useful results when the
1172 ;;; inputs are union types.
1173 #!+sb-propagate-fun-type
1174 (progn
1175 (defun trig-derive-type-aux (arg domain fcn
1176                                  &optional def-lo def-hi (increasingp t))
1177   (etypecase arg
1178     (numeric-type
1179      (cond ((eq (numeric-type-complexp arg) :complex)
1180             (make-numeric-type :class (numeric-type-class arg)
1181                                :format (numeric-type-format arg)
1182                                :complexp :complex))
1183            ((numeric-type-real-p arg)
1184             (let* ((format (case (numeric-type-class arg)
1185                              ((integer rational) 'single-float)
1186                              (t (numeric-type-format arg))))
1187                    (bound-type (or format 'float)))
1188               ;; If the argument is a subset of the "principal" domain
1189               ;; of the function, we can compute the bounds because
1190               ;; the function is monotonic. We can't do this in
1191               ;; general for these periodic functions because we can't
1192               ;; (and don't want to) do the argument reduction in
1193               ;; exactly the same way as the functions themselves do
1194               ;; it.
1195               (if (csubtypep arg domain)
1196                   (let ((res-lo (bound-func fcn (numeric-type-low arg)))
1197                         (res-hi (bound-func fcn (numeric-type-high arg))))
1198                     (unless increasingp
1199                       (rotatef res-lo res-hi))
1200                     (make-numeric-type
1201                      :class 'float
1202                      :format format
1203                      :low (coerce-numeric-bound res-lo bound-type)
1204                      :high (coerce-numeric-bound res-hi bound-type)))
1205                   (make-numeric-type
1206                    :class 'float
1207                    :format format
1208                    :low (and def-lo (coerce def-lo bound-type))
1209                    :high (and def-hi (coerce def-hi bound-type))))))
1210            (t
1211             (float-or-complex-float-type arg def-lo def-hi))))))
1212
1213 (defoptimizer (sin derive-type) ((num))
1214   (one-arg-derive-type
1215    num
1216    (lambda (arg)
1217      ;; Derive the bounds if the arg is in [-pi/2, pi/2].
1218      (trig-derive-type-aux
1219       arg
1220       (specifier-type `(float ,(- (/ pi 2)) ,(/ pi 2)))
1221       #'sin
1222       -1 1))
1223    #'sin))
1224
1225 (defoptimizer (cos derive-type) ((num))
1226   (one-arg-derive-type
1227    num
1228    (lambda (arg)
1229      ;; Derive the bounds if the arg is in [0, pi].
1230      (trig-derive-type-aux arg
1231                            (specifier-type `(float 0d0 ,pi))
1232                            #'cos
1233                            -1 1
1234                            nil))
1235    #'cos))
1236
1237 (defoptimizer (tan derive-type) ((num))
1238   (one-arg-derive-type
1239    num
1240    (lambda (arg)
1241      ;; Derive the bounds if the arg is in [-pi/2, pi/2].
1242      (trig-derive-type-aux arg
1243                            (specifier-type `(float ,(- (/ pi 2)) ,(/ pi 2)))
1244                            #'tan
1245                            nil nil))
1246    #'tan))
1247
1248 ;;; CONJUGATE always returns the same type as the input type.
1249 ;;;
1250 ;;; FIXME: ANSI allows any subtype of REAL for the components of COMPLEX.
1251 ;;; So what if the input type is (COMPLEX (SINGLE-FLOAT 0 1))?
1252 (defoptimizer (conjugate derive-type) ((num))
1253   (continuation-type num))
1254
1255 (defoptimizer (cis derive-type) ((num))
1256   (one-arg-derive-type num
1257      #'(lambda (arg)
1258          (sb!c::specifier-type
1259           `(complex ,(or (numeric-type-format arg) 'float))))
1260      #'cis))
1261
1262 ) ; PROGN