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