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