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