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