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