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