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