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