1.0.3.16: experimental x86-64/darwin suport
[sbcl.git] / src / compiler / aliencomp.lisp
1 ;;;; transforms and other stuff used to compile ALIEN operations
2
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
5 ;;;;
6 ;;;; This software is derived from the CMU CL system, which was
7 ;;;; written at Carnegie Mellon University and released into the
8 ;;;; public domain. The software is in the public domain and is
9 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
10 ;;;; files for more information.
11
12 (in-package "SB!C")
13 \f
14 ;;;; DEFKNOWNs
15
16 (defknown %sap-alien (system-area-pointer alien-type) alien-value
17   (flushable movable))
18 (defknown alien-sap (alien-value) system-area-pointer
19   (flushable movable))
20
21 (defknown slot (alien-value symbol) t
22   (flushable recursive))
23 (defknown %set-slot (alien-value symbol t) t
24   (recursive))
25 (defknown %slot-addr (alien-value symbol) (alien (* t))
26   (flushable movable recursive))
27
28 (defknown deref (alien-value &rest index) t
29   (flushable))
30 (defknown %set-deref (alien-value t &rest index) t
31   ())
32 (defknown %deref-addr (alien-value &rest index) (alien (* t))
33   (flushable movable))
34
35 (defknown %heap-alien (heap-alien-info) t
36   (flushable))
37 (defknown %set-heap-alien (heap-alien-info t) t
38   ())
39 (defknown %heap-alien-addr (heap-alien-info) (alien (* t))
40   (flushable movable))
41
42 (defknown make-local-alien (local-alien-info) t
43   ())
44 (defknown note-local-alien-type (local-alien-info t) null
45   ())
46 (defknown local-alien (local-alien-info t) t
47   (flushable))
48 (defknown %local-alien-forced-to-memory-p (local-alien-info) (member t nil)
49   (movable))
50 (defknown %set-local-alien (local-alien-info t t) t
51   ())
52 (defknown %local-alien-addr (local-alien-info t) (alien (* t))
53   (flushable movable))
54 (defknown dispose-local-alien (local-alien-info t) t
55   ())
56
57 (defknown %cast (alien-value alien-type) alien
58   (flushable movable))
59
60 (defknown naturalize (t alien-type) alien
61   (flushable movable))
62 (defknown deport (alien alien-type) t
63   (flushable movable))
64 (defknown deport-alloc (alien alien-type) t
65   (flushable movable))
66 (defknown extract-alien-value (system-area-pointer unsigned-byte alien-type) t
67   (flushable))
68 (defknown deposit-alien-value (system-area-pointer unsigned-byte alien-type t) t
69   ())
70
71 (defknown alien-funcall (alien-value &rest *) *
72   (any recursive))
73 \f
74 ;;;; cosmetic transforms
75
76 (deftransform slot ((object slot)
77                     ((alien (* t)) symbol))
78   '(slot (deref object) slot))
79
80 (deftransform %set-slot ((object slot value)
81                          ((alien (* t)) symbol t))
82   '(%set-slot (deref object) slot value))
83
84 (deftransform %slot-addr ((object slot)
85                           ((alien (* t)) symbol))
86   '(%slot-addr (deref object) slot))
87 \f
88 ;;;; SLOT support
89
90 (defun find-slot-offset-and-type (alien slot)
91   (unless (constant-lvar-p slot)
92     (give-up-ir1-transform
93      "The slot is not constant, so access cannot be open coded."))
94   (let ((type (lvar-type alien)))
95     (unless (alien-type-type-p type)
96       (give-up-ir1-transform))
97     (let ((alien-type (alien-type-type-alien-type type)))
98       (unless (alien-record-type-p alien-type)
99         (give-up-ir1-transform))
100       (let* ((slot-name (lvar-value slot))
101              (field (find slot-name (alien-record-type-fields alien-type)
102                           :key #'alien-record-field-name)))
103         (unless field
104           (abort-ir1-transform "~S doesn't have a slot named ~S"
105                                alien
106                                slot-name))
107         (values (alien-record-field-offset field)
108                 (alien-record-field-type field))))))
109
110 #+nil ;; Shouldn't be necessary.
111 (defoptimizer (slot derive-type) ((alien slot))
112   (block nil
113     (catch 'give-up-ir1-transform
114       (multiple-value-bind (slot-offset slot-type)
115           (find-slot-offset-and-type alien slot)
116         (declare (ignore slot-offset))
117         (return (make-alien-type-type slot-type))))
118     *wild-type*))
119
120 (deftransform slot ((alien slot) * * :important t)
121   (multiple-value-bind (slot-offset slot-type)
122       (find-slot-offset-and-type alien slot)
123     `(extract-alien-value (alien-sap alien)
124                           ,slot-offset
125                           ',slot-type)))
126
127 #+nil ;; ### But what about coercions?
128 (defoptimizer (%set-slot derive-type) ((alien slot value))
129   (block nil
130     (catch 'give-up-ir1-transform
131       (multiple-value-bind (slot-offset slot-type)
132           (find-slot-offset-and-type alien slot)
133         (declare (ignore slot-offset))
134         (let ((type (make-alien-type-type slot-type)))
135           (assert-lvar-type value type)
136           (return type))))
137     *wild-type*))
138
139 (deftransform %set-slot ((alien slot value) * * :important t)
140   (multiple-value-bind (slot-offset slot-type)
141       (find-slot-offset-and-type alien slot)
142     `(deposit-alien-value (alien-sap alien)
143                           ,slot-offset
144                           ',slot-type
145                           value)))
146
147 (defoptimizer (%slot-addr derive-type) ((alien slot))
148   (block nil
149     (catch 'give-up-ir1-transform
150       (multiple-value-bind (slot-offset slot-type)
151           (find-slot-offset-and-type alien slot)
152         (declare (ignore slot-offset))
153         (return (make-alien-type-type
154                  (make-alien-pointer-type :to slot-type)))))
155     *wild-type*))
156
157 (deftransform %slot-addr ((alien slot) * * :important t)
158   (multiple-value-bind (slot-offset slot-type)
159       (find-slot-offset-and-type alien slot)
160     (/noshow "in DEFTRANSFORM %SLOT-ADDR, creating %SAP-ALIEN")
161     `(%sap-alien (sap+ (alien-sap alien) (/ ,slot-offset sb!vm:n-byte-bits))
162                  ',(make-alien-pointer-type :to slot-type))))
163 \f
164 ;;;; DEREF support
165
166 (defun find-deref-alien-type (alien)
167   (let ((alien-type (lvar-type alien)))
168     (unless (alien-type-type-p alien-type)
169       (give-up-ir1-transform))
170     (let ((alien-type (alien-type-type-alien-type alien-type)))
171       (if (alien-type-p alien-type)
172           alien-type
173           (give-up-ir1-transform)))))
174
175 (defun find-deref-element-type (alien)
176   (let ((alien-type (find-deref-alien-type alien)))
177     (typecase alien-type
178       (alien-pointer-type
179        (alien-pointer-type-to alien-type))
180       (alien-array-type
181        (alien-array-type-element-type alien-type))
182       (t
183        (give-up-ir1-transform)))))
184
185 (defun compute-deref-guts (alien indices)
186   (let ((alien-type (find-deref-alien-type alien)))
187     (typecase alien-type
188       (alien-pointer-type
189        (when (cdr indices)
190          (abort-ir1-transform "too many indices for pointer deref: ~W"
191                               (length indices)))
192        (let ((element-type (alien-pointer-type-to alien-type)))
193          (if indices
194              (let ((bits (alien-type-bits element-type))
195                    (alignment (alien-type-alignment element-type)))
196                (unless bits
197                  (abort-ir1-transform "unknown element size"))
198                (unless alignment
199                  (abort-ir1-transform "unknown element alignment"))
200                (values '(offset)
201                        `(* offset
202                            ,(align-offset bits alignment))
203                        element-type))
204              (values nil 0 element-type))))
205       (alien-array-type
206        (let* ((element-type (alien-array-type-element-type alien-type))
207               (bits (alien-type-bits element-type))
208               (alignment (alien-type-alignment element-type))
209               (dims (alien-array-type-dimensions alien-type)))
210          (unless (= (length indices) (length dims))
211            (give-up-ir1-transform "incorrect number of indices"))
212          (unless bits
213            (give-up-ir1-transform "Element size is unknown."))
214          (unless alignment
215            (give-up-ir1-transform "Element alignment is unknown."))
216          (if (null dims)
217              (values nil 0 element-type)
218              (let* ((arg (gensym))
219                     (args (list arg))
220                     (offsetexpr arg))
221                (dolist (dim (cdr dims))
222                  (let ((arg (gensym)))
223                    (push arg args)
224                    (setf offsetexpr `(+ (* ,offsetexpr ,dim) ,arg))))
225                (values (reverse args)
226                        `(* ,offsetexpr
227                            ,(align-offset bits alignment))
228                        element-type)))))
229       (t
230        (abort-ir1-transform "~S not either a pointer or array type."
231                             alien-type)))))
232
233 #+nil ;; Shouldn't be necessary.
234 (defoptimizer (deref derive-type) ((alien &rest noise))
235   (declare (ignore noise))
236   (block nil
237     (catch 'give-up-ir1-transform
238       (return (make-alien-type-type (find-deref-element-type alien))))
239     *wild-type*))
240
241 (deftransform deref ((alien &rest indices) * * :important t)
242   (multiple-value-bind (indices-args offset-expr element-type)
243       (compute-deref-guts alien indices)
244     `(lambda (alien ,@indices-args)
245        (extract-alien-value (alien-sap alien)
246                             ,offset-expr
247                             ',element-type))))
248
249 #+nil ;; ### Again, the value might be coerced.
250 (defoptimizer (%set-deref derive-type) ((alien value &rest noise))
251   (declare (ignore noise))
252   (block nil
253     (catch 'give-up-ir1-transform
254       (let ((type (make-alien-type-type
255                    (make-alien-pointer-type
256                     :to (find-deref-element-type alien)))))
257         (assert-lvar-type value type)
258         (return type)))
259     *wild-type*))
260
261 (deftransform %set-deref ((alien value &rest indices) * * :important t)
262   (multiple-value-bind (indices-args offset-expr element-type)
263       (compute-deref-guts alien indices)
264     `(lambda (alien value ,@indices-args)
265        (deposit-alien-value (alien-sap alien)
266                             ,offset-expr
267                             ',element-type
268                             value))))
269
270 (defoptimizer (%deref-addr derive-type) ((alien &rest noise))
271   (declare (ignore noise))
272   (block nil
273     (catch 'give-up-ir1-transform
274       (return (make-alien-type-type
275                (make-alien-pointer-type
276                 :to (find-deref-element-type alien)))))
277     *wild-type*))
278
279 (deftransform %deref-addr ((alien &rest indices) * * :important t)
280   (multiple-value-bind (indices-args offset-expr element-type)
281       (compute-deref-guts alien indices)
282     (/noshow "in DEFTRANSFORM %DEREF-ADDR, creating (LAMBDA .. %SAP-ALIEN)")
283     `(lambda (alien ,@indices-args)
284        (%sap-alien (sap+ (alien-sap alien) (/ ,offset-expr sb!vm:n-byte-bits))
285                    ',(make-alien-pointer-type :to element-type)))))
286 \f
287 ;;;; support for aliens on the heap
288
289 (defun heap-alien-sap-and-type (info)
290   (unless (constant-lvar-p info)
291     (give-up-ir1-transform "info not constant; can't open code"))
292   (let ((info (lvar-value info)))
293     (values (heap-alien-info-sap-form info)
294             (heap-alien-info-type info))))
295
296 #+nil ; shouldn't be necessary
297 (defoptimizer (%heap-alien derive-type) ((info))
298   (block nil
299     (catch 'give-up
300       (multiple-value-bind (sap type) (heap-alien-sap-and-type info)
301         (declare (ignore sap))
302         (return (make-alien-type-type type))))
303     *wild-type*))
304
305 (deftransform %heap-alien ((info) * * :important t)
306   (multiple-value-bind (sap type) (heap-alien-sap-and-type info)
307     `(extract-alien-value ,sap 0 ',type)))
308
309 #+nil ;; ### Again, deposit value might change the type.
310 (defoptimizer (%set-heap-alien derive-type) ((info value))
311   (block nil
312     (catch 'give-up-ir1-transform
313       (multiple-value-bind (sap type) (heap-alien-sap-and-type info)
314         (declare (ignore sap))
315         (let ((type (make-alien-type-type type)))
316           (assert-lvar-type value type)
317           (return type))))
318     *wild-type*))
319
320 (deftransform %set-heap-alien ((info value) (heap-alien-info *) * :important t)
321   (multiple-value-bind (sap type) (heap-alien-sap-and-type info)
322     `(deposit-alien-value ,sap 0 ',type value)))
323
324 (defoptimizer (%heap-alien-addr derive-type) ((info))
325   (block nil
326     (catch 'give-up-ir1-transform
327       (multiple-value-bind (sap type) (heap-alien-sap-and-type info)
328         (declare (ignore sap))
329         (return (make-alien-type-type (make-alien-pointer-type :to type)))))
330     *wild-type*))
331
332 (deftransform %heap-alien-addr ((info) * * :important t)
333   (multiple-value-bind (sap type) (heap-alien-sap-and-type info)
334     (/noshow "in DEFTRANSFORM %HEAP-ALIEN-ADDR, creating %SAP-ALIEN")
335     `(%sap-alien ,sap ',type)))
336 \f
337 ;;;; support for local (stack or register) aliens
338
339 (deftransform make-local-alien ((info) * * :important t)
340   (unless (constant-lvar-p info)
341     (abort-ir1-transform "Local alien info isn't constant?"))
342   (let* ((info (lvar-value info))
343          (alien-type (local-alien-info-type info))
344          (bits (alien-type-bits alien-type)))
345     (unless bits
346       (abort-ir1-transform "unknown size: ~S" (unparse-alien-type alien-type)))
347     (/noshow "in DEFTRANSFORM MAKE-LOCAL-ALIEN" info)
348     (/noshow (local-alien-info-force-to-memory-p info))
349     (/noshow alien-type (unparse-alien-type alien-type) (alien-type-bits alien-type))
350     (if (local-alien-info-force-to-memory-p info)
351       #!+(or x86 x86-64) `(truly-the system-area-pointer
352                          (%primitive alloc-alien-stack-space
353                                      ,(ceiling (alien-type-bits alien-type)
354                                                sb!vm:n-byte-bits)))
355       #!-(or x86 x86-64) `(truly-the system-area-pointer
356                          (%primitive alloc-number-stack-space
357                                      ,(ceiling (alien-type-bits alien-type)
358                                                sb!vm:n-byte-bits)))
359       (let* ((alien-rep-type-spec (compute-alien-rep-type alien-type))
360              (alien-rep-type (specifier-type alien-rep-type-spec)))
361         (cond ((csubtypep (specifier-type 'system-area-pointer)
362                           alien-rep-type)
363                '(int-sap 0))
364               ((ctypep 0 alien-rep-type) 0)
365               ((ctypep 0.0f0 alien-rep-type) 0.0f0)
366               ((ctypep 0.0d0 alien-rep-type) 0.0d0)
367               (t
368                (compiler-error
369                 "Aliens of type ~S cannot be represented immediately."
370                 (unparse-alien-type alien-type))))))))
371
372 (deftransform note-local-alien-type ((info var) * * :important t)
373   ;; FIXME: This test and error occur about a zillion times. They
374   ;; could be factored into a function.
375   (unless (constant-lvar-p info)
376     (abort-ir1-transform "Local alien info isn't constant?"))
377   (let ((info (lvar-value info)))
378     (/noshow "in DEFTRANSFORM NOTE-LOCAL-ALIEN-TYPE" info)
379     (/noshow (local-alien-info-force-to-memory-p info))
380     (unless (local-alien-info-force-to-memory-p info)
381       (let ((var-node (lvar-uses var)))
382         (/noshow var-node (ref-p var-node))
383         (when (ref-p var-node)
384           (propagate-to-refs (ref-leaf var-node)
385                              (specifier-type
386                               (compute-alien-rep-type
387                                (local-alien-info-type info))))))))
388   nil)
389
390 (deftransform local-alien ((info var) * * :important t)
391   (unless (constant-lvar-p info)
392     (abort-ir1-transform "Local alien info isn't constant?"))
393   (let* ((info (lvar-value info))
394          (alien-type (local-alien-info-type info)))
395     (/noshow "in DEFTRANSFORM LOCAL-ALIEN" info alien-type)
396     (/noshow (local-alien-info-force-to-memory-p info))
397     (if (local-alien-info-force-to-memory-p info)
398         `(extract-alien-value var 0 ',alien-type)
399         `(naturalize var ',alien-type))))
400
401 (deftransform %local-alien-forced-to-memory-p ((info) * * :important t)
402   (unless (constant-lvar-p info)
403     (abort-ir1-transform "Local alien info isn't constant?"))
404   (let ((info (lvar-value info)))
405     (local-alien-info-force-to-memory-p info)))
406
407 (deftransform %set-local-alien ((info var value) * * :important t)
408   (unless (constant-lvar-p info)
409     (abort-ir1-transform "Local alien info isn't constant?"))
410   (let* ((info (lvar-value info))
411          (alien-type (local-alien-info-type info)))
412     (if (local-alien-info-force-to-memory-p info)
413         `(deposit-alien-value var 0 ',alien-type value)
414         '(error "This should be eliminated as dead code."))))
415
416 (defoptimizer (%local-alien-addr derive-type) ((info var))
417   (if (constant-lvar-p info)
418       (let* ((info (lvar-value info))
419              (alien-type (local-alien-info-type info)))
420         (make-alien-type-type (make-alien-pointer-type :to alien-type)))
421       *wild-type*))
422
423 (deftransform %local-alien-addr ((info var) * * :important t)
424   (unless (constant-lvar-p info)
425     (abort-ir1-transform "Local alien info isn't constant?"))
426   (let* ((info (lvar-value info))
427          (alien-type (local-alien-info-type info)))
428     (/noshow "in DEFTRANSFORM %LOCAL-ALIEN-ADDR, creating %SAP-ALIEN")
429     (if (local-alien-info-force-to-memory-p info)
430         `(%sap-alien var ',(make-alien-pointer-type :to alien-type))
431         (error "This shouldn't happen."))))
432
433 (deftransform dispose-local-alien ((info var) * * :important t)
434   (unless (constant-lvar-p info)
435     (abort-ir1-transform "Local alien info isn't constant?"))
436   (let* ((info (lvar-value info))
437          (alien-type (local-alien-info-type info)))
438     (if (local-alien-info-force-to-memory-p info)
439       #!+(or x86 x86-64) `(%primitive dealloc-alien-stack-space
440                           ,(ceiling (alien-type-bits alien-type)
441                                     sb!vm:n-byte-bits))
442       #!-(or x86 x86-64) `(%primitive dealloc-number-stack-space
443                           ,(ceiling (alien-type-bits alien-type)
444                                     sb!vm:n-byte-bits))
445       nil)))
446 \f
447 ;;;; %CAST
448
449 (defoptimizer (%cast derive-type) ((alien type))
450   (or (when (constant-lvar-p type)
451         (let ((alien-type (lvar-value type)))
452           (when (alien-type-p alien-type)
453             (make-alien-type-type alien-type))))
454       *wild-type*))
455
456 (deftransform %cast ((alien target-type) * * :important t)
457   (unless (constant-lvar-p target-type)
458     (give-up-ir1-transform
459      "The alien type is not constant, so access cannot be open coded."))
460   (let ((target-type (lvar-value target-type)))
461     (cond ((or (alien-pointer-type-p target-type)
462                (alien-array-type-p target-type)
463                (alien-fun-type-p target-type))
464            `(naturalize (alien-sap alien) ',target-type))
465           (t
466            (abort-ir1-transform "cannot cast to alien type ~S" target-type)))))
467 \f
468 ;;;; ALIEN-SAP, %SAP-ALIEN, %ADDR, etc.
469
470 (deftransform alien-sap ((alien) * * :important t)
471   (let ((alien-node (lvar-uses alien)))
472     (typecase alien-node
473       (combination
474        (splice-fun-args alien '%sap-alien 2)
475        '(lambda (sap type)
476           (declare (ignore type))
477           sap))
478       (t
479        (give-up-ir1-transform)))))
480
481 (defoptimizer (%sap-alien derive-type) ((sap type))
482   (declare (ignore sap))
483   (if (constant-lvar-p type)
484       (make-alien-type-type (lvar-value type))
485       *wild-type*))
486
487 (deftransform %sap-alien ((sap type) * * :important t)
488   (give-up-ir1-transform
489    ;; FIXME: The hardcoded newline here causes more-than-usually
490    ;; screwed-up formatting of the optimization note output.
491    "could not optimize away %SAP-ALIEN: forced to do runtime ~@
492     allocation of alien-value structure"))
493 \f
494 ;;;; NATURALIZE/DEPORT/EXTRACT/DEPOSIT magic
495
496 (flet ((%computed-lambda (compute-lambda type)
497          (declare (type function compute-lambda))
498          (unless (constant-lvar-p type)
499            (give-up-ir1-transform
500             "The type is not constant at compile time; can't open code."))
501          (handler-case
502              (let ((result (funcall compute-lambda (lvar-value type))))
503                (/noshow "in %COMPUTED-LAMBDA" (lvar-value type) result)
504                result)
505            (error (condition)
506                   (compiler-error "~A" condition)))))
507   (deftransform naturalize ((object type) * * :important t)
508     (%computed-lambda #'compute-naturalize-lambda type))
509   (deftransform deport ((alien type) * * :important t)
510     (%computed-lambda #'compute-deport-lambda type))
511   (deftransform deport-alloc ((alien type) * * :important t)
512     (%computed-lambda #'compute-deport-alloc-lambda type))
513   (deftransform extract-alien-value ((sap offset type) * * :important t)
514     (%computed-lambda #'compute-extract-lambda type))
515   (deftransform deposit-alien-value ((sap offset type value) * * :important t)
516     (%computed-lambda #'compute-deposit-lambda type)))
517 \f
518 ;;;; a hack to clean up divisions
519
520 (defun count-low-order-zeros (thing)
521   (typecase thing
522     (lvar
523      (if (constant-lvar-p thing)
524          (count-low-order-zeros (lvar-value thing))
525          (count-low-order-zeros (lvar-uses thing))))
526     (combination
527      (case (let ((name (lvar-fun-name (combination-fun thing))))
528              (or (modular-version-info name :unsigned) name))
529        ((+ -)
530         (let ((min most-positive-fixnum)
531               (itype (specifier-type 'integer)))
532           (dolist (arg (combination-args thing) min)
533             (if (csubtypep (lvar-type arg) itype)
534                 (setf min (min min (count-low-order-zeros arg)))
535                 (return 0)))))
536        (*
537         (let ((result 0)
538               (itype (specifier-type 'integer)))
539           (dolist (arg (combination-args thing) result)
540             (if (csubtypep (lvar-type arg) itype)
541                 (setf result (+ result (count-low-order-zeros arg)))
542                 (return 0)))))
543        (ash
544         (let ((args (combination-args thing)))
545           (if (= (length args) 2)
546               (let ((amount (second args)))
547                 (if (constant-lvar-p amount)
548                     (max (+ (count-low-order-zeros (first args))
549                             (lvar-value amount))
550                          0)
551                     0))
552               0)))
553        (t
554         0)))
555     (integer
556      (if (zerop thing)
557          most-positive-fixnum
558          (do ((result 0 (1+ result))
559               (num thing (ash num -1)))
560              ((logbitp 0 num) result))))
561     (cast
562      (count-low-order-zeros (cast-value thing)))
563     (t
564      0)))
565
566 (deftransform / ((numerator denominator) (integer integer))
567   "convert x/2^k to shift"
568   (unless (constant-lvar-p denominator)
569     (give-up-ir1-transform))
570   (let* ((denominator (lvar-value denominator))
571          (bits (1- (integer-length denominator))))
572     (unless (and (> denominator 0) (= (ash 1 bits) denominator))
573       (give-up-ir1-transform))
574     (let ((alignment (count-low-order-zeros numerator)))
575       (unless (>= alignment bits)
576         (give-up-ir1-transform))
577       `(ash numerator ,(- bits)))))
578
579 (deftransform ash ((value amount))
580   (let ((value-node (lvar-uses value)))
581     (unless (combination-p value-node)
582       (give-up-ir1-transform))
583     (let ((inside-fun-name (lvar-fun-name (combination-fun value-node))))
584       (multiple-value-bind (prototype width)
585           (modular-version-info inside-fun-name :unsigned)
586         (unless (eq (or prototype inside-fun-name) 'ash)
587           (give-up-ir1-transform))
588         (when (and width (not (constant-lvar-p amount)))
589           (give-up-ir1-transform))
590         (let ((inside-args (combination-args value-node)))
591           (unless (= (length inside-args) 2)
592             (give-up-ir1-transform))
593           (let ((inside-amount (second inside-args)))
594             (unless (and (constant-lvar-p inside-amount)
595                          (not (minusp (lvar-value inside-amount))))
596               (give-up-ir1-transform)))
597           (splice-fun-args value inside-fun-name 2)
598           (if width
599               `(lambda (value amount1 amount2)
600                  (logand (ash value (+ amount1 amount2))
601                          ,(1- (ash 1 (+ width (lvar-value amount))))))
602               `(lambda (value amount1 amount2)
603                  (ash value (+ amount1 amount2)))))))))
604 \f
605 ;;;; ALIEN-FUNCALL support
606
607 (deftransform alien-funcall ((function &rest args)
608                              ((alien (* t)) &rest *) *
609                              :important t)
610   (let ((names (make-gensym-list (length args))))
611     (/noshow "entering first DEFTRANSFORM ALIEN-FUNCALL" function args)
612     `(lambda (function ,@names)
613        (alien-funcall (deref function) ,@names))))
614
615 (deftransform alien-funcall ((function &rest args) * * :important t)
616   (let ((type (lvar-type function)))
617     (unless (alien-type-type-p type)
618       (give-up-ir1-transform "can't tell function type at compile time"))
619     (/noshow "entering second DEFTRANSFORM ALIEN-FUNCALL" function)
620     (let ((alien-type (alien-type-type-alien-type type)))
621       (unless (alien-fun-type-p alien-type)
622         (give-up-ir1-transform))
623       (let ((arg-types (alien-fun-type-arg-types alien-type)))
624         (unless (= (length args) (length arg-types))
625           (abort-ir1-transform
626            "wrong number of arguments; expected ~W, got ~W"
627            (length arg-types)
628            (length args)))
629         (collect ((params) (deports))
630           (dolist (arg-type arg-types)
631             (let ((param (gensym)))
632               (params param)
633               (deports `(deport ,param ',arg-type))))
634           ;; Build BODY from the inside out.
635           (let ((return-type (alien-fun-type-result-type alien-type))
636                 ;; Innermost, we DEPORT the parameters (e.g. by taking SAPs
637                 ;; to them) and do the call.
638                 (body `(%alien-funcall (deport function ',alien-type)
639                                        ',alien-type
640                                        ,@(deports))))
641             ;; Wrap that in a WITH-PINNED-OBJECTS to ensure the values
642             ;; the SAPs are taken for won't be moved by the GC. (If
643             ;; needed: some alien types won't need it).
644             (setf body `(maybe-with-pinned-objects ,(params) ,arg-types
645                           ,body))
646             ;; Around that handle any memory allocation that's needed.
647             ;; Mostly the DEPORT-ALLOC alien-type-methods are just an
648             ;; identity operation, but for example for deporting a
649             ;; Unicode string we need to convert the string into an
650             ;; octet array. This step needs to be done before the pinning
651             ;; to ensure we pin the right objects, so it can't be combined
652             ;; with the deporting.
653             ;; -- JES 2006-03-16
654             (loop for param in (params)
655                   for arg-type in arg-types
656                   do (setf body
657                            `(let ((,param (deport-alloc ,param ',arg-type)))
658                               ,body)))
659             (if (alien-values-type-p return-type)
660                 (collect ((temps) (results))
661                   (dolist (type (alien-values-type-values return-type))
662                     (let ((temp (gensym)))
663                       (temps temp)
664                       (results `(naturalize ,temp ',type))))
665                   (setf body
666                         `(multiple-value-bind ,(temps) ,body
667                            (values ,@(results)))))
668                 (setf body `(naturalize ,body ',return-type)))
669             (/noshow "returning from DEFTRANSFORM ALIEN-FUNCALL" (params) body)
670             `(lambda (function ,@(params))
671                ,body)))))))
672
673 (defoptimizer (%alien-funcall derive-type) ((function type &rest args))
674   (declare (ignore function args))
675   (unless (constant-lvar-p type)
676     (error "Something is broken."))
677   (let ((type (lvar-value type)))
678     (unless (alien-fun-type-p type)
679       (error "Something is broken."))
680     (values-specifier-type
681      (compute-alien-rep-type
682       (alien-fun-type-result-type type)))))
683
684 (defoptimizer (%alien-funcall ltn-annotate)
685               ((function type &rest args) node ltn-policy)
686   (setf (basic-combination-info node) :funny)
687   (setf (node-tail-p node) nil)
688   (annotate-ordinary-lvar function)
689   (dolist (arg args)
690     (annotate-ordinary-lvar arg)))
691
692 ;;; We support both the stdcall and cdecl calling conventions on win32 by
693 ;;; resetting ESP after the foreign function returns. This way it works
694 ;;; correctly whether the party that is supposed to pop arguments from
695 ;;; the stack is the caller (cdecl) or the callee (stdcall).
696 (defoptimizer (%alien-funcall ir2-convert)
697               ((function type &rest args) call block)
698   (let ((type (if (constant-lvar-p type)
699                   (lvar-value type)
700                   (error "Something is broken.")))
701         (lvar (node-lvar call))
702         (args args)
703         #!+(or (and (or x86 x86-64) darwin) win32) (stack-pointer (make-stack-pointer-tn)))
704     (multiple-value-bind (nsp stack-frame-size arg-tns result-tns)
705         (make-call-out-tns type)
706       #!+x86 (vop set-fpu-word-for-c call block)
707       #!+(or (and (or x86 x86-64) darwin) win32) (vop current-stack-pointer call block stack-pointer)
708       (vop alloc-number-stack-space call block stack-frame-size nsp)
709       (dolist (tn arg-tns)
710         ;; On PPC, TN might be a list. This is used to indicate
711         ;; something special needs to happen. See below.
712         ;;
713         ;; FIXME: We should implement something better than this.
714         (let* ((first-tn (if (listp tn) (car tn) tn))
715                (arg (pop args))
716                (sc (tn-sc first-tn))
717                (scn (sc-number sc))
718                #!-(or x86 x86-64) (temp-tn (make-representation-tn
719                                             (tn-primitive-type first-tn) scn))
720                (move-arg-vops (svref (sc-move-arg-vops sc) scn)))
721           (aver arg)
722           (unless (= (length move-arg-vops) 1)
723             (error "no unique move-arg-vop for moves in SC ~S" (sc-name sc)))
724           #!+(or x86 x86-64) (emit-move-arg-template call
725                                          block
726                                          (first move-arg-vops)
727                                          (lvar-tn call block arg)
728                                          nsp
729                                          first-tn)
730           #!-(or x86 x86-64) (progn
731                    (emit-move call
732                               block
733                               (lvar-tn call block arg)
734                               temp-tn)
735                    (emit-move-arg-template call
736                                            block
737                                            (first move-arg-vops)
738                                            temp-tn
739                                            nsp
740                                            first-tn))
741           #!+(and ppc darwin)
742           (when (listp tn)
743             ;; This means that we have a float arg that we need to
744             ;; also copy to some int regs. The list contains the TN
745             ;; for the float as well as the TNs to use for the int
746             ;; arg.
747             (destructuring-bind (float-tn i1-tn &optional i2-tn)
748                 tn
749               (if i2-tn
750                   (vop sb!vm::move-double-to-int-arg call block
751                        float-tn i1-tn i2-tn)
752                   (vop sb!vm::move-single-to-int-arg call block
753                        float-tn i1-tn))))))
754       (aver (null args))
755       (unless (listp result-tns)
756         (setf result-tns (list result-tns)))
757       (let ((arg-tns (flatten-list arg-tns)))
758         (vop* call-out call block
759               ((lvar-tn call block function)
760                (reference-tn-list arg-tns nil))
761               ((reference-tn-list result-tns t))))
762       #!-(or (and darwin (or x86 x86-64)) win32) (vop dealloc-number-stack-space call block stack-frame-size)
763       #!+(or (and darwin (or x86 x86-64)) win32) (vop reset-stack-pointer call block stack-pointer)
764       #!+x86 (vop set-fpu-word-for-lisp call block)
765       (move-lvar-result call block result-tns lvar))))