96196b82b4a4bcfb734de17d001a7c5693a38879
[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 \f
15 ;;;; utility functions
16
17 (defun align-offset (offset alignment)
18   (let ((extra (rem offset alignment)))
19     (if (zerop extra) offset (+ offset (- alignment extra)))))
20
21 (defun guess-alignment (bits)
22   (cond ((null bits) nil)
23         #!-x86 ((> bits 32) 64)
24         ((> bits 16) 32)
25         ((> bits 8) 16)
26         ((> bits 1) 8)
27         (t 1)))
28 \f
29 ;;;; ALIEN-TYPE-INFO stuff
30
31 (eval-when (:compile-toplevel :execute :load-toplevel)
32
33 (defstruct (alien-type-class (:copier nil))
34   (name nil :type symbol)
35   (include nil :type (or null alien-type-class))
36   (unparse nil :type (or null function))
37   (type= nil :type (or null function))
38   (lisp-rep nil :type (or null function))
39   (alien-rep nil :type (or null function))
40   (extract-gen nil :type (or null function))
41   (deposit-gen nil :type (or null function))
42   (naturalize-gen nil :type (or null function))
43   (deport-gen nil :type (or null function))
44   ;; Cast?
45   (arg-tn nil :type (or null function))
46   (result-tn nil :type (or null function))
47   (subtypep nil :type (or null function)))
48 (def!method print-object ((type-class alien-type-class) stream)
49   (print-unreadable-object (type-class stream :type t)
50     (prin1 (alien-type-class-name type-class) stream)))
51
52 (defun alien-type-class-or-lose (name)
53   (or (gethash name *alien-type-classes*)
54       (error "no alien type class ~S" name)))
55
56 (defun create-alien-type-class-if-necessary (name include)
57   (let ((old (gethash name *alien-type-classes*))
58         (include (and include (alien-type-class-or-lose include))))
59     (if old
60         (setf (alien-type-class-include old) include)
61         (setf (gethash name *alien-type-classes*)
62               (make-alien-type-class :name name :include include)))))
63
64 (defparameter *method-slot-alist*
65   '((:unparse . alien-type-class-unparse)
66     (:type= . alien-type-class-type=)
67     (:subtypep . alien-type-class-subtypep)
68     (:lisp-rep . alien-type-class-lisp-rep)
69     (:alien-rep . alien-type-class-alien-rep)
70     (:extract-gen . alien-type-class-extract-gen)
71     (:deposit-gen . alien-type-class-deposit-gen)
72     (:naturalize-gen . alien-type-class-naturalize-gen)
73     (:deport-gen . alien-type-class-deport-gen)
74     ;; cast?
75     (:arg-tn . alien-type-class-arg-tn)
76     (:result-tn . alien-type-class-result-tn)))
77
78 (defun method-slot (method)
79   (cdr (or (assoc method *method-slot-alist*)
80            (error "no method ~S" method))))
81
82 ) ; EVAL-WHEN
83
84 ;;; We define a keyword "BOA" constructor so that we can reference the
85 ;;; slot names in init forms.
86 (def!macro def-alien-type-class ((name &key include include-args) &rest slots)
87   (let ((defstruct-name (symbolicate "ALIEN-" name "-TYPE")))
88     (multiple-value-bind (include include-defstruct overrides)
89         (etypecase include
90           (null
91            (values nil 'alien-type nil))
92           (symbol
93            (values
94             include
95             (symbolicate "ALIEN-" include "-TYPE")
96             nil))
97           (list
98            (values
99             (car include)
100             (symbolicate "ALIEN-" (car include) "-TYPE")
101             (cdr include))))
102       `(progn
103          (eval-when (:compile-toplevel :load-toplevel :execute)
104            (create-alien-type-class-if-necessary ',name ',(or include 'root)))
105          (def!struct (,defstruct-name
106                         (:include ,include-defstruct
107                                   (:class ',name)
108                                   ,@overrides)
109                         (:constructor
110                          ,(symbolicate "MAKE-" defstruct-name)
111                          (&key class bits alignment
112                                ,@(mapcar (lambda (x)
113                                            (if (atom x) x (car x)))
114                                          slots)
115                                ,@include-args)))
116            ,@slots)))))
117
118 (def!macro def-alien-type-method ((class method) lambda-list &rest body)
119   (let ((defun-name (symbolicate class "-" method "-METHOD")))
120     `(progn
121        (defun ,defun-name ,lambda-list
122          ,@body)
123        (setf (,(method-slot method) (alien-type-class-or-lose ',class))
124              #',defun-name))))
125
126 (def!macro invoke-alien-type-method (method type &rest args)
127   (let ((slot (method-slot method)))
128     (once-only ((type type))
129       `(funcall (do ((class (alien-type-class-or-lose (alien-type-class ,type))
130                             (alien-type-class-include class)))
131                     ((null class)
132                      (error "method ~S not defined for ~S"
133                             ',method (alien-type-class ,type)))
134                   (let ((fn (,slot class)))
135                     (when fn
136                       (return fn))))
137                 ,type ,@args))))
138 \f
139 ;;;; type parsing and unparsing
140
141 ;;; CMU CL used COMPILER-LET to bind *AUXILIARY-TYPE-DEFINITIONS*, and
142 ;;; COMPILER-LET is no longer supported by ANSI or SBCL. Instead, we
143 ;;; follow the suggestion in CLTL2 of using SYMBOL-MACROLET to achieve
144 ;;; a similar effect.
145 (eval-when (:compile-toplevel :load-toplevel :execute)
146   (defun auxiliary-type-definitions (env)
147     (multiple-value-bind (result expanded-p)
148         (sb!xc:macroexpand '&auxiliary-type-definitions& env)
149       (if expanded-p
150           result
151           ;; This is like having the global symbol-macro definition be
152           ;; NIL, but global symbol-macros make me vaguely queasy, so
153           ;; I do it this way instead.
154           nil))))
155
156 ;;; Process stuff in a new scope.
157 (def!macro with-auxiliary-alien-types (env &body body)
158   ``(symbol-macrolet ((&auxiliary-type-definitions&
159                        ,(append *new-auxiliary-types*
160                                 (auxiliary-type-definitions ,env))))
161       ,(let ((*new-auxiliary-types* nil))
162          ,@body)))
163
164 ;;; FIXME: Now that *NEW-AUXILIARY-TYPES* is born initialized to NIL,
165 ;;; we no longer need to make a distinction between this and
166 ;;; %PARSE-ALIEN-TYPE.
167 (defun parse-alien-type (type env)
168   (declare (type (or sb!kernel:lexenv null) env))
169   #!+sb-doc
170   "Parse the list structure TYPE as an alien type specifier and return
171    the resultant ALIEN-TYPE structure."
172   (%parse-alien-type type env))
173
174 (defun %parse-alien-type (type env)
175   (declare (type (or sb!kernel:lexenv null) env))
176   (if (consp type)
177       (let ((translator (info :alien-type :translator (car type))))
178         (unless translator
179           (error "unknown alien type: ~S" type))
180         (funcall translator type env))
181       (case (info :alien-type :kind type)
182         (:primitive
183          (let ((translator (info :alien-type :translator type)))
184            (unless translator
185              (error "no translator for primitive alien type ~S" type))
186            (funcall translator (list type) env)))
187         (:defined
188          (or (info :alien-type :definition type)
189              (error "no definition for alien type ~S" type)))
190         (:unknown
191          (error "unknown alien type: ~S" type)))))
192
193 (defun auxiliary-alien-type (kind name env)
194   (declare (type (or sb!kernel:lexenv null) env))
195   (flet ((aux-defn-matches (x)
196            (and (eq (first x) kind) (eq (second x) name))))
197     (let ((in-auxiliaries
198            (or (find-if #'aux-defn-matches *new-auxiliary-types*)
199                (find-if #'aux-defn-matches (auxiliary-type-definitions env)))))
200       (if in-auxiliaries
201           (values (third in-auxiliaries) t)
202           (ecase kind
203             (:struct
204              (info :alien-type :struct name))
205             (:union
206              (info :alien-type :union name))
207             (:enum
208              (info :alien-type :enum name)))))))
209
210 (defun (setf auxiliary-alien-type) (new-value kind name env)
211   (declare (type (or sb!kernel:lexenv null) env))
212   (flet ((aux-defn-matches (x)
213            (and (eq (first x) kind) (eq (second x) name))))
214     (when (find-if #'aux-defn-matches *new-auxiliary-types*)
215       (error "attempt to multiply define ~A ~S" kind name))
216     (when (find-if #'aux-defn-matches (auxiliary-type-definitions env))
217       (error "attempt to shadow definition of ~A ~S" kind name)))
218   (push (list kind name new-value) *new-auxiliary-types*)
219   new-value)
220
221 (defun verify-local-auxiliaries-okay ()
222   (dolist (info *new-auxiliary-types*)
223     (destructuring-bind (kind name defn) info
224       (declare (ignore defn))
225       (when (ecase kind
226               (:struct
227                (info :alien-type :struct name))
228               (:union
229                (info :alien-type :union name))
230               (:enum
231                (info :alien-type :enum name)))
232         (error "attempt to shadow definition of ~A ~S" kind name)))))
233
234 (defun unparse-alien-type (type)
235   #!+sb-doc
236   "Convert the alien-type structure TYPE back into a list specification of
237    the type."
238   (declare (type alien-type type))
239   (let ((*record-types-already-unparsed* nil))
240     (%unparse-alien-type type)))
241
242 ;;; Does all the work of UNPARSE-ALIEN-TYPE. It's separate because we
243 ;;; need to recurse inside the binding of
244 ;;; *RECORD-TYPES-ALREADY-UNPARSED*.
245 (defun %unparse-alien-type (type)
246   (invoke-alien-type-method :unparse type))
247 \f
248 ;;;; alien type defining stuff
249
250 (def!macro def-alien-type-translator (name lambda-list &body body)
251   (let ((whole (gensym "WHOLE"))
252         (env (gensym "ENV"))
253         (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                                   'def-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          (%def-alien-type-translator ',name #',defun-name ,docs)))))
265
266 (eval-when (:compile-toplevel :load-toplevel :execute)
267   (defun %def-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 def-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              `((%def-alien-type ',name ',alien-type)))))))
288
289 (eval-when (:compile-toplevel :load-toplevel :execute)
290   (defun %def-auxiliary-alien-types (types)
291     (dolist (info types)
292       (destructuring-bind (kind name defn) info
293         (macrolet ((frob (kind)
294                          `(let ((old (info :alien-type ,kind name)))
295                             (unless (or (null old) (alien-type-= old defn))
296                               (warn
297                                "redefining ~A ~S to be:~%  ~S,~%was:~%  ~S"
298                                kind name defn old))
299                             (setf (info :alien-type ,kind name) defn))))
300           (ecase kind
301             (:struct (frob :struct))
302             (:union (frob :union))
303             (:enum (frob :enum)))))))
304   (defun %def-alien-type (name new)
305     (ecase (info :alien-type :kind name)
306       (:primitive
307        (error "~S is a built-in alien type." name))
308       (:defined
309        (let ((old (info :alien-type :definition name)))
310          (unless (or (null old) (alien-type-= new old))
311            (warn "redefining ~S to be:~%  ~S,~%was~%  ~S"
312                  name
313                  (unparse-alien-type new)
314                  (unparse-alien-type old)))))
315       (:unknown))
316     (setf (info :alien-type :definition name) new)
317     (setf (info :alien-type :kind name) :defined)
318     name))
319 \f
320 ;;;; the root alien type
321
322 (eval-when (:compile-toplevel :load-toplevel :execute)
323   (create-alien-type-class-if-necessary 'root nil))
324
325 (def!struct (alien-type
326              (:make-load-form-fun sb!kernel:just-dump-it-normally)
327              (:constructor make-alien-type (&key class bits alignment)))
328   (class 'root :type symbol)
329   (bits nil :type (or null unsigned-byte))
330   (alignment (guess-alignment bits) :type (or null unsigned-byte)))
331 (def!method print-object ((type alien-type) stream)
332   (print-unreadable-object (type stream :type t)
333     (prin1 (unparse-alien-type type) stream)))
334 \f
335 ;;;; the SAP type
336
337 (def-alien-type-class (system-area-pointer))
338
339 (def-alien-type-translator system-area-pointer ()
340   (make-alien-system-area-pointer-type
341    :bits #!-alpha sb!vm:word-bits #!+alpha 64))
342
343 (def-alien-type-method (system-area-pointer :unparse) (type)
344   (declare (ignore type))
345   'system-area-pointer)
346
347 (def-alien-type-method (system-area-pointer :lisp-rep) (type)
348   (declare (ignore type))
349   'system-area-pointer)
350
351 (def-alien-type-method (system-area-pointer :alien-rep) (type)
352   (declare (ignore type))
353   'system-area-pointer)
354
355 (def-alien-type-method (system-area-pointer :naturalize-gen) (type alien)
356   (declare (ignore type))
357   alien)
358
359 (def-alien-type-method (system-area-pointer :deport-gen) (type object)
360   (declare (ignore type))
361   (/noshow "doing alien type method SYSTEM-AREA-POINTER :DEPORT-GEN" object)
362   object)
363
364 (def-alien-type-method (system-area-pointer :extract-gen) (type sap offset)
365   (declare (ignore type))
366   `(sap-ref-sap ,sap (/ ,offset sb!vm:byte-bits)))
367 \f
368 ;;;; the ALIEN-VALUE type
369
370 (def-alien-type-class (alien-value :include system-area-pointer))
371
372 (def-alien-type-method (alien-value :lisp-rep) (type)
373   (declare (ignore type))
374   nil)
375
376 (def-alien-type-method (alien-value :naturalize-gen) (type alien)
377   `(%sap-alien ,alien ',type))
378
379 (def-alien-type-method (alien-value :deport-gen) (type value)
380   (declare (ignore type))
381   (/noshow "doing alien type method ALIEN-VALUE :DEPORT-GEN" value)
382   `(alien-sap ,value))
383 \f
384 ;;; HEAP-ALIEN-INFO -- defstruct.
385 ;;;
386 ;;; Information describing a heap-allocated alien.
387 (def!struct (heap-alien-info
388              (:make-load-form-fun sb!kernel:just-dump-it-normally))
389   ;; The type of this alien.
390   (type (required-argument) :type alien-type)
391   ;; The form to evaluate to produce the SAP pointing to where in the heap
392   ;; it is.
393   (sap-form (required-argument)))
394 (def!method print-object ((info heap-alien-info) stream)
395   (print-unreadable-object (info stream :type t)
396     (funcall (formatter "~S ~S")
397              stream
398              (heap-alien-info-sap-form info)
399              (unparse-alien-type (heap-alien-info-type info)))))
400 \f
401 ;;;; Interfaces to the different methods
402
403 (defun alien-type-= (type1 type2)
404   #!+sb-doc
405   "Return T iff TYPE1 and TYPE2 describe equivalent alien types."
406   (or (eq type1 type2)
407       (and (eq (alien-type-class type1)
408                (alien-type-class type2))
409            (invoke-alien-type-method :type= type1 type2))))
410
411 (defun alien-subtype-p (type1 type2)
412   #!+sb-doc
413   "Return T iff the alien type TYPE1 is a subtype of TYPE2. Currently, the
414    only supported subtype relationships are is that any pointer type is a
415    subtype of (* t), and any array type first dimension will match
416    (array <eltype> nil ...). Otherwise, the two types have to be
417    ALIEN-TYPE-=."
418   (or (eq type1 type2)
419       (invoke-alien-type-method :subtypep type1 type2)))
420
421 (defun compute-naturalize-lambda (type)
422   `(lambda (alien ignore)
423      (declare (ignore ignore))
424      ,(invoke-alien-type-method :naturalize-gen type 'alien)))
425
426 (defun compute-deport-lambda (type)
427   (declare (type alien-type type))
428   (/noshow "entering COMPUTE-DEPORT-LAMBDA" type)
429   (multiple-value-bind (form value-type)
430       (invoke-alien-type-method :deport-gen type 'value)
431     `(lambda (value ignore)
432        (declare (type ,(or value-type
433                            (compute-lisp-rep-type type)
434                            `(alien ,type))
435                       value)
436                 (ignore ignore))
437        ,form)))
438
439 (defun compute-extract-lambda (type)
440   `(lambda (sap offset ignore)
441      (declare (type system-area-pointer sap)
442               (type unsigned-byte offset)
443               (ignore ignore))
444      (naturalize ,(invoke-alien-type-method :extract-gen type 'sap 'offset)
445                  ',type)))
446
447 (defun compute-deposit-lambda (type)
448   (declare (type alien-type type))
449   `(lambda (sap offset ignore value)
450      (declare (type system-area-pointer sap)
451               (type unsigned-byte offset)
452               (ignore ignore))
453      (let ((value (deport value ',type)))
454        ,(invoke-alien-type-method :deposit-gen type 'sap 'offset 'value)
455        ;; Note: the reason we don't just return the pre-deported value
456        ;; is because that would inhibit any (deport (naturalize ...))
457        ;; optimizations that might have otherwise happen. Re-naturalizing
458        ;; the value might cause extra consing, but is flushable, so probably
459        ;; results in better code.
460        (naturalize value ',type))))
461
462 (defun compute-lisp-rep-type (type)
463   (invoke-alien-type-method :lisp-rep type))
464
465 (defun compute-alien-rep-type (type)
466   (invoke-alien-type-method :alien-rep type))
467 \f
468 ;;;; default methods
469
470 (def-alien-type-method (root :unparse) (type)
471   `(<unknown-alien-type> ,(type-of type)))
472
473 (def-alien-type-method (root :type=) (type1 type2)
474   (declare (ignore type1 type2))
475   t)
476
477 (def-alien-type-method (root :subtypep) (type1 type2)
478   (alien-type-= type1 type2))
479
480 (def-alien-type-method (root :lisp-rep) (type)
481   (declare (ignore type))
482   nil)
483
484 (def-alien-type-method (root :alien-rep) (type)
485   (declare (ignore type))
486   '*)
487
488 (def-alien-type-method (root :naturalize-gen) (type alien)
489   (declare (ignore alien))
490   (error "cannot represent ~S typed aliens" type))
491
492 (def-alien-type-method (root :deport-gen) (type object)
493   (declare (ignore object))
494   (error "cannot represent ~S typed aliens" type))
495
496 (def-alien-type-method (root :extract-gen) (type sap offset)
497   (declare (ignore sap offset))
498   (error "cannot represent ~S typed aliens" type))
499
500 (def-alien-type-method (root :deposit-gen) (type sap offset value)
501   `(setf ,(invoke-alien-type-method :extract-gen type sap offset) ,value))
502
503 (def-alien-type-method (root :arg-tn) (type state)
504   (declare (ignore state))
505   (error "Aliens of type ~S cannot be passed as arguments to CALL-OUT."
506          (unparse-alien-type type)))
507
508 (def-alien-type-method (root :result-tn) (type state)
509   (declare (ignore state))
510   (error "Aliens of type ~S cannot be returned from CALL-OUT."
511          (unparse-alien-type type)))
512 \f
513 ;;;; the INTEGER type
514
515 (def-alien-type-class (integer)
516   (signed t :type (member t nil)))
517
518 (def-alien-type-translator signed (&optional (bits sb!vm:word-bits))
519   (make-alien-integer-type :bits bits))
520
521 (def-alien-type-translator integer (&optional (bits sb!vm:word-bits))
522   (make-alien-integer-type :bits bits))
523
524 (def-alien-type-translator unsigned (&optional (bits sb!vm:word-bits))
525   (make-alien-integer-type :bits bits :signed nil))
526
527 (def-alien-type-method (integer :unparse) (type)
528   (list (if (alien-integer-type-signed type) 'signed 'unsigned)
529         (alien-integer-type-bits type)))
530
531 (def-alien-type-method (integer :type=) (type1 type2)
532   (and (eq (alien-integer-type-signed type1)
533            (alien-integer-type-signed type2))
534        (= (alien-integer-type-bits type1)
535           (alien-integer-type-bits type2))))
536
537 (def-alien-type-method (integer :lisp-rep) (type)
538   (list (if (alien-integer-type-signed type) 'signed-byte 'unsigned-byte)
539         (alien-integer-type-bits type)))
540
541 (def-alien-type-method (integer :alien-rep) (type)
542   (list (if (alien-integer-type-signed type) 'signed-byte 'unsigned-byte)
543         (alien-integer-type-bits type)))
544
545 (def-alien-type-method (integer :naturalize-gen) (type alien)
546   (declare (ignore type))
547   alien)
548
549 (def-alien-type-method (integer :deport-gen) (type value)
550   (declare (ignore type))
551   value)
552
553 (def-alien-type-method (integer :extract-gen) (type sap offset)
554   (declare (type alien-integer-type type))
555   (let ((ref-fun
556          (if (alien-integer-type-signed type)
557           (case (alien-integer-type-bits type)
558             (8 'signed-sap-ref-8)
559             (16 'signed-sap-ref-16)
560             (32 'signed-sap-ref-32)
561             #!+alpha (64 'signed-sap-ref-64))
562           (case (alien-integer-type-bits type)
563             (8 'sap-ref-8)
564             (16 'sap-ref-16)
565             (32 'sap-ref-32)
566             #!+alpha (64 'sap-ref-64)))))
567     (if ref-fun
568         `(,ref-fun ,sap (/ ,offset sb!vm:byte-bits))
569         (error "cannot extract ~D bit integers"
570                (alien-integer-type-bits type)))))
571 \f
572 ;;;; the BOOLEAN type
573
574 (def-alien-type-class (boolean :include integer :include-args (signed)))
575
576 ;;; FIXME: Check to make sure that we aren't attaching user-readable
577 ;;; stuff to CL:BOOLEAN in any way which impairs ANSI compliance.
578 (def-alien-type-translator boolean (&optional (bits sb!vm:word-bits))
579   (make-alien-boolean-type :bits bits :signed nil))
580
581 (def-alien-type-method (boolean :unparse) (type)
582   `(boolean ,(alien-boolean-type-bits type)))
583
584 (def-alien-type-method (boolean :lisp-rep) (type)
585   (declare (ignore type))
586   `(member t nil))
587
588 (def-alien-type-method (boolean :naturalize-gen) (type alien)
589   (declare (ignore type))
590   `(not (zerop ,alien)))
591
592 (def-alien-type-method (boolean :deport-gen) (type value)
593   (declare (ignore type))
594   `(if ,value 1 0))
595 \f
596 ;;;; the ENUM type
597
598 (def-alien-type-class (enum :include (integer (:bits 32))
599                             :include-args (signed))
600   name          ; name of this enum (if any)
601   from          ; alist from keywords to integers.
602   to            ; alist or vector from integers to keywords.
603   kind          ; Kind of from mapping, :vector or :alist.
604   offset)       ; Offset to add to value for :vector from mapping.
605
606 (def-alien-type-translator enum (&whole
607                                  type name
608                                  &rest mappings
609                                  &environment env)
610   (cond (mappings
611          (let ((result (parse-enum name mappings)))
612            (when name
613              (multiple-value-bind (old old-p)
614                  (auxiliary-alien-type :enum name env)
615                (when old-p
616                  (unless (alien-type-= result old)
617                    (warn "redefining alien enum ~S" name))))
618              (setf (auxiliary-alien-type :enum name env) result))
619            result))
620         (name
621          (multiple-value-bind (result found)
622              (auxiliary-alien-type :enum name env)
623            (unless found
624              (error "unknown enum type: ~S" name))
625            result))
626         (t
627          (error "empty enum type: ~S" type))))
628
629 (defun parse-enum (name elements)
630   (when (null elements)
631     (error "An enumeration must contain at least one element."))
632   (let ((min nil)
633         (max nil)
634         (from-alist ())
635         (prev -1))
636     (declare (list from-alist))
637     (dolist (el elements)
638       (multiple-value-bind (sym val)
639           (if (listp el)
640               (values (first el) (second el))
641               (values el (1+ prev)))
642         (setf prev val)
643         (unless (keywordp sym)
644           (error "The enumeration element ~S is not a keyword." sym))
645         (unless (integerp val)
646           (error "The element value ~S is not an integer." val))
647         (unless (and max (> max val)) (setq max val))
648         (unless (and min (< min val)) (setq min val))
649         (when (rassoc val from-alist)
650           (error "The element value ~S is used more than once." val))
651         (when (assoc sym from-alist :test #'eq)
652           (error "The enumeration element ~S is used more than once." sym))
653         (push (cons sym val) from-alist)))
654     (let* ((signed (minusp min))
655            (min-bits (if signed
656                          (1+ (max (integer-length min)
657                                   (integer-length max)))
658                          (integer-length max))))
659       (when (> min-bits 32)
660         (error "can't represent enums needing more than 32 bits"))
661       (setf from-alist (sort from-alist #'< :key #'cdr))
662       (cond
663        ;; If range is at least 20% dense, use vector mapping. Crossover
664        ;; point solely on basis of space would be 25%. Vector mapping
665        ;; is always faster, so give the benefit of the doubt.
666        ((< 0.2 (/ (float (length from-alist)) (float (- max min))))
667         ;; If offset is small and ignorable, ignore it to save time.
668         (when (< 0 min 10) (setq min 0))
669         (let ((to (make-array (1+ (- max min)))))
670           (dolist (el from-alist)
671             (setf (svref to (- (cdr el) min)) (car el)))
672           (make-alien-enum-type :name name :signed signed
673                                 :from from-alist :to to :kind
674                                 :vector :offset (- min))))
675        (t
676         (make-alien-enum-type :name name :signed signed
677                               :from from-alist
678                               :to (mapcar #'(lambda (x) (cons (cdr x) (car x)))
679                                           from-alist)
680                               :kind :alist))))))
681
682 (def-alien-type-method (enum :unparse) (type)
683   `(enum ,(alien-enum-type-name type)
684          ,@(let ((prev -1))
685              (mapcar #'(lambda (mapping)
686                          (let ((sym (car mapping))
687                                (value (cdr mapping)))
688                            (prog1
689                                (if (= (1+ prev) value)
690                                    sym
691                                    `(,sym ,value))
692                              (setf prev value))))
693                      (alien-enum-type-from type)))))
694
695 (def-alien-type-method (enum :type=) (type1 type2)
696   (and (eq (alien-enum-type-name type1)
697            (alien-enum-type-name type2))
698        (equal (alien-enum-type-from type1)
699               (alien-enum-type-from type2))))
700
701 (def-alien-type-method (enum :lisp-rep) (type)
702   `(member ,@(mapcar #'car (alien-enum-type-from type))))
703
704 (def-alien-type-method (enum :naturalize-gen) (type alien)
705   (ecase (alien-enum-type-kind type)
706     (:vector
707      `(svref ',(alien-enum-type-to type)
708              (+ ,alien ,(alien-enum-type-offset type))))
709     (:alist
710      `(ecase ,alien
711         ,@(mapcar #'(lambda (mapping)
712                       `(,(car mapping) ,(cdr mapping)))
713                   (alien-enum-type-to type))))))
714
715 (def-alien-type-method (enum :deport-gen) (type value)
716   `(ecase ,value
717      ,@(mapcar #'(lambda (mapping)
718                    `(,(car mapping) ,(cdr mapping)))
719                (alien-enum-type-from type))))
720 \f
721 ;;;; the FLOAT types
722
723 (def-alien-type-class (float)
724   (type (required-argument) :type symbol))
725
726 (def-alien-type-method (float :unparse) (type)
727   (alien-float-type-type type))
728
729 (def-alien-type-method (float :lisp-rep) (type)
730   (alien-float-type-type type))
731
732 (def-alien-type-method (float :alien-rep) (type)
733   (alien-float-type-type type))
734
735 (def-alien-type-method (float :naturalize-gen) (type alien)
736   (declare (ignore type))
737   alien)
738
739 (def-alien-type-method (float :deport-gen) (type value)
740   (declare (ignore type))
741   value)
742
743 (def-alien-type-class (single-float :include (float (:bits 32))
744                                     :include-args (type)))
745
746 (def-alien-type-translator single-float ()
747   (make-alien-single-float-type :type 'single-float))
748
749 (def-alien-type-method (single-float :extract-gen) (type sap offset)
750   (declare (ignore type))
751   `(sap-ref-single ,sap (/ ,offset sb!vm:byte-bits)))
752
753 (def-alien-type-class (double-float :include (float (:bits 64))
754                                     :include-args (type)))
755
756 (def-alien-type-translator double-float ()
757   (make-alien-double-float-type :type 'double-float))
758
759 (def-alien-type-method (double-float :extract-gen) (type sap offset)
760   (declare (ignore type))
761   `(sap-ref-double ,sap (/ ,offset sb!vm:byte-bits)))
762
763 #!+long-float
764 (def-alien-type-class (long-float :include (float (:bits #!+x86 96
765                                                           #!+sparc 128))
766                                   :include-args (type)))
767
768 #!+long-float
769 (def-alien-type-translator long-float ()
770   (make-alien-long-float-type :type 'long-float))
771
772 #!+long-float
773 (def-alien-type-method (long-float :extract-gen) (type sap offset)
774   (declare (ignore type))
775   `(sap-ref-long ,sap (/ ,offset sb!vm:byte-bits)))
776 \f
777 ;;;; the POINTER type
778
779 (def-alien-type-class (pointer :include (alien-value (:bits
780                                                       #!-alpha sb!vm:word-bits
781                                                       #!+alpha 64)))
782   (to nil :type (or alien-type null)))
783
784 (def-alien-type-translator * (to &environment env)
785   (make-alien-pointer-type :to (if (eq to t) nil (parse-alien-type to env))))
786
787 (def-alien-type-method (pointer :unparse) (type)
788   (let ((to (alien-pointer-type-to type)))
789     `(* ,(if to
790              (%unparse-alien-type to)
791              t))))
792
793 (def-alien-type-method (pointer :type=) (type1 type2)
794   (let ((to1 (alien-pointer-type-to type1))
795         (to2 (alien-pointer-type-to type2)))
796     (if to1
797         (if to2
798             (alien-type-= to1 to2)
799             nil)
800         (null to2))))
801
802 (def-alien-type-method (pointer :subtypep) (type1 type2)
803   (and (alien-pointer-type-p type2)
804        (let ((to1 (alien-pointer-type-to type1))
805              (to2 (alien-pointer-type-to type2)))
806          (if to1
807              (if to2
808                  (alien-subtype-p to1 to2)
809                  t)
810              (null to2)))))
811
812 (def-alien-type-method (pointer :deport-gen) (type value)
813   (/noshow "doing alien type method POINTER :DEPORT-GEN" type value)
814   (values
815    ;; FIXME: old version, highlighted a bug in xc optimization
816    `(etypecase ,value
817       (null
818        (int-sap 0))
819       (system-area-pointer
820        ,value)
821       ((alien ,type)
822        (alien-sap ,value)))
823    ;; new version, works around bug in xc optimization
824    #+nil
825    `(etypecase ,value
826       (system-area-pointer
827        ,value)
828       ((alien ,type)
829        (alien-sap ,value))
830       (null
831        (int-sap 0)))
832    `(or null system-area-pointer (alien ,type))))
833 \f
834 ;;;; the MEM-BLOCK type
835
836 (def-alien-type-class (mem-block :include alien-value))
837
838 (def-alien-type-method (mem-block :extract-gen) (type sap offset)
839   (declare (ignore type))
840   `(sap+ ,sap (/ ,offset sb!vm:byte-bits)))
841
842 (def-alien-type-method (mem-block :deposit-gen) (type sap offset value)
843   (let ((bits (alien-mem-block-type-bits type)))
844     (unless bits
845       (error "can't deposit aliens of type ~S (unknown size)" type))
846     `(sb!kernel:system-area-copy ,value 0 ,sap ,offset ',bits)))
847 \f
848 ;;;; the ARRAY type
849
850 (def-alien-type-class (array :include mem-block)
851   (element-type (required-argument) :type alien-type)
852   (dimensions (required-argument) :type list))
853
854 (def-alien-type-translator array (ele-type &rest dims &environment env)
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 ((type (parse-alien-type ele-type env)))
865     (make-alien-array-type
866      :element-type type
867      :dimensions dims
868      :alignment (alien-type-alignment type)
869      :bits (if (and (alien-type-bits type)
870                     (every #'integerp dims))
871                (* (align-offset (alien-type-bits type)
872                                 (alien-type-alignment type))
873                   (reduce #'* dims))))))
874
875 (def-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 (def-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 (def-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 (required-argument) :type symbol)
902   (type (required-argument) :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 (def-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 (def-alien-type-translator struct (name &rest fields &environment env)
919   (parse-alien-record-type :struct name fields env))
920
921 (def-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 (def-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 (def-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 types
1072
1073 (defvar *values-type-okay* nil)
1074
1075 (def-alien-type-class (function :include mem-block)
1076   (result-type (required-argument) :type alien-type)
1077   (arg-types (required-argument) :type list)
1078   (stub nil :type (or null function)))
1079
1080 (def-alien-type-translator function (result-type &rest arg-types
1081                                                  &environment env)
1082   (make-alien-function-type
1083    :result-type (let ((*values-type-okay* t))
1084                   (parse-alien-type result-type env))
1085    :arg-types (mapcar (lambda (arg-type) (parse-alien-type arg-type env))
1086                       arg-types)))
1087
1088 (def-alien-type-method (function :unparse) (type)
1089   `(function ,(%unparse-alien-type (alien-function-type-result-type type))
1090              ,@(mapcar #'%unparse-alien-type
1091                        (alien-function-type-arg-types type))))
1092
1093 (def-alien-type-method (function :type=) (type1 type2)
1094   (and (alien-type-= (alien-function-type-result-type type1)
1095                      (alien-function-type-result-type type2))
1096        (= (length (alien-function-type-arg-types type1))
1097           (length (alien-function-type-arg-types type2)))
1098        (every #'alien-type-=
1099               (alien-function-type-arg-types type1)
1100               (alien-function-type-arg-types type2))))
1101
1102 (def-alien-type-class (values)
1103   (values (required-argument) :type list))
1104
1105 (def-alien-type-translator values (&rest values &environment env)
1106   (unless *values-type-okay*
1107     (error "cannot use values types here"))
1108   (let ((*values-type-okay* nil))
1109     (make-alien-values-type
1110      :values (mapcar (lambda (alien-type) (parse-alien-type alien-type env))
1111                      values))))
1112
1113 (def-alien-type-method (values :unparse) (type)
1114   `(values ,@(mapcar #'%unparse-alien-type
1115                      (alien-values-type-values type))))
1116
1117 (def-alien-type-method (values :type=) (type1 type2)
1118   (and (= (length (alien-values-type-values type1))
1119           (length (alien-values-type-values type2)))
1120        (every #'alien-type-=
1121               (alien-values-type-values type1)
1122               (alien-values-type-values type2))))
1123 \f
1124 ;;;; a structure definition needed both in the target and in the
1125 ;;;; cross-compilation host
1126
1127 ;;; information about local aliens. The WITH-ALIEN macro builds one of
1128 ;;; these structures and LOCAL-ALIEN and friends communicate
1129 ;;; information about how that local alien is represented.
1130 (def!struct (local-alien-info
1131              (:make-load-form-fun sb!kernel:just-dump-it-normally)
1132              (:constructor make-local-alien-info
1133                            (&key type force-to-memory-p)))
1134   ;; the type of the local alien
1135   (type (required-argument) :type alien-type)
1136   ;; T if this local alien must be forced into memory. Using the ADDR macro
1137   ;; on a local alien will set this.
1138   (force-to-memory-p (or (alien-array-type-p type) (alien-record-type-p type))
1139                      :type (member t nil)))
1140 (def!method print-object ((info local-alien-info) stream)
1141   (print-unreadable-object (info stream :type t)
1142     (format stream
1143             "~:[~;(forced to stack) ~]~S"
1144             (local-alien-info-force-to-memory-p info)
1145             (unparse-alien-type (local-alien-info-type info)))))
1146 \f
1147 ;;;; the ADDR macro
1148
1149 (sb!kernel:defmacro-mundanely addr (expr &environment env)
1150   #!+sb-doc
1151   "Return an Alien pointer to the data addressed by Expr, which must be a call
1152    to SLOT or DEREF, or a reference to an Alien variable."
1153   (let ((form (sb!xc:macroexpand expr env)))
1154     (or (typecase form
1155           (cons
1156            (case (car form)
1157              (slot
1158               (cons '%slot-addr (cdr form)))
1159              (deref
1160               (cons '%deref-addr (cdr form)))
1161              (%heap-alien
1162               (cons '%heap-alien-addr (cdr form)))
1163              (local-alien
1164               (let ((info (let ((info-arg (second form)))
1165                             (and (consp info-arg)
1166                                  (eq (car info-arg) 'quote)
1167                                  (second info-arg)))))
1168                 (unless (local-alien-info-p info)
1169                   (error "Something is wrong, LOCAL-ALIEN-INFO not found: ~S"
1170                          form))
1171                 (setf (local-alien-info-force-to-memory-p info) t))
1172               (cons '%local-alien-addr (cdr form)))))
1173           (symbol
1174            (let ((kind (info :variable :kind form)))
1175              (when (eq kind :alien)
1176                `(%heap-alien-addr ',(info :variable :alien-info form))))))
1177         (error "~S is not a valid L-value." form))))