Allow inlining more calls to INVOKE-WITH-SAVED-FP-AND-PC during XC.
[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 %alien-value (system-area-pointer unsigned-byte alien-type) t
67   (flushable))
68 (defknown (setf %alien-value) (t system-area-pointer unsigned-byte alien-type) 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     `(%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     `(setf (%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          (unless element-type
194            (give-up-ir1-transform "unable to open code deref of wild pointer type"))
195          (if indices
196              (let ((bits (alien-type-bits element-type))
197                    (alignment (alien-type-alignment element-type)))
198                (unless bits
199                  (abort-ir1-transform "unknown element size"))
200                (unless alignment
201                  (abort-ir1-transform "unknown element alignment"))
202                (values '(offset)
203                        `(* offset
204                            ,(align-offset bits alignment))
205                        element-type))
206              (values nil 0 element-type))))
207       (alien-array-type
208        (let* ((element-type (alien-array-type-element-type alien-type))
209               (bits (alien-type-bits element-type))
210               (alignment (alien-type-alignment element-type))
211               (dims (alien-array-type-dimensions alien-type)))
212          (unless (= (length indices) (length dims))
213            (give-up-ir1-transform "incorrect number of indices"))
214          (unless bits
215            (give-up-ir1-transform "Element size is unknown."))
216          (unless alignment
217            (give-up-ir1-transform "Element alignment is unknown."))
218          (if (null dims)
219              (values nil 0 element-type)
220              (let* ((arg (gensym))
221                     (args (list arg))
222                     (offsetexpr arg))
223                (dolist (dim (cdr dims))
224                  (let ((arg (gensym)))
225                    (push arg args)
226                    (setf offsetexpr `(+ (* ,offsetexpr ,dim) ,arg))))
227                (values (reverse args)
228                        `(* ,offsetexpr
229                            ,(align-offset bits alignment))
230                        element-type)))))
231       (t
232        (abort-ir1-transform "~S not either a pointer or array type."
233                             alien-type)))))
234
235 #+nil ;; Shouldn't be necessary.
236 (defoptimizer (deref derive-type) ((alien &rest noise))
237   (declare (ignore noise))
238   (block nil
239     (catch 'give-up-ir1-transform
240       (return (make-alien-type-type (find-deref-element-type alien))))
241     *wild-type*))
242
243 (deftransform deref ((alien &rest indices) * * :important t)
244   (multiple-value-bind (indices-args offset-expr element-type)
245       (compute-deref-guts alien indices)
246     `(lambda (alien ,@indices-args)
247        (%alien-value (alien-sap alien)
248                      ,offset-expr
249                      ',element-type))))
250
251 #+nil ;; ### Again, the value might be coerced.
252 (defoptimizer (%set-deref derive-type) ((alien value &rest noise))
253   (declare (ignore noise))
254   (block nil
255     (catch 'give-up-ir1-transform
256       (let ((type (make-alien-type-type
257                    (make-alien-pointer-type
258                     :to (find-deref-element-type alien)))))
259         (assert-lvar-type value type)
260         (return type)))
261     *wild-type*))
262
263 (deftransform %set-deref ((alien value &rest indices) * * :important t)
264   (multiple-value-bind (indices-args offset-expr element-type)
265       (compute-deref-guts alien indices)
266     `(lambda (alien value ,@indices-args)
267        (setf (%alien-value (alien-sap alien)
268                            ,offset-expr
269                            ',element-type)
270              value))))
271
272 (defoptimizer (%deref-addr derive-type) ((alien &rest noise))
273   (declare (ignore noise))
274   (block nil
275     (catch 'give-up-ir1-transform
276       (return (make-alien-type-type
277                (make-alien-pointer-type
278                 :to (find-deref-element-type alien)))))
279     *wild-type*))
280
281 (deftransform %deref-addr ((alien &rest indices) * * :important t)
282   (multiple-value-bind (indices-args offset-expr element-type)
283       (compute-deref-guts alien indices)
284     (/noshow "in DEFTRANSFORM %DEREF-ADDR, creating (LAMBDA .. %SAP-ALIEN)")
285     `(lambda (alien ,@indices-args)
286        (%sap-alien (sap+ (alien-sap alien) (/ ,offset-expr sb!vm:n-byte-bits))
287                    ',(make-alien-pointer-type :to element-type)))))
288 \f
289 ;;;; support for aliens on the heap
290
291 (defun heap-alien-sap-and-type (info)
292   (unless (constant-lvar-p info)
293     (give-up-ir1-transform "info not constant; can't open code"))
294   (let ((info (lvar-value info)))
295     (values (heap-alien-info-sap-form info)
296             (heap-alien-info-type info))))
297
298 #+nil ; shouldn't be necessary
299 (defoptimizer (%heap-alien derive-type) ((info))
300   (block nil
301     (catch 'give-up
302       (multiple-value-bind (sap type) (heap-alien-sap-and-type info)
303         (declare (ignore sap))
304         (return (make-alien-type-type type))))
305     *wild-type*))
306
307 (deftransform %heap-alien ((info) ((constant-arg heap-alien-info)) * :important t)
308   (multiple-value-bind (sap type) (heap-alien-sap-and-type info)
309     `(%alien-value ,sap 0 ',type)))
310
311 #+nil ;; ### Again, deposit value might change the type.
312 (defoptimizer (%set-heap-alien derive-type) ((info value))
313   (block nil
314     (catch 'give-up-ir1-transform
315       (multiple-value-bind (sap type) (heap-alien-sap-and-type info)
316         (declare (ignore sap))
317         (let ((type (make-alien-type-type type)))
318           (assert-lvar-type value type)
319           (return type))))
320     *wild-type*))
321
322 (deftransform %set-heap-alien ((info value) (heap-alien-info *) * :important t)
323   (multiple-value-bind (sap type) (heap-alien-sap-and-type info)
324     `(setf (%alien-value ,sap 0 ',type) value)))
325
326 (defoptimizer (%heap-alien-addr derive-type) ((info))
327   (block nil
328     (catch 'give-up-ir1-transform
329       (multiple-value-bind (sap type) (heap-alien-sap-and-type info)
330         (declare (ignore sap))
331         (return (make-alien-type-type (make-alien-pointer-type :to type)))))
332     *wild-type*))
333
334 (deftransform %heap-alien-addr ((info) * * :important t)
335   (multiple-value-bind (sap type) (heap-alien-sap-and-type info)
336     (/noshow "in DEFTRANSFORM %HEAP-ALIEN-ADDR, creating %SAP-ALIEN")
337     `(%sap-alien ,sap ',(make-alien-pointer-type :to type))))
338
339 \f
340 ;;;; support for local (stack or register) aliens
341
342 (defun alien-info-constant-or-abort (info)
343   (unless (constant-lvar-p info)
344     (abort-ir1-transform "Local alien info isn't constant?")))
345
346 (deftransform make-local-alien ((info) * * :important t)
347   (alien-info-constant-or-abort info)
348   (let* ((info (lvar-value info))
349          (alien-type (local-alien-info-type info))
350          (bits (alien-type-bits alien-type)))
351     (unless bits
352       (abort-ir1-transform "unknown size: ~S" (unparse-alien-type alien-type)))
353     (/noshow "in DEFTRANSFORM MAKE-LOCAL-ALIEN" info)
354     (/noshow (local-alien-info-force-to-memory-p info))
355     (/noshow alien-type (unparse-alien-type alien-type) (alien-type-bits alien-type))
356     (if (local-alien-info-force-to-memory-p info)
357         #!+(or x86 x86-64)
358         `(%primitive alloc-alien-stack-space
359                      ,(ceiling (alien-type-bits alien-type)
360                                sb!vm:n-byte-bits))
361         #!-(or x86 x86-64)
362         `(%primitive alloc-number-stack-space
363                      ,(ceiling (alien-type-bits alien-type)
364                                sb!vm:n-byte-bits))
365         (let* ((alien-rep-type-spec (compute-alien-rep-type alien-type))
366                (alien-rep-type (specifier-type alien-rep-type-spec)))
367           (cond ((csubtypep (specifier-type 'system-area-pointer)
368                             alien-rep-type)
369                  '(int-sap 0))
370                 ((ctypep 0 alien-rep-type) 0)
371                 ((ctypep 0.0f0 alien-rep-type) 0.0f0)
372                 ((ctypep 0.0d0 alien-rep-type) 0.0d0)
373                 (t
374                  (compiler-error
375                   "Aliens of type ~S cannot be represented immediately."
376                   (unparse-alien-type alien-type))))))))
377
378 (deftransform note-local-alien-type ((info var) * * :important t)
379   (alien-info-constant-or-abort info)
380   (let ((info (lvar-value info)))
381     (/noshow "in DEFTRANSFORM NOTE-LOCAL-ALIEN-TYPE" info)
382     (/noshow (local-alien-info-force-to-memory-p info))
383     (unless (local-alien-info-force-to-memory-p info)
384       (let ((var-node (lvar-uses var)))
385         (/noshow var-node (ref-p var-node))
386         (when (ref-p var-node)
387           (propagate-to-refs (ref-leaf var-node)
388                              (specifier-type
389                               (compute-alien-rep-type
390                                (local-alien-info-type info))))))))
391   nil)
392
393 (deftransform local-alien ((info var) * * :important t)
394   (alien-info-constant-or-abort info)
395   (let* ((info (lvar-value info))
396          (alien-type (local-alien-info-type info)))
397     (/noshow "in DEFTRANSFORM LOCAL-ALIEN" info alien-type)
398     (/noshow (local-alien-info-force-to-memory-p info))
399     (if (local-alien-info-force-to-memory-p info)
400         `(%alien-value var 0 ',alien-type)
401         `(naturalize var ',alien-type))))
402
403 (deftransform %local-alien-forced-to-memory-p ((info) * * :important t)
404   (alien-info-constant-or-abort info)
405   (let ((info (lvar-value info)))
406     (local-alien-info-force-to-memory-p info)))
407
408 (deftransform %set-local-alien ((info var value) * * :important t)
409   (alien-info-constant-or-abort info)
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         `(setf (%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   (alien-info-constant-or-abort info)
425   (let* ((info (lvar-value info))
426          (alien-type (local-alien-info-type info)))
427     (/noshow "in DEFTRANSFORM %LOCAL-ALIEN-ADDR, creating %SAP-ALIEN")
428     (if (local-alien-info-force-to-memory-p info)
429         `(%sap-alien var ',(make-alien-pointer-type :to alien-type))
430         (error "This shouldn't happen."))))
431
432 (deftransform dispose-local-alien ((info var) * * :important t)
433   (alien-info-constant-or-abort info)
434   (let* ((info (lvar-value info))
435          (alien-type (local-alien-info-type info)))
436     (if (local-alien-info-force-to-memory-p info)
437       #!+(or x86 x86-64) `(%primitive dealloc-alien-stack-space
438                           ,(ceiling (alien-type-bits alien-type)
439                                     sb!vm:n-byte-bits))
440       #!-(or x86 x86-64) `(%primitive dealloc-number-stack-space
441                           ,(ceiling (alien-type-bits alien-type)
442                                     sb!vm:n-byte-bits))
443       nil)))
444 \f
445 ;;;; %CAST
446
447 (defoptimizer (%cast derive-type) ((alien type))
448   (or (when (constant-lvar-p type)
449         (let ((alien-type (lvar-value type)))
450           (when (alien-type-p alien-type)
451             (make-alien-type-type alien-type))))
452       *wild-type*))
453
454 (deftransform %cast ((alien target-type) * * :important t)
455   (unless (constant-lvar-p target-type)
456     (give-up-ir1-transform
457      "The alien type is not constant, so access cannot be open coded."))
458   (let ((target-type (lvar-value target-type)))
459     (cond ((or (alien-pointer-type-p target-type)
460                (alien-array-type-p target-type)
461                (alien-fun-type-p target-type))
462            `(naturalize (alien-sap alien) ',target-type))
463           (t
464            (abort-ir1-transform "cannot cast to alien type ~S" target-type)))))
465 \f
466 ;;;; ALIEN-SAP, %SAP-ALIEN, %ADDR, etc.
467
468 (deftransform alien-sap ((alien) * * :important t)
469   (let ((alien-node (lvar-uses alien)))
470     (typecase alien-node
471       (combination
472        (splice-fun-args alien '%sap-alien 2)
473        '(lambda (sap type)
474           (declare (ignore type))
475           sap))
476       (t
477        (give-up-ir1-transform)))))
478
479 (defoptimizer (%sap-alien derive-type) ((sap type))
480   (declare (ignore sap))
481   (if (constant-lvar-p type)
482       (make-alien-type-type (lvar-value type))
483       *wild-type*))
484
485 (deftransform %sap-alien ((sap type) * * :important t)
486   (give-up-ir1-transform
487    ;; FIXME: The hardcoded newline here causes more-than-usually
488    ;; screwed-up formatting of the optimization note output.
489    "could not optimize away %SAP-ALIEN: forced to do runtime ~@
490     allocation of alien-value structure"))
491 \f
492 ;;;; NATURALIZE/DEPORT/EXTRACT/DEPOSIT magic
493
494 (flet ((%computed-lambda (compute-lambda type)
495          (declare (type function compute-lambda))
496          (unless (constant-lvar-p type)
497            (give-up-ir1-transform
498             "The type is not constant at compile time; can't open code."))
499          (handler-case
500              (let ((result (funcall compute-lambda (lvar-value type))))
501                (/noshow "in %COMPUTED-LAMBDA" (lvar-value type) result)
502                result)
503            (error (condition)
504                   (compiler-error "~A" condition)))))
505   (deftransform naturalize ((object type) * * :important t)
506     (%computed-lambda #'compute-naturalize-lambda type))
507   (deftransform deport ((alien type) * * :important t)
508     (%computed-lambda #'compute-deport-lambda type))
509   (deftransform deport-alloc ((alien type) * * :important t)
510     (%computed-lambda #'compute-deport-alloc-lambda type))
511   (deftransform %alien-value ((sap offset type) * * :important t)
512     (%computed-lambda #'compute-extract-lambda type))
513   (deftransform (setf %alien-value) ((value sap offset type) * * :important t)
514     (%computed-lambda #'compute-deposit-lambda type)))
515 \f
516 ;;;; a hack to clean up divisions
517
518 (defun count-low-order-zeros (thing)
519   (typecase thing
520     (lvar
521      (if (constant-lvar-p thing)
522          (count-low-order-zeros (lvar-value thing))
523          (count-low-order-zeros (lvar-uses thing))))
524     (combination
525      (case (let ((name (lvar-fun-name (combination-fun thing))))
526              (or (modular-version-info name :untagged nil) name))
527        ((+ -)
528         (let ((min most-positive-fixnum)
529               (itype (specifier-type 'integer)))
530           (dolist (arg (combination-args thing) min)
531             (if (csubtypep (lvar-type arg) itype)
532                 (setf min (min min (count-low-order-zeros arg)))
533                 (return 0)))))
534        (*
535         (let ((result 0)
536               (itype (specifier-type 'integer)))
537           (dolist (arg (combination-args thing) result)
538             (if (csubtypep (lvar-type arg) itype)
539                 (setf result (+ result (count-low-order-zeros arg)))
540                 (return 0)))))
541        (ash
542         (let ((args (combination-args thing)))
543           (if (= (length args) 2)
544               (let ((amount (second args)))
545                 (if (constant-lvar-p amount)
546                     (max (+ (count-low-order-zeros (first args))
547                             (lvar-value amount))
548                          0)
549                     0))
550               0)))
551        (t
552         0)))
553     (integer
554      (if (zerop thing)
555          most-positive-fixnum
556          (do ((result 0 (1+ result))
557               (num thing (ash num -1)))
558              ((logbitp 0 num) result))))
559     (cast
560      (count-low-order-zeros (cast-value thing)))
561     (t
562      0)))
563
564 (deftransform / ((numerator denominator) (integer integer))
565   "convert x/2^k to shift"
566   (unless (constant-lvar-p denominator)
567     (give-up-ir1-transform))
568   (let* ((denominator (lvar-value denominator))
569          (bits (1- (integer-length denominator))))
570     (unless (and (> denominator 0) (= (ash 1 bits) denominator))
571       (give-up-ir1-transform))
572     (let ((alignment (count-low-order-zeros numerator)))
573       (unless (>= alignment bits)
574         (give-up-ir1-transform))
575       `(ash numerator ,(- bits)))))
576
577 (deftransform ash ((value amount))
578   (let ((value-node (lvar-uses value)))
579     (unless (combination-p value-node)
580       (give-up-ir1-transform))
581     (let ((inside-fun-name (lvar-fun-name (combination-fun value-node))))
582       (multiple-value-bind (prototype width)
583           (modular-version-info inside-fun-name :untagged nil)
584         (unless (eq (or prototype inside-fun-name) 'ash)
585           (give-up-ir1-transform))
586         (when (and width (not (constant-lvar-p amount)))
587           (give-up-ir1-transform))
588         (let ((inside-args (combination-args value-node)))
589           (unless (= (length inside-args) 2)
590             (give-up-ir1-transform))
591           (let ((inside-amount (second inside-args)))
592             (unless (and (constant-lvar-p inside-amount)
593                          (not (minusp (lvar-value inside-amount))))
594               (give-up-ir1-transform)))
595           (splice-fun-args value inside-fun-name 2)
596           (if width
597               `(lambda (value amount1 amount2)
598                  (logand (ash value (+ amount1 amount2))
599                          ,(1- (ash 1 (+ width (lvar-value amount))))))
600               `(lambda (value amount1 amount2)
601                  (ash value (+ amount1 amount2)))))))))
602 \f
603 ;;;; ALIEN-FUNCALL support
604
605 (deftransform alien-funcall ((function &rest args)
606                              ((alien (* t)) &rest *) *
607                              :important t)
608   (let ((names (make-gensym-list (length args))))
609     (/noshow "entering first DEFTRANSFORM ALIEN-FUNCALL" function args)
610     `(lambda (function ,@names)
611        (alien-funcall (deref function) ,@names))))
612
613 (deftransform alien-funcall ((function &rest args) * * :node node :important t)
614   (let ((type (lvar-type function)))
615     (unless (alien-type-type-p type)
616       (give-up-ir1-transform "can't tell function type at compile time"))
617     (/noshow "entering second DEFTRANSFORM ALIEN-FUNCALL" function)
618     (let ((alien-type (alien-type-type-alien-type type)))
619       (unless (alien-fun-type-p alien-type)
620         (give-up-ir1-transform))
621       (let ((arg-types (alien-fun-type-arg-types alien-type)))
622         (unless (= (length args) (length arg-types))
623           (abort-ir1-transform
624            "wrong number of arguments; expected ~W, got ~W"
625            (length arg-types)
626            (length args)))
627         (collect ((params) (deports))
628           (dolist (arg-type arg-types)
629             (let ((param (gensym)))
630               (params param)
631               (deports `(deport ,param ',arg-type))))
632           ;; Build BODY from the inside out.
633           (let ((return-type (alien-fun-type-result-type alien-type))
634                 ;; Innermost, we DEPORT the parameters (e.g. by taking SAPs
635                 ;; to them) and do the call.
636                 (body `(%alien-funcall (deport function ',alien-type)
637                                        ',alien-type
638                                        ,@(deports))))
639             ;; Wrap that in a WITH-PINNED-OBJECTS to ensure the values
640             ;; the SAPs are taken for won't be moved by the GC. (If
641             ;; needed: some alien types won't need it).
642             (setf body `(maybe-with-pinned-objects ,(params) ,arg-types
643                           ,body))
644             ;; Around that handle any memory allocation that's needed.
645             ;; Mostly the DEPORT-ALLOC alien-type-methods are just an
646             ;; identity operation, but for example for deporting a
647             ;; Unicode string we need to convert the string into an
648             ;; octet array. This step needs to be done before the pinning
649             ;; to ensure we pin the right objects, so it can't be combined
650             ;; with the deporting.
651             ;; -- JES 2006-03-16
652             (loop for param in (params)
653                   for arg-type in arg-types
654                   do (setf body
655                            `(let ((,param (deport-alloc ,param ',arg-type)))
656                               ,body)))
657             (if (alien-values-type-p return-type)
658                 (collect ((temps) (results))
659                   (dolist (type (alien-values-type-values return-type))
660                     (let ((temp (gensym)))
661                       (temps temp)
662                       (results `(naturalize ,temp ',type))))
663                   (setf body
664                         `(multiple-value-bind ,(temps) ,body
665                            (values ,@(results)))))
666                 (setf body `(naturalize ,body ',return-type)))
667             ;; Remember this frame to make sure that we can get back
668             ;; to it later regardless of how the foreign stack looks
669             ;; like.
670             #!+:c-stack-is-control-stack
671             (when (policy node (= 3 alien-funcall-saves-fp-and-pc))
672               (setf body `(invoke-with-saved-fp-and-pc (lambda () ,body))))
673             (/noshow "returning from DEFTRANSFORM ALIEN-FUNCALL" (params) body)
674             `(lambda (function ,@(params))
675                (declare (optimize (let-conversion 3)))
676                ,body)))))))
677
678 (defoptimizer (%alien-funcall derive-type) ((function type &rest args))
679   (declare (ignore function args))
680   (unless (constant-lvar-p type)
681     (error "Something is broken."))
682   (let ((type (lvar-value type)))
683     (unless (alien-fun-type-p type)
684       (error "Something is broken."))
685     (values-specifier-type
686      (compute-alien-rep-type
687       (alien-fun-type-result-type type)
688       :result))))
689
690 (defoptimizer (%alien-funcall ltn-annotate)
691               ((function type &rest args) node ltn-policy)
692   (setf (basic-combination-info node) :funny)
693   (setf (node-tail-p node) nil)
694   (annotate-ordinary-lvar function)
695   (dolist (arg args)
696     (annotate-ordinary-lvar arg)))
697
698 ;;; We support both the stdcall and cdecl calling conventions on win32 by
699 ;;; resetting ESP after the foreign function returns. This way it works
700 ;;; correctly whether the party that is supposed to pop arguments from
701 ;;; the stack is the caller (cdecl) or the callee (stdcall).
702 (defoptimizer (%alien-funcall ir2-convert)
703               ((function type &rest args) call block)
704   (let ((type (if (constant-lvar-p type)
705                   (lvar-value type)
706                   (error "Something is broken.")))
707         (lvar (node-lvar call))
708         (args args)
709         #!+x86
710         (stack-pointer (make-stack-pointer-tn)))
711     (multiple-value-bind (nsp stack-frame-size arg-tns result-tns)
712         (make-call-out-tns type)
713       #!+x86
714       (progn
715         (vop set-fpu-word-for-c call block)
716         (vop current-stack-pointer call block stack-pointer))
717       (vop alloc-number-stack-space call block stack-frame-size nsp)
718       (dolist (tn arg-tns)
719         ;; On PPC, TN might be a list. This is used to indicate
720         ;; something special needs to happen. See below.
721         ;;
722         ;; FIXME: We should implement something better than this.
723         (let* ((first-tn (if (listp tn) (car tn) tn))
724                (arg (pop args))
725                (sc (tn-sc first-tn))
726                (scn (sc-number sc))
727                #!-(or x86 x86-64) (temp-tn (make-representation-tn
728                                             (tn-primitive-type first-tn) scn))
729                (move-arg-vops (svref (sc-move-arg-vops sc) scn)))
730           (aver arg)
731           (unless (= (length move-arg-vops) 1)
732             (error "no unique move-arg-vop for moves in SC ~S" (sc-name sc)))
733           #!+(or x86 x86-64) (emit-move-arg-template call
734                                                      block
735                                                      (first move-arg-vops)
736                                                      (lvar-tn call block arg)
737                                                      nsp
738                                                      first-tn)
739           #!-(or x86 x86-64) (progn
740                                (emit-move call
741                                           block
742                                           (lvar-tn call block arg)
743                                           temp-tn)
744                                (emit-move-arg-template call
745                                                        block
746                                                        (first move-arg-vops)
747                                                        temp-tn
748                                                        nsp
749                                                        first-tn))
750           #!+(and ppc darwin)
751           (when (listp tn)
752             ;; This means that we have a float arg that we need to
753             ;; also copy to some int regs. The list contains the TN
754             ;; for the float as well as the TNs to use for the int
755             ;; arg.
756             (destructuring-bind (float-tn i1-tn &optional i2-tn)
757                 tn
758               (if i2-tn
759                   (vop sb!vm::move-double-to-int-arg call block
760                        float-tn i1-tn i2-tn)
761                   (vop sb!vm::move-single-to-int-arg call block
762                        float-tn i1-tn))))))
763       (aver (null args))
764       (unless (listp result-tns)
765         (setf result-tns (list result-tns)))
766       (let ((arg-tns (flatten-list arg-tns)))
767         (vop* call-out call block
768               ((lvar-tn call block function)
769                (reference-tn-list arg-tns nil))
770               ((reference-tn-list result-tns t))))
771       #!-x86
772       (vop dealloc-number-stack-space call block stack-frame-size)
773       #!+x86
774       (progn
775         (vop reset-stack-pointer call block stack-pointer)
776         (vop set-fpu-word-for-lisp call block))
777       (move-lvar-result call block result-tns lvar))))