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