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