source: branches/generic-class-file/abcl/src/org/armedbear/lisp/jvm.lisp @ 12895

Last change on this file since 12895 was 12895, checked in by ehuelsmann, 13 years ago

Remove exclamation marks which were in place to avoid naming
conflicts; the conflicting names have been deleted from pass2 now.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 23.6 KB
Line 
1;;; jvm.lisp
2;;;
3;;; Copyright (C) 2003-2008 Peter Graves
4;;; $Id: jvm.lisp 12895 2010-08-13 21:10:39Z ehuelsmann $
5;;;
6;;; This program is free software; you can redistribute it and/or
7;;; modify it under the terms of the GNU General Public License
8;;; as published by the Free Software Foundation; either version 2
9;;; of the License, or (at your option) any later version.
10;;;
11;;; This program is distributed in the hope that it will be useful,
12;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
13;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14;;; GNU General Public License for more details.
15;;;
16;;; You should have received a copy of the GNU General Public License
17;;; along with this program; if not, write to the Free Software
18;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
19;;;
20;;; As a special exception, the copyright holders of this library give you
21;;; permission to link this library with independent modules to produce an
22;;; executable, regardless of the license terms of these independent
23;;; modules, and to copy and distribute the resulting executable under
24;;; terms of your choice, provided that you also meet, for each linked
25;;; independent module, the terms and conditions of the license of that
26;;; module.  An independent module is a module which is not derived from
27;;; or based on this library.  If you modify this library, you may extend
28;;; this exception to your version of the library, but you are not
29;;; obligated to do so.  If you do not wish to do so, delete this
30;;; exception statement from your version.
31
32(in-package "JVM")
33
34(export '(compile-defun *catch-errors* jvm-compile-package
35          derive-compiler-type))
36
37(eval-when (:compile-toplevel :load-toplevel :execute)
38  (require "LOOP")
39  (require "FORMAT")
40  (require "CLOS")
41  (require "PRINT-OBJECT")
42  (require "COMPILER-TYPES")
43  (require "COMPILER-ERROR")
44  (require "KNOWN-FUNCTIONS")
45  (require "DUMP-FORM")
46  (require "JVM-INSTRUCTIONS")
47  (require "JVM-CLASS-FILE")
48  (require "KNOWN-SYMBOLS")
49  (require "JAVA")
50  (require "COMPILER-PASS1")
51  (require "COMPILER-PASS2"))
52
53(defvar *closure-variables* nil)
54
55(defvar *enable-dformat* nil)
56
57#+nil
58(defun dformat (destination control-string &rest args)
59  (when *enable-dformat*
60    (apply #'sys::%format destination control-string args)))
61
62(defmacro dformat (&rest ignored)
63  (declare (ignore ignored)))
64
65(declaim (inline u2 s1 s2))
66
67(defknown u2 (fixnum) cons)
68(defun u2 (n)
69  (declare (optimize speed))
70  (declare (type (unsigned-byte 16) n))
71  (when (not (<= 0 n 65535))
72    (error "u2 argument ~A out of 65k range." n))
73  (list (logand (ash n -8) #xff)
74        (logand n #xff)))
75
76(defknown s1 (fixnum) fixnum)
77(defun s1 (n)
78  (declare (optimize speed))
79  (declare (type (signed-byte 8) n))
80  (when (not (<= -128 n 127))
81    (error "s2 argument ~A out of 16-bit signed range." n))
82  (if (< n 0)
83      (1+ (logxor (- n) #xFF))
84      n))
85
86
87(defknown s2 (fixnum) cons)
88(defun s2 (n)
89  (declare (optimize speed))
90  (declare (type (signed-byte 16) n))
91  (when (not (<= -32768 n 32767))
92    (error "s2 argument ~A out of 16-bit signed range." n))
93  (u2 (if (< n 0) (1+ (logxor (- n) #xFFFF))
94          n)))
95
96
97
98
99
100(defmacro with-saved-compiler-policy (&body body)
101  "Saves compiler policy variables, restoring them after evaluating `body'."
102  `(let ((*speed* *speed*)
103         (*space* *space*)
104         (*safety* *safety*)
105         (*debug* *debug*)
106         (*explain* *explain*)
107         (*inline-declarations* *inline-declarations*))
108     ,@body))
109
110
111
112(defvar *compiler-debug* nil)
113
114(defvar *pool* nil)
115(defvar *static-code* ())
116(defvar *class-file* nil)
117
118(defvar *externalized-objects* nil)
119(defvar *declared-functions* nil)
120
121(defstruct (abcl-class-file (:include class-file)
122                            (:constructor %make-abcl-class-file))
123  pathname ; pathname of output file
124  lambda-name
125  lambda-list ; as advertised
126  static-code
127  objects ;; an alist of externalized objects and their field names
128  (functions (make-hash-table :test 'equal)) ;; because of (SETF ...) functions
129  )
130
131(defun class-name-from-filespec (filespec)
132  (let* ((name (pathname-name filespec)))
133    (declare (type string name))
134    (dotimes (i (length name))
135      (declare (type fixnum i))
136      (when (or (char= (char name i) #\-)
137                (char= (char name i) #\Space))
138        (setf (char name i) #\_)))
139    (make-class-name
140     (concatenate 'string "org.armedbear.lisp." name))))
141
142(defun make-unique-class-name ()
143  "Creates a random class name for use with a `class-file' structure's
144`class' slot."
145  (make-class-name
146   (concatenate 'string "abcl_"
147                (substitute #\_ #\-
148                            (java:jcall (java:jmethod "java.util.UUID"
149                                                      "toString")
150                                        (java:jstatic "randomUUID"
151                                                      "java.util.UUID"))))))
152
153(defun make-abcl-class-file (&key pathname lambda-name lambda-list)
154  "Creates a `class-file' structure. If `pathname' is non-NIL, it's
155used to derive a class name. If it is NIL, a random one created
156using `make-unique-class-name'."
157  (let* ((class-name (if pathname
158                         (class-name-from-filespec  pathname)
159                         (make-unique-class-name)))
160         (class-file (%make-abcl-class-file :pathname pathname
161                                            :class class-name
162                                            :lambda-name lambda-name
163                                            :lambda-list lambda-list)))
164    class-file))
165
166(defmacro with-class-file (class-file &body body)
167  (let ((var (gensym)))
168    `(let* ((,var                   ,class-file)
169            (*class-file*           ,var)
170            (*pool*                 (abcl-class-file-constants ,var))
171            (*static-code*          (abcl-class-file-static-code ,var))
172            (*externalized-objects* (abcl-class-file-objects ,var))
173            (*declared-functions*   (abcl-class-file-functions ,var)))
174       (progn ,@body)
175       (setf (abcl-class-file-static-code ,var)  *static-code*
176             (abcl-class-file-objects ,var)      *externalized-objects*
177             (abcl-class-file-functions ,var)    *declared-functions*))))
178
179(defstruct compiland
180  name
181  lambda-expression
182  arg-vars          ; variables for lambda arguments
183  free-specials     ;
184  arity             ; number of args, or NIL if the number of args can vary.
185  p1-result         ; the parse tree as created in pass 1
186  parent            ; the parent for compilands which defined within another
187  (children 0       ; Number of local functions
188            :type fixnum) ; defined with FLET, LABELS or LAMBDA
189  blocks            ; TAGBODY, PROGV, BLOCK, etc. blocks
190  argument-register
191  closure-register
192  environment-register
193  class-file ; class-file object
194  (%single-valued-p t))
195
196(defknown compiland-single-valued-p (t) t)
197(defun compiland-single-valued-p (compiland)
198  (unless (compiland-parent compiland)
199    (let ((name (compiland-name compiland)))
200      (when name
201        (let ((result-type
202               (or (function-result-type name)
203                   (and (proclaimed-ftype name)
204                        (ftype-result-type (proclaimed-ftype name))))))
205          (when result-type
206            (return-from compiland-single-valued-p
207                         (cond ((eq result-type '*)
208                                nil)
209                               ((atom result-type)
210                                t)
211                               ((eq (%car result-type) 'VALUES)
212                                (= (length result-type) 2))
213                               (t
214                                t))))))))
215  ;; Otherwise...
216  (compiland-%single-valued-p compiland))
217
218(defvar *current-compiland* nil)
219
220(defvar *this-class* nil)
221
222;; All tags visible at the current point of compilation, some of which may not
223;; be in the current compiland.
224(defvar *visible-tags* ())
225
226;; The next available register.
227(defvar *register* 0)
228
229;; Total number of registers allocated.
230(defvar *registers-allocated* 0)
231
232;; Variables visible at the current point of compilation.
233(defvar *visible-variables* nil
234  "All variables visible to the form currently being
235processed, including free specials.")
236
237;; All variables seen so far.
238(defvar *all-variables* nil
239  "All variables in the lexical scope (thus excluding free specials)
240of the compilands being processed (p1: so far; p2: in total).")
241
242;; Undefined variables that we've already warned about.
243(defvar *undefined-variables* nil)
244
245(defvar *dump-variables* nil)
246
247(defun dump-1-variable (variable)
248  (sys::%format t "  ~S special-p = ~S register = ~S binding-reg = ~S index = ~S declared-type = ~S~%"
249           (variable-name variable)
250           (variable-special-p variable)
251           (variable-register variable)
252           (variable-binding-register variable)
253           (variable-index variable)
254           (variable-declared-type variable)))
255
256(defun dump-variables (list caption &optional (force nil))
257  (when (or force *dump-variables*)
258    (write-string caption)
259    (if list
260        (dolist (variable list)
261          (dump-1-variable variable))
262        (sys::%format t "  None.~%"))))
263
264(defstruct (variable-info (:conc-name variable-)
265                          (:constructor make-variable)
266                          (:predicate variable-p))
267  name
268  initform
269  (declared-type :none)
270  (derived-type :none)
271  ignore-p
272  ignorable-p
273  representation
274  special-p     ; indicates whether a variable is special
275  register      ; register number for a local variable
276  binding-register ; register number containing the binding reference
277  index         ; index number for a variable in the argument array
278  closure-index ; index number for a variable in the closure context array
279  environment   ; the environment for the variable, if we're compiling in
280                ; a non-null lexical environment with variables
281    ;; a variable can be either special-p *or* have a register *or*
282    ;; have an index *or* a closure-index *or* an environment
283  (reads 0 :type fixnum)
284  (writes 0 :type fixnum)
285  references
286  (references-allowed-p t) ; NIL if this is a symbol macro in the enclosing
287                           ; lexical environment
288  used-non-locally-p
289  (compiland *current-compiland*)
290  block)
291
292(defstruct (var-ref (:constructor make-var-ref (variable)))
293  ;; The variable this reference refers to. Will be NIL if the VAR-REF has been
294  ;; rewritten to reference a constant value.
295  variable
296  ;; True if the VAR-REF has been rewritten to reference a constant value.
297  constant-p
298  ;; The constant value of this VAR-REF.
299  constant-value)
300
301;; obj can be a symbol or variable
302;; returns variable or nil
303(declaim (ftype (function (t) t) unboxed-fixnum-variable))
304(defun unboxed-fixnum-variable (obj)
305  (cond ((symbolp obj)
306         (let ((variable (find-visible-variable obj)))
307           (if (and variable
308                    (eq (variable-representation variable) :int))
309               variable
310               nil)))
311        ((variable-p obj)
312         (if (eq (variable-representation obj) :int)
313             obj
314             nil))
315        (t
316         nil)))
317
318(defvar *child-p* nil
319  "True for local functions created by FLET, LABELS and (NAMED-)LAMBDA")
320
321(defknown find-variable (symbol list) t)
322(defun find-variable (name variables)
323  (dolist (variable variables)
324    (when (eq name (variable-name variable))
325      (return variable))))
326
327(defknown find-visible-variable (t) t)
328(defun find-visible-variable (name)
329  (dolist (variable *visible-variables*)
330    (when (eq name (variable-name variable))
331      (return variable))))
332
333(defknown allocate-register () (integer 0 65535))
334(defun allocate-register ()
335  (let* ((register *register*)
336         (next-register (1+ register)))
337    (declare (type (unsigned-byte 16) register next-register))
338    (setf *register* next-register)
339    (when (< *registers-allocated* next-register)
340      (setf *registers-allocated* next-register))
341    register))
342
343(defknown allocate-register-pair () (integer 0 65535))
344(defun allocate-register-pair ()
345  (let* ((register *register*)
346         (next-register (+ register 2)))
347    (declare (type (unsigned-byte 16) register next-register))
348    (setf *register* next-register)
349    (when (< *registers-allocated* next-register)
350      (setf *registers-allocated* next-register))
351    register))
352
353(defstruct local-function
354  name
355  definition
356  compiland
357  inline-expansion
358  function    ;; the function loaded through load-compiled-function
359  class-file  ;; the class file structure for this function
360  variable    ;; the variable which contains the loaded compiled function
361              ;; or compiled closure
362  environment ;; the environment in which the function is stored in
363              ;; case of a function from an enclosing lexical environment
364              ;; which itself isn't being compiled
365  (references-allowed-p t) ;;whether a reference to the function CAN be captured
366  (references-needed-p nil) ;;whether a reference to the function NEEDS to be
367          ;;captured, because the function name is used in a
368                            ;;(function ...) form. Obviously implies
369                            ;;references-allowed-p.
370  )
371
372(defvar *local-functions* ())
373
374(defknown find-local-function (t) t)
375(defun find-local-function (name)
376  (dolist (local-function *local-functions* nil)
377    (when (equal name (local-function-name local-function))
378        (return local-function))))
379
380(defvar *using-arg-array* nil)
381(defvar *hairy-arglist-p* nil)
382
383(defstruct node
384  form
385  (compiland *current-compiland*))
386;; No need for a special constructor: nobody instantiates
387;; nodes directly
388
389;; control-transferring blocks: TAGBODY, CATCH, to do: BLOCK
390
391(defstruct (control-transferring-node (:include node))
392  ;; If non-nil, the TAGBODY contains local blocks which "contaminate" the
393  ;; environment, with GO forms in them which target tags in this TAGBODY
394  ;; Non-nil if and only if the block doesn't modify the environment
395  needs-environment-restoration
396  )
397;; No need for a special constructor: nobody instantiates
398;; control-transferring-nodes directly
399
400(defstruct (tagbody-node (:conc-name tagbody-)
401                         (:include control-transferring-node)
402       (:constructor %make-tagbody-node ()))
403  ;; True if a tag in this tagbody is the target of a non-local GO.
404  non-local-go-p
405  ;; Tags in the tagbody form; a list of tag structures
406  tags
407  ;; Contains a variable whose value uniquely identifies the
408  ;; lexical scope from this block, to be used by GO
409  id-variable)
410(defknown make-tagbody-node () t)
411(defun make-tagbody-node ()
412  (let ((block (%make-tagbody-node)))
413    (push block (compiland-blocks *current-compiland*))
414    block))
415
416(defstruct (catch-node (:conc-name catch-)
417                       (:include control-transferring-node)
418           (:constructor %make-catch-node ()))
419  ;; The catch tag-form is evaluated, meaning we
420  ;; have no predefined value to store here
421  )
422(defknown make-catch-node () t)
423(defun make-catch-node ()
424  (let ((block (%make-catch-node)))
425    (push block (compiland-blocks *current-compiland*))
426    block))
427
428(defstruct (block-node (:conc-name block-)
429                       (:include control-transferring-node)
430                       (:constructor %make-block-node (name)))
431  name  ;; Block name
432  (exit (gensym))
433  target
434  ;; True if there is a non-local RETURN from this block.
435  non-local-return-p
436  ;; Contains a variable whose value uniquely identifies the
437  ;; lexical scope from this block, to be used by RETURN-FROM
438  id-variable)
439(defknown make-block-node (t) t)
440(defun make-block-node (name)
441  (let ((block (%make-block-node name)))
442    (push block (compiland-blocks *current-compiland*))
443    block))
444
445;; binding blocks: LET, LET*, FLET, LABELS, M-V-B, PROGV, LOCALLY
446;;
447;; Binding blocks can carry references to local (optionally special) variable bindings,
448;;  contain free special bindings or both
449
450(defstruct (binding-node (:include node))
451  ;; number of the register of the saved dynamic env, or NIL if none
452  environment-register
453  ;; Not used for LOCALLY and FLET; LABELS uses vars to store its functions
454  vars
455  free-specials)
456;; nobody instantiates any binding nodes directly, so there's no reason
457;; to create a constructor with the approprate administration code
458
459(defstruct (let/let*-node (:conc-name let-)
460                          (:include binding-node)
461        (:constructor %make-let/let*-node ())))
462(defknown make-let/let*-node () t)
463(defun make-let/let*-node ()
464  (let ((block (%make-let/let*-node)))
465    (push block (compiland-blocks *current-compiland*))
466    block))
467
468(defstruct (flet-node (:conc-name flet-)
469                      (:include binding-node)
470          (:constructor %make-flet-node ())))
471(defknown make-flet-node () t)
472(defun make-flet-node ()
473  (let ((block (%make-flet-node)))
474    (push block (compiland-blocks *current-compiland*))
475    block))
476
477(defstruct (labels-node (:conc-name labels-)
478                        (:include binding-node)
479      (:constructor %make-labels-node ())))
480(defknown make-labels-node () t)
481(defun make-labels-node ()
482  (let ((block (%make-labels-node)))
483    (push block (compiland-blocks *current-compiland*))
484    block))
485
486(defstruct (m-v-b-node (:conc-name m-v-b-)
487                       (:include binding-node)
488           (:constructor %make-m-v-b-node ())))
489(defknown make-m-v-b-node () t)
490(defun make-m-v-b-node ()
491  (let ((block (%make-m-v-b-node)))
492    (push block (compiland-blocks *current-compiland*))
493    block))
494
495(defstruct (progv-node (:conc-name progv-)
496                       (:include binding-node)
497           (:constructor %make-progv-node ())))
498(defknown make-progv-node () t)
499(defun make-progv-node ()
500  (let ((block (%make-progv-node)))
501    (push block (compiland-blocks *current-compiland*))
502    block))
503
504(defstruct (locally-node (:conc-name locally-)
505                         (:include binding-node)
506       (:constructor %make-locally-node ())))
507(defknown make-locally-node () t)
508(defun make-locally-node ()
509  (let ((block (%make-locally-node)))
510    (push block (compiland-blocks *current-compiland*))
511    block))
512
513;; blocks requiring non-local exits: UNWIND-PROTECT, SYS:SYNCHRONIZED-ON
514
515(defstruct (protected-node (:include node)
516         (:constructor %make-protected-node ())))
517(defknown make-protected-node () t)
518(defun make-protected-node ()
519  (let ((block (%make-protected-node)))
520    (push block (compiland-blocks *current-compiland*))
521    block))
522
523(defstruct (unwind-protect-node (:conc-name unwind-protect-)
524                                (:include protected-node)
525        (:constructor %make-unwind-protect-node ())))
526(defknown make-unwind-protect-node () t)
527(defun make-unwind-protect-node ()
528  (let ((block (%make-unwind-protect-node)))
529    (push block (compiland-blocks *current-compiland*))
530    block))
531
532(defstruct (synchronized-node (:conc-name synchronized-)
533                              (:include protected-node)
534            (:constructor %make-synchronized-node ())))
535(defknown make-synchronized-node () t)
536(defun make-synchronized-node ()
537  (let ((block (%make-synchronized-node)))
538    (push block (compiland-blocks *current-compiland*))
539    block))
540
541
542(defvar *blocks* ())
543
544(defun find-block (name)
545  (dolist (block *blocks*)
546    (when (and (block-node-p block)
547               (eq name (block-name block)))
548      (return block))))
549
550(defknown node-constant-p (t) boolean)
551(defun node-constant-p (object)
552  (cond ((node-p object)
553         nil)
554        ((var-ref-p object)
555         nil)
556        ((constantp object)
557         t)
558        (t
559         nil)))
560
561(defknown block-requires-non-local-exit-p (t) boolean)
562(defun block-requires-non-local-exit-p (object)
563  "A block which *always* requires a 'non-local-exit' is a block which
564requires a transfer control exception to be thrown: e.g. Go and Return.
565
566Non-local exits are required by blocks which do more in their cleanup
567than just restore the lastSpecialBinding (= dynamic environment).
568"
569  (or (unwind-protect-node-p object)
570      (catch-node-p object)
571      (synchronized-node-p object)))
572
573(defknown block-creates-runtime-bindings-p (t) boolean)
574(defun block-creates-runtime-bindings-p (block)
575  ;; FIXME: This may be false, if the bindings to be
576  ;; created are a quoted list
577  (progv-node-p block))
578
579(defknown enclosed-by-runtime-bindings-creating-block-p (t) boolean)
580(defun enclosed-by-runtime-bindings-creating-block-p (outermost-block)
581  "Indicates whether the code being compiled/analyzed is enclosed in a
582block which creates special bindings at runtime."
583  (dolist (enclosing-block *blocks*)
584    (when (eq enclosing-block outermost-block)
585      (return-from enclosed-by-runtime-bindings-creating-block-p nil))
586    (when (block-creates-runtime-bindings-p enclosing-block)
587      (return-from enclosed-by-runtime-bindings-creating-block-p t))))
588
589(defknown enclosed-by-protected-block-p (&optional t) boolean)
590(defun enclosed-by-protected-block-p (&optional outermost-block)
591  "Indicates whether the code being compiled/analyzed is enclosed in
592a block which requires a non-local transfer of control exception to
593be generated.
594"
595  (dolist (enclosing-block *blocks*)
596    (when (eq enclosing-block outermost-block)
597      (return-from enclosed-by-protected-block-p nil))
598    (when (block-requires-non-local-exit-p enclosing-block)
599      (return-from enclosed-by-protected-block-p t))))
600
601(defknown enclosed-by-environment-setting-block-p (&optional t) boolean)
602(defun enclosed-by-environment-setting-block-p (&optional outermost-block)
603  (dolist (enclosing-block *blocks*)
604    (when (eq enclosing-block outermost-block)
605      (return nil))
606    (when (and (binding-node-p enclosing-block)
607               (binding-node-environment-register enclosing-block))
608      (return t))))
609
610(defknown environment-register-to-restore (&optional t) t)
611(defun environment-register-to-restore (&optional outermost-block)
612  "Returns the environment register which contains the
613saved environment from the outermost enclosing block:
614
615That's the one which contains the environment used in the outermost block."
616  (flet ((outermost-register (last-register block)
617           (when (eq block outermost-block)
618             (return-from environment-register-to-restore last-register))
619           (or (and (binding-node-p block)
620                    (binding-node-environment-register block))
621               last-register)))
622    (reduce #'outermost-register *blocks*
623            :initial-value nil)))
624
625(defstruct tag
626  ;; The symbol (or integer) naming the tag
627  name
628  ;; The symbol which is the jump target in JVM byte code
629  label
630  ;; The associated TAGBODY
631  block
632  (compiland *current-compiland*)
633  used
634  used-non-locally)
635
636(defknown find-tag (t) t)
637(defun find-tag (name)
638  (dolist (tag *visible-tags*)
639    (when (eql name (tag-name tag))
640      (return tag))))
641
642(defun process-ignore/ignorable (declaration names variables)
643  (when (memq declaration '(IGNORE IGNORABLE))
644    (let ((what (if (eq declaration 'IGNORE) "ignored" "ignorable")))
645      (dolist (name names)
646        (unless (and (consp name) (eq (car name) 'FUNCTION))
647          (let ((variable (find-variable name variables)))
648            (cond ((null variable)
649                   (compiler-style-warn "Declaring unknown variable ~S to be ~A."
650                                        name what))
651                  ((variable-special-p variable)
652                   (compiler-style-warn "Declaring special variable ~S to be ~A."
653                                        name what))
654                  ((eq declaration 'IGNORE)
655                   (setf (variable-ignore-p variable) t))
656                  (t
657                   (setf (variable-ignorable-p variable) t)))))))))
658
659(defun finalize-generic-functions ()
660  (dolist (sym '(make-instance
661                 initialize-instance
662                 shared-initialize))
663    (let ((gf (and (fboundp sym) (fdefinition sym))))
664      (when (typep gf 'generic-function)
665        (unless (compiled-function-p gf)
666          (mop::finalize-generic-function gf))))))
667
668(finalize-generic-functions)
669
670(provide 'jvm)
Note: See TracBrowser for help on using the repository browser.