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