0.6.11.13:
[sbcl.git] / src / compiler / disassem.lisp
1 ;;;; machine-independent disassembler
2
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
5 ;;;;
6 ;;;; This software is derived from the CMU CL system, which was
7 ;;;; written at Carnegie Mellon University and released into the
8 ;;;; public domain. The software is in the public domain and is
9 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
10 ;;;; files for more information.
11
12 (in-package "SB!DISASSEM")
13 \f
14 ;;; types and defaults
15
16 (defconstant label-column-width 7)
17
18 (deftype text-width () '(integer 0 1000))
19 (deftype alignment () '(integer 0 64))
20 (deftype offset () '(signed-byte 24))
21 (deftype address () '(unsigned-byte 32))
22 (deftype length () '(unsigned-byte 24))
23 (deftype column () '(integer 0 1000))
24
25 (defconstant max-filtered-value-index 32)
26 (deftype filtered-value-index ()
27   `(integer 0 ,max-filtered-value-index))
28 (deftype filtered-value-vector ()
29   `(simple-array t (,max-filtered-value-index)))
30 \f
31 ;;;; disassembly parameters
32
33 ;;; instructions
34 (defvar *disassem-insts* (make-hash-table :test 'eq))
35 (declaim (type hash-table *disassem-insts*))
36
37 (defvar *disassem-inst-space* nil)
38 (declaim (type (or null inst-space) *disassem-inst-space*))
39
40 ;;; minimum alignment of instructions, in bytes
41 (defvar *disassem-inst-alignment-bytes* sb!vm:word-bytes)
42 (declaim (type alignment *disassem-inst-alignment-bytes*))
43
44 (defvar *disassem-location-column-width* 8)
45 (declaim (type text-width *disassem-location-column-width*))
46
47 ;;; the width of the column in which instruction-names are printed. A
48 ;;; value of zero gives the effect of not aligning the arguments at
49 ;;; all.
50 (defvar *disassem-opcode-column-width* 6)
51 (declaim (type text-width *disassem-opcode-column-width*))
52
53 (defvar *disassem-note-column* 45
54   #!+sb-doc
55   "The column in which end-of-line comments for notes are started.")
56
57 ;;; the old CMU CL code to set the CMU CL disassembly parameters
58 #|
59 (defmacro set-disassem-params (&rest args)
60   #!+sb-doc
61   "Specify global disassembler params. &KEY arguments include:
62
63   :INSTRUCTION-ALIGNMENT number
64       Minimum alignment of instructions, in bits.
65
66   :ADDRESS-SIZE number
67       Size of a machine address, in bits.
68
69   :OPCODE-COLUMN-WIDTH
70       Width of the column used for printing the opcode portion of the
71       instruction, or NIL to use the default."
72   (gen-preamble-form args))
73
74 (defun gen-preamble-form (args)
75   #!+sb-doc
76   "Generate a form to specify global disassembler params. See the
77   documentation for SET-DISASSEM-PARAMS for more info."
78   (destructuring-bind
79       (&key instruction-alignment
80             address-size
81             (opcode-column-width nil opcode-column-width-p))
82       args
83     `(progn
84        (eval-when (:compile-toplevel :execute)
85          ;; these are not in the params because they only exist at compile time
86          (defparameter ,(format-table-name) (make-hash-table))
87          (defparameter ,(arg-type-table-name) nil)
88          (defparameter ,(function-cache-name) (make-function-cache)))
89        (let ((params
90               (or sb!c:*backend-disassem-params*
91                   (setf sb!c:*backend-disassem-params* (make-params)))))
92          (declare (ignorable params))
93          ,(when instruction-alignment
94             `(setf (params-instruction-alignment params)
95                    (bits-to-bytes ,instruction-alignment)))
96          ,(when address-size
97             `(setf (params-location-column-width params)
98                    (* 2 ,address-size)))
99          ,(when opcode-column-width-p
100             `(setf (params-opcode-column-width params) ,opcode-column-width))
101          'disassem-params))))
102 |#
103 \f
104 ;;;; cached functions
105
106 (defstruct (function-cache (:copier nil))
107   (printers nil :type list)
108   (labellers nil :type list)
109   (prefilters nil :type list))
110
111 (defvar *disassem-function-cache* (make-function-cache))
112 (declaim (type function-cache *disassem-function-cache*))
113 \f
114 ;;;; A DCHUNK contains the bits we look at to decode an
115 ;;;; instruction.
116 ;;;; I tried to keep this abstract so that if using integers > the machine
117 ;;;; word size conses too much, it can be changed to use bit-vectors or
118 ;;;; something.
119 ;;;;
120 ;;;; KLUDGE: It's not clear that using bit-vectors would be any more efficient.
121 ;;;; Perhaps the abstraction could go away. -- WHN 19991124
122
123 #!-sb-fluid
124 (declaim (inline dchunk-or dchunk-and dchunk-clear dchunk-not
125                  dchunk-make-mask dchunk-make-field
126                  sap-ref-dchunk
127                  dchunk-extract
128                  dchunk=
129                  dchunk-count-bits))
130
131 (defconstant dchunk-bits 32)
132
133 (deftype dchunk ()
134   `(unsigned-byte ,dchunk-bits))
135 (deftype dchunk-index ()
136   `(integer 0 ,dchunk-bits))
137
138 (defconstant dchunk-zero 0)
139 (defconstant dchunk-one #xFFFFFFFF)
140
141 (defun dchunk-extract (from pos)
142   (declare (type dchunk from))
143   (the dchunk (ldb pos (the dchunk from))))
144
145 (defmacro dchunk-copy (x)
146   `(the dchunk ,x))
147
148 (defun dchunk-or (to from)
149   (declare (type dchunk to from))
150   (the dchunk (logior to from)))
151 (defun dchunk-and (to from)
152   (declare (type dchunk to from))
153   (the dchunk (logand to from)))
154 (defun dchunk-clear (to from)
155   (declare (type dchunk to from))
156   (the dchunk (logandc2 to from)))
157 (defun dchunk-not (from)
158   (declare (type dchunk from))
159   (the dchunk (logand dchunk-one (lognot from))))
160
161 (defmacro dchunk-andf (to from)
162   `(setf ,to (dchunk-and ,to ,from)))
163 (defmacro dchunk-orf (to from)
164   `(setf ,to (dchunk-or ,to ,from)))
165 (defmacro dchunk-clearf (to from)
166   `(setf ,to (dchunk-clear ,to ,from)))
167
168 (defun dchunk-make-mask (pos)
169   (the dchunk (mask-field pos -1)))
170 (defun dchunk-make-field (pos value)
171   (the dchunk (dpb value pos 0)))
172
173 (defmacro make-dchunk (value)
174   `(the dchunk ,value))
175
176 (defun sap-ref-dchunk (sap byte-offset byte-order)
177   (declare (type sb!sys:system-area-pointer sap)
178            (type offset byte-offset)
179            (optimize (speed 3) (safety 0)))
180   (the dchunk
181        (if (eq byte-order :big-endian)
182            (+ (ash (sb!sys:sap-ref-8 sap byte-offset) 24)
183               (ash (sb!sys:sap-ref-8 sap (+ 1 byte-offset)) 16)
184               (ash (sb!sys:sap-ref-8 sap (+ 2 byte-offset)) 8)
185               (sb!sys:sap-ref-8 sap (+ 3 byte-offset)))
186            (+ (sb!sys:sap-ref-8 sap byte-offset)
187               (ash (sb!sys:sap-ref-8 sap (+ 1 byte-offset)) 8)
188               (ash (sb!sys:sap-ref-8 sap (+ 2 byte-offset)) 16)
189               (ash (sb!sys:sap-ref-8 sap (+ 3 byte-offset)) 24)))))
190
191 (defun dchunk-corrected-extract (from pos unit-bits byte-order)
192   (declare (type dchunk from))
193   (if (eq byte-order :big-endian)
194       (ldb (byte (byte-size pos)
195                  (+ (byte-position pos) (- dchunk-bits unit-bits)))
196            (the dchunk from))
197       (ldb pos (the dchunk from))))
198
199 (defmacro dchunk-insertf (place pos value)
200   `(setf ,place (the dchunk (dpb ,value ,pos (the dchunk,place)))))
201
202 (defun dchunk= (x y)
203   (declare (type dchunk x y))
204   (= x y))
205 (defmacro dchunk-zerop (x)
206   `(dchunk= ,x dchunk-zero))
207
208 (defun dchunk-strict-superset-p (sup sub)
209   (and (zerop (logandc2 sub sup))
210        (not (zerop (logandc2 sup sub)))))
211
212 (defun dchunk-count-bits (x)
213   (declare (type dchunk x))
214   (logcount x))
215 \f
216 (defstruct (instruction (:conc-name inst-)
217                         (:constructor
218                          make-instruction (name
219                                            format-name
220                                            print-name
221                                            length
222                                            mask id
223                                            printer
224                                            labeller prefilter control))
225                         (:copier nil))
226   (name nil :type (or symbol string))
227   (format-name nil :type (or symbol string))
228
229   (mask dchunk-zero :type dchunk)       ; bits in the inst that are constant
230   (id dchunk-zero :type dchunk)         ; value of those constant bits
231
232   (length 0 :type length)               ; in bytes
233
234   (print-name nil :type symbol)
235
236   ;; disassembly functions
237   (prefilter nil :type (or null function))
238   (labeller nil :type (or null function))
239   (printer (required-argument) :type (or null function))
240   (control nil :type (or null function))
241
242   ;; instructions that are the same as this instruction but with more
243   ;; constraints
244   (specializers nil :type list))
245 (def!method print-object ((inst instruction) stream)
246   (print-unreadable-object (inst stream :type t :identity t)
247     (format stream "~A(~A)" (inst-name inst) (inst-format-name inst))))
248 \f
249 ;;;; an instruction space holds all known machine instructions in a form that
250 ;;;; can be easily searched
251
252 (defstruct (inst-space (:conc-name ispace-)
253                        (:copier nil))
254   (valid-mask dchunk-zero :type dchunk) ; applies to *children*
255   (choices nil :type list))
256 (def!method print-object ((ispace inst-space) stream)
257   (print-unreadable-object (ispace stream :type t :identity t)))
258
259 (defstruct (inst-space-choice (:conc-name ischoice-)
260                               (:copier nil))
261   (common-id dchunk-zero :type dchunk)  ; applies to *parent's* mask
262   (subspace (required-argument) :type (or inst-space instruction)))
263 \f
264 ;;;; These are the kind of values we can compute for an argument, and
265 ;;;; how to compute them. The :CHECKER functions make sure that a given
266 ;;;; argument is compatible with another argument for a given use.
267
268 (defvar *arg-form-kinds* nil)
269
270 (defstruct (arg-form-kind (:copier nil))
271   (names nil :type list)
272   (producer (required-argument) :type function)
273   (checker (required-argument) :type function))
274
275 (defun arg-form-kind-or-lose (kind)
276   (or (getf *arg-form-kinds* kind)
277       (pd-error "unknown arg-form kind ~S" kind)))
278
279 (defun find-arg-form-producer (kind)
280   (arg-form-kind-producer (arg-form-kind-or-lose kind)))
281 (defun find-arg-form-checker (kind)
282   (arg-form-kind-checker (arg-form-kind-or-lose kind)))
283
284 (defun canonicalize-arg-form-kind (kind)
285   (car (arg-form-kind-names (arg-form-kind-or-lose kind))))
286 \f
287 ;;;; only used during compilation of the instructions for a backend
288 ;;;;
289 ;;;; FIXME: If only used then, isn't there some way we could do
290 ;;;; EVAL-WHEN tricks to keep this stuff from appearing in the target
291 ;;;; system?
292
293 (defvar *disassem-inst-formats* (make-hash-table))
294 (defvar *disassem-arg-types* nil)
295 (defvar *disassem-function-cache* (make-function-cache))
296
297 (defstruct (argument (:conc-name arg-))
298   (name nil :type symbol)
299   (fields nil :type list)
300
301   (value nil :type (or list integer))
302   (sign-extend-p nil :type (member t nil))
303
304   ;; position in a vector of prefiltered values
305   (position 0 :type fixnum)
306
307   ;; functions to use
308   (printer nil)
309   (prefilter nil)
310   (use-label nil))
311
312 (defstruct (instruction-format (:conc-name format-)
313                                (:copier nil))
314   (name nil)
315   (args nil :type list)
316
317   (length 0 :type length)               ; in bytes
318
319   (default-printer nil :type list))
320 \f
321 ;;; A FUNSTATE holds the state of any arguments used in a disassembly
322 ;;; function.
323 (defstruct (funstate (:conc-name funstate-)
324                      (:constructor %make-funstate)
325                      (:copier nil))
326   (args nil :type list)
327   (arg-temps nil :type list))           ; See below.
328
329 (defun make-funstate (args)
330   ;; give the args a position
331   (let ((i 0))
332     (dolist (arg args)
333       (setf (arg-position arg) i)
334       (incf i)))
335   (%make-funstate :args args))
336
337 (defun funstate-compatible-p (funstate args)
338   (every #'(lambda (this-arg-temps)
339              (let* ((old-arg (car this-arg-temps))
340                     (new-arg (find (arg-name old-arg) args :key #'arg-name)))
341                (and new-arg
342                     (every #'(lambda (this-kind-temps)
343                                (funcall (find-arg-form-checker
344                                          (car this-kind-temps))
345                                         new-arg
346                                         old-arg))
347                            (cdr this-arg-temps)))))
348          (funstate-arg-temps funstate)))
349
350 (defun arg-or-lose (name funstate)
351   (let ((arg (find name (funstate-args funstate) :key #'arg-name)))
352     (when (null arg)
353       (pd-error "unknown argument ~S" name))
354     arg))
355 \f
356 ;;;; Since we can't include some values in compiled output as they are
357 ;;;; (notably functions), we sometimes use a VALSRC structure to keep track of
358 ;;;; the source from which they were derived.
359
360 (defstruct (valsrc (:constructor %make-valsrc)
361                    (:copier nil))
362   (value nil)
363   (source nil))
364
365 (defun make-valsrc (value source)
366   (cond ((equal value source)
367          source)
368         ((and (listp value) (eq (car value) 'function))
369          value)
370         (t
371          (%make-valsrc :value value :source source))))
372
373 ;;; machinery to provide more meaningful error messages during compilation
374 (defvar *current-instruction-flavor* nil)
375 (defun pd-error (fmt &rest args)
376   (if *current-instruction-flavor*
377       (error "~@<in printer-definition for ~S(~S): ~3I~:_~?~:>"
378              (car *current-instruction-flavor*)
379              (cdr *current-instruction-flavor*)
380              fmt args)
381       (apply #'error fmt args)))
382
383 ;;; FIXME:
384 ;;;  1. This should become a utility in SB!IMPL.
385 ;;;  2. Arrays are self-evaluating too.
386 (defun self-evaluating-p (x)
387   (typecase x
388     (null t)
389     (keyword t)
390     (symbol (eq x t))
391     (cons nil)
392     (t t)))
393
394 (defun maybe-quote (evalp form)
395   (if (or evalp (self-evaluating-p form)) form `',form))
396
397 ;;; detect things that obviously don't need wrapping, like variable-refs and
398 ;;; #'function
399 (defun doesnt-need-wrapping-p (form)
400   (or (symbolp form)
401       (and (listp form)
402            (eq (car form) 'function)
403            (symbolp (cadr form)))))
404
405 (defun make-wrapper (form arg-name funargs prefix)
406   (if (and (listp form)
407            (eq (car form) 'function))
408       ;; a function def
409       (let ((wrapper-name (symbolicate prefix "-" arg-name "-WRAPPER"))
410             (wrapper-args (make-gensym-list (length funargs))))
411         (values `#',wrapper-name
412                 `(defun ,wrapper-name ,wrapper-args
413                    (funcall ,form ,@wrapper-args))))
414       ;; something else
415       (let ((wrapper-name (symbolicate "*" prefix "-" arg-name "-WRAPPER*")))
416         (values wrapper-name `(defparameter ,wrapper-name ,form)))))
417
418 (defun filter-overrides (overrides evalp)
419   (mapcar #'(lambda (override)
420               (list* (car override) (cadr override)
421                      (munge-fun-refs (cddr override) evalp)))
422           overrides))
423
424 (defparameter *arg-function-params*
425   '((:printer . (value stream dstate))
426     (:use-label . (value dstate))
427     (:prefilter . (value dstate))))
428
429 (defun munge-fun-refs (params evalp &optional wrap-defs-p (prefix ""))
430   (let ((params (copy-list params)))
431     (do ((tail params (cdr tail))
432          (wrapper-defs nil))
433         ((null tail)
434          (values params (nreverse wrapper-defs)))
435       (let ((fun-arg (assoc (car tail) *arg-function-params*)))
436         (when fun-arg
437           (let* ((fun-form (cadr tail))
438                  (quoted-fun-form `',fun-form))
439             (when (and wrap-defs-p (not (doesnt-need-wrapping-p fun-form)))
440               (multiple-value-bind (access-form wrapper-def-form)
441                   (make-wrapper fun-form (car fun-arg) (cdr fun-arg) prefix)
442                 (setf quoted-fun-form `',access-form)
443                 (push wrapper-def-form wrapper-defs)))
444             (if evalp
445                 (setf (cadr tail)
446                       `(make-valsrc ,fun-form ,quoted-fun-form))
447                 (setf (cadr tail)
448                       fun-form))))))))
449
450 (defun gen-args-def-form (overrides format-form &optional (evalp t))
451   (let ((args-var (gensym)))
452     `(let ((,args-var (copy-list (format-args ,format-form))))
453        ,@(mapcar #'(lambda (override)
454                      (update-args-form args-var
455                                        `',(car override)
456                                        (and (cdr override)
457                                             (cons :value (cdr override)))
458                                        evalp))
459                  overrides)
460        ,args-var)))
461
462 (defun gen-printer-def-forms-def-form (name def &optional (evalp t))
463   (destructuring-bind
464       (format-name
465        (&rest field-defs)
466        &optional (printer-form :default)
467        &key ((:print-name print-name-form) `',name) control)
468       def
469     (let ((format-var (gensym))
470           (field-defs (filter-overrides field-defs evalp)))
471       `(let* ((*current-instruction-flavor* ',(cons name format-name))
472               (,format-var (format-or-lose ',format-name))
473               (args ,(gen-args-def-form field-defs format-var evalp))
474               (funcache *disassem-function-cache*))
475          ;; FIXME: This should be SPEED 0 but can't be until we support
476          ;; byte compilation of components of the SBCL system.
477          ;;(declare (optimize (speed 0) (safety 0) (debug 0)))
478          (multiple-value-bind (printer-fun printer-defun)
479              (find-printer-fun ,(if (eq printer-form :default)
480                                      `(format-default-printer ,format-var)
481                                      (maybe-quote evalp printer-form))
482                                args funcache)
483            (multiple-value-bind (labeller-fun labeller-defun)
484                (find-labeller-fun args funcache)
485              (multiple-value-bind (prefilter-fun prefilter-defun)
486                  (find-prefilter-fun args funcache)
487                (multiple-value-bind (mask id)
488                    (compute-mask-id args)
489                  (values
490                   `(make-instruction ',',name
491                                      ',',format-name
492                                      ,',print-name-form
493                                      ,(format-length ,format-var)
494                                      ,mask
495                                      ,id
496                                      ,(and printer-fun `#',printer-fun)
497                                      ,(and labeller-fun `#',labeller-fun)
498                                      ,(and prefilter-fun `#',prefilter-fun)
499                                      ,',control)
500                   `(progn
501                      ,@(and printer-defun (list printer-defun))
502                      ,@(and labeller-defun (list labeller-defun))
503                      ,@(and prefilter-defun (list prefilter-defun))))
504                  ))))))))
505
506 (defun update-args-form (var name-form descrip-forms evalp
507                              &optional format-length-form)
508   `(setf ,var
509          ,(if evalp
510               `(modify-or-add-arg ,name-form
511                                   ,var
512                                   *disassem-arg-types*
513                                   ,@(and format-length-form
514                                          `(:format-length
515                                             ,format-length-form))
516                                   ,@descrip-forms)
517               `(apply #'modify-or-add-arg
518                       ,name-form
519                       ,var
520                       *disassem-arg-types*
521                       ,@(and format-length-form
522                              `(:format-length ,format-length-form))
523                       ',descrip-forms))))
524
525 (defun format-or-lose (name)
526   (or (gethash name *disassem-inst-formats*)
527       (pd-error "unknown instruction format ~S" name)))
528
529 ;;; FIXME: needed only at build-the-system time, not in running system
530 (defmacro define-instruction-format (header &rest fields)
531   #!+sb-doc
532   "DEFINE-INSTRUCTION-FORMAT (Name Length {Format-Key Value}*) Arg-Def*
533   Define an instruction format NAME for the disassembler's use. LENGTH is
534   the length of the format in bits.
535   Possible FORMAT-KEYs:
536
537   :INCLUDE other-format-name
538       Inherit all arguments and properties of the given format. Any
539       arguments defined in the current format definition will either modify
540       the copy of an existing argument (keeping in the same order with
541       respect to when pre-filter's are called), if it has the same name as
542       one, or be added to the end.
543   :DEFAULT-PRINTER printer-list
544       Use the given PRINTER-LIST as a format to print any instructions of
545       this format when they don't specify something else.
546
547   Each ARG-DEF defines one argument in the format, and is of the form
548     (Arg-Name {Arg-Key Value}*)
549
550   Possible ARG-KEYs (the values are evaluated unless otherwise specified):
551
552   :FIELDS byte-spec-list
553       The argument takes values from these fields in the instruction. If
554       the list is of length one, then the corresponding value is supplied by
555       itself; otherwise it is a list of the values. The list may be NIL.
556   :FIELD byte-spec
557       The same as :FIELDS (list byte-spec).
558
559   :VALUE value
560       If the argument only has one field, this is the value it should have,
561       otherwise it's a list of the values of the individual fields. This can
562       be overridden in an instruction-definition or a format definition
563       including this one by specifying another, or NIL to indicate that it's
564       variable.
565
566   :SIGN-EXTEND boolean
567       If non-NIL, the raw value of this argument is sign-extended,
568       immediately after being extracted from the instruction (before any
569       prefilters are run, for instance). If the argument has multiple
570       fields, they are all sign-extended.
571
572   :TYPE arg-type-name
573       Inherit any properties of the given argument-type.
574
575   :PREFILTER function
576       A function which is called (along with all other prefilters, in the
577       order that their arguments appear in the instruction-format) before
578       any printing is done, to filter the raw value. Any uses of READ-SUFFIX
579       must be done inside a prefilter.
580
581   :PRINTER function-string-or-vector
582       A function, string, or vector which is used to print this argument.
583
584   :USE-LABEL
585       If non-NIL, the value of this argument is used as an address, and if
586       that address occurs inside the disassembled code, it is replaced by a
587       label. If this is a function, it is called to filter the value."
588   (gen-format-def-form header fields))
589
590 ;;; FIXME: needed only at build-the-system time, not in running system
591 (defun gen-format-def-form (header descrips &optional (evalp t))
592   #!+sb-doc
593   "Generate a form to define an instruction format. See
594   DEFINE-INSTRUCTION-FORMAT for more info."
595   (when (atom header)
596     (setf header (list header)))
597   (destructuring-bind (name length &key default-printer include) header
598     (let ((args-var (gensym))
599           (length-var (gensym))
600           (all-wrapper-defs nil)
601           (arg-count 0))
602       (collect ((arg-def-forms))
603         (dolist (descrip descrips)
604           (let ((name (pop descrip)))
605             (multiple-value-bind (descrip wrapper-defs)
606                 (munge-fun-refs
607                  descrip evalp t (format nil "~:@(~A~)-~D" name arg-count))
608               (arg-def-forms
609                (update-args-form args-var `',name descrip evalp length-var))
610               (setf all-wrapper-defs
611                     (nconc wrapper-defs all-wrapper-defs)))
612             (incf arg-count)))
613         `(progn
614            ,@all-wrapper-defs
615            (eval-when (:compile-toplevel :execute)
616              (let ((,length-var ,length)
617                    (,args-var
618                     ,(and include
619                           `(copy-list
620                             (format-args
621                              (format-or-lose ,include))))))
622                ,@(arg-def-forms)
623                (setf (gethash ',name *disassem-inst-formats*)
624                      (make-instruction-format
625                       :name ',name
626                       :length (bits-to-bytes ,length-var)
627                       :default-printer ,(maybe-quote evalp default-printer)
628                       :args ,args-var))
629                (eval
630                 `(progn
631                    ,@(mapcar #'(lambda (arg)
632                                  (when (arg-fields arg)
633                                    (gen-arg-access-macro-def-form
634                                     arg ,args-var ',name)))
635                              ,args-var))))))))))
636
637 ;;; FIXME: probably needed only at build-the-system time, not in
638 ;;; final target system
639 (defun modify-or-add-arg (arg-name
640                           args
641                           type-table
642                           &key
643                           (value nil value-p)
644                           (type nil type-p)
645                           (prefilter nil prefilter-p)
646                           (printer nil printer-p)
647                           (sign-extend nil sign-extend-p)
648                           (use-label nil use-label-p)
649                           (field nil field-p)
650                           (fields nil fields-p)
651                           format-length)
652   (let* ((arg-pos (position arg-name args :key #'arg-name))
653          (arg
654           (if (null arg-pos)
655               (let ((arg (make-argument :name arg-name)))
656                 (if (null args)
657                     (setf args (list arg))
658                     (push arg (cdr (last args))))
659                 arg)
660               (setf (nth arg-pos args) (copy-argument (nth arg-pos args))))))
661     (when (and field-p (not fields-p))
662       (setf fields (list field))
663       (setf fields-p t))
664     (when type-p
665       (set-arg-from-type arg type type-table))
666     (when value-p
667       (setf (arg-value arg) value))
668     (when prefilter-p
669       (setf (arg-prefilter arg) prefilter))
670     (when sign-extend-p
671       (setf (arg-sign-extend-p arg) sign-extend))
672     (when printer-p
673       (setf (arg-printer arg) printer))
674     (when use-label-p
675       (setf (arg-use-label arg) use-label))
676     (when fields-p
677       (when (null format-length)
678         (error
679          "~@<in arg ~S: ~3I~:_~
680           can't specify fields except using DEFINE-INSTRUCTION-FORMAT~:>"
681          arg-name))
682       (setf (arg-fields arg)
683             (mapcar #'(lambda (bytespec)
684                         (when (> (+ (byte-position bytespec)
685                                     (byte-size bytespec))
686                                  format-length)
687                           (error "~@<in arg ~S: ~3I~:_~
688                                      The field ~S doesn't fit in an ~
689                                      instruction-format ~D bits wide.~:>"
690                                  arg-name
691                                  bytespec
692                                  format-length))
693                         (correct-dchunk-bytespec-for-endianness
694                          bytespec
695                          format-length
696                          sb!c:*backend-byte-order*))
697                     fields)))
698     args))
699
700 (defun gen-arg-access-macro-def-form (arg args format-name)
701   (let* ((funstate (make-funstate args))
702          (arg-val-form (arg-value-form arg funstate :adjusted))
703          (bindings (make-arg-temp-bindings funstate)))
704     `(sb!xc:defmacro ,(symbolicate format-name "-" (arg-name arg))
705          (chunk dstate)
706        `(let ((chunk ,chunk) (dstate ,dstate))
707           (declare (ignorable chunk dstate))
708           (flet ((local-filtered-value (offset)
709                    (declare (type filtered-value-index offset))
710                    (aref (dstate-filtered-values dstate) offset))
711                  (local-extract (bytespec)
712                    (dchunk-extract chunk bytespec)))
713             (declare (ignorable #'local-filtered-value #'local-extract)
714                      (inline local-filtered-value local-extract))
715             (let* ,',bindings
716               ,',arg-val-form))))))
717
718 (defun arg-value-form (arg funstate
719                        &optional
720                        (kind :final)
721                        (allow-multiple-p (not (eq kind :numeric))))
722   (let ((forms (gen-arg-forms arg kind funstate)))
723     (when (and (not allow-multiple-p)
724                (listp forms)
725                (/= (length forms) 1))
726       (pd-error "~S must not have multiple values." arg))
727     (maybe-listify forms)))
728
729 (defun correct-dchunk-bytespec-for-endianness (bs unit-bits byte-order)
730   (if (eq byte-order :big-endian)
731       (byte (byte-size bs) (+ (byte-position bs) (- dchunk-bits unit-bits)))
732       bs))
733
734 (defun make-arg-temp-bindings (funstate)
735   ;; (Everything is in reverse order, so we just use PUSH, which
736   ;; results in everything being in the right order at the end.)
737   (let ((bindings nil))
738     (dolist (ats (funstate-arg-temps funstate))
739       (dolist (atk (cdr ats))
740         (cond ((null (cadr atk)))
741               ((atom (cadr atk))
742                (push `(,(cadr atk) ,(cddr atk)) bindings))
743               (t
744                (mapc #'(lambda (var form)
745                          (push `(,var ,form) bindings))
746                      (cadr atk)
747                      (cddr atk))))))
748     bindings))
749
750 (defun gen-arg-forms (arg kind funstate)
751   (multiple-value-bind (vars forms)
752       (get-arg-temp arg kind funstate)
753     (when (null forms)
754       (multiple-value-bind (new-forms single-value-p)
755           (funcall (find-arg-form-producer kind) arg funstate)
756         (setq forms new-forms)
757         (cond ((or single-value-p (atom forms))
758                (unless (symbolp forms)
759                  (setq vars (gensym))))
760               ((every #'symbolp forms)
761                ;; just use the same as the forms
762                (setq vars nil))
763               (t
764                (setq vars (make-gensym-list (length forms)))))
765         (set-arg-temps vars forms arg kind funstate)))
766     (or vars forms)))
767
768 (defun maybe-listify (forms)
769   (cond ((atom forms)
770          forms)
771         ((/= (length forms) 1)
772          `(list ,@forms))
773         (t
774          (car forms))))
775 \f
776 (defun set-arg-from-type (arg type-name table)
777   (let ((type-arg (find type-name table :key #'arg-name)))
778     (when (null type-arg)
779       (pd-error "unknown argument type: ~S" type-name))
780     (setf (arg-printer arg) (arg-printer type-arg))
781     (setf (arg-prefilter arg) (arg-prefilter type-arg))
782     (setf (arg-sign-extend-p arg) (arg-sign-extend-p type-arg))
783     (setf (arg-use-label arg) (arg-use-label type-arg))))
784
785 (defun get-arg-temp (arg kind funstate)
786   (let ((this-arg-temps (assoc arg (funstate-arg-temps funstate))))
787     (if this-arg-temps
788         (let ((this-kind-temps
789                (assoc (canonicalize-arg-form-kind kind)
790                       (cdr this-arg-temps))))
791           (values (cadr this-kind-temps) (cddr this-kind-temps)))
792         (values nil nil))))
793
794 (defun set-arg-temps (vars forms arg kind funstate)
795   (let ((this-arg-temps
796          (or (assoc arg (funstate-arg-temps funstate))
797              (car (push (cons arg nil) (funstate-arg-temps funstate)))))
798         (kind (canonicalize-arg-form-kind kind)))
799     (let ((this-kind-temps
800            (or (assoc kind (cdr this-arg-temps))
801                (car (push (cons kind nil) (cdr this-arg-temps))))))
802       (setf (cdr this-kind-temps) (cons vars forms)))))
803 \f
804 (defmacro define-argument-type (name &rest args)
805   #!+sb-doc
806   "DEFINE-ARGUMENT-TYPE Name {Key Value}*
807   Define a disassembler argument type NAME (which can then be referenced in
808   another argument definition using the :TYPE argument). &KEY args are:
809
810   :SIGN-EXTEND boolean
811       If non-NIL, the raw value of this argument is sign-extended.
812
813   :TYPE arg-type-name
814       Inherit any properties of given argument-type.
815
816   :PREFILTER function
817       A function which is called (along with all other prefilters, in the
818       order that their arguments appear in the instruction- format) before
819       any printing is done, to filter the raw value. Any uses of READ-SUFFIX
820       must be done inside a prefilter.
821
822   :PRINTER function-string-or-vector
823       A function, string, or vector which is used to print an argument of
824       this type.
825
826   :USE-LABEL
827       If non-NIL, the value of an argument of this type is used as an
828       address, and if that address occurs inside the disassembled code, it is
829       replaced by a label. If this is a function, it is called to filter the
830       value."
831   (gen-arg-type-def-form name args))
832
833 (defun gen-arg-type-def-form (name args &optional (evalp t))
834   #!+sb-doc
835   "Generate a form to define a disassembler argument type. See
836   DEFINE-ARGUMENT-TYPE for more info."
837   (multiple-value-bind (args wrapper-defs)
838       (munge-fun-refs args evalp t name)
839     `(progn
840        ,@wrapper-defs
841        (eval-when (:compile-toplevel :execute)
842          ,(update-args-form '*disassem-arg-types* `',name args evalp))
843        ',name)))
844 \f
845 (defmacro def-arg-form-kind ((&rest names) &rest inits)
846   `(let ((kind (make-arg-form-kind :names ',names ,@inits)))
847      ,@(mapcar #'(lambda (name)
848                    `(setf (getf *arg-form-kinds* ',name) kind))
849                names)))
850
851 (def-arg-form-kind (:raw)
852   :producer #'(lambda (arg funstate)
853                 (declare (ignore funstate))
854                 (mapcar #'(lambda (bytespec)
855                             `(the (unsigned-byte ,(byte-size bytespec))
856                                   (local-extract ',bytespec)))
857                         (arg-fields arg)))
858   :checker #'(lambda (new-arg old-arg)
859                (equal (arg-fields new-arg)
860                       (arg-fields old-arg))))
861
862 (def-arg-form-kind (:sign-extended :unfiltered)
863   :producer #'(lambda (arg funstate)
864                 (let ((raw-forms (gen-arg-forms arg :raw funstate)))
865                   (if (and (arg-sign-extend-p arg) (listp raw-forms))
866                       (mapcar #'(lambda (form field)
867                                   `(the (signed-byte ,(byte-size field))
868                                         (sign-extend ,form
869                                                      ,(byte-size field))))
870                               raw-forms
871                               (arg-fields arg))
872                       raw-forms)))
873   :checker #'(lambda (new-arg old-arg)
874                (equal (arg-sign-extend-p new-arg)
875                       (arg-sign-extend-p old-arg))))
876
877 (defun valsrc-equal (f1 f2)
878   (if (null f1)
879       (null f2)
880       (equal (value-or-source f1)
881              (value-or-source f2))))
882
883 (def-arg-form-kind (:filtering)
884   :producer #'(lambda (arg funstate)
885                 (let ((sign-extended-forms
886                        (gen-arg-forms arg :sign-extended funstate))
887                       (pf (arg-prefilter arg)))
888                   (if pf
889                       (values
890                        `(local-filter ,(maybe-listify sign-extended-forms)
891                                       ,(source-form pf))
892                        t)
893                       (values sign-extended-forms nil))))
894   :checker #'(lambda (new-arg old-arg)
895                (valsrc-equal (arg-prefilter new-arg) (arg-prefilter old-arg))))
896
897 (def-arg-form-kind (:filtered :unadjusted)
898   :producer #'(lambda (arg funstate)
899                 (let ((pf (arg-prefilter arg)))
900                   (if pf
901                       (values `(local-filtered-value ,(arg-position arg)) t)
902                       (gen-arg-forms arg :sign-extended funstate))))
903   :checker #'(lambda (new-arg old-arg)
904                (let ((pf1 (arg-prefilter new-arg))
905                      (pf2 (arg-prefilter old-arg)))
906                  (if (null pf1)
907                      (null pf2)
908                      (= (arg-position new-arg)
909                         (arg-position old-arg))))))
910
911 (def-arg-form-kind (:adjusted :numeric :unlabelled)
912   :producer #'(lambda (arg funstate)
913                 (let ((filtered-forms (gen-arg-forms arg :filtered funstate))
914                       (use-label (arg-use-label arg)))
915                   (if (and use-label (not (eq use-label t)))
916                       (list
917                        `(adjust-label ,(maybe-listify filtered-forms)
918                                       ,(source-form use-label)))
919                       filtered-forms)))
920   :checker #'(lambda (new-arg old-arg)
921                (valsrc-equal (arg-use-label new-arg) (arg-use-label old-arg))))
922
923 (def-arg-form-kind (:labelled :final)
924   :producer #'(lambda (arg funstate)
925                 (let ((adjusted-forms
926                        (gen-arg-forms arg :adjusted funstate))
927                       (use-label (arg-use-label arg)))
928                   (if use-label
929                       (let ((form (maybe-listify adjusted-forms)))
930                         (if (and (not (eq use-label t))
931                                  (not (atom adjusted-forms))
932                                  (/= (Length adjusted-forms) 1))
933                             (pd-error
934                              "cannot label a multiple-field argument ~
935                               unless using a function: ~S" arg)
936                             `((lookup-label ,form))))
937                       adjusted-forms)))
938   :checker #'(lambda (new-arg old-arg)
939                (let ((lf1 (arg-use-label new-arg))
940                      (lf2 (arg-use-label old-arg)))
941                  (if (null lf1) (null lf2) t))))
942
943 ;;; This is a bogus kind that's just used to ensure that printers are
944 ;;; compatible...
945 (def-arg-form-kind (:printed)
946   :producer #'(lambda (&rest noise)
947                 (declare (ignore noise))
948                 (pd-error "bogus! can't use the :printed value of an arg!"))
949   :checker #'(lambda (new-arg old-arg)
950                (valsrc-equal (arg-printer new-arg) (arg-printer old-arg))))
951
952 (defun remember-printer-use (arg funstate)
953   (set-arg-temps nil nil arg :printed funstate))
954 \f
955 ;;; Returns a version of THING suitable for including in an evaluable
956 ;;; position in some form.
957 (defun source-form (thing)
958   (cond ((valsrc-p thing)
959          (valsrc-source thing))
960         ((functionp thing)
961          (pd-error
962           "can't dump functions, so function ref form must be quoted: ~S"
963           thing))
964         ((self-evaluating-p thing)
965          thing)
966         ((eq (car thing) 'function)
967          thing)
968         (t
969          `',thing)))
970
971 ;;; Returns anything but a VALSRC structure.
972 (defun value-or-source (thing)
973   (if (valsrc-p thing)
974       (valsrc-value thing)
975       thing))
976 \f
977 (defstruct (cached-function (:conc-name cached-fun-)
978                             (:copier nil))
979   (funstate nil :type (or null funstate))
980   (constraint nil :type list)
981   (name nil :type (or null symbol)))
982
983 (defun find-cached-function (cached-funs args constraint)
984   (dolist (cached-fun cached-funs nil)
985     (let ((funstate (cached-fun-funstate cached-fun)))
986       (when (and (equal constraint (cached-fun-constraint cached-fun))
987                  (or (null funstate)
988                      (funstate-compatible-p funstate args)))
989         (return cached-fun)))))
990
991 (defmacro with-cached-function ((name-var funstate-var cache cache-slot
992                                           args &key constraint prefix)
993                                 &body defun-maker-forms)
994   (let ((cache-var (gensym))
995         (constraint-var (gensym)))
996     `(let* ((,constraint-var ,constraint)
997             (,cache-var (find-cached-function (,cache-slot ,cache)
998                                               ,args ,constraint-var)))
999        (cond (,cache-var
1000               #+nil
1001               (Format t "~&; Using cached function ~S~%"
1002                       (cached-fun-name ,cache-var))
1003               (values (cached-fun-name ,cache-var) nil))
1004              (t
1005               (let* ((,name-var (gensym ,prefix))
1006                      (,funstate-var (make-funstate ,args))
1007                      (,cache-var
1008                       (make-cached-function :name ,name-var
1009                                             :funstate ,funstate-var
1010                                             :constraint ,constraint-var)))
1011                 #+nil
1012                 (format t "~&; Making new function ~S~%"
1013                         (cached-fun-name ,cache-var))
1014                 (values ,name-var
1015                         `(progn
1016                            ,(progn ,@defun-maker-forms)
1017                            (eval-when (:compile-toplevel :execute)
1018                              (push ,,cache-var
1019                                    (,',cache-slot ',,cache)))))))))))
1020 \f
1021 (defun find-printer-fun (printer-source args cache)
1022   (if (null printer-source)
1023       (values nil nil)
1024       (let ((printer-source (preprocess-printer printer-source args)))
1025         (with-cached-function
1026             (name funstate cache function-cache-printers args
1027                   :constraint printer-source
1028                   :prefix "PRINTER")
1029           (make-printer-defun printer-source funstate name)))))
1030 \f
1031 ;;;; Note that these things are compiled byte compiled to save space.
1032
1033 (defun make-printer-defun (source funstate function-name)
1034   (let ((printer-form (compile-printer-list source funstate))
1035         (bindings (make-arg-temp-bindings funstate)))
1036     `(defun ,function-name (chunk inst stream dstate)
1037        (declare (type dchunk chunk)
1038                 (type instruction inst)
1039                 (type stream stream)
1040                 (type disassem-state dstate)
1041                 ;; FIXME: This should be SPEED 0 but can't be until we support
1042                 ;; byte compilation of components of the SBCL system.
1043                 #+nil (optimize (speed 0) (safety 0) (debug 0)))
1044        (macrolet ((local-format-arg (arg fmt)
1045                     `(funcall (formatter ,fmt) stream ,arg)))
1046          (flet ((local-tab-to-arg-column ()
1047                   (tab (dstate-argument-column dstate) stream))
1048                 (local-print-name ()
1049                   (princ (inst-print-name inst) stream))
1050                 (local-write-char (ch)
1051                   (write-char ch stream))
1052                 (local-princ (thing)
1053                   (princ thing stream))
1054                 (local-princ16 (thing)
1055                   (princ16 thing stream))
1056                 (local-call-arg-printer (arg printer)
1057                   (funcall printer arg stream dstate))
1058                 (local-call-global-printer (fun)
1059                   (funcall fun chunk inst stream dstate))
1060                 (local-filtered-value (offset)
1061                   (declare (type filtered-value-index offset))
1062                   (aref (dstate-filtered-values dstate) offset))
1063                 (local-extract (bytespec)
1064                   (dchunk-extract chunk bytespec))
1065                 (lookup-label (lab)
1066                   (or (gethash lab (dstate-label-hash dstate))
1067                       lab))
1068                 (adjust-label (val adjust-fun)
1069                   (funcall adjust-fun val dstate)))
1070            (declare (ignorable #'local-tab-to-arg-column
1071                                #'local-print-name
1072                                #'local-princ #'local-princ16
1073                                #'local-write-char
1074                                #'local-call-arg-printer
1075                                #'local-call-global-printer
1076                                #'local-extract
1077                                #'local-filtered-value
1078                                #'lookup-label #'adjust-label)
1079                     (inline local-tab-to-arg-column
1080                             local-princ local-princ16
1081                             local-call-arg-printer local-call-global-printer
1082                             local-filtered-value local-extract
1083                             lookup-label adjust-label))
1084            (let* ,bindings
1085              ,@printer-form))))))
1086 \f
1087 (defun preprocess-test (subj form args)
1088   (multiple-value-bind (subj test)
1089       (if (and (consp form) (symbolp (car form)) (not (keywordp (car form))))
1090           (values (car form) (cdr form))
1091           (values subj form))
1092     (let ((key (if (consp test) (car test) test))
1093           (body (if (consp test) (cdr test) nil)))
1094       (case key
1095         (:constant
1096          (if (null body)
1097              ;; If no supplied constant values, just any constant is ok, just
1098              ;; see whether there's some constant value in the arg.
1099              (not
1100               (null
1101                (arg-value
1102                 (or (find subj args :key #'arg-name)
1103                     (pd-error "unknown argument ~S" subj)))))
1104              ;; Otherwise, defer to run-time.
1105              form))
1106         ((:or :and :not)
1107          (sharing-cons
1108           form
1109           subj
1110           (sharing-cons
1111            test
1112            key
1113            (sharing-mapcar
1114             #'(lambda (sub-test)
1115                 (preprocess-test subj sub-test args))
1116             body))))
1117         (t form)))))
1118
1119 (defun preprocess-conditionals (printer args)
1120   (if (atom printer)
1121       printer
1122       (case (car printer)
1123         (:unless
1124          (preprocess-conditionals
1125           `(:cond ((:not ,(nth 1 printer)) ,@(nthcdr 2 printer)))
1126           args))
1127         (:when
1128          (preprocess-conditionals `(:cond (,(cdr printer))) args))
1129         (:if
1130          (preprocess-conditionals
1131           `(:cond (,(nth 1 printer) ,(nth 2 printer))
1132                   (t ,(nth 3 printer)))
1133           args))
1134         (:cond
1135          (sharing-cons
1136           printer
1137           :cond
1138           (sharing-mapcar
1139            #'(lambda (clause)
1140                (let ((filtered-body
1141                       (sharing-mapcar
1142                        #'(lambda (sub-printer)
1143                            (preprocess-conditionals sub-printer args))
1144                        (cdr clause))))
1145                  (sharing-cons
1146                   clause
1147                   (preprocess-test (find-first-field-name filtered-body)
1148                                    (car clause)
1149                                    args)
1150                   filtered-body)))
1151            (cdr printer))))
1152         (quote printer)
1153         (t
1154          (sharing-mapcar
1155           #'(lambda (sub-printer)
1156               (preprocess-conditionals sub-printer args))
1157           printer)))))
1158
1159 (defun preprocess-printer (printer args)
1160   #!+sb-doc
1161   "Returns a version of the disassembly-template PRINTER with compile-time
1162   tests (e.g. :constant without a value), and any :CHOOSE operators resolved
1163   properly for the args ARGS. (:CHOOSE Sub*) simply returns the first Sub in
1164   which every field reference refers to a valid arg."
1165   (preprocess-conditionals (preprocess-chooses printer args) args))
1166 \f
1167 (defun find-first-field-name (tree)
1168   #!+sb-doc
1169   "Returns the first non-keyword symbol in a depth-first search of TREE."
1170   (cond ((null tree)
1171          nil)
1172         ((and (symbolp tree) (not (keywordp tree)))
1173          tree)
1174         ((atom tree)
1175          nil)
1176         ((eq (car tree) 'quote)
1177          nil)
1178         (t
1179          (or (find-first-field-name (car tree))
1180              (find-first-field-name (cdr tree))))))
1181
1182 (defun preprocess-chooses (printer args)
1183   (cond ((atom printer)
1184          printer)
1185         ((eq (car printer) :choose)
1186          (pick-printer-choice (cdr printer) args))
1187         (t
1188          (sharing-mapcar #'(lambda (sub) (preprocess-chooses sub args))
1189                          printer))))
1190 \f
1191 ;;;; some simple functions that help avoid consing when we're just
1192 ;;;; recursively filtering things that usually don't change
1193
1194 (defun sharing-cons (old-cons car cdr)
1195   #!+sb-doc
1196   "If CAR is eq to the car of OLD-CONS and CDR is eq to the CDR, return
1197   OLD-CONS, otherwise return (cons CAR CDR)."
1198   (if (and (eq car (car old-cons)) (eq cdr (cdr old-cons)))
1199       old-cons
1200       (cons car cdr)))
1201
1202 (defun sharing-mapcar (fun list)
1203   #!+sb-doc
1204   "A simple (one list arg) mapcar that avoids consing up a new list
1205   as long as the results of calling FUN on the elements of LIST are
1206   eq to the original."
1207   (and list
1208        (sharing-cons list
1209                      (funcall fun (car list))
1210                      (sharing-mapcar fun (cdr list)))))
1211 \f
1212 (defun all-arg-refs-relevant-p (printer args)
1213   (cond ((or (null printer) (keywordp printer) (eq printer t))
1214          t)
1215         ((symbolp printer)
1216          (find printer args :key #'arg-name))
1217         ((listp printer)
1218          (every #'(lambda (x) (all-arg-refs-relevant-p x args))
1219                 printer))
1220         (t t)))
1221
1222 (defun pick-printer-choice (choices args)
1223   (dolist (choice choices
1224            (pd-error "no suitable choice found in ~S" choices))
1225     (when (all-arg-refs-relevant-p choice args)
1226       (return choice))))
1227
1228 (defun compile-printer-list (sources funstate)
1229   (unless (null sources)
1230     ;; Coalesce adjacent symbols/strings, and convert to strings if possible,
1231     ;; since they require less consing to write.
1232     (do ((el (car sources) (car sources))
1233          (names nil (cons (strip-quote el) names)))
1234         ((not (string-or-qsym-p el))
1235          (when names
1236            ;; concatenate adjacent strings and symbols
1237            (let ((string
1238                   (apply #'concatenate
1239                          'string
1240                          (mapcar #'string (nreverse names)))))
1241              (push (if (some #'alpha-char-p string)
1242                        `',(make-symbol string) ; Preserve casifying output.
1243                        string)
1244                    sources))))
1245       (pop sources))
1246     (cons (compile-printer-body (car sources) funstate)
1247           (compile-printer-list (cdr sources) funstate))))
1248
1249 (defun compile-printer-body (source funstate)
1250   (cond ((null source)
1251          nil)
1252         ((eq source :name)
1253          `(local-print-name))
1254         ((eq source :tab)
1255          `(local-tab-to-arg-column))
1256         ((keywordp source)
1257          (pd-error "unknown printer element: ~S" source))
1258         ((symbolp source)
1259          (compile-print source funstate))
1260         ((atom source)
1261          `(local-princ ',source))
1262         ((eq (car source) :using)
1263          (unless (or (stringp (cadr source))
1264                      (and (listp (cadr source))
1265                           (eq (caadr source) 'function)))
1266            (pd-error "The first arg to :USING must be a string or #'function."))
1267          (compile-print (caddr source) funstate
1268                         (cons (eval (cadr source)) (cadr source))))
1269         ((eq (car source) :plus-integer)
1270          ;; prints the given field proceed with a + or a -
1271          (let ((form
1272                 (arg-value-form (arg-or-lose (cadr source) funstate)
1273                                 funstate
1274                                 :numeric)))
1275            `(progn
1276               (when (>= ,form 0)
1277                 (local-write-char #\+))
1278               (local-princ ,form))))
1279         ((eq (car source) 'quote)
1280          `(local-princ ,source))
1281         ((eq (car source) 'function)
1282          `(local-call-global-printer ,source))
1283         ((eq (car source) :cond)
1284          `(cond ,@(mapcar #'(lambda (clause)
1285                               `(,(compile-test (find-first-field-name
1286                                                 (cdr clause))
1287                                                (car clause)
1288                                                funstate)
1289                                 ,@(compile-printer-list (cdr clause)
1290                                                         funstate)))
1291                           (cdr source))))
1292         ;; :IF, :UNLESS, and :WHEN are replaced by :COND during preprocessing
1293         (t
1294          `(progn ,@(compile-printer-list source funstate)))))
1295
1296 (defun compile-print (arg-name funstate &optional printer)
1297   (let* ((arg (arg-or-lose arg-name funstate))
1298          (printer (or printer (arg-printer arg)))
1299          (printer-val (value-or-source printer))
1300          (printer-src (source-form printer)))
1301     (remember-printer-use arg funstate)
1302     (cond ((stringp printer-val)
1303            `(local-format-arg ,(arg-value-form arg funstate) ,printer-val))
1304           ((vectorp printer-val)
1305            `(local-princ
1306              (aref ,printer-src
1307                    ,(arg-value-form arg funstate :numeric))))
1308           ((or (functionp printer-val)
1309                (and (consp printer-val) (eq (car printer-val) 'function)))
1310            `(local-call-arg-printer ,(arg-value-form arg funstate)
1311                                     ,printer-src))
1312           ((or (null printer-val) (eq printer-val t))
1313            `(,(if (arg-use-label arg) 'local-princ16 'local-princ)
1314              ,(arg-value-form arg funstate)))
1315           (t
1316            (pd-error "illegal printer: ~S" printer-src)))))
1317
1318 (defun string-or-qsym-p (thing)
1319   (or (stringp thing)
1320       (and (consp thing)
1321            (eq (car thing) 'quote)
1322            (or (stringp (cadr thing))
1323                (symbolp (cadr thing))))))
1324
1325 (defun strip-quote (thing)
1326   (if (and (consp thing) (eq (car thing) 'quote))
1327       (cadr thing)
1328       thing))
1329 \f
1330 (defun compare-fields-form (val-form-1 val-form-2)
1331   (flet ((listify-fields (fields)
1332            (cond ((symbolp fields) fields)
1333                  ((every #'constantp fields) `',fields)
1334                  (t `(list ,@fields)))))
1335     (cond ((or (symbolp val-form-1) (symbolp val-form-2))
1336            `(equal ,(listify-fields val-form-1)
1337                    ,(listify-fields val-form-2)))
1338           (t
1339            `(and ,@(mapcar #'(lambda (v1 v2) `(= ,v1 ,v2))
1340                            val-form-1 val-form-2))))))
1341
1342 (defun compile-test (subj test funstate)
1343   (when (and (consp test) (symbolp (car test)) (not (keywordp (car test))))
1344     (setf subj (car test)
1345           test (cdr test)))
1346   (let ((key (if (consp test) (car test) test))
1347         (body (if (consp test) (cdr test) nil)))
1348     (cond ((null key)
1349            nil)
1350           ((eq key t)
1351            t)
1352           ((eq key :constant)
1353            (let* ((arg (arg-or-lose subj funstate))
1354                   (fields (arg-fields arg))
1355                   (consts body))
1356              (when (not (= (length fields) (length consts)))
1357                (pd-error "The number of constants doesn't match number of ~
1358                           fields in: (~S :constant~{ ~S~})"
1359                          subj body))
1360              (compare-fields-form (gen-arg-forms arg :numeric funstate)
1361                                   consts)))
1362           ((eq key :positive)
1363            `(> ,(arg-value-form (arg-or-lose subj funstate) funstate :numeric)
1364                0))
1365           ((eq key :negative)
1366            `(< ,(arg-value-form (arg-or-lose subj funstate) funstate :numeric)
1367                0))
1368           ((eq key :same-as)
1369            (let ((arg1 (arg-or-lose subj funstate))
1370                  (arg2 (arg-or-lose (car body) funstate)))
1371              (unless (and (= (length (arg-fields arg1))
1372                              (length (arg-fields arg2)))
1373                           (every #'(lambda (bs1 bs2)
1374                                      (= (byte-size bs1) (byte-size bs2)))
1375                                  (arg-fields arg1)
1376                                  (arg-fields arg2)))
1377                (pd-error "can't compare differently sized fields: ~
1378                           (~S :same-as ~S)" subj (car body)))
1379              (compare-fields-form (gen-arg-forms arg1 :numeric funstate)
1380                                   (gen-arg-forms arg2 :numeric funstate))))
1381           ((eq key :or)
1382            `(or ,@(mapcar #'(lambda (sub) (compile-test subj sub funstate))
1383                           body)))
1384           ((eq key :and)
1385            `(and ,@(mapcar #'(lambda (sub) (compile-test subj sub funstate))
1386                            body)))
1387           ((eq key :not)
1388            `(not ,(compile-test subj (car body) funstate)))
1389           ((and (consp key) (null body))
1390            (compile-test subj key funstate))
1391           (t
1392            (pd-error "bogus test-form: ~S" test)))))
1393 \f
1394 (defun find-labeller-fun (args cache)
1395   (let ((labelled-fields
1396          (mapcar #'arg-name (remove-if-not #'arg-use-label args))))
1397     (if (null labelled-fields)
1398         (values nil nil)
1399         (with-cached-function
1400             (name funstate cache function-cache-labellers args
1401              :prefix "LABELLER"
1402              :constraint labelled-fields)
1403           (let ((labels-form 'labels))
1404             (dolist (arg args)
1405               (when (arg-use-label arg)
1406                 (setf labels-form
1407                       `(let ((labels ,labels-form)
1408                              (addr
1409                               ,(arg-value-form arg funstate :adjusted nil)))
1410                          (if (assoc addr labels :test #'eq)
1411                              labels
1412                              (cons (cons addr nil) labels))))))
1413             `(defun ,name (chunk labels dstate)
1414                (declare (type list labels)
1415                         (type dchunk chunk)
1416                         (type disassem-state dstate)
1417                         ;; FIXME: This should be SPEED 0 but can't be
1418                         ;; until we support byte compilation of
1419                         ;; components of the SBCL system.
1420                         #+nil (optimize (speed 0) (safety 0) (debug 0)))
1421                (flet ((local-filtered-value (offset)
1422                         (declare (type filtered-value-index offset))
1423                         (aref (dstate-filtered-values dstate) offset))
1424                       (local-extract (bytespec)
1425                         (dchunk-extract chunk bytespec))
1426                       (adjust-label (val adjust-fun)
1427                         (funcall adjust-fun val dstate)))
1428                  (declare (ignorable #'local-filtered-value #'local-extract
1429                                      #'adjust-label)
1430                           (inline local-filtered-value local-extract
1431                                   adjust-label))
1432                  (let* ,(make-arg-temp-bindings funstate)
1433                    ,labels-form))))))))
1434
1435 (defun find-prefilter-fun (args cache)
1436   (let ((filtered-args
1437          (mapcar #'arg-name (remove-if-not #'arg-prefilter args))))
1438     (if (null filtered-args)
1439         (values nil nil)
1440         (with-cached-function
1441             (name funstate cache function-cache-prefilters args
1442              :prefix "PREFILTER"
1443              :constraint filtered-args)
1444           (collect ((forms))
1445             (dolist (arg args)
1446               (let ((pf (arg-prefilter arg)))
1447                 (when pf
1448                   (forms
1449                    `(setf (local-filtered-value ,(arg-position arg))
1450                           ,(maybe-listify
1451                             (gen-arg-forms arg :filtering funstate)))))
1452                 ))
1453             `(defun ,name (chunk dstate)
1454                (declare (type dchunk chunk)
1455                         (type disassem-state dstate)
1456                         ;; FIXME: This should be SPEED 0 but can't be
1457                         ;; until we support byte compilation of
1458                         ;; components of the SBCL system.
1459                         #+nil (optimize (speed 0) (safety 0) (debug 0)))
1460                (flet (((setf local-filtered-value) (value offset)
1461                        (declare (type filtered-value-index offset))
1462                        (setf (aref (dstate-filtered-values dstate) offset)
1463                              value))
1464                       (local-filter (value filter)
1465                                     (funcall filter value dstate))
1466                       (local-extract (bytespec)
1467                                      (dchunk-extract chunk bytespec)))
1468                 (declare (ignorable #'local-filter #'local-extract)
1469                          (inline (setf local-filtered-value)
1470                                  local-filter local-extract))
1471                 ;; Use them for side-effects only.
1472                 (let* ,(make-arg-temp-bindings funstate)
1473                   ,@(forms)))))))))
1474 \f
1475 (defun compute-mask-id (args)
1476   (let ((mask dchunk-zero)
1477         (id dchunk-zero))
1478     (dolist (arg args (values mask id))
1479       (let ((av (arg-value arg)))
1480         (when av
1481           (do ((fields (arg-fields arg) (cdr fields))
1482                (values (if (atom av) (list av) av) (cdr values)))
1483               ((null fields))
1484             (let ((field-mask (dchunk-make-mask (car fields))))
1485               (when (/= (dchunk-and mask field-mask) dchunk-zero)
1486                 (pd-error "The field ~S in arg ~S overlaps some other field."
1487                           (car fields)
1488                           (arg-name arg)))
1489               (dchunk-insertf id (car fields) (car values))
1490               (dchunk-orf mask field-mask))))))))
1491
1492 (defun install-inst-flavors (name flavors)
1493   (setf (gethash name *disassem-insts*)
1494         flavors))
1495 \f
1496 #!-sb-fluid (declaim (inline bytes-to-bits))
1497 (declaim (maybe-inline sign-extend aligned-p align tab tab0))
1498
1499 (defun bytes-to-bits (bytes)
1500   (declare (type length bytes))
1501   (* bytes sb!vm:byte-bits))
1502
1503 (defun bits-to-bytes (bits)
1504   (declare (type length bits))
1505   (multiple-value-bind (bytes rbits)
1506       (truncate bits sb!vm:byte-bits)
1507     (when (not (zerop rbits))
1508       (error "~D bits is not a byte-multiple." bits))
1509     bytes))
1510
1511 (defun sign-extend (int size)
1512   (declare (type integer int)
1513            (type (integer 0 128) size))
1514   (if (logbitp (1- size) int)
1515       (dpb int (byte size 0) -1)
1516       int))
1517
1518 (defun aligned-p (address size)
1519   #!+sb-doc
1520   "Returns non-NIL if ADDRESS is aligned on a SIZE byte boundary."
1521   (declare (type address address)
1522            (type alignment size))
1523   (zerop (logand (1- size) address)))
1524
1525 (defun align (address size)
1526   #!+sb-doc
1527   "Return ADDRESS aligned *upward* to a SIZE byte boundary."
1528   (declare (type address address)
1529            (type alignment size))
1530   (logandc1 (1- size) (+ (1- size) address)))
1531
1532 (defun tab (column stream)
1533   (funcall (formatter "~V,1t") stream column)
1534   nil)
1535 (defun tab0 (column stream)
1536   (funcall (formatter "~V,0t") stream column)
1537   nil)
1538
1539 (defun princ16 (value stream)
1540   (write value :stream stream :radix t :base 16 :escape nil))
1541 \f
1542 (defun read-signed-suffix (length dstate)
1543   (declare (type (member 8 16 32) length)
1544            (type disassem-state dstate)
1545            (optimize (speed 3) (safety 0)))
1546   (sign-extend (read-suffix length dstate) length))
1547
1548 ;;; KLUDGE: The associated run-time machinery for this is in
1549 ;;; target-disassem.lisp (much later). This is here just to make sure
1550 ;;; it's defined before it's used. -- WHN ca. 19990701
1551 (defmacro dstate-get-prop (dstate name)
1552   #!+sb-doc
1553   "Get the value of the property called NAME in DSTATE. Also setf'able."
1554   `(getf (dstate-properties ,dstate) ,name))