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