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