5f0a2d80ad2b7b33f8424fc3db05efdae500f389
[sbcl.git] / src / compiler / x86 / macros.lisp
1 ;;;; a bunch of handy macros for the x86
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!VM")
13
14 ;;; We can load/store into fp registers through the top of stack
15 ;;; %st(0) (fr0 here). Loads imply a push to an empty register which
16 ;;; then changes all the reg numbers. These macros help manage that.
17
18 ;;; Use this when we don't have to load anything. It preserves old tos
19 ;;; value, but probably destroys tn with operation.
20 (defmacro with-tn@fp-top((tn) &body body)
21   `(progn
22     (unless (zerop (tn-offset ,tn))
23       (inst fxch ,tn))
24     ,@body
25     (unless (zerop (tn-offset ,tn))
26       (inst fxch ,tn))))
27
28 ;;; Use this to prepare for load of new value from memory. This
29 ;;; changes the register numbering so the next instruction had better
30 ;;; be a FP load from memory; a register load from another register
31 ;;; will probably be loading the wrong register!
32 (defmacro with-empty-tn@fp-top((tn) &body body)
33   `(progn
34     (inst fstp ,tn)
35     ,@body
36     (unless (zerop (tn-offset ,tn))
37       (inst fxch ,tn))))                ; save into new dest and restore st(0)
38 \f
39 ;;;; instruction-like macros
40
41 (defmacro move (dst src)
42   #!+sb-doc
43   "Move SRC into DST unless they are location=."
44   (once-only ((n-dst dst)
45               (n-src src))
46     `(unless (location= ,n-dst ,n-src)
47        (inst mov ,n-dst ,n-src))))
48
49 (defmacro make-ea-for-object-slot (ptr slot lowtag &optional (size :dword))
50   `(make-ea ,size :base ,ptr :disp (- (* ,slot n-word-bytes) ,lowtag)))
51
52 (defmacro loadw (value ptr &optional (slot 0) (lowtag 0))
53   `(inst mov ,value (make-ea-for-object-slot ,ptr ,slot ,lowtag)))
54
55 (defmacro storew (value ptr &optional (slot 0) (lowtag 0))
56   (once-only ((value value))
57     `(inst mov (make-ea-for-object-slot ,ptr ,slot ,lowtag) ,value)))
58
59 ;;; A handy macro for storing widetags.
60 (defmacro storeb (value ptr &optional (slot 0) (lowtag 0))
61   (once-only ((value value))
62     `(inst mov (make-ea-for-object-slot ,ptr ,slot ,lowtag :byte) ,value)))
63
64 (defmacro pushw (ptr &optional (slot 0) (lowtag 0))
65   `(inst push (make-ea-for-object-slot ,ptr ,slot ,lowtag)))
66
67 (defmacro popw (ptr &optional (slot 0) (lowtag 0))
68   `(inst pop (make-ea-for-object-slot ,ptr ,slot ,lowtag)))
69 \f
70 ;;;; macros to generate useful values
71
72 (defmacro load-symbol (reg symbol)
73   `(inst mov ,reg (+ nil-value (static-symbol-offset ,symbol))))
74
75 (defmacro make-ea-for-symbol-value (symbol)
76   `(make-ea :dword
77     :disp (+ nil-value
78            (static-symbol-offset ',symbol)
79            (ash symbol-value-slot word-shift)
80            (- other-pointer-lowtag))))
81
82 (defmacro load-symbol-value (reg symbol)
83   `(inst mov ,reg (make-ea-for-symbol-value ,symbol)))
84
85 (defmacro store-symbol-value (reg symbol)
86   `(inst mov (make-ea-for-symbol-value ,symbol) ,reg))
87
88 #!+sb-thread
89 (defmacro make-ea-for-symbol-tls-index (symbol)
90   `(make-ea :dword
91     :disp (+ nil-value
92            (static-symbol-offset ',symbol)
93            (ash symbol-tls-index-slot word-shift)
94            (- other-pointer-lowtag))))
95
96 #!+sb-thread
97 (defmacro load-tl-symbol-value (reg symbol)
98   `(progn
99     (inst mov ,reg (make-ea-for-symbol-tls-index ,symbol))
100     (inst fs-segment-prefix)
101     (inst mov ,reg (make-ea :dword :base ,reg))))
102 #!-sb-thread
103 (defmacro load-tl-symbol-value (reg symbol) `(load-symbol-value ,reg ,symbol))
104
105 #!+sb-thread
106 (defmacro store-tl-symbol-value (reg symbol temp)
107   `(progn
108     (inst mov ,temp (make-ea-for-symbol-tls-index ,symbol))
109     (inst fs-segment-prefix)
110     (inst mov (make-ea :dword :base ,temp) ,reg)))
111 #!-sb-thread
112 (defmacro store-tl-symbol-value (reg symbol temp)
113   (declare (ignore temp))
114   `(store-symbol-value ,reg ,symbol))
115
116 (defmacro load-binding-stack-pointer (reg)
117   #!+sb-thread
118   `(progn
119      (inst fs-segment-prefix)
120      (inst mov ,reg (make-ea :dword
121                              :disp (* 4 thread-binding-stack-pointer-slot))))
122   #!-sb-thread
123   `(load-symbol-value ,reg *binding-stack-pointer*))
124
125 (defmacro store-binding-stack-pointer (reg)
126   #!+sb-thread
127   `(progn
128      (inst fs-segment-prefix)
129      (inst mov (make-ea :dword
130                         :disp (* 4 thread-binding-stack-pointer-slot))
131            ,reg))
132   #!-sb-thread
133   `(store-symbol-value ,reg *binding-stack-pointer*))
134
135 (defmacro load-type (target source &optional (offset 0))
136   #!+sb-doc
137   "Loads the type bits of a pointer into target independent of
138    byte-ordering issues."
139   (once-only ((n-target target)
140               (n-source source)
141               (n-offset offset))
142     (ecase *backend-byte-order*
143       (:little-endian
144        `(inst mov ,n-target
145               (make-ea :byte :base ,n-source :disp ,n-offset)))
146       (:big-endian
147        `(inst mov ,n-target
148               (make-ea :byte :base ,n-source :disp (+ ,n-offset 3)))))))
149 \f
150 ;;;; allocation helpers
151
152 ;;; Allocation within alloc_region (which is thread local) can be done
153 ;;; inline.  If the alloc_region is overflown allocation is done by
154 ;;; calling the C alloc() function.
155
156 ;;; C calls for allocation don't /seem/ to make an awful lot of
157 ;;; difference to speed. On pure consing it's about a 25%
158 ;;; gain. Guessing from historical context, it looks like inline
159 ;;; allocation was introduced before pseudo-atomic, at which time all
160 ;;; calls to alloc() would have needed a syscall to mask signals for
161 ;;; the duration.  Now we have pseudoatomic there's no need for that
162 ;;; overhead.
163
164 (defun allocation-dynamic-extent (alloc-tn size)
165   (inst sub esp-tn size)
166   ;; FIXME: SIZE _should_ be double-word aligned (suggested but
167   ;; unfortunately not enforced by PAD-DATA-BLOCK and
168   ;; WITH-FIXED-ALLOCATION), so that ESP is always divisible by 8 (for
169   ;; 32-bit lispobjs).  In that case, this AND instruction is
170   ;; unneccessary and could be removed.  If not, explain why.  -- CSR,
171   ;; 2004-03-30
172   (inst and esp-tn (lognot lowtag-mask))
173   (aver (not (location= alloc-tn esp-tn)))
174   (inst mov alloc-tn esp-tn)
175   (values))
176
177 (defun allocation-notinline (alloc-tn size)
178   (let* ((alloc-tn-offset (tn-offset alloc-tn))
179          ;; C call to allocate via dispatch routines. Each
180          ;; destination has a special entry point. The size may be a
181          ;; register or a constant.
182          (tn-text (ecase alloc-tn-offset
183                     (#.eax-offset "eax")
184                     (#.ecx-offset "ecx")
185                     (#.edx-offset "edx")
186                     (#.ebx-offset "ebx")
187                     (#.esi-offset "esi")
188                     (#.edi-offset "edi")))
189          (size-text (case size (8 "8_") (16 "16_") (t ""))))
190     (unless (or (eql size 8) (eql size 16))
191       (unless (and (tn-p size) (location= alloc-tn size))
192         (inst mov alloc-tn size)))
193     (inst call (make-fixup (concatenate 'string
194                                          "alloc_" size-text
195                                          "to_" tn-text)
196                            :foreign))))
197
198 (defun allocation-inline (alloc-tn size)
199   (let ((ok (gen-label))
200         (done (gen-label))
201         (free-pointer
202          (make-ea :dword :disp
203                   #!+sb-thread (* n-word-bytes thread-alloc-region-slot)
204                   #!-sb-thread (make-fixup "boxed_region" :foreign)
205                   :scale 1)) ; thread->alloc_region.free_pointer
206         (end-addr
207          (make-ea :dword :disp
208                   #!+sb-thread (* n-word-bytes (1+ thread-alloc-region-slot))
209                   #!-sb-thread (make-fixup "boxed_region" :foreign 4)
210                   :scale 1)))   ; thread->alloc_region.end_addr
211     (unless (and (tn-p size) (location= alloc-tn size))
212       (inst mov alloc-tn size))
213     #!+sb-thread (inst fs-segment-prefix)
214     (inst add alloc-tn free-pointer)
215     #!+sb-thread (inst fs-segment-prefix)
216     (inst cmp alloc-tn end-addr)
217     (inst jmp :be ok)
218     (let ((dst (ecase (tn-offset alloc-tn)
219                  (#.eax-offset "alloc_overflow_eax")
220                  (#.ecx-offset "alloc_overflow_ecx")
221                  (#.edx-offset "alloc_overflow_edx")
222                  (#.ebx-offset "alloc_overflow_ebx")
223                  (#.esi-offset "alloc_overflow_esi")
224                  (#.edi-offset "alloc_overflow_edi"))))
225       (inst call (make-fixup dst :foreign)))
226     (inst jmp-short done)
227     (emit-label ok)
228     ;; Swap ALLOC-TN and FREE-POINTER
229     (cond ((and (tn-p size) (location= alloc-tn size))
230            ;; XCHG is extremely slow, use the xor swap trick
231            #!+sb-thread (inst fs-segment-prefix)
232            (inst xor alloc-tn free-pointer)
233            #!+sb-thread (inst fs-segment-prefix)
234            (inst xor free-pointer alloc-tn)
235            #!+sb-thread (inst fs-segment-prefix)
236            (inst xor alloc-tn free-pointer))
237           (t
238            ;; It's easier if SIZE is still available.
239            #!+sb-thread (inst fs-segment-prefix)
240            (inst mov free-pointer alloc-tn)
241            (inst sub alloc-tn size)))
242     (emit-label done))
243   (values))
244
245
246 ;;; Emit code to allocate an object with a size in bytes given by
247 ;;; SIZE.  The size may be an integer or a TN. If Inline is a VOP
248 ;;; node-var then it is used to make an appropriate speed vs size
249 ;;; decision.
250
251 ;;; Allocation should only be used inside a pseudo-atomic section, which
252 ;;; should also cover subsequent initialization of the object.
253
254 ;;; (FIXME: so why aren't we asserting this?)
255
256 (defun allocation (alloc-tn size &optional inline dynamic-extent)
257   (cond
258     (dynamic-extent (allocation-dynamic-extent alloc-tn size))
259     ((or (null inline) (policy inline (>= speed space)))
260      (allocation-inline alloc-tn size))
261     (t (allocation-notinline alloc-tn size)))
262   (values))
263
264 ;;; Allocate an other-pointer object of fixed SIZE with a single word
265 ;;; header having the specified WIDETAG value. The result is placed in
266 ;;; RESULT-TN.
267 (defmacro with-fixed-allocation ((result-tn widetag size &optional inline)
268                                  &body forms)
269   (unless forms
270     (bug "empty &body in WITH-FIXED-ALLOCATION"))
271   (once-only ((result-tn result-tn) (size size))
272     `(pseudo-atomic
273       (allocation ,result-tn (pad-data-block ,size) ,inline)
274       (storew (logior (ash (1- ,size) n-widetag-bits) ,widetag)
275               ,result-tn)
276       (inst lea ,result-tn
277             (make-ea :byte :base ,result-tn :disp other-pointer-lowtag))
278       ,@forms)))
279 \f
280 ;;;; error code
281 (eval-when (#-sb-xc :compile-toplevel :load-toplevel :execute)
282   (defun emit-error-break (vop kind code values)
283     (let ((vector (gensym)))
284       `((progn
285           #-darwin (inst int 3)         ; i386 breakpoint instruction
286           ;; CLH 20060314
287           ;; On Darwin, we need to use #x0b0f instead of int3 in order
288           ;; to generate a SIGILL instead of a SIGTRAP as darwin/x86
289           ;; doesn't seem to be reliably firing SIGTRAP
290           ;; handlers. Hopefully this will be fixed by Apple at a
291           ;; later date.
292           #+darwin (inst word #x0b0f))
293         ;; The return PC points here; note the location for the debugger.
294         (let ((vop ,vop))
295           (when vop
296                 (note-this-location vop :internal-error)))
297         (inst byte ,kind)                       ; eg trap_Xyyy
298         (with-adjustable-vector (,vector)       ; interr arguments
299           (write-var-integer (error-number-or-lose ',code) ,vector)
300           ,@(mapcar (lambda (tn)
301                       `(let ((tn ,tn))
302                          ;; classic CMU CL comment:
303                          ;;   zzzzz jrd here. tn-offset is zero for constant
304                          ;;   tns.
305                          (write-var-integer (make-sc-offset (sc-number
306                                                              (tn-sc tn))
307                                                             (or (tn-offset tn)
308                                                                 0))
309                                             ,vector)))
310                     values)
311           (inst byte (length ,vector))
312           (dotimes (i (length ,vector))
313             (inst byte (aref ,vector i))))))))
314
315 (defmacro error-call (vop error-code &rest values)
316   #!+sb-doc
317   "Cause an error. ERROR-CODE is the error to cause."
318   (cons 'progn
319         (emit-error-break vop error-trap error-code values)))
320
321 (defmacro generate-error-code (vop error-code &rest values)
322   #!+sb-doc
323   "Generate-Error-Code Error-code Value*
324   Emit code for an error with the specified Error-Code and context Values."
325   `(assemble (*elsewhere*)
326      (let ((start-lab (gen-label)))
327        (emit-label start-lab)
328        (error-call ,vop ,error-code ,@values)
329        start-lab)))
330
331 \f
332 ;;;; PSEUDO-ATOMIC
333
334 ;;; This is used to wrap operations which leave untagged memory lying
335 ;;; around.  It's an operation which the AOP weenies would describe as
336 ;;; having "cross-cutting concerns", meaning it appears all over the
337 ;;; place and there's no logical single place to attach documentation.
338 ;;; grep (mostly in src/runtime) is your friend
339
340 ;;; KLUDGE: since the stack on the x86 is treated conservatively, it
341 ;;; does not matter whether a signal occurs during construction of a
342 ;;; dynamic-extent object, as the half-finished construction of the
343 ;;; object will not cause any difficulty.  We can therefore elide
344 (defmacro maybe-pseudo-atomic (really-p &body forms)
345   `(if ,really-p
346        (progn ,@forms)
347        (pseudo-atomic ,@forms)))
348
349 #!+sb-thread
350 (defmacro pseudo-atomic (&rest forms)
351   (with-unique-names (label)
352     `(let ((,label (gen-label)))
353        (inst fs-segment-prefix)
354        (inst or (make-ea :byte :disp (* 4 thread-pseudo-atomic-bits-slot))
355             (fixnumize 1))
356        ,@forms
357        (inst fs-segment-prefix)
358        (inst xor (make-ea :byte :disp (* 4 thread-pseudo-atomic-bits-slot))
359              (fixnumize 1))
360        (inst jmp :z ,label)
361        ;; if PAI was set, interrupts were disabled at the same
362        ;; time using the process signal mask.
363        (inst break pending-interrupt-trap)
364        (emit-label ,label))))
365
366 #!-sb-thread
367 (defmacro pseudo-atomic (&rest forms)
368   (with-unique-names (label)
369     `(let ((,label (gen-label)))
370        ;; FIXME: The MAKE-EA noise should become a MACROLET macro
371        ;; or something. (perhaps SVLB, for static variable low
372        ;; byte)
373        (inst or (make-ea :byte :disp (+ nil-value
374                                         (static-symbol-offset
375                                          '*pseudo-atomic-bits*)
376                                         (ash symbol-value-slot word-shift)
377                                         (- other-pointer-lowtag)))
378              (fixnumize 1))
379        ,@forms
380        (inst xor (make-ea :byte :disp (+ nil-value
381                                          (static-symbol-offset
382                                           '*pseudo-atomic-bits*)
383                                          (ash symbol-value-slot word-shift)
384                                          (- other-pointer-lowtag)))
385              (fixnumize 1))
386        (inst jmp :z ,label)
387        ;; if PAI was set, interrupts were disabled at the same
388        ;; time using the process signal mask.
389        (inst break pending-interrupt-trap)
390        (emit-label ,label))))
391 \f
392 ;;;; indexed references
393
394 (defmacro define-full-reffer (name type offset lowtag scs el-type &optional translate)
395   `(progn
396      (define-vop (,name)
397        ,@(when translate
398            `((:translate ,translate)))
399        (:policy :fast-safe)
400        (:args (object :scs (descriptor-reg))
401               (index :scs (any-reg immediate unsigned-reg)))
402        (:arg-types ,type tagged-num)
403        (:results (value :scs ,scs))
404        (:result-types ,el-type)
405        (:generator 3                    ; pw was 5
406          (sc-case index
407            (immediate
408             (inst mov value (make-ea :dword :base object
409                                      :disp (- (* (+ ,offset (tn-value index))
410                                                  n-word-bytes)
411                                               ,lowtag))))
412            (unsigned-reg
413             (inst mov value (make-ea :dword :base object :index index :scale 4
414                                      :disp (- (* ,offset n-word-bytes)
415                                               ,lowtag))))
416            (t
417             (inst mov value (make-ea :dword :base object :index index
418                                      :disp (- (* ,offset n-word-bytes)
419                                               ,lowtag)))))))))
420
421 (defmacro define-full-reffer+offset (name type offset lowtag scs el-type &optional translate)
422   `(progn
423      (define-vop (,name)
424        ,@(when translate
425            `((:translate ,translate)))
426        (:policy :fast-safe)
427        (:args (object :scs (descriptor-reg))
428               (index :scs (any-reg immediate unsigned-reg)))
429        (:arg-types ,type tagged-num
430                    (:constant (constant-displacement ,lowtag sb!vm:n-word-bytes ,offset)))
431        (:info offset)
432        (:results (value :scs ,scs))
433        (:result-types ,el-type)
434        (:generator 3                    ; pw was 5
435          (sc-case index
436            (immediate
437             (inst mov value (make-ea :dword :base object
438                                      :disp (- (* (+ ,offset
439                                                     (tn-value index)
440                                                     offset)
441                                                  n-word-bytes)
442                                               ,lowtag))))
443            (unsigned-reg
444             (inst mov value (make-ea :dword :base object :index index :scale 4
445                                      :disp (- (* (+ ,offset offset)
446                                                  n-word-bytes)
447                                               ,lowtag))))
448            (t
449             (inst mov value (make-ea :dword :base object :index index
450                                      :disp (- (* (+ ,offset offset)
451                                                  n-word-bytes)
452                                               ,lowtag)))))))))
453
454 (defmacro define-full-setter (name type offset lowtag scs el-type &optional translate)
455   `(progn
456      (define-vop (,name)
457        ,@(when translate
458            `((:translate ,translate)))
459        (:policy :fast-safe)
460        (:args (object :scs (descriptor-reg))
461               (index :scs (any-reg immediate))
462               (value :scs ,scs :target result))
463        (:arg-types ,type tagged-num ,el-type)
464        (:results (result :scs ,scs))
465        (:result-types ,el-type)
466        (:generator 4                    ; was 5
467          (sc-case index
468            (immediate
469             (inst mov (make-ea :dword :base object
470                                :disp (- (* (+ ,offset (tn-value index))
471                                            n-word-bytes)
472                                         ,lowtag))
473                   value))
474            (t
475             (inst mov (make-ea :dword :base object :index index
476                                :disp (- (* ,offset n-word-bytes) ,lowtag))
477                   value)))
478         (move result value)))))
479
480 (defmacro define-full-setter+offset (name type offset lowtag scs el-type &optional translate)
481   `(progn
482      (define-vop (,name)
483        ,@(when translate
484            `((:translate ,translate)))
485        (:policy :fast-safe)
486        (:args (object :scs (descriptor-reg))
487               (index :scs (any-reg immediate))
488               (value :scs ,scs :target result))
489        (:info offset)
490        (:arg-types ,type tagged-num
491                    (:constant (constant-displacement ,lowtag sb!vm:n-word-bytes ,offset)) ,el-type)
492        (:results (result :scs ,scs))
493        (:result-types ,el-type)
494        (:generator 4                    ; was 5
495          (sc-case index
496            (immediate
497             (inst mov (make-ea :dword :base object
498                                :disp (- (* (+ ,offset (tn-value index) offset)
499                                            n-word-bytes)
500                                         ,lowtag))
501                   value))
502            (t
503             (inst mov (make-ea :dword :base object :index index
504                                :disp (- (* (+ ,offset offset)
505                                            n-word-bytes) ,lowtag))
506                   value)))
507         (move result value)))))
508
509 ;;; helper for alien stuff.
510 (defmacro with-pinned-objects ((&rest objects) &body body)
511   "Arrange with the garbage collector that the pages occupied by
512 OBJECTS will not be moved in memory for the duration of BODY.
513 Useful for e.g. foreign calls where another thread may trigger
514 garbage collection"
515   `(multiple-value-prog1
516        (progn
517          ,@(loop for p in objects
518                  collect
519                  ;; There is no race here wrt to gc, because at every
520                  ;; point during the execution there is a reference to
521                  ;; P on the stack or in a register.
522                  `(push-word-on-c-stack
523                    (int-sap (sb!kernel:get-lisp-obj-address ,p))))
524          ,@body)
525      ;; If the body returned normally, we should restore the stack pointer
526      ;; for the benefit of any following code in the same function.  If
527      ;; there's a non-local exit in the body, sp is garbage anyway and
528      ;; will get set appropriately from {a, the} frame pointer before it's
529      ;; next needed
530      (pop-words-from-c-stack ,(length objects))))