0.6.12.22:
[sbcl.git] / src / compiler / byte-comp.lisp
1 ;;;; that part of the byte compiler which exists not only in the
2 ;;;; target Lisp, but also in the cross-compilation host Lisp
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!C")
14
15 ;;; ### remaining work:
16 ;;;
17 ;;; - add more inline operations.
18 ;;; - Breakpoints/debugging info.
19 \f
20 ;;;; stuff to emit noise
21
22 ;;; Note: We use the regular assembler, but we don't use any
23 ;;; ``instructions'' because there is no way to keep our byte-code
24 ;;; instructions separate from the instructions used by the native
25 ;;; backend. Besides, we don't want to do any scheduling or anything
26 ;;; like that, anyway.
27
28 #!-sb-fluid (declaim (inline output-byte))
29 (defun output-byte (segment byte)
30   (declare (type sb!assem:segment segment)
31            (type (unsigned-byte 8) byte))
32   (sb!assem:emit-byte segment byte))
33
34 ;;; Output OPERAND as 1 or 4 bytes, using #xFF as the extend code.
35 (defun output-extended-operand (segment operand)
36   (declare (type (unsigned-byte 24) operand))
37   (cond ((<= operand 254)
38          (output-byte segment operand))
39         (t
40          (output-byte segment #xFF)
41          (output-byte segment (ldb (byte 8 16) operand))
42          (output-byte segment (ldb (byte 8 8) operand))
43          (output-byte segment (ldb (byte 8 0) operand)))))
44
45 ;;; Output a byte, logior'ing in a 4 bit immediate constant. If that
46 ;;; immediate won't fit, then emit it as the next 1-4 bytes.
47 (defun output-byte-with-operand (segment byte operand)
48   (declare (type sb!assem:segment segment)
49            (type (unsigned-byte 8) byte)
50            (type (unsigned-byte 24) operand))
51   (cond ((<= operand 14)
52          (output-byte segment (logior byte operand)))
53         (t
54          (output-byte segment (logior byte 15))
55          (output-extended-operand segment operand)))
56   (values))
57
58 (defun output-label (segment label)
59   (declare (type sb!assem:segment segment)
60            (type sb!assem:label label))
61   (sb!assem:assemble (segment)
62     (sb!assem:emit-label label)))
63
64 ;;; Output a reference to LABEL.
65 (defun output-reference (segment label)
66   (declare (type sb!assem:segment segment)
67            (type sb!assem:label label))
68   (sb!assem:emit-back-patch
69    segment
70    3
71    #'(lambda (segment posn)
72        (declare (type sb!assem:segment segment)
73                 (ignore posn))
74        (let ((target (sb!assem:label-position label)))
75          (aver (<= 0 target (1- (ash 1 24))))
76          (output-byte segment (ldb (byte 8 16) target))
77          (output-byte segment (ldb (byte 8 8) target))
78          (output-byte segment (ldb (byte 8 0) target))))))
79
80 ;;; Output some branch byte-sequence.
81 (defun output-branch (segment kind label)
82   (declare (type sb!assem:segment segment)
83            (type (unsigned-byte 8) kind)
84            (type sb!assem:label label))
85   (sb!assem:emit-chooser
86    segment 4 1
87    #'(lambda (segment posn delta)
88        (when (<= (- (ash 1 7))
89                  (- (sb!assem:label-position label posn delta) posn 2)
90                  (1- (ash 1 7)))
91          (sb!assem:emit-chooser
92           segment 2 1
93           #'(lambda (segment posn delta)
94               (declare (ignore segment) (type index posn delta))
95               (when (zerop (- (sb!assem:label-position label posn delta)
96                               posn 2))
97                 ;; Don't emit anything, because the branch is to the following
98                 ;; instruction.
99                 t))
100           #'(lambda (segment posn)
101               ;; We know that we fit in one byte.
102               (declare (type sb!assem:segment segment)
103                        (type index posn))
104               (output-byte segment (logior kind 1))
105               (output-byte segment
106                            (ldb (byte 8 0)
107                                 (- (sb!assem:label-position label) posn 2)))))
108          t))
109    #'(lambda (segment posn)
110        (declare (type sb!assem:segment segment)
111                 (ignore posn))
112        (let ((target (sb!assem:label-position label)))
113          (aver (<= 0 target (1- (ash 1 24))))
114          (output-byte segment kind)
115          (output-byte segment (ldb (byte 8 16) target))
116          (output-byte segment (ldb (byte 8 8) target))
117          (output-byte segment (ldb (byte 8 0) target))))))
118 \f
119 ;;;; system constants, Xops, and inline functions
120
121 ;;; If (%FDEFINITION-MARKER% . NAME) is a key in the table, then the
122 ;;; corresponding value is the byte code fdefinition.
123 (eval-when (:compile-toplevel :load-toplevel :execute)
124   (defvar *system-constant-codes* (make-hash-table :test 'equal)))
125
126 (eval-when (:compile-toplevel :load-toplevel :execute)
127   (flet ((def-system-constant (index form)
128            (setf (gethash form *system-constant-codes*) index)))
129     (def-system-constant 0 nil)
130     (def-system-constant 1 t)
131     (def-system-constant 2 :start)
132     (def-system-constant 3 :end)
133     (def-system-constant 4 :test)
134     (def-system-constant 5 :count)
135     (def-system-constant 6 :test-not)
136     (def-system-constant 7 :key)
137     (def-system-constant 8 :from-end)
138     (def-system-constant 9 :type)
139     (def-system-constant 10 '(%fdefinition-marker% . error))
140     (def-system-constant 11 '(%fdefinition-marker% . format))
141     (def-system-constant 12 '(%fdefinition-marker% . %typep))
142     (def-system-constant 13 '(%fdefinition-marker% . eql))
143     (def-system-constant 14 '(%fdefinition-marker% . %negate))
144     (def-system-constant 15 '(%fdefinition-marker% . %%defun))
145     (def-system-constant 16 '(%fdefinition-marker% . %%defmacro))
146     (def-system-constant 17 '(%fdefinition-marker% . %%defconstant))
147     (def-system-constant 18 '(%fdefinition-marker% . length))
148     (def-system-constant 19 '(%fdefinition-marker% . equal))
149     (def-system-constant 20 '(%fdefinition-marker% . append))
150     (def-system-constant 21 '(%fdefinition-marker% . reverse))
151     (def-system-constant 22 '(%fdefinition-marker% . nreverse))
152     (def-system-constant 23 '(%fdefinition-marker% . nconc))
153     (def-system-constant 24 '(%fdefinition-marker% . list))
154     (def-system-constant 25 '(%fdefinition-marker% . list*))
155     (def-system-constant 26 '(%fdefinition-marker% . %coerce-name-to-function))
156     (def-system-constant 27 '(%fdefinition-marker% . values-list))))
157
158 (eval-when (#+sb-xc :compile-toplevel :load-toplevel :execute)
159
160 (defparameter *xop-names*
161   '(breakpoint; 0
162     dup; 1
163     type-check; 2
164     fdefn-function-or-lose; 3
165     default-unknown-values; 4
166     push-n-under; 5
167     xop6
168     xop7
169     merge-unknown-values
170     make-closure
171     throw
172     catch
173     breakup
174     return-from
175     tagbody
176     go
177     unwind-protect))
178
179 (defun xop-index-or-lose (name)
180   (or (position name *xop-names* :test #'eq)
181       (error "unknown XOP ~S" name)))
182
183 ) ; EVAL-WHEN
184
185 ;;; FIXME: The hardwired 32 here (found also in (MOD 32) above, and in
186 ;;; the number of bits tested in EXPAND-INTO-INLINES, and perhaps
187 ;;; elsewhere) is ugly. There should be some symbolic constant for the
188 ;;; number of bits devoted to coding byte-inline functions.
189 (eval-when (:compile-toplevel :load-toplevel :execute)
190
191   (defstruct (inline-function-info (:copier nil))
192     ;; the name of the function that we convert into calls to this
193     (function (required-argument) :type symbol)
194     ;; the name of the function that the interpreter should call to
195     ;; implement this. This may not be the same as the FUNCTION slot
196     ;; value if extra safety checks are required.
197     (interpreter-function (required-argument) :type symbol)
198     ;; the inline operation number, i.e. the byte value actually
199     ;; written into byte-compiled code
200     (number (required-argument) :type (mod 32))
201     ;; the type that calls must satisfy
202     (type (required-argument) :type function-type)
203     ;; Can we skip type checking of the arguments?
204     (safe (required-argument) :type boolean))
205
206   (defparameter *inline-functions* (make-array 32 :initial-element nil))
207   (defparameter *inline-function-table* (make-hash-table :test 'eq))
208   (let ((number 0))
209     (dolist (stuff
210              '((+ (fixnum fixnum) fixnum)
211                (- (fixnum fixnum) fixnum)
212                (make-value-cell (t) t)
213                (value-cell-ref (t) t)
214                (value-cell-setf (t t) (values))
215                (symbol-value (symbol) t
216                              :interpreter-function %byte-symbol-value)
217                (setf-symbol-value (t symbol) (values))
218                (%byte-special-bind (t symbol) (values))
219                (%byte-special-unbind () (values))
220                (%negate (fixnum) fixnum)
221                (< (fixnum fixnum) t)
222                (> (fixnum fixnum) t)
223                (car (t) t :interpreter-function %byte-car :safe t)
224                (cdr (t) t :interpreter-function %byte-cdr :safe t)
225                (length (list) t)
226                (cons (t t) t)
227                (list (t t) t)
228                (list* (t t t) t)
229                (%instance-ref (t t) t)
230                (%setf-instance-ref (t t t) (values))))
231       (destructuring-bind
232           (name arg-types result-type
233                 &key (interpreter-function name) alias safe)
234           stuff
235         (let ((info
236                (make-inline-function-info
237                 :function name
238                 :number number
239                 :interpreter-function interpreter-function
240                 :type (specifier-type `(function ,arg-types ,result-type))
241                 :safe safe)))
242           (setf (svref *inline-functions* number) info)
243           (setf (gethash name *inline-function-table*) info))
244         (unless alias (incf number))))))
245
246 (defun inline-function-number-or-lose (function)
247   (let ((info (gethash function *inline-function-table*)))
248     (if info
249         (inline-function-info-number info)
250         (error "unknown inline function: ~S" function))))
251 \f
252 ;;;; transforms which are specific to byte code
253
254 ;;; It appears that the idea here is that in byte code, EQ is more
255 ;;; efficient than CHAR=. -- WHN 199910
256
257 (deftransform eql ((x y) ((or fixnum character) (or fixnum character))
258                    * :when :byte)
259   '(eq x y))
260
261 (deftransform char= ((x y) * * :when :byte)
262   '(eq x y))
263 \f
264 ;;;; annotations hung off the IR1 while compiling
265
266 (defstruct (byte-component-info (:copier nil))
267   (constants (make-array 10 :adjustable t :fill-pointer 0)))
268
269 (defstruct (byte-lambda-info (:copier nil))
270   (label nil :type (or null label))
271   (stack-size 0 :type index)
272   ;; FIXME: should be INTERESTING-P T :TYPE BOOLEAN
273   (interesting t :type (member t nil)))
274
275 (defun block-interesting (block)
276   (byte-lambda-info-interesting (lambda-info (block-home-lambda block))))
277
278 (defstruct (byte-lambda-var-info (:copier nil))
279   (argp nil :type (member t nil))
280   (offset 0 :type index))
281
282 (defstruct (byte-nlx-info (:copier nil))
283   (stack-slot nil :type (or null index))
284   (label (sb!assem:gen-label) :type sb!assem:label)
285   (duplicate nil :type (member t nil)))
286
287 (defstruct (byte-block-info
288             (:copier nil)
289             (:include block-annotation)
290             (:constructor make-byte-block-info
291                           (block &key produces produces-sset consumes
292                             total-consumes nlx-entries nlx-entry-p)))
293   (label (sb!assem:gen-label) :type sb!assem:label)
294   ;; A list of the CONTINUATIONs describing values that this block
295   ;; pushes onto the stack. Note: PRODUCES and CONSUMES can contain
296   ;; the keyword :NLX-ENTRY marking the place on the stack where a
297   ;; non-local-exit frame is added or removed. Since breaking up a NLX
298   ;; restores the stack, we don't have to about (and in fact must not)
299   ;; discard values underneath a :NLX-ENTRY marker evern though they
300   ;; appear to be dead (since they might not be.)
301   (produces nil :type list)
302   ;; An SSET of the produces for faster set manipulations. The
303   ;; elements are the BYTE-CONTINUATION-INFO objects. :NLX-ENTRY
304   ;; markers are not represented.
305   (produces-sset (make-sset) :type sset)
306   ;; A list of the continuations that this block pops from the stack.
307   ;; See PRODUCES.
308   (consumes nil :type list)
309   ;; The transitive closure of what this block and all its successors
310   ;; consume. After stack-analysis, that is.
311   (total-consumes (make-sset) :type sset)
312   ;; Set to T whenever the consumes lists of a successor changes and
313   ;; the block is queued for re-analysis so we can easily avoid
314   ;; queueing the same block several times.
315   (already-queued nil :type (member t nil))
316   ;; The continuations and :NLX-ENTRY markers on the stack (in order)
317   ;; when this block starts.
318   (start-stack :unknown :type (or (member :unknown) list))
319   ;; The continuations and :NLX-ENTRY markers on the stack (in order)
320   ;; when this block ends.
321   (end-stack nil :type list)
322   ;; List of ((nlx-info*) produces consumes) for each ENTRY in this
323   ;; block that is a NLX target.
324   (nlx-entries nil :type list)
325   ;; T if this is an %nlx-entry point, and we shouldn't just assume we
326   ;; know what is going to be on the stack.
327   (nlx-entry-p nil :type (member t nil)))
328
329 (defprinter (byte-block-info)
330   block)
331
332 (defstruct (byte-continuation-info
333             (:include sset-element)
334             (:constructor make-byte-continuation-info
335                           (continuation results placeholders))
336             (:copier nil))
337   (continuation (required-argument) :type continuation)
338   (results (required-argument)
339            :type (or (member :fdefinition :eq-test :unknown) index))
340   ;; If the DEST is a local non-MV call, then we may need to push some
341   ;; number of placeholder args corresponding to deleted
342   ;; (unreferenced) args. If PLACEHOLDERS /= 0, then RESULTS is
343   ;; PLACEHOLDERS + 1.
344   (placeholders (required-argument) :type index))
345
346 (defprinter (byte-continuation-info)
347   continuation
348   results
349   (placeholders :test (/= placeholders 0)))
350 \f
351 ;;;; Annotate the IR1.
352
353 (defun annotate-continuation (cont results &optional (placeholders 0))
354   ;; For some reason, DO-NODES does the same return node multiple
355   ;; times, which causes ANNOTATE-CONTINUATION to be called multiple
356   ;; times on the same continuation. So we can't assert that we
357   ;; haven't done it.
358   #+nil
359   (aver (null (continuation-info cont)))
360   (setf (continuation-info cont)
361         (make-byte-continuation-info cont results placeholders))
362   (values))
363
364 (defun annotate-set (set)
365   ;; Annotate the value for one value.
366   (annotate-continuation (set-value set) 1))
367
368 ;;; We do different stack magic for non-MV and MV calls to figure out
369 ;;; how many values should be pushed during compilation of each arg.
370 ;;;
371 ;;; Since byte functions are directly caller by the interpreter (there
372 ;;; is no XEP), and it doesn't know which args are actually used, byte
373 ;;; functions must allow unused args to be passed. But this creates a
374 ;;; problem with local calls, because these unused args would not
375 ;;; otherwise be pushed (since the continuation has been deleted.) So,
376 ;;; in this function, we count up placeholders for any unused args
377 ;;; contiguously preceding this one. These placeholders are inserted
378 ;;; under the referenced arg by CHECKED-CANONICALIZE-VALUES.
379 ;;;
380 ;;; With MV calls, we try to figure out how many values are actually
381 ;;; generated. We allow initial args to supply a fixed number of
382 ;;; values, but everything after the first :unknown arg must also be
383 ;;; unknown. This picks off most of the standard uses (i.e. calls to
384 ;;; apply), but still is easy to implement.
385 (defun annotate-basic-combination-args (call)
386   (declare (type basic-combination call))
387   (etypecase call
388     (combination
389      (if (and (eq (basic-combination-kind call) :local)
390               (member (functional-kind (combination-lambda call))
391                       '(nil :optional :cleanup)))
392          (let ((placeholders 0))
393            (declare (type index placeholders))
394            (dolist (arg (combination-args call))
395              (cond (arg
396                     (annotate-continuation arg (1+ placeholders) placeholders)
397                     (setq placeholders 0))
398                    (t
399                     (incf placeholders)))))
400          (dolist (arg (combination-args call))
401            (when arg
402              (annotate-continuation arg 1)))))
403     (mv-combination
404      (labels
405          ((allow-fixed (remaining)
406             (when remaining
407               (let* ((cont (car remaining))
408                      (values (nth-value 1
409                                         (values-types
410                                          (continuation-derived-type cont)))))
411                 (cond ((eq values :unknown)
412                        (force-to-unknown remaining))
413                       (t
414                        (annotate-continuation cont values)
415                        (allow-fixed (cdr remaining)))))))
416           (force-to-unknown (remaining)
417             (when remaining
418               (let ((cont (car remaining)))
419                 (when cont
420                   (annotate-continuation cont :unknown)))
421               (force-to-unknown (cdr remaining)))))
422        (allow-fixed (mv-combination-args call)))))
423   (values))
424
425 (defun annotate-local-call (call)
426   (cond ((mv-combination-p call)
427          (annotate-continuation
428           (first (basic-combination-args call))
429           (length (lambda-vars (combination-lambda call)))))
430         (t
431          (annotate-basic-combination-args call)
432          (when (member (functional-kind (combination-lambda call))
433                        '(nil :optional :cleanup))
434            (dolist (arg (basic-combination-args call))
435              (when arg
436                (setf (continuation-%type-check arg) nil))))))
437   (annotate-continuation (basic-combination-fun call) 0)
438   (when (node-tail-p call)
439     (set-tail-local-call-successor call)))
440
441 ;;; Annotate the values for any :full combination. This includes
442 ;;; inline functions, multiple value calls & throw. If a real full
443 ;;; call or a safe inline operation, then clear any type-check
444 ;;; annotations. When we are done, remove jump to return for tail
445 ;;; calls.
446 ;;;
447 ;;; Also, we annotate slot accessors as inline if no type check is
448 ;;; needed and (for setters) no value needs to be left on the stack.
449 (defun annotate-full-call (call)
450   (let* ((fun (basic-combination-fun call))
451          (args (basic-combination-args call))
452          (name (continuation-function-name fun))
453          (info (gethash name *inline-function-table*)))
454     (flet ((annotate-args ()
455              (annotate-basic-combination-args call)
456              (dolist (arg args)
457                (when (continuation-type-check arg)
458                  (setf (continuation-%type-check arg) :deleted)))
459              (annotate-continuation
460               fun
461               (if (continuation-function-name fun) :fdefinition 1))))
462       (cond ((mv-combination-p call)
463              (cond ((eq name '%throw)
464                     (aver (= (length args) 2))
465                     (annotate-continuation (first args) 1)
466                     (annotate-continuation (second args) :unknown)
467                     (setf (node-tail-p call) nil)
468                     (annotate-continuation fun 0))
469                    (t
470                     (annotate-args))))
471             ((and info
472                   (valid-function-use call (inline-function-info-type info)))
473              (annotate-basic-combination-args call)
474              (setf (node-tail-p call) nil)
475              (setf (basic-combination-info call) info)
476              (annotate-continuation fun 0)
477              (when (inline-function-info-safe info)
478                (dolist (arg args)
479                  (when (continuation-type-check arg)
480                    (setf (continuation-%type-check arg) :deleted)))))
481             ((and name
482                   (let ((leaf (ref-leaf (continuation-use fun))))
483                     (and (slot-accessor-p leaf)
484                          (or (policy call (zerop safety))
485                              (not (find t args
486                                         :key #'continuation-type-check)))
487                          (if (consp name)
488                              (not (continuation-dest (node-cont call)))
489                              t))))
490              (setf (basic-combination-info call)
491                    (gethash (if (consp name) '%setf-instance-ref '%instance-ref)
492                             *inline-function-table*))
493              (setf (node-tail-p call) nil)
494              (annotate-continuation fun 0)
495              (annotate-basic-combination-args call))
496             (t
497              (annotate-args)))))
498
499   ;; If this is (still) a tail-call, then blow away the return.
500   (when (node-tail-p call)
501     (node-ends-block call)
502     (let ((block (node-block call)))
503       (unlink-blocks block (first (block-succ block)))
504       (link-blocks block (component-tail (block-component block)))))
505
506   (values))
507
508 (defun annotate-known-call (call)
509   (annotate-basic-combination-args call)
510   (setf (node-tail-p call) nil)
511   (annotate-continuation (basic-combination-fun call) 0)
512   t)
513
514 (defun annotate-basic-combination (call)
515   ;; Annotate the function.
516   (let ((kind (basic-combination-kind call)))
517     (case kind
518       (:local
519        (annotate-local-call call))
520       (:full
521        (annotate-full-call call))
522       (:error
523        (setf (basic-combination-kind call) :full)
524        (annotate-full-call call))
525       (t
526        (unless (and (function-info-byte-compile kind)
527                     (funcall (or (function-info-byte-annotate kind)
528                                  #'annotate-known-call)
529                              call))
530          (setf (basic-combination-kind call) :full)
531          (annotate-full-call call)))))
532
533   (values))
534
535 (defun annotate-if (if)
536   ;; Annotate the test.
537   (let* ((cont (if-test if))
538          (use (continuation-use cont)))
539     (annotate-continuation
540      cont
541      (if (and (combination-p use)
542               (eq (continuation-function-name (combination-fun use)) 'eq)
543               (= (length (combination-args use)) 2))
544          ;; If the test is a call to EQ, then we can use branch-if-eq
545          ;; so don't need to actually funcall the test.
546          :eq-test
547          ;; Otherwise, funcall the test for 1 value.
548          1))))
549
550 (defun annotate-return (return)
551   (let ((cont (return-result return)))
552     (annotate-continuation
553      cont
554      (nth-value 1 (values-types (continuation-derived-type cont))))))
555
556 (defun annotate-exit (exit)
557   (let ((cont (exit-value exit)))
558     (when cont
559       (annotate-continuation cont :unknown))))
560
561 (defun annotate-block (block)
562   (do-nodes (node cont block)
563     (etypecase node
564       (bind)
565       (ref)
566       (cset (annotate-set node))
567       (basic-combination (annotate-basic-combination node))
568       (cif (annotate-if node))
569       (creturn (annotate-return node))
570       (entry)
571       (exit (annotate-exit node))))
572   (values))
573
574 (defun annotate-ir1 (component)
575   (do-blocks (block component)
576     (when (block-interesting block)
577       (annotate-block block)))
578   (values))
579 \f
580 ;;;; stack analysis
581
582 (defvar *byte-continuation-counter*)
583
584 ;;; Scan the nodes in BLOCK and compute the information that we will
585 ;;; need to do flow analysis and our stack simulation walk. We simulate
586 ;;; the stack within the block, reducing it to ordered lists
587 ;;; representing the values we remove from the top of the stack and
588 ;;; place on the stack (not considering values that are produced and
589 ;;; consumed within the block.) A NLX entry point is considered to
590 ;;; push a :NLX-ENTRY marker (can be though of as the run-time catch
591 ;;; frame.)
592 (defun compute-produces-and-consumes (block)
593   (let ((stack nil)
594         (consumes nil)
595         (total-consumes (make-sset))
596         (nlx-entries nil)
597         (nlx-entry-p nil))
598     (labels ((interesting (cont)
599                (and cont
600                     (let ((info (continuation-info cont)))
601                       (and info
602                            (not (member (byte-continuation-info-results info)
603                                         '(0 :eq-test)))))))
604              (consume (cont)
605                (cond ((not (or (eq cont :nlx-entry) (interesting cont))))
606                      (stack
607                       (aver (eq (car stack) cont))
608                       (pop stack))
609                      (t
610                       (adjoin-cont cont total-consumes)
611                       (push cont consumes))))
612              (adjoin-cont (cont sset)
613                (unless (eq cont :nlx-entry)
614                  (let ((info (continuation-info cont)))
615                    (unless (byte-continuation-info-number info)
616                      (setf (byte-continuation-info-number info)
617                            (incf *byte-continuation-counter*)))
618                    (sset-adjoin info sset)))))
619       (do-nodes (node cont block)
620         (etypecase node
621           (bind)
622           (ref)
623           (cset
624            (consume (set-value node)))
625           (basic-combination
626            (dolist (arg (reverse (basic-combination-args node)))
627              (when arg
628                (consume arg)))
629            (consume (basic-combination-fun node))
630            (case (continuation-function-name (basic-combination-fun node))
631              (%nlx-entry
632               (let ((nlx-info (continuation-value
633                                (first (basic-combination-args node)))))
634                 (ecase (cleanup-kind (nlx-info-cleanup nlx-info))
635                   ((:catch :unwind-protect)
636                    (consume :nlx-entry))
637                   ;; If for a lexical exit, we will see a breakup later, so
638                   ;; don't consume :NLX-ENTRY now.
639                   (:tagbody)
640                   (:block
641                    (let ((cont (nlx-info-continuation nlx-info)))
642                      (when (interesting cont)
643                        (push cont stack))))))
644               (setf nlx-entry-p t))
645              (%lexical-exit-breakup
646               (unless (byte-nlx-info-duplicate
647                        (nlx-info-info
648                         (continuation-value
649                          (first (basic-combination-args node)))))
650                 (consume :nlx-entry)))
651              ((%catch-breakup %unwind-protect-breakup)
652               (consume :nlx-entry))))
653           (cif
654            (consume (if-test node)))
655           (creturn
656            (consume (return-result node)))
657           (entry
658            (let* ((cup (entry-cleanup node))
659                   (nlx-info (cleanup-nlx-info cup)))
660              (when nlx-info
661                (push :nlx-entry stack)
662                (push (list nlx-info stack (reverse consumes))
663                      nlx-entries))))
664           (exit
665            (when (exit-value node)
666              (consume (exit-value node)))))
667         (when (and (not (exit-p node)) (interesting cont))
668           (push cont stack)))
669
670       (setf (block-info block)
671             (make-byte-block-info
672              block
673              :produces stack
674              :produces-sset (let ((res (make-sset)))
675                               (dolist (product stack)
676                                 (adjoin-cont product res))
677                               res)
678              :consumes (reverse consumes)
679              :total-consumes total-consumes
680              :nlx-entries nlx-entries
681              :nlx-entry-p nlx-entry-p))))
682
683   (values))
684
685 (defun walk-successors (block stack)
686   (let ((tail (component-tail (block-component block))))
687     (dolist (succ (block-succ block))
688       (unless (or (eq succ tail)
689                   (not (block-interesting succ))
690                   (byte-block-info-nlx-entry-p (block-info succ)))
691         (walk-block succ block stack)))))
692
693 ;;; Take a stack and a consumes list, and remove the appropriate
694 ;;; stuff. When we consume a :NLX-ENTRY, we just remove the top
695 ;;; marker, and leave any values on top intact. This represents the
696 ;;; desired effect of %CATCH-BREAKUP, etc., which don't affect any
697 ;;; values on the stack.
698 (defun consume-stuff (stack stuff)
699   (let ((new-stack stack))
700     (dolist (cont stuff)
701       (cond ((eq cont :nlx-entry)
702              (aver (find :nlx-entry new-stack))
703              (setq new-stack (remove :nlx-entry new-stack :count 1)))
704             (t
705              (aver (eq (car new-stack) cont))
706              (pop new-stack))))
707     new-stack))
708
709 ;;; NLX-INFOS is the list of NLX-INFO structures for this ENTRY note.
710 ;;; CONSUME and PRODUCE are the values from outside this block that
711 ;;; were consumed and produced by this block before the ENTRY node.
712 ;;; STACK is the globally simulated stack at the start of this block.
713 (defun walk-nlx-entry (nlx-infos stack produce consume)
714   (let ((stack (consume-stuff stack consume)))
715     (dolist (nlx-info nlx-infos)
716       (walk-block (nlx-info-target nlx-info) nil (append produce stack))))
717   (values))
718
719 ;;; Simulate the stack across block boundaries, discarding any values
720 ;;; that are dead. A :NLX-ENTRY marker prevents values live at a NLX
721 ;;; entry point from being discarded prematurely.
722 (defun walk-block (block pred stack)
723   ;; Pop everything off of stack that isn't live.
724   (let* ((info (block-info block))
725          (live (byte-block-info-total-consumes info)))
726     (collect ((pops))
727       (let ((fixed 0))
728         (flet ((flush-fixed ()
729                  (unless (zerop fixed)
730                    (pops `(%byte-pop-stack ,fixed))
731                    (setf fixed 0))))
732           (loop
733             (unless stack
734               (return))
735             (let ((cont (car stack)))
736               (when (or (eq cont :nlx-entry)
737                         (sset-member (continuation-info cont) live))
738                 (return))
739               (pop stack)
740               (let ((results
741                      (byte-continuation-info-results
742                       (continuation-info cont))))
743                 (case results
744                   (:unknown
745                    (flush-fixed)
746                    (pops `(%byte-pop-stack 0)))
747                   (:fdefinition
748                    (incf fixed))
749                   (t
750                    (incf fixed results))))))
751           (flush-fixed)))
752       (when (pops)
753         (aver pred)
754         (let ((cleanup-block
755                (insert-cleanup-code pred block
756                                     (continuation-next (block-start block))
757                                     `(progn ,@(pops)))))
758           (annotate-block cleanup-block))))
759
760     (cond ((eq (byte-block-info-start-stack info) :unknown)
761            ;; Record what the stack looked like at the start of this block.
762            (setf (byte-block-info-start-stack info) stack)
763            ;; Process any nlx entries that build off of our stack.
764            (dolist (stuff (byte-block-info-nlx-entries info))
765              (walk-nlx-entry (first stuff) stack (second stuff) (third stuff)))
766            ;; Remove whatever we consume.
767            (setq stack (consume-stuff stack (byte-block-info-consumes info)))
768            ;; Add whatever we produce.
769            (setf stack (append (byte-block-info-produces info) stack))
770            (setf (byte-block-info-end-stack info) stack)
771            ;; Pass that on to all our successors.
772            (walk-successors block stack))
773           (t
774            ;; We have already processed the successors of this block. Just
775            ;; make sure we thing the stack is the same now as before.
776            (aver (equal (byte-block-info-start-stack info) stack)))))
777   (values))
778
779 ;;; Do lifetime flow analysis on values pushed on the stack, then call
780 ;;; do the stack simulation walk to discard dead values. In addition
781 ;;; to considering the obvious inputs from a block's successors, we
782 ;;; must also consider %NLX-ENTRY targets to be successors in order to
783 ;;; ensure that any values only used in the NLX entry stay alive until
784 ;;; we reach the mess-up node. After then, we can keep the values from
785 ;;; being discarded by placing a marker on the simulated stack.
786 (defun byte-stack-analyze (component)
787   (let ((head nil))
788     (let ((*byte-continuation-counter* 0))
789       (do-blocks (block component)
790         (when (block-interesting block)
791           (compute-produces-and-consumes block)
792           (push block head)
793           (setf (byte-block-info-already-queued (block-info block)) t))))
794     (let ((tail (last head)))
795       (labels ((maybe-enqueue (block)
796                  (when (block-interesting block)
797                    (let ((info (block-info block)))
798                      (unless (byte-block-info-already-queued info)
799                        (setf (byte-block-info-already-queued info) t)
800                        (let ((new (list block)))
801                          (if head
802                              (setf (cdr tail) new)
803                              (setf head new))
804                          (setf tail new))))))
805                (maybe-enqueue-predecessors (block)
806                  (when (byte-block-info-nlx-entry-p (block-info block))
807                    (maybe-enqueue
808                     (node-block
809                      (cleanup-mess-up
810                       (nlx-info-cleanup
811                        (find block
812                              (environment-nlx-info (block-environment block))
813                              :key #'nlx-info-target))))))
814
815                  (dolist (pred (block-pred block))
816                    (unless (eq pred (component-head (block-component block)))
817                      (maybe-enqueue pred)))))
818         (loop
819           (unless head
820             (return))
821           (let* ((block (pop head))
822                  (info (block-info block))
823                  (total-consumes (byte-block-info-total-consumes info))
824                  (produces-sset (byte-block-info-produces-sset info))
825                  (did-anything nil))
826             (setf (byte-block-info-already-queued info) nil)
827             (dolist (succ (block-succ block))
828               (unless (eq succ (component-tail component))
829                 (let ((succ-info (block-info succ)))
830                   (when (sset-union-of-difference
831                          total-consumes
832                          (byte-block-info-total-consumes succ-info)
833                          produces-sset)
834                     (setf did-anything t)))))
835             (dolist (nlx-list (byte-block-info-nlx-entries info))
836               (dolist (nlx-info (first nlx-list))
837                 (when (sset-union-of-difference
838                        total-consumes
839                        (byte-block-info-total-consumes
840                         (block-info
841                          (nlx-info-target nlx-info)))
842                        produces-sset)
843                   (setf did-anything t))))
844             (when did-anything
845               (maybe-enqueue-predecessors block)))))))
846
847   (walk-successors (component-head component) nil)
848   (values))
849 \f
850 ;;;; Actually generate the byte code.
851
852 (defvar *byte-component-info*)
853
854 ;;; FIXME: These might as well be generated with DEFENUM, right?
855 ;;; It would also be nice to give them less ambiguous names, perhaps
856 ;;; with a "BYTEOP-" prefix instead of "BYTE-".
857 (defconstant byte-push-local           #b00000000)
858 (defconstant byte-push-arg             #b00010000)
859 (defconstant byte-push-constant        #b00100000)
860 (defconstant byte-push-system-constant #b00110000)
861 (defconstant byte-push-int             #b01000000)
862 (defconstant byte-push-neg-int         #b01010000)
863 (defconstant byte-pop-local            #b01100000)
864 (defconstant byte-pop-n                #b01110000)
865 (defconstant byte-call                 #b10000000)
866 (defconstant byte-tail-call            #b10010000)
867 (defconstant byte-multiple-call        #b10100000)
868 (defconstant byte-named                #b00001000)
869 (defconstant byte-local-call           #b10110000)
870 (defconstant byte-local-tail-call      #b10111000)
871 (defconstant byte-local-multiple-call  #b11000000)
872 (defconstant byte-return               #b11001000)
873 (defconstant byte-branch-always        #b11010000)
874 (defconstant byte-branch-if-true       #b11010010)
875 (defconstant byte-branch-if-false      #b11010100)
876 (defconstant byte-branch-if-eq         #b11010110)
877 (defconstant byte-xop                  #b11011000)
878 (defconstant byte-inline-function      #b11100000)
879
880 (defun output-push-int (segment int)
881   (declare (type sb!assem:segment segment)
882            (type (integer #.(- (ash 1 24)) #.(1- (ash 1 24)))))
883   (if (minusp int)
884       (output-byte-with-operand segment byte-push-neg-int (- (1+ int)))
885       (output-byte-with-operand segment byte-push-int int)))
886
887 (defun output-push-constant-leaf (segment constant)
888   (declare (type sb!assem:segment segment)
889            (type constant constant))
890   (let ((info (constant-info constant)))
891     (if info
892         (output-byte-with-operand segment
893                                   (ecase (car info)
894                                     (:system-constant
895                                      byte-push-system-constant)
896                                     (:local-constant
897                                      byte-push-constant))
898                                   (cdr info))
899         (let ((const (constant-value constant)))
900           (if (and (integerp const) (< (- (ash 1 24)) const (ash 1 24)))
901               ;; It can be represented as an immediate.
902               (output-push-int segment const)
903               ;; We need to store it in the constants pool.
904               (let* ((posn
905                       (unless (and (consp const)
906                                    (eq (car const) '%fdefinition-marker%))
907                         (gethash const *system-constant-codes*)))
908                      (new-info (if posn
909                                    (cons :system-constant posn)
910                                    (cons :local-constant
911                                          (vector-push-extend
912                                           constant
913                                           (byte-component-info-constants
914                                            *byte-component-info*))))))
915                 (setf (constant-info constant) new-info)
916                 (output-push-constant-leaf segment constant)))))))
917
918 (defun output-push-constant (segment value)
919   (if (and (integerp value)
920            (< (- (ash 1 24)) value (ash 1 24)))
921       (output-push-int segment value)
922       (output-push-constant-leaf segment (find-constant value))))
923
924 ;;; Return the offset of a load-time constant in the constant pool,
925 ;;; adding it if absent.
926 (defun byte-load-time-constant-index (kind datum)
927   (let ((constants (byte-component-info-constants *byte-component-info*)))
928     (or (position-if #'(lambda (x)
929                          (and (consp x)
930                               (eq (car x) kind)
931                               (typecase datum
932                                 (cons (equal (cdr x) datum))
933                                 (ctype (type= (cdr x) datum))
934                                 (t
935                                  (eq (cdr x) datum)))))
936                      constants)
937         (vector-push-extend (cons kind datum) constants))))
938
939 (defun output-push-load-time-constant (segment kind datum)
940   (output-byte-with-operand segment byte-push-constant
941                             (byte-load-time-constant-index kind datum))
942   (values))
943
944 (defun output-do-inline-function (segment function)
945   ;; Note: we don't annotate this as a call site, because it is used
946   ;; for internal stuff. Functions that get inlined have code
947   ;; locations added byte generate-byte-code-for-full-call below.
948   (output-byte segment
949                (logior byte-inline-function
950                        (inline-function-number-or-lose function))))
951
952 (defun output-do-xop (segment xop)
953   (let ((index (xop-index-or-lose xop)))
954     (cond ((< index 7)
955            (output-byte segment (logior byte-xop index)))
956           (t
957            (output-byte segment (logior byte-xop 7))
958            (output-byte segment index)))))
959
960 (defun closure-position (var env)
961   (or (position var (environment-closure env))
962       (error "Can't find ~S" var)))
963
964 (defun output-ref-lambda-var (segment var env
965                                      &optional (indirect-value-cells t))
966   (declare (type sb!assem:segment segment)
967            (type lambda-var var)
968            (type environment env))
969   (if (eq (lambda-environment (lambda-var-home var)) env)
970       (let ((info (leaf-info var)))
971         (output-byte-with-operand segment
972                                   (if (byte-lambda-var-info-argp info)
973                                       byte-push-arg
974                                       byte-push-local)
975                                   (byte-lambda-var-info-offset info)))
976       (output-byte-with-operand segment
977                                 byte-push-arg
978                                 (closure-position var env)))
979   (when (and indirect-value-cells (lambda-var-indirect var))
980     (output-do-inline-function segment 'value-cell-ref)))
981
982 (defun output-ref-nlx-info (segment info env)
983   (if (eq (node-environment (cleanup-mess-up (nlx-info-cleanup info))) env)
984       (output-byte-with-operand segment
985                                 byte-push-local
986                                 (byte-nlx-info-stack-slot
987                                  (nlx-info-info info)))
988       (output-byte-with-operand segment
989                                 byte-push-arg
990                                 (closure-position info env))))
991
992 (defun output-set-lambda-var (segment var env &optional make-value-cells)
993   (declare (type sb!assem:segment segment)
994            (type lambda-var var)
995            (type environment env))
996   (let ((indirect (lambda-var-indirect var)))
997     (cond ((not (eq (lambda-environment (lambda-var-home var)) env))
998            ;; This is not this guy's home environment. So we need to
999            ;; get it the value cell out of the closure, and fill it in.
1000            (aver indirect)
1001            (aver (not make-value-cells))
1002            (output-byte-with-operand segment byte-push-arg
1003                                      (closure-position var env))
1004            (output-do-inline-function segment 'value-cell-setf))
1005           (t
1006            (let* ((pushp (and indirect (not make-value-cells)))
1007                   (byte-code (if pushp byte-push-local byte-pop-local))
1008                   (info (leaf-info var)))
1009              (aver (not (byte-lambda-var-info-argp info)))
1010              (when (and indirect make-value-cells)
1011                ;; Replace the stack top with a value cell holding the
1012                ;; stack top.
1013                (output-do-inline-function segment 'make-value-cell))
1014              (output-byte-with-operand segment byte-code
1015                                        (byte-lambda-var-info-offset info))
1016              (when pushp
1017                (output-do-inline-function segment 'value-cell-setf)))))))
1018
1019 ;;; Output whatever noise is necessary to canonicalize the values on
1020 ;;; the top of the stack. DESIRED is the number we want, and SUPPLIED
1021 ;;; is the number we have. Either push NIL or pop-n to make them
1022 ;;; balanced. Note: either desired or supplied can be :unknown, in
1023 ;;; which case it means use the ``unknown-values'' convention (which
1024 ;;; is the stack values followed by the number of values).
1025 (defun canonicalize-values (segment desired supplied)
1026   (declare (type sb!assem:segment segment)
1027            (type (or (member :unknown) index) desired supplied))
1028   (cond ((eq desired :unknown)
1029          (unless (eq supplied :unknown)
1030            (output-byte-with-operand segment byte-push-int supplied)))
1031         ((eq supplied :unknown)
1032          (unless (eq desired :unknown)
1033            (output-push-int segment desired)
1034            (output-do-xop segment 'default-unknown-values)))
1035         ((< supplied desired)
1036          (dotimes (i (- desired supplied))
1037            (output-push-constant segment nil)))
1038         ((> supplied desired)
1039          (output-byte-with-operand segment byte-pop-n (- supplied desired))))
1040   (values))
1041
1042 (defparameter *byte-type-weakenings*
1043   (mapcar #'specifier-type
1044           '(fixnum single-float double-float simple-vector simple-bit-vector
1045                    bit-vector)))
1046
1047 ;;; Emit byte code to check that the value on top of the stack is of
1048 ;;; the specified TYPE. NODE is used for policy information. We weaken
1049 ;;; or entirely omit the type check whether speed is more important
1050 ;;; than safety.
1051 (defun byte-generate-type-check (segment type node)
1052   (declare (type ctype type) (type node node))
1053   (unless (or (policy node (zerop safety))
1054               (csubtypep *universal-type* type))
1055     (let ((type (if (policy node (> speed safety))
1056                     (dolist (super *byte-type-weakenings* type)
1057                       (when (csubtypep type super) (return super)))
1058                     type)))
1059       (output-do-xop segment 'type-check)
1060       (output-extended-operand
1061        segment
1062        (byte-load-time-constant-index :type-predicate type)))))
1063
1064 ;;; This function is used when we are generating code which delivers
1065 ;;; values to a continuation. If this continuation needs a type check,
1066 ;;; and has a single value, then we do a type check. We also
1067 ;;; CANONICALIZE-VALUES for the continuation's desired number of
1068 ;;; values (w/o the placeholders.)
1069 ;;;
1070 ;;; Somewhat unrelatedly, we also push placeholders for deleted
1071 ;;; arguments to local calls. Although we check first, the actual
1072 ;;; PUSH-N-UNDER is done afterward, since then the single value we
1073 ;;; want is stack top.
1074 (defun checked-canonicalize-values (segment cont supplied)
1075   (let ((info (continuation-info cont)))
1076     (if info
1077         (let ((desired (byte-continuation-info-results info))
1078               (placeholders (byte-continuation-info-placeholders info)))
1079           (unless (zerop placeholders)
1080             (aver (eql desired (1+ placeholders)))
1081             (setq desired 1))
1082
1083           (flet ((do-check ()
1084                    (byte-generate-type-check
1085                     segment
1086                     (single-value-type (continuation-asserted-type cont))
1087                     (continuation-dest cont))))
1088             (cond
1089              ((member (continuation-type-check cont) '(nil :deleted))
1090               (canonicalize-values segment desired supplied))
1091              ((eql supplied 1)
1092               (do-check)
1093               (canonicalize-values segment desired supplied))
1094              ((eql desired 1)
1095               (canonicalize-values segment desired supplied)
1096               (do-check))
1097              (t
1098               (canonicalize-values segment desired supplied))))
1099
1100           (unless (zerop placeholders)
1101             (output-do-xop segment 'push-n-under)
1102             (output-extended-operand segment placeholders)))
1103
1104         (canonicalize-values segment 0 supplied))))
1105
1106 ;;; Emit prologue for non-LET functions. Assigned arguments must be
1107 ;;; copied into locals, and argument type checking may need to be done.
1108 (defun generate-byte-code-for-bind (segment bind cont)
1109   (declare (type sb!assem:segment segment) (type bind bind)
1110            (ignore cont))
1111   (let ((lambda (bind-lambda bind))
1112         (env (node-environment bind)))
1113     (ecase (lambda-kind lambda)
1114       ((nil :top-level :escape :cleanup :optional)
1115        (let* ((info (lambda-info lambda))
1116               (type-check (policy (lambda-bind lambda) (not (zerop safety))))
1117               (frame-size (byte-lambda-info-stack-size info)))
1118          (cond ((< frame-size (* 255 2))
1119                 (output-byte segment (ceiling frame-size 2)))
1120                (t
1121                 (output-byte segment 255)
1122                 (output-byte segment (ldb (byte 8 16) frame-size))
1123                 (output-byte segment (ldb (byte 8 8) frame-size))
1124                 (output-byte segment (ldb (byte 8 0) frame-size))))
1125
1126          (do ((argnum (1- (+ (length (lambda-vars lambda))
1127                              (length (environment-closure
1128                                       (lambda-environment lambda)))))
1129                       (1- argnum))
1130               (vars (lambda-vars lambda) (cdr vars))
1131               (pops 0))
1132              ((null vars)
1133               (unless (zerop pops)
1134                 (output-byte-with-operand segment byte-pop-n pops)))
1135            (declare (fixnum argnum pops))
1136            (let* ((var (car vars))
1137                   (info (lambda-var-info var))
1138                   (type (leaf-type var)))
1139              (cond ((not info))
1140                    ((byte-lambda-var-info-argp info)
1141                     (when (and type-check
1142                                (not (csubtypep *universal-type* type)))
1143                       (output-byte-with-operand segment byte-push-arg argnum)
1144                       (byte-generate-type-check segment type bind)
1145                       (incf pops)))
1146                    (t
1147                     (output-byte-with-operand segment byte-push-arg argnum)
1148                     (when type-check
1149                       (byte-generate-type-check segment type bind))
1150                     (output-set-lambda-var segment var env t)))))))
1151
1152       ;; Everything has been taken care of in the combination node.
1153       ((:let :mv-let :assignment))))
1154   (values))
1155
1156 ;;; This hashtable translates from n-ary function names to the
1157 ;;; two-arg-specific versions which we call to avoid &REST-arg consing.
1158 (defvar *two-arg-functions* (make-hash-table :test 'eq))
1159
1160 (dolist (fun '((sb!kernel:two-arg-ior  logior)
1161                (sb!kernel:two-arg-*  *)
1162                (sb!kernel:two-arg-+  +)
1163                (sb!kernel:two-arg-/  /)
1164                (sb!kernel:two-arg--  -)
1165                (sb!kernel:two-arg->  >)
1166                (sb!kernel:two-arg-<  <)
1167                (sb!kernel:two-arg-=  =)
1168                (sb!kernel:two-arg-lcm  lcm)
1169                (sb!kernel:two-arg-and  logand)
1170                (sb!kernel:two-arg-gcd  gcd)
1171                (sb!kernel:two-arg-xor  logxor)
1172
1173                (two-arg-char= char=)
1174                (two-arg-char< char<)
1175                (two-arg-char> char>)
1176                (two-arg-char-equal char-equal)
1177                (two-arg-char-lessp char-lessp)
1178                (two-arg-char-greaterp char-greaterp)
1179                (two-arg-string= string=)
1180                (two-arg-string< string<)
1181                (two-arg-string> string>)))
1182
1183   (setf (gethash (second fun) *two-arg-functions*) (first fun)))
1184
1185 ;;; If a system constant, push that, otherwise use a load-time constant.
1186 (defun output-push-fdefinition (segment name)
1187   (let ((offset (gethash `(%fdefinition-marker% . ,name)
1188                          *system-constant-codes*)))
1189     (if offset
1190         (output-byte-with-operand segment byte-push-system-constant
1191                                   offset)
1192         (output-push-load-time-constant segment :fdefinition name))))
1193
1194 (defun generate-byte-code-for-ref (segment ref cont)
1195   (declare (type sb!assem:segment segment) (type ref ref)
1196            (type continuation cont))
1197   (let ((info (continuation-info cont)))
1198     ;; If there is no info, then nobody wants the result.
1199     (when info
1200       (let ((values (byte-continuation-info-results info))
1201             (leaf (ref-leaf ref)))
1202         (cond
1203          ((eq values :fdefinition)
1204           (aver (and (global-var-p leaf)
1205                      (eq (global-var-kind leaf)
1206                          :global-function)))
1207           (let* ((name (global-var-name leaf))
1208                  (found (gethash name *two-arg-functions*)))
1209             (output-push-fdefinition
1210              segment
1211              (if (and found
1212                       (= (length (combination-args (continuation-dest cont)))
1213                          2))
1214                  found
1215                  name))))
1216          ((eql values 0)
1217           ;; really easy!
1218           nil)
1219          (t
1220           (etypecase leaf
1221             (constant
1222              (cond ((legal-immediate-constant-p leaf)
1223                      (output-push-constant-leaf segment leaf))
1224                    (t
1225                      (output-push-constant segment (leaf-name leaf))
1226                      (output-do-inline-function segment 'symbol-value))))
1227             (clambda
1228              (let* ((referred-env (lambda-environment leaf))
1229                     (closure (environment-closure referred-env)))
1230                (if (null closure)
1231                    (output-push-load-time-constant segment :entry leaf)
1232                    (let ((my-env (node-environment ref)))
1233                      (output-push-load-time-constant segment :entry leaf)
1234                      (dolist (thing closure)
1235                        (etypecase thing
1236                          (lambda-var
1237                           (output-ref-lambda-var segment thing my-env nil))
1238                          (nlx-info
1239                           (output-ref-nlx-info segment thing my-env))))
1240                      (output-push-int segment (length closure))
1241                      (output-do-xop segment 'make-closure)))))
1242             (functional
1243              (output-push-load-time-constant segment :entry leaf))
1244             (lambda-var
1245              (output-ref-lambda-var segment leaf (node-environment ref)))
1246             (global-var
1247              (ecase (global-var-kind leaf)
1248                ((:special :global :constant)
1249                 (output-push-constant segment (global-var-name leaf))
1250                 (output-do-inline-function segment 'symbol-value))
1251                (:global-function
1252                 (output-push-fdefinition segment (global-var-name leaf))
1253                 (output-do-xop segment 'fdefn-function-or-lose)))))
1254           (checked-canonicalize-values segment cont 1))))))
1255   (values))
1256
1257 (defun generate-byte-code-for-set (segment set cont)
1258   (declare (type sb!assem:segment segment) (type cset set)
1259            (type continuation cont))
1260   (let* ((leaf (set-var set))
1261          (info (continuation-info cont))
1262          (values (if info
1263                      (byte-continuation-info-results info)
1264                      0)))
1265     (unless (eql values 0)
1266       ;; Someone wants the value, so copy it.
1267       (output-do-xop segment 'dup))
1268     (etypecase leaf
1269       (global-var        
1270        (ecase (global-var-kind leaf)
1271          ((:special :global)
1272           (output-push-constant segment (global-var-name leaf))
1273           (output-do-inline-function segment 'setf-symbol-value))))
1274       (lambda-var
1275         ;; Note: It's important to test for whether there are any
1276         ;; references to the variable before we actually try to set it.
1277         ;; (Setting a lexical variable with no refs caused bugs ca. CMU
1278         ;; CL 18c, because the compiler deletes such variables.)
1279         (cond ((leaf-refs leaf)                
1280                 (output-set-lambda-var segment leaf (node-environment set)))
1281               ;; If no one wants the value, then pop it, else leave it
1282               ;; for them.
1283               ((eql values 0)
1284                 (output-byte-with-operand segment byte-pop-n 1)))))
1285     (unless (eql values 0)
1286       (checked-canonicalize-values segment cont 1)))
1287   (values))
1288
1289 (defun generate-byte-code-for-local-call (segment call cont num-args)
1290   (let* ((lambda (combination-lambda call))
1291          (vars (lambda-vars lambda))
1292          (env (lambda-environment lambda)))
1293     (ecase (functional-kind lambda)
1294       ((:let :assignment)
1295        (dolist (var (reverse vars))
1296          (when (lambda-var-refs var)
1297            (output-set-lambda-var segment var env t))))
1298       (:mv-let
1299        (let ((do-check (member (continuation-type-check
1300                                 (first (basic-combination-args call)))
1301                                '(t :error))))
1302          (dolist (var (reverse vars))
1303            (when do-check
1304              (byte-generate-type-check segment (leaf-type var) call))
1305            (output-set-lambda-var segment var env t))))
1306       ((nil :optional :cleanup)
1307        ;; We got us a local call.
1308        (aver (not (eq num-args :unknown)))
1309        ;; Push any trailing placeholder args...
1310        (dolist (x (reverse (basic-combination-args call)))
1311          (when x (return))
1312          (output-push-int segment 0))
1313        ;; Then push closure vars.
1314        (let ((closure (environment-closure env)))
1315          (when closure
1316            (let ((my-env (node-environment call)))
1317              (dolist (thing (reverse closure))
1318                (etypecase thing
1319                  (lambda-var
1320                   (output-ref-lambda-var segment thing my-env nil))
1321                  (nlx-info
1322                   (output-ref-nlx-info segment thing my-env)))))
1323            (incf num-args (length closure))))
1324        (let ((results
1325               (let ((info (continuation-info cont)))
1326                 (if info
1327                     (byte-continuation-info-results info)
1328                     0))))
1329          ;; Emit the op for whatever flavor of call we are using.
1330          (let ((operand
1331                 (cond ((> num-args 6)
1332                        (output-push-int segment num-args)
1333                        7)
1334                       (t
1335                        num-args))))
1336            (multiple-value-bind (opcode ret-vals)
1337                (cond ((node-tail-p call)
1338                       (values byte-local-tail-call 0))
1339                      ((member results '(0 1))
1340                       (values byte-local-call 1))
1341                      (t
1342                       (values byte-local-multiple-call :unknown)))
1343              ;; ### :call-site
1344              (output-byte segment (logior opcode operand))
1345              ;; Emit a reference to the label.
1346              (output-reference segment
1347                                (byte-lambda-info-label (lambda-info lambda)))
1348              ;; ### :unknown-return
1349              ;; Fix up the results.
1350              (unless (node-tail-p call)
1351                (checked-canonicalize-values segment cont ret-vals))))))))
1352   (values))
1353
1354 (defun generate-byte-code-for-full-call (segment call cont num-args)
1355   (let ((info (basic-combination-info call))
1356         (results
1357          (let ((info (continuation-info cont)))
1358            (if info
1359                (byte-continuation-info-results info)
1360                0))))
1361     (cond
1362      (info
1363       ;; It's an inline function.
1364       (aver (not (node-tail-p call)))
1365       (let* ((type (inline-function-info-type info))
1366              (desired-args (function-type-nargs type))
1367              (supplied-results
1368               (nth-value 1
1369                          (values-types (function-type-returns type))))
1370              (leaf (ref-leaf (continuation-use (basic-combination-fun call)))))
1371         (cond ((slot-accessor-p leaf)
1372                (aver (= num-args (1- desired-args)))
1373                (output-push-int segment (dsd-index (slot-accessor-slot leaf))))
1374               (t
1375                (canonicalize-values segment desired-args num-args)))
1376         ;; ### :call-site
1377         (output-byte segment (logior byte-inline-function
1378                                      (inline-function-info-number info)))
1379         ;; ### :known-return
1380         (checked-canonicalize-values segment cont supplied-results)))
1381      (t
1382       (let ((operand
1383              (cond ((eq num-args :unknown)
1384                     7)
1385                    ((> num-args 6)
1386                     (output-push-int segment num-args)
1387                     7)
1388                    (t
1389                     num-args))))
1390         (when (eq (byte-continuation-info-results
1391                    (continuation-info
1392                     (basic-combination-fun call)))
1393                   :fdefinition)
1394           (setf operand (logior operand byte-named)))
1395         ;; ### :call-site
1396         (cond
1397          ((node-tail-p call)
1398           (output-byte segment (logior byte-tail-call operand)))
1399          (t
1400           (multiple-value-bind (opcode ret-vals)
1401               (case results
1402                 (:unknown (values byte-multiple-call :unknown))
1403                 ((0 1) (values byte-call 1))
1404                 (t (values byte-multiple-call :unknown)))
1405           (output-byte segment (logior opcode operand))
1406           ;; ### :unknown-return
1407           (checked-canonicalize-values segment cont ret-vals)))))))))
1408
1409 (defun generate-byte-code-for-known-call (segment call cont num-args)
1410   (block nil
1411     (catch 'give-up-ir1-transform
1412       (funcall (function-info-byte-compile (basic-combination-kind call)) call
1413                (let ((info (continuation-info cont)))
1414                  (if info
1415                      (byte-continuation-info-results info)
1416                      0))
1417                num-args segment)
1418       (return))
1419     (aver (member (byte-continuation-info-results
1420                    (continuation-info
1421                     (basic-combination-fun call)))
1422                   '(1 :fdefinition)))
1423     (generate-byte-code-for-full-call segment call cont num-args))
1424   (values))
1425
1426 (defun generate-byte-code-for-generic-combination (segment call cont)
1427   (declare (type sb!assem:segment segment) (type basic-combination call)
1428            (type continuation cont))
1429   (labels ((examine (args num-fixed)
1430              (cond
1431               ((null args)
1432                ;; None of the arugments supply :UNKNOWN values, so
1433                ;; we know exactly how many there are.
1434                num-fixed)
1435               (t
1436                (let* ((vals
1437                        (byte-continuation-info-results
1438                         (continuation-info (car args)))))
1439                  (cond
1440                   ((eq vals :unknown)
1441                    (unless (null (cdr args))
1442                      ;; There are (LENGTH ARGS) :UNKNOWN value blocks on
1443                      ;; the top of the stack. We need to combine them.
1444                      (output-push-int segment (length args))
1445                      (output-do-xop segment 'merge-unknown-values))
1446                    (unless (zerop num-fixed)
1447                      ;; There are num-fixed fixed args above the unknown
1448                      ;; values block that want in on the action also.
1449                      ;; So add num-fixed to the count.
1450                      (output-push-int segment num-fixed)
1451                      (output-do-inline-function segment '+))
1452                    :unknown)
1453                   (t
1454                    (examine (cdr args) (+ num-fixed vals)))))))))
1455     (let* ((args (basic-combination-args call))
1456            (kind (basic-combination-kind call))
1457            (num-args (if (and (eq kind :local)
1458                               (combination-p call))
1459                          (length args)
1460                          (examine args 0))))
1461       (case kind
1462         (:local
1463          (generate-byte-code-for-local-call segment call cont num-args))
1464         (:full
1465          (generate-byte-code-for-full-call segment call cont num-args))
1466         (t
1467          (generate-byte-code-for-known-call segment call cont num-args))))))
1468
1469 (defun generate-byte-code-for-basic-combination (segment call cont)
1470   (cond ((and (mv-combination-p call)
1471               (eq (continuation-function-name (basic-combination-fun call))
1472                   '%throw))
1473          ;; ### :internal-error
1474          (output-do-xop segment 'throw))
1475         (t
1476          (generate-byte-code-for-generic-combination segment call cont))))
1477
1478 (defun generate-byte-code-for-if (segment if cont)
1479   (declare (type sb!assem:segment segment) (type cif if)
1480            (ignore cont))
1481   (let* ((next-info (byte-block-info-next (block-info (node-block if))))
1482          (consequent-info (block-info (if-consequent if)))
1483          (alternate-info (block-info (if-alternative if))))
1484     (cond ((eq (byte-continuation-info-results
1485                 (continuation-info (if-test if)))
1486                :eq-test)
1487            (output-branch segment
1488                           byte-branch-if-eq
1489                           (byte-block-info-label consequent-info))
1490            (unless (eq next-info alternate-info)
1491              (output-branch segment
1492                             byte-branch-always
1493                             (byte-block-info-label alternate-info))))
1494           ((eq next-info consequent-info)
1495            (output-branch segment
1496                           byte-branch-if-false
1497                           (byte-block-info-label alternate-info)))
1498           (t
1499            (output-branch segment
1500                           byte-branch-if-true
1501                           (byte-block-info-label consequent-info))
1502            (unless (eq next-info alternate-info)
1503              (output-branch segment
1504                             byte-branch-always
1505                             (byte-block-info-label alternate-info)))))))
1506
1507 (defun generate-byte-code-for-return (segment return cont)
1508   (declare (type sb!assem:segment segment) (type creturn return)
1509            (ignore cont))
1510   (let* ((result (return-result return))
1511          (info (continuation-info result))
1512          (results (byte-continuation-info-results info)))
1513     (cond ((eq results :unknown)
1514            (setf results 7))
1515           ((> results 6)
1516            (output-byte-with-operand segment byte-push-int results)
1517            (setf results 7)))
1518     (output-byte segment (logior byte-return results)))
1519   (values))
1520
1521 (defun generate-byte-code-for-entry (segment entry cont)
1522   (declare (type sb!assem:segment segment) (type entry entry)
1523            (ignore cont))
1524   (dolist (exit (entry-exits entry))
1525     (let ((nlx-info (find-nlx-info entry (node-cont exit))))
1526       (when nlx-info
1527         (let ((kind (cleanup-kind (nlx-info-cleanup nlx-info))))
1528           (when (member kind '(:block :tagbody))
1529             ;; Generate a unique tag.
1530             (output-push-constant
1531              segment
1532              (format nil
1533                      "tag for ~A"
1534                      (component-name *component-being-compiled*)))
1535             (output-push-constant segment nil)
1536             (output-do-inline-function segment 'cons)
1537             ;; Save it so people can close over it.
1538             (output-do-xop segment 'dup)
1539             (output-byte-with-operand segment
1540                                       byte-pop-local
1541                                       (byte-nlx-info-stack-slot
1542                                        (nlx-info-info nlx-info)))
1543             ;; Now do the actual XOP.
1544             (ecase kind
1545               (:block
1546                (output-do-xop segment 'catch)
1547                (output-reference segment
1548                                  (byte-nlx-info-label
1549                                   (nlx-info-info nlx-info))))
1550               (:tagbody
1551                (output-do-xop segment 'tagbody)))
1552             (return))))))
1553   (values))
1554
1555 (defun generate-byte-code-for-exit (segment exit cont)
1556   (declare (ignore cont))
1557   (let ((nlx-info (find-nlx-info (exit-entry exit) (node-cont exit))))
1558     (output-byte-with-operand segment
1559                               byte-push-arg
1560                               (closure-position nlx-info
1561                                                 (node-environment exit)))
1562     (ecase (cleanup-kind (nlx-info-cleanup nlx-info))
1563       (:block
1564        ;; ### :internal-error
1565        (output-do-xop segment 'return-from))
1566       (:tagbody
1567        ;; ### :internal-error
1568        (output-do-xop segment 'go)
1569        (output-reference segment
1570                          (byte-nlx-info-label (nlx-info-info nlx-info)))))))
1571
1572 (defun generate-byte-code (segment component)
1573   (let ((*byte-component-info* (component-info component)))
1574     (do* ((info (byte-block-info-next (block-info (component-head component)))
1575                 next)
1576           (block (byte-block-info-block info) (byte-block-info-block info))
1577           (next (byte-block-info-next info) (byte-block-info-next info)))
1578          ((eq block (component-tail component)))
1579       (when (block-interesting block)
1580         (output-label segment (byte-block-info-label info))
1581         (do-nodes (node cont block)
1582           (etypecase node
1583             (bind (generate-byte-code-for-bind segment node cont))
1584             (ref (generate-byte-code-for-ref segment node cont))
1585             (cset (generate-byte-code-for-set segment node cont))
1586             (basic-combination
1587              (generate-byte-code-for-basic-combination
1588               segment node cont))
1589             (cif (generate-byte-code-for-if segment node cont))
1590             (creturn (generate-byte-code-for-return segment node cont))
1591             (entry (generate-byte-code-for-entry segment node cont))
1592             (exit
1593              (when (exit-entry node)
1594                (generate-byte-code-for-exit segment node cont)))))
1595         (let* ((succ (block-succ block))
1596                (first-succ (car succ))
1597                (last (block-last block)))
1598           (unless (or (cdr succ)
1599                       (eq (byte-block-info-block next) first-succ)
1600                       (eq (component-tail component) first-succ)
1601                       (and (basic-combination-p last)
1602                            (node-tail-p last)
1603                            ;; Tail local calls that have been
1604                            ;; converted to an assignment need the
1605                            ;; branch.
1606                            (not (and (eq (basic-combination-kind last) :local)
1607                                      (member (functional-kind
1608                                               (combination-lambda last))
1609                                              '(:let :assignment))))))
1610             (output-branch segment
1611                            byte-branch-always
1612                            (byte-block-info-label
1613                             (block-info first-succ))))))))
1614   (values))
1615 \f
1616 ;;;; special purpose annotate/compile optimizers
1617
1618 (defoptimizer (eq byte-annotate) ((this that) node)
1619   (declare (ignore this that))
1620   (when (if-p (continuation-dest (node-cont node)))
1621     (annotate-known-call node)
1622     t))
1623
1624 (defoptimizer (eq byte-compile) ((this that) call results num-args segment)
1625   (progn segment) ; ignorable.
1626   ;; We don't have to do anything, because everything is handled by
1627   ;; the IF byte-generator.
1628   (aver (eq results :eq-test))
1629   (aver (eql num-args 2))
1630   (values))
1631
1632 (defoptimizer (values byte-compile)
1633               ((&rest values) node results num-args segment)
1634   (canonicalize-values segment results num-args))
1635
1636 (defknown %byte-pop-stack (index) (values))
1637
1638 (defoptimizer (%byte-pop-stack byte-annotate) ((count) node)
1639   (aver (constant-continuation-p count))
1640   (annotate-continuation count 0)
1641   (annotate-continuation (basic-combination-fun node) 0)
1642   (setf (node-tail-p node) nil)
1643   t)
1644
1645 (defoptimizer (%byte-pop-stack byte-compile)
1646               ((count) node results num-args segment)
1647   (aver (and (zerop num-args) (zerop results)))
1648   (output-byte-with-operand segment byte-pop-n (continuation-value count)))
1649
1650 (defoptimizer (%special-bind byte-annotate) ((var value) node)
1651   (annotate-continuation var 0)
1652   (annotate-continuation value 1)
1653   (annotate-continuation (basic-combination-fun node) 0)
1654   (setf (node-tail-p node) nil)
1655   t)
1656
1657 (defoptimizer (%special-bind byte-compile)
1658               ((var value) node results num-args segment)
1659   (aver (and (eql num-args 1) (zerop results)))
1660   (output-push-constant segment (leaf-name (continuation-value var)))
1661   (output-do-inline-function segment '%byte-special-bind))
1662
1663 (defoptimizer (%special-unbind byte-annotate) ((var) node)
1664   (annotate-continuation var 0)
1665   (annotate-continuation (basic-combination-fun node) 0)
1666   (setf (node-tail-p node) nil)
1667   t)
1668
1669 (defoptimizer (%special-unbind byte-compile)
1670               ((var) node results num-args segment)
1671   (aver (and (zerop num-args) (zerop results)))
1672   (output-do-inline-function segment '%byte-special-unbind))
1673
1674 (defoptimizer (%catch byte-annotate) ((nlx-info tag) node)
1675   (annotate-continuation nlx-info 0)
1676   (annotate-continuation tag 1)
1677   (annotate-continuation (basic-combination-fun node) 0)
1678   (setf (node-tail-p node) nil)
1679   t)
1680
1681 (defoptimizer (%catch byte-compile)
1682               ((nlx-info tag) node results num-args segment)
1683   (progn node) ; ignore
1684   (aver (and (= num-args 1) (zerop results)))
1685   (output-do-xop segment 'catch)
1686   (let ((info (nlx-info-info (continuation-value nlx-info))))
1687     (output-reference segment (byte-nlx-info-label info))))
1688
1689 (defoptimizer (%cleanup-point byte-compile) (() node results num-args segment)
1690   (progn node segment) ; ignore
1691   (aver (and (zerop num-args) (zerop results))))
1692
1693 (defoptimizer (%catch-breakup byte-compile) (() node results num-args segment)
1694   (progn node) ; ignore
1695   (aver (and (zerop num-args) (zerop results)))
1696   (output-do-xop segment 'breakup))
1697
1698 (defoptimizer (%lexical-exit-breakup byte-annotate) ((nlx-info) node)
1699   (annotate-continuation nlx-info 0)
1700   (annotate-continuation (basic-combination-fun node) 0)
1701   (setf (node-tail-p node) nil)
1702   t)
1703
1704 (defoptimizer (%lexical-exit-breakup byte-compile)
1705               ((nlx-info) node results num-args segment)
1706   (aver (and (zerop num-args) (zerop results)))
1707   (let ((nlx-info (continuation-value nlx-info)))
1708     (when (ecase (cleanup-kind (nlx-info-cleanup nlx-info))
1709             (:block
1710              ;; We only want to do this for the fall-though case.
1711              (not (eq (car (block-pred (node-block node)))
1712                       (nlx-info-target nlx-info))))
1713             (:tagbody
1714              ;; Only want to do it once per tagbody.
1715              (not (byte-nlx-info-duplicate (nlx-info-info nlx-info)))))
1716       (output-do-xop segment 'breakup))))
1717
1718 (defoptimizer (%nlx-entry byte-annotate) ((nlx-info) node)
1719   (annotate-continuation nlx-info 0)
1720   (annotate-continuation (basic-combination-fun node) 0)
1721   (setf (node-tail-p node) nil)
1722   t)
1723
1724 (defoptimizer (%nlx-entry byte-compile)
1725               ((nlx-info) node results num-args segment)
1726   (progn node results) ; ignore
1727   (aver (eql num-args 0))
1728   (let* ((info (continuation-value nlx-info))
1729          (byte-info (nlx-info-info info)))
1730     (output-label segment (byte-nlx-info-label byte-info))
1731     ;; ### :non-local-entry
1732     (ecase (cleanup-kind (nlx-info-cleanup info))
1733       ((:catch :block)
1734        (checked-canonicalize-values segment
1735                                     (nlx-info-continuation info)
1736                                     :unknown))
1737       ((:tagbody :unwind-protect)))))
1738
1739 (defoptimizer (%unwind-protect byte-annotate)
1740               ((nlx-info cleanup-fun) node)
1741   (annotate-continuation nlx-info 0)
1742   (annotate-continuation cleanup-fun 0)
1743   (annotate-continuation (basic-combination-fun node) 0)
1744   (setf (node-tail-p node) nil)
1745   t)
1746
1747 (defoptimizer (%unwind-protect byte-compile)
1748               ((nlx-info cleanup-fun) node results num-args segment)
1749   (aver (and (zerop num-args) (zerop results)))
1750   (output-do-xop segment 'unwind-protect)
1751   (output-reference segment
1752                     (byte-nlx-info-label
1753                      (nlx-info-info
1754                       (continuation-value nlx-info)))))
1755
1756 (defoptimizer (%unwind-protect-breakup byte-compile)
1757               (() node results num-args segment)
1758   (progn node) ; ignore
1759   (aver (and (zerop num-args) (zerop results)))
1760   (output-do-xop segment 'breakup))
1761
1762 (defoptimizer (%continue-unwind byte-annotate) ((a b c) node)
1763   (annotate-continuation a 0)
1764   (annotate-continuation b 0)
1765   (annotate-continuation c 0)
1766   (annotate-continuation (basic-combination-fun node) 0)
1767   (setf (node-tail-p node) nil)
1768   t)
1769
1770 (defoptimizer (%continue-unwind byte-compile)
1771               ((a b c) node results num-args segment)
1772   (progn node) ; ignore
1773   (aver (member results '(0 nil)))
1774   (aver (eql num-args 0))
1775   (output-do-xop segment 'breakup))
1776
1777 (defoptimizer (%load-time-value byte-annotate) ((handle) node)
1778   (annotate-continuation handle 0)
1779   (annotate-continuation (basic-combination-fun node) 0)
1780   (setf (node-tail-p node) nil)
1781   t)
1782
1783 (defoptimizer (%load-time-value byte-compile)
1784               ((handle) node results num-args segment)
1785   (progn node) ; ignore
1786   (aver (zerop num-args))
1787   (output-push-load-time-constant segment :load-time-value
1788                                   (continuation-value handle))
1789   (canonicalize-values segment results 1))
1790 \f
1791 ;;; Make a byte-function for LAMBDA.
1792 (defun make-xep-for (lambda)
1793   (flet ((entry-point-for (entry)
1794            (let ((info (lambda-info entry)))
1795              (aver (byte-lambda-info-interesting info))
1796              (sb!assem:label-position (byte-lambda-info-label info)))))
1797     (let ((entry (lambda-entry-function lambda)))
1798       (etypecase entry
1799         (optional-dispatch
1800          (let ((rest-arg-p nil)
1801                (num-more 0))
1802            (declare (type index num-more))
1803            (collect ((keywords))
1804              (dolist (var (nthcdr (optional-dispatch-max-args entry)
1805                                   (optional-dispatch-arglist entry)))
1806                (let ((arg-info (lambda-var-arg-info var)))
1807                  (aver arg-info)
1808                  (ecase (arg-info-kind arg-info)
1809                    (:rest
1810                     (aver (not rest-arg-p))
1811                     (incf num-more)
1812                     (setf rest-arg-p t))
1813                    (:keyword
1814                     ;; FIXME: Since ANSI specifies that &KEY arguments
1815                     ;; needn't actually be keywords, :KEY would be a
1816                     ;; better label for this behavior than :KEYWORD is,
1817                     ;; and (KEY-ARGS) would be a better name for the
1818                     ;; accumulator than (KEYWORDS) is.
1819                     (let ((s-p (arg-info-supplied-p arg-info))
1820                           (default (arg-info-default arg-info)))
1821                       (incf num-more (if s-p 2 1))
1822                       (keywords (list (arg-info-key arg-info)
1823                                       (if (constantp default)
1824                                           (eval default)
1825                                           nil)
1826                                       (if s-p t nil))))))))
1827              (make-hairy-byte-function
1828               :name (leaf-name entry)
1829               :min-args (optional-dispatch-min-args entry)
1830               :max-args (optional-dispatch-max-args entry)
1831               :entry-points
1832               (mapcar #'entry-point-for (optional-dispatch-entry-points entry))
1833               :more-args-entry-point
1834               (entry-point-for (optional-dispatch-main-entry entry))
1835               :num-more-args num-more
1836               :rest-arg-p rest-arg-p
1837               :keywords-p
1838               (if (optional-dispatch-keyp entry)
1839                   (if (optional-dispatch-allowp entry)
1840                       :allow-others t))
1841               :keywords (keywords)))))
1842         (clambda
1843          (let ((args (length (lambda-vars entry))))
1844            (make-simple-byte-function
1845             :name (leaf-name entry)
1846             :num-args args
1847             :entry-point (entry-point-for entry))))))))
1848
1849 (defun generate-xeps (component)
1850   (let ((xeps nil))
1851     (dolist (lambda (component-lambdas component))
1852       (when (member (lambda-kind lambda) '(:external :top-level))
1853         (push (cons lambda (make-xep-for lambda)) xeps)))
1854     xeps))
1855 \f
1856 ;;;; noise to actually do the compile
1857
1858 (defun assign-locals (component)
1859   ;; Process all of the lambdas in component, and assign stack frame
1860   ;; locations for all the locals.
1861   (dolist (lambda (component-lambdas component))
1862     ;; We don't generate any code for :external lambdas, so we don't need
1863     ;; to allocate stack space. Also, we don't use the ``more'' entry,
1864     ;; so we don't need code for it.
1865     (cond
1866      ((or (eq (lambda-kind lambda) :external)
1867           (and (eq (lambda-kind lambda) :optional)
1868                (eq (optional-dispatch-more-entry
1869                     (lambda-optional-dispatch lambda))
1870                    lambda)))
1871       (setf (lambda-info lambda)
1872             (make-byte-lambda-info :interesting nil)))
1873      (t
1874       (let ((num-locals 0))
1875         (let* ((vars (lambda-vars lambda))
1876                (arg-num (+ (length vars)
1877                            (length (environment-closure
1878                                     (lambda-environment lambda))))))
1879           (dolist (var vars)
1880             (decf arg-num)
1881             (cond ((or (lambda-var-sets var) (lambda-var-indirect var))
1882                    (setf (leaf-info var)
1883                          (make-byte-lambda-var-info :offset num-locals))
1884                    (incf num-locals))
1885                   ((leaf-refs var)
1886                    (setf (leaf-info var)
1887                          (make-byte-lambda-var-info :argp t
1888                                                     :offset arg-num))))))
1889         (dolist (let (lambda-lets lambda))
1890           (dolist (var (lambda-vars let))
1891             (setf (leaf-info var)
1892                   (make-byte-lambda-var-info :offset num-locals))
1893             (incf num-locals)))
1894         (let ((entry-nodes-already-done nil))
1895           (dolist (nlx-info (environment-nlx-info (lambda-environment lambda)))
1896             (ecase (cleanup-kind (nlx-info-cleanup nlx-info))
1897               (:block
1898                (setf (nlx-info-info nlx-info)
1899                      (make-byte-nlx-info :stack-slot num-locals))
1900                (incf num-locals))
1901               (:tagbody
1902                (let* ((entry (cleanup-mess-up (nlx-info-cleanup nlx-info)))
1903                       (cruft (assoc entry entry-nodes-already-done)))
1904                  (cond (cruft
1905                         (setf (nlx-info-info nlx-info)
1906                               (make-byte-nlx-info :stack-slot (cdr cruft)
1907                                                   :duplicate t)))
1908                        (t
1909                         (push (cons entry num-locals) entry-nodes-already-done)
1910                         (setf (nlx-info-info nlx-info)
1911                               (make-byte-nlx-info :stack-slot num-locals))
1912                         (incf num-locals)))))
1913               ((:catch :unwind-protect)
1914                (setf (nlx-info-info nlx-info) (make-byte-nlx-info))))))
1915         (setf (lambda-info lambda)
1916               (make-byte-lambda-info :stack-size num-locals))))))
1917
1918   (values))
1919
1920 (defun byte-compile-component (component)
1921   (setf (component-info component) (make-byte-component-info))
1922   (maybe-mumble "ByteAnn ")
1923
1924   ;; Assign offsets for all the locals, and figure out which args can
1925   ;; stay in the argument area and which need to be moved into locals.
1926   (assign-locals component)
1927
1928   ;; Annotate every continuation with information about how we want the
1929   ;; values.
1930   (annotate-ir1 component)
1931
1932   ;; Determine what stack values are dead, and emit cleanup code to pop
1933   ;; them.
1934   (byte-stack-analyze component)
1935
1936   ;; Make sure any newly added blocks have a block-number.
1937   (dfo-as-needed component)
1938
1939   ;; Assign an ordering of the blocks.
1940   (control-analyze component #'make-byte-block-info)
1941
1942   ;; Find the start labels for the lambdas.
1943   (dolist (lambda (component-lambdas component))
1944     (let ((info (lambda-info lambda)))
1945       (when (byte-lambda-info-interesting info)
1946         (setf (byte-lambda-info-label info)
1947               (byte-block-info-label
1948                (block-info (node-block (lambda-bind lambda))))))))
1949
1950   ;; Delete any blocks that we are not going to emit from the emit order.
1951   (do-blocks (block component)
1952     (unless (block-interesting block)
1953       (let* ((info (block-info block))
1954              (prev (byte-block-info-prev info))
1955              (next (byte-block-info-next info)))
1956         (setf (byte-block-info-next prev) next)
1957         (setf (byte-block-info-prev next) prev))))
1958
1959   (maybe-mumble "ByteGen ")
1960   (let ((segment nil))
1961     (unwind-protect
1962         (progn
1963           (setf segment (sb!assem:make-segment :name "Byte Output"))
1964           (generate-byte-code segment component)
1965           (let ((code-length (sb!assem:finalize-segment segment))
1966                 (xeps (generate-xeps component))
1967                 (constants (byte-component-info-constants
1968                             (component-info component))))
1969             (when *compiler-trace-output*
1970               (describe-component component *compiler-trace-output*)
1971               (describe-byte-component component xeps segment
1972                                        *compiler-trace-output*))
1973             (etypecase *compile-object*
1974               (fasl-output
1975                (maybe-mumble "FASL")
1976                (fasl-dump-byte-component segment code-length constants xeps
1977                                          *compile-object*))
1978               (core-object
1979                (maybe-mumble "Core")
1980                (make-core-byte-component segment code-length constants xeps
1981                                          *compile-object*))
1982               (null))))))
1983   (values))
1984 \f
1985 ;;;; extra stuff for debugging
1986
1987 #!+sb-show
1988 (defun dump-stack-info (component)
1989   (do-blocks (block component)
1990      (when (block-interesting block)
1991        (print-nodes block)
1992        (let ((info (block-info block)))
1993          (cond
1994           (info
1995            (format t
1996            "start-stack ~S~%consume ~S~%produce ~S~%end-stack ~S~%~
1997             total-consume ~S~%~@[nlx-entries ~S~%~]~@[nlx-entry-p ~S~%~]"
1998            (byte-block-info-start-stack info)
1999            (byte-block-info-consumes info)
2000            (byte-block-info-produces info)
2001            (byte-block-info-end-stack info)
2002            (byte-block-info-total-consumes info)
2003            (byte-block-info-nlx-entries info)
2004            (byte-block-info-nlx-entry-p info)))
2005           (t
2006            (format t "no info~%")))))))