0.6.7.22: removed CVS dollar-Header-dollar tags from sources
[sbcl.git] / src / compiler / assem.lisp
1 ;;;; scheduling assembler
2
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
5 ;;;;
6 ;;;; This software is derived from the CMU CL system, which was
7 ;;;; written at Carnegie Mellon University and released into the
8 ;;;; public domain. The software is in the public domain and is
9 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
10 ;;;; files for more information.
11
12 (in-package "SB!ASSEM")
13 \f
14 ;;;; assembly control parameters
15
16 (defvar *assem-scheduler-p* nil)
17 (declaim (type boolean *assem-scheduler-p*))
18
19 (defvar *assem-instructions* (make-hash-table :test 'equal))
20 (declaim (type hash-table *assem-instructions*))
21
22 (defvar *assem-max-locations* 0)
23 (declaim (type index *assem-max-locations*))
24 \f
25 ;;;; the SEGMENT structure
26
27 ;;; This structure holds the state of the assembler.
28 (defstruct segment
29   ;; the name of this segment (for debugging output and stuff)
30   (name "Unnamed" :type simple-base-string)
31   ;; Ordinarily this is a vector where instructions are written. If
32   ;; the segment is made invalid (e.g. by APPEND-SEGMENT) then the
33   ;; vector can be replaced by NIL.
34   (buffer (make-array 0
35                       :fill-pointer 0
36                       :adjustable t
37                       :element-type 'assembly-unit)
38           :type (or null (vector assembly-unit)))
39   ;; whether or not to run the scheduler. Note: if the instruction
40   ;; definitions were not compiled with the scheduler turned on, this
41   ;; has no effect.
42   (run-scheduler nil)
43   ;; If a function, then this is funcalled for each inst emitted with
44   ;; the segment, the VOP, the name of the inst (as a string), and the
45   ;; inst arguments.
46   (inst-hook nil :type (or function null))
47   ;; what position does this correspond to? Initially, positions and
48   ;; indexes are the same, but after we start collapsing choosers,
49   ;; positions can change while indexes stay the same.
50   (current-posn 0 :type index)
51   ;; a list of all the annotations that have been output to this segment
52   (annotations nil :type list)
53   ;; a pointer to the last cons cell in the annotations list. This is
54   ;; so we can quickly add things to the end of the annotations list.
55   (last-annotation nil :type list)
56   ;; the number of bits of alignment at the last time we synchronized
57   (alignment max-alignment :type alignment)
58   ;; the position the last time we synchronized
59   (sync-posn 0 :type index)
60   ;; The posn and index everything ends at. This is not maintained
61   ;; while the data is being generated, but is filled in after.
62   ;; Basically, we copy current-posn and current-index so that we can
63   ;; trash them while processing choosers and back-patches.
64   (final-posn 0 :type index)
65   (final-index 0 :type index)
66   ;; *** State used by the scheduler during instruction queueing.
67   ;;
68   ;; a list of postits. These are accumulated between instructions.
69   (postits nil :type list)
70   ;; ``Number'' for last instruction queued. Used only to supply insts
71   ;; with unique sset-element-number's.
72   (inst-number 0 :type index)
73   ;; SIMPLE-VECTORs mapping locations to the instruction that reads them and
74   ;; instructions that write them
75   (readers (make-array *assem-max-locations* :initial-element nil)
76            :type simple-vector)
77   (writers (make-array *assem-max-locations* :initial-element nil)
78            :type simple-vector)
79   ;; The number of additional cycles before the next control transfer,
80   ;; or NIL if a control transfer hasn't been queued. When a delayed
81   ;; branch is queued, this slot is set to the delay count.
82   (branch-countdown nil :type (or null (and fixnum unsigned-byte)))
83   ;; *** These two slots are used both by the queuing noise and the
84   ;; scheduling noise.
85   ;;
86   ;; All the instructions that are pending and don't have any
87   ;; unresolved dependents. We don't list branches here even if they
88   ;; would otherwise qualify. They are listed above.
89   (emittable-insts-sset (make-sset) :type sset)
90   ;; list of queued branches. We handle these specially, because they
91   ;; have to be emitted at a specific place (e.g. one slot before the
92   ;; end of the block).
93   (queued-branches nil :type list)
94   ;; *** state used by the scheduler during instruction scheduling.
95   ;;
96   ;; the instructions who would have had a read dependent removed if
97   ;; it were not for a delay slot. This is a list of lists. Each
98   ;; element in the top level list corresponds to yet another cycle of
99   ;; delay. Each element in the second level lists is a dotted pair,
100   ;; holding the dependency instruction and the dependent to remove.
101   (delayed nil :type list)
102   ;; The emittable insts again, except this time as a list sorted by depth.
103   (emittable-insts-queue nil :type list)
104   ;; Whether or not to collect dynamic statistics. This is just the same as
105   ;; *COLLECT-DYNAMIC-STATISTICS* but is faster to reference.
106   #!+sb-dyncount
107   (collect-dynamic-statistics nil))
108 (sb!c::defprinter (segment)
109   name)
110
111 ;;; where the next byte of output goes
112 #!-sb-fluid (declaim (inline segment-current-index))
113 (defun segment-current-index (segment)
114   (fill-pointer (segment-buffer segment)))
115 (defun (setf segment-current-index) (new-value segment)
116   (let ((buffer (segment-buffer segment)))
117     ;; Make sure that the array is big enough.
118     (do ()
119         ((>= (array-dimension buffer 0) new-value))
120       ;; When we have to increase the size of the array, we want to
121       ;; roughly double the vector length: that way growing the array
122       ;; to size N conses only O(N) bytes in total. But just doubling
123       ;; the length would leave a zero-length vector unchanged. Hence,
124       ;; take the MAX with 1..
125       (adjust-array buffer (max 1 (* 2 (array-dimension buffer 0)))))
126     ;; Now that the array has the intended next free byte, we can point to it.
127     (setf (fill-pointer buffer) new-value)))
128 \f
129 ;;;; structures/types used by the scheduler
130
131 (sb!c:def-boolean-attribute instruction
132   ;; This attribute is set if the scheduler can freely flush this
133   ;; instruction if it thinks it is not needed. Examples are NOP and
134   ;; instructions that have no side effect not described by the
135   ;; writes.
136   flushable
137   ;; This attribute is set when an instruction can cause a control
138   ;; transfer. For test instructions, the delay is used to determine
139   ;; how many instructions follow the branch.
140   branch
141   ;; This attribute indicates that this ``instruction'' can be
142   ;; variable length, and therefore better never be used in a branch
143   ;; delay slot.
144   variable-length)
145
146 (defstruct (instruction
147             (:include sset-element)
148             (:conc-name inst-)
149             (:constructor make-instruction (number emitter attributes delay)))
150   ;; The function to envoke to actually emit this instruction. Gets called
151   ;; with the segment as its one argument.
152   (emitter (required-argument) :type (or null function))
153   ;; The attributes of this instruction.
154   (attributes (instruction-attributes) :type sb!c:attributes)
155   ;; Number of instructions or cycles of delay before additional
156   ;; instructions can read our writes.
157   (delay 0 :type (and fixnum unsigned-byte))
158   ;; the maximum number of instructions in the longest dependency
159   ;; chain from this instruction to one of the independent
160   ;; instructions. This is used as a heuristic at to which
161   ;; instructions should be scheduled first.
162   (depth nil :type (or null (and fixnum unsigned-byte)))
163   ;; Note: When trying remember which of the next four is which, note
164   ;; that the ``read'' or ``write'' always refers to the dependent
165   ;; (second) instruction.
166   ;;
167   ;; instructions whose writes this instruction tries to read
168   (read-dependencies (make-sset) :type sset)
169   ;; instructions whose writes or reads are overwritten by this instruction
170   (write-dependencies (make-sset) :type sset)
171   ;; instructions which write what we read or write
172   (write-dependents (make-sset) :type sset)
173   ;; instructions which read what we write
174   (read-dependents (make-sset) :type sset))
175 #!+sb-show-assem (defvar *inst-ids* (make-hash-table :test 'eq))
176 #!+sb-show-assem (defvar *next-inst-id* 0)
177 (sb!int:def!method print-object ((inst instruction) stream)
178   (print-unreadable-object (inst stream :type t :identity t)
179     #!+sb-show-assem
180     (princ (or (gethash inst *inst-ids*)
181                (setf (gethash inst *inst-ids*)
182                      (incf *next-inst-id*)))
183            stream)
184     (format stream
185             #!+sb-show-assem " emitter=~S" #!-sb-show-assem "emitter=~S"
186             (let ((emitter (inst-emitter inst)))
187               (if emitter
188                   (multiple-value-bind (lambda lexenv-p name)
189                       (function-lambda-expression emitter)
190                     (declare (ignore lambda lexenv-p))
191                     name)
192                   '<flushed>)))
193     (when (inst-depth inst)
194       (format stream ", depth=~D" (inst-depth inst)))))
195
196 #!+sb-show-assem
197 (defun reset-inst-ids ()
198   (clrhash *inst-ids*)
199   (setf *next-inst-id* 0))
200 \f
201 ;;;; the scheduler itself
202
203 (defmacro without-scheduling ((&optional (segment '**current-segment**))
204                               &body body)
205   #!+sb-doc
206   "Execute BODY (as a PROGN) without scheduling any of the instructions
207    generated inside it. This is not protected by UNWIND-PROTECT, so
208    DO NOT use THROW or RETURN-FROM to escape from it."
209   ;; FIXME: Why not just use UNWIND-PROTECT? Or is there some other
210   ;; reason why we shouldn't use THROW or RETURN-FROM?
211   (let ((var (gensym))
212         (seg (gensym)))
213     `(let* ((,seg ,segment)
214             (,var (segment-run-scheduler ,seg)))
215        (when ,var
216          (schedule-pending-instructions ,seg)
217          (setf (segment-run-scheduler ,seg) nil))
218        ,@body
219        (setf (segment-run-scheduler ,seg) ,var))))
220
221 (defmacro note-dependencies ((segment inst) &body body)
222   (sb!int:once-only ((segment segment) (inst inst))
223     `(macrolet ((reads (loc) `(note-read-dependency ,',segment ,',inst ,loc))
224                 (writes (loc &rest keys)
225                   `(note-write-dependency ,',segment ,',inst ,loc ,@keys)))
226        ,@body)))
227
228 (defun note-read-dependency (segment inst read)
229   (multiple-value-bind (loc-num size)
230       (sb!c:location-number read)
231     #!+sb-show-assem (format *trace-output*
232                              "~&~S reads ~S[~D for ~D]~%"
233                              inst read loc-num size)
234     (when loc-num
235       ;; Iterate over all the locations for this TN.
236       (do ((index loc-num (1+ index))
237            (end-loc (+ loc-num (or size 1))))
238           ((>= index end-loc))
239         (declare (type (mod 2048) index end-loc))
240         (let ((writers (svref (segment-writers segment) index)))
241           (when writers
242             ;; The inst that wrote the value we want to read must have
243             ;; completed.
244             (let ((writer (car writers)))
245               (sset-adjoin writer (inst-read-dependencies inst))
246               (sset-adjoin inst (inst-read-dependents writer))
247               (sset-delete writer (segment-emittable-insts-sset segment))
248               ;; And it must have been completed *after* all other
249               ;; writes to that location. Actually, that isn't quite
250               ;; true. Each of the earlier writes could be done
251               ;; either before this last write, or after the read, but
252               ;; we have no way of representing that.
253               (dolist (other-writer (cdr writers))
254                 (sset-adjoin other-writer (inst-write-dependencies writer))
255                 (sset-adjoin writer (inst-write-dependents other-writer))
256                 (sset-delete other-writer
257                              (segment-emittable-insts-sset segment))))
258             ;; And we don't need to remember about earlier writes any
259             ;; more. Shortening the writers list means that we won't
260             ;; bother generating as many explicit arcs in the graph.
261             (setf (cdr writers) nil)))
262         (push inst (svref (segment-readers segment) index)))))
263   (values))
264
265 (defun note-write-dependency (segment inst write &key partially)
266   (multiple-value-bind (loc-num size)
267       (sb!c:location-number write)
268     #!+sb-show-assem (format *trace-output*
269                              "~&~S writes ~S[~D for ~D]~%"
270                              inst write loc-num size)
271     (when loc-num
272       ;; Iterate over all the locations for this TN.
273       (do ((index loc-num (1+ index))
274            (end-loc (+ loc-num (or size 1))))
275           ((>= index end-loc))
276         (declare (type (mod 2048) index end-loc))
277         ;; All previous reads of this location must have completed.
278         (dolist (prev-inst (svref (segment-readers segment) index))
279           (unless (eq prev-inst inst)
280             (sset-adjoin prev-inst (inst-write-dependencies inst))
281             (sset-adjoin inst (inst-write-dependents prev-inst))
282             (sset-delete prev-inst (segment-emittable-insts-sset segment))))
283         (when partially
284           ;; All previous writes to the location must have completed.
285           (dolist (prev-inst (svref (segment-writers segment) index))
286             (sset-adjoin prev-inst (inst-write-dependencies inst))
287             (sset-adjoin inst (inst-write-dependents prev-inst))
288             (sset-delete prev-inst (segment-emittable-insts-sset segment)))
289           ;; And we can forget about remembering them, because
290           ;; depending on us is as good as depending on them.
291           (setf (svref (segment-writers segment) index) nil))
292         (push inst (svref (segment-writers segment) index)))))
293   (values))
294
295 ;;; This routine is called by due to uses of the INST macro when the
296 ;;; scheduler is turned on. The change to the dependency graph has
297 ;;; already been computed, so we just have to check to see whether the
298 ;;; basic block is terminated.
299 (defun queue-inst (segment inst)
300   #!+sb-show-assem (format *trace-output* "~&queuing ~S~%" inst)
301   #!+sb-show-assem (format *trace-output*
302                            "  reads ~S~%  writes ~S~%"
303                            (sb!int:collect ((reads))
304                              (do-sset-elements (read
305                                                 (inst-read-dependencies inst))
306                                 (reads read))
307                              (reads))
308                            (sb!int:collect ((writes))
309                              (do-sset-elements (write
310                                                 (inst-write-dependencies inst))
311                                 (writes write))
312                              (writes)))
313   (assert (segment-run-scheduler segment))
314   (let ((countdown (segment-branch-countdown segment)))
315     (when countdown
316       (decf countdown)
317       (assert (not (instruction-attributep (inst-attributes inst)
318                                            variable-length))))
319     (cond ((instruction-attributep (inst-attributes inst) branch)
320            (unless countdown
321              (setf countdown (inst-delay inst)))
322            (push (cons countdown inst)
323                  (segment-queued-branches segment)))
324           (t
325            (sset-adjoin inst (segment-emittable-insts-sset segment))))
326     (when countdown
327       (setf (segment-branch-countdown segment) countdown)
328       (when (zerop countdown)
329         (schedule-pending-instructions segment))))
330   (values))
331
332 ;;; Emit all the pending instructions, and reset any state. This is
333 ;;; called whenever we hit a label (i.e. an entry point of some kind)
334 ;;; and when the user turns the scheduler off (otherwise, the queued
335 ;;; instructions would sit there until the scheduler was turned back
336 ;;; on, and emitted in the wrong place).
337 (defun schedule-pending-instructions (segment)
338   (assert (segment-run-scheduler segment))
339
340   ;; Quick blow-out if nothing to do.
341   (when (and (sset-empty (segment-emittable-insts-sset segment))
342              (null (segment-queued-branches segment)))
343     (return-from schedule-pending-instructions
344                  (values)))
345
346   #!+sb-show-assem (format *trace-output*
347                            "~&scheduling pending instructions..~%")
348
349   ;; Note that any values live at the end of the block have to be
350   ;; computed last.
351   (let ((emittable-insts (segment-emittable-insts-sset segment))
352         (writers (segment-writers segment)))
353     (dotimes (index (length writers))
354       (let* ((writer (svref writers index))
355              (inst (car writer))
356              (overwritten (cdr writer)))
357         (when writer
358           (when overwritten
359             (let ((write-dependencies (inst-write-dependencies inst)))
360               (dolist (other-inst overwritten)
361                 (sset-adjoin inst (inst-write-dependents other-inst))
362                 (sset-adjoin other-inst write-dependencies)
363                 (sset-delete other-inst emittable-insts))))
364           ;; If the value is live at the end of the block, we can't flush it.
365           (setf (instruction-attributep (inst-attributes inst) flushable)
366                 nil)))))
367
368   ;; Grovel through the entire graph in the forward direction finding
369   ;; all the leaf instructions.
370   (labels ((grovel-inst (inst)
371              (let ((max 0))
372                (do-sset-elements (dep (inst-write-dependencies inst))
373                  (let ((dep-depth (or (inst-depth dep) (grovel-inst dep))))
374                    (when (> dep-depth max)
375                      (setf max dep-depth))))
376                (do-sset-elements (dep (inst-read-dependencies inst))
377                  (let ((dep-depth
378                         (+ (or (inst-depth dep) (grovel-inst dep))
379                            (inst-delay dep))))
380                    (when (> dep-depth max)
381                      (setf max dep-depth))))
382                (cond ((and (sset-empty (inst-read-dependents inst))
383                            (instruction-attributep (inst-attributes inst)
384                                                    flushable))
385                       #!+sb-show-assem (format *trace-output*
386                                                "flushing ~S~%"
387                                                inst)
388                       (setf (inst-emitter inst) nil)
389                       (setf (inst-depth inst) max))
390                      (t
391                       (setf (inst-depth inst) max))))))
392     (let ((emittable-insts nil)
393           (delayed nil))
394       (do-sset-elements (inst (segment-emittable-insts-sset segment))
395         (grovel-inst inst)
396         (if (zerop (inst-delay inst))
397             (push inst emittable-insts)
398             (setf delayed
399                   (add-to-nth-list delayed inst (1- (inst-delay inst))))))
400       (setf (segment-emittable-insts-queue segment)
401             (sort emittable-insts #'> :key #'inst-depth))
402       (setf (segment-delayed segment) delayed))
403     (dolist (branch (segment-queued-branches segment))
404       (grovel-inst (cdr branch))))
405   #!+sb-show-assem (format *trace-output*
406                            "queued branches: ~S~%"
407                            (segment-queued-branches segment))
408   #!+sb-show-assem (format *trace-output*
409                            "initially emittable: ~S~%"
410                            (segment-emittable-insts-queue segment))
411   #!+sb-show-assem (format *trace-output*
412                            "initially delayed: ~S~%"
413                            (segment-delayed segment))
414
415   ;; Accumulate the results in reverse order. Well, actually, this
416   ;; list will be in forward order, because we are generating the
417   ;; reverse order in reverse.
418   (let ((results nil))
419
420     ;; Schedule all the branches in their exact locations.
421     (let ((insts-from-end (segment-branch-countdown segment)))
422       (dolist (branch (segment-queued-branches segment))
423         (let ((inst (cdr branch)))
424           (dotimes (i (- (car branch) insts-from-end))
425             ;; Each time through this loop we need to emit another
426             ;; instruction. First, we check to see whether there is
427             ;; any instruction that must be emitted before (i.e. must
428             ;; come after) the branch inst. If so, emit it. Otherwise,
429             ;; just pick one of the emittable insts. If there is
430             ;; nothing to do, then emit a nop. ### Note: despite the
431             ;; fact that this is a loop, it really won't work for
432             ;; repetitions other then zero and one. For example, if
433 p           ;; the branch has two dependents and one of them dpends on
434             ;; the other, then the stuff that grabs a dependent could
435             ;; easily grab the wrong one. But I don't feel like fixing
436             ;; this because it doesn't matter for any of the
437             ;; architectures we are using or plan on using.
438             (flet ((maybe-schedule-dependent (dependents)
439                      (do-sset-elements (inst dependents)
440                        ;; If do-sset-elements enters the body, then there is a
441                        ;; dependent. Emit it.
442                        (note-resolved-dependencies segment inst)
443                        ;; Remove it from the emittable insts.
444                        (setf (segment-emittable-insts-queue segment)
445                              (delete inst
446                                      (segment-emittable-insts-queue segment)
447                                      :test #'eq))
448                        ;; And if it was delayed, removed it from the delayed
449                        ;; list. This can happen if there is a load in a
450                        ;; branch delay slot.
451                        (block scan-delayed
452                          (do ((delayed (segment-delayed segment)
453                                        (cdr delayed)))
454                              ((null delayed))
455                            (do ((prev nil cons)
456                                 (cons (car delayed) (cdr cons)))
457                                ((null cons))
458                              (when (eq (car cons) inst)
459                                (if prev
460                                    (setf (cdr prev) (cdr cons))
461                                    (setf (car delayed) (cdr cons)))
462                                (return-from scan-delayed nil)))))
463                        ;; And return it.
464                        (return inst))))
465               (let ((fill (or (maybe-schedule-dependent
466                                (inst-read-dependents inst))
467                               (maybe-schedule-dependent
468                                (inst-write-dependents inst))
469                               (schedule-one-inst segment t)
470                               :nop)))
471                 #!+sb-show-assem (format *trace-output*
472                                          "filling branch delay slot with ~S~%"
473                                          fill)
474                 (push fill results)))
475             (advance-one-inst segment)
476             (incf insts-from-end))
477           (note-resolved-dependencies segment inst)
478           (push inst results)
479           #!+sb-show-assem (format *trace-output* "emitting ~S~%" inst)
480           (advance-one-inst segment))))
481
482     ;; Keep scheduling stuff until we run out.
483     (loop
484       (let ((inst (schedule-one-inst segment nil)))
485         (unless inst
486           (return))
487         (push inst results)
488         (advance-one-inst segment)))
489
490     ;; Now call the emitters, but turn the scheduler off for the duration.
491     (setf (segment-run-scheduler segment) nil)
492     (dolist (inst results)
493       (if (eq inst :nop)
494           (sb!c:emit-nop segment)
495           (funcall (inst-emitter inst) segment)))
496     (setf (segment-run-scheduler segment) t))
497
498   ;; Clear out any residue left over.
499   (setf (segment-inst-number segment) 0)
500   (setf (segment-queued-branches segment) nil)
501   (setf (segment-branch-countdown segment) nil)
502   (setf (segment-emittable-insts-sset segment) (make-sset))
503   (fill (segment-readers segment) nil)
504   (fill (segment-writers segment) nil)
505
506   ;; That's all, folks.
507   (values))
508
509 ;;; a utility for maintaining the segment-delayed list. We cdr down
510 ;;; list n times (extending it if necessary) and then push thing on
511 ;;; into the car of that cons cell.
512 (defun add-to-nth-list (list thing n)
513   (do ((cell (or list (setf list (list nil)))
514              (or (cdr cell) (setf (cdr cell) (list nil))))
515        (i n (1- i)))
516       ((zerop i)
517        (push thing (car cell))
518        list)))
519
520 ;;; Find the next instruction to schedule and return it after updating
521 ;;; any dependency information. If we can't do anything useful right
522 ;;; now, but there is more work to be done, return :NOP to indicate
523 ;;; that a nop must be emitted. If we are all done, return NIL.
524 (defun schedule-one-inst (segment delay-slot-p)
525   (do ((prev nil remaining)
526        (remaining (segment-emittable-insts-queue segment) (cdr remaining)))
527       ((null remaining))
528     (let ((inst (car remaining)))
529       (unless (and delay-slot-p
530                    (instruction-attributep (inst-attributes inst)
531                                            variable-length))
532         ;; We've got us a live one here. Go for it.
533         #!+sb-show-assem (format *trace-output* "emitting ~S~%" inst)
534         ;; Delete it from the list of insts.
535         (if prev
536             (setf (cdr prev) (cdr remaining))
537             (setf (segment-emittable-insts-queue segment)
538                   (cdr remaining)))
539         ;; Note that this inst has been emitted.
540         (note-resolved-dependencies segment inst)
541         ;; And return.
542         (return-from schedule-one-inst
543                      ;; Are we wanting to flush this instruction?
544                      (if (inst-emitter inst)
545                          ;; Nope, it's still a go. So return it.
546                          inst
547                          ;; Yes, so pick a new one. We have to start
548                          ;; over, because note-resolved-dependencies
549                          ;; might have changed the emittable-insts-queue.
550                          (schedule-one-inst segment delay-slot-p))))))
551   ;; Nothing to do, so make something up.
552   (cond ((segment-delayed segment)
553          ;; No emittable instructions, but we have more work to do. Emit
554          ;; a NOP to fill in a delay slot.
555          #!+sb-show-assem (format *trace-output* "emitting a NOP~%")
556          :nop)
557         (t
558          ;; All done.
559          nil)))
560
561 ;;; This function is called whenever an instruction has been
562 ;;; scheduled, and we want to know what possibilities that opens up.
563 ;;; So look at all the instructions that this one depends on, and
564 ;;; remove this instruction from their dependents list. If we were the
565 ;;; last dependent, then that dependency can be emitted now.
566 (defun note-resolved-dependencies (segment inst)
567   (assert (sset-empty (inst-read-dependents inst)))
568   (assert (sset-empty (inst-write-dependents inst)))
569   (do-sset-elements (dep (inst-write-dependencies inst))
570     ;; These are the instructions who have to be completed before our
571     ;; write fires. Doesn't matter how far before, just before.
572     (let ((dependents (inst-write-dependents dep)))
573       (sset-delete inst dependents)
574       (when (and (sset-empty dependents)
575                  (sset-empty (inst-read-dependents dep)))
576         (insert-emittable-inst segment dep))))
577   (do-sset-elements (dep (inst-read-dependencies inst))
578     ;; These are the instructions who write values we read. If there
579     ;; is no delay, then just remove us from the dependent list.
580     ;; Otherwise, record the fact that in n cycles, we should be
581     ;; removed.
582     (if (zerop (inst-delay dep))
583         (let ((dependents (inst-read-dependents dep)))
584           (sset-delete inst dependents)
585           (when (and (sset-empty dependents)
586                      (sset-empty (inst-write-dependents dep)))
587             (insert-emittable-inst segment dep)))
588         (setf (segment-delayed segment)
589               (add-to-nth-list (segment-delayed segment)
590                                (cons dep inst)
591                                (inst-delay dep)))))
592   (values))
593
594 ;;; Process the next entry in segment-delayed. This is called whenever
595 ;;; anyone emits an instruction.
596 (defun advance-one-inst (segment)
597   (let ((delayed-stuff (pop (segment-delayed segment))))
598     (dolist (stuff delayed-stuff)
599       (if (consp stuff)
600           (let* ((dependency (car stuff))
601                  (dependent (cdr stuff))
602                  (dependents (inst-read-dependents dependency)))
603             (sset-delete dependent dependents)
604             (when (and (sset-empty dependents)
605                        (sset-empty (inst-write-dependents dependency)))
606               (insert-emittable-inst segment dependency)))
607           (insert-emittable-inst segment stuff)))))
608
609 ;;; Note that inst is emittable by sticking it in the
610 ;;; SEGMENT-EMITTABLE-INSTS-QUEUE list. We keep the emittable-insts
611 ;;; sorted with the largest ``depths'' first. Except that if INST is a
612 ;;; branch, don't bother. It will be handled correctly by the branch
613 ;;; emitting code in SCHEDULE-PENDING-INSTRUCTIONS.
614 (defun insert-emittable-inst (segment inst)
615   (unless (instruction-attributep (inst-attributes inst) branch)
616     #!+sb-show-assem (format *trace-output* "now emittable: ~S~%" inst)
617     (do ((my-depth (inst-depth inst))
618          (remaining (segment-emittable-insts-queue segment) (cdr remaining))
619          (prev nil remaining))
620         ((or (null remaining) (> my-depth (inst-depth (car remaining))))
621          (if prev
622              (setf (cdr prev) (cons inst remaining))
623              (setf (segment-emittable-insts-queue segment)
624                    (cons inst remaining))))))
625   (values))
626 \f
627 ;;;; structure used during output emission
628
629 ;;; common supertype for all the different kinds of annotations
630 (defstruct (annotation (:constructor nil))
631   ;; Where in the raw output stream was this annotation emitted.
632   (index 0 :type index)
633   ;; What position does that correspond to.
634   (posn nil :type (or index null)))
635
636 (defstruct (label (:include annotation)
637                   (:constructor gen-label ()))
638   ;; (doesn't need any additional information beyond what is in the
639   ;; annotation structure)
640   )
641 (sb!int:def!method print-object ((label label) stream)
642   (if (or *print-escape* *print-readably*)
643       (print-unreadable-object (label stream :type t)
644         (prin1 (sb!c:label-id label) stream))
645       (format stream "L~D" (sb!c:label-id label))))
646
647 ;;; a constraint on how the output stream must be aligned
648 (defstruct (alignment-note
649             (:include annotation)
650             (:conc-name alignment-)
651             (:predicate alignment-p)
652             (:constructor make-alignment (bits size fill-byte)))
653   ;; The minimum number of low-order bits that must be zero.
654   (bits 0 :type alignment)
655   ;; The amount of filler we are assuming this alignment op will take.
656   (size 0 :type (integer 0 #.(1- (ash 1 max-alignment))))
657   ;; The byte used as filling.
658   (fill-byte 0 :type (or assembly-unit (signed-byte #.assembly-unit-bits))))
659
660 ;;; a reference to someplace that needs to be back-patched when
661 ;;; we actually know what label positions, etc. are
662 (defstruct (back-patch
663             (:include annotation)
664             (:constructor make-back-patch (size function)))
665   ;; The area effected by this back-patch.
666   (size 0 :type index)
667   ;; The function to use to generate the real data
668   (function nil :type function))
669
670 ;;; This is similar to a BACK-PATCH, but also an indication that the
671 ;;; amount of stuff output depends on label-positions, etc.
672 ;;; Back-patches can't change their mind about how much stuff to emit,
673 ;;; but choosers can.
674 (defstruct (chooser
675             (:include annotation)
676             (:constructor make-chooser
677                           (size alignment maybe-shrink worst-case-fun)))
678   ;; the worst case size for this chooser. There is this much space allocated
679   ;; in the output buffer.
680   (size 0 :type index)
681   ;; the worst case alignment this chooser is guaranteed to preserve
682   (alignment 0 :type alignment)
683   ;; the function to call to determine of we can use a shorter sequence. It
684   ;; returns NIL if nothing shorter can be used, or emits that sequence and
685   ;; returns T.
686   (maybe-shrink nil :type function)
687   ;; the function to call to generate the worst case sequence. This is used
688   ;; when nothing else can be condensed.
689   (worst-case-fun nil :type function))
690
691 ;;; This is used internally when we figure out a chooser or alignment doesn't
692 ;;; really need as much space as we initially gave it.
693 (defstruct (filler
694             (:include annotation)
695             (:constructor make-filler (bytes)))
696   ;; the number of bytes of filler here
697   (bytes 0 :type index))
698 \f
699 ;;;; output functions
700
701 ;;; interface: Emit the supplied BYTE to SEGMENT, growing SEGMENT if necessary.
702 (defun emit-byte (segment byte)
703   (declare (type segment segment))
704   ;; We could use DECLARE instead of CHECK-TYPE here, but (1) CMU CL's
705   ;; inspired decision to treat DECLARE as ASSERT by default has not
706   ;; been copied by other compilers, and this code runs in the
707   ;; cross-compilation host Common Lisp, not just CMU CL, and (2)
708   ;; classic CMU CL allowed more things here than this, and I haven't
709   ;; tried to proof-read all the calls to EMIT-BYTE to ensure that
710   ;; they're passing appropriate. -- WHN 19990323
711   (check-type byte possibly-signed-assembly-unit)
712   (vector-push-extend (logand byte assembly-unit-mask)
713                       (segment-buffer segment))
714   (incf (segment-current-posn segment))
715   (values))
716
717 ;;; interface: Output AMOUNT copies of FILL-BYTE to SEGMENT.
718 (defun emit-skip (segment amount &optional (fill-byte 0))
719   (declare (type segment segment)
720            (type index amount))
721   (dotimes (i amount)
722     (emit-byte segment fill-byte))
723   (values))
724
725 ;;; Used to handle the common parts of annotation emision. We just
726 ;;; assign the posn and index of the note and tack it on to the end of
727 ;;; the segment's annotations list.
728 (defun emit-annotation (segment note)
729   (declare (type segment segment)
730            (type annotation note))
731   (when (annotation-posn note)
732     (error "attempt to emit ~S a second time"))
733   (setf (annotation-posn note) (segment-current-posn segment))
734   (setf (annotation-index note) (segment-current-index segment))
735   (let ((last (segment-last-annotation segment))
736         (new (list note)))
737     (setf (segment-last-annotation segment)
738           (if last
739               (setf (cdr last) new)
740               (setf (segment-annotations segment) new))))
741   (values))
742
743 (defun emit-back-patch (segment size function)
744   #!+sb-doc
745   "Note that the instruction stream has to be back-patched when label positions
746    are finally known. SIZE bytes are reserved in SEGMENT, and function will
747    be called with two arguments: the segment and the position. The function
748    should look at the position and the position of any labels it wants to
749    and emit the correct sequence. (And it better be the same size as SIZE).
750    SIZE can be zero, which is useful if you just want to find out where things
751    ended up."
752   (emit-annotation segment (make-back-patch size function))
753   (emit-skip segment size))
754
755 (defun emit-chooser (segment size alignment maybe-shrink worst-case-fun)
756   #!+sb-doc
757   "Note that the instruction stream here depends on the actual positions of
758    various labels, so can't be output until label positions are known. Space
759    is made in SEGMENT for at least SIZE bytes. When all output has been
760    generated, the MAYBE-SHRINK functions for all choosers are called with
761    three arguments: the segment, the position, and a magic value. The MAYBE-
762    SHRINK decides if it can use a shorter sequence, and if so, emits that
763    sequence to the segment and returns T. If it can't do better than the
764    worst case, it should return NIL (without emitting anything). When calling
765    LABEL-POSITION, it should pass it the position and the magic-value it was
766    passed so that LABEL-POSITION can return the correct result. If the chooser
767    never decides to use a shorter sequence, the WORST-CASE-FUN will be called,
768    just like a BACK-PATCH. (See EMIT-BACK-PATCH.)"
769   (declare (type segment segment) (type index size) (type alignment alignment)
770            (type function maybe-shrink worst-case-fun))
771   (let ((chooser (make-chooser size alignment maybe-shrink worst-case-fun)))
772     (emit-annotation segment chooser)
773     (emit-skip segment size)
774     (adjust-alignment-after-chooser segment chooser)))
775
776 ;;; Called in EMIT-CHOOSER and COMPRESS-SEGMENT in order to recompute
777 ;;; the current alignment information in light of this chooser. If the
778 ;;; alignment guaranteed byte the chooser is less then the segments
779 ;;; current alignment, we have to adjust the segments notion of the
780 ;;; current alignment.
781 ;;;
782 ;;; The hard part is recomputing the sync posn, because it's not just
783 ;;; the choosers posn. Consider a chooser that emits either one or
784 ;;; three words. It preserves 8-byte (3 bit) alignments, because the
785 ;;; difference between the two choices is 8 bytes.
786 (defun adjust-alignment-after-chooser (segment chooser)
787   (declare (type segment segment) (type chooser chooser))
788   (let ((alignment (chooser-alignment chooser))
789         (seg-alignment (segment-alignment segment)))
790     (when (< alignment seg-alignment)
791       ;; The chooser might change the alignment of the output. So we
792       ;; have to figure out what the worst case alignment could be.
793       (setf (segment-alignment segment) alignment)
794       (let* ((posn (chooser-posn chooser))
795              (sync-posn (segment-sync-posn segment))
796              (offset (- posn sync-posn))
797              (delta (logand offset (1- (ash 1 alignment)))))
798         (setf (segment-sync-posn segment) (- posn delta)))))
799   (values))
800
801 ;;; Used internally whenever a chooser or alignment decides it doesn't
802 ;;; need as much space as it originally thought.
803 (defun emit-filler (segment bytes)
804   (let ((last (segment-last-annotation segment)))
805     (cond ((and last (filler-p (car last)))
806            (incf (filler-bytes (car last)) bytes))
807           (t
808            (emit-annotation segment (make-filler bytes)))))
809   (incf (segment-current-index segment) bytes)
810   (values))
811
812 ;;; EMIT-LABEL (the interface) basically just expands into this,
813 ;;; supplying the segment and vop.
814 (defun %emit-label (segment vop label)
815   (when (segment-run-scheduler segment)
816     (schedule-pending-instructions segment))
817   (let ((postits (segment-postits segment)))
818     (setf (segment-postits segment) nil)
819     (dolist (postit postits)
820       (emit-back-patch segment 0 postit)))
821   (let ((hook (segment-inst-hook segment)))
822     (when hook
823       (funcall hook segment vop :label label)))
824   (emit-annotation segment label))
825
826 ;;; Called by the ALIGN macro to emit an alignment note. We check to
827 ;;; see if we can guarantee the alignment restriction by just
828 ;;; outputting a fixed number of bytes. If so, we do so. Otherwise, we
829 ;;; create and emit an alignment note.
830 (defun emit-alignment (segment vop bits &optional (fill-byte 0))
831   (when (segment-run-scheduler segment)
832     (schedule-pending-instructions segment))
833   (let ((hook (segment-inst-hook segment)))
834     (when hook
835       (funcall hook segment vop :align bits)))
836   (let ((alignment (segment-alignment segment))
837         (offset (- (segment-current-posn segment)
838                    (segment-sync-posn segment))))
839     (cond ((> bits alignment)
840            ;; We need more bits of alignment. First emit enough noise
841            ;; to get back in sync with alignment, and then emit an
842            ;; alignment note to cover the rest.
843            (let ((slop (logand offset (1- (ash 1 alignment)))))
844              (unless (zerop slop)
845                (emit-skip segment (- (ash 1 alignment) slop) fill-byte)))
846            (let ((size (logand (1- (ash 1 bits))
847                                (lognot (1- (ash 1 alignment))))))
848              (assert (> size 0))
849              (emit-annotation segment (make-alignment bits size fill-byte))
850              (emit-skip segment size fill-byte))
851            (setf (segment-alignment segment) bits)
852            (setf (segment-sync-posn segment) (segment-current-posn segment)))
853           (t
854            ;; The last alignment was more restrictive then this one.
855            ;; So we can just figure out how much noise to emit
856            ;; assuming the last alignment was met.
857            (let* ((mask (1- (ash 1 bits)))
858                   (new-offset (logand (+ offset mask) (lognot mask))))
859              (emit-skip segment (- new-offset offset) fill-byte))
860            ;; But we emit an alignment with size=0 so we can verify
861            ;; that everything works.
862            (emit-annotation segment (make-alignment bits 0 fill-byte)))))
863   (values))
864
865 ;;; Used to find how ``aligned'' different offsets are. Returns the
866 ;;; number of low-order 0 bits, up to MAX-ALIGNMENT.
867 (defun find-alignment (offset)
868   (dotimes (i max-alignment max-alignment)
869     (when (logbitp i offset)
870       (return i))))
871
872 ;;; Emit a postit. The function will be called as a back-patch with
873 ;;; the position the following instruction is finally emitted. Postits
874 ;;; do not interfere at all with scheduling.
875 (defun %emit-postit (segment function)
876   (push function (segment-postits segment))
877   (values))
878 \f
879 ;;;; output compression/position assignment stuff
880
881 ;;; Grovel though all the annotations looking for choosers. When we
882 ;;; find a chooser, invoke the maybe-shrink function. If it returns T,
883 ;;; it output some other byte sequence.
884 (defun compress-output (segment)
885   (dotimes (i 5) ; it better not take more than one or two passes.
886     (let ((delta 0))
887       (setf (segment-alignment segment) max-alignment)
888       (setf (segment-sync-posn segment) 0)
889       (do* ((prev nil)
890             (remaining (segment-annotations segment) next)
891             (next (cdr remaining) (cdr remaining)))
892            ((null remaining))
893         (let* ((note (car remaining))
894                (posn (annotation-posn note)))
895           (unless (zerop delta)
896             (decf posn delta)
897             (setf (annotation-posn note) posn))
898           (cond
899            ((chooser-p note)
900             (setf (segment-current-index segment) (chooser-index note))
901             (setf (segment-current-posn segment) posn)
902             (setf (segment-last-annotation segment) prev)
903             (cond
904              ((funcall (chooser-maybe-shrink note) segment posn delta)
905               ;; It emitted some replacement.
906               (let ((new-size (- (segment-current-index segment)
907                                  (chooser-index note)))
908                     (old-size (chooser-size note)))
909                 (when (> new-size old-size)
910                   (error "~S emitted ~D bytes, but claimed its max was ~D."
911                          note new-size old-size))
912                 (let ((additional-delta (- old-size new-size)))
913                   (when (< (find-alignment additional-delta)
914                            (chooser-alignment note))
915                     (error "~S shrunk by ~D bytes, but claimed that it ~
916                             preserve ~D bits of alignment."
917                            note additional-delta (chooser-alignment note)))
918                   (incf delta additional-delta)
919                   (emit-filler segment additional-delta))
920                 (setf prev (segment-last-annotation segment))
921                 (if prev
922                     (setf (cdr prev) (cdr remaining))
923                     (setf (segment-annotations segment)
924                           (cdr remaining)))))
925              (t
926               ;; The chooser passed on shrinking. Make sure it didn't emit
927               ;; anything.
928               (unless (= (segment-current-index segment) (chooser-index note))
929                 (error "Chooser ~S passed, but not before emitting ~D bytes."
930                        note
931                        (- (segment-current-index segment)
932                           (chooser-index note))))
933               ;; Act like we just emitted this chooser.
934               (let ((size (chooser-size note)))
935                 (incf (segment-current-index segment) size)
936                 (incf (segment-current-posn segment) size))
937               ;; Adjust the alignment accordingly.
938               (adjust-alignment-after-chooser segment note)
939               ;; And keep this chooser for next time around.
940               (setf prev remaining))))
941            ((alignment-p note)
942             (unless (zerop (alignment-size note))
943               ;; Re-emit the alignment, letting it collapse if we know
944               ;; anything more about the alignment guarantees of the
945               ;; segment.
946               (let ((index (alignment-index note)))
947                 (setf (segment-current-index segment) index)
948                 (setf (segment-current-posn segment) posn)
949                 (setf (segment-last-annotation segment) prev)
950                 (emit-alignment segment nil (alignment-bits note)
951                                 (alignment-fill-byte note))
952                 (let* ((new-index (segment-current-index segment))
953                        (size (- new-index index))
954                        (old-size (alignment-size note))
955                        (additional-delta (- old-size size)))
956                   (when (minusp additional-delta)
957                     (error "Alignment ~S needs more space now?  It was ~D, ~
958                             and is ~D now."
959                            note old-size size))
960                   (when (plusp additional-delta)
961                     (emit-filler segment additional-delta)
962                     (incf delta additional-delta)))
963                 (setf prev (segment-last-annotation segment))
964                 (if prev
965                     (setf (cdr prev) (cdr remaining))
966                     (setf (segment-annotations segment)
967                           (cdr remaining))))))
968            (t
969             (setf prev remaining)))))
970       (when (zerop delta)
971         (return))
972       (decf (segment-final-posn segment) delta)))
973   (values))
974
975 ;;; We have run all the choosers we can, so now we have to figure out exactly
976 ;;; how much space each alignment note needs.
977 (defun finalize-positions (segment)
978   (let ((delta 0))
979     (do* ((prev nil)
980           (remaining (segment-annotations segment) next)
981           (next (cdr remaining) (cdr remaining)))
982          ((null remaining))
983       (let* ((note (car remaining))
984              (posn (- (annotation-posn note) delta)))
985         (cond
986          ((alignment-p note)
987           (let* ((bits (alignment-bits note))
988                  (mask (1- (ash 1 bits)))
989                  (new-posn (logand (+ posn mask) (lognot mask)))
990                  (size (- new-posn posn))
991                  (old-size (alignment-size note))
992                  (additional-delta (- old-size size)))
993             (assert (<= 0 size old-size))
994             (unless (zerop additional-delta)
995               (setf (segment-last-annotation segment) prev)
996               (incf delta additional-delta)
997               (setf (segment-current-index segment) (alignment-index note))
998               (setf (segment-current-posn segment) posn)
999               (emit-filler segment additional-delta)
1000               (setf prev (segment-last-annotation segment)))
1001             (if prev
1002                 (setf (cdr prev) next)
1003                 (setf (segment-annotations segment) next))))
1004          (t
1005           (setf (annotation-posn note) posn)
1006           (setf prev remaining)
1007           (setf next (cdr remaining))))))
1008     (unless (zerop delta)
1009       (decf (segment-final-posn segment) delta)))
1010   (values))
1011
1012 ;;; Grovel over segment, filling in any backpatches. If any choosers
1013 ;;; are left over, we need to emit their worst case varient.
1014 (defun process-back-patches (segment)
1015   (do* ((prev nil)
1016         (remaining (segment-annotations segment) next)
1017         (next (cdr remaining) (cdr remaining)))
1018       ((null remaining))
1019     (let ((note (car remaining)))
1020       (flet ((fill-in (function old-size)
1021                (let ((index (annotation-index note))
1022                      (posn (annotation-posn note)))
1023                  (setf (segment-current-index segment) index)
1024                  (setf (segment-current-posn segment) posn)
1025                  (setf (segment-last-annotation segment) prev)
1026                  (funcall function segment posn)
1027                  (let ((new-size (- (segment-current-index segment) index)))
1028                    (unless (= new-size old-size)
1029                      (error "~S emitted ~D bytes, but claimed it was ~D."
1030                             note new-size old-size)))
1031                  (let ((tail (segment-last-annotation segment)))
1032                    (if tail
1033                        (setf (cdr tail) next)
1034                        (setf (segment-annotations segment) next)))
1035                  (setf next (cdr prev)))))
1036         (cond ((back-patch-p note)
1037                (fill-in (back-patch-function note)
1038                         (back-patch-size note)))
1039               ((chooser-p note)
1040                (fill-in (chooser-worst-case-fun note)
1041                         (chooser-size note)))
1042               (t
1043                (setf prev remaining)))))))
1044 \f
1045 ;;;; interface to the rest of the compiler
1046
1047 ;;; This holds the current segment while assembling. Use ASSEMBLE to
1048 ;;; change it.
1049 ;;;
1050 ;;; The double asterisks in the name are intended to suggest that this
1051 ;;; isn't just any old special variable, it's an extra-special
1052 ;;; variable, because sometimes MACROLET is used to bind it. So be
1053 ;;; careful out there..
1054 (defvar **current-segment**)
1055
1056 ;;; Just like **CURRENT-SEGMENT**, except this holds the current vop.
1057 ;;; Used only to keep track of which vops emit which insts.
1058 ;;;
1059 ;;; The double asterisks in the name are intended to suggest that this
1060 ;;; isn't just any old special variable, it's an extra-special
1061 ;;; variable, because sometimes MACROLET is used to bind it. So be
1062 ;;; careful out there..
1063 (defvar **current-vop** nil)
1064
1065 ;;; We also SYMBOL-MACROLET **CURRENT-SEGMENT** to a local holding the
1066 ;;; segment so uses of **CURRENT-SEGMENT** inside the body don't have
1067 ;;; to keep dereferencing the symbol. Given that ASSEMBLE is the only
1068 ;;; interface to **CURRENT-SEGMENT**, we don't have to worry about the
1069 ;;; special value becomming out of sync with the lexical value. Unless
1070 ;;; some bozo closes over it, but nobody does anything like that...
1071 ;;;
1072 ;;; FIXME: The way this macro uses MACROEXPAND internally breaks my
1073 ;;; old assumptions about macros which are needed both in the host and
1074 ;;; the target. (This is more or less the same way that PUSH-IN,
1075 ;;; DELETEF-IN, and DEF-BOOLEAN-ATTRIBUTE break my old assumptions,
1076 ;;; except that they used GET-SETF-EXPANSION instead of MACROEXPAND to
1077 ;;; do the dirty deed.) The quick and dirty "solution" here is the
1078 ;;; same as there: use cut and paste to duplicate the defmacro in a
1079 ;;; (SB!INT:DEF!MACRO FOO (..) .. CL:MACROEXPAND ..) #+SB-XC-HOST
1080 ;;; (DEFMACRO FOO (..) .. SB!XC:MACROEXPAND ..) idiom. This is
1081 ;;; disgusting and unmaintainable, and there are obviously better
1082 ;;; solutions and maybe even good solutions, but I'm disinclined to
1083 ;;; hunt for good solutions until the system works and I can test them
1084 ;;; in isolation.
1085 (sb!int:def!macro assemble ((&optional segment vop &key labels) &body body
1086                             &environment env)
1087   #!+sb-doc
1088   "Execute BODY (as a progn) with SEGMENT as the current segment."
1089   (flet ((label-name-p (thing)
1090            (and thing (symbolp thing))))
1091     (let* ((seg-var (gensym "SEGMENT-"))
1092            (vop-var (gensym "VOP-"))
1093            (visible-labels (remove-if-not #'label-name-p body))
1094            (inherited-labels
1095             (multiple-value-bind (expansion expanded)
1096                 (macroexpand '..inherited-labels.. env)
1097               (if expanded expansion nil)))
1098            (new-labels (append labels
1099                                (set-difference visible-labels
1100                                                inherited-labels)))
1101            (nested-labels (set-difference (append inherited-labels new-labels)
1102                                           visible-labels)))
1103       (when (intersection labels inherited-labels)
1104         (error "duplicate nested labels: ~S"
1105                (intersection labels inherited-labels)))
1106       `(let* ((,seg-var ,(or segment '**current-segment**))
1107               (,vop-var ,(or vop '**current-vop**))
1108               ,@(when segment
1109                   `((**current-segment** ,seg-var)))
1110               ,@(when vop
1111                   `((**current-vop** ,vop-var)))
1112               ,@(mapcar #'(lambda (name)
1113                             `(,name (gen-label)))
1114                         new-labels))
1115          (symbol-macrolet ((**current-segment** ,seg-var)
1116                            (**current-vop** ,vop-var)
1117                            ,@(when (or inherited-labels nested-labels)
1118                                `((..inherited-labels.. ,nested-labels))))
1119            ,@(mapcar #'(lambda (form)
1120                          (if (label-name-p form)
1121                              `(emit-label ,form)
1122                              form))
1123                      body))))))
1124 #+sb-xc-host
1125 (sb!xc:defmacro assemble ((&optional segment vop &key labels)
1126                           &body body
1127                           &environment env)
1128   #!+sb-doc
1129   "Execute BODY (as a progn) with SEGMENT as the current segment."
1130   (flet ((label-name-p (thing)
1131            (and thing (symbolp thing))))
1132     (let* ((seg-var (gensym "SEGMENT-"))
1133            (vop-var (gensym "VOP-"))
1134            (visible-labels (remove-if-not #'label-name-p body))
1135            (inherited-labels
1136             (multiple-value-bind
1137                 (expansion expanded)
1138                 (sb!xc:macroexpand '..inherited-labels.. env)
1139               (if expanded expansion nil)))
1140            (new-labels (append labels
1141                                (set-difference visible-labels
1142                                                inherited-labels)))
1143            (nested-labels (set-difference (append inherited-labels new-labels)
1144                                           visible-labels)))
1145       (when (intersection labels inherited-labels)
1146         (error "duplicate nested labels: ~S"
1147                (intersection labels inherited-labels)))
1148       `(let* ((,seg-var ,(or segment '**current-segment**))
1149               (,vop-var ,(or vop '**current-vop**))
1150               ,@(when segment
1151                   `((**current-segment** ,seg-var)))
1152               ,@(when vop
1153                   `((**current-vop** ,vop-var)))
1154               ,@(mapcar #'(lambda (name)
1155                             `(,name (gen-label)))
1156                         new-labels))
1157          (symbol-macrolet ((**current-segment** ,seg-var)
1158                            (**current-vop** ,vop-var)
1159                            ,@(when (or inherited-labels nested-labels)
1160                                `((..inherited-labels.. ,nested-labels))))
1161            ,@(mapcar #'(lambda (form)
1162                          (if (label-name-p form)
1163                              `(emit-label ,form)
1164                              form))
1165                      body))))))
1166
1167 (defmacro inst (&whole whole instruction &rest args &environment env)
1168   #!+sb-doc
1169   "Emit the specified instruction to the current segment."
1170   (let ((inst (gethash (symbol-name instruction) *assem-instructions*)))
1171     (cond ((null inst)
1172            (error "unknown instruction: ~S" instruction))
1173           ((functionp inst)
1174            (funcall inst (cdr whole) env))
1175           (t
1176            `(,inst **current-segment** **current-vop** ,@args)))))
1177
1178 ;;; Note: The need to capture SYMBOL-MACROLET bindings of
1179 ;;; **CURRENT-SEGMENT* and **CURRENT-VOP** prevents this from being an
1180 ;;; ordinary function.
1181 (defmacro emit-label (label)
1182   #!+sb-doc
1183   "Emit LABEL at this location in the current segment."
1184   `(%emit-label **current-segment** **current-vop** ,label))
1185
1186 ;;; Note: The need to capture SYMBOL-MACROLET bindings of
1187 ;;; **CURRENT-SEGMENT* prevents this from being an ordinary function.
1188 (defmacro emit-postit (function)
1189   `(%emit-postit **current-segment** ,function))
1190
1191 ;;; Note: The need to capture SYMBOL-MACROLET bindings of
1192 ;;; **CURRENT-SEGMENT* and **CURRENT-VOP** prevents this from being an
1193 ;;; ordinary function.
1194 (defmacro align (bits &optional (fill-byte 0))
1195   #!+sb-doc
1196   "Emit an alignment restriction to the current segment."
1197   `(emit-alignment **current-segment** **current-vop** ,bits ,fill-byte))
1198 ;;; FIXME: By analogy with EMIT-LABEL and EMIT-POSTIT, this should be
1199 ;;; called EMIT-ALIGNMENT, and the function that it calls should be
1200 ;;; called %EMIT-ALIGNMENT.
1201
1202 (defun label-position (label &optional if-after delta)
1203   #!+sb-doc
1204   "Return the current position for LABEL. Chooser maybe-shrink functions
1205    should supply IF-AFTER and DELTA in order to ensure correct results."
1206   (let ((posn (label-posn label)))
1207     (if (and if-after (> posn if-after))
1208         (- posn delta)
1209         posn)))
1210
1211 (defun append-segment (segment other-segment)
1212   #!+sb-doc
1213   "Append OTHER-SEGMENT to the end of SEGMENT. Don't use OTHER-SEGMENT
1214    for anything after this."
1215   (when (segment-run-scheduler segment)
1216     (schedule-pending-instructions segment))
1217   (let ((postits (segment-postits segment)))
1218     (setf (segment-postits segment) (segment-postits other-segment))
1219     (dolist (postit postits)
1220       (emit-back-patch segment 0 postit)))
1221   #!-x86 (emit-alignment segment nil max-alignment)
1222   #!+x86 (emit-alignment segment nil max-alignment #x90)
1223   (let ((segment-current-index-0 (segment-current-index segment))
1224         (segment-current-posn-0  (segment-current-posn  segment)))
1225     (incf (segment-current-index segment)
1226           (segment-current-index other-segment))
1227     (replace (segment-buffer segment)
1228              (segment-buffer other-segment)
1229              :start1 segment-current-index-0)
1230     (setf (segment-buffer other-segment) nil) ; to prevent accidental reuse
1231     (incf (segment-current-posn segment)
1232           (segment-current-posn other-segment))
1233     (let ((other-annotations (segment-annotations other-segment)))
1234       (when other-annotations
1235         (dolist (note other-annotations)
1236           (incf (annotation-index note) segment-current-index-0)
1237           (incf (annotation-posn note) segment-current-posn-0))
1238         ;; This SEGMENT-LAST-ANNOTATION code is confusing. Is it really
1239         ;; worth enough in efficiency to justify it? -- WHN 19990322
1240         (let ((last (segment-last-annotation segment)))
1241           (if last
1242             (setf (cdr last) other-annotations)
1243             (setf (segment-annotations segment) other-annotations)))
1244         (setf (segment-last-annotation segment)
1245               (segment-last-annotation other-segment)))))
1246   (values))
1247
1248 (defun finalize-segment (segment)
1249   #!+sb-doc
1250   "Do any final processing of SEGMENT and return the total number of bytes
1251    covered by this segment."
1252   (when (segment-run-scheduler segment)
1253     (schedule-pending-instructions segment))
1254   (setf (segment-run-scheduler segment) nil)
1255   (let ((postits (segment-postits segment)))
1256     (setf (segment-postits segment) nil)
1257     (dolist (postit postits)
1258       (emit-back-patch segment 0 postit)))
1259   (setf (segment-final-index segment) (segment-current-index segment))
1260   (setf (segment-final-posn segment) (segment-current-posn segment))
1261   (setf (segment-inst-hook segment) nil)
1262   (compress-output segment)
1263   (finalize-positions segment)
1264   (process-back-patches segment)
1265   (segment-final-posn segment))
1266
1267 ;;; Call FUNCTION on all the stuff accumulated in SEGMENT. FUNCTION
1268 ;;; should accept a single vector argument. It will be called zero or
1269 ;;; more times on vectors of the appropriate byte type. The
1270 ;;; concatenation of the vector arguments from all the calls is the
1271 ;;; contents of SEGMENT.
1272 ;;;
1273 ;;; KLUDGE: This implementation is sort of slow and gross, calling
1274 ;;; FUNCTION repeatedly and consing a fresh vector for its argument
1275 ;;; each time. It might be possible to make a more efficient version
1276 ;;; by making FINALIZE-SEGMENT do all the compacting currently done by
1277 ;;; this function: then this function could become trivial and fast,
1278 ;;; calling FUNCTION once on the entire compacted segment buffer. --
1279 ;;; WHN 19990322
1280 (defun on-segment-contents-vectorly (segment function)
1281   (let ((buffer (segment-buffer segment))
1282         (i0 0))
1283     (flet ((frob (i0 i1)
1284              (when (< i0 i1)
1285                (funcall function (subseq buffer i0 i1)))))
1286       (dolist (note (segment-annotations segment))
1287         (when (filler-p note)
1288           (let ((i1 (filler-index note)))
1289             (frob i0 i1)
1290             (setf i0 (+ i1 (filler-bytes note))))))
1291       (frob i0 (segment-final-index segment))))
1292   (values))
1293
1294 ;;; Write the code accumulated in SEGMENT to STREAM, and return the
1295 ;;; number of bytes written.
1296 (defun write-segment-contents (segment stream)
1297   (let ((result 0))
1298     (declare (type index result))
1299     (on-segment-contents-vectorly segment
1300                                   (lambda (v)
1301                                     (declare (type (vector assembly-unit) v))
1302                                     (incf result (length v))
1303                                     (write-sequence v stream)))
1304     result))
1305 \f
1306 ;;;; interface to the instruction set definition
1307
1308 ;;; Define a function named NAME that merges its arguments into a
1309 ;;; single integer and then emits the bytes of that integer in the
1310 ;;; correct order based on the endianness of the target-backend.
1311 (defmacro define-bitfield-emitter (name total-bits &rest byte-specs)
1312   (sb!int:collect ((arg-names) (arg-types))
1313     (let* ((total-bits (eval total-bits))
1314            (overall-mask (ash -1 total-bits))
1315            (num-bytes (multiple-value-bind (quo rem)
1316                           (truncate total-bits assembly-unit-bits)
1317                         (unless (zerop rem)
1318                           (error "~D isn't an even multiple of ~D."
1319                                  total-bits assembly-unit-bits))
1320                         quo))
1321            (bytes (make-array num-bytes :initial-element nil))
1322            (segment-arg (gensym "SEGMENT-")))
1323       (dolist (byte-spec-expr byte-specs)
1324         (let* ((byte-spec (eval byte-spec-expr))
1325                (byte-size (byte-size byte-spec))
1326                (byte-posn (byte-position byte-spec))
1327                (arg (gensym (format nil "~:@(ARG-FOR-~S-~)" byte-spec-expr))))
1328           (when (ldb-test (byte byte-size byte-posn) overall-mask)
1329             (error "The byte spec ~S either overlaps another byte spec, or ~
1330                     extends past the end."
1331                    byte-spec-expr))
1332           (setf (ldb byte-spec overall-mask) -1)
1333           (arg-names arg)
1334           (arg-types `(type (integer ,(ash -1 (1- byte-size))
1335                                      ,(1- (ash 1 byte-size)))
1336                             ,arg))
1337           (multiple-value-bind (start-byte offset)
1338               (floor byte-posn assembly-unit-bits)
1339             (let ((end-byte (floor (1- (+ byte-posn byte-size))
1340                                    assembly-unit-bits)))
1341               (flet ((maybe-ash (expr offset)
1342                        (if (zerop offset)
1343                            expr
1344                            `(ash ,expr ,offset))))
1345                 (declare (inline maybe-ash))
1346                 (cond ((zerop byte-size))
1347                       ((= start-byte end-byte)
1348                        (push (maybe-ash `(ldb (byte ,byte-size 0) ,arg)
1349                                         offset)
1350                              (svref bytes start-byte)))
1351                       (t
1352                        (push (maybe-ash
1353                               `(ldb (byte ,(- assembly-unit-bits offset) 0)
1354                                     ,arg)
1355                               offset)
1356                              (svref bytes start-byte))
1357                        (do ((index (1+ start-byte) (1+ index)))
1358                            ((>= index end-byte))
1359                          (push
1360                           `(ldb (byte ,assembly-unit-bits
1361                                       ,(- (* assembly-unit-bits
1362                                              (- index start-byte))
1363                                           offset))
1364                                 ,arg)
1365                           (svref bytes index)))
1366                        (let ((len (rem (+ byte-size offset)
1367                                        assembly-unit-bits)))
1368                          (push
1369                           `(ldb (byte ,(if (zerop len)
1370                                            assembly-unit-bits
1371                                            len)
1372                                       ,(- (* assembly-unit-bits
1373                                              (- end-byte start-byte))
1374                                           offset))
1375                                 ,arg)
1376                           (svref bytes end-byte))))))))))
1377       (unless (= overall-mask -1)
1378         (error "There are holes."))
1379       (let ((forms nil))
1380         (dotimes (i num-bytes)
1381           (let ((pieces (svref bytes i)))
1382             (assert pieces)
1383             (push `(emit-byte ,segment-arg
1384                               ,(if (cdr pieces)
1385                                    `(logior ,@pieces)
1386                                    (car pieces)))
1387                   forms)))
1388         `(defun ,name (,segment-arg ,@(arg-names))
1389            (declare (type segment ,segment-arg) ,@(arg-types))
1390            ,@(ecase sb!c:*backend-byte-order*
1391                (:little-endian (nreverse forms))
1392                (:big-endian forms))
1393            ',name)))))
1394
1395 (defun grovel-lambda-list (lambda-list vop-var)
1396   (let ((segment-name (car lambda-list))
1397         (vop-var (or vop-var (gensym "VOP-"))))
1398     (sb!int:collect ((new-lambda-list))
1399       (new-lambda-list segment-name)
1400       (new-lambda-list vop-var)
1401       (labels
1402           ((grovel (state lambda-list)
1403              (when lambda-list
1404                (let ((param (car lambda-list)))
1405                  (cond
1406                   ((member param lambda-list-keywords)
1407                    (new-lambda-list param)
1408                    (grovel param (cdr lambda-list)))
1409                   (t
1410                    (ecase state
1411                      ((nil)
1412                       (new-lambda-list param)
1413                       `(cons ,param ,(grovel state (cdr lambda-list))))
1414                      (&optional
1415                       (multiple-value-bind (name default supplied-p)
1416                           (if (consp param)
1417                               (values (first param)
1418                                       (second param)
1419                                       (or (third param)
1420                                           (gensym "SUPPLIED-P-")))
1421                               (values param nil (gensym "SUPPLIED-P-")))
1422                         (new-lambda-list (list name default supplied-p))
1423                         `(and ,supplied-p
1424                               (cons ,(if (consp name)
1425                                          (second name)
1426                                          name)
1427                                     ,(grovel state (cdr lambda-list))))))
1428                      (&key
1429                       (multiple-value-bind (name default supplied-p)
1430                           (if (consp param)
1431                               (values (first param)
1432                                       (second param)
1433                                       (or (third param)
1434                                           (gensym "SUPPLIED-P-")))
1435                               (values param nil (gensym "SUPPLIED-P-")))
1436                         (new-lambda-list (list name default supplied-p))
1437                         (multiple-value-bind (key var)
1438                             (if (consp name)
1439                                 (values (first name) (second name))
1440                                 (values (intern (symbol-name name) :keyword)
1441                                         name))
1442                           `(append (and ,supplied-p (list ',key ,var))
1443                                    ,(grovel state (cdr lambda-list))))))
1444                      (&rest
1445                       (new-lambda-list param)
1446                       (grovel state (cdr lambda-list))
1447                       param))))))))
1448         (let ((reconstructor (grovel nil (cdr lambda-list))))
1449           (values (new-lambda-list)
1450                   segment-name
1451                   vop-var
1452                   reconstructor))))))
1453
1454 (defun extract-nths (index glue list-of-lists-of-lists)
1455   (mapcar #'(lambda (list-of-lists)
1456               (cons glue
1457                     (mapcar #'(lambda (list)
1458                                 (nth index list))
1459                             list-of-lists)))
1460           list-of-lists-of-lists))
1461
1462 (defmacro define-instruction (name lambda-list &rest options)
1463   (let* ((sym-name (symbol-name name))
1464          (defun-name (sb!int:symbolicate sym-name "-INST-EMITTER"))
1465          (vop-var nil)
1466          (postits (gensym "POSTITS-"))
1467          (emitter nil)
1468          (decls nil)
1469          (attributes nil)
1470          (cost nil)
1471          (dependencies nil)
1472          (delay nil)
1473          (pinned nil)
1474          (pdefs nil))
1475     (sb!int:/noshow "entering DEFINE-INSTRUCTION" name lambda-list options)
1476     (dolist (option-spec options)
1477       (sb!int:/noshow option-spec)
1478       (multiple-value-bind (option args)
1479           (if (consp option-spec)
1480               (values (car option-spec) (cdr option-spec))
1481               (values option-spec nil))
1482         (sb!int:/noshow option args)
1483         (case option
1484           (:emitter
1485            (when emitter
1486              (error "You can only specify :EMITTER once per instruction."))
1487            (setf emitter args))
1488           (:declare
1489            (setf decls (append decls args)))
1490           (:attributes
1491            (setf attributes (append attributes args)))
1492           (:cost
1493            (setf cost (first args)))
1494           (:dependencies
1495            (setf dependencies (append dependencies args)))
1496           (:delay
1497            (when delay
1498              (error "You can only specify :DELAY once per instruction."))
1499            (setf delay args))
1500           (:pinned
1501            (setf pinned t))
1502           (:vop-var
1503            (if vop-var
1504                (error "You can only specify :VOP-VAR once per instruction.")
1505                (setf vop-var (car args))))
1506           (:printer
1507            (push (eval `(list (multiple-value-list
1508                                ,(sb!disassem:gen-printer-def-forms-def-form
1509                                  name
1510                                  (cdr option-spec)))))
1511                  pdefs))
1512           (:printer-list
1513            ;; same as :PRINTER, but is EVALed first, and is a list of
1514            ;; printers
1515            (push
1516             (eval
1517              `(eval
1518                `(list ,@(mapcar #'(lambda (printer)
1519                                     `(multiple-value-list
1520                                       ,(sb!disassem:gen-printer-def-forms-def-form
1521                                         ',name printer nil)))
1522                                 ,(cadr option-spec)))))
1523             pdefs))
1524           (t
1525            (error "unknown option: ~S" option)))))
1526     (sb!int:/noshow "done processing options")
1527     (setf pdefs (nreverse pdefs))
1528     (multiple-value-bind
1529         (new-lambda-list segment-name vop-name arg-reconstructor)
1530         (grovel-lambda-list lambda-list vop-var)
1531       (sb!int:/noshow new-lambda-list segment-name vop-name arg-reconstructor)
1532       (push `(let ((hook (segment-inst-hook ,segment-name)))
1533                (when hook
1534                  (funcall hook ,segment-name ,vop-name ,sym-name
1535                           ,arg-reconstructor)))
1536             emitter)
1537       (push `(dolist (postit ,postits)
1538                (emit-back-patch ,segment-name 0 postit))
1539             emitter)
1540       (unless cost (setf cost 1))
1541       #!+sb-dyncount
1542       (push `(when (segment-collect-dynamic-statistics ,segment-name)
1543                (let* ((info (sb!c:ir2-component-dyncount-info
1544                              (sb!c:component-info
1545                               sb!c:*component-being-compiled*)))
1546                       (costs (sb!c:dyncount-info-costs info))
1547                       (block-number (sb!c:block-number
1548                                      (sb!c:ir2-block-block
1549                                       (sb!c:vop-block ,vop-name)))))
1550                  (incf (aref costs block-number) ,cost)))
1551             emitter)
1552       (when *assem-scheduler-p*
1553         (if pinned
1554             (setf emitter
1555                   `((when (segment-run-scheduler ,segment-name)
1556                       (schedule-pending-instructions ,segment-name))
1557                     ,@emitter))
1558             (let ((flet-name
1559                    (gensym (concatenate 'string "EMIT-" sym-name "-INST-")))
1560                   (inst-name (gensym "INST-")))
1561               (setf emitter `((flet ((,flet-name (,segment-name)
1562                                        ,@emitter))
1563                                 (if (segment-run-scheduler ,segment-name)
1564                                     (let ((,inst-name
1565                                            (make-instruction
1566                                             (incf (segment-inst-number
1567                                                    ,segment-name))
1568                                             #',flet-name
1569                                             (instruction-attributes
1570                                              ,@attributes)
1571                                             (progn ,@delay))))
1572                                       ,@(when dependencies
1573                                           `((note-dependencies
1574                                                 (,segment-name ,inst-name)
1575                                               ,@dependencies)))
1576                                       (queue-inst ,segment-name ,inst-name))
1577                                     (,flet-name ,segment-name))))))))
1578       `(progn
1579          (defun ,defun-name ,new-lambda-list
1580            ,@(when decls
1581                `((declare ,@decls)))
1582            (let ((,postits (segment-postits ,segment-name)))
1583              (setf (segment-postits ,segment-name) nil)
1584              (symbol-macrolet
1585                  (;; Apparently this binding is intended to keep
1586                   ;; anyone from accidentally using
1587                   ;; **CURRENT-SEGMENT** within the body of the
1588                   ;; emitter. The error message sorta suggests that
1589                   ;; this can happen accidentally by including one
1590                   ;; emitter inside another. But I dunno.. -- WHN
1591                   ;; 19990323
1592                   (**current-segment**
1593                    ;; FIXME: I can't see why we have to use
1594                    ;;   (MACROLET ((LOSE () (ERROR ..))) (LOSE))
1595                    ;; instead of just (ERROR "..") here.
1596                    (macrolet ((lose ()
1597                                 (error "You can't use INST without an ~
1598                                         ASSEMBLE inside emitters.")))
1599                      (lose))))
1600                ,@emitter))
1601            (values))
1602          (eval-when (:compile-toplevel :load-toplevel :execute)
1603            (%define-instruction ,sym-name ',defun-name))
1604          ,@(extract-nths 1 'progn pdefs)
1605          ,@(when pdefs
1606              `((sb!disassem:install-inst-flavors
1607                 ',name
1608                 (append ,@(extract-nths 0 'list pdefs)))))))))
1609
1610 (defmacro define-instruction-macro (name lambda-list &body body)
1611   (let ((whole (gensym "WHOLE-"))
1612         (env (gensym "ENV-")))
1613     (multiple-value-bind (body local-defs)
1614         (sb!kernel:parse-defmacro lambda-list
1615                                   whole
1616                                   body
1617                                   name
1618                                   'instruction-macro
1619                                   :environment env)
1620       `(eval-when (:compile-toplevel :load-toplevel :execute)
1621          (%define-instruction ,(symbol-name name)
1622                               #'(lambda (,whole ,env)
1623                                   ,@local-defs
1624                                   (block ,name
1625                                     ,body)))))))
1626
1627 (defun %define-instruction (name defun)
1628   (setf (gethash name *assem-instructions*) defun)
1629   name)