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