328cff652bfa2991c0a6f9057da8aecd95ec637b
[sbcl.git] / src / code / host-alieneval.lisp
1 ;;;; the part of the Alien implementation which is needed at
2 ;;;; cross-compilation time
3
4 ;;;; This software is part of the SBCL system. See the README file for
5 ;;;; more information.
6 ;;;;
7 ;;;; This software is derived from the CMU CL system, which was
8 ;;;; written at Carnegie Mellon University and released into the
9 ;;;; public domain. The software is in the public domain and is
10 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
11 ;;;; files for more information.
12
13 (in-package "SB!ALIEN")
14
15 (/show0 "host-alieneval.lisp 15")
16 \f
17 ;;;; utility functions
18
19 (defun align-offset (offset alignment)
20   (let ((extra (rem offset alignment)))
21     (if (zerop extra) offset (+ offset (- alignment extra)))))
22
23 (defun guess-alignment (bits)
24   (cond ((null bits) nil)
25         #!-(or (and x86 (not win32)) (and ppc darwin)) ((> bits 32) 64)
26         ((> bits 16) 32)
27         ((> bits 8) 16)
28         ((> bits 1) 8)
29         (t 1)))
30 \f
31 ;;;; ALIEN-TYPE-INFO stuff
32
33 (eval-when (#-sb-xc :compile-toplevel :execute :load-toplevel)
34
35 (defstruct (alien-type-class (:copier nil))
36   (name nil :type symbol)
37   (include nil :type (or null alien-type-class))
38   (unparse nil :type (or null function))
39   (type= nil :type (or null function))
40   (lisp-rep nil :type (or null function))
41   (alien-rep nil :type (or null function))
42   (extract-gen nil :type (or null function))
43   (deposit-gen nil :type (or null function))
44   (naturalize-gen nil :type (or null function))
45   (deport-gen nil :type (or null function))
46   (deport-alloc-gen nil :type (or null function))
47   (deport-pin-p nil :type (or null function))
48   ;; Cast?
49   (arg-tn nil :type (or null function))
50   (result-tn nil :type (or null function))
51   (subtypep nil :type (or null function)))
52 (def!method print-object ((type-class alien-type-class) stream)
53   (print-unreadable-object (type-class stream :type t)
54     (prin1 (alien-type-class-name type-class) stream)))
55
56 (defun alien-type-class-or-lose (name)
57   (or (gethash name *alien-type-classes*)
58       (error "no alien type class ~S" name)))
59
60 (defun create-alien-type-class-if-necessary (name include)
61   (let ((old (gethash name *alien-type-classes*))
62         (include (and include (alien-type-class-or-lose include))))
63     (if old
64         (setf (alien-type-class-include old) include)
65         (setf (gethash name *alien-type-classes*)
66               (make-alien-type-class :name name :include include)))))
67
68 (defparameter *method-slot-alist*
69   '((:unparse . alien-type-class-unparse)
70     (:type= . alien-type-class-type=)
71     (:subtypep . alien-type-class-subtypep)
72     (:lisp-rep . alien-type-class-lisp-rep)
73     (:alien-rep . alien-type-class-alien-rep)
74     (:extract-gen . alien-type-class-extract-gen)
75     (:deposit-gen . alien-type-class-deposit-gen)
76     (:naturalize-gen . alien-type-class-naturalize-gen)
77     (:deport-gen . alien-type-class-deport-gen)
78     (:deport-alloc-gen . alien-type-class-deport-alloc-gen)
79     (:deport-pin-p . alien-type-class-deport-pin-p)
80     ;; cast?
81     (:arg-tn . alien-type-class-arg-tn)
82     (:result-tn . alien-type-class-result-tn)))
83
84 (defun method-slot (method)
85   (cdr (or (assoc method *method-slot-alist*)
86            (error "no method ~S" method))))
87
88 ) ; EVAL-WHEN
89
90 ;;; We define a keyword "BOA" constructor so that we can reference the
91 ;;; slot names in init forms.
92 (def!macro define-alien-type-class ((name &key include include-args)
93                                     &rest slots)
94   (let ((defstruct-name (symbolicate "ALIEN-" name "-TYPE")))
95     (multiple-value-bind (include include-defstruct overrides)
96         (etypecase include
97           (null
98            (values nil 'alien-type nil))
99           (symbol
100            (values
101             include
102             (symbolicate "ALIEN-" include "-TYPE")
103             nil))
104           (list
105            (values
106             (car include)
107             (symbolicate "ALIEN-" (car include) "-TYPE")
108             (cdr include))))
109       `(progn
110          (eval-when (:compile-toplevel :load-toplevel :execute)
111            (create-alien-type-class-if-necessary ',name ',(or include 'root)))
112          (def!struct (,defstruct-name
113                         (:include ,include-defstruct
114                                   (class ',name)
115                                   ,@overrides)
116                         (:constructor
117                          ,(symbolicate "MAKE-" defstruct-name)
118                          (&key class bits alignment
119                                ,@(mapcar (lambda (x)
120                                            (if (atom x) x (car x)))
121                                          slots)
122                                ,@include-args
123                                ;; KLUDGE
124                                &aux (alignment (or alignment (guess-alignment bits))))))
125            ,@slots)))))
126
127 (def!macro define-alien-type-method ((class method) lambda-list &rest body)
128   (let ((defun-name (symbolicate class "-" method "-METHOD")))
129     `(progn
130        (defun ,defun-name ,lambda-list
131          ,@body)
132        (setf (,(method-slot method) (alien-type-class-or-lose ',class))
133              #',defun-name))))
134
135 (def!macro invoke-alien-type-method (method type &rest args)
136   (let ((slot (method-slot method)))
137     (once-only ((type type))
138       `(funcall (do ((class (alien-type-class-or-lose (alien-type-class ,type))
139                             (alien-type-class-include class)))
140                     ((null class)
141                      (error "method ~S not defined for ~S"
142                             ',method (alien-type-class ,type)))
143                   (let ((fn (,slot class)))
144                     (when fn
145                       (return fn))))
146                 ,type ,@args))))
147 \f
148 ;;;; type parsing and unparsing
149
150 ;;; CMU CL used COMPILER-LET to bind *AUXILIARY-TYPE-DEFINITIONS*, and
151 ;;; COMPILER-LET is no longer supported by ANSI or SBCL. Instead, we
152 ;;; follow the suggestion in CLTL2 of using SYMBOL-MACROLET to achieve
153 ;;; a similar effect.
154 (eval-when (#-sb-xc :compile-toplevel :load-toplevel :execute)
155   (defun auxiliary-type-definitions (env)
156     (multiple-value-bind (result expanded-p)
157         (sb!xc:macroexpand '&auxiliary-type-definitions& env)
158       (if expanded-p
159           result
160           ;; This is like having the global symbol-macro definition be
161           ;; NIL, but global symbol-macros make me vaguely queasy, so
162           ;; I do it this way instead.
163           nil))))
164
165 ;;; Process stuff in a new scope.
166 (def!macro with-auxiliary-alien-types (env &body body)
167   ``(symbol-macrolet ((&auxiliary-type-definitions&
168                        ,(append *new-auxiliary-types*
169                                 (auxiliary-type-definitions ,env))))
170       ,(let ((*new-auxiliary-types* nil))
171          ,@body)))
172
173 ;;; Parse TYPE as an alien type specifier and return the resultant
174 ;;; ALIEN-TYPE structure.
175 (defun parse-alien-type (type env)
176   (declare (type (or sb!kernel:lexenv null) env))
177   (if (consp type)
178       (let ((translator (info :alien-type :translator (car type))))
179         (unless translator
180           (error "unknown alien type: ~S" type))
181         (funcall translator type env))
182       (ecase (info :alien-type :kind type)
183         (:primitive
184          (let ((translator (info :alien-type :translator type)))
185            (unless translator
186              (error "no translator for primitive alien type ~S" type))
187            (funcall translator (list type) env)))
188         (:defined
189          (or (info :alien-type :definition type)
190              (error "no definition for alien type ~S" type)))
191         (:unknown
192          (error "unknown alien type: ~S" type)))))
193
194 (defun auxiliary-alien-type (kind name env)
195   (declare (type (or sb!kernel:lexenv null) env))
196   (flet ((aux-defn-matches (x)
197            (and (eq (first x) kind) (eq (second x) name))))
198     (let ((in-auxiliaries
199            (or (find-if #'aux-defn-matches *new-auxiliary-types*)
200                (find-if #'aux-defn-matches (auxiliary-type-definitions env)))))
201       (if in-auxiliaries
202           (values (third in-auxiliaries) t)
203           (ecase kind
204             (:struct
205              (info :alien-type :struct name))
206             (:union
207              (info :alien-type :union name))
208             (:enum
209              (info :alien-type :enum name)))))))
210
211 (defun (setf auxiliary-alien-type) (new-value kind name env)
212   (declare (type (or sb!kernel:lexenv null) env))
213   (flet ((aux-defn-matches (x)
214            (and (eq (first x) kind) (eq (second x) name))))
215     (when (find-if #'aux-defn-matches *new-auxiliary-types*)
216       (error "attempt to multiply define ~A ~S" kind name))
217     (when (find-if #'aux-defn-matches (auxiliary-type-definitions env))
218       (error "attempt to shadow definition of ~A ~S" kind name)))
219   (push (list kind name new-value) *new-auxiliary-types*)
220   new-value)
221
222 (defun verify-local-auxiliaries-okay ()
223   (dolist (info *new-auxiliary-types*)
224     (destructuring-bind (kind name defn) info
225       (declare (ignore defn))
226       (when (ecase kind
227               (:struct
228                (info :alien-type :struct name))
229               (:union
230                (info :alien-type :union name))
231               (:enum
232                (info :alien-type :enum name)))
233         (error "attempt to shadow definition of ~A ~S" kind name)))))
234
235 (defun unparse-alien-type (type)
236   #!+sb-doc
237   "Convert the alien-type structure TYPE back into a list specification of
238    the type."
239   (declare (type alien-type type))
240   (let ((*record-types-already-unparsed* nil))
241     (%unparse-alien-type type)))
242
243 ;;; Does all the work of UNPARSE-ALIEN-TYPE. It's separate because we
244 ;;; need to recurse inside the binding of
245 ;;; *RECORD-TYPES-ALREADY-UNPARSED*.
246 (defun %unparse-alien-type (type)
247   (invoke-alien-type-method :unparse type))
248 \f
249 ;;;; alien type defining stuff
250
251 (def!macro define-alien-type-translator (name lambda-list &body body)
252   (with-unique-names (whole env)
253     (let ((defun-name (symbolicate "ALIEN-" name "-TYPE-TRANSLATOR")))
254       (multiple-value-bind (body decls docs)
255           (sb!kernel:parse-defmacro lambda-list whole body name
256                                     'define-alien-type-translator
257                                     :environment env)
258         `(eval-when (:compile-toplevel :load-toplevel :execute)
259            (defun ,defun-name (,whole ,env)
260              (declare (ignorable ,env))
261              ,@decls
262              (block ,name
263                ,body))
264            (%define-alien-type-translator ',name #',defun-name ,docs))))))
265
266 (eval-when (#-sb-xc :compile-toplevel :load-toplevel :execute)
267   (defun %define-alien-type-translator (name translator docs)
268     (declare (ignore docs))
269     (setf (info :alien-type :kind name) :primitive)
270     (setf (info :alien-type :translator name) translator)
271     (clear-info :alien-type :definition name)
272     #+nil
273     (setf (fdocumentation name 'alien-type) docs)
274     name))
275
276 (def!macro define-alien-type (name type &environment env)
277   #!+sb-doc
278   "Define the alien type NAME to be equivalent to TYPE. Name may be NIL for
279    STRUCT and UNION types, in which case the name is taken from the type
280    specifier."
281   (with-auxiliary-alien-types env
282     (let ((alien-type (parse-alien-type type env)))
283       `(eval-when (:compile-toplevel :load-toplevel :execute)
284          ,@(when *new-auxiliary-types*
285              `((%def-auxiliary-alien-types ',*new-auxiliary-types*)))
286          ,@(when name
287              `((%define-alien-type ',name ',alien-type)))))))
288 (def!macro def-alien-type (&rest rest)
289   (deprecation-warning 'def-alien-type 'define-alien-type)
290   `(define-alien-type ,@rest))
291
292 (eval-when (#-sb-xc :compile-toplevel :load-toplevel :execute)
293   (defun %def-auxiliary-alien-types (types)
294     (dolist (info types)
295       ;; Clear up the type we're about to define from the toplevel
296       ;; *new-auxiliary-types* (local scopes take care of themselves).
297       ;; Unless this is done we never actually get back the full type
298       ;; from INFO, since the *new-auxiliary-types* have precendence.
299       (setf *new-auxiliary-types*
300             (remove info *new-auxiliary-types*
301                     :test (lambda (a b)
302                             (and (eq (first a) (first b))
303                                  (eq (second a) (second b))))))
304       (destructuring-bind (kind name defn) info
305         (macrolet ((frob (kind)
306                          `(let ((old (info :alien-type ,kind name)))
307                             (unless (or (null old) (alien-type-= old defn))
308                               (warn
309                                "redefining ~A ~S to be:~%  ~S,~%was:~%  ~S"
310                                kind name defn old))
311                             (setf (info :alien-type ,kind name) defn))))
312           (ecase kind
313             (:struct (frob :struct))
314             (:union (frob :union))
315             (:enum (frob :enum)))))))
316   (defun %define-alien-type (name new)
317     (ecase (info :alien-type :kind name)
318       (:primitive
319        (error "~S is a built-in alien type." name))
320       (:defined
321        (let ((old (info :alien-type :definition name)))
322          (unless (or (null old) (alien-type-= new old))
323            (warn "redefining ~S to be:~%  ~S,~%was~%  ~S"
324                  name
325                  (unparse-alien-type new)
326                  (unparse-alien-type old)))))
327       (:unknown))
328     (setf (info :alien-type :definition name) new)
329     (setf (info :alien-type :kind name) :defined)
330     name))
331 \f
332 ;;;; the root alien type
333
334 (eval-when (:compile-toplevel :load-toplevel :execute)
335   (create-alien-type-class-if-necessary 'root nil))
336
337 (def!struct (alien-type
338              (:make-load-form-fun sb!kernel:just-dump-it-normally)
339              (:constructor make-alien-type (&key class bits alignment
340                                             &aux (alignment (or alignment (guess-alignment bits))))))
341   (class 'root :type symbol)
342   (bits nil :type (or null unsigned-byte))
343   (alignment nil :type (or null unsigned-byte)))
344 (def!method print-object ((type alien-type) stream)
345   (print-unreadable-object (type stream :type t)
346     (prin1 (unparse-alien-type type) stream)))
347 \f
348 ;;;; the SAP type
349
350 (define-alien-type-class (system-area-pointer))
351
352 (define-alien-type-translator system-area-pointer ()
353   (make-alien-system-area-pointer-type
354    :bits #!-alpha sb!vm:n-word-bits #!+alpha 64))
355
356 (define-alien-type-method (system-area-pointer :unparse) (type)
357   (declare (ignore type))
358   'system-area-pointer)
359
360 (define-alien-type-method (system-area-pointer :lisp-rep) (type)
361   (declare (ignore type))
362   'system-area-pointer)
363
364 (define-alien-type-method (system-area-pointer :alien-rep) (type)
365   (declare (ignore type))
366   'system-area-pointer)
367
368 (define-alien-type-method (system-area-pointer :naturalize-gen) (type alien)
369   (declare (ignore type))
370   alien)
371
372 (define-alien-type-method (system-area-pointer :deport-gen) (type object)
373   (declare (ignore type))
374   (/noshow "doing alien type method SYSTEM-AREA-POINTER :DEPORT-GEN" object)
375   object)
376
377 (define-alien-type-method (system-area-pointer :extract-gen) (type sap offset)
378   (declare (ignore type))
379   `(sap-ref-sap ,sap (/ ,offset sb!vm:n-byte-bits)))
380 \f
381 ;;;; the ALIEN-VALUE type
382
383 (define-alien-type-class (alien-value :include system-area-pointer))
384
385 (define-alien-type-method (alien-value :lisp-rep) (type)
386   (declare (ignore type))
387   nil)
388
389 (define-alien-type-method (alien-value :naturalize-gen) (type alien)
390   `(%sap-alien ,alien ',type))
391
392 (define-alien-type-method (alien-value :deport-gen) (type value)
393   (declare (ignore type))
394   (/noshow "doing alien type method ALIEN-VALUE :DEPORT-GEN" value)
395   `(alien-sap ,value))
396 \f
397 ;;; HEAP-ALIEN-INFO -- defstruct.
398 ;;;
399 ;;; Information describing a heap-allocated alien.
400 (def!struct (heap-alien-info
401              (:make-load-form-fun sb!kernel:just-dump-it-normally))
402   ;; The type of this alien.
403   (type (missing-arg) :type alien-type)
404   ;; The form to evaluate to produce the SAP pointing to where in the heap
405   ;; it is.
406   (sap-form (missing-arg)))
407 (def!method print-object ((info heap-alien-info) stream)
408   (print-unreadable-object (info stream :type t)
409     (funcall (formatter "~S ~S")
410              stream
411              (heap-alien-info-sap-form info)
412              (unparse-alien-type (heap-alien-info-type info)))))
413 \f
414 ;;;; Interfaces to the different methods
415
416 (defun alien-type-= (type1 type2)
417   #!+sb-doc
418   "Return T iff TYPE1 and TYPE2 describe equivalent alien types."
419   (or (eq type1 type2)
420       (and (eq (alien-type-class type1)
421                (alien-type-class type2))
422            (invoke-alien-type-method :type= type1 type2))))
423
424 (defun alien-subtype-p (type1 type2)
425   #!+sb-doc
426   "Return T iff the alien type TYPE1 is a subtype of TYPE2. Currently, the
427    only supported subtype relationships are is that any pointer type is a
428    subtype of (* t), and any array type first dimension will match
429    (array <eltype> nil ...). Otherwise, the two types have to be
430    ALIEN-TYPE-=."
431   (or (eq type1 type2)
432       (invoke-alien-type-method :subtypep type1 type2)))
433
434 (defun compute-naturalize-lambda (type)
435   `(lambda (alien ignore)
436      (declare (ignore ignore))
437      ,(invoke-alien-type-method :naturalize-gen type 'alien)))
438
439 (defun compute-deport-lambda (type)
440   (declare (type alien-type type))
441   (/noshow "entering COMPUTE-DEPORT-LAMBDA" type)
442   (multiple-value-bind (form value-type)
443       (invoke-alien-type-method :deport-gen type 'value)
444     `(lambda (value ignore)
445        (declare (type ,(or value-type
446                            (compute-lisp-rep-type type)
447                            `(alien ,type))
448                       value)
449                 (ignore ignore))
450        ,form)))
451
452 (defun compute-deport-alloc-lambda (type)
453   `(lambda (value ignore)
454      (declare (ignore ignore))
455      ,(invoke-alien-type-method :deport-alloc-gen type 'value)))
456
457 (defun compute-extract-lambda (type)
458   `(lambda (sap offset ignore)
459      (declare (type system-area-pointer sap)
460               (type unsigned-byte offset)
461               (ignore ignore))
462      (naturalize ,(invoke-alien-type-method :extract-gen type 'sap 'offset)
463                  ',type)))
464
465 (def!macro maybe-with-pinned-objects (variables types &body body)
466   (let ((pin-variables
467          ;; Only pin things on x86/x86-64, since on non-conservative
468          ;; gcs it'd imply disabling the GC. Which is something we
469          ;; don't want to do every time we're calling to C.
470          #+(or x86 x86-64)
471          (loop for variable in variables
472                for type in types
473                when (invoke-alien-type-method :deport-pin-p type)
474                collect variable)))
475     (if pin-variables
476         `(with-pinned-objects ,pin-variables
477            ,@body)
478         `(progn
479            ,@body))))
480
481 (defun compute-deposit-lambda (type)
482   (declare (type alien-type type))
483   `(lambda (sap offset ignore value)
484      (declare (type system-area-pointer sap)
485               (type unsigned-byte offset)
486               (ignore ignore))
487      (let ((alloc-tmp (deport-alloc value ',type)))
488        (maybe-with-pinned-objects (alloc-tmp) (,type)
489          (let ((value (deport alloc-tmp  ',type)))
490            ,(invoke-alien-type-method :deposit-gen type 'sap 'offset 'value)
491            ;; Note: the reason we don't just return the pre-deported value
492            ;; is because that would inhibit any (deport (naturalize ...))
493            ;; optimizations that might have otherwise happen. Re-naturalizing
494            ;; the value might cause extra consing, but is flushable, so probably
495            ;; results in better code.
496            (naturalize value ',type))))))
497
498 (defun compute-lisp-rep-type (type)
499   (invoke-alien-type-method :lisp-rep type))
500
501 (defun compute-alien-rep-type (type)
502   (invoke-alien-type-method :alien-rep type))
503 \f
504 ;;;; default methods
505
506 (define-alien-type-method (root :unparse) (type)
507   `(<unknown-alien-type> ,(type-of type)))
508
509 (define-alien-type-method (root :type=) (type1 type2)
510   (declare (ignore type1 type2))
511   t)
512
513 (define-alien-type-method (root :subtypep) (type1 type2)
514   (alien-type-= type1 type2))
515
516 (define-alien-type-method (root :lisp-rep) (type)
517   (declare (ignore type))
518   nil)
519
520 (define-alien-type-method (root :alien-rep) (type)
521   (declare (ignore type))
522   '*)
523
524 (define-alien-type-method (root :naturalize-gen) (type alien)
525   (declare (ignore alien))
526   (error "cannot represent ~S typed aliens" type))
527
528 (define-alien-type-method (root :deport-gen) (type object)
529   (declare (ignore object))
530   (error "cannot represent ~S typed aliens" type))
531
532 (define-alien-type-method (root :deport-alloc-gen) (type object)
533   (declare (ignore type))
534   object)
535
536 (define-alien-type-method (root :deport-pin-p) (type)
537   (declare (ignore type))
538   ;; Override this method to return T for classes which take a SAP to a
539   ;; GCable lisp object when deporting.
540   nil)
541
542 (define-alien-type-method (root :extract-gen) (type sap offset)
543   (declare (ignore sap offset))
544   (error "cannot represent ~S typed aliens" type))
545
546 (define-alien-type-method (root :deposit-gen) (type sap offset value)
547   `(setf ,(invoke-alien-type-method :extract-gen type sap offset) ,value))
548
549 (define-alien-type-method (root :arg-tn) (type state)
550   (declare (ignore state))
551   (error "Aliens of type ~S cannot be passed as arguments to CALL-OUT."
552          (unparse-alien-type type)))
553
554 (define-alien-type-method (root :result-tn) (type state)
555   (declare (ignore state))
556   (error "Aliens of type ~S cannot be returned from CALL-OUT."
557          (unparse-alien-type type)))
558 \f
559 ;;;; the INTEGER type
560
561 (define-alien-type-class (integer)
562   (signed t :type (member t nil)))
563
564 (define-alien-type-translator signed (&optional (bits sb!vm:n-word-bits))
565   (make-alien-integer-type :bits bits))
566
567 (define-alien-type-translator integer (&optional (bits sb!vm:n-word-bits))
568   (make-alien-integer-type :bits bits))
569
570 (define-alien-type-translator unsigned (&optional (bits sb!vm:n-word-bits))
571   (make-alien-integer-type :bits bits :signed nil))
572
573 (define-alien-type-method (integer :unparse) (type)
574   (list (if (alien-integer-type-signed type) 'signed 'unsigned)
575         (alien-integer-type-bits type)))
576
577 (define-alien-type-method (integer :type=) (type1 type2)
578   (and (eq (alien-integer-type-signed type1)
579            (alien-integer-type-signed type2))
580        (= (alien-integer-type-bits type1)
581           (alien-integer-type-bits type2))))
582
583 (define-alien-type-method (integer :lisp-rep) (type)
584   (list (if (alien-integer-type-signed type) 'signed-byte 'unsigned-byte)
585         (alien-integer-type-bits type)))
586
587 (define-alien-type-method (integer :alien-rep) (type)
588   (list (if (alien-integer-type-signed type) 'signed-byte 'unsigned-byte)
589         (alien-integer-type-bits type)))
590
591 (define-alien-type-method (integer :naturalize-gen) (type alien)
592   (declare (ignore type))
593   alien)
594
595 (define-alien-type-method (integer :deport-gen) (type value)
596   (declare (ignore type))
597   value)
598
599 (define-alien-type-method (integer :extract-gen) (type sap offset)
600   (declare (type alien-integer-type type))
601   (let ((ref-fun
602          (if (alien-integer-type-signed type)
603           (case (alien-integer-type-bits type)
604             (8 'signed-sap-ref-8)
605             (16 'signed-sap-ref-16)
606             (32 'signed-sap-ref-32)
607             (64 'signed-sap-ref-64))
608           (case (alien-integer-type-bits type)
609             (8 'sap-ref-8)
610             (16 'sap-ref-16)
611             (32 'sap-ref-32)
612             (64 'sap-ref-64)))))
613     (if ref-fun
614         `(,ref-fun ,sap (/ ,offset sb!vm:n-byte-bits))
615         (error "cannot extract ~W-bit integers"
616                (alien-integer-type-bits type)))))
617 \f
618 ;;;; the BOOLEAN type
619
620 (define-alien-type-class (boolean :include integer :include-args (signed)))
621
622 ;;; FIXME: Check to make sure that we aren't attaching user-readable
623 ;;; stuff to CL:BOOLEAN in any way which impairs ANSI compliance.
624 (define-alien-type-translator boolean (&optional (bits sb!vm:n-word-bits))
625   (make-alien-boolean-type :bits bits :signed nil))
626
627 (define-alien-type-method (boolean :unparse) (type)
628   `(boolean ,(alien-boolean-type-bits type)))
629
630 (define-alien-type-method (boolean :lisp-rep) (type)
631   (declare (ignore type))
632   `(member t nil))
633
634 (define-alien-type-method (boolean :naturalize-gen) (type alien)
635   (declare (ignore type))
636   `(not (zerop ,alien)))
637
638 (define-alien-type-method (boolean :deport-gen) (type value)
639   (declare (ignore type))
640   `(if ,value 1 0))
641 \f
642 ;;;; the ENUM type
643
644 (define-alien-type-class (enum :include (integer (bits 32))
645                                :include-args (signed))
646   name          ; name of this enum (if any)
647   from          ; alist from symbols to integers
648   to            ; alist or vector from integers to symbols
649   kind          ; kind of from mapping, :VECTOR or :ALIST
650   offset)       ; offset to add to value for :VECTOR from mapping
651
652 (define-alien-type-translator enum (&whole
653                                  type name
654                                  &rest mappings
655                                  &environment env)
656   (cond (mappings
657          (let ((result (parse-enum name mappings)))
658            (when name
659              (multiple-value-bind (old old-p)
660                  (auxiliary-alien-type :enum name env)
661                (when old-p
662                  (unless (alien-type-= result old)
663                    (warn "redefining alien enum ~S" name))))
664              (setf (auxiliary-alien-type :enum name env) result))
665            result))
666         (name
667          (multiple-value-bind (result found)
668              (auxiliary-alien-type :enum name env)
669            (unless found
670              (error "unknown enum type: ~S" name))
671            result))
672         (t
673          (error "empty enum type: ~S" type))))
674
675 (defun parse-enum (name elements)
676   (when (null elements)
677     (error "An enumeration must contain at least one element."))
678   (let ((min nil)
679         (max nil)
680         (from-alist ())
681         (prev -1))
682     (declare (list from-alist))
683     (dolist (el elements)
684       (multiple-value-bind (sym val)
685           (if (listp el)
686               (values (first el) (second el))
687               (values el (1+ prev)))
688         (setf prev val)
689         (unless (symbolp sym)
690           (error "The enumeration element ~S is not a symbol." sym))
691         (unless (integerp val)
692           (error "The element value ~S is not an integer." val))
693         (unless (and max (> max val)) (setq max val))
694         (unless (and min (< min val)) (setq min val))
695         (when (rassoc val from-alist)
696           (style-warn "The element value ~S is used more than once." val))
697         (when (assoc sym from-alist :test #'eq)
698           (error "The enumeration element ~S is used more than once." sym))
699         (push (cons sym val) from-alist)))
700     (let* ((signed (minusp min))
701            (min-bits (if signed
702                          (1+ (max (integer-length min)
703                                   (integer-length max)))
704                          (integer-length max))))
705       (when (> min-bits 32)
706         (error "can't represent enums needing more than 32 bits"))
707       (setf from-alist (sort from-alist #'< :key #'cdr))
708       (cond
709        ;; If range is at least 20% dense, use vector mapping. Crossover
710        ;; point solely on basis of space would be 25%. Vector mapping
711        ;; is always faster, so give the benefit of the doubt.
712        ((< 0.2 (/ (float (length from-alist)) (float (1+ (- max min)))))
713         ;; If offset is small and ignorable, ignore it to save time.
714         (when (< 0 min 10) (setq min 0))
715         (let ((to (make-array (1+ (- max min)))))
716           (dolist (el from-alist)
717             (setf (svref to (- (cdr el) min)) (car el)))
718           (make-alien-enum-type :name name :signed signed
719                                 :from from-alist :to to :kind
720                                 :vector :offset (- min))))
721        (t
722         (make-alien-enum-type :name name :signed signed
723                               :from from-alist
724                               :to (mapcar (lambda (x) (cons (cdr x) (car x)))
725                                           from-alist)
726                               :kind :alist))))))
727
728 (define-alien-type-method (enum :unparse) (type)
729   `(enum ,(alien-enum-type-name type)
730          ,@(let ((prev -1))
731              (mapcar (lambda (mapping)
732                        (let ((sym (car mapping))
733                              (value (cdr mapping)))
734                          (prog1
735                              (if (= (1+ prev) value)
736                                  sym
737                                  `(,sym ,value))
738                            (setf prev value))))
739                      (alien-enum-type-from type)))))
740
741 (define-alien-type-method (enum :type=) (type1 type2)
742   (and (eq (alien-enum-type-name type1)
743            (alien-enum-type-name type2))
744        (equal (alien-enum-type-from type1)
745               (alien-enum-type-from type2))))
746
747 (define-alien-type-method (enum :lisp-rep) (type)
748   `(member ,@(mapcar #'car (alien-enum-type-from type))))
749
750 (define-alien-type-method (enum :naturalize-gen) (type alien)
751   (ecase (alien-enum-type-kind type)
752     (:vector
753      `(svref ',(alien-enum-type-to type)
754              (+ ,alien ,(alien-enum-type-offset type))))
755     (:alist
756      `(ecase ,alien
757         ,@(mapcar (lambda (mapping)
758                     `(,(car mapping) ',(cdr mapping)))
759                   (alien-enum-type-to type))))))
760
761 (define-alien-type-method (enum :deport-gen) (type value)
762   `(ecase ,value
763      ,@(mapcar (lambda (mapping)
764                  `(,(car mapping) ,(cdr mapping)))
765                (alien-enum-type-from type))))
766 \f
767 ;;;; the FLOAT types
768
769 (define-alien-type-class (float)
770   (type (missing-arg) :type symbol))
771
772 (define-alien-type-method (float :unparse) (type)
773   (alien-float-type-type type))
774
775 (define-alien-type-method (float :lisp-rep) (type)
776   (alien-float-type-type type))
777
778 (define-alien-type-method (float :alien-rep) (type)
779   (alien-float-type-type type))
780
781 (define-alien-type-method (float :naturalize-gen) (type alien)
782   (declare (ignore type))
783   alien)
784
785 (define-alien-type-method (float :deport-gen) (type value)
786   (declare (ignore type))
787   value)
788
789 (define-alien-type-class (single-float :include (float (bits 32))
790                                        :include-args (type)))
791
792 (define-alien-type-translator single-float ()
793   (make-alien-single-float-type :type 'single-float))
794
795 (define-alien-type-method (single-float :extract-gen) (type sap offset)
796   (declare (ignore type))
797   `(sap-ref-single ,sap (/ ,offset sb!vm:n-byte-bits)))
798
799 (define-alien-type-class (double-float :include (float (bits 64))
800                                        :include-args (type)))
801
802 (define-alien-type-translator double-float ()
803   (make-alien-double-float-type :type 'double-float))
804
805 (define-alien-type-method (double-float :extract-gen) (type sap offset)
806   (declare (ignore type))
807   `(sap-ref-double ,sap (/ ,offset sb!vm:n-byte-bits)))
808
809 \f
810 ;;;; the POINTER type
811
812 (define-alien-type-class (pointer :include (alien-value (bits
813                                                          #!-alpha
814                                                          sb!vm:n-word-bits
815                                                          #!+alpha 64)))
816   (to nil :type (or alien-type null)))
817
818 (define-alien-type-translator * (to &environment env)
819   (make-alien-pointer-type :to (if (eq to t) nil (parse-alien-type to env))))
820
821 (define-alien-type-method (pointer :unparse) (type)
822   (let ((to (alien-pointer-type-to type)))
823     `(* ,(if to
824              (%unparse-alien-type to)
825              t))))
826
827 (define-alien-type-method (pointer :type=) (type1 type2)
828   (let ((to1 (alien-pointer-type-to type1))
829         (to2 (alien-pointer-type-to type2)))
830     (if to1
831         (if to2
832             (alien-type-= to1 to2)
833             nil)
834         (null to2))))
835
836 (define-alien-type-method (pointer :subtypep) (type1 type2)
837   (and (alien-pointer-type-p type2)
838        (let ((to1 (alien-pointer-type-to type1))
839              (to2 (alien-pointer-type-to type2)))
840          (if to1
841              (if to2
842                  (alien-subtype-p to1 to2)
843                  t)
844              (null to2)))))
845
846 (define-alien-type-method (pointer :deport-gen) (type value)
847   (/noshow "doing alien type method POINTER :DEPORT-GEN" type value)
848   (values
849    ;; FIXME: old version, highlighted a bug in xc optimization
850    `(etypecase ,value
851       (null
852        (int-sap 0))
853       (system-area-pointer
854        ,value)
855       ((alien ,type)
856        (alien-sap ,value)))
857    ;; new version, works around bug in xc optimization
858    #+nil
859    `(etypecase ,value
860       (system-area-pointer
861        ,value)
862       ((alien ,type)
863        (alien-sap ,value))
864       (null
865        (int-sap 0)))
866    `(or null system-area-pointer (alien ,type))))
867 \f
868 ;;;; the MEM-BLOCK type
869
870 (define-alien-type-class (mem-block :include alien-value))
871
872 (define-alien-type-method (mem-block :extract-gen) (type sap offset)
873   (declare (ignore type))
874   `(sap+ ,sap (/ ,offset sb!vm:n-byte-bits)))
875
876 (define-alien-type-method (mem-block :deposit-gen) (type sap offset value)
877   (let ((bytes (truncate (alien-mem-block-type-bits type) sb!vm:n-byte-bits)))
878     (unless bytes
879       (error "can't deposit aliens of type ~S (unknown size)" type))
880     `(sb!kernel:system-area-ub8-copy ,value 0 ,sap ,offset ',bytes)))
881 \f
882 ;;;; the ARRAY type
883
884 (define-alien-type-class (array :include mem-block)
885   (element-type (missing-arg) :type alien-type)
886   (dimensions (missing-arg) :type list))
887
888 (define-alien-type-translator array (ele-type &rest dims &environment env)
889
890   (when dims
891     (unless (typep (first dims) '(or index null))
892       (error "The first dimension is not a non-negative fixnum or NIL: ~S"
893              (first dims)))
894     (let ((loser (find-if-not (lambda (x) (typep x 'index))
895                               (rest dims))))
896       (when loser
897         (error "A dimension is not a non-negative fixnum: ~S" loser))))
898
899   (let ((parsed-ele-type (parse-alien-type ele-type env)))
900     (make-alien-array-type
901      :element-type parsed-ele-type
902      :dimensions dims
903      :alignment (alien-type-alignment parsed-ele-type)
904      :bits (if (and (alien-type-bits parsed-ele-type)
905                     (every #'integerp dims))
906                (* (align-offset (alien-type-bits parsed-ele-type)
907                                 (alien-type-alignment parsed-ele-type))
908                   (reduce #'* dims))))))
909
910 (define-alien-type-method (array :unparse) (type)
911   `(array ,(%unparse-alien-type (alien-array-type-element-type type))
912           ,@(alien-array-type-dimensions type)))
913
914 (define-alien-type-method (array :type=) (type1 type2)
915   (and (equal (alien-array-type-dimensions type1)
916               (alien-array-type-dimensions type2))
917        (alien-type-= (alien-array-type-element-type type1)
918                      (alien-array-type-element-type type2))))
919
920 (define-alien-type-method (array :subtypep) (type1 type2)
921   (and (alien-array-type-p type2)
922        (let ((dim1 (alien-array-type-dimensions type1))
923              (dim2 (alien-array-type-dimensions type2)))
924          (and (= (length dim1) (length dim2))
925               (or (and dim2
926                        (null (car dim2))
927                        (equal (cdr dim1) (cdr dim2)))
928                   (equal dim1 dim2))
929               (alien-subtype-p (alien-array-type-element-type type1)
930                                (alien-array-type-element-type type2))))))
931 \f
932 ;;;; the RECORD type
933
934 (def!struct (alien-record-field
935              (:make-load-form-fun sb!kernel:just-dump-it-normally))
936   (name (missing-arg) :type symbol)
937   (type (missing-arg) :type alien-type)
938   (bits nil :type (or unsigned-byte null))
939   (offset 0 :type unsigned-byte))
940 (def!method print-object ((field alien-record-field) stream)
941   (print-unreadable-object (field stream :type t)
942     (format stream
943             "~S ~S~@[:~D~]"
944             (alien-record-field-type field)
945             (alien-record-field-name field)
946             (alien-record-field-bits field))))
947
948 (define-alien-type-class (record :include mem-block)
949   (kind :struct :type (member :struct :union))
950   (name nil :type (or symbol null))
951   (fields nil :type list))
952
953 (define-alien-type-translator struct (name &rest fields &environment env)
954   (parse-alien-record-type :struct name fields env))
955
956 (define-alien-type-translator union (name &rest fields &environment env)
957   (parse-alien-record-type :union name fields env))
958
959 ;;; FIXME: This is really pretty horrible: we avoid creating new
960 ;;; ALIEN-RECORD-TYPE objects when a live one is flitting around the
961 ;;; system already. This way forwrd-references sans fields get get
962 ;;; "updated" for free to contain the field info. Maybe rename
963 ;;; MAKE-ALIEN-RECORD-TYPE to %MAKE-ALIEN-RECORD-TYPE and use
964 ;;; ENSURE-ALIEN-RECORD-TYPE instead. --NS 20040729
965 (defun parse-alien-record-type (kind name fields env)
966   (declare (type (or sb!kernel:lexenv null) env))
967   (cond (fields
968          (let* ((old (and name (auxiliary-alien-type kind name env)))
969                 (old-fields (and old (alien-record-type-fields old))))
970            ;; KLUDGE: We can't easily compare the new fields
971            ;; against the old fields, since the old fields have
972            ;; already been parsed into an internal
973            ;; representation, so we just punt, assuming that
974            ;; they're consistent. -- WHN 200000505
975            #|
976              (unless (equal fields old-fields)
977                ;; FIXME: Perhaps this should be a warning, and we
978                ;; should overwrite the old definition and proceed?
979                (error "mismatch in fields for ~S~%  old ~S~%  new ~S"
980                       name old-fields fields))
981            |#
982            (if old-fields
983                old
984                (let ((type (or old (make-alien-record-type :name name :kind kind))))
985                  (when (and name (not old))
986                    (setf (auxiliary-alien-type kind name env) type))
987                  (parse-alien-record-fields type fields env)
988                  type))))
989         (name
990          (or (auxiliary-alien-type kind name env)
991              (setf (auxiliary-alien-type kind name env)
992                    (make-alien-record-type :name name :kind kind))))
993         (t
994          (make-alien-record-type :kind kind))))
995
996 ;;; This is used by PARSE-ALIEN-TYPE to parse the fields of struct and
997 ;;; union types. RESULT holds the record type we are paring the fields
998 ;;; of, and FIELDS is the list of field specifications.
999 (defun parse-alien-record-fields (result fields env)
1000   (declare (type alien-record-type result)
1001            (type list fields))
1002   (let ((total-bits 0)
1003         (overall-alignment 1)
1004         (parsed-fields nil))
1005     (dolist (field fields)
1006       (destructuring-bind (var type &key alignment) field
1007         (let* ((field-type (parse-alien-type type env))
1008                (bits (alien-type-bits field-type))
1009                (parsed-field
1010                 (make-alien-record-field :type field-type
1011                                          :name var)))
1012           (unless alignment
1013             (setf alignment (alien-type-alignment field-type)))
1014           (push parsed-field parsed-fields)
1015           (when (null bits)
1016             (error "unknown size: ~S" (unparse-alien-type field-type)))
1017           (when (null alignment)
1018             (error "unknown alignment: ~S" (unparse-alien-type field-type)))
1019           (setf overall-alignment (max overall-alignment alignment))
1020           (ecase (alien-record-type-kind result)
1021             (:struct
1022              (let ((offset (align-offset total-bits alignment)))
1023                (setf (alien-record-field-offset parsed-field) offset)
1024                (setf total-bits (+ offset bits))))
1025             (:union
1026              (setf total-bits (max total-bits bits)))))))
1027     (let ((new (nreverse parsed-fields)))
1028       (setf (alien-record-type-fields result) new))
1029     (setf (alien-record-type-alignment result) overall-alignment)
1030     (setf (alien-record-type-bits result)
1031           (align-offset total-bits overall-alignment))))
1032
1033 (define-alien-type-method (record :unparse) (type)
1034   `(,(case (alien-record-type-kind type)
1035        (:struct 'struct)
1036        (:union 'union)
1037        (t '???))
1038     ,(alien-record-type-name type)
1039     ,@(unless (member type *record-types-already-unparsed* :test #'eq)
1040         (push type *record-types-already-unparsed*)
1041         (mapcar (lambda (field)
1042                   `(,(alien-record-field-name field)
1043                     ,(%unparse-alien-type (alien-record-field-type field))
1044                     ,@(if (alien-record-field-bits field)
1045                           (list (alien-record-field-bits field)))))
1046                 (alien-record-type-fields type)))))
1047
1048 ;;; Test the record fields. Keep a hashtable table of already compared
1049 ;;; types to detect cycles.
1050 (defun record-fields-match-p (field1 field2)
1051   (and (eq (alien-record-field-name field1)
1052            (alien-record-field-name field2))
1053        (eql (alien-record-field-bits field1)
1054             (alien-record-field-bits field2))
1055        (eql (alien-record-field-offset field1)
1056             (alien-record-field-offset field2))
1057        (alien-type-= (alien-record-field-type field1)
1058                      (alien-record-field-type field2))))
1059
1060 (defvar *alien-type-matches* nil
1061   "A hashtable used to detect cycles while comparing record types.")
1062
1063 (define-alien-type-method (record :type=) (type1 type2)
1064   (and (eq (alien-record-type-name type1)
1065            (alien-record-type-name type2))
1066        (eq (alien-record-type-kind type1)
1067            (alien-record-type-kind type2))
1068        (eql (alien-type-bits type1)
1069             (alien-type-bits type2))
1070        (eql (alien-type-alignment type1)
1071             (alien-type-alignment type2))
1072        (flet ((match-fields (&optional old)
1073                 (setf (gethash type1 *alien-type-matches*) (cons type2 old))
1074                 (every #'record-fields-match-p
1075                        (alien-record-type-fields type1)
1076                        (alien-record-type-fields type2))))
1077          (if *alien-type-matches*
1078              (let ((types (gethash type1 *alien-type-matches*)))
1079                (or (memq type2 types) (match-fields types)))
1080              (let ((*alien-type-matches* (make-hash-table :test #'eq)))
1081                (match-fields))))))
1082 \f
1083 ;;;; the FUNCTION and VALUES alien types
1084
1085 (define-alien-type-class (fun :include mem-block)
1086   (result-type (missing-arg) :type alien-type)
1087   (arg-types (missing-arg) :type list)
1088   (stub nil :type (or null function)))
1089
1090 (define-alien-type-translator function (result-type &rest arg-types
1091                                                     &environment env)
1092   (make-alien-fun-type
1093    :result-type (let ((*values-type-okay* t))
1094                   (parse-alien-type result-type env))
1095    :arg-types (mapcar (lambda (arg-type) (parse-alien-type arg-type env))
1096                       arg-types)))
1097
1098 (define-alien-type-method (fun :unparse) (type)
1099   `(function ,(%unparse-alien-type (alien-fun-type-result-type type))
1100              ,@(mapcar #'%unparse-alien-type
1101                        (alien-fun-type-arg-types type))))
1102
1103 (define-alien-type-method (fun :type=) (type1 type2)
1104   (and (alien-type-= (alien-fun-type-result-type type1)
1105                      (alien-fun-type-result-type type2))
1106        (= (length (alien-fun-type-arg-types type1))
1107           (length (alien-fun-type-arg-types type2)))
1108        (every #'alien-type-=
1109               (alien-fun-type-arg-types type1)
1110               (alien-fun-type-arg-types type2))))
1111
1112 (define-alien-type-class (values)
1113   (values (missing-arg) :type list))
1114
1115 (define-alien-type-translator values (&rest values &environment env)
1116   (unless *values-type-okay*
1117     (error "cannot use values types here"))
1118   (let ((*values-type-okay* nil))
1119     (make-alien-values-type
1120      :values (mapcar (lambda (alien-type) (parse-alien-type alien-type env))
1121                      values))))
1122
1123 (define-alien-type-method (values :unparse) (type)
1124   `(values ,@(mapcar #'%unparse-alien-type
1125                      (alien-values-type-values type))))
1126
1127 (define-alien-type-method (values :type=) (type1 type2)
1128   (and (= (length (alien-values-type-values type1))
1129           (length (alien-values-type-values type2)))
1130        (every #'alien-type-=
1131               (alien-values-type-values type1)
1132               (alien-values-type-values type2))))
1133 \f
1134 ;;;; a structure definition needed both in the target and in the
1135 ;;;; cross-compilation host
1136
1137 ;;; information about local aliens. The WITH-ALIEN macro builds one of
1138 ;;; these structures and LOCAL-ALIEN and friends communicate
1139 ;;; information about how that local alien is represented.
1140 (def!struct (local-alien-info
1141              (:make-load-form-fun sb!kernel:just-dump-it-normally)
1142              (:constructor make-local-alien-info
1143                            (&key type force-to-memory-p
1144                             &aux (force-to-memory-p (or force-to-memory-p
1145                                                         (alien-array-type-p type)
1146                                                         (alien-record-type-p type))))))
1147   ;; the type of the local alien
1148   (type (missing-arg) :type alien-type)
1149   ;; Must this local alien be forced into memory? Using the ADDR macro
1150   ;; on a local alien will set this.
1151   (force-to-memory-p nil :type (member t nil)))
1152 (def!method print-object ((info local-alien-info) stream)
1153   (print-unreadable-object (info stream :type t)
1154     (format stream
1155             "~:[~;(forced to stack) ~]~S"
1156             (local-alien-info-force-to-memory-p info)
1157             (unparse-alien-type (local-alien-info-type info)))))
1158 \f
1159 ;;;; the ADDR macro
1160
1161 (defmacro-mundanely addr (expr &environment env)
1162   #!+sb-doc
1163   "Return an Alien pointer to the data addressed by Expr, which must be a call
1164    to SLOT or DEREF, or a reference to an Alien variable."
1165   (let ((form (sb!xc:macroexpand expr env)))
1166     (or (typecase form
1167           (cons
1168            (case (car form)
1169              (slot
1170               (cons '%slot-addr (cdr form)))
1171              (deref
1172               (cons '%deref-addr (cdr form)))
1173              (%heap-alien
1174               (cons '%heap-alien-addr (cdr form)))
1175              (local-alien
1176               (let ((info (let ((info-arg (second form)))
1177                             (and (consp info-arg)
1178                                  (eq (car info-arg) 'quote)
1179                                  (second info-arg)))))
1180                 (unless (local-alien-info-p info)
1181                   (error "Something is wrong, LOCAL-ALIEN-INFO not found: ~S"
1182                          form))
1183                 (setf (local-alien-info-force-to-memory-p info) t))
1184               (cons '%local-alien-addr (cdr form)))))
1185           (symbol
1186            (let ((kind (info :variable :kind form)))
1187              (when (eq kind :alien)
1188                `(%heap-alien-addr ',(info :variable :alien-info form))))))
1189         (error "~S is not a valid L-value." form))))
1190
1191 (/show0 "host-alieneval.lisp end of file")